示例#1
0
 public DeviceModel(int?deviceId)
 {
     if (deviceId.HasValue)
     {
         DeviceEntity device = new DeviceEntity(deviceId.Value);
         if (!device.IsNew)
         {
             DeviceId         = deviceId.Value;
             OrganizationId   = device.Location.OrganizationId;
             OrganizationName = device.Location.Organization.Name;
             LocationId       = device.LocationId;
             LocationName     = device.Location.Name;
             DeviceState      = device.DeviceState;
             SerialNumber     = device.SerialNumber;
             RevisionLevel    = device.RevisionLevel;
             ScansAvailable   = device.ScansAvailable;
             ScansCompleted   = device.ScansUsed;
             IssuedTime       = device.DateIssued;
             UniqueIdentifier = device.UniqueIdentifier;
             LastReportTime   = device.LastReportTime;
             UidQualifier     = DeviceUtils.GetUidQualifier(device, false);
         }
         else
         {
             DeviceState    = DeviceState.New;
             OrganizationId = -1;
         }
     }
     else
     {
         DeviceState    = DeviceState.New;
         OrganizationId = -1;
     }
 }
        public async Task <Device> Save(Device device)
        {
            var result = new Result <Device>();

            try
            {
                DeviceEntity deviceEntity = new DeviceEntity(device.UserEmail, device.Id)
                {
                    Id          = device.Id,
                    Name        = device.Name,
                    IconName    = device.IconName,
                    Description = device.Description,
                    Status      = device.Status,
                    IsOn        = device.IsOn,
                    UserEmail   = device.UserEmail
                };
                TableOperation insertOperation = TableOperation.Insert(deviceEntity);
                await cloudTable.ExecuteAsync(insertOperation);
            }
            catch (Exception e)
            {
                return(null);
            }
            return(device);
        }
示例#3
0
        private void UpdateTokenToServer(string token)
        {
            // mi collego al mio server e comunico il token di questo dispositivo

            if (config.GetEmailUser() != null)
            {
                Debug.WriteLine(string.Format("SendRegistrationToServer({0}) chiamata", token), TAG);
                DeviceEntity device = new DeviceEntity {
                    DeviceId    = config.GetDeviceId(),
                    DeviceToken = token,
                    User        = new UserEntity {
                        Email = config.GetEmailUser()
                    }
                };
                device.UpdateToken((updateTokenResult, errorMessage) => {
                    if (updateTokenResult)
                    {
                        Debug.WriteLine(string.Format("Aggiornamento token avvenuto con successo"));
                    }
                    else
                    {
                        Debug.WriteLine(string.Format("Il server ha restituito un errore. Messaggio : {0}",
                                                      errorMessage));
                    }
                });
            }
        }
示例#4
0
        private async Task LogDeviceInfo(DeviceInfo device, CancellationToken token)
        {
            if (device == null)
            {
                return;
            }

            var deviceEntity = await this.Database.Devices.GetSingleAsync(d => d.Id == device.Id, token);

            if (deviceEntity == null)
            {
                deviceEntity = new DeviceEntity()
                {
                    Id              = device.Id,
                    Name            = device.Name,
                    Type            = device.Type,
                    Model           = device.Model,
                    OperationSystem = device.OperationSystem
                };
                await this.Database.Devices.InsertAsync(deviceEntity, token);
            }
            else
            {
                var filterDefinition = Builders <DeviceEntity> .Filter.Where(e => e.Id == deviceEntity.Id);

                var updateDefinition = Builders <DeviceEntity> .Update.Set(e => e.UpdatedTime, DateTime.UtcNow);

                await this.Database.Devices.UpdateOneAsync(deviceEntity, filterDefinition, updateDefinition, token);
            }
        }
        public async Task CreateAsync(GeoloacationPayload payload)
        {
            var device = await _deviceRepository.FirstOrDefaultAsync(f => f.DeviceId == payload.DeviceId);

            if (device == null)
            {
                device = new DeviceEntity()
                {
                    Id       = Guid.NewGuid(),
                    DeviceId = payload.DeviceId
                };

                await _deviceRepository.AddAndSaveAsync(device);
            }

            var log = new LogEntity()
            {
                Id        = Guid.NewGuid(),
                DeviceId  = device.Id,
                Height    = Convert.ToDouble(payload.Height),
                Speed     = Convert.ToDouble(payload.Speed),
                Latitude  = Convert.ToDouble(payload.Latitude),
                Longitude = Convert.ToDouble(payload.Longitude),
                LogDate   = payload.LogDate
            };

            await _logRepository.AddAndSaveAsync(log);
        }
示例#6
0
        public bool Update(DeviceEntity _DeviceEntity)
        {
            bool isSaved = false;

            try
            {
                osqlConnection.Open();
                SqlCommand osqlCommand = new SqlCommand();
                osqlCommand.Connection  = osqlConnection;
                osqlCommand.CommandType = CommandType.Text;
                osqlCommand.CommandText = "UPDATE  TRN_SMkneet_t SET IpAddress= '" + _DeviceEntity.IpAddress + "',port= '" + _DeviceEntity.Port + "',Address='" + _DeviceEntity.Address + "',IsActive='" + (_DeviceEntity.IsActive) + "' WHERE MachineId='" + _DeviceEntity.MachineId + "' and zId='" + _DeviceEntity.Zid + "'";
                osqlCommand.ExecuteNonQuery();
                isSaved = true;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                if (osqlConnection.State == ConnectionState.Open)
                {
                    osqlConnection.Close();
                }
            }
            return(isSaved);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var deviceIdInfo = validationContext.ObjectType.GetProperty(DeviceId);
            var deviceId     = deviceIdInfo.GetValue(validationContext.ObjectInstance, null);

            if (deviceId != null)
            {
                var device = new DeviceEntity((int)deviceId);

                var scansAvailableInfo = validationContext.ObjectType.GetProperty(ScansAvailable);
                var scansAvailable     = (int)scansAvailableInfo.GetValue(validationContext.ObjectInstance, null);

                if (device.ScansAvailable != scansAvailable)
                {
                    return(base.IsValid(value, validationContext));
                }
            }
            else
            {
                // new device
                return(base.IsValid(value, validationContext));
            }

            return(null);
        }
        public void SaveDevice(string deviceId, int?userId)
        {
            using (var context = GetContext())
            {
                var guidDevice = new Guid(deviceId);
                var device     = context.Devices.Find(guidDevice);

                if (device != null)
                {
                    if (device.UserId != userId)
                    {
                        device.UserId = userId;
                    }
                }
                else
                {
                    var entity = new DeviceEntity
                    {
                        Id      = guidDevice,
                        UserId  = userId,
                        Created = DateTime.Now
                    };
                    context.Devices.Add(entity);
                }

                context.SaveChanges();
            }
        }
示例#9
0
        protected void MasterPage_YesClickHandler(object sender, EventArgs e)
        {
            if (ViewState["Delete"] != null)
            {
                try
                {
                    DeviceEntity entity = new DeviceEntity();
                    entity.OperationId = (int)OperationType.Delete;
                    entity.DeviceId    = Utility.GetInt(ViewState["DeviceId"]);

                    OperationStatusEntity c = new DeviceRepository(SessionContext).UpdateDevice(entity);

                    if (c.StatusResult == true)
                    {
                        ShowInfoMessage(c.InfoMessage);
                        ClearPageControl();
                        FillGrid();
                    }
                    else
                    {
                        ShowErrorMessage(c.InfoMessage);
                    }
                }
                catch (BaseException bex)
                {
                    ShowErrorMessage(bex.Message);
                }
            }
        }
示例#10
0
        private void RemoveTagGroup()
        {
            TreeListNode node   = deviceProp.CurrentNode();
            BaseEntity   entity = null;

            if (node != null)
            {
                if (node.Tag is Guid id)
                {
                    entity = DataHelper.Instance.AllEntities[id];
                }
            }

            if (entity is GroupEntity group)
            {
                if (XtraMessageBox.Show(
                        $"是否要删除[{group.Name}]标记组?",
                        "提问",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DeviceEntity device = group.Parent;
                    device.Groups.Remove(group);

                    deviceProp.RemoveCurrentNode();
                }
            }
        }
示例#11
0
        public async Task <IActionResult> PutDeviceEntity([FromRoute] int id, [FromBody] DeviceEntity deviceEntity)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != deviceEntity.Id)
            {
                return(BadRequest());
            }

            _context.Entry(deviceEntity).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DeviceEntityExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#12
0
文件: MainForm.cs 项目: Ankitvaibs/SM
        private void cmbDevices_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((SelectedDevice == null) || (Devices.ContainsKey(SelectedHubDeviceId) && SelectedDevice.Id != SelectedHubDeviceId))
            {
                if (DeviceInstance.Connected)
                {
                    if (DeviceInstance.Disconnect())
                    {
                        buttonSend.Enabled = false;
                    }
                }

                // Initialize IoT Hub client
                DeviceInstance = new DeviceSimulator();

                // Attach receive callback for alerts
                DeviceInstance.ReceivedMessageEventHandler += DeviceInstanceReceivedMessage;
                DeviceInstance.SentMessageEventHandler     += DeviceInstance_SentMessageEventHandlerBacNet;

                SelectedDevice = Devices[SelectedHubDeviceId];
                Connect(SelectedDevice.ConnectionString);
            }
            else
            {
                buttonSend.Enabled = true;
            }
        }
示例#13
0
        private void UpdateDeviceTagsToService()
        {
            DeviceEntity device = null;
            DCSGatewayServiceController service = null;

            if (trees.CurrentNode().Tag is Guid id)
            {
                BaseEntity entity = DataHelper.Instance.AllEntities[id];
                if (entity is DeviceEntity deviceEntity)
                {
                    device  = deviceEntity;
                    service = deviceEntity.Service;
                }
                else if (entity is ProductionLineEntity line)
                {
                    if (lineProp == null)
                    {
                        return;
                    }

                    if (lineProp.FocusedDevice == null)
                    {
                        return;
                    }

                    device  = lineProp.FocusedDevice;
                    service = lineProp.FocusedDevice.Service;
                }

                if (service != null)
                {
                    try
                    {
                        if (ServiceHelper.Instance.StopService(service.ServName))
                        {
                            service.UpdateDeviceTagsParam();
                        }
                        else
                        {
                            XtraMessageBox.Show(
                                $"无法停止DCS网关服务[{service.ServName}]运行",
                                "提示",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            trees.ResetMenuItemEnable();
                        }

                        ServiceHelper.Instance.StartService(service.ServName);
                    }
                    catch (Exception error)
                    {
                        XtraMessageBox.Show(
                            $"更新设备标签配置文件的时候发生错误:{error.Message}",
                            "出错啦",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }
                }
            }
        }
示例#14
0
        protected DeviceEntity GetDeviceEntity(ITransaction transaction)
        {
            if (!isDeviceEntitySet)
            {
                isDeviceEntitySet = true;

                int?id = DeviceId;
                if (id.HasValue)
                {
                    if (transaction == null)
                    {
                        deviceEntity = new DeviceEntity(id.Value);
                    }
                    else
                    {
                        deviceEntity = new DeviceEntity();
                        transaction.Add(deviceEntity);
                        deviceEntity.FetchUsingPK(id.Value);
                    }

                    if (deviceEntity.IsNew)
                    {
                        deviceEntity = null;
                    }
                }
            }

            // Return DeviceEntity. Can be null if not authenticated or device not found.
            return(deviceEntity);
        }
示例#15
0
        public void Validate(V0100.Objects.ValidationKeys keys)
        {
            DeviceEntity device = GetDevice();

            LocationEntity location = device.Location;

            if (location.UniqueIdentifier != keys.LocationGuid)
            {
                throw new WebFaultException <string>(V0100.Constants.StatusSubcode.LOCATION_INVALID, HttpStatusCode.NotAcceptable);
            }

            if (location.Organization.UniqueIdentifier != keys.OrganizationGuid)
            {
                throw new WebFaultException <string>(V0100.Constants.StatusSubcode.ORGANIZATION_INVALID, HttpStatusCode.NotAcceptable);
            }

            if (device.DeviceState != DeviceState.Active)
            {
                throw new WebFaultException <string>(V0100.Constants.StatusSubcode.DEVICE_STATE_INVALID, HttpStatusCode.NotAcceptable);
            }

            if (device.ScansAvailable <= 0)
            {
                throw new WebFaultException <string>(V0100.Constants.StatusSubcode.DEVICE_HAS_NO_SCANS, HttpStatusCode.NotAcceptable);
            }
        }
示例#16
0
        public static bool RecordScan(int deviceId, ScanType scanType, DateTime scanStartTime)
        {
            Transaction transaction = new Transaction(IsolationLevel.RepeatableRead, "ScanHistoryUpdate");

            try
            {
                DeviceEntity device = new DeviceEntity();
                transaction.Add(device);
                device.FetchUsingPK(deviceId);

                device.ScansUsed      = device.ScansUsed + 1;
                device.ScansAvailable = device.ScansAvailable - 1;

                ScanHistoryEntity history = device.ScanHistories.AddNew();
                history.ScanType      = scanType;
                history.ScanStartTime = scanStartTime;

                device.Save(true);                              // recurse=true; will also save the history record

                transaction.Commit();

                return(true);
            }
            catch (Exception)
            {
                transaction.Rollback();
                return(false);
            }
            finally
            {
                transaction.Dispose();
            }
        }
示例#17
0
        public async Task<List<DeviceEntity>> GetDevices()
        {
            try
            {
                DeviceEntity deviceEntity;
                var devices = await registryManager.GetDevicesAsync(maxCountOfDevices);

                if (devices != null)
                {
                    foreach (var device in devices)
                    {
                        deviceEntity = new DeviceEntity()
                        {
                            Id = device.Id,
                            ConnectionState = device.ConnectionState.ToString(),
                            ConnectionString = CreateDeviceConnectionString(device),
                            LastActivityTime = device.LastActivityTime,
                            LastConnectionStateUpdatedTime = device.ConnectionStateUpdatedTime,
                            LastStateUpdatedTime = device.StatusUpdatedTime,
                            MessageCount = device.CloudToDeviceMessageCount,
                            State = device.Status.ToString(),
                            SuspensionReason = device.StatusReason
                        };

                        if (device.Authentication != null)
                        {

                            deviceEntity.PrimaryKey = device.Authentication.SymmetricKey?.PrimaryKey;
                            deviceEntity.SecondaryKey = device.Authentication.SymmetricKey?.SecondaryKey;
                            deviceEntity.PrimaryThumbPrint = device.Authentication.X509Thumbprint?.PrimaryThumbprint;
                            deviceEntity.SecondaryThumbPrint = device.Authentication.X509Thumbprint?.SecondaryThumbprint;

                            //if ((device.Authentication.SymmetricKey != null) &&
                            //    !((device.Authentication.SymmetricKey.PrimaryKey == null) ||
                            //      (device.Authentication.SymmetricKey.SecondaryKey == null)))
                            //{
                            //    deviceEntity.PrimaryKey = device.Authentication.SymmetricKey.PrimaryKey;
                            //    deviceEntity.SecondaryKey = device.Authentication.SymmetricKey.SecondaryKey;
                            //    deviceEntity.PrimaryThumbPrint = "";
                            //    deviceEntity.SecondaryThumbPrint = "";
                            //}
                            //else
                            //{
                            //    deviceEntity.PrimaryKey = "";
                            //    deviceEntity.SecondaryKey = "";
                            //    deviceEntity.PrimaryThumbPrint = device.Authentication.X509Thumbprint.PrimaryThumbprint;
                            //    deviceEntity.SecondaryThumbPrint = device.Authentication.X509Thumbprint.SecondaryThumbprint;
                            //}
                        }

                        listOfDevices.Add(deviceEntity);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return listOfDevices;
        }
        public static DeviceEntity GetDeviceEntityFromDevice(String iotHubManagementConnectionString, string protocolGatewayHostName, Device device)
        {
            DeviceEntity deviceEntity = null;

            if (device != null)
            {
                deviceEntity = new DeviceEntity()
                {
                    Id = device.Id,
                    ConnectionState  = device.ConnectionState.ToString(),
                    ConnectionString = CreateDeviceConnectionString(iotHubManagementConnectionString, protocolGatewayHostName, device),
                    LastActivityTime = device.LastActivityTime,
                    LastConnectionStateUpdatedTime = device.ConnectionStateUpdatedTime,
                    LastStateUpdatedTime           = device.StatusUpdatedTime,
                    MessageCount     = device.CloudToDeviceMessageCount,
                    State            = device.Status.ToString(),
                    SuspensionReason = device.StatusReason
                };

                if (device.Authentication != null)
                {
                    deviceEntity.PrimaryKey          = device.Authentication.SymmetricKey?.PrimaryKey;
                    deviceEntity.SecondaryKey        = device.Authentication.SymmetricKey?.SecondaryKey;
                    deviceEntity.PrimaryThumbPrint   = device.Authentication.X509Thumbprint?.PrimaryThumbprint;
                    deviceEntity.SecondaryThumbPrint = device.Authentication.X509Thumbprint?.SecondaryThumbprint;
                }
            }

            return(deviceEntity);
        }
        public async static Task <DeviceEntity> SaveDeviceEntityToRegistry(bool isInsert, String iotHubManagementConnectionString, string protocolGatewayHostName, DeviceEntity deviceEntity)
        {
            RegistryManager registry;
            DeviceEntity    outputDeviceEntity = null;

            try
            {
                Device inputDevice = GetDeviceFromDeviceEntity(deviceEntity);
                Device outputDevice;
                registry = RegistryManager.CreateFromConnectionString(iotHubManagementConnectionString);
                if (isInsert)
                {
                    outputDevice = await registry.AddDeviceAsync(inputDevice);
                }
                else
                {
                    outputDevice = await registry.UpdateDeviceAsync(inputDevice, true);
                }
                outputDeviceEntity = GetDeviceEntityFromDevice(iotHubManagementConnectionString, protocolGatewayHostName, outputDevice);
            }
            catch (Exception ex)
            {
                throw new Exception($"An {ex.GetType().Name} occurred when Adding the Device to the Registry based on the provided DeviceEntity: {ex.Message}", ex);
            }

            return(outputDeviceEntity);
        }
示例#20
0
        public async Task <DeviceEntity> GetEntityByUserCodeAsync(string user_code)
        {
            try
            {
                // Create or reference an existing table
                CloudTable table = await CreateTableAsync("Devices");

                TableOperation retrieveOperation = TableOperation.Retrieve <DeviceEntity>(DeviceEntity.PartitionKeyName, user_code);
                TableResult    result            = await table.ExecuteAsync(retrieveOperation);

                DeviceEntity device = result.Result as DeviceEntity;

                // Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure CosmoS DB
                if (result.RequestCharge.HasValue)
                {
                    Console.WriteLine("Request Charge of Retrieve Operation: " + result.RequestCharge);
                }

                return(device);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
示例#21
0
        public async Task <DeviceEntity> AddAuthRequestAsync(string device_code, string user_code)
        {
            try
            {
                // Create or reference an existing table
                CloudTable table = await CreateTableAsync("Devices");

                // Add new entity
                DeviceEntity device = new DeviceEntity(device_code, user_code);

                // Create the InsertOrReplace table operation
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(device);

                // Execute the operation.
                TableResult result = await table.ExecuteAsync(insertOrMergeOperation);

                DeviceEntity insertedDevice = result.Result as DeviceEntity;

                // Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure Cosmos DB
                if (result.RequestCharge.HasValue)
                {
                    Console.WriteLine("Request Charge of InsertOrMerge Operation: " + result.RequestCharge);
                }

                return(insertedDevice);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
示例#22
0
        public bool Add(DeviceEntity _DeviceEntity)
        {
            bool isSaved = false;

            try
            {
                osqlConnection.Open();
                SqlCommand osqlCommand = new SqlCommand();
                osqlCommand.Connection  = osqlConnection;
                osqlCommand.CommandType = CommandType.Text;
                osqlCommand.CommandText = "INSERT INTO TRN_SMkneet_t VALUES('" + _DeviceEntity.MachineId + "', '" + _DeviceEntity.IpAddress + "', '" + _DeviceEntity.Port + "','" + _DeviceEntity.Address + "','" + (_DeviceEntity.IsActive) + "') ";
                osqlCommand.ExecuteNonQuery();
                isSaved = true;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                if (osqlConnection.State == ConnectionState.Open)
                {
                    osqlConnection.Close();
                }
            }
            return(isSaved);
        }
示例#23
0
        private void AddDeviceIfMissing(IRGBDevice rgbDevice, ArtemisSurface surface)
        {
            string        deviceIdentifier = rgbDevice.GetDeviceIdentifier();
            ArtemisDevice device           = surface.Devices.FirstOrDefault(d => d.DeviceEntity.DeviceIdentifier == deviceIdentifier);

            if (device != null)
            {
                return;
            }

            // Find an existing device config and use that
            DeviceEntity existingDeviceConfig = surface.SurfaceEntity.DeviceEntities.FirstOrDefault(d => d.DeviceIdentifier == deviceIdentifier);

            if (existingDeviceConfig != null)
            {
                Plugin plugin = _pluginService.GetPluginByDevice(rgbDevice);
                device = new ArtemisDevice(rgbDevice, plugin, surface, existingDeviceConfig);
            }
            // Fall back on creating a new device
            else
            {
                _logger.Information(
                    "No device config found for {deviceInfo}, device hash: {deviceHashCode}. Adding a new entry.",
                    rgbDevice.DeviceInfo,
                    deviceIdentifier
                    );
                Plugin plugin = _pluginService.GetPluginByDevice(rgbDevice);
                device = new ArtemisDevice(rgbDevice, plugin, surface);
            }

            surface.Devices.Add(device);
        }
 /// <summary> Retrieves the related entity of type 'DeviceEntity', using a relation of type 'n:1'</summary>
 /// <param name="forceFetch">if true, it will discard any changes currently in the currently loaded related entity and will refetch the entity from the persistent storage</param>
 /// <returns>A fetched entity of type 'DeviceEntity' which is related to this entity.</returns>
 public virtual DeviceEntity GetSingleDevice(bool forceFetch)
 {
     if ((!_alreadyFetchedDevice || forceFetch || _alwaysFetchDevice) && !this.IsSerializing && !this.IsDeserializing && !this.InDesignMode)
     {
         bool         performLazyLoading = this.CheckIfLazyLoadingShouldOccur(Relations.DeviceEntityUsingDeviceId);
         DeviceEntity newEntity          = new DeviceEntity();
         bool         fetchResult        = false;
         if (performLazyLoading)
         {
             AddToTransactionIfNecessary(newEntity);
             fetchResult = newEntity.FetchUsingPK(this.DeviceId);
         }
         if (fetchResult)
         {
             newEntity = (DeviceEntity)GetFromActiveContext(newEntity);
         }
         else
         {
             if (!_deviceReturnsNewIfNotFound)
             {
                 RemoveFromTransactionIfNecessary(newEntity);
                 newEntity = null;
             }
         }
         this.Device           = newEntity;
         _alreadyFetchedDevice = fetchResult;
     }
     return(_device);
 }
示例#25
0
        private void NewDevice()
        {
            TreeListNode         node       = trees.CurrentNode();
            TreeListNode         parentNode = null;
            ProductionLineEntity parent     = null;

            if (node.Tag is Guid id)
            {
                BaseEntity entity = DataHelper.Instance.AllEntities[id];
                if (entity is ProductionLineEntity line)
                {
                    parentNode = node;
                    parent     = line;
                }
                else if (entity is DeviceEntity device)
                {
                    parentNode = node.ParentNode;
                    parent     = device.Parent;
                }
            }

            if (parentNode != null && parent != null)
            {
                DeviceEntity newDevice = new DeviceEntity(parent);
                parent.Devices.Add(newDevice, null);
                DataHelper.Instance.AllEntities.Add(newDevice);

                newDevice.Node = trees.AppendNode(newDevice.Name, newDevice.ID, parentNode);
            }
        }
示例#26
0
        internal ArtemisDevice(IRGBDevice rgbDevice, DeviceProvider deviceProvider)
        {
            Identifier     = rgbDevice.GetDeviceIdentifier();
            DeviceEntity   = new DeviceEntity();
            RgbDevice      = rgbDevice;
            DeviceProvider = deviceProvider;

            Rotation   = 0;
            Scale      = 1;
            ZIndex     = 1;
            RedScale   = 1;
            GreenScale = 1;
            BlueScale  = 1;
            IsEnabled  = true;

            InputIdentifiers = new List <ArtemisDeviceInputIdentifier>();
            InputMappings    = new Dictionary <ArtemisLed, ArtemisLed>();
            Categories       = new HashSet <DeviceCategory>();

            UpdateLeds();
            ApplyKeyboardLayout();
            ApplyToEntity();
            ApplyDefaultCategories();
            CalculateRenderProperties();
        }
示例#27
0
        public Task ActivateMeAsync(string region, string device, int version)
        {
            CloudTable          cloudTable;
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(storageConnectionString);
            var cloudTableClient = cloudStorageAccount.CreateCloudTableClient();

            cloudTable = cloudTableClient.GetTableReference("Equipamentos");
            cloudTable.CreateIfNotExistsAsync();

            var Device = new DeviceEntity(device, region)
            {
                Version = version.ToString()
            };
            TableOperation insertOperation = TableOperation.InsertOrReplace(Device);

            cloudTable.ExecuteAsync(insertOperation);

            State._deviceInfo = new ThingInfo()
            {
                DeviceId = device,
                Region   = region,
                Version  = version
            };

            // based on the info, assign a group... for demonstration we are assigning a random group
            State._deviceGroupId = region;

            var deviceGroup = ActorProxy.Create <IThingGroup>(new ActorId(region));

            return(deviceGroup.RegisterDevice(State._deviceInfo));
        }
示例#28
0
        public async Task <int> Update(DeviceEntity device)
        {
            int index = devices.FindIndex(i => i.Id == device.Id);

            devices[index] = device;
            return(index);
        }
示例#29
0
        /// <summary>
        /// Envia um notification push para um device usando o sistema de notificações da Apple
        /// </summary>
        /// <param name="device">ARN registrado no amazon</param>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <param name="extra"></param>
        /// <returns></returns>
        protected override bool SendMessage(DeviceEntity device, string title, string message, bool silent, string extra = "")
        {
            try
            {
                string msg = "{ " + GetMessage(title, message, silent, extra) + " }";

                PublishRequest snsRequest = new PublishRequest()
                {
                    Message          = msg,
                    MessageStructure = "json",
                    TargetArn        = device.BrokerEndpoint
                };

                PublishResponse response = AWSFactory.SNSClient.Publish(snsRequest);

                if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                ServiceHelper.ThrowError(ex);
            }
            return(false);
        }
示例#30
0
        public override async Task <DeviceStatisticsModel> Handle(GetDeviceStatisticsCommand command)
        {
            DeviceEntity entity = await repository.GetEntities <DeviceEntity>()
                                  .FirstOrDefaultAsync(x => x.Id == command.DeviceId &&
                                                       x.Asset.Users.Any(y =>
                                                                         y.UserId == command.UserId && y.RoleId == (int)UserAssetRole.Owner));

            if (entity != null)
            {
                DeviceStatisticsModel model = new DeviceStatisticsModel
                {
                    Locations = await repository.GetEntities <LocationEntity>()
                                .CountAsync(x => x.DeviceId == entity.Id),
                    FirstLocationDateTime = (await repository.GetEntities <LocationEntity>()
                                             .Where(x => x.DeviceId == command.DeviceId)
                                             .OrderBy(x => x.DateTime)
                                             .FirstOrDefaultAsync())
                                            ?.DateTime,
                    LastLocationDateTime = (await repository.GetEntities <LocationEntity>()
                                            .Where(x => x.DeviceId == command.DeviceId)
                                            .OrderByDescending(x => x.DateTime)
                                            .FirstOrDefaultAsync())
                                           ?.DateTime,
                    Connections = await repository.GetEntities <DeviceConnectionEntity>()
                                  .CountAsync(x => x.DeviceId == command.DeviceId)
                };

                return(model);
            }

            return(null);
        }
        /// <summary>
        /// 更新实体状态
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public int UpdateStatus(string deviceId, int status)
        {
            var cnt = -1;

            try
            {
                DeviceEntity device = null;
                if (string.IsNullOrWhiteSpace(deviceId))
                {
                    throw new MessageException("设备Id不能为空");
                }
                else
                {
                    device = deviceServ.GetEntity(deviceId);
                    if (device == null)
                    {
                        throw new MessageException("设备不存在");
                    }
                }

                // 状态取值未校验
                if (device.DeviceStatus != status)
                {
                    device.DeviceStatus = status;
                    cnt = deviceServ.UpdateEntity(device);
                }
            }
            catch (Exception ex)
            {
                throw new MessageException(ex.Message);
            }
            return(cnt);
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["CreatedDetectPointList"] != null)
            {
                _CreatedDetectPointList = (List<DetectPointEntity>)Session["CreatedDetectPointList"];
            }
            else 
            {
                _CreatedDetectPointList = new List<DetectPointEntity>();
            }

            _Device = BusinessFacadeShanliTech_HLD_Business.DeviceDisp(IDX);
            if (_Device == null || _Device.ID <= 0) { return; }

            _DeviceFuncList = ToolMethods.GetFunctionsByDeviceID(_Device.ID);
            if (_DeviceFuncList == null || _DeviceFuncList.Count <= 0) { return; }
            _DeviceFuncList.Sort((x, y) => { return x.OrderID.CompareTo(y.OrderID); });

           

            _RangeList = ToolMethods.GetRangeList(_Device.DeviceNum, _Device.DeviceModel);
            _RangeList.Sort((x, y) => { return x.RangeEnd.CompareTo(y.RangeEnd); });
            _DeviceCMDList = ToolMethods.GetDeviceCmdAssembleList(_Device.DeviceModel);

            if (!IsPostBack)
            {
                BindDeviceFunction();
                _DetectPointList = GetDetectPointList();
                BindDetectPointList(_DetectPointList);
            }
            Label1.Text ="提示信息!";
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                _Function = BusinessFacadeShanliTech_HLD_Business.DeviceFunctionDisp(FunctionID);
                _Device = BusinessFacadeShanliTech_HLD_Business.DeviceDisp(_Function.DeviceID);

                BindDataList();
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
    
     _Function = BusinessFacadeShanliTech_HLD_Business.DeviceFunctionDisp(FunctionID);
     _Device = BusinessFacadeShanliTech_HLD_Business.DeviceDisp(_Function.DeviceID);
     if (!Page.IsPostBack)
     {
         BindDataList(_Function, _Device);
         OnStart(_Function, _Device);
     }
     if (string.IsNullOrEmpty(CMD)) CMD = "New";
 }
        public ModuleSelectionPresenter()
        {
            deviceList = new List<DeviceEntity>();
            objKiosk = new monitoringProxy.DeviceEntity();
            objPrinter = new monitoringProxy.DeviceEntity();
            objCashAcceptor = new monitoringProxy.DeviceEntity();
            objServiceResponse = new HealthCheckResponse();
            IsBackendServiceConnected = InitConnectivityPolling();

            pollcounter = Convert.ToInt16(string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["PUSHMONITORINGUPDATECOUNT"]) ? "10" : ConfigurationManager.AppSettings["PUSHMONITORINGUPDATECOUNT"]);

            //if (bool.Parse(ConfigurationManager.AppSettings["StandAloneMode"]) == false)
            //    IsBackendServiceConnected = InitConnectivityPolling();
            //else
            //    IsBackendServiceConnected = true;
        }
        public async Task<List<DeviceEntity>> GetDevices()
        {
            var listOfDevices = new List<DeviceEntity>();
            try
            {
                DeviceEntity deviceEntity;
                var devices = await registryManager.GetDevicesAsync(maxCountOfDevices);

                if (devices != null)
                {
                    foreach (var device in devices)
                    {
                        deviceEntity = new DeviceEntity()
                        {
                            Id = device.Id,
                            ConnectionState = device.ConnectionState.ToString(),
                            ConnectionString = CreateDeviceConnectionString(device),
                            LastActivityTime = device.LastActivityTime,
                            LastConnectionStateUpdatedTime = device.ConnectionStateUpdatedTime,
                            LastStateUpdatedTime = device.StatusUpdatedTime,
                            MessageCount = device.CloudToDeviceMessageCount,
                            State = device.Status.ToString(),
                            SuspensionReason = device.StatusReason
                        };

                        if (device.Authentication != null &&
                            device.Authentication.SymmetricKey != null)
                        {
                            deviceEntity.PrimaryKey = device.Authentication.SymmetricKey.PrimaryKey;
                            deviceEntity.SecondaryKey = device.Authentication.SymmetricKey.SecondaryKey;
                        }

                        listOfDevices.Add(deviceEntity);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return listOfDevices;
        }
        private void OnStart(DeviceFunctionEntity _Function,DeviceEntity _Device)
        {
            
            Device_Permition_DataEntity ut = BusinessFacadeShanliTech_HLD_Business.Device_Permition_DataDisp(IDX);
            OnStartData(ut,_Function,_Device);
            HiddenColumnsByPermitType(_Device.PermitType);
            switch (CMD)
            {
                case "New":
                    HideDisp();
                    break;
                case "List":
                    //HideInput();
                    HideDisp();
                    break;
                case "Edit":
                    HideDisp();
                    break;
                case "Delete":
                    #region 删除
                    
                    //ToolMethods.FunctionAndPointDeleteByDeviceID(IDX);  //级联删除相关功能及功能测试点

                    //ut.DataTable_Action_ = DataTable_Action.Update;
                    //ut.DelFlag = true;
                    //if (BusinessFacadeShanliTech_HLD_Business.DeviceInsertUpdateDelete(ut) > 0)
                    //{
                    //    EventMessage.MessageBox(1, "删除成功", string.Format("删除ID:{0}成功!", IDX), Icon_Type.OK, Common.GetHomeBaseUrl("Default.aspx"));
                    //}
                    //else
                    //{
                    //    EventMessage.MessageBox(1, "删除失败", string.Format("删除ID:{0}失败!", IDX), Icon_Type.Error, Common.GetHomeBaseUrl("Default.aspx"));
                    //}

                    #endregion
                    break;
            }
            HiddenFreqByFuncCode();
        }
 /// <summary>
 /// 绑定数据
 /// </summary>
 private void BindDataList(DeviceFunctionEntity _Function, DeviceEntity _Device)
 {
     QueryParam qp = new QueryParam();
     qp.Where = string.Format("Where DeviceNum = '{0}' And DeviceModel = '{1}' And FunctionCode = '{2}'", _Device.DeviceNum, _Device.DeviceModel, _Function.FunctionCode);
     qp.PageIndex = AspNetPager1.CurrentPageIndex;
     qp.PageSize = AspNetPager1.PageSize;
     qp.Orderfld = Orderfld;
     qp.OrderType = OrderType;
     int RecordCount = 0;
     List<Device_Permition_DataEntity> lst = BusinessFacadeShanliTech_HLD_Business.Device_Permition_DataList(qp, out RecordCount);
     GridView1.DataSource = lst;
     GridView1.DataBind();
     this.AspNetPager1.RecordCount = RecordCount;
 }
示例#39
0
        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="ut"></param>
        private void OnStartData(DeviceEntity ut)
        {
            CertifcateNumPart_Input.Text = CertifcateNumPart_Disp.Text = ut.CertifcateNumPart.ToString();
            //CmdClose_Input.Text = CmdClose_Disp.Text = ut.CmdClose.ToString();
            //CmdClear_Input.Text = CmdClear_Disp.Text = ut.CmdClear.ToString();
            //CmdOpen_Input.Text = CmdOpen_Disp.Text = ut.CmdOpen.ToString();
            CmdReset_Input.Text = CmdReset_Disp.Text = ut.CmdReset.ToString();
            CmdZero_Input.Text = CmdZero_Disp.Text = ut.CmdZero.ToString();
            CmdRead_Input.Text = CmdRead_Disp.Text = ut.CmdRead.ToString();
            CmdSTBY_Input.Text = CmdSTBY_Disp.Text = ut.CmdSTBY.ToString();
            SetCmdPerfix_Input.Text = SetCmdPerfix_Disp.Text = ut.SetCmdPerfix.ToString();
            SetCmdSuffix_Input.Text = SetCmdSuffix_Disp.Text = ut.SetCmdSuffix.ToString();

            DetectType_DropDown.SelectedValue = ut.DetectType.ToString();
            DetectType_Disp.Text = DetectType_DropDown.SelectedItem.Text;

            DeviceFactory_Input.Text = DeviceFactory_Disp.Text = ut.DeviceFactory.ToString();
            DeviceModel_Input.Text = DeviceModel_Disp.Text = ut.DeviceModel.ToString();
            DeviceName_Input.Text = DeviceName_Disp.Text = ut.DeviceName.ToString();
            DeviceNum_Input.Text = DeviceNum_Disp.Text = ut.DeviceNum.ToString();
            DeviceCategory_DropDown.SelectedValue = ut.DeviceCategoryID.ToString();
            DeviceCategoryID_Disp.Text = DeviceCategory_DropDown.SelectedItem.Text;

            Sleep_Input.Text = Sleep_Disp.Text = ut.Sleep.ToString();
            RS232_Conn_Input.Text = RS232_Conn_Disp.Text = ut.RS232_ConnStr.ToString();

            BoardNumber_Input.Text = BoardNumber_Disp.Text = ut.BoardNumber.ToString();
            PrimaryAddress_Input.Text = PrimaryAddress_Disp.Text = ut.PrimaryAddress.ToString();
            SecondaryAddress_Input.Text = SecondaryAddress_Disp.Text = ut.SecondaryAddress.ToString();
            ConnectType_DropDown.SelectedValue = ut.ConnectType.ToString();
            ConnectType_Disp.Text = ConnectType_DropDown.SelectedItem.Text;

            kvalue_Input.Text = kvalue_Disp.Text = ut.kvalue.ToString();
            kname_Input.Text = kname_Disp.Text = ut.kname.ToString();
            AccuracyLevel_Input.Text = AccuracyLevel_Disp.Text = ut.AccuracyLevel.ToString();
            ScaleUnit_Disp.Text = ScaleUnit_Input.Text = ut.ScaleUnit;
            ScaleValue_Disp.Text = ScaleValue_Input.Text = ut.ScaleValue.ToString();
            RangeUnit_Disp.Text = RangeUnit_Input.Text = ut.RangeUnit;
            RangeValue_Disp.Text = RangeValue_Input.Text = ut.RangeValue.ToString();
            DetectMedium_Input.Text = DetectMedium_Disp.Text = ut.DetectMedium;
            RoundLen_Input.Text = RoundLen_Disp.Text = ut.RoundLen.ToString();

            switch (ut.PermitType)
            {
                case 1:
                    Permit_Default.Checked = true;
                    E_PermitType_Disp.Text = Permit_Default.Text;
                    break;
                case 2:
                    Permit_Range.Checked = true;
                    E_PermitType_Disp.Text = Permit_Range.Text;
                    break;
                case 3:
                    Permit_Precision.Checked = true;
                    E_PermitType_Disp.Text = Permit_Precision.Text;
                    break;
            }
        }
 private void OnStartData(Device_Permition_DataEntity ut,DeviceFunctionEntity _Function,DeviceEntity _Device)
 {
     //FuncCode_Disp.Text = _Function.FunctionCode;
     //FuncRange_Disp.Text = _Function.TestRange;
     Unit_Disp.Text = Unit_Input.Text = ut.RangeUnitOriginal;
     Range_Input.Text = ut.RangeEndOriginal.ToString();
     RangeCode_Input.Text = ut.RangeCode;
     RangeFull_Input.Text = ut.RangeFull.ToString();
     FrequencyStart_Input.Text = ut.FreqStartOriginal.ToString();
     FrequencyEnd_Input.Text = ut.FreqEndOriginal.ToString();
     FreqStartUnit_DropDown.SelectedValue = ut.FreqStartUnitOriginal;
     FreqEndUnit_DropDown.SelectedValue = ut.FreqEndUnitOriginal;
     Ratio0_Input.Text = (100 * ut.Ratio0).ToString();
     Ratio1_Input.Text = (100 * ut.Ratio1).ToString();
     ConstValue_Input.Text = ut.ConstValueOriginal.ToString();
     ConstValueUnit_Input.Text = ut.ConstValueUnitOriginal;
     MinGraduation_Input.Text = MinGraduation_Disp.Text = ut.MinimumGraduationOriginal.ToString();
     MinUnit_Disp.Text = MinUnit_Input.Text = ut.MinimumUnitOriginal;
     PrecisionCount_Input.Text = ut.PrecisionCount.ToString();
 }