示例#1
1
        public bool MqttConnect(string serveur, string clientid, string username = null, string password = null, bool willRetain = false, byte willQosLevel = 1, bool willFlag = false, string willTopic = null, string willMessage = null, bool cleanSession = true, ushort keepAlivePeriod = 60)
        {
            // create client instance 
            client = new MqttClient(serveur);
            client.MqttMsgSubscribed += Client_MqttMsgSubscribed;
            client.MqttMsgUnsubscribed += Client_MqttMsgUnsubscribed;
            // register to message received 
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            //string clientId = Guid.NewGuid().ToString();
            if (username != null)
            {
                if (willFlag)
                    client.Connect(clientid, username, password, willRetain, willQosLevel, willFlag, willTopic, willMessage, cleanSession, keepAlivePeriod);
                else
                    client.Connect(clientid, username, password);
            }
            else
                client.Connect(clientid);
            //client.Unsubscribe(new string[] { "/#" });


            if (OnConnected != null)
                OnConnected(this, new EventArgs());
            return client.IsConnected;
        }
示例#2
1
        public void TaskRun()
        {
            Trace.t(cc.Norm, "Vision TaskRun started");

            Program.Pilot.Send(new { Cmd = "SRVO", Value = servoPosition });

            if (!Program.PilotString.Contains("com"))
            {
                Mq = new MqttClient(Program.PilotString);
                Trace.t(cc.Norm, string.Format("vision connecting to MQTT @ {0}", Program.PilotString));
                Mq.Connect("MMPXY");
                Trace.t(cc.Norm, "vision connected");

                Mq.MqttMsgPublishReceived += PixyMqRecvd;
                Mq.Subscribe(new string[] { "robot1/pixyCam" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            }

            SubState = VisionState.Run;

            // if finished, exit task
            while (Program.State != RobotState.Shutdown)
            {
                if (SubState == VisionState.Run)
                    if (coneFlag != ConeState.Lost && DateTime.Now > lastSeenTime + lostWaitTime)
                        LostCone();

                Program.Delay(100).Wait();
            }

            Trace.t(cc.Warn, "Vision exiting");
            SubState = VisionState.Idle;
            if (Mq != null && Mq.IsConnected)
                Mq.Disconnect();
        }
示例#3
0
    protected void InitMqtt()
    {
        var client = new uPLibrary.Networking.M2Mqtt.MqttClient(appState.Config.MqttServer, int.Parse(appState.Config.MqttPort), false);

        try
        {
            client.Connect("holoclient");
        }
        catch (Exception e)
        {
            Debug.LogError("Error connecting to mqtt");
        }
        if (client.IsConnected)
        {
            // register to message received
            client.MqttMsgPublishReceived += (sender, e) =>
            {
                UnityMainThreadDispatcher.Instance().Enqueue(() =>
                {
                    var msg = Encoding.UTF8.GetString(e.Message);
                    switch (e.Topic)
                    {
                    case "view":
                        SetView(msg);
                        break;
                    }
                    GameObject _3dText = GameObject.Find("tbTemp");
                    _3dText.GetComponent <TextMesh>().text = msg;
                });
            };

            //// subscribe to the topic "/home/temperature" with QoS 2
            client.Subscribe(new string[] { "view" }, new byte[] { uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
    }
        static void Main(string[] args)
        {
            try
            {
                localClient = new uPLibrary.Networking.M2Mqtt.MqttClient("172.30.28.5");
                string clientId = Guid.NewGuid().ToString();
                localClient.Connect(clientId);

                XmlDocument doc = new XmlDocument();
                doc.Load("\\Users\\Rodric\\Desktop\\values.xml");

                XmlNodeList elementList = doc.GetElementsByTagName("book");
                XmlNode node = elementList[1];

                for (int i = 0; i < elementList.Count; i++)
                {
                    string loc = elementList[i]["location"].InnerText;
                    string temp = elementList[i]["temperature"].InnerText;
                    string time = elementList[i]["time"].InnerText;

                    string allData = loc + ";" + temp + ";" + time;
                    byte[] data = Encoding.UTF8.GetBytes(allData);

                    localClient.Publish("/home/temperature", Encoding.UTF8.GetBytes(allData), uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Connection Failed: " + ex.Message);
            }
        }
示例#5
0
        public static void Main()
        {
            led = new OutputPort(Pins.ONBOARD_LED, false);

            Microsoft.SPOT.Hardware.Utility.SetLocalTime(new DateTime(2014, 4, 13));

            Thread.Sleep(10000);

            var networkInterface = NetworkInterface.GetAllNetworkInterfaces()[0];

            if (networkInterface.IPAddress == IPAddress.Any.ToString())
            {

                networkInterface.EnableDhcp();
                networkInterface.EnableDynamicDns();
                networkInterface.RenewDhcpLease();
            }

            // create client instance
            //MqttClient client = new MqttClient("dev.rabbitmq.com", 1883, false, null);
            MqttClient client = new MqttClient("206.205.188.34", 1883, false, null);

            // register to message received
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            client.MqttMsgSubscribed += client_MqttMsgSubscribed;
            client.MqttMsgUnsubscribed += client_MqttMsgUnsubscribed;
            client.MqttMsgPublished += client_MqttMsgPublished;

            // subscribe to the topic
            client.Subscribe(new string[] { "ABC12345/led" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });

            //Console.ReadLine();
            var state = client.Connect("ABC12345", "guest", "guest", false, 0, false, null, null, true, 60);
        }
示例#6
0
        static void Main(string[] args)
        {
            Console.WriteLine("***********PUBLISHER***********");

            //MqttClient client = new MqttClient("dev.rabbitmq.com", 1883, false, null);
            MqttClient client = new MqttClient("localhost", 1883, false, null);
            var state = client.Connect("Client993", "guest", "guest", false, 0, false, null, null, true, 60);

            string strValue = Convert.ToString("On");

            while (true)
            {
                // publish a message with command to turn LED on
                client.Publish("ABC12345/led", Encoding.UTF8.GetBytes(strValue), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, true);
                mcount++;

                Console.WriteLine(String.Format("Message {0} published.", mcount.ToString()));

                Console.WriteLine("Press enter to send Off command...");
                Console.ReadLine();

                // publish a message with command to turn LED on
                client.Publish("ABC12345/led", Encoding.UTF8.GetBytes("Off"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, true);
                mcount++;

                Console.WriteLine(String.Format("Message {0} published.", mcount.ToString()));

                Console.WriteLine("Press enter to send On comamnd...");
                Console.ReadLine();
            }
        }
示例#7
0
 // Use this for initialization
 void Start()
 {
     client = new MqttClient(MQTT_BROKER_ADDRESS);
     client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
     client.Connect("unity");
     client.Subscribe(new string[] { "doebi/#" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
 }
示例#8
0
 public MqttWorker(string brokerHostname, string[] nodes)
 {
     client = new MqttClient(brokerHostname);
     client.Connect(Guid.NewGuid().ToString());
     client.Subscribe(nodes.Select(n => $"nodes/{n}/packets").ToArray(), nodes.Select(n => MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE).ToArray());
     client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
     WorkerSupportsCancellation = true;
 }
示例#9
0
        public void Setup()
        {
            mqttClient = new MqttClient(IPAddress.Parse(config.AppSettings["MqttHost"]), int.Parse(config.AppSettings["MqttPort"]), false, null);
            mqttClient.MqttMsgPublished += client_MqttMsgPublished;
            mqttClient.Connect(config.AppSettings["MqttClientName"] + "-" + config.AppSettings["MqttPairingCode"], config.AppSettings["MqttUsername"], config.AppSettings["MqttPassword"]);

            lyncxClient = new LyncxClient();
            lyncxClient.AvailabilityChanged += lyncxClient_AvailabilityChanged;

            lyncxClient.Setup();
        }
示例#10
0
 public IOTHub()
 {
     if (client == null)
     {
         // create client instance 
         client = new MqttClient(MQTT_BROKER_ADDRESS);
         string clientId = Guid.NewGuid().ToString();
         client.Connect(clientId, "guest", "guest");
         SubscribeMessage();
     }
 }
示例#11
0
        public static void Main(string[] args)
        {
            MqttClient client = new MqttClient(MQTT_BROKER_ADDRESS);

            // register to message received
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId);

            client.Subscribe(new string[] { "/testit/now" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
示例#12
0
文件: Mqtt.cs 项目: robeat101/beakn
        public void Setup()
        {
            mqttClient = new MqttClient(Config.MqttHost, Config.MqttPort, false, null);
            mqttClient.Connect(Config.MqttClientId, Config.MqttUsername, Config.MqttPassword);

            Console.WriteLine("Connected: " + mqttClient.IsConnected);

            mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            mqttClient.MqttMsgSubscribed += client_MqttMsgSubscribed;

            mqttClient.Subscribe(new string[] { Config.MqttTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
示例#13
0
文件: Form1.cs 项目: ouv27/m2mqtt
        private void Form1_Load(object sender, EventArgs e)
        {
            // create client instance
            MqttClient client = new MqttClient("test.mosquitto.org");

            client.Connect("Test VS",null,null);

             //           string strValue = Convert.ToString(value);

            // publish a message on "/home/temperature" topic with QoS 2
            client.Publish("/home/temperature", Encoding.UTF8.GetBytes("test"));
        }
示例#14
0
        public AdafruitIOClient(string username, string key)
        {
            _username = username;
            _key = key;

            Feed.FeedChanged += OnFeedChanged;

            _client = new MqttClient("io.adafruit.com", 1883, false, MqttSslProtocols.None);
            _client.MqttMsgPublishReceived += OnMessageReceived;

            _client.Connect(Guid.NewGuid().ToString(), _username, _key);
        }
示例#15
0
        public static void Main()
        {
            netduino = NetduinoFactory.Get(config.AppSettings["LedPinType"]);
            netduino.Setup();

            mqttClient = new MqttClient(IPAddress.Parse(config.AppSettings["MqttHost"]), int.Parse(config.AppSettings["MqttPort"]), false, null);
            mqttClient.Connect(config.AppSettings["MqttClientName"] + "-" + config.AppSettings["MqttPairingCode"], config.AppSettings["MqttUsername"], config.AppSettings["MqttPassword"]);

            mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            mqttClient.MqttMsgSubscribed += client_MqttMsgSubscribed;

            mqttClient.Subscribe(new string[] { config.AppSettings["MqttTopic"] + config.AppSettings["MqttPairingCode"] }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
        }
示例#16
0
    private void Start()
    {
        mqttClient = new MqttClient(mqttBrokerHost);
        mqttClient.MqttMsgPublishReceived += HandleClientMqttMsgPublishReceived;

        String clientId = Guid.NewGuid().ToString();

        mqttClient.Connect(clientId);

        string[] topics = { mqttTopic };
        byte[]   qualityOfServiceLevels = { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE };
        mqttClient.Subscribe(topics, qualityOfServiceLevels);
    }
        public bool MqttConnect(string serveur, string clientid)
        {
            // create client instance 
            client = new MqttClient(serveur);

            // register to message received 
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            //string clientId = Guid.NewGuid().ToString();
            client.Connect(clientid);
            if (OnConnected != null)
                OnConnected(this, new EventArgs());
            return client.IsConnected;
        }
        public bool MqttConnect(string serveur, string clientid, string username, string password, bool willRetain, byte willQosLevel, bool willFlag, string willTopic, string willMessage, bool cleanSession, ushort keepAlivePeriod)
        {
            // create client instance 
            client = new MqttClient(serveur);

            // register to message received 
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            //string clientId = Guid.NewGuid().ToString();
           var res= client.Connect(clientid,  username,  password,  willRetain,  willQosLevel,  willFlag,  willTopic,  willMessage,  cleanSession,  keepAlivePeriod);
            if (OnConnected != null)
                OnConnected(this, new EventArgs());
            return client.IsConnected ;
        }
        public SenderIOT()
        {
            clientPub = new MqttClient(ipAddress, brokerPort, false, caCert, sslProtocol);
            clientIdPub = Guid.NewGuid().ToString();
            try
            {
                clientPub.Connect(clientIdPub);
            }
            catch (Exception)
            {

            }
        }
示例#20
0
        public static void Main()
        {
            netduino = NetduinoFactory.Get(ConfigurationManager.LedPinType);
            netduino.Setup();

            mqttClient = new MqttClient(ConfigurationManager.MqttHost, ConfigurationManager.MqttPort, false, null);
            mqttClient.Connect(ConfigurationManager.MqttClientId, ConfigurationManager.MqttUsername, ConfigurationManager.MqttPassword);

            mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            mqttClient.MqttMsgSubscribed += client_MqttMsgSubscribed;

            mqttClient.Subscribe(new string[] { ConfigurationManager.MqttTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
示例#21
0
        private static void ConnectSubscribe(string APIKEY, string FEEDID)
        {
            var ip = System.Net.IPAddress.Parse("216.52.233.120"); //this is api.xively.com ...

            var mqc = new MqttClient(ip);
            mqc.Connect(APIKEY);

            byte[] qosleve = new byte[1];
            qosleve[0] = 0;
            mqc.Subscribe(new string[] { APIKEY + FEEDID }, qosleve);

            mqc.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(mqc_MqttMsgPublishReceived);
        }
示例#22
0
    // Use this for initialization
    void Start()
    {
        // create client instance
        client = new MqttClient("vps.provolot.com", 1883 , false , null );

        // 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[] { "hello/world" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
    }
        public SenderIOT(string ipAddress, int brockerPort)
        {
            this.ipAddress = ipAddress;
            this.brokerPort = brockerPort;
            clientPub = new MqttClient(ipAddress, brokerPort, false, caCert, sslProtocol);
            clientIdPub = Guid.NewGuid().ToString();
            try
            {
                clientPub.Connect(clientIdPub);
            }
            catch (Exception)
            {

            }
        }
示例#24
0
 private void connectBtn_Click(object sender, RoutedEventArgs e)
 {
     string clientId = Guid.NewGuid().ToString();
     try
     {
         client = new MqttClient(brokerTB.Text);
         client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
         client.Connect(clientId);
         statusTB.Text = "Successfully connected to Broker";
     }
     catch (Exception ex)
     {
         statusTB.Text = ex.Message;
     }
 }
示例#25
0
        protected override void OnStart(string[] args)
        {
            t = new Timer(10000); // Timer de 10 secondes.
            t.Elapsed += new ElapsedEventHandler(t_Elapsed);
            t.Start();
            // create client instance
            MqttClient client = new MqttClient("test.mosquitto.org");

            client.Connect("SMO_IoT_WindowsService", null, null);
            // publish a message on "/home/temperature" topic with QoS 2
            IoT_Topics iot = new IoT_Topics();
            Iot_Constants IOTCONST = new Iot_Constants();
            string sTopic = iot.Get_Topics("", "");
            client.Publish("ou", Encoding.UTF8.GetBytes(sTopic));
        }
示例#26
0
        public static void FireEvent()
        {
            var client = new MqttClient("mqtt.bconimg.com");

            // register to message received
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

            var clientId = Guid.NewGuid().ToString();

            client.Connect(clientId);

            // subscribe to the topic "/home/temperature" with QoS 2
            client.Subscribe(
                new string[] { "merge01" },
                new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
示例#27
0
        static void Main(string[] args)
        {
            // create client instance
            uPLibrary.Networking.M2Mqtt.MqttClient client = new uPLibrary.Networking.M2Mqtt.MqttClient(Properties.Settings.Default.BrokerIP);

            // 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[] { "#" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            //client.Publish("ct/1/temp", Encoding.UTF8.GetBytes("20"));
        }
示例#28
0
        static void Main(string[] args)
        {
            // create client instance
            MqttClient client = new MqttClient(IPAddress.Parse("54.94.232.13"));
            client.ProtocolVersion = MqttProtocolVersion.Version_3_1;

            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId, "hack", "12345");

            string[] topic = { "presenca" };
            byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE };
            client.Subscribe(topic, qosLevels);

            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

            Console.WriteLine("Aguardando requisições...");
        }
        public MainPage()
        {
            this.InitializeComponent();

            disconnected();

            _mqtt = new MqttClient("m11.cloudmqtt.com", 12360, false, MqttSslProtocols.None);
            _mqtt.ConnectionClosed += (sender, args) => { disconnected(); };
            _mqtt.MqttMsgSubscribed += (sender, args) =>
            {
                connected();
            };
            _mqtt.MqttMsgPublishReceived += (sender, args) =>
                            {
                var msg = Encoding.ASCII.GetString(args.Message);

                switch (msg)
                {
                    case "happy":
                        {
                        }
                        break;
                    case "sad":
                    {
                    }
                        break;
                    case "indifferent":
                        {
                        }
                        break;
                }
            };

            Task.Run(() =>
            {
                try
                {
                    _mqtt.Connect("1", "mike", "cloudmqtt");
                    _mqtt.Subscribe(new[] {"mqttdotnet/pubtest/#"}, new[] {MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE});
                }
                catch (Exception ex)
                {

                }
            });
        }
示例#30
0
        /// <summary>
        /// 브로커 접속 테스트
        /// </summary>
        /// <param name="BrokerIP">브로커 주소</param>
        /// <param name="ClientID">클라이언트 ID</param>
        /// <returns>테스트 결과</returns>
        public static bool Test(string BrokerIP, string ClientID)
        {
            bool ret = false;

            try
            {
                var client = new uPLibrary.Networking.M2Mqtt.MqttClient(BrokerIP);
                if (client.Connect(ClientID) == 0)
                {
                    ret = true;
                    System.Threading.Thread.Sleep(500);
                    client.Disconnect();
                }
            }
            catch (Exception) { }
            return(ret);
        }
示例#31
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            m_Deferral = taskInstance.GetDeferral();
            taskInstance.Canceled += TaskInstanceCanceled;

            // initialize I2C
            var i2cSettings = new I2cConnectionSettings(TSL2561.Address)
            {
                BusSpeed = I2cBusSpeed.FastMode,
                SharingMode = I2cSharingMode.Shared,
            };
            var selector = I2cDevice.GetDeviceSelector(m_DeviceSelector);
            var deviceInformation = await DeviceInformation.FindAllAsync(selector);
            m_Device = await I2cDevice.FromIdAsync(deviceInformation[0].Id, i2cSettings);

            // initialize sensor
            m_Sensor = new TSL2561(m_Device);
            m_Sensor.SetTiming(m_Gain, m_Timing);
            m_Sensor.PowerUp();

            // initialize MQTT
            try
            {
                m_Client = new MqttClient(m_Host);
                m_Client.Connect(m_ClientId);
            }
            catch (MqttConnectionException ex)
            {
                // ignore connection exception and retry to connect later
                Debug.WriteLine("Cannot connect to MQTT broker: " + ex.Message);
                m_Client = null;
            }

            var appService = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            if (appService != null && appService.Name == m_ServiceName)
            {
                m_AppServiceConnection = appService.AppServiceConnection;
                m_AppServiceConnection.RequestReceived += OnRequestReceived;
            }

            m_Client.Publish(m_ServiceTopic, Encoding.UTF8.GetBytes(DateTime.Now.ToUniversalTime().ToString("O")), m_QoS, true);

            // start timer
            m_Timer = new Timer(LuxProvider, null, m_TimerDueTime, m_TimerInterval);
        }
示例#32
0
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                MqttClient client = new MqttClient("m20.cloudmqtt.com:18478");
                byte code = client.Connect("MyClient_MQTT", "xzofiqbg", "igNpeCm_8j6f");
                client.MqttMsgPublished += client_MqttMsgPublished;
                ushort msgId = client.Publish("/my_topic", // topic
                              Encoding.UTF8.GetBytes("MyMessageBody"), // message body
                              MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, // QoS level
                              false); // retained

            }
            catch
            {
                textBox1.Text = "Erreur catch";
            }
        }
        private void initMqtt()
        {
            client = new MqttClient(MQTT_BROKER_ADDRESS);
            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId);
            //subscribe
            client.MqttMsgPublishReceived += async (sender, e) =>
            {

                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    var gpio = GpioController.GetDefault();
                    // Show an error if there is no GPIO controller
                    if (gpio == null)
                    {
                        GpioStatus.Text = "There is no GPIO controller on this device.";
                        return;
                    }
                    string Message = new string(Encoding.UTF8.GetChars(e.Message));
                    if (Message.IndexOf(":") < 1) return;
                   // handle message received 
                   TxtMsg.Text = "Message Received : " + Message;
                   //switch gpio state
                   string[] pinItem = Message.Split(':');
                    int pinsel = Convert.ToInt32(pinItem[0]);
                    GpioPinValue state = pinItem[1] == "True" ? GpioPinValue.High : GpioPinValue.Low;
                    if (pins.ContainsKey(pinsel)) {
                        pins[pinsel].Write(state);
                    }
                    else {
                        var pin = gpio.OpenPin(pinsel);
                        pin.Write(state);
                        pin.SetDriveMode(GpioPinDriveMode.Output);
                        pins.Add(pinsel, pin);
                    }
                    devices[pinsel] = (state == GpioPinValue.High ? true : false);
                    GpioStatus.Text = string.Format("PIN {0} -> {1}", pinsel, state == GpioPinValue.High ? "ON" : "OFF");

                });
            };
            client.Subscribe(new string[] { "/raspberry/control" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });

        }
        static void Main(string[] args)
        {
            try
            {
                    MqttClient client = new MqttClient("172.30.28.5");

                    client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

                    string clientId = Guid.NewGuid().ToString();
                    client.Connect(clientId);

                    //client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
                    client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            }
            catch(Exception ex)
            {
                Console.WriteLine("Failed to connect: " + ex.Message);
            }
        }
示例#35
0
        static void Main(string[] args)
        {
            // Azure IoT Hub
            const string IoTHubName = "[Azure IoT Suite IoT Hub URI]"; // azure iot suite

            // Azure IoT gateway (MQTT broker)
            const string GatewayHost = "[IP Address Azure Iot Protocol Gateway]";
            const int GatewayMqttPort = 8883;

            // device/client information
            const string DeviceId = "[DeviceId in Azure IoT Suite]";
            const string DeviceKey = "[DeviceKey in Azure IoT Suite]"; // azure iot suite

            string Username = string.Format("{0}/{1}", IoTHubName, DeviceId);
            string Password = CreateSharedAccessSignature(DeviceId, DeviceKey, IoTHubName);

            // define topics
            TopicDevice2Service = string.Format("devices/{0}/messages/events", DeviceId);

            try
            {
                // ignore any TLS errors
                client = new MqttClient(GatewayHost, GatewayMqttPort, true, MqttSslProtocols.TLSv1_0, (sender, certificate, chain, errors) => true, null);
                client.Connect(DeviceId, Username, Password);

                // initialize the new physical device on Azure IoT Suite
                InitializeDevice(DeviceId);

                // send fake telemtry data
                var rand = new Random();
                Console.Write("Press ENTER to start sending telemetry data"); Console.ReadKey();
                while (true)
                {
                    SendTelemetryData(DeviceId, rand.Next(10, 60), rand.Next(10, 60));
                    System.Threading.Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
示例#36
0
        public override async Task InitializeAsync(DevicePluginConfigurationModel configuration)
        {
            await base.InitializeAsync(configuration);

            try
            {
                _deviceid = configuration.Properties["DeviceId"];
                string deviceSas     = configuration.Properties["DeviceSas"];
                string iotHubAddress = configuration.Properties["IotHubAddress"];
                int    iotHubPort    = Int32.Parse(configuration.Properties["IotHubPort"]);

                // init mqtt client
                _mqttclient = new uPLibrary.Networking.M2Mqtt.MqttClient(iotHubAddress, iotHubPort, true, MqttSslProtocols.TLSv1_2);
                _mqttclient.ConnectionClosed += MqttclientOnConnectionClosed;
                _mqttclient.Connect(_deviceid, $"{iotHubAddress}/{_deviceid}/api-version=2016-11-14", deviceSas);
                _mqttclient.Subscribe(new[] { $"devices/{_deviceid}/messages/devicebound/#" }, new byte[] { 0 });
                _mqttclient.Subscribe(new[] { "$iothub/methods/POST/#" }, new byte[] { 0 });
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                //TODO Log
            }
        }
示例#37
0
        static int Main(string[] args)
        {
            if (args.Any() && args[0] == "TestMode")
            {
                var client = new MqttClient("localhost");
                client.MqttMsgPublishReceived += (s, m) =>
                {
                    Console.WriteLine($"Publish Recieved: {m.Topic} \t {Encoding.ASCII.GetString(m.Message)}");
                };

                client.MqttMsgPublished += (s, m) =>
                {
                    Console.WriteLine("Message Published");
                };

                client.ConnectionClosed += (s, m) =>
                {
                    Console.WriteLine("Connection Closed");
                };

                client.MqttMsgSubscribed += (s, m) =>
                {
                    Console.WriteLine("Message Subscribed");
                };

                client.MqttMsgUnsubscribed += (s, m) =>
                {
                    Console.WriteLine("Message Unsubscribed");
                };

                client.Reconnected += (s, m) =>
                {
                    Console.WriteLine("Reconnected");
                };

                client.Connected += (s, m) =>
                {
                    Console.WriteLine("Connected");
                };

                client.Connected += (s, m) =>
                {
                    Console.WriteLine("I am a fruitcake");
                };

                client.Disconnected += (s, m) =>
                {
                    Console.WriteLine("Disconnected");
                };

                client.Event += (s, m) =>
                {
                    var t = "{\r\n";
                    var q = m.Dict.Select((a) => $"\t\"{a.Key}\" : \"{a.Value}\"");
                    t += String.Join(",\r\n", q);
                    t += "\r\n}";
                    Console.WriteLine(t);
                };

                //client.shouldReconnect = false;
                client.Connect();

                Console.ReadKey();
                Console.WriteLine("Begin attempt publish");
                var do_the_thing = true;
                new Thread(() =>
                {
                    while (do_the_thing)
                    {
                        client.Publish("/banana", Encoding.ASCII.GetBytes("I am a fish"));
                        Thread.Sleep(1000);
                    }
                }).Start();

                Console.ReadKey();
                Console.WriteLine("subscribe to banana");
                client.AddTopic(new Topic.Topic("/banana"));
                Console.ReadKey();
                Console.WriteLine("subscribe to fig");
                client.AddTopic(new Topic.Topic("/fig"));
                Console.ReadKey();
                Console.WriteLine("unsubscribe from fig");
                client.RemoveTopic("/fig");
                Console.ReadKey();
                do_the_thing = false;
                client.Disconnect();
            }
            return(0);
        }