#include "ds18b20_onewire.h"

static onewire_ret_t ds18b20_match_rom(ds18b20_t *ds) {
    onewire_bus_write_byte(ds->ow_driver, 0x55); // Issue match ROM
    for(uint8_t i = 0; i < 8; i++) {
        onewire_bus_write_byte(ds->ow_driver, ds->rom.rom_num[i]);
    }

    return OW_OK;
}

onewire_ret_t ds18b20_start_convert(ds18b20_t *ds) {
    onewire_bus_reset(ds->ow_driver);
    ds18b20_match_rom(ds);
    onewire_bus_write_byte(ds->ow_driver, 0x44); // Issue convert T command

    return OW_OK;
}

uint8_t ds18b20_check_busy(ds18b20_t *ds) {
    uint8_t done = onewire_bus_read_bit(ds->ow_driver);

    if(done) return 0;
    return 1;
}

onewire_ret_t ds18b20_read_temperature(ds18b20_t *ds, ds18b20_temp_t *temp) {
    onewire_bus_reset(ds->ow_driver);
    ds18b20_match_rom(ds);
    onewire_bus_write_byte(ds->ow_driver, 0xBE); // Issue read scrachpad command

    temp->t_low = onewire_bus_read_byte(ds->ow_driver);
    temp->t_high = onewire_bus_read_byte(ds->ow_driver);

    onewire_bus_reset(ds->ow_driver);

    temp->t_decimal = (temp->t_high & 0xF8) ? 0x8000 : 0x0000;
    temp->t_decimal |= (temp->t_high & 0x07) << 8U;
    temp->t_decimal |= temp->t_low;

    temp->t_decimal = temp->t_decimal * 625 / 1000;

    return OW_OK;
}