Commit 209ea177a591f561601ad3c896b209ae3d23105e

Authored by Adhidarma Hadiwinoto
1 parent 956ce5804d
Exists in master

modemInfo.device

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