esp_zb_switch.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * Copyright (c) 2021 Espressif Systems (Shanghai) CO LTD
  3. * All rights reserved.
  4. *
  5. *
  6. * Redistribution and use in source and binary forms, with or without modification,
  7. * are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form, except as embedded into a Espressif Systems
  13. * integrated circuit in a product or a software update for such product,
  14. * must reproduce the above copyright notice, this list of conditions and
  15. * the following disclaimer in the documentation and/or other materials
  16. * provided with the distribution.
  17. *
  18. * 3. Neither the name of the copyright holder nor the names of its contributors
  19. * may be used to endorse or promote products derived from this software without
  20. * specific prior written permission.
  21. *
  22. * 4. Any software provided in binary form under this license must not be reverse
  23. * engineered, decompiled, modified and/or disassembled.
  24. *
  25. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  26. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  27. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  28. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  29. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  30. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  31. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  32. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  33. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  34. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  35. * POSSIBILITY OF SUCH DAMAGE.
  36. */
  37. #include "esp_log.h"
  38. #include "freertos/FreeRTOS.h"
  39. #include "freertos/task.h"
  40. #include "esp_zb_switch.h"
  41. /**
  42. * @note Make sure set idf.py menuconfig in zigbee component as zigbee coordinator device!
  43. */
  44. #if defined ZB_ED_ROLE
  45. #error Define ZB_COORDINATOR_ROLE in idf.py menuconfig to compile light switch source code.
  46. #endif
  47. /* define Button function currently only 1 switch define */
  48. static switch_func_pair_t button_func_pair[] = {
  49. {GPIO_INPUT_IO_TOGGLE_SWITCH, SWITCH_ONOFF_TOGGLE_CONTROL}
  50. };
  51. static switch_device_ctx_t esp_switch_ctx = {
  52. /* basic cluster attributes data */
  53. .basic_attr.zcl_version = ZB_ZCL_VERSION,
  54. .basic_attr.power_source = ZB_ZCL_BASIC_POWER_SOURCE_UNKNOWN,
  55. /* identify cluster attributes data */
  56. .identify_attr.identify_time = 0,
  57. /* bulb parameters */
  58. .bulb_params.short_addr = 0xffff,
  59. };
  60. static const char *TAG = "ESP_ZB_SWITCH";
  61. /******************* Declare attributes ************************/
  62. /* basic cluster attributes data */
  63. ZB_ZCL_DECLARE_BASIC_ATTRIB_LIST(basic_attr_list,
  64. &esp_switch_ctx.basic_attr.zcl_version,
  65. &esp_switch_ctx.basic_attr.power_source);
  66. /* identify cluster attributes data */
  67. ZB_ZCL_DECLARE_IDENTIFY_ATTRIB_LIST(identify_attr_list,
  68. &esp_switch_ctx.identify_attr.identify_time);
  69. /* switch config cluster attributes data */
  70. zb_uint8_t attr_switch_type =
  71. ZB_ZCL_ON_OFF_SWITCH_CONFIGURATION_SWITCH_TYPE_TOGGLE;
  72. zb_uint8_t attr_switch_actions =
  73. ZB_ZCL_ON_OFF_SWITCH_CONFIGURATION_SWITCH_ACTIONS_DEFAULT_VALUE;
  74. ZB_ZCL_DECLARE_ON_OFF_SWITCH_CONFIGURATION_ATTRIB_LIST(switch_cfg_attr_list, &attr_switch_type, &attr_switch_actions);
  75. /********************* Declare device **************************/
  76. ZB_HA_DECLARE_ON_OFF_SWITCH_CLUSTER_LIST(on_off_switch_clusters, switch_cfg_attr_list, basic_attr_list, identify_attr_list);
  77. ZB_HA_DECLARE_ON_OFF_SWITCH_EP(on_off_switch_ep, HA_ONOFF_SWITCH_ENDPOINT, on_off_switch_clusters);
  78. ZB_HA_DECLARE_ON_OFF_SWITCH_CTX(on_off_switch_ctx, on_off_switch_ep);
  79. static void esp_zb_find_light_bulb_cb(zb_bufid_t bufid);
  80. /********************* Define functions **************************/
  81. /**
  82. * @brief return true is switch find bulb
  83. */
  84. static bool esp_zb_already_find_light_bulb(void)
  85. {
  86. return !(esp_switch_ctx.bulb_params.short_addr == 0xffff);
  87. }
  88. /**
  89. * @brief Function for sending on/off and Level Control find request.
  90. *
  91. * @param bufid Zigbee zboss stack buffer id will be used to construct find request.
  92. */
  93. static void esp_zb_find_light_bulb(zb_bufid_t bufid)
  94. {
  95. zb_zdo_match_desc_param_t *p_req;
  96. /* initialize pointers inside buffer and reserve space for zb_zdo_match_desc_param_t request */
  97. p_req = zb_buf_initial_alloc(bufid, sizeof(zb_zdo_match_desc_param_t) + (1) * sizeof(zb_uint16_t));
  98. p_req->nwk_addr = MATCH_DESC_REQ_ROLE; /* send to devices specified by MATCH_DESC_REQ_ROLE */
  99. p_req->addr_of_interest = MATCH_DESC_REQ_ROLE; /* get responses from devices specified by MATCH_DESC_REQ_ROLE */
  100. p_req->profile_id = ZB_AF_HA_PROFILE_ID; /* look for Home Automation profile clusters */
  101. /* we are searching for 1 cluster:
  102. on/off
  103. */
  104. p_req->num_in_clusters = 1;
  105. p_req->num_out_clusters = 0;
  106. p_req->cluster_list[0] = ZB_ZCL_CLUSTER_ID_ON_OFF;
  107. /* set 0xFFFF to reset short address in order to parse only one response. */
  108. esp_switch_ctx.bulb_params.short_addr = 0xFFFF;
  109. zb_zdo_match_desc_req(bufid, esp_zb_find_light_bulb_cb);
  110. }
  111. /**
  112. * @brief Finding procedure timeout handler.
  113. *
  114. * @param bufid Zigbee zboss stack buffer id will be used to construct find request.
  115. */
  116. static void esp_zb_find_light_bulb_timeout(zb_bufid_t bufid)
  117. {
  118. zb_ret_t zb_err_code;
  119. if (bufid) {
  120. ESP_LOGW(TAG, "Bulb not found, try again");
  121. zb_err_code = ZB_SCHEDULE_APP_ALARM(esp_zb_find_light_bulb, bufid, MATCH_DESC_REQ_START_DELAY);
  122. ESP_ERROR_CHECK(zb_err_code);
  123. zb_err_code = ZB_SCHEDULE_APP_ALARM(esp_zb_find_light_bulb_timeout, 0, MATCH_DESC_REQ_TIMEOUT);
  124. ESP_ERROR_CHECK(zb_err_code);
  125. } else {
  126. zb_err_code = zb_buf_get_out_delayed(esp_zb_find_light_bulb_timeout);
  127. ESP_ERROR_CHECK(zb_err_code);
  128. }
  129. }
  130. /**
  131. * @brief Callback function receiving finding procedure results.
  132. *
  133. * @param bufid Zigbee zboss stack buffer id is used to pass received data.
  134. */
  135. static void esp_zb_find_light_bulb_cb(zb_bufid_t bufid)
  136. {
  137. zb_zdo_match_desc_resp_t *p_resp = (zb_zdo_match_desc_resp_t *) zb_buf_begin(bufid); /* get the beginning of the response */
  138. zb_apsde_data_indication_t *p_ind = ZB_BUF_GET_PARAM(bufid, zb_apsde_data_indication_t); /* get the pointer to the parameters buffer, which stores APS layer response */
  139. zb_uint8_t *p_match_ep;
  140. zb_ret_t zb_err_code;
  141. if ((p_resp->status == ZB_ZDP_STATUS_SUCCESS) && (p_resp->match_len > 0) && (esp_switch_ctx.bulb_params.short_addr == 0xFFFF)) {
  142. /* match EP list follows right after response header */
  143. p_match_ep = (zb_uint8_t *)(p_resp + 1);
  144. /* We are searching for exact cluster, so only 1 EP may be found */
  145. esp_switch_ctx.bulb_params.endpoint = *p_match_ep;
  146. esp_switch_ctx.bulb_params.short_addr = p_ind->src_addr;
  147. ESP_LOGI(TAG, "Found bulb addr: 0x%x ep: %d", esp_switch_ctx.bulb_params.short_addr, esp_switch_ctx.bulb_params.endpoint);
  148. zb_err_code = ZB_SCHEDULE_APP_ALARM_CANCEL(esp_zb_find_light_bulb_timeout, ZB_ALARM_ANY_PARAM);
  149. ESP_ERROR_CHECK(zb_err_code);
  150. }
  151. if (bufid) {
  152. zb_buf_free(bufid);
  153. }
  154. }
  155. /**
  156. * @brief Function for sending on/off Toggle requests to the light bulb.
  157. *
  158. * @param bufid Zigbee zboss stack buffer id will be used to construct on/off request.
  159. * @param on_off_toggle unused value.
  160. */
  161. static void esp_zb_light_switch_send_on_off_toggle(zb_bufid_t bufid, zb_uint16_t on_off_toggle)
  162. {
  163. static zb_uint8_t cmd_id = ZB_ZCL_CMD_ON_OFF_TOGGLE_ID;
  164. ESP_LOGI(TAG, "Send ON/OFF toggle command");
  165. ZB_ZCL_ON_OFF_SEND_REQ(bufid,
  166. esp_switch_ctx.bulb_params.short_addr,
  167. ZB_APS_ADDR_MODE_16_ENDP_PRESENT,
  168. esp_switch_ctx.bulb_params.endpoint,
  169. HA_ONOFF_SWITCH_ENDPOINT,
  170. ZB_AF_HA_PROFILE_ID,
  171. ZB_ZCL_DISABLE_DEFAULT_RESPONSE,
  172. cmd_id,
  173. NULL);
  174. }
  175. /**
  176. * @brief Callback for button events, currently only toggle event available
  177. *
  178. * @param button_func_pair Incoming event from the button_pair.
  179. */
  180. static void esp_zb_buttons_handler(switch_func_pair_t button_func_pair)
  181. {
  182. zb_ret_t zb_err_code = ESP_OK;
  183. if (!esp_zb_already_find_light_bulb()) {
  184. /* no bulb found yet */
  185. return;
  186. }
  187. if (button_func_pair.func == SWITCH_ONOFF_TOGGLE_CONTROL) {
  188. /* implemented light switch toggle functionality */
  189. zb_err_code = zb_buf_get_out_delayed_ext(esp_zb_light_switch_send_on_off_toggle, 0, 0);
  190. }
  191. ESP_ERROR_CHECK(zb_err_code);
  192. }
  193. static void bdb_start_top_level_commissioning_cb(zb_uint8_t mode_mask)
  194. {
  195. if (!bdb_start_top_level_commissioning(mode_mask)) {
  196. ESP_LOGE(TAG, "In BDB commissioning, an error occurred (for example: the device has already been running)");
  197. }
  198. }
  199. /**
  200. * @brief Zigbee zboss stack event signal handler.
  201. *
  202. * @param bufid Zigbee zboss stack buffer id used to pass signal.
  203. */
  204. void zboss_signal_handler(zb_bufid_t bufid)
  205. {
  206. zb_zdo_app_signal_hdr_t *p_sg_p = NULL;
  207. zb_uint8_t status = ZB_GET_APP_SIGNAL_STATUS(bufid);
  208. zb_zdo_app_signal_type_t sig = zb_get_app_signal(bufid, &p_sg_p);
  209. zb_zdo_signal_device_annce_params_t *dev_annce_params = NULL;
  210. zb_ret_t zb_err_code;
  211. zb_nlme_permit_joining_request_t *request = NULL;
  212. switch (sig) {
  213. case ZB_ZDO_SIGNAL_SKIP_STARTUP:
  214. ESP_LOGI(TAG, "Zigbee stack initialized");
  215. bdb_start_top_level_commissioning(ZB_BDB_INITIALIZATION);
  216. break;
  217. case ZB_BDB_SIGNAL_DEVICE_FIRST_START:
  218. if (status == RET_OK) {
  219. ESP_LOGI(TAG, "Start network formation");
  220. bdb_start_top_level_commissioning(ZB_BDB_NETWORK_FORMATION);
  221. } else {
  222. ESP_LOGE(TAG, "Failed to initialize Zigbee stack (status: %d)", status);
  223. }
  224. break;
  225. case ZB_BDB_SIGNAL_FORMATION:
  226. if (status == RET_OK) {
  227. zb_ext_pan_id_t extended_pan_id;
  228. zb_get_extended_pan_id(extended_pan_id);
  229. ESP_LOGI(TAG, "Joined network successfully (Extended PAN ID: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x, PAN ID: 0x%04hx)",
  230. extended_pan_id[7], extended_pan_id[6], extended_pan_id[5], extended_pan_id[4],
  231. extended_pan_id[3], extended_pan_id[2], extended_pan_id[1], extended_pan_id[0],
  232. ZB_PIBCACHE_PAN_ID());
  233. bdb_start_top_level_commissioning(ZB_BDB_NETWORK_STEERING);
  234. } else {
  235. ESP_LOGI(TAG, "Restart network formation (status: %d)", status);
  236. ZB_SCHEDULE_APP_ALARM((zb_callback_t)bdb_start_top_level_commissioning_cb, ZB_BDB_NETWORK_FORMATION, ZB_TIME_ONE_SECOND);
  237. }
  238. break;
  239. case ZB_BDB_SIGNAL_STEERING:
  240. if (status == RET_OK) {
  241. request = ZB_BUF_GET_PARAM(bufid, zb_nlme_permit_joining_request_t);
  242. ESP_LOGI(TAG, "Network steering started/refreshed");
  243. ZB_SCHEDULE_APP_ALARM((zb_callback_t)bdb_start_top_level_commissioning_cb, ZB_BDB_NETWORK_STEERING, (request->permit_duration)*ZB_TIME_ONE_SECOND);
  244. }
  245. break;
  246. case ZB_ZDO_SIGNAL_DEVICE_ANNCE:
  247. dev_annce_params = ZB_ZDO_SIGNAL_GET_PARAMS(p_sg_p, zb_zdo_signal_device_annce_params_t);
  248. ESP_LOGI(TAG, "New device commissioned or rejoined (short: 0x%04hx)", dev_annce_params->device_short_addr);
  249. /* check the light device address */
  250. if (!esp_zb_already_find_light_bulb()) {
  251. zb_err_code = ZB_SCHEDULE_APP_ALARM(esp_zb_find_light_bulb, bufid, MATCH_DESC_REQ_START_DELAY);
  252. ESP_ERROR_CHECK(zb_err_code);
  253. zb_err_code = ZB_SCHEDULE_APP_ALARM(esp_zb_find_light_bulb_timeout, 0, MATCH_DESC_REQ_TIMEOUT);
  254. ESP_ERROR_CHECK(zb_err_code);
  255. bufid = 0; /* Do not free buffer - it will be reused by find_light_bulb callback */
  256. }
  257. break;
  258. default:
  259. ESP_LOGI(TAG, "status: %d", status);
  260. break;
  261. }
  262. if (bufid) {
  263. zb_buf_free(bufid);
  264. }
  265. }
  266. static void zboss_task(void *pvParameters)
  267. {
  268. /* initialize Zigbee stack. */
  269. ZB_INIT("light_switch");
  270. zb_set_network_coordinator_role(IEEE_CHANNEL_MASK);
  271. zb_set_max_children(MAX_CHILDREN);
  272. zb_set_nvram_erase_at_start(ERASE_PERSISTENT_CONFIG);
  273. /* hardware related and device init */
  274. switch_driver_init(button_func_pair, PAIR_SIZE(button_func_pair), esp_zb_buttons_handler);
  275. /* register on_off switch device context (endpoints) */
  276. ZB_AF_REGISTER_DEVICE_CTX(&on_off_switch_ctx);
  277. ESP_ERROR_CHECK(zboss_start_no_autostart());
  278. while (1) {
  279. zboss_main_loop_iteration();
  280. }
  281. }
  282. void app_main(void)
  283. {
  284. zb_esp_platform_config_t config = {
  285. .radio_config = ZB_ESP_DEFAULT_RADIO_CONFIG(),
  286. .host_config = ZB_ESP_DEFAULT_HOST_CONFIG(),
  287. };
  288. /* load Zigbee switch platform config to initialization */
  289. ESP_ERROR_CHECK(zb_esp_platform_config(&config));
  290. xTaskCreate(zboss_task, "zboss_main", 4096, NULL, 5, NULL);
  291. }