node red function and export to CSV - javascript

I have the raspberry pi and sense hat. I wish to extract acceleration z,y,x,Temperature and Pressure and time to csv. However, the code I've written does not do what i want it to do. I was expecting the data to leave the function in an array but the debug window shows them as separate objects. How do i get acceleration z,y,x and time to leave as one array so i can export to CSV?
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.9487
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.2781
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Object
object
payload: 0.1491
_msgid: "ae0db049.020f6"
29/03/2017, 17:17:23node: abf1ef08.31a6f
msg : Date
"Wed Mar 29 2017 16:17:25 GMT+0000 (UTC)
Here's the function code :
var msgAccelZ,msgAccelX,msgAccelY,msgTemperature,msgPressure,msgCurrentTime;
if (msg.topic === 'motion') {
msgAccelZ = { payload: msg.payload.acceleration.z, };
msgAccelX = { payload: msg.payload.acceleration.x, };
msgAccelY = { payload: msg.payload.acceleration.y, };
} else if (msg.topic === 'environment') {
msgTemperature = { payload: msg.payload.temperature };
msgPressure = { payload: msg.payload.pressure };
}
msgCurrentTime = new Date();
return [ [msgAccelZ, msgAccelX, msgAccelY,msgCurrentTime] ,[msgTemperature, msgPressure, msgCurrentTime] ];

A Function needs to return a message object, not just a raw value.
By convention, you'd put the data you want to return under msg.payload:
msg.payload = [ [msgAccelZ, msgAccelX, msgAccelY,msgCurrentTime] ,[msgTemperature, msgPressure, msgCurrentTime] ];
return msg;
The documentation for the Function node explains in more detail: http://nodered.org/docs/writing-functions

Related

How to convert object timestamp to firebase timestamp?

I want to convert the following timestamp:
Object {
"_nanoseconds": 725000000,
"_seconds": 1621386976,
}
to this timestamp:
t {
"nanoseconds": 725000000,
"seconds": 1621386976,
}
How can I go about doing this? I am stumped. I have tried toDate() and variations of this, but nothing is working.
Found this on reddit:
getTimeText = (timeObject: any) => {
// Convert to time text once it's of type firestore.Timestamp
const getTextFromTimestamp = (timestamp: app.firestore.Timestamp) => {
return this.timeAgo.format(timestamp.toDate())
}
if (timeObject instanceof app.firestore.Timestamp) {
// Check if Timestamp (accessed from client SDK)
return getTextFromTimestamp(timeObject)
} else if (Object.prototype.toString.call(timeObject) === '[object Object]') {
// Check if it's a Map (accessed from Cloud Functions)
const seconds = timeObject['_seconds']
const nanoseconds = timeObject['_nanoseconds']
if (seconds && nanoseconds) {
const timestamp = new app.firestore.Timestamp(seconds, nanoseconds)
return getTextFromTimestamp(timestamp)
}
}
console.log('Couldn\'t parse time', timeObject)
// Fallback
return 'some time ago'
}

I want to replace the value of an object inside an array?

I have a timestamp in my array that I have removed the UTC letters from and I want to replace the old timestamp with the "new" timestamp(without UTC)
Maybe there is an even easier way to do the removing?
So I've tried to loop over my data with .forEach and .map trying to replace it but still haven't figure it out how to exactly do so.
I've watched a bunch of Stackoverflow threads about this but haven't found a solution that I get to work....clearly missing something or writing something wrong.
So can anyone guide me how to solve this in the best way?
const data = [
{
timestamp: "2019-03-01 09:00:00UTC",
url: "/blub.html",
userid: "12345"
},
{
timestamp: "2019-03-01 09:00:00UTC",
url: "/cont.html ",
userid: "12346"
},
{
timestamp: "2019-03-01 10:00:00UTC ",
url: "/cont.html ",
userid: "12345"
},
{
timestamp: "2019-03-01 10:30:00UTC",
url: "/ho.html ",
userid: "12347"
}
];
console.log("data", data);
console.log("ex: first data object:", data[0]);
//loop through and grab the timestamp in each object and remove the UTC stamp
const GrabTimeStamp = () => {
data.forEach(function (objects, index) {
const timeStamp = objects.timestamp;
const newTimeStamp = timeStamp.slice(0, 19);
console.log("newTimeStamp:", newTimeStamp, index);
//next step to replace the old timestamp with newTimeStamp
});
};
GrabTimeStamp()
Your code looks fine, just refactor that fragment (best approach to work with forEach):
data.forEach((item, index) => {
const timeStamp = item.timestamp;
const newTimeStamp = timeStamp.slice(0, 19);
item.timestamp = newTimeStamp;
});
and it should work.
Did you know that variables declared with "const" could not be changed? So it seems like you want to use "var" here. The last 3 letters can be removed by "slice(0, -3)".
var data = [
{
timestamp: "2019-03-01 09:00:00UTC",
url: "/blub.html",
userid: "12345"
},
{
timestamp: "2019-03-01 09:00:00UTC",
url: "/cont.html ",
userid: "12346"
},
{
timestamp: "2019-03-01 10:00:00UTC",
url: "/cont.html ",
userid: "12345"
},
{
timestamp: "2019-03-01 10:30:00UTC",
url: "/ho.html ",
userid: "12347"
}
];
console.log("data", data);
console.log("ex: first data object:", data[0]);
//loop through and grab the timestamp in each object and remove the UTC stamp
var grabTimeStamp = () => {
data.forEach(function (object, index) {
var newTimeStamp = object.timestamp.slice(0, -3);
console.log("newTimeStamp:", newTimeStamp, index);
//next step to replace the old timestamp with newTimeStamp
object.timestamp = newTimeStamp;
});
};
grabTimeStamp();
Since it does seem like you are fairly new to coding, I tried to change only a few things in your code. However your function grabTimeStamp can be done shorter:
function removeTimestamp(data){
data.foreach((item, index) => {
item.timestamp = item.timestamp.slice(0, -3);
});
}
removeTimestamp(data);

