Skip to content

Instantly share code, notes, and snippets.

@zoutepopcorn
Last active August 21, 2017 11:16
Show Gist options
  • Save zoutepopcorn/86393c086f013698715f0d6183d7b926 to your computer and use it in GitHub Desktop.
Save zoutepopcorn/86393c086f013698715f0d6183d7b926 to your computer and use it in GitHub Desktop.
const msg = require('./sms')
msg(() => {
}) ;
// ms.send("0031600000000", "mijn bericht", () => { console.log("jaja"); });
// require('./sms')
// ms.send("0031600000000", "mijn bericht", () => { console.log("jaja"); });
const isRoot = require('is-root');
const raspi = require('raspi');
const Serial = require('raspi-serial').Serial;
let serial, succes, error;
let current, tmp, line = "";
const CMD = { "set_sms" : "AT+CMGF=1",
"sms" : "AT+CMGS=",
"ctrl_z" : "\x1A",
"pin" : "AT+CPIN=",
"at" : "AT",
"call" : "ATD>0<",
"hangup" : "ATH" };
const RES = { "ok" : "OK",
"msg" : ">" };
const ERR = { "error" : "ERROR" };
if(!isRoot()) {
console.log(` You have to run this program as root.\r\nRestart with: sudo node`);
console.log('TODO: add serail to user group');
process.exit(1);
}
let response = (res) => {
if(res == "") return;
for (let at in RES) {
if(res.indexOf(RES[at]) > -1) {
console.log("<< OK >>");
succes();
return;
}
}
for (let at in ERR) {
if(res.indexOf(ERR[at]) > -1) {
console.log("<< ERROR >>");
error();
return;
}
}
line = "";
}
let sendAt = (command) => {
console.log(command);
if( command.startsWith("ctr") ) {
console.log("ctrl");
serial.write(0x1a);
} else {
console.log(`cmd: ${command}`)
serial.write(command + "\r\n");
}
}
let getAt = (cmd, args) => {
for(let i = 0; i < args.length; i++) {
cmd = cmd.replace(`>${i}<`, args[i]);
}
return cmd;
}
let dataIn= (data) => {
const out = data.toString('utf8');
line += out;
let arr = line.split("\r\n");
if(arr.length > 1) {
console.log(`data: ${ arr[arr.length-1] }`);
for(i= 0; i < arr.length; i++) {
response(arr[i]);
}
line = arr[arr.length-1];
}
}
let sendSms = (nr, bericht, cb) => {
console.log("sending sms");
// sending a AT command
let at = function(value) {
console.log(`=> ${value}`);
return new Promise((resolve, reject) => {
succes = resolve;
error = reject;
sendAt(value);
});
};
// sending AT commands
at(CMD.set_sms)
.then(() => at(CMD.sms + nr))
.then(() => at(bericht))
.then(() => {
succes = cb;
serial.write('\x1A');
})
.catch((err) => console.log(err));
}
function SMS() {
this.send = (nr, msg, cb) => {
sendSms(nr, msg, cb);
};
this.init = (cb) => {
raspi.init(() => {
console.log("init");
serial = new Serial({"baudRate" : 115200 });
serial.open(() => {
serial.on('data', (data) => { dataIn(data); });
cb();
});
});
}
this.sendRaw = (raw) => {
serial.write(raw);
}
}
module.exports = new SMS();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment