Http Request JSON

Hi everyone.

Back to work with NodeRed. I am trying to make a call to an API to know the price of electricity in the different time zones.

The problem I have is that the API returns a JSON divided into three parts (the three parts of the day morning, afternoon and night) and I don't really know how to work with that data.

I have managed to get the price of a certain time slot in the day (eg 11-12), but I don't know how to get the data for the morning, afternoon or night.

Any ideas?

Thank you very much in advance for the answers.

[{"id":"3540934444401c02","type":"tab","label":"Red Electrica Española","disabled":false,"info":""},{"id":"1360ce35dd704b4e","type":"inject","z":"3540934444401c02","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":120,"y":60,"wires":[["9f6a2bad182d7051"]]},{"id":"9f6a2bad182d7051","type":"http request","z":"3540934444401c02","name":"","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://api.esios.ree.es/archives/70/download_json?locale=es","tls":"","persist":false,"proxy":"","authType":"","x":290,"y":60,"wires":[["7887d4217c174221","4d27106bc9b2050e","34e634a4c2176154"]]},{"id":"7887d4217c174221","type":"ui_text","z":"3540934444401c02","group":"9e908f06.94c48","order":3,"width":0,"height":0,"name":"","label":"Precio Energía Actual Mañana","format":"{{msg.payload.PVPC[10].PCB}}","layout":"row-spread","className":"","x":1277.5,"y":67,"wires":[]},{"id":"634e8b7f13d1d5f1","type":"ui_text","z":"3540934444401c02","group":"9e908f06.94c48","order":3,"width":0,"height":0,"name":"","label":"Precio Energía Actual Mediodia","format":"{{msg.payload.PVPC[10].PCB}}","layout":"row-spread","className":"","x":1278,"y":141,"wires":[]},{"id":"359eb1eddb8ddc01","type":"ui_text","z":"3540934444401c02","group":"9e908f06.94c48","order":3,"width":0,"height":0,"name":"","label":"Precio Energía Actual Tarde","format":"{{msg.payload.PVPC[10].PCB}}","layout":"row-spread","className":"","x":1273,"y":211,"wires":[]},{"id":"4d27106bc9b2050e","type":"ui_gauge","z":"3540934444401c02","name":"","group":"2260f340.79727c","order":6,"width":"3","height":"3","gtype":"donut","title":"Gate A Status","label":"€/KwH","format":"{{msg.payload.PVPC[10].PCB}}","min":0,"max":"5","colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","className":"","x":1250,"y":299,"wires":[]},{"id":"34e634a4c2176154","type":"debug","z":"3540934444401c02","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":466.5,"y":254,"wires":[]},{"id":"9e908f06.94c48","type":"ui_group","name":"Hoy","tab":"41973f9d.b568a","order":2,"disp":true,"width":"10","collapse":false,"className":""},{"id":"2260f340.79727c","type":"ui_group","name":"Climatización","tab":"41973f9d.b568a","order":6,"disp":true,"width":"10","collapse":false,"className":""},{"id":"41973f9d.b568a","type":"ui_tab","name":"Home","icon":"home","order":1}]

Probably more useful for you to post an example of the data rather than your flow.

Do you know about using the debug panel to copy the property path inside an object? You can then use that in a function or change node for example.

Hello @TotallyInformation

Thanks for the answer.

It's true. I am attaching two screenshots of the data I want to work with.

Yes. I know the debugging panel, that's where I have been able to get the data, but only for a specific hour.

Datos 1

I actually meant for you to post the json in </> :grinning: but anyway, I think I can see even from the pictures that there are 24 array entries which means that almost certainly msg.payload.PVPC[14] would be the entry for 3pm (15:00). Does that help?

Hello @TotallyInformation

And again thanks for responding so quickly.

Forgive my mistake, here I publish the JSON.

Yes. Exactly. It has from 0 to 23 which are the entries of the hours of the day.

What I was looking to do is. Put a graph or text so that depending on the time of day I am, it shows the price that the API delivers.

