Maxim Integrated / Mbed 2 deprecated DeepCover Embedded Security in IoT

Dependencies:   MaximInterface mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ESP8266.hpp Source File

ESP8266.hpp

00001 /*******************************************************************************
00002 * Copyright (C) 2016 Maxim Integrated Products, Inc., All Rights Reserved.
00003 *
00004 * Permission is hereby granted, free of charge, to any person obtaining a
00005 * copy of this software and associated documentation files (the "Software"),
00006 * to deal in the Software without restriction, including without limitation
00007 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
00008 * and/or sell copies of the Software, and to permit persons to whom the
00009 * Software is furnished to do so, subject to the following conditions:
00010 *
00011 * The above copyright notice and this permission notice shall be included
00012 * in all copies or substantial portions of the Software.
00013 *
00014 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
00015 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
00016 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
00017 * IN NO EVENT SHALL MAXIM INTEGRATED BE LIABLE FOR ANY CLAIM, DAMAGES
00018 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
00019 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
00020 * OTHER DEALINGS IN THE SOFTWARE.
00021 *
00022 * Except as contained in this notice, the name of Maxim Integrated
00023 * Products, Inc. shall not be used except as stated in the Maxim Integrated
00024 * Products, Inc. Branding Policy.
00025 *
00026 * The mere transfer of this software does not imply any licenses
00027 * of trade secrets, proprietary technology, copyrights, patents,
00028 * trademarks, maskwork rights, or any other form of intellectual
00029 * property whatsoever. Maxim Integrated Products, Inc. retains all
00030 * ownership rights.
00031 *******************************************************************************/
00032 
00033 #ifndef ESP8266_HPP
00034 #define ESP8266_HPP
00035 
00036 #include <string>
00037 #include <sstream>
00038 #include <PinNames.h>
00039 #include <Serial.h>
00040 #include <DigitalOut.h>
00041 #include <CircularBuffer.h>
00042 
00043 /// Interface to the ESP8266 Wi-Fi module.
00044 class ESP8266 {
00045 public:
00046   /// Result of sending an AT command.
00047   enum CmdResult {
00048     AT_OK = 1,
00049     AT_FAIL = 0,
00050     AT_ERROR = -1,
00051     HardwareError = -2,
00052     TimeoutError = -3
00053   };
00054 
00055   /// ESP8266 Wi-Fi mode.
00056   enum WifiMode { station_mode = 1, softAP_mode = 2, softAP_station_mode = 3 };
00057 
00058   /// Connection type.
00059   enum ConnType { TCP, UDP };
00060 
00061   /// Recovery time between Send Data operation as specified by datasheet.
00062   static const int sendDataRecoveryTimeMs = 1000;
00063 
00064   /// Builds command strings for the ESP8266 with proper formatting.
00065   class CmdBuilder {
00066   public:
00067     /// @param cmd Command of the format "AT+[cmd]".
00068     CmdBuilder (const std::string & cmd = "");
00069 
00070     /// Clear all arguments.
00071     /// @param cmd Command of the format "AT+[cmd]".
00072     void clear(const std::string & cmd);
00073 
00074     /// Append an argument using the default string conversion for that type.
00075     /// @param arg Argument to append to the command.
00076     template <typename T> void addRawArgument(const T & arg) {
00077       cmdStream << ((numArgs == 0) ? "=" : ",") << arg;
00078       numArgs++;
00079     }
00080 
00081     /// Append a string argument with proper quoting.
00082     /// @param arg Argument to append to the command.
00083     void addStringArgument(const std::string & arg);
00084 
00085     /// Create a string suitable for use with sendCommand().
00086     /// @returns The formatted command string.
00087     std::string str() const;
00088 
00089   private:
00090     int numArgs;
00091     std::ostringstream cmdStream;
00092   };
00093 
00094   /// @param tx Transmit pin from mbed to ESP8266.
00095   /// @param rx Receive pin from ESP8266 to mbed.
00096   /// @param rst Reset pin on ESP8266.
00097   /// @param CH_PD Power-down pin on ESP8266.
00098   /// @param baud Baud rate that the ESP8266 is using.
00099   /// @param debugMsgIntf Optional serial interface for debugging messages.
00100   ESP8266 (const PinName tx, const PinName rx, const PinName rst,
00101           const PinName CH_PD, const int baud,
00102           mbed::Serial * debugMsgIntf = NULL);
00103 
00104   /// Reset the ESP8266 via the hardware reset pin.
00105   void reset();
00106 
00107   // Update the baud rate for the ESP8266.
00108   void setBaud(int baud) { AT_intf.baud(baud); }
00109 
00110   /// @{
00111   /// Control if the ESP8266 is powered via the hardware power-down pin.
00112   bool powered () const;
00113   void setPowered(bool powered );
00114   /// @}
00115 
00116   /// Perform a self-test on the ESP8266.
00117   CmdResult performSelfTest();
00118 
00119   /// Set the current Wi-Fi mode.
00120   CmdResult setCurrentWifiMode(const WifiMode mode);
00121 
00122   /// Join a Wi-Fi access point.
00123   /// @param ssid Network SSID to connect to.
00124   /// @param pwd Network password.
00125   /// @param bssid Optional network BSSID.
00126   CmdResult joinCurrentAccessPoint(const std::string & ssid,
00127                                    const std::string & pwd,
00128                                    const std::string & bssid = "");
00129 
00130   /// Quit the current access point.
00131   CmdResult quitAccessPoint();
00132 
00133   /// Set the maximum WiFi tranmission power.
00134   /// @param power_dBm Power in dBm valid from 0 to 20.5 in 0.25 dBm increments.
00135   CmdResult setMaxRFTXPower(const float power_dBm);
00136 
00137   /// Ping a host via the current access point.
00138   /// @param IP IP address or resolvable hostname.
00139   CmdResult ping(const std::string & IP);
00140 
00141   /// Open a connection to a host via the current access point.
00142   /// @param type TCP or UPD connection.
00143   /// @param remoteIP IP address or resolvable hostname to connect to.
00144   /// @param remotePort Port on the host to connect to.
00145   CmdResult openConnection(const ConnType type, const std::string & remoteIP,
00146                            const unsigned int remotePort);
00147 
00148   /// Close the connection to the current host.
00149   CmdResult closeConnection();
00150 
00151   /// Send data to the currently connected host.
00152   /// @param data May be in text or binary form.
00153   CmdResult sendData(const std::string & data);
00154 
00155   /// Send an AT command to the ESP8266.
00156   /// @param cmd Formatted command to send.
00157   CmdResult sendCommand(const CmdBuilder & cmd);
00158 
00159   /// Check if received IP data is available in the buffer.
00160   /// @note Allow some processing delay to happen between calls to this function.
00161   /// @returns True if data is available.
00162   bool recvIpDataReadable();
00163   /// Get the next character of received IP data from the buffer.
00164   char getcRecvIpData();
00165   /// Clear all received data from the buffer.
00166   void clearRecvData();
00167 
00168 private:
00169   mbed::Serial AT_intf;
00170   mbed::DigitalOut resetPin;
00171   /// @note Mark as mutable for use in powered().
00172   mutable mbed::DigitalOut powerDownPin;
00173   /// Received IP data buffer.
00174   mbed::CircularBuffer<char, 1024> recvIpDataBuffer;
00175   mbed::Serial * debugMsg;
00176   /// Indicates when AT interface received data parsers should be reset.
00177   volatile bool parseRecvReset;
00178 
00179   /// Send raw AT data to the ESP8266.
00180   /// @param cmdString Data to send.
00181   /// @param expectEcho True if the ESP8266 will echo sent data back.
00182   CmdResult send_AT_data(const std::string & cmdString, const bool expectEcho);
00183 
00184   /// Attempts to read an entire line terminated with \r\n from the AT interface.
00185   /// \r will be preserved in the final string and \n will be stripped.
00186   /// @param line Buffer to store received characters in.
00187   /// @returns True if an entire line was read.
00188   bool read_line(std::string & line);
00189 
00190   /// Callback for when data is received on the AT interface.
00191   void recv_AT_data_cb();
00192   /// Parse the next character received on the AT interface checking for valid IP data.
00193   void parseRecvIpData(const char received);
00194   /// Parse the next character receive on the AT interface for the connection
00195   /// closed message.
00196   void parseRecvConnClosedMsg(const char received);
00197 
00198   /// Print a message on the debugging interface if setup.
00199   /// @param message Null terminated string.
00200   void printDbgMsg(const char * message);
00201 };
00202 
00203 #endif