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

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

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

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

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

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

python 复制代码
#修改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中添加代码

python 复制代码
            
    #web数据接口返回值参数大小写
    @staticmethod
    def 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

python 复制代码
#! 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 = 1
    attErr_desc = "成功"
    
    def __init__(self):
        pass
    
    def 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 = 0
    attS_result = 1
    
    def __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转Json
    def 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

python 复制代码
#! 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 = 0
    
    def __init__(self, inputStrValue,inputNum,inputPort):
        self.attStrNum = inputNum
        self.attStrValue = inputStrValue
        self.attPort = inputPort
            
    def run(self):
        temS = None
        try:
            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 = sock
                    temServerHH.attStrIP = addr
                    t1 = 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))#打印异常信息
                    pass
        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))#打印异常信息
            pass 

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

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

import os

from 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 = None
    attStrIP = "0.0.0.0"
    attReturn_Value = Return_Value()
    attConnection = ""
    
    def __init__(self):
        pass
    
    def run(self):
        self.server_link()
        
    def server_link(self):
        Com_Para.socket_count = Com_Para.socket_count + 1
        if 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.ApplicationPath
        if 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+temFUrl
        temFilePath = temFilePath + inputWeb_name        
        if os.path.exists(temFilePath):
            bVue = False
            #自定义页面组件后缀
            if inputStrUrl.find(".dlls") != -1 and inputStrUrl.find(".dlls") == len(inputStrUrl) - len(".dlls"):
                bVue = True
            temFile = None
            try:
                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: #如果没有读到数据,跳出循环
                        break
                if 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.attConnection
        temStrUrl = temRequest.attUri
        temPost_Str = temRequest.attPost_str
        self.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.HttpUrl
        temReturnMessage += "\r\n" + "Connection: Keep-Alive"
        temStrResult = "-1"
        temGd = Query_Data(self.attReturn_Value)
        #通用接口
        bWeb_Name =  False
        for 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 = True
                break
        if bWeb_Name == True or temRequest.attUploadFile != "":
            pass
        elif 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.attServSocket
            temRequest.attStrIP = self.attStrIP
            self.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_id
            temStrAry = 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)
相关推荐
denghai邓海11 分钟前
红黑树删除之向上调整
python·b+树
封步宇AIGC37 分钟前
量化交易系统开发-实时行情自动化交易-3.4.1.2.A股交易数据
人工智能·python·机器学习·数据挖掘
何曾参静谧37 分钟前
「Py」Python基础篇 之 Python都可以做哪些自动化?
开发语言·python·自动化
Prejudices41 分钟前
C++如何调用Python脚本
开发语言·c++·python
我狠狠地刷刷刷刷刷1 小时前
中文分词模拟器
开发语言·python·算法
Jam-Young1 小时前
Python的装饰器
开发语言·python
Mr.咕咕1 小时前
Django 搭建数据管理web——商品管理
前端·python·django
AnFany2 小时前
LeetCode【0028】找出字符串中第一个匹配项的下标
python·算法·leetcode·字符串·kmp·字符串匹配
爪哇学长2 小时前
Java API类与接口:日期类型与集合的使用
java·开发语言·python
EterNity_TiMe_2 小时前
【论文复现】STM32设计的物联网智能鱼缸
stm32·单片机·嵌入式硬件·物联网·学习·性能优化