Showing posts with label Twitter. Show all posts
Showing posts with label Twitter. Show all posts

Monday, May 22, 2017

Tweeting Cat Door (now with Rasperry PI)

-----
It is hard to believe, but it was over five years ago that we created a Tweeting CatDoor using the Electric Imp.  Basic hobby IoT was much harder back then.  The Electric Imp, being a commercial grade product, was rock solid.  It only needed to reboot twice during it's entire service.  That said, a lightening strike may have gotten the best of it.
----
Basic hobby IoT is easier today thanks to project sites like HackaDay, etc.

A look into our spare parts box prompted some changes:  The Electric Imp gets replaced by a Raspberry Pi ZERO and WiFi dongle (we didn't have a spare ZERO-W laying around).  The original magnetic reed switch implementation goes solid state and gets replaced with a A3144EUA Hall Effect Sensor.  The concept is still the same as the original; a magnet is placed on the door and when Zena or Kelso use the door a magnet swings past the stationary sensor triggering a GPIO event.

As shown in the wiring diagram above, the build is simple.  The python code straightforward.

For the python code below you will need you create your own Twitter App and establish:
      - Consumer Key (API Key) and Consumer Secret (API Secret)
      - Access Token and Access Token Secret
These Keys and Tokens are, of course, changed in the python code below for obvious reasons.  Also, to save space the 'database' of tweets listed in the code is reduced.
-----
# May 2017 / WhiskeyTangoHotel.Com
# Raspberry PI ZERO for tweeting Cat Door activity
# MagSwitch is model A3144EUA Hall Effect sensor with magnet next to it
# Activate tweet loop whenever the Hall Effect Sensor changes state

import random
import time

# Set up Auth and token ID for the twitter API
from twython import Twython
# fill in your 4 keys in following variables
C_key = "ckckckckckblaghblagckckckckck"
C_secret = "cscscscscsblaghblaghblaghcscscscscs"
A_token = "atatatatatblaghblaghblagatatatatat"
A_secret = "asasasasasblaghblaghblagasasasasas"

localtime = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
Current_day = time.strftime("%d", time.localtime()) # what day of the month is it
New_day_dawned = Current_day # 1st run after midnight send status tweet to verify program is running

###  PROGRAM VAR SETTINGS ###

# Flood control (in seconds) for debounce and not sending to many tweets
Flood_control = 180 # seconds

# Really tweet (YES) or just test/debug (NO)?
Tweet = "YES"   # YES or NO in ALL UPPERCASE

# Track how many times the door has been triggered
Counter = 0

# Set up Hall Effect Sensor
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD) # to use Raspberry Pi board pin numbers
MagSwitch = 8  # Pin from signal of hall effect sensor
#Set pin to input and set pull-up resistor to hold the pin is high
GPIO.setup(MagSwitch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
print ' '
print "Program starts with Flood control of " + str(Flood_control) + " seconds."
print "Tweet set to " + Tweet
print " "

localtime = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
print "RasPI started on " + localtime + ".  Begin the mission!!!"
MagSwitch_Current = GPIO.input(MagSwitch)
#print "MagSwitch value is: " + str(MagSwitch_Current)
print ' '
if (Tweet == "YES"):
    myTweet = Twython(C_key,C_secret,A_token,A_secret)
    localtime = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
    myTweet.update_status(status="RasPI started at " + localtime + ".  Begin the mission!!!")
  
time.sleep(1)  # Whew... let's rest a bit..    Why?  Dunno...

while True:    # program runs 'forever'
    # First check if this is a new day.  If yes, tweet program is still active
    localtime = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
    Current_day = time.strftime("%d", time.localtime())
    if Current_day != New_day_dawned:
        print "A new day has dawned. It is " + localtime + "."
        print ' '
        if (Tweet == "YES"):
            myTweet = Twython(C_key,C_secret,A_token,A_secret)
            localtime = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
            myTweet.update_status(status="Hello, Twitter. Let's make the best of " + localtime)
        New_day_dawned = Current_day
                  
    # Now check to see if Sensor has changed state.  If so then Let's tweet
    if (GPIO.input(MagSwitch) != MagSwitch_Current):
        print ' '
        localtime = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
        print "Triggered at: " + localtime
        print '-------------------------------'
      
        Counter = Counter + 1
          
        # Load the CatQuotes; then Tweet it
        CatQuote = [
        "ZERO", #this is zero and should never be called.  just here to make counting easier 'cuz i'm stupid
        "Tweet Quote 1",
        "Tweet Quote 2",
        "Tweet Quote 3",
        "Tweet Quote 4",
        "Tweet Quote 5",
        "Tweet Quote etc...",        ]
      
        Number_of_quotes =  6 - 1
        random.seed() # seed off the CPU clock
        r = random.random()              
        r = int((r * Number_of_quotes) + 1)

        print str(Counter) + ": CatQuote("+str(r)+"): " + CatQuote[r]
        print "Flood control set to " + str(Flood_control) + " seconds."
        print "Tweet set to: " + Tweet
        if (Tweet == "YES"):
            myTweet = Twython(C_key,C_secret,A_token,A_secret)
            myTweet.update_status(status=CatQuote[r])
      
        time.sleep(Flood_control)  # pause for debounce, re-read HE sensor, keeps from tweeting all the time.
      
        # Door etc has settled after the Flood Control.  Reset and wait for next toggle
        MagSwitch_Current = GPIO.input(MagSwitch)
      
        print "Flood Control PASSED."
        print " "
-----
Good luck if you decide to build your own tweeting RasPI.

Tuesday, April 1, 2014

RasPI + RGB LED = Color of Twitter

This project uses a Raspberry PI to scan all posted Tweets in real time for the mention of a color.  When a color is Tweeted  the Red, Green, and/or Blue segments of a RGB LED are turned on to display the Tweeted color.  Video demo below:

-----
The project is pretty cool and simple to duplicate.  You should be able to just copy/past my Python script below into your favorite RasPI editor and go from there.

Note that the code expects the RGB LED to be connected to I/O Pins 11 (Red), 15 (Green) and 13 (Blue).  Also, be sure to add a current limiting resistor to each of the three I/O pins; not the RGB LED ground pin.  My RGB LED was spec'd for 330 Ohm resistors.  This picture should help identify Pins 11, 15, and 13:
-----
You will also need to establish your own Twitter API Token.  Don't worry; it's easy if you already have a Twitter account.  To get them go to https://dev.twitter.com/.  Enter these API Token values where the X's are in the source code below.
-----
#  Program to search Twitter to control a RGB LED
#  by WhiskeyTangoHotel.Com with special thanks to Sparkfun and twython
#  Tracks a tally count after each find
#  APRIL 2014

import time
import datetime # to allow timestamp math
import RPi.GPIO as GPIO
from twython import TwythonStreamer

#  PI I/O 11 = Red
#  PI I/O 13 = Blue
#  PI I/O 15 = Green
#  Red + Blue = Orange
#  Red + Green = Pink
#  None on = Black

# GPIO pin number of LED
Red = 11
Blue = 13
Green = 15

# Setup GPIO as output
GPIO.setmode(GPIO.BOARD)
GPIO.setup(Red, GPIO.OUT)
GPIO.output(Red, GPIO.LOW)

GPIO.setup(Green, GPIO.OUT)
GPIO.output(Green, GPIO.LOW)

GPIO.setup(Blue, GPIO.OUT)
GPIO.output(Blue, GPIO.LOW)

# Twitter application authentication

APP_KEY = 'xxxxxxxxxxxxxxxxxxxx'
APP_SECRET = 'xxxxxxxxxxxxxxxxxxxx'
OAUTH_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
OAUTH_TOKEN_SECRET = 'xxxxxxxxxxxxxxxxxxxx'

# Search terms placed in array TERM[]   # will find any term within the array ['one', 'two', 'three']   CASE SENSITIVE
TERM = []
TERM.append('red') #TERM[0]
TERM.append('blue') #TERM[1]
TERM.append('green') #TERM[2]
TERM.append('orange') #TERM[3]
TERM.append('pink') #TERM[4]

LED_secs_on = 30  # when found; how long to burn the LED

localtime = time.asctime( time.localtime(time.time()) )
print localtime
t0 = datetime.datetime.now()  # for timestamp math
print 'Self testing RGB LED...'
#Test RGB LED
i = 0
for i in range(0,5):
print 'RED...  GREEN...  BLUE...'
GPIO.output(Red, GPIO.HIGH)
time.sleep(0.3)
GPIO.output(Red, GPIO.LOW)

GPIO.output(Green, GPIO.HIGH)
time.sleep(0.3)
GPIO.output(Green, GPIO.LOW)

GPIO.output(Blue, GPIO.HIGH)
time.sleep(0.3)
GPIO.output(Blue, GPIO.LOW)
i = i + 1

print ' '
print "START searching for TERMS: "
print TERM[0]
print TERM[1]
print TERM[2]
print TERM[3]
print TERM[4]
print '................................'
print ' '

Tally_0 = 0
Tally_1 = 0
Tally_2 = 0
Tally_3 = 0
Tally_4 = 0

# Setup callbacks from Twython Streamer
class BlinkyLED(TwythonStreamer):
        def on_success(self, data):
global Tally_0
global Tally_1
global Tally_2
global Tally_3
global Tally_4

if 'text' in data:
check_string = data['text'].encode('utf-8')

if TERM[0] in check_string:
print TERM[0] + ' found on ' + time.asctime( time.localtime(time.time()) )
print ' '
Tally_0 = Tally_0 + 1
print data['text'].encode('utf-8')
GPIO.output(Red, GPIO.HIGH)


if TERM[1] in check_string:
print TERM[1] + ' found on ' + time.asctime( time.localtime(time.time()) )
print ' '
Tally_1 = Tally_1 +1
print data['text'].encode('utf-8')
GPIO.output(Blue, GPIO.HIGH)

if TERM[2] in check_string:
print TERM[2] + ' found on ' + time.asctime( time.localtime(time.time()) )
print ' '
Tally_2 = Tally_2 +1
print data['text'].encode('utf-8')
GPIO.output(Green, GPIO.HIGH)

if TERM[3] in check_string:
print TERM[3] + ' found on ' + time.asctime( time.localtime(time.time()) )
print ' '
Tally_3 = Tally_3 + 1
print data['text'].encode('utf-8')
GPIO.output(Red, GPIO.HIGH)
GPIO.output(Green, GPIO.HIGH)

if TERM[4] in check_string:
print TERM[4] + ' found on ' + time.asctime( time.localtime(time.time()) )
print ' '
Tally_4 = Tally_4 + 1
print data['text'].encode('utf-8')
GPIO.output(Red, GPIO.HIGH)
GPIO.output(Blue, GPIO.HIGH)

if TERM[0] in check_string or TERM[1] in check_string or TERM[2] in check_string or TERM[3] in check_string or TERM[4] in check_string:
print ' '
print 'SCORE:'
print TERM[0] + ' = ' + str(Tally_0)
print TERM[1] + ' = ' + str(Tally_1)
print TERM[2] + ' = ' + str(Tally_2)
print TERM[3] + ' = ' + str(Tally_3)
print TERM[4] + ' = ' + str(Tally_4)
print ' '
print str(Tally_0 + Tally_1 + Tally_2 + Tally_3 + Tally_4) + ' total finds after ' + str(datetime.datetime.now() - t0)
print '--------------------------------'
print ' '
time.sleep(LED_secs_on)    # keep LED on for xx secs
GPIO.output(Red, GPIO.LOW)  # turn off the LED
GPIO.output(Green, GPIO.LOW)
GPIO.output(Blue, GPIO.LOW)

# Create streamer
try:
        stream = BlinkyLED(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        stream.statuses.filter(track=TERM)
except KeyboardInterrupt:
        GPIO.cleanup()

-----
That's it.  Hope you give it a try!

Sunday, February 23, 2014

Graphing Twitter Mentions with the Raspberry PI

Objective:
Use the Raspberry PI to monitor Twitter for specific words or hashtags that are tweeted.  Graphically display the results on a publicly viewable webpage (http://open.sen.se/).
-----
If you are not interested in the build details and just want to see the result then take a look at this short video.  We had the RasPI set up to monitor for a "Tektronix" or "Agilent" mention in any and every message Twitter receives.

The video shows an iPad tweeting the message "Tektronix and Agilent. RasPI HashVote Test".  Since this tweet contains both search words the RasPI is monitoring for, each counter gets incremented and the graph is updated.

Tektronix and Agilent are well know test and measurement companies.  In general, they both get tweeted about the same number of times each day.  However, take a look at Agilent's graph the day they released their (not so good) quarterly earnings.  The graph clearly shows the extra Twitter chatter on Agilent due their earnings announcement. 
-----
So how does it work?
You're going to need a Raspberry PI connected to the internet (duh?), a Twitter account, and an open.se account.

Then you are going to create a Python script that runs on the Raspberry PI to search for Tweets and update the counters and graph on your open.se account.  The Python code is listed below.  If you are going to track two terms (as in the example above) you will have a separate Python script running for each search term.  You are going to need API authorization/access tokens for your Python scripts.  Don't panic; that's easy.

- Twitter API Token: Go to https://dev.twitter.com/.  You will need to create API tokens for each Python script you have running.  In the example above I am tracking two words; "Tektronix" and "Agilent", so I need to set up two API tokens.  If you decide to change the search terms from "Tektronix" or "Agilent" to "Happy" and "Sad" you will not have to create new API tokens.  Just simple change the search terms in the RasPI Python scripts.

- open.se API Token: Go to http://open.sen.se/ and create a "Channel" for each search term you want to track.  Again, the example above tracks two terms being tweeted so two channels are created.  After you create a "Channel" you will get a "FEED ID" for each channel.  You will also get an API token that is assigned to your account.  This API token is private to you and the same for each channel.  Then, play around with the "apps" at open.se to created graphs, counters, gauges, and a ton of other cool things.  Their tutorials are good, so I wont explain how to do that here.

Now boot your Raspberry PI, open your favorite text editor, and copy/past in the code below.  Replace the 'xxxxxxxx' with your custom API token and FEED ID information.  Again, you will need a Python script running for each Twitter term you are searching for.  There is probably a way to do this with one Python script, but I'm not that smart.

Run the script and watch the data flow and the counters update.  During debug and test, I would suggest tracking a commonly tweeted word such as "retweet" or "ipad".  That will help with the debug.  If you track a term like "WhiskeyTangoHotel.com" you may be waiting a while to see a result.  ;)

Mostly, the system runs perfectly, but for reasons unknown to me the Python script will 'freeze' from time to time.  I have had them running for days and days at a time without issue, but from time to time the freeze just happens.  If you know why, please enter into comments section of the youtube demo shown above.
-----
#  RasPI Python script to search Twitter for a string and post to open.se
#  by WhiskeyTangoHotel.Com with special thanks to Sparkfun and twython
#  FEB 2014



import time
from twython import TwythonStreamer
import httplib
import json as simplejson

#
# Search term that you want to find and count
#
Search_Term = 'WhiskeyTangoHotel.Com'  # Not case sensitive. TweET = tweet.
global Search_Term_Counter 
Search_Term_Counter = 0   # counts the finds

localtime = time.asctime( time.localtime(time.time()) )
print localtime
print "START searching for: " + Search_Term

# Twitter application authentication
APP_KEY = 'xxxxxxxxxxxxxxxx'
APP_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
OAUTH_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
OAUTH_TOKEN_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

# open.se application authentication
SENSE_API_KEY = "xxxxxxxxxxxxxxxxxxxxx"
FEED_ID1 = 12345  #FeedID for Hashvote_Counter2 on open.se

# def function to send Search_Term_Counter to open.se for processing
def send_to_opensense(data):
#    print  >> fout, "\t=> Sending to OpenSense: %s" % data
        try:    # error trap to continue run if crash during open.se postings
                # prepare data     
                datalist = [{"feed_id" : FEED_ID1, "value" :data['F']},]  #:data string not important for counting, but leave it
                headers = {"sense_key": SENSE_API_KEY,"content-type": "application/json"}
                conn = httplib.HTTPConnection("api.sen.se")
                # format a POST request with JSON content
                conn.request("POST", "/events/", simplejson.dumps(datalist), headers)
                response = conn.getresponse()
                # you may get interesting information here in case it fails
                #   print >> fout, response.status, response.reason
                #   print >> fout, response.read()
                conn.close()
        except:
                pass

# def Hash_Counter called from 'class' below.  Add custom code here.
def Hash_Counter ():  
        global Search_Term_Counter
        Search_Term_Counter = Search_Term_Counter + 1
        localtime = time.asctime( time.localtime(time.time()) )
        print localtime
        print "Search Term " + Search_Term + " found " + str(Search_Term_Counter) + " times."
        data = {'F' : Search_Term_Counter}
        send_to_opensense(data)
        
# Setup callbacks from Twython Streamer
try:  # error trap to continue run if crash due to offsite TwythonStreamer
class Search_Twitter (TwythonStreamer):
def on_success(self, data):
#Hash_Counter()         # for debug only
if 'text' in data:
Hash_Counter()  # found so call the Hash_Counter def
print data['text'].encode('utf-8')  # Typically REM'd unless for debug
print "-----"  # seperator to format the screen.
time.sleep(10)  #pause xx seconds just to keep from flooding sen.se with data
except:
pass
   
# Create streamer to search Twitter fot the Search_Term var
try:
        stream = Search_Twitter(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        stream.statuses.filter(track=Search_Term)
except:  #  KeyboardInterrupt:  # helps during debug to exit more gracefully on CNTRL C
        pass  
-----
Good luck and thanks for the visit!

Saturday, December 29, 2012

Electric Imp Tweeting Cat Door

Objective:
  • Using the Electric Imp,  create a rig to 'tweet' whenever activity is sensed on a cat door.
  • Create a real time graph of the activity here.
For those not interested in the build details, Kelso helped with this short video of @OurCatDoor in action:
-----
We have two cats (Zena and Kelso) that were eager to get online.  When they are not helping out in the labs (example pic) they like to walk through a cat door and relax on the screened in sun porch where they can enjoy food, drink, and take a bathroom break.

Tweeting cat doors are nothing new to The Net.  However, when I saw the Electric Imp I thought it could be a different way to tackle the problem and learn a few things along the way.  Let's take you through the process.

To start you are going to need an Electric Imp and an "April" Imp Breakout Board.  Oh, and a cat or two...



The Electric Imp is a pretty cool piece of kit.  It looks like a SD Card, but it is really a Cortex-M3 processor with WiFi on board.  Damn!  An onboard mini USB connector is used only to power the device; not for data.
-----
The Electric Imp is useless until you get it established with a wireless network.  As mentioned above, the USB is not used for data.  So how do you program it?  With light from the screen of an app that is run on your iPhone or Android.  You enter your WiFi SSID (and security paswords if needed) and the app sends "flashes" to the screen that are picked up by the Imp to program it.  The process works surprisingly well.
----
The physical I/O for the project is pretty straight forward.  All that is needed is a magnetic reed switch to sense if the cat door flap has opened.  A blue LED is used as a visual clue for ON/OFF and switch detection.  After deciding how to map the Imp's GPIO for the project, the schematic is embarrassingly simple:
-----
After soldering headers to the April breakout board a connector was repurposed making the connection setup clean and simple.
-----
The real challenge is in the software and the cross platform integration (Imp to WhiskeyTangoHotel.com webserver to Sen.se to Twitter) and that process was not trivial, but I'll take you through that as well.
-----
Now that you have the Imp all wired up and connected to a WiFi network, how do you program it?  Remember again that the USB is just for power.  The Imp is programmed in Squirrel through your browser (I used Chrome) from the Electric Imp website.  To me, Squirrel has a "C" type feel to it.  You work through a screen called "The Planner" to code up your project behind "nodes".  These "nodes" can be connected with "noodles" for flow control.  Here is the Imp planner screenshot of my finished project.  Note that you can't see the source code here as it is embedded under the "blue node".  I'll show my source code below later.
-----
In The Planner above, the Imp runs the code under the BLUE box and passes output to the GREEN box.  The code in the BLUE box has the Imp doing a few basic things:  1) turn on a blue LED to let everyone know the Imp is powered and 2) monitoring a magnetic reed switch on the cat door.  If the cat door is opened the reed switch opens contact.  The Imp will 'see' the switch change and 3) blink the blue LED off to provide a visual confirmation and 4) pass the text string to be "tweeted" to the green box.

So what's in the green box?  When the green box is called a PHP script is executed on the WhiskeyTangoHotel.com webserver.  From this point, we leave the Electric Imp world and enter the Sen.se world.  
-----
Sen.se is one cool place.  Their goal is to assist in internet connectivity of personal devices.  They have widgets, tools, applications, channels and a few other things that I barely understand. One of the widgets found there helps with broadcasting to Twitter.  So, the PHP script in the green box above passes the string the cat wanted to "tweet" to the Sen.se Twitter app and the final result is achieved; a cat walking through a door unknowingly Tweeting a message to the world.  

Presto!  Even without opposable thumbs, the ability to type, speak English, read, or boot a computer our cats are online. 
-----
A few closing comments... I found the current Electric Imp user community to be pretty small. That said, the project wouldn't have come off without help from Electric Imp forums.  Most notable are "brendandawes" and "Hugo" who were my two main enablers.  Hugo is actually the CEO/Co-Founder of Electric Imp and I was pretty impressed that he is so involved.  Also,  I do wonder how the project would have gone with a near cost equivalent Raspberry PI.  I never really got comfortable with the fact that all my Electric Imp code was not stored locally.  I also wish there were more examples on the web to build a knowledge base from.   But, the Electric Imp package is crazy small and tight with low power draw so that is a huge plus.  In all I can't complain, the project works great and taught me a lot.  I don't have any experience with the Raspberry PI anyway, so any judgement will have to wait. 
-----
If you are still with us, here is some source code for your reading pleasure:
-----
Code Under the "Blue" Box Electric Imp Planner

/*
Tweeting Cat Door
Dec 2012
www.WhiskeyTangoHotel.Com

Read switch on PIN7 and GND
    Normally Open or Normally Closed can be adjusted in swEvent function
Blue LED PIN9 to V3V is ON if the code in running
    Blinks off for 0.5 secs when door switch dectected
*/

hardware.pin9.write(0); // LED ON, active LOW
local channelOutput = [ OutputPort("Ch 1", "string")]; // String var that gets sent to PHP script

//Watchdog code below send Ping to Imp server every xx secs
//I added this because the Imp was not Tweeting all switch closures and
//power up/down seems to correct it.  Assuming lost cost with Imp server?
function watchdog() {
  imp.wakeup(120,watchdog);  //xxx is seconds between pings
  server.log("WD ping");
}
watchdog();
//End of my watchdog code experiment

// function swEvent handles looking for action on the door switch
function swEvent() {    
        local d = date();  // Date info not sent to twitter.  Used only for planner debug
        local min = d["min"];
        local hour = d["hour"];
        local sec = d["sec"];
        local state = hardware.pin7.read();
        if (state == 0) {   // "1" Tweets when switch opens (for a NC swtich).  "0" Tweets when switch closes (for a NO swtich).
     
        // Select Random Msg.  Increase %xx as number of random msgs increases
            local r = math.rand()%4;   // generate random number (min val is 0.  max val is %xxx in Decimal)
   
            if (r == 3) {
                channelOutput[0].set("Random message for r = 3 here");
            }
         
            if (r == 2) {
                channelOutput[0].set("Random message for r = 2 here");
            }
         
            if (r == 1) {
                channelOutput[0].set("Random message for r = 1 here");
            }
         
            if (r == 0) {
                channelOutput[0].set("Random message for r = 0 here.");
            }
        // end Random Msg selecton
     
        // Blink the LED Off to show a door swing detected
        hardware.pin9.write(1);  // LED OFF
        imp.sleep(0.5)          // 500mS delay
        hardware.pin9.write(0);  //  LED back ON
     
        server.show("r="+r+" @ "+hour+":"+min+":"+sec);  //echo to the Imp Planner status the generated RANDOM# and time.  Used for debug.
        }   // end if state ==0 (or state ==1 depending on NO or NC switch type)
       
        imp.sleep(1.0);  // switch settle time of x.x seconds (keep greater that 0.5)    
        server.log(state);  //  echo switch state (O or 1) to planner window for debug      
}  // End function swEvent

// Configure pin 9 as an open drain output with internal pull up
// Configure pin 7 as switch
hardware.pin9.configure(DIGITAL_OUT_OD_PULLUP);
hardware.pin7.configure(DIGITAL_IN_PULLUP, swEvent);

imp.configure( "TCD w-Blink", [], channelOutput);
------
PHP Script called from Green Box in the Electric Imp Planner:
<?php
$feed_id = "sen.seAsignedXXX.XXXXXX";
$api_key = "sen.seAssignedXXX.XXXXXX";
if(isset($_POST['value'])) {
$data = array("feed_id" => $feed_id, "value" => $_POST['value']);                                                                    
$data_string = json_encode($data);                                                                                   
$ch = curl_init('http://api.sen.se/events/?sense_key='.$api_key);                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   
$result = curl_exec($ch);
}
?>
-----
Link back: Hack a Day
Link back: Hacked Gadgets
-----