private void UpdateSensorConfig(SensorOperation operation)
 {
     if (operation == null)
     {
         return;
     }
     if (operation.Action != Operations.ChangedDtu)
     {
         if (this.GetDtuNodeListener != null)
         {
             DtuNode node = this.GetDtuNodeListener(operation.Sensor.DtuID);
             if (node != null && operation.Sensor.SensorType != SensorType.Virtual)
             {
                 node.AddSensorOperation(operation);
             }
         }
     }
     else
     {
         try
         {
             this.SensorChangedDtu(operation);
         }
         catch (Exception ex)
         {
             this._log.ErrorFormat("sensor {0} changed Dtu error {1}", operation.Sensor.SensorID, ex.Message);
         }
     }
 }
Пример #2
0
        public static FsMessage GetDtuConfigChangedMsg(ChangedStatus changedStatus, DtuNode dtu, string dtucode = null)
        {
            var msg = new FsMessage
            {
                Header = new FsMessageHeader
                {
                    A = "PUT",
                    R = "/et/config/dtu/",
                    U = Guid.NewGuid(),
                    T = Guid.NewGuid(),
                    D = "et",
                    M = "config"
                },
                Body = JsonConvert.SerializeObject(dtu)
            };

            switch (changedStatus)
            {
            case ChangedStatus.Add:
                msg.Header.R = "/et/config/dtu/add";
                break;

            case ChangedStatus.Modify:
                msg.Header.M = "previous:" + dtucode;
                msg.Header.R = "/et/config/dtu/mod";
                break;

            case ChangedStatus.Delete:
                msg.Header.R = "/et/config/dtu/del";
                break;
            }
            return(msg);
        }
Пример #3
0
        private void ScheduleJob(DtuNode dtu, DateTimeOffset startTime, uint dacinterval = DtuNode.DefaultDacInterval, string group = JobGroup)
        {
            if (_schedule.CheckExists(new JobKey(string.Format("{0}{1}", DailyJobName, dtu.DtuCode), group)))
            {
                Log.DebugFormat("Exist Job: {0}, {1},{2}", dtu.DtuId, dtu.Name, dtu.DtuCode);
                return;
            }
            Log.DebugFormat("Arrange Timed Job: {0}, {1},{2}", dtu.DtuId, dtu.Name, dtu.DtuCode);
            // 任务
            IJobDetail job = JobBuilder.Create <DTUDacJob>()
                             .WithIdentity(string.Format("{0}{1}", DailyJobName, dtu.DtuCode), group)
                             .Build();

            AssignJobInfo(this, TaskType.TIMED, job, new Guid().ToString(), dtu, null, OnTimedTaskFinished);

            //// 调度策略
            //// DateTimeOffset startTime = DateBuilder.NextGivenMinuteDate(null, 1); //开始时间.
            //// 重复间隔: dtu.DacInterval (秒);
            //// 重复次数: 无限
            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity(string.Format("{0}{1}", DailyTrigger, dtu.DtuCode), group)
                                     .WithSimpleSchedule(x => x.WithInterval(new TimeSpan(0, 0, (int)dacinterval)).RepeatForever())
                                     .StartAt(startTime)
                                     .Build();

            // TODO 任务重入!!!
            _schedule.ScheduleJob(job, trigger);
        }
Пример #4
0
 public FileDtuConnection(DtuNode dtuNode)
 {
     this.DtuID    = dtuNode.DtuCode;
     this.Status   = WorkingStatus.IDLE;
     this.FilePath = dtuNode.GetProperty("param1").ToString();
     this.IsOnline = this.FilePath != null && (System.IO.File.Exists(this.FilePath) || System.IO.Directory.Exists(this.FilePath));
 }
Пример #5
0
        public DACTaskResult Run(DACTask task, DacTaskContext context)
        {
            DACTaskResult rslt;
            DtuNode       dtu = context.Node;

            switch (dtu.NetworkType)
            {
            case NetworkType.gprs:
                rslt = this.ExcuteGprsDacTask(task, context);
                break;

            case NetworkType.hclocal:
                rslt = this.ExcuteLocalDacTask(task, context);
                break;

            default:
                log.ErrorFormat("Dtu:{0}-Network Type:{1} : Error, Executor Is Not Implemented", dtu.DtuCode, dtu.NetworkType);
                rslt             = new DACTaskResult();
                rslt.Task        = task;
                rslt.Task.Status = DACTaskStatus.DONE;
                rslt.ErrorCode   = (int)Errors.ERR_INVALID_DTU;
                rslt.ErrorMsg    = string.Format("Dtu:{0},Network Type Error", dtu.DtuCode);
                rslt.Finished    = System.DateTime.Now;
                break;
            }

            return(rslt);
        }
Пример #6
0
        public void TestAddSensor()
        {
            DtuNode node = new DtuNode()
            {
                DtuCode     = "12345678",
                DtuId       = 2,
                Type        = DtuType.Gprs,
                Name        = "Test",
                DacInterval = 5
            };

            new Thread(t =>
            {
                uint i = 1;
                while (i < 100)
                {
                    var senopera = new SensorOperation
                    {
                        Sensor = new Sensor
                        {
                            SensorID  = i,
                            ModuleNo  = 2000 + 1,
                            ChannelNo = 1,
                            DtuID     = 2
                        },
                        Action = Operations.Add
                    };
                    node.AddSensorOperation(senopera);
                    i++;
                }
            }).Start();
            Thread.Sleep(10);
            new Thread(t =>
            {
                uint i = 5;
                while (i < 50)
                {
                    var senopera = new SensorOperation
                    {
                        OldSensorId = i,
                        Action      = Operations.Delete
                    };
                    node.AddSensorOperation(senopera);
                    i++;
                }
            }).Start();

            Thread.Sleep(100);
            var t2 = new Thread(t =>
            {
                node.UpDateSensor();
            });

            t2.Start();
            t2.Join();

            Console.WriteLine("dtunode's sensors count is {0}", node.Sensors.Count);
        }
