from machine import Pin,unique_id
import urequests as requests
import utime
import ujson
import sys, os
import urandom as random
import wlan
# --- 設定區 ---
INTERVAL = 1000 # millisecond
user_id = ""
access_token = ""
WEBHOOK_URL = "https://api.line.me/v2/bot/message/push"
if(sys.platform=="esp8266"):
led_pin = 2 # GPIO2(D4)
button_pin = 4 # GPIO4(D2)
elif(sys.platform=="esp32"):
led_pin = 2
button_pin = 35
elif(sys.platform=="rp2"):
led_pin = "LED"
button_pin = 21
def randint(min, max):
span = max - min + 1
div = 0x3FFFFFFF // span
offset = random.getrandbits(30) // div
val = min + offset
return val
# 發送LINE訊息
def send_line_message(text):
headers = {"Content-Type": "application/json",
"Authorization": "Bearer " + access_token
}
payload = {"to": user_id,
"messages": [
{
"type": "text",
"text": text
}
]
}
# 將字典轉為 JSON 字串並發送 POST 請求
json_data = ujson.dumps(payload)
print("Send JSON:", json_data)
try:
wlan.connect_wifi() # Connecting to WiFi Router
response = requests.post(WEBHOOK_URL,
headers=headers,
data=json_data)
print("Response Status:", response.status_code)
print("Response Text:", response.text)
response.close()
print("Send success!")
except Exception as e:
print("Error sending message:", e)
# Function to handle button press interrupt (optional)
def button_press(pin):
global button_down
button_down = True
# Start Function
if __name__ == '__main__':
print(os.uname())
print("Hello, " + os.uname().sysname + "!")
# Define GPIO pins for LED and push button
led = Pin(led_pin, Pin.OUT)
led.off()
button = Pin(button_pin, Pin.IN, Pin.PULL_UP) # 按鍵接在 GPxx, Internal pull-up resistor
button_down = False
# Attach interrupt to the push button pin
button.irq(trigger=Pin.IRQ_FALLING, handler=button_press)
utime.sleep_ms(1000)
led.on()
payload = """This message is sent by "{:s}".""".format(os.uname().sysname)
send_line_message(payload)
led.off()
lastTime = utime.ticks_ms()
while True:
try:
currTime = utime.ticks_ms()
if (currTime - lastTime > INTERVAL):
lastTime = currTime
led.toggle()
if button_down == True:
led.on()
# 模擬溫濕度數據
temp = randint(20, 35) # 假設攝氏 20~35℃
humi = randint(40, 80) # 假設濕度 40~80%
Temp="Temp: %2d" % (temp)
Humi="Humi: %2d" % (humi)
payload = "{:s}, {:s}..".format(Temp,Humi)
send_line_message(payload)
button_down = False
led.off()
# Do other tasks while waiting for button press
utime.sleep_ms(100)
except KeyboardInterrupt:
print("Stop")
break