I'm new to node-red and sorta new to javascript and would appreciate any helpful criticism concerning best practices.
This function stores sensor data in a context variable every 5 seconds then at one minute timer ticks sends the data to a file. It only sends the last sensor data stored in a variable, not all data for the past minute.
var ambient = context.get('ambient')||0;
var brewbox = context.get('brewbox')||0;
var brewbucket = context.get('brewbucket')||0;
var setpoint = context.get('setpoint')||0;
var heat = context.get('heat')||0;
var cool = context.get('cool')||0;
var enable = context.get('enable')||false;
var time_tick = context.get('time_tick')||0;
var payload = msg.payload;
var topic = msg.topic;
switch (topic){
case 'tick':
context.set('time_tick', payload);
//node.status({fill:"red",shape:"dot",text:msg.topic});
if (context.get('enable') === true){
msg.payload={
'TIME':context.get('time_tick')||0,
'AMBIENT':context.get('ambient')||0,
'BREWBOX':context.get('brewbox')||0,
'BREWBUCKET':context.get('brewbucket')||0,
'SETPOINT':context.get('setpoint')||0,
'HEAT':context.get('heat')||0,
'COOL':context.get('cool')||0}
msg.topic = 'status_tick';
return msg;
}
break;
case 'enable':
node.status({fill:"red",shape:"dot",text:topic +':' + payload});
context.set('enable', payload);
if (context.get('enable')){
msg.payload={
'TIME':'TIME',
'AMBIENT':'AMBIENT',
'BREWBOX':'BREWBOX',
'BREWBUCKET':'BREWBUCKET',
'SETPOINT':'SETPOINT',
'HEAT':'HEAT',
'COOL':'COOL'}
msg.topic = 'status_tick';
return msg;
}
break;
case 'ambient':
//node.status({fill:"red",shape:"dot",text:msg.topic});
context.set('ambient',payload);
break;
case 'brewbox':
//node.status({fill:"red",shape:"dot",text:msg.topic});
context.set('brewbox',payload);
break;
case 'brewbucket':
//node.status({fill:"red",shape:"dot",text:msg.topic});
context.set('brewbucket',payload);
break;
case 'setpoint':
//node.status({fill:"red",shape:"dot",text:msg.topic});
context.set('setpoint',payload);
break;
case 'heat':
//node.status({fill:"red",shape:"dot",text:msg.topic});
context.set('heat',payload);
break;
case 'cool':
//node.status({fill:"red",shape:"dot",text:msg.topic});
context.set('cool',payload);
break;
case 'end':
context.set('enable', false);
msg.payload={
'TIME':context.get('time_tick')||0,
'AMBIENT':'end',
'BREWBOX':'end',
'BREWBUCKET':'end',
'SETPOINT':'end',
'HEAT':'end',
'COOL':'end'};
msg.topic = 'status_tick';
return msg;
}