024——驱动、server、client、GUI全功能联调

2024-04-16 15:12

本文主要是介绍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全功能联调的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/909146

相关文章

mysql出现ERROR 2003 (HY000): Can‘t connect to MySQL server on ‘localhost‘ (10061)的解决方法

《mysql出现ERROR2003(HY000):Can‘tconnecttoMySQLserveron‘localhost‘(10061)的解决方法》本文主要介绍了mysql出现... 目录前言:第一步:第二步:第三步:总结:前言:当你想通过命令窗口想打开mysql时候发现提http://www.cpp

Python GUI框架中的PyQt详解

《PythonGUI框架中的PyQt详解》PyQt是Python语言中最强大且广泛应用的GUI框架之一,基于Qt库的Python绑定实现,本文将深入解析PyQt的核心模块,并通过代码示例展示其应用场... 目录一、PyQt核心模块概览二、核心模块详解与示例1. QtCore - 核心基础模块2. QtWid

SQL Server清除日志文件ERRORLOG和删除tempdb.mdf

《SQLServer清除日志文件ERRORLOG和删除tempdb.mdf》数据库再使用一段时间后,日志文件会增大,特别是在磁盘容量不足的情况下,更是需要缩减,以下为缩减方法:如果可以停止SQLSe... 目录缩减 ERRORLOG 文件(停止服务后)停止 SQL Server 服务:找到错误日志文件:删除

Windows Server服务器上配置FileZilla后,FTP连接不上?

《WindowsServer服务器上配置FileZilla后,FTP连接不上?》WindowsServer服务器上配置FileZilla后,FTP连接错误和操作超时的问题,应该如何解决?首先,通过... 目录在Windohttp://www.chinasem.cnws防火墙开启的情况下,遇到的错误如下:无法与

一文详解SQL Server如何跟踪自动统计信息更新

《一文详解SQLServer如何跟踪自动统计信息更新》SQLServer数据库中,我们都清楚统计信息对于优化器来说非常重要,所以本文就来和大家简单聊一聊SQLServer如何跟踪自动统计信息更新吧... SQL Server数据库中,我们都清楚统计信息对于优化器来说非常重要。一般情况下,我们会开启"自动更新

JAVA虚拟机中 -D, -X, -XX ,-server参数使用

《JAVA虚拟机中-D,-X,-XX,-server参数使用》本文主要介绍了JAVA虚拟机中-D,-X,-XX,-server参数使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有... 目录一、-D参数二、-X参数三、-XX参数总结:在Java开发过程中,对Java虚拟机(JVM)的启动参数进

Windows server服务器使用blat命令行发送邮件

《Windowsserver服务器使用blat命令行发送邮件》在linux平台的命令行下可以使用mail命令来发送邮件,windows平台没有内置的命令,但可以使用开源的blat,其官方主页为ht... 目录下载blatBAT命令行示例备注总结在linux平台的命令行下可以使用mail命令来发送邮件,Win

golang获取prometheus数据(prometheus/client_golang包)

《golang获取prometheus数据(prometheus/client_golang包)》本文主要介绍了使用Go语言的prometheus/client_golang包来获取Prometheu... 目录1. 创建链接1.1 语法1.2 完整示例2. 简单查询2.1 语法2.2 完整示例3. 范围值

MySQL 中的服务器配置和状态详解(MySQL Server Configuration and Status)

《MySQL中的服务器配置和状态详解(MySQLServerConfigurationandStatus)》MySQL服务器配置和状态设置包括服务器选项、系统变量和状态变量三个方面,可以通过... 目录mysql 之服务器配置和状态1 MySQL 架构和性能优化1.1 服务器配置和状态1.1.1 服务器选项

查询SQL Server数据库服务器IP地址的多种有效方法

《查询SQLServer数据库服务器IP地址的多种有效方法》作为数据库管理员或开发人员,了解如何查询SQLServer数据库服务器的IP地址是一项重要技能,本文将介绍几种简单而有效的方法,帮助你轻松... 目录使用T-SQL查询方法1:使用系统函数方法2:使用系统视图使用SQL Server Configu