//************************************************************************* // InitPICE() // //************************************************************************* BOOLEAN InitPICE(void) { ULONG ulHandleScancode=0,ulHandleKbdEvent=0; ARGS Args; KIRQL Dirql; KAFFINITY Affinity; ULONG ulAddr; ENTER_FUNC(); DPRINT((0,"InitPICE(): trace step 0.5\n")); KeyboardIRQL = HalGetInterruptVector(Internal, 0, 0, KEYBOARD_IRQ, &Dirql, &Affinity); DPRINT((0,"KeyboardIRQL: %x\n", KeyboardIRQL)); DPRINT((0,"InitPICE(): trace step 1\n")); // enable monochrome passthrough on BX type chipset EnablePassThrough(); DPRINT((0,"InitPICE(): trace step 2\n")); // now load all symbol files described in /etc/pice.conf if(!LoadSymbolsFromConfig(FALSE)) { DPRINT((0,"InitPICE: LoadSymbolsFromConfig() failed\n")); LEAVE_FUNC(); return FALSE; } DPRINT((0,"InitPICE(): trace step 3\n")); // init the output console // this might be one of the following depending setup // a) monochrome card // b) serial terminal (TODO) if(!ConsoleInit()) { DPRINT((0,"InitPICE: ConsoleInit() failed\n")); UnloadSymbols(); LEAVE_FUNC(); return FALSE; } DPRINT((0,"InitPICE(): trace step 4\n")); // print the initial screen template PrintTemplate(); /* DPRINT((0,"InitPICE(): trace step 5\n")); // ask the user if he wants to abort the debugger load if(!CheckLoadAbort()) { Print(OUTPUT_WINDOW,"pICE: ABORT (abort by user)\n"); UnloadSymbols(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } */ DPRINT((0,"InitPICE(): trace step 6\n")); // load the file /boot/System.map. // !!! It must be consistent with the current kernel at all cost!!! if(!LoadExports()) { Print(OUTPUT_WINDOW,"pICE: failed to load exports\n"); Print(OUTPUT_WINDOW,"press any key to continue...\n"); while(!GetKeyPolled()); UnloadSymbols(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } DPRINT((0,"InitPICE(): trace step 7\n")); ScanExports("_KernelAddressSpace", &ulAddr); my_init_mm = (PMADDRESS_SPACE) ulAddr; DPRINT((0,"init_mm %x @ %x\n",&my_init_mm,my_init_mm)); if(!my_init_mm) { Print(OUTPUT_WINDOW,"pICE: ABORT (initial memory map not found)\n"); Print(OUTPUT_WINDOW,"pICE: press any key to continue...\n"); DbgPrint("pICE: ABORT (initial memory map not found)\n"); DbgPrint("pICE: press any key to continue...\n"); while(!GetKeyPolled()); UnloadSymbols(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } DPRINT((0,"InitPICE(): trace step 7.1\n")); ScanExports("_ModuleListHead",&ulAddr); pModuleListHead = (LIST_ENTRY*)ulAddr; DPRINT((0,"pModuleListHead @ %X\n",pModuleListHead)); if(!pModuleListHead) { Print(OUTPUT_WINDOW,"pICE: ABORT (pModuleListHead not found)\n"); Print(OUTPUT_WINDOW,"pICE: press any key to continue...\n"); while(!GetKeyPolled()); UnloadSymbols(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } DPRINT((0,"InitPICE(): trace step 7.2\n")); ScanExports("_PsProcessListHead",&ulAddr); pPsProcessListHead = (LIST_ENTRY*)ulAddr; DPRINT((0,"pPsProcessListHead @ %X\n",pPsProcessListHead)); if(!pPsProcessListHead) { Print(OUTPUT_WINDOW,"pICE: ABORT (PsProcessListHead not found)\n"); Print(OUTPUT_WINDOW,"pICE: press any key to continue...\n"); while(!GetKeyPolled()); UnloadSymbols(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } DPRINT((0,"InitPICE(): trace step 8\n")); // end of the kernel /* ScanExports("_end",(PULONG)&kernel_end); if(!kernel_end) { Print(OUTPUT_WINDOW,"pICE: ABORT (kernel size is unknown)\n"); Print(OUTPUT_WINDOW,"pICE: press any key to continue...\n"); while(!GetKeyPolled()); UnloadExports(); UnloadSymbols(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } */ DPRINT((0,"InitPICE(): trace step 9\n")); // the loaded module list ScanExports("_NameSpaceRoot", &ulAddr); pNameSpaceRoot = (PDIRECTORY_OBJECT *)ulAddr; DPRINT((0,"pNameSpaceRoot @ %X\n",pNameSpaceRoot)); if(!pNameSpaceRoot) { Print(OUTPUT_WINDOW,"pICE: ABORT (couldn't retreive name space root)\n"); Print(OUTPUT_WINDOW,"pICE: press any key to continue...\n"); while(!GetKeyPolled()); UnloadExports(); UnloadSymbols(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } DPRINT((0,"InitPICE(): trace step 10\n")); // setup a linked list for use in module parsing routines. if(!InitModuleList(&pdebug_module_head, 100)) { Print(OUTPUT_WINDOW,"pICE: ABORT (couldn't initialize kernel module list)\n"); Print(OUTPUT_WINDOW,"pICE: press any key to continue...\n"); FreeModuleList( pdebug_module_head ); while(!GetKeyPolled()); UnloadExports(); UnloadSymbols(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } pdebug_module_tail = pdebug_module_head; DPRINT((0,"InitPICE(): trace step 11\n")); // do a sanity check on exports if(!SanityCheckExports()) { Print(OUTPUT_WINDOW,"pICE: ABORT (exports are conflicting with kernel symbols)\n"); Print(OUTPUT_WINDOW,"pICE: press any key to continue...\n"); while(!GetKeyPolled()); UnloadExports(); UnloadSymbols(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } DPRINT((0,"InitPICE(): trace step 12\n")); DPRINT((0,"InitPICE(): trace step 13\n")); // patch the keyboard driver if(!PatchKeyboardDriver()) { Print(OUTPUT_WINDOW,"pICE: ABORT (couldn't patch keyboard driver)\n"); Print(OUTPUT_WINDOW,"pICE: press any key to continue...\n"); while(!GetKeyPolled()); UnloadSymbols(); UnloadExports(); ConsoleShutdown(); LEAVE_FUNC(); return FALSE; } DPRINT((0,"InitPICE(): trace step 14\n")); // partial init of shadow registers CurrentCS = GLOBAL_CODE_SEGMENT; CurrentEIP = (ULONG)RealIsr; CurrentDS = CurrentSS = GLOBAL_DATA_SEGMENT; __asm__("\n\t \ mov %%esp,%%eax\n\t \ mov %%eax,_CurrentESP\n\t \ ":::"eax"); // display version and symbol information Ver(NULL); // disable HW breakpoints __asm__("\n\t \ xorl %%eax,%%eax\n\t \ mov %%eax,%%dr6\n\t \ mov %%eax,%%dr7\n\t \ mov %%dr0,%%eax\n\t \ mov %%dr1,%%eax\n\t \ mov %%dr2,%%eax\n\t \ mov %%dr3,%%eax" :::"eax" ); DPRINT((0,"InitPICE(): trace step 15\n")); TakeIdtSnapshot(); DPRINT((0,"InitPICE(): trace step 16\n")); // install all hooks InstallTraceHook(); InstallGlobalKeyboardHook(); InstallSyscallHook(); InstallInt3Hook(); InstallDblFltHook(); InstallGPFaultHook(); InstallIntEHook(); InstallPrintkHook(); DPRINT((0,"InitPICE(): trace step 16\n")); if(ulDoInitialBreak) { DPRINT((0,"about to do initial break...\n")); // simulate an initial break __asm__("\n\t \ pushfl\n\t \ pushl %cs\n\t \ pushl $initialreturnpoint\n\t \ pushl $" STR(REASON_CTRLF) "\n\t \ jmp NewInt31Handler\n\t \ initialreturnpoint:"); } else {
/************************************************************************* main ==== **************************************************************************/ int main(void) { IODIR0 |= (1<<10);//Debug LED on the olimex 2148 dev board set to output mode IODIR0 |= (1<<11);//Debug LED on the olimex 2148 dev board set to output mode // PLL and MAM HalSysInit(); #ifdef LPC214x // init DBG ConsoleInit(60000000 / (16 * BAUD_RATE)); #else // init DBG ConsoleInit(72000000 / (16 * BAUD_RATE)); #endif DBG("Initialising USB stack\n"); // initialise stack USBInit(); // register descriptors USBRegisterDescriptors(abDescriptors); // register class request handler USBRegisterRequestHandler(REQTYPE_TYPE_CLASS, HandleClassRequest, abClassReqData); // register endpoint handlers USBHwRegisterEPIntHandler(INT_IN_EP, NULL); // register frame handler USBHwRegisterFrameHandler(USBFrameHandler); // register device event handler USBHwRegisterDevIntHandler(USBDevIntHandler); inputIsocDataBuffer[0] = 0; USBInitializeUSBDMA(udcaHeadArray); USBEnableDMAForEndpoint(ISOC_IN_EP); DBG("Starting USB communication\n"); #ifdef LPC214x (*(&VICVectCntl0+INT_VECT_NUM)) = 0x20 | 22; // choose highest priority ISR slot (*(&VICVectAddr0+INT_VECT_NUM)) = (int)USBIntHandler; #else VICVectCntl22 = 0x01; VICVectAddr22 = (int)USBIntHandler; #endif // set up USB interrupt VICIntSelect &= ~(1<<22); // select IRQ for USB VICIntEnable |= (1<<22); enableIRQ(); // connect to bus USBHwConnect(TRUE); int x = 0; const int interval = 200000; // echo any character received (do USB stuff in interrupt) for(;;) { x++; if (x == interval) { IOSET0 = (1<<11);//turn on led on olimex dev board } else if (x >= (interval*2)) { IOCLR0 = (1<<11);//turn off led on olimex dev board x = 0; } } return 0; }
int main(void) #endif { BYTE i, j; BYTE TxSynCount = 0; BYTE TxNum = 0; BYTE RxNum = 0; BOOL bReceivedMessage = FALSE; /*******************************************************************/ // Initialize the system /*******************************************************************/ BoardInit(); ConsoleInit(); DemoOutput_Greeting(); /*******************************************************************/ // Function MiApp_ProtocolInit initialize the protocol stack. The // only input parameter indicates if previous network configuration // should be restored. In this example, if button 1 is pressed and // hold when powering up, we assume the user would like to enable // the Network Freezer and load previous network configuration // from NVM. /*******************************************************************/ if( (PUSH_BUTTON_1 == 0) && ( MiApp_ProtocolInit(TRUE) == TRUE ) ) { DemoOutput_NetworkFreezer(); LED_1 = 1; while(PUSH_BUTTON_1 == 0); } else { /*******************************************************************/ // Function MiApp_ProtocolInit initialize the protocol stack. In // this example, if button 1 is released when powering up, we assume // that the user want the network to start from scratch. /*******************************************************************/ MiApp_ProtocolInit(FALSE); LED_1 = 0; LED_2 = 0; myChannel = 0xFF; DemoOutput_StartActiveScan(); /*******************************************************************/ // Function MiApp_SearchConnection will return the number of // existing connections in all channels. It will help to decide // which channel to operate on and which connection to add. // The return value is the number of connections. The connection // data are stored in global variable ActiveScanResults. // Maximum active scan result is defined as // ACTIVE_SCAN_RESULT_SIZE // The first parameter is the scan duration, which has the same // definition in Energy Scan. 10 is roughly 1 second. 9 is a // half second and 11 is 2 seconds. Maximum scan duration is 14, // or roughly 16 seconds. // The second parameter is the channel map. Bit 0 of the // double word parameter represents channel 0. For the 2.4GHz // frequency band, all possible channels are channel 11 to // channel 26. As the result, the bit map is 0x07FFF800. Stack // will filter out all invalid channels, so the application // only needs to pay attention to the channels that are not // preferred. /*******************************************************************/ i = MiApp_SearchConnection(10, 0xFFFFFFFF); DemoOutput_ActiveScanResults(i); /*******************************************************************/ // Function MiApp_ConnectionMode sets the connection mode for the // protocol stack. Possible connection modes are: // - ENABLE_ALL_CONN accept all connection request // - ENABLE_PREV_CONN accept only known device to connect // - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but // allow response to active scan // - DISABLE_ALL_CONN disable all connection request, including // active scan request /*******************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); if( i > 0 ) { /*******************************************************************/ // Function MiApp_EstablishConnection try to establish a new // connection with peer device. // The first parameter is the index to the active scan result, which // is acquired by discovery process (active scan). If the value // of the index is 0xFF, try to establish a connection with any // peer. // The second parameter is the mode to establish connection, either // direct or indirect. Direct mode means connection within the // radio range; Indirect mode means connection may or may not // in the radio range. /*******************************************************************/ if( MiApp_EstablishConnection(0, CONN_MODE_DIRECT) == 0xFF ) { DemoOutput_JoinFail(); } } else { DemoOutput_EnergyScan(); /*******************************************************************/ // Function MiApp_StartConnection tries to start a new network // // The first parameter is the mode of start connection. There are // two valid connection modes: // - START_CONN_DIRECT start the connection on current // channel // - START_CONN_ENERGY_SCN perform an energy scan first, // before starting the connection on // the channel with least noise // - START_CONN_CS_SCN perform a carrier sense scan // first, before starting the // connection on the channel with // least carrier sense noise. Not // supported for current radios // // The second parameter is the scan duration, which has the same // definition in Energy Scan. 10 is roughly 1 second. 9 is a // half second and 11 is 2 seconds. Maximum scan duration is // 14, or roughly 16 seconds. // // The third parameter is the channel map. Bit 0 of the // double word parameter represents channel 0. For the 2.4GHz // frequency band, all possible channels are channel 11 to // channel 26. As the result, the bit map is 0x07FFF800. Stack // will filter out all invalid channels, so the application // only needs to pay attention to the channels that are not // preferred. /*******************************************************************/ MiApp_StartConnection(START_CONN_ENERGY_SCN, 10, 0xFFFFFFFF); } // Turn on LED 1 to indicate ready to accept new connections LED_1 = 1; } DumpConnection(0xFF); DemoOutput_StartConnection(); DemoOutput_Instruction(); while(1) { /*******************************************************************/ // Function MiApp_MessageAvailable will return a boolean to indicate // if a message for application layer has been received by the // transceiver. If a message has been received, all information will // be stored in the rxMessage, structure of RECEIVED_MESSAGE. /*******************************************************************/ if( MiApp_MessageAvailable() ) { DemoOutput_HandleMessage(); /*******************************************************************/ // Function MiApp_DiscardMessage is used to release the current // received message. After calling this function, the stack can // start to process the next received message. /*******************************************************************/ MiApp_DiscardMessage(); // Toggle LED2 to indicate receiving a packet. LED_2 ^= 1; bReceivedMessage = TRUE; DemoOutput_UpdateTxRx(TxNum, ++RxNum); } else { /*******************************************************************/ // If no packet received, now we can check if we want to send out // any information. // Function ButtonPressed will return if any of the two buttons // has been pushed. /*******************************************************************/ BYTE PressedButton = ButtonPressed(); switch( PressedButton ) { case 1: { DWORD ChannelMap = ~((DWORD)0x00000001 << currentChannel); DemoOutput_InitFreqHop(); /*******************************************************************/ // Function MiApp_InitChannelHopping will start the process of // channel hopping. This function can be only called by Frquency // Agility starter and the device must have the energy detection // feature turned on. This function will do an energy detection // scan of all input channels and start the process of jumping to // the channel with least noise // // The only parameter of this function is the bit map of the // allowed channels. Bit 0 of the double word parameter represents // channel 0. For the 2.4GHz frequency band, the possible channels // are channel 11 to channel 26. As the result, the bit map is // 0x07FFF800. // // Microchip proprietary stack does not limit the application when to // do channel hopping. The typical triggers for channel hopping are: // 1. Continuous data transmission failures // 2. Periodical try the channel hopping process every few hours // or once per day // 3. Receive a request to start the channel hopping process. This // demo is an example of manually issue the request. In the // real application, a Frequency Agility follower can send a // message to request channel hopping and the Frequency Agility // starter will decide if start the process. /*******************************************************************/ if( MiApp_InitChannelHopping(ChannelMap & 0xFFFFFFFF) == TRUE ) { DemoOutput_FreqHopSuccess(); } else { DemoOutput_FreqHopFail(); } } break; case 2: /*******************************************************************/ // Button 2 (RB4 on PICDEM Z or RD7 on Explorer 16) pressed. We need // to send out the bitmap of word "P2P" encrypted. // First call function MiApp_FlushTx to reset the Transmit buffer. // Then fill the buffer one byte by one byte by calling function // MiApp_WriteData /*******************************************************************/ MiApp_FlushTx(); for(i = 0; i < 11; i++) { MiApp_WriteData(DE[(TxSynCount%6)][i]); } TxSynCount++; /*******************************************************************/ // Function MiApp_UnicastConnection is one of the functions to // unicast a message. // The first parameter is the index of connection table for // the peer device. In this demo, since there are only two // devices involved, the peer device must be stored in the // first P2P Connection Entry of the connection table. // The second parameter is the boolean to indicate if we need // to secure the frame. If encryption is applied, the // security level and security key are defined in the // configuration file for the transceiver // // Another way to unicast a message is by calling function // MiApp_UnicastAddress. Instead of supplying the index of the // connection table of the peer device, this function requires the // input parameter of destination address directly. /*******************************************************************/ if( MiApp_UnicastConnection(0, TRUE) == FALSE ) { DemoOutput_UnicastFail(); } else { TxNum++; } DemoOutput_UpdateTxRx(TxNum, RxNum); break; default: break; } } } }
Tcl_Channel TclWinOpenConsoleChannel( HANDLE handle, char *channelName, int permissions) { char encoding[4 + TCL_INTEGER_SPACE]; ConsoleInfo *infoPtr; DWORD id, modes; ConsoleInit(); /* * See if a channel with this handle already exists. */ infoPtr = (ConsoleInfo *) ckalloc((unsigned) sizeof(ConsoleInfo)); memset(infoPtr, 0, sizeof(ConsoleInfo)); infoPtr->validMask = permissions; infoPtr->handle = handle; infoPtr->channel = (Tcl_Channel) NULL; wsprintfA(encoding, "cp%d", GetConsoleCP()); infoPtr->threadId = Tcl_GetCurrentThread(); /* * Use the pointer for the name of the result channel. This keeps the * channel names unique, since some may share handles (stdin/stdout/stderr * for instance). */ wsprintfA(channelName, "file%lx", (int) infoPtr); infoPtr->channel = Tcl_CreateChannel(&consoleChannelType, channelName, (ClientData) infoPtr, permissions); if (permissions & TCL_READABLE) { /* * Make sure the console input buffer is ready for only character * input notifications and the buffer is set for line buffering. IOW, * we only want to catch when complete lines are ready for reading. */ GetConsoleMode(infoPtr->handle, &modes); modes &= ~(ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT); modes |= ENABLE_LINE_INPUT; SetConsoleMode(infoPtr->handle, modes); infoPtr->readable = CreateEvent(NULL, TRUE, TRUE, NULL); infoPtr->startReader = CreateEvent(NULL, FALSE, FALSE, NULL); infoPtr->stopReader = CreateEvent(NULL, FALSE, FALSE, NULL); infoPtr->readThread = CreateThread(NULL, 256, ConsoleReaderThread, infoPtr, 0, &id); SetThreadPriority(infoPtr->readThread, THREAD_PRIORITY_HIGHEST); } if (permissions & TCL_WRITABLE) { infoPtr->writable = CreateEvent(NULL, TRUE, TRUE, NULL); infoPtr->startWriter = CreateEvent(NULL, FALSE, FALSE, NULL); infoPtr->stopWriter = CreateEvent(NULL, FALSE, FALSE, NULL); infoPtr->writeThread = CreateThread(NULL, 256, ConsoleWriterThread, infoPtr, 0, &id); SetThreadPriority(infoPtr->writeThread, THREAD_PRIORITY_HIGHEST); } /* * Files have default translation of AUTO and ^Z eof char, which means * that a ^Z will be accepted as EOF when reading. */ Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto"); Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "\032 {}"); if (tclWinProcs->useWide) Tcl_SetChannelOption(NULL, infoPtr->channel, "-encoding", "unicode"); else Tcl_SetChannelOption(NULL, infoPtr->channel, "-encoding", encoding); return infoPtr->channel; }
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"); }
int main(void) #endif { BYTE i, j; BYTE TxSynCount = 0; BOOL bReceivedMessage = FALSE; _U16 m; #define BAUDRG 77 /*******************************************************************/ // Initialize the system /*******************************************************************/ ANCON0 = 0XFF; /*desactiva entradas analogicas*/ ANCON1 = 0XFF; /*desactiva entradas analogicas*/ PPSUnLock(); PPSOutput(PPS_RP10, PPS_TX2CK2); // TX2 RP17/RC6 PPSInput(PPS_RX2DT2, PPS_RP9); // RX2 RP18/RC7 PPSOutput(PPS_RP23, PPS_SDO2); // SDO2 RP23/RD6 PPSInput(PPS_SDI2, PPS_RP24); // SDI2 RP24/RD7 PPSOutput(PPS_RP22, PPS_SCK2); // SCK2 RP22/RD5 PPSLock(); System_PeripheralPinSelect( ExternalInterrupt3, 19); /*external interrupt 3 B3*/ BoardInit(); ConsoleInit(); Open2USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG); baud2USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF); Gpios_PinDirection(GPIOS_PORTD, 7, GPIOS_INPUT); /*pin C0 como salida para SDI*/ Gpios_PinDirection(GPIOS_PORTD, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/ Gpios_PinDirection(GPIOS_PORTD, 5, GPIOS_OUTPUT); /*pin C2 como salida para SCK*/ Spi_Init(SPI_PORT1, SPI_64DIV); /*Inicializamos SPI2*/ Spi_Init(SPI_PORT2, SPI_64DIV); /*Inicializamos SPI2*/ //Spi_SetMode(SPI_PORT1, 1); //Spi_SetMode(SPI_PORT1, 1); LED_1 = 1; LED_2 = 1; Read_MAC_Address(); LED_1 = 0; LED_2 = 0; ConsolePutROMString((ROM char *)"\r\n<MAC Addr:"); PrintChar(myLongAddress[3]); PrintChar(myLongAddress[2]); PrintChar(myLongAddress[1]); PrintChar(myLongAddress[0]); ConsolePutROMString((ROM char *)"\r>"); Printf("\r\nStarting Testing Interface for MiWi(TM) PRO Stack ..."); #if defined(MRF24J40) Printf("\r\n RF Transceiver: MRF24J40"); #elif defined(MRF49XA) Printf("\r\n RF Transceiver: MRF49XA"); #elif defined(MRF89XA) Printf("\r\n RF Transceiver: MRF89XA"); #endif Printf("\r\n Demo Instruction:"); Printf("\r\n Press Enter to bring up the menu."); Printf("\r\n Type in hyper terminal to choose"); Printf("\r\n menu item. "); Printf("\r\n\r\n"); /*******************************************************************/ // Following block display demo information on LCD of Explore 16 or // PIC18 Explorer demo board. /*******************************************************************/ #if defined(MRF49XA) LCDDisplay((char *)"MiWi PRO Test Interface MRF49XA", 0, TRUE); #elif defined(MRF24J40) LCDDisplay((char *)"MiWi PRO Test Interface MRF24J40", 0, TRUE); #elif defined(MRF89XA) LCDDisplay((char *)"MiWi PRO Test Interface MRF89XA", 0, TRUE); #endif //if( (PUSH_BUTTON_1 == 0) || ( MiApp_ProtocolInit(TRUE) == FALSE ) ) if (PUSH_BUTTON_1 == 1) { MiApp_ProtocolInit(FALSE); LED_1 = 0; LED_2 = 0; #ifdef ENABLE_ACTIVE_SCAN myChannel = 0xFF; ConsolePutROMString((ROM char *)"\r\nStarting Active Scan..."); LCDDisplay((char *)"Active Scanning", 0, FALSE); /*******************************************************************/ // Function MiApp_SearchConnection will return the number of // existing connections in all channels. It will help to decide // which channel to operate on and which connection to add. // The return value is the number of connections. The connection // data are stored in global variable ActiveScanResults. // Maximum active scan result is defined as // ACTIVE_SCAN_RESULT_SIZE // The first parameter is the scan duration, which has the same // definition in Energy Scan. 10 is roughly 1 second. 9 is a // half second and 11 is 2 seconds. Maximum scan duration is 14, // or roughly 16 seconds. // The second parameter is the channel map. Bit 0 of the // double word parameter represents channel 0. For the 2.4GHz // frequency band, all possible channels are channel 11 to // channel 26. As the result, the bit map is 0x07FFF800. Stack // will filter out all invalid channels, so the application // only needs to pay attention to the channels that are not // preferred. /*******************************************************************/ i = MiApp_SearchConnection(10, 0x02000000); if( i > 0 ) { // now print out the scan result. Printf("\r\nActive Scan Results: \r\n"); for(j = 0; j < i; j++) { Printf("Channel: "); PrintDec(ActiveScanResults[j].Channel ); Printf(" RSSI: "); PrintChar(ActiveScanResults[j].RSSIValue); Printf("\r\n"); myChannel = ActiveScanResults[j].Channel; Printf("PeerInfo: "); PrintChar( ActiveScanResults[j].PeerInfo[0]); } } #endif /*******************************************************************/ // Function MiApp_ConnectionMode sets the connection mode for the // protocol stack. Possible connection modes are: // - ENABLE_ALL_CONN accept all connection request // - ENABLE_PREV_CONN accept only known device to connect // - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but // allow response to active scan // - DISABLE_ALL_CONN disable all connection request, including // active scan request /*******************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); if( i > 0 ) { /*******************************************************************/ // Function MiApp_EstablishConnection try to establish a new // connection with peer device. // The first parameter is the index to the active scan result, which // is acquired by discovery process (active scan). If the value // of the index is 0xFF, try to establish a connection with any // peer. // The second parameter is the mode to establish connection, either // direct or indirect. Direct mode means connection within the // radio range; Indirect mode means connection may or may not // in the radio range. /*******************************************************************/ if( MiApp_EstablishConnection(0, CONN_MODE_DIRECT) == 0xFF ) { Printf("\r\nJoin Fail"); } } else { /*******************************************************************/ // Function MiApp_StartConnection tries to start a new network // // The first parameter is the mode of start connection. There are // two valid connection modes: // - START_CONN_DIRECT start the connection on current // channel // - START_CONN_ENERGY_SCN perform an energy scan first, // before starting the connection on // the channel with least noise // - START_CONN_CS_SCN perform a carrier sense scan // first, before starting the // connection on the channel with // least carrier sense noise. Not // supported on currrent radios // // The second parameter is the scan duration, which has the same // definition in Energy Scan. 10 is roughly 1 second. 9 is a // half second and 11 is 2 seconds. Maximum scan duration is // 14, or roughly 16 seconds. // // The third parameter is the channel map. Bit 0 of the // double word parameter represents channel 0. For the 2.4GHz // frequency band, all possible channels are channel 11 to // channel 26. As the result, the bit map is 0x07FFF800. Stack // will filter out all invalid channels, so the application // only needs to pay attention to the channels that are not // preferred. /*******************************************************************/ #ifdef ENABLE_ED_SCAN //LCDDisplay((char *)"Active Scanning Energy Scanning", 0, FALSE); ConsolePutROMString((ROM char *)"\r\nActive Scanning Energy Scanning"); MiApp_StartConnection(START_CONN_ENERGY_SCN, 10, 0x02000000); #endif } // Turn on LED 1 to indicate ready to accept new connections LED_1 = 1; } else { //LCDDisplay((char *)" Network Freezer ENABLED", 0, TRUE); Printf("\r\nNetwork Freezer Feature is enabled. There will be no hand-shake process.\r\n"); LED_1 = 1; DumpConnection(0xFF); } LCDDisplay((char *)"Start Connection on Channel %d", currentChannel, TRUE); LCDDisplay((char *)"Testing Menu on Hyper Terminal", 0, FALSE); while(1) { /*******************************************************************/ // Function MiApp_MessageAvailable will return a boolean to indicate // if a message for application layer has been received by the // transceiver. If a message has been received, all information will // be stored in the rxMessage, structure of RECEIVED_MESSAGE. /*******************************************************************/ if( MiApp_MessageAvailable() ) { /*******************************************************************/ // If a packet has been received, following code prints out some of // the information available in rxFrame. /*******************************************************************/ if( rxMessage.flags.bits.secEn ) { ConsolePutROMString((ROM char *)"Secured "); } if( rxMessage.flags.bits.broadcast ) { ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI "); } else { ConsolePutROMString((ROM char *)"Unicast Packet with RSSI "); } PrintChar(rxMessage.PacketRSSI); if( rxMessage.flags.bits.srcPrsnt ) { ConsolePutROMString((ROM char *)" from "); if( rxMessage.flags.bits.altSrcAddr ) { PrintChar(rxMessage.SourceAddress[1]); PrintChar(rxMessage.SourceAddress[0]); } else { for(i = 0; i < MY_ADDRESS_LENGTH; i++) { PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]); } } } ConsolePutROMString((ROM char *)": "); for(i = 0; i < rxMessage.PayloadSize; i++) { ConsolePut(rxMessage.Payload[i]); } // Toggle LED2 to indicate receiving a packet. LED_2 ^= 1; /*******************************************************************/ // Function MiApp_DiscardMessage is used to release the current // received message. After calling this function, the stack can // start to process the next received message. /*******************************************************************/ MiApp_DiscardMessage(); bReceivedMessage = TRUE; /*******************************************************************/ // Following block update the total received and transmitted messages // on the LCD of the demo board. /*******************************************************************/ LCDTRXCount(TxNum, ++RxNum); } else { ++m; if(m > 8000) { m=0; //LED_1 ^= 1; MiApp_FlushTx(); MiApp_WriteData('H'); MiApp_WriteData('o'); MiApp_WriteData('l'); MiApp_WriteData('a'); MiApp_WriteData('a'); MiApp_WriteData('a'); MiApp_WriteData(0x0D); MiApp_WriteData(0x0A); MiApp_BroadcastPacket(FALSE); } if ( ConsoleIsGetReady() ) { //ProcessMenu(); } } } }
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(); } } }
Tcl_Channel TclWinOpenConsoleChannel( HANDLE handle, char *channelName, int permissions) { char encoding[4 + TCL_INTEGER_SPACE]; ConsoleInfo *infoPtr; DWORD modes; ConsoleInit(); /* * See if a channel with this handle already exists. */ infoPtr = ckalloc(sizeof(ConsoleInfo)); memset(infoPtr, 0, sizeof(ConsoleInfo)); infoPtr->validMask = permissions; infoPtr->handle = handle; infoPtr->channel = (Tcl_Channel) NULL; wsprintfA(encoding, "cp%d", GetConsoleCP()); infoPtr->threadId = Tcl_GetCurrentThread(); /* * Use the pointer for the name of the result channel. This keeps the * channel names unique, since some may share handles (stdin/stdout/stderr * for instance). */ sprintf(channelName, "file%" TCL_I_MODIFIER "x", (size_t) infoPtr); infoPtr->channel = Tcl_CreateChannel(&consoleChannelType, channelName, infoPtr, permissions); if (permissions & TCL_READABLE) { /* * Make sure the console input buffer is ready for only character * input notifications and the buffer is set for line buffering. IOW, * we only want to catch when complete lines are ready for reading. */ GetConsoleMode(infoPtr->handle, &modes); modes &= ~(ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT); modes |= ENABLE_LINE_INPUT; SetConsoleMode(infoPtr->handle, modes); StartChannelThread(infoPtr, &infoPtr->reader, ConsoleReaderThread); } if (permissions & TCL_WRITABLE) { StartChannelThread(infoPtr, &infoPtr->writer, ConsoleWriterThread); } /* * Files have default translation of AUTO and ^Z eof char, which means * that a ^Z will be accepted as EOF when reading. */ Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto"); Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "\032 {}"); #ifdef UNICODE Tcl_SetChannelOption(NULL, infoPtr->channel, "-encoding", "unicode"); #else Tcl_SetChannelOption(NULL, infoPtr->channel, "-encoding", encoding); #endif return infoPtr->channel; }
void NandDumper(){ ConsoleSetTitle(strings[STR_DUMP], strings[STR_NAND]); File myFile; int isEmuNand = SYS_NAND; if(checkEmuNAND() && (isEmuNand = NandSwitch()) == UNK_NAND) return; isEmuNand--; ConsoleInit(); ConsoleSetTitle(strings[STR_DUMP], strings[STR_NAND]); unsigned char* buf = (void*)0x21000000; unsigned int nsectors = 0x200; //sectors in a row wchar_t tmpstr[STR_MAX_LEN]; wchar_t ProgressBar[41] = {0,}; for(int i=0; i<PROGRESS_WIDTH; i++) wcscat(ProgressBar, strings[STR_PROGRESS]); unsigned int progress = 0; wchar_t filename[_MAX_LFN]; swprintf(filename, _MAX_LFN, L"rxTools/nand/%sNAND.bin", isEmuNand ? L"EMU" : L""); if(FileOpen(&myFile, filename, 1)){ print(strings[STR_DUMPING], isEmuNand ? strings[STR_EMUNAND] : strings[STR_SYSNAND], filename); ConsoleShow(); int x, y; ConsoleGetXY(&x, &y); y += FONT_HEIGHT * 6; x += FONT_HWIDTH * 2; DrawString(BOT_SCREEN, ProgressBar, x, y, ConsoleGetTextColor(), ConsoleGetBackgroundColor()); swprintf(tmpstr, STR_MAX_LEN, strings[STR_PRESS_BUTTON_ACTION], strings[STR_BUTTON_B], strings[STR_CANCEL]); DrawString(BOT_SCREEN, tmpstr, x, y + FONT_HEIGHT*2, ConsoleGetTextColor(), ConsoleGetBackgroundColor()); for(int count = 0; count < getNandSize()/NAND_SECTOR_SIZE/nsectors; count++){ if(isEmuNand) sdmmc_sdcard_readsectors(count*nsectors, nsectors, buf); else sdmmc_nand_readsectors(count*nsectors, nsectors, buf); FileWrite(&myFile, buf, nsectors*NAND_SECTOR_SIZE, count*NAND_SECTOR_SIZE*nsectors); TryScreenShot(); if((count % (int)(getNandSize()/NAND_SECTOR_SIZE/nsectors/PROGRESS_WIDTH)) == 0 && count != 0){ DrawString(BOT_SCREEN, strings[STR_PROGRESS_OK], x+(FONT_WIDTH*(progress++)), y, ConsoleGetTextColor(), ConsoleGetBackgroundColor()); } unsigned int pad = GetInput(); if (pad & BUTTON_B) { FileClose(&myFile); goto end; } } if(isEmuNand){ sdmmc_sdcard_readsectors(checkEmuNAND()/0x200, 1, buf); FileWrite(&myFile, buf, 0x200, 0); } FileClose(&myFile); print(strings[STR_COMPLETED]); ConsoleShow(); }else{ print(strings[STR_FAILED]); ConsoleShow(); } end: print(strings[STR_PRESS_BUTTON_ACTION], strings[STR_BUTTON_A], strings[STR_CONTINUE]); ConsoleShow(); WaitForButton(BUTTON_A); }
int main(void) #endif { BYTE i, j; BYTE OperatingChannel = 0xFF; BYTE TxSynCount = 0; BYTE TxSynCount2 = 0; BYTE TxPersistFailures = 0; BOOL ReadyToSleep = FALSE; BYTE TxNum = 0; BYTE RxNum = 0; BYTE PressedButton = 0; /*******************************************************************/ // Initialize the system /*******************************************************************/ BoardInit(); ConsoleInit(); DemoOutput_Greeting(); /*********************************************************************/ // Function MiApp_ProtocolInit intialize the protocol stack. // The return value is a boolean to indicate the status of the // operation. // The only parameter indicates if Network Freezer should be invoked. // When Network Freezer feature is invoked, all previous network // configurations will be restored to the states before the // reset or power cycle // // In this example, we assume that the user wants to apply Network // Freezer feature and restore the network configuration if // button 1 is pressed and hold when powering up. /*********************************************************************/ if( (PUSH_BUTTON_1 == 0) && ( MiApp_ProtocolInit(TRUE) == TRUE ) ) { DemoOutput_NetworkFreezer(); while(PUSH_BUTTON_1 == 0 ); } else { /*********************************************************************/ // Function MiApp_ProtocolInit intialize the protocol stack. // The return value is a boolean to indicate the status of the // operation. // The only parameter indicates if Network Freezer should be invoked. // When Network Freezer feature is invoked, all previous network // configurations will be restored to the states before the // reset or power cycle // // In this example, we assume that the user wants to start from // scratch and ignore previous network configuration if button 1 // is released when powering up. /*********************************************************************/ MiApp_ProtocolInit(FALSE); DemoOutput_StartActiveScan(); while(1) { /*********************************************************************/ // Function MiApp_SearchConnection will return the number of existing // connections in all channels. It will help to decide which channel // to operate on and which connection to add // The return value is the number of connections. The connection data // are stored in global variable ActiveScanResults. Maximum active // scan result is defined as ACTIVE_SCAN_RESULT_SIZE // The first parameter is the scan duration, which has the same // definition in Energy Scan. 10 is roughly 1 second. 9 is a half // second and 11 is 2 seconds. Maximum scan duration is 14, or // roughly 16 seconds. // The second parameter is the channel map. Bit 0 of the double // word parameter represents channel 0. For the 2.4GHz frequency // band, all possible channels are channel 11 to channel 26. // As the result, the bit map is 0x07FFF800. Stack will filter // out all invalid channels, so the application only needs to pay // attention to the channels that are not preferred. /*********************************************************************/ j = MiApp_SearchConnection(10, 0xFFFFFFFF); OperatingChannel = DemoOutput_ActiveScanResults(j); if( OperatingChannel != 0xFF ) { /*******************************************************************/ // Function MiApp_SetChannel assign the operation channel(frequency) // for the transceiver. Channels 0 - 31 has been defined for the // wireless protocols, but not all channels are valid for all // transceivers, depending on their hardware design, operating // frequency band, data rate and other RF parameters. Check the // definition of FULL_CHANNEL_MAP for details. /*******************************************************************/ MiApp_SetChannel(OperatingChannel); break; } DemoOutput_Rescan(); } /*********************************************************************/ // Function MiApp_ConnectionMode sets the connection mode for the // protocol stack. Possible connection modes are: // - ENABLE_ALL_CONN accept all connection request // - ENABLE_PREV_CONN accept only known device to connect // - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but allow // response to active scan // - DISABLE_ALL_CONN disable all connection request, including // active scan request /*********************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); /*******************************************************************/ // Function MiApp_EstablishConnection establish connections between // two devices. It has two input parameters: // The first parameter is the index of the target device in the // active scan table. It requires a MiApp_SearchConnection call // before hand. If seraching connection is not performed in // advance, user can apply 0xFF to the first parameter to // indicate that it is OK to establish connection with any // device. // The second parameter is the connection mode, either directly or // indirectly. Direct connection is a connection in the radio // range. All protocol stack support this connection mode. // Indirect connection is the connection out of radio range. // An indirect connection has to rely on other device to route // the messages between two connected devices. Indirect // connection is also called "Socket" connection in MiWi // Protocol. Since MiWi P2P protocol only handles connection // of one hop, indirect connection is not supported in MiWi // P2P protocol, but supported in other networking protocols. // Function MiApp_EstablishConnection returns the index of the // connected device in the connection table. If no connection // is established after predefined retry times // CONNECTION_RETRY_TIMES, it will return 0xFF. If multiple // connections have been established, it will return the one // of the indexes of the connected device. /*******************************************************************/ i = MiApp_EstablishConnection(0, CONN_MODE_DIRECT); DemoOutput_Connected(); } // Turn on LED 1 to indicate connection established LED_1 = 1; /*******************************************************************/ // Function DumpConnection is used to print out the content of the // P2P Connection Entry on the hyperterminal. It may be useful in // the debugging phase. // The only parameter of this function is the index of the // Connection Entry. The value of 0xFF means to print out all // valid Connection Entries; otherwise, the Connection Entry // of the input index will be printed out. /*******************************************************************/ DumpConnection(0xFF); DemoOutput_Instruction(); while(1) { /*******************************************************************/ // Function MiApp_MessageAvailable will return a boolean to indicate // if a message for application layer has been received by the // transceiver. If a message has been received, all information will // be stored in rxMessage, structure of RECEIVED_MESSAGE. /*******************************************************************/ if( MiApp_MessageAvailable() ) { DemoOutput_HandleMessage(); /*******************************************************************/ // Function MiApp_DiscardMessage is used to release the current // received message. After calling this function, the stack can // start to process the next received message. /*******************************************************************/ MiApp_DiscardMessage(); // Toggle LED2 to indicate receiving a packet. LED_2 ^= 1; DemoOutput_UpdateTxRx(TxNum, ++RxNum); } else { /***********************************************************************/ // TxPersistFailures is the local variable to track the transmission // failure because no acknowledgement frame is received. Typically, // this is the indication of either very strong noise, or the PAN // has hopped to another channel. /***********************************************************************/ if( TxPersistFailures > 3 ) { DemoOutput_StartResync(); /*******************************************************************/ // Function MiApp_TransceiverPowerState is used to set the power state // of RF transceiver. There are three possible states: // - POWER_STATE_SLEEP Put transceiver into sleep // - POWER_STATE_WAKEUP Wake up the transceiver only // - POWER_STATE_WAKEUP_DR Wake up and send Data Request command /*******************************************************************/ MiApp_TransceiverPowerState(POWER_STATE_WAKEUP); /***********************************************************************/ // Function MiApp_ResyncConnection is used to synchronized connection // if one side of communication jumped to another channel, when // frequency agility is performed. Usually, this is done by the // sleeping device, since the sleeping device cannot hear the broadcast // of channel hopping command. // // The first parameter is the index of connection table for the peer // node, which we would like to resynchronize to. // The second parameter is the bit map of channels to be scanned /***********************************************************************/ MiApp_ResyncConnection(0, 0xFFFFFFFF); TxPersistFailures = 0; ReadyToSleep = FALSE; DemoOutput_EndResync(); } else { ReadyToSleep = TRUE; } /*******************************************************************/ // If Data Request command and data transmision has been handled, // as the RFD device, it is time to consider put both the radio and // MCU into sleep mode to conserve power. /*******************************************************************/ if( ReadyToSleep ) { ReadyToSleep = FALSE; /*******************************************************************/ // Function MiApp_TransceiverPowerState is used to set the power // state of RF transceiver. There are three possible states: // - POWER_STATE_SLEEP Put transceiver into sleep // - POWER_STATE_WAKEUP Wake up the transceiver only // - POWER_STATE_WAKEUP_DR Wake up and send Data Request // command /*******************************************************************/ MiApp_TransceiverPowerState(POWER_STATE_SLEEP); /*******************************************************************/ // Prepare the condition to wake up the MCU. The MCU can either be // waken up by the timeout of watch dog timer (Time Synchronization // off), timeout of counter with external 32KHz crystal (Time // Synchronization on), or by the pin change notification interrupt // by pushing the button. MCU handling of sleep preparing for // different demo boards can be found in HardwareProfile.c /*******************************************************************/ PrepareWakeup(); // Put MCU into sleep mode Sleep(); /*******************************************************************/ // Handling the wakeup procedure. The steps differ for different // demo boards and families of MCUs. Details can be found in // HardwareProfile.c /*******************************************************************/ AfterWakeup(); PressedButton = ButtonPressed(); /*******************************************************************/ // Function MiApp_TransceiverPowerState is used to set the power // state of RF transceiver. There are three possible states: // - POWER_STATE_SLEEP Put transceiver into sleep // - POWER_STATE_WAKEUP Wake up the transceiver only // - POWER_STATE_WAKEUP_DR Wake up and send Data Request // command /*******************************************************************/ if( MiApp_TransceiverPowerState(POWER_STATE_WAKEUP_DR) > SUCCESS ) { TxPersistFailures++; DemoOutput_ConnectionLost(TxPersistFailures); } else { if( TxPersistFailures > 0 ) { DemoOutput_UpdateTxRx(TxNum, RxNum); } TxPersistFailures = 0; } switch( PressedButton ) { case 1: /*******************************************************************/ // Button 1 pressed. // First use MiApp_FlushTx to reset the Transmit buffer. Then fill // the TX buffer by calling function MiApp_WriteData /*******************************************************************/ MiApp_FlushTx(); for(i = 0; i < 21; i++) { MiApp_WriteData(MiWi[(TxSynCount%6)][i]); } TxSynCount++; /*******************************************************************/ // Function MiApp_BroadcastPacket is used to broadcast a message // The only parameter is the boolean to indicate if we need to // secure the message /*******************************************************************/ MiApp_BroadcastPacket(FALSE); DemoOutput_UpdateTxRx(++TxNum, RxNum); break; case 2: /*******************************************************************/ // Button 2 pressed. // First use MiApp_FlushTx to reset the Transmit buffer. Then fill // the TX buffer by calling function MiApp_WriteData /*******************************************************************/ MiApp_FlushTx(); for(i = 0; i < 11; i++) { MiApp_WriteData(DE[(TxSynCount2%6)][i]); } TxSynCount2++; /*******************************************************************/ // Function MiApp_UnicastConnection is one of the functions to // unicast a message. // The first parameter is the index of connection table for // the peer device. In this demo, since there are only two // devices involved, the peer device must be stored in the // first Connection Entry in the connection table. // The second parameter is the boolean to indicate if we need // to secure the frame. If encryption is applied, the // security level and security key are defined in the // configuration file for the transceiver // // Another way to unicast a message is by calling function // MiApp_UnicastAddress. Instead of supplying the index of the // connection table of the peer device, this function requires the // input parameter of destination address directly. /*******************************************************************/ if( MiApp_UnicastConnection(0, TRUE) == FALSE ) { DemoOutput_UnicastFail(); } else { TxNum++; } DemoOutput_UpdateTxRx(TxNum, RxNum); break; default: break; } } } } }
/************************************************************************* main ==== **************************************************************************/ int main(void) { int c, i; IODIR0 |= (1<<10); // PLL and MAM HalSysInit(); #ifdef LPC214x // init DBG ConsoleInit(60000000 / (16 * BAUD_RATE)); #else // init DBG ConsoleInit(72000000 / (16 * BAUD_RATE)); #endif DBG("Initialising USB stack\n"); // initialise stack USBInit(); configureADCPort(AD0_3); // register descriptors USBRegisterDescriptors(abDescriptors); // register class request handler USBRegisterRequestHandler(REQTYPE_TYPE_CLASS, HandleClassRequest, abClassReqData); // register endpoint handlers USBHwRegisterEPIntHandler(INT_IN_EP, NULL); // register frame handler USBHwRegisterFrameHandler(USBFrameHandler); // register device event handler USBHwRegisterDevIntHandler(USBDevIntHandler); char ch = 'a'; for (i = 0; i < BYTES_PER_ISOC_FRAME; i++) { inputIsocDataBuffer[i] = ch; ch = (ch == 'z' ? 'a' : (ch + 1)); } DBG("Starting USB communication\n"); #ifdef LPC214x (*(&VICVectCntl0+INT_VECT_NUM)) = 0x20 | 22; // choose highest priority ISR slot (*(&VICVectAddr0+INT_VECT_NUM)) = (int)USBIntHandler; #else VICVectCntl22 = 0x01; VICVectAddr22 = (int)USBIntHandler; #endif // set up USB interrupt VICIntSelect &= ~(1<<22); // select IRQ for USB VICIntEnable |= (1<<22); enableIRQ(); // connect to bus USBHwConnect(TRUE); int x = 0; const int interval = 100000; // echo any character received (do USB stuff in interrupt) for(;;) { x++; U32 temp = cADC_Result(AD0_3); if( temp >= 0 && temp <= 1024 ) inputIsocDataBuffer[ADC_INPUT_INDEX] = temp; inputIsocDataBuffer[BUTTON1_INPUT_INDEX] = ((IOPIN0 & (1<<15)) ? 1 : 0); inputIsocDataBuffer[BUTTON2_INPUT_INDEX] = ((IOPIN0 & (1<<16)) ? 1 : 0); if (x == interval) { IOSET0 = (1<<11); //turn on led } else if (x >= (interval*2)) { IOCLR0 = (1<<11); //turn off led x = 0; } } return 0; }
/********************************************************************* * Function: void BoardInit( void ) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: Board is initialized for P2P usage * * Overview: This function configures the board * * Note: This routine needs to be called before the function * to initialize P2P stack or any other function that * operates on the stack ********************************************************************/ void BoardInit(void) { // primary internal oscillator OSCCON = 0x7B; WDTCONbits.SWDTEN = 0; #if defined(MRF89XA) PHY_RESETn_TRIS = 1; #endif EECON2 = 0x55; EECON2 = 0xAA; PPSCONbits.IOLOCK = 0; #if defined(MRF49XA) RPINR3 = 6; #endif #if defined(MRF24J40) RPINR1 = 4; #endif #if defined(MRF89XA) RPINR3 = 6; #endif #if !defined(SENSOR_PORT_UART) // use LCD RPINR21 = 19; //Mapping SDI2 to RD2 RPOR23 = 9; //Mapping SDO2 to RD6 RPOR21 = 10; //Mapping SCK2 to RD4 #endif #if defined(SENSOR_PORT_UART) // use UART RPINR16 = 19; RPOR17 = 5; #endif EECON2 = 0x55; EECON2 = 0xAA; PPSCONbits.IOLOCK = 1; ANCON0 = 0xFF; ANCON1 = 0x3F; INTCON2bits.RBPU = 0; TRISA = 0xFF; TRISB = 0xFF; TRISC = 0xFF; TRISD = 0x00; TRISE = 0xFF; LATA = 0; LATB = 0; //LATC = 0; LATD = 0; LATE = 0; TRISDbits.TRISD2 = 0; LATDbits.LATD2 = 1; TRISCbits.TRISC6 = 0; LATCbits.LATC6 = 0; // set I/O ports BUTTON_RB0_TRIS = 1; BUTTON_RB2_TRIS = 1; LED_1_TRIS = 0; LED_2_TRIS = 0; #if defined(MRF24J40) || defined(MRF49XA) PHY_CS_TRIS = 0; PHY_CS = 1; PHY_RESETn_TRIS = 0; PHY_RESETn = 1; RF_INT_TRIS = 1; #endif #if defined(MRF89XA) PHY_RESETn_TRIS = 1; IRQ1_INT_TRIS = 1; IRQ0_INT_TRIS = 1; #if defined(USE_IRQ0_AS_INTERRUPT) //Enable the effective INT edge PHY_IRQ0_En = 1; PHY_IRQ0 = 0; #endif #endif SDI_TRIS = 1; SDO_TRIS = 0; SCK_TRIS = 0; #if defined(HARDWARE_SPI) SSP1STAT = 0xC0; SSP1CON1 = 0x21; #else SPI_SDO = 0; SPI_SCK = 0; #endif #if defined(MRF49XA) nFSEL_TRIS = 0; FINT_TRIS = 1; nFSEL = 1; // nFSEL inactive INTCON2bits.INTEDG3 = 0; #endif #if defined(MRF24J40) PHY_WAKE_TRIS = 0; PHY_WAKE = 1; INTCON2bits.INTEDG1 = 0; #endif #if defined(MRF89XA) Config_nCS_TRIS = 0; //nCS_Config as output Data_nCS_TRIS = 0; //nCS_DATA as output Config_nCS_TRIS = 0; Data_nCS = 1; Config_nCS = 1; INTCON2bits.INTEDG3 = 1; #endif //#if defined(ENABLE_NVM) EE_nCS_TRIS = 0; EE_nCS = 1; //#endif INTCONbits.GIEH = 1; #if defined(MRF24J40) || defined(MRF49XA) RFIF = 0; RFIE = 1; #endif #if defined(SENSOR_PORT_LCD) LCDInit(); #endif ConsoleInit(); //Initializes the Console }
int rxMode(int emu) { if (!checkEmuNAND() && emu) { ConsoleInit(); ConsoleSetTitle(L"EMUNAND NOT FOUND!"); print(L"The emunand was not found on\n"); print(L"your SDCard. \n"); print(L"\n"); print(L"Press A to boot SYSNAND\n"); ConsoleShow(); WaitForButton(BUTTON_A); emu = 0; char s[32]; sprintf(s, "/rxTools/Theme/%u/boot.bin", cfgs[CFG_THEME].val.i); DrawBottomSplash(s); } static const char patchNandPrefix[] = ".patch.p9.nand"; unsigned int cur, off, shstrSize; char path[64], shstrtab[512], *sh_name; const char *platformDir; FirmInfo info; const wchar_t *msg; int r, sector; void *p; Elf32_Ehdr ehdr; Elf32_Shdr shdr; FIL fd, keyxFd; UINT br, fsz; setAgbBios(); getFirmPath(path, getMpInfo() == MPINFO_KTR ? TID_KTR_NATIVE_FIRM : TID_CTR_NATIVE_FIRM); strcpy(path + strlen(path) - 4, "orig.bin"); r = loadFirm(path, &fsz); if (r) { msg = L"Failed to load NATIVE_FIRM: %d\n" L"Reboot rxTools and try again.\n"; goto fail; } makeFirmInfo((const uint8_t*)FIRM_ADDR, &info); r = getMpInfo(); switch (r) { case MPINFO_KTR: platformDir = "ktr"; break; case MPINFO_CTR: platformDir = "ctr"; break; default: msg = L"Unknown Platform: %d"; goto fail; } sprintf(path, SYSTEM_PATH "/patches/%s/native_firm.elf", platformDir); r = f_open(&fd, path, FA_READ); if (r != FR_OK) goto patchFail; r = f_read(&fd, &ehdr, sizeof(ehdr), &br); if (r != FR_OK) goto patchFail; r = f_lseek(&fd, ehdr.e_shoff + ehdr.e_shstrndx * sizeof(Elf32_Shdr)); if (r != FR_OK) goto patchFail; r = f_read(&fd, &shdr, sizeof(shdr), &br); if (r != FR_OK) goto patchFail; r = f_lseek(&fd, shdr.sh_offset); if (r != FR_OK) goto patchFail; r = f_read(&fd, shstrtab, shdr.sh_size > sizeof(shstrtab) ? sizeof(shstrtab) : shdr.sh_size, &shstrSize); if (r != FR_OK) goto patchFail; if (emu) { sector = checkEmuNAND(); if (sector == 0) { msg = L"Failed to find EmuNAND.\n" L"Check your EmuNAND.\n"; goto fail; } } else sector = 0; cur = ehdr.e_shoff; for (; ehdr.e_shnum; ehdr.e_shnum--, cur += sizeof(shdr)) { if (f_lseek(&fd, cur) != FR_OK) continue; if (f_read(&fd, &shdr, sizeof(shdr), &br) != FR_OK) continue; if (!(shdr.sh_flags & SHF_ALLOC) || shdr.sh_name >= shstrSize) continue; off = addrToOff(shdr.sh_addr, &info); if (off == 0) continue; p = (void *)(FIRM_ADDR + off); sh_name = shstrtab + shdr.sh_name; if (!strcmp(sh_name, ".rodata.keyx")) { if (sysver >= 7) continue; if (f_open(&keyxFd, "slot0x25KeyX.bin", FA_READ) != FR_OK) continue; f_read(&keyxFd, p, shdr.sh_size, &br); f_close(&keyxFd); } else if (!strcmp(sh_name, ".rodata.nand.sector")) { if (sector) *(uint32_t *)p = (sector / 0x200) - 1; } else if (!strcmp(sh_name, ".rodata.label")) { *(uint32_t *)p = sector ? 'E-XR' : 'S-XR'; } else if (shdr.sh_type == SHT_PROGBITS && (sector || memcmp(sh_name, patchNandPrefix, sizeof(patchNandPrefix) - 1)) && (sysver < 7 || strcmp(sh_name, ".patch.p9.keyx"))) { if (f_lseek(&fd, shdr.sh_offset) != FR_OK) continue; f_read(&fd, p, shdr.sh_size, &br); } } getFirmPath(path, getMpInfo() == MPINFO_KTR ? TID_KTR_NATIVE_FIRM : TID_CTR_NATIVE_FIRM); f_open(&fd, path, FA_WRITE | FA_CREATE_ALWAYS); f_write(&fd, (void *)FIRM_ADDR, fsz, &br); f_close(&fd); r = loadExecReboot(); // This won't return if it succeeds. msg = L"Failed to load reboot.bin: %d\n" L"Check your installation.\n"; fail: ConsoleInit(); ConsoleSetTitle(L"rxMode"); print(msg, r); print(L"\n"); print(strings[STR_PRESS_BUTTON_ACTION], strings[STR_BUTTON_A], strings[STR_CONTINUE]); ConsoleShow(); WaitForButton(BUTTON_A); return r; patchFail: msg = L"Failed to load native_firm.elf: %d\n" L"Check your installation.\n"; goto fail; }
/********************************************************************* * Function: void main(void) * * PreCondition: none * * Input: none * * Output: none * * Side Effects: none * * Overview: This is the main function that runs the simple * example demo. The purpose of this example is to * demonstrate the simple application programming * interface for the MiWi(TM) Development * Environment. By virtually total of less than 30 * lines of code, we can develop a complete * application using MiApp interface. The * application will first try to establish a P2P * link with another device and then process the * received information as well as transmit its own * information. * MiWi(TM) DE also support a set of rich * features. Example code FeatureExample will * demonstrate how to implement the rich features * through MiApp programming interfaces. * * Note: **********************************************************************/ void main (void) { BYTE i; BYTE TxSynCount = 0; BYTE TxSynCount2 = 0; BoardInit(); //Has LCDInit() also covered in this, need to make this separate to ensure that if there was a problem with I2C the board hangs up ConsoleInit(); // Initialize the system /*******************************************************************/ LCDBacklightON(); LCDDisplay((char *)"8-Bit Wireless Development Kit ", 0, TRUE); DelayMs(5000); LCDBacklightOFF(); Printf("\r\nInput Configuration:"); Printf("\r\n Button 1: RB0"); Printf("\r\n Button 2: RB2"); Printf("\r\nOutput Configuration:"); Printf("\r\n LED 1: RA2"); Printf("\r\n LED 2: RA3"); Printf("\r\n LED 3: RB1"); #if defined(MRF24J40) Printf("\r\n RF Transceiver: MRF24J40"); #elif defined(MRF49XA) Printf("\r\n RF Transceiver: MRF49XA"); #elif defined(MRF89XA) Printf("\r\n RF Transceiver: MRF89XA"); #endif Printf("\r\n Demo Instruction:"); Printf("\r\n Power on the board until LED 1 lights up "); Printf("\r\n to indicate connecting with peer. "); Printf("\r\n Ping Pong Results will be displayed on LCD"); Printf("\r\n Use MCLR + RB2 to switch to Self Test Mode. "); Printf("\r\n\r\n"); LED_1 = 0; LED_2 = 0; MiApp_ProtocolInit(FALSE); // Set default channel if(MiApp_SetChannel(myChannel) == FALSE) { #if defined(__18CXX) return; #else return (0); #endif } /*******************************************************************/ // Function MiApp_ConnectionMode defines the connection mode. The // possible connection modes are: // ENABLE_ALL_CONN: Enable all kinds of connection // ENABLE_PREV_CONN: Only allow connection already exists in // connection table // ENABL_ACTIVE_SCAN_RSP: Allow response to Active scan // DISABLE_ALL_CONN: Disable all connections. /*******************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); /*******************************************************************/ // Display current opertion on LCD of demo board, if applicable /*******************************************************************/ LCDDisplay((char *)"Connecting Peer on Channel %d ", myChannel, TRUE); /*******************************************************************/ // Function MiApp_EstablishConnection try to establish a new // connection with peer device. // The first parameter is the index to the active scan result, // which is acquired by discovery process (active scan). If // the value of the index is 0xFF, try to establish a // connection with any peer. // The second parameter is the mode to establish connection, // either direct or indirect. Direct mode means connection // within the radio range; indirect mode means connection // may or may not in the radio range. /*******************************************************************/ #ifdef ENABLE_HAND_SHAKE i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT); #endif /*******************************************************************/ // Display current opertion on LCD of demo board, if applicable /*******************************************************************/ if(i != 0xFF) { LCDDisplay((char *)"Joined Network Successfully..", 0, TRUE); } else { MiApp_StartConnection(START_CONN_DIRECT, 10, 0); } /*******************************************************************/ // Function DumpConnection is used to print out the content of the // Connection Entry on the hyperterminal. It may be useful in // the debugging phase. // The only parameter of this function is the index of the // Connection Entry. The value of 0xFF means to print out all // valid Connection Entry; otherwise, the Connection Entry // of the input index will be printed out. /*******************************************************************/ #ifdef ENABLE_DUMP DumpConnection(0xFF); #endif #ifndef ENABLE_POWERSAVE // Turn on LED 1 to indicate P2P connection established LED_1 = 1; #endif DelayMs(20); LCDDisplay((char *)"Ping Pong Demo RB0(TX) RB2(RX)", 0, TRUE); /*******************************************************************/ // Following block display demo instructions on LCD based on the // demo board used. /*******************************************************************/ /*Configure the device in transmit or Receive Mode*/ ReadButtonPress(); while(1) { PingPongStateMachine(); } //end of while(1) } //end of main
void main(void) { #define BAUDRG 77 BYTE SecNum = 0; BOOL Tx_Success = FALSE; BYTE Tx_Trials = 0, scanresult = 0; /*******************************************************************/ // Initialize the system /*******************************************************************/ ANCON0 = 0XFF; /*desactiva entradas analogicas*/ ANCON1 = 0XFF; /*desactiva entradas analogicas*/ PPSUnLock(); PPSOutput(PPS_RP10, PPS_TX2CK2); // TX2 RP17/RC6 icsp PPSInput(PPS_RX2DT2, PPS_RP9); // RX2 RP18/RC7 PPSOutput(PPS_RP23, PPS_SDO2); // SDO2 RP23/RD6 PPSInput(PPS_SDI2, PPS_RP24); // SDI2 RP24/RD7 PPSOutput(PPS_RP22, PPS_SCK2); // SCK2 RP22/RD5 PPSLock(); System_PeripheralPinSelect( ExternalInterrupt3, 19); /*external interrupt 3 B3*/ BoardInit(); ConsoleInit(); Gpios_PinDirection(GPIOS_PORTC, 7, GPIOS_INPUT); /*pin C0 como salida para SDI*/ Gpios_PinDirection(GPIOS_PORTC, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/ //Gpios_PinDirection(GPIOS_PORTD, 4, GPIOS_OUTPUT); /*pin D4 como salida */ Open1USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG); baud1USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF); Open2USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG); baud2USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF); OpenTimer1( TIMER_INT_OFF &T1_16BIT_RW &T1_SOURCE_FOSC_4 & T1_PS_1_8 &T1_OSC1EN_OFF &T1_SYNC_EXT_OFF, TIMER_GATE_OFF & TIMER_GATE_INT_OFF); Gpios_PinDirection(GPIOS_PORTD, 7, GPIOS_INPUT); /*pin C0 como salida para SDI*/ Gpios_PinDirection(GPIOS_PORTD, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/ Gpios_PinDirection(GPIOS_PORTD, 5, GPIOS_OUTPUT); /*pin C2 como salida para SCK*/ Spi_Init(SPI_PORT1, SPI_64DIV); /*Inicializamos SPI2*/ Spi_Init(SPI_PORT2, SPI_64DIV); /*Inicializamos SPI2*/ //Adc_Init(ADC_10BITS); LED_1 = 1; LED_2 = 0; //RLY_1 = 0; RLY_2 = 0; ON_RADIO = 1; ON_MAC = 1; ON_TEMP = 1; StartWirelessConnection(); //myDevicesRequiredStatus[0] = 0x55; EEPROMRead(&myDevicesRequiredStatus, 0, 1); if(myDevicesRequiredStatus[0] == 0x55) { RLY_1 = 1; EEPROMCHG = 1; ConsolePutROMString((ROM char *)"RELAY ON "); } if(myDevicesRequiredStatus[0] == 0xAA) { RLY_1 = 0; EEPROMCHG = 0; ConsolePutROMString((ROM char *)"RELAY OFF "); } for(j=0;j<10;j++) { DelayMs(50); LED_1 ^= 1; LED_2 ^= 1; } LED_1 = 0; LED_2 = 0; //RLY_1 = 0; RLY_2 = 0; TickScaler = 4; EndDevStateMachine =0; /* while(!Tx_Success) { if(myChannel < 8) scanresult = MiApp_SearchConnection(10, (0x00000001 << myChannel)); else if(myChannel < 16) scanresult = MiApp_SearchConnection(10, (0x00000100 << (myChannel-8))); else if(myChannel < 24) scanresult = MiApp_SearchConnection(10, (0x00010000 << (myChannel-16))); else scanresult = MiApp_SearchConnection(10, (0x01000000 << (myChannel-24))); if(scanresult == 0) { Tx_Trials++; if(Tx_Trials > 2) break; } else Tx_Success = TRUE; } if(Tx_Success) { ConsolePutROMString((ROM char *)"RADIO OK "); } else { ConsolePutROMString((ROM char *)"RADIO FAIL "); } */ //.VBGOE = 0; //ANCON1bits.VBGEN = 1; // Enable Band gap reference voltage //DelayMs(10); //VBGResult = Adc_u16Read(15); //ANCON1bits.VBGEN = 0; // Disable Bandgap //Adc_Init(ADC_10BITS); ANCON0 = 0xFF; ANCON1 = 0x9F; ANCON1bits.VBGEN = 1; // Enable Band gap reference voltage ADCON0bits.VCFG = 0; // vreff VDD-VSS ADCON0bits.CHS = 0x0F; // VBG channel select ADCON1 = 0xBE; ADCON0bits.ADON = 1; //for(j=0;j<16;j++) //{ //myDevicesOutputStatus[j] = j; //} //EEPROMWRITE(myDevicesOutputStatus,0,16); //for(j=0;j<16;j++) //{ //myDevicesOutputStatus[j] = 0; //} //DelayMs(500); EEPROMRead(&myDevicesOutputStatus, 0, 16); ConsolePutROMString((ROM char *)"EEPROM READ: "); //PrintChar(TemperatureCalibrationValue); for(j=0;j<1;j++) { PrintChar(myDevicesOutputStatus[j]); } SwTimer3 = 0; SwTimer4 = 0; TRISB&=0xEF; //JL: Configuro el pin B4 como salida si modificar el estado de los demas pines while(1) { /* WirelessTxRx(); WirelesStatus(); Bypass(); */ //No se utilizaron //Menu(); //Timer1Tick(); //WirelessTxRxPANCOORD(); //TaskScheduler(); //JLEstas funciones deben habilitarse para trabajar como repetidora Timer1Tick(); Repeater(); } }
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( ¤tPrimitive ); 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( ¶ms.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. // ********************************************************************* } }
/************************************************************************* main ==== **************************************************************************/ int main(void) { /////////////////////////////////////////////////// // PRELUDE /////////////////////////////////////////////////// // PLL and MAM HalSysInit(); #ifdef LPC214x // init DBG ConsoleInit(60000000 / (16 * BAUD_RATE)); #else // init DBG ConsoleInit(72000000 / (16 * BAUD_RATE)); #endif DBG("Initialising USB stack\n"); // initialise stack USBInit(); // enable bulk-in interrupts on NAKs USBHwNakIntEnable(INACK_BI); // register descriptors USBRegisterDescriptors(isoDescriptors); //USBRegisterRequestHandler(REQTYPE_TYPE_CLASS, HandleClassRequest, abClassReqData); // register endpoint handlers USBHwRegisterEPIntHandler(INT_IN_EP, NULL); USBHwRegisterEPIntHandler(BULK_IN_EP, BulkIn); USBHwRegisterEPIntHandler(BULK_OUT_EP, BulkOut); // USBHwRegisterEPIntHandler(ISOC_OUT_EP, IsocOut); // register frame handler //USBHwRegisterFrameHandler(USBFrameHandler); // register device event handler USBHwRegisterDevIntHandler(USBDevIntHandler); bulk_init(); DBG("Starting USB communication\n"); #ifdef LPC214x (*(&VICVectCntl0+INT_VECT_NUM)) = 0x20 | 22; // choose highest priority ISR slot (*(&VICVectAddr0+INT_VECT_NUM)) = (int)USBIntHandler; #else VICVectCntl22 = 0x01; VICVectAddr22 = (int)USBIntHandler; #endif // set up USB interrupt VICIntSelect &= ~(1<<22); // select IRQ for USB VICIntEnable |= (1<<22); enableIRQ(); // connect to bus USBHwConnect(TRUE); ///////////////////////////////////////////// // FUNCTION ///////////////////////////////////////////// // int // bulk - echo // isoc A - regular - Broadcast numbers // isoc B - dma -echo // isoc C - dma ////////////////////////////////////////// // DEBUG LIGHTS ////////////////////////////////////////// int c; int x = 0; int ch ='a'; c = EOF; // echo any character received (do USB stuff in interrupt) while (1) { // Turn light on and off. x++; if (x == 400000) { IOSET0 = (1<<11); //turn on led if( ch > 'z' ) { ch = 'a'; } ch++; } else if (x >= 800000) { IOCLR0 = (1<<11); //turn off led x = 0; } } return 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( ¤tPrimitive ); 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( ¶ms.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. // ********************************************************************* } }
int rxMode(int emu) { const Elf32_Addr line = 32; wchar_t path[64]; const char *shstrtab; const wchar_t *msg; uint8_t keyx[16]; uint32_t tid; int r, sector; Elf32_Ehdr *ehdr; Elf32_Shdr *shdr, *btmShdr; Elf32_Addr cur, btm; void *keyxArg; FIL fd; UINT br, fsz; if (emu) { sector = checkEmuNAND(); if (sector == 0) { ConsoleInit(); ConsoleSetTitle(L"EMUNAND NOT FOUND!"); print(L"The emunand was not found on\n"); print(L"your SDCard. \n"); print(L"\n"); print(L"Press A to boot SYSNAND\n"); ConsoleShow(); WaitForButton(BUTTON_A); swprintf(path, _MAX_LFN, L"/rxTools/Theme/%u/boot.bin", cfgs[CFG_THEME].val.i); DrawBottomSplash(path); } } else sector = 0; r = getMpInfo(); switch (r) { case MPINFO_KTR: tid = TID_KTR_NATIVE_FIRM; break; case MPINFO_CTR: tid = TID_CTR_NATIVE_FIRM; break; default: msg = L"Unknown Platform: %d"; goto fail; } setAgbBios(); if (sysver < 7 && f_open(&fd, _T("slot0x25KeyX.bin"), FA_READ) == FR_OK) { f_read(&fd, keyx, sizeof(keyx), &br); f_close(&fd); keyxArg = keyx; } else keyxArg = NULL; getFirmPath(path, tid); r = loadFirm(path, &fsz); if (r) { msg = L"Failed to load NATIVE_FIRM: %d\n" L"Reboot rxTools and try again.\n"; goto fail; } ((FirmHdr *)FIRM_ADDR)->arm9Entry = 0x0801B01C; getFirmPatchPath(path, tid); r = f_open(&fd, path, FA_READ); if (r != FR_OK) goto patchFail; r = f_read(&fd, (void *)PATCH_ADDR, PATCH_SIZE, &br); if (r != FR_OK) goto patchFail; f_close(&fd); ehdr = (void *)PATCH_ADDR; shdr = (void *)(PATCH_ADDR + ehdr->e_shoff); shstrtab = (char *)PATCH_ADDR + shdr[ehdr->e_shstrndx].sh_offset; for (btmShdr = shdr + ehdr->e_shnum; shdr != btmShdr; shdr++) { if (!strcmp(shstrtab + shdr->sh_name, ".patch.p9.reboot.body")) { memcpy((void *)ehdr->e_entry, (void *)(PATCH_ADDR + shdr->sh_offset), shdr->sh_size); // Drain write buffer __asm__ volatile ("mcr p15, 0, %0, c7, c10, 4" :: "r"(0)); cur = ehdr->e_entry & ~(line - 1); btm = ehdr->e_entry + shdr->sh_size; while (cur < btm) { __asm__ volatile ( // Clean Dcache "mcr p15, 0, %0, c7, c10, 1\n\t" // Flush Icache "mcr p15, 0, %0, c7, c5, 1" :: "r"(cur)); cur += line; } ((void (*)(uint32_t, void *, uintptr_t))ehdr->e_entry)( sector, keyxArg, 0x1FFFFFF8); __builtin_unreachable(); } }
int Initialize() { char str[100]; char strl[100]; char strr[100]; char tmp[256]; wchar_t wtmp[256]; int r; preloadStringsA(); DrawString(BOT_SCREEN, strings[STR_INITIALIZING], FONT_WIDTH, SCREEN_HEIGHT-FONT_HEIGHT, WHITE, BLACK); if(FSInit()){ DrawString(BOT_SCREEN, strings[STR_LOADING], BOT_SCREEN_WIDTH/2, SCREEN_HEIGHT-FONT_HEIGHT, WHITE, BLACK); }else{ DrawString(BOT_SCREEN, strings[STR_FAILED], BOT_SCREEN_WIDTH/2, SCREEN_HEIGHT-FONT_HEIGHT, RED, BLACK); return 1; } LoadFont(); if (fontLoaded){ swprintf(wtmp, sizeof(wtmp)/sizeof(wtmp[0]), strings[STR_ERROR_OPENING], fontpath); DrawString(BOT_SCREEN, wtmp, FONT_WIDTH, SCREEN_HEIGHT-FONT_HEIGHT*2, RED, BLACK); }else{ preloadStringsU(); } //Console Stuff ConsoleSetXY(15, 20); ConsoleSetWH(BOT_SCREEN_WIDTH-30, SCREEN_HEIGHT-80); ConsoleSetBorderColor(BLUE); ConsoleSetTextColor(RGB(0, 141, 197)); ConsoleSetBackgroundColor(TRANSPARENT); ConsoleSetSpecialColor(BLUE); ConsoleSetSpacing(2); ConsoleSetBorderWidth(3); //Check that the data is installed f_mkdir("rxTools"); f_mkdir("rxTools/nand"); InstallConfigData(); readCfg(); if (fontLoaded) cfgs[CFG_LANG].val.s = cfgLang; r = loadStrings(); if (r) { sprintf(tmp, "%s/%s", langPath, cfgs[CFG_LANG].val.s); swprintf(wtmp, sizeof(wtmp)/sizeof(wtmp[0]), strings[STR_ERROR_OPENING], tmp); DrawString(BOT_SCREEN, wtmp, FONT_WIDTH, SCREEN_HEIGHT-FONT_HEIGHT*3, RED, BLACK); } sprintf(str, "/rxTools/Theme/%u/TOP.bin", cfgs[CFG_THEME].val.i); sprintf(strl, "/rxTools/Theme/%u/TOPL.bin", cfgs[CFG_THEME].val.i); sprintf(strr, "/rxTools/Theme/%u/TOPR.bin", cfgs[CFG_THEME].val.i); if (cfgs[CFG_3D].val.i) DrawTopSplash(str, strl, strr); else DrawTopSplash(str, str, str); if (!cfgs[CFG_GUI].val.i) { if(cfgs[CFG_SILENT].val.i) { sprintf(str, "/rxTools/Theme/%u/boot.bin", cfgs[CFG_THEME].val.i); DrawBottomSplash(str); for (int i = 0; i < 0x333333 * 2; i++){ uint32_t pad = GetInput(); if (pad & BUTTON_R1 && i > 0x333333) goto rxTools_boot; } } else { ConsoleInit(); ConsoleSetTitle(strings[STR_AUTOBOOT]); print(strings[STR_HOLD_BUTTON_ACTION], strings[STR_BUTTON_R], strings[STR_OPEN_MENU]); ConsoleShow(); for (int i = 0; i < 0x333333 * 6; i++){ uint32_t pad = GetInput(); if (pad & BUTTON_R1 && i > 0x333333) goto rxTools_boot; } } rxMode(1); } rxTools_boot: sprintf(str, "/rxTools/Theme/%u/TOP.bin", cfgs[CFG_THEME].val.i); sprintf(strl, "/rxTools/Theme/%u/TOPL.bin", cfgs[CFG_THEME].val.i); sprintf(strr, "/rxTools/Theme/%u/TOPR.bin", cfgs[CFG_THEME].val.i); if (cfgs[CFG_3D].val.i) DrawTopSplash(str, strl, strr); else DrawTopSplash(str, str, str); return 0; }
void Initialize(){ char str[100]; char strl[100]; char strr[100]; DrawString(BOT_SCREEN, " INITIALIZE... ", 0, SCREEN_HEIGHT-FONT_SIZE, WHITE, BLACK); if(FSInit()){ DrawString(BOT_SCREEN, " LOADING... ", 0, SCREEN_HEIGHT-FONT_SIZE, WHITE, BLACK); }else{ DrawString(BOT_SCREEN, " ERROR! ", 0, SCREEN_HEIGHT-FONT_SIZE, RED, BLACK); } LoadPack(); //Console Stuff ConsoleSetXY(15, 20); ConsoleSetWH(SCREEN_WIDTH-30, SCREEN_HEIGHT-80); ConsoleSetBorderColor(BLUE); ConsoleSetTextColor(RGB(0, 141, 197)); ConsoleSetBackgroundColor(TRANSPARENT); ConsoleSetSpecialColor(BLUE); ConsoleSetSpacing(2); ConsoleSetBorderWidth(3); //Check that the data is installed f_mkdir("rxTools"); f_mkdir("rxTools/nand"); InstallConfigData(); LoadSettings(); sprintf(str, "/rxTools/Theme/%c/TOP.bin", Theme); sprintf(strl, "/rxTools/Theme/%c/TOPL.bin", Theme); sprintf(strr, "/rxTools/Theme/%c/TOPR.bin", Theme); if(theme_3d) DrawTopSplash(str, strl, strr); else DrawTopSplash(str, str, str); if (!bootGUI) { if(silent_boot) { sprintf(str, "/rxTools/Theme/%c/boot.bin", Theme); DrawBottomSplash(str); for (int i = 0; i < 0x333333 * 2; i++){ u32 pad = GetInput(); if (pad & BUTTON_R1 && i > 0x333333) goto rxTools_boot; } } else { ConsoleInit(); ConsoleSetTitle(STR_AUTOBOOT[language]); print(STR_HOLD_R[language]); ConsoleShow(); for (int i = 0; i < 0x333333 * 6; i++){ u32 pad = GetInput(); if (pad & BUTTON_R1 && i > 0x333333) goto rxTools_boot; } } rxModeQuickBoot(); } rxTools_boot: sprintf(str, "/rxTools/Theme/%c/TOP.bin", Theme); sprintf(strl, "/rxTools/Theme/%c/TOPL.bin", Theme); sprintf(strr, "/rxTools/Theme/%c/TOPR.bin", Theme); if(theme_3d) DrawTopSplash(str, strl, strr); else DrawTopSplash(str, str, str); }
/************************************************************************* main ==== **************************************************************************/ int main(void) { int c, i; // PLL and MAM HalSysInit(); #ifdef LPC214x // init DBG ConsoleInit(60000000 / (16 * BAUD_RATE)); #else // init DBG ConsoleInit(72000000 / (16 * BAUD_RATE)); #endif configureADCPort(AD0_3); DBG("Initialising USB stack\n"); // initialise stack USBInit(); // register descriptors USBRegisterDescriptors(abDescriptors); // register class request handler USBRegisterRequestHandler(REQTYPE_TYPE_CLASS, HandleClassRequest, abClassReqData); // register endpoint handlers USBHwRegisterEPIntHandler(INT_IN_EP, NULL); // register frame handler USBHwRegisterFrameHandler(USBFrameHandler); // register device event handler USBHwRegisterDevIntHandler(USBDevIntHandler); USBInitializeUSBDMA(udcaHeadArray); USBEnableDMAForEndpoint(ISOC_IN_EP); DBG("Starting USB communication\n"); #ifdef LPC214x (*(&VICVectCntl0+INT_VECT_NUM)) = 0x20 | 22; // choose highest priority ISR slot (*(&VICVectAddr0+INT_VECT_NUM)) = (int)USBIntHandler; #else VICVectCntl22 = 0x01; VICVectAddr22 = (int)USBIntHandler; #endif // set up USB interrupt VICIntSelect &= ~(1<<22); // select IRQ for USB VICIntEnable |= (1<<22); enableIRQ(); // connect to bus USBHwConnect(TRUE); int x = 0; c = EOF; //populate source data with all 'B's for(i = 0; i < ISOC_INPUT_DATA_BUFFER_SIZE; i++ ) { inputIsocDataBuffer[i] = 'B'; } int cnt = 0; const int interval = 100000; // echo any character received (do USB stuff in interrupt) for(;;) { x++; U32 temp = cADC_Result(AD0_3); if( temp >= 0 && temp <= 1024 ) currentADCReadValue = temp; if (x == interval) { qq++; IOSET0 = (1<<11); //turn on led } else if (x >= (interval*2)) { IOCLR0 = (1<<11); //turn off led x = 0; } } return 0; }
int ProcessCTR(char* path){ PartitionInfo myInfo; File myFile; char myString[256]; //In case it is needed... if(FileOpen(&myFile, path, 0)){ ConsoleInit(); ConsoleAddText(TITLE); unsigned int ncch_base = 0x100; unsigned char magic[] = { 0, 0, 0, 0, 0}; FileRead(&myFile, magic, 4, ncch_base); if(magic[0] == 'N' && magic[1] == 'C' && magic[2] == 'S' && magic[3] == 'D'){ ncch_base = 0x4000; FileRead(&myFile, magic, 4, ncch_base+0x100); if(!(magic[0] == 'N' && magic[1] == 'C' && magic[2] == 'C' && magic[3] == 'H')){ FileClose(&myFile); return 2; } }else if(magic[0] == 'N' && magic[1] == 'C' && magic[2] == 'C' && magic[3] == 'H'){ ncch_base = 0x0; }else{ FileClose(&myFile); return 2; } ctr_ncchheader NCCH; unsigned int mediaunitsize = 0x200; FileRead(&myFile, &NCCH, 0x200, ncch_base); //ConsoleAddText(path); ConsoleAddText(NCCH.productcode); unsigned int NEWCRYPTO = 0, CRYPTO = 1; if(NCCH.flags[3] != 0) NEWCRYPTO = 1; if(NCCH.flags[7] & 4) CRYPTO = 0; if(NEWCRYPTO){ ConsoleAddText("\nCryptoType : 7.X Key security"); }else if(CRYPTO){ ConsoleAddText("\nCryptoType : Secure"); }else{ ConsoleAddText("\nCryptoType : None"); ConsoleAddText("Decryption completed!"); FileClose(&myFile); ConsoleShow(); return 3; } ConsoleShow(); u8 CTR[16]; if(getle32(NCCH.extendedheadersize) > 0){ ConsoleAddText("Decrypting ExHeader..."); ConsoleShow(); ncch_get_counter(NCCH, CTR, 1); FileRead(&myFile, BUFFER_ADDR, 0x800, ncch_base + 0x200); myInfo.buffer = BUFFER_ADDR; myInfo.size = 0x800; myInfo.keyslot = 0x2C; myInfo.ctr = CTR; myInfo.keyY = NCCH.signature; DecryptPartition(&myInfo); FileWrite(&myFile, BUFFER_ADDR, 0x800, ncch_base + 0x200); } if(getle32(NCCH.exefssize) > 0){ ConsoleAddText("Decrypting ExeFS..."); ConsoleShow(); ncch_get_counter(NCCH, CTR, 2); myInfo.buffer = BUFFER_ADDR; myInfo.keyslot = NEWCRYPTO ? 0x25 : 0x2C; myInfo.ctr = CTR; myInfo.keyY = NCCH.signature; size_t bytesRead = FileRead(&myFile, BUFFER_ADDR, getle32(NCCH.exefssize) * mediaunitsize, ncch_base + getle32(NCCH.exefsoffset) * mediaunitsize); myInfo.size = bytesRead; ProcessExeFS(&myInfo); //Explanation at function definition FileWrite(&myFile, BUFFER_ADDR, getle32(NCCH.exefssize) * mediaunitsize, ncch_base + getle32(NCCH.exefsoffset) * mediaunitsize); } if(getle32(NCCH.romfssize) > 0){ ConsoleAddText("Decrypting RomFS..."); ConsoleShow(); ncch_get_counter(NCCH, CTR, 3); myInfo.buffer = BUFFER_ADDR; myInfo.keyslot = NEWCRYPTO ? 0x25 : 0x2C; myInfo.ctr = CTR; myInfo.keyY = NCCH.signature; for(int i = 0; i < getle32(NCCH.romfssize) * mediaunitsize / BLOCK_SIZE; i++){ sprintf(myString, "%i%%", (int)((i*BLOCK_SIZE)/(getle32(NCCH.romfssize) * mediaunitsize/ 100))); int x, y; ConsoleGetXY(&x, &y); y += CHAR_WIDTH * 4; x += CHAR_WIDTH*22; DrawString(TOP_SCREEN, myString, x, y, ConsoleGetTextColor(), ConsoleGetBackgroundColor()); size_t bytesRead = FileRead(&myFile, BUFFER_ADDR, BLOCK_SIZE, ncch_base + getle32(NCCH.romfsoffset) * mediaunitsize + i*BLOCK_SIZE); myInfo.size = bytesRead; DecryptPartition(&myInfo); add_ctr(myInfo.ctr, bytesRead/16); FileWrite(&myFile, BUFFER_ADDR, BLOCK_SIZE, ncch_base + getle32(NCCH.romfsoffset) * mediaunitsize + i*BLOCK_SIZE); } } NCCH.flags[7] |= 4; //Disable encryption NCCH.flags[3] = 0; //Disable 7.XKey usage FileWrite(&myFile, &NCCH, 0x200, ncch_base); if(ncch_base == 0x4000) FileWrite(&myFile, ((u8*)&NCCH) + 0x100, 0x100, 0x1100); //Only for NCSD FileClose(&myFile); ConsoleAddText("Decryption completed!"); ConsoleShow(); return 0; }else return 1; }
int rxMode(int emu) { wchar_t path[64]; const char *shstrtab; const wchar_t *msg; uint8_t keyx[16]; uint32_t tid; int r, sector; Elf32_Ehdr *ehdr; Elf32_Shdr *shdr, *btm; void *keyxArg; FIL fd; UINT br, fsz; if (emu) { sector = checkEmuNAND(); if (sector == 0) { ConsoleInit(); ConsoleSetTitle(L"EMUNAND NOT FOUND!"); print(L"The emunand was not found on\n"); print(L"your SDCard. \n"); print(L"\n"); print(L"Press A to boot SYSNAND\n"); ConsoleShow(); WaitForButton(BUTTON_A); swprintf(path, _MAX_LFN, L"/rxTools/Theme/%u/boot.bin", cfgs[CFG_THEME].val.i); DrawBottomSplash(path); } } else sector = 0; r = getMpInfo(); switch (r) { case MPINFO_KTR: tid = TID_KTR_NATIVE_FIRM; break; case MPINFO_CTR: tid = TID_CTR_NATIVE_FIRM; break; default: msg = L"Unknown Platform: %d"; goto fail; } setAgbBios(); if (sysver < 7 && f_open(&fd, _T("slot0x25KeyX.bin"), FA_READ) == FR_OK) { f_read(&fd, keyx, sizeof(keyx), &br); f_close(&fd); keyxArg = keyx; } else keyxArg = NULL; getFirmPath(path, tid); r = loadFirm(path, &fsz); if (r) { msg = L"Failed to load NATIVE_FIRM: %d\n" L"Reboot rxTools and try again.\n"; goto fail; } ((FirmHdr *)FIRM_ADDR)->arm9Entry = 0x0801B01C; getFirmPatchPath(path, tid); r = f_open(&fd, path, FA_READ); if (r != FR_OK) goto patchFail; r = f_read(&fd, (void *)PATCH_ADDR, PATCH_SIZE, &br); if (r != FR_OK) goto patchFail; f_close(&fd); ehdr = (void *)PATCH_ADDR; shdr = (void *)(PATCH_ADDR + ehdr->e_shoff); shstrtab = (char *)PATCH_ADDR + shdr[ehdr->e_shstrndx].sh_offset; for (btm = shdr + ehdr->e_shnum; shdr != btm; shdr++) { if (!strcmp(shstrtab + shdr->sh_name, ".patch.p9.reboot.body")) { execReboot(sector, keyxArg, ehdr->e_entry, shdr); __builtin_unreachable(); } } msg = L".patch.p9.reboot.body not found\n" L"Please check your installation.\n"; fail: ConsoleInit(); ConsoleSetTitle(L"rxMode"); print(msg, r); print(L"\n"); print(strings[STR_PRESS_BUTTON_ACTION], strings[STR_BUTTON_A], strings[STR_CONTINUE]); ConsoleShow(); WaitForButton(BUTTON_A); return r; patchFail: msg = L"Failed to load the patch: %d\n" L"Check your installation.\n"; goto fail; }
/************************************************************************* main ==== **************************************************************************/ int main(void) { GO go_entry; // PLL and MAM Initialize(); // init DBG ConsoleInit(CCLK / (16 * BAUD_RATE)); DBG("Initialising USB stack\n"); write_ram_len=0; read_mem_len=0; unlocked=0; bEcho=1; // initialise stack USBInit(); // register descriptors USBRegisterDescriptors(abDescriptors); // register vendor request handler USBRegisterRequestHandler(REQTYPE_TYPE_VENDOR, HandleVendorRequest); // register pre request handler USBRegisterPreRequestHandler(PreHandleRequest); DBG("Starting USB communication\n"); // connect to bus USBHwConnect(TRUE); start_app = 0; // call USB interrupt handler continuously while (1) { USBHwISR(); if (start_app == 1) { volatile unsigned int count; // wait some time until response is sent for (count=0;count<10000;count++) USBHwISR(); // disconnect from bus USBHwConnect(FALSE); // wait some ms so that called app might safely re-connect usb for (count=0;count<300000;count++) count=count; go_entry = (GO) (start_adr); go_entry(); } } return 0; }
void dumpCoolFiles() { int nandtype = NandSwitch(); if (nandtype == UNK_NAND) return; selectedFile = -1; MenuInit(&CoolFilesMenu); MenuShow(); while (true) { uint32_t pad_state = InputWait(); if (pad_state & BUTTON_DOWN) MenuNextSelection(); if (pad_state & BUTTON_UP) MenuPrevSelection(); if (pad_state & BUTTON_A) { MenuSelect(); break; } if (pad_state & BUTTON_B) break; TryScreenShot(); MenuShow(); } if (selectedFile == -1) return; ConsoleInit(); ConsoleSetTitle(strings[STR_DUMP], strings[STR_FILES]); char dest[256], tmpstr[sizeof(dest)]; wchar_t wsrc[sizeof(tmpstr)]; sprintf(dest, "rxTools/%s", CoolFiles[selectedFile].name); sprintf(tmpstr, "%d:%s/%s", nandtype, CoolFiles[selectedFile].path, CoolFiles[selectedFile].name); mbstowcs(wsrc, tmpstr, sizeof(tmpstr)); print(strings[STR_DUMPING], wsrc, dest); ConsoleShow(); unsigned int res = FSFileCopy(dest, tmpstr); if (res != 0 && (selectedFile == 1 || selectedFile == 2)){ if (selectedFile == 1) { /* Fix for SecureInfo_B */ sprintf(dest, "rxTools/%.11s%c", CoolFiles[selectedFile].name, 'B'); sprintf(tmpstr, "%d:%s/%.11s%c", nandtype, CoolFiles[selectedFile].path, CoolFiles[selectedFile].name, 'B'); } else if (selectedFile == 2) { /* Fix for LocalFriendCodeSeed_A */ sprintf(dest, "rxTools/%.20s%c", CoolFiles[selectedFile].name, 'A'); sprintf(tmpstr, "%d:%s/%.20s%c", nandtype, CoolFiles[selectedFile].path, CoolFiles[selectedFile].name, 'A'); } mbstowcs(wsrc, tmpstr, sizeof(tmpstr)); print(strings[STR_FAILED]); print(strings[STR_DUMPING], wsrc, dest); ConsoleShow(); res = FSFileCopy(dest, tmpstr); } switch ((res >> 8) & 0xFF) { case 0: print(strings[STR_COMPLETED]); break; case 1: print(strings[STR_ERROR_OPENING], tmpstr); break; case 2: print(strings[STR_ERROR_CREATING], dest); break; case 3: case 4: print(strings[STR_ERROR_READING], tmpstr); break; case 5: case 6: print(strings[STR_ERROR_WRITING], dest); break; default: print(strings[STR_FAILED]); break; } print(strings[STR_PRESS_BUTTON_ACTION], strings[STR_BUTTON_A], strings[STR_CONTINUE]); ConsoleShow(); WaitForButton(BUTTON_A); }
INT wmain(INT argc, WCHAR *argv[]) { #ifdef STANDALONE if (argc < 2) { wprintf(L"\nReactOS Virtual DOS Machine\n\n" L"Usage: NTVDM <executable> [<parameters>]\n"); return 0; } #else INT i; WCHAR *endptr; /* Parse the command line arguments */ for (i = 1; i < argc; i++) { if (wcsncmp(argv[i], L"-i", 2) == 0) { /* This is the session ID */ SessionId = wcstoul(argv[i] + 2, &endptr, 10); /* The VDM hasn't been started from a console, so quit when the task is done */ AcceptCommands = FALSE; } } #endif NtVdmArgc = argc; NtVdmArgv = argv; DPRINT1("\n\n\nNTVDM - Starting...\n\n\n"); /* Create the task event */ VdmTaskEvent = CreateEvent(NULL, TRUE, FALSE, NULL); ASSERT(VdmTaskEvent != NULL); /* Initialize the console */ if (!ConsoleInit()) { wprintf(L"FATAL: A problem occurred when trying to initialize the console\n"); goto Cleanup; } /* Initialize the emulator */ if (!EmulatorInitialize(ConsoleInput, ConsoleOutput)) { wprintf(L"FATAL: Failed to initialize the emulator\n"); goto Cleanup; } /* Initialize the system BIOS */ if (!BiosInitialize(NULL)) { wprintf(L"FATAL: Failed to initialize the VDM BIOS.\n"); goto Cleanup; } /* Let's go! Start simulation */ CpuSimulate(); Cleanup: BiosCleanup(); EmulatorCleanup(); ConsoleCleanup(); #ifndef STANDALONE ExitVDM(FALSE, 0); #endif /* Quit the VDM */ DPRINT1("\n\n\nNTVDM - Exiting...\n\n\n"); return 0; }