/*
 * accel.c
 *
 *  Created on: Oct 13, 2024
 *      Author: true
 */

#include "accel.h"

#include "hw/lis2dw12_reg.h"
#include "comm/i2c.h"



// user data
AccelData accel;
AccelData accel_last[4];
AccelData accel_smoothing;

int16_t movement;


// hardware
static stmdev_ctx_t dev_ctx;



int32_t accel_i2c_write(void *handle, uint8_t reg, const uint8_t *bufp, uint16_t len)
{
    (void)(handle);

    i2c_write_reg8(LIS2DW_I2C_ADDR, reg, bufp, len);

    return 0;
}

int32_t accel_i2c_read(void *handle, uint8_t reg, uint8_t *bufp, uint16_t len)
{
    (void)(handle);

    i2c_read_reg8(LIS2DW_I2C_ADDR, reg, bufp, len);

    return 0;
}


void accel_init()
{
    uint8_t devid;
    uint8_t reset;

    dev_ctx.write_reg = accel_i2c_write;
    dev_ctx.read_reg = accel_i2c_read;

    // make sure we've got the right device
    lis2dw12_device_id_get(&dev_ctx, &devid);
    if (devid != LIS2DW12_ID) {
        while (1) {
            // might as well crash the user's badge
        }
    }

    // reset accelerometer
    lis2dw12_reset_set(&dev_ctx, PROPERTY_ENABLE);
    do {
        lis2dw12_reset_get(&dev_ctx, &reset);
    } while (reset);

    // configure scale, power mode
    lis2dw12_full_scale_set(&dev_ctx, LIS2DW12_2g);
    lis2dw12_power_mode_set(&dev_ctx, LIS2DW12_SINGLE_LOW_PWR_LOW_NOISE_4);

    // configure output data rate
    lis2dw12_data_rate_set(&dev_ctx, LIS2DW12_XL_ODR_100Hz);
}

int8_t accel_get_rotation()
{
    return 0;
}

int16_t accel_get_movement()
{
    return movement;
}
