Example #1
0
 def __connect(self, force = False, reload = False):
     if self.is_connected() and not force and not reload:
         return True
     self.disconnect()
     self.load(reload)
     self.__check_config()
     if self.__valid_config:
         if self.config_item(ENABLED, False):
             if self.__with_auth:
                 self.__client = MQTTClient(
                     DEVICE_NAME, self.config_item(HOST), self.config_item(PORT),
                     self.config_item(USER), self.config_item(PASSWORD), 0, SSL)
             else:
                 self.__client = MQTTClient(
                     DEVICE_NAME, self.config_item(HOST), self.config_item(PORT),
                     None, None, 0, SSL)
         else:
             log.info("MQTT disabled")
             return False
     else:
         log.error("Invalid mqtt config")
         return False
     self.__client.connect()
     self.__client.DEBUG = DEBUG
     self.__client.set_callback(self.__sub_callback)
     self.__client.subscribe(bytes(CMD_TOPIC, 'utf-8'))
     self.__connected = True
     log.debug("Mqtt broker connected")
     return True
Example #2
0
 def setup(self):
     try:
         log.debug("Load cron jobs")
         self.cleanup_cron()
         js = self.load()
         for j in js:
             self.__create_scheduler(j, False)
     except BaseException as e:  #NOSONAR #pylint: disable=bare-except
         log.error("Load cron failed %r", e)
         self.cleanup_cron()
Example #3
0
def dump_json(obj, file):
    log.info("Write json to file as string: %s", file)
    try:
        with open(file, "w") as fp:
            fp.write(dumps(obj))
        log.info("Write json, done")
        return True
    except BaseException as e:  #NOSONAR
        log.error("Write json failed! %s", e)
    return False
Example #4
0
 def __connect_finish(self):
     start_time = time()  # Check time
     while not self.__wlan.isconnected():
         sleep_ms(DEFAULT_300)
         self.__led.on()
         sleep_ms(DEFAULT_300)
         self.__led.off()
         if time() - start_time > self.__timeout:
             log.error("Wifi connection timeout: %d", self.__timeout)
             break
     return self.__set_properties()
Example #5
0
 def __sub_callback(self, topic, pay): 
     s = pay.decode("utf-8")
     log.info('Received %s: %s' , topic.decode("utf-8"), s)
     try:
         json = loads(s)
         if ENCRYPTED_INPUT: # 处理加密
             st = Sec()
             json = st.dec_payload(json)
         create_task(self.__opc.op_request(json))
     except BaseException as e:
         m = "Process message failed: %r" % e
         log.error(m)
         self.publish_op_log(None, None, result(500, m))
Example #6
0
def load_json(json):
    log.info("Load json: %s", json)
    try:
        with open(json) as fp:
            data = loads(fp.read())
            if type(data) == str:
                if data == "[]":
                    return []
                return {}
        log.info("Read json, done")
        return data
    except BaseException as e:  #NOSONAR
        log.error("Read json failed! %s", e)
    return None
Example #7
0
 def publish(self, ret, retain = False, qos = 0, topic = None):
     t = None
     try:
         ret['i'] = DEVICE_NAME
         if topic is None:
             t = self.config_item(TOPIC)
         else:
             t = topic
         if t is None:
             log.debug("None topic, ignored")
             return
         log.debug("Add msg to pub queue: topic: %s, %r ", t, ret)
         l = {'t': bytes(t, 'utf-8'), 'm': bytes(dumps(ret), 'utf-8'), 'r': retain, 'q': qos}
         self.__pub_queue.put_nowait(l)
     except BaseException as e:
         log.error("Publish to topic %s failed: %r", t, e)
Example #8
0
 def __connect_init(self):
     self.check_wifi_config()
     if self.__config is None:
         log.error("Wifi config is None")
         return
     log.info("Connect to wifi: %s", self.__config[SSID])
     self.__wlan = WLAN(STA_IF)  # 创建 station 接口
     if self.__wlan.isconnected():
         self.__wlan.disconnect()
     self.__wlan.active(True)  # Activate the interface
     self.__wlan.scan()  # Scan
     self.__led.off()
     self.__wlan.config(dhcp_hostname=self.__hostname)
     self.__wlan.connect(self.__config[SSID],
                         self.__config[PASSWORD])  # 连接到指定ESSID网络
     if TIMEOUT in self.__config:
         self.__timeout = self.__config[TIMEOUT]
Example #9
0
 async def op(self, token, path, command, param, req_auth=True):
     r = None
     if req_auth:
         tm = self.tm_auth(token)
         if tm is not None:
             r = tm
         if not self.auth(token):
             r = AUTH_ERR
     if r is None:
         async with op_lock:  #pylint: disable=not-async-context-manager
             try:
                 r = await self.int_op(path, command, param)
             except BaseException as e:  #NOSONAR
                 msg = CALL_ERROR % (path + ':' + command, e)
                 log.error(msg)
                 r = result(500, msg)
     if self.__mqtt is not None:
         self.__mqtt.publish_op_log(path, command, r)
     return r
