Program(string appkey) { Console.WriteLine("Initialize the client with the appkey: " + appkey + "\n"); try { // Instantiate client using MqttClientFactory with appkey _client = MqttClientFactory.CreateClientWithAppkey(appkey); } catch (Exception) { Console.WriteLine("Instantiate the client failed. Please check your network and app key, then try it again."); Environment.Exit(0); } // Enable auto reconnect _client.AutoReconnect = true; // Setup some useful client delegate callbacks _client.Connected += new ConnectionDelegate(client_Connected); _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); _client.Published += new CompleteDelegate(_client_Published); _client.Subscribed += new CompleteDelegate(_client_Subscribed); _client.Unsubscribed += new CompleteDelegate(_client_Unsubscribed); }
void Run() { ColetorTopicoLog ctlm = new ColetorTopicoLog(); ctlm.Id_ColetorTopico = 1; ctlm.DataHora = getData(); ctlm.Valor = "RunInicio"; db.ColetorTopicoLog.Add(ctlm); db.SaveChanges(); /* * client.username_pw_set("","ESQXpO-H7-1y") * client.connect("m14.cloudmqtt.com", 11718, 60) * */ // string connectionString = "mqtt://m13.cloudmqtt.com:12644"; string connectionString = "tcp://m14.cloudmqtt.com:11718"; // Instantiate client using MqttClientFactory //_client = MqttClientFactory.CreateClient(connectionString, "aneuk", "clpfcosb", "ILo_4ucaK3P_"); _client = MqttClientFactory.CreateClient(connectionString, "aneuk", "fgwuwgpw", "ESQXpO-H7-1y"); // Setup some useful client delegate callbacks _client.Connected += new ConnectionDelegate(client_Connected); _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); // ColetorTopicoLog ctlm2 = new ColetorTopicoLog(); ctlm2.Id_ColetorTopico = 1; ctlm2.DataHora = getData(); ctlm2.Valor = "RunFim"; db.ColetorTopicoLog.Add(ctlm2); db.SaveChanges(); Start(); }
static void ConnectionServer() { var options = new MqttClientTcpOptions { // Port = 61613, Server = "127.0.0.1", ClientId = "c001", UserName = "******", Password = "******", CleanSession = true }; var mqttClient = new MqttClientFactory().CreateMqttClient(); mqttClient.ConnectAsync(options); mqttClient.SubscribeAsync(new List <TopicFilter> { new TopicFilter("家/客厅/空调/#", MqttQualityOfServiceLevel.AtMostOnce) }); var appMsg = new MqttApplicationMessage("家/客厅/空调/开关", Encoding.UTF8.GetBytes("消息内容"), MqttQualityOfServiceLevel.AtMostOnce, false); mqttClient.PublishAsync(appMsg); }
public bool Connect(string connString, string clientId, ushort keepAlive, string username = null, string password = null, IPersistence persistence = null) { try { mqtt = MqttClientFactory.CreateClient(connString, clientId, username, password, persistence); mqtt.KeepAliveInterval = keepAlive; if (withWill) { mqtt.Connect(willTopic, willQos, new MqttPayload(willMessage), willRetained, cleanSession); } else { mqtt.Connect(cleanSession); } mqtt.Connected += Mqtt_Connected; mqtt.PublishArrived += Mqtt_PublishArrived; mqtt.Published += Mqtt_Published; mqtt.Subscribed += Mqtt_Subscribed; mqtt.Unsubscribed += Mqtt_Unsubscribed; mqtt.ConnectionLost += Mqtt_ConnectionLost; return(true); } catch (Exception m_ex) { return(false); } }
private async void Connect(object sender, RoutedEventArgs e) { var options = new MqttClientOptions { Server = Server.Text, UserName = User.Text, Password = Password.Text, ClientId = ClientId.Text }; options.TlsOptions.UseTls = UseTls.IsChecked == true; try { if (_mqttClient != null) { await _mqttClient.DisconnectAsync(); } var factory = new MqttClientFactory(); _mqttClient = factory.CreateMqttClient(options); await _mqttClient.ConnectAsync(); } catch (Exception exception) { Trace.Text += exception + Environment.NewLine; } }
private void MQTT_TEST(string connectionString, string clientId, string username, string password) { _client = MqttClientFactory.CreateClient(connectionString, clientId, username, password); _client.Connected += new ConnectionDelegate(client_Connected); _client.ConnectionLost += new ConnectionDelegate(client_ConnectionLost); _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); _client.PublishArrived += _client_PublishArrived; }
public MQTTManager(string connectionString, string clientId, string userName, string password) { this._connectionString = connectionString; this._clientId = clientId; this._client = MqttClientFactory.CreateClient(connectionString, _clientId, userName, password); this._client.Connected += new ConnectionDelegate(client_Connected); this._client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); this._client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); }
// Program() { string connectionString = "tcp://m16.cloudmqtt.com:14106"; _client = MqttClientFactory.CreateClient(connectionString, "useracl", "username", "password"); _client.Connected += new ConnectionDelegate(client_Connected); _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); }
private void ConnectToBroker() { if (Servers.SelectedIndex < 0) { ShowSettingsPage(); return; } if (_clientConnected) { return; } Settings settings = Settings.LoadSettings(Servers.Items[Servers.SelectedIndex]); if (!settings.EnableControls) { return; } IWifi wifi = new Wifi(); string server = wifi.GetSSID() == $"\"{settings.LocalSSID}\"" ? settings.LocalServerName : settings.RemoteServerName; string connectionString = $"tcp://{server}:{settings.MqttPort}"; Device.BeginInvokeOnMainThread(() => { if (!string.IsNullOrEmpty(settings.Username)) { client = MqttClientFactory.CreateClient(connectionString, Guid.NewGuid().ToString(), settings.Username, settings.Password); } else { client = MqttClientFactory.CreateClient(connectionString, Guid.NewGuid().ToString()); } client.Connected += ClientConnected; client.ConnectionLost += ClientConnectionLost; client.PublishArrived += ClientPublishArrived; IDeviceInfo device = new DeviceInfo(); string name = device.GetName(); try { client.Connect("car/DISCONNECT", QoS.BestEfforts, new MqttPayload(name), false, true); } catch (Exception ex) { Toaster(ex.Message, ToastPriority.Critical, ToastLength.Long); _clientConnected = false; } }); }
Program(string connectionString, string clientId) { // Instantiate client using MqttClientFactory _client = MqttClientFactory.CreateClient(connectionString, clientId); // Setup some useful client delegate callbacks _client.Connected += new ConnectionDelegate(client_Connected); _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); }
void ProgramSetup(string connectionString, string clientId, string username, string password) { // Instantiate client using MqttClientFactor _client = MqttClientFactory.CreateClient(connectionString, clientId, username, password); // Setup some useful client delegate callbacks _client.Connected += new ConnectionDelegate(client_Connected); _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); //textBoxIncomming.Text = e.Payload; }
private void OpenMqtt() { client = MqttClientFactory.CreateClient(connectionString, clientId); client.Connect(true); client.Connected += new ConnectionDelegate(client_Connected); client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); client.Published += new CompleteDelegate(_client_Published); }
Program(string clientId) { var connectionString = "tcp://fantastic-teacher.cloudmqtt.com:1883"; _client = MqttClientFactory.CreateClient(connectionString, clientId, "gnztvlsa", "CZbmTTBjvd8f"); // Setup some useful client delegate callbacks _client.Connected += client_Connected; _client.ConnectionLost += _client_ConnectionLost; _client.PublishArrived += client_PublishArrived; }
protected virtual async Task <IMqttClient> GetClientAsync() { var binding = new TcpBinding(); var initializer = new MqttClientFactory(IPAddress.Loopback.ToString(), binding); if (Configuration == null) { LoadConfiguration(); } return(await initializer.CreateClientAsync(Configuration)); }
/// <summary> /// Execute start up tasks /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void MainWindow_Loaded(object sender, RoutedEventArgs e) { m_client = MqttClientFactory.CreateClient("tcp://192.168.0.50:1883", "MQTTKinect"); m_client.Connect(cleanStart: true); m_client.Publish("text", "Kinect 2.0 just loaded!", QoS.BestEfforts, false); timer = System.DateTimeOffset.Now.AddSeconds(0.1f); if (this.bodyFrameReader != null) { this.bodyFrameReader.FrameArrived += this.Reader_FrameArrived; } }
public Form1() { InitializeComponent(); _client = MqttClientFactory.CreateClient("tcp://postman.cloudmqtt.com:17127", "comp1", "laivxdgr", "RQJhNBmGjTN4"); _client.Connected += new ConnectionDelegate(client_Connected); _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); _client.PublishArrived += new PublishArrivedDelegate(Client_PublishArrived); // Setup some useful client delegate callbacks Start(); }
public void ListenerCredentialsFailsTest() { var context = new MockContext(); context.Settings.Add("MqttBroker", MosquittoServer); var client = new MqttClientFactory(context).Create(); var messageHandler = new MockMessageHandler(context); var credential = new NetworkCredential("user", "password"); var listener = new Listener(client, credential, messageHandler, context); Assert.IsFalse(listener.Listen(), "Listen fails"); messageHandler.Dispose(); }
public void ListenerServerFailsTest() { var context = new MockContext(); context.Settings.Add("MqttBroker", "bogus"); // this is the slow step. var client = new MqttClientFactory(context).Create(); var messageHandler = new MockMessageHandler(context); var listener = new Listener(client, null, messageHandler, context); Assert.IsFalse(listener.Listen(), "Listen fails"); messageHandler.Dispose(); }
public void Mqtt1() { var rnd = new Random(); var client1 = MqttClientFactory.CreateConnectedClient(); var client2 = MqttClientFactory.CreateConnectedClient(); var lck = new object(); string mqttMsg = null; var topic = "opentrigger/tests/D59979C42762488F8B570A1F16BE3AB6/" + DateTime.Now.Ticks; var msg = "asdf-" + DateTime.Now.Ticks; client1.MqttMsgSubscribed += (sender, args) => { Debug.WriteLine($"subscribed {args.MessageId}"); }; client1.Subscribe(topic); client1.Subscribe(topic + "/ll"); client1.MqttMsgPublishReceived += (sender, args) => { var inMsg = Encoding.UTF8.GetString(args.Message); var dbgMsg = $"msg '{inMsg}' from '{args.Topic}'"; Debug.WriteLine(dbgMsg); lock (lck) { mqttMsg = inMsg; } }; client2.Publish(topic, Encoding.UTF8.GetBytes(msg)); var sw = new Stopwatch(); sw.Start(); while (true) { lock (lck) { if (mqttMsg == msg || sw.ElapsedMilliseconds > 5000) { break; } } System.Threading.Thread.Sleep(500); } client1.Disconnect(); client2.Disconnect(); Assert.AreEqual(msg, mqttMsg); }
private MqttClient GetMqttClient() { if (_channels == null) { var prefix = AppSettings.Get("MqttPrefix").TrimEnd('/'); var websocket = AppSettings.Get("MqttWebsocket"); _channels = new Channels { Prefix = prefix, Websocket = websocket, ScreenN = $"{prefix}/N", ScreenS = $"{prefix}/S", ScreenW = $"{prefix}/W", ScreenO = $"{prefix}/O", Vote = $"{prefix}/Vote", Debug = $"{prefix}/Debug", Command = $"{prefix}/Command", OpenTriggerRelease = AppSettings.Get <string>("OpenTriggerTopic", null), }; } if (_mqttClient == null || _mqttClient.IsConnected == false) { _mqttClient = MqttClientFactory.CreateConnectedClient(); _mqttClient.MqttMsgSubscribed += (sender, args) => { var client = (MqttClient)sender; var msg = new { @event = "MqttMsgSubscribed", client.ClientId, args.MessageId, args.GrantedQoSLevels, }; PublishMessage(_channels.Debug, msg); }; _mqttClient.Subscribe(_channels.Vote); if (!string.IsNullOrWhiteSpace(_channels.OpenTriggerRelease)) { _mqttClient.Subscribe(_channels.OpenTriggerRelease); } _mqttClient.MqttMsgPublishReceived += (sender, args) => { var msg = JToken.Parse(_encoding.GetString(args.Message)); MessageReceived(args.Topic, msg, args.QosLevel, args.Retain, args.DupFlag); }; } return(_mqttClient); }
public void Connect(string clientId) { // Instantiate client using MqttClientFactory this._clientId = clientId; this._client = MqttClientFactory.CreateClient(this._connectionString, this._clientId, this._authMode, this._authToken); // Setup some useful client delegate callbacks this._client.Connected += new ConnectionDelegate(client_Connected); this._client.ConnectionLost += new ConnectionDelegate(client_ConnectionLost); this._client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); //instantiating the connection _client.Connect(true); }
// Use this for initialization protected void Start() { Debug.Log("Starting"); // Instantiate client using MqttClientFactory _client = MqttClientFactory.CreateClient(ConnectionString, ClientId, UserName, Password); Debug.Log(_client); // Setup some useful client delegate callbacks _client.Connected += new ConnectionDelegate(client_Connected); _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); Debug.Log("Connecting......"); _client.Connect(); }
void init() { // User Settings XmlDocument xmlConfig = new XmlDocument(); xmlConfig.Load(AppDomain.CurrentDomain.BaseDirectory + "config.xml"); var mqttConfig = xmlConfig["RazerChromaMqtt"]["MQTT"]; var v = mqttConfig["MqttUser"].InnerText.Trim(); mqttHost = mqttConfig["MqttHost"].InnerText.Trim(); mqttPort = mqttConfig["MqttPort"].InnerText.Trim(); mqttUser = mqttConfig["MqttUser"].InnerText.Trim(); mqttPw = mqttConfig["MqttPw"].InnerText.Trim(); mqttPreTopic = mqttConfig["MqttPreTopic"].InnerText.Trim(); if (mqttUser == "" || mqttPw == "") { mqttUser = mqttPw = null; } // MQTT mqttClient = MqttClientFactory.CreateClient($"tcp://{mqttHost}:{mqttPort}", "chroma", mqttUser, mqttPw); mqttClient.Connected += MqttC_Connected; mqttClient.ConnectionLost += MqttC_ConnectionLost; mqttClient.PublishArrived += MqttC_PublishArrived; MqttAppender.mqttClient = mqttClient; MqttAppender.mqttPreTopic = mqttPreTopic; try { mqttClient.Connect(mqttPreTopic + "state", QoS.BestEfforts, new MqttPayload("offline"), false); } catch (Exception e) { log.Error("Mqtt connect eror : " + e.Message); base.Stop(); } Task <IChroma> connectChroma = ColoreProvider.CreateNativeAsync(); connectChroma.Wait(); chroma = connectChroma.Result; }
public static async Task Main(string[] args) { // Read the configuration file IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located .AddJsonFile(APPSETTINGS_FILENAME, optional: false, reloadOnChange: true) .Build(); // Create an HttpClient that doesn't validate the server certificate HttpClientHandler customHttpClientHandler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); } }; TelemetryConfiguration telemetryConfig = AppInsights.GetTelemetryConfiguration(configuration); using (AppInsights.InitializeDependencyTracking(telemetryConfig)) using (AppInsights.InitializePerformanceTracking(telemetryConfig)) using (HttpClient _httpClient = new HttpClient(customHttpClientHandler)) { _telemetryClient = new TelemetryClient(telemetryConfig); // Abstraction representing the home automation system _hub = new Hubitat(configuration, _httpClient); // Start the MQTT service, if applicable. MqttOptions mqttOptions = configuration.GetSection("MQTT").Get <MqttOptions>(); if (mqttOptions?.Enabled ?? false) { _mqtt = new MqttService(await MqttClientFactory.GetClient(mqttOptions), mqttOptions, _hub); await _mqtt.Start(); } // Class to manage long-running tasks _taskManager = new AutomationTaskManager(configuration); // Bind a method to handle the events raised // by the Hubitat device _hub.AutomationEvent += Hub_AutomationEvent; var hubTask = _hub.StartAutomationEventWatcher(); // Wait forever, this is a daemon process await hubTask; } }
public async Task when_initializing_client_then_succeeds() { var port = new Random().Next(IPEndPoint.MinPort, IPEndPoint.MaxPort); var listener = new TcpListener(IPAddress.Loopback, port); listener.Start(); var configuration = new MqttConfiguration { BufferSize = 131072, Port = port }; var binding = new TcpBinding(); var initializer = new MqttClientFactory(IPAddress.Loopback.ToString(), binding); var client = await initializer.CreateClientAsync(configuration); Assert.NotNull(client); listener.Stop(); }
void MQTTProgram(string connectionString, string clientId) { if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(clientId)) { return; } // Instantiate client using MqttClientFactory _client = MqttClientFactory.CreateClient(connectionString, clientId); // Setup some useful client delegate callbacks _client.Connected += new ConnectionDelegate(client_Connected); _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost); _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived); Start(); //Stop(); }
void InitHandle() { try { handle = MqttClientFactory.CreateClient(connStr, clientId, user, pass); Log.Info("MqttAdaptor handle constructed"); } catch (Exception e) { Log.Error("MqttAdaptor InitHandle construct throw exp:{0}", e); throw; } handle.Connected = OnConnected; handle.ConnectionLost = OnDisconnected; handle.PublishArrived = OnReceived; Log.Info("MqttAdaptor InitHandle"); }
//Awake function connects to the mqtt broker and sets a function to be called whenever a publish arrives //NOTE: a factory class may be used to allow connections to any mqtt broker not just a hard coded one void Awake() { m_client = MqttClientFactory.CreateClient("tcp://" + IPAddress + ":" + Port, "UnityProxy"); m_client.Connect(true); m_client.PublishArrived += new PublishArrivedDelegate(MessageRecieved); }
private static async Task RunClientAsync(string[] arguments) { MqttTrace.TraceMessagePublished += (s, e) => { Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}"); if (e.Exception != null) { Console.WriteLine(e.Exception); } }; try { var options = new MqttClientOptions { Server = "localhost", ClientId = "XYZ", CleanSession = true }; var client = new MqttClientFactory().CreateMqttClient(options); client.ApplicationMessageReceived += (s, e) => { Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}"); Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}"); Console.WriteLine(); }; client.Connected += async(s, e) => { Console.WriteLine("### CONNECTED WITH SERVER ###"); await client.SubscribeAsync(new List <TopicFilter> { new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce) }); }; client.Disconnected += async(s, e) => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await client.ConnectAsync(); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }; try { await client.ConnectAsync(); } catch (Exception exception) { Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception); } Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###"); var messageFactory = new MqttApplicationMessageFactory(); while (true) { Console.ReadLine(); var applicationMessage = messageFactory.CreateApplicationMessage("myTopic", "Hello World", MqttQualityOfServiceLevel.AtLeastOnce); await client.PublishAsync(applicationMessage); } } catch (Exception exception) { Console.WriteLine(exception); } }
private static async Task RunClientAsync(int msgChunkSize, TimeSpan interval) { try { var options = new MqttClientOptions { Server = "localhost", ClientId = "XYZ", CleanSession = true, DefaultCommunicationTimeout = TimeSpan.FromMinutes(10) }; var client = new MqttClientFactory().CreateMqttClient(options); client.ApplicationMessageReceived += (s, e) => { }; client.Connected += async(s, e) => { Console.WriteLine("### CONNECTED WITH SERVER ###"); await client.SubscribeAsync(new List <TopicFilter> { new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce) }); Console.WriteLine("### SUBSCRIBED ###"); }; client.Disconnected += async(s, e) => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await client.ConnectAsync(); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }; try { await client.ConnectAsync(); } catch (Exception exception) { Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception); } Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###"); var testMessageCount = 10000; var message = CreateMessage(); var stopwatch = Stopwatch.StartNew(); for (var i = 0; i < testMessageCount; i++) { await client.PublishAsync(message); } stopwatch.Stop(); Console.WriteLine($"Sent 10.000 messages within {stopwatch.ElapsedMilliseconds} ms ({stopwatch.ElapsedMilliseconds / (float)testMessageCount} ms / message)."); stopwatch.Restart(); var sentMessagesCount = 0; while (stopwatch.ElapsedMilliseconds < 1000) { await client.PublishAsync(message); sentMessagesCount++; } Console.WriteLine($"Sending {sentMessagesCount} messages per second."); var last = DateTime.Now; var msgCount = 0; while (true) { var msgs = Enumerable.Range(0, msgChunkSize) .Select(i => CreateMessage()) .ToList(); ////if (false) ////{ //// //send concurrent (test for raceconditions) //// var sendTasks = msgs //// .Select(msg => PublishSingleMessage(client, msg, ref msgCount)) //// .ToList(); //// await Task.WhenAll(sendTasks); ////} ////else { await client.PublishAsync(msgs); msgCount += msgs.Count; //send multiple } var now = DateTime.Now; if (last < now - TimeSpan.FromSeconds(1)) { Console.WriteLine($"sending {msgCount} inteded {msgChunkSize / interval.TotalSeconds}"); msgCount = 0; last = now; } await Task.Delay(interval).ConfigureAwait(false); } } catch (Exception exception) { Console.WriteLine(exception); } }