# Reference: https://qiita.com/kotaproj/items/3b974425dfa2579afdbc
from machine import Pin,unique_id
import time
import usocket as socket
import ussl as ssl
import ubinascii
import urandom as random
import os
import wlan
# discord webhook url
discord_id = "1293767438089060493"
discord_token = "K35zLOGAprFdegbyl_18kc3UtzUM4rJaANp9nrLlAGtZjpDgnUeeoxxqa5I8tMB8EWAq"
HOST = "discord.com" # 伺服器網址,不可動
API_URL = "/api/webhooks/" + discord_id + "/" + discord_token # 連線對象URL, 不可動
PORT = 443
button_down = False
button_up = False
GPIO_PIN = 2 # 使用D4腳位
def randint(min, max):
span = max - min + 1
div = 0x3FFFFFFF // span
offset = random.getrandbits(30) // div
val = min + offset
return val
# Function to handle button press interrupt (optional)
def button_press(pin):
global button_down
led2_pin.value(not led2_pin.value())
button_down = True
def sendMessage(param_data):
# 定義發送至伺服器的訊息內容
message_str = "POST " + API_URL + " HTTP/1.1\r\n" \
+ "Host: " + HOST + "\r\n" \
+ "Content-Length: " + str(len(param_data)) + "\r\n" \
+ "Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
+ param_data + "\r\n"
addr = socket.getaddrinfo(HOST, PORT)[0][-1] # 取得連線到伺服器的相關訊息
print(addr) # 顯示取得的address訊息內容
try:
Socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create STREAM TCP socket
print("connecting to server")
Socket1.connect(addr) # 與伺服器進行連線
print("server is connected")
time.sleep_ms(1000)
ssl_sock = ssl.wrap_socket(Socket1) # SSL wrap
ssl_sock.write(message_str) # send data
print("send done")
time.sleep_ms(1000)
Socket1.close() # 關閉與伺服器的連線,避免佔用端口。
except:
print("except")
time.sleep_ms(1000)
# Start Function
if __name__ == '__main__':
print(os.uname())
print("Hello, " + os.uname().sysname + "!")
# ESP32 unique ID
CLIENT_ID = ubinascii.hexlify(unique_id())
print("Unique ID: ", end="")
print(CLIENT_ID)
# Define GPIO pins for LED and push button
led1_pin = Pin(4, Pin.OUT)
led2_pin = Pin(2, Pin.OUT)
led1_pin.value(False)
led2_pin.value(False)
button_pin = Pin(35, Pin.IN, Pin.PULL_UP) # Internal pull-up resistor
# Attach interrupt to the push button pin
button_pin.irq(trigger=Pin.IRQ_FALLING, handler=button_press)
wlan.connect_wifi()
payload = """content=This message is sent by "{:s}".""".format(os.uname().sysname)
print(payload) # 顯示此訊息內容進行debug
sendMessage(payload) # 執行此函數
while True:
led1_pin.value(not led1_pin.value())
if button_down == True:
temp=randint(1,50)
humi=randint(1,100)
Temp="Temp: %2d\u00b0C" % (temp)
Humi="Humi: %2d%%" % (humi)
payload = """content={:s}, {:s}..""".format(Temp,Humi)
print(payload) # 顯示此訊息內容進行debug
sendMessage(payload) # 執行此函數
button_down = False
# Do other tasks while waiting for button press
time.sleep_ms(100)