- 监测数据采集物联网应用开发步骤(8.1)
新建TCP/IP Client线程类com.zxy.tcp.ClientThread.py
#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''
import datetime
import socket
import threading
import time
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.tcp.TcpClient import TcpClient
from com.zxy.z_debug import z_debug
#监测数据采集物联网应用--TCP/IP Client线程
class ClientThread(z_debug):
#断线重连
idtTimeOut = 60
sServerIP = "0.0.0.0"
iPort = 6000
connectionFlag = False
def __init__(self, timeout, ServerIP, temPort):
self.idtTimeOut = timeout
self.sServerIP = ServerIP
self.iPort = temPort
#inputFlag网络链接是否正常
def set_dSockList(self,inputFlag):
key = str(self.sServerIP)+"|"+str(self.iPort)
#存在
if key not in list(Com_Para.dSockList.keys()):
Com_Para.dSockList[key] = [0,datetime.datetime.now()]
if inputFlag == False:
objAry = Com_Para.dSockList[key]
if objAry[0] <= int(180 / self.idtTimeOut)+12:
objAry[0] = objAry[0] + 1
objAry[1] = datetime.datetime.now()
Com_Para.dSockList[key] = objAry
else:
Com_Para.dSockList[key] = [0,datetime.datetime.now()]
#判断上次链接时间频率是否合规
def judge_dSock(self):
key = str(self.sServerIP)+"|"+str(self.iPort)
if key not in list(Com_Para.dSockList.keys()):
Com_Para.dSockList[key] = [0,datetime.datetime.now()]
objAry = Com_Para.dSockList[key]
starttime = datetime.datetime.now()
if objAry[0] <= int(120 / self.idtTimeOut)+1:
return True
elif objAry[0] <= int(120 / self.idtTimeOut)+7 and starttime >= objAry[1] + datetime.timedelta(minutes=10):
return True
elif objAry[0] <= int(120 / self.idtTimeOut)+12 and starttime >= objAry[1] + datetime.timedelta(hours=1):
return True
elif objAry[0] > int(120 / self.idtTimeOut)+12 and starttime >= objAry[1] + datetime.timedelta(hours=1):
return True
else:
return False
def run(self):
starttime = datetime.datetime.now()
endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.idtTimeOut)
ckeys = self.sServerIP + "|" + str(self.iPort)
tc = TcpClient(ckeys)
t = None
try:
#判断上次链接时间频率是否合规
if not self.judge_dSock():
return None
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.sServerIP, self.iPort))
Com_Fun.SetHashTable(Com_Para.dClientThreadList, ckeys, s)
self.set_dSockList(True)
temResult = "*"
Com_Fun.SendSocket(temResult,s)
t = threading.Thread(target=tc.client_link, name="ClientTh" + ckeys)
t.start()
except IOError as e:
temError = "repeat connect server error:"+self.sServerIP+" "+Com_Fun.GetTime("%Y-%m-%d %H:%M:%S") + repr(e)
uL = UsAdmin_Log(Com_Para.ApplicationPath, temError)
uL.WriteLog()
self.set_dSockList(False);
while True:
starttime = datetime.datetime.now()
try:
if t is None and starttime <= endtime:
if Com_Fun.GetHashTableNone(Com_Para.dClientThreadList, ckeys) is not None:
t = threading.Thread(target=tc.client_link, name="ClientTh" + self.sServerIP)
t.start()
time.sleep(self.idtTimeOut/2)
elif starttime >= endtime:
endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.idtTimeOut)
if Com_Fun.GetHashTableNone(Com_Para.dClientThreadList, ckeys) is None and self.judge_dSock():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.sServerIP, self.iPort))
self.set_dSockList(True)
Com_Fun.SetHashTable(Com_Para.dClientThreadList, s.getpeername()[0]+"|"+str(s.getpeername()[1]), s)
t = threading.Thread(target=tc.client_link, name="ClientTh" + self.sServerIP)
t.start()
time.sleep(self.idtTimeOut/2)
#超过10分钟,重新计时
elif (endtime - starttime).seconds > 10 * self.idtTimeOut:
endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.idtTimeOut)
else:
time.sleep(self.idtTimeOut/2)
except IOError as e:
temError = "repeat connect server error:"+self.sServerIP+" "+Com_Fun.GetTime("%Y-%m-%d %H:%M:%S") + repr(e)
uL = UsAdmin_Log(Com_Para.ApplicationPath, temError)
uL.WriteLog()
self.set_dSockList(False);
def list_run(self):
starttime = datetime.datetime.now()
endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.idtTimeOut)
ckeys = self.sServerIP + "|" + str(self.iPort)
tc = TcpClient(ckeys)
t = None
try:
#判断上次链接时间频率是否合规
if not self.judge_dSock():
return None
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.sServerIP, self.iPort))
Com_Fun.SetHashTable(Com_Para.dClientThreadList, ckeys, s)
self.set_dSockList(True)
t = threading.Thread(target=tc.client_link, name="ClientTh" + ckeys)
t.start()
except IOError as e:
temError = "repeat connect server error:"+self.sServerIP+" "+Com_Fun.GetTime("%Y-%m-%d %H:%M:%S") + repr(e)
uL = UsAdmin_Log(Com_Para.ApplicationPath, temError)
uL.WriteLog()
self.set_dSockList(False)
while True:
starttime = datetime.datetime.now()
try:
if t is None and starttime <= endtime:
if Com_Fun.GetHashTableNone(Com_Para.dClientThreadList, ckeys) is not None:
t = threading.Thread(target=tc.client_link, name="ClientTh" + self.sServerIP)
t.start()
time.sleep(self.idtTimeOut/2)
elif starttime >= endtime:
endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.idtTimeOut)
if Com_Fun.GetHashTableNone(Com_Para.dClientThreadList, ckeys) is None and self.judge_dSock():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.sServerIP, self.iPort))
Com_Fun.SetHashTable(Com_Para.dClientThreadList, s.getpeername()[0]+"|"+str(s.getpeername()[1]), s)
self.set_dSockList(True)
t = threading.Thread(target=tc.client_link, name="ClientTh" + self.sServerIP)
t.start()
time.sleep(self.idtTimeOut/2)
#超过10分钟,重新计时
elif (endtime - starttime).seconds > 10 * self.idtTimeOut:
endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.idtTimeOut)
else:
time.sleep(self.idtTimeOut/2)
except IOError as e:
temError = "repeat connect server error:"+self.sServerIP+" "+Com_Fun.GetTime("%Y-%m-%d %H:%M:%S") + repr(e)
uL = UsAdmin_Log(Com_Para.ApplicationPath, temError)
uL.WriteLog()
self.set_dSockList(False);
新建tcp client数据接收插件类1 com.plugins.Usereflect.testClientReflectClass1.py
#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''
from com.zxy.z_debug import z_debug
#监测数据采集物联网应用--往平台端发送数据协议拦截器,可组装发送平台数据协议程序
class testClientReflectClass1(z_debug):
#接收到数据
strResult = ""
#需要发送到服务端数据
strSend = ""
#是否继续执行 1:继续执行 0:中断执行
strContinue = "1"
#所连接的远端IP
strIP = ""
def __init__(self):
pass
def init_start(self):
#作为客户端接收数据拦截器
if self.strResult == "A01":
self.strSend = "#send to server data:server1"
print("AAA作为客户端接收数据拦截器:"+self.strResult)
self.strResult = "ok"
#Com_Para.dClientThreadList 本机作为客户端连接socket list
#Com_Para.htComPort 串口通讯hashtable <String, seria>
# /*示例:此处写业务逻辑,最后给 strResult重新赋值*/
# //self.strResult = "test"
# //self.strSend = "发送到服务端数据"
# /**************************************************/
新建tcp client数据接收插件类2 com.plugins.Usereflect.testClientReflectClass2.py
#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''
from com.zxy.z_debug import z_debug
#监测数据采集物联网应用--往平台端发送数据协议拦截器,可组装发送平台数据协议程序
class testClientReflectClass2(z_debug):
#接收到数据
strResult = ""
#需要发送到服务端数据
strSend = ""
#是否继续执行 1:继续执行 0:中断执行
strContinue = "1"
#所连接的远端IP
strIP = ""
def __init__(self):
pass
def init_start(self):
#作为客户端接收数据拦截器
if self.strResult == "A02":
self.strSend = "#send to server data:server"
print("BBB作为客户端接收数据拦截器:"+self.strResult)
self.strResult = "ok"
#Com_Para.dClientThreadList 本机作为客户端连接socket list
#Com_Para.htComPort 串口通讯hashtable <String, seria>
# /*示例:此处写业务逻辑,最后给 strResult重新赋值*/
# //self.strResult = "test"
# //self.strSend = "发送到服务端数据"
# /**************************************************/
在com.zxy.main.Init_Page.py中添加代码
@staticmethod
def Start_Client():
try:
for temSIP in Com_Para.ServerIPList.split(";"):
if temSIP != "":
sttem = ClientThread(10, temSIP.split(":")[0], int(temSIP.split(":")[1]))
# TCP客户端案例
t4tem = threading.Thread(target=sttem.list_run, name="ClientMainThread" + temSIP.split(":")[0])
t4tem.start()
except Exception as e:
print("TCP client error:" + repr(e)+"=>"+str(e.__traceback__.tb_lineno))
finally:
Pass
TCP Client测试案例MonitorDataCmd.py主文件中编写:
在 if __name__ == '__main__':下添加
#TCP Client配置服务端ip及端口参数
Com_Para.ServerIPList = "127.0.0.1:5002;127.0.0.1:5003"
#TCP/IP client连接初始化
Init_Page.Start_Client()
#暂停3秒钟,tcp client连接需要时间
time.sleep(3)
#测试TCP/IP client发送数据
tcSock = Com_Fun.GetHashTableNone(Com_Para.dClientThreadList,"127.0.0.1|5002")
#作为客户端接收数据拦截器
Com_Para.ClientREFLECT_IN_CLASS = "com.plugins.usereflect.testClientReflectClass1"
if tcSock != None:
temStr = "TCP client往服务端发送数据:"+Com_Fun.GetTimeDef()+"\r\n"
print("开始准备发送数据")
Com_Fun.SendSocket(temStr, tcSock)
print("TCP client往服务端发送数据")
else:
print("TCP Client未准备好")
#改变下作为客户端接收数据拦截器
#Com_Para.ClientREFLECT_IN_CLASS = "com.plugins.usereflect.testClientReflectClass2"
#接收数据解析插件已经改变了
运行测试结果如下图:
文章来源:https://www.toymoban.com/news/detail-684327.html
监测数据采集物联网应用开发步骤(9.1)文章来源地址https://www.toymoban.com/news/detail-684327.html
到了这里,关于11、监测数据采集物联网应用开发步骤(8.2)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!