@@ -31,52 +31,44 @@ class BridgeTCPServer final: public Server {
3131 IPAddress _addr{};
3232 uint16_t _port;
3333 bool _listening = false ;
34- uint32_t listener_id;
34+ uint32_t listener_id = 0 ;
35+ uint32_t connection_id = 0 ;
3536 struct k_mutex server_mutex{};
3637
3738public:
3839 explicit BridgeTCPServer (BridgeClass& bridge, const IPAddress& addr, uint16_t port): bridge(&bridge), _addr(addr), _port(port) {}
3940
40- explicit BridgeTCPServer (BridgeClass& bridge, uint16_t port): bridge(&bridge), _addr(IP_ANY_TYPE ), _port(port) {}
41+ // explicit BridgeTCPServer(BridgeClass& bridge, uint16_t port): bridge(&bridge), _addr(INADDR_NONE ), _port(port) {}
4142
42- bool begin () {
43+ void begin () override {
4344 k_mutex_init (&server_mutex);
45+
4446 if (!(*bridge)) {
45- if (!bridge->begin ()) {
46- return false ;
47- }
47+ while (!bridge->begin ());
4848 }
4949
5050 k_mutex_lock (&server_mutex, K_FOREVER);
5151
52- String conn_str = addr.toString () + String (_port);
53- const bool ret = bridge->call (TCP_LISTEN_METHOD, listener_id, conn_str);
54- // TODO is listener_id one per server obj?
55-
56- if (ret) {
57- _listening = true ;
58- }
52+ String hostname = _addr.toString ();
53+ _listening = bridge->call (TCP_LISTEN_METHOD, listener_id, hostname, _port);
5954
6055 k_mutex_unlock (&server_mutex);
6156
62- return ret;
6357 }
6458
65- void begin (uint16_t port) {
66- _port = port;
67- begin ();
68- }
59+ BridgeTCPClient<BufferSize> accept () {
6960
61+ if (connection_id != 0 ) {
62+ return BridgeTCPClient<BufferSize>(*bridge, connection_id);
63+ }
7064
71- BridgeTCPClient<BufferSize> accept () {
7265 k_mutex_lock (&server_mutex, K_FOREVER);
7366
74- uint32_t connection_id = 0 ;
7567 const bool ret = bridge->call (TCP_ACCEPT_METHOD, connection_id, listener_id);
7668
7769 k_mutex_unlock (&server_mutex);
7870
79- if (ret && connection_id != 0 ) { // TODO is connection_id 0 acceptable???
71+ if (ret && connection_id != 0 ) { // connection_id 0 marks an invalid connection
8072 return BridgeTCPClient<BufferSize>(*bridge, connection_id);
8173 }
8274
@@ -89,12 +81,29 @@ class BridgeTCPServer final: public Server {
8981 }
9082
9183 size_t write (const uint8_t *buf, size_t size) override {
92- // Broadcasting to all clients would require tracking them
93- // For now, this is not implemented
94- // TODO a logic to resolve which port-socket is the target of the write
84+
85+ BridgeTCPClient<BufferSize> client = accept ();
86+
87+ if (client) {
88+ return client.write (buf, size);
89+ }
90+
9591 return 0 ;
9692 }
9793
94+ void close () {
95+ k_mutex_lock (&server_mutex, K_FOREVER);
96+
97+ String msg;
98+ const bool ret = bridge->call (TCP_CLOSE_METHOD, msg, listener_id);
99+
100+ if (ret) {
101+ _listening = false ;
102+ }
103+
104+ k_mutex_unlock (&server_mutex);
105+ }
106+
98107 bool is_listening () const {
99108 return _listening;
100109 }
0 commit comments