The thing system - Clients

by The Thing System



Overview

More complicated clients, one which monitor updates from the steward looking for changing conditions, and reacting to them on behalf of the user by asking the steward to perform actions, are entirely possible. Technically speaking these are intelligent agents working in a multi-agent system with shared goals of making life more convenient for the user. We like to think that we’re implementing magic.

Example code

  1. example clients, saying “Hello Lightbulbs”
var http = require("http");
var util = require("util");
var url = require("url");
var WebSocket = require('ws');

function onRequest(request, response) {    
    var ws;

    console.log("Request recieved.");
    var pathname = url.parse(request.url).pathname;
    response.writeHead(200, {"Content-Type":"text/html"});

    ws = new WebSocket('ws://127.0.0.1:8887/manage');
    console.log("Created websocket.");    

    ws.onopen = function(event) {
    console.log("Opened websocket to steward.");
    if ( pathname == "/on") {
        var json = JSON.stringify({ path      :'/api/v1/actor/perform/device/lighting', 
                                requestID :'1', 
                                perform   :'on', 
                                parameter :JSON.stringify({ brightness: 100, color: { model: 'rgb',         rgb: { r: 255, g: 255, b: 255 }}}) });
        ws.send(json);    
        console.log( json );

    } else if ( pathname == "/off") {
        var json = JSON.stringify({ path      :'/api/v1/actor/perform/device/lighting', 
                                    requestID :'2', 
                                    perform   :'off', 
                                    parameter :'' });            
        ws.send(json);
        console.log( json );

    } else {
        response.write("<h2>Unrecognised request</h2>");
        ws.close(); 
        response.end();
    }
};

ws.onmessage = function(event) {
    console.log("Socket message: " + util.inspect(event.data));
    response.write( "<h2>Turning lightbulb '" + pathname +"'</h2>" + util.inspect(event.data, {depth: null}));
    ws.close(); 
    response.end();

};

ws.onclose = function(event) {
    console.log("Socket closed: " + util.inspect(event.wasClean));
};

ws.onerror = function(event) {
    console.log("Socket error: " + util.inspect(event, {depth: null}));
    try { 
        ws.close(); 
        console.log("Closed websocket.");
    } catch (ex) {}
};

}

var server = http.createServer(onRequest).listen(9999);
console.log("Server started on port 9999.");</code></pre>
  1. Example using Arduino
    #include &lt;Dhcp.h;
    #include Dns.h;
    #include Ethernet.h&gt;
    #include EthernetClient.h&gt;
    #include util.h&gt;
    #include SPI.h;

    #include &lt;Base64.h&gt;
    #include &lt;global.h&gt;
    #include &lt;MD5.h&gt;
    #include &lt;sha1.h&gt;
    #include &lt;WebSocketClient.h;

const char *server = "192.168.1.91";

const int buttonPin = 7;
const int ledPin = 6;

int ledState = LOW;         
int buttonState;             
int lastButtonState = LOW;
int sentPacket = 0;

long lastDebounceTime = 0;  
long debounceDelay = 50; 

char *jsonOff = "{\"path\":\"/api/v1/actor/perform/device/lighting\",\"requestID\":\"2\",\"perform\":\"off\",\"parameter\":\"\"}";
char *jsonOn = "{\"path\":\"/api/v1/actor/perform/device/lighting\",\"requestID\":\"1\",\"perform\":\"on\",\"parameter\":\"{\\\"brightness\\\":100}\"}";
byte mac[] = { 0x0, 0xA2, 0xDA, 0x0D, 0x90, 0xE2 };  

EthernetClient client;
WebSocketClient webSocketClient;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);  

  Serial.begin(9600);
  while(!Serial) {  }

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Error: Failed to configure Ethernet using DHCP");
    while(1) {  }
  } 
}

void loop() {
  String data;
  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  } 
  if ((millis() - lastDebounceTime) &gt; debounceDelay) {
    buttonState = reading;
    if ( buttonState &amp;&amp; !sentPacket ) {
       if ( ledState ) {
          Serial.println( "Turning lights off.");
          Serial.println("Connecting to steward...");
          if( client.connect(server,8887) ) {
            Serial.println("Connected");
            webSocketClient.path = "/manage";
            webSocketClient.host = "dastardly.local";
            if (webSocketClient.handshake(client)) {
                Serial.println("Handshake successful");
            } else {
                Serial.println("Handshake failed.");
                while(1) {
                  // Hang on failure
                }  
            }
            webSocketClient.sendData(jsonOff);
          }          

       } else {       
          Serial.println( "Turning lights on.");
          Serial.println("Connecting to steward...");
          if( client.connect(server,8887) ) {
            Serial.println("Connected");
            webSocketClient.path = "/manage";
            webSocketClient.host = "dastardly.local";
            if (webSocketClient.handshake(client)) {
                Serial.println("Handshake successful");
            } else {
                Serial.println("Handshake failed.");
                while(1) {
                // Hang on failure
                }  
            }
            webSocketClient.sendData(jsonOn);
          }                    
       }
       sentPacket = 1;
    }
  }

  if (client.connected()) {
    data = webSocketClient.getData();
    if (data.length() &gt; 0) {
      Serial.print("Received data: ");
      Serial.println(data);
      client.stop();
      if ( ledState ) {
          digitalWrite(ledPin, LOW);
          ledState = LOW;       
      } else {
          digitalWrite(ledPin, HIGH);
          ledState = HIGH;       
      }
    }
  }

  if ( lastButtonState != reading ) {
     sentPacket = 0; 
  }  
  lastButtonState = reading;
}

Learn More

Goto Original


블로그 이미지

MidnightCow

위즈네트 칩(W5300, W5200, W7100, W7500) 개발자

,