public ExternalDoorController(IMqtt mqttService, ILogger logger,string houseCode, string deviceCode)
 {
     _logger = logger;
     _mqttService = mqttService;
     _houseCode = houseCode;
     _deviceCode = deviceCode;
 }
Example #2
0
        Program(string appkey)
        {
            Console.WriteLine("Initialize the client with the appkey: " + appkey + "\n");

            try
            {
                // Instantiate client using MqttClientFactory with appkey
                _client = MqttClientFactory.CreateClientWithAppkey(appkey);
            }
            catch (Exception)
            {
                Console.WriteLine("Instantiate the client failed. Please check your network and app key, then try it again.");
                Environment.Exit(0);
            }

            // Enable auto reconnect
            _client.AutoReconnect = true;

            // Setup some useful client delegate callbacks
            _client.Connected      += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
            _client.Published      += new CompleteDelegate(_client_Published);
            _client.Subscribed     += new CompleteDelegate(_client_Subscribed);
            _client.Unsubscribed   += new CompleteDelegate(_client_Unsubscribed);
        }
Example #3
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init ();

            // Code for starting up the Xamarin Test Cloud Agent
            #if ENABLE_TEST_CLOUD
            Xamarin.Calabash.Start();
            #endif

            MqttClient.Ios.Bootstrapper.Setup ();

            LoadApplication (new App ());

            var connectionString = Keys.MQTT_BROKER_CONNECTION;
            var clientId = "iphone";

            // Instantiate client using MqttClientFactory
            _client = MqttClientFactory.CreateClient(connectionString, clientId);

            // Setup some useful client delegate callbacks
            _client.Connected += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate (client_PublishArrived);

            _client.Connect ();
            _client.Subscribe (
                new Subscription[] {
                    new Subscription ("/status", QoS.BestEfforts),
                    new Subscription ("/cmd", QoS.BestEfforts),
                    new Subscription ("/event", QoS.BestEfforts),

                });

            return base.FinishedLaunching (app, options);
        }
Example #4
0
        public FrmMqttMain(IMqtt mqtt, IMqttPublish mqttPublish, MainFormContainer mainFormContainer)
        {
            _mqtt        = mqtt;
            _mqttPublish = mqttPublish;

            mainFormContainer.MainForm = this;

            try
            {
                InitializeComponent();
                Version version = Assembly.GetExecutingAssembly().GetName().Version;
                toolStripStatusLabel2.Text = "";

                Properties.Settings.Default.Upgrade();


                notifyIcon1.Visible        = false;
                notifyIcon1.Text           = NotifyIconText;
                notifyIcon1.BalloonTipText = NotifyIconBalloonTipText;
                notifyIcon1.ShowBalloonTip(NotifyIconBalloonTipTimer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            lblConnected.Text = "Disconnected";
            _mqttClient = MqttClientFactory.CreateClient("tcp://m11.cloudmqtt.com:12360", Guid.NewGuid().ToString(), "mike", "cloudmqtt");
            _mqttClient.Connected += (object sender, EventArgs e) => {

                InvokeOnMainThread(() =>
                {
                    var subscription = new Subscription("mqttdotnet/pubtest", QoS.BestEfforts);
                    _mqttClient.Subscribe(subscription);
                    setConneectedState();
                });
            };
            _mqttClient.ConnectionLost += (object sender, EventArgs e) => {
                InvokeOnMainThread(() => {
                    setDisconnectedState();
                });
            };
            _mqttClient.Subscribed += _mqttClient_Subscribed;
            _mqttClient.Unsubscribed += _mqttClient_Unsubscribed;
            _mqttClient.PublishArrived += _mqttClient_PublishArrived;

            _mqttClient.Connect();
        }
Example #6
0
        Program(string appkey)
        {
            Console.WriteLine("Initialize the client with the appkey: " + appkey + "\n");

            try
            {
                // Instantiate client using MqttClientFactory with appkey
                _client = MqttClientFactory.CreateClientWithAppkey(appkey);
            }
            catch(Exception)
            {
                Console.WriteLine("Instantiate the client failed. Please check your network and app key, then try it again.");
                Environment.Exit(0);
            }

            // Enable auto reconnect
            _client.AutoReconnect = true;

            // Setup some useful client delegate callbacks
            _client.Connected += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
            _client.Published += new CompleteDelegate(_client_Published);
            _client.Subscribed += new CompleteDelegate(_client_Subscribed);
            _client.Unsubscribed += new CompleteDelegate(_client_Unsubscribed);
        }
        public AlarmPanelController(IMqtt mqttService, ILogger logger,string houseCode, string locationCode)
        {
            _logger = logger;
            _mqttService = mqttService;
            _houseCode = houseCode;
            _locationCode = locationCode;

            // Setup the timer that turns off the onboard led after a length of time
            _pingResponseTimer = new Timer(new TimerCallback(OnPingResponseTimer), this._pingResponseOutput, Timeout.Infinite, Timeout.Infinite);

            // Setup the timer that flashes the LED when the code is invalid
            _invalidCodeFlashLEDTimer = new Timer(new TimerCallback(OnFlashLEDTimer), this._invalidCodeLED, Timeout.Infinite, Timeout.Infinite);

            // Setup the interrupt handler to detect when the windows opened or closed
            _windowCircuit.StateChanged += new AutoRepeatEventHandler(_windowCircuit_StateChanged);

            // Setup the interrupt handler to detect when the motion detector opened or closed
            _motionCircuit.StateChanged += new AutoRepeatEventHandler(_motionCircuit_StateChanged);

            // Setup the interrupt handlers that detect when a keypad key is depressed
            _keyboard0Key.StateChanged += new AutoRepeatEventHandler(_keyboard0Key_StateChanged);
            _keyboard1Key.StateChanged += new AutoRepeatEventHandler(_keyboard1Key_StateChanged);
            _keyboardEnterKey.StateChanged += new AutoRepeatEventHandler(_keyboardEnterKey_StateChanged);

            // Setup the interrupt handlers that detect when the sleep button is pressed
            _sleepMode.StateChanged += new AutoRepeatEventHandler(_sleepMode_StateChanged);

            // Setup the interrupt handlers that detect when the alarm button is pressed
            _awayMode.StateChanged += new AutoRepeatEventHandler(_awayMode_StateChanged);
        }
Example #8
0
 public bool Connect(string connString, string clientId, ushort keepAlive,
                     string username          = null, string password = null,
                     IPersistence persistence = null)
 {
     try
     {
         mqtt = MqttClientFactory.CreateClient(connString, clientId,
                                               username, password, persistence);
         mqtt.KeepAliveInterval = keepAlive;
         if (withWill)
         {
             mqtt.Connect(willTopic, willQos,
                          new MqttPayload(willMessage), willRetained, cleanSession);
         }
         else
         {
             mqtt.Connect(cleanSession);
         }
         mqtt.Connected      += Mqtt_Connected;
         mqtt.PublishArrived += Mqtt_PublishArrived;
         mqtt.Published      += Mqtt_Published;
         mqtt.Subscribed     += Mqtt_Subscribed;
         mqtt.Unsubscribed   += Mqtt_Unsubscribed;
         mqtt.ConnectionLost += Mqtt_ConnectionLost;
         return(true);
     }
     catch (Exception m_ex)
     {
         return(false);
     }
 }
 public DoorBellController(IMqtt mqttService, ILogger logger, string houseCode, string locationCode)
 {
     _logger = logger;
     _mqttService = mqttService;
     _houseCode = houseCode;
     _locationCode = locationCode;
 }
        public MasterControlPanel(IMqtt client)
        {
            _client = client;
            _giveMeTimeToEnterTimer = new Timer(1000);
            _giveMeTimeToEnterTimer.Enabled = false;
            _giveMeTimeToEnterTimer.Elapsed += _giveMeTimeToEnterTimer_Elapsed;

            _giveMeTimeToExitTimer = new Timer(1000);
            _giveMeTimeToExitTimer.Enabled = false;
            _giveMeTimeToExitTimer.Elapsed += _giveMeTimeToExitTimer_Elapsed;

            _turnOffDoorbellIndicatorTimer = new Timer(3000);
            _turnOffDoorbellIndicatorTimer.Enabled = false;
            _turnOffDoorbellIndicatorTimer.Elapsed += _turnOffDoorbellIndicatorTimer_Elapsed;

            _sensors.Add(new SecuritySensor { HouseCode = "house1", DeviceCode = "externaldoor", LocationCode = "front", Sensor = "door", SensorValue = "closed" });
            _sensors.Add(new SecuritySensor { HouseCode = "house1", DeviceCode = "externaldoor", LocationCode = "side", Sensor = "door", SensorValue = "closed" });
            _sensors.Add(new SecuritySensor { HouseCode = "house1", DeviceCode = "externaldoor", LocationCode = "back", Sensor = "door", SensorValue = "closed" });
            _sensors.Add(new SecuritySensor { HouseCode = "house1", DeviceCode = "alarmpanel", LocationCode = "firstfloor", Sensor = "window", SensorValue = "closed" });
            _sensors.Add(new SecuritySensor { HouseCode = "house1", DeviceCode = "alarmpanel", LocationCode = "firstfloor", Sensor = "motion", SensorValue = "closed" });
            _sensors.Add(new SecuritySensor { HouseCode = "house1", DeviceCode = "alarmpanel", LocationCode = "masterbedroom", Sensor = "window", SensorValue = "closed" });
            _sensors.Add(new SecuritySensor { HouseCode = "house1", DeviceCode = "alarmpanel", LocationCode = "bedroom1", Sensor = "window", SensorValue = "closed" });
            _sensors.Add(new SecuritySensor { HouseCode = "house1", DeviceCode = "alarmpanel", LocationCode = "bedroom2", Sensor = "window", SensorValue = "closed" });

            _lockState.Add(new SecurityActuator { HouseCode = "house1", DeviceCode = "externaldoor", LocationCode = "front", Actuator = "lock", ActuatorValue = "unlocked" });
            _lockState.Add(new SecurityActuator { HouseCode = "house1", DeviceCode = "externaldoor", LocationCode = "back", Actuator = "lock", ActuatorValue = "unlocked" });
            _lockState.Add(new SecurityActuator { HouseCode = "house1", DeviceCode = "externaldoor", LocationCode = "side", Actuator = "lock", ActuatorValue = "unlocked" });

            _alarmHornState.Add(new SecurityActuator { HouseCode = "house1", DeviceCode = "alarmpanel", LocationCode = "masterbedroom", Actuator = "burglar", ActuatorValue = "off" });
            _alarmHornState.Add(new SecurityActuator { HouseCode = "house1", DeviceCode = "alarmpanel", LocationCode = "bedroom1", Actuator = "burglar", ActuatorValue = "off" });
            _alarmHornState.Add(new SecurityActuator { HouseCode = "house1", DeviceCode = "alarmpanel", LocationCode = "bedroom2", Actuator = "burglar", ActuatorValue = "off" });
            _alarmHornState.Add(new SecurityActuator { HouseCode = "house1", DeviceCode = "alarmpanel", LocationCode = "firstfloor", Actuator = "burglar", ActuatorValue = "off" });
        }
Example #11
0
        void Run()
        {
            ColetorTopicoLog ctlm = new ColetorTopicoLog();

            ctlm.Id_ColetorTopico = 1;
            ctlm.DataHora         = getData();
            ctlm.Valor            = "RunInicio";
            db.ColetorTopicoLog.Add(ctlm);
            db.SaveChanges();

            /*
             * client.username_pw_set("","ESQXpO-H7-1y")
             * client.connect("m14.cloudmqtt.com", 11718, 60)
             *
             */
            // string connectionString = "mqtt://m13.cloudmqtt.com:12644";
            string connectionString = "tcp://m14.cloudmqtt.com:11718";

            // Instantiate client using MqttClientFactory
            //_client = MqttClientFactory.CreateClient(connectionString, "aneuk", "clpfcosb", "ILo_4ucaK3P_");
            _client = MqttClientFactory.CreateClient(connectionString, "aneuk", "fgwuwgpw", "ESQXpO-H7-1y");
            // Setup some useful client delegate callbacks
            _client.Connected      += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
            //
            ColetorTopicoLog ctlm2 = new ColetorTopicoLog();

            ctlm2.Id_ColetorTopico = 1;
            ctlm2.DataHora         = getData();
            ctlm2.Valor            = "RunFim";
            db.ColetorTopicoLog.Add(ctlm2);
            db.SaveChanges();
            Start();
        }
Example #12
0
 private void MQTT_TEST(string connectionString, string clientId, string username, string password)
 {
     _client                 = MqttClientFactory.CreateClient(connectionString, clientId, username, password);
     _client.Connected      += new ConnectionDelegate(client_Connected);
     _client.ConnectionLost += new ConnectionDelegate(client_ConnectionLost);
     _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
     _client.PublishArrived += _client_PublishArrived;
 }
Example #13
0
 public MQTTManager(string connectionString, string clientId, string userName, string password)
 {
     this._connectionString       = connectionString;
     this._clientId               = clientId;
     this._client                 = MqttClientFactory.CreateClient(connectionString, _clientId, userName, password);
     this._client.Connected      += new ConnectionDelegate(client_Connected);
     this._client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
     this._client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
 }
Example #14
0
        //
        Program()
        {
            string connectionString = "tcp://m16.cloudmqtt.com:14106";

            _client                 = MqttClientFactory.CreateClient(connectionString, "useracl", "username", "password");
            _client.Connected      += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
        }
Example #15
0
        private void ConnectToBroker()
        {
            if (Servers.SelectedIndex < 0)
            {
                ShowSettingsPage();
                return;
            }
            if (_clientConnected)
            {
                return;
            }

            Settings settings = Settings.LoadSettings(Servers.Items[Servers.SelectedIndex]);

            if (!settings.EnableControls)
            {
                return;
            }
            IWifi wifi = new Wifi();

            string server = wifi.GetSSID() == $"\"{settings.LocalSSID}\""
                ? settings.LocalServerName
                : settings.RemoteServerName;

            string connectionString = $"tcp://{server}:{settings.MqttPort}";

            Device.BeginInvokeOnMainThread(() =>
            {
                if (!string.IsNullOrEmpty(settings.Username))
                {
                    client = MqttClientFactory.CreateClient(connectionString, Guid.NewGuid().ToString(), settings.Username,
                                                            settings.Password);
                }
                else
                {
                    client = MqttClientFactory.CreateClient(connectionString, Guid.NewGuid().ToString());
                }

                client.Connected      += ClientConnected;
                client.ConnectionLost += ClientConnectionLost;
                client.PublishArrived += ClientPublishArrived;

                IDeviceInfo device = new DeviceInfo();
                string name        = device.GetName();

                try
                {
                    client.Connect("car/DISCONNECT", QoS.BestEfforts, new MqttPayload(name), false, true);
                }
                catch (Exception ex)
                {
                    Toaster(ex.Message, ToastPriority.Critical, ToastLength.Long);
                    _clientConnected = false;
                }
            });
        }
 void ProgramSetup(string connectionString, string clientId, string username, string password)
 {
     // Instantiate client using MqttClientFactor
     _client = MqttClientFactory.CreateClient(connectionString, clientId, username, password);
     // Setup some useful client delegate callbacks
     _client.Connected      += new ConnectionDelegate(client_Connected);
     _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
     _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
     //textBoxIncomming.Text = e.Payload;
 }
Example #17
0
        Program(string connectionString, string clientId)
        {
            // Instantiate client using MqttClientFactory
            _client = MqttClientFactory.CreateClient(connectionString, clientId);

            // Setup some useful client delegate callbacks
            _client.Connected += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
        }
Example #18
0
        Program(string connectionString, string clientId)
        {
            // Instantiate client using MqttClientFactory
            _client = MqttClientFactory.CreateClient(connectionString, clientId);

            // Setup some useful client delegate callbacks
            _client.Connected      += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
        }
        Program(string clientId)
        {
            var connectionString = "tcp://fantastic-teacher.cloudmqtt.com:1883";

            _client = MqttClientFactory.CreateClient(connectionString, clientId, "gnztvlsa", "CZbmTTBjvd8f");
            // Setup some useful client delegate callbacks
            _client.Connected      += client_Connected;
            _client.ConnectionLost += _client_ConnectionLost;
            _client.PublishArrived += client_PublishArrived;
        }
Example #20
0
        private void OpenMqtt()
        {
            client = MqttClientFactory.CreateClient(connectionString, clientId);
            client.Connect(true);

            client.Connected      += new ConnectionDelegate(client_Connected);
            client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
            client.Published      += new CompleteDelegate(_client_Published);
        }
        public AlarmController(IMqtt mqttService, ILogger logger,string houseCode, string locationCode)
        {
            _logger = logger;
            _mqttService = mqttService;
            _houseCode = houseCode;
            _locationCode = locationCode;

            // Setup the timer to wait forever
            _burglarAlarmTimer = new Timer(new TimerCallback(OnTimer), this._burglarAlarmOutput, Timeout.Infinite, Timeout.Infinite);

            _pingResponseTimer = new Timer(new TimerCallback(OnPingResponseTimer), this._pingResponseOutput, Timeout.Infinite, Timeout.Infinite);
        }
        /// <summary>
        /// Execute start up tasks
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            m_client = MqttClientFactory.CreateClient("tcp://192.168.0.50:1883", "MQTTKinect");
            m_client.Connect(cleanStart: true);
            m_client.Publish("text", "Kinect 2.0 just loaded!", QoS.BestEfforts, false);
            timer = System.DateTimeOffset.Now.AddSeconds(0.1f);

            if (this.bodyFrameReader != null)
            {
                this.bodyFrameReader.FrameArrived += this.Reader_FrameArrived;
            }
        }
        public DoorBellController(IMqtt mqttService, ILogger logger, string houseCode, string locationCode)
        {
            _logger = logger;
            _mqttService = mqttService;
            _houseCode = houseCode;
            _locationCode = locationCode;

            // Setup the timer to wait forever
            _pingResponseTimer = new Timer(new TimerCallback(OnPingResponseTimer), this._pingResponseOutput, Timeout.Infinite, Timeout.Infinite);
            _doorbellFrontTimer = new Timer(new TimerCallback(OnDoorbellFrontTimer), this._doorbellFrontOutput, Timeout.Infinite, Timeout.Infinite);
            _doorbellBackTimer = new Timer(new TimerCallback(OnDoorbellBackTimer), this._doorbellBackOutput, Timeout.Infinite, Timeout.Infinite);
            _doorbellSideTimer = new Timer(new TimerCallback(OnDoorbellSideTimer), this._doorbellSideOutput, Timeout.Infinite, Timeout.Infinite);
        }
        public void Connect(string clientId)
        {
            // Instantiate client using MqttClientFactory
            this._clientId = clientId;
            this._client   = MqttClientFactory.CreateClient(this._connectionString, this._clientId, this._authMode, this._authToken);

            // Setup some useful client delegate callbacks
            this._client.Connected      += new ConnectionDelegate(client_Connected);
            this._client.ConnectionLost += new ConnectionDelegate(client_ConnectionLost);
            this._client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);

            //instantiating the connection
            _client.Connect(true);
        }
Example #25
0
    // Use this for initialization
    protected void Start()
    {
        Debug.Log("Starting");
        // Instantiate client using MqttClientFactory
        _client = MqttClientFactory.CreateClient(ConnectionString, ClientId, UserName, Password);

        Debug.Log(_client);
        // Setup some useful client delegate callbacks
        _client.Connected      += new ConnectionDelegate(client_Connected);
        _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
        _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);

        Debug.Log("Connecting......");
        _client.Connect();
    }
Example #26
0
 protected override void LibUpadteThread(Object state)
 {
     try {
         if (this.mqtt.IsConnected)
         {
             if (state.GetType().HasInterface(typeof(IMqtt)))
             {
                 IMqtt sensor = state as IMqtt;
                 ((ADataBackend)this.mqtt).Send("lora/" + sensor.MqttTopic(), sensor.ToJson());
                 this.Update?.Invoke(this, new MqttEvent("lora/" + sensor.MqttTopic(), sensor.ToJson()));
             }
         }
     } catch (Exception e) {
         Helper.WriteError("Fraunhofer.Fit.IoT.Bots.LoraBot.Moduls.Mqtt.LibUpadteThread: " + e.Message);
     }
 }
Example #27
0
        void init()
        {
            // User Settings

            XmlDocument xmlConfig = new XmlDocument();

            xmlConfig.Load(AppDomain.CurrentDomain.BaseDirectory + "config.xml");
            var mqttConfig = xmlConfig["RazerChromaMqtt"]["MQTT"];
            var v          = mqttConfig["MqttUser"].InnerText.Trim();

            mqttHost     = mqttConfig["MqttHost"].InnerText.Trim();
            mqttPort     = mqttConfig["MqttPort"].InnerText.Trim();
            mqttUser     = mqttConfig["MqttUser"].InnerText.Trim();
            mqttPw       = mqttConfig["MqttPw"].InnerText.Trim();
            mqttPreTopic = mqttConfig["MqttPreTopic"].InnerText.Trim();

            if (mqttUser == "" || mqttPw == "")
            {
                mqttUser = mqttPw = null;
            }


            // MQTT
            mqttClient                 = MqttClientFactory.CreateClient($"tcp://{mqttHost}:{mqttPort}", "chroma", mqttUser, mqttPw);
            mqttClient.Connected      += MqttC_Connected;
            mqttClient.ConnectionLost += MqttC_ConnectionLost;
            mqttClient.PublishArrived += MqttC_PublishArrived;

            MqttAppender.mqttClient   = mqttClient;
            MqttAppender.mqttPreTopic = mqttPreTopic;

            try
            {
                mqttClient.Connect(mqttPreTopic + "state", QoS.BestEfforts, new MqttPayload("offline"), false);
            }
            catch (Exception e)
            {
                log.Error("Mqtt connect eror : " + e.Message);
                base.Stop();
            }


            Task <IChroma> connectChroma = ColoreProvider.CreateNativeAsync();

            connectChroma.Wait();
            chroma = connectChroma.Result;
        }
Example #28
0
 // reconnect
 // todo easy one implementation
 // just drop old handle
 public void Reconnect()
 {
     ThreadPool.QueueUserWorkItem((o) =>
     {
         Log.Info("Reconnect handle.Connect(false);");
         try
         {
             handle   = null;
             clientId = string.Format("client_{0}", Guid.NewGuid());
             InitHandle();
             handle.Connect(false);
             Log.Info("Reconnect handle.Connect(false); complete");
         }
         catch (Exception e)
         {
             Log.Error("MqttAdaptor Reconnect throw exp:{0}", e);
         }
     });
 }
Example #29
0
        void InitHandle()
        {
            try
            {
                handle = MqttClientFactory.CreateClient(connStr, clientId, user, pass);
                Log.Info("MqttAdaptor handle constructed");
            }
            catch (Exception e)
            {
                Log.Error("MqttAdaptor InitHandle construct throw exp:{0}", e);
                throw;
            }

            handle.Connected = OnConnected;
            handle.ConnectionLost = OnDisconnected;
            handle.PublishArrived = OnReceived;

            Log.Info("MqttAdaptor InitHandle");
        }
        void MQTTProgram(string connectionString, string clientId)
        {
            if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(clientId))
            {
                return;
            }
            // Instantiate client using MqttClientFactory
            _client = MqttClientFactory.CreateClient(connectionString, clientId);

            // Setup some useful client delegate callbacks
            _client.Connected      += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);



            Start();
            //Stop();
        }
Example #31
0
        void InitHandle()
        {
            try
            {
                handle = MqttClientFactory.CreateClient(connStr, clientId, user, pass);
                Log.Info("MqttAdaptor handle constructed");
            }
            catch (Exception e)
            {
                Log.Error("MqttAdaptor InitHandle construct throw exp:{0}", e);
                throw;
            }

            handle.Connected      = OnConnected;
            handle.ConnectionLost = OnDisconnected;
            handle.PublishArrived = OnReceived;

            Log.Info("MqttAdaptor InitHandle");
        }
Example #32
0
        public FrmMqttMain(IMqtt mqtt, IMqttPublish mqttPublish, MainFormContainer mainFormContainer)
        {
            _mqtt        = mqtt;
            _mqttPublish = mqttPublish;
            mainFormContainer.MainForm = this;

            try
            {
                InitializeComponent();
                Version version = Assembly.GetExecutingAssembly().GetName().Version;
                toolStripStatusLabel2.Text = "";
                MqttSettings.Init();
                SetupNotify();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            // Perform any additional setup after loading the view, typically from a nib.

            btnConnect.Enabled = true;
            btnPush.Enabled = false;

            lbConnected.TextColor = UIColor.Red;
            lbConnected.Text = "Not connected";
            lbStatus.Text = "...";

            _wormHole = new Wormhole ("group.tech.seamlessthingies.ccmqttex", "messageDir");
            _wormHole.ListenForMessage<string> ("emotion", (message) => {
                _mqttClient.Publish("mqttdotnet/pubtest", "Hi from your watch!", QoS.BestEfforts, false);
                InvokeOnMainThread(() => { lbStatus.Text = "got message from watch: " + _i.ToString();});
                _i++;
            });

            _mqttClient = MqttClientFactory.CreateClient ("tcp://m11.cloudmqtt.com:12360", Guid.NewGuid ().ToString (), "mike", "cloudmqtt");
            _mqttClient.Connected += (object sender, EventArgs e) => {
                InvokeOnMainThread (() => {
                    btnConnect.Enabled = false;
                    btnPush.Enabled = true;
                    lbConnected.TextColor = UIColor.Green;
                    lbConnected.Text = "Connected";
                    _connected = true;
                });
            };

            _mqttClient.ConnectionLost += (object sender, EventArgs e) => {
                InvokeOnMainThread (() => {
                    btnConnect.Enabled = true;
                    btnPush.Enabled = false;
                    lbConnected.TextColor = UIColor.Red;
                    lbConnected.Text = "Not connected";
                    _connected = false;
                });
            };

            _mqttClient.Connect (true);
        }
        public ExternalDoorController(IMqtt mqttService, ILogger logger,string houseCode, string deviceCode)
        {
            _logger = logger;
            _mqttService = mqttService;
            _houseCode = houseCode;
            _deviceCode = deviceCode;

            // Setup the timer to wait forever
            _pingResponseTimer = new Timer(new TimerCallback(OnPingResponseTimer), this._pingResponseOutput, Timeout.Infinite, Timeout.Infinite);

            // Setup the timer that flashes the LED when the code is invalid
            _invalidCodeFlashLEDTimer = new Timer(new TimerCallback(OnFlashLEDTimer), this._invalidCodeLED, Timeout.Infinite, Timeout.Infinite);

            // Setup the interrupt handlers that detect when a door is opened or closed
            _door.StateChanged += new AutoRepeatEventHandler(_door_StateChanged);

            // Setup the interrupt handlers that detect when a keypad key is depressed
            _keyboard0Key.StateChanged += new AutoRepeatEventHandler(_keyboard0Key_StateChanged);
            _keyboard1Key.StateChanged += new AutoRepeatEventHandler(_keyboard1Key_StateChanged);
            _keyboardEnterKey.StateChanged += new AutoRepeatEventHandler(_keyboardEnterKey_StateChanged);

            // Setup the interrupt handlers that detect when a doorbell is pressed
            _doorBell.StateChanged += new AutoRepeatEventHandler(_doorBell_StateChanged);
        }
Example #35
0
 public MqttPublish(IMqtt mqtt, IAudio audio)
 {
     _mqtt     = mqtt;
     _audioobj = audio;
 }
Example #36
0
 //Awake function connects to the mqtt broker and sets a function to be called whenever a publish arrives
 //NOTE: a factory class may be used to allow connections to any mqtt broker not just a hard coded one
 void Awake()
 {
     m_client = MqttClientFactory.CreateClient("tcp://" + IPAddress + ":" + Port, "UnityProxy");
     m_client.Connect(true);
     m_client.PublishArrived += new PublishArrivedDelegate(MessageRecieved);
 }
Example #37
0
 public void Close()
 {
     DisConnect();
     mqtt = null;
 }
Example #38
0
 public SystemShutdown(IMqtt mqtt)
 {
     _mqtt = mqtt;
 }
Example #39
0
        private static void SetupMqtt()
        {
            try
            {
                _mqtt = MqttClientFactory.CreateClient(_settings.Server, _settings.Key);

                _mqtt.PublishArrived -= new PublishArrivedDelegate(MqttPublishArrived);
                _mqtt.ConnectionLost -= new ConnectionDelegate(MqttConnectionLost);

                _mqtt.Connect();

                Subscription subscription = new Subscription(_settings.Key, QoS.BestEfforts);
                _mqtt.Subscribe(subscription);

                _mqtt.PublishArrived += new PublishArrivedDelegate(MqttPublishArrived);
                _mqtt.ConnectionLost += new ConnectionDelegate(MqttConnectionLost);

                _blinkLedCommand.Execute(CreateLedBlinkCommand(2));
            }
            catch (Exception ex)
            {
                Restart("Setup MQTT has failed", ex);
            }
        }
Example #40
0
 // reconnect
 // todo easy one implementation 
 // just drop old handle
 public void Reconnect()
 {
     ThreadPool.QueueUserWorkItem((o) =>
     {
         Log.Info("Reconnect handle.Connect(false);");
         try
         {
             handle = null;
             clientId = string.Format("client_{0}", Guid.NewGuid());
             InitHandle();
             handle.Connect(false);
             Log.Info("Reconnect handle.Connect(false); complete");
         }
         catch (Exception e)
         {
             Log.Error("MqttAdaptor Reconnect throw exp:{0}", e);
         }
     });
 }
        private void ConnectToBroker(string ip, int port, string clientId)
        {
            if (string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(clientId) || port == 0)
                return;
            if (_client != null)
            {
                _client.PublishArrived -= new PublishArrivedDelegate(_client_PublishArrived);
                _client.Connected -= new ConnectionDelegate(_client_Connected);
                _client.ConnectionLost -= new ConnectionDelegate(_client_ConnectionLost);
                _client.Published -= new CompleteDelegate(_client_Published);
                _client.Subscribed -= new CompleteDelegate(_client_Subscribed);
                _client.Unsubscribed -= new CompleteDelegate(_client_Unsubscribed);
                if (_client.IsConnected)
                {
                    // TODO this might be async
                    _client.Disconnect();
                }
            }

            _client = MqttClientFactory.CreateClient("tcp://" + ip + ":" + port.ToString(), clientId);

            _client.Connect();

            // Subscribe to the house code in config
            string houseCode = ConfigurationManager.AppSettings["HouseCode"];

            _client.Subscribe("/" + houseCode + "/#", QoS.BestEfforts);
            _client.Subscribe("$SYS/broker/clients/#", QoS.BestEfforts);
            _client.PublishArrived += new PublishArrivedDelegate(_client_PublishArrived);
            _client.Connected += new ConnectionDelegate(_client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.Published += new CompleteDelegate(_client_Published);
            _client.Subscribed += new CompleteDelegate(_client_Subscribed);
            _client.Unsubscribed += new CompleteDelegate(_client_Unsubscribed);
        }