/trunk/main.js |
@@ -0,0 +1,60 @@ |
/////////////////////////////////////////////////////////////////////////// |
// Copyright (C) Wizardry and Steamworks 2018 - License: GNU GPLv3 // |
// Please see: http://www.gnu.org/licenses/gpl.html for legal details, // |
// rights of fair usage, the disclaimer and warranty conditions. // |
/////////////////////////////////////////////////////////////////////////// |
|
const Gpio = require('onoff').Gpio |
const mqtt = require('mqtt') |
const YAML = require('yamljs'); |
const winston = require('winston') |
|
// Load configuration file. |
const config = YAML.load('config.yml'); |
|
// Generate GPIO pins for configuration. |
var COOL = {}; |
for(var i in config.GPIO) { |
if(!config.GPIO.hasOwnProperty(i)) |
continue; |
|
if(config.GPIO[i] === -1) |
continue; |
|
COOL[i] = new Gpio(config.GPIO[i], 'out') |
} |
|
// Set up logger. |
winston.add(winston.transports.File, {filename: 'cool-iot.log'}) |
|
// Initiate connection to MQTT. |
const client = mqtt.connect(config.mqtt.url) |
|
client.on('connect', function () { |
winston.info('Connected to MQTT server') |
client.subscribe(config.mqtt.topic) |
//client.publish('presence', 'Hello mqtt') |
}) |
|
client.on('message', function (topic, message) { |
// message is Buffer |
message = message.toString() |
winston.info('Received request: ' + message) |
if(!(message in config.GPIO)) { |
winston.warn('Request to toggle unknown GPIO: ' + message) |
return; |
} |
|
var pin = config.GPIO[message] |
if(pin === -1) { |
winston.warn('GPIO pin for "' + message + '" is not configured') |
return; |
} |
|
winston.info('Toggling pin ' + pin + ' for ' + message) |
COOL[message].writeSync(1) |
setTimeout(function() { |
winston.info('Toggled pin ' + pin + ' for ' + message) |
COOL[message].writeSync(0) |
}, 1000) |
}) |