9、监测数据采集物联网应用开发步骤(7)

源码将于最后一遍文章给出下载

监测数据采集物联网应用开发步骤(6)

串口(COM)通讯开发

本章节测试使用了 Configure Virtual Serial Port Driver虚拟串口工具和本人自写的串口调试工具,请自行baidu下载对应工具

com.zxy.common.Com_Para.py中添加如下内容

#RS232串口通讯列表 串口号,波特率,数据位,索引(A,B,C,D区分),多串口分割符;
ComPortList = ""  #linux参考:/dev/ttyS0,9600,8,0,A;/dev/ttyS1.9600,8,0,B windwows参考:COM1,9600,8,0;COM2,9600,8,2
#串口通讯全局变量hashtable <String, seria>串口索引---串口对象
htComPort = {}

 在com.zxy.main.Init_Page.py中添加如下内容

    @staticmethoddef Start_ComPort():iIndex = 0for temComPort in Com_Para.ComPortList.split(";"):iIndex = iIndex + 1temComPortInfo = temComPort.split(",")   try:if len(temComPortInfo) == 5 and Com_Fun.GetHashTableNone(Com_Para.htComPort, temComPortInfo[4]) is None:temCD = ComDev(temComPortInfo[0], int(temComPortInfo[1]), int(temComPortInfo[2]), int(temComPortInfo[3]), iIndex)temCD.attPortName = temComPortInfo[4]Com_Fun.SetHashTable(Com_Para.htComPort, temComPortInfo[4], temCD)except Exception as e:print("com link error:COM"+temComPortInfo[0]+"==>"  + repr(e)+"=>"+str(e.__traceback__.tb_lineno))finally:Pass

创建串口设备管理类com.zxy.comport.ComDev.py

#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''import datetime,threading,time,serial
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.zxy.common import Com_Para
from com.zxy.z_debug import z_debug#监测数据采集物联网应用--串口设备管理
class ComDev(z_debug):    attIndex    =   0attPort     =   0attBaudrate =   9600attBytesize =   8attSerial   =   None#超时时间(秒) 为了验证测试效果,将时间设置为10秒attTimeout  =   10#返回值attReturnValue  = NoneattPortName     = ""#特殊插件处理attProtocol     = ""#回发数据attSendValue    = None#线程锁attLock = threading.Lock()def __init__(self, inputPort,inputBaudrate,inputBytesize,inputparity,inputIndex):self.attPort = inputPortself.attBaudrate = inputBaudrateself.attBytesize = inputBytesizetemParity =  "N"if str(inputparity) == "0":   #无校验temParity =  "N"elif str(inputparity) == "1": #偶校验temParity =  "E"elif str(inputparity) == "2": #奇校验temParity =  "O"elif str(inputparity) == "3":temParity =  "M"elif str(inputparity) == "4":temParity =  "S"self.attSerial = serial.Serial(port=self.attPort,baudrate=self.attBaudrate,bytesize=self.attBytesize,parity=temParity, stopbits=1)self.attSerial.timeout = self.attTimeoutself.attIndex = inputIndexself.OpenSeriaPort()#打开串口def OpenSeriaPort(self):try: if not self.attSerial.isOpen():  self.attSerial.open()t = threading.Thread(target=self.OnDataReceived, name="ComPortTh" + str(self.attIndex))t.start()uL = UsAdmin_Log(Com_Para.ApplicationPath,str("ComPortTh" + str(self.attIndex)))uL.SaveFileDaySub("thread")      print("Open ComPortTh" + str(self.attIndex)+" COM:"+str(self.attSerial.port)+" "+Com_Fun.GetTimeDef()+" lenThreads:"+str(len(threading.enumerate())))return Trueexcept Exception as e:if str(type(self)) == "<class 'type'>":self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息else:self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息return Falsefinally:pass#关闭串口def CloseSeriaPort(self):try: if not self.attSerial.isOpen():  self.attSerial.close()return Trueexcept Exception as e:if str(type(self)) == "<class 'type'>":self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息else:self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息return Falsefinally:pass#发送数据无返回 def WritePortDataImmed(self,inputByte):try: if not self.attSerial.isOpen():  self.OpenSeriaPort()if self.attSerial.isOpen() and self.attLock.acquire():                    self.attReturnValue = NonetemNumber = self.attSerial.write(inputByte)time.sleep(0.2)self.attLock.release()return temNumberelse:return 0except Exception as e:if str(type(self)) == "<class 'type'>":self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息else:self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息return -1#返回值为字节,带结束符 def WritePortDataFlag(self,inputByte,EndFlag):try: if not self.attSerial.isOpen():  self.OpenSeriaPort()if self.attSerial.isOpen() and self.attLock.acquire():                    self.attReturnValue = NonetemNumber = self.attSerial.write(inputByte)    starttime = datetime.datetime.now()    endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.attTimeout)while (self.attReturnValue is None or self.attReturnValue[len(self.attReturnValue) - len(EndFlag):len(self.attReturnValue)] != EndFlag.encode(Com_Para.U_CODE)) and starttime <= endtime:starttime = datetime.datetime.now()time.sleep(0.2)                self.attLock.release()return temNumberexcept Exception as e:if str(type(self)) == "<class 'type'>":self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息else:self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息return -1finally:pass#返回值为字节 def WritePortData(self,inputByte):try: if not self.attSerial.isOpen():  self.OpenSeriaPort()if self.attSerial.isOpen() and self.attLock.acquire():                    self.attReturnValue = NonetemNumber = self.attSerial.write(inputByte)    starttime = datetime.datetime.now()    endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.attTimeout)while self.attReturnValue is None and starttime <= endtime:starttime = datetime.datetime.now()time.sleep(0.2)                self.attLock.release()return temNumberexcept Exception as e:if str(type(self)) == "<class 'type'>":self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息else:self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息return -1finally:pass#接收数据        def OnDataReceived(self):try:while self.attSerial.isOpen():temNum = self.attSerial.inWaiting()if temNum > 0:if self.attReturnValue is None:self.attReturnValue = self.attSerial.read(temNum)else:self.attReturnValue = self.attReturnValue + self.attSerial.read(temNum)else:time.sleep(1)except Exception as e:if str(type(self)) == "<class 'type'>":self.debug_in(self, repr(e)+"=>"+str(e.__traceback__.tb_lineno))else:self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))self.attReturnValue = None

