-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.py
44 lines (32 loc) · 1.32 KB
/
index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Based on this article: https://docs.losant.com/getting-started/boards/getting-started-with-raspberry-pi
import json
from gpiozero import LED, Button # Import GPIO library: https://gpiozero.readthedocs.io/en/stable/
from time import sleep
from losantmqtt import Device # Import Losant library: https://github.com/Losant/losant-mqtt-python
led_gpio = 23
button_gpio = 4
led = LED(led_gpio)
button = Button(button_gpio, pull_up=False)
# Construct Losant device
device = Device("my-device-id", "my-app-access-key", "my-app-access-secret")
def on_command(device, command):
print(command["name"] + " command received.")
# Listen for the gpioControl. This name configured in Losant
if command["name"] == "toggle":
# toggle the LED
led.toggle()
if command["name"] == "switch_on":
# toggle the LED
led.on()
if command["name"] == "switch_off":
# toggle the LED
led.off()
def sendDeviceState():
print("Sending Device State")
device.send_state({"button": True})
# Listen for commands.
device.add_event_observer("command", on_command)
print("Listening for device commands")
button.when_pressed = sendDeviceState # Send device state when button is pressed
# Connect to Losant and leave the connection open
device.connect(blocking=True)