"""
1. 使用Wokwi模拟运行ESP8266,实现OLED屏幕显示**广州**疫情数据.
2. 数据接口使用MQTT服务,服务器地址:116.25.46.126  
   topic = "Bwulianwang212"  #mqtt的主题.
3. api接口为https://api.inews.qq.com/newsqa/v1/query/pubished/daily/list?adCode=440100&limit=1,
   请求方式:GET
"""

import network
import time
from machine import Pin,SoftI2C
import urequests
import ujson
import dht
from umqtt.simple import MQTTClient
from ssd1306 import SSD1306_I2C

#oled屏幕定义
i2c = SoftI2C(sda = Pin(12), scl = Pin(13))
oled = SSD1306_I2C(128, 64, i2c, addr = 0x3c)
#定义DHT温湿度传感器引脚
sensor = dht.DHT22(Pin(15))
# MQTT Server Parameters
MQTT_CLIENT_ID = "ESP8622_mcu"
MQTT_BROKER    = "116.25.46.126"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "Bwulianwang212"

#订阅主题 
def sub(t, m):
  print("接收到订阅消息")
  message_City = "City: GuangZhou" #显示城市
  string=ujson.loads(m.decode())#将订阅到的消息解析成字符串
  oled.fill(0)
  oled.text(message_City,0,0)
  oled.text("total", 0, 15)
  oled.text(str(string["total"]),64,15)
  oled.text("new", 0, 30)
  oled.text(str(string["new"]),64,30)
  oled.text("T", 0, 50)
  oled.text(str(string["temp"]),20,50)
  oled.text("H", 64, 50)
  oled.text(str(string["humi"]),84,50)
  oled.show()
def pub(t, m):
  client.publish(t, m)
#连接网络
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
  print(".", end="")
  time.sleep(0.1)
print(" Connected!")
#连接MQTT服务器
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub)#回调订阅函数
client.connect()
client.subscribe(MQTT_TOPIC)
print("Connected!")

oled.show()
while True:
  
  #读取温湿度数据
  sensor.measure()
  #读取疫情数据
  print("读取疫情数据 ", end="")
  try:
    response = urequests.get('https://api.inews.qq.com/newsqa/v1/query/pubished/daily/list?adCode=440100&limit=1')
    parsed = response.json()["data"]
    num_confirm= parsed[0]["confirm"]
    num_confirm_add = parsed[0]["yes_confirm_add"]

    #构造发布主题的消息
    message = ujson.dumps({
      "total": num_confirm,
      "new": num_confirm_add,
      "temp": sensor.temperature(),
      "humi": sensor.humidity(),
    })
    #发布MQTT消息
    pub(MQTT_TOPIC,message)#数据上传MQTT服务器
    print("发布MQTT消息成功")
    #接收订阅消息
    client.check_msg()
  except:
    print("error!try again!")
  time.sleep(3)