public IHttpActionResult CreateDevice(DeviceModel model)
 {
     if (!ModelState.IsValid)
     {
         return BadRequest(ModelState);
     }
     ClientPort.Tell(model.BuildImmutable());
     return Ok();
 }
        public List<TrackingModel> GetData(DeviceModel device, DateTime date)
        {
            MongoCollection<TrackingModel> dataDb = Tools.MongoConnector.Instance.DataBaseReadOnly.GetCollection<TrackingModel>(TRACKING_DB_NAME);

            List<TrackingModel>  result = (from d in dataDb.AsQueryable<TrackingModel>()
                      where d.DeviceID == device.Id && d.RecordedDateKey == date.GenerateKey()
                      select d).ToList();

            return result;
        }
        private static string GetDeviceModelName(DeviceModel deviceModel, Match deviceModelMatch)
        {
            if (deviceModel.Model.Contains("$"))
            {
                var capturingGroups = Regex.Matches(deviceModel.Model, @"\$\d")
                                      .Cast <Match>()
                                      .Select(m => m.Value)
                                      .Aggregate(deviceModel.Model, (modelName, capturingGroup) =>
                {
                    return(modelName.Replace(capturingGroup, deviceModelMatch.GetCapturingGroupValue(capturingGroup)));
                });
                return(capturingGroups);
            }

            return(deviceModel.Model);
        }
        public ActionResult DeviceModelEdit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DeviceModel deviceModel = db.DeviceModels.Find(id);

            if (deviceModel == null)
            {
                return(HttpNotFound());
            }
            ViewBag.DeviceTypeId   = new SelectList(db.DeviceTypes, "DeviceTypeId", "Name", deviceModel.DeviceTypeId);
            ViewBag.ManufacturerId = new SelectList(db.Manufacturers, "ManufacturerId", "Name", deviceModel.ManufacturerId);
            return(View(deviceModel));
        }
        /// <summary>
        /// Create or replace a device model.
        /// </summary>
        public async Task <DeviceModel> UpsertAsync(DeviceModel deviceModel)
        {
            if (this.CheckStockDeviceModelExistence(deviceModel.Id))
            {
                this.log.Error("Stock device models cannot be updated",
                               () => new { deviceModel });
                throw new ConflictingResourceException(
                          "Stock device models cannot be updated");
            }

            var result = await this.customDeviceModels.UpsertAsync(deviceModel);

            deviceModel.ETag = result.ETag;

            return(deviceModel);
        }
Example #6
0
        public DisconnectTest(ITestOutputHelper log)
        {
            this.logger                = new Mock <ILogger>();
            this.devices               = new Mock <IDevices>();
            this.scriptInterpreter     = new Mock <IScriptInterpreter>();
            this.rateLimitingConfig    = new Mock <IRateLimitingConfig>();
            this.deviceStateActor      = new Mock <IDeviceStateActor>();
            this.deviceConnectionActor = new Mock <IDeviceConnectionActor>();
            this.deviceClient          = new Mock <IDeviceClient>();
            this.loopSettings          = new Mock <ConnectionLoopSettings>(this.rateLimitingConfig.Object);
            this.deviceModel           = new DeviceModel {
                Id = DEVICE_ID
            };

            this.target = new Disconnect(this.devices.Object, this.scriptInterpreter.Object, this.logger.Object);
        }
Example #7
0
        private async void GetCodeAfromViewModel()
        {
            var device = new DeviceModel
            {
                AndroidIDmacHash = "dfdsfreSFDFas",
                TypeDeviceID     = 1,
                codeA            = 0,
                codeB            = 0,
                Name             = "android",
                Token            = "token"
            };

            Pair pair = await pairViewModel.GetCodeATestingOnly(device);

            label_code.Text = pair.CodeA.ToString();
        }
        // Redefine the interval at which the device state is generated
        private void SetSimulationInterval(TimeSpan?interval, DeviceModel result)
        {
            if (interval == null || result.Simulation.Interval.ToString("c") == interval.Value.ToString("c"))
            {
                return;
            }

            this.log.Debug("Overriding device state simulation frequency",
                           () => new
            {
                Original = result.Simulation.Interval.ToString("c"),
                NewValue = interval.Value.ToString("c")
            });

            result.Simulation.Interval = interval.Value;
        }
        protected async override Task RunTest()
        {
            DeviceModel device = new DeviceModel()
            {
                Id = 1
            };
            var scanModels = m_scanGenerator.Run(device, m_wifiDevices, m_bluetoothDevices);

            Console.WriteLine("Scan Models {0}", scanModels.Count);

            var batchModels = ScanServiceClient.CreateScanBatchModels(scanModels, 5);
            ServiceEndpointLoad <ScanBatchModel> load = new ServiceEndpointLoad <ScanBatchModel>("Cluster Data", batchModels, SB =>
                                                                                                 m_scanServiceClient.InsertScanBatchAsync(SB));

            await load.Run();
        }
        public void Edit(DeviceModel vm)
        {
            DeviceData data          = new DeviceData(_config);
            var        updatedDevice = new DeviceModel()
            {
                Id                = vm.Id,
                Hostname          = vm.Hostname,
                IpAddress         = vm.IpAddress,
                MACAddress        = vm.MACAddress,
                Vendor            = vm.Vendor,
                UserId            = vm.UserId,
                DeviceDescription = vm.DeviceDescription
            };

            data.Edit(updatedDevice);
        }
        public async Task Add([FromBody] DeviceModel model)
        {
            DeviceData data = new DeviceData(_config);

            var device = new DeviceModel()
            {
                Hostname          = model.Hostname,
                IpAddress         = model.IpAddress,
                MACAddress        = model.MACAddress,
                Vendor            = model.Vendor,
                UserId            = model.UserId,
                DeviceDescription = model.DeviceDescription
            };

            data.Add(model);
        }
 private List <DeviceModel> WriteObjectsToList(List <DeviceModel> devices, string filepath)
 {
     using var reader = new StreamReader(filepath);
     reader.ReadLine();
     while (!reader.EndOfStream)
     {
         var line = reader.ReadLine();
         if (line != null)
         {
             var         values = line.Split(',');
             DeviceModel device = FormatStringToDeviceObject(values);
             devices.Add(device);
         }
     }
     return(devices);
 }
        public ActionResult Finish(QuotationModel model, DeviceModel m, string sNum, string IDnum)
        {
            TempData.Keep();
            //model.Name = TempData["SerialNumber"].ToString();
            //model.Status = TempData["status"].ToString();

            model.IdentityNumber = sNum;
            //quote.technician = TempData["technician"].ToString();
            //quote.IdentityNumber = TempData["IdentityNumber"].ToString();

            //m.customerIdNumber = TempData["IdentityNumber"].ToString();



            return(View());
        }
        public async Task RemoveDeviceAsync(string deviceId)
        {
            if (string.IsNullOrEmpty(deviceId))
            {
                throw new ArgumentNullException(nameof(deviceId));
            }

            DeviceModel existingDevice = await GetDeviceAsync(deviceId);

            if (existingDevice == null)
            {
                throw new DeviceNotRegisteredException(deviceId);
            }

            await _documentClient.DeleteAsync(existingDevice.id);
        }
