コード例 #1
0
        public ActionResult <Device> RegisterDevice(RegisterDevice registerDevice)
        {
            if (registerDevice == null || string.IsNullOrWhiteSpace(registerDevice.FirmwareVersion) || string.IsNullOrWhiteSpace(registerDevice.SerialNumber))
            {
                return(BadRequest(new BadRequestObjectResult(ModelState)
                {
                    Value = "Must provide device SerialNumber and FirmwareVersion"
                }));
            }

            var existingDevice = _deviceService.GetBySerial(registerDevice.SerialNumber);

            if (existingDevice != null)
            {
                return(BadRequest(new BadRequestObjectResult(ModelState)
                {
                    Value = "Device already registered."
                }));
            }

            var device = new Device()
            {
                SerialNumber     = registerDevice.SerialNumber,
                FirmwareVersion  = registerDevice.FirmwareVersion,
                RegistrationDate = System.DateTime.Now
            };

            _deviceService.Create(device);

            return(CreatedAtRoute("GetDevice", new { id = device.Id.ToString() }, device));
        }
コード例 #2
0
        public async Task <Models.DTO.Device> Create(
            string userId,
            string tenantId,
            RegisterDevice device,
            CancellationToken cancellationToken)
        {
            if (!ObjectId.TryParse(device.TypeId, out var deviceId))
            {
                throw new ArgumentException("Invalid TypeId");
            }

            var type = await _typeRepository.Get(
                deviceId,
                tenantId,
                cancellationToken)
                       ??
                       throw new ArgumentException("Type not found.");

            var newDevice = DeviceMapper.MapToDomain(
                device,
                type,
                userId,
                tenantId);

            await _deviceRepository.Create(
                newDevice,
                cancellationToken);

            return(DeviceMapper.MapToDto(newDevice));
        }
コード例 #3
0
        public HttpResponseMessage RegisterDevice([FromBody] RegisterDevice device)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            if (string.IsNullOrEmpty(device.Codigo) || string.IsNullOrEmpty(device.Email) || string.IsNullOrEmpty(device.User) || string.IsNullOrEmpty(device.Dni))
            {
                response         = new HttpResponseMessage(HttpStatusCode.BadRequest);
                response.Content = new StringContent(EngineData.modeloImcompleto, Encoding.Unicode);
                return(response);
            }

            Company company = Metodo.GetCompanyCodigo(device.Codigo); //Obtiene el codigo de la empresa

            if (company == null || company.Id == 0)
            {
                response.Content = new StringContent("No existe el codigo ingresado", Encoding.Unicode);
                return(response);
            }
            DevicesCompany deviceCompany = new DevicesCompany();
            int            countDevice   = Metodo.NumberDeviceRegister(company.Id); //Obtiene la cantidad de equipos registrados

            if (countDevice == 0)
            {
                deviceCompany = Funcion.BuilDeviceCompany(company, device, Metodo);
            }
            else
            {
                List <RegisterDevice> listDevice = Metodo.GetListDevicesRegistered(device.Codigo); // Obtiene la lista de equipos registrados
                if (listDevice.Count > countDevice)
                {
                    response.Content = new StringContent("Limite para registrar dispositivos superado", Encoding.Unicode);
                    return(response);
                }
                else
                {
                    deviceCompany = Funcion.BuilDeviceCompany(listDevice, device, Metodo);
                    if (deviceCompany == null)
                    {
                        response.Content = new StringContent("El usuario no existe", Encoding.Unicode);
                        return(response);
                    }
                }
            }
            bool resultado = Metodo.RegisterDevice(deviceCompany);

            if (resultado)
            {
                Metodo.UpdateUserApi(company.Id, company.NameCompany, device.User, device.Email);
                response.Content          = new StringContent(EngineData.transaccionExitosa, Encoding.Unicode);
                response.Headers.Location = new Uri(EngineData.UrlBase + EngineData.UrlDevices);
            }
            else
            {
                response.Content          = new StringContent(EngineData.transaccionFallida, Encoding.Unicode);
                response.Headers.Location = new Uri(EngineData.UrlBase + EngineData.UrlDevices);
            }
            return(response);
        }
コード例 #4
0
        private void OnRegisterDevice(RegisterDevice msg)
        {
            DeviceInfoDto dto = msg.DeviceDto;
            string        uniqueDeviceActorName = ActorSystemReferences.ActorNames.DeviceActorNamePrefix + dto.DeviceId;

            IActorRef deviceActorRef = Context.Child(uniqueDeviceActorName);

            if (deviceActorRef.IsNobody())
            {
                deviceActorRef = Context.ActorOf(Props.Create <DeviceActor>(), uniqueDeviceActorName);
            }
            deviceActorRef.Tell(msg);
        }
