57 lines
1.6 KiB
Python
57 lines
1.6 KiB
Python
import paho.mqtt.client as mqtt
|
|
import threading
|
|
import logging
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class HardwareClient(mqtt.Client):
|
|
def __init__(self, app=None):
|
|
super(HardwareClient, self).__init__()
|
|
|
|
self.event = threading.Event()
|
|
|
|
if app:
|
|
self.init_app(app)
|
|
|
|
def init_app(self, app):
|
|
self.app = app
|
|
self.hardware_topic = 'iot/{}/relay/on'.format(
|
|
self.app.config['HARDWARE_ID'])
|
|
|
|
host, port = self.app.config['BROKER']
|
|
if self.app.config.get('BROKER_CREDS'):
|
|
self.username_pw_set(
|
|
self.app.config['BROKER_CREDS'].get('username'),
|
|
self.app.config['BROKER_CREDS'].get('password'),
|
|
)
|
|
|
|
self.connect(host, port, 60)
|
|
self.loop_start()
|
|
|
|
logger.info('Starting...')
|
|
|
|
def on_connect(self, client, userdata, flags, rc):
|
|
logger.info('Connected')
|
|
self.subscribe(self.hardware_topic)
|
|
#'iot/{}/+/+'.format(self.app.config['HARDWARE_ID']))
|
|
|
|
def on_message(self, client, userdata, msg):
|
|
logger.info('Message received %s: %s', msg.topic, msg.payload)
|
|
self.event.set()
|
|
|
|
def enable(self):
|
|
return self.set_state('true')
|
|
|
|
def disable(self):
|
|
return self.set_state('false')
|
|
|
|
def set_state(self, state):
|
|
# This will fail. Of course it will.
|
|
self.event.clear()
|
|
self.publish('{}/set'.format(self.hardware_topic), state)
|
|
|
|
resp = self.event.wait(self.app.config.get('HARDWARE_TIMEOUT', 5))
|
|
self.event.clear()
|
|
return resp
|