def _on_command_wrapper(self, worker_obj, client, userdata, c):
     _LOGGER.debug("on command wrapper for with %s: %s", c.topic, c.payload)
     global_topic_prefix = userdata['global_topic_prefix']
     topic = c.topic[len(global_topic_prefix + '/'
                         ):] if global_topic_prefix is not None else c.topic
     self._queue_command(
         self.Command(worker_obj.on_command, [topic, c.payload]))
        def execute(self):
            messages = []
            with timeout(35):
                messages = self._callback(*self._args)

            _LOGGER.debug(messages)
            return messages
Example #3
0
 def run(self, mqtt):
   with serial.Serial(self.port, self.baudrate, timeout=10) as ser:
     _LOGGER.debug("Starting mysensors at: %s" % ser.name)
     while True:
       line = ser.readline()
       if not line:
         continue
       splited_line = self.format_topic(line.decode('utf-8').strip()).split(';')
       topic = '/'.join(splited_line[0:-1])
       payload = ''.join(splited_line[-1])
       mqtt.publish([MqttMessage(topic=topic, payload=payload)])
 def _update_interval_wrapper(self, command, job_id, client, userdata, c):
     _LOGGER.debug("Recieved updated interval for %s with: %s", c.topic,
                   c.payload)
     try:
         new_interval = int(c.payload)
         self._scheduler.remove_job(job_id)
         self._scheduler.add_job(partial(self._queue_command, command),
                                 'interval',
                                 seconds=new_interval,
                                 id=job_id)
     except ValueError:
         _LOGGER.info("New interval invalid, recieved: %s", c.payload)
Example #5
0
    def __init__(self, config):
        self._config = config
        self._mqttc = mqtt.Client(
            client_id=self.client_id,
            clean_session=False,
            userdata={'global_topic_prefix': self.topic_prefix})

        if self.username and self.password:
            self.mqttc.username_pw_set(self.username, self.password)

        if self.availability_topic:
            topic = self._format_topic(self.availability_topic)
            _LOGGER.debug("Setting LWT to: %s" % topic)
            self.mqttc.will_set(topic, payload=LWT_OFFLINE, retain=True)
    def register_workers(self, config):
        for (worker_name, worker_config) in config['workers'].items():
            module_obj = importlib.import_module("workers.%s" % worker_name)
            klass = getattr(module_obj, "%sWorker" % worker_name.title())

            if module_obj.REQUIREMENTS is not None:
                self._pip_install_helper(module_obj.REQUIREMENTS)

            worker_obj = klass(**worker_config['args'])

            if hasattr(worker_obj, 'status_update'):
                _LOGGER.debug("Added: %s with %d seconds interval" %
                              (worker_name, worker_config['update_interval']))
                command = self.Command(worker_obj.status_update, [])
                self._update_commands.append(command)

                if 'update_interval' in worker_config:
                    job_id = '{}_interval_job'.format(worker_name)
                    interval_job = self._scheduler.add_job(
                        partial(self._queue_command, command),
                        'interval',
                        seconds=worker_config['update_interval'],
                        id=job_id)
                    self._mqtt_callbacks.append(
                        (worker_obj.format_topic('update_interval'),
                         partial(self._update_interval_wrapper, command,
                                 job_id)))
            elif hasattr(worker_obj, 'run'):
                _LOGGER.debug("Registered: %s as daemon" % (worker_name))
                self._daemons.append(worker_obj)
            else:
                raise "%s cannot be initialized, it has to define run or status_update method" % worker_name

            if 'topic_subscription' in worker_config:
                self._mqtt_callbacks.append(
                    (worker_config['topic_subscription'],
                     partial(self._on_command_wrapper, worker_obj)))

        if 'topic_subscription' in config:
            for (callback_name,
                 options) in config['topic_subscription'].items():
                self._mqtt_callbacks.append(
                    (options['topic'],
                     lambda client, _, c: self._queue_if_matching_payload(
                         self.Command(getattr(self, callback_name)), c.payload,
                         options['payload'])))

        return self
Example #7
0
    def callbacks_subscription(self, callbacks):
        self.mqttc.connect(self.hostname, port=self.port)

        for topic, callback in callbacks:
            topic = self._format_topic(topic)
            _LOGGER.debug("Subscribing to: %s" % topic)
            self.mqttc.message_callback_add(topic, callback)
            self.mqttc.subscribe(topic)

        self.mqttc.loop_start()

        if self.availability_topic:
            self.publish([
                MqttMessage(topic=self.availability_topic,
                            payload=LWT_ONLINE,
                            retain=True)
            ])
Example #8
0
    def status_update(self):
        scanner = Scanner().withDelegate(ScanDelegate())
        devices = scanner.scan(5.0)
        ret = []

        for name, mac in self.devices.items():
            device = self.searchmac(devices, mac)
            if device is None:
                ret.append(
                    MqttMessage(topic=self.format_topic(name + '/presence'),
                                payload="0"))
            else:
                ret.append(
                    MqttMessage(topic=self.format_topic(name +
                                                        '/presence/rssi'),
                                payload=device.rssi))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + '/presence'),
                                payload="1"))
                _LOGGER.debug("text: %s" % device.getValueText(255))
                bytes_ = bytearray(bytes.fromhex(device.getValueText(255)))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + '/running'),
                                payload=bytes_[5]))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + '/pressure'),
                                payload=bytes_[6]))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + '/time'),
                                payload=bytes_[7] * 60 + bytes_[8]))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + '/mode'),
                                payload=bytes_[9]))
                ret.append(
                    MqttMessage(topic=self.format_topic(name + '/quadrant'),
                                payload=bytes_[10]))

        return ret
 def handleDiscovery(self, dev, isNewDev, isNewData):
     if isNewDev:
         _LOGGER.debug("Discovered new device: %s" % dev.addr)
Example #10
0
 def update_all(self):
     _LOGGER.debug("Updating all workers")
     for command in self._update_commands:
         self._queue_command(command)
Example #11
0
from config import settings
from mqtt import MqttClient
from workers_manager import WorkersManager

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-d', '--debug', action='store_true', default=False)
group.add_argument('-q', '--quiet', action='store_true', default=False)
parsed = parser.parse_args()

if parsed.debug:
    _LOGGER.setLevel(logging.DEBUG)
else:
    _LOGGER.setLevel(logging.INFO)

_LOGGER.debug('Starting')

mqtt = MqttClient(settings['mqtt'])
manager = WorkersManager()
manager.register_workers(settings['manager']).start(mqtt)

running = True

try:
    while running:
        try:
            mqtt.publish(_WORKERS_QUEUE.get(block=True).execute())
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception as e:
            if not parsed.quiet:
Example #12
0
 def _on_command_wrapper(self, worker_obj, client, _, c):
   _LOGGER.debug("on command wrapper for with %s: %s", c.topic, c.payload)
   self._queue_command(self.Command(worker_obj.on_command, [c.topic, c.payload]))