Пример #7
0
 private DACWorker FindWorker(string dtuCode)
 {
     if (_dtuCodeMap.ContainsKey(dtuCode))
     {
         DtuNode d = _dtuCodeMap[dtuCode];
         return(FindWorker(d.DtuId));
     }
     return(null);
 }
Пример #8
0
        public void TestGetDtuByCode()
        {
            DbAccessorHelper.Init(new MsDbAccessor(connstr));
            DtuNode d0 = DbAccessorHelper.DbAccessor.QueryDtuNode("20120049");

            Assert.AreEqual((ushort)1, d0.DtuId);
            Assert.AreEqual("20120049", d0.DtuCode);
            Assert.AreEqual("K765集中采集站箱内", d0.Name);
        }
Пример #9
0
        private DACTaskResult ExcuteGprsDacTask(DACTask task, DacTaskContext context)
        {
            DtuNode dtu = context.Node;
            var     r   = new DACTaskResult {
                Task = task
            };

            r.Task.Status = DACTaskStatus.RUNNING;
            r.ErrorMsg    = "OK";
            r.DtuCode     = dtu.DtuCode;
            // 循环发送数据
            long totalElapsed = 0;

            context.DtuConnection.Connect(); // Connect to Resource.
            r.Started = DateTime.Now;
            foreach (Sensor si in dtu.Sensors)
            {
                SensorAcqResult resp = null;
                if (!this.IsSensorRequired(context, task.Sensors, si))
                {
                    continue;
                }

                try
                {
                    resp = this.RequestGprsSensor(si, context.DtuConnection, (int)dtu.DacTimeout);
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("[DACTaskExecutor] : unknown exceptions {0}", ex.Message);
                    if (resp == null)
                    {
                        resp = this.CreateAcqResult(context.DtuConnection.DtuID, si, (int)Errors.ERR_UNKNOW, "unknown exceptions");
                    }
                }
                if (resp.Data == null)
                {
                    resp.Data = new SensorErrorData(si.SensorID, resp.ErrorCode);
                }
                r.AddSensorResult(resp);
                totalElapsed += resp.Elapsed;
                if (!r.IsOK)
                {
                    r.ErrorCode = resp.ErrorCode;
                    r.ErrorMsg  = resp.ErrorMsg;
                    break; // ERROR.
                }

                Thread.Sleep(DELAY_BEFORE_NEW_COMMAND); //延迟.
            }
            r.Finished    = DateTime.Now;
            r.Elapsed     = totalElapsed;
            r.Task.Status = DACTaskStatus.DONE;
            context.DtuConnection.Disconnect();

            return(r);
        }
Пример #10
0
 public ComDtuConnection(DtuNode dtu)
 {
     this.DtuID  = dtu.DtuCode;
     this.Status = WorkingStatus.IDLE;
     this._port  = (SerialPort)dtu.GetProperty("serial");
     this._port.ReadBufferSize = 1048;
     //    this._timeout = dtu..DacTimeout;
     this._port.DataReceived  += this.OnDataReceived;
     this._port.ErrorReceived += this.OnErrorReceived;
 }
Пример #11
0
        public void TestGetDtuByCode()
        {
            var cs = connstr.Split(',');

            DbAccessorHelper.Init(new SQLiteDbAccessor(cs[0]));
            DtuNode d0 = DbAccessorHelper.DbAccessor.QueryDtuNode("COM14");

            Assert.AreEqual((ushort)3, d0.DtuId);
            Assert.AreEqual("COM14", d0.DtuCode);
            Assert.AreEqual("", d0.Name);
        }
Пример #12
0
 public void AddDtu(DtuNode dtu)
 {
     if (dtu == null)
     {
         return;
     }
     _dtus[dtu.DtuId]         = dtu;
     _dtuCodeMap[dtu.DtuCode] = dtu;
     ScheduleJob(dtu, DateBuilder.NextGivenMinuteDate(null, (int)dtu.DacInterval / 60));
     if (!_schedule.IsStarted)
     {
         _schedule.Start();
     }
 }
Пример #13
0
        public bool DtuConfigChanged(ChangedStatus cmd, DtuNode dtu, string dtucode = null)
        {
            switch (cmd)
            {
            case ChangedStatus.Add:
                return(dtu.NetworkType == NetworkType.gprs ? _dtuServer.Disconnect(dtu.DtuCode) : _fileServer.Disconnect(dtu));

            case ChangedStatus.Modify:
                return(ModifyDtu(dtu, dtucode));

            case ChangedStatus.Delete:
                return(RemoveDtu(dtu));
            }
            return(false);
        }
Пример #14
0
        /// <summary>
        /// 删除DTU
        /// </summary>
        /// <param name="dtu"></param>
        private bool RemoveDtu(DtuNode dtu)
        {
            DtuNode dn;

            if (_dtus.ContainsKey(dtu.DtuId))
            {
                _dtus.TryRemove(dtu.DtuId, out dn);
            }
            if (_dtuCodeMap.ContainsKey(dtu.DtuCode))
            {
                _dtuCodeMap.TryRemove(dtu.DtuCode, out dn);
            }
            TryRemoveJob(dtu.DtuCode);
            return(true);
        }
Пример #15
0
        // COM 建立连接.
        public IDtuConnection GetConnection(DtuNode dtuInfo)
        {
            ComDtuConnection cc    = null;
            string           dtuId = dtuInfo.DtuCode;

            if (!_connectPool.ContainsKey(dtuId))
            {
                cc = new ComDtuConnection(dtuInfo);
                _connectPool[dtuId] = cc;
            }
            else
            {
                cc = _connectPool[dtuId];
            }
            return(cc);
        }
Пример #16
0
        public IDtuConnection GetConnection(DtuNode node)
        {
            FileDtuConnection fc    = null;
            string            dtuId = node.DtuCode;

            if (!this._connectPool.ContainsKey(dtuId))
            {
                fc = new FileDtuConnection(node);
                this._connectPool[dtuId] = fc;
            }
            else
            {
                fc = this._connectPool[dtuId];
            }
            return(fc);
        }
Пример #17
0
        public void TestGetDtus()
        {
            DbAccessorHelper.Init(new MsDbAccessor(connstr));

            IList <DtuNode> dtus = DbAccessorHelper.DbAccessor.QueryDtuNodes();

            Assert.IsTrue(dtus != null);

            Assert.IsTrue(dtus.Count > 0);
            return;

            DtuNode d0 = dtus[0];

            Assert.AreEqual((ushort)1, d0.DtuId);
            Assert.AreEqual("20120049", d0.DtuCode);
            Assert.AreEqual("K765集中采集站箱内", d0.Name);
            Assert.AreEqual((uint)300, d0.DacInterval); // 5m
            // dtuId	sid	mno	cno	factor	PRODUCT_SENSOR_ID	PROTOCOL_CODE	name
            //  1	    17	9596	1	10	82	1503	K765左侧一阶平台1号测斜孔-下

            IList <Sensor> sensors = d0.Sensors;

            Assert.IsTrue(sensors.Count > 0);
            Sensor s1 = sensors[0];

            Assert.AreEqual((uint)1, s1.DtuID);
            Assert.AreEqual((uint)17, s1.SensorID);
            Assert.AreEqual((uint)9596, s1.ModuleNo);

            // param.
            SensorParam sp1 = s1.Parameters[0];

            Assert.AreEqual(-0.2969320000000, sp1.Value);

            SensorParam sp3 = s1.Parameters[2];

            Assert.AreEqual(600, sp3.Value);

            Assert.AreEqual("GPRS", d0.NetworkType.ToString().ToUpper());

            DtuNode dx = dtus.First(d => d.DtuCode == "20141015");

            //Assert.AreEqual("GNSS_NMEA0183", dx.NetworkType);
            Assert.AreEqual("hclocal", dx.NetworkType.ToString());
            Assert.AreEqual(@"C:\华测\HCMonitor 1.0\HCMonitor 1.0\Resultcsv\Net01.csv", dx.GetProperty("param1"));
            Assert.AreEqual(string.Empty, dx.GetProperty("param2"));
        }
Пример #18
0
        public void Init(Dictionary <string, string> pms)
        {
            this.DtuCode = 20120049;
            string  com  = pms["PortName"];
            DtuNode node = new DtuNode();

            node.DtuCode = com;
            node.AddProperty("serial", new SerialPort
            {
                PortName    = com,
                BaudRate    = Convert.ToInt32(pms["BaudRate"]),
                Parity      = (Parity)Convert.ToInt32(pms["Parity"]),
                DataBits    = Convert.ToInt32(pms["DataBits"]),
                StopBits    = (StopBits)Convert.ToInt32(pms["StopBits"]),
                ReadTimeout = Convert.ToInt32(pms["ReadTimeOut"])
            });
            this._dtuConnection = new ComDtuConnection(node);
        }
Пример #19
0
        public bool ModifyJobTime(DtuNode dtu)
        {
            if (_schedule == null)
            {
                return(false);
            }
            string   triggerKeystr = GetDailyTriggerKey(dtu.DtuId);
            ITrigger trigger       = _schedule.GetTrigger(new TriggerKey(triggerKeystr, JobGroup));

            if (trigger != null)
            {
                _schedule.PauseJob(new JobKey(GetDailyJobKey(dtu.DtuCode), JobGroup));
                TryRemoveJob(dtu.DtuCode);
                _schedule.UnscheduleJob(new TriggerKey(triggerKeystr, JobGroup));
                ScheduleJob(dtu, DateBuilder.NextGivenMinuteDate(null, (int)dtu.DacInterval / 60));


                //IJobDetail job = JobBuilder.Create<DTUDacJob>()
                //    .WithIdentity(string.Format("{0}{1}", DailyJobName, dtu.DtuCode), JobGroup)
                //    .Build();
                //AssignJobInfo(this, TaskType.TIMED, job, new Guid().ToString(), dtu, null, OnTimedTaskFinished);
                //// 调度策略
                //DateTimeOffset startTime = DateBuilder.NextGivenMinuteDate(null, (int) dtu.DacInterval/60); //开始时间.
                //// 重复间隔: dtu.DacInterval (秒);
                //// 重复次数: 无限
                //trigger = (ISimpleTrigger) TriggerBuilder.Create()
                //    .WithIdentity(triggerKeystr, JobGroup)
                //    .WithSimpleSchedule(x => x.WithInterval(new TimeSpan(0, 0, (int) dtu.DacInterval)).RepeatForever())
                //    .StartAt(startTime)
                //    .Build();
                //_schedule.ScheduleJob(job, trigger);
                if (!_schedule.IsStarted)
                {
                    _schedule.Start();
                }
                return(true);
            }
            return(false);
        }
Пример #20
0
 /// <summary>
 /// 修改DTU
 /// </summary>
 /// <param name="dtu"></param>
 private bool ModifyDtu(DtuNode dtu, string dtucode)
 {
     //dtu编号没有改变
     if (dtu.DtuCode == dtucode)
     {
         dtu.DacInterval               = dtu.DacInterval * 60;
         _dtus[dtu.DtuId].Name         = dtu.Name;
         _dtuCodeMap[dtu.DtuCode].Name = dtu.Name;
         if (_dtus[dtu.DtuId].DacInterval != dtu.DacInterval)
         {
             _dtuCodeMap[dtu.DtuCode].DacInterval = dtu.DacInterval;
             // 重新调度该DTU任务
             ModifyJobTime(dtu);
         }
         return(true);
     }
     if (_dtuCodeMap.ContainsKey(dtu.DtuCode))
     {
         DtuNode dn;
         _dtuCodeMap.TryRemove(dtu.DtuCode, out dn);
     }
     return(TryRemoveJob(dtu.DtuCode));
 }
