private void 除ToolStripMenuItem_Click(object sender, EventArgs e) { if (this.listView1.SelectedItems.Count > 0) { //if (MessageBox.Show("是否删除该通讯设备类型?") == DialogResult.OK) if (MessageBox.Show("确定要删除该通讯设备类型吗?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { if (this.listView1.SelectedItems[0].Tag is CommunicateDeviceType) { var communicateDeviceType = this.listView1.SelectedItems[0].Tag as CommunicateDeviceType; var id = communicateDeviceType.ID; List <CommunicateDevice> communicateDeviceList = CommunicateDevice.FindAllByCommunicateDeviceTypeID(id); if (communicateDeviceList != null) { MessageBox.Show("该设备类型已经在使用,不能删除"); return; } CommunicateDeviceType.Delete(communicateDeviceType); this.InitCommunicateDeviceTypeListView(); this .communicateDeviceTypeId = 0; } } } }
private void Display() { CommunicateDevice.FindAllWithCache().ForEach(com => { com.ShowDevices.ForEach(showDevice => { var cardType = showDevice.ShowDeviceType; var ledType = LedDeviceFactory.GetLedDeviceType(cardType.Name); ILedDevice ledDevice = LedDeviceFactory.CreateLedDevice(ledType); if (ledDevice != null) { try { var host = com.Args1; var args = Convert.ToInt32(com.Args2); ledDevice.Init(host, args); var maxPosition = 0; var messageList = showDevice.ShowDatas.ToList() .Select(sd => { var dev = sd.SensorDeviceUnit; var position = sd.Position; var info = dev.ShowValue; if (info == "负无穷大") { info = ""; } if (dev.Sensor.Name.Contains("雨雪")) { info = dev.ProcessedValue == 1M ? "有" : "无"; } if (dev.Sensor.Name.Contains("风向")) { info = JudgWindDirection(dev.ProcessedValue); dev.Sensor.Unit = ""; //发送到屏幕上去除风向的单位 } if (position > maxPosition) { maxPosition = position; } return(new Tuple <int, string>(position, string.Format("{0}:{1}{2}", dev.Name, info, dev.Sensor.Unit))); }).ToList(); if (!Setting.Current.LedAttactInfo.IsNullOrWhiteSpace()) { messageList.Add(new Tuple <int, string>(maxPosition + 1, Setting.Current.LedAttactInfo)); } ledDevice.Display(messageList); ServiceLogger.Current.WriteDebugLog("LED发送成功,{0}:{1}", com.Args1, com.Args2); } catch (Exception ex) { ServiceLogger.Current.WriteError("发送LED失败," + ex.Message); ServiceLogger.Current.WriteException(ex); } } }); }); }
private void advPropertyGrid1_PropertyValueChanging(object sender, PropertyValueChangingEventArgs e) { //var item = GetObjAndField(e.PropertyPath); //var obj= item.Item1; //var propertyName = item.Item2; if (e.PropertyName.EqualIgnoreCase("ModularDevices")) { var ModularDeviceID = ModularDevice.FindAllByName(e.NewValue.ToString())[0].ID; selectObj.Item1.SetItem("ModularDeviceID", ModularDeviceID); } else if (e.PropertyName.EqualIgnoreCase("Sensors")) { var SensorId = Sensor.FindAllByName("name", e.NewValue, null, 0, 0)[0].ID; selectObj.Item1.SetItem("SensorId", SensorId); } else if (e.PropertyName.EqualIgnoreCase("ControlJobTypes")) { var ControlJobTypeId = ControlJobType.FindAllByName("name", e.NewValue, null, 0, 0)[0].Id; selectObj.Item1.SetItem("ControlJobTypeId", ControlJobTypeId); } else if (e.PropertyName.EqualIgnoreCase("RelayTypes")) { var RelayTypeId = RelayType.FindAllByName("name", e.NewValue, null, 0, 0)[0].Id; selectObj.Item1.SetItem("RelayTypeId", RelayTypeId); } else if (e.PropertyName.EqualIgnoreCase("DeviceTypes")) { var DeviceTypeSerialnum = DeviceType.FindAllByName("name", e.NewValue, null, 0, 0)[0].Serialnum; selectObj.Item1.SetItem("DeviceTypeSerialnum", DeviceTypeSerialnum); } else if (e.PropertyName.EqualIgnoreCase("ShowDeviceTypes")) { var ShowDeviceTypeID = ShowDeviceType.FindAllByName("name", e.NewValue, null, 0, 0)[0].ID; selectObj.Item1.SetItem("ShowDeviceTypeID", ShowDeviceTypeID); } else if (e.PropertyName.EqualIgnoreCase("CommunicateDevices")) { var CommunicateDeviceID = CommunicateDevice.FindAllByName("name", e.NewValue, null, 0, 0)[0].ID; selectObj.Item1.SetItem("CommunicateDeviceID", CommunicateDeviceID); } else if (e.PropertyName.EqualIgnoreCase("Farms")) { var FarmID = Farm.FindAllByName("name", e.NewValue, null, 0, 0)[0].ID; selectObj.Item1.SetItem("FarmID", FarmID); } else if (e.PropertyName.EqualIgnoreCase("FacilityTypes")) { var FacilityTypeSerialnum = FacilityType.FindAllByName("name", e.NewValue, null, 0, 0)[0].Serialnum; selectObj.Item1.SetItem("FacilityTypeSerialnum", FacilityTypeSerialnum); } else { selectObj.Item1.SetItem(e.PropertyName, e.NewValue); } }
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { var types = CommunicateDevice.FindAll(); var names = new ArrayList(); if (types != null && types.Count > 0) { names.AddRange(types); } return(new StandardValuesCollection(names)); }
/// <summary> /// 初始化通讯设备 /// </summary> private void InitCommunicateDevice() { List <CommunicateDevice> communicateDeviceList = CommunicateDevice.FindAll(); //foreach (var communicateDevice in communicateDeviceList) //{ // this.cbCommunicateDevice.Items.Add(communicateDevice); // this.cbCommunicateDevice.DisplayMember = communicateDevice.ID.ToString(); // this.cbCommunicateDevice.ValueMember = communicateDevice.Name; //} if (communicateDeviceList.Count > 0) { this.cbCommunicateDevice.DataSource = communicateDeviceList; this.cbCommunicateDevice.DisplayMember = "Name"; this.cbCommunicateDevice.ValueMember = "ID"; } }
/// <summary> /// 创建所有的通讯会话 /// </summary> private void CreateAllTransport() { var devices = CommunicateDevice.FindAll(); devices.ForEach(dev => { //dynamic args = new ExpandoObject(); //args.Args1 = dev.Args1; //args.Args2 = dev.Args2; //var type = (TransportEnum)Enum.Parse(typeof(TransportEnum), dev.CommunicateDeviceTypeName); //TransportFactory.CreateTransport(args, type); string key = "{0}://{1}:{2}".F(dev.CommunicateDeviceTypeName, dev.Args1, dev.Args2); //string key = "{0}://{1}:{2}".F(dev.CommunicateDeviceTypeName, "192.168.0.233", "10001"); TransportFactory.GetTransport(key); ServiceLogger.Current.WriteDebugLog("创建通讯 {0}", key); }); }
/// <summary> /// 初始化通讯设备列表 /// </summary> private void InitCommunicateDeviceListView() { this.listView1.Items.Clear(); List <CommunicateDevice> communicateDeviceList = CommunicateDevice.FindAll(); foreach (var communicateDevice in communicateDeviceList) { var strings = new string[] { communicateDevice.ID.ToString(), communicateDevice.Name, communicateDevice.CommunicateDeviceTypeName, communicateDevice.Args1, communicateDevice.Args2, communicateDevice.Args3, communicateDevice.Args4, communicateDevice.Args5, communicateDevice.OnlineStatus.ToString(), communicateDevice.Exception, communicateDevice.Remark }; var listViewItem = new ListViewItem(strings); listViewItem.Tag = communicateDevice; this.listView1.Items.Add(listViewItem); } }
private void Display() { CommunicateDevice.FindAllWithCache().ForEach(com => { ///判断一下是否为TTS设备。。。 TransportTypeEnum type; if (!TransportTypeEnum.TryParse(com.CommunicateDeviceTypeName, true, out type)) { type = TransportTypeEnum.Unknow; } var host = com.Args1; var e = Convert.ToInt32(com.Args2); var timeout = Convert.ToInt32(com.Args3); //获取Transport var transport = TransportFactory.GetTransport(type, host, e, timeout); var kdxf = new KdxfDevice(transport); com.ShowDevices.ForEach(showDevice => { var devices = showDevice.ShowDatas.ToList().Select(sd => sd.SensorDeviceUnit); devices.ForEach(dev => { var message = "{0} {1} {2} {3}".F("", dev.Name, dev.ShowValue, dev.Sensor.Unit); var result = kdxf.Display(message); if (result) { ServiceLogger.Current.WriteDebugLog("播报成功"); } else { ServiceLogger.Current.WriteError("语音播报失败:{0}", message); } }); }); }); }
/// <summary> /// 采集控制设备状态 /// </summary> private static void Collect() { CommunicateDevice.FindAllWithCache().ForEach(com => { var key = "{0}://{1}:{2}".F(com.CommunicateDeviceTypeName, com.Args1, com.Args2); TransportTypeEnum type; if (!Enum.TryParse(com.CommunicateDeviceTypeName, true, out type)) { type = TransportTypeEnum.Unknow; } var host = com.Args1; var e = Convert.ToInt32(com.Args2); var timeout = Convert.ToInt32(com.Args3); //获取Transport var transport = TransportFactory.GetTransport(type, host, e, timeout); if (transport != null) { var modulars = com.ModularDevices; if (modulars != null && modulars.Count > 0) { modulars.ForEach(modular => { var controlDevices = modular.ControlDeviceUnits; if (controlDevices != null && controlDevices.Count > 0) { var dataType = modular.ProtocalTypeName; if (dataType.EqualIgnoreCase(ProtocalTypeEnum.MODBUS.ToString())) { var modbusControlDevice = new ModbusControlDevice(transport, Convert.ToByte(modular.Address)) { Registers = controlDevices.ToList().SelectMany(controlDeviceUnit => { var addrs = new List <int> { Convert.ToInt32(controlDeviceUnit.RegisterAddress1) }; //添加第一个 //如果是组合设备添加第二个 //if (controlDeviceUnit.IsComposite) // addrs.Add(Convert.ToInt32(controlDeviceUnit.RegisterAddress2)); return(addrs); }).ToList() }; //读数据,重试三次 var result = false; for (var i = 0; i < 3; i++) { try { modbusControlDevice.EnsureTransport(transport); result = modbusControlDevice.Read(); break; } catch (ObjectDisposedException odx) { LogHelper.Fatal(odx.ToString()); //重新构建transport transport = TransportFactory.GetTransport(type, host, e, timeout); } catch (Exception ex) { LogHelper.Fatal(ex.ToString()); } LogHelper.Debug("第{3}次读取{0}:{1}地址为{2}数据失败", host, e, modular.Address, (i + 1)); } if (result) { //处理设备状态 //保存到数据库 var minReg = modbusControlDevice.Registers.Min(); controlDevices.ForEach(controlDevice => { var regAddr = Convert.ToInt32(controlDevice.RegisterAddress1); var value1 = modbusControlDevice.Values.Skip(regAddr - minReg).Take(1).ElementAt(0); var value = 0; //控制设备当前状态 //if (controlDevice.IsComposite) //{ // var regAddr2 = Convert.ToInt32(controlDevice.RegisterAddress1); // var value2 = modbusControlDevice.Values.Skip(regAddr2 - minReg).Take(1).ElementAt(0); // //controlDevice.OriginalValue = (value1 << 8) + value2; // if (value1 && !value2) // { // value = 0xFF00; // controlDevice.ProcessedValue = "正转"; // } // else if (!value1 && value2) // { // value = 0; // controlDevice.ProcessedValue = "停止"; // } // else if (!value1 && !value2) // { // value = 0X00FF; // controlDevice.ProcessedValue = "反转"; // } //} //else //{ value = value1 ? 1 : 0; //} controlDevice.OriginalValue = value; controlDevice.ProcessedValue = CalcControlDeviceValue.CalcProcessValue( controlDevice.FacilityControlDeviceUnits[0]); controlDevice.UpdateTime = DateTime.Now; controlDevice.Save(); //执行控制 //bool success= control(value,controldevice.id); // if(success) // { // servicelogger.current.writelog("设备控制成功"); // } // else // { // servicelogger.current.writeerror("设备控制失败"); // } }); } else { LogHelper.Error("读取设备控制数据失败"); } } } }); } } else { //通讯对象创建失败 LogHelper.Error("无法创建通讯{0}", key); } }); }
private static void Collect() { #if DEBUG var sw = new Stopwatch(); sw.Start(); #endif var batchNo = DateTime.Now.ToString("yyyyMMddHHmm"); CommunicateDevice.FindAll().ForEach(com => { //var key = "{0}://{1}:{2}-{3}".F(com.CommunicateDeviceTypeName, com.Args1, com.Args2, com.Args3); TransportTypeEnum type; if (!Enum.TryParse(com.CommunicateDeviceTypeName, true, out type)) { type = TransportTypeEnum.Unknow; } var host = com.Args1; var e = Convert.ToInt32(com.Args2); var timeout = Convert.ToInt32(com.Args3); //获取Transport var transport = TransportFactory.GetTransport(type, host, e, timeout); var modulars = com.ModularDevices; if (modulars != null && modulars.Count > 0) { modulars.ForEach(modular => { var deviceUnits = modular.SensorDeviceUnits; if (deviceUnits != null && deviceUnits.Count > 0) { //按Function分组 deviceUnits.ToList().GroupBy(s => s.Function).ToList().ForEach(functionGp => { var function = functionGp.Key; var dataType = modular.ProtocalTypeName; if (!dataType.EqualIgnoreCase(ProtocalTypeEnum.MODBUS.ToString())) { return; } var modbusFunction = (MBFunction)Convert.ToByte(function); var collectDevice = new ModbusCollectDevice(transport, Convert.ToByte(modular.Address), modbusFunction) { Registers = functionGp.ToList().SelectMany(deviceUnit => { var start = Convert.ToInt32(deviceUnit.RegisterAddress); var count = deviceUnit.RegisterSize; var addrs = Enumerable.Range(start, count); return(addrs); }).ToList() }; var result = false; try { collectDevice.EnsureTransport(transport); result = collectDevice.Read(); while (!result) { collectDevice.EnsureTransport(transport); result = collectDevice.Read(); if (result == true) { break; } } } catch (ObjectDisposedException odx) { LogHelper.Fatal(odx.ToString()); //重新构建transport transport = TransportFactory.GetTransport(type, host, e, timeout); } catch (Exception ex) { LogHelper.Fatal(ex.ToString()); } //读数据,重试三次 //for (var i = 0; i < 3; i++) //{ // try // { // collectDevice.EnsureTransport(transport); // result = collectDevice.Read(); // break; // } // catch (ObjectDisposedException odx) // { // ServiceLogger.Current.WriteException(odx); // //重新构建transport // transport = TransportFactory.GetTransport(type, host, e, timeout); // } // catch (Exception ex) // { // ServiceLogger.Current.WriteException(ex); // } // ServiceLogger.Current.WriteWarn("第{3}次读取{0}:{1}地址为{2}数据失败", host, e, modular.Address, (i + 1)); //} if (result) { //保存到数据库 var minReg = collectDevice.Registers.Min(); functionGp.ToList().ForEach(deviceUnit => { var regAddr = Convert.ToInt32(deviceUnit.RegisterAddress); var size = deviceUnit.RegisterSize; //根据起始地址和数量计算出数值 var value = collectDevice.Values.Skip(regAddr - minReg) .Take(size) .Sum(Convert.ToInt32); //判断是否为负数,负数取反+1,气象站温度使用 if ((value & 0x8000) > 0) { //此传感器值为负数,需特殊处理 var val = ~(Convert.ToInt16(value & 0x7fff)) & 0x7fff; value = Convert.ToInt16(val + 1) * (-1); } //根据传感器的计算公式,转换成实际值 var sensor = deviceUnit.Sensor; if (sensor != null) { var compute = sensor.ValueComputeString; var processValue = ComputeHelper.CalcValue(compute, value, sensor.Accuracy); deviceUnit.OriginalValue = value; //异常数据显示处理 //Random random = new Random(DateTime.Now.Millisecond); //if(processValue>deviceUnit.Sensor.ExperienceMax&& // processValue<deviceUnit.Sensor.ExperienceMin) //{ // //deviceUnit.ProcessedValue = random.Next(Convert.ToInt32(processValue), Convert.ToInt32(processValue +2));//随机范围为上次处理值左右 // deviceUnit.ProcessedValue = processValue; // deviceUnit.ShowValue = sensor.ValueComputeString.IsNullOrWhiteSpace() // ? deviceUnit.ProcessedValue.ToString() // : ComputeHelper.CalcString(sensor.ValueComputeString, value); //} deviceUnit.ProcessedValue = processValue; deviceUnit.ShowValue = sensor.ValueComputeString.IsNullOrWhiteSpace() ? deviceUnit.ProcessedValue.ToString(CultureInfo.InvariantCulture) : ComputeHelper.CalcString(sensor.ValueComputeString, value); deviceUnit.UpdateTime = DateTime.Now; deviceUnit.Save(); LogHelper.Debug("更新传感器实时数据 {0} {1}", deviceUnit.Name, deviceUnit.ProcessedValue); var dd = new DeviceData { Code1 = deviceUnit.FacilitySensorDeviceUnits[0].Code1, //暂时设定一个传感器设备只属于一个设施 SensorDeviceUnitID = deviceUnit.ID, OriginalValue = deviceUnit.OriginalValue, ProcessedValue = deviceUnit.ProcessedValue, ShowValue = deviceUnit.ShowValue, Max = sensor.ExperienceMax, Min = sensor.ExperienceMin, Upload = false, CreateTime = DateTime.Now, Remark = batchNo }; //测量值 //if (dd.ProcessedValue > sensor.MaxValue || dd.ProcessedValue < sensor.MinValue) // dd.IsException = true; //经验值:超过经验值即为超出设定上下限 if (dd.ProcessedValue > sensor.ExperienceMax || dd.ProcessedValue < sensor.ExperienceMin) { dd.IsException = true; } dd.Save(); //ServiceLogger.Current.WriteDebugLog("添加历史数据 {0} {1}", deviceUnit.Name, // deviceUnit.ProcessedValue); } else { LogHelper.Error("ID ={0} {1} 未配置传感器", deviceUnit.ID, deviceUnit.Name); } }); } else { LogHelper.Error("读取设备数据失败"); } }); } }); } }); #if DEBUG sw.Stop(); LogHelper.Debug("传感器采集耗时" + sw.ElapsedMilliseconds.ToString() + "ms"); #endif }
private void btnSave_Click(object sender, EventArgs e) { if (this.txtName.Text.Trim().IsNullOrWhiteSpace()) { MessageBox.Show("名称不能为空,请输入"); this.txtName.Focus(); return; } if (this.communicateDeviceId != 0) { try { // 更新 var communicateDevice = new CommunicateDevice { ID = this.communicateDeviceId, Name = this.txtName.Text.Trim(), CommunicateDeviceTypeID = Convert.ToInt32(this.cbCommunicateDeviceType.SelectedValue), Args1 = this.txtArgs1.Text, Args2 = this.txtArgs2.Text, Args3 = this.txtArgs3.Text, Args4 = this.txtArgs4.Text, Args5 = this.txtArgs5.Text, //OnlineStatus = Convert.ToBoolean(this.cbOnlineStatus.SelectedValue), OnlineStatus = this.rbtOnlineStatus.Checked, Exception = this.txtException.Text, //Remark = this.txtRemark.Text.Trim() }; CommunicateDevice.Update(communicateDevice); MessageBox.Show("更新成功"); } catch (Exception ex) { XTrace.WriteException(ex); MessageBox.Show("更新失败"); } } else { try { // 保存 var communicateDevice = new CommunicateDevice { //ID = Convert.ToInt32(this.txtId.Text), Name = this.txtName.Text.Trim(), CommunicateDeviceTypeID = Convert.ToInt32(this.cbCommunicateDeviceType.SelectedValue), Args1 = this.txtArgs1.Text, Args2 = this.txtArgs2.Text, Args3 = this.txtArgs3.Text, Args4 = this.txtArgs4.Text, Args5 = this.txtArgs5.Text, //OnlineStatus = Convert.ToBoolean(this.cbOnlineStatus.SelectedValue), OnlineStatus = this.rbtOnlineStatus.Checked, Exception = this.txtException.Text, //Remark = this.txtRemark.Text.Trim() }; CommunicateDevice.Save(communicateDevice); MessageBox.Show("保存成功"); } catch (Exception ex) { XTrace.WriteException(ex); MessageBox.Show("保存失败"); } } this.InitCommunicateDeviceListView(); }