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

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

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

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

程序自动更新开发

前面章节写了部分功能模块开发:

  1. 日志或文本文件读写开发;
  2. Sqlite3数据库读写操作开发;
  3. 定时器插件化开发;
  4. 串口(COM)通讯开发;
  5. TCP/IP Client开发;
  6. TCP/IP Server 开发;
  7. modbus协议开发;

本章节啰嗦些,该解决方案最终业务成品有些需要部署在不同工控机或设备上,在实际应用过程中随时间推移有些需要升级迭代或修改bug,一旦安装部署设备点位达到一定数量,系统自动更新升级就是一个必要的步骤了。笔者开发的业务应用在相应的设备上安装已近千台设备,鉴于此增加了程序自动更新功能模块。

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

#自动更新服务端文件夹地址
urlPath = ""
#程序版本号
version = ""

新建程序版本自动更新类com.zxy.autoUpdate.GetVersion.py
 

#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import urllib.request,datetime
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.interfaceReflect.A01_A1B2C3 import A01_A1B2C3
from com.zxy.z_debug import z_debug
from urllib.parse import urlparse

#监测数据采集物联网应用--程序版本自动更新类
class GetVersion(z_debug):

    def __init__(self):
        pass
    
    #下载文件
    def SaveRemoteFile(self,inputFileName,inputLocalFileName):
        try:
            temResult = urllib.request.urlretrieve(Com_Para.urlPath+"/"+inputFileName,Com_Para.ApplicationPath+Com_Para.zxyPath+inputLocalFileName)
        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 temResult
    
    #保存版本号文件
    def SaveVersionFile(self,version_no,inputLocalFileName):
        temStrTFileName = Com_Para.ApplicationPath+Com_Para.zxyPath+inputLocalFileName
        temFile = None
        try: 
            temFile = open(temStrTFileName, 'w',encoding=Com_Para.U_CODE)
            temFile.write(version_no)
            temFile.close()
        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))#打印异常信息
        finally:
            if temFile != None:
                temFile.close()
            
    #检测最新版本
    def CheckVersion(self):
        try:
            print("check new version..."+Com_Fun.GetTimeDef())
            #读取服务器端version.txt信息
            temResult = self.GetRequestWeb()
            if temResult == "":
                return 0
            temUL = UsAdmin_Log(Com_Para.ApplicationPath,temResult,0)
            #文件形式版本号管理
            temVersion = temUL.ReadFile(Com_Para.ApplicationPath+Com_Para.zxyPath + "version.txt")
            Com_Para.version = temVersion
            #数据库形式版本号管理
            temVersion = Com_Para.version
            temAryTem = []
            temVersion_No = ""
            temLastFile = ""
            #判断文件是否存在
            if temVersion == "" and temResult != "":
                print("local version none,downloading new version")
                temAryTem = temResult.split("\n")
                for temLine in temAryTem:
                    temLine = temLine.replace("\r","").replace("\n","")
                    temLastFile = temLine
                    if temLine.find("version=") != -1:
                        temVersion_No = temLine
                    elif temLine != "":
                        print("new version file download:"+temLine)
                        self.SaveRemoteFile(temLine,"back/"+temLine)
                        self.CopyFile(temLine)
                        if temVersion_No != "":
                            #文件形式版本管理     
                            self.SaveVersionFile(temVersion_No,"version.txt")
                            #数据库形式版本文件管理
                            #将版本号insert入库 该处代码省略....
                            Com_Para.version = temVersion_No    
                            print("new version updated over:")
                        #如果读到reboot.txt则需要重启设备
                        if temLastFile.strip() == "reboot.txt":
                            self.RebootProgram()
                            return 0
                if temVersion_No != "":
                    #文件形式版本管理     
                    print("new version updated over:")
                    self.SaveVersionFile(temVersion_No,"version.txt")
                    #数据库形式版本文件管理
                    #将版本号insert入库  该处代码省略....
                    Com_Para.version = temVersion_No
            elif temResult != "":
                #数据库形式版本号管理
