Created
November 29, 2017 07:49
-
-
Save kfatehi/5126dc74705c9ad414a74ad5f3635ebf to your computer and use it in GitHub Desktop.
fireplace server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
root@fireplace:~# cat server.js | |
var fs = require('fs'); | |
var http = require('http'); | |
const PORT=80; | |
function write(file, content) { | |
try {fs.writeFileSync(file, content)} | |
catch (err) {console.error(err.message)} | |
} | |
write('/sys/class/gpio/export', 26); | |
write('/sys/class/gpio/gpio26/direction', 'out'); | |
write('/sys/class/gpio/gpio26/value', 0); | |
http.createServer(function(request, response) { | |
console.log('Handling request', request.url); | |
if ( request.url === '/off' ) { | |
write('/sys/class/gpio/gpio26/value', 0); | |
response.end('off'); | |
} else if ( request.url === '/on' ) { | |
write('/sys/class/gpio/gpio26/value', 1); | |
response.end('on'); | |
} else if (request.url === '/toggle' ) { | |
var oldValue = parseInt(fs.readFileSync('/sys/class/gpio/gpio26/value')); | |
var newValue = oldValue === 0 ? 1 : 0 | |
write('/sys/class/gpio/gpio26/value', newValue); | |
response.end(newValue === 0 ? 'off' : 'on'); | |
} else if (request.url === '/status' ) { | |
response.end(JSON.stringify({ | |
value: parseInt(fs.readFileSync('/sys/class/gpio/gpio26/value')) | |
})) | |
} else { | |
response.end('404'); | |
} | |
}).listen(PORT, function() { | |
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