搭建好了homeassitant和homebridge环境,开始搭建硬件平台,这里使用esp8266模块和官方的mqtt的SDK
首先,需要在homeassistant的配置文件中添加:
light:
platform: mqtt
name: 'Light'
state_topic: '/mqtt/topic/0'
command_topic: '/mqtt/topic/1'
brightness_state_topic: '/mqtt/topic/2'
brightness_command_topic: '/mqtt/topic/3'
brightness_scale: 100
重启hass便可以看到概览界面多了一个灯,
硬件程序设计:
1、配置mqtt_config.h中相应宏定义,以匹配之前搭建的mqtt环境
2、添加light的状态结构体以及PWM用到的IO引脚的宏
#define PWM_CHANNEL 1 // 5:5channel ; 3:3channel
/*Definition of GPIO PIN params, for GPIO initialization*/
#define PWM_0_OUT_IO_MUX PERIPHS_IO_MUX_MTDI_U
#define PWM_0_OUT_IO_NUM 12
#define PWM_0_OUT_IO_FUNC FUNC_GPIO12
struct light_param {
uint32 pwm_period;
uint32 pwm_duty[PWM_CHANNEL];
};
struct light_state {
uint32 state;
};
在用户代码文件中:
#define LIGHT_SWITCH_ON "ON"
#define LIGHT_SWITCH_OFF "OFF"
#define LIGHT_SWITCH_STATE "/mqtt/topic/0"
#define LIGHT_SWITCH_CONTROL "/mqtt/topic/1"
#define LIGHT_BRIGHTNESS_STATE "/mqtt/topic/2"
#define LIGHT_BRIGHTNESS_CONTROL "/mqtt/topic/3"
#define LIGHT_GPIO_1 5
#define LIGHT_GPIO_ON 1
#define LIGHT_GPIO_OFF 0
#define LIGHT_PWM_CYCLE 1000
#define LIGHT_PWM_DUTY_MAX (LIGHT_PWM_CYCLE*1000/45)
#define LIGHT_PWM_DUTY_UNIT (LIGHT_PWM_DUTY_MAX/100)
#define LIGHT_PWM_DUTY(n) ((n*45)/(LIGHT_PWM_CYCLE * 1000))
uint32 io_info[][3] =
{{PWM_4_OUT_IO_MUX,PWM_4_OUT_IO_FUNC,PWM_4_OUT_IO_NUM},
struct light_param light_p;
struct light_state light_s;
主要用户代码:
if(0 != os_strstr(topicBuf, LIGHT_SWITCH_CONTROL))
{
if(0 != os_strstr(dataBuf, LIGHT_SWITCH_OFF))
{
MQTT_Publish(client, LIGHT_SWITCH_STATE, LIGHT_SWITCH_OFF, 3, 0, 0);
hw_timer_cmd(0);
GPIO_OUTPUT_SET(LIGHT_GPIO_1, LIGHT_GPIO_OFF);
}
else
{
MQTT_Publish(client, LIGHT_SWITCH_STATE, LIGHT_SWITCH_ON, 2, 0, 0);
hw_timer_cmd(1);
pwm_set_duty(light_p.pwm_duty[0], 0);
pwm_start();
}
}
if(0 != os_strstr(topicBuf, LIGHT_BRIGHTNESS_CONTROL))
{
if(data_len == 3)
{
brightness = ((dataBuf[0] - 0x30)*100);
brightness += ((dataBuf[1] - 0x30) * 10);
brightness += (dataBuf[2] - 0x30);
}
else if(data_len == 2)
{
brightness = ((dataBuf[0] - 0x30)*10);
brightness += (dataBuf[1] - 0x30) ;
}
else
{
brightness += (dataBuf[0] - 0x30) ;
}
MQTT_Publish(client, LIGHT_BRIGHTNESS_STATE, dataBuf, strlen(dataBuf), 0, 0);
if(brightness == 0)
{
MQTT_Publish(client, LIGHT_SWITCH_STATE, LIGHT_SWITCH_OFF, 3, 0, 0);
light_p.pwm_duty[0] = 0;
}
else{
MQTT_Publish(client, LIGHT_SWITCH_STATE, LIGHT_SWITCH_ON, 2, 0, 0);
light_p.pwm_duty[0] = brightness*LIGHT_PWM_DUTY_UNIT;
}
pwm_set_duty(light_p.pwm_duty[0], 0);
pwm_start();
}