Blame view

simulators/plc/guitalens_worker.py 2.95 KB
240873f8   Patrick Maeght   date modif
1
2
"""
PM 20190108
e355ba3f   Patrick Maeght   PlcSimulator with...
3

240873f8   Patrick Maeght   date modif
4
"""
e355ba3f   Patrick Maeght   PlcSimulator with...
5
6
7
8
9
10
11

import logging
import threading
import time
from datetime import datetime
import urllib.request
import json
647a6c47   Patrick Maeght   guitalens worker ...
12
13
14
15
import os, sys
print(os.path.abspath("."))
_path = os.path.abspath("..")
sys.path.insert(0, _path )
240873f8   Patrick Maeght   date modif
16
#import logconf
e355ba3f   Patrick Maeght   PlcSimulator with...
17
logger = logging.getLogger(__name__)
647a6c47   Patrick Maeght   guitalens worker ...
18
19
20
21
"""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')"""
e355ba3f   Patrick Maeght   PlcSimulator with...
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

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'
f6076245   Patrick Maeght   penelope work part 1
48
        self.shared.status = 'init'
e355ba3f   Patrick Maeght   PlcSimulator with...
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
        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))
647a6c47   Patrick Maeght   guitalens worker ...
73
            #self.shared.status = 'wait'
e355ba3f   Patrick Maeght   PlcSimulator with...
74
75
76
77
78
79

    def try_work(self):
        try:
            self.work()
        except Exception as e:
            logger.info('Worker error ' + str(e))
647a6c47   Patrick Maeght   guitalens worker ...
80
            self.shared.status = 'init'
e355ba3f   Patrick Maeght   PlcSimulator with...
81
82
83
84
85
86
87

    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:
f6076245   Patrick Maeght   penelope work part 1
88
                        self.set_values(self.ret["entities"][0])
e355ba3f   Patrick Maeght   PlcSimulator with...
89
90
91
92
93
94
95
                        
    def stop(self):
        self.shared.worker = 'stop'

    def set_values(self, ret):
        # cant replace object
        self.msg_struct['entity_name'] = ret['entity_name']
f4465c28   Patrick Maeght   json modified fro...
96
        self.msg_struct['origin'] = ret['origin']
e355ba3f   Patrick Maeght   PlcSimulator with...
97
98
99
100
        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']