#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "intelhex/intelhexclass.h" /** the version string of the program. */ const char *argp_program_version = "eBUS adapter PIC firmware loader"; /** the documentation of the program. */ static const char argpdoc[] = "A tool for loading firmware to the eBUS adapter PIC." "\vPORT is the serial port to use (e.g./dev/ttyUSB0)"; static const char argpargsdoc[] = "PORT"; /** the definition of the known program arguments. */ static const struct argp_option argpoptions[] = { {"verbose", 'v', nullptr, 0, "enable verbose output", 0 }, {"dhcp", 'd', nullptr, 0, "set IP address to DHCP", 0 }, {"ip", 'i', "IP", 0, "set IP address (e.g. 192.168.0.10)", 0 }, {"mask", 'm', "MASK", 0, "set IP mask (e.g. 24)", 0 }, {"macip", 'M', nullptr, 0, "set the MAC address suffix from the IP address", 0 }, {"flash", 'f', "FILE", 0, "flash the FILE to the device", 0 }, {"reset", 'r', nullptr, 0, "reset the device at the end on success", 0 }, {"speed", 's', nullptr, 0, "enable high speed transfer", 0 }, {nullptr, 0, nullptr, 0, nullptr, 0 }, }; static bool verbose = false; static bool setDhcp = false; static bool setIp = false; static uint8_t setIpAddress[] = {0, 0, 0, 0}; static bool setMacFromIp = false; static bool setMask = false; static uint8_t setMaskLen = 0x1f; static char* flashFile = nullptr; static bool reset = false; static bool highSpeed = false; bool parseByte(const char *arg, uint8_t minValue, uint8_t maxValue, uint8_t *result) { char* strEnd = nullptr; unsigned long value = 0; strEnd = nullptr; value = strtoul(arg, &strEnd, 10); if (strEnd == nullptr || strEnd == arg || *strEnd != 0) { return false; } if (valuemaxValue) { return false; } *result = (uint8_t)value; return true; } bool parseShort(const char *arg, uint16_t minValue, uint16_t maxValue, uint16_t *result) { char* strEnd = nullptr; unsigned long value = 0; strEnd = nullptr; value = strtoul(arg, &strEnd, 10); if (strEnd == nullptr || strEnd == arg || *strEnd != 0) { return false; } if (valuemaxValue) { return false; } *result = (uint16_t)value; return true; } error_t parse_opt(int key, char *arg, struct argp_state *state) { char *ip = nullptr, *part = nullptr; int pos = 0, sum = 0; struct stat st; switch (key) { case 'v': // --verbose verbose = true; break; case 'd': // --dhcp if (setIp || setMask) { argp_error(state, "either DHCP or IP address is needed"); return EINVAL; } setDhcp = true; break; case 'i': // --ip=192.168.0.10 if (arg == nullptr || arg[0] == 0) { argp_error(state, "invalid IP address"); return EINVAL; } if (setDhcp) { argp_error(state, "either DHCP or IP address is needed"); return EINVAL; } ip = strdup(arg); part = strtok(ip, "."); for (pos=0; part && pos<4; pos++) { if (!parseByte(part, 0, 255, setIpAddress+pos)) { break; } sum += setIpAddress[pos]; part = strtok(nullptr, "."); } free(ip); if (pos!=4 || part || sum==0) { argp_error(state, "invalid IP address"); return EINVAL; } setIp = true; break; case 'm': if (arg == nullptr || arg[0] == 0) { argp_error(state, "invalid IP mask"); return EINVAL; } if (setDhcp) { argp_error(state, "either DHCP or IP address is needed"); return EINVAL; } if (!parseByte(arg, 0, 0x1e, &setMaskLen)) { argp_error(state, "invalid IP mask"); return EINVAL; } setMask = true; break; case 'M': setMacFromIp = true; break; case 'f': if (arg == nullptr || arg[0] == 0 || stat(arg, &st) != 0 || !S_ISREG(st.st_mode)) { argp_error(state, "invalid flash file"); return EINVAL; } flashFile = arg; break; case 'r': reset = true; break; case 's': highSpeed = true; break; default: return ARGP_ERR_UNKNOWN; } return 0; } // START: copy from generated bootloader #define WRITE_FLASH_BLOCKSIZE 32 #define ERASE_FLASH_BLOCKSIZE 32 #define END_FLASH 0x4000 // Frame Format // // [<...DATA...>] // These values are negative because the FSR is set to PACKET_DATA to minimize FSR reloads. typedef union { struct __attribute__((__packed__)) { uint8_t command; uint16_t data_length; uint8_t EE_key_1; uint8_t EE_key_2; uint8_t address_L; uint8_t address_H; uint8_t address_U; uint8_t address_unused; uint8_t data[2*WRITE_FLASH_BLOCKSIZE]; }; uint8_t buffer[2*WRITE_FLASH_BLOCKSIZE+9]; }frame_t; #define STX 0x55 #define READ_VERSION 0 #define READ_FLASH 1 #define WRITE_FLASH 2 #define ERASE_FLASH 3 #define READ_EE_DATA 4 #define WRITE_EE_DATA 5 #define READ_CONFIG 6 #define WRITE_CONFIG 7 #define CALC_CHECKSUM 8 #define RESET_DEVICE 9 #define CALC_CRC 10 #define MINOR_VERSION 0x08 // Version #define MAJOR_VERSION 0x00 //#define STX 0x55 // Actually code 0x55 is 'U' But this is what the autobaud feature of the PIC16F1 EUSART is looking for #define ERROR_ADDRESS_OUT_OF_RANGE 0xFE #define ERROR_INVALID_COMMAND 0xFF #define COMMAND_SUCCESS 0x01 // END: copy from generated bootloader #define FRAME_HEADER_LEN 9 #define FRAME_MAX_LEN (FRAME_HEADER_LEN+2*WRITE_FLASH_BLOCKSIZE) #define BAUDRATE_NORMAL B115200 #define BAUDRATE_HIGH B921600 #define WAIT_BYTE_TRANSFERRED_MILLIS 200 #define WAIT_BITRATE_DETECTION_MICROS 100 #define WAIT_RESPONSE_TIMEOUT_MILLIS 100 // size of flash in bytes #define END_FLASH_BYTES (END_FLASH*2) // size of boot block in words #define END_BOOT 0x0400 // size of boot block in bytes #define END_BOOT_BYTES (END_BOOT*2) long long getTime() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec*1000+ts.tv_nsec/1000000; } ssize_t waitWrite(int fd, uint8_t *data, size_t len, int timeoutMillis) { int ret; struct pollfd pfd; pfd.fd = fd; pfd.events = POLLOUT | POLLERR | POLLHUP; ret = poll(&pfd, 1, timeoutMillis); if (ret >= 0 && pfd.revents & (POLLERR | POLLHUP)) { return -1; } if (ret <= 0) { return ret; } ret = write(fd, data, len); if (ret<0) { return ret; } #ifdef DEBUG_RAW std::cout<<"> "<(ret)<<"/"<(len)<<":"<(data[pos]); } std::cout<= 0 && pfd.revents & (POLLERR | POLLHUP)) { return -1; } if (ret <= 0) { return ret; } ret = read(fd, data, len); if (ret<0) { return ret; } #ifdef DEBUG_RAW std::cout<<"< "<(ret)<<"/"<(len)<<":"<(data[pos]); } std::cout<(ch) << std::endl; } return -1; } // read the answer from the device len = FRAME_HEADER_LEN; // start with the header itself for (size_t pos=0; pos(frame.data[2] | (frame.data[3] << 8)) << std::endl; } std::cout<<"Device ID: "<(frame.data[6] | (frame.data[7]<<8)); if (frame.data[6]==0xb0 && frame.data[7]==0x30) { std::cout<<" (PIC16F15356)"; } std::cout<(frame.data[10])<(frame.data[11])<(frame.data[12])<(frame.data[13])<(frame.data[14])<(frame.data[15])<(address)<<":"; } std::cout<<" "<(frame.data[pos++]); if (skipHigh) { pos++; } else if (pos(frame.data[pos++]); } address++; if ((pos%16)==0) { std::cout<(frame.command)<(frame.data_length)<(frame.address_H)<(frame.address_L); for (int pos = 0; pos(pos)<<":"<(frame.data[pos++]); pos++; } std::cout<>8)&0xff; ssize_t ret = sendReceiveFrame(fd, frame, 0, len); if (ret!=0) { return ret; } if (print) { printFrameData(frame, skipHigh); } if (storeData) { memcpy(storeData, frame.data, len); } return 0; } int writeConfig(int fd, uint16_t address, uint16_t len, uint8_t* data) { frame_t frame; memset(frame.buffer, 0, FRAME_MAX_LEN); frame.command = WRITE_CONFIG; frame.data_length = len; frame.EE_key_1 = 0x55; frame.EE_key_2 = 0xaa; frame.address_L = address&0xff; frame.address_H = (address>>8)&0xff; memcpy(frame.data, data, len); ssize_t ret = sendReceiveFrame(fd, frame, len, 1, 50); if (ret!=0) { return ret; } if (frame.data[0]!=COMMAND_SUCCESS) { return -1; } return 0; } int readFlash(int fd, uint16_t address, bool skipHigh=false, bool print=true, uint8_t* storeData=nullptr) { frame_t frame; memset(frame.buffer, 0, FRAME_MAX_LEN); frame.command = READ_FLASH; frame.data_length = 0x10; frame.address_L = address&0xff; frame.address_H = (address>>8)&0xff; ssize_t ret = sendReceiveFrame(fd, frame, 0, -1); if (ret!=0) { return ret; } if (print) { printFrameData(frame, skipHigh); } if (storeData) { memcpy(storeData, frame.data, 0x10); } return 0; } int writeFlash(int fd, uint16_t address, uint16_t len, uint8_t* data, bool hideErrors=false) { frame_t frame; memset(frame.buffer, 0, FRAME_MAX_LEN); frame.command = WRITE_FLASH; frame.data_length = len; frame.EE_key_1 = 0x55; frame.EE_key_2 = 0xaa; frame.address_L = address&0xff; frame.address_H = (address>>8)&0xff; memcpy(frame.data, data, len); ssize_t ret = sendReceiveFrame(fd, frame, len, 1, len*30, hideErrors); if (ret!=0) { return ret; } if (frame.data[0]!=COMMAND_SUCCESS) { return -1; } return 0; } int eraseFlash(int fd, uint16_t address, uint16_t len) { frame_t frame; memset(frame.buffer, 0, FRAME_MAX_LEN); frame.command = ERASE_FLASH; frame.data_length = (len+ERASE_FLASH_BLOCKSIZE-1)/ERASE_FLASH_BLOCKSIZE; frame.EE_key_1 = 0x55; frame.EE_key_2 = 0xaa; frame.address_L = address&0xff; frame.address_H = (address>>8)&0xff; ssize_t ret = sendReceiveFrame(fd, frame, 0, 1, frame.data_length*5); if (ret!=0) { return ret; } if (frame.data[0]!=COMMAND_SUCCESS) { return -frame.data[0]-1; } return 0; } int calcChecksum(int fd, uint16_t address, uint16_t len) { frame_t frame; memset(frame.buffer, 0, FRAME_MAX_LEN); frame.command = CALC_CHECKSUM; frame.data_length = len; frame.address_L = address&0xff; frame.address_H = (address>>8)&0xff; ssize_t ret = sendReceiveFrame(fd, frame, 0, 2, len*30); if (ret!=0) { return ret; } return frame.data[0] | (frame.data[1]<<8); } int resetDevice(int fd) { frame_t frame; memset(frame.buffer, 0, FRAME_MAX_LEN); frame.command = RESET_DEVICE; ssize_t ret = sendReceiveFrame(fd, frame, 0, 1); if (ret!=0) { return ret; } if (frame.data[0]!=COMMAND_SUCCESS) { return -frame.data[0]-1; } return 0; } struct termios termios_original; int openSerial(std::string port) { // open serial port int fd = open(port.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); // non-blocking IO: | O_NONBLOCK); if (fd == -1) { std::cerr<<"unable to open "<> ih; if (ih.getNoErrors()>0 || ih.getNoWarnings()>0) { std::cerr<<"unable to read file"<=END_FLASH_BYTES || endAddr(newFirmwareVersion) << " [" << std::hex << std::setw (4) << std::setfill('0') << static_cast(checkSum) << "]" << std::endl; } bool flashPic(int fd) { std::ifstream inStream; inStream.open(flashFile, ifstream::in); if (!inStream.good()) { std::cerr<<"unable to open file"<> ih; if (ih.getNoErrors()>0 || ih.getNoWarnings()>0) { std::cerr<<"errors or warnings while reading the file:"<(startAddr) << " - 0x" << std::hex << std::setfill('0') << std::setw(4) << static_cast(endAddr) << std::endl; } if (startAddr=END_FLASH_BYTES || endAddr(nextAddr)<(-eraseRes-1)<(nextAddr/2) << " - 0x" << static_cast(endAddr/2) << std::endl; size_t blocks = 0; while (blockStart(blockStart/2)<<" "; } if (writeFlash(fd, blockStart/2, WRITE_FLASH_BLOCKSIZE, buf, true)!=0) { // repeat once silently: if (writeFlash(fd, blockStart/2, WRITE_FLASH_BLOCKSIZE, buf)!=0) { std::cerr << "unable to write flash at 0x" << std::hex << std::setfill('0') << std::setw(4) << static_cast(blockStart/2) << std::endl; return false; } } std::cout<<"."; if (++blocks>=64) { blocks = 0; } std::cout.flush(); } blockStart += WRITE_FLASH_BLOCKSIZE; } std::cout<0) { mac[2+i] = configData[i*2]; } } if (useMUI) { // read MUI to build uniqueMAC address // start with MUI6, end with MUI8 (MUI9 is reserved) readConfig(fd, 0x0106, 8, true, false, configData); // MUI for (int i=0; i<3; i++) { mac[3+i] = configData[i*2]; } } std::cout<<"MAC address:"; for (int i=0; i<6; i++) { std::cout<<(i==0?' ':':')<(mac[i]); } std::cout<(ip[i]); } std::cout<<"/"<(maskLen)<=8 ? 255 : maskLen<=0 ? 0 : (255^((1<<(8-maskLen))-1)); ip[pos] &= mask[pos]; maskLen = maskLen>=8 ? maskLen-8 : 0; } ip[3] |= 1; // first address in network is used as gateway (not needed anyway)) std::cout<<"IP gateway:"; for (int i=0; i<4; i++) { std::cout<<(i==0?' ':'.')<(ip[i]); } std::cout<(((data[1]&0xf)<<2) | ((data[0]&0xc0)>>6)) << "." << static_cast(data[0]&0x3f) << std::endl; if (verbose) { std::cout << "Configuration words:" << std::endl; readConfig(fd, 0x0007, 5*2); // Configuration Words std::cout << "MUI:" << std::endl; readConfig(fd, 0x0100, 9*2, true); // MUI std::cout<<"EUI:"<(bootloaderVersion) << " [" << std::hex << std::setw (4) << std::setfill('0') << static_cast(picSum) << "]" << std::endl; } else { std::cerr<<"Bootloader version not found"<(firmwareVersion) << " [" << std::hex << std::setw (4) << std::setfill('0') << static_cast(picSum) << "]" << std::endl; } else { std::cout<<"Firmware version not found"<