コード例 #5
0
        public async Task <ActionResult <Models.DTO.Device> > Post(
            [FromBody] RegisterDevice device,
            CancellationToken cancellationToken)
        {
            var userId   = "GET FROM JWT";
            var tenantId = "GET FROM JWT";

            return(await _deviceService.Create(
                       userId,
                       tenantId,
                       device,
                       cancellationToken));
        }
コード例 #6
0
ファイル: PUCServer.cs プロジェクト: jwnichls/puc
        protected void serverStateChanged(bool added, IDevice2 dev)
        {
            if (_discoveryServiceRunning)
            {
                Message msg = new ServerInformation(Name, _devices.GetEnumerator());

                for (int i = 0; i < _connections.Count; i++)
                {
                    Connection c = (Connection)_connections[i];

                    if (!c.IsConnected())
                    {
                        _connections.RemoveAt(i);
                        i--;
                        continue;
                    }

                    if (c.LocalPort == SERVER_INFO_PORT)
                    {
                        c.Send(msg);
                    }
                }
            }
            else
            {
                if (dev == null)
                {
                    return;
                }

                Message msg;
                if (added)
                {
                    msg = new RegisterDevice(dev.Name, dev.Port);
                }
                else
                {
                    msg = new UnregisterDevice(dev.Port);
                }

                try
                {
                    _discoveryConnection.Send(msg);
                }
                catch (Exception)
                {
                    // problem sending message to discovery service
                }
            }
        }
コード例 #7
0
        public string BuildRegisterDeviceStr(string user, string email, string codigo, string phone, string dni, string nombre)
        {
            RegisterDevice modelo = new RegisterDevice()
            {
                User   = user,
                Email  = email,
                Codigo = codigo,
                Phone  = phone,
                Dni    = dni,
                Nombre = nombre
            };

            return(JsonConvert.SerializeObject(modelo));
        }
コード例 #8
0
ファイル: AddDevice.cs プロジェクト: Neilsawb/AzureFunctions
        public static async Task <string> AddtoSqlAsync(RegisterDevice data)
        {
            using (var conn = new SqlConnection(Environment.GetEnvironmentVariable("SqlConnection")))
            {
                await conn.OpenAsync();

                using (var cmd = new SqlCommand("", conn))
                {
                    /* DeviceVendors */
                    cmd.CommandText = "IF NOT EXISTS (SELECT Id FROM DeviceVendors WHERE VendorName = @Vendor) INSERT INTO DeviceVendors OUTPUT inserted.Id VALUES(@Vendor) ELSE SELECT Id FROM DeviceVendors WHERE VendorName = @Vendor";
                    cmd.Parameters.AddWithValue("@Vendor", data.Vendor);
                    var vendorId = int.Parse(cmd.ExecuteScalar().ToString());

                    /* DeviceModels */
                    cmd.CommandText = "IF NOT EXISTS (SELECT Id FROM DeviceModels WHERE ModelName = @ModelName)INSERT INTO DeviceModels OUTPUT inserted.Id VALUES(@ModelName, @VendorId) ELSE SELECT Id FROM DeviceModels WHERE ModelName = @ModelName";
                    cmd.Parameters.AddWithValue("@ModelName", data.Model);
                    cmd.Parameters.AddWithValue("@VendorId", vendorId);
                    var modelId = int.Parse(cmd.ExecuteScalar().ToString());

                    /* DeviceTypes */
                    cmd.CommandText = "IF NOT EXISTS (SELECT Id FROM DeviceTypes WHERE TypeName = @TypeName) INSERT INTO DeviceTypes OUTPUT inserted.Id VALUES(@TypeName) ELSE SELECT Id FROM DeviceTypes WHERE TypeName = @TypeName";
                    cmd.Parameters.AddWithValue("@TypeName", data.Type);
                    var deviceTypeId = int.Parse(cmd.ExecuteScalar().ToString());

                    /* GeoLocations */
                    cmd.CommandText = "IF NOT EXISTS (SELECT Id FROM GeoLocations WHERE Latitude = @Latitude AND Longitude = @Longitude) INSERT INTO GeoLocations OUTPUT inserted.Id VALUES(@Latitude, @Longitude) ELSE SELECT Id FROM GeoLocations WHERE Latitude = @Latitude AND Longitude = @Longitude";
                    cmd.Parameters.AddWithValue("@Latitude", data.Latitude);
                    cmd.Parameters.AddWithValue("@Longitude", data.Longitude);
                    var geoLocationId = long.Parse(cmd.ExecuteScalar().ToString());

                    /* Devices */
                    cmd.CommandText = "IF NOT EXISTS (SELECT DeviceName FROM Devices WHERE DeviceName = @DeviceName) INSERT INTO Devices OUTPUT inserted.DeviceName VALUES(@DeviceName, @DeviceTypeId, @GeoLocationId, @ModelId) ELSE SELECT DeviceName FROM Devices WHERE DeviceName = @DeviceName";
                    cmd.Parameters.AddWithValue("@DeviceName", data.DeviceName);
                    cmd.Parameters.AddWithValue("@DeviceTypeId", deviceTypeId);
                    cmd.Parameters.AddWithValue("@GeoLocationId", geoLocationId);
                    cmd.Parameters.AddWithValue("@ModelId", modelId);
                    var deviceName = cmd.ExecuteScalar().ToString();

                    /* DhtMeasurements */
                    //var dhtdata = JsonConvert.DeserializeObject<DhtMeasurement>(Encoding.UTF8.GetString(req.));
                    //cmd.Parameters.AddWithValue("@temperature", dhtdata.Temperature);
                    //cmd.Parameters.AddWithValue("@humidity", dhtdata.Humidity);


                    cmd.ExecuteNonQuery();

                    return(deviceName);
                }
            }
        }
