-
Notifications
You must be signed in to change notification settings - Fork 0
/
iotfclient.c
401 lines (318 loc) · 9.36 KB
/
iotfclient.c
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*******************************************************************************
* Copyright (c) 2015 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Jeffrey Dare - initial implementation and API implementation
*******************************************************************************/
#include <stdio.h>
#include <signal.h>
#include <memory.h>
#include <sys/time.h>
#include "iotfclient.h"
unsigned char buf[100];
unsigned char readbuf[100];
int isQuickstart = 0 ;
//Command Callback
commandCallback cb;
//util functions
char *trim(char *str);
int get_config(char * filename, struct config * configstr);
void messageArrived(MessageData* md);
int length(char *str);
int retry_connection(Iotfclient *client);
int reconnect_delay(int i);
/**
* Function used to initialize the IoTF client using the config file which is generated when you register your device
* @param configFilePath - File path to the configuration file
*
* @return int return code
* error codes
* CONFIG_FILE_ERROR -3 - Config file not present or not in right format
*/
int initialize_configfile(Iotfclient *client, char *configFilePath)
{
struct config configstr = {"", "", "", "", ""};
int rc = 0;
rc = get_config(configFilePath, &configstr);
if(rc != SUCCESS) {
return rc;
}
if(!length(configstr.org) || !length(configstr.type) || !length(configstr.id) || !length(configstr.authmethod) || !length(configstr.authtoken)) {
printf ("returning config file error ");
return CONFIG_FILE_ERROR;
}
client->config = configstr;
return rc;
}
/**
* Function used to initialize the IoTF client
* @param org - Your organization ID
* @param type - The type of your device
* @param id - The ID of your device
* @param auth-method - Method of authentication (the only value currently supported is “token”)
* @param auth-token - API key token (required if auth-method is “token”)
*
* @return int return code
*/
int initialize(Iotfclient *client, char *orgId, char *deviceType, char *deviceId, char *authmethod, char *authToken)
{
struct config configstr = {"", "", "", "", ""};
if(orgId==NULL || deviceType==NULL || deviceId==NULL) {
return MISSING_INPUT_PARAM;
}
strncpy(configstr.org, orgId, 15);
strncpy(configstr.type, deviceType, 50);
strncpy(configstr.id, deviceId, 50);
if((strcmp(orgId,"quickstart") != 0)) {
if(authmethod == NULL || authToken == NULL) {
return MISSING_INPUT_PARAM;
}
strncpy(configstr.authmethod, authmethod, 10);
strncpy(configstr.authtoken, authToken, 50);
}
client->config = configstr;
return SUCCESS;
}
/**
* Function used to initialize the IoTF client
* @param client - Reference to the Iotfclient
*
* @return int return code
*/
int connectiotf(Iotfclient *client)
{
int rc = 0;
if(strcmp(client->config.org,"quickstart") == 0){
isQuickstart = 1 ;
}
const char* messagingUrl = ".messaging.internetofthings.ibmcloud.com";
char hostname[strlen(client->config.org) + strlen(messagingUrl) + 1];
sprintf(hostname, "%s%s", client->config.org, messagingUrl);
//TODO : change to 8883 if registered, add support when available in MQTTClient
int port = 1883;
char clientId[strlen(client->config.org) + strlen(client->config.type) + strlen(client->config.id) + 5];
sprintf(clientId, "d:%s:%s:%s", client->config.org, client->config.type, client->config.id);
NewNetwork(&client->n);
ConnectNetwork(&client->n, hostname, port);
MQTTClient(&client->c, &client->n, 1000, buf, 100, readbuf, 100);
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.willFlag = 0;
data.MQTTVersion = 3;
data.clientID.cstring = clientId;
if(!isQuickstart) {
printf("Connecting to registered service with org %s\n", client->config.org);
data.username.cstring = "use-token-auth";
printf ("the auth token being used is [%s]\n", client->config.authtoken);
data.password.cstring = client->config.authtoken;
}
data.keepAliveInterval = 10;
data.cleansession = 1;
rc = MQTTConnect(&client->c, &data);
if(!isQuickstart) {
//Subscibe to all commands
subscribeCommands(client);
}
return rc;
}
/**
* Function used to Publish events from the device to the IoTF service
* @param eventType - Type of event to be published e.g status, gps
* @param eventFormat - Format of the event e.g json
* @param data - Payload of the event
* @param QoS - qos for the publish event. Supported values : QOS0, QOS1, QOS2
*
* @return int return code from the publish
*/
int publishEvent(Iotfclient *client, char *eventType, char *eventFormat, unsigned char* data, enum QoS qos)
{
int rc = -1;
char publishTopic[strlen(eventType) + strlen(eventFormat) + 16];
sprintf(publishTopic, "iot-2/evt/%s/fmt/%s", eventType, eventFormat);
printf ("publishTopic = %s\n", publishTopic );
MQTTMessage pub;
pub.qos = qos;
pub.retained = '0';
pub.payload = data;
pub.payloadlen = strlen(data);
rc = MQTTPublish(&client->c, publishTopic , &pub);
if(rc != SUCCESS) {
printf("connection lost.. \n");
retry_connection(client);
rc = MQTTPublish(&client->c, publishTopic , &pub);
}
return rc;
}
/**
* Function used to set the Command Callback function. This must be set if you to recieve commands.
*
* @param cb - A Function pointer to the commandCallback. Its signature - void (*commandCallback)(char* commandName, char* payload)
* @return int return code
*/
void setCommandHandler(Iotfclient *client, commandCallback handler)
{
cb = handler;
}
/**
* Function used to subscribe to all commands. This function is by default called when in registered mode.
*
* @return int return code
*/
int subscribeCommands(Iotfclient *client)
{
int rc = -1;
rc = MQTTSubscribe(&client->c, "iot-2/cmd/+/fmt/+", QOS0, messageArrived);
return rc;
}
/**
* Function used to Yield for commands.
* @param time_ms - Time in milliseconds
* @return int return code
*/
int yield(Iotfclient *client, int time_ms)
{
int rc = 0;
rc = MQTTYield(&client->c, time_ms);
return rc;
}
/**
* Function used to check if the client is connected
*
* @return int return code
*/
int isConnected(Iotfclient *client)
{
return client->c.isconnected;
}
/**
* Function used to disconnect from the IoTF service
*
* @return int return code
*/
int disconnect(Iotfclient *client)
{
int rc = 0;
rc = MQTTDisconnect(&client->c);
client->n.disconnect(&client->n);
return rc;
}
//Handler for all commands. Invoke the callback.
void messageArrived(MessageData* md)
{
if(cb != 0) {
MQTTMessage* message = md->message;
char *topic = malloc(md->topicName->lenstring.len+1);
sprintf(topic,"%.*s",md->topicName->lenstring.len,md->topicName->lenstring.data);
void *payload = message->payload;
strtok(topic, "/");
strtok(NULL, "/");
char *commandName = strtok(NULL, "/");
strtok(NULL, "/");
char *format = strtok(NULL, "/");
free(topic);
(*cb)(commandName, format, payload);
}
}
//Utility Functions
//Trimming characters
char *trim(char *str) {
size_t len = 0;
char *frontp = str - 1;
char *endp = NULL;
if (str == NULL)
return NULL;
if (str[0] == '\0')
return str;
len = strlen(str);
endp = str + len;
while (isspace(*(++frontp)))
;
while (isspace(*(--endp)) && endp != frontp)
;
if (str + len - 1 != endp)
*(endp + 1) = '\0';
else if (frontp != str && endp == frontp)
*str = '\0';
endp = str;
if (frontp != str) {
while (*frontp)
*endp++ = *frontp++;
*endp = '\0';
}
return str;
}
// This is the function to read the config from the device.cfg file
int get_config(char * filename, struct config * configstr) {
FILE* prop;
char str1[10], str2[10];
prop = fopen(filename, "r");
if (prop == NULL) {
printf("Config file not found at %s\n",filename);
return CONFIG_FILE_ERROR;
}
char line[256];
int linenum = 0;
while (fgets(line, 256, prop) != NULL) {
char* prop;
char* value;
linenum++;
if (line[0] == '#')
continue;
prop = strtok(line, "=");
prop = trim(prop);
value = strtok(NULL, "=");
value = trim(value);
if (strcmp(prop, "org") == 0)
strncpy(configstr->org, value, 10);
else if (strcmp(prop, "type") == 0)
strncpy(configstr->type, value, 50);
else if (strcmp(prop, "id") == 0)
strncpy(configstr->id, value, 50);
else if (strcmp(prop, "auth-token") == 0)
strncpy(configstr->authtoken, value, 50);
else if (strcmp(prop, "auth-method") == 0)
strncpy(configstr->authmethod, value, 10);
}
printf ("returning success in get_config() ");
return SUCCESS;
}
int length(char *str)
{
int length = 0;
while (str[length] != '\0')
length++;
return length;
}
//Staggered retry
int retry_connection(Iotfclient *client)
{
int retry = 1;
printf("Attempting to connect\n");
while(connectiotf(client) != SUCCESS)
{
printf("Retry Attempt #%d ", retry);
int delay = reconnect_delay(retry++);
printf(" next attempt in %d seconds\n", delay);
sleep(delay);
}
}
/* Reconnect delay time
* depends on the number of failed attempts
*/
int reconnect_delay(int i)
{
if (i < 10) {
return 3; // first 10 attempts try every 3 seconds
}
if (i < 20)
return 60; // next 10 attempts retry after every 1 minute
return 600; // after 20 attempts, retry every 10 minutes
}