Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

Sending data to Xively

Xively cosm netduino_plus_2

  • Please log in to reply
3 replies to this topic

#1 o0Higgy0o

o0Higgy0o

    New Member

  • Members
  • Pip
  • 3 posts

Posted 13 June 2013 - 03:35 PM

Hi,

 

Now that cosm has become Xively I decided to change my temperature senser feed over to xively rather than have it as a legacy cosm feed. I had some initial issues getting the PUT request right to send my temperature data for logging, but finally got it working. So to help anyone wanting to change to xively you will need to firstly set up a new feed and get a new ID and ApiKey. To send the data the DNS lookup is:

IPHostEntry entry = Dns.GetHostEntry("api.xively.com");

or to hard code the IP address: 

IPAddress remote_IP = IPAddress.Parse("216.52.233.120");

Host is api.xively.com

 

All the rest is as it was for cosm.

 

Here is my temperature sensing and basic socket sending code.  I used socket sending as I wanted to understand the basics of sending the put request. I have copied other peoples code in parts which has been very helpful and appreciated.

using Microsoft.SPOT;using Microsoft.SPOT.Hardware;using SecretLabs.NETMF.Hardware.Netduino;using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;namespace XivelyTemperature{    public class Program    {        const string ApiKey = "Your Key;        const string FeedId = "Your Feed Id";        const string UserAgent = "Xively Netduino Plus 2 Example"; // user agent is the project name        const string CRLF = "rn";        const double VoltsPerDegree = 0.01;        const double OffsetVolts = 0.5;        const double MaxVoltage = 3.3;        const uint MaxAdcValue = 4096;        // wait 10 mins between samples        const int SamplingPeriod = 60000;        const int ConnectionTimeout = 1000;        // if you don't want to use DNS (and reduce your sketch size)        // use the numeric IP instead of the name for the server:        static IPAddress remote_IP = IPAddress.Parse("216.52.233.120");    // numeric IP for api.xively.com        static OutputPort ledPort = new OutputPort(Pins.ONBOARD_LED, true);        static AnalogInput tempInPort = new AnalogInput(Cpu.AnalogChannel.ANALOG_0);        static Timer watchdog = null;        static TimerCallback timerDelegate = new TimerCallback(TimesUp);        const int WatchdogTime = 10000;        static Socket serversocket = null;        public static void Main()        {            IPEndPoint remoteEndPoint = new IPEndPoint(remote_IP, 80);            // use this if you want to use DNS lookup to get IP Address rather than hard code it            //IPHostEntry entry = Dns.GetHostEntry("api.xively.com");            //IPAddress address = entry.AddressList[0];            //IPEndPoint remoteEndPoint = new IPEndPoint(address, 80);            int rawValue;            double temperature;            string temp;            while (true)            {                try                {                    WaitUntilNextPeriod(SamplingPeriod);                    ledPort.Write(true);                    // start watchdog timer for SendData                    watchdog = new Timer(timerDelegate, null, WatchdogTime, Timeout.Infinite);                    Debug.Print("time: " + DateTime.Now);                    //Debug.Print("memory available: " + Debug.GC(true));                    rawValue = tempInPort.ReadRaw();                    Debug.Print("Raw value: " + rawValue.ToString());                    temperature = GetTempFromRaw(rawValue);                    temp = "Temperature, " + temperature.ToString("f");                    Debug.Print(temp);                    SendData(remoteEndPoint, temp);                    ledPort.Write(false);                }                catch (Exception ex)                {                    Debug.Print(ex.Message + " " + ex.StackTrace);                }                finally                {                    // Stop the timer                    watchdog = null;                    // garbage collect                    Debug.GC(true);                }            }        }        /// <summary>        /// send data to xively        /// </summary>        /// <param name="remoteEndPoint">endpoint to send data to</param>        /// <param name="temperature">string parameter to send</param>        private static void SendData(IPEndPoint remoteEndPoint, string temperature)        {            serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            serversocket.Connect(remoteEndPoint);            // calculate the length of the sensor reading in bytes:            int ContentLength = temperature.Length;            string WholePacket = string.Empty;            // send the HTTP PUT request:            WholePacket += "PUT /v2/feeds/" + FeedId.ToString() + ".csv HTTP/1.1rn";            WholePacket += "Host: api.xively.com" + CRLF;            WholePacket += "X-ApiKey: " + ApiKey + CRLF;            WholePacket += "User-Agent: " + UserAgent + CRLF;            WholePacket += "Content-Length: " + ContentLength.ToString() + CRLF;            // last pieces of the HTTP PUT request:            WholePacket += "Content-Type: text/csv" + CRLF;            WholePacket += "Connection: close" + CRLF;            WholePacket += CRLF;            // here's the actual content of the PUT request:            WholePacket += temperature + CRLF;            byte[] buffer = Encoding.UTF8.GetBytes(WholePacket);            serversocket.Send(buffer);            bool poll = serversocket.Poll(1000000, SelectMode.SelectRead);            if (serversocket.Available > 0)            {                buffer = new byte[serversocket.Available];                serversocket.Receive(buffer);                string resp = new string(Encoding.UTF8.GetChars(buffer));                Debug.Print(resp);            }            serversocket.Close();        }        /// <summary>        /// convert the raw ADC value to real temperature        /// </summary>        /// <param name="rawValue">int ADC value</param>        /// <returns>double real temperature</returns>        private static double GetTempFromRaw(int rawValue)        {            double voltsValue = (rawValue * MaxVoltage) / MaxAdcValue;            return (voltsValue - OffsetVolts) / VoltsPerDegree;        }        /// <summary>        /// sleep to next sample time        /// </summary>        /// <param name="samplingPeriod">time to sleep for</param>        private static void WaitUntilNextPeriod(int samplingPeriod)        {            long now = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;            var offset = (int)(now % samplingPeriod);            int delay = samplingPeriod - offset;            Debug.Print("sleep for " + delay + " msrn");            Thread.Sleep(delay);        }        /// <summary>        /// watchdog event to run when it kicks in        /// </summary>        /// <param name="state">object passed to method</param>        private static void TimesUp(object state)        {            Debug.Print("Watchdog kicked in");            PowerState.RebootDevice(true);        }    }}

cheers



#2 iced98lx

iced98lx

    Advanced Member

  • Members
  • PipPipPip
  • 134 posts
  • LocationSouth Dakota

Posted 11 November 2013 - 02:48 PM

Hat Tip, Mate. They push using HTTPS (yuck) or sockets now-a-days, you wouldn't happen to have updated yours to do it via sockets have you?



#3 iced98lx

iced98lx

    Advanced Member

  • Members
  • PipPipPip
  • 134 posts
  • LocationSouth Dakota

Posted 12 November 2013 - 03:35 AM

BTW using your work as the basis for this: http://forums.netdui...y-helper-class/



#4 JoopC

JoopC

    Advanced Member

  • Members
  • PipPipPip
  • 148 posts

Posted 12 November 2013 - 06:49 PM

You do not need to reset when the Netduino hangs while it's try to send data to a provider. (the well known network bug).

 

Put the "sending to Xiverly" procedure in a seperate thread, when the thread hangs, (the timer is fine)  simple dispose the thread.

(Thread.abort and thread.dispose) It is more safe then resetting your Netduino and it works well.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.