-
Notifications
You must be signed in to change notification settings - Fork 3
/
dustmeter.py
98 lines (90 loc) · 3.54 KB
/
dustmeter.py
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
91
92
93
94
95
96
97
98
import socket
import select
import threading
import time
import meter_base
class DustMeter(meter_base.MeterBase, threading.Thread):
defaultProps= {
'name': 'dustMeter',
'host': 'localhost',
'port': 8888,
'default_dust': 0,
'reconnect': True
}
def __init__(self, **kwargs):
threading.Thread.__init__(self)
for attr, value in DustMeter.defaultProps.items():
if attr not in kwargs:
kwargs[attr] = value
self.name = kwargs['name']
self.host = kwargs['host']
self.port = kwargs['port']
self.reconnect = kwargs['reconnect']
self.dust_small = kwargs['default_dust']
self.dust_large = kwargs['default_dust']
self.is_connected = False
self.ev = threading.Event()
def run(self):
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if s.connect_ex((self.host, self.port)) == 0:
self.is_connected = True
print(self.name, '#', self.host+':'+str(self.port), 'is connected!')
else:
self.is_connected = False
print(self.name, '#', self.host+':'+str(self.port), 'is unreachable!')
if self.reconnect:
print(self.name, '#', 'reconnect later')
time.sleep(30)
continue
else:
print(self.name, '#', 'no connection, stop')
self.dust_small = DustMeter.defaultProps['default_dust']
self.dust_large = DustMeter.defaultProps['default_dust']
s.close()
break
inout = [s]
idel_loop_count = 0
while True:
infds, outfds, errfds = select.select(inout, [], [], 0.01)
if len(infds) != 0:
time.sleep(0.1)
buf = s.recv(64)
if len(buf) != 0:
idel_loop_count = 0;
[small_str, large_str] = buf.split(',')
self.dust_small=int(small_str)
self.dust_large=int(large_str)
print(self.name, '#', 'receive data:', repr(buf))
if self.ev.wait(30):
self.ev.clear()
print(self.name, '#', 'close connection by user')
self.dust_small = DustMeter.defaultProps['default_dust']
self.dust_large = DustMeter.defaultProps['default_dust']
self.is_connected = False
s.close()
return
else:
idel_loop_count += 1
if(idel_loop_count > 4):
print(self.name, '#','no incoming data, closing connection')
self.dust_small = DustMeter.defaultProps['default_dust']
self.dust_large = DustMeter.defaultProps['default_dust']
self.is_connected = False
s.close()
break
def getpresentValue(self):
return self.dust_small
def stop(self):
self.ev.set()
def getMeters(config):
return DustMeter(**config)
if __name__ == "__main__":
d = DustMeter(name = 'mydustmeter_somewhere', host = 'fhlrs232_a27.desy.de')
d.start()
time.sleep(70)
print('wake up')
d.stop()
print('stop 0')
d.join()
print('join 0')