Klika Tech / Mbed 2 deprecated Nucleo-AWS-IoT-mbed

Dependencies:   X_NUCLEO_IKS01A1 mbed FP MQTTPacket DnsQuery ATParser

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers TCPServer.cpp Source File

TCPServer.cpp

00001 /* Socket
00002  * Copyright (c) 2015 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 #include "TCPServer.h"
00018 #include "Timer.h"
00019 
00020 TCPServer::TCPServer()
00021 {
00022 }
00023 
00024 TCPServer::TCPServer(NetworkStack *iface)
00025 {
00026     open(iface);
00027 }
00028 
00029 int TCPServer::open(NetworkStack *iface)
00030 {
00031     return Socket::open(iface, NSAPI_TCP);
00032 }
00033 
00034 int TCPServer::listen(int backlog)
00035 {
00036     if (!_socket) {
00037         return NSAPI_ERROR_NO_SOCKET;   
00038     }
00039 
00040     return _iface->socket_listen(_socket, backlog);
00041 }
00042 
00043 int TCPServer::accept(TCPSocket *connection)
00044 {
00045     mbed::Timer timer;
00046     timer.start();
00047     mbed::Timeout timeout;
00048     if (_timeout >= 0) {
00049         timeout.attach_us(&Socket::wakeup, _timeout * 1000);
00050     }
00051 
00052     if (connection->_socket) {
00053         connection->close();
00054     }
00055 
00056     while (true) {
00057         if (!_socket) {
00058             return NSAPI_ERROR_NO_SOCKET;   
00059         }
00060 
00061         void *socket;
00062         int err = _iface->socket_accept(&socket, _socket);
00063         if (!err) {
00064             connection->_iface = _iface;
00065             connection->_socket = socket;
00066         }
00067 
00068         if (err != NSAPI_ERROR_WOULD_BLOCK
00069             || (_timeout >= 0 && timer.read_ms() >= _timeout)) {
00070             return err;
00071         }
00072 
00073         __WFI();
00074     }
00075 }