Пример #21
0
        public void TestGetDtus()
        {
            var cs = connstr.Split(',');

            DbAccessorHelper.Init(new SQLiteDbAccessor(cs[0]));

            IList <DtuNode> dtus = DbAccessorHelper.DbAccessor.QueryDtuNodes();

            Assert.IsTrue(dtus != null);

            Assert.IsTrue(dtus.Count > 0);

            DtuNode d0 = dtus[0];

            Assert.AreEqual((ushort)2, d0.DtuId);
            Assert.AreEqual("COM6", d0.DtuCode);
            Assert.AreEqual((uint)300, d0.DacInterval);  // 5m
            // dtuId	sid	mno	cno	factor	PRODUCT_SENSOR_ID	PROTOCOL_CODE	name
            //  1	    17	9596	1	10	82	1503	K765左侧一阶平台1号测斜孔-下

            IList <Sensor> sensors = d0.Sensors;

            Assert.IsTrue(sensors.Count > 0);
            Sensor s1 = sensors[0];

            Assert.AreEqual((uint)2, s1.DtuID);
            Assert.AreEqual((uint)1, s1.SensorID);
            Assert.AreEqual((uint)9877, s1.ModuleNo);

            DtuNode d91 = dtus.Last();
            Sensor  s89 = d91.FindSensor(89); //89号传感器. 参数, 2, 归属公式: 9, 类型 28,27
            // param.
            SensorParam sp0 = s89.Parameters[0];

            Assert.AreEqual(9, sp0.FormulaParam.FID);
            Assert.AreEqual(27, sp0.FormulaParam.PID);
        }
Пример #22
0
        private static string GetWorkerInfo(DACWorker worker)
        {
            string info = null;

            if (worker == null)
            {
                info = "null";
            }
            else
            {
                DacTaskContext ctx = worker.GetContext();
                if (ctx != null)
                {
                    IDtuConnection c = ctx.DtuConnection;
                    DtuNode        d = ctx.Node;
                    info = string.Format("Node={0}, conn={1}", d.DtuCode, c != null ? (c.IsOnline ? "online" : "offline") : "null");
                }
                else
                {
                    info = "Context null";
                }
            }
            return(info);
        }
Пример #23
0
        public HttpResponseMessage Remove(int dtuId, int structId)
        {
            using (var entity = new SecureCloud_Entities())
            {
                var dtuEntity = entity.T_DIM_REMOTE_DTU.FirstOrDefault(d => d.ID == dtuId);
                if (dtuEntity == null || dtuEntity.REMOTE_DTU_STATE == false)
                {
                    return(Request.CreateResponse(
                               HttpStatusCode.BadRequest,
                               StringHelper.GetMessageString("DTU不存在或已禁用")));
                }

                // 检查传感器关联
                var sens = entity.T_DIM_SENSOR.Where(s => s.DTU_ID == dtuId && !s.IsDeleted);
                if (sens.Any())
                {
                    return(Request.CreateResponse(
                               HttpStatusCode.Conflict,
                               StringHelper.GetMessageString("请先删除该DTU下的传感器")));
                }

                // 删除关联
                var sd = entity.T_DIM_STRUCT_DTU.Where(d => d.DtuId == dtuId && d.StructureId == structId);
                foreach (var m in sd)
                {
                    entity.T_DIM_STRUCT_DTU.Remove(m);
                }

                // 检查关联
                if (!entity.T_DIM_STRUCT_DTU.Any(d => d.DtuId == dtuId))
                {
                    dtuEntity.REMOTE_DTU_STATE = false;
                }

                #region 日志信息

                var info = (from d in entity.T_DIM_REMOTE_DTU
                            from s in entity.T_DIM_STRUCT_DTU
                            from st in entity.T_DIM_STRUCTURE
                            where d.ID == s.DtuId && d.ID == dtuId && s.StructureId == st.ID
                            select new { d.REMOTE_DTU_NUMBER, st.STRUCTURE_NAME_CN }).FirstOrDefault();
                var dtu = info == null ? string.Empty : info.REMOTE_DTU_NUMBER;
                var stc = info == null ? string.Empty : info.STRUCTURE_NAME_CN;

                this.Request.Properties["ActionParameterShow"] = string.Format("dtu号:{0}, 所属结构物:{1}", dtu, stc);
                #endregion

                try
                {
                    var dtnod = new DtuNode
                    {
                        DtuId       = (uint)dtuEntity.ID,
                        Type        = DtuType.Gprs,
                        DtuCode     = dtuEntity.REMOTE_DTU_NUMBER,
                        Name        = dtuEntity.DESCRIPTION,
                        DacInterval = dtuEntity.REMOTE_DTU_GRANULARITY == null ? DtuNode.DefaultDacInterval : (uint)(dtuEntity.REMOTE_DTU_GRANULARITY * 60),
                        NetworkType = dtuEntity.ProductDtuId == 2 ? NetworkType.hclocal : NetworkType.gprs
                    };
                    if (dtnod.NetworkType == NetworkType.hclocal)
                    {
                        dtnod.AddProperty("param1", dtuEntity.P1);
                    }
                    entity.SaveChanges();
                    WebClientService.SendToET(ConfigChangedMsgHelper.GetDtuConfigChangedMsg(ChangedStatus.Delete, dtnod));
                    return(Request.CreateResponse(
                               HttpStatusCode.Accepted,
                               StringHelper.GetMessageString("DTU删除成功")));
                }
                catch (Exception ex)
                {
                    return(Request.CreateResponse(
                               HttpStatusCode.BadRequest,
                               StringHelper.GetMessageString("DTU删除失败")));
                }
            }
        }
