0
Answered

Get json with http request and parse

Nikolay Rusanov 7 years ago in iRidium Script updated by Aleksandr Romanov (CTO) 7 years ago 5

I need to parse weather data which i get in json format as response to this url: http://api.openweathermap.org/data/2.5/weather?q=Moscow,Russia&units=metric&appid=072808c7b054b6b21a549dbbb3c936c0


(you can try)


Could anyone please point me to an example of how to get that in iridium script and then set 'temp':23.1 to a chanel value.


Thank you!

+1
IR.AddListener(IR.EVENT_START,0,function()
{
   pWther.request(function(resp) {
      try {
         if (resp.main.temp !== undefined) {
            IR.Log("TEMPERATURE is " + resp.main.temp);
            //IR.Log(typeof resp.main.temp)
            //IR.GetDevice("HDL-BUS Pro Network (UDP)").Set("HVAC:temp", resp.main.temp); //type conversion warring!
         }
      } catch (e) {
         IR.Log("Something is wrong \n" + e); // error handler 
      } 
   });
});
var pWther  = {};
pWther.dev = IR.CreateDevice(IR.DEVICE_CUSTOM_HTTP_TCP, "pWeather", "api.openweathermap.org", 80);
pWther.request = function(in_callback){
      pWther.dev.SetParameters({ConnectWaitTimeMax: 5000, ReceiveWaitTimeMax: 10000});
      pWther.dev.Connect(); // Must be
        pWther.dev.SendEx({
            Type: "GET",
            Url: "/data/2.5/weather?q=Moscow,Russia&units=metric&appid=072808c7b054b6b21a549dbbb3c936c0",
            /*Headers: {
            "Content-Type": "application/json"
            },*/
            cbReceiveText: function(text, code, headers) {
            if (code != 200) return; //parse other error codes!
                var resp = JSON.Parse(text);
            //IR.Log(text); 
            pWther.dev.Disconnect();            
            in_callback(resp);            
            },
        });
   }

(tvoyu'j mat')


Thank you very much, tomorrow I'll try this one. Not as simple as I thought it would be!

I need it to be checked periodically


Should I use something like    IR.SetInterval(20000,in_callback(resp));?