+/rtos
git clone https://git.julia.blue/+/rtos
413cd76
master
1// Driver for ESP8266 module to act as a WiFi client or server 2// Currently restricted to one incoming or outgoing connection at a time 3// ESP8266 resources below: 4// General info and AT commands: http://nurdspace.nl/ESP8266 5// General info and AT commands: http://www.electrodragon.com/w/Wi07c 6// Vcc is a separate regulated 3.3V supply with at least 215mA 7// /------------------------------\ 8// | chip 1 8 | 9// | Ant 2 7 | 10// | enna processor 3 6 | 11// | 4 5 | 12// \------------------------------/ 13// Connects (#define below) TM4C123 on either UART1 (PB) or UART2 (PD) 14// Reset (#define below) on either PB5 or PB1 15 16// ESP8266 TM4C123 17// 1 URxD PD7 UART out of TM4C123, 115200 baud 18// 2 GPIO0 +3.3V for normal operation (ground to flash) 19// 3 GPIO2 +3.3V 20// 4 GND Gnd GND (70mA) 21// 5 UTxD PD6 UART out of ESP8266, 115200 baud 22// 6 Ch_PD chip select, 10k resistor to 3.3V 23// 7 Reset PB1 TM4C123 can issue output low to cause hardware reset 24// 8 Vcc regulated 3.3V supply with at least 70mA 25 26#include "esp8266.h" 27#include "fifo.h" 28#include "interrupts.h" 29#include "io.h" 30#include "printf.h" 31#include "std.h" 32#include "tivaware/gpio.h" 33#include "tivaware/hw_gpio.h" 34#include "tivaware/hw_ints.h" 35#include "tivaware/hw_memmap.h" 36#include "tivaware/hw_types.h" 37#include "tivaware/hw_uart.h" 38#include "tivaware/pin_map.h" 39#include "tivaware/rom.h" 40#include "tivaware/sysctl.h" 41#include <stdbool.h> 42#include <stdint.h> 43 44#ifndef PASSKEY 45#define PASSKEY "" 46#endif 47#ifndef SSID_NAME 48#define SSID_NAME "" 49#endif 50 51// ESP responses 52static const char * ESP8266_READY_RESPONSE = "\r\nready\r\n" ; 53static const char * ESP8266_OK_RESPONSE = "\r\nOK\r\n" ; 54static const char * ESP8266_ERROR_RESPONSE = "\r\nERROR\r\n" ; 55static const char * ESP8266_FAIL_RESPONSE = "\r\nFAIL\r\n" ; 56static const char * ESP8266_SENDOK_RESPONSE = "\r\nSEND OK\r\n" ; 57 58// Globals for UART driver 59bool ESP8266_EchoResponse = false; 60bool ESP8266_EchoCommand = false; 61bool ESP8266_ConnectionMux = false; 62 63#define FIFOSIZE 1024 // size of the FIFOs 64static FIFO * rxfifo ; 65static FIFO * rxdata_fifo ; 66static FIFO * txfifo ; 67 68// ESP8266 state 69uint16_t ESP8266_Server = 0 ;// server port, if any 70 71const char * ReceiveDataSearchString = "+IPD," ; 72static uint32_t ReceiveDataSearchIndex = 0 ; 73static uint32_t ReceiveDataState = 1 ;// 0 to disable filtering 74static uint32_t ReceiveDataStream = 0 ;// connection ID for received data 75static uint32_t ReceiveDataLen = 0 ;// receive data packet remaining size 76volatile uint32_t ESP8266_DataAvailable = 770 ;// received data (about to be) available 78volatile uint32_t ESP8266_DataLoss = 0 ;// lost data (for debugging) 79 80// State machine to filter out received data stream from UART Rx input 81// Inputs: character to check 82// returns true if data was filtered out, false otherwise 83static bool ReceiveDataFilter (char letter ) { 84switch (ReceiveDataState ) {// Filter FSM 85case 4 :// filter out data and put it into the right receive FIFO 86if (ReceiveDataLen ) { 87switch (ReceiveDataStream ) { 88case 0 : 89if (!fifo_try_put (rxdata_fifo ,letter )) {// overflow, data loss 90ESP8266_DataAvailable -- ; 91ESP8266_DataLoss ++ ; 92 } 93break ; 94// only one connection currently supported 95 } 96ReceiveDataLen -- ; 97return true; 98 } 99ReceiveDataState = 1 ;// restart 100// fall through to start searching again if data is done 101case 1 :// Look for +IPD 102if (letter == ReceiveDataSearchString [ReceiveDataSearchIndex ]) { 103// match letter 104ReceiveDataSearchIndex ++ ; 105if (ReceiveDataSearchString [ReceiveDataSearchIndex ]== 0 ) { 106// end of match string 107ReceiveDataState = ESP8266_ConnectionMux ?2 :3 ; 108ReceiveDataSearchIndex = 0 ; 109ReceiveDataStream = 0 ; 110ReceiveDataLen = 0 ; 111 } 112 }else { 113ReceiveDataSearchIndex = 0 ;// start over 114 } 115return false; 116case 2 :// look for connection ID (separated by comma) 117if (letter >='0' && letter <='9' ) { 118ReceiveDataStream = 119ReceiveDataStream * 10 + (letter - '0' );// add digit to ID 120 }else if (letter == ',' ) { 121ReceiveDataState = 3 ;// ID completed, move on 122 }else { 123ReceiveDataStream = 0 ; 124ReceiveDataState = 1 ;// error, start over 125 } 126return false; 127case 3 :// look for receive data size (separated by colon) 128if (letter >='0' && letter <='9' ) { 129ReceiveDataLen = 130ReceiveDataLen * 10 + (letter - '0' );// add digit to length 131 }else if (letter == ':' ) { 132ReceiveDataState = 4 ;// size complete, move on 133ESP8266_DataAvailable += 134ReceiveDataLen ;// mark as becoming available 135 }else { 136ReceiveDataStream = 0 ; 137ReceiveDataLen = 0 ; 138ReceiveDataState = 1 ;// error, start over 139 } 140return false; 141 } 142return false; 143} 144 145// Preprocessor magic to construct UARTx_ identifiers 146#define STR (x ) #x 147#define CONCAT (x ,y ,z ) x##y##z 148 149#define UART_STR (uart ) "UART" STR(uart) 150#define UART_NAME (uart ,identifier ) CONCAT(UART, uart, identifier) 151 152#define UART_ESP8266 (identifier ) HWREG(UART2_BASE + UART_##identifier) 153 154const uint32_t baud = 115200 ; 155void ESP8266_InitUART (int rx_echo ,int tx_echo ) { 156rxfifo = fifo_new (FIFOSIZE ); 157rxdata_fifo = fifo_new (FIFOSIZE ); 158txfifo = fifo_new (FIFOSIZE ); 159ESP8266_EchoResponse = rx_echo ; 160ESP8266_EchoCommand = tx_echo ; 161ROM_SysCtlPeripheralEnable (SYSCTL_PERIPH_UART2 ); 162while (!ROM_SysCtlPeripheralReady (SYSCTL_PERIPH_UART2 )) {} 163HWREG (GPIO_PORTD_BASE + GPIO_O_LOCK )= GPIO_LOCK_KEY ;// unlock port d 164HWREG (GPIO_PORTD_BASE + GPIO_O_CR ) |=0xFF ;// allow changes to PD7 165ROM_GPIOPinConfigure (GPIO_PD6_U2RX ); 166ROM_GPIOPinConfigure (GPIO_PD7_U2TX ); 167ROM_GPIOPinTypeUART (GPIO_PORTD_BASE ,GPIO_PIN_6 |GPIO_PIN_7 ); 168 169// Initialize the UART. Set the baud rate, number of data bit 170UART_ESP8266 (O_CTL ) &= 171 ~UART_CTL_UARTEN ;// Clear UART enable bit during config 172UART_ESP8266 (O_IBRD )= (80000000 /16 ) /baud ; 173UART_ESP8266 (O_FBRD )= ((64 * ((80000000 /16 ) %baud ))+ baud /2 ) /baud ; 174// UART_ESP8266(_IBRD_R) = 43; // IBRD = int(80,000,000 / (16 * 115,200)) 175// = int(43.403) UART_ESP8266(_FBRD_R) = 26; // FBRD = round(0.4028 * 64 ) 176// = 26 177UART_ESP8266 (O_LCRH )= 178 (UART_LCRH_WLEN_8 | 179UART_LCRH_FEN );// 8 bit word length, 1 stop, no parity, FIFOs enabled 180UART_ESP8266 (O_IFLS ) &= 181 ~0x3F ;// Clear TX and RX interrupt FIFO level fields 182UART_ESP8266 (O_IFLS )+= 183 (UART_IFLS_TX1_8 | 184UART_IFLS_RX1_8 );// RX and TX FIFO interrupt threshold >= 1/8th full 185UART_ESP8266 (O_IM ) |= 186 (UART_IM_RXIM |UART_IM_TXIM | 187UART_IM_RTIM );// Enable interupt on TX, RX and RX transmission end 188UART_ESP8266 (O_CTL ) |= 189 (UART_CTL_UARTEN |UART_CTL_RXE |UART_CTL_TXE );// Set UART enable bit 190} 191 192// Copies TX buffer (software defined FIFO) to uart 193void static ESP8266BufferToTx (void ) { 194uint8_t letter ; 195while (((UART_ESP8266 (O_FR )& UART_FR_TXFF )== 0 )&& 196 (!fifo_empty (txfifo ))) { 197fifo_try_get (txfifo ,& letter ); 198if (ESP8266_EchoCommand ) { 199uart_putchar (letter ); 200 } 201UART_ESP8266 (O_DR )= letter ; 202 } 203} 204 205// Copies uart fifo to RX buffer (software defined FIFO) 206static void ESP8266RxToBuffer (void ) { 207char letter ; 208while (((UART_ESP8266 (O_FR )& UART_FR_RXFE )== 0 )&& !fifo_full (rxfifo )) { 209letter = UART_ESP8266 (O_DR ); 210if (ESP8266_EchoResponse ) { 211uart_putchar (letter ); 212 } 213if (!ReceiveDataFilter (letter )) { 214fifo_try_put (rxfifo ,letter ); 215 } 216 } 217} 218 219// at least one of three things has happened: 220// hardware TX FIFO goes from 3 to 2 or less items 221// hardware RX FIFO goes from 1 to 2 or more items 222// UART receiver has timed out 223void uart2_handler (void ) { 224if (UART_ESP8266 (O_RIS )& UART_RIS_TXRIS ) {// hardware TX FIFO <= 2 items 225UART_ESP8266 (O_ICR )= UART_ICR_TXIC ;// acknowledge TX FIFO 226ESP8266BufferToTx (); 227if (fifo_empty (txfifo )) { 228UART_ESP8266 (O_IM ) &= ~UART_IM_TXIM ;// disable TX FIFO interrupt 229 } 230 } 231if (UART_ESP8266 (O_RIS )& UART_RIS_RXRIS ) {// hardware RX FIFO >= 2 items 232UART_ESP8266 (O_ICR )= UART_ICR_RXIC ;// acknowledge RX FIFO 233ESP8266RxToBuffer (); 234 } 235if (UART_ESP8266 (O_RIS )& UART_RIS_RTRIS ) {// receiver timed out 236UART_ESP8266 (O_ICR )= UART_ICR_RTIC ;// acknowledge receiver time out 237ESP8266RxToBuffer (); 238 } 239} 240 241static void esp_putc (char data ) { 242while (!fifo_try_put (txfifo ,data )) {}; 243UART_ESP8266 (O_IM ) &= ~UART_IM_TXIM ;// disable TX FIFO interrupt 244ESP8266BufferToTx (); 245UART_ESP8266 (O_IM ) |=UART_IM_TXIM ;// enable TX FIFO interrupt 246} 247 248static char esp_getc (void ) { 249uint8_t letter ; 250while (!fifo_try_get (rxfifo ,& letter )) {}; 251return letter ; 252} 253 254static void esp_puts (const char * command ) { 255int index = 0 ; 256while (command [index ]) {esp_putc (command [index ++ ]); } 257} 258 259bool ESP8266_WaitForResponse (const char * success ,const char * failure ) { 260char d ; 261const char * s = success ; 262const char * f = failure ; 263while ((!s || * s )&& (!f || * f )) {// end of search string reached? 264d = esp_getc (); 265if (s && (d == * s )) { 266s ++ ; 267 }else { 268s = success ;// start over 269if (s && (d == * s )) 270s ++ ;// match first char? 271 } 272if (f && (d == * f )) { 273f ++ ; 274 }else { 275f = failure ;// start over 276if (f && (d == * f )) 277f ++ ;// match first char? 278 } 279 } 280if (failure && !(* f )) 281return false; 282return true; 283} 284 285bool ESP8266_Init (bool rx_echo ,bool tx_echo ) { 286char c ; 287const char * s ; 288uint32_t timer = 1 ; 289 290ROM_IntDisable (INT_UART2 ); 291ESP8266_InitUART (rx_echo ,tx_echo ); 292ROM_GPIOPinTypeGPIOOutput (GPIO_PORTB_BASE ,GPIO_PIN_1 );// Reset pin 293 294// Hard reset 295ROM_GPIOPinWrite (GPIO_PORTB_BASE ,GPIO_PIN_1 ,0 ); 296busy_wait (7 ,ms (10 )); 297ROM_GPIOPinWrite (GPIO_PORTB_BASE ,GPIO_PIN_1 ,GPIO_PIN_1 ); 298 299// Wait for ready status with timeout 300// Use low-level UART communication, interrupts disabled 301s = ESP8266_READY_RESPONSE ; 302timer = 5000000 ;// around a 1-2s total timeout 303while (* s ) { 304while (timer && ((UART_ESP8266 (O_FR )& UART_FR_RXFE )!= 0 )) {timer -- ; } 305if (!timer ) 306break ; 307c = (char )(UART_ESP8266 (O_DR )& 0xFF ); 308if (rx_echo ) 309uart_putchar (c );// will print garbage 310if (c == * s ) { 311s ++ ; 312 }else { 313s = ESP8266_READY_RESPONSE ; 314if (c == * s ) 315s ++ ; 316 } 317 } 318ROM_IntPrioritySet (INT_UART2 ,4 <<5 ); 319ROM_IntEnable (INT_UART2 ); 320 321return timer ; 322} 323 324bool ESP8266_Connect (bool verbose ) { 325return ESP8266_Reset ()&& (verbose ?ESP8266_GetMACAddress () : true)&& 326 (verbose ?ESP8266_ListAccessPoints () : true)&& 327ESP8266_SetWifiMode (CLIENT )&& 328ESP8266_JoinAccessPoint (SSID_NAME ,PASSKEY )&& 329 (verbose ?ESP8266_GetIPAddress () : true); 330} 331 332bool ESP8266_SetConnectionMux (bool multiple ) { 333char TXBuffer [32 ]; 334sprintf (TXBuffer ,"AT+CIPMUX=%d\r\n" ,multiple ); 335esp_puts (TXBuffer ); 336if (ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,0 )) { 337ESP8266_ConnectionMux = multiple ; 338return true; 339 } 340return false; 341} 342 343bool ESP8266_StartServer (uint16_t port ,uint16_t timeout ) { 344ESP8266_SetConnectionMux (true); 345char TXBuffer [32 ]; 346sprintf (TXBuffer ,"AT+CIPSERVER=1,%d\r\n" ,port ); 347esp_puts (TXBuffer ); 348if (ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,0 )) { 349ESP8266_Server = port ; 350return ESP8266_SetServerTimeout (timeout ); 351 } 352return false; 353} 354 355bool ESP8266_StopServer (void ) { 356esp_puts ("AT+CIPSERVER=0\r\n" ); 357ESP8266_Server = 0 ; 358return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,0 )&& 359ESP8266_SetConnectionMux (false); 360} 361 362bool ESP8266_Reset (void ) { 363esp_puts ("AT+RST\r\n" ); 364return ESP8266_WaitForResponse (ESP8266_READY_RESPONSE ,0 ); 365} 366 367bool ESP8266_Restore (void ) { 368esp_puts ("AT+RESTORE\r\n" ); 369return ESP8266_WaitForResponse (ESP8266_READY_RESPONSE ,0 ); 370} 371 372bool ESP8266_GetVersionNumber (void ) { 373esp_puts ("AT+GMR\r\n" ); 374return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,0 ); 375} 376 377bool ESP8266_GetMACAddress (void ) { 378esp_puts ("AT+CIPSTAMAC?\r\n" ); 379return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,0 ); 380} 381 382bool ESP8266_SetWifiMode (uint8_t mode ) { 383char TXBuffer [32 ]; 384sprintf (TXBuffer ,"AT+CWMODE=%d\r\n" ,mode ); 385esp_puts (TXBuffer ); 386return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,0 ); 387} 388 389bool ESP8266_ListAccessPoints (void ) { 390esp_puts ("AT+CWLAP\r\n" ); 391return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,ESP8266_ERROR_RESPONSE ); 392} 393 394bool ESP8266_JoinAccessPoint (const char * ssid ,const char * password ) { 395esp_puts ("AT+CWJAP=\"" ); 396esp_puts (ssid ); 397esp_puts ("\",\"" ); 398esp_puts (password ); 399esp_puts ("\"\r\n" ); 400return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,ESP8266_FAIL_RESPONSE ); 401} 402 403bool ESP8266_QuitAccessPoint (void ) { 404esp_puts ("AT+CWQAP\r\n" ); 405return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,0 ); 406} 407 408bool ESP8266_GetIPAddress (void ) { 409esp_puts ("AT+CIFSR\r\n" ); 410return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,ESP8266_ERROR_RESPONSE ); 411} 412 413bool ESP8266_MakeTCPConnection (char * IPaddress ,uint16_t port ) { 414char TXBuffer [32 ]; 415esp_puts ("AT+CIPSTART=\"TCP\",\"" ); 416esp_puts (IPaddress ); 417sprintf (TXBuffer ,"\",%d\r\n" ,port ); 418esp_puts (TXBuffer );// open and connect to a socket 419return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,ESP8266_ERROR_RESPONSE ); 420} 421 422bool ESP8266_Send (const char * str ) { 423char TXBuffer [32 ]; 424if (ESP8266_ConnectionMux ) { 425sprintf (TXBuffer ,"AT+CIPSEND=%d,%d\r\n" ,0 ,strlen (str )); 426 }else { 427sprintf (TXBuffer ,"AT+CIPSEND=%d\r\n" ,strlen (str )); 428 } 429esp_puts (TXBuffer ); 430if (!ESP8266_WaitForResponse (">" ,ESP8266_ERROR_RESPONSE )) 431return false; 432esp_puts (str ); 433return ESP8266_WaitForResponse (ESP8266_SENDOK_RESPONSE , 434ESP8266_ERROR_RESPONSE ); 435} 436 437bool ESP8266_SendBuffered (const char * str ) { 438char TXBuffer [32 ]; 439if (ESP8266_ConnectionMux ) { 440sprintf (TXBuffer ,"AT+CIPSEND=%d,%d\r\n" ,0 ,strlen (str )); 441 }else { 442sprintf (TXBuffer ,"AT+CIPSEND=%d\r\n" ,strlen (str )); 443 } 444esp_puts (TXBuffer ); 445if (!ESP8266_WaitForResponse (">" ,ESP8266_ERROR_RESPONSE )) 446return false; 447esp_puts (str ); 448sprintf (TXBuffer ,"Recv %d bytes" ,strlen (str )); 449return ESP8266_WaitForResponse (TXBuffer ,ESP8266_ERROR_RESPONSE ); 450} 451 452bool ESP8266_Receive (char * buf ,uint32_t max ) { 453long sr ; 454uint8_t letter ; 455while (max > 1 ) { 456if (fifo_size (rxdata_fifo )|| 457ESP8266_DataAvailable ) {// data (about to be) available? 458while (fifo_try_get (rxdata_fifo ,& letter )== false) {}; 459sr = start_critical (); 460if (ESP8266_DataAvailable ) 461ESP8266_DataAvailable -- ; 462end_critical (sr ); 463if (letter == '\r' ) 464continue ; 465if (letter == '\n' ) 466break ; 467* buf = letter ; 468buf ++ ; 469max -- ; 470 }else {// wait for next packet or connection close 471if (!ESP8266_WaitForResponse (ReceiveDataSearchString , 472ESP8266_ConnectionMux ?"0,CLOSED" 473 :"CLOSED" )) { 474* buf = 0 ;// connection closed 475return false; 476 } 477while (esp_getc ()!= ':' ) {}// wait for DataAvailable to be updated 478 } 479 } 480* buf = 0 ;// terminate with null character 481return true; 482} 483 484bool ESP8266_ReceiveEcho () { 485long sr ; 486uint8_t letter ; 487while (true) { 488if (fifo_size (rxdata_fifo )|| 489ESP8266_DataAvailable ) {// data (about to be) available? 490while (fifo_try_get (rxdata_fifo ,& letter )== false) {}; 491sr = start_critical (); 492if (ESP8266_DataAvailable ) 493ESP8266_DataAvailable -- ; 494end_critical (sr ); 495if (letter == '\x03' )// ETX 496break ; 497uart_putchar (letter ); 498 }else {// wait for next packet or connection close 499if (!ESP8266_WaitForResponse (ReceiveDataSearchString , 500ESP8266_ConnectionMux ?"0,CLOSED" 501 :"CLOSED" )) { 502return false; 503 } 504while (esp_getc ()!= ':' ) {}// wait for DataAvailable to be updated 505 } 506 } 507return true; 508} 509 510bool ESP8266_CloseTCPConnection (void ) { 511esp_puts (ESP8266_ConnectionMux ?"AT+CIPCLOSE=0\r\n" :"AT+CIPCLOSE\r\n" ); 512fifo_clear (rxdata_fifo ); 513return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,ESP8266_ERROR_RESPONSE ); 514} 515 516bool ESP8266_GetStatus (void ) { 517esp_puts ("AT+CIPSTATUS\r\n" ); 518return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,0 ); 519} 520 521bool ESP8266_SetServerTimeout (uint16_t timeout ) { 522char TXBuffer [32 ]; 523sprintf (TXBuffer ,"AT+CIPSTO=%d\r\n" ,timeout ); 524esp_puts (TXBuffer ); 525return ESP8266_WaitForResponse (ESP8266_OK_RESPONSE ,ESP8266_ERROR_RESPONSE ); 526} 527 528bool ESP8266_WaitForConnection (void ) { 529return ESP8266_ConnectionMux && ESP8266_Server && 530ESP8266_WaitForResponse ("0,CONNECT\r\n" ,0 ); 531}