Пример #24
0
        public void TestSnGpsTask()
        {
            if (System.IO.File.Exists("lastAcqDate.dat"))
            {
                System.IO.File.Delete("lastAcqDate.dat");
            }

            (new Gps_SN_SensorAdapter() as GpsBaseAdapter).UpdateSensorLastDataAcqTime(1, new DateTime(2015, 1, 28, 23, 51, 35));

            var adapterManager = SensorAdapterManager.InitializeManager();
            var taskexcutor    = new DACTaskExecutor(adapterManager);
            var dtusens        = new List <uint>();

            dtusens.Add(1);
            var task    = new DACTask("1", 100, dtusens, TaskType.TIMED, null);
            var dtunode = new DtuNode
            {
                DtuId       = 100,
                Type        = DtuType.File,
                NetworkType = NetworkType.hclocal
            };
            var s = new Sensor
            {
                SensorID     = 1,
                ModuleNo     = 9003,
                ProtocolType = 9403,
                ChannelNo    = 1,
                TableColums  = "SURFACE_DISPLACEMENT_X_VALUE,SURFACE_DISPLACEMENT_Y_VALUE,SURFACE_DISPLACEMENT_Z_VALUE"
            };

            s.AddParameter(new SensorParam(null)
            {
                Value = 2
            });
            s.AddParameter(new SensorParam(null)
            {
                Value = 2
            });
            s.AddParameter(new SensorParam(null)
            {
                Value = 2
            });
            s.AddParameter(new SensorParam(null)
            {
                Value = 0
            });
            dtunode.AddSensor(s);
            dtunode.AddProperty("param1", filepath);
            var conn   = new FileDtuConnection(dtunode);
            var contxt = new DacTaskContext()
            {
                Node          = dtunode,
                DtuConnection = conn
            };

            var dactaskresult = taskexcutor.Run(task, contxt);

            Assert.IsNotNull(dactaskresult);
            Assert.IsTrue(dactaskresult.Task.Status == DACTaskStatus.DONE);
            var sensorresults = dactaskresult.SensorResults;

            Assert.NotNull(sensorresults);
            Assert.IsNotEmpty(sensorresults);
            Assert.AreEqual(101, sensorresults.Count);
            var senres = sensorresults[0];

            Assert.IsTrue(senres.IsOK);
            var sendata = senres.Data;

            Assert.IsTrue(sendata is Gps3dData);
            Assert.AreEqual(sendata.RawValues[0], 4435175.4523 * 1000, 0.0000001);
            Assert.AreEqual(sendata.RawValues[1], 524121.0006 * 1000, 0.0000001);
            Assert.AreEqual(sendata.RawValues[2], 82.2112 * 1000, 0.0000001);
            Assert.AreEqual(sendata.ThemeValues[0].Value, 4435175.4523 * 1000 - 2, 0.0000001);
            Assert.AreEqual(sendata.ThemeValues[1].Value, 524121.0006 * 1000 - 2, 0.0000001);
            Assert.AreEqual(sendata.ThemeValues[2].Value, 82.2112 * 1000 - 2, 0.0000001);
        }
Пример #25
0
        public void TestRemoteDtuRead()
        {
            this.Log.Debug("TestRemoteDtuRead");
            IList <DtuNode> _nodes = new List <DtuNode>();
            DtuNode         dn1    = new DtuNode
            {
                DtuCode     = "20140168",
                DacTimeout  = 2,  // 10s timeout
                DacInterval = 10, //30s interval
                DtuId       = 999,
                NetworkType = NetworkType.gprs,
                Type        = DtuType.Gprs
            };
            DtuNode dn2 = new DtuNode
            {
                DtuCode     = "20140167",
                DacTimeout  = 6,  // 10s timeout
                DacInterval = 20, //30s interval
                DtuId       = 998,
                NetworkType = NetworkType.gprs,
                Type        = DtuType.Gprs
            };
            Sensor s02 = new Sensor
            {
                ProtocolType = (uint)ProtocolType.Pressure_MPM,
                DtuID        = 999,
                SensorID     = 1,
                ModuleNo     = 2,
                ChannelNo    = 0,
                FactorType   = (uint)SafetyFactor.StressStrainPoreWaterPressure,
                Name         = "Pressure 02"
            };
            Sensor s27 = new Sensor
            {
                ProtocolType = (uint)ProtocolType.Pressure_MPM,
                DtuID        = 999,
                SensorID     = 2,
                ModuleNo     = 27,
                ChannelNo    = 0,
                FactorType   = (uint)SafetyFactor.StressStrainPoreWaterPressure,
                Name         = "Pressure 27"
            };

            Sensor s5135 = new Sensor
            {
                ProtocolType = (uint)ProtocolType.VibratingWire_OLD, //
                DtuID        = 998,
                SensorID     = 3,
                ModuleNo     = 5135,
                ChannelNo    = 1,
                FactorType   = (uint)SafetyFactor.Forcesteelbar,
                Name         = "Pressure 5135"
            };

            _nodes.Add(dn1);
            //_nodes.Add(dn2);
            dn1.AddSensor(s02);
            dn1.AddSensor(s27);
            dn1.AddSensor(s5135);

            GprsDtuServer _server = new GprsDtuServer(5056);

            this.Log.Debug("Server started.");
            string sqlconn = "server=localhost;database=iSecureCloud;uid=tester;pwd=Fas123";

            // sqlconn = "server=192.168.1.128;database=DW_iSecureCloud_Empty2.2;uid=sa;pwd=861004";
            this.Log.DebugFormat("Connect to db: {0}", sqlconn);
            DbAccessorHelper.Init(new MsDbAccessor(sqlconn));

            _server.Start();

            tm = new DACTaskManager(_server, _nodes, null, DtuType.Gprs);
            tm.ArrangeTimedTask();
            Console.ReadLine();
        }
