How to update a Xively feed on a Raspberry Pi

This will show you how to make a C++ program that you can run from the command line of your Raspberry Pi to update a Xively/Cosm feed.

First, make sure you have git installed. If you don’t have it, use this command to install it:

sudo apt-get install git-core

If you haven’t done so already, create a Xively account and a new feed.
Use these commands to install the Xively C library:

git clone --recursive
cd libxively/src
mkdir xively
cd xively

Create a file called main.cpp. You can use a filemanager or just call

sudo nano main.cpp

Put this code in your main.cpp:

#include “xively.h”
#include “xi_err.h”


using namespace std;

#define XI_FEED_ID 0 // set Xively Feed ID (numerical, no quoutes)
#define XI_API_KEY “” // set Xively API key (double-quoted string)

int update_single(char* name, float value) {
xi_feed_t feed;
memset( &feed, NULL, sizeof( xi_feed_t ) );

feed.feed_id = XI_FEED_ID;
feed.datastream_count = 1;
feed.datastreams[0].datapoint_count = 1;
xi_datastream_t* datastream = &feed.datastreams[0];
strcpy(datastream->datastream_id, name);
xi_datapoint_t* datapoint = &datastream->datapoints[0];

xi_context_t* xi_context = xi_create_context( XI_HTTP, XI_API_KEY, feed.feed_id );

if( xi_context == NULL ) return -1;

xi_set_value_f32(datapoint, value);
xi_feed_update(xi_context, &feed);
return 0;

int main(int argc, char *argv[]) {
if (argc == 4)
if (strcmp(argv[1],”update”) == 0) {
return update_single(argv[2],atof(argv[3]));

cout << "usage: xively update " << endl; return 0; }[/code] Put your Xively feed ID and your API key in the main.cpp and compile the C++ program: [code]g++ main.cpp ../obj/libxively.a -I../libxively/ -o ../bin/my_project[/code] Now you can update your Xively feed from the Raspberry Pi's command line like this: [code]./libxively/src/bin/xively update temperature 24.5[/code] Many programming environments like PHP or Python provide a way to run a terminal command so you can do this programmatically. Here is an example for a C++ function that updates the xively feed: [code] std::string exec(char* cmd) { FILE* pipe = popen(cmd, "r"); if (!pipe) return "ERROR"; char buffer[128]; std::string result = ""; while(!feof(pipe)) { if(fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); return result; } void update_xively(char* name, float value) [ char command[60]; sprintf(command,"/home/pi/libxively/src/bin/xively update %s %f", name, value); exec(command); } [/code] (source)