value.getTime is not a function GraphQL custom scalar Date

I receive LASTUPDATE: 1579452599 response from an external API,
I want to parse the value in this format: Mon Jan 19 2020 13:44:04, I tried using custom scallar, but I'm having this error:
value.getTime is not a function
What am I doing wrong?
This is my code,
resolvers.js
import fetch from 'node-fetch';
import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';
export const resolvers = {
Query: {
getCrypto: async() => {
const response = await fetch('https://min-api.cryptocompare.com/data/top/totalvolfull?limit=10&tsym=USD&api_key=260d15e639be7b967c2b0e4f9f3b6d656897ccbdfe772b1d24818d9f96d3a6ed')
let data = await response.json()
return data.Data[0].RAW.USD;
}
},
Date: new GraphQLScalarType({
name: 'Date',
description: 'Date custom scalar type',
parseValue(value) {
return new Date(value); // value from the client
},
serialize(value) {
console.log(value)
return value.getTime(); // value sent to the client
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return parseInt(ast.value, 10); // ast value is always in string format
}
return null;
},
})
};
schema.graphql
type CryptoCurrency {
FROMSYMBOL: String
PRICE: Float
TOSYMBOL: String
LASTUPDATE: Date
}
type Query {
getCrypto: CryptoCurrency
}
scalar Date
type MyType {
created: Date
}
In console I see the value
In case anyone else comes here from a google search for a similar issue
You should convert LASTUPDATE from timestamp to actual date, and have to multiply by 1000 because Javascript uses milliseconds.
serialize(value) {
console.log( new Date(value).toISOString())
return new Date(value * 1000).toISOString(); // value sent to the client
}

How can you destructure an array of objects in Javascript into two predefined variables in ES6?

I have an array containing one object of this form :
Array = [ { type: type, message: message } ]
I keep getting ESLint errors asking me to use object destructuring and array destructuring.
Currently my code looks like this :
let type=null;
let message=null;
if (data.length > 0) {
({ type, message } = data[0]);
}
So far this works and my variables are assigned correctly, however I am still getting the "Use array destructuring" message from ESLint.
Any help with this would be appreciated. Thank you
You can destructure the array:
let type=null;
let message=null;
if (data.length > 0) {
[{ type, message }] = data;
}
The code above is a shorter version of:
[ firstElement ] = data; // array destructruring
({ type, message } = firstElement); // object destructuring
Faly's way is good. You can also use default values when destructuring:
function test(label, data) {
// 1 -----------------------------vvvvv
let [{type = null, message = null} = {}] = data;
// 2 -----^^^^^^^---------^^^^^^^
console.log(label, type, message);
}
test("test1: ", []);
test("test2: ", [{type: "t"}]);
test("test3: ", [{type: "t", message: "m"}]);
That works because if data.length is 0, data[0] is undefined, and so triggers use of the default value {} (1) for the array part of that; within the object part of that, we use null (2) to handle any missing values on the object as well.
EsLint wants you to write
let type = null;
let message = null;
if (data.length > 0) {
[{ type, message }] = data;
}
which destructures the first item of an iterable data into the {type, message} target. (More items are ignored).
I would however recommend to use default values for the empty case:
const [{type, message} = {type:null, message:null}] = data;
or also
const [{type = null, message = null} = {}] = data;

property missing in returned json response / javascript

Im working in React on some weather widget which displays temp and rain forecast. Im fetching data from OpenWeather and my json response looks like:
//rainy day
0:{
main: {
temp:10}
rain: {
3h: 1000}
}
//sunny day
1:{
main: {
temp:10}
}
the problem is rain.3h property appears in returned response only when it has some data, otherwise its missing. My request looks like:
async getForecast(term) {
const forecastUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + term + "&appid=" + apiKey + "&lang=us&units=metric&cnt=16";
try {
let response = await fetch(forecastUrl);
if (response.ok) {
let jsonResponse = await response.json();
let forecast = jsonResponse.list.map(
day => {
return {
temp: day.main.temp,
rain: day.rain["3h"], // can't map missed property
}
}
)
return (forecast);
}
} catch (error) {
console.log(error);
}
}
And Im getting error
TypeError: Cannot read property '3h' of undefined.
How may I add default rain:0 when the property is missing from response
You could do a check using ternary operator
let forecast = jsonResponse.list.map(
day => {
return {
temp: day.main.temp,
rain: day.rain?day.rain["3h"] : ''
}
}
)
You should check whether the property exists or not
var obj = {};
obj.temp = day.main.temp;
if (day.hasOwnProperty("rain") && day.rain.hasOwnProperty("3h"))
obj.rain = day.rain["3h"];
return obj;
You can use assignment with double ampersand "&&":
let forecast = jsonResponse.list.map(
day => {
return {
temp: day.main.temp,
rain: day.rain && day.rain["3h"] || 0
}
}
)
This works because if day.rain is undefined then the second part of the boolean expression will not be evaluated, avoiding the cannot read property of undefined error, and the value from the OR will be used for default assignment.

Categories