public async Task FailedConnectionToClient() { MQTTClient client = new MQTTClient(); bool isConnected = await client.Connect(this.IP, this.PORT, this.PASSWORD); Assert.IsTrue(isConnected); }
void WyslijWiadomosc() { var receivedMessage = false; string message = ""; // create the client var client = new MQTTClient("xxx.xxx.xxx.xxx", 10883); // hook up the MessageReceived event with a handler //client.MessageReceived += (topic, qos, payload) => //{ // MessageBox.Show("Odebrano: " + topic); // receivedMessage = true; //}; // connect to the MQTT server message = Guid.NewGuid().ToString(); client.Connect("Klient1234"); // wait for the connection to complete // add a subscription client.Subscriptions.Add(new Subscription("test")); string User = ""; User = client.BrokerHostName; var data = DateTime.Now; client.Publish("test", data + " Wiadomosc: " + message, QoS.AcknowledgeDelivery, false); status.Content = "Wysłano"; if (client.IsConnected) { client.Disconnect(); } }
/// <summary> /// 方法说明:连接MQTT服务 /// 完成时间:2016-04-20 /// </summary> /// <param name="userId">对应MQTT的客户端用户ID</param> /// <param name="mqttConfig">登录时获取到的MQTT连接配置</param> /// <param name="errorMsg">MQTT连接错误提示</param> /// <returns>是否连接成功</returns> public bool Connect(string userId, GetConnectConfigOutput mqttConfig, ref string errorMsg) { this._userId = userId; try { _client = new MQTTClient(mqttConfig.host, int.Parse(mqttConfig.port)); if (_client.Connect(mqttConfig.clientId, mqttConfig.userName, mqttConfig.password)) { _client.MessageReceived += OnMessageReceived; _client.ReconnectedMqtt += OnReconnectedMqtt; _client.Disconnected += OnDisconnectedMqtt; LogHelper.WriteDebug($"{Resources.SdkMqttConnectSuccess}:{mqttConfig.host}:{mqttConfig.port}"); //连接成功就开始跑定时器 _heartbeattimer = new System.Timers.Timer(1000); _heartbeattimer.Elapsed += _heartbeattimer_Elapsed; _heartbeattimer.Start(); return(true); } else { LogHelper.WriteError( $"{Resources.SdkMqttConnectFail}:[{mqttConfig.host}:{mqttConfig.port}] {errorMsg}"); return(false); } } catch (Exception ex) { errorMsg = ex.Message; LogHelper.WriteError( $"{Resources.SdkMqttConnectFail}:[{mqttConfig.host}:{mqttConfig.port}] {ex.Message}"); return(false); } }
private static void Connect() { _ = Task.Run(() => { mqtt.Connect(NombreCliente); }); }
private void DoMqttConnect() { try { if (MQTTClient != null && !MQTTClient.IsConnected) { PrintTime(); Console.WriteLine("Connecting to MQTT server"); Log.Logger.Information("Connecting to MQTT server"); MQTTState = MQTTClient.Connect(CLIENT_IDENTIFIER, Setting.Default.MQTTUser, Setting.Default.MQTTPass, true, Setting.Default.KeepAlive); Console.WriteLine("Connect called "); Console.WriteLine("State: "); Console.Write(MQTTState); Log.Logger.Information("---> Connect called"); } else { PrintTime(); Console.WriteLine("Tried connecting to MQTT server - but was already connected"); Log.Logger.Information("Tried connecting to MQTT server - but was already connected"); } } catch (Exception e) { PrintTime(); Console.WriteLine("Error while connecting. Retrying again in 5 seconds: " + e); Log.Logger.Error("Error while connecting. Retrying again in 5 seconds: " + e); Thread.Sleep(5000); } }
private async void StartMQTT() { bool connected = await mqttClient.Connect(); if (connected) { mqttClient.StartSubscribe(); mqttClient.SubscribeListener += MqttClient_SubscribeListener; } }
public async Task DisconnectFromClient() { MQTTClient client = new MQTTClient(); bool isConnected = await client.Connect(this.IP, this.PORT, this.PASSWORD); Assert.IsTrue(isConnected); isConnected = await client.Disconnect(); Assert.IsFalse(isConnected); }
public async Task SubscribeAndSendMessage() { MQTTClient client = new MQTTClient(); _ = await client.Connect(this.IP, this.PORT, this.PASSWORD); client.Subscribe(this.TESTCHANNEL); client.Publish(this.TESTCHANNEL, "hello world"); Thread.Sleep(100); MQTTMessage message = client.MQTTMessageStore.GetLatestMessageFromTopic(this.TESTCHANNEL); Assert.AreEqual("hello world", message.Message); }
public void ClientReceiveTest() { var receivedMessage = false; var client = new MQTTClient("ec2-18-217-218-110.us-east-2.compute.amazonaws.com", 1883); client.MessageReceived += (topic, qos, payload) => { Debug.WriteLine("RX: " + topic); receivedMessage = true; }; var i = 0; client.Connect("solution-family", "solution-family", "s36158"); while (!client.IsConnected) { Thread.Sleep(1000); if (i++ > 10) { Assert.Fail(); } } Assert.IsTrue(client.IsConnected); client.Subscriptions.Add(new Subscription("solution-family/#")); i = 0; while (true) { if (receivedMessage) { break; } Thread.Sleep(1000); client.Publish("solution-family/Test", "Hello", QoS.FireAndForget, false); if (i++ > 10) { break; } } Assert.IsTrue(receivedMessage); }
static void Main(string[] ass) { //// int count = 0; var ClientId = DateTime.Now.Ticks.ToString(); MQTTClient client = new MQTTClient("my.hnlyf.com"); client.Connect(new MQTTConnectInfo() { UserName = "******", Password = "******", ClientId = ClientId }); // client.Subscribe("iot/log/#"); ; System.Timers.Timer timer = new System.Timers.Timer(1000); timer.Elapsed += (o, e) => { Console.Title = ($"{ClientId}--{ass[0]}:当前每秒:{count}个,总个数:{TotalCount}"); count = 0; }; timer.Start(); while (true) { //Console.WriteLine("请随意输入"); var text = Guid.NewGuid().ToString(); if (string.IsNullOrEmpty(text)) { client.UnSubscribe("iot/log/#");; client.Disconnect(); } PublishDataPackage applicationMessage = new PublishDataPackage() { Topic = $"iot/log/{ass[0]}", Text = text }; if (!client.Publish(applicationMessage)) { Console.WriteLine("断线了?"); Console.ReadLine(); } System.Threading.Interlocked.Increment(ref count); System.Threading.Interlocked.Increment(ref TotalCount); System.Threading.Thread.Sleep(10); } Console.ReadLine(); }
/// <summary> /// MQTT message interpreter. /// </summary> public MQTTHandler(string host, int port, string user, string password) { client = new MQTTClient(host, port); client.MessageReceived += MessageReceived; client.Connect(host, user, password); int i = 0; while (!client.IsConnected) { System.Threading.Thread.Sleep(500); if (i++ > 10) { Alert.SendAlert(null, "MQTT connection failed to " + host + " as " + user + '.'); break; } } client.Subscriptions.Add(new Subscription("#")); }
public Actuadores() { InitializeComponent(); mensajes = new List <string>(); mqtt = new MQTTClient("broker.hivemq.com", 1883); mqtt.MessageReceived += Mqtt_MessageReceived; mqtt.Connect("AppMovilESP8266"); mqtt.Subscriptions.Add(new Subscription("ServerProfeCarlos")); Device.StartTimer(TimeSpan.FromSeconds(1), () => { if (mensajes.Count > m) { lstMensajes.ItemsSource = null; lstMensajes.ItemsSource = mensajes; m = mensajes.Count; } return(true); }); }
private static void DoMqttConnect() { try { if (MQTTClient != null && !MQTTClient.IsConnected) { Console.WriteLine("Connecting to MQTT server"); var state = MQTTClient.Connect(CLIENT_IDENTIFIER, Setting.Default.MQTTUser, Setting.Default.MQTTPass, true, Setting.Default.KeepAlive); Console.WriteLine("Connect called "); } else { Console.WriteLine("Tried connecting to MQTT server - but was already connected"); } } catch (Exception e) { } }
public async Task MQTTPublish(string deviceId, object attribs, string user) { var topic = $"/{ user }/{deviceId}/attrs"; var content = JsonConvert.SerializeObject(attribs); client.Connect(GenerateRandomKey()); var i = 0; while (!client.IsConnected) { await Task.Delay(1000); if (i++ > timeout) { throw new TimeoutException(); } } client.Publish(topic, content, QoS.FireAndForget, false); }
// Use this to connect up to the given MQTT broker public bool Connect(string brokerAddress, int port, string clientID, int amountOfRetries) { //attachedApplication.output.PrintLine("Connecting to " + brokerAddress + ":" + port + "..."); // Create a new MQTT client client = new MQTTClient(brokerAddress, port); // Register to message received client.MessageReceived += OnMessageRecievedLocal; // Connect up the client client.Connect(clientID); // Wait for the connection to complete while (!client.IsConnected) { Thread.Sleep(100); if (amountOfRetries <= 0) { attachedApplication.output.PrintLine("$maFailed $mato $maconnect... $ma:("); return(false); } amountOfRetries--; } return(true); }
/// <summary> /// 连接MQTT服务 /// </summary> /// <param name="token">对应MQTT的客户端ID</param> /// <returns></returns> public bool Connect(ref string errMsg) { try { Client = new MQTTClient(GlobalVariable.ConfigEntity.MQTT_Host, int.Parse(GlobalVariable.ConfigEntity.MQTT_Port)); if (Client.Connect(GlobalVariable.LoginOutput.userId + "/" + (int)GlobalVariable.OSType.PC, GlobalVariable.ConfigEntity.MQTT_UserName, GlobalVariable.ConfigEntity.MQTT_Password)) { #region 发心跳消息 //Heartbeat heartbeat = new Heartbeat(); //heartbeat.ctt.token = token; //pingTimer = new Timer((state) => //{ // Publish<Heartbeat>("heartbeat", heartbeat); // //Client.Publish("heartbeat", byteArray, Qos.AtLeastOnce); //}, null, 0, KeepAlive * 1000); #endregion Client.MessageReceived += OnMessageReceived; Client.ReconnectedMqtt += OnReconnectedMqtt; LogHelper.WriteDebug("MQTT连接成功:" + GlobalVariable.ConfigEntity.MQTT_Host + ":" + int.Parse(GlobalVariable.ConfigEntity.MQTT_Port)); return(true); } else { errMsg = "消息服务器连接异常"; LogHelper.WriteDebug(string.Format("MQTT连接失败:[{0}:{1}] {2}", GlobalVariable.ConfigEntity.MQTT_Host, GlobalVariable.ConfigEntity.MQTT_Port, errMsg)); return(false); } } catch (Exception ex) { errMsg = "消息服务器连接异常"; LogHelper.WriteDebug(string.Format("MQTT连接失败:[{0}:{1}] {2}", GlobalVariable.ConfigEntity.MQTT_Host, GlobalVariable.ConfigEntity.MQTT_Port, errMsg)); return(false); } }
private void OnGUI() { scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, GUILayout.Height(position.height), GUILayout.Width(position.width)); #region Logging. EditorGUILayout.BeginVertical(LayoutSettings.mainBox.style); Logger = new SerializedObject(FindObjectOfType <LoggerObject>().settings); outputPath = Logger.FindProperty("outputPath"); outputFile = Logger.FindProperty("outputFile"); EditorGUILayout.LabelField("Logging", LayoutSettings.sectionLabel); if (EditorApplication.isPlaying) { GUI.enabled = false; } // file/ EditorGUILayout.PropertyField(outputFile, new GUIContent("Session Name: "), false, GUILayout.Width(300)); EditorGUILayout.PropertyField(Logger.FindProperty("sessionId"), new GUIContent("Session Id: "), false, GUILayout.Width(300)); Logger.ApplyModifiedProperties(); EditorGUILayout.EndVertical(); #endregion #region MQTT // MQTT Settings. if (EditorApplication.isPlaying) { GUI.enabled = false; // disable on play. } EditorGUILayout.BeginVertical(LayoutSettings.mainBox.style); EditorGUILayout.LabelField("MQTT", LayoutSettings.sectionLabel); _client.ip = EditorGUILayout.TextField("ip: ", _client.ip, GUILayout.Width(300)); _client.port = int.Parse(EditorGUILayout.TextField("port: ", _client.port.ToString(), GUILayout.Width(300))); if (GUI.changed) { EditorPrefs.SetString("JaneliaVR_MQTT_IP", _client.ip); EditorPrefs.SetInt("JaneliaVR_MQTT_Port", _client.port); } if (GUILayout.Button("Test Connection")) { _client.Connect(true); _client.Disconnect(); } //Messaging settings. msgSettings.isFold = EditorGUILayout.Foldout(msgSettings.isFold, "Messaging"); if (msgSettings.isFold) { EditorGUILayout.BeginVertical(LayoutSettings.subBox.style); bool newSendFrame = EditorGUILayout.Toggle("Send Frame Messages", msgSettings.sendFrameMsg, LayoutSettings.editFieldOp); if (newSendFrame != msgSettings.sendFrameMsg) { msgSettings.sendFrameMsg = newSendFrame; EditorPrefs.SetBool("Gimbl_sendFrameMsg", newSendFrame); } EditorGUILayout.EndVertical(); } //Session settings. sessionSettings.isFold = EditorGUILayout.Foldout(sessionSettings.isFold, "External Control"); if (sessionSettings.isFold) { EditorGUILayout.BeginVertical(LayoutSettings.subBox.style); bool newExternalStart = EditorGUILayout.Toggle("External Start Trigger", sessionSettings.externalStart, LayoutSettings.editFieldOp); if (newExternalStart != sessionSettings.externalStart) { sessionSettings.externalStart = newExternalStart; EditorPrefs.SetBool("Gimbl_externalStart", newExternalStart); } bool newExternalLog = EditorGUILayout.Toggle("External Log Naming", sessionSettings.externalLog, LayoutSettings.editFieldOp); if (newExternalLog != sessionSettings.externalLog) { sessionSettings.externalLog = newExternalLog; EditorPrefs.SetBool("Gimbl_externalLog", newExternalLog); } EditorGUILayout.EndVertical(); } GUI.enabled = true; EditorGUILayout.EndVertical(); #endregion EditorGUILayout.BeginVertical(LayoutSettings.mainBox.style); EditorGUILayout.LabelField("General", LayoutSettings.sectionLabel); #region Teleport. foldBlink = EditorGUILayout.Foldout(foldBlink, "Teleport"); if (foldBlink) { EditorGUILayout.BeginVertical(LayoutSettings.subBox.style); EditorGUILayout.BeginHorizontal(LayoutSettings.editFieldOp); int newDuration = EditorGUILayout.IntField("Dark Duration: ", PlayerPrefs.GetInt("Gimbl_BlinkDuration", 2000)); EditorGUILayout.LabelField("(ms)", GUILayout.Width(50)); if (newDuration != duration) { PlayerPrefs.SetInt("Gimbl_BlinkDuration", newDuration); duration = newDuration; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(LayoutSettings.editFieldOp); int newFadeTime = EditorGUILayout.IntField("Fade Time: ", PlayerPrefs.GetInt("Gimbl_BlinkFadeTime", 3000)); EditorGUILayout.LabelField("(ms)", GUILayout.Width(50)); if (newFadeTime != fadeTime) { PlayerPrefs.SetInt("Gimbl_BlinkFadeTime", newFadeTime); fadeTime = newFadeTime; } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } #endregion EditorGUILayout.EndVertical(); #region Export/Import. EditorGUILayout.BeginVertical(LayoutSettings.mainBox.style); EditorGUILayout.LabelField("Setup", LayoutSettings.sectionLabel); if (GUILayout.Button("Export Setup")) { ExportSetup(); } if (GUILayout.Button("Import Setup")) { ImportSetup(); } EditorGUILayout.EndVertical(); #endregion EditorGUILayout.EndScrollView(); }