Example #15
0
 public String Create(DeviceModel deviceModel)
 {
     using (var connection = new MySqlConnection(Constant.getDatabaseConnectionString()))
     {
         CityModel city = connection.Query <CityModel>(
             "SELECT * FROM city WHERE city.cityName=@cn", new
         {
             cn = deviceModel.City
         }).FirstOrDefault();
         FactoryModel factory = connection.Query <FactoryModel>(
             "SELECT * FROM factory WHERE factory.factoryName=@fn", new
         {
             fn = deviceModel.Factory
         }).FirstOrDefault();
         WorkshopModel workshop = connection.Query <WorkshopModel>(
             "SELECT * FROM workshop WHERE workshop.workshopName=@wn", new
         {
             wn = deviceModel.Workshop
         }).FirstOrDefault();
         GatewayModel gateway = connection.Query <GatewayModel>("select * from gateway where gatewayName=@gn",
                                                                new { gn = deviceModel.GatewayId }).FirstOrDefault();
         int deviceType = connection.Query <int>(
             "select id from config where configTag=@ct and configValue=@cv", new
         {
             ct = "deviceType",
             cv = deviceModel.DeviceType
         }).FirstOrDefault();
         int rows = connection.Execute(
             "INSERT INTO " +
             "device(hardwareDeviceID, deviceName, city, factory, workshop, deviceState, imageUrl, gatewayId, mac, deviceType, remark)" +
             " VALUES (@hdid, @dn, @c, @f, @w, @ds, @iu, @gid, @m, @dt, @r)", new
         {
             hdid = deviceModel.HardwareDeviceId,
             dn   = deviceModel.DeviceName,
             c    = city.Id,
             f    = factory.Id,
             w    = workshop.Id,
             ds   = deviceModel.DeviceState,
             iu   = deviceModel.ImageUrl,
             gid  = gateway.Id,
             m    = deviceModel.Mac,
             dt   = deviceType,
             r    = deviceModel.Remark
         });
         return(rows == 1 ? "success" : "error");
     }
 }
Example #16
0
        //修改设备的位置信息
        public ResponseData UpdateDevicePosition(DeviceViewModel dvm)
        {
            ResponseData rd = new ResponseData();
            //获取设备信息
            DeviceModel dm = _dr.Find(dvm.DeviceSn, dvm.Token);

            if (dm == null)
            {
                rd.Success = false;
                rd.Message = "不存在此设备,请确认";
                return(rd);
            }
            #region 验证用户权限
            bool bRet = CheckDeviceAuth(dm, dvm.Account, dvm.Token, 2);
            //int pid = dm.PId;//获取设备所属的项目(一级项目)
            //if (pid == 0)//设备没有添加所属的一级项目,此时需要递归获取一级项目编号
            //{
            //    pid = dm.ProjectId.Value;
            //    bRet = new UserService().IsAuthProject(dvm.Account, dvm.Token, pid, 2);//获取用户是否有权限修改设备信息
            //}
            //else
            //{
            //    bRet = new UserService().IsAuthProject(dvm.Account, dvm.Token, pid, 2, 0);//获取用户是否有权限修改设备信息(此时的项目编号为一级项目编号)
            //}
            if (!bRet)
            {
                rd.Success = false;
                rd.Message = "用户没有权限修改设备位置信息";
                return(rd);
            }
            #endregion
            #region 修改设备的位置信息
            dm.Position = dvm.Position;
            try
            {
                _dr.Save(dm);
                rd.Success = true;
                rd.Message = "修改设备位置信息成功";
            }
            catch (Exception ex)
            {
                rd.Success = false;
                rd.Message = "修改设备位置信息失败" + ex.Message;
            }
            #endregion
            return(rd);
        }
