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

这篇具有很好参考价值的文章主要介绍了9、监测数据采集物联网应用开发步骤(7)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

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

串口(COM)通讯开发

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

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

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中添加如下内容

    @staticmethod
    def Start_ComPort():
        iIndex = 0
        for temComPort in Com_Para.ComPortList.split(";"):
            iIndex = iIndex + 1
            temComPortInfo = 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    =   0
    attPort     =   0
    attBaudrate =   9600
    attBytesize =   8
    attSerial   =   None
    #超时时间(秒) 为了验证测试效果,将时间设置为10秒
    attTimeout  =   10
    #返回值
    attReturnValue  = None
    attPortName     = ""
    #特殊插件处理
    attProtocol     = ""
    #回发数据
    attSendValue    = None
    #线程锁
    attLock = threading.Lock()
    
    def __init__(self, inputPort,inputBaudrate,inputBytesize,inputparity,inputIndex):
        self.attPort = inputPort
        self.attBaudrate = inputBaudrate
        self.attBytesize = inputBytesize
        temParity =  "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.attTimeout
        self.attIndex = inputIndex
        self.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 True
        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))#打印异常信息
            return False
        finally:
            pass

    #关闭串口
    def CloseSeriaPort(self):
        try: 
            if not self.attSerial.isOpen():  
                self.attSerial.close()
            return True
        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))#打印异常信息
            return False
        finally:
            pass
    
    #发送数据无返回 
    def WritePortDataImmed(self,inputByte):
        try: 
            if not self.attSerial.isOpen():  
                self.OpenSeriaPort()
            if self.attSerial.isOpen() and self.attLock.acquire():                    
                self.attReturnValue = None
                temNumber = self.attSerial.write(inputByte)
                time.sleep(0.2)
                self.attLock.release()
                return temNumber
            else:
                return 0
        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))#打印异常信息
            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 = None
                temNumber = 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 temNumber
        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))#打印异常信息
            return -1
        finally:
            pass
    
    #返回值为字节 
    def WritePortData(self,inputByte):
        try: 
            if not self.attSerial.isOpen():  
                self.OpenSeriaPort()
            if self.attSerial.isOpen() and self.attLock.acquire():                    
                self.attReturnValue = None
                temNumber = 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 temNumber
        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))#打印异常信息
            return -1
        finally:
            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主文件中编写:

在该语句下添加

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

       #串口配置参数
        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)

串口调试测试结果:

9、监测数据采集物联网应用开发步骤(7),物联网,python文章来源地址https://www.toymoban.com/news/detail-680722.html

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

到了这里,关于9、监测数据采集物联网应用开发步骤(7)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 11、监测数据采集物联网应用开发步骤(8.2)

    监测数据采集物联网应用开发步骤(8.1) 新建TCP/IP Client线程类 com.zxy.tcp.ClientThread.py 新建tcp client数据接收插件类1 com.plugins.Usereflect.testClientReflectClass1.py 新建tcp client数据接收插件类2 com.plugins.Usereflect.testClientReflectClass2.py 在 com.zxy.main.Init_Page.py 中添加代码 TCP Client测试案例 Monit

    2024年02月10日
    浏览(35)
  • 7、监测数据采集物联网应用开发步骤(5.3)

    监测数据采集物联网应用开发步骤(5.2) 静态配置库数据库调用,新建全局变量初始化类 com.zxy.main.Init_Page.py 数据库操作测试 MonitorDataCmd.py 主文件中编写: if __name__ == \\\'__main__\\\' : 下编写 程序执行成功结果:自动生成center_data.db 打印出数据库数据 小测试:把上文的sql语句故意语法

    2024年02月10日
    浏览(32)
  • 13、监测数据采集物联网应用开发步骤(9.2)

    监测数据采集物联网应用开发步骤(9.1) TCP/IP Server开发 新建TCP/IP Server线程类 com.zxy.tcp.ServerThread.py 新建作为TCP Server接收数据拦截器插件类 com.plugins.usereflect.testServerReflectInClass1.py 新建作为TCP Server接收数据拦截器插件类 com.plugins.usereflect.testServerReflectInClass2.py 在 com.zxy.main.Init_

    2024年02月10日
    浏览(34)
  • 物联网数据采集网关在工厂数字化转型中的应用

    物联网数据采集网关能将各种传感器、执行器等设备连接在一起,通过收集、处理和传输来自各种物理设备的信息,实现数据的集成和分析,同时可通过云平台进行数据交互。它具有数据转换、数据处理、数据传输等功能,是工厂数字化转型的核心组件。随着科技的飞速发展

    2024年02月22日
    浏览(47)
  • iNeuOS工业互联网操作系统,高效采集数据配置与应用

    1. 概述 2. 通讯原理 3. 参数配置  1.   概述 某生产企业世界500强的集团能源管控平台项目建设,通过专线网络实现异地厂区数据集成, 每个终端能源仪表都有 IP 地址,总共有1000 多台能源表计,总共有将近10000 个数据点 。在集团端部署iNeuOS工业互联网操作系统,终端能源表

    2024年02月05日
    浏览(44)
  • 【雕爷学编程】MicroPython手册之 ESP32-CAM 物联网图像数据采集应用

    MicroPython是为了在嵌入式系统中运行Python 3编程语言而设计的轻量级版本解释器。与常规Python相比,MicroPython解释器体积小(仅100KB左右),通过编译成二进制Executable文件运行,执行效率较高。它使用了轻量级的垃圾回收机制并移除了大部分Python标准库,以适应资源限制的微控制

    2024年02月20日
    浏览(36)
  • 嵌入式物联网单片机项目开发实例-4G DTU边缘数据采集网关开发

    链接:https://pan.baidu.com/s/163D-kElFqXov629YaSrWDw?pwd=1688 提取码:1688 [1.EC200S_STM32F103_4G CAT1网络TCP和UDP的透传字符串] [2.EC200S_STM32F103_4G CAT1网络TCP和UDP的透传十六进制包含0x00] [3.EC200S_STM32F103_4G CAT1通过外置MQTT协议发送定位和固定数据到ONENET] [4.EC200S_STM32F103_4G CAT1通过外置MQTT协议发送

    2024年01月16日
    浏览(43)
  • 【IoT物联网】IoT小程序在展示中央空调采集数据和实时运行状态上的应用

      利用前端语言实现跨平台应用开发似乎是大势所趋,跨平台并不是一个新的概念,“一次编译、到处运行”是老牌服务端跨平台语言Java的一个基本特性。随着时代的发展,无论是后端开发语言还是前端开发语言,一切都在朝着减少工作量,降低工作成本的方向发展。  

    2024年02月16日
    浏览(33)
  • 水库安全监测方案(实时数据采集、高速数据传输)

    ​ 一、引言 水库的安全监测对于防止水灾和保障人民生命财产安全至关重要。为了提高水库安全监测的效率和准确性,本文将介绍一种使用星创易联DTU200和SG800 5g工业路由器部署的水库安全监测方案。 二、方案概述 本方案主要通过使用星创易联DTU200和SG800 5g工业路由器实现

    2024年02月08日
    浏览(41)
  • 桥梁安全监测系统中数据采集上传用 什么?

    背景 2023年7月6日凌晨时分,G5012恩广高速达万段230公里加80米处6号大桥部分桥面发生垮塌,导致造成2车受损后自燃,3人受轻伤。目前,四川省公安厅交通警察总队高速公路五支队十四大队民警已对现场进行双向管制。 作为世界第一桥梁大国,目前我国公路桥梁数量超过100万

    2024年02月12日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包