Skip to content

Instantly share code, notes, and snippets.

@jpmens jpmens/lamp.py
Created Jun 4, 2013

Embed
What would you like to do?
Simulate a lamp for use with homA (https://github.com/binarybucks/homA)
#!/usr/bin/env python
# lamp.py (C)2013 by Jan-Piet Mens <jpmens()gmail.com>
# Simulate a lamp for use with homA (https://github.com/binarybucks/homA)
# The lamp is switched on by creating a file in the current directory.
# Switching it off, removes the file.
import mosquitto
import sys, os
roomname = "My office"
devname = "Desk Lamp"
systemid = '69001-lamp'
prefix = "/devices/" + systemid
semafile = 'lamp.status'
def on_connect(mosq, userdata, rc):
mqttc.subscribe("/devices/" + systemid + "/controls/" + devname + "/on", 0)
# Publish (retained) our room and device name
mqttc.publish("/devices/" + systemid + "/meta/room", roomname, qos=0, retain=True)
mqttc.publish("/devices/" + systemid + "/meta/name", devname, qos=0, retain=True)
# Create (if it doesn't yet exist), a switch control. If it exists (previously
# retained), this simply "overwrites" retained values.
mqttc.publish("/devices/" + systemid + "/controls/" + devname + "/meta/type", "switch", qos=0, retain=True)
def on_disconnect(mosq, userdata, rc):
print "OOOOPS! disconnect"
def semaphore(on):
print "Switching lamp to %d" % on
try:
if on:
f = open(semafile, 'w')
f.write("Lamp is on")
f.close()
else:
os.remove(semafile)
except OSError:
pass
def on_message(mosq, userdata, msg):
if msg.topic == "/devices/" + systemid + "/controls/" + devname + "/on":
on = int(msg.payload)
semaphore(on)
# Now publish the status back. Note the missing "/on" !
mqttc.publish("/devices/" + systemid + "/controls/" + devname, on, qos=0, retain=True)
def on_log(mosq, userdata, level, string):
print(string)
mqttc = mosquitto.Mosquitto()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.on_disconnect = on_disconnect
#mqttc.on_log = on_log
mqttc.connect(os.getenv('HOMA_BROKERHOST', 'localhost'),
int(os.getenv('HOMA_BROKERPORT', '1883')))
try:
mqttc.loop_forever()
except KeyboardInterrupt:
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.