get_opc_data.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import redis
  2. import logging
  3. from asyncua import Client
  4. from datetime import datetime
  5. from get_config import get_conf
  6. # 连接redis服务
  7. def get_redis_conn():
  8. # 获取配置
  9. config = get_conf()
  10. # 创建redis对象
  11. try:
  12. redis_conf = config['redis_conf']
  13. redis_ip = redis_conf['ip']
  14. pool = redis.ConnectionPool(host=redis_ip, password='')
  15. redis_conn = redis.Redis(connection_pool=pool)
  16. except BaseException as e:
  17. print(e)
  18. print("异常,redis连接错误!")
  19. return redis_conn
  20. # 根据服务、和点位获取OPC数据
  21. async def get_opc_data(sys_url, point_arr, ns=2):
  22. if sys_url is None or point_arr is None:
  23. return
  24. # 获取配置
  25. # config = get_conf()
  26. # 获取redis
  27. redis_conn = get_redis_conn()
  28. # 连接opc服务
  29. try:
  30. print("正在连接OPCUA服务...")
  31. async with Client(url=sys_url) as client:
  32. i = 0
  33. result_arr = {}
  34. print(datetime.now().strftime('Start_time:%Y-%m-%d %H:%M:%S.%f'))
  35. while i < len(point_arr):
  36. try:
  37. node = f"ns={ns};s={point_arr[i]}"
  38. tag = client.get_node(node)
  39. value = await tag.read_value()
  40. # redis值
  41. redis_conn.set(str(node), str(value))
  42. arr_key = node.split("=")
  43. result_arr[arr_key[2]] = value
  44. finally:
  45. i += 1
  46. continue
  47. print(datetime.now().strftime('End_time:%Y-%m-%d %H:%M:%S.%f'))
  48. return result_arr
  49. except KeyError as e:
  50. # logging.warning(e.args)
  51. logging.warning("服务连接错误!")
  52. return "服务连接错误!"
  53. except BaseException as e:
  54. print(e)
  55. return "服务连接错误!"
  56. # 将点位值赋予json(递归,适配多级json)
  57. def point_data_to_arr(point_data, data_arr=[]):
  58. # 未获取到值返回空数组
  59. if len(data_arr) == 0:
  60. return point_data
  61. point_dict = {}
  62. if isinstance(point_data, dict):
  63. for key, val in point_data.items():
  64. data = point_data[key]
  65. if 'val' == key:
  66. point_key = point_dict['key']
  67. if point_key in data_arr:
  68. point_dict['val'] = data_arr[point_key]
  69. else:
  70. point_dict['val'] = ""
  71. elif isinstance(val, str):
  72. point_dict[key] = point_data[key]
  73. else:
  74. test = point_data_to_arr(data, data_arr)
  75. point_dict[key] = test
  76. elif isinstance(point_data, list):
  77. point_arr = []
  78. for i in range(len(point_data)):
  79. data = point_data[i]
  80. data_dic = point_data_to_arr(data, data_arr)
  81. point_arr.append(data_dic)
  82. # point_arr[i] =
  83. return point_arr
  84. return point_dict