Exemplo n.º 1
0
        protected override void Write(IFileWriter dataWriter, DataChunk chunk)
        {
            var prefixSize = StructSerializer.GetSize <GzipChunkPrefix>();

            using (MemoryStream memoryStream = new MemoryStream(prefixSize + chunk.Data.Length))
            {
                using (GZipStream compressionStream = new GZipStream(memoryStream, CompressionMode.Compress, leaveOpen: true))
                {
                    memoryStream.Position = prefixSize;
                    compressionStream.Write(chunk.Data, 0, chunk.Data.Length);
                }

                var prefix = new GzipChunkPrefix()
                {
                    ChunkSize    = chunk.Data.Length,
                    Offset       = chunk.Offset,
                    GzipDataSize = (int)memoryStream.Length - prefixSize
                };

                memoryStream.Position = 0;
                var prefixBytes = StructSerializer.Serialize(prefix);
                memoryStream.Write(prefixBytes, 0, prefixBytes.Length);

                memoryStream.Capacity = (int)memoryStream.Length;
                var compressedData = memoryStream.GetBuffer();

                var offset = Interlocked.Add(ref _writeOffset, compressedData.Length) - compressedData.Length;
                dataWriter.WriteChunk(offset, compressedData);
            }
        }
Exemplo n.º 2
0
        public void TestOnlyAByte()
        {
            var obj = new OnlyAByte(0xab);
            var onlyAByteSerializer = new StructSerializer(new BaseSerializer[] { new ByteSerializer(obj.F1) });
            var expected            = new byte[] { 0xab };

            Assert.Equal(expected, onlyAByteSerializer.Serialize());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Converts the struct to a memory stream in host-endian format (little-endian on PCs).
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The structure.</param>
        /// <returns></returns>
        public static MemoryStream ToStream <T>([NotNull] this T source)
            where T : struct
        {
            source.ThrowIfNull(nameof(source));

            var ms = new MemoryStream();

            StructSerializer.Serialize(ms, source);
            return(ms);
        }
Exemplo n.º 4
0
        public void TestByteAndUInt32()
        {
            var obj = new ByteAndUInt32()
            {
                F1 = 0xab,
                F2 = 0x010203,
            };
            var byteAndUInt32Serializer = new StructSerializer(new BaseSerializer[] { new ByteSerializer(obj.F1), new UInt32Serializer(obj.F2) });

            byte[] expected = new byte[] { 0xab, 0x03, 0x02, 0x01, 0x00 };
            Assert.Equal(expected, byteAndUInt32Serializer.Serialize());
        }
Exemplo n.º 5
0
        public void Dispatch(DeviceLookup lookup)
        {
            //Update values
            DateTime now = DateTime.Now;

            for (int i = 0; i < _config.Count; i++)
            {
                int messageIndex = i / TelemetryMessage.EntryLength;
                int entryIndex   = i % TelemetryMessage.EntryLength;

                DeviceValue entry = _messages[messageIndex].Devices[entryIndex];
                object      value = lookup[entry.Hash].Get();
                if (lookup[entry.Hash].Property.PropertyType == typeof(Int32))
                {
                    _messages[messageIndex].Devices[entryIndex].IValue = (Int32)value;
                }
                else if (lookup[entry.Hash].Property.PropertyType == typeof(float))
                {
                    _messages[messageIndex].Devices[entryIndex].DValue = (float)value;
                }
                else
                {
                    Console.WriteLine("Unknown Type: {0}", lookup[entry.Hash].Property.PropertyType);
                }
            }

            //Send packets
            foreach (TelemetryMessage message in _messages)
            {
                //var m = message;
                //m.Header.DateTime = now;

                //Send telemetry
                byte[] buffer = StructSerializer.Serialize(message);
                _stream.Write(buffer);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Converts the struct to a byte array in host-endian format (little-endian on PCs).
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="source">The structure.</param>
 /// <returns></returns>
 public static byte[] ToBytes <T>([NotNull] this T source)
     where T : struct => StructSerializer.Serialize(source);
Exemplo n.º 7
0
        static async Task Main(string[] args)
        {
            // udp server configuration
            var serverIpAddress = IPAddress.Parse("192.168.1.53");
            var serverPort      = 9996;
            var serverEndpoint  = new IPEndPoint(serverIpAddress, serverPort);

            // automapper initialization for mapping interop Datagrams => Models
            // NTS: Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
            MapperConfiguration config = new MapperConfiguration(
                cfg =>
            {
                cfg.CreateMap <HandshakeResponseDatagram, HandshakeResponseModel>();
                cfg.CreateMap <CarUpdateDatagram, CarStateModel>();
            }
                );

            var mapper = new Mapper(config);

            var handshakeRequest = new TelemetryServerConfigurationDatagram()
            {
                identifier  = PlatformType.Web,
                version     = 1,
                operationId = OperationType.Handshake
            };

            // serialize request
            var requestByteArray = StructSerializer.Serialize(handshakeRequest);

            // send request and block for response
            using var client = new UdpClient();
            client.Connect(serverEndpoint);
            client.Send(requestByteArray, Marshal.SizeOf(typeof(TelemetryServerConfigurationDatagram)));
            var responseByteArray = client.Receive(ref serverEndpoint);

            // deserialize and map to model
            var handshakeResponse = StructSerializer.Deserialize <HandshakeResponseDatagram>(responseByteArray, 0);
            var handshakeOutput   = mapper.Map <HandshakeResponseModel>(handshakeResponse);

            // print result of handshake
            Console.WriteLine(handshakeOutput);

            var updateRequest = new TelemetryServerConfigurationDatagram()
            {
                identifier  = PlatformType.Web,
                operationId = OperationType.SubscriberUpdate,
                version     = 1
            };

            requestByteArray = StructSerializer.Serialize(updateRequest);
            await client.SendAsync(requestByteArray, Marshal.SizeOf(typeof(TelemetryServerConfigurationDatagram)));

            var path = $"telemetry/" +
                       $"{handshakeOutput.DriverName}/" +
                       $"{handshakeOutput.TrackName}/" +
                       $"{handshakeOutput.CarName}/";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using var streamWriter = new StreamWriter($"{path}/{DateTime.Now.ToFileTime()}.csv");
            using var csvWriter    = new CsvWriter(streamWriter, CultureInfo.InvariantCulture);
            csvWriter.WriteHeader(typeof(CarStateModel));

            Console.CancelKeyPress += (sender, e) =>
            {
                csvWriter.Flush();
                streamWriter.Close();
                csvWriter.Dispose();
                streamWriter.Dispose();

                var disconnect = new TelemetryServerConfigurationDatagram()
                {
                    identifier  = PlatformType.Web,
                    operationId = OperationType.Dismiss,
                    version     = 1
                };

                requestByteArray = StructSerializer.Serialize(disconnect);
                client.Send(requestByteArray, Marshal.SizeOf(typeof(TelemetryServerConfigurationDatagram)));
                Console.WriteLine("Exiting Gracefully...");
                Environment.Exit(0);
            };

            await ProcessSubscriberUpdates(client, csvWriter, mapper);
        }