Ejemplo n.º 1
0
        public void When_reading_non_padded_hexadecimal_string_it_should_throw(string dataToParse, params byte[] expectedData)
        {
            // Arrange
            _parser = CreateSubject(dataToParse);
            int position = 0;

            // Act
            Func <byte> readByte = () => _parser.ReadByte();

            foreach (byte expectedByte in expectedData)
            {
                position += 2;
                readByte.Should()
                .NotThrow("two or more characters are still on the stream")
                .Which.Should()
                .Be(expectedByte);
            }

            // Assert
            _parser.AtEndOfStream()
            .Should()
            .BeFalse("the last char is not read yet");

            ProtocolReaderException ex = readByte
                                         .Should()
                                         .Throw <ProtocolReaderException>("the stream does not have enough hex chars left")
                                         .Which;

            ex.Message.Should().StartWith("Reached end of stream");
            ex.Position.Should().Be(position);
            ex.Length.Should().Be(dataToParse.Length);

            _parser.AtEndOfStream().Should().BeTrue();
        }
Ejemplo n.º 2
0
        public void When_reading_beyond_end_of_stream_it_should_throw(string dataToParse, int successfulReadsCount)
        {
            // Arrange
            _parser = CreateSubject(dataToParse);
            if (!string.IsNullOrEmpty(dataToParse))
            {
                _parser.AtEndOfStream().Should().BeFalse();
            }

            // Act
            Func <byte> readByte = () => _parser.ReadByte();

            for (int i = 0; i < successfulReadsCount; i++)
            {
                readByte.Should().NotThrow();
            }

            // Assert
            _parser.AtEndOfStream()
            .Should()
            .BeTrue("all hex data was read");

            readByte
            .Should()
            .Throw <ProtocolReaderException>()
            .Which.Message
            .Should().StartWith("Reached end of stream");
        }
Ejemplo n.º 3
0
 public ServerService(IListener listener, IPublisher publisher, IProtocolReader protocolReader, IProtocolOrchestrator protocolOrchestrator)
 {
     _listener             = listener;
     _publisher            = publisher;
     _protocolReader       = protocolReader;
     _protocolOrchestrator = protocolOrchestrator;
 }
