Linux, 工作, 生活, 家人

Programming

Python 取得 PM2.5 和天氣資訊

最近終於將很久之前就說要架的室內 PM 2.5 偵測弄起來,上一版是用 Cacti 做的,但是有點過時了,這一版是用 Grafana + Prometheus 做的,看起來就漂亮多了

不過架上去之後的問題是,想比較數值,但是又不想再組一套系統出來,畢竟感測器也是成本,不如就用現成的氣象和環保局的數據吧,反正都只是參考用的,看個大概就好了

PM 2.5 的數據

這是取用 PM 2.5 Open Data 網站的數據,看起來是中研院架的,但是不知道為什麼是在 .org 下,不過沒關係,其中有提供很多來源,我自己是取用環保局的資料

環保局的資料有一個問題,並不是每個地方都有,所以我是選用土城的測站,因為離家最近

Open Data 的資料是 .gz ,不需要認證,所以用 urlopen 下載下來送到 gzip module 最後給 json 就可以解了,程式如下

這個數據是每 10 分鐘更新一次,所以每 10 分鐘抓一次即可

def getpm25():
     req = Request(PM25URL)
     req.add_header('Accept-Encoding','gzip')
     response = urlopen(req)
     content = gzip.decompress(response.read())
     my_object = json.loads(content.decode('utf-8'))
     item = my_object['feeds'] 
     for i in range(len(item)):     
         # print(item[i]['County'])     
         if item[i]['SiteName'] == "土城":         
            print(item[i])         
            print("PM25:", item[i]['PM2_5'])         
            print("PM10:", item[i]['PM10'])

天氣的數據

天氣的數據是取用中央氣象局的,目前 Google 到的資料也略有出入,所以我就寫個簡單的 Code 解出我要的資訊,應該可以更漂亮的解法,不過寫個 Sample 省大家時間也不錯

氣象局的資料要去氣象資料開放平台註冊,註冊完會給一組 API ,再利用這組 API Key 抓你要的資料,我這邊選用的是 JSON 格式
O-A0001-001 :資料型態,我這是即時氣象資料
Authorization=CWB-111111E2-1877-4711-2624-216276053413: API Key ,後面 KEY 要換成自己申請的
format=JSON,資料格式,還有其他的,但是我只有試 JSON

if localitem[j][‘elementName’] == “TEMP”: > 氣溫
elif localitem[j][‘elementName’] == “HUMD”: > 濕度

說明文件可以參考 中央氣象局開放資料平臺之資料擷取API ,有比較詳細的說明

def get_local_temperature():
     res = "https://opendata.cwb.gov.tw/fileapi/v1/opendataapi/O-A0001-001?Authorization=CWB-111111E2-1877-4711-2624-216276053413&format=JSON"
     with urllib.request.urlopen(res) as url:
         data = url.read()
         my_object = json.loads(data.decode('utf-8'))
         item = my_object['cwbopendata']['location']
         # print(item)
         for i in range(len(item)):
             # print(item[i])
             if item[i]['locationName'] == "鶯歌":
                 # print(item[i])             
                 # print(item[i]['weatherElement'])             
                 localitem = item[i]['weatherElement']             
                 for j in range(len(localitem)):                 
                     # print(localitem[j])                 
                     if localitem[j]['elementName'] == "TEMP":
                         print("Temp:", localitem[j]['elementValue']['value'])                 
                     elif localitem[j]['elementName'] == "HUMD":
                         print("RH:", localitem[j]['elementValue']['value'])

發佈留言