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

2023-10-20 12:04

本文主要是介绍16、监测数据采集物联网应用开发步骤(12.1),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

阶段性源码将于本章节末尾给出下载

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

本章节进行前端web UI开发+web数据接口服务开发

web数据接口服务利用SOCKET TCP服务方式解析http协议内容模式

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

#修改web数据接口服务端口
port = 9000
#是否启用http协议
bThread = True
#web数据接口访问函数名
Inf_Name = "CenterData"
#web文件后缀{}
web_Name = [".html", ".js", ".css", ".jpg", ".gif", ".png", ".svg", ".eot", ".ttf", ".woff2", ".woff", ".ico" ,".json", ".log",".xlsx",".xls",".vue",".dlls"]
#web数据接口返回值字段大小写,0不设置  1大写 2小写
iReturnUppLower = 1
#web数据接口TCP连接socket统计
socket_count = 0
#指定跨域访问IP xxx.xx.xx.xxx 默认为空
HttpUrl = ""
#上传文件后缀
attUpFile = ".txt|.zip|.rar|.tar|.json|.jpg|.bmp|.gif|.xls|.xlsx|.sql|.doc|.docx|"

com.zxy.common.Com_Fun.py中添加代码

            #web数据接口返回值参数大小写@staticmethoddef GetLowUpp(inputValue):if Com_Para.iReturnUppLower == 1:return inputValue.upper()elif Com_Para.iReturnUppLower == 2:return inputValue.lower()else:return inputValue

新建web数据接口返回格式类com.zxy.model.Return_Value.py

#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''
from com.zxy.common.Com_Fun import Com_Fun#监测数据采集物联网应用--web数据接口返回格式
class Return_Value(object):attParam_name = "COMMOND_NAME"attS_result = 1attErr_desc = "成功"def __init__(self):passdef Back_Value(self):return "{\""+self.attParam_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\""+self.attS_result+"\",\""+Com_Fun.GetLowUpp("err_desc")+"\":\""+self.attErr_desc+"\"}]}"新建数据业务处理和获取类com.zxy.business.Ope_DB_Cent.py
#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''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.db_Self.Db_Common_Self import Db_Common_Self
from com.zxy.z_debug import z_debug#监测数据采集物联网应用--数据业务处理、获取
class Ope_DB_Cent(z_debug):attICount = 0attS_result = 1def __init__(self):pass#带参数数据库读写
#     temSqlIns = "insert into xxx(x,x,x) values(?,?,?)
#     temParameters = []
#     temParamTypes = []
#     temParamOutName = []
#     temParamOutType = []
#     iIndex = 0
#     try:
#         temDb_self = Db_Common_Self()
#         temTpn = T_PROC_NAME()
#         temTpn.attINF_EN_SQL = temSqlIns        
#         temDb_self.Common_Sql_Proc("Ins_Data_JSON",temParameters,temParamTypes,temParamOutName,temParamOutType,temTpn)
#         #temSqlException = temDb_self.attSqlException
#         #temColumnNames = temDb_self.attColumnNames
#     except Exception as es:
#         temError = "get data error[Ins_Data_JSON]" +temSqlIns+") "+temstrSqlValues+")" +"\r\n"+repr(es)
#         uL = UsAdmin_Log(Com_Para.ApplicationPath, temError)
#         uL.WriteLog()#resultSet转Jsondef ResultSetToJson(self,input_sql):temDbSelf = Db_Common_Self()temRs = temDbSelf.Common_Sql(input_sql)temColumnNames = temDbSelf.attColumnNames        jsary1 = []try:for temItem in temRs:temjso1 = {}for i in range(0,len(temColumnNames)):if temItem[i] != "null":temjso1[Com_Fun.GetLowUpp(temColumnNames[i][0])] = temItem[i]else:temjso1[Com_Fun.GetLowUpp(temColumnNames[i][0])] = ""jsary1.append(temjso1)except Exception as e:temLog = ""if str(type(self)) == "<class 'type'>":temLog = self.debug_info(self)+input_sql+"==>"+repr(e)self.debug_in(self,input_sql+"==>"+repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息else:temLog = self.debug_info(self)+input_sql+"==>"+repr(e)self.debug_in(input_sql+"==>"+repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)uL.WriteLog()return jsary1#数据业务处理、获取def Cal_Data(self, inputSub_code, inputParam_name, inputAryParamValue, inputStrIP,inputSession_id,inputHtParam):temResult = ""if inputParam_name == "init_page":#写读取缓存内容return "{\"" + inputParam_name + "\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"读取缓存信息成功!\"}]}"elif inputParam_name == "A01_AAA111":return "{\"" + inputParam_name + "\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"后台获取的业务时间:"+Com_Fun.GetTimeDef()+"\"}]}"elif inputParam_name == "A01_AAA222":return "{\"" + inputParam_name + "\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"后台获取的GUID:"+Com_Fun.Get_New_GUID()+"\"}]}"return temResult

新建web数据接口业务查询类com.zxy.business.Query_Data.py

#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''from com.zxy.z_debug import z_debug
from com.zxy.model.Return_Value import Return_Value
from com.zxy.business.Ope_DB_Cent import Ope_DB_Cent#监测数据采集物联网应用--web数据接口业务查询
class Query_Data(z_debug):attSession_id    = ""attReturn_Value  = Return_Value()def __init__(self,inputReturn_Value):self.attReturn_Value = inputReturn_Value#后台数据处理def GetDataList(self,inputSub_code, inputSub_usercode, inputParam_name, inputAryParamValue, inputStrUrl, inputDelay_data, inputDelay_code, inputStrIP,inputHtParam):temOpd = Ope_DB_Cent()temResult = temOpd.Cal_Data(inputSub_code,inputParam_name,inputAryParamValue,inputStrIP,self.attSession_id,inputHtParam)return temResult新建web数据接口socket服务类com.zxy.tcp.ServerThreadHttp.py
#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''import socket,threading
from com.zxy.z_debug import z_debug
from com.zxy.tcp.ServerHandlerHttp import ServerHandlerHttp#监测数据采集物联网应用--web数据接口socket服务
class ServerThreadHttp(z_debug):attStrValue = ""attStrNum = ""attPort = 0def __init__(self, inputStrValue,inputNum,inputPort):self.attStrNum = inputNumself.attStrValue = inputStrValueself.attPort = inputPortdef run(self):temS = Nonetry:temS = socket.socket(socket.AF_INET, socket.SOCK_STREAM)temS.bind(('0.0.0.0', self.attPort))temS.listen(400)while True:try:sock,addr = temS.accept()sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)temServerHH = ServerHandlerHttp()temServerHH.attServSocket = socktemServerHH.attStrIP = addrt1 = threading.Thread(target=temServerHH.run, name="ServerHttpThread"+"_"+str(addr[0])+"_"+str(addr[1]))t1.start()except Exception as en:if str(type(self)) == "<class 'type'>":self.debug_in(self,repr(en)+"=>"+str(en.__traceback__.tb_lineno))#打印异常信息else:self.debug_in(repr(en)+"=>"+str(en.__traceback__.tb_lineno))#打印异常信息passexcept 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))#打印异常信息pass 

新建web数据接口服务Handler类com.zxy.tcp.ServerHandlerHttp.py

