Skip to content

Instantly share code, notes, and snippets.

@ravenlp
Created June 20, 2013 05:26
Show Gist options
  • Save ravenlp/5820493 to your computer and use it in GitHub Desktop.
Save ravenlp/5820493 to your computer and use it in GitHub Desktop.
NodeJs script to parse webpages and send data to Arduino via Serial connection
#!/usr/bin/env node
/* Info that is likely to be different for you */
var ARDUINO_PORT = "/dev/tty.usbserial-A1004c6U",
URL = 'http://www.cotizacion-dolar.com.ar/',
FETCH_CICLE = 30 * 60 * 1000;
/* Probably it's not a good idea to modify the following lines */
var jsdom = require("jsdom"),
sp = require("serialport"),
SerialPort = sp.SerialPort,
serialPort = new SerialPort(ARDUINO_PORT, {
baudRate: 9600, // this is synced to what was set for the Arduino Code
dataBits: 8, // this is the default for Arduino serial communication
parity: 'none', // this is the default for Arduino serial communication
stopBits: 1, // this is the default for Arduino serial communication
flowControl: false
}),
LCD_MAX_CHARS_LINE = 16;
console.log('Connecting to Arduino');
// Firing it up
fetchDataOnline();
var timer = setInterval(fetchDataOnline, FETCH_CICLE);
/**
* Consumes the webpage and get out the info we need
*/
function fetchDataOnline(){
console.log("Fetching data from web...");
jsdom.env(
URL,
["http://code.jquery.com/jquery.js"], // adding jQuery for happy traversing and parsing
function(errors, window) {
if (errors) {
console.warn(errors);
return;
}
// Now all the fetching and data processing
var data = window.$('.cotizaciones3').map(function() {
return window.$(this).text().trim()
}).get();
console.log("fetched: ", data);
sendData(data);
});
}
/**
* Arrange the data and send it to Arduino
* @param data array
*/
function sendData(data){
if (data.length < 4) return;
// First line
var line = createCenteredLine('Dolar: ' + data[0] + '/' + data[1]);
// Second line
line += createCenteredLine('Euro: ' + data[2] + '/' + data[3]);
// Send it out to serial
serialPort.write(line);
}
/**
* Append and pre-append spaces to center the content on the line
* @param content string
* @returns {string}
*/
function createCenteredLine(content){
var padding = LCD_MAX_CHARS_LINE - content.length,
line = '';
if(padding > 1){
padding = Math.floor(padding/2);
}
for(var i = 0; i < padding; i++){
line += " ";
}
line += content;
for(var i = 0; i < (LCD_MAX_CHARS_LINE - line.length); i++){
line += " ";
}
return line;
}
@EhsanShaghaei
Copy link

Thanks for providing such a good sample

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment