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

相关文章

Java 创建图形用户界面(GUI)入门指南(Swing库 JFrame 类)概述

概述 基本概念 Java Swing 的架构 Java Swing 是一个为 Java 设计的 GUI 工具包,是 JAVA 基础类的一部分,基于 Java AWT 构建,提供了一系列轻量级、可定制的图形用户界面(GUI)组件。 与 AWT 相比,Swing 提供了许多比 AWT 更好的屏幕显示元素,更加灵活和可定制,具有更好的跨平台性能。 组件和容器 Java Swing 提供了许多

Linux_kernel驱动开发11

一、改回nfs方式挂载根文件系统         在产品将要上线之前,需要制作不同类型格式的根文件系统         在产品研发阶段,我们还是需要使用nfs的方式挂载根文件系统         优点:可以直接在上位机中修改文件系统内容,延长EMMC的寿命         【1】重启上位机nfs服务         sudo service nfs-kernel-server resta

red5-server源码

red5-server源码:https://github.com/Red5/red5-server

Golang GUI入门——andlabs ui

官方不提供gui标准库,只好寻求第三方库。 https://github.com/google/gxui 这个gui库是谷歌内部人员提供的,并不是谷歌官方出品,现在停止维护,只好作罢。 第三方gui库 找了好多,也比较了好多,最终决定使用的是还是 https://github.com/andlabs/ui 相信golang gui还会发展的更好,期待更优秀的gui库 由于andlabs

【CSS in Depth 2 精译_024】4.2 弹性子元素的大小

当前内容所在位置(可进入专栏查看其他译好的章节内容) 第一章 层叠、优先级与继承(已完结) 1.1 层叠1.2 继承1.3 特殊值1.4 简写属性1.5 CSS 渐进式增强技术1.6 本章小结 第二章 相对单位(已完结) 2.1 相对单位的威力2.2 em 与 rem2.3 告别像素思维2.4 视口的相对单位2.5 无单位的数值与行高2.6 自定义属性2.7 本章小结 第三章 文档流与盒模型(已

安装SQL2005后SQL Server Management Studio 没有出来的解决方案

一种情况,在安装 sqlServer2005 时 居然出现两个警告: 1 Com+ 目录要求 2 Edition change check 郁闷!网上说出现两个警告,是肯定装不成功的!我抱着侥幸的态度试了下,成功了。 安装成功后,正准备 “ 仅工具、联机丛书和示例(T)” 但是安装不了,他提示我“工作站组件”安装过了对现有组件无法更新或升级。 解决办法: 1 打开“控

驱动(RK3588S)第七课时:单节点设备树

目录 需求一、设备树的概念1、设备树的后缀名:2、设备树的语法格式3、设备树的属性(重要)4、设备树格式举例 二、设备树所用函数1、如何在内核层种获取设备树节点:2、从设备树上获取 gpio 口的属性3、获取节点上的属性只针对于字符串属性的4、函数读取 np 结点中的 propname 属性的值,并将读取到的 u32 类型的值保存在 out_value 指向的内存中,函数的返回值表示读取到的

驱动安装注册表指令

HKCR: HKEY_CLASSES_ROOT HKCU: HKEY_CURRENT_USER HKLM: HKEY_LOCAL_MACHINE HKU: HEKY_USER HER: 相对根键

UMDF驱动安装

VS2013 + WDF8.1,UMDF驱动选择User Mode Driver,不要选User Mode Driver 2.0,否则Win7安装有问题,如图 另外,在驱动安装时不要忘记WUDFUpdate_<主版本号><次版本号>.dll文件,具体文件名在INF中查找。此文件可在WDF的安装目录中找到。注意:在WDF的安装目录中会有3个WUDFUpdate_xxx.dll文件,x86,x6

GUI编程08:画笔paint

本节内容视频链接:10、画笔paint_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1DJ411B75F?p=10&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5 package com.yundait.lesson03;import java.awt.*;import java.awt.event.Wind