Ejemplo n.º 1
0
        private static async Task PublishTestMessage <T>(T payload, string topicSettingKey)
        {
            var configuration = Utils.ConfigBuilder.Build();

            var options = configuration.GetSection("MQTT")
                          .Get <MqttClientOptions>();

            var topic = configuration[topicSettingKey];

            var logger = LoggerFactory.Create(c => c.AddConsole()).CreateLogger <MqttClient>();

            using (var mqttClient = new MqttClient(Options.Create(options), logger))
            {
                var waitToken = new CancellationTokenSource();
                await mqttClient.Connect("test", () =>
                {
                    waitToken.Cancel();
                    return(Task.CompletedTask);
                });

                try
                {
                    await Task.Delay(8000, waitToken.Token); // Wait connection to be stablished
                }
                catch { }

                await mqttClient.Subscribe(topic, (message) =>
                {
                    var content = Encoding.UTF8.GetString(message.ApplicationMessage.Payload);
                    logger.LogInformation($"Topic {message.ApplicationMessage.Topic}. Message {content}");
                    return(Task.CompletedTask);
                });

                if (payload is string)
                {
                    await mqttClient.Publish(topic, payload as string);
                }
                else
                {
                    await mqttClient.Publish(topic, payload);
                }
                await Task.Delay(5000);

                await mqttClient.Close();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Close a client
        /// </summary>
        /// <param name="client">Client to close</param>
        private void CloseClient(MqttClient client)
        {
            if (this.clients.Contains(client))
            {
                // if client is connected and it has a will message
                if (!client.IsConnected && client.WillFlag)
                {
                    // create the will PUBLISH message
                    MqttMsgPublish publish =
                        new MqttMsgPublish(client.WillTopic, Encoding.UTF8.GetBytes(client.WillMessage), false, client.WillQosLevel, false);

                    // publish message through publisher manager
                    this.publisherManager.Publish(publish);
                }

                // if not clean session
                if (!client.CleanSession)
                {
                    List <MqttSubscription> subscriptions = this.subscriberManager.GetSubscriptionsByClient(client.ClientId);

                    if ((subscriptions != null) && (subscriptions.Count > 0))
                    {
                        this.sessionManager.SaveSession(client.ClientId, client.Session, subscriptions);

                        // TODO : persist client session if broker close
                    }
                }

                // delete client from runtime subscription
                this.subscriberManager.Unsubscribe(client);

                // close the client
                client.Close();

                // remove client from the collection
                this.clients.Remove(client);

                mqttBridge.OnClientDisconnect(client);
            }
        }
Ejemplo n.º 3
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "Connect")
            {
                if (client == null)
                {
                    client = new MqttClient("test.mosquitto.org");
                }
                listBox1.Items.Add("=============================================");

                client.PublishReceived += MqttMsgPubRecv;
                client.Subscribed      += MqttMsgSubscribed;
                client.Unsubscribed    += MqttMsgUnsubscribed;
                client.Connect();

                if (client.IsConnected)
                {
                    listBox1.Items.Add("Connection established.");
                    listBox1.Items.Add("Create a topic now and subscribe to it!");
                }
                else
                {
                    listBox1.Items.Add("Connection failed. No internet?");
                    return;
                }

                button1.Text    = "Disconnect";
                button3.Enabled = true;
            }
            else if (button1.Text == "Disconnect")
            {
                client.Close();
                client.Disconnect();
                client          = null;
                button1.Text    = "Connect";
                button2.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
            }
        }
        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
        }