main.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import asyncio
  2. import json
  3. import redis
  4. import logging
  5. from flask import Flask, request, render_template
  6. from asyncua import Client
  7. from datetime import datetime
  8. class SubHandler(object):
  9. r = None
  10. pool = None
  11. config = None
  12. def __init__(self):
  13. self.config = get_conf()
  14. redis_conf = self.config['redis_conf']
  15. ip = redis_conf['ip']
  16. self.pool = redis.ConnectionPool(host=ip, password='')
  17. self.r = redis.Redis(connection_pool=self.pool)
  18. async def datachange_notification(self, node, val, data):
  19. print("Python: New data change event", node, val)
  20. def event_notification(self, event):
  21. print("Python: New event", event)
  22. app = Flask(__name__)
  23. # route
  24. @app.route("/get/", methods=['GET', 'POST'])
  25. def get():
  26. # 矿名key
  27. sys_key = request.values.get('sys_key')
  28. # 自动化系统key
  29. sys_name = request.values.get('sys_name')
  30. # 参数判断
  31. if sys_key is None or len(sys_key) == 0 or sys_name is None or len(sys_name) == 0:
  32. return "参数错误"
  33. # 获取对应配置
  34. base_conf = get_conf()
  35. # 获取opc服务地址
  36. sys_url = base_conf["server_url"]
  37. # 获取配置文件名
  38. sys_file_path = base_conf['sys_conf'][sys_key]['path']
  39. sys_file_name = base_conf['sys_conf'][sys_key]['file_name']
  40. # 获取点位数组
  41. point_conf = get_conf(sys_file_name, sys_file_path)
  42. # 取到配置
  43. point_base_dic = point_conf['sys_point']
  44. point_arr = []
  45. # 取点位数据
  46. # print(point_base_dic)
  47. for group in point_base_dic:
  48. for item in point_base_dic[group]:
  49. point_arr.append(item['key'])
  50. # 根据服务地址获取Opc数据
  51. data = asyncio.run(get_opc_data(sys_url, point_arr, 2))
  52. get_request_ip()
  53. for group in point_base_dic:
  54. for item in point_base_dic[group]:
  55. try:
  56. key = item['key']
  57. point_val = data[key]
  58. item['val'] = point_val
  59. finally:
  60. continue
  61. return point_base_dic
  62. def get_conf(file_name="config.json", file_path="./config"):
  63. path = f"{file_path}/{file_name}"
  64. with open(path, "r", encoding="utf-8") as f:
  65. content = json.load(f)
  66. f.close()
  67. return content
  68. async def get_opc_data(sys_url, point_arr, ns=2):
  69. if sys_url is None or point_arr is None:
  70. return
  71. url = sys_url
  72. async with Client(url=url) as client:
  73. handler = SubHandler()
  74. r = handler.r
  75. i = 0
  76. result_arr = {}
  77. print(datetime.now().strftime('Start_time:%Y-%m-%d %H:%M:%S.%f'))
  78. while i < len(point_arr):
  79. node = f"ns={ns};s={point_arr[i]}"
  80. tag = client.get_node(node)
  81. sub = await client.create_subscription(500, handler)
  82. value = None
  83. try:
  84. value = await tag.read_value()
  85. #redis值
  86. r.set(str(node), str(value))
  87. #获取点位key
  88. arr_key = node.split("=")
  89. result_arr[arr_key[2]] = value
  90. # print(f"tag1 is: {tag} with value {value} ")
  91. i += 1
  92. if i == len(point_arr):
  93. print("Get Data Success")
  94. finally:
  95. i += 1
  96. continue
  97. print(datetime.now().strftime('End_time:%Y-%m-%d %H:%M:%S.%f'))
  98. return result_arr
  99. def get_request_ip():
  100. ip = request.remote_addr
  101. logging.debug(ip)
  102. if __name__ == '__main__':
  103. app.run()