Example #17
0
        public void Run()
        {
            IDictionary <int, DeviceModel> _currentDeviceModels = new Dictionary <int, DeviceModel>();
            IList <ScanModel> _scanModels = new List <ScanModel>();

            List <GowallaCheckIn> CheckIns = FileParser.ReadGowallaCheckIns(DATA_SIZE);

            foreach (GowallaCheckIn CheckIn in CheckIns)
            {
                if (!_currentDeviceModels.ContainsKey(CheckIn.Id))
                {
                    DeviceModel model = new DeviceModel()
                    {
                        Id            = CheckIn.Id,
                        Model         = GetFakeModel(),
                        BluetoothName = GetFakeBleName(),
                        MacAddress    = GetFakeMacAddress(),
                        Manufacturer  = GetFakeManufacturer()
                    };

                    _currentDeviceModels.Add(CheckIn.Id, model);
                }

                ScanModel scanModel = new ScanModel()
                {
                    BluetoothDevices      = new List <BluetoothDeviceModel>(),
                    WifiDevices           = new List <WifiDeviceModel>(),
                    GlobalConfigurationId = 1,
                    DateTime   = CheckIn.DateTime,
                    DeviceId   = CheckIn.Id,
                    Kinematics = new KinematicsModel
                    {
                        Latitude  = CheckIn.Latitude,
                        Longitude = CheckIn.Longitude
                    }
                };

                _scanModels.Add(scanModel);
            }

            FileParser.WriteDevices(_currentDeviceModels.Values);

            FileParser.WriteScans(_scanModels);

            Console.WriteLine("Found {0} devices", _currentDeviceModels.Count);
            Console.WriteLine("Found {0} scans", _scanModels.Count);
        }
Example #18
0
        private void AddDeviceCommandExecute()
        {
            List <DeviceModel> lDevicesTemp = new List <DeviceModel>(lDevices);

            if (string.IsNullOrEmpty(NameDevice) || string.IsNullOrEmpty(Uuid) || string.IsNullOrEmpty(UuidService))
            {
                Application.Current.MainPage.DisplayAlert("Atención", "Debe rellenar los campos obligatorios", "Aceptar");
            }
            else if (!Modify && lDevicesTemp.Find(d => d.Name.Equals(NameDevice)) != null)
            {
                Application.Current.MainPage.DisplayAlert("Atención", "Ya existe un dispositivo con el mismo nombre", "Aceptar");
            }
            else
            {
                string regexUuid = "[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}";

                if (!Regex.IsMatch(Uuid, regexUuid))
                {
                    Application.Current.MainPage.DisplayAlert("Atención", "El UUID del dispositivo no cumple con el formato", "Aceptar");
                    return;
                }

                if (!Regex.IsMatch(UuidService, regexUuid))
                {
                    Application.Current.MainPage.DisplayAlert("Atención", "El UUID del servicio no cumple con el formato", "Aceptar");
                    return;
                }

                if (!Regex.IsMatch(UuidCharacteristic, regexUuid))
                {
                    Application.Current.MainPage.DisplayAlert("Atención", "El UUID de la característica no cumple con el formato", "Aceptar");
                    return;
                }

                DeviceModel newDevice = new DeviceModel();
                newDevice.Name           = NameDevice;
                newDevice.Uuid           = Uuid;
                newDevice.Service        = UuidService;
                newDevice.Characteristic = UuidCharacteristic;
                newDevice.State          = DeviceState.Disconnected.ToString();
                lDevices.Add(newDevice);
                NameDevice         = null;
                Uuid               = null;
                UuidService        = null;
                UuidCharacteristic = null;
            }
        }
Example #19
0
        }//关闭设备

        private async void BtnAddZigBee_Click(object sender, RoutedEventArgs e)
        {
            #region 配置串口
            var selection = ConnectDevices.SelectedItems;
            if (selection.Count <= 0)
            {
                return;
            }

            DeviceInformation entry = (DeviceInformation)selection[0];

            try
            {
                serialPort = await SerialDevice.FromIdAsync(entry.Id);

                if (serialPort == null)
                {
                    return;
                }
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate     = 9600;
                serialPort.Parity       = SerialParity.None;
                serialPort.StopBits     = SerialStopBitCount.One;
                serialPort.DataBits     = 8;
                serialPort.Handshake    = SerialHandshake.None;
                // Create cancellation token object to close I/O operations when closing the device
                ReadCancellationTokenSource = new CancellationTokenSource();
                Listen();
            }
            catch (Exception)
            { }
            #endregion

            DeviceModel Device = new DeviceModel
            {
                NetPort   = await DevicesMethod.GetPortNum() + 1,
                Type      = "照明系统",
                IPAddress = "Zigbee设备"
            };
            ViewDevModel DevObj = ModelConverter.DataToView(Device);
            Obj.Add(Device);
            DevicesMethod.UpdateDevices(Obj);
            gridView.Items.Add(DevObj);
            CreateLine(Device.NetPort);//绑定新通道
            btnAddZigBee.IsEnabled = false;
        }
Example #20
0
        async Task SaveContent(DeviceModel content)
        {
            try
            {
                var json = JObject.Parse(JsonConvert.SerializeObject(content));

                json["apiKey"] = "API KEY";
                if (App.IsConnected)
                {
                    var results = await _networkService.PostAsync
                                      (json, $"URL");

                    if (results != null)
                    {
                        int result = (int)results["result"];
                        if (result == 1)
                        {
                            if (content.ID != 0)
                            {
                                _db.DeleteInput(content);
                            }
                            IsBusy = false;
                            _dialog.ShowToastMessage("Data Submitted", true);
                            return;
                        }
                        else
                        {
                            _dialog.ShowToastMessage(results["message"].ToString(), true);
                        }
                    }
                    else
                    {
                        _dialog.ShowToastMessage("Something went wrong", true);
                    }
                    _db.SaveInput(content);
                }
                else
                {
                    _db.SaveInput(content);
                    _dialog.ShowToastMessage("Data Saved for offline Sync", true);
                }
            }
            catch (Exception ex)
            {
                Utils.Utility.ShowDebug(ex);
            }
        }
Example #21
0
        private async Task <DeviceWithKeys> AddDeviceAsync(UnregisteredDeviceModel unregisteredDeviceModel)
        {
            Debug.Assert(
                unregisteredDeviceModel != null,
                "unregisteredDeviceModel is a null reference.");

            Debug.Assert(
                unregisteredDeviceModel.DeviceType != null,
                "unregisteredDeviceModel.DeviceType is a null reference.");

            DeviceModel device = DeviceCreatorHelper.BuildDeviceStructure(unregisteredDeviceModel.DeviceId,
                                                                          unregisteredDeviceModel.DeviceType.IsSimulatedDevice, unregisteredDeviceModel.Iccid);

            DeviceWithKeys addedDevice = await this._deviceLogic.AddDeviceAsync(device);

            return(addedDevice);
        }
Example #22
0
 public void Edit(DeviceModel device)
 {
     using (SqlConnection con = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB; " +
                                                  "Initial Catalog=IoTCybersecurityDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;" +
                                                  "ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
         using (SqlCommand cmd = new SqlCommand("dbo.spEditDeviceLookup", con))
         {
             cmd.CommandType = CommandType.StoredProcedure;
             cmd.Parameters.Add("@PrimaryKey", SqlDbType.NVarChar);
             cmd.Parameters["@PrimaryKey"].Value = device.Id;
             cmd.Parameters.AddWithValue("devicedescription", device.DeviceDescription);
             // open connection, execute command, close connection
             con.Open();
             cmd.ExecuteNonQuery();
             con.Close();
         }
 }
Example #23
0
        }//向云上传数据

        #endregion

        #region 设备模型相关

        private async void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            string[] data = cmbIp.SelectedItem.ToString().Trim().Split(Convert.ToChar("/"));

            DeviceModel Device = new DeviceModel {
                NetPort   = await DevicesMethod.GetPortNum() + 1,
                Type      = data[1],
                IPAddress = data[0]
            };
            ViewDevModel DevObj = ModelConverter.DataToView(Device);

            Obj.Add(Device);
            DevicesMethod.UpdateDevices(Obj);
            gridView.Items.Add(DevObj);
            CreateLine(Device.NetPort); //绑定新通道
            SendAllow(Device.NetPort);  //发送端口允许
        }
Example #24
0
        public MainWindowViewModel()
        {
            _disposables           = new CompositeDisposable();
            _connectionDisposables = new CompositeDisposable();

            VideoPlayer         = new VideoPlayerModel().AddTo(_disposables);
            ConnectedDevice     = new DeviceModel();
            SelectDeviceCommand = new ReactiveCommand().AddTo(_disposables);
            SelectDeviceCommand.Delay(new TimeSpan(100)).ObserveOnUIDispatcher().SelectMany(_ => DialogHost.Show(new DeviceSelectDialog(), OnSelectDeviceDialogClosing).ToObservable())
            .Subscribe(async(result) => await ConnenctDevice(result as DiscoverResult)).AddTo(_disposables);

            _viewMode    = new BehaviorSubject <ViewMode>(ViewMode.None).AddTo(_disposables);
            IsModeRec    = new ReactiveProperty <bool>().AddTo(_disposables);
            IsModeLive   = new ReactiveProperty <bool>().AddTo(_disposables);
            IsModeInput  = new ReactiveProperty <bool>().AddTo(_disposables);
            IsModeOutput = new ReactiveProperty <bool>().AddTo(_disposables);
            _viewMode.DistinctUntilChanged().Subscribe(m => {
                IsModeRec.Value    = (m == ViewMode.Rec);
                IsModeLive.Value   = (m == ViewMode.Live);
                IsModeInput.Value  = (m == ViewMode.Input);
                IsModeOutput.Value = (m == ViewMode.Output);
            }).AddTo(_disposables);
            IsModeRec.Where(b => b).Subscribe(async(_) => await ToRecMode()).AddTo(_disposables);
            IsModeLive.Where(b => b).Subscribe(async(_) => await ToLiveMode()).AddTo(_disposables);
            IsModeInput.Where(b => b).Subscribe(async(_) => await ToInputMode()).AddTo(_disposables);
            IsModeOutput.Where(b => b).Subscribe(async(_) => await ToOutputMode()).AddTo(_disposables);
            _viewMode.OnNext(ViewMode.Output);

            SliderValue = new[] {
                new ReactiveProperty <double>(1.0).AddTo(_disposables),
                new ReactiveProperty <double>(0.0).AddTo(_disposables),
                new ReactiveProperty <double>(0.0).AddTo(_disposables),
                new ReactiveProperty <double>(0.0).AddTo(_disposables)
            };
            SliderMaximum  = new ReactiveProperty <double>(1.0).AddTo(_disposables);
            IsSliderActive = new[] {
                new ReactiveProperty <bool>(true).AddTo(_disposables),
                new ReactiveProperty <bool>(false).AddTo(_disposables),
                new ReactiveProperty <bool>(false).AddTo(_disposables),
                new ReactiveProperty <bool>(false).AddTo(_disposables)
            };
            SliderValue[0].Subscribe(async(value) => await OnSliderValueChanged(0, value)).AddTo(_disposables);
            SliderValue[1].Subscribe(async(value) => await OnSliderValueChanged(1, value)).AddTo(_disposables);
            SliderValue[2].Subscribe(async(value) => await OnSliderValueChanged(2, value)).AddTo(_disposables);
            SliderValue[3].Subscribe(async(value) => await OnSliderValueChanged(3, value)).AddTo(_disposables);
        }
