fix 线程
This commit is contained in:
@@ -46,14 +46,14 @@ public class ConveyorDevice {
|
||||
public void run() {
|
||||
System.out.println("test");
|
||||
String MODE = "RD1.RD1." + id + ".mode";
|
||||
String code = OpcUtl.read(MODE);
|
||||
if ("2".equals(code)) {
|
||||
TaskService taskserver = SpringContextHolder.getBean(TaskServiceImpl.class);
|
||||
TaskDto dto = new TaskDto();
|
||||
dto.setStart_point_code(id);
|
||||
dto.setNext_point_code("1002");
|
||||
taskserver.create(dto);
|
||||
}
|
||||
// String code = OpcUtl.read(MODE);
|
||||
// if ("2".equals(code)) {
|
||||
// TaskService taskserver = SpringContextHolder.getBean(TaskServiceImpl.class);
|
||||
// TaskDto dto = new TaskDto();
|
||||
// dto.setStart_point_code(id);
|
||||
// dto.setNext_point_code("1002");
|
||||
// taskserver.create(dto);
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ public class LnshCrusherDeviceDriver extends AbstractOpcDeviceDriver implements
|
||||
logServer.deviceItemValue(this.device_code,"mode" ,String.valueOf(mode));
|
||||
logServer.deviceExecuteLog(this.device_code,"","","信号mode:" + last_mode + "->" + mode);
|
||||
luceneExecuteLogService.deviceExecuteLog(
|
||||
new LuceneLogDto(this.getDevice().getOpc_server_code(),this.getDevice().getOpc_plc_code(),this.device_code,ItemProtocol.to_home_relocation,this.last_home_relocation,this.home_relocation));
|
||||
new LuceneLogDto(this.getDevice().getOpc_server_code(),this.getDevice().getOpc_plc_code(),this.device_code,ItemProtocol.item_mode,this.last_mode,this.mode));
|
||||
}
|
||||
if (status != last_status) {
|
||||
logServer.deviceItemValue(this.device_code,"status" ,String.valueOf(status));
|
||||
|
||||
@@ -81,4 +81,9 @@ public interface DeviceAppService {
|
||||
*/
|
||||
String findDeviceTypeByCode(String deviceCode);
|
||||
|
||||
|
||||
void removeDevice(String deviceCode);
|
||||
|
||||
void addDevice(String deviceCode);
|
||||
|
||||
}
|
||||
|
||||
@@ -302,6 +302,51 @@ public class DeviceAppServiceImpl implements DeviceAppService, ApplicationAutoIn
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeDevice(String deviceCode) {
|
||||
|
||||
Iterator<Device> iterator = devices.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Device device = iterator.next();
|
||||
if (StrUtil.equals(device.getDevice_code(), deviceCode)) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
Iterator<String> iterator2 = code_indexs.iterator();
|
||||
while (iterator2.hasNext()) {
|
||||
String str = iterator2.next();
|
||||
if (StrUtil.equals(str, deviceCode)) {
|
||||
iterator2.remove();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addDevice(String deviceCode) {
|
||||
List<DeviceManageDto> deviceManageDtos = this.deviceManageService.queryAllWithExtra(deviceCode);
|
||||
int i = 0;
|
||||
|
||||
for (int size = deviceManageDtos.size(); i < size; ++i) {
|
||||
DeviceManageDto deviceManage = (DeviceManageDto) deviceManageDtos.get(i);
|
||||
Device device = new Device();
|
||||
BeanUtil.copyProperties(deviceManage, device);
|
||||
this.devices.add(device);
|
||||
this.code_indexs.add(device.getDevice_code());
|
||||
|
||||
if (!StrUtil.isEmpty(device.getDriver_code())) {
|
||||
DeviceDriverDefination defination = this.deviceDriverDefinationAppService.getDeviceDriverDefination(deviceManage.getDriver_code());
|
||||
if (defination != null) {
|
||||
device.setDeviceDriverDefination(defination);
|
||||
DeviceDriver driver = defination.getDriverInstance(device);
|
||||
device.setDeviceDriver(driver);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public List<LinewayDeviceDriver> findLaneway() {
|
||||
return this.findDeviceDriver(LinewayDeviceDriver.class);
|
||||
}
|
||||
|
||||
@@ -4,4 +4,7 @@ import java.util.List;
|
||||
|
||||
public interface DeviceManageService {
|
||||
List<DeviceManageDto> queryAllWithExtra();
|
||||
|
||||
List<DeviceManageDto> queryAllWithExtra(String device_code);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.nl.modules.wql.core.bean.ResultBean;
|
||||
import org.nl.modules.wql.core.bean.WQLObject;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -33,8 +35,83 @@ public class DeviceManageServiceImpl implements DeviceManageService {
|
||||
String opc_plc_id = json.getString("opc_plc_id");
|
||||
if (StrUtil.isNotEmpty(opc_plc_id) && StrUtil.isNotEmpty(opc_server_id)) {
|
||||
//OPC表【acs_opc】
|
||||
String opc_code = opcTab.query("is_delete= '0' AND is_active= '1' AND opc_id = '" + opc_server_id + "'").uniqueResult(0).getString("opc_code");
|
||||
JSONObject rb = opcTab.query("is_delete= '0' AND is_active= '1' AND opc_id = '" + opc_server_id + "'").uniqueResult(0);
|
||||
if(ObjectUtil.isEmpty(rb)){
|
||||
System.out.println(device.getDevice_code());
|
||||
continue;
|
||||
}
|
||||
String opc_code= rb.getString("opc_code");
|
||||
device.setOpc_server_code(opc_code);
|
||||
if(ObjectUtil.isEmpty(plcTab.query("is_delete= '0' AND is_active= '1' AND plc_id = '" + opc_plc_id + "'").uniqueResult(0)))
|
||||
{
|
||||
System.out.println(device.getDevice_code());
|
||||
continue;
|
||||
}
|
||||
String plc_code = plcTab.query("is_delete= '0' AND is_active= '1' AND plc_id = '" + opc_plc_id + "'").uniqueResult(0).getString("plc_code");
|
||||
device.setOpc_plc_code(plc_code);
|
||||
}
|
||||
devices.add(device);
|
||||
}
|
||||
|
||||
Iterator it = devices.iterator();
|
||||
|
||||
while (it.hasNext()) {
|
||||
DeviceManageDto device = (DeviceManageDto) it.next();
|
||||
Iterator var5 = extras.iterator();
|
||||
while (var5.hasNext()) {
|
||||
DeviceExtraManageDto extra = (DeviceExtraManageDto) var5.next();
|
||||
if (extra.getDevice_id().equals(device.getDevice_id())) {
|
||||
device.getExtra().add(extra);
|
||||
if (StrUtil.equals(extra.getExtra_code(), "station_manager") && StrUtil.equals(extra.getExtra_value().toString(), "true")) {
|
||||
String has_goods = runpointTab.query("is_delete= '0' AND is_active= '1' AND device_id = '" + extra.getDevice_id() + "'").uniqueResult(0).getString("hasgoods");
|
||||
String material_type = runpointTab.query("is_delete= '0' AND is_active= '1' AND device_id = '" + extra.getDevice_id() + "'").uniqueResult(0).getString("material_type");
|
||||
String batch = runpointTab.query("is_delete= '0' AND is_active= '1' AND device_id = '" + extra.getDevice_id() + "'").uniqueResult(0).getString("batch");
|
||||
String islock = runpointTab.query("is_delete= '0' AND is_active= '1' AND device_id = '" + extra.getDevice_id() + "'").uniqueResult(0).getString("islock");
|
||||
device.setMaterial_type(material_type);
|
||||
device.setHas_goods(Integer.parseInt(has_goods));
|
||||
device.setBatch(batch);
|
||||
device.setIslock(islock);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return devices;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceManageDto> queryAllWithExtra(String device_code) {
|
||||
JSONArray arr = WQLObject.getWQLObject("acs_device").query("device_code = '" + device_code + " '").getResultJSONArray(0);
|
||||
|
||||
JSONArray extArr = WQLObject.getWQLObject("acs_device_extra").query("device_code = '" + device_code + " '").getResultJSONArray(0);
|
||||
|
||||
List<DeviceExtraManageDto> extras = extArr.toJavaList(DeviceExtraManageDto.class);
|
||||
|
||||
WQLObject runpointTab = WQLObject.getWQLObject("acs_device_runpoint");
|
||||
|
||||
WQLObject opcTab = WQLObject.getWQLObject("acs_opc");
|
||||
//OPC_PLC表【acs_opc_plc】
|
||||
WQLObject plcTab = WQLObject.getWQLObject("acs_opc_plc");
|
||||
List<DeviceManageDto> devices = new ArrayList<>();
|
||||
for (int i = 0; i < arr.size(); i++) {
|
||||
JSONObject json = arr.getJSONObject(i);
|
||||
DeviceManageDto device = json.toJavaObject(DeviceManageDto.class);
|
||||
String opc_server_id = json.getString("opc_server_id");
|
||||
String opc_plc_id = json.getString("opc_plc_id");
|
||||
if (StrUtil.isNotEmpty(opc_plc_id) && StrUtil.isNotEmpty(opc_server_id)) {
|
||||
//OPC表【acs_opc】
|
||||
JSONObject rb = opcTab.query("is_delete= '0' AND is_active= '1' AND opc_id = '" + opc_server_id + "'").uniqueResult(0);
|
||||
if(ObjectUtil.isEmpty(rb)){
|
||||
System.out.println(device.getDevice_code());
|
||||
continue;
|
||||
}
|
||||
String opc_code= rb.getString("opc_code");
|
||||
device.setOpc_server_code(opc_code);
|
||||
if(ObjectUtil.isEmpty(plcTab.query("is_delete= '0' AND is_active= '1' AND plc_id = '" + opc_plc_id + "'").uniqueResult(0)))
|
||||
{
|
||||
System.out.println(device.getDevice_code());
|
||||
continue;
|
||||
}
|
||||
String plc_code = plcTab.query("is_delete= '0' AND is_active= '1' AND plc_id = '" + opc_plc_id + "'").uniqueResult(0).getString("plc_code");
|
||||
device.setOpc_plc_code(plc_code);
|
||||
}
|
||||
|
||||
@@ -1,28 +1,35 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.nl.acs.udw.UnifiedDataAccessor;
|
||||
import org.nl.acs.udw.UnifiedDataAccessorFactory;
|
||||
import org.openscada.opc.lib.da.Group;
|
||||
import org.openscada.opc.lib.da.Item;
|
||||
import org.openscada.opc.lib.da.ItemState;
|
||||
import org.openscada.opc.lib.da.Server;
|
||||
import org.nl.acs.udw.UnifiedDataAppService;
|
||||
import org.openscada.opc.lib.da.*;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
|
||||
@Slf4j
|
||||
public class DeviceOpcProtocolRunable implements Runnable {
|
||||
public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerConnectionStateListener {
|
||||
List<OpcItemDto> protocols;
|
||||
OpcServerManageDto OpcServer;
|
||||
int error_num;
|
||||
String message;
|
||||
int maxResartNum;
|
||||
private Server server;
|
||||
private Group group;
|
||||
boolean flag = false;
|
||||
private int all_null;
|
||||
private Map<String, OpcItemDto> itemSearchCache;
|
||||
|
||||
public DeviceOpcProtocolRunable() {
|
||||
this.error_num = 0;
|
||||
this.all_null = 0;
|
||||
this.message = null;
|
||||
this.itemSearchCache = new HashMap();
|
||||
this.server = null;
|
||||
}
|
||||
|
||||
public List<OpcItemDto> getProtocols() {
|
||||
@@ -41,32 +48,58 @@ public class DeviceOpcProtocolRunable implements Runnable {
|
||||
this.OpcServer = opcServer;
|
||||
}
|
||||
|
||||
OpcItemDto getItem(String item) {
|
||||
Iterator var2 = this.protocols.iterator();
|
||||
|
||||
OpcItemDto dto;
|
||||
do {
|
||||
if (!var2.hasNext()) {
|
||||
return null;
|
||||
private OpcItemDto getItem(String item) {
|
||||
OpcItemDto x = (OpcItemDto) this.itemSearchCache.get(item);
|
||||
if (x == null) {
|
||||
Iterator var3 = this.protocols.iterator();
|
||||
|
||||
while (var3.hasNext()) {
|
||||
OpcItemDto dto = (OpcItemDto) var3.next();
|
||||
if (StrUtil.equals(item, dto.getItem_code())) {
|
||||
x = dto;
|
||||
this.itemSearchCache.put(item, dto);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dto = (OpcItemDto) var2.next();
|
||||
} while (!StrUtil.equals(item, dto.getItem_code()));
|
||||
|
||||
return dto;
|
||||
return x;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (true) {
|
||||
try {
|
||||
Server server = OpcServerUtl.getServerWithOutException(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain());
|
||||
Group group = server.addGroup();
|
||||
List<String> itemsString = new ArrayList();
|
||||
Iterator it = this.protocols.iterator();
|
||||
if (OpcConfig.opc_item_read_using_callback) {
|
||||
this.runNew();
|
||||
} else {
|
||||
this.runOld();
|
||||
}
|
||||
}
|
||||
|
||||
while (it.hasNext()) {
|
||||
OpcItemDto protocol = (OpcItemDto) it.next();
|
||||
|
||||
private void runOld() {
|
||||
while (true) {
|
||||
start:
|
||||
try {
|
||||
if (this.group != null) {
|
||||
group.clear();
|
||||
group.remove();
|
||||
log.trace("清理group...");
|
||||
}
|
||||
if (this.server != null) {
|
||||
server.disconnect();
|
||||
log.trace("清理server...");
|
||||
}
|
||||
|
||||
this.server = OpcServerUtl.getServerWithOutException(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain());
|
||||
this.server.addStateListener(this);
|
||||
group = this.server.addGroup();
|
||||
List<String> itemsString = new ArrayList();
|
||||
Iterator var3 = this.protocols.iterator();
|
||||
|
||||
while (var3.hasNext()) {
|
||||
OpcItemDto protocol = (OpcItemDto) var3.next();
|
||||
String item = protocol.getItem_code();
|
||||
itemsString.add(item);
|
||||
}
|
||||
@@ -74,47 +107,56 @@ public class DeviceOpcProtocolRunable implements Runnable {
|
||||
Map<String, Item> itemsMap = new LinkedHashMap();
|
||||
boolean is_error = false;
|
||||
StringBuilder err_message = new StringBuilder();
|
||||
Iterator var7 = itemsString.iterator();
|
||||
Iterator var6 = itemsString.iterator();
|
||||
|
||||
while (var7.hasNext()) {
|
||||
String string = (String) var7.next();
|
||||
while (var6.hasNext()) {
|
||||
String string = (String) var6.next();
|
||||
|
||||
try {
|
||||
itemsMap.put(string, group.addItem(string));
|
||||
Item item = group.addItem(string);
|
||||
itemsMap.put(string, item);
|
||||
log.trace("添加成功 {}", string);
|
||||
} catch (Exception var29) {
|
||||
err_message.append(string + ":" + var29.getMessage());
|
||||
} catch (Exception var26) {
|
||||
err_message.append(string + ":" + var26.getMessage());
|
||||
if (!is_error) {
|
||||
is_error = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String tag;
|
||||
if (is_error) {
|
||||
log.info("设备OPC数据同步配置异常");
|
||||
tag = err_message.toString();
|
||||
log.warn("{}:{}", OpcConfig.resource_code, tag);
|
||||
}
|
||||
|
||||
if (!OpcStartTag.is_run) {
|
||||
OpcStartTag.is_run = true;
|
||||
}
|
||||
|
||||
//线程名
|
||||
String tag = Thread.currentThread().getName();
|
||||
if (this.OpcServer != null) {
|
||||
tag = tag + this.OpcServer.getOpc_code();
|
||||
tag = "";
|
||||
if (log.isWarnEnabled()) {
|
||||
tag = Thread.currentThread().getName();
|
||||
if (this.OpcServer != null) {
|
||||
tag = tag + this.getOpcGroupID();
|
||||
}
|
||||
}
|
||||
|
||||
UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
|
||||
|
||||
boolean time_out = false;
|
||||
|
||||
label97:
|
||||
while (true) {
|
||||
while (DeviceOpcSynchronizeAutoRun.isRun) {
|
||||
long begin = System.currentTimeMillis();
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("{} 开始记时{}", tag, DateUtil.now());
|
||||
}
|
||||
|
||||
Map<Item, ItemState> itemStatus = group.read(true, (Item[]) itemsMap.values().toArray(new Item[0]));
|
||||
long end = System.currentTimeMillis();
|
||||
log.trace("{} 开始记时{}", tag, DateUtil.now());
|
||||
long duration = end - begin;
|
||||
log.trace("{} 读取耗时:{}", tag, duration);
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("{} 读取耗时:{}", tag, duration);
|
||||
}
|
||||
|
||||
if (duration > 1000L) {
|
||||
if (!time_out) {
|
||||
log.warn("{} 读取超时 : {}", tag, duration);
|
||||
@@ -125,78 +167,195 @@ public class DeviceOpcProtocolRunable implements Runnable {
|
||||
time_out = false;
|
||||
}
|
||||
|
||||
boolean valueAllNotNull = false;
|
||||
Set<Item> items = itemStatus.keySet();
|
||||
Iterator var18 = items.iterator();
|
||||
|
||||
while (true) {
|
||||
Item item;
|
||||
//当前值
|
||||
Object value;
|
||||
//旧的值
|
||||
Object his;
|
||||
do {
|
||||
if (!var18.hasNext()) {
|
||||
end = System.currentTimeMillis();
|
||||
log.trace("{}", itemsString);
|
||||
log.trace("{} 计算完成耗时{}", tag, end - begin);
|
||||
Thread.sleep((long) OpcConfig.synchronized_millisecond);
|
||||
if (this.error_num != 0) {
|
||||
this.error_num = 0;
|
||||
this.message = null;
|
||||
}
|
||||
continue label97;
|
||||
}
|
||||
|
||||
item = (Item) var18.next();
|
||||
ItemState itemState = (ItemState) itemStatus.get(item);
|
||||
value = OpcUtl.getValue(item, itemState);
|
||||
his = accessor_value.getValue(item.getId());
|
||||
if (!ObjectUtil.equal(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && his != null) {
|
||||
log.warn("opc 值不健康 item: {}, 状态: {}", item.getId(), itemState.getQuality());
|
||||
}
|
||||
} while (ObjectUtil.equal(value, his));//如果两次的值相等,不走下面的代码
|
||||
|
||||
OpcItemDto itemDto = this.getItem(item.getId());
|
||||
if (itemDto.getNeed_log() != null && itemDto.getNeed_log()) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
//设备的ITEM项
|
||||
List<String> relate_items = itemDto.getRelate_items();
|
||||
Iterator var26 = relate_items.iterator();
|
||||
|
||||
while (var26.hasNext()) {
|
||||
String relate = (String) var26.next();
|
||||
Object obj = accessor_value.getValue(relate);
|
||||
sb.append("key:" + relate + "value:" + obj + ";");
|
||||
}
|
||||
|
||||
log.info("信号{}变更从{}->{};信号快照:{}", new Object[]{item.getId(), his, value, sb});
|
||||
|
||||
while (var18.hasNext()) {
|
||||
Item item = (Item) var18.next();
|
||||
ItemState itemState = (ItemState) itemStatus.get(item);
|
||||
Object value = OpcUtl.getValue(item, itemState);
|
||||
if (value != null) {
|
||||
valueAllNotNull = true;
|
||||
}
|
||||
//设置值
|
||||
accessor_value.setValue(item.getId(), value);
|
||||
|
||||
String itemId = item.getId();
|
||||
Object his = accessor_value.getValue(itemId);
|
||||
if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && his != null) {
|
||||
log.warn("opc 值不健康 item: {}, 状态: {}", itemId, itemState.getQuality());
|
||||
}
|
||||
|
||||
if (!UnifiedDataAppService.isEquals(value, his)) {
|
||||
OpcItemDto itemDto = this.getItem(itemId);
|
||||
if (true) {
|
||||
this.logItemChanged(itemId, accessor_value, value, itemDto);
|
||||
}
|
||||
|
||||
accessor_value.setValue(itemId, value);
|
||||
}
|
||||
}
|
||||
|
||||
end = System.currentTimeMillis();
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("{}", itemsString);
|
||||
log.trace("{} 计算完成耗时{}", tag, end - begin);
|
||||
}
|
||||
|
||||
ThreadUtl.sleep((long) OpcConfig.synchronized_millisecond);
|
||||
if (this.error_num != 0) {
|
||||
this.error_num = 0;
|
||||
this.message = null;
|
||||
}
|
||||
|
||||
if (!valueAllNotNull) {
|
||||
int random = (new Random()).nextInt(10) + 1;
|
||||
random *= 1000;
|
||||
if (this.all_null < 3) {
|
||||
if (log.isWarnEnabled()) {
|
||||
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null,5000 + random);
|
||||
}
|
||||
|
||||
ThreadUtl.sleep((long) (5000 + random));
|
||||
} else if (this.all_null < 6) {
|
||||
if (log.isWarnEnabled()) {
|
||||
log.warn(tag + "重新创建server");
|
||||
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null,30000 + random);
|
||||
}
|
||||
// ThreadUtl.sleep((long) (30000 + random));
|
||||
ThreadUtl.sleep((long) ((new Random()).nextInt(3) +1) * 1000);
|
||||
break start;
|
||||
} else if (this.all_null < 12) {
|
||||
if (log.isWarnEnabled()) {
|
||||
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}ms", tag, all_null, '\uea60' + random);
|
||||
}
|
||||
|
||||
ThreadUtl.sleep((long) ('\uea60' + random));
|
||||
} else {
|
||||
if (log.isWarnEnabled()) {
|
||||
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}ms", tag, all_null, 120000 + random);
|
||||
}
|
||||
|
||||
ThreadUtl.sleep((long) (120000 + random));
|
||||
}
|
||||
|
||||
++this.all_null;
|
||||
} else {
|
||||
this.all_null = 0;
|
||||
}
|
||||
// break start;
|
||||
|
||||
}
|
||||
|
||||
log.warn("opc线程停止。。。");
|
||||
return;
|
||||
} catch (Exception var27) {
|
||||
if (this.server != null) {
|
||||
try {
|
||||
this.server.disconnect();
|
||||
} catch (Exception var25) {
|
||||
}
|
||||
}
|
||||
} catch (Exception var30) {
|
||||
String error_message = "设备信息同步异常";
|
||||
if (!StrUtil.equals(this.message, error_message)) {
|
||||
log.warn("", var30);
|
||||
|
||||
this.server = null;
|
||||
if (!DeviceOpcSynchronizeAutoRun.isRun) {
|
||||
log.warn("opc线程停止2。。。");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000));
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
String error_message = "设备信息同步异常";
|
||||
if (!StrUtil.equals(this.message, error_message)) {
|
||||
log.warn(error_message, var27);
|
||||
}
|
||||
|
||||
ThreadUtl.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000));
|
||||
++this.error_num;
|
||||
if (this.error_num > 3 && !StrUtil.equals(this.message, error_message)) {
|
||||
log.info("设备同步通信异常");
|
||||
this.message = error_message;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void runNew() {
|
||||
Async20Access accessor = null;
|
||||
|
||||
while (true) {
|
||||
String opcGroupId = this.getOpcGroupID();
|
||||
|
||||
try {
|
||||
if (this.server == null) {
|
||||
this.server = OpcServerUtl.getServerWithOutException(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain());
|
||||
this.server.addStateListener(this);
|
||||
accessor = new Async20Access(this.server, OpcConfig.synchronized_millisecond, true);
|
||||
Iterator var9 = this.protocols.iterator();
|
||||
|
||||
while (var9.hasNext()) {
|
||||
OpcItemDto protocol = (OpcItemDto) var9.next();
|
||||
String itemId = protocol.getItem_code();
|
||||
accessor.addItem(itemId, this);
|
||||
}
|
||||
|
||||
accessor.bind();
|
||||
log.info("Async20Access bind {}", opcGroupId);
|
||||
}
|
||||
|
||||
Thread.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000));
|
||||
} catch (Exception var8) {
|
||||
if (accessor != null) {
|
||||
try {
|
||||
log.warn("Async20Access unbind {}", opcGroupId);
|
||||
accessor.unbind();
|
||||
} catch (Exception var7) {
|
||||
var7.printStackTrace();
|
||||
}
|
||||
|
||||
accessor = null;
|
||||
}
|
||||
|
||||
if (this.server != null) {
|
||||
try {
|
||||
this.server.disconnect();
|
||||
} catch (Exception var6) {
|
||||
}
|
||||
|
||||
this.server = null;
|
||||
}
|
||||
|
||||
if (var8 instanceof InterruptedException) {
|
||||
log.warn("OPC 同步线程(%s)被中断", opcGroupId);
|
||||
return;
|
||||
}
|
||||
|
||||
log.warn("设备信息同步异常", var8);
|
||||
ThreadUtl.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000));
|
||||
String error_message = var8.getMessage();
|
||||
if (error_message == null) {
|
||||
error_message = var8.toString();
|
||||
}
|
||||
|
||||
++this.error_num;
|
||||
if (this.error_num > 3 && !StrUtil.equals(this.message, error_message)) {
|
||||
this.message = error_message;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void connectionStateChanged(boolean connected) {
|
||||
if (!connected) {
|
||||
this.server = null;
|
||||
}
|
||||
|
||||
log.warn("opc server {} {}", this.getOpcGroupID(), connected ? "connected" : "disconnected");
|
||||
}
|
||||
|
||||
private String getOpcGroupID() {
|
||||
String var10000 = this.OpcServer.getOpc_code();
|
||||
return var10000 + "(" + this.protocols.size() + " items)";
|
||||
}
|
||||
|
||||
public static String formatDuring(long mss) {
|
||||
long days = mss / 86400000L;
|
||||
long hours = mss % 86400000L / 3600000L;
|
||||
@@ -204,4 +363,55 @@ public class DeviceOpcProtocolRunable implements Runnable {
|
||||
long seconds = mss % 60000L / 1000L;
|
||||
return days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ";
|
||||
}
|
||||
|
||||
|
||||
public void changed(Item item, ItemState itemState) {
|
||||
String itemId = item.getId();
|
||||
|
||||
try {
|
||||
Object value = OpcUtl.getValue(item, itemState);
|
||||
UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
|
||||
accessor_value.setValue(itemId, value);
|
||||
|
||||
// if (value != null) {
|
||||
// if (log.isTraceEnabled()) {
|
||||
// log.trace("Item {} new value: {}, Timestamp: {}", new Object[]{itemId, itemState.getValue(), itemState.getTimestamp().getTime()});
|
||||
// }
|
||||
// } else if (log.isInfoEnabled()) {
|
||||
// log.info("Item {} new value: {}, Timestamp: {}, Quality: {}", new Object[]{itemId, itemState.getValue(), itemState.getTimestamp().getTime(), itemState.getQuality()});
|
||||
// }
|
||||
log.trace("Item {} new value: {}, Timestamp: {}", new Object[]{itemId, itemState.getValue(), itemState.getTimestamp().getTime()});
|
||||
|
||||
OpcItemDto itemDto = this.getItem(itemId);
|
||||
// if (Boolean.TRUE.equals(itemDto.getNeed_log())) {
|
||||
// this.logItemChanged(itemId, accessor_value, value, itemDto);
|
||||
// }
|
||||
this.logItemChanged(itemId, accessor_value, value, itemDto);
|
||||
|
||||
} catch (Exception var7) {
|
||||
log.error(itemId, var7);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void logItemChanged(String itemId, UnifiedDataAccessor accessor_value, Object value, OpcItemDto itemDto) {
|
||||
Object his = accessor_value.getValue(itemId);
|
||||
List<String> relate_items = itemDto.getRelate_items();
|
||||
if (relate_items != null && !relate_items.isEmpty()) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Iterator var8 = relate_items.iterator();
|
||||
|
||||
while (var8.hasNext()) {
|
||||
String relate = (String) var8.next();
|
||||
Object obj = accessor_value.getValue(relate);
|
||||
sb.append("key:" + relate + "value:" + obj + ";");
|
||||
}
|
||||
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value, sb});
|
||||
// this.businessLogger.setResource(itemDto.getDevice_code(), itemDto.getDevice_name()).log("信号{}变更从{}->{};信号快照:{}", new Object[]{itemId, his, value, sb});
|
||||
} else {
|
||||
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value});
|
||||
// this.businessLogger.setResource(itemDto.getDevice_code(), itemDto.getDevice_name()).log("信号{}变更从{}->{}", new Object[]{itemId, his, value});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,81 +1,305 @@
|
||||
//
|
||||
// Source code recreated from a .class file by IntelliJ IDEA
|
||||
// (powered by FernFlower decompiler)
|
||||
//
|
||||
|
||||
package org.nl.acs.opc;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.lucene.util.NamedThreadFactory;
|
||||
import org.nl.acs.auto.run.AbstractAutoRunnable;
|
||||
import org.nl.acs.task.service.TaskService;
|
||||
import org.nl.acs.udw.UnifiedDataAccessor;
|
||||
import org.nl.acs.udw.UnifiedDataAccessorFactory;
|
||||
import org.nl.acs.udw.UnifiedDataAppService;
|
||||
import org.nl.modules.wql.util.SpringContextHolder;
|
||||
import org.openscada.opc.lib.da.Group;
|
||||
import org.openscada.opc.lib.da.Item;
|
||||
import org.openscada.opc.lib.da.ItemState;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* OPC设备同步启动
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class DeviceOpcSynchronizeAutoRun extends AbstractAutoRunnable {
|
||||
ExecutorService executorService = Executors.newCachedThreadPool();
|
||||
static boolean isRun = true;
|
||||
@Autowired
|
||||
private DeviceAppService deviceAppService;
|
||||
@Autowired
|
||||
private OpcServerManageService opcServerManageService;
|
||||
static ExecutorService executorService;
|
||||
public static Map<String, OpcServerManageDto> opcServersConfig;
|
||||
public static Map<String, OpcItemDto> itemCodeOpcItemDtoMapping = new ConcurrentHashMap();
|
||||
|
||||
static boolean canRefreshOpcEntity = true;
|
||||
private long lastRefreshOpcEntityTime;
|
||||
static UnifiedDataAccessor udw;
|
||||
private static Map<String, Boolean> canReadOpcValues;
|
||||
private static volatile Map<String, OpcEntity> opcCodeOpcEntityMapping;
|
||||
|
||||
public DeviceOpcSynchronizeAutoRun() {
|
||||
this.lastRefreshOpcEntityTime = 0L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCode() {
|
||||
return DeviceOpcSynchronizeAutoRun.class.getSimpleName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "opc设备同步器";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void autoRun() throws Exception {
|
||||
{
|
||||
static Group getGroup(String opcCode) throws Exception {
|
||||
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class);
|
||||
return opcServerService.getServer(opcCode);
|
||||
}
|
||||
|
||||
Map<String, OpcServerManageDto> servers = this.opcServerManageService.queryAllServerMap();
|
||||
Map<String, List<List<OpcItemDto>>> pros;
|
||||
do{
|
||||
Thread.sleep(1000L);
|
||||
pros = this.deviceAppService.findAllFormatProtocolFromDriver();
|
||||
}while (ObjectUtil.isEmpty(pros));
|
||||
Set<String> keys = pros.keySet();
|
||||
Iterator var4 = keys.iterator();
|
||||
System.out.println("test:" + var4.hasNext());
|
||||
//代码执行一次
|
||||
while (var4.hasNext()) {
|
||||
String key = (String) var4.next();
|
||||
List<List<OpcItemDto>> list = (List) pros.get(key);
|
||||
OpcServerManageDto opcServer = (OpcServerManageDto) servers.get(key);
|
||||
Iterator var8 = list.iterator();
|
||||
System.out.println("test2:" + var8.hasNext());
|
||||
static void submitTimeLimitTask(Runnable runnable, String opcCode) {
|
||||
CompletableFuture future = CompletableFuture.runAsync(runnable, executorService);
|
||||
|
||||
while (var8.hasNext()) {
|
||||
List<OpcItemDto> groupProtols = (List) var8.next();
|
||||
DeviceOpcProtocolRunable runable = new DeviceOpcProtocolRunable();
|
||||
runable.setProtocols(groupProtols);
|
||||
runable.setOpcServer(opcServer);
|
||||
this.executorService.submit(runable);
|
||||
try {
|
||||
future.get(10L, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException var9) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (ExecutionException var10) {
|
||||
var10.printStackTrace();
|
||||
} catch (TimeoutException var11) {
|
||||
itemCodeOpcItemDtoMapping.keySet().forEach((key) -> {
|
||||
udw.setValue(key, (Object)null);
|
||||
});
|
||||
canReadOpcValues = new ConcurrentHashMap();
|
||||
System.out.println("opc设备同步器 任务执行超时,取消任务...");
|
||||
future.cancel(true);
|
||||
} finally {
|
||||
canRefreshOpcEntity = true;
|
||||
if (opcCode != null) {
|
||||
canReadOpcValues.put(opcCode, true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private ExecutorService createThreadPool() {
|
||||
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 30, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory("opc-sync"));
|
||||
executor.allowCoreThreadTimeOut(true);
|
||||
return executor;
|
||||
}
|
||||
|
||||
public void autoRun() {
|
||||
OpcStartTag.is_run = true;
|
||||
opcServersConfig = this.opcServerManageService.queryAllServerMap();
|
||||
executorService = this.createThreadPool();
|
||||
opcCodeOpcEntityMapping = new ConcurrentHashMap();
|
||||
itemCodeOpcItemDtoMapping.keySet().forEach((key) -> {
|
||||
udw.setValue(key, (Object)null);
|
||||
});
|
||||
canRefreshOpcEntity = true;
|
||||
canReadOpcValues.clear();
|
||||
|
||||
while(true) {
|
||||
this.refreshOpcEntity();
|
||||
Iterator var1 = opcServersConfig.keySet().iterator();
|
||||
|
||||
while(var1.hasNext()) {
|
||||
String opcCode = (String)var1.next();
|
||||
Boolean canRead = (Boolean)canReadOpcValues.computeIfAbsent(opcCode, (key) -> {
|
||||
return true;
|
||||
});
|
||||
if (canRead) {
|
||||
canReadOpcValues.put(opcCode, false);
|
||||
submitTimeLimitTask(() -> {
|
||||
try {
|
||||
this.readOpcValues(opcCode);
|
||||
} catch (Exception var3) {
|
||||
var3.printStackTrace();
|
||||
}
|
||||
|
||||
}, opcCode);
|
||||
}
|
||||
}
|
||||
|
||||
// 同步无光电设备信号
|
||||
//Map<String, List<List<OpcItemDto>>> pros1 = this.deviceAppService.findAllFormatProtocolFromDriver();
|
||||
//List<DeviceDriver> opcDrivers = this.deviceAppService.findDeviceDriver(DeviceDriver.class);
|
||||
ThreadUtl.sleep((long)OpcConfig.synchronized_millisecond);
|
||||
}
|
||||
}
|
||||
|
||||
while (true) {
|
||||
Thread.sleep(3000L);
|
||||
private void readOpcValues(String opcCode) throws Exception {
|
||||
synchronized(opcCode.intern()) {
|
||||
OpcEntity opcEntity = (OpcEntity)opcCodeOpcEntityMapping.get(opcCode);
|
||||
if (opcEntity != null) {
|
||||
if (opcEntity.getItems().size() != 0) {
|
||||
long begin = System.currentTimeMillis();
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("opc {} 开始计时{}", opcCode, begin);
|
||||
}
|
||||
|
||||
new HashMap();
|
||||
|
||||
Map itemStatus;
|
||||
try {
|
||||
itemStatus = opcEntity.readAll();
|
||||
} catch (Exception var15) {
|
||||
itemStatus = opcEntity.readDividually();
|
||||
}
|
||||
|
||||
long end = System.currentTimeMillis();
|
||||
long duration = end - begin;
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("opc {} 读取耗时:{}", opcCode, duration);
|
||||
}
|
||||
|
||||
if (duration > 1000L) {
|
||||
log.warn("opc {} 读取超时 : {}", opcCode, duration);
|
||||
}
|
||||
|
||||
// boolean allNull = itemStatus.entrySet().stream().map((map) -> {
|
||||
// return OpcUtl.getValue((Item)map.getKey(), (ItemState)map.getValue());
|
||||
// }).allMatch(Objects::isNull);
|
||||
// if (allNull) {
|
||||
// opcEntity.getItems().clear();
|
||||
// }
|
||||
|
||||
|
||||
|
||||
UnifiedDataAccessor udw = opcEntity.getUdw();
|
||||
|
||||
|
||||
Set<Item> items = itemStatus.keySet();
|
||||
Iterator var18 = items.iterator();
|
||||
|
||||
while (var18.hasNext()) {
|
||||
Item item = (Item) var18.next();
|
||||
ItemState itemState = (ItemState) itemStatus.get(item);
|
||||
Object nowValue = OpcUtl.getValue(item, itemState);
|
||||
String itemId = item.getId();
|
||||
Object historyValue = udw.getValue(itemId);
|
||||
if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && historyValue != null) {
|
||||
log.warn("opc 值不健康 item: {}, 状态: {}", itemId, itemState.getQuality());
|
||||
}
|
||||
|
||||
if (!UnifiedDataAppService.isEquals(nowValue, historyValue)) {
|
||||
OpcItemDto itemDto = (OpcItemDto) itemCodeOpcItemDtoMapping.get(itemId);
|
||||
if (true) {
|
||||
this.logItemChanged(itemId, udw, nowValue, itemDto);
|
||||
}
|
||||
|
||||
udw.setValue(itemId, nowValue);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// itemStatus.forEach((Item item, ItemState itemState) -> {
|
||||
// Object nowValue = null;
|
||||
// try {
|
||||
// nowValue = OpcUtl.getValue((Item)item, (ItemState)itemState);
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// String itemId = item.getId();
|
||||
// Object historyValue = udw.getValue(itemId);
|
||||
// if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && historyValue != null) {
|
||||
// log.warn("opc 值不健康 item: {}, 状态: {}", itemId, itemState.getQuality());
|
||||
// }
|
||||
//
|
||||
// if (!UnifiedDataAppService.isEquals(nowValue, historyValue)) {
|
||||
// OpcItemDto itemDto = (OpcItemDto)itemCodeOpcItemDtoMapping.get(itemId);
|
||||
// if (Boolean.TRUE.equals(itemDto.getNeed_log())) {
|
||||
// this.logItemChanged(itemId, udw, nowValue, itemDto);
|
||||
// }
|
||||
//
|
||||
// udw.setValue(itemId, nowValue);
|
||||
// }
|
||||
//
|
||||
// });
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
private void refreshOpcEntity() {
|
||||
if (canRefreshOpcEntity) {
|
||||
canRefreshOpcEntity = false;
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - this.lastRefreshOpcEntityTime >= 20000L) {
|
||||
this.lastRefreshOpcEntityTime = now;
|
||||
submitTimeLimitTask(() -> {
|
||||
try {
|
||||
Map<String, List<List<OpcItemDto>>> protocol = this.deviceAppService.findAllFormatProtocolFromDriver();
|
||||
Iterator var2 = protocol.entrySet().iterator();
|
||||
|
||||
while(var2.hasNext()) {
|
||||
Entry<String, List<List<OpcItemDto>>> stringListEntry = (Entry)var2.next();
|
||||
String opcCode = (String)stringListEntry.getKey();
|
||||
List<List<OpcItemDto>> opcItemDtos = (List)stringListEntry.getValue();
|
||||
((OpcEntity)opcCodeOpcEntityMapping.computeIfAbsent(opcCode, OpcEntity::new)).reload(opcItemDtos);
|
||||
}
|
||||
} catch (Exception var6) {
|
||||
var6.printStackTrace();
|
||||
}
|
||||
|
||||
}, (String)null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void logMessage(String errorMessage) {
|
||||
try {
|
||||
// issueLogger.setResource(OpcConfig.resource_code, OpcConfig.resource_name).setError(StringUtl.getString(100), "设备同步通信异常").log(errorMessage, new Object[0]);
|
||||
// businessLogger.setResource(OpcConfig.resource_code, OpcConfig.resource_name).setError(StringUtl.getString(100), "设备同步通信异常").log(errorMessage, new Object[0]);
|
||||
} catch (Exception var5) {
|
||||
var5.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void after() {
|
||||
this.executorService.shutdownNow();
|
||||
this.executorService = Executors.newCachedThreadPool();
|
||||
OpcStartTag.is_run = false;
|
||||
opcCodeOpcEntityMapping.values().forEach((opcEntity) -> {
|
||||
opcEntity.cleanUdwCache();
|
||||
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class);
|
||||
opcServerService.cleanGroups(opcEntity.getOpcCode());
|
||||
});
|
||||
opcCodeOpcEntityMapping = new ConcurrentHashMap();
|
||||
itemCodeOpcItemDtoMapping = new ConcurrentHashMap();
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
|
||||
private void logItemChanged(String itemCode, UnifiedDataAccessor udw, Object value, OpcItemDto itemDto) {
|
||||
Object his = udw.getValue(itemCode);
|
||||
List<String> relate_items = itemDto.getRelate_items();
|
||||
if (relate_items != null && !relate_items.isEmpty()) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Iterator var8 = relate_items.iterator();
|
||||
|
||||
while(var8.hasNext()) {
|
||||
String relate = (String)var8.next();
|
||||
Object obj = udw.getValue(relate);
|
||||
sb.append("key:").append(relate).append("value:").append(obj).append(";");
|
||||
}
|
||||
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemCode, his, value, sb});
|
||||
System.out.println("设备:"+itemDto.getDevice_code() + "信号:"+ itemCode + itemCode + "变更从:" + his + "->" +value);
|
||||
} else {
|
||||
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemCode, his, value});
|
||||
System.out.println("设备:"+itemDto.getDevice_code() + "信号:"+ itemCode + itemCode + "变更从:" + his + "->" +value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static {
|
||||
udw = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
|
||||
canReadOpcValues = new ConcurrentHashMap();
|
||||
opcCodeOpcEntityMapping = new ConcurrentHashMap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
public class ItemValue {
|
||||
private String item_code;
|
||||
private Object item_value;
|
||||
|
||||
public ItemValue() {
|
||||
}
|
||||
|
||||
public ItemValue(String item_code, Object item_value) {
|
||||
this.item_code = item_code;
|
||||
this.item_value = item_value;
|
||||
}
|
||||
|
||||
public String getItem_code() {
|
||||
return this.item_code;
|
||||
}
|
||||
|
||||
public void setItem_code(String item_code) {
|
||||
this.item_code = item_code;
|
||||
}
|
||||
|
||||
public Object getItem_value() {
|
||||
return this.item_value;
|
||||
}
|
||||
|
||||
public void setItem_value(Object item_value) {
|
||||
this.item_value = item_value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
|
||||
import org.nl.modules.wql.exception.WDKException;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
public class ObjectUtl {
|
||||
private ObjectUtl() {
|
||||
}
|
||||
|
||||
public static boolean isEquals(Object a, Object b) {
|
||||
if (a == null && b == null) {
|
||||
return true;
|
||||
} else if (a != null && b != null) {
|
||||
if (a.getClass().isArray()) {
|
||||
if (a instanceof boolean[]) {
|
||||
return Arrays.equals((boolean[]) ((boolean[]) a), (boolean[]) ((boolean[]) b));
|
||||
} else if (a instanceof byte[]) {
|
||||
return Arrays.equals((byte[]) ((byte[]) a), (byte[]) ((byte[]) b));
|
||||
} else if (a instanceof int[]) {
|
||||
return Arrays.equals((int[]) ((int[]) a), (int[]) ((int[]) b));
|
||||
} else if (a instanceof long[]) {
|
||||
return Arrays.equals((long[]) ((long[]) a), (long[]) ((long[]) b));
|
||||
} else if (a instanceof double[]) {
|
||||
return Arrays.equals((double[]) ((double[]) a), (double[]) ((double[]) b));
|
||||
} else if (a instanceof short[]) {
|
||||
return Arrays.equals((short[]) ((short[]) a), (short[]) ((short[]) b));
|
||||
} else if (a instanceof char[]) {
|
||||
return Arrays.equals((char[]) ((char[]) a), (char[]) ((char[]) b));
|
||||
} else if (a instanceof float[]) {
|
||||
return Arrays.equals((float[]) ((float[]) a), (float[]) ((float[]) b));
|
||||
} else if (a instanceof Object[]) {
|
||||
return Arrays.equals((Object[]) ((Object[]) a), (Object[]) ((Object[]) b));
|
||||
} else {
|
||||
throw new WDKException("未实现");
|
||||
}
|
||||
} else {
|
||||
return Objects.equals(a, b);
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isTrue(Boolean boolean_) {
|
||||
return boolean_ != null && isEquals(boolean_, true);
|
||||
}
|
||||
|
||||
public static boolean isTrue(Boolean targetBoolean, boolean defaultBoolean) {
|
||||
return targetBoolean == null ? defaultBoolean : targetBoolean;
|
||||
}
|
||||
|
||||
public static boolean isFalse(Boolean boolean_) {
|
||||
return boolean_ != null && isEquals(boolean_, false);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public static boolean isObject(Class<?> clazz) {
|
||||
if (clazz == null) {
|
||||
return false;
|
||||
} else if (clazz.getClass().isArray()) {
|
||||
return false;
|
||||
} else {
|
||||
return Object.class.isAssignableFrom(clazz);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,13 @@ public class OpcConfig {
|
||||
public static Boolean auto_start_opc = Boolean.valueOf(true);
|
||||
public static String udw_opc_value_key = "opc_value";
|
||||
public static Integer synchronized_millisecond = Integer.valueOf(100);
|
||||
public static Integer synchronized_exception_wait_second = Integer.valueOf(10);
|
||||
public static Integer synchronized_exception_wait_second = Integer.valueOf(3);
|
||||
public static Integer retry_times = Integer.valueOf(3);
|
||||
public static String sync_issue_type_code = "device_opc_sync";
|
||||
public static String opc_server_default_group = "group";
|
||||
public static String resource_code = "opc_sync";
|
||||
public static String resource_name = "opc同步";
|
||||
|
||||
//OPC 数据同步是否采用回调机制实现。之前是线程定期全部读,效率低。
|
||||
public static Boolean opc_item_read_using_callback = false;
|
||||
}
|
||||
|
||||
177
acs/nladmin-system/src/main/java/org/nl/acs/opc/OpcEntity.java
Normal file
177
acs/nladmin-system/src/main/java/org/nl/acs/opc/OpcEntity.java
Normal file
@@ -0,0 +1,177 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
import org.jinterop.dcom.common.JIException;
|
||||
import org.nl.acs.udw.UnifiedDataAccessor;
|
||||
import org.nl.acs.udw.UnifiedDataAccessorFactory;
|
||||
import org.nl.modules.wql.util.SpringContextHolder;
|
||||
import org.openscada.opc.lib.da.Group;
|
||||
import org.openscada.opc.lib.da.Item;
|
||||
import org.openscada.opc.lib.da.ItemState;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
public class OpcEntity {
|
||||
@Autowired
|
||||
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class);
|
||||
private final UnifiedDataAccessor udw;
|
||||
private Map<String, List<Item>> items;
|
||||
private Map<String, List<String>> someFailDevices;
|
||||
private String opcCode;
|
||||
|
||||
public OpcEntity(String opcCode) {
|
||||
this.udw = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
|
||||
this.items = new ConcurrentHashMap();
|
||||
this.someFailDevices = new ConcurrentHashMap();
|
||||
this.opcCode = opcCode;
|
||||
}
|
||||
|
||||
public void reload(List<List<OpcItemDto>> opcItemDtos) {
|
||||
Map<String, List<String>> itemCodes = new ConcurrentHashMap();
|
||||
(opcItemDtos.stream().flatMap(Collection::stream).collect(Collectors.groupingBy(OpcItemDto::getDevice_code))).forEach((deviceCodes, opcItemDtoList) -> {
|
||||
itemCodes.put(deviceCodes, opcItemDtoList.stream().map(OpcItemDto::getItem_code).collect(Collectors.toList()));
|
||||
});
|
||||
DeviceOpcSynchronizeAutoRun.itemCodeOpcItemDtoMapping.putAll((Map)opcItemDtos.stream().flatMap(Collection::stream).collect(Collectors.toMap(OpcItemDto::getItem_code, (obj) -> {
|
||||
return obj;
|
||||
})));
|
||||
if (this.items.size() == 0) {
|
||||
itemCodes.values().stream().flatMap(Collection::stream).forEach((key) -> {
|
||||
this.udw.setValue(key, (Object)null);
|
||||
});
|
||||
this.addItemsIntoGroup(itemCodes);
|
||||
} else {
|
||||
if (this.someFailDevices.size() > 0) {
|
||||
this.reAddDevices();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void reAddDevices() {
|
||||
Map<String, List<Item>> addItems = new ConcurrentHashMap();
|
||||
StringBuilder err_message = new StringBuilder();
|
||||
this.someFailDevices.forEach((deviceCode, itemCodesList) -> {
|
||||
itemCodesList.forEach((itemCode) -> {
|
||||
try {
|
||||
Group group = DeviceOpcSynchronizeAutoRun.getGroup(this.opcCode);
|
||||
((List)addItems.computeIfAbsent(deviceCode, (key) -> {
|
||||
return new ArrayList();
|
||||
})).add(group.addItem(itemCode));
|
||||
} catch (Exception var6) {
|
||||
err_message.append(itemCode).append(" 添加失败; ");
|
||||
}
|
||||
|
||||
});
|
||||
List<Item> deviceItems = (List)addItems.get(deviceCode);
|
||||
if (deviceItems != null && deviceItems.size() == itemCodesList.size()) {
|
||||
this.someFailDevices.remove(deviceCode);
|
||||
} else if (itemCodesList.size() == 0) {
|
||||
addItems.remove(deviceCode);
|
||||
} else {
|
||||
assert deviceItems != null;
|
||||
|
||||
((List)this.someFailDevices.get(deviceCode)).removeAll(deviceItems);
|
||||
}
|
||||
|
||||
synchronized(this.opcCode.intern()) {
|
||||
this.items.putAll(addItems);
|
||||
}
|
||||
|
||||
if (err_message.length() > 0) {
|
||||
String errMsg = err_message.toString();
|
||||
//this.log.warn("{}:{}", com.wxzd.wcs.opc.OpcConfig.resource_code, errMsg);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
private void addItemsIntoGroup(Map<String, List<String>> itemCodes) {
|
||||
try {
|
||||
Group group = DeviceOpcSynchronizeAutoRun.getGroup(this.opcCode);
|
||||
StringBuilder err_message = new StringBuilder();
|
||||
Map<String, List<Item>> items = new ConcurrentHashMap();
|
||||
itemCodes.forEach((deviceCode, itemCodesList) -> {
|
||||
itemCodesList.forEach((itemCode) -> {
|
||||
try {
|
||||
((List)items.computeIfAbsent(deviceCode, (key) -> {
|
||||
return new ArrayList();
|
||||
})).add(group.addItem(itemCode));
|
||||
} catch (Exception var7) {
|
||||
((List)this.someFailDevices.computeIfAbsent(deviceCode, (key) -> {
|
||||
return new ArrayList();
|
||||
})).add(itemCode);
|
||||
this.udw.setValue(itemCode, (Object)null);
|
||||
err_message.append(itemCode).append(" 添加失败; ");
|
||||
}
|
||||
|
||||
});
|
||||
List<Item> deviceItems = (List)items.get(deviceCode);
|
||||
if (deviceItems != null && deviceItems.size() != itemCodesList.size()) {
|
||||
items.remove(deviceCode);
|
||||
this.someFailDevices.put(deviceCode, itemCodesList);
|
||||
}
|
||||
|
||||
});
|
||||
synchronized(this.opcCode.intern()) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
if (err_message.length() > 0) {
|
||||
String errMsg = err_message.toString();
|
||||
// this.log.warn("{}:{}", OpcConfig.resource_code, errMsg);
|
||||
}
|
||||
} catch (Exception var8) {
|
||||
var8.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void cleanUdwCache() {
|
||||
this.items.values().stream().flatMap(Collection::stream).map(Item::getId).forEach((key) -> {
|
||||
this.udw.setValue(key, (Object)null);
|
||||
});
|
||||
}
|
||||
|
||||
public Map<Item, ItemState> readAll() throws Exception {
|
||||
return opcServerService.getServer(this.opcCode).read(true, (Item[])this.items.values().stream().flatMap(Collection::stream).toArray((x$0) -> {
|
||||
return new Item[x$0];
|
||||
}));
|
||||
}
|
||||
|
||||
public Map<Item, ItemState> readDividually() {
|
||||
Map<Item, ItemState> result = new HashMap();
|
||||
CompletableFuture[] futures = (CompletableFuture[])this.items.entrySet().stream().map((entry) -> {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
Group group = DeviceOpcSynchronizeAutoRun.getGroup(this.opcCode);
|
||||
result.putAll(group.read(true, (Item[])((List)entry.getValue()).toArray(new Item[0])));
|
||||
} catch (Exception var5) {
|
||||
String deviceCode = (String)entry.getKey();
|
||||
// to do
|
||||
// this.someFailDevices.put(deviceCode, ((List)entry.getValue()).stream().map(Item::getId).collect(Collectors.toList()));
|
||||
this.items.remove(deviceCode);
|
||||
}
|
||||
|
||||
}, DeviceOpcSynchronizeAutoRun.executorService);
|
||||
}).toArray((x$0) -> {
|
||||
return new CompletableFuture[x$0];
|
||||
});
|
||||
CompletableFuture.allOf(futures).join();
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public UnifiedDataAccessor getUdw() {
|
||||
return this.udw;
|
||||
}
|
||||
|
||||
public Map<String, List<Item>> getItems() {
|
||||
return this.items;
|
||||
}
|
||||
|
||||
public String getOpcCode() {
|
||||
return this.opcCode;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class OpcItemDto {
|
||||
private String device_code;
|
||||
private String device_name;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
import org.openscada.opc.lib.da.Group;
|
||||
|
||||
/**
|
||||
* @author ldjun
|
||||
* @version 1.0
|
||||
* @date 2023年02月01日 11:26
|
||||
* @desc desc
|
||||
*/
|
||||
public interface OpcServerService {
|
||||
|
||||
void reload();
|
||||
|
||||
Group getServer(String var1) throws Exception;
|
||||
|
||||
void writeInteger(String var1, ItemValue... var2);
|
||||
|
||||
void clearServer(String var1);
|
||||
|
||||
void cleanGroups(String var1);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.jinterop.dcom.common.JIException;
|
||||
import org.nl.acs.auto.initial.ApplicationAutoInitial;
|
||||
import org.nl.modules.common.exception.BadRequestException;
|
||||
import org.openscada.opc.lib.common.NotConnectedException;
|
||||
import org.openscada.opc.lib.da.Group;
|
||||
import org.openscada.opc.lib.da.Server;
|
||||
import org.openscada.opc.lib.da.UnknownGroupException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author ldjun
|
||||
* @version 1.0
|
||||
* @date 2023年02月01日 11:27
|
||||
* @desc desc
|
||||
*/
|
||||
@Service
|
||||
public class OpcServerServiceImpl implements OpcServerService, ApplicationAutoInitial {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OpcServerServiceImpl.class);
|
||||
@Autowired OpcServerManageService opcServerManageService;
|
||||
Map<String, OpcServerManageDto> opcServerManageDtos = new HashMap();
|
||||
Map<String, Server> servers = Collections.synchronizedMap(new HashMap());
|
||||
Map<String, Group> groups = Collections.synchronizedMap(new HashMap());
|
||||
|
||||
public OpcServerServiceImpl() {}
|
||||
|
||||
public void autoInitial() throws Exception {
|
||||
this.reload();
|
||||
if (OpcConfig.auto_start_opc) {
|
||||
Thread t =
|
||||
new Thread() {
|
||||
public void run() {
|
||||
Iterator var1 = OpcServerServiceImpl.this.opcServerManageDtos.values().iterator();
|
||||
|
||||
while (var1.hasNext()) {
|
||||
OpcServerManageDto dto = (OpcServerManageDto) var1.next();
|
||||
|
||||
try {
|
||||
OpcServerServiceImpl.this.getServer(dto.getOpc_code());
|
||||
OpcServerServiceImpl.log.info("加载opc server {}", dto.getOpc_code());
|
||||
} catch (Exception var4) {
|
||||
OpcServerServiceImpl.log.warn("启动无法载入servers", var4);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void reload() {
|
||||
this.opcServerManageDtos = this.opcServerManageService.queryAllServerMap();
|
||||
this.opcServerManageDtos = Collections.synchronizedMap(this.opcServerManageDtos);
|
||||
}
|
||||
|
||||
public void cleanGroups(String opcCode) {
|
||||
Group group = (Group)this.groups.get(opcCode);
|
||||
if (group != null) {
|
||||
Server server = group.getServer();
|
||||
|
||||
try {
|
||||
group.remove();
|
||||
} catch (JIException var5) {
|
||||
var5.printStackTrace();
|
||||
}
|
||||
|
||||
this.groups.remove(opcCode);
|
||||
server.disconnect();
|
||||
this.servers.remove(opcCode);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Group getServer(String code) throws Exception {
|
||||
synchronized(this.buildLock(code)) {
|
||||
Group group = null;
|
||||
group = (Group)this.groups.get(code);
|
||||
if (group != null) {
|
||||
label68: {
|
||||
Group var10000;
|
||||
try {
|
||||
if (!group.isActive()) {
|
||||
break label68;
|
||||
}
|
||||
|
||||
var10000 = group;
|
||||
} catch (JIException var14) {
|
||||
log.error(code, var14);
|
||||
break label68;
|
||||
}
|
||||
|
||||
return var10000;
|
||||
}
|
||||
}
|
||||
|
||||
Server server = (Server)this.servers.get(code);
|
||||
boolean needcreate = false;
|
||||
String groupName = code;
|
||||
if (server == null) {
|
||||
needcreate = true;
|
||||
} else {
|
||||
try {
|
||||
group = server.findGroup(groupName);
|
||||
} catch (UnknownHostException | JIException | UnknownGroupException | NotConnectedException | IllegalArgumentException var13) {
|
||||
log.error(code, var13);
|
||||
needcreate = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (needcreate) {
|
||||
OpcServerManageDto dto = (OpcServerManageDto)this.opcServerManageDtos.get(code);
|
||||
if (dto == null) {
|
||||
throw new BadRequestException(code + "{} 不存在");
|
||||
}
|
||||
|
||||
if (server == null) {
|
||||
server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain()));
|
||||
}
|
||||
|
||||
try {
|
||||
group = server.addGroup(groupName);
|
||||
} catch (Exception var12) {
|
||||
this.clearServer(code);
|
||||
ThreadUtl.sleep(5000L);
|
||||
log.warn("获取opc出错重新获取", code, var12);
|
||||
server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain()));
|
||||
|
||||
try {
|
||||
group = server.addGroup(groupName);
|
||||
} catch (Exception var11) {
|
||||
var11.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
this.servers.put(code, server);
|
||||
this.groups.put(code, group);
|
||||
}
|
||||
|
||||
return group;
|
||||
}
|
||||
}
|
||||
|
||||
public void clearServer(String code) {
|
||||
synchronized(this.buildLock(code)) {
|
||||
try {
|
||||
Server server = (Server)this.servers.get(code);
|
||||
server.disconnect();
|
||||
} catch (Exception var5) {
|
||||
}
|
||||
|
||||
this.servers.remove(code);
|
||||
this.groups.remove(code);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void writeInteger(String code, ItemValue... values) {
|
||||
try {
|
||||
Group group = this.getServer(code);
|
||||
OpcUtl.writeValue(group, values);
|
||||
} catch (Exception var4) {
|
||||
this.clearServer(code);
|
||||
log.warn("写入出错opc server {} 重新加载", code, var4);
|
||||
ThreadUtl.sleep(5000L);
|
||||
// throw var4;
|
||||
}
|
||||
}
|
||||
|
||||
private String buildLock(String key) {
|
||||
if (StrUtil.isEmpty(key)) {
|
||||
key = "";
|
||||
}
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("OpcServerService.");
|
||||
builder.append(key);
|
||||
String lock = builder.toString().intern();
|
||||
return lock;
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,13 @@ import org.openscada.opc.lib.da.Server;
|
||||
public class OpcServerUtl {
|
||||
|
||||
public static synchronized Server getServerWithOutException(String host, String clsid, String user, String password,
|
||||
String domain) {
|
||||
String domain) throws Exception {
|
||||
if (!StrUtil.isEmpty(host) && !StrUtil.isEmpty(clsid) && !StrUtil.isEmpty(user)) {
|
||||
if (domain == null) {
|
||||
domain = "";
|
||||
}
|
||||
return OpcUtl.getServer(host, clsid, user, password, domain);
|
||||
// return OpcUtl.getAutoServer(host, clsid, user, password, domain);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
public class OpcStartTag {
|
||||
public static boolean is_run = true;
|
||||
public static boolean is_run = false;
|
||||
}
|
||||
|
||||
@@ -1,63 +1,109 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
import cn.hutool.core.util.NumberUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jinterop.dcom.common.JIException;
|
||||
import org.jinterop.dcom.core.*;
|
||||
import org.nl.modules.common.exception.BadRequestException;
|
||||
import org.nl.modules.wql.exception.WDKException;
|
||||
import org.openscada.opc.lib.common.ConnectionInformation;
|
||||
import org.openscada.opc.lib.da.*;
|
||||
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jinterop.dcom.common.JIException;
|
||||
import org.jinterop.dcom.core.IJIUnsigned;
|
||||
import org.jinterop.dcom.core.JIArray;
|
||||
import org.jinterop.dcom.core.JIString;
|
||||
import org.jinterop.dcom.core.JIUnsignedByte;
|
||||
import org.jinterop.dcom.core.JIUnsignedShort;
|
||||
import org.jinterop.dcom.core.JIVariant;
|
||||
import org.openscada.opc.dcom.list.ClassDetails;
|
||||
import org.openscada.opc.lib.common.AlreadyConnectedException;
|
||||
import org.openscada.opc.lib.common.ConnectionInformation;
|
||||
import org.openscada.opc.lib.da.AddFailedException;
|
||||
import org.openscada.opc.lib.da.AutoReconnectController;
|
||||
import org.openscada.opc.lib.da.Group;
|
||||
import org.openscada.opc.lib.da.Item;
|
||||
import org.openscada.opc.lib.da.ItemState;
|
||||
import org.openscada.opc.lib.da.Server;
|
||||
import org.openscada.opc.lib.da.WriteRequest;
|
||||
import org.openscada.opc.lib.list.Categories;
|
||||
import org.openscada.opc.lib.list.Category;
|
||||
import org.openscada.opc.lib.list.ServerList;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Slf4j
|
||||
public class OpcUtl {
|
||||
private static int timeout = 180000;
|
||||
private static String key = "rpc.socketTimeout";
|
||||
|
||||
public static void checkTimeout() {
|
||||
if (Integer.getInteger(key, 0).intValue() != timeout) {
|
||||
if (Integer.getInteger(key, 0) != timeout) {
|
||||
System.setProperty(key, String.valueOf(timeout));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private OpcUtl() {
|
||||
}
|
||||
|
||||
public static void writeValue(Group group, WriteRequest... requests) {
|
||||
public static List<Map<String, String>> showAllOpcServer(String host, String user, String password, String domain) throws Exception {
|
||||
try {
|
||||
Map e = group.write(requests);
|
||||
boolean is_success = true;
|
||||
StringBuilder message = new StringBuilder();
|
||||
Iterator arg4 = e.keySet().iterator();
|
||||
List<Map<String, String>> listResult = new ArrayList();
|
||||
ServerList serverList = new ServerList(host, user, password, domain);
|
||||
Collection<ClassDetails> classDetails = serverList.listServersWithDetails(new Category[]{Categories.OPCDAServer10, Categories.OPCDAServer20, Categories.OPCDAServer30}, new Category[0]);
|
||||
Iterator var7 = classDetails.iterator();
|
||||
|
||||
while (arg4.hasNext()) {
|
||||
Item item = (Item) arg4.next();
|
||||
Integer integer = (Integer) e.get(item);
|
||||
if (integer.intValue() != 0) {
|
||||
if (is_success) {
|
||||
is_success = false;
|
||||
}
|
||||
|
||||
message.append(item.getId());
|
||||
message.append(":error code:");
|
||||
message.append(integer);
|
||||
message.append("; ");
|
||||
}
|
||||
while(var7.hasNext()) {
|
||||
ClassDetails details = (ClassDetails)var7.next();
|
||||
Map<String, String> result = new LinkedHashMap();
|
||||
result.put("classId", details.getClsId());
|
||||
result.put("progId", details.getProgId());
|
||||
result.put("description", details.getDescription());
|
||||
listResult.add(result);
|
||||
}
|
||||
|
||||
if (!is_success) {
|
||||
// throw new BusinessException(message.toString());
|
||||
}
|
||||
} catch (JIException arg7) {
|
||||
// throw new BusinessException(arg7);
|
||||
return listResult;
|
||||
} catch (UnknownHostException | JIException | IllegalArgumentException var10) {
|
||||
throw new Exception(var10);
|
||||
}
|
||||
}
|
||||
|
||||
public static Object getValue(Item item, ItemState itemState) throws BadRequestException {
|
||||
if (NumberUtil.compare(itemState.getQuality(), Short.valueOf(QualityTypeValue.OPC_QUALITY_GOOD)) != 0) {
|
||||
public static Server getServer(String host, String clsid, String user, String password, String domain) throws Exception {
|
||||
checkTimeout();
|
||||
Server server = null;
|
||||
|
||||
try {
|
||||
server = new Server(getConnection(host, clsid, user, password, domain), Executors.newSingleThreadScheduledExecutor());
|
||||
server.connect();
|
||||
return server;
|
||||
} catch (UnknownHostException | JIException | AlreadyConnectedException | IllegalArgumentException var7) {
|
||||
throw new Exception(var7);
|
||||
}
|
||||
}
|
||||
|
||||
public static Server getAutoServer(String host, String clsid, String user, String password, String domain) throws Exception {
|
||||
checkTimeout();
|
||||
Server server = null;
|
||||
server = new Server(getConnection(host, clsid, user, password, domain), Executors.newSingleThreadScheduledExecutor());
|
||||
AutoReconnectController autoReconnectController = new AutoReconnectController(server);
|
||||
autoReconnectController.connect();
|
||||
return server;
|
||||
}
|
||||
|
||||
public static ConnectionInformation getConnection(String host, String clsid, String user, String password, String domain) {
|
||||
ConnectionInformation connection = new ConnectionInformation();
|
||||
connection.setHost(host);
|
||||
connection.setClsid(clsid);
|
||||
connection.setUser(user);
|
||||
connection.setPassword(password);
|
||||
connection.setDomain(domain);
|
||||
return connection;
|
||||
}
|
||||
|
||||
public static Object getValue(Item item, ItemState itemState) throws Exception {
|
||||
if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD)) {
|
||||
if (item != null) {
|
||||
log.debug("value is not good {} : {}", item.getId(), itemState.getQuality());
|
||||
} else {
|
||||
@@ -71,24 +117,36 @@ public class OpcUtl {
|
||||
}
|
||||
}
|
||||
|
||||
public static Object getValue(JIVariant jiVariant, String id) throws BadRequestException {
|
||||
public static int getIntegerValue(Item item, ItemState itemState) throws Exception {
|
||||
return (Integer)getValue(item, itemState);
|
||||
}
|
||||
|
||||
public static String getStringValue(Item item, ItemState itemState) throws Exception {
|
||||
return (String)getValue(item, itemState);
|
||||
}
|
||||
|
||||
public static byte[] getByteArrayValue(Item item, ItemState itemState) throws Exception {
|
||||
return (byte[])((byte[])getValue(item, itemState));
|
||||
}
|
||||
|
||||
public static Object getValue(JIVariant jiVariant, String id) {
|
||||
try {
|
||||
Object e = jiVariant.getObject();
|
||||
if (e instanceof IJIUnsigned) {
|
||||
return Integer.valueOf(((IJIUnsigned) e).getValue().intValue());
|
||||
} else if (e instanceof Boolean) {
|
||||
return jiVariant.getObjectAsBoolean() ? Integer.valueOf(1) : Integer.valueOf(0);
|
||||
} else if (e instanceof JIString) {
|
||||
return ((JIString) e).getString();
|
||||
} else if (!(e instanceof JIArray)) {
|
||||
if (e instanceof Integer) {
|
||||
Object object = jiVariant.getObject();
|
||||
if (object instanceof IJIUnsigned) {
|
||||
return ((IJIUnsigned)object).getValue().intValue();
|
||||
} else if (object instanceof Boolean) {
|
||||
return jiVariant.getObjectAsBoolean() ? 1 : 0;
|
||||
} else if (object instanceof JIString) {
|
||||
return ((JIString)object).getString();
|
||||
} else if (!(object instanceof JIArray)) {
|
||||
if (object instanceof Integer) {
|
||||
return jiVariant.getObject();
|
||||
} else if (e instanceof Short) {
|
||||
} else if (object instanceof Short) {
|
||||
return jiVariant.getObject();
|
||||
} else if (e instanceof Float) {
|
||||
} else if (object instanceof Float) {
|
||||
return jiVariant.getObject();
|
||||
} else {
|
||||
System.err.println(id + "不明类型" + e.getClass());
|
||||
System.err.println(id + "不明类型" + object.getClass());
|
||||
if (jiVariant.getType() == 0) {
|
||||
System.err.println("因类型为emtpy 返回 null");
|
||||
return null;
|
||||
@@ -100,15 +158,15 @@ public class OpcUtl {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Class clazz = ((JIArray) e).getArrayClass();
|
||||
Class<?> clazz = ((JIArray)object).getArrayClass();
|
||||
int[] r;
|
||||
int i;
|
||||
if (JIUnsignedByte.class.isAssignableFrom(clazz)) {
|
||||
JIUnsignedByte[] arg7 = (JIUnsignedByte[]) ((JIUnsignedByte[]) ((JIArray) e).getArrayInstance());
|
||||
r = new int[arg7.length];
|
||||
JIUnsignedByte[] array = (JIUnsignedByte[])((JIUnsignedByte[])((JIArray)object).getArrayInstance());
|
||||
r = new int[array.length];
|
||||
|
||||
for (i = 0; i < arg7.length; ++i) {
|
||||
r[i] = arg7[i].getValue().byteValue();
|
||||
for(i = 0; i < array.length; ++i) {
|
||||
r[i] = array[i].getValue().byteValue();
|
||||
}
|
||||
|
||||
return r;
|
||||
@@ -121,77 +179,141 @@ public class OpcUtl {
|
||||
System.err.println("因类型为null 返回 null");
|
||||
return null;
|
||||
} else {
|
||||
return ((JIArray) e).getArrayInstance();
|
||||
return ((JIArray)object).getArrayInstance();
|
||||
}
|
||||
} else {
|
||||
JIUnsignedShort[] array = (JIUnsignedShort[]) ((JIUnsignedShort[]) ((JIArray) e)
|
||||
.getArrayInstance());
|
||||
JIUnsignedShort[] array = (JIUnsignedShort[])((JIUnsignedShort[])((JIArray)object).getArrayInstance());
|
||||
r = new int[array.length];
|
||||
|
||||
for (i = 0; i < array.length; ++i) {
|
||||
for(i = 0; i < array.length; ++i) {
|
||||
r[i] = array[i].getValue().intValue();
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
}
|
||||
} catch (JIException e) {
|
||||
throw new BadRequestException(e.getMessage());
|
||||
} catch (JIException var7) {
|
||||
// throw new Exception(var7);
|
||||
var7.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static Server getServer(String host, String clsid, String user, String password, String domain)
|
||||
throws WDKException {
|
||||
checkTimeout();
|
||||
Server server = null;
|
||||
|
||||
public static void writeValue(Group group, WriteRequest... requests) throws Exception {
|
||||
try {
|
||||
server = new Server(getConnection(host, clsid, user, password, domain),
|
||||
Executors.newSingleThreadScheduledExecutor());
|
||||
server.connect();
|
||||
return server;
|
||||
} catch (Exception e) {
|
||||
throw new WDKException(e);
|
||||
Map<Item, Integer> write = group.write(requests);
|
||||
boolean is_success = true;
|
||||
StringBuilder message = new StringBuilder();
|
||||
Iterator var5 = write.keySet().iterator();
|
||||
|
||||
while(var5.hasNext()) {
|
||||
Item item = (Item)var5.next();
|
||||
Integer integer = (Integer)write.get(item);
|
||||
if (integer != 0) {
|
||||
if (is_success) {
|
||||
is_success = false;
|
||||
}
|
||||
|
||||
message.append(item.getId());
|
||||
message.append(":error code:");
|
||||
message.append(integer);
|
||||
message.append("; ");
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_success) {
|
||||
throw new Exception(message.toString());
|
||||
}
|
||||
} catch (JIException var8) {
|
||||
throw new Exception(var8);
|
||||
}
|
||||
}
|
||||
|
||||
public static ConnectionInformation getConnection(String host, String clsid, String user, String password,
|
||||
String domain) {
|
||||
ConnectionInformation connection = new ConnectionInformation();
|
||||
connection.setHost(host);
|
||||
connection.setClsid(clsid);
|
||||
connection.setUser(user);
|
||||
connection.setPassword(password);
|
||||
connection.setDomain(domain);
|
||||
return connection;
|
||||
public static void writeValue(Group group, ItemValue... values) throws Exception {
|
||||
try {
|
||||
if (values != null && values.length > 0) {
|
||||
List<WriteRequest> ws = new ArrayList();
|
||||
ItemValue[] var3 = values;
|
||||
int var4 = values.length;
|
||||
|
||||
for(int var5 = 0; var5 < var4; ++var5) {
|
||||
ItemValue value = var3[var5];
|
||||
Item item = group.addItem(value.getItem_code());
|
||||
ws.add(new WriteRequest(item, getVariant(value.getItem_value())));
|
||||
}
|
||||
|
||||
writeValue(group, (WriteRequest[])ws.toArray(new WriteRequest[0]));
|
||||
}
|
||||
|
||||
} catch (AddFailedException | JIException var8) {
|
||||
throw new Exception(var8);
|
||||
}
|
||||
}
|
||||
|
||||
public static String read(String item) throws Exception {
|
||||
System.out.println(item);
|
||||
Server server = getServer("192.168.81.251", "7bc0cc8e-482c-47ca-abdc-0fe7f9c6e729", "administrator", "Huawei@123", "");
|
||||
// String byteItemString = "RD1.RD1.1001.mode";
|
||||
Group group = server.addGroup();
|
||||
Item byteItem = group.addItem(item);
|
||||
ItemState itemState = null;
|
||||
JIVariant value = null;
|
||||
itemState = byteItem.read(true);
|
||||
value = itemState.getValue();
|
||||
String data = OpcUtl.getValue(byteItem, itemState) + "";
|
||||
return data;
|
||||
public static JIVariant getVariant(Object object) throws Exception {
|
||||
if (object instanceof Integer) {
|
||||
return getIntegerVariant((Integer)object);
|
||||
} else if (object instanceof String) {
|
||||
return getStringVariant((String)object);
|
||||
} else if (object instanceof byte[]) {
|
||||
return getByteArrayVariant((byte[])((byte[])object));
|
||||
} else if (object instanceof Byte[]) {
|
||||
return getByteArrayVariant((Byte[])((Byte[])object));
|
||||
} else if (object instanceof Boolean) {
|
||||
return new JIVariant((Boolean)object);
|
||||
} else if (object instanceof int[]) {
|
||||
return getByteArrayVariantxx((int[])((int[])object));
|
||||
} else if (object instanceof Integer[]) {
|
||||
JIArray array = new JIArray((Integer)object, false);
|
||||
JIVariant value = new JIVariant(array);
|
||||
return value;
|
||||
} else if (object instanceof JIVariant) {
|
||||
return (JIVariant)object;
|
||||
} else {
|
||||
throw new Exception("未实现目前支持是int,string,byte[]");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Server server = getServer("192.168.81.251", "7bc0cc8e-482c-47ca-abdc-0fe7f9c6e729", "administrator", "Huawei@123", "");
|
||||
String byteItemString = "RD1.RD1.1001.mode";
|
||||
Group group = server.addGroup();
|
||||
Item byteItem = group.addItem(byteItemString);
|
||||
ItemState itemState = null;
|
||||
JIVariant value = null;
|
||||
System.out.println(byteItem.getId());
|
||||
itemState = byteItem.read(true);
|
||||
System.out.println(itemState.getQuality());
|
||||
System.out.println(getValue(byteItem, itemState));
|
||||
public static JIVariant getByteArrayVariantxx(int[] bytes) {
|
||||
Integer[] byte_Data = new Integer[bytes.length];
|
||||
|
||||
for(int i = 0; i < bytes.length; ++i) {
|
||||
byte_Data[i] = bytes[i];
|
||||
}
|
||||
|
||||
JIArray array = new JIArray(byte_Data, false);
|
||||
JIVariant value = new JIVariant(array);
|
||||
return value;
|
||||
}
|
||||
|
||||
public static JIVariant getIntegerVariant(Integer integer) {
|
||||
return new JIVariant(integer);
|
||||
}
|
||||
|
||||
public static JIVariant getStringVariant(String string) {
|
||||
return new JIVariant(string);
|
||||
}
|
||||
|
||||
public static JIVariant getByteArrayVariant(byte[] bytes) {
|
||||
Byte[] byte_Data = new Byte[bytes.length];
|
||||
|
||||
for(int i = 0; i < bytes.length; ++i) {
|
||||
byte_Data[i] = bytes[i];
|
||||
}
|
||||
|
||||
JIArray array = new JIArray(byte_Data, false);
|
||||
JIVariant value = new JIVariant(array);
|
||||
return value;
|
||||
}
|
||||
|
||||
public static JIVariant getByteArrayVariant(Byte[] bytes) {
|
||||
JIArray array = new JIArray(bytes, false);
|
||||
JIVariant value = new JIVariant(array);
|
||||
return value;
|
||||
}
|
||||
|
||||
static {
|
||||
checkTimeout();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.nl.acs.opc;
|
||||
|
||||
/**
|
||||
* @author ldjun
|
||||
* @version 1.0
|
||||
* @date 2023年02月01日 11:28
|
||||
* @desc desc
|
||||
*/
|
||||
public class ThreadUtl {
|
||||
private ThreadUtl() {
|
||||
}
|
||||
|
||||
public static void sleep(long times) throws RuntimeException {
|
||||
try {
|
||||
Thread.sleep(times);
|
||||
} catch (InterruptedException var3) {
|
||||
throw new RuntimeException(var3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ public class UtgardTutorial1 {
|
||||
public static void main(String[] args) throws Exception {
|
||||
// 连接信息
|
||||
ConnectionInformation ci = new ConnectionInformation();
|
||||
ci.setHost("192.168.46.225");
|
||||
ci.setHost("127.0.0.1");
|
||||
ci.setDomain("");
|
||||
ci.setUser("administrator");
|
||||
ci.setPassword("damien");
|
||||
@@ -33,7 +33,7 @@ public class UtgardTutorial1 {
|
||||
|
||||
// 使用KEPServer的配置
|
||||
ci.setClsid("7BC0CC8E-482C-47CA-ABDC-0FE7F9C6E729"); // KEPServer的注册表ID,可以在“组件服务”里看到
|
||||
final String itemId = "RD1.RD1.A1.mode"; // 项的名字按实际,没有实际PLC,用的模拟器:simulator
|
||||
final String itemId = "RKQ.RKQ.1002.mode"; // 项的名字按实际,没有实际PLC,用的模拟器:simulator
|
||||
// final String itemId = "通道 1.设备 1.标记 1";
|
||||
|
||||
// 启动服务
|
||||
|
||||
@@ -10,4 +10,7 @@ public class WcsConfig {
|
||||
//物料默认类型描述
|
||||
public static String task_container_type_default_desc;
|
||||
|
||||
//重复的指令下发超时 ms
|
||||
public static Integer opc_write_repeat_check = 1000;
|
||||
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ public class opcServerManageServiceImpl implements OpcServerManageService {
|
||||
public List<OpcServerManageDto> queryAll() {
|
||||
//return this.opcServerRepository.queryAll(OpcServerManageDto.class);
|
||||
//OPC表【acs_opc】
|
||||
JSONArray arr = WQLObject.getWQLObject("acs_opc").query().getResultJSONArray(0);
|
||||
JSONArray arr = WQLObject.getWQLObject("acs_opc").query("is_active='1' and is_delete='0'").getResultJSONArray(0);
|
||||
|
||||
return arr.toJavaList(OpcServerManageDto.class);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.nl.modules.logging;
|
||||
|
||||
import ch.qos.logback.core.PropertyDefinerBase;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
// 通过实现logback的PropertyDefinerBase方法,动态定义logback配置中的变量
|
||||
@Component
|
||||
public class DeviceCodeDir extends PropertyDefinerBase {
|
||||
|
||||
String deviceCodeDir = "";
|
||||
public void setPropertyValue(String deviceCode) {
|
||||
deviceCodeDir = deviceCode ;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPropertyValue() {
|
||||
if (deviceCodeDir == ""){
|
||||
deviceCodeDir = "默认";
|
||||
}
|
||||
return "默认";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
server:
|
||||
port: 8010
|
||||
port: 8011
|
||||
#配置数据源
|
||||
spring:
|
||||
datasource:
|
||||
|
||||
@@ -2,7 +2,7 @@ spring:
|
||||
freemarker:
|
||||
check-template-location: false
|
||||
profiles:
|
||||
active: prod
|
||||
active: dev
|
||||
jackson:
|
||||
time-zone: GMT+8
|
||||
data:
|
||||
|
||||
Reference in New Issue
Block a user