#                 localVersion = Com_Para.version
                #文件形式版本号管理
                temAryTem = temVersion.split("\n")
                for temLine in temAryTem:
                    temArySub = temLine.split("=")
                    if len(temArySub) > 1 and temArySub[0] == "version":
                        localVersion = temArySub[1]
                        break 
                bFlag = False
                temAryTem = temResult.split("\n")
                for temLine in temAryTem:
                    temLine = temLine.replace("\r","").replace("\n","")
                    temLastFile = temLine
                    temArySub = temLine.split("=")
                    if len(temArySub) > 1 and temArySub[0] == "version":
                        try:
                            if localVersion.find("=") != -1:
                                iLV = int(localVersion.split("=")[1])
                            else:
                                iLV = int(localVersion)
                                
                            if localVersion != "" and iLV >= int(temArySub[1]):
                                bFlag = False
                            else:
                                temVersion_No = temLine
                                bFlag = True
                        except:
                            bFlag = False
                            break
                    else:
                        if bFlag:
                            self.SaveRemoteFile(temLine,"back/"+temLine)
                            self.CopyFile(temLine)
                            if temVersion_No != "":
                                #文件形式版本管理     
                                self.SaveVersionFile(temVersion_No,"version.txt") 
                                #数据库形式版本文件管理  
                                #将版本号insert入库  该处代码省略....
                                Com_Para.version = temVersion_No
                                print("new version updated over:"+temVersion_No)
                            if temLastFile.strip() == "reboot.txt":
                                self.RebootProgram()
                                return 0
                                    
                if (bFlag and temVersion_No != ""):
                    #文件形式版本管理     
                    self.SaveVersionFile(temVersion_No,"version.txt")
                    #数据库形式版本文件管理  
                    #将版本号insert入库  该处代码省略....
                    Com_Para.version = temVersion_No
                    print("new version updated over:")
                if bFlag and temLastFile.strip() == "reboot.txt":
                    self.RebootProgram()
                    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 RebootProgram(self):        
        aa = A01_A1B2C3()
        if Com_Para.devsys.lower() == "linux": 
            aa.param_value2 = "reboot -f"
            aa.CmdExecLinux()
        else:
            aa.param_value2 = "shutdown -r"
            aa.CmdExecWin()
        
    #文件更新
    def CopyFile(self,inputWebFile):
        temAryTem = inputWebFile.split("\n")
        for temLine in temAryTem:
            if temLine.find("=") == -1:
                aa = A01_A1B2C3()
                temFileName = temLine[0:temLine.find(".")]
                temFileAtt = temLine[temLine.find("."):len(temLine)].upper()
                if temFileAtt.upper() == ".ZIP":
                    aa.param_value2 = "unzip -o "+Com_Para.ApplicationPath+Com_Para.zxyPath+"back"+Com_Para.zxyPath+temLine+" -d "+Com_Para.ApplicationPath+Com_Para.zxyPath+"back"+Com_Para.zxyPath+temFileName+Com_Para.zxyPath
                    aa.param_value3 = Com_Para.ApplicationPath+Com_Para.zxyPath+"back"+Com_Para.zxyPath+temLine
                    aa.param_value4 = Com_Para.ApplicationPath+Com_Para.zxyPath+"back"+Com_Para.zxyPath+temFileName+Com_Para.zxyPath
                    #利用命令进行解压缩
                    #aa.CmdExecLinux()
                    #利用python自带解压缩模块
                    aa.unzip_file()                     
                    if Com_Para.devsys.lower() == "linux":                 
                        aa.param_value2 = "cp -rf "+Com_Para.ApplicationPath+Com_Para.zxyPath+"back"+Com_Para.zxyPath+temFileName+Com_Para.zxyPath+"* "+Com_Para.ApplicationPath+Com_Para.zxyPath
                    else:
                        aa.param_value2 = "xcopy "+Com_Para.ApplicationPath+Com_Para.zxyPath+"back"+Com_Para.zxyPath+temFileName+Com_Para.zxyPath+"*.* "+Com_Para.ApplicationPath+" /E /Y"
                    aa.CmdExecLinux()
                #执行sql语句
                elif temFileAtt.upper() == ".SQL":
                    aa.RunSqlFile(Com_Para.ApplicationPath+Com_Para.zxyPath+"back"+Com_Para.zxyPath+temLine)
                #执行更新数据接口
                elif temFileAtt.upper() == ".JSON":
                    #JSON业务数据进行数据库结构更改或升级
                    pass
                else:
                    if Com_Para.devsys.lower() == "linux":                 
                        aa.param_value2 = "cp -rf "+Com_Para.ApplicationPath+Com_Para.zxyPath+"back"+Com_Para.zxyPath+temLine+" "+Com_Para.ApplicationPath+Com_Para.zxyPath
                    else:
                        aa.param_value2 = "copy "+Com_Para.ApplicationPath+Com_Para.zxyPath+"back"+Com_Para.zxyPath+temLine+" "+Com_Para.ApplicationPath+Com_Para.zxyPath+" /Y"
                    aa.CmdExecLinux()
    
    #inputFlag网络链接是否正常
    def set_dSockList(self,inputFlag):
        urlp = urlparse(Com_Para.urlPath)
        if Com_Para.urlPath == "":
            return None                
        key = str(urlp.netloc.replace(":","|")) 
        #存在
        if key not in list(Com_Para.dSockList.keys()):
            Com_Para.dSockList[key] = [0,datetime.datetime.now()]
        if inputFlag == False:
            objAry = Com_Para.dSockList[key]
            if objAry[0] <= 10:
                objAry[0] = objAry[0] + 1
            objAry[1] = datetime.datetime.now()
            Com_Para.dSockList[key] = objAry
        else:
            Com_Para.dSockList[key] = [0,datetime.datetime.now()]    
    
    #判断上次链接时间频率是否合规
    def judge_dSock(self):
        urlp = urlparse(Com_Para.urlPath)
        if Com_Para.urlPath == "":
            return False                
        key = str(urlp.netloc.replace(":","|")) 
        if key not in list(Com_Para.dSockList.keys()):
            Com_Para.dSockList[key] = [0,datetime.datetime.now()]
        objAry = Com_Para.dSockList[key]
        starttime = datetime.datetime.now()
        if objAry[0] <= 3:
            return True
        elif objAry[0] > 4 and starttime >= objAry[1] + datetime.timedelta(hours=12):
            return True
        else:
            return False
            
    def GetRequestWeb(self):
        temResult = ""
        try:
            #判断上次链接时间频率是否合规
            if not self.judge_dSock():
                return ""
            resp = urllib.request.urlopen(Com_Para.urlPath+"/version.txt",timeout=5)
            temResult = resp.read().decode(Com_Para.U_CODE)        
        except Exception as e:
            temLog = ""
            if str(type(self)) == "<class 'type'>":
                temLog = self.debug_info(self)+repr(e)
            else:
                temLog = self.debug_info()+repr(e)
            uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog+"=>"+str(e.__traceback__.tb_lineno))
            uL.WriteLog()
            temResult = ""
            self.set_dSockList(False)
        return temResult