Example #25
0
        public Point GetFreeRoomPositionForRect(Rect rect)
        {
            DeviceModel overlappingDM = GetFirstOverlappingDevice(rect);

            if (overlappingDM == null)
            {
                return(new Point(rect.X, rect.Y));
            }
            else
            {
                return(GetFreeRoomPositionForRect(new Rect(
                                                      overlappingDM.PixelRight,
                                                      overlappingDM.PixelTop,
                                                      rect.Width,
                                                      rect.Height)));
            }
        }
Example #26
0
        internal int GetAvailableDeviceQuantities(DeviceModel dummy)
        {
            SqlConnection con = new SqlConnection(connectionString);

            con.Open();
            SqlCommand cmd = new SqlCommand("GetModelDeviceQuantityAvailable", con);

            cmd.CommandType = System.Data.CommandType.StoredProcedure;

            SqlDataReader reader = cmd.ExecuteReader();

            //set quantity from query
            int quantity = (int)reader["QuantityOfAvailableDevices"];

            con.Close();
            return(quantity);
        }
Example #27
0
        /**
         * For each device create one actor to periodically update the internal state,
         * one actor to manage the connection to the hub, and one actor for each
         * telemetry message to send.
         */
        private void CreateActorsForDevice(DeviceModel deviceModel, int position, int total, string deviceId = null)
        {
            var id  = deviceId ?? this.devices.GenerateId(deviceModel.Id, position);
            var key = deviceId ?? deviceModel.Id + "#" + position;

            this.log.Debug("Creating device actors...",
                           () => new { ModelName = deviceModel.Name, ModelId = deviceModel.Id, position });

            // Create one state actor for each device
            var deviceStateActor = this.factory.Resolve <IDeviceStateActor>();

            deviceStateActor.Setup(id, deviceModel, position, total);
            this.deviceStateActors.Add(key, deviceStateActor);

            // Create one connection actor for each device
            var deviceConnectionActor = this.factory.Resolve <IDeviceConnectionActor>();

            deviceConnectionActor.Setup(id, deviceModel, deviceStateActor, this.connectionLoopSettings);
            this.deviceConnectionActors.Add(key, deviceConnectionActor);

            // Create one device properties actor for each device
            var devicePropertiesActor = this.factory.Resolve <IDevicePropertiesActor>();

            devicePropertiesActor.Setup(id, deviceStateActor, deviceConnectionActor, this.propertiesLoopSettings);
            this.devicePropertiesActors.Add(key, devicePropertiesActor);

            // Create one telemetry actor for each telemetry message to be sent
            var i = 0;

            foreach (var message in deviceModel.Telemetry)
            {
                // Skip telemetry without an interval set
                if (!(message.Interval.TotalMilliseconds > 0))
                {
                    this.log.Warn("Skipping telemetry with interval = 0",
                                  () => new { model = deviceModel.Id, message });
                    continue;
                }

                var deviceTelemetryActor = this.factory.Resolve <IDeviceTelemetryActor>();
                deviceTelemetryActor.Setup(id, deviceModel, message, deviceStateActor, deviceConnectionActor);

                var actorKey = key + "#" + (i++).ToString();
                this.deviceTelemetryActors.Add(actorKey, deviceTelemetryActor);
            }
        }