Пример #26
0
        private DACTaskResult ExcuteLocalDacTask(DACTask task, DacTaskContext context)
        {
            DtuNode       dtu  = context.Node;
            DACTaskResult rslt = new DACTaskResult();

            rslt.Task             = task;
            rslt.Task.Status      = DACTaskStatus.RUNNING;
            rslt.ErrorMsg         = "OK";
            rslt.StoragedTimeType = SensorAcqResultTimeType.SensorResponseTime;

            Stopwatch sw = new Stopwatch();

            sw.Start();
            var dtuConn = context.DtuConnection as FileDtuConnection; // 强转成FileDtuConnection

            if (dtuConn != null && dtuConn.Connect())
            {
                try
                {
                    foreach (Sensor si in dtu.Sensors)
                    {
                        if (!this.IsSensorRequired(context, task.Sensors, si))
                        {
                            continue;
                        }

                        var result = this.RequestFileSensor(si, dtuConn);// 请求文件传感器
                        foreach (SensorAcqResult r in result)
                        {
                            rslt.AddSensorResult(r);
                        }
                    }
                    this.CheckFileAndBackup(dtuConn.FilePath);
                }
                catch (System.Exception e)
                {
                    rslt.ErrorCode = (int)Errors.ERR_NOT_CONNECTED;
                    rslt.ErrorMsg  = string.Format(
                        "DTU:{0},FilePath:{1},Failed To Read the File,Msg:{2}",
                        dtu.DtuCode,
                        dtuConn.FilePath,
                        e.Message);
                    log.ErrorFormat(
                        "dtu:{0} network={1},file={2},Failed To Read the File,Msg:{3}",
                        dtu.DtuCode,
                        dtu.NetworkType,
                        dtuConn.FilePath,
                        e.Message);
                }
            }
            else
            {
                rslt.ErrorCode = (int)Errors.ERR_NOT_CONNECTED;
                rslt.ErrorMsg  = string.Format(
                    "DTU:{0},FilePath:{1},File Not Exists",
                    dtu.DtuCode,
                    dtuConn != null ? dtuConn.FilePath : null);
                log.ErrorFormat("dtu:{0} network={1},file={2},File Not Exists", dtu.DtuCode, dtu.NetworkType, dtuConn != null ? dtuConn.FilePath : null);
            }
            sw.Stop();
            rslt.Finished    = System.DateTime.Now;
            rslt.Elapsed     = sw.ElapsedMilliseconds;
            rslt.Task.Status = DACTaskStatus.DONE;
            context.DtuConnection.Disconnect();

            return(rslt);
        }
Пример #27
0
        /// <summary>
        /// 获取DTU列表.
        /// </summary>
        /// <param name="dtuCode">要查询的DTU编码</param>
        /// <param name="networkType">网络类型</param>
        /// <returns></returns>
        public IList <DtuNode> QueryDtuNodes(string dtuCode = null, NetworkType?networkType = null)
        {
            List <DtuNode> dtus = new List <DtuNode>();
            DataSet        ds   = this._helper.Query(string.Format(@"
select 
    D.[ID] id, 
    D.[REMOTE_DTU_NUMBER] code, 
    D.[REMOTE_DTU_SUBSCRIBER] subscriber,
    D.[REMOTE_DTU_GRANULARITY] interval, 
    D.[DESCRIPTION] as [desc] ,
    D.[ProductDtuId],
    P.[NetworkType],
    D.[P1],
    D.[P2],
    D.[P3],
    D.[P4],
    sd.StructureId sid
from T_DIM_REMOTE_DTU D 
left join [T_DIM_DTU_PRODUCT] P on P.ProductId = D.ProductDtuId
left join [T_DIM_STRUCT_DTU] sd on sd.DtuId = D.ID
where D.ProductDtuId !=3 {0} {1}
order by ID",
                                                                   string.IsNullOrEmpty(dtuCode)? "":  string.Format("and D.REMOTE_DTU_NUMBER={0}", dtuCode),
                                                                   networkType == null ? "": string.Format("and P.NetworkType='{0}'", networkType)
                                                                   ));

            if (ds != null)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    try
                    {
                        NetworkType nwType;
                        bool        success = Enum.TryParse(Convert.ToString(dr["NetworkType"]), out nwType);

                        DtuNode di = new DtuNode
                        {
                            DtuId = (uint)Convert.ToInt32(dr["id"]),
                            //StructId = dr.IsNull("sid") ? 0 : Convert.ToUInt32(dr["sid"]),
                            DtuCode     = Convert.ToString(dr["code"]),
                            DacInterval = dr.IsNull("interval")
                                ? DtuNode.DefaultDacInterval
                                : (uint)(Convert.ToInt32(dr["interval"]) * 60),
                            Name        = Convert.ToString(dr["desc"]),
                            NetworkType = success ? (NetworkType?)nwType : null
                        };
                        di.AddProperty("param1", Convert.ToString(dr["P1"]));
                        di.AddProperty("param2", Convert.ToString(dr["P2"]));
                        di.AddProperty("param3", Convert.ToString(dr["P3"]));
                        di.AddProperty("param4", Convert.ToString(dr["P4"]));
                        dtus.Add(di);
                    }
                    catch (Exception ex)
                    {
                        Log.WarnFormat("DTU :{0}-{1}  error:{2}", Convert.ToInt32(dr["id"]), Convert.ToString(dr["code"]), ex.Message);
                    }
                }
            }
            ds = this._helper.Query(@"
select
    s.STRUCT_ID structId,
    s.DTU_ID dtuId,
    s.SENSOR_ID sid,
    s.MODULE_NO mno,
    s.DAI_CHANNEL_NUMBER cno,
    s.SAFETY_FACTOR_TYPE_ID factor, 
    s.PRODUCT_SENSOR_ID pid,
    s.Identification sensortype,
    s.Enable enable,
    protocol.PROTOCOL_CODE protocol_type,
    s.SENSOR_LOCATION_DESCRIPTION name,
    factorType.THEMES_TABLE_NAME factorTypeTable,
    factorType.THEMES_COLUMNS tableColums,
    product.PRODUCT_ID productId,
    product.PRODUCT_CODE productCode
from T_DIM_SENSOR s ,dbo.T_DIM_SENSOR_PRODUCT product, dbo.T_DIM_PROTOCOL_TYPE protocol,dbo.T_DIM_SAFETY_FACTOR_TYPE factorType
where s.PRODUCT_SENSOR_ID = product.PRODUCT_ID AND product.PROTOCOL_ID = protocol.PROTOCOL_ID AND s.SAFETY_FACTOR_TYPE_ID = factorType.SAFETY_FACTOR_TYPE_ID AND s.MODULE_NO is not null AND s.IsDeleted = 0
order by SENSOR_ID");
            DataTable table            = ds.Tables[0];
            var       formulaParamDict = this.GetFormulaParamDict();                               // 获取参数定义
            DataSet   paramSet         = this._helper.Query(@"select * from T_DIM_FORMULAID_SET"); //公式配置。
            DataTable paramTable       = paramSet.Tables[0];

            foreach (DtuNode dtu in dtus)
            {
                if (dtu == null)
                {
                    continue;
                }
                // filter to Node
                var sr = from r in table.AsEnumerable()
                         where !r.IsNull("dtuId") && r.Field <int>("dtuId") == dtu.DtuId
                         orderby r["sid"]
                         select r;
                if (!sr.Any())
                {
                    continue;
                }
                foreach (DataRow row in sr)
                {
                    try
                    {
                        var sensor = new Sensor
                        {
                            DtuID           = dtu.DtuId,
                            DtuCode         = dtu.DtuCode,
                            StructId        = Convert.ToUInt32(row["structId"]),
                            SensorID        = Convert.ToUInt32(row["sid"]),
                            ChannelNo       = row.IsNull("cno") ? 1 : Convert.ToUInt32(row["cno"]),
                            ModuleNo        = row.IsNull("mno") ? 0 : Convert.ToUInt32(row["mno"]),
                            ProtocolType    = Convert.ToUInt16(row["protocol_type"]),
                            Name            = Convert.ToString(row["name"]),
                            FactorType      = Convert.ToUInt32(row["factor"]),
                            FactorTypeTable = Convert.ToString(row["factorTypeTable"]),
                            TableColums     = Convert.ToString(row["tableColums"]),
                            ProductId       = Convert.ToInt32(row["productId"]),
                            ProductCode     = row["productCode"].ToString().Trim(),
                            AcqInterval     = dtu.DacInterval / 60, // 分钟
                            LastTime        = DateTime.MinValue,
                            SensorType      = (SensorType)Convert.ToByte(row["sensortype"]),
                            UnEnable        = Convert.ToBoolean(row["enable"])
                        };
                        this.GetParameters(paramTable, sensor, formulaParamDict);
                        if (sensor.Parameters.Count > 0)
                        {
                            sensor.FormulaID = (uint)sensor.Parameters[0].FormulaParam.FID;
                        }
                        dtu.AddSensor(sensor);
                    }
                    catch (Exception ex)
                    {
                        Log.WarnFormat("Sensor :{0}  error:{1}", Convert.ToUInt32(row["sid"]), ex.Message);
                    }
                }
            }
            return(dtus);
        }
Пример #28
0
        public HttpResponseMessage Modify([FromUri] int dtuId, [FromBody] DtuModel dtu)
        {
            using (var entity = new SecureCloud_Entities())
            {
                var dtuEntity = entity.T_DIM_REMOTE_DTU.FirstOrDefault(d => d.ID == dtuId);
                if (dtuEntity == null || dtuEntity.REMOTE_DTU_STATE == false)
                {
                    return(Request.CreateResponse(
                               HttpStatusCode.BadRequest,
                               StringHelper.GetMessageString("DTU不存在或已禁用")));
                }

                StringBuilder sb      = new StringBuilder();
                string        dtucode = dtuEntity.REMOTE_DTU_NUMBER;
                if (dtu.DtuNo != default(string) && dtu.DtuNo != dtuEntity.REMOTE_DTU_NUMBER)
                {
                    dtuEntity.REMOTE_DTU_NUMBER = dtu.DtuNo;
                    sb.AppendFormat("Dtu编号改为:{0},", dtu.DtuNo);
                }
                if (dtu.Granularity != default(int) && dtu.Granularity != dtuEntity.REMOTE_DTU_GRANULARITY)
                {
                    dtuEntity.REMOTE_DTU_GRANULARITY = (short)dtu.Granularity;
                    sb.AppendFormat("采集间隔改为:{0},", dtu.Granularity);
                }
                if (dtu.Sim != dtuEntity.REMOTE_DTU_SUBSCRIBER)
                {
                    dtuEntity.REMOTE_DTU_SUBSCRIBER = dtu.Sim;
                    sb.AppendFormat("sim卡号改为:{0},", dtu.Sim);
                }
                if (dtu.Ip != dtuEntity.DTU_IP)
                {
                    dtuEntity.DTU_IP = dtu.Ip;
                    sb.AppendFormat("Ip改为:{0},", dtu.Ip);
                }
                if (dtu.Port != dtuEntity.DTU_PORT)
                {
                    dtuEntity.DTU_PORT = dtu.Port;
                    sb.AppendFormat("端口改为:{0},", dtu.Port);
                }
                if (dtu.ProductId != default(int) && dtu.ProductId != dtuEntity.ProductDtuId)
                {
                    dtuEntity.ProductDtuId = dtu.ProductId;
                    var product = entity.T_DIM_DTU_PRODUCT.FirstOrDefault(p => p.ProductId == dtu.ProductId);
                    if (product != null)
                    {
                        sb.AppendFormat("产品厂商改为{0},型号改为:{1}", product.DtuFactory, product.DtuModel);
                    }
                    else
                    {
                        sb.AppendFormat("产品id改为{0}", dtu.ProductId);
                    }
                }
                if (dtu.P1 != dtuEntity.P1)
                {
                    dtuEntity.P1 = dtu.P1;
                    sb.AppendFormat("参数1改为:{0}", dtu.P1);
                }
                if (dtu.P2 != dtuEntity.P2)
                {
                    dtuEntity.P2 = dtu.P2;
                    sb.AppendFormat("参数2改为:{0}", dtu.P1);
                }
                if (dtu.P3 != dtuEntity.P3)
                {
                    dtuEntity.P3 = dtu.P3;
                    sb.AppendFormat("参数3改为:{0}", dtu.P1);
                }
                if (dtu.P4 != dtuEntity.P4)
                {
                    dtuEntity.P4 = dtu.P4;
                    sb.AppendFormat("参数4改为:{0}", dtu.P1);
                }

                #region 日志信息

                this.Request.Properties["ActionParameter"]     = JsonConvert.SerializeObject(dtu);
                this.Request.Properties["ActionParameterShow"] = string.Format("dtu号:{0}:{1}", dtu.DtuNo ?? string.Empty, sb);
                #endregion

                try
                {
                    entity.SaveChanges();
                    var dtnod = new DtuNode
                    {
                        DtuId       = (uint)dtuEntity.ID,
                        Type        = DtuType.Gprs,
                        DtuCode     = dtuEntity.REMOTE_DTU_NUMBER,
                        NetworkType = dtuEntity.ProductDtuId == 2 ? NetworkType.hclocal : NetworkType.gprs,
                        Name        = dtuEntity.DESCRIPTION,
                        DacInterval = dtuEntity.REMOTE_DTU_GRANULARITY == null ? DtuNode.DefaultDacInterval : (uint)dtuEntity.REMOTE_DTU_GRANULARITY
                    };
                    if (dtnod.NetworkType == NetworkType.hclocal)
                    {
                        dtnod.AddProperty("param1", dtuEntity.P1);
                    }
                    WebClientService.SendToET(ConfigChangedMsgHelper.GetDtuConfigChangedMsg(ChangedStatus.Modify, dtnod, dtucode));
                    return(Request.CreateResponse(
                               HttpStatusCode.Accepted,
                               StringHelper.GetMessageString("DTU信息修改成功")));
                }
                catch (Exception ex)
                {
                    return(Request.CreateResponse(
                               HttpStatusCode.BadRequest,
                               StringHelper.GetMessageString("DTU信息修改失败")));
                }
            }
        }
