在c#控制台应用程序中,每10秒更新一次api的恒温器结果

本文关键字:一次 api 结果 恒温器 更新 应用程序 控制台 10秒 | 更新日期: 2023-09-27 18:19:09

我需要帮助更新恒温器温度从thingspeak。io API每10秒启动一次。我从thingspeak通道获得JSON数据,并将其转换并显示在控制台中。

这是我到目前为止的代码

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();

现在我想每10秒更新一次这个数据。如果你们中有人能给我指出正确的方向或帮助我修复代码,我将非常感激。

在c#控制台应用程序中,每10秒更新一次api的恒温器结果

一个选择是使用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's a trick:
    Console.Write("'r{0}",DateTime.Now);
}

定时器MSDN文档在这里