ThingSpeak .net Class

April 13, 2011 § 1 Comment

ThingSpeak (www.thingspeak.com) is a cool application that allows you to send it any kind of data you want graphed.  Your imagination is the limitation.  Some ideas of what can be graphed:

  • How many beers you drank last night
  • The temperature of your office during the day
  • The CPU load of your server
  • The number of calories you’ve consumed
  • The number of calories you’ve burned

The API is very simple to begin with but the first thing I would need to do is wrap it in a class to make is easy.  Below is that class (C# .net). You can download it here.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Net;
using System.IO;

namespace ThingSpeak
{
    public class ThingSpeak
    {
        private const string _url = "http://api.thingspeak.com/";
        private const string _APIKey = "YOUR_KEY_HERE";

        public static Boolean SendDataToThingSpeak(string field1, string field2, string field3, string field4, string field5, string field6, string field7, string field8, out Int16 TSResponse)
        {
            StringBuilder sbQS = new StringBuilder();

            // Build the querystring
            sbQS.Append(_url + "update?key=" + _APIKey);
            if (field1 != null) sbQS.Append("&field1=" + HttpUtility.UrlEncode(field1));
            if (field2 != null) sbQS.Append("&field2=" + HttpUtility.UrlEncode(field2));
            if (field3 != null) sbQS.Append("&field3=" + HttpUtility.UrlEncode(field3));
            if (field4 != null) sbQS.Append("&field4=" + HttpUtility.UrlEncode(field4));
            if (field5 != null) sbQS.Append("&field5=" + HttpUtility.UrlEncode(field5));
            if (field6 != null) sbQS.Append("&field6=" + HttpUtility.UrlEncode(field6));
            if (field7 != null) sbQS.Append("&field7=" + HttpUtility.UrlEncode(field7));
            if (field8 != null) sbQS.Append("&field8=" + HttpUtility.UrlEncode(field8));

            // The response will be a "0" if there is an error or the entry_id if > 0
            TSResponse = Convert.ToInt16(PostToThingSpeak(sbQS.ToString()));

            if (TSResponse > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        public static Boolean UpdateThingkSpeakStatus(string status, out Int16 TSResponse)
        {
            StringBuilder sbQS = new StringBuilder();
            sbQS.Append(_url + "update?key=" + _APIKey + "&status=" + HttpUtility.UrlEncode(status));

            TSResponse = Convert.ToInt16(PostToThingSpeak(sbQS.ToString()));

            if (TSResponse > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static Boolean UpdateThingSpeakLocation(string TSLat, string TSLong, string TSElevation, out Int16 TSResponse)
        {
            StringBuilder sbQS = new StringBuilder();
            sbQS.Append(_url + "update?key=" + _APIKey);

            if (TSLat != null) sbQS.Append("&lat=" + TSLat);
            if (TSLong != null) sbQS.Append("&long=" + TSLong);
            if (TSElevation != null) sbQS.Append("&elevation=" + TSElevation);

            TSResponse = Convert.ToInt16(PostToThingSpeak(sbQS.ToString()));

            if (TSResponse > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private static string PostToThingSpeak(string QueryString)
        {
            StringBuilder sbResponse = new StringBuilder();
            byte[] buf = new byte[8192];

            // Hit the URL with the querystring and put the response in webResponse
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(QueryString);
            HttpWebResponse webResponse = (HttpWebResponse)myRequest.GetResponse();
            try
            {
                Stream myResponse = webResponse.GetResponseStream();

                int count = 0;

                // Read the response buffer and return
                do
                {
                    count = myResponse.Read(buf, 0, buf.Length);
                    if (count != 0)
                    {
                        sbResponse.Append(Encoding.ASCII.GetString(buf, 0, count));
                    }
                }
                while (count > 0);
                return sbResponse.ToString();
            }
            catch (WebException ex)
            {
                return "0";
            }

        }
    }
}

Now how do we use it? First, at the top of the class you will need to change the _APIKey to your own API key:

private const string _APIKey = "YOUR_KEY_HERE";

Each function returns a true if it was successful and a false if it failed. In addition, there is a TSResponse that is the last parameter that will return the entry_id of your post. Here are the call you can make:
SendDataToThingSpeak — Sends data fields (1-8, put a null if you don’t want to send the field)
UpdateThingkSpeakStatus — Sends a status update. this shows up in the data entries but I’m not sure what it does
UpdateThingSpeakLocation — Updates your location, lat, long and elevation. Again, I don’t see where it’s being used on the graph or even my channel page but I do see it in the data

Below are examples on how to use it.

Post data fields 1-6 only. It will return a true and TSEntryId will be populated with thingspeak’s entryId or it will return a false if it fales.

Boolean TS = ThingSpeak.SendDataToThingSpeak("5", "6", "2", "9", "4", "5", null, null, out TSEntryId);

Post a status update. I don’t see on ThingSpeak how it is used yet but I’m sure it’s very useful! It will return a true and TSEntryId will be populated with thingspeak’s entryId or it will return a false if it false.

Boolean TS = ThingSpeak.UpdateThingkSpeakStatus("New status to see what this does.", out TSEntryId);

Update the location of data. Again, I don’t see on ThingSpeak how it is used yet but I’m sure it’s very useful! It will return a true and TSEntryId will be populated with thingspeak’s entryId or it will return a false if it fales.

Boolean TS = ThingSpeak.UpdateThingSpeakLocation("33.777909", "-117.88914", 800, out TSEntryId);