public async Task <SessionState> ConnectAsync(MqttClientCredentials credentials, MqttLastWill will = null, bool cleanSession = false) { await _pipe.ConnectAsync(_config.WaitTimeoutSecs * 1000); if (_pipe.TransmissionMode != PipeTransmissionMode.Message) { throw new NotSupportedException("The transmission is only supported in message mode."); } await _pipeFormatter.SendPayloadAsync(StubClientHeader.Connect, credentials, will, cleanSession); Stack result = _pipeFormatter.ReceivePayload(); if (!(result.Pop() is SessionState state)) { throw new InvalidOperationException("Unexpected payload return type."); } return(state); }
async Task Run(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { Queue <object> payload = await _pf.ReceivePayloadAsync(cancellationToken); if (!(payload.Dequeue() is StubClientHeader clientHeader)) { throw new InvalidOperationException("Payload did not start with a ClientHeader."); } switch (clientHeader) { case StubClientHeader.Disconnect: await _client.DisconnectAsync(); _m.Warn($"Disconnect should have empty payload, but the payload contain ${payload.Count} objects."); break; case StubClientHeader.Connect: SessionState state; if (payload.Count == 1) { state = await _client.ConnectAsync((MqttLastWill)payload.Dequeue()); } else if (payload.Count == 3) { state = await _client.ConnectAsync((MqttClientCredentials)payload.Dequeue(), (MqttLastWill)payload.Dequeue(), (bool)payload.Dequeue()); } else { throw new InvalidOperationException("Payload count is incorrect."); } await _pf.SendPayloadAsync(state); break; case StubClientHeader.Publish: await _client.PublishAsync((MqttApplicationMessage)payload.Dequeue(), (MqttQualityOfService)payload.Dequeue(), (bool)payload.Dequeue()); break; case StubClientHeader.Subscribe: await _client.SubscribeAsync((string)payload.Dequeue(), (MqttQualityOfService)payload.Dequeue()); break; case StubClientHeader.Unsubscribe: await _client.UnsubscribeAsync((string[])payload.Dequeue()); break; case StubClientHeader.IsConnected: await _pf.SendPayloadAsync(_client.IsConnected); break; default: throw new InvalidOperationException("Unknown ClientHeader."); } } }