Browse Source

lamp is now control with mqtt

master
tjiho 1 year ago
parent
commit
0cff6d9112
  1. 1
      requirements.txt
  2. 55
      server.py

1
requirements.txt

@ -3,3 +3,4 @@ pkg-resources
webthing
pifacecommon < 5.0.0
pifacedigitalio < 4
paho-mqtt < 1.6.0

55
server.py

@ -1,44 +1,45 @@
from webthing import (Action, Event, Property, SingleThing, Thing, Value, WebThingServer)
import paho.mqtt.client as mqtt
import logging
import pifacedigitalio
logging.basicConfig(
level=10,
format="%(asctime)s %(filename)s:%(lineno)s %(levelname)s %(message)s"
)
pifacedigital = pifacedigitalio.PiFaceDigital()
def on_connect(client, userdata, flags, rc):
"""Called when connected to MQTT broker."""
client.subscribe("cmnd/totoro/power")
client.subscribe("cmnd/totoro/#")
logging.info("Connected. Waiting for intents.")
def on_disconnect(client, userdata, flags, rc):
"""Called when disconnected from MQTT broker."""
client.reconnect()
def on_message(client, userdata, msg):
"""Called each time a message is received on a subscribed topic."""
logging.info('get message on ' + msg.topic)
if msg.topic == "cmnd/totoro/power":
client.publish("sensor/totoro/state",relay(not pifacedigital.output_pins[1].value))
def relay(v):
if v:
logging.info('on...')
pifacedigital.output_pins[1].turn_on()
return 'on'
else:
logging.info('off...')
pifacedigital.output_pins[1].turn_off()
return 'off'
light = Thing(
'totoro:lamp',
'Lampe chambre',
['OnOffSwitch', 'Light'],
'A web connected lamp'
)
client = mqtt.Client()
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
light.add_property(
Property(
light,
'on',
Value(pifacedigital.output_pins[1].value, relay),
metadata={
'@type': 'OnOffProperty',
'title': 'On/Off',
'type': 'boolean',
'description': 'Whether the lamp is turned on',
}))
server = WebThingServer(SingleThing(light), port=8888)
try:
logging.info('starting the server')
server.start()
except KeyboardInterrupt:
server.stop()
client.connect("10.10.10.9", 1883)
client.loop_forever()
Loading…
Cancel
Save