/*******************************************************************************
 * @file	app_raw.c
 * @author	CandyPops Co.
 * @version	V1.0.0
 * @date	2022-09-05
 * @brief
 ******************************************************************************/

/*******************************************************************************
 * [Module overview] ICM42670P IMU driver application layer
 *
 * Application layer module responsible for initialization, configuration,
 * and data reading of the ICM42670P IMU sensor. Wraps InvenSense driver API.
 *
 * Key functions:
 *   1) setup_imu_device()     - IMU init and WHOAMI verification (0x67 = ICM42670P)
 *   2) configure_imu_device() - Sensor parameter configuration
 *      - Accelerometer: +/-4g FSR, 100Hz (low-power) or 800Hz (low-noise)
 *      - Gyroscope:     +/-2000dps FSR, 100Hz or 800Hz
 *      - FIFO disabled (direct register read mode)
 *   3) get_imu_data()         - Read sensor data from FIFO or registers
 *   4) imu_callback()         - Sensor data receive callback
 *      - Applies mounting matrix (board orientation correction)
 *      - info4 mode: stores data in info_imu[6]
 *      - BLE mode:   sends 6-axis data via BLE with "rsp:" tag
 *      - UART mode:  outputs text format to serial
 *   5) imu_read_direct()      - Direct I2C register read bypassing driver API
 *      - Configure sensor -> power ON -> wait 80ms -> read 12 bytes -> sleep
 *
 * Mounting matrix:
 *   3x3 rotation matrix in Q30 fixed-point format, correcting the sensor's
 *   physical mounting orientation to match the software coordinate system.
 ******************************************************************************/

#include "sdk_config.h"
#include "app_raw.h"
#include "inv_imu_extfunc.h"
#include "inv_imu_driver.h"
#include "ble_nus.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"

#include "app_util_platform.h"
#include "main.h"
#include "debug_print.h"
#include "nrf_delay.h"


/*
 * Data output format selection
 * 0 : Raw data output (raw accel, gyro, temp)
 * 1 : Scaled data output (g, dps, Celsius)
 */
#define SCALED_DATA_G_DPS 0


/* --------------------------------------------------------------------------------------
 *  Static and extern variables
 * -------------------------------------------------------------------------------------- */

/* IMU driver object — always passed to driver API calls */
static struct inv_imu_device icm_driver;

/* Binary buffer for BLE transmission */
 uint8_t imu_bin_buffer[BLE_NUS_MAX_DATA_LEN] = {0};

/*
 * ICM42670P mounting matrix (Q30 fixed-point)
 *
 * Coordinate transform based on the sensor's physical mounting orientation.
 * Q30 format: 1.0 = (1 << 30) = 0x40000000
 *
 * SM_REVB_DB (dev board): X->-Y, Y->X transform (90-degree rotation)
 * Default (SmartMotion): identity matrix (no transform)
 */
#if (SM_BOARD_REV == SM_REVB_DB) /* when DB or EVB are used */
static int32_t icm_mounting_matrix[9] = {  0,     -(1<<30), 0,
                                          (1<<30), 0,       0,
                                           0,      0,      (1<<30) };
#else /* For SmartMotion */
static int32_t icm_mounting_matrix[9] = {(1<<30),  0,       0,
                                          0,      (1<<30),  0,
                                          0,       0,      (1<<30)};
#endif

bool custom_add_data;                              		/* Custom data append flag (BLE transmission control) */
extern bool motion_raw_data_enabled;               		/* Flag requesting raw data read from external module */
extern char		ble_tx_buffer[BLE_NUS_MAX_DATA_LEN]; 	/* BLE text transmit buffer */
extern which_cmd_t cmd_type_t;                     		/* Current command source (BLE or UART) */
uint16_t ssp_data[6]={0,};                         		/* 6-axis data array for BLE (accel XYZ + gyro XYZ) */
extern bool info4;                                 		/* info4 mode flag (set by cmd_parse) */
 volatile uint16_t info_imu[6];                    		/* Global array storing IMU data in info4 mode */

/* --------------------------------------------------------------------------------------
 *  static function declaration
 * -------------------------------------------------------------------------------------- */
static void apply_mounting_matrix(const int32_t matrix[9], int32_t raw[3]);

/* --------------------------------------------------------------------------------------
 *  Functions definition
 * -------------------------------------------------------------------------------------- */

/*
 * setup_imu_device()
 * IMU device initialization and identification verification.
 *
 * Flow:
 *   1) Initialize driver via inv_imu_init() (serial interface + callback registration)
 *   2) Read WHOAMI register for device identification
 *   3) Verify WHOAMI value matches ICM_WHOAMI (0x67)
 *
 * Returns: 0=success, negative=error
 */
int setup_imu_device(struct inv_imu_serif *icm_serif)
{
	int rc = 0;
	uint8_t who_am_i;

	/* Initialize IMU driver — connect serial interface and register callback */
	rc = inv_imu_init(&icm_driver, icm_serif, imu_callback);
	if (rc != INV_ERROR_SUCCESS) {
		DBG_PRINTF("!!! ERROR : Failed to initialize IMU!\r\n");
		return rc;
	}

	/* Read WHOAMI register — verify device presence and communication */
	rc = inv_imu_get_who_am_i(&icm_driver, &who_am_i);
	if (rc != INV_ERROR_SUCCESS) {
		DBG_PRINTF("!!! ERROR : Failed to read whoami!\r\n");
		return rc;
	}

	/* Verify WHOAMI value — must be 0x67 for ICM42670P */
	if (who_am_i != ICM_WHOAMI) {
		DBG_PRINTF("!!! ERROR : Bad WHOAMI value! Read 0x%02x, expected 0x%02x\r\n", who_am_i, ICM_WHOAMI);
		return INV_ERROR;
	}

	return rc;
}

/*
 * configure_imu_device()
 * Configures IMU sensor operating parameters.
 *
 * Settings:
 *   - FIFO: disabled (when USE_FIFO=0, direct register read mode)
 *   - Accel FSR: +/-4g (when USE_HIGH_RES_MODE=0)
 *   - Gyro FSR: +/-2000dps
 *   - ODR (output data rate):
 *     - Low-noise mode (USE_LOW_NOISE_MODE=1): 800Hz
 *     - Low-power mode (USE_LOW_NOISE_MODE=0): 100Hz
 *   - Gyro always operates in low-noise mode
 *   - Waits for gyro startup time when FIFO is not used
 *
 * Returns: 0=success, negative=error
 */
int configure_imu_device(void)
{
	int rc = 0;

	/* Disable FIFO — read data directly from registers */
	if (!USE_FIFO)
		rc |= inv_imu_configure_fifo(&icm_driver, INV_IMU_FIFO_DISABLED);

	if (USE_HIGH_RES_MODE) {
		/* High-resolution FIFO mode: 20-bit data, FSR locked to 16g/2000dps */
		rc |= inv_imu_enable_high_resolution_fifo(&icm_driver);
	} else {
		/* Standard mode: accel +/-4g, gyro +/-2000dps FSR */
		rc |= inv_imu_set_accel_fsr(&icm_driver, ACCEL_CONFIG0_FS_SEL_4g);
		rc |= inv_imu_set_gyro_fsr(&icm_driver, GYRO_CONFIG0_FS_SEL_2000dps);
	}

	if (USE_LOW_NOISE_MODE) {
		/* Low-noise mode: 800Hz ODR, enable accel low-noise mode */
		rc |= inv_imu_set_accel_frequency(&icm_driver, ACCEL_CONFIG0_ODR_800_HZ);
		rc |= inv_imu_set_gyro_frequency(&icm_driver, GYRO_CONFIG0_ODR_800_HZ);
		rc |= inv_imu_enable_accel_low_noise_mode(&icm_driver);
	} else {
		/* Low-power mode: 100Hz ODR, enable accel low-power mode */
		rc |= inv_imu_set_accel_frequency(&icm_driver, ACCEL_CONFIG0_ODR_100_HZ);
		rc |= inv_imu_set_gyro_frequency(&icm_driver, GYRO_CONFIG0_ODR_100_HZ);
		rc |= inv_imu_enable_accel_low_power_mode(&icm_driver);
	}

	/* Gyro always operates in low-noise mode regardless of setting */
	rc |= inv_imu_enable_gyro_low_noise_mode(&icm_driver);

	/* When FIFO is not used, wait for gyro startup time (delay until first valid data) */
	if (!USE_FIFO)
		inv_imu_sleep_us(GYR_STARTUP_TIME_US);

	return rc;
}


