guitalens_worker.py 2.93 KB


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']