in hertzbeat-collector/hertzbeat-collector-basic/src/main/java/org/apache/hertzbeat/collector/collect/plc/AbstractPlcCollectImpl.java [112:180]
public void collect(CollectRep.MetricsData.Builder builder, Metrics metrics) {
long startTime = System.currentTimeMillis();
PlcProtocol plcProtocol = metrics.getPlc();
PlcConnection plcConnection = null;
try {
String connectionString = getConnectionString(metrics);
plcConnection = CONNECTION_MANAGER.getConnection(connectionString);
if (!plcConnection.getMetadata().isReadSupported()) {
log.error("This connection doesn't support reading.");
}
// Check if this connection support reading of data.
if (!plcConnection.getMetadata().isWriteSupported()) {
log.error("This connection doesn't support writing.");
}
PlcReadRequest readRequest = buildRequest(metrics, plcConnection);
PlcReadResponse response = readRequest.execute().get(Long.parseLong(plcProtocol.getTimeout()), TimeUnit.MILLISECONDS);
long responseTime = System.currentTimeMillis() - startTime;
Map<String, String> resultMap = new HashMap<>();
for (String tagName : response.getTagNames()) {
if (response.getResponseCode(tagName) == PlcResponseCode.OK) {
int numValues = response.getNumberOfValues(tagName);
// If it's just one element, output just one single line.
log.info("{}: {}", tagName, response.getPlcValue(tagName));
if (numValues == 1) {
resultMap.put(tagName, response.getPlcValue(tagName).toString());
}
// If it's more than one element, output each in a single row.
else {
for (int i = 0; i < numValues; i++) {
resultMap.put(tagName + "-" + i, response.getObject(tagName, i).toString());
}
}
} else {
log.error("Error[{}]: {}", tagName, response.getResponseCode(tagName).name());
}
}
if (COIL.equals(plcProtocol.getAddressSyntax())) {
resultMap = resultMap.entrySet()
.stream()
.peek(obj -> obj.setValue(String.valueOf(Boolean.TRUE.equals(Boolean.valueOf(obj.getValue())) ? 1 : 0)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
resultMap.put(CollectorConstants.RESPONSE_TIME, Long.toString(responseTime));
List<String> aliasFields = metrics.getAliasFields();
CollectRep.ValueRow.Builder valueRowBuilder = CollectRep.ValueRow.newBuilder();
for (String field : aliasFields) {
String fieldValue = resultMap.get(field);
valueRowBuilder.addColumn(Objects.requireNonNullElse(fieldValue, CommonConstants.NULL_VALUE));
}
builder.addValueRow(valueRowBuilder.build());
} catch (Exception e) {
builder.setCode(CollectRep.Code.FAIL);
String message = CommonUtil.getMessageFromThrowable(e);
builder.setMsg(message);
log.warn(message, e);
} finally {
if (plcConnection != null) {
try {
plcConnection.close();
} catch (Exception e) {
log.warn(e.getMessage());
}
}
}
}