Thingspeak python

From emboxit
Revision as of 16:51, 11 September 2015 by Admin (Talk | contribs)

Jump to: navigation, search
  • pyMCU is a PIC board connected to R-Pi, the interesting part of the example is the ThingSpeak POST using Python

<python> import pymcu import time import httplib, urllib

mb = pymcu.mcuModule()

while 1:

   mb.lcd()
   ctemp = mb.i2cRead(145,0,2) # Read Temperature data address ( 1 0 0 1 A2 A1 A0 R ) = 10010001 (145 Decimal value) My A2, A1, A0 are all connected to ground
   bh = ctemp[0] << 3  # Shift left 3 bytes to make room for the other 3 bytes of the 11 byte temperature data.
   bl = ctemp[1] >> 5  # Get rid of the first 5 bytes by shifting right as they are ignored according to the datasheet
   ttemp = bh | bl     # Or the 2 bytes together to make the complete 11 byte temperature data.
   # Need to check first if the temperature data is going to be a negative or positive number
   if ctemp[0] >> 7 == 1: # Negative Temp (Need to do 2's Complement conversion)
       tempInC = ((ttemp ^ 2047) + 1) * -0.125
       tempInF = tempInC * 1.8 + 32.0
   else: # Positive Temp
       tempInC = ttemp * 0.125
       tempInF = tempInC * 1.8 + 32.0
   params = urllib.urlencode({'key': 'API_KEY_NOT_SHOWN','field1': tempInF})
   headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
   conn = httplib.HTTPConnection("api.thingspeak.com")
   conn.request("POST", "/update", params, headers)
   response = conn.getresponse()
   print response.status, response.reason
   data = response.read()
   conn.close()
   mb.lcd(1,str(tempInC) + " C")
   mb.lcd(2,str(tempInF) + " F")
   time.sleep(300)

</python>


This module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. Some restrictions apply — it can only open URLs for reading, and no seek operations are available.


This module defines classes which implement the client side of the HTTP and HTTPS protocols. It is normally not used directly — the module urllib uses it to handle URLs that use HTTP and HTTPS.


Send with Python and receive with PHP

I made a minimal python script to send data to Thingspeak channel 7742 (...I made it public now). It worked fine!
Then I copied the australianrobotics PHP example (Make Some Pretty Pictures) to a folder on my sever <ref>embedding Thingspeak channel 7742 graph to my hosted-server</ref>, just changing the channel number from 300 to 7742. Worked fine when I configured channel 7742 as public (from Thingspeak page)
The PHP code should run in any server like Raspberry-pi, xampp, hosted server


Python run in my winXP machine from command line <python>

  1. Pushing data to Thingspeak
  2. python

import httplib, urllib params = urllib.urlencode({'field1': 90, 'field2': 11,'key':'XCASH390WFIB81H9'}) headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} conn = httplib.HTTPConnection("api.thingspeak.com:80") conn.request("POST", "/update", params, headers) response = conn.getresponse() print response.status, response.reason

  1. Should respond: 200 OK

data = response.read() conn.close() </python> Only field 1 is used. The key corresponds to channel 7742. Other channel will have different key. Data is hard-coded to Python script (it is just proof of concept code)


3.php in my hosted server <php> <!DOCTYPE HTML> <html> <body>

<iframe style="border: 1px solid #cccccc;" src="https://www.thingspeak.com/channels/7742/charts/1?

 height=300&width=640&results=30&title=Nikos Python and PHP%20Data from Thingspeak channel 7742%20:)
 &dynamic=true&results=30" height="300" width="640">

</iframe>

</body> </html> </php>


Thingspeak-python-php-2.jpgThingspeak-python-php-1.jpg

  • After the basic case is working, I tested also the australianrobotics python script that sends the PC cpu-usage and free memory every 16 seconds to Thingspeak. It just worked

<python> import httplib, urllib

  1. download from <a href="http://code.google.com/p/psutil/" title="http://code.google.com/p/psutil/">http://code.google.com/p/psutil/</a>

import psutil import time

def doit():

   cpu_pc = psutil.cpu_percent()
   mem_avail_mb = psutil.avail_phymem()/1000000
   print cpu_pc
   print mem_avail_mb
   params = urllib.urlencode({'field1': cpu_pc, 'field2': mem_avail_mb,'key':'XCASH390WFIB81H9'})
   headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
   conn = httplib.HTTPConnection("api.thingspeak.com:80")
   conn.request("POST", "/update", params, headers)
   response = conn.getresponse()
   print response.status, response.reason
   data = response.read()
   conn.close()

  1. sleep for 16 seconds (api limit of 15 secs)

if __name__ == "__main__":

   while True:
       doit()
       time.sleep(16) 

</python>