Bladeren bron

shuizhi connector update & history search by page

liqudong 3 jaren geleden
bovenliggende
commit
940f1c7ded
7 gewijzigde bestanden met toevoegingen van 187 en 585 verwijderingen
  1. 3 2
      config.json
  2. 18 0
      configuration.py
  3. 90 236
      connectors/shuizhi_tcp_connector.py
  4. 0 321
      connectors/shuizhi_tcp_connector_old.py
  5. 5 0
      event_storage.py
  6. 55 24
      gateway.py
  7. 16 2
      hard_disk_storage.py

+ 3 - 2
config.json

@@ -2,11 +2,12 @@
   "hardDiskdataBase": {
     "ip": "127.0.0.1",
     "username": "root",
-    "password": "sea12345",
+    "password": "sA3b20GdDAfq/UViWnJ63g==",
     "dataBaseName": "shucai"
   },
   "memoryDatabase": {
     "ip": "127.0.0.1",
     "port": 6379
-  }
+  },
+  "code": "18srfpUIeKFw+z/itQkUHbbi5nEh+4iF"
 }

+ 18 - 0
configuration.py

@@ -1,6 +1,20 @@
 import json
 import os
 import sys
+import base64
+
+import pyDes
+
+
+def DesEncrypt(string):
+    Des_Key = "u357asdu"  # Key
+    Des_IV = "u357asdu"  # 自定IV向量
+    string = base64.b64decode(string)
+    k = pyDes.des(Des_Key, pyDes.CBC, Des_IV, pad=None,
+                  padmode=pyDes.PAD_PKCS5)
+    decryptStr = k.decrypt(string)
+    # print(decryptStr)
+    return decryptStr
 
 
 class Configuration:
@@ -16,6 +30,10 @@ class Configuration:
             config_file_path = 'config.json'
         with open(config_file_path) as json_file:
             config = json.load(json_file)
+        # 解密密码和序列号
+        config['hardDiskdataBase']['password'] = DesEncrypt(
+            config['hardDiskdataBase']['password']).decode('utf-8')
+        # config['code'] = DesEncrypt(config['code']).decode('utf-8')
         return config
 
     def set_config(self):

+ 90 - 236
connectors/shuizhi_tcp_connector.py

@@ -10,6 +10,8 @@ import socket
 from connector import Connector
 from event_storage import EventStorage
 from log import Log
+from binascii import *
+from crcmod import *
 
 sendFlag = 0
 
@@ -17,6 +19,8 @@ sendFlag = 0
 class ShuizhiTcpConnector(Connector, threading.Thread):
     def __init__(self, name, config, converter):
         super().__init__()
+        self._param_id = {}
+        self._len_param = None
         self.__log = Log()
         self.__sock = None
         self.__connected = False
@@ -30,6 +34,7 @@ class ShuizhiTcpConnector(Connector, threading.Thread):
         self.setName(name)
         self.__last_seve_time = 0
         self.__data_point_config = self.__storager.get_station_info(name)
+        self._storage = EventStorage()
         # for i in self.__data_point_config:
         #     print(i)
 
@@ -47,6 +52,7 @@ class ShuizhiTcpConnector(Connector, threading.Thread):
         try:
             self.__sock.connect((self.__ip, self.__port))
             self.__log.info(f'Connect to [{self.get_name()}]:[{self.__ip}]:[{self.__port}] success !')
+            print(f'Connect to [{self.get_name()}]:[{self.__ip}]:[{self.__port}] success !')
             self.__connected = True
         except socket.error as e:
             self.__log.info(f'Connect to [{self.get_name()}]:[{self.__ip}]:[{self.__port}] failed:{e} !!!')
@@ -64,6 +70,7 @@ class ShuizhiTcpConnector(Connector, threading.Thread):
                 self.__log.info(f'Reconnect to [{self.get_name()}]:[{self.__ip}]:[{self.__port}] success !')
                 break
             except Exception as e:
+                print("e=", e)
                 print("Continue reconnect in 5s..")
                 self.__log.info(
                     f'Reconnect to [{self.get_name()}]:[{self.__ip}]:[{self.__port}] failed:{e} !!! Continue reconnect in 5s..')
