test.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. from modbus_tk import modbus_rtu_over_tcp
  4. def modbus_rtu_over_tcp_conn(ip, port):
  5. # ip = "192.168.1.181"
  6. # port = 1030
  7. device_id = 1
  8. function_code = 1
  9. start_addr = 0
  10. length = 4
  11. try:
  12. master = modbus_rtu_over_tcp.RtuOverTcpMaster(host=ip, port=port)
  13. # print(f"{ip}:{port} connect success!")
  14. res = master.execute(device_id, function_code, start_addr, length)
  15. print(f"{ip}:{port} res = {res}")
  16. except Exception as e:
  17. print(f"{ip}:{port} connect failed! {e}")
  18. modbus_rtu_over_tcp_conn("192.168.1.181", 1030)
  19. modbus_rtu_over_tcp_conn("192.168.1.182", 1030)
  20. modbus_rtu_over_tcp_conn("192.168.1.183", 1030)
  21. modbus_rtu_over_tcp_conn("192.168.1.184", 1030)
  22. """
  23. 测试水下云台、水下灯的远程控制开和关的功能
  24. """
  25. import socket
  26. from datetime import datetime
  27. import time
  28. def socket_tcp(ip):
  29. """水下云台"""
  30. # ip = "192.168.1.78"
  31. # ip = "192.168.1.79"
  32. port = 1030
  33. # data = "48 3A 01 70 01 01 00 00 45 44" # 开
  34. # data = "48 3A 01 70 01 00 00 00 45 44" # 关
  35. data = "48 3a 01 53 00 00 00 00 00 00 00 00 d6 45 44" # 状态
  36. """立体剖面"""
  37. # ip = "192.168.1.253"
  38. # port = 1030
  39. # data = "48 3A 01 70 04 01 00 00 45 44" # 开
  40. # data = "48 3A 01 70 04 00 00 00 45 44" # 关
  41. data = bytes.fromhex(data)
  42. # data = bytes.fromhex(data).decode()
  43. # print("--------------------------------------------", data)
  44. conn_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  45. conn_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许重用本地地址和端口
  46. conn_sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳维护
  47. conn_sock.settimeout(10) # 设置超时时间3mins
  48. try:
  49. conn_sock.connect((ip, port))
  50. print("connect success!")
  51. # data = data.encode(encoding='utf-8')
  52. conn_sock.send(data)
  53. res = conn_sock.recv(15).hex()
  54. print(datetime.now(), ip, res)
  55. except Exception as e:
  56. print("connect failed")
  57. '''
  58. while 1:
  59. socket_tcp("192.168.1.78")
  60. socket_tcp("192.168.1.79")
  61. socket_tcp("192.168.1.253")
  62. time.sleep(2)
  63. '''
  64. from event_storage import EventStorage
  65. import time
  66. from datetime import datetime
  67. def readReal(lists):
  68. storage = EventStorage()
  69. while 1:
  70. real_data_dict = storage.get_real_data(lists)
  71. print(real_data_dict, datetime.now())
  72. time.sleep(2)
  73. # readReal(["c785", "c786", "c787"])
  74. import pymysql
  75. def execute_sql(sql):
  76. try:
  77. conn = pymysql.connect(host="127.0.0.1", user="root", password="zzZZ4144670..", database="centralized_control_db", port=3306, autocommit=True)
  78. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  79. cursor.execute(sql)
  80. results = cursor.fetchall()
  81. cursor.close()
  82. return results
  83. except Exception as e:
  84. print(e)
  85. return False
  86. def execute_update_sql(sql):
  87. try:
  88. conn = pymysql.connect(host="127.0.0.1", user="root", password="zzZZ4144670..", database="centralized_control_db", port=3306, autocommit=True)
  89. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  90. cursor.execute(sql)
  91. conn.commit()
  92. cursor.close()
  93. return True
  94. except pymysql.Error as mysql_error:
  95. print(mysql_error)
  96. return False
  97. def ele():
  98. mouth_list = ['2021-05', '2021-06', '2021-07', '2021-08', '2021-09', '2021-10', '2021-11', '2021-12', '2022-01', '2022-02', '2022-03', '2022-04', '2022-05', '2022-06', '2022-07', '2022-08', '2022-09']
  99. ele_info_sql = "SELECT serial_number,device_id,device_name,io_point_name FROM `data_point_tbl` WHERE `device_name` LIKE '%_electric';"
  100. sqls = []
  101. for ele_info in execute_sql(ele_info_sql):
  102. device_name = ele_info['device_name'] # zfdj_electric
  103. table = "table_" + device_name # table_zfdj_electric
  104. c = "c" + str(ele_info['serial_number']) # c151
  105. n = ele_info['io_point_name'] # Ua
  106. for m in mouth_list:
  107. max_sql = f"SELECT `times`, {c} AS {n}_max FROM {table} WHERE `times` LIKE '{m}-%' ORDER BY {c} DESC LIMIT 1;"
  108. min_sql = f"SELECT `times`, {c} AS {n}_min FROM {table} WHERE `times` LIKE '{m}-%' AND {c}>0 ORDER BY {c} LIMIT 1;"
  109. # print(max_sql)
  110. # print(min_sql)
  111. sqls.append([device_name, max_sql])
  112. sqls.append([device_name,min_sql])
  113. print("len(sqls) = ", len(sqls))
  114. for each in sqls:
  115. sql = each[1]
  116. data = execute_sql(sql)
  117. if len(data) == 1:
  118. times = data[0]["times"]
  119. data[0].pop("times")
  120. for k, v in data[0].items():
  121. insert_sql = f"INSERT INTO `var` (`device_name`, `name`, `times`, `value`) VALUES ('{each[0]}', '{k}', '{times}', {v});"
  122. # print(insert_sql)
  123. res = execute_sql(insert_sql)
  124. if res is False:
  125. print(insert_sql)
  126. # print(times, name, values)
  127. else:
  128. print(sql)
  129. # ele()
  130. import socket
  131. import time
  132. from datetime import datetime
  133. class SockConnector:
  134. def __init__(self):
  135. self.sock_status = False
  136. self.ip = "192.168.1.78"
  137. self.port = 1030
  138. self.data = '483a01530000000000000000d64544'
  139. def run(self):
  140. self.sock_conn()
  141. while True:
  142. if self.sock_status:
  143. try:
  144. self._sock.send(bytes.fromhex(self.data))
  145. res = self._sock.recv(1024)
  146. print(f"{datetime.now()} len(res)={len(res)} res={res} | {self._sock} ")
  147. print(type(self._sock))
  148. except Exception as e:
  149. print(f"{datetime.now()} {e} | self.sock_status={self._sock}")
  150. self.sock_status = False
  151. else:
  152. self.sock_reconn()
  153. time.sleep(10)
  154. def sock_conn(self):
  155. try:
  156. self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  157. self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许重用本地地址和端口
  158. self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳维护
  159. self._sock.settimeout(2) # 设置超时时间
  160. self._sock.connect((self.ip, self.port))
  161. self.sock_status = True
  162. print(f"{datetime.now()} connect success!")
  163. except Exception as e:
  164. self.sock_status = False
  165. print(f"{datetime.now()} connect failed! {e} | {self._sock}")
  166. self.sock_reconn()
  167. def sock_reconn(self):
  168. while self.sock_status is False:
  169. try:
  170. self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  171. self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许重用本地地址和端口
  172. self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳维护
  173. self._sock.settimeout(2) # 设置超时时间
  174. self._sock.connect((self.ip, self.port))
  175. self.sock_status = True
  176. print(f"{datetime.now()} reconnect success!")
  177. except Exception as e:
  178. self.sock_status = False
  179. print(f"{datetime.now()} reconnect failed! {e} | {self._sock}")
  180. # SockConnector().run()
  181. # from event_storage import EventStorage
  182. #
  183. # storage = EventStorage()
  184. # real_data_dict = storage.get_real_data(['c785', 'c786', 'c787'])
  185. # print(real_data_dict)