diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/.gitignore b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6864878994ba54ae651a8719fcf6fd88eee2de69 --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/.gitignore @@ -0,0 +1,2 @@ +firmware/* +build/* diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/Makefile b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/Makefile similarity index 92% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/Makefile rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/Makefile index 1dcb340686afc6a7680c4bf231bfaee37fc2ed1a..6b52c5c811604e8517d327fb1ebe1aa37141ab5f 100644 --- a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/Makefile +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/Makefile @@ -19,15 +19,15 @@ FW_BASE = firmware # base directory for the compiler # NOTE: Replace this with the path to your esp-open-sdk -XTENSA_TOOLS_ROOT ?= /home/eric/esp8266/esp-open-sdk/xtensa-lx106-elf/bin +XTENSA_TOOLS_ROOT ?= $(HOME)/esp-open-sdk/xtensa-lx106-elf/bin # base directory of the ESP8266 SDK package, absolute # Note: Replace this one too -SDK_BASE ?= /home/eric/esp8266/esp-open-sdk/sdk +SDK_BASE ?= $(HOME)/esp-open-sdk/sdk # esptool.py path and port ESPTOOL ?= $(XTENSA_TOOLS_ROOT)/esptool.py -ESPPORT ?= /dev/ttyUSB0 +ESPPORT ?= /dev/ttyACM0 # name for the target project TARGET = uart @@ -41,7 +41,7 @@ LIBS = c gcc hal pp phy net80211 lwip wpa main # compiler flags using during compilation of source files # -CFLAGS = -Os -O2 -Wpointer-arith -Wundef -Werror -Wl,-EL -fno-inline-functions -nostdlib -mlongcalls -mtext-section-literals -D__ets__ -DICACHE_FLASH +CFLAGS = -Os -O2 -Wpointer-arith -Wundef -Wl,-EL -fno-inline-functions -nostdlib -mlongcalls -mtext-section-literals -D__ets__ -DICACHE_FLASH # linker flags used to generate the main object file LDFLAGS = -nostdlib -Wl,--no-check-sections -u call_user_start -Wl,-static diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/README.md b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ee761db74197a75c84bdbcbb4c5c5badc6eb8cf9 --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/README.md @@ -0,0 +1,4 @@ +# ESP8266_Wifi-Serial-Adapter-AP + +This directory contains the code running on the ESP8266 ESP-01 chip +on the quad, if the quad is acting as the AP. For information on programming see [ESP Programming Documentation](../esp_programming.md). diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/driver/RingBuffer.c b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/driver/RingBuffer.c similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/driver/RingBuffer.c rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/driver/RingBuffer.c diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/driver/uart.c b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/driver/uart.c similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/driver/uart.c rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/driver/uart.c diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/driver/RingBuffer.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/driver/RingBuffer.h similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/driver/RingBuffer.h rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/driver/RingBuffer.h diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/driver/uart.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/driver/uart.h similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/driver/uart.h rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/driver/uart.h diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/driver/uart_register.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/driver/uart_register.h similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/driver/uart_register.h rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/driver/uart_register.h diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/espmissingincludes.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/espmissingincludes.h similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/espmissingincludes.h rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/espmissingincludes.h diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/user_config.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/user_config.h similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/user_config.h rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/user_config.h diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/user_tcp.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/user_tcp.h similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/include/user_tcp.h rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/include/user_tcp.h diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/user/user_main.c b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/user/user_main.c similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/user/user_main.c rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/user/user_main.c diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/user/user_tcp.c b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/user/user_tcp.c similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/user/user_tcp.c rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-AP/user/user_tcp.c diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/.gitignore b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6864878994ba54ae651a8719fcf6fd88eee2de69 --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/.gitignore @@ -0,0 +1,2 @@ +firmware/* +build/* diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/Makefile b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..6b52c5c811604e8517d327fb1ebe1aa37141ab5f --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/Makefile @@ -0,0 +1,140 @@ +# Makefile for ESP8266 projects +# +# Thanks to: +# - zarya +# - Jeroen Domburg (Sprite_tm) +# - Christian Klippel (mamalala) +# - Tommie Gannert (tommie) +# +# Changelog: +# - 2014-10-06: Changed the variables to include the header file directory +# - 2014-10-06: Added global var for the Xtensa tool root +# - 2014-11-23: Updated for SDK 0.9.3 +# - 2014-12-25: Replaced esptool by esptool.py + +# Output directors to store intermediate compiled files +# relative to the project directory +BUILD_BASE = build +FW_BASE = firmware + +# base directory for the compiler +# NOTE: Replace this with the path to your esp-open-sdk +XTENSA_TOOLS_ROOT ?= $(HOME)/esp-open-sdk/xtensa-lx106-elf/bin + +# base directory of the ESP8266 SDK package, absolute +# Note: Replace this one too +SDK_BASE ?= $(HOME)/esp-open-sdk/sdk + +# esptool.py path and port +ESPTOOL ?= $(XTENSA_TOOLS_ROOT)/esptool.py +ESPPORT ?= /dev/ttyACM0 + +# name for the target project +TARGET = uart + +# which modules (subdirectories) of the project to include in compiling +MODULES = driver user +EXTRA_INCDIR = include + +# libraries used in this project, mainly provided by the SDK +LIBS = c gcc hal pp phy net80211 lwip wpa main + +# compiler flags using during compilation of source files +# +CFLAGS = -Os -O2 -Wpointer-arith -Wundef -Wl,-EL -fno-inline-functions -nostdlib -mlongcalls -mtext-section-literals -D__ets__ -DICACHE_FLASH + +# linker flags used to generate the main object file +LDFLAGS = -nostdlib -Wl,--no-check-sections -u call_user_start -Wl,-static + +# linker script used for the above linkier step +LD_SCRIPT = eagle.app.v6.ld + +# various paths from the SDK used in this project +SDK_LIBDIR = lib +SDK_LDDIR = ld +SDK_INCDIR = include include/json + +# we create two different files for uploading into the flash +# these are the names and options to generate them +FW_FILE_1_ADDR = 0x00000 +FW_FILE_2_ADDR = 0x10000 + +# select which tools to use as compiler, librarian and linker +CC := $(XTENSA_TOOLS_ROOT)/xtensa-lx106-elf-gcc +AR := $(XTENSA_TOOLS_ROOT)/xtensa-lx106-elf-ar +LD := $(XTENSA_TOOLS_ROOT)/xtensa-lx106-elf-gcc + + + +#### +#### no user configurable options below here +#### +SRC_DIR := $(MODULES) +BUILD_DIR := $(addprefix $(BUILD_BASE)/,$(MODULES)) + +SDK_LIBDIR := $(addprefix $(SDK_BASE)/,$(SDK_LIBDIR)) +SDK_INCDIR := $(addprefix -I$(SDK_BASE)/,$(SDK_INCDIR)) + +SRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.c)) +OBJ := $(patsubst %.c,$(BUILD_BASE)/%.o,$(SRC)) +LIBS := $(addprefix -l,$(LIBS)) +APP_AR := $(addprefix $(BUILD_BASE)/,$(TARGET)_app.a) +TARGET_OUT := $(addprefix $(BUILD_BASE)/,$(TARGET).out) + +LD_SCRIPT := $(addprefix -T$(SDK_BASE)/$(SDK_LDDIR)/,$(LD_SCRIPT)) + +INCDIR := $(addprefix -I,$(SRC_DIR)) +EXTRA_INCDIR := $(addprefix -I,$(EXTRA_INCDIR)) +MODULE_INCDIR := $(addsuffix /include,$(INCDIR)) + +FW_FILE_1 := $(addprefix $(FW_BASE)/,$(FW_FILE_1_ADDR).bin) +FW_FILE_2 := $(addprefix $(FW_BASE)/,$(FW_FILE_2_ADDR).bin) + +V = $(VERBOSE) +ifeq ("$(V)","1") +Q := +vecho := @true +else +Q := @ +vecho := @echo +endif + +vpath %.c $(SRC_DIR) + +define compile-objects +$1/%.o: %.c + $(vecho) "CC $$<" + $(Q) $(CC) $(INCDIR) $(MODULE_INCDIR) $(EXTRA_INCDIR) $(SDK_INCDIR) $(CFLAGS) -c $$< -o $$@ +endef + +.PHONY: all checkdirs flash clean + +all: checkdirs $(TARGET_OUT) $(FW_FILE_1) $(FW_FILE_2) + +$(FW_BASE)/%.bin: $(TARGET_OUT) | $(FW_BASE) + $(vecho) "FW $(FW_BASE)/" + $(Q) $(ESPTOOL) elf2image -o $(FW_BASE)/ $(TARGET_OUT) + +$(TARGET_OUT): $(APP_AR) + $(vecho) "LD $@" + $(Q) $(LD) -L$(SDK_LIBDIR) $(LD_SCRIPT) $(LDFLAGS) -Wl,--start-group $(LIBS) $(APP_AR) -Wl,--end-group -o $@ + +$(APP_AR): $(OBJ) + $(vecho) "AR $@" + $(Q) $(AR) cru $@ $^ + +checkdirs: $(BUILD_DIR) $(FW_BASE) + +$(BUILD_DIR): + $(Q) mkdir -p $@ + +$(FW_BASE): + $(Q) mkdir -p $@ + +flash: $(FW_FILE_1) $(FW_FILE_2) + $(ESPTOOL) --port $(ESPPORT) write_flash $(FW_FILE_1_ADDR) $(FW_FILE_1) $(FW_FILE_2_ADDR) $(FW_FILE_2) + +clean: + $(Q) rm -rf $(FW_BASE) $(BUILD_BASE) + +$(foreach bdir,$(BUILD_DIR),$(eval $(call compile-objects,$(bdir)))) diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/README.md b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/README.md new file mode 100644 index 0000000000000000000000000000000000000000..672cccbdc9e172df758e4c8530c87ac0c3d395fc --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/README.md @@ -0,0 +1,5 @@ +# ESP8266_Wifi-Serial-Adapter-Client + +This directory contains the code running on the ESP8266 ESP-01 chip +on the quad if the quad is acting as a Client. For information on programming +see [ESP Programming Documentation](../esp_programming.md). diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/driver/RingBuffer.c b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/driver/RingBuffer.c new file mode 100644 index 0000000000000000000000000000000000000000..c1385c6e2ede4520ecb5fb829404d21534e66c65 --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/driver/RingBuffer.c @@ -0,0 +1,48 @@ +#include "driver/RingBuffer.h" + +#include <mem.h> +#include <string.h> //memcpy + +void RingBuffer_init(RingBuffer *buffer, uint16 size) { + buffer->front = 0; + buffer->back = 0; + buffer->size = size; + + buffer->buffer = (uint8*)os_malloc(size); +} + +void RingBuffer_addByte(RingBuffer *buffer, uint8 byte) { + buffer->buffer[buffer->back] = byte; + + buffer->back = (buffer->back + 1) & (buffer->size - 1); +} + +void RingBuffer_clear(RingBuffer *buffer) { + buffer->front = buffer->back = 0; +} + +uint16_t RingBuffer_getSize(RingBuffer *buffer) { + return (buffer->back >= buffer->front) ? (buffer->back - buffer->front) + : (buffer->size + buffer->back - buffer->front); +} + +uint16_t RingBuffer_get(RingBuffer *buffer, uint8 *out, uint16 outSize) { + uint16_t cpyAmt = RingBuffer_getSize(buffer); + if(cpyAmt > outSize) + cpyAmt = outSize; + + if( (buffer->front + cpyAmt) > buffer->size ) { + uint16_t cpyRemainder = buffer->front + cpyAmt - buffer->size; + //Two copies + memcpy(out, buffer->buffer + buffer->front, cpyAmt - cpyRemainder); + memcpy(out + cpyAmt - cpyRemainder, buffer->buffer, cpyRemainder); + } + else { + //One copy + memcpy(out, buffer->buffer + buffer->front, cpyAmt); + } + + buffer->front = (buffer->front + cpyAmt) & (buffer->size - 1); + + return cpyAmt; +} diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/uart.c b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/driver/uart.c similarity index 81% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/uart.c rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/driver/uart.c index f7e68ee6d019ab7935587837fc9a48d6e6339c5f..7faf39ba99edf91fccae77a2795f18e1d0386e02 100644 --- a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/uart.c +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/driver/uart.c @@ -22,6 +22,9 @@ #include "mem.h" #include "os_type.h" #include "driver/RingBuffer.h" +#include "user_config.h" + +#define BUFFER_SIZE 2048 //static volatile RingBuffer _rxBuffer; static volatile uint8 _rxBuffer[BUFFER_SIZE]; @@ -65,8 +68,8 @@ uart_config(uint8 uart_no) if (uart_no == UART0){ //set rx fifo trigger WRITE_PERI_REG(UART_CONF1(uart_no), - ((100 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | - (4 & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S | + ((UART_RX_FULL_LEVEL & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | + ((UART_RX_TO_LEVEL & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S) | UART_RX_TOUT_EN| ((0x10 & UART_TXFIFO_EMPTY_THRHD)<<UART_TXFIFO_EMPTY_THRHD_S));//wjl SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_TOUT_INT_ENA |UART_FRM_ERR_INT_ENA); @@ -76,21 +79,56 @@ uart_config(uint8 uart_no) //clear all interrupt WRITE_PERI_REG(UART_INT_CLR(uart_no), 0xffff); //enable rx_interrupt - SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA|UART_RXFIFO_OVF_INT_ENA|UART_RXFIFO_TOUT_INT_ENA); + SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA|UART_RXFIFO_OVF_INT_ENA|UART_RXFIFO_TOUT_INT_ENA|UART_FRM_ERR_INT_ENA|UART_PARITY_ERR_INT_ENA); } uint16 uart_get(uint8 *out, uint16 len) { - uart_rx_intr_disable(UART0); + //uart_rx_intr_disable(UART0); - //uint16 amount = RingBuffer_get((RingBuffer*)&_rxBuffer, out, len); uint16 amount = (_rxLen < len) ? _rxLen : len; memcpy(out, (uint8*)_rxBuffer, amount); + + if(amount != _rxLen) { + memcpy((uint8*)_rxBuffer, (uint8*)_rxBuffer + amount, _rxLen - amount); + } _rxLen -= amount; - uart_rx_intr_enable(UART0); + //uart_rx_intr_enable(UART0); return amount; +/* + //Grab the data from the FIFO + uint8 fifo_len = (READ_PERI_REG(UART_STATUS(UART0)) >> UART_RXFIFO_CNT_S) + & UART_RXFIFO_CNT; + + uint8 i; + + for(i = 0; i < fifo_len; ++i) { + //uart_tx_one_char(UART0, READ_PERI_REG(UART_FIFO(UART0)) & 0xFF); + //RingBuffer_addByte((RingBuffer*)&_rxBuffer, READ_PERI_REG(UART_FIFO(UART0)) & 0xFF); + out[i] = READ_PERI_REG(UART_FIFO(UART0)) & 0xFF; + } + + //Re-enable UART RX interrupts + SET_PERI_REG_MASK(UART_INT_ENA(UART0), UART_RXFIFO_FULL_INT_ENA | UART_RXFIFO_TOUT_INT_ENA); + + return fifo_len; +*/ +} + +uint16 uart_getFifoLen() { + uint8 fifo_len = (READ_PERI_REG(UART_STATUS(UART0)) >> UART_RXFIFO_CNT_S) + & UART_RXFIFO_CNT; + + return fifo_len; +} + +uint8 uart_getTxFifoAvail() { + uint8 fifo_len = (READ_PERI_REG(UART_STATUS(UART0)) >> UART_TXFIFO_CNT_S) + & UART_TXFIFO_CNT; + + return UART_FIFO_LEN - fifo_len; } /****************************************************************************** @@ -180,7 +218,7 @@ void uart_rx_flush() { LOCAL void uart0_rx_intr_handler(void *para) { - uint32 intMask = 0, recv = 0; + uint32 intMask = 0; uint8_t uart_no = UART0; /* uart0 and uart1 intr combine togther, when interrupt occur, see reg 0x3ff20020, bit2, bit0 represents @@ -192,41 +230,73 @@ uart0_rx_intr_handler(void *para) //uint8 buf_idx = 0; //uint8 temp,cnt; //RcvMsgBuff *pRxBuff = (RcvMsgBuff *)para; + uint8 read = 0; /*ATTENTION:*/ /*IN NON-OS VERSION SDK, DO NOT USE "ICACHE_FLASH_ATTR" FUNCTIONS IN THE WHOLE HANDLER PROCESS*/ /*ALL THE FUNCTIONS CALLED IN INTERRUPT HANDLER MUST BE DECLARED IN RAM */ /*IF NOT , POST AN EVENT AND PROCESS IN SYSTEM TASK */ - if(UART_FRM_ERR_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_FRM_ERR_INT_ST)){ - WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_FRM_ERR_INT_CLR); - } - else if(UART_RXFIFO_FULL_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST)){ - recv = 1; - intMask = UART_RXFIFO_FULL_INT_CLR; + if(UART_RXFIFO_FULL_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST)){ + //recv = 1; + //intMask = UART_RXFIFO_FULL_INT_CLR; + + //Disable this interrupt until we read the data from the fifo + //CLEAR_PERI_REG_MASK(UART_INT_ENA(UART0), UART_RXFIFO_FULL_INT_ENA | UART_RXFIFO_TOUT_INT_ENA); + + //system_os_post(UART_TASK_PRIORITY, UART_SIG_RECV, 0); + //Clear interrupt flag + //WRITE_PERI_REG(UART_INT_CLR(UART0), UART_RXFIFO_FULL_INT_CLR); - //system_os_post(uart_recvTaskPrio, 0, 0); + //uint16 count = uart_get((uint8*)_rxBuffer + _rxLen, BUFFER_SIZE - _rxLen); + //_rxLen += count; + read = 1; + intMask = UART_RXFIFO_FULL_INT_CLR; } else if(UART_RXFIFO_TOUT_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_TOUT_INT_ST)){ - recv = 1; + //recv = 1; intMask = UART_RXFIFO_TOUT_INT_CLR; + + //Disable this interrupt until we read the data from the fifo + //CLEAR_PERI_REG_MASK(UART_INT_ENA(UART0), UART_RXFIFO_TOUT_INT_ENA | UART_RXFIFO_FULL_INT_ENA); + + //system_os_post(UART_TASK_PRIORITY, UART_SIG_RECV, 0); + + //Clear interrupt flag + WRITE_PERI_REG(UART_INT_CLR(UART0), UART_RXFIFO_TOUT_INT_CLR); + + //uint16 count = uart_get((uint8*)_rxBuffer + _rxLen, BUFFER_SIZE - _rxLen); + //_rxLen += count; + read = 1; - //system_os_post(uart_recvTaskPrio, 0, 0); } else if(UART_TXFIFO_EMPTY_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_TXFIFO_EMPTY_INT_ST)){ CLEAR_PERI_REG_MASK(UART_INT_ENA(UART0), UART_TXFIFO_EMPTY_INT_ENA); - _intFlags &= ~(UART_TXFIFO_EMPTY_INT_ENA); + //_intFlags &= ~(UART_TXFIFO_EMPTY_INT_ENA); system_os_post(UART_TASK_PRIORITY, UART_SIG_TXTO, 0); WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_TXFIFO_EMPTY_INT_CLR); } else if(UART_RXFIFO_OVF_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_OVF_INT_ST)){ - WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_RXFIFO_OVF_INT_CLR); + system_os_post(UART_TASK_PRIORITY, UART_SIG_RXOVF, 0); + + WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_RXFIFO_OVF_INT_CLR); } + else if(UART_FRM_ERR_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_FRM_ERR_INT_ST)) { + system_os_post(UART_TASK_PRIORITY, UART_SIG_ERR_FRM, 0); - if(recv) { + WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_FRM_ERR_INT_CLR); + } + else if(UART_PARITY_ERR_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_PARITY_ERR_INT_ST)) { + //system_os_post(UART_TASK_PRIORITY, UART_SIG_ERR_PARITY, 0); + + WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_PARITY_ERR_INT_CLR); + } + + + if(read) { //Grab data from FIFO uint8 fifo_len = (READ_PERI_REG(UART_STATUS(UART0)) >> UART_RXFIFO_CNT_S) & UART_RXFIFO_CNT; @@ -243,6 +313,7 @@ uart0_rx_intr_handler(void *para) //Post receive message system_os_post(UART_TASK_PRIORITY, UART_SIG_RECV, 0); } + } /****************************************************************************** @@ -310,13 +381,21 @@ STATUS uart0_tx_one_char_no_wait(uint8 TxChar) return OK; } +void uart_debugSend(char *str) { +#if USE_UART_DEBUG == 0 + return; +#else + uart0_send_nowait(str, os_strlen(str)); +#endif +} + uint16 uart0_send_nowait(uint8 *buffer, uint16 len) { uint8 fifo_cnt = (( READ_PERI_REG(UART_STATUS(UART0))>>UART_TXFIFO_CNT_S)& UART_TXFIFO_CNT); uint8 written = 0; - if(fifo_cnt < 126) { - uint8 avail = 126 - fifo_cnt; + if(fifo_cnt < UART_FIFO_LEN) { + uint8 avail = UART_FIFO_LEN - fifo_cnt; if(avail > len) avail = len; diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/driver/RingBuffer.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/driver/RingBuffer.h new file mode 100644 index 0000000000000000000000000000000000000000..3934fcf3b0e59beb37ab1e72c1352ab2b7d8b8e4 --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/driver/RingBuffer.h @@ -0,0 +1,21 @@ +#pragma once + +#include "os_type.h" + +typedef struct { + uint8 *buffer; + uint16 front, back, size; +} RingBuffer; + + +void RingBuffer_init(RingBuffer *buffer, uint16 size); + +void RingBuffer_addByte(RingBuffer *buffer, uint8 byte); + +void RingBuffer_put(RingBuffer *buffer, uint8 *data, uint16 len); + +void RingBuffer_clear(RingBuffer *buffer); + +uint16_t RingBuffer_getSize(RingBuffer *buffer); + +uint16_t RingBuffer_get(RingBuffer *buffer, uint8 *out, uint16 outSize); diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/uart.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/driver/uart.h similarity index 94% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/uart.h rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/driver/uart.h index 3f9fff514337206895fb6b0e1461ace70d0c0ba3..8f0cf2d6bb7137949afddc91c1bf70ef7c11a8cd 100644 --- a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/uart.h +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/driver/uart.h @@ -26,8 +26,14 @@ #define UART_SIG_RECV 0x01 #define UART_SIG_TXTO 0x02 +#define UART_SIG_RXOVF 0x03 +#define UART_SIG_ERR_FRM 0x04 +#define UART_SIG_ERR_PARITY 0x05 #define UART_TASK_PRIORITY 2 +#define UART_RX_FULL_LEVEL (100) +#define UART_RX_TO_LEVEL (10) + typedef enum { FIVE_BITS = 0x0, SIX_BITS = 0x1, @@ -138,12 +144,15 @@ typedef struct { void uart_init(UartBautRate uart0_br, UartBautRate uart1_br); void uart0_sendStr(const char *str); uint16 uart0_send_nowait(uint8 *buffer, uint16 len); +void uart_debugSend(char *str); void uart_set_txto(); void uart_clear_txto(); +uint16 uart_getFifoLen(); +uint8 uart_getTxFifoAvail(); /////////////////////////////////////// -#define UART_FIFO_LEN 128 //define the tx fifo length +#define UART_FIFO_LEN 126 //define the tx fifo length #define UART_TX_EMPTY_THRESH_VAL 0x10 diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/uart_register.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/driver/uart_register.h similarity index 100% rename from wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/uart_register.h rename to wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/driver/uart_register.h diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/espmissingincludes.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/espmissingincludes.h new file mode 100644 index 0000000000000000000000000000000000000000..3541f4084bf0b89295a01c59fba47c79d1b49bac --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/espmissingincludes.h @@ -0,0 +1,78 @@ +#ifndef ESPMISSINGINCLUDES_H +#define ESPMISSINGINCLUDES_H + +#include <stdint.h> +#include <c_types.h> + +#include "os_type.h" + +int strcasecmp(const char *a, const char *b); +#ifndef FREERTOS +#include <eagle_soc.h> +#include <ets_sys.h> +//Missing function prototypes in include folders. Gcc will warn on these if we don't define 'em anywhere. +//MOST OF THESE ARE GUESSED! but they seem to swork and shut up the compiler. +typedef struct espconn espconn; + +int atoi(const char *nptr); +void ets_install_putc1(void *routine); +void ets_isr_attach(int intr, void *handler, void *arg); +void ets_isr_mask(unsigned intr); +void ets_isr_unmask(unsigned intr); +int ets_memcmp(const void *s1, const void *s2, size_t n); +void *ets_memcpy(void *dest, const void *src, size_t n); +void *ets_memset(void *s, int c, size_t n); +int ets_sprintf(char *str, const char *format, ...) __attribute__ ((format (printf, 2, 3))); +int ets_str2macaddr(void *, void *); +int ets_strcmp(const char *s1, const char *s2); +char *ets_strcpy(char *dest, const char *src); +size_t ets_strlen(const char *s); +int ets_strncmp(const char *s1, const char *s2, int len); +char *ets_strncpy(char *dest, const char *src, size_t n); +char *ets_strstr(const char *haystack, const char *needle); +void ets_timer_arm_new(os_timer_t *a, int b, int c, int isMstimer); +void ets_timer_disarm(os_timer_t *a); +void ets_timer_setfn(os_timer_t *t, ETSTimerFunc *fn, void *parg); +void ets_update_cpu_frequency(int freqmhz); +void *os_memmove(void *dest, const void *src, size_t n); +int os_printf(const char *format, ...) __attribute__ ((format (printf, 1, 2))); +int os_snprintf(char *str, size_t size, const char *format, ...) __attribute__ ((format (printf, 3, 4))); +int os_printf_plus(const char *format, ...) __attribute__ ((format (printf, 1, 2))); +void uart_div_modify(int no, unsigned int freq); +uint8 wifi_get_opmode(void); +uint32 system_get_time(); +int rand(void); +void ets_bzero(void *s, size_t n); +void ets_delay_us(int ms); + +//Hack: this is defined in SDK 1.4.0 and undefined in 1.3.0. It's only used for this, the symbol itself +//has no meaning here. +#ifndef RC_LIMIT_P2P_11N +//Defs for SDK <1.4.0 +void *pvPortMalloc(size_t xWantedSize); +void *pvPortZalloc(size_t); +void vPortFree(void *ptr); +void *vPortMalloc(size_t xWantedSize); +void pvPortFree(void *ptr); +#else +void *pvPortMalloc(size_t xWantedSize, const char *file, int line); +void *pvPortZalloc(size_t, const char *file, int line); +void vPortFree(void *ptr, const char *file, int line); +void *vPortMalloc(size_t xWantedSize, const char *file, int line); +void pvPortFree(void *ptr, const char *file, int line); +#endif + +//Standard PIN_FUNC_SELECT gives a warning. Replace by a non-warning one. +#ifdef PIN_FUNC_SELECT +#undef PIN_FUNC_SELECT +#define PIN_FUNC_SELECT(PIN_NAME, FUNC) do { \ + WRITE_PERI_REG(PIN_NAME, \ + (READ_PERI_REG(PIN_NAME) \ + & (~(PERIPHS_IO_MUX_FUNC<<PERIPHS_IO_MUX_FUNC_S))) \ + |( (((FUNC&BIT2)<<2)|(FUNC&0x3))<<PERIPHS_IO_MUX_FUNC_S) ); \ + } while (0) +#endif + +#endif + +#endif diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/user_config.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/user_config.h new file mode 100644 index 0000000000000000000000000000000000000000..0e4bf25c3497cdd3c5bd694960aa3285f957e4b1 --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/user_config.h @@ -0,0 +1,26 @@ +#ifndef USER_CONFIG_H +#define USER_CONFIG_H + +//Set to 1 to enable uart debug messages +#define USE_UART_DEBUG 0 + +//Make sure to enable USE_UART_DEBUG before enabling one of the options below +//Print out information relating to wifi ap and connecting clients +#define DEBUG_WIFI 0 +//Print out heap information during operation +#define DEBUG_NETWORK_TASK 0 + +//WIFI Variables +#define TCP_PORT 8080 +#define AP_SSID "MicroCART" +#define AP_PSK "m1cr0cart" + +//Defines the quad to program the wifi client for 0 is the old quad, +//1 is the new quad +#define QUAD_NUM 0 + +//UART Settings +#define BAUD 921600 +#define UART_RX_BUFFER_SIZE (1024) +#define UART_TX_BUFFER_SIZE (256) +#endif diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/user_tcp.h b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/user_tcp.h new file mode 100644 index 0000000000000000000000000000000000000000..f0a2434a6e61b5807b2b42f10b28cf83517fed42 --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/include/user_tcp.h @@ -0,0 +1,13 @@ +#pragma once + +#include "os_type.h" + +typedef void (*ReceiveHandler)(uint16 len); + +void tcp_start(uint16 port); +void tcp_stop(); + +void tcp_setRecvHandler(ReceiveHandler handler); + +void tcp_send(uint8* buffer, uint16 len); +uint16 tcp_receive(uint8* buffer, uint16 size); diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/user/user_main.c b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/user/user_main.c new file mode 100644 index 0000000000000000000000000000000000000000..706022ea963ea9b0d382f536d18922292c1fe938 --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/user/user_main.c @@ -0,0 +1,264 @@ +#include <string.h> +#include "ets_sys.h" +#include "osapi.h" +#include "gpio.h" +#include "os_type.h" +#include "user_config.h" +#include "driver/uart.h" +#include "user_interface.h" +#include "espconn.h" +#include "user_tcp.h" +#include <mem.h> + +#define NETWORK_UPDATE_RATE 5 + +#define user_procTaskQueueLen 10 + +#if QUAD_NUM == 0 +uint8_t mac[6] = {0xb8, 0xd7, 0x63, 0x00, 0xfe, 0xef}; +#elif QUAD_NUM == 1 +uint8_t mac[6] = {0xb8, 0xd7, 0x63, 0x00, 0xfe, 0xf0}; +#else +uint8_t mac[6] = {}; +#endif + +static uint8 *_rxBuffer; +static uint8 *_txBuffer; + +os_event_t user_procTaskQueue[user_procTaskQueueLen]; +static void uart_task(os_event_t *events); +static void tcp_recvHandler(uint16 len); + +static volatile os_timer_t networkTimer; +static volatile uint8 _ledSet; + +static void wifi_handler(System_Event_t *event); + +static volatile int uartCount = 0; +static volatile uint8 _uartTxFlag; + +void network_task(void *arg) { + static uint8_t ledState = 0; + + if(_ledSet) { + ledState = 1; + _ledSet = 0; + + //Turn on activity LED + gpio_output_set(BIT0, 0, BIT0, 0); + } + + if(ledState) { + if(ledState++ > 10) { + ledState = 0; + gpio_output_set(0, BIT0, BIT0, 0); + } + } + +#if DEBUG_NETWORK_TASK == 1 + static int i = 0; + if(i == 0) { + i = 100; + + char msg[128]; + os_sprintf(msg, "[Heap] %d\r\n", + (int)system_get_free_heap_size()); + uart_debugSend(msg); + } + i--; +#endif +} + +//Task to process events +//static void ICACHE_FLASH_ATTR +static void uart_task(os_event_t *events) +{ + switch(events->sig) { + case UART_SIG_ERR_FRM: { + uart_debugSend("UART RX Frame error\r\n"); + } + break; + + case UART_SIG_ERR_PARITY: { + uart_debugSend("UART RX Parity error\r\n"); + } + break; + + case UART_SIG_RXOVF: { + uart_debugSend("UART RX overflow\r\n"); + } + case UART_SIG_RECV: { + static int bytesRecv = 0; + + //Set the activity LED + _ledSet = 1; + + //Echo data + int count = uart_get((char*)_rxBuffer, UART_RX_BUFFER_SIZE); + + bytesRecv += count; + + if(count > 0) { + tcp_send((uint8*)_rxBuffer, count); + + uartCount = 0; + + } + } + break; + + + + case UART_SIG_TXTO: { + //Transmit FIFO near empty + + //Grab as much as we can send + uint8 sendSpace = uart_getTxFifoAvail(); + uint8 toSend = tcp_receive(_txBuffer, sendSpace); + + if(toSend > 0) { + //Fill the FIFO + uart0_send_nowait(_txBuffer, toSend); + + uart_set_txto(); + _ledSet = 1; + } + else { + uart_clear_txto(); + + _uartTxFlag = 0; + } + } + break; + + default: + break; + } +} + +void wifi_init() { + char ssid[32]; + char password[64]; + + //Set to Station mode + wifi_set_opmode(STATION_MODE); + + //Set station mac + //NOTE THIS MUST BE CALLED AFTER wifi_set_opmode + //NOTE THIS CAN ONLY GO IN THE user_init function (wifi_init is called from user_init so it is okay) + wifi_set_macaddr(STATION_IF, mac); + + //Station configuration + struct station_config stationConf; + + //Set ap settings + strcpy(&stationConf.ssid, AP_SSID); + strcpy(&stationConf.password, AP_PSK); + + //Set configuration + wifi_station_set_config(&stationConf); + + //Set WiFi event handler + wifi_set_event_handler_cb(&wifi_handler); +} + +void wifi_handler(System_Event_t *evt) { + char msg[256]; + switch(evt->event) { +#if DEBUG_WIFI == 1 + case EVENT_STAMODE_GOT_IP: + os_sprintf(msg, "ip:" IPSTR ", mask:" IPSTR ",gw:" IPSTR "\n\r", + IP2STR(&evt->event_info.got_ip.ip), + IP2STR(&evt->event_info.got_ip.mask), + IP2STR(&evt->event_info.got_ip.gw)); + uart_debugSend(msg); + break; + case EVENT_STAMODE_DISCONNECTED: + os_sprintf(msg, "disconnected from ssid: %s, reason %d\n\r", + evt->event_info.disconnected.ssid, + evt->event_info.disconnected.reason); + uart_debugSend(msg); + break; + case EVENT_STAMODE_CONNECTED: + os_sprintf(msg, "connect to ssid %s, channel %d\n\r", + evt->event_info.connected.ssid, + evt->event_info.connected.channel); + uart_debugSend(msg); + break; +#endif + default: + break; + } +} + +void tcp_recvHandler(uint16 len) { + if(_uartTxFlag == 0) { + //Grab as much as we can currently send + uint8 sendSpace = uart_getTxFifoAvail(); + uint8 toSend = tcp_receive(_txBuffer, sendSpace); + + uart0_send_nowait(_txBuffer, toSend); + uart_set_txto(); + + _uartTxFlag = 1; + _ledSet = 1; + } +} + +//Init function +void ICACHE_FLASH_ATTR +user_init() +{ + //Remove debug statements from UART0 + system_set_os_print(0); + + // Initialize the GPIO subsystem. + gpio_init(); + + //Set GPIO2 to output mode + PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2); + + //Set GPIO2 low + gpio_output_set(0, BIT0, BIT0, 0); + + //Initialize UART + uart_init(BAUD, BAUD); + + _rxBuffer = (uint8*)os_malloc(UART_RX_BUFFER_SIZE); + _txBuffer = (uint8*)os_malloc(UART_TX_BUFFER_SIZE); + + _uartTxFlag = 0; + + //Initialize WiFi + wifi_init(); + +#if DEBUG_WIFI == 1 + char mac_address[32]; + wifi_get_macaddr(0, &mac_address[0]); + char msg[256]; + os_sprintf(msg, "MAC Address %02x-%02x-%02x-%02x-%02x-%02x\n\r", + (unsigned) mac_address[0], (unsigned) mac_address[1], + (unsigned) mac_address[2], (unsigned) mac_address[3], + (unsigned) mac_address[4], (unsigned) mac_address[5]); + uart_debugSend(msg); +#endif + + //Start TCP server + tcp_start(TCP_PORT); + tcp_setRecvHandler(&tcp_recvHandler); + + _ledSet = 0; + + //Disarm timer + os_timer_disarm(&networkTimer); + + //Setup timer + os_timer_setfn(&networkTimer, (os_timer_func_t *)network_task, NULL); + + //Arm the timer + os_timer_arm(&networkTimer, NETWORK_UPDATE_RATE, 1); + + //Start os task + system_os_task(uart_task, UART_TASK_PRIORITY,user_procTaskQueue, + user_procTaskQueueLen); +} diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/user/user_tcp.c b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/user/user_tcp.c new file mode 100644 index 0000000000000000000000000000000000000000..615a86a0e1e4b93bee1322290a9163a8de08b15e --- /dev/null +++ b/wifi_bridge/ESP8266_Wifi-Serial-Adapter-Client/user/user_tcp.c @@ -0,0 +1,301 @@ +#include "user_tcp.h" + +#include "ip_addr.h" +#include "osapi.h" +#include "espconn.h" +#include "os_type.h" +#include <mem.h> +#include <string.h> + +//Debugging +#include "driver/uart.h" + +#define TCP_MAX_PACKET (1460) +#define TCP_SEND_BUFFER_SIZE (1024 * 20) +#define TCP_RECV_BUFFER_SIZE (10*TCP_MAX_PACKET) + +#define TCP_RECV_HOLD_LIMIT (5*TCP_MAX_PACKET) +#define TCP_TIMEOUT (7200) + +#define MAX_SEND_COUNT (2) + +struct Connection { + struct espconn *pConn; + + uint8 *sendBuffer; + uint16 sendSize, sendLen; + + uint8 *recvBuffer; + uint16 recvSize, recvLen; + uint8 recvHold; + + ReceiveHandler recvHandler; + + int sendCount; +}; + +static struct espconn _tcpServer; + +static struct Connection _tcpConn; + +static volatile os_timer_t _sendTimer; + +//Callbacks +static void __connectHandler(void *arg); +static void __disconnectHandler(void *arg); +static void __reconnectHandler(void *arg, sint8 err); +static void __recvHandler(void *arg, char *data, unsigned short len); +static void __sentHandler(void *arg); +static void __writeHandler(void *arg); + +static void __sendTimerHandler(void *arg); + +static uint16 __send(struct Connection *conn, uint8 *data, uint16 len); + + +void tcp_start(uint16 port) { + os_timer_disarm(&_sendTimer); + os_timer_setfn(&_sendTimer, (os_timer_func_t*)__sendTimerHandler, NULL); + + _tcpConn.sendBuffer = (uint8*)os_malloc(TCP_SEND_BUFFER_SIZE); + _tcpConn.sendSize = TCP_SEND_BUFFER_SIZE; + _tcpConn.sendLen = 0; + + _tcpConn.recvBuffer = (uint8*)os_malloc(TCP_RECV_BUFFER_SIZE); + _tcpConn.recvSize = TCP_RECV_BUFFER_SIZE; + _tcpConn.recvLen = 0; + _tcpConn.recvHold = 0; + + _tcpConn.pConn = NULL; + + _tcpServer.type = ESPCONN_TCP; + _tcpServer.state = ESPCONN_NONE; + _tcpServer.proto.tcp = (esp_tcp*)os_malloc(sizeof(esp_tcp)); + _tcpServer.proto.tcp->local_port = port; + + espconn_regist_connectcb(&_tcpServer, &__connectHandler); + espconn_regist_time(&_tcpServer, TCP_TIMEOUT, ESPCONN_KEEPINTVL); + + espconn_accept(&_tcpServer); + espconn_tcp_set_max_con(1); +} + +void tcp_stop() { + //TODO +} + +void tcp_setRecvHandler(ReceiveHandler handler) { + _tcpConn.recvHandler = handler; +} + +void tcp_send(uint8* buffer, uint16 len) { + if(len == 0) { + uart_debugSend("[tcp_send] Given buffer length 0\r\n"); + + return; + } + + if(_tcpConn.pConn != NULL) { + if((_tcpConn.sendCount < MAX_SEND_COUNT) && (_tcpConn.sendLen == 0)) { + uint16 sendAmt = __send(&_tcpConn, buffer, len); + + if(sendAmt < len) { + if((sendAmt + _tcpConn.sendLen) > _tcpConn.sendSize) { + uart_debugSend("[tcp_send] send buffer full!\r\n"); + } + else { + memcpy(_tcpConn.sendBuffer, buffer + sendAmt, len - sendAmt); + _tcpConn.sendLen = len - sendAmt; + } + } + } + else { + if((_tcpConn.sendLen + len) > _tcpConn.sendSize) { + uart_debugSend("[tcp_send] send buffer full!\r\n"); + } + else { + memcpy(_tcpConn.sendBuffer + _tcpConn.sendLen, buffer, len); + _tcpConn.sendLen += len; + } + + //char msg[128]; + //os_sprintf(msg, "[tcp_send] Defferred (%d)\r\n", (int)_tcpConn.sendLen); + //__debug(msg); + } + } + else { + uart_debugSend("[Send] (Not connected)\r\n"); + } +} + +uint16 tcp_receive(uint8 *buffer, uint16 size) { + uint16 recvAmt = _tcpConn.recvLen; + if(recvAmt > size) + recvAmt = size; + + memcpy(buffer, _tcpConn.recvBuffer, recvAmt); + + if(recvAmt != _tcpConn.recvLen) { + memmove(_tcpConn.recvBuffer, _tcpConn.recvBuffer + recvAmt, (_tcpConn.recvLen - recvAmt)); + } + + _tcpConn.recvLen -= recvAmt; + + if( (_tcpConn.recvHold == 1) && (_tcpConn.recvLen < TCP_RECV_HOLD_LIMIT) ) { + espconn_recv_unhold(_tcpConn.pConn); + _tcpConn.recvHold = 0; + } + + return recvAmt; +} + +uint16 __send(struct Connection *conn, uint8 *data, uint16 len) { + //conn->sendCount++; + + uint16 sendAmt = len; + if(sendAmt > TCP_MAX_PACKET) + sendAmt = TCP_MAX_PACKET; + + + if(conn->pConn == NULL) { + uart_debugSend("[__send] NULL espconn\r\n"); + + return 0; + } + + sint8 retval = espconn_send(conn->pConn, data, sendAmt); +/* + char msg[128]; + os_sprintf(msg, "[__send] Sent %d\r\n", (int)sendAmt); + uart_debugSend(msg); +*/ + + if((retval != 0) && (conn->sendCount == 0)) { + os_timer_arm(&_sendTimer, 1, 0); + } + + if(retval == ESPCONN_ARG) { + char msg[128]; + os_sprintf(msg, "[__send] ESPCONN_ARG: %d, %d\r\n", (int)data, (int)sendAmt); + uart_debugSend(msg); + + return 0; + } + else if(retval != 0) { + char msg[128]; + os_sprintf(msg, "[__send] (%d, %d)\r\n", (int)retval, (int)(conn->sendCount)); + uart_debugSend(msg); + + sendAmt = 0; + } + else { + //char msg[128]; + //os_sprintf(msg, "[__send] %d sent\r\n", (int)sendAmt); + //uart_debugSend(msg); + + conn->sendCount++; + } + + return sendAmt; +} + +void __connectHandler(void *arg) { + struct espconn *conn = (struct espconn*)arg; + + _tcpConn.pConn = conn; + conn->reverse = &_tcpConn; + _tcpConn.sendLen = 0; + + //Register handlers + espconn_regist_disconcb(conn, &__disconnectHandler); + espconn_regist_reconcb(conn, &__reconnectHandler); + espconn_regist_recvcb(conn, &__recvHandler); + espconn_regist_sentcb(conn, &__sentHandler); + espconn_regist_write_finish(conn, &__writeHandler); + espconn_regist_time(conn, TCP_TIMEOUT, ESPCONN_KEEPINTVL); + + + //Set socket options + espconn_set_opt(conn, ESPCONN_NODELAY | ESPCONN_COPY); + + //Clear tcpConn structure + //RingBuffer_clear(&(_tcpConn.sendBuffer)); + _tcpConn.sendCount = 0; +} + +void __disconnectHandler(void *arg) { + struct Connection *conn = (struct Connection*)(((struct espconn*)arg)->reverse); + + conn->pConn = NULL; + + uart_debugSend("[Disconnect]\r\n"); +} + +void __reconnectHandler(void *arg, sint8 err) { + char msg[128]; + + os_sprintf(msg, "[Reconnect] (%d)\r\n", (int)err); + uart_debugSend(msg); +} + +void __recvHandler(void *arg, char *data, unsigned short len) { + struct Connection *conn = (struct Connection*)(((struct espconn*)arg)->reverse); + + memcpy(conn->recvBuffer + conn->recvLen, data, len); + conn->recvLen += len; + + if( (conn->recvLen > TCP_RECV_HOLD_LIMIT) && (conn->recvHold == 0) ) { + espconn_recv_hold(conn->pConn); + conn->recvHold = 1; + } + + if(conn->recvHandler != NULL) { + conn->recvHandler(len); + } +} + +void __sentHandler(void *arg) { + struct Connection *conn = (struct Connection*)(((struct espconn*)arg)->reverse); + + conn->sendCount--; + +/* + char msg[128]; + os_sprintf(msg, "[__sentHandler] %d\r\n", (int)conn->sendCount); + uart_debugSend(msg); +*/ + + if((conn->sendCount < MAX_SEND_COUNT) && (conn->sendLen > 0)) { + uint16 sendAmt = __send(conn, conn->sendBuffer, conn->sendLen); + + if(sendAmt != 0) { + if(sendAmt != conn->sendLen) { + memmove(conn->sendBuffer, conn->sendBuffer + sendAmt, + conn->sendLen - sendAmt); + } + conn->sendLen -= sendAmt; + } + + //char msg[128]; + //os_sprintf(msg, "[sentHandler] Sent %d (%d)\r\n", (int)sendAmt, (int)conn->sendLen); + //__debug(msg); + } +} + +void __writeHandler(void *arg) { + struct Connection *conn = (struct Connection*)(((struct espconn*)arg)->reverse); +} + +void __sendTimerHandler(void *arg) { + if((_tcpConn.sendCount < MAX_SEND_COUNT) && (_tcpConn.sendLen > 0)) { + uint16 sendAmt = __send(&_tcpConn, _tcpConn.sendBuffer, _tcpConn.sendLen); + + if(sendAmt != 0) { + if(sendAmt != _tcpConn.sendLen) { + memmove(_tcpConn.sendBuffer, _tcpConn.sendBuffer + sendAmt, + _tcpConn.sendLen - sendAmt); + } + _tcpConn.sendLen -= sendAmt; + } + } +} diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/README.md b/wifi_bridge/ESP8266_Wifi-Serial-Adapter/README.md deleted file mode 100644 index e946c51e0041640f184f61b529f1654b9488fcdc..0000000000000000000000000000000000000000 --- a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/README.md +++ /dev/null @@ -1 +0,0 @@ -# ESP8266_Wifi-Serial-Adapter diff --git a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/user_main.c b/wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/user_main.c deleted file mode 100644 index d53d48ff1070fd2c10f612f49d8ba6c779c05bf7..0000000000000000000000000000000000000000 --- a/wifi_bridge/ESP8266_Wifi-Serial-Adapter/temp/user_main.c +++ /dev/null @@ -1,452 +0,0 @@ -#include <string.h> -#include "ets_sys.h" -#include "osapi.h" -#include "gpio.h" -#include "os_type.h" -#include "user_config.h" -#include "driver/uart.h" -#include "user_interface.h" -#include "espconn.h" -#include <mem.h> - -#define NETWORK_UPDATE_RATE 5 - -#define user_procTaskQueueLen 1 - - -#define BAUD 921600 - -#define TCP_PORT 8080 - -#define AP_CHANNEL 6 -#define AP_MAX_CONNECTIONS 4 -#define AP_SSID "MicroCART" -#define AP_PSK "m1cr0cart" - -#define AP_GATEWAY "192.168.1.1" -#define AP_NETMASK "255.255.255.0" - -#define DHCP_IP_START "192.168.1.10" -#define DHCP_IP_END "192.168.1.15" - -#define TCP_MAX_PACKET_SIZE 1460 -#define UART_TX_BUFFER_SIZE (TCP_MAX_PACKET_SIZE * 14) -#define TCP_SEND_BUFFER_SIZE (TCP_MAX_PACKET_SIZE * 6) - -#define TCP_MAX_SEND (500) - -static volatile uint8 *_txBuffer; -static volatile uint16 _txBufferSize; -static volatile uint16 _txBufferLen; -static volatile uint8 _tcpRecvHold = 0; -static volatile int _tcpHoldCount = -10; - -//TCP send -static volatile int _tcpSendActive = 0; -static volatile uint8 *_tcpSendBuffer; -static volatile uint16 _tcpSendBufferLen = 0; - -//static volatile char *_messageBuffer; - -static struct espconn tcpServerConn; -static struct espconn *tcpClient = NULL; - -os_event_t user_procTaskQueue[user_procTaskQueueLen]; -static void uart_task(os_event_t *events); - -static volatile os_timer_t networkTimer; -static volatile uint8 _ledSet; - -static void startServer(); - -static void wifi_handler(System_Event_t *event); -static void tcp_connect_handler(void *arg); -static void tcp_disconnect_handler(void *arg); -static void tcp_recv_handler(void *arg, char *data, unsigned short len); -static void tcp_sent_handler(void *arg); -static void tcp_write_handler(void *arg); - -static int tcpSend(uint8 *data, uint8 len); -static int tcpSendSome(); - - -void network_task(void *arg) { - static uint8_t ledState = 0; - - if(_ledSet) { - ledState = 1; - _ledSet = 0; - - //Turn on activity LED - gpio_output_set(BIT0, 0, BIT0, 0); - } - - if(ledState) { - if(ledState++ > 10) { - ledState = 0; - gpio_output_set(0, BIT0, BIT0, 0); - } - } - - //Verify that there's no data "stuck" in the TCP send buffer - if(tcpClient != NULL && !_tcpSendActive && _tcpSendBufferLen > 0) { - //Let's send some - if(tcpSendSome() > 0) { - _tcpSendActive = 1; - } - } -} - -//Task to process events -static void ICACHE_FLASH_ATTR -uart_task(os_event_t *events) -{ - switch(events->sig) { - case UART_SIG_RECV: { - //uint8 data[128]; - - //Set the activity LED - _ledSet = 1; - - //Echo data - //int count = uart_get((char*)data, sizeof(data)); - int count = uart_get((char*)(_tcpSendBuffer + _tcpSendBufferLen), - TCP_SEND_BUFFER_SIZE - _tcpSendBufferLen); - - _tcpSendBufferLen += count; - - //Send over TCP - if(tcpClient != NULL && !_tcpSendActive) { - _tcpSendActive = 1; - - tcpSendSome(); - } - } - break; - - case UART_SIG_TXTO: - //Transmit FIFO near empty - - if(_txBufferLen > 0) { - //Fill the FIFO - uint16 sent = uart0_send_nowait((uint8*)_txBuffer, _txBufferLen); - - if(sent < _txBufferLen) { - memmove((uint8*)_txBuffer, (uint8*)_txBuffer + sent, - _txBufferLen - sent); - _txBufferLen -= sent; - - uart_set_txto(); - } - else { - _txBufferLen = 0; - uart_clear_txto(); - } - - //Check if receive hold is active - if((_tcpRecvHold == 1) && (tcpClient != NULL) && - ((_txBufferSize - _txBufferLen) >= (10*TCP_MAX_PACKET_SIZE)) ) { - espconn_recv_unhold(tcpClient); - _tcpRecvHold = 0; - - _tcpHoldCount--; - } - } - break; - - default: - os_delay_us(10); - break; - } - - //os_delay_us(100); -} - -void wifi_init() { - //Set to SoftAP mode - wifi_set_opmode(SOFTAP_MODE); - - //SoftAP configuration - struct softap_config apConfig = { - .channel = AP_CHANNEL, - .authmode = AUTH_WPA2_PSK, - .ssid_hidden = 0, - .max_connection = AP_MAX_CONNECTIONS, - .beacon_interval = 100 - }; - strcpy(apConfig.ssid, AP_SSID); - strcpy(apConfig.password, AP_PSK); - apConfig.ssid_len = strlen(AP_SSID); - - //Set configuration - wifi_softap_set_config(&apConfig); - - //Disable power saving mode - //This seems to help reduce jitter in latency - //wifi_set_sleep_type(NONE_SLEEP_T); - - //DHCP configuration - struct dhcps_lease dhcpLease = { - .start_ip = ipaddr_addr(DHCP_IP_START), - .end_ip = ipaddr_addr(DHCP_IP_END) - }; - - //Disable DHCP server while making changes - wifi_softap_dhcps_stop(); - wifi_softap_set_dhcps_lease(&dhcpLease); - - //Set IP info - struct ip_info ipInfo = { - .ip = ipaddr_addr(AP_GATEWAY), - .gw = ipaddr_addr(AP_GATEWAY), - .netmask = ipaddr_addr(AP_NETMASK) - }; - wifi_set_ip_info(SOFTAP_IF, &ipInfo); - - //Restart DHCP server - wifi_softap_dhcps_start(); - - //Set WiFi event handler - wifi_set_event_handler_cb(&wifi_handler); - - startServer(); -} - -void startServer() { - //Configure TCP server - tcpServerConn.type = ESPCONN_TCP; - tcpServerConn.state = ESPCONN_NONE; - tcpServerConn.proto.tcp = (esp_tcp*)os_malloc(sizeof(esp_tcp)); - tcpServerConn.proto.tcp->local_port = TCP_PORT; - - espconn_regist_connectcb(&tcpServerConn, &tcp_connect_handler); - - tcpClient = NULL; - - //Start TCP server - espconn_accept(&tcpServerConn); - - //Set maximum connection count - espconn_tcp_set_max_con(1); -} - -void wifi_handler(System_Event_t *event) { - switch(event->event) { - case EVENT_SOFTAPMODE_STACONNECTED: - //TODO: Perhaps do something with this information - break; - - case EVENT_SOFTAPMODE_STADISCONNECTED: - //TODO: Maybe do something here? - break; - - default: - break; - } -} - -void tcp_connect_handler(void *arg) { - struct espconn *conn = (struct espconn*)arg; - - espconn_regist_disconcb(conn, &tcp_disconnect_handler); - espconn_regist_recvcb(conn, &tcp_recv_handler); - espconn_regist_sentcb(conn, &tcp_sent_handler); - espconn_regist_write_finish(conn, &tcp_write_handler); - - //Set socket options - espconn_set_opt(conn, ESPCONN_NODELAY | ESPCONN_REUSEADDR | ESPCONN_KEEPALIVE | ESPCONN_COPY); - - tcpClient = conn; - _tcpRecvHold = 0; - - _tcpSendActive = 0; - _tcpSendBufferLen = 0; -} - -void tcp_disconnect_handler(void *arg) { - tcpClient = NULL; - - char msg[128]; - os_sprintf("tcp_disconnect_handler: %d\r\n", (int)_tcpSendBufferLen); - uart0_send_nowait(msg, strlen(msg)); - - _tcpSendBufferLen = 0; - _tcpSendActive = 0; -} - -void tcp_recv_handler(void *arg, char *data, unsigned short len) { - //Send over UART - - //Copy into UART tx buffer - if( (_txBufferLen + len) > _txBufferSize ) { - //Yikes! - espconn_recv_hold((struct espconn*)arg); - _tcpRecvHold = 1; - } - else { - if(_txBufferLen == 0) { - //Software buffer is empty - - //Put as much as possible into FIFO - uint16 sent = uart0_send_nowait(data, len); - - if(sent < len) { - //Put the rest in the software buffer - memcpy((uint8*)_txBuffer, data + sent, len - sent); - _txBufferLen = len - sent; - uart_set_txto(); - } - } - else { - //Just copy all of the data into the software buffer - memcpy((uint8*)_txBuffer + _txBufferLen, data, len); - _txBufferLen += len; - uart_set_txto(); - } - - if( (_tcpRecvHold == 0) && - (_txBufferSize - _txBufferLen) < (10*TCP_MAX_PACKET_SIZE) ) { - //If we can't fit another packet into the software buffer - //Temporarily disable receiving - espconn_recv_hold((struct espconn*)arg); - _tcpRecvHold = 1; - - _tcpHoldCount++; - - } - } - - - _ledSet = 1; -} - -int tcpSendSome() { - if(_tcpSendBufferLen == 0) { - return 0; - } - else if(tcpClient == NULL) { - return 0; - } - - uint16 sendAmt = (_tcpSendBufferLen < TCP_MAX_SEND) ? (_tcpSendBufferLen) : (TCP_MAX_SEND); - - sint8 retval = espconn_sent(tcpClient, (uint8*)_tcpSendBuffer, sendAmt); - - if(retval != 0) { - /* - char buffer[128]; - char *msg; - - if(retval == ESPCONN_MEM) { - msg = "[Error] espconn_sent returned ESPCONN_MEM\r\n"; - } - else if(retval == ESPCONN_ARG) { - msg = "[Error] espconn_sent returned ESPCONN_ARG\r\n"; - } - else { - os_sprintf(buffer, "[Error] espconn_sent returned an unknown error: %d\r\n", (int)retval); - msg = buffer; - } - uart0_send_nowait(msg, strlen(msg)); - - - char msg[128]; - os_sprintf("tcpSendSome: Failed to send (%d)\r\n", (int)_tcpSendBufferLen); - uart0_send_nowait(msg, strlen(msg)); - */ - //Error, nothing was sent - return 0; - } - else { - //Remove the sent data from the buffer - memmove((uint8*)_tcpSendBuffer, (uint8*)_tcpSendBuffer + sendAmt, (uint16)_tcpSendBufferLen - sendAmt); - _tcpSendBufferLen -= sendAmt; -/* - char msg[128]; - os_sprintf("tcpSendSome: Sent %d (%d left)\r\n", (int)sendAmt, (int)_tcpSendBufferLen); - uart0_send_nowait(msg, strlen(msg)); -*/ - return sendAmt; - } -} - -void tcp_sent_handler(void *arg) { - //Nothing to do here - char msg[128]; - os_sprintf(msg, "tcp_sent_handler: %d, %d\r\n", (int)_tcpSendActive, (int)_tcpSendBufferLen); - uart0_send_nowait(msg, strlen(msg)); -} - -void tcp_write_handler(void *arg) { - if(tcpClient == NULL) { - return; - } - - //Debug stuff - char msg[128]; - os_sprintf(msg, "tcp_write_handler: %d, %d\r\n", (int)_tcpSendActive, (int)_tcpSendBufferLen); - uart0_send_nowait(msg, strlen(msg)); - - if(_tcpSendBufferLen > 0) { - //Send some more - int sent = tcpSendSome(); - - if(sent == 0 || _tcpSendBufferLen == 0) { - _tcpSendActive = 0; - } - } - else { - _tcpSendActive = 0; - } -} - -//Init function -void ICACHE_FLASH_ATTR -user_init() -{ - //Remove debug statements from UART0 - system_set_os_print(0); - - // Initialize the GPIO subsystem. - gpio_init(); - - //Set GPIO2 to output mode - PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2); - - //Set GPIO2 low - gpio_output_set(0, BIT0, BIT0, 0); - - //Initialize UART - uart_init(BAUD, BAUD); - - //Initialize UART TX buffer - _txBuffer = (uint8*)os_malloc(UART_TX_BUFFER_SIZE); - _txBufferSize = UART_TX_BUFFER_SIZE; - _txBufferLen = 0; - - //Initialize TCP send buffer - _tcpSendBuffer = (uint8*)os_malloc(TCP_SEND_BUFFER_SIZE); - _tcpSendBufferLen = 0; - _tcpSendActive = 0; - - //Initialize WiFi - wifi_init(); - - //Start TCP server - startServer(); - - _ledSet = 0; - - //Disarm timer - os_timer_disarm(&networkTimer); - - //Setup timer - os_timer_setfn(&networkTimer, (os_timer_func_t *)network_task, NULL); - - //Arm the timer - os_timer_arm(&networkTimer, NETWORK_UPDATE_RATE, 1); - - //Start os task - system_os_task(uart_task, UART_TASK_PRIORITY,user_procTaskQueue, - user_procTaskQueueLen); -} diff --git a/wifi_bridge/README.md b/wifi_bridge/README.md new file mode 100644 index 0000000000000000000000000000000000000000..59a44d3a91cd05c4841a8416e6cbadf3328a275b --- /dev/null +++ b/wifi_bridge/README.md @@ -0,0 +1,15 @@ +# Wifi Bridge Documentation + +This directory contains all code that pertains to the ESP8266 ESP-01 chip. +This allows the MicroCART quad to use Wifi for communication. This directory +codes the following: + + * The code that is actually running on the Quad (if acting as an AP) is in the directory [ESP8266_Wifi-Serial-Adapter-AP](./ESP8266_Wifi-Serial-Adapter-AP). + * The code that is actually running on the Quad (if acting as an Client) is in the directory [ESP8266_Wifi-Serial-Adapter-Client](./ESP8266_Wifi-Serial-Adapter-Client). + * Old Arduino projects and c code used during development in the directory [wifi_dropin_old](./wifi_dropin_old). + * Test scripts for the wifi bridge are in [test_scripts](./test_scripts). + * An Arduino project for a simple bridge in [simple_bridge](./simple_bridge), also see the [README](./simple_bridge/README.md). + * An Arduino project for a less simple bridge (more similar to the AP ESP Open SDK version) in [simple_bridge2](./simple_bridge2), also see the [README](./simple_bridge2/README.md). + * A Visual Studio project for Serial Echo is contained in [SerialEchoConsole](./SerialEchoConsole). This was used for latency testing the wifi latency. + +For instructions on how to program the ESP8266 ESP-01 see [ESP Programming Documentation](./esp_programming.md). diff --git a/wifi_bridge/esp_programming.md b/wifi_bridge/esp_programming.md new file mode 100644 index 0000000000000000000000000000000000000000..cec42052d65828261cf3209d17a98aed94896713 --- /dev/null +++ b/wifi_bridge/esp_programming.md @@ -0,0 +1,72 @@ +# WIFI Bridge Documentation + +## ESP8266 ESP-01 Programming + +This document will go over all the steps needed to program the ESP8266 ESP-01 chip +used on the MicroCART quad. These chips are a SOC (System on chip) design meaning that they can +be programmed as they act like a small computer. The base directory for the AP software is in the +folder [ESP8266_Wifi-Serial-Adapter-AP](./ESP8266_Wifi-Serial-Adapter-AP). The base directory for the +Client software is in the folder [ESP8266_Wifi_Serial_Adapter-Client](./ESP8266_Wifi_Serial_Adapter_Client). + +### Hardware Setup + +The ESP-01 chip contains on-board memory which can be flashed with a program +that the chip is intended to run. There are multiple setups that can be used +to program the chip, like using an [Arduino](./images/ESP8266_setup.png), but the approach that is taken is +using a circuit with buttons to control reset and GPIO 2, with a USB converter. +This circuit was taken from [here](https://www.allaboutcircuits.com/projects/breadboard-and-program-an-esp-01-circuit-with-the-arduino-ide/). + +A perfboard design has been made, as seen below, and can be found in the MicroCART cabinet in the corner of the lab. The pinout should be included on the box that +contains the board, but will also be shown below. Note that the USB convert chip can also +be swapped if needed. Also if you would like to design your own circuit please seen the actual +circuit also included below. + + + +Pinouts: + + + +Below is an image of the circuit: + + + +### Software setup + +The current software that runs on the chip does not use the Arduino IDE for +programming as it did not give the low level access needed to a reliable system, +as it caused issues with dropping packets (but this could be a fun process of porting +the software to work correctly within the Arduino IDE for ease of use). As such +esp-open-sdk is needed. This is open source software than can be installed from +[here](https://github.com/pfalcon/esp-open-sdk), the repository also goes over +the installation process. Please note that this process may take about 40 minutes. Also, +note that this is not installed on the MicroCART computers in the lab. +You will need the following packages installed: + + gperf bison flex texinfo help2man gawk make libtool-bin libncurses5-dev + +Once esp-open-sdk is installed open the [Makefile](./ESP8266_Wifi-Serial-Adapter-AP/Makefile) within [ESP8266_Wifi-Serial-Adapter-AP](./ESP8266_Wifi-Serial-Adapter-AP) +directory. This Makefile needs the path to the compiler named [XTENSA_TOOLS_ROOT](./ESP8266_Wifi-Serial-Adapter-AP/Makefile#L22), +the base directory of the ESP8266 SDK package named [SDK_BASE](./ESP8266_Wifi-Serial-Adapter-AP/Makefile#L26) and +as well as the port the ESP programming circuit is connected to named [ESPPORT](./ESP8266_Wifi-Serial-Adapter-AP/Makefile#L30). + +**NOTE: do the same steps as above for the Client code as well.** + +### Programming Steps + +After completing the software setup you should be able to run `make`. This Makefile also +contains the capability to flash the chip with the command `make flash`. But before this +you must do the following with the hardware circuit: + + 1. Hold down the RESET button. + 2. Hold down the FLASH button. + 3. Release the RESET button. + 4. Release the FLASH button. + +The timing on these steps can be finicky but usually releasing the FLASH button a couple +seconds after the RESET button works. Now run `make flash`. + +Congrats you are done programming!! + +If any more explanation is needed please read the orginal page that goes over programming +with this circuit, linked above as well as [here](https://www.allaboutcircuits.com/projects/breadboard-and-program-an-esp-01-circuit-with-the-arduino-ide/). diff --git a/wifi_bridge/images/ESP-01_Connection_Diagram.png b/wifi_bridge/images/ESP-01_Connection_Diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..1af72e8cfc80f3e1da46c4a409be333c93822e64 Binary files /dev/null and b/wifi_bridge/images/ESP-01_Connection_Diagram.png differ diff --git a/wifi_bridge/images/ESP8266_setup.png b/wifi_bridge/images/ESP8266_setup.png new file mode 100644 index 0000000000000000000000000000000000000000..9c67acb4cba2a4f0a3e2724ef8be707beee93e13 Binary files /dev/null and b/wifi_bridge/images/ESP8266_setup.png differ diff --git a/wifi_bridge/images/perfboard_circuit.png b/wifi_bridge/images/perfboard_circuit.png new file mode 100644 index 0000000000000000000000000000000000000000..79e1db37a20ca367e9da2e3931475a2f9bfdf1c8 Binary files /dev/null and b/wifi_bridge/images/perfboard_circuit.png differ diff --git a/wifi_bridge/images/perfboard_pinout b/wifi_bridge/images/perfboard_pinout new file mode 100644 index 0000000000000000000000000000000000000000..b8a162f9306bfc5093049674c340a1007f94fa4b --- /dev/null +++ b/wifi_bridge/images/perfboard_pinout @@ -0,0 +1 @@ +<mxfile userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36" version="8.5.0" editor="www.draw.io" type="google"><diagram id="bdcc5db4-ac34-57cf-e0e9-29462034d689" name="Page-1">5Zpdc6IwFIZ/DZfuEMKHXrZqu73YrlPcj9sIUZgiYSGuur9+gwSVHJztzFZI23FG4QQS8pyTnDdBA4/Xu/ucZNEXFtLEsMxwZ+CJYVne0BXfpWFfGWxvVBlWeRxWJnQy+PEfKo2mtG7ikBaNCzljCY+zpjFgaUoD3rCRPGfb5mVLljRbzciKAoMfkARaf8Qhjyrr0DFP9s80XkV1y8iUJWtSXywNRURCtj0z4amBxzljvDpa78Y0KdnVXKr77i6UHh8spyl/yQ3YIQsLLa3A9WzPowNsVTX8JslGdlY+KN/Xvc/ZJg1pWYFp4NttFHPqZyQoS7fC3cIW8XUizpA4XLKUSwciV5wnZEGTWxI8rw7VjFnC8kO1eOqWn/KWOEna7PLJaM7p7mJ30RGiCD7K1pTne3GJvGEkscu4c53qdHtyolM7MTpzoOvJC4kMnNWx5hNbcSDxtqP28IKShWsvHERsFwUDBFDjT/g7wP0PwKTIqhBfxrvSKa+B6RivkpNVQzkDNWzhVNteFROMyJ86MnK8Hhnht8HIHvXIyH4jjFCPjJy3wQjjHhm5gNH940RHSm6Hs7aqI2Buu8vZWlhmbEtz8etvsizZA2yi97xJquA5e6a1HkhZShWJIE0kiVepOA0ELdECvi1ZxkKz3ciCdRyGZTOtiqWpaVTRco2U+sJhbl3BOXAmnGsxzFV51uUwVxnBmVAXcaZS6lJ4qJTgXPjkz3WE1KXyUCF5ANL0UUtGHSoPldEQMvJnQ8sVAWaKo4GJPk6qANOgCf2C3I5yxQg4RhO1gz19kkU9cM7nQS0yqgqpz1yBoCa8nz18FRY4tjVA1WfGQHDPQ6KytETVY+JAcOtjMn8yLDcpk8NCLDXcFT92u19ux73FHrbVADe4CBjPfR0p9Tpn6bsMUDH1Ol/BdYAeK0oAqc+ZCq4D9BAJKqRelRRcCGiiN1VKve6uQVX+zRedNMcsPXRSpD3zbj55ED8CRhwAgO928eTYTjPHtoz4UYubrrF2sqCMq4VJ2fOGR9xfG1YXDIoDk5tS79nZ7lRYixm4NjZnNF8uGMnD8jhO2YbXTYmnrlq7IITebSioW64Iwde9VlfraAvq1P+e1a4xfEyvycyEzLqa5SwovgAyUUOcFZdCrGt4SIHXEnBt8eZeAx5MpDrGGx6O9Ik3mFX1jjc8UuD1GG+1Zjx/45eQIioVyBxud7/bpKMGtPeyeL5GysFww+2JFpR/NJc4ig5occkrKUKjfMtd/3XvUHb2/0c8/Qs=</diagram></mxfile> \ No newline at end of file diff --git a/wifi_bridge/images/perfboard_pinout.png b/wifi_bridge/images/perfboard_pinout.png new file mode 100644 index 0000000000000000000000000000000000000000..83645b8eadc55489f826d17a3f6e516fba3b68bf Binary files /dev/null and b/wifi_bridge/images/perfboard_pinout.png differ diff --git a/wifi_bridge/simple_bridge/README.md b/wifi_bridge/simple_bridge/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fa96ddf365c393c4e5a18b42046056f40a922bd3 --- /dev/null +++ b/wifi_bridge/simple_bridge/README.md @@ -0,0 +1,62 @@ +# WIFI Bridge Documentation + +## Simple Bridge + +This directory contains files that can be used to setup the ESP8266 +chip with a simple bridge. This will configure the ESP8266 to be a WIFI access +point that can be accessed via the SSID uCart_AP. The ESP8266 chip will check +for data and if there is anything waiting the ESP will grab the data and send +it back to the connected client as well as print it over serial. + +**Note: ESP8266 Platform is required, see [Arduino Project Hub](https://create.arduino.cc/projecthub/ROBINTHOMAS/programming-esp8266-esp-01-with-arduino-011389) for in depth steps on how to add this.** + +### SETUP + +In order to program the ESP8266 setup will be needed. First, obtain a ESP8266 +chip and an Arduino UNO and wire as shown in the image below. The connections +that are needed are as follows: + + * Connect ground (GND) of the ESP-015 to the ground of the Arduino. + * Connect GPIO 0 (I00) of the ESP-015 to the ground of the Arduino (only duri + ng programming, otherwise do not connect this pin). + * Connect enable (EN) of the ESP-015 to 3.3 V. + * Connect vcc (3V3) of the ESP-015 to 3.3 V. + * Connect RX of the ESP-015 to digital pin 0 (labeled RX<-0) of the Arduino. + * Connect TX of the ESP-015 to digital pin 1 (labeled TX->0) of the Arduino. + +**NOTE: In the image below GPIO 2 is connected to a LED, that is NOT needed +for our program, but can be used to provide visual feedback.** + +**NOTE: In the image below 5V of the Arduino UNO is connected to a voltage divider. +This is the better way to power the ESP8266 as the 3.3 V from the +Arduino UNO is poor. That being said, it does work to connect directly to +3.3 V.** + +Image taken from [Arduino Project Hub](https://create.arduino.cc/projecthub/ROBINTHOMAS/programming-esp8266-esp-01-with-arduino-011389) + + + +### Programming + +Once all connections are made first make sure that the GPIO 0 pin is connected +to ground for programming. Open the simple_bridge.ino file in the Arduino IDE +and verify/compile (use Verify button or Sketch->Verify/Compile). Then before +programming make sure that the Arduino UNO is connected to the computer and +select the "Generic ESP8266 Module" as the board and the proper port for +programming. Next upload the files (use Upload Button or Sketch->Upload). + +After the Upload has completed (look for 'closing bootloader' and then 'flush +complete'), and disconnect the Arduino UNO. Disconnect the GPIO 0 pin from the +ESP8266 chip and reconnect the Arduino UNO to power the chip. + +### Connecting to Access Point + +After uploading the code one should be able to connected to the access point +by finding the uCart_AP ssid in the wifi select window. + +### Running TCP Corrup Test + +Once connected to the access point the TCP Corrup Test can be run using python3. +The command is as follows: `python3 tcp_corrup_test.py`. This test will make +sure that communication is working between the ESP8266 and the connected client. +Upon successful completion of this test 'Successfully received 20000' will be printed. diff --git a/wifi_bridge/simple_bridge/simple_bridge.ino b/wifi_bridge/simple_bridge/simple_bridge.ino index 4366654d02733a951b06665e7f786ba2152b0d9d..1afa5d5932bd96f605274f882cf9804204a6b37d 100644 --- a/wifi_bridge/simple_bridge/simple_bridge.ino +++ b/wifi_bridge/simple_bridge/simple_bridge.ino @@ -34,7 +34,7 @@ int ser_buf_size = 1024; byte* serial_buf = (byte*) malloc(ser_buf_size); void setup() { - Serial1.begin(115200); + //Serial1.begin(115200); //WiFi.begin(ssid, password); @@ -81,6 +81,7 @@ void loop() { int retval = serverClients[0].read(tcp_buf, aval); Serial.write(tcp_buf, aval); + serverClients[0].write((const uint8_t*)tcp_buf, aval); } } @@ -97,3 +98,4 @@ void serialFlush(){ char t = Serial.read(); } } + diff --git a/wifi_bridge/simple_bridge2/README.md b/wifi_bridge/simple_bridge2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5966b8bbb4a2cee1e6d3d91f7cee470308b74e7a --- /dev/null +++ b/wifi_bridge/simple_bridge2/README.md @@ -0,0 +1 @@ +Simple Bridge 2 is a more secure version of simple bridge as in it has a password. The identical TCP script can be used to test it, but in order to setup the wifi communication loop for the TCP script to work correctly [COMM_LOOP](./simple_bridge2.ino#L25) needs to be set to 1 and the ESP chip must be reprogramming. This arduino project is closer to the ESP OPEN SDK model. It does print information to serial at a baud rate of 1,000,000. In order to see how to program and more information as a whole about simple bridge look [here](../simple_bridge/README.md). diff --git a/wifi_bridge/simple_bridge2/SerialEchoConsole.py b/wifi_bridge/simple_bridge2/SerialEchoConsole.py new file mode 100644 index 0000000000000000000000000000000000000000..ff1885691dc8c25bd228b9858951e1b96f71c8b6 --- /dev/null +++ b/wifi_bridge/simple_bridge2/SerialEchoConsole.py @@ -0,0 +1,46 @@ +import serial +import sys + +def main(): + #port is set to the port by the user, this is an example value + port = "/dev/ttyUSB0" + #baudrate is set to the baud rate by the user, this is an example value + baudrate = 921600 + + #Get the port and baudrate + if len(sys.argv) == 3: + port = sys.argv[1] + baudrate = sys.argv[2] + else: + print('Improper usage, expecting python SerialEchoConsole.py <port> <baudrate>') + print('Note: this file accepts both Windows and Linux ports, for example COM3 as well as /dev/ttyUSB0 would both be accepted') + print('Note: if using this serial echo colsole for the base MicroCART files the baud rate should be 921600') + return 1 + + print('Starting...') + + with serial.Serial(port=port, baudrate=baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None) as ser: + #ser.open() + counter = 0 + while ser.is_open: + + if ser.in_waiting > 0: + rec = ser.read(ser.in_waiting) + print(":".join("{:02x}".format(c) for c in rec)) + ser.write(bytes(rec)) + print('.', end='') + sys.stdout.flush() + counter += 1 + if counter > 50: + counter = 0 + print() + + #if not sys.stdin.isatty(): + # for line in sys.stdin: + # print('Will attempt to write:') + # print(line.strip()) + + print('Exiting...') + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/wifi_bridge/simple_bridge2/simple_bridge2.ino b/wifi_bridge/simple_bridge2/simple_bridge2.ino new file mode 100644 index 0000000000000000000000000000000000000000..227577e74723caab478307f9bd52aa4062b31f2c --- /dev/null +++ b/wifi_bridge/simple_bridge2/simple_bridge2.ino @@ -0,0 +1,153 @@ +/* + WiFiTelnetToSerial - Example Transparent UART to Telnet Server for esp8266 + + Copyright (c) 2015 Hristo Gochkov. All rights reserved. + This file is part of the ESP8266WiFi library for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include <ESP8266WiFi.h> +#include <algorithm> + +//Set to 1 for the server to loop messages back to client +#define COMM_LOOP 0 + +//Set to 1 for Serial Loop (same idea as above) +#define SERIAL_LOOP 1 + +//Set to 1 for debug prints on start +#define DEBUG_PRINT 1 + +//how many clients should be able to telnet to this ESP8266 +#define MAX_SRV_CLIENTS 1 + +//SSID and PASSWORD SAME AS MICROCART WIFI IN LAB OR ON AP ESP8266 ESP-01 +const char* ssid = "MicroCART"; +const char* password = "m1cr0cart"; + +//Set up sever on 8080 port (TCP Server) +WiFiServer server(8080); + +//Set up clients +WiFiClient serverClients[MAX_SRV_CLIENTS]; + +//TCP and Serial buffer +int tcp_buf_size = 2048; +byte* tcp_buf = (byte*) malloc(tcp_buf_size); +int ser_buf_size = 1024; +byte* serial_buf = (byte*) malloc(ser_buf_size); + +//Setup for AP +IPAddress ip(192, 168, 1, 1); +IPAddress gateway(198, 168, 1, 1); +IPAddress subnet(255, 255, 255, 0); + +void setup() { + //start serial + Serial.begin(1000000); + Serial.setRxBufferSize(1024); + +#if DEBUG_PRINT == 1 + Serial.printf("Setting soft-AP configuration ... \r\n"); + Serial.printf("%s\r\n", WiFi.softAPConfig(ip, gateway, subnet) ? "Ready" : "Failed!"); +#else + WiFi.softAPConfig(ip, gateway, subnet); +#endif + + //Configure for access point. +#if DEBUG_PRINT == 1 + Serial.printf("Setting mode ... \r\n"); + Serial.printf("%s\r\n", WiFi.mode(WIFI_AP) ? "Ready" : "Failed!"); +#else + WiFi.mode(WIFI_AP); +#endif + +#if DEBUG_PRINT == 1 + Serial.printf("Setting soft-AP ... \r\n"); +#endif + // Wait for Access point to be created + while (!WiFi.softAP(ssid, password)) { +#if DEBUG_PRINT == 1 + Serial.printf("Failed!\r\n"); +#endif + delay(500); // Wait half a second before re-trying + } +#if DEBUG_PRINT == 1 + Serial.printf("Ready\r\n"); +#endif + +#if DEBUG_PRINT == 1 + Serial.printf("Soft-AP IP address = "); + Serial.print(WiFi.softAPIP()); + Serial.printf("\r\n"); + + Serial.printf("MAC address = %s\r\n", WiFi.softAPmacAddress().c_str()); +#endif + + //start server + server.begin(); + server.setNoDelay(true); + +} + +void loop() { + + uint8_t i, j; + //check if there are any new clients + if (server.hasClient()){ + for(i = 0; i < MAX_SRV_CLIENTS; i++){ + //find free/disconnected spot + if (!serverClients[i] || !serverClients[i].connected()){ + if(serverClients[i]) serverClients[i].stop(); + serverClients[i] = server.available(); + continue; + } + } + serialFlush(); + //no free/disconnected spot so reject + WiFiClient serverClient = server.available(); + serverClient.stop(); + } + + //check clients for data + if (serverClients[0] && serverClients[0].connected()){ + //delay(1); + while(serverClients[0].available()){ + int aval = std::min(serverClients[0].available(), tcp_buf_size); + + int retval = serverClients[0].read(tcp_buf, aval); +#if COMM_LOOP == 1 + int written = serverClients[0].write((const uint8_t*)tcp_buf, aval); +#endif + Serial.write(tcp_buf, aval); + } + } + + if (Serial.available()) { + size_t len = std::min(Serial.available(), ser_buf_size); + Serial.readBytes(serial_buf, len); + int written = serverClients[0].write((const uint8_t*)serial_buf, len); + +#if SERIAL_LOOP == 1 + Serial.write(serial_buf, len); +#endif + } +} + +void serialFlush(){ + while(Serial.available() > 0) { + char t = Serial.read(); + } +} diff --git a/wifi_bridge/simple_bridge2/tcp_corrup_test.py b/wifi_bridge/simple_bridge2/tcp_corrup_test.py new file mode 100644 index 0000000000000000000000000000000000000000..78c354e0922a3cab546db28df2400ed93c87145c --- /dev/null +++ b/wifi_bridge/simple_bridge2/tcp_corrup_test.py @@ -0,0 +1,74 @@ +import socket +import time +import csv + +TCP_IP = "192.168.1.1" +TCP_PORT = 8080 + +# sock.bind(('', UDP_PORT)) + +send_size = 350 +message = bytes(i % 256 for i in range(send_size)) +times_full = [] +times_network = [] +dropped = True +response = bytes("initial", 'ASCII') +recvd_data = [] + +n_matched = 0 + +for i in range(20000): + if dropped: + attempts = 0 + while attempts < 5: + print("Trying to connect") + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(2) + try: + sock.connect((TCP_IP, TCP_PORT)) + dropped = False + break + except: + attempts += 1 + if dropped: + print("Failed to connect") + break + print("connected") + send_msg = message + + sock.send(send_msg) + try: + # while len(recvd_data) < send_size+4: + response = sock.recv(1024) + recvd_data.extend(response) + except: + print("timed out") + dropped = True + sock.close() + + if len(recvd_data) >= send_size or dropped: + response = bytes(recvd_data[0:send_size]) + if response != message: + print("Don't match") + print(":".join("{:02x}".format(c) for c in message)) + print(":".join("{:02x}".format(c) for c in response)) + else: + n_matched += 1 + recvd_data = recvd_data[send_size:] + + # written = int.from_bytes(recvd_data[0:4], byteorder='little') + # recvd_data = recvd_data[4:] + # print("ESP said wrote " + str(written)) + + # print(":".join("{:02x}".format(c) for c in response)) + if dropped: + recvd_data = [] + print("") + # break + time.sleep(0.01) + if i % 1000 == 0: + print(i) + +print("Successfully received " + str(n_matched)) + + diff --git a/wifi_bridge/test_scripts/.gitignore b/wifi_bridge/test_scripts/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6ada7e5dca1937951bbc93ef422da5627b38efb9 --- /dev/null +++ b/wifi_bridge/test_scripts/.gitignore @@ -0,0 +1,2 @@ +*.csv +*.ods diff --git a/wifi_bridge/test_scripts/tcp_timer.py b/wifi_bridge/test_scripts/tcp_timer_AP.py similarity index 90% rename from wifi_bridge/test_scripts/tcp_timer.py rename to wifi_bridge/test_scripts/tcp_timer_AP.py index 6732f05012b8b354e36188a2f5b54822cc2933b9..c2fb738646dc04a7053fa42316618520d248a112 100644 --- a/wifi_bridge/test_scripts/tcp_timer.py +++ b/wifi_bridge/test_scripts/tcp_timer_AP.py @@ -11,12 +11,12 @@ TCP_PORT = 8080 message = bytes(range(36)) times_full = [] times_network = [] -times = [0.0]*200 +times = [0.0]*10000 dropped = True response = bytes("initial", 'ASCII') addr = "initial" recvd_data = [] -for i in range(200): +for i in range(10000): if dropped: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) @@ -24,7 +24,7 @@ for i in range(200): sock.connect((TCP_IP, TCP_PORT)) dropped = False send_msg = list(message) - send_msg[0] = i + send_msg[0] = i % 256 send_msg = bytes(send_msg) send_time = time.perf_counter() @@ -51,7 +51,7 @@ for i in range(200): while time.perf_counter() - send_time < 0.01: pass - with open("tcp_dist.csv", 'w', newline='') as f: + with open("tcp_dist_AP.csv", 'w', newline='') as f: writer = csv.writer(f) for t in times_network: writer.writerow([t]) diff --git a/wifi_bridge/test_scripts/tcp_timer_client1.py b/wifi_bridge/test_scripts/tcp_timer_client1.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5219b2887af768232e5874618d508f945eda91 --- /dev/null +++ b/wifi_bridge/test_scripts/tcp_timer_client1.py @@ -0,0 +1,64 @@ +import socket +import time +import csv + +TCP_IP = "192.168.1.2" +# UDP_IP = "127.0.0.1" +TCP_PORT = 8080 + +# sock.bind(('', UDP_PORT)) + +message = bytes(range(36)) +times_full = [] +times_network = [] +times = [0.0]*10000 +dropped = True +response = bytes("initial", 'ASCII') +addr = "initial" +recvd_data = [] +for i in range(10000): + if dropped: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + sock.settimeout(2) + sock.connect((TCP_IP, TCP_PORT)) + dropped = False + send_msg = list(message) + send_msg[0] = i % 256 + send_msg = bytes(send_msg) + + send_time = time.perf_counter() + times[i] = send_time + sock.send(send_msg) + try: + response = sock.recv(1024) + recvd_data.extend(response) + except: + print("timed out") + dropped = True + if len(recvd_data) >= 36: + end_time = time.perf_counter() + response = bytes(recvd_data[0:36]) + recvd_data = recvd_data[36:] + msg_id = int(response[0]) + latency = end_time - times[msg_id] + # serial_time = int.from_bytes(response[0:4], byteorder='big') / 1000 + serial_time = 0 + # times_full.append(1000 * (end_time - send_time) - 0) + times_full.append(1000 * latency) + times_network.append(1000 * (end_time - send_time) - serial_time) + print("received " + str(response) + " in " + str(times_full[-1]) + " from " + str(addr)) + while time.perf_counter() - send_time < 0.01: + pass + + with open("tcp_dist_client1.csv", 'w', newline='') as f: + writer = csv.writer(f) + for t in times_network: + writer.writerow([t]) + +for time in [times_full, times_network]: + print("lowest: " + str(min(time))) + print("highest: " + str(max(time))) + print("median: " + str(sorted(time)[int(len(time) / 2)])) + print("average; " + str(sum(time) / len(time))) + diff --git a/wifi_bridge/test_scripts/tcp_timer_client2.py b/wifi_bridge/test_scripts/tcp_timer_client2.py new file mode 100644 index 0000000000000000000000000000000000000000..df852617f0070e32c1422bb1a7dc8b345492b5a7 --- /dev/null +++ b/wifi_bridge/test_scripts/tcp_timer_client2.py @@ -0,0 +1,64 @@ +import socket +import time +import csv + +TCP_IP = "192.168.1.3" +# UDP_IP = "127.0.0.1" +TCP_PORT = 8080 + +# sock.bind(('', UDP_PORT)) + +message = bytes(range(36)) +times_full = [] +times_network = [] +times = [0.0]*10000 +dropped = True +response = bytes("initial", 'ASCII') +addr = "initial" +recvd_data = [] +for i in range(10000): + if dropped: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + sock.settimeout(2) + sock.connect((TCP_IP, TCP_PORT)) + dropped = False + send_msg = list(message) + send_msg[0] = i % 256 + send_msg = bytes(send_msg) + + send_time = time.perf_counter() + times[i] = send_time + sock.send(send_msg) + try: + response = sock.recv(1024) + recvd_data.extend(response) + except: + print("timed out") + dropped = True + if len(recvd_data) >= 36: + end_time = time.perf_counter() + response = bytes(recvd_data[0:36]) + recvd_data = recvd_data[36:] + msg_id = int(response[0]) + latency = end_time - times[msg_id] + # serial_time = int.from_bytes(response[0:4], byteorder='big') / 1000 + serial_time = 0 + # times_full.append(1000 * (end_time - send_time) - 0) + times_full.append(1000 * latency) + times_network.append(1000 * (end_time - send_time) - serial_time) + print("received " + str(response) + " in " + str(times_full[-1]) + " from " + str(addr)) + while time.perf_counter() - send_time < 0.01: + pass + + with open("tcp_dist_client2.csv", 'w', newline='') as f: + writer = csv.writer(f) + for t in times_network: + writer.writerow([t]) + +for time in [times_full, times_network]: + print("lowest: " + str(min(time))) + print("highest: " + str(max(time))) + print("median: " + str(sorted(time)[int(len(time) / 2)])) + print("average; " + str(sum(time) / len(time))) + diff --git a/wifi_bridge/test_scripts/tcp_timer_client3.py b/wifi_bridge/test_scripts/tcp_timer_client3.py new file mode 100644 index 0000000000000000000000000000000000000000..3686701bdc3937cefb4a2868ae6b5b1cc322dc16 --- /dev/null +++ b/wifi_bridge/test_scripts/tcp_timer_client3.py @@ -0,0 +1,64 @@ +import socket +import time +import csv + +TCP_IP = "192.168.1.4" +# UDP_IP = "127.0.0.1" +TCP_PORT = 8080 + +# sock.bind(('', UDP_PORT)) + +message = bytes(range(36)) +times_full = [] +times_network = [] +times = [0.0]*10000 +dropped = True +response = bytes("initial", 'ASCII') +addr = "initial" +recvd_data = [] +for i in range(10000): + if dropped: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + sock.settimeout(2) + sock.connect((TCP_IP, TCP_PORT)) + dropped = False + send_msg = list(message) + send_msg[0] = i % 256 + send_msg = bytes(send_msg) + + send_time = time.perf_counter() + times[i] = send_time + sock.send(send_msg) + try: + response = sock.recv(1024) + recvd_data.extend(response) + except: + print("timed out") + dropped = True + if len(recvd_data) >= 36: + end_time = time.perf_counter() + response = bytes(recvd_data[0:36]) + recvd_data = recvd_data[36:] + msg_id = int(response[0]) + latency = end_time - times[msg_id] + # serial_time = int.from_bytes(response[0:4], byteorder='big') / 1000 + serial_time = 0 + # times_full.append(1000 * (end_time - send_time) - 0) + times_full.append(1000 * latency) + times_network.append(1000 * (end_time - send_time) - serial_time) + print("received " + str(response) + " in " + str(times_full[-1]) + " from " + str(addr)) + while time.perf_counter() - send_time < 0.01: + pass + + with open("tcp_dist_client3.csv", 'w', newline='') as f: + writer = csv.writer(f) + for t in times_network: + writer.writerow([t]) + +for time in [times_full, times_network]: + print("lowest: " + str(min(time))) + print("highest: " + str(max(time))) + print("median: " + str(sorted(time)[int(len(time) / 2)])) + print("average; " + str(sum(time) / len(time))) +