@@ -94,48 +101,52 @@ class ShuizhiTcpConnector(Connector, threading.Thread):
     def run(self):
         self.__connect()
         self.__connected = True
-        dissolved_oxygen = bytes.fromhex('02 03 00 25 00 08 55 F4')  # 读溶解氧发送指令,接收数据长度:21
-        temperature = bytes.fromhex('01 03 15 4A 00 02 E1 D1')  # 读温度和盐度发送指令,接收数据长度:9
-        salinity = bytes.fromhex('01 03 15 97 00 04 F1 E9')  # 读温度和盐度发送指令,接收数据长度:13
-        PH = bytes.fromhex('01 03 01 D9 00 0A 15 CA')  # 读PH发送指令,数据接收长度:25
-        chlorophyll = bytes.fromhex('01 03 16 A8 00 07 81 A0')  # 读叶绿素发送指令,接收数据长度:19
-        depth = bytes.fromhex('01 03 15 66 00 03 E1 D8')  # 读深度发送指令,接收数据长度:11
-        turbidity = bytes.fromhex('01 03 15 F2 00 05 20 36')  # 读浊度发送指令,接收数据长度:15
+        # dissolved_oxygen = bytes.fromhex('01 03 15 CF 00 05 B1 FA')    # 读溶解氧发送指令,接收数据:
+        # temperature = bytes.fromhex('01 03 15 4A 00 05 A0 13')  # 读温度发送指令,接收数据:01 03 0A 41 C0 BC 1C 00 00 00 01 00 01 61 42
+        # salinity = bytes.fromhex('01 03 15 97 00 05 30 29')     # 读盐度发送指令,接收数据:01 03 0A 00 00 00 00 00 00 00 61 00 0C 75 6D
+        # PH = bytes.fromhex('01 03 15 BA 00 05 A0 20')           # 读 PH 发送指令,接收数据:01 03 0A 40 F9 2B 79 00 00 00 91 00 11 72 BB
+        # chlorophyll = bytes.fromhex('01 03 16 A8 00 05 00 61')  # 读叶绿素发送指令,接收数据:01 03 0A 00 00 00 00 00 00 01 01 00 33 34 9F
+        # depth = bytes.fromhex('01 03 15 66 00 05 61 DA')        # 读深度发送指令,接收数据:01 03 0A 42 08 1B F4 00 00 00 26 00 05 34 D0
+
+        # 获取需要读取的参数的相关信息
+        param_list = self._storage.get_in_situ_command()
+        depth_index = None
+        depth = ""
+        # ①判断参数中是否有 深度, ②处理 寄存器偏移量 的位置
+        for each in param_list:
+            self._param_id[each["parameter_id"]] = each["name"]
+            if each["name"] == "深度":
+                crc_check = crc16Add(each['station_code'] + each["function_code"] + dec_to_hex(each["address"]) + "0005")
+                depth = bytes.fromhex(crc_check)
+                depth_index = param_list.index(each)
+        if depth_index is not None:
+            param_list.pop(depth_index)
+        instruct_list = []
+        if len(depth) > 0:
+            for each in param_list:
+                crc_check = crc16Add(each['station_code'] + each["function_code"] + dec_to_hex(each["address"]) + "0005")
+                instruct_list.append(depth)
+                instruct_list.append(bytes.fromhex(crc_check))
+            instruct_list.append(depth)
+        else:
+            for each in param_list:
+                crc_check = crc16Add(each['station_code'] + each["function_code"] + dec_to_hex(each["address"]) + "0005")
+                instruct_list.append(bytes.fromhex(crc_check))
+        self._len_param = len(instruct_list)
+
+        for i in instruct_list:
+            print(i)
+
         # 创建接收线程
         threading.Thread(target=self.SocketReceive, args=(self.__sock,)).start()
-
+        # 循环发送指令
         while 1:
             time.sleep(0.2)
             if not self.__connected:
                 continue
             try:
-
-                if sendFlag == 0:
-                    self.__sock.send(depth)
-                elif sendFlag == 1:
-                    self.__sock.send(dissolved_oxygen)
-                elif sendFlag == 2:
-                    self.__sock.send(depth)
-                elif sendFlag == 3:
-                    self.__sock.send(temperature)
-                elif sendFlag == 4:
-                    self.__sock.send(depth)
-                elif sendFlag == 5:
-                    self.__sock.send(salinity)
-                elif sendFlag == 6:
-                    self.__sock.send(depth)
-                elif sendFlag == 7:
-                    self.__sock.send(PH)
-                elif sendFlag == 8:
-                    self.__sock.send(depth)
-                elif sendFlag == 9:
-                    self.__sock.send(chlorophyll)
-                elif sendFlag == 10:
-                    self.__sock.send(depth)
-                elif sendFlag == 11:
-                    self.__sock.send(turbidity)
-                elif sendFlag == 12:
-                    self.__sock.send(depth)
+                # print("发送", instruct_list[sendFlag], "....")
+                self.__sock.send(instruct_list[sendFlag])
             except Exception as e:
                 self.__connected = False
                 self.__reconnect()
@@ -143,10 +154,7 @@ class ShuizhiTcpConnector(Connector, threading.Thread):
             if self.__stopped:
                 break
 
-    # 水质解析器
     def save_format_data(self, t, name):
-        if name == '深度':
-            print(name, t, time.strftime('%Y-%m-%d %H:%M:%S'))
         data = {}
         for index in self.__data_point_config:
             if index["io_point_name"] == name:
@@ -154,213 +162,34 @@ class ShuizhiTcpConnector(Connector, threading.Thread):
                     t = t / index['divisor']
                 if index['offset'] is not None:
                     t = t - index['offset']
-                if index['low_limit'] is not None and index['up_limit'] is not None and index['low_limit'] <= t <= \
-                        index['up_limit']:
-                    data = {'c' + str(index['serial_number']): t}
-                    self.__storager.real_time_data_storage(data)
+                data = {'c' + str(index['serial_number']): t}
+                self.__storager.real_time_data_storage(data)
+        # print(data)
 
     def SocketReceive(self, clientSocket):
         global sendFlag
         ''' Socket 接收线程。'''
-        # global socket_flag, socket_msg  # 通过全局变量,让外部可以控制线程的运行,也可以处理信息
-
         while 1:
-            time.sleep(0.5)
+            time.sleep(0.2)
             # print(sendFlag, time.time())
