user_openOpc.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import logging
  2. import re
  3. import time
  4. import app
  5. import main
  6. import threading
  7. import log
  8. from typing import List
  9. import OpenOPC
  10. import _thread
  11. import pythoncom
  12. import win32com.client
  13. from win32com.client import gencache
  14. import win32timezone
  15. from win32com.client import Dispatch
  16. from win32com.client import DispatchWithEvents
  17. import pywintypes
  18. pywintypes.datetime = pywintypes.TimeType
  19. class opc_server(threading.Thread):
  20. def __init__(self, threadID, name, counter):
  21. threading.Thread.__init__(self)
  22. self.threadID = threadID
  23. self.name = name
  24. self.counter = counter
  25. self.user_var = app.user_var
  26. self.opcServer = OpenOPC.client()
  27. self.opcaddrlist = app.opc_value.opcaddrlist
  28. self.opc_value = app.opc_value
  29. self.rdkv = self.opc_value.opcrdkv
  30. self.wrkv = self.opc_value.opcwrkv
  31. self.wrstatkv = app.opc_value.opcwrstatkv
  32. self.exit_stat = False
  33. self.log_file = log.log_file
  34. self.log_print = log.log_file
  35. self.readtag_stat = False
  36. self.group = self.opc_value.stationgroup
  37. def OnDataChange(self, TransactionID, NumItems, ClientHandles, ItemValues, Qualities, TimeStamps):
  38. i = 0
  39. print("callback")
  40. while (i < NumItems):
  41. handle = ClientHandles[i]
  42. value = ItemValues[i]
  43. quality = Qualities[i]
  44. time = TimeStamps[i]
  45. print(
  46. 'item:{0} , value:{1} , quality:{2}, time:{3}'.format(self.opcaddrlist[handle - 1], value, quality,
  47. time))
  48. self.rdkv[self.opcaddrlist[handle-1]] = value
  49. i = i + 1
  50. def connect_opc(self, progID: str):
  51. self.opcServer.connect(progID, 'localhost')
  52. self.log_print.logger.info('已连接到opc - [{}]'.format(progID))
  53. return self.opcServer
  54. def disconnect_opc(self, opcServer):
  55. self.log_print.logger.info('opc断开连接')
  56. self.opcServer.Disconnect()
  57. def asyn_write_items(self):
  58. write_list = []
  59. for key, value in self.wrstatkv.items():
  60. if value == True:
  61. write_tuple = (key, self.wrkv[key])
  62. write_list.append(write_tuple)
  63. if len(write_list) > 0:
  64. self.opcServer.write(write_list)
  65. def opc_start(self):
  66. opc_conn = False
  67. wr_stat = True
  68. self.opcServer = OpenOPC.client()
  69. self.opcServer = self.connect_opc('Kepware.KEPServerEX.V6')
  70. opc_conn = True
  71. try:
  72. while self.exit_stat == False:
  73. if self.readtag_stat == False:
  74. self.readtag_stat = True
  75. count = 0
  76. listvalue = self.opcServer.read(self.opcaddrlist, include_error=True)
  77. with main.threadlock:
  78. for tup in listvalue:
  79. if tup[2] == 'Good':
  80. self.rdkv[tup[0]] = tup[1]
  81. elif tup[2] == 'Error' or tup[2] == 'Bad':
  82. count = count + 1
  83. if count >= len(listvalue):
  84. self.user_var.opc_conn_stat = "PLC未连接"
  85. else:
  86. self.user_var.opc_conn_stat = "PLC已连接"
  87. self.readtag_stat = False
  88. with main.threadlock:
  89. try:
  90. self.asyn_write_items()
  91. wr_stat = True
  92. except Exception as e:
  93. if wr_stat == True:
  94. wr_stat = False
  95. self.log_file.logger.error('opc写异常: {0}'.format(e), exc_info=True,
  96. stack_info=True)
  97. break
  98. time.sleep(0.01)
  99. except Exception as e:
  100. self.log_file.logger.error('opc工作异常: {0}'.format(e), exc_info=True, stack_info=True)
  101. finally:
  102. self.opcServer.close()
  103. if(opc_conn==False):
  104. self.user_var.opc_conn_stat = "OPC服务器未连接"
  105. def exit(self):
  106. self.exit_stat = True
  107. def run(self):
  108. # pythoncom.CoInitialize()
  109. while self.exit_stat == False:
  110. time.sleep(1)
  111. self.opc_start()
  112. print("opc进程结束!")