public static bool TryUpdate(DroneConfiguration configuration, ConfigurationPacket packet) { bool updated = false; using (var ms = new MemoryStream(packet.Data)) using (var sr = new StreamReader(ms)) { string line; while ((line = sr.ReadLine()) != null) { Match match = _reKeyValue.Match(line); if (match.Success) { string key = match.Groups["key"].Value; IConfigurationItem item; if (configuration.Items.TryGetValue(key, out item)) { string value = match.Groups["value"].Value; if (item.TryUpdate(value)) { updated = true; } else { Trace.TraceWarning("Configuration key {0} update failed. Original line: {1}", key, line); } } else { Trace.TraceWarning("Configuration key {0} is not supported by parser. Original line: {1}", key, line); } } } } return updated; }
public DroneConfiguration GetConfiguration(CancellationToken token) { using (var tcpClient = new TcpClient(_client.NetworkConfiguration.DroneHostname, ControlPort)) using (NetworkStream stream = tcpClient.GetStream()) try { _client.NavigationDataAcquired += OnNavigationData; var buffer = new byte[NetworkBufferSize]; Stopwatch swConfigTimeout = Stopwatch.StartNew(); while (swConfigTimeout.ElapsedMilliseconds < ConfigTimeout) { token.ThrowIfCancellationRequested(); int offset = 0; if (tcpClient.Available == 0) { Thread.Sleep(10); } else { offset += stream.Read(buffer, offset, buffer.Length); swConfigTimeout.Restart(); // config eof check if (offset > 0 && buffer[offset - 1] == 0x00) { var data = new byte[offset]; Array.Copy(buffer, data, offset); var packet = new ConfigurationPacket { Timestamp = DateTime.UtcNow.Ticks, Data = data }; var configuration = new DroneConfiguration(); if (ConfigurationPacketParser.TryUpdate(configuration, packet)) { return configuration; } throw new InvalidDataException(); } } } throw new TimeoutException(); } finally { _client.NavigationDataAcquired -= OnNavigationData; } }
protected override void Loop(CancellationToken token) { using (var tcpClient = new TcpClient(_networkConfiguration.DroneHostname, ControlPort)) using (NetworkStream stream = tcpClient.GetStream()) { var buffer = new byte[NetworkBufferSize]; Stopwatch swConfigTimeout = Stopwatch.StartNew(); while (token.IsCancellationRequested == false && swConfigTimeout.ElapsedMilliseconds < ConfigTimeout) { int offset = 0; if (tcpClient.Available == 0) { Thread.Sleep(1); } else { offset += stream.Read(buffer, offset, buffer.Length); // config eof check if (offset > 0 && buffer[offset - 1] == 0x00) { var data = new byte[offset]; Array.Copy(buffer, data, offset); var packet = new ConfigurationPacket { Timestamp = DateTime.UtcNow.Ticks, Data = data }; _configurationAcquired(packet); return; } } } } }
private void OnConfigurationPacketAcquired(ConfigurationPacket packet) { if (ConfigurationPacketAcquired != null) ConfigurationPacketAcquired(packet); if (ConfigurationPacketParser.TryUpdate(_droneConfiguration, packet)) { if (ConfigurationUpdated != null) ConfigurationUpdated(_droneConfiguration); } }