linfeng zhong
/
SIM_ByIrq
Using the interrupt function to dispose messages
main.cpp
- Committer:
- Zero_YI
- Date:
- 2017-11-29
- Revision:
- 0:0e1ee46c6ffb
File content as of revision 0:0e1ee46c6ffb:
#include "mbed.h" #include "string.h" #define MAX_READ_LEN 256 #define SEVER "122.5.17.146" #define PORT 9961 DigitalOut myled(LED1); Timer timer; Serial pc(USBTX,USBRX,9600); Serial sim(PA_9,PA_10,115200); char readBuf[MAX_READ_LEN]; int bufPtr; bool revOK; enum rxMode{ CMDMODE = 0; GPSMODE = 1; }; void uartIrq() { while(sim.readable()&&bufPtr<MAX_READ_LEN) { char buf = sim.getc(); if(buf!='\r'&&buf!='\n') { readBuf[bufPtr++] = buf; } if(buf=='\n') { readBuf[bufPtr] = 0; bufPtr = 0; revOK = true; } } } int getReply(uint16_t timeOut=1000) { int begin; timer.start(); begin = timer.read_ms(); while(!revOK) { if(timer.read_ms()-begin>timeOut) { timer.stop(); return 0; //time out; } } timer.stop(); revOK = false; return 1; } bool expectReply(char* eptReply,uint16_t timeOut,uint8_t mulNum=2) { for(int i=0;i<mulNum;i++) { getReply(timeOut); if(0!=strstr(readBuf,eptReply)) { return true; } } return false; } int sendCheckReply(char* cmd,char* reply,uint16_t timeOut=1000) { sim.printf("%s\r\n",cmd); return expectReply(reply,timeOut,5); } bool TCPconnect(char *server, uint16_t port) { if (! sendCheckReply("AT+CIPSHUT", "SHUT OK", 5000) ) return false; //pc.printf("%s\r\n",readBuf); if (! sendCheckReply("AT+CIPMUX=0", "OK") ) return false; sim.printf("AT+CIPSTART=\"TCP\",\"%s\",%d\r\n",server,port); if (! expectReply("OK",1000,2)) return false; if (! expectReply("CONNECT OK",1000,3)) return false; return true; } bool init() { for(int i=0;i<3;i++) { if(sendCheckReply("AT","OK")) { return true; } wait(0.5); } return false; } bool TCPsend(char*sendData) { if(sendCheckReply("AT+CIPSTATUS","CONNECT OK")) { sendCheckReply("AT+CIPSEND",">"); sim.printf("%s\r\n",sendData); sim.printf("%c\r\n",char(0x1a)); if(expectReply("SEND OK",1000,5)) { // pc.printf("SEND OK\r\n"); return true; } else { // pc.printf("SEND FAIL:%s\r\n",readBuf); return false; } } return false; } bool TCPclose() { if(sendCheckReply("AT+CIPCLOSE","CLOSE OK")) { return true; } else { return false; } } int main() { sim.attach(&uartIrq,Serial::RxIrq); pc.printf("Hello World!\r\n"); while(pc.readable()) pc.getc(); if(init()) pc.printf("init OK\r\n"); else pc.printf("init failed!please try again later!\r\n"); if(TCPconnect(SEVER,PORT)) pc.printf("TCPconnect OK\r\n"); else pc.printf("TCPconnect Fail\r\n"); if(TCPsend("I Love Juan")) pc.printf("Send OK\r\n"); else pc.printf("Send Fail\r\n"); while(1) { myled = !myled; wait(1); } }