Newer
Older
Tardis / src / NetworkHandler.cpp
/*
SPDX-License-Identifier: MIT
Copyright (c) 2023 Casey Reeves and the LuminaSensum contributors
*/

#include "EthernetInterface.h"
#include "mbed-trace/mbed_trace.h"
#include "mbed.h"
#define TRACE_GROUP "NET"

// instantiate the network interface

EthernetInterface eth;

// create a function to allow other part of the program to connect to the
// network

void network_connect(void) { eth.connect(); }

// create a function to disconnect from the network

void network_disconnect(void) { eth.disconnect(); }

// set up a status callback function to monitor for changes

bool is_connected = false;
void status_callback(nsapi_event_t status, intptr_t param) {
	tr_debug("Detected a connection status change.");
	switch (param) {
	case NSAPI_STATUS_CONNECTING:
		tr_info("Connecting to the network");
		break;
	case NSAPI_STATUS_LOCAL_UP:
		tr_debug("Local IP address acquired");
		break;
	case NSAPI_STATUS_GLOBAL_UP:
		if (!is_connected) {
			tr_info("Global IP address acquired.. Networking is "
				"now fully operational.");
			is_connected = true;
		}
		break;
	case NSAPI_STATUS_DISCONNECTED:
		tr_info("No network connection available.");
		if (is_connected) {
			is_connected = false;
		}
		break;
	default:
		tr_info("Networking is not supported.");
		break;
	}
}

// create a function to set the network interface in async mode and attach the
// status callback. This should only be called by main.

void network_init(void) {
	eth.set_blocking(false);
	tr_debug("Network interface now in async mode.");
	eth.attach(&status_callback);
	tr_debug("Status callback now attached to monitor changes.");
}