guitalens_worker.py
2.93 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
91
92
93
94
95
96
97
import logging
import threading
import time
from datetime import datetime
import urllib.request
import json
import os, sys
print(os.path.abspath("."))
_path = os.path.abspath("..")
sys.path.insert(0, _path )
import logconf
logger = logging.getLogger(__name__)
"""logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.FileHandler('../../logs/guitalens.log', mode='w')
logger.setLevel('DEBUG')"""
class WorkerState(object):
"""
worker: start/stop
status: wait/init/work...
"""
def __init__(self):
self.worker = None
self.status = None
self.status_time = str(datetime.now())
class WorkerUrl(threading.Thread):
def __init__(self, shared, msg_struct):
threading.Thread.__init__(self)
self.shared = shared
self.msg_struct = msg_struct
self._url = "http://astroguita.hd.free.fr:8080/meteo/plc_guitalens.json"
self.req = None
self.ret = None
self.time_step = 4
# call by thread.start()
def run(self):
self.shared.worker = 'start'
self.shared.status = 'init'
logger.info('Worker up')
# as lonq worker = start
while self.shared.worker == 'start':
# status (init, write)
if self.shared.status == 'wait':
pass
elif self.shared.status == 'init':
self.try_init()
elif self.shared.status == 'work':
self.try_work()
time.sleep(self.time_step)
# End work
logger.info('Worker down')
self.shared.status = "off"
return
def try_init(self):
try:
self.req = urllib.request.Request(url=self._url)
self.shared.status = 'work'
self.shared.status_time = str(datetime.now())
except Exception as e:
logger.info('Worker init error ' + str(e))
#self.shared.status = 'wait'
def try_work(self):
try:
self.work()
except Exception as e:
logger.info('Worker error ' + str(e))
self.shared.status = 'init'
def work(self):
#logger.info('Working '+ str(self.item))
with urllib.request.urlopen(self.req) as f:
success = (f.code == 200)
self.ret = json.loads(f.read().decode('utf-8'))
if success:
self.set_values(self.ret["entities"][0])
def stop(self):
self.shared.worker = 'stop'
def set_values(self, ret):
# cant replace object
self.msg_struct['entity_name'] = ret['entity_name']
self.msg_struct['origin'] = ret['origin']
self.msg_struct['version_firmware'] = ret['version_firmware']
self.msg_struct['site'] = ret['site']
self.msg_struct['date'] = ret['date']
self.msg_struct['devices'] = ret['devices']