Пример #1
0
        public static void Publish(string topic, object message, byte qos = 0, bool retain = false)
        {
            // {
            //  "CardId": "fd-a6-4a-95",
            //	"DeviceId": 6,
            //	"InLocation": 1,
            //	"SwipeTime": "2016-05-22T18:18:54Z"
            //}

            //var topic = $"location/{locationId}/movement";

            var jsonData = JsonConvert.SerializeObject(message);

            var data = Encoding.UTF8.GetBytes(jsonData);

            //var data = GetBytes(jsonData);

            if (_client == null || !_client.IsConnected)
            {
                _client = null;
                Connect();
            }

            _client?.Publish(topic, data);
        }
Пример #2
0
 private void Callback(object state)
 {
     _client.Publish(_settings.MqttTopic, Encoding.UTF8.GetBytes($"{DateTime.Now}"));
 }
Пример #3
0
 private void OnUnknownCommand(ReceivedCommand arguments)
 {
     MqttClient.Publish($"{m_TopicPrefix}/{m_UnknownCommandTopic}", Encoding.GetBytes(arguments.RawString));
 }
        static void Main(string[] args)
        {
            #region MQTT Client 資料上傳範例

            IPHostEntry wraIP = Dns.GetHostEntry("iapi.wra.gov.tw");

            MqttClient.ConnectConfig cc = new MqttClient.ConnectConfig()
            {
                IpAddress = wraIP.AddressList[0],
                Port      = 1883,
                UserName  = "",
                Password  = ""
            };

            MqttClient dps = new MqttClient(cc);

            dps.Open();
            Console.WriteLine("啟動MQTT連線");
            Console.ReadKey();

            if (!dps.IsConnected)
            {
                Console.WriteLine("連線失敗");
                Console.ReadKey();
            }

            //產生隨機數值
            Random rnd = new Random();

            //寫入物理量 Id
            Guid pqId = Guid.Parse("");
            Console.WriteLine("Publish Data..");

            for (int index = 0; index < 20; index++)
            {
                //Mqtt Payload 格式
                MqttClient.ObservationsPacket op = new MqttClient.ObservationsPacket()
                {
                    phenomenonTime = DateTime.Now.AddMinutes(-index).ToString("yyyyMMddTHHmmss+08"),
                    result         = 4 + rnd.NextDouble()
                };

                Console.WriteLine($"發送資料 {op.result.ToString()}");

                dps.Publish(pqId, op);
                Thread.Sleep(1000);
            }
            Console.WriteLine("Publish Data Finish.");
            Console.ReadKey();
            dps.Close();

            #endregion


            #region 初始化 OAuth2 Client and User API Client

            //初始化 OAuth2 Client
            _oAuth2Client = new OAuth2Client(_wraOAuth2UriRoot, _clientId, _clientSecret);

            //初始化 UserApi Client
            _userApiClient = new UserApiClient(_wraApiUriRoot, _oAuth2Client);

            #endregion


            #region ETL API 使用範例

            Console.WriteLine("\r\n-----讀取全部監測站群組------");
            IEnumerable <StationGroupInfo> stationGroupInfos = StationGroupGetAll();
            Console.ReadKey();

            //取得單一監測站群組
            Console.WriteLine($"\r\n-----使用監測站群組ID讀取單一監測站群組 {stationGroupInfos.First().Id.ToString() }------");
            StationGroupGet(stationGroupInfos.First().Id);
            Console.ReadKey();

            //取得全部監測站
            Console.WriteLine($"\r\n-----取得全部監測站------");
            IEnumerable <StationInfo> stationInfos = StationGetAll();
            Console.ReadKey();

            //取得單一監測站
            Console.WriteLine($"\r\n-----取得單一監測站 {stationInfos.First().Id.ToString() }------");
            StationGet(stationInfos.First().Id);
            Console.ReadKey();

            //取得全部物理量
            Console.WriteLine($"\r\n-----取得全部物理量------");
            IEnumerable <PhysicalQuantityInfo> physicalQuantityInfos = PhysicalQuantityGetAll();
            Console.ReadKey();

            //取得單一物理量
            Console.WriteLine($"\r\n-----取得單一物理量 {physicalQuantityInfos.First().Id.ToString() }------");
            PhysicalQuantityGet(physicalQuantityInfos.First().Id);
            Console.ReadKey();

            //讀取全部物理量即時資料
            Console.WriteLine($"\r\n-----讀取全部物理量即時資料------");
            LastestDataReadAll();
            Console.ReadKey();

            //讀取單一物理量即時資料
            Console.WriteLine($"\r\n-----讀取單一物理量即時資料 {physicalQuantityInfos.First().Id.ToString()}------");
            LatestDataReadPhysicalQuantity(physicalQuantityInfos.First().Id);
            Console.ReadKey();

            Console.WriteLine($"\r\n-----讀取單一監測站下所有物理量資料 Station Id: {stationInfos.First().Id.ToString()}");
            LastestDataReadStation(stationInfos.First().Id);
            Console.ReadKey();

            Console.WriteLine($"\r\n-----讀取單一監測站群組下所有物理量資料 StationGroup Id: {stationGroupInfos.First().ChildStationGroups.First().Id.ToString()}");
            LastestDataReadStationGroup(stationGroupInfos.First().ChildStationGroups.First().Id);
            Console.ReadKey();

            Console.WriteLine($"\r\n-----讀取單一物理量之歷史原始資料-------");
            TimeSeriesDataReadRawData(physicalQuantityInfos.First().Id);
            Console.ReadKey();

            Console.WriteLine($"\r\n-----讀取單一物理量之歷史彙總資料-------");
            DataSeriesEs dataSeries = TimeSeriesDataReadAggregratedData(Guid.Parse("38a666f9-dcc4-4259-b454-9313f95a9d0c"));
            Console.ReadKey();

            #endregion

            #region 可視化 API 使用範例

            Console.WriteLine($"\r\n----產生可嵌入圖表--------");
            ChartGenerate(dataSeries);
            Console.ReadKey();

            #endregion

            #region 雲端運算 API 使用範例

            int jobId = 40;
            Console.WriteLine($"\r\n----從 S3 上傳 Java 檔案至雲端運算資源--------");
            //jobId = SparkJobSubmit();
            Console.ReadKey();

            Console.WriteLine($"\r\n----取得工作列表-------");
            SparkJobList();
            Console.ReadKey();

            Console.WriteLine("\r\n----取得工作狀態-----");
            SparkJobStatus(jobId);
            Console.ReadKey();

            Console.WriteLine("\r\n----取得工作狀態-----");
            SparkJobStatus(jobId);
            Console.ReadKey();

            Console.WriteLine("r\n----取得工作紀錄-----");
            SparkJobLog(35);
            Console.ReadKey();

            #endregion

            #region 地理圖資 API

            Console.WriteLine($"\r\n----上傳檔案至地理圖資資料庫--------");
            RasterMapFileUpload();
            Console.ReadKey();

            Console.WriteLine($"\r\n----讀取地理圖資資料庫檔案列表--------");
            IEnumerable <FileDetails> fileDetails = RasterMapFileList();
            Console.ReadKey();

            Console.WriteLine($"\r\n----下載地理圖資檔案-------");
            RasterMapFileDownload(fileDetails.First().FileName);
            Console.ReadKey();

            Console.WriteLine($"\r\n----讀取地理圖資檔案 NetCDF ASCII--------");
            RasterMapNetCDFGet(fileDetails.First().FileName);
            Console.ReadKey();

            #endregion
        }
Пример #5
0
 public void PublishMessage(string Message)
 {
     var hasil = MqttClient.Publish(AppConstants.MqttTopic, Encoding.UTF8.GetBytes(Message), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
 }
Пример #6
0
        public static MqttClient publishMsgsAndWait(MqttClient client,
                                                    string messageType, string deviceId, int numMsgs,
                                                    string registryId, DateTime iat, int jwtExpiresMin,
                                                    string algorithm, string pass, string projectId,
                                                    string privateKeyFile, string clientId, int waitTime)
        {
            // Publish to the events or state topic based on the flag.
            string sub_topic = messageType == "event" ? "events" : "state";

            // The MQTT topic that this device will publish telemetry data to.
            // The MQTT topic name is required to be in the format below.
            // Note that this is not the same as the device registry's
            // Cloud Pub/Sub topic.
            string mqttTopic = $"/devices/{deviceId}/{sub_topic}";

            SetupMqttTopics(client, deviceId);

            //Publish num_messages mesages to the MQTT bridge once per second.
            for (var i = 1; i <= numMsgs; ++i)
            {
                string payload = string.Format("{0}/{1}-payload-{2}",
                                               registryId, deviceId, i);
                Console.WriteLine("Publishing {0} message {1}/{2}: '{3}'\n"
                                  , messageType, i, numMsgs, payload);
                var BinaryData = Encoding.Unicode.GetBytes(payload);

                // Refresh the connection credentials before the JWT expires.
                long secsSinceRefresh =
                    (DateTime.Now.Millisecond - iat.Millisecond) / 1000;
                if (secsSinceRefresh > 60 * jwtExpiresMin)
                {
                    Console.WriteLine("\tRefreshing token after: {0} seconds\n"
                                      , secsSinceRefresh);
                    iat = DateTime.Now;
                    if (algorithm == "RS256")
                    {
                        pass = CreateJwtRsa(projectId, privateKeyFile);
                    }
                    else if (algorithm == "ES256")
                    {
                        //TODO: needs to be implemented
                    }
                    else
                    {
                        throw new ArgumentException("Invalid algorithm {0}. " +
                                                    "Should be one of 'RS256' or 'ES256'", algorithm);
                    }
                    client.Disconnect();
                    client.Connect(clientId, "unused", pass);
                }

                // Publish "payload" to the MQTT topic. qos=1 means at least
                // once delivery. Cloud IoT Core also supports qos=0 for at
                // most once delivery.
                client.Publish(mqttTopic, BinaryData,
                               MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);

                if (messageType.Equals("event"))
                {
                    // Send telemetry events every second
                    System.Threading.Thread.Sleep(1000);
                }
                else
                {
                    // Note: Update Device state less frequently than with
                    // telemetry events
                    System.Threading.Thread.Sleep(5000);
                }
            }

            for (int i = 1; i < waitTime; i++)
            {
                Console.Write(".");
                System.Threading.Thread.Sleep(1000);
            }
            Console.WriteLine();
            return(client);
        }
Пример #7
0
 public void Poll()
 {
     _msgId   = _mqtt.Publish(_cmdIn, Encoding.UTF8.GetBytes("{}"));
     _msgPoll = true;
 }
Пример #8
0
 public void publish(string topic, string message)
 {
     Debug.Log("Publish: " + topic + "~ " + message);
     client.Publish(topic, System.Text.Encoding.UTF8.GetBytes(message), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
 }
Пример #9
0
        //PhanTich
        private void PhanTichImei(string filep, string fname)
        {
            try
            {
                //Tách ra các thông tin cần thiết trước

                string app_path = System.IO.Directory.GetCurrentDirectory();
                string kq       = "";
                int    stt      = 0;

                File.Copy(@filep, @app_path + @"/Temp/" + @fname, true);
                System.IO.StreamReader file = new System.IO.StreamReader(@app_path + "/Temp/" + @fname);

                while (file.EndOfStream != true)
                {
                    kq = file.ReadLine().Trim().ToLower();
                }
                file.Close();
                //Debug.WriteLine(kq);
                string Code = "OK";

                if (kq.Contains("alarm on"))
                {
                    stt = 0;
                    //Tách lấy error code
                    string[] ketqua1 = kq.Split('(');
                    string[] ketqua2 = ketqua1[1].Split(')');
                    Code = ketqua2[0];
                }
                if (kq.Contains("alarm off"))
                {
                    stt = 1;
                }

                //Xoa file khi k dùng đến
                File.Delete(@app_path + "/Temp/" + @fname);


                TbMachine.Rows[0]["LastTime"]  = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                TbMachine.Rows[0]["Status"]    = stt;
                TbMachine.Rows[0]["ErrorCode"] = Code;


                //Dù sao đi chăng nữa thì cũng Pub lên server thôi mà Man
                //Build Json rồi Pub lên kênh
                if (client.IsConnected)
                {
                    string abc = "[{\"LastTime\":\"" + TbMachine.Rows[0]["LastTime"] + "\",\"Name\":\"IMEI\",\"Status\":" + stt + ",\"ErrorCode\":\"" + Code + "\",\"Note\":\"" + Note + "\",\"Ip\":\"" + Ip + "\"}]";
                    client.Publish("hev", Encoding.UTF8.GetBytes(abc), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                    // Debug.WriteLine("Vừa pub dữ liệu lẻ lên server đó a");
                }
                else
                {
                    //Debug.WriteLine("K kết nối tới server");
                    log.Error("C160. Khong Publish du lieu len Server duoc");
                }
            }

            catch (Exception ex)
            {
                log.Error("Loi khi phan tich file log: " + ex);
            }

            finally
            {
                this.radGridView1.CurrentRow = null;
            }
        }
Пример #10
0
        public static void Main()
        {
            MqttClient client = null;
            string     clientId;
            bool       running = true;

            // Wait for Wifi/network to connect (temp)
            SetupAndConnectNetwork();

            // Loop forever
            while (true)
            {
                try
                {
                    string BrokerAddress = "192.168.2.129";
                    client = new MqttClient(BrokerAddress);

                    // register a callback-function (we have to implement, see below) which is called by the library when a message was received
                    client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
                    client.MqttMsgSubscribed      += Client_MqttMsgSubscribed;

                    // use a unique id as client id, each time we start the application
                    //clientId = Guid.NewGuid().ToString();
                    clientId = new Guid(1, 23, 44, 32, 45, 33, 22, 11, 1, 2, 3).ToString();

                    Debug.WriteLine("Connecting MQTT");

                    client.Connect(clientId);

                    Debug.WriteLine("Connected MQTT");
                    // Subscribe topics
                    //     client.Subscribe(new string[] { "Test1", "Test2" }, new byte[] { 2, 2 });

                    byte[] message = Encoding.UTF8.GetBytes("Test message");
                    client.Publish("/Esp32/Test1", message, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);

                    string[] SubTopics = new string[]
                    {
                        "/Automation/Lights/#"
                    };

                    Debug.WriteLine("Subscribe /Automation/Lights/#");
                    client.Subscribe(SubTopics, new byte[] { 2 });

                    Debug.WriteLine("Enter wait loop");
                    while (running)
                    {
                        Thread.Sleep(10000);
                        client.Publish("/Esp32/Test1", message, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                    }

                    client.Disconnect();
                }
                catch (Exception ex)
                {
                    // Do whatever please you with the exception caught
                    Debug.WriteLine("Main exception " + ex.Message);
                }

                // Wait before retry
                Thread.Sleep(10000);
            }
        }
Пример #11
0
 private void pubButton_Click(object sender, EventArgs e)
 {
     client.Publish(topicTextBox.Text, Encoding.UTF8.GetBytes(pubTextBox.Text));
 }
Пример #12
0
 void client_MqttMsgPublish(string topic, string msg)
 {
     client.Publish(topic, System.Text.Encoding.UTF8.GetBytes(msg), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
 }
Пример #13
0
 /// <summary>
 /// 버튼 클릭 현재 정보를 전달한다.
 /// </summary>
 /// <param name="topic">버튼 주소</param>
 public void SendPublishButtonData(string topic, string sendData)
 {
     client.Publish("siheung/namu/" + topic, System.Text.Encoding.Default.GetBytes(sendData));
 }
Пример #14
0
 private ushort PublishMessage(string topic, string msg)
 {
     return(_client.Publish(topic, Encoding.UTF8.GetBytes(msg)));
 }
Пример #15
0
        public static void Main()
        {
            MqttClient client = null;
            string     clientId;

            // Wait for Wifi/network to connect (temp)
            SetupAndConnectNetwork();

            // Loop forever
            while (true)
            {
                try
                {
                    client = new MqttClient(BrokerAddress);
                    // register a callback-function (we have to implement, see below) which is called by the library when a message was received
                    client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
                    client.MqttMsgSubscribed      += Client_MqttMsgSubscribed;
                    // use a unique id as client id, each time we start the application
                    //clientId = Guid.NewGuid().ToString();
                    clientId = Guid.NewGuid().ToString();

                    Debug.WriteLine("Connecting MQTT");

                    client.Connect(clientId, _token, "");

                    Debug.WriteLine("Connected MQTT");
                    // Subscribe topics
                    //     client.Subscribe(new string[] { "Test1", "Test2" }, new byte[] { 2, 2 });
                    var    buffer  = nanoFramework.Hardware.Stm32.Utilities.UniqueDeviceId;
                    byte[] message = Encoding.UTF8.GetBytes("{\"DeviceId\":\"" + Encoding.UTF8.GetString(buffer, 0, buffer.Length) + "\"}");
                    client.Publish("devices/" + clientId + "/attributes", message, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);

                    string[] SubTopics = new string[]
                    {
                        "/devices/" + clientId + "/rpc/request/+/+",
                        "/devices/" + clientId + "/attributes/update/"
                    };

                    Debug.WriteLine("Subscribe attributes and request");
                    client.Subscribe(SubTopics, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });

                    Debug.WriteLine("Enter wait loop");
                    while (client.IsConnected)
                    {
                        try
                        {
                            Thread.Sleep(10000);
                            message = Encoding.UTF8.GetBytes("{\"NowDateTime\":\"" + DateTime.UtcNow.ToString() + "\"}");
                            var result = client.Publish("devices/" + clientId + "/telemetry", message, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                            Debug.WriteLine(result.ToString());
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Publish exception " + ex.Message);
                        }
                    }

                    client.Disconnect();
                }
                catch (Exception ex)
                {
                    // Do whatever please you with the exception caught
                    Debug.WriteLine("Main exception " + ex.Message);
                }

                // Wait before retry
                Thread.Sleep(10000);
            }
        }
Пример #16
0
 //MQTT Senden von Nachrichten
 public void MQTTPublish(string channel, string msg)
 {
     mqtt.Publish(channel, Encoding.UTF8.GetBytes(msg));
 }
Пример #17
0
        static void Main(string[] args)
        {
            // Command line arguments
            var options = new Options();

            if (CommandLine.Parser.Default.ParseArgumentsStrict(args, options))
            {
                if (options.Help)
                {
                    Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options));
                    return;
                }
                //Console.WriteLine(options.Help);
            }

            DateTime dtnow = DateTime.Now;
            long     iat   = ((DateTimeOffset)dtnow).ToUnixTimeSeconds();
            long     exp   = iat + 3600; // Token expires in 3600 seconds, or whatever duration you need.

            var claims = new Dictionary <string, object>()
            {
                { "iat", iat }                 // Issued at
                , { "exp", exp }               // expiration time
                , { "aud", options.projectId } // audience is gcp project
            };

            X509Certificate x509_roots = new X509Certificate(currentExcutionPath + "\\" + sRoots);

            X509Certificate2 x509Certificate2 = new X509Certificate2(currentExcutionPath + "\\" + sP12Cert
                                                                     , sP12Pass
                                                                     , X509KeyStorageFlags.Exportable);

            string token = Jose.JWT.Encode(claims
                                           , x509Certificate2.PrivateKey
                                           , JwsAlgorithm.RS256); // Using RSA Signature with SHA-256 asymmetric algorithm


            MqttClient client = new MqttClient("mqtt.googleapis.com", // Google Cloud mqtt API host
                                               8883                   // ssl mqtt port
                                               , true                 // secure = true
                                               , x509_roots           //caCert,CA certificate for secure connection, the CA certificate used to sign the broker certificate you’ll connect to
                                               , x509Certificate2     //ClientCert,Client certificate
                                               , MqttSslProtocols.TLSv1_2
                                               );

            // Know if a subscription to a topic is completed and registered to the broker
            // client.MqttMsgSubscribed += client_MqttMsgSubscribed;

            // Subscribe to be notified about received messages,
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

            // event handler for published messages
            client.MqttMsgPublished += Client_MqttMsgPublished;

            // Building clientId as required by google mqtt
            String clientId = "projects/" + options.projectId + "/locations/" + options.cloudRegion + "/registries/" + options.registryId + "/devices/" + options.deviceId;
            String topic    = "/devices/" + options.deviceId + "/" + options.topic;


            // Username is null, authentication via JWT
            client.Connect(clientId, null, token);

            if (client.IsConnected)
            {
                //publish 10 messages
                for (int i = 0; i < 10; i++)
                {
                    Random rnd      = new Random(); // just a random number for sample date
                    string strValue = dtnow + "," + Convert.ToString(rnd.Next());
                    strValue = strValue + "-anything";

                    byte[] bMessage = Encoding.UTF8.GetBytes(strValue);

                    // This call returns immediately the id assigned to the message that will be sent shortly after.
                    // The library works in an asynchronous way with an internal queue and an internal thread for publishing messages.
                    // An error means that the client made more attempts to send the message but it couldn’t reach the broker
                    // of course this is true only for QoS level 1 and 2 where an acknowledge sequence from broker is expected
                    msgId = client.Publish(topic
                                           , bMessage
                                           , MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE
                                           , false); //publish a retained message if set to true

                    // 1000ms between each publish
                    System.Threading.Thread.Sleep(1000);
                }

                // Flushing queued messages to broker
                try
                {
                    client.Disconnect(); // Flush on disconnect
                }
                catch
                {
                    Console.WriteLine("Error publishing message(s)" + ", failed topic = " + topic);
                    Environment.Exit(0);
                }
                finally
                {
                    // do something if needed
                }
            }
            else
            {
                Console.WriteLine("Can not connect to project: {0} or connection lost.", options.projectId);
                Environment.Exit(0);
            }
        }
Пример #18
0
        static void MQClient_recievedMessage(object sender, MqttMsgPublishEventArgs e)
        {
            if (!GWisBusy)
            {
                GWisBusy = true;
                var message = Encoding.UTF8.GetString(e.Message);
                MQClient.Publish(GWApp.DeviceID + GWApp.MQTTSettings.StatusTopic, Encoding.UTF8.GetBytes(GWApp.MQTTSettings.Messages.WorkingOnConfig));


                if (e.Topic == GWApp.DeviceID + GWApp.MQTTSettings.ConfigTopic)
                {
                    try
                    {
                        GWConfig = JsonConvert.DeserializeObject <GWConfig>(message);

                        //LiteDatabase db = new LiteDatabase(@"C:\Temp\GW_Data.db");

                        //    File.SetAttributes(@"C:\Temp\GW_Data.db", FileAttributes.Normal);
                        //    var col = db.GetCollection<GWConfig>("Config");
                        //    col.Insert(GWConfig);


                        if (!GWConfig.VarOK())
                        {
                            MQClient.Publish(GWApp.DeviceID + GWApp.MQTTSettings.StatusTopic, Encoding.UTF8.GetBytes("Cannot update. Invalid format"));
                        }

                        //if (!(ConnectToPLC(GWConfig.PLC) == 0))
                        //{
                        //    MQClient.Publish("HSMA/IOTGW/status", Encoding.UTF8.GetBytes("something is wrong with the plc"));
                        //    GWisBusy = false;
                        //    return;
                        //}


                        GWisBusy      = false;
                        initialConfig = false;
                        GWConfig.InitTimer();
                    }
                    catch
                    {
                        MQClient.Publish(GWApp.DeviceID + GWApp.MQTTSettings.StatusTopic, Encoding.UTF8.GetBytes("Cannot update. Invalid format"));
                        GWisBusy = false;
                    }
                }
                else
                {
                    try
                    {
                        GWConfigUpdate = JsonConvert.DeserializeObject <GWConfigUpdate>(message);

                        if (initialConfig)
                        {
                            MQClient.Publish(GWApp.DeviceID + GWApp.MQTTSettings.StatusTopic, Encoding.UTF8.GetBytes("Cannot update if no config avaliable"));
                        }
                        else if (GWConfig.configID == GWConfigUpdate.ConfigID)
                        {
                            GWConfig.CancelTimer();
                            GWConfig.interval = GWConfigUpdate.interval;
                            GWConfig.InitTimer();
                        }
                        else
                        {
                            MQClient.Publish(GWApp.DeviceID + GWApp.MQTTSettings.StatusTopic, Encoding.UTF8.GetBytes("Cannot update. ID is not correct "));
                        }
                    }
                    catch
                    {
                        MQClient.Publish(GWApp.DeviceID + GWApp.MQTTSettings.StatusTopic, Encoding.UTF8.GetBytes("Cannot update. Invalid format"));
                    }

                    GWisBusy = false;
                }
            }
        }
 public void SendServerMessage(string topicName, string serverMessage)
 {
     client.Publish(topic, Encoding.Default.GetBytes(message));
 }
Пример #20
0
        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            string meldung = txtNickName.Text + ": " + txtMessage.Text;

            client.Publish("htlvillach/5AHIF", Encoding.UTF8.GetBytes(meldung));
        }
Пример #21
0
        static void Main(string[] args)
        {
            var mre = new ManualResetEvent(false);

            var options = new Options();

            if (!Parser.Default.ParseArguments(args, options))
            {
                Console.Error.WriteLine("Invalid options");
                Environment.Exit(-1);
            }

            var serialNumber = options.SerialNumberOverride ?? "DEFAULT_FAKE_SERIAL_NUMBER";

            var serialPort = new SerialPort(options.SerialPort, 9600, Parity.None, 8, StopBits.One);

            serialPort.Open();

            var client = new MqttClient(options.MqttBroker);

            client.MqttMsgPublished += (sender, e) =>
            {
                Console.WriteLine("Published message ID {0}", e.MessageId);
            };

            client.MqttMsgPublishReceived += (sender, e) =>
            {
                var data = Encoding.UTF8.GetString(e.Message);
                Console.WriteLine("Received message {0}", data);

                if (e.Topic.EndsWith("/serial") && serialPort.IsOpen)
                {
                    serialPort.Write(data);
                }
                else if (e.Topic.EndsWith("/quit"))
                {
                    serialPort.Close();
                    client.Disconnect();
                    mre.Set();
                }
            };

            Console.WriteLine("Connecting to {0}", options.MqttBroker);
            var clientId = Guid.NewGuid().ToString();

            client.Connect(clientId);

            Console.WriteLine("Subscribing to /devices/{0}/#", serialNumber);
            client.Subscribe(new[]
            {
                string.Format("/devices/{0}/#", serialNumber),
            }, new []
            {
                MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE,
            });

            Console.WriteLine("Publishing provisioning message for {0}", serialNumber);
            client.Publish(string.Format("/devices/provision/{0}", serialNumber), Encoding.UTF8.GetBytes(DateTimeOffset.Now.ToString()));


            Console.WriteLine("Waiting for messages...");
            mre.WaitOne();
            Console.WriteLine("Finished!");
        }
Пример #22
0
    void SendMessage(string topic, string message)
    {
//        Debug.Log("MQTT send message " + topic + " " + message);
        mqttClient.Publish(topic, System.Text.Encoding.UTF8.GetBytes(message), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
    }
Пример #23
0
 /// <summary>
 /// Callback method for the altitude timer
 /// </summary>
 /// <param name="state">not used</param>
 private static void AltitudeTimerCallback(object state)
 {
     CurrentAltitude = 44330.0 * (1.0 - Math.Pow(CurrentPressure / 1025.0, 0.1903));
     Console.WriteLine("Publishing altitude: " + CurrentAltitude);
     Client.Publish(AltitudeTopic, Encoding.UTF8.GetBytes(CurrentAltitude.ToString()));
 }
Пример #24
0
 public void WriteString(String topic, String data)
 {
     mqttClient.Publish(topic, Encoding.UTF8.GetBytes(data));
 }
Пример #25
0
 public void PublishMessage(string Message)
 {
     MqttClient.Publish(DataTopic, Encoding.UTF8.GetBytes(Message), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
 }
 public void SendRPCReply(TBRpcResponse rpcResponse)
 {
     client.Publish(RPC_RESPONSE_TOPIC + rpcResponse.RpcResponsetId, Encoding.UTF8.GetBytes(rpcResponse.ToJson()), QoS, false);
 }
Пример #27
0
        private static void ReadMeter(string mqttIP, string meterIP)
        {
            MeterReading   meterReading = new MeterReading();
            List <Reading> readings     = new List <Reading>();

            MqttClient MQTTClient = new MqttClient(IPAddress.Parse(mqttIP));

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

            MQTTClient.Connect(clientId);

            string context = "";

            string[] arrNames      = new string[] { "Energy, Active import", "Power, Active", "Power, Active, L1", "Power, Active, L2", "Power, Active, L3", "Voltage, L1", "Voltage, L2", "Voltage, L3", "Current, L1", "Current, L2", "Current, L3", "Frequency", "Power factor" };
            string[] arrShartNames = new string[] { "E", "P", "P1", "P2", "P3", "U1", "U2", "U3", "I1", "I2", "I3", "f", "cfi" };
            string[] arrUnits      = new string[] { "kWh", "W", "W", "W", "W", "V", "V", "V", "A", "A", "A", "Hz", "" };

            string[] arrValues = new string[arrNames.Length];

            try
            {
                context = new TimedWebClient {
                    Timeout = 10000
                }.DownloadString($"http://{meterIP}/static?path=/newsite/meterdata/");
            }
            catch
            {
                Console.WriteLine("Error reading meter, skipping");
                return;
            }

            //Get values for each measure exept Power factor
            for (int i = 0; i < arrNames.Length - 1; i++)
            {
                arrValues[i] = getValueByName(arrNames[i], context, ' ');
            }
            //Get values for Power factor
            arrValues[arrNames.Length - 1] = getValueByName(arrNames[arrNames.Length - 1], context, '<');

            //Write values into object
            for (int i = 0; i < arrNames.Length; i++)
            {
                Reading reading = new Reading(arrNames[i], arrShartNames[i], arrUnits[i], float.Parse(arrValues[i], CultureInfo.InvariantCulture.NumberFormat));
                readings.Add(reading);
            }


            meterReading.Readings = readings;

            string strJson = Newtonsoft.Json.JsonConvert.SerializeObject(meterReading);

            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strJson);

            //Print out values
            //Console.WriteLine(strJson);
            //for (int i = 0; i < arrNames.Length; i++)
            //{
            //    Console.WriteLine(arrNames[i] + ": " + arrValues[i]);
            //}

            //Send Values to MQTT broker
            MQTTClient.Publish($"meter/reading", bytes, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
            //for (int i = 0; i < arrNames.Length; i++)
            //{
            //    MQTTClient.Publish($"meter/{arrNames[i]}", Encoding.UTF8.GetBytes(arrValues[i]), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
            //}

            Console.Write("Done!! ");

            Console.WriteLine(DateTime.Now.ToString());



            string getValueByName(string valueName, string text, char delim)
            {
                string indexText       = valueName;
                int    indexTextLength = valueName.Length;
                int    indexStart      = text.IndexOf(indexText) + indexTextLength + 5;
                int    indexLength     = text.IndexOf(delim, indexStart) - indexStart;

                return(text.Substring(indexStart, indexLength));
            }
        }
Пример #28
0
 public void tester()
 {
     client.Publish("Gama", System.Text.Encoding.UTF8.GetBytes("Good, Bug fixed -> Sending from Unity3D!!! Good"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
 }
Пример #29
0
        private void CalcButton_Click(object sender, EventArgs e)
        {
            CalcButton.Enabled  = false;
            progressBar.Visible = true;
            _queryID            = Guid.NewGuid().ToString();

            DateTime calcstarttime = startTime.Value;
            DateTime calcendtime   = endtime.Value;

            string startTimeString = calcstarttime.ToString("yyyy-MM-dd H:mm:ss.fff");
            string endTimeString   = calcendtime.ToString("yyyy-MM-dd H:mm:ss.fff");

            string             topic           = "DBQUERY/" + _queryID;
            string             fulldescription = description.Text.Replace("%timestamp%", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt"));
            ComboBoxConnection conn            = (ComboBoxConnection)cb_connection.SelectedItem;

            // SQL Server version
            string query = "";

            switch (_dbtype)
            {
            case "SQLSERVER":
                query = "EXECUTE CalcStats @StartTime = '" + startTimeString + "',@EndTime = '" + endTimeString + "',@returnResults = 1";
                if (description.Text != "")
                {
                    query += ",@description='" + fulldescription + "'";
                }

                if (cb_connection.SelectedItem != null && cb_connection.SelectedIndex > 0)
                {
                    query += ",@connection = '" + conn.ID + "'";
                }

                if (device.Text != "")
                {
                    query += ",@device = '" + device.Text + "'";
                }

                if (chkSaveToDB.Checked)
                {
                    query += ",@saveOutput = 1";
                    if (outputtable.Text != "")
                    {
                        query += ",@outputTable = '" + outputtable.Text + "'";
                    }
                }
                else
                {
                    query += ",@saveOutput = 0";
                }
                break;

            case "POSTGRESQL":
            {
                // start time, end time, return results,description
                query = "SELECT * from calcstats('" + startTimeString + "','" + endTimeString + "',1::bit,'" + description.Text + "',";

                // connection filter
                if (cb_connection.SelectedItem != null && cb_connection.SelectedIndex > 0)
                {
                    query += "'" + conn.ID + "',";
                }
                else
                {
                    query += "null,";
                }

                // device filter
                if (device.Text != "")
                {
                    query += "'" + device.Text + "',";
                }
                else
                {
                    query += "null,";
                }

                // output table
                if (chkSaveToDB.Checked && outputtable.Text != "")
                {
                    query += "'" + outputtable.Text + "',";
                }
                else
                {
                    query += "null,";
                }

                // save to DB enabled
                if (chkSaveToDB.Checked)
                {
                    query += "1::bit";
                }
                else
                {
                    query += "0::bit";
                }

                query += ");";

                break;
            }
            }

            byte[] serializedQuery = Encoding.UTF8.GetBytes(query);

            // subscribe to the result
            _mqtt.Subscribe(new string[] { "DBQUERYRESULT/" + _queryID }, new byte[] { 0 });

            // publish the query request
            _mqtt.Publish(topic, serializedQuery);
        }
Пример #30
0
 public static async Task <ushort> PublishAsync(this MqttClient client, string topic, byte[] payload)
 {
     return(await Task.Run(() => client.Publish(topic, payload, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false)));
 }