本文主要是介绍024——驱动、server、client、GUI全功能联调,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
一、本次修改
二、GUI和Client之间联调
2.1 工程结构修改
2.2 将TCP程序修改为可被其它程序调用
2.3 优化显示界面
2.4 解决GUI通过tcp send的问题
2.5 处理服务器数据
时间不是很多了,我想压缩一下快点把属于毕设的这部分搞完,俺要出去旅游了。所以后面写的东西不会很多了。等我回来接着跟大家详细的分享技术。
一、本次修改
改的太多了,整个修改过程主要部分都在下面详细说明包括中间版本的文件。
二、GUI和Client之间联调
2.1 工程结构修改
为了更规范一些我把项目做了拆分,全局变量在global_var文件中。
tcp通信在tcp中,工具在tool里。GUI在show里。客户端的主程序就叫client
2.2 将TCP程序修改为可被其它程序调用
'''
fuction : 与服务器建立连接
author : 辛天宇
data : 2024-4-9
-------------------------------
author data modify'''
import socket
import global_var# def Client_server():
# # 设置服务器地址和端口
# server_address = (global_var.SERVER_IP, global_var.SERVER_PORT)# # 创建一个socket对象
# client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # # 连接到服务器
# try:
# client_socket.connect(server_address)
# print(f'Connected to {server_address}') # # 接收用户输入并发送给服务器
# while True:
# try:
# user_input = input('Enter command (or "exit" to quit): ')
# if user_input.lower() == 'exit':
# cmd = 'Q'
# client_socket.sendall(cmd.encode())
# break
# while 'Q' == user_input:
# print(f'please input other string')
# user_input = input('Enter command (or "exit" to quit): ')
# client_socket.sendall(user_input.encode()) # # 接收服务器的响应
# data = client_socket.recv(512)
# print(f'Received: {data.decode()}') # except KeyboardInterrupt:
# print('\nKeyboardInterrupt received, exiting...')
# break
# except ConnectionResetError:
# print('\nConnection reset by server, exiting...')
# break
# except Exception as e:
# print(f'An error occurred: {e}, trying to reconnect...')
# client_socket.close() # Close the socket if there's an error
# client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a new one
# client_socket.connect(server_address) # Reconnect to the server # finally:
# # 关闭连接
# print('Closing socket')
# client_socket.close()def connect_to_server(server_address): # 创建一个socket对象 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 尝试连接到服务器 try: client_socket.connect(server_address) print(f'Connected to {server_address}') return client_socket except Exception as e: print(f'Failed to connect to server: {e}') return None def process_data(client_socket, server_address): try: # 接收用户输入并发送给服务器 while True: try: user_input = input('Enter command (or "exit" to quit): ') if user_input.lower() == 'exit': cmd = 'Q' client_socket.sendall(cmd.encode()) break while user_input.lower() == 'q': print(f'Please input other string') user_input = input('Enter command (or "exit" to quit): ') client_socket.sendall(user_input.encode()) # 接收服务器的响应 data = client_socket.recv(512) print(f'Received: {data.decode()}') except KeyboardInterrupt: print('\nKeyboardInterrupt received, exiting...') break except ConnectionResetError: print('\nConnection reset by server, exiting...') break except Exception as e: print(f'An error occurred: {e}, trying to reconnect...') client_socket.close() # 关闭当前socket client_socket = connect_to_server(server_address) # 尝试重新连接 if client_socket is None: break # 如果连接失败,则退出循环 finally: # 关闭连接 print('Closing socket') client_socket.close() def Client_server(): # 设置服务器地址和端口 server_address = (global_var.SERVER_IP, global_var.SERVER_PORT)# 尝试连接到服务器 client_socket = connect_to_server(server_address) if client_socket is not None: # 如果连接成功,则处理数据 process_data(client_socket, server_address) def main():Client_server()if __name__ == '__main__':main()
2.3 优化显示界面
更人性化了一丢丢
'''
fuction : 客户端程序
author : 辛天宇
data : 2024-4-13
-------------------------------
author data modify'''
import show
import tcp
import tool
import socket
import global_vardef tcp_handle():# 设置服务器地址和端口 server_address = (global_var.SERVER_IP, global_var.SERVER_PORT)# 尝试连接到服务器 client_socket = connect_to_server(server_address) if client_socket is not None: # 如果连接成功,则处理数据 tcp.process_data(client_socket, server_address) # 处理事件
def event_handle():window = show.show_window('DefaultNoMoreNagging')# 事件循环 while True: try:event, values = window.read()if event == 'input':window['txbuff'].update(disabled=not values['input'])elif event == 'send':global_var.TX_BUF = values['txbuff'] print(f"tcbuff={global_var.TX_BUF}")window['txbuff'].update(value='')elif event == 'Clean':window['Output'].update(value='')elif event == 'dht11':message = f"{global_var.TEM}°C {global_var.HUM}%"window['Getvalue'].update(message)elif event == 'ds18b20':message = f"{global_var.TEM}°C"window['Getvalue'].update(message)elif event == 'Quit': print(f"See you.............")breakelif event == 'Connect':global_var.SERVER_IP = "192.168.5.10"window['IP'].update(global_var.SERVER_IP)elif event == 'Disconnect': global_var.SERVER_IP = "connectionless network service"window['IP'].update(global_var.SERVER_IP)elif event is None:print(f"xxxxxxxxxxxxxxxxxxxx")breakelif event == 'LED': print(f"LED-----------------") # 处理其他事件...except Exception as e:window.close()print(f"An error occurred: {e}")return 0window.close()return 0 def main():event_handle()if __name__ == '__main__':main()
2.4 解决GUI通过tcp send的问题
'''
fuction : 客户端程序
author : 辛天宇
data : 2024-4-13
-------------------------------
author data modify'''
import show
import tcp
import tool
import socket
import global_vardef tcp_handle():# 设置服务器地址和端口 server_address = (global_var.SERVER_IP, global_var.SERVER_PORT)# 尝试连接到服务器 client_socket = connect_to_server(server_address) # if client_socket is not None: # # 如果连接成功,则处理数据 # return client_socket, server_address# else:# return Nonedef process_data(client_socket, server_address): try:if global_var.TX_BUF == 'exit': cmd = 'Q' client_socket.sendall(cmd.encode()) return 0# 接收服务器的响应 data = client_socket.recv(512) print(f'Received: {data.decode()}') except KeyboardInterrupt: print('\nKeyboardInterrupt received, exiting...') return KeyboardInterruptexcept ConnectionResetError: print('\nConnection reset by server, exiting...') return ConnectionResetError except Exception as e: print(f'An error occurred: {e}, trying to reconnect...') client_socket.close() # 关闭当前socket client_socket = connect_to_server(server_address) # 尝试重新连接 if client_socket is None: return -1# 处理事件
def event_handle():window = show.show_window('DefaultNoMoreNagging')# 尝试连接到服务器 client_socket = tcp.connect_to_server()if client_socket is not None: # 事件循环 while True: try:event, values = window.read()if event == 'input':window['txbuff'].update(disabled=not values['input'])elif event == 'send':global_var.FLAG == 1global_var.TX_BUF = values['txbuff'] print(f"tcbuff={global_var.TX_BUF}")window['txbuff'].update(value='')if 0 == tcp.process_data(client_socket, server_address):passelse:print(f"send ERROR!!!")return -1elif event == 'Clean':window['Output'].update(value='')elif event == 'dht11':message = f"{global_var.TEM}°C {global_var.HUM}%"window['Getvalue'].update(message)elif event == 'ds18b20':message = f"{global_var.TEM}°C"window['Getvalue'].update(message)elif event == 'Quit': print(f"See you.............")breakelif event is None:print(f"xxxxxxxxxxxxxxxxxxxx")breakelif event == 'LED': print(f"LED-----------------") # 处理其他事件...except Exception as e:window.close()print(f"An error occurred: {e}")return 0window.close()return 0 def main():event_handle()if __name__ == '__main__':main()
做了大改动现在的问题是
会闪退
原来是函数参数改完这面忘记改了
加上GUI后输出都会到GUI的OUTPUT导致直接闪退什么都看不到
终于是通信上了,其实这部分可以单独拿出来做个项目了哈哈,图形化的网络编程聊天室,就是要在优化优化现在就是个框架。
'''
fuction : 客户端程序
author : 辛天宇
data : 2024-4-13
-------------------------------
author data modify'''
import show
import tcp
import tool
import socket
import global_var# 处理事件
def event_handle(window, client_socket):# 事件循环 while True: try:event, values = window.read()if event == 'input':window['txbuff'].update(disabled=not values['input'])elif event == 'send':global_var.TX_BUF = values['txbuff'] print(f"tcbuff={global_var.TX_BUF}")window['txbuff'].update(value='')user_input = global_var.TX_BUFclient_socket.sendall(user_input.encode())# 接收服务器的响应 data = client_socket.recv(512)print(f"rx......{data}") elif event == 'Clean':window['Output'].update(value='')elif event == 'dht11':message = f"{global_var.TEM}°C {global_var.HUM}%"window['Getvalue'].update(message)elif event == 'ds18b20':message = f"{global_var.TEM}°C"window['Getvalue'].update(message)elif event == 'Quit': print(f"See you.............")breakelif event is None:print(f"xxxxxxxxxxxxxxxxxxxx")breakelif event == 'LED': print(f"LED-----------------") # 处理其他事件...except Exception as e:window.close()print(f"An error occurred: {e}")return 0window.close()return 0 def main():# 创建GUI对象window = show.show_window('DefaultNoMoreNagging')# 尝试连接到服务器 client_socket = tcp.connect_to_server()if client_socket is not None: event_handle(window, client_socket)if __name__ == '__main__':main()
简化成了这个样子
2.5 处理服务器数据
'''
fuction : 客户端程序
author : 辛天宇
data : 2024-4-13
-------------------------------
author data modify'''
import show
import tcp
import tool
import socket
import global_vardef send_handle(window, client_socket, values):global_var.TX_BUF = values['txbuff'] print(f"txbuff={global_var.TX_BUF}")# 清理inputwindow['txbuff'].update(value='')data = global_var.TX_BUFclient_socket.sendall(data.encode())# 接收服务器的响应data = client_socket.recv(512)# 将字节字符串转化为字符串global_var.RX_BUF = data.decode('utf-8')print(f"rx......{global_var.RX_BUF}") # 进行一次发送和接收
def send_cmd(client_socket):data = global_var.TX_BUFclient_socket.sendall(data.encode())# 接收服务器的响应data = client_socket.recv(512)# 将字节字符串转化为字符串global_var.RX_BUF = data.decode('utf-8')# 设置发送消息
def set_tx_buf(device, message): if device == 'sr04':global_var.TX_BUF = '@002'elif device == 'sr501':global_var.TX_BUF = '@001'elif device == 'irda':global_var.TX_BUF = '@003'elif device == 'motor':global_var.TX_BUF = '@004'+messageelif device == 'dht11':global_var.TX_BUF = '@005'+messageprint(f"dht11={global_var.TX_BUF}")elif device == 'ds18b20':global_var.TX_BUF = '@006'elif device == 'iic':global_var.TX_BUF = '@007'elif device == 'iic':global_var.TX_BUF = '@008'# 处理数据
def cmd_handle():cmd = global_var.RX_BUFif len(cmd) < 4:print("cmd ERROR")return -1if '@' == cmd[0]:# 目前驱动设备数量只有两位数if cmd[1] == '0':#LEDif cmd[2] == '0' and cmd[3] == '0':if cmd[4] == '1':print("LED Open")elif cmd[4] == '0':print("LED Close")else:print("message ERROR")#SR501elif cmd[2] == '0' and cmd[3] == '1':if cmd[4] == '1':print("有人")elif cmd[4] == '0':print("无人")else:print("message ERROR")#SR04elif cmd[2] == '0' and cmd[3] == '2':print(cmd[4:])#irdaelif cmd[2] == '0' and cmd[3] == '3':print(cmd[4:])#motorelif cmd[2] == '0' and cmd[3] == '4':print(cmd[4:])#dht11elif cmd[2] == '0' and cmd[3] == '5':print(cmd[4:])global_var.TEM=cmd[4]+cmd[5]global_var.HUM=cmd[6]+cmd[7]#ds18b20elif cmd[2] == '0' and cmd[3] == '6':print(cmd[4:])#iicelif cmd[2] == '0' and cmd[3] == '7':print(cmd[4:])#spielif cmd[2] == '0' and cmd[3] == '8':print(cmd[4:])# 处理事件
def event_handle(window, client_socket):# 事件循环 while True: try:cmd_handle()event, values = window.read()if event == 'input':window['txbuff'].update(disabled=not values['input'])elif event == 'send':send_handle(window, client_socket, values)elif event == 'Clean':window['Output'].update(value='')elif event == 'dht11':set_tx_buf('dht11', '2525')send_cmd(client_socket)message = f"{global_var.TEM}°C {global_var.HUM}%"window['Getvalue'].update(message)elif event == 'ds18b20':message = f"{global_var.TEM}°C"window['Getvalue'].update(message)elif event == 'Quit': print(f"See you.............")breakelif event is None:print(f"xxxxxxxxxxxxxxxxxxxx")breakelif event == 'LED': print(f"LED-----------------") # 处理其他事件...except Exception as e:window.close()print(f"An error occurred: {e}")return 0window.close()return 0 def main():# 创建GUI对象window = show.show_window('DefaultNoMoreNagging')# 尝试连接到服务器 client_socket = tcp.connect_to_server()if client_socket is not None: event_handle(window, client_socket)if __name__ == '__main__':main()
这块基本没问题了
完成了调试了三天麻了,好多东西没来得及记录结合驱动程序的调试放到下篇文章啦
这篇关于024——驱动、server、client、GUI全功能联调的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!