예제 #1
0
        async Task EstablishMqttConnectionAsync(ConnectionPref pref)
        {
            //configure options
            IMqttClientOptions options = new MqttClientOptionsBuilder()
                                         .WithClientId(_mqttPref.Id.ToString())
                                         .WithTcpServer(_mqttPref.HostAdress, _mqttPref.PortNumber)
                                         // .WithCredentials("bud", "%spencer%")
                                         .WithCleanSession()
                                         .Build();

            //Handlers
            _clientMqtt.UseConnectedHandler(async e =>
            {
                _eventBus?.Print($"Connected successfully with MQTT Brokers.");

                //Subscribe to topic
                await _clientMqtt.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("RemoteSrvrData/#").Build());
            });
            _clientMqtt.UseDisconnectedHandler(e =>
            {
                _eventBus?.Print($"Disconnected from MQTT Brokers. Reason:{e.Reason.ToString()}");
            });
            _clientMqtt.UseApplicationMessageReceivedHandler(async e => { await _eventBus?.OnMqqtEvent(e); });

            //actually connect
            await _clientMqtt.ConnectAsync(options);
        }
예제 #2
0
        public async Task EstablishConnectionAsync(ConnectionPref pref, MqttConnectionPref mqttPref)
        {
            _tcpClient ??= new TcpClient();

            if (!_tcpClient.Connected)
            {
                try
                {
                    _pref     = pref;
                    _mqttPref = mqttPref;
                    _eventBus?.Print("Establishing connection");

                    await _tcpClient.ConnectAsync(_pref.HostNameOrAdress, _pref.PortNumber);

                    NetworkStream stream = _tcpClient.GetStream();
                    _sReader = new StreamReader(stream, Encoding.ASCII);
                    _sWriter = new StreamWriter(stream, Encoding.ASCII)
                    {
                        AutoFlush = true
                    };

                    await _sWriter.WriteLineAsync(_pref.UserName);

                    await _sWriter.WriteLineAsync(_pref.Id.ToString());

                    await EstablishMqttConnectionAsync(_pref);

                    WaitForData();
                    IsConnected = _tcpClient.Connected;
                }
                catch (Exception ex)
                {
                    _eventBus?.Error(ex.Message);
                    IsConnected = false;
                }
            }
        }