-            # 深度
-            if sendFlag == 0:
-                try:
-                    # print(clientSocket)
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:
-                    # print("深度1", e)
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('----深度:', t, 'res:', len(res), 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 1
-            # 溶解氧
-            if sendFlag == 1:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                # print(time.strftime('%Y-%m-%d %H:%M:%S'))
-                if length == 21:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('溶解氧:', t, 'res:', len(res), 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "溶解氧")
-                    sendFlag = 2
-            # 深度
-            if sendFlag == 2:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('深度:', t, 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 3
-            # 温度
-            if sendFlag == 3:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 9:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('温度:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "温度")
-                    sendFlag = 4
-            # 深度
-            if sendFlag == 4:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('深度:', t, 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 5
-            # 盐度
-            if sendFlag == 5:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 13:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('盐度:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "盐度")
-                    sendFlag = 6
-            # 深度
-            if sendFlag == 6:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('深度:', t, 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 7
-            # PH
-            if sendFlag == 7:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 25:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('PH:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "PH")
-                    sendFlag = 8
-            # 深度
-            if sendFlag == 8:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('深度:', t, 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 9
-            # 叶绿素
-            if sendFlag == 9:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 19:
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('叶绿素:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "叶绿素")
-                    sendFlag = 10
-            # 深度
-            if sendFlag == 10:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('深度:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 11
-            # 浊度
-            if sendFlag == 11:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 15:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('浊度:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "浊度")
-                    sendFlag = 12
-            # 深度
-            if sendFlag == 12:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
+            try:
+                recvData = clientSocket.recv(1024)
+                # print("recvData=", recvData)
+            except Exception as e:
+                print("e=", e)
+                break
+            length = len(recvData)
+            if length == 15:
                 fmt = str(length) + 'B'
                 res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    self.save_format_data(t, "深度")
+                t = int_to_hex(res[3], res[4], res[5], res[6])
+                print(time.strftime('%Y-%m-%d %H:%M:%S'), self._param_id[res[12]], "   t=", t)
+                self.save_format_data(t, self._param_id[res[12]])
+                if sendFlag == self._len_param - 1:
+                    print("-------------------")
                     sendFlag = 0
+                else:
+                    sendFlag = sendFlag + 1
         clientSocket.close()
         self.__log.info("Client closed.")
 
@@ -377,3 +206,28 @@ def int_to_hex(a1, a2, b1, b2):
     t = t1 + t2
     t = struct.unpack('>f', binascii.unhexlify(t.replace(' ', '')))[0]
     return t
+
+
+def dec_to_hex(num):
+    """
+    十进制转十六进制
+    """
+    t = hex(num)
+    t = (6 - len(t)) * "0" + t[2:]
+    return t
+
+
+# CRC16-MODBUS
+def crc16Add(read):
+    """
+    生成CRC16校验位
+    """
+    crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
+    data = read.replace(" ", "")
+    read_crcout = hex(crc16(unhexlify(data))).upper()
+    str_list = list(read_crcout)
+    if len(str_list) < 6:
+        str_list.insert(2, '0' * (6 - len(str_list)))  # 位数不足补0
+    crc_data = "".join(str_list)
+    read = read.strip() + '' + crc_data[4:] + '' + crc_data[2:4]
+    return read

+ 0 - 321
connectors/shuizhi_tcp_connector_old.py

@@ -1,321 +0,0 @@
-"""
-@Date  :2021/5/21/00219:10:57
-@Desc  :
-"""
-import binascii
-import threading
-import time
-import struct
-import socket
-from connector import Connector
-from event_storage import EventStorage
-from log import Log
-
-sendFlag = 0
-
-
-class ShuizhiTcpConnector(Connector, threading.Thread):
-    def __init__(self, name, config, converter):
-        super().__init__()
-        self.__log = Log()
-        self.__sock = None
-        self.__connected = False
-        self.__stopped = False
-        self.__size = 1024
-        self.__ip = config['ip']
-        self.__port = config['port']
-        self.__converter = converter
-        self.__storager = EventStorage()
-        self.__save_frequency = config['save_frequency']
-        self.setName(name)
-        self.__last_seve_time = 0
-        self.__data_point_config = self.__storager.get_station_info(name)
-        # for i in self.__data_point_config:
-        #     print(i)
-
-    def open(self):
-        self.__stopped = False
-        self.start()
-
-    # 建立socket连接
-    def __connect(self):
-        if self.__sock:
-            self.close()
-        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)  # 在客户端开启心跳维护
-        try:
-            self.__sock.connect((self.__ip, self.__port))
-            self.__log.info(f'Connect to [{self.get_name()}]:[{self.__ip}]:[{self.__port}] success !')
-            self.__connected = True
-        except socket.error as e:
-            self.__log.info(f'Connect to [{self.get_name()}]:[{self.__ip}]:[{self.__port}] failed:{e} !!!')
-            self.__connected = False
-            self.__reconnect()
-
-    def __reconnect(self):
-        while True:
-            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.connect((self.__ip, self.__port))
-                self.__connected = True
-                self.__log.info(f'Reconnect to [{self.get_name()}]:[{self.__ip}]:[{self.__port}] success !')
-                break
-            except Exception as e:
-                print("Continue reconnect in 5s..")
-                self.__log.info(
-                    f'Reconnect to [{self.get_name()}]:[{self.__ip}]:[{self.__port}] failed:{e} !!! Continue reconnect in 5s..')
-                self.__connected = False
-                time.sleep(5)
-
-    def close(self):
-        """Close the connection with the TCP Slave"""
-        if self.__sock:
-            self.__sock.close()
-            self.__stopped = True
-            self.__sock = None
-            self.__connected = False
-            return None
-
-    def get_name(self):
-        return self.name
-
-    def is_connected(self):
-        return self.__connected
-
-    def send_command(self, command_list):
-        pass
-
-    def command_polling(self):
-        pass
-
-    def run(self):
-        self.__connect()
-        self.__connected = True
-        # dissolved_oxygen = bytes.fromhex('01030025000AD406')  # 读溶解氧发送指令,接收数据长度:25
-        dissolved_oxygen = bytes.fromhex('010315CF0005B1FA')  # 读溶解氧发送指令,接收数据长度:15
-        temperature_salinity = bytes.fromhex('010300FF001AF431')  # 读温度和盐度发送指令,接收数据长度:52 + 5 = 57
-        PH = bytes.fromhex('010301D90002140C')  # 读PH发送指令,数据接收长度:4 + 5 = 9
-        # chlorophyll = bytes.fromhex('010316A1000411A3')  # 读叶绿素发送指令,接收数据长度:8 + 5 = 13
-        chlorophyll = bytes.fromhex('010316A80004C1A1')  # 读叶绿素发送指令,接收数据长度:8 + 5 = 13
-
-        # depth = bytes.fromhex('0103046F0012F4EA')  # 读深度发送指令,接收数据长度:36 + 5 = 41
-        # depth = bytes.fromhex('0103155100035016')  # 读深度发送指令,接收数据长度:6 + 5 = 11
-        depth = bytes.fromhex('010315660003E1D8')  # 读深度发送指令,接收数据长度:6 + 5 = 11
-        # 01 03 06 40 BA FD 82 00 00 67 EA 返回数据测试
-
-        # 创建接收线程
-        threading.Thread(target=self.SocketReceive, args=(self.__sock,)).start()
-
-        while 1:
-            time.sleep(0.2)
-            if not self.__connected:
-                continue
-            try:
-                if sendFlag == 0:
-                    self.__sock.send(depth)
-                elif sendFlag == 1:
-                    self.__sock.send(dissolved_oxygen)
-                elif sendFlag == 2:
-                    self.__sock.send(depth)
-                elif sendFlag == 3:
-                    self.__sock.send(temperature_salinity)
-                elif sendFlag == 4:
-                    self.__sock.send(depth)
-                elif sendFlag == 5:
-                    self.__sock.send(PH)
-                elif sendFlag == 6:
-                    self.__sock.send(depth)
-                elif sendFlag == 7:
-                    self.__sock.send(chlorophyll)
-                elif sendFlag == 8:
-                    self.__sock.send(depth)
-            except Exception as e:
-                self.__connected = False
-                self.__reconnect()
-                threading.Thread(target=self.SocketReceive, args=(self.__sock,)).start()
-            if self.__stopped:
-                break
-
-    # 水质解析器
-    def save_format_data(self, t, name):
-        data = {}
-        for index in self.__data_point_config:
-            if index["io_point_name"] == name:
-                if index['divisor'] is not None:
-                    t = t / index['divisor']
-                if index['offset'] is not None:
-                    t = t - index['offset']
-                if index['low_limit'] is not None and index['up_limit'] is not None and index['low_limit'] <= t <= \
-                        index['up_limit']:
-                    data = {'c' + str(index['serial_number']): t}
-                    self.__storager.real_time_data_storage(data)
-        print(data)
-
-    def SocketReceive(self, clientSocket):
-        global sendFlag
-        ''' Socket 接收线程。'''
-        # global socket_flag, socket_msg  # 通过全局变量,让外部可以控制线程的运行,也可以处理信息
-
-        while 1:
-            time.sleep(0.5)
-            # print(sendFlag, time.time())
-            # 深度
-            if sendFlag == 0:
-                try:
-                    # print(clientSocket)
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:
-                    # print("深度1", e)
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    print('----深度:', t, 'res:', len(res), 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 1
-            # 溶解氧
-            if sendFlag == 1:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                # print(time.strftime('%Y-%m-%d %H:%M:%S'))
-                if length == 15:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    print('溶解氧:', t, 'res:', len(res), 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "溶解氧")
-                    sendFlag = 2
-            # 深度
-            if sendFlag == 2:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    print('深度:', t, 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 3
-            # 温度、盐度
-            if sendFlag == 3:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 57:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    print('温度:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "温度")
-
-                    q = int_to_hex(res[-6], res[-5], res[-4], res[-3])
-                    print('盐度:', q, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(q, "盐度")
-                    sendFlag = 4
-            # 深度
-            if sendFlag == 4:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    print('深度:', t, 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 5
-            # PH
-            if sendFlag == 5:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 9:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('PH:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "PH")
-                    sendFlag = 6
-            # 深度
-            if sendFlag == 6:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    print('深度:', t, 'length:', length, time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-
-                    sendFlag = 7
-            # 叶绿素
-            if sendFlag == 7:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 13:
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    # print('叶绿素:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "叶绿素")
-                    sendFlag = 8
-            # 深度
-            if sendFlag == 8:
-                try:
-                    recvData = clientSocket.recv(1024)
-                except Exception as e:  # 忽视掉超时
-                    break
-                length = len(recvData)
-                fmt = str(length) + 'B'
-                res = struct.unpack(fmt, recvData)
-                if length == 11:
-                    # print(len(res), res)
-                    t = int_to_hex(res[3], res[4], res[5], res[6])
-                    print('深度:', t, 'len:', len(res), time.strftime('%Y-%m-%d %H:%M:%S'))
-                    self.save_format_data(t, "深度")
-                    sendFlag = 0
-        clientSocket.close()
-        self.__log.info("Client closed.")
-
-        # print(time.strftime('%Y-%m-%d %H:%M:%S'), len(recvData))
-        # socket_msg = recvData.decode()  # 将接收到的字节数据转为 string
-        # print("Socket receive: " + socket_msg)
-
-
-def int_to_hex(a1, a2, b1, b2):
-    t1 = hex(a1 * 256 + a2)[2:]
-    t2 = hex(b1 * 256 + b2)[2:]
-    if len(t1) != 4: t1 = (4 - len(t1)) * '0' + t1
-    if len(t2) != 4: t2 = (4 - len(t2)) * '0' + t2
-    t = t1 + t2
-    t = struct.unpack('>f', binascii.unhexlify(t.replace(' ', '')))[0]
-    return t

+ 5 - 0
event_storage.py

@@ -63,6 +63,11 @@ class EventStorage:
         data = self.hardDiskStorage.quary_table_data(select_info)
         return data
 
+    # 获取insitu指令
+    def get_in_situ_command(self):
+        data = self.hardDiskStorage.get_in_situ_command()
+        return data
+
 
 class Networkerror(RuntimeError):
     def __init__(self, arg):

+ 55 - 24
gateway.py

@@ -5,6 +5,8 @@ import sys
 import threading
 import time
 
+import win32api
+import wmi
 from sanic import Sanic
 from sanic_cors import CORS, cross_origin
 from sanic import response
@@ -21,10 +23,6 @@ from api_context import ApiContext
 
 app = Sanic(__name__)
 CORS(app)
-system_config = Configuration().get_system_config()
-gateway_storage = EventStorage()
-connector_config = gateway_storage.get_connector_config()
-Utility.start_connectors(connector_config)
 
 
 # config = {"ip": "127.0.0.1",
@@ -67,9 +65,7 @@ def get_one_page_content(request):
     return response.text(data_json)
 
 
-# 历史数据库分页查询接口--------------------------------------------//
-
-# 历史数据库分页查询接口--------------------------------------------\\
+# 历史数据导出接口--------------------------------------------\\
 @app.post('/quary')
 async def quary_table_data(request):
     dict = request.json
@@ -80,7 +76,7 @@ async def quary_table_data(request):
 
 
 @app.route("/download")
-async def test(request):
+async def downlod_file(request):
     filename = request.args.get("filename")
     if sys.platform == 'win32':
         filepath = './' + filename
@@ -93,26 +89,25 @@ async def test(request):
     )
 
 
-# 历史数据库分页查询接口--------------------------------------------//
 @app.route('/readPointInfo', methods=['POST'])
 async def read_point_info(request):
     data_list = gateway_storage.get_point_info(None)
     return response.json(data_list)
 
 
-@app.route('/readStatistics', methods=['POST'])
-async def read_statistics_data(request):
-    list = request.json['pointList']
-    dict = gateway_storage.get_real_data(list)
-    return response.json(dict)
-
-
-@app.route('/write', methods=['POST'])
-async def write_data(request):
-    id = request.json["id"]
-    value = request.json["value"]
-    connector = request.json["device"]
-    connector.send_command("zz")
+# @app.route('/readStatistics', methods=['POST'])
+# async def read_statistics_data(request):
+#     list = request.json['pointList']
+#     dict = gateway_storage.get_real_data(list)
+#     return response.json(dict)
+#
+#
+# @app.route('/write', methods=['POST'])
+# async def write_data(request):
+#     id = request.json["id"]
+#     value = request.json["value"]
+#     connector = request.json["device"]
+#     connector.send_command("zz")
 
 
 @app.route('/api', methods=['POST'])
@@ -130,6 +125,31 @@ async def read_statistics_data(request):
     return response.json(list)
 
 
+# def verify_cpu_code():
+#     # 获取配置文件中CPU序列号
+#     config_handle = Configuration()
+#     config = config_handle.get_system_config()
+#     cpu_code_from_config_file = config['code']
+#     # 获取当前设备CPU序列号
+#     c = wmi.WMI()
+#     for cpu in c.Win32_Processor():
+#         cpu_code = cpu.ProcessorId.strip()
+#
+#     # 判断是否匹配
+#     if cpu_code == cpu_code_from_config_file:
+#         return True
+#     else:
+#         return False
+
+
+# @app.post('/verify')
+# def verify_app(request):
+#     if is_active:
+#         return response.json({'status': 'yes'})
+#     else:
+#         return response.json({'status': 'no'})
+
+
 # def overrun_alarm(alarms):
 #     print('async overrun_alarm')
 #     await asyncio.sleep(.1)
@@ -144,6 +164,8 @@ async def read_statistics_data(request):
 async def notify_server_started_after_five_seconds():
     while True:
         await asyncio.sleep(10)
+        if 'wxt536' not in Utility.available_connectors:
+            break
         connector = Utility.available_connectors["wxt536"]
         data = "0XZRU\r\n"
         # 8:00:00-8:01:00 everyday
@@ -157,6 +179,13 @@ async def notify_server_started_after_five_seconds():
 
 
 if __name__ == "__main__":
+    system_config = Configuration().get_system_config()
+    print(system_config)
+    gateway_storage = EventStorage()
+    connector_config = gateway_storage.get_connector_config()
+    # is_active = verify_cpu_code()
+    # if is_active:
+    Utility.start_connectors(connector_config)
     alarm1 = Alarm()
     threading.Thread(target=alarm1.overrun_alarm).start()
     # threading.Thread(target=alarm2.displacement_alarm).start()
@@ -164,7 +193,9 @@ if __name__ == "__main__":
     threading.Thread(target=historicalDataStorage.run).start()
     # app.add_task(overrun_alarm(app, alarm))
     # app.add_task(displacement_alarm(app, alarm))
-    # app.add_task(notify_server_started_after_five_seconds())  # 气象仪降雨量每日清零:一号打开,二号关闭,三号关闭
-    app.run(host="0.0.0.0", port=8000, debug=True)
+    # 气象仪降雨量每日清零:一号打开,二号关闭,三号关闭
+    app.add_task(notify_server_started_after_five_seconds())
+    app.run(host="0.0.0.0", port=8000)
+
 # pyinstaller -F -p C:\Users\wenge\AppData\Local\Programs\Python\Python38\Lib\site-packages  gateway.spec
 # pyinstaller -F -p D:\DevTools\Python38\Lib\site-packages  gateway.spec

+ 16 - 2
hard_disk_storage.py

@@ -132,7 +132,7 @@ class HardDiskStorage():
             print(traceback.format_exc())
             return None
 
-    # 历史查询接口(new)--------------------------------------------//
+    # --------------------------------------------//
 
     # 数据导出接口------------------------------------------------\\
     def quary_table_data(self, search_info):
@@ -177,7 +177,21 @@ class HardDiskStorage():
         book.save(savepath)
         return savepath
 
-    # 数据导出接口------------------------------------------------//
+    # ------------------------------------------------//
+
+    # 获取insitu指令接口
+    def get_in_situ_command(self):
+        sql = "select * from shuizhi_insitu_instruct;"
+        try:
+            self._reConn()
+            self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
+            self.cursor.execute(sql)
+            results = self.cursor.fetchall()
+            self.cursor.close()
+            return results
+        except:
+            print(traceback.format_exc())
+            return None
 
     def get_connectors(self):
         sql = "SELECT * FROM station_info_tbl WHERE status = 1"