summaryrefslogtreecommitdiff
path: root/main.cpp
blob: 9dd61f24ef6ddc08f1bbe342131eea8a01e3ed3b (plain)
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/*
 * Copyright (C) 2015 by Multi-Tech Systems
 *
 * This file is part of lora-query.
 *
 * lora-query is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * lora-query is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with lora-query.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <mts/MTS_Text.h>
#include <mts/MTS_Logger.h>
#include <json/json.h>
#include <getopt.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
#include <fstream>
#include <algorithm>
#include "Version.h"

#define INET_ADDR "127.0.0.1"
#define INET_PORT 6677
#define MAX_RECEIVED_BYTES 2000
#define TIMEOUT 100 /* By default 100 msec */

int opt_get_stats = 0;
int opt_get_nodelist = 0;
int opt_get_json = 0;
int opt_stats_reset = 0;
int opt_get_nodeconfig = 0;
int opt_add_node = 0;
int opt_delete_node = 0;
int opt_update_node = 0;
int opt_command = 0;
int opt_timeout = 0;

char* command_command;
char* node_get_addr;
char* node_delete_addr;
char* node_config_addr;
char* node_update_addr;
char* node_update_field;
char* node_update_value;
int node_add_count = 0;
char* node_add_args[6];
int command_count = 0;
char* command_args[20];

int timeout = TIMEOUT;

const char* cmd_stats = "stats";
const char* cmd_stats_reset = "stats reset";
const char* cmd_node_list = "node stats";
const char* cmd_node_config = "node config";
const char* cmd_node_update = "node update";
const char* cmd_node_delete = "node delete";
const char* cmd_nodeadd = "node add";
const std::string lora_command_output("/var/tmp/lora_command_output");
const std::string lora_network_stats_json("/var/tmp/lora_network_stats.json");
const std::string lora_network_nodelist("/var/tmp/lora_network_nodelist");
const std::string lora_network_nodelist_json("/var/tmp/lora_network_nodelist.json");
const std::string lora_network_nodeconfig("/var/tmp/lora_network_nodeconfig");
const std::string lora_network_nodeconfig_json("/var/tmp/lora_network_nodeconfig.json");
std::stringstream receiveStream;

const int nodeSize = 16;
const int configSize = 7;
const std::string NODE_ADDR("nodeAddr");
const std::string NODE_DEV_EUI("devEui");
const std::string NODE_APP_EUI("appEui");
const std::string NODE_APP_KEY("appKey");
const std::string NODE_NS_KEY("nsKey");
const std::string NODE_DS_KEY("dsKey");
const std::string NODE_CLASS("class");
const std::string NODE_JOINED("joined");
const std::string NODE_SEQ_NUM("seqNum");
const std::string NODE_PKTS_UP("pktsUp");
const std::string NODE_PKTS_DOWN("pktsDown");
const std::string NODE_PKTS_1ST("pkts1st");
const std::string NODE_PKTS_2ND("pkts2nd");
const std::string NODE_DROPPED("dropped");
const std::string NODE_RSSI_MIN("rssiMin");
const std::string NODE_RSSI_MAX("rssiMax");
const std::string NODE_RSSI_AVR("rssiAvg");
const std::string NODE_SNR_MIX("snrMin");
const std::string NODE_SNR_MAX("snrMax");
const std::string NODE_SNR_AVR("snrAvg");

void runCmd(const char *command);
void printStats(void);
void printNodeList(void);
void printNodeConfig(void);
void saveToFile(const std::string& fileName, const std::string& buffer);
void parseOptions(int argc, char** argv);
void printHelp(const std::string& sApp);
std::string trim(std::string& str);

int main(int argc, char**argv) {
    parseOptions(argc, argv);

    if (opt_stats_reset) {
        runCmd(cmd_stats_reset);
    }

    if (opt_command) {
        std::stringstream cmd;

        for (int i = 0; i < command_count; i++) {
            cmd << " " << command_args[i];
        }

        runCmd(cmd.str().c_str());
        if (receiveStream.str().empty()) {
	        return 0;
        }
        saveToFile(lora_command_output, receiveStream.str());
        std::cout << receiveStream.str();
    }

    if (opt_get_stats) {
        runCmd(cmd_stats);
        printStats();
    }
    if (opt_get_nodelist) {
        runCmd(cmd_node_list);
        if (opt_get_json) {
            printNodeList();
        } else {
            if (receiveStream.str().empty()) {
                return 0;
            }
            saveToFile(lora_network_nodelist, receiveStream.str());
            std::cout << receiveStream.str();
        }
    }
    if (opt_get_nodeconfig) {
        char buff[256];
        snprintf(buff, 256, "%s %s", cmd_node_config, node_config_addr);
        runCmd(buff);
        if (opt_get_json) {
            printNodeConfig();
        } else {
            if (!receiveStream.str().empty()) {
                saveToFile(lora_network_nodelist, receiveStream.str());
                std::cout << receiveStream.str();
            }
        }
    }
    if (opt_add_node) {
        if (node_add_count < 4) {
            std::cout << "usage: --node-add <NODE-ADDR> [CLASS] <APP-EUI> <DEV-EUI> ([APP-KEY] | [NET-SKEY] [APP-SKEY])\n";
            return 0;
        }

        std::stringstream cmd;
        cmd << cmd_nodeadd;

        for (int i = 0; i < node_add_count; i++) {
            cmd << " " << node_add_args[i];
        }

        runCmd(cmd.str().c_str());

        if (!receiveStream.str().empty()) {
            std::cout << receiveStream.str();
        }
    }
    if (opt_delete_node) {
        char buff[256];
        snprintf(buff, 256, "%s %s", cmd_node_delete, node_delete_addr);
        runCmd(buff);
        if (!receiveStream.str().empty()) {
            std::cout << receiveStream.str();
        }
    }
    if (opt_update_node) {

        std::stringstream cmd;
        cmd << cmd_node_update;

        cmd << " " << node_update_addr;
        cmd << " " << node_update_field;
        cmd << " " << node_update_value;

        runCmd(cmd.str().c_str());

        if (!receiveStream.str().empty()) {
            std::cout << receiveStream.str();
        }
    }

    return 0;
}

