Esempio n. 1
0
void main(void)
{
    // they're static so they're heap based (check this ;)
    //
    static int i;
    static char received = 0;

    LATD = 0xff;

    CardType = 0;     // no card

    CLOCKINIT();

    // ensure all ADC channels, comparators are off
    //
    ADCON1 = 0b00001111;
    CMCON = 0x07;
    TRISA = 0b11011111;

    // enable PSP
    //
    TRISE = 0b00010111;

    REDLEDOFF();
    GREENLEDOFF();

    LEDPINSOUT();

    configByte = ReadEEPROM(EE_SYSFLAGS);

    // copy the bootloader's version bytes out of program flash
    //
    memcpypgm2ram((void*)(&globalData[0]), (const rom far void *)12, 1);
    memcpypgm2ram((void*)(&globalData[1]), (const rom far void *)14, 1);
    blVersion = (globalData[0] << 4) + (globalData[1] & 0x0f);

    LATB = ReadEEPROM(EE_PORTBVALU);
    TRISB = ReadEEPROM(EE_PORTBTRIS);

    at_initprocessor();

    RELEASEIRQ();

doneprocessing:
    ACTIVITYSTROBE(1);
    PIR1bits.PSPIF = 0;

    while (PIR1bits.PSPIF == 0) {}

    at_process();
    goto doneprocessing;
}
Esempio n. 2
0
static void InitAppConfig(void)
{
	// Set the node's MAC address
	AppConfig.MyMACAddr.v[0] = MAC_BYTE1;
	AppConfig.MyMACAddr.v[1] = MAC_BYTE2;
	AppConfig.MyMACAddr.v[2] = MAC_BYTE3;
	AppConfig.MyMACAddr.v[3] = MAC_BYTE4;
	AppConfig.MyMACAddr.v[4] = MAC_BYTE5;
	AppConfig.MyMACAddr.v[5] = MAC_BYTE6;

	// Set the node's IP address
	AppConfig.MyIPAddr.Val = IP_ADDR_BYTE1 | IP_ADDR_BYTE2<<8 | IP_ADDR_BYTE3<<16 | IP_ADDR_BYTE4 << 24;

	// Se the default IP address for this node
	AppConfig.DefaultIPAddr.Val = AppConfig.MyIPAddr.Val;

	// Set the DNS mask and default mask
	AppConfig.MyMask.Val = MASK_BYTE1 | MASK_BYTE2<<8 | MASK_BYTE3<<16 | MASK_BYTE4<<24;
	AppConfig.DefaultMask.Val = AppConfig.MyMask.Val;

	// Set the default gateway
	AppConfig.MyGateway.Val = GATE_BYTE1 | GATE_BYTE2<<8 | GATE_BYTE3<<16 | GATE_BYTE4<<24;

	// Set the DNS servers.
	AppConfig.PrimaryDNSServer.Val = PRIMARY_DNS_BYTE1 | PRIMARY_DNS_BYTE2<<8  | PRIMARY_DNS_BYTE3<<16  | PRIMARY_DNS_BYTE4<<24;
	AppConfig.SecondaryDNSServer.Val = SECONDARY_DNS_BYTE1 | SECONDARY_DNS_BYTE2<<8  | SECONDARY_DNS_BYTE3<<16  | SECONDARY_DNS_BYTE4<<24;

	// Load the default NetBIOS Host Name
	memcpypgm2ram(AppConfig.NetBIOSName, (const void*)HOSTNAME, 16);
	FormatNetBIOSName(AppConfig.NetBIOSName);
}
/*
 *  FUNCTION: TaperDegreesToDistance
 *
 *  PARAMETERS:		p 	-- Pointer to Menu
 *
 *  USES GLOBALS:
 *
 *  DESCRIPTION:		Convert the full angle degrees to inch/foot of diameter.
 *
 *
 *  RETURNS: 
 *
 */
int8 
TaperDegreesToDistance(TMENU_DATA * p) {
	// Convert the included angle in degrees to inch/inch of diameter.
	p->Data.FloatValue = tan((p->Data.FloatValue)/2 * RADIANS_PER_DEGREE)*2;
	// Then check if metric measurements are wanted.
	if (p->Dependancy != (uint8)0) {	//
		DEBUGSTR("To Metric Var is dependant on %02X\n",p->Dependancy );
		// First get menu from FLASH into data structure
	  	memcpypgm2ram(
			(void *)&d, 
			(MEM_MODEL rom void *)&MenuData[p->Dependancy], 
 			sizeof(TMENU_DATA)
			);
		// Then test the flag.
		if (GetFlagVar(&d)) {	// If the metric flag is set convert the value to metric.
			DEBUGSTR("Convert to Metric\n");
			p->Data.FloatValue *= 25.4;	
			return('m');
		}
		else
			return('"');	
	}
	else
		return(' ');
}
Esempio n. 4
0
static void InitAppConfig(void)
{
    AppConfig.Flags.bIsDHCPEnabled = TRUE;
    AppConfig.Flags.bInConfigMode = TRUE;
    memcpypgm2ram((void*)&AppConfig.MyMACAddr, (ROM void*)SerializedMACAddress, sizeof(AppConfig.MyMACAddr));
    memcpypgm2ram(AppConfig.NetBIOSName, (ROM void*)MY_DEFAULT_HOST_NAME, 16);
    FormatNetBIOSName(AppConfig.NetBIOSName);
    AppConfig.MyIPAddr.Val = MY_DEFAULT_IP_ADDR_BYTE1 | MY_DEFAULT_IP_ADDR_BYTE2<<8ul | MY_DEFAULT_IP_ADDR_BYTE3<<16ul | MY_DEFAULT_IP_ADDR_BYTE4<<24ul;
    AppConfig.DefaultIPAddr.Val = AppConfig.MyIPAddr.Val;
    AppConfig.MyMask.Val = MY_DEFAULT_MASK_BYTE1 | MY_DEFAULT_MASK_BYTE2<<8ul | MY_DEFAULT_MASK_BYTE3<<16ul | MY_DEFAULT_MASK_BYTE4<<24ul;
    AppConfig.DefaultMask.Val = AppConfig.MyMask.Val;
    AppConfig.MyGateway.Val = MY_DEFAULT_GATE_BYTE1 | MY_DEFAULT_GATE_BYTE2<<8ul | MY_DEFAULT_GATE_BYTE3<<16ul | MY_DEFAULT_GATE_BYTE4<<24ul;
    AppConfig.PrimaryDNSServer.Val = MY_DEFAULT_PRIMARY_DNS_BYTE1 | MY_DEFAULT_PRIMARY_DNS_BYTE2<<8ul  | MY_DEFAULT_PRIMARY_DNS_BYTE3<<16ul  | MY_DEFAULT_PRIMARY_DNS_BYTE4<<24ul;
    AppConfig.SecondaryDNSServer.Val = MY_DEFAULT_SECONDARY_DNS_BYTE1 | MY_DEFAULT_SECONDARY_DNS_BYTE2<<8ul  | MY_DEFAULT_SECONDARY_DNS_BYTE3<<16ul  | MY_DEFAULT_SECONDARY_DNS_BYTE4<<24ul;

    #if defined(EEPROM_CS_TRIS)
    {
        BYTE c;

        // When a record is saved, first byte is written as 0x60 to indicate
        // that a valid record was saved.  Note that older stack versions
        // used 0x57.  This change has been made to so old EEPROM contents
        // will get overwritten.  The AppConfig() structure has been changed,
        // resulting in parameter misalignment if still using old EEPROM
        // contents.
        XEEReadArray(0x0000, &c, 1);
        if(c == 0x42u)
        {
            XEEReadArray(0x0001, (BYTE*)&AppConfig, sizeof(AppConfig));
        }
    else
        SaveAppConfig();
    }
    #elif defined(SPIFLASH_CS_TRIS)
    {
        BYTE c;

        SPIFlashReadArray(0x0000, &c, 1);
        if(c == 0x42u)
        {
            SPIFlashReadArray(0x0001, (BYTE*)&AppConfig, sizeof(AppConfig));
        }
        else
            SaveAppConfig();
    }
    #endif
}
Esempio n. 5
0
void strcpypgm2ram(char *d, __ADDRESS__ s)
{
   char c;
   do
   {
      memcpypgm2ram(&c, s++, 1);
      *d++ = c;
   } while(c);
}
Esempio n. 6
0
MPFS MPFSOpenROM(ROM BYTE* file) 
{
   BYTE nameRAM[MAX_FILE_NAME_LEN+1];
   
   memcpypgm2ram(nameRAM, (ROM void*)file, strlenpgm((ROM char*)file));
   nameRAM[strlenpgm((ROM char*)file)] = '\0';
   
   return MPFSOpen(nameRAM);
}   
Esempio n. 7
0
unsigned int8 strlenpgm( __ADDRESS__ s)
{
   char c;
   char counter = 0;
   do{
      memcpypgm2ram(&c,s++,1);
      counter++;
   }while(c != 0);
   return(counter - 1);
}
Esempio n. 8
0
void unabto_sha256_init(sha256_ctx* context) {
#if UNABTO_PLATFORM_PIC18
  memcpypgm2ram(context->state, sha256_initial_hash_value, sizeof(sha256_initial_hash_value));
#else
    memcpy(context->state, sha256_initial_hash_value, sizeof(sha256_initial_hash_value));
#endif
	MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH);

	context->byteCount = 0;
}
Esempio n. 9
0
void main (void)
{
    initBoard();
	memcpypgm2ram((void*)GetLcdBuffer(), "I am Alive",10);
	LCDUpdate();
	
	while (1)
	{

		StateMachine();
		sprintf(GetLcdBuffer(),"%d %d %d %d %d %d %d ",L_MOTOR_FB1,L_WHITE_LINE_SENSE,R_BACK_BUMPER,FRONT_BUMPER,L_BACK_BUMPER,R_WHITE_LINE_SENSE,R_MOTOR_FB1);
		LCDUpdate();










#if 0
		if( !BUTTON0_IO ) 
		{
			LED0_IO =1;
			CCPR3L += 1;
			CCPR4L += 1;
			sprintf(GetLcdBuffer(),"%d %d %d %d %d %d %d ",L_MOTOR_FB1,L_WHITE_LINE_SENSE,BUMPER1,BUMPER2,BUMPER3,R_WHITE_LINE_SENSE,R_MOTOR_FB1);
			sprintf(GetLcdBuffer()+16,"val: %d",CCPR3L);
			LCDUpdate();
			MOTOR_CARD_RELAY = 1;
			//L_MOTOR_BREAK = 1;
			R_MOTOR_BREAK = 1;
			DelayMs(100);	
		}
		else
		{
			LED0_IO = 0;
			sprintf(GetLcdBuffer(),"%d %d %d %d %d %d %d ",L_MOTOR_FB1,L_WHITE_LINE_SENSE,BUMPER1,BUMPER2,BUMPER3,R_WHITE_LINE_SENSE,R_MOTOR_FB1);
			LCDUpdate();
			
		}
		if( !BUTTON1_IO )
		{
			MOTOR_CARD_RELAY = 0;
			L_MOTOR_BREAK = 0;
			R_MOTOR_BREAK = 0;
			CCPR3L = 0;
			CCPR4L = 0;
		}
#endif
	}

}
Esempio n. 10
0
	void _general_exception_handler(unsigned cause, unsigned status)
	{
		Nop();
			#if defined(TEST)
			{
				memcpypgm2ram(Err_String,"C32 GENRAl EXECPTION",19);
				ERR_LOG (Err_String);
			}
			#endif
		Nop();
	}
Esempio n. 11
0
void WriteLCDMenu(void)
{// Update the LCD screen
	
	// Blank the LCD display
	strcpypgm2ram((char*)LCDText, (ROM char*)"                                ");
	
	// Show the name
	strcpy((char*)LCDText, (char*)Products[curItem].name);
	LCDText[strlen((char*)Products[curItem].name)] = ' ';
	
	// Show the price, or sold out status
	if(Products[curItem].stock == 0u)
	{
		memcpypgm2ram(&LCDText[12], (ROM void*)"SOLD", 4);
	}
	else
	{
		LCDText[11] = '$';
		WritePriceLCD(Products[curItem].price, 12);
	}
	
	// Show the current credit
	LCDText[16] = '$';
	WritePriceLCD(curCredit, 17);
	
	// Show the vend button if available
	if(Products[curItem].stock != 0u && Products[curItem].price <= curCredit)
		memcpypgm2ram(&LCDText[22], (ROM void*)"Vend", 4);
	else
		memcpypgm2ram(&LCDText[23], (ROM void*)"--", 2);
	
	// Show the rest of the buttons
	if(curItem != 0u)
		memcpypgm2ram(&LCDText[27], (ROM void*)"<<", 2);
	if(curItem != MAX_PRODUCTS-1)
		memcpypgm2ram(&LCDText[30], (ROM void*)">>", 2);

	// Update to the screen	
	LCDUpdate();
}
Esempio n. 12
0
static void InitAppConfig(void)
{
	
	while(1)
	{
		// Start out zeroing all AppConfig bytes to ensure all fields are 
		// deterministic for checksum generation
		memset((void*)&AppConfig, 0x00, sizeof(AppConfig));
		
		AppConfig.Flags.bIsDHCPEnabled = TRUE;
		AppConfig.Flags.bInConfigMode = TRUE;
		memcpypgm2ram((void*)&AppConfig.MyMACAddr, (ROM void*)SerializedMACAddress, sizeof(AppConfig.MyMACAddr));
//		{
//			_prog_addressT MACAddressAddress;
//			MACAddressAddress.next = 0x157F8;
//			_memcpy_p2d24((char*)&AppConfig.MyMACAddr, MACAddressAddress, sizeof(AppConfig.MyMACAddr));
//		}
		AppConfig.MyIPAddr.Val = MY_DEFAULT_IP_ADDR_BYTE1 | MY_DEFAULT_IP_ADDR_BYTE2<<8ul | MY_DEFAULT_IP_ADDR_BYTE3<<16ul | MY_DEFAULT_IP_ADDR_BYTE4<<24ul;
		AppConfig.DefaultIPAddr.Val = AppConfig.MyIPAddr.Val;
		AppConfig.MyMask.Val = MY_DEFAULT_MASK_BYTE1 | MY_DEFAULT_MASK_BYTE2<<8ul | MY_DEFAULT_MASK_BYTE3<<16ul | MY_DEFAULT_MASK_BYTE4<<24ul;
		AppConfig.DefaultMask.Val = AppConfig.MyMask.Val;
		AppConfig.MyGateway.Val = MY_DEFAULT_GATE_BYTE1 | MY_DEFAULT_GATE_BYTE2<<8ul | MY_DEFAULT_GATE_BYTE3<<16ul | MY_DEFAULT_GATE_BYTE4<<24ul;
		AppConfig.PrimaryDNSServer.Val = MY_DEFAULT_PRIMARY_DNS_BYTE1 | MY_DEFAULT_PRIMARY_DNS_BYTE2<<8ul  | MY_DEFAULT_PRIMARY_DNS_BYTE3<<16ul  | MY_DEFAULT_PRIMARY_DNS_BYTE4<<24ul;
		AppConfig.SecondaryDNSServer.Val = MY_DEFAULT_SECONDARY_DNS_BYTE1 | MY_DEFAULT_SECONDARY_DNS_BYTE2<<8ul  | MY_DEFAULT_SECONDARY_DNS_BYTE3<<16ul  | MY_DEFAULT_SECONDARY_DNS_BYTE4<<24ul;
	
	
		// Load the default NetBIOS Host Name
		memcpypgm2ram(AppConfig.NetBIOSName, (ROM void*)MY_DEFAULT_HOST_NAME, 16);
		FormatNetBIOSName(AppConfig.NetBIOSName);

		// Compute the checksum of the AppConfig defaults as loaded from ROM
		wOriginalAppConfigChecksum = CalcIPChecksum((BYTE*)&AppConfig, sizeof(AppConfig));

		break;
	}
}
Esempio n. 13
0
BYTE MDD_IntFlash_SectorRead(DWORD sector_addr, BYTE* buffer)
{
    //Error check.  Make sure the host is trying to read from a legitimate
    //address, which corresponds to the MSD volume (and not some other program
    //memory region beyond the end of the MSD volume).
    if(sector_addr >= MDD_INTERNAL_FLASH_TOTAL_DISK_SIZE)
    {
        return FALSE;
    }   
    
    //Read a sector worth of data, and copy it to the specified RAM "buffer".
    memcpypgm2ram
    (
        (void*)buffer,
        (ROM void*)(MASTER_BOOT_RECORD_ADDRESS + (sector_addr * MEDIA_SECTOR_SIZE)),
        MEDIA_SECTOR_SIZE
    );

	return TRUE;
}//end SectorRead
int8
CalcMetricDepth( TMENU_DATA * p) {
	// Conversions are often dependant on whether another flag is set.
	if (p->Dependancy != (uint8)0) {	//
		// First get menu from FLASH into data structure
	  	memcpypgm2ram(
			(void *)&d, 
			(MEM_MODEL rom void *)&MenuData[p->Dependancy], 
			sizeof(TMENU_DATA)
			);
		p->Data.FloatValue = (GlobalVars[DEPTH_MULTIPLIER_NDX].f * GlobalVars[THREAD_SIZE_NDX].f);
		// Then test the flag.
		if (GetFlagVar(&d)) {	// If the metric flag is set convert the value to metric.
			p->Data.FloatValue *= 25.4;
			return('m');
		}
		else
			return('"');	
	}
	else
		return(' ');
}
/*
 *  FUNCTION: TaperDistanceToDegrees
 *
 *  PARAMETERS:		p 	-- Pointer to Menu
 *
 *  USES GLOBALS:
 *
 *  DESCRIPTION:	Convert taper in inch/ft to degrees.
 *
 *  RETURNS: 		Nothing.
 *
 */
int8 
TaperDistanceToDegrees(TMENU_DATA * p) {
	// Conversions are often dependant on whether another flag is set.
	if (p->Dependancy != (uint8)0) {	//
		DEBUGSTR("To Imperial Var is dependant on %02X\n",p->Dependancy );
		// First get menu from FLASH into data structure
	  	memcpypgm2ram(
			(void *)&d, 
			(MEM_MODEL rom void *)&MenuData[p->Dependancy], 
			sizeof(TMENU_DATA)
			);
		// Then test the flag.
		if (GetFlagVar(&d)) {	// If the metric flag is set convert the value to imperial.
			DEBUGSTR("Convert to Imperial\n");
			p->Data.FloatValue /= 25.4;
		}	
	}
	// Now we know we have imperial units in inch per inch and then degrees
	// finally change that to (included) angle degrees.
	p->Data.FloatValue = (atan(p->Data.FloatValue / 2) / RADIANS_PER_DEGREE) * 2;
	return(' ');
}
/*
 *  FUNCTION: ConvertToMetric
 *
 *  PARAMETERS:		p 	-- Pointer to Menu
 *
 *  USES GLOBALS:
 *
 *  DESCRIPTION:	Tests menu parameter to see if it needs to be converted
 *					from imperial to metric and returns m ' or space character.
 *
 *  RETURNS: 		' ', 'm', '"'
 *
 */
int8
ConvertToMetric( TMENU_DATA * p) {
	// Conversions are often dependant on whether another flag is set.
	if (p->Dependancy != (uint8)0) {	//
		DEBUGSTR("To Metric Var is dependant on %02X\n",p->Dependancy );
		// First get menu from FLASH into data structure
	  	memcpypgm2ram(
			(void *)&d, 
			(MEM_MODEL rom void *)&MenuData[p->Dependancy], 
			sizeof(TMENU_DATA)
			);
		// Then test the flag.
		if (GetFlagVar(&d)) {	// If the metric flag is set convert the value to metric.
			DEBUGSTR("Convert to Metric\n");
			p->Data.FloatValue *= 25.4;	
			return('m');
		}
		else
			return('"');	
	}
	else
		return(' ');
}
Esempio n. 17
0
void HTTPExecCmd(BYTE** argv, BYTE argc)
{
    BYTE command;
    BYTE var;

    /*
     * Design your pages such that they contain command code
     * as a one character numerical value.
     * Being a one character numerical value greatly simplifies
     * the job.
     */
    command = argv[0][0] - '0';

    /*
     * Find out the cgi file name and interpret parameters
     * accordingly
     */
    switch(command)
    {
    case CGI_CMD_DIGOUT:
        /*
         * This DIGOUTS.CGI.  Any arguments with this file
         * must be about controlling digital outputs.
         */

        /*
         * Identify the parameters.
         * Compare it in upper case format.
         */
        var = argv[1][0] - '0';

        switch(var)
        {
        case HEATER:
            /*
             * Toggle RC2.
             */
            if(LATB4)
            {
                LATB4 = 0;
			}
            else
            {
                LATB4 = 1; 
                heater_started = 1;   
            }
            //LATB4 ^= 1;
            break;

        case FAN:
            /*
             * Toggle RC5.
             */
            LATB5 ^= 1;
            break;
         }

         memcpypgm2ram((void*)argv[0],
              (ROM void*)COMMANDS_OK_PAGE, COMMANDS_OK_PAGE_LEN);
         break;

    case CGI_CMD_LCDOUT:
        /*
         * Note implemented.
         */
        break;

    default:
        memcpypgm2ram((void*)argv[0],
              (ROM void*)CMD_UNKNOWN_PAGE, CMD_UNKNOWN_PAGE_LEN);
        break;
    }

}
Esempio n. 18
0
/*********************************************************************
 * Function:        MPFS MPFSOpen(BYTE* file)
 *
 * PreCondition:    None
 *
 * Input:           file        - NULL terminated file name.
 *
 * Output:          A handle if file is found
 *                  MPFS_INVALID if file is not found.
 *
 * Side Effects:    None
 *
 * Overview:        None
 *
 * Note:            None
 ********************************************************************/
