#!/usr/bin/python
# coding=UTF-8
import RPi.GPIO as GPIO
import serial
import time
from threading import Timer
from EC200U import*      
rec_buff = ''
APN = 'CMNET'
ServerIP = '47.92.146.210'
Port = '9999'
Message = 'hello mozihao'
wenshidu={'wendu':23,'shidu':42}
class EC200UCtr:#发AT指令控制模块
    def EC200U_AT(self):
        while(ec200u.ATinit('ATE0\r\n','OK')==0):#判断模块是否存在
            pass
        while(ec200u.ATinit('AT+CIMI\r\n','460')==0):#判断卡是否存在
            pass
        while(ec200u.ATinit('AT+CGATT?\r\n','+CGATT: 1')==0):#判断是否注册网络成功
            pass
        ec200u.ATSignle('AT+QIACT=1\r\n','OK')
        ec200u.ATSignle('AT+QIACT?\r\n','+QIACT:')#GET IP address
        ec200u.ATSignle('at+qiclose=0\r\n','OK')#对上一次连接断开，不需要判断是否关闭成功
        if ec200u.ATSignle('AT+QIOPEN=1,0,\"UDP\",\"'+ServerIP+'\",'+Port+',0,1\r\n','+QIOPEN: 0,0')==1:#连接TCP服务器，并确认连接状态
            self.tcpconok=1#连接上服务器了
        else:
            self.tcpconok=0#fail
    def EC200U_REC(self):
        if b'+QIURC:' in ec200u.rxData:#rec data from server
            recvalue=ec200u.rxData.find(b'LED10')#LED1 OFF
            if recvalue!=-1:#
                GPIO.output(20,GPIO.LOW)
                print('LED10')
            recvalue=ec200u.rxData.find(b'LED11')#LED1 ON
            if recvalue!=-1:#
                GPIO.output(20,GPIO.HIGH)
                print('LED11')
            recvalue=ec200u.rxData.find(b'LED20')#LED2 OFF
            if recvalue!=-1:#
                GPIO.output(21,GPIO.LOW)
                print('LED20')
            recvalue=ec200u.rxData.find(b'LED21')#LED2 ON
            if recvalue!=-1:#
                GPIO.output(21,GPIO.HIGH)
                print('LED21')
        ec200u.rxData=''
ec200u=EC200U('/dev/ttyS0',115200)
ec200uctr=EC200UCtr()
ec200uctr.EC200U_AT()
GPIO.setmode(GPIO.BCM)
GPIO.setup(20,GPIO.OUT)#LED1
GPIO.setup(21,GPIO.OUT)#LED2
wenshidu['wendu']=12#key zidian
wenshidu['shidu']=88#key zidian
while True:
    if ec200uctr.tcpconok==1:#conn
         if(ec200u.TCPSend(str('AT+QISEND=0,')+str(len(str(wenshidu)))+'\r\n','>')==1):#发送数据长度
             if(ec200u.TCPSend(str(wenshidu),'SEND OK')==1):#发送数据成功
                 print("data send is OK")
                 time.sleep(1)#单位是s
                 ec200uctr.EC200U_REC()
         
         