Пример #1
0
        private static void Main(string[] args)
        {
            var factory = new TransportFactory();

            var road = factory.GetTransport(Enum.Transport.Road);

            Console.WriteLine(road.Deliver(90));

            var maritime = factory.GetTransport(Enum.Transport.Maritime);

            Console.WriteLine(maritime.Deliver(1200));

            Console.ReadKey();
        }
Пример #2
0
        public void Run()
        {
            if (auditQueueAddress == null)
            {
                return;
            }

            inputTransport = TransportFactory.GetTransport(OnTransportMessageReceived);
            inputTransport.Start(auditQueueAddress);
        }
Пример #3
0
        public void Run()
        {
            if (errorQueueAddress == null)
            {
                return;
            }

            NServiceBus.Utils.MsmqUtilities.CreateQueueIfNecessary(errorLogAddress, Thread.CurrentPrincipal.Identity.Name);

            inputTransport = TransportFactory.GetTransport(OnTransportMessageReceived);

            inputTransport.Start(errorQueueAddress);
        }
Пример #4
0
        /// <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);
            });
        }
Пример #5
0
        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);
                        }
                    });
                });
            });
        }
Пример #6
0
        /// <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);
                }
            });
        }
Пример #7
0
        public void Deliver()
        {
            var transport = _transportFactory.GetTransport();

            transport.Deliver();
        }
Пример #8
0
        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
        }
Пример #9
0
        /// <summary>
        /// 控制设备
        /// </summary>
        /// <param name="deviceId">控制设备ID</param>
        /// <param name="status">设备状态</param>
        private void Control(int deviceId, int status)
        {
            const bool result = false;
            List <FacilityControlDeviceUnit> fac = FacilityControlDeviceUnit.FindAllByControlDeviceUnitGroupNum(deviceId);

            if (fac == null || !fac.Any())
            {
                return;
            }
            var device = ControlDeviceUnit.FindByID(deviceId);

            if (device == null)
            {
                return;
            }
            string            reason = null;
            TransportTypeEnum type;

            if (
                !Enum.TryParse(device.ModularDevice.CommunicateDevice.CommunicateDeviceTypeName,
                               true, out type))
            {
                type = TransportTypeEnum.Unknow;
            }
            var host    = device.ModularDevice.CommunicateDevice.Args1;
            var e       = Convert.ToInt32(device.ModularDevice.CommunicateDevice.Args2);
            var timeout = Convert.ToInt32(device.ModularDevice.CommunicateDevice.Args3);
            //获取Transport
            var transport           = TransportFactory.GetTransport(type, host, e, timeout);
            var modbusControlDevice = new ModbusControlDevice(transport,
                                                              Convert.ToByte(device.ModularDevice.Address));

            try
            {
                //待编写控制指令

                //if (device.IsComposite) //三态设备  正转  反转  停止
                //{
                //    if (status == -1)
                //    {
                //        result = modbusControlDevice.Write(device.RegisterAddress1, true);
                //    }
                //    else if (status == 0)
                //    {
                //        result = modbusControlDevice.Write(device.RegisterAddress1, false);
                //        result = modbusControlDevice.Write(device.RegisterAddress2, false);
                //    }
                //    else if (status == 1)
                //    {
                //        result = modbusControlDevice.Write(device.RegisterAddress2, true);
                //    }
                //}
                //else //两态设备 开 关
                //{
                //    result = modbusControlDevice.Write(device.RegisterAddress1, status == 1 ? true : false);
                //}
            }
            catch (Exception ex)
            {
                reason = ex.ToString();
            }
            LogHelper.Debug("指令执行" + (result ? "成功" : "失败"));

            DeviceControlCommand.FindAllByControlDeviceUnitID(deviceId).ToList().ForEach(deviceControlCommand =>
            {
                var controlResult = new ControlResult
                {
                    Serialnum = deviceControlCommand.Code1,
                    //Command = status,
                    //FacilityCode = fac[0].Facility.Code1,
                    //DeviceCode = fac[0].Code1,
                    //ContinueTime = 5,
                    Time       = DateTime.Now,
                    Result     = result,
                    FailReason = reason
                };
                var devControlLog = new DeviceControlLog
                {
                    Code1 = deviceControlCommand.Code1,
                    ControlDeviceUnitID    = deviceControlCommand.ControlDeviceUnitGroupNum,
                    ControlResult          = result,
                    CreateTime             = DateTime.Now,
                    DeviceControlCommand   = deviceControlCommand,
                    DeviceControlCommandID = deviceControlCommand.ID,
                    DeviceValue            = Convert.ToInt32(CalcControlDeviceValue.CalcProcessValue(fac[0])),
                    ShowValue  = CalcControlDeviceValue.CalcOriginal(fac[0]).ToString(),
                    FailReason = reason
                };
                devControlLog.Save();
                UploadControlCommand(controlResult, fac[0].Facility); //上传控制指令
                Thread.Sleep(50);
            });
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="VerifoneDeviceProtocol"/> class.
 /// </summary>
 /// <param name="config">Configuration parameters.</param>
 public VerifoneDeviceProtocol(IDictionary <string, string> config)
 {
     this.transport = TransportFactory.GetTransport(config);
 }
Пример #11
0
 private QueuekerClient(TransportTypes transportType, QueuekerSettings settings)
 {
     _queuekerSettings = settings;
     _transport        = TransportFactory.GetTransport(transportType, settings);
 }