Skip to content

Instantly share code, notes, and snippets.

@parasquid
Created February 26, 2020 12:57
Show Gist options
  • Save parasquid/5c8122da73923fb0acfee6e3f85e9996 to your computer and use it in GitHub Desktop.
Save parasquid/5c8122da73923fb0acfee6e3f85e9996 to your computer and use it in GitHub Desktop.
rgb mqtt
E.setClock(160);
var esp8266 = require("ESP8266");
console.log(esp8266.getState());
pinMode(D4, "output");
var numPixels = 8;
var server = "x.x.x.x";
var options = {
keep_alive: 60,
port: 1883,
client_id: 'esp8266_psqd',
};
var topic = "/test/random";
var wifi = require("Wifi");
var ssid = "";
var pswd = "";
var wifi = require("Wifi");
wifi.stopAP();
function colorLeds(red, green, blue) {
var data = new Uint8ClampedArray(numPixels*3);
for (var i=0; i < data.length; i += 3) {
data[i ] = red;
data[i+1] = green;
data[i+2] = blue;
}
require("neopixel").write(NodeMCU.D4, data);
}
colorLeds(255, 255, 255);
colorLeds(0, 0, 0);
function onInit() {
wifi.connect(ssid, {password: pswd}, function(err) {
console.log("connected? err=", err, "info=", wifi.getIP());
var mqtt = require("MQTT").create(server, options);
mqtt.connect();
mqtt.on('connected', function() {
console.log("mqtt connected");
mqtt.on('disconnected', function() {
console.log("MQTT disconnected... reconnecting.");
setTimeout(function() {
mqtt.connect();
}, 1000);
});
mqtt.subscribe(topic);
mqtt.on('publish', function (pub) {
console.log("topic: " + pub.topic);
console.log("message: " + pub.message);
values = JSON.parse(pub.message);
if(values.name === "rgb") {
colorLeds(values.r, values.g, values.b);
}
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment