├── LICENSE ├── Makefile ├── README.md ├── captures ├── cli.png ├── esp32_gdb.png ├── esp32_openocd.png ├── esp32_ttgo.jpg ├── imu_tool.png ├── imu_tool_dashboard.png ├── jtag_capture.jpg ├── mag_calibration.png └── sdio_adapter.jpg ├── components ├── mongoose │ ├── Kconfig │ ├── component.mk │ ├── include │ │ └── mongoose.h │ └── mongoose.c └── utils │ ├── Kconfig │ ├── circ_buffer.c │ ├── cli.c │ ├── cli_telnet.c │ ├── component.mk │ ├── include │ ├── circ_buffer.h │ ├── cli.h │ ├── common_def.h │ ├── generic_list.h │ ├── io_driver.h │ ├── io_driver_notifier.h │ ├── sock_util.h │ ├── soft_timer.h │ ├── stream.h │ ├── tcp_server.h │ ├── tcp_server_ipv4.h │ ├── telnet.h │ └── telnet_reader.h │ ├── io_driver.c │ ├── io_driver_notifier.c │ ├── sock_util.c │ ├── soft_timer.c │ ├── stream.c │ ├── tcp_server.c │ ├── tcp_server_ipv4.c │ └── telnet_reader.c ├── doc ├── AK8963C.pdf ├── AN2272_001-32379_0C_V.pdf ├── MPU-9250-Register-Map.pdf ├── T10_V1.2.pdf ├── esp32_chip_pin_list_en.pdf ├── esp32_technical_reference_manual_en.pdf ├── madgwick_internal_report.pdf └── mpu9250_spec.pdf ├── imu_tool ├── .babelrc ├── .electron-vue │ ├── build.js │ ├── dev-client.js │ ├── dev-runner.js │ ├── webpack.main.config.js │ ├── webpack.renderer.config.js │ └── webpack.web.config.js ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .travis.yml ├── README.md ├── appveyor.yml ├── build │ └── icons │ │ ├── 256x256.png │ │ ├── icon.icns │ │ └── icon.ico ├── dist │ ├── electron │ │ └── .gitkeep │ └── web │ │ └── .gitkeep ├── package.json ├── src │ ├── index.ejs │ ├── main │ │ ├── index.dev.js │ │ └── index.js │ └── renderer │ │ ├── App.vue │ │ ├── assets │ │ ├── .gitkeep │ │ └── logo.png │ │ ├── components │ │ ├── Compass.vue │ │ ├── ConnectDialog.vue │ │ ├── IMUCalibration.vue │ │ ├── IMUDashboard.vue │ │ ├── IMUGraph.vue │ │ ├── InspireView.vue │ │ ├── LineChart.vue │ │ ├── MAGCalibration.vue │ │ ├── MAGCalibrationDialog.vue │ │ ├── OrientationThree.vue │ │ ├── SphereFittingView.vue │ │ ├── WelcomeView.vue │ │ └── WelcomeView │ │ │ └── SystemInformation.vue │ │ ├── imu_comm │ │ └── index.js │ │ ├── imu_comm_ws │ │ └── index.js │ │ ├── main.js │ │ ├── router │ │ └── index.js │ │ └── store │ │ ├── index.js │ │ └── modules │ │ ├── Counter.js │ │ └── index.js ├── static │ ├── .gitkeep │ └── v.png └── test │ ├── .eslintrc │ ├── e2e │ ├── index.js │ ├── specs │ │ └── Launch.spec.js │ └── utils.js │ └── unit │ ├── index.js │ ├── karma.conf.js │ └── specs │ └── LandingPage.spec.js ├── main ├── Kconfig.projbuild ├── accel_calibration.c ├── accel_calibration.h ├── app_wifi.c ├── app_wifi.h ├── blinky.c ├── blinky.h ├── component.mk ├── gyro_calibration.c ├── gyro_calibration.h ├── imu.c ├── imu.h ├── imu_task.c ├── imu_task.h ├── lcd_driver.c ├── lcd_driver.h ├── madgwick.c ├── madgwick.h ├── mag_calibration.c ├── mag_calibration.h ├── mahony.c ├── mahony.h ├── main.c ├── math_helper.h ├── mpu9250.c ├── mpu9250.h ├── mpu9250_i2c.c ├── mpu9250_i2c.h ├── sensor_calib.c ├── sensor_calib.h ├── shell.c ├── shell.h ├── st7735.c ├── st7735.h ├── webserver.c └── webserver.h ├── poll.sh ├── sdkconfig ├── sdkconfig.defaults └── tests └── cli_load_test.exp /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Hawk Kim 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # This is a project Makefile. It is assumed the directory this Makefile resides in is a 3 | # project subdirectory. 4 | # 5 | 6 | PROJECT_NAME := esp32_imu 7 | 8 | include $(IDF_PATH)/make/project.mk 9 | 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ESP32 IMU 2 | 3 | 9-DOF IMU using ESP32 and MPU9250 4 | 5 | ![esp32 ttgo](captures/esp32_ttgo.jpg "esp32 ttgo") 6 | 7 | ## current status 8 | 9 | ### IMU tool (May/29/2018) 10 | One picture is worth a thousand words! 11 | 12 | ![IMU tool](captures/imu_tool.png "IMU tool") 13 | ![IMU tool dashboard](captures/imu_tool_dashboard.png "IMU tool dashboard") 14 | ![MAG Calibration](captures/mag_calibration.png "Magnetometer Calibration") 15 | 16 | 17 | 18 | ### as of May,13,2018 19 | CLI is implemented. Now you can access ESP32 via telnet. 20 | 21 | By the way, the code might seem a bit intimidating at first. 22 | But that is how I think networking code should be written. Everything should be an event 23 | using an simple event loop. Otherwise you wouldn't be able to handle the complications and the concurrency in the end. Just my 10 cents on it! 24 | 25 | ![telnet cli](captures/cli.png "shell telnetl") 26 | 27 | ### as of May,12,2018 28 | just getting started, folks! 29 | 30 | ## Pins 31 | 32 | | Purpose | Pin # | 33 | | ---------- | ------ | 34 | | Green LED | 22 | 35 | 36 | 37 | ## Schematic 38 | 39 | Check [this](doc/T10_V1.2.pdf) out 40 | 41 | ## Boot Process 42 | 43 | To develop a firm understanding on what's going on behind the scenes, I always care about system startup process. 44 | Actually this is well explained [here](https://esp-idf.readthedocs.io/en/v2.0/general-notes.html) 45 | 46 | To sum it up, 47 | 1. ROM bootloader loads second-stage bootloader in SPI Flash to RAM from flash offset 0x1000 48 | * Second-stage bootloader source is available at components/bootloader directory of ESP-IDF. 49 | * Partition table is at 0x8000 of SPI flash. 50 | * It is interesting to note that second-stage bootloader initializes MMU! 51 | * Also it is interesting to note that SPI flash memory is memory mapped by MMU and can be read via normal memory read. 52 | 53 | 2. Second-stage bootloader loads partition table and main application image 54 | 55 | 3. main app executes 56 | 57 | Application Memory Layout. The chip itself is not that simple. 58 | ESP32 comes with 520 KiB SRAM. Most boards I know have 4 MB SPI flash. 59 | 60 | | Type | Note | 61 | | ----------- | -------------------------------------------------------------------- | 62 | | IRAM | instruction RAM. a part of internal SRAM0. fast execution & for ISRs | 63 | | IROM | instruction ROM. SPI flash. | 64 | | RTC fasl | for code that has to run after wake-up from deep sleep. | 65 | | DRAM | data ram. of course. | 66 | | DROM | read only data in SPI flash. | 67 | | RTC slow | blah blah blah | 68 | 69 | ## 1.44 LCD 70 | 71 | According to the shcematic, ST7735 TFT is connected to ESP32. 72 | 73 | | Name | Pin # | 74 | | ---------- | ------ | 75 | | MOSI | 23 | 76 | | SCK | 5 | 77 | | CS | 16 | 78 | | MOSI | 23 | 79 | | CMD/DATA | 17 | 80 | | RESET | N/A | 81 | 82 | One more thing to note is there is no pin to control LCD backlight with. 83 | It can be quite annoying. 84 | 85 | ## Debugger Setup 86 | 87 | 1. get openocd 88 | * [well explained here](http://esp-idf.readthedocs.io/en/latest/api-guides/jtag-debugging/#jtag-debugging-setup-openocd) 89 | * [download esp32 openocd](http://esp-idf.readthedocs.io/en/latest/api-guides/jtag-debugging/setup-openocd-linux.html) 90 | 91 | 2. FTDI Connection as shown below 92 | 93 | | FT2232HL | ESP32 | Purpose | SDIO Pin | 94 | | ------------ | ---------- | ---------- | -------- | 95 | |ADBUS0 | 13 | TCK | DAT3(2) | 96 | |ADBUS1 | 12 | TDI | DAT2(1) | 97 | |ADBUS2 | 15 | TDO | CMD(3) | 98 | |ADBUS3 | 14 | TMS | CLK(5) | 99 | |GND | GND | GND | VSS2(6) | 100 | |VIO | 3V3 | 3V3 | NC | 101 | 102 | Problem is pin 12/13/14/15 are used for SDIO, which means 103 | * you can't use JTAG interface while using Micro-SD slot 104 | * we need a some special SDIO adapter to connect FT2232H and ESP32 105 | 106 | And finally found a wonderful sdio adapter. 107 | ![SDIO adapter](captures/sdio_adapter.jpg "sdio adapter") 108 | Check it out at [Aliexpress](https://www.aliexpress.com/item/kebidu-Hot-sale-25CM-48CM-62CM-TF-to-micro-SD-card-Flex-Extension-cable-Extender-Adapter/32832944156.html?spm=2114.10010108.1000013.1.27bc4b3b74DRpO&scm=1007.13339.90158.0&scm_id=1007.13339.90158.0&scm-url=1007.13339.90158.0&pvid=2645295a-4392-4172-896b-e88ce2aafd8f&_t=pvid:2645295a-4392-4172-896b-e88ce2aafd8f,scm-url:1007.13339.90158.0) 109 | 110 | sdio adapter pin mapping 111 | 1 Left, 13 Right 112 | 113 | | SDIO Side | Adapter Side | Note | 114 | | --------- | ------------- | --------------------- | 115 | | 1 | 1 | TDI | 116 | | 2 | 3 | TCK | 117 | | 3 | 5 | TDO | 118 | | 4 | 7 | VDD (Do Not Connect) | 119 | | 5 | 9 | TMS | 120 | | 6 | 2,4,6,8,10,12 | GND | 121 | | 7 | 11 | NC | 122 | | 8 | 13 | NC | 123 | 124 | 125 | Got my order from China and here we go 126 | ![ESP32 JTAG Connect](captures/jtag_capture.jpg "jtag connect") 127 | 128 | And here we go 129 | ![ESP32 Openocd](captures/esp32_openocd.png "esp32 openocd") 130 | ![ESP32 GDB](captures/esp32_gdb.png "esp32 gdb") 131 | 132 | 133 | ## esptool.py 134 | ### to read parition table 135 | esptoo.py read_flash 0x8000 0xc00 partition.img 136 | 137 | ### to backup the entire flash 138 | esptool.py read_flash 0x0000 0x400000 backup.img 139 | 140 | ### to read the MAC address 141 | esptool.py read_mac 142 | 143 | ### to reset 144 | esptool.py run 145 | 146 | ### to write to flash 147 | esptoo.py write_flash address your-bin 148 | 149 | ### built-in partition table 150 | partition table is at 0x8000 with size 0xc00 151 | 152 | ### to convert binary partition table to csv 153 | gen_esp32part.py --verify binary_partitions.bin input_partitions.csv 154 | 155 | ### to convert csv to partition table 156 | gen_esp32part.py --verify input_partitions.csv binary_partitions.bin 157 | 158 | ### default esp32 partition table 159 | Espressif ESP32 Partition Table 160 | 161 | |Name |Type |SubType |Offset |Size | 162 | | -------- | ------ | --------- | --------- | -------- | 163 | | nvs | data | nvs | 0x9000 | 0x6000 | 164 | | phy_init | data | phy | 0xf000 | 0x1000 | 165 | | factory | app | factory | 0x10000 | 1M | 166 | -------------------------------------------------------------------------------- /captures/cli.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/captures/cli.png -------------------------------------------------------------------------------- /captures/esp32_gdb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/captures/esp32_gdb.png -------------------------------------------------------------------------------- /captures/esp32_openocd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/captures/esp32_openocd.png -------------------------------------------------------------------------------- /captures/esp32_ttgo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/captures/esp32_ttgo.jpg -------------------------------------------------------------------------------- /captures/imu_tool.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/captures/imu_tool.png -------------------------------------------------------------------------------- /captures/imu_tool_dashboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/captures/imu_tool_dashboard.png -------------------------------------------------------------------------------- /captures/jtag_capture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/captures/jtag_capture.jpg -------------------------------------------------------------------------------- /captures/mag_calibration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/captures/mag_calibration.png -------------------------------------------------------------------------------- /captures/sdio_adapter.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/captures/sdio_adapter.jpg -------------------------------------------------------------------------------- /components/mongoose/Kconfig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/components/mongoose/Kconfig -------------------------------------------------------------------------------- /components/mongoose/component.mk: -------------------------------------------------------------------------------- 1 | # 2 | # "main" pseudo-component makefile. 3 | # 4 | # (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) 5 | -------------------------------------------------------------------------------- /components/utils/Kconfig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/components/utils/Kconfig -------------------------------------------------------------------------------- /components/utils/circ_buffer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "circ_buffer.h" 5 | 6 | /* 7 | * initializes circular buffer 8 | * allocates a circular buffer of size "size" 9 | * 10 | * @param cb circular buffer 11 | * @param size size of circular buffer 12 | * @return 0 on success, -1 on fail 13 | */ 14 | int 15 | circ_buffer_init(circ_buffer_t* cb, int size) 16 | { 17 | cb->buffer = NULL; 18 | cb->size = 0; 19 | cb->begin = 0; 20 | cb->end = 0; 21 | cb->data_size = 0; 22 | 23 | cb->buffer = (uint8_t*)malloc(size); 24 | if(cb->buffer == NULL) 25 | { 26 | return -1; 27 | } 28 | 29 | cb->size = size; 30 | return 0; 31 | } 32 | 33 | /* 34 | * de-initializes circular buffer 35 | * frees buffer used by circular buffer 36 | * 37 | * @param cb circular buffer 38 | */ 39 | void 40 | circ_buffer_deinit(circ_buffer_t* cb) 41 | { 42 | if(cb->buffer != NULL) 43 | { 44 | free(cb->buffer); 45 | cb->buffer = NULL; 46 | } 47 | } 48 | 49 | /* 50 | * adds data to circular buffer 51 | * if the whole size data cannot be added to the circular buffer 52 | * error is returned 53 | * 54 | * @param cb circular buffer 55 | * @param buf data buffer 56 | * @param size size of data 57 | * @return 0 on success, -1 on error 58 | */ 59 | int 60 | circ_buffer_put(circ_buffer_t* cb, uint8_t* buf, int size) 61 | { 62 | if(cb->data_size + size > cb->size) 63 | { 64 | return -1; 65 | } 66 | 67 | if(cb->end + size > cb->size) 68 | { 69 | int begin_len = cb->size - cb->end; 70 | 71 | memcpy(&cb->buffer[cb->end], buf, begin_len); 72 | memcpy(&cb->buffer[0], &buf[begin_len], size - begin_len); 73 | } 74 | else 75 | { 76 | memcpy(&cb->buffer[cb->end], buf, size); 77 | } 78 | 79 | cb->end = (cb->end + size) % cb->size; 80 | cb->data_size += size; 81 | return 0; 82 | } 83 | 84 | /* 85 | * removes data from circular buffer 86 | * if the whole size data cannot be removed from the circular buffer 87 | * error is returned 88 | * 89 | * @param cb circular buffer 90 | * @param buf buffer to copy data from circular buffer 91 | * @param size size of data requested 92 | * @return 0 on success, -1 on error 93 | */ 94 | int 95 | circ_buffer_get(circ_buffer_t* cb, uint8_t* buf, int size) 96 | { 97 | if(cb->data_size - size < 0) 98 | { 99 | return -1; 100 | } 101 | 102 | if(cb->begin + size <= cb->size) 103 | { 104 | memcpy(buf, &cb->buffer[cb->begin], size); 105 | } 106 | else 107 | { 108 | int begin_len = cb->size - cb->begin; 109 | 110 | memcpy(buf, &cb->buffer[cb->begin], begin_len); 111 | memcpy(&buf[begin_len], &cb->buffer[0], size - begin_len); 112 | } 113 | 114 | cb->begin = (cb->begin + size) % cb->size; 115 | cb->data_size -= size; 116 | return 0; 117 | } 118 | 119 | /* 120 | * removes data from circular but the data is not copied to 121 | * user buffer 122 | * if the whole size data cannot be copied from the circular buffer 123 | * error is returned 124 | * 125 | * @param cb circular buffer 126 | * @param size size of data requested 127 | * @return 0 on success, -1 on error 128 | */ 129 | int 130 | circ_buffer_advance(circ_buffer_t* cb, int size) 131 | { 132 | if(cb->data_size - size < 0) 133 | { 134 | return -1; 135 | } 136 | 137 | cb->begin = (cb->begin + size) % cb->size; 138 | cb->data_size -= size; 139 | return 0; 140 | } 141 | 142 | /* 143 | * gets data from circular but the data still remains in circular buffer 144 | * if the whole size data cannot be copied from the circular buffer 145 | * error is returned 146 | * 147 | * @param cb circular buffer 148 | * @param buf user buffer to copy data to 149 | * @param size size of data requested 150 | * @return 0 on success, -1 on error 151 | */ 152 | int 153 | circ_buffer_peek(circ_buffer_t* cb, uint8_t* buf, int size) 154 | { 155 | if(cb->data_size - size < 0) 156 | { 157 | return -1; 158 | } 159 | 160 | if(cb->begin + size <= cb->size) 161 | { 162 | memcpy(buf, &cb->buffer[cb->begin], size); 163 | } 164 | else 165 | { 166 | int begin_len = cb->size - cb->begin; 167 | 168 | memcpy(buf, &cb->buffer[cb->begin], begin_len); 169 | memcpy(&buf[begin_len], &cb->buffer[0], size - begin_len); 170 | } 171 | return 0; 172 | } 173 | -------------------------------------------------------------------------------- /components/utils/cli.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "cli.h" 9 | 10 | extern void cli_telnet_intf_init(int port); 11 | extern void cli_telnet_show_connections(cli_intf_t* intf); 12 | 13 | //////////////////////////////////////////////////////////////////////////////// 14 | // 15 | // private definitions 16 | // 17 | //////////////////////////////////////////////////////////////////////////////// 18 | #define CLI_MAX_COLUMNS_PER_LINE 512 19 | #define VERSION "ESP32 CLI V1.0" 20 | 21 | #define CLI_EOL_CHAR '\r' 22 | 23 | //////////////////////////////////////////////////////////////////////////////// 24 | // 25 | // private prototypes 26 | // 27 | //////////////////////////////////////////////////////////////////////////////// 28 | static void cli_command_help(cli_intf_t* intf, int argc, const char** argv); 29 | static void cli_command_version(cli_intf_t* intf, int argc, const char** argv); 30 | static void cli_command_cli_connections(cli_intf_t* intf, int argc, const char** argv); 31 | 32 | //////////////////////////////////////////////////////////////////////////////// 33 | // 34 | // private variables 35 | // 36 | //////////////////////////////////////////////////////////////////////////////// 37 | static LIST_HEAD_DECL(_cli_intf_list); 38 | 39 | static cli_command_t _core_commands[] = 40 | { 41 | { 42 | "help", 43 | "show this command", 44 | cli_command_help, 45 | }, 46 | { 47 | "version", 48 | "show version", 49 | cli_command_version, 50 | }, 51 | { 52 | "cli_conn", 53 | "show current CLI connections", 54 | cli_command_cli_connections, 55 | }, 56 | }; 57 | 58 | static cli_command_t* _user_commands; 59 | static int _num_user_commands; 60 | 61 | static char _print_buffer[CLI_MAX_COLUMNS_PER_LINE + 1]; 62 | static const char* _prompt = "\r\nESP32> "; 63 | 64 | //////////////////////////////////////////////////////////////////////////////// 65 | // 66 | // core cli command handlers 67 | // 68 | //////////////////////////////////////////////////////////////////////////////// 69 | static void 70 | cli_command_help(cli_intf_t* intf, int argc, const char** argv) 71 | { 72 | size_t i; 73 | 74 | cli_printf(intf, CLI_EOL); 75 | 76 | for(i = 0; i < sizeof(_core_commands)/sizeof(cli_command_t); i++) 77 | { 78 | cli_printf(intf, "%-20s: ", _core_commands[i].command); 79 | cli_printf(intf, "%s"CLI_EOL, _core_commands[i].help_str); 80 | } 81 | 82 | for(i = 0; i < _num_user_commands; i++) 83 | { 84 | cli_printf(intf, "%-20s: ", _user_commands[i].command); 85 | cli_printf(intf, "%s"CLI_EOL, _user_commands[i].help_str); 86 | } 87 | } 88 | 89 | static void 90 | cli_command_version(cli_intf_t* intf, int argc, const char** argv) 91 | { 92 | cli_printf(intf, CLI_EOL); 93 | cli_printf(intf, "%s"CLI_EOL, VERSION); 94 | } 95 | 96 | static void 97 | cli_command_cli_connections(cli_intf_t* intf, int argc, const char** argv) 98 | { 99 | cli_telnet_show_connections(intf); 100 | } 101 | 102 | //////////////////////////////////////////////////////////////////////////////// 103 | // 104 | // cli core 105 | // 106 | //////////////////////////////////////////////////////////////////////////////// 107 | static void 108 | cli_execute_command(cli_intf_t* intf, char* cmd) 109 | { 110 | static const char* argv[CLI_COMMAND_MAX_ARGS]; 111 | int argc = 0; 112 | size_t i; 113 | char *s, *t; 114 | 115 | while((s = strtok_r(argc == 0 ? cmd : NULL, " \t", &t)) != NULL) 116 | { 117 | if(argc >= CLI_COMMAND_MAX_ARGS) 118 | { 119 | cli_printf(intf, CLI_EOL"Error: too many arguments"CLI_EOL); 120 | return; 121 | } 122 | argv[argc++] = s; 123 | } 124 | 125 | if(argc == 0) 126 | { 127 | return; 128 | } 129 | 130 | for(i = 0; i < sizeof(_core_commands)/sizeof(cli_command_t); i++) 131 | { 132 | if(strcmp(_core_commands[i].command, argv[0]) == 0) 133 | { 134 | cli_printf(intf, CLI_EOL"Executing %s"CLI_EOL, argv[0]); 135 | _core_commands[i].handler(intf, argc, argv); 136 | return; 137 | } 138 | } 139 | 140 | for(i = 0; i < _num_user_commands; i++) 141 | { 142 | if(strcmp(_user_commands[i].command, argv[0]) == 0) 143 | { 144 | cli_printf(intf, CLI_EOL"Executing %s"CLI_EOL, argv[0]); 145 | _user_commands[i].handler(intf, argc, argv); 146 | return; 147 | } 148 | } 149 | cli_printf(intf, "%s", CLI_EOL"Unknown Command: "); 150 | cli_printf(intf, "%s", argv[0]); 151 | cli_printf(intf, "%s", CLI_EOL); 152 | } 153 | 154 | void 155 | cli_printf(cli_intf_t* intf, const char* fmt, ...) 156 | { 157 | va_list args; 158 | int len; 159 | 160 | va_start(args, fmt); 161 | len = vsnprintf(_print_buffer, CLI_MAX_COLUMNS_PER_LINE, fmt, args); 162 | va_end(args); 163 | 164 | intf->put_tx_data(intf, _print_buffer, len); 165 | } 166 | 167 | static inline void 168 | cli_prompt(cli_intf_t* intf) 169 | { 170 | intf->put_tx_data(intf, _prompt, strlen(_prompt)); 171 | } 172 | 173 | //////////////////////////////////////////////////////////////////////////////// 174 | // 175 | // public interface 176 | // 177 | //////////////////////////////////////////////////////////////////////////////// 178 | void 179 | cli_init(cli_command_t* cmds, int num_cmds, int port) 180 | { 181 | _user_commands = cmds; 182 | _num_user_commands = num_cmds; 183 | 184 | cli_telnet_intf_init(port); 185 | } 186 | 187 | void 188 | cli_handle_rx(cli_intf_t* intf, uint8_t* data, int len) 189 | { 190 | char b; 191 | int i; 192 | 193 | for(i = 0; i < len; i++) 194 | { 195 | b = (char)data[i]; 196 | 197 | if(b != CLI_EOL_CHAR && intf->cmd_buffer_ndx < CLI_MAX_COMMAND_LEN) 198 | { 199 | if(b == '\b' || b == 0x7f) 200 | { 201 | if(intf->cmd_buffer_ndx > 0) 202 | { 203 | //cli_printf(intf, "%c%c%c", b, 0x20, b); 204 | cli_printf(intf, "%c%c%c", 0x08, 0x20, 0x08); 205 | intf->cmd_buffer_ndx--; 206 | } 207 | } 208 | else 209 | { 210 | cli_printf(intf, "%c", b); 211 | intf->cmd_buffer[intf->cmd_buffer_ndx++] = b; 212 | } 213 | } 214 | else if(b == CLI_EOL_CHAR) 215 | { 216 | intf->cmd_buffer[intf->cmd_buffer_ndx++] = '\0'; 217 | 218 | cli_execute_command(intf, (char*)intf->cmd_buffer); 219 | 220 | intf->cmd_buffer_ndx = 0; 221 | cli_prompt(intf); 222 | } 223 | } 224 | } 225 | 226 | void 227 | cli_intf_register(cli_intf_t* intf) 228 | { 229 | INIT_LIST_HEAD(&intf->le); 230 | intf->cmd_buffer_ndx = 0; 231 | 232 | list_add_tail(&intf->le, &_cli_intf_list); 233 | } 234 | 235 | void 236 | cli_intf_unregister(cli_intf_t* intf) 237 | { 238 | list_del_init(&intf->le); 239 | } 240 | -------------------------------------------------------------------------------- /components/utils/cli_telnet.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "telnet.h" 8 | 9 | #include "common_def.h" 10 | #include "cli.h" 11 | #include "tcp_server.h" 12 | #include "tcp_server_ipv4.h" 13 | #include "stream.h" 14 | #include "sock_util.h" 15 | #include "telnet_reader.h" 16 | #include "io_driver.h" 17 | 18 | static const char* TAG = "cli_telnet"; 19 | 20 | //////////////////////////////////////////////////////////////////////////////// 21 | // 22 | // private definitions 23 | // 24 | //////////////////////////////////////////////////////////////////////////////// 25 | typedef struct 26 | { 27 | struct list_head le; // a list of connections in cli_server 28 | stream_t stream; // connected stream 29 | cli_intf_t cli_intf; // cli interface 30 | telnet_reader_t telnet; 31 | uint8_t rx_buf[128]; 32 | } cli_connection_t; 33 | 34 | typedef struct 35 | { 36 | tcp_server_t tcp_server; 37 | struct list_head conns; 38 | } cli_server_t; 39 | 40 | static void handle_stream_event(stream_t* stream, stream_event_t evt); 41 | static void cli_put_tx_data(cli_intf_t* intf, const char* data, int len); 42 | static void telnet_rx_databack(telnet_reader_t* tr, uint8_t data); 43 | static void telnet_rx_cmdback(telnet_reader_t* tr); 44 | 45 | //////////////////////////////////////////////////////////////////////////////// 46 | // 47 | // private variables 48 | // 49 | //////////////////////////////////////////////////////////////////////////////// 50 | static cli_server_t _cli_ipv4_server; 51 | 52 | //////////////////////////////////////////////////////////////////////////////// 53 | // 54 | // private utilities 55 | // 56 | //////////////////////////////////////////////////////////////////////////////// 57 | static void 58 | init_telnet_session(cli_connection_t* conn) 59 | { 60 | static const char iacs_to_send[] = 61 | { 62 | IAC, WILL, TELOPT_SGA, 63 | IAC, WILL, TELOPT_ECHO, 64 | }; 65 | 66 | stream_write(&conn->stream, (uint8_t*)iacs_to_send, sizeof(iacs_to_send)); 67 | } 68 | 69 | static void 70 | alloc_cli_connection(cli_server_t* server, int newsd) 71 | { 72 | cli_connection_t* conn; 73 | uint8_t dummy = '\r'; 74 | 75 | conn = malloc(sizeof(cli_connection_t)); 76 | if(conn == NULL) 77 | { 78 | ESP_LOGI(TAG, "malloc failed"); 79 | close(newsd); 80 | return; 81 | } 82 | 83 | INIT_LIST_HEAD(&conn->le); 84 | list_add_tail(&conn->le, &server->conns); 85 | 86 | stream_init_with_fd(cli_io_driver(), &conn->stream, newsd, conn->rx_buf, 128, 128); 87 | 88 | sock_util_put_nonblock(newsd); 89 | 90 | // 91 | // setup callbacks 92 | // 93 | conn->stream.cb = handle_stream_event; 94 | 95 | // 96 | // register CLI interface 97 | // 98 | conn->cli_intf.put_tx_data = cli_put_tx_data; 99 | 100 | cli_intf_register(&conn->cli_intf); 101 | 102 | conn->telnet.databack = telnet_rx_databack; 103 | conn->telnet.cmdback = telnet_rx_cmdback; 104 | telnet_reader_init(&conn->telnet); 105 | 106 | init_telnet_session(conn); 107 | 108 | // show prompt 109 | cli_handle_rx(&conn->cli_intf, &dummy, 1); 110 | } 111 | 112 | static void 113 | dealloc_cli_connection(cli_connection_t* conn) 114 | { 115 | stream_deinit(&conn->stream); 116 | 117 | cli_intf_unregister(&conn->cli_intf); 118 | 119 | list_del_init(&conn->le); 120 | 121 | free(conn); 122 | } 123 | 124 | //////////////////////////////////////////////////////////////////////////////// 125 | // 126 | // telnet callbacks 127 | // 128 | //////////////////////////////////////////////////////////////////////////////// 129 | static void 130 | telnet_rx_databack(telnet_reader_t* tr, uint8_t data) 131 | { 132 | cli_connection_t* conn = container_of(tr, cli_connection_t, telnet); 133 | 134 | if(data == 0) 135 | { 136 | return; 137 | } 138 | cli_handle_rx(&conn->cli_intf, &data, 1); 139 | } 140 | 141 | static void 142 | telnet_rx_cmdback(telnet_reader_t* tr) 143 | { 144 | // ignore 145 | } 146 | 147 | //////////////////////////////////////////////////////////////////////////////// 148 | // 149 | // cli interfaces 150 | // 151 | //////////////////////////////////////////////////////////////////////////////// 152 | static void 153 | cli_put_tx_data(cli_intf_t* intf, const char* data, int len) 154 | { 155 | cli_connection_t* conn = container_of(intf, cli_connection_t, cli_intf); 156 | 157 | stream_write(&conn->stream, (uint8_t*)data, len); 158 | } 159 | 160 | //////////////////////////////////////////////////////////////////////////////// 161 | // 162 | // stream callback 163 | // 164 | //////////////////////////////////////////////////////////////////////////////// 165 | static void 166 | handle_stream_event(stream_t* stream, stream_event_t evt) 167 | { 168 | cli_connection_t* conn = container_of(stream, cli_connection_t, stream); 169 | 170 | //log_write("handle_stream_event %d\n", evt); 171 | switch(evt) 172 | { 173 | case stream_event_rx: 174 | telnet_reader_feed(&conn->telnet, stream->rx_buf, stream->rx_data_len); 175 | break; 176 | 177 | case stream_event_eof: 178 | ESP_LOGI(TAG, "connection eof detected"); 179 | dealloc_cli_connection(conn); 180 | break; 181 | 182 | case stream_event_err: 183 | ESP_LOGI(TAG, "connection error detected"); 184 | dealloc_cli_connection(conn); 185 | break; 186 | 187 | case stream_event_tx: 188 | // never occurs 189 | break; 190 | } 191 | } 192 | 193 | //////////////////////////////////////////////////////////////////////////////// 194 | // 195 | // tcp server callback 196 | // 197 | //////////////////////////////////////////////////////////////////////////////// 198 | static void 199 | cli_server_new_connection(tcp_server_t* server, int newsd, struct sockaddr* from) 200 | { 201 | cli_server_t* cli_server = container_of(server, cli_server_t, tcp_server); 202 | ESP_LOGI(TAG, "new cli connection"); 203 | alloc_cli_connection(cli_server, newsd); 204 | } 205 | 206 | //////////////////////////////////////////////////////////////////////////////// 207 | // 208 | // private utilities 209 | // 210 | //////////////////////////////////////////////////////////////////////////////// 211 | static 212 | void cli_telnet_server_init(cli_server_t* server, int port, int backlog) 213 | { 214 | INIT_LIST_HEAD(&server->conns); 215 | 216 | server->tcp_server.conn_cb = cli_server_new_connection; 217 | tcp_server_ipv4_init(cli_io_driver(), &server->tcp_server, port, backlog); 218 | tcp_server_start(&server->tcp_server); 219 | } 220 | 221 | //////////////////////////////////////////////////////////////////////////////// 222 | // 223 | // public interfaces 224 | // 225 | //////////////////////////////////////////////////////////////////////////////// 226 | void 227 | cli_telnet_intf_init(int port) 228 | { 229 | ESP_LOGI(TAG, "initializing cli telnet interface for port %d", port); 230 | 231 | cli_telnet_server_init(&_cli_ipv4_server, port, 5); 232 | } 233 | 234 | void 235 | cli_telnet_show_connections(cli_intf_t* intf) 236 | { 237 | cli_connection_t* con; 238 | struct sockaddr_in from; 239 | socklen_t from_len; 240 | char strbuf[128]; 241 | 242 | 243 | list_for_each_entry(con, &_cli_ipv4_server.conns, le) 244 | { 245 | memset(&from, 0, sizeof(from)); 246 | from_len = sizeof(from); 247 | 248 | getpeername(con->stream.watcher.fd, (struct sockaddr*)&from, &from_len); 249 | 250 | inet_ntoa_r(from.sin_addr, strbuf, 128); 251 | 252 | cli_printf(intf, "%s:%d"CLI_EOL, strbuf, ntohs(from.sin_port)); 253 | } 254 | } 255 | -------------------------------------------------------------------------------- /components/utils/component.mk: -------------------------------------------------------------------------------- 1 | # 2 | # "main" pseudo-component makefile. 3 | # 4 | # (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) 5 | -------------------------------------------------------------------------------- /components/utils/include/circ_buffer.h: -------------------------------------------------------------------------------- 1 | #ifndef __CIRC_BUFFER_DEF_H__ 2 | #define __CIRC_BUFFER_DEF_H__ 3 | 4 | #include "common_def.h" 5 | 6 | /** 7 | * circular buffer structure 8 | */ 9 | typedef struct 10 | { 11 | uint8_t* buffer; /** buffer pointer to store data */ 12 | int size; /** size of buffer */ 13 | int data_size; /** size of data in buffer */ 14 | int begin; /** buffer begin index */ 15 | int end; /** buffer end index */ 16 | } circ_buffer_t; 17 | 18 | extern int circ_buffer_init(circ_buffer_t* cb, int size); 19 | extern void circ_buffer_deinit(circ_buffer_t* cb); 20 | extern int circ_buffer_put(circ_buffer_t* cb, uint8_t* buf, int size); 21 | extern int circ_buffer_get(circ_buffer_t* cb, uint8_t* buf, int size); 22 | extern int circ_buffer_peek(circ_buffer_t* cb, uint8_t* buf, int size); 23 | extern int circ_buffer_advance(circ_buffer_t* cb, int size); 24 | 25 | /* 26 | * reset circular buffer 27 | * 28 | * @param cb circular buffer 29 | */ 30 | static inline void 31 | circ_buffer_reset(circ_buffer_t* cb) 32 | { 33 | cb->begin = 0; 34 | cb->end = 0; 35 | cb->data_size = 0; 36 | } 37 | 38 | /* 39 | * get data size in circular buffer 40 | * 41 | * @param cb circular buffer 42 | * @return data size 43 | */ 44 | static inline int 45 | circ_buffer_get_data_size(circ_buffer_t* cb) 46 | { 47 | return cb->data_size; 48 | } 49 | 50 | /* 51 | * get buffer size of circular buffer 52 | * 53 | * @param cb circular buffer 54 | * @return buffer size 55 | */ 56 | static inline int 57 | circ_buffer_get_size(circ_buffer_t* cb) 58 | { 59 | return cb->size; 60 | } 61 | 62 | /* 63 | * check if circular buffer is full 64 | * 65 | * @param cb circular buffer 66 | * @return TRUE when full, FALSE otherwise 67 | */ 68 | static inline bool 69 | circ_buffer_is_full(circ_buffer_t* cb) 70 | { 71 | if(cb->data_size == cb->size) 72 | { 73 | return TRUE; 74 | } 75 | return FALSE; 76 | } 77 | 78 | /* 79 | * check if circular buffer is empty 80 | * 81 | * @param cb circular buffer 82 | * @return TRUE when empty, FALSE otherwise 83 | */ 84 | static inline bool 85 | circ_buffer_is_empty(circ_buffer_t* cb) 86 | { 87 | if(cb->data_size == 0) 88 | { 89 | return TRUE; 90 | } 91 | return FALSE; 92 | } 93 | 94 | #endif //!__CIRC_BUFFER_DEF_H__ 95 | -------------------------------------------------------------------------------- /components/utils/include/cli.h: -------------------------------------------------------------------------------- 1 | #ifndef __CLI_DEF_H__ 2 | #define __CLI_DEF_H__ 3 | 4 | #include "common_def.h" 5 | #include "generic_list.h" 6 | #include "io_driver.h" 7 | 8 | #define CLI_COMMAND_MAX_ARGS 32 9 | #define CLI_RX_BUFFER_LENGTH 252 10 | #define CLI_MAX_COMMAND_LEN 252 11 | 12 | #define CLI_EOL "\r\n" 13 | 14 | typedef struct __cli_intf cli_intf_t; 15 | 16 | struct __cli_intf 17 | { 18 | uint8_t cmd_buffer_ndx; 19 | char cmd_buffer[CLI_MAX_COMMAND_LEN]; 20 | 21 | void (*put_tx_data)(cli_intf_t* intf, const char* data, int len); 22 | void (*print_status)(cli_intf_t* intf); 23 | 24 | struct list_head le; 25 | }; 26 | 27 | typedef void (*cli_command_handler)(cli_intf_t* intf, int argc, const char** argv); 28 | typedef struct 29 | { 30 | const char* command; 31 | const char* help_str; 32 | cli_command_handler handler; 33 | } cli_command_t; 34 | 35 | extern void cli_init(cli_command_t* cmds, int num_cmds, int port); 36 | extern void cli_handle_rx(cli_intf_t* intf, uint8_t* data, int len); 37 | extern void cli_intf_register(cli_intf_t* intf); 38 | extern void cli_intf_unregister(cli_intf_t* intf); 39 | 40 | extern void cli_printf(cli_intf_t* intf, const char* fmt, ...); 41 | 42 | extern io_driver_t* cli_io_driver(void); 43 | 44 | #endif /* !__CLI_DEF_H__ */ 45 | -------------------------------------------------------------------------------- /components/utils/include/common_def.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_DEF_H__ 2 | #define __COMMON_DEF_H__ 3 | 4 | #include 5 | #include 6 | #include "esp_log.h" 7 | 8 | // typedef uint8_t bool; 9 | 10 | #define TRUE 1 11 | #define FALSE 0 12 | 13 | #define CRASH() \ 14 | { \ 15 | char* __bullshit = NULL; \ 16 | *__bullshit = 0; \ 17 | } 18 | 19 | #define NARRAY(a) (sizeof(a)/sizeof(a[0])) 20 | #define UNUSED(a) (void)(a) 21 | 22 | #define HI_BYTE(w) ((uint8_t)((w >> 8) & 0xff)) 23 | #define LO_BYTE(w) ((uint8_t)(w & 0xff)) 24 | 25 | #define BUFFER_TO_U16(b) ((uint16_t)b[0] << 8 | (uint16_t)b[1]) 26 | 27 | #define U16_TO_BUFFER(w, b) \ 28 | b[0] = HI_BYTE(w); \ 29 | b[1] = LO_BYTE(w); 30 | 31 | #define MIN(a,b) (a < b ? a : b) 32 | #define MAX(a,b) (a > b ? a : b) 33 | 34 | 35 | #endif /* !__COMMON_DEF_H__ */ 36 | -------------------------------------------------------------------------------- /components/utils/include/io_driver.h: -------------------------------------------------------------------------------- 1 | // 2 | // 3 | // a very simple select based IO driver for memory/resource tight embedded systems 4 | // -hkim- 5 | // 6 | // 7 | #ifndef __IO_DRIVER_DEF_H__ 8 | #define __IO_DRIVER_DEF_H__ 9 | 10 | #include 11 | #include "common_def.h" 12 | #include "generic_list.h" 13 | 14 | typedef enum 15 | { 16 | IO_DRIVER_EVENT_RX = 0x01, // rx 17 | IO_DRIVER_EVENT_TX = 0x02, // tx 18 | IO_DRIVER_EVENT_EX = 0x04, // error 19 | } io_driver_event; 20 | 21 | struct __io_driver_watcher; 22 | typedef struct __io_driver_watcher io_driver_watcher_t; 23 | 24 | typedef void (*io_driver_callback)(io_driver_watcher_t* watcher, io_driver_event event); 25 | 26 | struct __io_driver_watcher 27 | { 28 | int fd; 29 | uint8_t event_listening; 30 | io_driver_callback callback; 31 | struct list_head le; 32 | }; 33 | 34 | 35 | typedef struct 36 | { 37 | struct list_head watchers; 38 | } io_driver_t; 39 | 40 | extern void io_driver_init(io_driver_t* driver); 41 | extern void io_driver_run(io_driver_t* driver); 42 | extern void io_driver_watcher_init(io_driver_watcher_t* watcher); 43 | extern void io_driver_watch(io_driver_t* driver, io_driver_watcher_t* watcher, io_driver_event event); 44 | extern void io_driver_no_watch(io_driver_t* driver, io_driver_watcher_t* watcher, io_driver_event event); 45 | 46 | #endif /* !__IO_DRIVER_DEF_H__ */ 47 | -------------------------------------------------------------------------------- /components/utils/include/io_driver_notifier.h: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // with non POSIX based RTOS, it's quite hard to multiplex sockets and other 4 | // freertos events, 5 | // which causes hell lot of uglyness in integrating select based event loop. 6 | // 7 | // In this kind of situations, I've been using two approaches. 8 | // 9 | // One is to motify LwIP stack so that with minimal resource and performance usage, 10 | // we can notify select based event loop 11 | // using a special IOCTL. 12 | // 13 | // The other is using a tcp socket as a pipe. 14 | // 15 | // This implementation is about the latter since I don't wanna rely on modifying 16 | // LwIP stack maintained by ESP32 community. 17 | // 18 | // -hkim- 19 | // 20 | //////////////////////////////////////////////////////////////////////////////// 21 | 22 | #ifndef __IO_DRIVER_NOTIFIER_DEF_H__ 23 | #define __IO_DRIVER_NOTIFIER_DEF_H__ 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include "common_def.h" 31 | #include "io_driver.h" 32 | 33 | struct __io_driver_notifier_t; 34 | typedef struct __io_driver_notifier_t io_driver_notifier_t; 35 | 36 | typedef void (*io_driver_notifier_callback)(io_driver_notifier_t* notifier, uint8_t cmd); 37 | 38 | struct __io_driver_notifier_t 39 | { 40 | io_driver_watcher_t watcher; 41 | io_driver_t* driver; 42 | int pipe[2]; // 0 is for reading, 1 is for writing 43 | io_driver_notifier_callback cb; 44 | }; 45 | 46 | extern void io_driver_notifier_init(io_driver_t* driver, io_driver_notifier_t* notifier); 47 | extern void io_driver_notifier_deinit(io_driver_notifier_t* notifier); 48 | extern void io_driver_notifier_notify(io_driver_notifier_t* notifier, uint8_t cmd); 49 | 50 | #endif /* !__IO_DRIVER_NOTIFIER_DEF_H__ */ 51 | -------------------------------------------------------------------------------- /components/utils/include/sock_util.h: -------------------------------------------------------------------------------- 1 | #ifndef __SOCK_UTIL_DEF_H__ 2 | #define __SOCK_UTIL_DEF_H__ 3 | 4 | extern void sock_util_put_nonblock(int sd); 5 | extern void sock_set_keepalive(int sd, int cnt, int idle, int interval); 6 | 7 | #endif /* !__SOCK_UTIL_DEF_H__ */ 8 | -------------------------------------------------------------------------------- /components/utils/include/soft_timer.h: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // soft timer for deterministic single threaded timer management 4 | // 5 | //////////////////////////////////////////////////////////////////////////////// 6 | #ifndef __SOFT_TIMER_DEF_H__ 7 | #define __SOFT_TIMER_DEF_H__ 8 | 9 | #include "generic_list.h" 10 | 11 | #define SOFT_TIMER_NUM_BUCKETS 8 12 | 13 | typedef struct _soft_timer_elem SoftTimerElem; 14 | 15 | /** 16 | * timer callback function 17 | */ 18 | typedef void (*timer_cb)(SoftTimerElem*); 19 | 20 | /** 21 | * timer element representing one timer 22 | */ 23 | struct _soft_timer_elem 24 | { 25 | struct list_head next; /** a list head for next timer element in the bucket */ 26 | timer_cb cb; /** timeout callback */ 27 | unsigned int tick; /** absolute timeout tick count */ 28 | void* priv; /** private argument for timeout callback */ 29 | }; 30 | 31 | /** 32 | * a context block for timer manager 33 | */ 34 | typedef struct _timer 35 | { 36 | int tick_rate; /** tick rate 1 means a tick per 1ms */ 37 | unsigned int tick; /** current tick */ 38 | struct list_head buckets[SOFT_TIMER_NUM_BUCKETS]; /** bucket array */ 39 | } SoftTimer; 40 | 41 | extern int soft_timer_init(SoftTimer* timer, int tick_rate); 42 | extern void soft_timer_deinit(SoftTimer* timer); 43 | extern void soft_timer_init_elem(SoftTimerElem* elem); 44 | extern void soft_timer_add(SoftTimer* timer, SoftTimerElem* elem, int expires); 45 | extern void soft_timer_del(SoftTimer* timer, SoftTimerElem* elem); 46 | extern void soft_timer_drive(SoftTimer* timer); 47 | 48 | /** 49 | * check if a given timer element is currently running 50 | * 51 | * @param elem timer element to check with 52 | * @return 0 if timer elemnt is not running, 1 if running 53 | */ 54 | static inline int 55 | is_soft_timer_running(SoftTimerElem* elem) 56 | { 57 | if(elem->next.next == &elem->next && elem->next.prev == &elem->next) 58 | { 59 | return 0; 60 | } 61 | return 1; 62 | } 63 | 64 | /** 65 | * calculate timer tick count from given milli second 66 | * 67 | * @param timer timer manager context block 68 | * @param milsec desired millisecond 69 | * @return the closes tick count for a given tick rate 70 | */ 71 | static inline unsigned int 72 | get_soft_tick_from_milsec(SoftTimer* timer, int milsec) 73 | { 74 | unsigned int tick, 75 | mod; 76 | 77 | tick = milsec / timer->tick_rate; 78 | mod = milsec % timer->tick_rate; 79 | 80 | if(mod != 0) 81 | { 82 | tick += 1; 83 | } 84 | return tick; 85 | } 86 | 87 | #endif //!__SOFT_TIMER_DEF_H__ 88 | -------------------------------------------------------------------------------- /components/utils/include/stream.h: -------------------------------------------------------------------------------- 1 | #ifndef __STREAM_DEF_H__ 2 | #define __STREAM_DEF_H__ 3 | 4 | #include "common_def.h" 5 | #include "circ_buffer.h" 6 | #include "io_driver.h" 7 | 8 | struct __stream; 9 | typedef struct __stream stream_t; 10 | 11 | typedef enum 12 | { 13 | stream_event_rx, // just received data 14 | stream_event_eof, // eof detect 15 | stream_event_err, // error catched 16 | stream_event_tx, // tx buffer available 17 | } stream_event_t; 18 | 19 | typedef void (*stream_callback)(stream_t* stream, stream_event_t evt); 20 | 21 | struct __stream 22 | { 23 | io_driver_watcher_t watcher; 24 | io_driver_t* driver; 25 | uint8_t* rx_buf; 26 | int rx_buf_size; 27 | int rx_data_len; 28 | stream_callback cb; 29 | circ_buffer_t tx_buf; 30 | }; 31 | 32 | extern void stream_init_with_fd(io_driver_t* driver, stream_t* stream, int fd, uint8_t* rx_buf, int rx_buf_size, int tx_buf_size); 33 | extern void stream_deinit(stream_t* stream); 34 | extern bool stream_write(stream_t* stream, uint8_t* data, int len); 35 | 36 | #endif /* !__STREAM_DEF_H__ */ 37 | -------------------------------------------------------------------------------- /components/utils/include/tcp_server.h: -------------------------------------------------------------------------------- 1 | #ifndef __TCP_SERVER_DEF_H__ 2 | #define __TCP_SERVER_DEF_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "common_def.h" 10 | #include "io_driver.h" 11 | 12 | #define MAX_ADDRESS_STRING_LEN 256 13 | 14 | typedef enum 15 | { 16 | tcp_server_type_ipv4, 17 | } tcp_server_type_t; 18 | 19 | struct __tcp_server; 20 | typedef struct __tcp_server tcp_server_t; 21 | 22 | typedef void (*tcp_server_rx_event)(tcp_server_t* server); 23 | typedef void (*tcp_server_bound_addr)(tcp_server_t* server, char string[MAX_ADDRESS_STRING_LEN]); 24 | typedef void (*tcp_new_connection_cb)(tcp_server_t* server, int newsd, struct sockaddr* from); 25 | 26 | struct __tcp_server 27 | { 28 | int sd; 29 | bool is_listening; 30 | 31 | // 32 | // protocol specific callback 33 | // 34 | tcp_server_rx_event rx_event; 35 | tcp_server_bound_addr get_bound_addr; 36 | 37 | // 38 | // user callback 39 | // 40 | tcp_new_connection_cb conn_cb; 41 | 42 | union 43 | { 44 | struct sockaddr_in ipv4_addr; 45 | }; 46 | 47 | tcp_server_type_t server_type; 48 | 49 | io_driver_watcher_t watcher; 50 | io_driver_t* driver; 51 | }; 52 | 53 | extern void tcp_server_init(io_driver_t* driver, tcp_server_t* server, int sd, tcp_server_rx_event cb); 54 | extern void tcp_server_deinit(tcp_server_t* server); 55 | extern void tcp_server_start(tcp_server_t* server); 56 | extern void tcp_server_stop(tcp_server_t* server); 57 | extern void tcp_server_get_port_name(tcp_server_t* server, char name[MAX_ADDRESS_STRING_LEN]); 58 | 59 | #endif /* !__TCP_SERVER_DEF_H__ */ 60 | -------------------------------------------------------------------------------- /components/utils/include/tcp_server_ipv4.h: -------------------------------------------------------------------------------- 1 | #ifndef __TCP_SERVER_IPV4_DEF_H__ 2 | #define __TCP_SERVER_IPV4_DEF_H__ 3 | 4 | #include "common_def.h" 5 | #include "tcp_server.h" 6 | #include "io_driver.h" 7 | 8 | extern int tcp_server_ipv4_init(io_driver_t* driver, tcp_server_t* server, int port, int backlog); 9 | extern int tcp_server_ipv4_init_with_addr(io_driver_t* driver, tcp_server_t* server, struct sockaddr_in* addr, int backlog); 10 | extern int tcp_server_ipv4_get_local_port(tcp_server_t* server); 11 | 12 | #endif /* !__TCP_SERVER_IPV4_DEF_H__ */ 13 | -------------------------------------------------------------------------------- /components/utils/include/telnet_reader.h: -------------------------------------------------------------------------------- 1 | #ifndef __TELNET_READER_DEF_H__ 2 | #define __TELNET_READER_DEF_H__ 3 | 4 | #include "common_def.h" 5 | 6 | #define TELNET_READER_BUFFER_SIZE 32 7 | 8 | struct __telnet_reader; 9 | typedef struct __telnet_reader telnet_reader_t; 10 | 11 | typedef enum 12 | { 13 | telnet_reader_state_start, 14 | telnet_reader_state_rx_iac, 15 | telnet_reader_state_rx_do_dont_will_wont, 16 | telnet_reader_state_rx_sb, 17 | telnet_reader_state_wait_for_se, 18 | } telnet_reader_state_t; 19 | 20 | typedef void (*telnet_data_callback)(telnet_reader_t* tr, uint8_t data); 21 | typedef void (*telnet_cmd_callback)(telnet_reader_t* tr); 22 | 23 | struct __telnet_reader 24 | { 25 | uint8_t buffer[TELNET_READER_BUFFER_SIZE]; 26 | uint8_t buf_ndx; 27 | 28 | telnet_reader_state_t state; 29 | uint8_t command; 30 | uint8_t opt; 31 | 32 | telnet_data_callback databack; 33 | telnet_cmd_callback cmdback; 34 | }; 35 | 36 | extern void telnet_reader_init(telnet_reader_t* tr); 37 | extern void telnet_reader_feed(telnet_reader_t* tr, uint8_t* data, int len); 38 | 39 | #endif /* !__TELNET_READER_DEF_H__ */ 40 | -------------------------------------------------------------------------------- /components/utils/io_driver.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "io_driver.h" 4 | 5 | #include "lwip/err.h" 6 | #include "lwip/sockets.h" 7 | #include "lwip/sys.h" 8 | #include "lwip/netdb.h" 9 | 10 | #include "esp_log.h" 11 | 12 | static const char* TAG = "io_driver"; 13 | 14 | typedef struct 15 | { 16 | fd_set rset; 17 | fd_set wset; 18 | fd_set eset; 19 | bool rset_empty; 20 | bool wset_empty; 21 | bool eset_empty; 22 | int maxfd; 23 | } select_call_arg_t; 24 | 25 | /////////////////////////////////////////////////////////////////////////////// 26 | // 27 | // private utilities 28 | // 29 | /////////////////////////////////////////////////////////////////////////////// 30 | static void 31 | io_driver_preselect(io_driver_t* driver, select_call_arg_t* s) 32 | { 33 | io_driver_watcher_t* watcher; 34 | 35 | FD_ZERO(&s->rset); 36 | FD_ZERO(&s->wset); 37 | FD_ZERO(&s->eset); 38 | 39 | s->rset_empty = TRUE; 40 | s->wset_empty = TRUE; 41 | s->eset_empty = TRUE; 42 | 43 | s->maxfd = 0; 44 | 45 | list_for_each_entry(watcher, &driver->watchers, le) 46 | { 47 | if(watcher->event_listening & IO_DRIVER_EVENT_RX) 48 | { 49 | FD_SET(watcher->fd, &s->rset); 50 | s->maxfd = MAX(watcher->fd, s->maxfd); 51 | s->rset_empty = FALSE; 52 | } 53 | 54 | if(watcher->event_listening & IO_DRIVER_EVENT_TX) 55 | { 56 | FD_SET(watcher->fd, &s->wset); 57 | s->maxfd = MAX(watcher->fd, s->maxfd); 58 | s->wset_empty = FALSE; 59 | } 60 | 61 | if(watcher->event_listening & IO_DRIVER_EVENT_EX) 62 | { 63 | FD_SET(watcher->fd, &s->eset); 64 | s->maxfd = MAX(watcher->fd, s->maxfd); 65 | s->eset_empty = FALSE; 66 | } 67 | } 68 | } 69 | 70 | static void 71 | io_driver_postselect(io_driver_t* driver, select_call_arg_t* s) 72 | { 73 | // 74 | // I know what you think. But even on single threaded env, manipulating elements on temporary run_list 75 | // is the only way to ensure list structure consistency. 76 | // 77 | // by employing temporary run_list, we can solve the following requirements. 78 | // 1) callbacks should be able to add new watcher (by calling XXX_watch) 79 | // ==> new watcher is added to driver->watchers immediately and scheduled at next loop. 80 | // 81 | // 2) callbacks should be able to delete itself (by calling XXX_no_watch) 82 | // ==> the watcher is deleted from driver->watchers . 83 | // 84 | // 3) callbakcs should be able to delete other watchers (by calling XXX_no_watch) 85 | // ==> other watchers are deleted from run_list and never gets scheduled. 86 | // 87 | // I understand this is confusing even to me LoL. Good Luck to us! 88 | // 89 | // the only remaining issue here is calling sequence. 90 | // Currently, the sequence is RX-> TX -> EX 91 | // I believe it should be ususally OK except some exceptionally rare cases 92 | // -hkim- 93 | // 94 | io_driver_watcher_t* watcher; 95 | struct list_head run_list; 96 | 97 | INIT_LIST_HEAD(&run_list); 98 | 99 | list_splice_init(&driver->watchers, &run_list); 100 | 101 | while(!list_empty(&run_list)) 102 | { 103 | watcher = list_first_entry(&run_list, io_driver_watcher_t, le); 104 | 105 | list_del_init(&watcher->le); 106 | list_add_tail(&watcher->le, &driver->watchers); 107 | 108 | if((watcher->event_listening & IO_DRIVER_EVENT_RX) && FD_ISSET(watcher->fd, &s->rset)) 109 | { 110 | watcher->callback(watcher, IO_DRIVER_EVENT_RX); 111 | } 112 | 113 | if((watcher->event_listening & IO_DRIVER_EVENT_TX) && FD_ISSET(watcher->fd, &s->wset)) 114 | { 115 | watcher->callback(watcher, IO_DRIVER_EVENT_TX); 116 | } 117 | 118 | if((watcher->event_listening & IO_DRIVER_EVENT_EX) && FD_ISSET(watcher->fd, &s->eset)) 119 | { 120 | watcher->callback(watcher, IO_DRIVER_EVENT_EX); 121 | } 122 | } 123 | } 124 | 125 | /////////////////////////////////////////////////////////////////////////////// 126 | // 127 | // public interfaces 128 | // 129 | /////////////////////////////////////////////////////////////////////////////// 130 | void 131 | io_driver_init(io_driver_t* driver) 132 | { 133 | INIT_LIST_HEAD(&driver->watchers); 134 | } 135 | 136 | void 137 | io_driver_run(io_driver_t* driver) 138 | { 139 | select_call_arg_t s; 140 | struct timeval tv = 141 | { 142 | .tv_sec = 1, 143 | .tv_usec = 0, 144 | }; 145 | int ret; 146 | 147 | io_driver_preselect(driver, &s); 148 | 149 | ret = lwip_select(s.maxfd + 1, 150 | s.rset_empty ? NULL : &s.rset, 151 | s.wset_empty ? NULL : &s.wset, 152 | s.eset_empty ? NULL : &s.eset, 153 | &tv); 154 | 155 | if(ret < 0) 156 | { 157 | ESP_LOGE(TAG, "select returned error: %d", ret); 158 | return; 159 | } 160 | 161 | if(ret == 0) 162 | { 163 | return; 164 | } 165 | 166 | io_driver_postselect(driver, &s); 167 | } 168 | 169 | void 170 | io_driver_watcher_init(io_driver_watcher_t* watcher) 171 | { 172 | INIT_LIST_HEAD(&watcher->le); 173 | 174 | watcher->fd = -1; 175 | watcher->event_listening = 0; 176 | } 177 | 178 | void 179 | io_driver_watch(io_driver_t* driver, io_driver_watcher_t* watcher, io_driver_event event) 180 | { 181 | uint8_t old_set = watcher->event_listening; 182 | 183 | watcher->event_listening |= event; 184 | 185 | if(old_set == 0 && watcher->event_listening != 0) 186 | { 187 | list_add_tail(&watcher->le, &driver->watchers); 188 | } 189 | } 190 | 191 | void 192 | io_driver_no_watch(io_driver_t* driver, io_driver_watcher_t* watcher, io_driver_event event) 193 | { 194 | uint8_t old_set = watcher->event_listening; 195 | 196 | watcher->event_listening &= ~event; 197 | 198 | if(old_set != 0 && watcher->event_listening == 0) 199 | { 200 | list_del_init(&watcher->le); 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /components/utils/io_driver_notifier.c: -------------------------------------------------------------------------------- 1 | #include "io_driver_notifier.h" 2 | 3 | static const char* TAG = "io_driver_notifier"; 4 | 5 | /////////////////////////////////////////////////////////////////////////////// 6 | // 7 | // utilities 8 | // 9 | /////////////////////////////////////////////////////////////////////////////// 10 | static int 11 | pipe_tcp_socket(void) 12 | { 13 | return socket(AF_INET, SOCK_STREAM, 0); 14 | } 15 | 16 | static int 17 | create_pipe(int filedes[2]) 18 | { 19 | struct sockaddr_in addr = { 0 }; 20 | struct sockaddr_in adr2; 21 | socklen_t addr_size = sizeof (addr); 22 | socklen_t adr2_size = sizeof (adr2); 23 | int listener; 24 | int sock [2] = { -1, -1 }; 25 | 26 | if ((listener = pipe_tcp_socket()) == -1) 27 | return -1; 28 | 29 | addr.sin_family = AF_INET; 30 | addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); 31 | addr.sin_port = 0; 32 | 33 | if (bind(listener, (struct sockaddr *)&addr, addr_size)) 34 | goto fail; 35 | 36 | if (getsockname(listener, (struct sockaddr *)&addr, &addr_size)) 37 | goto fail; 38 | 39 | if (listen(listener, 1)) 40 | goto fail; 41 | 42 | if ((sock[0] = pipe_tcp_socket()) == -1) 43 | goto fail; 44 | 45 | if (connect(sock[0], (struct sockaddr *)&addr, addr_size)) 46 | goto fail; 47 | 48 | if ((sock [1] = accept (listener, 0, 0)) == -1) 49 | goto fail; 50 | 51 | if (getpeername(sock[0], (struct sockaddr *)&addr, &addr_size)) 52 | goto fail; 53 | 54 | if (getsockname(sock[1], (struct sockaddr *)&adr2, &adr2_size)) 55 | goto fail; 56 | 57 | if (addr_size != adr2_size 58 | || addr.sin_addr.s_addr != adr2.sin_addr.s_addr 59 | || addr.sin_port != adr2.sin_port) 60 | goto fail; 61 | 62 | close(listener); 63 | 64 | filedes[0] = sock[0]; 65 | filedes[1] = sock[1]; 66 | 67 | return 0; 68 | 69 | fail: 70 | ESP_LOGE(TAG, "failed to create pipe"); 71 | close(listener); 72 | 73 | if(sock[0] != -1) close(sock[0]); 74 | if(sock[1] != -1) close(sock[1]); 75 | 76 | return -1; 77 | } 78 | 79 | /////////////////////////////////////////////////////////////////////////////// 80 | // 81 | // watcher callback 82 | // 83 | /////////////////////////////////////////////////////////////////////////////// 84 | static void 85 | __io_driver_notifier__watcher_callback(io_driver_watcher_t* watcher, io_driver_event evt) 86 | { 87 | uint8_t cmd; 88 | 89 | io_driver_notifier_t* notifier = container_of(watcher, io_driver_notifier_t, watcher); 90 | 91 | if(recv(notifier->pipe[0], &cmd, 1, 0) != 1) 92 | { 93 | ESP_LOGE(TAG, "failed to recv. stop watching io event"); 94 | io_driver_no_watch(notifier->driver, ¬ifier->watcher, IO_DRIVER_EVENT_RX); 95 | return; 96 | } 97 | 98 | notifier->cb(notifier, cmd); 99 | } 100 | 101 | /////////////////////////////////////////////////////////////////////////////// 102 | // 103 | // public interfaces 104 | // 105 | /////////////////////////////////////////////////////////////////////////////// 106 | void 107 | io_driver_notifier_init(io_driver_t* driver, io_driver_notifier_t* notifier) 108 | { 109 | notifier->driver = driver; 110 | 111 | create_pipe(notifier->pipe); 112 | notifier->watcher.fd = notifier->pipe[0]; 113 | notifier->watcher.callback = __io_driver_notifier__watcher_callback; 114 | 115 | io_driver_watch(driver, ¬ifier->watcher, IO_DRIVER_EVENT_RX); 116 | } 117 | 118 | void 119 | io_driver_notifier_deinit(io_driver_notifier_t* notifier) 120 | { 121 | io_driver_no_watch(notifier->driver, ¬ifier->watcher, IO_DRIVER_EVENT_RX); 122 | 123 | close(notifier->pipe[0]); 124 | close(notifier->pipe[1]); 125 | } 126 | 127 | void 128 | io_driver_notifier_notify(io_driver_notifier_t* notifier, uint8_t cmd) 129 | { 130 | if(send(notifier->pipe[1], &cmd, 1, 0) != 1) 131 | { 132 | // FIXME error handling 133 | ESP_LOGE(TAG, "failed to send"); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /components/utils/sock_util.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "lwip/err.h" 12 | #include "lwip/sockets.h" 13 | #include "lwip/sys.h" 14 | #include "lwip/netdb.h" 15 | 16 | #include "sock_util.h" 17 | 18 | void 19 | sock_util_put_nonblock(int sd) 20 | { 21 | const int const_int_1 = 1; 22 | 23 | ioctl(sd, FIONBIO, (char*)&const_int_1); 24 | } 25 | 26 | void 27 | sock_set_keepalive(int sd, int cnt, int idle, int interval) 28 | { 29 | const int const_int_1 = 1; 30 | 31 | #ifdef SOL_TCP 32 | if(setsockopt(sd, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1)) < 0) 33 | { 34 | ESP_LOGE("sock_uitil", "failed to enable keep alive"); 35 | return; 36 | } 37 | 38 | setsockopt(sd, SOL_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)); 39 | setsockopt(sd, SOL_TCP, TCP_KEEPIDLE, &idle, sizeof(idle)); 40 | setsockopt(sd, SOL_TCP, TCP_KEEPINTVL, &interval, sizeof(interval)); 41 | #else // mostly OSX 42 | setsockopt(sd, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1)); 43 | 44 | setsockopt(sd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)); 45 | setsockopt(sd, IPPROTO_TCP, TCP_KEEPALIVE, &idle, sizeof(idle)); 46 | setsockopt(sd, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(interval)); 47 | #endif 48 | } 49 | -------------------------------------------------------------------------------- /components/utils/soft_timer.c: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // an old invention of hkim and open nature of the internet 4 | // 5 | //////////////////////////////////////////////////////////////////////////////// 6 | #include 7 | #include 8 | #include "soft_timer.h" 9 | 10 | /** 11 | * initialize a timer manager 12 | * 13 | * @param timer timer manager context block 14 | * @param tick_rate desired tick rate 15 | * @param n_buckets number of buckets desired 16 | * @return 0 on success, -1 on failure 17 | */ 18 | int 19 | soft_timer_init(SoftTimer* timer, int tick_rate) 20 | { 21 | int i; 22 | 23 | timer->tick_rate = tick_rate; 24 | timer->tick = 0; 25 | 26 | for(i = 0; i < SOFT_TIMER_NUM_BUCKETS; i++) 27 | { 28 | INIT_LIST_HEAD(&timer->buckets[i]); 29 | } 30 | return 0; 31 | } 32 | 33 | /** 34 | * deinitialize a timer manager 35 | * 36 | * @param timer timer context block 37 | */ 38 | void 39 | soft_timer_deinit(SoftTimer* timer) 40 | { 41 | } 42 | 43 | /** 44 | * initialize a timer element before using it 45 | * 46 | * @param elem timer element to initialize 47 | */ 48 | void 49 | soft_timer_init_elem(SoftTimerElem* elem) 50 | { 51 | INIT_LIST_HEAD(&elem->next); 52 | } 53 | 54 | /** 55 | * start a stopped timer element by adding it to timer manager 56 | * 57 | * @param timer timer manager context block 58 | * @param elem new timer element to add to timer manager 59 | * @param expires desired timeout value in milliseconds 60 | */ 61 | void 62 | soft_timer_add(SoftTimer* timer, SoftTimerElem* elem, int expires) 63 | { 64 | int target; 65 | 66 | if(is_soft_timer_running(elem)) 67 | { 68 | // XXX add crash code 69 | return; 70 | } 71 | 72 | INIT_LIST_HEAD(&elem->next); 73 | 74 | elem->tick = timer->tick + get_soft_tick_from_milsec(timer, expires); 75 | target = elem->tick % SOFT_TIMER_NUM_BUCKETS; 76 | 77 | list_add_tail(&elem->next, &timer->buckets[target]); 78 | } 79 | 80 | /** 81 | * stop a running timer element by deleting it from timer manager 82 | * 83 | * @param timer tmier manager context block 84 | * @param elem timer elemen to delete 85 | */ 86 | void 87 | soft_timer_del(SoftTimer* timer, SoftTimerElem* elem) 88 | { 89 | if(!is_soft_timer_running(elem)) 90 | { 91 | return; 92 | } 93 | list_del_init(&elem->next); 94 | } 95 | 96 | static void 97 | timer_tick(SoftTimer* timer) 98 | { 99 | int current; 100 | SoftTimerElem *p, *n; 101 | struct list_head timeout_list = LIST_HEAD_INIT(timeout_list); 102 | 103 | timer->tick++; 104 | 105 | current = timer->tick % SOFT_TIMER_NUM_BUCKETS; 106 | 107 | // 108 | // be careful with this code.. 109 | // Here is the logic behind this 110 | // 1. once timer expires, it should be able to re-add the same timer again 111 | // 2. when a timer expires, it should be able to remove 112 | // other timers including ones timed out inside the timeout handler 113 | // 114 | list_for_each_entry_safe(p, n, &timer->buckets[current], next) 115 | { 116 | if(p->tick == timer->tick) 117 | { 118 | list_del(&p->next); 119 | list_add_tail(&p->next, &timeout_list); 120 | } 121 | } 122 | 123 | while(!list_empty(&timeout_list)) 124 | { 125 | p = list_first_entry(&timeout_list, SoftTimerElem, next); 126 | list_del_init(&p->next); 127 | p->cb(p); 128 | } 129 | } 130 | 131 | /** 132 | * drive a given timer manager 133 | * this routine should be called every tick rate as close as possible 134 | * On non-realtime systems, some late timeout is just inevitable 135 | * 136 | * @param timer timer manager context block 137 | */ 138 | void 139 | soft_timer_drive(SoftTimer* timer) 140 | { 141 | timer_tick(timer); 142 | } 143 | -------------------------------------------------------------------------------- /components/utils/stream.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "stream.h" 3 | 4 | #include "lwip/err.h" 5 | #include "lwip/sockets.h" 6 | #include "lwip/sys.h" 7 | #include "lwip/netdb.h" 8 | 9 | static const char* TAG = "stream"; 10 | 11 | static void 12 | stream_handle_tx_event(stream_t* stream) 13 | { 14 | uint8_t buffer[128]; 15 | int data_size, 16 | ret, 17 | len; 18 | 19 | if(circ_buffer_is_empty(&stream->tx_buf)) 20 | { 21 | ESP_LOGI(TAG, "disabling TX event. circ buffer empty now"); 22 | io_driver_no_watch(stream->driver, &stream->watcher, IO_DRIVER_EVENT_TX); 23 | return; 24 | } 25 | 26 | // XXX 27 | // looping would be more efficient but 28 | // on the other hand, this has better time sharing feature 29 | // 30 | data_size = circ_buffer_get_data_size(&stream->tx_buf); 31 | len = data_size < 128 ? data_size : 128; 32 | circ_buffer_peek(&stream->tx_buf, buffer, len); 33 | 34 | ret = write(stream->watcher.fd, buffer, len); 35 | if(ret <= 0) 36 | { 37 | // definitely stream got into a trouble 38 | io_driver_no_watch(stream->driver, &stream->watcher, IO_DRIVER_EVENT_TX); 39 | 40 | ESP_LOGI(TAG, "XXXXXXXX this should not happen"); 41 | CRASH(); 42 | return; 43 | } 44 | 45 | circ_buffer_advance(&stream->tx_buf, ret); 46 | 47 | if(circ_buffer_is_empty(&stream->tx_buf)) 48 | { 49 | io_driver_no_watch(stream->driver, &stream->watcher, IO_DRIVER_EVENT_TX); 50 | } 51 | 52 | return; 53 | } 54 | 55 | static void 56 | stream_watcher_callback(io_driver_watcher_t* watcher, io_driver_event evt) 57 | { 58 | int ret; 59 | stream_t* stream = container_of(watcher, stream_t, watcher); 60 | stream_event_t sevt = 0; 61 | 62 | //log_write("watch event: %d\n", evt); 63 | switch(evt) 64 | { 65 | case IO_DRIVER_EVENT_RX: 66 | ret = read(watcher->fd, stream->rx_buf, stream->rx_buf_size); 67 | if(ret > 0) 68 | { 69 | sevt = stream_event_rx; 70 | stream->rx_data_len = ret; 71 | } 72 | else if(ret == 0) 73 | { 74 | sevt = stream_event_eof; 75 | } 76 | else 77 | { 78 | sevt = stream_event_err; 79 | } 80 | break; 81 | 82 | case IO_DRIVER_EVENT_TX: 83 | stream_handle_tx_event(stream); 84 | return; 85 | 86 | case IO_DRIVER_EVENT_EX: 87 | sevt = stream_event_err; 88 | break; 89 | } 90 | 91 | stream->cb(stream, sevt); 92 | } 93 | 94 | 95 | void 96 | stream_init_with_fd(io_driver_t* driver, stream_t* stream, int fd, uint8_t* rx_buf, int rx_buf_size, int tx_buf_size) 97 | { 98 | // XXX return value check 99 | circ_buffer_init(&stream->tx_buf, tx_buf_size); 100 | 101 | stream->rx_buf = rx_buf; 102 | stream->rx_buf_size = rx_buf_size; 103 | 104 | io_driver_watcher_init(&stream->watcher); 105 | 106 | stream->driver = driver; 107 | stream->watcher.fd = fd; 108 | stream->watcher.callback = stream_watcher_callback; 109 | 110 | io_driver_watch(stream->driver, &stream->watcher, IO_DRIVER_EVENT_RX); 111 | io_driver_watch(stream->driver, &stream->watcher, IO_DRIVER_EVENT_EX); 112 | } 113 | 114 | void 115 | stream_deinit(stream_t* stream) 116 | { 117 | circ_buffer_deinit(&stream->tx_buf); 118 | 119 | io_driver_no_watch(stream->driver, &stream->watcher, IO_DRIVER_EVENT_RX); 120 | io_driver_no_watch(stream->driver, &stream->watcher, IO_DRIVER_EVENT_TX); 121 | io_driver_no_watch(stream->driver, &stream->watcher, IO_DRIVER_EVENT_EX); 122 | 123 | close(stream->watcher.fd); 124 | } 125 | 126 | bool 127 | stream_write(stream_t* stream, uint8_t* data, int len) 128 | { 129 | int ret; 130 | 131 | if(circ_buffer_is_empty(&stream->tx_buf) == FALSE) 132 | { 133 | // something got queued up due to socket buffer full 134 | // tx watcher is alreadt started in this case 135 | return circ_buffer_put(&stream->tx_buf, data, len) == 0; 136 | } 137 | else 138 | { 139 | ret = write(stream->watcher.fd, data, len); 140 | if(ret == len) 141 | { 142 | return TRUE; 143 | } 144 | 145 | if(ret < 0) 146 | { 147 | if(!(errno == EWOULDBLOCK || errno == EAGAIN)) 148 | { 149 | ESP_LOGI(TAG, "stream tx error other than EWOULDBLOCK"); 150 | return FALSE; 151 | } 152 | ret = 0; 153 | } 154 | 155 | // start tx watcher and queue remaining data 156 | if(circ_buffer_put(&stream->tx_buf, &data[ret], len - ret) == FALSE) 157 | { 158 | ESP_LOGI(TAG, "can't TX.. circ buffer overflow"); 159 | return FALSE; 160 | } 161 | 162 | ESP_LOGI(TAG, "enabling TX event"); 163 | io_driver_watch(stream->driver, &stream->watcher, IO_DRIVER_EVENT_TX); 164 | return TRUE; 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /components/utils/tcp_server.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "tcp_server.h" 4 | #include "generic_list.h" 5 | 6 | /////////////////////////////////////////////////////////////////////////////// 7 | // 8 | // watcher callback 9 | // 10 | /////////////////////////////////////////////////////////////////////////////// 11 | static void 12 | __tcp_server_watcher_callback(io_driver_watcher_t* watcher, io_driver_event evt) 13 | { 14 | tcp_server_t* server = container_of(watcher, tcp_server_t, watcher); 15 | 16 | server->rx_event(server); 17 | } 18 | 19 | /////////////////////////////////////////////////////////////////////////////// 20 | // 21 | // public interfaces 22 | // 23 | /////////////////////////////////////////////////////////////////////////////// 24 | void 25 | tcp_server_init(io_driver_t* driver, tcp_server_t* server, int sd, tcp_server_rx_event cb) 26 | { 27 | server->sd = sd; 28 | server->is_listening = FALSE; 29 | server->rx_event = cb; 30 | 31 | server->driver = driver; 32 | 33 | server->watcher.fd = sd; 34 | server->watcher.callback = __tcp_server_watcher_callback; 35 | 36 | io_driver_watch(server->driver, &server->watcher, IO_DRIVER_EVENT_RX); 37 | } 38 | 39 | void 40 | tcp_server_deinit(tcp_server_t* server) 41 | { 42 | tcp_server_stop(server); 43 | 44 | if(server->sd != -1) 45 | { 46 | close(server->sd); 47 | server->sd = -1; 48 | } 49 | } 50 | 51 | void 52 | tcp_server_start(tcp_server_t* server) 53 | { 54 | if(server->is_listening) 55 | { 56 | return; 57 | } 58 | 59 | server->is_listening = TRUE; 60 | } 61 | 62 | void 63 | tcp_server_stop(tcp_server_t* server) 64 | { 65 | if(!server->is_listening) 66 | { 67 | return; 68 | } 69 | 70 | server->is_listening = FALSE; 71 | 72 | io_driver_no_watch(server->driver, &server->watcher, IO_DRIVER_EVENT_RX); 73 | io_driver_no_watch(server->driver, &server->watcher, IO_DRIVER_EVENT_TX); 74 | io_driver_no_watch(server->driver, &server->watcher, IO_DRIVER_EVENT_EX); 75 | } 76 | 77 | void 78 | tcp_server_get_port_name(tcp_server_t* server, char name[MAX_ADDRESS_STRING_LEN]) 79 | { 80 | server->get_bound_addr(server, name); 81 | } 82 | -------------------------------------------------------------------------------- /components/utils/tcp_server_ipv4.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "generic_list.h" 10 | #include "tcp_server_ipv4.h" 11 | #include "sock_util.h" 12 | 13 | static const char* TAG = "tcp_ipv4_server"; 14 | 15 | /////////////////////////////////////////////////////////////////////////////// 16 | // 17 | // rx event handler on server socket 18 | // 19 | /////////////////////////////////////////////////////////////////////////////// 20 | static void 21 | tcp_server_ipv4_rx_event(tcp_server_t* self) 22 | { 23 | struct sockaddr_in from; 24 | socklen_t from_len; 25 | int newsd; 26 | 27 | from_len = sizeof(struct sockaddr_in); 28 | memset(&from, 0, from_len); 29 | 30 | newsd = accept(self->sd, (struct sockaddr*)&from, &from_len); 31 | if(newsd < 0) 32 | { 33 | ESP_LOGE(TAG, "accept() failed: %d", errno); 34 | return; 35 | } 36 | 37 | self->conn_cb(self, newsd, (struct sockaddr*)&from); 38 | } 39 | 40 | /////////////////////////////////////////////////////////////////////////////// 41 | // 42 | // bound address info for debugging 43 | // 44 | /////////////////////////////////////////////////////////////////////////////// 45 | static void 46 | tcp_server_ipv4_get_bound_addr(tcp_server_t* self, char string[MAX_ADDRESS_STRING_LEN]) 47 | { 48 | snprintf(string, MAX_ADDRESS_STRING_LEN - 1, "ipv4_tcp:%d", ntohs(self->ipv4_addr.sin_port)); 49 | } 50 | 51 | /////////////////////////////////////////////////////////////////////////////// 52 | // 53 | // utilities 54 | // 55 | /////////////////////////////////////////////////////////////////////////////// 56 | static int 57 | __init_tcp_server_ipv4(io_driver_t* driver, tcp_server_t* server, struct sockaddr_in* addr, int backlog) 58 | { 59 | int sd; 60 | const int on = 1; 61 | 62 | server->server_type = tcp_server_type_ipv4; 63 | memcpy(&server->ipv4_addr, addr, sizeof(struct sockaddr_in)); 64 | 65 | server->sd = -1; 66 | 67 | sd = socket(AF_INET, SOCK_STREAM, 0); 68 | if(sd < 0) 69 | { 70 | ESP_LOGE(TAG, "socket() failed: %d", errno); 71 | return -1; 72 | } 73 | 74 | sock_util_put_nonblock(sd); 75 | 76 | setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); 77 | 78 | if(bind(sd, (struct sockaddr*)&server->ipv4_addr, sizeof(struct sockaddr_in)) != 0) 79 | { 80 | ESP_LOGE(TAG, "bind() failed: %d", errno); 81 | close(sd); 82 | return -1; 83 | } 84 | 85 | if(listen(sd, backlog) != 0) 86 | { 87 | ESP_LOGE(TAG, "listen() failed: %d", errno); 88 | close(sd); 89 | return -1; 90 | } 91 | 92 | tcp_server_init(driver, server, sd, tcp_server_ipv4_rx_event); 93 | server->get_bound_addr = tcp_server_ipv4_get_bound_addr; 94 | 95 | return 0; 96 | } 97 | 98 | /////////////////////////////////////////////////////////////////////////////// 99 | // 100 | // public interfaces 101 | // 102 | /////////////////////////////////////////////////////////////////////////////// 103 | /** 104 | * initialize IPV4 tcp server 105 | * 106 | * @param server server structure to initialize 107 | * @param port port to use 108 | * @return 0 on success, -1 on failure 109 | */ 110 | int 111 | tcp_server_ipv4_init(io_driver_t* driver, tcp_server_t* server, int port, int backlog) 112 | { 113 | struct sockaddr_in my_addr; 114 | 115 | memset(&my_addr, 0, sizeof(struct sockaddr_in)); 116 | 117 | my_addr.sin_family = AF_INET; 118 | my_addr.sin_addr.s_addr = INADDR_ANY; 119 | my_addr.sin_port = htons(port); 120 | 121 | return __init_tcp_server_ipv4(driver, server, &my_addr, backlog); 122 | } 123 | 124 | int 125 | tcp_server_ipv4_init_with_addr(io_driver_t* driver, tcp_server_t* server, struct sockaddr_in* addr, int backlog) 126 | { 127 | return __init_tcp_server_ipv4(driver, server, addr, backlog); 128 | } 129 | 130 | int 131 | tcp_server_ipv4_get_local_port(tcp_server_t* server) 132 | { 133 | struct sockaddr_in sin; 134 | socklen_t len = sizeof(sin); 135 | 136 | if(server->sd < 0) 137 | { 138 | return -1; 139 | } 140 | 141 | getsockname(server->sd, (struct sockaddr*)&sin, &len); 142 | return ntohs(sin.sin_port); 143 | } 144 | -------------------------------------------------------------------------------- /components/utils/telnet_reader.c: -------------------------------------------------------------------------------- 1 | #include "telnet.h" 2 | #include "telnet_reader.h" 3 | 4 | static inline void 5 | telnet_reader_move_state(telnet_reader_t* tr, telnet_reader_state_t s) 6 | { 7 | tr->state = s; 8 | } 9 | 10 | static bool 11 | telnet_reader_handle_command(telnet_reader_t* tr, uint8_t d) 12 | { 13 | tr->command = d; 14 | switch(d) 15 | { 16 | case DO: 17 | case DONT: 18 | case WILL: 19 | case WONT: 20 | telnet_reader_move_state(tr, telnet_reader_state_rx_do_dont_will_wont); 21 | break; 22 | 23 | case SB: 24 | tr->buf_ndx = 0; 25 | telnet_reader_move_state(tr, telnet_reader_state_rx_sb); 26 | break; 27 | 28 | default: 29 | // invalid syntax 30 | return FALSE; 31 | } 32 | return TRUE; 33 | } 34 | 35 | static bool 36 | telnet_reader_handle_subcommand(telnet_reader_t* tr, uint8_t d) 37 | { 38 | switch(d) 39 | { 40 | case IAC: 41 | // could be buggy but who cares 42 | telnet_reader_move_state(tr, telnet_reader_state_wait_for_se); 43 | break; 44 | 45 | default: 46 | if(tr->buf_ndx < TELNET_READER_BUFFER_SIZE) 47 | { 48 | tr->buffer[tr->buf_ndx++] = d; 49 | } 50 | else 51 | { 52 | return FALSE; 53 | } 54 | break; 55 | } 56 | return TRUE; 57 | } 58 | 59 | static void 60 | telnet_reader_state_machine(telnet_reader_t* tr, uint8_t d) 61 | { 62 | switch(tr->state) 63 | { 64 | case telnet_reader_state_start: 65 | if(d == IAC) 66 | { 67 | telnet_reader_move_state(tr, telnet_reader_state_rx_iac); 68 | } 69 | else 70 | { 71 | tr->databack(tr, d); 72 | } 73 | break; 74 | 75 | case telnet_reader_state_rx_iac: 76 | if(d == IAC) 77 | { 78 | telnet_reader_move_state(tr, telnet_reader_state_start); 79 | tr->databack(tr, IAC); 80 | } 81 | else 82 | { 83 | if(telnet_reader_handle_command(tr, d) == FALSE) 84 | { 85 | // discard 86 | telnet_reader_move_state(tr, telnet_reader_state_start); 87 | } 88 | } 89 | break; 90 | 91 | case telnet_reader_state_rx_do_dont_will_wont: 92 | tr->opt = d; 93 | tr->cmdback(tr); 94 | telnet_reader_move_state(tr, telnet_reader_state_start); 95 | break; 96 | 97 | case telnet_reader_state_rx_sb: 98 | if(telnet_reader_handle_subcommand(tr, d) == FALSE) 99 | { 100 | telnet_reader_move_state(tr, telnet_reader_state_start); 101 | return; 102 | } 103 | break; 104 | 105 | case telnet_reader_state_wait_for_se: 106 | if(d == SE) 107 | { 108 | tr->cmdback(tr); 109 | } 110 | telnet_reader_move_state(tr, telnet_reader_state_start); 111 | break; 112 | } 113 | } 114 | 115 | void 116 | telnet_reader_init(telnet_reader_t* tr) 117 | { 118 | tr->state = telnet_reader_state_start; 119 | tr->buf_ndx = 0; 120 | } 121 | 122 | void 123 | telnet_reader_feed(telnet_reader_t* tr, uint8_t* data, int len) 124 | { 125 | int i; 126 | 127 | for(i = 0; i < len; i++) 128 | { 129 | telnet_reader_state_machine(tr, data[i]); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /doc/AK8963C.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/doc/AK8963C.pdf -------------------------------------------------------------------------------- /doc/AN2272_001-32379_0C_V.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/doc/AN2272_001-32379_0C_V.pdf -------------------------------------------------------------------------------- /doc/MPU-9250-Register-Map.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/doc/MPU-9250-Register-Map.pdf -------------------------------------------------------------------------------- /doc/T10_V1.2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/doc/T10_V1.2.pdf -------------------------------------------------------------------------------- /doc/esp32_chip_pin_list_en.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/doc/esp32_chip_pin_list_en.pdf -------------------------------------------------------------------------------- /doc/esp32_technical_reference_manual_en.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/doc/esp32_technical_reference_manual_en.pdf -------------------------------------------------------------------------------- /doc/madgwick_internal_report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/doc/madgwick_internal_report.pdf -------------------------------------------------------------------------------- /doc/mpu9250_spec.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/doc/mpu9250_spec.pdf -------------------------------------------------------------------------------- /imu_tool/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "comments": false, 3 | "env": { 4 | "test": { 5 | "presets": [ 6 | ["env", { 7 | "targets": { "node": 7 } 8 | }], 9 | "stage-0" 10 | ], 11 | "plugins": ["istanbul"] 12 | }, 13 | "main": { 14 | "presets": [ 15 | ["env", { 16 | "targets": { "node": 7 } 17 | }], 18 | "stage-0" 19 | ] 20 | }, 21 | "renderer": { 22 | "presets": [ 23 | ["env", { 24 | "modules": false 25 | }], 26 | "stage-0" 27 | ] 28 | }, 29 | "web": { 30 | "presets": [ 31 | ["env", { 32 | "modules": false 33 | }], 34 | "stage-0" 35 | ] 36 | } 37 | }, 38 | "plugins": ["transform-runtime"] 39 | } 40 | -------------------------------------------------------------------------------- /imu_tool/.electron-vue/build.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | process.env.NODE_ENV = 'production' 4 | 5 | const { say } = require('cfonts') 6 | const chalk = require('chalk') 7 | const del = require('del') 8 | const { spawn } = require('child_process') 9 | const webpack = require('webpack') 10 | const Multispinner = require('multispinner') 11 | 12 | 13 | const mainConfig = require('./webpack.main.config') 14 | const rendererConfig = require('./webpack.renderer.config') 15 | const webConfig = require('./webpack.web.config') 16 | 17 | const doneLog = chalk.bgGreen.white(' DONE ') + ' ' 18 | const errorLog = chalk.bgRed.white(' ERROR ') + ' ' 19 | const okayLog = chalk.bgBlue.white(' OKAY ') + ' ' 20 | const isCI = process.env.CI || false 21 | 22 | if (process.env.BUILD_TARGET === 'clean') clean() 23 | else if (process.env.BUILD_TARGET === 'web') web() 24 | else build() 25 | 26 | function clean () { 27 | del.sync(['build/*', '!build/icons', '!build/icons/icon.*']) 28 | console.log(`\n${doneLog}\n`) 29 | process.exit() 30 | } 31 | 32 | function build () { 33 | greeting() 34 | 35 | del.sync(['dist/electron/*', '!.gitkeep']) 36 | 37 | const tasks = ['main', 'renderer'] 38 | const m = new Multispinner(tasks, { 39 | preText: 'building', 40 | postText: 'process' 41 | }) 42 | 43 | let results = '' 44 | 45 | m.on('success', () => { 46 | process.stdout.write('\x1B[2J\x1B[0f') 47 | console.log(`\n\n${results}`) 48 | console.log(`${okayLog}take it away ${chalk.yellow('`electron-builder`')}\n`) 49 | process.exit() 50 | }) 51 | 52 | pack(mainConfig).then(result => { 53 | results += result + '\n\n' 54 | m.success('main') 55 | }).catch(err => { 56 | m.error('main') 57 | console.log(`\n ${errorLog}failed to build main process`) 58 | console.error(`\n${err}\n`) 59 | process.exit(1) 60 | }) 61 | 62 | pack(rendererConfig).then(result => { 63 | results += result + '\n\n' 64 | m.success('renderer') 65 | }).catch(err => { 66 | m.error('renderer') 67 | console.log(`\n ${errorLog}failed to build renderer process`) 68 | console.error(`\n${err}\n`) 69 | process.exit(1) 70 | }) 71 | } 72 | 73 | function pack (config) { 74 | return new Promise((resolve, reject) => { 75 | webpack(config, (err, stats) => { 76 | if (err) reject(err.stack || err) 77 | else if (stats.hasErrors()) { 78 | let err = '' 79 | 80 | stats.toString({ 81 | chunks: false, 82 | colors: true 83 | }) 84 | .split(/\r?\n/) 85 | .forEach(line => { 86 | err += ` ${line}\n` 87 | }) 88 | 89 | reject(err) 90 | } else { 91 | resolve(stats.toString({ 92 | chunks: false, 93 | colors: true 94 | })) 95 | } 96 | }) 97 | }) 98 | } 99 | 100 | function web () { 101 | del.sync(['dist/web/*', '!.gitkeep']) 102 | webpack(webConfig, (err, stats) => { 103 | if (err || stats.hasErrors()) console.log(err) 104 | 105 | console.log(stats.toString({ 106 | chunks: false, 107 | colors: true 108 | })) 109 | 110 | process.exit() 111 | }) 112 | } 113 | 114 | function greeting () { 115 | const cols = process.stdout.columns 116 | let text = '' 117 | 118 | if (cols > 85) text = 'lets-build' 119 | else if (cols > 60) text = 'lets-|build' 120 | else text = false 121 | 122 | if (text && !isCI) { 123 | say(text, { 124 | colors: ['yellow'], 125 | font: 'simple3d', 126 | space: false 127 | }) 128 | } else console.log(chalk.yellow.bold('\n lets-build')) 129 | console.log() 130 | } 131 | -------------------------------------------------------------------------------- /imu_tool/.electron-vue/dev-client.js: -------------------------------------------------------------------------------- 1 | const hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') 2 | 3 | hotClient.subscribe(event => { 4 | /** 5 | * Reload browser when HTMLWebpackPlugin emits a new index.html 6 | * 7 | * Currently disabled until jantimon/html-webpack-plugin#680 is resolved. 8 | * https://github.com/SimulatedGREG/electron-vue/issues/437 9 | * https://github.com/jantimon/html-webpack-plugin/issues/680 10 | */ 11 | // if (event.action === 'reload') { 12 | // window.location.reload() 13 | // } 14 | 15 | /** 16 | * Notify `mainWindow` when `main` process is compiling, 17 | * giving notice for an expected reload of the `electron` process 18 | */ 19 | if (event.action === 'compiling') { 20 | document.body.innerHTML += ` 21 | 34 | 35 |
36 | Compiling Main Process... 37 |
38 | ` 39 | } 40 | }) 41 | -------------------------------------------------------------------------------- /imu_tool/.electron-vue/dev-runner.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const chalk = require('chalk') 4 | const electron = require('electron') 5 | const path = require('path') 6 | const { say } = require('cfonts') 7 | const { spawn } = require('child_process') 8 | const webpack = require('webpack') 9 | const WebpackDevServer = require('webpack-dev-server') 10 | const webpackHotMiddleware = require('webpack-hot-middleware') 11 | 12 | const mainConfig = require('./webpack.main.config') 13 | const rendererConfig = require('./webpack.renderer.config') 14 | 15 | let electronProcess = null 16 | let manualRestart = false 17 | let hotMiddleware 18 | 19 | function logStats (proc, data) { 20 | let log = '' 21 | 22 | log += chalk.yellow.bold(`┏ ${proc} Process ${new Array((19 - proc.length) + 1).join('-')}`) 23 | log += '\n\n' 24 | 25 | if (typeof data === 'object') { 26 | data.toString({ 27 | colors: true, 28 | chunks: false 29 | }).split(/\r?\n/).forEach(line => { 30 | log += ' ' + line + '\n' 31 | }) 32 | } else { 33 | log += ` ${data}\n` 34 | } 35 | 36 | log += '\n' + chalk.yellow.bold(`┗ ${new Array(28 + 1).join('-')}`) + '\n' 37 | 38 | console.log(log) 39 | } 40 | 41 | function startRenderer () { 42 | return new Promise((resolve, reject) => { 43 | rendererConfig.entry.renderer = [path.join(__dirname, 'dev-client')].concat(rendererConfig.entry.renderer) 44 | 45 | const compiler = webpack(rendererConfig) 46 | hotMiddleware = webpackHotMiddleware(compiler, { 47 | log: false, 48 | heartbeat: 2500 49 | }) 50 | 51 | compiler.plugin('compilation', compilation => { 52 | compilation.plugin('html-webpack-plugin-after-emit', (data, cb) => { 53 | hotMiddleware.publish({ action: 'reload' }) 54 | cb() 55 | }) 56 | }) 57 | 58 | compiler.plugin('done', stats => { 59 | logStats('Renderer', stats) 60 | }) 61 | 62 | const server = new WebpackDevServer( 63 | compiler, 64 | { 65 | contentBase: path.join(__dirname, '../'), 66 | quiet: true, 67 | before (app, ctx) { 68 | app.use(hotMiddleware) 69 | ctx.middleware.waitUntilValid(() => { 70 | resolve() 71 | }) 72 | } 73 | } 74 | ) 75 | 76 | server.listen(9080) 77 | }) 78 | } 79 | 80 | function startMain () { 81 | return new Promise((resolve, reject) => { 82 | mainConfig.entry.main = [path.join(__dirname, '../src/main/index.dev.js')].concat(mainConfig.entry.main) 83 | 84 | const compiler = webpack(mainConfig) 85 | 86 | compiler.plugin('watch-run', (compilation, done) => { 87 | logStats('Main', chalk.white.bold('compiling...')) 88 | hotMiddleware.publish({ action: 'compiling' }) 89 | done() 90 | }) 91 | 92 | compiler.watch({}, (err, stats) => { 93 | if (err) { 94 | console.log(err) 95 | return 96 | } 97 | 98 | logStats('Main', stats) 99 | 100 | if (electronProcess && electronProcess.kill) { 101 | manualRestart = true 102 | process.kill(electronProcess.pid) 103 | electronProcess = null 104 | startElectron() 105 | 106 | setTimeout(() => { 107 | manualRestart = false 108 | }, 5000) 109 | } 110 | 111 | resolve() 112 | }) 113 | }) 114 | } 115 | 116 | function startElectron () { 117 | electronProcess = spawn(electron, ['--inspect=5858', path.join(__dirname, '../dist/electron/main.js')]) 118 | 119 | electronProcess.stdout.on('data', data => { 120 | electronLog(data, 'blue') 121 | }) 122 | electronProcess.stderr.on('data', data => { 123 | electronLog(data, 'red') 124 | }) 125 | 126 | electronProcess.on('close', () => { 127 | if (!manualRestart) process.exit() 128 | }) 129 | } 130 | 131 | function electronLog (data, color) { 132 | let log = '' 133 | data = data.toString().split(/\r?\n/) 134 | data.forEach(line => { 135 | log += ` ${line}\n` 136 | }) 137 | if (/[0-9A-z]+/.test(log)) { 138 | console.log( 139 | chalk[color].bold('┏ Electron -------------------') + 140 | '\n\n' + 141 | log + 142 | chalk[color].bold('┗ ----------------------------') + 143 | '\n' 144 | ) 145 | } 146 | } 147 | 148 | function greeting () { 149 | const cols = process.stdout.columns 150 | let text = '' 151 | 152 | if (cols > 104) text = 'electron-vue' 153 | else if (cols > 76) text = 'electron-|vue' 154 | else text = false 155 | 156 | if (text) { 157 | say(text, { 158 | colors: ['yellow'], 159 | font: 'simple3d', 160 | space: false 161 | }) 162 | } else console.log(chalk.yellow.bold('\n electron-vue')) 163 | console.log(chalk.blue(' getting ready...') + '\n') 164 | } 165 | 166 | function init () { 167 | greeting() 168 | 169 | Promise.all([startRenderer(), startMain()]) 170 | .then(() => { 171 | startElectron() 172 | }) 173 | .catch(err => { 174 | console.error(err) 175 | }) 176 | } 177 | 178 | init() 179 | -------------------------------------------------------------------------------- /imu_tool/.electron-vue/webpack.main.config.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | process.env.BABEL_ENV = 'main' 4 | 5 | const path = require('path') 6 | const { dependencies } = require('../package.json') 7 | const webpack = require('webpack') 8 | 9 | const BabiliWebpackPlugin = require('babili-webpack-plugin') 10 | 11 | let mainConfig = { 12 | entry: { 13 | main: path.join(__dirname, '../src/main/index.js') 14 | }, 15 | externals: [ 16 | ...Object.keys(dependencies || {}) 17 | ], 18 | module: { 19 | rules: [ 20 | { 21 | test: /\.(js)$/, 22 | enforce: 'pre', 23 | exclude: /node_modules/, 24 | use: { 25 | loader: 'eslint-loader', 26 | options: { 27 | formatter: require('eslint-friendly-formatter') 28 | } 29 | } 30 | }, 31 | { 32 | test: /\.js$/, 33 | use: 'babel-loader', 34 | exclude: /node_modules/ 35 | }, 36 | { 37 | test: /\.node$/, 38 | use: 'node-loader' 39 | } 40 | ] 41 | }, 42 | node: { 43 | __dirname: process.env.NODE_ENV !== 'production', 44 | __filename: process.env.NODE_ENV !== 'production' 45 | }, 46 | output: { 47 | filename: '[name].js', 48 | libraryTarget: 'commonjs2', 49 | path: path.join(__dirname, '../dist/electron') 50 | }, 51 | plugins: [ 52 | new webpack.NoEmitOnErrorsPlugin() 53 | ], 54 | resolve: { 55 | extensions: ['.js', '.json', '.node'] 56 | }, 57 | target: 'electron-main' 58 | } 59 | 60 | /** 61 | * Adjust mainConfig for development settings 62 | */ 63 | if (process.env.NODE_ENV !== 'production') { 64 | mainConfig.plugins.push( 65 | new webpack.DefinePlugin({ 66 | '__static': `"${path.join(__dirname, '../static').replace(/\\/g, '\\\\')}"` 67 | }) 68 | ) 69 | } 70 | 71 | /** 72 | * Adjust mainConfig for production settings 73 | */ 74 | if (process.env.NODE_ENV === 'production') { 75 | mainConfig.plugins.push( 76 | new BabiliWebpackPlugin(), 77 | new webpack.DefinePlugin({ 78 | 'process.env.NODE_ENV': '"production"' 79 | }) 80 | ) 81 | } 82 | 83 | module.exports = mainConfig 84 | -------------------------------------------------------------------------------- /imu_tool/.electron-vue/webpack.renderer.config.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | process.env.BABEL_ENV = 'renderer' 4 | 5 | const path = require('path') 6 | const { dependencies } = require('../package.json') 7 | const webpack = require('webpack') 8 | 9 | const BabiliWebpackPlugin = require('babili-webpack-plugin') 10 | const CopyWebpackPlugin = require('copy-webpack-plugin') 11 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 12 | const HtmlWebpackPlugin = require('html-webpack-plugin') 13 | 14 | /** 15 | * List of node_modules to include in webpack bundle 16 | * 17 | * Required for specific packages like Vue UI libraries 18 | * that provide pure *.vue files that need compiling 19 | * https://simulatedgreg.gitbooks.io/electron-vue/content/en/webpack-configurations.html#white-listing-externals 20 | */ 21 | let whiteListedModules = ['vue'] 22 | 23 | let rendererConfig = { 24 | devtool: '#cheap-module-eval-source-map', 25 | entry: { 26 | renderer: path.join(__dirname, '../src/renderer/main.js') 27 | }, 28 | externals: [ 29 | ...Object.keys(dependencies || {}).filter(d => !whiteListedModules.includes(d)) 30 | ], 31 | module: { 32 | rules: [ 33 | { 34 | test: /\.(js|vue)$/, 35 | enforce: 'pre', 36 | exclude: /node_modules/, 37 | use: { 38 | loader: 'eslint-loader', 39 | options: { 40 | formatter: require('eslint-friendly-formatter') 41 | } 42 | } 43 | }, 44 | { 45 | test: /\.css$/, 46 | use: ExtractTextPlugin.extract({ 47 | fallback: 'style-loader', 48 | use: 'css-loader' 49 | }) 50 | }, 51 | { 52 | test: /\.html$/, 53 | use: 'vue-html-loader' 54 | }, 55 | { 56 | test: /\.js$/, 57 | use: 'babel-loader', 58 | exclude: /node_modules/ 59 | }, 60 | { 61 | test: /\.node$/, 62 | use: 'node-loader' 63 | }, 64 | { 65 | test: /\.vue$/, 66 | use: { 67 | loader: 'vue-loader', 68 | options: { 69 | extractCSS: process.env.NODE_ENV === 'production', 70 | loaders: { 71 | sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax=1', 72 | scss: 'vue-style-loader!css-loader!sass-loader' 73 | } 74 | } 75 | } 76 | }, 77 | { 78 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 79 | use: { 80 | loader: 'url-loader', 81 | query: { 82 | limit: 10000, 83 | name: 'imgs/[name]--[folder].[ext]' 84 | } 85 | } 86 | }, 87 | { 88 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, 89 | loader: 'url-loader', 90 | options: { 91 | limit: 10000, 92 | name: 'media/[name]--[folder].[ext]' 93 | } 94 | }, 95 | { 96 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 97 | use: { 98 | loader: 'url-loader', 99 | query: { 100 | limit: 10000, 101 | name: 'fonts/[name]--[folder].[ext]' 102 | } 103 | } 104 | } 105 | ] 106 | }, 107 | node: { 108 | __dirname: process.env.NODE_ENV !== 'production', 109 | __filename: process.env.NODE_ENV !== 'production' 110 | }, 111 | plugins: [ 112 | new ExtractTextPlugin('styles.css'), 113 | new HtmlWebpackPlugin({ 114 | filename: 'index.html', 115 | template: path.resolve(__dirname, '../src/index.ejs'), 116 | minify: { 117 | collapseWhitespace: true, 118 | removeAttributeQuotes: true, 119 | removeComments: true 120 | }, 121 | nodeModules: process.env.NODE_ENV !== 'production' 122 | ? path.resolve(__dirname, '../node_modules') 123 | : false 124 | }), 125 | new webpack.HotModuleReplacementPlugin(), 126 | new webpack.NoEmitOnErrorsPlugin() 127 | ], 128 | output: { 129 | filename: '[name].js', 130 | libraryTarget: 'commonjs2', 131 | path: path.join(__dirname, '../dist/electron') 132 | }, 133 | resolve: { 134 | alias: { 135 | '@': path.join(__dirname, '../src/renderer'), 136 | 'vue$': 'vue/dist/vue.esm.js' 137 | }, 138 | extensions: ['.js', '.vue', '.json', '.css', '.node'] 139 | }, 140 | target: 'electron-renderer' 141 | } 142 | 143 | /** 144 | * Adjust rendererConfig for development settings 145 | */ 146 | if (process.env.NODE_ENV !== 'production') { 147 | rendererConfig.plugins.push( 148 | new webpack.DefinePlugin({ 149 | '__static': `"${path.join(__dirname, '../static').replace(/\\/g, '\\\\')}"` 150 | }) 151 | ) 152 | } 153 | 154 | /** 155 | * Adjust rendererConfig for production settings 156 | */ 157 | if (process.env.NODE_ENV === 'production') { 158 | rendererConfig.devtool = '' 159 | 160 | rendererConfig.plugins.push( 161 | new BabiliWebpackPlugin(), 162 | new CopyWebpackPlugin([ 163 | { 164 | from: path.join(__dirname, '../static'), 165 | to: path.join(__dirname, '../dist/electron/static'), 166 | ignore: ['.*'] 167 | } 168 | ]), 169 | new webpack.DefinePlugin({ 170 | 'process.env.NODE_ENV': '"production"' 171 | }), 172 | new webpack.LoaderOptionsPlugin({ 173 | minimize: true 174 | }) 175 | ) 176 | } 177 | 178 | module.exports = rendererConfig 179 | -------------------------------------------------------------------------------- /imu_tool/.electron-vue/webpack.web.config.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | process.env.BABEL_ENV = 'web' 4 | 5 | const path = require('path') 6 | const webpack = require('webpack') 7 | 8 | const BabiliWebpackPlugin = require('babili-webpack-plugin') 9 | const CopyWebpackPlugin = require('copy-webpack-plugin') 10 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 11 | const HtmlWebpackPlugin = require('html-webpack-plugin') 12 | 13 | let webConfig = { 14 | devtool: '#cheap-module-eval-source-map', 15 | entry: { 16 | web: path.join(__dirname, '../src/renderer/main.js') 17 | }, 18 | module: { 19 | rules: [ 20 | { 21 | test: /\.(js|vue)$/, 22 | enforce: 'pre', 23 | exclude: /node_modules/, 24 | use: { 25 | loader: 'eslint-loader', 26 | options: { 27 | formatter: require('eslint-friendly-formatter') 28 | } 29 | } 30 | }, 31 | { 32 | test: /\.css$/, 33 | use: ExtractTextPlugin.extract({ 34 | fallback: 'style-loader', 35 | use: 'css-loader' 36 | }) 37 | }, 38 | { 39 | test: /\.html$/, 40 | use: 'vue-html-loader' 41 | }, 42 | { 43 | test: /\.js$/, 44 | use: 'babel-loader', 45 | include: [ path.resolve(__dirname, '../src/renderer') ], 46 | exclude: /node_modules/ 47 | }, 48 | { 49 | test: /\.vue$/, 50 | use: { 51 | loader: 'vue-loader', 52 | options: { 53 | extractCSS: true, 54 | loaders: { 55 | sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax=1', 56 | scss: 'vue-style-loader!css-loader!sass-loader' 57 | } 58 | } 59 | } 60 | }, 61 | { 62 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 63 | use: { 64 | loader: 'url-loader', 65 | query: { 66 | limit: 10000, 67 | name: 'imgs/[name].[ext]' 68 | } 69 | } 70 | }, 71 | { 72 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 73 | use: { 74 | loader: 'url-loader', 75 | query: { 76 | limit: 10000, 77 | name: 'fonts/[name].[ext]' 78 | } 79 | } 80 | } 81 | ] 82 | }, 83 | plugins: [ 84 | new ExtractTextPlugin('styles.css'), 85 | new HtmlWebpackPlugin({ 86 | filename: 'index.html', 87 | template: path.resolve(__dirname, '../src/index.ejs'), 88 | minify: { 89 | collapseWhitespace: true, 90 | removeAttributeQuotes: true, 91 | removeComments: true 92 | }, 93 | nodeModules: false 94 | }), 95 | new webpack.DefinePlugin({ 96 | 'process.env.IS_WEB': 'true' 97 | }), 98 | new webpack.HotModuleReplacementPlugin(), 99 | new webpack.NoEmitOnErrorsPlugin() 100 | ], 101 | output: { 102 | filename: '[name].js', 103 | path: path.join(__dirname, '../dist/web') 104 | }, 105 | resolve: { 106 | alias: { 107 | '@': path.join(__dirname, '../src/renderer'), 108 | 'vue$': 'vue/dist/vue.esm.js' 109 | }, 110 | extensions: ['.js', '.vue', '.json', '.css'] 111 | }, 112 | target: 'web' 113 | } 114 | 115 | /** 116 | * Adjust webConfig for production settings 117 | */ 118 | if (process.env.NODE_ENV === 'production') { 119 | webConfig.devtool = '' 120 | 121 | webConfig.plugins.push( 122 | new BabiliWebpackPlugin(), 123 | new CopyWebpackPlugin([ 124 | { 125 | from: path.join(__dirname, '../static'), 126 | to: path.join(__dirname, '../dist/web/static'), 127 | ignore: ['.*'] 128 | } 129 | ]), 130 | new webpack.DefinePlugin({ 131 | 'process.env.NODE_ENV': '"production"' 132 | }), 133 | new webpack.LoaderOptionsPlugin({ 134 | minimize: true 135 | }) 136 | ) 137 | } 138 | 139 | module.exports = webConfig 140 | -------------------------------------------------------------------------------- /imu_tool/.eslintignore: -------------------------------------------------------------------------------- 1 | test/unit/coverage/** 2 | test/unit/*.js 3 | test/e2e/*.js 4 | -------------------------------------------------------------------------------- /imu_tool/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: 'babel-eslint', 4 | parserOptions: { 5 | sourceType: 'module' 6 | }, 7 | env: { 8 | browser: true, 9 | node: true 10 | }, 11 | extends: 'standard', 12 | globals: { 13 | __static: true 14 | }, 15 | plugins: [ 16 | 'html' 17 | ], 18 | 'rules': { 19 | // allow paren-less arrow functions 20 | 'arrow-parens': 0, 21 | // allow async-await 22 | 'generator-star-spacing': 0, 23 | // allow debugger during development 24 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /imu_tool/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | dist/electron/* 3 | dist/web/* 4 | build/* 5 | !build/icons 6 | coverage 7 | node_modules/ 8 | npm-debug.log 9 | npm-debug.log.* 10 | thumbs.db 11 | !.gitkeep 12 | -------------------------------------------------------------------------------- /imu_tool/.travis.yml: -------------------------------------------------------------------------------- 1 | # Commented sections below can be used to run tests on the CI server 2 | # https://simulatedgreg.gitbooks.io/electron-vue/content/en/testing.html#on-the-subject-of-ci-testing 3 | osx_image: xcode8.3 4 | sudo: required 5 | dist: trusty 6 | language: c 7 | matrix: 8 | include: 9 | - os: osx 10 | - os: linux 11 | env: CC=clang CXX=clang++ npm_config_clang=1 12 | compiler: clang 13 | cache: 14 | directories: 15 | - node_modules 16 | - "$HOME/.electron" 17 | - "$HOME/.cache" 18 | addons: 19 | apt: 20 | packages: 21 | - libgnome-keyring-dev 22 | - icnsutils 23 | #- xvfb 24 | before_install: 25 | - mkdir -p /tmp/git-lfs && curl -L https://github.com/github/git-lfs/releases/download/v1.2.1/git-lfs-$([ 26 | "$TRAVIS_OS_NAME" == "linux" ] && echo "linux" || echo "darwin")-amd64-1.2.1.tar.gz 27 | | tar -xz -C /tmp/git-lfs --strip-components 1 && /tmp/git-lfs/git-lfs pull 28 | - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get install --no-install-recommends -y icnsutils graphicsmagick xz-utils; fi 29 | install: 30 | #- export DISPLAY=':99.0' 31 | #- Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & 32 | - nvm install 7 33 | - curl -o- -L https://yarnpkg.com/install.sh | bash 34 | - source ~/.bashrc 35 | - npm install -g xvfb-maybe 36 | - yarn 37 | script: 38 | #- xvfb-maybe node_modules/.bin/karma start test/unit/karma.conf.js 39 | #- yarn run pack && xvfb-maybe node_modules/.bin/mocha test/e2e 40 | - yarn run build 41 | branches: 42 | only: 43 | - master 44 | -------------------------------------------------------------------------------- /imu_tool/README.md: -------------------------------------------------------------------------------- 1 | # imu_tool 2 | 3 | > An electron-vue project 4 | 5 | #### Build Setup 6 | 7 | ``` bash 8 | # install dependencies 9 | npm install 10 | 11 | # serve with hot reload at localhost:9080 12 | npm run dev 13 | 14 | # build electron application for production 15 | npm run build 16 | 17 | # run unit & end-to-end tests 18 | npm test 19 | 20 | 21 | # lint all JS/Vue component files in `src/` 22 | npm run lint 23 | 24 | ``` 25 | 26 | --- 27 | 28 | This project was generated with [electron-vue](https://github.com/SimulatedGREG/electron-vue)@[7c4e3e9](https://github.com/SimulatedGREG/electron-vue/tree/7c4e3e90a772bd4c27d2dd4790f61f09bae0fcef) using [vue-cli](https://github.com/vuejs/vue-cli). Documentation about the original structure can be found [here](https://simulatedgreg.gitbooks.io/electron-vue/content/index.html). 29 | -------------------------------------------------------------------------------- /imu_tool/appveyor.yml: -------------------------------------------------------------------------------- 1 | # Commented sections below can be used to run tests on the CI server 2 | # https://simulatedgreg.gitbooks.io/electron-vue/content/en/testing.html#on-the-subject-of-ci-testing 3 | version: 0.1.{build} 4 | 5 | branches: 6 | only: 7 | - master 8 | 9 | image: Visual Studio 2017 10 | platform: 11 | - x64 12 | 13 | cache: 14 | - node_modules 15 | - '%APPDATA%\npm-cache' 16 | - '%USERPROFILE%\.electron' 17 | - '%USERPROFILE%\AppData\Local\Yarn\cache' 18 | 19 | init: 20 | - git config --global core.autocrlf input 21 | 22 | install: 23 | - ps: Install-Product node 8 x64 24 | - choco install yarn --ignore-dependencies 25 | - git reset --hard HEAD 26 | - yarn 27 | - node --version 28 | 29 | build_script: 30 | #- yarn test 31 | - yarn build 32 | 33 | test: off 34 | -------------------------------------------------------------------------------- /imu_tool/build/icons/256x256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/imu_tool/build/icons/256x256.png -------------------------------------------------------------------------------- /imu_tool/build/icons/icon.icns: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/imu_tool/build/icons/icon.icns -------------------------------------------------------------------------------- /imu_tool/build/icons/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/imu_tool/build/icons/icon.ico -------------------------------------------------------------------------------- /imu_tool/dist/electron/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/imu_tool/dist/electron/.gitkeep -------------------------------------------------------------------------------- /imu_tool/dist/web/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/imu_tool/dist/web/.gitkeep -------------------------------------------------------------------------------- /imu_tool/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "imu_tool", 3 | "version": "0.0.0", 4 | "author": "Hawk Kim ", 5 | "description": "An electron-vue project", 6 | "license": null, 7 | "main": "./dist/electron/main.js", 8 | "scripts": { 9 | "build": "node .electron-vue/build.js && electron-builder", 10 | "build:dir": "node .electron-vue/build.js && electron-builder --dir", 11 | "build:clean": "cross-env BUILD_TARGET=clean node .electron-vue/build.js", 12 | "build:web": "cross-env BUILD_TARGET=web node .electron-vue/build.js", 13 | "dev": "node .electron-vue/dev-runner.js", 14 | "e2e": "npm run pack && mocha test/e2e", 15 | "lint": "eslint --ext .js,.vue -f ./node_modules/eslint-friendly-formatter src test", 16 | "lint:fix": "eslint --ext .js,.vue -f ./node_modules/eslint-friendly-formatter --fix src test", 17 | "pack": "npm run pack:main && npm run pack:renderer", 18 | "pack:main": "cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.main.config.js", 19 | "pack:renderer": "cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.renderer.config.js", 20 | "test": "npm run unit && npm run e2e", 21 | "unit": "karma start test/unit/karma.conf.js", 22 | "postinstall": "npm run lint:fix" 23 | }, 24 | "build": { 25 | "productName": "imu_tool", 26 | "appId": "org.simulatedgreg.electron-vue", 27 | "directories": { 28 | "output": "build" 29 | }, 30 | "files": [ 31 | "dist/electron/**/*" 32 | ], 33 | "dmg": { 34 | "contents": [ 35 | { 36 | "x": 410, 37 | "y": 150, 38 | "type": "link", 39 | "path": "/Applications" 40 | }, 41 | { 42 | "x": 130, 43 | "y": 150, 44 | "type": "file" 45 | } 46 | ] 47 | }, 48 | "mac": { 49 | "icon": "build/icons/icon.icns" 50 | }, 51 | "win": { 52 | "icon": "build/icons/icon.ico" 53 | }, 54 | "linux": { 55 | "icon": "build/icons" 56 | } 57 | }, 58 | "dependencies": { 59 | "axios": "^0.16.1", 60 | "canvas-gauges": "^2.1.5", 61 | "chart.js": "^2.7.2", 62 | "dat.gui": "^0.7.2", 63 | "dateformat": "^3.0.3", 64 | "three": "^0.93.0", 65 | "three-orbit-controls": "^82.1.0", 66 | "v-dragged": "0.0.5", 67 | "vue": "^2.4.2", 68 | "vue-chartjs": "^3.3.1", 69 | "vue-electron": "^1.0.6", 70 | "vue-router": "^2.5.3", 71 | "vue2-canvas-gauges": "0.0.0", 72 | "vuetify": "1.0.0", 73 | "vuewheel": "^2.1.6", 74 | "vuex": "^2.3.1", 75 | "webpack-material-design-icons": "^0.1.0" 76 | }, 77 | "devDependencies": { 78 | "babel-core": "^6.25.0", 79 | "babel-loader": "^7.1.1", 80 | "babel-plugin-transform-runtime": "^6.23.0", 81 | "babel-preset-env": "^1.6.0", 82 | "babel-preset-stage-0": "^6.24.1", 83 | "babel-register": "^6.24.1", 84 | "babili-webpack-plugin": "^0.1.2", 85 | "cfonts": "^1.1.3", 86 | "chalk": "^2.1.0", 87 | "copy-webpack-plugin": "^4.0.1", 88 | "cross-env": "^5.0.5", 89 | "css-loader": "^0.28.4", 90 | "del": "^3.0.0", 91 | "devtron": "^1.4.0", 92 | "electron": "^1.7.5", 93 | "electron-debug": "^1.4.0", 94 | "electron-devtools-installer": "^2.2.0", 95 | "electron-builder": "^19.19.1", 96 | "babel-eslint": "^7.2.3", 97 | "eslint": "^4.4.1", 98 | "eslint-friendly-formatter": "^3.0.0", 99 | "eslint-loader": "^1.9.0", 100 | "eslint-plugin-html": "^3.1.1", 101 | "eslint-config-standard": "^10.2.1", 102 | "eslint-plugin-import": "^2.7.0", 103 | "eslint-plugin-node": "^5.1.1", 104 | "eslint-plugin-promise": "^3.5.0", 105 | "eslint-plugin-standard": "^3.0.1", 106 | "extract-text-webpack-plugin": "^3.0.0", 107 | "file-loader": "^0.11.2", 108 | "html-webpack-plugin": "^2.30.1", 109 | "inject-loader": "^3.0.0", 110 | "karma": "^1.3.0", 111 | "karma-chai": "^0.1.0", 112 | "karma-coverage": "^1.1.1", 113 | "karma-electron": "^5.1.1", 114 | "karma-mocha": "^1.2.0", 115 | "karma-sourcemap-loader": "^0.3.7", 116 | "karma-spec-reporter": "^0.0.31", 117 | "karma-webpack": "^2.0.1", 118 | "webpack-merge": "^4.1.0", 119 | "require-dir": "^0.3.0", 120 | "spectron": "^3.7.1", 121 | "babel-plugin-istanbul": "^4.1.1", 122 | "chai": "^4.0.0", 123 | "mocha": "^3.0.2", 124 | "multispinner": "^0.2.1", 125 | "node-loader": "^0.6.0", 126 | "style-loader": "^0.18.2", 127 | "stylus": "^0.54.5", 128 | "stylus-loader": "^3.0.1", 129 | "url-loader": "^0.5.9", 130 | "vue-html-loader": "^1.2.4", 131 | "vue-loader": "^13.0.5", 132 | "vue-style-loader": "^3.0.1", 133 | "vue-template-compiler": "^2.4.2", 134 | "webpack": "^3.5.2", 135 | "webpack-dev-server": "^2.7.1", 136 | "webpack-hot-middleware": "^2.18.2" 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /imu_tool/src/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IMU Tool 6 | <% if (htmlWebpackPlugin.options.nodeModules) { %> 7 | 8 | 11 | <% } %> 12 | 13 | 14 |
15 | 16 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /imu_tool/src/main/index.dev.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file is used specifically and only for development. It installs 3 | * `electron-debug` & `vue-devtools`. There shouldn't be any need to 4 | * modify this file, but it can be used to extend your development 5 | * environment. 6 | */ 7 | 8 | /* eslint-disable */ 9 | 10 | // Set environment for development 11 | process.env.NODE_ENV = 'development' 12 | 13 | // Install `electron-debug` with `devtron` 14 | require('electron-debug')({ showDevTools: true }) 15 | 16 | // Install `vue-devtools` 17 | require('electron').app.on('ready', () => { 18 | let installExtension = require('electron-devtools-installer') 19 | installExtension.default(installExtension.VUEJS_DEVTOOLS) 20 | .then(() => {}) 21 | .catch(err => { 22 | console.log('Unable to install `vue-devtools`: \n', err) 23 | }) 24 | }) 25 | 26 | // Require `main` process to boot app 27 | require('./index') 28 | -------------------------------------------------------------------------------- /imu_tool/src/main/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | import { app, BrowserWindow } from 'electron' 4 | 5 | /** 6 | * Set `__static` path to static files in production 7 | * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html 8 | */ 9 | if (process.env.NODE_ENV !== 'development') { 10 | global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\') 11 | } 12 | 13 | let mainWindow 14 | const winURL = process.env.NODE_ENV === 'development' 15 | ? `http://localhost:9080` 16 | : `file://${__dirname}/index.html` 17 | 18 | function createWindow () { 19 | /** 20 | * Initial window options 21 | */ 22 | mainWindow = new BrowserWindow({ 23 | height: 563, 24 | useContentSize: true, 25 | width: 1000, 26 | webPreferences: { 27 | webSecurity: false 28 | } 29 | }) 30 | 31 | mainWindow.loadURL(winURL) 32 | 33 | mainWindow.on('closed', () => { 34 | mainWindow = null 35 | }) 36 | } 37 | 38 | app.on('ready', createWindow) 39 | 40 | app.on('window-all-closed', () => { 41 | if (process.platform !== 'darwin') { 42 | app.quit() 43 | } 44 | }) 45 | 46 | app.on('activate', () => { 47 | if (mainWindow === null) { 48 | createWindow() 49 | } 50 | }) 51 | 52 | /** 53 | * Auto Updater 54 | * 55 | * Uncomment the following code below and install `electron-updater` to 56 | * support auto updating. Code Signing with a valid certificate is required. 57 | * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating 58 | */ 59 | 60 | /* 61 | import { autoUpdater } from 'electron-updater' 62 | 63 | autoUpdater.on('update-downloaded', () => { 64 | autoUpdater.quitAndInstall() 65 | }) 66 | 67 | app.on('ready', () => { 68 | if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates() 69 | }) 70 | */ 71 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/App.vue: -------------------------------------------------------------------------------- 1 | 95 | 96 | 135 | 136 | 138 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/imu_tool/src/renderer/assets/.gitkeep -------------------------------------------------------------------------------- /imu_tool/src/renderer/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/imu_tool/src/renderer/assets/logo.png -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/Compass.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 93 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/ConnectDialog.vue: -------------------------------------------------------------------------------- 1 | 22 | 23 | 63 | 64 | 66 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/IMUCalibration.vue: -------------------------------------------------------------------------------- 1 | 32 | 33 | 68 | 69 | 71 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/IMUDashboard.vue: -------------------------------------------------------------------------------- 1 | 17 | 18 | 66 | 67 | 69 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/InspireView.vue: -------------------------------------------------------------------------------- 1 | 16 | 17 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/LineChart.vue: -------------------------------------------------------------------------------- 1 | 18 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/MAGCalibration.vue: -------------------------------------------------------------------------------- 1 | 36 | 37 | 110 | 111 | 113 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/MAGCalibrationDialog.vue: -------------------------------------------------------------------------------- 1 | 20 | 21 | 80 | 81 | 83 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/OrientationThree.vue: -------------------------------------------------------------------------------- 1 | 12 | 13 | 179 | 180 | 188 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/SphereFittingView.vue: -------------------------------------------------------------------------------- 1 | 5 | 6 | 109 | 110 | 112 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/WelcomeView.vue: -------------------------------------------------------------------------------- 1 | 45 | 46 | 59 | 60 | 78 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/components/WelcomeView/SystemInformation.vue: -------------------------------------------------------------------------------- 1 | 35 | 36 | 50 | 51 | 75 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/imu_comm/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | 3 | const ImuCommModeOrientation = 0 4 | const ImuCommModeMagnetometer = 1 5 | 6 | export const ImuComm = new Vue({ 7 | methods: { 8 | getOrientationData () { 9 | var self = this 10 | var url = 'http://' + self.ipAddress + ':' + self.port + '/imu/orientation' 11 | 12 | self.numRequest++ 13 | self.$http.get(url) 14 | .then((response) => { 15 | // console.log('got data') 16 | self.numSuccess++ 17 | if (self.isStopped === true) { 18 | return 19 | } 20 | self.$emit('imuOrientation', response.data) 21 | if (self.wait !== 0) { 22 | self.timer = setTimeout(() => { 23 | self.getIMUData() 24 | }, self.wait) 25 | } else { 26 | self.getIMUData() 27 | } 28 | }, (err) => { 29 | self.numFail++ 30 | console.log('failed to retrieve:' + err) 31 | self.isStopped = true 32 | }) 33 | }, 34 | getMagData () { 35 | var self = this 36 | var url = 'http://' + self.ipAddress + ':' + self.port + '/imu/mag_data' 37 | 38 | self.numRequest++ 39 | self.$http.get(url) 40 | .then((response) => { 41 | // console.log('got data') 42 | self.numSuccess++ 43 | if (self.isStopped === true) { 44 | return 45 | } 46 | self.$emit('imuMagnetometer', response.data) 47 | if (self.wait !== 0) { 48 | self.timer = setTimeout(() => { 49 | self.getIMUData() 50 | }, self.wait) 51 | } else { 52 | self.getIMUData() 53 | } 54 | }, (err) => { 55 | self.numFail++ 56 | console.log('failed to retrieve:' + err) 57 | self.isStopped = true 58 | }) 59 | }, 60 | getIMUData () { 61 | switch (this.mode) { 62 | case ImuCommModeOrientation: 63 | this.getOrientationData() 64 | break 65 | 66 | case ImuCommModeMagnetometer: 67 | this.getMagData() 68 | break 69 | } 70 | }, 71 | start (serverInfo) { 72 | this.ipAddress = serverInfo.ipAddress 73 | this.port = serverInfo.port 74 | this.wait = serverInfo.wait 75 | this.bufferSize = serverInfo.bufferSize 76 | this.isStopped = false 77 | 78 | this.$emit('onConnected') 79 | 80 | console.log('start polling: ' + this.ipAddress + ':' + this.port) 81 | this.getIMUData() 82 | }, 83 | stop () { 84 | console.log('stop polling: ' + this.ipAddress + ':' + this.port) 85 | 86 | this.$emit('onDisconnected') 87 | this.isStopped = true 88 | if (this.timer != null) { 89 | clearTimeout(this.timer) 90 | this.timer = null 91 | } 92 | }, 93 | putOrientationMode () { 94 | this.mode = ImuCommModeOrientation 95 | }, 96 | putMagnetometerMode () { 97 | this.mode = ImuCommModeMagnetometer 98 | }, 99 | startMagCalibration (callback) { 100 | var self = this 101 | var url = 'http://' + self.ipAddress + ':' + self.port + '/imu/mag_calibrate' 102 | 103 | self.$http.post(url, 104 | { 105 | dummy: 0 106 | }, 107 | { 108 | headers: { 'Content-Type': 'application/json' } 109 | }) 110 | .then((response) => { 111 | callback(null, response) 112 | }, (err) => { 113 | callback(err, null) 114 | }) 115 | } 116 | }, 117 | data: { 118 | ipAddress: null, 119 | port: null, 120 | wait: 0, 121 | isStopped: true, 122 | timer: null, 123 | bufferSize: 5, 124 | numRequest: 0, 125 | numSuccess: 0, 126 | numFail: 0, 127 | mode: ImuCommModeOrientation 128 | } 129 | }) 130 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/imu_comm_ws/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | 3 | const ImuCommModeOrientation = 0 4 | const ImuCommModeMagnetometer = 1 5 | 6 | export const ImuComm = new Vue({ 7 | methods: { 8 | getOrientationData () { 9 | var self = this 10 | 11 | if (this.ws === null) { 12 | return 13 | } 14 | 15 | var url = '/imu/orientation' 16 | 17 | self.numRequest++ 18 | 19 | self.ws.onmessage = function (e) { 20 | var msg = e.data 21 | 22 | self.numSuccess++ 23 | 24 | if (self.isStopped === true) { 25 | return 26 | } 27 | 28 | // console.log('orientation: ' + msg) 29 | self.$emit('imuOrientation', JSON.parse(msg)) 30 | 31 | if (self.wait !== 0) { 32 | self.timer = setTimeout(() => { 33 | self.getIMUData() 34 | }, self.wait) 35 | } else { 36 | self.getIMUData() 37 | } 38 | } 39 | self.ws.send(url) 40 | }, 41 | getMagData () { 42 | var self = this 43 | var url = '/imu/mag_data' 44 | 45 | self.numRequest++ 46 | 47 | self.ws.onmessage = function (e) { 48 | var msg = e.data 49 | 50 | // console.log('mag data: ' + msg) 51 | self.numSuccess++ 52 | 53 | if (self.isStopped === true) { 54 | return 55 | } 56 | 57 | self.$emit('imuMagnetometer', JSON.parse(msg)) 58 | 59 | if (self.wait !== 0) { 60 | self.timer = setTimeout(() => { 61 | self.getIMUData() 62 | }, self.wait) 63 | } else { 64 | self.getIMUData() 65 | } 66 | } 67 | self.ws.send(url) 68 | }, 69 | getIMUData () { 70 | switch (this.mode) { 71 | case ImuCommModeOrientation: 72 | this.getOrientationData() 73 | break 74 | 75 | case ImuCommModeMagnetometer: 76 | this.getMagData() 77 | break 78 | } 79 | }, 80 | start (serverInfo) { 81 | var self = this 82 | 83 | self.ipAddress = serverInfo.ipAddress 84 | self.port = serverInfo.port 85 | self.wait = serverInfo.wait 86 | self.bufferSize = serverInfo.bufferSize 87 | self.isStopped = false 88 | 89 | self.$emit('onConnecting') 90 | self.ws = new WebSocket('ws://' + self.ipAddress + ':' + self.port, 'json') 91 | 92 | self.ws.onopen = function () { 93 | self.$emit('onConnected') 94 | 95 | console.log('start polling: ' + self.ipAddress + ':' + self.port) 96 | self.getIMUData() 97 | } 98 | 99 | self.ws.onerror = function (error) { 100 | console.log('WebSocket Error ' + error) 101 | } 102 | }, 103 | stop () { 104 | var self = this 105 | 106 | console.log('stop polling: ' + self.ipAddress + ':' + self.port) 107 | 108 | self.$emit('onDisconnected') 109 | self.isStopped = true 110 | if (self.timer != null) { 111 | clearTimeout(self.timer) 112 | self.timer = null 113 | } 114 | self.ws.close() 115 | self.ws = null 116 | }, 117 | putOrientationMode () { 118 | this.mode = ImuCommModeOrientation 119 | }, 120 | putMagnetometerMode () { 121 | this.mode = ImuCommModeMagnetometer 122 | }, 123 | startMagCalibration (callback) { 124 | var self = this 125 | var url = 'http://' + self.ipAddress + ':' + self.port + '/imu/mag_calibrate' 126 | 127 | self.$http.post(url, 128 | { 129 | dummy: 0 130 | }, 131 | { 132 | headers: { 'Content-Type': 'application/json' } 133 | }) 134 | .then((response) => { 135 | callback(null, response) 136 | }, (err) => { 137 | callback(err, null) 138 | }) 139 | } 140 | }, 141 | data: { 142 | ipAddress: null, 143 | port: null, 144 | wait: 0, 145 | isStopped: true, 146 | timer: null, 147 | bufferSize: 5, 148 | numRequest: 0, 149 | numSuccess: 0, 150 | numFail: 0, 151 | mode: ImuCommModeOrientation, 152 | ws: null 153 | } 154 | }) 155 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import axios from 'axios' 3 | import Vuetify from 'vuetify' 4 | import 'vuetify/dist/vuetify.css' 5 | 6 | import App from './App' 7 | import router from './router' 8 | import store from './store' 9 | 10 | import VDragged from 'v-dragged' 11 | import vuewheel from 'vuewheel' 12 | 13 | import 'material-design-icons/iconfont/material-icons.css' 14 | 15 | Vue.use(Vuetify) 16 | Vue.use(VDragged) 17 | Vue.use(vuewheel) 18 | 19 | if (!process.env.IS_WEB) Vue.use(require('vue-electron')) 20 | Vue.http = Vue.prototype.$http = axios 21 | Vue.config.productionTip = false 22 | 23 | /* eslint-disable no-new */ 24 | new Vue({ 25 | components: { App }, 26 | router, 27 | store, 28 | template: '' 29 | }).$mount('#app') 30 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Router from 'vue-router' 3 | 4 | Vue.use(Router) 5 | 6 | export default new Router({ 7 | routes: [ 8 | { 9 | path: '/', 10 | name: 'welcome-view', 11 | component: require('@/components/WelcomeView').default 12 | }, 13 | { 14 | path: '/inspire', 15 | name: 'inspire', 16 | component: require('@/components/InspireView').default 17 | }, 18 | { 19 | path: '/imu-graph', 20 | name: 'imu-graph', 21 | component: require('@/components/IMUGraph').default 22 | }, 23 | { 24 | path: '/imu-dashboard', 25 | name: 'imu-dashboard', 26 | component: require('@/components/IMUDashboard').default 27 | }, 28 | { 29 | path: '/imu-calibration', 30 | name: 'imu-calibration', 31 | component: require('@/components/IMUCalibration').default 32 | }, 33 | { 34 | path: '*', 35 | redirect: '/' 36 | } 37 | ] 38 | }) 39 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/store/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Vuex from 'vuex' 3 | 4 | import modules from './modules' 5 | 6 | Vue.use(Vuex) 7 | 8 | export default new Vuex.Store({ 9 | modules, 10 | strict: process.env.NODE_ENV !== 'production' 11 | }) 12 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/store/modules/Counter.js: -------------------------------------------------------------------------------- 1 | const state = { 2 | main: 0 3 | } 4 | 5 | const mutations = { 6 | DECREMENT_MAIN_COUNTER (state) { 7 | state.main-- 8 | }, 9 | INCREMENT_MAIN_COUNTER (state) { 10 | state.main++ 11 | } 12 | } 13 | 14 | const actions = { 15 | someAsyncTask ({ commit }) { 16 | // do something async 17 | commit('INCREMENT_MAIN_COUNTER') 18 | } 19 | } 20 | 21 | export default { 22 | state, 23 | mutations, 24 | actions 25 | } 26 | -------------------------------------------------------------------------------- /imu_tool/src/renderer/store/modules/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * The file enables `@/store/index.js` to import all vuex modules 3 | * in a one-shot manner. There should not be any reason to edit this file. 4 | */ 5 | 6 | const files = require.context('.', false, /\.js$/) 7 | const modules = {} 8 | 9 | files.keys().forEach(key => { 10 | if (key === './index.js') return 11 | modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default 12 | }) 13 | 14 | export default modules 15 | -------------------------------------------------------------------------------- /imu_tool/static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/imu_tool/static/.gitkeep -------------------------------------------------------------------------------- /imu_tool/static/v.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peakhunt/esp32_imu/4b29574924694e182c61d6eac2090e01159f4b30/imu_tool/static/v.png -------------------------------------------------------------------------------- /imu_tool/test/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "mocha": true 4 | }, 5 | "globals": { 6 | "assert": true, 7 | "expect": true, 8 | "should": true, 9 | "__static": true 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /imu_tool/test/e2e/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | // Set BABEL_ENV to use proper env config 4 | process.env.BABEL_ENV = 'test' 5 | 6 | // Enable use of ES6+ on required files 7 | require('babel-register')({ 8 | ignore: /node_modules/ 9 | }) 10 | 11 | // Attach Chai APIs to global scope 12 | const { expect, should, assert } = require('chai') 13 | global.expect = expect 14 | global.should = should 15 | global.assert = assert 16 | 17 | // Require all JS files in `./specs` for Mocha to consume 18 | require('require-dir')('./specs') 19 | -------------------------------------------------------------------------------- /imu_tool/test/e2e/specs/Launch.spec.js: -------------------------------------------------------------------------------- 1 | import utils from '../utils' 2 | 3 | describe('Launch', function () { 4 | beforeEach(utils.beforeEach) 5 | afterEach(utils.afterEach) 6 | 7 | it('shows the proper application title', function () { 8 | return this.app.client.getTitle() 9 | .then(title => { 10 | expect(title).to.equal('imu_tool') 11 | }) 12 | }) 13 | }) 14 | -------------------------------------------------------------------------------- /imu_tool/test/e2e/utils.js: -------------------------------------------------------------------------------- 1 | import electron from 'electron' 2 | import { Application } from 'spectron' 3 | 4 | export default { 5 | afterEach () { 6 | this.timeout(10000) 7 | 8 | if (this.app && this.app.isRunning()) { 9 | return this.app.stop() 10 | } 11 | }, 12 | beforeEach () { 13 | this.timeout(10000) 14 | this.app = new Application({ 15 | path: electron, 16 | args: ['dist/electron/main.js'], 17 | startTimeout: 10000, 18 | waitTimeout: 10000 19 | }) 20 | 21 | return this.app.start() 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /imu_tool/test/unit/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | Vue.config.devtools = false 3 | Vue.config.productionTip = false 4 | 5 | // require all test files (files that ends with .spec.js) 6 | const testsContext = require.context('./specs', true, /\.spec$/) 7 | testsContext.keys().forEach(testsContext) 8 | 9 | // require all src files except main.js for coverage. 10 | // you can also change this to match only the subset of files that 11 | // you want coverage for. 12 | const srcContext = require.context('../../src/renderer', true, /^\.\/(?!main(\.js)?$)/) 13 | srcContext.keys().forEach(srcContext) 14 | -------------------------------------------------------------------------------- /imu_tool/test/unit/karma.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const path = require('path') 4 | const merge = require('webpack-merge') 5 | const webpack = require('webpack') 6 | 7 | const baseConfig = require('../../.electron-vue/webpack.renderer.config') 8 | const projectRoot = path.resolve(__dirname, '../../src/renderer') 9 | 10 | // Set BABEL_ENV to use proper preset config 11 | process.env.BABEL_ENV = 'test' 12 | 13 | let webpackConfig = merge(baseConfig, { 14 | devtool: '#inline-source-map', 15 | plugins: [ 16 | new webpack.DefinePlugin({ 17 | 'process.env.NODE_ENV': '"testing"' 18 | }) 19 | ] 20 | }) 21 | 22 | // don't treat dependencies as externals 23 | delete webpackConfig.entry 24 | delete webpackConfig.externals 25 | delete webpackConfig.output.libraryTarget 26 | 27 | // apply vue option to apply isparta-loader on js 28 | webpackConfig.module.rules 29 | .find(rule => rule.use.loader === 'vue-loader').use.options.loaders.js = 'babel-loader' 30 | 31 | module.exports = config => { 32 | config.set({ 33 | browsers: ['visibleElectron'], 34 | client: { 35 | useIframe: false 36 | }, 37 | coverageReporter: { 38 | dir: './coverage', 39 | reporters: [ 40 | { type: 'lcov', subdir: '.' }, 41 | { type: 'text-summary' } 42 | ] 43 | }, 44 | customLaunchers: { 45 | 'visibleElectron': { 46 | base: 'Electron', 47 | flags: ['--show'] 48 | } 49 | }, 50 | frameworks: ['mocha', 'chai'], 51 | files: ['./index.js'], 52 | preprocessors: { 53 | './index.js': ['webpack', 'sourcemap'] 54 | }, 55 | reporters: ['spec', 'coverage'], 56 | singleRun: true, 57 | webpack: webpackConfig, 58 | webpackMiddleware: { 59 | noInfo: true 60 | } 61 | }) 62 | } 63 | -------------------------------------------------------------------------------- /imu_tool/test/unit/specs/LandingPage.spec.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import LandingPage from '@/components/LandingPage' 3 | 4 | describe('LandingPage.vue', () => { 5 | it('should render correct contents', () => { 6 | const vm = new Vue({ 7 | el: document.createElement('div'), 8 | render: h => h(LandingPage) 9 | }).$mount() 10 | 11 | expect(vm.$el.querySelector('.title').textContent).to.contain('Welcome to your new project!') 12 | }) 13 | }) 14 | -------------------------------------------------------------------------------- /main/Kconfig.projbuild: -------------------------------------------------------------------------------- 1 | menu "ESP32 IMU Configuration" 2 | 3 | config BLINK_GPIO 4 | int "Blink GPIO number" 5 | range 0 34 6 | default 5 7 | help 8 | GPIO number (IOxx) to blink on and off. 9 | 10 | Some GPIOs are used for other purposes (flash connections, etc.) and cannot be used to blink. 11 | 12 | GPIOs 35-39 are input-only so cannot be used as outputs. 13 | 14 | 15 | config WIFI_SSID 16 | string "WiFi SSID" 17 | default "myssid" 18 | help 19 | SSID (network name) for the example to connect to. 20 | 21 | config WIFI_PASSWORD 22 | string "WiFi Password" 23 | default "myssid" 24 | help 25 | WiFi password (WPA or WPA2) for the example to use. 26 | 27 | Can be left blank if the network has no security set. 28 | 29 | config TELNET_PORT 30 | int "Telnet Server Port number" 31 | default 7000 32 | help 33 | Telnet Server Port Number for CLI access. 34 | 35 | endmenu 36 | -------------------------------------------------------------------------------- /main/accel_calibration.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "accel_calibration.h" 3 | #include "sensor_calib.h" 4 | 5 | /* 6 | As for accelerometer, things are not that simple. The purpose of accelerometer calibration 7 | is to find offset and scale for the sensor so that actual accelerometer value is 8 | calculated using the following fomula. 9 | actual = (raw - offset) * scale 10 | To calculate offset/scale, we use a typical 6 axis sampling/calibration mechanism. 11 | */ 12 | 13 | static int32_t _sample_count[6]; 14 | static int32_t _acc_sum[6][3]; 15 | static int32_t _offset[3]; 16 | static int32_t _gain[3]; 17 | 18 | static sensor_calib_t _cal_state; 19 | 20 | #define ACCEL_GAIN_REF (512 * 8) 21 | 22 | static int 23 | getPrimaryAxisIndex(int32_t sample[3]) 24 | { 25 | const int x = 0, 26 | y = 1, 27 | z = 2; 28 | 29 | // tolerate up to atan(1 / 1.5) = 33 deg tilt (in worst case 66 deg separation between points) 30 | if ((abs(sample[z]) / 1.5f) > abs(sample[x]) && (abs(sample[z]) / 1.5f) > abs(sample[y])) { 31 | //z-axis 32 | return (sample[z] > 0) ? 0 : 1; 33 | } 34 | else if ((abs(sample[x]) / 1.5f) > abs(sample[y]) && (abs(sample[x]) / 1.5f) > abs(sample[z])) { 35 | //x-axis 36 | return (sample[x] > 0) ? 2 : 3; 37 | } 38 | else if ((abs(sample[y]) / 1.5f) > abs(sample[x]) && (abs(sample[y]) / 1.5f) > abs(sample[z])) { 39 | //y-axis 40 | return (sample[y] > 0) ? 4 : 5; 41 | } 42 | else 43 | return -1; 44 | } 45 | 46 | void 47 | accel_calibration_init(void) 48 | { 49 | for(int i = 0; i < 6; i++) 50 | { 51 | _acc_sum[i][0] = 0; 52 | _acc_sum[i][1] = 0; 53 | _acc_sum[i][2] = 0; 54 | 55 | _sample_count[i] = 0; 56 | } 57 | 58 | sensorCalibrationResetState(&_cal_state); 59 | } 60 | 61 | void 62 | accel_calibration_update(int16_t ax, int16_t ay, int16_t az) 63 | { 64 | int32_t accel_value[3]; 65 | int axis_ndx; 66 | 67 | accel_value[0] = ax; 68 | accel_value[1] = ay; 69 | accel_value[2] = az; 70 | 71 | axis_ndx = getPrimaryAxisIndex(accel_value); 72 | 73 | if (axis_ndx < 0) 74 | { 75 | return; 76 | } 77 | 78 | sensorCalibrationPushSampleForOffsetCalculation(&_cal_state, accel_value); 79 | 80 | _acc_sum[axis_ndx][0] += accel_value[0]; 81 | _acc_sum[axis_ndx][1] += accel_value[1]; 82 | _acc_sum[axis_ndx][2] += accel_value[2]; 83 | 84 | _sample_count[axis_ndx]++; 85 | } 86 | 87 | void 88 | accel_calibration_finish(int16_t offsets[3], int16_t gains[3]) 89 | { 90 | float tmp[3]; 91 | int32_t sample[3]; 92 | 93 | /* calculate offset */ 94 | sensorCalibrationSolveForOffset(&_cal_state, tmp); 95 | 96 | for(int i = 0; i < 3; i++) 97 | { 98 | _offset[i] = lrintf(tmp[i]); 99 | } 100 | 101 | /* Not we can offset our accumulated averages samples and calculate scale factors and calculate gains */ 102 | sensorCalibrationResetState(&_cal_state); 103 | 104 | for (int axis = 0; axis < 6; axis++) { 105 | sample[0] = _acc_sum[axis][0] / _sample_count[axis] - _offset[0]; 106 | sample[1] = _acc_sum[axis][1] / _sample_count[axis] - _offset[1]; 107 | sample[2] = _acc_sum[axis][2] / _sample_count[axis] - _offset[2]; 108 | 109 | sensorCalibrationPushSampleForScaleCalculation(&_cal_state, axis / 2, sample, ACCEL_GAIN_REF); 110 | } 111 | 112 | sensorCalibrationSolveForScale(&_cal_state, tmp); 113 | 114 | for (int axis = 0; axis < 3; axis++) 115 | { 116 | _gain[axis] = lrintf(tmp[axis] * 4096); 117 | } 118 | 119 | offsets[0] = _offset[0]; 120 | offsets[1] = _offset[1]; 121 | offsets[2] = _offset[2]; 122 | 123 | gains[0] = _gain[0]; 124 | gains[1] = _gain[1]; 125 | gains[2] = _gain[2]; 126 | } 127 | -------------------------------------------------------------------------------- /main/accel_calibration.h: -------------------------------------------------------------------------------- 1 | #ifndef __ACCEL_CALIBRATION_DEF_H__ 2 | #define __ACCEL_CALIBRATION_DEF_H__ 3 | 4 | #include "common_def.h" 5 | 6 | extern void accel_calibration_init(void); 7 | extern void accel_calibration_update(int16_t ax, int16_t ay, int16_t az); 8 | extern void accel_calibration_finish(int16_t offsets[3], int16_t gains[3]); 9 | 10 | #endif /* !__ACCEL_CALIBRATION_DEF_H__ */ 11 | -------------------------------------------------------------------------------- /main/app_wifi.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "freertos/FreeRTOS.h" 4 | #include "freertos/task.h" 5 | #include "freertos/event_groups.h" 6 | #include "freertos/semphr.h" 7 | #include "esp_wifi.h" 8 | #include "esp_wpa2.h" 9 | #include "esp_event_loop.h" 10 | #include "esp_log.h" 11 | #include "esp_system.h" 12 | #include "nvs_flash.h" 13 | 14 | #include "app_wifi.h" 15 | 16 | #define TARGET_WIFI_SSID CONFIG_WIFI_SSID 17 | #define TARGET_WIFI_PASS CONFIG_WIFI_PASSWORD 18 | 19 | static const char* TAG = "app_wifi"; 20 | static tcpip_adapter_ip_info_t _ip_info; 21 | static bool _ip_configured = FALSE; 22 | static SemaphoreHandle_t _mutex; 23 | 24 | static wifi_config_t _wifi_config = 25 | { 26 | .sta = { 27 | .ssid = CONFIG_WIFI_SSID, 28 | .password = CONFIG_WIFI_PASSWORD, 29 | }, 30 | }; 31 | 32 | static void 33 | update_ip_info(const tcpip_adapter_ip_info_t* info) 34 | { 35 | xSemaphoreTake(_mutex, portMAX_DELAY); 36 | 37 | _ip_configured = TRUE; 38 | memcpy(&_ip_info, info, sizeof(_ip_info)); 39 | 40 | xSemaphoreGive(_mutex); 41 | } 42 | 43 | static void 44 | get_ip_info(tcpip_adapter_ip_info_t* info, bool* is_configured) 45 | { 46 | xSemaphoreTake(_mutex, portMAX_DELAY); 47 | 48 | *is_configured = _ip_configured; 49 | memcpy(info, &_ip_info, sizeof(_ip_info)); 50 | 51 | xSemaphoreGive(_mutex); 52 | } 53 | 54 | static esp_err_t 55 | wifi_event_handler(void* ctx, system_event_t* event) 56 | { 57 | switch(event->event_id) 58 | { 59 | case SYSTEM_EVENT_STA_START: 60 | // FIXME 61 | ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START"); 62 | ESP_ERROR_CHECK(esp_wifi_connect()); // ??? why ??? 63 | break; 64 | 65 | case SYSTEM_EVENT_STA_GOT_IP: 66 | // FIXME 67 | update_ip_info(&event->event_info.got_ip.ip_info); 68 | 69 | ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP"); 70 | ESP_LOGI(TAG, "got ip:%s", ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip)); 71 | break; 72 | 73 | case SYSTEM_EVENT_STA_DISCONNECTED: 74 | // FIXME 75 | _ip_configured = FALSE; 76 | 77 | ESP_LOGI(TAG, "SYSTEM_EVENT_STA_DISCONNECTED"); 78 | ESP_ERROR_CHECK(esp_wifi_connect()); 79 | break; 80 | 81 | default: 82 | break; 83 | } 84 | 85 | return ESP_OK; 86 | } 87 | 88 | static void 89 | app_wifi_read_config(void) 90 | { 91 | esp_err_t err; 92 | nvs_handle my_handle; 93 | size_t len; 94 | 95 | err = nvs_open("storage", NVS_READWRITE, &my_handle); 96 | 97 | if(err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) 98 | { 99 | return; 100 | } 101 | 102 | err = nvs_get_str(my_handle, "ap", NULL, &len); 103 | if(err == ESP_OK) 104 | { 105 | nvs_get_str(my_handle, "ap", (char*)_wifi_config.sta.ssid, &len); 106 | } 107 | 108 | err = nvs_get_str(my_handle, "pass", NULL, &len); 109 | if(err == ESP_OK) 110 | { 111 | nvs_get_str(my_handle, "pass", (char*)_wifi_config.sta.password, &len); 112 | } 113 | 114 | nvs_close(my_handle); 115 | } 116 | 117 | void 118 | app_wifi_init(void) 119 | { 120 | _mutex = xSemaphoreCreateMutex(); 121 | 122 | app_wifi_read_config(); 123 | 124 | tcpip_adapter_init(); 125 | 126 | ESP_ERROR_CHECK(esp_event_loop_init(wifi_event_handler, NULL)); 127 | 128 | ESP_LOGI(TAG, "initializing wifi"); 129 | 130 | wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); 131 | ESP_ERROR_CHECK(esp_wifi_init(&cfg)); 132 | 133 | // ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) ); 134 | 135 | ESP_LOGI(TAG, "starting wifi: ssid %s", _wifi_config.sta.ssid); 136 | 137 | ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); 138 | ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &_wifi_config)); 139 | ESP_ERROR_CHECK(esp_wifi_start()); 140 | } 141 | 142 | void 143 | app_wifi_get_config(tcpip_adapter_ip_info_t* info, char ssid[32], bool* is_configured) 144 | { 145 | strcpy(ssid, (char*)_wifi_config.sta.ssid); 146 | get_ip_info(info, is_configured); 147 | } 148 | -------------------------------------------------------------------------------- /main/app_wifi.h: -------------------------------------------------------------------------------- 1 | #ifndef __APP_WIFI_DEF_H__ 2 | #define __APP_WIFI_DEF_H__ 3 | 4 | #include "common_def.h" 5 | #include "tcpip_adapter.h" 6 | 7 | extern void app_wifi_init(void); 8 | extern void app_wifi_get_config(tcpip_adapter_ip_info_t* info, char ssid[32], bool* is_configured); 9 | 10 | #endif /* !__APP_WIFI_DEF_H__ */ 11 | -------------------------------------------------------------------------------- /main/blinky.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "freertos/FreeRTOS.h" 3 | #include "freertos/task.h" 4 | #include "driver/gpio.h" 5 | #include "esp_log.h" 6 | #include "sdkconfig.h" 7 | 8 | #define BLINK_GPIO CONFIG_BLINK_GPIO 9 | #define BLINK_DELAY 100 10 | 11 | static const char* TAG = "blinky"; 12 | 13 | void blink_task(void *pvParameter) 14 | { 15 | gpio_pad_select_gpio(BLINK_GPIO); 16 | /* Set the GPIO as a push/pull output */ 17 | gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT); 18 | 19 | while(1) 20 | { 21 | /* Blink off (output low) */ 22 | gpio_set_level(BLINK_GPIO, 0); 23 | vTaskDelay(BLINK_DELAY / portTICK_PERIOD_MS); 24 | 25 | /* Blink on (output high) */ 26 | gpio_set_level(BLINK_GPIO, 1); 27 | vTaskDelay(BLINK_DELAY / portTICK_PERIOD_MS); 28 | } 29 | } 30 | 31 | void 32 | blinky_init(void) 33 | { 34 | ESP_LOGI(TAG, "starting blinky"); 35 | // 36 | // XXX 37 | // with this task stack size. calling ESP_LOGI will overflow the stack. 38 | // but at the same time, does the blinky task deserves a 1K task stack? 39 | // I don't think so. 40 | // 41 | xTaskCreate(blink_task, "blink_task", configMINIMAL_STACK_SIZE, NULL, 5, NULL); 42 | } 43 | -------------------------------------------------------------------------------- /main/blinky.h: -------------------------------------------------------------------------------- 1 | #ifndef __BLINKY_DEF_H__ 2 | #define __BLINKY_DEF_H__ 3 | 4 | extern void blinky_init(void); 5 | 6 | #endif /* !__BLINKY_DEF_H__ */ 7 | -------------------------------------------------------------------------------- /main/component.mk: -------------------------------------------------------------------------------- 1 | # 2 | # "main" pseudo-component makefile. 3 | # 4 | # (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) 5 | -------------------------------------------------------------------------------- /main/gyro_calibration.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "gyro_calibration.h" 3 | #include "sensor_calib.h" 4 | 5 | /* 6 | As for gyro, all we can do is zero calibration. That is, 7 | when the board stands still, we should get zero values for all the axises from gyro. 8 | But in reality, those values will be slightly bigger/smaller than zero due to various 9 | errors. So all we gotta do is calculate the offset values for zero position and save them. 10 | Later after calibration, those offset values will be simply subtracted from real sample 11 | values to produce more correct value. 12 | Offset can be calculated simply by off = (sum of all samples) / num_samples 13 | */ 14 | 15 | static uint32_t _sample_count; 16 | 17 | static float _sum[3]; 18 | 19 | void 20 | gyro_calibration_init(void) 21 | { 22 | _sample_count = 0; 23 | _sum[0] = 24 | _sum[1] = 25 | _sum[2] = 0.0f; 26 | } 27 | 28 | void 29 | gyro_calibration_update(int16_t gx, int16_t gy, int16_t gz) 30 | { 31 | _sum[0] += gx; 32 | _sum[1] += gy; 33 | _sum[2] += gz; 34 | 35 | _sample_count++; 36 | } 37 | 38 | void 39 | gyro_calibration_finish(int16_t offsets[3]) 40 | { 41 | offsets[0] = (int16_t)(_sum[0] / _sample_count); 42 | offsets[1] = (int16_t)(_sum[1] / _sample_count); 43 | offsets[2] = (int16_t)(_sum[2] / _sample_count); 44 | } 45 | -------------------------------------------------------------------------------- /main/gyro_calibration.h: -------------------------------------------------------------------------------- 1 | #ifndef __GYRO_CALIBRATION_DEF_H__ 2 | #define __GYRO_CALIBRATION_DEF_H__ 3 | 4 | #include "common_def.h" 5 | 6 | extern void gyro_calibration_init(void); 7 | extern void gyro_calibration_update(int16_t gx, int16_t gy, int16_t gz); 8 | extern void gyro_calibration_finish(int16_t offsets[3]); 9 | 10 | #endif /* !__GYRO_CALIBRATION_DEF_H__ */ 11 | -------------------------------------------------------------------------------- /main/imu.h: -------------------------------------------------------------------------------- 1 | #ifndef __IMU_DEF_H__ 2 | #define __IMU_DEF_H__ 3 | 4 | #include "common_def.h" 5 | #include "madgwick.h" 6 | #include "mahony.h" 7 | 8 | #define USE_MADGWICK 1 9 | 10 | typedef enum 11 | { 12 | imu_mode_normal, 13 | imu_mode_accel_calibrating, 14 | imu_mode_gyro_calibrating, 15 | imu_mode_mag_calibrating, 16 | } imu_mode_t; 17 | 18 | typedef enum 19 | { 20 | imu_board_align_cw_0, 21 | imu_board_align_cw_90, 22 | imu_board_align_cw_180, 23 | imu_board_align_cw_270, 24 | imu_board_align_cw_0_flip, 25 | imu_board_align_cw_90_flip, 26 | imu_board_align_cw_180_flip, 27 | imu_board_align_cw_270_flip, 28 | imu_board_align_special, 29 | imu_board_align_special2 30 | } imu_board_align_t; 31 | 32 | typedef struct 33 | { 34 | int16_t accel[3]; 35 | int16_t gyro[3]; 36 | int16_t mag[3]; 37 | int16_t temp; 38 | } imu_sensor_data_t; 39 | 40 | typedef struct 41 | { 42 | int16_t accel_off[3]; 43 | int16_t accel_scale[3]; 44 | int16_t gyro_off[3]; 45 | int16_t mag_bias[3]; 46 | float mag_declination; 47 | } imu_sensor_calib_data_t; 48 | 49 | typedef struct 50 | { 51 | float accel_lsb; 52 | float gyro_lsb; 53 | float mag_lsb; 54 | } imu_raw_to_real_t; 55 | 56 | typedef struct 57 | { 58 | float accel[3]; // in G 59 | float gyro[3]; // in degrees per sec (not radian) 60 | float mag[3]; // in uT 61 | float temp; // in celcius 62 | float orientation[3]; // AHRS output 63 | float quaternion[4]; 64 | } imu_data_t; 65 | 66 | typedef struct 67 | { 68 | imu_mode_t mode; 69 | 70 | imu_sensor_data_t raw; 71 | imu_sensor_data_t adjusted; 72 | 73 | imu_sensor_calib_data_t cal; 74 | 75 | imu_board_align_t accel_align; 76 | imu_board_align_t gyro_align; 77 | imu_board_align_t mag_align; 78 | 79 | imu_raw_to_real_t lsb; 80 | 81 | imu_data_t data; 82 | 83 | #if USE_MADGWICK == 1 84 | madgwick_t filter; 85 | #else 86 | mahony_t filter; 87 | #endif 88 | float update_rate; 89 | } imu_t; 90 | 91 | extern void imu_init(imu_t* imu); 92 | extern void imu_update(imu_t* imu); 93 | 94 | extern void imu_mag_calibration_start(imu_t* imu); 95 | extern void imu_mag_calibration_finish(imu_t* imu); 96 | 97 | extern void imu_gyro_calibration_start(imu_t* imu); 98 | extern void imu_gyro_calibration_finish(imu_t* imu); 99 | 100 | extern void imu_accel_calibration_init(imu_t* imu); 101 | extern void imu_accel_calibration_step_start(imu_t* imu); 102 | extern void imu_accel_calibration_step_stop(imu_t* imu); 103 | extern void imu_accel_calibration_finish(imu_t* imu); 104 | 105 | #endif /* !__IMU_DEF_H__ */ 106 | -------------------------------------------------------------------------------- /main/imu_task.h: -------------------------------------------------------------------------------- 1 | #ifndef __IMU_TASK_DEF_H__ 2 | #define __IMU_TASK_DEF_H__ 3 | 4 | #include "common_def.h" 5 | 6 | #include "imu.h" 7 | #include "mpu9250.h" 8 | 9 | extern void imu_task_init(void); 10 | 11 | extern void imu_task_do_mag_calibration(void); 12 | extern void imu_task_do_gyro_calibration(void); 13 | 14 | extern void imu_task_do_accel_calibration_init(void); 15 | extern void imu_task_do_accel_calibration_start(void); 16 | extern void imu_task_do_accel_calibration_finish(void); 17 | 18 | extern void imu_task_get_raw_and_data(imu_mode_t* mode, 19 | imu_sensor_data_t* raw, 20 | imu_sensor_data_t* calibrated, 21 | imu_data_t* data); 22 | extern uint32_t imu_task_get_loop_cnt(void); 23 | 24 | extern void imu_task_get_cal_state(imu_sensor_calib_data_t* cal); 25 | 26 | extern void imu_task_get_mag_calibration(imu_mode_t* mode, 27 | int16_t raw[3], 28 | int16_t calibrated[3], 29 | int16_t mag_bias[3]); 30 | 31 | #endif /* !__IMU_TASK_DEF_H__ */ 32 | -------------------------------------------------------------------------------- /main/lcd_driver.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "freertos/FreeRTOS.h" 3 | #include "freertos/task.h" 4 | #include "freertos/queue.h" 5 | #include "esp_log.h" 6 | #include "sdkconfig.h" 7 | #include "st7735.h" 8 | #include "app_wifi.h" 9 | #include "driver/gpio.h" 10 | 11 | #include "imu_task.h" 12 | 13 | #define BUTTON_1 35 14 | #define BUTTON_2 34 15 | #define BUTTON_3 39 16 | 17 | #define BUTTON_PIN_SEL ((1ULL << BUTTON_1) | (1ULL << BUTTON_2) | (1ULL << BUTTON_3)) 18 | 19 | static const char* TAG = "lcd driver"; 20 | static xQueueHandle gpio_evt_queue = NULL; 21 | 22 | static void 23 | IRAM_ATTR gpio_isr_handler(void* arg) 24 | { 25 | uint32_t gpio_num = (uint32_t) arg; 26 | 27 | xQueueSendFromISR(gpio_evt_queue, &gpio_num, NULL); 28 | } 29 | 30 | 31 | static void 32 | print_page1(void) 33 | { 34 | tcpip_adapter_ip_info_t info; 35 | bool is_configured; 36 | char ssid[32]; 37 | char buffer[32]; 38 | 39 | app_wifi_get_config(&info, ssid, &is_configured); 40 | 41 | st7735_drawstring(0, 0, "System Ready ", ST7735_WHITE); 42 | 43 | sprintf(buffer, "SSID:%-16s", ssid); 44 | st7735_drawstring(0, 1, buffer, ST7735_WHITE); 45 | 46 | if(is_configured) 47 | { 48 | st7735_drawstring(0, 2, "IP Addreess Info ", ST7735_WHITE); 49 | 50 | sprintf(buffer, "IP :%-16s", ip4addr_ntoa(&info.ip)); 51 | st7735_drawstring(0, 3, buffer, ST7735_WHITE); 52 | 53 | sprintf(buffer, "Mask:%-16s", ip4addr_ntoa(&info.netmask)); 54 | st7735_drawstring(0, 4, buffer, ST7735_WHITE); 55 | 56 | sprintf(buffer, "GW :%-16s", ip4addr_ntoa(&info.gw)); 57 | st7735_drawstring(0, 5, buffer, ST7735_WHITE); 58 | } 59 | else 60 | { 61 | st7735_drawstring(0, 2, "Obtaining IP Address ", ST7735_WHITE); 62 | st7735_drawstring(0, 3, " ", ST7735_WHITE); 63 | st7735_drawstring(0, 4, " ", ST7735_WHITE); 64 | st7735_drawstring(0, 5, " ", ST7735_WHITE); 65 | } 66 | } 67 | 68 | static void 69 | print_page2(void) 70 | { 71 | imu_sensor_data_t raw, calibrated; 72 | imu_data_t data; 73 | char buffer[32]; 74 | imu_mode_t mode; 75 | 76 | imu_task_get_raw_and_data(&mode, &raw, &calibrated, &data); 77 | 78 | if(mode == imu_mode_normal) 79 | { 80 | st7735_drawstring(0, 0, "Page 2 ", ST7735_WHITE); 81 | 82 | sprintf(buffer, "Roll : %-5.2f", data.orientation[0]); 83 | st7735_drawstring(0, 1, buffer, ST7735_WHITE); 84 | 85 | sprintf(buffer, "Pitch: %-5.2f", data.orientation[1]); 86 | st7735_drawstring(0, 2, buffer, ST7735_WHITE); 87 | 88 | sprintf(buffer, "Yaw : %-5.2f", data.orientation[2]); 89 | st7735_drawstring(0, 3, buffer, ST7735_WHITE); 90 | } 91 | else 92 | { 93 | st7735_drawstring(0, 0, "Page 2 ", ST7735_WHITE); 94 | switch(mode) 95 | { 96 | case imu_mode_gyro_calibrating: 97 | st7735_drawstring(0, 1, "Calibrating Gyro ", ST7735_WHITE); 98 | break; 99 | 100 | case imu_mode_accel_calibrating: 101 | st7735_drawstring(0, 1, "Calibrating Accelero ", ST7735_WHITE); 102 | break; 103 | 104 | case imu_mode_mag_calibrating: 105 | st7735_drawstring(0, 1, "Calibrating Magneto ", ST7735_WHITE); 106 | break; 107 | 108 | default: 109 | st7735_drawstring(0, 1, "BUG................ ", ST7735_WHITE); 110 | break; 111 | } 112 | st7735_drawstring(0, 2, " ", ST7735_WHITE); 113 | st7735_drawstring(0, 3, " ", ST7735_WHITE); 114 | } 115 | } 116 | 117 | static void 118 | print_page3(void) 119 | { 120 | st7735_drawstring(0, 0, "Page 3 ", ST7735_WHITE); 121 | } 122 | 123 | static void 124 | lcd_driver_task(void *pvParameter) 125 | { 126 | uint32_t pin_num, 127 | page_num = 2; 128 | 129 | st7735_initr(INITR_144GREENTAB); 130 | st7735_fillscreen(ST7735_BLACK); 131 | 132 | st7735_setrotation(0) ; 133 | 134 | st7735_drawstring(0, 0, "Booting up... ", ST7735_WHITE); 135 | 136 | while(1) 137 | { 138 | switch(page_num) 139 | { 140 | case 1: 141 | print_page1(); 142 | break; 143 | 144 | case 2: 145 | print_page2(); 146 | break; 147 | 148 | case 3: 149 | print_page3(); 150 | break; 151 | } 152 | 153 | if(xQueueReceive(gpio_evt_queue, &pin_num, 500 / portTICK_PERIOD_MS)) 154 | { 155 | switch(pin_num) 156 | { 157 | case BUTTON_1: 158 | page_num = 1; 159 | break; 160 | 161 | case BUTTON_2: 162 | page_num = 2; 163 | break; 164 | 165 | case BUTTON_3: 166 | // page_num = 3; 167 | imu_task_do_mag_calibration(); 168 | break; 169 | } 170 | st7735_fillscreen(ST7735_BLACK); 171 | } 172 | 173 | } 174 | } 175 | 176 | void 177 | lcd_driver_init(void) 178 | { 179 | gpio_config_t io_conf; 180 | 181 | io_conf.intr_type = GPIO_PIN_INTR_NEGEDGE; 182 | io_conf.pin_bit_mask = BUTTON_PIN_SEL; 183 | io_conf.mode = GPIO_MODE_INPUT; 184 | io_conf.pull_down_en = 0; 185 | io_conf.pull_up_en = 0; 186 | gpio_config(&io_conf); 187 | 188 | gpio_install_isr_service(0); 189 | 190 | gpio_evt_queue = xQueueCreate(10, sizeof(uint32_t)); 191 | 192 | gpio_isr_handler_add(BUTTON_1, gpio_isr_handler, (void*)BUTTON_1); 193 | gpio_isr_handler_add(BUTTON_2, gpio_isr_handler, (void*)BUTTON_2); 194 | gpio_isr_handler_add(BUTTON_3, gpio_isr_handler, (void*)BUTTON_3); 195 | 196 | ESP_LOGI(TAG, "starting lcd driver"); 197 | 198 | xTaskCreate(lcd_driver_task, "lcd_driver_task", 4096, NULL, 5, NULL); 199 | } 200 | -------------------------------------------------------------------------------- /main/lcd_driver.h: -------------------------------------------------------------------------------- 1 | #ifndef __LCD_DRIVER_DEF_H__ 2 | #define __LCD_DRIVER_DEF_H__ 3 | 4 | extern void lcd_driver_init(void); 5 | 6 | #endif /* !__LCD_DRIVER_DEF_H__ */ 7 | -------------------------------------------------------------------------------- /main/madgwick.h: -------------------------------------------------------------------------------- 1 | #ifndef __MADGWICK_DEF_H__ 2 | #define __MADGWICK_DEF_H__ 3 | 4 | typedef struct 5 | { 6 | float sampleFreq; 7 | float invSampleFreq; 8 | float beta; 9 | float q0, q1, q2, q3; 10 | } madgwick_t; 11 | 12 | extern void madgwick_init(madgwick_t* madgwick, float sample_freq); 13 | extern void madgwick_updateIMU(madgwick_t* madgwick, 14 | float gx, float gy, float gz, 15 | float ax, float ay, float az); 16 | extern void madgwick_update(madgwick_t* madgwick, 17 | float gx, float gy, float gz, 18 | float ax, float ay, float az, 19 | float mx, float my, float mz); 20 | extern void madgwick_get_roll_pitch_yaw(madgwick_t* madgwick, float data[3], float mg); 21 | extern void madgwick_get_quaternion(madgwick_t* madgwick, float data[4]); 22 | 23 | #endif //!__MADGWICK_DEF_H__ 24 | -------------------------------------------------------------------------------- /main/mag_calibration.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "mag_calibration.h" 4 | #include "sensor_calib.h" 5 | 6 | static int32_t _mag_prev[3]; 7 | static int16_t _mag_offset[3]; 8 | 9 | static sensor_calib_t _cal_state; 10 | 11 | void 12 | mag_calibration_init(void) 13 | { 14 | _mag_prev[0] = 15 | _mag_prev[1] = 16 | _mag_prev[2] = 0; 17 | 18 | sensorCalibrationResetState(&_cal_state); 19 | } 20 | 21 | void 22 | mag_calibration_update(int16_t mx, int16_t my, int16_t mz) 23 | { 24 | float diffMag = 0; 25 | float avgMag = 0; 26 | int32_t mag_data[3]; 27 | 28 | mag_data[0] = mx; 29 | mag_data[1] = my; 30 | mag_data[2] = mz; 31 | 32 | for (int axis = 0; axis < 3; axis++) { 33 | diffMag += (mag_data[axis] - _mag_prev[axis]) * (mag_data[axis] - _mag_prev[axis]); 34 | avgMag += (mag_data[axis] + _mag_prev[axis]) * (mag_data[axis] + _mag_prev[axis]) / 4.0f; 35 | } 36 | 37 | // sqrtf(diffMag / avgMag) is a rough approximation of tangent of angle between magADC and _mag_prev. tan(8 deg) = 0.14 38 | if ((avgMag > 0.01f) && ((diffMag / avgMag) > (0.14f * 0.14f))) { 39 | sensorCalibrationPushSampleForOffsetCalculation(&_cal_state, mag_data); 40 | 41 | for (int axis = 0; axis < 3; axis++) { 42 | _mag_prev[axis] = mag_data[axis]; 43 | } 44 | } 45 | } 46 | 47 | void 48 | mag_calibration_finish(int16_t offsets[3]) 49 | { 50 | float magZerof[3]; 51 | 52 | sensorCalibrationSolveForOffset(&_cal_state, magZerof); 53 | 54 | for (int axis = 0; axis < 3; axis++) 55 | { 56 | _mag_offset[axis] = lrintf(magZerof[axis]); 57 | } 58 | 59 | offsets[0] = _mag_offset[0]; 60 | offsets[1] = _mag_offset[1]; 61 | offsets[2] = _mag_offset[2]; 62 | } 63 | -------------------------------------------------------------------------------- /main/mag_calibration.h: -------------------------------------------------------------------------------- 1 | #ifndef __MAG_CALIBRATION_DEF_H__ 2 | #define __MAG_CALIBRATION_DEF_H__ 3 | 4 | #include "common_def.h" 5 | 6 | extern void mag_calibration_init(void); 7 | extern void mag_calibration_update(int16_t mx, int16_t my, int16_t mz); 8 | extern void mag_calibration_finish(int16_t offsets[3]); 9 | 10 | #endif /* !__MAG_CALIBRATION_DEF_H__ */ 11 | -------------------------------------------------------------------------------- /main/mahony.h: -------------------------------------------------------------------------------- 1 | #ifndef __MAHONY_DEF_H__ 2 | #define __MAHONY_DEF_H__ 3 | 4 | typedef struct 5 | { 6 | float twoKp; // 2 * proportional gain (Kp) 7 | float twoKi; // 2 * integral gain (Ki) 8 | float q0, q1, q2, q3; // quaternion of sensor frame relative to auxiliary frame 9 | float integralFBx, integralFBy, integralFBz; // integral error terms scaled by Ki 10 | float invSampleFreq; 11 | } mahony_t; 12 | 13 | extern void mahony_init(mahony_t* mahony, float sampleFrequency); 14 | extern void mahony_updateIMU(mahony_t* mahony, float gx, float gy, float gz, 15 | float ax, float ay, float az); 16 | extern void mahony_update(mahony_t* mahony, 17 | float gx, float gy, float gz, 18 | float ax, float ay, float az, 19 | float mx, float my, float mz); 20 | extern void mahony_get_roll_pitch_yaw(mahony_t* mahony, float data[3], float md); 21 | extern void mahony_get_quaternion(mahony_t* mahony, float data[4]); 22 | 23 | #endif //!__MAHONY_DEF_H__ 24 | -------------------------------------------------------------------------------- /main/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "freertos/FreeRTOS.h" 3 | #include "freertos/task.h" 4 | #include "driver/gpio.h" 5 | #include "nvs_flash.h" 6 | #include "sdkconfig.h" 7 | 8 | #include "blinky.h" 9 | #include "app_wifi.h" 10 | #include "imu_task.h" 11 | #include "shell.h" 12 | #include "lcd_driver.h" 13 | #include "webserver.h" 14 | 15 | void app_main() 16 | { 17 | esp_err_t ret = nvs_flash_init(); 18 | 19 | if(ret == ESP_ERR_NVS_NO_FREE_PAGES) { 20 | ESP_ERROR_CHECK(nvs_flash_erase()); 21 | ret = nvs_flash_init(); 22 | } 23 | 24 | ESP_ERROR_CHECK(ret); 25 | 26 | app_wifi_init(); 27 | blinky_init(); 28 | imu_task_init(); 29 | lcd_driver_init(); 30 | shell_init(); 31 | webserver_init(); 32 | } 33 | -------------------------------------------------------------------------------- /main/math_helper.h: -------------------------------------------------------------------------------- 1 | #ifndef __MATH_HELPER_DEF_H__ 2 | #define __MATH_HELPER_DEF_H__ 3 | 4 | #define M_PIf 3.14159265358979323846f 5 | #define M_LN2f 0.69314718055994530942f 6 | #define M_Ef 2.71828182845904523536f 7 | 8 | #define RAD (M_PIf / 180.0f) 9 | 10 | #define F_EPSILON 0.000000001f 11 | 12 | typedef struct 13 | { 14 | double x; 15 | double y; 16 | double z; 17 | } VectorDouble; 18 | 19 | typedef struct 20 | { 21 | int16_t x; 22 | int16_t y; 23 | int16_t z; 24 | } VectorInt16; 25 | 26 | typedef struct 27 | { 28 | float x; 29 | float y; 30 | float z; 31 | } VectorFloat; 32 | 33 | #if 0 // original 34 | static inline float 35 | invSqrt(float x) 36 | { 37 | float halfx = 0.5f * x; 38 | float y = x; 39 | long i = *(long*)&y; 40 | 41 | i = 0x5f3759df - (i>>1); 42 | y = *(float*)&i; 43 | y = y * (1.5f - (halfx * y * y)); 44 | y = y * (1.5f - (halfx * y * y)); 45 | return y; 46 | 47 | } 48 | #else 49 | typedef union 50 | { 51 | float f; 52 | long l; 53 | } float_long_t; 54 | 55 | /* 56 | static inline float 57 | invSqrt(float x) 58 | { 59 | float halfx = 0.5f * x; 60 | float_long_t y; 61 | float_long_t i; 62 | 63 | y.f = x; 64 | i = y; 65 | 66 | i.l = 0x5f3759df - (i.l>>1); 67 | y = i; 68 | y.f = y.f * (1.5f - (halfx * y.f * y.f)); 69 | y.f = y.f * (1.5f - (halfx * y.f * y.f)); 70 | return y.f; 71 | } 72 | */ 73 | float invSqrt(float x) { 74 | float halfx = 0.5f * x; 75 | float y = x; 76 | long i = *(long*)&y; 77 | i = 0x5f3759df - (i>>1); 78 | y = *(float*)&i; 79 | y = y * (1.5f - (halfx * y * y)); 80 | y = y * (1.5f - (halfx * y * y)); 81 | return y; 82 | } 83 | #endif 84 | 85 | static inline bool 86 | float_zero(float x) 87 | { 88 | if(fabs(x) < F_EPSILON) 89 | { 90 | return true; 91 | } 92 | return false; 93 | } 94 | 95 | #endif //!__MATH_HELPER_DEF_H__ 96 | -------------------------------------------------------------------------------- /main/mpu9250.c: -------------------------------------------------------------------------------- 1 | #include "mpu9250.h" 2 | #include "mpu9250_i2c.h" 3 | #include "esp_log.h" 4 | #include "sdkconfig.h" 5 | 6 | const static char* TAG = "mpu9250"; 7 | 8 | static const float _accel_lsbs[] = 9 | { 10 | 1.0f / MPU9250_ACCE_SENS_2, 11 | 1.0f / MPU9250_ACCE_SENS_4, 12 | 1.0f / MPU9250_ACCE_SENS_8, 13 | 1.0f / MPU9250_ACCE_SENS_16, 14 | }; 15 | 16 | static const float _gyro_lsbs[] = 17 | { 18 | 1.0f / MPU9250_GYRO_SENS_250, 19 | 1.0f / MPU9250_GYRO_SENS_500, 20 | 1.0f / MPU9250_GYRO_SENS_1000, 21 | 1.0f / MPU9250_GYRO_SENS_2000, 22 | }; 23 | 24 | //////////////////////////////////////////////////////////////////////////////// 25 | // 26 | // private utilities 27 | // 28 | //////////////////////////////////////////////////////////////////////////////// 29 | static inline void 30 | mpu9250_write_reg(uint8_t reg, uint8_t data) 31 | { 32 | uint8_t buffer[2]; 33 | 34 | buffer[0] = reg; 35 | buffer[1] = data; 36 | 37 | if(mpu9250_i2c_write(MPU9250_I2C_ADDR, buffer, 2) == FALSE) 38 | { 39 | ESP_LOGE(TAG, "mpu9250_write_reg: failed to mpu9250_i2c_write"); 40 | } 41 | } 42 | 43 | static inline void 44 | mpu9250_write_reg16(uint8_t reg, uint16_t data) 45 | { 46 | uint8_t buffer[3]; 47 | 48 | buffer[0] = reg; 49 | buffer[1] = (data >> 8 ) & 0xff; 50 | buffer[2] = data & 0xff; 51 | 52 | if(mpu9250_i2c_write(MPU9250_I2C_ADDR, buffer, 3) == FALSE) 53 | { 54 | ESP_LOGE(TAG, "mpu9250_write_reg16: failed to mpu9250_i2c_write"); 55 | } 56 | } 57 | 58 | static inline uint8_t 59 | mpu9250_read_reg(uint8_t reg) 60 | { 61 | uint8_t ret; 62 | 63 | if(mpu9250_i2c_write(MPU9250_I2C_ADDR, ®, 1) == FALSE) 64 | { 65 | ESP_LOGE(TAG, "mpu9250_read_reg: failed to mpu9250_i2c_write"); 66 | } 67 | 68 | 69 | if(mpu9250_i2c_read(MPU9250_I2C_ADDR, &ret, 1) == FALSE) 70 | { 71 | ESP_LOGE(TAG, "mpu9250_read_reg: failed to mpu9250_i2c_read"); 72 | } 73 | 74 | return ret; 75 | } 76 | 77 | static inline void 78 | mpu9250_read_data(uint8_t reg, uint8_t* data, uint8_t len) 79 | { 80 | if(mpu9250_i2c_write(MPU9250_I2C_ADDR, ®, 1) == FALSE) 81 | { 82 | ESP_LOGE(TAG, "mpu9250_read_data: failed to mpu9250_i2c_write"); 83 | } 84 | 85 | if(mpu9250_i2c_read(MPU9250_I2C_ADDR, data, len) == FALSE) 86 | { 87 | ESP_LOGE(TAG, "mpu9250_read_data: failed to mpu9250_i2c_read"); 88 | } 89 | } 90 | 91 | static inline uint8_t 92 | ak8963_read_reg(uint8_t reg) 93 | { 94 | uint8_t ret; 95 | 96 | if(mpu9250_i2c_write(AK8963_I2C_ADDR, ®, 1) == FALSE) 97 | { 98 | ESP_LOGE(TAG, "ak8963_read_reg: failed to mpu9250_i2c_write"); 99 | } 100 | 101 | if(mpu9250_i2c_read(AK8963_I2C_ADDR, &ret, 1) == FALSE) 102 | { 103 | ESP_LOGE(TAG, "ak8963_read_reg: failed to mpu9250_i2c_read"); 104 | } 105 | return ret; 106 | } 107 | 108 | static inline void 109 | ak8963_write_reg(uint8_t reg, uint8_t data) 110 | { 111 | uint8_t buffer[2]; 112 | 113 | buffer[0] = reg; 114 | buffer[1] = data; 115 | 116 | if(mpu9250_i2c_write(AK8963_I2C_ADDR, buffer, 2) == FALSE) 117 | { 118 | ESP_LOGE(TAG, "ak8963_write_reg: failed to mpu9250_i2c_write"); 119 | } 120 | } 121 | 122 | static inline void 123 | ak8963_read_data(uint8_t reg, uint8_t* data, uint8_t len) 124 | { 125 | if(mpu9250_i2c_write(AK8963_I2C_ADDR, ®, 1) == FALSE) 126 | { 127 | ESP_LOGE(TAG, "ak8963_read_data: failed to mpu9250_i2c_write"); 128 | } 129 | 130 | if(mpu9250_i2c_read(AK8963_I2C_ADDR, data, len) == FALSE) 131 | { 132 | ESP_LOGE(TAG, "ak8963_read_data: failed to mpu9250_i2c_read"); 133 | } 134 | } 135 | 136 | static void 137 | ak8963_init(mpu9250_t* mpu9250) 138 | { 139 | uint8_t v; 140 | 141 | v = ak8963_read_reg(AK8963_WIA); 142 | ESP_LOGI(TAG, "ak8963 chip ID: %x", v); 143 | 144 | // put ak8963 in mode 2 for 100Hz measurement 145 | // also set 16 bit output 146 | v = ((1 << 4) | 0x06); 147 | ak8963_write_reg(AK8963_CNTL1, v); 148 | 149 | v = ak8963_read_reg(AK8963_CNTL1); 150 | ESP_LOGI(TAG, "ak8963 control reg: %x", v); 151 | } 152 | 153 | static void 154 | ak8963_read_all(imu_sensor_data_t* imu) 155 | { 156 | uint8_t data[7]; 157 | 158 | ak8963_read_data(AK8963_HXL, data, 7); 159 | 160 | imu->mag[0] = (int16_t)(data[1] << 8 | data[0]); 161 | imu->mag[1] = (int16_t)(data[3] << 8 | data[2]); 162 | imu->mag[2] = (int16_t)(data[5] << 8 | data[4]); 163 | } 164 | 165 | //////////////////////////////////////////////////////////////////////////////// 166 | // 167 | // public utilities 168 | // 169 | //////////////////////////////////////////////////////////////////////////////// 170 | void 171 | mpu9250_init(mpu9250_t* mpu9250, 172 | MPU9250_Accelerometer_t accel_sensitivity, 173 | MPU9250_Gyroscope_t gyro_sensitivity, 174 | imu_raw_to_real_t* lsb) 175 | { 176 | mpu9250_i2c_init(); 177 | 178 | mpu9250->accel_config = accel_sensitivity; 179 | mpu9250->gyro_config = gyro_sensitivity; 180 | 181 | uint8_t temp; 182 | 183 | /* Wakeup MPU6050 */ 184 | mpu9250_write_reg(MPU9250_PWR_MGMT_1, 0x00); 185 | 186 | /* Config accelerometer */ 187 | temp = mpu9250_read_reg(MPU9250_ACCEL_CONFIG); 188 | temp = (temp & 0xE7) | (uint8_t)accel_sensitivity << 3; 189 | mpu9250_write_reg(MPU9250_ACCEL_CONFIG, temp); 190 | 191 | /* Config gyroscope */ 192 | temp = mpu9250_read_reg(MPU9250_GYRO_CONFIG); 193 | temp = (temp & 0xE7) | (uint8_t)gyro_sensitivity << 3; 194 | mpu9250_write_reg(MPU9250_GYRO_CONFIG, temp); 195 | 196 | // enable bypass mode to access AK8963 197 | mpu9250_write_reg(55, 0x02); 198 | 199 | ak8963_init(mpu9250); 200 | 201 | lsb->accel_lsb = _accel_lsbs[accel_sensitivity]; 202 | lsb->gyro_lsb = _gyro_lsbs[gyro_sensitivity]; 203 | lsb->mag_lsb = AK8963_MAG_LSB; 204 | } 205 | 206 | bool 207 | mpu9250_read_gyro_accel(mpu9250_t* mpu9250, imu_sensor_data_t* imu) 208 | { 209 | uint8_t data[14]; 210 | 211 | // read full raw data 212 | mpu9250_read_data(MPU9250_ACCEL_XOUT_H, data, 14); 213 | 214 | imu->accel[0] = (int16_t)(data[0] << 8 | data[1]); 215 | imu->accel[1] = (int16_t)(data[2] << 8 | data[3]); 216 | imu->accel[2] = (int16_t)(data[4] << 8 | data[5]); 217 | 218 | imu->temp = (data[6] << 8 | data[7]); 219 | 220 | imu->gyro[0] = (int16_t)(data[8] << 8 | data[9]); 221 | imu->gyro[1] = (int16_t)(data[10] << 8 | data[11]); 222 | imu->gyro[2] = (int16_t)(data[12] << 8 | data[13]); 223 | 224 | return TRUE; 225 | } 226 | 227 | bool 228 | mpu9250_read_mag(mpu9250_t* mpu9250, imu_sensor_data_t* imu) 229 | { 230 | ak8963_read_all(imu); 231 | return TRUE; 232 | } 233 | 234 | bool 235 | mpu9250_read_all(mpu9250_t* mpu9250, imu_sensor_data_t* imu) 236 | { 237 | uint8_t data[14]; 238 | 239 | // read full raw data 240 | mpu9250_read_data(MPU9250_ACCEL_XOUT_H, data, 14); 241 | 242 | imu->accel[0] = (int16_t)(data[0] << 8 | data[1]); 243 | imu->accel[1] = (int16_t)(data[2] << 8 | data[3]); 244 | imu->accel[2] = (int16_t)(data[4] << 8 | data[5]); 245 | 246 | imu->temp = (data[6] << 8 | data[7]); 247 | 248 | imu->gyro[0] = (int16_t)(data[8] << 8 | data[9]); 249 | imu->gyro[1] = (int16_t)(data[10] << 8 | data[11]); 250 | imu->gyro[2] = (int16_t)(data[12] << 8 | data[13]); 251 | 252 | ak8963_read_all(imu); 253 | 254 | return TRUE; 255 | } 256 | 257 | /* 258 | void 259 | mpu9250_convert_to_eng_units(mpu9250_t* mpu9250, imu_sensor_data_t* imu) 260 | { 261 | imu->accel[0] = imu->accel_raw[0] * mpu9250->accel_lsb; 262 | imu->accel[1] = imu->accel_raw[1] * mpu9250->accel_lsb; 263 | imu->accel[2] = imu->accel_raw[2] * mpu9250->accel_lsb; 264 | 265 | imu->temp = (imu->temp_raw / 340333.87f + 21.0f); 266 | 267 | imu->gyro[0] = imu->gyro_raw[0] * mpu9250->gyro_lsb; 268 | imu->gyro[1] = imu->gyro_raw[1] * mpu9250->gyro_lsb; 269 | imu->gyro[2] = imu->gyro_raw[2] * mpu9250->gyro_lsb; 270 | 271 | imu->mag[0] = imu->mag_raw[0] * mpu9250->mag_lsb; 272 | imu->mag[1] = imu->mag_raw[1] * mpu9250->mag_lsb; 273 | imu->mag[2] = imu->mag_raw[2] * mpu9250->mag_lsb; 274 | } 275 | */ 276 | -------------------------------------------------------------------------------- /main/mpu9250.h: -------------------------------------------------------------------------------- 1 | #ifndef __MPU_9250_DEF_H__ 2 | #define __MPU_9250_DEF_H__ 3 | 4 | #include "common_def.h" 5 | #include "imu.h" 6 | 7 | //////////////////////////////////////////////////////////////////////////////// 8 | // 9 | // XXX refer to page 38 of MPU9250 Product specification 10 | // for accel/gyro/mag orientation 11 | // 12 | // 13 | // chip orientation mark: top left 14 | // 15 | // accel/gyro 16 | // X : left positive, counter clock 17 | // y : forward positive, counter clock 18 | // Z : up positive, counter clock 19 | // 20 | // mag 21 | // x : forward positive 22 | // y : left positive 23 | // z : down positive 24 | // 25 | //////////////////////////////////////////////////////////////////////////////// 26 | 27 | #define MPU9250_I2C_ADDR 0x68 // or 110 100x. 400Khz interface 28 | 29 | /* MPU9250 registers */ 30 | #define MPU9250_AUX_VDDIO 0x01 31 | #define MPU9250_SMPLRT_DIV 0x19 32 | #define MPU9250_REG_ACCEL_XOFFS_H (0x06) 33 | #define MPU9250_REG_ACCEL_XOFFS_L (0x07) 34 | #define MPU9250_REG_ACCEL_YOFFS_H (0x08) 35 | #define MPU9250_REG_ACCEL_YOFFS_L (0x09) 36 | #define MPU9250_REG_ACCEL_ZOFFS_H (0x0A) 37 | #define MPU9250_REG_ACCEL_ZOFFS_L (0x0B) 38 | #define MPU9250_REG_GYRO_XOFFS_H (0x13) 39 | #define MPU9250_REG_GYRO_XOFFS_L (0x14) 40 | #define MPU9250_REG_GYRO_YOFFS_H (0x15) 41 | #define MPU9250_REG_GYRO_YOFFS_L (0x16) 42 | #define MPU9250_REG_GYRO_ZOFFS_H (0x17) 43 | #define MPU9250_REG_GYRO_ZOFFS_L (0x18) 44 | #define MPU9250_CONFIG 0x1A 45 | #define MPU9250_GYRO_CONFIG 0x1B 46 | #define MPU9250_ACCEL_CONFIG 0x1C 47 | #define MPU9250_MOTION_THRESH 0x1F 48 | #define MPU9250_INT_PIN_CFG 0x37 49 | #define MPU9250_INT_ENABLE 0x38 50 | #define MPU9250_INT_STATUS 0x3A 51 | #define MPU9250_ACCEL_XOUT_H 0x3B 52 | #define MPU9250_ACCEL_XOUT_L 0x3C 53 | #define MPU9250_ACCEL_YOUT_H 0x3D 54 | #define MPU9250_ACCEL_YOUT_L 0x3E 55 | #define MPU9250_ACCEL_ZOUT_H 0x3F 56 | #define MPU9250_ACCEL_ZOUT_L 0x40 57 | #define MPU9250_TEMP_OUT_H 0x41 58 | #define MPU9250_TEMP_OUT_L 0x42 59 | #define MPU9250_GYRO_XOUT_H 0x43 60 | #define MPU9250_GYRO_XOUT_L 0x44 61 | #define MPU9250_GYRO_YOUT_H 0x45 62 | #define MPU9250_GYRO_YOUT_L 0x46 63 | #define MPU9250_GYRO_ZOUT_H 0x47 64 | #define MPU9250_GYRO_ZOUT_L 0x48 65 | #define MPU9250_MOT_DETECT_STATUS 0x61 66 | #define MPU9250_SIGNAL_PATH_RESET 0x68 67 | #define MPU9250_MOT_DETECT_CTRL 0x69 68 | #define MPU9250_USER_CTRL 0x6A 69 | #define MPU9250_PWR_MGMT_1 0x6B 70 | #define MPU9250_PWR_MGMT_2 0x6C 71 | #define MPU9250_FIFO_COUNTH 0x72 72 | #define MPU9250_FIFO_COUNTL 0x73 73 | #define MPU9250_FIFO_R_W 0x74 74 | #define MPU9250_WHO_AM_I 0x75 75 | 76 | /* Gyro sensitivities in °/s */ 77 | #define MPU9250_GYRO_SENS_250 ((float) 131) 78 | #define MPU9250_GYRO_SENS_500 ((float) 65.5) 79 | #define MPU9250_GYRO_SENS_1000 ((float) 32.8) 80 | #define MPU9250_GYRO_SENS_2000 ((float) 16.4) 81 | 82 | /* Acce sensitivities in g */ 83 | #define MPU9250_ACCE_SENS_2 ((float) 16384) 84 | #define MPU9250_ACCE_SENS_4 ((float) 8192) 85 | #define MPU9250_ACCE_SENS_8 ((float) 4096) 86 | #define MPU9250_ACCE_SENS_16 ((float) 2048) 87 | 88 | #define AK8963_WIA 0x00 89 | #define AK8963_INFO 0x01 90 | #define AK8963_ST1 0x02 91 | #define AK8963_HXL 0x03 92 | #define AK8963_HXH 0x04 93 | #define AK8963_HYL 0x05 94 | #define AK8963_HYH 0x06 95 | #define AK8963_HZL 0x07 96 | #define AK8963_HZH 0x08 97 | #define AK8963_ST2 0x09 98 | #define AK8963_CNTL1 0x0a 99 | #define AK8963_ASTC 0x0c 100 | 101 | #define AK8963_I2C_ADDR 0x0c 102 | #define AK8963_MAG_LSB 0.15f // in 16 bit mode, 0.15uT per LSB 103 | 104 | typedef enum 105 | { 106 | MPU9250_Accelerometer_2G = 0x00, /*!< Range is +- 2G */ 107 | MPU9250_Accelerometer_4G = 0x01, /*!< Range is +- 4G */ 108 | MPU9250_Accelerometer_8G = 0x02, /*!< Range is +- 8G */ 109 | MPU9250_Accelerometer_16G = 0x03 /*!< Range is +- 16G */ 110 | } MPU9250_Accelerometer_t; 111 | 112 | typedef enum 113 | { 114 | MPU9250_Gyroscope_250s = 0x00, /*!< Range is +- 250 degrees/s */ 115 | MPU9250_Gyroscope_500s = 0x01, /*!< Range is +- 500 degrees/s */ 116 | MPU9250_Gyroscope_1000s = 0x02, /*!< Range is +- 1000 degrees/s */ 117 | MPU9250_Gyroscope_2000s = 0x03 /*!< Range is +- 2000 degrees/s */ 118 | } MPU9250_Gyroscope_t; 119 | 120 | typedef struct 121 | { 122 | MPU9250_Accelerometer_t accel_config; 123 | MPU9250_Gyroscope_t gyro_config; 124 | } mpu9250_t; 125 | 126 | extern void mpu9250_init(mpu9250_t* mpu9250, 127 | MPU9250_Accelerometer_t accel_sensitivity, 128 | MPU9250_Gyroscope_t gyro_sensitivity, 129 | imu_raw_to_real_t* lsb); 130 | 131 | extern bool mpu9250_read_all(mpu9250_t* mpu9250, imu_sensor_data_t* data); 132 | extern bool mpu9250_read_mag(mpu9250_t* mpu9250, imu_sensor_data_t* imu); 133 | extern bool mpu9250_read_gyro_accel(mpu9250_t* mpu9250, imu_sensor_data_t* imu); 134 | 135 | #endif /* !__MPU_9250_DEF_H__ */ 136 | -------------------------------------------------------------------------------- /main/mpu9250_i2c.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "driver/i2c.h" 3 | #include "mpu9250_i2c.h" 4 | 5 | #define WRITE_BIT I2C_MASTER_WRITE /*!< I2C master write */ 6 | #define READ_BIT I2C_MASTER_READ /*!< I2C master read */ 7 | #define ACK_CHECK_EN 0x1 /*!< I2C master will check ack from slave*/ 8 | #define ACK_CHECK_DIS 0x0 /*!< I2C master will not check ack from slave */ 9 | #define ACK_VAL 0x0 /*!< I2C ack value */ 10 | #define NACK_VAL 0x1 /*!< I2C nack value */ 11 | 12 | void 13 | mpu9250_i2c_init(void) 14 | { 15 | i2c_config_t conf; 16 | 17 | conf.mode = I2C_MODE_MASTER; 18 | conf.sda_io_num = MPU9250_I2C_MASTER_SDA_IO; 19 | conf.sda_pullup_en = GPIO_PULLUP_DISABLE; 20 | conf.scl_io_num = MPU9250_I2C_MASTER_SCL_IO; 21 | conf.scl_pullup_en = GPIO_PULLUP_DISABLE; 22 | conf.master.clk_speed = MPU9250_I2C_CLK_FREQ; 23 | 24 | i2c_param_config(MPU9250_I2C_NUM, &conf); 25 | 26 | i2c_driver_install(MPU9250_I2C_NUM, conf.mode, 27 | MPU9250_I2C_RX_BUFFER_DISABLE, 28 | MPU9250_I2C_TX_BUFFER_DISABLE, 0); 29 | 30 | } 31 | 32 | bool 33 | mpu9250_i2c_read(uint8_t addr, uint8_t* data, uint32_t size) 34 | { 35 | i2c_cmd_handle_t cmd = i2c_cmd_link_create(); 36 | 37 | i2c_master_start(cmd); 38 | i2c_master_write_byte(cmd, (addr << 1) | READ_BIT, ACK_CHECK_EN); 39 | if(size > 1) 40 | { 41 | i2c_master_read(cmd, data, size - 1, ACK_VAL); 42 | } 43 | i2c_master_read_byte(cmd, &data[size-1], NACK_VAL); 44 | i2c_master_stop(cmd); 45 | 46 | esp_err_t ret = i2c_master_cmd_begin(MPU9250_I2C_NUM, cmd, 1000 / portTICK_RATE_MS); 47 | i2c_cmd_link_delete(cmd); 48 | 49 | if(ret == ESP_OK) 50 | { 51 | return TRUE; 52 | } 53 | return FALSE; 54 | } 55 | 56 | bool 57 | mpu9250_i2c_write(uint8_t addr, uint8_t* data, uint32_t size) 58 | { 59 | i2c_cmd_handle_t cmd = i2c_cmd_link_create(); 60 | 61 | i2c_master_start(cmd); 62 | i2c_master_write_byte(cmd, ( addr << 1 ) | WRITE_BIT, ACK_CHECK_EN); 63 | i2c_master_write(cmd, data, size, ACK_CHECK_EN); 64 | i2c_master_stop(cmd); 65 | 66 | esp_err_t ret = i2c_master_cmd_begin(MPU9250_I2C_NUM, cmd, 1000 / portTICK_RATE_MS); 67 | i2c_cmd_link_delete(cmd); 68 | 69 | if(ret == ESP_OK) 70 | { 71 | return TRUE; 72 | } 73 | return FALSE; 74 | } 75 | -------------------------------------------------------------------------------- /main/mpu9250_i2c.h: -------------------------------------------------------------------------------- 1 | #ifndef __MPU9250_I2C_DEF_H__ 2 | #define __MPU9250_I2C_DEF_H__ 3 | 4 | #include "common_def.h" 5 | 6 | #define MPU9250_I2C_NUM I2C_NUM_1 7 | #define MPU9250_I2C_MASTER_SDA_IO 19 8 | #define MPU9250_I2C_MASTER_SCL_IO 18 9 | #define MPU9250_I2C_CLK_FREQ 400000 10 | 11 | #define MPU9250_I2C_RX_BUFFER_DISABLE 0 12 | #define MPU9250_I2C_TX_BUFFER_DISABLE 0 13 | 14 | extern void mpu9250_i2c_init(void); 15 | extern bool mpu9250_i2c_read(uint8_t addr, uint8_t* data, uint32_t size); 16 | extern bool mpu9250_i2c_write(uint8_t addr, uint8_t* data, uint32_t size); 17 | 18 | #endif /* !__MPU9250_I2C_DEF_H__ */ 19 | -------------------------------------------------------------------------------- /main/sensor_calib.c: -------------------------------------------------------------------------------- 1 | /* 2 | * copied from iNav 3 | */ 4 | #include 5 | 6 | #include "sensor_calib.h" 7 | 8 | void sensorCalibrationResetState(sensor_calib_t * state) 9 | { 10 | int i, j; 11 | 12 | for(i = 0; i < 4; i++){ 13 | for(j = 0; j < 4; j++){ 14 | state->XtX[i][j] = 0; 15 | } 16 | state->XtY[i] = 0; 17 | } 18 | } 19 | 20 | void sensorCalibrationPushSampleForOffsetCalculation(sensor_calib_t * state, int32_t sample[3]) 21 | { 22 | state->XtX[0][0] += (float)sample[0] * sample[0]; 23 | state->XtX[0][1] += (float)sample[0] * sample[1]; 24 | state->XtX[0][2] += (float)sample[0] * sample[2]; 25 | state->XtX[0][3] += (float)sample[0]; 26 | 27 | state->XtX[1][0] += (float)sample[1] * sample[0]; 28 | state->XtX[1][1] += (float)sample[1] * sample[1]; 29 | state->XtX[1][2] += (float)sample[1] * sample[2]; 30 | state->XtX[1][3] += (float)sample[1]; 31 | 32 | state->XtX[2][0] += (float)sample[2] * sample[0]; 33 | state->XtX[2][1] += (float)sample[2] * sample[1]; 34 | state->XtX[2][2] += (float)sample[2] * sample[2]; 35 | state->XtX[2][3] += (float)sample[2]; 36 | 37 | state->XtX[3][0] += (float)sample[0]; 38 | state->XtX[3][1] += (float)sample[1]; 39 | state->XtX[3][2] += (float)sample[2]; 40 | state->XtX[3][3] += 1; 41 | 42 | float squareSum = ((float)sample[0] * sample[0]) + ((float)sample[1] * sample[1]) + ((float)sample[2] * sample[2]); 43 | 44 | state->XtY[0] += sample[0] * squareSum; 45 | state->XtY[1] += sample[1] * squareSum; 46 | state->XtY[2] += sample[2] * squareSum; 47 | state->XtY[3] += squareSum; 48 | } 49 | 50 | void sensorCalibrationPushSampleForScaleCalculation(sensor_calib_t * state, int axis, int32_t sample[3], int target) 51 | { 52 | int i; 53 | 54 | for (i = 0; i < 3; i++) { 55 | float scaledSample = (float)sample[i] / (float)target; 56 | state->XtX[axis][i] += scaledSample * scaledSample; 57 | state->XtX[3][i] += scaledSample * scaledSample; 58 | } 59 | 60 | state->XtX[axis][3] += 1; 61 | state->XtY[axis] += 1; 62 | state->XtY[3] += 1; 63 | } 64 | 65 | static void sensorCalibration_gaussLR(float mat[4][4]) 66 | { 67 | uint8_t n = 4; 68 | int i, j, k; 69 | for (i = 0; i < 4; i++) { 70 | // Determine R 71 | for (j = i; j < 4; j++) { 72 | for (k = 0; k < i; k++) { 73 | mat[i][j] -= mat[i][k] * mat[k][j]; 74 | } 75 | } 76 | // Determine L 77 | for (j = i + 1; j < n; j++) { 78 | for (k = 0; k < i; k++) { 79 | mat[j][i] -= mat[j][k] * mat[k][i]; 80 | } 81 | mat[j][i] /= mat[i][i]; 82 | } 83 | } 84 | } 85 | 86 | void sensorCalibration_ForwardSubstitution(float LR[4][4], float y[4], float b[4]) 87 | { 88 | int i, k; 89 | for (i = 0; i < 4; ++i) { 90 | y[i] = b[i]; 91 | for (k = 0; k < i; ++k) { 92 | y[i] -= LR[i][k] * y[k]; 93 | } 94 | //y[i] /= MAT_ELEM_AT(LR,i,i); //Do not use, LR(i,i) is 1 anyways and not stored in this matrix 95 | } 96 | } 97 | 98 | void sensorCalibration_BackwardSubstitution(float LR[4][4], float x[4], float y[4]) 99 | { 100 | int i, k; 101 | for (i = 3 ; i >= 0; --i) { 102 | x[i] = y[i]; 103 | for (k = i + 1; k < 4; ++k) { 104 | x[i] -= LR[i][k] * x[k]; 105 | } 106 | x[i] /= LR[i][i]; 107 | } 108 | } 109 | 110 | // solve linear equation 111 | // https://en.wikipedia.org/wiki/Gaussian_elimination 112 | static void sensorCalibration_SolveLGS(float A[4][4], float x[4], float b[4]) 113 | { 114 | int i; 115 | float y[4]; 116 | 117 | sensorCalibration_gaussLR(A); 118 | 119 | for (i = 0; i < 4; ++i) { 120 | y[i] = 0; 121 | } 122 | 123 | sensorCalibration_ForwardSubstitution(A, y, b); 124 | sensorCalibration_BackwardSubstitution(A, x, y); 125 | } 126 | 127 | void sensorCalibrationSolveForOffset(sensor_calib_t * state, float result[3]) 128 | { 129 | float beta[4]; 130 | int i; 131 | 132 | sensorCalibration_SolveLGS(state->XtX, beta, state->XtY); 133 | 134 | for (i = 0; i < 3; i++) { 135 | result[i] = beta[i] / 2; 136 | } 137 | } 138 | 139 | void sensorCalibrationSolveForScale(sensor_calib_t * state, float result[3]) 140 | { 141 | float beta[4]; 142 | int i; 143 | sensorCalibration_SolveLGS(state->XtX, beta, state->XtY); 144 | 145 | for (i = 0; i < 3; i++) { 146 | result[i] = sqrtf(beta[i]); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /main/sensor_calib.h: -------------------------------------------------------------------------------- 1 | #ifndef __SENSOR_CALIB_DEF_H__ 2 | #define __SENSOR_CALIB_DEF_H__ 3 | 4 | #include "common_def.h" 5 | 6 | /** 7 | * 8 | * Sensor offset calculation code based on Freescale's AN4246 9 | * 10 | */ 11 | 12 | typedef struct { 13 | float XtY[4]; 14 | float XtX[4][4]; 15 | } sensor_calib_t; 16 | 17 | void sensorCalibrationResetState(sensor_calib_t * state); 18 | void sensorCalibrationPushSampleForOffsetCalculation(sensor_calib_t * state, int32_t sample[3]); 19 | void sensorCalibrationPushSampleForScaleCalculation(sensor_calib_t * state, int axis, int32_t sample[3], int target); 20 | void sensorCalibrationSolveForOffset(sensor_calib_t * state, float result[3]); 21 | void sensorCalibrationSolveForScale(sensor_calib_t * state, float result[3]); 22 | 23 | #endif /* !__SENSOR_CALIB_DEF_H__ */ 24 | -------------------------------------------------------------------------------- /main/shell.h: -------------------------------------------------------------------------------- 1 | #ifndef __SHELL_DEF_H__ 2 | #define __SHELL_DEF_H__ 3 | 4 | extern void shell_init(void); 5 | 6 | #endif /* !__SHELL_DEF_H__ */ 7 | -------------------------------------------------------------------------------- /main/st7735.h: -------------------------------------------------------------------------------- 1 | #ifndef __ST7735_DEF_H__ 2 | #define __ST7735_DEF_H__ 3 | 4 | enum initRFlags 5 | { 6 | none, 7 | INITR_GREENTAB, 8 | INITR_REDTAB, 9 | INITR_BLACKTAB, 10 | INITR_144GREENTAB 11 | }; 12 | 13 | #define ST7735_TFTWIDTH 128 14 | #define ST7735_TFTHEIGHT 128 15 | 16 | 17 | // Color definitions 18 | #define ST7735_BLACK 0x0000 19 | #define ST7735_BLUE 0x001F 20 | #define ST7735_RED 0xF800 21 | #define ST7735_GREEN 0x07E0 22 | #define ST7735_CYAN 0x07FF 23 | #define ST7735_MAGENTA 0xF81F 24 | #define ST7735_YELLOW 0xFFE0 25 | #define ST7735_WHITE 0xFFFF 26 | 27 | void st7735_initb(void); 28 | void st7735_initr(enum initRFlags option); 29 | void st7735_drawpixel(int16_t x, int16_t y, uint16_t color); 30 | void st7735_drawfastvline(int16_t x, int16_t y, int16_t h, uint16_t color); 31 | void st7735_drawfasthline(int16_t x, int16_t y, int16_t w, uint16_t color); 32 | void st7735_fillscreen(uint16_t color); 33 | void st7735_fillrect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color); 34 | uint16_t st7735_color565(uint8_t r, uint8_t g, uint8_t b); 35 | uint16_t st7735_swapcolor(uint16_t x) ; 36 | void st7735_drawbitmap(int16_t x, int16_t y, const uint16_t *image, int16_t w, int16_t h); 37 | void st7735_drawchars(int16_t x, int16_t y, char c, int16_t textColor, int16_t bgColor, uint8_t size); 38 | void st7735_drawchar(int16_t x, int16_t y, char c, int16_t textColor, int16_t bgColor, uint8_t size); 39 | uint32_t st7735_drawstring(uint16_t x, uint16_t y, char *pt, int16_t textColor);; 40 | void st7735_setcursor(uint32_t newX, uint32_t newY); 41 | void st7735_outudec(uint32_t n); 42 | void st7735_setrotation(uint8_t m) ; 43 | void st7735_invertdisplay(int i) ; 44 | void st7735_plotclear(int32_t ymin, int32_t ymax); 45 | void st7735_plotpoint(int32_t y); 46 | void st7735_plotline(int32_t y); 47 | void st7735_plotpoints(int32_t y1,int32_t y2); 48 | void st7735_plotbar(int32_t y); 49 | void st7735_plotdbfs(int32_t y); 50 | void st7735_plotnext(void); 51 | void st7735_plotnexterase(void); 52 | void st7735_outchar(char ch); 53 | void st7735_outstring(char *ptr); 54 | void st7735_settextcolor(uint16_t color); 55 | void st7735_output_init(void); 56 | void st7735_output_clear(void); 57 | void st7735_output_off(void); 58 | void st7735_output_on(void); 59 | void st7735_output_color(uint32_t newColor); 60 | 61 | #endif /* !__ST7735_DEF_H__ */ 62 | -------------------------------------------------------------------------------- /main/webserver.h: -------------------------------------------------------------------------------- 1 | #ifndef __WEBSERVER_DEF_H__ 2 | #define __WEBSERVER_DEF_H__ 3 | 4 | extern void webserver_init(void); 5 | 6 | #endif /* !__WEBSERVER_DEF_H__ */ 7 | -------------------------------------------------------------------------------- /poll.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | URL="http://"$1"/imu/orientation" 4 | 5 | while [ 1 ] 6 | do 7 | curl $URL 8 | echo "" 9 | sleep 0.01 10 | done 11 | -------------------------------------------------------------------------------- /sdkconfig.defaults: -------------------------------------------------------------------------------- 1 | # 2 | 3 | -------------------------------------------------------------------------------- /tests/cli_load_test.exp: -------------------------------------------------------------------------------- 1 | #!/usr/bin/expect 2 | 3 | set test_cnt 0 4 | 5 | proc do_cli_telnet {} { 6 | spawn telnet 192.168.1.114 7000 7 | expect "ESP32> " 8 | 9 | send "help\r" 10 | 11 | interact timeout 1 return 12 | 13 | send "" 14 | expect "telnet> " 15 | send "q\r" 16 | expect eof 17 | wait 18 | } 19 | 20 | set timeout 20 21 | 22 | while { 1 } { 23 | do_cli_telnet 24 | 25 | set test_cnt "[expr $test_cnt + 1]" 26 | puts "######### Test $test_cnt passed" 27 | sleep 1 28 | } 29 | --------------------------------------------------------------------------------