---
# System prepended metadata

title: Untitled

---

## Line Notify 傳送訊息
我們利用line notify 傳送溫度與濕度的訊息至Line上 
```
    import network, ubinascii
    import time
    import urequests as requests
    import ntptime
    import ujson
    from machine import Pin, I2C, SoftI2C, ADC ,Timer
    from dht import DHT11
    import ssd1306
    wlan = network.WLAN(network.STA_IF)
    ssid = 'Wifi-user'
    passwd = 'Wifi-password'
    Linetoken     ="eDCyEx2s3fiRvSybdXbksV9Q2Zwja8nt2HLXkS1Kh7x" # 資料平台裝置的存取權限碼 #eDCyEx2s3fiRvSybdXbksV9Q2Zwja8nt2HLXkS1Kh7x #老師 r4vDLzxAzZGqbmY80mLVQbk986FjTE09ymyYG04qNfj
    timer_1 = Timer(1)
    def main():
        i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000)
        display = ssd1306.SSD1306_I2C(128, 64, i2c)
        active_wlan()
        #show_wifi()
        if connect_sta():
            print(f'\nConnected ssid {ssid}. Network config: {wlan.ifconfig()}')
        else:
            print(f'\nFailed. Not Connected to: {ssid}')

    #aqi, status = get_AQI()
    #print(f"花蓮 AQI {aqi} status {status}")
    if tw_ntp():
        print("Time Renew")
    else:
        print("Renew Fail")
    #while True:
    temp , humid = temperature()
    localtime = time.localtime()
    date_str = str(localtime[0])+"/" + str(localtime[1])+"/" + str(localtime[2])
    if localtime[4]<10:
        time_str = str(localtime[3])+":0"+str(localtime[4]) +":"+ str(localtime[5])
    else:
        time_str = str(localtime[3])+":"+str(localtime[4]) +":"+ str(localtime[5])
    temp_str  = f"Temp: {temp}"
    humid_str = f"Himid: {humid}"
    display.fill(0)  # 填充螢幕  0 = 全黑, 1 = 全亮
    display.text(date_str, 0, 0, 1)
    display.text(time_str, 0, 1*8, 1)
    display.text(temp_str, 0, 2*8, 1)
    display.text(humid_str, 0, 3*8, 1)
    display.show()
    lineNotifyMessage(Linetoken,temp_str)
    lineNotifyMessage(Linetoken,humid_str)
    time.sleep(360)

def active_wlan():
    active = wlan.active()
    if not active:
        wlan.active(True)

def show_wifi():
    scans = wlan.scan()
    for scan in scans:
        ssid = scan[0].decode()
        bssid = ubinascii.hexlify(scan[1],'.').decode()
        print(ssid, bssid)

def connect_sta():
    if wlan.isconnected():
        return True
    print(f'Trying to connect to {ssid}')
    wlan.connect(ssid, passwd)
    for retry in range(100):
        connected = wlan.isconnected()
        if connected:
            break
        time.sleep(0.1)
        print('.', end='')
    return connected


def get_flag():
    web = "https://flagtech.github.io/flag.txt"
    res = requests.get(web)
    if res.status_code == 200:
        print(f"{res.text}")
    else:
        print("Oops. Web Page Not Found")

def tw_ntp(host='clock.stdtime.gov.tw', must=False):
    """
    host: 台灣可用的 ntp server 如下可任選，未指定預設為 clock.stdtime.gov.tw
        tock.stdtime.gov.tw
        watch.stdtime.gov.tw
        time.stdtime.gov.tw
        clock.stdtime.gov.tw
        tick.stdtime.gov.tw
    must: 是否非對到不可
    """
    print("coneecting ntp server")
    ntptime.NTP_DELTA = 3155644800 # UTC+8 的 magic number
    ntptime.host = host
    count = 1
    if must:
        count = 100
    for _ in  range(count):
        try:
          ntptime.settime()
          print("connected ...")
        except:
          time.sleep(1)
          print('-', end='')
          continue
        else:
          return True
    return False

"""
example:
tw_ntp()              # 使用預設值
tw_ntp(must=True)     # 非對到時不可
tw_ntp(must=1)        # 同上
tw_ntp('tick.stdtime.gov.tw', 1) # 指定server，並強制對時
"""

url = "https://notify-api.line.me/api/notify"
def lineNotifyMessage(token, msg):
    print(f"token {token} message {msg}")
    headers = {"Content-Type": "application/x-www-form-urlencoded",
               "Authorization": "Bearer " + token}
    post_data = f"message={msg}"

    response = requests.post(url, headers = headers, data = post_data)
    print(response.text)
    if response.status_code<300: #"response.status_code.ok" is also good
        print("successed")
    else:
        print("[HTTPError]"+str(response.status_code))
    return response.status_code
def temperature():
    dht11 = DHT11(Pin(15))
    dht11.measure()                 # start to measure
    temp  = dht11.temperature()     # return the temperature
    humid = dht11.humidity()        # return the humidity
    temp_str  = f"Temp: {temp}"
    humid_str = f"Himid: {humid}"

    return temp_str , humid_str

main()

```
![](https://i.imgur.com/CvB6fIN.png)
