/* * tcp_client.c * * Created on: Nov 29, 2023 * Author: marcr */ #include "lwip/opt.h" #include "lwip/sockets.h" #include "lwip/api.h" #include "lwip/sys.h" #include "tcp_client.h" #include "string.h" #define TARGET_HOST_ADDR "192.168.1.46" #define TARGET_PORT 50000 // Print err via UART and light up LED void ReportErr(GPIO_TypeDef* LED_PORT, uint16_t LED_PIN, int err); extern UART_HandleTypeDef huart3; // Tâche TCP static void TcpThread(void *arg) { struct sockaddr_in addr; int s; int err; // char numbuf[5]; // static uint32_t conn_count = 0; memset(&addr, 0, sizeof(addr)); // Initialiser adresse comme vide addr.sin_len = sizeof(addr); // Taille de l'adresse addr.sin_family = AF_INET; // Type d'adresse: adresse Internet IPv4 addr.sin_port = PP_HTONS(TARGET_PORT); // Mettre dans le bon ordre (endianess) le port de destination addr.sin_addr.s_addr = inet_addr(TARGET_HOST_ADDR); // Transformer addresse de chaine de charactère en entier pour pouvoir l'utiliser // Créer le socket s = lwip_socket(AF_INET, SOCK_STREAM, 0); if(s >= 0) { HAL_UART_Transmit(&huart3, (uint8_t *)"Created\n\r", 10, 5*sizeof(char)); //LWIP_ASSERT("s >= 0", s >= 0); // Verifie que le socket est bien crée } else { HAL_UART_Transmit(&huart3, (uint8_t *)"Could not create socket\n\r", 26*sizeof(char), 6); HAL_GPIO_WritePin(LD1_GPIO_Port, LD1_Pin, GPIO_PIN_SET); } // Connect err = lwip_connect(s, (struct sockaddr *)&addr, sizeof(addr)); if (err == 0) HAL_UART_Transmit(&huart3, (uint8_t *)"Connected!\n\r", 13*sizeof(char), 5); else { err = lwip_close(s); HAL_UART_Transmit(&huart3, (uint8_t *)"Could not Connect\n\r", 20*sizeof(char), 5); ReportErr(LD1_GPIO_Port, LD2_Pin, err); } err = lwip_write(s, "I3", 2); if (err==2) HAL_UART_Transmit(&huart3, (uint8_t *)"Sent!\n\r", 8*sizeof(char), 5); else { err = lwip_close(s); HAL_UART_Transmit(&huart3, (uint8_t *)"Could not send\n\r", 17*sizeof(char), 5); ReportErr(LD2_GPIO_Port, LD3_Pin, err); } err = lwip_close(s); if (err==0) HAL_UART_Transmit(&huart3, (uint8_t *)"Closed!\n\r", 10*sizeof(char), 5); else { HAL_UART_Transmit(&huart3, (uint8_t *)"Could not close\n\r", 18*sizeof(char), 5); ReportErr(LD3_GPIO_Port, LD3_Pin, err); } vTaskDelete(NULL); } void TcpInit(void) { TaskHandle_t tcp_thread_id; xTaskCreate(TcpThread, "TCP", 128 * 4, NULL, osPriorityNormal, &tcp_thread_id); } void ReportErr(GPIO_TypeDef* LED_PORT, uint16_t LED_PIN, int err) { char err_buf[10]; char report_buf[30] = "Error code : "; sprintf(err_buf, "%d\n\r", err); strcat(report_buf, err_buf); HAL_UART_Transmit(&huart3, (uint8_t *)report_buf, sizeof(report_buf), 5); HAL_GPIO_WritePin(LED_PORT, LED_PIN, GPIO_PIN_SET); }