コード例 #9
0
        public DevicesCompany BuilDeviceCompany(Company company, RegisterDevice device, IEngineDb Metodo)
        {
            string[]       arrayUser      = { device.Email, device.User };
            UserApi        userApi        = Metodo.GetUser(arrayUser);
            DevicesCompany devicesCompany = new DevicesCompany()
            {
                IdCompany  = company.Id,
                IdUserApi  = userApi.Id,
                IdTypeUser = 2,
                CreateDate = DateTime.UtcNow,
                Phone      = device.Phone,
                Dni        = device.Dni,
                Nombre     = device.Nombre
            };

            return(devicesCompany);
        }
コード例 #10
0
 public static Models.Domain.Device MapToDomain(
     RegisterDevice device,
     Models.Domain.Type type,
     string userId,
     string tenantId)
 {
     return(new Models.Domain.Device
     {
         Name = device.Name,
         TypeId = type.Id,
         TenantId = tenantId,
         UserId = userId,
         ThingTypes = type.ThingTypes,
         Icons = type.Icons,
         Images = type.Images,
         ActuatorValues = type.ActuatorValues,
         SensorValues = type.SensorValues,
         DateAdded = DateTime.UtcNow,
         MessageProtocols = type.MessageProtocols
     });
 }
コード例 #11
0
ファイル: PUCServer.cs プロジェクト: jwnichls/puc
 private void _discoveryConnection_ConnectionRegainedEvent(ConnectionEventArgs args)
 {
     if (!_discoveryServiceRunning)
     {
         try
         {
             IEnumerator e = _devices.GetEnumerator();
             while (e.MoveNext())
             {
                 IDevice2 dev = (IDevice2)e.Current;
                 Message  msg = new RegisterDevice(dev.Name, dev.Port);
                 _discoveryConnection.Send(msg);
             }
         }
         catch (Exception)
         {
             // do nothing here...wait for another opportunity
             // to re-connect
         }
     }
 }
コード例 #12
0
        public DevicesCompany BuilDeviceCompany(List <RegisterDevice> listDevice, RegisterDevice device, IEngineDb Metodo)
        {
            string[] arrayUser = { device.Email, device.User };
            UserApi  userApi   = Metodo.GetUser(arrayUser);

            if (userApi != null)
            {
                DevicesCompany devicesCompany = new DevicesCompany()
                {
                    IdCompany  = listDevice[0].IdCompany,
                    IdUserApi  = userApi.Id,
                    IdTypeUser = 2,
                    CreateDate = DateTime.UtcNow,
                    Phone      = device.Phone,
                    Dni        = device.Dni,
                    Nombre     = device.Nombre
                };
                return(devicesCompany);
            }

            return(null);
        }
コード例 #13
0
ファイル: AddDevice.cs プロジェクト: Neilsawb/AzureFunctions
        public static async Task <string> AddDeviceAsync(RegisterDevice data)
        {
            Device device;

            if (data.DeviceName != null)
            {
                if (data.DeviceName.Length == 17)
                {
                    try
                    {
                        var deviceName = await AddtoSqlAsync(data);

                        try
                        {
                            device = await registryManager.GetDeviceAsync(deviceName);

                            if (device == null)
                            {
                                device = await registryManager.AddDeviceAsync(new Device(data.DeviceName));
                            }

                            if (device.Id == data.DeviceName)
                            {
                                return($"{iotHub.Split(";")[0]};DeviceId={device.Id};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey}");
                            }
                        }
                        catch
                        {
                        }
                    }
                    catch
                    {
                    }
                }
            }

            return("");
        }
