诊断小系统通信设计(初步)--Apple的学习笔记
昨天做了需求分析,今天进行python客户端架构设计,做了个最小雏形,验证设计方案。创建2个类,一个是TCPsocket通信,一个HMI显示。
后续注意点,需要学习下的
1.python私有变量貌似是加下划线前缀,当前我加self的都是public变量。2.需要使用try except进行安全保障,添加打印提示信息。
3.添加装饰函数保存log.txt文件。
最小雏形功能简介,主函数中有GUI按钮通过TCPsocket进行发送数据,并且创建一个心跳监控线程,超过3s没有收到服务器发来的信息则断线重连。本来创建了GUI传入TCPcom对象作为参数,但是需要添加timeout断线重连,重连后又是另外一个TCPcom对象了,为了避免GUI更新,所以索性把com对象作为全局变量。反正2个类的关系就是GUI依赖TCPcom。
#client demo code
import socket
from tkinter import *
from tkinter.ttk import *
import threading
import time
__author__ = 'AppleCai'
class TCPcom():
def __init__(self,host,port):
self.host = host
self.port = port
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def ConnCom(self):
self.s.connect((self.host, self.port))
print("Connect %s:%d ok" % (self.host, self.port))
def CloseCom(self):
self.s.close()
def SendCom(self,data):
self.s.send(data)
def RecviveCom(self):
self.s.settimeout(5)
ret = self.s.recv(1024) #10
print(ret)
return ret
class GUI():
def __init__(self):
self.rectime = 0
pass
def update_table(self):
global com
com.SendCom(b'00 01 02')
resp = com.RecviveCom()
self.rectime = time.time()
def setupWin(self):
Button(text="send", width=5, command=self.update_table).grid(row=1, column=3, sticky='w')
def showWin(self):
root = Tk()
root.title("IG Sim")
root.geometry('420x300')
self.setupWin()
root.mainloop()
def heatDetect( threadName, delay):
while True:
global com
time.sleep(delay)
#print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
now = time.time()
delta = now - tool.rectime
print(now,tool.rectime,delta)
if(delta>3):
print("reconnect!")
com.CloseCom()
com = TCPcom('127.0.0.1',2345)
ret = com.ConnCom()
if __name__=="__main__":
# connect with server
com = TCPcom('127.0.0.1',2345)
ret = com.ConnCom()
# init for GUI
tool = GUI()
print(ret)
# start heart moniter
th1 = threading.Thread(target=heatDetect, args=("thread1", 3), name="thread1")
th1.start()
# run GUI
tool.showWin()
最小雏形,运行效果