Created
December 10, 2014 19:23
-
-
Save andreareginato/564ccfcffbcc1471d266 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import RPi.GPIO as GPIO | |
GPIO.setmode(GPIO.BOARD) | |
GPIO.cleanup() | |
# led pin setup | |
GPIO.setup(7, GPIO.OUT) | |
# button pin setup | |
GPIO.setup(12, GPIO.IN) | |
import mosquitto, json, time | |
# event callbacks | |
def on_connect(obj, rc): | |
print('Connected, rc: ' + str(rc)) | |
def on_message(obj, msg): | |
json_data = msg.payload | |
client.publish(out_topic, json_data) | |
value = json.loads(json_data)['properties'][0]['value'] | |
if value == 'on': | |
GPIO.output(7, GPIO.HIGH) | |
else: | |
GPIO.output(7, GPIO.LOW) | |
def on_subscribe(mosq, obj, mid): | |
print('Subscribed: ' + str(mid)) | |
# create client | |
client = mosquitto.Mosquitto('<CLIENT-ID>') | |
# assign event callbacks | |
client.on_message = on_message | |
client.on_connect = on_connect | |
client.on_subscribe = on_subscribe | |
# device credentials | |
device_id = '<DEVICE-ID>' | |
device_secret = '<DEVICE-SECRET>' | |
# device topics | |
in_topic = 'devices/' + device_id + '/get' # receiving messages | |
out_topic = 'devices/' + device_id + '/set' # publishing messages | |
# client connection | |
client.username_pw_set(device_id, device_secret) | |
client.connect('96.126.109.170') | |
# subscribe (with QoS level 0) | |
client.subscribe(in_topic, 0) | |
prev_status = GPIO.LOW | |
updated_at = 0 # the last time the output pin was toggled | |
debounce = 0.2 # the debounce time, increase if the output flickers | |
# Continue the network loop, exit when an error occurs | |
rc = 0 | |
while rc == 0: | |
rc = client.loop() | |
button = GPIO.input(12) | |
if button != prev_status and time.time() - updated_at > debounce: | |
prev_status = button | |
updated_at = time.time() | |
button_payload = 'off' | |
if button == GPIO.HIGH: | |
button_payload = 'on' | |
# effectively update the light status | |
GPIO.output(7, button) | |
payload = { 'properties': [{ 'id': '518be5a700045e1521000001', 'value': button_payload }] } | |
client.publish(out_topic, json.dumps(payload)) | |
print('rc: ' + str(rc)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment