forked from TylerM89/gsmjs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gsm.js
346 lines (303 loc) · 9.81 KB
/
gsm.js
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
// Original Author: Mike Reich (https://github.com/sensamo/sim900js)
// Tyler McDowall (Acenth)
var mraa = require('mraa');
var sp = require('serialport');
var GSM = function(port, baud) {
if (!port) {
var uart = new mraa.Uart(0);
port = uart.getDevicePath();
}
if (!baud) {
baud = 9600;
}
this._port = port;
this._baud = baud;
this._clear();
var SerialPort = sp.SerialPort;
this._sp = new SerialPort(port, {
baudrate: baud
});
};
GSM.prototype._handleResponse = function(buf, cb) {
var response = null;
var error = null;
if(!this._buffer) return cb(error, response);
var raw = this._buffer.toString().split("\r");
var items = [];
var that = this;
var command = this._parseCommand(buf);
//console.log('raw', raw);
raw.forEach(function(res) {
res = res.trim();
if(res === '') return;
//console.log(res);
if (res[0] == '+') {
// Some responses contain information that needs to be parsed out. These responses start with +<COMMAND>: <DATA> - Could also start with CMERROR: <DATA>
var details = res.split(':');
var resCommand = that._parseCommand(details[0]);
//console.log(command);
if (resCommand == command) {
res = details[1];
}
else {
return error = res.substr(1, res.length-1);
}
res = res.trim();
if (res.indexOf(',') > -1) {
// Responses can contain multiple values, split them out so we can send them with other items in response
var resItems = res.split(',');
resItems.forEach(function(resItem){
items.push(resItem);
});
}
}
else {
items.push(res);
}
if(res == "OK" || res == ">") {
response = error || res;
error = null;
}
});
cb(error, response, items, raw);
};
GSM.prototype._parseCommand = function(c) {
// We want to compare the source command to the response command.
c = c.replace('?', '');
if (c[0] == '+') {
c = 'AT' + c;
}
if (c.indexOf('=') > -1) {
c = c.split('=')[0];
}
return c;
};
GSM.prototype._handleData = function(data) {
//console.log('[GSM]#> ', data.toString());
this._buffer = data;
};
GSM.prototype._handleError = function(error) {
this._error = error;
};
GSM.prototype._clear = function() {
this._buffer = null;
this._error = null;
};
GSM.prototype._connect = function(cb, retryCount) {
var that = this;
if (retryCount >= 3) {
console.log('[GSM] Failed to connect to GSM network after ' + retryCount + ' tries.');
}
this._writeCommand('AT', 500, function(err, resp, raw) {
if (err) {
console.log('Error connecting to network.. retrying');
that._connect(cb, retryCount++);
return;
}
console.log('[GSM] Connected to GSM network');
that.getDeviceInfo(function(err, resp, raw){
if (err) {
console.log('[GSM] Failed to get device information: ' + err);
return;
}
cb(err);
});
});
};
GSM.prototype.connect = function (cb) {
console.log('[GSM] Opening connection...' + this._port);
var that = this;
this._sp.open(function(err) {
that._sp.on('data', that._handleData.bind(that));
that._sp.on('error', that._handleError.bind(that));
if (err) {
cb(err);
}
that._connect(cb, 0);
});
};
GSM.prototype.getDeviceInfo = function(cb) {
console.log('[GSM] Getting device information...');
var that = this;
this.getICCID(function(err, resp, raw) {
if (err) {
cb(err, resp);
return;
}
that.getIMSI(function(err, resp, raw) {
if (err) {
cb(err, resp);
return;
}
cb(err, resp);
});
});
};
GSM.prototype.getICCID = function(cb) {
var that = this;
this._writeCommand('AT+CCID', 1000, function(err, resp, raw) {
if (err) {
console.log('[GSM] Error getting ICCID...' + err);
cb(err, resp);
return;
}
that._iccid = raw[1];
console.log('[GSM] ICCID: ' + raw[1]);
cb(err, resp, raw[1]);
});
};
GSM.prototype.getIMSI = function(cb) {
var that = this;
this._writeCommand('AT+CIMI', 1000, function(err, resp, raw) {
if (err) {
console.log('[GSM] Error getting IMSI...' + err);
cb(err, resp);
return;
}
that._imsi = raw[1];
console.log('[GSM] IMSI: ' + raw[1]);
cb(err, resp, raw[1]);
});
};
GSM.prototype.status = function(cb) {
this._writeCommand('AT+CREG?', 500, cb);
};
GSM.prototype.getSignalStrength = function(cb) {
this._writeCommand('AT+CSQ', 1000, cb);
};
GSM.prototype.close = function(cb) {
this._sp.close();
};
GSM.prototype._writeCommand = function(buf, timeout, cb) {
this._clear();
var that = this;
var originalBuf = buf;
if(buf && buf.length > 0 && buf[buf.length-1] != String.fromCharCode(13))
buf = buf+String.fromCharCode(13);
//console.log('[GSM] > ', buf.toString());
this._sp.write(buf, function(err) {
that._sp.drain(function() {
setTimeout(function() {
that._handleResponse(originalBuf, cb);
}, timeout);
});
});
};
GSM.prototype._writeCommandSequence = function(commands, timeout, cb) {
var that = this;
if(typeof timeout === 'function') {
cb = timeout;
timeout = null;
}
var processCommand = function(err, resp, raw) {
if(err) return cb(err);
if(commands.length === 0) return cb(err, resp, raw);
var command = commands.shift();
if(Array.isArray(command)) {
timeout = command[1];
command = command[0];
}
that._writeCommand(command, timeout, processCommand);
};
processCommand();
};
GSM.prototype.initialize = function(cb) {
var that = this;
console.log('[GSM] Initializing context...');
this._writeCommand('AT+SAPBR=2,1', 500, function(err, resp, raw) {
if (raw[2] == 1) {
console.log('[GSM] Context already open')
cb(err, resp, raw);
}
else {
console.log('[GSM] Opening context...');
that._initGPRS(function(err, resp, raw){
console.log('[GSM] Context opened');
cb(err, resp, raw);
});
}
});
};
GSM.prototype._httpInit = function(cb) {
console.log('[GSM] Initializing HTTP service');
this._writeCommand('AT+HTTPINIT', 6000, function(err, resp, raw) {
cb(err, resp, raw);
});
};
GSM.prototype._startsWith = function stringStartsWith (string, prefix) {
return string.slice(0, prefix.length) == prefix;
};
GSM.prototype.request = function(url, options, cb) {
var that = this;
if(typeof options === 'function') {
cb = options;
options = null;
}
// Options
var method = options && options['method'] ? options['method'] : 0;
var contentType = options && options['contentType'] ? options['contentType'] : 'text/plain';
var data = options && options['data'] ? options['data'] : null;
var timeout = options && options['timeout'] ? options['timeout'] : 15000;
var commands = [];
// SSL support
if (this._startsWith(url, 'https://')) {
commands.push('AT+HTTPSSL=1');
} else {
commands.push('AT+HTTPSSL=0');
}
commands.push('AT+HTTPPARA="CID",1');
commands.push('AT+HTTPPARA="URL","' + url + '"');
// POST
if (method == 1) {
commands.push('AT+HTTPPARA="CONTENT","' + contentType + '"');
commands.push(['AT+HTTPDATA=' + data.length + ',10000', 1000]);
commands.push([data+String.fromCharCode(parseInt("1A", 16)), 5000]);
}
commands.push(['AT+HTTPACTION=' + method, timeout]);
this._httpInit(function(err, resp, raw){
that._writeCommandSequence(commands, 1000, function(err, resp, raw) {
if (raw[1] == 200) {
console.log('[GSM] HTTP Response Code: ' + raw[1]);
that._readHTTPResponse(raw[2], 0, cb);
} else {
console.log('[GSM] HTTP Error: ' + resp);
that._httpTerminate();
return cb(resp);
}
});
});
};
GSM.prototype._readHTTPResponse = function(bytes, start, cb) {
var that = this;
if(typeof start == 'function') {
cb = start;
start = 0;
}
var buff = '';
var readBytes = function(start, end) {
if (end > bytes) end = bytes;
var readName = start + ',' + end;
//console.log('[GSM] Reading...' + readName);
that._writeCommand('AT+HTTPREAD=' + start + ',' + end, (end-start) * 100, function(err, resp, items, raw) {
if(raw && raw.length > 0 && raw[0] && (raw[raw.length-2] && raw[raw.length-2].trim() === 'OK')) {
buff += raw[raw.length-3];
if(end == bytes) {
that._httpTerminate();
cb(buff);
} else readBytes(end+1, end+101);
} else {
console.log('[GSM] Read failed (' + readName + '):', raw);
that._httpTerminate();
return cb(buff);
}
});
};
readBytes(0, bytes);
};
GSM.prototype._httpTerminate = function() {
this._writeCommand('AT+HTTPTERM', 100, function() {});
};
GSM.prototype._initGPRS = function(cb) {
this._writeCommand('AT+SAPBR=1,1', 500, cb);
};
module.exports = GSM;