public void SetReadSeries(ReceiveItem data, ReceiveItem alarm, ReceiveItem alarmtatus) { try { int index = this.chart1.Series["Series" + data.Name].Points.AddXY(ScadaHexByteOperator.GetDateTime(data.DateTime).Value.ToString("mm:ss"), data.Value); if (data.Value == "-9999") { this.chart1.Series["Series" + data.Name].Points[index].IsEmpty = true; } if (this.chart1.Series["Series" + data.Name].Points.Count > 400) { this.chart1.Series["Series" + data.Name].Points.RemoveAt(0); } if (this.chart1.Series["Series" + data.Name].Points.Count > 0) { if (this.chart1.Series["Series" + data.Name].YAxisType == System.Windows.Forms.DataVisualization.Charting.AxisType.Primary) { this.chart1.ChartAreas[this.chart1.Series["Series" + data.Name].ChartArea].AxisY.Maximum = this.chart1.Series["Series" + data.Name].Points.FindMaxByValue().YValues[0] + this.chart1.Series["Series" + data.Name].Points.FindMaxByValue().YValues[0] / 10.0d; } else { this.chart1.ChartAreas[this.chart1.Series["Series" + data.Name].ChartArea].AxisY2.Maximum = this.chart1.Series["Series" + data.Name].Points.FindMaxByValue().YValues[0] + this.chart1.Series["Series" + data.Name].Points.FindMaxByValue().YValues[0] / 10.0d; } } } catch { } }
/// <summary> /// 获取有效数据,每次获取数据则清空缓存 /// </summary> public List <ReceiveItem> GetItems(int TimeSpan, string Id, string paraName) { List <ReceiveItem> items = new List <ReceiveItem>(); DateTime end = DateTime.Now; DateTime start = DateTime.Now.AddSeconds(-TimeSpan); List <ReceiveItem> selectItems = ReceiveItems.FindAll(x => x.Id.ToString() == Id && ScadaHexByteOperator.GetDateTime(x.DateTime) > start && ScadaHexByteOperator.GetDateTime(x.DateTime) <= end && x.Name == paraName.Trim()); if (OnGeted != null) { OnGeted(selectItems); } return(selectItems); }
/// <summary> /// 发布实时数据 /// </summary> private async static void PublicRealDataJson(string clientid) { logFrm.AddLog("客户端发布数据 " + clientid); if (clientid == null || clientid == "") { return; } if (Config.MQTT.ClientID.Trim().ToLower() != clientid.Trim().ToLower()) { return; } try { if (MqttClient != null && MqttClient.IsConnected) { //构造一个对象 PublicMqttJsonObject publicJsonObject = new PublicMqttJsonObject(); publicJsonObject.device = new PublicMqttJsonDevice() { uid = "1" }; publicJsonObject.paras = new List <PublicMqttJsonPara>(); for (int i = 0; i < Config.Channels.Count; i++) { if (Config.Channels[i].BindingArress.Trim() != "") { foreach (ModbusPara para in Config.ModbusPara) { //获取当前缓存的数据 List <ReceiveItem> channelDatas = ReceiveCachec.GetItems(MqttUpdateCycle, Config.Channels[i].Id.Trim(), para.Name); List <ReceiveItem> channelAlarmDatas = ReceiveAlarmCachec.GetItems(MqttUpdateCycle, Config.Channels[i].Id.Trim(), para.Name); List <ReceiveItem> channelAlarmStatusDatas = ReceiveAlarmStatusCachec.GetItems(MqttUpdateCycle, Config.Channels[i].Id.Trim(), para.Name); //当前缓存最新的数据 ReceiveItem receiveItem = channelDatas.Find(x => int.Parse(x.Address) == int.Parse(Config.Channels[i].BindingArress.Trim())); if (receiveItem != null) { PublicMqttJsonPara paraData = new PublicMqttJsonPara() { name = receiveItem.Name + "_" + int.Parse(Config.Channels[i].Id).ToString() + "_" + int.Parse(receiveItem.Address).ToString(), data = new List <object>() { receiveItem.DateTime, receiveItem.Value, receiveItem.Unit }, }; publicJsonObject.paras.Add(paraData); } //报警值 ReceiveItem receiveAlarmItem = channelAlarmDatas.Find(x => int.Parse(x.Address) == int.Parse(Config.Channels[i].BindingArress.Trim())); if (receiveAlarmItem != null) { PublicMqttJsonPara paraData = new PublicMqttJsonPara() { name = receiveAlarmItem.Name + "_" + int.Parse(Config.Channels[i].Id).ToString() + "_" + int.Parse(receiveAlarmItem.Address).ToString() + "_alarm", data = new List <object>() { receiveAlarmItem.DateTime, receiveAlarmItem.Value, receiveAlarmItem.Unit } }; publicJsonObject.paras.Add(paraData); } ; //报警值 ReceiveItem receiveAlarmStatusItem = channelAlarmStatusDatas.Find(x => int.Parse(x.Address) == int.Parse(Config.Channels[i].BindingArress.Trim())); if (receiveAlarmStatusItem != null) { PublicMqttJsonPara paraData = new PublicMqttJsonPara() { name = receiveAlarmStatusItem.Name + "_" + int.Parse(Config.Channels[i].Id).ToString() + "_" + int.Parse(receiveAlarmItem.Address).ToString() + "_status", data = new List <object>() { receiveAlarmStatusItem.DateTime, receiveAlarmStatusItem.Value, receiveAlarmStatusItem.Unit } }; publicJsonObject.paras.Add(paraData); } ; } } } string json = ScadaHexByteOperator.ObjectToJson(publicJsonObject); //发布订阅的数据 await MqttClient.PublishAsync(new MqttApplicationMessage() { Payload = Encoding.UTF8.GetBytes(json), QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, Retain = false, Topic = Config.MQTT.DataPublicTopic }); } } catch (Exception emx) { logFrm.AddLog(emx.Message); return; } }
private async static void CreateMqttClient() { try { string cleintID = Config.MQTT.ClientID.Trim(); var options = new MqttClientOptions() { ClientId = cleintID }; options.ChannelOptions = new MqttClientTcpOptions() { Server = Config.MQTT.ServerIP.Trim(), Port = Convert.ToInt32(Config.MQTT.Port) }; options.Credentials = new MqttClientCredentials() { Username = Config.MQTT.Account.Trim(), Password = Config.MQTT.Password.Trim() }; options.CleanSession = true; options.KeepAlivePeriod = TimeSpan.FromSeconds(100.5); options.KeepAliveSendInterval = TimeSpan.FromSeconds(20000); if (null != MqttClient) { await MqttClient.DisconnectAsync(); MqttClient = null; } MqttClient = new MqttFactory().CreateMqttClient(); ///接收到数据 MqttClient.ApplicationMessageReceived += (sender, args) => { if (args.ClientId == null || args.ClientId == "") { return; } if (args.ApplicationMessage.Payload == null || args.ApplicationMessage.Payload.Length <= 0) { return; } if (args.ApplicationMessage.Topic.Trim() == Config.MQTT.PassiveSubTopic.Trim()) { Task.Run(() => { ///获取当前的json字符串 string json = args.ApplicationMessage.ConvertPayloadToString(); //将json对象转换为c#对象 MQTTPassiveSubTopicObject subTopicObject = ScadaHexByteOperator.JsonToObject <MQTTPassiveSubTopicObject>(json); logFrm.AddLog("服务器请求发布数据"); if (subTopicObject != null) { PublicRealDataJson(args.ClientId);//发布一次数据 } }); } else if (args.ApplicationMessage.Topic.Trim() == Config.MQTT.UpdateCycleSubTopic.Trim())//用户上位机读取数据的间隔,是秒 { Task.Run(() => { ///获取当前的json字符串 string json = args.ApplicationMessage.ConvertPayloadToString(); //将json对象转换为c#对象 MQTTPassiveSubTopicObject subTopicObject = ScadaHexByteOperator.JsonToObject <MQTTPassiveSubTopicObject>(json); if (subTopicObject != null) { logFrm.AddLog("服务器循环周期更新 更新周期" + subTopicObject.updatecycle); //修改客户端数据查询周期 MqttUpdateCycle = subTopicObject.updatecycle; } }); } else if (args.ApplicationMessage.Topic.Trim() == Config.MQTT.CommandSubTopic.Trim())//用户上位机下置数据 { //解析数据 } }; MqttClient.Connected += (sender, args) => { logFrm.AddLog("连接MQTT服务器成功"); MqttClient.SubscribeAsync(Config.MQTT.CommandSubTopic, MqttQualityOfServiceLevel.AtMostOnce); //服务器端下置命令的主题 if (Config.MQTT.PublicType == "被动") //一个被动订阅的主题 { Task.Run(() => { MqttClient.SubscribeAsync(Config.MQTT.UpdateCycleSubTopic, MqttQualityOfServiceLevel.AtMostOnce); //服务器端设置了更新数据周期后通知到客户端 MqttClient.SubscribeAsync(Config.MQTT.PassiveSubTopic, MqttQualityOfServiceLevel.AtMostOnce); //被动订阅循环主题 }); } else if (Config.MQTT.PublicType == "主动")//一个被动订阅的主题 { Task.Run(() => { while (true) { if (MqttClient.IsConnected) { PublicRealDataJson(cleintID); } Thread.Sleep(MqttUpdateCycle * 1000); } }); } }; MqttClient.Disconnected += async(sender, args) => { Thread.Sleep(30000);//30秒后尝试重连 try { await MqttClient.ConnectAsync(options); logFrm.AddLog("连接MQTT服务器成功"); } catch (Exception emx) { logFrm.AddLog(emx.Message); } }; try { await MqttClient.ConnectAsync(options); logFrm.AddLog("连接MQTT服务器成功"); } catch (Exception emx) { logFrm.AddLog(emx.Message); } } catch (Exception emx) { logFrm.AddLog(emx.Message); return; } }
/// <summary> /// 传入读取的数据,data, 报警 alarm,报警状态 ,alarmstatus /// </summary> /// <param name="data"></param> /// <param name="alarm"></param> /// <param name="alarmStatu"></param> public void SetReadData(ReceiveItem data, ReceiveItem alarm, ReceiveItem alarmtatus) { ChannelAlarm channelAlarm = GasMonitorManager.Config.ChannelAlarms.Find(x => int.Parse(x.ChanelID) == int.Parse(this.Channel.Id)); uledTime.Text = ScadaHexByteOperator.GetDateTime(data.DateTime).Value.ToString("HH:mm:ss"); ///设置值 switch (data.Name) { case "CO": uledCO.Text = data.Value.ToString(); uslabCO.Text = data.Name + "/" + data.Unit; //系统报警优先 if (alarmtatus.Value.ToString() == "0") //无报警 { uledbubCO.Color = Color.Green; uiLedAlarmCO.Text = ""; } else if (alarmtatus.Value.ToString() == "1") //低报警 { uledbubCO.Color = Color.Yellow; uiLedAlarmCO.Text = alarm.Value.ToString(); } else if (alarmtatus.Value.ToString() == "2") //高报警 { uledbubCO.Color = Color.Red; uiLedAlarmCO.Text = alarm.Value.ToString(); } //设置曲线 if (channelAlarm != null) { ParaAlarm paraAlarm = channelAlarm.ParaAlarms.Find(x => x.Name.Trim().ToUpper() == "CO" && x.Enable == "1"); //表示系统报警开启 if (paraAlarm != null) { float high = Convert.ToSingle(paraAlarm.High); float low = Convert.ToSingle(paraAlarm.Low); float v = Convert.ToSingle(data.Value); if (v <= low) { uledbubCO.Color = Color.Yellow; uiLedAlarmCO.Text = alarm.Value.ToString(); } else if (v >= high) { uledbubCO.Color = Color.Red; uiLedAlarmCO.Text = alarm.Value.ToString(); } } } break; case "EX": uledEX.Text = data.Value.ToString(); uslabEX.Text = data.Name + "/" + data.Unit; if (alarmtatus.Value.ToString() == "0") //无报警 { uledbubEX.Color = Color.Green; uiLedAlarmEX.Text = ""; } else if (alarmtatus.Value.ToString() == "1") //低报警 { uledbubEX.Color = Color.Yellow; uiLedAlarmEX.Text = alarm.Value.ToString(); } else if (alarmtatus.Value.ToString() == "2") //高报警 { uledbubEX.Color = Color.Red; uiLedAlarmEX.Text = alarm.Value.ToString(); } if (channelAlarm != null) { ParaAlarm paraAlarm = channelAlarm.ParaAlarms.Find(x => x.Name.Trim().ToUpper() == "EX" && x.Enable == "1"); if (paraAlarm != null) { //表示系统报警开启 float high = Convert.ToSingle(paraAlarm.High); float low = Convert.ToSingle(paraAlarm.Low); float v = Convert.ToSingle(data.Value); if (v <= low) { uledbubEX.Color = Color.Yellow; uiLedAlarmEX.Text = alarm.Value.ToString(); } else if (v >= high) { uledbubEX.Color = Color.Red; uiLedAlarmEX.Text = alarm.Value.ToString(); } } } break; case "H2S": uledH2S.Text = data.Value.ToString(); uslabH2S.Text = data.Name + "/" + data.Unit; if (alarmtatus.Value.ToString() == "0") //无报警 { uledbubH2S.Color = Color.Green; uiLedAlarmH2S.Text = ""; } else if (alarmtatus.Value.ToString() == "1") //低报警 { uledbubH2S.Color = Color.Yellow; uiLedAlarmH2S.Text = alarm.Value.ToString(); } else if (alarmtatus.Value.ToString() == "2") //高报警 { uledbubH2S.Color = Color.Red; uiLedAlarmH2S.Text = alarm.Value.ToString(); } if (channelAlarm != null) { ParaAlarm paraAlarm = channelAlarm.ParaAlarms.Find(x => x.Name.Trim().ToUpper() == "H2S" && x.Enable == "1"); //表示系统报警开启 if (paraAlarm != null) { float high = Convert.ToSingle(paraAlarm.High); float low = Convert.ToSingle(paraAlarm.Low); float v = Convert.ToSingle(data.Value); if (v <= low) { uledbubH2S.Color = Color.Yellow; uiLedAlarmH2S.Text = alarm.Value.ToString(); } else if (v >= high) { uledbubH2S.Color = Color.Red; uiLedAlarmH2S.Text = alarm.Value.ToString(); } } } break; case "O2": uledO2.Text = data.Value.ToString(); uslabO2.Text = data.Name + "/" + data.Unit; if (alarmtatus.Value.ToString() == "0") //无报警 { uledbubO2.Color = Color.Green; uiLedAlarmO2.Text = ""; } else if (alarmtatus.Value.ToString() == "1") //低报警 { uledbubO2.Color = Color.Yellow; uiLedAlarmO2.Text = alarm.Value.ToString(); } else if (alarmtatus.Value.ToString() == "2") //高报警 { uledbubO2.Color = Color.Red; uiLedAlarmO2.Text = alarm.Value.ToString(); } if (channelAlarm != null) { ParaAlarm paraAlarm = channelAlarm.ParaAlarms.Find(x => x.Name.Trim().ToUpper() == "H2S" && x.Enable == "1"); //表示系统报警开启 if (paraAlarm != null) { float high = Convert.ToSingle(paraAlarm.High); float low = Convert.ToSingle(paraAlarm.Low); float v = Convert.ToSingle(data.Value); if (v <= low) { uledbubO2.Color = Color.Yellow; uiLedAlarmO2.Text = alarm.Value.ToString(); } else if (v >= high) { uledbubO2.Color = Color.Red; uiLedAlarmO2.Text = alarm.Value.ToString(); } } } break; } if (!string.IsNullOrEmpty(data.Value) && data.Value != "-9999") { uiLedDeviceStatus.Color = Color.Green; } int index = this.chart1.Series["Series" + data.Name].Points.AddXY(ScadaHexByteOperator.GetDateTime(data.DateTime).Value.ToString("mm:ss"), data.Value); if (data.Value == "-9999") { this.chart1.Series["Series" + data.Name].Points[index].IsEmpty = true; } if (this.chart1.Series["Series" + data.Name].Points.Count > 200) { this.chart1.Series["Series" + data.Name].Points.RemoveAt(0); } if (this.chart1.Series["Series" + data.Name].Points.Count > 0) { if (this.chart1.Series["Series" + data.Name].YAxisType == System.Windows.Forms.DataVisualization.Charting.AxisType.Primary) { this.chart1.ChartAreas[this.chart1.Series["Series" + data.Name].ChartArea].AxisY.Maximum = this.chart1.Series["Series" + data.Name].Points.FindMaxByValue().YValues[0] + this.chart1.Series["Series" + data.Name].Points.FindMaxByValue().YValues[0] / 10.0d; } else { this.chart1.ChartAreas[this.chart1.Series["Series" + data.Name].ChartArea].AxisY2.Maximum = this.chart1.Series["Series" + data.Name].Points.FindMaxByValue().YValues[0] + this.chart1.Series["Series" + data.Name].Points.FindMaxByValue().YValues[0] / 10.0d; } } }