/*
 * get_imu_data()
 * Reads sensor data from the IMU.
 * Fetches data from FIFO or registers depending on USE_FIFO setting.
 * Read data is processed via imu_callback().
 */
int get_imu_data(void)
{
#if USE_FIFO
	return inv_imu_get_data_from_fifo(&icm_driver);
#else

	return inv_imu_get_data_from_registers(&icm_driver);
#endif
}

#if SCALED_DATA_G_DPS
/*
 * get_accel_and_gyr_fsr()
 * Retrieves the currently configured FSR (Full Scale Range) for accel and gyro.
 * Used for converting to scaled data (g, dps).
 */
static void get_accel_and_gyr_fsr(int16_t * accel_fsr_g, int16_t * gyro_fsr_dps)
{
	ACCEL_CONFIG0_FS_SEL_t accel_fsr_bitfield;
	GYRO_CONFIG0_FS_SEL_t gyro_fsr_bitfield;

	inv_imu_get_accel_fsr(&icm_driver, &accel_fsr_bitfield);
	switch(accel_fsr_bitfield) {
	case ACCEL_CONFIG0_FS_SEL_2g:   *accel_fsr_g = 2;
	break;
	case ACCEL_CONFIG0_FS_SEL_4g:   *accel_fsr_g = 4;
	break;
	case ACCEL_CONFIG0_FS_SEL_8g:   *accel_fsr_g = 8;
	break;
	case ACCEL_CONFIG0_FS_SEL_16g:  *accel_fsr_g = 16;
	break;
	default:                        *accel_fsr_g = -1;
	}

	inv_imu_get_gyro_fsr(&icm_driver, &gyro_fsr_bitfield);
	switch(gyro_fsr_bitfield) {
	case GYRO_CONFIG0_FS_SEL_250dps:  *gyro_fsr_dps = 250;
	break;
	case GYRO_CONFIG0_FS_SEL_500dps:  *gyro_fsr_dps = 500;
	break;
	case GYRO_CONFIG0_FS_SEL_1000dps: *gyro_fsr_dps = 1000;
	break;
	case GYRO_CONFIG0_FS_SEL_2000dps: *gyro_fsr_dps = 2000;
	break;
	default:                          *gyro_fsr_dps = -1;
	}
}
#endif


/*
 * imu_callback()
 * Callback invoked each time the IMU driver reads new sensor data.
 *
 * Flow:
 *   1) Extract raw accel/gyro data from event
 *      - FIFO mode: handles timestamp rollover, supports high-res (20-bit)
 *      - Register mode: uses 16-bit data directly
 *   2) Apply mounting matrix (board orientation correction)
 *   3) Output data (branches by mode):
 *      - info4 mode: stores in info_imu[6] global array (polled externally)
 *      - UART mode: text output with "Tp" prefix for 6-axis data
 *      - BLE mode:  binary packet with "rsp:" tag + simultaneous UART output
 */
