// /*/* main.c - Application main entry point */

// /*
//  * Copyright (c) 2019 Aaron Tsui <aaron.tsui@outlook.com>
//  *
//  * SPDX-License-Identifier: Apache-2.0
//  */

// #include <zephyr/types.h>
// #include <stddef.h>
// #include <string.h>
// #include <errno.h>
// #include <zephyr/sys/printk.h>
// #include <zephyr/sys/byteorder.h>
// #include <zephyr/kernel.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 <zephyr/bluetooth/services/bas.h>

// #include "hts.h"
// // iv_added-8th-oct-25-start
// #include "sensirion_common.h"
// #include "sensirion_i2c_hal.h"
// #include "sts4x_i2c.h"
// // iv_added-8th-oct-25-end

// static const struct bt_data ad[] = {
// 	BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
// 	BT_DATA_BYTES(BT_DATA_UUID16_ALL,
// 		      BT_UUID_16_ENCODE(BT_UUID_HTS_VAL),
// 		      BT_UUID_16_ENCODE(BT_UUID_DIS_VAL),
// 		      BT_UUID_16_ENCODE(BT_UUID_BAS_VAL)),
// };

// static const struct bt_data sd[] = {
// 	BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, sizeof(CONFIG_BT_DEVICE_NAME) - 1),
// };

// static void connected(struct bt_conn *conn, uint8_t err)
// {
// 	if (err) {
// 		printk("Connection failed, err 0x%02x %s\n", err, bt_hci_err_to_str(err));
// 	} else {
// 		printk("Connected\n");
// 	}
// }

// static void disconnected(struct bt_conn *conn, uint8_t reason)
// {
// 	printk("Disconnected, reason 0x%02x %s\n", reason, bt_hci_err_to_str(reason));
// }

// BT_CONN_CB_DEFINE(conn_callbacks) = {
// 	.connected = connected,
// 	.disconnected = disconnected,
// };

// static void bt_ready(void)
// {
// 	int err;

// 	printk("Bluetooth initialized\n");

// 	hts_init();

// 	err = bt_le_adv_start(BT_LE_ADV_CONN_ONE_TIME, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));
// 	if (err) {
// 		printk("Advertising failed to start (err %d)\n", err);
// 		return;
// 	}

// 	printk("Advertising successfully started\n");
// }

// 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));

// 	printk("Pairing cancelled: %s\n", addr);
// }

// static struct bt_conn_auth_cb auth_cb_display = {
// 	.cancel = auth_cancel,
// };

// static void bas_notify(void)
// {
// 	uint8_t battery_level = bt_bas_get_battery_level();

// 	battery_level--;

// 	if (!battery_level) {
// 		battery_level = 100U;
// 	}

// 	bt_bas_set_battery_level(battery_level);
// }

// int main(void)
// {
// 	int err;
// 	int16_t error = 0;


// 	err = bt_enable(NULL);
// 	if (err) {
// 		printk("Bluetooth init failed (err %d)\n", err);
// 		return 0;
// 	}

// 	bt_ready();

// 	// iv_added-8th-oct-25-start
// 	// Select the correct I2C address for your sensor
//     // STS40-CD1B: 0x46
//     // STS40-AD1B: 0x44
//     // STS40-BD1B: 0x45
//     init_driver(ADDR_STS4X); // Use the correct macro for your sensor

//     uint32_t serial_number;
//     error = sts4x_serial_number(&serial_number);
//     if (error) {
//         printf("Error executing sts4x_serial_number(): %i\n", error);
//     } else {
//         printf("Serial number: %u\n", serial_number);
//     }

//     for (;;) {
//         int32_t temperature;
//         error = sts4x_measure_high_precision(&temperature);
//         if (error) {
//             printf("Error executing sts4x_measure_high_precision(): %i\n", error);
//         } else {
//             printf("Temperature: %.1f °C\n", temperature / 1000.0f);
//         }
//         sensirion_i2c_hal_sleep_usec(1000000);
//     }
// 	// iv_added-8th-oct-25-end


// 	bt_conn_auth_cb_register(&auth_cb_display);

// 	/* Implement indicate. At the moment there is no suitable way
// 	 * of starting delayed work so we do it here
// 	 */
// 	while (1) {
// 		k_sleep(K_SECONDS(1));

// 		/* Temperature measurements simulation */
// 		hts_indicate();

// 		/* Battery level simulation */
// 		bas_notify();
// 	}
// 	return 0;
// }

/* main.c - Application main entry point */