新建操作系统执行指令接口类com.zxy.interfaceReflect.A01_A1B2C3.py

#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import os, sys,zipfile,subprocess,tempfile
from urllib.parse import unquote
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.z_debug import z_debug

#监测数据采集物联网应用--操作系统执行指令接口类
class A01_A1B2C3(z_debug):
    strResult        = ""
    session_id       = ""
    param_name       = ""
    param_value1     = None  #1:同步更新设备时间
    param_value2     = None  #当前时间
    param_value3     = None
    param_value4     = None
    param_value5     = None
    param_value6     = None
    param_value7     = None
    param_value8     = None
    param_value9     = None
    param_value10    = None
    #是否继续执行 1:继续执行 0:中断执行
    strContinue      = "0"
    strCmdValue     = ""
    
    def __init__(self):
        pass
        
    def init_start(self):       
#         /**************************************************/
#         //示例: 此处写业务逻辑,最后给 param_name,param_value1....重新赋值 
#         // param_name += Com_Fun.Get_New_GUID()
#         // param_value1 += Com_Fun.Get_New_GUID()
#         // param_value2 += Com_Fun.Get_New_GUID()
#         // ......
        
#         /**************************************************/
#         //示例:若业务逻辑判断失败,不发送数据库接口请求并返回失败信息
        #strContinue      = "0" 表示拦截器判断接口执行结束,不需要入库操作,直接返回信息
        temValue = ""
        self.strContinue = "0"
        if self.param_value1 == "100" and Com_Para.devsys == "linux":
            temValue = self.CmdExecLinux(self)
            self.strResult = "命令结果:\r\n"
            for temR in temValue:
                self.strResult = self.strResult+temR.decode(Com_Para.U_CODE)+"\r\n"
        #100执行命令
        elif self.param_value1 == "100" and Com_Para.devsys == "windows":
            temValue = self.CmdExecWin(self)
            self.strResult = "{\""+self.param_name+"\":[{\"s_result\":\"1\",\"error_desc\":\"命令执行成功"+temValue+"\"}]}"
       
    #利用python自带解压缩
    def unzip_file(self):
        temzipfile = zipfile.ZipFile(self.param_value3, 'r')
        temzipfile.extractall(self.param_value4)        
    
    #重启程序
    def RestartPro(self):
        python = sys.executable
        os.execl(python,python,* sys.argv)
        
    #执行命令(Linux)
    def CmdExecLinux(self):
        out_temp = None
        try:       
            temCommand = unquote(unquote(self.param_value2,Com_Para.U_CODE))
            out_temp = tempfile.SpooledTemporaryFile(max_size=10*1000)
            fileno = out_temp.fileno()
            obj = subprocess.Popen(temCommand,stdout=fileno,stderr=fileno,shell=True)
            obj.wait()            
            out_temp.seek(0)
            temResult = out_temp.readlines()              
        except Exception as e:
            temResult = repr(e)
        finally:
            if out_temp is not None:
                out_temp.close()
        return temResult
    
    #执行命令(Windows)
    def CmdExecWin(self):
        try:
            temCommand = unquote(unquote(self.param_value2,Com_Para.U_CODE))
            temResult = os.popen(temCommand).read()
        except Exception as e:
            temResult = repr(e)
        return temResult
    
    #更新设备时间(Windows)
    def ChangeDateWin(self):
        try:
            temDate = Com_Fun.GetDateInput('%Y-%m-%d', '%Y-%m-%d %H:%M:%S', unquote(unquote(self.param_value2.replace("+"," "),Com_Para.U_CODE)))
            temTime = Com_Fun.GetDateInput('%H:%M:%S', '%Y-%m-%d %H:%M:%S', unquote(unquote(self.param_value2.replace("+"," "),Com_Para.U_CODE)))
            temResult = os.system('date {} && time {}'.format(temDate,temTime))
        except:
            temResult = -1
        return temResult
    
    #更新设备时间(Linux)
    def ChangeDateLinux(self):
        try:            
            #将硬件时间写入到系统时间:
            #hwclock -s
            #将系统时间写入到硬件时间
            #hwclock -w
            temCommand = unquote(unquote("date -s \""+self.param_value2.replace("+"," ").split(" ")[0]+"\"",Com_Para.U_CODE))
            temCommand = unquote(unquote("date -s \""+self.param_value2.replace("+"," ").split(" ")[1]+"\"",Com_Para.U_CODE))
            out_temp = tempfile.SpooledTemporaryFile(max_size=10*1000)
            fileno = out_temp.fileno()
            obj = subprocess.Popen(temCommand,stdout=fileno,stderr=fileno,shell=True)
            obj.wait()
            temCommand = unquote(unquote("hwclock -w",Com_Para.U_CODE))
            obj = subprocess.Popen(temCommand,stdout=fileno,stderr=fileno,shell=True)
            obj.wait()         
            out_temp.seek(0)
            temByt = out_temp.readlines()
            temResult = temByt[0].decode(Com_Para.U_CODE)
            if temResult == "" :
                temResult = "1"
        except Exception as e:
            temResult = "-1"        
        finally:
            if out_temp is not None:
                out_temp.close()
        return temResult