串口通讯测试案例MonitorDataCmd.py主文件中编写:

在该语句下添加

       #串口配置参数Com_Para.ComPortList = "COM2,9600,8,0,A;COM4,9600,8,2,B"#串口连接初始化Init_Page.Start_ComPort()#测试串口数据发送和接收temCP2 = Com_Fun.GetHashTable(Com_Para.htComPort,"A")#获取串口2对象temCP4 = Com_Fun.GetHashTable(Com_Para.htComPort,"B")#获取串口4对象temByte1 = ("AABBCCDDVV").encode(Com_Para.U_CODE)   #发送字符串转byte[]temByte2 = ("11223344KM").encode(Com_Para.U_CODE)   #发送字符串转byte[]print("开始发送串口数据")temRec1 = temCP2.WritePortData(temByte1)#往串口2发送数据print("串口2发送数据长度:"+str(temRec1))strRec = ""if temCP2.attReturnValue != None:strRec = temCP2.attReturnValue.decode(Com_Para.U_CODE)#收到串口数据print("串口2收到数据值:"+strRec)temRec2 = temCP4.WritePortData(temByte2)#往串口4发送数据print("串口3发送数据长度:"+str(temRec2))strRec = ""if temCP4.attReturnValue != None:strRec = temCP4.attReturnValue.decode(Com_Para.U_CODE)#收到串口数据print("串口4收到数据值:"+strRec)

串口调试测试结果:

  1. 监测数据采集物联网应用开发步骤(8.1)

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

matlab的基本使用

matlab的基本使用&#xff0c;可以参考如下的教程&#xff1a;matlab教程 本文针对基本内容进行记录。 matlab简介 MATLAB是美国MathWorks公司出品的商业数学软件&#xff0c;用于数据分析、无线通信、深度学习、图像处理与计算机视觉、信号处理、量化金融与风险管理、机器人&…

浅谈多人游戏原理和简单实现。

