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

news2024/11/24 7:07:19

目录

一、本次修改

二、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_var

def 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.............")
                break
            elif 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")
                break
            elif event == 'LED':  
                print(f"LED-----------------") 
            # 处理其他事件...
        except Exception as e:
            window.close()
            print(f"An error occurred: {e}")
            return 0
    window.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_var

def 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 None

def 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 KeyboardInterrupt
    except 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 == 1
                    global_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):
                        pass
                    else:
                        print(f"send ERROR!!!")
                        return -1
                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.............")
                    break
                elif event is None:
                    print(f"xxxxxxxxxxxxxxxxxxxx")
                    break
                elif event == 'LED':  
                    print(f"LED-----------------") 
                # 处理其他事件...
            except Exception as e:
                window.close()
                print(f"An error occurred: {e}")
                return 0
    window.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_BUF
                client_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.............")
                break
            elif event is None:
                print(f"xxxxxxxxxxxxxxxxxxxx")
                break
            elif event == 'LED':  
                print(f"LED-----------------") 
            # 处理其他事件...
        except Exception as e:
            window.close()
            print(f"An error occurred: {e}")
            return 0
    window.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_var


def send_handle(window, client_socket, values):
    global_var.TX_BUF = values['txbuff'] 
    print(f"txbuff={global_var.TX_BUF}")
    # 清理input
    window['txbuff'].update(value='')
    data = global_var.TX_BUF
    client_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_BUF
    client_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'+message
    elif device == 'dht11':
        global_var.TX_BUF = '@005'+message
        print(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_BUF
    if len(cmd) < 4:
        print("cmd ERROR")
        return -1
    if '@' == cmd[0]:
        # 目前驱动设备数量只有两位数
        if cmd[1] == '0':
            #LED
            if 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")
            #SR501
            elif cmd[2] == '0' and cmd[3] == '1':
                if cmd[4] == '1':
                    print("有人")
                elif cmd[4] == '0':
                    print("无人")
                else:
                    print("message ERROR")
            #SR04
            elif cmd[2] == '0' and cmd[3] == '2':
                print(cmd[4:])
            #irda
            elif cmd[2] == '0' and cmd[3] == '3':
                print(cmd[4:])
            #motor
            elif cmd[2] == '0' and cmd[3] == '4':
                print(cmd[4:])
            #dht11
            elif cmd[2] == '0' and cmd[3] == '5':
                print(cmd[4:])
                global_var.TEM=cmd[4]+cmd[5]
                global_var.HUM=cmd[6]+cmd[7]
            #ds18b20
            elif cmd[2] == '0' and cmd[3] == '6':
                print(cmd[4:])
            #iic
            elif cmd[2] == '0' and cmd[3] == '7':
                print(cmd[4:])
            #spi
            elif 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.............")
                break
            elif event is None:
                print(f"xxxxxxxxxxxxxxxxxxxx")
                break
            elif event == 'LED':  
                print(f"LED-----------------") 
            # 处理其他事件...
        except Exception as e:
            window.close()
            print(f"An error occurred: {e}")
            return 0
    window.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()

这块基本没问题了

完成了调试了三天麻了,好多东西没来得及记录结合驱动程序的调试放到下篇文章啦

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1606624.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

[算法] 动态规划

对这个算法的原有印象就是非常难理解&#xff0c;而且怎么都感觉这个算法名称有些误导&#xff1b;或者是要引申着看&#xff1f;因为里面的动态是怎么个动态&#xff1f; 这里的动态是指每一次的计算结果会影响下一次&#xff0c;或者再次的运算效率&#xff0c;也就是说下一次…

记录ubuntu20.04安装nvidia-525.85.05显卡驱动(学习笔记2024.4.15、4.16)

电脑&#xff1a;华硕天选X2024 显卡&#xff1a;4060Ti i5-14400F 架构&#xff1a;x86_64 我需要使用Linux系统使用IsaacSim进行仿真&#xff0c;所以安装的都是IsaacSim中的推荐版本。 一.对新鲜的电脑进行分盘 电脑刚到手&#xff0c;900多个G全在C盘里&#xff0c;给它…

历史遗留问题1-Oracle Mysql如何存储数据、索引

在学习到Oracle redo和undo时&#xff0c;涉及到很多存储结构的知识&#xff0c;但是网上的教程都不是很详细&#xff0c;就去复习了一下mysql&#xff0c;感觉是不是开源的问题&#xff0c;Mysql的社区和知识沉淀远高于Oracle&#xff0c; 对于初学者很友好&#xff0c;我想请…

Python文件处理--进阶

Python标准库文件操作相关模块&#xff1a; 1.使用pickle序列化 序列化指的是&#xff1a;将对象转化成“串行化”数据形式&#xff0c;存储到硬盘或通过网络传输到其他地方。反序列化是指相反的过程&#xff0c;将读取到的“串行化数据”转化成对象。我们可以使用pickle模块…

vivo怎么录屏?玩转手机新体验!(2024最新)

“最近新入手了一款vivo手机&#xff0c;感觉用起来真的很顺手&#xff0c;各种功能都很强大。昨天和朋友一起打游戏&#xff0c;突然想到要记录下精彩瞬间&#xff0c;但是找遍了手机&#xff0c;都没有找到录屏功能。我想请教一下各位vivo手机用户&#xff0c;你们通常在哪里…

亚马逊Bedrock凭借Anthropic的开创性Claude 3系列扩展了AI产品组合

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…

基于SSM+Jsp+Mysql的文物管理系统

开发语言&#xff1a;Java框架&#xff1a;ssm技术&#xff1a;JSPJDK版本&#xff1a;JDK1.8服务器&#xff1a;tomcat7数据库&#xff1a;mysql 5.7&#xff08;一定要5.7版本&#xff09;数据库工具&#xff1a;Navicat11开发软件&#xff1a;eclipse/myeclipse/ideaMaven包…

Vue项目实现懒加载——自用笔记

熟悉指令语法&#xff1a; <template><HomePanel title"人气推荐" sub-title"人气爆款 不容错过"><ul class"goods-list"><li v-for"item in hotList" :key"item.id"><RouterLink to"/&qu…

富文本编辑器(wangEdit)+(jquery.wordexport)实现web版在线编辑导出

小插曲&#xff1a;最开始的方向是Html5的contenteditable"true"的文档可编辑属性。只能修改文档文字内容&#xff0c;不能修改样式&#xff0c;如修改字体&#xff0c;字号&#xff0c;颜色等。于是用了第一款&#xff08;quil&#xff09;富文本插件。只能说一般&a…

接收区块链的CCF会议--ICSOC 2024 截止7.24

ICSOC是CCF B类会议&#xff08;软件工程/系统软件/程序设计语言&#xff09; 2023年长文短文录用率22% Focus Area 4: Emerging Technologies Quantum Service Computing Digital Twins 3D Printing/additive Manufacturing Techniques Blockchain Robotic Process Autom…

【CSS】盒子居中

目录 效果图 代码及其解释 补充解释 效果图 同时实现盒子与文字的居中 代码及其解释 <!DOCTYPE html> <html><head><meta charset"utf-8"><title></title><style type"text/css">#box1{width: 500px;height:…

python将xml格式文件转成png或者pdf格式

本文主要介绍运行NCCL代码时输出的xml文件该如何转成更加容易观看的图格式 如下是举例&#xff0c;服务器上的PCIE相关的topo xml 文件 <system version"1"><cpu numaid"1" affinity"ffffff00,0000ffff,ff000000" arch"x86_64&q…

【论文解读系列】从RNN/CNN到大模型全解析

论文&#xff1a;A Survey of Neural Code Intelligence: Paradigms, Advances and Beyond 地址&#xff1a;GitHub&#xff1a;https://github.com/QiushiSun/NCISurvey 文章目录 一、代码模型的发展 1.神经语言建模&#xff08;Neural Language Modeling&#xff09;时代 …

手动给docusaurus添加一个搜索

新版博客用docusaurus重构已经有些日子了&#xff0c;根据docusaurus的文档上也申请了Algolia,想一劳永逸的解决博客的搜索问题。但是流水有意&#xff0c;落花无情。 algolia总是不给我回复&#xff0c;我只能对着algolia的申请页面仰天长叹。 正常情况的申请 按照docusaur…

2024 年 Web 前端开发趋势

希腊哲学家赫拉克利特认为&#xff0c;变化是生命中唯一不变的东西。这句话适用于我们的个人生活、行业和职业领域。 尤其是前端开发领域&#xff0c;新技术、开发趋势、库和框架不断涌现&#xff0c;变化并不陌生。最近发生的一些事件正在改变开发人员构建网站和 Web 应用的方…

图像生成模型浅析(Stable Diffusion、DALL-E、Imagen)

目录 前言1. 速览图像生成模型1.1 VAE1.2 Flow-based Model1.3 Diffusion Model1.4 GAN1.5 对比速览 2. Diffusion Model3. Stable Diffusion3.1 Text Encoder3.2 Decoder3.3 Generation Model 总结参考 前言 简单学习下图像生成模型的相关知识&#x1f917; 以下内容来自于李宏…

吴恩达深度学习笔记:深度学习的 实践层面 (Practical aspects of Deep Learning)1.4-1.5

目录 第一门课&#xff1a;第二门课 改善深层神经网络&#xff1a;超参数调试、正 则 化 以 及 优 化 (Improving Deep Neural Networks:Hyperparameter tuning, Regularization and Optimization)第一周&#xff1a;深度学习的 实践层面 (Practical aspects of Deep Learning)…

计算机网络——DHCP协议

目录 前言 前篇 引言 设置IP地址的两种方式 DHCP协议流程 前言 本博客是博主用于复习计算机网络的博客&#xff0c;如果疏忽出现错误&#xff0c;还望各位指正。 这篇博客是在B站掌芝士zzs这个UP主的视频的总结&#xff0c;讲的非常好。 可以先去看一篇视频&#xff0c…

qt 开发 缩放比例问题 修复中

在日常开中&#xff0c;需要开启 高分辨率的支持&#xff0c;windows环境下&#xff0c;不是 字体缩放&#xff0c;就是分辨率模糊&#xff0c;缩放机制&#xff0c;并且开启了150%缩放&#xff0c;有点搞不明白&#xff0c;最后还是不行&#xff0c;先做个记录&#xff0c;在找…

【2024 SCI一区】 基于DCS-BiLSTM-Attention的多元回归预测(Matlab实现)

【2024 SCI一区】 基于DCS-BiLSTM-Attention的多元回归预测&#xff08;Matlab实现&#xff09; 目录 【2024 SCI一区】 基于DCS-BiLSTM-Attention的多元回归预测&#xff08;Matlab实现&#xff09;效果一览基本介绍程序设计参考资料 效果一览 基本介绍 差异创意搜索算法&…