Exemplo n.º 1
0
 def __init__(self, daemon, cfg):
     super(gpio, self).__init__(daemon, cfg)
     daemon.knx_read_cbs.append(self.process_knx)
     daemon.value_direct_cbs.append(self.process_direct)
     for o in cfg["objects"]:
         gpio_type = o["gpio_type"]
         gpio_pin = o["gpio_pin"]
         if o["enabled"] and gpio_type in self.GPIO_TYPE_MAP:
             gpio_obj = self.GPIO_TYPE_MAP[gpio_type][0](gpio_pin)
             o["gpio_object"] = gpio_obj
             o["gpio_direction"] = self.GPIO_TYPE_MAP[gpio_type][1]
             for key, val in o["actions"].items():
                 if o["gpio_direction"] == self.GPIO_DIRECTION_INPUT:
                     action = key
                     value = val
                 elif o["gpio_direction"] == self.GPIO_DIRECTION_OUTPUT:
                     action = val
                     value = key
                 if action in self.GPIO_ACTION_MAP:
                     actioncbname = self.GPIO_ACTION_MAP[action]
                     if hasattr(gpio_obj, actioncbname):
                         actioncb = (lambda value: lambda evt: self.gpio_action(evt, o["knx_group"], value))(value)
                         if o["gpio_direction"] == self.GPIO_DIRECTION_INPUT:
                             setattr(gpio_obj, actioncbname, actioncb)
                             log.debug(f"{self.device_name} init. on callback='{actioncbname}' set value='{value}' for {o!r}")
                         else:
                             o["set_cb"] = getattr(gpio_obj, actioncbname)
                             log.debug(f"{self.device_name} init. on value change to '{value}', call='{actioncbname}' for {o!r}")
                     else:
                         log.warning(f"{self.device_name} init illegal action '{actioncbname}' for {gpio_obj!r}")
     log.debug("{} obj_list: {!r}".format(self.device_name, self.obj_list))
Exemplo n.º 2
0
 async def mqtt_loop(self):
     while True:
       try:
           await self.mqtt_stack()
       except MqttError as error:
           log.warning("MqttError: {error}. Reconnecting in {self.poll_interval} seconds.")
       finally:
           await asyncio.sleep(self.poll_interval)
Exemplo n.º 3
0
 def receive_info(self):
     try:
         self._cached_ctrl_fields = self._get(
             "/aircon/get_control_info")
         log.debug("Daikin AC Control Fields {!r}".format(
             self._cached_ctrl_fields))
         self._cached_sens_fields = self._get(
             "/aircon/get_sensor_info")
         log.debug("Daikin AC Sensor Fields {!r}".format(
             self._cached_sens_fields))
     except ConnectionError as e:
         log.warning(
             "Daikin AC Couldn't perform API read {!r}".format(e))
Exemplo n.º 4
0
 async def process_knx(self, cmd):
     try:
         knx_group, knx_val = cmd.strip().split("=")
         try:
             o = self.get_obj_by_knxgrp(knx_group)
             if o["enabled"]:
                 debug_msg = f"{self.device_name} process_knx({knx_group}={knx_val})"
                 await self._write_mqtt(knx_group, knx_val, debug_msg)
         except StopIteration:
             pass
         return True
     except Exception as e:
         log.warning("f{self.device_name} couldn't parse KNX command {cmd} ({e}!")
         return False
Exemplo n.º 5
0
 async def set_gpio(self, o, value):
     log.debug(f"{self.device_name} set_gpio({o!r}, {value})")
     try:
         gpio_obj = o["gpio_object"]
         prev_value = gpio_obj.value
         set_cb = o["set_cb"]
         log.info(f"{self.device_name} set_gpio prev_active={prev_value}->{value}. calling {set_cb!r}...")
         set_cb()
         if "actuate_seconds" in o:
             delay = o["actuate_seconds"]
             log.debug(f"{self.device_name} waiting {delay} s")
             await asyncio.sleep(delay)
             gpio_obj.value = prev_value
             log.debug(f"{self.device_name} restored previous state")
     except (TypeError, AttributeError):
         log.warning(f"{self.device_name} set_gpio illegal action '{value}' for {gpio_obj!r}")
