예제 #1
0
        public async Task <IActionResult> PutAirQuality(long id, AirQuality airQuality)
        {
            if (id != airQuality.AirQualityID)
            {
                return(BadRequest());
            }

            _context.Entry(airQuality).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AirQualityExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
예제 #2
0
        public async Task <ActionResult <AirQuality> > PostAirQuality(AirQuality airQuality)
        {
            _context.AirQualities.Add(airQuality);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetAirQuality", new { id = airQuality.AirQualityID }, airQuality));
        }
예제 #3
0
        private static AdaptiveCard GetCard(string place, string date, string AppKey)
        {
            //WeatherModel model = new Repository().GetWeatherData(AppKey, GetBy.CityName, place, Days.Five);
            AirQuality model = new AirQuality()
            {
                AreaNumber = 1, AQI = 32, AQICategory = "Good", ForecastDateTime = DateTime.Now, AreaName = "California", Pollutant = " Ozone (o3)", Ozone = 1.0, PMTen = 1.0, PMTwoFive = 2.5
            };
            var card = new AdaptiveCard("1.1");

            if (model != null)
            {
                //card.Speak = $"<s>Today the temperature is {model.current.temp_f}</s><s>Winds are {model.current.wind_mph} miles per hour from the {model.current.wind_dir}</s>";
                AddCurrentWeather(model, card);
                //AddForecast(place, model, card);
                return(card);
            }
            return(null);
        }
예제 #4
0
        public async Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs)
        {
            Console.WriteLine("handing message!");

            var payload = eventArgs.ApplicationMessage.Payload;


            var     json    = Encoding.UTF8.GetString(payload);
            JObject jObject = JObject.Parse(json);

            Console.WriteLine(json.ToString());
            return;

            var now = DateTime.Now;
            //  var nowLocal = DateTime.SpecifyKind(now, DateTimeKind.Local);
            var      nowLocal = now;
            DateTime dateTime = new DateTime(nowLocal.Year, nowLocal.Month, nowLocal.Day, nowLocal.Hour, 0, 0);

            //DateTime dateTime1 = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, dateNow.Hour, 0, 0);
            // dateNow = dateNow.AddHours(1);
            AirQuality air = new AirQuality()
            {
                PointId     = Guid.Parse((string)jObject["id"]),
                DateTime    = dateTime.AddHours(-1),
                Humidity    = (float)jObject["humidity"],
                Temperature = (float)jObject["temperature"],
                O3          = (float)jObject["O3"],
                CO          = (float)jObject["CO"],
                NO2         = (float)jObject["NO2"],
                SO2         = (float)jObject["SO2"],
                PM2_5       = (int)jObject["pm2_5"],
                PM10_0      = (int)jObject["pm10_0"],
            };

            // Console.WriteLine(JObject.FromObject(air).ToString());

            air.AQIInHour = _AQIHeper.GetAQIInHour(air);
            await _context.AirQualities.InsertOneAsync(air);
        }
예제 #5
0
        private static void AddCurrentWeather(AirQuality model, AdaptiveCard card)
        {
            var headerContainer = new AdaptiveContainer();
            var header          = new AdaptiveColumnSet();

            card.Body.Add(headerContainer);
            var headerColumn = new AdaptiveColumn();
            var textHeader   = new AdaptiveTextBlock();

            textHeader.Size    = AdaptiveTextSize.Medium;
            textHeader.Weight  = AdaptiveTextWeight.Bolder;
            textHeader.Text    = "AQMD Air Quality";
            headerColumn.Width = AdaptiveColumnWidth.Stretch;
            headerColumn.Items.Add(textHeader);
            header.Columns.Add(headerColumn);
            headerContainer.Bleed = true;
            headerContainer.Style = AdaptiveContainerStyle.Default;
            headerContainer.Items.Add(header);

            var bodyContainer = new AdaptiveContainer();
            var data          = new AdaptiveFactSet();

            data.Spacing = AdaptiveSpacing.ExtraLarge;
            data.Facts.Add(new AdaptiveFact()
            {
                Title = "Area Number", Value = model.AreaNumber.ToString()
            });
            data.Facts.Add(new AdaptiveFact()
            {
                Title = "Area Name", Value = model.AreaName.ToString()
            });
            data.Facts.Add(new AdaptiveFact()
            {
                Title = "AQI  Value", Value = model.AQI.ToString()
            });
            data.Facts.Add(new AdaptiveFact()
            {
                Title = "Reading Date", Value = model.ForecastDateTime.ToString()
            });
            data.Facts.Add(new AdaptiveFact()
            {
                Title = "AQI Category", Value = model.AQICategory.ToString()
            });
            data.Facts.Add(new AdaptiveFact()
            {
                Title = "Pollutants", Value = model.Pollutant.ToString()
            });
            bodyContainer.Items.Add(data);
            card.Body.Add(bodyContainer);
            var detailContainer = new AdaptiveContainer();

            detailContainer.Id = "details1";
            var info = new AdaptiveFactSet();

            info.Spacing = AdaptiveSpacing.ExtraLarge;
            info.Facts.Add(new AdaptiveFact()
            {
                Title = "Ozone", Value = model.Ozone.ToString()
            });
            info.Facts.Add(new AdaptiveFact()
            {
                Title = "PM 10", Value = model.PMTen.ToString()
            });
            info.Facts.Add(new AdaptiveFact()
            {
                Title = "PM 2.5", Value = model.PMTwoFive.ToString()
            });
            detailContainer.Items.Add(info);
            card.Body.Add(detailContainer);
            // body.Facts.Add(new AdaptiveFact() { Title = "Area Name", Value = model.AreaNumber.ToString() });

            //card.Actions.Add(new AdaptiveToggleVisibilityAction { Title = "Show Detail", TargetElements = new List<AdaptiveTargetElement> { "details1" } });
            //var showdetailContainer = new AdaptiveContainer();
            //var showDetailColumnSet = new AdaptiveColumnSet();
            //card.Body.Add(showdetailContainer);
            //var showDetailColumn = new AdaptiveColumn();
            //showDetailColumn.Id = "chevronDown4";
            //showDetailColumn.SelectAction.Type = "Action.ToggleVisibility";
            //showDetailColumn.SelectAction.Title = "show detail";
            //showDetailColumn.SelectAction. = "show detail";
            //var textHeader = new AdaptiveTextBlock();
            //textHeader.Size = AdaptiveTextSize.Medium;
            //textHeader.Weight = AdaptiveTextWeight.Bolder;
            //textHeader.Text = "AQMD Air Quality";
            //headerColumn.Width = AdaptiveColumnWidth.Stretch;
            //headerColumn.Items.Add(textHeader);
            //header.Columns.Add(headerColumn);
            //headerContainer.Bleed = true;
            //headerContainer.Style = AdaptiveContainerStyle.Default;
            //headerContainer.Items.Add(header);

            //card.Body.Add(headerContainer);

            //var headerColumn = new AdaptiveColumn();
            //var textHeader = new AdaptiveTextBlock();
            //textHeader.Size = AdaptiveTextSize.Medium;
            //textHeader.Weight = AdaptiveTextWeight.Bolder;
            //textHeader.Text = "AQMD Air Quality";
            //headerColumn.Width = AdaptiveColumnWidth.Auto;
            //headerColumn.Items.Add(textHeader);
            //header.Columns.Add(headerColumn);
            //headerContainer.Items.Add(header);

            //var currentContainer = new AdaptiveContainer();
            //currentContainer.Style = AdaptiveContainerStyle.Emphasis;
            //var current = new AdaptiveColumnSet();


            //card.Body.Add(currentContainer);



            //var currentColumn2 = new Column();
            //current.Columns.Add(currentColumn2);
            //currentColumn2.Size = "65";

            //string date = DateTime.Parse(model.current.last_updated).DayOfWeek.ToString();

            //AddTextBlock(currentColumn2, $"{model.location.name} ({date})", TextSize.Large, false);
            //AddTextBlock(currentColumn2, $"{model.current.temp_f.ToString().Split('.')[0]}° F", TextSize.Large);
            //AddTextBlock(currentColumn2, $"{model.current.condition.text}", TextSize.Medium);
            //AddTextBlock(currentColumn2, $"Winds {model.current.wind_mph} mph {model.current.wind_dir}", TextSize.Medium);
        }
예제 #6
0
        //get hour
        public int GetAQIInHour(AirQuality air)
        {
            int aqi = GetAQIwithO3(air.O3);

            aqi = Math.Max(aqi, GetAQIwithSO2(air.SO2));
            aqi = Math.Max(aqi, GetAQIwithCO(air.CO));
            aqi = Math.Max(aqi, GetAQIwithNO2(air.NO2));


            var arrAir = airQualityRepository.GetAirQualityNowLimit(air.PointId, 11);

            arrAir.Add(air);

            foreach (var item in arrAir)
            {
                Console.Write("\t" + item.PM2_5);
            }
            Console.WriteLine();



            List <float> arrPm2_5  = new List <float>(12);
            List <float> arrPm10_0 = new List <float>(12);

            for (int i = 0; i < 12; i++)
            {
                arrPm2_5.Add(0);
                arrPm10_0.Add(0);
            }

            var currentTime = air.DateTime;

            foreach (var item in arrAir)
            {
                var      time     = item.DateTime;
                TimeSpan duration = currentTime - time;
                if (duration.TotalHours > 11)
                {
                    continue;
                }
                Console.WriteLine("duration " + duration.TotalHours);
                arrPm2_5[(int)duration.TotalHours]  = item.PM2_5;
                arrPm10_0[(int)duration.TotalHours] = item.PM10_0;
            }

            foreach (var item in arrPm2_5)
            {
                Console.Write("\t" + item);
            }
            Console.WriteLine();
            var nowcastPm2_5 = GetNowcast(arrPm2_5);

            if (nowcastPm2_5 != -1)
            {
                aqi = Math.Max(aqi, GetAQIwithPM2_5(nowcastPm2_5));
            }

            var nowcastPm10_0 = GetNowcast(arrPm10_0);

            if (nowcastPm10_0 != -1)
            {
                aqi = Math.Max(aqi, GetAQIwithPM2_5(nowcastPm10_0));
            }

            return(aqi);
        }
예제 #7
0
        public async Task <IHttpActionResult> POST()
        {
            string postData = Request.Content.ReadAsStringAsync().Result;
            //剖析JSON
            var messageObject = isRock.LineBot.Utility.Parsing(postData).events.FirstOrDefault();

            if (!await VaridateSignature(Request))
            {
                isRock.LineBot.Utility.ReplyMessage(messageObject.replyToken, "驗證失敗", ChannelAccessToken);
                return(Ok());
            }

            //取得user說的話
            string message = messageObject.message.text;
            //回覆訊息
            string reply = string.Empty;
            //Message = "你說了:" + item.message.text;

            string       id       = string.Empty;
            LineUserInfo userInfo = GetUserInfoAndId(messageObject, out id);
            string       ownKey   = userInfo.userId + "Own";
            var          regex    = new Regex("\\D", RegexOptions.IgnoreCase);

            try
            {
                if (message == "大樂透")
                {
                    var numbers  = GetLetou();
                    var letouMsg = Letou.Instance.Compare(numbers);
                    reply  = $"給你一組幸運號碼: {numbers}\\n";
                    reply += letouMsg;
                }
                else if (message == "安安9527" || message == "9527安安" || message == "安安")
                {
                    Utility.ReplyMessageWithJSON(messageObject.replyToken, Demo.Show(), ChannelAccessToken);
                }
                else if (message.Contains("抽"))
                {
                    var beauty = Beauty.GetBeauty();
                    var random = new Random(new Random().Next(1, beauty.Count()));
                    var image  = beauty[random.Next(1, beauty.Count())];
                    Utility.ReplyImageMessage(messageObject.replyToken, image, image, ChannelAccessToken);
                    return(Ok());
                }
                else if (message.Contains("美食"))
                {
                    var eat  = new Eat();
                    var data = await eat.GetEatData(message.Replace("美食", ""));

                    var list = new List <TemplateModel>();

                    var model = new TemplateModel();
                    model.template         = new CarouselModel();
                    model.template.columns = new List <ThumbnailImageModel>();

                    foreach (var item in data.response.Where(x => x.restaurant != null).Take(10))
                    {
                        model.template.columns.Add(new ThumbnailImageModel()
                        {
                            thumbnailImageUrl = item.restaurant.cover_url,
                            title             = item.restaurant.name,
                            text          = item.address,
                            defaultAction = new UriModel()
                            {
                                label = "瀏覽網誌",
                                uri   = item.url.IndexOf('-') > 0 ? item.url.Substring(0, item.url.IndexOf('-')) : item.url
                            },
                            actions = new List <ActionModel>()
                            {
                                new UriModel()
                                {
                                    label = "導航",
                                    uri   = $"https://www.google.com.tw/maps/place/{item.restaurant.address}"
                                }
                            }
                        });
                    }
                    list.Add(model);

                    if (model.template.columns.Count > 0)
                    {
                        Utility.ReplyMessageWithJSON(messageObject.replyToken, JsonConvert.SerializeObject(list), ChannelAccessToken);
                    }
                    else
                    {
                        reply = "查無資料...";
                    }
                }
                else if (message.Contains("天氣"))
                {
                    var area = message.Replace("天氣", "").Replace("台", "臺").Trim();
                    var data = (await Weather.Instance.GetData()).records.location.FirstOrDefault(x => x.locationName.Contains(area));
                    var dic  = new Dictionary <string, string>();
                    foreach (var item in data.weatherElement.OrderBy(x => x.elementName))
                    {
                        foreach (var time in item.time)
                        {
                            var key = $"{time.startTime}~{time.endTime}";
                            if (!dic.Keys.Contains(key))
                            {
                                dic.Add(key, "");
                            }

                            switch (item.elementName)
                            {
                            case "Wx":
                                dic[key] += $"天氣:{time.parameter.parameterName}\\n";
                                break;

                            case "PoP":
                                dic[key] += $"降雨機率:{time.parameter.parameterName}%\\n";
                                break;

                            case "MinT":
                                dic[key] += $"低溫:{time.parameter.parameterName}C\\n";
                                break;

                            case "CI":
                                dic[key] += $"適度:{time.parameter.parameterName}\\n";
                                break;

                            case "MaxT":
                                dic[key] += $"高溫:{time.parameter.parameterName}C\\n";
                                break;

                            default:
                                break;
                            }
                        }
                    }

                    foreach (var item in dic)
                    {
                        reply += $"{item.Key}\\n{item.Value}";
                    }

                    if (reply == string.Empty)
                    {
                        reply = "查無資料... 試試台北天氣";
                    }
                }
                else if (message.ToLower().Contains("ubike"))
                {
                    var data = await UBike.Instance.GetAllData();

                    var mday        = data.FirstOrDefault().mday;
                    var refreshTime = new DateTime(Convert.ToInt16(mday.Substring(0, 4)), Convert.ToInt16(mday.Substring(4, 2)),
                                                   Convert.ToInt16(mday.Substring(6, 2)), Convert.ToInt16(mday.Substring(8, 2)),
                                                   Convert.ToInt16(mday.Substring(10, 2)), Convert.ToInt16(mday.Substring(12, 2)));
                    var location = message.ToLower().Replace("ubike", "").Trim();
                    if (location == "三重家")
                    {
                        foreach (var item in data.Where(x => x.sno == "1008" || x.sno == "1010"))
                        {
                            reply += $"[{item.sarea}-{item.sna}]車{item.sbi}空{item.bemp}\\n";
                        }

                        if (reply == string.Empty)
                        {
                            reply = "查無資料...";
                        }
                        else
                        {
                            reply += $"更新時間{refreshTime.ToString("yyyy/MM/dd HH:mm:ss")}";
                        }
                    }
                    else if (location.Contains("區"))
                    {
                        foreach (var item in data.Where(x => x.sarea == location))
                        {
                            reply += $"[{item.sarea}-{item.sna}]車{item.sbi}空{item.bemp}\\n";
                        }

                        if (reply == string.Empty)
                        {
                            reply = "查無資料...";
                        }
                        else
                        {
                            reply += $"更新時間{refreshTime.ToString("yyyy/MM/dd HH:mm:ss")}";
                        }
                    }
                    else if (location != string.Empty)
                    {
                        foreach (var item in data.Where(x => x.sna.Contains(location)))
                        {
                            reply += $"[{item.sarea}-{item.sna}]車{item.sbi}空{item.bemp}\\n";
                        }

                        if (reply == string.Empty)
                        {
                            reply = "查無資料...";
                        }
                        else
                        {
                            reply += $"更新時間{refreshTime.ToString("yyyy/MM/dd HH:mm:ss")}";
                        }
                    }
                }
                else if (message == "大樂透機率")
                {
                    reply = Letou.Instance.GetHighRateNumbers();
                }
                else if (message.Contains("大樂透"))
                {
                    var numbers = message.Split(' ')?[1];
                    if (numbers != null && numbers.Split(',').Count() == 6)
                    {
                        reply = Letou.Instance.Compare(numbers);
                    }
                }
                //else if (LuisMaster.HitLuis(message,out string luisMessage))
                //{
                //    reply = $"{luisMessage}";
                //}
                else if (message.Contains("打球了"))
                {
                    bool     isFriday = false;
                    DateTime date     = DateTime.Now;

                    if (date.DayOfWeek == DayOfWeek.Friday)
                    {
                        reply = $"今晚7點半,高品打老虎";
                    }
                    else
                    {
                        while (!isFriday)
                        {
                            if (date.DayOfWeek == DayOfWeek.Friday)
                            {
                                isFriday = true;
                            }
                            else
                            {
                                date = date.AddDays(1);
                            }
                        }

                        reply = $"{date.ToString("yyyy/M/d")} 星期五 晚上7點半, 高品集合~~";
                    }
                }
                else if (message == "猜數字")
                {
                    reply = $"{userInfo.displayName} 開始猜數字 , 請輸入: 4位數字 (ex:1234) , 時間20分鐘";
                    var number = new GuessNum().GenNum();
                    var policy = new CacheItemPolicy
                    {
                        AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(20)
                    };
                    cache.Set(ownKey, number, policy);
                    cache.Set($"{ownKey}Count", 0, policy);
                    cache.Remove(id);
                }
                else if (!regex.IsMatch(message) && message.Length == 4 && cache[ownKey] != null && cache[id] == null)
                {
                    var ans = cache[ownKey].ToString();
                    int.TryParse(cache[$"{ownKey}Count"].ToString(), out int count);
                    count++;
                    var compare = new GuessNum().Compare(ans, message, out string errorMessage);
                    if (compare.A == 4)
                    {
                        reply = $"恭喜你猜對了 : {message} [你一共猜了{count}次]";
                        cache.Remove(ownKey);
                        cache.Remove($"{ownKey}Count");
                    }
                    else if (errorMessage != string.Empty)
                    {
                        reply += $"{errorMessage}";
                    }
                    else
                    {
                        reply += $"{message}==>{compare.A} A {compare.B} B ...己經猜了{count}次";
                        cache[$"{ownKey}Count"] = count;
                    }
                }
                else if (message == "一起猜")
                {
                    reply = $"大家開始猜數字 , 請輸入: 4位數字 (ex:1234) , 時間20分鐘";
                    var number = new GuessNum().GenNum();
                    var policy = new CacheItemPolicy
                    {
                        AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(20)
                    };
                    cache.Set(id, number, policy);
                    cache.Set($"{id}Count", 0, policy);
                }
                else if (!regex.IsMatch(message) && message.Length == 4 && cache[id] != null)
                {
                    var ans = cache[id].ToString();
                    int.TryParse(cache[$"{id}Count"].ToString(), out int count);
                    count++;
                    var compare = new GuessNum().Compare(ans, message, out string errorMessage);
                    if (compare.A == 4)
                    {
                        reply += $"恭喜猜對了 : {message} [一共猜了{count}次]" +
                                 cache.Remove(id);
                        cache.Remove($"{id}Count");
                    }
                    else if (errorMessage != string.Empty)
                    {
                        reply += $"{errorMessage}";
                    }
                    else
                    {
                        reply += $"{message}==>{compare.A} A {compare.B} B ...己經猜了{count}次";
                        cache[$"{id}Count"] = count;
                    }
                }
                else if (message.Contains("PM2.5"))
                {
                    var word = message.Split('的');
                    if (word.Length == 2 && word[1].Contains("PM2.5"))
                    {
                        var area  = word[0].Replace("台", "臺");
                        var air   = new AirQuality();
                        var model = air.GetList().Where(x => x.county.Contains(area) || x.Site.Contains(area));
                        if (model.Count() > 0)
                        {
                            foreach (var item in model)
                            {
                                reply += $"{item.county}{item.Site}的PM2.5為[{item.PM25}], {item.Status}\\n";
                            }
                            reply += $"更新時間:{model.FirstOrDefault().DataCreationDate.Value}";
                        }
                        else
                        {
                            reply = "查無資料 , 有可能打錯關鍵字, 可以試試 新北市的PM2.5 或 三重的PM2.5";
                        }
                    }
                }

                //回覆API OK
                isRock.LineBot.Utility.ReplyMessage(messageObject.replyToken, $"{reply}", ChannelAccessToken);

                //Utility.ReplyMessageWithJSON(messageObject.replyToken,FlexMessage(), ChannelAccessToken);
                return(Ok());
            }
            catch (Exception ex)
            {
                //isRock.LineBot.Utility.ReplyMessage(messageObject.replyToken, $"{ex.Message}  \nitem.source.type {messageObject.source.type}", ChannelAccessToken);
                return(Ok());
            }
        }