Пример #29
0
 public IDtuConnection GetConnection(DtuNode dtu)
 {
     return(_connectPool.ContainsKey(dtu.DtuCode)? _connectPool[dtu.DtuCode]:null);
 }
Пример #30
0
        public HttpResponseMessage Add([FromBody] DtuModel dtu)
        {
            using (var entity = new SecureCloud_Entities())
            {
                // 新增dtu
                var dtuEntity = new T_DIM_REMOTE_DTU();
                dtuEntity.REMOTE_DTU_NUMBER      = dtu.DtuNo;
                dtuEntity.REMOTE_DTU_SUBSCRIBER  = dtu.Sim;
                dtuEntity.REMOTE_DTU_GRANULARITY = (short)dtu.Granularity;
                dtuEntity.DTU_IP           = dtu.Ip;
                dtuEntity.DTU_PORT         = dtu.Port;
                dtuEntity.P1               = dtu.P1;
                dtuEntity.P2               = dtu.P2;
                dtuEntity.P3               = dtu.P3;
                dtuEntity.P4               = dtu.P4;
                dtuEntity.ProductDtuId     = dtu.ProductId;
                dtuEntity.REMOTE_DTU_STATE = true;

                var entry = entity.Entry(dtuEntity);
                entry.State = System.Data.EntityState.Added;

                // 添加关联关系
                var sdEntity = new T_DIM_STRUCT_DTU();
                sdEntity.DtuId       = dtuEntity.ID;
                sdEntity.StructureId = dtu.StructId;

                var entry2 = entity.Entry(sdEntity);
                entry2.State = System.Data.EntityState.Added;

                #region 日志信息

                var stc        = entity.T_DIM_STRUCTURE.FirstOrDefault(s => s.ID == dtu.StructId);
                var product    = entity.T_DIM_DTU_PRODUCT.FirstOrDefault(p => p.ProductId == dtu.ProductId);
                var paramName1 = (product != null && product.NetworkType.ToLower().Contains("local")) ? "文件路径" : "参数1";
                this.Request.Properties["ActionParameter"]     = JsonConvert.SerializeObject(dtu);
                this.Request.Properties["ActionParameterShow"] =
                    string.Format(
                        "dtu号:{0},结构物:{1},采集粒度:{3},产品厂商:{6},产品型号:{7},sim卡号:{2},ip地址:{4},端口:{5},[{12}:{8},参数2:{9},参数3:{10},参数4:{11}]",
                        dtu.DtuNo ?? string.Empty,
                        stc == null ? string.Empty : stc.STRUCTURE_NAME_CN,
                        dtu.Sim ?? string.Empty,
                        dtu.Granularity,
                        dtu.Ip,
                        dtu.Port,
                        product != null ? product.DtuFactory : string.Empty,
                        product != null ? product.DtuModel : string.Empty,
                        dtu.P1,
                        dtu.P2,
                        dtu.P3,
                        dtu.P4,
                        paramName1);
                #endregion

                try
                {
                    entity.SaveChanges();
                    var dtnod = new DtuNode
                    {
                        DtuId       = (uint)dtuEntity.ID,
                        Type        = DtuType.Gprs,
                        DtuCode     = dtuEntity.REMOTE_DTU_NUMBER,
                        Name        = dtuEntity.DESCRIPTION,
                        DacInterval = dtuEntity.REMOTE_DTU_GRANULARITY == null ? DtuNode.DefaultDacInterval : (uint)(dtuEntity.REMOTE_DTU_GRANULARITY * 60),
                        NetworkType = dtuEntity.ProductDtuId == 2 ? NetworkType.hclocal : NetworkType.gprs
                    };
                    if (dtnod.NetworkType == NetworkType.hclocal)
                    {
                        dtnod.AddProperty("param1", dtuEntity.P1);
                    }
                    WebClientService.SendToET(ConfigChangedMsgHelper.GetDtuConfigChangedMsg(ChangedStatus.Add, dtnod));
                    return(Request.CreateResponse(
                               HttpStatusCode.Accepted,
                               StringHelper.GetMessageString("添加DTU成功")));
                }
                catch (Exception ex)
                {
                    return(Request.CreateResponse(
                               HttpStatusCode.BadRequest,
                               StringHelper.GetMessageString("添加DTU失败")));
                }
            }
        }