2015年2月18日水曜日

Processing で Philips hue を制御

Processingからhueを制御しようとして、PUTがうまくできずに困った。
結局、以下のように直接 Java で書けば問題なく動いた。

以下の 192.168.11.20 はhueブリッジのアドレス
newdeveloperは登録したユーザ名とする。
ユーザ名の登録の仕方は、hue api等で検索すれば出てくる。
例えば以下のサイトを参照。
http://blog.udcp.net/2013/10/09/philips-hue-api/

import processing.net.*;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.*;

Client c;
String data;
JSONObject json;
Boolean onoff;

void setup() {
  size(300, 300);
  onoff = true;

}

void draw() {
  if (onoff) {
    background(255);
    textSize(32); textAlign(CENTER); fill(0); text("ON", width/2, height/2);
  } else {
    background(0);
    textSize(32); textAlign(CENTER); fill(255); text("OFF", width/2, height/2);  
  }
};

void mouseReleased() {
  onoff = !onoff;
  lightSwitch(1, onoff);
  lightSwitch(2, onoff);
  lightSwitch(3, onoff);
};

void lightSwitch(int lightnum, Boolean onoff) {
  json = new JSONObject();
  json.setBoolean("on", onoff);
  sendPUT(lightnum, json);
};

void sendPUT(int num, JSONObject json) {
  try {
    URL url = new URL("http://192.168.11.20/api/newdeveloper/lights/"+num+"/state");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestMethod("PUT");
    OutputStreamWriter out = new OutputStreamWriter(
      httpCon.getOutputStream());
    out.write(json.toString()+"\r\n");
    out.close();
    httpCon.getInputStream();
  } catch (Exception e) {
  }
};

0 件のコメント: