Skip to content

Instantly share code, notes, and snippets.

@mentos1386
Created January 14, 2019 15:37
Show Gist options
  • Save mentos1386/6442898abbb25067647bf137ae41925f to your computer and use it in GitHub Desktop.
Save mentos1386/6442898abbb25067647bf137ae41925f to your computer and use it in GitHub Desktop.
#include <SPI.h>
#include <Ethernet.h>
#include "PubSubClient.h"
// Update these with values suitable for your network.
byte mac[] = { 0xEA, 0x66, 0xCC, 0x6A, 0xF7, 0xCB };
IPAddress myDns(192, 168, 0, 1);
// Hue lights
IPAddress hueLightsHubIP(192, 168, 20, 85);
String hueLightsHubIPString = "192.168.20.85";
String hueLightsHubToken = "Y3v6mHOhiyfUj0SzbsclVhUxaUU2uV79yh7lgi7-";
String lamp_status_topic = "lamps/";
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);
void setup()
{
// Settup mqtt client
mqttClient.setServer("m15.cloudmqtt.com", 13529);
mqttClient.setCallback(callback);
// You can use Ethernet.init(pin) to configure the CS pin
Ethernet.init(10); // Most Arduino shields
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// Settup internet
setup_internet();
}
void setup_internet() {
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, myDns);
} else {
Serial.print(" DHCP assigned IP ");
Serial.println(Ethernet.localIP());
}
// Allow the hardware to sort itself out
delay(1500);
}
void mqtt_connect() {
// Loop until we're reconnected
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqttClient.connect("arduinoClient", "mbenncqj", "ucqFWykVc1De")) {
Serial.println("connected");
// ... and resubscribe
mqttClient.subscribe("sensor/arduino");
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 1 seconds");
// Wait 1 seconds before retrying
delay(1000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String message = "";
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
message.concat((char)payload[i]);
}
Serial.println();
// message := 123={"on": true}
int delimiter_pos = message.indexOf('=');
String lampId = message.substring(0, delimiter_pos);
String command = message.substring(delimiter_pos + 1);
if (command == "status") {
Serial.println("== Lamp " + lampId + " ==");
String status_string = get_status(lampId);
String topic_string = lamp_status_topic + lampId;
int response = mqttClient.publish((const char*) topic_string.c_str(), (const char*) status_string.c_str());
Serial.print("mqtt response ");
Serial.println(response);
//mqttClient.disconnect();
} else {
control_light(command, lampId);
}
}
String get_status(String lampId) {
if (ethClient.connect(hueLightsHubIP, 80)) {
Serial.println("Getting status of " + lampId);
ethClient.println("GET /api/" + hueLightsHubToken + "/lights/" + lampId + " HTTP/1.1");
ethClient.println("Host: " + hueLightsHubIPString);
ethClient.println("Content-Type: text/plain;charset=UTF-8");
ethClient.println("keep-alive");
ethClient.println();
String response = "";
int foundBeginings = 0;
int foundParameters = 0;
while (ethClient.connected())
{
int len = ethClient.available();
if (len > 0) {
byte buffer[80];
if (len > 80) len = 80;
ethClient.read(buffer, len);
for (int i=0; i < 80; i++) {
String character = String((char)buffer[i]);
if (character == "{") {
foundBeginings ++;
}
if (foundBeginings >= 2) {
if (character == ",") {
foundParameters ++;
}
if (foundParameters < 4) {
response.concat((char)buffer[i]);
}
}
}
}
}
Serial.println(response);
Serial.println("===================================");
ethClient.stop();
return response;
}
return "";
}
void control_light(String cmd, String lampId) {
if (ethClient.connect(hueLightsHubIP, 80)) {
Serial.print("Sending command: ");
Serial.println(cmd);
ethClient.println("PUT /api/" + hueLightsHubToken + "/lights/" + lampId + "/state HTTP/1.1");
ethClient.println("Host: " + hueLightsHubIPString);
ethClient.println("Content-Type: text/plain;charset=UTF-8");
ethClient.print("Content-Length: ");
ethClient.println(cmd.length());
ethClient.println("keep-alive");
ethClient.println();
ethClient.println(cmd);
while (ethClient.connected())
{
int len = ethClient.available();
Serial.println(len);
Serial.println("len");
if (len > 0) {
byte buffer[80];
if (len > 80) len = 80;
ethClient.read(buffer, len);
Serial.write(buffer, len);
}
}
Serial.println();
Serial.println("===================================");
ethClient.stop();
} else {
Serial.println("Error sending command");
}
}
void loop()
{
if (!mqttClient.connected()) {
mqtt_connect();
}
mqttClient.loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment