Created
December 15, 2017 20:28
-
-
Save jamesbulpin/c74020ba6c1d054d7c604386c4a5770f to your computer and use it in GitHub Desktop.
Simple Azure IoT client to relay messages to an Arduino via serial-over-USB
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
var SerialPort = require("serialport"); | |
var clientFromConnectionString = require('azure-iot-device-amqp').clientFromConnectionString; | |
var tinycolor2 = require("tinycolor2"); | |
var connectionString = "<IoT Hub connection string>"; | |
var portdev = "/dev/ttyACM0"; | |
var port = new SerialPort(portdev, { | |
baudRate: 9600, | |
}); | |
port.on('error', function(err) { | |
console.log('Error: ', err.message); | |
}) | |
port.on('data', function (data) { | |
console.log('Data: ' + data); | |
}); | |
// AMQP-specific factory function returns Client object from core package | |
var client = clientFromConnectionString(connectionString); | |
// use Message object from core package | |
var Message = require('azure-iot-device').Message; | |
var connectCallback = function (err) { | |
if (err) { | |
console.error('Could not connect: ' + err); | |
} else { | |
console.log('Client connected'); | |
client.on('message', function (msg) { | |
console.log('Id: ' + msg.messageId + ' Body: ' + msg.data); | |
if (msg.data.toString() == "flash") { | |
port.write("FLASH\n"); | |
} else if (msg.data.toString() == "noflash") { | |
port.write("NOFLASH\n"); | |
} | |
else { | |
var c = tinycolor2(msg.data.toString()).toRgb(); | |
// Divide all values by 4 to reduce brightness and power usage | |
var r = c.r / 4; | |
var g = c.g / 4; | |
var b = c.b / 4; | |
console.log(r,g,b); | |
// These LEDs have red and green swapped | |
var x = "COLOR " + tinycolor2({ r: g, g: r, b: b }).toHexString() + "\n"; | |
port.write(x); | |
console.log(x); | |
} | |
client.complete(msg, printResultFor('completed')); | |
}); | |
}; | |
}; | |
client.open(connectCallback); | |
// Helper function to print results in the console | |
function printResultFor(op) { | |
return function printResult(err, res) { | |
if (err) console.log(op + ' error: ' + err.toString()); | |
if (res) console.log(op + ' status: ' + res.constructor.name); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment