IEnumerable <Subscription> GetSubscriptions(byte[] bytes, int headerLength) { if (bytes.Length - headerLength < 4) //At least 4 bytes required on payload: MSB, LSB, Topic Filter, Requests QoS { throw new MqttProtocolViolationException(ClientProperties.SubscribeFormatter_MissingTopicFilterQosPair); } int index = headerLength; do { string topicFilter = bytes.GetString(index, out index); if (!topicEvaluator.IsValidTopicFilter(topicFilter)) { throw new MqttException(ClientProperties.SubscribeFormatter_InvalidTopicFilter(topicFilter)); } byte requestedQosByte = bytes.Byte(index); if (!Enum.IsDefined(typeof(MqttQualityOfService), requestedQosByte)) { throw new MqttProtocolViolationException(ClientProperties.Formatter_InvalidQualityOfService); } MqttQualityOfService requestedQos = (MqttQualityOfService)requestedQosByte; yield return(new Subscription(topicFilter, requestedQos)); index++; } while(bytes.Length - index + 1 >= 2); }
public async Task <IActionResult> Edit(int id, [Bind("Id,ClientId,Key,Value")] ClientProperties clientProperties) { if (id != clientProperties.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(clientProperties); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ClientPropertiesExists(clientProperties.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(clientProperties)); }
public DefaultClientTemplate() { Properties = new ClientProperties(); Schedule = new ClientSchedule(); Status = new ClientStatus(); PluginTemplate = new DefaultPluginTemplate(); }
byte[] GetPayload(Subscribe packet) { if (packet.Subscriptions == null || !packet.Subscriptions.Any()) { throw new MqttProtocolViolationException(ClientProperties.SubscribeFormatter_MissingTopicFilterQosPair); } List <byte> payload = new List <byte>(); foreach (Subscription subscription in packet.Subscriptions) { if (string.IsNullOrEmpty(subscription.TopicFilter)) { throw new MqttProtocolViolationException(ClientProperties.SubscribeFormatter_MissingTopicFilterQosPair); } if (!topicEvaluator.IsValidTopicFilter(subscription.TopicFilter)) { throw new MqttException(ClientProperties.SubscribeFormatter_InvalidTopicFilter(subscription.TopicFilter)); } byte[] topicBytes = MqttProtocol.Encoding.EncodeString(subscription.TopicFilter); byte requestedQosByte = Convert.ToByte(subscription.MaximumQualityOfService); payload.AddRange(topicBytes); payload.Add(requestedQosByte); } return(payload.ToArray()); }
async Task DispatchPacketAsync(IPacket packet) { IProtocolFlow flow = _flowProvider.GetFlow(packet.Type); if (flow != null) { try { _packets.OnNext(packet); await _flowRunner.Run(async() => { Publish publish = packet as Publish; if (publish == null) { _tracer.Info(ClientProperties.ClientPacketListener_DispatchingMessage(_clientId, packet.Type, flow.GetType().Name)); } else { _tracer.Info(ClientProperties.ClientPacketListener_DispatchingPublish(_clientId, flow.GetType().Name, publish.Topic)); } await flow.ExecuteAsync(_clientId, packet, _channel); }); } catch (Exception ex) { NotifyError(ex); } } }
void StartKeepAliveMonitor() { int interval = _configuration.KeepAliveSecs * 1000; _keepAliveTimer = new Timer { AutoReset = true, IntervalMillisecs = interval }; _keepAliveTimer.Elapsed += async(sender, e) => { try { _tracer.Warn(ClientProperties.ClientPacketListener_SendingKeepAlive(_clientId, _configuration.KeepAliveSecs)); PingRequest ping = new PingRequest(); await _channel.SendAsync(ping); } catch (Exception ex) { NotifyError(ex); } }; _keepAliveTimer.Start(); _channel.SenderStream.Subscribe(p => { _keepAliveTimer.IntervalMillisecs = interval; }); }
public async Task SendAsync(byte[] message) { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } if (!IsConnected) { throw new MqttException(ClientProperties.MqttChannel_ClientNotConnected); } _sender.OnNext(message); try { _tracer.Verbose(ClientProperties.MqttChannel_SendingPacket(message.Length)); await _client.GetStream() .WriteAsync(message, 0, message.Length); } catch (ObjectDisposedException disposedEx) { throw new MqttException(ClientProperties.MqttChannel_StreamDisconnected, disposedEx); } }
IDisposable ListenFirstPacket() { return(_channel .ReceiverStream .FirstOrDefaultAsync() .Subscribe(async packet => { if (packet == default(IPacket)) { return; } _tracer.Info(ClientProperties.ClientPacketListener_FirstPacketReceived(_clientId, packet.Type)); if (!(packet is ConnectAck connectAck)) { NotifyError(ClientProperties.ClientPacketListener_FirstReceivedPacketMustBeConnectAck); return; } if (_configuration.KeepAliveSecs > 0) { StartKeepAliveMonitor(); } await DispatchPacketAsync(packet); }, ex => { NotifyError(ex); })); }
protected async Task MonitorAckAsync <T>(Publish sentMessage, string clientId, IMqttChannel <IPacket> channel) where T : IFlowPacket { using (IDisposable intervalSubscription = Observable .Interval(TimeSpan.FromSeconds(configuration.WaitTimeoutSecs), NewThreadScheduler.Default) .Subscribe(async _ => { if (channel.IsConnected) { _tracer.Warn(ClientProperties.PublishFlow_RetryingQoSFlow(sentMessage.Type, clientId)); Publish duplicated = new Publish(sentMessage.Topic, sentMessage.QualityOfService, sentMessage.Retain, duplicated: true, packetId: sentMessage.PacketId) { Payload = sentMessage.Payload }; await channel.SendAsync(duplicated); } })) { await channel .ReceiverStream .ObserveOn(NewThreadScheduler.Default) .OfType <T>() .FirstOrDefaultAsync(x => x.PacketId == sentMessage.PacketId.Value); } }
public void CloneTest() { string expectedDesc = "desc"; bool expectedIsEnabled = true; string expectedName = "name"; PropertyDictionary expectedPd = new PropertyDictionary() { { "key1", "value1" } }; ClientProperties target = new ClientProperties() { Description = expectedDesc, IsEnabled = expectedIsEnabled, Name = expectedName, Properties = expectedPd }; ClientProperties actual = target.Clone(); Assert.AreEqual(expectedDesc, actual.Description, "Description"); Assert.AreEqual(expectedIsEnabled, actual.IsEnabled, "IsEnabled"); Assert.AreEqual(expectedName, actual.Name, "Name"); foreach (var item in actual.Properties) { Assert.IsTrue(expectedPd.ContainsKey(item.Key), "Key " + item.Key + " not found."); Assert.AreEqual(expectedPd[item.Key], item.Value, "Value " + expectedPd[item.Key] + " not equal to " + item.Value); } }
byte[] GetVariableHeader(Publish packet) { if (!_topicEvaluator.IsValidTopicName(packet.Topic)) { throw new MqttException(ClientProperties.PublishFormatter_InvalidTopicName(packet.Topic)); } if (packet.PacketId.HasValue && packet.QualityOfService == MqttQualityOfService.AtMostOnce) { throw new MqttException(ClientProperties.PublishFormatter_InvalidPacketId); } if (!packet.PacketId.HasValue && packet.QualityOfService != MqttQualityOfService.AtMostOnce) { throw new MqttException(ClientProperties.PublishFormatter_PacketIdRequired); } List <byte> variableHeader = new List <byte>(); byte[] topicBytes = MqttProtocol.Encoding.EncodeString(packet.Topic); variableHeader.AddRange(topicBytes); if (packet.PacketId.HasValue) { byte[] packetIdBytes = MqttProtocol.Encoding.EncodeInteger(packet.PacketId.Value); variableHeader.AddRange(packetIdBytes); } return(variableHeader.ToArray()); }
public Task SendAsync(byte[] message) { if (_disposed) { throw new ObjectDisposedException(nameof(PrivateChannel)); } if (!IsConnected) { throw new MqttException(ClientProperties.MqttChannel_ClientNotConnected); } _sender.OnNext(message); try { _tracer.Verbose(ClientProperties.MqttChannel_SendingPacket(message.Length)); _stream.Send(message, _identifier); return(Task.FromResult(true)); } catch (ObjectDisposedException disposedEx) { throw new MqttException(ClientProperties.MqttChannel_StreamDisconnected, disposedEx); } }
IDisposable SubscribeStream() { EndpointIdentifier senderIdentifier = _identifier == EndpointIdentifier.Client ? EndpointIdentifier.Server : EndpointIdentifier.Client; return(_stream .Receive(senderIdentifier) .ObserveOn(NewThreadScheduler.Default) .Subscribe(packet => { _tracer.Verbose(ClientProperties.MqttChannel_ReceivedPacket(packet.Length)); _receiver.OnNext(packet); }, ex => { if (ex is ObjectDisposedException) { _receiver.OnError(new MqttException(ClientProperties.MqttChannel_StreamDisconnected, ex)); } else { _receiver.OnError(ex); } }, () => { _tracer.Warn(ClientProperties.MqttChannel_NetworkStreamCompleted); _receiver.OnCompleted(); })); }
public async Task <IActionResult> Create([Bind("Id,ClientId,Key,Value")] ClientProperties clientProperties) { if (ModelState.IsValid) { _context.Add(clientProperties); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(clientProperties)); }
protected void ValidateHeaderFlag(byte[] bytes, Func <MqttPacketType, bool> packetTypePredicate, int expectedFlag) { byte headerFlag = bytes.Byte(0).Bits(5, 4); if (packetTypePredicate(PacketType) && headerFlag != expectedFlag) { string error = ClientProperties.Formatter_InvalidHeaderFlag(headerFlag, typeof(T).Name, expectedFlag); throw new MqttException(error); } }
IDisposable ListenCompletionAndErrors() => _channel .ReceiverStream .Subscribe(_ => { }, ex => NotifyError(ex) , () => { _tracer.Warn(ClientProperties.ClientPacketListener_PacketChannelCompleted(_clientId)); _packets.OnCompleted(); } );
public string getStringVariable(ushort clientID, ClientProperties property) { IntPtr valuePtr = IntPtr.Zero; uint result = Error.ok; if ((result = GetClientVariableAsString(_serverID, clientID, property, out valuePtr)) != Error.ok) { notifyError(string.Format("Error getting variable: {0}", property.ToString())); return(string.Empty); } return(getStringFromPointer(valuePtr)); }
public async Task <IPacket> FormatAsync(byte[] bytes) { MqttPacketType actualType = (MqttPacketType)bytes.Byte(0).Bits(4); if (PacketType != actualType) { throw new MqttException(ClientProperties.Formatter_InvalidPacket(typeof(T).Name)); } T packet = await Task.Run(() => Read( bytes )); return(packet); }
public async Task when_subscribing_invalid_topic_then_fails(string topicFilter) { IMqttClient client = await GetClientAsync(); AggregateException ex = Assert.Throws <AggregateException>(() => client.SubscribeAsync(topicFilter, MqttQualityOfService.AtMostOnce).Wait()); Assert.NotNull(ex); Assert.NotNull(ex.InnerException); Assert.True(ex.InnerException is MqttClientException); Assert.NotNull(ex.InnerException.InnerException); Assert.NotNull(ex.InnerException.InnerException is MqttException); ex.InnerException.InnerException.Message.Should().Be(ClientProperties.SubscribeFormatter_InvalidTopicFilter(topicFilter)); }
public async Task <byte[]> FormatAsync(IPacket packet) { if (packet.Type != PacketType) { string error = ClientProperties.Formatter_InvalidPacket(typeof(T).Name); throw new MqttException(error); } byte[] bytes = await Task.Run(() => Write( packet as T )); return(bytes); }
byte[] GetPayload(Connect packet) { if (packet.ClientId.Length > MqttProtocol.ClientIdMaxLength) { throw new MqttException(ClientProperties.ConnectFormatter_ClientIdMaxLengthExceeded); } if (!IsValidClientId(packet.ClientId)) { throw new MqttException(ClientProperties.ConnectFormatter_InvalidClientIdFormat(packet.ClientId)); } List <byte> payload = new List <byte>(); byte[] clientIdBytes = MqttProtocol.Encoding.EncodeString(packet.ClientId); payload.AddRange(clientIdBytes); if (packet.Will != null) { byte[] willTopicBytes = MqttProtocol.Encoding.EncodeString(packet.Will.Topic); byte[] willMessageBytes = packet.Will.Payload; byte[] willMessageLengthBytes = MqttProtocol.Encoding.EncodeInteger(willMessageBytes.Length); payload.AddRange(willTopicBytes); payload.Add(willMessageLengthBytes[willMessageLengthBytes.Length - 2]); payload.Add(willMessageLengthBytes[willMessageLengthBytes.Length - 1]); payload.AddRange(willMessageBytes); } if (string.IsNullOrEmpty(packet.UserName) && !string.IsNullOrEmpty(packet.Password)) { throw new MqttException(ClientProperties.ConnectFormatter_PasswordNotAllowed); } if (!string.IsNullOrEmpty(packet.UserName)) { byte[] userNameBytes = MqttProtocol.Encoding.EncodeString(packet.UserName); payload.AddRange(userNameBytes); } if (!string.IsNullOrEmpty(packet.Password)) { byte[] passwordBytes = MqttProtocol.Encoding.EncodeString(packet.Password); payload.AddRange(passwordBytes); } return(payload.ToArray()); }
public void Dispose() { if (_disposed) { return; } _tracer.Info(ClientProperties.Mqtt_Disposing(GetType().FullName)); _subscription.Dispose(); _receiver.OnCompleted(); _innerChannel.Dispose(); _disposed = true; }
public byte[] DownloadFileData(CacheIndex index, int fileId, CacheFileInfo fileInfo) { if (!fileInfo.Crc.HasValue) { throw new ArgumentException("File CRC must be set when requesting HTTP files."); } if (!fileInfo.Version.HasValue) { throw new ArgumentException("File version must be set when requesting HTTP files."); } if (!fileInfo.CompressedSize.HasValue) { throw new ArgumentException("File compressed size must be set when requesting HTTP files."); } var webRequest = WebRequest.CreateHttp( $"https://{ClientProperties.GetContentServerHostname()}/ms?m=0&a={(int)index}&k={ClientProperties.GetServerVersion().Item1}&g={fileId}&c={fileInfo.Crc}&v={fileInfo.Version}" ); try { using var response = (HttpWebResponse)webRequest.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { throw new DownloaderException($"HTTP interface responded with status code: {response.StatusCode}."); } if (response.ContentLength != fileInfo.CompressedSize) { throw new DownloaderException($"Downloaded file size {response.ContentLength} does not match expected {fileInfo.CompressedSize}."); } var dataStream = new MemoryStream(); var dataWriter = new BinaryWriter(dataStream); var responseReader = new BinaryReader(response.GetResponseStream()); dataWriter.Write(responseReader.ReadBytesExactly((int)response.ContentLength)); return(dataStream.ToArray()); } catch (WebException exception) { throw new DownloaderException( $"Could not download {(int)index}/{fileId} via HTTP due to a request error.", exception ); } }
public void Dispose() { if (_disposed) { return; } _tracer.Info(ClientProperties.Mqtt_Disposing(GetType().FullName)); _listenerDisposable.Dispose(); _packets.OnCompleted(); (_flowRunner as IDisposable)?.Dispose(); _disposed = true; }
public FsdManager(IEventBroker broker, IAppConfig config) : base(broker) { mConfig = config; mSystemUID = SystemIdentifier.GetSystemDriveVolumeId(); mPositionUpdateTimer = new System.Timers.Timer(); mPositionUpdateTimer.Elapsed += PositionUpdateTimer_Elapsed; if (!Directory.Exists(Path.Combine(mConfig.AppPath, "NetworkLogs"))) { Directory.CreateDirectory(Path.Combine(mConfig.AppPath, "NetworkLogs")); } var directory = new DirectoryInfo(Path.Combine(mConfig.AppPath, "NetworkLogs")); var query = directory.GetFiles("*", SearchOption.AllDirectories); foreach (var file in query.OrderByDescending(file => file.CreationTime).Skip(10)) { file.Delete(); } ClientProperties = new ClientProperties("xPilot", mVersion, Assembly.GetEntryAssembly().Location.CheckSum(), ""); mRawDataStream = new StreamWriter(Path.Combine(mConfig.AppPath, $"NetworkLogs/NetworkLog-{DateTime.UtcNow:yyyyMMddHHmmss}.log"), false); FSD = new FSDSession(ClientProperties); FSD.IgnoreUnknownPackets = true; FSD.NetworkError += FSD_NetworkError; FSD.ProtocolErrorReceived += FSD_ProtocolErrorReceived; FSD.RawDataReceived += FSD_RawDataReceived; FSD.RawDataSent += FSD_RawDataSent; FSD.NetworkConnected += FSD_NetworkConnected; FSD.NetworkDisconnected += FSD_NetworkDisconnected; FSD.ServerIdentificationReceived += FSD_ServerIdentificationReceived; FSD.KillRequestReceived += FSD_KillRequestReceived; FSD.AcarsResponseReceived += FSD_AcarsResponseReceived; FSD.RadioMessageReceived += FSD_RadioMessageReceived; FSD.TextMessageReceived += FSD_TextMessageReceived; FSD.BroadcastMessageReceived += FSD_BroadcastMessageReceived; FSD.PilotPositionReceived += FSD_PilotPositionReceived; FSD.ATCPositionReceived += FSD_ATCPositionReceived; FSD.ClientQueryResponseReceived += FSD_ClientQueryResponseReceived; FSD.ClientQueryReceived += FSD_ClientQueryReceived; FSD.PlaneInfoRequestReceived += FSD_PlaneInfoRequestReceived; FSD.PlaneInfoResponseReceived += FSD_PlaneInfoResponseReceived; FSD.LegacyPlaneInfoResponseReceived += FSD_LegacyPlaneInfoResponseReceived; FSD.DeletePilotReceived += FSD_DeletePilotReceived; FSD.DeleteATCReceived += FSD_DeleteATCReceived; FSD.FlightPlanReceived += FSD_FlightPlanReceived; FSD.PingReceived += FSD_PingReceived; }
public ClientSideHandshake(SSPClient client, ClientProperties Properties) { this.Client = client; this.HandShakes = new List <Handshake>(); this.HandShakes.Add(new CHS_Validation(client)); this.HandShakes.Add(new CHS_Seed(client)); this.HandShakes.Add(new CHS_KeyExchange(client)); this.HandShakes.Add(new CHS_Authentication(client, Properties)); this.HandShakes.Add(new CHS_TimeSynchronisation(client)); this.HandShakes.Add(new CHS_ClientInfo(client)); this.HandShakes.Add(new CHS_UDP(client, Properties)); this.HandShakes.Add(new CHS_Plugins(client)); this.HandShakes.Add(new CHS_ShareClasses(client)); }
protected override Publish Read(byte[] bytes) { int remainingLength = MqttProtocol.Encoding.DecodeRemainingLength(bytes, out int remainingLengthBytesLength); byte packetFlags = bytes.Byte(0).Bits(5, 4); if (packetFlags.Bits(6, 2) == 0x03) { throw new MqttException(ClientProperties.Formatter_InvalidQualityOfService); } MqttQualityOfService qos = (MqttQualityOfService)packetFlags.Bits(6, 2); bool duplicated = packetFlags.IsSet(3); if (qos == MqttQualityOfService.AtMostOnce && duplicated) { throw new MqttException(ClientProperties.PublishFormatter_InvalidDuplicatedWithQoSZero); } bool retainFlag = packetFlags.IsSet(0); int topicStartIndex = 1 + remainingLengthBytesLength; string topic = bytes.GetString(topicStartIndex, out int nextIndex); if (!_topicEvaluator.IsValidTopicName(topic)) { throw new MqttException(ClientProperties.PublishFormatter_InvalidTopicName(topic)); } int variableHeaderLength = topic.Length + 2; ushort?packetId = default; if (qos != MqttQualityOfService.AtMostOnce) { packetId = bytes.Bytes(nextIndex, 2).ToUInt16(); variableHeaderLength += 2; } Publish publish = new Publish(topic, qos, retainFlag, duplicated, packetId); if (remainingLength > variableHeaderLength) { int payloadStartIndex = 1 + remainingLengthBytesLength + variableHeaderLength; publish.Payload = bytes.Bytes(payloadStartIndex); } return(publish); }
public void Dispose() { if (_disposed) { return; } _tracer.Info(ClientProperties.Mqtt_Disposing(nameof(PrivateChannel))); _streamSubscription.Dispose(); _receiver.OnCompleted(); _stream.Dispose(); _disposed = true; }
public async Task <IMqttChannel <byte[]> > CreateAsync() { TcpClient tcpClient = new TcpClient(); try { Task connectTask = tcpClient.ConnectAsync(_hostAddress, _configuration.Port); Task timeoutTask = Task.Delay(TimeSpan.FromSeconds(_configuration.ConnectionTimeoutSecs)); Task resultTask = await Task .WhenAny(connectTask, timeoutTask); if (resultTask == timeoutTask) { throw new TimeoutException(); } if (resultTask.IsFaulted) { ExceptionDispatchInfo.Capture(resultTask.Exception.InnerException).Throw(); } return(new TcpChannel(tcpClient, new PacketBuffer(), _configuration)); } catch (SocketException socketEx) { string message = ClientProperties.TcpChannelFactory_TcpClient_Failed(_hostAddress, _configuration.Port); _tracer.Error(socketEx, message); throw new MqttException(message, socketEx); } catch (TimeoutException timeoutEx) { try { // Just in case the connection is a little late, // dispose the tcpClient. This may throw an exception, // which we should just eat. tcpClient.Dispose(); } catch { } string message = ClientProperties.TcpChannelFactory_TcpClient_Failed(_hostAddress, _configuration.Port); _tracer.Error(timeoutEx, message); throw new MqttException(message, timeoutEx); } }
/// <summary> /// Create a connection to the specified endpoint or return existing one /// </summary> /// <exception cref="T:RabbitMQ.Client.Exceptions.BrokerUnreachableException">When the configured host name was not reachable</exception> public override IConnection CreateConnection() { lock (_syncLock) { if (_connectionSingleton == null) { if (!ClientProperties.ContainsKey("SrUfSdkType")) { Configure(); // configure only the first time, even if disconnect happens } _connectionSingleton = base.CreateConnection(); ConnectionCreated = DateTime.Now; } return(_connectionSingleton); } }
private static extern uint SetClientVariableAsString(ulong serverID, ClientProperties flag, string value);
private static extern uint GetClientVariableAsString(ulong serverID, ushort clientID, ClientProperties flag, out IntPtr result);
private static extern uint SetClientVariableAsInt(ulong serverID, ClientProperties flag, int value);
static extern uint GetClientVariableAsulong(ulong serverID, ushort clientID, ClientProperties flag, out ulong result);
public string getStringVariable(ushort clientID, ClientProperties property) { IntPtr valuePtr = IntPtr.Zero; uint result = Error.ok; if ((result = GetClientVariableAsString(_serverID, clientID, property, out valuePtr)) != Error.ok) { notifyError(string.Format("Error getting variable: {0}", property.ToString())); return string.Empty; } return getStringFromPointer(valuePtr); }
public static extern uint getClientVariableAsString(uint64 arg0, anyID arg1, ClientProperties arg2, out IntPtr arg3);
static extern uint GetClientSelfVariableAsString(ulong serverID, ClientProperties flag, out IntPtr result);
static extern uint GetClientSelfVariableAsInt(ulong serverID, ClientProperties flag, out int result);
public int getIntVariable(ClientProperties property) { int value = 0; if (GetClientSelfVariableAsInt(_connectedServerID, property, out value) != Error.ok) { notifyError(string.Format("Error getting variable: {0}", property.ToString())); return 0; } return value; }
public bool setIntVariable(ulong serverID, ulong channelID, ClientProperties property, int value) { if (SetClientSelfVariableAsInt(_connectedServerID, property, value) != Error.ok) { notifyError(string.Format("Error setting variable: {0}", property.ToString())); return false; } return true; }