/* * TFTP.c * * Created: 26.05.2021 17:39:50 * Author: Admin */ #include "lwip/api.h" #include "tftp_server.h" #include "ff.h" #include "string.h" #include "log_and_debug.h" uint32_t TFTPbyteWrite = 0; uint32_t TFTPbyteRead = 0; static void* tftp_open(const char* fname, const char* mode, u8_t write); static void tftp_close(void* handle); static int tftp_write(void* handle, struct pbuf* p); static int tftp_read(void* handle, void* buf, int bytes); void tftpServer_init(void) { static const struct tftp_context tftp = { tftp_open, tftp_close, tftp_read, tftp_write, }; if(tftp_init(&tftp) == ERR_OK) __debug(DEBUG_SERVSE, "TFTP server started: port 69\r\n"); } static void* tftp_open(const char* fname, const char* mode, u8_t write) { void *file = NULL; static FIL FSFileTFTP; __debug(DEBUG_SERVSE, "TFTP: path to file %s %s\r\n", fname, write ? "write" : "read"); switch(write){ case 0: if(f_open(&FSFileTFTP, fname, FA_READ) == FR_OK)file = (void*)&FSFileTFTP; break; case 1: if(f_open(&FSFileTFTP, fname, FA_CREATE_ALWAYS | FA_WRITE) == FR_OK)file = (void*)&FSFileTFTP; break; } return file; } static void tftp_close(void* handle) { f_close((FIL*)handle); TFTPbyteWrite = 0; TFTPbyteRead = 0; } static int tftp_write(void* handle, struct pbuf* p) { uint32_t TFTPbyteWritten = 0; if((FIL*)handle == NULL) return -1; f_lseek((FIL*)handle, TFTPbyteWrite); if(f_write((FIL*)handle, p->payload, (UINT)p->len, (UINT*)&TFTPbyteWritten) != FR_OK)return -1; TFTPbyteWrite += p->len; return 0; } static int tftp_read(void* handle, void* buf, int bytes) { uint32_t TFTPbyteReading = 0; if((FIL*)handle == NULL) return -1; f_lseek((FIL*)handle, TFTPbyteRead); if(f_read((FIL*)handle, buf, (UINT)bytes, (UINT*)&TFTPbyteReading) != FR_OK)return -1; TFTPbyteRead += bytes; return TFTPbyteReading; }