25 lines
1.2 KiB
Python
25 lines
1.2 KiB
Python
import paho.mqtt.client as pahomqtt
|
|
BROKER = "192.168.0.239"
|
|
BASE_TOPIC = "/facescan"
|
|
class ESPMegaMQTT:
|
|
input_buffer = [0]*16
|
|
mqtt: pahomqtt.Client
|
|
def __init__(self) -> None:
|
|
self.mqtt = pahomqtt.Client(client_id="pyfacescan")
|
|
self.mqtt.connect(host=BROKER,port=1883,keepalive=60)
|
|
self.mqtt.subscribe(f'{BASE_TOPIC}/input/#')
|
|
self.mqtt.on_message=self.handle_message
|
|
self.request_state()
|
|
self.mqtt.loop_start()
|
|
def write_pwm(self, id: int, state: bool, value: int = 4095):
|
|
self.mqtt.publish(f'{BASE_TOPIC}/pwm/{"%02d"}/set/state'%id,"on" if state else "off")
|
|
self.mqtt.publish(f'{BASE_TOPIC}/pwm/{"%02d"}/set/value'%id, str(value))
|
|
def read_digital(self, id: int):
|
|
return self.input_buffer[id]
|
|
def request_state(self):
|
|
self.mqtt.publish(f'{BASE_TOPIC}/requeststate',"req")
|
|
def handle_message(self, client: pahomqtt.Client, data, message: pahomqtt.MQTTMessage):
|
|
if (message.topic.startswith(BASE_TOPIC+"/input/")):
|
|
id = int(message.topic[len(BASE_TOPIC)+7:len(message.topic)])
|
|
state = int(message.payload)
|
|
self.input_buffer[id] = state |