1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| # encoding=utf-8 import os import serial import time import json import sqlite3 from struct import *
# pip install requests
ser = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=2.0)
def read_pm_line(_port): rv = b'' while True: ch1 = _port.read() if ch1 == b'\x42': ch2 = _port.read() if ch2 == b'\x4d': rv += ch1 + ch2 rv += _port.read(38) return rv
def writefile(filereadlines): #write file newfile = open('/srv/http/pm25/data.json', mode='w', encoding='UTF-8') newfile.writelines(filereadlines) newfile.close()
def save_to_sqlite(data): """直接保存数据到SQLite数据库""" dbfile = '/srv/http/pm25/pm25.db' try: # 连接到SQLite数据库 conn = sqlite3.connect(dbfile) cursor = conn.cursor() # 插入数据 sql = "INSERT INTO pm(data) VALUES(?)" cursor.execute(sql, (data,)) # 提交事务 conn.commit() print(f"数据已保存到数据库: {data}") except sqlite3.Error as e: print(f"数据库操作失败: {e}") except Exception as e: print(f"保存数据时发生错误: {e}") finally: if conn: conn.close()
def main(): recv = read_pm_line(ser)
tmp = recv[4:36] datas = unpack('>hhhhhhhhhhhhhhhh', tmp) sendData = datas[0], datas[1], datas[2], datas[3], datas[4], datas[5], datas[6], datas[ 7], datas[8], datas[9], datas[10], datas[11], datas[12]/1000.0, datas[13]/10.0, datas[14]/10.0 sendData = str(tuple(sendData)) tmp = sendData.split(' ') sendData = ''.join(tmp) # 直接保存到SQLite数据库,而不是通过HTTP请求 save_to_sqlite(sendData[1:-1]) ser.flushInput() time.sleep(0.1)
outputData = {'temperature':datas[13]/10,'humidity':datas[14]/10,'pm25':datas[4]}
writefile(json.dumps(outputData))
if __name__ == '__main__': try: main() except KeyboardInterrupt: if ser != None: ser.close()
|