├── IMAGES ├── 01.png ├── 03.png ├── 04.png ├── README.md ├── SNZB-02_EFEKTA.jpg ├── photo_2022-09-04_22-57-46.jpg ├── photo_2022-09-04_22-57-47.jpg ├── photo_2022-09-08_18-49-16.jpg └── photo_2022-09-08_19-19-08.jpg ├── PROJECT SOURCE ├── README.md └── TH_SONOFF │ ├── CC2530DB │ ├── GenericApp.ewp │ ├── GenericApp.eww │ └── settings │ │ └── GenericApp.reggroups │ ├── Source │ ├── .DS_Store │ ├── OSAL_App.c │ ├── hal_board_cfg.h │ ├── hdc1080.c │ ├── hdc1080.h │ ├── preinclude.h │ ├── stdint.h │ ├── version.c │ ├── version.h │ ├── zcl_app.c │ ├── zcl_app.h │ └── zcl_app_data.c │ ├── firmwares │ ├── SNZB-02_EFEKTA.hex │ ├── SNZB-02_EFEKTA_H.hex │ └── SONOFF.hex │ ├── jsons2csv.py │ ├── ver.py │ └── zstack-lib │ ├── Debug.c │ ├── Debug.h │ ├── LICENSE │ ├── README.md │ ├── _f8wConfig.cfg │ ├── battery.h │ ├── bettery.c │ ├── commissioning.c │ ├── commissioning.h │ ├── f8wConfig.cfg │ ├── factory_reset.c │ ├── factory_reset.h │ ├── hal_i2c.c │ ├── hal_i2c.h │ ├── hal_key.c │ ├── hal_key.h │ ├── mhz19.c │ ├── mhz19.h │ ├── senseair.c │ ├── senseair.h │ ├── stdint.h │ ├── tl_resetter.c │ ├── tl_resetter.h │ ├── utils.c │ └── utils.h ├── README.md ├── SCHEMATIC ├── README.md └── Schematic_ZB-TH01.pdf └── Z2M CONVERTER ├── README.md ├── SNZB-02_EFEKTA.js └── __SNZB-02_EFEKTA_OLD_VERSION.js /IMAGES/01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/IMAGES/01.png -------------------------------------------------------------------------------- /IMAGES/03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/IMAGES/03.png -------------------------------------------------------------------------------- /IMAGES/04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/IMAGES/04.png -------------------------------------------------------------------------------- /IMAGES/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /IMAGES/SNZB-02_EFEKTA.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/IMAGES/SNZB-02_EFEKTA.jpg -------------------------------------------------------------------------------- /IMAGES/photo_2022-09-04_22-57-46.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/IMAGES/photo_2022-09-04_22-57-46.jpg -------------------------------------------------------------------------------- /IMAGES/photo_2022-09-04_22-57-47.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/IMAGES/photo_2022-09-04_22-57-47.jpg -------------------------------------------------------------------------------- /IMAGES/photo_2022-09-08_18-49-16.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/IMAGES/photo_2022-09-08_18-49-16.jpg -------------------------------------------------------------------------------- /IMAGES/photo_2022-09-08_19-19-08.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/IMAGES/photo_2022-09-08_19-19-08.jpg -------------------------------------------------------------------------------- /PROJECT SOURCE/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/CC2530DB/GenericApp.eww: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $WS_DIR$\GenericApp.ewp 5 | 6 | 7 | 8 | ALL 9 | 10 | GenericApp 11 | DIYRuZ_Flower 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/CC2530DB/settings/GenericApp.reggroups: -------------------------------------------------------------------------------- 1 | group = "io", "P0" 2 | group = "Unnamed2", "P1" 3 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/PROJECT SOURCE/TH_SONOFF/Source/.DS_Store -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/OSAL_App.c: -------------------------------------------------------------------------------- 1 | #include "OSAL.h" 2 | #include "OSAL_Tasks.h" 3 | #include "ZComDef.h" 4 | #include "hal_drivers.h" 5 | 6 | #include "APS.h" 7 | #include "ZDApp.h" 8 | #include "nwk.h" 9 | 10 | #include "bdb_interface.h" 11 | #include "zcl_app.h" 12 | #include "factory_reset.h" 13 | #include "commissioning.h" 14 | #include "Debug.h" 15 | 16 | #if defined ( MT_TASK ) 17 | #include "MT.h" 18 | #include "MT_TASK.h" 19 | #endif 20 | 21 | const pTaskEventHandlerFn tasksArr[] = {macEventLoop, 22 | nwk_event_loop, 23 | Hal_ProcessEvent, 24 | #if defined( MT_TASK ) 25 | MT_ProcessEvent, 26 | #endif 27 | APS_event_loop, 28 | ZDApp_event_loop, 29 | zcl_event_loop, 30 | bdb_event_loop, 31 | zclApp_event_loop, 32 | zclFactoryResetter_loop, 33 | zclCommissioning_event_loop 34 | }; 35 | 36 | const uint8 tasksCnt = sizeof(tasksArr) / sizeof(tasksArr[0]); 37 | uint16 *tasksEvents; 38 | 39 | void osalInitTasks(void) { 40 | DebugInit(); 41 | uint8 taskID = 0; 42 | 43 | tasksEvents = (uint16 *)osal_mem_alloc(sizeof(uint16) * tasksCnt); 44 | osal_memset(tasksEvents, 0, (sizeof(uint16) * tasksCnt)); 45 | macTaskInit(taskID++); 46 | nwk_init(taskID++); 47 | Hal_Init(taskID++); 48 | #if defined( MT_TASK ) 49 | MT_TaskInit( taskID++ ); 50 | #endif 51 | APS_Init(taskID++); 52 | ZDApp_Init(taskID++); 53 | zcl_Init(taskID++); 54 | bdb_Init(taskID++); 55 | zclApp_Init(taskID++); 56 | zclFactoryResetter_Init(taskID++); 57 | zclCommissioning_Init(taskID++); 58 | } 59 | 60 | /********************************************************************* 61 | *********************************************************************/ 62 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/hal_board_cfg.h: -------------------------------------------------------------------------------- 1 | #ifndef HAL_BOARD_CFG_H 2 | #define HAL_BOARD_CFG_H 3 | 4 | 5 | /* ------------------------------------------------------------------------------------------------ 6 | * Includes 7 | * ------------------------------------------------------------------------------------------------ 8 | */ 9 | 10 | #include "hal_mcu.h" 11 | #include "hal_defs.h" 12 | #include "hal_types.h" 13 | 14 | 15 | /* ------------------------------------------------------------------------------------------------ 16 | * CC2590/CC2591 support 17 | * 18 | * Define HAL_PA_LNA_CC2590 if CC2530+CC2590EM is used 19 | * Define HAL_PA_LNA if CC2530+CC2591EM is used 20 | * Note that only one of them can be defined 21 | * ------------------------------------------------------------------------------------------------ 22 | */ 23 | 24 | 25 | 26 | /* ------------------------------------------------------------------------------------------------ 27 | * Clock Speed 28 | * ------------------------------------------------------------------------------------------------ 29 | */ 30 | 31 | #define HAL_CPU_CLOCK_MHZ 32 32 | 33 | /* 32 kHz clock source select in CLKCONCMD */ 34 | #if !defined (OSC32K_CRYSTAL_INSTALLED) || (defined (OSC32K_CRYSTAL_INSTALLED) && (OSC32K_CRYSTAL_INSTALLED == TRUE)) 35 | #define OSC_32KHZ 0x80 /* external 32 KHz xosc */ 36 | #else 37 | #define OSC_32KHZ 0x80 /* internal 32 KHz rcosc */ 38 | #endif 39 | 40 | #define HAL_CLOCK_STABLE() 41 | 42 | /* ------------------------------------------------------------------------------------------------ 43 | * Key Release detect support 44 | * ------------------------------------------------------------------------------------------------ 45 | */ 46 | #define HAL_KEY_CODE_NOKEY 0xff 47 | 48 | 49 | /* ------------------------------------------------------------------------------------------------ 50 | * LED Configuration 51 | * ------------------------------------------------------------------------------------------------ 52 | */ 53 | 54 | // TODO: review all HAL_BOARD_CC2530EB_REV17 and replace with HAL_BOARD_CC2530RC 55 | // if applicable. 56 | #define HAL_NUM_LEDS 0 57 | 58 | #define HAL_LED_BLINK_DELAY() st( { volatile uint32 i; for (i=0; i<0x5800; i++) { }; } ) 59 | #define ACTIVE_LOW ! 60 | #define ACTIVE_HIGH !! /* double negation forces result to be '1' */ 61 | 62 | /* ------------------------------------------------------------------------------------------------ 63 | * OSAL NV implemented by internal flash pages. 64 | * ------------------------------------------------------------------------------------------------ 65 | */ 66 | 67 | // Flash is partitioned into 8 banks of 32 KB or 16 pages. 68 | #define HAL_FLASH_PAGE_PER_BANK 16 69 | // Flash is constructed of 128 pages of 2 KB. 70 | #define HAL_FLASH_PAGE_SIZE 2048 71 | #define HAL_FLASH_WORD_SIZE 4 72 | 73 | // CODE banks get mapped into the XDATA range 8000-FFFF. 74 | #define HAL_FLASH_PAGE_MAP 0x8000 75 | 76 | // The last 16 bytes of the last available page are reserved for flash lock bits. 77 | // NV page definitions must coincide with segment declaration in project *.xcl file. 78 | #if defined NON_BANKED 79 | #define HAL_FLASH_LOCK_BITS 16 80 | #define HAL_NV_PAGE_END 30 81 | #define HAL_NV_PAGE_CNT 2 82 | #else 83 | #define HAL_FLASH_LOCK_BITS 16 84 | #define HAL_NV_PAGE_END 126 85 | #define HAL_NV_PAGE_CNT 6 86 | #endif 87 | 88 | // Re-defining Z_EXTADDR_LEN here so as not to include a Z-Stack .h file. 89 | #define HAL_FLASH_IEEE_SIZE 8 90 | #define HAL_FLASH_IEEE_PAGE (HAL_NV_PAGE_END+1) 91 | #define HAL_FLASH_IEEE_OSET (HAL_FLASH_PAGE_SIZE - HAL_FLASH_LOCK_BITS - HAL_FLASH_IEEE_SIZE) 92 | #define HAL_INFOP_IEEE_OSET 0xC 93 | 94 | #define HAL_FLASH_DEV_PRIVATE_KEY_OSET 0x7D2 95 | #define HAL_FLASH_CA_PUBLIC_KEY_OSET 0x7BC 96 | #define HAL_FLASH_IMPLICIT_CERT_OSET 0x78C 97 | 98 | #define HAL_NV_PAGE_BEG (HAL_NV_PAGE_END-HAL_NV_PAGE_CNT+1) 99 | // Used by DMA macros to shift 1 to create a mask for DMA registers. 100 | #define HAL_NV_DMA_CH 0 101 | #define HAL_DMA_CH_RX 3 102 | #define HAL_DMA_CH_TX 4 103 | 104 | #define HAL_NV_DMA_GET_DESC() HAL_DMA_GET_DESC0() 105 | #define HAL_NV_DMA_SET_ADDR(a) HAL_DMA_SET_ADDR_DESC0((a)) 106 | 107 | /* ------------------------------------------------------------------------------------------------ 108 | * Serial Boot Loader: reserving the first 4 pages of flash and other memory in cc2530-sb.xcl. 109 | * ------------------------------------------------------------------------------------------------ 110 | */ 111 | 112 | #define HAL_SB_IMG_ADDR 0x2000 113 | #define HAL_SB_CRC_ADDR 0x2090 114 | // Size of internal flash less 4 pages for boot loader, 6 pages for NV, & 1 page for lock bits. 115 | #define HAL_SB_IMG_SIZE (0x40000 - 0x2000 - 0x3000 - 0x0800) 116 | 117 | /* ------------------------------------------------------------------------------------------------ 118 | * Macros 119 | * ------------------------------------------------------------------------------------------------ 120 | */ 121 | 122 | /* ----------- RF-frontend Connection Initialization ---------- */ 123 | #ifdef HAL_PA_LNA_CC2592 124 | extern void MAC_RfFrontendSetup(void); 125 | #define HAL_BOARD_RF_FRONTEND_SETUP() MAC_RfFrontendSetup() 126 | #else 127 | #define HAL_BOARD_RF_FRONTEND_SETUP() 128 | #endif 129 | 130 | 131 | /* ------------------------------------------------------------------------------------------------ 132 | * Macros 133 | * ------------------------------------------------------------------------------------------------ 134 | */ 135 | 136 | #define CLKCONCMD_VALUE (CLKCONCMD_32MHZ | OSC_32KHZ) 137 | 138 | /* ----------- Cache Prefetch control ---------- */ 139 | #define PREFETCH_ENABLE() st( FCTL = 0x08; ) 140 | #define PREFETCH_DISABLE() st( FCTL = 0x04; ) 141 | 142 | /* ----------- Board Initialization ---------- */ 143 | 144 | 145 | #ifdef HAL_PA_LNA_CC2592 146 | #define HAL_BOARD_INIT() \ 147 | { \ 148 | uint16 i; \ 149 | \ 150 | SLEEPCMD &= ~OSC_PD; /* turn on 16MHz RC and 32MHz XOSC */ \ 151 | while (!(SLEEPSTA & XOSC_STB)); /* wait for 32MHz XOSC stable */ \ 152 | asm("NOP"); /* chip bug workaround */ \ 153 | for (i=0; i<504; i++) asm("NOP"); /* Require 63us delay for all revs */ \ 154 | CLKCONCMD = (CLKCONCMD_32MHZ | OSC_32KHZ); /* Select 32MHz XOSC and the source for 32K clock */ \ 155 | while (CLKCONSTA != (CLKCONCMD_32MHZ | OSC_32KHZ)); /* Wait for the change to be effective */ \ 156 | SLEEPCMD |= OSC_PD; /* turn off 16MHz RC */ \ 157 | \ 158 | /* Turn on cache prefetch mode */ \ 159 | PREFETCH_ENABLE(); \ 160 | \ 161 | /* set direction for GPIO outputs */ \ 162 | /* For SE2431L PA LNA this sets ANT_SEL to output */ \ 163 | /* For CC2592 this enables LNA */ \ 164 | P1DIR |= BV(0) | BV(1); \ 165 | \ 166 | /* Set PA/LNA HGM control P0_7 */ \ 167 | P0DIR |= BV(7); \ 168 | \ 169 | \ 170 | /* setup RF frontend if necessary */ \ 171 | HAL_BOARD_RF_FRONTEND_SETUP(); \ 172 | HAL_TURN_OFF_LED1(); \ 173 | LED1_DDR |= LED1_BV; \ 174 | LED4_DDR |= LED4_BV; \ 175 | } 176 | #else 177 | #define HAL_BOARD_INIT() \ 178 | { \ 179 | uint16 i; \ 180 | \ 181 | SLEEPCMD &= ~OSC_PD; /* turn on 16MHz RC and 32MHz XOSC */ \ 182 | while (!(SLEEPSTA & XOSC_STB)); /* wait for 32MHz XOSC stable */ \ 183 | asm("NOP"); /* chip bug workaround */ \ 184 | for (i=0; i<504; i++) asm("NOP"); /* Require 63us delay for all revs */ \ 185 | CLKCONCMD = CLKCONCMD_VALUE; /* Select 32MHz XOSC and the source for 32K clock */ \ 186 | while (CLKCONSTA != CLKCONCMD_VALUE); /* Wait for the change to be effective */ \ 187 | SLEEPCMD |= OSC_PD; /* turn off 16MHz RC */ \ 188 | \ 189 | /* Turn on cache prefetch mode */ \ 190 | PREFETCH_ENABLE(); \ 191 | HAL_TURN_OFF_LED1(); \ 192 | LED1_DDR |= LED1_BV; \ 193 | } 194 | #endif 195 | 196 | /* ----------- Debounce ---------- */ 197 | #define HAL_DEBOUNCE(expr) { int i; for (i=0; i<500; i++) { if (!(expr)) i = 0; } } 198 | 199 | /* ----------- Push Buttons ---------- */ 200 | #define HAL_PUSH_BUTTON1() (0) 201 | #define HAL_PUSH_BUTTON2() (0) 202 | #define HAL_PUSH_BUTTON3() (0) 203 | #define HAL_PUSH_BUTTON4() (0) 204 | #define HAL_PUSH_BUTTON5() (0) 205 | #define HAL_PUSH_BUTTON6() (0) 206 | 207 | /* ----------- LED's ---------- */ 208 | 209 | 210 | #define LED1_BV BV(0) 211 | #define LED1_SBIT P1_0 212 | #define LED1_DDR P1DIR 213 | #define LED1_POLARITY ACTIVE_LOW 214 | 215 | 216 | #define HAL_TURN_OFF_LED1() st( LED1_SBIT = LED1_POLARITY (0); ) 217 | #define HAL_TURN_OFF_LED2() asm("NOP") 218 | #define HAL_TURN_OFF_LED3() asm("NOP") 219 | #define HAL_TURN_OFF_LED4() asm("NOP") 220 | 221 | #define HAL_TURN_ON_LED1() st( LED1_SBIT = LED1_POLARITY (1); ) 222 | #define HAL_TURN_ON_LED2() asm("NOP") 223 | #define HAL_TURN_ON_LED3() asm("NOP") 224 | #define HAL_TURN_ON_LED4() asm("NOP") 225 | 226 | #define HAL_TOGGLE_LED1() st( if (LED1_SBIT) { LED1_SBIT = 0; } else { LED1_SBIT = 1;} ) 227 | #define HAL_TOGGLE_LED2() asm("NOP") 228 | #define HAL_TOGGLE_LED3() asm("NOP") 229 | #define HAL_TOGGLE_LED4() asm("NOP") 230 | 231 | #define HAL_STATE_LED1() (LED1_POLARITY (LED1_SBIT)) 232 | #define HAL_STATE_LED2() 0 233 | #define HAL_STATE_LED3() 0 234 | #define HAL_STATE_LED4() 0 235 | 236 | /* ----------- Minimum safe bus voltage ---------- */ 237 | 238 | // Vdd/3 / Internal Reference X ENOB --> (Vdd / 3) / 1.15 X 127 239 | #define VDD_2_0 74 // 2.0 V required to safely read/write internal flash. 240 | #define VDD_2_7 100 // 2.7 V required for the Numonyx device. 241 | 242 | #define VDD_MIN_RUN VDD_2_0 243 | #define VDD_MIN_NV (VDD_2_0+4) // 5% margin over minimum to survive a page erase and compaction. 244 | #define VDD_MIN_GOOD (VDD_2_0+8) // 10% margin over minimum to survive a page erase and compaction. 245 | #define VDD_MIN_XNV (VDD_2_7+5) // 5% margin over minimum to survive a page erase and compaction. 246 | 247 | /* ------------------------------------------------------------------------------------------------ 248 | * Driver Configuration 249 | * ------------------------------------------------------------------------------------------------ 250 | */ 251 | 252 | /* Set to TRUE enable H/W TIMER usage, FALSE disable it */ 253 | #ifndef HAL_TIMER 254 | #define HAL_TIMER FALSE 255 | #endif 256 | 257 | /* Set to TRUE enable ADC usage, FALSE disable it */ 258 | #ifndef HAL_ADC 259 | #define HAL_ADC TRUE 260 | #endif 261 | 262 | /* Set to TRUE enable DMA usage, FALSE disable it */ 263 | #ifndef HAL_DMA 264 | #define HAL_DMA TRUE 265 | #endif 266 | 267 | /* Set to TRUE enable Flash access, FALSE disable it */ 268 | #ifndef HAL_FLASH 269 | #define HAL_FLASH TRUE 270 | #endif 271 | 272 | /* Set to TRUE enable AES usage, FALSE disable it */ 273 | #ifndef HAL_AES 274 | #define HAL_AES TRUE 275 | #endif 276 | 277 | #ifndef HAL_AES_DMA 278 | #define HAL_AES_DMA FALSE 279 | #endif 280 | 281 | /* Set to TRUE enable LCD usage, FALSE disable it */ 282 | #ifndef HAL_LCD 283 | #define HAL_LCD FALSE 284 | #endif 285 | 286 | /* Set to TRUE enable LED usage, FALSE disable it */ 287 | #ifndef HAL_LED 288 | #define HAL_LED FALSE 289 | #endif 290 | #if (!defined BLINK_LEDS) && (HAL_LED == TRUE) 291 | //#define BLINK_LEDS 292 | #endif 293 | 294 | #ifndef HAL_MOTION 295 | #define HAL_MOTION FASLE 296 | #endif 297 | 298 | /* Set to TRUE enable KEY usage, FALSE disable it */ 299 | #ifndef HAL_KEY 300 | #define HAL_KEY TRUE 301 | #endif 302 | 303 | /* Set to TRUE enable UART usage, FALSE disable it */ 304 | #ifndef HAL_UART 305 | #define HAL_UART FALSE 306 | #endif 307 | 308 | #if HAL_UART 309 | #ifndef HAL_UART_DMA 310 | #if HAL_DMA 311 | #if (defined ZAPP_P2) || (defined ZTOOL_P2) 312 | #define HAL_UART_DMA 2 313 | #else 314 | #define HAL_UART_DMA 1 315 | #endif 316 | #else 317 | #define HAL_UART_DMA 0 318 | #endif 319 | #endif 320 | 321 | #ifndef HAL_UART_ISR 322 | #if HAL_UART_DMA // Default preference for DMA over ISR. 323 | #define HAL_UART_ISR 0 324 | #elif (defined ZAPP_P2) || (defined ZTOOL_P2) 325 | #define HAL_UART_ISR 2 326 | #else 327 | #define HAL_UART_ISR 1 328 | #endif 329 | #endif 330 | 331 | #if (HAL_UART_DMA && (HAL_UART_DMA == HAL_UART_ISR)) 332 | #error HAL_UART_DMA & HAL_UART_ISR must be different. 333 | #endif 334 | 335 | // Used to set P2 priority - USART0 over USART1 if both are defined. 336 | #if ((HAL_UART_DMA == 1) || (HAL_UART_ISR == 1)) 337 | #define HAL_UART_PRIPO 0x00 338 | #else 339 | #define HAL_UART_PRIPO 0x40 340 | #endif 341 | 342 | #else 343 | #define HAL_UART_DMA 0 344 | #define HAL_UART_ISR 0 345 | #endif 346 | 347 | /* USB is not used for CC2530 configuration */ 348 | #define HAL_UART_USB 0 349 | 350 | #ifndef HAL_BUZZER 351 | #define HAL_BUZZER TRUE 352 | #endif 353 | 354 | /******************************************************************************************************* 355 | */ 356 | #endif 357 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/hdc1080.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | HDC1080 lightweight sensor driver for CC2530, ** 3 | Written by Andrew Lamchenko aka Berk, ** 4 | LLC EfektaLab, Moscow, Russia, ** 5 | September, 2022. ** 6 | **************************************************************************************************/ 7 | 8 | #include "hdc1080.h" 9 | #include 10 | #include "hal_i2c.h" 11 | 12 | void hdc1080_init(Temp_Reso Temperature_Resolution_x_bit,Humi_Reso Humidity_Resolution_x_bit) 13 | { 14 | uint16_t config_reg_value=0x1000; 15 | uint8_t data_send[2]; 16 | 17 | if(Temperature_Resolution_x_bit == TResolution_11) 18 | { 19 | config_reg_value |= (1<<10); 20 | } 21 | 22 | switch(Humidity_Resolution_x_bit) 23 | { 24 | case HResolution_11: 25 | config_reg_value|= (1<<8); 26 | break; 27 | case HResolution_8: 28 | config_reg_value|= (1<<9); 29 | break; 30 | } 31 | 32 | data_send[0]= (config_reg_value>>8); 33 | data_send[1]= (config_reg_value&0x00ff); 34 | 35 | HalI2CSend(HDC_1080_ADD_WRITE, data_send, 2); 36 | } 37 | 38 | 39 | void hdc1080_start_measurement(void) 40 | { 41 | uint8_t command = Temperature_register_add; 42 | HalI2CSend(HDC_1080_ADD_WRITE, &command, 1); 43 | // Need delay here 15ms for conversion compelete. 44 | } 45 | 46 | 47 | void hdc1080_read_measurement(float* temperature, float* humidity) 48 | { 49 | uint8_t receive_data[4]; 50 | uint16_t temp_x,humi_x; 51 | 52 | HalI2CReceive(HDC_1080_ADD_READ, receive_data, 4); 53 | 54 | temp_x =((receive_data[0]<<8)|receive_data[1]); 55 | humi_x =((receive_data[2]<<8)|receive_data[3]); 56 | 57 | *temperature=((temp_x/65536.0)*165.0)-40.0; 58 | *humidity=((humi_x/65536.0)*100.0); 59 | } 60 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/hdc1080.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************* 2 | HDC1080 lightweight sensor driver for CC2530, ** 3 | Written by Andrew Lamchenko aka Berk, ** 4 | LLC EfektaLab, Moscow, Russia, ** 5 | September, 2022. ** 6 | **************************************************************************************************/ 7 | 8 | #ifndef __HDC1080_H 9 | #define __HDC1080_H 10 | 11 | #define HDC_1080_ADD 0x40 12 | #define HDC_1080_ADD_READ (HDC_1080_ADD << 1) | 0x01 13 | #define HDC_1080_ADD_WRITE (HDC_1080_ADD << 1) | 0x00 14 | #define Configuration_register_add 0x02 15 | #define Temperature_register_add 0x00 16 | #define Humidity_register_add 0x01 17 | 18 | 19 | typedef enum 20 | { 21 | TResolution_14 = 0, 22 | TResolution_11 = 1 23 | }Temp_Reso; 24 | 25 | typedef enum 26 | { 27 | HResolution_14 = 0, 28 | HResolution_11 = 1, 29 | HResolution_8 =2 30 | }Humi_Reso; 31 | 32 | void hdc1080_init(Temp_Reso Temperature_Resolution_x_bit,Humi_Reso Humidity_Resolution_x_bit); 33 | void hdc1080_start_measurement(void); 34 | void hdc1080_read_measurement(float* temperature, float* humidity); 35 | #endif 36 | 37 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/preinclude.h: -------------------------------------------------------------------------------- 1 | #define TC_LINKKEY_JOIN 2 | #define NV_INIT 3 | #define NV_RESTORE 4 | #define ZCL_ON_OFF 5 | #define TP2_LEGACY_ZC 6 | #define NWK_AUTO_POLL 7 | #define MULTICAST_ENABLED FALSE 8 | #define ZCL_READ 9 | #define ZCL_WRITE 10 | #define ZCL_BASIC 11 | #define ZCL_IDENTIFY 12 | #define ZCL_REPORTING_DEVICE 13 | #define ZSTACK_DEVICE_BUILD (DEVICE_BUILD_ENDDEVICE) 14 | #define DISABLE_GREENPOWER_BASIC_PROXY 15 | #define BDB_FINDING_BINDING_CAPABILITY_ENABLED 1 16 | #define BDB_REPORTING TRUE 17 | #define BDB_MAX_CLUSTERENDPOINTS_REPORTING 10 18 | 19 | #define ISR_KEYINTERRUPT 20 | #define HAL_BUZZER FALSE 21 | #define HAL_LCD FALSE 22 | #define HAL_LED TRUE 23 | #define HAL_I2C TRUE 24 | #define BLINK_LEDS TRUE 25 | 26 | //i2c 27 | #define OCM_CLK_PORT 1 28 | #define OCM_DATA_PORT 1 29 | #define OCM_CLK_PIN 6 30 | #define OCM_DATA_PIN 7 31 | #define HAL_I2C_RETRY_CNT 1 32 | 33 | #define POWER_SAVING 34 | 35 | // #define DO_DEBUG_UART 36 | 37 | #ifdef DO_DEBUG_UART 38 | #define HAL_UART TRUE 39 | #define HAL_UART_DMA 1 40 | #define INT_HEAP_LEN (2685 - 0x4B - 0xBB) 41 | #endif 42 | 43 | #define HAL_KEY_P2_INPUT_PINS BV(0) 44 | 45 | #include "hal_board_cfg.h" 46 | #include "stdint.h" 47 | #include "stddef.h" -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/stdint.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _STDINT 3 | #define _STDINT 4 | 5 | #ifndef int8_t 6 | #define int8_t int8 7 | #endif 8 | #ifndef int16_t 9 | #define int16_t int16 10 | #endif 11 | #ifndef int32_t 12 | #define int32_t int32 13 | #endif 14 | #ifndef int64_t 15 | #define int64_t int64 16 | #endif 17 | #ifndef uint8_t 18 | #define uint8_t uint8 19 | #endif 20 | #ifndef uint16_t 21 | #define uint16_t uint16 22 | #endif 23 | #ifndef uint32_t 24 | #define uint32_t uint32 25 | #endif 26 | 27 | 28 | #define S8_C(x) x 29 | #define U8_C(x) x 30 | #define S16_C(x) x 31 | #define U16_C(x) x 32 | #define S32_C(x) x 33 | #define U32_C(x) x 34 | #define S64_C(x) x 35 | #define U64_C(x) x 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/version.c: -------------------------------------------------------------------------------- 1 | 2 | #ifndef ZCL_APP_VERSION_H 3 | #define ZCL_APP_VERSION_H 4 | 5 | #ifdef __cplusplus 6 | extern "C" { 7 | #endif 8 | 9 | #include "version.h" 10 | const uint8 zclApp_DateCode[] = { 16, '0', '6', '/', '0', '9', '/', '2', '0', '2', '2', ' ', '1', '0', ':', '0', '4' }; 11 | const char zclApp_DateCodeNT[] = "06/09/2022 10:04"; 12 | 13 | #ifdef __cplusplus 14 | } 15 | #endif 16 | 17 | #endif /* ZCL_APP_VERSION_H */ 18 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/version.h: -------------------------------------------------------------------------------- 1 | extern const uint8 zclApp_DateCode[]; 2 | extern const char zclApp_DateCodeNT[]; -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/zcl_app.c: -------------------------------------------------------------------------------- 1 | #include "AF.h" 2 | #include "OSAL.h" 3 | #include "OSAL_Clock.h" 4 | #include "OSAL_PwrMgr.h" 5 | #include "ZComDef.h" 6 | #include "ZDApp.h" 7 | #include "ZDNwkMgr.h" 8 | #include "ZDObject.h" 9 | #include "math.h" 10 | 11 | #include "nwk_util.h" 12 | #include "zcl.h" 13 | #include "zcl_app.h" 14 | #include "zcl_diagnostic.h" 15 | #include "zcl_general.h" 16 | #include "zcl_ms.h" 17 | 18 | #include "bdb.h" 19 | #include "bdb_interface.h" 20 | #include "gp_interface.h" 21 | 22 | #include "Debug.h" 23 | #include "OnBoard.h" 24 | 25 | #include 26 | #include 27 | 28 | #include "hal_adc.h" 29 | #include "hal_drivers.h" 30 | #include "hal_key.h" 31 | #include "hal_led.h" 32 | 33 | #include "hal_i2c.h" 34 | 35 | #include "battery.h" 36 | #include "commissioning.h" 37 | #include "factory_reset.h" 38 | #include "utils.h" 39 | #include "version.h" 40 | 41 | #include "hdc1080.h" 42 | 43 | 44 | #define HAL_KEY_CODE_RELEASE_KEY HAL_KEY_CODE_NOKEY 45 | 46 | #define HAL_KEY_CODE_RELEASE_KEY HAL_KEY_CODE_NOKEY 47 | 48 | extern bool requestNewTrustCenterLinkKey; 49 | byte zclApp_TaskID; 50 | bool initOut = false; 51 | int16 sendInitReportCount = 0; 52 | static uint8 currentSensorsReadingPhase = 0; 53 | static uint8 currentConfigRepPhase = 0; 54 | int16 temp_old = 0; 55 | int16 temp_tr = 10; 56 | int16 humi_old = 0; 57 | int16 humi_tr = 25; 58 | int16 startWork = 0; 59 | bool pushBut = false; 60 | 61 | afAddrType_t inderect_DstAddr = {.addrMode = (afAddrMode_t)AddrNotPresent, .endPoint = 0, .addr.shortAddr = 0}; 62 | 63 | static void zclApp_BasicResetCB(void); 64 | static void zclApp_RestoreAttributesFromNV(void); 65 | static void zclApp_SaveAttributesToNV(void); 66 | static ZStatus_t zclApp_ReadWriteAuthCB(afAddrType_t *srcAddr, zclAttrRec_t *pAttr, uint8 oper); 67 | static void zclApp_HandleKeys(byte shift, byte keys); 68 | static void zclApp_Report(void); 69 | static void zclApp_ReadSensors(void); 70 | static void zclApp_TempHumiSens(void); 71 | static void zclSendTemp(int16 temp); 72 | static void zclSendHum(uint16 hum); 73 | static void zclApp_SendTemp(void); 74 | static void zclApp_SendHum(void); 75 | static void zclSendTemp(int16 temp); 76 | static void zclSendHum(uint16 hum); 77 | static void zclApp_SendRepTime(void); 78 | static void zclApp_ConfigTemp(void); 79 | static void zclApp_ConfigHum(void); 80 | static void zclSendRT(void); 81 | static void zclSendCTTr(void); 82 | static void zclSendCHTr(void); 83 | 84 | static zclGeneral_AppCallbacks_t zclApp_CmdCallbacks = { 85 | zclApp_BasicResetCB, 86 | NULL, 87 | NULL, 88 | NULL, 89 | NULL, 90 | NULL, 91 | NULL, 92 | NULL 93 | }; 94 | 95 | void zclApp_Init(byte task_id) { 96 | requestNewTrustCenterLinkKey = FALSE; 97 | zclApp_RestoreAttributesFromNV(); 98 | zclApp_TaskID = task_id; 99 | bdb_RegisterSimpleDescriptor(&zclApp_FirstEP); 100 | zclGeneral_RegisterCmdCallbacks(zclApp_FirstEP.EndPoint, &zclApp_CmdCallbacks); 101 | zcl_registerAttrList(zclApp_FirstEP.EndPoint, zclApp_AttrsFirstEPCount, zclApp_AttrsFirstEP); 102 | zcl_registerReadWriteCB(zclApp_FirstEP.EndPoint, NULL, zclApp_ReadWriteAuthCB); 103 | zcl_registerForMsg(zclApp_TaskID); 104 | RegisterForKeys(zclApp_TaskID); 105 | 106 | IO_PUD_PORT(OCM_CLK_PORT, IO_PUP); 107 | IO_PUD_PORT(OCM_DATA_PORT, IO_PUP) 108 | HalI2CInit(); 109 | hdc1080_init(TResolution_14,HResolution_14); 110 | 111 | //LREP("Started build %s \r\n", zclApp_DateCodeNT); 112 | zclApp_ReadSensors(); 113 | 114 | osal_start_timerEx(zclApp_TaskID, APP_REPORT_EVT, 10000); 115 | osal_start_reload_timer(zclApp_TaskID, APP_REPORT_BEVT, 7200000); 116 | } 117 | 118 | uint16 zclApp_event_loop(uint8 task_id, uint16 events) { 119 | afIncomingMSGPacket_t *MSGpkt; 120 | 121 | (void)task_id; 122 | if (events & SYS_EVENT_MSG) { 123 | while ((MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive(zclApp_TaskID))) { 124 | switch (MSGpkt->hdr.event) { 125 | case KEY_CHANGE: 126 | zclApp_HandleKeys(((keyChange_t *)MSGpkt)->state, ((keyChange_t *)MSGpkt)->keys); 127 | break; 128 | case ZCL_INCOMING_MSG: 129 | if (((zclIncomingMsg_t *)MSGpkt)->attrCmd) { 130 | osal_mem_free(((zclIncomingMsg_t *)MSGpkt)->attrCmd); 131 | } 132 | break; 133 | 134 | default: 135 | break; 136 | } 137 | osal_msg_deallocate((uint8 *)MSGpkt); 138 | } 139 | return (events ^ SYS_EVENT_MSG); 140 | } 141 | 142 | if (events & APP_REPORT_EVT) { 143 | LREPMaster("APP_REPORT_EVT\r\n"); 144 | if (initOut == false){ 145 | sendInitReportCount++; 146 | if(sendInitReportCount >= 5){ 147 | osal_stop_timerEx(zclApp_TaskID, APP_REPORT_EVT); 148 | osal_clear_event(zclApp_TaskID, APP_REPORT_EVT); 149 | osal_start_timerEx(zclApp_TaskID, APP_REPORT_EVT, zclApp_Config.ReportDelay*60000); 150 | initOut = true; 151 | }else{ 152 | osal_stop_timerEx(zclApp_TaskID, APP_REPORT_EVT); 153 | osal_clear_event(zclApp_TaskID, APP_REPORT_EVT); 154 | osal_start_timerEx(zclApp_TaskID, APP_REPORT_EVT, 10000); 155 | } 156 | pushBut = true; 157 | zclApp_Report(); 158 | }else{ 159 | osal_stop_timerEx(zclApp_TaskID, APP_REPORT_EVT); 160 | osal_clear_event(zclApp_TaskID, APP_REPORT_EVT); 161 | osal_start_timerEx(zclApp_TaskID, APP_REPORT_EVT, zclApp_Config.ReportDelay*60000); 162 | zclApp_Report(); 163 | } 164 | return (events ^ APP_REPORT_EVT); 165 | } 166 | 167 | if (events & APP_READ_SENSORS_EVT) { 168 | LREPMaster("APP_READ_SENSORS_EVT\r\n"); 169 | zclApp_ReadSensors(); 170 | return (events ^ APP_READ_SENSORS_EVT); 171 | } 172 | 173 | if (events & APP_REPORT_BEVT) { 174 | //LREPMaster("APP_REPORT_BEVT\r\n"); 175 | zclBattery_Report(); 176 | zclApp_SendRepTime(); 177 | return (events ^ APP_REPORT_BEVT); 178 | } 179 | if (events & APP_REPORT_CEVT) { 180 | //LREPMaster("APP_REPORT_CEVT\r\n"); 181 | zclApp_SendRepTime(); 182 | return (events ^APP_REPORT_CEVT); 183 | } 184 | 185 | if (events & APP_SAVE_ATTRS_EVT) { 186 | //LREPMaster("APP_SAVE_ATTRS_EVT\r\n"); 187 | zclApp_SaveAttributesToNV(); 188 | return (events ^ APP_SAVE_ATTRS_EVT); 189 | } 190 | return 0; 191 | } 192 | 193 | static void zclApp_HandleKeys(byte portAndAction, byte keyCode) { 194 | LREP("zclApp_HandleKeys portAndAction=0x%X keyCode=0x%X\r\n", portAndAction, keyCode); 195 | 196 | zclFactoryResetter_HandleKeys(portAndAction, keyCode); 197 | zclCommissioning_HandleKeys(portAndAction, keyCode); 198 | 199 | if (portAndAction & HAL_KEY_RELEASE) { 200 | LREPMaster("Key press\r\n"); 201 | pushBut = true; 202 | zclApp_Report(); 203 | osal_start_timerEx(zclApp_TaskID, APP_REPORT_CEVT, 200); 204 | } 205 | 206 | } 207 | 208 | 209 | static void zclApp_BasicResetCB(void) { 210 | zclApp_ResetAttributesToDefaultValues(); 211 | zclApp_SaveAttributesToNV(); 212 | } 213 | 214 | static ZStatus_t zclApp_ReadWriteAuthCB(afAddrType_t *srcAddr, zclAttrRec_t *pAttr, uint8 oper) { 215 | 216 | osal_start_timerEx(zclApp_TaskID, APP_SAVE_ATTRS_EVT, 2000); 217 | return ZSuccess; 218 | } 219 | 220 | static void zclApp_SaveAttributesToNV(void) { 221 | uint8 writeStatus = osal_nv_write(NW_APP_CONFIG, 0, sizeof(application_config_t), &zclApp_Config); 222 | } 223 | 224 | static void zclApp_RestoreAttributesFromNV(void) { 225 | 226 | uint8 status = osal_nv_item_init(NW_APP_CONFIG, sizeof(application_config_t), NULL); 227 | if (status == NV_ITEM_UNINIT) { 228 | uint8 writeStatus = osal_nv_write(NW_APP_CONFIG, 0, sizeof(application_config_t), &zclApp_Config); 229 | } 230 | if (status == ZSUCCESS) { 231 | osal_nv_read(NW_APP_CONFIG, 0, sizeof(application_config_t), &zclApp_Config); 232 | } 233 | } 234 | 235 | 236 | 237 | static void zclApp_ReadSensors(void) { 238 | LREP("currentSensorsReadingPhase %d\r\n", currentSensorsReadingPhase); 239 | 240 | switch (currentSensorsReadingPhase++) { 241 | 242 | case 0: 243 | hdc1080_start_measurement(); 244 | 245 | break; 246 | 247 | case 1: 248 | zclApp_TempHumiSens(); 249 | 250 | break; 251 | 252 | case 2: 253 | zclApp_SendTemp(); 254 | 255 | break; 256 | 257 | case 3: 258 | zclApp_SendHum(); 259 | 260 | break; 261 | 262 | case 4: 263 | if(zclApp_Config.EnableTemp == 1){ 264 | zclApp_ConfigTemp(); 265 | } 266 | if(zclApp_Config.EnableHum == 1){ 267 | zclApp_ConfigHum(); 268 | } 269 | break; 270 | 271 | case 5: 272 | if(!pushBut){ 273 | if(startWork <= 10){ 274 | startWork++; 275 | zclBattery_Report(); 276 | osal_start_timerEx(zclApp_TaskID, APP_REPORT_CEVT, 250); 277 | } 278 | }else{ 279 | zclBattery_Report(); 280 | osal_start_timerEx(zclApp_TaskID, APP_REPORT_CEVT, 250); 281 | } 282 | break; 283 | 284 | default: 285 | currentSensorsReadingPhase = 0; 286 | if(pushBut == true){ 287 | pushBut = false; 288 | } 289 | HalLedSet(HAL_LED_1, HAL_LED_MODE_BLINK); 290 | osal_pwrmgr_task_state(zclApp_TaskID, PWRMGR_CONSERVE); 291 | break; 292 | } 293 | if (currentSensorsReadingPhase != 0) { 294 | 295 | osal_start_timerEx(zclApp_TaskID, APP_READ_SENSORS_EVT, 30); 296 | } 297 | } 298 | 299 | 300 | static void zclApp_TempHumiSens(void) { 301 | 302 | float t = 0.0; 303 | float h = 0.0; 304 | hdc1080_read_measurement(&t, &h); 305 | zclApp_Temperature_Sensor_MeasuredValue = (int16)(t*100); 306 | zclApp_HumiditySensor_MeasuredValue = (uint16)(h*100); 307 | } 308 | 309 | 310 | static void _delay_us(uint16 microSecs) { 311 | while (microSecs--) { 312 | asm("NOP"); 313 | asm("NOP"); 314 | asm("NOP"); 315 | asm("NOP"); 316 | asm("NOP"); 317 | asm("NOP"); 318 | asm("NOP"); 319 | asm("NOP"); 320 | } 321 | } 322 | 323 | void user_delay_ms(uint32_t period) { _delay_us(1000 * period); } 324 | 325 | static void zclApp_Report(void) { 326 | osal_start_timerEx(zclApp_TaskID, APP_READ_SENSORS_EVT, 100); 327 | } 328 | 329 | 330 | static void zclApp_SendTemp(void){ 331 | if(!pushBut){ 332 | if (abs(zclApp_Temperature_Sensor_MeasuredValue - temp_old) >= temp_tr) { 333 | temp_old = zclApp_Temperature_Sensor_MeasuredValue; 334 | //LREP("ReadIntTempSens t=%d\r\n", zclApp_Temperature_Sensor_MeasuredValue); 335 | //bdb_RepChangedAttrValue(zclApp_FirstEP.EndPoint, TEMP, ATTRID_MS_TEMPERATURE_MEASURED_VALUE); 336 | zclSendTemp(zclApp_Temperature_Sensor_MeasuredValue); 337 | } 338 | } 339 | } 340 | 341 | 342 | static void zclApp_SendHum(void){ 343 | if(!pushBut){ 344 | if (abs(zclApp_HumiditySensor_MeasuredValue - humi_old) >= humi_tr*10) { 345 | humi_old = zclApp_HumiditySensor_MeasuredValue; 346 | //LREP("ReadIntTempSens t=%d\r\n", zclApp_HumiditySensor_MeasuredValue); 347 | //bdb_RepChangedAttrValue(zclApp_FirstEP.EndPoint, HUMIDITY, ATTRID_MS_RELATIVE_HUMIDITY_MEASURED_VALUE); 348 | zclSendHum(zclApp_HumiditySensor_MeasuredValue); 349 | } 350 | } 351 | } 352 | 353 | 354 | static void zclSendTemp(int16 temp) { 355 | 356 | const uint8 NUM_ATTRIBUTES = 1; 357 | zclReportCmd_t *pReportCmd; 358 | pReportCmd = osal_mem_alloc(sizeof(zclReportCmd_t) + (NUM_ATTRIBUTES * sizeof(zclReport_t))); 359 | if (pReportCmd != NULL) { 360 | pReportCmd->numAttr = NUM_ATTRIBUTES; 361 | pReportCmd->attrList[0].attrID = ATTRID_MS_TEMPERATURE_MEASURED_VALUE; 362 | pReportCmd->attrList[0].dataType = ZCL_DATATYPE_INT16; 363 | pReportCmd->attrList[0].attrData = (void *)(&temp); 364 | zcl_SendReportCmd(zclApp_FirstEP.EndPoint, &inderect_DstAddr, TEMP, pReportCmd, ZCL_FRAME_CLIENT_SERVER_DIR, false, bdb_getZCLFrameCounter()); 365 | } 366 | osal_mem_free(pReportCmd); 367 | } 368 | 369 | static void zclSendHum(uint16 hum) { 370 | 371 | const uint8 NUM_ATTRIBUTES = 1; 372 | zclReportCmd_t *pReportCmd; 373 | pReportCmd = osal_mem_alloc(sizeof(zclReportCmd_t) + (NUM_ATTRIBUTES * sizeof(zclReport_t))); 374 | if (pReportCmd != NULL) { 375 | pReportCmd->numAttr = NUM_ATTRIBUTES; 376 | pReportCmd->attrList[0].attrID = ATTRID_MS_RELATIVE_HUMIDITY_MEASURED_VALUE; 377 | pReportCmd->attrList[0].dataType = ZCL_DATATYPE_UINT16; 378 | pReportCmd->attrList[0].attrData = (void *)(&hum); 379 | zcl_SendReportCmd(zclApp_FirstEP.EndPoint, &inderect_DstAddr, HUMIDITY, pReportCmd, ZCL_FRAME_CLIENT_SERVER_DIR, false, bdb_getZCLFrameCounter()); 380 | } 381 | osal_mem_free(pReportCmd); 382 | } 383 | 384 | 385 | static void zclApp_SendRepTime(void){ 386 | 387 | switch (currentConfigRepPhase++) { 388 | 389 | case 0: 390 | zclSendRT(); 391 | break; 392 | 393 | case 1: 394 | zclSendCTTr(); 395 | break; 396 | 397 | case 2: 398 | zclSendCHTr(); 399 | break; 400 | 401 | default: 402 | currentConfigRepPhase = 0; 403 | HalLedSet(HAL_LED_1, HAL_LED_MODE_BLINK); 404 | osal_pwrmgr_task_state(zclApp_TaskID, PWRMGR_CONSERVE); 405 | break; 406 | } 407 | if (currentConfigRepPhase != 0) { 408 | osal_start_timerEx(zclApp_TaskID, APP_REPORT_CEVT, 50); 409 | } 410 | } 411 | 412 | 413 | static void zclApp_ConfigTemp(void){ 414 | if(zclApp_Temperature_Sensor_MeasuredValue >= zclApp_Config.HighTemp*100){ 415 | zclGeneral_SendOnOff_CmdOff(zclApp_FirstEP.EndPoint, &inderect_DstAddr, TRUE, bdb_getZCLFrameCounter()); 416 | }else if(zclApp_Temperature_Sensor_MeasuredValue <= zclApp_Config.LowTemp*100){ 417 | zclGeneral_SendOnOff_CmdOn(zclApp_FirstEP.EndPoint, &inderect_DstAddr, TRUE, bdb_getZCLFrameCounter()); 418 | } 419 | } 420 | 421 | 422 | static void zclApp_ConfigHum(void){ 423 | if(zclApp_Config.EnableHum == 1){ 424 | if(zclApp_HumiditySensor_MeasuredValue >= zclApp_Config.HighHum*100){ 425 | zclGeneral_SendOnOff_CmdOn(zclApp_FirstEP.EndPoint, &inderect_DstAddr, TRUE, bdb_getZCLFrameCounter()); 426 | }else if(zclApp_HumiditySensor_MeasuredValue <= zclApp_Config.HighHum*100){ 427 | zclGeneral_SendOnOff_CmdOff(zclApp_FirstEP.EndPoint, &inderect_DstAddr, TRUE, bdb_getZCLFrameCounter()); 428 | } 429 | } 430 | } 431 | 432 | 433 | static void zclSendRT(void) { 434 | 435 | const uint8 NUM_ATTRIBUTES = 1; 436 | zclReportCmd_t *pReportCmd; 437 | pReportCmd = osal_mem_alloc(sizeof(zclReportCmd_t) + (NUM_ATTRIBUTES * sizeof(zclReport_t))); 438 | if (pReportCmd != NULL) { 439 | pReportCmd->numAttr = NUM_ATTRIBUTES; 440 | pReportCmd->attrList[0].attrID = ATTRID_ReportDelay; 441 | pReportCmd->attrList[0].dataType = ZCL_DATATYPE_UINT16; 442 | pReportCmd->attrList[0].attrData = (void *)(&zclApp_Config.ReportDelay); 443 | zcl_SendReportCmd(zclApp_FirstEP.EndPoint, &inderect_DstAddr, POWER_CFG, pReportCmd, ZCL_FRAME_CLIENT_SERVER_DIR, false, bdb_getZCLFrameCounter()); 444 | } 445 | osal_mem_free(pReportCmd); 446 | } 447 | 448 | 449 | static void zclSendCTTr(void) { 450 | 451 | const uint8 NUM_ATTRIBUTES = 4; 452 | zclReportCmd_t *pReportCmd; 453 | pReportCmd = osal_mem_alloc(sizeof(zclReportCmd_t) + (NUM_ATTRIBUTES * sizeof(zclReport_t))); 454 | if (pReportCmd != NULL) { 455 | pReportCmd->numAttr = NUM_ATTRIBUTES; 456 | pReportCmd->attrList[0].attrID = ATTRID_MS_TEMPERATURE_MEASURED_VALUE; 457 | pReportCmd->attrList[0].dataType = ZCL_DATATYPE_INT16; 458 | pReportCmd->attrList[0].attrData = (void *)(&zclApp_Temperature_Sensor_MeasuredValue); 459 | 460 | pReportCmd->attrList[1].attrID = ATTRID_ENABLE_TEMP; 461 | pReportCmd->attrList[1].dataType = ZCL_DATATYPE_BOOLEAN; 462 | pReportCmd->attrList[1].attrData = (void *)(&zclApp_Config.EnableTemp); 463 | 464 | pReportCmd->attrList[2].attrID = ATTRID_SET_HIGHTEMP; 465 | pReportCmd->attrList[2].dataType = ZCL_INT16; 466 | pReportCmd->attrList[2].attrData = (void *)(&zclApp_Config.HighTemp); 467 | 468 | pReportCmd->attrList[3].attrID = ATTRID_SET_LOWTEMP; 469 | pReportCmd->attrList[3].dataType = ZCL_INT16; 470 | pReportCmd->attrList[3].attrData = (void *)(&zclApp_Config.LowTemp); 471 | 472 | zcl_SendReportCmd(zclApp_FirstEP.EndPoint, &inderect_DstAddr, TEMP, pReportCmd, ZCL_FRAME_CLIENT_SERVER_DIR, false, bdb_getZCLFrameCounter()); 473 | } 474 | osal_mem_free(pReportCmd); 475 | } 476 | 477 | 478 | static void zclSendCHTr(void) { 479 | 480 | const uint8 NUM_ATTRIBUTES = 4; 481 | zclReportCmd_t *pReportCmd; 482 | pReportCmd = osal_mem_alloc(sizeof(zclReportCmd_t) + (NUM_ATTRIBUTES * sizeof(zclReport_t))); 483 | if (pReportCmd != NULL) { 484 | pReportCmd->numAttr = NUM_ATTRIBUTES; 485 | pReportCmd->attrList[0].attrID = ATTRID_MS_RELATIVE_HUMIDITY_MEASURED_VALUE; 486 | pReportCmd->attrList[0].dataType = ZCL_DATATYPE_UINT16; 487 | pReportCmd->attrList[0].attrData = (void *)(&zclApp_HumiditySensor_MeasuredValue); 488 | 489 | pReportCmd->attrList[1].attrID = ATTRID_ENABLE_HUM; 490 | pReportCmd->attrList[1].dataType = ZCL_DATATYPE_BOOLEAN; 491 | pReportCmd->attrList[1].attrData = (void *)(&zclApp_Config.EnableHum); 492 | 493 | pReportCmd->attrList[2].attrID = ATTRID_SET_HIGHHUM; 494 | pReportCmd->attrList[2].dataType = ZCL_UINT16; 495 | pReportCmd->attrList[2].attrData = (void *)(&zclApp_Config.HighHum); 496 | 497 | pReportCmd->attrList[3].attrID = ATTRID_SET_LOWHUM; 498 | pReportCmd->attrList[3].dataType = ZCL_UINT16; 499 | pReportCmd->attrList[3].attrData = (void *)(&zclApp_Config.LowHum); 500 | 501 | zcl_SendReportCmd(zclApp_FirstEP.EndPoint, &inderect_DstAddr, HUMIDITY, pReportCmd, ZCL_FRAME_CLIENT_SERVER_DIR, false, bdb_getZCLFrameCounter()); 502 | } 503 | osal_mem_free(pReportCmd); 504 | zclSendHum(zclApp_HumiditySensor_MeasuredValue); 505 | } -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/zcl_app.h: -------------------------------------------------------------------------------- 1 | #ifndef ZCL_APP_H 2 | #define ZCL_APP_H 3 | 4 | #ifdef __cplusplus 5 | extern "C" { 6 | #endif 7 | 8 | #include "version.h" 9 | #include "zcl.h" 10 | 11 | #define APP_REPORT_EVT 0x0001 12 | #define APP_READ_SENSORS_EVT 0x0002 13 | #define APP_SAVE_ATTRS_EVT 0x0004 14 | #define APP_REPORT_BEVT 0x0008 15 | #define APP_REPORT_CEVT 0x0020 16 | 17 | #define NW_APP_CONFIG 0x0402 18 | 19 | #define R ACCESS_CONTROL_READ 20 | #define RW (R | ACCESS_CONTROL_WRITE | ACCESS_CONTROL_AUTH_WRITE) 21 | #define RR (R | ACCESS_REPORTABLE) 22 | #define RRW (R | ACCESS_REPORTABLE | ACCESS_CONTROL_WRITE | ACCESS_CONTROL_AUTH_WRITE) 23 | 24 | #define BASIC ZCL_CLUSTER_ID_GEN_BASIC 25 | #define POWER_CFG ZCL_CLUSTER_ID_GEN_POWER_CFG 26 | #define ONOFF ZCL_CLUSTER_ID_GEN_ON_OFF 27 | #define TEMP ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT 28 | #define HUMIDITY ZCL_CLUSTER_ID_MS_RELATIVE_HUMIDITY 29 | 30 | #define ATTRID_ReportDelay 0x0201 31 | #define ATTRID_SET_HIGHTEMP 0x0202 32 | #define ATTRID_SET_LOWTEMP 0x0203 33 | #define ATTRID_SET_HIGHHUM 0x0204 34 | #define ATTRID_SET_LOWHUM 0x0205 35 | #define ATTRID_ENABLE_TEMP 0x0206 36 | #define ATTRID_ENABLE_HUM 0x0207 37 | 38 | #define ZCL_UINT8 ZCL_DATATYPE_UINT8 39 | #define ZCL_UINT16 ZCL_DATATYPE_UINT16 40 | #define ZCL_INT16 ZCL_DATATYPE_INT16 41 | #define ZCL_INT8 ZCL_DATATYPE_INT8 42 | #define ZCL_INT32 ZCL_DATATYPE_INT32 43 | #define ZCL_UINT32 ZCL_DATATYPE_UINT32 44 | #define ZCL_SINGLE ZCL_DATATYPE_SINGLE_PREC 45 | 46 | typedef struct { 47 | int16 HighTemp; 48 | int16 LowTemp; 49 | uint16 HighHum; 50 | uint16 LowHum; 51 | uint16 EnableTemp; 52 | uint16 EnableHum; 53 | uint16 ReportDelay; 54 | } application_config_t; 55 | 56 | extern SimpleDescriptionFormat_t zclApp_FirstEP; 57 | 58 | extern uint8 zclApp_BatteryVoltage; 59 | extern uint8 zclApp_BatteryPercentageRemainig; 60 | extern uint16 zclApp_BatteryVoltageRawAdc; 61 | extern int16 zclApp_Temperature_Sensor_MeasuredValue; 62 | extern uint16 zclApp_HumiditySensor_MeasuredValue; 63 | 64 | extern CONST zclAttrRec_t zclApp_AttrsFirstEP[]; 65 | extern CONST uint8 zclApp_AttrsFirstEPCount; 66 | extern application_config_t zclApp_Config; 67 | 68 | extern const uint8 zclApp_ManufacturerName[]; 69 | extern const uint8 zclApp_ModelId[]; 70 | extern const uint8 zclApp_PowerSource; 71 | 72 | extern void zclApp_Init(byte task_id); 73 | 74 | extern UINT16 zclApp_event_loop(byte task_id, UINT16 events); 75 | extern void zclApp_ResetAttributesToDefaultValues(void); 76 | void user_delay_ms(uint32_t period); 77 | 78 | #ifdef __cplusplus 79 | } 80 | #endif 81 | 82 | #endif /* ZCL_APP_H */ 83 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/Source/zcl_app_data.c: -------------------------------------------------------------------------------- 1 | #include "AF.h" 2 | #include "OSAL.h" 3 | #include "ZComDef.h" 4 | #include "ZDConfig.h" 5 | #include "zcl.h" 6 | #include "zcl_general.h" 7 | #include "zcl_ms.h" 8 | #include "zcl_ha.h" 9 | #include "zcl_app.h" 10 | #include "battery.h" 11 | #include "version.h" 12 | 13 | #define APP_DEVICE_VERSION 2 14 | #define APP_FLAGS 0 15 | #define APP_HWVERSION 1 16 | #define APP_ZCLVERSION 1 17 | 18 | #define DEFAULT_SET_HIGH_TEMP 0 19 | #define DEFAULT_SET_LOW_TEMP 0 20 | #define DEFAULT_SET_HIGH_HUM 0 21 | #define DEFAULT_SET_LOW_HUM 0 22 | #define DEFAULT_ENABLE_TEMP FALSE 23 | #define DEFAULT_ENABLE_HUM FALSE 24 | #define APP_REPORT_DELAY 5 25 | 26 | const uint16 zclApp_clusterRevision_all = 0x0001; 27 | 28 | int16 zclApp_Temperature_Sensor_MeasuredValue = 0; 29 | uint16 zclApp_HumiditySensor_MeasuredValue = 0; 30 | 31 | const uint8 zclApp_HWRevision = APP_HWVERSION; 32 | const uint8 zclApp_ZCLVersion = APP_ZCLVERSION; 33 | const uint8 zclApp_ApplicationVersion = 3; 34 | const uint8 zclApp_StackVersion = 4; 35 | 36 | const uint8 zclApp_ManufacturerName[] = {13, 'e', 'f', 'e', 'k', 't', 'a', 'l', 'a', 'b', '.', 'c', 'o', 'm'}; 37 | 38 | const uint8 zclApp_ModelId[] = {14, 'S', 'N', 'Z', 'B', '-', '0', '2', '_', 'E', 'F', 'E', 'K', 'T', 'A'}; 39 | 40 | const uint8 zclApp_PowerSource = POWER_SOURCE_BATTERY; 41 | 42 | application_config_t zclApp_Config = { 43 | .HighTemp = DEFAULT_SET_HIGH_TEMP, 44 | .LowTemp = DEFAULT_SET_LOW_TEMP, 45 | .HighHum = DEFAULT_SET_HIGH_HUM, 46 | .LowHum = DEFAULT_SET_LOW_HUM, 47 | .EnableTemp = DEFAULT_ENABLE_TEMP, 48 | .EnableHum = DEFAULT_ENABLE_HUM, 49 | .ReportDelay = APP_REPORT_DELAY 50 | }; 51 | 52 | CONST zclAttrRec_t zclApp_AttrsFirstEP[] = { 53 | {BASIC, {ATTRID_BASIC_ZCL_VERSION, ZCL_UINT8, R, (void *)&zclApp_ZCLVersion}}, 54 | {BASIC, {ATTRID_BASIC_APPL_VERSION, ZCL_UINT8, R, (void *)&zclApp_ApplicationVersion}}, 55 | {BASIC, {ATTRID_BASIC_STACK_VERSION, ZCL_UINT8, R, (void *)&zclApp_StackVersion}}, 56 | {BASIC, {ATTRID_BASIC_HW_VERSION, ZCL_UINT8, R, (void *)&zclApp_HWRevision}}, 57 | {BASIC, {ATTRID_BASIC_MANUFACTURER_NAME, ZCL_DATATYPE_CHAR_STR, R, (void *)zclApp_ManufacturerName}}, 58 | {BASIC, {ATTRID_BASIC_MODEL_ID, ZCL_DATATYPE_CHAR_STR, R, (void *)zclApp_ModelId}}, 59 | {BASIC, {ATTRID_BASIC_DATE_CODE, ZCL_DATATYPE_CHAR_STR, R, (void *)zclApp_DateCode}}, 60 | {BASIC, {ATTRID_BASIC_POWER_SOURCE, ZCL_DATATYPE_ENUM8, R, (void *)&zclApp_PowerSource}}, 61 | {BASIC, {ATTRID_BASIC_SW_BUILD_ID, ZCL_DATATYPE_CHAR_STR, R, (void *)zclApp_DateCode}}, 62 | {BASIC, {ATTRID_CLUSTER_REVISION, ZCL_DATATYPE_UINT16, R, (void *)&zclApp_clusterRevision_all}}, 63 | {POWER_CFG, {ATTRID_POWER_CFG_BATTERY_VOLTAGE, ZCL_UINT8, RR, (void *)&zclBattery_Voltage}}, 64 | {POWER_CFG, {ATTRID_POWER_CFG_BATTERY_PERCENTAGE_REMAINING, ZCL_UINT8, RR, (void *)&zclBattery_PercentageRemainig}}, 65 | {POWER_CFG, {ATTRID_POWER_CFG_BATTERY_VOLTAGE_RAW_ADC, ZCL_UINT16, RR, (void *)&zclBattery_RawAdc}}, 66 | {POWER_CFG, {ATTRID_ReportDelay, ZCL_UINT16, RW, (void *)&zclApp_Config.ReportDelay}}, 67 | {TEMP, {ATTRID_MS_TEMPERATURE_MEASURED_VALUE, ZCL_INT16, R, (void *)&zclApp_Temperature_Sensor_MeasuredValue}}, 68 | {TEMP, {ATTRID_SET_HIGHTEMP, ZCL_INT16, RW, (void *)&zclApp_Config.HighTemp}}, 69 | {TEMP, {ATTRID_SET_LOWTEMP, ZCL_INT16, RW, (void *)&zclApp_Config.LowTemp}}, 70 | {TEMP, {ATTRID_ENABLE_TEMP, ZCL_DATATYPE_BOOLEAN, RW, (void *)&zclApp_Config.EnableTemp}}, 71 | {HUMIDITY, {ATTRID_MS_RELATIVE_HUMIDITY_MEASURED_VALUE, ZCL_UINT16, R, (void *)&zclApp_HumiditySensor_MeasuredValue}}, 72 | {HUMIDITY, {ATTRID_SET_HIGHHUM, ZCL_UINT16, RW, (void *)&zclApp_Config.HighHum}}, 73 | {HUMIDITY, {ATTRID_SET_LOWHUM, ZCL_UINT16, RW, (void *)&zclApp_Config.LowHum}}, 74 | {HUMIDITY, {ATTRID_ENABLE_HUM, ZCL_DATATYPE_BOOLEAN, RW, (void *)&zclApp_Config.EnableHum}} 75 | }; 76 | 77 | uint8 CONST zclApp_AttrsFirstEPCount = (sizeof(zclApp_AttrsFirstEP) / sizeof(zclApp_AttrsFirstEP[0])); 78 | 79 | const cId_t zclApp_InClusterList[] = {ZCL_CLUSTER_ID_GEN_BASIC, POWER_CFG, TEMP, HUMIDITY}; 80 | 81 | #define APP_MAX_INCLUSTERS (sizeof(zclApp_InClusterList) / sizeof(zclApp_InClusterList[0])) 82 | 83 | const cId_t zclApp_OutClusterListFirstEP[] = {ONOFF, TEMP, HUMIDITY}; 84 | 85 | #define APP_MAX_OUTCLUSTERS_FIRST_EP (sizeof(zclApp_OutClusterListFirstEP) / sizeof(zclApp_OutClusterListFirstEP[0])) 86 | 87 | SimpleDescriptionFormat_t zclApp_FirstEP = { 88 | 1, 89 | ZCL_HA_PROFILE_ID, 90 | ZCL_HA_DEVICEID_SIMPLE_SENSOR, 91 | APP_DEVICE_VERSION, 92 | APP_FLAGS, 93 | APP_MAX_INCLUSTERS, 94 | (cId_t *)zclApp_InClusterList, 95 | APP_MAX_OUTCLUSTERS_FIRST_EP, 96 | (cId_t *)zclApp_OutClusterListFirstEP 97 | }; 98 | 99 | void zclApp_ResetAttributesToDefaultValues(void) { 100 | zclApp_Config.HighTemp = DEFAULT_SET_HIGH_TEMP; 101 | zclApp_Config.LowTemp = DEFAULT_SET_LOW_TEMP; 102 | zclApp_Config.HighHum = DEFAULT_SET_HIGH_HUM; 103 | zclApp_Config.LowHum = DEFAULT_SET_LOW_HUM; 104 | zclApp_Config.EnableTemp = DEFAULT_ENABLE_TEMP; 105 | zclApp_Config.EnableHum = DEFAULT_ENABLE_HUM; 106 | zclApp_Config.ReportDelay = APP_REPORT_DELAY; 107 | } -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/jsons2csv.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import json 4 | import csv 5 | 6 | intput_file = sys.argv[1] 7 | output_file = sys.argv[2] 8 | 9 | with open(intput_file) as fp: 10 | with open(output_file, 'w', newline='') as csvfile: 11 | fieldnames = ['raw_battery_adc_2', 'raw_humidity_adc_2'] 12 | writer = csv.DictWriter(csvfile, fieldnames=fieldnames) 13 | writer.writeheader() 14 | 15 | for line in fp: 16 | record = json.loads(line) 17 | writer.writerow({'raw_battery_adc_2': record['raw_battery_adc_2'], 'raw_humidity_adc_2': record['raw_humidity_adc_2']}) 18 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/ver.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from os.path import dirname, join 3 | cwd = dirname(__file__) 4 | now = datetime.now() 5 | dt_string = now.strftime("%d/%m/%Y %H:%M") 6 | print("date and time =", dt_string) 7 | with open(join(cwd, './Source/version.c'), 'w') as f: 8 | chars = ["'{0}'".format(char) for char in dt_string] 9 | f.write(""" 10 | #ifndef ZCL_APP_VERSION_H 11 | #define ZCL_APP_VERSION_H 12 | 13 | #ifdef __cplusplus 14 | extern "C" { 15 | #endif 16 | 17 | """ 18 | ) 19 | f.write('#include "version.h"\n') 20 | code = """const uint8 zclApp_DateCode[] = {{ {0}, {1} }};\n""".format(len(chars), ', '.join(chars)) 21 | f.write(code) 22 | code = """const char zclApp_DateCodeNT[] = \"{0}\";\n""".format(dt_string) 23 | f.write(code) 24 | f.write(""" 25 | #ifdef __cplusplus 26 | } 27 | #endif 28 | 29 | #endif /* ZCL_APP_VERSION_H */ 30 | """) -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/Debug.c: -------------------------------------------------------------------------------- 1 | #include "Debug.h" 2 | #include "DebugTrace.h" 3 | #include "MT.h" 4 | #include "OSAL.h" 5 | #include "OSAL_Memory.h" 6 | 7 | 8 | void vprint(const char *fmt, va_list argp) { 9 | uint8 string[100]; 10 | if (0 < vsprintf((char *)string, fmt, argp)) // build string 11 | { 12 | LREPMaster(string); 13 | } 14 | } 15 | 16 | #ifdef DO_DEBUG_UART 17 | #define UART_PORT HAL_UART_PORT_0 18 | bool DebugInit() { 19 | halUARTCfg_t halUARTConfig; 20 | halUARTConfig.configured = TRUE; 21 | halUARTConfig.baudRate = HAL_UART_BR_115200; 22 | halUARTConfig.flowControl = FALSE; 23 | halUARTConfig.flowControlThreshold = 48; // this parameter indicates number of bytes left before Rx Buffer 24 | // reaches maxRxBufSize 25 | halUARTConfig.idleTimeout = 10; // this parameter indicates rx timeout period in millisecond 26 | halUARTConfig.rx.maxBufSize = 0; 27 | halUARTConfig.tx.maxBufSize = BUFFLEN; 28 | halUARTConfig.intEnable = TRUE; 29 | halUARTConfig.callBackFunc = NULL; 30 | HalUARTInit(); 31 | if (HalUARTOpen(UART_PORT, &halUARTConfig) == HAL_UART_SUCCESS) { 32 | LREPMaster("Initialized debug module \r\n"); 33 | return true; 34 | } 35 | return false; 36 | } 37 | 38 | void LREPMaster(uint8 *data) { 39 | if (data == NULL) { 40 | return; 41 | } 42 | HalUARTWrite(UART_PORT, data, osal_strlen((char *)data)); 43 | } 44 | 45 | void LREP(char *format, ...) { 46 | va_list argp; 47 | va_start(argp, format); 48 | vprint(format, argp); 49 | va_end(argp); 50 | } 51 | #elif defined(DO_DEBUG_MT) 52 | 53 | bool DebugInit() { 54 | debugThreshold = 0x04; // increase threshold as soon as we initialize debug module 55 | LREPMaster("Initialized debug module \r\n"); 56 | return TRUE; 57 | } 58 | void LREP(char *format, ...) { 59 | 60 | va_list argp; 61 | va_start(argp, format); 62 | vprint(format, argp); 63 | va_end(argp); 64 | } 65 | void LREPMaster(uint8 *data) { debug_str(data); } 66 | #else 67 | bool DebugInit() {return true;}; 68 | void LREP(char *format, ...) { 69 | va_list argp; 70 | va_start(argp, format); 71 | printf(format, argp); 72 | va_end(argp); 73 | }; 74 | void LREPMaster(uint8 *data) { 75 | printf((const char*)data); 76 | }; 77 | #endif 78 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/Debug.h: -------------------------------------------------------------------------------- 1 | #ifndef _DEBUG_H 2 | #define _DEBUG_H 3 | 4 | #include "hal_types.h" 5 | #include "hal_uart.h" 6 | #include 7 | #include 8 | #include 9 | 10 | #define BUFFLEN 128 11 | #define BUFFER 100 12 | 13 | #define PRINT_NUMBER_TYPE long 14 | 15 | #define PAD_RIGHT 1 16 | #define PAD_ZERO 2 17 | 18 | #define PRINT_BUF_LEN 12 19 | 20 | #define PRINT_IMMEDIATE_PRINT 0 21 | 22 | 23 | #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" 24 | #define BYTE_TO_BINARY(byte) \ 25 | (byte & 0x80 ? '1' : '0'), \ 26 | (byte & 0x40 ? '1' : '0'), \ 27 | (byte & 0x20 ? '1' : '0'), \ 28 | (byte & 0x10 ? '1' : '0'), \ 29 | (byte & 0x08 ? '1' : '0'), \ 30 | (byte & 0x04 ? '1' : '0'), \ 31 | (byte & 0x02 ? '1' : '0'), \ 32 | (byte & 0x01 ? '1' : '0') 33 | 34 | extern halUARTCfg_t halUARTConfig; 35 | 36 | void vprint(const char *fmt, va_list argp); 37 | extern bool DebugInit(void); 38 | extern void LREP(char *format, ...); 39 | extern void LREPMaster(uint8 *data); 40 | #endif -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/README.md: -------------------------------------------------------------------------------- 1 | # Collection of reusable componets for Z-stack 3.0.2 -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/_f8wConfig.cfg: -------------------------------------------------------------------------------- 1 | /* 2 | * f8wConfig.cfg 3 | * 4 | * Compiler command-line options used to define a TI Z-Stack ZigBee device. 5 | * To move an option from here to the project file, comment out or delete the 6 | * option from this file and enter it into the "Define Symbols" box under the 7 | * Preprocessor tab of the C/C++ Compiler Project Options. New user defined 8 | * options may be added to this file, as necessary. 9 | * 10 | * Each macro is prefixed with '-D'. The entries are to be constructed as if 11 | * they are to be on the compiler command line invocation (which they are). 12 | * 13 | * NOTE: The RHS (Right-Hand-Side) must be quoted if there are embedded blanks. 14 | * See the DEFAULT_KEY definition for an example. 15 | */ 16 | 17 | /* Enable ZigBee-Pro */ 18 | -DZIGBEEPRO 19 | 20 | /* Set to 1 to enable security. To disable set to 0 */ 21 | -DSECURE=1 22 | -DZG_SECURE_DYNAMIC=0 23 | 24 | /* Enable the Reflector */ 25 | -DREFLECTOR 26 | 27 | /* Default channel is Channel 11 - 0x0B */ 28 | // Channels are defined in the following: 29 | // 0 : 868 MHz 0x00000001 30 | // 1 - 10 : 915 MHz 0x000007FE 31 | // 11 - 26 : 2.4 GHz 0x07FFF800 32 | // 33 | //-DMAX_CHANNELS_868MHZ 0x00000001 34 | //-DMAX_CHANNELS_915MHZ 0x000007FE 35 | //-DMAX_CHANNELS_24GHZ 0x07FFF800 36 | //-DDEFAULT_CHANLIST=0x04000000 // 26 - 0x1A 37 | //-DDEFAULT_CHANLIST=0x02000000 // 25 - 0x19 38 | //-DDEFAULT_CHANLIST=0x01000000 // 24 - 0x18 39 | //-DDEFAULT_CHANLIST=0x00800000 // 23 - 0x17 40 | //-DDEFAULT_CHANLIST=0x00400000 // 22 - 0x16 41 | //-DDEFAULT_CHANLIST=0x00200000 // 21 - 0x15 42 | //-DDEFAULT_CHANLIST=0x00100000 // 20 - 0x14 43 | //-DDEFAULT_CHANLIST=0x00080000 // 19 - 0x13 44 | //-DDEFAULT_CHANLIST=0x00040000 // 18 - 0x12 45 | //-DDEFAULT_CHANLIST=0x00020000 // 17 - 0x11 46 | //-DDEFAULT_CHANLIST=0x00010000 // 16 - 0x10 47 | //-DDEFAULT_CHANLIST=0x00008000 // 15 - 0x0F 48 | //-DDEFAULT_CHANLIST=0x00004000 // 14 - 0x0E 49 | //-DDEFAULT_CHANLIST=0x00002000 // 13 - 0x0D 50 | //-DDEFAULT_CHANLIST=0x00001000 // 12 - 0x0C 51 | -DDEFAULT_CHANLIST=0x00000800 // 11 - 0x0B 52 | 53 | /* Define the default PAN ID. 54 | * 55 | * Setting this to a value other than 0xFFFF causes 56 | * ZDO_COORD to use this value as its PAN ID and 57 | * Routers and end devices to join PAN with this ID 58 | */ 59 | -DZDAPP_CONFIG_PAN_ID=0xFFFF 60 | 61 | /* Minimum number of milliseconds to hold off the start of the device 62 | * in the network and the minimum delay between joining cycles. 63 | */ 64 | -DNWK_START_DELAY=100 65 | 66 | /* Mask for the random joining delay. This value is masked with 67 | * the return from osal_rand() to get a random delay time for 68 | * each joining cycle. This random value is added to NWK_START_DELAY. 69 | * For example, a value of 0x007F will be a joining delay of 0 to 127 70 | * milliseconds. 71 | */ 72 | -DEXTENDED_JOINING_RANDOM_MASK=0x007F 73 | 74 | /* Minimum number of milliseconds to delay between each beacon request 75 | * in a joining cycle. 76 | */ 77 | -DBEACON_REQUEST_DELAY=100 78 | 79 | /* Mask for the random beacon request delay. This value is masked with the 80 | * return from osal_rand() to get a random delay time for each joining cycle. 81 | * This random value is added to DBEACON_REQUEST_DELAY. For example, a value 82 | * of 0x00FF will be a beacon request delay of 0 to 255 milliseconds. 83 | */ 84 | -DBEACON_REQ_DELAY_MASK=0x00FF 85 | 86 | /* Jitter mask for the link status report timer. This value is masked with the 87 | * return from osal_rand() to add a random delay to _NIB.nwkLinkStatusPeriod. 88 | * For example, a value of 0x007F allows a jitter between 0-127 milliseconds. 89 | */ 90 | -DLINK_STATUS_JITTER_MASK=0x007F 91 | 92 | /* in seconds; set to 0 to turn off route expiry */ 93 | -DROUTE_EXPIRY_TIME=30 94 | 95 | /* This number is used by polled devices, since the spec'd formula 96 | * doesn't work for sleeping end devices. For non-polled devices, 97 | * a formula is used. Value is in 2 milliseconds periods 98 | */ 99 | -DAPSC_ACK_WAIT_DURATION_POLLED=3000 100 | 101 | /* Default indirect message holding timeout value: 102 | * 1-65535 (0 -> 65536) X CNT_RTG_TIMER X RTG_TIMER_INTERVAL 103 | */ 104 | -DNWK_INDIRECT_MSG_TIMEOUT=7 105 | 106 | /* The number of simultaneous route discoveries in network */ 107 | -DMAX_RREQ_ENTRIES=8 108 | 109 | /* The maximum number of retries allowed after a transmission failure */ 110 | -DAPSC_MAX_FRAME_RETRIES=3 111 | 112 | /* Max number of times retry looking for the next hop address of a message */ 113 | -DNWK_MAX_DATA_RETRIES=2 114 | 115 | /* Number of times retry to poll parent before indicating loss of synchronization 116 | * with parent. Note that larger value will cause longer delay for the child to 117 | * rejoin the network. 118 | */ 119 | -DMAX_POLL_FAILURE_RETRIES=2 120 | 121 | /* The number of items in the broadcast table */ 122 | -DMAX_BCAST=9 123 | 124 | /* The maximum number of groups in the groups table */ 125 | -DAPS_MAX_GROUPS=16 126 | 127 | /* Number of entries in the regular routing table plus additional 128 | * entries for route repair 129 | */ 130 | -DMAX_RTG_ENTRIES=40 131 | 132 | /* Maximum number of entries in the Binding table. */ 133 | -DNWK_MAX_BINDING_ENTRIES=4 134 | 135 | /* Maximum number of cluster IDs for each binding table entry. 136 | * Note that any value other than the default value may cause a 137 | * compilation warning but Device Binding will function correctly. 138 | */ 139 | -DMAX_BINDING_CLUSTER_IDS=4 140 | 141 | /* Default security key. */ 142 | -DDEFAULT_KEY="{0}" 143 | 144 | /* Reset when ASSERT occurs, otherwise flash LEDs */ 145 | //-DASSERT_RESET 146 | 147 | /* Set the MAC MAX Frame Size (802.15.4 default is 102) */ 148 | -DMAC_MAX_FRAME_SIZE=116 149 | 150 | /* Minimum transmissions attempted for Channel Interference detection, 151 | * Frequency Agility can be disabled by setting this parameter to zero. 152 | */ 153 | -DZDNWKMGR_MIN_TRANSMISSIONS=20 154 | 155 | /* Compiler keywords */ 156 | -DCONST="const __code" 157 | -DGENERIC=__generic 158 | 159 | /**************************************** 160 | * The following are for End Devices only 161 | ***************************************/ 162 | 163 | -DRFD_RCVC_ALWAYS_ON=FALSE 164 | 165 | /* The number of milliseconds to wait between data request polls to the coordinator. */ 166 | -DPOLL_RATE=1000 167 | 168 | /* This is used after receiving a data indication to poll immediately 169 | * for queued messages...in milliseconds. 170 | */ 171 | -DQUEUED_POLL_RATE=100 172 | 173 | /* This is used after receiving a data confirmation to poll immediately 174 | * for response messages...in milliseconds 175 | */ 176 | -DRESPONSE_POLL_RATE=100 177 | 178 | /* This is used as an alternate response poll rate only for rejoin request. 179 | * This rate is determined by the response time of the parent that the device 180 | * is trying to join. 181 | */ 182 | -DREJOIN_POLL_RATE=440 183 | 184 | /* Rejoin retry backoff silent period timer duration in milliseconds - default 15 minutes according to HA test spec */ 185 | -DREJOIN_BACKOFF=900000 186 | 187 | /* Rejoin retry backoff scan timer duration in milliseconds - default 15 minutes according to HA test spec */ 188 | -DREJOIN_SCAN=900000 189 | 190 | /* Latest sample apps use LED4 and do not use S1 switch */ 191 | -DENABLE_LED4_DISABLE_S1 192 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/battery.h: -------------------------------------------------------------------------------- 1 | #ifndef _BATTERY_H 2 | #define _BATTERY_H 3 | //This is custom attribute 4 | #define ATTRID_POWER_CFG_BATTERY_VOLTAGE_RAW_ADC 0x0200 5 | 6 | 7 | extern uint8 zclBattery_Voltage; 8 | extern uint8 zclBattery_PercentageRemainig; 9 | extern uint16 zclBattery_RawAdc; 10 | 11 | 12 | extern uint16 getBatteryVoltage(void); 13 | extern uint8 getBatteryVoltageZCL(uint16 millivolts); 14 | extern uint8 getBatteryRemainingPercentageZCL(uint16 millivolts); 15 | extern uint8 getBatteryRemainingPercentageZCLCR2032(uint16 volt16); 16 | 17 | extern void zclBattery_Init(uint8 task_id); 18 | extern uint16 zclBattery_event_loop(uint8 task_id, uint16 events); 19 | extern void zclBattery_HandleKeys(uint8 portAndAction, uint8 keyCode); 20 | extern void zclBattery_Report(void); 21 | #endif -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/bettery.c: -------------------------------------------------------------------------------- 1 | #include "Debug.h" 2 | #include "battery.h" 3 | #include "hal_adc.h" 4 | #include "utils.h" 5 | #include "OSAL.h" 6 | #include "zcl.h" 7 | #include "zcl_general.h" 8 | #include "bdb_interface.h" 9 | // (( 3 * 1.15 ) / (( 2^14 / 2 ) - 1 )) * 1000 (not correct) 10 | // #define MULTI (float) 0.4211939934 11 | // this coefficient calculated using 12 | // https://docs.google.com/spreadsheets/d/1qrFdMTo0ZrqtlGUoafeB3hplhU3GzDnVWuUK4M9OgNo/edit?usp=sharing 13 | #define MULTI (float)0.443 14 | 15 | #define VOLTAGE_MIN 2.0 16 | 17 | #define VOLTAGE_MAX 3.3 18 | 19 | #ifndef ZCL_BATTERY_REPORT_INTERVAL 20 | #define ZCL_BATTERY_REPORT_INTERVAL ((uint32) 1800000) //30 minutes 21 | #endif 22 | 23 | #ifndef ZCL_BATTERY_REPORT_DELAY 24 | #define ZCL_BATTERY_REPORT_DELAY 5 * 1000 25 | #endif 26 | 27 | #ifndef ZCL_BATTERY_REPORT_REPORT_CONVERTER 28 | #define ZCL_BATTERY_REPORT_REPORT_CONVERTER(millivolts) getBatteryRemainingPercentageZCLCR2032(millivolts) 29 | #endif 30 | 31 | #define POWER_CFG ZCL_CLUSTER_ID_GEN_POWER_CFG 32 | 33 | #define ZCL_BATTERY_REPORT_EVT 0x0001 34 | 35 | 36 | uint8 zclBattery_Voltage = 0xff; 37 | uint8 zclBattery_PercentageRemainig = 0xff; 38 | uint16 zclBattery_RawAdc = 0xff; 39 | 40 | uint8 getBatteryVoltageZCL(uint16 millivolts) { 41 | uint8 volt8 = (uint8)(millivolts / 100); 42 | if ((millivolts - (volt8 * 100)) > 50) { 43 | return volt8 + 1; 44 | } else { 45 | return volt8; 46 | } 47 | } 48 | // return millivolts 49 | uint16 getBatteryVoltage(void) { 50 | HalAdcSetReference(HAL_ADC_REF_125V); 51 | zclBattery_RawAdc = adcReadSampled(HAL_ADC_CHANNEL_VDD, HAL_ADC_RESOLUTION_14, HAL_ADC_REF_125V, 10); 52 | return (uint16)(zclBattery_RawAdc * MULTI); 53 | } 54 | 55 | uint8 getBatteryRemainingPercentageZCL(uint16 millivolts) { return (uint8)mapRange(VOLTAGE_MIN, VOLTAGE_MAX, 0.0, 200.0, millivolts); } 56 | 57 | uint8 getBatteryRemainingPercentageZCLCR2032(uint16 volt16) { 58 | float battery_level; 59 | if (volt16 >= 3000) { 60 | battery_level = 100; 61 | } else if (volt16 > 2900) { 62 | battery_level = 100 - ((3000 - volt16) * 58) / 100; 63 | } else if (volt16 > 2740) { 64 | battery_level = 42 - ((2900 - volt16) * 24) / 160; 65 | } else if (volt16 > 2440) { 66 | battery_level = 18 - ((2740 - volt16) * 12) / 300; 67 | } else if (volt16 > 2100) { 68 | battery_level = 6 - ((2440 - volt16) * 6) / 340; 69 | } else { 70 | battery_level = 0; 71 | } 72 | return (uint8)(battery_level * 2); 73 | } 74 | 75 | void zclBattery_Report(void) { 76 | uint16 millivolts = getBatteryVoltage(); 77 | zclBattery_Voltage = getBatteryVoltageZCL(millivolts); 78 | zclBattery_PercentageRemainig = ZCL_BATTERY_REPORT_REPORT_CONVERTER(millivolts); 79 | LREP("Battery voltageZCL=%d prc=%d voltage=%d\r\n", zclBattery_Voltage, zclBattery_PercentageRemainig, millivolts); 80 | #if BDB_REPORTING 81 | bdb_RepChangedAttrValue(1, POWER_CFG, ATTRID_POWER_CFG_BATTERY_PERCENTAGE_REMAINING); 82 | #else 83 | const uint8 NUM_ATTRIBUTES = 3; 84 | zclReportCmd_t *pReportCmd; 85 | pReportCmd = osal_mem_alloc(sizeof(zclReportCmd_t) + (NUM_ATTRIBUTES * sizeof(zclReport_t))); 86 | if (pReportCmd != NULL) { 87 | pReportCmd->numAttr = NUM_ATTRIBUTES; 88 | 89 | pReportCmd->attrList[0].attrID = ATTRID_POWER_CFG_BATTERY_VOLTAGE; 90 | pReportCmd->attrList[0].dataType = ZCL_DATATYPE_UINT8; 91 | pReportCmd->attrList[0].attrData = (void *)(&zclBattery_Voltage); 92 | 93 | pReportCmd->attrList[1].attrID = ATTRID_POWER_CFG_BATTERY_PERCENTAGE_REMAINING; 94 | pReportCmd->attrList[1].dataType = ZCL_DATATYPE_UINT8; 95 | pReportCmd->attrList[1].attrData = (void *)(&zclBattery_PercentageRemainig); 96 | 97 | pReportCmd->attrList[2].attrID = ATTRID_POWER_CFG_BATTERY_VOLTAGE_RAW_ADC; 98 | pReportCmd->attrList[2].dataType = ZCL_DATATYPE_UINT16; 99 | pReportCmd->attrList[2].attrData = (void *)(&zclBattery_RawAdc); 100 | 101 | afAddrType_t inderect_DstAddr = {.addrMode = (afAddrMode_t)AddrNotPresent, .endPoint = 0, .addr.shortAddr = 0}; 102 | zcl_SendReportCmd(1, &inderect_DstAddr, POWER_CFG, pReportCmd, ZCL_FRAME_CLIENT_SERVER_DIR, TRUE, bdb_getZCLFrameCounter()); 103 | } 104 | osal_mem_free(pReportCmd); 105 | #endif 106 | } 107 | 108 | uint8 zclBattery_TaskId = 0; 109 | 110 | void zclBattery_Init(uint8 task_id) { 111 | zclBattery_TaskId = task_id; 112 | #if BDB_REPORTING 113 | osal_start_reload_timer(zclBattery_TaskId, ZCL_BATTERY_REPORT_EVT, ZCL_BATTERY_REPORT_INTERVAL); 114 | #endif 115 | } 116 | 117 | uint16 zclBattery_event_loop(uint8 task_id, uint16 events) { 118 | LREP("zclBattery_event_loop 0x%X\r\n", events); 119 | if (events & ZCL_BATTERY_REPORT_EVT) { 120 | LREPMaster("ZCL_BATTERY_REPORT_EVT\r\n"); 121 | zclBattery_Report(); 122 | return (events ^ ZCL_BATTERY_REPORT_EVT); 123 | } 124 | return 0; 125 | } 126 | 127 | void zclBattery_HandleKeys(uint8 portAndAction, uint8 keyCode) { 128 | osal_start_timerEx(zclBattery_TaskId, ZCL_BATTERY_REPORT_EVT, ZCL_BATTERY_REPORT_DELAY); 129 | } -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/commissioning.c: -------------------------------------------------------------------------------- 1 | #include "commissioning.h" 2 | #include "Debug.h" 3 | #include "OSAL_PwrMgr.h" 4 | #include "ZDApp.h" 5 | #include "bdb_interface.h" 6 | #include "hal_key.h" 7 | #include "hal_led.h" 8 | 9 | static void zclCommissioning_ProcessCommissioningStatus(bdbCommissioningModeMsg_t *bdbCommissioningModeMsg); 10 | static void zclCommissioning_ResetBackoffRetry(void); 11 | static void zclCommissioning_BindNotification(bdbBindNotificationData_t *data); 12 | extern bool requestNewTrustCenterLinkKey; 13 | 14 | byte rejoinsLeft = APP_COMMISSIONING_END_DEVICE_REJOIN_TRIES; 15 | uint32 rejoinDelay = APP_COMMISSIONING_END_DEVICE_REJOIN_START_DELAY; 16 | 17 | uint8 zclCommissioning_TaskId = 0; 18 | 19 | #ifndef APP_TX_POWER 20 | #define APP_TX_POWER TX_PWR_PLUS_4 21 | #endif 22 | 23 | void zclCommissioning_Init(uint8 task_id) { 24 | zclCommissioning_TaskId = task_id; 25 | 26 | bdb_RegisterCommissioningStatusCB(zclCommissioning_ProcessCommissioningStatus); 27 | bdb_RegisterBindNotificationCB(zclCommissioning_BindNotification); 28 | 29 | ZMacSetTransmitPower(APP_TX_POWER); 30 | 31 | // this is important to allow connects throught routers 32 | // to make this work, coordinator should be compiled with this flag #define TP2_LEGACY_ZC 33 | requestNewTrustCenterLinkKey = FALSE; 34 | bdb_StartCommissioning(BDB_COMMISSIONING_MODE_NWK_STEERING | BDB_COMMISSIONING_MODE_FINDING_BINDING); 35 | } 36 | 37 | static void zclCommissioning_ResetBackoffRetry(void) { 38 | rejoinsLeft = APP_COMMISSIONING_END_DEVICE_REJOIN_TRIES; 39 | rejoinDelay = APP_COMMISSIONING_END_DEVICE_REJOIN_START_DELAY; 40 | } 41 | 42 | static void zclCommissioning_OnConnect(void) { 43 | LREPMaster("zclCommissioning_OnConnect \r\n"); 44 | zclCommissioning_ResetBackoffRetry(); 45 | osal_start_timerEx(zclCommissioning_TaskId, APP_COMMISSIONING_CLOCK_DOWN_POLING_RATE_EVT, 10 * 1000); 46 | } 47 | 48 | static void zclCommissioning_ProcessCommissioningStatus(bdbCommissioningModeMsg_t *bdbCommissioningModeMsg) { 49 | LREP("bdbCommissioningMode=%d bdbCommissioningStatus=%d bdbRemainingCommissioningModes=0x%X\r\n", 50 | bdbCommissioningModeMsg->bdbCommissioningMode, bdbCommissioningModeMsg->bdbCommissioningStatus, 51 | bdbCommissioningModeMsg->bdbRemainingCommissioningModes); 52 | switch (bdbCommissioningModeMsg->bdbCommissioningMode) { 53 | case BDB_COMMISSIONING_INITIALIZATION: 54 | switch (bdbCommissioningModeMsg->bdbCommissioningStatus) { 55 | case BDB_COMMISSIONING_NO_NETWORK: 56 | LREP("No network\r\n"); 57 | HalLedBlink(HAL_LED_1, 2, 60, 800); 58 | break; 59 | case BDB_COMMISSIONING_NETWORK_RESTORED: 60 | zclCommissioning_OnConnect(); 61 | break; 62 | default: 63 | break; 64 | } 65 | break; 66 | case BDB_COMMISSIONING_NWK_STEERING: 67 | switch (bdbCommissioningModeMsg->bdbCommissioningStatus) { 68 | case BDB_COMMISSIONING_SUCCESS: 69 | HalLedBlink(HAL_LED_1, 7, 60, 400); 70 | LREPMaster("BDB_COMMISSIONING_SUCCESS\r\n"); 71 | zclCommissioning_OnConnect(); 72 | break; 73 | 74 | default: 75 | HalLedSet(HAL_LED_1, HAL_LED_MODE_BLINK); 76 | break; 77 | } 78 | 79 | break; 80 | 81 | case BDB_COMMISSIONING_PARENT_LOST: 82 | LREPMaster("BDB_COMMISSIONING_PARENT_LOST\r\n"); 83 | switch (bdbCommissioningModeMsg->bdbCommissioningStatus) { 84 | case BDB_COMMISSIONING_NETWORK_RESTORED: 85 | zclCommissioning_ResetBackoffRetry(); 86 | break; 87 | 88 | default: 89 | HalLedSet(HAL_LED_1, HAL_LED_MODE_BLINK); 90 | // // Parent not found, attempt to rejoin again after a exponential backoff delay 91 | LREP("rejoinsLeft %d rejoinDelay=%ld\r\n", rejoinsLeft, rejoinDelay); 92 | if (rejoinsLeft > 0) { 93 | rejoinDelay *= APP_COMMISSIONING_END_DEVICE_REJOIN_BACKOFF; 94 | rejoinsLeft -= 1; 95 | } else { 96 | rejoinDelay = APP_COMMISSIONING_END_DEVICE_REJOIN_MAX_DELAY; 97 | } 98 | osal_start_timerEx(zclCommissioning_TaskId, APP_COMMISSIONING_END_DEVICE_REJOIN_EVT, rejoinDelay); 99 | break; 100 | } 101 | break; 102 | default: 103 | break; 104 | } 105 | } 106 | 107 | static void zclCommissioning_ProcessIncomingMsg(zclIncomingMsg_t *pInMsg) { 108 | if (pInMsg->attrCmd) { 109 | osal_mem_free(pInMsg->attrCmd); 110 | } 111 | } 112 | 113 | void zclCommissioning_Sleep(uint8 allow) { 114 | LREP("zclCommissioning_Sleep %d\r\n", allow); 115 | #if defined(POWER_SAVING) 116 | if (allow) { 117 | NLME_SetPollRate(0); 118 | } else { 119 | NLME_SetPollRate(POLL_RATE); 120 | } 121 | #endif 122 | } 123 | 124 | uint16 zclCommissioning_event_loop(uint8 task_id, uint16 events) { 125 | if (events & SYS_EVENT_MSG) { 126 | devStates_t zclApp_NwkState; 127 | afIncomingMSGPacket_t *MSGpkt; 128 | while ((MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive(zclCommissioning_TaskId))) { 129 | 130 | switch (MSGpkt->hdr.event) { 131 | case ZDO_STATE_CHANGE: 132 | HalLedSet(HAL_LED_1, HAL_LED_MODE_BLINK); 133 | zclApp_NwkState = (devStates_t)(MSGpkt->hdr.status); 134 | LREP("NwkState=%d\r\n", zclApp_NwkState); 135 | if (zclApp_NwkState == DEV_END_DEVICE) { 136 | HalLedSet(HAL_LED_1, HAL_LED_MODE_OFF); 137 | } 138 | break; 139 | 140 | case ZCL_INCOMING_MSG: 141 | zclCommissioning_ProcessIncomingMsg((zclIncomingMsg_t *)MSGpkt); 142 | break; 143 | 144 | default: 145 | break; 146 | } 147 | 148 | // Release the memory 149 | osal_msg_deallocate((uint8 *)MSGpkt); 150 | } 151 | 152 | // return unprocessed events 153 | return (events ^ SYS_EVENT_MSG); 154 | } 155 | if (events & APP_COMMISSIONING_END_DEVICE_REJOIN_EVT) { 156 | LREPMaster("APP_END_DEVICE_REJOIN_EVT\r\n"); 157 | #if ZG_BUILD_ENDDEVICE_TYPE 158 | bdb_ZedAttemptRecoverNwk(); 159 | #endif 160 | return (events ^ APP_COMMISSIONING_END_DEVICE_REJOIN_EVT); 161 | } 162 | 163 | if (events & APP_COMMISSIONING_CLOCK_DOWN_POLING_RATE_EVT) { 164 | LREPMaster("APP_CLOCK_DOWN_POLING_RATE_EVT\r\n"); 165 | zclCommissioning_Sleep(true); 166 | return (events ^ APP_COMMISSIONING_CLOCK_DOWN_POLING_RATE_EVT); 167 | } 168 | 169 | // Discard unknown events 170 | return 0; 171 | } 172 | 173 | static void zclCommissioning_BindNotification(bdbBindNotificationData_t *data) { 174 | HalLedSet(HAL_LED_1, HAL_LED_MODE_BLINK); 175 | LREP("Recieved bind request clusterId=0x%X dstAddr=0x%X ep=%d\r\n", data->clusterId, data->dstAddr, data->ep); 176 | uint16 maxEntries = 0, usedEntries = 0; 177 | bindCapacity(&maxEntries, &usedEntries); 178 | LREP("bindCapacity %d %usedEntries %d \r\n", maxEntries, usedEntries); 179 | } 180 | 181 | void zclCommissioning_HandleKeys(uint8 portAndAction, uint8 keyCode) { 182 | if (portAndAction & HAL_KEY_PRESS) { 183 | #if ZG_BUILD_ENDDEVICE_TYPE 184 | if (devState == DEV_NWK_ORPHAN) { 185 | LREP("devState=%d try to restore network\r\n", devState); 186 | bdb_ZedAttemptRecoverNwk(); 187 | } 188 | #endif 189 | } 190 | #if defined(POWER_SAVING) 191 | NLME_SetPollRate(1); 192 | #endif 193 | } -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/commissioning.h: -------------------------------------------------------------------------------- 1 | #ifndef commissioning_h 2 | #define commissioning_h 3 | 4 | #define APP_COMMISSIONING_CLOCK_DOWN_POLING_RATE_EVT 0x0001 5 | #define APP_COMMISSIONING_END_DEVICE_REJOIN_EVT 0x0002 6 | 7 | #define APP_COMMISSIONING_END_DEVICE_REJOIN_MAX_DELAY ((uint32)1800000) // 30 minutes 30 * 60 * 1000 8 | #define APP_COMMISSIONING_END_DEVICE_REJOIN_START_DELAY 30 * 1000 // 10 seconds 9 | #define APP_COMMISSIONING_END_DEVICE_REJOIN_BACKOFF ((float) 1.2) 10 | #define APP_COMMISSIONING_END_DEVICE_REJOIN_TRIES 5 11 | 12 | 13 | 14 | 15 | extern void zclCommissioning_Init(uint8 task_id); 16 | extern uint16 zclCommissioning_event_loop(uint8 task_id, uint16 events); 17 | extern void zclCommissioning_Sleep( uint8 allow ); 18 | extern void zclCommissioning_HandleKeys(uint8 portAndAction, uint8 keyCode); 19 | 20 | #endif -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/f8wConfig.cfg: -------------------------------------------------------------------------------- 1 | /* 2 | * f8wConfig.cfg 3 | * 4 | * Compiler command-line options used to define a TI Z-Stack ZigBee device. 5 | * To move an option from here to the project file, comment out or delete the 6 | * option from this file and enter it into the "Define Symbols" box under the 7 | * Preprocessor tab of the C/C++ Compiler Project Options. New user defined 8 | * options may be added to this file, as necessary. 9 | * 10 | * Each macro is prefixed with '-D'. The entries are to be constructed as if 11 | * they are to be on the compiler command line invocation (which they are). 12 | * 13 | * NOTE: The RHS (Right-Hand-Side) must be quoted if there are embedded blanks. 14 | * See the DEFAULT_KEY definition for an example. 15 | */ 16 | 17 | /* Enable ZigBee-Pro */ 18 | -DZIGBEEPRO 19 | 20 | /* Set to 1 to enable security. To disable set to 0 */ 21 | -DSECURE=1 22 | -DZG_SECURE_DYNAMIC=0 23 | 24 | /* Enable the Reflector */ 25 | -DREFLECTOR 26 | 27 | /* Default channel is Channel 11 - 0x0B */ 28 | // Channels are defined in the following: 29 | // 0 : 868 MHz 0x00000001 30 | // 1 - 10 : 915 MHz 0x000007FE 31 | // 11 - 26 : 2.4 GHz 0x07FFF800 32 | // 33 | //-DMAX_CHANNELS_868MHZ 0x00000001 34 | //-DMAX_CHANNELS_915MHZ 0x000007FE 35 | //-DMAX_CHANNELS_24GHZ 0x07FFF800 36 | //-DDEFAULT_CHANLIST=0x04000000 // 26 - 0x1A 37 | //-DDEFAULT_CHANLIST=0x02000000 // 25 - 0x19 38 | //-DDEFAULT_CHANLIST=0x01000000 // 24 - 0x18 39 | //-DDEFAULT_CHANLIST=0x00800000 // 23 - 0x17 40 | //-DDEFAULT_CHANLIST=0x00400000 // 22 - 0x16 41 | //-DDEFAULT_CHANLIST=0x00200000 // 21 - 0x15 42 | //-DDEFAULT_CHANLIST=0x00100000 // 20 - 0x14 43 | //-DDEFAULT_CHANLIST=0x00080000 // 19 - 0x13 44 | //-DDEFAULT_CHANLIST=0x00040000 // 18 - 0x12 45 | //-DDEFAULT_CHANLIST=0x00020000 // 17 - 0x11 46 | //-DDEFAULT_CHANLIST=0x00010000 // 16 - 0x10 47 | //-DDEFAULT_CHANLIST=0x00008000 // 15 - 0x0F 48 | //-DDEFAULT_CHANLIST=0x00004000 // 14 - 0x0E 49 | //-DDEFAULT_CHANLIST=0x00002000 // 13 - 0x0D 50 | //-DDEFAULT_CHANLIST=0x00001000 // 12 - 0x0C 51 | -DDEFAULT_CHANLIST=0x07FFF800 // ALL channels 52 | 53 | /* Define the default PAN ID. 54 | * 55 | * Setting this to a value other than 0xFFFF causes 56 | * ZDO_COORD to use this value as its PAN ID and 57 | * Routers and end devices to join PAN with this ID 58 | */ 59 | -DZDAPP_CONFIG_PAN_ID=0xFFFF 60 | 61 | /* Minimum number of milliseconds to hold off the start of the device 62 | * in the network and the minimum delay between joining cycles. 63 | */ 64 | -DNWK_START_DELAY=100 65 | 66 | /* Mask for the random joining delay. This value is masked with 67 | * the return from osal_rand() to get a random delay time for 68 | * each joining cycle. This random value is added to NWK_START_DELAY. 69 | * For example, a value of 0x007F will be a joining delay of 0 to 127 70 | * milliseconds. 71 | */ 72 | -DEXTENDED_JOINING_RANDOM_MASK=0x007F 73 | 74 | /* Minimum number of milliseconds to delay between each beacon request 75 | * in a joining cycle. 76 | */ 77 | -DBEACON_REQUEST_DELAY=100 78 | 79 | /* Mask for the random beacon request delay. This value is masked with the 80 | * return from osal_rand() to get a random delay time for each joining cycle. 81 | * This random value is added to DBEACON_REQUEST_DELAY. For example, a value 82 | * of 0x00FF will be a beacon request delay of 0 to 255 milliseconds. 83 | */ 84 | -DBEACON_REQ_DELAY_MASK=0x00FF 85 | 86 | /* Jitter mask for the link status report timer. This value is masked with the 87 | * return from osal_rand() to add a random delay to _NIB.nwkLinkStatusPeriod. 88 | * For example, a value of 0x007F allows a jitter between 0-127 milliseconds. 89 | */ 90 | -DLINK_STATUS_JITTER_MASK=0x007F 91 | 92 | /* in seconds; set to 0 to turn off route expiry */ 93 | -DROUTE_EXPIRY_TIME=30 94 | 95 | /* This number is used by polled devices, since the spec'd formula 96 | * doesn't work for sleeping end devices. For non-polled devices, 97 | * a formula is used. Value is in 2 milliseconds periods 98 | */ 99 | -DAPSC_ACK_WAIT_DURATION_POLLED=3000 100 | 101 | /* Default indirect message holding timeout value: 102 | * 1-65535 (0 -> 65536) X CNT_RTG_TIMER X RTG_TIMER_INTERVAL 103 | */ 104 | -DNWK_INDIRECT_MSG_TIMEOUT=7 105 | 106 | /* The number of simultaneous route discoveries in network */ 107 | -DMAX_RREQ_ENTRIES=8 108 | 109 | /* The maximum number of retries allowed after a transmission failure */ 110 | -DAPSC_MAX_FRAME_RETRIES=3 111 | 112 | /* Max number of times retry looking for the next hop address of a message */ 113 | -DNWK_MAX_DATA_RETRIES=2 114 | 115 | /* Number of times retry to poll parent before indicating loss of synchronization 116 | * with parent. Note that larger value will cause longer delay for the child to 117 | * rejoin the network. 118 | */ 119 | -DMAX_POLL_FAILURE_RETRIES=2 120 | 121 | /* The number of items in the broadcast table */ 122 | -DMAX_BCAST=9 123 | 124 | /* The maximum number of groups in the groups table */ 125 | -DAPS_MAX_GROUPS=16 126 | 127 | /* Number of entries in the regular routing table plus additional 128 | * entries for route repair 129 | */ 130 | -DMAX_RTG_ENTRIES=40 131 | 132 | /* Maximum number of entries in the Binding table. */ 133 | -DNWK_MAX_BINDING_ENTRIES=5 134 | 135 | /* Maximum number of cluster IDs for each binding table entry. 136 | * Note that any value other than the default value may cause a 137 | * compilation warning but Device Binding will function correctly. 138 | */ 139 | -DMAX_BINDING_CLUSTER_IDS=15 140 | 141 | /* Default security key. */ 142 | -DDEFAULT_KEY="{0}" 143 | 144 | /* Reset when ASSERT occurs, otherwise flash LEDs */ 145 | //-DASSERT_RESET 146 | 147 | /* Set the MAC MAX Frame Size (802.15.4 default is 102) */ 148 | -DMAC_MAX_FRAME_SIZE=116 149 | 150 | /* Minimum transmissions attempted for Channel Interference detection, 151 | * Frequency Agility can be disabled by setting this parameter to zero. 152 | */ 153 | -DZDNWKMGR_MIN_TRANSMISSIONS=20 154 | 155 | /* Compiler keywords */ 156 | -DCONST="const __code" 157 | -DGENERIC=__generic 158 | 159 | /**************************************** 160 | * The following are for End Devices only 161 | ***************************************/ 162 | 163 | -DRFD_RCVC_ALWAYS_ON=FALSE 164 | 165 | /* The number of milliseconds to wait between data request polls to the coordinator. */ 166 | -DPOLL_RATE=1000 167 | 168 | /* This is used after receiving a data indication to poll immediately 169 | * for queued messages...in milliseconds. 170 | */ 171 | -DQUEUED_POLL_RATE=300 172 | 173 | /* This is used after receiving a data confirmation to poll immediately 174 | * for response messages...in milliseconds 175 | */ 176 | -DRESPONSE_POLL_RATE=300 177 | 178 | /* This is used as an alternate response poll rate only for rejoin request. 179 | * This rate is determined by the response time of the parent that the device 180 | * is trying to join. 181 | */ 182 | -DREJOIN_POLL_RATE=700 183 | 184 | /* Rejoin retry backoff silent period timer duration in milliseconds - default 15 minutes according to HA test spec */ 185 | -DREJOIN_BACKOFF=900000 186 | 187 | /* Rejoin retry backoff scan timer duration in milliseconds - default 15 minutes according to HA test spec */ 188 | -DREJOIN_SCAN=900000 189 | 190 | /* Latest sample apps use LED4 and do not use S1 switch */ 191 | -DENABLE_LED4_DISABLE_S1 -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/factory_reset.c: -------------------------------------------------------------------------------- 1 | #include "factory_reset.h" 2 | #include "AF.h" 3 | #include "Debug.h" 4 | #include "OnBoard.h" 5 | #include "bdb.h" 6 | #include "bdb_interface.h" 7 | #include "hal_led.h" 8 | #include "ZComDef.h" 9 | #include "hal_key.h" 10 | 11 | static void zclFactoryResetter_ResetToFN(void); 12 | static void zclFactoryResetter_ProcessBootCounter(void); 13 | static void zclFactoryResetter_ResetBootCounter(void); 14 | 15 | static uint8 zclFactoryResetter_TaskID; 16 | 17 | uint16 zclFactoryResetter_loop(uint8 task_id, uint16 events) { 18 | LREP("zclFactoryResetter_loop 0x%X\r\n", events); 19 | if (events & FACTORY_RESET_EVT) { 20 | LREPMaster("FACTORY_RESET_EVT\r\n"); 21 | zclFactoryResetter_ResetToFN(); 22 | return (events ^ FACTORY_RESET_EVT); 23 | } 24 | 25 | if (events & FACTORY_BOOTCOUNTER_RESET_EVT) { 26 | LREPMaster("FACTORY_BOOTCOUNTER_RESET_EVT\r\n"); 27 | zclFactoryResetter_ResetBootCounter(); 28 | return (events ^ FACTORY_BOOTCOUNTER_RESET_EVT); 29 | } 30 | return 0; 31 | } 32 | void zclFactoryResetter_ResetBootCounter(void) { 33 | uint16 bootCnt = 0; 34 | LREPMaster("Clear boot counter\r\n"); 35 | osal_nv_write(ZCD_NV_BOOTCOUNTER, 0, sizeof(bootCnt), &bootCnt); 36 | } 37 | 38 | void zclFactoryResetter_Init(uint8 task_id) { 39 | zclFactoryResetter_TaskID = task_id; 40 | /** 41 | * We can't register more than one task, call in main app taks 42 | * zclFactoryResetter_HandleKeys(portAndAction, keyCode); 43 | * */ 44 | // RegisterForKeys(task_id); 45 | #if FACTORY_RESET_BY_BOOT_COUNTER 46 | zclFactoryResetter_ProcessBootCounter(); 47 | #endif 48 | } 49 | 50 | void zclFactoryResetter_ResetToFN(void) { 51 | HalLedSet(HAL_LED_1, HAL_LED_MODE_FLASH); 52 | LREP("bdbAttributes.bdbNodeIsOnANetwork=%d bdbAttributes.bdbCommissioningMode=0x%X\r\n", bdbAttributes.bdbNodeIsOnANetwork, bdbAttributes.bdbCommissioningMode); 53 | LREPMaster("zclFactoryResetter: Reset to FN\r\n"); 54 | bdb_resetLocalAction(); 55 | } 56 | 57 | void zclFactoryResetter_HandleKeys(uint8 portAndAction, uint8 keyCode) { 58 | #if FACTORY_RESET_BY_LONG_PRESS 59 | if (portAndAction & HAL_KEY_RELEASE) { 60 | LREPMaster("zclFactoryResetter: Key release\r\n"); 61 | osal_stop_timerEx(zclFactoryResetter_TaskID, FACTORY_RESET_EVT); 62 | } else { 63 | LREPMaster("zclFactoryResetter: Key press\r\n"); 64 | bool statTimer = true; 65 | #if FACTORY_RESET_BY_LONG_PRESS_PORT 66 | statTimer = FACTORY_RESET_BY_LONG_PRESS_PORT & portAndAction; 67 | #endif 68 | LREP("zclFactoryResetter statTimer hold timer %d\r\n", statTimer); 69 | if (statTimer) { 70 | uint32 timeout = bdbAttributes.bdbNodeIsOnANetwork ? FACTORY_RESET_HOLD_TIME_LONG : FACTORY_RESET_HOLD_TIME_FAST; 71 | osal_start_timerEx(zclFactoryResetter_TaskID, FACTORY_RESET_EVT, timeout); 72 | } 73 | } 74 | #endif 75 | } 76 | 77 | void zclFactoryResetter_ProcessBootCounter(void) { 78 | LREPMaster("zclFactoryResetter_ProcessBootCounter\r\n"); 79 | osal_start_timerEx(zclFactoryResetter_TaskID, FACTORY_BOOTCOUNTER_RESET_EVT, FACTORY_RESET_BOOTCOUNTER_RESET_TIME); 80 | 81 | uint16 bootCnt = 0; 82 | if (osal_nv_item_init(ZCD_NV_BOOTCOUNTER, sizeof(bootCnt), &bootCnt) == ZSUCCESS) { 83 | osal_nv_read(ZCD_NV_BOOTCOUNTER, 0, sizeof(bootCnt), &bootCnt); 84 | } 85 | LREP("bootCnt %d\r\n", bootCnt); 86 | bootCnt += 1; 87 | if (bootCnt >= FACTORY_RESET_BOOTCOUNTER_MAX_VALUE) { 88 | LREP("bootCnt =%d greater than, ressetting %d\r\n", bootCnt, FACTORY_RESET_BOOTCOUNTER_MAX_VALUE); 89 | bootCnt = 0; 90 | osal_stop_timerEx(zclFactoryResetter_TaskID, FACTORY_BOOTCOUNTER_RESET_EVT); 91 | osal_start_timerEx(zclFactoryResetter_TaskID, FACTORY_RESET_EVT, 5000); 92 | } 93 | osal_nv_write(ZCD_NV_BOOTCOUNTER, 0, sizeof(bootCnt), &bootCnt); 94 | } -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/factory_reset.h: -------------------------------------------------------------------------------- 1 | #ifndef FACTORY_RESET_H 2 | #define FACTORY_RESET_H 3 | 4 | #define FACTORY_RESET_EVT 0x1000 5 | #define FACTORY_BOOTCOUNTER_RESET_EVT 0x2000 6 | 7 | #ifndef FACTORY_RESET_HOLD_TIME_LONG 8 | #define FACTORY_RESET_HOLD_TIME_LONG ((uint32)10 * 1000) 9 | #endif 10 | 11 | #ifndef FACTORY_RESET_HOLD_TIME_FAST 12 | #define FACTORY_RESET_HOLD_TIME_FAST 1000 13 | #endif 14 | 15 | #ifndef FACTORY_RESET_BOOTCOUNTER_MAX_VALUE 16 | #define FACTORY_RESET_BOOTCOUNTER_MAX_VALUE 5 17 | #endif 18 | 19 | #ifndef FACTORY_RESET_BOOTCOUNTER_RESET_TIME 20 | #define FACTORY_RESET_BOOTCOUNTER_RESET_TIME 10 * 1000 21 | #endif 22 | 23 | #ifndef FACTORY_RESET_BY_LONG_PRESS 24 | #define FACTORY_RESET_BY_LONG_PRESS TRUE 25 | #endif 26 | 27 | 28 | #ifndef FACTORY_RESET_BY_LONG_PRESS_PORT 29 | #define FACTORY_RESET_BY_LONG_PRESS_PORT 0x00 30 | #endif 31 | 32 | 33 | #ifndef FACTORY_RESET_BY_BOOT_COUNTER 34 | #define FACTORY_RESET_BY_BOOT_COUNTER TRUE 35 | #endif 36 | 37 | extern void zclFactoryResetter_Init(uint8 task_id); 38 | extern uint16 zclFactoryResetter_loop(uint8 task_id, uint16 events); 39 | extern void zclFactoryResetter_HandleKeys(uint8 portAndAction, uint8 keyCode); 40 | #endif -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/hal_i2c.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************** 2 | Filename: hal_i2c.c 3 | Revised: $Date: 2012-09-21 06:30:38 -0700 (Fri, 21 Sep 2012) $ 4 | Revision: $Revision: 31581 $ 5 | 6 | Description: This module defines the HAL I2C API for the CC2541ST. It 7 | implements the I2C master. 8 | 9 | 10 | Copyright 2012 Texas Instruments Incorporated. All rights reserved. 11 | 12 | IMPORTANT: Your use of this Software is limited to those specific rights 13 | granted under the terms of a software license agreement between the user 14 | who downloaded the software, his/her employer (which must be your employer) 15 | and Texas Instruments Incorporated (the "License"). You may not use this 16 | Software unless you agree to abide by the terms of the License. The License 17 | limits your use, and you acknowledge, that the Software may not be modified, 18 | copied or distributed unless embedded on a Texas Instruments microcontroller 19 | or used solely and exclusively in conjunction with a Texas Instruments radio 20 | frequency transceiver, which is integrated into your product. Other than for 21 | the foregoing purpose, you may not use, reproduce, copy, prepare derivative 22 | works of, modify, distribute, perform, display or sell this Software and/or 23 | its documentation for any purpose. 24 | 25 | YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE 26 | PROVIDED �AS IS� WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, 27 | INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, 28 | NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL 29 | TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, 30 | NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER 31 | LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES 32 | INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE 33 | OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT 34 | OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES 35 | (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. 36 | 37 | Should you have any questions regarding your right to use this Software, 38 | contact Texas Instruments Incorporated at www.TI.com. 39 | **************************************************************************************************/ 40 | #include "hal_i2c.h" 41 | 42 | #include "Debug.h" 43 | #include "ioCC2530.h" 44 | #include "zcomdef.h" 45 | #include "utils.h" 46 | 47 | #define STATIC static 48 | 49 | #if !defined HAL_I2C_RETRY_CNT 50 | #define HAL_I2C_RETRY_CNT 3 51 | #endif 52 | 53 | // the default cofiguration below uses P0.6 for SDA and P0.5 for SCL. 54 | // change these as needed. 55 | #ifndef OCM_CLK_PORT 56 | #define OCM_CLK_PORT 0 57 | #endif 58 | 59 | #ifndef OCM_DATA_PORT 60 | #define OCM_DATA_PORT 0 61 | #endif 62 | 63 | #ifndef OCM_CLK_PIN 64 | #define OCM_CLK_PIN 5 65 | #endif 66 | 67 | #ifndef OCM_DATA_PIN 68 | #define OCM_DATA_PIN 6 69 | #endif 70 | 71 | 72 | 73 | #define OCM_ADDRESS (0xA0) 74 | 75 | #define SMB_ACK (0) 76 | #define SMB_NAK (1) 77 | #define SEND_STOP (0) 78 | #define NOSEND_STOP (1) 79 | #define SEND_START (0) 80 | #define NOSEND_START (1) 81 | 82 | // device specific as to where the 17th address bit goes... 83 | 84 | // ************************* MACROS ************************************ 85 | #undef P 86 | 87 | 88 | 89 | // OCM port I/O defintions 90 | #define OCM_SCL BNAME(OCM_CLK_PORT, OCM_CLK_PIN) 91 | #define OCM_SDA BNAME(OCM_DATA_PORT, OCM_DATA_PIN) 92 | 93 | 94 | 95 | #define OCM_DATA_HIGH() { IO_DIR_PORT_PIN(OCM_DATA_PORT, OCM_DATA_PIN, IO_IN); } 96 | 97 | #define OCM_DATA_LOW() \ 98 | { \ 99 | IO_DIR_PORT_PIN(OCM_DATA_PORT, OCM_DATA_PIN, IO_OUT); \ 100 | OCM_SDA = 0; \ 101 | } 102 | 103 | 104 | 105 | STATIC void hali2cSend(uint8 *buffer, uint16 len, uint8 sendStart, uint8 sendStop); 106 | STATIC _Bool hali2cSendByte(uint8 dByte); 107 | STATIC void hali2cWrite(bool dBit); 108 | STATIC void hali2cClock(bool dir); 109 | STATIC void hali2cStart(void); 110 | STATIC void hali2cStop(void); 111 | STATIC void hali2cReceive(uint8 address, uint8 *buffer, uint16 len); 112 | STATIC uint8 hali2cReceiveByte(void); 113 | STATIC _Bool hali2cRead(void); 114 | STATIC void hali2cSendDeviceAddress(uint8 address); 115 | 116 | STATIC __near_func void hali2cWait(uint8); 117 | 118 | static void hali2cGroudPins(void); 119 | 120 | void hali2cGroudPins(void) { 121 | IO_DIR_PORT_PIN(OCM_DATA_PORT, OCM_DATA_PIN, IO_IN); 122 | IO_DIR_PORT_PIN(OCM_CLK_PORT, OCM_CLK_PIN, IO_IN); 123 | } 124 | 125 | STATIC uint8 s_xmemIsInit; 126 | 127 | /********************************************************************* 128 | * @fn HalI2CInit 129 | * @brief Initializes two-wire serial I/O bus 130 | * @param void 131 | * @return void 132 | */ 133 | void HalI2CInit(void) { 134 | if (!s_xmemIsInit) { 135 | s_xmemIsInit = 1; 136 | 137 | // // Set port pins as inputs 138 | // IO_DIR_PORT_PIN(OCM_CLK_PORT, OCM_CLK_PIN, IO_IN); 139 | // IO_DIR_PORT_PIN(OCM_DATA_PORT, OCM_DATA_PIN, IO_IN); 140 | // // 141 | // // Set for general I/O operation 142 | // IO_FUNC_PORT_PIN(OCM_CLK_PORT, OCM_CLK_PIN, IO_GIO); 143 | // IO_FUNC_PORT_PIN(OCM_DATA_PORT, OCM_DATA_PIN, IO_GIO); 144 | // // 145 | // // Set I/O mode for pull-up/pull-down 146 | // IO_IMODE_PORT_PIN(OCM_CLK_PORT, OCM_CLK_PIN, IO_PUD); 147 | // IO_IMODE_PORT_PIN(OCM_DATA_PORT, OCM_DATA_PIN, IO_PUD); 148 | 149 | // // Set pins to pull-up 150 | // IO_PUD_PORT(OCM_CLK_PORT, IO_PUP); 151 | // IO_PUD_PORT(OCM_DATA_PORT, IO_PUP); 152 | } 153 | } 154 | 155 | int8 HalI2CReceive(uint8 address, uint8 *buf, uint16 len) { 156 | hali2cReceive(address, buf, len); 157 | 158 | return 0; 159 | } 160 | 161 | int8 HalI2CSend(uint8 address, uint8 *buf, uint16 len) { 162 | // begin the write sequence with the address byte 163 | hali2cSendDeviceAddress(address); 164 | hali2cSend(buf, len, NOSEND_START, SEND_STOP); 165 | 166 | return 0; 167 | } 168 | /********************************************************************* 169 | * @fn hali2cSend 170 | * @brief Sends buffer contents to SM-Bus device 171 | * @param buffer - ptr to buffered data to send 172 | * @param len - number of bytes in buffer 173 | * @param sendStart - whether or not to send start condition. 174 | * @param sendStop - whether or not to send stop condition. 175 | * @return void 176 | */ 177 | STATIC void hali2cSend(uint8 *buffer, uint16 len, uint8 sendStart, uint8 sendStop) { 178 | uint16 i; 179 | uint8 retry = HAL_I2C_RETRY_CNT; 180 | 181 | if (!len) { 182 | return; 183 | } 184 | 185 | if (sendStart == SEND_START) { 186 | hali2cStart(); 187 | } 188 | 189 | for (i = 0; i < len; i++) { 190 | do { 191 | if (hali2cSendByte(buffer[i])) // takes care of ack polling 192 | { 193 | break; 194 | } 195 | } while (--retry); 196 | } 197 | 198 | if (sendStop == SEND_STOP) { 199 | hali2cStop(); 200 | } 201 | } 202 | 203 | /********************************************************************* 204 | * @fn hali2cSendByte 205 | * @brief Serialize and send one byte to SM-Bus device 206 | * @param dByte - data byte to send 207 | * @return ACK status - 0=none, 1=received 208 | */ 209 | STATIC _Bool hali2cSendByte(uint8 dByte) { 210 | uint8 i; 211 | 212 | for (i = 0; i < 8; i++) { 213 | // Send the MSB 214 | hali2cWrite(dByte & 0x80); 215 | // Next bit into MSB 216 | dByte <<= 1; 217 | } 218 | // need clock low so if the SDA transitions on the next statement the 219 | // slave doesn't stop. Also give opportunity for slave to set SDA 220 | hali2cClock(0); 221 | OCM_DATA_HIGH(); // set to input to receive ack... 222 | hali2cClock(1); 223 | hali2cWait(1); 224 | 225 | return (!OCM_SDA); // Return ACK status 226 | } 227 | 228 | /********************************************************************* 229 | * @fn hali2cWrite 230 | * @brief Send one bit to SM-Bus device 231 | * @param dBit - data bit to clock onto SM-Bus 232 | * @return void 233 | */ 234 | STATIC void hali2cWrite(bool dBit) { 235 | hali2cClock(0); 236 | hali2cWait(1); 237 | if (dBit) { 238 | OCM_DATA_HIGH(); 239 | } else { 240 | OCM_DATA_LOW(); 241 | } 242 | 243 | hali2cClock(1); 244 | hali2cWait(1); 245 | } 246 | 247 | /********************************************************************* 248 | * @fn hali2cClock 249 | * @brief Clocks the SM-Bus. If a negative edge is going out, the 250 | * I/O pin is set as an output and driven low. If a positive 251 | * edge is going out, the pin is set as an input and the pin 252 | * pull-up drives the line high. This way, the slave device 253 | * can hold the node low if longer setup time is desired. 254 | * @param dir - clock line direction 255 | * @return void 256 | */ 257 | STATIC void hali2cClock(bool dir) { 258 | uint8 maxWait = 10; 259 | if (dir) { 260 | IO_DIR_PORT_PIN(OCM_CLK_PORT, OCM_CLK_PIN, IO_IN); 261 | /* Wait until clock is high */ 262 | while (!OCM_SCL && maxWait) { 263 | hali2cWait(1); 264 | maxWait -= 1; 265 | } 266 | 267 | } else { 268 | IO_DIR_PORT_PIN(OCM_CLK_PORT, OCM_CLK_PIN, IO_OUT); 269 | OCM_SCL = 0; 270 | } 271 | hali2cWait(1); 272 | } 273 | 274 | /********************************************************************* 275 | * @fn hali2cStart 276 | * @brief Initiates SM-Bus communication. Makes sure that both the 277 | * clock and data lines of the SM-Bus are high. Then the data 278 | * line is set high and clock line is set low to start I/O. 279 | * @param void 280 | * @return void 281 | */ 282 | STATIC void hali2cStart(void) { 283 | uint8 retry = HAL_I2C_RETRY_CNT; 284 | 285 | // set SCL to input but with pull-up. if slave is pulling down it will stay down. 286 | hali2cClock(1); 287 | 288 | do { 289 | // wait for slave to release clock line... 290 | if (OCM_SCL) // wait until the line is high... 291 | { 292 | break; 293 | } 294 | hali2cWait(1); 295 | } while (--retry); 296 | 297 | // SCL low to set SDA high so the transition will be correct. 298 | hali2cClock(0); 299 | OCM_DATA_HIGH(); // SDA high 300 | hali2cClock(1); // set up for transition 301 | hali2cWait(1); 302 | OCM_DATA_LOW(); // start 303 | 304 | hali2cWait(1); 305 | hali2cClock(0); 306 | } 307 | 308 | /********************************************************************* 309 | * @fn hali2cStop 310 | * @brief Terminates SM-Bus communication. Waits unitl the data line 311 | * is low and the clock line is high. Then sets the data line 312 | * high, keeping the clock line high to stop I/O. 313 | * @param void 314 | * @return void 315 | */ 316 | STATIC void hali2cStop(void) { 317 | // Wait for clock high and data low 318 | hali2cClock(0); 319 | OCM_DATA_LOW(); // force low with SCL low 320 | hali2cWait(1); 321 | 322 | hali2cClock(1); 323 | OCM_DATA_HIGH(); // stop condition 324 | hali2cWait(1); 325 | 326 | hali2cGroudPins(); 327 | } 328 | 329 | /********************************************************************* 330 | * @fn hali2cWait 331 | * @brief Wastes a an amount of time. 332 | * @param count: down count in busy-wait 333 | * @return void 334 | */ 335 | STATIC __near_func void hali2cWait(uint8 count) { 336 | while (count--) { 337 | asm("NOP"); 338 | } 339 | } 340 | 341 | /********************************************************************* 342 | * @fn hali2cReceiveByte 343 | * @brief Read the 8 data bits. 344 | * @param void 345 | * @return character read 346 | */ 347 | STATIC uint8 hali2cReceiveByte() { 348 | int8 i, rval = 0; 349 | 350 | for (i = 7; i >= 0; --i) { 351 | if (hali2cRead()) { 352 | rval |= 1 << i; 353 | } 354 | } 355 | 356 | return rval; 357 | } 358 | /************************************************************************************************** 359 | **************************************************************************************************/ 360 | /********************************************************************* 361 | * @fn hali2cReceive 362 | * @brief reads data into a buffer 363 | * @param address: linear address on part from which to read 364 | * @param buffer: target array for read characters 365 | * @param len: max number of characters to read 366 | * @return void 367 | */ 368 | STATIC void hali2cReceive(uint8 address, uint8 *buffer, uint16 len) { 369 | // uint8 ch; 370 | uint16 i; 371 | 372 | if (!len) { 373 | return; 374 | } 375 | 376 | hali2cSendDeviceAddress(address); 377 | 378 | // ch = OCM_ADDRESS_BYTE(0, OCM_READ); 379 | // hali2cSend(&ch, 1, SEND_START, NOSEND_STOP); 380 | 381 | for (i = 0; i < len - 1; i++) { 382 | // SCL may be high. set SCL low. If SDA goes high when input 383 | // mode is set the slave won't see a STOP 384 | hali2cClock(0); 385 | OCM_DATA_HIGH(); 386 | 387 | buffer[i] = hali2cReceiveByte(); 388 | hali2cWrite(SMB_ACK); // write leaves SCL high 389 | } 390 | 391 | // condition SDA one more time... 392 | hali2cClock(0); 393 | OCM_DATA_HIGH(); 394 | buffer[i] = hali2cReceiveByte(); 395 | hali2cWrite(SMB_NAK); 396 | 397 | hali2cStop(); 398 | } 399 | 400 | /********************************************************************* 401 | * @fn hali2cRead 402 | * @brief Toggle the clock line to let the slave set the data line. 403 | * Then read the data line. 404 | * @param void 405 | * @return TRUE if bit read is 1 else FALSE 406 | */ 407 | STATIC _Bool hali2cRead(void) { 408 | // SCL low to let slave set SDA. SCL high for SDA 409 | // valid and then get bit 410 | hali2cClock(0); 411 | hali2cWait(1); 412 | hali2cClock(1); 413 | hali2cWait(1); 414 | 415 | return OCM_SDA; 416 | } 417 | 418 | /********************************************************************* 419 | * @fn hali2cSendDeviceAddress 420 | * @brief Send onlythe device address. Do ack polling 421 | * 422 | * @param void 423 | * @return none 424 | */ 425 | STATIC void hali2cSendDeviceAddress(uint8 address) { 426 | uint8 retry = HAL_I2C_RETRY_CNT; 427 | 428 | do { 429 | hali2cStart(); 430 | if (hali2cSendByte(address)) // do ack polling... 431 | { 432 | break; 433 | } 434 | } while (--retry); 435 | } 436 | 437 | // http://e2e.ti.com/support/wireless-connectivity/zigbee-and-thread/f/158/t/140917 438 | /********************************************************************* 439 | * @fn I2C_ReadMultByte 440 | * @brief reads data into a buffer 441 | * @param address: linear address on part from which to read 442 | * @param reg: internal register address on part read from 443 | * @param buffer: target array for read characters 444 | * @param len: max number of bytes to read 445 | */ 446 | int8 I2C_ReadMultByte(uint8 address, uint8 reg, uint8 *buffer, uint16 len) { 447 | uint16 i = 0; 448 | uint8 _address = 0; 449 | 450 | if (!len) { 451 | return I2C_ERROR; 452 | } 453 | 454 | /* Send START condition */ 455 | hali2cStart(); 456 | 457 | /* Set direction of transmission */ 458 | // Reset the address bit0 for write 459 | // _address &= OCM_WRITE; 460 | 461 | _address = ((address << 1) | OCM_WRITE); 462 | 463 | /* Send Address and get acknowledgement from slave*/ 464 | if (!hali2cSendByte(_address)) { 465 | return I2C_ERROR; 466 | } 467 | 468 | /* Send internal register to read from to */ 469 | if (!hali2cSendByte(reg)) 470 | return I2C_ERROR; 471 | 472 | /* Send RESTART condition */ 473 | hali2cStart(); 474 | 475 | /* Set direction of transmission */ 476 | // Reset the address bit0 for read 477 | // _address |= OCM_READ; 478 | _address = ((address << 1) | OCM_READ); 479 | /* Send Address and get acknowledgement from slave*/ 480 | if (!hali2cSendByte(_address)) 481 | return I2C_ERROR; 482 | 483 | while (len) { 484 | // SCL may be high. set SCL low. If SDA goes high when input 485 | // mode is set the slave won't see a STOP 486 | hali2cClock(0); 487 | OCM_DATA_HIGH(); 488 | buffer[i] = hali2cReceiveByte(); 489 | // Acknowledgement if not sending last byte 490 | if (len > 1) { 491 | hali2cWrite(SMB_ACK); // write leaves SCL high 492 | } 493 | 494 | // increment buffer register 495 | i++; 496 | // Decrement the read bytes counter 497 | len--; 498 | } 499 | 500 | // condition SDA one more time... 501 | hali2cClock(0); 502 | OCM_DATA_HIGH(); 503 | hali2cWrite(SMB_NAK); 504 | 505 | hali2cStop(); 506 | 507 | // condition SDA one more time... 508 | // hali2cClock(0); 509 | // OCM_DATA_HIGH(); 510 | // buffer[i] = hali2cReceiveByte(); 511 | // hali2cWrite(SMB_NAK); 512 | 513 | // hali2cStop(); 514 | return I2C_SUCCESS; 515 | } 516 | 517 | /********************************************************************* 518 | * @fn I2C_WriteMultByte 519 | * @brief reads data into a buffer 520 | * @param address: linear address on part from which to read 521 | * @param reg: internal register address on part read from 522 | * @param buffer: target array for read characters 523 | * @param len: max number of bytes to read 524 | */ 525 | int8 I2C_WriteMultByte(uint8 address, uint8 reg, uint8 *buffer, uint16 len) { 526 | uint16 i = 0; 527 | uint8 _address = 0; 528 | 529 | if (!len) { 530 | return I2C_ERROR; 531 | } 532 | 533 | /* Send START condition */ 534 | hali2cStart(); 535 | // return I2C_ERROR; 536 | 537 | /* Set direction of transmission */ 538 | // Reset the address bit0 for write 539 | // _address &= OCM_WRITE; 540 | _address = ((address << 1) | OCM_WRITE); 541 | 542 | /* Send Address and get acknowledgement from slave*/ 543 | if (!hali2cSendByte(_address)) 544 | return I2C_ERROR; 545 | 546 | /* Send internal register to read from to */ 547 | if (!hali2cSendByte(reg)) 548 | return I2C_ERROR; 549 | 550 | /* Write data into register */ 551 | // read bytes of data into buffer 552 | while (len) { 553 | // SCL may be high. set SCL low. If SDA goes high when input 554 | // mode is set the slave won't see a STOP 555 | hali2cClock(0); 556 | OCM_DATA_HIGH(); 557 | 558 | /* Send Address and get acknowledgement from slave*/ 559 | if (!hali2cSendByte(buffer[i])) 560 | return I2C_ERROR; 561 | 562 | // increment buffer register 563 | i++; 564 | // Decrement the read bytes counter 565 | len--; 566 | } 567 | 568 | hali2cStop(); 569 | return I2C_SUCCESS; 570 | } -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/hal_i2c.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************** 2 | Filename: hal_i2c.h 3 | Revised: $Date: 2009-01-20 06:41:30 -0800 (Tue, 20 Jan 2009) $ 4 | Revision: $Revision: 18809 $ 5 | 6 | Description: Interface for I2C driver. 7 | 8 | 9 | Copyright 2006 - 2008 Texas Instruments Incorporated. All rights reserved. 10 | 11 | IMPORTANT: Your use of this Software is limited to those specific rights 12 | granted under the terms of a software license agreement between the user 13 | who downloaded the software, his/her employer (which must be your employer) 14 | and Texas Instruments Incorporated (the "License"). You may not use this 15 | Software unless you agree to abide by the terms of the License. The License 16 | limits your use, and you acknowledge, that the Software may not be modified, 17 | copied or distributed unless embedded on a Texas Instruments microcontroller 18 | or used solely and exclusively in conjunction with a Texas Instruments radio 19 | frequency transceiver, which is integrated into your product. Other than for 20 | the foregoing purpose, you may not use, reproduce, copy, prepare derivative 21 | works of, modify, distribute, perform, display or sell this Software and/or 22 | its documentation for any purpose. 23 | 24 | YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE 25 | PROVIDED �AS IS� WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, 26 | INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, 27 | NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL 28 | TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, 29 | NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER 30 | LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES 31 | INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE 32 | OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT 33 | OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES 34 | (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. 35 | 36 | Should you have any questions regarding your right to use this Software, 37 | contact Texas Instruments Incorporated at www.TI.com. 38 | **************************************************************************************************/ 39 | 40 | #ifndef HAL_I2C_H 41 | #define HAL_I2C_H 42 | 43 | 44 | #define I2C_ERROR 1 45 | #define I2C_SUCCESS 0 46 | 47 | #define OCM_READ (0x01) 48 | #define OCM_WRITE (0x00) 49 | 50 | /********************************************************************* 51 | * @fn HalI2CInit 52 | * @brief Initializes two-wire serial I/O bus 53 | * @param void 54 | * @return void 55 | */ 56 | void HalI2CInit( void ); 57 | 58 | /********************************************************************* 59 | * @fn HALI2CReceive 60 | * @brief Receives data into a buffer from an I2C slave device 61 | * @param address: address of the slave device 62 | * @param buf: target array for read characters 63 | * @param len: max number of characters to read 64 | * @return zero when successful. 65 | */ 66 | int8 HalI2CReceive(uint8 address, uint8 *buf, uint16 len); 67 | 68 | /********************************************************************* 69 | * @fn HALI2CSend 70 | * @brief Sends buffer contents to an I2C slave device 71 | * @param address: address of the slave device 72 | * @param buf - ptr to buffered data to send 73 | * @param len - number of bytes in buffer 74 | * @return zero when successful. 75 | */ 76 | int8 HalI2CSend(uint8 address, uint8 *buf, uint16 len); 77 | 78 | 79 | 80 | int8 I2C_ReadMultByte( uint8 address, uint8 reg, uint8 *buffer, uint16 len ); 81 | int8 I2C_WriteMultByte( uint8 address, uint8 reg, uint8 *buffer, uint16 len ); 82 | #endif 83 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/hal_key.c: -------------------------------------------------------------------------------- 1 | /************************************************************************************************** 2 | * INCLUDES 3 | **************************************************************************************************/ 4 | #include "hal_key.h" 5 | #include "Debug.h" 6 | #include "OnBoard.h" 7 | #include "utils.h" 8 | 9 | #include "hal_adc.h" 10 | #include "hal_defs.h" 11 | #include "hal_drivers.h" 12 | #include "hal_led.h" 13 | #include "hal_mcu.h" 14 | #include "hal_types.h" 15 | #include "osal.h" 16 | 17 | /************************************************************************************************** 18 | * MACROS 19 | **************************************************************************************************/ 20 | 21 | #ifndef HAL_KEY_P0_INPUT_PINS 22 | #define HAL_KEY_P0_INPUT_PINS 0x00 23 | #endif 24 | 25 | #ifndef HAL_KEY_P1_INPUT_PINS 26 | #define HAL_KEY_P1_INPUT_PINS 0x00 27 | #endif 28 | 29 | #ifndef HAL_KEY_P2_INPUT_PINS 30 | #define HAL_KEY_P2_INPUT_PINS 0x00 31 | #endif 32 | 33 | 34 | #ifndef HAL_KEY_P0_INPUT_PINS_EDGE 35 | #define HAL_KEY_P0_INPUT_PINS_EDGE HAL_KEY_FALLING_EDGE 36 | #endif 37 | 38 | #ifndef HAL_KEY_P1_INPUT_PINS_EDGE 39 | #define HAL_KEY_P1_INPUT_PINS_EDGE HAL_KEY_FALLING_EDGE 40 | #endif 41 | 42 | #ifndef HAL_KEY_P2_INPUT_PINS_EDGE 43 | #define HAL_KEY_P2_INPUT_PINS_EDGE HAL_KEY_FALLING_EDGE 44 | #endif 45 | /************************************************************************************************** 46 | * CONSTANTS 47 | **************************************************************************************************/ 48 | 49 | uint8 portNum = 0; 50 | uint8 pinNum = 0; 51 | 52 | #define HAL_KEY_DEBOUNCE_VALUE 25 53 | 54 | #define HAL_KEY_P0_EDGE_BITS HAL_KEY_BIT0 55 | #define HAL_KEY_P1_EDGE_BITS (HAL_KEY_BIT1 | HAL_KEY_BIT2) 56 | #define HAL_KEY_P2_EDGE_BITS HAL_KEY_BIT3 57 | 58 | /************************************************************************************************** 59 | * TYPEDEFS 60 | **************************************************************************************************/ 61 | 62 | /************************************************************************************************** 63 | * GLOBAL VARIABLES 64 | **************************************************************************************************/ 65 | bool Hal_KeyIntEnable; 66 | /************************************************************************************************** 67 | * FUNCTIONS - Local 68 | **************************************************************************************************/ 69 | void halProcessKeyInterrupt(uint8 portNum); 70 | 71 | void HalKeyPoll(void) { 72 | uint8 pinStatus = 0; 73 | bool isPressed = false; 74 | switch (portNum) { 75 | case HAL_KEY_PORT0: 76 | PICTL ^= HAL_KEY_P0_EDGE_BITS; // flip edge bit 77 | pinStatus = P0 & pinNum; 78 | isPressed = HAL_KEY_P0_INPUT_PINS_EDGE != !!(pinStatus); 79 | break; 80 | 81 | case HAL_KEY_PORT1: 82 | PICTL ^= HAL_KEY_P1_EDGE_BITS; // flip edge bit 83 | pinStatus = P1 & pinNum; 84 | isPressed = HAL_KEY_P1_INPUT_PINS_EDGE != !!(pinStatus); 85 | break; 86 | 87 | case HAL_KEY_PORT2: 88 | PICTL ^= HAL_KEY_P2_EDGE_BITS; // flip edge bit 89 | pinStatus = P2 & pinNum; 90 | isPressed = HAL_KEY_P2_INPUT_PINS_EDGE != !!(pinStatus); 91 | break; 92 | 93 | default: 94 | break; 95 | } 96 | LREP("portNum=0x%X pinNum=0x%X isPressed=%d\r\n", portNum, pinNum, isPressed); 97 | 98 | // LREP("pinStatus=" BYTE_TO_BINARY_PATTERN "\r\n", BYTE_TO_BINARY(pinStatus)); 99 | OnBoard_SendKeys(pinNum, (isPressed ? HAL_KEY_PRESS : HAL_KEY_RELEASE) | portNum); 100 | } 101 | 102 | void HalKeyInit(void) { 103 | #if HAL_KEY_P0_INPUT_PINS 104 | P0SEL &= ~HAL_KEY_P0_INPUT_PINS; 105 | P0DIR &= ~(HAL_KEY_P0_INPUT_PINS); 106 | #endif 107 | 108 | #if HAL_KEY_P1_INPUT_PINS 109 | P1SEL &= ~HAL_KEY_P1_INPUT_PINS; 110 | P1DIR &= ~(HAL_KEY_P1_INPUT_PINS); 111 | #endif 112 | 113 | #if HAL_KEY_P2_INPUT_PINS 114 | P2SEL &= ~HAL_KEY_P2_INPUT_PINS; 115 | P2DIR &= ~(HAL_KEY_P2_INPUT_PINS); 116 | #endif 117 | 118 | } 119 | 120 | void HalKeyConfig(bool interruptEnable, halKeyCBack_t cback) { 121 | Hal_KeyIntEnable = true; 122 | 123 | #if HAL_KEY_P0_INPUT_PINS 124 | P0IEN |= HAL_KEY_P0_INPUT_PINS; 125 | IEN1 |= HAL_KEY_BIT5; // enable port0 int 126 | P0INP &= ~HAL_KEY_P0_INPUT_PINS; // Pullup/pulldown 127 | #if (HAL_KEY_P0_INPUT_PINS_EDGE == HAL_KEY_FALLING_EDGE) 128 | P2INP &= ~HAL_KEY_BIT5; // pull up 129 | MicroWait(50); 130 | PICTL |= HAL_KEY_P0_EDGE_BITS; // set falling edge on port 131 | #else 132 | P2INP |= HAL_KEY_BIT5; // pull down 133 | MicroWait(50); 134 | PICTL &= ~(HAL_KEY_P0_EDGE_BITS); 135 | #endif 136 | 137 | #endif 138 | 139 | #if HAL_KEY_P1_INPUT_PINS 140 | P1IEN |= HAL_KEY_P1_INPUT_PINS; 141 | IEN2 |= HAL_KEY_BIT4; // enable port1 int 142 | P1INP &= ~HAL_KEY_P1_INPUT_PINS; //Pullup/pulldown 143 | #if (HAL_KEY_P1_INPUT_PINS_EDGE == HAL_KEY_FALLING_EDGE) 144 | P2INP &= ~HAL_KEY_BIT6; // pull up 145 | MicroWait(50); 146 | PICTL |= HAL_KEY_P1_EDGE_BITS; // set falling edge on port 147 | #else 148 | P2INP |= HAL_KEY_BIT6; // pull down 149 | MicroWait(50); 150 | PICTL &= ~HAL_KEY_P1_EDGE_BITS; 151 | #endif 152 | 153 | #endif 154 | 155 | #if HAL_KEY_P2_INPUT_PINS 156 | P2IEN |= HAL_KEY_P2_INPUT_PINS; 157 | IEN2 |= HAL_KEY_BIT1; // enable port2 int 158 | P2INP &= ~HAL_KEY_P2_INPUT_PINS; //Pullup/pulldown 159 | #if (HAL_KEY_P2_INPUT_PINS_EDGE == HAL_KEY_FALLING_EDGE) 160 | P2INP &= ~HAL_KEY_BIT7; // pull up 161 | MicroWait(50); 162 | PICTL |= HAL_KEY_P2_EDGE_BITS; // set falling edge on port 163 | #else 164 | P2INP |= HAL_KEY_BIT7; // pull down 165 | MicroWait(50); 166 | PICTL &= ~HAL_KEY_P2_EDGE_BITS; 167 | #endif 168 | 169 | #endif 170 | } 171 | 172 | void halProcessKeyInterrupt(uint8 _portNum) { 173 | portNum = _portNum; 174 | switch (_portNum) { 175 | case HAL_KEY_PORT0: 176 | pinNum = P0IFG & HAL_KEY_P0_INPUT_PINS; 177 | break; 178 | 179 | case HAL_KEY_PORT1: 180 | pinNum = P1IFG & HAL_KEY_P1_INPUT_PINS; 181 | break; 182 | 183 | case HAL_KEY_PORT2: 184 | pinNum = P2IFG & HAL_KEY_P2_INPUT_PINS; 185 | break; 186 | default: 187 | break; 188 | } 189 | osal_start_timerEx(Hal_TaskID, HAL_KEY_EVENT, HAL_KEY_DEBOUNCE_VALUE); 190 | } 191 | 192 | void HalKeyEnterSleep(void) { 193 | uint8 clkcmd = CLKCONCMD; 194 | uint8 clksta = CLKCONSTA; 195 | // Switch to 16MHz before setting the DC/DC to bypass to reduce risk of flash corruption 196 | CLKCONCMD = (CLKCONCMD_16MHZ | OSC_32KHZ); 197 | // wait till clock speed stablizes 198 | while (CLKCONSTA != (CLKCONCMD_16MHZ | OSC_32KHZ)) 199 | ; 200 | 201 | CLKCONCMD = clkcmd; 202 | while (CLKCONSTA != (clksta)) 203 | ; 204 | } 205 | 206 | uint8 HalKeyExitSleep(void) { 207 | uint8 clkcmd = CLKCONCMD; 208 | // Switch to 16MHz before setting the DC/DC to on to reduce risk of flash corruption 209 | CLKCONCMD = (CLKCONCMD_16MHZ | OSC_32KHZ); 210 | // wait till clock speed stablizes 211 | while (CLKCONSTA != (CLKCONCMD_16MHZ | OSC_32KHZ)) 212 | ; 213 | 214 | CLKCONCMD = clkcmd; 215 | 216 | // /* Wake up and read keys */ 217 | return (HalKeyRead()); 218 | } 219 | 220 | #if HAL_KEY_P0_INPUT_PINS 221 | HAL_ISR_FUNCTION(halKeyPort0Isr, P0INT_VECTOR) { 222 | HAL_ENTER_ISR(); 223 | 224 | if (P0IFG & HAL_KEY_P0_INPUT_PINS) { 225 | halProcessKeyInterrupt(HAL_KEY_PORT0); 226 | } 227 | 228 | P0IFG = 0; //&= ~HAL_KEY_P0_INPUT_PINS; 229 | P0IF = 0; 230 | 231 | CLEAR_SLEEP_MODE(); 232 | HAL_EXIT_ISR(); 233 | } 234 | #endif 235 | 236 | #if HAL_KEY_P1_INPUT_PINS 237 | HAL_ISR_FUNCTION(halKeyPort1Isr, P1INT_VECTOR) { 238 | HAL_ENTER_ISR(); 239 | 240 | if (P1IFG & HAL_KEY_P1_INPUT_PINS) { 241 | halProcessKeyInterrupt(HAL_KEY_PORT1); 242 | } 243 | 244 | P1IFG = 0; //&= ~HAL_KEY_P1_INPUT_PINS; 245 | P1IF = 0; 246 | 247 | CLEAR_SLEEP_MODE(); 248 | HAL_EXIT_ISR(); 249 | } 250 | #endif 251 | 252 | #if HAL_KEY_P2_INPUT_PINS 253 | HAL_ISR_FUNCTION(halKeyPort2Isr, P2INT_VECTOR) { 254 | HAL_ENTER_ISR(); 255 | 256 | if (P2IFG & HAL_KEY_P2_INPUT_PINS) { 257 | halProcessKeyInterrupt(HAL_KEY_PORT2); 258 | } 259 | 260 | P2IFG = 0; //&= ~HAL_KEY_P2_INPUT_PINS; 261 | P2IF = 0; 262 | 263 | CLEAR_SLEEP_MODE(); 264 | HAL_EXIT_ISR(); 265 | } 266 | #endif 267 | 268 | 269 | 270 | uint8 HalKeyRead ( void ){ 271 | return 0; 272 | } -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/hal_key.h: -------------------------------------------------------------------------------- 1 | /************************************************************************************************** 2 | Filename: hal_key.h 3 | Revised: $Date: 2007-07-06 10:42:24 -0700 (Fri, 06 Jul 2007) $ 4 | Revision: $Revision: 13579 $ 5 | 6 | Description: This file contains the interface to the KEY Service. 7 | 8 | 9 | Copyright 2005-2012 Texas Instruments Incorporated. All rights reserved. 10 | 11 | IMPORTANT: Your use of this Software is limited to those specific rights 12 | granted under the terms of a software license agreement between the user 13 | who downloaded the software, his/her employer (which must be your employer) 14 | and Texas Instruments Incorporated (the "License"). You may not use this 15 | Software unless you agree to abide by the terms of the License. The License 16 | limits your use, and you acknowledge, that the Software may not be modified, 17 | copied or distributed unless embedded on a Texas Instruments microcontroller 18 | or used solely and exclusively in conjunction with a Texas Instruments radio 19 | frequency transceiver, which is integrated into your product. Other than for 20 | the foregoing purpose, you may not use, reproduce, copy, prepare derivative 21 | works of, modify, distribute, perform, display or sell this Software and/or 22 | its documentation for any purpose. 23 | 24 | YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE 25 | PROVIDED �AS IS� WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, 26 | INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, 27 | NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL 28 | TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, 29 | NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER 30 | LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES 31 | INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE 32 | OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT 33 | OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES 34 | (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. 35 | 36 | Should you have any questions regarding your right to use this Software, 37 | contact Texas Instruments Incorporated at www.TI.com. 38 | **************************************************************************************************/ 39 | 40 | #ifndef HAL_KEY_H 41 | #define HAL_KEY_H 42 | 43 | #ifdef __cplusplus 44 | extern "C" 45 | { 46 | #endif 47 | 48 | /************************************************************************************************** 49 | * INCLUDES 50 | **************************************************************************************************/ 51 | #include "hal_board.h" 52 | 53 | /************************************************************************************************** 54 | * MACROS 55 | **************************************************************************************************/ 56 | 57 | /************************************************************************************************** 58 | * CONSTANTS 59 | **************************************************************************************************/ 60 | #define HAL_KEY_BIT0 0x01 61 | #define HAL_KEY_BIT1 0x02 62 | #define HAL_KEY_BIT2 0x04 63 | #define HAL_KEY_BIT3 0x08 64 | #define HAL_KEY_BIT4 0x10 65 | #define HAL_KEY_BIT5 0x20 66 | #define HAL_KEY_BIT6 0x40 67 | #define HAL_KEY_BIT7 0x80 68 | 69 | 70 | 71 | 72 | 73 | /* Interrupt option - Enable or disable */ 74 | #define HAL_KEY_INTERRUPT_DISABLE 0x00 75 | #define HAL_KEY_INTERRUPT_ENABLE 0x01 76 | 77 | /* Key state - shift or nornal */ 78 | #define HAL_KEY_STATE_NORMAL 0x00 79 | #define HAL_KEY_STATE_SHIFT 0x01 80 | 81 | #define HAL_KEY_RISING_EDGE 0 82 | #define HAL_KEY_FALLING_EDGE 1 83 | 84 | 85 | 86 | #define HAL_KEY_PORT0 0x01 87 | #define HAL_KEY_PORT1 0x02 88 | #define HAL_KEY_PORT2 0x04 89 | 90 | #define HAL_KEY_PRESS 0x20 91 | #define HAL_KEY_RELEASE 0x40 92 | 93 | 94 | 95 | #define HAL_KEY_SW_1 0x01 // Joystick up 96 | #define HAL_KEY_SW_2 0x02 // Joystick right 97 | #define HAL_KEY_SW_5 0x04 // Joystick center 98 | #define HAL_KEY_SW_4 0x08 // Joystick left 99 | #define HAL_KEY_SW_3 0x10 // Joystick down 100 | 101 | #define HAL_KEY_SW_6 0x20 // Button S1 if available 102 | #define HAL_KEY_SW_7 0x40 // Button S2 if available 103 | 104 | /************************************************************************************************** 105 | * TYPEDEFS 106 | **************************************************************************************************/ 107 | typedef void (*halKeyCBack_t) (uint8 keys, uint8 state); 108 | 109 | /************************************************************************************************** 110 | * GLOBAL VARIABLES 111 | **************************************************************************************************/ 112 | extern bool Hal_KeyIntEnable; 113 | 114 | /************************************************************************************************** 115 | * FUNCTIONS - API 116 | **************************************************************************************************/ 117 | 118 | /* 119 | * Initialize the Key Service 120 | */ 121 | extern void HalKeyInit( void ); 122 | 123 | /* 124 | * Configure the Key Service 125 | */ 126 | extern void HalKeyConfig( bool interruptEnable, const halKeyCBack_t cback); 127 | 128 | /* 129 | * Read the Key status 130 | */ 131 | extern uint8 HalKeyRead( void); 132 | 133 | /* 134 | * Enter sleep mode, store important values 135 | */ 136 | extern void HalKeyEnterSleep ( void ); 137 | 138 | /* 139 | * Exit sleep mode, retore values 140 | */ 141 | extern uint8 HalKeyExitSleep ( void ); 142 | 143 | /* 144 | * This is for internal used by hal_driver 145 | */ 146 | extern void HalKeyPoll ( void ); 147 | 148 | /* 149 | * This is for internal used by hal_sleep 150 | */ 151 | extern bool HalKeyPressed( void ); 152 | 153 | extern uint8 hal_key_keys(void); 154 | 155 | extern uint8 hal_key_int_keys(void); 156 | 157 | /************************************************************************************************** 158 | **************************************************************************************************/ 159 | 160 | #ifdef __cplusplus 161 | } 162 | #endif 163 | 164 | #endif 165 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/mhz19.c: -------------------------------------------------------------------------------- 1 | #include "mhz19.h" 2 | #include "Debug.h" 3 | #include "OSAL.h" 4 | #include "OnBoard.h" 5 | #include "hal_led.h" 6 | #include "hal_uart.h" 7 | 8 | #ifndef CO2_UART_PORT 9 | #define CO2_UART_PORT HAL_UART_PORT_1 10 | #endif 11 | 12 | #define MHZ18_RESPONSE_LENGTH 13 13 | 14 | uint8 MHZ19_RESPONSE_LENGTH = 9; 15 | uint8 MHZ19_COMMAND_GET_PPM[] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79}; 16 | uint8 MHZ19_COMMAND_ABC_ENABLE[] = {0xFF, 0x01, 0x79, 0xA0, 0x00, 0x00, 0x00, 0x00, 0xE6}; 17 | uint8 MHZ19_COMMAND_ABC_DISABLE[] = {0xFF, 0x01, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86}; 18 | static uint8 MHZ19_COMMAND_SET_RANGE_5000PPM[] = {0xFF, 0x01, 0x99, 0x00, 0x00, 0x00, 0x13, 0x88, 0xCB}; 19 | 20 | static void flushUART(void); 21 | 22 | static void flushUART(void) { 23 | uint8 response; 24 | while (Hal_UART_RxBufLen(CO2_UART_PORT) > 0) { 25 | HalUARTRead(CO2_UART_PORT, (uint8 *)&response, 1); 26 | } 27 | } 28 | void MHZ19_SetRange5000PPM(void) { 29 | flushUART(); 30 | HalUARTWrite(CO2_UART_PORT, MHZ19_COMMAND_SET_RANGE_5000PPM, sizeof(MHZ19_COMMAND_SET_RANGE_5000PPM) / sizeof(MHZ19_COMMAND_SET_RANGE_5000PPM[0])); 31 | } 32 | 33 | void MHZ19_SetABC(bool isEnabled) { 34 | flushUART(); 35 | if (isEnabled) { 36 | HalUARTWrite(CO2_UART_PORT, MHZ19_COMMAND_ABC_ENABLE, sizeof(MHZ19_COMMAND_ABC_ENABLE) / sizeof(MHZ19_COMMAND_ABC_ENABLE[0])); 37 | } else { 38 | HalUARTWrite(CO2_UART_PORT, MHZ19_COMMAND_ABC_DISABLE, sizeof(MHZ19_COMMAND_ABC_DISABLE) / sizeof(MHZ19_COMMAND_ABC_DISABLE[0])); 39 | } 40 | } 41 | 42 | void MHZ19_RequestMeasure(void) { 43 | flushUART(); 44 | HalUARTWrite(CO2_UART_PORT, MHZ19_COMMAND_GET_PPM, sizeof(MHZ19_COMMAND_GET_PPM) / sizeof(MHZ19_COMMAND_GET_PPM[0])); 45 | } 46 | uint16 MHZ19_Read(void) { 47 | 48 | uint8 response[MHZ18_RESPONSE_LENGTH]; 49 | HalUARTRead(CO2_UART_PORT, (uint8 *)&response, sizeof(response) / sizeof(response[0])); 50 | 51 | if (response[0] != 0xFF || response[1] != 0x86) { 52 | LREPMaster("MHZ18 Invalid response\r\n"); 53 | HalLedSet(HAL_LED_ALL, HAL_LED_MODE_FLASH); 54 | return 0; 55 | } 56 | 57 | const uint16 ppm = (((uint16)response[2]) << 8) | response[3]; 58 | const int temp = ((int)response[4]) - 40; 59 | const uint8 status = response[5]; 60 | 61 | LREP("MHZ18 Received CO₂=%d ppm Status=0x%X temp=%d\r\n", ppm, status, temp); 62 | 63 | return ppm; 64 | } -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/mhz19.h: -------------------------------------------------------------------------------- 1 | #ifndef mhz19_h 2 | #define mhz19_h 3 | extern void MHZ19_RequestMeasure(void); 4 | extern uint16 MHZ19_Read(void); 5 | extern void MHZ19_SetABC(bool isEnabled); 6 | extern void MHZ19_SetRange5000PPM(void); 7 | #endif -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/senseair.c: -------------------------------------------------------------------------------- 1 | #include "senseair.h" 2 | #include "Debug.h" 3 | #include "OSAL.h" 4 | #include "OnBoard.h" 5 | #include "hal_uart.h" 6 | #include "hal_led.h" 7 | 8 | #ifndef CO2_UART_PORT 9 | #define CO2_UART_PORT HAL_UART_PORT_1 10 | #endif 11 | 12 | #define SENSEAIR_RESPONSE_LENGTH 13 13 | 14 | uint8 readCO2[] = {0xFE, 0x04, 0x00, 0x00, 0x00, 0x04, 0xE5, 0xC6}; 15 | uint8 disableABC[] = {0xFE, 0x06, 0x00, 0x1F, 0x00, 0x00, 0xAC, 0x03}; 16 | uint8 enableABC[] = {0xFE, 0x60, 0x00, 0x1F, 0x00, 0xB4, 0xAC, 0x74}; 17 | 18 | void SenseAir_SetABC(bool isEnabled) { 19 | if (isEnabled) { 20 | HalUARTWrite(CO2_UART_PORT, enableABC, sizeof(enableABC) / sizeof(enableABC[0])); 21 | } else { 22 | HalUARTWrite(CO2_UART_PORT, disableABC, sizeof(disableABC) / sizeof(disableABC[0])); 23 | } 24 | } 25 | 26 | void SenseAir_RequestMeasure(void) { 27 | HalUARTWrite(CO2_UART_PORT, readCO2, sizeof(readCO2) / sizeof(readCO2[0])); 28 | } 29 | uint16 SenseAir_Read(void) { 30 | 31 | uint8 response[SENSEAIR_RESPONSE_LENGTH]; 32 | HalUARTRead(CO2_UART_PORT, (uint8 *)&response, sizeof(response) / sizeof(response[0])); 33 | 34 | if (response[0] != 0xFE || response[1] != 0x04) { 35 | LREPMaster("Invalid response\r\n"); 36 | HalLedSet(HAL_LED_ALL, HAL_LED_MODE_FLASH); 37 | return 0; 38 | } 39 | 40 | const uint8 length = response[2]; 41 | const uint16 status = (((uint16)response[3]) << 8) | response[4]; 42 | const uint16 ppm = (((uint16)response[length + 1]) << 8) | response[length + 2]; 43 | 44 | LREP("SenseAir Received CO₂=%d ppm Status=0x%X\r\n", ppm, status); 45 | 46 | return ppm; 47 | } -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/senseair.h: -------------------------------------------------------------------------------- 1 | #ifndef SENSEAIR_H 2 | #define SENSEAIR_H 3 | extern void SenseAir_RequestMeasure(void); 4 | extern uint16 SenseAir_Read(void); 5 | extern void SenseAir_SetABC(bool isEnabled); 6 | #endif -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/stdint.h: -------------------------------------------------------------------------------- 1 | #ifndef _STDINT 2 | #define _STDINT 3 | 4 | #ifndef int8_t 5 | #define int8_t int8 6 | #endif 7 | #ifndef int16_t 8 | #define int16_t int16 9 | #endif 10 | #ifndef int32_t 11 | #define int32_t int32 12 | #endif 13 | #ifndef int64_t 14 | #define int64_t int64 15 | #endif 16 | #ifndef uint8_t 17 | #define uint8_t uint8 18 | #endif 19 | #ifndef uint16_t 20 | #define uint16_t uint16 21 | #endif 22 | #ifndef uint32_t 23 | #define uint32_t uint32 24 | #endif 25 | 26 | 27 | #define S8_C(x) x 28 | #define U8_C(x) x 29 | #define S16_C(x) x 30 | #define U16_C(x) x 31 | #define S32_C(x) x 32 | #define U32_C(x) x 33 | #define S64_C(x) x 34 | #define U64_C(x) x 35 | 36 | #endif -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/tl_resetter.c: -------------------------------------------------------------------------------- 1 | #include "tl_resetter.h" 2 | #include "Debug.h" 3 | #include "Osal_Memory.h" 4 | #include "bdb.h" 5 | #include "bdb_interface.h" 6 | #include "bdb_touchlink.h" 7 | #include "bdb_touchlink_initiator.h" 8 | #include "hal_key.h" 9 | #include "hal_led.h" 10 | 11 | #ifndef TL_RESETTER_TRIGGER_KEY 12 | #define TL_RESETTER_TRIGGER_KEY 2 13 | #endif 14 | 15 | 16 | #ifndef TL_RESETTERL_START_DELAY 17 | #define TL_RESETTERL_START_DELAY 5 * 1000 18 | #endif 19 | 20 | #ifndef TL_RESETTERL_REPEAT_DELAY 21 | #define TL_RESETTERL_REPEAT_DELAY 1 * 1000 22 | #endif 23 | 24 | #ifndef TL_RESETTER_ATTEMPTS_COUNT 25 | #define TL_RESETTER_ATTEMPTS_COUNT 10 26 | #endif 27 | 28 | #define TL_RESETTER_START_TL_EVT 0x0001 29 | #define TL_RESETTER_RETRY_TL_EVT 0x0002 30 | 31 | static void zclTouchLinkResetter_StartTL(void); 32 | static ZStatus_t zclTouchLinkResetter_TL_NotifyCb(epInfoRec_t *pData); 33 | 34 | 35 | uint8 zclTouchLinkResetter_TaskId = 0; 36 | uint8 zclTouchLinkResetter_CurrentAttempt = 0; 37 | 38 | static void zclTouchLinkResetter_StartTL(void) { 39 | LREP("zclTouchLinkResetter_StartTL attempt=%d\r\n", zclTouchLinkResetter_CurrentAttempt); 40 | HalLedSet(HAL_LED_1, HAL_LED_MODE_FLASH); 41 | if (zclTouchLinkResetter_CurrentAttempt < TL_RESETTER_ATTEMPTS_COUNT) { 42 | touchLinkInitiator_StartDevDisc(); 43 | zclTouchLinkResetter_CurrentAttempt += 1; 44 | osal_start_timerEx(zclTouchLinkResetter_TaskId, TL_RESETTER_RETRY_TL_EVT, TL_RESETTERL_REPEAT_DELAY); 45 | } 46 | } 47 | 48 | ZStatus_t zclTouchLinkResetter_TL_NotifyCb(epInfoRec_t *pData) { 49 | LREPMaster("zclTouchLinkResetter_TL_NotifyCb\r\n"); 50 | osal_stop_timerEx(zclTouchLinkResetter_TaskId, TL_RESETTER_RETRY_TL_EVT); 51 | touchLinkInitiator_ResetToFNSelectedTarget(); 52 | HalLedSet(HAL_LED_1, HAL_LED_MODE_OFF); 53 | return ZSuccess; 54 | } 55 | 56 | void zclTouchLinkRestter_Init(uint8 task_id) { 57 | zclTouchLinkResetter_TaskId = task_id; 58 | touchLinkInitiator_RegisterNotifyTLCB(zclTouchLinkResetter_TL_NotifyCb); 59 | } 60 | 61 | uint16 zclTouchLinkRestter_event_loop(uint8 task_id, uint16 events) { 62 | LREP("zclTouchLinkRestter_event_loop 0x%X\r\n", events); 63 | if (events & TL_RESETTER_START_TL_EVT) { 64 | zclTouchLinkResetter_CurrentAttempt = 0; 65 | zclTouchLinkResetter_StartTL(); 66 | return (events ^ TL_RESETTER_START_TL_EVT); 67 | } 68 | 69 | if (events & TL_RESETTER_RETRY_TL_EVT) { 70 | LREPMaster("TL_RESETTER_RETRY_TL_EVT\r\n"); 71 | zclTouchLinkResetter_StartTL(); 72 | return (events ^ TL_RESETTER_RETRY_TL_EVT); 73 | } 74 | 75 | return 0; 76 | } 77 | 78 | void zclTouchLinkRestter_HandleKeys(uint8 portAndAction, uint8 keyCode) { 79 | if (portAndAction & HAL_KEY_PRESS) { 80 | if (keyCode == TL_RESETTER_TRIGGER_KEY) { 81 | osal_start_timerEx(zclTouchLinkResetter_TaskId, TL_RESETTER_START_TL_EVT, TL_RESETTERL_START_DELAY); 82 | } 83 | } else { 84 | osal_stop_timerEx(zclTouchLinkResetter_TaskId, TL_RESETTER_START_TL_EVT); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/tl_resetter.h: -------------------------------------------------------------------------------- 1 | #ifndef TL_RESETTER_H 2 | #define TL_RESETTER_H 3 | 4 | 5 | extern void zclTouchLinkRestter_Init(uint8 task_id); 6 | extern uint16 zclTouchLinkRestter_event_loop(uint8 task_id, uint16 events); 7 | extern void zclTouchLinkRestter_HandleKeys(uint8 portAndAction, uint8 keyCode); 8 | #endif -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/utils.c: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | #include "hal_adc.h" 3 | 4 | // #define MAX(x, y) (((x) > (y)) ? (x) : (y)) 5 | // #define MIN(x, y) (((x) < (y)) ? (x) : (y)) 6 | 7 | double mapRange(double a1, double a2, double b1, double b2, double s) { 8 | double result = b1 + (s - a1) * (b2 - b1) / (a2 - a1); 9 | return MIN(b2, MAX(result, b1)); 10 | } 11 | 12 | uint16 adcReadSampled(uint8 channel, uint8 resolution, uint8 reference, uint8 samplesCount) { 13 | HalAdcSetReference(reference); 14 | uint32 samplesSum = 0; 15 | for (uint8 i = 0; i < samplesCount; i++) { 16 | samplesSum += HalAdcRead(channel, resolution); 17 | } 18 | return samplesSum /samplesCount; 19 | } 20 | -------------------------------------------------------------------------------- /PROJECT SOURCE/TH_SONOFF/zstack-lib/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef UTILS_H 2 | #define UTILS_H 3 | extern double mapRange(double a1, double a2, double b1, double b2, double s); 4 | 5 | extern uint16 adcReadSampled(uint8 channel, uint8 resolution, uint8 reference, uint8 samplesCount); 6 | 7 | 8 | #undef P 9 | #undef INP 10 | #define INP INP 11 | #undef DIR 12 | #define DIR DIR 13 | #undef SEL 14 | #define SEL SEL 15 | 16 | // General I/O definitions 17 | #define IO_GIO 0 // General purpose I/O 18 | #define IO_PER 1 // Peripheral function 19 | #define IO_IN 0 // Input pin 20 | #define IO_OUT 1 // Output pin 21 | #define IO_PUD 0 // Pullup/pulldn input 22 | #define IO_TRI 1 // Tri-state input 23 | #define IO_PUP 0 // Pull-up input pin 24 | #define IO_PDN 1 // Pull-down input pin 25 | 26 | /* I/O PORT CONFIGURATION */ 27 | #define CAT1(x, y) x##y // Concatenates 2 strings 28 | #define CAT2(x, y) CAT1(x, y) // Forces evaluation of CAT1 29 | 30 | // OCM port I/O defintions 31 | // Builds I/O port name: PNAME(1,INP) ==> P1INP 32 | #define PNAME(y, z) CAT2(P, CAT2(y, z)) 33 | // Builds I/O bit name: BNAME(1,2) ==> P1_2 34 | #define BNAME(port, pin) CAT2(CAT2(P, port), CAT2(_, pin)) 35 | 36 | 37 | #define IO_DIR_PORT_PIN(port, pin, dir) \ 38 | { \ 39 | if (dir == IO_OUT) \ 40 | PNAME(port, DIR) |= (1 << (pin)); \ 41 | else \ 42 | PNAME(port, DIR) &= ~(1 << (pin)); \ 43 | } 44 | 45 | 46 | 47 | #define IO_FUNC_PORT_PIN(port, pin, func) \ 48 | { \ 49 | if (port < 2) { \ 50 | if (func == IO_PER) \ 51 | PNAME(port, SEL) |= (1 << (pin)); \ 52 | else \ 53 | PNAME(port, SEL) &= ~(1 << (pin)); \ 54 | } else { \ 55 | if (func == IO_PER) \ 56 | P2SEL |= (1 << (pin >> 1)); \ 57 | else \ 58 | P2SEL &= ~(1 << (pin >> 1)); \ 59 | } \ 60 | } 61 | 62 | #define IO_IMODE_PORT_PIN(port, pin, mode) \ 63 | { \ 64 | if (mode == IO_TRI) \ 65 | PNAME(port, INP) |= (1 << (pin)); \ 66 | else \ 67 | PNAME(port, INP) &= ~(1 << (pin)); \ 68 | } 69 | 70 | #define IO_PUD_PORT(port, dir) \ 71 | { \ 72 | if (dir == IO_PDN) \ 73 | P2INP |= (1 << (port + 5)); \ 74 | else \ 75 | P2INP &= ~(1 << (port + 5)); \ 76 | } 77 | #endif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SONOFF-SNZB-02-Temperature-and-humidity-sensor 2 | 3 | Поблагодарить автора: https://www.donationalerts.com/r/efektalab 4 | 5 | Thank the author: http://www.donationalerts.ru/r/EfektaLab 6 | 7 | Телеграм чат DIY Devices - https://t.me/diy_devices 8 | 9 | Продажа DIY Устройств - https://t.me/diydevmart 10 | 11 | Альтернативная версия встроенного ПО для датчика температуры и влажности SONOFF SNZB-02. Регулируемый интервал сна через сеть zigbee, функциональность термостата и гидростата, стандартные кластеры температуры и влажности, поддержка привязки. Аппаратное обеспечение 252530, hdc1080. (RU) 12 | 13 | An alternative firmware version for the SONOFF SNZB-02 temperature and humidity sensor. Adjustable sleep interval via zigbee network, thermostat and hydrostat functionality, standard temperature and humidity clusters, binding support. Hardware сс2530, hdc1080. (ENG) 14 | 15 | #### Video: 16 | 17 | #### Telegram DiyDev - https://t.me/diy_devices 18 | 19 | #### Instagram - https://www.instagram.com/efektalab/ 20 | 21 | #### Order PCB of others for my projects - https://www.pcbway.com/setinvite.aspx?inviteid=550959 22 | 23 | ![SONOFF SNZB-02 Temperature and humidity sensor](https://github.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/blob/main/IMAGES/photo_2022-09-04_22-57-46.jpg) 24 | 25 | ![SONOFF SNZB-02 Temperature and humidity sensor](https://github.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/blob/main/IMAGES/photo_2022-09-04_22-57-47.jpg) 26 | 27 | ![SONOFF SNZB-02 Temperature and humidity sensor](https://github.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/blob/main/IMAGES/01.png) 28 | 29 | 30 | ![SONOFF SNZB-02 Temperature and humidity sensor](https://github.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/blob/main/IMAGES/photo_2022-09-08_18-49-16.jpg) 31 | 32 | ![SONOFF SNZB-02 Temperature and humidity sensor](https://github.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/blob/main/IMAGES/photo_2022-09-08_19-19-08.jpg) 33 | 34 | --- 35 | 36 | ### How to flash the device 37 | 38 | 1. Download the Smart RF Flash Programmer V1 https://www.ti.com/tool/FLASH-PROGRAMMER 39 | 40 | 2. Open the application select the HEX firmware file 41 | 42 | 3. Connect the device with wires to CCDebugger, first erase the chip, then flash it. 43 | 44 | --- 45 | 46 | ### How to install IAR 47 | 48 | https://github.com/ZigDevWiki/zigdevwiki.github.io/blob/main/docs/Begin/IAR_install.md 49 | 50 | https://github.com/sigma7i/zigbee-wiki/wiki/zigbee-firmware-install (RU) 51 | 52 | --- 53 | 54 | ### How to add support yourself in MJD 55 | 56 | 1. https://github.com/smartboxchannel/Plant-Watering-Sensor-Zigbee/blob/main/majordomo-zigbee2mqtt/README.md (MJD https://mjdm.ru/) 57 | 58 | --- 59 | 60 | ### How to join: 61 | #### If device in FN(factory new) state: 62 | ##### one way 63 | 1. Open z2m, make sure that joining is prohibited 64 | 2. Insert the battery into the device 65 | 3. Click on the icon in z2m - allow joining (you have 300 seconds to add the device) 66 | 4. Go to the LOGS tab 67 | 5. Press the reset button on the device (the join procedure will begin, еhe device starts flashing the LED repeatedly) 68 | 69 | ##### another way 70 | 1. Open z2m, make sure that joining is prohibited 71 | 2. Insert the battery into the device 72 | 3. Click on the icon in z2m - allow joining (you have 300 seconds to add the device) 73 | 4. Go to the LOGS tab 74 | 5. Press and hold button (1) for 2-3 seconds, until device start flashing the LED repeatedly 75 | 76 | 77 | #### If device in a network: 78 | ##### one way 79 | 1. Hold button (1) for 10 seconds, this will reset device to FN(factory new) status 80 | 2. Click on the icon in z2m - allow joining (you have 180 seconds to add the device) 81 | 3. Go to the LOGS tab 82 | 5. Press and hold button (1) for 2-3 seconds, until device start flashing the LED repeatedly 83 | 84 | ##### another way 85 | 1. Find the device in the list of z2m devices and delete it by applying force remove 86 | 2. Click on the icon in z2m - allow joining (you have 300 seconds to add the device) 87 | 3. Go to the LOGS tab 88 | 4. Press the reset button on the device (the join procedure will begin, еhe device starts flashing the LED repeatedly) 89 | 90 | ### How to configure: 91 | 92 | 1. Open configuration.yaml in the editor. 93 | 2. Find the friendly_name of your device. 94 | 3. For example to add a temperature calibration you need to add the string temperature_calibration: 5. 95 | 96 | ![Plant-Watering-Sensor-Zigbee2](https://github.com/smartboxchannel/Plant-Watering-Sensor-Zigbee/blob/main/IMAGES/2000.png) 97 | 98 | ### Troubleshooting 99 | 100 | If a device does not connect to your coordinator, please try the following: 101 | 102 | 1. Power off all routers in your network. 103 | 2. Move the device near to your coordinator (about 1 meter). 104 | or if you cannot disable routers (for example, internal switches), you may try the following: 105 | 2.1. Disconnect an external antenna from your coordinator. 106 | 2.2. Move a device to your coordinator closely (1-3 centimeters). 107 | 3. Power on, power on the device. 108 | 4. Restart your coordinator (for example, restart Zigbee2MQTT if you use it). 109 | 110 | If the device has not fully passed the join 111 | 112 | 1. If the device is visible in the list of z2m devices, remove it by applying force remove 113 | 2. Restart your coordinator (for example, restart Zigbee2MQTT if you use it). 114 | 3. Click on the icon in z2m - allow joining (you have 180 seconds to add the device) 115 | 4. Go to the LOGS tab 116 | 5. Press and hold button (1) for 2-3 seconds, until device start flashing the LED repeatedly 117 | 6. Wait, in case of successfull join, device will flash led 5 times, if join failed, device will flash led 2 times 118 | 119 | 120 | 121 | ### Other checks 122 | 123 | Please, ensure the following: 124 | 125 | 1. Your power source is OK (a battery has more than 3V). You can temporarily use an external power source for testings (for example, from a debugger). 126 | 2. The RF part of your E18 board works. You can upload another firmware to it and try to pair it with your coordinator. Or you may use another coordinator and build a separate Zigbee network for testing. 127 | 3. Your coordinator has free slots for direct connections. 128 | 4. You permit joining on your coordinator. 129 | 5. Your device did not join to other opened Zigbee network. When you press and hold the button, it should flash every 3-4 seconds. It means that the device in the joining state. 130 | 131 | -------------------------------------------------------------------------------- /SCHEMATIC/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /SCHEMATIC/Schematic_ZB-TH01.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smartboxchannel/SONOFF-SNZB-02-Temperature-and-humidity-sensor/3a549811bf287de440613add3a3d46116823ea94/SCHEMATIC/Schematic_ZB-TH01.pdf -------------------------------------------------------------------------------- /Z2M CONVERTER/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Z2M CONVERTER/SNZB-02_EFEKTA.js: -------------------------------------------------------------------------------- 1 | const fz = require('zigbee-herdsman-converters/converters/fromZigbee'); 2 | const tz = require('zigbee-herdsman-converters/converters/toZigbee'); 3 | const exposes = require('zigbee-herdsman-converters/lib/exposes'); 4 | const reporting = require('zigbee-herdsman-converters/lib/reporting'); 5 | const e = exposes.presets; 6 | const ea = exposes.access; 7 | 8 | const tzLocal = { 9 | node_config: { 10 | key: ['report_delay', 'comparison_previous_data'], 11 | convertSet: async (entity, key, rawValue, meta) => { 12 | const lookup = {'OFF': 0x00, 'ON': 0x01}; 13 | const value = lookup.hasOwnProperty(rawValue) ? lookup[rawValue] : parseInt(rawValue, 10); 14 | const payloads = { 15 | report_delay: ['genPowerCfg', {0x0201: {value, type: 0x21}}], 16 | comparison_previous_data: ['genPowerCfg', {0x0205: {value, type: 0x10}}], 17 | }; 18 | await entity.write(payloads[key][0], payloads[key][1]); 19 | return { 20 | state: {[key]: rawValue}, 21 | }; 22 | }, 23 | }, 24 | termostat_config: { 25 | key: ['high_temp', 'low_temp', 'enable_temp', 'invert_logic_temp'], 26 | convertSet: async (entity, key, rawValue, meta) => { 27 | const lookup = {'OFF': 0x00, 'ON': 0x01}; 28 | const value = lookup.hasOwnProperty(rawValue) ? lookup[rawValue] : parseInt(rawValue, 10); 29 | const payloads = { 30 | high_temp: ['msTemperatureMeasurement', {0x0221: {value, type: 0x29}}], 31 | low_temp: ['msTemperatureMeasurement', {0x0222: {value, type: 0x29}}], 32 | enable_temp: ['msTemperatureMeasurement', {0x0220: {value, type: 0x10}}], 33 | invert_logic_temp: ['msTemperatureMeasurement', {0x0225: {value, type: 0x10}}], 34 | }; 35 | await entity.write(payloads[key][0], payloads[key][1]); 36 | return { 37 | state: {[key]: rawValue}, 38 | }; 39 | }, 40 | }, 41 | hydrostat_config: { 42 | key: ['high_hum', 'low_hum', 'enable_hum', 'invert_logic_hum'], 43 | convertSet: async (entity, key, rawValue, meta) => { 44 | const lookup = {'OFF': 0x00, 'ON': 0x01}; 45 | const value = lookup.hasOwnProperty(rawValue) ? lookup[rawValue] : parseInt(rawValue, 10); 46 | const payloads = { 47 | high_hum: ['msRelativeHumidity', {0x0221: {value, type: 0x21}}], 48 | low_hum: ['msRelativeHumidity', {0x0222: {value, type: 0x21}}], 49 | enable_hum: ['msRelativeHumidity', {0x0220: {value, type: 0x10}}], 50 | invert_logic_hum: ['msRelativeHumidity', {0x0225: {value, type: 0x10}}], 51 | }; 52 | await entity.write(payloads[key][0], payloads[key][1]); 53 | return { 54 | state: {[key]: rawValue}, 55 | }; 56 | }, 57 | }, 58 | temperaturef_config: { 59 | key: ['temperature_offset'], 60 | convertSet: async (entity, key, rawValue, meta) => { 61 | const value = parseFloat(rawValue)*10; 62 | const payloads = { 63 | temperature_offset: ['msTemperatureMeasurement', {0x0210: {value, type: 0x29}}], 64 | }; 65 | await entity.write(payloads[key][0], payloads[key][1]); 66 | return { 67 | state: {[key]: rawValue}, 68 | }; 69 | }, 70 | }, 71 | humidityf_config: { 72 | key: ['humidity_offset'], 73 | convertSet: async (entity, key, rawValue, meta) => { 74 | const value = parseFloat(rawValue)*10; 75 | const payloads = { 76 | humidity_offset: ['msRelativeHumidity', {0x0210: {value, type: 0x29}}], 77 | }; 78 | await entity.write(payloads[key][0], payloads[key][1]); 79 | return { 80 | state: {[key]: rawValue}, 81 | }; 82 | }, 83 | }, 84 | }; 85 | 86 | const fzLocal = { 87 | node_config: { 88 | cluster: 'genPowerCfg', 89 | type: ['attributeReport', 'readResponse'], 90 | convert: (model, msg, publish, options, meta) => { 91 | const result = {}; 92 | if (msg.data.hasOwnProperty(0x0201)) { 93 | result.report_delay = msg.data[0x0201]; 94 | } 95 | if (msg.data.hasOwnProperty(0x0205)) { 96 | result.comparison_previous_data = ['OFF', 'ON'][msg.data[0x0205]]; 97 | } 98 | return result; 99 | }, 100 | }, 101 | termostat_config: { 102 | cluster: 'msTemperatureMeasurement', 103 | type: ['attributeReport', 'readResponse'], 104 | convert: (model, msg, publish, options, meta) => { 105 | const result = {}; 106 | if (msg.data.hasOwnProperty(0x0221)) { 107 | result.high_temp = msg.data[0x0221]; 108 | } 109 | if (msg.data.hasOwnProperty(0x0222)) { 110 | result.low_temp = msg.data[0x0222]; 111 | } 112 | if (msg.data.hasOwnProperty(0x0220)) { 113 | result.enable_temp = ['OFF', 'ON'][msg.data[0x0220]]; 114 | } 115 | if (msg.data.hasOwnProperty(0x0225)) { 116 | result.invert_logic_temp = ['OFF', 'ON'][msg.data[0x0225]]; 117 | } 118 | return result; 119 | }, 120 | }, 121 | hydrostat_config: { 122 | cluster: 'msRelativeHumidity', 123 | type: ['attributeReport', 'readResponse'], 124 | convert: (model, msg, publish, options, meta) => { 125 | const result = {}; 126 | if (msg.data.hasOwnProperty(0x0221)) { 127 | result.high_hum = msg.data[0x0221]; 128 | } 129 | if (msg.data.hasOwnProperty(0x0222)) { 130 | result.low_hum = msg.data[0x0222]; 131 | } 132 | if (msg.data.hasOwnProperty(0x0220)) { 133 | result.enable_hum = ['OFF', 'ON'][msg.data[0x0220]]; 134 | } 135 | if (msg.data.hasOwnProperty(0x0225)) { 136 | result.invert_logic_hum = ['OFF', 'ON'][msg.data[0x0225]]; 137 | } 138 | return result; 139 | }, 140 | }, 141 | temperaturef_config: { 142 | cluster: 'msTemperatureMeasurement', 143 | type: ['attributeReport', 'readResponse'], 144 | convert: (model, msg, publish, options, meta) => { 145 | const result = {}; 146 | if (msg.data.hasOwnProperty(0x0210)) { 147 | result.temperature_offset = parseFloat(msg.data[0x0210])/10.0; 148 | } 149 | return result; 150 | }, 151 | }, 152 | humidityf_config: { 153 | cluster: 'msRelativeHumidity', 154 | type: ['attributeReport', 'readResponse'], 155 | convert: (model, msg, publish, options, meta) => { 156 | const result = {}; 157 | if (msg.data.hasOwnProperty(0x0210)) { 158 | result.humidity_offset = parseFloat(msg.data[0x0210])/10.0; 159 | } 160 | return result; 161 | }, 162 | }, 163 | }; 164 | 165 | const definition = { 166 | zigbeeModel: ['SNZB-02_EFEKTA'], 167 | model: 'SNZB-02_EFEKTA', 168 | vendor: 'Custom devices (DiY)', 169 | description: 'EFEKTA_SS - temperature and humidity sensors with increased battery life', 170 | fromZigbee: [fz.temperature, fz.humidity, fz.battery, fzLocal.termostat_config, fzLocal.hydrostat_config, fzLocal.node_config, 171 | fzLocal.temperaturef_config, fzLocal.humidityf_config], 172 | toZigbee: [tz.factory_reset, tzLocal.termostat_config, tzLocal.hydrostat_config, tzLocal.node_config, 173 | tzLocal.temperaturef_config, tzLocal.humidityf_config], 174 | configure: async (device, coordinatorEndpoint, logger) => { 175 | const endpointOne = device.getEndpoint(1); 176 | await reporting.bind(endpointOne, coordinatorEndpoint, ['genPowerCfg', 'msTemperatureMeasurement', 'msRelativeHumidity']); 177 | }, 178 | exposes: [e.temperature(), e.humidity(), e.battery(), e.battery_low(), e.battery_voltage(), 179 | exposes.numeric('report_delay', ea.STATE_SET).withUnit('Seconds').withDescription('Adjust Report Delay. Setting the time in seconds, by default 60 seconds') 180 | .withValueMin(10).withValueMax(3600), 181 | exposes.binary('comparison_previous_data', ea.STATE_SET, 'ON', 'OFF').withDescription('Enable сontrol of comparison with previous data'), 182 | exposes.numeric('temperature_offset', ea.STATE_SET).withUnit('°C').withValueStep(0.1).withDescription('Adjust temperature') 183 | .withValueMin(-50.0).withValueMax(50.0), 184 | exposes.numeric('humidity_offset', ea.STATE_SET).withUnit('%').withValueStep(0.1).withDescription('Adjust humidity') 185 | .withValueMin(-50.0).withValueMax(50.0), 186 | exposes.binary('enable_temp', ea.STATE_SET, 'ON', 'OFF').withDescription('Enable Temperature Control'), 187 | exposes.binary('invert_logic_temp', ea.STATE_SET, 'ON', 'OFF').withDescription('Invert Logic Temperature Control'), 188 | exposes.numeric('high_temp', ea.STATE_SET).withUnit('C').withDescription('Setting High Temperature Border') 189 | .withValueMin(-5).withValueMax(50), 190 | exposes.numeric('low_temp', ea.STATE_SET).withUnit('C').withDescription('Setting Low Temperature Border') 191 | .withValueMin(-5).withValueMax(50), 192 | exposes.binary('enable_hum', ea.STATE_SET, 'ON', 'OFF').withDescription('Enable Humidity Control'), 193 | exposes.binary('invert_logic_hum', ea.STATE_SET, 'ON', 'OFF').withDescription('Invert Logoc Humidity Control'), 194 | exposes.numeric('high_hum', ea.STATE_SET).withUnit('C').withDescription('Setting High Humidity Border') 195 | .withValueMin(0).withValueMax(99), 196 | exposes.numeric('low_hum', ea.STATE_SET).withUnit('C').withDescription('Setting Low Humidity Border') 197 | .withValueMin(0).withValueMax(99)], 198 | }; 199 | 200 | module.exports = definition; 201 | -------------------------------------------------------------------------------- /Z2M CONVERTER/__SNZB-02_EFEKTA_OLD_VERSION.js: -------------------------------------------------------------------------------- 1 | const fz = require('zigbee-herdsman-converters/converters/fromZigbee'); 2 | const tz = require('zigbee-herdsman-converters/converters/toZigbee'); 3 | const exposes = require('zigbee-herdsman-converters/lib/exposes'); 4 | const reporting = require('zigbee-herdsman-converters/lib/reporting'); 5 | const e = exposes.presets; 6 | const ea = exposes.access; 7 | 8 | const tzLocal = { 9 | node_config: { 10 | key: ['report_delay'], 11 | convertSet: async (entity, key, rawValue, meta) => { 12 | const lookup = {'OFF': 0x00, 'ON': 0x01}; 13 | const value = lookup.hasOwnProperty(rawValue) ? lookup[rawValue] : parseInt(rawValue, 10); 14 | const payloads = { 15 | report_delay: ['genPowerCfg', {0x0201: {value, type: 0x21}}], 16 | }; 17 | await entity.write(payloads[key][0], payloads[key][1]); 18 | return { 19 | state: {[key]: rawValue}, 20 | }; 21 | }, 22 | }, 23 | termostat_config: { 24 | key: ['high_temp', 'low_temp', 'enable_temp'], 25 | convertSet: async (entity, key, rawValue, meta) => { 26 | const lookup = {'OFF': 0x00, 'ON': 0x01}; 27 | const value = lookup.hasOwnProperty(rawValue) ? lookup[rawValue] : parseInt(rawValue, 10); 28 | const payloads = { 29 | high_temp: ['msTemperatureMeasurement', {0x0202: {value, type: 0x29}}], 30 | low_temp: ['msTemperatureMeasurement', {0x0203: {value, type: 0x29}}], 31 | enable_temp: ['msTemperatureMeasurement', {0x0206: {value, type: 0x10}}], 32 | }; 33 | await entity.write(payloads[key][0], payloads[key][1]); 34 | return { 35 | state: {[key]: rawValue}, 36 | }; 37 | }, 38 | }, 39 | hydrostat_config: { 40 | key: ['high_hum', 'low_hum', 'enable_hum'], 41 | convertSet: async (entity, key, rawValue, meta) => { 42 | const lookup = {'OFF': 0x00, 'ON': 0x01}; 43 | const value = lookup.hasOwnProperty(rawValue) ? lookup[rawValue] : parseInt(rawValue, 10); 44 | const payloads = { 45 | high_hum: ['msRelativeHumidity', {0x0204: {value, type: 0x21}}], 46 | low_hum: ['msRelativeHumidity', {0x0205: {value, type: 0x21}}], 47 | enable_hum: ['msRelativeHumidity', {0x0207: {value, type: 0x10}}], 48 | }; 49 | await entity.write(payloads[key][0], payloads[key][1]); 50 | return { 51 | state: {[key]: rawValue}, 52 | }; 53 | }, 54 | }, 55 | }; 56 | 57 | const fzLocal = { 58 | node_config: { 59 | cluster: 'genPowerCfg', 60 | type: ['attributeReport', 'readResponse'], 61 | convert: (model, msg, publish, options, meta) => { 62 | const result = {}; 63 | if (msg.data.hasOwnProperty(0x0201)) { 64 | result.report_delay = msg.data[0x0201]; 65 | } 66 | return result; 67 | }, 68 | }, 69 | termostat_config: { 70 | cluster: 'msTemperatureMeasurement', 71 | type: ['attributeReport', 'readResponse'], 72 | convert: (model, msg, publish, options, meta) => { 73 | const result = {}; 74 | if (msg.data.hasOwnProperty(0x0202)) { 75 | result.high_temp = msg.data[0x0202]; 76 | } 77 | if (msg.data.hasOwnProperty(0x0203)) { 78 | result.low_temp = msg.data[0x0203]; 79 | } 80 | if (msg.data.hasOwnProperty(0x0206)) { 81 | result.enable_temp = ['OFF', 'ON'][msg.data[0x0206]]; 82 | } 83 | return result; 84 | }, 85 | }, 86 | hydrostat_config: { 87 | cluster: 'msRelativeHumidity', 88 | type: ['attributeReport', 'readResponse'], 89 | convert: (model, msg, publish, options, meta) => { 90 | const result = {}; 91 | if (msg.data.hasOwnProperty(0x0204)) { 92 | result.high_hum = msg.data[0x0204]; 93 | } 94 | if (msg.data.hasOwnProperty(0x0205)) { 95 | result.low_hum = msg.data[0x0205]; 96 | } 97 | if (msg.data.hasOwnProperty(0x0207)) { 98 | result.enable_hum = ['OFF', 'ON'][msg.data[0x0207]]; 99 | } 100 | return result; 101 | }, 102 | }, 103 | }; 104 | 105 | const definition = { 106 | zigbeeModel: ['SNZB-02_EFEKTA'], 107 | model: 'SNZB-02_EFEKTA', 108 | vendor: 'Custom devices (DiY)', 109 | description: 'An alternative view from EfektaLab on the SONOFF SNZB-02 sensor, DIY', 110 | fromZigbee: [fz.temperature, fz.humidity, fz.battery, fzLocal.termostat_config, fzLocal.hydrostat_config, fzLocal.node_config], 111 | toZigbee: [tz.factory_reset, tzLocal.termostat_config, tzLocal.hydrostat_config, tzLocal.node_config], 112 | configure: async (device, coordinatorEndpoint, logger) => { 113 | const endpoint = device.getEndpoint(1); 114 | await reporting.bind(endpoint, coordinatorEndpoint, [ 115 | 'genPowerCfg', 'msTemperatureMeasurement', 'msRelativeHumidity']); 116 | const overides = {min: 0, max: 43200, change: 0}; 117 | await reporting.batteryVoltage(endpoint, overides); 118 | await reporting.batteryPercentageRemaining(endpoint, overides); 119 | }, 120 | exposes: [e.battery(), e.temperature(), e.humidity(), 121 | exposes.numeric('report_delay', ea.STATE_SET).withUnit('Minutes').withDescription('Adjust Report Delay. Setting the time in minutes, by default 5 minutes') 122 | .withValueMin(1).withValueMax(60), 123 | exposes.binary('enable_temp', ea.STATE_SET, 'ON', 'OFF').withDescription('Enable Temperature Control'), 124 | exposes.numeric('high_temp', ea.STATE_SET).withUnit('C').withDescription('Setting High Temperature Border') 125 | .withValueMin(-5).withValueMax(50), 126 | exposes.numeric('low_temp', ea.STATE_SET).withUnit('C').withDescription('Setting Low Temperature Border') 127 | .withValueMin(-5).withValueMax(50), 128 | exposes.binary('enable_hum', ea.STATE_SET, 'ON', 'OFF').withDescription('Enable Humidity Control'), 129 | exposes.numeric('high_hum', ea.STATE_SET).withUnit('C').withDescription('Setting High Humidity Border') 130 | .withValueMin(0).withValueMax(99), 131 | exposes.numeric('low_hum', ea.STATE_SET).withUnit('C').withDescription('Setting Low Humidity Border') 132 | .withValueMin(0).withValueMax(99)], 133 | }; 134 | 135 | module.exports = definition; 136 | --------------------------------------------------------------------------------