コード例 #14
0
        private async Task <string> RegisterDevice(string email, string password, string countryCode)
        {
            RegisterDevice registerUserDevice = new RegisterDevice
            {
                Email          = email,
                Password       = password,
                DeviceId       = GlobalAccess.DeviceId,
                DeviceOS       = GlobalAccess.DeviceOS,
                DeviceTypeId   = (int)GlobalAccess.DeviceService.GetDeviceType(),
                EreaderVersion = GlobalAccess.DeviceService.GetEreaderVersion(),
                CountryCode    = countryCode
            };
            var registerResult = await authenticationService.RegisterDevice(registerUserDevice);

            if (registerResult.IsSuccess)
            {
                var  response = registerResult.DeserializeObject <RegisterDeviceResponse>();
                bool updateSymmetricKeySuccess = (userAccess.UpdateSymmetricKey(response.Key, email, countryCode) > 0);
                if (updateSymmetricKeySuccess)
                {
                    return(response.Key);
                }
            }
            else
            {
                switch (registerResult.Content)
                {
                case Constants.MAX_REG_EXCEEDED:
                    throw new MaxDeviceExceededException(registerResult.Content);

                case Constants.NET_ERROR:
                    throw new CusNetDisConnectedException(registerResult.Content);
                }
            }
            return(null);
        }
        // Message event handler
        private void OnRegisterDevice(RegisterDevice msg)
        {
            _sender = Sender;

            Become(Registered);
        }
コード例 #16
0
        private void OnRegisterDevice(RegisterDevice msg)
        {
            _deviceDto = msg.DeviceDto;

            Become(Registered);
        }
コード例 #17
0
ファイル: DeviceService.cs プロジェクト: nukedbit/stackx
        public async Task <object> AnyAsync(RegisterDevice request)
        {
            string userAuthName = GetSession().UserAuthName;
            string userAuthId   = GetSession().UserAuthId;
            var    utcNow       = DateTime.UtcNow;
            var    existings    = await Db.SelectAsync <Device>(d => d.DeviceId.ToLower() == request.DeviceId.ToLower());

            if (existings.FirstOrDefault() is { } existing)
            {
                if (existing.DeletedDate is not null)
                {
                    return(new RegisterDeviceResponse()
                    {
                        DeviceBlocked = true
                    });
                }

                existing.LastActiveBy   = userAuthName;
                existing.LastActiveDate = utcNow;
                existing.Meta           = request.Meta;
                await Db.SaveAsync(existing);

                return(new RegisterDeviceResponse()
                {
                    DeviceBlocked = false
                });
            }

            var deviceFeature = HostContext.AssertPlugin <DevicesFeature>();

            if (deviceFeature.LimitActiveDevicesForUser)
            {
                var limit = await deviceFeature.GetUserDeviceCountLimitAsync(Request);

                var deviceCount = await Db.CountAsync <Device>(d => d.UserAuthId == userAuthId && d.DeletedDate == null);

                if (deviceCount >= limit)
                {
                    throw new HttpError(HttpStatusCode.Forbidden, "Device Limit Reached");
                }
            }

            var device = new Device()
            {
                UserAuthId     = userAuthId,
                DeviceId       = request.DeviceId,
                Description    = request.Description,
                ModifiedBy     = userAuthName,
                CreatedBy      = userAuthName,
                CreatedDate    = utcNow,
                ModifiedDate   = utcNow,
                LastActiveBy   = userAuthName,
                LastActiveDate = utcNow,
                Meta           = request.Meta,
                DeviceKindId   = request.DeviceKindId
            };
            await Db.InsertAsync(device);

            return(new RegisterDeviceResponse()
            {
                DeviceBlocked = false
            });
        }
コード例 #18
0
ファイル: PUCServer.cs プロジェクト: jwnichls/puc
 public RegisteredDevice(RegisterDevice msg)
 {
     _name = msg.GetDeviceName();
     _port = msg.GetDevicePort();
 }
コード例 #19
0
 public Task <HttpResponse> RegisterDevice(RegisterDevice registerUserDevice)
 {
     return(ServiceAgent.RestFullServiceJsonRequest(base.GetTargetUri(registerUserDevice.CountryCode), ServiceConfig.REGISTER_DEVICE, registerUserDevice));
 }