Пример #1
0
        /// <summary>
        /// Creates a communication line, communication channel and devices.
        /// </summary>
        public static CommLine Create(LineConfig lineConfig, CoreLogic coreLogic, DriverHolder driverHolder)
        {
            // create communication line
            CommLine commLine = new CommLine(lineConfig, coreLogic);

            // create communication channel
            if (string.IsNullOrEmpty(lineConfig.Channel.Driver))
            {
                ChannelLogic channelLogic = new ChannelLogic(commLine, lineConfig.Channel); // stub
                commLine.channel = new ChannelWrapper(channelLogic, commLine.Log);
            }
            else if (driverHolder.GetDriver(lineConfig.Channel.Driver, out DriverLogic driverLogic))
            {
                ChannelLogic channelLogic = driverLogic.CreateChannel(commLine, lineConfig.Channel);
                commLine.channel = new ChannelWrapper(channelLogic, commLine.Log);
            }
            else
            {
                throw new ScadaException(Locale.IsRussian ?
                                         "Драйвер канала связи {0} не найден." :
                                         "Communication channel driver {0} not found.", lineConfig.Channel.Driver);
            }

            // create devices
            foreach (DeviceConfig deviceConfig in lineConfig.DevicePolling)
            {
                if (deviceConfig.Active && !coreLogic.DeviceExists(deviceConfig.DeviceNum))
                {
                    if (driverHolder.GetDriver(deviceConfig.Driver, out DriverLogic driverLogic))
                    {
                        DeviceLogic deviceLogic = driverLogic.CreateDevice(commLine, deviceConfig);

                        if (deviceLogic == null)
                        {
                            throw new ScadaException(Locale.IsRussian ?
                                                     "Не удалось создать устройство {0}." :
                                                     "Unable to create device {0}.", deviceConfig.Title);
                        }

                        commLine.AddDevice(deviceLogic);
                    }
                    else
                    {
                        throw new ScadaException(Locale.IsRussian ?
                                                 "Драйвер {0} для устройства {1} не найден." :
                                                 "Driver {0} for device {1} not found.",
                                                 deviceConfig.Driver, deviceConfig.Title);
                    }
                }
            }

            // prepare channel after adding devices
            commLine.channel.ChannelLogic.MakeReady();

            return(commLine);
        }
Пример #2
0
        /// <summary>
        /// 根据设备id获取token
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public static string GetTokenByDeviceId(string imei)
        {
            Device d = DeviceLogic.GetDeviceByImei(imei);

            if (d == null)
            {
                return("");
            }
            return(GetToken(d.UserId));
        }
Пример #3
0
        /// <summary>
        /// 绑定设备之前先验证设备是符合绑定的条件
        /// </summary>
        /// <param name="user"></param>
        /// <param name="imei"></param>
        /// <returns></returns>
        public static Device preBindDevice(User user, string ip = "1.1.1.1")
        {
            Device _d = DeviceLogic.GetDeviceByUserId(user.Id);

            //验证设备是否存在
            if (!string.IsNullOrWhiteSpace(user.IMEI) && _d == null)
            {
                //需先调用设备接口验证
                DeviceCheckModel dcm = DeviceData.CheckDevice(user.IMEI, user.APIUserId ?? 0);
                if (dcm.State != 0 && dcm.State != 1105)
                {
                    //  res.State = State.Falid;
                    string msg = dcm.Message;
                    //res.Message = msg;
                    //   SaveUserLog(, LogLevel.Error, user.LoginName, "preBindDevice", "绑定该设备");

                    LogQueueInfo queue = new LogQueueInfo();
                    queue.IsSaveDB = true;
                    queue.DbLog    = new WebLog
                    {
                        Content  = user.LoginName + "绑定设备失败:" + msg,
                        Created  = DateTime.Now,
                        UserId   = user.Id,
                        UserName = user.LoginName,
                        LogName  = msg,
                        LogLevel = (int)LogLevel.Sensitive,
                        ClientIp = ip,
                        Method   = "preBindDevice"
                    };
                    HWebQueue.LogQueue.Enqueue(queue);

                    // return Json(res);
                    return(null);
                }
                else
                {
                    //添加设备表
                    Device d = new Device
                    {
                        UserId         = 0,
                        IconId         = 3,
                        Created        = DateTime.Now,
                        Imei           = user.IMEI,
                        Status         = (int)Status.Normal,
                        APIDeviceId    = dcm.DeviceId,
                        APIDeviceModel = dcm.Model
                    };
                    DeviceLogic.SaveDevice(d);
                    // SaveUserLog(AuthUser.LoginName + "为" + user.LoginName + "绑定设备:" + user.IMEI, LogLevel.Error, AuthUser.LoginName, "AjaxEditUser", "绑定设备");
                    return(d);
                }
            }
            return(null);
        }
Пример #4
0
 /// <summary>
 /// Calls the InvalidateData method of the device.
 /// </summary>
 public void InvalidateData()
 {
     try
     {
         DeviceLogic.InvalidateData();
     }
     catch (Exception ex)
     {
         log.WriteException(ex, CommPhrases.ErrorInDevice, nameof(InvalidateData), DeviceLogic.Title);
     }
 }
Пример #5
0
 /// <summary>
 /// Calls the Session method of the device.
 /// </summary>
 public void Session()
 {
     try
     {
         DeviceLogic.Session();
     }
     catch (Exception ex)
     {
         log.WriteException(ex, CommPhrases.ErrorInDevice, nameof(Session), DeviceLogic.Title);
     }
 }
Пример #6
0
 /// <summary>
 /// Calls the SendCommand method of the device.
 /// </summary>
 public void SendCommand(TeleCommand cmd)
 {
     try
     {
         DeviceLogic.SendCommand(cmd);
     }
     catch (Exception ex)
     {
         log.WriteException(ex, CommPhrases.ErrorInDevice, nameof(SendCommand), DeviceLogic.Title);
     }
 }
Пример #7
0
        /// <summary>
        /// 监控页面的获取设备列表
        /// </summary>
        /// <param name="pi"></param>
        /// <param name="pc"></param>
        /// <returns></returns>
        public JsonResult AjaxGetMonitorList(int pi, int pc)
        {
            List <DeviceAndUser> dus = DeviceLogic.GetDeviceList(AuthUser.UserTypeId.Value, AuthUser.Id, pi, pc);
            string deviceIds         = "";

            foreach (var du in dus)
            {
                deviceIds += du.APIDeviceId + ",";
            }
            deviceIds = deviceIds.TrimEnd(',');
            DeviceListModel  list = DeviceData.GetDeviceList(deviceIds, pi, pc);
            DeviceListResult res  = new DeviceListResult();

            res.Items = new List <DeviceInfo>();
            if (list.Items.Count > 0)
            {
                list.Items.ForEach(p =>
                {
                    DeviceAndUser du = dus.FirstOrDefault(t => t.APIDeviceId == p.Id);
                    if (du != null)
                    {
                        DeviceInfo di    = new DeviceInfo();
                        di.Id            = du.DeviceId;
                        di.APIId         = du.APIDeviceId ?? 0;
                        di.Battery       = p.Battery;
                        di.Icon          = du.IconId ?? 0;
                        di.Model         = p.Model;
                        di.IMEI          = du.Imei;
                        di.Latitude      = Convert.ToDecimal(WebHelper.GetLatLngString(p.Latitude));
                        di.Longitude     = Convert.ToDecimal(WebHelper.GetLatLngString(p.Longitude));
                        di.ServerUtcDate = p.ServerUtcDate.AddHours(8);
                        di.DeviceUtcDate = p.DeviceUtcDate.AddHours(8);
                        di.Type          = p.Type;
                        di.Sim           = p.Sim;
                        di.Status        = p.Status;
                        if (DateTime.Now.AddMinutes(-15) < di.ServerUtcDate)
                        {
                            di.Status = 2;
                        }

                        di.UserId   = du.UserId;
                        di.UserName = string.IsNullOrWhiteSpace(du.UserName) ? du.LoginName : du.UserName;
                        di.Sex      = du.Sex ?? 2;
                        res.Items.Add(di);
                    }
                });
            }
            else
            {
                res.State   = State.Falid;
                res.Message = list.Message;
            }
            return(Json(res));
        }
Пример #8
0
 /// <summary>
 /// Calls the OnCommLineTerminate method of the device.
 /// </summary>
 public void OnCommLineTerminate()
 {
     try
     {
         DeviceLogic.OnCommLineTerminate();
     }
     catch (Exception ex)
     {
         log.WriteException(ex, CommPhrases.ErrorInDevice, nameof(OnCommLineTerminate), DeviceLogic.Title);
     }
 }
Пример #9
0
 /// <summary>
 /// Calls the OnCommLineStart method of the device.
 /// </summary>
 public void OnCommLineStart()
 {
     try
     {
         DeviceLogic.OnCommLineStart();
     }
     catch (Exception ex)
     {
         log.WriteError(ex, CommPhrases.ErrorInDevice, nameof(OnCommLineStart), DeviceLogic.Title);
     }
 }
Пример #10
0
 /// <summary>
 /// Calls the BeforeSession method of the communication channel.
 /// </summary>
 public void BeforeSession(DeviceLogic deviceLogic)
 {
     try
     {
         ChannelLogic.BeforeSession(deviceLogic);
     }
     catch (Exception ex)
     {
         log.WriteException(ex, CommPhrases.ErrorInChannel, nameof(BeforeSession), ChannelLogic.Title);
     }
 }
Пример #11
0
 /// <summary>
 /// Calls the InitDeviceTags method of the device.
 /// </summary>
 public void InitDeviceTags()
 {
     try
     {
         DeviceLogic.InitDeviceTags();
     }
     catch (Exception ex)
     {
         log.WriteException(ex, CommPhrases.ErrorInDevice, nameof(InitDeviceTags), DeviceLogic.Title);
     }
 }
Пример #12
0
        /// <summary>
        /// Performs actions before polling the specified device.
        /// </summary>
        public override void BeforeSession(DeviceLogic deviceLogic)
        {
            if (Behavior == ChannelBehavior.Slave)
            {
                Monitor.Enter(serialConn.SyncRoot);
            }

            if (!serialConn.Connected)
            {
                OpenSerialPort();
            }
        }
Пример #13
0
        /// <summary>
        /// Performs actions after polling the specified device.
        /// </summary>
        public override void AfterSession(DeviceLogic deviceLogic)
        {
            if (serialConn.Connected && serialConn.WriteError)
            {
                CloseSerialPort();
            }

            if (Behavior == ChannelBehavior.Slave)
            {
                Monitor.Exit(serialConn.SyncRoot);
            }
        }
Пример #14
0
 /// <summary>
 /// Gets the device by device number.
 /// </summary>
 bool ILineContext.GetDevice(int deviceNum, out DeviceLogic deviceLogic)
 {
     if (deviceMap.TryGetValue(deviceNum, out DeviceWrapper deviceWrapper))
     {
         deviceLogic = deviceWrapper.DeviceLogic;
         return(true);
     }
     else
     {
         deviceLogic = null;
         return(true);
     }
 }
Пример #15
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            DeviceLogic dl = new DeviceLogic();

            if (!dl.newDevice(int.Parse(inputCodeDevice.Text), inputName.Text, double.Parse(inputFacilityCost.Text), inputFreightCompany.Text, 1111, inputDetails.Text))
            {
                Label2.Text = "The code is already exist";
            }
            else
            {
                Label2.Text = "you have successfuly add a new dvice!";
            }
        }
Пример #16
0
        /// <summary>
        /// Binds the device to the connection.
        /// </summary>
        public void BindDevice(DeviceLogic deviceLogic)
        {
            if (deviceLogic != null)
            {
                deviceLogic.Connection = this;

                lock (boundDevices)
                {
                    boundDevices.Add(deviceLogic);
                    devicesCopy = null;
                }
            }
        }