MPFS MPFSOpen(BYTE* file)
{
    MPFS_ENTRY entry;
    MPFS FAT;
    BYTE fileNameLen;
    
    debug_mpfs(debug_mpfs_putc, "\r\nMPFSOpen() '%s' ", file);

    if( mpfsFlags.bits.bNotAvailable )
    {
        debug_mpfs(debug_mpfs_putc, "NOT AVAILABLE");
        return MPFS_NOT_AVAILABLE;
    }

#if defined(MPFS_USE_EEPROM) || defined(MPFS_USE_SPI_FLASH)
    FAT = MPFS_Start;
#else
    FAT = (MPFS)MPFS_Start;
#endif

    // If string is empty, do not attempt to find it in FAT.
    if ( *file == '\0' )
        return MPFS_INVALID;

    //debug_mpfs("p1='%s'0x%LX ", file, file);

    file = (BYTE*)strupr((char*)file);
    
    //debug_mpfs("p2='%s'0x%LX ", file, file);

    debug_mpfs(debug_mpfs_putc, "START=0x%LX ", FAT);

    for(;;)
    {
        // Bring current FAT entry into RAM.
      #if defined(MPFS_USE_EEPROM)
           XEEReadArray(FAT, (unsigned char*)&entry, sizeof(entry));
      #elif defined(MPFS_USE_SPI_FLASH)
           SPIFlashReadArray(FAT, (BYTE*)&entry, sizeof(entry));
      #else
         #if defined(__C30__)
              memcpypgm2ram(&entry, (ROM void*)(WORD)FAT, sizeof(entry));
         #else
              memcpypgm2ram(&entry, (ROM void*)FAT, sizeof(entry));
         #endif
      #endif

       debug_mpfs(debug_mpfs_putc, "FLAG=0x%X ", entry.Flag);

        // Make sure that it is a valid entry.
        if (entry.Flag == MPFS_DATA)
        {
            // Does the file name match ?
            fileNameLen = strlen((char*)file);
            
            if ( fileNameLen > MAX_FILE_NAME_LEN )
                fileNameLen = MAX_FILE_NAME_LEN;

            //debug_mpfs("f='%s' (%u) vs '%s' ", entry.Name, fileNameLen, file);

            if( memcmp((void*)file, (void*)entry.Name, fileNameLen) == 0 )
            {
             #if defined(__PCD__)
               #warning 4.121 temporary bug fix
               memcpy(&_currentFile, &entry.Address, 4);
              #if defined(MPFS_RETURN_OFFSET)
                _currentFile += MPFS_Start;
              #endif
                mpfsOpenCount++;
                debug_mpfs(debug_mpfs_putc, "found_0x%LX ", _currentFile);
                return _currentFile;
             #else
              #if defined(MPFS_RETURN_OFFSET)
                entry.Address += MPFS_Start;
              #endif
                _currentFile = (MPFS)entry.Address;
                mpfsOpenCount++;
                debug_mpfs(debug_mpfs_putc, "found_0x%LX ", _currentFile);
                return entry.Address;
             #endif
            }

            // File does not match.  Try next entry...
            FAT += sizeof(entry);
        }
        else if ( entry.Flag == MPFS_ETX )
        {
            #warning 4.121 temporary bug fix
            unsigned int32 entry_Address;
            memcpy(&entry_Address, &entry.Address, 4);
            if ( entry_Address != (MPFS)MPFS_INVALID )
            {
                FAT = (MPFS)entry_Address; //original, doesn't work 4.121 pcd
                debug_mpfs(debug_mpfs_putc, "(etx 0x%LX) ", FAT);
            }
            else
            {
                debug_mpfs(debug_mpfs_putc, "invalid_etx ");
                break;
            }
        }
       else
       {
           debug_mpfs(debug_mpfs_putc, "invalid_flag ");
           return (MPFS)MPFS_INVALID;
       }
    }
    debug_mpfs(debug_mpfs_putc, "not_found ");
    return (MPFS)MPFS_INVALID;
}
/******************************************************************************
 	Function:
 		void MSDProcessCommandMediaAbsent(void)
 		
 	Description:
 		This funtion processes a command received through the MSD
 		class driver
 		
 	PreCondition:
 		None
 		
 	Parameters:
 		None
 	
 	Return Values:
 		BYTE - the current state of the MSDProcessCommand state
 		machine.  The valid values are defined in MSD.h under the 
 		MSDProcessCommand state machine declaration section
 		
 	Remarks:
 		None
 
  *****************************************************************************/	
void MSDProcessCommandMediaAbsent(void)
{
    BYTE i;

    switch(MSDCommandState)
    {
        case MSD_REQUEST_SENSE:
        {
            ResetSenseData();
            gblSenseData[LUN_INDEX].SenseKey=S_NOT_READY;
    		gblSenseData[LUN_INDEX].ASC=ASC_MEDIUM_NOT_PRESENT;
    		gblSenseData[LUN_INDEX].ASCQ=ASCQ_MEDIUM_NOT_PRESENT;

          	for(i=0;i<sizeof(RequestSenseResponse);i++)
          	{
          		msd_buffer[i]=gblSenseData[LUN_INDEX]._byte[i];
            }
          	
            msd_csw.dCSWDataResidue=sizeof(RequestSenseResponse);
          	msd_csw.bCSWStatus=0x0;					// success
          	MSDCommandState = MSD_COMMAND_RESPONSE;
            break;
        } 
        case MSD_PREVENT_ALLOW_MEDIUM_REMOVAL:
        case MSD_TEST_UNIT_READY:
        {
    		msd_csw.bCSWStatus=0x01;
            MSDCommandState = MSD_COMMAND_WAIT;
            break;
        }
        case MSD_INQUIRY:
        {
        	memcpypgm2ram(
        	    (void *)&msd_buffer[0],
        	    (ROM void*)&inq_resp,
        	    sizeof(InquiryResponse)
        	    );
        	msd_csw.dCSWDataResidue=sizeof(InquiryResponse);
        	msd_csw.bCSWStatus=0x00;			// success
        	MSDCommandState = MSD_COMMAND_RESPONSE;
            break;
        }
        case MSD_COMMAND_WAIT:
        {
            MSDCommandState = gblCBW.CBWCB[0];
            break;
        }
        case MSD_COMMAND_RESPONSE:
            if(USBHandleBusy(USBMSDInHandle) == FALSE)
            {
                USBMSDInHandle = USBTxOnePacket(MSD_DATA_IN_EP,(BYTE*)&msd_buffer[0],msd_csw.dCSWDataResidue);
			    MSDCommandState = MSD_COMMAND_WAIT;

        		msd_csw.dCSWDataResidue=0;
            }
            break;
        default:
        {
            //Stall MSD endpoint IN
            USBStallEndpoint(MSD_DATA_IN_EP,1);
    		msd_csw.bCSWStatus=0x01;
            MSDCommandState = MSD_COMMAND_WAIT;
            break;
        }
    }
}
/******************************************************************************
 	Function:
 		void MSDProcessCommandMediaPresent(void)
 		
 	Description:
 		This funtion processes a command received through the MSD
 		class driver
 		
 	PreCondition:
 		None
 		
 	Paramters:
 		None
 	
 	Return Values:
 		BYTE - the current state of the MSDProcessCommand state
 		machine.  The valid values are defined in MSD.h under the 
 		MSDProcessCommand state machine declaration section
 		
 	Remarks:
 		None
 
 *****************************************************************************/	
void MSDProcessCommandMediaPresent(void)
{
    BYTE i; 

    switch(MSDCommandState)
    {
        case MSD_COMMAND_WAIT:
            //copy the received command to the command state machine
            MSDCommandState = gblCBW.CBWCB[0];
            break;
    	case MSD_INQUIRY:
    	{
            //copy the inquiry results from the defined ROM buffer 
            //  into the USB buffer so that it can be transmitted
        	memcpypgm2ram(
        	    (void *)&msd_buffer[0],
        	    (ROM void*)&inq_resp,
        	    sizeof(InquiryResponse)
        	    );
        	msd_csw.dCSWDataResidue=sizeof(InquiryResponse);
        	msd_csw.bCSWStatus=0x00;			// success
        	MSDCommandState = MSD_COMMAND_RESPONSE;
            break;
        }
        case MSD_READ_CAPACITY:
        {
            //If the host asked for the capacity of the device
            DWORD_VAL sectorSize;
            DWORD_VAL capacity;

        	msd_csw.bCSWStatus=0x00;			  // success
            
            //get the information from the physical media
            capacity.Val = LUNReadCapacity();
            sectorSize.Val = LUNReadSectorSize();
            
            //copy the data to the buffer
        	msd_buffer[0]=capacity.v[3];
        	msd_buffer[1]=capacity.v[2];
        	msd_buffer[2]=capacity.v[1];
        	msd_buffer[3]=capacity.v[0];
        	
        	msd_buffer[4]=sectorSize.v[3];
        	msd_buffer[5]=sectorSize.v[2];
        	msd_buffer[6]=sectorSize.v[1];
        	msd_buffer[7]=sectorSize.v[0];
        
        	msd_csw.dCSWDataResidue=0x08;		  // size of response
        	MSDCommandState = MSD_COMMAND_RESPONSE;
            break;
        }
		case MSD_READ_10:
        	if(MSDReadHandler() == MSD_READ10_WAIT)
        	{
			    MSDCommandState = MSD_COMMAND_WAIT;
            }
            break;
    	case MSD_WRITE_10:
        	if(MSDWriteHandler() == MSD_WRITE10_WAIT)
        	{
			    MSDCommandState = MSD_COMMAND_WAIT;
            }
		    break;
        case MSD_REQUEST_SENSE:    
          	for(i=0;i<sizeof(RequestSenseResponse);i++)
          	{
          		msd_buffer[i]=gblSenseData[LUN_INDEX]._byte[i];
            }
          	
            msd_csw.dCSWDataResidue=sizeof(RequestSenseResponse);
          	msd_csw.bCSWStatus=0x0;					// success
          	MSDCommandState = MSD_COMMAND_RESPONSE;
            break;
	    case MSD_MODE_SENSE:
        	msd_buffer[0]=0x02;
        	msd_buffer[1]=0x00;
        	msd_buffer[2]=0x00;
        	msd_buffer[3]=0x00;
        	
        	msd_csw.bCSWStatus=0x0;
        	msd_csw.dCSWDataResidue=0x04;
        	MSDCommandState = MSD_COMMAND_RESPONSE;
    	    break;
		case MSD_PREVENT_ALLOW_MEDIUM_REMOVAL:
            if(LUNMediaDetect())
            {
        		msd_csw.bCSWStatus=0x00;
        		msd_csw.dCSWDataResidue=0x00;
        	}
            else
            {
        		gblSenseData[LUN_INDEX].SenseKey=S_NOT_READY;
        		gblSenseData[LUN_INDEX].ASC=ASC_MEDIUM_NOT_PRESENT;
        		gblSenseData[LUN_INDEX].ASCQ=ASCQ_MEDIUM_NOT_PRESENT;
        		msd_csw.bCSWStatus=0x01;
        	}
			MSDCommandState = MSD_COMMAND_WAIT;
            break;
		case MSD_TEST_UNIT_READY:
            if((gblSenseData[LUN_INDEX].SenseKey==S_UNIT_ATTENTION) && (msd_csw.bCSWStatus==1))
            {
                MSDCommandState = MSD_COMMAND_WAIT;
            }
            else
            {
            	ResetSenseData();
            	msd_csw.dCSWDataResidue=0x00;
    			MSDCommandState = MSD_COMMAND_WAIT;
            }
            break;
		case MSD_VERIFY:
            //Fall through to STOP_START
		case MSD_STOP_START:
        	msd_csw.bCSWStatus=0x0;
        	msd_csw.dCSWDataResidue=0x00;
			MSDCommandState = MSD_COMMAND_WAIT;
            break;
        case MSD_COMMAND_RESPONSE:
            if(USBHandleBusy(USBMSDInHandle) == FALSE)
            {
                USBMSDInHandle = USBTxOnePacket(MSD_DATA_IN_EP,(BYTE*)&msd_buffer[0],msd_csw.dCSWDataResidue);
			    MSDCommandState = MSD_COMMAND_WAIT;

        		msd_csw.dCSWDataResidue=0;
            }
            break;
        case MSD_COMMAND_ERROR:
		default:
        	ResetSenseData();
			gblSenseData[LUN_INDEX].SenseKey=S_ILLEGAL_REQUEST;
			gblSenseData[LUN_INDEX].ASC=ASC_INVALID_COMMAND_OPCODE;
			gblSenseData[LUN_INDEX].ASCQ=ASCQ_INVALID_COMMAND_OPCODE;
			msd_csw.bCSWStatus=0x01;
			msd_csw.dCSWDataResidue=0x00;
			MSDCommandState = MSD_COMMAND_RESPONSE;
 		    break;
	} // end switch	
}
//////////////////////////////////////////////////////////////////////////////////////////
// NOTE: The following HTTP code pretains to the old HTTP server.
//       Upgrading to HTTP2 is *strongly* recommended for all new designs.
//       Custom control of HTTP2 is implemented in CustomHTTPApp.c
//////////////////////////////////////////////////////////////////////////////////////////
WORD HTTPGetVar(BYTE var, WORD ref, BYTE* val)
{
	// Temporary variables designated for storage of a whole return 
	// result to simplify logic needed since one byte must be returned
	// at a time.
	static BYTE VarString[25];
#if defined(ENABLE_REMOTE_CONFIG)
	static BYTE VarStringLen;
	BYTE *VarStringPtr;

	BYTE i;
	BYTE *DataSource;
#endif
	
	// Identify variable
    switch(var)
    {
    case VAR_LED0:
        *val = LED0_IO ? '1':'0';
        break;
    case VAR_LED1:
        *val = LED1_IO ? '1':'0';
        break;
    case VAR_LED2:
        *val = LED2_IO ? '1':'0';
        break;
    case VAR_LED3:
        *val = LED3_IO ? '1':'0';
        break;
    case VAR_LED4:
        *val = LED4_IO ? '1':'0';
        break;
    case VAR_LED5:
        *val = LED5_IO ? '1':'0';
        break;
    case VAR_LED6:
        *val = LED6_IO ? '1':'0';
        break;
    case VAR_LED7:
        *val = LED7_IO ? '1':'0';
        break;

    case VAR_ANAIN_AN0:
        *val = AN0String[(BYTE)ref];
        if(AN0String[(BYTE)ref] == '\0')
            return HTTP_END_OF_VAR;
		else if(AN0String[(BYTE)++ref] == '\0' )
            return HTTP_END_OF_VAR;
        return ref;
//    case VAR_ANAIN_AN1:
//        *val = AN1String[(BYTE)ref];
//        if(AN1String[(BYTE)ref] == '\0')
//            return HTTP_END_OF_VAR;
//		else if(AN1String[(BYTE)++ref] == '\0' )
//            return HTTP_END_OF_VAR;
//        return ref;

    case VAR_DIGIN0:
        *val = BUTTON0_IO ? '1':'0';
        break;
    case VAR_DIGIN1:
        *val = BUTTON1_IO ? '1':'0';
        break;
    case VAR_DIGIN2:
        *val = BUTTON2_IO ? '1':'0';
        break;
    case VAR_DIGIN3:
        *val = BUTTON3_IO ? '1':'0';
        break;

	case VAR_STACK_VERSION:
        if(ref == HTTP_START_OF_VAR)
		{
			strncpypgm2ram((char*)VarString, (ROM char*)TCPIP_STACK_VERSION, sizeof(VarString));
		}
        *val = VarString[(BYTE)ref];
        if(VarString[(BYTE)ref] == '\0')
            return HTTP_END_OF_VAR;
		else if(VarString[(BYTE)++ref] == '\0' )
            return HTTP_END_OF_VAR;
        return ref;
	case VAR_STACK_DATE:
        if(ref == HTTP_START_OF_VAR)
		{
			strncpypgm2ram((char*)VarString, (ROM char*)(__DATE__ " " __TIME__), sizeof(VarString));
		}
        *val = VarString[(BYTE)ref];
        if(VarString[(BYTE)ref] == '\0')
            return HTTP_END_OF_VAR;
		else if(VarString[(BYTE)++ref] == '\0' )
            return HTTP_END_OF_VAR;
        return ref;

#if defined(ENABLE_REMOTE_CONFIG)
    case VAR_MAC_ADDRESS:
        if ( ref == HTTP_START_OF_VAR )
        {
            VarStringLen = 2*6+5;	// 17 bytes: 2 for each of the 6 address bytes + 5 octet spacers

	        // Format the entire string
            i = 0;
            VarStringPtr = VarString;
            while(1)
            {
	            *VarStringPtr++ = btohexa_high(AppConfig.MyMACAddr.v[i]);
	            *VarStringPtr++ = btohexa_low(AppConfig.MyMACAddr.v[i]);
	            if(++i == 6)
	            	break;
	            *VarStringPtr++ = '-';
	        }
        }

		// Send one byte back to the calling function (the HTTP Server)
		*val = VarString[(BYTE)ref];
		
        if ( (BYTE)++ref == VarStringLen )
            return HTTP_END_OF_VAR;

        return ref;
    		
    case VAR_IP_ADDRESS:
    case VAR_SUBNET_MASK:
    case VAR_GATEWAY_ADDRESS:
    	// Check if ref == 0 meaning that the first character of this 
    	// variable needs to be returned
        if ( ref == HTTP_START_OF_VAR )
        {
	        // Decide which 4 variable bytes to send back
	        if(var == VAR_IP_ADDRESS)
		    	DataSource = (BYTE*)&AppConfig.MyIPAddr;
		    else if(var == VAR_SUBNET_MASK)
		    	DataSource = (BYTE*)&AppConfig.MyMask;
		    else if(var == VAR_GATEWAY_ADDRESS)
		    	DataSource = (BYTE*)&AppConfig.MyGateway;
	        
	        // Format the entire string
	        VarStringPtr = VarString;
	        i = 0;
	        while(1)
	        {
		        uitoa((WORD)*DataSource++, VarStringPtr);
		        VarStringPtr += strlen(VarStringPtr);
		        if(++i == 4)
		        	break;
		        *VarStringPtr++ = '.';
		    }
		    VarStringLen = strlen(VarString);
        }

		// Send one byte back to the calling function (the HTTP Server)
		*val = VarString[(BYTE)ref];
		
		// If this is the last byte to be returned, return 
		// HTTP_END_OF_VAR so the HTTP server won't keep calling this 
		// application callback function
        if ( (BYTE)++ref == VarStringLen )
            return HTTP_END_OF_VAR;

        return ref;
    	
    case VAR_DHCP_TRUE:
    case VAR_DHCP_FALSE:
    	// Check if ref == 0 meaning that the first character of this 
    	// variable needs to be returned
        if ( ref == HTTP_START_OF_VAR )
        {
	        if((var == VAR_DHCP_TRUE) ^ AppConfig.Flags.bIsDHCPEnabled)
	        	return HTTP_END_OF_VAR;

            VarStringLen = 7;
			memcpypgm2ram(VarString, (ROM void *)"checked", 7);
        }

		*val = VarString[(BYTE)ref];
		
        if ( (BYTE)++ref == VarStringLen )
            return HTTP_END_OF_VAR;

        return ref;
#endif	// #if defined(ENABLE_REMOTE_CONFIG)
    }

    return HTTP_END_OF_VAR;
}
void HTTPExecCmd(BYTE** argv, BYTE argc)
{
    BYTE command;
    BYTE var;
#if defined(ENABLE_REMOTE_CONFIG)
	DWORD_VAL dwVal;
    BYTE CurrentArg;
    WORD_VAL TmpWord;
#endif
    /*
     * Design your pages such that they contain command code
     * as a one character numerical value.
     * Being a one character numerical value greatly simplifies
     * the job.
     */
    command = argv[0][0] - '0';

    /*
     * Find out the cgi file name and interpret parameters
     * accordingly
     */
    switch(command)
    {
    case CGI_CMD_DIGOUT:	// ACTION=0
        /*
         * Identify the parameters.
         * Compare it in upper case format.
         */
        var = argv[1][0] - '0';

        switch(var)
        {
        case CMD_LED1:	// NAME=0
            // Toggle LED.
            LED1_IO ^= 1;
            break;

        case CMD_LED2:	// NAME=1
            // Toggle LED.
            LED2_IO ^= 1;
            break;
         }

         memcpypgm2ram((void*)argv[0], (ROM void*)COMMANDS_OK_PAGE, COMMANDS_OK_PAGE_LEN);
         break;
#if defined(USE_LCD)
    case CGI_CMD_LCDOUT:	// ACTION=1
		if(argc > 2u)	// Text provided in argv[2]
		{
			// Convert %20 to spaces, and other URL transformations
			UnencodeURL(argv[2]);

			// Write 32 received characters or less to LCDText
			if(strlen((char*)argv[2]) < 32u)
			{
				memset(LCDText, ' ', 32);
				strcpy((char*)LCDText, (char*)argv[2]);
			}
			else
			{
				memcpy(LCDText, (void*)argv[2], 32);
			}

			// Write LCDText to the LCD
			LCDUpdate();
		}
		else			// No text provided
		{
			LCDErase();
		}
		memcpypgm2ram((void*)argv[0], (ROM void*)COMMANDS_OK_PAGE, COMMANDS_OK_PAGE_LEN);
        break;
#endif
#if defined(ENABLE_REMOTE_CONFIG)
// Possibly useful code for remotely reconfiguring the board through 
// HTTP
	case CGI_CMD_RECONFIG:	// ACTION=2
		// Loop through all variables that we've been given
		CurrentArg = 1;
		while(argc > CurrentArg)
		{
			// Get the variable identifier (HTML "name"), and 
			// increment to the variable's value
			TmpWord.v[1] = argv[CurrentArg][0];
			TmpWord.v[0] = argv[CurrentArg++][1];
	        var = hexatob(TmpWord);
	        
	        // Make sure the variable's value exists
	        if(CurrentArg >= argc)
	        	break;
	        
	        // Take action with this variable/value
	        switch(var)
	        {
	        case VAR_IP_ADDRESS:
	        case VAR_SUBNET_MASK:
	        case VAR_GATEWAY_ADDRESS:
	        	{
		        	// Convert the returned value to the 4 octect 
		        	// binary representation
			        if(!StringToIPAddress(argv[CurrentArg], (IP_ADDR*)&dwVal))
			        	break;

					// Reconfigure the App to use the new values
			        if(var == VAR_IP_ADDRESS)
			        {
				        // Cause the IP address to be rebroadcast
				        // through Announce.c or the RS232 port since
				        // we now have a new IP address
				        if(dwVal.Val != *(DWORD*)&AppConfig.MyIPAddr)
					        DHCPBindCount++;
					    
					    // Set the new address
			        	memcpy((void*)&AppConfig.MyIPAddr, (void*)&dwVal, sizeof(AppConfig.MyIPAddr));
			        }
			        else if(var == VAR_SUBNET_MASK)
			        	memcpy((void*)&AppConfig.MyMask, (void*)&dwVal, sizeof(AppConfig.MyMask));
			        else if(var == VAR_GATEWAY_ADDRESS)
			        	memcpy((void*)&AppConfig.MyGateway, (void*)&dwVal, sizeof(AppConfig.MyGateway));
		        }
	            break;
	
	        case VAR_DHCP:
	        	if(AppConfig.Flags.bIsDHCPEnabled)
	        	{
		        	if(!(argv[CurrentArg][0]-'0'))
		        	{
		        		AppConfig.Flags.bIsDHCPEnabled = FALSE;
		        	}
		        }
		        else
	        	{
		        	if(argv[CurrentArg][0]-'0')
		        	{
						AppConfig.MyIPAddr.Val = 0x00000000ul;
		        		AppConfig.Flags.bIsDHCPEnabled = TRUE;
				        AppConfig.Flags.bInConfigMode = TRUE;
			        	DHCPInit(0);
		        	}
		        }
	            break;
	    	}

			// Advance to the next variable (if present)
			CurrentArg++;	
        }
		
		// Save any changes to non-volatile memory
      	SaveAppConfig(&AppConfig);


		// Return the same CONFIG.CGI file as a result.
        memcpypgm2ram((void*)argv[0],
             (ROM void*)CONFIG_UPDATE_PAGE, CONFIG_UPDATE_PAGE_LEN);
		break;
#endif	// #if defined(ENABLE_REMOTE_CONFIG)

    default:
		memcpypgm2ram((void*)argv[0], (ROM void*)COMMANDS_OK_PAGE, COMMANDS_OK_PAGE_LEN);
        break;
    }

}
Esempio n. 23
0
    BYTE NVMInit( void )
    {
        BYTE    *memBlock;
        BYTE    result = 0;

        SPIUnselectEEPROM();

        CLRWDT();

        #ifdef ENABLE_DEBUG
            ConsolePutROMString((ROM char * const)"NVMInit started...\r\n");
        #endif

        #if defined(USE_EXTERNAL_NVM) && defined(STORE_MAC_EXTERNAL)
            result |= NVMalloc(sizeof (LONG_ADDR), &macLongAddrEE );
            #ifdef ZCP_DEBUG
                PutMACAddress(macLongAddrByte);
            #endif
        #endif

        #if defined(I_SUPPORT_BINDINGS)
            result |= NVMalloc( sizeof(WORD), &bindingValidityKey );
            result |= NVMalloc( sizeof(BINDING_RECORD) * MAX_BINDINGS, &apsBindingTable );
            result |= NVMalloc( BINDING_USAGE_MAP_SIZE, &bindingTableUsageMap );
            result |= NVMalloc( BINDING_USAGE_MAP_SIZE, &bindingTableSourceNodeMap );
        #endif

        #if defined(I_SUPPORT_GROUP_ADDRESSING)
            result |= NVMalloc( sizeof(APS_GROUP_RECORD) * MAX_GROUP, &apsGroupAddressTable);
        #endif

        result |= NVMalloc( sizeof(NEIGHBOR_TABLE_INFO), &neighborTableInfo );
        result |= NVMalloc( sizeof(NEIGHBOR_RECORD) * MAX_NEIGHBORS, &neighborTable );

        #if defined(I_SUPPORT_ROUTING) && !defined(USE_TREE_ROUTING_ONLY)
            result |= NVMalloc( sizeof(ROUTING_ENTRY) * ROUTING_TABLE_SIZE, &routingTable );
        #endif


        result |= NVMalloc( sizeof(NODE_DESCRIPTOR), &configNodeDescriptor );
        result |= NVMalloc( sizeof(NODE_POWER_DESCRIPTOR), &configPowerDescriptor );
        // NOTE - the simple descriptor for the ZDO has been removed in later specs, so the "+1" will go away.
        result |= NVMalloc( sizeof(NODE_SIMPLE_DESCRIPTOR) * (NUM_USER_ENDPOINTS+1), &configSimpleDescriptors );


        #if MAX_APS_ADDRESSES > 0
            result |= NVMalloc( sizeof(WORD), &apsAddressMapValidityKey );
            result |= NVMalloc( sizeof(APS_ADDRESS_MAP) * MAX_APS_ADDRESSES, &apsAddressMap );
        #endif

        #if defined(I_SUPPORT_SECURITY)
            result |= NVMalloc( sizeof(BYTE), &nwkActiveKeyNumber );
            result |= NVMalloc( sizeof(NETWORK_KEY_INFO) * NUM_NWK_KEYS, &networkKeyInfo );
            #if !(defined(I_AM_COORDINATOR) || defined(I_AM_TRUST_CENTER))
                result |= NVMalloc( sizeof(LONG_ADDR), &trustCenterLongAddr );
            #endif
        #endif

        if (!result)
        {
            #ifdef ENABLE_DEBUG
                ConsolePutROMString((ROM char * const)"Initializing EE...\r\n");
            #endif
            // If the MAC Address is stored externally, then the user is responsible
            // for programming it.  They may choose to preprogram the EEPROM, or program
            // it based on other input.  It should be programmed with the PutMACAddress() macro.


            // Initialize the trust center address
            #if defined(I_SUPPORT_SECURITY) && (defined(I_AM_COORDINATOR) || defined(I_AM_TRUST_CENTER))
                if ((memBlock = SRAMalloc( 8 )) == NULL)
                {
                    result = 1;
                }
                else
                {
                    int i = 0;
    
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE0;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE1;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE2;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE3;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE4;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE5;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE6;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE7;
    
                    NVMWrite( trustCenterLongAddr, memBlock, 8 );
                    SRAMfree( memBlock );
                }
            #endif

            // Initialize the descriptors using the ROM copy.
            if ((memBlock = SRAMalloc( sizeof(NODE_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                memcpypgm2ram( memBlock, (void *)&Config_Node_Descriptor, sizeof(NODE_DESCRIPTOR) );
                NVMWrite( configNodeDescriptor, memBlock, sizeof(NODE_DESCRIPTOR) );
                SRAMfree( memBlock );
            }

            if ((memBlock = SRAMalloc( sizeof(NODE_POWER_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                memcpypgm2ram( memBlock, (void *)&Config_Power_Descriptor, sizeof(NODE_POWER_DESCRIPTOR) );
                NVMWrite( configPowerDescriptor, memBlock, sizeof(NODE_POWER_DESCRIPTOR) );
                SRAMfree( memBlock );
            }

            if ((memBlock = SRAMalloc( sizeof(NODE_SIMPLE_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                // NOTE - Currently, a simple descriptor is needed for the ZDO endpoint.  When this requirement
                // goes away, take off the "+1".
                int     i;

                for (i=0; i<NUM_USER_ENDPOINTS+1; i++)
                {
                    memcpypgm2ram( memBlock, (void *)Config_Simple_Descriptors + i * sizeof(NODE_SIMPLE_DESCRIPTOR), sizeof(NODE_SIMPLE_DESCRIPTOR) );
                    NVMWrite( configSimpleDescriptors + (WORD)i * (WORD)sizeof(NODE_SIMPLE_DESCRIPTOR), memBlock, sizeof(NODE_SIMPLE_DESCRIPTOR) );
                }
                SRAMfree( memBlock );
            }
        }

        #ifdef ENABLE_DEBUG
            ConsolePutROMString((ROM char * const)"NVMInit complete.\r\n");
        #endif

        CLRWDT();

        return result;
    }
Esempio n. 24
0
/*********************************************************************
 * Function:        void InitAppConfig(void)
 *
 * PreCondition:    MPFSInit() is already called.
 *
 * Input:           None
 *
 * Output:          Write/Read non-volatile config variables.
 *
 * Side Effects:    None
 *
 * Overview:        None
 *
 * Note:            None
 ********************************************************************/
static void InitAppConfig(void) {
#if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS)
    //unsigned char vNeedToSaveDefaults = 0;
#endif

    while (1) {
        // Start out zeroing all AppConfig bytes to ensure all fields are
        // deterministic for checksum generation
        memset((void*) &AppConfig, 0x00, sizeof (AppConfig));

        AppConfig.Flags.bIsDHCPEnabled = TRUE;
        AppConfig.Flags.bInConfigMode = TRUE;
        memcpypgm2ram((void*) &AppConfig.MyMACAddr, (ROM void*) SerializedMACAddress, sizeof (AppConfig.MyMACAddr));
        //                            {
        //                                            _prog_addressT MACAddressAddress;
        //                                            MACAddressAddress.next = 0x157F8;
        //                                            _memcpy_p2d24((char*)&AppConfig.MyMACAddr, MACAddressAddress, sizeof(AppConfig.MyMACAddr));
        //                            }


        // SoftAP on certain setups with IP 192.168.1.1 has problem with DHCP client assigning new IP address on redirection.
        // 192.168.1.1 is a common IP address with most APs. This is still under investigation.
        // For now, assign this as 192.168.1.3
        //#if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)
            AppConfig.MyIPAddr.Val = 192ul | 168ul<<8ul | 1ul<<16ul | 3ul<<24ul;
            AppConfig.DefaultIPAddr.Val = AppConfig.MyIPAddr.Val;
            AppConfig.MyMask.Val = 255ul | 255ul<<8ul | 0ul<<16ul | 0ul<<24ul;
            AppConfig.DefaultMask.Val = AppConfig.MyMask.Val;
            AppConfig.MyGateway.Val = AppConfig.MyIPAddr.Val;
            AppConfig.PrimaryDNSServer.Val = AppConfig.MyIPAddr.Val;
            AppConfig.SecondaryDNSServer.Val = AppConfig.MyIPAddr.Val;

        //#else
         /*
        AppConfig.MyIPAddr.Val = MY_DEFAULT_IP_ADDR_BYTE1 | MY_DEFAULT_IP_ADDR_BYTE2 << 8ul | MY_DEFAULT_IP_ADDR_BYTE3 << 16ul | MY_DEFAULT_IP_ADDR_BYTE4 << 24ul;
        AppConfig.DefaultIPAddr.Val = AppConfig.MyIPAddr.Val;
        AppConfig.MyMask.Val = MY_DEFAULT_MASK_BYTE1 | MY_DEFAULT_MASK_BYTE2 << 8ul | MY_DEFAULT_MASK_BYTE3 << 16ul | MY_DEFAULT_MASK_BYTE4 << 24ul;
        AppConfig.DefaultMask.Val = AppConfig.MyMask.Val;
        AppConfig.MyGateway.Val = MY_DEFAULT_GATE_BYTE1 | MY_DEFAULT_GATE_BYTE2 << 8ul | MY_DEFAULT_GATE_BYTE3 << 16ul | MY_DEFAULT_GATE_BYTE4 << 24ul;
        AppConfig.PrimaryDNSServer.Val = MY_DEFAULT_PRIMARY_DNS_BYTE1 | MY_DEFAULT_PRIMARY_DNS_BYTE2 << 8ul | MY_DEFAULT_PRIMARY_DNS_BYTE3 << 16ul | MY_DEFAULT_PRIMARY_DNS_BYTE4 << 24ul;
        AppConfig.SecondaryDNSServer.Val = MY_DEFAULT_SECONDARY_DNS_BYTE1 | MY_DEFAULT_SECONDARY_DNS_BYTE2 << 8ul | MY_DEFAULT_SECONDARY_DNS_BYTE3 << 16ul | MY_DEFAULT_SECONDARY_DNS_BYTE4 << 24ul;
         * */
        //#endif
        // Load the default NetBIOS Host Name
        memcpypgm2ram(AppConfig.NetBIOSName, (ROM void*) MY_DEFAULT_HOST_NAME, 16);
        FormatNetBIOSName(AppConfig.NetBIOSName);

#if defined(WF_CS_TRIS)
        // Load the default SSID Name
        WF_ASSERT(sizeof (MY_DEFAULT_SSID_NAME) <= sizeof (AppConfig.MySSID));
        memcpypgm2ram(AppConfig.MySSID, (ROM void*) MY_DEFAULT_SSID_NAME, sizeof (MY_DEFAULT_SSID_NAME));
        AppConfig.SsidLength = sizeof (MY_DEFAULT_SSID_NAME) - 1;
        AppConfig.SecurityMode = MY_DEFAULT_WIFI_SECURITY_MODE;
        if (AppConfig.SecurityMode == WF_SECURITY_WEP_40) {
            AppConfig.WepKeyIndex = MY_DEFAULT_WEP_KEY_INDEX;
            memcpypgm2ram(AppConfig.SecurityKey, (ROM void*) MY_DEFAULT_WEP_KEYS_40, sizeof (MY_DEFAULT_WEP_KEYS_40) - 1);
            AppConfig.SecurityKeyLength = sizeof (MY_DEFAULT_WEP_KEYS_40) - 1;
        } else if (AppConfig.SecurityMode == WF_SECURITY_WEP_104) {
            AppConfig.WepKeyIndex = MY_DEFAULT_WEP_KEY_INDEX;
            memcpypgm2ram(AppConfig.SecurityKey, (ROM void*) MY_DEFAULT_WEP_KEYS_104, sizeof (MY_DEFAULT_WEP_KEYS_104) - 1);
            AppConfig.SecurityKeyLength = sizeof (MY_DEFAULT_WEP_KEYS_104) - 1;
        }
        AppConfig.networkType = MY_DEFAULT_NETWORK_TYPE;
        AppConfig.dataValid = 0;
#endif

        // Compute the checksum of the AppConfig defaults as loaded from ROM
        wOriginalAppConfigChecksum = CalcIPChecksum((BYTE*) & AppConfig, sizeof (AppConfig));
        /*
        #if defined(EEPROM_CS_TRIS)
                    NVM_VALIDATION_STRUCT NVMValidationStruct;

                    // Check to see if we have a flag set indicating that we need to
                    // save the ROM default AppConfig values.
                    if(vNeedToSaveDefaults)
                        SaveAppConfig(&AppConfig);

                    // Read the NVMValidation record and AppConfig struct out of EEPROM/Flash
                        XEEReadArray(0x0000, (BYTE*)&NVMValidationStruct, sizeof(NVMValidationStruct));
                        XEEReadArray(sizeof(NVMValidationStruct), (BYTE*)&AppConfig, sizeof(AppConfig));

                    // Check EEPROM/Flash validitity.  If it isn't valid, set a flag so
                    // that we will save the ROM default values on the next loop
                    // iteration.
                    if((NVMValidationStruct.wConfigurationLength != sizeof(AppConfig)) ||
                       (NVMValidationStruct.wOriginalChecksum != wOriginalAppConfigChecksum) ||
                       (NVMValidationStruct.wCurrentChecksum != CalcIPChecksum((BYTE*)&AppConfig, sizeof(AppConfig))))
                    {
                        // Check to ensure that the vNeedToSaveDefaults flag is zero,
                        // indicating that this is the first iteration through the do
                        // loop.  If we have already saved the defaults once and the
                        // EEPROM/Flash still doesn't pass the validity check, then it
                        // means we aren't successfully reading or writing to the
                        // EEPROM/Flash.  This means you have a hardware error and/or
                        // SPI configuration error.
                        if(vNeedToSaveDefaults)
                        {
                            while(1);
                        }

                        // Set flag and restart loop to load ROM defaults and save them
                        vNeedToSaveDefaults = 1;
                        continue;
                    }

                    // If we get down here, it means the EEPROM/Flash has valid contents
                    // and either matches the ROM defaults or previously matched and
                    // was run-time reconfigured by the user.  In this case, we shall
                    // use the contents loaded from EEPROM/Flash.
                    break;
        #endif
         */
        break;

    }


#if defined (EZ_CONFIG_STORE)
    // Set configuration for ZG from NVM
    /* Set security type and key if necessary, convert from app storage to ZG driver */

    if (AppConfig.dataValid)
        CFGCXT.isWifiDoneConfigure = 1;

    AppConfig.saveSecurityInfo = FALSE;
#endif // EZ_CONFIG_STORE

}
Esempio n. 25
0
/*********************************************************************
 * Function:        MPFS MPFSOpen(BYTE* file)
 *
 * PreCondition:    None
 *
 * Input:           file        - NULL terminated file name.
 *
 * Output:          A handle if file is found
 *                  MPFS_INVALID if file is not found.
 *
 * Side Effects:    None
 *
 * Overview:        None
 *
 * Note:            None
 ********************************************************************/
MPFS MPFSOpen(BYTE* file)
{
    MPFS_ENTRY entry;
    MPFS FAT;
    BYTE fileNameLen;

    if( mpfsFlags.bits.bNotAvailable )
        return MPFS_NOT_AVAILABLE;

#if defined(MPFS_USE_EEPROM) || defined(MPFS_USE_SPI_FLASH)
    FAT = MPFS_Start;
#else
    FAT = (MPFS)MPFS_Start;
#endif

    // If string is empty, do not attempt to find it in FAT.
    if ( *file == '\0' )
        return MPFS_INVALID;

    file = (BYTE*)strupr((char*)file);

    while(1)
    {
        // Bring current FAT entry into RAM.
		#if defined(MPFS_USE_EEPROM)
        	XEEReadArray(FAT, (unsigned char*)&entry, sizeof(entry));
		#else
			#if defined(__C30__)
	        	memcpypgm2ram(&entry, (ROM void*)(WORD)FAT, sizeof(entry));
			#else
	        	memcpypgm2ram(&entry, (ROM void*)FAT, sizeof(entry));
			#endif
		#endif

        // Make sure that it is a valid entry.
        if (entry.Flag == MPFS_DATA)
        {
            // Does the file name match ?
            fileNameLen = strlen((char*)file);
            if ( fileNameLen > MAX_FILE_NAME_LEN )
                fileNameLen = MAX_FILE_NAME_LEN;

            if( memcmp((void*)file, (void*)entry.Name, fileNameLen) == 0 )
            {
                _currentFile = (MPFS)entry.Address;
                mpfsOpenCount++;
                return entry.Address;
            }

            // File does not match.  Try next entry...
            FAT += sizeof(entry);
        }
        else if ( entry.Flag == MPFS_ETX )
        {
            if ( entry.Address != (MPFS)MPFS_INVALID )
                FAT = (MPFS)entry.Address;
            else
                break;
        }
	    else
	        return (MPFS)MPFS_INVALID;
    }
    return (MPFS)MPFS_INVALID;
}
Esempio n. 26
0
/*****************************************************************************
  Function:
    void PingDemo(void)

  Summary:
    Demonstrates use of the ICMP (Ping) client.

  Description:
    This function implements a simple ICMP client.  The function is called
    periodically by the stack, and it checks if BUTTON0 has been pressed.
    If the button is pressed, the function sends an ICMP Echo Request (Ping)
    to a Microchip web server.  The round trip time is displayed on the UART
    when the response is received.

    This function can be used as a model for applications requiring Ping
    capabilities to check if a host is reachable.

  Precondition:
    TCP is initialized.

  Parameters:
    None

  Returns:
    None
  ***************************************************************************/
void PingDemo(void)
{
    static enum
    {
        SM_HOME = 0,
        SM_GET_ICMP_RESPONSE
    } PingState = SM_HOME;
    static uint32_t Timer;
    int32_t ret;

    switch(PingState)
    {
        case SM_HOME:
            // Send a ping request out if the user pushes BUTTON0 (right-most one)
            if(BUTTON0_IO == 0u)
            {
                // Don't ping flood: wait at least 1 second between ping requests
                if(TickGet() - Timer > 1ul*TICK_SECOND)
                {
                    // Obtain ownership of the ICMP module
                    if(!ICMPBeginUsage())
                        break;

                    // Update anti-ping flood timer
                    Timer = TickGet();

                    // Send ICMP echo request
                    #if defined(STACK_USE_DNS)
                        ICMPSendPingToHostROM((ROM uint8_t*)HOST_TO_PING);
                    #else
                        ICMPSendPing(AppConfig.MyGateway.Val);
                    #endif
                    PingState = SM_GET_ICMP_RESPONSE;
                }
            }
            break;

        case SM_GET_ICMP_RESPONSE:
            // Get the status of the ICMP module
            ret = ICMPGetReply();
            if(ret == -2)
            {
                // Do nothing: still waiting for echo
                break;
            }
            else if(ret == -1)
            {
                // Request timed out
                #if defined(USE_LCD)
                memcpypgm2ram((void*)&LCDText[16], (ROM void *)"Ping timed out", 15);
                LCDUpdate();
                #endif
                PingState = SM_HOME;
            }
            else if(ret == -3)
            {
                // DNS address not resolvable
                #if defined(USE_LCD)
                memcpypgm2ram((void*)&LCDText[16], (ROM void *)"Can't resolve IP", 16);
                LCDUpdate();
                #endif
                PingState = SM_HOME;
            }
            else
            {
                // Echo received.  Time elapsed is stored in ret (Tick units).
                #if defined(USE_LCD)
                memcpypgm2ram((void*)&LCDText[16], (ROM void *)"Reply: ", 7);
                uitoa((uint16_t)TickConvertToMilliseconds((uint32_t)ret), &LCDText[16+7]);
                strcatpgm2ram((char*)&LCDText[16+7], "ms");
                LCDUpdate();
                #endif
                PingState = SM_HOME;
            }

            // Finished with the ICMP module, release it so other apps can begin using it
            ICMPEndUsage();
            break;
    }
}
Esempio n. 27
0
/*********************************************************************
 * Function:        BYTE MPFSGet(void)
 *
 * PreCondition:    MPFSOpen() != MPFS_INVALID &&
 *                  MPFSGetBegin() == TRUE
 *
 * Input:           None
 *
 * Output:          Data byte from current address.
 *
 * Side Effects:    None
 *
 * Overview:        Reads a byte from current address.
 *
 * Note:            Caller must call MPFSIsEOF() to check for end of
 *                  file condition
 ********************************************************************/
BYTE MPFSGet(void)
{
    BYTE t;
    
   #if defined(MPFS_USE_EEPROM)
      t = XEERead();
      _currentHandle++;
   #elif defined(MPFS_USE_SPI_FLASH)
      //SPIFlashReadArray(_currentHandle++, (BYTE*)&t, 1);  //orig
      SPIFlashReadArray(_currentHandle, (BYTE*)&t, 1);   //ccs workaround
      _currentHandle++; //ccs workaround
   #else
      #if defined(__C30__) && !defined(__PCD__) //__CCS__ change
         {
            DWORD_VAL i;
   
            // The uppermost byte, ((DWORD_VAL*)&_currentHandle)->v[3]), is the byte lane to read from.
            // 16 bit PICs have a 24 bit wide Flash program word.  Bytes 0-2 are the actual address, but 
            // odd addresses aren't implemented.
            i.Val = ReadProgramMemory(_currentHandle & 0x00FFFFFF);
            t = i.v[((DWORD_VAL*)&_currentHandle)->v[3]++];
            if(((DWORD_VAL*)&_currentHandle)->v[3] >= 3)
            {
               _currentHandle = (_currentHandle + 2) & 0x00FFFFFF;
            }
         }
      #else
          //t = (BYTE)*_currentHandle; //__ccs__ change because MPFS isn't rom pointer
          memcpypgm2ram(&t, _currentHandle, 1); //__ccs__ change because MPFS isn't rom pointer
          _currentHandle++;
      #endif
   #endif

    if(t == MPFS_DLE)
    {
      #if defined(MPFS_USE_EEPROM)
          t = XEERead();
          _currentHandle++;
      #elif defined(MPFS_USE_SPI_FLASH)
         //SPIFlashReadArray(_currentHandle++, (BYTE*)&t, 1); //orig
         SPIFlashReadArray(_currentHandle, (BYTE*)&t, 1);   //ccs workaround
         _currentHandle++; //ccs workaround
      #else
         #if defined(__C30__) && !defined(__PCD__) //__CCS__ change
            {
               DWORD_VAL i;
      
            // The uppermost byte, ((DWORD_VAL*)&_currentHandle)->v[3]), is the byte lane to read from.
            // 16 bit PICs have a 24 bit wide Flash program word.  Bytes 0-2 are the actual address, but 
            // odd addresses aren't implemented.
            i.Val = ReadProgramMemory(_currentHandle & 0x00FFFFFF);
            t = i.v[((DWORD_VAL*)&_currentHandle)->v[3]++];
            if(((DWORD_VAL*)&_currentHandle)->v[3] >= 3)
            {
               _currentHandle = (_currentHandle + 2) & 0x00FFFFFF;
            }
            }
         #else
             //t = (BYTE)*_currentHandle; //__ccs__ change because MPFS isn't rom pointer
             memcpypgm2ram(&t, _currentHandle, 1); //__ccs__ change because MPFS isn't rom pointer
             _currentHandle++;
         #endif
      #endif
    }
    else if(t == MPFS_ETX)
    {
        _currentHandle = MPFS_INVALID;
    }

   //printf(UserPutc, " ret=%X\r\n", t);
    return t;
}
Esempio n. 28
0
static void InitAppConfig(void)
{
#if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS)
	unsigned char vNeedToSaveDefaults = 0;
#endif
	
	while(1)
	{
		// Start out zeroing all AppConfig bytes to ensure all fields are 
		// deterministic for checksum generation
		memset((void*)&AppConfig, 0x00, sizeof(AppConfig));
		
		AppConfig.Flags.bIsDHCPEnabled = TRUE;
		AppConfig.Flags.bInConfigMode = TRUE;
		memcpypgm2ram((void*)&AppConfig.MyMACAddr, (ROM void*)SerializedMACAddress, sizeof(AppConfig.MyMACAddr));
//		{
//			_prog_addressT MACAddressAddress;
//			MACAddressAddress.next = 0x157F8;
//			_memcpy_p2d24((char*)&AppConfig.MyMACAddr, MACAddressAddress, sizeof(AppConfig.MyMACAddr));
//		}
		AppConfig.MyIPAddr.Val = MY_DEFAULT_IP_ADDR_BYTE1 | MY_DEFAULT_IP_ADDR_BYTE2<<8ul | MY_DEFAULT_IP_ADDR_BYTE3<<16ul | MY_DEFAULT_IP_ADDR_BYTE4<<24ul;
		AppConfig.DefaultIPAddr.Val = AppConfig.MyIPAddr.Val;
		AppConfig.MyMask.Val = MY_DEFAULT_MASK_BYTE1 | MY_DEFAULT_MASK_BYTE2<<8ul | MY_DEFAULT_MASK_BYTE3<<16ul | MY_DEFAULT_MASK_BYTE4<<24ul;
		AppConfig.DefaultMask.Val = AppConfig.MyMask.Val;
		AppConfig.MyGateway.Val = MY_DEFAULT_GATE_BYTE1 | MY_DEFAULT_GATE_BYTE2<<8ul | MY_DEFAULT_GATE_BYTE3<<16ul | MY_DEFAULT_GATE_BYTE4<<24ul;
		AppConfig.PrimaryDNSServer.Val = MY_DEFAULT_PRIMARY_DNS_BYTE1 | MY_DEFAULT_PRIMARY_DNS_BYTE2<<8ul  | MY_DEFAULT_PRIMARY_DNS_BYTE3<<16ul  | MY_DEFAULT_PRIMARY_DNS_BYTE4<<24ul;
		AppConfig.SecondaryDNSServer.Val = MY_DEFAULT_SECONDARY_DNS_BYTE1 | MY_DEFAULT_SECONDARY_DNS_BYTE2<<8ul  | MY_DEFAULT_SECONDARY_DNS_BYTE3<<16ul  | MY_DEFAULT_SECONDARY_DNS_BYTE4<<24ul;
	
	
		// SNMP Community String configuration
		#if defined(STACK_USE_SNMP_SERVER)
		{
			BYTE i;
			static ROM char * ROM cReadCommunities[] = SNMP_READ_COMMUNITIES;
			static ROM char * ROM cWriteCommunities[] = SNMP_WRITE_COMMUNITIES;
			ROM char * strCommunity;
			
			for(i = 0; i < SNMP_MAX_COMMUNITY_SUPPORT; i++)
			{
				// Get a pointer to the next community string
				strCommunity = cReadCommunities[i];
				if(i >= sizeof(cReadCommunities)/sizeof(cReadCommunities[0]))
					strCommunity = "";
	
				// Ensure we don't buffer overflow.  If your code gets stuck here, 
				// it means your SNMP_COMMUNITY_MAX_LEN definition in TCPIPConfig.h 
				// is either too small or one of your community string lengths 
				// (SNMP_READ_COMMUNITIES) are too large.  Fix either.
				if(strlenpgm(strCommunity) >= sizeof(AppConfig.readCommunity[0]))
					while(1);
				
				// Copy string into AppConfig
				strcpypgm2ram((char*)AppConfig.readCommunity[i], strCommunity);
	
				// Get a pointer to the next community string
				strCommunity = cWriteCommunities[i];
				if(i >= sizeof(cWriteCommunities)/sizeof(cWriteCommunities[0]))
					strCommunity = "";
	
				// Ensure we don't buffer overflow.  If your code gets stuck here, 
				// it means your SNMP_COMMUNITY_MAX_LEN definition in TCPIPConfig.h 
				// is either too small or one of your community string lengths 
				// (SNMP_WRITE_COMMUNITIES) are too large.  Fix either.
				if(strlenpgm(strCommunity) >= sizeof(AppConfig.writeCommunity[0]))
					while(1);
	
				// Copy string into AppConfig
				strcpypgm2ram((char*)AppConfig.writeCommunity[i], strCommunity);
			}
		}
		#endif
	
		// Load the default NetBIOS Host Name
		memcpypgm2ram(AppConfig.NetBIOSName, (ROM void*)MY_DEFAULT_HOST_NAME, 16);
		FormatNetBIOSName(AppConfig.NetBIOSName);
	
		#if defined(WF_CS_TRIS)
			// Load the default SSID Name
			WF_ASSERT(sizeof(MY_DEFAULT_SSID_NAME) <= sizeof(AppConfig.MySSID));
			memcpypgm2ram(AppConfig.MySSID, (ROM void*)MY_DEFAULT_SSID_NAME, sizeof(MY_DEFAULT_SSID_NAME));
			AppConfig.SsidLength = sizeof(MY_DEFAULT_SSID_NAME) - 1;
	        #if defined (EZ_CONFIG_STORE)
	        AppConfig.SecurityMode = MY_DEFAULT_WIFI_SECURITY_MODE;
	        AppConfig.networkType = MY_DEFAULT_NETWORK_TYPE;
	        AppConfig.dataValid = 0;
	        #endif // EZ_CONFIG_STORE
		#endif

		// Compute the checksum of the AppConfig defaults as loaded from ROM
		wOriginalAppConfigChecksum = CalcIPChecksum((BYTE*)&AppConfig, sizeof(AppConfig));

		#if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS)
		{
			NVM_VALIDATION_STRUCT NVMValidationStruct;

			// Check to see if we have a flag set indicating that we need to 
			// save the ROM default AppConfig values.
			if(vNeedToSaveDefaults)
				SaveAppConfig(&AppConfig);
		
			// Read the NVMValidation record and AppConfig struct out of EEPROM/Flash
			#if defined(EEPROM_CS_TRIS)
			{
				XEEReadArray(0x0000, (BYTE*)&NVMValidationStruct, sizeof(NVMValidationStruct));
				XEEReadArray(sizeof(NVMValidationStruct), (BYTE*)&AppConfig, sizeof(AppConfig));
			}
			#elif defined(SPIFLASH_CS_TRIS)
			{
				SPIFlashReadArray(0x0000, (BYTE*)&NVMValidationStruct, sizeof(NVMValidationStruct));
				SPIFlashReadArray(sizeof(NVMValidationStruct), (BYTE*)&AppConfig, sizeof(AppConfig));
			}
			#endif
	
			// Check EEPROM/Flash validitity.  If it isn't valid, set a flag so 
			// that we will save the ROM default values on the next loop 
			// iteration.
			if((NVMValidationStruct.wConfigurationLength != sizeof(AppConfig)) ||
			   (NVMValidationStruct.wOriginalChecksum != wOriginalAppConfigChecksum) ||
			   (NVMValidationStruct.wCurrentChecksum != CalcIPChecksum((BYTE*)&AppConfig, sizeof(AppConfig))))
			{
				// Check to ensure that the vNeedToSaveDefaults flag is zero, 
				// indicating that this is the first iteration through the do 
				// loop.  If we have already saved the defaults once and the 
				// EEPROM/Flash still doesn't pass the validity check, then it 
				// means we aren't successfully reading or writing to the 
				// EEPROM/Flash.  This means you have a hardware error and/or 
				// SPI configuration error.
				if(vNeedToSaveDefaults)
				{
					while(1);
				}
				
				// Set flag and restart loop to load ROM defaults and save them
				vNeedToSaveDefaults = 1;
				continue;
			}
			
			// If we get down here, it means the EEPROM/Flash has valid contents 
			// and either matches the ROM defaults or previously matched and 
			// was run-time reconfigured by the user.  In this case, we shall 
			// use the contents loaded from EEPROM/Flash.
			break;
		}
		#endif
		break;
	}
	WiFiInfo.CurrentConfigHasChanged = 1;

    #if defined (EZ_CONFIG_STORE)
    // Set configuration for ZG from NVM
    /* Set security type and key if necessary, convert from app storage to ZG driver */

    if (AppConfig.dataValid)
        CFGCXT.isWifiDoneConfigure = 1;

    AppConfig.saveSecurityInfo = FALSE;
    #endif // EZ_CONFIG_STORE
}
Esempio n. 29
0
/*****************************************************************************
  Function:
	WORD MPFSGetArray(MPFS_HANDLE hMPFS, BYTE* cData, WORD wLen)

  Description:
	Reads a series of bytes from a file.
	
  Precondition:
	The file handle referenced by hMPFS is already open.

  Parameters:
	hMPFS - the file handle from which to read
	cData - where to store the bytes that were read
	wLen - how many bytes to read

  Returns:
	The number of bytes successfully read.  If this is less than wLen, 
	an EOF occurred while attempting to read.
  ***************************************************************************/
WORD MPFSGetArray(MPFS_HANDLE hMPFS, BYTE* cData, WORD wLen)
{	
	// Make sure we're reading a valid address
	if(hMPFS > MAX_MPFS_HANDLES)
		return 0;
		
	// Determine how many we can actually read
	if(wLen > MPFSStubs[hMPFS].bytesRem)
		wLen = MPFSStubs[hMPFS].bytesRem;

	// Make sure we're reading a valid address
	if(MPFSStubs[hMPFS].addr == MPFS_INVALID || wLen == 0u)
		return 0;
		
	if(cData == NULL)
	{
		MPFSStubs[hMPFS].addr += wLen;
		MPFSStubs[hMPFS].bytesRem -= wLen;
		return wLen;
	}
	
	// Read the data
	#if defined(MPFS_USE_EEPROM)
		XEEReadArray(MPFSStubs[hMPFS].addr+MPFS_HEAD, cData, wLen);
		MPFSStubs[hMPFS].addr += wLen;
		MPFSStubs[hMPFS].bytesRem -= wLen;
		lastRead = MPFS_INVALID;
	#elif defined(MPFS_USE_SPI_FLASH)
		#if (GRAPHICS_PICTAIL_VERSION == 3)
			SST25ReadArray(MPFSStubs[hMPFS].addr+MPFS_HEAD, cData, wLen);
		#else
			xSemaphoreTake(QVGASemaphore, portMAX_DELAY);
			SST39PMPInit();
			SST39ReadArray(MPFSStubs[hMPFS].addr+MPFS_HEAD, cData, wLen);
			LCDPMPInit();
			xSemaphoreGive(QVGASemaphore);
		#endif
		MPFSStubs[hMPFS].addr += wLen;
		MPFSStubs[hMPFS].bytesRem -= wLen;
	#else
		#if defined(__C30__)
		{
			DWORD addr;
			DWORD_VAL read;
			WORD count;
			BYTE i;
	
			// MPFS Images are addressed by the byte; Program memory by the word.
			//
			// Flash program memory is 24 bits wide and only even words are
			// implemented.  The upper byte of the upper word is read as 0x00.
			// Address in program memory of any given byte is (MPFSAddr * 2) / 3
			//
			// We will read 24 bits at a time, but need to support using only 
			// fractions of the first and last byte.
			
			// Find the beginning address in program memory.
			addr = (MPFSStubs[hMPFS].addr / 3) << 1;
			
			// Find where to start in that first 3 bytes
			read.Val = (addr * 3) >> 1;
			if(read.Val == MPFSStubs[hMPFS].addr)
				i = 0;
			else if(read.Val+1 == MPFSStubs[hMPFS].addr)
				i = 1;
			else
				i = 2;
	
			// Add in the MPFS starting address offset
			addr += MPFS_HEAD;
			
			// Update the MPFS Handle
			MPFSStubs[hMPFS].addr += wLen;
			MPFSStubs[hMPFS].bytesRem -= wLen;
	
			// Read the first DWORD 
			read.Val = ReadProgramMemory(addr & 0x00FFFFFF);
			addr += 2;
	
			// Copy values as needed
			for(count = wLen; count > 0; cData++, count--)
			{
				// Copy the next value in
				*cData = read.v[i++];
				
				// Check if a new DWORD is needed
				if(i == 3 && count != 1)
				{// Read in a new DWORD
					read.Val = ReadProgramMemory(addr & 0x00FFFFFF);
					addr += 2;
					i = 0;
				}
			}
			
		}
		#else
		{
			DWORD dwHITECHWorkaround = MPFS_HEAD;
			memcpypgm2ram(cData, (ROM void*)(MPFSStubs[hMPFS].addr + dwHITECHWorkaround), wLen);
			MPFSStubs[hMPFS].addr += wLen;
			MPFSStubs[hMPFS].bytesRem -= wLen;
		}
		#endif
	#endif
	
	return wLen;
}
Esempio n. 30
0
    BYTE NVMInit( void )
    {
        BYTE    *memBlock;
        BYTE    result = 0;
        WORD NodeDescriptorValiditykey;
        WORD validitykey;

        SPIUnselectEEPROM();

        CLRWDT();

        #if defined(I_SUPPORT_BINDINGS)
            result |= NVMalloc( sizeof(WORD), &bindingValidityKey );
            result |= NVMalloc( sizeof(BINDING_RECORD) * MAX_BINDINGS, &apsBindingTable );
            result |= NVMalloc( BINDING_USAGE_MAP_SIZE, &bindingTableUsageMap );
            result |= NVMalloc( BINDING_USAGE_MAP_SIZE, &bindingTableSourceNodeMap );
        #endif

        #if defined(USE_EXTERNAL_NVM) && defined(STORE_MAC_EXTERNAL)
            result |= NVMalloc( sizeof(WORD), &macLongAddrValidityKey );
            result |= NVMalloc( sizeof(LONG_ADDR), &macLongAddrEE );

            GetMACAddressValidityKey(&validitykey);
            if (validitykey != MAC_ADDRESS_VALID)
            {
                PutMACAddress(macLongAddrByte);
                MACEnable();
            }

        #endif
        #if defined(I_SUPPORT_GROUP_ADDRESSING)
            result |= NVMalloc( sizeof(APS_GROUP_RECORD) * MAX_GROUP, &apsGroupAddressTable);
        #endif

        result |= NVMalloc( sizeof(NEIGHBOR_TABLE_INFO), &neighborTableInfo );
        result |= NVMalloc( sizeof(NEIGHBOR_RECORD) * MAX_NEIGHBORS, &neighborTable );

        #if defined(I_SUPPORT_ROUTING) && !defined(USE_TREE_ROUTING_ONLY)
            result |= NVMalloc( sizeof(ROUTING_ENTRY) * ROUTING_TABLE_SIZE, &routingTable );
        #endif

        result |= NVMalloc( sizeof(WORD), &nodeDescriptorValidityKey);
        result |= NVMalloc( sizeof(NODE_DESCRIPTOR), &configNodeDescriptor );
        result |= NVMalloc( sizeof(NODE_POWER_DESCRIPTOR), &configPowerDescriptor );
        // NOTE - the simple descriptor for the ZDO has been removed in later specs, so the "+1" will go away.
        result |= NVMalloc( sizeof(NODE_SIMPLE_DESCRIPTOR) * (NUM_USER_ENDPOINTS+1), &configSimpleDescriptors );

        result |= NVMalloc(sizeof(PERSISTENCE_PIB), &persistencePIB);

        #if MAX_APS_ADDRESSES > 0
            result |= NVMalloc( sizeof(WORD), &apsAddressMapValidityKey );
            result |= NVMalloc( sizeof(APS_ADDRESS_MAP) * MAX_APS_ADDRESSES, &apsAddressMap );
        #endif

        #if defined(I_SUPPORT_SECURITY)
            result |= NVMalloc( sizeof(BYTE), &nwkActiveKeyNumber );
            result |= NVMalloc( sizeof(NETWORK_KEY_INFO) * NUM_NWK_KEYS, &networkKeyInfo );
            /* location for outgoing nwk frame counters */
			result |= NVMalloc(( sizeof(DWORD_VAL)*2), &outgoingFrameCounterIndex);

        #endif
        #if I_SUPPORT_LINK_KEY == 1
                result |= NVMalloc( sizeof(APS_KEY_PAIR_DESCRIPTOR) * MAX_APPLICATION_LINK_KEY_SUPPORTED, &appLinkKeyTable );
        #endif

        #if I_SUPPORT_LINK_KEY == 1
            #if I_SUPPORT_MULTIPLE_TC_LINK_KEY == 1
                result |= NVMalloc( sizeof(TC_LINK_KEY_TABLE) * MAX_TC_LINK_KEY_SUPPORTED, &TCLinkKeyTable );
            #endif
        #endif

        #if defined(I_SUPPORT_COMMISSIONING)
            result |= NVMalloc( sizeof(BYTE), &activeSASIndex );
            result |= NVMalloc( sizeof(STARTUP_ATTRIBUTE_SET), &default_SAS );
            result |= NVMalloc( (sizeof(STARTUP_ATTRIBUTE_SET) * 2), &Commissioned_SAS );
        #endif

        #if defined(I_SUPPORT_SECURITY)
			result |= NVMalloc(( sizeof(DWORD_VAL)*2), &outgoingFrameCounterIndex);
		#endif

        if (!result)
        {
            #ifdef ENABLE_DEBUG
                ConsolePutROMString((ROM char * const)"Initializing EE...\r\n");
            #endif
            #ifdef I_SUPPORT_COMMISSIONING
                BYTE index;
            #endif
            // If the MAC Address is stored externally, then the user is responsible
            // for programming it.  They may choose to preprogram the EEPROM, or program
            // it based on other input.  It should be programmed with the PutMACAddress() macro.


  /*          // Initialize the trust center address
            //below is code is comment #if defined(I_SUPPORT_SECURITY) && (defined(I_AM_COORDINATOR) || defined(I_AM_TRUST_CENTER))
                if ((memBlock = SRAMalloc( 8 )) == NULL)
                {
                    result = 1;
                }
                else
                {
                    int i = 0;

                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[0];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[1];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[2];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[3];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[4];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[5];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[6];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[7];

                    NVMWrite( trustCenterLongAddr, memBlock, 8 );
                    SRAMfree( memBlock );
                }
            #endif*/
            GetNodeDescriptorValidity(&NodeDescriptorValiditykey);
            if (NodeDescriptorValiditykey != NODE_DESCRIPTOR_VALID)
            {
                // Initialize the descriptors using the ROM copy.
                if ((memBlock = SRAMalloc( sizeof(NODE_DESCRIPTOR) )) == NULL)
                {
                    result = 1;
                }
                else
                {
                    memcpy( memBlock, (void *)&Config_Node_Descriptor, sizeof(NODE_DESCRIPTOR) );
                    NVMWrite( configNodeDescriptor, memBlock, sizeof(NODE_DESCRIPTOR) );
                    SRAMfree( memBlock );
                    NodeDescriptorValiditykey = NODE_DESCRIPTOR_VALID;
                    PutNodeDescriptorValidity(&NodeDescriptorValiditykey);
                }
            }

            if ((memBlock = SRAMalloc( sizeof(NODE_POWER_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                memcpy( memBlock, (void *)&Config_Power_Descriptor, sizeof(NODE_POWER_DESCRIPTOR) );
                NVMWrite( configPowerDescriptor, memBlock, sizeof(NODE_POWER_DESCRIPTOR) );
                SRAMfree( memBlock );
            }

            if ((memBlock = SRAMalloc( sizeof(NODE_SIMPLE_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                // NOTE - Currently, a simple descriptor is needed for the ZDO endpoint.  When this requirement
                // goes away, take off the "+1".
                int     i;

                for (i=0; i<NUM_USER_ENDPOINTS+1; i++)
                {
					if(NOW_I_AM_A_ROUTER())
						memcpypgm2ram( memBlock, (void *)Config_Simple_Descriptors_MTR + i * sizeof(NODE_SIMPLE_DESCRIPTOR), sizeof(NODE_SIMPLE_DESCRIPTOR) );
					else if (NOW_I_AM_A_CORDINATOR())
						memcpypgm2ram( memBlock, (void *)Config_Simple_Descriptors_ESP + i * sizeof(NODE_SIMPLE_DESCRIPTOR), sizeof(NODE_SIMPLE_DESCRIPTOR) );
                    //memcpypgm2ram( memBlock, (void *)Config_Simple_Descriptors + i * sizeof(NODE_SIMPLE_DESCRIPTOR), sizeof(NODE_SIMPLE_DESCRIPTOR) );
                    NVMWrite( configSimpleDescriptors + (WORD)i * (WORD)sizeof(NODE_SIMPLE_DESCRIPTOR), memBlock, sizeof(NODE_SIMPLE_DESCRIPTOR) );
                }
                SRAMfree( memBlock );
            }
            #ifdef I_SUPPORT_COMMISSIONING
                GetSAS(&current_SAS,default_SAS);
		       if( MSDCL_Commission.ValidCleanStartUp == MSDCL_COMMISSION_DATA_VALID)
		       {
					memcpy(&current_SAS.spas.ExtendedPANId.v[0], &MSDCL_Commission.ExtendedPANId[0], sizeof(MSDCL_Commission.ExtendedPANId) );
			                       
				    current_SAS.spas.PreconfiguredLinkKey[15]= MSDCL_Commission.LinkKey[15];
				    current_SAS.spas.PreconfiguredLinkKey[14]= MSDCL_Commission.LinkKey[14];
				    current_SAS.spas.PreconfiguredLinkKey[13]= MSDCL_Commission.LinkKey[13];
				    current_SAS.spas.PreconfiguredLinkKey[12]= MSDCL_Commission.LinkKey[12];
				    current_SAS.spas.PreconfiguredLinkKey[11]= MSDCL_Commission.LinkKey[11];
				    current_SAS.spas.PreconfiguredLinkKey[10]= MSDCL_Commission.LinkKey[10];
				    current_SAS.spas.PreconfiguredLinkKey[9]= MSDCL_Commission.LinkKey[9];
				    current_SAS.spas.PreconfiguredLinkKey[8]= MSDCL_Commission.LinkKey[8];
				    current_SAS.spas.PreconfiguredLinkKey[7]= MSDCL_Commission.LinkKey[7];
				    current_SAS.spas.PreconfiguredLinkKey[6]= MSDCL_Commission.LinkKey[6];
				    current_SAS.spas.PreconfiguredLinkKey[5]= MSDCL_Commission.LinkKey[5];
				    current_SAS.spas.PreconfiguredLinkKey[4]= MSDCL_Commission.LinkKey[4];
				    current_SAS.spas.PreconfiguredLinkKey[3]= MSDCL_Commission.LinkKey[3];
				    current_SAS.spas.PreconfiguredLinkKey[2]= MSDCL_Commission.LinkKey[2];
				    current_SAS.spas.PreconfiguredLinkKey[1]= MSDCL_Commission.LinkKey[1];
				    current_SAS.spas.PreconfiguredLinkKey[0]= MSDCL_Commission.LinkKey[0];
			
				    current_SAS.spas.ChannelMask.Val = MSDCL_Commission.ChannelMask.Val & 0x07FFF800UL;
			
			   		current_SAS.spas.StartupControl = MSDCL_Commission.StartupStatus;
			    
			    	//PutNeighborTableInfo();
			    	//MSDCL_Commission.DoCleanStartUp = 0;
			    	//NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
				}

                if(current_SAS.validitykey != SAS_TABLE_VALID)
                {
                    Initdefault_SAS();
                    index = 0xFF;
                    PutActiveSASIndex(&index);
                }
            #endif
        }

        CLRWDT();

        return result;
    }