void imu_callback(inv_imu_sensor_event_t *event)
{
	int32_t accel[3], gyro[3];

#if SCALED_DATA_G_DPS
	float accel_g[3];
	float gyro_dps[3];
	float temp_degc;
	int16_t accel_fsr_g, gyro_fsr_dps;
#endif

#if USE_FIFO
	static uint64_t last_fifo_timestamp = 0;
	static uint32_t rollover_num = 0;

	/* FIFO timestamp rollover handling (16-bit -> 64-bit extension) */
	if (last_fifo_timestamp > event->timestamp_fsync)
		rollover_num++;
	last_fifo_timestamp = event->timestamp_fsync;

	/* Convert timestamp to microseconds (apply Q24 resolution) */
	timestamp = event->timestamp_fsync + rollover_num * UINT16_MAX;
	timestamp *= inv_imu_get_fifo_timestamp_resolution_us_q24(&icm_driver);
	timestamp /= (1UL << 24);

	if (icm_driver.fifo_highres_enabled) {
		/* High-res mode: left-shift 16-bit data by 4 + add lower 4 bits -> 20-bit */
		accel[0] = (((int32_t)event->accel[0] << 4)) | event->accel_high_res[0];
		accel[1] = (((int32_t)event->accel[1] << 4)) | event->accel_high_res[1];
		accel[2] = (((int32_t)event->accel[2] << 4)) | event->accel_high_res[2];

		gyro[0] = (((int32_t)event->gyro[0] << 4)) | event->gyro_high_res[0];
		gyro[1] = (((int32_t)event->gyro[1] << 4)) | event->gyro_high_res[1];
		gyro[2] = (((int32_t)event->gyro[2] << 4)) | event->gyro_high_res[2];

	} else {
		/* Standard resolution: use 16-bit data as-is */
		accel[0] = event->accel[0];
		accel[1] = event->accel[1];
		accel[2] = event->accel[2];

		gyro[0] = event->gyro[0];
		gyro[1] = event->gyro[1];
		gyro[2] = event->gyro[2];
	}
#else

	/* Direct register read mode: extract 16-bit raw data */
	accel[0] = event->accel[0];
	accel[1] = event->accel[1];
	accel[2] = event->accel[2];

	gyro[0] = event->gyro[0];
	gyro[1] = event->gyro[1];
	gyro[2] = event->gyro[2];

	/* In register mode, force sensor mask so the output logic below works */
	event->sensor_mask |= (1 << INV_SENSOR_TEMPERATURE);
	event->sensor_mask |= (1 << INV_SENSOR_ACCEL);
	event->sensor_mask |= (1 << INV_SENSOR_GYRO);
#endif

	/* Apply mounting matrix — correct sensor physical orientation to software coordinates */
	apply_mounting_matrix(icm_mounting_matrix, accel);
	apply_mounting_matrix(icm_mounting_matrix, gyro);

#if SCALED_DATA_G_DPS
	/*
	 * Convert raw data to physical units (g, dps)
	 * Formula: physical_value = raw_value * FSR / INT16_MAX
	*/
	get_accel_and_gyr_fsr(&accel_fsr_g, &gyro_fsr_dps);
	accel_g[0]  = (float)(accel[0] * accel_fsr_g)  / INT16_MAX;
	accel_g[1]  = (float)(accel[1] * accel_fsr_g)  / INT16_MAX;
	accel_g[2]  = (float)(accel[2] * accel_fsr_g)  / INT16_MAX;
	gyro_dps[0] = (float)(gyro[0]  * gyro_fsr_dps) / INT16_MAX;
	gyro_dps[1] = (float)(gyro[1]  * gyro_fsr_dps) / INT16_MAX;
	gyro_dps[2] = (float)(gyro[2]  * gyro_fsr_dps) / INT16_MAX;

	/* Temperature conversion: high-res/register mode uses /128, FIFO standard mode uses /2 */
	if (USE_HIGH_RES_MODE || !USE_FIFO)
		temp_degc = 25 + ((float)event->temperature / 128);
	else
		temp_degc = 25 + ((float)event->temperature / 2);

	/*
	 * Output scaled data via UART
	 */
	if (event->sensor_mask & (1 << INV_SENSOR_ACCEL) && event->sensor_mask & (1 << INV_SENSOR_GYRO))
		DBG_PRINTF("%u: %.3f, \t%.3f, \t%.3f, \t%.3f, \t%.3f, \t%.3f, \t%.3f\r\n",
		        (uint32_t)timestamp,
		        accel_g[0], accel_g[1], accel_g[2],
		        temp_degc,
		        gyro_dps[0], gyro_dps[1], gyro_dps[2]);
#else

	/*
	 * Raw data output — branches by command source (info4/UART/BLE)
	 */
	if (event->sensor_mask & (1 << INV_SENSOR_ACCEL) && event->sensor_mask & (1 << INV_SENSOR_GYRO) || motion_raw_data_enabled)
	{
		motion_raw_data_enabled = false;

		/* info4 mode: store data in global array info_imu[6], polled by external modules */
		if (info4 == true)
		{
			info_imu[0] = (uint16_t)accel[0];
			info_imu[1] = (uint16_t)accel[1];
			info_imu[2] = (uint16_t)accel[2];
			info_imu[3] = (uint16_t)gyro[0];
			info_imu[4] = (uint16_t)gyro[1];
			info_imu[5] = (uint16_t)gyro[2];
		}

		/* UART mode: output 6-axis data in text format with "Tp" prefix */
		else if(cmd_type_t == CMD_UART) {
			//DBG_PRINTF("Tp%d,%d,%d,%d,%d,%d\r\n\r\n", accel[0], accel[1], accel[2], gyro[0], gyro[1], gyro[2]);
		}

		/*
			* BLE mode: send 6-axis data as binary packet via BLE
			* ssp_data[0..2] = accel XYZ, ssp_data[3..5] = gyro XYZ
			* format_data() packs "rsp:" tag + 12-byte data
			* dr_binary_tx_safe() sends 8 bytes via BLE
		*/
		else if(cmd_type_t == CMD_BLE) {
			ssp_data[0] = (uint16_t)accel[0];
			ssp_data[1] = (uint16_t)accel[1];
			ssp_data[2] = (uint16_t)accel[2];
			ssp_data[3] = (uint16_t)gyro[0];
			ssp_data[4] = (uint16_t)gyro[1];
			ssp_data[5] = (uint16_t)gyro[2];

			format_data(imu_bin_buffer, "rsp:", ssp_data,12);
			//DBG_PRINTF("Tp%d,%d,%d,%d,%d,%d\r\n\r\n", accel[0], accel[1], accel[2], gyro[0], gyro[1], gyro[2]);
			dr_binary_tx_safe(imu_bin_buffer,8);

			if(custom_add_data==true) {
				custom_add_data = false;
			}
			else {
				//data_tx_handler(ble_tx_buffer);
			}
		}
	}
#endif
}