Пример #17
0
 public DeviceListWindow()
 {
     try
     {
         InitializeComponent();
         dt = DeviceLogic.GetDeviceList(DeviceEnum.None, "");
         DeviceList.ItemsSource = dt.DefaultView;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Пример #18
0
 /// <summary>
 /// Performs actions after polling the specified device.
 /// </summary>
 public override void AfterSession(DeviceLogic deviceLogic)
 {
     if (Behavior == ChannelBehavior.Master)
     {
         if (deviceLogic.DeviceStatus == DeviceStatus.Error)
         {
             masterConn.ClearDatagramBuffer();
         }
     }
     else
     {
         Monitor.Exit(deviceLock);
     }
 }
Пример #19
0
 /// <summary>
 /// Calls the BindDeviceTags method of the device.
 /// </summary>
 public void BindDeviceTags(ConfigDataset configDataset)
 {
     try
     {
         if (DeviceLogic.IsBound && configDataset != null)
         {
             DeviceLogic.BindDeviceTags(configDataset);
         }
     }
     catch (Exception ex)
     {
         log.WriteError(ex, CommPhrases.ErrorInDevice, nameof(BindDeviceTags), DeviceLogic.Title);
     }
 }
Пример #20
0
        /// <summary>
        /// 请求用户的健康数据
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public JsonResult AjaxGetHealthInfo(int deviceId)
        {
            Device d = DeviceLogic.GetDeviceById(deviceId);

            if (d == null)
            {
                return(Json(new BaseResult {
                    State = State.NotFind, Message = "未找到该设备"
                }));
            }
            HealthInfoModel model = HealthData.GetHealthInfo(d.APIDeviceId ?? 0);

            return(Json(new { State = State.Success, Item = model }));
        }
Пример #21
0
 /// <summary>
 /// Calls the BindDeviceTags method of the device.
 /// </summary>
 public void BindDeviceTags(BaseDataSet baseDataSet)
 {
     try
     {
         if (DeviceLogic.IsBound && baseDataSet != null)
         {
             DeviceLogic.BindDeviceTags(baseDataSet);
         }
     }
     catch (Exception ex)
     {
         log.WriteException(ex, CommPhrases.ErrorInDevice, nameof(BindDeviceTags), DeviceLogic.Title);
     }
 }
Пример #22
0
        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="imei"></param>
        /// <returns></returns>
        public JsonResult AjaxAddDevice(string imei)
        {
            BaseResult res = new BaseResult();

            Device _d = DeviceLogic.GetDeviceByImei(imei);

            //验证设备是否存在
            if (_d == null)
            {
                //需先调用设备接口验证
                DeviceCheckModel dcm = DeviceData.CheckDevice(imei, 1);
                if (dcm.State != 0 && dcm.State != 1105)
                {
                    //  res.State = State.Falid;
                    string msg = dcm.Message;
                    res.Message = msg;
                    res.State   = State.Falid;
                    //res.Message = msg;
                    SaveUserLog(AuthUser.LoginName + "添加设备失败:" + msg, LogLevel.Error, AuthUser.LoginName, "AjaxAddDevice", "添加设备");
                    // return Json(res);;
                }
                else
                {
                    //添加设备表
                    Device d = new Device
                    {
                        UserId         = 0,
                        IconId         = 3,
                        Created        = DateTime.Now,
                        Imei           = imei,
                        Status         = (int)Status.Normal,
                        APIDeviceId    = dcm.DeviceId,
                        APIDeviceModel = dcm.Model
                    };
                    DeviceLogic.SaveDevice(d);
                    SaveUserLog(AuthUser.LoginName + "添加了设备:" + imei, LogLevel.Info, AuthUser.LoginName, "AjaxAddDevice", "添加设备");
                    res.State   = State.Success;
                    res.Message = "添加成功";
                    //return Json(res);
                }
            }
            else
            {
                res.State   = State.DeviceIn;
                res.Message = "设备已存在";
            }

            return(Json(res));
        }
Пример #23
0
 /// <summary>
 /// Calls the AfterSession method of the communication channel.
 /// </summary>
 public void AfterSession(DeviceLogic deviceLogic)
 {
     try
     {
         ChannelLogic.AfterSession(deviceLogic);
     }
     catch (ScadaException ex)
     {
         log.WriteError(ex.Message);
     }
     catch (Exception ex)
     {
         log.WriteException(ex, CommPhrases.ErrorInChannel, nameof(AfterSession), ChannelLogic.Title);
     }
 }
Пример #24
0
        private void StartDevices()
        {
            _mOut = DeviceLogic.InitMidiOut(_midiOIndex);
            _mIn  = DeviceLogic.InitMidiIn(_midiIIndex);

            //Register for containers
            _container.RegisterInstance(_mOut);
            _container.RegisterInstance(_mIn);

            DeviceEnable  = false;
            DeviceDisable = true;

            _ea.GetEvent <InitializedEvent>().Publish(true);
            UpdateStatus("Devices Enabled...");
        }
Пример #25
0
        /// <summary>
        /// Performs actions before polling the specified device.
        /// </summary>
        public override void BeforeSession(DeviceLogic deviceLogic)
        {
            currentConn = deviceLogic.Connection as TcpConnection;

            if (currentConn != null)
            {
                if (Behavior == ChannelBehavior.Slave)
                {
                    Monitor.Enter(currentConn.SyncRoot);
                }

                // connect if disconnected
                if (!currentConn.Connected)
                {
                    // get host and port
                    string host;
                    int    port;

                    if (currentConn == sharedConn)
                    {
                        host = options.Host;
                        port = options.TcpPort;
                    }
                    else if (currentConn.RemotePort > 0)
                    {
                        host = currentConn.RemoteAddress;
                        port = currentConn.RemotePort;
                    }
                    else
                    {
                        ScadaUtils.RetrieveHostAndPort(deviceLogic.StrAddress, options.TcpPort, out host, out port);
                    }

                    // connect
                    Log.WriteLine();
                    Log.WriteAction(Locale.IsRussian ?
                                    "Соединение с {0}:{1}" :
                                    "Connect to {0}:{1}", host, port);

                    if (currentConn.NetStream != null) // connection was already open but broken
                    {
                        currentConn.Renew();
                    }

                    currentConn.Open(host, port);
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Calls the InitDeviceTags method of the device.
        /// </summary>
        public void InitDeviceTags()
        {
            try
            {
                DeviceLogic.InitDeviceTags();

                if (DeviceLogic.DeviceTags.UseStatusTag)
                {
                    DeviceLogic.DeviceTags.AddStatusTag();
                }
            }
            catch (Exception ex)
            {
                log.WriteError(ex, CommPhrases.ErrorInDevice, nameof(InitDeviceTags), DeviceLogic.Title);
            }
        }
Пример #27
0
 /// <summary>
 /// Processes the incoming request just read for the specified device.
 /// </summary>
 protected bool ProcessIncomingRequest(DeviceLogic deviceLogic, byte[] buffer, int offset, int count,
                                       IncomingRequestArgs requestArgs)
 {
     try
     {
         deviceLogic.ProcessIncomingRequest(buffer, offset, count, requestArgs);
         return(!requestArgs.HasError);
     }
     catch (Exception ex)
     {
         Log.WriteException(ex, Locale.IsRussian ?
                            "Ошибка при обработке входящего запроса КП {0}" :
                            "Error processing incoming request for the device {0}", deviceLogic.Title);
         return(false);
     }
 }
Пример #28
0
 /// <summary>
 /// Receives an unread incoming request for the specified device.
 /// </summary>
 protected bool ReceiveIncomingRequest(DeviceLogic deviceLogic, Connection conn,
                                       IncomingRequestArgs requestArgs)
 {
     try
     {
         deviceLogic.ReceiveIncomingRequest(conn, requestArgs);
         return(!requestArgs.HasError);
     }
     catch (Exception ex)
     {
         Log.WriteException(ex, Locale.IsRussian ?
                            "Ошибка при приёме входящего запроса КП {0}" :
                            "Error receiving incoming request for the device {0}", deviceLogic.Title);
         return(false);
     }
 }
Пример #29
0
 /// <summary>
 /// Writes device information to the file.
 /// </summary>
 public void WriteInfo()
 {
     try
     {
         using (StreamWriter writer = new StreamWriter(InfoFileName, false, Encoding.UTF8))
         {
             writer.Write(DeviceLogic.GetInfo());
         }
     }
     catch (Exception ex)
     {
         log.WriteException(ex, Locale.IsRussian ?
                            "Ошибка при записи в файл информации о работе КП {0}" :
                            "Error writing device {0} information to the file", DeviceLogic.Title);
     }
 }
Пример #30
0
 /// <summary>
 /// Performs actions after polling the specified device.
 /// </summary>
 public override void AfterSession(DeviceLogic deviceLogic)
 {
     if (currentConn != null)
     {
         if (Behavior == ChannelBehavior.Master)
         {
             if (deviceLogic.DeviceStatus == DeviceStatus.Error && currentConn.Connected)
             {
                 currentConn.ClearNetStream(inBuf);
             }
         }
         else
         {
             Monitor.Exit(currentConn.SyncRoot);
         }
     }
 }