Example #10
0
 def __callback(self, b):
     log.debug("IRQ data: %r", b)
     state = disable_irq()
     tm = ticks_ms()
     log.debug("tm: %d, old: %d, %gap", tm, self.ticks, self.cool_down_gap)
     if tm > self.ticks + self.cool_down_gap:
         self.ticks = tm
         try:
             self._get_data(b)
             if self.handler is not None:
                 log.debug("Call handler")
                 schedule(self.handler, self.__handler_data)
             if self.queue is not None:
                 log.debug("Send sensor data to queue")
                 create_task(self.queue.put(self.__handler_data))
             sleep_ms(self.interval)
         except BaseException as e: # NOSONAR
             log.error("Excetion while check and call irq handler: %r", e)
     enable_irq(state)
Example #11
0
 def read(self):  #NOSONAR
     try:
         while True:
             (stat, tag_type, raw_uid, uid) = self.get_stat()
             if stat == self._rdr.OK:
                 if self._rdr.select_tag(raw_uid) == self._rdr.OK:
                     key = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                     if self._rdr.auth(self._rdr.AUTHENT1A, 8, key,
                                       raw_uid) == self._rdr.OK:
                         data = self._rdr.read(self._addr)
                         self._rdr.stop_crypto1()
                         if data is not None:
                             return stat, tag_type, raw_uid, uid, data
                         log.error("Failed to read data to card")
                     else:
                         log.error("Authentication error")
                 else:
                     log.error("Failed to select tag")
     except BaseException as e:
         log.info("Stop reading %r", e)
Example #12
0
 def write(self, data):
     log.info("Writing...")
     try:
         while True:
             (stat, _, raw_uid, _) = self.get_stat()
             if stat == self._rdr.OK:
                 if self._rdr.select_tag(raw_uid) == self._rdr.OK:
                     key = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                     if self._rdr.auth(self._rdr.AUTHENT1A, 8, key,
                                       raw_uid) == self._rdr.OK:
                         stat = self._rdr.write(self._addr, data)
                         self._rdr.stop_crypto1()
                         if stat == self._rdr.OK:
                             log.info("Data written to card")
                             return True
                         log.error("Failed to write data to card")
                     else:
                         log.error("Authentication error")
                 else:
                     log.error("Failed to select tag")
     except BaseException as e:
         log.info("Stop writing %r", e)
     return False
Example #13
0
    async def _handler(self, reader, writer): #NOSONAR
        """Handler for TCP connection with
        HTTP/1.0 protocol implementation
        """
        gc.collect()

        try:
            req = request(reader)
            resp = response(writer)
            # Read HTTP Request with timeout
            await asyncio.wait_for(self._handle_request(req, resp),
                                   self.request_timeout)

            # OPTIONS method is handled automatically
            if req.method == b'OPTIONS':
                resp.add_access_control_headers()
                # Since we support only HTTP 1.0 - it is important
                # to tell browser that there is no payload expected
                # otherwise some webkit based browsers (Chrome)
                # treat this behavior as an error
                resp.add_header('Content-Length', '0')
                await resp._send_headers()
                return

            # Ensure that HTTP method is allowed for this path
            if req.method not in req.params['methods']:
                raise HTTPException(405)

            # Handle URL
            gc.collect()
            if hasattr(req, '_param'):
                await req.handler(req, resp, req._param)
            else:
                await req.handler(req, resp)
            # Done here
        except (asyncio.CancelledError, asyncio.TimeoutError):
            pass
        except OSError as e:
            # Do not send response for connection related errors - too late :)
            # P.S. code 32 - is possible BROKEN PIPE error (TODO: is it true?)
            if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, 32):
                try:
                    await resp.error(500)
                except Exception as e:
                    log.exc(e, "")
        except HTTPException as e:
            try:
                await resp.error(e.code)
            except Exception as e:
                log.exc(e)
        except Exception as e:
            # Unhandled expection in user's method
            log.error(req.path.decode())
            log.exc(e, "")
            try:
                await resp.error(500)
                # Send exception info if desired
                if self.debug:
                    sys.print_exception(e, resp.writer.s)
            except Exception as e:
                pass
        finally:
            await writer.aclose()
            # Max concurrency support -
            # if queue is full schedule resume of TCP server task
            if len(self.conns) == self.max_concurrency:
                self.loop.create_task(self._server_coro)
            # Delete connection, using socket as a key
            del self.conns[id(writer.s)]