1 // *********************************************************************
    2 //   Custom DPA Handler code example - PIR controlled lighting demo    *
    3 // *********************************************************************
    4 // Copyright (c) MICRORISC s.r.o.
    5 //
    6 // File:    $RCSfile: CustomDpaHandler-PIRlighting.c,v $
    7 // Version: $Revision: 1.31 $
    8 // Date:    $Date: 2022/02/25 09:41:25 $
    9 //
   10 // Revision history:
   11 //   2022/02/24  Release for DPA 4.17
   12 //   2017/03/13  Release for DPA 3.00
   13 //   2015/08/05  Release for DPA 2.20
   14 //
   15 // *********************************************************************
   16 
   17 // Online DPA documentation https://doc.iqrf.org/DpaTechGuide/
   18 
   19 // Default IQRF include (modify the path according to your setup)
   20 #include "IQRF.h"
   21 
   22 // Default DPA header (modify the path according to your setup)
   23 #include "DPA.h"
   24 // Default Custom DPA Handler header (modify the path according to your setup)
   25 #include "DPAcustomHandler.h"
   26 
   27 // This is an example of PIR controlled lighting. The application can be configured and controlled by EEPROM and RAM DPA peripherals respectively.
   28 //
   29 // When a PIR input is active the device sends non-network Peer2Peer packet that contains the address of the device.
   30 // PIR input is then inactive for next PIRdelay seconds in order not to jam with many same packets.
   31 // Other nodes that receive the Peer2Peer packet will set the LIGHT output if the address of the sender matches any of the condition bytes
   32 // from the 16 byte long list stored at EEPROM peripheral from address 1. The light will stay on for number of second stored at EEPROM peripheral at address 0.
   33 // Condition bytes:
   34 //  0         End of the condition bytes list
   35 //  255       Any node will switch the light on. This condition byte overrides condition bytes described below.
   36 //  1 - 239   Only node having address equal this value switches the light on.
   37 //  240 - 254 Only node having address that differs ( ConditionByte - 239 ) from my address maximum switches the light on.
   38 //            E.g. when my address is 10 and condition byte is 241, then only nodes with address 8-12 would switch my light on.
   39 //
   40 // If bit PeripheralRam[0].0 is set, PIR input is inactive. This allows to disable PIR detectors e.g. during the day.
   41 //
   42 // ! Please note that User peer-to-peer packets must be enabled at the HWP configuration
   43 // This example works only at STD mode, not at LP mode
   44 
   45 // Initialize the EEPROM peripheral area
   46 #pragma cdata[ __EESTART + PERIPHERAL_EEPROM_START ] = \
   47   /* Set light timeout to 5 seconds. */ \
   48   5, \
   49   /* Allow switching the light on only by nodes with address 1 and address 2 and with address that differs 2 maximum. */ \
   50   1, 2, MAX_ADDRESS + 2, \
   51   /* End of the list. */ \
   52   0
   53 // Note: symbol MAX_ADDRESS equals 239
   54 
   55 //############################################################################################
   56 
   57 // PIR input
   58 #define PIR   buttonPressed
   59 // Light output
   60 #define LIGHT _LEDG
   61 
   62 // Fixed PIR repetition delay [s]
   63 #define PIRdelay    2
   64 
   65 //############################################################################################
   66 
   67 // Length of the address list
   68 #define ADDR_LIST_LEN 16
   69 
   70 // 40 ms counter used to measure 1 s
   71 static uns8 tmrCounter40ms;
   72 
   73 // Light on counter
   74 static uns8 lightTimeout;
   75 
   76 // Initial light timeout counter value, read from EEPROM peripheral at address 0
   77 static uns8 lightTimeoutSetting;
   78 
   79 // Switches the light on, initializes timeout
   80 void LightOn();
   81 // Starts new second
   82 void StartSecond();
   83 
   84 // Must be the 1st defined function in the source code in order to be placed at the correct FLASH location!
   85 //############################################################################################
   86 bit CustomDpaHandler()
   87 //############################################################################################
   88 {
   89   // Handler presence mark
   90   clrwdt();
   91 
   92   // Place for local static variables used only within CustomDpaHandler() among more events
   93 
   94   // If TRUE, PIR was activated and after timeout
   95   static bit PIRactivated;
   96 
   97   // Detect DPA event to handle
   98   switch ( GetDpaEvent() )
   99   {
  100     // -------------------------------------------------
  101     case DpaEvent_Interrupt:
  102       // Do an extra quick background interrupt work
  103       // ! The time spent handling this event is critical.If there is no interrupt to handle return immediately otherwise keep the code as fast as possible.
  104       // ! Make sure the event is the 1st case in the main switch statement at the handler routine.This ensures that the event is handled as the 1st one.
  105       // ! It is desirable that this event is handled with immediate return even if it is not used by the custom handler because the Interrupt event is raised on every MCU interrupt and the "empty" return handler ensures the shortest possible interrupt routine response time.
  106       // ! Only global variables or local ones marked by static keyword can be used to allow reentrancy.
  107       // ! Make sure race condition does not occur when accessing those variables at other places.
  108       // ! Make sure( inspect.lst file generated by C compiler ) compiler does not create any hidden temporary local variable( occurs when using division, multiplication or bit shifts ) at the event handler code.The name of such variable is usually Cnumbercnt.
  109       // ! Do not call any OS functions except setINDFx().
  110       // ! Do not use any OS variables especially for writing access.
  111       // ! All above rules apply also to any other function being called from the event handler code, although calling any function from Interrupt event is not recommended because of additional MCU stack usage.
  112 
  113       // PIR timeout counter
  114       static uns8 PIRtimeout;
  115 
  116       //  If TMR6 interrupt occurred
  117       if ( TMR6IF )
  118       {
  119         // Unmask interrupt
  120         TMR6IF = 0;
  121         // Decrement count
  122         if ( --tmrCounter40ms == 0 )
  123         {
  124           // 1 s is over
  125           StartSecond();
  126 
  127           // Decrement PIR counter
  128           if ( PIRtimeout != 0 )
  129             PIRtimeout--;
  130 
  131           // Decrement light counter
  132           if ( lightTimeout != 0 )
  133           {
  134             lightTimeout--;
  135             if ( lightTimeout == 0 )
  136               // Switch off the light
  137               LIGHT = 0;
  138           }
  139         }
  140       }
  141 
  142       // Last state of PIR input
  143       static bit lastPIR;
  144 
  145       // PIR is on?
  146       if ( PIR )
  147       {
  148         // Was PIR off and PIR timeout is over and not disabled?
  149         if ( !lastPIR && PIRtimeout == 0 && !PeripheralRam[0].0 )
  150         {
  151           // Initializes PIR timeout counter
  152           PIRtimeout = PIRdelay;
  153           // PIR is activated
  154           PIRactivated = TRUE;
  155         }
  156 
  157         lastPIR = TRUE;
  158       }
  159       else
  160         lastPIR = FALSE;
  161 
  162 DpaHandleReturnTRUE:
  163       return TRUE;
  164 
  165       // -------------------------------------------------
  166     case DpaEvent_Idle:
  167       // Do a quick background work when RF packet is not received
  168 
  169       // PIR was activated, send the P2P packet
  170       if ( PIRactivated )
  171       {
  172         // Note: Here Listen before Talk technique should be implemented to avoid collisions
  173 
  174         // PIR not activated any more
  175         PIRactivated = FALSE;
  176 
  177         // Save RF settings and set new ones
  178         setNonetMode();
  179         setRFmode( _TX_STD | _STDL );
  180 
  181         // Prepare P2P packet
  182         // Header
  183         bufferRF[0] = 'P';
  184         // Address
  185         bufferRF[1] = ntwADDR;
  186         // Packet length
  187         DLEN = 2;
  188         PIN = 0;
  189         // Transmit the prepared packet
  190         RFTXpacket();
  191 
  192         // Restore RF settings
  193         DpaApiSetRfDefaults();
  194         setNodeMode();
  195 
  196         LightOn();
  197       }
  198 
  199       break;
  200 
  201       // -------------------------------------------------
  202     case DpaEvent_PeerToPeer:
  203       // Called when peer-to-peer (non-networking) packet is received
  204 
  205       // Note: peer-to-peer packet should be better protected when not used at this example
  206 
  207       // Is my peer-to-peer packet (check length and content)?
  208       if ( DLEN == 2 && bufferRF[0] == 'P' )
  209       {
  210         // Read list of condition bytes from EEPROM[1..x]
  211         eeReadData( PERIPHERAL_EEPROM_START + 1, ADDR_LIST_LEN );
  212         // Force list end
  213         bufferINFO[ADDR_LIST_LEN] = 0;
  214         // Pointer before 1st address
  215         FSR0 = bufferINFO - 1;
  216         // Loop the list
  217         while ( *++FSR0 != 0 )
  218         {
  219           // Any address or address match?
  220           if ( *FSR0 == 0xff || *FSR0 == bufferRF[1] )
  221           {
  222             LightOn();
  223             break;
  224           }
  225 
  226           if ( *FSR0 > MAX_ADDRESS )
  227           {
  228             // Compute absolute address difference
  229             int8 addrDiff = bufferRF[1] - ntwADDR;
  230             if ( addrDiff < 0 )
  231               addrDiff = -addrDiff;
  232 
  233             // Get maximum difference
  234             uns8 absDelta = *FSR0 - MAX_ADDRESS;
  235             // Is max. difference met?
  236             if ( (uns8)addrDiff <= absDelta )
  237             {
  238               LightOn();
  239               break;
  240             }
  241           }
  242         }
  243       }
  244 
  245       break;
  246 
  247       // -------------------------------------------------
  248     case DpaEvent_Init:
  249       // Do a one time initialization before main loop starts
  250 
  251       // Setup TMR6 to generate ticks on the background (ticks every 10ms)
  252       _PR6 = 250 - 1;
  253       // Prescaler 16, Postscaler 10, 16 * 10 * 250 = 40000 = 4MHz * 10ms
  254 #if defined( TR7xG )
  255       TMR6MD = 0;
  256       T6CON = 0b1.100.1001;
  257       //  Timer2/4/6 Clock Select bits = FOSC/4
  258       T6CLKCON |= 0b0000.0001;
  259 #else
  260       T6CON = 0b0.1001.1.10;
  261 #endif
  262 
  263       TMR6IE = TRUE;
  264 
  265       // Initialize 1 s timer
  266       StartSecond();
  267 
  268 RefreshLightDelay:
  269       // Read light delay from EEPROM[0]
  270       lightTimeoutSetting = eeReadByte( PERIPHERAL_EEPROM_START + 0 );
  271       break;
  272 
  273       // -------------------------------------------------
  274     case DpaEvent_Notification:
  275       // Called after DPA request was processed and after DPA response was sent
  276 
  277       // Anything written to the EEPROM?
  278       // (could be optimized by checking the EEPROM address that was written to)
  279       if ( _PNUM == PNUM_EEPROM && _PCMD == CMD_EEPROM_WRITE )
  280         goto RefreshLightDelay;
  281 
  282       break;
  283 
  284       // -------------------------------------------------
  285     case DpaEvent_AfterSleep:
  286       // Called on wake-up from sleep
  287       TMR6IE = TRUE;
  288       _TMR6ON = TRUE;
  289       break;
  290 
  291       // -------------------------------------------------
  292     case DpaEvent_BeforeSleep:
  293       // Called before going to sleep   (the same handling as DpaEvent_DisableInterrupts event)
  294 
  295       // -------------------------------------------------
  296     case DpaEvent_DisableInterrupts:
  297       // Called when device needs all hardware interrupts to be disabled (before Reset, Restart, LoadCode, Remove bond, and Run RFPGM)
  298       // Must not use TMR6 any more
  299       _TMR6ON = FALSE;
  300       TMR6IE = FALSE;
  301       break;
  302   }
  303 
  304   return FALSE;
  305 }
  306 
  307 //############################################################################################
  308 void LightOn()
  309 //############################################################################################
  310 {
  311   lightTimeout = lightTimeoutSetting;
  312   LIGHT = 1;
  313   StartSecond();
  314 }
  315 
  316 //############################################################################################
  317 void StartSecond()
  318 //############################################################################################
  319 {
  320   tmrCounter40ms = 1000 / 40;
  321 }
  322 
  323 //############################################################################################
  324 // Default Custom DPA Handler header; 2nd include implementing a Code bumper to detect too long code of the Custom DPA Handler (modify the path according to your setup)
  325 #include "DPAcustomHandler.h"
  326 //############################################################################################