EMW3162 driver
Revision 0:65ba09002ce8, committed 2016-11-01
- Comitter:
- Maggie17
- Date:
- Tue Nov 01 12:43:30 2016 +0000
- Commit message:
- Initial commit
Changed in this revision
diff -r 000000000000 -r 65ba09002ce8 EMW3162Interface.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/EMW3162Interface.cpp Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,223 @@ +/* ESP8266 implementation of NetworkInterfaceAPI + * Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "EMW3162Interface.h" + +// Various timeouts for different ESP8266 operations +#define ESP8266_CONNECT_TIMEOUT 15000 +#define ESP8266_SEND_TIMEOUT 500 +#define ESP8266_RECV_TIMEOUT 0 +#define ESP8266_MISC_TIMEOUT 500 + + +// ESP8266Interface implementation +ESP8266Interface::ESP8266Interface(PinName tx, PinName rx, bool debug) + : _esp(tx, rx, debug) +{ + memset(_ids, 0, sizeof(_ids)); + memset(_cbs, 0, sizeof(_cbs)); + + _esp.attach(this, &ESP8266Interface::event); +} + +int ESP8266Interface::connect( + const char *ssid, + const char *pass, + nsapi_security_t security) +{ + _esp.setTimeout(ESP8266_CONNECT_TIMEOUT); + + if (!_esp.startup()) { + return NSAPI_ERROR_DEVICE_ERROR; + } + + if (!_esp.dhcp(true)) { + return NSAPI_ERROR_DHCP_FAILURE; + } + + if (!_esp.connect(ssid, pass)) { + return NSAPI_ERROR_NO_CONNECTION; + } + + if (!_esp.getIPAddress()) { + return NSAPI_ERROR_DHCP_FAILURE; + } + + return 0; +} + +int ESP8266Interface::disconnect() +{ + _esp.setTimeout(ESP8266_MISC_TIMEOUT); + + if (!_esp.disconnect()) { + return NSAPI_ERROR_DEVICE_ERROR; + } + + return 0; +} + +const char* ESP8266Interface::get_ip_address() +{ + return _esp.getIPAddress(); +} + +const char* ESP8266Interface::get_mac_address() +{ + return _esp.getMACAddress(); +} + +struct ESP8266_socket { + int id; + int socketId; + nsapi_protocol_t proto; + bool connected; +}; + +int ESP8266Interface::socket_open(void **handle, nsapi_protocol_t proto) +{ + // Look for an unused socket + int id = -1; + + for (int i = 1; i < ESP8266_SOCKET_COUNT; i++) { + if (!_ids[i]) { + id = i; + _ids[i] = true; + break; + } + } + + if (id == -1) { + return NSAPI_ERROR_NO_SOCKET; + } + + struct ESP8266_socket *socket = new struct ESP8266_socket; + if (!socket) { + return NSAPI_ERROR_NO_SOCKET; + } + + socket->id = id; + socket->socketId = 0; + socket->proto = proto; + socket->connected = false; + *handle = socket; + return 0; +} + +int ESP8266Interface::socket_close(void *handle) +{ + struct ESP8266_socket *socket = (struct ESP8266_socket *)handle; + int err = 0; + _esp.setTimeout(ESP8266_MISC_TIMEOUT); + + if (!_esp.close(socket->socketId)) { + err = NSAPI_ERROR_DEVICE_ERROR; + } + + _ids[socket->id] = false; + delete socket; + return err; +} + +int ESP8266Interface::socket_bind(void *handle, const SocketAddress &address) +{ + return NSAPI_ERROR_UNSUPPORTED; +} + +int ESP8266Interface::socket_listen(void *handle, int backlog) +{ + return NSAPI_ERROR_UNSUPPORTED; +} + +int ESP8266Interface::socket_connect(void *handle, const SocketAddress &addr) +{ + struct ESP8266_socket *socket = (struct ESP8266_socket *)handle; + _esp.setTimeout(ESP8266_MISC_TIMEOUT); + + const char *proto = (socket->proto == NSAPI_UDP) ? "UNICAST" : "CLIENT"; + socket -> socketId = _esp.open(proto, socket->id, addr.get_ip_address(), addr.get_port()); + if (!(socket -> socketId)) { + return NSAPI_ERROR_DEVICE_ERROR; + } + + socket->connected = true; + return 0; +} + +int ESP8266Interface::socket_accept(void **handle, void *server) +{ + return NSAPI_ERROR_UNSUPPORTED; +} + +int ESP8266Interface::socket_send(void *handle, const void *data, unsigned size) +{ + struct ESP8266_socket *socket = (struct ESP8266_socket *)handle; + _esp.setTimeout(ESP8266_SEND_TIMEOUT); + + if (!_esp.send(socket->socketId, data, size)) { + return NSAPI_ERROR_DEVICE_ERROR; + } + + return size; +} + +int ESP8266Interface::socket_recv(void *handle, void *data, unsigned size) +{ + struct ESP8266_socket *socket = (struct ESP8266_socket *)handle; + _esp.setTimeout(ESP8266_RECV_TIMEOUT); + + int32_t recv = _esp.recv(socket->socketId, data, size); + if (recv < 0) { + return NSAPI_ERROR_WOULD_BLOCK; + } + + return recv; +} + +int ESP8266Interface::socket_sendto(void *handle, const SocketAddress &addr, const void *data, unsigned size) +{ + struct ESP8266_socket *socket = (struct ESP8266_socket *)handle; + if (!socket->connected) { + int err = socket_connect(socket, addr); + if (err < 0) { + return err; + } + } + + return socket_send(socket, data, size); +} + +int ESP8266Interface::socket_recvfrom(void *handle, SocketAddress *addr, void *data, unsigned size) +{ + struct ESP8266_socket *socket = (struct ESP8266_socket *)handle; + return socket_recv(socket, data, size); +} + +void ESP8266Interface::socket_attach(void *handle, void (*callback)(void *), void *data) +{ + struct ESP8266_socket *socket = (struct ESP8266_socket *)handle; + _cbs[socket->id].callback = callback; + _cbs[socket->id].data = data; +} + +void ESP8266Interface::event() { + for (int i = 0; i < ESP8266_SOCKET_COUNT; i++) { + if (_cbs[i].callback) { + _cbs[i].callback(_cbs[i].data); + } + } +}
diff -r 000000000000 -r 65ba09002ce8 EMW3162Interface.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/EMW3162Interface.h Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,190 @@ +/* ESP8266 implementation of NetworkInterfaceAPI + * Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ESP8266_INTERFACE_H +#define ESP8266_INTERFACE_H + +#include "network-socket/NetworkStack.h" +#include "network-socket/WiFiInterface.h" +#include "EMW3162.h" + + +#define ESP8266_SOCKET_COUNT 5 + +/** ESP8266Interface class + * Implementation of the NetworkStack for the ESP8266 + */ +class ESP8266Interface : public NetworkStack, public WiFiInterface +{ +public: + /** ESP8266Interface lifetime + * @param tx TX pin + * @param rx RX pin + * @param debug Enable debugging + */ + ESP8266Interface(PinName tx, PinName rx, bool debug = true); + + /** Start the interface + * + * Attempts to connect to a WiFi network. If passphrase is invalid, + * NSAPI_ERROR_AUTH_ERROR is returned. + * + * @param ssid Name of the network to connect to + * @param pass Security passphrase to connect to the network + * @param security Type of encryption for connection + * @return 0 on success, negative error code on failure + */ + virtual int connect( + const char *ssid, + const char *pass, + nsapi_security_t security = NSAPI_SECURITY_NONE); + + /** Stop the interface + * @return 0 on success, negative on failure + */ + virtual int disconnect(); + + /** Get the internally stored IP address + * @return IP address of the interface or null if not yet connected + */ + virtual const char *get_ip_address(); + + /** Get the internally stored MAC address + * @return MAC address of the interface + */ + virtual const char *get_mac_address(); + +protected: + /** Open a socket + * @param handle Handle in which to store new socket + * @param proto Type of socket to open, NSAPI_TCP or NSAPI_UDP + * @return 0 on success, negative on failure + */ + virtual int socket_open(void **handle, nsapi_protocol_t proto); + + /** Close the socket + * @param handle Socket handle + * @return 0 on success, negative on failure + * @note On failure, any memory associated with the socket must still + * be cleaned up + */ + virtual int socket_close(void *handle); + + /** Bind a server socket to a specific port + * @param handle Socket handle + * @param address Local address to listen for incoming connections on + * @return 0 on success, negative on failure. + */ + virtual int socket_bind(void *handle, const SocketAddress &address); + + /** Start listening for incoming connections + * @param handle Socket handle + * @param backlog Number of pending connections that can be queued up at any + * one time [Default: 1] + * @return 0 on success, negative on failure + */ + virtual int socket_listen(void *handle, int backlog); + + /** Connects this TCP socket to the server + * @param handle Socket handle + * @param address SocketAddress to connect to + * @return 0 on success, negative on failure + */ + virtual int socket_connect(void *handle, const SocketAddress &address); + + /** Accept a new connection. + * @param handle Handle in which to store new socket + * @param server Socket handle to server to accept from + * @return 0 on success, negative on failure + * @note This call is not-blocking, if this call would block, must + * immediately return NSAPI_ERROR_WOULD_WAIT + */ + virtual int socket_accept(void **handle, void *server); + + /** Send data to the remote host + * @param handle Socket handle + * @param data The buffer to send to the host + * @param size The length of the buffer to send + * @return Number of written bytes on success, negative on failure + * @note This call is not-blocking, if this call would block, must + * immediately return NSAPI_ERROR_WOULD_WAIT + */ + virtual int socket_send(void *handle, const void *data, unsigned size); + + /** Receive data from the remote host + * @param handle Socket handle + * @param data The buffer in which to store the data received from the host + * @param size The maximum length of the buffer + * @return Number of received bytes on success, negative on failure + * @note This call is not-blocking, if this call would block, must + * immediately return NSAPI_ERROR_WOULD_WAIT + */ + virtual int socket_recv(void *handle, void *data, unsigned size); + + /** Send a packet to a remote endpoint + * @param handle Socket handle + * @param address The remote SocketAddress + * @param data The packet to be sent + * @param size The length of the packet to be sent + * @return The number of written bytes on success, negative on failure + * @note This call is not-blocking, if this call would block, must + * immediately return NSAPI_ERROR_WOULD_WAIT + */ + virtual int socket_sendto(void *handle, const SocketAddress &address, const void *data, unsigned size); + + /** Receive a packet from a remote endpoint + * @param handle Socket handle + * @param address Destination for the remote SocketAddress or null + * @param buffer The buffer for storing the incoming packet data + * If a packet is too long to fit in the supplied buffer, + * excess bytes are discarded + * @param size The length of the buffer + * @return The number of received bytes on success, negative on failure + * @note This call is not-blocking, if this call would block, must + * immediately return NSAPI_ERROR_WOULD_WAIT + */ + virtual int socket_recvfrom(void *handle, SocketAddress *address, void *buffer, unsigned size); + + /** Register a callback on state change of the socket + * @param handle Socket handle + * @param callback Function to call on state change + * @param data Argument to pass to callback + * @note Callback may be called in an interrupt context. + */ + virtual void socket_attach(void *handle, void (*callback)(void *), void *data); + + /** Provide access to the NetworkStack object + * + * @return The underlying NetworkStack object + */ + virtual NetworkStack *get_stack() + { + return this; + } + +private: + ESP8266 _esp; + bool _ids[ESP8266_SOCKET_COUNT]; + + void event(); + struct { + void (*callback)(void *); + void *data; + } _cbs[ESP8266_SOCKET_COUNT]; +}; + + +#endif
diff -r 000000000000 -r 65ba09002ce8 emw3162/ATParser/ATParser.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emw3162/ATParser/ATParser.cpp Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,340 @@ +/* Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @section DESCRIPTION + * + * Parser for the AT command syntax + * + */ + +#include "ATParser.h" +#include "mbed_debug.h" + + +// getc/putc handling with timeouts +int ATParser::putc(char c) +{ + Timer timer; + timer.start(); + + while (true) { + if (_serial->writeable()) { + return _serial->putc(c); + } + if (timer.read_ms() > _timeout) { + return -1; + } + } +} + +int ATParser::getc() +{ + Timer timer; + timer.start(); + + while (true) { + if (_serial->readable()) { + return _serial->getc(); + } + if (timer.read_ms() > _timeout) { + return -1; + } + } +} + +void ATParser::flush() +{ + while (_serial->readable()) { + _serial->getc(); + } +} + + +// read/write handling with timeouts +int ATParser::write(const char *data, int size) +{ + int i = 0; + for ( ; i < size; i++) { + if (putc(data[i]) < 0) { + return -1; + } + } + return i; +} + +int ATParser::read(char *data, int size) +{ + int i = 0; + for ( ; i < size; i++) { + int c = getc(); + if (c < 0) { + return -1; + } + data[i] = c; + } + return i; +} + + +// printf/scanf handling +int ATParser::vprintf(const char *format, va_list args) +{ + if (vsprintf(_buffer, format, args) < 0) { + return false; + } + int i = 0; + for ( ; _buffer[i]; i++) { + if (putc(_buffer[i]) < 0) { + return -1; + } + } + return i; +} + +int ATParser::vscanf(const char *format, va_list args) +{ + // Since format is const, we need to copy it into our buffer to + // add the line's null terminator and clobber value-matches with asterisks. + // + // We just use the beginning of the buffer to avoid unnecessary allocations. + int i = 0; + int offset = 0; + + while (format[i]) { + if (format[i] == '%' && format[i+1] != '%' && format[i+1] != '*') { + _buffer[offset++] = '%'; + _buffer[offset++] = '*'; + i++; + } else { + _buffer[offset++] = format[i++]; + } + } + + // Scanf has very poor support for catching errors + // fortunately, we can abuse the %n specifier to determine + // if the entire string was matched. + _buffer[offset++] = '%'; + _buffer[offset++] = 'n'; + _buffer[offset++] = 0; + + // To workaround scanf's lack of error reporting, we actually + // make two passes. One checks the validity with the modified + // format string that only stores the matched characters (%n). + // The other reads in the actual matched values. + // + // We keep trying the match until we succeed or some other error + // derails us. + int j = 0; + + while (true) { + // Ran out of space + if (j+1 >= _buffer_size - offset) { + return false; + } + // Recieve next character + int c = getc(); + if (c < 0) { + return -1; + } + _buffer[offset + j++] = c; + _buffer[offset + j] = 0; + + // Check for match + int count = -1; + sscanf(_buffer+offset, _buffer, &count); + + // We only succeed if all characters in the response are matched + if (count == j) { + // Store the found results + vsscanf(_buffer+offset, format, args); + return j; + } + } +} + + +// Command parsing with line handling +bool ATParser::vsend(const char *command, va_list args) +{ + // Create and send command + if (vsprintf(_buffer, command, args) < 0) { + return false; + } + + for (int i = 0; _buffer[i]; i++) { + if (putc(_buffer[i]) < 0) { + return false; + } + } + + // Finish with newline// + char s[] = "\x0d"; + for (int i = 0; s[i]; i++){ + if(putc(s[i]) < 0) + printf("send <CR> error\n"); + } + + debug_if(dbg_on, "AT> %s\r\n", _buffer); + return true; +} + +bool ATParser::vrecv(const char *response, va_list args) +{ + // Iterate through each line in the expected response + while (response[0]) { + // Since response is const, we need to copy it into our buffer to + // add the line's null terminator and clobber value-matches with asterisks. + // + // We just use the beginning of the buffer to avoid unnecessary allocations. + int i = 0; + int offset = 0; + + while (response[i]) { + if (memcmp(&response[i+1-_delim_size], _delimiter, _delim_size) == 0) { + i++; + break; + } else if (response[i] == '%' && response[i+1] != '%' && response[i+1] != '*') { + _buffer[offset++] = '%'; + _buffer[offset++] = '*'; + i++; + } else { + _buffer[offset++] = response[i++]; + } + } + + // Scanf has very poor support for catching errors + // fortunately, we can abuse the %n specifier to determine + // if the entire string was matched. + _buffer[offset++] = '%'; + _buffer[offset++] = 'n'; + _buffer[offset++] = 0; + + // To workaround scanf's lack of error reporting, we actually + // make two passes. One checks the validity with the modified + // format string that only stores the matched characters (%n). + // The other reads in the actual matched values. + // + // We keep trying the match until we succeed or some other error + // derails us. + int j = 0; + + while (true) { + // Recieve next character + int c = getc(); + //printf("111111111c= %d\n", c); + if (c < 0) { + return false; + } + + if (c == 0x0d) + c = '#'; + + _buffer[offset + j++] = c; + _buffer[offset + j] = 0; + + // Check for oob data + for (int k = 0; k < _oobs.size(); k++) { + if (j == _oobs[k].len && memcmp( + _oobs[k].prefix, _buffer+offset, _oobs[k].len) == 0) { + debug_if(dbg_on, "AT! %s\r\n", _oobs[k].prefix); + _oobs[k].cb(); + + // oob may have corrupted non-reentrant buffer, + // so we need to set it up again + return vrecv(response, args); + } + } + + // Check for match + int count = -1; + sscanf(_buffer+offset, _buffer, &count); + //printf("_buffer+offset is %s, _buffer is %s\n", _buffer+offset, _buffer); + + // We only succeed if all characters in the response are matched + if (count == j) { + debug_if(dbg_on, "AT= %s\r\n", _buffer+offset); + // Reuse the front end of the buffer + memcpy(_buffer, response, i); + _buffer[i] = 0; + + // Store the found results + vsscanf(_buffer+offset, _buffer, args); + + // Jump to next line and continue parsing + response += i; + break; + } + + // Clear the buffer when we hit a newline or ran out of space + // running out of space usually means we ran into binary data + if (c == '\n' || j+1 >= _buffer_size - offset || + strcmp(&_buffer[offset + j-_delim_size], _delimiter) == 0) { + + debug_if(dbg_on, "AT< %s", _buffer+offset); + j = 0; + } + } + } + + return true; +} + + +//// Mapping to vararg functions +//int ATParser::printf(const char *format, ...) +//{ +// va_list args; +// va_start(args, format); +// int res = vprintf(format, args); +// va_end(args); +// return res; +//} + +int ATParser::scanf(const char *format, ...) +{ + va_list args; + va_start(args, format); + int res = vscanf(format, args); + va_end(args); + return res; +} + +bool ATParser::send(const char *command, ...) +{ + va_list args; + va_start(args, command); + bool res = vsend(command, args); + va_end(args); + return res; +} + +bool ATParser::recv(const char *response, ...) +{ + va_list args; + va_start(args, response); + bool res = vrecv(response, args); + va_end(args); + return res; +} + + +// oob registration +void ATParser::oob(const char *prefix, Callback<void()> cb) +{ + struct oob oob; + oob.len = strlen(prefix); + oob.prefix = prefix; + oob.cb = cb; + _oobs.push_back(oob); +}
diff -r 000000000000 -r 65ba09002ce8 emw3162/ATParser/ATParser.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emw3162/ATParser/ATParser.h Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,232 @@ +/* Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @section DESCRIPTION + * + * Parser for the AT command syntax + * + */ + +#include "mbed.h" +#include <cstdarg> +#include <vector> +#include "BufferedSerial.h" +#include "Callback.h" + + +/** +* Parser class for parsing AT commands +* +* Here are some examples: +* @code +* ATParser at = ATParser(serial, "\r\n"); +* int value; +* char buffer[100]; +* +* at.send("AT") && at.recv("OK"); +* at.send("AT+CWMODE=%d", 3) && at.recv("OK"); +* at.send("AT+CWMODE?") && at.recv("+CWMODE:%d\r\nOK", &value); +* at.recv("+IPD,%d:", &value); +* at.read(buffer, value); +* at.recv("OK"); +* @endcode +*/ +class ATParser +{ +private: + // Serial information + BufferedSerial *_serial; + int _buffer_size; + char *_buffer; + int _timeout; + + // Parsing information + const char *_delimiter; + int _delim_size; + bool dbg_on; + + struct oob { + unsigned len; + const char *prefix; + mbed::Callback<void()> cb; + }; + std::vector<oob> _oobs; + +public: + /** + * Constructor + * + * @param serial serial interface to use for AT commands + * @param buffer_size size of internal buffer for transaction + * @param timeout timeout of the connection + * @param delimiter string of characters to use as line delimiters + */ + ATParser(BufferedSerial &serial, const char *delimiter = "#\n", int buffer_size = 256, int timeout = 8000, bool debug = false) : + _serial(&serial), + _buffer_size(buffer_size) { + _buffer = new char[buffer_size]; + setTimeout(timeout); + setDelimiter(delimiter); + debugOn(debug); + } + + /** + * Destructor + */ + ~ATParser() { + delete [] _buffer; + } + + /** + * Allows timeout to be changed between commands + * + * @param timeout timeout of the connection + */ + void setTimeout(int timeout) { + _timeout = timeout; + } + + /** + * Sets string of characters to use as line delimiters + * + * @param delimiter string of characters to use as line delimiters + */ + void setDelimiter(const char *delimiter) { + _delimiter = delimiter; + _delim_size = strlen(delimiter); + } + + /** + * Allows echo to be on or off + * + * @param echo 1 for echo and 0 turns it off + */ + void debugOn(uint8_t on) { + dbg_on = (on) ? 1 : 0; + } + + /** + * Sends an AT command + * + * Sends a formatted command using printf style formatting + * @see ::printf + * + * @param command printf-like format string of command to send which + * is appended with the specified delimiter + * @param ... all printf-like arguments to insert into command + * @return true only if command is successfully sent + */ + bool send(const char *command, ...); + bool vsend(const char *command, va_list args); + + /** + * Recieve an AT response + * + * Recieves a formatted response using scanf style formatting + * @see ::scanf + * + * Responses are parsed line at a time using the specified delimiter. + * Any recieved data that does not match the response is ignored until + * a timeout occurs. + * + * @param response scanf-like format string of response to expect + * @param ... all scanf-like arguments to extract from response + * @return true only if response is successfully matched + */ + bool recv(const char *response, ...); + bool vrecv(const char *response, va_list args); + + /** + * Write a single byte to the underlying stream + * + * @param c The byte to write + * @return The byte that was written or -1 during a timeout + */ + int putc(char c); + + /** + * Get a single byte from the underlying stream + * + * @return The byte that was read or -1 during a timeout + */ + int getc(); + + /** + * Write an array of bytes to the underlying stream + * + * @param data the array of bytes to write + * @param size number of bytes to write + * @return number of bytes written or -1 on failure + */ + int write(const char *data, int size); + + /** + * Read an array of bytes from the underlying stream + * + * @param data the destination for the read bytes + * @param size number of bytes to read + * @return number of bytes read or -1 on failure + */ + int read(char *data, int size); + + /** + * Direct printf to underlying stream + * @see ::printf + * + * @param format format string to pass to printf + * @param ... arguments to printf + * @return number of bytes written or -1 on failure + */ + //int printf(const char *format, ...); + int vprintf(const char *format, va_list args); + + /** + * Direct scanf on underlying stream + * @see ::scanf + * + * @param format format string to pass to scanf + * @param ... arguments to scanf + * @return number of bytes read or -1 on failure + */ + int scanf(const char *format, ...); + int vscanf(const char *format, va_list args); + + /** + * Attach a callback for out-of-band data + * + * @param prefix string on when to initiate callback + * @param func callback to call when string is read + * @note out-of-band data is only processed during a scanf call + */ + void oob(const char *prefix, mbed::Callback<void()> func); + + /** + * Attach a callback for out-of-band data + * + * @param prefix string on when to initiate callback + * @param obj pointer to object to call member function on + * @param method callback to call when string is read + * @note out-of-band data is only processed during a scanf call + */ + template <typename T, typename M> + void oob(const char *prefix, T *obj, M method) { + return oob(prefix, mbed::Callback<void()>(obj, method)); + } + + /** + * Flushes the underlying stream + */ + void flush(); +}; +
diff -r 000000000000 -r 65ba09002ce8 emw3162/ATParser/BufferedSerial/Buffer/MyBuffer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emw3162/ATParser/BufferedSerial/Buffer/MyBuffer.cpp Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,76 @@ + +/** + * @file Buffer.cpp + * @brief Software Buffer - Templated Ring Buffer for most data types + * @author sam grove + * @version 1.0 + * @see + * + * Copyright (c) 2013 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "MyBuffer.h" + +template <class T> +MyBuffer<T>::MyBuffer(uint32_t size) +{ + _buf = new T [size]; + _size = size; + clear(); + + return; +} + +template <class T> +MyBuffer<T>::~MyBuffer() +{ + delete [] _buf; + + return; +} + +template <class T> +uint32_t MyBuffer<T>::getSize() +{ + return this->_size; +} + +template <class T> +void MyBuffer<T>::clear(void) +{ + _wloc = 0; + _rloc = 0; + memset(_buf, 0, _size); + + return; +} + +template <class T> +uint32_t MyBuffer<T>::peek(char c) +{ + return 1; +} + +// make the linker aware of some possible types +template class MyBuffer<uint8_t>; +template class MyBuffer<int8_t>; +template class MyBuffer<uint16_t>; +template class MyBuffer<int16_t>; +template class MyBuffer<uint32_t>; +template class MyBuffer<int32_t>; +template class MyBuffer<uint64_t>; +template class MyBuffer<int64_t>; +template class MyBuffer<char>; +template class MyBuffer<wchar_t>;
diff -r 000000000000 -r 65ba09002ce8 emw3162/ATParser/BufferedSerial/Buffer/MyBuffer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emw3162/ATParser/BufferedSerial/Buffer/MyBuffer.h Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,163 @@ + +/** + * @file Buffer.h + * @brief Software Buffer - Templated Ring Buffer for most data types + * @author sam grove + * @version 1.0 + * @see + * + * Copyright (c) 2013 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MYBUFFER_H +#define MYBUFFER_H + +#include <stdint.h> +#include <string.h> + +/** A templated software ring buffer + * + * Example: + * @code + * #include "mbed.h" + * #include "MyBuffer.h" + * + * MyBuffer <char> buf; + * + * int main() + * { + * buf = 'a'; + * buf.put('b'); + * char *head = buf.head(); + * puts(head); + * + * char whats_in_there[2] = {0}; + * int pos = 0; + * + * while(buf.available()) + * { + * whats_in_there[pos++] = buf; + * } + * printf("%c %c\n", whats_in_there[0], whats_in_there[1]); + * buf.clear(); + * error("done\n\n\n"); + * } + * @endcode + */ + +template <typename T> +class MyBuffer +{ +private: + T *_buf; + volatile uint32_t _wloc; + volatile uint32_t _rloc; + uint32_t _size; + +public: + /** Create a Buffer and allocate memory for it + * @param size The size of the buffer + */ + MyBuffer(uint32_t size = 0x100); + + /** Get the size of the ring buffer + * @return the size of the ring buffer + */ + uint32_t getSize(); + + /** Destry a Buffer and release it's allocated memory + */ + ~MyBuffer(); + + /** Add a data element into the buffer + * @param data Something to add to the buffer + */ + void put(T data); + + /** Remove a data element from the buffer + * @return Pull the oldest element from the buffer + */ + T get(void); + + /** Get the address to the head of the buffer + * @return The address of element 0 in the buffer + */ + T *head(void); + + /** Reset the buffer to 0. Useful if using head() to parse packeted data + */ + void clear(void); + + /** Determine if anything is readable in the buffer + * @return 1 if something can be read, 0 otherwise + */ + uint32_t available(void); + + /** Overloaded operator for writing to the buffer + * @param data Something to put in the buffer + * @return + */ + MyBuffer &operator= (T data) + { + put(data); + return *this; + } + + /** Overloaded operator for reading from the buffer + * @return Pull the oldest element from the buffer + */ + operator int(void) + { + return get(); + } + + uint32_t peek(char c); + +}; + +template <class T> +inline void MyBuffer<T>::put(T data) +{ + _buf[_wloc++] = data; + _wloc %= (_size-1); + + return; +} + +template <class T> +inline T MyBuffer<T>::get(void) +{ + T data_pos = _buf[_rloc++]; + _rloc %= (_size-1); + + return data_pos; +} + +template <class T> +inline T *MyBuffer<T>::head(void) +{ + T *data_pos = &_buf[0]; + + return data_pos; +} + +template <class T> +inline uint32_t MyBuffer<T>::available(void) +{ + return (_wloc == _rloc) ? 0 : 1; +} + +#endif +
diff -r 000000000000 -r 65ba09002ce8 emw3162/ATParser/BufferedSerial/BufferedPrint.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emw3162/ATParser/BufferedSerial/BufferedPrint.c Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2014-2015 ARM Limited. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <stdarg.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> + +#include "mbed_error.h" + +size_t BufferedSerialThunk(void *buf_serial, const void *s, size_t length); + +int BufferedPrintfC(void *stream, int size, const char* format, va_list arg) +{ + int r; + char buffer[512]; + if (size >= 512) { + return -1; + } + memset(buffer, 0, size); + r = vsprintf(buffer, format, arg); + // this may not hit the heap but should alert the user anyways + if(r > (int32_t) size) { + error("%s %d buffer overwrite (max_buf_size: %d exceeded: %d)!\r\n", __FILE__, __LINE__, size, r); + return 0; + } + if ( r > 0 ) { + BufferedSerialThunk(stream, buffer, r); + } + return r; +}
diff -r 000000000000 -r 65ba09002ce8 emw3162/ATParser/BufferedSerial/BufferedSerial.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emw3162/ATParser/BufferedSerial/BufferedSerial.cpp Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,166 @@ +/** + * @file BufferedSerial.cpp + * @brief Software Buffer - Extends mbed Serial functionallity adding irq driven TX and RX + * @author sam grove + * @version 1.0 + * @see + * + * Copyright (c) 2013 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "BufferedSerial.h" +#include <stdarg.h> + +extern "C" int BufferedPrintfC(void *stream, int size, const char* format, va_list arg); + +BufferedSerial::BufferedSerial(PinName tx, PinName rx, uint32_t buf_size, uint32_t tx_multiple, const char* name) + : RawSerial(tx, rx) , _rxbuf(buf_size), _txbuf((uint32_t)(tx_multiple*buf_size)) +{ + RawSerial::attach(this, &BufferedSerial::rxIrq, Serial::RxIrq); + this->_buf_size = buf_size; + this->_tx_multiple = tx_multiple; + return; +} + +BufferedSerial::~BufferedSerial(void) +{ + RawSerial::attach(NULL, RawSerial::RxIrq); + RawSerial::attach(NULL, RawSerial::TxIrq); + + return; +} + +int BufferedSerial::readable(void) +{ + return _rxbuf.available(); // note: look if things are in the buffer +} + +int BufferedSerial::writeable(void) +{ + return 1; // buffer allows overwriting by design, always true +} + +int BufferedSerial::getc(void) +{ + return _rxbuf; +} + +int BufferedSerial::putc(int c) +{ + _txbuf = (char)c; + BufferedSerial::prime(); + + return c; +} + +int BufferedSerial::puts(const char *s) +{ + if (s != NULL) { + const char* ptr = s; + + while(*(ptr) != 0) { + _txbuf = *(ptr++); + } + _txbuf = '\n'; // done per puts definition + BufferedSerial::prime(); + + return (ptr - s) + 1; + } + return 0; +} + +extern "C" size_t BufferedSerialThunk(void *buf_serial, const void *s, size_t length) +{ + BufferedSerial *buffered_serial = (BufferedSerial *)buf_serial; + return buffered_serial->write(s, length); +} + +int BufferedSerial::printf(const char* format, ...) +{ + va_list arg; + va_start(arg, format); + int r = BufferedPrintfC((void*)this, this->_buf_size, format, arg); + va_end(arg); + return r; +} + +ssize_t BufferedSerial::write(const void *s, size_t length) +{ + if (s != NULL && length > 0) { + const char* ptr = (const char*)s; + const char* end = ptr + length; + + while (ptr != end) { + _txbuf = *(ptr++); + } + BufferedSerial::prime(); + + return ptr - (const char*)s; + } + return 0; +} + + +void BufferedSerial::rxIrq(void) +{ + // read from the peripheral and make sure something is available + if(serial_readable(&_serial)) { + _rxbuf = serial_getc(&_serial); // if so load them into a buffer + // trigger callback if necessary + if (_cbs[RxIrq]) { + _cbs[RxIrq](); + } + } + + return; +} + +void BufferedSerial::txIrq(void) +{ + // see if there is room in the hardware fifo and if something is in the software fifo + while(serial_writable(&_serial)) { + if(_txbuf.available()) { + serial_putc(&_serial, (int)_txbuf.get()); + } else { + // disable the TX interrupt when there is nothing left to send + RawSerial::attach(NULL, RawSerial::TxIrq); + // trigger callback if necessary + if (_cbs[TxIrq]) { + _cbs[TxIrq](); + } + break; + } + } + + return; +} + +void BufferedSerial::prime(void) +{ + // if already busy then the irq will pick this up + if(serial_writable(&_serial)) { + RawSerial::attach(NULL, RawSerial::TxIrq); // make sure not to cause contention in the irq + BufferedSerial::txIrq(); // only write to hardware in one place + RawSerial::attach(this, &BufferedSerial::txIrq, RawSerial::TxIrq); + } + + return; +} + +void BufferedSerial::attach(Callback<void()> func, IrqType type) +{ + _cbs[type] = func; +} +
diff -r 000000000000 -r 65ba09002ce8 emw3162/ATParser/BufferedSerial/BufferedSerial.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emw3162/ATParser/BufferedSerial/BufferedSerial.h Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,168 @@ + +/** + * @file BufferedSerial.h + * @brief Software Buffer - Extends mbed Serial functionallity adding irq driven TX and RX + * @author sam grove + * @version 1.0 + * @see + * + * Copyright (c) 2013 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BUFFEREDSERIAL_H +#define BUFFEREDSERIAL_H + +#include "mbed.h" +#include "MyBuffer.h" + +/** A serial port (UART) for communication with other serial devices + * + * Can be used for Full Duplex communication, or Simplex by specifying + * one pin as NC (Not Connected) + * + * Example: + * @code + * #include "mbed.h" + * #include "BufferedSerial.h" + * + * BufferedSerial pc(USBTX, USBRX); + * + * int main() + * { + * while(1) + * { + * Timer s; + * + * s.start(); + * pc.printf("Hello World - buffered\n"); + * int buffered_time = s.read_us(); + * wait(0.1f); // give time for the buffer to empty + * + * s.reset(); + * printf("Hello World - blocking\n"); + * int polled_time = s.read_us(); + * s.stop(); + * wait(0.1f); // give time for the buffer to empty + * + * pc.printf("printf buffered took %d us\n", buffered_time); + * pc.printf("printf blocking took %d us\n", polled_time); + * wait(0.5f); + * } + * } + * @endcode + */ + +/** + * @class BufferedSerial + * @brief Software buffers and interrupt driven tx and rx for Serial + */ +class BufferedSerial : public RawSerial +{ +private: + MyBuffer <char> _rxbuf; + MyBuffer <char> _txbuf; + uint32_t _buf_size; + uint32_t _tx_multiple; + + void rxIrq(void); + void txIrq(void); + void prime(void); + + Callback<void()> _cbs[2]; + +public: + /** Create a BufferedSerial port, connected to the specified transmit and receive pins + * @param tx Transmit pin + * @param rx Receive pin + * @param buf_size printf() buffer size + * @param tx_multiple amount of max printf() present in the internal ring buffer at one time + * @param name optional name + * @note Either tx or rx may be specified as NC if unused + */ + BufferedSerial(PinName tx, PinName rx, uint32_t buf_size = 256, uint32_t tx_multiple = 4,const char* name=NULL); + + /** Destroy a BufferedSerial port + */ + virtual ~BufferedSerial(void); + + /** Check on how many bytes are in the rx buffer + * @return 1 if something exists, 0 otherwise + */ + virtual int readable(void); + + /** Check to see if the tx buffer has room + * @return 1 always has room and can overwrite previous content if too small / slow + */ + virtual int writeable(void); + + /** Get a single byte from the BufferedSerial Port. + * Should check readable() before calling this. + * @return A byte that came in on the Serial Port + */ + virtual int getc(void); + + /** Write a single byte to the BufferedSerial Port. + * @param c The byte to write to the Serial Port + * @return The byte that was written to the Serial Port Buffer + */ + virtual int putc(int c); + + /** Write a string to the BufferedSerial Port. Must be NULL terminated + * @param s The string to write to the Serial Port + * @return The number of bytes written to the Serial Port Buffer + */ + virtual int puts(const char *s); + + /** Write a formatted string to the BufferedSerial Port. + * @param format The string + format specifiers to write to the Serial Port + * @return The number of bytes written to the Serial Port Buffer + */ + virtual int printf(const char* format, ...); + + /** Write data to the Buffered Serial Port + * @param s A pointer to data to send + * @param length The amount of data being pointed to + * @return The number of bytes written to the Serial Port Buffer + */ + virtual ssize_t write(const void *s, std::size_t length); + + /** Attach a function to call whenever a serial interrupt is generated + * @param func A pointer to a void function, or 0 to set as none + * @param type Which serial interrupt to attach the member function to (Serial::RxIrq for receive, TxIrq for transmit buffer empty) + */ + virtual void attach(Callback<void()> func, IrqType type=RxIrq); + + /** Attach a member function to call whenever a serial interrupt is generated + * @param obj pointer to the object to call the member function on + * @param method pointer to the member function to call + * @param type Which serial interrupt to attach the member function to (Serial::RxIrq for receive, TxIrq for transmit buffer empty) + */ + template <typename T> + void attach(T *obj, void (T::*method)(), IrqType type=RxIrq) { + attach(Callback<void()>(obj, method), type); + } + + /** Attach a member function to call whenever a serial interrupt is generated + * @param obj pointer to the object to call the member function on + * @param method pointer to the member function to call + * @param type Which serial interrupt to attach the member function to (Serial::RxIrq for receive, TxIrq for transmit buffer empty) + */ + template <typename T> + void attach(T *obj, void (*method)(T*), IrqType type=RxIrq) { + attach(Callback<void()>(obj, method), type); + } +}; + +#endif
diff -r 000000000000 -r 65ba09002ce8 emw3162/EMW3162.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emw3162/EMW3162.cpp Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,240 @@ +/* ESP8266 Example + * Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "EMW3162.h" + +ESP8266::ESP8266(PinName tx, PinName rx, bool debug) + : _serial(tx, rx, 1024), _parser(_serial) + , _packets(0), _packets_end(&_packets) +{ + _serial.baud(115200); + _parser.debugOn(debug); +} + +bool ESP8266::startup(void) +{ + bool success = reset("FACTORY"); + + _parser.oob("+EVENT=SOCKET", this, &ESP8266::_packet_handler); + + return success; +} + +bool ESP8266::reset(const char *reset) +{ + for (int i = 0; i < 2; i++) { + if (_parser.send("AT+%s", reset) + && _parser.recv("+OK")) { + return true; + } + } + + return false; +} + +bool ESP8266::dhcp(bool enabled) +{ + return _parser.send("AT+DHCP=%s", enabled ? "ON":"OFF") + && _parser.recv("+OK"); +} + +bool ESP8266::connect(const char *ap, const char *passPhrase) +{ + return _parser.send("AT+WSTA=%s,%s", ap, passPhrase) + && _parser.recv("+OK") + && _parser.send("AT+EVENT=ON") + && _parser.recv("+OK") + && _parser.recv("+EVENT=WIFI_LINK,STATION_UP"); +} + +bool ESP8266::disconnect(void) +{ + + return _parser.send("AT+WLANF=STA,OFF") + && _parser.recv("+OK") + && _parser.recv("+EVENT=WIFI_LINK,STATION_DOWN") + && _parser.send("AT+EVENT=OFF") + && _parser.recv("+OK"); +} + +const char *ESP8266::getIPAddress(void) +{ + if (!(_parser.send("AT+IPCONFIG") + && _parser.recv("%*[^,],%*[^,],%*[^,],%[^,]%*[^#]#", _ip_buffer))) { + return 0; + } + + return _ip_buffer; +} + +const char *ESP8266::getMACAddress(void) +{ + if (!(_parser.send("AT+WMAC") + && _parser.recv("%*[^=]=%[^#]#", _mac_buffer))) { + return 0; + } + + return _mac_buffer; +} + +bool ESP8266::isConnected(void) +{ + return getIPAddress() != 0; +} + +int ESP8266::open(const char *type, int id, const char* addr, int port) +{ + int state1 = 0, state2 = 0; + state1 = _parser.send("AT+CON1=%s,%d,%d,%s", type, id, port, addr) + && _parser.recv("+OK") + && _parser.send("AT+SAVE") + && _parser.recv("+OK") + && reset("REBOOT") + && _parser.recv("+EVENT=REBOOT"); + + wait(3); + char conType[10]; // UDP/TCP connection type: SERVER, CLIENT, BROADCAST, UNICAST + int socketId; // UDP/TCP socket id + + // Receive wifi connect event + state2 = _parser.recv("+EVENT=WIFI_LINK,STATION_UP") + && _parser.recv("+EVENT=%[^,],CONNECT,%d", conType, &socketId); + + if (state1 && state2) + return socketId; + else + return -1; +} + +bool ESP8266::send(int id, const void *data, uint32_t amount) +{ + //May take a second try if device is busy + for (unsigned i = 0; i < 2; i++) { + if (_parser.send("AT+SSEND=%d,%d", id, amount) + && _parser.recv(">") + && _parser.write((char*)data, (int)amount) >= 0 + && _parser.recv("+OK")) { + //wait(3); + return true; + } + } + + return false; +} + +void ESP8266::_packet_handler() +{ + int id; + uint32_t amount; + + // parse out the packet + if (!_parser.recv(",%d,%d,", &id, &amount)) { + return; + } + + struct packet *packet = (struct packet*)malloc( + sizeof(struct packet) + amount); + if (!packet) { + return; + } + + packet->id = id; + packet->len = amount; + packet->next = 0; + + if (!(_parser.read((char*)(packet + 1), amount))) { + free(packet); + return; + } + + // append to packet list + *_packets_end = packet; + _packets_end = &packet->next; +} + +int32_t ESP8266::recv(int id, void *data, uint32_t amount) +{ + while (true) { + // check if any packets are ready for us + for (struct packet **p = &_packets; *p; p = &(*p)->next) { + if ((*p)->id == id) { + struct packet *q = *p; + + if (q->len <= amount) { // Return and remove full packet + memcpy(data, q+1, q->len); + + if (_packets_end == &(*p)->next) { + _packets_end = p; + } + *p = (*p)->next; + + uint32_t len = q->len; + free(q); + return len; + } else { // return only partial packet + memcpy(data, q+1, amount); + + q->len -= amount; + memmove(q+1, (uint8_t*)(q+1) + amount, q->len); + + return amount; + } + } + } + + // Wait for inbound packet + if (!_parser.recv("#")) { + return -1; + } + } +} + +bool ESP8266::close(int id) +{ + //May take a second try if device is busy + for (unsigned i = 0; i < 2; i++) { + if (_parser.send("AT+CONF=1,OFF") + && _parser.recv("+OK")) { + char conType[10]; // Used for UDP/TCP connection type: SERVER, CLIENT, BROADCAST, UNICAST + int socketId; // Used for UDP/TCP socket id + + _parser.recv("+EVENT=%[^,],DISCONNECT,%d", conType, &socketId); + return true; + } + } + + return false; +} + +void ESP8266::setTimeout(uint32_t timeout_ms) +{ + _parser.setTimeout(timeout_ms); +} + +bool ESP8266::readable() +{ + return _serial.readable(); +} + +bool ESP8266::writeable() +{ + return _serial.writeable(); +} + +void ESP8266::attach(Callback<void()> func) +{ + _serial.attach(func); +}
diff -r 000000000000 -r 65ba09002ce8 emw3162/EMW3162.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emw3162/EMW3162.h Tue Nov 01 12:43:30 2016 +0000 @@ -0,0 +1,181 @@ +/* ESP8266Interface Example + * Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ESP8266_H +#define ESP8266_H + +#include "ATParser.h" + +/** ESP8266Interface class. + This is an interface to a ESP8266 radio. + */ +class ESP8266 +{ +public: + ESP8266(PinName tx, PinName rx, bool debug=false); + + /** + * Startup the ESP8266 + * + * @param mode mode of WIFI 1-client, 2-host, 3-both + * @return true only if ESP8266 was setup correctly + */ + bool startup(); + + /** + * Reset ESP8266 + * + * @return true only if ESP8266 resets successfully + */ + bool reset(const char *reset); + + /** + * Enable/Disable DHCP + * + * @param enabled DHCP enabled when true + * @param mode mode of DHCP 0-softAP, 1-station, 2-both + * @return true only if ESP8266 enables/disables DHCP successfully + */ + bool dhcp(bool enabled); + + /** + * Connect ESP8266 to AP + * + * @param ap the name of the AP + * @param passPhrase the password of AP + * @return true only if ESP8266 is connected successfully + */ + bool connect(const char *ap, const char *passPhrase); + + /** + * Disconnect ESP8266 from AP + * + * @return true only if ESP8266 is disconnected successfully + */ + bool disconnect(void); + + /** + * Get the IP address of ESP8266 + * + * @return null-teriminated IP address or null if no IP address is assigned + */ + const char *getIPAddress(void); + + /** + * Get the MAC address of ESP8266 + * + * @return null-terminated MAC address or null if no MAC address is assigned + */ + const char *getMACAddress(void); + + /** + * Check if ESP8266 is conenected + * + * @return true only if the chip has an IP address + */ + bool isConnected(void); + + /** + * Open a socketed connection + * + * @param type the type of socket to open "UDP" or "TCP" + * @param id id to give the new socket, valid 0-4 + * @param port port to open connection with + * @param addr the IP address of the destination + * @return true only if socket opened successfully + */ + int open(const char *type, int id, const char* addr, int port); + + /** + * Sends data to an open socket + * + * @param id id of socket to send to + * @param data data to be sent + * @param amount amount of data to be sent - max 1024 + * @return true only if data sent successfully + */ + bool send(int id, const void *data, uint32_t amount); + + /** + * Receives data from an open socket + * + * @param id id to receive from + * @param data placeholder for returned information + * @param amount number of bytes to be received + * @return the number of bytes received + */ + int32_t recv(int id, void *data, uint32_t amount); + + /** + * Closes a socket + * + * @param id id of socket to close, valid only 0-4 + * @return true only if socket is closed successfully + */ + bool close(int id); + + /** + * Allows timeout to be changed between commands + * + * @param timeout_ms timeout of the connection + */ + void setTimeout(uint32_t timeout_ms); + + /** + * Checks if data is available + */ + bool readable(); + + /** + * Checks if data can be written + */ + bool writeable(); + + /** + * Attach a function to call whenever network state has changed + * + * @param func A pointer to a void function, or 0 to set as none + */ + void attach(Callback<void()> func); + + /** + * Attach a function to call whenever network state has changed + * + * @param obj pointer to the object to call the member function on + * @param method pointer to the member function to call + */ + template <typename T, typename M> + void attach(T *obj, M method) { + attach(Callback<void()>(obj, method)); + } + +private: + BufferedSerial _serial; + ATParser _parser; + + struct packet { + struct packet *next; + int id; + uint32_t len; + // data follows + } *_packets, **_packets_end; + void _packet_handler(); + + char _ip_buffer[16]; + char _mac_buffer[18]; +}; + +#endif