[{"id":"3540934444401c02","type":"tab","label":"Red Electrica Española","disabled":false,"info":""},{"id":"1360ce35dd704b4e","type":"inject","z":"3540934444401c02","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":120,"y":60,"wires":[["9f6a2bad182d7051"]]},{"id":"9f6a2bad182d7051","type":"http request","z":"3540934444401c02","name":"","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://api.esios.ree.es/archives/70/download_json?locale=es","tls":"","persist":false,"proxy":"","authType":"","x":290,"y":60,"wires":[["7887d4217c174221","4d27106bc9b2050e","34e634a4c2176154"]]},{"id":"7887d4217c174221","type":"ui_text","z":"3540934444401c02","group":"9e908f06.94c48","order":3,"width":0,"height":0,"name":"","label":"Precio Energía Actual Mañana","format":"{{msg.payload.PVPC[10].PCB}}","layout":"row-spread","className":"","x":1277.5,"y":67,"wires":[]},{"id":"634e8b7f13d1d5f1","type":"ui_text","z":"3540934444401c02","group":"9e908f06.94c48","order":3,"width":0,"height":0,"name":"","label":"Precio Energía Actual Mediodia","format":"{{msg.payload.PVPC[10].PCB}}","layout":"row-spread","className":"","x":1278,"y":141,"wires":[]},{"id":"359eb1eddb8ddc01","type":"ui_text","z":"3540934444401c02","group":"9e908f06.94c48","order":3,"width":0,"height":0,"name":"","label":"Precio Energía Actual Tarde","format":"{{msg.payload.PVPC[10].PCB}}","layout":"row-spread","className":"","x":1273,"y":211,"wires":[]},{"id":"4d27106bc9b2050e","type":"ui_gauge","z":"3540934444401c02","name":"","group":"2260f340.79727c","order":6,"width":"3","height":"3","gtype":"donut","title":"Gate A Status","label":"€/KwH","format":"{{msg.payload.PVPC[10].PCB}}","min":0,"max":"5","colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","className":"","x":1250,"y":299,"wires":[]},{"id":"34e634a4c2176154","type":"debug","z":"3540934444401c02","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":466.5,"y":254,"wires":[]},{"id":"9e908f06.94c48","type":"ui_group","name":"Hoy","tab":"41973f9d.b568a","order":2,"disp":true,"width":"10","collapse":false,"className":""},{"id":"2260f340.79727c","type":"ui_group","name":"Climatización","tab":"41973f9d.b568a","order":6,"disp":true,"width":"10","collapse":false,"className":""},{"id":"41973f9d.b568a","type":"ui_tab","name":"Home","icon":"home","order":1}]

This is one of those cases where JSONata is REALLY good.

For example, this JSONata code payload.PVPC.{"Hour": Hora, "Price": PMHCYM} should give you:

[
  {
    "Hour": "00-01",
    "Price": "242,29"
  },
  {
    "Hour": "01-02",
    "Price": "235,73"
  },
  ...
]

That you could probably easily feed into a Dashboard chart node.

Or this gives you just one set of prices on their own payload.PVPC.PMHCYM:

[
  "242,29",
  "235,73",
  "235,31",
  "228,17",
  "227,98",
  "233,68",
  "249,28",
  "272,40",
  "285,42",
  "278,63",
  "248,56",
  "217,61",
  "215,18",
  "210,13",
  "212,75",
  "211,65",
  "211,47",
  "231,78",
  "248,84",
  "285,95",
  "291,75",
  "275,31",
  "252,56",
  "240,51"
]

Or as an array of arrays PVPC.[Hora,PMHCYM]:

[
  [
    "00-01",
    "242,29"
  ],
  [
    "01-02",
    "235,73"
  ],
  ...
]

Hello @TotallyInformation, and again, thank you for the answer.

The truth is that I am learning little by little.

You mean to paste the code into a "parser / json" node type?

I have tried putting the code payload.PVPC. {"Hour": Hour, "Price": PMHCYM} in various gauges but I can't get it to display correctly.

I'm getting a little stuck.

The code I shared was JSONata, it goes into a change node where you set, say, the msg.payload to a JSONata function. Paste in the code and it should work. Have a look at the help for the change node and I'm sure you will get it shortly.

Hello

Sorry to bother so much, in the end I will get it !!!

I guess I mean this.

I have tried, but it returns an array similar to the previous one. Or as I suppose it happens, am I not doing it right?

flow1

Here is an example this will take your data and create the data for the chart node. It uses JSONata expression to manipulate the data. Hopefully you can work out what it's doing, if not ask away.