Exemplo n.º 6
0
 async def handle(self, request):
     query = request.rel_url.query
     log.debug(f"{self.device_name} handle: {query!r}")
     if "toggle" in query:
         if not "key" in query:
             log.warning(
                 f"{self.device_name} no FOB key given when handling {query!r}!"
             )
             return web.Response(status=403, text="Forbidden\n")
         fobkey = query["key"]
         fobname = self.d.cfg["fobs"].get(fobkey, "unknown")
         for item in self.obj_list:
             if "opener" in item:
                 opener = item
             if "lock" in item:
                 lock = item
         if lock["value"] == "close":
             if fobkey in lock["allowed_fobs"]:
                 log.warning(
                     f"{self.device_name} {fobname}' FOB ({fobkey}) validated for unlocking!"
                 )
                 await self.d.set_group_value_dict(
                     {lock["knx_group"]: "open"})
                 lockdelay = lock["delay"]
                 await asyncio.sleep(lock["delay"])
                 log.warning(
                     f"{self.device_name} lockdelay waited for {lockdelay}s"
                 )
             else:
                 log.warning(
                     f"{self.device_name} {fobname}' FOB ({fobkey}) not allowed to unlock!"
                 )
                 return web.Response(status=403, text="Forbidden\n")
         if fobkey in opener["allowed_fobs"]:
             log.info(
                 f"{self.device_name} {fobname}'s FOB validated ({fobkey}) for opening!"
             )
             await self.d.set_group_value_dict({opener["knx_group"]: "on"})
             await asyncio.sleep(opener["delay"])
             await self.d.set_group_value_dict({opener["knx_group"]: "off"})
             return web.Response(text="success\n")
         else:
             log.warning(
                 f"{self.device_name} {fobname}'s FOB ({fobkey}) not allowed to open!"
             )
             return web.Response(status=403, text="Forbidden\n")
     return web.Response(status=404, text="Not found\n")
Exemplo n.º 7
0
    def start(self):
        log.info("Started KNX Bus Adapter Deamon.")

        knx_client = self.loop.run_until_complete(
            self.linknx_client(self.loop, self.cfg["linknx"]))

        knx_server_coro = asyncio.start_server(
            self.knx_server_handler,
            self.cfg["sys"]["listenHost"],
            self.cfg["linknx"]["listenPort"],
            loop=self.loop)
        knx_server = self.loop.run_until_complete(knx_server_coro)

        plugins = []
        for plugin_config in self.cfg["plugins"]:
            klass = plugin_config["class"]
            if klass in PLUGINS and plugin_config["enabled"]:
                try:
                    plugin_module = import_module(klass)
                    plugin_class = plugin_module.plugin_def()
                    if plugin_class:
                        plugins.append(plugin_class(self, plugin_config))
                except ModuleNotFoundError as e:
                    log.warning(
                        "module not found: {}. Plugin '{}' unavailable!".
                        format(e, klass))

        tasks = []
        for plugin in plugins:
            task = plugin.run()
            if task:
                tasks += task

        futs = asyncio.gather(*tasks)
        self.loop.run_until_complete(futs)

        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            pass
        finally:
            knx_server.close()
            self.loop.run_until_complete(knx_server.wait_closed())
            for plugin in plugins:
                plugin.quit()
            self.loop.close()
Exemplo n.º 8
0
    async def handle_rs485(self):
        while True:
            try:
                line = await self._reader.readline()
                cmd = line.decode('utf-8').strip()
                log.debug(self.device_name + " received: '" + cmd + "'")
                (key, val) = cmd.split('=')

                o = self._get_obj_by_key(key)
                if "receive" in o["enabled"]:
                    if "valmap" in o and val in o["valmap"]:
                        knxval = o["valmap"][val]
                    else:
                        knxval = val
                    await self.d.set_group_value_dict({o["knx_group"]: knxval})
                else:
                    log.warning(
                        f"{self.device_name} command key {key} is not a receiving object!"
                    )

            except ValueError:
                log.warning("{} couldn't parse command {!r}!".format(
                    self.device_name, line))
            except StopIteration:
                log.warning(
                    f"{self.device_name} command key {key} not configured!")
