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

static SteeringControl s_steering_devices[] = {
    {DEVICE_CAR0101, "car0101", NULL,                                    NULL},
    {DEVICE_CAR0102, "car0102", car0102_control_steering_change_process, car0102_steering_smooth_all},
    {DEVICE_CAR0103, "car0103", NULL,                                    NULL},
    {DEVICE_CAR0104, "car0104", NULL,                                    NULL},
    {DEVICE_CAR0105, "car0105", NULL,                                    NULL},
    {DEVICE_TANK0202, "tank0202", NULL, NULL},
    {DEVICE_TANK0203, "tank0203", NULL, NULL},
    {DEVICE_TANK0204, "tank0204", NULL, NULL},
    {DEVICE_TANK0206, "tank0206", NULL, NULL},
    {DEVICE_TANK0207, "tank0207", NULL, NULL},
    {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;
}

// 线程调用：通过结构体分发到对应设备的平滑处理函数
void steering_control_process(void) {
    static SteeringControl *ctrl = NULL;
    if (ctrl == NULL) {
        my_zlog_info("steering_control_process: ctrl is NULL");
        ctrl = get_steering_control();
    }
    if (ctrl && ctrl->smooth_process_func) {
        ctrl->smooth_process_func();
    }
}

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