Skip to content

Instantly share code, notes, and snippets.

@josephmosby
Created October 10, 2015 05:20
Show Gist options
  • Save josephmosby/d9ee7216d1ef88cee259 to your computer and use it in GitHub Desktop.
Save josephmosby/d9ee7216d1ef88cee259 to your computer and use it in GitHub Desktop.
var request = require('request');
var fs = require('fs');
var moment = require('moment');
var htmlToText = require('html-to-text');
var SerialPort = require('serialport').SerialPort,
serialPort = new SerialPort('/dev/ttyAMA0', {
baudrate: 19200
}),
Printer = require('thermalprinter');
var last_id = null;
// Open file containing the last briefing read (if it exists)
fs.readFile('id.txt', {encoding: "utf8", flag: "r+"}, function (err, data) {
if(!err){
last_id = data;
};
});
// Request latest briefings
request('http://www.nationaljournal.com/petro/briefings/briefing_updates', function(err, res, body){
if(err) throw err;
var finished = false;
var printingJobs = [];
body = JSON.parse(body);
fs.writeFile('id.txt', body[0]._id.$oid, function(err){ if(err) throw err; });
body.forEach(function(briefing, i){
// Have we printed this briefing before?
if(briefing._id.$oid == last_id){
// Throw finished flag because YOU HAVE READ THIS BEFORE BRO
finished == true;
}
// Only retrieve 5 latest briefings
if( i < 5 && !finished){
printingJobs.push({ content: briefing.kicker, format: "small" })
printingJobs.push({ content: briefing.headline, format: "big" });
briefing.content = htmlToText.fromString(briefing.content, { ignoreHref: true} );
while (briefing.content) {
printingJobs.push({ content: briefing.content.slice(0,140), format: ""});
briefing.content = briefing.content.slice(140);
}
printingJobs.push({ content: " ", format: "" });
}
});
printIt(printingJobs)
});
function printIt(printingJobs){
serialPort.on('open',function() {
var currentJob = 0;
var printer = new Printer(serialPort);
printer.on('ready', function() {
printingJobs.forEach(function(job, i){
var pending = false;
var interval = setInterval(function(){
if(currentJob == i && pending == false){
switch(job.format){
case "small":
printer.small(true)
break;
case "big":
printer.big(true)
break;
case "line":
printer.horizontalLine(16);
break;
default:
printer.big(false);
printer.small(false);
break;
}
if( job.content ){
printer.printLine(job.content)
}
printer.print(function(){
currentJob++;
clearInterval(interval);
});
pending == true;
}
}, 250);
});
});
});
serialPort.open();
console.log(printingJobs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment