private void DoMqttConnect()
        {
            try
            {
                if (MQTTClient != null && !MQTTClient.IsConnected)
                {
                    PrintTime();
                    Console.WriteLine("Connecting to MQTT server");
                    Log.Logger.Information("Connecting to MQTT server");
                    MQTTState = MQTTClient.Connect(CLIENT_IDENTIFIER, Setting.Default.MQTTUser, Setting.Default.MQTTPass, true, Setting.Default.KeepAlive);
                    Console.WriteLine("Connect called ");
                    Console.WriteLine("State: ");
                    Console.Write(MQTTState);

                    Log.Logger.Information("---> Connect called");
                }
                else
                {
                    PrintTime();
                    Console.WriteLine("Tried connecting to MQTT server - but was already connected");
                    Log.Logger.Information("Tried connecting to MQTT server - but was already connected");
                }
            }
            catch (Exception e)
            {
                PrintTime();

                Console.WriteLine("Error while connecting. Retrying again in 5 seconds: " + e);
                Log.Logger.Error("Error while connecting. Retrying again in 5 seconds: " + e);
                Thread.Sleep(5000);
            }
        }
Ejemplo n.º 2
0
        void WyslijWiadomosc()
        {
            var    receivedMessage = false;
            string message         = "";
            // create the client
            var client = new MQTTClient("xxx.xxx.xxx.xxx", 10883);

            // hook up the MessageReceived event with a handler
            //client.MessageReceived += (topic, qos, payload) =>
            //{
            //    MessageBox.Show("Odebrano: " + topic);
            //    receivedMessage = true;
            //};

            // connect to the MQTT server
            message = Guid.NewGuid().ToString();
            client.Connect("Klient1234");
            // wait for the connection to complete

            // add a subscription
            client.Subscriptions.Add(new Subscription("test"));

            string User = "";

            User = client.BrokerHostName;
            var data = DateTime.Now;

            client.Publish("test", data + " Wiadomosc: " + message, QoS.AcknowledgeDelivery, false);
            status.Content = "Wysłano";
            if (client.IsConnected)
            {
                client.Disconnect();
            }
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Index(string theme, string Message, string username, string password)
        {
            MQTTClient    mq     = new MQTTClient(_config);
            List <string> topics = new List <string>();

            topics.Add("test1");
            mq.ConnectAsync(_ip, "svin", "123", topics);
            new Thread(() =>
            {
                mq.Reconnect(topics);
            }).Start();
            mq.PublisherAsync("test1");
            new Thread(async() =>
            {
                await foreach (var m in mq.Receive())
                {
                    mq.Save(m);
                }
            }).Start();

            Thread.Sleep(3000);
            var    recData = SignalsRepository.FindAll();
            string result  = null;

            foreach (var t in recData)
            {
                result += t.Name + ' ' + t.Data + ' ' + t.Time + ' ' + t.Quality + "/n";
            }
            return(Content(result));
        }
Ejemplo n.º 4
0
        //Cleans up after MQTT connections. First, it disconnects if it is still connected. Next it unsubsribes all events
        private static void CleanUpMQTT()
        {
            try
            {
                // deregister event listeners
                if (MQTTClient != null)
                {
                    if (MQTTClient.IsConnected)
                    {
                        MQTTClient.Disconnect();
                    }

                    MQTTClient.MqttMsgPublishReceived -= Client_MqttMsgPublishReceived;
                    MQTTClient.MqttMsgSubscribed      -= Client_MqttMsgSubscribed;
                    MQTTClient.MqttMsgUnsubscribed    -= Client_MqttMsgUnsubscribed;
                    MQTTClient.MqttMsgPublished       -= Client_MqttMsgPublished;
                    MQTTClient.ConnectionClosed       -= MQTTClient_ConnectionClosed;
                    MQTTClient = null;
                }
            }
            catch (Exception e)
            {
                //Log.Logger.Error("Error during clean up: " + e);
                Console.WriteLine("Error during clean up: " + e);
            }
        }
Ejemplo n.º 5
0
        public async Task FailedConnectionToClient()
        {
            MQTTClient client      = new MQTTClient();
            bool       isConnected = await client.Connect(this.IP, this.PORT, this.PASSWORD);

            Assert.IsTrue(isConnected);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// 方法说明:连接MQTT服务
 /// 完成时间:2016-04-20
 /// </summary>
 /// <param name="userId">对应MQTT的客户端用户ID</param>
 /// <param name="mqttConfig">登录时获取到的MQTT连接配置</param>
 /// <param name="errorMsg">MQTT连接错误提示</param>
 /// <returns>是否连接成功</returns>
 public bool Connect(string userId, GetConnectConfigOutput mqttConfig, ref string errorMsg)
 {
     this._userId = userId;
     try
     {
         _client = new MQTTClient(mqttConfig.host, int.Parse(mqttConfig.port));
         if (_client.Connect(mqttConfig.clientId, mqttConfig.userName, mqttConfig.password))
         {
             _client.MessageReceived += OnMessageReceived;
             _client.ReconnectedMqtt += OnReconnectedMqtt;
             _client.Disconnected    += OnDisconnectedMqtt;
             LogHelper.WriteDebug($"{Resources.SdkMqttConnectSuccess}:{mqttConfig.host}:{mqttConfig.port}");
             //连接成功就开始跑定时器
             _heartbeattimer          = new System.Timers.Timer(1000);
             _heartbeattimer.Elapsed += _heartbeattimer_Elapsed;
             _heartbeattimer.Start();
             return(true);
         }
         else
         {
             LogHelper.WriteError(
                 $"{Resources.SdkMqttConnectFail}:[{mqttConfig.host}:{mqttConfig.port}] {errorMsg}");
             return(false);
         }
     }
     catch (Exception ex)
     {
         errorMsg = ex.Message;
         LogHelper.WriteError(
             $"{Resources.SdkMqttConnectFail}:[{mqttConfig.host}:{mqttConfig.port}] {ex.Message}");
         return(false);
     }
 }
Ejemplo n.º 7
0
        public static MQTTClient Conectar()
        {
            MQTTClient client = new MQTTClient(iplan, 1883);

            client.ConnectAsync(iplan);
            return(client);
        }
Ejemplo n.º 8
0
        public static void Main(string[] args)
        {
            //create a new thread for MQTT websocket json transfer
            MQTTClient client = new MQTTClient();

            Task.Run(async() => await client.GetMQTTDataAsync());
            CreateHostBuilder(args).Build().Run();
        }
Ejemplo n.º 9
0
        private void InitializeObject()
        {
            resourceCore = new ResourceCore();
            mqttClient   = new MQTTClient();

            cctvTimer          = new DispatcherTimer();
            cctvTimer.Tick    += CctvTimer_Tick;
            cctvTimer.Interval = new TimeSpan(0, 0, 10);
        }
Ejemplo n.º 10
0
 public ModBusService(MQTTClient mqtt, IOptions <AppSettings> options, ILogger <ModBusService> logger, ISchedulerFactory factory)
 {
     _logger                    = logger;
     _options                   = options.Value;
     _mqtt                      = mqtt;
     _mqtt.OnExcCommand        += _mqtt_OnExcCommand;
     _mqtt.OnReceiveAttributes += Mqtt_OnReceiveAttributesAsync;
     _factory                   = factory;
 }
Ejemplo n.º 11
0
        public async Task DisconnectFromClient()
        {
            MQTTClient client      = new MQTTClient();
            bool       isConnected = await client.Connect(this.IP, this.PORT, this.PASSWORD);

            Assert.IsTrue(isConnected);
            isConnected = await client.Disconnect();

            Assert.IsFalse(isConnected);
        }
Ejemplo n.º 12
0
 private static void SendMQTT(string message)
 {
     System.Media.SystemSounds.Asterisk.Play();
     Task.Run(() =>
     {
         //Send the message with exactly once semantics
         MQTTClient.Publish(Setting.Default.Topic, Encoding.UTF8.GetBytes(message),           // message body
                            MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE,                              // QoS level
                            true);
     });
 }
 public static void Conectar(string nombreCliente, string server, int puerto = 1883)
 {
     mqtt                  = new MQTTClient(server, puerto);
     NombreCliente         = nombreCliente;
     mqtt.Connected       += Mqtt_Connected;
     mqtt.MessageReceived += Mqtt_MessageReceived;
     mqtt.Disconnected    += Mqtt_Disconnected;
     mqtt.Subscriptions.SubscriptionAdded   += Subscriptions_SubscriptionAdded;
     mqtt.Subscriptions.SubscriptionRemoved += Subscriptions_SubscriptionRemoved;
     Connect();
 }
Ejemplo n.º 14
0
        public async Task SubscribeAndSendMessage()
        {
            MQTTClient client = new MQTTClient();

            _ = await client.Connect(this.IP, this.PORT, this.PASSWORD);

            client.Subscribe(this.TESTCHANNEL);
            client.Publish(this.TESTCHANNEL, "hello world");
            Thread.Sleep(100);
            MQTTMessage message = client.MQTTMessageStore.GetLatestMessageFromTopic(this.TESTCHANNEL);

            Assert.AreEqual("hello world", message.Message);
        }
Ejemplo n.º 15
0
    // Use this for initialization
    void Start()
    {
        // create client instance
        client = new MqttClient(IPAddress.Parse(BrokerIP), BrokerPort, false, null);

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

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

        singleton = this;
    }
 public MQTTPublishNode(Guid id, Guid accId, string name, bool isActivated, NodeActionParameters parameters)
 {
     Type      = NodeTypes.HTTPAPIRequest;
     Id        = id;
     AccountId = accId;
     Name      = name;
     if (parameters != null)
     {
         LoadParameters(parameters);
         SetNodeTriggerType(parameters.TriggerType);
     }
     IsActivated       = isActivated;
     ActualTriggerType = NodeActionTriggerTypes.None;
     mqttClient        = new MQTTClient("node-" + id.ToString());
 }
Ejemplo n.º 17
0
        private void InitializeObject()
        {
            resourceCore    = new ResourceCore();
            environmentCore = new EnvironmentCore();
            mqttClient      = new MQTTClient();
            serial          = new Serial(9600);

            weatherResetTimer          = new DispatcherTimer();
            weatherResetTimer.Tick    += WeatherResetTimer_Tick;
            weatherResetTimer.Interval = new TimeSpan(0, 30, 0);

            cctvTimer          = new DispatcherTimer();
            cctvTimer.Tick    += CctvTimer_Tick;
            cctvTimer.Interval = new TimeSpan(0, 0, 10);
        }
Ejemplo n.º 18
0
        CreateObservableMQTTClient(
            IClientOptions options,
            IWillMessage willMessage = null,
            params ITopicFilter[] topicFilters)
        {
            ClientOptions = options;
            WillMessage   = willMessage;

            _wrappedClient = new MQTTClient(this, topicFilters);

            var observable = Observable.Create <IMQTTMessage>(
                obs =>
            {
                var disposableConnect = _wrappedClient.ObservableConnect
                                        .Subscribe(_ =>
                {
                },
                                                   obs.OnError,
                                                   obs.OnCompleted);

                var disposableMessage = _wrappedClient.ObservableMessage
                                        .Subscribe(
                    obs.OnNext,
                    obs.OnError,
                    obs.OnCompleted);

                var disposableDisconnect = _wrappedClient.ObservableDisconnect
                                           .Where(disconnect => disconnect == true)
                                           .Select(x => Observable.FromAsync(() => _wrappedClient.DisconnectAsync()).Timeout(TimeSpan.FromSeconds(5)))
                                           .Concat()
                                           .Subscribe(d =>
                {
                    Debug.WriteLine("Disconnected");
                    obs.OnCompleted();
                },
                                                      obs.OnError,
                                                      obs.OnCompleted);

                return(new CompositeDisposable(
                           disposableMessage,
                           disposableConnect,
                           disposableDisconnect));
            })
                             .FinallyAsync(async() => { await _wrappedClient?.DisconnectAsync(); })
                             .Publish().RefCount();

            return(observable, _wrappedClient);
        }
Ejemplo n.º 19
0
        static void Main(string[] ass)
        {
            ////
            int        count    = 0;
            var        ClientId = DateTime.Now.Ticks.ToString();
            MQTTClient client   = new MQTTClient("my.hnlyf.com");

            client.Connect(new MQTTConnectInfo()
            {
                UserName = "******", Password = "******", ClientId = ClientId
            });
            // client.Subscribe("iot/log/#"); ;
            System.Timers.Timer timer = new System.Timers.Timer(1000);
            timer.Elapsed += (o, e) =>
            {
                Console.Title = ($"{ClientId}--{ass[0]}:当前每秒:{count}个,总个数:{TotalCount}");
                count         = 0;
            };

            timer.Start();
            while (true)
            {
                //Console.WriteLine("请随意输入");
                var text = Guid.NewGuid().ToString();
                if (string.IsNullOrEmpty(text))
                {
                    client.UnSubscribe("iot/log/#");;
                    client.Disconnect();
                }
                PublishDataPackage applicationMessage = new PublishDataPackage()
                {
                    Topic = $"iot/log/{ass[0]}", Text = text
                };
                if (!client.Publish(applicationMessage))
                {
                    Console.WriteLine("断线了?");
                    Console.ReadLine();
                }
                System.Threading.Interlocked.Increment(ref count);
                System.Threading.Interlocked.Increment(ref TotalCount);
                System.Threading.Thread.Sleep(10);
            }



            Console.ReadLine();
        }
Ejemplo n.º 20
0
        public void ClientReceiveTest()
        {
            var receivedMessage = false;

            var client = new MQTTClient("ec2-18-217-218-110.us-east-2.compute.amazonaws.com", 1883);

            client.MessageReceived += (topic, qos, payload) =>
            {
                Debug.WriteLine("RX: " + topic);
                receivedMessage = true;
            };

            var i = 0;

            client.Connect("solution-family", "solution-family", "s36158");
            while (!client.IsConnected)
            {
                Thread.Sleep(1000);

                if (i++ > 10)
                {
                    Assert.Fail();
                }
            }

            Assert.IsTrue(client.IsConnected);
            client.Subscriptions.Add(new Subscription("solution-family/#"));

            i = 0;
            while (true)
            {
                if (receivedMessage)
                {
                    break;
                }

                Thread.Sleep(1000);
                client.Publish("solution-family/Test", "Hello", QoS.FireAndForget, false);

                if (i++ > 10)
                {
                    break;
                }
            }

            Assert.IsTrue(receivedMessage);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// MQTT message interpreter.
        /// </summary>
        public MQTTHandler(string host, int port, string user, string password)
        {
            client = new MQTTClient(host, port);
            client.MessageReceived += MessageReceived;
            client.Connect(host, user, password);
            int i = 0;

            while (!client.IsConnected)
            {
                System.Threading.Thread.Sleep(500);
                if (i++ > 10)
                {
                    Alert.SendAlert(null, "MQTT connection failed to " + host + " as " + user + '.');
                    break;
                }
            }
            client.Subscriptions.Add(new Subscription("#"));
        }
Ejemplo n.º 22
0
 private static void DoMqttConnect()
 {
     try
     {
         if (MQTTClient != null && !MQTTClient.IsConnected)
         {
             Console.WriteLine("Connecting to MQTT server");
             var state = MQTTClient.Connect(CLIENT_IDENTIFIER, Setting.Default.MQTTUser, Setting.Default.MQTTPass, true, Setting.Default.KeepAlive);
             Console.WriteLine("Connect called ");
         }
         else
         {
             Console.WriteLine("Tried connecting to MQTT server - but was already connected");
         }
     }
     catch (Exception e)
     {
     }
 }
Ejemplo n.º 23
0
 public Actuadores()
 {
     InitializeComponent();
     mensajes              = new List <string>();
     mqtt                  = new MQTTClient("broker.hivemq.com", 1883);
     mqtt.MessageReceived += Mqtt_MessageReceived;
     mqtt.Connect("AppMovilESP8266");
     mqtt.Subscriptions.Add(new Subscription("ServerProfeCarlos"));
     Device.StartTimer(TimeSpan.FromSeconds(1), () =>
     {
         if (mensajes.Count > m)
         {
             lstMensajes.ItemsSource = null;
             lstMensajes.ItemsSource = mensajes;
             m = mensajes.Count;
         }
         return(true);
     });
 }
 // Use this to connect up to the given MQTT broker
 public bool Connect(string brokerAddress, int port, string clientID, int amountOfRetries)
 {
     //attachedApplication.output.PrintLine("Connecting to " + brokerAddress + ":" + port + "...");
     // Create a new MQTT client
     client = new MQTTClient(brokerAddress, port);
     // Register to message received
     client.MessageReceived += OnMessageRecievedLocal;
     // Connect up the client
     client.Connect(clientID);
     // Wait for the connection to complete
     while (!client.IsConnected)
     {
         Thread.Sleep(100);
         if (amountOfRetries <= 0)
         {
             attachedApplication.output.PrintLine("$maFailed $mato $maconnect... $ma:(");
             return(false);
         }
         amountOfRetries--;
     }
     return(true);
 }
Ejemplo n.º 25
0
        /// <summary>
        /// 连接MQTT服务
        /// </summary>
        /// <param name="token">对应MQTT的客户端ID</param>
        /// <returns></returns>
        public bool Connect(ref string errMsg)
        {
            try
            {
                Client = new MQTTClient(GlobalVariable.ConfigEntity.MQTT_Host, int.Parse(GlobalVariable.ConfigEntity.MQTT_Port));
                if (Client.Connect(GlobalVariable.LoginOutput.userId + "/" + (int)GlobalVariable.OSType.PC, GlobalVariable.ConfigEntity.MQTT_UserName, GlobalVariable.ConfigEntity.MQTT_Password))
                {
                    #region 发心跳消息
                    //Heartbeat heartbeat = new Heartbeat();
                    //heartbeat.ctt.token = token;
                    //pingTimer = new Timer((state) =>
                    //{

                    //    Publish<Heartbeat>("heartbeat", heartbeat);
                    //    //Client.Publish("heartbeat", byteArray, Qos.AtLeastOnce);
                    //}, null, 0, KeepAlive * 1000);
                    #endregion
                    Client.MessageReceived += OnMessageReceived;
                    Client.ReconnectedMqtt += OnReconnectedMqtt;
                    LogHelper.WriteDebug("MQTT连接成功:" + GlobalVariable.ConfigEntity.MQTT_Host + ":" + int.Parse(GlobalVariable.ConfigEntity.MQTT_Port));
                    return(true);
                }
                else
                {
                    errMsg = "消息服务器连接异常";
                    LogHelper.WriteDebug(string.Format("MQTT连接失败:[{0}:{1}] {2}", GlobalVariable.ConfigEntity.MQTT_Host, GlobalVariable.ConfigEntity.MQTT_Port, errMsg));
                    return(false);
                }
            }
            catch (Exception ex)
            {
                errMsg = "消息服务器连接异常";
                LogHelper.WriteDebug(string.Format("MQTT连接失败:[{0}:{1}] {2}", GlobalVariable.ConfigEntity.MQTT_Host, GlobalVariable.ConfigEntity.MQTT_Port, errMsg));
                return(false);
            }
        }
Ejemplo n.º 26
0
        private int timeout; // Timeout in seconds

        public DojotMqtt(string address, int port, int timeoutSecs)
        {
            client = new MQTTClient(address, port);
            SetTimeout(timeoutSecs);
        }
Ejemplo n.º 27
0
 //client.Publish("home/quarto/01", "OFF",QoS.FireAndForget,false);
 public static async void Publicar(string dispositivo, string comando)
 {
     MQTTClient client = Conectar();
     await client.PublishAsync(dispositivo, comando, QoS.FireAndForget, true);
 }
 public AuthenticationController(MQTTClient MQTTClient) => this.MQTTClient = MQTTClient;
Ejemplo n.º 29
0
    //IntializeScene. Check for excistence of key gameobjects and set reference variables.
    private void InitializeScene()
    {
        // Create settings folders.
        if (!AssetDatabase.IsValidFolder("Assets/Logs"))
        {
            AssetDatabase.CreateFolder("Assets", "Logs");
        }
        if (!AssetDatabase.IsValidFolder("Assets/VRSettings"))
        {
            AssetDatabase.CreateFolder("Assets", "VRSettings");
        }
        if (!AssetDatabase.IsValidFolder("Assets/VRSettings/PathCreator"))
        {
            AssetDatabase.CreateFolder("Assets/VRSettings", "PathCreator");
        }
        if (!AssetDatabase.IsValidFolder("Assets/VRSettings/Controllers"))
        {
            AssetDatabase.CreateFolder("Assets/VRSettings", "Controllers");
        }
        if (!AssetDatabase.IsValidFolder("Assets/VRSettings/Displays"))
        {
            AssetDatabase.CreateFolder("Assets/VRSettings", "Displays");
        }
        if (!AssetDatabase.IsValidFolder("Assets/VRSettings/Actors"))
        {
            AssetDatabase.CreateFolder("Assets/VRSettings", "Actors");
        }

        // Check for main default objects.
        GameObject obj;

        string[] DefaultObjects = { "Actors", "Controllers", "MQTT Client", "Paths", "Logger" };
        foreach (string objName in DefaultObjects)
        {
            if (!GameObject.Find(objName))
            {
                Debug.Log(string.Format("Creating Object: {0}..", objName));
                obj = new GameObject(objName);
                // Special circumstances.
                switch (objName)
                {
                case "MQTT Client":
                    obj.AddComponent <Gimbl.MQTTClient>();
                    break;

                case "Logger":
                    _logger = obj.AddComponent <Gimbl.LoggerObject>();
                    Gimbl.LoggerSettings asset = CreateInstance <Gimbl.LoggerSettings>();
                    AssetDatabase.CreateAsset(asset, "Assets/VRSettings/LoggerSettings.asset");
                    _logger.settings = asset;
                    break;
                }
                // Things have changed. Mark scene for save.
                UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
            }
            else
            {
                obj = GameObject.Find(objName);
            }
            switch (objName)
            {
            // Assign for controls.
            case "MQTT Client":
                _client       = obj.GetComponent <Gimbl.MQTTClient>();
                obj.hideFlags = HideFlags.HideInHierarchy;
                break;

            case "Paths":
                break;

            case "Controllers":
                obj.hideFlags = HideFlags.None;
                break;

            case "Logger":
                _logger          = obj.GetComponent <Gimbl.LoggerObject>();
                _logger.settings = (LoggerSettings)AssetDatabase.LoadAssetAtPath("Assets/VRSettings/LoggerSettings.asset", typeof(LoggerSettings));
                obj.hideFlags    = HideFlags.HideInHierarchy;
                break;

            case "Actors":
                break;
            }
        }
        // Set client IP settings from stored.
        _client.ip = EditorPrefs.GetString("JaneliaVR_MQTT_IP");
        if (_client.ip == "")
        {
            _client.ip = "127.0.0.1";
        }
        _client.port = EditorPrefs.GetInt("JaneliaVR_MQTT_Port");
        if (_client.port == 0)
        {
            _client.port = 1883;
        }
        // Set default properties.
        msgSettings.sendFrameMsg      = EditorPrefs.GetBool("Gimbl_sendFrameMsg", false);
        sessionSettings.externalStart = EditorPrefs.GetBool("Gimbl_externalStart", false);
        sessionSettings.externalLog   = EditorPrefs.GetBool("Gimbl_externalLog", false);
        // Check for global display settings path creator.
        if (UnityEditor.AssetDatabase.FindAssets("t:GlobalDisplaySettings").Length == 0)
        {
            PathCreation.GlobalDisplaySettings asset = CreateInstance <PathCreation.GlobalDisplaySettings>();
            AssetDatabase.CreateAsset(asset, "Assets/VRSettings/PathCreator/GlobalDisplaySettings.asset");
        }
    }
Ejemplo n.º 30
0
 public Slaver(MQTTClient mqtt, IOptions <AppSettings> options, ILogger <Slaver> logger)
 {
     _mqtt       = mqtt;
     _logger     = logger;
     appSettings = options.Value;
 }