import RPi.GPIO as GPIO
import serial
import time
# coding=UTF-8
class  EC200U:
    def __init__(self,port,baudrate):
        self.uart0 = serial.Serial(port,baudrate)#
        if self.uart0.isOpen == True:
            self.uart0.open()
            self.uart0.flushInput()
    def ATinit(self,ATcmd,OKcmd):#发AT指令给模块
         self.uart0.flushInput()
         self.uart0.write(ATcmd.encode())
         #self.uart0.write(b'\r\n')
         time.sleep(0.3)#单位是s
         self.rxData=''
         self.rxData = self.uart0.read(self.uart0.inWaiting())
         #print(rec_buff)
         #while self.uart0.any() > 0:
              #self.rxData += self.uart0.read(1).decode()#读取里面的内容
         print(self.rxData.decode())
         if OKcmd not in  self.rxData.decode():#返回的数据里面不在，表明读取异常
              return 0
         else:#读取正确
              return 1   
    def ATSignle(self,ATcmd,OKcmd):#发AT指令给模块,但每次只发一次,用户连接服务器
         self.uart0.write(ATcmd.encode())
         time.sleep(2)#单位是s
         self.rxData=''
         self.rxData = self.uart0.read(self.uart0.inWaiting())#读取里面的内容
         print(self.rxData.decode('utf-8','ignore'))
         if OKcmd not in  self.rxData.decode('utf-8','ignore'):#返回的数据里面不在，表明读取异常
               return 0
         else:#读取正确
               return 1
    def ATHEXSignle(self,ATcmd,OKcmd):#发AT指令给模块,但每次只发一次,用户连接服务器
         self.uart0.write(ATcmd)
         time.sleep(2)#单位是s
         self.rxData=''
         self.rxData = self.uart0.read(self.uart0.inWaiting())#读取里面的内容
         print(self.rxData.decode('utf-8','ignore'))
         if OKcmd not in  self.rxData.decode('utf-8','ignore'):#返回的数据里面不在，表明读取异常
               return 0
         else:#读取正确
               return 1
    def TCPSend(self,ATcmd,OKcmd):#发TCP数据到服务器
         self.uart0.write(ATcmd.encode())
         time.sleep(0.5)#单位是s
         #self.rxData=''
         self.rxData = self.uart0.read(self.uart0.inWaiting())#读取里面的内容
         print(self.rxData.decode())
         if OKcmd not in  self.rxData.decode():#返回的数据里面不在，表明读取异常
               return 0
         else:#读取正确
               return 1
    def TCPREC(self):#recieve server data
        #self.rxData=''
        self.rxData = self.uart0.read(self.uart0.inWaiting())#读取里面的内容
        print(self.recData.decode())
    def Writedata(self,data):
        self.uart0.write(data)
        
    
        