#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''import osfrom com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.zxy.business.Query_Data import Query_Data
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.model.Return_Value import Return_Value
from com.zxy.tcp.Request import Request
from com.zxy.z_debug import z_debug#监测数据采集物联网应用--web数据接口服务Handler
class ServerHandlerHttp(z_debug):attServSocket = NoneattStrIP = "0.0.0.0"attReturn_Value = Return_Value()attConnection = ""def __init__(self):passdef run(self):self.server_link()def server_link(self):Com_Para.socket_count = Com_Para.socket_count + 1if Com_Para.driverClassName == "org.sqlite.JDBC":self.init()else:self.init()Com_Para.socket_count = Com_Para.socket_count - 1#web文件内容加载,如:html css js......def webPage_Real(self,inputStrUrl,inputS_guid,inputPost_str,inputQuery_Data,inputReturnMessage,inputWeb_name):temFilePath = Com_Para.ApplicationPath +Com_Para.zxyPath+ "web"if inputWeb_name == ".log":temFilePath = Com_Para.ApplicationPathif inputStrUrl[0:10] =="/root_api/":temFUrl = inputStrUrl[10:inputStrUrl.index(inputWeb_name)]else:temFUrl = inputStrUrl[0:inputStrUrl.index(inputWeb_name)]temFilePath = temFilePath + Com_Para.zxyPath+temFUrltemFilePath = temFilePath + inputWeb_name        if os.path.exists(temFilePath):bVue = False#自定义页面组件后缀if inputStrUrl.find(".dlls") != -1 and inputStrUrl.find(".dlls") == len(inputStrUrl) - len(".dlls"):bVue = TruetemFile = Nonetry:temFile = open(file=temFilePath,mode='rb')                self.attServSocket.send((inputReturnMessage +"\r\n\r\n").encode(Com_Para.U_CODE))if bVue:self.attServSocket.send(b'ReadCommonRes("')while True:byt = temFile.read(1024)# 每次读取1024个字节if bVue :self.attServSocket.send(byt.replace(b'\t',b'').replace(b'\n',b'').replace(b'\r',b'').replace(b'\"',b'\\\"').replace(b'$',b'"'))else:self.attServSocket.send(byt)#字节形式发送数据                    if not byt: #如果没有读到数据,跳出循环breakif bVue:self.attServSocket.send(b'");')self.attServSocket.send("\r\n".encode(Com_Para.U_CODE))                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 not temFile is None:temFile.close()else:temErrorMessage = "HTTP/1.1 404 File Not Found\r\n"temErrorMessage += "Content-Type: text/html\r\n"temErrorMessage += "Content-Length: 230\r\n"temErrorMessage += "\r\n" + "<h1>未找到正确页面</h1>"try:self.attServSocket.send(temErrorMessage.encode(Com_Para.U_CODE))self.attServSocket.send("\r\n".encode(Com_Para.U_CODE))except Exception as e:pass#解析http协议def SubAnalyseRecBytes(self,temRequest):temS_guid = "" temRequest.parse()self.attConnection = temRequest.attConnectiontemStrUrl = temRequest.attUritemPost_Str = temRequest.attPost_strself.attReturn_Value = temRequest.attRv        temReturnMessage = "HTTP/1.1 200 OK\r\n"if temStrUrl.find(".html") != -1 and temStrUrl.find(".html") == len(temStrUrl) - 5:temReturnMessage += "Content-Type: text/html\r\n"elif temStrUrl.find(".js") != -1 and temStrUrl.find(".js") == len(temStrUrl) - 3:temReturnMessage += "Content-Type: application/x-javascript\r\n"elif temStrUrl.find(".css") != -1 and temStrUrl.find(".css") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: text/css\r\n"elif temStrUrl.find(".jpg") != -1 and temStrUrl.find(".jpg") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: image/jpg\r\n"elif temStrUrl.find(".gif") != -1 and temStrUrl.find(".gif") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: image/jpg\r\n"elif temStrUrl.find(".png") != -1 and temStrUrl.find(".png") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: mage/png\r\n"elif temStrUrl.find(".svg") != -1 and temStrUrl.find(".svg") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: text/svg+xml\r\n"elif temStrUrl.find(".eot") != -1 and temStrUrl.find(".eot") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: application/vnd.ms-fontobject\r\n"elif temStrUrl.find(".ttf") != -1 and temStrUrl.find(".ttf") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: application/x-font-ttf\r\n"elif temStrUrl.find(".woff") != -1 and temStrUrl.find(".woff") == len(temStrUrl) - 5:temReturnMessage += "Content-Type: application/x-font-woff\r\n"elif temStrUrl.find(".woff2") != -1 and temStrUrl.find(".woff2") == len(temStrUrl) - 6:temReturnMessage += "Content-Type: application/x-font-woff\r\n"elif temStrUrl.find(".ico") != -1 and temStrUrl.find(".ico") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: image/ico\r\n"                elif temStrUrl.find(".log") != -1 and temStrUrl.find(".log") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: text\r\n"elif temStrUrl.find(".dlls") != -1 and temStrUrl.find(".dlls") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: application/x-javascript\r\n"elif temStrUrl.find(".vue") != -1 and temStrUrl.find(".vue") == len(temStrUrl) - 4:temReturnMessage += "Content-Type: application/x-javascript\r\n"else:temReturnMessage += "Content-Type: text/html\r\n"temReturnMessage += "Access-Control-Allow-Methods: POST,GET\r\n"temReturnMessage += "Access-Control-Allow-Origin:*" + Com_Para.HttpUrltemReturnMessage += "\r\n" + "Connection: Keep-Alive"temStrResult = "-1"temGd = Query_Data(self.attReturn_Value)#通用接口bWeb_Name =  Falsefor temAttF in Com_Para.web_Name:if temStrUrl.find(temAttF) != -1 and temStrUrl.find(temAttF) == len(temStrUrl) - len(temAttF) and temStrUrl.find("param_name=") == -1:self.webPage_Real(temStrUrl,temS_guid,temPost_Str,temGd,temReturnMessage,temAttF)bWeb_Name = Truebreakif bWeb_Name == True or temRequest.attUploadFile != "":passelif temStrUrl.find("sub_code=") != -1 and temStrUrl.find("param_name=") != -1:                temStrResult = self.Center_Data_Rel(temStrUrl,temS_guid,temPost_Str,temGd,temReturnMessage,temRequest.attStrIP[0])elif temStrUrl.strip() == "" and temStrUrl.strip().find("GET /favicon.ico HTTP/1.1") != -1:                temStrResult = self.Send_Error(temStrUrl,temS_guid,temPost_Str,temGd,temReturnMessage)elif temStrUrl.strip() != "":self.attServSocket.send((temReturnMessage+"\r\n\r\n请求错误接口或页面\r\n").encode(Com_Para.U_CODE))if temRequest.attUploadFile != "":self.attServSocket.send((temReturnMessage + "\r\n\r\n" + temRequest.attUploadFile  + "\r\n").encode(Com_Para.U_CODE))              elif temStrResult != "-1":self.attServSocket.send((temReturnMessage + "\r\n\r\n" + temStrResult + "\r\n").encode(Com_Para.U_CODE))              return temReturnMessage#初始化def init(self):try:temRequest = Request()temRequest.attServSocket = self.attServSockettemRequest.attStrIP = self.attStrIPself.attServSocket.setblocking(1)temReturnMessage = self.SubAnalyseRecBytes(temRequest)except Exception as e:self.attServSocket.send(temReturnMessage+"\r\n\r\n"+repr(e)+"\r\n".encode(Com_Para.U_CODE))temLog = ""if str(type(self)) == "<class 'type'>":temLog = self.debug_info(self)+repr(e)self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息else:temLog = self.debug_info()+repr(e)self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)uL.WriteLog()            finally:self.attServSocket.shutdown(1)self.attServSocket.close()def Send_Error(self,inputStrUrl,inputS_guid,inputPost_Str,inputGd,inputReturnMessage):inputReturnMessage = "Error请求语法错误"return inputReturnMessage#通用获取数据接口    def Center_Data_Rel(self,inputStrUrl, inputS_guid, inputPost_Str, inputGd, inputReturnMessage, inputStrIP):temStrAry = ""#<String,String>temHtParam = {}for temStrTemV in inputStrUrl.split("&"):temStrTemPar = temStrTemV.split("=")if len(temStrTemPar) == 2:Com_Fun.SetHashTable(temHtParam,temStrTemPar[0],temStrTemPar[1])else:Com_Fun.SetHashTable(temHtParam,temStrTemPar[0],"")temSub_code = Com_Fun.GetHashTable(temHtParam,"sub_code")temSub_usercode = Com_Fun.GetHashTable(temHtParam,"sub_usercode")temDelay_data = Com_Fun.GetHashTable(temHtParam,"delay_data")temDelay_code = Com_Fun.GetHashTable(temHtParam,"delay_code")temParam_name = Com_Fun.GetHashTable(temHtParam,"param_name")temSession_id = Com_Fun.GetHashTable(temHtParam,"session_id")temJsoncallback = Com_Fun.GetHashTable(temHtParam,"jsoncallback")self.attReturn_Value.attParam_name = temParam_name#传递in 参数<String>temAryParamValue = []for temTemstr in inputPost_Str:if temTemstr == "jsonpzxyong":temJsoncallback = temTemstr.split("=")[1]break#获取版本号if temParam_name == "get_version":temStrAry = "{\""+ temParam_name+ "\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"\",\""+Com_Fun.GetLowUpp("version")+"\":\""+Com_Para.version+"\"}]}"#通用数据接口else:inputGd.attSession_id = temSession_idtemStrAry = inputGd.GetDataList(temSub_code,temSub_usercode,temParam_name,temAryParamValue,inputStrUrl,temDelay_data,temDelay_code,inputStrIP,temHtParam)if temJsoncallback != "":temStrAry = temJsoncallback + "("+temStrAry+")"if self.attReturn_Value.attS_result == 1:self.attReturn_Value = inputGd.attReturn_Value        temHtParam = None        return temStrAry

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

