Skip to content

Instantly share code, notes, and snippets.

@printminion
Last active January 28, 2017 15:38
Show Gist options
  • Select an option

  • Save printminion/89d216ca9e1d05dd9a863fbfdb66b3b0 to your computer and use it in GitHub Desktop.

Select an option

Save printminion/89d216ca9e1d05dd9a863fbfdb66b3b0 to your computer and use it in GitHub Desktop.
Switch lamp color from green to red by activating PIN 2 (only if the hue bulb is in on state)
/*
Talking to Hue from an Arduino
By James Bruce (MakeUseOf.com)
Adapted from code by Gilson Oguime. https://github.com/oguime/Hue_W5100_HT6P20B/blob/master/Hue_W5100_HT6P20B.ino
http://www.makeuseof.com/tag/control-philips-hue-lights-arduino-and-motion-sensor/
Adapted for own purpose by @printminion:
Switch lamp color from green to red by activating PIN 2 (only if the hue bulb is in on state)
*/
#include <ArduinoHttpClient.h>
#include <SPI.h>
//#include <Ethernet.h>
#include <WiFi101.h>
char ssid[] = "o2-WLAN89"; // your network SSID (name)
char pass[] = "*********"; // your network password (use for WPA, or use as key for WEP)
// Hue constants
const int hueBulbId = 1;
const char hueHubIP[] = "192.168.178.2"; // Hue hub IP
const int hueHubPort = 80;
//const char hueUsername[] = "3nSfq-GCA63AmYGr1BqXL2JiWC0bNHshLE-mYVQK"; // Hue username
String hueUsername = "3nSfq-GCA63AmYGr1BqXL2JiWC0bNHshLE-mYVQK"; // Hue username
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;
int status = WL_IDLE_STATUS;
HttpClient httpClient = HttpClient(client, hueHubIP, hueHubPort);
// PIR
int inPin = 2;
boolean activated = false;
bool lastPinState = false;
bool isFirstRun = true;
// Hue variables
boolean hueOn; // on/off
int hueBri; // brightness value
long hueHue; // hue value
long hueSat; // hue saturation
String hueCmd; // Hue command
unsigned long buffer=0; //buffer for received data storage
unsigned long addr;
// Ethernet
byte mac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; // W5100 MAC address
IPAddress ip(192,168,1,2); // Arduino IP
//EthernetClient client;
int statusCode = 0;
String response;
/*
Setup
*/
void setup()
{
Serial.begin(9600);
//Ethernet.begin(mac,ip);
//Initialize serial and wait for port to open:
Serial.begin(9600);
//while (!Serial) {
// ; // wait for serial port to connect. Needed for native USB port only
//}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
pinMode(inPin,INPUT);
delay(2000);
Serial.println("Ready.");
}
void loop()
{
bool inPinReadOn = digitalRead(inPin);
Serial.print("inPinReadOn: ");
Serial.println(inPinReadOn);
if (!isFirstRun) {
//change only on pin state change
if (lastPinState == inPinReadOn) {
delay(100);
return;
}
Serial.println("Pin state changed..");
lastPinState = inPinReadOn;
} else {
isFirstRun = false;
Serial.println("First run..");
}
//set to true to add hue status check
if (false) {
bool hueStatus = getHue(hueBulbId);
//do nothing if hue status is not available
if (!hueStatus) {
delay(1000);
return;
}
//do nothing if hue is off
if (!hueOn) {
delay(1000);
return;
}
}
if(inPinReadOn){
Serial.println("activated");
if (hueBri == 1 && hueHue == 65280 && hueSat == 251) {
Serial.println(" - same values nothing to do");
return;
}
String command = "{\"on\":true,\"bri\":1,\"hue\":65280,\"sat\":251}";
setHue(hueBulbId, command);
// so we can track state
activated = true;
} else {
activated = false;
Serial.println("deactivated");
//was activated, so send a single off command
//String command = "{\"on\": false}";
if (hueBri == 1 && hueHue == 25500 && hueSat == 251) {
Serial.println(" - same values nothing to do");
return;
}
String command = "{\"on\":true,\"bri\":1,\"hue\":25500,\"sat\":251}";
Serial.println("setHue #1 ...");
setHue(hueBulbId, command);
}
delay(1000);
}
/* setHue() is our main command function, which needs to be passed a light number and a
* properly formatted command string in JSON format (basically a Javascript style array of variables
* and values. It then makes a simple HTTP PUT request to the Bridge at the IP specified at the start.
*/
boolean setHue(int lightNum,String command)
{
Serial.print("Connect to ");
Serial.print(hueHubIP);
Serial.print(":");
Serial.print(hueHubPort);
Serial.println("...");
if (!client.connect(hueHubIP, hueHubPort))
{
Serial.println("Not connected ...");
return false; // command failed
}
if(client.connected())
{
Serial.println();
Serial.print("PUT /api/");
Serial.print(hueUsername);
Serial.print("/lights/");
Serial.print(lightNum); // hueLight zero based, add 1
Serial.println("/state HTTP/1.1");
Serial.println("keep-alive");
Serial.print("Host: ");
Serial.println(hueHubIP);
Serial.print("Content-Length: ");
Serial.println(command.length());
Serial.println("Content-Type: text/plain;charset=UTF-8");
Serial.println(); // blank line before body
Serial.println(command); // Hue command
client.print("PUT /api/");
client.print(hueUsername);
client.print("/lights/");
client.print(lightNum); // hueLight zero based, add 1
client.println("/state HTTP/1.1");
client.println("keep-alive");
client.print("Host: ");
client.println(hueHubIP);
client.print("Content-Length: ");
client.println(command.length());
client.println("Content-Type: text/plain;charset=UTF-8");
client.println(); // blank line before body
client.println(command); // Hue command
client.println(); // blank line before body
client.println(); // blank line before body
}
client.stop();
return true; // command executed
}
boolean getHue(int lightNum) {
String path = "/api/" + hueUsername + "/lights/" + lightNum;
Serial.print("GET: ");
Serial.println(path);
httpClient.get(path);
// read the status code and body of the response
statusCode = httpClient.responseStatusCode();
response = httpClient.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
int labelStart = response.indexOf("on\"");
int contentStart = response.indexOf(":", labelStart);
int contentEnd = response.indexOf(",", labelStart);
String content = response.substring(contentStart + 1, contentEnd);
hueOn = (content == "true"); // if light is on, set variable to true
labelStart = response.indexOf("bri\"");
contentStart = response.indexOf(":", labelStart);
contentEnd = response.indexOf(",", labelStart);
content = response.substring(contentStart + 1, contentEnd);
hueBri = content.toInt(); // set variable to brightness value
labelStart = response.indexOf("hue\"");
contentStart = response.indexOf(":", labelStart);
contentEnd = response.indexOf(",", labelStart);
content = response.substring(contentStart + 1, contentEnd);
hueHue = content.toInt(); // set variable to brightness value
labelStart = response.indexOf("sat\"");
contentStart = response.indexOf(":", labelStart);
contentEnd = response.indexOf(",", labelStart);
content = response.substring(contentStart + 1, contentEnd);
hueSat = content.toInt(); // set variable to brightness value
}
/* A helper function in case your logic depends on the current state of the light.
* This sets a number of global variables which you can check to find out if a light is currently on or not
* and the hue etc. Not needed just to send out commands
*/
boolean getHueOld(int lightNum)
{
if (client.connect(hueHubIP, hueHubPort))
{
client.print("GET /api/");
client.print(hueUsername);
client.print("/lights/");
client.print(lightNum);
client.println(" HTTP/1.1");
client.print("Host: ");
client.println(hueHubIP);
client.println("Content-type: application/json");
client.println("keep-alive");
client.println();
while (client.connected())
{
if (client.available())
{
client.findUntil("\"on\":", "\0");
hueOn = (client.readStringUntil(',') == "true"); // if light is on, set variable to true
client.findUntil("\"bri\":", "\0");
hueBri = client.readStringUntil(',').toInt(); // set variable to brightness value
client.findUntil("\"hue\":", "\0");
hueHue = client.readStringUntil(',').toInt(); // set variable to hue value
Serial.println();
Serial.print("hueOn:");
Serial.print(hueOn);
Serial.print(" hueBri:");
Serial.print(hueBri);
Serial.print(" hueHue:");
Serial.print(hueHue);
Serial.println();
break; // not capturing other light attributes yet
}
}
client.stop();
return true; // captured on,bri,hue
}
else
return false; // error reading on,bri,hue
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment