-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathc8y_onboard.py
139 lines (120 loc) · 5.81 KB
/
c8y_onboard.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import paho.mqtt.client as mqtt
import sys, os.path, time
import logging, json
class Onboard():
def __init__(self, device_id):
self.device_id = device_id
self.credentialsReceived = False
self.credentialsFile = "frpresales-credentials.json"
self.bootstrapUsername = "management/devicebootstrap"
self.bootstrapPassword = "Fhdt1bb1f"
self.brokerUrl = "mqtt.cumulocity.com"
self.credentials = {}
self.auth = ()
def dcr_handler(self, client, userdata, message):
payload = message.payload.decode("utf-8")
print("Received message " + payload)
if payload.startswith("70,"):
[tenant, username, password] = payload.split(",")[1:4]
print(f"Credentials received! {tenant}/{username}, {password}")
self.credentials[self.device_id] = {"tenant": tenant, "username": username, "password": password}
with open(self.credentialsFile,"w") as cred_file:
cred_file.write(json.dumps(self.credentials, indent=4, sort_keys=True))
self.credentialsReceived = True
print("Credentials successfully written to file!")
def error_handler(self, client, userdata, message):
payload = message.payload.decode("utf-8")
print("Error message " + payload)
def default_message_callback(self, client, userdata, message):
payload = message.payload.decode("utf-8")
print(f"Unhandled message received: {payload}")
def publish(self, topic, message, waitForAck = False):
message_info = self.client.publish(topic, message, 2)
if message:
print(f"Publishing message: '{message}' with id {message_info.mid}")
else:
print(f"Publishing message with id {message_info.mid}")
if (waitForAck):
print(f"Waiting for message {message_info.mid} to be acknowledeged...")
message_info.wait_for_publish()
print(f"Message {message_info.mid} acknowledeged")
def on_publish(self, client, userdata, mid):
print(f"Message published: {str(mid)}")
def on_connect(self, client, userdata, flags, rc):
print(f"Connection returned result: {mqtt.connack_string(rc)}")
def bootstrap(self):
print("Credentials not found. Bootstrapping device...")
self.initMqttClient()
self.client.username_pw_set(self.bootstrapUsername, self.bootstrapPassword)
self.client.connect(self.brokerUrl, 1883)
self.client.loop_start()
self.client.subscribe("s/e")
self.client.subscribe("s/dcr")
self.message_callback_add("s/e", self.error_handler)
self.message_callback_add("s/dcr", self.dcr_handler)
print("Waiting for device to be registered...")
cpt = 1
while not self.credentialsReceived:
print("Attempt: " + str(cpt))
self.publish("s/ucr", None, True)
time.sleep(1.0)
cpt = cpt + 1
self.client.disconnect()
self.connect()
def connect(self, tenant = None, username = None, password = None):
if (os.path.isfile(self.credentialsFile)):
with open(self.credentialsFile) as cred_file:
self.credentials = json.load(cred_file)
if self.device_id in self.credentials:
tenant = self.credentials[self.device_id]["tenant"]
username = self.credentials[self.device_id]["username"]
password = self.credentials[self.device_id]["password"]
if tenant and username and password:
self.credentials[self.device_id] = {"tenant": tenant, "username": username, "password": password}
with open(self.credentialsFile,"w") as cred_file:
json.dump(self.credentials, cred_file)
self.auth = (tenant + "/" + username, password)
print("File with credentials found. Using them to connect...")
print(f"Connecting with: {tenant}/{username}, {password}")
self.initMqttClient()
self.client.username_pw_set(tenant + "/" + username, password)
self.client.connect(self.brokerUrl, 1883)
self.client.loop_start()
self.client.subscribe("s/e")
self.message_callback_add("s/e", self.error_handler)
print("Connected!")
else:
self.bootstrap()
def initMqttClient(self):
self.client = mqtt.Client(client_id=self.device_id)
logger = logging.getLogger(__name__)
self.client.enable_logger(logger)
self.client.on_publish = self.on_publish
self.client.on_connect = self.on_connect
self.client.on_message = self.default_message_callback
def message_callback_add(self, sub, callback):
self.client.message_callback_add(sub, callback)
def subscribe(self, topic):
self.client.subscribe(topic, 2)
def getCredentials(self):
return self.credentials[self.device_id]
def getAuth(self):
return self.auth
if __name__ == "__main__":
device_name = sys.argv[1]
device_id = sys.argv[2]
serial = sys.argv[3]
o = Onboard(device_id);
o.connect()
print("Creating the device in Cumulocity...")
o.publish("s/us", "100," + device_name + ",c8y_Test", True)
print("Sending additional info...")
o.publish("s/us", "110," + serial + ",Test,Rev0.1", True)
o.publish("s/us", "400,registered,Device connected", True)
o.publish("s/us", '''211,20.4,2019-09-03T08:36:10.432Z
211,20.5,2019-09-03T08:36:11.432Z
211,20.6,2019-09-03T08:36:12.432Z
211,20.7,2019-09-03T08:36:13.432Z
211,20.8,2019-09-03T08:36:14.432Z
211,20.9,2019-09-03T08:36:15.432Z
211,20.10,2019-09-03T08:36:16.432Z''', True)