-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathg3.py
More file actions
91 lines (83 loc) · 2.96 KB
/
g3.py
File metadata and controls
91 lines (83 loc) · 2.96 KB
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
84
85
86
87
88
89
90
import serial
import time
import sys
from struct import *
debug=0
class g3sensor():
def __init__(self):
if debug: print "init"
self.endian = sys.byteorder
def conn_serial_port(self, device):
if debug: print device
self.serial = serial.Serial(device, baudrate=9600)
if debug: print "conn ok"
def check_keyword(self):
if debug: print "check_keyword"
while True:
token = self.serial.read()
token_hex=token.encode('hex')
if debug: print token_hex
if token_hex == '42':
if debug: print "get 42"
token2 = self.serial.read()
token2_hex=token2.encode('hex')
if debug: print token2_hex
if token2_hex == '4d':
if debug: print "get 4d"
return True
elif token2_hex == '00': # fixme
if debug: print "get 00"
token3 = self.serial.read()
token3_hex=token3.encode('hex')
if token3_hex == '4d':
if debug: print "get 4d"
return True
def vertify_data(self, data):
if debug: print data
n = 2
sum = int('42',16)+int('4d',16)
for i in range(0, len(data)-4, n):
#print data[i:i+n]
sum=sum+int(data[i:i+n],16)
versum = int(data[40]+data[41]+data[42]+data[43],16)
if debug: print sum
if debug: print versum
if sum == versum:
print "data correct"
def read_data(self):
data = self.serial.read(22)
data_hex=data.encode('hex')
if debug: self.vertify_data(data_hex)
pm1_cf=int(data_hex[4]+data_hex[5]+data_hex[6]+data_hex[7],16)
pm25_cf=int(data_hex[8]+data_hex[9]+data_hex[10]+data_hex[11],16)
pm10_cf=int(data_hex[12]+data_hex[13]+data_hex[14]+data_hex[15],16)
pm1=int(data_hex[16]+data_hex[17]+data_hex[18]+data_hex[19],16)
pm25=int(data_hex[20]+data_hex[21]+data_hex[22]+data_hex[23],16)
pm10=int(data_hex[24]+data_hex[25]+data_hex[26]+data_hex[27],16)
if debug: print "pm1_cf: "+str(pm1_cf)
if debug: print "pm25_cf: "+str(pm25_cf)
if debug: print "pm10_cf: "+str(pm10_cf)
if debug: print "pm1: "+str(pm1)
if debug: print "pm25: "+str(pm25)
if debug: print "pm10: "+str(pm10)
data = [pm1_cf, pm10_cf, pm25_cf, pm1, pm10, pm25]
self.serial.close()
return data
def read(self, argv):
tty=argv[0:]
self.conn_serial_port(tty)
if self.check_keyword() == True:
self.data = self.read_data()
if debug: print self.data
return self.data
if __name__ == '__main__':
air=g3sensor()
while True:
pmdata=0
try:
pmdata=air.read("/dev/ttyUSB1")
except:
next
if pmdata != 0:
print pmdata
break