-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain-ds18b20.py
102 lines (78 loc) · 2.69 KB
/
main-ds18b20.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
from time import time, sleep
from machine import Pin, reset
from network import WLAN, STA_IF
from onewire import OneWire
from ds18x20 import DS18X20
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__'
ONEWIRE_DATA_PIN = 14
WIFI_CONNECTION_TIMEOUT = 10 # seconds
# Decrease this value for testing purposes.
PUBLISH_INTERVAL = 300 # seconds
# --------------------------------------------------------------------------- #
ds18 = DS18X20(OneWire(Pin(ONEWIRE_DATA_PIN)))
thermometers = ds18.scan()
print("Found", len(thermometers), "thermometers:", thermometers)
def read_thermometers():
if thermometers:
print("Getting temperatures from DS18B20 sensors...")
ds18.convert_temp()
sleep(1)
def get_temperature(value):
return ds18.read_temp(thermometers[0]) if thermometers else None
read_thermometers()
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({
'Temperature': {
'type': 'numeric',
'value': None,
'bind': get_temperature
}
})
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()
if time() >= next_publish:
read_thermometers()
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