Commit 30befba5c765ecbaf6a6ed2d4099ce1c6e29b791

Authored by Adhidarma Hadiwinoto
1 parent aaaf3604ea
Exists in master

Report sender update modemInfo message counter

Showing 2 changed files with 17 additions and 2 deletions Inline Diff

1 'use strict'; 1 'use strict';
2 2
3 const INTERVAL_BEETWEN_SIGNAL_STRENGTH_MS = 60000; 3 const INTERVAL_BEETWEN_SIGNAL_STRENGTH_MS = 60000;
4 const MAX_LAST_DATA_AGE_MS = 3 * 60 * 1000; 4 const MAX_LAST_DATA_AGE_MS = 3 * 60 * 1000;
5 const REGEX_WAIT_FOR_OK_OR_ERROR = /\n(?:OK|ERROR)\r\n/; 5 const REGEX_WAIT_FOR_OK_OR_ERROR = /\n(?:OK|ERROR)\r\n/;
6 6
7 const moment = require('moment'); 7 const moment = require('moment');
8 const SerialPort = require('serialport'); 8 const SerialPort = require('serialport');
9 const ParserReadline = require('@serialport/parser-readline'); 9 const ParserReadline = require('@serialport/parser-readline');
10 // const ParserDelimiter = require('@serialport/parser-delimiter'); 10 // const ParserDelimiter = require('@serialport/parser-delimiter');
11 11
12 const ParserRegex = require('@serialport/parser-regex'); 12 const ParserRegex = require('@serialport/parser-regex');
13 13
14 const config = require('komodo-sdk/config'); 14 const config = require('komodo-sdk/config');
15 const logger = require('komodo-sdk/logger'); 15 const logger = require('komodo-sdk/logger');
16 16
17 const mutex = require('./mutex'); 17 const mutex = require('./mutex');
18 const common = require('./common'); 18 const common = require('./common');
19 const sms = require('./sms'); 19 const sms = require('./sms');
20 const dbCops = require('./db-cops'); 20 const dbCops = require('./db-cops');
21 const reportSender = require('./report-sender'); 21 const reportSender = require('./report-sender');
22 // const msisdn = require('./msisdn'); 22 // const msisdn = require('./msisdn');
23 const registerModem = require('./register-modem'); 23 const registerModem = require('./register-modem');
24 const counters = require('./counters'); 24 const counters = require('./counters');
25 25
26 const modemInfo = { 26 const modemInfo = {
27 device: config.modem.device, 27 device: config.modem.device,
28 manufacturer: null, 28 manufacturer: null,
29 model: null, 29 model: null,
30 imei: null, 30 imei: null,
31 imsi: null, 31 imsi: null,
32 msisdn: null, 32 msisdn: null,
33 cops: null, 33 cops: null,
34 networkId: null, 34 networkId: null,
35 networkName: null, 35 networkName: null,
36 signalStrength: null, 36 signalStrength: null,
37 signalStrengthTs: null, 37 signalStrengthTs: null,
38 signalStrengthTsReadable: null, 38 signalStrengthTsReadable: null,
39 messageSentCounter: null,
40 messageReceivedCounter: null,
39 }; 41 };
40 42
41 let lastTs = new Date(); 43 let lastTs = new Date();
42 44
43 let port; 45 let port;
44 46
45 const parserReadLine = new ParserReadline(); 47 const parserReadLine = new ParserReadline();
46 48
47 const parserWaitForOK = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR }); 49 const parserWaitForOK = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR });
48 parserWaitForOK.on('data', () => { 50 parserWaitForOK.on('data', () => {
49 mutex.releaseLockWaitForCommand(); 51 mutex.releaseLockWaitForCommand();
50 }); 52 });
51 53
52 function writeToPort(data) { 54 function writeToPort(data) {
53 return new Promise((resolve) => { 55 return new Promise((resolve) => {
54 port.write(data, (err, bytesWritten) => { 56 port.write(data, (err, bytesWritten) => {
55 if (err) logger.warn(`ERROR: ${err.toString()}`); 57 if (err) logger.warn(`ERROR: ${err.toString()}`);
56 logger.verbose(`* OUT: ${data}`); 58 logger.verbose(`* OUT: ${data}`);
57 resolve(bytesWritten); 59 resolve(bytesWritten);
58 }); 60 });
59 }); 61 });
60 } 62 }
61 63
62 // eslint-disable-next-line no-unused-vars 64 // eslint-disable-next-line no-unused-vars
63 async function writeToPortAndWaitForOK(data) { 65 async function writeToPortAndWaitForOK(data) {
64 await mutex.setLockWaitForCommand(); 66 await mutex.setLockWaitForCommand();
65 const result = await writeToPort(data); 67 const result = await writeToPort(data);
66 68
67 await mutex.setLockWaitForCommand(); 69 await mutex.setLockWaitForCommand();
68 mutex.releaseLockWaitForCommand(); 70 mutex.releaseLockWaitForCommand();
69 71
70 return result; 72 return result;
71 } 73 }
72 74
73 async function readSMS(slot) { 75 async function readSMS(slot) {
74 const parserCMGR = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR }); 76 const parserCMGR = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR });
75 parserCMGR.on('data', (data) => { 77 parserCMGR.on('data', (data) => {
76 if (data) { 78 if (data) {
77 try { 79 try {
78 reportSender.incomingSMS(sms.extract(data.toString().trim()), modemInfo); 80 reportSender.incomingSMS(sms.extract(data.toString().trim()), modemInfo);
79 } catch (e) { 81 } catch (e) {
80 logger.warn(`Exception on reporting new message. ${e.toString()}`, { smsObj: e.smsObj, dataFromModem: data }); 82 logger.warn(`Exception on reporting new message. ${e.toString()}`, { smsObj: e.smsObj, dataFromModem: data });
81 83
82 process.exit(0); 84 process.exit(0);
83 } 85 }
84 } 86 }
85 port.unpipe(parserCMGR); 87 port.unpipe(parserCMGR);
86 mutex.releaseLockWaitForCommand(); 88 mutex.releaseLockWaitForCommand();
87 }); 89 });
88 90
89 // const parserCMGD = new ParserDelimiter({ delimiter: DELIMITER_WAIT_FOR_OK }); 91 // const parserCMGD = new ParserDelimiter({ delimiter: DELIMITER_WAIT_FOR_OK });
90 const parserCMGD = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR }); 92 const parserCMGD = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR });
91 parserCMGD.on('data', () => { 93 parserCMGD.on('data', () => {
92 port.unpipe(parserCMGD); 94 port.unpipe(parserCMGD);
93 mutex.releaseLockWaitForCommand(); 95 mutex.releaseLockWaitForCommand();
94 }); 96 });
95 97
96 logger.info(`Reading SMS on slot ${slot}`); 98 logger.info(`Reading SMS on slot ${slot}`);
97 await mutex.setLockWaitForCommand(); 99 await mutex.setLockWaitForCommand();
98 port.pipe(parserCMGR); 100 port.pipe(parserCMGR);
99 await writeToPort(`AT+CMGR=${slot}\r`); 101 await writeToPort(`AT+CMGR=${slot}\r`);
100 logger.info(`Finished reading SMS on slot ${slot}`); 102 logger.info(`Finished reading SMS on slot ${slot}`);
101 103
102 logger.info(`Deleting message on slot ${slot}`); 104 logger.info(`Deleting message on slot ${slot}`);
103 await mutex.setLockWaitForCommand(); 105 await mutex.setLockWaitForCommand();
104 port.pipe(parserCMGD); 106 port.pipe(parserCMGD);
105 await writeToPort(`AT+CMGD=${slot}\r`); 107 await writeToPort(`AT+CMGD=${slot}\r`);
106 logger.info('Message processing has completed'); 108 logger.info('Message processing has completed');
107 } 109 }
108 110
109 function onIncomingSMS(data) { 111 function onIncomingSMS(data) {
110 const value = common.extractValueFromReadLineData(data); 112 const value = common.extractValueFromReadLineData(data);
111 if (!value) return; 113 if (!value) return;
112 114
113 const chunks = value.split(','); 115 const chunks = value.split(',');
114 if (!chunks && !chunks[1]) return; 116 if (!chunks && !chunks[1]) return;
115 117
116 const slot = chunks[1]; 118 const slot = chunks[1];
117 119
118 logger.info(`Incoming SMS on slot ${slot}`); 120 logger.info(`Incoming SMS on slot ${slot}`);
119 readSMS(slot); 121 readSMS(slot);
120 } 122 }
121 123
122 function onCOPS(data) { 124 function onCOPS(data) {
123 modemInfo.cops = common.extractValueFromReadLineData(data).trim(); 125 modemInfo.cops = common.extractValueFromReadLineData(data).trim();
124 logger.info(`Connected Network: ${modemInfo.cops}`); 126 logger.info(`Connected Network: ${modemInfo.cops}`);
125 127
126 if (!modemInfo.cops) return; 128 if (!modemInfo.cops) return;
127 129
128 [, , modemInfo.networkId] = modemInfo.cops.split(','); 130 [, , modemInfo.networkId] = modemInfo.cops.split(',');
129 131
130 if (modemInfo.networkId) { 132 if (modemInfo.networkId) {
131 modemInfo.networkName = dbCops[modemInfo.networkId] || modemInfo.networkId; 133 modemInfo.networkName = dbCops[modemInfo.networkId] || modemInfo.networkId;
132 } 134 }
133 } 135 }
134 136
135 parserReadLine.on('data', (data) => { 137 parserReadLine.on('data', (data) => {
136 logger.verbose(`* IN: ${data}`); 138 logger.verbose(`* IN: ${data}`);
137 if (data) { 139 if (data) {
138 lastTs = new Date(); 140 lastTs = new Date();
139 if (data.indexOf('+CSQ: ') === 0) { 141 if (data.indexOf('+CSQ: ') === 0) {
140 const signalStrength = common.extractValueFromReadLineData(data).trim(); 142 const signalStrength = common.extractValueFromReadLineData(data).trim();
141 if (signalStrength) { 143 if (signalStrength) {
142 modemInfo.signalStrength = signalStrength; 144 modemInfo.signalStrength = signalStrength;
143 modemInfo.signalStrengthTs = new Date(); 145 modemInfo.signalStrengthTs = new Date();
144 modemInfo.signalStrengthTsReadable = moment(modemInfo.signalStrengthTs).format('YYYY-MM-DD HH:mm:ss'); 146 modemInfo.signalStrengthTsReadable = moment(modemInfo.signalStrengthTs).format('YYYY-MM-DD HH:mm:ss');
145 logger.info(`Signal strength: ${modemInfo.signalStrength}`); 147 logger.info(`Signal strength: ${modemInfo.signalStrength}`);
146 registerModem(modemInfo); 148 registerModem(modemInfo);
147 } 149 }
148 } else if (data.indexOf('+CMTI: ') === 0) { 150 } else if (data.indexOf('+CMTI: ') === 0) {
149 counters.increment('MESSAGE_RECEIVED', modemInfo); 151 counters.increment('MESSAGE_RECEIVED', modemInfo);
150 onIncomingSMS(data); 152 onIncomingSMS(data);
151 } else if (data.indexOf('+COPS: ') === 0) { 153 } else if (data.indexOf('+COPS: ') === 0) {
152 onCOPS(data); 154 onCOPS(data);
153 } 155 }
154 } 156 }
155 }); 157 });
156 158
157 async function simpleSubCommand(cmd, callback) { 159 async function simpleSubCommand(cmd, callback) {
158 const parser = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR }); 160 const parser = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR });
159 parser.on('data', (data) => { 161 parser.on('data', (data) => {
160 port.unpipe(parser); 162 port.unpipe(parser);
161 mutex.releaseLockWaitForSubCommand(); 163 mutex.releaseLockWaitForSubCommand();
162 164
163 if (data) { 165 if (data) {
164 if (callback) callback(null, data.toString().trim()); 166 if (callback) callback(null, data.toString().trim());
165 } 167 }
166 }); 168 });
167 169
168 return new Promise(async (resolve) => { 170 return new Promise(async (resolve) => {
169 await mutex.setLockWaitForSubCommand(); 171 await mutex.setLockWaitForSubCommand();
170 port.pipe(parser); 172 port.pipe(parser);
171 writeToPort(cmd); 173 writeToPort(cmd);
172 174
173 await mutex.setLockWaitForSubCommand(); 175 await mutex.setLockWaitForSubCommand();
174 mutex.releaseLockWaitForSubCommand(); 176 mutex.releaseLockWaitForSubCommand();
175 177
176 resolve(); 178 resolve();
177 }); 179 });
178 } 180 }
179 181
180 function readManufacturer() { 182 function readManufacturer() {
181 return new Promise((resolve) => { 183 return new Promise((resolve) => {
182 simpleSubCommand('AT+CGMI\r', (err, result) => { 184 simpleSubCommand('AT+CGMI\r', (err, result) => {
183 modemInfo.manufacturer = result; 185 modemInfo.manufacturer = result;
184 logger.info(`Manufacturer: ${result}`); 186 logger.info(`Manufacturer: ${result}`);
185 resolve(result); 187 resolve(result);
186 }); 188 });
187 }); 189 });
188 } 190 }
189 191
190 function readModel() { 192 function readModel() {
191 return new Promise((resolve) => { 193 return new Promise((resolve) => {
192 simpleSubCommand('AT+CGMM\r', (err, result) => { 194 simpleSubCommand('AT+CGMM\r', (err, result) => {
193 modemInfo.model = result; 195 modemInfo.model = result;
194 logger.info(`Model: ${result}`); 196 logger.info(`Model: ${result}`);
195 resolve(result); 197 resolve(result);
196 }); 198 });
197 }); 199 });
198 } 200 }
199 201
200 function readIMEI() { 202 function readIMEI() {
201 return new Promise((resolve) => { 203 return new Promise((resolve) => {
202 simpleSubCommand('AT+CGSN\r', (err, result) => { 204 simpleSubCommand('AT+CGSN\r', (err, result) => {
203 modemInfo.imei = result; 205 modemInfo.imei = result;
204 logger.info(`IMEI: ${result}`); 206 logger.info(`IMEI: ${result}`);
205 resolve(result); 207 resolve(result);
206 }); 208 });
207 }); 209 });
208 } 210 }
209 211
210 function readIMSI() { 212 function readIMSI() {
211 return new Promise((resolve) => { 213 return new Promise((resolve) => {
212 simpleSubCommand('AT+CIMI\r', (err, result) => { 214 simpleSubCommand('AT+CIMI\r', (err, result) => {
213 modemInfo.imsi = result; 215 modemInfo.imsi = result;
214 logger.info(`IMSI: ${result}`); 216 logger.info(`IMSI: ${result}`);
215 217
216 if (result) { 218 if (result) {
217 /* 219 /*
218 modemInfo.msisdn = msisdn[result]; 220 modemInfo.msisdn = msisdn[result];
219 if (modemInfo.msisdn) { 221 if (modemInfo.msisdn) {
220 logger.info(`MSISDN: ${modemInfo.msisdn}`); 222 logger.info(`MSISDN: ${modemInfo.msisdn}`);
221 registerModem(modemInfo); 223 registerModem(modemInfo);
222 } 224 }
223 */ 225 */
224 } else { 226 } else {
225 logger.warn(`IMSI not detected. Please insert a sim card to your modem. Terminating ${config.modem.device}.`); 227 logger.warn(`IMSI not detected. Please insert a sim card to your modem. Terminating ${config.modem.device}.`);
226 process.exit(2); 228 process.exit(2);
227 } 229 }
228 resolve(result); 230 resolve(result);
229 }); 231 });
230 }); 232 });
231 } 233 }
232 234
233 function readCOPS() { 235 function readCOPS() {
234 return new Promise((resolve) => { 236 return new Promise((resolve) => {
235 simpleSubCommand('AT+COPS?\r', (err, result) => { 237 simpleSubCommand('AT+COPS?\r', (err, result) => {
236 resolve(result); 238 resolve(result);
237 }); 239 });
238 }); 240 });
239 } 241 }
240 242
241 function deleteInbox() { 243 function deleteInbox() {
242 return new Promise((resolve) => { 244 return new Promise((resolve) => {
243 simpleSubCommand('AT+CMGD=0,4\r', (err, result) => { 245 simpleSubCommand('AT+CMGD=0,4\r', (err, result) => {
244 resolve(result); 246 resolve(result);
245 }); 247 });
246 }); 248 });
247 } 249 }
248 250
249 async function querySignalStrength() { 251 async function querySignalStrength() {
250 const parser = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR }); 252 const parser = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR });
251 parser.on('data', () => { 253 parser.on('data', () => {
252 port.unpipe(parser); 254 port.unpipe(parser);
253 mutex.releaseLockWaitForCommand(); 255 mutex.releaseLockWaitForCommand();
254 }); 256 });
255 257
256 if (mutex.tryLockWaitForCommand()) { 258 if (mutex.tryLockWaitForCommand()) {
257 port.pipe(parser); 259 port.pipe(parser);
258 await writeToPort('AT+CSQ\r'); 260 await writeToPort('AT+CSQ\r');
259 } 261 }
260 } 262 }
261 263
262 function registerModemToCenterPeriodically() { 264 function registerModemToCenterPeriodically() {
263 registerModem(modemInfo); 265 registerModem(modemInfo);
264 266
265 setInterval(() => { 267 setInterval(() => {
266 registerModem(modemInfo); 268 registerModem(modemInfo);
267 }, 60 * 1000); 269 }, 60 * 1000);
268 } 270 }
269 271
270 async function registerSignalStrengthBackgroundQuery() { 272 async function registerSignalStrengthBackgroundQuery() {
271 logger.info('Registering background signal strength query'); 273 logger.info('Registering background signal strength query');
272 274
273 querySignalStrength(); 275 querySignalStrength();
274 276
275 setInterval(() => { 277 setInterval(() => {
276 querySignalStrength(); 278 querySignalStrength();
277 }, config.interval_beetwen_signal_strength_ms || INTERVAL_BEETWEN_SIGNAL_STRENGTH_MS); 279 }, config.interval_beetwen_signal_strength_ms || INTERVAL_BEETWEN_SIGNAL_STRENGTH_MS);
278 } 280 }
279 281
280 async function sendSMS(destination, msg) { 282 async function sendSMS(destination, msg) {
281 if (typeof destination !== 'string' || typeof msg !== 'string' || !destination.trim() || !msg.trim()) return; 283 if (typeof destination !== 'string' || typeof msg !== 'string' || !destination.trim() || !msg.trim()) return;
282 284
283 const parser = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR }); 285 const parser = new ParserRegex({ regex: REGEX_WAIT_FOR_OK_OR_ERROR });
284 parser.on('data', () => { 286 parser.on('data', () => {
285 port.unpipe(parser); 287 port.unpipe(parser);
286 mutex.releaseLockWaitForSubCommand(); 288 mutex.releaseLockWaitForSubCommand();
287 }); 289 });
288 290
289 logger.verbose('Waiting for command lock to send message'); 291 logger.verbose('Waiting for command lock to send message');
290 await mutex.setLockWaitForCommand(); 292 await mutex.setLockWaitForCommand();
291 293
292 logger.info('Sending message', { destination, msg }); 294 logger.info('Sending message', { destination, msg });
293 counters.increment('MESSAGE_SENT', modemInfo); 295 counters.increment('MESSAGE_SENT', modemInfo);
294 296
295 const correctedDestination = `+${destination}`.replace(/^0/, '62').replace(/^\++/, '+'); 297 const correctedDestination = `+${destination}`.replace(/^0/, '62').replace(/^\++/, '+');
296 298
297 logger.verbose('Waiting for lock before set to text mode'); 299 logger.verbose('Waiting for lock before set to text mode');
298 await mutex.setLockWaitForSubCommand(); 300 await mutex.setLockWaitForSubCommand();
299 port.pipe(parser); 301 port.pipe(parser);
300 await writeToPort('AT+CMGF=1\r'); 302 await writeToPort('AT+CMGF=1\r');
301 303
302 logger.verbose('Waiting for lock before writing message'); 304 logger.verbose('Waiting for lock before writing message');
303 await mutex.setLockWaitForSubCommand(); 305 await mutex.setLockWaitForSubCommand();
304 port.pipe(parser); 306 port.pipe(parser);
305 await writeToPort(`AT+CMGS="${correctedDestination}"\n${msg}${Buffer.from([0x1A])}`); 307 await writeToPort(`AT+CMGS="${correctedDestination}"\n${msg}${Buffer.from([0x1A])}`);
306 308
307 await mutex.setLockWaitForSubCommand(); 309 await mutex.setLockWaitForSubCommand();
308 mutex.releaseLockWaitForSubCommand(); 310 mutex.releaseLockWaitForSubCommand();
309 311
310 logger.info('Message has been sent'); 312 logger.info('Message has been sent');
311 313
312 setTimeout(() => { 314 setTimeout(() => {
313 logger.verbose('Releasing command lock'); 315 logger.verbose('Releasing command lock');
314 mutex.releaseLockWaitForCommand(); 316 mutex.releaseLockWaitForCommand();
315 }, 2000); 317 }, 2000);
316 } 318 }
317 319
318 function init() { 320 function init() {
319 port = new SerialPort(config.modem.device, { baudRate: 115200 }, (err) => { 321 port = new SerialPort(config.modem.device, { baudRate: 115200 }, (err) => {
320 if (err) { 322 if (err) {
321 logger.warn(`Error opening modem. ${err}. Terminating modem ${config.modem.device}.`); 323 logger.warn(`Error opening modem. ${err}. Terminating modem ${config.modem.device}.`);
322 process.exit(1); 324 process.exit(1);
323 } 325 }
324 326
325 registerModem(modemInfo); 327 registerModem(modemInfo);
326 }); 328 });
327 port.pipe(parserReadLine); 329 port.pipe(parserReadLine);
328 330
329 setInterval(() => { 331 setInterval(() => {
330 if ((new Date() - lastTs) > MAX_LAST_DATA_AGE_MS) { 332 if ((new Date() - lastTs) > MAX_LAST_DATA_AGE_MS) {
331 logger.warn(`No data for more than ${MAX_LAST_DATA_AGE_MS} ms. Modem might be unresponsive. Terminating modem ${config.modem.device}.`); 333 logger.warn(`No data for more than ${MAX_LAST_DATA_AGE_MS} ms. Modem might be unresponsive. Terminating modem ${config.modem.device}.`);
332 process.exit(0); 334 process.exit(0);
333 } 335 }
334 }, 30 * 1000); 336 }, 30 * 1000);
335 337
336 port.on('open', async () => { 338 port.on('open', async () => {
337 await mutex.setLockWaitForCommand(); 339 await mutex.setLockWaitForCommand();
338 340
339 logger.info('Modem opened'); 341 logger.info('Modem opened');
340 await writeToPort('\r'); 342 await writeToPort('\r');
341 await simpleSubCommand('AT\r'); 343 await simpleSubCommand('AT\r');
342 344
343 logger.info('Initializing modem to factory set'); 345 logger.info('Initializing modem to factory set');
344 await simpleSubCommand('AT&F\r'); 346 await simpleSubCommand('AT&F\r');
345 347
346 logger.info('Disabling echo'); 348 logger.info('Disabling echo');
347 await simpleSubCommand('ATE0\r'); 349 await simpleSubCommand('ATE0\r');
348 350
349 await readCOPS(); 351 await readCOPS();
350 352
351 await readManufacturer(); 353 await readManufacturer();
352 await readModel(); 354 await readModel();
353 await readIMEI(); 355 await readIMEI();
354 await readIMSI(); 356 await readIMSI();
355 357
356 if (!config.disable_delete_inbox_on_startup) { 358 if (!config.disable_delete_inbox_on_startup) {
357 logger.info('Deleting existing messages'); 359 logger.info('Deleting existing messages');
358 await deleteInbox(); 360 await deleteInbox();
359 } 361 }
360 362
361 mutex.releaseLockWaitForCommand(); 363 mutex.releaseLockWaitForCommand();
362 logger.verbose('Init completed'); 364 logger.verbose('Init completed');
363 365
364 registerModemToCenterPeriodically(); 366 registerModemToCenterPeriodically();
365 registerSignalStrengthBackgroundQuery(); 367 registerSignalStrengthBackgroundQuery();
366 }); 368 });
367 } 369 }
368 370
369 init(); 371 init();
370 372
371 exports.modemInfo = modemInfo; 373 exports.modemInfo = modemInfo;
372 exports.sendSMS = sendSMS; 374 exports.sendSMS = sendSMS;
373 375
lib/register-modem.js
1 'use strict'; 1 'use strict';
2 2
3 const path = require('path'); 3 const path = require('path');
4 const request = require('request'); 4 const request = require('request');
5 5
6 const locks = require('locks'); 6 const locks = require('locks');
7 7
8 const config = require('komodo-sdk/config'); 8 const config = require('komodo-sdk/config');
9 const logger = require('komodo-sdk/logger'); 9 const logger = require('komodo-sdk/logger');
10 10
11 const counters = require('./counters');
12
11 const mutex = locks.createMutex(); 13 const mutex = locks.createMutex();
12 14
13 function reportUrl() { 15 function reportUrl() {
14 if (config.report_url.register_modem) { 16 if (config.report_url.register_modem) {
15 return config.report_url.register_modem; 17 return config.report_url.register_modem;
16 } 18 }
17 19
18 const baseUrl = path.dirname(config.report_url.incoming_sms); 20 const baseUrl = path.dirname(config.report_url.incoming_sms);
19 return `${baseUrl}/modems/set`; 21 return `${baseUrl}/modems/set`;
20 } 22 }
21 23
22 module.exports = (modemInfo) => { 24 async function sender(modemInfo) {
23 if (mutex.tryLock()) { 25 if (mutex.tryLock()) {
26 logger.info('Getting message counters before registering modem');
27
28 // eslint-disable-next-line no-param-reassign
29 modemInfo.messageSentCounter = await counters.get('MESSAGE_SENT', modemInfo);
30 // eslint-disable-next-line no-param-reassign
31 modemInfo.messageReceivedCounter = await counters.get('MESSAGE_RECEIVED', modemInfo);
32
24 const requestOptions = { 33 const requestOptions = {
25 url: reportUrl(), 34 url: reportUrl(),
26 qs: { 35 qs: {
27 modem: config.name, 36 modem: config.name,
28 modem_device: config.modem.device, 37 modem_device: config.modem.device,
29 modem_imsi: modemInfo.imsi, 38 modem_imsi: modemInfo.imsi,
30 modem_msisdn: modemInfo.msisdn, 39 modem_msisdn: modemInfo.msisdn,
31 modem_network_id: modemInfo.networkId, 40 modem_network_id: modemInfo.networkId,
32 modem_network_name: modemInfo.networkName, 41 modem_network_name: modemInfo.networkName,
33 modem_signal_strength: modemInfo.signalStrength, 42 modem_signal_strength: modemInfo.signalStrength,
34 uptime: Math.floor(process.uptime()), 43 uptime: Math.floor(process.uptime()),
35 report_port: config.http_command_server.listen_port, 44 report_port: config.http_command_server.listen_port,
36 report_apikey: config.http_command_server.apikey, 45 report_apikey: config.http_command_server.apikey,
37 report_path_sms: '/sms', 46 report_path_sms: '/sms',
47 counter_sent: modemInfo.messageSentCounter,
48 counter_received: modemInfo.messageReceivedCounter,
38 }, 49 },
39 }; 50 };
40 51
41 logger.info('Sending modem registration to center'); 52 logger.info('Sending modem registration to center');
42 request(requestOptions, (err, res) => { 53 request(requestOptions, (err, res) => {
43 mutex.unlock(); 54 mutex.unlock();
44 55
45 if (err) { 56 if (err) {
46 logger.warn(`Error registering modem. ${err.toString()}`); 57 logger.warn(`Error registering modem. ${err.toString()}`);
47 } else if (res.statusCode !== 200) { 58 } else if (res.statusCode !== 200) {
48 logger.warn(`SMS center respond with HTTP status code ${res.statusCode}.`); 59 logger.warn(`SMS center respond with HTTP status code ${res.statusCode}.`);
49 } 60 }
50 }); 61 });
51 } 62 }
52 }; 63 }
64
65 module.exports = sender;
53 66