赞
踩
/**
* @param <T>
* @param item 多个储位序列化成list
* @return
* @throws ErrorResponseException
* @throws ModbusTransportException
*/
public static <T> boolean writeObjToModbusBatch( ModbusMaster modbusMaster, List<T> item ,int slaveId, Integer startOffset) throws ModbusTransportException, ErrorResponseException {
List<Pair<BaseLocator<?>, Object>> list = writeObjToModbus(item , slaveId, startOffset );
list.parallelStream().forEach(pair ->{
try {
modbusMaster.setValue(pair.first, pair.second);
} catch (Exception e) {
log.error("wirte_to_modbus_error:{}" , Throwables.getStackTraceAsString(e));
}
});
return true;
};
/**
* @param <T>
* @param item 多个储位序列化成list
* @return
*/
public static <T> List<Pair<BaseLocator<?>, Object>> writeObjToModbus(List<T> item ,int slaveId, Integer startOffset) {
final Pair<Integer, Integer> offsetTemp = Pair.makePair(startOffset, null) ;
List<Pair<BaseLocator<?>, Object>> list = Lists.newArrayList();
for ( T t : item ) {
List<Pair<BaseLocator<?>, Object>> modelList = getJsonModelList( t , slaveId , offsetTemp ) ;
list.addAll( modelList);
}
return list;
};
/**
* 单个实体转换为modbus 定位器
*
* @param <T>
* @param i
* @return
*/
@SuppressWarnings("unchecked")
private static <T> List<Pair<BaseLocator<?>, Object>> getJsonModelList(T i , int slaveId, Pair<Integer, Integer> offsetTemp ) {
Class<? extends Object> itemClazz = i.getClass();
if (Objects.isNull(itemClazz)) {
return Lists.newArrayList();
}
ModBusItem modBusItem = itemClazz.getAnnotation(ModBusItem.class);
ToolUtil.isNull(modBusItem, "the javabean must annotatied ModBusItem annotation");
Map<Field, ModBusItem> map = CLAZZ_FILED_ANNOTATIONS.get(itemClazz);
List<?> collect = map.entrySet().stream().filter(mapEntry -> Objects.nonNull(mapEntry.getValue())).map(item ->{
ModBusItem modbusItem = item.getValue();
BaseLocator<?> loc = null;
if(modbusItem.loc() == NumericLocator.class) {
loc = BaseLocator.holdingRegister( slaveId, offsetTemp.first , modbusItem.dataType());
}
if(modbusItem.loc() == StringLocator.class) {
loc = new StringLocator(slaveId, RegisterRange.HOLDING_REGISTER, offsetTemp.first, DataType.CHAR, modbusItem.maxRegisterCount());
}
offsetTemp.setFirst(offsetTemp.first + modbusItem.maxRegisterCount());
Object value = null;
try {
value = item.getKey().get( i);
} catch (IllegalArgumentException | IllegalAccessException e) {
log.error("getJsonModelList_error:{}" , Throwables.getStackTraceAsString(e)) ;
}
return Pair.makePair(loc, value );
}).collect(Collectors.toList());
return (List<Pair<BaseLocator<?>, Object>>) collect;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。