void runCmd(const char *command) {
    int sockfd;
    struct sockaddr_in servaddr;
    int receiveBytes = 0;
    char receiveMessage[MAX_RECEIVED_BYTES];
    struct timeval tv;


    if (opt_timeout) {
        tv.tv_sec = timeout / 1000;
        tv.tv_usec = (timeout % 1000) * 1000;
    } else {
        // set initial timeout to 5 seconds
        tv.tv_sec = 5;
        tv.tv_usec = 0;
    }

    receiveStream.str("");
    receiveStream.clear();

    if (system("netstat -lanu | grep 6677 &> /dev/null")) {
        return;
    }

    if (NULL == command) {
        printError("Command is null\n");
        return;
    }

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(INET_ADDR);
    servaddr.sin_port = htons(INET_PORT);
    memset(receiveMessage, 0, MAX_RECEIVED_BYTES);

    if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
        printError("setsockopt error\n");
        return;
    }

    // Lower timeout for subsequent reads
    tv.tv_sec = timeout / 1000;
    tv.tv_usec = (timeout % 1000) * 1000;

    sendto(sockfd, command, strlen(command), 0, (struct sockaddr *) &servaddr, sizeof(servaddr));

    while (1) {
        receiveBytes = recvfrom(sockfd, receiveMessage, MAX_RECEIVED_BYTES, 0, NULL, NULL);
        if (receiveBytes < 0) {
            /*printf("timeout\n");*/
            break;
        }

        // Lower timeout for subsequent reads
        if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
            printError("setsockopt error\n");
            return;
        }

        receiveStream << std::string(receiveMessage, receiveBytes);
    }
}

void printStats() {
    Json::Reader reader;
    Json::Value stats;

    if (receiveStream.str().empty()) {
        return;
    }

    if (!reader.parse(receiveStream.str(), stats), false) {
        printError("Error parsing JSON: [%s]", receiveStream.str().c_str());
    }

    // Replace underscores keys with camel-case.
    if (stats.isObject()) {
        Json::Value::Members keys = stats.getMemberNames();
        std::string newKey;
        for (Json::Value::Members::iterator it = keys.begin(); it != keys.end(); ++it) {
            const std::string& key = *it;
            newKey.clear();
            for (size_t i = 0; i < key.length(); ++i) {
                if (('_' == key[i]) || ('-' == key[i])) {
                    if ((i + 1) < key.length()) {
                        newKey.push_back(std::toupper(key[++i]));
                    }
                } else {
                    newKey.push_back(key[i]);
                }
            }
            stats[newKey] = stats[key];
            stats.removeMember(key);
        }
    }
    saveToFile(lora_network_stats_json, stats.toStyledString());
    std::cout << stats.toStyledString();
}

void printNodeConfig() {
    std::string line;
    std::vector < std::string > parts;
    Json::Value nodeList = Json::ValueType::arrayValue;

    if (receiveStream.str().empty()) {
        return;
    }

    getline(receiveStream, line);
    while (1) {
        getline(receiveStream, line);
        if (line.size() == 0)
            break;

        line = trim(line);
        parts = MTS::Text::split(line, " ");

        if (configSize == (int)parts.size()) {
            Json::Value jNode(Json::objectValue);
            int index = 0;
            jNode[NODE_ADDR] = parts[index++];
            jNode[NODE_DEV_EUI] = parts[index++];
            jNode[NODE_CLASS] = parts[index++];
            jNode[NODE_APP_EUI] = parts[index++];
            jNode[NODE_APP_KEY] = parts[index++];
            jNode[NODE_NS_KEY] = parts[index++];
            jNode[NODE_DS_KEY] = parts[index++];
            nodeList.append(jNode);
        }
        else {
            printError("Incorrect Node Data!  parts.size() = [%d]\n", parts.size());
        }
    }
    saveToFile(lora_network_nodelist_json, nodeList.toStyledString());
    std::cout << nodeList.toStyledString();
}

