forked from cloud4rpi/cloud4rpi-esp8266-micropython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main-gpio.py
111 lines (87 loc) · 2.89 KB
/
main-gpio.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
from time import time, sleep
from machine import Pin, reset
from network import WLAN, STA_IF
import cloud4rpi
# Enter the name of your Wi-Fi and its password here.
# If you have an open Wi-Fi, simply remove the second item.
WIFI_SSID_PASSWORD = '__SSID__', '__PWD__'
# Enter your device token here. To get the token,
# sign up at https://cloud4rpi.io and create a device.
DEVICE_TOKEN = '__YOUR_DEVICE_TOKEN__'
LED_PIN = 12
BUTTON_PIN = 16
WIFI_CONNECTION_TIMEOUT = 10 # seconds
PUBLISH_INTERVAL = 60 # seconds
# --------------------------------------------------------------------------- #
led = Pin(LED_PIN, Pin.OUT)
button = Pin(BUTTON_PIN, Pin.IN)
button_state_prev = button.value()
button_state_now = button_state_prev
btn_value = False
def on_led(value):
led.value(not value)
return not led.value()
def get_btn(value):
global btn_value
return btn_value
STA = WLAN(STA_IF)
STA.active(True)
while not STA.isconnected():
print("Connecting to Wi-Fi...")
wifi_reconnect_time = time() + WIFI_CONNECTION_TIMEOUT
STA.connect(*WIFI_SSID_PASSWORD)
while not STA.isconnected() and time() < wifi_reconnect_time:
sleep(0.5)
if not STA.isconnected():
print("Connection FAILED!")
continue
print("Connected!")
device = None
while not device:
if not STA.isconnected():
print("Wi-Fi Connection failed!")
break
print("Connecting to Cloud4RPi...")
device = cloud4rpi.connect(DEVICE_TOKEN)
if not device:
continue
print("Connected!")
# Available types: 'bool', 'numeric', 'string'
device.declare({
'LED': {
'type': 'bool',
'value': False,
'bind': on_led
},
'Button': {
'type': 'bool',
'value': False,
'bind': get_btn
}
})
device.declare_diag({
'IP Address': STA.ifconfig()[0]
})
device.publish_diag()
device.publish_config()
device.publish_data()
print("Waiting for messages...")
next_publish = time() + PUBLISH_INTERVAL
while True:
try:
device.check_commands()
button_state_prev = button_state_now
button_state_now = button.value()
# Falling edge detection
if button_state_prev == 1 and button_state_now == 0:
btn_value = not btn_value
device.publish_data()
if time() >= next_publish:
print("Scheduled publishing...")
device.publish_data()
next_publish = time() + PUBLISH_INTERVAL
sleep(0.1)
except Exception as e:
print("%s: %s" % (type(e).__name__, e))
device = None
break