#include "ch32v003fun.h"
#include "config.h"
#include "debug.h"
#include "dhcp.h"
#include "modbus_handler.h"
#include "mqtt_handler.h"
#include "system_init.h"
#include "w5500.h"

static mqtt_state_t mqtt_state;
static modbus_context_t modbus_ctx;

// Callback for modbus values
static void on_modbus_value(uint8_t device_idx, const char* property,
                            uint16_t value) {
  if (mqtt_state.is_connected) {
    publish_value(&mqtt_state.client, RS485_DEVICES[device_idx].name, property,
                  value);
  }
}

int main(void) {
  init_system();
  Delay_Ms(W5500_INIT_DELAY_MS);

  configure_network();
  dhcp_init();

  if (!wait_for_dhcp()) {
    while (1) {
      // TODO: Implement proper error handling
    }
  }

  // init handlers
  mqtt_init(&mqtt_state);
  modbus_handler_init(&modbus_ctx, on_modbus_value);

  while (1) {
    dhcp_process();
    mqtt_process(&mqtt_state);
    modbus_handler_process();
  }

  return 0;
}