示例#1
0
        private static Twin SetupTwins(uint?deviceFcntUp, uint?deviceFcntDown, uint?startFcntUp, uint?startFcntDown, bool abpRelaxed, bool supports32Bit, SimulatedDevice simulatedDevice, DevEui devEui, DevAddr devAddr)
        {
            var initialTwin = new Twin();

            initialTwin.Properties.Desired[TwinProperty.DevEUI]        = devEui.ToString();
            initialTwin.Properties.Desired[TwinProperty.AppEui]        = simulatedDevice.LoRaDevice.AppEui?.ToString();
            initialTwin.Properties.Desired[TwinProperty.AppKey]        = simulatedDevice.LoRaDevice.AppKey?.ToString();
            initialTwin.Properties.Desired[TwinProperty.NwkSKey]       = simulatedDevice.LoRaDevice.NwkSKey?.ToString();
            initialTwin.Properties.Desired[TwinProperty.AppSKey]       = simulatedDevice.LoRaDevice.AppSKey?.ToString();
            initialTwin.Properties.Desired[TwinProperty.DevAddr]       = devAddr.ToString();
            initialTwin.Properties.Desired[TwinProperty.SensorDecoder] = simulatedDevice.LoRaDevice.SensorDecoder;
            initialTwin.Properties.Desired[TwinProperty.GatewayID]     = simulatedDevice.LoRaDevice.GatewayID;
            initialTwin.Properties.Desired[TwinProperty.ABPRelaxMode]  = abpRelaxed;

            initialTwin.Properties.Desired[TwinProperty.Supports32BitFCnt] = supports32Bit;

            if (deviceFcntUp.HasValue)
            {
                initialTwin.Properties.Reported[TwinProperty.FCntUp] = deviceFcntUp.Value;
            }
            if (deviceFcntDown.HasValue)
            {
                initialTwin.Properties.Reported[TwinProperty.FCntDown] = deviceFcntDown.Value;
            }
            if (startFcntUp.HasValue)
            {
                initialTwin.Properties.Desired[TwinProperty.FCntUpStart] = startFcntUp.Value;
            }
            if (startFcntDown.HasValue)
            {
                initialTwin.Properties.Desired[TwinProperty.FCntDownStart] = startFcntDown.Value;
            }
            return(initialTwin);
        }
        public async ValueTask <DecodePayloadResult> DecodeMessageAsync(DevEui devEui, byte[] payload, FramePort fport, string sensorDecoder)
        {
            sensorDecoder ??= string.Empty;

            var base64Payload = ((payload?.Length ?? 0) == 0) ? string.Empty : Convert.ToBase64String(payload);

            // Call local decoder (no "http://" in SensorDecoder)
            if (Uri.TryCreate(sensorDecoder, UriKind.Absolute, out var url) && url.Scheme is "http")
            {
                // Support decoders that have a parameter in the URL
                // http://decoder/api/sampleDecoder?x=1 -> should become http://decoder/api/sampleDecoder?x=1&devEUI=11&fport=1&payload=12345

                var query = HttpUtility.ParseQueryString(url.Query);
                query["devEUI"]  = devEui.ToString();
                query["fport"]   = ((int)fport).ToString(CultureInfo.InvariantCulture);
                query["payload"] = base64Payload;

                var urlBuilder = new UriBuilder(url)
                {
                    Query = query.ToString()
                };

                if (urlBuilder.Path.EndsWith('/'))
                {
                    urlBuilder.Path = urlBuilder.Path[..^ 1];
示例#3
0
            public void StationEui_Can_Be_Interpreted_As_Dev_Eui()
            {
                const ulong value      = 0x1a2b3c;
                var         devEui     = new DevEui(value);
                var         stationEui = new StationEui(value);

                Assert.Equal(devEui.ToString(), stationEui.ToString());
            }
        public async Task When_Device_Is_Found_Should_Returns_Device_Information()
        {
            // arrange
            var devEui     = new DevEui(13213123212131);
            var primaryKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(PrimaryKey));

            var(registryManager, request) = SetupIotHubQuery(devEui.ToString(), PrimaryKey);
            var searchDeviceByDevEUI = new SearchDeviceByDevEUI(registryManager.Object);

            // act
            var result = await searchDeviceByDevEUI.GetDeviceByDevEUI(request, NullLogger.Instance);

            // assert
            var okObjectResult = Assert.IsType <OkObjectResult>(result);

            Assert.Equal(JsonConvert.SerializeObject(new { DevEUI = devEui.ToString(), PrimaryKey = primaryKey }), JsonConvert.SerializeObject(okObjectResult.Value));
            registryManager.VerifyAll();
        }
示例#5
0
        public async Task When_Querying_Devices_And_Finds_Class_A_Should_Send_Message()
        {
            var devEui = new DevEui(123456789);

            var deviceTwin = new Twin
            {
                Properties = new TwinProperties()
                {
                    Desired = new TwinCollection($"{{\"DevAddr\": \"03010101\"}}"),
                }
            };

            var query = new Mock <IQuery>(MockBehavior.Strict);

            query.Setup(x => x.HasMoreResults).Returns(true);
            query.Setup(x => x.GetNextAsTwinAsync())
            .ReturnsAsync(new[] { deviceTwin });

            this.registryManager.Setup(x => x.CreateQuery(It.IsNotNull <string>(), It.IsAny <int?>()))
            .Returns(query.Object);

            var actualMessage = new LoRaCloudToDeviceMessage()
            {
                MessageId = "myMessageId-1234",
                Fport     = TestPort,
                Payload   = "hello",
            };

            LoRaCloudToDeviceMessage     receivedC2DMessage = null;
            IDictionary <string, string> receivedProperties = null;

            this.serviceClient.Setup(x => x.SendAsync(devEui.ToString(), It.IsNotNull <Message>()))
            .Callback((string d, Message m) => (receivedProperties, receivedC2DMessage) = (m.Properties, JsonConvert.DeserializeObject <LoRaCloudToDeviceMessage>(Encoding.UTF8.GetString(m.GetBytes()))))
            .Returns(Task.CompletedTask);

            var actual = await this.sendCloudToDeviceMessage.SendCloudToDeviceMessageImplementationAsync(
                devEui,
                actualMessage);

            Assert.IsType <OkObjectResult>(actual);
            var responseValue = ((OkObjectResult)actual).Value as SendCloudToDeviceMessageResult;

            Assert.NotNull(responseValue);
            Assert.Equal("A", responseValue.ClassType);
            Assert.Equal(devEui, responseValue.DevEui);
            Assert.Equal(actualMessage.MessageId, responseValue.MessageID);

            Assert.Empty(receivedProperties);
            Assert.Equal(receivedC2DMessage.Fport, actualMessage.Fport);
            Assert.Equal(receivedC2DMessage.Payload, actualMessage.Payload);
            Assert.Equal(receivedC2DMessage.MessageId, actualMessage.MessageId);

            this.serviceClient.VerifyAll();
            this.registryManager.VerifyAll();
            query.VerifyAll();
        }
        public async Task When_Device_Is_Not_Found_Should_Returns_NotFound(string format)
        {
            var devEUI = new DevEui(13213123212131);
            var ctx    = new DefaultHttpContext();

            ctx.Request.QueryString = new QueryString($"?devEUI={devEUI.ToString(format, null)}&{ApiVersion.QueryStringParamName}={ApiVersion.LatestVersion}");

            var registryManager = new Mock <RegistryManager>(MockBehavior.Strict);

            registryManager.Setup(x => x.GetDeviceAsync(devEUI.ToString()))
            .ReturnsAsync((Device)null);

            var searchDeviceByDevEUI = new SearchDeviceByDevEUI(registryManager.Object);

            var result = await searchDeviceByDevEUI.GetDeviceByDevEUI(ctx.Request, NullLogger.Instance);

            Assert.IsType <NotFoundResult>(result);

            registryManager.VerifyAll();
        }
示例#7
0
        public LoRaDeviceCache(ILoRaDeviceCacheStore cacheStore, DevEui devEUI, string gatewayId)
        {
            if (string.IsNullOrEmpty(gatewayId))
            {
                throw new ArgumentNullException(nameof(gatewayId));
            }

            this.cacheStore = cacheStore;
            this.devEUI     = devEUI;
            this.gatewayId  = gatewayId;
            this.cacheKey   = devEUI.ToString();
        }
        /// <summary>
        /// Helper method that calls the API GetDevice method.
        /// </summary>
        private async Task <SearchDevicesResult> SearchDevicesAsync(string gatewayID = null, DevAddr?devAddr = null, DevEui?devEui = null, string appEUI = null, DevNonce?devNonce = null)
        {
            this.deviceLoadRequests?.Add(1);

            var client = this.serviceFacadeHttpClientProvider.GetHttpClient();

            var url = BuildUri("GetDevice", new Dictionary <string, string>
            {
                ["code"]      = AuthCode,
                ["GateWayId"] = gatewayID,
                ["DevAddr"]   = devAddr?.ToString(),
                ["DevEUI"]    = devEui?.ToString(),
                ["AppEUI"]    = appEUI,
                ["DevNonce"]  = devNonce?.ToString()
            });

            var response = await client.GetAsync(url);

            if (!response.IsSuccessStatusCode)
            {
                if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    var badReqResult = await response.Content.ReadAsStringAsync();

                    if (string.Equals(badReqResult, "UsedDevNonce", StringComparison.OrdinalIgnoreCase))
                    {
                        return(new SearchDevicesResult
                        {
                            IsDevNonceAlreadyUsed = true,
                        });
                    }

                    if (badReqResult != null && badReqResult.StartsWith("JoinRefused", StringComparison.OrdinalIgnoreCase))
                    {
                        return(new SearchDevicesResult()
                        {
                            RefusedMessage = badReqResult
                        });
                    }
                }

                this.logger.LogError($"{devAddr} error calling get device function api: {response.ReasonPhrase}, status: {response.StatusCode}, check the azure function log");

                // TODO: FBE check if we return null or throw exception
                return(new SearchDevicesResult());
            }

            var result = await response.Content.ReadAsStringAsync();

            var devices = (List <IoTHubDeviceInfo>)JsonConvert.DeserializeObject(result, typeof(List <IoTHubDeviceInfo>));

            return(new SearchDevicesResult(devices));
        }
        private static RegistryManager InitRegistryManager(DevEui devEui)
        {
            var mockRegistryManager = new Mock <RegistryManager>(MockBehavior.Strict);
            var primaryKey          = Convert.ToBase64String(Encoding.UTF8.GetBytes(PrimaryKey));

            mockRegistryManager
            .Setup(x => x.GetDeviceAsync(It.Is(devEui.ToString(), StringComparer.Ordinal)))
            .ReturnsAsync((string deviceId) => new Device(deviceId)
            {
                Authentication = new AuthenticationMechanism()
                {
                    SymmetricKey = new SymmetricKey()
                    {
                        PrimaryKey = primaryKey
                    }
                }
            });

            mockRegistryManager
            .Setup(x => x.GetTwinAsync(It.Is(devEui.ToString(), StringComparer.Ordinal)))
            .ReturnsAsync((string deviceId) => new Twin(deviceId));

            return(mockRegistryManager.Object);
        }
示例#10
0
        public async Task When_Sending_Message_Throws_Error_Should_Return_Application_Error()
        {
            var devEui = new DevEui(123456789);

            var deviceTwin = new Twin
            {
                Properties = new TwinProperties()
                {
                    Desired = new TwinCollection($"{{\"DevAddr\": \"03010101\"}}"),
                }
            };

            var query = new Mock <IQuery>(MockBehavior.Strict);

            query.Setup(x => x.HasMoreResults).Returns(true);
            query.Setup(x => x.GetNextAsTwinAsync())
            .ReturnsAsync(new[] { deviceTwin });

            this.registryManager.Setup(x => x.CreateQuery(It.IsNotNull <string>(), It.IsAny <int?>()))
            .Returns(query.Object);

            var actualMessage = new LoRaCloudToDeviceMessage()
            {
                MessageId = "myMessageId-1234",
                Fport     = TestPort,
                Payload   = "hello",
            };

            this.serviceClient.Setup(x => x.SendAsync(devEui.ToString(), It.IsNotNull <Message>()))
            .ThrowsAsync(new IotHubCommunicationException(string.Empty));

            var actual = await this.sendCloudToDeviceMessage.SendCloudToDeviceMessageImplementationAsync(
                devEui,
                actualMessage);

            Assert.IsType <ObjectResult>(actual);
            Assert.Equal((int)HttpStatusCode.InternalServerError, ((ObjectResult)actual).StatusCode);

            this.serviceClient.VerifyAll();
            this.registryManager.VerifyAll();
            query.VerifyAll();
        }
        private async Task <IActionResult> SendMessageViaCloudToDeviceMessageAsync(DevEui devEUI, LoRaCloudToDeviceMessage c2dMessage)
        {
            try
            {
                using var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(c2dMessage)));
                message.MessageId = string.IsNullOrEmpty(c2dMessage.MessageId) ? Guid.NewGuid().ToString() : c2dMessage.MessageId;

                try
                {
                    await this.serviceClient.SendAsync(devEUI.ToString(), message);
                }
                catch (IotHubException ex)
                {
                    this.log.LogError(ex, "Failed to send message to {devEUI} to IoT Hub", devEUI);
                    return(new ObjectResult("Failed to send message to device to IoT Hub")
                    {
                        StatusCode = (int)HttpStatusCode.InternalServerError
                    });
                }

                this.log.LogInformation("Sending cloud to device message to {devEUI} succeeded", devEUI);

                return(new OkObjectResult(new SendCloudToDeviceMessageResult()
                {
                    DevEui = devEUI,
                    MessageID = message.MessageId,
                    ClassType = "A",
                }));
            }
            catch (JsonSerializationException ex)
            {
                this.log.LogError(ex, "Failed to serialize message {c2dmessage} for device {devEUI} to IoT Hub", c2dMessage, devEUI);
                return(new ObjectResult("Failed to serialize c2d message to device to IoT Hub")
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError
                });
            }
        }
 /// <inheritdoc />
 public override Task <string> GetPrimaryKeyByEuiAsync(DevEui eui) =>
 GetPrimaryKeyByEuiAsync(eui.ToString());