_b ? _a : _b; })
-
-char ssid[32];
-char password[] = "testing123";
-int wifi_secure_mode = 0;
-
-static const int pin = 2;
-
-// Structure holding the TCP connection information.
-struct espconn tcp_conn;
-// TCP specific protocol structure.
-esp_tcp tcp_proto;
-
-// interrupt communication on port 1338, UDP!
-struct espconn inter_conn;
-esp_udp inter_proto;
-
-uint32_t sendData[0x14] = {0};
-uint32_t recvData[0x40] = {0};
-
-static int ICACHE_FLASH_ATTR __spi_comm(char *dat, int len, uint32_t *recvData, int recvDataLen) {
- unsigned int length = 0;
-
- SpiData spiData;
-
- spiData.cmd = 2;
- spiData.cmdLen = 0;
- spiData.addr = NULL;
- spiData.addrLen = 0;
-
- // float boot pin
- gpio_output_set(0, 0, 0, (1 << 4));
-
- // manual CS pin
- gpio_output_set(0, (1 << 5), 0, 0);
- memset(sendData, 0xCC, 0x14);
-
- // wait for ST to respond to CS interrupt
- os_delay_us(50);
-
- // send request
- memcpy(((void*)sendData), dat, len);
- spiData.data = sendData;
- spiData.dataLen = 0x14;
- SPIMasterSendData(SpiNum_HSPI, &spiData);
-
- #define SPI_TIMEOUT 50000
- // give the ST time to be ready, up to 500ms
- int i;
- for (i = 0; (gpio_input_get() & (1 << 4)) && i < SPI_TIMEOUT; i++) {
- os_delay_us(10);
- system_soft_wdt_feed();
- }
-
- // TODO: handle this better
- if (i == SPI_TIMEOUT) {
- os_printf("ERROR: SPI receive failed\n");
- goto fail;
- }
-
- // blank out recvData
- memset(recvData, 0x00, 0x44);
-
- // receive the length
- spiData.data = recvData;
- spiData.dataLen = 4;
- if(SPIMasterRecvData(SpiNum_HSPI, &spiData) == -1) {
- // TODO: Handle gracefully. Maybe fail if len read fails?
- os_printf("SPI: Failed to recv length\n");
- goto fail;
- }
-
- length = recvData[0];
- if (length > 0x40) {
- os_printf("SPI: BAD LENGTH RECEIVED %x\n", length);
- length = 0;
- goto fail;
- }
-
- // got response, 0x40 works, 0x44 does not
- spiData.data = recvData+1;
- spiData.dataLen = (length+3)&(~3); // recvDataLen;
- if(SPIMasterRecvData(SpiNum_HSPI, &spiData) == -1) {
- // TODO: Handle gracefully. Maybe retry if payload failed.
- os_printf("SPI: Failed to recv payload\n");
- length = 0;
- goto fail;
- }
-
-fail:
- // clear CS
- gpio_output_set((1 << 5), 0, 0, 0);
-
- // set boot pin back
- gpio_output_set((1 << 4), 0, (1 << 4), 0);
-
- return length;
-}
-
-int ICACHE_FLASH_ATTR spi_comm(char *dat, int len, uint32_t *recvData, int recvDataLen) {
- // blink the led during SPI comm
- if (GPIO_REG_READ(GPIO_OUT_ADDRESS) & (1 << pin)) {
- // set gpio low
- gpio_output_set(0, (1 << pin), 0, 0);
- } else {
- // set gpio high
- gpio_output_set((1 << pin), 0, 0, 0);
- }
-
- return __spi_comm(dat, len, recvData, recvDataLen);
-}
-
-static void ICACHE_FLASH_ATTR tcp_rx_cb(void *arg, char *data, uint16_t len) {
- // nothing too big
- if (len > 0x14) return;
-
- // do the SPI comm
- spi_comm(data, len, recvData, 0x40);
-
- espconn_send(&tcp_conn, recvData, 0x44);
-}
-
-void ICACHE_FLASH_ATTR tcp_connect_cb(void *arg) {
- struct espconn *conn = (struct espconn *)arg;
- espconn_set_opt(&tcp_conn, ESPCONN_NODELAY);
- espconn_regist_recvcb(conn, tcp_rx_cb);
-}
-
-// must be 0x44, because we can fit 4 more
-uint8_t buf[0x44*0x10];
-int queue_send_len = -1;
-
-void ICACHE_FLASH_ATTR poll_can(void *arg) {
- uint8_t timerRecvData[0x44] = {0};
- int i = 0;
- int j;
-
- while (i < 0x40) {
- int len = spi_comm("\x01\x00\x00\x00", 4, timerRecvData, 0x40);
- if (len == 0) break;
- if (len > 0x40) { os_printf("SPI LENGTH ERROR!"); break; }
-
- // if it sends it, assume it's valid CAN
- for (j = 0; j < len; j += 0x10) {
- memcpy(buf + i*0x10, (timerRecvData+4)+j, 0x10);
- i++;
- }
- }
-
- if (i != 0) {
- int ret = espconn_sendto(&inter_conn, buf, i*0x10);
- if (ret != 0) {
- os_printf("send failed: %d\n", ret);
- queue_send_len = i*0x10;
- } else {
- queue_send_len = -1;
- }
- }
-}
-
-int udp_countdown = 0;
-
-static volatile os_timer_t udp_callback;
-void ICACHE_FLASH_ATTR udp_callback_func(void *arg) {
- if (queue_send_len == -1) {
- poll_can(NULL);
- } else {
- int ret = espconn_sendto(&inter_conn, buf, queue_send_len);
- if (ret == 0) {
- queue_send_len = -1;
- }
- }
- if (udp_countdown > 0) {
- os_timer_arm(&udp_callback, 5, 0);
- udp_countdown--;
- } else {
- os_printf("UDP timeout\n");
- }
-}
-
-void ICACHE_FLASH_ATTR inter_recv_cb(void *arg, char *pusrdata, unsigned short length) {
- remot_info *premot = NULL;
- if (espconn_get_connection_info(&inter_conn,&premot,0) == ESPCONN_OK) {
- inter_conn.proto.udp->remote_port = premot->remote_port;
- inter_conn.proto.udp->remote_ip[0] = premot->remote_ip[0];
- inter_conn.proto.udp->remote_ip[1] = premot->remote_ip[1];
- inter_conn.proto.udp->remote_ip[2] = premot->remote_ip[2];
- inter_conn.proto.udp->remote_ip[3] = premot->remote_ip[3];
-
-
- if (udp_countdown == 0) {
- os_printf("UDP recv\n");
- udp_countdown = 200*5;
-
- // start 5 second timer
- os_timer_disarm(&udp_callback);
- os_timer_setfn(&udp_callback, (os_timer_func_t *)udp_callback_func, NULL);
- os_timer_arm(&udp_callback, 5, 0);
- } else {
- udp_countdown = 200*5;
- }
- }
-}
-
-void ICACHE_FLASH_ATTR wifi_configure(int secure) {
- wifi_secure_mode = secure;
-
- // start wifi AP
- wifi_set_opmode(SOFTAP_MODE);
- struct softap_config config = {0};
- wifi_softap_get_config(&config);
- strcpy(config.ssid, ssid);
- if (wifi_secure_mode == 0) strcat(config.ssid, "-pair");
- strcpy(config.password, password);
- config.ssid_len = strlen(config.ssid);
- config.authmode = wifi_secure_mode ? AUTH_WPA2_PSK : AUTH_OPEN;
- config.beacon_interval = 100;
- config.max_connection = 4;
- wifi_softap_set_config(&config);
-
- if (wifi_secure_mode) {
- // setup tcp server
- tcp_proto.local_port = 1337;
- tcp_conn.type = ESPCONN_TCP;
- tcp_conn.state = ESPCONN_NONE;
- tcp_conn.proto.tcp = &tcp_proto;
- espconn_regist_connectcb(&tcp_conn, tcp_connect_cb);
- espconn_accept(&tcp_conn);
- espconn_regist_time(&tcp_conn, 60, 0); // 60s timeout for all connections
-
- // setup inter server
- inter_proto.local_port = 1338;
- const char udp_remote_ip[4] = {255, 255, 255, 255};
- os_memcpy(inter_proto.remote_ip, udp_remote_ip, 4);
- inter_proto.remote_port = 1338;
-
- inter_conn.type = ESPCONN_UDP;
- inter_conn.proto.udp = &inter_proto;
-
- espconn_regist_recvcb(&inter_conn, inter_recv_cb);
- espconn_create(&inter_conn);
- }
-}
-
-void ICACHE_FLASH_ATTR wifi_init() {
- // default ssid and password
- memset(ssid, 0, 32);
- os_sprintf(ssid, "panda-%08x-BROKEN", system_get_chip_id());
-
- // fetch secure ssid and password
- // update, try 20 times, for 1 second
- for (int i = 0; i < 20; i++) {
- uint8_t digest[SHA_DIGEST_SIZE];
- char resp[0x20];
- __spi_comm("\x00\x00\x00\x00\x40\xD0\x00\x00\x00\x00\x20\x00", 0xC, recvData, 0x40);
- memcpy(resp, recvData+1, 0x20);
-
- SHA_hash(resp, 0x1C, digest);
- if (memcmp(digest, resp+0x1C, 4) == 0) {
- // OTP is valid
- memcpy(ssid+6, resp, 0x10);
- memcpy(password, resp+0x10, 10);
- break;
- }
- os_delay_us(50000);
- }
- os_printf("Finished getting SID\n");
- os_printf(ssid);
- os_printf("\n");
-
- // set IP
- wifi_softap_dhcps_stop(); //stop DHCP before setting static IP
- struct ip_info ip_config;
- IP4_ADDR(&ip_config.ip, 192, 168, 0, 10);
- IP4_ADDR(&ip_config.gw, 0, 0, 0, 0);
- IP4_ADDR(&ip_config.netmask, 255, 255, 255, 0);
- wifi_set_ip_info(SOFTAP_IF, &ip_config);
- int stupid_gateway = 0;
- wifi_softap_set_dhcps_offer_option(OFFER_ROUTER, &stupid_gateway);
- wifi_softap_dhcps_start();
-
- wifi_configure(0);
-}
-
-#define LOOP_PRIO 2
-#define QUEUE_SIZE 1
-static os_event_t my_queue[QUEUE_SIZE];
-void loop();
-
-void ICACHE_FLASH_ATTR web_init();
-void ICACHE_FLASH_ATTR elm327_init();
-
-void ICACHE_FLASH_ATTR user_init() {
- // init gpio subsystem
- gpio_init();
-
- // configure UART TXD to be GPIO1, set as output
- PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_GPIO1);
- gpio_output_set(0, 0, (1 << pin), 0);
-
- // configure SPI
- SpiAttr hSpiAttr;
- hSpiAttr.bitOrder = SpiBitOrder_MSBFirst;
- hSpiAttr.speed = SpiSpeed_10MHz;
- hSpiAttr.mode = SpiMode_Master;
- hSpiAttr.subMode = SpiSubMode_0;
-
- // TODO: is one of these CS?
- WRITE_PERI_REG(PERIPHS_IO_MUX, 0x105);
- PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDI_U, 2); // configure io to spi mode
- PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTCK_U, 2); // configure io to spi mode
- PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTMS_U, 2); // configure io to spi mode
- PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDO_U, 2); // configure io to spi mode
- SPIInit(SpiNum_HSPI, &hSpiAttr);
- //SPICsPinSelect(SpiNum_HSPI, SpiPinCS_1);
-
- // configure UART TXD to be GPIO1, set as output
- PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO5_U, FUNC_GPIO5);
- gpio_output_set(0, 0, (1 << 5), 0);
- gpio_output_set((1 << 5), 0, 0, 0);
-
- // uart init
- uart_init(BIT_RATE_115200, BIT_RATE_115200);
-
- // led init
- PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2);
- gpio_output_set(0, (1 << pin), (1 << pin), 0);
-
- os_printf("hello\n");
-
- // needs SPI
- wifi_init();
-
- // support ota upgrades
- elm327_init();
- web_init();
-
- // set gpio high, so LED is off by default
- for (int i = 0; i < 5; i++) {
- gpio_output_set(0, (1 << pin), 0, 0);
- os_delay_us(50000);
- gpio_output_set((1 << pin), 0, 0, 0);
- os_delay_us(50000);
- }
-
- // jump to OS
- system_os_task(loop, LOOP_PRIO, my_queue, QUEUE_SIZE);
- system_os_post(LOOP_PRIO, 0, 0);
-}
-
-void ICACHE_FLASH_ATTR loop(os_event_t *events) {
- system_os_post(LOOP_PRIO, 0, 0);
-}
-
diff --git a/boardesp/python2_make.py b/boardesp/python2_make.py
deleted file mode 100644
index 85bee3457..000000000
--- a/boardesp/python2_make.py
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env python2
-import os
-import sys
-os.system(sys.argv[1])
diff --git a/boardesp/user_config.h b/boardesp/user_config.h
deleted file mode 100644
index e69de29bb..000000000
diff --git a/boardesp/webserver.c b/boardesp/webserver.c
deleted file mode 100644
index b1a514626..000000000
--- a/boardesp/webserver.c
+++ /dev/null
@@ -1,380 +0,0 @@
-#include "stdlib.h"
-#include "ets_sys.h"
-#include "osapi.h"
-#include "gpio.h"
-#include "mem.h"
-#include "os_type.h"
-#include "user_interface.h"
-#include "espconn.h"
-#include "upgrade.h"
-
-#include "crypto/rsa.h"
-#include "crypto/sha.h"
-
-#include "obj/gitversion.h"
-#include "obj/cert.h"
-
-#define MAX(a,b) ((a) > (b) ? (a) : (b))
-#define MIN(a,b) ((a) < (b) ? (a) : (b))
-#define espconn_send_string(conn, x) espconn_send(conn, x, strlen(x))
-
-#define MAX_RESP 0x800
-char resp[MAX_RESP];
-char pageheader[] = "HTTP/1.0 200 OK\nContent-Type: text/html\n\n"
-"\n"
-"\n"
-"\n"
-"Panda\n"
-"\n"
-"\n"
-"This is your comma.ai panda\n\n"
-"It's open source. Find the code here\n";
-
-char pagefooter[] = "
\n"
-"\n"
-"\n";
-
-char OK_header[] = "HTTP/1.0 200 OK\nContent-Type: text/html\n\n";
-
-static struct espconn web_conn;
-static esp_tcp web_proto;
-extern char ssid[];
-extern int wifi_secure_mode;
-
-char *st_firmware;
-int real_content_length, content_length = 0;
-char *st_firmware_ptr;
-LOCAL os_timer_t ota_reboot_timer;
-
-#define FIRMWARE_SIZE 503808
-
-typedef struct {
- uint16_t ep;
- uint16_t extra_len;
- union {
- struct {
- uint8_t request_type;
- uint8_t request;
- uint16_t value;
- uint16_t index;
- uint16_t length;
- } control;
- uint8_t data[0x10];
- } u;
-} usb_msg;
-
-int ICACHE_FLASH_ATTR usb_cmd(int ep, int len, int request,
- int value, int index, char *data) {
- usb_msg usb = {0};
-
- usb.ep = ep;
- usb.extra_len = (ep == 0) ? 0 : len;
- if (ep == 0) {
- usb.u.control.request_type = 0xc0;
- usb.u.control.request = request;
- usb.u.control.value = value;
- usb.u.control.index = index;
- } else {
- memcpy(&usb.u.data, data, usb.extra_len);
- }
-
- uint32_t recv[0x44/4];
- spi_comm(&usb, sizeof(usb), recv, 0x40);
-
- return recv[0];
-}
-
-
-void ICACHE_FLASH_ATTR st_flash() {
- if (st_firmware != NULL) {
- // boot mode
- os_printf("st_flash: enter boot mode\n");
- st_set_boot_mode(1);
-
- // echo
- os_printf("st_flash: wait for echo\n");
- for (int i = 0; i < 10; i++) {
- os_printf(" attempt: %d\n", i);
- if (usb_cmd(0, 0, 0xb0, 0, 0, NULL) > 0) break;
- }
-
- // unlock flash
- os_printf("st_flash: unlock flash\n");
- usb_cmd(0, 0, 0xb1, 0, 0, NULL);
-
- // erase sector 1
- os_printf("st_flash: erase sector 1\n");
- usb_cmd(0, 0, 0xb2, 1, 0, NULL);
-
- if (real_content_length >= 16384) {
- // erase sector 2
- os_printf("st_flash: erase sector 2\n");
- usb_cmd(0, 0, 0xb2, 2, 0, NULL);
- }
-
- // real content length will always be 0x10 aligned
- os_printf("st_flash: flashing\n");
- for (int i = 0; i < real_content_length; i += 0x10) {
- int rl = MIN(0x10, real_content_length-i);
- usb_cmd(2, rl, 0, 0, 0, &st_firmware[i]);
- system_soft_wdt_feed();
- }
-
- // reboot into normal mode
- os_printf("st_flash: rebooting\n");
- usb_cmd(0, 0, 0xd8, 0, 0, NULL);
-
- // done with this
- os_free(st_firmware);
- st_firmware = NULL;
- }
-}
-
-typedef enum {
- NOT_STARTED,
- CONNECTION_ESTABLISHED,
- RECEIVING_HEADER,
- RECEIVING_ST_FIRMWARE,
- RECEIVING_ESP_FIRMWARE,
- REBOOTING,
- ERROR
-} web_state_t;
-
-web_state_t state = NOT_STARTED;
-int esp_address, esp_address_erase_limit, start_address;
-
-void ICACHE_FLASH_ATTR hexdump(char *data, int len) {
- int i;
- for (i=0;isecure it");
- }
-
- ets_strcat(resp,"\nSet USB Mode:"
- ""
- ""
- "\n");
-
- ets_strcat(resp, pagefooter);
-
- espconn_send_string(&web_conn, resp);
- espconn_disconnect(conn);
- } else if (memcmp(data, "GET /secure", 11) == 0 && !wifi_secure_mode) {
- wifi_configure(1);
- } else if (memcmp(data, "GET /set_property?usb_mode=", 27) == 0 && wifi_secure_mode) {
- char mode_value = data[27] - '0';
- if (mode_value >= '\x00' && mode_value <= '\x02') {
- memset(resp, 0, MAX_RESP);
- char set_usb_mode_packet[] = "\x00\x00\x00\x00\x40\xE6\x00\x00\x00\x00\x40\x00";
- set_usb_mode_packet[6] = mode_value;
- uint32_t recvData[1];
- spi_comm(set_usb_mode_packet, 0xC, recvData, 0);
- os_sprintf(resp, "%sUSB Mode set to %02x\n\n", OK_header, mode_value);
- espconn_send_string(&web_conn, resp);
- espconn_disconnect(conn);
- }
- } else if (memcmp(data, "PUT /stupdate ", 14) == 0 && wifi_secure_mode) {
- os_printf("init st firmware\n");
- char *cl = strstr(data, "Content-Length: ");
- if (cl != NULL) {
- // get content length
- cl += strlen("Content-Length: ");
- content_length = skip_atoi(&cl);
- os_printf("with content length %d\n", content_length);
-
- // should be small enough to fit in RAM
- real_content_length = (content_length+0xF)&(~0xF);
- st_firmware_ptr = st_firmware = os_malloc(real_content_length);
- memset(st_firmware, 0, real_content_length);
- state = RECEIVING_ST_FIRMWARE;
- }
-
- } else if (((memcmp(data, "PUT /espupdate1 ", 16) == 0) ||
- (memcmp(data, "PUT /espupdate2 ", 16) == 0)) && wifi_secure_mode) {
- // 0x1000 = user1.bin
- // 0x81000 = user2.bin
- // 0x3FE000 = blank.bin
- os_printf("init esp firmware\n");
- char *cl = strstr(data, "Content-Length: ");
- if (cl != NULL) {
- // get content length
- cl += strlen("Content-Length: ");
- content_length = skip_atoi(&cl);
- os_printf("with content length %d\n", content_length);
-
- // setup flashing
- uint8_t current = system_upgrade_userbin_check();
- if (data[14] == '2' && current == UPGRADE_FW_BIN1) {
- os_printf("flashing boot2.bin\n");
- state = RECEIVING_ESP_FIRMWARE;
- esp_address = 4*1024 + FIRMWARE_SIZE + 16*1024 + 4*1024;
- } else if (data[14] == '1' && current == UPGRADE_FW_BIN2) {
- os_printf("flashing boot1.bin\n");
- state = RECEIVING_ESP_FIRMWARE;
- esp_address = 4*1024;
- } else {
- espconn_send_string(&web_conn, "HTTP/1.0 404 Not Found\nContent-Type: text/html\n\nwrong!\n");
- espconn_disconnect(conn);
- }
- esp_address_erase_limit = esp_address;
- start_address = esp_address;
- }
- } else {
- espconn_send_string(&web_conn, "HTTP/1.0 404 Not Found\nContent-Type: text/html\n\n404 Not Found!\n");
- espconn_disconnect(conn);
- }
- } else if (state == RECEIVING_ST_FIRMWARE) {
- os_printf("receiving st firmware: %d/%d\n", len, content_length);
- memcpy(st_firmware_ptr, data, MIN(content_length, len));
- st_firmware_ptr += len;
- content_length -= len;
-
- if (content_length <= 0 && real_content_length > 1000) {
- state = NOT_STARTED;
- os_printf("done!\n");
- espconn_send_string(&web_conn, "HTTP/1.0 200 OK\nContent-Type: text/html\n\nsuccess!\n");
- espconn_disconnect(conn);
-
- // reboot
- os_printf("Scheduling st_flash in 100ms.\n");
- os_timer_disarm(&ota_reboot_timer);
- os_timer_setfn(&ota_reboot_timer, (os_timer_func_t *)st_flash, NULL);
- os_timer_arm(&ota_reboot_timer, 100, 0);
- }
- } else if (state == RECEIVING_ESP_FIRMWARE) {
- if ((esp_address+len) < (start_address + FIRMWARE_SIZE)) {
- os_printf("receiving esp firmware: %d/%d -- 0x%x - 0x%x\n", len, content_length,
- esp_address, esp_address_erase_limit);
- content_length -= len;
- while (esp_address_erase_limit < (esp_address + len)) {
- os_printf("erasing 0x%X\n", esp_address_erase_limit);
- spi_flash_erase_sector(esp_address_erase_limit / SPI_FLASH_SEC_SIZE);
- esp_address_erase_limit += SPI_FLASH_SEC_SIZE;
- }
- SpiFlashOpResult res = spi_flash_write(esp_address, data, len);
- if (res != SPI_FLASH_RESULT_OK) {
- os_printf("flash fail @ 0x%x\n", esp_address);
- }
- esp_address += len;
-
- if (content_length == 0) {
-
- char digest[SHA_DIGEST_SIZE];
- uint32_t rsa[RSANUMBYTES/4];
- uint32_t dat[0x80/4];
- int ll;
- spi_flash_read(esp_address-RSANUMBYTES, rsa, RSANUMBYTES);
-
- // 32-bit aligned accesses only
- SHA_CTX ctx;
- SHA_init(&ctx);
- for (ll = start_address; ll < esp_address-RSANUMBYTES; ll += 0x80) {
- spi_flash_read(ll, dat, 0x80);
- SHA_update(&ctx, dat, MIN((esp_address-RSANUMBYTES)-ll, 0x80));
- }
- memcpy(digest, SHA_final(&ctx), SHA_DIGEST_SIZE);
-
- if (RSA_verify(&releaseesp_rsa_key, rsa, RSANUMBYTES, digest, SHA_DIGEST_SIZE) ||
- #ifdef ALLOW_DEBUG
- RSA_verify(&debugesp_rsa_key, rsa, RSANUMBYTES, digest, SHA_DIGEST_SIZE)
- #else
- false
- #endif
- ) {
- os_printf("RSA verify success!\n");
- espconn_send_string(&web_conn, "HTTP/1.0 200 OK\nContent-Type: text/html\n\nsuccess!\n");
- system_upgrade_flag_set(UPGRADE_FLAG_FINISH);
-
- // reboot
- os_printf("Scheduling reboot.\n");
- os_timer_disarm(&ota_reboot_timer);
- os_timer_setfn(&ota_reboot_timer, (os_timer_func_t *)system_upgrade_reboot, NULL);
- os_timer_arm(&ota_reboot_timer, 2000, 0);
- } else {
- os_printf("RSA verify FAILURE\n");
- espconn_send_string(&web_conn, "HTTP/1.0 500 Internal Server Error\nContent-Type: text/html\n\nrsa verify fail\n");
- }
- espconn_disconnect(conn);
- }
- }
- }
-}
-
-void ICACHE_FLASH_ATTR web_tcp_connect_cb(void *arg) {
- state = CONNECTION_ESTABLISHED;
- struct espconn *conn = (struct espconn *)arg;
- espconn_set_opt(&web_conn, ESPCONN_NODELAY);
- espconn_regist_recvcb(conn, web_rx_cb);
-}
-
-void ICACHE_FLASH_ATTR web_init() {
- web_proto.local_port = 80;
- web_conn.type = ESPCONN_TCP;
- web_conn.state = ESPCONN_NONE;
- web_conn.proto.tcp = &web_proto;
- espconn_regist_connectcb(&web_conn, web_tcp_connect_cb);
- espconn_accept(&web_conn);
-}
-
diff --git a/certs/debugesp b/certs/debugesp
deleted file mode 100644
index 789beaac1..000000000
--- a/certs/debugesp
+++ /dev/null
@@ -1,15 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIICXAIBAAKBgQCjIHvrSCWN0Nec6ozbImYik30PIF7JSWgdwDKTxSJ05RM3pj5E
-LQEGt3qcaVrTokO68tpt5Gu1p6ZsNqWg7iVTW9M7Qj7IH45YDzQP/PSRjgSosQA6
-6f5Gokba5QrW38myqimvj+0p+YH+CNGCBRlTUQGCO8uLCspMZneRSLPW9QIDAQAB
-AoGADaUn+HRef9BaWMvd4G6uMHI54cwJYbj8NpDfKjExQqnuw5bqWnWRQmiSnwbJ
-DC7kj3zE/LBAuj890ot3q1CAWqh47ZICZfoX9Qbi5TpvIHFCGy6YkOliF6iIQhR2
-4+zNKTAA0zNKskOM25PdI+grK1Ni/bEofSA6TrqvEwsmxnkCQQDVp9FUUor2Bo/h
-/3oAIP51LTw7vfpztYbJr+BDV63czV2DLXzSwzeNrwH4sA3oy1mjUgMBBgAarNGE
-DYlc4H5jAkEAw3UCHzzXPlxkw2QGp7nBly5y3p80Uqc31NuYz8rdX/U8KTngi2No
-Ft/SGCEXNpeYbToj+WK3RJJ2Ey0mK8+IxwJAcpGd/5CPsaQNLcw4WK9Yo+8Q2Jxk
-G/4gfDCSmqn+smNxnLEcuUwzkwdgkEGgA9BfjeOhdsAH+EXpx90WZrZ/LwJBAK0k
-jq+rTqUQZbZsejTEKYjJ/bnV4BzDwoKN0Q1pkLc7X4LJoW74rTFuLgdv8MdMfRtt
-IIb/eoeFEpGkMicnHesCQHgR7BTUGBM6Uxam7RCdsgVsxoHBma21E/44ivWUMZzN
-3oVt0mPnjS4speOlqwED5pCJ7yw7jwLPFMs8kNxuIKU=
------END RSA PRIVATE KEY-----
diff --git a/certs/debugesp.pub b/certs/debugesp.pub
deleted file mode 100644
index 3afcf3988..000000000
--- a/certs/debugesp.pub
+++ /dev/null
@@ -1 +0,0 @@
-ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCjIHvrSCWN0Nec6ozbImYik30PIF7JSWgdwDKTxSJ05RM3pj5ELQEGt3qcaVrTokO68tpt5Gu1p6ZsNqWg7iVTW9M7Qj7IH45YDzQP/PSRjgSosQA66f5Gokba5QrW38myqimvj+0p+YH+CNGCBRlTUQGCO8uLCspMZneRSLPW9Q== batman@y840
diff --git a/certs/releaseesp.pub b/certs/releaseesp.pub
deleted file mode 100644
index 1d1d54bb7..000000000
--- a/certs/releaseesp.pub
+++ /dev/null
@@ -1 +0,0 @@
-ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDN4pVyGuJJSde1l3Fjay8qPxog09DsAJZtYPk+armoYO1L6YKReUTcMNyHQYZZMZFmhCdgjCgTIF2QYWMoP4KSe8l6JF04YPP51dIgefc6UXjtlSI8Pyutr0v9xXjSfsVm3RAJxDSHgzs9AoMsluKCL+LhAR1nd7cuHXITJ80O4w== batman@y840
diff --git a/docs/panda_wifi_setup.md b/docs/panda_wifi_setup.md
deleted file mode 100644
index 4e9c80cea..000000000
--- a/docs/panda_wifi_setup.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# Connecting to White Panda via Wi-Fi
-
-1. First connect to your White Panda's Wi-Fi pairing network (this should be the Wi-Fi network WITH the "-pair" at the end)
-
-2. Now in your favorite web browser go to this address **192.168.0.10** (this should open a web interface to interact with the White Panda)
-
-3. Inside the web interface enable secured mode by clinking the **secure it** link/button (this should make the White Panda's Wi-Fi network visible)
-
- ### If you need your White Panda's Wi-Fi Password
-
- * Run the **get_panda_password.py** script in found in **examples/** (Must have panda paw for this step because you need to connect White Panda via USB to retrive the Wi-Fi password)
- * Also ensure that you are connected to your White Panda's Wi-Fi pairing network
-
-4. Connect to your White Panda's default Wi-Fi network (this should be the Wi-Fi network WITHOUT the "-pair" at the end)
-
-5. Your White Panda is now connected to Wi-Fi you can test this by running this line of code `python -c 'from panda import Panda; panda = Panda("WIFI")'` in your terminal of choice.
\ No newline at end of file
diff --git a/python/__init__.py b/python/__init__.py
index 21b2fd5df..d5d21c172 100644
--- a/python/__init__.py
+++ b/python/__init__.py
@@ -10,7 +10,6 @@ import traceback
import subprocess
import sys
from .dfu import PandaDFU # pylint: disable=import-error
-from .esptool import ESPROM, CesantaFlasher # noqa pylint: disable=import-error
from .flash_release import flash_release # noqa pylint: disable=import-error
from .update import ensure_st_up_to_date # noqa pylint: disable=import-error
from .serial import PandaSerial # noqa pylint: disable=import-error
diff --git a/python/esptool.py b/python/esptool.py
deleted file mode 100755
index 4a7dabfa2..000000000
--- a/python/esptool.py
+++ /dev/null
@@ -1,1317 +0,0 @@
-#!/usr/bin/env python
-# NB: Before sending a PR to change the above line to '#!/usr/bin/env python3', please read https://github.com/themadinventor/esptool/issues/21
-#
-# ESP8266 ROM Bootloader Utility
-# https://github.com/themadinventor/esptool
-#
-# Copyright (C) 2014-2016 Fredrik Ahlberg, Angus Gratton, other contributors as noted.
-#
-# This program is free software; you can redistribute it and/or modify it under
-# the terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 2 of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License along with
-# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
-# Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-# pylint: skip-file
-# flake8: noqa
-
-import argparse
-import hashlib
-import inspect
-import json
-import os
-#import serial
-import struct
-import subprocess
-import sys
-import tempfile
-import time
-#import traceback
-import usb1
-
-__version__ = "1.2"
-
-class FakePort(object):
- def __init__(self, serial=None):
- from panda import Panda
- self.panda = Panda(serial)
-
- # will only work on new st, old ones will stay @ 921600
- self.baudrate = 230400
-
- @property
- def baudrate(self):
- return self.baudrate
-
- @baudrate.setter
- def baudrate(self, x):
- print("set baud to", x)
- self.panda.set_uart_baud(1, x)
-
- def write(self, buf):
- SEND_STEP = 0x20
- for i in range(0, len(buf), SEND_STEP):
- self.panda.serial_write(1, buf[i:i+SEND_STEP])
-
- def flushInput(self):
- self.panda.serial_clear(1)
-
- def flushOutput(self):
- self.panda.serial_clear(1)
-
- def read(self, llen):
- ret = self.panda._handle.controlRead(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, 0xe0, 1, 0, 1)
- if ret == '':
- time.sleep(0.1)
- ret = self.panda._handle.controlRead(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, 0xe0, 1, 0, 1)
- return str(ret)
-
- def reset(self):
- self.panda.esp_reset(1)
-
- def inWaiting(self):
- return False
-
-class ESPROM(object):
- # These are the currently known commands supported by the ROM
- ESP_FLASH_BEGIN = 0x02
- ESP_FLASH_DATA = 0x03
- ESP_FLASH_END = 0x04
- ESP_MEM_BEGIN = 0x05
- ESP_MEM_END = 0x06
- ESP_MEM_DATA = 0x07
- ESP_SYNC = 0x08
- ESP_WRITE_REG = 0x09
- ESP_READ_REG = 0x0a
-
- # Maximum block sized for RAM and Flash writes, respectively.
- ESP_RAM_BLOCK = 0x1800
- ESP_FLASH_BLOCK = 0x400
-
- # Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want.
- ESP_ROM_BAUD = 115200
-
- # First byte of the application image
- ESP_IMAGE_MAGIC = 0xe9
-
- # Initial state for the checksum routine
- ESP_CHECKSUM_MAGIC = 0xef
-
- # OTP ROM addresses
- ESP_OTP_MAC0 = 0x3ff00050
- ESP_OTP_MAC1 = 0x3ff00054
- ESP_OTP_MAC3 = 0x3ff0005c
-
- # Flash sector size, minimum unit of erase.
- ESP_FLASH_SECTOR = 0x1000
-
- def __init__(self, port=None, baud=ESP_ROM_BAUD):
- self._port = FakePort(port)
- self._slip_reader = slip_reader(self._port)
-
- """ Read a SLIP packet from the serial port """
- def read(self):
- return next(self._slip_reader)
-
- """ Write bytes to the serial port while performing SLIP escaping """
- def write(self, packet):
- buf = '\xc0' \
- + (packet.replace('\xdb','\xdb\xdd').replace('\xc0','\xdb\xdc')) \
- + '\xc0'
- self._port.write(buf)
-
- """ Calculate checksum of a blob, as it is defined by the ROM """
- @staticmethod
- def checksum(data, state=ESP_CHECKSUM_MAGIC):
- for b in data:
- state ^= ord(b)
- return state
-
- """ Send a request and read the response """
- def command(self, op=None, data=None, chk=0):
- if op is not None:
- pkt = struct.pack('> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
- elif ((mac1 >> 16) & 0xff) == 0:
- oui = (0x18, 0xfe, 0x34)
- elif ((mac1 >> 16) & 0xff) == 1:
- oui = (0xac, 0xd0, 0x74)
- else:
- raise FatalError("Unknown OUI")
- return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff)
-
- """ Read Chip ID from OTP ROM - see http://esp8266-re.foogod.com/wiki/System_get_chip_id_%28IoT_RTOS_SDK_0.9.9%29 """
- def chip_id(self):
- id0 = self.read_reg(self.ESP_OTP_MAC0)
- id1 = self.read_reg(self.ESP_OTP_MAC1)
- return (id0 >> 24) | ((id1 & 0xffffff) << 8)
-
- """ Read SPI flash manufacturer and device id """
- def flash_id(self):
- self.flash_begin(0, 0)
- self.write_reg(0x60000240, 0x0, 0xffffffff)
- self.write_reg(0x60000200, 0x10000000, 0xffffffff)
- flash_id = self.read_reg(0x60000240)
- return flash_id
-
- """ Abuse the loader protocol to force flash to be left in write mode """
- def flash_unlock_dio(self):
- # Enable flash write mode
- self.flash_begin(0, 0)
- # Reset the chip rather than call flash_finish(), which would have
- # write protected the chip again (why oh why does it do that?!)
- self.mem_begin(0,0,0,0x40100000)
- self.mem_finish(0x40000080)
-
- """ Perform a chip erase of SPI flash """
- def flash_erase(self):
- # Trick ROM to initialize SFlash
- self.flash_begin(0, 0)
-
- # This is hacky: we don't have a custom stub, instead we trick
- # the bootloader to jump to the SPIEraseChip() routine and then halt/crash
- # when it tries to boot an unconfigured system.
- self.mem_begin(0,0,0,0x40100000)
- self.mem_finish(0x40004984)
-
- # Yup - there's no good way to detect if we succeeded.
- # It it on the other hand unlikely to fail.
-
- def run_stub(self, stub, params, read_output=True):
- stub = dict(stub)
- stub['code'] = unhexify(stub['code'])
- if 'data' in stub:
- stub['data'] = unhexify(stub['data'])
-
- if stub['num_params'] != len(params):
- raise FatalError('Stub requires %d params, %d provided'
- % (stub['num_params'], len(params)))
-
- params = struct.pack('<' + ('I' * stub['num_params']), *params)
- pc = params + stub['code']
-
- # Upload
- self.mem_begin(len(pc), 1, len(pc), stub['params_start'])
- self.mem_block(pc, 0)
- if 'data' in stub:
- self.mem_begin(len(stub['data']), 1, len(stub['data']), stub['data_start'])
- self.mem_block(stub['data'], 0)
- self.mem_finish(stub['entry'])
-
- if read_output:
- print('Stub executed, reading response:')
- while True:
- p = self.read()
- print(hexify(p))
- if p == '':
- return
-
-
-class ESPBOOTLOADER(object):
- """ These are constants related to software ESP bootloader, working with 'v2' image files """
-
- # First byte of the "v2" application image
- IMAGE_V2_MAGIC = 0xea
-
- # First 'segment' value in a "v2" application image, appears to be a constant version value?
- IMAGE_V2_SEGMENT = 4
-
-
-def LoadFirmwareImage(filename):
- """ Load a firmware image, without knowing what kind of file (v1 or v2) it is.
-
- Returns a BaseFirmwareImage subclass, either ESPFirmwareImage (v1) or OTAFirmwareImage (v2).
- """
- with open(filename, 'rb') as f:
- magic = ord(f.read(1))
- f.seek(0)
- if magic == ESPROM.ESP_IMAGE_MAGIC:
- return ESPFirmwareImage(f)
- elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC:
- return OTAFirmwareImage(f)
- else:
- raise FatalError("Invalid image magic number: %d" % magic)
-
-
-class BaseFirmwareImage(object):
- """ Base class with common firmware image functions """
- def __init__(self):
- self.segments = []
- self.entrypoint = 0
-
- def add_segment(self, addr, data, pad_to=4):
- """ Add a segment to the image, with specified address & data
- (padded to a boundary of pad_to size) """
- # Data should be aligned on word boundary
- l = len(data)
- if l % pad_to:
- data += b"\x00" * (pad_to - l % pad_to)
- if l > 0:
- self.segments.append((addr, len(data), data))
-
- def load_segment(self, f, is_irom_segment=False):
- """ Load the next segment from the image file """
- (offset, size) = struct.unpack(' 0x40200000 or offset < 0x3ffe0000 or size > 65536:
- raise FatalError('Suspicious segment 0x%x, length %d' % (offset, size))
- segment_data = f.read(size)
- if len(segment_data) < size:
- raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data)))
- segment = (offset, size, segment_data)
- self.segments.append(segment)
- return segment
-
- def save_segment(self, f, segment, checksum=None):
- """ Save the next segment to the image file, return next checksum value if provided """
- (offset, size, data) = segment
- f.write(struct.pack(' 16:
- raise FatalError('Invalid firmware image magic=%d segments=%d' % (magic, segments))
-
- for i in range(segments):
- self.load_segment(load_file)
- self.checksum = self.read_checksum(load_file)
-
- def save(self, filename):
- with open(filename, 'wb') as f:
- self.write_v1_header(f, self.segments)
- checksum = ESPROM.ESP_CHECKSUM_MAGIC
- for segment in self.segments:
- checksum = self.save_segment(f, segment, checksum)
- self.append_checksum(f, checksum)
-
-
-class OTAFirmwareImage(BaseFirmwareImage):
- """ 'Version 2' firmware image, segments loaded by software bootloader stub
- (ie Espressif bootloader or rboot)
- """
- def __init__(self, load_file=None):
- super(OTAFirmwareImage, self).__init__()
- self.version = 2
- if load_file is not None:
- (magic, segments, first_flash_mode, first_flash_size_freq, first_entrypoint) = struct.unpack(' 16:
- raise FatalError('Invalid V2 second header magic=%d segments=%d' % (magic, segments))
-
- # load all the usual segments
- for _ in range(segments):
- self.load_segment(load_file)
- self.checksum = self.read_checksum(load_file)
-
- def save(self, filename):
- with open(filename, 'wb') as f:
- # Save first header for irom0 segment
- f.write(struct.pack(' 0:
- esp._port.baudrate = baud_rate
- # Read the greeting.
- p = esp.read()
- if p != 'OHAI':
- raise FatalError('Failed to connect to the flasher (got %s)' % hexify(p))
-
- def flash_write(self, addr, data, show_progress=False):
- assert addr % self._esp.ESP_FLASH_SECTOR == 0, 'Address must be sector-aligned'
- assert len(data) % self._esp.ESP_FLASH_SECTOR == 0, 'Length must be sector-aligned'
- sys.stdout.write('Writing %d @ 0x%x... ' % (len(data), addr))
- sys.stdout.flush()
- self._esp.write(struct.pack(' length:
- raise FatalError('Read more than expected')
- p = self._esp.read()
- if len(p) != 16:
- raise FatalError('Expected digest, got: %s' % hexify(p))
- expected_digest = hexify(p).upper()
- digest = hashlib.md5(data).hexdigest().upper()
- print()
- if digest != expected_digest:
- raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
- p = self._esp.read()
- if len(p) != 1:
- raise FatalError('Expected status, got: %s' % hexify(p))
- status_code = struct.unpack(', ) or a single
-# argument.
-
-def load_ram(esp, args):
- image = LoadFirmwareImage(args.filename)
-
- print('RAM boot...')
- for (offset, size, data) in image.segments:
- print('Downloading %d bytes at %08x...' % (size, offset), end=' ')
- sys.stdout.flush()
- esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, offset)
-
- seq = 0
- while len(data) > 0:
- esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq)
- data = data[esp.ESP_RAM_BLOCK:]
- seq += 1
- print('done!')
-
- print('All segments done, executing at %08x' % image.entrypoint)
- esp.mem_finish(image.entrypoint)
-
-
-def read_mem(esp, args):
- print('0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address)))
-
-
-def write_mem(esp, args):
- esp.write_reg(args.address, args.value, args.mask, 0)
- print('Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address))
-
-
-def dump_mem(esp, args):
- f = open(args.filename, 'wb')
- for i in range(args.size / 4):
- d = esp.read_reg(args.address + (i * 4))
- f.write(struct.pack('> 16
- args.flash_size = {18: '2m', 19: '4m', 20: '8m', 21: '16m', 22: '32m'}.get(size_id)
- if args.flash_size is None:
- print('Warning: Could not auto-detect Flash size (FlashID=0x%x, SizeID=0x%x), defaulting to 4m' % (flash_id, size_id))
- args.flash_size = '4m'
- else:
- print('Auto-detected Flash size:', args.flash_size)
-
-
-def write_flash(esp, args):
- detect_flash_size(esp, args)
- flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
- flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40, '16m-c1': 0x50, '32m-c1':0x60, '32m-c2':0x70}[args.flash_size]
- flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
- flash_params = struct.pack('BB', flash_mode, flash_size_freq)
-
- flasher = CesantaFlasher(esp, args.baud)
-
- for address, argfile in args.addr_filename:
- image = argfile.read()
- argfile.seek(0) # rewind in case we need it again
- if address + len(image) > int(args.flash_size.split('m')[0]) * (1 << 17):
- print('WARNING: Unlikely to work as data goes beyond end of flash. Hint: Use --flash_size')
- # Fix sflash config data.
- if address == 0 and image[0] == '\xe9':
- print('Flash params set to 0x%02x%02x' % (flash_mode, flash_size_freq))
- image = image[0:2] + flash_params + image[4:]
- # Pad to sector size, which is the minimum unit of writing (erasing really).
- if len(image) % esp.ESP_FLASH_SECTOR != 0:
- image += '\xff' * (esp.ESP_FLASH_SECTOR - (len(image) % esp.ESP_FLASH_SECTOR))
- t = time.time()
- flasher.flash_write(address, image, not args.no_progress)
- t = time.time() - t
- print('\rWrote %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
- % (len(image), address, t, len(image) / t * 8 / 1000))
- print('Leaving...')
- if args.verify:
- print('Verifying just-written flash...')
- _verify_flash(flasher, args, flash_params)
- flasher.boot_fw()
-
-
-def image_info(args):
- image = LoadFirmwareImage(args.filename)
- print('Image version: %d' % image.version)
- print(('Entry point: %08x' % image.entrypoint) if image.entrypoint != 0 else 'Entry point not set')
- print('%d segments' % len(image.segments))
- print()
- checksum = ESPROM.ESP_CHECKSUM_MAGIC
- for (idx, (offset, size, data)) in enumerate(image.segments):
- if image.version == 2 and idx == 0:
- print('Segment 1: %d bytes IROM0 (no load address)' % size)
- else:
- print('Segment %d: %5d bytes at %08x' % (idx + 1, size, offset))
- checksum = ESPROM.checksum(data, checksum)
- print()
- print('Checksum: %02x (%s)' % (image.checksum, 'valid' if image.checksum == checksum else 'invalid!'))
-
-
-def make_image(args):
- image = ESPFirmwareImage()
- if len(args.segfile) == 0:
- raise FatalError('No segments specified')
- if len(args.segfile) != len(args.segaddr):
- raise FatalError('Number of specified files does not match number of specified addresses')
- for (seg, addr) in zip(args.segfile, args.segaddr):
- data = open(seg, 'rb').read()
- image.add_segment(addr, data)
- image.entrypoint = args.entrypoint
- image.save(args.output)
-
-
-def elf2image(args):
- e = ELFFile(args.input)
- if args.version == '1':
- image = ESPFirmwareImage()
- else:
- image = OTAFirmwareImage()
- irom_data = e.load_section('.irom0.text')
- if len(irom_data) == 0:
- raise FatalError(".irom0.text section not found in ELF file - can't create V2 image.")
- image.add_segment(0, irom_data, 16)
- image.entrypoint = e.get_entry_point()
- for section, start in ((".text", "_text_start"), (".data", "_data_start"), (".rodata", "_rodata_start")):
- data = e.load_section(section)
- image.add_segment(e.get_symbol_addr(start), data)
-
- image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
- image.flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40, '16m-c1': 0x50, '32m-c1':0x60, '32m-c2':0x70}[args.flash_size]
- image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
-
- irom_offs = e.get_symbol_addr("_irom0_text_start") - 0x40200000
-
- if args.version == '1':
- if args.output is None:
- args.output = args.input + '-'
- image.save(args.output + "0x00000.bin")
- data = e.load_section(".irom0.text")
- if irom_offs < 0:
- raise FatalError('Address of symbol _irom0_text_start in ELF is located before flash mapping address. Bad linker script?')
- if (irom_offs & 0xFFF) != 0: # irom0 isn't flash sector aligned
- print("WARNING: irom0 section offset is 0x%08x. ELF is probably linked for 'elf2image --version=2'" % irom_offs)
- with open(args.output + "0x%05x.bin" % irom_offs, "wb") as f:
- f.write(data)
- f.close()
- else: # V2 OTA image
- if args.output is None:
- args.output = "%s-0x%05x.bin" % (os.path.splitext(args.input)[0], irom_offs & ~(ESPROM.ESP_FLASH_SECTOR - 1))
- image.save(args.output)
-
-
-def read_mac(esp, args):
- mac = esp.read_mac()
- print('MAC: %s' % ':'.join(['%02x' % x for x in mac]))
-
-
-def chip_id(esp, args):
- chipid = esp.chip_id()
- print('Chip ID: 0x%08x' % chipid)
-
-
-def erase_flash(esp, args):
- flasher = CesantaFlasher(esp, args.baud)
- print('Erasing flash (this may take a while)...')
- t = time.time()
- flasher.flash_erase_chip()
- t = time.time() - t
- print('Erase took %.1f seconds' % t)
-
-
-def run(esp, args):
- esp.run()
-
-
-def flash_id(esp, args):
- flash_id = esp.flash_id()
- esp.flash_finish(False)
- print('Manufacturer: %02x' % (flash_id & 0xff))
- print('Device: %02x%02x' % ((flash_id >> 8) & 0xff, (flash_id >> 16) & 0xff))
-
-
-def read_flash(esp, args):
- flasher = CesantaFlasher(esp, args.baud)
- t = time.time()
- data = flasher.flash_read(args.address, args.size, not args.no_progress)
- t = time.time() - t
- print('\rRead %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
- % (len(data), args.address, t, len(data) / t * 8 / 1000))
- open(args.filename, 'wb').write(data)
-
-
-def _verify_flash(flasher, args, flash_params=None):
- differences = False
- for address, argfile in args.addr_filename:
- image = argfile.read()
- argfile.seek(0) # rewind in case we need it again
- if address == 0 and image[0] == '\xe9' and flash_params is not None:
- image = image[0:2] + flash_params + image[4:]
- image_size = len(image)
- print('Verifying 0x%x (%d) bytes @ 0x%08x in flash against %s...' % (image_size, image_size, address, argfile.name))
- # Try digest first, only read if there are differences.
- digest, _ = flasher.flash_digest(address, image_size)
- digest = hexify(digest).upper()
- expected_digest = hashlib.md5(image).hexdigest().upper()
- if digest == expected_digest:
- print('-- verify OK (digest matched)')
- continue
- else:
- differences = True
- if getattr(args, 'diff', 'no') != 'yes':
- print('-- verify FAILED (digest mismatch)')
- continue
-
- flash = flasher.flash_read(address, image_size)
- assert flash != image
- diff = [i for i in range(image_size) if flash[i] != image[i]]
- print('-- verify FAILED: %d differences, first @ 0x%08x' % (len(diff), address + diff[0]))
- for d in diff:
- print(' %08x %02x %02x' % (address + d, ord(flash[d]), ord(image[d])))
- if differences:
- raise FatalError("Verify failed.")
-
-
-def verify_flash(esp, args, flash_params=None):
- flasher = CesantaFlasher(esp)
- _verify_flash(flasher, args, flash_params)
-
-
-def version(args):
- print(__version__)
-
-#
-# End of operations functions
-#
-
-
-def main():
- parser = argparse.ArgumentParser(description='esptool.py v%s - ESP8266 ROM Bootloader Utility' % __version__, prog='esptool')
-
- parser.add_argument(
- '--port', '-p',
- help='Serial port device',
- default=os.environ.get('ESPTOOL_PORT', None))
-
- parser.add_argument(
- '--baud', '-b',
- help='Serial port baud rate used when flashing/reading',
- type=arg_auto_int,
- default=os.environ.get('ESPTOOL_BAUD', ESPROM.ESP_ROM_BAUD))
-
- subparsers = parser.add_subparsers(
- dest='operation',
- help='Run esptool {command} -h for additional help')
-
- parser_load_ram = subparsers.add_parser(
- 'load_ram',
- help='Download an image to RAM and execute')
- parser_load_ram.add_argument('filename', help='Firmware image')
-
- parser_dump_mem = subparsers.add_parser(
- 'dump_mem',
- help='Dump arbitrary memory to disk')
- parser_dump_mem.add_argument('address', help='Base address', type=arg_auto_int)
- parser_dump_mem.add_argument('size', help='Size of region to dump', type=arg_auto_int)
- parser_dump_mem.add_argument('filename', help='Name of binary dump')
-
- parser_read_mem = subparsers.add_parser(
- 'read_mem',
- help='Read arbitrary memory location')
- parser_read_mem.add_argument('address', help='Address to read', type=arg_auto_int)
-
- parser_write_mem = subparsers.add_parser(
- 'write_mem',
- help='Read-modify-write to arbitrary memory location')
- parser_write_mem.add_argument('address', help='Address to write', type=arg_auto_int)
- parser_write_mem.add_argument('value', help='Value', type=arg_auto_int)
- parser_write_mem.add_argument('mask', help='Mask of bits to write', type=arg_auto_int)
-
- def add_spi_flash_subparsers(parent, auto_detect=False):
- """ Add common parser arguments for SPI flash properties """
- parent.add_argument('--flash_freq', '-ff', help='SPI Flash frequency',
- choices=['40m', '26m', '20m', '80m'],
- default=os.environ.get('ESPTOOL_FF', '40m'))
- parent.add_argument('--flash_mode', '-fm', help='SPI Flash mode',
- choices=['qio', 'qout', 'dio', 'dout'],
- default=os.environ.get('ESPTOOL_FM', 'qio'))
- choices = ['4m', '2m', '8m', '16m', '32m', '16m-c1', '32m-c1', '32m-c2']
- default = '4m'
- if auto_detect:
- default = 'detect'
- choices.insert(0, 'detect')
- parent.add_argument('--flash_size', '-fs', help='SPI Flash size in Mbit', type=str.lower,
- choices=choices,
- default=os.environ.get('ESPTOOL_FS', default))
-
- parser_write_flash = subparsers.add_parser(
- 'write_flash',
- help='Write a binary blob to flash')
- parser_write_flash.add_argument('addr_filename', metavar=' ', help='Address followed by binary filename, separated by space',
- action=AddrFilenamePairAction)
- add_spi_flash_subparsers(parser_write_flash, auto_detect=True)
- parser_write_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
- parser_write_flash.add_argument('--verify', help='Verify just-written data (only necessary if very cautious, data is already CRCed', action='store_true')
-
- subparsers.add_parser(
- 'run',
- help='Run application code in flash')
-
- parser_image_info = subparsers.add_parser(
- 'image_info',
- help='Dump headers from an application image')
- parser_image_info.add_argument('filename', help='Image file to parse')
-
- parser_make_image = subparsers.add_parser(
- 'make_image',
- help='Create an application image from binary files')
- parser_make_image.add_argument('output', help='Output image file')
- parser_make_image.add_argument('--segfile', '-f', action='append', help='Segment input file')
- parser_make_image.add_argument('--segaddr', '-a', action='append', help='Segment base address', type=arg_auto_int)
- parser_make_image.add_argument('--entrypoint', '-e', help='Address of entry point', type=arg_auto_int, default=0)
-
- parser_elf2image = subparsers.add_parser(
- 'elf2image',
- help='Create an application image from ELF file')
- parser_elf2image.add_argument('input', help='Input ELF file')
- parser_elf2image.add_argument('--output', '-o', help='Output filename prefix (for version 1 image), or filename (for version 2 single image)', type=str)
- parser_elf2image.add_argument('--version', '-e', help='Output image version', choices=['1','2'], default='1')
- add_spi_flash_subparsers(parser_elf2image)
-
- subparsers.add_parser(
- 'read_mac',
- help='Read MAC address from OTP ROM')
-
- subparsers.add_parser(
- 'chip_id',
- help='Read Chip ID from OTP ROM')
-
- subparsers.add_parser(
- 'flash_id',
- help='Read SPI flash manufacturer and device ID')
-
- parser_read_flash = subparsers.add_parser(
- 'read_flash',
- help='Read SPI flash content')
- parser_read_flash.add_argument('address', help='Start address', type=arg_auto_int)
- parser_read_flash.add_argument('size', help='Size of region to dump', type=arg_auto_int)
- parser_read_flash.add_argument('filename', help='Name of binary dump')
- parser_read_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
-
- parser_verify_flash = subparsers.add_parser(
- 'verify_flash',
- help='Verify a binary blob against flash')
- parser_verify_flash.add_argument('addr_filename', help='Address and binary file to verify there, separated by space',
- action=AddrFilenamePairAction)
- parser_verify_flash.add_argument('--diff', '-d', help='Show differences',
- choices=['no', 'yes'], default='no')
-
- subparsers.add_parser(
- 'erase_flash',
- help='Perform Chip Erase on SPI flash')
-
- subparsers.add_parser(
- 'version', help='Print esptool version')
-
- # internal sanity check - every operation matches a module function of the same name
- for operation in list(subparsers.choices.keys()):
- assert operation in globals(), "%s should be a module function" % operation
-
- args = parser.parse_args()
-
- print('esptool.py v%s' % __version__)
-
- # operation function can take 1 arg (args), 2 args (esp, arg)
- # or be a member function of the ESPROM class.
-
- operation_func = globals()[args.operation]
- operation_args,_,_,_ = inspect.getargspec(operation_func)
- if operation_args[0] == 'esp': # operation function takes an ESPROM connection object
- initial_baud = min(ESPROM.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate
- esp = ESPROM(args.port, initial_baud)
- esp.connect()
- operation_func(esp, args)
- else:
- operation_func(args)
-
-
-class AddrFilenamePairAction(argparse.Action):
- """ Custom parser class for the address/filename pairs passed as arguments """
- def __init__(self, option_strings, dest, nargs='+', **kwargs):
- super(AddrFilenamePairAction, self).__init__(option_strings, dest, nargs, **kwargs)
-
- def __call__(self, parser, namespace, values, option_string=None):
- # validate pair arguments
- pairs = []
- for i in range(0,len(values),2):
- try:
- address = int(values[i],0)
- except ValueError:
- raise argparse.ArgumentError(self,'Address "%s" must be a number' % values[i])
- try:
- argfile = open(values[i + 1], 'rb')
- except IOError as e:
- raise argparse.ArgumentError(self, e)
- except IndexError:
- raise argparse.ArgumentError(self,'Must be pairs of an address and the binary filename to write there')
- pairs.append((address, argfile))
- setattr(namespace, self.dest, pairs)
-
-# This is "wrapped" stub_flasher.c, to be loaded using run_stub.
-_CESANTA_FLASHER_STUB = """\
-{"code_start": 1074790404, "code": "080000601C000060000000601000006031FCFF71FCFF\
-81FCFFC02000680332D218C020004807404074DCC48608005823C0200098081BA5A9239245005803\
-1B555903582337350129230B446604DFC6F3FF21EEFFC0200069020DF0000000010078480040004A\
-0040B449004012C1F0C921D911E901DD0209312020B4ED033C2C56C2073020B43C3C56420701F5FF\
-C000003C4C569206CD0EEADD860300202C4101F1FFC0000056A204C2DCF0C02DC0CC6CCAE2D1EAFF\
-0606002030F456D3FD86FBFF00002020F501E8FFC00000EC82D0CCC0C02EC0C73DEB2ADC46030020\
-2C4101E1FFC00000DC42C2DCF0C02DC056BCFEC602003C5C8601003C6C4600003C7C08312D0CD811\
-C821E80112C1100DF0000C180000140010400C0000607418000064180000801800008C1800008418\
-0000881800009018000018980040880F0040A80F0040349800404C4A0040740F0040800F0040980F\
-00400099004012C1E091F5FFC961CD0221EFFFE941F9310971D9519011C01A223902E2D1180C0222\
-6E1D21E4FF31E9FF2AF11A332D0F42630001EAFFC00000C030B43C2256A31621E1FF1A2228022030\
-B43C3256B31501ADFFC00000DD023C4256ED1431D6FF4D010C52D90E192E126E0101DDFFC0000021\
-D2FF32A101C020004802303420C0200039022C0201D7FFC00000463300000031CDFF1A333803D023\
-C03199FF27B31ADC7F31CBFF1A3328030198FFC0000056C20E2193FF2ADD060E000031C6FF1A3328\
-030191FFC0000056820DD2DD10460800000021BEFF1A2228029CE231BCFFC020F51A33290331BBFF\
-C02C411A332903C0F0F4222E1D22D204273D9332A3FFC02000280E27B3F721ABFF381E1A2242A400\
-01B5FFC00000381E2D0C42A40001B3FFC0000056120801B2FFC00000C02000280EC2DC0422D2FCC0\
-2000290E01ADFFC00000222E1D22D204226E1D281E22D204E7B204291E860000126E012198FF32A0\
-042A21C54C003198FF222E1D1A33380337B202C6D6FF2C02019FFFC000002191FF318CFF1A223A31\
-019CFFC00000218DFF1C031A22C549000C02060300003C528601003C624600003C72918BFF9A1108\
-71C861D851E841F83112C1200DF00010000068100000581000007010000074100000781000007C10\
-0000801000001C4B0040803C004091FDFF12C1E061F7FFC961E941F9310971D9519011C01A662906\
-21F3FFC2D1101A22390231F2FF0C0F1A33590331EAFFF26C1AED045C2247B3028636002D0C016DFF\
-C0000021E5FF41EAFF2A611A4469040622000021E4FF1A222802F0D2C0D7BE01DD0E31E0FF4D0D1A\
-3328033D0101E2FFC00000561209D03D2010212001DFFFC000004D0D2D0C3D01015DFFC0000041D5\
-FFDAFF1A444804D0648041D2FF1A4462640061D1FF106680622600673F1331D0FF10338028030C43\
-853A002642164613000041CAFF222C1A1A444804202FC047328006F6FF222C1A273F3861C2FF222C\
-1A1A6668066732B921BDFF3D0C1022800148FFC0000021BAFF1C031A2201BFFFC000000C02460300\
-5C3206020000005C424600005C5291B7FF9A110871C861D851E841F83112C1200DF0B0100000C010\
-0000D010000012C1E091FEFFC961D951E9410971F931CD039011C0ED02DD0431A1FF9C1422A06247\
-B302062D0021F4FF1A22490286010021F1FF1A223902219CFF2AF12D0F011FFFC00000461C0022D1\
-10011CFFC0000021E9FFFD0C1A222802C7B20621E6FF1A22F8022D0E3D014D0F0195FFC000008C52\
-22A063C6180000218BFF3D01102280F04F200111FFC00000AC7D22D1103D014D0F010DFFC0000021\
-D6FF32D110102280010EFFC0000021D3FF1C031A220185FFC00000FAEEF0CCC056ACF821CDFF317A\
-FF1A223A310105FFC0000021C9FF1C031A22017CFFC000002D0C91C8FF9A110871C861D851E841F8\
-3112C1200DF0000200600000001040020060FFFFFF0012C1E00C02290131FAFF21FAFF026107C961\
-C02000226300C02000C80320CC10564CFF21F5FFC02000380221F4FF20231029010C432D010163FF\
-C0000008712D0CC86112C1200DF00080FE3F8449004012C1D0C9A109B17CFC22C1110C13C51C0026\
-1202463000220111C24110B68202462B0031F5FF3022A02802A002002D011C03851A0066820A2801\
-32210105A6FF0607003C12C60500000010212032A01085180066A20F2221003811482105B3FF2241\
-10861A004C1206FDFF2D011C03C5160066B20E280138114821583185CFFF06F7FF005C1286F5FF00\
-10212032A01085140066A20D2221003811482105E1FF06EFFF0022A06146EDFF45F0FFC6EBFF0000\
-01D2FFC0000006E9FF000C022241100C1322C110C50F00220111060600000022C1100C13C50E0022\
-011132C2FA303074B6230206C8FF08B1C8A112C1300DF0000000000010404F484149007519031027\
-000000110040A8100040BC0F0040583F0040CC2E00401CE20040D83900408000004021F4FF12C1E0\
-C961C80221F2FF097129010C02D951C91101F4FFC0000001F3FFC00000AC2C22A3E801F2FFC00000\
-21EAFFC031412A233D0C01EFFFC000003D0222A00001EDFFC00000C1E4FF2D0C01E8FFC000002D01\
-32A004450400C5E7FFDD022D0C01E3FFC00000666D1F4B2131DCFF4600004B22C0200048023794F5\
-31D9FFC0200039023DF08601000001DCFFC000000871C861D85112C1200DF000000012C1F0026103\
-01EAFEC00000083112C1100DF000643B004012C1D0E98109B1C9A1D991F97129013911E2A0C001FA\
-FFC00000CD02E792F40C0DE2A0C0F2A0DB860D00000001F4FFC00000204220E71240F7921C226102\
-01EFFFC0000052A0DC482157120952A0DD571205460500004D0C3801DA234242001BDD3811379DC5\
-C6000000000C0DC2A0C001E3FFC00000C792F608B12D0DC8A1D891E881F87112C1300DF00000", "\
-entry": 1074792180, "num_params": 1, "params_start": 1074790400, "data": "FE0510\
-401A0610403B0610405A0610407A061040820610408C0610408C061040", "data_start": 10736\
-43520}
-"""
-
-if __name__ == '__main__':
- try:
- main()
- except FatalError as e:
- print('\nA fatal error occurred: %s' % e)
- sys.exit(2)
diff --git a/python/flash_release.py b/python/flash_release.py
index 961a83a0d..f8862bd27 100755
--- a/python/flash_release.py
+++ b/python/flash_release.py
@@ -7,7 +7,7 @@ import json
import io
def flash_release(path=None, st_serial=None):
- from panda import Panda, PandaDFU, ESPROM, CesantaFlasher
+ from panda import Panda, PandaDFU
from zipfile import ZipFile
def status(x):
@@ -43,9 +43,6 @@ def flash_release(path=None, st_serial=None):
code_boot_15 = zf.read("boot_v1.5.bin")
code_boot_15 = code_boot_15[0:2] + "\x00\x30" + code_boot_15[4:]
- code_user1 = zf.read("user1.bin")
- code_user2 = zf.read("user2.bin")
-
# enter DFU mode
status("1. Entering DFU mode")
panda = Panda(st_serial)
@@ -64,29 +61,8 @@ def flash_release(path=None, st_serial=None):
panda.flash(code=code_panda)
panda.close()
- # flashing ESP
- if panda.is_white():
- status("4. Flashing ESP (slow!)")
-
- def align(x, sz=0x1000):
- x + "\xFF" * ((sz - len(x)) % sz)
-
- esp = ESPROM(st_serial)
- esp.connect()
- flasher = CesantaFlasher(esp, 230400)
- flasher.flash_write(0x0, align(code_boot_15), True)
- flasher.flash_write(0x1000, align(code_user1), True)
- flasher.flash_write(0x81000, align(code_user2), True)
- flasher.flash_write(0x3FE000, "\xFF" * 0x1000)
- flasher.boot_fw()
- del flasher
- del esp
- time.sleep(1)
- else:
- status("4. No ESP in non-white panda")
-
# check for connection
- status("5. Verifying version")
+ status("4. Verifying version")
panda = Panda(st_serial)
my_version = panda.get_version()
print("dongle id: %s" % panda.get_serial()[0])
diff --git a/run_automated_tests.sh b/run_automated_tests.sh
index e876c670a..6bfdcf533 100755
--- a/run_automated_tests.sh
+++ b/run_automated_tests.sh
@@ -6,11 +6,7 @@ else
TESTSUITE_NAME="Panda_Test-DEV"
fi
-if [ ! -z "${SKIPWIFI}" ] || [ -f "/EON" ]; then
- TEST_SCRIPTS=$(ls tests/automated/$1*.py | grep -v wifi)
-else
- TEST_SCRIPTS=$(ls tests/automated/$1*.py)
-fi
+TEST_SCRIPTS=$(ls tests/automated/$1*.py)
IFS=$'\n'
for NAME in $(nmcli --fields NAME con show | grep panda | awk '{$1=$1};1')
diff --git a/tests/all_wifi_test.py b/tests/all_wifi_test.py
deleted file mode 100755
index b1ca79cc5..000000000
--- a/tests/all_wifi_test.py
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/usr/bin/env python3
-import requests
-import json
-from .automated.helpers import _connect_wifi # pylint: disable=import-error
-from panda import Panda
-from nose.tools import assert_equal
-
-if __name__ == "__main__":
- print("Fetching latest firmware from github.com/commaai/panda-artifacts")
- r = requests.get("https://raw.githubusercontent.com/commaai/panda-artifacts/master/latest.json")
- latest_version = json.loads(r.text)['version']
-
- for p in Panda.list():
- dongle_id, pw = Panda(p).get_serial()
- print(dongle_id, pw)
- assert(dongle_id.isalnum())
- _connect_wifi(dongle_id, pw)
-
- r = requests.get("http://192.168.0.10/")
- print(r.text)
- wifi_dongle_id = r.text.split("ssid: panda-")[1].split("
")[0]
- st_version = r.text.split("st version:")[1].strip().split("
")[0]
- esp_version = r.text.split("esp version:")[1].strip().split("
")[0]
-
- assert_equal(str(dongle_id), wifi_dongle_id)
- assert_equal(latest_version, st_version)
- assert_equal(latest_version, esp_version)
diff --git a/tests/automated/7_can_loopback.py b/tests/automated/4_can_loopback.py
similarity index 100%
rename from tests/automated/7_can_loopback.py
rename to tests/automated/4_can_loopback.py
diff --git a/tests/automated/4_wifi.py b/tests/automated/4_wifi.py
deleted file mode 100644
index 15b8dc6c9..000000000
--- a/tests/automated/4_wifi.py
+++ /dev/null
@@ -1,60 +0,0 @@
-import time
-from panda import Panda
-from .helpers import reset_pandas, connect_wifi, test_white, test_all_pandas, panda_type_to_serial, panda_connect_and_init
-import requests
-
-# Reset the pandas before running tests
-def aaaa_reset_before_tests():
- reset_pandas()
-
-@test_all_pandas
-@panda_connect_and_init
-def test_get_serial(p):
- print(p.get_serial())
-
-@test_all_pandas
-@panda_connect_and_init
-def test_get_serial_in_flash_mode(p):
- p.reset(enter_bootstub=True)
- assert(p.bootstub)
- print(p.get_serial())
- p.reset()
-
-@test_white
-@panda_type_to_serial
-def test_connect_wifi(serials=None):
- connect_wifi(serials[0])
-
-@test_white
-@panda_type_to_serial
-def test_flash_wifi(serials=None):
- connect_wifi(serials[0])
- assert Panda.flash_ota_wifi(release=False), "OTA Wifi Flash Failed"
- connect_wifi(serials[0])
-
-@test_white
-@panda_type_to_serial
-def test_wifi_flash_st(serials=None):
- connect_wifi(serials[0])
- assert Panda.flash_ota_st(), "OTA ST Flash Failed"
- connected = False
- st = time.time()
- while not connected and (time.time() - st) < 20:
- try:
- p = Panda(serial=serials[0])
- p.get_serial()
- connected = True
- except:
- time.sleep(1)
-
- if not connected:
- assert False, "Panda failed to connect on USB after flashing"
-
-@test_white
-@panda_type_to_serial
-def test_webpage_fetch(serials=None):
- connect_wifi(serials[0])
- r = requests.get("http://192.168.0.10/")
- print(r.text)
-
- assert "This is your comma.ai panda" in r.text
diff --git a/tests/automated/8_gps.py b/tests/automated/5_gps.py
similarity index 100%
rename from tests/automated/8_gps.py
rename to tests/automated/5_gps.py
diff --git a/tests/automated/5_wifi_functionality.py b/tests/automated/5_wifi_functionality.py
deleted file mode 100644
index f467400a7..000000000
--- a/tests/automated/5_wifi_functionality.py
+++ /dev/null
@@ -1,69 +0,0 @@
-import time
-from panda import Panda
-from .helpers import start_heartbeat_thread, reset_pandas, time_many_sends, connect_wifi, test_white, panda_type_to_serial
-
-# Reset the pandas before running tests
-def aaaa_reset_before_tests():
- reset_pandas()
-
-@test_white
-@panda_type_to_serial
-def test_get_serial_wifi(serials=None):
- connect_wifi(serials[0])
-
- p = Panda("WIFI")
- print(p.get_serial())
-
-@test_white
-@panda_type_to_serial
-def test_throughput(serials=None):
- connect_wifi(serials[0])
- p = Panda(serials[0])
-
- # Start heartbeat
- start_heartbeat_thread(p)
-
- # enable output mode
- p.set_safety_mode(Panda.SAFETY_ALLOUTPUT)
-
- # enable CAN loopback mode
- p.set_can_loopback(True)
-
- p = Panda("WIFI")
-
- for speed in [100, 250, 500, 750, 1000]:
- # set bus 0 speed to speed
- p.set_can_speed_kbps(0, speed)
- time.sleep(0.1)
-
- comp_kbps = time_many_sends(p, 0)
-
- # bit count from https://en.wikipedia.org/wiki/CAN_bus
- saturation_pct = (comp_kbps / speed) * 100.0
- #assert_greater(saturation_pct, 80)
- #assert_less(saturation_pct, 100)
-
- print("WIFI loopback 100 messages at speed %d, comp speed is %.2f, percent %.2f" % (speed, comp_kbps, saturation_pct))
-
-@test_white
-@panda_type_to_serial
-def test_recv_only(serials=None):
- connect_wifi(serials[0])
- p = Panda(serials[0])
-
- # Start heartbeat
- start_heartbeat_thread(p)
-
- p.set_safety_mode(Panda.SAFETY_ALLOUTPUT)
-
- p.set_can_loopback(True)
- pwifi = Panda("WIFI")
-
- # TODO: msg_count=1000 drops packets, is this fixable?
- for msg_count in [10, 100, 200]:
- speed = 500
- p.set_can_speed_kbps(0, speed)
- comp_kbps = time_many_sends(p, 0, pwifi, msg_count)
- saturation_pct = (comp_kbps / speed) * 100.0
-
- print("HT WIFI loopback %d messages at speed %d, comp speed is %.2f, percent %.2f" % (msg_count, speed, comp_kbps, saturation_pct))
diff --git a/tests/automated/6_wifi_udp.py b/tests/automated/6_wifi_udp.py
deleted file mode 100644
index bee5130cc..000000000
--- a/tests/automated/6_wifi_udp.py
+++ /dev/null
@@ -1,73 +0,0 @@
-import sys
-import time
-from .helpers import start_heartbeat_thread, reset_pandas, time_many_sends, connect_wifi, test_white, panda_type_to_serial
-from panda import Panda, PandaWifiStreaming
-from nose.tools import assert_less, assert_greater
-
-# Reset the pandas before running tests
-def aaaa_reset_before_tests():
- reset_pandas()
-
-@test_white
-@panda_type_to_serial
-def test_udp_doesnt_drop(serials=None):
- connect_wifi(serials[0])
-
- p = Panda(serials[0])
-
- # Start heartbeat
- start_heartbeat_thread(p)
-
- p.set_safety_mode(Panda.SAFETY_ALLOUTPUT)
- p.set_can_loopback(True)
-
- pwifi = PandaWifiStreaming()
- while 1:
- if len(pwifi.can_recv()) == 0:
- break
-
- for msg_count in [1, 100]:
- saturation_pcts = []
- for i in range({1: 0x80, 100: 0x20}[msg_count]):
- pwifi.kick()
-
- speed = 500
- p.set_can_speed_kbps(0, speed)
- comp_kbps = time_many_sends(p, 0, pwifi, msg_count=msg_count, msg_id=0x100 + i)
- saturation_pct = (comp_kbps / speed) * 100.0
-
- if msg_count == 1:
- sys.stdout.write(".")
- sys.stdout.flush()
- else:
- print("UDP WIFI loopback %d messages at speed %d, comp speed is %.2f, percent %.2f" % (msg_count, speed, comp_kbps, saturation_pct))
- assert_greater(saturation_pct, 20) # sometimes the wifi can be slow...
- assert_less(saturation_pct, 100)
- saturation_pcts.append(saturation_pct)
- if len(saturation_pcts) > 0:
- assert_greater(sum(saturation_pcts) / len(saturation_pcts), 60)
-
- time.sleep(5)
- usb_ok_cnt = 0
- REQ_USB_OK_CNT = 500
- st = time.time()
- msg_id = 0x1bb
- bus = 0
- last_missing_msg = 0
- while usb_ok_cnt < REQ_USB_OK_CNT and (time.time() - st) < 40:
- p.can_send(msg_id, "message", bus)
- time.sleep(0.01)
- r = [1]
- missing = True
- while len(r) > 0:
- r = p.can_recv()
- r = [x for x in r if x[3] == bus and x[0] == msg_id]
- if len(r) > 0:
- missing = False
- usb_ok_cnt += len(r)
- if missing:
- last_missing_msg = time.time()
- et = time.time() - st
- last_missing_msg = last_missing_msg - st
- print("waited {} for panda to recv can on usb, {} msgs, last missing at {}".format(et, usb_ok_cnt, last_missing_msg))
- assert usb_ok_cnt >= REQ_USB_OK_CNT, "Unable to recv can on USB after UDP"
diff --git a/tests/automated/helpers.py b/tests/automated/helpers.py
index dbe9e7218..671e43be5 100644
--- a/tests/automated/helpers.py
+++ b/tests/automated/helpers.py
@@ -8,7 +8,6 @@ from panda_jungle import PandaJungle # pylint: disable=import-error
from nose.tools import assert_equal
from parameterized import parameterized, param
from .timeout import run_with_timeout
-from .wifi_helpers import _connect_wifi
SPEED_NORMAL = 500
SPEED_GMLAN = 33.3
@@ -70,13 +69,6 @@ test_uno = parameterized([
param(panda_type=Panda.HW_TYPE_UNO)
])
-def connect_wifi(serial=None):
- p = Panda(serial=serial)
- p.set_esp_power(True)
- dongle_id, pw = p.get_serial()
- assert(dongle_id.isalnum())
- _connect_wifi(dongle_id, pw)
-
def time_many_sends(p, bus, p_recv=None, msg_count=100, msg_id=None, two_pandas=False):
if p_recv == None:
p_recv = p
diff --git a/tests/automated/wifi_helpers.py b/tests/automated/wifi_helpers.py
deleted file mode 100644
index f92aee970..000000000
--- a/tests/automated/wifi_helpers.py
+++ /dev/null
@@ -1,90 +0,0 @@
-import os
-import sys
-import time
-import subprocess
-import requests
-from panda import Panda
-FNULL = open(os.devnull, 'w')
-def _connect_wifi(dongle_id, pw, insecure_okay=False):
- ssid = "panda-" + dongle_id
-
- r = subprocess.call(["ping", "-W", "4", "-c", "1", "192.168.0.10"], stdout=FNULL, stderr=subprocess.STDOUT)
- if not r:
- # Can already ping, try connecting on wifi
- try:
- p = Panda("WIFI")
- p.get_serial()
- print("Already connected")
- return
- except:
- pass
-
- print("WIFI: connecting to %s" % ssid)
-
- while 1:
- if sys.platform == "darwin":
- os.system("networksetup -setairportnetwork en0 %s %s" % (ssid, pw))
- else:
- wlan_interface = subprocess.check_output(["sh", "-c", "iw dev | awk '/Interface/ {print $2}'"]).strip().decode('utf8')
- cnt = 0
- MAX_TRIES = 10
- while cnt < MAX_TRIES:
- print("WIFI: scanning %d" % cnt)
- os.system("iwlist %s scanning > /dev/null" % wlan_interface)
- os.system("nmcli device wifi rescan")
- wifi_networks = [x.decode("utf8") for x in subprocess.check_output(["nmcli", "dev", "wifi", "list"]).split(b"\n")]
- wifi_scan = [x for x in wifi_networks if ssid in x]
- if len(wifi_scan) != 0:
- break
- time.sleep(0.1)
- # MAX_TRIES tries, ~10 seconds max
- cnt += 1
- assert cnt < MAX_TRIES
- if "-pair" in wifi_scan[0]:
- os.system("nmcli d wifi connect %s-pair" % (ssid))
- connect_cnt = 0
- MAX_TRIES = 100
- while connect_cnt < MAX_TRIES:
- connect_cnt += 1
- r = subprocess.call(["ping", "-W", "4", "-c", "1", "192.168.0.10"], stdout=FNULL, stderr=subprocess.STDOUT)
- if r:
- print("Waiting for panda to ping...")
- time.sleep(0.5)
- else:
- break
- if insecure_okay:
- break
- # fetch webpage
- print("connecting to insecure network to secure")
- try:
- r = requests.get("http://192.168.0.10/")
- except requests.ConnectionError:
- r = requests.get("http://192.168.0.10/")
- assert r.status_code == 200
-
- print("securing")
- try:
- r = requests.get("http://192.168.0.10/secure", timeout=0.01)
- except requests.exceptions.Timeout:
- print("timeout http request to secure")
- pass
- else:
- ret = os.system("nmcli d wifi connect %s password %s" % (ssid, pw))
- if os.WEXITSTATUS(ret) == 0:
- #check ping too
- ping_ok = False
- connect_cnt = 0
- MAX_TRIES = 10
- while connect_cnt < MAX_TRIES:
- connect_cnt += 1
- r = subprocess.call(["ping", "-W", "4", "-c", "1", "192.168.0.10"], stdout=FNULL, stderr=subprocess.STDOUT)
- if r:
- print("Waiting for panda to ping...")
- time.sleep(0.1)
- else:
- ping_ok = True
- break
- if ping_ok:
- break
-
- # TODO: confirm that it's connected to the right panda
diff --git a/tests/build/Dockerfile.panda_esp b/tests/build/Dockerfile.panda_esp
deleted file mode 100644
index c4b49270f..000000000
--- a/tests/build/Dockerfile.panda_esp
+++ /dev/null
@@ -1,23 +0,0 @@
-FROM ubuntu:16.04
-
-RUN apt-get update && apt-get install -y gcc-arm-none-eabi libnewlib-arm-none-eabi python python-pip gcc g++ git autoconf gperf bison flex automake texinfo wget help2man gawk libtool libtool-bin ncurses-dev unzip unrar-free libexpat-dev sed bzip2 locales curl zlib1g-dev libffi-dev libssl-dev python3 python3-pip
-
-RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen
-ENV LANG en_US.UTF-8
-ENV LANGUAGE en_US:en
-ENV LC_ALL en_US.UTF-8
-
-RUN pip3 install pycryptodome==3.9.8
-
-# Build esp toolchain
-RUN mkdir -p /panda/boardesp
-WORKDIR /panda/boardesp
-RUN git clone --recursive https://github.com/pfalcon/esp-open-sdk.git
-WORKDIR /panda/boardesp/esp-open-sdk
-RUN git checkout 03f5e898a059451ec5f3de30e7feff30455f7ce
-COPY ./boardesp/python2_make.py /panda/boardesp/esp-open-sdk
-RUN python2 python2_make.py "CT_ALLOW_BUILD_AS_ROOT_SURE=1 make STANDALONE=y"
-
-COPY . /panda
-
-WORKDIR /panda
diff --git a/tests/disable_esp.py b/tests/disable_esp.py
deleted file mode 100755
index 1194c2e6d..000000000
--- a/tests/disable_esp.py
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/usr/bin/env python3
-from panda import Panda
-Panda().set_esp_power(False)
diff --git a/tests/elm_wifi.py b/tests/elm_wifi.py
deleted file mode 100644
index 0e0ef5214..000000000
--- a/tests/elm_wifi.py
+++ /dev/null
@@ -1,669 +0,0 @@
-# flake8: noqa
-
-import os
-import sys
-import time
-import socket
-import select
-import struct
-
-sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
-sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", ".."))
-from panda import Panda
-from panda.tests import elm_car_simulator
-
-def elm_connect():
- s = socket.create_connection(("192.168.0.10", 35000))
- s.setblocking(0)
- return s
-
-def read_or_fail(s):
- ready = select.select([s], [], [], 4)
- assert ready[0], "Socket did not receive data within the timeout duration."
- return s.recv(1000)
-
-def sendrecv(s, dat):
- s.send(dat)
- return read_or_fail(s)
-
-def send_compare(s, dat, ret, timeout=4):
- s.send(dat)
- res = b''
- while ret.startswith(res) and ret != res:
- print("Waiting")
- ready = select.select([s], [], [], timeout)
- if not ready[0]:
- print("current recv data:", repr(res))
- break
- res += s.recv(1000)
- #print("final recv data: '%s'" % repr(res))
- assert ret == res # , "Data does not agree (%s) (%s)"%(repr(ret), repr(res))
-
-def sync_reset(s):
- s.send("ATZ\r")
- res = b''
- while not res.endswith("ELM327 v1.5\r\r>"):
- res += read_or_fail(s)
- print("Reset response is '%s'" % repr(res))
-
-def test_reset():
- s = socket.create_connection(("192.168.0.10", 35000))
- s.setblocking(0)
-
- try:
- sync_reset(s)
- finally:
- s.close()
-
-def test_elm_cli():
- s = elm_connect()
-
- try:
- sync_reset(s)
-
- send_compare(s, b'ATI\r', b'ATI\rELM327 v1.5\r\r>')
-
- #Test Echo Off
- #Expected to be misimplimentation, but this is how the reference device behaved.
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Here is the odd part
- send_compare(s, b'ATE0\r', b'OK\r\r>') # Should prob show this immediately
- send_compare(s, b'ATI\r', b'ELM327 v1.5\r\r>')
-
- #Test Newline On
- send_compare(s, b'ATL1\r', b'OK\r\n\r\n>')
- send_compare(s, b'ATI\r', b'ELM327 v1.5\r\n\r\n>')
- send_compare(s, b'ATL0\r', b'OK\r\r>')
- send_compare(s, b'ATI\r', b'ELM327 v1.5\r\r>')
-
- send_compare(s, b'ATI\r', b'ELM327 v1.5\r\r>') # Test repeat command no echo
- send_compare(s, b'\r', b'ELM327 v1.5\r\r>')
-
- send_compare(s, b'aTi\r', b'ELM327 v1.5\r\r>') # Test different case
-
- send_compare(s, b' a T i\r', b'ELM327 v1.5\r\r>') # Test with white space
-
- send_compare(s, b'ATCATHAT\r', b'?\r\r>') # Test Invalid AT command
-
- send_compare(s, b'01 00 00 00 00 00 00 00\r', b'?\r\r>') # Test Invalid (too long) OBD command
- send_compare(s, b'01 GZ\r', b'?\r\r>') # Test Invalid (Non hex chars) OBD command
- finally:
- s.close()
-
-def test_elm_setget_protocol():
- s = elm_connect()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
-
- send_compare(s, b'ATSP0\r', b"OK\r\r>") # Set auto
- send_compare(s, b'ATDP\r', b"AUTO\r\r>")
- send_compare(s, b'ATDPN\r', b"A0\r\r>")
-
- send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set protocol
- send_compare(s, b'ATDP\r', b"ISO 15765-4 (CAN 11/500)\r\r>")
- send_compare(s, b'ATDPN\r', b"6\r\r>")
-
- send_compare(s, b'ATSPA6\r', b"OK\r\r>") # Set auto with protocol default
- send_compare(s, b'ATDP\r', b"AUTO, ISO 15765-4 (CAN 11/500)\r\r>")
- send_compare(s, b'ATDPN\r', b"A6\r\r>")
-
- send_compare(s, b'ATSP7\r', b"OK\r\r>")
- send_compare(s, b'ATDP\r', b"ISO 15765-4 (CAN 29/500)\r\r>")
- send_compare(s, b'ATDPN\r', b"7\r\r>") # Test Does not accept invalid protocols
- send_compare(s, b'ATSPD\r', b"?\r\r>")
- send_compare(s, b'ATDP\r', b"ISO 15765-4 (CAN 29/500)\r\r>")
- send_compare(s, b'ATDPN\r', b"7\r\r>")
- finally:
- s.close()
-
-def test_elm_protocol_failure():
- s = elm_connect()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
-
- send_compare(s, b'ATSP0\r', b"OK\r\r>")
- send_compare(s, b'0100\r', b"SEARCHING...\rUNABLE TO CONNECT\r\r>", timeout=10)
-
- send_compare(s, b'ATSP1\r', b"OK\r\r>")
- send_compare(s, b'0100\r', b"NO DATA\r\r>")
-
- send_compare(s, b'ATSP2\r', b"OK\r\r>")
- send_compare(s, b'0100\r', b"NO DATA\r\r>")
-
- send_compare(s, b'ATSP3\r', b"OK\r\r>")
- send_compare(s, b'0100\r', b"BUS INIT: ...ERROR\r\r>")
-
- send_compare(s, b'ATSP4\r', b"OK\r\r>")
- send_compare(s, b'0100\r', b"BUS INIT: ...ERROR\r\r>")
-
- send_compare(s, b'ATSP5\r', b"OK\r\r>")
- send_compare(s, b'0100\r', b"BUS INIT: ERROR\r\r>")
-
- #send_compare(s, b'ATSP6\r', b"OK\r\r>")
- #send_compare(s, b'0100\r', b"NO DATA\r\r>")
- #
- #send_compare(s, b'ATSP7\r', b"OK\r\r>")
- #send_compare(s, b'0100\r', b"NO DATA\r\r>")
- #
- #send_compare(s, b'ATSP8\r', b"OK\r\r>")
- #send_compare(s, b'0100\r', b"NO DATA\r\r>")
- #
- #send_compare(s, b'ATSP9\r', b"OK\r\r>")
- #send_compare(s, b'0100\r', b"NO DATA\r\r>")
- #
- #send_compare(s, b'ATSPA\r', b"OK\r\r>")
- #send_compare(s, b'0100\r', b"NO DATA\r\r>")
- #
- #send_compare(s, b'ATSPB\r', b"OK\r\r>")
- #send_compare(s, b'0100\r', b"NO DATA\r\r>")
- #
- #send_compare(s, b'ATSPC\r', b"OK\r\r>")
- #send_compare(s, b'0100\r', b"NO DATA\r\r>")
- finally:
- s.close()
-
-def test_elm_protocol_autodetect_ISO14230_KWP_FAST():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, can=False) # , silent=True)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATH0\r', b'OK\r\r>') # Headers ON
- send_compare(s, b'ATS0\r', b"OK\r\r>")
-
- send_compare(s, b'ATSP0\r', b"OK\r\r>")
- send_compare(s, b'010D\r', b"SEARCHING...\r410D53\r\r>", timeout=10)
- send_compare(s, b'ATDPN\r', b"A5\r\r>")
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_basic_send_lin():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, can=False) # , silent=True)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATSP5\r', b"ATSP5\rOK\r\r>") # Set Proto
-
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'0100\r', b"BUS INIT: OK\r41 00 FF FF FF FE \r\r>")
- send_compare(s, b'010D\r', b"41 0D 53 \r\r>")
-
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces Off
- send_compare(s, b'0100\r', b"4100FFFFFFFE\r\r>")
- send_compare(s, b'010D\r', b"410D53\r\r>")
-
- send_compare(s, b'ATH1\r', b'OK\r\r>') # Spaces Off Headers On
- send_compare(s, b'0100\r', b"86F1104100FFFFFFFEC3\r\r>")
- send_compare(s, b'010D\r', b"83F110410D5325\r\r>")
-
- send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces On Headers On
- send_compare(s, b'0100\r', b"86 F1 10 41 00 FF FF FF FE C3 \r\r>")
- send_compare(s, b'010D\r', b"83 F1 10 41 0D 53 25 \r\r>")
-
- send_compare(s, b'1F00\r', b"NO DATA\r\r>") # Unhandled msg, no response.
-
- # Repeat last check to see if it still works after NO DATA was received
- send_compare(s, b'0100\r', b"86 F1 10 41 00 FF FF FF FE C3 \r\r>")
- send_compare(s, b'010D\r', b"83 F1 10 41 0D 53 25 \r\r>")
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_send_lin_multiline_msg():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, can=False)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATSP5\r', b"OK\r\r>") # Set Proto
-
- send_compare(s, b'0902\r', # headers OFF, Spaces ON
- b"BUS INIT: OK\r"
- b"49 02 01 00 00 00 31 \r"
- b"49 02 02 44 34 47 50 \r"
- b"49 02 03 30 30 52 35 \r"
- b"49 02 04 35 42 31 32 \r"
- b"49 02 05 33 34 35 36 \r\r>")
-
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF
- send_compare(s, b'0902\r', # Headers OFF, Spaces OFF
- b"49020100000031\r"
- b"49020244344750\r"
- b"49020330305235\r"
- b"49020435423132\r"
- b"49020533343536\r\r>")
-
- send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON
- send_compare(s, b'0902\r', # Headers ON, Spaces OFF
- b"87F1104902010000003105\r"
- b"87F11049020244344750E4\r"
- b"87F11049020330305235BD\r"
- b"87F11049020435423132B1\r"
- b"87F11049020533343536AA\r\r>")
-
- send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces ON
- send_compare(s, b'0902\r', # Headers ON, Spaces ON
- b"87 F1 10 49 02 01 00 00 00 31 05 \r"
- b"87 F1 10 49 02 02 44 34 47 50 E4 \r"
- b"87 F1 10 49 02 03 30 30 52 35 BD \r"
- b"87 F1 10 49 02 04 35 42 31 32 B1 \r"
- b"87 F1 10 49 02 05 33 34 35 36 AA \r\r>")
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_send_lin_multiline_msg_throughput():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, can=False, silent=True)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATSP5\r', b"ATSP5\rOK\r\r>") # Set Proto
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF
- send_compare(s, b'ATH0\r', b'OK\r\r>') # Headers OFF
-
- send_compare(s, b'09fc\r', # headers OFF, Spaces OFF
- b"BUS INIT: OK\r" +
- b''.join((b'49FC' + hex(num + 1)[2:].upper().zfill(2) +
- b'AAAA' + hex(num + 1)[2:].upper().zfill(4) + b'\r'
- for num in range(80))) +
- b"\r>",
- timeout=10
- )
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_panda_safety_mode_KWPFast():
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- p_car = Panda(serial) # Configure this so the messages will send
- p_car.set_safety_mode(Panda.SAFETY_ALLOUTPUT)
- p_car.kline_drain()
-
- p_elm = Panda("WIFI")
- p_elm.set_safety_mode(Panda.SAFETY_ELM327)
-
- def get_checksum(dat):
- result = 0
- result += sum(map(ord, dat)) if isinstance(b'dat', str) else sum(dat)
- return struct.pack("B", result % 0x100)
-
- def timed_recv_check(p, bus, goodmsg):
- t = time.time()
- msg = bytearray()
-
- while time.time() - t < 0.5 and len(msg) != len(goodmsg):
- msg += p._handle.controlRead(Panda.REQUEST_OUT, 0xe0, bus, 0, len(goodmsg) - len(msg))
- #print("Received", repr(msg))
- if msg == goodmsg:
- return True
- time.sleep(0.01)
- return False
-
- def kline_send(p, x, bus=2):
- p.kline_drain(bus=bus)
- p._handle.bulkWrite(2, bytes([bus]) + x)
- return timed_recv_check(p, bus, x)
-
- def did_send(priority, toaddr, fromaddr, dat, bus=2, checkbyte=None):
- msgout = struct.pack("BBB", priority | len(dat), toaddr, fromaddr) + dat
- msgout += get_checksum(msgout) if checkbyte is None else checkbyte
- print("Sending", hex(priority), hex(toaddr), hex(fromaddr), repr(msgout))
-
- if not kline_send(p_elm, msgout, bus=bus):
- return False
- return timed_recv_check(p_car, bus, msgout)
-
- assert not did_send(0xC0, 0x33, 0xF1, b'\x01\x0F', bus=3) # wrong bus
- assert not did_send(0xC0, 0x33, 0xF1, b'') # wrong length
- assert not did_send(0xB0, 0x33, 0xF1, b'\x01\x0E') # bad priority
- assert not did_send(0xC0, 0x00, 0xF1, b'\x01\x0D') # bad addr
- assert not did_send(0xC0, 0x33, 0x00, b'\x01\x0C') # bad addr
-
- assert did_send(0xC0, 0x33, 0xF1, b'\x01\x0B') # good! (obd func req)
-
-def test_elm_lin_keepalive():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, can=False, silent=True)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATSP5\r', b"ATSP5\rOK\r\r>") # Set Proto
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF
- send_compare(s, b'ATH0\r', b'OK\r\r>') # Headers OFF
-
- send_compare(s, b'0100\r', b"BUS INIT: OK\r4100FFFFFFFE\r\r>")
- assert sim.lin_active
- time.sleep(6)
- assert sim.lin_active
-
- send_compare(s, b'ATPC\r', b"OK\r\r>") # STOP KEEPALIVE
- assert sim.lin_active
- time.sleep(6)
- assert not sim.lin_active
-
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-#////////////
-def test_elm_protocol_autodetect_ISO15765():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, lin=False, silent=True)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON
- send_compare(s, b'ATS0\r', b"OK\r\r>")
-
- sim.can_mode_11b()
- send_compare(s, b'ATSP0\r', b"OK\r\r>")
- send_compare(s, b'010D\r', b"SEARCHING...\r7E803410D53\r\r>", timeout=10)
- send_compare(s, b'ATDPN\r', b"A6\r\r>")
-
- sim.can_mode_29b()
- send_compare(s, b'ATSP0\r', b"OK\r\r>")
- send_compare(s, b'010D\r', b"SEARCHING...\r18DAF11003410D53\r\r>", timeout=10)
- send_compare(s, b'ATDPN\r', b"A7\r\r>")
-
- sim.change_can_baud(250)
-
- sim.can_mode_11b()
- send_compare(s, b'ATSP0\r', b"OK\r\r>")
- send_compare(s, b'010D\r', b"SEARCHING...\r7E803410D53\r\r>", timeout=10)
- send_compare(s, b'ATDPN\r', b"A8\r\r>")
-
- sim.can_mode_29b()
- send_compare(s, b'ATSP0\r', b"OK\r\r>")
- send_compare(s, b'010D\r', b"SEARCHING...\r18DAF11003410D53\r\r>", timeout=10)
- send_compare(s, b'ATDPN\r', b"A9\r\r>")
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_basic_send_can():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, lin=False, silent=True)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATSP6\r', b"ATSP6\rOK\r\r>") # Set Proto
-
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'0100\r', b"41 00 FF FF FF FE \r\r>")
- send_compare(s, b'010D\r', b"41 0D 53 \r\r>")
-
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces Off
- send_compare(s, b'0100\r', b"4100FFFFFFFE\r\r>")
- send_compare(s, b'010D\r', b"410D53\r\r>")
-
- send_compare(s, b'ATH1\r', b'OK\r\r>') # Spaces Off Headers On
- send_compare(s, b'0100\r', b"7E8064100FFFFFFFE\r\r>")
- send_compare(s, b'010D\r', b"7E803410D53\r\r>")
-
- send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces On Headers On
- send_compare(s, b'0100\r', b"7E8 06 41 00 FF FF FF FE \r\r>")
- send_compare(s, b'010D\r', b"7E8 03 41 0D 53 \r\r>")
-
- send_compare(s, b'1F00\r', b"NO DATA\r\r>") # Unhandled msg, no response.
-
- # Repeat last check to see if it still works after NO DATA was received
- send_compare(s, b'0100\r', b"7E8 06 41 00 FF FF FF FE \r\r>")
- send_compare(s, b'010D\r', b"7E8 03 41 0D 53 \r\r>")
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_send_can_multimsg():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, lin=False)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces OFF
- send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON
-
- send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/500)
- sim.can_add_extra_noise(b'\x03\x41\x0D\xFA', addr=0x7E9) # Inject message into the stream
- send_compare(s, b'010D\r',
- b"7E8 03 41 0D 53 \r"
- b"7E9 03 41 0D FA \r\r>") # Check it was ignored.
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_can_check_mode_pid():
- """The ability to correctly filter out messages with the wrong PID is not
- implemented correctly in the reference device."""
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, lin=False)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF
- send_compare(s, b'ATH0\r', b'OK\r\r>') # Headers OFF
-
- send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/500)
- sim.can_add_extra_noise(b'\x03\x41\x0E\xFA') # Inject message into the stream
- send_compare(s, b'010D\r', b"410D53\r\r>") # Check it was ignored.
- send_compare(s, b'0100\r', b"4100FFFFFFFE\r\r>") # Check it was ignored again.
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_send_can_multiline_msg():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, lin=False)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATSP6\r', b"ATSP6\rOK\r\r>") # Set Proto
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
-
- send_compare(s, b'0902\r', # headers OFF, Spaces ON
- b"014 \r"
- b"0: 49 02 01 31 44 34 \r"
- b"1: 47 50 30 30 52 35 35 \r"
- b"2: 42 31 32 33 34 35 36 \r\r>")
-
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF
- send_compare(s, b'0902\r', # Headers OFF, Spaces OFF
- b"014\r"
- b"0:490201314434\r"
- b"1:47503030523535\r"
- b"2:42313233343536\r\r>")
-
- send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON
- send_compare(s, b'0902\r', # Headers ON, Spaces OFF
- b"7E81014490201314434\r"
- b"7E82147503030523535\r"
- b"7E82242313233343536\r\r>")
-
- send_compare(s, b'ATS1\r', b'OK\r\r>') # Spaces ON
- send_compare(s, b'0902\r', # Headers ON, Spaces ON
- b"7E8 10 14 49 02 01 31 44 34 \r"
- b"7E8 21 47 50 30 30 52 35 35 \r"
- b"7E8 22 42 31 32 33 34 35 36 \r\r>")
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_send_can_multiline_msg_throughput():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, lin=False, silent=True)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATSP6\r', b"ATSP6\rOK\r\r>") # Set Proto
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF
- send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON
-
- rows = 584
- send_compare(s, b'09ff\r', # headers ON, Spaces OFF
- ("7E8" + "1" + hex((rows * 7) + 6)[2:].upper().zfill(3) + "49FF01" + "AA0000\r" +
- "".join(
- ("7E82" + hex((num + 1) % 0x10)[2:].upper() + ("AA" * 5) +
- hex(num + 1)[2:].upper().zfill(4) + "\r" for num in range(rows))
- ) + "\r>").encode(),
- timeout=10
- )
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_interrupted_obd_cmd_resets_state():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, lin=False, silent=True)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF
- s.send(b"09fd\r")
- ready = select.select([s], [], [], 4)
- assert ready[0], "Socket did not receive data within the timeout duration."
- s.send(b"ATI\r")
-
- assert b"236\r0:49FD01AAAAAA\r" in s.recv(10000)
-
- #Will likely have to be improved to scan for STOPPED if the FW gets more responsive.
- ready = select.select([s], [], [], 4)
- assert ready[0], "Socket did not receive data within the timeout duration."
-
- assert b"STOPPED" in s.recv(10000)
-
- sim.set_enable(False)
- send_compare(s, b'09fd\r', b"NO DATA\r\r>")
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_can_baud():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- sim = elm_car_simulator.ELMCarSimulator(serial, lin=False)
- sim.start()
-
- try:
- sync_reset(s)
- send_compare(s, b'ATE0\r', b'ATE0\rOK\r\r>') # Echo OFF
- send_compare(s, b'ATS0\r', b'OK\r\r>') # Spaces OFF
- send_compare(s, b'ATH1\r', b'OK\r\r>') # Headers ON
-
- send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/500)
- send_compare(s, b'0100\r', b"7E8064100FFFFFFFE\r\r>")
-
- send_compare(s, b'ATSP8\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/250)
- send_compare(s, b'0100\r', b"CAN ERROR\r\r>")
-
- sim.change_can_baud(250)
-
- send_compare(s, b'ATSP6\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/500)
- send_compare(s, b'0100\r', b"CAN ERROR\r\r>")
-
- send_compare(s, b'ATSP8\r', b"OK\r\r>") # Set Proto ISO 15765-4 (CAN 11/250)
- send_compare(s, b'0100\r', b"7E8064100FFFFFFFE\r\r>")
- finally:
- sim.stop()
- sim.join()
- s.close()
-
-def test_elm_panda_safety_mode_ISO15765():
- s = elm_connect()
- serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None
- p_car = Panda(serial) # Configure this so the messages will send
- p_car.set_can_speed_kbps(0, 500)
- p_car.set_safety_mode(Panda.SAFETY_ALLOUTPUT)
-
- p_elm = Panda("WIFI")
- p_elm.set_safety_mode(Panda.SAFETY_ELM327)
-
- #sim = elm_car_simulator.ELMCarSimulator(serial, lin=False)
- #sim.start()
-
- def did_send(p, addr, dat, bus):
- p.can_send(addr, dat, bus)
- t = time.time()
- while time.time() - t < 0.5:
- msg = p.can_recv()
- for addrin, _, datin, busin in msg:
- if (0x80 | bus) == busin and addr == addrin and datin == dat:
- return True
- time.sleep(0.01)
- return False
-
- try:
- sync_reset(s) # Reset elm (which requests the ELM327 safety mode)
-
- #29 bit
- assert not did_send(p_elm, 0x18DB33F1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 1) # wrong canid
- assert not did_send(p_elm, 0x18DB33F1, b'\x02\x01\x00', 0) # wrong length
- assert not did_send(p_elm, 0x10000000, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # bad addr
- assert not did_send(p_elm, 0x18DAF133, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # bad addr (phy addr)
- assert not did_send(p_elm, 0x18DAF000, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # bad addr
- assert not did_send(p_elm, 0x18DAF1F3, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # bad addr! (phys rsp to elm)
-
- assert did_send(p_elm, 0x18DB33F1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # good! (obd func req)
- assert did_send(p_elm, 0x18DA10F1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # good! (phys response)
-
- #11 bit
- assert not did_send(p_elm, 0X7DF, b'\x02\x01\x00\x00\x00\x00\x00\x00', 1) # wrong canid
- assert not did_send(p_elm, 0X7DF, b'\x02\x01\x00', 0) # wrong length
- assert not did_send(p_elm, 0xAA, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # bad addr
- assert not did_send(p_elm, 0x7DA, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # bad addr (phy addr)
- assert not did_send(p_elm, 0x7E8, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # bad addr (sending 'response')
-
- assert did_send(p_elm, 0x7DF, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # good! (obd func req)
- assert did_send(p_elm, 0x7E1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) # good! (phys response)
-
- finally:
- s.close()