void printNodeList() {
    std::string line;
    std::vector < std::string > parts;
    Json::Value nodeList = Json::ValueType::arrayValue;

    if (receiveStream.str().empty()) {
        return;
    }

    getline(receiveStream, line);
    while (1) {
        getline(receiveStream, line);
        if (line.size() == 0)
            break;

        line = trim(line);
        parts = MTS::Text::split(line, " ");

        if (nodeSize == (int)parts.size()) {
            Json::Value jNode(Json::objectValue);
            int index = 0;
            jNode[NODE_ADDR] = parts[index++];
            jNode[NODE_DEV_EUI] = parts[index++];
            jNode[NODE_CLASS] = parts[index++];
            jNode[NODE_JOINED] = parts[index++];
            jNode[NODE_SEQ_NUM] = (uint32_t)std::strtoul(parts[index++].c_str(), nullptr, 10);
            jNode[NODE_PKTS_UP] = (uint32_t)std::strtoul(parts[index++].c_str(), nullptr, 10);
            jNode[NODE_PKTS_DOWN] = (uint32_t)std::strtoul(parts[index++].c_str(), nullptr, 10);
            jNode[NODE_PKTS_1ST] = (uint32_t)std::strtoul(parts[index++].c_str(), nullptr, 10);
            jNode[NODE_PKTS_2ND] = (uint32_t)std::strtoul(parts[index++].c_str(), nullptr, 10);
            jNode[NODE_DROPPED] = (uint32_t)std::strtoul(parts[index++].c_str(), nullptr, 10);
            jNode[NODE_RSSI_MIN] = atof(parts[index++].c_str());
            jNode[NODE_RSSI_MAX] = atof(parts[index++].c_str());
            jNode[NODE_RSSI_AVR] = atof(parts[index++].c_str());
            jNode[NODE_SNR_MIX] = atof(parts[index++].c_str());
            jNode[NODE_SNR_MAX] = atof(parts[index++].c_str());
            jNode[NODE_SNR_AVR] = atof(parts[index++].c_str());

            nodeList.append(jNode);
        }
        else {
            printError("Incorrect Node Data!  parts.size() = [%d]\n", parts.size());
        }
    }
    saveToFile(lora_network_nodelist_json, nodeList.toStyledString());
    std::cout << nodeList.toStyledString();
}

void saveToFile(const std::string& fileName, const std::string& buffer) {
    std::ofstream outFile;
    outFile.open(fileName);
    outFile << buffer;
    outFile.close();
}

void parseOptions(int argc, char** argv) {

    if (argc == 1) {
        printHelp(argv[0]);
        exit(0);
    }

    const char* short_options = "hvsrnc:a:u:d:jt:x:";

    const struct option long_options[] = {
                                           { "help", no_argument, 0, 'h' },
                                           { "version", no_argument, 0, 'v' },
                                           { "stats", no_argument, 0, 's' },
                                           { "stats-reset", no_argument, 0, 'r' },
                                           { "node-list", no_argument, 0, 'n' },
                                           { "command", required_argument, 0, 'x' },
                                           { "json", no_argument, 0, 'j' },
                                           { "timeout", required_argument, 0, 't' },
                                           { 0, 0, 0, 0 }
    };

    int rez;
    int option_index;

    while ((rez = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) {
        switch (rez) {
        	case 'x': {
        		++opt_command;
        		command_args[command_count++] = optarg;
                for (int i = optind; i < argc; i++) {
                    command_args[command_count++] = argv[i];
                }
        		break;
        	}
            case 's': {
                ++opt_get_stats;
                break;
            }
            case 'r': {
                ++opt_stats_reset;
                break;
            }
            case 'n': {
                ++opt_get_nodelist;
                break;
            }
            case 'j': {
                ++opt_get_json;
                break;
            }
            case 't': {
                opt_timeout = 1;
                timeout = atoi(optarg);
                break;
            }
            case 'v':
                printf("Version: %s\n", Version::version.c_str());
                exit(0);
                break;
            case 'h':
                case '?':
                default: {
                printHelp(argv[0]);
                exit(0);
                break;
            }
        };
    };
}

void printHelp(const std::string& sApp) {
    printf("Usage: %s [-t timeout] [-s] [-n]\n", sApp.c_str());
    printf("\tSimple UDP client utility to pull info from LoRa Network server\n");
    printf("\t--timeout (t)     : UDP recv timeout, default: 100 (msecs)\n");
    printf("\t--stats (s)       : get LoRa Network server statistics\n");
    printf("\t--stats-reset (r) : reset LoRa Network server statistics\n");
    printf("\t--node-list (n)   : get Node List\n");
    printf("\t--command (x) : send command string to network server\n");
    printf("\t\tusage: --command <COMMAND-NAME> <COMMAND-OPTIONS> ...\n");
    printf("\t\tex:    --command device list json\n");
    printf("\t\tex:    -x help\n");
    printf("\t--json (j)        : data in json format\n");
    printf("\t--help (?)        : returns this message\n");
    printf("\t--version (v)     : print version\n");
}

std::string trim(std::string& str) {
    str.erase(std::unique(str.begin(), str.end(), [](char a, char b) {return a == ' ' && b == ' ';}), str.end());
    return str;
}