w2works
12/4/2014 - 12:01 PM

raspberry-pi-light.py

import RPi.GPIO as GPIO
import mosquitto, json, time


# -------------- #
# Board settings #
# -------------- #

GPIO.setmode(GPIO.BOARD)  # use P1 header pin numbering convention
GPIO.cleanup()            # clean up resources
GPIO.setup(7, GPIO.OUT)   # led pin setup
GPIO.setup(12, GPIO.IN)   # button pin setup


# --------------- #
# Callback events #
# --------------- #

# connection event
def on_connect(obj, rc):
    print('Connected, rc: ' + str(rc))

# subscription event
def on_subscribe(mosq, obj, mid):
    print('Subscribed: ' + str(mid))

# received message event
def on_message(obj, msg):
    # get the JSON message
    json_data = msg.payload
    # check the status property value
    value = json.loads(json_data)['properties'][0]['value']
    if value == 'on':
        led_status = GPIO.HIGH
        GPIO.output(7, GPIO.HIGH)
    else:
        led_status = GPIO.LOW
        GPIO.output(7, GPIO.LOW)

    # confirm changes to Leylan
    client.publish(out_topic, json_data)


# ------------- #
# MQTT settings #
# ------------- #

# create the MQTT client
client = mosquitto.Mosquitto('<CLIENT-ID>')  # * set a random string (max 23 chars)

# assign event callbacks
client.on_message = on_message
client.on_connect = on_connect
client.on_subscribe = on_subscribe

# device credentials
device_id     = '<DEVICE-ID>'      # * set your device id (will be the MQTT client username)
device_secret = '<DEVICE-SECRET>'  # * set your device secret (will be the MQTT client password)

# 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)  # MQTT server credentials
client.connect('178.62.108.47')                   # MQTT server address
client.subscribe(in_topic, 0)                     # MQTT subscribtion (with QoS level 0)


# ------------ #
# Button logic #
# ------------ #

prev_status = GPIO.LOW
led_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()

        if button:
            led_status = not led_status
            button_payload = 'off'
            if led_status == GPIO.HIGH:
                button_payload = 'on'
            # effectively update the light status
            GPIO.output(7, led_status)
            payload = { 'properties': [{ 'id': '518be5a700045e1521000001', 'value': button_payload }] }
            client.publish(out_topic, json.dumps(payload))

print('rc: ' + str(rc))