basic/websocket_server/websocket_server.c

See examples/basic/websocket-server

/*
* ZentriOS SDK LICENSE AGREEMENT | Zentri.com, 2015.
*
* Use of source code and/or libraries contained in the ZentriOS SDK is
* subject to the Zentri Operating System SDK license agreement and
* applicable open source license agreements.
*
*/
/* Documentation for this app is available online.
* See https://docs.zentri.com/wifi/sdk/latest/examples/basic/websocket-server
*/
#include "zos.h"
/*************************************************************************************************/
void zn_app_init(void)
{
char buffer[32];
zos_result_t result;
if(zn_load_app_settings("settings.ini") != ZOS_SUCCESS)
{
ZOS_LOG("Failed to load settings");
return;
}
{
ZOS_LOG("Failed to restart network: %d", result);
}
zn_websocket_register_server_event_handlers(websocket_connect_handler, websocket_disconnect_handler, websocket_receive_handler);
zn_network_register_event_handler(ZOS_WLAN, wlan_network_event_handler);
ZOS_LOG("HTTP Server running,");
ZOS_LOG("Using a web browser, go to: http://%s.local", ZOS_GET_SETTING_STR("mdns.name", buffer));
}
/*************************************************************************************************/
zos_bool_t zn_app_idle(void)
{
// Return TRUE so the event loop idles
// It will wakeup when an HTTP request comes in
return ZOS_TRUE;
}
/*************************************************************************************************/
static void wlan_network_event_handler(uint32_t is_up)
{
if(is_up)
{
ZOS_LOG("Network up");
}
else
{
ZOS_LOG("Network down");
}
}
/*************************************************************************************************/
static void websocket_connect_handler(uint32_t handle)
{
char buffer[24];
uint16_t port;
zn_websocket_get_info(handle, buffer, sizeof(buffer), &port);
ZOS_LOG("Websocket connected: %s:%u", buffer, port);
}
/*************************************************************************************************/
static void websocket_disconnect_handler(uint32_t handle)
{
ZOS_LOG("Websocket disconnected: %u", handle);
}
/*************************************************************************************************/
static void websocket_receive_handler(uint32_t handle)
{
char buffer[256];
uint32_t bytes_read;
while(zn_websocket_read(handle, buffer, sizeof(buffer)-1, &bytes_read) == ZOS_SUCCESS)
{
zos_result_t result;
if(bytes_read == 0)
{
break;
}
buffer[bytes_read] = 0;
ZOS_LOG("Rx data: %s", buffer);
if(ZOS_FAILED(result, zn_websocket_write(handle, buffer, bytes_read, ZOS_FALSE)))
{
ZOS_LOG("Failed to send data: %d", result);
}
}
}