py实现网关功能

来源:互联网 发布:ubuntu更新内核命令 编辑:程序博客网 时间:2024/06/05 08:36

python实现读取串口,发送数据到服务器


myTestSeria.py

#启动程序
from conf1 import Conf

if __name__ == '__main__':
    conf = Conf()
    conf.run()

#数格式据
##FF 00 01 07 00 1C 2A FF 00 03 06 00 10 FF 00 02 08 00 62
##FF 00 01 07 00 1C 2A FF 00 03 06 00 10 FF 00 02 08 00 61
##FF 00 01 07 00 1C 2A FF 00 03 06 00 10 FF 00 02 08 00 62
##FF 00 01 07 00 1C 2A FF 00 03 06 00 10 FF 00 02 08 00 62
##FF 00 01 07 00 1C 2A FF 00 03 06 00 10 FF 00 02 08 00 61 
    

conf1.py

#参考的博客

##http://blog.csdn.net/fireroll/article/details/38865743
##http://www.th7.cn/Program/Python/201501/343145.shtml
##http://lihf198628.blog.163.com/blog/static/1138145200910210535337/
##http://ju.outofmemory.cn/entry/52646
##https://pypi.python.org/pypi?%3Aaction=search&term=SocketServer&submit=search
##http://blog.csdn.net/hcx25909/article/details/50537939
##http://www.cnblogs.com/Dreamxi/p/4109450.htm
##是一个完整的例子

#open configure info
import urllib
import http.client,httplib2
import demjson
import configparser
import serial
import socket
import json
import threading
import binascii

class Conf:
    __cfg = {
            'hardware' : {},
            'send'     : {},
            'recv'     : {},
            'log'      : {}
        } #collection,info
    
    __serial = None
    __mac    = None
    __readDataLen = 19#56#19
    __separator = ' ' #分隔符

    
    def __init__(self): #初始化函数
        self.__loadConfig()
        self.__initSerialPort()


    def __loadConfig(self): #加载配置文件
        cfg = configparser.ConfigParser()
        try:
            cfg.read('configure.ini')
            self.__cfg['hardware']['serialDev'] = cfg.get('HARDWARE','SERIAL_DEV')
            self.__cfg['hardware']['baudrate']  = cfg.get('HARDWARE','BAUDRATE')


            self.__cfg['send']['remoteUrl'] = cfg.get('SEND','REMOTE_URL')
            self.__cfg['send']['delay'] = cfg.get('SEND','DELAY')
            self.__cfg['send']['port']=cfg.get('SEND','PORT')
            self.__cfg['send']['webDoc']=cfg.get('SEND','WEB_DOC')
            
            self.__cfg['recv']['remoteUrl'] = cfg.get('RECV','REMOTE_URL')
            self.__cfg['recv']['delay'] = cfg.get('RECV','DELAY')


            self.__cfg['log']['enable'] = cfg.get('LOG','ENABLE')


            if self.__cfg['log']['enable'] == '1':
                self.__cfg['log']['path'] = cfg.get('LOG','PATH');


            for value in self.__cfg.values():
                for k,v in value.items():
                    if v == None:
                        self.__half('All configuration items cannot be empty!')
            


        except:
            self.__half('Load config failed')
        finally:
            pass


    
    def __initSerialPort(self): #初始化串口
        self.__serial = serial.Serial(
                    port     = self.__cfg['hardware']['serialDev'],
                    baudrate = self.__cfg['hardware']['baudrate']
                    )
        try:
            if not self.__serial.isOpen():
                    self.__serial.open()
        except:
            self.__half('cann`t opren port')
        finally:
            pass


    def __readSerialData(self):     #读取串口数据
        self.__serial.flushOutput() #丢弃接收缓存中的所有数据
        self.__serial.flushInput()  #终止当前写操作,并丢弃发送缓存中的数据。

        sData = {'temp':{},
                 'humi':{},
                 'photo':{},
                 'air':{}}
        i = 0
        
        while True:
            if self.__first_data()=='0xff' and self.__first_data()=='0x00':
                sensor_type = self.__first_data()
                if sensor_type == '0x01':     #temp and humi
                    self.__first_data()
                    self.__first_data()
                    sData['temp'] = self.__first_data(2)
                    sData['humi'] = self.__first_data(2)
##                    print('temp')
##                    print(sData['temp'])
                    i = i+1
                elif sensor_type == '0x02':   #photo
                    self.__first_data()
                    self.__first_data()
                    sData['photo'] = self.__first_data(2)
##                    print('photo')
##                    print(sData['photo'])
                    i = i+1
                elif sensor_type == '0x03':   #air
                    self.__first_data()
                    self.__first_data()
                    sData['air'] = self.__first_data(2)
##                    print('air')
##                    print(sData['air'])
                    i = i+1
            if i>=3:
                print(sData)
                return sData


                
##            print(self.__first_data()=='0xff')
##            print(self.__first_data()=='0x00')
##            print('---')




    def __first_data(self,types=1):    #data type is str ,ex "b'ff'"
        data = self.__read_ascii()
        temp = data[2:len(data)-1]
        temp = '0x'+temp
