/** * @brief This function is used to close the tcp connection with server */ static void tcp_echoclient_connection_close(TM_TCPCLIENT_t* client, uint8_t success) { /* Remove callbacks from PCB */ if (client->pcb != NULL) { tcp_recv(client->pcb, NULL); tcp_sent(client->pcb, NULL); tcp_poll(client->pcb, NULL, 0); } /* Close tcp connection */ if (client->pcb != NULL) { tcp_close(client->pcb); } /* Free pcb */ mem_free(client->pcb); /* Increase number of connections */ TM_ETHERNET.ClientConnections++; /* In case connection was successfull */ if (success) { /* Increase successfull connections counter */ TM_ETHERNET.ClientSuccessfullConnections++; } /* Free client, it's not real free, only free flag is set */ /* Called before connection callback, so user can make a new connection */ /* inside connection closed callback */ tcp_client_free(client); /* Call user function if defined */ TM_ETHERNETCLIENT_ConnectionClosedCallback(client, success); }
static int tcp_client_remove(int cid) { tcp_client* c; c = hashtable_remove(clients, &cid); if (c == NULL) return 0; tcp_client_free(c); return 1; }
/* Connects to the TCP echo server */ err_t tcp_echoclient_connect(char* conn_name, uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4, uint16_t port, void* user_parameters) { struct ip_addr DestIPaddr; TM_TCPCLIENT_t* client; /* Check if we have already active connections */ if (tcp_client_get_number_active_connections()) { /* If cable is unplugged and we want to make a new connection */ if (CablePluggedWithActiveConnection) { /* Call user function if he wants to reset MCU */ TM_ETHERNET_SystemResetCallback(); /* Return "error" */ return ERR_CONN; } } /* Check if conection name is too big */ if (strlen(conn_name) >= ETHERNET_MAX_CONNECTION_NAME) { return ERR_ARG; } /* Check for connection */ client = tcp_client_malloc(); /* In case no memory available */ if (client == NULL) { return ERR_MEM; } tcp_echoclient_connection_close(client, 0); tcp_client_free(client); /* create new tcp pcb */ client->pcb = tcp_new(); if (client->pcb != NULL) { /* Set IP address */ IP4_ADDR(&DestIPaddr, ip1, ip2, ip3, ip4); /* Save IP address */ client->ip_addr[0] = ip1; client->ip_addr[1] = ip2; client->ip_addr[2] = ip3; client->ip_addr[3] = ip4; /* Save port */ client->port = port; /* Clear flag for headers */ client->headers_done = 0; /* Save user parameters */ client->user_parameters = user_parameters; /* Save connection name */ strcpy(client->name, conn_name); /* Set parameters */ tcp_arg(client->pcb, client); /* Set error function */ tcp_err(client->pcb, tcp_echoclient_error); /* connect to destination address/port */ tcp_connect(client->pcb, &DestIPaddr, port, tcp_echoclient_connected); /* Connection has started */ TM_ETHERNETCLIENT_ConnectionStartedCallback(client); /* Return OK */ return ERR_OK; } else { /* Deallocate */ tcp_client_free(client); } /* Return error */ return ERR_CONN; }