/* --------------------------------------------------------------------------------------
 *  Static functions definition
 * -------------------------------------------------------------------------------------- */

/*
 * apply_mounting_matrix()
 * Applies a Q30 fixed-point rotation matrix to a 3-axis vector.
 *
 * Calculation:
 *   result[i] = matrix[i*3+0]*raw[0] + matrix[i*3+1]*raw[1] + matrix[i*3+2]*raw[2]
 *   Right-shift result by 30 bits for Q30 -> integer conversion.
 *
 * Ensures a consistent coordinate system regardless of physical sensor orientation.
 */
static void apply_mounting_matrix(const int32_t matrix[9], int32_t raw[3])
{
	unsigned i;
	int64_t data_q30[3];

	for(i = 0; i < 3; i++) {
		data_q30[i] =  ((int64_t)matrix[3*i+0] * raw[0]);
		data_q30[i] += ((int64_t)matrix[3*i+1] * raw[1]);
		data_q30[i] += ((int64_t)matrix[3*i+2] * raw[2]);
	}
	/* Q30 -> integer conversion: right-shift by 30 bits */
	raw[0] = (int32_t)(data_q30[0]>>30);
	raw[1] = (int32_t)(data_q30[1]>>30);
	raw[2] = (int32_t)(data_q30[2]>>30);
}


/*
 * imu_read_direct()
 * Reads IMU registers directly via I2C, bypassing the driver API.
 * Reads data immediately without waiting for DRDY interrupt.
 *
 * Flow:
 *   1) Check TWI initialization (first call only)
 *   2) Gyro config: +/-2000dps, 100Hz ODR (GYRO_CONFIG0 = 0x09)
 *   3) Accel config: +/-4g, 100Hz ODR (ACCEL_CONFIG0 = 0x29)
 *   4) Power ON: accel+gyro low-noise mode (PWR_MGMT0 = 0x0F)
 *   5) Wait 80ms (gyro startup: min 45ms + margin)
 *   6) Read 12 consecutive bytes from ACCEL_DATA_X1 (0x0B) (accel 6 + gyro 6)
 *   7) Big-endian -> int16_t conversion
 *   8) Apply mounting matrix
 *   9) Send via BLE with "rsp:" tag
 *  10) Switch IMU to sleep mode (power saving)
 *
 * Returns: 0=success, -1=TX failure, -2=RX failure
 */
/* Raw I2C read from ICM42670P — bypasses driver API entirely */
#include "system_interface.h"
#include "nrfx_twi.h"

extern const nrfx_twi_t m_twi_icm42670;

#define IMU_I2C_ADDR   0x68
#define REG_ACCEL_X1   0x0B  /* ACCEL_DATA_X1 — accel X-axis upper byte register */

/* --------------------------------------------------------------------------------------
 * Direct IMU register read — raw I2C, no DRDY, sends rsp: via BLE
 * Direct I2C register read (no interrupt, no IMU driver API)
 * -------------------------------------------------------------------------------------- */
int imu_read_direct(void)
{
	uint8_t raw[12];  /* accel 6 bytes + gyro 6 bytes */
	int32_t accel[3], gyro[3];
	uint8_t reg;
	uint32_t ret;

	static bool twi_ready = false;

	/* TWI (I2C) init — performed only once (re-init ensures clean state) */
	if (!twi_ready) {
		inv_i2c_master_uninitialize();
		inv_i2c_master_initialize();
		twi_ready = true;
	}

	/* Gyro config: GYRO_CONFIG0(0x20) = 0x09 -> +/-2000dps FSR, 100Hz ODR */
	{
		uint8_t gyro_cfg[2] = { 0x20, 0x09 };
		icm42670_twi_tx(IMU_I2C_ADDR, gyro_cfg, 2, false);
	}

	/* Accel config: ACCEL_CONFIG0(0x21) = 0x29 -> +/-4g FSR, 100Hz ODR */
	{
		uint8_t accel_cfg[2] = { 0x21, 0x29 };
		icm42670_twi_tx(IMU_I2C_ADDR, accel_cfg, 2, false);
	}

	/* Power ON: PWR_MGMT0(0x1F) = 0x0F -> accel (low-noise) + gyro (low-noise) enabled */
	{
		uint8_t pwr_cmd[2] = { 0x1F, 0x0F };  /* reg=0x1F, val=0x0F */
		icm42670_twi_tx(IMU_I2C_ADDR, pwr_cmd, 2, false);
		//nrf_delay_ms(80);  /* Gyro startup: min 45ms + safety margin */
		dr_sd_delay_ms(80);
	}

	/* Read 12 consecutive bytes from ACCEL_DATA_X1 (0x0B~0x16) */
	reg = REG_ACCEL_X1;
	ret = icm42670_twi_tx(IMU_I2C_ADDR, &reg, 1, true);  /* Send register address (no STOP) */
	
	if (ret)
	{
		DBG_PRINTF("[IMU] tx FAIL %u\r\n", ret);
		return -1;
	}

	ret = icm42670_twi_rx(IMU_I2C_ADDR, raw, 12);  /* Receive 12 bytes of data */

	if (ret)
	{
		DBG_PRINTF("[IMU] rx FAIL %u\r\n", ret);
		return -2;
	}

	/*
	 * Convert big-endian register layout to int16_t
	 * raw[0..5] = accel X,Y,Z (2 bytes each, MSB first)
	 * raw[6..11] = gyro X,Y,Z (2 bytes each, MSB first)
	 */
	accel[0] = (int16_t)((raw[0] << 8) | raw[1]);
	accel[1] = (int16_t)((raw[2] << 8) | raw[3]);
	accel[2] = (int16_t)((raw[4] << 8) | raw[5]);
	gyro[0]  = (int16_t)((raw[6] << 8) | raw[7]);
	gyro[1]  = (int16_t)((raw[8] << 8) | raw[9]);
	gyro[2]  = (int16_t)((raw[10] << 8) | raw[11]);

	/* Apply mounting matrix — board orientation correction */
	apply_mounting_matrix(icm_mounting_matrix, accel);
	apply_mounting_matrix(icm_mounting_matrix, gyro);

	/* Pack data */
	ssp_data[0] = (uint16_t)accel[0];
	ssp_data[1] = (uint16_t)accel[1];
	ssp_data[2] = (uint16_t)accel[2];
	ssp_data[3] = (uint16_t)gyro[0];
	ssp_data[4] = (uint16_t)gyro[1];
	ssp_data[5] = (uint16_t)gyro[2];

	if (info4 == true)
	{
		/* info4 mode: store in global array (sent as rbb: packet by mbb?) */
		info_imu[0] = ssp_data[0];
		info_imu[1] = ssp_data[1];
		info_imu[2] = ssp_data[2];
		info_imu[3] = ssp_data[3];
		info_imu[4] = ssp_data[4];
		info_imu[5] = ssp_data[5];
	}
	else
	{
		/* Normal mode: send immediately via BLE with "rsp:" tag */
		format_data(imu_bin_buffer, "rsp:", ssp_data, 12);
		dr_binary_tx_safe(imu_bin_buffer, 8);
	}

	/* IMU sleep mode: PWR_MGMT0 = 0x00 -> accel/gyro both OFF (power saving) */
	{
		uint8_t pwr_off[2] = { 0x1F, 0x00 };  /* reg=PWR_MGMT0, val=0x00 */
		icm42670_twi_tx(IMU_I2C_ADDR, pwr_off, 2, false);
	}

	return 0;
}
