forked from OnionIoT/smart-plant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
losantHelper.py
57 lines (48 loc) · 1.32 KB
/
losantHelper.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
import time
from losantmqtt import Device
device = None
waterPlantFunction = None
# check if config file has: deviceId, key, and secret
# if it does, return True
# if not, return False
def isConfigValid(config):
bValid = False
if 'deviceId' in config:
bValid = True
if 'key' in config:
bValid = True
if 'secret' in config:
bValid = True
if not bValid:
print("ERROR: Losant config file must contain:")
print(" deviceId")
print(" key")
print(" secret")
return bValid
# carry out actions from received commands
def onCommand(device, command):
print("> Losant command!")
if command["name"] == "waterPlant":
print(" > Watering plant!")
try:
duration = int(command["payload"])
waterPlantFunction(duration)
except:
waterPlantFunction()
# initialize mqtt connection with losant
def init(deviceId, key, secret, waterPlantFunctionPtr=None):
global device
# Construct device
device = Device(deviceId, key, secret)
# setup command functions
global waterPlantFunction
waterPlantFunction = waterPlantFunctionPtr
# Listen for commands
device.add_event_observer("command", onCommand)
# Connect to Losant.
device.connect(blocking=False)
# send state measurement to Losant
def sendMeasurement(stateName, stateValue):
device.loop()
if device.is_connected():
device.send_state({stateName: stateValue})