/// <summary> /// Запуск задачи соединения с облаком /// </summary> /// <param name="connection_string"></param> /// <param name="client_id"></param> private async Task <bool> Start(MQTTClient client) { return(await Task.Run(() => { try { var configuration = new MqttConfiguration { //BufferSize = 128 * 1024, Port = client.Port //KeepAliveSecs = 10, //WaitTimeoutSecs = 12, //MaximumQualityOfService = MqttQualityOfService.AtMostOnce //AllowWildcardsInTopicFilters = true }; //System.Net.Sockets.Socket. CloudConnectionResult.Message = "В ожидании соединения"; _client = MqttClient.CreateAsync(client.Server, configuration).Result; _client.Disconnected += _client_Disconnected; var sessionState = _client.ConnectAsync(new MqttClientCredentials(clientId: client.ClientId, userName: client.UserName, password: client.Password), cleanSession: false).Result; CloudConnectionResult.Message = "Соединение установлено"; return true; } catch (System.Exception ex) { CloudConnectionResult.Message = ex.Message; Log.Debug(MQTT_TAG, ex.Message); Toast.MakeText(_context, ex.Message, ToastLength.Long); return false; } })); }
public async static void SetupClient() { localClient = new MqttClientLocal(); var configuration = new MqttConfiguration() { Port = 12393, KeepAliveSecs = 60, WaitTimeoutSecs = 5, BufferSize = 128 * 1024, AllowWildcardsInTopicFilters = true, MaximumQualityOfService = MqttQualityOfService.AtLeastOnce }; string topicSubscribe = "song/#"; string topicSubscribe2 = "status"; remoteClient = await MqttClient.CreateAsync("broker.busk.cf", configuration); await remoteClient.ConnectAsync(new MqttClientCredentials(clientId : "Frontend", "front", "frontpass")); await remoteClient.SubscribeAsync(topicSubscribe, MqttQualityOfService.AtLeastOnce); //subscribe on cloud mqtt await remoteClient.SubscribeAsync(topicSubscribe2, MqttQualityOfService.AtLeastOnce); //subscribe on cloud mqtt localClient.Subscribe(remoteClient.MessageStream); // subscribe to the iobservable (the response message stream) }
public IObservable <uint> Create() { return(Observable.Create <uint>( async observer => { var config = new MqttConfiguration { Port = _configuration.Value.Port, MaximumQualityOfService = MqttQualityOfService.ExactlyOnce, AllowWildcardsInTopicFilters = true }; var client = await MqttClient.CreateAsync(_configuration.Value.Broker, config); _ = await client.ConnectAsync(); await client.SubscribeAsync(_configuration.Value.Topic, MqttQualityOfService.AtLeastOnce); var subscription = client .MessageStream .Where(message => message.Payload.Length == 4) .Select(message => BitConverter.ToUInt32(message.Payload)) .Subscribe(observer); return new CompositeDisposable( subscription, client ); } )); }
public async void publishMQTT(MqttCon mqtt) { if (string.IsNullOrEmpty(mqtt.topic) || string.IsNullOrEmpty(mqtt.msg)) { Console.WriteLine("Debe contener Topic y Message"); } else { Console.WriteLine(mqtt.topic); Console.WriteLine(mqtt.msg); var configuration = new MqttConfiguration { BufferSize = 128 * 1024, Port = 1883, KeepAliveSecs = 10, WaitTimeoutSecs = 2, MaximumQualityOfService = MqttQualityOfService.AtMostOnce, AllowWildcardsInTopicFilters = true }; var client = await MqttClient.CreateAsync("iot02.qaingenieros.com", configuration); var sessionState = await client.ConnectAsync(new MqttClientCredentials(clientId : "foo")); var message1 = new MqttApplicationMessage(mqtt.topic, Encoding.UTF8.GetBytes(mqtt.msg)); await client.PublishAsync(message1, MqttQualityOfService.AtMostOnce); //QoS0 await client.DisconnectAsync(); } }
public static async Task <int> Runner(Options options) { var config = new MqttConfiguration { Port = options.Port, AllowWildcardsInTopicFilters = true }; try { using (var client = await MqttClient.CreateAsync(options.Broker, config)) { var session = await client.ConnectAsync(new MqttClientCredentials(Client.Id.Provider.GetClientId(options), options.Username, options.Password), cleanSession : true); var payload = await GetContent(options); var message = new MqttApplicationMessage(options.Topic, payload); await client.PublishAsync(message, MqttQualityOfService.AtMostOnce); await client.DisconnectAsync(); } Console.WriteLine("Message published successfully."); return(0); } catch (Exception exception) { Console.WriteLine($"Error: {exception.Message}"); return(-1); } }
public bool PostToQueue(string message) { using (var mqttClient = MqttClient.CreateAsync("10.0.0.50").Result) { // var mqttClient = MqttClient.CreateAsync("10.0.0.50").Result ; var sess = mqttClient.ConnectAsync().Result; string rcvTopic = "chickenai" + "/receive"; string sendTopic = "chickenai" + "/command"; mqttClient.SubscribeAsync(rcvTopic, MqttQualityOfService.ExactlyOnce); var sendData = String.Empty; Task.Run(() => { var line = message; var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(line)); // var line = Regex.Unescape("{'command':" + command + "'}"); // var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(line.Replace("'","\"").Remove(0,1))); sendData = data.ToString(); Console.WriteLine(System.DateTime.Now.ToString() + "------- MQTT: SENDTOPIC: " + sendTopic + " --------"); mqttClient.PublishAsync(new MqttApplicationMessage(sendTopic, data), MqttQualityOfService.ExactlyOnce).Wait(); }); } return(true); }
public async void Start() { var configuration = new MqttConfiguration { BufferSize = 128 * 1024, Port = 55555, KeepAliveSecs = 10, WaitTimeoutSecs = 2, MaximumQualityOfService = MqttQualityOfService.AtMostOnce, AllowWildcardsInTopicFilters = true }; var client = await MqttClient.CreateAsync("127.0.0.1", configuration); var sessionState = await client.ConnectAsync(new MqttClientCredentials(clientId : int.MaxValue.ToString()), cleanSession : true); await client.SubscribeAsync("foo/bar/topic1", MqttQualityOfService.AtMostOnce); //QoS0 await client.SubscribeAsync("foo/bar/topic2", MqttQualityOfService.AtLeastOnce); //QoS1 await client.SubscribeAsync("foo/bar/topic3", MqttQualityOfService.ExactlyOnce); //QoS2 //client.MessageStream.Subscribe(msg => Console.WriteLine($"Message received in topic {msg.Topic}")); var message3 = new MqttApplicationMessage("foo/bar/topic4", Encoding.UTF8.GetBytes("Foo Message 4")); await client.PublishAsync(message3, MqttQualityOfService.AtMostOnce); //QoS0 client.MessageStream.Where(msg => msg.Topic == "foo/bar/topic2").Subscribe(msg => Console.WriteLine($"Message received in topic {msg.Topic}")); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var configuration = new MqttConfiguration() { Port = port, AllowWildcardsInTopicFilters = true, KeepAliveSecs = 30, ConnectionTimeoutSecs = 30, WaitTimeoutSecs = 30 }; client = await MqttClient.CreateAsync(broker, configuration); clientId = Guid.NewGuid().ToString().Replace("-", ""); client.Disconnected += Client_Disconnected; do { try { if (!client.IsConnected) { await Connect(); } await Task.Delay(5000, stoppingToken); } catch (Exception ex) { _logger.LogError(ex.GetType().ToString()); _logger.LogError(ex.Message); } }while (!stoppingToken.IsCancellationRequested); }
/// <summary> /// Connects the MQTT. /// </summary> private void ConnectMQTTAsync() { string strHost = Properties.Settings.Default.MQTTHost; int iPort = Properties.Settings.Default.MQTTPort; MqttConfiguration configuration = new MqttConfiguration { //BufferSize = 128 * 1024, Port = iPort, //KeepAliveSecs = 10, //WaitTimeoutSecs = 2, //MaximumQualityOfService = MqttQualityOfService.AtLeastOnce, AllowWildcardsInTopicFilters = true }; try { Task <IMqttClient> tClient = MqttClient.CreateAsync(strHost, configuration); tClient.Wait(); this.mqttclient = tClient.Result; //this.mqttclient.ConnectAsync(new MqttClientCredentials(Tool.ProductName)).Wait(); ////Task<SessionState> session = mqttclient.ConnectAsync(new MqttClientCredentials(Guid.NewGuid().ToString())); //session.Wait(); this.MQTTStatusBrush = Brushes.Lime; this.MQTTStatusMessage = $"Connected To MQTTT Broker ({strHost})"; } catch (Exception ex) { this.MQTTStatusBrush = Brushes.Red; this.MQTTStatusMessage = $"Not Connected To MQTTT Broker ({strHost}):\n{ex.Message}"; } }
private async void Button_ClickedAsync(object sender, EventArgs e) { var configuration = new MqttConfiguration { BufferSize = 128 * 1024, Port = 1883, KeepAliveSecs = 10, WaitTimeoutSecs = 2, MaximumQualityOfService = MqttQualityOfService.AtMostOnce, AllowWildcardsInTopicFilters = true }; Botao1.IsEnabled = false; client = await MqttClient.CreateAsync(BrokerURL, BrokerPort); sessionState = await client.ConnectAsync(new MqttClientCredentials(clientId : MQTTClientID)); if (client.IsConnected) { await DisplayAlert("Conexão", "Estado: Conectado", "Ok"); } Botao1.IsEnabled = false; Botao1.Text = "Conectado"; Xamarin.Forms.Color xfColor = Xamarin.Forms.Color.FromRgb(0, 255, 0); Botao1.BackgroundColor = xfColor; }
public void Connect() { try { var config = new MqttConfiguration { Port = 1883 }; var client = MqttClient.CreateAsync(host, config).Result; var clientId = "XamarinClient"; client.ConnectAsync(new MqttClientCredentials(clientId)).Wait(); client.SubscribeAsync(topic, MqttQualityOfService.AtLeastOnce).Wait(); client.MessageStream.Subscribe(message => { var data = Encoding.UTF8.GetString(message.Payload); Debug.WriteLine($"Message Received; {data}"); var msg = new MqttMessage { Topic = message.Topic, Payload = data }; //MessagingCenter.Send<XamFormsSample.ViewModels.MainPageViewModel>(this, "Hi"); // TODO get nuget fixed.... Messenger.Default.Send <MqttMessage>(msg); }); } catch (Exception e) { Debug.WriteLine("_________________ Begin e _________________"); Debug.WriteLine(e); Debug.WriteLine("_________________ End e _________________"); } }
public Publisher(string broker, int port) { var configuration = new MqttConfiguration { Port = port }; this.client = MqttClient.CreateAsync(broker, configuration).Result; }
private async Task <IMqttClient> CreateClient() { Logger.LogInfo($"Connecting to MQTT broker '{_conf.Host}'"); var mqttConf = new MqttConfiguration(); return(await MqttClient.CreateAsync(_conf.Host, mqttConf)); }
/// <summary> /// Constructor /// </summary> /// <param name="host">The hostname or IP or the mqtt message broker</param> /// <param name="port">The port on the host of the mqtt message broker</param> /// <param name="configuration"></param> public ServiceBus(string host, int port, ServiceBusConfiguration configuration = null) { _configuration = configuration ?? new ServiceBusConfiguration(); var connectionString = host + ":" + port; _bus = MqttClient.CreateAsync(connectionString).Result; }
public MqttTrafficControlService(int camNumber) { // connect to mqtt broker var mqttHost = Environment.GetEnvironmentVariable("MQTT_HOST") ?? "localhost"; _client = MqttClient.CreateAsync(mqttHost, 1883).Result; var sessionState = _client.ConnectAsync( new MqttClientCredentials(clientId: $"camerasim{camNumber}")).Result; }
public async Task ConnectAsync() { _logger.LogInformation($"Connecting to MQTT broker at '{_config.Value.Address}:{_config.Value.Port}'"); _client = await MqttClient.CreateAsync(_config.Value.Address, new MqttConfiguration { Port = _config.Value.Port }); _session = await _client.ConnectAsync(new MqttClientCredentials(clientId : _config.Value.ClientId)); _logger.LogInformation($"Successfully connected to MQTT broker at '{_config.Value.Address}:{_config.Value.Port}'"); }
public async Task Connect() { _mqttClient = await MqttClient.CreateAsync(Address, Port); await _mqttClient.ConnectAsync(); _mqttClient .MessageStream .Subscribe(OnMessageReceived); }
protected async override void OnAppearing() { client = await MqttClient.CreateAsync(host, port); await client.ConnectAsync(); await client.SubscribeAsync(topic, MqttQualityOfService.AtMostOnce); client.MessageStream.Subscribe(ReceivedMessage); }
protected async override void OnStart() { client = await MqttClient.CreateAsync(host, port); await client.ConnectAsync(); await client.SubscribeAsync(App.Current.Properties["prefix"].ToString() + "gamestarted/answer", MqttQualityOfService.AtMostOnce); client.MessageStream.Subscribe(ReceivedMessage); }
private static async Task TestReceiveMqtt() { var configuration = new MqttConfiguration(); var client = await MqttClient.CreateAsync("localhost", configuration); var sessionState = await client.ConnectAsync(new MqttClientCredentials(clientId : "hatest")); await client.SubscribeAsync("house/light", MqttQualityOfService.AtLeastOnce); //QoS0 client.MessageStream.Subscribe(x => Console.WriteLine($"Message {x.Payload} received in topic {x.Topic}")); }
private Task <IMqttClient> CreateClient() { var config = new MqttConfiguration { Port = _options.Port, MaximumQualityOfService = MqttQualityOfService.ExactlyOnce, AllowWildcardsInTopicFilters = true }; return(MqttClient.CreateAsync(_options.Broker, config)); }
protected async override void OnAppearing() { client = await MqttClient.CreateAsync(host, port); var payload = Encoding.UTF8.GetBytes("Dead"); var lastWill = new MqttLastWill(topic, MqttQualityOfService.AtMostOnce, false, payload); await client.ConnectAsync(lastWill); await client.SubscribeAsync(topic, MqttQualityOfService.AtMostOnce); client.MessageStream.Subscribe(ReceivedMessage); }
static async Task Main(string[] args) { State = States.New; string roomId = null; var id = "B2904CCF-4B7D-4457-A26C-6CBCA89EF02E".ToLower(); var configuration = new MqttConfiguration(); var client = await MqttClient.CreateAsync("localhost", configuration); var credentials = new MqttClientCredentials(null, "rabbit", "rabbit"); var sessionState = await client.ConnectAsync(credentials, null, true); await client.SubscribeAsync(id, MqttQualityOfService.AtLeastOnce); client.MessageStream.Subscribe(msg => { if (msg.Topic == id) { if (State == States.WaitingResponse) { var msgObj = JsonConvert.DeserializeObject <Dictionary <string, object> >(Encoding.UTF8.GetString(msg.Payload)); Console.WriteLine("Received newsensor response, we are now registered"); roomId = (string)msgObj["RoomId"]; // Not used yet as we can get the roomId from SensorService based on sensorId State = States.Registered; } } }); while (true) { switch (State) { case States.New: await PublishNewSensorMessage(client, id).ConfigureAwait(false); State = States.WaitingResponse; break; case States.WaitingResponse: break; case States.Registered: await PublishEnvironment(client, id).ConfigureAwait(false); break; default: throw new NotImplementedException("Invalid state"); } await Task.Delay(200).ConfigureAwait(false); } }
public async ValueTask <IMqttClient> Create() { var config = new MqttConfiguration { Port = _config.Value.Port, MaximumQualityOfService = MqttQualityOfService.ExactlyOnce, AllowWildcardsInTopicFilters = true }; var client = await MqttClient.CreateAsync(_config.Value.Broker, config); return(client); }
public async Task <IActionResult> Forward() { var mqttClient = await MqttClient.CreateAsync("sss"); var sess = await mqttClient.ConnectAsync(new MqttClientCredentials("xxx", "xxx", "xxx")); string sendTopic = "movement"; var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject("d")); await mqttClient.PublishAsync(new MqttApplicationMessage(sendTopic, data), MqttQualityOfService.ExactlyOnce); return(Ok()); }
private static async Task TestSendMqtt() { var configuration = new MqttConfiguration(); var client = await MqttClient.CreateAsync("localhost", configuration); var sessionState = await client.ConnectAsync(new MqttClientCredentials(clientId : "hatest")); //await client.SubscribeAsync("house/light", MqttQualityOfService.AtLeastOnce); //QoS0 //client.MessageStream.Subscribe(x => Console.WriteLine($"Message {x.Payload} received in topic {x.Topic}")); var message1 = new MqttApplicationMessage("house/light", Encoding.UTF8.GetBytes("Foo Message 1")); await client.PublishAsync(message1, MqttQualityOfService.AtLeastOnce); }
public async void connectMQTT(object sender, EventArgs e) { var configuration = new MqttConfiguration { BufferSize = 128 * 1024, Port = 1883, KeepAliveSecs = 10, WaitTimeoutSecs = 2, MaximumQualityOfService = MqttQualityOfService.AtMostOnce, AllowWildcardsInTopicFilters = true }; var client = await MqttClient.CreateAsync("iot02.qaingenieros.com", configuration); var sessionState = await client.ConnectAsync(new MqttClientCredentials(clientId : "foo")); }
static async Task Main(string[] args) { var openweathermapAppid = Environment.GetEnvironmentVariable("OPENWEATHERMAP_APPID"); if (openweathermapAppid == null) { openweathermapAppid = await System.IO.File.ReadAllTextAsync("/run/secrets/OPENWEATHERMAP_APPID"); } // TODO: Location could be received from SensorService via Home ID var client = new OpenWeatherMapClient( Environment.GetEnvironmentVariable("WEATHER_LOCATION"), openweathermapAppid ); var response = await client.GetCurrentConditions(); var messageDict = new Dictionary <string, object> { ["homeId"] = Environment.GetEnvironmentVariable("HOME_ID"), ["weather"] = response }; var configuration = new MqttConfiguration(); var rabbitmqHost = Environment.GetEnvironmentVariable("RABBITMQ_HOST"); var mqttClient = await MqttClient.CreateAsync(rabbitmqHost, configuration); const string clientId = "weathersensor"; var username = Environment.GetEnvironmentVariable("RABBITMQ_USERNAME"); var password = Environment.GetEnvironmentVariable("RABBITMQ_PASSWORD"); MqttClientCredentials credentials; if (username == null) { credentials = new MqttClientCredentials(clientId); } else { credentials = new MqttClientCredentials(clientId, username, password); } var sessionState = await mqttClient.ConnectAsync(credentials); var message = new MqttApplicationMessage("weather", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageDict))); await mqttClient.PublishAsync(message, MqttQualityOfService.AtMostOnce); await mqttClient.DisconnectAsync(); }
public async void subscribeAll() { var configuration = new MqttConfiguration { BufferSize = 128 * 1024, Port = 1883, KeepAliveSecs = 10, WaitTimeoutSecs = 2, MaximumQualityOfService = MqttQualityOfService.AtMostOnce, AllowWildcardsInTopicFilters = true }; var client = await MqttClient.CreateAsync("iot02.qaingenieros.com", configuration); await client.SubscribeAsync("SubscribeTest", MqttQualityOfService.AtMostOnce); await client.DisconnectAsync(); }
public async void publish(string clientid) { var r = new Random(Environment.CurrentManagedThreadId + (int)DateTime.Now.Ticks); var cli = await MqttClient.CreateAsync(_config.server).ConfigureAwait(false); await cli.ConnectAsync(new MqttClientCredentials(clientid)).ConfigureAwait(false); string topic = string.Format("clients/{0}", clientid); await cli.PublishAsync(new MqttApplicationMessage(topic, new byte[] { 1 }), MqttQualityOfService.AtLeastOnce) .ConfigureAwait(false); Console.WriteLine("Type 'q' to quit (enter to publish)"); string text = null; do { r.Next(); if ((r.Next(10000) % 2) == 0) { topic = "house/serverroom/temp"; } else { topic = "house/garage/temp"; } float f = (float)(r.NextDouble() * 100.0d); byte[] bytes = new byte[8]; bytes[0] = 2; bytes[1] = 2; { var b1 = BitConverter.GetBytes(f); for (int i = 0; i < b1.Length; ++i) { bytes[2 + i] = b1[i]; } } await cli.PublishAsync(new MqttApplicationMessage(topic, bytes), MqttQualityOfService.AtLeastOnce).ConfigureAwait(false); text = Console.ReadLine(); } while(text != "q"); await cli.DisconnectAsync(); cli.Dispose(); cli = null; }