forked from openhab/openhab-core
/
RxTxPortProvider.java
77 lines (67 loc) · 2.8 KB
/
RxTxPortProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.io.transport.serial.internal;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.io.transport.serial.ProtocolType;
import org.eclipse.smarthome.io.transport.serial.ProtocolType.PathType;
import org.eclipse.smarthome.io.transport.serial.SerialPortIdentifier;
import org.eclipse.smarthome.io.transport.serial.SerialPortProvider;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
/**
*
* @author Matthias Steigenberger - Initial Contribution
* @author Wouter Born - Fix serial ports missing when ports are added to system property
*/
@NonNullByDefault
@Component
public class RxTxPortProvider implements SerialPortProvider {
private final Logger logger = LoggerFactory.getLogger(RxTxPortProvider.class);
@Override
public @Nullable SerialPortIdentifier getPortIdentifier(URI port) {
try {
CommPortIdentifier ident = SerialPortUtil.getPortIdentifier(port.getPath());
return new SerialPortIdentifierImpl(ident);
} catch (NoSuchPortException e) {
logger.debug("No SerialPortIdentifier found for: {}", port.getPath());
return null;
}
}
@Override
public Stream<ProtocolType> getAcceptedProtocols() {
return Stream.of(new ProtocolType(PathType.LOCAL, "rxtx"));
}
@Override
public Stream<SerialPortIdentifier> getSerialPortIdentifiers() {
Stream<CommPortIdentifier> scanIds = SerialPortUtil.getPortIdentifiersUsingScan();
Stream<CommPortIdentifier> propIds = SerialPortUtil.getPortIdentifiersUsingProperty();
return Stream.concat(scanIds, propIds).filter(distinctByKey(CommPortIdentifier::getName))
.filter(id -> id.getPortType() == CommPortIdentifier.PORT_SERIAL)
.map(sid -> new SerialPortIdentifierImpl(sid));
}
@SuppressWarnings("null")
private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, String> seen = new ConcurrentHashMap<>();
return t -> seen.put(keyExtractor.apply(t), "") == null;
}
}