&#x1f61c;作 者&#xff1a;是江迪呀✒️本文关键词&#xff1a;websocket、网络、原理、多人游戏☀️每日 一言&#xff1a;这世上有两种东西无法直视&#xff0c;一是太阳&#xff0c;二是人心&#xff01; 一、我的游戏史 我最开始接触游戏要从一盘300游戏…

Kafka3.0.0版本——手动调整分区副本示例

目录 一、服务器信息二、启动zookeeper和kafka集群2.1、先启动zookeeper集群2.2、再启动kafka集群 三、手动调整分区副本3.1、手动调整分区副本的前提条件3.2、手动调整分区副本的示例需求3.3、手动调整分区副本的示例 一、服务器信息 四台服务器 原始服务器名称原始服务器ip节…

【MySQL】存储引擎

1.MySQL体系结构 1). 连接层 最上层是一些客户端和链接服务&#xff0c;包含本地 sock 通信和大多数基于客户端 / 服务端工具实现的类似 于TCP/IP的通信。主要完成一些类似于连接处理、授权认证、及相关的安全方案。在该层上引入 了线程池的概念&#xff0c;为通过认证安全接…

A. Increasing and Decreasing

题目&#xff1a;样例&#xff1a; 输入 3 1 4 3 1 3 3 100 200 4输出 1 3 4 -1 100 150 180 200 思路&#xff1a; 思维题&#xff0c;这里我们看一下规律&#xff0c;我们已知a(1)&#xff0c;a(n) &#xff0c;又因为 数列b 应该是递减的&#xff0c;而观察规律可知 &#x…

活动预告 | 龙智、紫龙游戏与JFrog专家将出席龙智DevSecOps研讨会,探讨企业大规模开发创新

2023年9月8日&#xff08;周五&#xff09;下午13:30-19:45&#xff0c;龙智即将携手Atlassian与JFrog在上海共同举办主题为“大规模开发创新&#xff1a;如何提升企业级开发效率与质量”的线下研讨会。 在此次研讨会上&#xff0c;龙智高级咨询顾问、Atlassian认证专家叶燕秀…

数据库CPU飙高问题定位及解决

在业务服务提供能力的时候&#xff0c;常常会遇到CPU飙高的问题&#xff0c;遇到这类问题&#xff0c;大多不是数据库自身问题&#xff0c;都是因为使用不当导致&#xff0c;这里记录下业务服务如何定位数据库CPU飙高问题并给出常见的解决方案。 CPU 使用率飙升根因分析 在分…

动态规划之连续乘积最大子数组 连续和最大子数组

一. 连续和最大子数组 给你一个整数数组 nums &#xff0c;请你找出一个具有最大和的连续子数组&#xff08;子数组最少包含一个元素&#xff09;&#xff0c;返回其最大和。 子数组 是数组中的一个连续部分。 示例 1&#xff1a; 输入&#xff1a;nums [-2,1,-3,4,-1,2,1,-5,…

YOLOv5算法改进(8)— 替换主干网络之MobileNetV3

前言&#xff1a;Hello大家好&#xff0c;我是小哥谈。MobileNetV3是由Google团队在2019年提出的一种卷积神经网络结构&#xff0c;其目标是在保持高性能的同时减少计算延时。MobileNetV3相比于前一版本&#xff08;MobileNetV2&#xff09;在性能上有明显的提升。根据原论文&a…

jvm-堆

1.堆的核心概念 一个jvm实例只存在一个堆内存&#xff0c;堆也是java内存管理核心区域 java堆区在jvm启动的时候即被创建&#xff0c;其空间大小就确定了&#xff0c;是jvm管理最大的一块内存空间&#xff1b; 堆可以处于物理上不连续的内存空间&#xff0c;但在逻辑上它应该被…

使用Python对数据的操作转换

1、列表加值转字典 在Python中&#xff0c;将列表的值转换为字典的键可以使用以下代码&#xff1a; myList ["name", "age", "location"] myDict {k: None for k in myList} print(myDict) 输出&#xff1a; {name: None, age: None, loca…

vue中html引入使用<%= BASE_URL %>变量

首先使用src相对路径引入 注意&#xff1a; js 文件放在public文件下 不要放在assets静态资源文件下 否则 可能会报错 GET http://192.168.0.113:8080/src/assets/js/websockets.js net::ERR_ABORTED 500 (Internal Server Error) 正确使用如下&#xff1a;eg // html中引…