Esempio n. 1
0
void main(void)
{
#if !defined(MAX_UART_RX_BUF_CNT)
    #error "Define MAX_UART_RX_BUF_CNT > 0 in config.h for this example"
#endif

    WD_STOP();
    ClockConfig(16);
    HardwareInit();
    // init uart at 115k
    UartInit(115200);

    _EINT();

    printf("\n\nEnter your name: ");
    static uint8_t buf[30];
    uint8_t* cur_char = &buf[0];
    while(1)
    {
        // poll the rx buffer for new data
        if (!UartBufEmpty())
        {
            // pull the data out one byte at a time
            *cur_char = getchar();
            // was the last character a carriage return?
            if (*(cur_char - 1) == '\r')
            {
                printf("\nHello %s",buf);
            }
        }
    }
}
Esempio n. 2
0
void main(void)
{
#if defined(MAX_UART_RX_BUF_CNT) || defined(MAX_UART_TX_BUF_CNT)
    #error "Comment out MAX_UART_RX_BUF_CNT and MAX_UART_TX_BUF_CNT in config.h for this example"
#endif

    WD_STOP();
    ClockConfig(16);
    HardwareInit();
    // init uart at 115k
    UartInit(115200);

    _EINT();
    printf("\n\nEnter your name: ");
    static uint8_t buf[20];
    uint8_t* cur_char = &buf[0];
    while(1)
    {
        // The code will stop here and wait for a character to be received
        while((*cur_char++ = getchar()) == '\r')
        {
            printf("\nHello %s",buf);
        }
    }
}
Esempio n. 3
0
void main(void) {
    HardwareInit();
    UartInit(STDIO,115200,DEFAULT_LINE_CTRL);
    while (1){
       eForth();
       UartPrint(STDOUT,"VM crashed!\r restarting it.\r");
    }
}
Esempio n. 4
0
void main(void)
{

    HardwareInit();
   
 
	//StartAllSensor();
    
 

	while(1)
	{



          
            

		if(TimerCounter==MAXCounter)  
			TimerCounter=0;  //归零



		u8 counter=GetSendCounter();
		if(TimerCounter%counter==0)  //达到测量周期
		{

			StartAllSensor();
		}
		if(TimerCounter%OneSec==0)  //达到测量周期,实现测量电压

		{
			GetVCCValue();     //测定电压
			RxWayConfig() ;    //   在十分之一时隙内建立接收通信
		}
		if(TimerCounter%OneSec==50)  //
		{
                  OSLEDControl(2);
                  
                  
			SetStandbyMode();
		}



		if(TimerCounter%counter==5)  //完成测量和发送周期
		{
			OSLEDControl(2);

			GetAllSensorData();
			//CalAllSensorData();
			W_PutString();
			CloseAllSensor();

		}
		LPM0;
	}
}
Esempio n. 5
0
int main(void)
{
  HardwareInit();
  SoftwareInit();
  UART0Send("Main\r\n",6);
  while (true)
  {
    PrintTelemetry();
  }
}
Esempio n. 6
0
void main(void)
{
    WD_STOP();
    ClockConfig(1);
    HardwareInit();

    ScheduleTimerInit();
    BlinkLed1();
    _EINT();
    LPM0;
}
Esempio n. 7
0
void main(void)
{
    WD_STOP();
    ClockConfig(16);
    ScheduleTimerInit();
    HardwareInit();

    // call ToggleLed2 and it will continue to reschedule itself forever
    ToggleLed2();
    _EINT();
    LPM0;
}
Esempio n. 8
0
int main()
{
    HardwareInit();

    BleAppInit((const BLEAPP_CFG *)&s_BleAppCfg, true);

	//uint64_t period = g_Timer.EnableTimerTrigger(0, 500UL, TIMER_TRIG_TYPE_CONTINUOUS, AppTimerHandler);

    BleAppRun();

	return 0;
}
Esempio n. 9
0
void main(void)
{
    WD_STOP();
    ClockConfig(16);
    ScheduleTimerInit();
    HardwareInit();

    // attach function to SW1 falling edge interrupt
    InterruptAttach(GPIO(SW1), QueueButton, FALLING);
    _EINT();
    LPM0;
}
Esempio n. 10
0
File: main.c Progetto: ADTL/AFGUI
//************************************************************
// MAIN
//************************************************************
//----------------------------------------------------------------------------
int main(void)

 {
	tn_arm_disable_interrupts();

	HardwareInit();
	
			
	tn_start_system(); //-- Never returns

   return 1;
}
Esempio n. 11
0
void main(void) {
    HardwareInit();
    UartInit(STDIO,115200,DEFAULT_LINE_CTRL);
    heap_size=free_heap();
#if defined DEBUG
    test_pattern();
#endif
    UartPrint(STDOUT,"video initialization\r");
    VideoInit();
    delay_ms(500);
    UartPrint(STDOUT,"keyboard initialization: ");
    if (KeyboardInit()){
        UartPrint(STDOUT,"OK\r");
        comm_channel=LOCAL_CON;
    }else{
        UartPrint(STDOUT,"keyboard error\r");
        UartPrint(STDOUT,"Using uart2 channel.\r");
        comm_channel=SERIAL_CON;
    }
    text_coord_t cpos;
    UartPrint(STDOUT,"SD initialization: ");
    if (!mount(0)){
        UartPrint(STDOUT,"Failed\r");
        SDCardReady=FALSE;
    }else{
        UartPrint(STDOUT,"succeeded\r");
        SDCardReady=TRUE;
    }
    UartPrint(STDOUT,"SRAM initialization\r");
    sram_init();
    UartPrint(STDOUT,"sound initialization.\r");
    tune((unsigned int*)&e3k[0]);
    UartPrint(STDOUT,"initialization completed.\r");
    set_cursor(CR_BLOCK); // sauvegare video_buffer dans SRAM
    clear_screen();
#if defined _DEBUG_
    graphics_test();
    set_curpos(0,LINE_PER_SCREEN-1);
    print(comm_channel,"test");
    sram_write_block(100000,video_bmp,BMP_SIZE);
    delay_ms(1000);
    clear_screen();
    delay_ms(1000);
    sram_read_block(100000,video_bmp,BMP_SIZE);
    delay_ms(1000);
    clear_screen();
//    print(comm_channel,"heap_size: ");
//    print_int(comm_channel,heap_size,0);
//    crlf();
#endif
    shell();
} // main()
Esempio n. 12
0
int main(void)
{
	uchar   i = 1;
	uchar	hidCurrentMode = 255;
	char remainingData=0;
	uchar offset=0;

	HardwareInit();
	usbInit();

	// Set up descriptor
	hidMode = HIDM_1P;
	ReadController(1);
	SetHIDMode();

    for(;;){                /* main event loop */
        usbPoll();
        if(usbInterruptIsReady()){
            /* called after every poll of the interrupt endpoint */
			ReadController(i);
			RemapButtons(&(reportBuffer.b1), &(reportBuffer.b2));
			RemapButtons(&(reportBufferWheel.b1), &(reportBufferWheel.b2));
			remainingData=reportBufferLength;
			offset=0;
			// handle report with more than 8 byte length (for NegCon and future expansion)
			do {
				if (remainingData<=8) {
					usbSetInterrupt(reportBufferAddress+offset, remainingData);
					remainingData=0;
				}
				else {	
					usbSetInterrupt(reportBufferAddress+offset, 8);				
					offset+=8;
					remainingData-=8;
					do {
						usbPoll();
					} while (!usbInterruptIsReady());	
				}
			} while (remainingData>0);				
				
			i++;
			if (i > hidNumReports) i = 1;
			if (hidCurrentMode != hidMode)
			{
				SetHIDMode();
				hidCurrentMode = hidMode;
			}
        }
    }

    return 0;
}
Esempio n. 13
0
int main()
{
    HardwareInit();

    g_Uart.printf("UART over BLE Demo\r\n");

    //g_Uart.Disable();

    BleAppInit((const BLEAPP_CFG *)&s_BleAppCfg, true);

    BleAppRun();

	return 0;
}
Esempio n. 14
0
void MyModuleInit(RTC::Manager* manager)
{
  HardwareInit(manager);
  RTC::RtcBase* comp;

  // Create a component
  comp = manager->createComponent("Hardware");

  if (comp==NULL)
  {
    std::cerr << "Component create failed." << std::endl;
    abort();
  }
  return;
}
Esempio n. 15
0
void main(void)
{
    WD_STOP();
    ClockConfig(16);
    HardwareInit();

    // Init the timer
    ScheduleTimerInit();
    // register a function and define its period
    CallbackRegister(BlinkLed1, 100ul * _MILLISECOND);
    // attach function to SW1 falling edge interrupt
    InterruptAttach(GPIO(SW1),ToggleEnable,FALLING);

    _EINT();
    LPM0;
}
Esempio n. 16
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	HardwareInit();

	/* Create a regular character stream for the interface so that it can be used with the stdio.h functions */
	CDC_Device_CreateStream(&VirtualSerial_CDC_Interface, &USBSerialStream);
	stdout = &USBSerialStream;

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	sei();

	//OldButtonState = GetButtonState();
	for (;;)
	{
		RunCommand();
		HandleButtonPress();
	}
}
Esempio n. 17
0
void main(void)
{
    WD_STOP();
    ClockConfig(16);
    HardwareInit();

    // Init the timer
    ScheduleTimerInit();
    // register functions and define their period
    CallbackRegister(BlinkLed1, 100ul * _MILLISECOND);
    CallbackRegister(BlinkLed2, 101ul * _MILLISECOND);
    // callbacks are disabled by default, so enable them
    CallbackMode(BlinkLed1, ENABLED);
    CallbackMode(BlinkLed2, ENABLED);

    _EINT();
    LPM0;
}
Esempio n. 18
0
int main()
{
	HardwareInit();

	APP_SCHED_INIT(SCHED_MAX_EVENT_DATA_SIZE, SCHED_QUEUE_SIZE);
	timers_init();

	BLEStart();
//	timers_start();
//	blink();


	while (1)
	{
		app_sched_execute();
		uint32_t err_code = sd_app_evt_wait();
		APP_ERROR_CHECK(err_code);
		//BlueIOADCStart();
	}
}
Esempio n. 19
0
//----------------------------------------------------------------------------
int main(void)
{
  int i;

   tn_arm_disable_interrupts();

   MEMMAP = 0x1;  //-- Flash Build

   HardwareInit();

   //===Takuji Ebinuma code===
   // make reset:
   outpw(RESET, 0);
   //set TIC period:
   outpw(PROG_TIC_LOW,   (7999999L & 0x0000ffff));      // 0.1 sec.
   outpw(PROG_TIC_HIGH, ((7999999L & 0xffff0000)>>16)); // 0.1 sec.

   // Initialize channels
   for (i=0; i<MAX_CHANNELS; i++) {
     CH[i].BASE = 0x26*i;
     CH[i].prn = IDLE;
     CH[i].lock_status = NO_LOCK;
     CH[i].pow_code = LossThresh;
     CH[i].pow_carr = LossThresh;
     CH[i].IP  = 0;
     CH[i].QP  = 0;
     CH[i].E   = 0;
     CH[i].Tau = 0;
     CH[i].half_chip_counter = 0;
     CH[i].freq_bin_counter  = 0;
     CH[i].pull_in_time      = 0;
     CH[i].carr_nco_sign = CARR_REF_SIGN; //[Art]. IQ-processing rough addition.
     CH[i].carr_nco      = CARR_REF;
     CH[i].code_nco      = CODE_REF;
   }
   //===Takuji Ebinuma code - END===

   tn_start_system(); //-- Never returns

   return 1;
}
Esempio n. 20
0
/**
 *  PlatformInit - sets up platform and protocol hardware. Also configures the
 *  protocol using the setup structure data.
 *
 *    @return   Success of the operation. If true, the protocol has been setup
 *              successfully. If false, an error has occurred during protocol
 *              setup.
 */
bool PlatformInit(void)
{
  // Disable global interrupts during hardware initialization to prevent any
  // unwanted interrupts from occurring.
  MCU_DISABLE_INTERRUPT();
  
  // Setup basic platform hardware (e.g. watchdog, clocks).
  HardwareInit();
  
  // Attempt to initialize protocol hardware and information using the provided
  // setup structure data.
  if (!ProtocolInit(&gProtocolSetupInfo))
  {
    return false;
  }
  
  // Re-enable global interrupts for normal operation.
  MCU_ENABLE_INTERRUPT();
  
  return true;
}
Esempio n. 21
0
void main(void)
{
    WD_STOP();
    CAL_CLOCK();
    
//    TimerAInit();
    HardwareInit();
    I2cInit(0x02, 0x00);
    _EINT();
    
    while (1)
    {
        //LPM0;
        //_NOP();
        if (GetWriteEndpoint(0))
            SET_LOW(RED_LED);
        else
            SET_HIGH(RED_LED);
        
        SetReadEndpoint(0, READ_IN(LP_SWITCH));
    }
}
Esempio n. 22
0
void main(void)
{
#if !defined(MAX_UART_TX_BUF_CNT)
    #error "Define MAX_UART_TX_BUF_CNT > 0 in config.h for this example"
#endif
    WD_STOP();
    ClockConfig(16);
    HardwareInit();
    // init uart at 115k
    UartInit(115200);

    _EINT();

    printf("\n\nThis is %s\n",        "a string");
    printf("Hex number(16): 0x%x\n",  60);
    printf("Hex number(32): 0x%lx\n", 100000);
    printf("Char: %c\n",              'x');
    printf("Unsigned short: %u\n",    100);
    printf("Signed short: %i\n",     -100);
    printf("Unsigned long: %lu\n",    250000);
    printf("Signed long: %li\n",     -250000);
    LPM0;
}
Esempio n. 23
0
void ResetISR(void)
{
    unsigned long *pulSrc, *pulDest;

    //Copy the data segment initializers from flash to SRAM.
    pulSrc = &_etext;
    for(pulDest = &_data; pulDest < &_edata; ){
        *pulDest++ = *pulSrc++;
    }

    // Zero fill the bss segment.
    __asm("    ldr     r0, =_bss\n"
          "    ldr     r1, =_ebss\n"
          "    mov     r2, #0\n"
          "    .thumb_func\n"
          "zero_loop:\n"
          "        cmp     r0, r1\n"
          "        it      lt\n"
          "        strlt   r2, [r0], #4\n"
          "        blt     zero_loop");

    HardwareInit();
}
Esempio n. 24
0
void init_platform_bootloader( void )
{
  uint32_t BootNvmInfo;
  OSStatus err;
  
  MicoGpioInitialize( BOOT_SEL, INPUT_PULL_UP );
  MicoGpioInitialize( MFG_SEL, INPUT_PULL_UP );
#ifdef MICO_ATE_START_ADDRESS
	MicoGpioInitialize( EasyLink_BUTTON, INPUT_PULL_UP );
#endif  
  /* Check USB-HOST is inserted */
  err = MicoGpioInitialize( (mico_gpio_t)USB_DETECT, INPUT_PULL_DOWN );
  require_noerr(err, exit);
  mico_thread_msleep_no_os(2);
  
  require_string( MicoGpioInputGet( (mico_gpio_t)USB_DETECT ) == true, exit, "USB device is not inserted" );

  //platform_log("USB device inserted");
  if( HardwareInit(DEV_ID_USB) ){
    FolderOpenByNum(&RootFolder, NULL, 1);
    FileBrowse(RootFolder.FsContext);
  }

  /* Check last firmware update is success or not. */
  NvmRead(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4);

  if(false == UpgradeFileFound)
  {
    if(BootNvmInfo == UPGRADE_SUCC_MAGIC)
    {
      /*
       * boot up check for the last time
       */
      platform_log("[UPGRADE]:upgrade successful completely");
    }
    else if(BootNvmInfo == (uint32_t)UPGRADE_ERRNO_NOERR)
    {
      platform_log("[UPGRADE]:no upgrade, boot normallly");
    }
    else if(BootNvmInfo == (uint32_t)UPGRADE_ERRNO_CODBUFDAT)
    {
      platform_log("[UPGRADE]:upgrade successful partly, data fail");
    }
    else
    {
      platform_log("[UPGRADE]:upgrade error, errno = %d", (int32_t)BootNvmInfo);
    }
  }
  else
  {
    if(BootNvmInfo == (uint32_t)UPGRADE_ERRNO_NOERR)
    {
      platform_log("[UPGRADE]:found upgrade ball, prepare to boot upgrade");
      BootNvmInfo = UPGRADE_REQT_MAGIC;
      NvmWrite(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4);
            //if you want PORRESET to reset GPIO only,uncomment it
            //GpioPorSysReset(GPIO_RSTSRC_PORREST);
      NVIC_SystemReset();
      while(1);;;
    }
    else if(BootNvmInfo == UPGRADE_SUCC_MAGIC)
    {
      BootNvmInfo = (uint32_t)UPGRADE_ERRNO_NOERR;
      NvmWrite(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4);
      platform_log("[UPGRADE]:found upgrade ball file for the last time, re-plugin/out, if you want to upgrade again");
    }
    else
    {
      platform_log("[UPGRADE]:upgrade error, errno = %d", (int32_t)BootNvmInfo);
      if( BootNvmInfo == -9 ) {
        platform_log("[UPGRADE]:Same file, no need to update");
        goto exit;
      }
      BootNvmInfo = (uint32_t)UPGRADE_ERRNO_NOERR;
      NvmWrite(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4);
      BootNvmInfo = UPGRADE_REQT_MAGIC;
      NvmWrite(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4);
            //if you want PORRESET to reset GPIO only,uncomment it
            //GpioPorSysReset(GPIO_RSTSRC_PORREST);
      NVIC_SystemReset();
    }
  }
exit:
  return;
}
Esempio n. 25
0
int main(void)
{
	uchar   i = 1;
	uchar	hidCurrentMode = 255;
	char remainingData=0;
	uchar offset=0;

	HardwareInit();
	usbInit();

	// Set up descriptor
	hidMode = HIDM_1P;
	ReadController(1);
	SetHIDMode();

//	uchar j = 1; //for speed test only
	
    for(;;){                /* main event loop */
        usbPoll();
        if(usbInterruptIsReady()){
            /* called after every poll of the interrupt endpoint */
			ReadController(i);
			
			switch (hidCurrentMode)
			{
				case HIDM_1P:
					RemapController(&(reportBuffer.x), &(reportBuffer.y), 
						&(reportBuffer.rx), &(reportBuffer.ry),
						&(reportBuffer.b1), &(reportBuffer.b2));
					break;
				case HIDM_2P:
					RemapController(&(reportBuffer.x), &(reportBuffer.y), 
						&(reportBuffer.rx), &(reportBuffer.ry),
						&(reportBuffer.b1), &(reportBuffer.b2));
					break;
				case HIDM_NEGCON:
					RemapController(&(reportBufferNegCon.x), &(reportBufferNegCon.y), 
						&(reportBufferNegCon.rx), &(reportBufferNegCon.ry),
						&(reportBufferNegCon.b1), &(reportBufferNegCon.b2));
					break;
			}

			remainingData=reportBufferLength;
			offset=0;

// For speed test, uncommnent the next three lines and the line "uchar j=0" above
//			reportBuffer.x=(j%4)*10; //for speed test only
//			reportBufferNegCon.x=(j%4)*10; //for speed test only
//			j++; //for speed test only
		
			// handle report with more than 8 byte length (for NegCon and future expansion)
			do {
				if (remainingData<=8) {
					usbSetInterrupt(reportBufferAddress+offset, remainingData);
					remainingData=0;
				}
				else {	
					usbSetInterrupt(reportBufferAddress+offset, 8);				
					offset+=8;
					remainingData-=8;
					do {
						usbPoll();
					} while (!usbInterruptIsReady());	
				}
			} while (remainingData>0);				

			i++;
			if (i > hidNumReports) i = 1;
			if (hidCurrentMode != hidMode)
			{
				SetHIDMode();
				hidCurrentMode = hidMode;
			}
        }
    }

    return 0;
}
Esempio n. 26
0
int main ()
{
	

	unsigned char zigbee_mode = 0;

	HardwareInit();
	ConsoleInit();
	InitSymbolTimer();
	uart_init();
	initMSDCLTimers();
	IFS1bits.U2RXIF = 0;
	

	ConsolePutROMString( (ROM char *)"\r\nW to exit");

	SendModuleStartData();
	while( StartNetworkFlag == FALSE )
	{
		HanddleUART2();	
		if(IFS1bits.U2RXIF)
		{
			zigbee_mode = U2RXREG;
			if(zigbee_mode == 'W')
				break;
		}
	}
	StartNetworkFlag = FALSE;
	zigbee_mode = 0;
	
    ConsolePutROMString( (ROM char *)"\r\n*********************************" );
	ConsolePutROMString( (ROM char *)"\r\nMicrochip SE Profile 1.0.version.0.5.3" );
	ConsolePutROMString( (ROM char *)"\r\n*********************************" );
	ConsolePutROMString( (ROM char *)"\r\nE:Comission device as ESP\r\n" );
	ConsolePutROMString( (ROM char *)"\r\nM:Comission device as MTR\r\n" );
	
	{
		
		TICK startTime = TickGet();
		
		do
		{
			IFS1bits.U2RXIF = 0;
			do
			{
				if( TickGetDiff(TickGet(),startTime) > (2 * ONE_SECOND))
				{
					break;
				}
			}
			while( !IFS1bits.U2RXIF );
			if( TickGetDiff(TickGet(),startTime) > (2 * ONE_SECOND))
			{
				break;
			}
			zigbee_mode = U2RXREG;
			ConsolePut(zigbee_mode);
		}while( (zigbee_mode != 'M') && (zigbee_mode != 'm') && (zigbee_mode != 'E') && (zigbee_mode != 'e') );
		
		NVMRead ( (BYTE*)&MSDCL_Commission, MSDCL_Commission_Locations, sizeof(MSDCL_Commission));

		if( ( MSDCL_Commission.ValidCleanStartUp != MSDCL_COMMISSION_DATA_VALID )
			 && (MSDCL_Commission.ValidCleanStartUp != MSDCL_DEFAULT_MTR) && 
			 (MSDCL_Commission.ValidCleanStartUp != MSDCL_DEFAULT_ESP) &&  (zigbee_mode != 'E') && (zigbee_mode != 'e') )
		{
			zigbee_mode = 'M';
	 	}   
	 			
		if( ((zigbee_mode == 'M') || (zigbee_mode == 'm') || (MSDCL_Commission.ValidCleanStartUp == MSDCL_DEFAULT_MTR))
			&& (zigbee_mode != 'E') && (zigbee_mode != 'e') )
		{
			NowIam = 0;
 			NowIam = A_ROUTER | A_FFD; // These variables are exported in Zigbee.def
			I_AM_TRUST_CENTER = 0; 		//Trust center enabled Enabled
			USE_COMMON_TC_LINK_KEY = 1;
			MAX_ENERGY_THRESHOLD = 112;
			DEFAULT_STARTUP_CONTROL = DEFAULT_STARTUP_CONTROL_MTR;
			MSDCL_Commission.StartupStatus = STARTUP_CONTROL_JOIN_NEW_NETWORK;
			ALLOWED_CHANNELS = ALLOWED_CHANNELS_PRE_CONFIG;
			if(MSDCL_Commission.ValidCleanStartUp != MSDCL_DEFAULT_MTR)
			{
				MSDCL_Commission.ValidCleanStartUp = MSDCL_DEFAULT_MTR;
				NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
			}
		}
		else if( (zigbee_mode == 'E') || (zigbee_mode == 'e') || (MSDCL_Commission.ValidCleanStartUp == MSDCL_DEFAULT_ESP)  )
		{
			NowIam = 0;
 			NowIam = A_CORDINATOR | A_FFD; // These variables are exported in Zigbee.def
			I_AM_TRUST_CENTER = 1; 		//Trust center enabled Enabled
			USE_COMMON_TC_LINK_KEY = 1;
			MAX_ENERGY_THRESHOLD = 241;
			DEFAULT_STARTUP_CONTROL = DEFAULT_STARTUP_CONTROL_ESP;
			MSDCL_Commission.StartupStatus = STARTUP_CONTROL_FORM_NEW_NETWORK;
			ALLOWED_CHANNELS = ALLOWED_CHANNELS_PRE_CONFIG;
			if(MSDCL_Commission.ValidCleanStartUp != MSDCL_DEFAULT_ESP)
			{
				MSDCL_Commission.ValidCleanStartUp = MSDCL_DEFAULT_ESP;
				NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
			}
		}


	if((MSDCL_Commission.ValidCleanStartUp == MSDCL_COMMISSION_DATA_VALID) )
	{
	 	switch( MSDCL_Commission.StartupStatus )
	 	{
		 	case STARTUP_CONTROL_FORM_NEW_NETWORK:
		 		ConsolePutROMString( (ROM char *)"\r\nStarting as ESP\r\n" );
				NowIam = 0;
	 			NowIam = A_CORDINATOR | A_FFD; // These variables are exported in Zigbee.def
				I_AM_TRUST_CENTER = 1; 		//Trust center enabled Enabled
				USE_COMMON_TC_LINK_KEY = 1;
				MAX_ENERGY_THRESHOLD = 241;
				ALLOWED_CHANNELS = MSDCL_Commission.ChannelMask.Val ;
				DEFAULT_STARTUP_CONTROL = DEFAULT_STARTUP_CONTROL_ESP;
		 	break;
		 	
		 	case STARTUP_CONTROL_PART_OF_NETWORK_NO_EXPLICIT_ACTION:
		 	case STARTUP_CONTROL_JOIN_NEW_NETWORK:
		 	case STARTUP_CONTROL_START_FROM_SCRATCH_AS_ROUTER:
		 	default:
		 		ConsolePutROMString( (ROM char *)"\r\nStarting as MTR\r\n" );
				NowIam = 0;
	 			NowIam = A_ROUTER | A_FFD; // These variables are exported in Zigbee.def
				I_AM_TRUST_CENTER = 1; 		//Trust center enabled Enabled
				USE_COMMON_TC_LINK_KEY = 0;
				MAX_ENERGY_THRESHOLD = 112;
				ALLOWED_CHANNELS = MSDCL_Commission.ChannelMask.Val ;
				DEFAULT_STARTUP_CONTROL = DEFAULT_STARTUP_CONTROL_MTR;
		 	break;
		}
	}
	
	}
	
//	if (NOW_I_AM_A_CORDINATOR())
//		USE_COMMON_TC_LINK_KEY = 1;
//	else
//		USE_COMMON_TC_LINK_KEY = 0;
		
	if(NOW_I_AM_A_ROUTER())
		I_AM_TRUST_CENTER = 0;

	
	if(NOW_I_AM_A_ROUTER())
		appNextSeqNum_PTR = &appNextSeqNum_MTR;
	else if (NOW_I_AM_A_CORDINATOR())
		appNextSeqNum_PTR = &appNextSeqNum_ESP;
	
	if(NOW_I_AM_A_ROUTER())
		App_AttributeStorageTable = App_AttributeStorageTable_MTR;
	else if (NOW_I_AM_A_CORDINATOR())
		App_AttributeStorageTable = App_AttributeStorageTable_ESP;
		
	if(NOW_I_AM_A_ROUTER())
		Config_Node_Descriptor.NodeLogicalType = 0x01;
	else if (NOW_I_AM_A_CORDINATOR())
		Config_Node_Descriptor.NodeLogicalType = 0x00;
		
	if( NOW_I_AM_A_ROUTER() )
		pAppListOfDeviceServerInfo[0] = &Meter_DeviceServerinfo;
	else if( NOW_I_AM_A_CORDINATOR() )
		pAppListOfDeviceServerInfo[0] = &ESP_DeviceServerinfo;
		
	if( NOW_I_AM_A_ROUTER() )
		pAppListOfDeviceClientInfo[0] = &Meter_DeviceClientinfo;
	else if( NOW_I_AM_A_CORDINATOR() )
		pAppListOfDeviceClientInfo[0] = &ESP_DeviceClientinfo;
		
	if( NOW_I_AM_A_ROUTER() )
		Config_Simple_Descriptors = Config_Simple_Descriptors_MTR;
	else if( NOW_I_AM_A_CORDINATOR() )
		Config_Simple_Descriptors = Config_Simple_Descriptors_ESP;

	if( MSDCL_Commission.ValidCleanStartUp == MSDCL_COMMISSION_DATA_VALID)
	{
		if( ChannelsToBeScanned.Val == 0 )
		{
			ChannelsToBeScanned.Val = MSDCL_Commission.ChannelMask.Val & 0x03FFF800UL;
		}
	}
	else
	{
		if( ChannelsToBeScanned.Val == 0 )
		{
			ChannelsToBeScanned.Val = ALLOWED_CHANNELS_PRE_CONFIG & 0x03FFF800UL;
		}
	}
	{
		unsigned long channelMaskToScan = 0x00000800UL;
		
		if( ( ChannelsToBeScanned.Val & 0x03FFF800UL ) == 0 )
		{
			ChannelsToBeScanned.Val = ALLOWED_CHANNELS_PRE_CONFIG & 0x03FFF800UL;
		}
		
		ChannelsToBeScanned.Val &= 0x03FFF800UL;
	
		while( !(ChannelsToBeScanned.Val & channelMaskToScan) )
		{
			channelMaskToScan <<= 1;	
		}
		ALLOWED_CHANNELS = channelMaskToScan;
		ChannelsToBeScanned.Val &= channelMaskToScan ^ 0xFFFFFFFFUL;
		
		//ALLOWED_CHANNELS = 0x3FFFC00UL;
	}
	

	//ALLOWED_CHANNELS = 0b000000000111111111101111100000000000;
	ALLOWED_CHANNELS = 0b0000000000010000000000000000000000;

	while(1)
	{	
		if (NOW_I_AM_A_CORDINATOR())
			main_ESP(); 
		else
		{
			
			main_MTR();
		}
	}
}
Esempio n. 27
0
File: main.c Progetto: LuccoJ/z80sim
void main() {
	task* TI1;
	task* TI2;
	char* Data;
	char* Encoded;

	register unsigned int i;

        _asm;
        di
        ld sp,#0xffff
        ld a,#0x0
        ld bc,#0x0
        ld de,#0x0
        ld hl,#0x0
        ld ix,#0x0
        ld iy,#0x0
        _endasm;

	_SimWriteProtect((void*)0x0000, (void*)0x3fff);

        _SimPrintString("\n-------------------\n");
        _SimPrintString("System reset\n");
        _SimPrintString("-------------------\n");

	IntsOff();

	_SimPrintString("Interrupts disabled. Booting...\n");

	TestMemory();
	HardwareInit();
        LocksInit();
        SchedulingInit();
	SupervisorMode();
	TimeInit();
	SystemInit();
	MemoryInit();
	//KeyboardInit();
	//TapeInit();
	ConsoleInit();
	ConsoleWrite("LJL OS 0.1 FOR ZX SPECTRUM 48\n");
	ConsoleWrite("\nCONSOLE OUTPUT\n\n");
/*
        TapeSave((void*)0x4000, (void*)0x5800);
	TapeLoad((void*)0x4000, (void*)0x5800);
	for(i=0; i<0x4000; i+=0x100) {
		ConsoleWrite(".");
		SaveBlock((void*)i);
	}
	Halt("Saved");
*/
	MainEntry=Task1;
	TI1=CreateTask(MainEntry, 100);
	MainEntry=Task2;
	TI2=CreateTask(MainEntry, 100);
	ConsoleWrite("TASKS CREATED\n");
	SetScheduler(DefaultScheduler);
	ConsoleWrite("SCHEDULER SET\n");
        Resume();
	//ConsoleWrite("RESUMING\n");
	//if(!IsMultitasking()) Halt("NOT MULTITASKING");
	for(;;);
	Halt("SYSTEM SHUTDOWN");
}
Esempio n. 28
0
void main(void)
{
    CLRWDT();
    ENABLE_WDT();

    currentPrimitive = NO_PRIMITIVE;
    NetworkDescriptor = NULL;
    orphanTries = 3;

    // If you are going to send data to a terminal, initialize the UART.
    ConsoleInit();

	ConsolePutROMString( (ROM char *)"Universidade Paulista - UNIP\r\n" );
	ConsolePutROMString( (ROM char *)"Daniel Gonçalves\r\n" );
	ConsolePutROMString( (ROM char *)"Projeto: Baba Eletronica\r\n\r\n" );
    ConsolePutROMString( (ROM char *)"\r\n\r\n\r\n*************************************\r\n" );
    ConsolePutROMString( (ROM char *)"Microchip ZigBee(TM) Stack - v1.0-3.8\r\n\r\n" );
    ConsolePutROMString( (ROM char *)"ZigBee RFD\r\n\r\n" );
    ConsolePutROMString( (ROM char *)"Transceiver-MRF24J40\r\n\r\n" );

    // Inicializa o Hardware
    HardwareInit();

    // Inicializa a pilha ZigBee
    ZigBeeInit();

    // *************************************************************************
    // Outras Inicializações
    // *************************************************************************

    myStatusFlags.Val = STATUS_FLAGS_INIT;

    // Endereço padrão do Coordenador
    destinationAddress.Val = 0x0000;

    // Inicializa os LEDS
    MOVE_SENSOR_LED = ON;
    LEVEL_SENSOR_LED = ON;

    // Habilita as interrupções 
    RCONbits.IPEN = 1;
    INTCONbits.GIEH = 1;

    while (1)
    {
        CLRWDT();
        ZigBeeTasks( &currentPrimitive );

        switch (currentPrimitive)
        {
            case NLME_NETWORK_DISCOVERY_confirm:
                currentPrimitive = NO_PRIMITIVE;
                if (!params.NLME_NETWORK_DISCOVERY_confirm.Status)
                {
                    if (!params.NLME_NETWORK_DISCOVERY_confirm.NetworkCount)
                    {
                        ConsolePutROMString( (ROM char *)"No networks found.  Trying again...\r\n" );
                    }
                    else
                    {
                        // Save the descriptor list pointer so we can destroy it later.
                        NetworkDescriptor = params.NLME_NETWORK_DISCOVERY_confirm.NetworkDescriptor;

                        // Select a network to try to join.  We're not going to be picky right now...
                        currentNetworkDescriptor = NetworkDescriptor;

SubmitJoinRequest:
                        // not needed for new join params.NLME_JOIN_request.ScanDuration = ;
                        // not needed for new join params.NLME_JOIN_request.ScanChannels = ;
                        params.NLME_JOIN_request.PANId          = currentNetworkDescriptor->PanID;
                        ConsolePutROMString( (ROM char *)"Network(s) found. Trying to join " );
                        PrintChar( params.NLME_JOIN_request.PANId.byte.MSB );
                        PrintChar( params.NLME_JOIN_request.PANId.byte.LSB );
                        ConsolePutROMString( (ROM char *)".\r\n" );
                        params.NLME_JOIN_request.JoinAsRouter   = FALSE;
                        params.NLME_JOIN_request.RejoinNetwork  = FALSE;
                        params.NLME_JOIN_request.PowerSource    = NOT_MAINS_POWERED;
                        params.NLME_JOIN_request.RxOnWhenIdle   = FALSE;
                        params.NLME_JOIN_request.MACSecurity    = FALSE;
                        currentPrimitive = NLME_JOIN_request;
                    }
                }
                else
                {
                    PrintChar( params.NLME_NETWORK_DISCOVERY_confirm.Status );
                    ConsolePutROMString( (ROM char *)" Error finding network.  Trying again...\r\n" );
                }
                break;

            case NLME_JOIN_confirm:
                currentPrimitive = NO_PRIMITIVE;
                if (!params.NLME_JOIN_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Join successful!\r\n" );

                    // Free the network descriptor list, if it exists. If we joined as an orphan, it will be NULL.
                    while (NetworkDescriptor)
                    {
                        currentNetworkDescriptor = NetworkDescriptor->next;
                        free( NetworkDescriptor );
                        NetworkDescriptor = currentNetworkDescriptor;
                    }
                }
                else
                {
                    PrintChar( params.NLME_JOIN_confirm.Status );

                    // If we were trying as an orphan, see if we have some more orphan attempts.
                    if (ZigBeeStatus.flags.bits.bTryOrphanJoin)
                    {
                        // If we tried to join as an orphan, we do not have NetworkDescriptor, so we do
                        // not have to free it.

                        ConsolePutROMString( (ROM char *)" Could not join as orphan. " );
                        orphanTries--;
                        if (orphanTries == 0)
                        {
                            ConsolePutROMString( (ROM char *)"Must try as new node...\r\n" );
                            ZigBeeStatus.flags.bits.bTryOrphanJoin = 0;
                        }
                        else
                        {
                            ConsolePutROMString( (ROM char *)"Trying again...\r\n" );
                        }
                    }
                    else
                    {
                        ConsolePutROMString( (ROM char *)" Could not join selected network. " );
                        currentNetworkDescriptor = currentNetworkDescriptor->next;
                        if (currentNetworkDescriptor)
                        {
                            ConsolePutROMString( (ROM char *)"Trying next discovered network...\r\n" );
                            goto SubmitJoinRequest;
                        }
                        else
                        {
                            // We ran out of descriptors.  Free the network descriptor list, and fall
                            // through to try discovery again.
                            ConsolePutROMString( (ROM char *)"Cleaning up and retrying discovery...\r\n" );
                            while (NetworkDescriptor)
                            {
                                currentNetworkDescriptor = NetworkDescriptor->next;
                                free( NetworkDescriptor );
                                NetworkDescriptor = currentNetworkDescriptor;
                            }
                        }
                    }
                }
                break;

            case NLME_LEAVE_indication:
                if (!memcmppgm2ram( &params.NLME_LEAVE_indication.DeviceAddress, (ROM void *)&macLongAddr, 8 ))
                {
                    ConsolePutROMString( (ROM char *)"We have left the network.\r\n" );
                }
                else
                {
                    ConsolePutROMString( (ROM char *)"Another node has left the network.\r\n" );
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NLME_RESET_confirm:
                ConsolePutROMString( (ROM char *)"ZigBee Stack has been reset.\r\n" );
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NLME_SYNC_confirm:
                switch (params.NLME_SYNC_confirm.Status)
                {
                    case SUCCESS:
                        // I have heard from my parent, but it has no data for me.  Note that
                        // if my parent has data for me, I will get an APSDE_DATA_indication.
                        ConsolePutROMString( (ROM char *)"No data available.\r\n" );
                        break;

                    case NWK_SYNC_FAILURE:
                        // I cannot communicate with my parent.
                        ConsolePutROMString( (ROM char *)"I cannot communicate with my parent.\r\n" );
                        break;

                    case NWK_INVALID_PARAMETER:
                        // If we call NLME_SYNC_request correctly, this doesn't occur.
                        ConsolePutROMString( (ROM char *)"Invalid sync parameter.\r\n" );
                        break;
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case APSDE_DATA_indication:
                {
                    WORD_VAL    attributeId;
                    BYTE        command;
                    BYTE        data;
                    BYTE        dataLength;
                    //BYTE        dataType;
                    BYTE        frameHeader;
                    BYTE        sequenceNumber;
                    BYTE        transaction;
                    BYTE        transByte;

                    currentPrimitive = NO_PRIMITIVE;
                    frameHeader = APLGet();

                    switch (params.APSDE_DATA_indication.DstEndpoint)
                    {
                        case EP_ZDO:
                            ConsolePutROMString( (ROM char *)"  Receiving ZDO cluster " );
                            PrintChar( params.APSDE_DATA_indication.ClusterId );
                            ConsolePutROMString( (ROM char *)"\r\n" );

                            // Put code here to handle any ZDO responses that we requested
                            if ((frameHeader & APL_FRAME_TYPE_MASK) == APL_FRAME_TYPE_MSG)
                            {
                                frameHeader &= APL_FRAME_COUNT_MASK;
                                for (transaction=0; transaction<frameHeader; transaction++)
                                {
                                    sequenceNumber          = APLGet();
                                    dataLength              = APLGet();
                                    transByte               = 1;    // Account for status byte

                                    switch( params.APSDE_DATA_indication.ClusterId )
                                    {

                                        // ********************************************************
                                        // Put a case here to handle each ZDO response that we requested.
                                        // ********************************************************

                                        case NWK_ADDR_rsp:
                                            if (APLGet() == SUCCESS)
                                            {
                                                ConsolePutROMString( (ROM char *)"  Receiving NWK_ADDR_rsp.\r\n" );

                                                // Skip over the IEEE address of the responder.
                                                for (data=0; data<8; data++)
                                                {
                                                    APLGet();
                                                    transByte++;
                                                }
                                                destinationAddress.byte.LSB = APLGet();
                                                destinationAddress.byte.MSB = APLGet();
                                                transByte += 2;
                                                myStatusFlags.bits.bDestinationAddressKnown = 1;
                                            }
                                            break;
                                        default:
                                            break;
                                    }

                                    // Read out the rest of the MSG in case there is another transaction.
                                    for (; transByte<dataLength; transByte++)
                                    {
                                        APLGet();
                                    }
                                }
                            }
                            break;

                        // ************************************************************************
                        // Place a case for each user defined endpoint.
                        // ************************************************************************
                        case EP_LIGHT:
                            if ((frameHeader & APL_FRAME_TYPE_MASK) == APL_FRAME_TYPE_KVP)
                            {
                                frameHeader &= APL_FRAME_COUNT_MASK;
                                for (transaction=0; transaction<frameHeader; transaction++)
                                {
                                    sequenceNumber          = APLGet();
                                    command                 = APLGet();
                                    attributeId.byte.LSB    = APLGet();
                                    attributeId.byte.MSB    = APLGet();

                                    //dataType = command & APL_FRAME_DATA_TYPE_MASK;
                                    command &= APL_FRAME_COMMAND_MASK;

                                    if ((params.APSDE_DATA_indication.ClusterId == OnOffSRC_CLUSTER) &&
                                        (attributeId.Val == OnOffSRC_OnOff))
                                    {
                                        if ((command == APL_FRAME_COMMAND_SET) ||
                                            (command == APL_FRAME_COMMAND_SETACK))
                                        {
                                            // Prepare a response in case it is needed.
                                            TxBuffer[TxData++] = APL_FRAME_TYPE_KVP | 1;    // KVP, 1 transaction
                                            TxBuffer[TxData++] = sequenceNumber;
                                            TxBuffer[TxData++] = APL_FRAME_COMMAND_SET_RES | (APL_FRAME_DATA_TYPE_UINT8 << 4);
                                            TxBuffer[TxData++] = attributeId.byte.LSB;
                                            TxBuffer[TxData++] = attributeId.byte.MSB;

                                            // Data type for this attibute must be APL_FRAME_DATA_TYPE_UINT8
                                            data = APLGet();
                                            switch (data)
                                            {
                                                case LIGHT_OFF:
                                                    ConsolePutROMString( (ROM char *)" Turning light off.\r\n" );
                                                    LEVEL_SENSOR_LED = 0;
                                                    TxBuffer[TxData++] = SUCCESS;
                                                    break;
                                                case LIGHT_ON:
                                                    ConsolePutROMString( (ROM char *)" Turning light on.\r\n" );
                                                    LEVEL_SENSOR_LED = 1;
                                                    TxBuffer[TxData++] = SUCCESS;
                                                    break;
                                                case LIGHT_TOGGLE:
                                                    ConsolePutROMString( (ROM char *)" Toggling light.\r\n" );
                                                    LEVEL_SENSOR_LED ^= 1;
                                                    TxBuffer[TxData++] = SUCCESS;
                                                    break;
                                                default:
                                                    PrintChar( data );
                                                    ConsolePutROMString( (ROM char *)" Invalid light message.\r\n" );
                                                    TxBuffer[TxData++] = KVP_INVALID_ATTRIBUTE_DATA;
                                                    break;
                                            }
                                        }
                                        if (command == APL_FRAME_COMMAND_SETACK)
                                        {
                                            // Send back an application level acknowledge.
                                            ZigBeeBlockTx();

                                            // Take care here that parameters are not overwritten before they are used.
                                            // We can use the data byte as a temporary variable.
                                            params.APSDE_DATA_request.DstAddrMode = params.APSDE_DATA_indication.SrcAddrMode;
                                            params.APSDE_DATA_request.DstEndpoint = params.APSDE_DATA_indication.SrcEndpoint;
                                            params.APSDE_DATA_request.DstAddress.ShortAddr = params.APSDE_DATA_indication.SrcAddress.ShortAddr;

                                            //params.APSDE_DATA_request.asduLength; TxData
                                            //params.APSDE_DATA_request.ProfileId; unchanged
                                            params.APSDE_DATA_request.RadiusCounter = DEFAULT_RADIUS;
                                            params.APSDE_DATA_request.DiscoverRoute = ROUTE_DISCOVERY_ENABLE;
											#ifdef I_SUPPORT_SECURITY
												params.APSDE_DATA_request.TxOptions.Val = 1;
											#else											                                            
                                            	params.APSDE_DATA_request.TxOptions.Val = 0;
											#endif                                            
                                            params.APSDE_DATA_request.SrcEndpoint = EP_LIGHT;
                                            //params.APSDE_DATA_request.ClusterId; unchanged

                                            currentPrimitive = APSDE_DATA_request;
                                        }
                                        else
                                        {
                                            // We are not sending an acknowledge, so reset the transmit message pointer.
                                            TxData = TX_DATA_START;
                                        }
                                    }
                                    // TODO read to the end of the transaction.
                                } // each transaction
                            } // frame type
                            break;
                          
                        default:               
                			break;
                	}

                    APLDiscardRx();
                }
                break;

            case APSDE_DATA_confirm:
                if (params.APSDE_DATA_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Error " );
                    PrintChar( params.APSDE_DATA_confirm.Status );
                    ConsolePutROMString( (ROM char *)" sending message.\r\n" );
                }
                else
                {
                    ConsolePutROMString( (ROM char *)" Message sent successfully.\r\n" );
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NO_PRIMITIVE:
                if (!ZigBeeStatus.flags.bits.bNetworkJoined)
                {
                    if (!ZigBeeStatus.flags.bits.bTryingToJoinNetwork)
                    {
                        if (ZigBeeStatus.flags.bits.bTryOrphanJoin)
                        {
                            ConsolePutROMString( (ROM char *)"Trying to join network as an orphan...\r\n" );
                            params.NLME_JOIN_request.JoinAsRouter           = FALSE;
                            params.NLME_JOIN_request.RejoinNetwork          = TRUE;
                            params.NLME_JOIN_request.PowerSource            = NOT_MAINS_POWERED;
                            params.NLME_JOIN_request.RxOnWhenIdle           = FALSE;
                            params.NLME_JOIN_request.MACSecurity            = FALSE;
                            params.NLME_JOIN_request.ScanDuration           = 8;
                            params.NLME_JOIN_request.ScanChannels.Val       = ALLOWED_CHANNELS;
                            currentPrimitive = NLME_JOIN_request;
                        }
                        else
                        {
                            ConsolePutROMString( (ROM char *)"Trying to join network as a new device...\r\n" );
                            params.NLME_NETWORK_DISCOVERY_request.ScanDuration          = 6;
                            params.NLME_NETWORK_DISCOVERY_request.ScanChannels.Val      = ALLOWED_CHANNELS;
                            currentPrimitive = NLME_NETWORK_DISCOVERY_request;
                        }
                    }
                }
                else
                {
                    // See if I can do my own internal tasks.  We don't want to try to send a message
                    // if we just asked for one.
                    if (ZigBeeStatus.flags.bits.bDataRequestComplete && ZigBeeReady())
                    {

                        // ************************************************************************
                        // Place all processes that can send messages here.  Be sure to call
                        // ZigBeeBlockTx() when currentPrimitive is set to APSDE_DATA_request.
                        // ************************************************************************
                        if ( myStatusFlags.bits.bMoveSensorButtonPressed)
                        {
                            // Send a light toggle message to the other node.
                            myStatusFlags.bits.bMoveSensorButtonPressed = FALSE;

							BLINK_LED(MOVE_SENSOR_LED);							

							// envia a mensagem para ligar/desligar o led
							RFDSendMessage(MoveSensor_Activated, 0x00);                
                        }
                        else if (myStatusFlags.bits.bLevelSensorButtonPressed)
                        {
                        	// Envia mensagem indicando que o sensor de nível foi acionado

                            myStatusFlags.bits.bLevelSensorButtonPressed = FALSE;

							BLINK_LED(LEVEL_SENSOR_LED);

							RFDSendMessage(LevelSensor_Activated, 0x00);                                
                        }

                        // We've processed any key press, so re-enable interrupts.
                        INTCONbits.RBIE = 1;
                    }

                    // If we don't have to execute a primitive, see if we need to request data from
                    // our parent, or if we can go to sleep.
                    if (currentPrimitive == NO_PRIMITIVE)
                    {
                        if (!ZigBeeStatus.flags.bits.bDataRequestComplete)
                        {
                            // We have not received all data from our parent.  If we are not waiting
                            // for an answer from a data request, send a data request.
                            if (!ZigBeeStatus.flags.bits.bRequestingData)
                            {
                                if (ZigBeeReady())
                                {
                                    // Our parent still may have data for us.
                                    params.NLME_SYNC_request.Track = FALSE;
                                    currentPrimitive = NLME_SYNC_request;
                                    ConsolePutROMString( (ROM char *)"Requesting data...\r\n" );
                                }
                            }
                        }
                        else
                        {
                            if (!ZigBeeStatus.flags.bits.bHasBackgroundTasks && myProcessesAreDone())
                            {
                                // We do not have a primitive to execute, we've extracted all messages
                                // that our parent has for us, the stack has no background tasks,
                                // and all application-specific processes are complete.  Now we can
                                // go to sleep.  Make sure that the UART is finished, turn off the transceiver,
                                // and make sure that we wakeup from key press.
                                if(APLDisable() == TRUE)
                                {
	                                ConsolePutROMString( (ROM char *)"Going to sleep...\r\n" );
    	                            while (!ConsoleIsPutReady());
                                	APLDisable();
    	                            INTCONbits.RBIE = 1;
	                                SLEEP();
        	                        NOP();

	                                // We just woke up from sleep. Turn on the transceiver and
	                                // request data from our parent.
	                                APLEnable();
	                                params.NLME_SYNC_request.Track = FALSE;
	                                currentPrimitive = NLME_SYNC_request;
	                                ConsolePutROMString( (ROM char *)"Requesting data...\r\n" );
								}
                            }
                        }
                    }
                }
                break;

            default:
                PrintChar( currentPrimitive );
                ConsolePutROMString( (ROM char *)" Unhandled primitive.\r\n" );
                currentPrimitive = NO_PRIMITIVE;
        }

        // *********************************************************************
        // Place any non-ZigBee related processing here.  Be sure that the code
        // will loop back and execute ZigBeeTasks() in a timely manner.
        // *********************************************************************

    }
}
Esempio n. 29
0
// Main - Set things up, call the pattern generator.
int main (void) {

  int i;

  // Reserve the pixel data memory.
  galaxyData_t galaxy;                // Contains an array of pointers to pixels.
  color_t actualPixels[PIXEL_COUNT];  // Sets aside memory for the actual pixels.

  galaxy.size = PIXEL_COUNT;

  // Map the array of pointers to the actual pixel memory.
  for (i = 0; i < PIXEL_COUNT; i++) {
    galaxy.pixels[i] = &actualPixels[i];
  }

  // Seed the pseudorandom number generator.
  srand(25);

  // Initialize the PIC hardware
  HardwareInit();

  // Initialize the emulator hardware.
#ifdef EMULATE
  // Init the display window.
  // SDL, Simple DirectMedia Layer, is a library for access to the keyboard,
  // and graphics hardware.  See www.libsdl.org  
  if (SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0) {
    fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
    exit(EXIT_FAILURE);
  } else {
    // Register an exit callback to cleanup SDL.
    atexit(SDL_Quit);
  }

   // Initialize the SDL surfaces.
  SDL_CreateWindowAndRenderer(INITIAL_WINDOW_WIDTH, INITIAL_WINDOW_HEIGHT,
                              SDL_WINDOW_RESIZABLE, &sdlWindow, &sdlRenderer);
  if ((sdlWindow == NULL) || (sdlRenderer == NULL)) {
    fprintf(stderr, "Unable to create SDL window or renderer! %s\n", SDL_GetError());
    exit(EXIT_FAILURE);
  }

  // Set the window title
  WindowTitle(delayMultiplier);

  // Clear the window to black.
  SDL_SetRenderDrawColor(sdlRenderer, 0, 0, 0, 255);
  SDL_RenderClear(sdlRenderer);
  SDL_RenderPresent(sdlRenderer);

  // Generate the output pixel map
  GeneratePixelMap(INITIAL_WINDOW_WIDTH, INITIAL_WINDOW_HEIGHT);

  // Print version information.
  if (strlen(PRERELEASE_VERSION) == 0) {
    printf("Galaxy Emulator v%s.%s.%s\n", MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION);
  } else {
    printf("Galaxy Emulator v%s.%s.%s-%s\n", MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION, PRERELEASE_VERSION);
  }
  printf("Keys: ESC, <ctrl> c, q - Quit\n");
  printf("      +                - Increase emulation speed\n");
  printf("      -                - Decrease emulation speed\n");
  printf("      0                - Set emulation speed to 100%%\n");
  printf("      p                - Pause / unpause the simulation\n");
  printf("      SPACE            - Go to another pattern\n");
  printf("The emulator window must have focus for the key presses to work.\n");
#endif

  // Hand off control to the pattern generator.
  GeneratePattern(&galaxy);

  // We can only get this far on the emulator.
  exit(EXIT_SUCCESS);  // Required on the emu target for SDL cleanup.
  return(0);  // Never happens.
}
void main(void)
{
    CLRWDT();
    ENABLE_WDT();

    currentPrimitive = NO_PRIMITIVE;
    NetworkDescriptor = NULL;

    // If you are going to send data to a terminal, initialize the UART.
    ConsoleInit();

    // Initialize the hardware - must be done before initializing ZigBee.
    HardwareInit();

    // Initialize the ZigBee Stack.
    ZigBeeInit();


    // *************************************************************************
    // Perform any other initialization here
    // *************************************************************************


    // Enable interrupts to get everything going.
    IPEN = 1;
    GIEH = 1;

    while (1)
    {
        CLRWDT();
        ZigBeeTasks( &currentPrimitive );

        switch (currentPrimitive)
        {
            case NLME_NETWORK_DISCOVERY_confirm:
                currentPrimitive = NO_PRIMITIVE;
                if (!params.NLME_NETWORK_DISCOVERY_confirm.Status)
                {
                    if (!params.NLME_NETWORK_DISCOVERY_confirm.NetworkCount)
                    {
                        ConsolePutROMString( (ROM char *)"No networks found.  Trying again...\r\n" );
                    }
                    else
                    {
                        // Save the descriptor list pointer so we can destroy it later.
                        NetworkDescriptor = params.NLME_NETWORK_DISCOVERY_confirm.NetworkDescriptor;

                        // Select a network to try to join.  We're not going to be picky right now...
                        currentNetworkDescriptor = NetworkDescriptor;

                        // not needed for new join params.NLME_JOIN_request.ScanDuration = ;
                        // not needed for new join params.NLME_JOIN_request.ScanChannels = ;
                        params.NLME_JOIN_request.PANId          = currentNetworkDescriptor->PanID;
                        params.NLME_JOIN_request.JoinAsRouter   = FALSE;
                        params.NLME_JOIN_request.RejoinNetwork  = FALSE;
                        params.NLME_JOIN_request.PowerSource    = NOT_MAINS_POWERED;
                        params.NLME_JOIN_request.RxOnWhenIdle   = FALSE;
                        params.NLME_JOIN_request.MACSecurity    = FALSE;
                        currentPrimitive = NLME_JOIN_request;

                        ConsolePutROMString( (ROM char *)"Network(s) found. Trying to join " );
                        PrintChar( params.NLME_JOIN_request.PANId.byte.MSB );
                        PrintChar( params.NLME_JOIN_request.PANId.byte.LSB );
                        ConsolePutROMString( (ROM char *)".\r\n" );
                    }
                }
                else
                {
                    PrintChar( params.NLME_NETWORK_DISCOVERY_confirm.Status );
                    ConsolePutROMString( (ROM char *)" Error finding network.  Trying again...\r\n" );
                }
                break;

            case NLME_JOIN_confirm:
                currentPrimitive = NO_PRIMITIVE;
                if (!params.NLME_JOIN_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Join successful!\r\n" );
                    if (NetworkDescriptor)
                    {
                        // If we joined as an orphan, this will be NULL.
                        free( NetworkDescriptor );
                    }

                    // We are now on the network.  Enable routing.
                    params.NLME_START_ROUTER_request.BeaconOrder = MAC_PIB_macBeaconOrder;
                    params.NLME_START_ROUTER_request.SuperframeOrder = MAC_PIB_macSuperframeOrder;
                    params.NLME_START_ROUTER_request.BatteryLifeExtension = FALSE;
                    currentPrimitive = NLME_START_ROUTER_request;
                }
                else
                {
                    PrintChar( params.NLME_JOIN_confirm.Status );
                    ConsolePutROMString( (ROM char *)" Could not join. Trying again as new device..." );
                }
                break;

            case NLME_LEAVE_indication:
                if (!memcmppgm2ram( &params.NLME_LEAVE_indication.DeviceAddress, (ROM void *)&macLongAddr, 8 ))
                {
                    ConsolePutROMString( (ROM char *)"We have left the network.\r\n" );
                }
                else
                {
                    ConsolePutROMString( (ROM char *)"Another node has left the network.\r\n" );
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NLME_RESET_confirm:
                ConsolePutROMString( (ROM char *)"ZigBee Stack has been reset.\r\n" );
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NLME_START_ROUTER_confirm:
                if (!params.NLME_START_ROUTER_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Router Started!\r\n" );
                }
                else
                {
                    PrintChar( params.NLME_JOIN_confirm.Status );
                    ConsolePutROMString( (ROM char *)" Router start unsuccessful. We cannot route frames.\r\n" );
                }

                // We are now ready to do ZigBee related tasks.
                currentPrimitive = NO_PRIMITIVE;
                break;

            case APSDE_DATA_indication:
                {
                    WORD_VAL    attributeId;
                    BYTE        command;
                    BYTE        data;
                    BYTE        dataLength;
                    //BYTE        dataType;
                    BYTE        frameHeader;
                    BYTE        sequenceNumber;
                    BYTE        transaction;
                    BYTE        transByte;

                    currentPrimitive = NO_PRIMITIVE;
                    frameHeader = APLGet();

                    switch (params.APSDE_DATA_indication.DstEndpoint)
                    {
                        case EP_ZDO:
                            if ((frameHeader & APL_FRAME_TYPE_MASK) == APL_FRAME_TYPE_MSG)
                            {
                                frameHeader &= APL_FRAME_COUNT_MASK;
                                for (transaction=0; transaction<frameHeader; transaction++)
                                {
                                    sequenceNumber          = APLGet();
                                    dataLength              = APLGet();
                                    transByte               = 0;

                                    switch( params.APSDE_DATA_indication.ClusterId )
                                    {

                                        // ********************************************************
                                        // Put a case here to handle each ZDO response that we requested.
                                        // Be sure to increment transByte for each APLGet().
                                        // ********************************************************

                                        default:
                                            break;
                                    }

                                    // Read out the rest of the MSG in case there is another transaction.
                                    for (; transByte<dataLength; transByte++)
                                    {
                                        APLGet();
                                    }
                                }
                            }
                            break;

                        // ************************************************************************
                        // Place a case for each user defined endpoint.
                        // ************************************************************************

                        default:
                            // If the command type was something that requested an acknowledge, we could send back
                            // KVP_INVALID_ENDPOINT here.
                            break;
                    }
                    APLDiscardRx();
                }
                break;

            case APSDE_DATA_confirm:
                if (params.APSDE_DATA_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Error " );
                    PrintChar( params.APSDE_DATA_confirm.Status );
                    ConsolePutROMString( (ROM char *)" sending message.\r\n" );
                }
                else
                {
                    ConsolePutROMString( (ROM char *)" Message sent successfully.\r\n" );
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NO_PRIMITIVE:
                if (!ZigBeeStatus.flags.bits.bNetworkJoined)
                {
                    if (!ZigBeeStatus.flags.bits.bTryingToJoinNetwork)
                    {
                        if (ZigBeeStatus.flags.bits.bTryOrphanJoin)
                        {
                            ConsolePutROMString( (ROM char *)"Trying to join network as an orphan...\r\n" );
                            params.NLME_JOIN_request.ScanDuration       = 8;
                            params.NLME_JOIN_request.ScanChannels.Val   = ALLOWED_CHANNELS;
                            // not needed for orphan join - params.NLME_JOIN_request.PANId
                            params.NLME_JOIN_request.JoinAsRouter       = FALSE;
                            params.NLME_JOIN_request.RejoinNetwork      = TRUE;
                            params.NLME_JOIN_request.PowerSource        = NOT_MAINS_POWERED;
                            params.NLME_JOIN_request.RxOnWhenIdle       = FALSE;
                            params.NLME_JOIN_request.MACSecurity        = FALSE;
                            currentPrimitive = NLME_JOIN_request;
                        }
                        else
                        {
                            ConsolePutROMString( (ROM char *)"Trying to join network as a new device...\r\n" );
                            params.NLME_NETWORK_DISCOVERY_request.ScanDuration          = 8;
                            params.NLME_NETWORK_DISCOVERY_request.ScanChannels.Val      = ALLOWED_CHANNELS;
                            currentPrimitive = NLME_NETWORK_DISCOVERY_request;
                        }
                    }
                }
                else
                {
                    // See if we can do our own internal tasks.
                    if (ZigBeeReady())
                    {

                        // ************************************************************************
                        // Place all processes that can send messages here.  Be sure to call
                        // ZigBeeBlockTx() when currentPrimitive is set to APSDE_DATA_request.
                        // ************************************************************************

                    }
                }
                break;

            default:
                PrintChar( currentPrimitive );
                ConsolePutROMString( (ROM char *)" Unhandled primitive.\r\n" );
                currentPrimitive = NO_PRIMITIVE;
                break;
        }

        // *********************************************************************
        // Place any non-ZigBee related processing here.  Be sure that the code
        // will loop back and execute ZigBeeTasks() in a timely manner.
        // *********************************************************************

    }
}