/// <summary> /// Constructor /// </summary> public MqttBrokerSession() : base() { this.Client = null; this.Subscriptions = new List<MqttSubscription>(); this.OutgoingMessages = new Queue<MqttMsgPublish>(); }
public override void Clear() { base.Clear(); this.Client = null; this.Subscriptions.Clear(); this.OutgoingMessages.Clear(); }
public static void Disconnect() { mqttClient.Dispose(); mqttClient = null; // drop the old subscriptions subscriptions = new List<PublishSubscription>(); }
/// <summary> /// Connects to the specified mqtt server. /// </summary> /// <param name="server"></param> /// <param name="port"></param> /// <returns>The state of the connection.</returns> public ConnectionState Connect (string server, short port) { client = new MqttClient (server, port, Options.ClientIdentifier); syncContext = SynchronizationContext.Current; Trace.WriteLine ("Connecting to " + server + ":" + port.ToString ()); return client.Connect(Options.Username, Options.Password); }
public void Connect() { var c = new MqttClient("clientId", new MockMqttClient()); Assert.IsFalse(c.IsConnected); c.Connect(new IPEndPoint(IPAddress.Loopback, 1883)).Wait(); Assert.IsTrue(c.IsConnected); c.Disconnect(TimeSpan.FromSeconds(1)); Assert.IsFalse(c.IsConnected); }
/// <summary> /// Connects to the specified mqtt server. /// </summary> /// <param name="server"></param> /// <param name="port"></param> /// <returns>The state of the connection.</returns> public ConnectionState Connect(string server, short port) { client = new MqttClient (server, port, Options.ClientIdentifier); client.MessageAvailable += ClientMessageAvailable; syncContext = SynchronizationContext.Current; Trace.WriteLine ("Connecting to " + server + ":" + port.ToString ()); return client.Connect(); }
static void Main(string[] args) { var client = new MqttClient("localhost", "whatter"); client.Connect(); var topicObservable = client.Observe<String, AsciiPayloadConverter>("Nmqtt_quickstart_topic", MqttQos.AtLeastOnce); topicObservable.Subscribe( msg => Console.WriteLine(String.Format("Msg Received on '{0}' is '{1}'", msg.Topic, msg.Payload))); topicObservable.Subscribe( msg => Console.WriteLine(String.Format("Second Msg Received on '{0}' is '{1}'", msg.Topic, msg.Payload))); Console.ReadKey(); }
public void connect() { // SUBSCRIBER // create client instance MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS)); // register to message received client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; string clientId = Guid.NewGuid().ToString(); client.Connect(clientId); // subscribe to the topic "/home/temperature" with QoS 2 client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); }
private async void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { await Task.Factory.StartNew (() => { try { // create network channel to accept connection request IMqttNetworkChannel channel = new MqttNetworkChannel(args.Socket); channel.Accept(); // handling channel for connected client MqttClient client = new MqttClient(channel); // raise client raw connection event this.OnClientConnected(client); } catch (Exception) { // TODO : check errors/exceptions on accepting connection } }); }
static void Main(string[] args) { if (client == null) { // create client instance client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS)); string clientId = Guid.NewGuid().ToString(); client.Connect(clientId, "guest", "guest"); SubscribeMessage(); } // Initialize DirectInput var directInput = new DirectInput(); // Find a Joystick Guid var joystickGuid = Guid.Empty; foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } // If Gamepad not found, look for a Joystick if (joystickGuid == Guid.Empty) { foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) { joystickGuid = deviceInstance.InstanceGuid; } } // If Joystick not found, throws an error if (joystickGuid == Guid.Empty) { Console.WriteLine("No joystick/Gamepad found."); Console.ReadKey(); Environment.Exit(1); } // Instantiate the joystick var joystick = new Joystick(directInput, joystickGuid); Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid); // Query all suported ForceFeedback effects var allEffects = joystick.GetEffects(); foreach (var effectInfo in allEffects) { Console.WriteLine("Effect available {0}", effectInfo.Name); } // Set BufferSize in order to use buffered data. joystick.Properties.BufferSize = 128; // Acquire the joystick joystick.Acquire(); const int stop = 32511; // Poll events from joystick while (true) { joystick.Poll(); var datas = joystick.GetBufferedData(); foreach (var state in datas) { if (state.Offset.ToString() == "X" && state.Value > stop) { MoveRobot("MOVE", "R"); Console.WriteLine("Kanan"); } else if (state.Offset.ToString() == "X" && state.Value < stop) { MoveRobot("MOVE", "L"); Console.WriteLine("Kiri"); } else if (state.Offset.ToString() == "Y" && state.Value < stop) { MoveRobot("MOVE", "F"); Console.WriteLine("Maju"); } else if (state.Offset.ToString() == "Y" && state.Value > stop) { MoveRobot("MOVE", "B"); Console.WriteLine("Mundur"); } else { MoveRobot("MOVE", "S"); Console.WriteLine("Stop"); } } } }
private void Setup(string ip, string ns) { this.nameSpace = ns; if (this.requestHandlers == null) { this.requestHandlers = new Dictionary <string, Func <byte[], bool> >() { { "/" + ns + "/request/image", HandleRequestImage }, { "/" + ns + "/request/centers", HandleRequestImageCenters } }; } if (this.client == null) { this.client = new MqttClient(ip); this.client.ProtocolVersion = MqttProtocolVersion.Version_3_1; this.client.MqttMsgPublishReceived += this.onMqttReceive; this.client.Subscribe(this.requestHandlers.Keys.ToArray(), Enumerable.Repeat(MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, this.requestHandlers.Count).ToArray()); this.client.Connect(Guid.NewGuid().ToString()); } if (this.frames == null) { this.frames = new Dictionary <MediaFrameSourceKind, MediaFrameReference>() { { MediaFrameSourceKind.Color, null }, { MediaFrameSourceKind.Depth, null } } } ; while (this.mediaCapture == null) { // select device with both color and depth streams var cameras = Task.Run(async() => { return(await MediaFrameSourceGroup.FindAllAsync()); }); var eligible = cameras.Result.Select(c => new { Group = c, SourceInfos = new MediaFrameSourceInfo[] { c.SourceInfos.FirstOrDefault(info => info.SourceKind == MediaFrameSourceKind.Color), c.SourceInfos.FirstOrDefault(info => info.SourceKind == MediaFrameSourceKind.Depth) } }).Where(c => c.SourceInfos[0] != null && c.SourceInfos[1] != null).ToList(); if (eligible.Count == 0) // retry 1 second later { this.restartingCamera = true; BackgroundMediaPlayer.Current.SetUriSource(new Uri("ms-winsoundevent:Notification.Default")); BackgroundMediaPlayer.Current.Play(); Task.Run(async() => { await System.Threading.Tasks.Task.Delay(1000); }).Wait(); continue; } this.restartingCamera = false; this.lastNetworkCall = this.appClockNetwork.Elapsed.TotalMilliseconds; var selected = eligible[0]; // open device this.mediaCapture = new MediaCapture(); Task.Run(async() => { await this.mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { SourceGroup = selected.Group, SharingMode = MediaCaptureSharingMode.SharedReadOnly, StreamingCaptureMode = StreamingCaptureMode.Video, MemoryPreference = MediaCaptureMemoryPreference.Cpu }); }).Wait(); // set stream callbacks for (int i = 0; i < selected.SourceInfos.Length; ++i) { MediaFrameSourceInfo info = selected.SourceInfos[i]; MediaFrameSource frameSource = null; if (this.mediaCapture.FrameSources.TryGetValue(info.Id, out frameSource)) { var frameReader = Task.Run(async() => { return(await this.mediaCapture.CreateFrameReaderAsync(frameSource)); }); frameReader.Result.FrameArrived += FrameReader_FrameArrived; var status = Task.Run(async() => { return(await frameReader.Result.StartAsync()); }); if (status.Result != MediaFrameReaderStartStatus.Success) { return; } } } } #if PRINT_STATUS_MESSAGE this.appClock.Start(); #endif }
public RpcClient(MqttClient mqttClient, ILogger logger) { _mqttClient = mqttClient ?? throw new ArgumentNullException(nameof(mqttClient)); _logger = logger; _mqttClient.ApplicationMessageReceivedAsync += OnApplicationMessageReceived; }
public frmCustomQuery(MqttClient mqtt) { InitializeComponent(); _mqtt = mqtt; _mqtt.MqttMsgPublishReceived += _mqtt_MqttMsgPublishReceived; }
async void IMessageHandler.Rfm9XOnReceive(Rfm9XDevice.OnDataReceivedEventArgs e) { LoggingFields processReceiveLoggingFields = new LoggingFields(); JObject telemetryDataPoint = new JObject(); char[] sensorReadingSeparators = { ',' }; char[] sensorIdAndValueSeparators = { ' ' }; processReceiveLoggingFields.AddString("PacketSNR", e.PacketSnr.ToString("F1")); processReceiveLoggingFields.AddInt32("PacketRSSI", e.PacketRssi); processReceiveLoggingFields.AddInt32("RSSI", e.Rssi); string addressBcdText = BitConverter.ToString(e.Address); processReceiveLoggingFields.AddInt32("DeviceAddressLength", e.Address.Length); processReceiveLoggingFields.AddString("DeviceAddressBCD", addressBcdText); string messageText; try { messageText = UTF8Encoding.UTF8.GetString(e.Data); processReceiveLoggingFields.AddString("MessageText", messageText); } catch (Exception ex) { processReceiveLoggingFields.AddString("Exception", ex.ToString()); this.Logging.LogEvent("PayloadProcess failure converting payload to text", processReceiveLoggingFields, LoggingLevel.Warning); return; } // Chop up the CSV text string[] sensorReadings = messageText.Split(sensorReadingSeparators, StringSplitOptions.RemoveEmptyEntries); if (sensorReadings.Length < 1) { this.Logging.LogEvent("PayloadProcess payload contains no sensor readings", processReceiveLoggingFields, LoggingLevel.Warning); return; } // Chop up each sensor read into an ID & value foreach (string sensorReading in sensorReadings) { string[] sensorIdAndValue = sensorReading.Split(sensorIdAndValueSeparators, StringSplitOptions.RemoveEmptyEntries); // Check that there is an id & value if (sensorIdAndValue.Length != 2) { this.Logging.LogEvent("PayloadProcess payload invalid format", processReceiveLoggingFields, LoggingLevel.Warning); return; } string sensorId = sensorIdAndValue[0]; string value = sensorIdAndValue[1]; telemetryDataPoint.Add(addressBcdText + sensorId, Convert.ToDouble(value)); } processReceiveLoggingFields.AddString("MQTTClientId", MqttClient.Options.ClientId); string stateTopic = string.Format(stateTopicFormat, MqttClient.Options.ClientId); try { var message = new MqttApplicationMessageBuilder() .WithTopic(stateTopic) .WithPayload(JsonConvert.SerializeObject(telemetryDataPoint)) .WithAtLeastOnceQoS() .Build(); Debug.WriteLine(" {0:HH:mm:ss} MQTT Client PublishAsync start", DateTime.UtcNow); await MqttClient.PublishAsync(message); Debug.WriteLine(" {0:HH:mm:ss} MQTT Client PublishAsync finish", DateTime.UtcNow); this.Logging.LogEvent("PublishAsync Ubidots payload", processReceiveLoggingFields, LoggingLevel.Information); } catch (Exception ex) { processReceiveLoggingFields.AddString("Exception", ex.ToString()); this.Logging.LogEvent("PublishAsync Ubidots payload", processReceiveLoggingFields, LoggingLevel.Error); } }
// This method is run when the mainboard is powered up or reset. void ProgramStarted() { //setup wifi wifiRS21.DebugPrintEnabled = true; NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged; // setup events NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged; wifiRS21.NetworkDown += new GT.Modules.Module.NetworkModule.NetworkEventHandler(wifi_NetworkDown); wifiRS21.NetworkUp += new GT.Modules.Module.NetworkModule.NetworkEventHandler(wifi_NetworkUp); // use the router's DHCP server to set my network info if (!wifiRS21.NetworkInterface.Opened) wifiRS21.NetworkInterface.Open(); if (!wifiRS21.NetworkInterface.IsDhcpEnabled) { wifiRS21.UseDHCP(); wifiRS21.NetworkInterface.EnableDhcp(); wifiRS21.NetworkInterface.EnableDynamicDns(); } // look for avaiable networks var scanResults = wifiRS21.NetworkInterface.Scan(); // go through each network and print out settings in the debug window foreach (GHI.Networking.WiFiRS9110.NetworkParameters result in scanResults) { Debug.Print("****" + result.Ssid + "****"); Debug.Print("ChannelNumber = " + result.Channel); Debug.Print("networkType = " + result.NetworkType); Debug.Print("PhysicalAddress = " + GetMACAddress(result.PhysicalAddress)); Debug.Print("RSSI = " + result.Rssi); Debug.Print("SecMode = " + result.SecurityMode); } // locate a specific network GHI.Networking.WiFiRS9110.NetworkParameters[] info = wifiRS21.NetworkInterface.Scan(SSID); if (info != null) { wifiRS21.NetworkInterface.Join(info[0].Ssid, KeyWifi); wifiRS21.UseThisNetworkInterface(); bool res = wifiRS21.IsNetworkConnected; Debug.Print("Network joined"); Debug.Print("active:" + wifiRS21.NetworkInterface.ActiveNetwork.Ssid); } Debug.Print("Program Started"); Mobil = new MobilRemote(); GT.Timer timer = new GT.Timer(100); timer.Tick += (x) => { if (isNavigating) return; isNavigating = true; ledStrip.TurnAllLedsOff(); switch (Mobil.Arah) { case MobilRemote.ArahJalan.Maju: motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, 1); motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, 1); ledStrip.TurnAllLedsOn(); break; case MobilRemote.ArahJalan.Mundur: motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, -0.7); motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, -0.7); ledStrip.TurnLedOn(2); ledStrip.TurnLedOn(3); ledStrip.TurnLedOn(4); break; case MobilRemote.ArahJalan.Kiri: motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, -0.7); motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, 0.7); ledStrip.TurnLedOn(0); ledStrip.TurnLedOn(1); break; case MobilRemote.ArahJalan.Kanan: motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, 0.7); motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, -0.7); ledStrip.TurnLedOn(5); ledStrip.TurnLedOn(6); break; case MobilRemote.ArahJalan.Stop: motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, 0); motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, 0); break; } isNavigating = false; }; timer.Start(); while (!wifiRS21.IsNetworkConnected || wifiRS21.NetworkInterface.IPAddress=="0.0.0.0") { Thread.Sleep(100); } client = new MqttClient(MQTT_BROKER_ADDRESS); string clientId = Guid.NewGuid().ToString(); client.Connect(clientId); SubscribeMessage(); }
private static void MonitorMqtt() { UTF8Encoding Encoder = new UTF8Encoding(false); bool HasLightValue = false; bool HasMotionValue = false; MqttClient Client = null; try { WaitHandle[] Handles = new WaitHandle[] { updateLeds, updateAlarm }; while (executing) { try { if (Client == null) { Client = new MqttClient("iot.eclipse.org", MqttClient.DefaultPort, "LearningIoTController", string.Empty, false); //Client.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal)); Client.Open(); Client.CONNECT(20, true); Client.OnDataPublished += (Sender, e) => { string Topic = e.Topic; if (!Topic.StartsWith("Clayster/LearningIoT/Sensor/")) { return; } string s = System.Text.Encoding.UTF8.GetString(e.Data); PhysicalMagnitude Magnitude; bool b; Topic = Topic.Substring(28); switch (Topic) { case "Light": if (PhysicalMagnitude.TryParse(s, out Magnitude) && Magnitude.Unit == "%" && Magnitude.Value >= 0 && Magnitude.Value <= 100) { lightPercent = Magnitude.Value; if (!HasLightValue) { HasLightValue = true; if (HasMotionValue) { hasValues = true; } } CheckControlRules(); } break; case "Motion": if (!string.IsNullOrEmpty(s) && XmlUtilities.TryParseBoolean(s, out b)) { motion = b; if (!HasMotionValue) { HasMotionValue = true; if (HasLightValue) { hasValues = true; } } CheckControlRules(); } break; } }; Client.SUBSCRIBE(new KeyValuePair <string, MqttQoS> ("Clayster/LearningIoT/Sensor/#", MqttQoS.QoS1_Acknowledged)); Log.Information("Listening on MQTT topic Clayster/LearningIoT/Sensor @ ", EventLevel.Minor, Client.Host + ":" + Client.PortNumber.ToString()); } switch (WaitHandle.WaitAny(Handles, 1000)) { case 0: // Update LEDS int i; lock (synchObject) { i = lastLedMask; } Client.PUBLISH("Clayster/LearningIoT/Actuator/do", Encoder.GetBytes(i.ToString()), MqttQoS.QoS1_Acknowledged, true); // Just to synchronize with the other topics. for (int j = 1; j <= 8; j++) { Client.PUBLISH("Clayster/LearningIoT/Actuator/do" + j.ToString(), Encoder.GetBytes((i & 1).ToString()), MqttQoS.QoS1_Acknowledged, true); i >>= 1; } break; case 1: // Update Alarm bool b; lock (synchObject) { b = lastAlarm.Value; } Client.PUBLISH("Clayster/LearningIoT/Actuator/ao", Encoder.GetBytes(b ? "1" : "0"), MqttQoS.QoS1_Acknowledged, true); if (b) { Thread T = new Thread(SendAlarmMail); T.Priority = ThreadPriority.BelowNormal; T.Name = "SendAlarmMail"; T.Start(); } break; default: // Timeout CheckSubscriptions(30); break; } } catch (ThreadAbortException) { // Don't log. Exception will be automatically re-raised. } catch (Exception ex) { Log.Exception(ex); if (Client != null) { Client.Dispose(); Client = null; } Thread.Sleep(5000); } } } finally { Client.Dispose(); } }
private async Task MqttConnection_OnContentReceived(object Sender, MqttContent Content) { BinaryInput Input = Content.DataInput; byte Command = Input.ReadByte(); switch (Command) { case 0: // Hello string ApplicationName = Input.ReadString(); if (ApplicationName != this.applicationName) { break; } Player Player = this.Deserialize(Input); if (Player is null) { break; } #if LineListener Console.Out.WriteLine("Rx: HELLO(" + Player.ToString() + ")"); #endif IPEndPoint ExpectedEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork); lock (this.remotePlayersByEndpoint) { this.remotePlayersByEndpoint[ExpectedEndpoint] = Player; this.remotePlayerIPs[ExpectedEndpoint.Address] = true; this.playersById[Player.PlayerId] = Player; this.UpdateRemotePlayersLocked(); } MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerAvailable; if (!(h is null)) { try { await h(this, Player); } catch (Exception ex) { Log.Critical(ex); } } break; case 1: // Interconnect ApplicationName = Input.ReadString(); if (ApplicationName != this.applicationName) { break; } Player = this.Deserialize(Input); if (Player is null) { break; } #if LineListener Console.Out.Write("Rx: INTERCONNECT(" + Player.ToString()); #endif int Index = 0; int i, c; LinkedList <Player> Players = new LinkedList <Player>(); bool LocalPlayerIncluded = false; Player.Index = Index++; Players.AddLast(Player); c = (int)Input.ReadUInt(); for (i = 0; i < c; i++) { Player = this.Deserialize(Input); if (Player is null) { #if LineListener Console.Out.Write("," + this.localPlayer.ToString()); #endif this.localPlayer.Index = Index++; LocalPlayerIncluded = true; } else { #if LineListener Console.Out.Write("," + Player.ToString()); #endif Player.Index = Index++; Players.AddLast(Player); } } #if LineListener Console.Out.WriteLine(")"); #endif if (!LocalPlayerIncluded) { break; } this.mqttConnection.Dispose(); this.mqttConnection = null; lock (this.remotePlayersByEndpoint) { this.remotePlayersByEndpoint.Clear(); this.remotePlayerIPs.Clear(); this.remotePlayersByIndex.Clear(); this.playersById.Clear(); this.remotePlayersByIndex[this.localPlayer.Index] = this.localPlayer; this.playersById[this.localPlayer.PlayerId] = this.localPlayer; foreach (Player Player2 in Players) { ExpectedEndpoint = Player2.GetExpectedEndpoint(this.p2pNetwork); this.remotePlayersByIndex[Player2.Index] = Player2; this.remotePlayersByEndpoint[ExpectedEndpoint] = Player2; this.remotePlayerIPs[ExpectedEndpoint.Address] = true; this.playersById[Player2.PlayerId] = Player2; } this.UpdateRemotePlayersLocked(); } await this.SetState(MultiPlayerState.ConnectingPlayers); await this.StartConnecting(); break; case 2: // Bye ApplicationName = Input.ReadString(); if (ApplicationName != this.applicationName) { break; } Guid PlayerId = Input.ReadGuid(); lock (this.remotePlayersByEndpoint) { if (!this.playersById.TryGetValue(PlayerId, out Player)) { break; } #if LineListener Console.Out.WriteLine("Rx: BYE(" + Player.ToString() + ")"); #endif ExpectedEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork); this.playersById.Remove(PlayerId); this.remotePlayersByEndpoint.Remove(ExpectedEndpoint); this.remotePlayersByIndex.Remove(Player.Index); IPAddress ExpectedAddress = ExpectedEndpoint.Address; bool AddressFound = false; foreach (IPEndPoint EP in this.remotePlayersByEndpoint.Keys) { if (IPAddress.Equals(EP.Address, ExpectedAddress)) { AddressFound = true; break; } } if (!AddressFound) { this.remotePlayerIPs.Remove(ExpectedAddress); } this.UpdateRemotePlayersLocked(); } break; } }
public static ushort Publish(this MqttClient mqttClient, string topic, byte[] message, MqttQoSLevel qosLevel, bool retain) { return(mqttClient.Publish(topic, message, (byte)qosLevel, retain)); }
private void startMqtt_button_Click(object sender, EventArgs e) { MqttClient client = new MqttClient(IP_ADDR); byte code = client.Connect(new Guid().ToString(), null, null, true, 10); if (code == 0) { Console.WriteLine("port numbr : " + client.Settings.Port.ToString()); Console.WriteLine("ClientID : " + client.ClientId.ToString()); Console.WriteLine("Is connected? : " + client.IsConnected.ToString()); Console.WriteLine("Protocol version: " + client.ProtocolVersion.ToString()); } else { Console.WriteLine("Failed to connect with " + code.ToString()); Console.WriteLine("Code is: " + code.ToString()); return; } // try to subscribe // from https://m2mqtt.wordpress.com/using-mqttclient/ client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; //string[] topic = { "sensor/temp", "sensor/humidity" }; // list of topins to subscribe to string[] topic = { "test" }; // list of topins to subscribe to byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE }; client.Subscribe(topic, qosLevels); Boolean dir_up = true; int counter = 0; for (int i = 0; i < 1000; i++) { ushort msgId = client.Publish(MQTT_TOPIC, Encoding.UTF8.GetBytes(counter.ToString()), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false); Console.WriteLine("msgId is: " + msgId.ToString()); Thread.Sleep(1000); mqtt_msg_box.Text = counter.ToString(); if (dir_up == true) { counter += 1; } else { counter -= 1; } if (counter == 10) { dir_up = false; } if (counter == 0) { dir_up = true; } global_counter += 1; mqtt_msg_cnt_box.Text = global_counter.ToString(); Application.DoEvents(); Thread.Sleep(1000); } Console.WriteLine("Finished. Numbe of iterations: " + global_counter.ToString()); client.Unsubscribe(topic); client.Disconnect(); client = null; }
public NetHelper MqttService(string server, int port, string username, string password, string clientId) { mqttClient = new MqttClient(server, port, clientId); mqttClient.Connect(username, password); return(this); }
public void TestCleanup() { this.client?.Dispose(); this.client = null; }
public void TestInitialize() { this.client = new MqttClient("mqtt.eclipse.org", this.Port, this.Encypted, "UnitTest", string.Empty, new TextWriterSniffer(Console.Out, BinaryPresentationMethod.Hexadecimal)); }
private void Connect() { Disconnect(); mqttClient = new MqttClient(endPoint.Address, endPoint.Port, endPoint.ClientId); if (this.networkCredential != null) { mqttClient.Connect(this.networkCredential.UserName, this.networkCredential.Password); } else { mqttClient.Connect(); } }
protected override void SolveInstance(IGH_DataAccess DA) { // set output value lock (mutex) { DA.SetData(0, topic); DA.SetData(1, payload); } // get data String rawURI = ""; if (!DA.GetData(0, ref rawURI)) { return; } // return if uri has not changed if (lastURI == rawURI) { return; } // set last uri lastURI = rawURI; // otherwise prepare for connection change // validate uri if (rawURI == "") { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Missing URI"); return; } // parse uri var uri = new Uri(rawURI); // disconnect current client (ignoring errors) if (client != null) { try { client.Disconnect(); } catch {} client = null; } // get port int port = uri.Port; if (port <= 0) { port = 1883; } // create client instance client = new MqttClient(uri.Host, port, false, null, null, MqttSslProtocols.None); // register callback client.MqttMsgPublishReceived += MessageReceived; // get username password var creds = uri.UserInfo.Split(':'); // connect to broker if (creds.Length == 0) { client.Connect(""); } else if (creds.Length == 1) { client.Connect("", creds[0], ""); } else if (creds.Length == 2) { client.Connect("", creds[0], creds[1]); } // default to # if path is empty var path = uri.AbsolutePath; if (path == "") { path = "#"; } // subscribe to the topic client.Subscribe(new string[] { path }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE }); }
/// <summary> /// Raise client connected event /// </summary> /// <param name="e">Event args</param> private void OnClientConnected(MqttClient client) { if (this.ClientConnected != null) this.ClientConnected(this, new MqttClientConnectedEventArgs(client)); }
public void Create(Configuration configuration) { this.config = configuration; QualityOfService = (byte)Enum.Parse(typeof(QualityOfService), this.config[QOSParam]); this.client = CreateClient(); if (UseNestedObject) { Grid coGrid = new Grid { Value = this.config[ObjectPropertiesParam] }; //Store source/alias names for the complex object ComplexObjectAliases = coGrid.Rows.Select(r => { string source = (string)r[SourceNameColumn]; string alias = (string)r[OutputNameColumn]; alias = string.IsNullOrWhiteSpace(alias) ? source : alias; return(new Tuple <string, string>(source, alias)); }).ToArray(); } MqttClient CreateClient() { X509Certificate2 caCert = null; X509Certificate2 clientCert = null; MqttSslProtocols protocol = MqttSslProtocols.None; bool secure = bool.TryParse(this.config[SecureParam], out secure) && secure; if (secure) { //MQTT can be made secure by a certificate from a Certificate Authority alone, or a CA certificate and a client certificate //The CA certificate should never need a password caCert = ListenerAdvanced.LoadCertificate(File.Parse(this.config[CACertParam]), string.Empty); //The Client certificate should always require a password if (!string.IsNullOrWhiteSpace(this.config[ClientCertParam])) { OnDecryptRequestArgs certDecryptArgs = new OnDecryptRequestArgs(this.config[CertPasswordParam]); OnDecryptRequest(this, certDecryptArgs); string clientPassword = certDecryptArgs.DecryptedValue; clientCert = ListenerAdvanced.LoadCertificate(File.Parse(this.config[ClientCertParam]), clientPassword); } if (Enum.TryParse(this.config[SecureProtocolParam], out MqttSslProtocols parsedProtocol)) { protocol = parsedProtocol; } } return(new MqttClient( this.config[BrokerParam] , Int32.TryParse(this.config[BrokerPortParam], out int port) && port > 0 ? port : 1883 , secure , caCert , clientCert , protocol , null)); } }
private void ParkSS_Load(object sender, EventArgs e) { client = new MqttClient(textBoxIP.Text); btnSubscribe_Click(sender, e); }
public async Task <IActionResult> Tag([FromQuery(Name = "id")] string codePart, [FromQuery(Name = "workstation")] string workstation) { #region Connect to Broker rfidJson = ""; // CONNECT TO BROKER string brokerAddress = "test.mosquitto.org"; MqttClient mClient = new MqttClient(brokerAddress); string clientId = Guid.NewGuid().ToString(); mClient.Connect(clientId); if (!mClient.IsConnected) { TempData["ErrorConn"] = "Erro na conexão!"; return(RedirectToAction("Index", "Tag")); } else { // INVOKE PUBLISH AND SUBSCRIBE AT THE SAME TIME Parallel.Invoke ( () => Publish(mClient, codePart, workstation), () => Subscribe(mClient, codePart) ); string topic = "part" + codePart; if (rfidJson == "1") { return(RedirectToAction("Index", "Tag", new { error = "1" })); } var obj = JObject.Parse(rfidJson); var rfid = obj["rfid"]; #region Consume endpoint string payload = JsonConvert.SerializeObject(""); var content = new StringContent(payload, Encoding.UTF8, "application/json"); using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", HttpContext.Session.GetString("sessionKey")); using (var response = await httpClient.PutAsync("http://localhost:8080/api/parts/" + codePart + "/tag/" + rfid, content)) { string apiResponse = await response.Content.ReadAsStringAsync(); var status = response.IsSuccessStatusCode; if (status == true) { // DISCONNECT AND UNSUBSCRIBE mClient.Unsubscribe(new string[] { topic }); mClient.Disconnect(); TempData["SuccessRFID"] = "Peça " + codePart + " taggada com o rfid: " + rfid; return(RedirectToAction("Index", "Tag")); } else { // DISCONNECT AND UNSUBSCRIBE mClient.Unsubscribe(new string[] { topic }); mClient.Disconnect(); if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { TempData["ErrorRFID"] = "Tag não encontrada. Usar um RFID válido."; return(RedirectToAction("Index", "Tag")); } TempData["ErrorRFID"] = "Erro a guardar o RFID!"; return(RedirectToAction("Index", "Tag")); } } } #endregion } #endregion }
private async Task ClientStart() { try { var tcpServer = txtIPAddr.Text; var tcpPort = int.Parse(txtPort.Text.Trim()); var mqttUser = txtUserName.Text.Trim(); var mqttPassword = txtPWD.Text.Trim(); var mqttFactory = new MqttFactory(); var options = new MqttClientOptions { ClientId = txtClientID.Text.Trim(), ProtocolVersion = MQTTnet.Formatter.MqttProtocolVersion.V311, ChannelOptions = new MqttClientTcpOptions { Server = tcpServer, Port = tcpPort }, WillDelayInterval = 10, WillMessage = new MqttApplicationMessage() { Topic = $"LastWill/{txtClientID.Text.Trim()}", Payload = Encoding.UTF8.GetBytes("I Lost the connection!"), QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce } }; if (options.ChannelOptions == null) { throw new InvalidOperationException(); } if (!string.IsNullOrEmpty(mqttUser)) { options.Credentials = new MqttClientCredentials { Username = mqttUser, Password = Encoding.UTF8.GetBytes(mqttPassword) }; } options.CleanSession = true; options.KeepAlivePeriod = TimeSpan.FromSeconds(5); mqttClient = mqttFactory.CreateMqttClient() as MqttClient; mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnMqttClientConnected); mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnMqttClientDisConnected); mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); await mqttClient.ConnectAsync(options); lbxMonitor.BeginInvoke(_updateMonitorAction, Logger.TraceLog(Logger.Level.Info, $"客户端[{options.ClientId}]尝试连接...")); } catch (Exception ex) { lbxMonitor.BeginInvoke(_updateMonitorAction, Logger.TraceLog(Logger.Level.Fatal, $"客户端尝试连接出错.>{ex.Message}")); } }
public static void Main() { //distance sensor //triger (12), echo (13), 5V + G HC_SR04 sensor = new HC_SR04(Pins.GPIO_PIN_D12, Pins.GPIO_PIN_D13); //buzzer OutputPort Klakson = new OutputPort(Pins.GPIO_PIN_D0, false); //motor driver HBridge MotorDriver = new HBridge(SecretLabs.NETMF.Hardware.Netduino.PWMChannels.PWM_PIN_D5, Pins.GPIO_PIN_D4, SecretLabs.NETMF.Hardware.Netduino.PWMChannels.PWM_PIN_D6, Pins.GPIO_PIN_D7); //led indicator if there is an object in the front of robot OutputPort WarningLed = new OutputPort(Pins.GPIO_PIN_D1, false); OutputPort GoLed = new OutputPort(Pins.GPIO_PIN_D2, false); //waiting till connect... if (!Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IsDhcpEnabled) { // using static IP while (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { ; // wait for network connectivity } } else { // using DHCP while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) { ; // wait for DHCP-allocated IP address } } //Debug print our IP address Debug.Print("Device IP: " + Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress); // create mqtt client instance client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS)); string clientId = Guid.NewGuid().ToString(); client.Connect(clientId); SubscribeMessage(); PublishMessage("/robot/state", "ONLINE"); while (true) { long ticks = sensor.Ping(); if (ticks > 0L) { double inches = sensor.TicksToInches(ticks); Debug.Print("jarak ke object :" + inches); if (inches < 4) { jalan = Arah.Berhenti; Klakson.Write(true); WarningLed.Write(true); GoLed.Write(false); PublishMessage("/robot/status", "Watchout there is an object in the front of robot!"); } else { Klakson.Write(false); WarningLed.Write(false); GoLed.Write(true); } } //stop first before change direction or turn if (lastDirection != jalan) { //stop before start new direction MotorDriver.SetState(HBridge.Motors.Motor1, 0); MotorDriver.SetState(HBridge.Motors.Motor2, 0); } switch (jalan) { case Arah.Maju: MotorDriver.SetState(HBridge.Motors.Motor1, Speed); MotorDriver.SetState(HBridge.Motors.Motor2, Speed); break; case Arah.Mundur: MotorDriver.SetState(HBridge.Motors.Motor1, (sbyte)(-Speed)); MotorDriver.SetState(HBridge.Motors.Motor2, (sbyte)(-Speed)); break; case Arah.Kiri: MotorDriver.SetState(HBridge.Motors.Motor1, -50); MotorDriver.SetState(HBridge.Motors.Motor2, 50); break; case Arah.Kanan: MotorDriver.SetState(HBridge.Motors.Motor1, 50); MotorDriver.SetState(HBridge.Motors.Motor2, -50); break; case Arah.Berhenti: MotorDriver.SetState(HBridge.Motors.Motor1, 0); MotorDriver.SetState(HBridge.Motors.Motor2, 0); break; } lastDirection = jalan; } }
private static void UseMQTT() { MqttClient mqtt = null; try { // Create M2MQTT client mqtt = new MqttClient( Properties.Settings.Default.MQTTServer, // Server name Properties.Settings.Default.MQTTPort, // Server port false, MqttSslProtocols.None, null, null ); // Set protocol for server mqtt.ProtocolVersion = MqttProtocolVersion.Version_3_1; // Add event handlers mqtt.MqttMsgPublishReceived += client_MqttMsgPublishReceived; mqtt.MqttMsgSubscribed += client_MqttMsgSubscribed; mqtt.MqttMsgUnsubscribed += client_MqttMsgUnsubscribed; mqtt.ConnectionClosed += client_ConnectionClosed; Console.WriteLine(string.Format( "Connect to broker: {0}:{1}", Properties.Settings.Default.MQTTServer, Properties.Settings.Default.MQTTPort )); // Subscribe to broker topics // 1. gateway messages // 2. nodes packets string[] topic = new string[Properties.Settings.Default.MQTTTopic.Count]; byte[] qos = new byte[Properties.Settings.Default.MQTTTopic.Count]; for (int i = 0; i < topic.Length; i++) { topic[i] = Properties.Settings.Default.MQTTTopic[i]; Console.WriteLine(string.Format("Subscribe to {0}", topic[i])); qos[i] = MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE; } // Connect to server mqtt.Connect(Guid.NewGuid().ToString()); // and subscribe ushort msgId = mqtt.Subscribe(topic, qos); WaitKeyPress("Press any key to exit\n"); // Unsubscribe mqtt.Unsubscribe(topic); complete = false; for (int timeout = 0; timeout < 500; timeout++) { if (complete) { break; } Thread.Sleep(10); } } catch (Exception ex) { Console.WriteLine(string.Format("MQTT ERROR:{0}", ex.Message)); } // Disconnect from server if (mqtt != null && mqtt.IsConnected) { mqtt.Disconnect(); complete = false; for (int timeout = 0; timeout < 500; timeout++) { if (complete) { break; } Thread.Sleep(10); } } WaitKeyPress(); }
public void SetMqttClient(MqttClient client) { this.client = client; }
public SmartH20_Alarm() { Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); InitializeComponent(); readXmlRules(); //connect to mosquito client = new MqttClient("host.dynip.sapo.pt", 21, false, null, null, MqttSslProtocols.None); client.Connect(Guid.NewGuid().ToString(), "isuser", "is2016"); if (client.IsConnected) { //Subscribe client.MqttMsgPublishReceived += readSensors; byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }; client.Subscribe(m_strTopicsInfo, qosLevels); } else { Console.Write("Error connecting to message broker..."); return; } //populate listView foreach (Sensor sensor in sensorList) { listBoxSensors.Items.Add(sensor.name); } if (!checkBoxActivate.Checked) { groupBox1.Enabled = false; } else { groupBox1.Enabled = true; } if (!checkBoxEq.Checked) { groupBox2.Enabled = false; } else { groupBox2.Enabled = true; } if (!checkBoxGr.Checked) { groupBox3.Enabled = false; } else { groupBox3.Enabled = true; } if (!checkBoxLs.Checked) { groupBox4.Enabled = false; } else { groupBox4.Enabled = true; } if (!checkBoxBT.Checked) { groupBox5.Enabled = false; } else { groupBox5.Enabled = true; } }
private void ConnectMqttBroker() { BrokerClient = new MqttClient(TxtBrokerIp.Text); BrokerClient.Connect("FakerDaemon"); }
public static void Connect() { mqttClient = new MqttClient(Settings.Default.MqttServerName, Settings.Default.MqttServerPort, Settings.Default.MqttClientIdentifier); mqttClient.Connect(); }
public NetHelper MqttService(string server, int port, string clientId) { mqttClient = new MqttClient(server, port, clientId); if (this.networkCredential != null) { mqttClient.Connect(this.networkCredential.UserName, this.networkCredential.Password); } else { mqttClient.Connect(); } return this; }
public MainPage() { this.InitializeComponent(); ApplicationView.PreferredLaunchViewSize = new Size(350, 350); ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize; if (this.localSettings.Values["mqttHostAddress"] != null) { this.IPText.Text = this.localSettings.Values["mqttHostAddress"].ToString(); } if (this.localSettings.Values["topicNameSpace"] != null) { this.NSText.Text = this.localSettings.Values["topicNameSpace"].ToString(); } else { this.NSText.Text = this.nameSpace; } try { // auto start client if (this.requestHandlers == null) { this.requestHandlers = new Dictionary <string, Func <byte[], bool> >() { { "/network/alive", UpdateLastNetworkCall }, { "/" + this.NSText.Text + "/request/image", HandleRequestImage }, { "/" + this.NSText.Text + "/request/centers", HandleRequestImageCenters }, { "/" + this.NSText.Text + "/start/camera/depth", HandleRequestStart }, { "/" + this.NSText.Text + "/stop/camera/depth", HandleRequestStop }, { "/" + this.NSText.Text + "/kill/camera/depth", HandleRequestKill }, }; } if (this.client == null) { this.client = new MqttClient(this.IPText.Text); this.client.ProtocolVersion = MqttProtocolVersion.Version_3_1; this.client.MqttMsgPublishReceived += this.onMqttReceive; this.client.Subscribe(this.requestHandlers.Keys.ToArray(), Enumerable.Repeat(MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, this.requestHandlers.Count).ToArray()); this.client.Connect(Guid.NewGuid().ToString()); } } catch { // failed auto start client this.requestHandlers = null; this.client = null; } this.colorPoints = new Point[640 * 360]; int row = 0; int at = 0; for (int idx = 0; idx < this.colorPoints.Length; ++idx) { int y = at / 1920; int x = at - y * 1920; this.colorPoints[idx] = new Point(x, y); at += 3; if (at - row * 1920 >= 1920) { row += 3; at = row * 1920; } } #if PRINT_STATUS_MESSAGE this.statusLogTimer.Interval = TimeSpan.FromMilliseconds(100); this.statusLogTimer.Tick += StatusLogTick; this.statusLogTimer.Start(); #endif this.networkTimer.Interval = TimeSpan.FromMilliseconds(100); this.networkTimer.Tick += NetworkTick; this.networkTimer.Start(); displayRequest.RequestActive(); }
public static int Main (string[] args) { Log.Register (new ConsoleOutEventLog (80)); Log.Information ("Initializing application..."); HttpSocketClient.RegisterHttpProxyUse (false, false); // Don't look for proxies. DB.BackupConnectionString = "Data Source=actuator.db;Version=3;"; DB.BackupProviderName = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider"; db = DB.GetDatabaseProxy ("TheActuator"); Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; executionLed.Low (); }; // HTTP Interface HttpServer HttpServer = new HttpServer (80, 10, true, true, 1); int i; Log.Information ("HTTP Server receiving requests on port " + HttpServer.Port.ToString ()); HttpServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Actuator Realm", GetDigestUserPasswordHash)); HttpServer.RegisterAuthenticationMethod (new SessionAuthentication ()); credentials = LoginCredentials.LoadCredentials (); if (credentials == null) { credentials = new LoginCredentials (); credentials.UserName = "******"; credentials.PasswordHash = CalcHash ("Admin", "Password"); credentials.SaveNew (); } state = State.LoadState (); if (state == null) { state = new State (); state.SaveNew (); } else { for (i = 0; i < 8; i++) digitalOutputs [i].Value = state.GetDO (i + 1); if (state.Alarm) AlarmOn (); else AlarmOff (); } WebServiceAPI wsApi; HttpServer.Register ("/", HttpGetRoot, HttpPostRoot, false); // Synchronous, no authentication HttpServer.Register ("/credentials", HttpGetCredentials, HttpPostCredentials, false); // Synchronous, no authentication HttpServer.Register ("/set", HttpGetSet, HttpPostSet, true); // Synchronous, http authentication HttpServer.Register ("/xml", HttpGetXml, true); // Synchronous, http authentication HttpServer.Register ("/json", HttpGetJson, true); // Synchronous, http authentication HttpServer.Register ("/turtle", HttpGetTurtle, true); // Synchronous, http authentication HttpServer.Register ("/rdf", HttpGetRdf, true); // Synchronous, http authentication HttpServer.Register (wsApi = new WebServiceAPI (), true); // HTTPS interface // Certificate must be a valid P12 (PFX) certificate file containing a private key. // X509Certificate2 Certificate = new X509Certificate2 ("Certificate.pfx", "PASSWORD"); // HttpServer HttpsServer = new HttpServer (443, 10, true, true, 1, true, false, Certificate); // // HttpsServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Actuator Realm", GetDigestUserPasswordHash)); // // foreach (IHttpServerResource Resource in HttpServer.GetResources()) // HttpsServer.Register (Resource); // // Log.Information ("HTTPS Server receiving requests on port " + HttpsServer.Port.ToString ()); // CoAP Interface CoapEndpoint CoapEndpoint = new CoapEndpoint (); Log.Information ("CoAP endpoint receiving requests on port " + CoapEndpoint.Port.ToString ()); //CoapEndpoint.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal, true)); for (i = 1; i <= 8; i++) { CoapEndpoint.RegisterResource ("do" + i.ToString () + "/txt", "Digital Output " + i.ToString () + ", as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, false, CoapGetDigitalOutputTxt, CoapSetDigitalOutputTxt); } CoapEndpoint.RegisterResource ("do/txt", "Digital Outputs, as a number 0-255 as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, false, CoapGetDigitalOutputsTxt, CoapSetDigitalOutputsTxt); CoapEndpoint.RegisterResource ("alarm/txt", "Alarm Output " + i.ToString () + ", as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, false, CoapGetAlarmOutputTxt, CoapSetAlarmOutputTxt); foreach (CoapBlockSize BlockSize in Enum.GetValues(typeof(CoapBlockSize))) { if (BlockSize == CoapBlockSize.BlockLimit_Datagram) continue; string Bytes = (1 << (4 + (int)BlockSize)).ToString (); CoapEndpoint.RegisterResource ("xml/" + Bytes, "Complete sensor readout, in XML. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetXml); CoapEndpoint.RegisterResource ("json/" + Bytes, "Complete sensor readout, in JSON. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetJson); CoapEndpoint.RegisterResource ("turtle/" + Bytes, "Complete sensor readout, in TURTLE. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetTurtle); CoapEndpoint.RegisterResource ("rdf/" + Bytes, "Complete sensor readout, in RDF. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetRdf); } // MQTT MqttClient MqttClient = new MqttClient ("iot.eclipse.org", MqttClient.DefaultPort, "LearningIoTActuator", string.Empty, false); //MqttClient.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal)); MqttClient.Open (); MqttClient.CONNECT (20, true); MqttClient.PUBLISH ("Clayster/LearningIoT/Actuator/ao", state.Alarm ? "1" : "0", MqttQoS.QoS1_Acknowledged, true); MqttClient.PUBLISH ("Clayster/LearningIoT/Actuator/do", wsApi.GetDigitalOutputs ().ToString (), MqttQoS.QoS1_Acknowledged, true); for (i = 1; i <= 8; i++) MqttClient.PUBLISH ("Clayster/LearningIoT/Actuator/do" + i.ToString (), wsApi.GetDigitalOutput (i) ? "1" : "0", MqttQoS.QoS1_Acknowledged, true); MqttClient.SUBSCRIBE (new KeyValuePair<string, MqttQoS> ("Clayster/LearningIoT/Actuator/#", MqttQoS.QoS1_Acknowledged)); MqttClient.OnDataPublished += OnMqttDataPublished; Log.Information ("Receiving commands via MQTT from Clayster/LearningIoT/Actuator @ ", EventLevel.Minor, MqttClient.Host + ":" + MqttClient.PortNumber.ToString ()); // Main loop Log.Information ("Initialization complete. Application started..."); try { while (executionLed.Value) { System.Threading.Thread.Sleep (1000); RemoveOldSessions (); } } catch (Exception ex) { Log.Exception (ex); executionLed.Low (); } finally { Log.Information ("Terminating application."); Log.Flush (); Log.Terminate (); HttpServer.Dispose (); //HttpsServer.Dispose (); if (MqttClient != null) MqttClient.Dispose (); executionLed.Dispose (); foreach (DigitalOutput Output in digitalOutputs) Output.Dispose (); if (alarmThread != null) { alarmThread.Abort (); alarmThread = null; } } return 0; }
public LightpackMqttClient(LightpackApiClient lightpackApiClient, IOptions <MqttConfiguration> mqttConfig) { _lightpackApiClient = lightpackApiClient; _mqttConfig = mqttConfig.Value; _mqttClient = new MqttClient(mqttConfig.Value.Host); }
/// <summary> /// Creates an instance of a Zigbee 2 MQTT hub /// </summary> /// <param name="mqtt">A client to the MQTT broker used by Zigbee 2 MQTT</param> /// <param name="scheduler">The scheduler used to run scripts, automations and manage devices of this Home Assistant</param> public Zigbee2MqttHub(MqttClient mqtt, IScheduler scheduler, string topic = DefaultTopic) { var deviceHost = new Zigbee2MqttDeviceHost(mqtt, topic, scheduler); Devices = new HomeDevicesManager(deviceHost); }
/// <summary> /// Disconnects from the MQTT server. /// </summary> public MqttClientHelper Disconnect() { if (this.mqttClient != null) { try { this.mqttClient.Dispose(); } catch { } mqttClient = null; } return this; }
private void buttonChangeIP_Click(object sender, EventArgs e) { client = new MqttClient(textBoxIP.Text); }
public MyMqttClient() { _mqttClient = MqttClient.CreateAsync(_mqttHostname).Result; var sess = _mqttClient.ConnectAsync().Result; }
private static void MqttThread () { WaitHandle[] Events = new WaitHandle[]{ mqttNewTemp, mqttNewLight, mqttNewMotion }; MqttClient Client = null; try { while (true) { try { if (Client == null) { Client = new MqttClient ("iot.eclipse.org", MqttClient.DefaultPort, "LearningIoTSensor", string.Empty, false); //Client.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal)); Client.Open (); Client.CONNECT (20, true); Log.Information ("Publishing via MQTT to Clayster/LearningIoT/Sensor @ ", EventLevel.Minor, Client.Host + ":" + Client.PortNumber.ToString ()); } switch (WaitHandle.WaitAny (Events, 1000)) { case 0: // New temperature Client.PUBLISH ("Clayster/LearningIoT/Sensor/Temperature", FieldNumeric.Format (temperatureC, "C", 1), MqttQoS.QoS1_Acknowledged, true); break; case 1: // New light Client.PUBLISH ("Clayster/LearningIoT/Sensor/Light", FieldNumeric.Format (lightPercent, "%", 1), MqttQoS.QoS1_Acknowledged, true); break; case 2: // New motion Client.PUBLISH ("Clayster/LearningIoT/Sensor/Motion", motionDetected ? "1" : "0", MqttQoS.QoS1_Acknowledged, true); break; } } catch (Exception ex) { Log.Exception (ex); if (Client != null) { Client.Dispose (); Client = null; } mqttNewTemp.Set (); mqttNewLight.Set (); mqttNewMotion.Set (); Thread.Sleep(5000); } } } catch (ThreadAbortException) { Thread.ResetAbort (); } catch (Exception ex) { Log.Exception (ex); } finally { if (Client != null) Client.Dispose (); } }
private void ProcessData(object param) { while (!this.shouldStop) { try { if (!this.mqttClient.IsConnected) { this.mqttClient = new MqttClient(this.mqttBrokerAddress, this.mqttBrokerPort, false, (X509Certificate)null, (X509Certificate)null, MqttSslProtocols.None); string clientId = Guid.NewGuid().ToString(); if (this.MqttUserName == null || this.MqttPassword == null) { int num1 = (int)this.mqttClient.Connect(clientId); } else { int num2 = (int)this.mqttClient.Connect(clientId, this.MqttUserName, this.MqttPassword); } } } catch (Exception ex) { if (!this.AutomaticReconnect) { throw ex; } } ReadOrder readOrder = (ReadOrder)param; lock (this.lockProcessData) { try { if (readOrder.FunctionCode == FunctionCode.ReadCoils) { bool[] flagArray = this.modbusClient.ReadCoils(readOrder.StartingAddress, readOrder.Quantity); int index = 0; while (index < flagArray.Length) { if (readOrder.oldvalue[index] == null) { int num1 = (int)this.mqttClient.Publish(readOrder.Topic[index], Encoding.UTF8.GetBytes(flagArray[index].ToString()), (byte)2, readOrder.Retain != null && readOrder.Retain[index]); } else if ((bool)readOrder.oldvalue[index] != flagArray[index]) { int num2 = (int)this.mqttClient.Publish(readOrder.Topic[index], Encoding.UTF8.GetBytes(flagArray[index].ToString()), (byte)2, readOrder.Retain != null && readOrder.Retain[index]); } readOrder.oldvalue[index] = (object)flagArray[index]; checked { ++index; } } } if (readOrder.FunctionCode == FunctionCode.ReadDiscreteInputs) { bool[] flagArray = this.modbusClient.ReadDiscreteInputs(readOrder.StartingAddress, readOrder.Quantity); int index = 0; while (index < flagArray.Length) { if (readOrder.oldvalue[index] == null) { int num1 = (int)this.mqttClient.Publish(readOrder.Topic[index], Encoding.UTF8.GetBytes(flagArray[index].ToString()), (byte)2, readOrder.Retain != null && readOrder.Retain[index]); } else if ((bool)readOrder.oldvalue[index] != flagArray[index]) { int num2 = (int)this.mqttClient.Publish(readOrder.Topic[index], Encoding.UTF8.GetBytes(flagArray[index].ToString()), (byte)2, readOrder.Retain != null && readOrder.Retain[index]); } readOrder.oldvalue[index] = (object)flagArray[index]; checked { ++index; } } } if (readOrder.FunctionCode == FunctionCode.ReadHoldingRegisters) { int[] numArray = this.modbusClient.ReadHoldingRegisters(readOrder.StartingAddress, readOrder.Quantity); int index = 0; while (index < numArray.Length) { float num1 = readOrder.Scale != null ? ((double)readOrder.Scale[index] == 0.0 ? 1f : readOrder.Scale[index]) : 1f; if (readOrder.oldvalue[index] == null) { int num2 = (int)this.mqttClient.Publish(readOrder.Topic[index], readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)numArray[index] * num1).ToString()) : Encoding.UTF8.GetBytes(((double)numArray[index] * (double)num1).ToString() + " " + readOrder.Unit[index]), (byte)2, readOrder.Retain != null && readOrder.Retain[index]); readOrder.oldvalue[index] = (object)numArray[index]; } else if ((int)readOrder.oldvalue[index] != numArray[index] && (readOrder.Hysteresis == null || numArray[index] < checked ((int)readOrder.oldvalue[index] - readOrder.Hysteresis[index]) | numArray[index] > checked ((int)readOrder.oldvalue[index] + readOrder.Hysteresis[index]))) { int num2 = (int)this.mqttClient.Publish(readOrder.Topic[index], readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)numArray[index] * num1).ToString()) : Encoding.UTF8.GetBytes(((float)numArray[index] * num1).ToString() + " " + readOrder.Unit[index]), (byte)2, readOrder.Retain != null && readOrder.Retain[index]); readOrder.oldvalue[index] = (object)numArray[index]; } checked { ++index; } } } if (readOrder.FunctionCode == FunctionCode.ReadInputRegisters) { int[] numArray = this.modbusClient.ReadInputRegisters(readOrder.StartingAddress, readOrder.Quantity); int index = 0; while (index < numArray.Length) { float num1 = readOrder.Scale != null ? ((double)readOrder.Scale[index] == 0.0 ? 1f : readOrder.Scale[index]) : 1f; if (readOrder.oldvalue[index] == null) { int num2 = (int)this.mqttClient.Publish(readOrder.Topic[index], readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)numArray[index] * num1).ToString()) : Encoding.UTF8.GetBytes(((float)numArray[index] * num1).ToString() + " " + readOrder.Unit[index]), (byte)2, readOrder.Retain != null && readOrder.Retain[index]); readOrder.oldvalue[index] = (object)numArray[index]; } else if ((int)readOrder.oldvalue[index] != numArray[index] && (readOrder.Hysteresis == null || numArray[index] < checked ((int)readOrder.oldvalue[index] - readOrder.Hysteresis[index]) | numArray[index] > checked ((int)readOrder.oldvalue[index] + readOrder.Hysteresis[index]))) { int num2 = (int)this.mqttClient.Publish(readOrder.Topic[index], readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)numArray[index] * num1).ToString()) : Encoding.UTF8.GetBytes(((float)numArray[index] * num1).ToString() + " " + readOrder.Unit[index]), (byte)2, readOrder.Retain != null && readOrder.Retain[index]); readOrder.oldvalue[index] = (object)numArray[index]; } checked { ++index; } } } } catch (Exception ex1) { this.modbusClient.Disconnect(); Thread.Sleep(2000); if (!this.AutomaticReconnect) { throw ex1; } Debug.WriteLine(ex1.StackTrace); if (!this.modbusClient.Connected) { try { this.modbusClient.Connect(); } catch (Exception ex2) { } } } } Thread.Sleep(readOrder.CylceTime); } }
private static void DoMqttStuff() { // nanoFramework socket implementation requires a valid root CA to authenticate with a // this can be supplied to the caller (as it's doing on the code bellow) or the Root CA has to be stored in the certificate store // Root CA for Azure from here: https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c X509Certificate azureRootCACert = new X509Certificate(Resources.GetBytes(Resources.BinaryResources.AzureCAcertificate)); //Create MQTT Client with default port 8883 using TLS protocol MqttClient mqttc = new MqttClient( iotBrokerAddress, 8883, true, azureRootCACert, null, MqttSslProtocols.TLSv1_2); // event when connection has been dropped mqttc.ConnectionClosed += Client_ConnectionClosed; // handler for received messages on the subscribed topics mqttc.MqttMsgPublishReceived += Client_MqttMsgReceived; // handler for publisher mqttc.MqttMsgPublished += Client_MqttMsgPublished; // handler for subscriber mqttc.MqttMsgSubscribed += Client_MqttMsgSubscribed; // handler for unsubscriber mqttc.MqttMsgUnsubscribed += client_MqttMsgUnsubscribed; byte code = mqttc.Connect( deviceID, String.Format("{0}/{1}/api-version=2018-06-30", iotBrokerAddress, deviceID), GetSharedAccessSignature(null, SasKey, String.Format("{0}/devices/{1}", iotBrokerAddress, deviceID), new TimeSpan(24, 0, 0)), false, MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false, "$iothub/twin/GET/?$rid=999", "Disconnected", false, 60 ); if (mqttc.IsConnected) { Trace("subscribing to topics"); mqttc.Subscribe( new[] { "$iothub/methods/POST/#", String.Format("devices/{0}/messages/devicebound/#", deviceID), "$iothub/twin/PATCH/properties/desired/#", "$iothub/twin/res/#" }, new[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE } ); Trace("Sending twin properties"); mqttc.Publish(String.Format("{0}?$rid={1}", twinReportedPropertiesTopic, Guid.NewGuid()), Encoding.UTF8.GetBytes("{ \"Firmware\": \"nanoFramework\"}"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false); Trace("Getting twin properties"); mqttc.Publish(String.Format("{0}?$rid={1}", twinDesiredPropertiesTopic, Guid.NewGuid()), Encoding.UTF8.GetBytes(""), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false); Trace("[MQTT Client] Start to send telemetry"); } int temp = 10; while (mqttc.IsConnected) { // get temperature value... temp = temp + 1; // ...publish it to the broker //Publish telemetry data using AT LEAST ONCE QOS Level mqttc.Publish(telemetryTopic, Encoding.UTF8.GetBytes("{ Temperature: " + temp + "}"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false); Trace(String.Format("{0} [MQTT Client] Sent telemetry {{ Temperature: {1} }}", DateTime.UtcNow.ToString("u"), temp.ToString())); Thread.Sleep(1000 * 60); if (temp > 30) { temp = 10; } } Trace(String.Format("{0} [MQTT Client]" + " is Disconnected", DateTime.UtcNow.ToString("u"))); }
public NetHelper MqttService(string server, int port, string username, string password, string clientId) { mqttClient = new MqttClient(server, port, clientId); mqttClient.Connect(username, password); return this; }
public void connect(String url, string id) { client = new MqttClient(url); client.Connect(id); }
private static void MonitorMqtt () { UTF8Encoding Encoder = new UTF8Encoding (false); bool HasLightValue = false; bool HasMotionValue = false; MqttClient Client = null; try { WaitHandle[] Handles = new WaitHandle[]{ updateLeds, updateAlarm }; while (executing) { try { if (Client == null) { Client = new MqttClient ("iot.eclipse.org", MqttClient.DefaultPort, "LearningIoTController", string.Empty, false); //Client.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal)); Client.Open (); Client.CONNECT (20, true); Client.OnDataPublished += (Sender, e) => { string Topic = e.Topic; if (!Topic.StartsWith ("Clayster/LearningIoT/Sensor/")) return; string s = System.Text.Encoding.UTF8.GetString (e.Data); PhysicalMagnitude Magnitude; bool b; Topic = Topic.Substring (28); switch (Topic) { case "Light": if (PhysicalMagnitude.TryParse (s, out Magnitude) && Magnitude.Unit == "%" && Magnitude.Value >= 0 && Magnitude.Value <= 100) { lightPercent = Magnitude.Value; if (!HasLightValue) { HasLightValue = true; if (HasMotionValue) hasValues = true; } CheckControlRules (); } break; case "Motion": if (!string.IsNullOrEmpty (s) && XmlUtilities.TryParseBoolean (s, out b)) { motion = b; if (!HasMotionValue) { HasMotionValue = true; if (HasLightValue) hasValues = true; } CheckControlRules (); } break; } }; Client.SUBSCRIBE (new KeyValuePair<string, MqttQoS> ("Clayster/LearningIoT/Sensor/#", MqttQoS.QoS1_Acknowledged)); Log.Information ("Listening on MQTT topic Clayster/LearningIoT/Sensor @ ", EventLevel.Minor, Client.Host + ":" + Client.PortNumber.ToString ()); } switch (WaitHandle.WaitAny (Handles, 1000)) { case 0: // Update LEDS int i; lock (synchObject) { i = lastLedMask; } Client.PUBLISH ("Clayster/LearningIoT/Actuator/do", Encoder.GetBytes (i.ToString ()), MqttQoS.QoS1_Acknowledged, true); // Just to synchronize with the other topics. for (int j = 1; j <= 8; j++) { Client.PUBLISH ("Clayster/LearningIoT/Actuator/do" + j.ToString (), Encoder.GetBytes ((i & 1).ToString ()), MqttQoS.QoS1_Acknowledged, true); i >>= 1; } break; case 1: // Update Alarm bool b; lock (synchObject) { b = lastAlarm.Value; } Client.PUBLISH ("Clayster/LearningIoT/Actuator/ao", Encoder.GetBytes (b ? "1" : "0"), MqttQoS.QoS1_Acknowledged, true); if (b) { Thread T = new Thread (SendAlarmMail); T.Priority = ThreadPriority.BelowNormal; T.Name = "SendAlarmMail"; T.Start (); } break; default: // Timeout CheckSubscriptions (30); break; } } catch (ThreadAbortException) { // Don't log. Exception will be automatically re-raised. } catch (Exception ex) { Log.Exception (ex); if (Client != null) { Client.Dispose (); Client = null; } Thread.Sleep(5000); } } } finally { Client.Dispose (); } }
/// <summary> /// Constructor /// </summary> /// <param name="client">Connected client</param> public MqttClientConnectedEventArgs(MqttClient client) { this.Client = client; }