Example #28
0
        private async Task ConnenctDevice(DiscoverResult result)
        {
            await VideoPlayer.StopVideo();

            _connectionDisposables.Clear();
            ConnectedDevice.Dispose();
            ConnectedDevice = new DeviceModel();
            if (result == null)
            {
                return;
            }

            var oldViewMode = _viewMode.Value;
            var nextDevice  = new DeviceModel(result);

            nextDevice.ModeChanged.Subscribe(async(_) => await OnDeviceModeChanged()).AddTo(_connectionDisposables);
            nextDevice.PreviewModeChanged.Subscribe(async(_) => await OnDeviceModeChanged()).AddTo(_connectionDisposables);
            nextDevice.VideoSwitcherStatusChanged.Subscribe(OnVideoSwitcherStatusChanged).AddTo(_connectionDisposables);
            await nextDevice.Connect();

            if (nextDevice.IsConnected == false)
            {
                _connectionDisposables.Clear();
                nextDevice.Dispose();
                return;
            }

            switch (oldViewMode)
            {
            case ViewMode.Input:
                await nextDevice.PreviewInputTile();

                break;

            case ViewMode.Output:
                await nextDevice.PreviewProgramOut();

                break;

            default:
                break;
            }

            ConnectedDevice = nextDevice;
            VideoPlayer.SetEnable();
        }
        /// <summary>
        /// Invoke this method before calling Start(), to initialize the actor
        /// with details such as the device model and message type to simulate.
        /// If this method is not called before Run(), the application will
        /// throw an exception.
        /// Init() should be called only once, typically after the constructor.
        /// </summary>
        public void Init(
            ISimulationContext simulationContext,
            string deviceId,
            DeviceModel deviceModel,
            int deviceCounter)
        {
            this.instance.InitOnce();

            this.simulationContext = simulationContext;
            this.deviceModel       = deviceModel;
            this.deviceId          = deviceId;

            // Distribute actors start over 10 secs
            this.startDelayMsecs = deviceCounter % START_DISTRIBUTION_WINDOW_MSECS;

            this.instance.InitComplete();
        }
        private void SetupDeviceStateActor()
        {
            string DEVICE_ID   = "01";
            int    postion     = 1;
            int    total       = 10;
            var    deviceModel = new DeviceModel {
                Id = DEVICE_ID
            };

            var mockSimulationContext = new Mock <ISimulationContext>();

            this.target.Init(
                mockSimulationContext.Object,
                DEVICE_ID,
                deviceModel,
                postion);
        }
        private bool SearchTypePropertiesForValue(DeviceModel device, string search)
        {
            // if the device or its system properties are null then
            // there's nothing that can be searched on
            if (device?.DeviceProperties == null)
            {
                return(false);
            }

            // iterate through the DeviceProperties Properties and look for the search value
            // case insensitive search
            var upperCaseSearch = search.ToUpperInvariant();

            return(device.DeviceProperties.ToKeyValuePairs().Any(t =>
                                                                 (t.Value != null) &&
                                                                 t.Value.ToString().ToUpperInvariant().Contains(upperCaseSearch)));
        }
        public IHttpActionResult GetDeviceInformation(bool isInterID, string Device)
        {
            try
            {
                var sqlWhere = string.Empty;
                if (isInterID)
                {
                    sqlWhere = string.Format("where t0.FinterID = @Device");
                }
                else
                {
                    sqlWhere = string.Format("where t0.FNumber = @Device");
                }
                var sql = string.Format(@"select top 1
                                t0.FinterID as DeviceID,
                                t0.FNumber as DeviceNo,
                                t0.FName as DeviceName,
                                t0.FModel as Model,
								t0.FKeepEmpID as CustodianID,
                                t1.Fnumber as CustodianCode,
                                t1.Fname as CustodianName,
                                t2.Fname as CustodianDept,
                                t1.FPhone as CustodianTel
                                from t_FACard t0 
                                left outer join t_emp t1 on t1.FleaveDate is null And t0.FKeepEmpID=t1.FitemID
                                left outer join t_Department t2 on t1.FDeptmentID=t2.FItemID 
                                {0}", sqlWhere);
                Dictionary <string, object> dic = new Dictionary <string, object>();
                dic.Add("Device", Device);
                DeviceModel deviceModel = Query <DeviceModel>(sql, dic);
                if (deviceModel == null)
                {
                    return(Ok(new ReturnMessage(ReturnMessType.Error, GetLocalText("Query_Result_NotExist"))));
                }
                return(Ok(new ReturnMessage(ReturnMessType.Success, new Dictionary <string, object>()
                {
                    { "DeviceMessage", deviceModel },
                    { "RepairOrder", null }
                })));
            }
            catch
            {
                //return Ok(new ReturnMessage(ReturnMessType.Error, e.Message));
                return(Ok(new ReturnMessage(ReturnMessType.Error, GetLocalText("DataBase_Error"))));
            }
        }
            public void should_remove_selected_item_after_loaded()
            {
                var deviceModelId = "11";
                var columnId = "22";

                var deviceModel = new DeviceModel() { Id = "1" };
                this.RedisServiceMock.Setup(s => s.GetModelWithCustomProperties<DeviceModel, CustomProperty>(It.Is<string>(p => p == deviceModelId))).Returns(deviceModel);

                var searchedApps = new List<App>() { new App { Id = "1", AppNo = "1" }, new App { Id = "2", AppNo = "2" } };
                var selectedApps = new List<App>() { new App { Id = "1", AppNo = "1" } };

                this.AppStoreServiceMock.Setup(s => s.GetAppsForDeviceModel(It.IsAny<DeviceModel>())).Returns(searchedApps);
                this.AppStoreServiceMock.Setup(s => s.GetAppsFromAppList<AppColumn>(It.Is<string>(x => x == columnId))).Returns(selectedApps);

                var ret = this.Controller.ColumnListManage(deviceModelId, columnId);

                Assert.Equal(1, ((ret as ViewResult).Model as List<App>).Count);
            }
Example #34
0
 /// <summary>
 /// Создаёт устройство на основе типа
 /// </summary>
 /// <param name="deviceType">Тип устройства</param>
 /// <returns></returns>
 public static DeviceBase CreateDevice(DeviceModel deviceType)
 {
     throw new NotImplementedException();
 }
Example #35
0
 public Device()
 {
     DataContext = this;
     _selectedDevice=new DeviceModel();
 }
Example #36
0
 private void Remove()
 {
     DeviceCollection.Remove(_selectedDevice);
     SelectedDevice = DeviceCollection.FirstOrDefault();
 }
 public void Save(DeviceModel device)
 {
     MongoCollection<DeviceModel> devicesDB = Tools.MongoConnector.Instance.DataBase.GetCollection<DeviceModel>(DEVICE_DB_NAME);
     devicesDB.Save(device);
 }
Example #38
0
        private DeviceModel GetFormData()
        {
            DeviceModel deviceModel = new DeviceModel();

            deviceModel.Id = Id;
            deviceModel.IdDeviceType = MainHelper.DdlGetSelectedValueInt(ref ddlDeviceType);
            deviceModel.Name = MainHelper.TxtGetText(ref txtName);
            deviceModel.Vendor = MainHelper.TxtGetText(ref txtVendor);
            //deviceModel.Nickname = MainHelper.TxtGetText(ref txtNickname);
            deviceModel.Speed = MainHelper.TxtGetTextDecimal(ref txtSpeed, true);
            deviceModel.IdDeviceImprint = MainHelper.DdlGetSelectedValueInt(ref ddlDeviceImprint, true);
            deviceModel.IdPrintType = MainHelper.DdlGetSelectedValueInt(ref ddlPrintType, true);
            deviceModel.IdCartridgeType = MainHelper.DdlGetSelectedValueInt(ref ddlCartridgeType, true);
            deviceModel.IdCreator = User.Id;
            deviceModel.MaxVolume = MainHelper.TxtGetTextInt32(ref txtMaxVolume,true);
            deviceModel.IdClassifierCategory = MainHelper.DdlGetSelectedValueInt(ref ddlClassifier, true);

            return deviceModel;
        }
Example #39
0
            /// <summary>
            /// Копировать модель устройства из заданной
            /// </summary>
            public void CopyFrom(DeviceModel srcDeviceModel)
            {
                if (srcDeviceModel == null)
                    throw new ArgumentNullException("srcDeviceModel");

                // очистка списков групп элементов и команд
                ElemGroups.Clear();
                Cmds.Clear();

                // копирование групп элементов
                foreach (ElemGroup srcGroup in srcDeviceModel.ElemGroups)
                {
                    ElemGroup elemGroup = new ElemGroup(srcGroup.TableType)
                    {
                        Address = srcGroup.Address,
                        Name = srcGroup.Name,
                        StartKPTagInd = srcGroup.StartKPTagInd,
                        StartSignal = srcGroup.StartSignal,
                    };

                    foreach (Elem srcElem in srcGroup.Elems)
                    {
                        elemGroup.Elems.Add(new Elem()
                        {
                            Name = srcElem.Name,
                            ElemType = srcElem.ElemType
                        });
                    }

                    ElemGroups.Add(elemGroup);
                }

                // копирование команд
                foreach (Cmd srcCmd in srcDeviceModel.Cmds)
                {
                    Cmds.Add(new Cmd(srcCmd.TableType)
                    {
                        Multiple = srcCmd.Multiple,
                        ElemCnt = srcCmd.ElemCnt,
                        Address = srcCmd.Address,
                        Name = srcCmd.Name,
                        CmdNum = srcCmd.CmdNum
                    });
                }
            }
Example #40
0
        protected new void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if (!IsPostBack)
            {
                FormTitle = "Добавление модели";

                if (Id > 0)
                {
                    DeviceModel device = new DeviceModel(Id);
                    FillFormData(device);
                }
            }
        }
