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
|
/**********************************************************************
* COPYRIGHT 2020 MULTI-TECH SYSTEMS, INC.
*
* ALL RIGHTS RESERVED BY AND FOR THE EXCLUSIVE BENEFIT OF
* MULTI-TECH SYSTEMS, INC.
*
* MULTI-TECH SYSTEMS, INC. - CONFIDENTIAL AND PROPRIETARY
* INFORMATION AND/OR TRADE SECRET.
*
* NOTICE: ALL CODE, PROGRAM, INFORMATION, SCRIPT, INSTRUCTION,
* DATA, AND COMMENT HEREIN IS AND SHALL REMAIN THE CONFIDENTIAL
* INFORMATION AND PROPERTY OF MULTI-TECH SYSTEMS, INC.
* USE AND DISCLOSURE THEREOF, EXCEPT AS STRICTLY AUTHORIZED IN A
* WRITTEN AGREEMENT SIGNED BY MULTI-TECH SYSTEMS, INC. IS PROHIBITED.
*
***********************************************************************/
#include "Device.h"
const std::vector<std::string> Device::apIdentifiers = {"ap1", "ap2", "lora", "lora-2", "slot1", "slot2"};
const std::regex Device::apFilters("(modalias)|(power)(.*)|(subsystem)|(uevent)");
const std::regex Device::lora15Filters("(MTAC-LORA-)(.*)|(MTCAP-LORA-)(.*)|(MTLGA-)(.*)|(MTCDT3-)(.*)");
const std::regex Device::loraG16Filters("(MTAC-LORA-G16)(.*)");
const std::regex Device::loraG64Filters("(MTAC-LORA-G64)(.*)");
const std::regex Device::gpiobFilters("(MTAC-GPIOB)|(MMTAC-GPIOI)");
const std::regex Device::mfserFilters("(MTAC-MFSER-DTE)|(MTAC-MFSER-DCE)|(MTR-)(.*)");
const std::regex Device::serialModeFilter("(.*)(serial-mode)");
const std::regex Device::storeFilters("(.*)(mac-)(.*)|(.*)(-id)|(uuid)|(.*)(/eui)|(.*)(/cdone)|(.*)(hw-version)|(imei)|(capability)(.*)|(radio-reset-backoff-seconds)|(modalias)|(power)|((subsystem)(.*))|(uevent)|(board-temperature)|(reset)|(led3)|(led-ls)|(usbhd-ps-oc)|(.*)(adc[0-9])|(.*)(din[0-9])|(gpi[0-9])|(gpi[0-9][0-9])");
const std::regex Device::showFilters("(modalias)|(subsystem)|(uevent)");
std::map<std::string, bool> Device::capabilityList = {{"adc", false},{"battery", false},{"bluetooth", false},
{"cell", false},{"cellWwan", false},{"din", false},{"dout", false},{"externalSerialPort", false},
{"gpio", false},{"gps", false},{"lora", false},{"loraNetworkServer", false},
{"nodeRed", false},{"rs232", false},{"rs422", false},{"rs485", false},{"serial", false},
{"supercap", false},{"wifi", false}};
std::map<std::string, std::string> Device::deviceInfoList = {{"deviceId", ""},{"hardwareVersion", ""},
{"imei", ""},{"macAddress", "00:00:00:00:00:00"},{"macBluetooth", "00:00:00:00:00:00"},
{"macWifi", "00:00:00:00:00:00"},{"productId", ""},{"uuid", ""},{"vendorId", ""}};
Device::Device() {
isRoot = !getuid();
verbose = false;
}
bool Device::isAccessoryCard(const char * d_name, const char * dir_name) {
return std::binary_search(apIdentifiers.begin(), apIdentifiers.end(), dir_name) && !regex_match(d_name, apFilters);
}
void Device::sortAccessoryCards() {
rapidjson::SizeType i, j;
for (i = 0; i < accessoryCards.Size() - 1; i++) {
for (j = 0; j < accessoryCards.Size() - i - 1; j++) {
if (accessoryCards[j]["port"].GetString() < accessoryCards[j+1]["port"].GetString()) {
accessoryCards[j].Swap( accessoryCards[j+1]);
}
}
}
}
bool Device::isValidDirectory(const struct dirent * entry, std::string fullPath, const char * d_name) {
std::string path = fullPath + "/" + std::string(d_name);
return (entry->d_type & DT_DIR) && strcmp (d_name, "..") != 0 && strcmp (d_name, ".") != 0 && (path.length() < PATH_MAX);
}
void Device::getSystemTreeJson(const char * dir_name) {
std::string fullPath = SYSFS_PLATFORM + std::string(dir_name);
DIR * d = opendir (fullPath.c_str());
if (!d) {
logError("Cannot open directory " + fullPath);
exitHandler(99);
}
while (1) {
struct dirent * entry = readdir (d); /* Gets subsequent entries from "d" */
if (!entry) { /* If there are no more entries, exit */
break;
}
const char * d_name = entry->d_name; /* Get file name */
std::string fileData;
if (!(entry->d_type & DT_DIR) && (MTS::System::readFile(fullPath + "/" + std::string(d_name), fileData) == 0)) {
fileData = MTS::Text::trim(fileData);
if (strlen(dir_name) > 0) {
if (isAccessoryCard(d_name, dir_name)) {
if (accessoryCard.IsNull()) {
accessoryCard.SetObject();
accessoryCard.AddMember("port", rapidjson::Value().SetString(dir_name, accessoryCardsAlloc), accessoryCardsAlloc);
} else if (accessoryCard["port"] != dir_name) {
accessoryCards.PushBack(accessoryCard, accessoryCardsAlloc);
accessoryCard.SetObject();
accessoryCard.AddMember("port", rapidjson::Value().SetString(dir_name, accessoryCardsAlloc), accessoryCardsAlloc);
}
if (strcmp(d_name, "product-id") == 0) { /* Map card specific details based on the product id */
if (regex_match(fileData, loraG16Filters)) {
Lora21Card lora21(*this, fileData, dir_name);
} else if (regex_match(fileData, loraG64Filters)) {
Lora21ExtCard lora21Ext(*this, fileData, dir_name);
} else if (regex_match(fileData, lora15Filters)) {
Lora15Card lora15(*this, fileData, dir_name);
} else if (regex_match(fileData, gpiobFilters)) {
Gpiob ppiob(*this, fileData, dir_name);
} else if (regex_match(fileData, mfserFilters)) {
Mfser msfer(*this, fileData, dir_name);
}
}
accessoryCard.AddMember(rapidjson::Value().SetString(toCamelCase(d_name).c_str(), accessoryCardsAlloc), rapidjson::Value().SetString(fileData.c_str(), accessoryCardsAlloc), accessoryCardsAlloc);
} else if (strcmp (dir_name, "capability") == 0 && fileData == "1") {
capabilityList[toCamelCase(d_name)] = true;
}
} else if ((entry->d_type != DT_LNK)){
if (deviceInfoList.count(toCamelCase(d_name)) > 0) {
deviceInfoList[toCamelCase(d_name)] = fileData;
} else if (strcmp(d_name, "hw-version") == 0) {
deviceInfoList["hardwareVersion"] = fileData;
} else if (strcmp(d_name, "mac-eth") == 0) {
deviceInfoList["macAddress"] = fileData;
} else if (strcmp(d_name, "has-radio") == 0 && fileData == "1") {
capabilityList["cell"] = true;
}
}
}
if (isValidDirectory(entry, fullPath, d_name)) { /* Check that the directory is not "d" or d's parent */
getSystemTreeJson(d_name); /* Recursively call with the new path */
}
}
if (closedir (d)) { /* After going through all the entries, close the directory */
logError("Could not close " + std::string(fullPath));
exitHandler(errno);
}
}
void Device::init() {
if (!isRoot) {
logError("Must be root to generate device_info.json");
exitHandler(99);
}
load();
writeJson();
exitHandler(0);
}
void Device::json() {
if (!isRoot) {
logError("Must be root to generate json");
exitHandler(99);
}
load();
printJson();
exitHandler(0);
}
void Device::load() {
deviceInfo.SetObject();
capabilities.SetObject();
accessoryCards.SetArray();
getSystemTreeJson("");
if (!accessoryCard.IsNull()) {
accessoryCards.PushBack(accessoryCard, accessoryCardsAlloc);
if (accessoryCards.Size() > 1) {
sortAccessoryCards();
}
}
mapFileToCapability();
mapFirmware();
mapMacAddress2();
for (const auto capability : capabilityList) {
capabilities.AddMember(rapidjson::Value().SetString(capability.first.c_str(),
capability.first.length(), accessoryCardsAlloc), capability.second, accessoryCardsAlloc);
}
for (const auto device : deviceInfoList) {
deviceInfo.AddMember(rapidjson::Value().SetString(device.first.c_str(),
device.first.length(), alloc), rapidjson::Value().SetString(device.second.c_str(),
device.second.length(), alloc), alloc);
}
deviceInfo.AddMember("capabilities", capabilities, alloc);
deviceInfo.AddMember("accessoryCards", accessoryCards, alloc);
}
void Device::logError(std::string info) {
printf("error: %s\n", info.c_str());
}
void Device::logInfo(std::string info) {
if (verbose) {
printf("info: %s\n", info.c_str());
}
}
void Device::mapFileToCapability() {
if (fileType("/opt/node-red") == S_IFDIR) { /* node-red is a directory */
capabilityList["nodeRed"] = true;
}
if (fileType("/opt/lora/lora-network-server") == S_IFREG) { /* lora-network-server is a regular file */
capabilityList["loraNetworkServer"] = true;
}
if (fileType("/dev/cdc-wdm0") == S_IFCHR) { /* Cellular modem is wwan/qmi character device */
capabilityList["cellWwan"] = true;
}
if (fileType("/dev/ext_serial") == S_IFCHR) { /* ext_serial is a character device */
capabilityList["externalSerialPort"] = true;
}
}
void Device::mapMacAddress2() {
std::ifstream file("/sys/devices/platform/mts-io/base/mac-eth");
if (file.is_open()){
std::string line = "";
std::getline(file, line);
deviceInfoList["macAddress1"] = line;
}
}
void Device::mapFirmware() {
std::ifstream file(FIRMWARE_FILE);
if (!file.is_open()){
return;
}
std::string line;
while (std::getline(file, line)){
if (line.find(FIRMWARE_VERSION) != std::string::npos){
deviceInfoList["firmware"] = line.substr(line.find(" ") + 1);
} else if (line.find(FIRMWARE_DATE) != std::string::npos){
deviceInfoList["firmwareDate"] = line.substr(line.find(" ") + 1);
}
}
}
void Device::printDir(const std::string dir_name, std::vector<std::string> &results) {
std::string fullPath = SYSFS_PLATFORM + std::string(dir_name);
DIR * d = opendir(fullPath.c_str());
if (!d) {
logError("Cannot open directory " + std::string(fullPath));
exitHandler(99);
}
while (1) {
struct dirent * entry = readdir (d);
if (!entry) {
break;
}
const char * d_name = entry->d_name;
if (!(entry->d_type & DT_DIR)) {
std::string result;
if (dir_name.size() > 0) {
result = (dir_name + "/");
}
result.append(d_name);
results.push_back(result);
}
if (isValidDirectory(entry, fullPath, d_name)) { /* Check that the directory is not "d" or d's parent. */
printDir(d_name, results);
}
}
if (closedir (d)) { /* After going through all the entries, close the directory. */
logError("Could not close " + std::string(fullPath));
exitHandler(errno);
}
}
void Device::printJson() {
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
deviceInfo.Accept(writer);
std::cout << buffer.GetString();
}
void Device::printVersion (std::string name) {
printf("%s %s\nCopyright (C) 2020 by Multi-Tech Systems\nThis program is free software; you may redistribute it under the terms of\nthe GNU General Public License version 2 or (at your option) any later version.\nThis program has absolutely no warranty.\n",name.c_str(), Version::version.c_str());
}
void Device::printUsage(std::string program) {
std::vector<std::string> showResults;
printf("Usage: %s [ OPTIONS ] OBJECT [--] [ ARGUMENTS ]\n", program.c_str());
printf("where OBJECT := {\n");
printf(" init |\n");
printf(" show SHOW-NAME |\n");
printf(" store STORE-NAME |\n");
printf(" json |\n");
printf(" }\n");
printf("\n");
printf(" SHOW-NAME := {\n");
printDir("", showResults);
sort(showResults.begin(), showResults.end()); // Unix file tree is not sorted
for (std::string showResult: showResults) {
if (!regex_match(showResult, showFilters))
printf (" %s\n", showResult.c_str());
}
printf(" }\n");
printf("\n");
printf(" STORE-NAME := {\n");
for (std::string showResult: showResults) {
if (showResult == "radio-reset") {
printf (" %s { 0 }\n", showResult.c_str());
} else if (showResult == "reset-monitor") {
printf (" %s { pid short-signal long-signal [extra-long-signal] }\n", showResult.c_str());
} else if (showResult == "reset-monitor-intervals") {
printf (" %s { short-interval long-interval }\n", showResult.c_str());
} else if (regex_match(showResult, serialModeFilter)) {
printf (" %s { loopback | rs232 | rs485-half | rs422-485-full }\n", showResult.c_str());
} else if (!regex_match(showResult, storeFilters)) {
printf (" %s BOOLEAN\n", showResult.c_str());
}
}
printf(" OPTIONS := {\n");
printf(" --verbose\n");
printf(" }\n");
printf("\n");
printf(" BOOLEAN := { OFF | ON }\n");
printf(" OFF := 0\n");
printf(" ON := 1\n");
printf("\n");
exitHandler(1);
}
void Device::show(std::string name) {
std::string fileData;
int32_t code = MTS::System::readFile(SYSFS_PLATFORM + name, fileData);
if (code == 0) {
printf("%s",fileData.c_str());
exitHandler(0);
} else {
logError("cat: can't open " + std::string(SYSFS_PLATFORM) + name + ": No such file or directory");
exitHandler(99);
}
}
void Device::showTrigger(std::string name) {
std::string fileData;
int32_t code = MTS::System::readFile(LEDS_GPIO_DIR + name + "/trigger", fileData);
if (code == 0) {
printf("%s",fileData.c_str());
exitHandler(0);
} else {
logError("can't not open '" + std::string(LEDS_GPIO_DIR) + name + "/trigger': No such file or directory");
exitHandler(99);
}
}
void Device::store(std::string name, std::string value) {
if (!isRoot) {
logError("Must be root to store to " + name);
exitHandler(99);
}
logInfo("setting " + name + " to " + value);
std::ofstream fileToWrite(SYSFS_PLATFORM + name);
if (!fileToWrite.bad()) {
fileToWrite << value;
fileToWrite.close();
exitHandler(0);
} else {
logError("can't not open '" + std::string(SYSFS_PLATFORM) + name + "': No such file or directory");
exitHandler(99);
}
}
void Device::storeTrigger(std::string name, std::string value) {
if (!isRoot) {
logError("Must be root to storeTrigger to " + name + "/trigger");
exitHandler(99);
}
logInfo("setting " + name + " to " + value);
std::ofstream fileToWrite(LEDS_GPIO_DIR + name + "/trigger");
if (!fileToWrite.bad()) {
fileToWrite << value;
fileToWrite.close();
exitHandler(0);
} else {
logError("can't not open '" + std::string(LEDS_GPIO_DIR) + name + "/trigger': No such file or directory");
exitHandler(99);
}
}
void Device::Verbose(const bool val) {
verbose = val;
}
bool Device::Verbose() {
return verbose;
}
void Device::writeJson() {
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
deviceInfo.Accept(writer);
std::ofstream os(DEVICE_INFO_FILE);
if (!os) {
logError("Can't write to " + std::string(DEVICE_INFO_FILE));
exitHandler(99);
} else {
os << buffer.GetString();
}
}
|