在C#控制台应用程序中,每10秒从API更新恒温器结果。

4

我需要帮助从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秒更新一次这个数据。如果你们中的任何人可以指导我正确的方向或帮助我修复代码,我将非常感激。

1个回答

4

一种选择是使用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);
}

Timer MSDN documentation here


嗯,似乎不起作用,或者是我做错了什么 :S - aiden87
你需要一些方式来延迟主线程,以便应用程序不会停止执行。比如使用Console.ReadLine(); 运行上面的代码,它应该能够演示出来。 - Leo Nix
这个可以用。但是它会不断重复并在已显示的状态下显示(如此:http://s15.postimg.org/43vmgn263/Capture.jpg)。是否有任何可能刷新已显示的状态的方法? - aiden87
不能说我能做到那样 :-) 但是非常欢迎你! - Leo Nix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接