Ejemplo n.º 4
0
        public void When_reading_to_end_should_return_correct_string(string dataToParse, params object[] expectedValues)
        {
            // Arrange
            _parser = CreateSubject(dataToParse);

            // Act & Assert
            _parser.ReadByte().Should().Be((byte)expectedValues[0]);
            _parser.ReadByte().Should().Be((byte)expectedValues[1]);
            _parser.ReadToEnd().Should().Be((string)expectedValues[2]);
            _parser.AtEndOfStream().Should().BeTrue();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// At this moment the bytes are read(parsed) and return as a string.
        /// </summary>
        private static DeviceSettingsPayload ParseCompositeZwave(int ProtocolNr, IProtocolReader reader)
        {
            var setting = reader.ReadByte();

            if (setting != 0x47)
            {
                throw new ArgumentOutOfRangeException(String.Format("By 0x4D (Composite Zwave) Expected byte is: 0x47 found: {0:x2}", setting));
            }
            var data = new ZWaveNetworkInfo();

            data.NumberOfDevices = reader.ReadByte();
            var nbrOfClientInfo = reader.ReadByte();

            for (int i = 0; i < nbrOfClientInfo; i++)
            {
                data.ClientInfos.Add(new ZWaveClientInfo
                {
                    Info = reader.ReadEncapsulatedString('"')
                });
            }

            setting = reader.ReadByte();
            if (setting != (byte)DeviceSettingType.ClientZWaveNetworkInfoList)
            {
                throw new ArgumentOutOfRangeException(String.Format("By 0x4D (Composite Zwave) Expected byte after client info's is: 0x60 found: {0:x2}", setting));
            }

            var nbrOfDevices = reader.ReadByte();

            for (int i = 0; i < nbrOfDevices; i++)
            {
                data.Devices.Add(new ZWaveNetworkDevice
                {
                    NodeId     = reader.ReadByte(),
                    DeviceType = reader.ReadByte()
                });
            }

            var deviceSettingValueStr = JsonConvert.SerializeObject(data,
                                                                    new JsonSerializerSettings()
            {
                Converters = new JsonConverter[] { new StringEnumConverter() },
                Formatting = Formatting.Indented
            }
                                                                    );

            return(new DeviceSettingsPayload
            {
                LastReceived = DateTime.Now.ToUniversalTime(),
                Client = null,
                DeviceSettingValueStr = deviceSettingValueStr
            });
        }
Ejemplo n.º 6
0
        public void When_reading_datetime_should_read_correct_value(string dataToParse, string expectedDateStr)
        {
            // Arrange
            _parser = CreateSubject(dataToParse);
            DateTime expectedDate = XmlConvert.ToDateTime(expectedDateStr, XmlDateTimeSerializationMode.Unspecified);

            // Act
            DateTime actual = _parser.ReadDateTime();

            // Assert
            actual.Should().Be(expectedDate);
            _parser.AtEndOfStream().Should().BeTrue();
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Can the message be parsed?
 /// </summary>
 /// <remarks>
 /// This is checked by actually parsing the message, so only use in contexts that are not performance critical.
 /// </remarks>
 public bool CanParse(string source)
 {
     BaseParseResult = new MiniParseResult();
     try
     {
         Reader = _protocolReaderFactory.Create(source.AsMemory());
         DoParse();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 8
0
        public void Read(IProtocolReader protocol, ModelHeader modelHeader)
        {
            for (var a = 0; a < modelHeader.PropertyCount; a++)
            {
                var propertyHeader = protocol.ReadModelPropertyStart();

                if (!this.ReadProperty(protocol, propertyHeader))
                {
                    throw new Exception("Property " + propertyHeader.PropertyName + " not recognized");
                }

                protocol.ReadModelPropertyEnd();
            }
        }
Ejemplo n.º 9
0
        public void When_reading_encapsulated_text_that_does_not_start_with_char_should_throw()
        {
            // Arrange
            _parser = CreateSubject("data");

            // Act
            Action act = () => _parser.ReadEncapsulatedString('|');

            // Assert
            ProtocolReaderException ex = act.Should().Throw <ProtocolReaderException>().Which;

            ex.Position.Should().Be(0);
            ex.Length.Should().Be(4);
        }
Ejemplo n.º 10
0
        public void When_reading_encapsulated_text_should_return_correct_data(string dataToParse, char delimiter, params string[] expectedValues)
        {
            // Arrange
            _parser = CreateSubject(dataToParse);

            // Act
            foreach (string expectedValue in expectedValues)
            {
                string actual = _parser.ReadEncapsulatedString(delimiter);

                actual.Should().Be(expectedValue);
            }

            // Assert
            _parser.AtEndOfStream().Should().BeTrue();
        }
Ejemplo n.º 11
0
        public void When_reading_ushort_should_read_correct_value(string dataToParse, params ushort[] expectedValues)
        {
            // Arrange
            _parser = CreateSubject(dataToParse);

            // Act
            foreach (ushort expectedValue in expectedValues)
            {
                ushort actual = _parser.ReadUInt16();

                // Assert
                actual.Should().Be(expectedValue);
            }

            _parser.AtEndOfStream().Should().BeTrue();
        }
Ejemplo n.º 12
0
        public void When_reading_byte_should_read_correct_value(string dataToParse, params byte[] expectedValues)
        {
            // Arrange
            _parser = CreateSubject(dataToParse);

            // Act
            foreach (byte expectedValue in expectedValues)
            {
                byte actual = _parser.ReadByte();

                // Assert
                actual.Should().Be(expectedValue);
            }

            _parser.AtEndOfStream().Should().BeTrue();
        }
Ejemplo n.º 13
0
        public void When_reading_byte_from_data_that_is_not_hexadecimal_it_should_throw()
        {
            // Arrange
            _parser = CreateSubject("Zs");

            // Act
            Action readByte = () => _parser.ReadByte();

            // Assert
            ProtocolReaderException ex = readByte.Should()
                                         .Throw <ProtocolReaderException>()
                                         .Which;

            ex.InnerException.Should().BeOfType <FormatException>()
            .Which.Message.Should().Be("Could not find any recognizable digits.");
            ex.Position.Should().Be(0);
            ex.Length.Should().Be(2);

            _parser.AtEndOfStream().Should().BeTrue();
        }
Ejemplo n.º 14
0
        /// <inheritdoc />
        public BaseParseResult Parse(string source)
        {
            _logger.LogTrace("Enter");
            BaseParseResult = new MiniParseResult();
            try
            {
                Reader = _protocolReaderFactory.Create(source.AsMemory());
                DoParse();
            }
            catch (Exception e)
            {
                BaseParseResult = new ErrorParseResult(BaseParseResult)
                {
                    Error = String.Format("Source: {0}{1}Error: {2} {3}", source, Environment.NewLine, e.Message, e.InnerException == null ? "" : e.InnerException.Message)
                };
                _logger.LogError(e, "{0} (source = {1})", e.Message, source);
            }

            _logger.LogTrace("Return");
            return(BaseParseResult);
        }
Ejemplo n.º 15
0
 public ProtocolReader(ConnectionContext connection, IProtocolReader <TReadMessage> reader, int?maximumMessageSize)
 {
     Connection          = connection;
     _reader             = reader;
     _maximumMessageSize = maximumMessageSize;
 }
Ejemplo n.º 16
0
 public static ProtocolReader <TReadMessage> CreateReader <TReadMessage>(this ConnectionContext connection, IProtocolReader <TReadMessage> reader, int?maximumMessageSize = null)
 => new ProtocolReader <TReadMessage>(connection, reader, maximumMessageSize);
Ejemplo n.º 17
0
        /// <summary>
        /// Parse devicesettings and returns one or a list of DeviceSettings
        /// Number of DeviceSettings is dependent on first DeviceSettingType (setting), SensorSettingsComposite and SensorMeasurements contains multi settings
        /// </summary>
        /// <param name="ProtocolNr">Firmware version 39: clientbyte added by client settings & client info</param>
        /// <param name="setting">DeviceSettingType</param>
        /// <param name="reader">The protocol reader.</param>
        /// <returns></returns>
        public static IEnumerable <DeviceSettingsPayload> GetDeviceSettings(int ProtocolNr, DeviceSettingType setting, IProtocolReader reader)
        {
            bool handled = false;

            if (ProtocolNr >= 41)
            {
                handled = true;
                switch (setting)
                {
                case DeviceSettingType.P1CounterOptions:
                    yield return(new DeviceSettingsPayload {
                        LastReceived = DateTime.Now.ToUniversalTime(), DeviceSetting = setting, DeviceSettingValue = reader.ReadByte()
                    });

                    break;

                case DeviceSettingType.ClientManufacturerReport:
                    yield return(new DeviceSettingsPayload
                    {
                        LastReceived = DateTime.Now.ToUniversalTime(),
                        DeviceSetting = setting,
                        Client = null,
                        DeviceSettingValueStr =
                            String.Format("Manufacturer ID {0}, Product type {1}, Product ID {2}",
                                          reader.ReadInt16(),
                                          reader.ReadInt16(),
                                          reader.ReadInt16())
                    });

                    break;

                case DeviceSettingType.ClientNodeId:
                case DeviceSettingType.ClientNumberOfDevicesInZWaveNetwork:
                    reader.ReadByte();
                    break;

                case DeviceSettingType.ClientCounterTypesSmartPlug:
                    var nbrCounterTypes = reader.ReadByte();
                    for (int i = 0; i < nbrCounterTypes; i++)
                    {
                        reader.ReadByte();
                    }
                    break;

                case DeviceSettingType.ClientCompositeZWave:                          // 0x4D
                    yield return(ParseCompositeZwave(ProtocolNr, reader));

                    break;

                case DeviceSettingType.ClientRawNodeInformation:
                case DeviceSettingType.ClientRawSupportedReport:
                    reader.ReadByte();
                    reader.ReadEncapsulatedString('"');
                    break;

                case DeviceSettingType.ClientZWaveNetworkInfoList:                         // 0x60,
                    break;

                case DeviceSettingType.ClientZWaveMeterReport:                         // 0x61,
                    break;

                case DeviceSettingType.ClientZwaveBasicSetSetting:                         // 0x62
                    break;

                default:
                    handled = false;
                    break;
                }
            }

            if ((!handled) && (ProtocolNr >= 44))
            {
                handled = true;
                switch (setting)
                {
                case DeviceSettingType.P1DSMRVersion:
                    yield return(new DeviceSettingsPayload {
                        LastReceived = DateTime.Now.ToUniversalTime(), DeviceSetting = setting, DeviceSettingValue = reader.ReadByte()
                    });

                    break;

                default:
                    handled = false;
                    break;
                }
            }

            if (!handled)
            {
                switch (setting)
                {
                case DeviceSettingType.ManufacturerMeterType:
                    yield return(new DeviceSettingsPayload {
                        LastReceived = DateTime.Now.ToUniversalTime(), DeviceSetting = setting, DeviceSettingValue = reader.ReadInt32()
                    });

                    break;

                case DeviceSettingType.Sensor1Low:
                case DeviceSettingType.Sensor1High:
                case DeviceSettingType.Sensor2Low:
                case DeviceSettingType.Sensor2High:
                case DeviceSettingType.SensorMinPulseLength:
                case DeviceSettingType.SensorMinPulseWidth:
                case DeviceSettingType.SensorMaxPulseWidth:
                case DeviceSettingType.SensorMinGap:
                case DeviceSettingType.SensorMaxGap:
                case DeviceSettingType.SensorNoiseLevel:
                case DeviceSettingType.SensorFilterCoefficient:
                case DeviceSettingType.SensorPulseLengthMin:
                case DeviceSettingType.SensorPulseLengthMax:
                case DeviceSettingType.SensorPulseWidthMin:
                case DeviceSettingType.SensorPulseWidthMax:
                case DeviceSettingType.SensorBaselineMin:
                case DeviceSettingType.SensorBaselineMax:
                case DeviceSettingType.SensorSignalMin:
                case DeviceSettingType.SensorSignalMax:
                case DeviceSettingType.SensorSignalAverage:
                    yield return(new DeviceSettingsPayload {
                        LastReceived = DateTime.Now.ToUniversalTime(), DeviceSetting = setting, DeviceSettingValue = reader.ReadUInt16()
                    });

                    break;

                case DeviceSettingType.PrimaryMeterType:
                case DeviceSettingType.SecondaryMeterType:
                case DeviceSettingType.SensorChannel:
                    yield return(new DeviceSettingsPayload {
                        LastReceived = DateTime.Now.ToUniversalTime(), DeviceSetting = setting, DeviceSettingValue = reader.ReadByte()
                    });

                    break;

                case DeviceSettingType.CalibrationSettingsComposite:
                    for (byte i = 0; i < 4; i++)
                    {
                        yield return(new DeviceSettingsPayload {
                            LastReceived = DateTime.Now.ToUniversalTime(), DeviceSetting = (DeviceSettingType)reader.ReadByte(), DeviceSettingValue = reader.ReadUInt16()
                        });
                    }
                    break;

                case DeviceSettingType.SensorSettingsComposite:
                    for (byte i = 0; i < 7; i++)
                    {
                        yield return(new DeviceSettingsPayload {
                            LastReceived = DateTime.Now.ToUniversalTime(), DeviceSetting = (DeviceSettingType)reader.ReadByte(), DeviceSettingValue = reader.ReadUInt16()
                        });
                    }
                    break;

                case DeviceSettingType.SensorMeasurements:
                    for (int i = 0; i < 9; i++)
                    {
                        yield return(new DeviceSettingsPayload {
                            LastReceived = DateTime.Now.ToUniversalTime(), DeviceSetting = (DeviceSettingType)reader.ReadByte(), DeviceSettingValue = reader.ReadUInt16()
                        });
                    }
                    break;

                case DeviceSettingType.FirmwareUrl:
                case DeviceSettingType.ReportUrl:
                case DeviceSettingType.P1ManufacturerCode:
                    yield return(new DeviceSettingsPayload {
                        LastReceived = DateTime.Now.ToUniversalTime(), DeviceSetting = setting, DeviceSettingValueStr = reader.ReadEncapsulatedString('"')
                    });

                    break;

                case DeviceSettingType.ClientProductAndSerialNumber:
                case DeviceSettingType.ClientRawP1Data:
                    yield return(new DeviceSettingsPayload
                    {
                        LastReceived = DateTime.Now.ToUniversalTime(),
                        DeviceSetting = setting,
                        Client = ProtocolNr >= 39 ? (QboxClient?)reader.ReadByte() : null,
                        DeviceSettingValueStr = reader.ReadEncapsulatedString('"')
                    });

                    break;

                case DeviceSettingType.ClientPrimaryMeterType:
                case DeviceSettingType.ClientSecondaryMeterType:
                case DeviceSettingType.ClientFirmwareVersion:
                    yield return(new DeviceSettingsPayload
                    {
                        LastReceived = DateTime.Now.ToUniversalTime(),
                        DeviceSetting = setting,
                        Client = ProtocolNr >= 39 ? (QboxClient?)reader.ReadByte() : null,
                        DeviceSettingValue = reader.ReadByte()
                    });

                    break;

                default:
                    throw new Exception(String.Format("Unknown device setting: {0}", setting));
                }
            }
        }
Ejemplo n.º 18
0
 public ListenerService(IProtocolSender protocolSender, IProtocolReader protocolReader)
 {
     _protocolSender = protocolSender;
     _protocolReader = protocolReader;
 }
Ejemplo n.º 19
0
 protected virtual bool ReadProperty(IProtocolReader protocol, ModelPropertyHeader propertyHeader)
 {
     return(false);
 }