Properly setting up Xively Channels with Agent?

From what I can tell I have properly set up 5 thermistors (pins 2, 5, 7, 8, 9) and am passing individual temps to the agent, which is sending the temps to Xively.

I love the fact that this agent code (in this case from Tom’s Tempbug) automatically establishes the channels on Xively. However, no matter how I modify the agent code through experimentation, I can only get Xively to show one channel, and the data shown on that channel is always the last thermistor value passed to Xively (in this case, temp_pin_9).

I can see on the one channel on Xively that all 5 thermistor values are being posted to that channel. Really fast. One after the other.

My question is, can someone save me a bit of time and explain how the agent code (attached txt file) needs to be changed so that 5 channels are automatically created on Xively reflecting the 5 individual thermistor readings (temp_pin_2, temp_pin_5, temp_pin_7, temp_pin_8, temp_pin_9? I’m obviously not making the correct edits myself…

Can you log the names of your channels as you send them? I see that you have this:

const XIVELYCHANNEL = "temp_pin2";

Wouldn’t you want it to be just “temp_pin” and then add datapoint.id?

Perhaps you aren’t actually getting anything for datapoint.id, and therefore your channel name never changes?

Also, remove your API key from your code… you don’t want people messing with your feed.

Thanks man. I did hide the API key. That was dumb of me.

I’m a real novice at this, but you do seem to be on to the answer. I spent most of the day on this yesterday but don’t seem to be closer to an answer. I’m not making/finding any edits to this code which correctly sends multiple temps to Xively with different “id” numbers.

The original code was this (Tom’s) for one thermistor. I’m only editing these portions, and if that appears wrong, please let me know. Most people on this forum probably know how to get the current tempbug code from github, I assume.

Device
`// Configure Pins
// pin 8 is driven high to turn off temp monitor (saves power) or low to read
therm_en_l <- hardware.pin8;
therm_en_l.configure(DIGITAL_OUT);
therm_en_l.write(1);
// pin 9 is the middle of the voltage divider formed by the NTC - read the analog voltage to determine temperature
temp_sns <- hardware.pin9;
// instantiate sensor classes

// instantiate our thermistor class
myThermistor <- thermistor(temp_sns, b_therm, t0_therm, r_therm, 10, false);

therm_en_l.write(0);
imp.sleep(0.001);
local id = hardware.getdeviceid();
local datapoint = {
“id” : id,
“temp” : format("%.2f",myThermistor.read_f())
}
agent.send(“data”,datapoint);
therm_en_l.write(1);

Agent
device.on(“data”, function(datapoint) {
postToXively(datapoint.temp, datapoint.id);
});
`

What I have is this, below, which does read individual thermistors (pins 2 and 5) and accurately shows 2 different temp values in the log and on Xively, except both temps are posted on the same channel graph, one after the other. It would appear that I have no clue how to assign two different id numbers to the temps.

Device (condensed)
`//READ PIN 2 AND SEND VALUE TO AGENT
therm_en_l <- hardware.pin1;
therm_en_l.configure(DIGITAL_OUT);
therm_en_l.write(1);
temp_sns <- hardware.pin2;
myThermistor <- thermistor(temp_sns, b_therm, t0_therm, r_therm, 10, false);
therm_en_l.write(0);
imp.sleep(0.001);
local id = hardware.getdeviceid();
local datapoint = {
“id” : id,
“temp” : format("%.2f",myThermistor.read_f())
}
agent.send(“temperatures”,datapoint);
therm_en_l.write(1);

//READ PIN 5 AND SEND VALUE TO AGENT
therm_en_l <- hardware.pin1;
therm_en_l.configure(DIGITAL_OUT);
therm_en_l.write(1);
temp_sns <- hardware.pin5;
myThermistor <- thermistor(temp_sns, b_therm, t0_therm, r_therm, 10, false);
therm_en_l.write(0);
imp.sleep(0.001);
local id = hardware.getdeviceid();
local datapoint = {
“id” : id,
“temp” : format("%.2f",myThermistor.read_f())
}
agent.send(“temperatures”,datapoint);
therm_en_l.write(1);
`

Agent
device.on("temperatures", function(datapoint) { postToXively(datapoint.temp, datapoint.id); });

Like I said, I’m only editing these portions of the code. Based on what’s shown here, is it clear (or not) that other parts of the code should be edited too?

also, what’s the best way to post code? or at least to get rid of those “br /” html parts?

i have some talents, but coding and sharing code is not one of them :wink:

select the code and push the “C” tab and if it doesn’t show right away, refresh the page (F5)

Click the “C” in the markup menu bar to wrap you code in tags.

hardware.getdeviceid() is returning the impee ID, not a unique id for your thermistor. Thats why you are only ever getting one channel.

How about local ID = “Thermistor 1”; and so forth for each one.

Oh Cool. Thanks jwehr. That did it. I had no idea i could edit that local ID line.

You rock!

Your are just assigning the value of the impee id to a local variable named id. You don’t even need to do that… you could just specify the value of the id in your JSON table when you send it like this…

local datapoint = { "id" : "Thermistor_1", "temp" : format("%.2f",myThermistor.read_f())

cool. thanks again. i had this 5 thermistor imp working great last november but the blueprint retiring and the fact that xively blocked my ip addy brought this project to a halt.

You really helped me. tomorrow we are converting a solar hot water system from a conventional vented closed loop glycol type to a non-vented stagnation type and it will really help during testing to leave this imp on a battery in the attic monitoring pipe temps while i record temps in mechanical room.

by the way, any chance u know the definitive answer on what the true limit on data upload to xively might b? i got blocked doing every 20 seconds but am now using 1 minute. since solar thermal stagnation (steam filled collectors on roof) happens over 10 to 20 minutes i want high resolution from the imp in the attic. minimum 3 minutes. maybe i should search the threads or post a new thread about it…

I’d have to look… I usually update my thermocouple monitors every 30 seconds, yesterday I was updating about every 3 seconds with no issues…I’ve never been blocked by Xively even pushing a little faster than that… though I usually don’t do a faster rate for hours. Let me look at the docs…

wow. thanks. im sorry i posted the other thread before checking this one. thanks for the help. the best i can offer right now in return is a full report on this crazy experiment tomorrow…and into coming days. the more data i can collect the better. the premise is in removing the biggest liability to most solar hot water systems through just bigger expansion tank sizing, something the germans school us on, but we are slow to accept here in america…

Glad to help. I’m finishing up a tutorial on my dual probe thermocouple project right n ow… if you end up needed to measure really high or low temps, take a look at it.

hello, I’m with a similar problem on the code.

I`m using the same agent code from tempbug to opena channel and send the data to xively.

What I’m trying to do:
1)Arduino sends data trough softserial (2400) to imp in this format: (ok)

2)Imp gets the data string and splits the string into the individual sensor data (I’m only extracting temp data to make things simpler, after I got temp working I will implement the others: light, soil humidity and air humidity.) Imp reports through serve.log the temp data so it gets a (Ok).

3)Imp sends this temp data to agent (not ok Agent server.log is not shown on log)

4)Agent creates channel and post data to xively (not ok)

Help is much appreciated. how can I fix the float error shown by the log?

This is what I get from the server log:
2014-01-24 16:19:54 UTC-2: [Status] Device booting; 2.81% program storage used 2014-01-24 16:20:49 UTC-2: [Device] Temp:24.60 2014-01-24 16:20:49 UTC-2: [Device] ERROR: float expected for the specified format 2014-01-24 16:20:49 UTC-2: [Device] ERROR: at checkUART:30 2014-01-24 16:20:54 UTC-2: [Status] Device disconnected; 42 bytes sent, 0 received, 42 total

Agent:
`/*
Copyright © 2013 electric imp, inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the “Software”), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/*

/* GLOBALS and CONSTANTS -----------------------------------------------------*/

const XIVELY_API_KEY = “YOUR API KEY HERE”;
const XIVELY_FEED_ID = “YOUR FEED ID HERE”;
const XIVELYCHANNEL = “temperature”;
Xively <- {}; // this makes a ‘namespace’

/* CLASS AND GLOBAL FUNCTION DEFINITIONS -------------------------------------*/

// Xively “library”. See https://github.com/electricimp/reference/tree/master/webservices/xively

class Xively.Client {
ApiKey = null;
triggers = [];

constructor(apiKey) {
this.ApiKey = apiKey;
}

/*****************************************
 * method: PUT
 * IN:
 *   feed: a XivelyFeed we are pushing to
 *   ApiKey: Your Xively API Key
 * OUT:
 *   HttpResponse object from Xively
 *   200 and no body is success
 *****************************************/
function Put(feed){
	local url = "https://api.xively.com/v2/feeds/" + feed.FeedID + ".json";
	local headers = { "X-ApiKey" : ApiKey, "Content-Type":"application/json", "User-Agent" : "Xively-Imp-Lib/1.0" };
	local request = http.put(url, headers, feed.ToJson());

	return request.sendsync();
}

/*****************************************
 * method: GET
 * IN:
 *   feed: a XivelyFeed we fulling from
 *   ApiKey: Your Xively API Key
 * OUT:
 *   An updated XivelyFeed object on success
 *   null on failure
 *****************************************/
function Get(feed){
	local url = "https://api.xively.com/v2/feeds/" + feed.FeedID + ".json";
	local headers = { "X-ApiKey" : ApiKey, "User-Agent" : "xively-Imp-Lib/1.0" };
	local request = http.get(url, headers);
	local response = request.sendsync();
	if(response.statuscode != 200) {
		server.log("error sending message: " + response.body);
		return null;
	}

	local channel = http.jsondecode(response.body);
	for (local i = 0; i < channel.datastreams.len(); i++)
	{
		for (local j = 0; j < feed.Channels.len(); j++)
		{
			if (channel.datastreams[i].id == feed.Channels[j].id)
			{
				feed.Channels[j].current_value = channel.datastreams[i].current_value;
				break;
			}
		}
	}

	return feed;
}

}

class Xively.Feed{
FeedID = null;
Channels = null;

constructor(feedID, channels)
{
    this.FeedID = feedID;
    this.Channels = channels;
}

function GetFeedID() { return FeedID; }

function ToJson()
{
    local json = "{ \"datastreams\": [";
    for (local i = 0; i < this.Channels.len(); i++)
    {
        json += this.Channels[i].ToJson();
        if (i < this.Channels.len() - 1) json += ",";
    }
    json += "] }";
    return json;
}

}

class Xively.Channel {
id = null;
current_value = null;

constructor(_id)
{
    this.id = _id;
}

function Set(value) { 
	this.current_value = value; 
}

function Get() { 
	return this.current_value; 
}

function ToJson() { 
	return http.jsonencode({id = this.id, current_value = this.current_value }); 
}

}

function postToXively(data,id) {
xivelyChannel <- Xively.Channel(XIVELYCHANNEL+id);
xivelyChannel.Set(data);
xivelyFeed <- Xively.Feed(XIVELY_FEED_ID, [xivelyChannel]);
local resp = xivelyClient.Put(xivelyFeed);
server.log("Posted to Xively: “+data+”, got return code: “+resp.statuscode+”, msg: "+resp.body);
}

/* REGISTER DEVICE CALLBACKS ------------------------------------------------*/

device.on(“data”, function(datapoint) {
postToXively(datapoint.temp, datapoint.id);
server.log(datapoint)
});

/* REGISTER HTTP HANDLER -----------------------------------------------------*/

// This agent does not need an HTTP handler

/* RUNTIME BEGINS HERE -------------------------------------------------------*/

server.log(“Agente Jardineiro a postos!”);

// instantiate our Xively client
xivelyClient <- Xively.Client(XIVELY_API_KEY);
xivelyChannel <- Xively.Channel(“temperature”);`

Device:
`//uart initialization
function startUART()
{
hardware.configure(UART_1289);
hardware.uart1289.configure(2400, 8, PARITY_NONE, 1, NO_CTSRTS); //baud:19200, dataBits:8, parity, stopbit
}
//uart check
function checkUART()
{
imp.wakeup(5, checkUART);
local c = “”;
local b = hardware.uart1289.read();

while (b != -1) 
{
c += b.tochar();
b = hardware.uart1289.read();
}

//TEMPERATURE info from arduino data and send to agent
if (c.len()){
local tStart = c.find(“T”);
tStart = tStart + 1;
local temp = c.slice(tStart);
local tEnd = temp.find(“T”);
temp = temp.slice(0,tEnd);
server.log(“Temp:” + temp);
local id = “Temperatura"
local datapoint = {
“id” : id,
“temp” : format(”%.2f",temp)
}
agent.send(“data”,datapoint);
}
} //checkUART bracket end
startUART(); //setup uart
checkUART(); //begin uart polling
`

Arduino (Partial code, only the function that sends data to imp):
void sendData() { toSend = String(""); char temp[10]; dtostrf(tempNew,1,2,temp); char hum[10]; dtostrf(humidNew,1,2,hum); toSend = toSend(toSend + "L" + luxNew + "L" + "M" + moistNew + "M" + "T" + temp + "T" + "H" + hum + "H"); //Serial.println(toSend); Serial.print("sending"); Serial.println(toSend); softSerial.print(toSend); }

I think you need to cast temp to a float… its a string… I think…
Try this:
local datapoint = { "id" : id, "temp" : format("%.2f",temp.tofloat())

%.2f will format a float with 2 decimal places.

Tried this but it came with errors.

I took some different approaches and came with this code, lets see the steps:

1)Arduino sends data trough softserial (2400) to imp in this format: (done)
2)Imp gets the data string and splits the string into the individual sensor data (done)
3)Imp reports through serve.log all individual sensor data(done).
4)Imp sends data to agent and Agent report each value correctly (done)

5)Agent creates channel and post data to xively (not ok)

Agent code:
`/* GLOBALS and CONSTANTS -----------------------------------------------------*/

const XIVELY_API_KEY = “fill here”;
const XIVELY_FEED_ID = “fill here”;
const XIVELYCHANNEL = “temperature”;
Xively <- {}; // this makes a ‘namespace’

/* CLASS AND GLOBAL FUNCTION DEFINITIONS -------------------------------------*/

// Xively “library”. See https://github.com/electricimp/reference/tree/master/webservices/xively

class Xively.Client {
ApiKey = null;
triggers = [];

constructor(apiKey) {
this.ApiKey = apiKey;
}

/*****************************************
 * method: PUT
 * IN:
 *   feed: a XivelyFeed we are pushing to
 *   ApiKey: Your Xively API Key
 * OUT:
 *   HttpResponse object from Xively
 *   200 and no body is success
 *****************************************/
function Put(feed){
	local url = "https://api.xively.com/v2/feeds/" + feed.FeedID + ".json";
	local headers = { "X-ApiKey" : ApiKey, "Content-Type":"application/json", "User-Agent" : "Xively-Imp-Lib/1.0" };
	local request = http.put(url, headers, feed.ToJson());

	return request.sendsync();
}

/*****************************************
 * method: GET
 * IN:
 *   feed: a XivelyFeed we fulling from
 *   ApiKey: Your Xively API Key
 * OUT:
 *   An updated XivelyFeed object on success
 *   null on failure
 *****************************************/
function Get(feed){
	local url = "https://api.xively.com/v2/feeds/" + feed.FeedID + ".json";
	local headers = { "X-ApiKey" : ApiKey, "User-Agent" : "xively-Imp-Lib/1.0" };
	local request = http.get(url, headers);
	local response = request.sendsync();
	if(response.statuscode != 200) {
		server.log("error sending message: " + response.body);
		return null;
	}

	local channel = http.jsondecode(response.body);
	for (local i = 0; i < channel.datastreams.len(); i++)
	{
		for (local j = 0; j < feed.Channels.len(); j++)
		{
			if (channel.datastreams[i].id == feed.Channels[j].id)
			{
				feed.Channels[j].current_value = channel.datastreams[i].current_value;
				break;
			}
		}
	}

	return feed;
}

}

class Xively.Feed{
FeedID = null;
Channels = null;

constructor(feedID, channels)
{
    this.FeedID = feedID;
    this.Channels = channels;
}

function GetFeedID() { return FeedID; }

function ToJson()
{
    local json = "{ \"datastreams\": [";
    for (local i = 0; i < this.Channels.len(); i++)
    {
        json += this.Channels[i].ToJson();
        if (i < this.Channels.len() - 1) json += ",";
    }
    json += "] }";
    return json;
}

}

class Xively.Channel {
id = null;
current_value = null;

constructor(_id)
{
    this.id = _id;
}

function Set(value) { 
	this.current_value = value; 
}

function Get() { 
	return this.current_value; 
}

function ToJson() { 
	return http.jsonencode({id = this.id, current_value = this.current_value }); 
}

}

function postToXively(data,id) {
xivelyChannel <- Xively.Channel(XIVELYCHANNEL+id);
xivelyChannel.Set(data);
xivelyFeed <- Xively.Feed(XIVELY_FEED_ID, [xivelyChannel]);
local resp = xivelyClient.Put(xivelyFeed);
server.log("Posted to Xively: “+data+”, got return code: “+resp.statuscode+”, msg: "+resp.body);
}

/* REGISTER DEVICE CALLBACKS ------------------------------------------------*/
//this catches data sent from device
device.on(“temp”, function(temp) {
server.log(temp)
});

device.on(“lux”, function(lux) {
server.log(lux)
});

device.on(“soil”, function(soil) {
server.log(soil)
});

device.on(“humid”, function(humid) {
server.log(humid)
});
/* RUNTIME BEGINS HERE -------------------------------------------------------*/

server.log(“Agente Jardineiro a postos!”);

// instantiate our Xively client
xivelyClient <- Xively.Client(XIVELY_API_KEY);
xivelyChannel <- Xively.Channel(“temperature”);Device code://Growerbot code by Havoc (luizhavoc@gmail.com)
//thanks to https://github.com/liseman for parts of the code

//uart initialization
function startUART()
{
hardware.configure(UART_1289);
hardware.uart1289.configure(2400, 8, PARITY_NONE, 1, NO_CTSRTS);
//using this baud to match arduino softserial config on its firmware
}
//uart check
function checkUART()
{
imp.wakeup(1, checkUART);
local c = “”;
local b = hardware.uart1289.read();

while (b != -1) 
{
c += b.tochar();
b = hardware.uart1289.read();
}

if (c.len()){
//this splits the string sent by arduino into individual sensors and logs them throug server.log
//TEMPERATURE info from arduino data
local tStart = c.find(“T”);
tStart = tStart + 1;
local temp = c.slice(tStart);
local tEnd = temp.find(“T”);
temp = temp.slice(0,tEnd);
server.log(“Temp:” + temp);
//find location of L in sensor data string
local lStart = c.find(“L”);
lStart = lStart + 1;
local light = c.slice(lStart);
local lEnd = light.find(“L”);
light = light.slice(0,lEnd);
server.log(“Lux:” + light);
//find location of M(soil) in sensor data string
local mStart = c.find(“M”);
mStart = mStart + 1;
local soil = c.slice(mStart);
local mEnd = soil.find(“M”);
soil = soil.slice(0,mEnd);
server.log(“Soil:” + soil);
//find location of Humidity in sensor data string
local hStart = c.find(“H”);
hStart = hStart + 1;
local humid = c.slice(hStart);
local hEnd = humid.find(“H”);
humid = humid.slice(0,hEnd);
server.log(“Hum:” + humid + “%+”);
//this sends each sensor value to agent agent catches this through device.on command
agent.send(“temp”, temp);
agent.send(“lux”, light);
agent.send(“soil”, soil);
agent.send(“humid”, humid);
} // if bracket end
} //checkUART bracket end

startUART(); //setup uart
checkUART(); //begin uart polling`

I can see a couple of things that won’t work. Your device.on functions don’t do anything except log the values, and this function takes an id parameter that isn’t specified anywhere. My guess is that you don’t actually want an id tagged onto your channel.
function postToXively(data,id)

So, a couple of questions:

Do you want to send a value for each of your sensors at the same time or at separate times? If the Arduino sends values for each sensor with each communication, you can send all the data to the agent once, and immediately write that to Xively. Let me know I can post some code to try.

Almost there! :slight_smile:
jwehr, I corrected device.on functions.
I dont mind having a id tagged, this is needed by the agent code to automatically opens the channel right?

Ok, instead trying to get id to each channel from device, I tryed to do this in the agent code.
I added all sensor channels on the begining of the code (XIVELYCHANNEL1, XIVELYCHANNEL2, XIVELYCHANNEL3, XIVELYCHANNEL4)
I made the function device.on that first catch each sensor value and then declares a local id = “each sensor”, after that calls postToXively(eachsensor, id)

when I first tryed server log shown me a error on line 125:

xivelyChannel <- Xively.Channel(XIVELYCHANNEL+id);
“XIVELYCHANNEL does not exist or something like that”

so I changed to (line 125):

xivelyChannel <- Xively.Channel(xivelyChannel+id);

After this I finally start to get responses from xively:

[Agent] Posted to Xively: 35.50, got return code: 400, msg: 400 Bad request Your browser sent an invalid request.

Forgot Feed ID and API key, d’oh!

but note how Agent now tried to post the correct value to xively (in this example 35.50 is the temperature in Celsius read from sensor)

So I filled the Feed Id and API key and tried again:

server log:

[Agent] Posted to Xively: 26.60, got return code: 422, msg: {“title”:“Unprocessable Entity”,“errors”:[“Datastreams stream is invalid”]}

I went on xively and saw the request log filled with “422 PUT send”

clicked on those and they have this info on request (last 5 requests):
"datastreams": "id": "(instance : 0x7fd4dd362430)temp","current_value": "26.60"

"datastreams": "id": "(instance : 0x7fd4d903ca10)lux","current_value": "439"
"datastreams":"id": "(instance : 0x7fd4d926a740)lux","current_value": "446"
"datastreams": "id": "(instance : 0x7fd4de810a10)humid","current_value": "37.20"
"datastreams": "id": "(instance : 0x7fd4dd35df20)temp","current_value": "26.50"

Here is the last code used:
Agent:
`/* GLOBALS and CONSTANTS -----------------------------------------------------*/

const XIVELY_API_KEY = “fill here”;
const XIVELY_FEED_ID = “fill here”;
const XIVELYCHANNEL1 = “Temperature”;
const XIVELYCHANNEL2 = “Light”;
const XIVELYCHANNEL3 = “Soil Moisture”;
const XIVELYCHANNEL4 = “Relative Humidity”;
Xively <- {}; // this makes a ‘namespace’

/* CLASS AND GLOBAL FUNCTION DEFINITIONS -------------------------------------*/

// Xively “library”. See https://github.com/electricimp/reference/tree/master/webservices/xively

class Xively.Client {
ApiKey = null;
triggers = [];

constructor(apiKey) {
this.ApiKey = apiKey;
}

/*****************************************
 * method: PUT
 * IN:
 *   feed: a XivelyFeed we are pushing to
 *   ApiKey: Your Xively API Key
 * OUT:
 *   HttpResponse object from Xively
 *   200 and no body is success
 *****************************************/
function Put(feed){
	local url = "https://api.xively.com/v2/feeds/" + feed.FeedID + ".json";
	local headers = { "X-ApiKey" : ApiKey, "Content-Type":"application/json", "User-Agent" : "Xively-Imp-Lib/1.0" };
	local request = http.put(url, headers, feed.ToJson());

	return request.sendsync();
}

/*****************************************
 * method: GET
 * IN:
 *   feed: a XivelyFeed we fulling from
 *   ApiKey: Your Xively API Key
 * OUT:
 *   An updated XivelyFeed object on success
 *   null on failure
 *****************************************/
function Get(feed){
	local url = "https://api.xively.com/v2/feeds/" + feed.FeedID + ".json";
	local headers = { "X-ApiKey" : ApiKey, "User-Agent" : "xively-Imp-Lib/1.0" };
	local request = http.get(url, headers);
	local response = request.sendsync();
	if(response.statuscode != 200) {
		server.log("error sending message: " + response.body);
		return null;
	}

	local channel = http.jsondecode(response.body);
	for (local i = 0; i < channel.datastreams.len(); i++)
	{
		for (local j = 0; j < feed.Channels.len(); j++)
		{
			if (channel.datastreams[i].id == feed.Channels[j].id)
			{
				feed.Channels[j].current_value = channel.datastreams[i].current_value;
				break;
			}
		}
	}

	return feed;
}

}

class Xively.Feed{
FeedID = null;
Channels = null;

constructor(feedID, channels)
{
    this.FeedID = feedID;
    this.Channels = channels;
}

function GetFeedID() { return FeedID; }

function ToJson()
{
    local json = "{ \"datastreams\": [";
    for (local i = 0; i < this.Channels.len(); i++)
    {
        json += this.Channels[i].ToJson();
        if (i < this.Channels.len() - 1) json += ",";
    }
    json += "] }";
    return json;
}

}

class Xively.Channel {
id = null;
current_value = null;

constructor(_id)
{
    this.id = _id;
}

function Set(value) { 
	this.current_value = value; 
}

function Get() { 
	return this.current_value; 
}

function ToJson() { 
	return http.jsonencode({id = this.id, current_value = this.current_value }); 
}

}

function postToXively(data,id) {
xivelyChannel <- Xively.Channel(xivelyChannel+id);
xivelyChannel.Set(data);
xivelyFeed <- Xively.Feed(XIVELY_FEED_ID, [xivelyChannel]);
local resp = xivelyClient.Put(xivelyFeed);
server.log("Posted to Xively: “+data+”, got return code: “+resp.statuscode+”, msg: "+resp.body);
}

/* REGISTER DEVICE CALLBACKS ------------------------------------------------*/
//this catches data sent from device
device.on(“temp”, function(temp) {
local id = "temp"
server.log(temp)
postToXively(temp, id);
});

device.on(“lux”, function(lux) {
local id = "lux"
server.log(lux)
postToXively(lux, id);
});

device.on(“soil”, function(soil) {
local id = "soil"
server.log(soil)
postToXively(soil, id);
});

device.on(“humid”, function(humid) {
local id = "humid"
server.log(humid)
postToXively(humid, id);
});
/* RUNTIME BEGINS HERE -------------------------------------------------------*/

server.log(“Agente Jardineiro a postos!”);

// instantiate our Xively client
xivelyClient <- Xively.Client(XIVELY_API_KEY);
xivelyChannel <- Xively.Channel(XIVELYCHANNEL1);
xivelyChannel <- Xively.Channel(XIVELYCHANNEL2);
xivelyChannel <- Xively.Channel(XIVELYCHANNEL3);
xivelyChannel <- Xively.Channel(XIVELYCHANNEL4);`

Ok, a couple of things:

At the bottom of your agent code, you have this:
// instantiate our Xively client xivelyChannel <- Xively.Channel(XIVELYCHANNEL1); xivelyChannel <- Xively.Channel(XIVELYCHANNEL2); xivelyChannel <- Xively.Channel(XIVELYCHANNEL3); xivelyChannel <- Xively.Channel(XIVELYCHANNEL4);

You aren’t creating 4 different channels here, you are just creating one, and then successively assigning your channel ID’s to it, which means that it will have the ID that was assigned last. In any case, you don’t even need these lines, because your postToXively function is assigning an ID to the channel each time you pass a parameter to it.

Try this: I am coding it on the forum, so hopefully it is correct:

`
function postToXively(data, channel) {
xivelyChannel <- Xively.Channel(channel);
xivelyChannel.Set(data);
xivelyFeed <- Xively.Feed(XIVELY_FEED_ID, [xivelyChannel]);
local resp = xivelyClient.Put(xivelyFeed);
server.log("Posted to Xively: “+data+”, got return code: “+resp.statuscode+”, msg: "+resp.body);
}

/* REGISTER DEVICE CALLBACKS ------------------------------------------------*/
//this catches data sent from device
device.on(“temp”, function(temp) {
server.log(temp)
postToXively(temp, XIVELYCHANNEL1);
});

device.on(“lux”, function(lux) {
server.log(lux)
postToXively(lux, XIVELYCHANNEL2);
});

device.on(“soil”, function(soil) {
server.log(soil)
postToXively(soil, XIVELYCHANNEL3);
});

device.on(“humid”, function(humid) {
server.log(humid)
postToXively(humid, XIVELYCHANNEL4);
});
`

Ty a lot! its working now!

https://xively.com/feeds/1712082892

:slight_smile: