from machine import Pin,unique_id
import urequests as requests
import utime
import ubinascii
import sys, os
import urandom as random
import wlan
RECONNECT_INTERVAL = 60000 # millisecond
# Discord Webhook URL
discord_id = ""
discord_token = ""
WEBHOOK_URL = "https://discord.com/api/webhooks/" + discord_id + "/" + discord_token
if(sys.platform=="esp8266"):
led_pin = 2 # GPIO2(D4)
buzzer_pin = 5 # GPIO5(D1)
button_pin = 4 # GPIO4(D2)
elif(sys.platform=="esp32"):
led_pin = 2
buzzer_pin = 5
button_pin = 35
elif(sys.platform=="rp2"):
led_pin = "LED"
buzzer_pin = 15
button_pin = 21
def randint(min, max):
span = max - min + 1
div = 0x3FFFFFFF // span
offset = random.getrandbits(30) // div
val = min + offset
return val
# 發送訊息
def sendMessage(param_data):
headers = {"Content-Type": "application/x-www-form-urlencoded"
}
try:
wlan.connect_wifi() # Connecting to WiFi Router
print(param_data) # 顯示此訊息內容進行debug
response = requests.post(WEBHOOK_URL,
headers=headers,
data=param_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 + "!")
# Unique ID
CLIENT_ID = ubinascii.hexlify(unique_id())
print("Unique ID: ", end="")
print(CLIENT_ID)
# 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 = """content=This message is sent by "{:s}".""".format(os.uname().sysname)
sendMessage(payload)
led.off()
lastTime = utime.ticks_ms()
while True:
try:
currTime = utime.ticks_ms()
if (currTime - lastTime > RECONNECT_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\u00b0C" % (temp) # 🌡
Humi="Humi: %2d%%" % (humi) # 💧
payload = """content={:s}, {:s}..""".format(Temp,Humi)
sendMessage(payload)
button_down = False
led.off()
# Do other tasks while waiting for button press
utime.sleep_ms(100)
except KeyboardInterrupt:
print("Stop")
break