Updating thermostat result from api every 10 seconds in c # console application

I need help updating the thermostat temperature in the thingspeak.io API every 10 seconds. I get JSON data from thingspeak channel and I convert it and display it on the console.

This is my code so far

string url = "http://api.thingspeak.com/channels/135/feed.json";

WebClient webClient = new WebClient();
var data = webClient.DownloadString(url);
dynamic feed = JsonConvert.DeserializeObject<dynamic>(data);
List<dynamic> feeds = feed.feeds.ToObject<List<dynamic>>();
string field1 = feeds.Last().field1;
float temperature = float.Parse(field1, CultureInfo.InvariantCulture);

Console.WriteLine("----------CURRENT CHANNEL----------");
Console.WriteLine("\n");
Console.WriteLine("Channel name: " + feed.channel.name);
Console.WriteLine("Temperature: " + temperature.ToString() + " °C");
Console.WriteLine("\n");

int trenutna_temp = Convert.ToInt32(temperature);

Console.WriteLine("----------DEVICES----------");

if (trenutna_temp < 10)
{
    Console.WriteLine("turn on heating);
}
else if (trenutna_temp > 10 && trenutna_temp < 20)
{
    Console.WriteLine("turn off");
}
else if (trenutna_temp > 20)
{
    Console.WriteLine("Turn on cooling");
}
Console.ReadLine();

Now I would like to update this data every 10 seconds. I would really appreciate it if any of you guys could point me in the right direction or help me fix the code.

+4
source share
1 answer

One option is to use System.Threading.Timer:

public static void Main() 
{  
   System.Threading.Timer t = new System.Threading.Timer(UpdateThermostat, 5, 0, 2000); //10 times 1000 miliseconds
   Console.ReadLine();
   t.Dispose(); // dispose the timer
}


private static void UpdateThermostat(Object state) 
{ 
   // your code to get your thermostat
   //option one to print on the same line:
   //move the cursor to the beginning of the line before printing:
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(DateTime.Now);

   //option two to print on the same line:
   //printing "\r" moves cursor back to the beginning of the line so it a trick:
    Console.Write("\r{0}",DateTime.Now);
}

MSDN timer documentation here

+4
source

Source: https://habr.com/ru/post/1613034/


All Articles