123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246 |
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- from modbus_tk import modbus_rtu_over_tcp
- def modbus_rtu_over_tcp_conn(ip, port):
- # ip = "192.168.1.181"
- # port = 1030
- device_id = 1
- function_code = 1
- start_addr = 0
- length = 4
- try:
- master = modbus_rtu_over_tcp.RtuOverTcpMaster(host=ip, port=port)
- # print(f"{ip}:{port} connect success!")
- res = master.execute(device_id, function_code, start_addr, length)
- print(f"{ip}:{port} res = {res}")
- except Exception as e:
- print(f"{ip}:{port} connect failed! {e}")
- modbus_rtu_over_tcp_conn("192.168.1.181", 1030)
- modbus_rtu_over_tcp_conn("192.168.1.182", 1030)
- modbus_rtu_over_tcp_conn("192.168.1.183", 1030)
- modbus_rtu_over_tcp_conn("192.168.1.184", 1030)
- """
- 测试水下云台、水下灯的远程控制开和关的功能
- """
- import socket
- from datetime import datetime
- import time
- def socket_tcp(ip):
- """水下云台"""
- # ip = "192.168.1.78"
- # ip = "192.168.1.79"
- port = 1030
- # data = "48 3A 01 70 01 01 00 00 45 44" # 开
- # data = "48 3A 01 70 01 00 00 00 45 44" # 关
- data = "48 3a 01 53 00 00 00 00 00 00 00 00 d6 45 44" # 状态
-
- """立体剖面"""
- # ip = "192.168.1.253"
- # port = 1030
- # data = "48 3A 01 70 04 01 00 00 45 44" # 开
- # data = "48 3A 01 70 04 00 00 00 45 44" # 关
-
-
- data = bytes.fromhex(data)
- # data = bytes.fromhex(data).decode()
- # print("--------------------------------------------", data)
- conn_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- conn_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许重用本地地址和端口
- conn_sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳维护
- conn_sock.settimeout(10) # 设置超时时间3mins
- try:
- conn_sock.connect((ip, port))
- print("connect success!")
- # data = data.encode(encoding='utf-8')
- conn_sock.send(data)
- res = conn_sock.recv(15).hex()
-
- print(datetime.now(), ip, res)
-
-
- except Exception as e:
- print("connect failed")
- '''
- while 1:
- socket_tcp("192.168.1.78")
- socket_tcp("192.168.1.79")
- socket_tcp("192.168.1.253")
- time.sleep(2)
- '''
- from event_storage import EventStorage
- import time
- from datetime import datetime
- def readReal(lists):
-
- storage = EventStorage()
- while 1:
- real_data_dict = storage.get_real_data(lists)
- print(real_data_dict, datetime.now())
- time.sleep(2)
-
- # readReal(["c785", "c786", "c787"])
- import pymysql
- def execute_sql(sql):
- try:
- conn = pymysql.connect(host="127.0.0.1", user="root", password="zzZZ4144670..", database="centralized_control_db", port=3306, autocommit=True)
- cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
- cursor.execute(sql)
- results = cursor.fetchall()
- cursor.close()
- return results
- except Exception as e:
- print(e)
- return False
- def execute_update_sql(sql):
- try:
- conn = pymysql.connect(host="127.0.0.1", user="root", password="zzZZ4144670..", database="centralized_control_db", port=3306, autocommit=True)
- cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
- cursor.execute(sql)
- conn.commit()
- cursor.close()
- return True
- except pymysql.Error as mysql_error:
- print(mysql_error)
- return False
- def ele():
-
- 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']
- ele_info_sql = "SELECT serial_number,device_id,device_name,io_point_name FROM `data_point_tbl` WHERE `device_name` LIKE '%_electric';"
- sqls = []
- for ele_info in execute_sql(ele_info_sql):
- device_name = ele_info['device_name'] # zfdj_electric
- table = "table_" + device_name # table_zfdj_electric
- c = "c" + str(ele_info['serial_number']) # c151
- n = ele_info['io_point_name'] # Ua
- for m in mouth_list:
- max_sql = f"SELECT `times`, {c} AS {n}_max FROM {table} WHERE `times` LIKE '{m}-%' ORDER BY {c} DESC LIMIT 1;"
- min_sql = f"SELECT `times`, {c} AS {n}_min FROM {table} WHERE `times` LIKE '{m}-%' AND {c}>0 ORDER BY {c} LIMIT 1;"
- # print(max_sql)
- # print(min_sql)
- sqls.append([device_name, max_sql])
- sqls.append([device_name,min_sql])
- print("len(sqls) = ", len(sqls))
- for each in sqls:
- sql = each[1]
- data = execute_sql(sql)
- if len(data) == 1:
- times = data[0]["times"]
- data[0].pop("times")
- for k, v in data[0].items():
- insert_sql = f"INSERT INTO `var` (`device_name`, `name`, `times`, `value`) VALUES ('{each[0]}', '{k}', '{times}', {v});"
- # print(insert_sql)
- res = execute_sql(insert_sql)
- if res is False:
- print(insert_sql)
- # print(times, name, values)
- else:
- print(sql)
- # ele()
- import socket
- import time
- from datetime import datetime
- class SockConnector:
- def __init__(self):
- self.sock_status = False
- self.ip = "192.168.1.78"
- self.port = 1030
- self.data = '483a01530000000000000000d64544'
- def run(self):
- self.sock_conn()
- while True:
- if self.sock_status:
- try:
- self._sock.send(bytes.fromhex(self.data))
- res = self._sock.recv(1024)
- print(f"{datetime.now()} len(res)={len(res)} res={res} | {self._sock} ")
- print(type(self._sock))
- except Exception as e:
- print(f"{datetime.now()} {e} | self.sock_status={self._sock}")
- self.sock_status = False
- else:
- self.sock_reconn()
- time.sleep(10)
- def sock_conn(self):
- try:
- self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许重用本地地址和端口
- self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳维护
- self._sock.settimeout(2) # 设置超时时间
- self._sock.connect((self.ip, self.port))
- self.sock_status = True
- print(f"{datetime.now()} connect success!")
- except Exception as e:
- self.sock_status = False
- print(f"{datetime.now()} connect failed! {e} | {self._sock}")
- self.sock_reconn()
- def sock_reconn(self):
- while self.sock_status is False:
- try:
- self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许重用本地地址和端口
- self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # 在客户端开启心跳维护
- self._sock.settimeout(2) # 设置超时时间
- self._sock.connect((self.ip, self.port))
- self.sock_status = True
- print(f"{datetime.now()} reconnect success!")
- except Exception as e:
- self.sock_status = False
- print(f"{datetime.now()} reconnect failed! {e} | {self._sock}")
- # SockConnector().run()
- # from event_storage import EventStorage
- #
- # storage = EventStorage()
- # real_data_dict = storage.get_real_data(['c785', 'c786', 'c787'])
- # print(real_data_dict)
|