|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import os.path as path |
| 3 | +import paho.mqtt.client as mqtt |
| 4 | + |
| 5 | + |
| 6 | +class Module: |
| 7 | + def __init__(self, incoming=False, verbose=False, options=None): |
| 8 | + # extract the file name from __file__. __file__ is proxymodules/name.py |
| 9 | + self.name = path.splitext(path.basename(__file__))[0] |
| 10 | + self.description = 'Publish the data to an MQTT server' |
| 11 | + self.incoming = incoming # incoming means module is on -im chain |
| 12 | + self.client_id = '' |
| 13 | + self.username = None |
| 14 | + self.password = None |
| 15 | + self.server = None |
| 16 | + self.port = 1883 |
| 17 | + self.topic = "" |
| 18 | + if options is not None: |
| 19 | + if 'clientid' in options.keys(): |
| 20 | + self.client_id = options['clientid'] |
| 21 | + if 'server' in options.keys(): |
| 22 | + self.server = options['server'] |
| 23 | + if 'username' in options.keys(): |
| 24 | + self.username = options['username'] |
| 25 | + if 'password' in options.keys(): |
| 26 | + self.server = options['password'] |
| 27 | + if 'port' in options.keys(): |
| 28 | + try: |
| 29 | + self.port = int(options['port']) |
| 30 | + except ValueError: |
| 31 | + print('invalid port, using default 1883') |
| 32 | + if 'topic' in options.keys(): |
| 33 | + self.topic = options['topic'] |
| 34 | + |
| 35 | + if self.server is not None: |
| 36 | + self.mqtt = mqtt.Client(self.client_id) |
| 37 | + if self.username is not None or self.password is not None: |
| 38 | + self.mqtt.username_pw_set(self.username, self.password) |
| 39 | + self.mqtt.connect(self.server, self.port) |
| 40 | + else: |
| 41 | + self.mqtt = None |
| 42 | + |
| 43 | + def execute(self, data): |
| 44 | + if self.mqtt is not None: |
| 45 | + if not self.mqtt.is_connected(): |
| 46 | + self.mqtt.reconnect() |
| 47 | + self.mqtt.publish(self.topic, data.hex()) |
| 48 | + return data |
| 49 | + |
| 50 | + def help(self): |
| 51 | + h = '\tserver: server to connect to, required\n' |
| 52 | + h += ('\tclientid: what to use as client_id, default is empty\n' |
| 53 | + '\tusername: username\n' |
| 54 | + '\tpassword: password\n' |
| 55 | + '\tport: port to connect to, default 1883\n' |
| 56 | + '\ttopic: topic to publish to, default is empty') |
| 57 | + return h |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + print('This module is not supposed to be executed alone!') |
0 commit comments