Network APIs
APIs to perform various networking tasks, such as open server sockets on the Dev Board Micro, connect to other sockets as a client, create HTTP servers, connect to Wi-Fi networks, and more.
Note
If using SSL (with Curl or Mbed TLS), you must first call
A71ChInit()
to initialize the a71ch crypto chip.
TCP/IP sockets
APIs to create TCP/IP network socket servers and client connections with the Dev Board Micro.
All socket communication is facilitated by read/write functions that require
a socket file descriptor, which you can get by creating a new server with
SocketServer()
, accepting an incoming client connection
with SocketAccept()
, or initiating a client connection
with SocketClient()
.
For an example, see examples/audio_streaming/
.
-
namespace
coralmicro
Enums
Functions
-
IOStatus
ReadBytes
(int fd, void *bytes, size_t size)¶ Reads data from a socket file descriptor to a buffer.
- Parameters
fd – The file descriptor to read from.
bytes – The buffer to output the data.
size – The number of bytes to read.
- Returns
The status result of the operation.
-
template<typename
T
>
IOStatusReadArray
(int fd, T *array, size_t array_size)¶ Read an array of data from a socket file descriptor.
- Parameters
fd – The file descriptor to read from.
array – The array to output the data to.
array_size – The size of the array.
- Template Parameters
T – The data type of the array.
- Returns
The status result of the operation.
-
IOStatus
WriteBytes
(int fd, const void *bytes, size_t size, size_t chunk_size = 1024)¶ Writes data from a buffer into a socket file descriptor.
- Parameters
fd – The file descriptor to write to.
bytes – The buffer of data to write.
size – The size of the buffer.
chunk_size – The size of the chunk to write.
- Returns
The status result of the operation.
-
template<typename
T
>
IOStatusWriteArray
(int fd, const T *array, size_t array_size)¶ Writes data from an array into a socket file descriptor.
- Parameters
fd – The file descriptor to write to.
array – The array of data to write.
size – The size of the array.
chunk_size – The size of the chunk to write.
- Template Parameters
T – The data type of the array.
- Returns
The status result of the operation.
-
IOStatus
WriteMessage
(int fd, uint8_t type, const void *bytes, size_t size, size_t chunk_size = 1024)¶ Writes a
message
with custom type from a buffer into a socket file descriptor.The
message
is going to have a 40 bits prefix that contains 32 bits for the size and 8 bits for the custom message type, following by the bytes.- Parameters
fd – The file descriptor to write to.
type – The type of the message. This parameter can be used to create custom message type.
bytes – The buffer of data to write.
size – The size of the buffer.
chunk_size – The size of the chunk to write.
- Returns
The status result of the operation.
-
bool
SocketHasPendingInput
(int sockfd)¶ Checks whether a socket file descriptor still has some bytes to read.
- Parameters
sockfd – The socket file descriptor to check.
- Returns
True if there are bytes remaining to read; false otherwise.
-
int
SocketServer
(int port, int backlog)¶ Starts a new TCP socket server.
- Parameters
port – The port to listen on.
backlog – The maximum length to which the queue of pending connections for sockfd may grow
- Returns
The server’s socket file descriptor.
-
int
SocketAccept
(int sockfd)¶ Accepts a connection request from a listening socket.
- Parameters
sockfd – The listening socket file descriptor.
- Returns
The client’s socket file descriptor.
-
void
SocketClose
(int sockfd)¶ Close a socket.
- Parameters
sockfd – The socket file descriptor to close.
-
int
SocketClient
(ip_addr_t ip, int port)¶ Starts a client-side connection with a server.
- Parameters
ip – The server’s ip address.
port – The server’s port number.
- Returns
The server’s socket file descriptor.
-
int
SocketClient
(const char *host, int port)¶ Starts a client-side connection with a server.
- Parameters
host – The server’s hostname.
port – The server’s port number.
- Returns
The server’s socket file descriptor.
-
int
SocketAvailable
(int sockfd)¶ Checks if a socket has available bytes to read.
- Parameters
sockfd – The socket file descriptor to check.
- Returns
Number of bytes that can be read from the socket.
-
ip4_addr_t
DnsGetServer
()¶ Retrieves the configured DNS server for the network.
- Returns
ip4_addr_t
containing the IP address where DNS requests are sent.
-
void
DnsSetServer
(ip4_addr_t addr, bool persist)¶ Sets the DNS server for the network, and optionally persists it to flash memory.
- Parameters
addr – The address for the DNS server.
persist – True to persist the address to flash; false otherwise.
-
IOStatus
Ethernet network
APIs to get online via Ethernet and read network details.
Note
Using Ethernet requires the Coral PoE Add-on board (or similar add-on).
To get started, just call EthernetInit()
. If it returns
true, then you’re connected to the network and you can use other functions to
query details such as the board IP address and MAC address.
For example code that uses Curl over Ethernet, see examples/curl/
.
-
namespace
coralmicro
Functions
-
struct netif *
EthernetGetInterface
()¶ Gets the ethernet interface, which contains info like ip and hw addresses, interface names, etc.
- Returns
A pointer to the netif ethernet interface, or nullptr if
EthernetInit()
has not been called or the POE add-on board failed to initialize. See: https://os.mbed.com/docs/mbed-os/v6.15/mbed-os-api-doxy/structnetif.html
-
bool
EthernetInit
(bool default_iface)¶ Initializes the ethernet module.
This function requires that the POE add-on board is connected and it must be called before
EthernetGetInterface()
.- Parameters
default_iface – True sets ethernet as the default network interface, false disables it.
- Returns
True if ethernet successfully initialized; false otherwise.
-
std::optional<std::string>
EthernetGetIp
()¶ Gets the device’s Ethernet IP address, with a timeout of 30s.
- Returns
A string representing the IPv4 IP address or
std::nullopt
on failure.
-
std::optional<std::string>
EthernetGetIp
(uint64_t timeout_ms)¶ Gets the device’s Ethernet IP address.
- Parameters
timeout_ms – Amount of time to wait for DHCP to finish, in milliseconds.
- Returns
A string representing the IPv4 IP address or
std::nullopt
on failure.
-
std::array<uint8_t, 6>
EthernetGetMacAddress
()¶ Gets the assigned MAC address from the device fuses.
- Returns
The MAC address assigned to the device.
-
std::optional<std::string>
EthernetGetSubnetMask
()¶
-
std::optional<std::string>
EthernetGetSubnetMask
(uint64_t timeout_ms)¶
-
std::optional<std::string>
EthernetGetGateway
()¶
-
std::optional<std::string>
EthernetGetGateway
(uint64_t timeout_ms)¶
-
int
EthernetGetSpeed
()¶ Retrieves the ethernet speed that is stored in flash memory.
- Returns
The ethernet speed in Mbps. The default return value is 100, if no value is stored in flash.
-
bool
EthernetSetStaticIp
(ip4_addr_t addr)¶ Stores an IP address in flash memory, to be used as the Ethernet IP.
- Parameters
addr – IP address to store.
- Returns
True if the address was stored successfully; false otherwise.
-
bool
EthernetSetStaticSubnetMask
(ip4_addr_t addr)¶ Stores an IP address in flash memory, to be used as the Ethernet subnet mask.
- Parameters
addr – IP address to store.
- Returns
True if the address was stored successfully; false otherwise.
-
bool
EthernetSetStaticGateway
(ip4_addr_t addr)¶ Stores an IP address in flash memory, to be used as the Ethernet gateway address.
- Parameters
addr – IP address to store.
- Returns
True if the address was stored successfully; false otherwise.
-
struct netif *
Wi-Fi network
APIs to get online and perform basic Wi-Fi tasks, such as scan for Wi-Fi networks, connect to a Wi-Fi network, and read network details.
Note
Using Wi-Fi requires the Coral Wireless Add-on board (or similar add-on).
To get started, call WiFiTurnOn()
to enable the Wi-Fi
module, and then call WiFiConnect()
to connect to a
Wi-Fi network.
For example code that uses Curl over Wi-Fi, see examples/curl/
.
-
namespace
coralmicro
Enums
Functions
-
bool
WiFiGetDefaultSsid
(std::string *wifi_ssid_out)¶ Gets the Wi-Fi SSID that is stored in flash memory.
- Parameters
wifi_ssid_out – A pointer to a string in which to store the SSID.
- Returns
True if the SSID was successfully retrieved; false otherwise.
-
bool
WiFiSetDefaultSsid
(const std::string &wifi_ssid)¶ Sets the Wi-Fi SSID in flash memory.
- Parameters
wifi_ssid – A pointer to a string containing the SSID.
- Returns
True if the SSID was successfully stored; false otherwise.
-
bool
WiFiGetDefaultPsk
(std::string *wifi_psk_out)¶ Gets the Wi-Fi key that is stored in flash memory.
- Parameters
wifi_ssid_out – A pointer to a string in which to store the SSID.
- Returns
True if the SSID was successfully retrieved; false otherwise.
-
bool
WiFiSetDefaultPsk
(const std::string &wifi_psk)¶ Sets the Wi-Fi key in flash memory.
- Parameters
wifi_psk – A pointer to a string containing the key.
- Returns
True if the key was successfully stored; false otherwise.
-
bool
WiFiTurnOn
(bool default_iface)¶ Turns on the Wi-Fi module.
- Parameters
default_iface – True sets Wi-Fi as the default network interface.
- Returns
True if successfully turned on; false otherwise.
-
bool
WiFiTurnOff
()¶ Turns off the Wi-Fi module.
- Returns
True if successfully turned off; false otherwise.
-
bool
WiFiIsConnected
()¶ Checks if the board is connected to a Wi-Fi network.
- Returns
True if it is connected; false otherwise.
-
bool
WiFiConnect
(const WIFINetworkParams_t &network_params, int retry_count = kDefaultRetryCount)¶ Connects to a Wi-Fi network.
- Parameters
network_params – A pointer to a
WIFINetworkParams_t
that contains information of the ssid such as name, password, and security type. See: https://aws.github.io/amazon-freertos/202107.00/html1/struct_w_i_f_i_network_params__t.htmlretry_count – The max number of connection attempts. Default is 5.
- Returns
True if successfully connected to Wi-Fi; false otherwise.
-
bool
WiFiConnect
(const char *ssid, const char *psk, int retry_count = kDefaultRetryCount)¶ Connects to a Wi-Fi network with the given network name and password.
- Parameters
ssid – The network name.
psk – The password for the ssid.
retry_count – The max number of connection attempts. Default is 5.
- Returns
True if successfully connected to Wi-Fi; false otherwise.
-
bool
WiFiConnect
(int retry_count = kDefaultRetryCount)¶ Connects to the Wi-Fi network that’s saved on the device.
Internally, this API reads the stored ssid and password using
utils::GetWiFiSSID()
andutils::GetWiFiPSK()
, which could both be set either during flash with the--wifi_ssid
and--wifi_psk
flags or with a direct call toutils::SetWiFiSSID()
andutils::SetWiFiPSK()
.- Parameters
retry_count – The max number of connection attempts. Default is 5.
- Returns
True if successfully connected to Wi-Fi; false otherwise.
-
bool
WiFiDisconnect
(int retry_count = kDefaultRetryCount)¶ Disconnects from the Wi-Fi network.
- Parameters
retry_count – The max number of disconnect attempts. Default is 5.
- Returns
True if Wi-Fi is successfully disconnected; false otherwise.
-
std::vector<WIFIScanResult_t>
WiFiScan
()¶ Scans for Wi-Fi networks.
- Returns
A vector of
WIFIScanResult_t
which contains info like name, security type, etc. See: https://aws.github.io/amazon-freertos/202107.00/html1/struct_w_i_f_i_scan_result__t.html
-
std::optional<std::string>
WiFiGetIp
()¶ Gets the device’s Wi-Fi IP address.
- Returns
A string representing the IPv4 IP address or
std::nullopt
on failure.
-
std::optional<std::array<uint8_t, 6>>
WiFiGetMac
()¶ Gets the device’s Wi-Fi MAC address.
- Returns
Byte array containing the MAC address or
std::nullopt
on failure.
-
std::optional<std::array<uint8_t, 6>>
WiFiGetBssid
()¶ Gets the BSSID (MAC address of connected Access Point).
- Returns
Byte array containing the MAC address or
std::nullopt
on failure.
-
std::optional<int32_t>
WiFiGetRssi
()¶ Gets the RSSI of the connected access point.
- Returns
Signal strength in dBm or
std::nullopt
on failure.
-
void
WiFiSetAntenna
(WiFiAntenna antenna)¶ Sets which Wi-Fi antenna type to use (internal or external).
- Parameters
antenna – The type of antenna to use.
Variables
-
constexpr int
kDefaultRetryCount
= {5}¶
-
bool
HTTP server
APIs to create an HTTP server on the Dev Board Micro.
To get started, create an instance of
HttpServer
and call UriHandler
to specify a callback function that handles incoming requests. Then pass the
HttpServer
to UseHttpServer()
.
For example, this code creates an HTTP server that responds with a “Hello World”
web page (from examples/http_server/
):
namespace coralmicro {
namespace {
HttpServer::Content UriHandler(const char* path) {
printf("Request received for %s\r\n", path);
std::vector<uint8_t> html;
html.reserve(64);
if (std::strcmp(path, "/hello.html") == 0) {
printf("Hello World!\r\n");
StrAppend(&html, "<html><body>Hello World!</body></html>");
return html;
}
return {};
}
void Main() {
printf("HTTP Server Example!\r\n");
// Turn on Status LED to show the board is on.
LedSet(Led::kStatus, true);
printf("Starting server...\r\n");
HttpServer http_server;
http_server.AddUriHandler(UriHandler);
UseHttpServer(&http_server);
std::string ip;
if (GetUsbIpAddress(&ip)) {
printf("GO TO: http://%s/%s\r\n", ip.c_str(), "hello.html");
}
vTaskSuspend(nullptr);
}
} // namespace
} // namespace coralmicro
extern "C" void app_main(void* param) {
(void)param;
coralmicro::Main();
vTaskSuspend(nullptr);
}
-
namespace
coralmicro
-
class
HttpServer
¶ - #include <http_server.h>
Defines an HTTP server on the device.
This is a light wrapper around the lwIP stack. For more detail, see https://www.nongnu.org/lwip/2_1_x/index.html.
For an example, see examples/http_server/http_server.cc.
-
struct
StaticBuffer
¶ - #include <http_server.h>
Defines a static buffer in which to return data from the server.
Public Functions
-
virtual
~HttpServer
() = default¶
-
inline virtual err_t
PostBegin
(void *connection, const char *uri, const char *http_request, u16_t http_request_len, int content_len, char *response_uri, u16_t response_uri_len, u8_t *post_auto_wnd)¶ Called when an HTTP POST request is first received. This must be implemented by subclasses that want to handle posts.
- Parameters
connection – Unique connection identifier, valid until
PostFinished()
is called.uri – The HTTP header URI receiving the POST request.
http_request – The raw HTTP request (the first packet, normally).
http_request_len – Size of ‘http_request’.
content_len – Content-Length from HTTP header.
response_uri – Filename of response file, to be filled when denying the request.
response_uri_len – Size of the ‘response_uri’ buffer.
post_auto_wnd – Set this to 0 to let the callback code handle window updates by calling
httpd_post_data_recved
(to throttle rx speed) default is 1 (httpd handles window updates automatically)
-
inline virtual err_t
PostReceiveData
(void *connection, struct pbuf *p)¶ Called for each packet buffer of data that is received for a POST.
- Parameters
connection – Unique connection identifier.
p – Received data as a pbuf. ATTENTION: Your application is responsible for freeing the pbufs!
-
inline virtual void
PostFinished
(void *connection, char *response_uri, u16_t response_uri_len)¶ Called when all data is received or when the connection is closed. The application must return the filename/URI of a file to send in response to this POST request. If the response_uri buffer is untouched, a 404 response is returned.
- Parameters
connection – Unique connection identifier.
response_uri – Filename of response file, to be filled when denying the request.
response_uri_len – Size of the ‘response_uri’ buffer.
-
inline virtual void
CgiHandler
(struct fs_file *file, const char *uri, int iNumParams, char **pcParam, char **pcValue)¶ Called once to handle CGI for every URI with parameters.
- Parameters
file – The file received.
uri – The HTTP header URI.
iNumParams – The number of parameters in the URI.
pcParam – Parameter names from the URI.
pcValue – Values for each parameter. file, uri, count, http_cgi_params, http_cgi_param_vals
-
virtual int
FsOpenCustom
(struct fs_file *file, const char *name)¶ Called first for every opened file to allow opening custom files that are not included in fsdata(_custom).c.
-
virtual int
FsReadCustom
(struct fs_file *file, char *buffer, int count)¶ Called to read custom files.
-
virtual void
FsCloseCustom
(struct fs_file *file)¶ Called to close custom files.
-
inline void
AddUriHandler
(UriHandler handler)¶ Adds a URI handler function for the server.
You can specify multiple handlers and incoming requests will be sent to the handlers in the order that each handler was added with this function. That is, the first handler you add receives all requests first, and if it does not handle it, then it is sent to the next handler, and so on.
- Parameters
handler – A callback function to handle each incoming HTTP request. It must accept the URI path as a char string and return the response as
Content
.
Public Types
-
using
Content
= std::variant<std::monostate, std::string, std::vector<uint8_t>, StaticBuffer>¶ Defines the allowed response types returned by
AddUriHandler()
. Successful requests will typically respond with the content in a string, a dynamic buffer (a vector), or aStaticBuffer
, or an empty vector if the URI is unhandled.
-
using
UriHandler
= std::function<Content(const char *uri)>¶ Represents the callback function type required by
AddUriHandler()
.
-
struct
Functions
-
void
UseHttpServer
(HttpServer *server)¶ Starts an HTTP server.
To handle server requests, you must pass your implementation of
UriHandler()
toAddUriHandler()
.- Parameters
The – server to start.
-
class
RPC HTTP server
APIs to create an RPC server on the Dev Board Micro.
The setup is the same as HttpServer
but you must pass
an instance of JsonRpcHttpServer
to
UseHttpServer()
and also initialize jsonrpc
.
Note
You must also include third_party/mjson/src/mjson.h
to initialize
with jsonrpc_init()
and specify RPC functions with jsonrpc_export()
.
For example, this code creates an RPC server that responds with the board
serial number (from examples/rpc_server/
):
namespace coralmicro {
namespace {
void SerialNumber(struct jsonrpc_request* r) {
auto serial = GetSerialNumber();
jsonrpc_return_success(r, "{%Q:%.*Q}", "serial_number", serial.size(),
serial.c_str());
}
void Main() {
printf("RPC Server Example!\r\n");
// Turn on Status LED to show the board is on.
LedSet(Led::kStatus, true);
jsonrpc_init(nullptr, nullptr);
jsonrpc_export("serial_number", SerialNumber);
UseHttpServer(new JsonRpcHttpServer);
printf("RPC server ready\r\n");
}
} // namespace
} // namespace coralmicro
extern "C" void app_main(void* param) {
(void)param;
coralmicro::Main();
vTaskSuspend(nullptr);
}
-
namespace
coralmicro
-
class
JsonRpcHttpServer
: public coralmicro::HttpServer¶ - #include <rpc_http_server.h>
Public Functions
-
inline explicit
JsonRpcHttpServer
(struct jsonrpc_ctx *ctx = &jsonrpc_default_context)¶
-
virtual err_t
PostBegin
(void *connection, const char *uri, const char *http_request, u16_t http_request_len, int content_len, char *response_uri, u16_t response_uri_len, u8_t *post_auto_wnd) override¶ Called when an HTTP POST request is first received. This must be implemented by subclasses that want to handle posts.
- Parameters
connection – Unique connection identifier, valid until
PostFinished()
is called.uri – The HTTP header URI receiving the POST request.
http_request – The raw HTTP request (the first packet, normally).
http_request_len – Size of ‘http_request’.
content_len – Content-Length from HTTP header.
response_uri – Filename of response file, to be filled when denying the request.
response_uri_len – Size of the ‘response_uri’ buffer.
post_auto_wnd – Set this to 0 to let the callback code handle window updates by calling
httpd_post_data_recved
(to throttle rx speed) default is 1 (httpd handles window updates automatically)
-
virtual err_t
PostReceiveData
(void *connection, struct pbuf *p) override¶ Called for each packet buffer of data that is received for a POST.
- Parameters
connection – Unique connection identifier.
p – Received data as a pbuf. ATTENTION: Your application is responsible for freeing the pbufs!
-
virtual void
PostFinished
(void *connection, char *response_uri, u16_t response_uri_len) override¶ Called when all data is received or when the connection is closed. The application must return the filename/URI of a file to send in response to this POST request. If the response_uri buffer is untouched, a 404 response is returned.
- Parameters
connection – Unique connection identifier.
response_uri – Filename of response file, to be filled when denying the request.
response_uri_len – Size of the ‘response_uri’ buffer.
-
virtual void
CgiHandler
(struct fs_file *file, const char *uri, int iNumParams, char **pcParam, char **pcValue) override¶ Called once to handle CGI for every URI with parameters.
- Parameters
file – The file received.
uri – The HTTP header URI.
iNumParams – The number of parameters in the URI.
pcParam – Parameter names from the URI.
pcValue – Values for each parameter. file, uri, count, http_cgi_params, http_cgi_param_vals
-
virtual int
FsOpenCustom
(struct fs_file *file, const char *name) override¶ Called first for every opened file to allow opening custom files that are not included in fsdata(_custom).c.
-
virtual void
FsCloseCustom
(struct fs_file *file) override¶ Called to close custom files.
-
inline explicit
-
class
RPC utils
-
namespace
coralmicro
Functions
-
void
JsonRpcReturnBadParam
(struct jsonrpc_request *request, const char *message, const char *param_name)¶ Response a JSONRPC_ERROR_BAD_PARAMS code to the requester.
- Parameters
request – The request to response to.
message – The message to send back to the requester.
param_name – The name of the bad param.
-
bool
JsonRpcGetIntegerParam
(struct jsonrpc_request *request, const char *param_name, int *out)¶ Gets an integer param from RPC request.
- Parameters
request – The request to parse the integer.
param_name – The name of the parameter to parse.
out – The integer to return the value to.
- Returns
True if the param were parsed successfully, else False.
-
bool
JsonRpcGetBooleanParam
(struct jsonrpc_request *request, const char *param_name, bool *out)¶ Gets a boolean param from RPC request.
- Parameters
request – The request to parse the boolean.
param_name – The name of the parameter to parse.
out – The boolean to return the value to.
- Returns
True if the param were parsed successfully, else False.
-
bool
JsonRpcGetStringParam
(struct jsonrpc_request *request, const char *param_name, std::string *out)¶ Gets a string param from RPC request.
- Parameters
request – The request to parse the string.
param_name – The name of the parameter to parse.
out – The string to return the value to.
- Returns
True if the param were parsed successfully, else False.
-
bool
JsonRpcGetBase64Param
(struct jsonrpc_request *request, const char *param_name, std::vector<uint8_t> *out)¶ Gets a base64 encoded string param from RPC request.
- Parameters
request – The request to parse the string.
param_name – The name of the parameter to parse.
out – The output array to return the value to.
- Returns
True if the param were parsed successfully, else False.
-
void
Device information
-
namespace
coralmicro
Functions
-
uint64_t
GetUniqueId
()¶ Gets the 64-bit unique identifiers of the RT1176.
- Returns
64-bit value that is unique to the device.
-
std::string
GetSerialNumber
()¶ Gets the hex string representation of the unique identifier.
- Returns
String containing the 64-bit unique identifier, as a printable hex string.
-
bool
GetUsbIpAddress
(std::string *usb_ip_out)¶ Gets the USB IP address that is stored in flash memory.
- Parameters
usb_ip_out – A pointer to a string in which to store a printable version of the IP.
- Returns
True if the address was successfully retrieved; false otherwise.
-
bool
GetIpFromFile
(const char *path, ip4_addr_t *addr)¶ Attempts to open a given file at
path
, and if the contents are an IP address, return them inaddr
.- Parameters
path – File path to read an address from.
addr – Pointer to an
ip4_addr_t
that the address will be stored in.
- Returns
True if successful; false otherwise.
-
uint64_t
Is this content helpful?