Example #41
0
 private void ParseModelNumber(string modelString, out DeviceModel model, out DeviceGeneration generation)
 {
     switch (modelString)
     {
         case "M8513":
         case "M8541":
         case "M8697":
         case "M8709":
             model = DeviceModel.Regular;
             generation = DeviceGeneration.First;
             break;
         case "M8737":
         case "M8740":
         case "M8738":
         case "M8741":
             model = DeviceModel.Regular;
             generation = DeviceGeneration.Second;
             break;
         case "M8976":
         case "M8946":
         case "M9460":
         case "M9244":
         case "M8948":
         case "M9245":
             model = DeviceModel.Regular;
             generation = DeviceGeneration.Third;
             break;
         case "M9282":
         case "M9787":
         case "M9268":
         case "MA079":
         case "MA127":
         case "ME436": //HP iPod
             model = DeviceModel.Regular;
             generation = DeviceGeneration.Fourth;
             break;
         case "M9160":
             model = DeviceModel.Mini;
             generation = DeviceGeneration.First;
             break;
         case "M9436":
             model = DeviceModel.MiniBlue;
             generation = DeviceGeneration.First;
             break;
         case "M9435":
             model = DeviceModel.MiniPink;
             generation = DeviceGeneration.First;
             break;
         case "M9434":
             model = DeviceModel.MiniGreen;
             generation = DeviceGeneration.First;
             break;
         case "M9437":
             model = DeviceModel.MiniGold;
             generation = DeviceGeneration.First;
             break;
         case "M9800":
         case "M9801":
             model = DeviceModel.Mini;
             generation = DeviceGeneration.Second;
             break;
         case "M9802":
         case "M9803":
             model = DeviceModel.MiniBlue;
             generation = DeviceGeneration.Second;
             break;
         case "M9804":
         case "M9805":
             model = DeviceModel.MiniPink;
             generation = DeviceGeneration.Second;
             break;
         case "M9806":
         case "M9807":
             model = DeviceModel.MiniGreen;
             generation = DeviceGeneration.Second;
             break;
         case "M9829":
         case "M9585":
         case "M9586":
         case "M9830":
             model = DeviceModel.Color;
             generation = DeviceGeneration.Fourth;
             break;
         case "M9724":
         case "M9725":
             model = DeviceModel.Shuffle;
             generation = DeviceGeneration.First;
             break;
         case "MA546":
             model = DeviceModel.ShuffleSilver;
             generation = DeviceGeneration.Second;
             break;
         case "MA947":
             model = DeviceModel.ShufflePink;
             generation = DeviceGeneration.Second;
             break;
         case "MA949":
             model = DeviceModel.ShuffleBlue;
             generation = DeviceGeneration.Second;
             break;
         case "MA951":
             model = DeviceModel.ShuffleGreen;
             generation = DeviceGeneration.Second;
             break;
         case "MA953":
             model = DeviceModel.ShuffleOrange;
             generation = DeviceGeneration.Second;
             break;
         case "MA350":
         case "MA004":
         case "MA005":
             model = DeviceModel.NanoWhite;
             generation = DeviceGeneration.First;
             break;
         case "MA352":
         case "MA009":
         case "MA107":
             model = DeviceModel.NanoBlack;
             generation = DeviceGeneration.First;
             break;
         case "MA477":
         case "MA426":
             model = DeviceModel.NanoSilver;
             generation = DeviceGeneration.Second;
             break;
         case "MA428":
             model = DeviceModel.NanoBlue;
             generation = DeviceGeneration.Second;
             break;
         case "MA487":
             model = DeviceModel.NanoGreen;
             generation = DeviceGeneration.Second;
             break;
         case "MA489":
             model = DeviceModel.NanoPink;
             generation = DeviceGeneration.Second;
             break;
         case "MA725":
         case "MA726":
             model = DeviceModel.NanoProductRed;
             generation = DeviceGeneration.Second;
             break;
         case "MA497":
             model = DeviceModel.NanoBlack;
             generation = DeviceGeneration.Second;
             break;
         case "MA002":
         case "MA003":
         case "MA444":
             model = DeviceModel.VideoWhite;
             generation = DeviceGeneration.Fifth;
             break;
         case "MA146":
         case "MA147":
         case "MA448":
         case "MA450": /* Possibly Video U2? */
         case "MA446": /* Video U2 */
             model = DeviceModel.VideoBlack;
             generation = DeviceGeneration.Fifth;
             break;
         default:
             model = DeviceModel.Unknown;
             generation = DeviceGeneration.Unknown;
             break;
     }
 }
