Skip to content

Instantly share code, notes, and snippets.

@fador
Last active April 27, 2017 07:38
Show Gist options
  • Save fador/15d77bc30b8acf65066cbe86652dab80 to your computer and use it in GitHub Desktop.
Save fador/15d77bc30b8acf65066cbe86652dab80 to your computer and use it in GitHub Desktop.
Raspberry Pi -> ESP8266 request forward script in Node.js
// Use HTTP module
var http = require('http');
// Define a port we want to listen to
const PORT=8000;
// This function sends requests to the ESP8266
function doRequest(url) {
try {
var req = http.get({
host: '10.0.0.3',
port: 8000,
path: '/'+url
}, function(response) { }
).on('error', function(err) {
// handle errors with the request itself
console.error('Error with the request:', err.message);
});
} catch(e) {
}
}
// This function handles requests
function handleRequest(req, res){
// Map ID values to LED seqments
var mapValues = ["1-2", "3-4", "5-6", "7-8", "9-10", "11-12", "13-14", "15-16"];
// Define pre- and post-delays
var delay_pre = [4, 8, 12, 16, 20, 24, 28, 32];
var delay_post = [32, 28, 24, 20, 16, 12, 8, 4];
var led_on_time = 25;
// On /set/, set four states to switch between off and green
if (req.method === "GET" && req.url.substr(0,4) === "/set") {
var led_idx = parseInt(req.url[5]);
// Send request to the ESP8266 (/set/<LED_ids>/<State>/<Red>/<Green>/<Blue>/<Transition time to next state in ticks of 30ms>
doRequest("set/"+mapValues[led_idx]+"/0/0/0/0/"+delay_pre[led_idx]); // Stay off for delay_pre time
doRequest("set/"+mapValues[led_idx]+"/1/0/0/0/5"); // Transition to off-state, and 5 tick transition to "green"
doRequest("set/"+mapValues[led_idx]+"/2/0/40/0/"+led_on_time); // Green on-state
doRequest("set/"+mapValues[led_idx]+"/3/0/0/0/"+delay_post[led_idx]);// Balance the overall delay, so that the LEDs don't go off-sync
doRequest("cleartime/"); // Clear all timings, so that the sequence blinks as it should
res.end();
// On /clear/, set four states to switch between off and red
} else if (req.method === "GET" && req.url.substr(0,6) === "/clear") {
var led_idx = parseInt(req.url[7]);
doRequest("set/"+mapValues[led_idx]+"/0/0/0/0/"+delay_pre[led_idx]);
doRequest("set/"+mapValues[led_idx]+"/1/0/0/0/5");
doRequest("set/"+mapValues[led_idx]+"/2/40/0/0/"+led_on_time);
doRequest("set/"+mapValues[led_idx]+"/3/0/0/0/"+delay_post[led_idx]);
doRequest("cleartime/");
res.end();
} else {
res.statusCode = 404;
res.end();
}
}
//Create the server
var server = http.createServer(handleRequest);
// Listen for connections
server.listen(PORT, function(){
// Listening..
console.log("Server listening on: http://localhost:%s", PORT);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment