-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.c
774 lines (648 loc) · 26.5 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/**
* Changes:
*
* 2-8-2019: Otávio Ribeiro <otavio.ribeiro@gmail.com>
*
* Addapting i2c digital light sensor to work as a zigbee illumination sensor
* using Nordic SDK
*/
/**
* Copyright (c) 2019, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdbool.h>
#include <stddef.h>
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"
#include "zboss_api.h"
#include "zb_mem_config_med.h"
#include "zb_error_handler.h"
#include "zigbee_helpers.h"
#include "app_timer.h"
#include "bsp.h"
#include "boards.h"
#include "nrf_assert.h"
#include "nrf_drv_clock.h"
#include "nrf_delay.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "zb_light_sensor.h"
#include "twi_config.h"
#include "nrf_drv_twi.h"
#include "tsl2561.h"
/**
* TWI master instance.
*/
static const nrf_drv_twi_t m_twi_master = NRF_DRV_TWI_INSTANCE(MASTER_TWI_INST);
#define MAX_CHILDREN 5
#define IEEE_CHANNEL_MASK 0x7FFF800 /**< Scan all channel to find the coordinator. */
#define ERASE_PERSISTENT_CONFIG ZB_FALSE /**< Do not erase NVRAM to save the network parameters after device reboot or power-off. */
#define ZIGBEE_NETWORK_STATE_LED BSP_BOARD_LED_0 /**< Joined, Joing, Failed Join */
#define ZIGBEE_NETWORK_COMMISSIONING_BTN BSP_BUTTON_0 /**< Joined, Joing, Failed Join */
#define MAX_ILLUMINANCE 1500
#define MIN_ILLUMINANCE 0
#if !defined ZB_ROUTER_ROLE
#error Define ZB_ROUTER_ROLE to compile light bulb (Router) source code.
#endif
#define ZIGBEE_MAIN_TASK_PRIORITY (tskIDLE_PRIORITY + 2U)
static TaskHandle_t m_zigbee_main_task_handle;
static SemaphoreHandle_t m_zigbee_main_task_mutex;
#define ILLUMINANCE_MEASUREMENT_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE + 200U)
#define ILLUMINANCE_MEASUREMENT_TASK_PRIORITY (tskIDLE_PRIORITY + 2U)
static TaskHandle_t m_illuminance_measurement_task_handle;
#define LED_TOGGLE_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE + 64U)
#define LED_TOGGLE_TASK_PRIORITY (tskIDLE_PRIORITY + 2U)
static TaskHandle_t m_led_toggle_task_handle;
#if (NRF_LOG_ENABLED && NRF_LOG_DEFERRED)
#define LOG_TASK_STACK_SIZE (1024U / sizeof(StackType_t))
#define LOG_TASK_PRIORITY (tskIDLE_PRIORITY + 1U) /**< Must be lower than any task generating logs */
static TaskHandle_t m_logger_task_handle;
#endif
static sensor_device_ctx_t m_dev_ctx;
/* current light sensor sensitivity */
static tsl2561_sensitivity_t current_sensitivity = TSL2561_SENSITIVITY_HIGH;
/* keep track of how many button has been clicked */
static uint8_t button_count = 0;
static volatile bool ind_reset_network = false;
ZB_ZCL_DECLARE_IDENTIFY_ATTR_LIST(identify_attr_list,
m_dev_ctx.identify_attr);
ZB_ZCL_DECLARE_BASIC_ATTRIB_LIST_EXT(basic_attr_list,
&m_dev_ctx.basic_attr.zcl_version,
&m_dev_ctx.basic_attr.app_version,
&m_dev_ctx.basic_attr.stack_version,
&m_dev_ctx.basic_attr.hw_version,
m_dev_ctx.basic_attr.mf_name,
m_dev_ctx.basic_attr.model_id,
m_dev_ctx.basic_attr.date_code,
&m_dev_ctx.basic_attr.power_source,
m_dev_ctx.basic_attr.location_id,
&m_dev_ctx.basic_attr.ph_env,
m_dev_ctx.basic_attr.sw_ver);
ZB_ZCL_DECLARE_ILLUMINANCE_MEASUREMENT_ATTRIB_LIST(illum_measure_attr_list,
&m_dev_ctx.illum_attr.measure_value,
&m_dev_ctx.illum_attr.min_measure_value,
&m_dev_ctx.illum_attr.max_measure_value);
ZB_DECLARE_LIGHT_SENSOR_CLUSTER_LIST(light_sensor_clusters,
identify_attr_list,
basic_attr_list,
illum_measure_attr_list);
ZB_ZCL_DECLARE_LIGHT_SENSOR_EP(light_sensor_ep,
LIGHT_SENSOR_ENDPOINT,
light_sensor_clusters);
ZBOSS_DECLARE_DEVICE_CTX_1_EP(light_sensor_ctx, light_sensor_ep);
APP_TIMER_DEF(button_timer);
static void blink_sensitivity(){
bsp_board_led_off(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_on(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_off(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_on(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_off(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_on(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
/**
* blink led "current_sensitivity" times
*
* 1 - low
* 2 - medium
* 3 - high
*
* */
bsp_board_led_off(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(1000);
for(int i = 0; i < current_sensitivity; i++){
bsp_board_led_on(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(500);
bsp_board_led_off(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(500);
}
nrf_delay_ms(500);
bsp_board_led_on(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_off(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_on(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_off(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_on(ZIGBEE_NETWORK_STATE_LED);
nrf_delay_ms(100);
bsp_board_led_off(ZIGBEE_NETWORK_STATE_LED);
}
/**@brief Callback scheduled from @ref button_timer_handler
*
* @details This callback does the real job executing the button action. That will depend on the number
* of times that the buttons has been clicked
*
* @param param[in] Parameter passed t ZB_SCHEDULE_APP_CALLBACK, unused here.
*/
static void button_handle_cb(zb_uint8_t param)
{
NRF_LOG_INFO("Processing button handle: %d clicks", param);
if(param == 2){
//TODO: save this change on flash to start the sensor right on reboot
if(++current_sensitivity > TSL2561_SENSITIVITY_HIGH) current_sensitivity = TSL2561_SENSITIVITY_LOW;
NRF_LOG_INFO("Changing sensor sensitivity to %s", (current_sensitivity == TSL2561_SENSITIVITY_HIGH ? "high" : (current_sensitivity == TSL2561_SENSITIVITY_MEDIUM ? "medium" : "low")));
tsl2561_sensitivity(&m_twi_master, current_sensitivity);
blink_sensitivity();
} else if(param == 3){
/* just use the led to shows the current sensitivity level */
blink_sensitivity();
} else if(param == 10){
NRF_LOG_INFO("Factory Reset");
ind_reset_network = true;
}
}
/**@brief Function for handling counting how many times the button has been pressed
*
* @param[in] context void pointer to context
*/
static void button_timer_handler(void * context)
{
ret_code_t error_code;
zb_ret_t zb_ret;
UNUSED_PARAMETER(context);
/* Note: ZB_SCHEDULE_APP_CALLBACK is thread safe by exception, conversely to most ZBOSS API */
zb_ret = ZB_SCHEDULE_APP_CALLBACK(button_handle_cb, button_count);
if (zb_ret != RET_OK)
{
NRF_LOG_ERROR("Button Handle Lost.");
}
/* reset button count*/
button_count = 0;
/* stop timer */
error_code = app_timer_stop(button_timer);
APP_ERROR_CHECK(error_code);
}
/**
* @brief TWI events handler.
*/
void twi_handler(nrf_drv_twi_evt_t const * p_event, void * p_context)
{
tsl2561_twi_handler(p_event, p_context);
}
/**
* @brief Initialize the master TWI.
*
* Function used to initialize the master TWI interface.
*
* @return NRF_SUCCESS or the reason of failure.
*/
static ret_code_t twi_master_init(void)
{
ret_code_t ret;
const nrf_drv_twi_config_t config =
{
.scl = TWI_SCL_M,
.sda = TWI_SDA_M,
.frequency = NRF_DRV_TWI_FREQ_400K,
.interrupt_priority = APP_IRQ_PRIORITY_HIGH,
.clear_bus_init = false
};
ret = nrf_drv_twi_init(&m_twi_master, &config, twi_handler, NULL);
if (NRF_SUCCESS == ret)
{
NRF_LOG_INFO("Twi interface started.");
nrf_drv_twi_enable(&m_twi_master);
} else {
NRF_LOG_INFO("Error starting twi interface.");
}
return ret;
}
/**@brief Function for the Timer initialization.
*
* @details Initializes the timer module. This creates and starts application timers.
*/
static void timers_init(void)
{
ret_code_t err_code;
// Initialize timer module.
err_code = app_timer_init();
APP_ERROR_CHECK(err_code);
}
/**@brief Function for initializing the nrf log module.
*/
static void log_init(void)
{
ret_code_t err_code = NRF_LOG_INIT(NULL);
APP_ERROR_CHECK(err_code);
NRF_LOG_DEFAULT_BACKENDS_INIT();
}
/**@brief Function for initializing the clock.
*/
static void clock_init(void)
{
ret_code_t err_code = nrf_drv_clock_init();
APP_ERROR_CHECK(err_code);
}
/**@brief Function for initializing all clusters attributes.
*/
static void light_sensor_clusters_attr_init(void)
{
/* Basic cluster attributes data */
m_dev_ctx.basic_attr.zcl_version = ZB_ZCL_VERSION;
m_dev_ctx.basic_attr.app_version = SENSOR_INIT_BASIC_APP_VERSION;
m_dev_ctx.basic_attr.stack_version = SENSOR_INIT_BASIC_STACK_VERSION;
m_dev_ctx.basic_attr.hw_version = SENSOR_INIT_BASIC_HW_VERSION;
/* Use ZB_ZCL_SET_STRING_VAL to set strings, because the first byte should
* contain string length without trailing zero.
*
* For example "test" string wil be encoded as:
* [(0x4), 't', 'e', 's', 't']
*/
ZB_ZCL_SET_STRING_VAL(m_dev_ctx.basic_attr.mf_name,
SENSOR_INIT_BASIC_MANUF_NAME,
ZB_ZCL_STRING_CONST_SIZE(SENSOR_INIT_BASIC_MANUF_NAME));
ZB_ZCL_SET_STRING_VAL(m_dev_ctx.basic_attr.model_id,
SENSOR_INIT_BASIC_MODEL_ID,
ZB_ZCL_STRING_CONST_SIZE(SENSOR_INIT_BASIC_MODEL_ID));
ZB_ZCL_SET_STRING_VAL(m_dev_ctx.basic_attr.date_code,
SENSOR_INIT_BASIC_DATE_CODE,
ZB_ZCL_STRING_CONST_SIZE(SENSOR_INIT_BASIC_DATE_CODE));
m_dev_ctx.basic_attr.power_source = SENSOR_INIT_BASIC_POWER_SOURCE;
ZB_ZCL_SET_STRING_VAL(m_dev_ctx.basic_attr.location_id,
SENSOR_INIT_BASIC_LOCATION_DESC,
ZB_ZCL_STRING_CONST_SIZE(SENSOR_INIT_BASIC_LOCATION_DESC));
m_dev_ctx.basic_attr.ph_env = SENSOR_INIT_BASIC_PH_ENV;
/* Identify cluster attributes data */
m_dev_ctx.identify_attr.identify_time = ZB_ZCL_IDENTIFY_IDENTIFY_TIME_DEFAULT_VALUE;
/* Illuminance measurement cluster attributes data */
m_dev_ctx.illum_attr.measure_value = ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_DEFAULT;
m_dev_ctx.illum_attr.min_measure_value = MIN_ILLUMINANCE;
m_dev_ctx.illum_attr.max_measure_value = MAX_ILLUMINANCE;
}
void bsp_evt_handler(bsp_event_t evt)
{
switch (evt)
{
case BSP_EVENT_KEY_0:
/* increase button count and start waiting */
button_count ++;
/* start our timer. This will fail after the second click, but its ok */
app_timer_start(button_timer, APP_TIMER_TICKS(5000), NULL);
break;
default:
return; // no implementation needed
}
}
/**@brief Function for initializing LEDs and Buttons.
*/
static void board_init(void)
{
ret_code_t error_code;
/* Initialize LEDs - use BSP to control them. */
error_code = bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, bsp_evt_handler);
APP_ERROR_CHECK(error_code);
bsp_board_leds_off();
}
/**@brief Task performing illuminance measurement.
*
* @param pvParam Not used, required by freertos api
*/
static void illuminance_measurement_task(void *pvParam)
{
UNUSED_PARAMETER(pvParam);
NRF_LOG_INFO("The illuminance_measurement_task started.");
zb_zcl_status_t zcl_status;
zb_uint16_t new_illumination_value;
TickType_t last_update_wake_timestamp;
uint8_t signature = tsl2561_read_id(&m_twi_master);
if(signature == 0x50){
NRF_LOG_INFO("Digital Light Sensor TSL2561 found! Initializing...");
tsl2561_init(&m_twi_master);
tsl2561_sensitivity(&m_twi_master, current_sensitivity);
} else {
NRF_LOG_ERROR("Digital Light Sensor TSL2561 not found!");
}
last_update_wake_timestamp = xTaskGetTickCount();
while (true)
{
vTaskSuspendAll();
/* Get new pressure measured value */
if(tsl2561_read_lux(&m_twi_master, (uint16_t*)&new_illumination_value) != TSL2561_LUX_ERROR_NOERROR){
new_illumination_value = MAX_ILLUMINANCE;
}
if(new_illumination_value > MAX_ILLUMINANCE){
new_illumination_value = MAX_ILLUMINANCE;
}
if(new_illumination_value <= 1) new_illumination_value = 0;
NRF_LOG_INFO("Illumination value is: %ld", new_illumination_value);
UNUSED_RETURN_VALUE(xTaskResumeAll());
if (xSemaphoreTakeRecursive(m_zigbee_main_task_mutex, 1000U) == pdTRUE)
{
/* Set new illuminance value as zcl attribute
* NOTE this is not thread-safe and locking is required
*/
zcl_status = zb_zcl_set_attr_val(LIGHT_SENSOR_ENDPOINT,
ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT,
ZB_ZCL_CLUSTER_SERVER_ROLE,
ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID,
(zb_uint8_t *)&new_illumination_value,
ZB_FALSE);
UNUSED_RETURN_VALUE(xSemaphoreGiveRecursive(m_zigbee_main_task_mutex));
if (zcl_status != ZB_ZCL_STATUS_SUCCESS)
{
NRF_LOG_INFO("Set illumination value fail. zcl_status: %d", zcl_status);
}
}
/* Let the task sleep for some time, consider it as illumination sample period */
vTaskDelayUntil(&last_update_wake_timestamp, pdMS_TO_TICKS(5000U));
}
}
static zb_void_t device_join(zb_uint8_t param)
{
UNUSED_PARAMETER(param);
zb_bool_t comm_status;
comm_status = bdb_start_top_level_commissioning(ZB_BDB_NETWORK_STEERING);
ZB_COMM_STATUS_CHECK(comm_status);
}
static void light_sensor_leave_and_join( zb_uint8_t param )
{
zb_bdb_reset_via_local_action(param);
}
/**@brief ZigBee stack event handler.
*
* @param[in] param Reference to ZigBee stack buffer used to pass arguments (signal).
*/
void zboss_signal_handler(zb_bufid_t param)
{
zb_zdo_app_signal_hdr_t * p_sg_p = NULL;
zb_zdo_app_signal_type_t sig = zb_get_app_signal(param, &p_sg_p);
zb_ret_t status = ZB_GET_APP_SIGNAL_STATUS(param);
zb_ret_t zb_err_code;
zb_bool_t comm_status;
switch (sig)
{
case ZB_BDB_SIGNAL_DEVICE_FIRST_START:
if (status == RET_OK) {
comm_status = bdb_start_top_level_commissioning(ZB_BDB_NETWORK_STEERING);
ZB_COMM_STATUS_CHECK(comm_status);
} else {
/* Failed to initialize Zigbee stack. */
}
break;
case ZB_BDB_SIGNAL_DEVICE_REBOOT:
/* fall-through */
case ZB_BDB_SIGNAL_STEERING:
ZB_ERROR_CHECK(zigbee_default_signal_handler(param));
if (status == RET_OK) {
/* Joined network successfully. */
/* TODO: Start application-specific logic that requires the device to be connected to a Zigbee network. */
} else {
/* Unable to join the network. Restart network steering. */
zb_err_code = ZB_SCHEDULE_APP_ALARM(device_join, 0, ZB_TIME_ONE_SECOND);
ZB_ERROR_CHECK(zb_err_code);
}
break;
case ZB_ZDO_SIGNAL_LEAVE:
NRF_LOG_INFO("Leaving Zigbee Network");
if (status == RET_OK) {
/* Device has left the network. */
/* TODO: Start application-specific logic or start network steering to join a new network. */
/* This signal comes with additional data in which type of leave is stored. */
zb_zdo_signal_leave_params_t *leave_params = ZB_ZDO_SIGNAL_GET_PARAMS(p_sg_p, zb_zdo_signal_leave_params_t);
switch (leave_params->leave_type) {
case ZB_NWK_LEAVE_TYPE_RESET:
/* Device left network without rejoining. */
zb_err_code = ZB_SCHEDULE_APP_ALARM(device_join, 0, ZB_TIME_ONE_SECOND);
ZB_ERROR_CHECK(zb_err_code);
break;
case ZB_NWK_LEAVE_TYPE_REJOIN:
/* Device left network with rejoin. */
break;
default:
/* Unrecognised leave type. */
/* Device left network without rejoining. */
zb_err_code = ZB_SCHEDULE_APP_ALARM(device_join, 0, ZB_TIME_ONE_SECOND);
ZB_ERROR_CHECK(zb_err_code);
break;
}
} else {
/* Device was unable to leave network. */
}
break;
default:
/* Call default signal handler. */
ZB_ERROR_CHECK(zigbee_default_signal_handler(param));
break;
}
if (param)
{
zb_buf_free(param);
}
}
void zigbee_main_task(void *pvParameter)
{
//zb_ret_t zb_err_code;
ret_code_t err_code;
UNUSED_PARAMETER(pvParameter);
NRF_LOG_INFO("The zigbee_main_task started.");
zb_bdb_set_legacy_device_support(1);
/* Start Zigbee Stack. */
err_code = zboss_start_no_autostart();
ZB_ERROR_CHECK(err_code);
while (true){
if (xSemaphoreTakeRecursive(m_zigbee_main_task_mutex, 5) == pdTRUE){
if(ind_reset_network){
ind_reset_network = false;
light_sensor_leave_and_join(0);
}
zboss_main_loop_iteration();
UNUSED_RETURN_VALUE(xSemaphoreGiveRecursive(m_zigbee_main_task_mutex));
}
vTaskDelay(1);
}
}
/**@brief Task function responsible for led blinking
*
* @note This simple functionality could be achieved in other ways with less resources (e.g. by using timers).
* Here it shows just the device has some other activity to perform, not related to zigbee itself
*
* @param pvParameter FreeRTOS task parameter, unused here, required by FreeRTOS API.
*/
static void led_toggle_task(void *pvParameter)
{
UNUSED_PARAMETER(pvParameter);
NRF_LOG_INFO("The led_toggle_task started.");
TickType_t last_led_invert_timestamp;
last_led_invert_timestamp = xTaskGetTickCount();
while (true)
{
bsp_board_led_invert(ZIGBEE_NETWORK_STATE_LED);
vTaskDelayUntil(&last_led_invert_timestamp, (ZB_JOINED() ? 5000U : 200U));
}
}
#if (NRF_LOG_ENABLED && NRF_LOG_DEFERRED)
/**@brief Task function responsible for deferred log processing.
*
* @note It must be running on lower priority than any task generating logs.
*
* @param pvParameter FreeRTOS task parameter, unused here, required by FreeRTOS API.
*/
static void logger_task(void *pvParameter)
{
UNUSED_PARAMETER(pvParameter);
NRF_LOG_INFO("Logger task");
NRF_LOG_FINAL_FLUSH();
while (true)
{
if (!(NRF_LOG_PROCESS()))
{
/* No more logs, let's sleep and wait for any */
vTaskDelay(1);
}
}
}
#endif
/**@brief FreeRTOS hook function called from idle task */
void vApplicationIdleHook(void)
{
/* No task is running, just idle on lowest priority, so we can lower power usage */
__WFE();
}
/**@brief FreeRTOS hook function called when stack overflow has been detected
* @note See FreeRTOS API
*/
void vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName)
{
NRF_LOG_ERROR("vApplicationStackOverflowHook(%x,\"%s\")", xTask, pcTaskName);
NRF_LOG_FINAL_FLUSH();
APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
}
/**@brief Function which tries to sleep down the MCU
*
* @details This function is called from @ref zboss_main_loop_iteration, when there is no more
* messages to process. Because @ref zigbee_main_task is not the only one, implementation found
* in zb_nrf52840_common.c is not appropriate.
*
* @note This function overrides implementation found in zb_nrf52840_common.c
*/
zb_void_t zb_osif_go_idle(zb_void_t)
{
/* Intentionally empty implementation */
}
/**@brief Function for application main entry.
*/
int main(void)
{
ret_code_t error_code;
zb_ieee_addr_t ieee_addr;
/* Initialize logging system and GPIOs. */
log_init();
NRF_LOG_INFO("Application start");
NRF_LOG_FINAL_FLUSH();
clock_init();
timers_init();
board_init();
twi_master_init();
/* Set ZigBee stack logging level and traffic dump subsystem. */
ZB_SET_TRACE_LEVEL(ZIGBEE_TRACE_LEVEL);
ZB_SET_TRACE_MASK(ZIGBEE_TRACE_MASK);
ZB_SET_TRAF_DUMP_OFF();
/* Initialize ZigBee stack. */
ZB_INIT("zigbee_digital_light_sensor");
/* Set device address to the value read from FICR registers. */
zb_osif_get_ieee_eui64(ieee_addr);
zb_set_long_address(ieee_addr);
/* Set static long IEEE address. */
zb_set_network_router_role(IEEE_CHANNEL_MASK);
zb_set_max_children(MAX_CHILDREN);
zigbee_erase_persistent_storage(ERASE_PERSISTENT_CONFIG);
zb_set_keepalive_timeout(ZB_MILLISECONDS_TO_BEACON_INTERVAL(3000));
/* Initialize application context structure. */
UNUSED_RETURN_VALUE(ZB_MEMSET(&m_dev_ctx, 0, sizeof(m_dev_ctx)));
/* Register illuminance sensor device context (endpoints). */
ZB_AF_REGISTER_DEVICE_CTX(&light_sensor_ctx);
/* Initialize sensor device attibutes */
light_sensor_clusters_attr_init();
BaseType_t rtos_result;
#if (NRF_LOG_ENABLED && NRF_LOG_DEFERRED)
rtos_result = xTaskCreate(logger_task, "LOG", LOG_TASK_STACK_SIZE,
NULL, LOG_TASK_PRIORITY, &m_logger_task_handle);
if (rtos_result != pdTRUE)
{
APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
}
#endif
/* Create task for LED0 blinking with priority set to 2 */
rtos_result = xTaskCreate(led_toggle_task, "LED", LED_TOGGLE_TASK_STACK_SIZE,
NULL, LED_TOGGLE_TASK_PRIORITY, &m_led_toggle_task_handle);
if (rtos_result != pdPASS)
{
APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
}
m_zigbee_main_task_mutex = xSemaphoreCreateRecursiveMutex();
if (m_zigbee_main_task_mutex == NULL)
{
APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
}
rtos_result = xTaskCreate(illuminance_measurement_task, "LUX", ILLUMINANCE_MEASUREMENT_TASK_STACK_SIZE,
NULL, ILLUMINANCE_MEASUREMENT_TASK_PRIORITY, &m_illuminance_measurement_task_handle);
if (rtos_result != pdPASS)
{
APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
}
/* Create task where zboss_main_loop_iteration will be called from */
rtos_result = xTaskCreate(zigbee_main_task, "ZB", ZIGBEE_MAIN_TASK_STACK_SIZE,
NULL, ZIGBEE_MAIN_TASK_PRIORITY, &m_zigbee_main_task_handle);
if (rtos_result != pdPASS)
{
APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
}
/* Create Timer for executing button action */
error_code = app_timer_create(&button_timer, APP_TIMER_MODE_REPEATED, button_timer_handler);
APP_ERROR_CHECK(error_code);
/* Start FreeRTOS scheduler. */
NRF_LOG_INFO("Starting FreeRTOS scheduler");
NRF_LOG_FLUSH();
vTaskStartScheduler();
while (true)
{
/* FreeRTOS should not be here... FreeRTOS goes back to the start of stack
* in vTaskStartScheduler function. */
}
}
/**
* @}
*/