版本更新测试案例MonitorDataCmd.py主文件中编写:

from com.zxy.autoUpdate.GetVersion import GetVersion

在    if __name__ == '__main__':下添加

        #版本更新测试

        Com_Para.urlPath = "http://localhost:8080/testweb/updtest/"

        gv = GetVersion()    

        gv.CheckVersion()

        print("=>版本更新完成")

程序文件新建15、监测数据采集物联网应用开发步骤(11),python,物联网back文件夹临时存放下载更新包的zip文件;

版本更新服务端文件信息15、监测数据采集物联网应用开发步骤(11),python,物联网

版本更新服务端版本号信息

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

运行结果设备端更新之后新增文件

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

更新文件已下载并自动解压缩成功。

print打印出的内容

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

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

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

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

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

相关文章

  • 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日
    浏览(29)
  • 7、监测数据采集物联网应用开发步骤(5.3)

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

    2024年02月10日
    浏览(29)
  • 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日
    浏览(31)
  • 物联网数据采集网关在工厂数字化转型中的应用

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

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

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

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

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

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

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

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

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

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

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

    2024年02月12日
    浏览(30)
  • 工程监测振弦采集仪采集到的数据如何进行分析和处理

    工程监测振弦采集仪采集到的数据如何进行分析和处理 振弦采集仪是一个用于测量和记录物体振动的设备。它通过测量物体表面的振动来提取振动信号数据,然后将其转换为数字信号,以便进行分析和处理。在实际应用中,振弦采集仪是广泛应用于机械、建筑、航空航天和汽

    2024年02月12日
    浏览(33)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包