Пример #1
0
 public BasicsStationConfigurationServiceTests()
 {
     this.stationEui = new StationEui(ulong.MaxValue);
     this.devEui     = DevEui.Parse(this.stationEui.ToString());
     this.loRaDeviceApiServiceMock = new Mock <LoRaDeviceAPIServiceBase>();
     this.loRaDeviceFactoryMock    = new Mock <ILoRaDeviceFactory>();
     this.memoryCache = new MemoryCache(new MemoryCacheOptions());
     this.sut         = new BasicsStationConfigurationService(this.loRaDeviceApiServiceMock.Object,
                                                              this.loRaDeviceFactoryMock.Object,
                                                              this.memoryCache,
                                                              NullLogger <BasicsStationConfigurationService> .Instance);
 }
        public async Task Test_ClassC_Send_Message_Using_Function_Endpoint_Should_Be_Received()
        {
            var device = TestFixtureCi.Device24_ABP;

            LogTestStart(device);

            await ArduinoDevice.setDeviceModeAsync(LoRaArduinoSerial._device_mode_t.LWABP);

            await ArduinoDevice.setIdAsync(device.DevAddr, device.DeviceID, null);

            await ArduinoDevice.setKeyAsync(device.NwkSKey, device.AppSKey, null);

            await ArduinoDevice.SetupLora(TestFixtureCi.Configuration);

            await ArduinoDevice.setClassTypeAsync(LoRaArduinoSerial._class_type_t.CLASS_C);

            // send one confirmed message for ensuring that a basicstation is "bound" to the device
            await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES);

            var msg = PayloadGenerator.Next().ToString(CultureInfo.InvariantCulture);

            Log($"{device.DeviceID}: Sending confirmed '{msg}'");
            await ArduinoDevice.transferPacketWithConfirmedAsync(msg, 10);

            await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES);

            TestFixtureCi.ClearLogs();

            // Now sending a c2d
            var c2d = new LoRaCloudToDeviceMessage()
            {
                DevEUI     = DevEui.Parse(device.DeviceID),
                MessageId  = Guid.NewGuid().ToString(),
                Fport      = FramePorts.App23,
                RawPayload = Convert.ToBase64String(new byte[] { 0xFF, 0x00 }),
            };

            TestLogger.Log($"[INFO] Using service API to send C2D message to device {device.DeviceID}");
            TestLogger.Log($"[INFO] {JsonConvert.SerializeObject(c2d, Formatting.None)}");

            // send message using the SendCloudToDeviceMessage API endpoint
            Assert.True(await LoRaAPIHelper.SendCloudToDeviceMessage(device.DevEui, c2d));

            await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES);

            // 0000000000000024: received cloud to device message from direct method
            await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: received cloud to device message from direct method");

            Assert.Contains(ArduinoDevice.SerialLogs, (l) => l.Contains("PORT: 23; RX: \"FF00\"", StringComparison.Ordinal));
            Assert.Contains(ArduinoDevice.SerialLogs, (l) => l.Contains("RXWIN0, RSSI", StringComparison.Ordinal));
            await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", ArduinoDevice.SerialLogs);
        }
Пример #3
0
        private async Task <List <DevAddrCacheInfo> > GetDeviceTwinsFromIotHub(RegistryManager registryManager, string inputQuery)
        {
            var query       = registryManager.CreateQuery(inputQuery);
            var lastQueryTs = DateTime.UtcNow.AddSeconds(-10); // account for some clock drift

            _ = this.cacheStore.StringSet(LastDeltaUpdateKeyValue, lastQueryTs.ToString(LoraKeysManagerFacadeConstants.RoundTripDateTimeStringFormat, CultureInfo.InvariantCulture), TimeSpan.FromDays(1));
            var devAddrCacheInfos = new List <DevAddrCacheInfo>();

            while (query.HasMoreResults)
            {
                var page = await query.GetNextAsTwinAsync();

                foreach (var twin in page)
                {
                    if (twin.DeviceId != null)
                    {
                        if (!twin.Properties.Desired.TryRead(LoraKeysManagerFacadeConstants.TwinProperty_DevAddr, this.logger, out DevAddr devAddr) &&
                            !twin.Properties.Reported.TryRead(LoraKeysManagerFacadeConstants.TwinProperty_DevAddr, this.logger, out devAddr))
                        {
                            continue;
                        }

                        devAddrCacheInfos.Add(new DevAddrCacheInfo()
                        {
                            DevAddr          = devAddr,
                            DevEUI           = DevEui.Parse(twin.DeviceId),
                            GatewayId        = twin.GetGatewayID(),
                            NwkSKey          = twin.GetNwkSKey(),
                            LastUpdatedTwins = twin.Properties.Desired.GetLastUpdated()
                        });
                    }
                }
            }

            return(devAddrCacheInfos);
        }
Пример #4
0
 public override ILoRaDeviceClient CreateDeviceClient(string deviceId, string primaryKey) =>
 this.deviceClientMap.TryGetValue(DevEui.Parse(deviceId), out var deviceClientToAssign) ? deviceClientToAssign : this.loRaDeviceClient;
Пример #5
0
        public async Task Unconfirmed_Cloud_To_Device_From_Decoder_Should_Send_Downstream_Message(string c2dDevEUI)
        {
            const uint PayloadFcnt           = 10;
            const uint InitialDeviceFcntUp   = 9;
            const uint InitialDeviceFcntDown = 20;

            var simulatedDevice = new SimulatedDevice(
                TestDeviceInfo.CreateABPDevice(1, gatewayID: ServerConfiguration.GatewayID),
                frmCntUp: InitialDeviceFcntUp,
                frmCntDown: InitialDeviceFcntDown);

            var loraDevice = CreateLoRaDevice(simulatedDevice);

            LoRaDeviceClient.Setup(x => x.SendEventAsync(It.IsNotNull <LoRaDeviceTelemetry>(), null))
            .ReturnsAsync(true);

            var decoderResult = new DecodePayloadResult("1")
            {
                CloudToDeviceMessage = new ReceivedLoRaCloudToDeviceMessage()
                {
                    Fport     = TestPort,
                    MessageId = "123",
                    Payload   = "12",
                    DevEUI    = c2dDevEUI is { } someDevEui?DevEui.Parse(someDevEui) : null
                },
            };

            var payloadDecoder = new Mock <ILoRaPayloadDecoder>(MockBehavior.Strict);

            payloadDecoder.Setup(x => x.DecodeMessageAsync(simulatedDevice.DevEUI, It.IsNotNull <byte[]>(), TestPort, It.IsAny <string>()))
            .ReturnsAsync(decoderResult);
            PayloadDecoder.SetDecoder(payloadDecoder.Object);

            using var cache           = EmptyMemoryCache();
            using var loraDeviceCache = CreateDeviceCache(loraDevice);
            using var deviceRegistry  = new LoRaDeviceRegistry(ServerConfiguration, cache, LoRaDeviceApi.Object, LoRaDeviceFactory, loraDeviceCache);

            // Send to message processor
            using var messageProcessor = new MessageDispatcher(
                      ServerConfiguration,
                      deviceRegistry,
                      FrameCounterUpdateStrategyProvider);

            var payload = simulatedDevice.CreateUnconfirmedDataUpMessage("1234", fcnt: PayloadFcnt);

            using var request = CreateWaitableRequest(payload);
            messageProcessor.DispatchRequest(request);
            Assert.True(await request.WaitCompleteAsync());

            // Expectations
            // 1. Message was sent to IoT Hub
            LoRaDeviceClient.VerifyAll();
            LoRaDeviceApi.VerifyAll();

            // 2. Return is downstream message
            Assert.NotNull(request.ResponseDownlink);
            Assert.True(request.ProcessingSucceeded);
            Assert.Single(DownstreamMessageSender.DownlinkMessages);
            var downlinkMessage = DownstreamMessageSender.DownlinkMessages[0];
            var payloadDataDown = new LoRaPayloadData(downlinkMessage.Data);

            payloadDataDown.Serialize(loraDevice.AppSKey.Value);
            Assert.Equal(payloadDataDown.DevAddr, loraDevice.DevAddr);
            Assert.False(payloadDataDown.IsConfirmed);
            Assert.Equal(MacMessageType.UnconfirmedDataDown, payloadDataDown.MessageType);

            // 4. Frame counter up was updated
            Assert.Equal(PayloadFcnt, loraDevice.FCntUp);

            // 5. Frame counter down is updated
            Assert.Equal(InitialDeviceFcntDown + 1, loraDevice.FCntDown);
            Assert.Equal(InitialDeviceFcntDown + 1, payloadDataDown.Fcnt);

            // 6. Frame count has pending changes
            Assert.True(loraDevice.HasFrameCountChanges);

            LoRaDeviceApi.VerifyAll();
            LoRaDeviceClient.VerifyAll();

            payloadDecoder.VerifyAll();
        }
        public void When_Multiple_Scopes_Set_DevEUI_Preferred_Over_DevAddr_Preferred_Over_StationEUI(string devEuiScope, string devAddrScope, int?stationEuiScope, string expected)
        {
            // arrange
            var options  = CreateLoggerConfigMonitor();
            var moqInfo  = new Mock <Action <string> >();
            var provider = new Mock <LoRaConsoleLoggerProvider>(options);
            var logger   = new TestLoRaConsoleLogger(moqInfo.Object, null, provider.Object);

            // act
            using var euiScope = devEuiScope is { } someDevEuiScope?logger.BeginDeviceScope(DevEui.Parse(someDevEuiScope)) : default;

            using var addrScope = devAddrScope is null ? default : logger.BeginDeviceAddressScope(devAddrScope);
                                  using var statScope = stationEuiScope is { } s?logger.BeginEuiScope(new StationEui ((ulong)s)): default;

                                  logger.LogInformation("foo");

                                  // assert
                                  moqInfo.Verify(x => x.Invoke(expected), Times.Once);
        }