Пример #1
0
            public async Task Subscribe(CancellationToken ct, string topic)
            {
                if (!_currentClient.Task.IsCompleted)
                {
                    throw new InvalidOperationException("Cannot subscribe to a topic a this point");
                }

                var client = _currentClient.Task.Result;

                if (!client.IsConnected)
                {
                    throw new Exception("The resolved client is not connected");
                }

                topic = topic + "/#";
                this.Log().Info("Subscribing to topic: " + topic);

                using (await _clientGate.LockAsync(ct))
                {
                    await client.SubscribeAsync(topic, MqttQualityOfService.AtLeastOnce);
                }
            }
            public async Task <PendingCommand> Send <TCommand>(TCommand command, CancellationToken ct)
                where TCommand : HomeAssistantCommand
            {
                if (await _state.FirstOrDefaultAsync(state => state == State.Connected) != State.Connected)
                {
                    throw new InvalidOperationException("Connection failed");
                }

                using (await _sendGate.LockAsync(ct))
                    using (var id = _commandIdProvider.GetNext())
                    {
                        var sender  = new PendingCommand(command, this, id, ct);
                        var payload = JsonSerializer.SerializeToUtf8Bytes(command, JsonWriteOpts);

                        await _client.SendAsync(new ArraySegment <byte>(payload), WebSocketMessageType.Text, true, ct);

                        return(sender);
                    }
            }