#include "steering_control.h"
#include "devcontrol_common.h"
#include "gpio_common.h"

static SteeringControl s_steering_devices[] = {
    {DEVICE_CAR0102, "car0102", car0102_control_steering_change_process, car0102_steering_smooth_all},
    {DEVICE_SHIP0302, "ship0302", ship0302_control_steering_change_process, ship0302_steering_smooth_all},
    {0, "unknown", NULL, NULL}
};

SteeringControl* get_steering_control(void)
{
    int i = 0;
    while (s_steering_devices[i].id != 0) {
        if (s_steering_devices[i].id == g_device_type) {
            return &s_steering_devices[i];
        }
        i++;
    }
    return NULL;
}

// 线程调用：通过结构体分发到对应设备的平滑处理函数
bool steering_control_process(void) {
    static SteeringControl *ctrl = NULL;
    static bool s_initialized = false;
    if (!s_initialized) {
        ctrl = get_steering_control();
        s_initialized = true;
        if (ctrl == NULL) {
            my_zlog_info("当前设备无方向盘控制，线程退出");
            return false;
        }
    }
    if (ctrl && ctrl->smooth_process_func) {
        ctrl->smooth_process_func();
    }
    return true;
}

// MQTT调用：通过结构体分发到对应设备的方向盘接收函数
void steering_mqtt_recv(cJSON *body) {
    static SteeringControl *ctrl = NULL;
    
    if (ctrl == NULL) {
        ctrl = get_steering_control();
    }
    if (ctrl && ctrl->mqtt_recv_func) {
        cJSON *pwm_ctrl = cJSON_GetObjectItem(body, "pwm_ctrl");
        cJSON *pin_setctrl = cJSON_GetObjectItem(body, "pin_setctrl");
        if (pwm_ctrl == NULL || pin_setctrl == NULL)
        {
            return;
        }
        cJSON *mode = cJSON_GetObjectItem(pwm_ctrl, "mode"); // mode=1 速度，mode=2 转向(unsigned char)
        cJSON *type = cJSON_GetObjectItem(pwm_ctrl, "type");
        cJSON *val = cJSON_GetObjectItem(pwm_ctrl, "val"); // val为pwm的值 0~100(unsigned char)(unsigned char)
    
        int modeTemp = mode->valueint;
        int typeTemp = type->valueint;
        int valTemp = val->valueint;
        int buf[3]={typeTemp,modeTemp,valTemp};
    
        my_zlog_debug("typeTemp:%d,modeTemp:%d,valTemp:%d", buf[0], buf[1], buf[2]);
        ctrl->mqtt_recv_func(buf);
    }
}
