PKXK˧oJ mqttclient/__init__.py"""MQTT Client for Python""" __version__ = '0.0.1' import asyncio import inspect import json import os import time import random import re import urllib import paho.mqtt.client as mqtt from wheezy.routing import PathRouter from .mqtt_messages import MqttMessages _underscorer1 = re.compile(r'(.)([A-Z][a-z]+)') _underscorer2 = re.compile('([a-z0-9])([A-Z])') def camelToSnake(s): # https://gist.github.com/jaytaylor/3660565 subbed = _underscorer1.sub(r'\1_\2', s) return _underscorer2.sub(r'\1_\2', subbed).lower() class MqttClient(MqttMessages): """ Example MqttClient for Application Frameworks (such as Microdrop) Used with the following broker: https://github.com/sci-bots/microdrop-3.0/blob/master/MoscaServer.js """ def __init__(self, host="localhost", port=1883, base="microdrop"): super().__init__() self.router = PathRouter() self.host = host self.port = port self.base = base self.subscriptions = [] self.client_id = self.ClientID() self.client = self.Client() self.connected = False @property def filepath(self): try: return os.path.dirname(inspect.getfile(self.__class__)) except: return 'unknown' @property def name(self): safe_chars = '~@#$&()*!+=:;,.?/\'' return urllib.parse.quote(camelToSnake(self.__class__.__name__), safe=safe_chars) @property def version(self): return '0.0' def send_message(self, topic, msg={}, retain=False, qos=0, dup=False): message = json.dumps(msg) self.client.publish(topic, message, retain=retain, qos=qos) def on_connect(self, client, userdata, flags, rc): self.connected = True self.listen() self.trigger('start', 'null') def on_disconnect(self, client, userdata, rc): self.connected = False def listen(self): print(f'No listen method implemented for {self.name}') def on_message(self, client, userdata, msg): method, args = self.router.match(msg.topic) try: payload = json.loads(msg.payload) except ValueError: print("Message contains invalid json") print(f'topic: {msg.topic}') payload = None if method: method(payload, args) def wrap_data(self, key, val): msg = {} if isinstance(val, dict) and val != None: msg = val else: msg[key] = val msg['__head__'] = self.DefaultHeader() return msg def Client(self, keepalive=60): client = mqtt.Client(self.client_id) client.on_connect = self.on_connect client.on_message = self.on_message client.on_disconnect = self.on_disconnect client.connect(host=self.host, port=self.port) client.loop_start() return client def ClientID(self): timestamp = str(time.time()).replace(".","") randnum = random.randint(1,1000) return f'{self.name}>>{self.filepath}>>{timestamp}.{randnum}' def DefaultHeader(self): header = {} header['plugin_name'] = self.name header['plugin_version'] = self.version return header PKVKgH H mqttclient/mqtt_messages.pyimport re from onoff import OnOffMixin class MqttMessages(OnOffMixin): """ Mixins for listening and subscribing to mqtt messages, with helpers to automate common app framework uri structures like: state, put, notify, status, trigger, and signal. These mixins only automate the naming conventions and the expected retain behaviour. """ def add_subscription(self, channel, method): def m(payload, args): if 'route_name' in args: del args['route_name'] vals = args.values() return method(*vals, payload) self.router.add_route(channel, m) subscription = re.sub(r"\{(.+?)\}", "+", channel) if not self.connected: print(f'{this.name} :: Can not add subscription, disconnected') return subscription if subscription in self.subscriptions: return subscription self.subscriptions.append(subscription) self.client.subscribe(subscription) return subscription def add_binding(self, channel, event, retain=False, qos=0, dup=False): return self.on(event, lambda d: self.send_message(channel, d, retain, qos, dup)) def on_state_msg(self, sender, val, method): return self.add_subscription(f'{self.base}/{sender}/state/{val}', method) def bind_state_msg(self, val, event, persist=True): return self.add_binding(f'{self.base}/{self.name}/state/{val}', event, persist) def on_put_msg(self, val, method): return self.add_subscription(f'{self.base}/put/{self.name}/{val}', method) def bind_put_msg(self, receiver, val, event): return self.add_binding(f'{self.base}/put/{receiver}/{val}', event) def on_notify_msg(self, sender, topic, method): return self.add_subscription(f'{self.base}/{sender}/notify/{self.name}/{topic}', method) def bind_notify_msg(self, receiver, topic, event): return self.add_binding(f'{self.base}/{name}/notify/{receiver}/{topic}', event) def on_status_msg(self, sender, method): return self.add_subscription(f'{self.base}/status/{sender}', method) def bind_status_msg(self, event): return self.add_binding(f'{self.base}/status/{self.name}', event) def on_trigger_msg(self, action, method): return self.add_subscription(f'{self.base}/trigger/{self.name}/action', method) def bind_trigger_msg(self, receiver, action, event): return self.add_binding(f'{self.base}/trigger/{receiver}/{action}', event) def on_signal_msg(self, sender, topic, method): return self.add_subscription(f'{self.base}/{sender}/signal/{topic}', method) def bind_signal_msg(self, topic, event): return self.add_binding(f'{self.base}/{self.name}/signal/{topic}', event) PKSK ##"mqttclient-0.0.1.dist-info/LICENSEBSD 2-Clause License Copyright (c) 2017, Lucas Zeer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK!H0RR mqttclient-0.0.1.dist-info/WHEEL1 W% 0n1JBZS`ޝ/Qf:3&.~l" kW*дY00?PK!H,o9#mqttclient-0.0.1.dist-info/METADATA]An0E>/`RXtmPCĖbOBuJU$wp19 FB:3=uhpR#[ <"C2U967Wíu TZzjCN(rȺqjE\od?^S ELȗ',i#X#ev{mPK!He4.!mqttclient-0.0.1.dist-info/RECORD}̻v0o4PҢA,F AQNnwDf1iB{C"g[}iE $bvYv8k7rJq8Oǘ}TEr8tSlZd5$(\k+iGd3NTUgLBN'MɦRG=եrp5fa|!+V}7`yՁ9 .w&@K<̕;v!Zw9> tc۳ayT|y謠]#.[I=&PKXK˧oJ mqttclient/__init__.pyPKVKgH H  mqttclient/mqtt_messages.pyPKSK ##"mqttclient-0.0.1.dist-info/LICENSEPK!H0RR mqttclient-0.0.1.dist-info/WHEELPK!H,o9#umqttclient-0.0.1.dist-info/METADATAPK!He4.!mqttclient-0.0.1.dist-info/RECORDPK