Exemplo n.º 9
0
 def _read_modbus(self, data_type, register):
     methods = {
         "float": self._read_float,
         "I16": self._read_i16,
         "U16": self._read_u16,
         "I32": self._read_i32,
         "U32": self._read_u32,
         "U64": self._read_u64
     }
     ret = None
     try:
         func = methods[data_type]
         ret = func(register)
     except KeyError:
         log.warning(
             "Modbus Data Type {} not found for register {} on device {}".
             format(data_type, register, self.device_name))
     except:
         log.warning(
             "Couldn't read register {} from Modbus device {}".format(
                 register, self.device_name))
     return ret
Exemplo n.º 10
0
    async def _card_inserted(self, card):
        key = str(card.value)
        if key in self.forbidden_fobs:
            name = self.fobs[key]
            log.warning(
                f"{self.device_name} {name}'s FOB forbidden attempt! ({card})")

        if key in self.fobs:
            name = self.fobs[key]
            log.info(f"{self.device_name} {name}'s FOB validated ({card})")
            if key in self.objs_by_fob:
                for obj in self.objs_by_fob[key]:
                    knx_group = obj["knx_group"]
                    log.info(f"{self.device_name} opening {knx_group}")
                    await self.d.set_group_value_dict({knx_group: "on"})
            else:
                log.warning(
                    f"{self.device_name} {name}'s FOB forbidden attempt! ({card})"
                )
        else:
            log.warning(
                f"{self.device_name} Unknown FOB {card} attempted! delaying for {self.throttle_delay} s!"
            )
            await asyncio.sleep(self.throttle_delay)
Exemplo n.º 11
0
 async def _invalid_card(self, card):
     log.warning(f"{self.device_name} Invalid FOB {card} attempted!")
Exemplo n.º 12
0
    async def handle_ups(self):
        while True:
            data = await self.ups_reader.readuntil(b'\x00\x00')
            debug_msg = []

            if not data:
                break

            data = data.decode('ascii')
            m = re.match(self.expression, data, re.DOTALL)

            if m:
                group_value_dict = {}
                for idx, o in enumerate(self.obj_list):
                    group = o["knx_group"]
                    val = m.groups(0)[idx]
                    debug_line = "idx: {} group: {} val: {}".format(
                        idx, group, val)
                    prev_val = o["value"]
                    try:
                        value = float(val)
                        debug_line += " numeric value: {0:g}".format(value)
                        hysteresis = o["hysteresis"]
                        if type(hysteresis
                                ) == str and "%" in hysteresis and abs(
                                    value - prev_val) <= float(
                                        hysteresis.strip('%')
                                    ) * value * 0.01 or type(
                                        hysteresis) == float and abs(
                                            value - prev_val) <= hysteresis:
                            debug_msg.append(
                                "{}-{:g} < {:g} hysteresis, ignored!".format(
                                    debug_line, prev_val, hysteresis))
                            continue
                        elif prev_val == value:
                            debug_msg.append(
                                "{} unchanged, ignored!".format(debug_line))
                            continue
                        group_value_dict[group] = "%.2f" % value

                    except ValueError:
                        if val == "ONLINE":
                            value = "true"
                        elif val == "ONBATT":
                            value = "false"
                        debug_line += " non-numeric value: ->{}".format(value)
                        if prev_val == value:
                            debug_msg.append(
                                "{} unchanged, ignored!".format(debug_line))
                            continue
                        group_value_dict[group] = value

                    o["value"] = value
                    debug_msg.append(debug_line)

                log.debug("{} {!r}\t".format(self.device_name, data) +
                          "\n\t".join(debug_msg))

                if group_value_dict:
                    await self.d.set_group_value_dict(group_value_dict)

            else:
                log.warning("{} Couldn't parse {!r}".format(
                    self.device_name, data))