#include <zephyr/types.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <zephyr/sys/printk.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/kernel.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 <zephyr/bluetooth/services/bas.h>
#include <zephyr/drivers/i2c.h>


#include "hts.h"
// iv_added-8th-oct-25-start
#include "sensirion_common.h"
#include "sensirion_i2c_hal.h"
#include "sts4x_i2c.h"
// iv_added-8th-oct-25-end

#define I2C_NODE DT_NODELABEL(sts4x)


static const struct bt_data ad[] = {
    BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
    BT_DATA_BYTES(BT_DATA_UUID16_ALL,
              BT_UUID_16_ENCODE(BT_UUID_HTS_VAL),
              BT_UUID_16_ENCODE(BT_UUID_DIS_VAL),
              BT_UUID_16_ENCODE(BT_UUID_BAS_VAL)),
};

static const struct bt_data sd[] = {
    BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, sizeof(CONFIG_BT_DEVICE_NAME) - 1),
};

static void connected(struct bt_conn *conn, uint8_t err)
{
    if (err) {
        printk("Connection failed, err 0x%02x %s\n", err, bt_hci_err_to_str(err));
    } else {
        printk("Connected\n");
    }
}

static void disconnected(struct bt_conn *conn, uint8_t reason)
{
    printk("Disconnected, reason 0x%02x %s\n", reason, bt_hci_err_to_str(reason));
}

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

static void bt_ready(void)
{
    int err;

    printk("Bluetooth initialized\n");

    hts_init();

    err = bt_le_adv_start(BT_LE_ADV_CONN_ONE_TIME, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));
    if (err) {
        printk("Advertising failed to start (err %d)\n", err);
        return;
    }

    printk("Advertising successfully started\n");
}

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));

    printk("Pairing cancelled: %s\n", addr);
}

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

static void bas_notify(void)
{
    uint8_t battery_level = bt_bas_get_battery_level();

    battery_level--;

    if (!battery_level) {
        battery_level = 100U;
    }

    bt_bas_set_battery_level(battery_level);
}

int main(void)
{
    int err;
    int16_t error = 0;

    printk("Starting application...\n");

    // Initialize Bluetooth first
    err = bt_enable(NULL);
    if (err) {
        printk("Bluetooth init failed (err %d)\n", err);
        return 0;
    }

    bt_ready();
    bt_conn_auth_cb_register(&auth_cb_display);
	

    // Initialize STS4X sensor
    printk("Initializing STS4X sensor...\n");
    init_driver(ADDR_STS4X); // Use 0x46 for STS40-CD1B

    uint32_t serial_number;
    error = sts4x_serial_number(&serial_number);
    if (error) {
        printk("Error executing sts4x_serial_number(): %i\n", error);
    } else {
        printk("Serial number: %u\n", serial_number);
    }

    /* Add after init_driver in main */
    const struct device *i2c_dev_dbg = DEVICE_DT_GET(DT_NODELABEL(i2c0));
    if (!device_is_ready(i2c_dev_dbg)) {
        printk("i2c0 not ready\n");
    } else {
        printk("i2c0 ready, probing 0x46...\n");
        uint8_t dummy;
        int ret = i2c_read(i2c_dev_dbg, &dummy, 1, 0x46);
        printk("probe 0x46 result: %d\n", ret);
    }
	/* in main after init_driver */
	// const struct device *i2c_dev_dbg = DEVICE_DT_GET(DT_NODELABEL(i2c0));
	// if (!device_is_ready(i2c_dev_dbg)) {
	// 	printk("i2c0 not ready\n");
	// } else {
	// 	printk("i2c0 ready, probing 0x46...\n");
	// 	bool ok = i2c_probe_addr(i2c_dev_dbg, 0x46);
	// 	printk("probe 0x46 %s\n", ok ? "OK" : "FAIL");
	// }
    // Main loop - combine both BLE and sensor reading
    while (1) {
        k_sleep(K_SECONDS(1));

        // Read temperature from STS4X
        int32_t temperature;
        error = sts4x_measure_high_precision(&temperature);
        if (error) {
            printk("Error executing sts4x_measure_high_precision(): %i\n", error);
            printk("Check: 1) Pull-up resistors 2) Wiring 3) I2C address\n");
        } else {
            printk("Temperature: %.1f °C\n", temperature / 1000.0f);
        }

        //  sensirion_i2c_hal_sleep_usec(1000000);  /* Wait 1 second */

        /* Temperature measurements simulation (or use real temp) */
        hts_indicate();

        /* Battery level simulation */
        bas_notify();
    }
    
    return 0;
}

