public void start() { this.shouldStop = false; if (mqttBrokerAddress == null) { throw new ArgumentOutOfRangeException("Mqtt Broker Address not initialized"); } mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None); string clientID = new Guid().ToString(); try { if (MqttUserName == null || MqttPassword == null) { mqttClient.Connect(clientID); } else { mqttClient.Connect(clientID, MqttUserName, MqttPassword); } if (!modbusClient.Connected) { modbusClient.Connect(); } } catch (Exception exc) { if (!this.AutomaticReconnect) { throw exc; } } for (int i = 0; i < readOrders.Count; i++) { readOrders[i].thread = new System.Threading.Thread(new ParameterizedThreadStart(ProcessData)); readOrders[i].thread.Start(readOrders[i]); } }
// ========= PUBLIC MEMBERS ==================================================================================== /// <summary> /// Setup the client with the specified host and port. /// </summary> /// <param name="host">Host.</param> /// <param name="port">Port.</param> public void Setup(string host, int port) { if (!_IsSetup) { _clientId = Guid.NewGuid().ToString(); _brokerEndPoint = new IPEndPoint(IPAddress.Parse(host), port); _client = new MQClient(host); _client.MqttMsgPublishReceived += OnMessageHandler; _client.MqttMsgSubscribed += OnTopicSubscribeHandler; _client.MqttMsgUnsubscribed += OnTopicUnsubscribeHandler; _subscribedTopics = new List <string>(int.Parse(Settings.MaxTopics)); _subscribedTopicsMapping = new Dictionary <int, string>(int.Parse(Settings.MaxTopics)); _disposedValue = false; _IsSetup = true; _connectionThread = new Thread(ConnectionService) { IsBackground = true, Name = "ConnectionService" }; _connectionThread.Start(); Console.WriteLine("Setup Client {0}", _clientId); } }
protected void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { try { _client.Disconnect(); } catch (System.Net.Sockets.SocketException) { Console.Error.WriteLine("Client not disconnected properly"); } finally { _IsSetup = false; _client = null; _brokerEndPoint = null; } } _disposedValue = true; } }
public void publish(string[] topic, string[] payload, string mqttBrokerAddress) { if (mqttClient != null) { if (!mqttBrokerAddress.Equals(this.MqttBrokerAddressPublish) & mqttClient.IsConnected) { mqttClient.Disconnect(); } } if (topic.Length != payload.Length) { throw new ArgumentOutOfRangeException("Array topic and payload must be the same size"); } mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress); string clientID = Guid.NewGuid().ToString(); if (!mqttClient.IsConnected) { mqttClient.Connect(clientID); } for (int i = 0; i < payload.Length; i++) { mqttClient.Publish(topic[i], Encoding.UTF8.GetBytes(payload[i]), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); } }
public void publish(string topic, string payload, string mqttBrokerAddress) { if (mqttClient != null) { if (!mqttBrokerAddress.Equals(this.MqttBrokerAddressPublish) & mqttClient.IsConnected) { mqttClient.Disconnect(); } } mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None); string clientID = Guid.NewGuid().ToString(); if (!mqttClient.IsConnected) { if (MqttUserName == null || MqttPassword == null) { mqttClient.Connect(clientID); } else { mqttClient.Connect(clientID, MqttUserName, MqttPassword); } } if (payload != null) { mqttClient.Publish(topic, Encoding.UTF8.GetBytes(payload), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, RetainMessages); } else { mqttClient.Publish(topic, null, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, RetainMessages); } }
private static async Task <int> _publish() { Console.WriteLine("Type 'q' to quit"); var client = new uPLibrary.Networking.M2Mqtt.MqttClient("grissom.klingon"); client.Connect(Guid.NewGuid().ToString()); Random r = new Random((int)(DateTime.Now.Ticks + (long)Environment.CurrentManagedThreadId)); string text = null; do { text = Console.ReadLine(); if (text != "q") { double d = r.NextDouble() * 100.00; var bytes = System.Text.Encoding.UTF8.GetBytes(string.Format("{{ \"temp\":{0} }}", d)); client.Publish("house/serverroom/temp", bytes); Console.WriteLine(1); } } while(text != "q"); client.Disconnect(); return(1); }
private static void _subscribe(MqttConfig cfg) { //System.Threading.Timer tmr; //"192.168.9.21" var client = new uPLibrary.Networking.M2Mqtt.MqttClient(cfg.server); client.ProtocolVersion = uPLibrary.Networking.M2Mqtt.MqttProtocolVersion.Version_3_1_1; client.MqttMsgSubscribed += Client_MqttMsgSubscribed; client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived; client.MqttMsgPublished += Client_MqttMsgPublished; if (!string.IsNullOrWhiteSpace(cfg.username)) { client.Connect(Guid.NewGuid().ToString(), cfg.username, cfg.password); } else { client.Connect(Guid.NewGuid().ToString()); } var channels = new List <string>(); var qoss = new List <byte>(); { foreach (var s in cfg.subscriptions) { channels.Add(s.channel); qoss.Add(s.qos); } } /*client.Subscribe(new string[] {"house/serverroom/temp"}, new byte[] { 0});*/ client.Subscribe(channels.ToArray(), qoss.ToArray()); Console.WriteLine("Type 'q' to quit"); string text = null; do { text = Console.ReadLine(); } while(text != "q"); client.Disconnect(); }
public MqttClient(IConfiguration configuration, ILoggerFactory loggerFactory) { this.configuration = configuration; logger = loggerFactory.CreateLogger(GetType()); hostName = configuration["mqtt:hostname"]; baseTopic = configuration["mqtt:topic"]; if (string.IsNullOrWhiteSpace(hostName)) { throw new InvalidOperationException("Missing 'hostname' in config file"); } if (string.IsNullOrWhiteSpace(baseTopic)) { throw new InvalidOperationException("Missing 'topic' in config file"); } mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(configuration["mqtt:hostname"]); }
public void start() { this.shouldStop = false; if (mqttBrokerAddress == null) { throw new ArgumentOutOfRangeException("Mqtt Broker Address not initialized"); } if (!modbusClient.Connected) { modbusClient.Connect(); } mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress); string clientID = new Guid().ToString(); mqttClient.Connect(clientID); for (int i = 0; i < readOrders.Count; i++) { readOrders[i].thread = new System.Threading.Thread(new ParameterizedThreadStart(ProcessData)); readOrders[i].thread.Start(readOrders[i]); } }
public MqttClient(Connect.Conference.Core.Models.Conferences.Conference conference) { Conference = conference; if (!string.IsNullOrEmpty(conference.MqttBroker)) { var filename = string.Format("{0}\\Portals\\_default\\Logs\\Connect.Conference.{1}.{2:yyyy-MM-dd}", DotNetNuke.Common.Globals.ApplicationMapPath, Conference.ConferenceId, System.DateTime.Now); var i = 0; while (true) { try { if (Logger == null) { Logger = new StreamWriter(string.Format("{0}-{1}.resources", filename, i), true, Encoding.UTF8); } break; } catch (System.Exception) { } i++; } string clientId = string.Format("Connect.Conference.{0}.{1}", DotNetNuke.Entities.Host.Host.GUID, conference.ConferenceId); Client = new uPLibrary.Networking.M2Mqtt.MqttClient(conference.MqttBroker); Client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; if (string.IsNullOrEmpty(conference.MqttBrokerUsername)) { Client.Connect(clientId); } else { Client.Connect(clientId, conference.MqttBrokerUsername, conference.MqttBrokerPassword, false, 1000); } Client.Subscribe(new string[] { Conference.BaseTopicPath + "rfid/room/+" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); } }
private void ProcessData(object param) { while (!shouldStop) { try { if (!mqttClient.IsConnected) { mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None); string clientID = Guid.NewGuid().ToString(); if (MqttUserName == null || MqttPassword == null) { mqttClient.Connect(clientID); } else { mqttClient.Connect(clientID, MqttUserName, MqttPassword); } } } catch (Exception exc) { if (!this.AutomaticReconnect) { throw exc; } } ReadOrder readOrder = (ReadOrder)param; lock (lockProcessData) { try { if (readOrder.FunctionCode == FunctionCode.ReadCoils) { bool[] value = modbusClient.ReadCoils(readOrder.StartingAddress, readOrder.Quantity); for (int i = 0; i < value.Length; i++) { if (readOrder.oldvalue[i] == null) { mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]); } else if ((bool)readOrder.oldvalue[i] != value[i]) { mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]); } readOrder.oldvalue[i] = value[i]; } } if (readOrder.FunctionCode == FunctionCode.ReadDiscreteInputs) { bool[] value = modbusClient.ReadDiscreteInputs(readOrder.StartingAddress, readOrder.Quantity); for (int i = 0; i < value.Length; i++) { if (readOrder.oldvalue[i] == null) { mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]); } else if ((bool)readOrder.oldvalue[i] != value[i]) { mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]); } readOrder.oldvalue[i] = value[i]; } } if (readOrder.FunctionCode == FunctionCode.ReadHoldingRegisters) { int[] value = modbusClient.ReadHoldingRegisters(readOrder.StartingAddress, readOrder.Quantity); for (int i = 0; i < value.Length; i++) { float scale = readOrder.Scale != null ? (readOrder.Scale[i] == 0) ? 1 : readOrder.Scale[i] : 1; if (readOrder.oldvalue[i] == null) { mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale) + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]); readOrder.oldvalue[i] = value[i]; } else if (((int)readOrder.oldvalue[i] != value[i]) && (readOrder.Hysteresis != null ? ((value[i] < (int)readOrder.oldvalue[i] - (int)readOrder.Hysteresis[i]) | (value[i] > (int)readOrder.oldvalue[i] + (int)readOrder.Hysteresis[i])) : true)) { mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]); readOrder.oldvalue[i] = value[i]; } } } if (readOrder.FunctionCode == FunctionCode.ReadInputRegisters) { int[] value = modbusClient.ReadInputRegisters(readOrder.StartingAddress, readOrder.Quantity); for (int i = 0; i < value.Length; i++) { float scale = readOrder.Scale != null ? (readOrder.Scale[i] == 0) ? 1 : readOrder.Scale[i] : 1; if (readOrder.oldvalue[i] == null) { mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]); readOrder.oldvalue[i] = value[i]; } else if (((int)readOrder.oldvalue[i] != value[i]) && (readOrder.Hysteresis != null ? ((value[i] < (int)readOrder.oldvalue[i] - (int)readOrder.Hysteresis[i]) | (value[i] > (int)readOrder.oldvalue[i] + (int)readOrder.Hysteresis[i])) : true)) { mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]); readOrder.oldvalue[i] = value[i]; } } } } catch (Exception exc) { modbusClient.Disconnect(); Thread.Sleep(2000); if (!AutomaticReconnect) { throw exc; } if (!modbusClient.Connected) { try { modbusClient.Connect(); } catch (Exception) { } } } } System.Threading.Thread.Sleep(readOrder.CylceTime); } }