[{"id":"1360ce35dd704b4e","type":"inject","z":"3540934444401c02","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":120,"y":60,"wires":[["9f6a2bad182d7051"]]},{"id":"9f6a2bad182d7051","type":"http request","z":"3540934444401c02","name":"","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://api.esios.ree.es/archives/70/download_json?locale=es","tls":"","persist":false,"proxy":"","authType":"","x":260,"y":160,"wires":[["74daa16b.dc125"]]},{"id":"74daa16b.dc125","type":"change","z":"3540934444401c02","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"[{\t\"labels\": [],\t\"series\": [\"a\"],\t\"data\": [[payload.PVPC.{\"x\": $number($substring($.Hora, 0, 2)), \"y\": $number($replace($.PCB, \",\", \".\"))}]]\t}]","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":510,"y":160,"wires":[["34e634a4c2176154","be6e8e5e.75676"]]},{"id":"34e634a4c2176154","type":"debug","z":"3540934444401c02","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":466.5,"y":254,"wires":[]},{"id":"be6e8e5e.75676","type":"ui_chart","z":"3540934444401c02","name":"","group":"8b5cde76.edd58","order":0,"width":0,"height":0,"label":"chart","chartType":"line","legend":"false","xformat":"x","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"useUTC":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"outputs":1,"useDifferentColor":false,"x":650,"y":200,"wires":[[]]},{"id":"8b5cde76.edd58","type":"ui_group","name":"","tab":"8f03e639.85956","order":1,"disp":true,"width":"12","collapse":false},{"id":"8f03e639.85956","type":"ui_tab","name":"Home","icon":"dashboard","disabled":false,"hidden":false}]

the expression

[
   {
       "labels": [],
       "series": ["a"],
       "data": [
           [
               payload.PVPC.{
                   "x": $number($substring($.Hora, 0, 2)),
                   "y": $number($replace($.PCB, ",", "."))
               }
           ]
       ]
    }
]
2 Likes

Hello
I have this flow which gets prices from esios and stores it in an influxDB database.
Later on, I can plot the data with Grafana.

[{"id":"78d8c1b0.1a383","type":"group","z":"ea309d53.9aca9","name":"get PVPC prices","style":{"label":true},"nodes":["7554f0ab.61df6","f64ebf42.76f9","86b1f3e9.37c6f","c89b46cf.d82f58","894c30ba.7dfe2","cb48087.056a7f8","ae1242c.c9e88c","b8739b1d.cd8bb8"],"x":44,"y":19,"w":662,"h":142},{"id":"7554f0ab.61df6","type":"change","z":"ea309d53.9aca9","g":"78d8c1b0.1a383","name":"Prepara data","rules":[{"t":"set","p":"payload","pt":"msg","to":"payload.PVPC.[{\t        'time': $number($moment(Dia, 'DD/MM/YYYY').format('x')) + $number($substringBefore(Hora, \"-\"))*1000*60*60,\t        'PVPC': $number($replace(PCB,',','.'))/1000\t    }\t]","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":495,"y":120,"wires":[["f64ebf42.76f9","86b1f3e9.37c6f"]],"l":false},{"id":"f64ebf42.76f9","type":"debug","z":"ea309d53.9aca9","g":"78d8c1b0.1a383","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":595,"y":80,"wires":[],"l":false},{"id":"86b1f3e9.37c6f","type":"influxdb out","z":"ea309d53.9aca9","g":"78d8c1b0.1a383","influxdb":"e0a9238e.97607","name":"PVPC","measurement":"PVPC","precision":"ms","retentionPolicy":"","database":"","retentionPolicyV18Flux":"","org":"","bucket":"","x":630,"y":120,"wires":[]},{"id":"c89b46cf.d82f58","type":"http request","z":"ea309d53.9aca9","g":"78d8c1b0.1a383","name":"recupera de ESIOS","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://api.esios.ree.es/archives/70/download_json?date_type=datos&end_date={{{payload}}}T23%3A59%3A59%2B00%3A00&locale=es&start_date={{{payload}}}T00%3A00%3A00%2B00%3A00","tls":"","persist":false,"proxy":"","authType":"","credentials":{},"x":330,"y":120,"wires":[["894c30ba.7dfe2","7554f0ab.61df6"]]},{"id":"894c30ba.7dfe2","type":"debug","z":"ea309d53.9aca9","g":"78d8c1b0.1a383","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":495,"y":80,"wires":[],"l":false},{"id":"cb48087.056a7f8","type":"time-inject","z":"ea309d53.9aca9","g":"78d8c1b0.1a383","name":"Mañana","nameInt":"⏲ 20:30 = json expr.↷","positionConfig":"a39cfa79.ae17c8","props":[{"p":"","pt":"msgPayload","v":"$millis()+86400000 ~> $fromMillis('[D01]/[M01]/[Y]')","vt":"jsonata","o":"1","oT":"num","oM":"86400000","f":12,"fS":12,"fT":"local date","fI":"12","next":true,"days":"","months":"","onlyOddDays":false,"onlyEvenDays":false},{"p":"","pt":"msgTopic","v":"","vt":"str","o":"","oT":"none","oM":"60000","f":0,"fS":0,"fT":"UNIX timestamp (ms)","fI":"0","next":false,"days":"","months":"","onlyOddDays":false,"onlyEvenDays":false}],"injectTypeSelect":"time","intervalCount":1,"intervalCountType":"num","intervalCountMultiplier":60000,"time":"20:30","timeType":"entered","offset":0,"offsetType":"none","offsetMultiplier":60000,"timeEnd":"","timeEndType":"entered","timeEndOffset":0,"timeEndOffsetType":"none","timeEndOffsetMultiplier":60000,"timeDays":"*","timeOnlyOddDays":false,"timeOnlyEvenDays":false,"timeMonths":"*","timedatestart":"","timedateend":"","property":"","propertyType":"none","propertyCompare":"true","propertyThreshold":"","propertyThresholdType":"num","timeAlt":"","timeAltType":"entered","timeAltDays":"*","timeAltOnlyOddDays":false,"timeAltOnlyEvenDays":false,"timeAltMonths":"*","timeAltOffset":0,"timeAltOffsetType":"none","timeAltOffsetMultiplier":60000,"once":false,"onceDelay":0.1,"recalcTime":2,"x":140,"y":120,"wires":[["ae1242c.c9e88c","c89b46cf.d82f58"]]},{"id":"ae1242c.c9e88c","type":"debug","z":"ea309d53.9aca9","g":"78d8c1b0.1a383","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":255,"y":80,"wires":[],"l":false},{"id":"b8739b1d.cd8bb8","type":"comment","z":"ea309d53.9aca9","g":"78d8c1b0.1a383","name":"get PVPC prices","info":"","x":95,"y":60,"wires":[],"l":false},{"id":"e0a9238e.97607","type":"influxdb","hostname":"192.168.2.46","port":"8086","protocol":"http","database":"MB3iot","name":"MB3iot_DB","usetls":false,"tls":"","influxdbVersion":"1.x"},{"id":"a39cfa79.ae17c8","type":"position-config","name":"MB3","isValide":"true","longitude":"0","latitude":"0","angleType":"deg","timeZoneOffset":"99","timeZoneDST":"0","stateTimeFormat":"3","stateDateFormat":"12"}]

If you have Iberdrola distribución as your electricity distributor I can share a flow which gets hourly consumption data from the meter

1 Like

Hello @juanbal

It looks very very good. Yes, I have Iberdrola Distribución as an electricity company.

Very grateful if you share the flow that you have with me.

a greeting

Here's the flow.
You'll need to configure your username and password for the API.
Also you'll need to configure your influxdb connection and create the dashboard in grafana

You'll see that the flow connects to the API just once per hour.
If you increase the rate, your user will probably get banned.

[{"id":"f5be0c89d90593e2","type":"group","z":"19980b40dbba5f60","name":"Conecta a la API de Iberdrola distribución","style":{"label":true},"nodes":["0a7491fe831647d1","17123a370c161c84","0849efc401fdbdb8","41cb9a30171554d3","d1e84e1ce358b9b9","b0c40f4c00710450","225eec8ada9d49c9","0b3aef0670da6623","4dbe4bb9def4245c","855fd9334d622208","551e454a33c04e55","ca229abb05cd9270","f9cd98ec67d3933e","75b53a411c540185","9944217487f27a4f","c0a600cbaac17960","6ef444455b834e70","7c0acb43ca24d493","9949c13ca1f81430","4191e0aef5d0f17b","ede264a8f90e646e","ab31557b99366db1","7686ace805c8c8ef","5574cd4142bac37a","5d747b21535d13ed","eaadacf45168f9b5","d36ee45ad2a17816","467921d83c47a2ad","b9b6331259ae7253","5ce10976109ddd6c","4e54022f9e992bce","f46ae85a10de3ee3","35ac5da4b90bf43a","c44b13bfb15f1d40","c384d358fbabf3e2","e5661fee262d28d4","bd73e700ed66fe6c","321d4073ba366420","7800206f915b669a","be57baf6949dcf59","e1f7ecba1f2e0f35"],"x":74,"y":139,"w":1002,"h":442},{"id":"0a7491fe831647d1","type":"change","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"Params","rules":[{"t":"set","p":"email","pt":"flow","to":"xxxx","tot":"str"},{"t":"set","p":"pass","pt":"flow","to":"yyyy","tot":"str"},{"t":"set","p":"contadorRetries","pt":"flow","to":"0","tot":"num"}],"action":"","property":"","from":"","to":"","reg":false,"x":280,"y":180,"wires":[[]]},{"id":"17123a370c161c84","type":"inject","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"start","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":true,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":135,"y":180,"wires":[["0a7491fe831647d1"]],"l":false},{"id":"0849efc401fdbdb8","type":"http request","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"Login","method":"POST","ret":"obj","paytoqs":"ignore","url":"https://www.i-de.es/consumidores/rest/loginNew/login","tls":"","persist":false,"proxy":"","authType":"","x":290,"y":320,"wires":[["41cb9a30171554d3","b0c40f4c00710450"]]},{"id":"41cb9a30171554d3","type":"debug","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":375,"y":280,"wires":[],"l":false},{"id":"d1e84e1ce358b9b9","type":"function","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"preparaLogin","func":"var login = flow.get(\"email\");\nvar password = flow.get(\"pass\");\nmsg.payload = '[\"'+ login +'\",\"' + password + '\",null,\"Linux -\",\"PC\",\"Chrome 77.0.3865.90\",\"0\",\"\",\"s\"]';\nmsg.headers = {};\nmsg.headers['Content-Type'] = 'application/json; charset=utf-8';\nmsg.headers['Accept'] = 'application/json; charset=utf-8';\nmsg.headers['User-agent'] =\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/77.0.3865.90 Chrome/77.0.3865.90 Safari/537.36\";\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":195,"y":320,"wires":[["0849efc401fdbdb8"]],"l":false},{"id":"b0c40f4c00710450","type":"change","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"saveCookie","rules":[{"t":"set","p":"jsessionid","pt":"flow","to":"headers[\"set-cookie\"][1]","tot":"msg"},{"t":"set","p":"jsessionid_0","pt":"flow","to":"headers[\"set-cookie\"][0]","tot":"msg"},{"t":"delete","p":"payload","pt":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":415,"y":320,"wires":[["c0a600cbaac17960"]],"l":false},{"id":"225eec8ada9d49c9","type":"http request","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"Consums","method":"use","ret":"obj","paytoqs":"ignore","url":"","tls":"","persist":false,"proxy":"","authType":"","x":660,"y":280,"wires":[["4dbe4bb9def4245c","bd73e700ed66fe6c"]]},{"id":"0b3aef0670da6623","type":"function","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"Prepara getConsums","func":"// Netejem msg\nvar msgTopic = msg.topic;\nmsg={};\nmsg.topic = msgTopic;\n// Construim header\nvar jsessionId = flow.get(\"jsessionid\").split(\";\");\nvar jsessionId_0 = flow.get(\"jsessionid_0\").split(\";\");\nmsg.headers = {};\nmsg.headers['Content-Type'] = 'application/json; charset=UTF-8';\nmsg.headers['Accept'] = 'application/json, text/plain, */*';\nmsg.headers['AppVersion'] = 'v2';\nmsg.headers['dispositivo'] = 'desktop';\nmsg.headers['User-agent'] =\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/77.0.3865.90 Chrome/77.0.3865.90 Safari/537.36\";\nmsg.headers['cookie'] = jsessionId[0];\nmsg.headers['cookie'] = jsessionId_0[0];\n\n//https://www.i-de.es/consumidores/rest/consumoNew/obtenerDatosConsumoPeriodo/fechaInicio/20-11-202000:00:00/fechaFinal/30-11-202000:00:00/\n\n//Fecha de ayer\nvar date = new Date();\ndate.setDate(date.getDate() - 1);\nvar day = date.getDate(); \nvar month = date.getMonth() + 1; \nvar year= date.getFullYear(); \nif (day < 10) { day = '0' + day; } \nif (month < 10) { month = '0' + month; } \n//var fechaIni = day + \"-\" + month + \"-\" + year + \"00:00:00\";\nvar fechaIni = day + \"-\" + month + \"-\" + year;\n\nmsg.url = \"https://www.i-de.es/consumidores/rest/consumoNew/obtenerDatosConsumoDH/\" + fechaIni + \"/\" + fechaIni + \"/horas/\";\n//msg.url = \"https://www.i-de.es/consumidores/rest/consumoNew/obtenerDatosConsumoDH/13-10-2021/13-10-2021/horas/\";\nmsg.method =\"GET\";\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":535,"y":280,"wires":[["225eec8ada9d49c9","e5661fee262d28d4"]],"l":false},{"id":"4dbe4bb9def4245c","type":"debug","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":755,"y":240,"wires":[],"l":false},{"id":"855fd9334d622208","type":"debug","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":915,"y":320,"wires":[],"l":false},{"id":"551e454a33c04e55","type":"function","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","func":"var data = msg.payload[0].valores;\nvar date = msg.payload[0].fechaDesde;\nvar arrayConsum = [];\nvar objConsumTotals = {};\nvar msg2={};\nvar consumPunta = 0; // de 10 a 14h y de 18 a 22h.\nvar consumLlano = 0; // de 08 a 10h, de 14 a 18h y de 22 a 00h.\nvar consumValle = 0; // de 00 a 08h entre diario. Sábados, domingos y festivos todo el día.\nvar consumoTotalDia = parseFloat(msg.payload[0].total/1000);\n\nvar day = date.substring(0,2); \nvar month = date.substring(3,5)-1;\nvar year= date.substring(6,10);\nvar diaSemana = new Date(year,month,day).getDay();\n\n// Crea array amb objecte amb hora y consum\nfor (let i = 0; i < data.length; i++) {\n    //Crea timestamp per hores\n    var datum = new Date(year,month,day,i,'00','00');\n    // Acumulamos periodos\n    if (diaSemana == 0 || diaSemana == 6) {\n        // Dissabte y diumenge tot es punta\n        consumValle+=parseFloat(data[i]/1000);\n    } else {\n        // Entre setmana\n        if([0,1,2,3,4,5,6,7].includes(i)) { consumValle+=parseFloat(data[i]/1000) }\n        if([8,9,14,15,16,17,22,23].includes(i)) { consumLlano+=parseFloat(data[i]/1000) }\n        if([10,11,12,13,18,19,20,21].includes(i)) { consumPunta+=parseFloat(data[i]/1000) }\n    }\n    arrayConsum[i] = [{ \"time\":datum.getTime(), \"iberdrolaConsum\":parseFloat(data[i]/1000), \"totalConsumoDia\":consumoTotalDia}]; \n }\n\n// Objecte totals acumulats\nmsg.payload=arrayConsum;\nmsg2.payload=objConsumTotals = { \"time\":new Date(year,month,day,'00','00','00').getTime(),\"totalConsumoDia\":consumoTotalDia, \"totalConsumoPunta\": consumPunta, \"totalConsumoLlano\": consumLlano, \"totalConsumoValle\": consumValle };\n\nreturn [msg,msg2];\n\n//node.warn(i);","outputs":2,"noerr":0,"initialize":"","finalize":"","libs":[],"x":855,"y":260,"wires":[["75b53a411c540185","ca229abb05cd9270"],["855fd9334d622208","9944217487f27a4f"]],"l":false},{"id":"ca229abb05cd9270","type":"influxdb out","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","influxdb":"e0a9238e.97607","name":"iberdrolaConsum","measurement":"electricConsumHores","precision":"ms","retentionPolicy":"","database":"","retentionPolicyV18Flux":"","org":"","bucket":"","x":935,"y":240,"wires":[],"l":false},{"id":"f9cd98ec67d3933e","type":"time-inject","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","nameInt":"getConsumYesterday:⏲ 10:00 = timestamp","positionConfig":"a39cfa79.ae17c8","props":[{"p":"","pt":"msgPayload","v":"","vt":"date","o":"","oT":"none","oM":"60000","f":0,"fS":0,"fT":"UNIX timestamp (ms)","fI":"0","next":true,"days":"","months":"","onlyOddDays":false,"onlyEvenDays":false},{"p":"","pt":"msgTopic","v":"getConsumYesterday","vt":"str","o":"","oT":"none","oM":"60000","f":0,"fS":0,"fT":"UNIX timestamp (ms)","fI":"0","next":false,"days":"","months":"","onlyOddDays":false,"onlyEvenDays":false}],"injectTypeSelect":"time","intervalCount":1,"intervalCountType":"num","intervalCountMultiplier":60000,"time":"10:00","timeType":"entered","offset":0,"offsetType":"none","offsetMultiplier":60000,"timeEnd":"","timeEndType":"entered","timeEndOffset":0,"timeEndOffsetType":"none","timeEndOffsetMultiplier":60000,"timeDays":"*","timeOnlyOddDays":false,"timeOnlyEvenDays":false,"timeMonths":"*","timedatestart":"","timedateend":"","property":"","propertyType":"none","propertyCompare":"true","propertyThreshold":"","propertyThresholdType":"num","timeAlt":"","timeAltType":"entered","timeAltDays":"*","timeAltOnlyOddDays":false,"timeAltOnlyEvenDays":false,"timeAltMonths":"*","timeAltOffset":0,"timeAltOffsetType":"none","timeAltOffsetMultiplier":60000,"once":false,"onceDelay":0.1,"recalcTime":2,"x":135,"y":260,"wires":[["d1e84e1ce358b9b9","7686ace805c8c8ef"]],"l":false},{"id":"75b53a411c540185","type":"debug","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":915,"y":200,"wires":[],"l":false},{"id":"9944217487f27a4f","type":"influxdb out","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","influxdb":"e0a9238e.97607","name":"iberdrolaConsum","measurement":"electricConsumAcumulat","precision":"ms","retentionPolicy":"","database":"","retentionPolicyV18Flux":"","org":"","bucket":"","x":935,"y":280,"wires":[],"l":false},{"id":"c0a600cbaac17960","type":"switch","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"source","property":"topic","propertyType":"msg","rules":[{"t":"eq","v":"getConsumYesterday","vt":"str"},{"t":"eq","v":"getConsumMoment","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":475,"y":320,"wires":[["0b3aef0670da6623"],["7c0acb43ca24d493"]],"l":false},{"id":"6ef444455b834e70","type":"time-inject","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"getConsumMoment","nameInt":"07:00 - 23:00 = timestamp ↻60min","positionConfig":"a39cfa79.ae17c8","props":[{"p":"","pt":"msgPayload","v":"","vt":"date","o":"","oT":"none","oM":"60000","f":0,"fS":0,"fT":"UNIX timestamp (ms)","fI":"0","next":true,"days":"","months":"","onlyOddDays":false,"onlyEvenDays":false},{"p":"","pt":"msgTopic","v":"getConsumMoment","vt":"str","o":"","oT":"none","oM":"60000","f":0,"fS":0,"fT":"UNIX timestamp (ms)","fI":"0","next":false,"days":"","months":"","onlyOddDays":false,"onlyEvenDays":false}],"injectTypeSelect":"interval-time","intervalCount":"60","intervalCountType":"num","intervalCountMultiplier":60000,"time":"07:00","timeType":"entered","offset":0,"offsetType":"none","offsetMultiplier":60000,"timeEnd":"23:00","timeEndType":"entered","timeEndOffset":0,"timeEndOffsetType":"none","timeEndOffsetMultiplier":60000,"timeDays":"*","timeOnlyOddDays":false,"timeOnlyEvenDays":false,"timeMonths":"*","timedatestart":"","timedateend":"","property":"","propertyType":"none","propertyCompare":"true","propertyThreshold":"","propertyThresholdType":"num","timeAlt":"","timeAltType":"entered","timeAltDays":"*","timeAltOnlyOddDays":false,"timeAltOnlyEvenDays":false,"timeAltMonths":"*","timeAltOffset":0,"timeAltOffsetType":"none","timeAltOffsetMultiplier":60000,"once":false,"onceDelay":0.1,"recalcTime":2,"x":135,"y":360,"wires":[["d1e84e1ce358b9b9"]],"l":false},{"id":"7c0acb43ca24d493","type":"function","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"preparaMedicion","func":"var jsessionId = flow.get(\"jsessionid\").split(\";\");\nvar jsessionId_0 = flow.get(\"jsessionid_0\").split(\";\");\nmsg.headers = {};\nmsg.headers['Content-Type'] = 'application/json; charset=utf-8';\nmsg.headers['Accept'] = 'application/json; charset=utf-8';\nmsg.headers['User-agent'] =\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/77.0.3865.90 Chrome/77.0.3865.90 Safari/537.36\";\nmsg.headers['cookie'] = jsessionId[0];\nmsg.headers['cookie'] = jsessionId_0[0];\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":555,"y":420,"wires":[["9949c13ca1f81430"]],"l":false},{"id":"9949c13ca1f81430","type":"http request","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"Medicion","method":"GET","ret":"obj","paytoqs":"body","url":"https://www.i-de.es/consumidores/rest/escenarioNew/obtenerMedicionOnline/24","tls":"","persist":false,"proxy":"","authType":"","x":680,"y":420,"wires":[["4191e0aef5d0f17b","ede264a8f90e646e"]]},{"id":"4191e0aef5d0f17b","type":"debug","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":775,"y":380,"wires":[],"l":false},{"id":"ede264a8f90e646e","type":"change","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"extract data from response","rules":[{"t":"set","p":"payload","pt":"msg","to":"{\t \"instantConsum\" : $number(payload.valMagnitud)/1000,\t \"lecturaContador\": $number(payload.valLecturaContador)\t}","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":795,"y":420,"wires":[["ab31557b99366db1","d36ee45ad2a17816"]],"l":false},{"id":"ab31557b99366db1","type":"debug","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":855,"y":380,"wires":[],"l":false},{"id":"7686ace805c8c8ef","type":"function","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"c. mes acumulat","func":"var date = new Date();\nvar firstDay = new Date(date.getFullYear(), date.getMonth(), 1).getTime();\nvar lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0,\"23\",\"59\",\"59\").getTime();\n\n//node.warn(firstDay);\n//node.warn(lastDay);\n\n\nvar query='SELECT sum(\"iberdrolaConsum\") FROM \"electricConsumHores\" WHERE time >= ' + firstDay + 'ms and time <= ' + lastDay +'ms';\n\nmsg.query = query;\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":195,"y":240,"wires":[["5574cd4142bac37a"]],"l":false},{"id":"5574cd4142bac37a","type":"influxdb in","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","influxdb":"e0a9238e.97607","name":"query","query":"","rawOutput":true,"precision":"","retentionPolicy":"","org":"organisation","x":255,"y":240,"wires":[["5d747b21535d13ed"]],"l":false},{"id":"5d747b21535d13ed","type":"change","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","rules":[{"t":"set","p":"#:(file)::cMensualAcumulat","pt":"flow","to":"$round(payload.results[0].series[0].values[0][1],3)","tot":"msg"},{"t":"set","p":"payload","pt":"msg","to":"$formatNumber($round(payload.results[0].series[0].values[0][1],3),'#.###,000', {\"decimal-separator\": \",\",\"grouping-separator\":\".\"})","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":335,"y":240,"wires":[[]],"l":false},{"id":"eaadacf45168f9b5","type":"influxdb out","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","influxdb":"e0a9238e.97607","name":"iberdrolaConsum","measurement":"lecturesInstantContador","precision":"ms","retentionPolicy":"","database":"","retentionPolicyV18Flux":"","org":"","bucket":"","x":955,"y":400,"wires":[],"l":false},{"id":"d36ee45ad2a17816","type":"switch","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"payload empty?","property":"payload","propertyType":"msg","rules":[{"t":"nempty"},{"t":"empty"}],"checkall":"true","repair":false,"outputs":2,"x":875,"y":420,"wires":[["eaadacf45168f9b5","467921d83c47a2ad","c44b13bfb15f1d40"],["4e54022f9e992bce"]],"l":false},{"id":"467921d83c47a2ad","type":"function","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","func":"// Preparem dates\nvar date = new Date();\nvar dateMonth = Number(date.getMonth()) + 1;\nvar dateDayToday = Number(date.getDate());\nvar dateDayYesterday = Number(date.getDate())-1;\nvar dateToday = date.getFullYear() +\"-\"+ dateMonth +\"-\"+ dateDayToday;\nvar dateYesterday = date.getFullYear() +\"-\"+ dateMonth +\"-\"+ dateDayYesterday;\n\n// getFlows\nvar objConsumDia = flow.get(\"consum_\" + dateToday) || {\"instantConsum\":0,\"lecturaContador\":0};\nvar ConsumDiaAcumulat = flow.get(\"ConsumDiaAcumulat\") || 0;\n\nvar ContadorActual = msg.payload.lecturaContador;\n\nif (objConsumDia.instantConsum == 0){\n    // Si es 0, es perque es un nou dia. Intentem el d'ahir\n    objConsumDia = flow.get(\"consum_\" + dateYesterday) || {\"instantConsum\":0,\"lecturaContador\":0};\n    // Resetejem acumulat del dia\n    ConsumDiaAcumulat = 0;\n    // Si no trobem mètrica d'ahir. Ens assegurem de començar de 0.\n    if (objConsumDia.instantConsum == 0) {\n        msg.payload.lecturaContador = 0;\n    }\n}\n\nConsumDiaAcumulat += Number(msg.payload.lecturaContador - objConsumDia.lecturaContador);\n\n\n// Guardem ultim consum\nflow.set(\"consum_\" + dateToday, msg.payload);\nflow.set(\"ConsumDiaAcumulat\", ConsumDiaAcumulat);\n\nmsg.payload=ConsumDiaAcumulat;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":975,"y":440,"wires":[["b9b6331259ae7253"]],"l":false},{"id":"b9b6331259ae7253","type":"debug","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":1015,"y":400,"wires":[],"l":false},{"id":"5ce10976109ddd6c","type":"inject","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"instantConsum\":0.17367,\"lecturaContador\":18340}","payloadType":"json","x":895,"y":500,"wires":[["467921d83c47a2ad"]],"l":false},{"id":"4e54022f9e992bce","type":"delay","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","pauseType":"delay","timeout":"300","timeoutUnits":"seconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"allowrate":false,"outputs":1,"x":755,"y":480,"wires":[["f46ae85a10de3ee3"]],"l":false},{"id":"f46ae85a10de3ee3","type":"change","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"augmenta contadorRetries","rules":[{"t":"set","p":"contadorRetries","pt":"flow","to":"$number($flowContext(\"contadorRetries\"))+1","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":575,"y":480,"wires":[["35ac5da4b90bf43a"]],"l":false},{"id":"35ac5da4b90bf43a","type":"switch","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"check maxRetries","property":"contadorRetries","propertyType":"flow","rules":[{"t":"lte","v":"5","vt":"num"},{"t":"gt","v":"5","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":635,"y":480,"wires":[["7c0acb43ca24d493"],["c44b13bfb15f1d40"]],"l":false},{"id":"c44b13bfb15f1d40","type":"change","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"reset contadorRetries","rules":[{"t":"set","p":"contadorRetries","pt":"flow","to":"0","tot":"num"}],"action":"","property":"","from":"","to":"","reg":false,"x":835,"y":540,"wires":[[]],"l":false},{"id":"c384d358fbabf3e2","type":"comment","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"Limita reintents conexió","info":"","x":515,"y":480,"wires":[],"l":false},{"id":"e5661fee262d28d4","type":"debug","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":585,"y":240,"wires":[],"l":false},{"id":"bd73e700ed66fe6c","type":"switch","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"valores descargados?","property":"payload[0].valores","propertyType":"msg","rules":[{"t":"nnull"},{"t":"null"}],"checkall":"true","repair":false,"outputs":2,"x":795,"y":280,"wires":[["551e454a33c04e55"],["321d4073ba366420"]],"l":false},{"id":"321d4073ba366420","type":"delay","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"1h delay","pauseType":"delay","timeout":"1","timeoutUnits":"hours","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"allowrate":false,"outputs":1,"x":635,"y":340,"wires":[["7800206f915b669a"]],"l":false},{"id":"7800206f915b669a","type":"change","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"timestamp payload","rules":[{"t":"set","p":"topic","pt":"msg","to":"getConsumYesterday","tot":"str"},{"t":"set","p":"payload","pt":"msg","to":"","tot":"date"}],"action":"","property":"","from":"","to":"","reg":false,"x":695,"y":340,"wires":[["be57baf6949dcf59"]],"l":false},{"id":"be57baf6949dcf59","type":"link out","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"electricity consum retry out","links":["e1f7ecba1f2e0f35"],"x":755,"y":340,"wires":[]},{"id":"e1f7ecba1f2e0f35","type":"link in","z":"19980b40dbba5f60","g":"f5be0c89d90593e2","name":"electricity consum retry in","links":["be57baf6949dcf59"],"x":135,"y":320,"wires":[["d1e84e1ce358b9b9"]]},{"id":"e0a9238e.97607","type":"influxdb","hostname":"192.168.1.99","port":"8086","protocol":"http","database":"XXXX","name":"XXXX_DB","usetls":false,"tls":"","influxdbVersion":"1.x"},{"id":"a39cfa79.ae17c8","type":"position-config","name":"YYY","isValide":"true","longitude":"0","latitude":"0","angleType":"deg","timeZoneOffset":"99","timeZoneDST":"0","stateTimeFormat":"3","stateDateFormat":"12"}]

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.