-
Notifications
You must be signed in to change notification settings - Fork 8
/
sync_device_key.py
97 lines (73 loc) · 2.2 KB
/
sync_device_key.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
from iotc.models import Command, Storage, CredentialsCache, Property
from iotc import IoTCClient
from iotc import (
IOTCConnectType,
IOTCLogLevel,
IOTCEvents,
)
import os
import configparser
from re import M
import sys
import time
from random import randint
config = configparser.ConfigParser()
config.read(os.path.join(os.path.dirname(__file__), "samples.ini"))
if config["DEFAULT"].getboolean("Local"):
sys.path.insert(0, "src")
device_id = config["DEVICE_M3"]["DeviceId"]
scope_id = config["DEVICE_M3"]["ScopeId"]
key = config["DEVICE_M3"]["DeviceKey"]
hub_name = config["DEVICE_M3"]["HubName"]
class MemStorage(Storage):
def retrieve(self):
return CredentialsCache(
hub_name,
device_id,
key,
)
def persist(self, credentials):
# a further option would be updating config file with latest hub name
return None
# optional model Id for auto-provisioning
try:
model_id = config["DEVICE_M3"]["ModelId"]
except:
model_id = None
def on_props(prop: Property):
print(f"Received {prop.name}:{prop.value}")
return True
def on_commands(command):
print("Received command {} with value {}".format(command.name, command.value))
command.reply()
def on_enqueued_commands(command):
print("Received offline command {} with value {}".format(
command.name, command.value))
# change connect type to reflect the used key (device or group)
client = IoTCClient(
device_id,
scope_id,
IOTCConnectType.IOTC_CONNECT_DEVICE_KEY,
key,
storage=MemStorage(),
)
if model_id != None:
client.set_model_id(model_id)
client.set_log_level(IOTCLogLevel.IOTC_LOGGING_ALL)
client.on(IOTCEvents.IOTC_PROPERTIES, on_props)
client.on(IOTCEvents.IOTC_COMMAND, on_commands)
client.on(IOTCEvents.IOTC_ENQUEUED_COMMAND, on_enqueued_commands)
def main():
client.connect()
client.send_property({"writeableProp": 50})
while not client.terminated():
if client.is_connected():
client.send_telemetry(
{
"temperature": randint(20, 45)
}, {
"$.sub": "firstcomponent"
}
)
time.sleep(3)
main()