from microbit import *

#*****************************WIFI模块内部代码***************************************************
class Obloq(object):
    ip_address = ''
    def connectWifi(self,SSID,PASSWORD,TIME):
        uart.write('AT+RST\r\n')
        sleep(5000) 
        uart.write('AT+CWMODE_CUR=3\r\n')
        sleep(1000) 
        uart.write('AT+CWJAP_CUR="%s","%s"\r\n' %(SSID, PASSWORD))      # 设置wifi模块连接无线网络
        # display.scroll("wait...");display.show(Image.HAPPY)
        sleep(8000) 
        return True
        uart.write('AT+CIPMUX=0\r\n');sleep(500)                   # 设置WIFI模块单路链接模式
        uart.write('AT+CIPSTART="TCP","0",0\r\n');sleep(TIME)   
        if uart.any():                                              #第二次读，返回服务器IP设置消息
            data = str(uart.read(), "UTF-8");sleep(1000)    
        uart.write('AT+CIFSR\r\n');sleep(2000);data=0               # 设置这个后 读串口返回绑定ip 
        if uart.any():
            data = str(uart.read(), "UTF-8")
            temp = data.split("\"",5)
            self.ip_address = temp[1]
            if self.ip_address[0]=='1' and len(self.ip_address)>10: 
                return True
            else:
                display.show(".");sleep(3000)
                return False     
        else:
            display.show(".");sleep(3000)
            return False
                        
    def ifconfig(self):
        return self.ip_address
               
    def httpSet(self,IP,PORT):
        uart.write('AT+CIPSTART="TCP","%s",%s\r\n' %(IP, PORT))  
        sleep(6000)
        uart.write('AT+CIPMODE=1\r\n')  # 设置WIFI模块为透穿模式
        sleep(500)
        uart.write('AT+CIPSEND\r\n')  # 在透穿模式下开始发送数据
        sleep(3000)
        if uart.any():  # 如果串口有值
            self.res = str(uart.read(), "UTF-8")
            self.res = 0
      
    def get(self,url,time):
        uart.write('GET /'+ url + '\r\n\r\n')  
        sleep(1000)
        if uart.any():  # 如果串口有值
            res = str(uart.read(), "UTF-8")  
            return (200,res)
        return (404,"NOT FOUND")
  
Obloq = Obloq()
#***********************************************************************************************

IP="192.168.60.108"   
PORT="8080"
SSID="haoda7"
PASSWORD="0123456789"

uart.init(baudrate=115200, bits=8, parity=None, stop=1, tx=pin2, rx=pin1)  # 设置串口引脚，连接到wifi模块

while Obloq.connectWifi(SSID,PASSWORD,10000) != True:
    display.show(".")

display.scroll(Obloq.ifconfig())
Obloq.httpSet(IP,PORT)

while True:
    erron,resp = Obloq.get('input?id=1&val=' + str("%.1f"%(pin0.read_analog()*3.3/10.24)), 10000) 
    if erron == 200:
        display.scroll(resp)
    else:
        display.scroll(str(erron))
    sleep(1000*5)


     
    
    