这篇关于16、监测数据采集物联网应用开发步骤(12.1)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/246979

相关文章

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

SpringBoot 多环境开发实战(从配置、管理与控制)

《SpringBoot多环境开发实战(从配置、管理与控制)》本文详解SpringBoot多环境配置,涵盖单文件YAML、多文件模式、MavenProfile分组及激活策略,通过优先级控制灵活切换环境... 目录一、多环境开发基础(单文件 YAML 版)(一)配置原理与优势(二)实操示例二、多环境开发多文件版

使用docker搭建嵌入式Linux开发环境

《使用docker搭建嵌入式Linux开发环境》本文主要介绍了使用docker搭建嵌入式Linux开发环境,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录1、前言2、安装docker3、编写容器管理脚本4、创建容器1、前言在日常开发全志、rk等不同

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

Python实战之SEO优化自动化工具开发指南

《Python实战之SEO优化自动化工具开发指南》在数字化营销时代,搜索引擎优化(SEO)已成为网站获取流量的重要手段,本文将带您使用Python开发一套完整的SEO自动化工具,需要的可以了解下... 目录前言项目概述技术栈选择核心模块实现1. 关键词研究模块2. 网站技术seo检测模块3. 内容优化分析模

Linux搭建ftp服务器的步骤

《Linux搭建ftp服务器的步骤》本文给大家分享Linux搭建ftp服务器的步骤,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录ftp搭建1:下载vsftpd工具2:下载客户端工具3:进入配置文件目录vsftpd.conf配置文件4: