Python to thingspeak example

3,508

In this simple code example we will send the cpu percentage and available memory of a PC to thingspeak using a python script.

Install Python
Import Psutil – https://github.com/giampaolo/psutil/blob/master/INSTALL.rst the instructions vary depending on your operating system

Setup a thingspeak channel with 2 fields, this shows the fields

thingspeakpc2

 

Code

#!/usr/bin/env python
 
import httplib, urllib
from time import localtime, strftime
import psutil
import time
 
sleep = 20 
key = 'your api key'  # Thingspeak API key
 
def doit():
	cpu_percent = psutil.cpu_percent(interval=1)
	mem = psutil.virtual_memory()	
	params = urllib.urlencode({'field1': cpu_percent, 'field2': mem.available,'key':key})
	#params = urllib.urlencode({'field1': temp, 'key':key }) 
	headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
	conn = httplib.HTTPConnection("api.thingspeak.com:80")
	time.sleep(16) 
	try:
		conn.request("POST", "/update", params, headers)
		response = conn.getresponse()
		print cpu_pc
		print mem.available
		print strftime("%a, %d %b %Y %H:%M:%S", localtime())
		print response.status, response.reason
		data = response.read()
		conn.close()
	except:
		print "connection failed"	
 
#sleep for 20 seconds
if __name__ == "__main__":
	while True:
		doit()
		time.sleep(sleep)

 

Testing

Navigate to your channel

thingspeakpc

 

 

Comments are closed, but trackbacks and pingbacks are open.