Code (2 of 2) for @MattsOffice

As promised in my earlier post and the follow up post, here is some sample code I’m using to respond to @MattsOffice mentions. With a version of this code and a Cron job I can respond to any number of specific commands.

This code only illustrates responding to one command, “light”, but could easily be extended as is done with @MattsOffice.

<?php
include_once('class.twitter.php');// http://code.google.com/p/php-twitter/

$ioBridgeJSONFeedURL = 'http://www.iobridge.com/api/feed/key=XXXXXXXXXXXXXXXXXXXXXX';
$buzzerOnURL = 'http://yourserver.com/iobridge-proxy.php?widget=buzzeron';
$buzzerOffURL = 'http://yourserver.com/iobridge-proxy.php?widget=buzzeroff';

$t = new twitter;
$t->username = 'twitter_username';
$t->password = 'twitter_password';

// Read the ID of the last reply
$myFile = "lastreply.txt";
$fileHandle = fopen($myFile, 'r');
$lastReplyID = fgets($fileHandle);
fclose($fileHandle);

// Get the latest unanwsered replies
$data = $t->getReplies('','',$lastReplyID);

$counter = 1;
if(!empty($data)){
    foreach($data as $tweet) {
        if (!empty($tweet->user->id)){

            // Check for valid command
            if(stripos($tweet->text, "light"){
                // retrieve data from ioBridge.com
                $curl_handle=curl_init();
                curl_setopt($curl_handle,CURLOPT_URL,$ioBridgeJSONFeedURL);
                curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
                curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
                $ioBridgeResultsObject = curl_exec($curl_handle);
                $ioBridgeResultsObject = json_decode($ioBridgeResultsObject);
                curl_close($curl_handle);

                $lightResults = $ioBridgeResultsObject->{'module'}->{'channels'}[2]->{'AnalogInput'};
                $updateText = ' @' . $tweet->user->screen_name . ' Ambient Light = ' . $lightResults;
            }
            // If no valid command was found reply with what commands are valid
            else{
                $messageText = ' Valid commands are: light, bright, dark, temp, hot, cold, lcd, and/or view';
                $updateText = ' @' . $tweet->user->screen_name . $messageText;
            }

            // Send update
            $updateData = $t->update($updateText, $tweet->id);

            // Update text file with ID of last reply (first reply of loop)
            if($counter === 1){
                $myFile = "lastreply.txt";
                $fileHandle = fopen($myFile, 'w') or die("can't open file");
                fwrite($fileHandle, $tweet->id);
                fclose($fileHandle);
            }
            $counter++;

            // Sound Buzzer (serves as an audible alert when someone pings @MattsOffice)
            $curl_handle=curl_init();
            curl_setopt($curl_handle,CURLOPT_URL,$buzzerOnURL);
            curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,5);
            curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
            $results = curl_exec($curl_handle);
            curl_setopt($curl_handle,CURLOPT_URL,$buzzerOffURL);
            $results = curl_exec($curl_handle);
            curl_close($curl_handle);
        }// if (!empty($tweet->user->id)){
    }// foreach($data as $tweet) {
}// if(!empty($data)){
else {
    echo 'All replies have been responded to.';
}

print '<pre>Twitter says(list of @mentions):'; print_r($data); print '</pre>';
print '<pre>Twitter says(response to status update):'; print_r($updateData); print '</pre>';
?>

In order to keep track of what @MattsOffice mentions have already been answered, the ID of the last successful reply is saved to a plain text file. A database could also be used but the text file method is much simpler even if it doesn’t allow logging.

In order for this code to work your server needs the ioBridge PHP Widge Control API and this Twitter library.

Code (1 of 2) for @MattsOffice

As promised in my earlier post here is the code that I’m using to auto-update the MattsOffice Twitter account. With this code and a Cron job I can update the light and temperature conditions of my office automatically at whatever time interval I choose.

ioBridge.com does offer “Actions” but none of the current actions allow the trigger to be time based. Once they introduce time as a trigger this code will no longer be needed.

<?php
include_once('class.twitter.php');//http://code.google.com/p/php-twitter/

$ioBridgeJSONFeedURL = 'http://www.iobridge.com/api/feed/key=XXXXXXXXXXXXXXXXXX';

$t = new twitter;
$t->username = 'twitter_username';
$t->password = 'twitter_pwd';

$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,$ioBridgeJSONFeedURL);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$ioBridgeResultsObject = curl_exec($curl_handle);
$ioBridgeResultsObject = json_decode($ioBridgeResultsObject);
curl_close($curl_handle);

if (empty($ioBridgeResultsObject)){
    print "Sorry, something went wrong.";
}
else{
    $data = $t->update('Temperature = '. $ioBridgeResultsObject->{'module'}->{'channels'}[0]->{'AnalogInput'} . '°F / Ambient Light = ' . $ioBridgeResultsObject->{'module'}->{'channels'}[2]->{'AnalogInput'});
    print '<pre>Twitter says: '; print_r($data); print '</pre>';
}
?>

In a few days I will post the code that parses my Twitter account for @MattsOffice mentions and responds to them accordingly.

Update: 07/17/09
Second post is up with more code

Introducing http://twitter.com/MattsOffice

A couple months back I came across IOBridge’s IO-204 and instantly knew I needed one. I went ahead and bought the device as well as several of their accessory boards. Once everything arrived I started tinkering and was amazed with how easy it was at connecting DIY projects to the web.

Now if only I had a project to use it with.

Lucky for me one of my graduate courses on computer communications requires a research paper on a “communications based” project. Well actually maybe I’m not so lucky, who likes to write research papers? The title of the paper is “Feasibility Study of Home Automation via Social Networks” and I hope to have it finished by August. Once it is done I will post it here.

System Diagram

System Diagram

The project was inspired by many of the current Twittering household devices.

The one thing lacking in most of these devices was 2-way communication between Twitter and the device. In all of the examples I could find the device is sending an update to Twitter but is never performing an action based on a Twitter message.

With http://twitter.com/MattsOffice you can send a command by placing a keyword in a @reply message. Valid keywords are “light”, “bright”, “dark”, “temp”, “hot”, “cold”, “lcd”, and “view”. For example, to retrieve the temperature of my office I just need to update my Twitter status with a simple question like “@MattsOffice What is the temperature?”. Here are some more examples:

“@MattsOffice How cold is it?” – replies with the current temperature
“@MattsOffice How bright is it?” – replies with the current ambient light reading
“@MattsOffice lcd test message” – outputs “test message” to my LCD sitting on my desk
“@MattsOffice What is the view from your office look like?” – uploads a picture taken from my office window to TwitPic.com

Multiple commands can be posted together:

“@MattsOffice temp bright view” – replies with the current temperature, brightness, and post a picture

I can also turn off or on my desk light by updating my status with “@MattsOffice light on” or “@MattsOffice light off”. To prevent my light from turning off when I don’t want it to be off I have disable this feature for everyone but myself (i.e. it only works if @xzolian ask to turn the light on or off).

Go try it out! Let me know if there are any bugs. Look for a follow up post on how I made all this work and some example code.

Update: 07/15/2009
The first part of the code can be found here.

Update: 07/17/09
Second post is up with more code. This post was updated with Youtube video.