Exemplo n.º 1
0
            public static DeviceConfig CreateChangeObject(DeviceConfig currentConfig, DeviceConfig newConfig)
            {
                var change = new DeviceConfig();

                if (currentConfig.Name != newConfig.Name)
                {
                    change.Name = newConfig.Name;
                }
                if (currentConfig.DeviceID != newConfig.DeviceID)
                {
                    change.Name = newConfig.DeviceID;
                }
                if (!currentConfig.WiFi.Equals(newConfig.WiFi))
                {
                    change.WiFi = WiFi.CreateChangeObject(currentConfig.WiFi, newConfig.WiFi);
                }
                if (!currentConfig.MQTT.Equals(newConfig.MQTT))
                {
                    change.MQTT = MQTT.CreateChangeObject(currentConfig.MQTT, newConfig.MQTT);
                }
                if (!currentConfig.OTA.Equals(newConfig.OTA))
                {
                    change.OTA = OTA.CreateChangeObject(currentConfig.OTA, newConfig.OTA);
                }
                change.Settings = CreateChangeSettings(currentConfig.Settings, newConfig.Settings);

                return(change);
            }
Exemplo n.º 2
0
            public static MQTT CreateChangeObject(MQTT currentMQTT, MQTT newMQTT)
            {
                var change = new MQTT();

                if (currentMQTT.Host != newMQTT.Host)
                {
                    change.Host = newMQTT.Host;
                }
                if (currentMQTT.Port != newMQTT.Port)
                {
                    change.Port = newMQTT.Port;
                }
                if (currentMQTT.BaseTopic != newMQTT.BaseTopic)
                {
                    change.BaseTopic = newMQTT.BaseTopic;
                }
                if (currentMQTT.Auth != newMQTT.Auth)
                {
                    change.Auth = newMQTT.Auth;
                }
                if (currentMQTT.Username != newMQTT.Username)
                {
                    change.Username = newMQTT.Username;
                }
                if (currentMQTT.Password != newMQTT.Password)
                {
                    change.Password = newMQTT.Password;
                }
                return(change);
            }
Exemplo n.º 3
0
 public UpdateWorker(CancellationToken token, ILogger <Worker> logger, AppSettings appSettings)
 {
     _token       = token;
     _logger      = logger;
     _appSettings = appSettings;
     _mqttConfig  = appSettings.MQTT;
 }
Exemplo n.º 4
0
 public MqttWorker(ILogger <Worker> logger, AppSettings appSettings)
 {
     _logger        = logger;
     config         = appSettings.MQTT;
     inverterConfig = appSettings.Inverter;
     MqttClient     = new MqttClient(config.server);
 }
Exemplo n.º 5
0
        private void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            try
            {
                Regex rgx = new Regex(@"/[A-Za-z0-9]*/[A-Za-z0-9]*/[A-Za-z0-9]*");
                if (rgx.IsMatch(e.Topic))
                {
                    var topicos = e.Topic.Split('/');

                    MQTT novo = new MQTT()
                    {
                        topico    = e.Topic,
                        titulo    = topicos[2],
                        local     = topicos[1],
                        isPublish = topicos[3] == "label" ? false : true,
                        valor     = Encoding.UTF8.GetString(e.Message)
                    };

                    if (mqtt.Select(x => x.topico).Contains(e.Topic))
                    {
                        mqtt.Remove(mqtt.Where(x => x.topico == e.Topic).First());
                    }
                    mqtt.Add(novo);
                }
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 6
0
        public async Task MtqqMessageTest()
        {
            MessageHandler messageHandler = new MessageHandler();
            var            client         = await MQTT.StartClient(messageHandler);

            /**
             * PublicChatMessage|{"author":"sokcuri","message":"hello world"}
             */
            await MQTT.Publish(client, "chat", "PublicChatMessage", "{'author': 'Sokcuri', 'message': 'hello world'}");

            await MQTT.Publish(client, "chat", "WhisperMessage", "{'sender': 'foo', 'receiver': 'bar', 'message': 'message'}");

            await MQTT.Publish(client, "notice", "NoticeMessage", "{'notice': 'notice message', 'important': 2, 'sticky': true}");

            if (!WaitHandle.WaitAll(new WaitHandle[] { noticeEvent, publicChatEvent, whisperEvent }, TimeSpan.FromSeconds(5)))
            {
                Assert.Fail("Timeout");
            }

            Assert.AreEqual("Sokcuri", publicChatMessage.author);
            Assert.AreEqual("hello world", publicChatMessage.message);

            Assert.AreEqual("foo", whisperMessage.sender);
            Assert.AreEqual("bar", whisperMessage.receiver);
            Assert.AreEqual("message", whisperMessage.message);

            Assert.AreEqual("notice message", noticeMessage.notice);
            Assert.AreEqual(2, noticeMessage.important);
            Assert.AreEqual(true, noticeMessage.sticky);
        }
Exemplo n.º 7
0
 private void MqttClient_Disconnected(object sender, EventArgs e)
 {
     Application.Current.Dispatcher.Invoke((new Action(() =>
     {
         MQTT.AppendText("已断开MQTT连接!" + Environment.NewLine);
     })));
 }
Exemplo n.º 8
0
        private async Task ConnectMqttServerAsync()
        {
            if (mqttClient == null)
            {
                mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient;
                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
                mqttClient.Connected    += MqttClient_Connected;
                mqttClient.Disconnected += MqttClient_Disconnected;
            }

            try
            {
                var options = new MqttClientTcpOptions
                {
                    Server       = "127.0.0.1",
                    ClientId     = "win7-PC",
                    UserName     = "******",
                    Password     = "******",
                    CleanSession = true
                };

                await mqttClient.ConnectAsync(options);
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke((new Action(() =>
                {
                    MQTT.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
                })));
            }
        }
Exemplo n.º 9
0
 public Configuracao(MQTT mqtt)
 {
     InitializeComponent();
     mqttConfig       = mqtt;
     txtPorta.Text    = mqtt.Porta.ToString();
     txtSenha.Text    = mqtt.Senha;
     txtServidor.Text = mqtt.Servidor;
     txtUsuario.Text  = mqtt.Usuario;
     ckUsar.IsToggled = mqttConfig.Usar;
 }
Exemplo n.º 10
0
 public override int GetHashCode()
 {
     return
         ((Name != null ? Name.GetHashCode() : 0) +
          (DeviceID != null ? DeviceID.GetHashCode() : 0) +
          (WiFi != null ? WiFi.GetHashCode() : 0) +
          (MQTT != null ? MQTT.GetHashCode() : 0) +
          (OTA != null ? OTA.GetHashCode() : 0) +
          (Settings != null ? Settings.Select(item => (item.Key.GetHashCode() + item.Value.GetHashCode()).GetHashCode()).Sum(item => (long)item).GetHashCode() : 0));
 }
        public void Get()
        {
            var mqtt = new MQTT
            {
                Bytes = new Byte[2]
            };

            mqtt.SetByte(0, 0b_0000_0001);

            mqtt.Retain.Should().Be(true);
        }
Exemplo n.º 12
0
        public void Get()
        {
            var mqtt = new MQTT
            {
                Bytes = new Byte[2]
            };

            mqtt.SetByte(0, 0b_0000_1000);

            mqtt.Duplicate.Should().Be(true);
        }
        public void Set(UInt16 expected, MQTTType input)
        {
            var mqtt = new MQTT
            {
                Bytes = new Byte[32]
            };

            mqtt.Type = input;
            mqtt.Id   = expected;

            mqtt.Id.Should().Be(expected);
        }
        public void Get(UInt16 expected, MQTTType input)
        {
            var mqtt = new MQTT
            {
                Bytes = new Byte[32]
            };

            mqtt.Type = input;
            mqtt.SetByte(2, 0x12);
            mqtt.SetByte(3, 0x34);

            mqtt.Id.Should().Be(expected);
        }
Exemplo n.º 15
0
        public void Set()
        {
            var mqtt = new MQTT
            {
                Bytes = new Byte[2]
            };

            mqtt.Duplicate = true;
            mqtt.GetByte(0).Should().Be(0b_0000_1000);

            mqtt.Duplicate = false;
            mqtt.GetByte(0).Should().Be(0b_0000_0000);
        }
        public void Set()
        {
            var mqtt = new MQTT
            {
                Bytes = new Byte[2]
            };

            mqtt.Retain = true;
            mqtt.GetByte(0).Should().Be(0b_0000_0001);

            mqtt.Retain = false;
            mqtt.GetByte(0).Should().Be(0b_0000_0000);
        }
Exemplo n.º 17
0
        public Payload MQTTPost([FromForm] Payload FormData)
        {
            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Payload));
            MemoryStream msObj            = new MemoryStream();

            js.WriteObject(msObj, FormData);
            msObj.Position = 0;
            StreamReader sr   = new StreamReader(msObj);
            string       json = sr.ReadToEnd();

            MQTT.Publish(json); //MQTT Publish

            return(FormData);   //Return Input Data
        }
Exemplo n.º 18
0
 static void ServidorMQTT(MQTT mqtt)
 {
     try
     {
         MqttClient client = new MqttClient(mqtt.Servidor, mqtt.Porta, false, null, null, MqttSslProtocols.None);
         client.Connect(Guid.NewGuid().ToString(), mqtt.Usuario, mqtt.Senha);
         client.Subscribe(mqtt.Topicos, mqtt.QoS);
         client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
         Log.GravarLog("Servidor MQTT Conectado", "OK");
     }
     catch (Exception ex)
     {
         Log.GravarLog("Não foi possivel Conectar ao Servidor MQTT " + ex.Message, "ERRO");
         System.Environment.Exit(0);
     }
 }
Exemplo n.º 19
0
        public IActionResult OnPostSubmit()
        {
            string Reply = "";
            bool   Veri  = SQL.Verification(DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"), OTP);

            if (Veri == true)
            {
                MQTT.Publish();
                Reply = "Success";
            }
            else
            {
                Reply = "Incorrect OTP";
            }

            return(RedirectToPage("Success", "Message", new { msg = Reply }));
        }
Exemplo n.º 20
0
        public static void GravarConfig(MQTT mqtt)
        {
            var    path     = Directory.GetCurrentDirectory();
            string LocalLog = $@"{path}\Config";

            if (!Directory.Exists(LocalLog))
            {
                Directory.CreateDirectory(LocalLog);
            }
            string       nomeArquivo = $@"{LocalLog}\mqttconfig.json";
            StreamWriter writer      = new StreamWriter(nomeArquivo, true);
            string       output      = JsonConvert.SerializeObject(mqtt);

            writer.Write("");
            writer.Write(output);
            writer.Close();
        }
Exemplo n.º 21
0
        public async void GetConfig(string titulo)
        {
            List <MQTT> configs = new List <MQTT>();

            if (await Storage.FileExistAsync("MQTTMobileConfig"))
            {
                var Json = await Storage.ReadAllTextAsync("MQTTMobileConfig");

                configs = JsonConvert.DeserializeObject <List <MQTT> >(Json);
            }
            MQTT selecionado = configs.Where(x => x.Usar).First();

            client = new MqttClient(selecionado.Servidor, selecionado.Porta, false, null, null, MqttSslProtocols.None);
            client.Connect(Guid.NewGuid().ToString(), selecionado.Usuario, selecionado.Senha);
            client.Subscribe(new string[] { $"/{titulo}/#" }, new byte[] { 0 });
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
        }
Exemplo n.º 22
0
        private async void btnSalvar_Clicked(object sender, EventArgs e)
        {
            mqttConfig.Porta    = int.Parse(txtPorta.Text);
            mqttConfig.Servidor = txtServidor.Text;
            mqttConfig.Usuario  = txtUsuario.Text;
            mqttConfig.Senha    = txtSenha.Text;
            mqttConfig.Usar     = ckUsar.IsToggled;
            List <MQTT> configs = new List <MQTT>();

            if (await Storage.FileExistAsync("MQTTMobileConfig"))
            {
                var Json = await Storage.ReadAllTextAsync("MQTTMobileConfig");

                configs = JsonConvert.DeserializeObject <List <MQTT> >(Json);
            }

            MQTT remover = null;

            foreach (var item in configs)
            {
                if (mqttConfig.Usar)
                {
                    item.Usar = false;
                }
                if (mqttConfig.ID == item.ID)
                {
                    remover = item;
                }
            }

            if (remover != null)
            {
                configs.Remove(remover);
            }

            configs.Add(mqttConfig);
            await Storage.WriteTextAllAsync("MQTTMobileConfig", JsonConvert.SerializeObject(configs));

            await DisplayAlert("Configuração", "Servidor MQTT salvo com Sucesso!!!!!!", "OK");

            await Navigation.PopModalAsync();
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            //Intailize the Broker Settings
            BrokerModel _Broker = new BrokerModel();

            _Broker.Url           = "tailor.cloudmqtt.com";
            _Broker.Username      = "******";
            _Broker.Password      = "******";
            _Broker.Port          = 11300;
            _Broker.SSLPort       = 21300;
            _Broker.WebSocketPort = 31300;

            //Connect to Server
            MQTT mQTT = new MQTT();

            mQTT.Initailize(_Broker);
            mQTT.Connect();

            while (true)
            {
                if (mQTT.Connected)
                {
                    //publish string
                    mQTT.Publish("StringValue", "5");

                    //publish json Object
                    Sensor Sensor     = new Sensor();
                    var    result     = Sensor.CreateSensor();
                    string Jsonresult = JsonConvert.SerializeObject(result);
                    mQTT.Publish("SensorObject", Jsonresult);

                    //publish json List of Objectss

                    var    resultList     = Sensor.CreateSensorList();
                    string JsonresultList = JsonConvert.SerializeObject(resultList);
                    mQTT.Publish("SensorList", JsonresultList);
                }


                Thread.Sleep(10000);
            }
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            //Intailize the Broker Settings
            BrokerModel _Broker = new BrokerModel();

            _Broker.Url           = "tailor.cloudmqtt.com";
            _Broker.Username      = "******";
            _Broker.Password      = "******";
            _Broker.Port          = 11300;
            _Broker.SSLPort       = 21300;
            _Broker.WebSocketPort = 31300;

            //Connect to Server
            MQTT mQTT = new MQTT();

            mQTT.Initailize(_Broker);
            mQTT.Connect();
            mQTT.SubscribeEventHandler(client_MqttMsgPublishReceived);
            mQTT.Subscribe("StringValue");
            mQTT.Subscribe("SensorObject");
            mQTT.Subscribe("SensorList");
        }
Exemplo n.º 25
0
        private async void btnTestar_Clicked(object sender, EventArgs e)
        {
            try
            {
                List <MQTT> configs = new List <MQTT>();
                if (await Storage.FileExistAsync("MQTTMobileConfig"))
                {
                    var Json = await Storage.ReadAllTextAsync("MQTTMobileConfig");

                    configs = JsonConvert.DeserializeObject <List <MQTT> >(Json);
                }
                MQTT selecionado = configs.Where(x => x.Usar).First();

                MqttClient client = new MqttClient(selecionado.Servidor, selecionado.Porta, false, null, null, MqttSslProtocols.None);
                client.Connect(Guid.NewGuid().ToString(), selecionado.Usuario, selecionado.Senha);
                txtstatus.Text = "Servidor Conectado";
            }
            catch (Exception)
            {
                txtstatus.Text = "Nao foi Possivel Conectar ao Servidor";
            }
        }
Exemplo n.º 26
0
        private void MqttClient_Connected(object sender, EventArgs e)
        {
            Application.Current.Dispatcher.Invoke((new Action(() =>
            {
                MQTT.AppendText("已连接到MQTT服务器!" + Environment.NewLine);
            })));

            string topic = "/ros_planned_path";

            if (!mqttClient.IsConnected)
            {
                MessageBox.Show("MQTT客户端尚未连接!");
                return;
            }
            mqttClient.SubscribeAsync(new List <TopicFilter> {
                new TopicFilter(topic, MqttQualityOfServiceLevel.AtMostOnce)
            });
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                MQTT.AppendText($"已订阅[{topic}]主题" + Environment.NewLine);
            }));
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            mqtt = MQTTConfig.LerConfig();
            bd   = BDConfig.LerConfig();
            switch (bd.Tipo)
            {
            case TipoBD.SQLServer:
                ServidorSQLServer(bd);
                break;

            case TipoBD.PostgreSQL:
                ServidorPostgreSQL(bd);
                break;

            case TipoBD.MySQL:
                ServidorMySQL(bd);
                break;

            case TipoBD.MongoDB:
                ServidorMongoDB(bd);
                break;
            }
            ServidorMQTT(mqtt);
        }
Exemplo n.º 28
0
        private async void getConfig()
        {
            try
            {
                List <MQTT> configs = new List <MQTT>();
                if (await Storage.FileExistAsync("MQTTMobileConfig"))
                {
                    var Json = await Storage.ReadAllTextAsync("MQTTMobileConfig");

                    configs = JsonConvert.DeserializeObject <List <MQTT> >(Json);
                }
                MQTT selecionado = configs.Where(x => x.Usar).First();

                MqttClient client = new MqttClient(selecionado.Servidor, selecionado.Porta, false, null, null, MqttSslProtocols.None);
                client.Connect(Guid.NewGuid().ToString(), selecionado.Usuario, selecionado.Senha);
                client.Subscribe(new string[] { "#" }, new byte[] { 0 });
                client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
                status = "Servidor Conectado";
            }
            catch (Exception)
            {
                status = "Nao foi Possivel Conectar ao Servidor";
            }
        }
Exemplo n.º 29
0
 void Awake()
 {
     _instance = this;
 }
Exemplo n.º 30
0
 public void OnGet()
 {
     MQTT.Init();
 }