/*
 * Copyright (c) 2018 Nordic Semiconductor ASA
 *
 * SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
 */

/** @file
 *  @brief Nordic UART Service Client sample
 */

#include <errno.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/sys/printk.h>

#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/hci.h>
#include <zephyr/bluetooth/conn.h>
#include <zephyr/bluetooth/uuid.h>
#include <zephyr/bluetooth/gatt.h>

#include <bluetooth/services/nus.h>
#include <bluetooth/services/nus_client.h>
#include <bluetooth/gatt_dm.h>
#include <bluetooth/scan.h>

#include <zephyr/settings/settings.h>

#include <zephyr/drivers/uart.h>

#include <zephyr/logging/log.h>

#define LOG_MODULE_NAME central_uart
LOG_MODULE_REGISTER(LOG_MODULE_NAME);


// ***************************************************************************************
// This #define enables improved NUS throughput compared to original application.
// This will also display periodic RTT logs showing present throughput.
#define BLE_NUS_THROUGHPUT_MAX

// Only define this if you want to see BLE received data rate, **without** the received data
//  being processed onwards for UART transmission.
//#define BLE_NUS_THROUGHPUT_TEST

// In peripheral_uart, we sometimes see 0.5-0.75sec time to execute bt_nus_send()
// This only seems to occur if central_uart has negotiated security/bonding.
// This very large delay causes a huge drop in BLE throughput, roughly every 29 seconds.
// Appears to be a bug in NCS lower levels. Seen with NCS 1.6.x up to latest NCS 1.8.x
// Working with NordicSemi to address problem.
// With this #define below, this will disable central_uart from establishing a secure link.
//  In this scenario, we then see perfect BLE throughput ( in a clean RF environment )
#define BLE_NUS_DISABLE_BT_CONN_SECURITY
// ***************************************************************************************

#if defined(BLE_NUS_THROUGHPUT_MAX)
  /* UART payload buffer element size, to handle max BLE payload */
  #define UART_BUF_SIZE CONFIG_UART_0_NRF_TX_BUFFER_SIZE
#else
/* UART payload buffer element size. */
#define UART_BUF_SIZE 20
#endif

#define KEY_PASSKEY_ACCEPT DK_BTN1_MSK
#define KEY_PASSKEY_REJECT DK_BTN2_MSK

#define NUS_WRITE_TIMEOUT K_MSEC(150)
#define UART_WAIT_FOR_BUF_DELAY K_MSEC(50)
#define UART_RX_TIMEOUT 50000 /* Wait for RX complete event time in microseconds. */

static const struct device *uart = DEVICE_DT_GET(DT_CHOSEN(nordic_nus_uart));
static struct k_work_delayable uart_work;

K_SEM_DEFINE(nus_write_sem, 0, 1);


// These are changes from original application to support maximum BLE throughput.
#if defined(BLE_NUS_THROUGHPUT_MAX)
  static K_SEM_DEFINE(nus_connection_sem, 0, 1);
  #define INTERVAL_MIN	0x140	/* 320 units, 400 ms */
  #define INTERVAL_MAX	0x140	/* 320 units, 400 ms */
  #define CONN_LATENCY    0

  #define MIN_CONN_INTERVAL   6
  #define MAX_CONN_INTERVAL   3200
  #define SUPERVISION_TIMEOUT 1000

  static struct bt_gatt_exchange_params mtu_exchange_params;

  static struct test_params {
  	struct bt_le_conn_param *conn_param;
  	struct bt_conn_le_phy_param *phy;
  	struct bt_conn_le_data_len_param *data_len;
  } test_params = {
  	.conn_param = BT_LE_CONN_PARAM(INTERVAL_MIN, INTERVAL_MAX, CONN_LATENCY,
  				       SUPERVISION_TIMEOUT),
  	.phy = BT_CONN_LE_PHY_PARAM_2M,
  	.data_len = BT_LE_DATA_LEN_PARAM_MAX
  };

  static volatile bool data_length_req;
  static const char *phy2str(uint8_t phy)
  {
  	switch (phy) {
  	case 0: return "No packets";
  	case BT_GAP_LE_PHY_1M: return "LE 1M";
  	case BT_GAP_LE_PHY_2M: return "LE 2M";
  	case BT_GAP_LE_PHY_CODED: return "LE Coded";
  	default: return "Unknown";
  	}
  }
#endif //defined(BLE_NUS_THROUGHPUT_MAX)


struct uart_data_t {
	void *fifo_reserved;
	uint8_t  data[UART_BUF_SIZE];
	uint16_t len;
};

static K_FIFO_DEFINE(fifo_uart_tx_data);
static K_FIFO_DEFINE(fifo_uart_rx_data);

static struct bt_conn *default_conn;
static struct bt_nus_client nus_client;

static void ble_data_sent(struct bt_nus_client *nus, uint8_t err,
					const uint8_t *const data, uint16_t len)
{
	ARG_UNUSED(nus);
	ARG_UNUSED(data);
	ARG_UNUSED(len);

	k_sem_give(&nus_write_sem);

	if (err) {
		LOG_WRN("ATT error code: 0x%02X", err);
	}
}


#if defined(BLE_NUS_THROUGHPUT_MAX)
static bool ble_data_received_stats(uint16_t len)
{
  // Let's put out on the logs periodically the effective bit rate we are receiving
  static uint32_t   counts_cycles = 0;
  static uint32_t   bytes_rx  = 0;
  static uint32_t   last_bytes_rx  = 0;
  static uint32_t   counts_rx = 0;
  
  // 1st time initialization for counts_cycles on 1st callback into ble_data_received()
  if (!counts_cycles)
  {
    counts_cycles = k_cycle_get_32();
  }
  // Increment the amount of bytes received
  bytes_rx += len;

  #if defined(BLE_NUS_THROUGHPUT_TEST)
    // Every 50 passes, spit out a measurement.
    #define COUNTS_RX_MAX   50
  #else
    #define COUNTS_RX_MAX   10
  #endif
  
  if (!(counts_rx++ % COUNTS_RX_MAX)) {
    counts_cycles = k_cycle_get_32() - counts_cycles;
    // Each cycle is in units of 1/CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC in time
    // Estimate bit rate of data since last time ...  
    // For UART equivalent, use 10 bits/byte
   
    if (counts_cycles) {    
   
      // With this COUNTS_RX_MAX value, data_bps_rate enumerator value will get close to uint32_t limit
      uint32_t data_bps_rate = 
        ( (bytes_rx-last_bytes_rx) * 8 * (uint32_t)CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC)
          / counts_cycles;

		uint32_t rx_bytes = bytes_rx-last_bytes_rx;


      last_bytes_rx = bytes_rx;
        uint32_t  ble_time_ms;
        ble_time_ms = (counts_cycles*1000)/CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC;
     #if defined(BLE_NUS_THROUGHPUT_TEST)
        // Most ble_time_ms peak out in 300ish, but if above 1sec, then Sender will run out of buffers.
        if (ble_time_ms < 1000)   {       
            LOG_INF("BLE time(ms): %d Rx:%d bps(%d bytes)", 
                  ble_time_ms, 
                  data_bps_rate, rx_bytes);
          }
          else {
            LOG_ERR("BLE time(ms): %d Rx:%d bps", 
                  ble_time_ms, 
                  data_bps_rate);
          }
      #else
            LOG_INF("BLE time(ms): %d Rx:%d bps", 
                  ble_time_ms, 
                  data_bps_rate);
      #endif

      // Get current cycle count now, so there are no time capture gaps
      counts_cycles = k_cycle_get_32();
    }
    return true;
  }
  else  {
    return false;
  }
}
#endif //#if defined(BLE_NUS_THROUGHPUT_MAX)


static uint8_t ble_data_received(struct bt_nus_client *nus,
						const uint8_t *data, uint16_t len)
{
	ARG_UNUSED(nus);

	int err;

	#if defined(BLE_NUS_THROUGHPUT_MAX)
      // Display running BLE receive throughput statistics ...
       ble_data_received_stats(len);

      #if defined(BLE_NUS_THROUGHPUT_TEST)
        // Simply return, and so that we can monitor solely BLE receive data throughput,
        //  without processing 'data' onwards to uart transmit operations.
        return BT_GATT_ITER_CONTINUE;
      #endif

    #endif //defined(BLE_NUS_THROUGHPUT_MAX)

	for (uint16_t pos = 0; pos != len;) {
		struct uart_data_t *tx = k_malloc(sizeof(*tx));

		if (!tx) {
			LOG_WRN("Not able to allocate UART send data buffer");
			return BT_GATT_ITER_CONTINUE;
		}

		/* Keep the last byte of TX buffer for potential LF char. */
		size_t tx_data_size = sizeof(tx->data) - 1;

		if ((len - pos) > tx_data_size) {
			tx->len = tx_data_size;
		} else {
			tx->len = (len - pos);
		}

		memcpy(tx->data, &data[pos], tx->len);

		pos += tx->len;

		/* Append the LF character when the CR character triggered
		 * transmission from the peer.
		 */
		if ((pos == len) && (data[len - 1] == '\r')) {
			tx->data[tx->len] = '\n';
			tx->len++;
		}

		err = uart_tx(uart, tx->data, tx->len, SYS_FOREVER_MS);
		if (err) {
			k_fifo_put(&fifo_uart_tx_data, tx);
		}
	}

	return BT_GATT_ITER_CONTINUE;
}

static void uart_cb(const struct device *dev, struct uart_event *evt, void *user_data)
{
	ARG_UNUSED(dev);

	static size_t aborted_len;
	struct uart_data_t *buf;
	static uint8_t *aborted_buf;
	static bool disable_req;

	switch (evt->type) {
	case UART_TX_DONE:
		LOG_DBG("UART_TX_DONE");
		if ((evt->data.tx.len == 0) ||
		    (!evt->data.tx.buf)) {
			return;
		}

		if (aborted_buf) {
			buf = CONTAINER_OF(aborted_buf, struct uart_data_t,
					   data[0]);
			aborted_buf = NULL;
			aborted_len = 0;
		} else {
			buf = CONTAINER_OF(evt->data.tx.buf,
					   struct uart_data_t,
					   data[0]);
		}

		k_free(buf);

		buf = k_fifo_get(&fifo_uart_tx_data, K_NO_WAIT);
		if (!buf) {
			return;
		}

		if (uart_tx(uart, buf->data, buf->len, SYS_FOREVER_MS)) {
			LOG_WRN("Failed to send data over UART");
		}

		break;

	case UART_RX_RDY:
		LOG_DBG("UART_RX_RDY");
		buf = CONTAINER_OF(evt->data.rx.buf, struct uart_data_t, data[0]);
		buf->len += evt->data.rx.len;

		if (disable_req) {
			return;
		}

		if ((evt->data.rx.buf[buf->len - 1] == '\n') ||
		    (evt->data.rx.buf[buf->len - 1] == '\r')) {
			disable_req = true;
			uart_rx_disable(uart);
		}

		break;

	case UART_RX_DISABLED:
		LOG_DBG("UART_RX_DISABLED");
		disable_req = false;

		buf = k_malloc(sizeof(*buf));
		if (buf) {
			buf->len = 0;
		} else {
			LOG_WRN("Not able to allocate UART receive buffer");
			k_work_reschedule(&uart_work, UART_WAIT_FOR_BUF_DELAY);
			return;
		}

		uart_rx_enable(uart, buf->data, sizeof(buf->data),
			       UART_RX_TIMEOUT);

		break;

	case UART_RX_BUF_REQUEST:
		LOG_DBG("UART_RX_BUF_REQUEST");
		buf = k_malloc(sizeof(*buf));
		if (buf) {
			buf->len = 0;
			uart_rx_buf_rsp(uart, buf->data, sizeof(buf->data));
		} else {
			LOG_WRN("Not able to allocate UART receive buffer");
		}

		break;

	case UART_RX_BUF_RELEASED:
		LOG_DBG("UART_RX_BUF_RELEASED");
		buf = CONTAINER_OF(evt->data.rx_buf.buf, struct uart_data_t,
				   data[0]);

		if (buf->len > 0) {
			k_fifo_put(&fifo_uart_rx_data, buf);
		} else {
			k_free(buf);
		}

		break;

	case UART_TX_ABORTED:
		LOG_DBG("UART_TX_ABORTED");
		if (!aborted_buf) {
			aborted_buf = (uint8_t *)evt->data.tx.buf;
		}

		aborted_len += evt->data.tx.len;
		buf = CONTAINER_OF(aborted_buf, struct uart_data_t,
				   data[0]);

		uart_tx(uart, &buf->data[aborted_len],
			buf->len - aborted_len, SYS_FOREVER_MS);

		break;

	default:
		break;
	}
}

static void uart_work_handler(struct k_work *item)
{
	struct uart_data_t *buf;

	buf = k_malloc(sizeof(*buf));
	if (buf) {
		buf->len = 0;
	} else {
		LOG_WRN("Not able to allocate UART receive buffer");
		k_work_reschedule(&uart_work, UART_WAIT_FOR_BUF_DELAY);
		return;
	}

	uart_rx_enable(uart, buf->data, sizeof(buf->data), UART_RX_TIMEOUT);
}

static int uart_init(void)
{
	int err;
	struct uart_data_t *rx;

	if (!device_is_ready(uart)) {
		LOG_ERR("UART device not ready");
		return -ENODEV;
	}

	rx = k_malloc(sizeof(*rx));
	if (rx) {
		rx->len = 0;
	} else {
		return -ENOMEM;
	}

	k_work_init_delayable(&uart_work, uart_work_handler);

	err = uart_callback_set(uart, uart_cb, NULL);
	if (err) {
		return err;
	}

	return uart_rx_enable(uart, rx->data, sizeof(rx->data),
			      UART_RX_TIMEOUT);
}

static void discovery_complete(struct bt_gatt_dm *dm,
			       void *context)
{
	struct bt_nus_client *nus = context;
	LOG_INF("Service discovery completed");

	bt_gatt_dm_data_print(dm);

	bt_nus_handles_assign(dm, nus);
	bt_nus_subscribe_receive(nus);

	bt_gatt_dm_data_release(dm);

	#if defined(BLE_NUS_THROUGHPUT_MAX)
  // This semaphore is given so that main() task can proceed onwards.
  k_sem_give(&nus_connection_sem);
	#endif 
}

static void discovery_service_not_found(struct bt_conn *conn,
					void *context)
{
	LOG_INF("Service not found");
}

static void discovery_error(struct bt_conn *conn,
			    int err,
			    void *context)
{
	LOG_WRN("Error while discovering GATT database: (%d)", err);
}

struct bt_gatt_dm_cb discovery_cb = {
	.completed         = discovery_complete,
	.service_not_found = discovery_service_not_found,
	.error_found       = discovery_error,
};

static void gatt_discover(struct bt_conn *conn)
{
	int err;

	if (conn != default_conn) {
		return;
	}

	err = bt_gatt_dm_start(conn,
			       BT_UUID_NUS_SERVICE,
			       &discovery_cb,
			       &nus_client);
	if (err) {
		LOG_ERR("could not start the discovery procedure, error "
			"code: %d", err);
	}
}

#if !defined(BLE_NUS_THROUGHPUT_MAX)

static void exchange_func(struct bt_conn *conn, uint8_t err, struct bt_gatt_exchange_params *params)
{
	if (!err) {
		LOG_INF("MTU exchange done");
	} else {
		LOG_WRN("MTU exchange failed (err %" PRIu8 ")", err);
	}
}

#endif

static void connected(struct bt_conn *conn, uint8_t conn_err)
{
	char addr[BT_ADDR_LE_STR_LEN];
	int err;

	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));

	if (conn_err) {
		LOG_INF("Failed to connect to %s (%d)", addr, conn_err);

		if (default_conn == conn) {
			bt_conn_unref(default_conn);
			default_conn = NULL;

			err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
			if (err) {
				LOG_ERR("Scanning failed to start (err %d)",
					err);
			}
		}

		return;
	}

	LOG_INF("Connected: %s", addr);

#if !defined(BLE_NUS_THROUGHPUT_MAX)
	static struct bt_gatt_exchange_params exchange_params;

	exchange_params.func = exchange_func;
	err = bt_gatt_exchange_mtu(conn, &exchange_params);
	if (err) {
		LOG_WRN("MTU exchange failed (err %d)", err);
	}
#else 
	// we perfom bt gatt exchange mtu in connection_configuration_set()
#endif //#if defined(BLE_NUS_THROUGHPUT_MAX)

#if defined(BLE_NUS_DISABLE_BT_CONN_SECURITY)
        gatt_discover(conn);
#else
	err = bt_conn_set_security(conn, BT_SECURITY_L2);
	if (err) {
		LOG_WRN("Failed to set security: %d", err);

		              // If we fail setting security, we will attempt to continue.
              // gatt_discover() would normally be called in callback security_changed()
              // But since bt_conn_set_security failed, we need to do it here.

		gatt_discover(conn);
	}
#endif //defined(BLE_NUS_DISABLE_BT_CONN_SECURITY)

	err = bt_scan_stop();
	if ((!err) && (err != -EALREADY)) {
		LOG_ERR("Stop LE scan failed (err %d)", err);
	}
}

static void disconnected(struct bt_conn *conn, uint8_t reason)
{
	char addr[BT_ADDR_LE_STR_LEN];
	int err;

	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));

	LOG_INF("Disconnected: %s (reason %u)", addr, reason);

	if (default_conn != conn) {
		return;
	}

	bt_conn_unref(default_conn);
	default_conn = NULL;

	err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
	if (err) {
		LOG_ERR("Scanning failed to start (err %d)",
			err);
	}
}

static void security_changed(struct bt_conn *conn, bt_security_t level,
			     enum bt_security_err err)
{
	char addr[BT_ADDR_LE_STR_LEN];

	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));

	if (!err) {
		LOG_INF("Security changed: %s level %u", addr, level);
	} else {
		LOG_WRN("Security failed: %s level %u err %d", addr,
			level, err);
	}

	gatt_discover(conn);
}


#if defined(BLE_NUS_THROUGHPUT_MAX)
static bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param)
{		
	LOG_INF("Connection parameters update request received.");
	LOG_INF("Minimum interval: %d, Maximum interval: %d",
	       param->interval_min, param->interval_max);
	LOG_INF("Latency: %d, Timeout: %d", param->latency, param->timeout);

	return true;
}

static void le_param_updated(struct bt_conn *conn, uint16_t interval,
			     uint16_t latency, uint16_t timeout)
{
  LOG_INF("Connection parameters updated."
         " interval: %d, latency: %d, timeout: %d",
         interval, latency, timeout);

  k_sem_give(&nus_connection_sem);
}

static void le_phy_updated(struct bt_conn *conn,
			   struct bt_conn_le_phy_info *param)
{
  LOG_INF("LE PHY updated: TX PHY %s, RX PHY %s",
         phy2str(param->tx_phy), phy2str(param->rx_phy));
  k_sem_give(&nus_connection_sem);
}

static void le_data_length_updated(struct bt_conn *conn,
				   struct bt_conn_le_data_len_info *info)
{
  if (!data_length_req) {
          return;
  }

  LOG_INF("LE data len updated: TX (len: %d time: %d)"
         " RX (len: %d time: %d)", info->tx_max_len,
         info->tx_max_time, info->rx_max_len, info->rx_max_time);

  data_length_req = false;
        
  k_sem_give(&nus_connection_sem);
}

static void mtu_exchange_updated(struct bt_conn *conn, uint8_t err, struct bt_gatt_exchange_params *params)
{
  if (!err) {
    LOG_INF("MTU exchange done. MTU = %d", bt_gatt_get_mtu(conn));
  } else {
    LOG_WRN("MTU exchange failed (err %" PRIu8 ")", err);
  }
  
  // This semaphore is given so that main() task can proceed onwards.
  k_sem_give(&nus_connection_sem);
}

#endif //#if defined(BLE_NUS_THROUGHPUT_MAX)


BT_CONN_CB_DEFINE(conn_callbacks) = {
	.connected = connected,
	.disconnected = disconnected,

	#if defined(BLE_NUS_THROUGHPUT_MAX)
        .le_param_req = le_param_req,
        .le_param_updated = le_param_updated,
        .le_phy_updated = le_phy_updated,
        .le_data_len_updated = le_data_length_updated,
	#endif 

	.security_changed = security_changed
};

static void scan_filter_match(struct bt_scan_device_info *device_info,
			      struct bt_scan_filter_match *filter_match,
			      bool connectable)
{
	char addr[BT_ADDR_LE_STR_LEN];

	bt_addr_le_to_str(device_info->recv_info->addr, addr, sizeof(addr));

	LOG_INF("Filters matched. Address: %s connectable: %d",
		addr, connectable);
}

static void scan_connecting_error(struct bt_scan_device_info *device_info)
{
	LOG_WRN("Connecting failed");
}

static void scan_connecting(struct bt_scan_device_info *device_info,
			    struct bt_conn *conn)
{
	default_conn = bt_conn_ref(conn);
}

static int nus_client_init(void)
{
	int err;
	struct bt_nus_client_init_param init = {
		.cb = {
			.received = ble_data_received,
			.sent = ble_data_sent,
		}
	};

	err = bt_nus_client_init(&nus_client, &init);
	if (err) {
		LOG_ERR("NUS Client initialization failed (err %d)", err);
		return err;
	}

	LOG_INF("NUS Client module initialized");
	return err;
}

BT_SCAN_CB_INIT(scan_cb, scan_filter_match, NULL,
		scan_connecting_error, scan_connecting);

static int scan_init(void)
{
	int err;
	struct bt_scan_init_param scan_init = {
		.connect_if_match = 1,
	};

	bt_scan_init(&scan_init);
	bt_scan_cb_register(&scan_cb);

	err = bt_scan_filter_add(BT_SCAN_FILTER_TYPE_UUID, BT_UUID_NUS_SERVICE);
	if (err) {
		LOG_ERR("Scanning filters cannot be set (err %d)", err);
		return err;
	}

	err = bt_scan_filter_enable(BT_SCAN_UUID_FILTER, false);
	if (err) {
		LOG_ERR("Filters cannot be turned on (err %d)", err);
		return err;
	}

	LOG_INF("Scan module initialized");
	return err;
}


static void auth_cancel(struct bt_conn *conn)
{
	char addr[BT_ADDR_LE_STR_LEN];

	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));

	LOG_INF("Pairing cancelled: %s", addr);
}


static void pairing_complete(struct bt_conn *conn, bool bonded)
{
	char addr[BT_ADDR_LE_STR_LEN];

	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));

	LOG_INF("Pairing completed: %s, bonded: %d", addr, bonded);
}


static void pairing_failed(struct bt_conn *conn, enum bt_security_err reason)
{
	char addr[BT_ADDR_LE_STR_LEN];

	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));

	LOG_WRN("Pairing failed conn: %s, reason %d", addr, reason);
}


#if defined(BLE_NUS_THROUGHPUT_MAX)
static int print_connection_info(struct bt_conn_info *pInfo)
{
  // Display some of the connection settings ... more can be displayed ...
  LOG_INF("Data Length TX:%d", pInfo->le.data_len->tx_max_len);
  LOG_INF("Data Length RX:%d", pInfo->le.data_len->rx_max_len);
  LOG_INF("Phy TX:%d", pInfo->le.phy->tx_phy);
  LOG_INF("Phy RX:%d", pInfo->le.phy->rx_phy);

  return 0;
}

// Seems that MTU/DLE/Connection interval/... negotiations are not stored in bonding info.
// TODO: Is there some way to do that at compile time ?
// This would speed up connection process ... if that was important to us.
static int connection_configuration_set(
			const struct bt_le_conn_param *conn_param,
			const struct bt_conn_le_phy_param *phy,
			const struct bt_conn_le_data_len_param *data_len)
{
  int err;
  struct bt_conn_info info = {0};

  err = bt_conn_get_info(default_conn, &info);
  if (err) {
    LOG_INF("Failed to get connection info %d", err);
    return err;
  }

  print_connection_info(&info);

  // Define time for negotiation to occur ...
  #define LINK_UPDATE_TIMEOUT K_SECONDS(20)

  err = bt_conn_le_phy_update(default_conn, phy);
  if (err) {
          LOG_INF("PHY update failed: %d", err);
          return err;
  }

  LOG_INF("PHY update pending");
  // Wait for semaphore to be given upon phy update ...
  err = k_sem_take(&nus_connection_sem, LINK_UPDATE_TIMEOUT);
  if (err) {
    LOG_ERR("PHY update timeout !");
  }

  if (info.le.data_len->tx_max_len != data_len->tx_max_len) {
    data_length_req = true;

    err = bt_conn_le_data_len_update(default_conn, data_len);
    if (err) {
      LOG_INF("LE data length update failed: %d", err);
      return err;
    }

    LOG_INF("LE Data length update pending");
    // Wait for semaphore to be given upon data length update ...
    err = k_sem_take(&nus_connection_sem, LINK_UPDATE_TIMEOUT);
    if (err) {
      LOG_INF("LE Data Length update timeout");
      return err;
    }
  }

  if (info.le.interval != conn_param->interval_max) {
    err = bt_conn_le_param_update(default_conn, conn_param);
    if (err) {
      LOG_INF("Connection parameters update failed: %d", err);
      return err;
    }

    LOG_INF("Connection parameters update pending");
    // Wait for semaphore to be given upon connection parameters update ...
    err = k_sem_take(&nus_connection_sem, LINK_UPDATE_TIMEOUT);
    if (err) {
      LOG_INF("Connection parameters update timeout");
      return err;
    }
  }


  // So if we want a different MTU than default, we need to exchange with the peer.
  // Important understandings found in:
  //  https://devzone.nordicsemi.com/f/nordic-q-a/81860/set-mtu-size-in-zephyr/341062#341062
  //
  // In our proj.conf, we already have CONFIG_BT_L2CAP_TX_MTU=247, but that only
  //  seems to be referenced within functions of bt_gatt_exchange_mtu()
  // Setup callback to capture MTU exchange status with Peer.
  mtu_exchange_params.func = mtu_exchange_updated;
  err = bt_gatt_exchange_mtu(default_conn, &mtu_exchange_params);
  if (err) {
    LOG_INF("MTU exchange failed (err %d)", err);
    return err;
  } 
  
  LOG_INF("MTU exchange pending");
  // Wait for semaphore to be given upon mtu exchange update ...
  err = k_sem_take(&nus_connection_sem, LINK_UPDATE_TIMEOUT);
  if (err) {
    LOG_INF("MTU exchange update timeout");
    return err;
  }

  // If we are here then all the connection negotiations completed succesfully
  return 0;
}
#endif // #if defined(BLE_NUS_THROUGHPUT_MAX)


static struct bt_conn_auth_cb conn_auth_callbacks = {
	.cancel = auth_cancel,
};

static struct bt_conn_auth_info_cb conn_auth_info_callbacks = {
	.pairing_complete = pairing_complete,
	.pairing_failed = pairing_failed
};

int main(void)
{
	int err;

	err = bt_conn_auth_cb_register(&conn_auth_callbacks);
	if (err) {
		LOG_ERR("Failed to register authorization callbacks.");
		return 0;
	}

	err = bt_conn_auth_info_cb_register(&conn_auth_info_callbacks);
	if (err) {
		printk("Failed to register authorization info callbacks.\n");
		return 0;
	}

	err = bt_enable(NULL);
	if (err) {
		LOG_ERR("Bluetooth init failed (err %d)", err);
		return 0;
	}
	LOG_INF("Bluetooth initialized");

	if (IS_ENABLED(CONFIG_SETTINGS)) {
		settings_load();
	}

	err = uart_init();
	if (err != 0) {
		LOG_ERR("uart_init failed (err %d)", err);
		return 0;
	}

	err = scan_init();
	if (err != 0) {
		LOG_ERR("scan_init failed (err %d)", err);
		return 0;
	}

	err = nus_client_init();
	if (err != 0) {
		LOG_ERR("nus_client_init failed (err %d)", err);
		return 0;
	}

	printk("Starting Bluetooth Central UART example\n");

	err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
	if (err) {
		LOG_ERR("Scanning failed to start (err %d)", err);
		return 0;
	}

	LOG_INF("Scanning successfully started");

	struct uart_data_t nus_data = {
		.len = 0,
	};


#if defined(BLE_NUS_THROUGHPUT_MAX)
      LOG_INF("waiting to establish connection with peripheral_uart...");
      // Wait for semaphore to be given upon connection ...
      k_sem_take(&nus_connection_sem, K_FOREVER);
      // At this point, the BLE connection is established.
      // But we need to finish link negotiations before it is
      //  safe to proceed with communications to the peer Peripheral.

      err = connection_configuration_set(test_params.conn_param, test_params.phy, test_params.data_len);
      if (err) {
        LOG_WRN("Error in connection_configuration_set()");
      }
      else {
        LOG_INF("Peripheral connected and discovery is complete.");
      }
#endif //#if defined(BLE_NUS_THROUGHPUT_MAX)


	for (;;) {
		/* Wait indefinitely for data to be sent over Bluetooth */
		struct uart_data_t *buf = k_fifo_get(&fifo_uart_rx_data,
						     K_FOREVER);

		int plen = MIN(sizeof(nus_data.data) - nus_data.len, buf->len);
		int loc = 0;

		while (plen > 0) {
			memcpy(&nus_data.data[nus_data.len], &buf->data[loc], plen);
			nus_data.len += plen;
			loc += plen;
			if (nus_data.len >= sizeof(nus_data.data) ||
			   (nus_data.data[nus_data.len - 1] == '\n') ||
			   (nus_data.data[nus_data.len - 1] == '\r')) {
				err = bt_nus_client_send(&nus_client, nus_data.data, nus_data.len);
				if (err) {
					LOG_WRN("Failed to send data over BLE connection"
						"(err %d)", err);
				}

				err = k_sem_take(&nus_write_sem, NUS_WRITE_TIMEOUT);
				if (err) {
					LOG_WRN("NUS send timeout");
				}

				nus_data.len = 0;
			}

			plen = MIN(sizeof(nus_data.data), buf->len - loc);
	}

		k_free(buf);
	}
}