Example #42
0
 public static String DeviceModelToString(DeviceModel model) {
     switch (model) {
     case DeviceModel.DEVICE_MODEL_GENERIC: return "Generic";
     case DeviceModel.DEVICE_MODEL_F200: return "F200";
     case DeviceModel.DEVICE_MODEL_R200:	return "R200";
     case DeviceModel.DEVICE_MODEL_F250:	return "F250";
     }
     return "Unknown";
 }
Example #43
0
 private void FillFormData(DeviceModel deviceModel)
 {
     FormTitle = Id == 0 ? "Добавление модели" : String.Format("Редактирование модели {0}", deviceModel.Name);
     MainHelper.DdlSetSelectedValue(ref ddlDeviceType, deviceModel.IdDeviceType);
     MainHelper.TxtSetText(ref txtName, deviceModel.Name);
     MainHelper.TxtSetText(ref txtVendor, deviceModel.Vendor);
     //MainHelper.TxtSetText(ref txtNickname, deviceModel.Nickname);
     MainHelper.TxtSetText(ref txtSpeed, deviceModel.Speed);
     MainHelper.DdlSetSelectedValue(ref ddlDeviceImprint, deviceModel.IdDeviceImprint);
     MainHelper.DdlSetSelectedValue(ref ddlPrintType, deviceModel.IdPrintType);
     MainHelper.DdlSetSelectedValue(ref ddlCartridgeType, deviceModel.IdCartridgeType);
     MainHelper.TxtSetText(ref txtMaxVolume, deviceModel.MaxVolume);
 }
Example #44
0
 private void AddNew()
 {
     var newDevice = new DeviceModel {Name = "New Device"};
     DeviceCollection.Insert(0,newDevice);
     SelectedDevice = newDevice;
     IsEditMode = true;
 }
        private void DecodeTracking(MD.CloudConnect.ITracking t, AccountModel account, List<TrackingModel> saveTracks, List<DeviceModel> saveDevices)
        {
            string imei = t.Asset;

            DeviceModel device = RepositoryFactory.Instance.DeviceDb.GetDevice(imei);

            if (device == null)
            {
                device = new DeviceModel() { Imei = imei };
                RepositoryFactory.Instance.DeviceDb.Save(device);
                device = RepositoryFactory.Instance.DeviceDb.GetDevice(imei);
            }

            device.LastReport = t.Recorded_at;
            if (t.IsValid)
            {
                device.LastValidLocation = t.Recorded_at;
                device.LastLongitude = t.Longitude;
                device.LastLatitude = t.Latitude;
            }

            TrackingModel track = new TrackingModel();
            track.DeviceID = device.Id;
            track.Data = (MD.CloudConnect.Data.TrackingData)t;
            track.RecordedDateKey = t.Recorded_at.GenerateKey();
            saveTracks.Add(track);

            device.UpdateField(track);

            if (saveDevices.Where(x => x.Imei == device.Imei).Count() == 0)
                saveDevices.Add(device);
        }
        public int CheckDeviceNo(string merchantCode, string deviceNo, out string message)
        {
            var rep = DMRepository.Get<EVehicle>();

            List<ETenant> list = new List<ETenant>();
            DeviceModel dm = new DeviceModel();
            dm.GetParentMerchantByRecursion(merchantCode, list);
            string merchantCodes = string.Join(",", list.Select(p => p.TenantCode).ToArray());

            var device = rep.Get(p => p.MerchantCode.In(merchantCodes) && p.DeviceNo == deviceNo);
            if (device != null)
            {
                if (!string.IsNullOrEmpty(device.TenantCode) && device.TenantCode != "0")
                {
                    message = "该设备号已经与其它设备关联!";
                    return 0;
                }

                var gpsTypeEntity = DACFacade.Gps.GpsTypeDAC.Select(device.GPSTypeID);
                if (gpsTypeEntity == null)
                {
                    message = "设备类型";
                    return 0;
                }
                else
                {
                    message = gpsTypeEntity.TypeName;
                    return 1;

                }
            }
            message = "没有找到该设备号!";
            return 0;
        }