/* Close socket if was opened */
close_socket(socket);
+ /* If we are in server mode we do nothing */
+ if (socket->handler)
+ return true;
+
+
/* Start with new connection */
socket->sock = netconn_new(NETCONN_TCP);
if(!socket->sock)
socket->error = 0;
}
+void tcpsocket_serverPoll(KFile *fd)
+{
+ TcpSocket *socket = TCPSOCKET_CAST(fd);
+
+
+ if (!socket->sock)
+ socket->sock = netconn_accept(socket->server_sock);
+
+ if (!socket->sock)
+ {
+ LOG_ERR("Unable to connect with client\n");
+ return;
+ }
+
+ socket->handler(fd);
+}
+
void tcpsocket_init(TcpSocket *socket, struct ip_addr *local_addr, struct ip_addr *remote_addr, uint16_t port)
{
- socket->sock = NULL;
+ memset(socket, 0, sizeof(TcpSocket));
+
socket->local_addr = local_addr;
socket->remote_addr = remote_addr;
socket->port = port;
socket->fd.reopen = tcpsocket_reopen;
}
+
+void tcpsocket_serverInit(TcpSocket *socket, struct ip_addr *local_addr, struct ip_addr *listen_addr, uint16_t port, tcphandler_t handler)
+{
+ tcpsocket_init(socket, local_addr, listen_addr, port);
+ socket->handler = handler;
+
+ socket->server_sock = netconn_new(NETCONN_TCP);
+ socket->error = netconn_bind(socket->server_sock, listen_addr, port);
+ socket->error = netconn_listen(socket->server_sock);
+ if(socket->error != ERR_OK)
+ LOG_ERR("Init server\n");
+}
#include <lwip/netif.h>
#include <lwip/ip_addr.h>
+typedef void (*tcphandler_t)(KFile *fd);
+
typedef struct TcpSocket
{
KFile fd; ///< KFile context.
- struct netconn *sock; ///< Current sockect connection pointer.
+ struct netconn *sock; ///< Current socket connection.
struct netbuf *rx_buf_conn; ///< Current received buffer from socket.
size_t remaning_data_len; ///< Number of bytes to read from the received buffer.
uint16_t port; ///< Number port to connect.
int error; ///< Error status.
+
+ struct netconn *server_sock; ///< Server sockect connection.
+ tcphandler_t handler; ///< TCP handler when are in server mode.
} TcpSocket;
#define KFT_TCPSOCKET MAKE_ID('T', 'S', 'C', 'K')
void tcpsocket_init(TcpSocket *socket, struct ip_addr *local_addr, struct ip_addr *remote_addr, uint16_t port);
+void tcpsocket_serverPoll(KFile *fd);
+void tcpsocket_serverInit(TcpSocket *socket, struct ip_addr *local_addr, struct ip_addr *remote_addr, uint16_t port, tcphandler_t handler);
+
#endif /* NET_TCP_SOCKET_H */