Commit 1030ff0a6cc674d2a7708849f3305a2cfbea3337

Authored by Adhidarma Hadiwinoto
1 parent 97d8bd49cb
Exists in master

Register modem before opening port

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