之前采集、推送周期都是写死的
现在就是新增一个需求,需要能够配置采集时间,比如我想1s采集一次,5s采集一次或者1分钟采集一次,然后定时推送也是,如此,我想设置推送的时间;
还有定时推送和变化推送功能我可以配置是否开启关闭,有时候我只需要一种推送功能即可
这样我们就可以在配置中增加这几个个参数
在设备配置类中增加采集周期
public class DeviceLink
{
//...
/// <summary>
/// 采集周期 单位:s
/// </summary>
public double AcqTimeSpan {
get; set; }
}
增加一个服务配置类
增加推送周期,这里默认最小推送周期就是1s,所以用int;
增加定时推送和变化推送功能开关,用于配置功能的可用
public class ServiceConfig
{
/// <summary>
/// 推送周期,单位:s
/// </summary>
public int PushTimeSpan {
get; set; }
/// <summary>
/// 是否定时推送
/// </summary>
public bool IsPushScheduled {
get; set; }
/// <summary>
/// 是否变化推送
/// </summary>
public bool IsPushChanged {
get; set; }
}
在总的配置中,添加服务配置
扫描二维码关注公众号,回复:
17450575 查看本文章
![](/qrcode.jpg)
在配置文件中同步修改
{
"DeviceLink": {
"UID": "device01",
"Ip": "127.0.0.1",
"Port": 502,
"SlaveId": 1,
"AcqTimeSpan": 1
},
"MqttConfig": {
"Ip": "127.0.0.1",
"Port": 1883,
"Username": "admin",
"Password": "12345"
},
"ServiceConfig": {
"PushTimeSpan": 5,
"IsPushScheduled": true,
"IsPushChanged": true
}
}
在服务中使用
都需要×1000转换成毫秒
public DAqService(DAqOption option)
{
_option = option;
deviceLink = option.DeviceLink;
points = option.Points;
timer = new System.Timers.Timer(_option.PushTimeSpan * 1000);//修改为配置值
timer.Elapsed += Timer_Elapsed;
}
在modbustcp中使用
需要定义一个变量,将其转换成毫秒
private int _timeSpan = 1000;
public ModbusTcp(DeviceLink link, List<RegisterPoint> registers)
{
//...
_timeSpan = (int)(link.AcqTimeSpan * 1000);
}
/// <summary>
/// 启动主采集线程,循环采集
/// </summary>
public void DoMonitor()
{
Task.Run(() =>
{
//防止重复启动
if (IsMonitored)
return;
IsMonitored = true;
while (true)
{
//...
Task.Delay(_timeSpan).Wait();
}
});
}