# api: https://api.weatherapi.com/v1/current.json?q=Phitsanulok+&key=633d3d6016f241f194281252250402
import network
import time
import urequests as requests
api_key = '633d3d6016f241f194281252250402'
location ='Phitsanulok'
# Request URL
url = f'https://api.weatherapi.com/v1/current.json?q={location}+&key={api_key}'
#กำหนดข้อมูลรับรอง Wi-Fi (ชื่อเครือข่ายและรหัสผ่าน)
ssid = 'Wokwi-GUEST'
password = ''
# ssid = 'REPLACE_WITH_YOUR_SSID'
# password = 'REPLACE_WITH_YOUR_PASSWORD'
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF) #สร้างอินสแตนซ์ของ WLAN และเปิดใช้งานโหมดสถานี (STA)
sta_if.active(True)
sta_if.connect(ssid, password) # เชื่อมต่อกับเครือข่าย Wi-Fi โดยใช้ข้อมูลรับรองที่กำหนด
while not sta_if.isconnected(): #รอจนกว่าจะเชื่อมต่อกับ Wi-Fi สำเร็จ
print(".", end="")
time.sleep(0.1)
print(" Connected!") #เมื่อเชื่อมต่อสำเร็จ พิมพ์ข้อความ "Connected!"
while True:
try:
# Make the request
response = requests.get(url)
#Print the response code
print('Response code: ', response.status_code)
# Get response content
weather = response.json()
# Close the request
response.close()
# Print bulk weather data
print('Weather JSON: ', weather)
# Get specific weather data
weather_description = weather['current']['condition']['text']
print('Current weather: ', weather_description)
# Temperature and humidity
temperature_c = weather['current']['temp_c']
humidity = weather['current']['humidity']
print(f'Temperature in Celsius: {temperature_c:.2f}')
print(f'Humidity (%): {humidity:.2f}')
#Dew point
dewpoint_c = weather['current']['dewpoint_c']
print(f'Dewpoint temperature in Celsius: {dewpoint_c:.2f}')
# Precipitation
precipitation = weather['current']['precip_mm']
print(f'Precipitation in mm: {precipitation}')
# Wind
wind_speed = weather['current']['wind_kph']
print('Wind speed in kph:', wind_speed)
wind_direction = weather['current']['wind_dir']
wind_degree = weather['current']['wind_degree']
print('Wind direction & Wind_degree:', wind_direction, '&', wind_degree, 'degree' )
time.sleep(120)
except Exception as e:
# Handle any exceptions during the request
print('Error during request:', e)