##        print(int(temp,16))
        if types == 1:
##            print(temp)
            return temp                     #data type is str
        else :
##            print(temp)
            return int(temp,16)             #data type is int


    def __read_ascii(self):             #read serial data,turn to ascii
        return str(binascii.b2a_hex(self.__serial.read()))
        
##
####    def __sendSerialData(self): #发送数据到串口,未实现
####
##    def __readData(self):   #读取http数据,未实现
##


    #"Content-type":"application/x-www-form-urlencode",
    #"Mozilla/5.0(Macintosh;Intel Mac OS X 10_11_6)AppleWebKit/537.36(KHTMK,like Gecko) Chrome/51.0.2704.103 Safari/537.36"


    def __sendData(self,data):
        header = {"charset":"utf-8",
          "Content-Type":"application/json"}
        try:
            conn = http.client.HTTPConnection(self.__cfg['send']['remoteUrl'],self.__cfg['send']['port'])  
            json_data = json.dumps(data,ensure_ascii = 'False')
            conn.request("POST",self.__cfg['send']['webDoc'],sampleJson,header)
            response = conn.getresponse()
            print(response.read())


        except Exception as e:
            print(e)
        finally :
            conn.close()
##        headers = {
##            "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36",
##            "Content-Type":"application/x-www-form-urlencode",
##            "Accept":"text/plain,text/html,*/*;q=0.01"}
####        self.__cfg['send']['remoteUrl']  '192.168.61.136'
##        conn = http.client.HTTPConnection(self.__cfg['send']['remoteUrl'] ,self.__cfg['send']['port'])
##        try:
##            conn.request('POST',self.__cfg['send']['webDoc'],json_data,headers)
##            response = conn.getresponse()
##            print(response.status,response.reason)
####            print(response.getheaders())
####            data = str(response.read(),encoding='utf-8')#.encode('utf-8')
####            print('receive data is:')
####            print(data)
####            print('send ok')
##        except Exception as e:
##            print(e)
##        finally :
##            conn.close()
            
##    def __sendData(self,json_data):   #发送数据到http
##        try:
##            request = urllib.Request(self.__cfg['send']['remoteUrl'],json_data)
##            header = {'User-Agent':'Mozilla/5.0(window N; Trident/7.0; rv:11.0) like Gecho'}
##            req = Request(url=self.__cfg['send']['remoteUrl'],
##                          data = json_data,
##                          headers = header,
##                          method = 'POST')
####            params = urllib.urlencode(data)
####            request = urllib2.Request(self.__cfg['send'][remoteUrl],'params')
####            response = urllib2.urlopen(request)
##        except:
##            self.__writeLog('Send data to server failed')
##        finally:
##            passg
##
##    def __getMAC(self): #获取MAC
##        process = os.open('/sbin/infconfig eth0')
##        info = process.read()
##        process.close()
##        mac = re.search("HWaddr\s+(\S+)",info)
##        if mac:
##            return mac.group(1)
##        else:
##            return "00-00-00-00-00-00"
##
##    def __writeLog(self,log): #写入日志
##        if self.__cfg['log']['enable'] == '1':
##            fp = open(self.__cfg['log']['path'],'a+')
##            try:
##                written = time.strftime('[%Y-%m-%d %H:%M:%S]',time,localtime(time.time()))+log+'\r\n'
##                fp.write(written)
##            except:
##                print('Cannot written the log infomation')
##            finally:
##                pass
##
##        else:
##            print('log not enable')
##            pass


    def __half(self,msg,isWriteLog = True): #停止运行
        if isWriteLog:
            print(msg)
            exit
    


    def run(self):  #运行
        data = {}
##        data['mac'] = self.__mac
##        print(data)
        while True:
            data = self.__readSerialData()
            
##            json_data = demjson.encode(data)
##            sData = {'temp':{},
##                 'humi':{},
##                 'photo':{},
##                 'air':{}}
            #先将发送数据注释,方便调试
            print('send data is:')
            print(json_data)
            self.__sendData(json_data)
            
##            strj = 'data'+str(i)
##            data[strj] = self.__readSerialData()
####            print(data)
##            if i%3 == 0:
##                json_data = demjson.encode(data)
##                self.__sendData(json_data)
##                i=0
##                data = {}
####                print(json_data)
####            print(data)
##            i=i+1
##            self.__sendData(data)
##            time.sleep(self.__cfg['send']['delay'])
##        测试使用
##         for value in self.__cfg.values():
##                for k,v in value.items():
##                    print(k,"==>",v)
            
##            


    def __del__(self):  #退出程序,关闭串口
        if self.__serial and self.__serial.isOpen():
            self.__serial.close()
    


configure.ini   配置文件

[HARDWARE]
SERIAL_DEV=COM2
BAUDRATE=38400


[SEND]
REMOTE_URL=192.168.61.136
WEB_DOC=/practice/connDB.php
DELAY=100
PORT=80


[RECV]
REMOTE_URL=
DELAY=100


[LOG]
ENABLE=1
PATH=log.txt





php服务端接收参考:

http://blog.csdn.net/shawshank_bingo/article/details/73005602

            
            

原创粉丝点击