Esempio n. 1
0
//                                  MAIN
/////////////////////////////////////////////////////////////////////////////
int main(void)
{
    GOL_MSG msg;                        // GOL message structure to interact with GOL
   
    InitializeBoard();

#ifdef __PIC32MX__
    ImageDecoderInit();
    JPEGInit();                  // Initialize JPEG
#endif
    
    SetColor(WHITE);
    ClearDevice();

    GFX_SchemeInit();

    while(1)
    {
        if(GOLDraw())
        {                               // Draw GOL objects
            // Drawing is finished, we can now process new message
            TouchGetMsg(&msg);          // Get message from touch screen           
            GOLMsg(&msg);               // Process message
        }   	
    }
}
Esempio n. 2
0
int main(void)
{
	BYTE i; 
    GOL_MSG msg;                    // GOL message structure to interact with GOL
    
    InitializeBoard();
    
	TRISGbits.TRISG3 = 1;
	TRISGbits.TRISG2 = 0;
	Nop();
	PORTGbits.RG2 = 1;
	Nop();
	
	//RADIO SETUP
	// Function MiApp_ProtocolInit initialize the protocol stack.//
 	MiApp_ProtocolInit(FALSE);
	
	//setting the frequency at whick this wx will transmit over comes back as false if the set channel fails 
	if( MiApp_SetChannel(myChannel) == FALSE )
	{
            return 0;
    }

	//Enables all connection types
 	MiApp_ConnectionMode(ENABLE_ALL_CONN);

	//try to establish connection with peer device: p1=0xff=establish connection with any device, p2=direct connection
	//returns 0xFF if it false 
	i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT);

	if( i == 0xFF )
   	{
		//starting a connecton: direct connect, duration of scan, channel to start connection on	
		MiApp_StartConnection(START_CONN_DIRECT, 10, 24);
	}
	//END RADIO SETUP
	
    LED = 1;
//	i2cRec(2);
	
    while(1)
    {	//i2cSend(3,2);
        if(GOLDraw())               // Draw GOL object
        {
            TouchGetMsg(&msg);      // Get message from touch screen
            GOLMsg(&msg);           // Process message
        }
        
        /* MiApp_MessageAvailable returns a bool*/
		if( MiApp_MessageAvailable() )
        {
			Incoming=*rxMessage.Payload;
			/* Function MiApp_DiscardMessage is used to release the current received packet.*/
           	MiApp_DiscardMessage();
		}
	}//end while
}
Esempio n. 3
0
int UNIFLoad(const char *name, FCEUFILE *fp)
{
	FCEU_fseek(fp,0,SEEK_SET);
	FCEU_fread(&unhead,1,4,fp);
	if(memcmp(&unhead,"UNIF",4))
		return 0;

	ResetCartMapping();

	ResetExState(0,0);
	ResetUNIF();
	if(!FCEU_read32le(&unhead.info,fp))
		goto aborto;
	if(FCEU_fseek(fp,0x20,SEEK_SET)<0)
		goto aborto;
	if(!LoadUNIFChunks(fp))
		goto aborto;
	{
		int x;
		struct md5_context md5;

		md5_starts(&md5);

		for(x=0;x<32;x++)
			if(malloced[x])
			{
				md5_update(&md5,malloced[x],mallocedsizes[x]);
			}
			md5_finish(&md5,UNIFCart.MD5);
			FCEU_printf(" ROM MD5:  0x");
			for(x=0;x<16;x++)
				FCEU_printf("%02x",UNIFCart.MD5[x]);
			FCEU_printf("\n");
			memcpy(&GameInfo->MD5,&UNIFCart.MD5,sizeof(UNIFCart.MD5));
	}

	if(!InitializeBoard())
		goto aborto;

	#if !defined(GEKKO)|| !defined(_XBOX)
	FCEU_LoadGameSave(&UNIFCart);
	#endif

	strcpy(LoadedRomFName,name); //For the debugger list
	GameInterface=UNIFGI;
	return 1;

aborto:

	FreeUNIF();
	ResetUNIF();


	return 0;
}
Esempio n. 4
0
/****************************************************************************
  Function:
    void ChipKITEthernetBegin(const BYTE *rgbMac, const BYTE *rgbIP, const BYTE *rgbGateWay, const BYTE *rgbSubNet, const BYTE *rgbDNS1, const BYTE *rgbDNS2)

  Description:
    This routine impements the Arduino Ethernet.Begin Method. This initializes the
	board, start supporting tasks, builds a default application configuration data structure,
	overrides the configuration structure if static IPs or assigned MACs are specified,
	and starts the Ethernet stack.

  Precondition:
    None

  Parameters:
    rgbMac 	- If all 6 bytes are zero, than use the internal MCU programed MAC address
			as defined by Microchip. It will be a unique MAC address in the Microchip range. 
			The range will be somewhere starting with 00:04:A3:XX:XX:XX

			If non-zero, the specified MAC address will be used.

	rgbIP 	-	If all 4 bytes are zero, then DHCP is used and rest of the parameters are ignored

			If an IP is specified then DHCP is not used and the IP represents a static IP address to use. The 
			remainng parameters have value.

	rgbGateWay 	- 4 bytes IP address of the gateway to use. Only valid if rgbIP is specified
	rgbSubNet	- 4 byte mask representing the subnet mask.Only valid if rgbIP is specified
	rgbDNS1		- 4 byte IP address of the primary DNS server. Only valid if rgbIP is specified. This value may be 0s if not required
	rgbDNS2		- 4 byte IP address of the secondary DNS server. Only valid if rgbIP is specifed. This value may be 0s if not required

  Returns:

    None

  Remarks:
    None
  ***************************************************************************/
void ChipKITEthernetBegin(const BYTE *rgbMac, const BYTE *rgbIP, const BYTE *rgbGateWay, const BYTE *rgbSubNet, const BYTE *rgbDNS1, const BYTE *rgbDNS2)
{
	DWORD t = 0;
	const DWORD tDHCPTimeout = 30 * TICK_SECOND;

	// Initialize application specific hardware
	InitializeBoard();

	// Initialize stack-related hardware components that may be 
	// required by the UART configuration routines
    TickInit();

	// Initialize Stack and application related NV variables into AppConfig.
	InitAppConfig();

	// see if we have something other than to use our MAC address
	if((rgbMac[0] | rgbMac[1] | rgbMac[2] | rgbMac[3] | rgbMac[4] | rgbMac[5]) != 0)
	{
		memcpy(&AppConfig.MyMACAddr, rgbMac, 6);
	}

	// if we are not to use DHCP; fill in what came in.
	if((rgbIP[0] | rgbIP[1] | rgbIP[2] | rgbIP[3]) != 0)
	{
		AppConfig.Flags.bIsDHCPEnabled = FALSE;		// don't use dhcp
		memcpy(&AppConfig.MyIPAddr, rgbIP, 4);
		memcpy(&AppConfig.MyGateway, rgbGateWay, 4);
		memcpy(&AppConfig.MyMask,rgbSubNet, 4);
		memcpy(&AppConfig.PrimaryDNSServer, rgbDNS1, 4);
		memcpy(&AppConfig.SecondaryDNSServer, rgbDNS2, 4);
		
		AppConfig.DefaultIPAddr = AppConfig.MyIPAddr;
		AppConfig.DefaultMask = AppConfig.MyMask;
	}


	// make sure our static array is zeroed out.
	memset(rgUDPSocketBuffers, 0, sizeof(rgUDPSocketBuffers));

	// Initialize core stack layers (MAC, ARP, TCP, UDP) and
	// application modules (HTTP, SNMP, etc.)
    StackInit();

	// arp will not work right until DHCP finishes
	// if DHCP won't configure after the timeout; then just go with it
	// maybe later it will configure, but until then, things might not work right.
	t = TickGet();
	while(AppConfig.Flags.bIsDHCPEnabled && !DHCPIsBound(0) && ((TickGet() - t) < tDHCPTimeout))
	{
		ChipKITPeriodicTasks();
	}
}
Esempio n. 5
0
int UNIFLoad(const char *name, int fp)
{
        FCEU_fseek(fp,0,SEEK_SET);
        FCEU_fread(&unhead,1,4,fp);
        if(memcmp(&unhead,"UNIF",4))
         return 0;

	ResetCartMapping();

        ResetExState(0,0);
        ResetUNIF();
        if(!FCEU_read32(&unhead.info,fp))
	 goto aborto;
        if(FCEU_fseek(fp,0x20,SEEK_SET)<0)
	 goto aborto;
        if(!LoadUNIFChunks(fp))
	 goto aborto;
	{
	 int x;
	 struct md5_context md5;

	 md5_starts(&md5);

	 for(x=0;x<32;x++)
	  if(malloced[x])
	  {
	   md5_update(&md5,malloced[x],mallocedsizes[x]);
	  }
	  md5_finish(&md5,UNIFCart.MD5);
          FCEU_printf(" ROM MD5:  0x");
          for(x=0;x<16;x++)
           FCEU_printf("%02x",UNIFCart.MD5[x]);
          FCEU_printf("\n");
	  memcpy(FCEUGameInfo.MD5,UNIFCart.MD5,sizeof(UNIFCart.MD5));
	}

        if(!InitializeBoard())
	 goto aborto;

	FCEU_LoadGameSave(&UNIFCart);
        GameInterface=UNIFGI;
        return 1;

	aborto:

	FreeUNIF();
	ResetUNIF();


	return 0;
}
/*==============================================================================
* Exosite_Init
*
* Initializes peripherals required for communications
*=============================================================================*/
char 
Exosite_Init(void)
{
	//Initialize board-specific peripherals
	InitializeBoard();

  // Setup the UI for eye candy and debug output
	InitializeUI();
  
  // Enable processor interrupts.
  IntMasterEnable();
  
  return 1; 
}
Esempio n. 7
0
int CopyFamiLoad() {
	ResetCartMapping();
	ResetExState(0, 0);

	sboardname = "COPYFAMI";
	if (!InitializeBoard())
		goto aborto;

	FCEU_LoadGameSave(&UNIFCart);
	GameInterface = UNIFGI;
	return 1;

 aborto:

	FreeUNIF();
	ResetUNIF();
	return 0;
}
Esempio n. 8
0
bool Game::InitializeGameObjects() {
    
    if (InitializeSFML() == false) {
        return false;
    }
    if (InitializeBoard() == false) {
        return false;
    }
    if (InitializeTargets() == false) {
        return false;
    }
    if (InitializePaddle() == false) {
        return false;
    }
    if (InitializeBall() == false) {
        return false;
    }
    
    return true;
    
}
Esempio n. 9
0
int main()
{
	// declare variables
	char board[ROWS][COLS];

	// initialize board
	InitializeBoard(board);

	// populate the board with moves
	PlayerMove( 1,  1, board, MARKONE );
	PlayerMove( 1,  2, board, MARKONE );
	PlayerMove( 4,  3, board, MARKONE );
	PlayerMove( 1,  1, board, MARKTWO );
	PlayerMove( 6,  2, board, MARKTWO );
	PlayerMove( 4, 12, board, MARKTWO );

	// display the board
	DisplayBoard(board);

	// exit program
	return 0;
}
Esempio n. 10
0
int main()
{
    char board[ROWS][COLS];
    int status;
    char marks[2] = { MARKONE, MARKTWO };

    InitializeBoard(board);

    status = 1;

    while ( status == 1 ) {
        if ( status = turn(board, marks[0], 0) ) {
            status = turn(board, marks[1], 0);
        }
    }

    if ( !run_again_query() ) {
        return 0;
    }

    main();
}
Esempio n. 11
0
int main()
{
	while (true) {
		//initialize
		Randomize();
		Set<string> wordsSeen;
		Lexicon lex("lexicon.dat");
		Grid<string> board(4,4);			//changes for 5x5
		SetWindowSize(9, 5);
		InitGraphics();
		DrawBoard(4,4);						//changes for 5x5
		Welcome();
		GiveInstructions();
		
		//either set up the board automatically or let the user set it up
		cout << "Would you like to configure the board? ";
		string response = GetLine();
		response = ConvertToUpperCase(response);
		if (response == "YES") {
			UserConfigureBoard(board);
		} else {
			InitializeBoard(board);
		}
		
		//have the player play, then the computer
		PlayerTurn(board, lex, wordsSeen);
		ComputerTurn(board, lex, wordsSeen);
		
		//check if the user wants to play again
		cout << "Would you like to play again? ";
		response = GetLine();
		response = ConvertToUpperCase(response);
		if (response != "YES") break;
	}
	return 0;
}
Esempio n. 12
0
int main(void)
#endif
{
	static DWORD t = 0;
	static DWORD dwLastIP = 0;

	// Initialize application specific hardware
	InitializeBoard();

	#if defined(USE_LCD)
	// Initialize and display the stack version on the LCD
	LCDInit();
	DelayMs(100);
	strcpypgm2ram((char*)LCDText, "WebVend Demo App"
								  "                ");
	LCDUpdate();
	#endif

	// Initialize stack-related hardware components that may be 
	// required by the UART configuration routines
    TickInit();
	#if defined(STACK_USE_MPFS2)
	MPFSInit();
	#endif

	// Initialize Stack and application related NV variables into AppConfig.
	InitAppConfig();

    // Initiates board setup process if button is depressed 
	// on startup
    if(BUTTON0_IO == 0u)
    {
		#if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS)
		// Invalidate the EEPROM contents if BUTTON0 is held down for more than 4 seconds
		DWORD StartTime = TickGet();
		LED_PUT(0x00);
				
		while(BUTTON0_IO == 0u)
		{
			if(TickGet() - StartTime > 4*TICK_SECOND)
			{
				#if defined(EEPROM_CS_TRIS)
			    XEEBeginWrite(0x0000);
			    XEEWrite(0xFF);
			    XEEWrite(0xFF);
			    XEEEndWrite();
			    #elif defined(SPIFLASH_CS_TRIS)
			    SPIFlashBeginWrite(0x0000);
			    SPIFlashWrite(0xFF);
			    SPIFlashWrite(0xFF);
			    #endif
			    
				#if defined(STACK_USE_UART)
				putrsUART("\r\n\r\nBUTTON0 held for more than 4 seconds.  Default settings restored.\r\n\r\n");
				#endif

				LED_PUT(0x0F);
				while((LONG)(TickGet() - StartTime) <= (LONG)(9*TICK_SECOND/2));
				LED_PUT(0x00);
				while(BUTTON0_IO == 0u);
				Reset();
				break;
			}
		}
		#endif
    }

	// Initialize core stack layers (MAC, ARP, TCP, UDP) and
	// application modules (HTTP, SNMP, etc.)
    StackInit();

    #if defined(WF_CS_TRIS)
    WF_Connect();
    #endif

	// Initialize any application-specific modules or functions/
	// For this demo application, this only includes the
	// UART 2 TCP Bridge
	#if defined(STACK_USE_UART2TCP_BRIDGE)
	UART2TCPBridgeInit();
	#endif

	#if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
    ZeroconfLLInitialize();
	#endif

	#if defined(STACK_USE_ZEROCONF_MDNS_SD)
	mDNSInitialize(MY_DEFAULT_HOST_NAME);
	mDNSServiceRegister(
		(const char *) "DemoWebServer",	// base name of the service
		"_http._tcp.local",			    // type of the service
		80,				                // TCP or UDP port, at which this service is available
		((const BYTE *)"path=/index.htm"),	// TXT info
		1,								    // auto rename the service when if needed
		NULL,							    // no callback function
		NULL							    // no application context
		);

    mDNSMulticastFilterRegister();			
	#endif

	// Now that all items are initialized, begin the co-operative
	// multitasking loop.  This infinite loop will continuously 
	// execute all stack-related tasks, as well as your own
	// application's functions.  Custom functions should be added
	// at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.
    while(1)
    {
        // Blink LED0 (right most one) every second.
        if(TickGet() - t >= TICK_SECOND/2ul)
        {
            t = TickGet();
            LED0_IO ^= 1;
        }

        // This task performs normal stack task including checking
        // for incoming packet, type of packet and calling
        // appropriate stack entity to process it.
        StackTask();

        // This tasks invokes each of the core stack application tasks
        StackApplications();

        #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
		ZeroconfLLProcess();
        #endif

        #if defined(STACK_USE_ZEROCONF_MDNS_SD)
        mDNSProcess();
		// Use this function to exercise service update function
		// HTTPUpdateRecord();
        #endif

		// Process application specific tasks here.
		// For this demo app, this will include the Generic TCP 
		// client and servers, and the SNMP, Ping, and SNMP Trap
		// demos.  Following that, we will process any IO from
		// the inputs on the board itself.
		// Any custom modules or processing you need to do should
		// go here.

		ProcessIO();

        // If the local IP address has changed (ex: due to DHCP lease change)
        // write the new IP address to the LCD display, UART, and Announce 
        // service
		if(dwLastIP != AppConfig.MyIPAddr.Val)
		{
			dwLastIP = AppConfig.MyIPAddr.Val;
			
			#if defined(STACK_USE_UART)
				putrsUART((ROM char*)"\r\nNew IP Address: ");
			#endif

			// If not vending, show the new IP
			if(smVend == SM_IDLE || smVend == SM_DISPLAY_WAIT)
			{
				memcpypgm2ram(LCDText, "WebVend Demo App", 16);
        	    DisplayIPValue(AppConfig.MyIPAddr);	// Print to UART

				#if defined(STACK_USE_UART)
					putrsUART((ROM char*)"\r\n");
				#endif

        	    displayTimeout = TickGet() + 2*TICK_SECOND;
        	    smVend = SM_DISPLAY_WAIT;
        	}

			#if defined(STACK_USE_ANNOUNCE)
				AnnounceIP();
			#endif

            #if defined(STACK_USE_ZEROCONF_MDNS_SD)
				mDNSFillHostRecord();
			#endif
		}
	}
}
Esempio n. 13
0
int main(void)
{
	static DWORD per_sec = 0;
	InitializeBoard();													// Initialize application specific hardware
	PowerONGSM(TRUE);
	Initialization();		

	//................File System Initialisation...................//
	
	while(disk_status(MMC_DRIVE));     //Wait untill SD card is inserted											
	if(!(disk_status(MMC_DRIVE) ))//& STA_NODISK))					//if SD card is inserted	
	{
		// disk inserted so initialise it
		if (disk_initialize(MMC_DRIVE) == 0) 							//if SD card initialize
		{
			if (f_mount(MMC_DRIVE, &fatfs[MMC_DRIVE]) == FR_OK) 
			{
				uc_Flag_SDInit = TRUE;	  //succefully initialise sd card							//if file system initialize properly
			}
			else
			{
				Reset();
			}
		}
		else
		{
			Reset();
		}
	}
	InitConnection();														//functional initialization gateway device sensors,etc	
	while(1)
	{
		ClrWdt();
		if(ReadADC==TRUE)
		{
			Sample_Flag++;
			ReadADC=FALSE;
			ADC_Read_Value=AnalogData*3.3/1024;
			Toatal_Value=Toatal_Value+ADC_Read_Value;
			if(ADC_Read_Value<min)
			{
				min=ADC_Read_Value;
			}
			else if(ADC_Read_Value>max)
			{
				max=ADC_Read_Value;
			}
			
		}
		if((Sample_Flag>=600) && (uc_HTTP_DONE==TRUE))
		{
			heartbeat++;
			value=Toatal_Value/Sample_Flag;
			if(uc_GPRS_Done==FALSE)
			{
				GPRSFailed++;
			}
			uc_GPRS_Done=FALSE;
		
			Sample_Flag=0;
			min=0;
			max=0;
			Toatal_Value=0;
			sendData=TRUE;
			POST_DATA=SEND_DATA;
			uc_HTTP_DONE=FALSE;	
		}
		if(sendData==TRUE)
		{
		
			switch(POST_DATA)
			{
				case GATE_HEARTBEAT:
				{
					if(url_build==FALSE)
					{
						Transmit_Gateway_Heartbeat();
						url_build=TRUE;
						uc_GPRS_Done=FALSE;
					}	
					SendURL((METHOD) POST);	
					if(uc_GPRS_Done==TRUE)
					{
						POST_DATA=SENS_HEARTBEAT;
						url_build=FALSE;
					}
					break;
				}
				
				case SENS_HEARTBEAT:
				{
					if(url_build==FALSE)
					{
						Transmit_Sensor_Heartbeat();
						url_build=TRUE;
						uc_GPRS_Done=FALSE;
					}	
					SendURL((METHOD) POST);	
					if(uc_GPRS_Done==TRUE)
					{
						url_build=FALSE;
						sendData=FALSE;
						uc_HTTP_DONE=TRUE;
						POST_DATA=10;
					}
					break;
				}
				case SEND_DATA:
				{
					if(url_build==FALSE)
					{
						Transmit_Analog_Data(value);
						url_build=TRUE;
						uc_GPRS_Done=FALSE;
						
						//	GetTimeStamp();
						//time=t_day;
					}	
					SendURL((METHOD)POST);	
					if(uc_GPRS_Done==TRUE)
					{
						if(heartbeat>=5)
						{
							heartbeat=0;
							POST_DATA=GATE_HEARTBEAT;
							url_build=FALSE;
						}
						else
						{
							POST_DATA=10;
							url_build=FALSE;
							sendData=FALSE;
							uc_HTTP_DONE=TRUE;
							//	GetTimeStamp();
							//time1=t_day;
							asm("NOP");
						}
					
					}
					break;
				}
				default:
				break;
			}
		}
		if(TickGet() - per_sec >= TICK_SECOND/2ul)								// Blink LED0 (right most one) every half second.
		{
			per_sec = TickGet();
			LED4_IO ^= 1;													//internal heartbit LED
			HRTBIT_LED_IO ^=1; 											//pannel heartbit LED
	
		}
		if((uc_GSMRestart==TRUE) || ((uc_GPRSFailed == TRUE) && (uc_GPRSTried == TRUE)))
		{
			PowerONGSM(FALSE);
			DelayMs(200);
			uc_GSMRestart=3;	
			PowerONGSM(TRUE);
			uc_GPRSFailed=FALSE;
			uc_GPRSTried=FALSE;
		}
	}
}
Esempio n. 14
0
int main(void)
#endif
{
    BYTE i;
    static DWORD t = 0;
    static DWORD dwLastIP = 0;
    static UINT8 updateDisplay = 0;

#if defined (EZ_CONFIG_STORE)
    static DWORD ButtonPushStart = 0;
#endif

#if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)
    UINT8 channelList[] = MY_DEFAULT_CHANNEL_LIST_PRESCAN; // WF_PRESCAN
    tWFScanResult bssDesc;
#endif

    // Initialize application specific hardware
    InitializeBoard();

    // Initiates board setup process if button is depressed
    // on startup
    if (BUTTON1_IO == 0u) {
        while (BUTTON1_IO == 0);
        SelfTestMode();
    }

    //#if defined(USE_LCD)



    /*******************************************************************/
    // Initialize the LCD
    /*******************************************************************/

    ConfigureLCD_SPI();

    LCDInit();

    /*******************************************************************/
    // Display Start-up Splash Screen
    /*******************************************************************/
    LCDBacklightON();
    LEDS_ON();
    LCDErase();
    sprintf((char *) LCDText, (char*) "  MiWi - WiFi  ");
    sprintf((char *) &(LCDText[16]), (char*) " Gateway  Demo");
    LCDUpdate();





    /*******************************************************************/
    // Initialize the MiWi Protocol Stack. The only input parameter indicates
    // if previous network configuration should be restored.
    /*******************************************************************/
    MiApp_ProtocolInit(FALSE);

    /*******************************************************************/
    // Set Device Communication Channel
    /*******************************************************************/
    if (MiApp_SetChannel(myChannel) == FALSE) {
        LCDDisplay((char *) "ERROR: Unable to Set Channel..", 0, TRUE);
        while (1);
    }

    /*******************************************************************/
    //  Set 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);

    /*******************************************************************/
    // 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.
    /*******************************************************************/
    i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT);

    /*******************************************************************/
    // Display current opertion on LCD of demo board, if applicable
    /*******************************************************************/
    if (i != 0xFF) {
        ; // Connected Peer on Channel
    } else {
        /*******************************************************************/
        // If no network can be found and join, we need to start a new
        // network by calling function MiApp_StartConnection
        //
        // 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_DIRECT, 10, 0);
    }

    // Turn OFF LCD after setting up MiWi Connection
    LCDBacklightOFF();

    // Initialize stack-related hardware components that may be
    // required by the UART configuration routines
    TickInit();
#if defined(STACK_USE_MPFS2)
    MPFSInit();
#endif

    // Initialize Stack and application related NV variables into AppConfig.
    InitAppConfig();
    dwLastIP = AppConfig.MyIPAddr.Val;
    // Initialize core stack layers (MAC, ARP, TCP, UDP) and
    // application modules (HTTP, SNMP, etc.)
    StackInit();

#if defined ( EZ_CONFIG_SCAN )
    WFInitScan();
#endif

#if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)
    // WF_PRESCAN: Pre-scan before starting up as SoftAP mode  
    WF_CASetScanType(MY_DEFAULT_SCAN_TYPE);
    WF_CASetChannelList(channelList, sizeof (channelList));

    if (WFStartScan() == WF_SUCCESS) {
        SCAN_SET_DISPLAY(SCANCXT.scanState);
        SCANCXT.displayIdx = 0;
        //putsUART("main: Prescan WFStartScan() success ................. \r\n");
    }

    // Needed to trigger g_scan_done		
    WFRetrieveScanResult(0, &bssDesc);
#else

#if defined(WF_CS_TRIS)
    WF_Connect();
#endif // defined(WF_CS_TRIS)

#endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)

    // Initialize any application-specific modules or functions/
    // For this demo application, this only includes the
    // UART 2 TCP Bridge
#if defined(STACK_USE_UART2TCP_BRIDGE)
    UART2TCPBridgeInit();
#endif

#if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
    ZeroconfLLInitialize();
#endif

#if defined(STACK_USE_ZEROCONF_MDNS_SD)
    mDNSInitialize(MY_DEFAULT_HOST_NAME);
    mDNSServiceRegister(
            (const char *) AppConfig.NetBIOSName, // base name of the service
            "_http._tcp.local", // type of the service
            80, // TCP or UDP port, at which this service is available
            ((const BYTE *) "path=/index.htm"), // TXT info
            1, // auto rename the service when if needed
            NULL, // no callback function
            NULL // no application context
            );

    mDNSMulticastFilterRegister();
#endif

#if defined(WF_CONSOLE)
    WFConsoleInit();
#endif

    // Now that all items are initialized, begin the co-operative
    // multitasking loop.  This infinite loop will continuously
    // execute all stack-related tasks, as well as your own
    // application's functions.  Custom functions should be added
    // at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.

    LEDS_OFF();

    while (1) {

        /*******************************************************************/
        // Check Button Events
        /*******************************************************************/
        if (BUTTON1_IO == 0u) {
            while (BUTTON1_IO == 0);
            LCDErase();
            sprintf((char *) LCDText, (char*) "Erase Room Info?");
            sprintf((char *) &(LCDText[16]), (char*) "SW0:Yes  SW2:No");
            LCDUpdate();

            while (1) {
                if (BUTTON1_IO == 0u) {
                    while (BUTTON1_IO == 0);
                    LCDDisplay((char *) "STATUS: Erasing...", 0, TRUE);
                    EraseRoomInfo();
                    DisplaySSID();
                    break;
                } else if (BUTTON2_IO == 0u) {
                    while (BUTTON2_IO == 0);
                    DisplaySSID();
                    break;
                }


            }
        }

        // Blink LED0 twice per sec when unconfigured, once per sec after config
        if ((TickGet() - t >= TICK_SECOND / (4ul - (CFGCXT.isWifiDoneConfigure * 2ul)))) {
            t = TickGet();
            LED0_INV();
        }

        if(CFGCXT.isWifiNeedToConfigure) updateDisplay = 1;
        

        #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)
                if (g_scan_done) {
                    if (g_prescan_waiting) {
                        SCANCXT.displayIdx = 0;
                        while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) {
                            WFDisplayScanMgr();
                        }


        #if defined(WF_CS_TRIS)
                        WF_Connect();
        #endif
                        DisplaySSID();
                        g_scan_done = 0;
                        g_prescan_waiting = 0;
                    }
                }
        #endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)


        // This task performs normal stack task including checking
        // for incoming packet, type of packet and calling
        // appropriate stack entity to process it.
        StackTask();

        WiFiTask();
        // This tasks invokes each of the core stack application tasks
        StackApplications();

        #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
                ZeroconfLLProcess();
        #endif

        #if defined(STACK_USE_ZEROCONF_MDNS_SD)
                mDNSProcess();
                // Use this function to exercise service update function
                // HTTPUpdateRecord();
        #endif

        // Process application specific tasks here.
        // For this demo app, this will include the Generic TCP
        // client and servers, and the SNMP, Ping, and SNMP Trap
        // demos.  Following that, we will process any IO from
        // the inputs on the board itself.
        // Any custom modules or processing you need to do should
        // go here.

        #if defined(WF_CONSOLE)
                //WFConsoleProcess();
                //    #if !defined(STACK_USE_EZ_CONFIG)
                //	IperfAppCall();
                //      #endif
                //WFConsoleProcessEpilogue();
        wait_console_input:
        #endif

        #if defined(STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE)
                GenericTCPClient();
        #endif

        #if defined(STACK_USE_GENERIC_TCP_SERVER_EXAMPLE)
                GenericTCPServer();
        #endif

        #if defined(STACK_USE_SMTP_CLIENT)
                SMTPDemo();
        #endif

        #if defined(STACK_USE_ICMP_CLIENT)
                PingDemo();
                //PingConsole();
        #endif

        #if defined(STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED)
                //User should use one of the following SNMP demo
                // This routine demonstrates V1 or V2 trap formats with one variable binding.
                SNMPTrapDemo();

        #if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3)
                //This routine provides V2 format notifications with multiple (3) variable bindings
                //User should modify this routine to send v2 trap format notifications with the required varbinds.
                //SNMPV2TrapDemo();
        #endif
                if (gSendTrapFlag)
                    SNMPSendTrap();
        #endif

        #if defined ( WF_CONSOLE ) && defined ( EZ_CONFIG_SCAN )
                WFDisplayScanMgr();
        #endif

        #if defined(STACK_USE_BERKELEY_API)
                BerkeleyTCPClientDemo();
                BerkeleyTCPServerDemo();
                BerkeleyUDPClientDemo();
        #endif

        if((updateDisplay && CFGCXT.isWifiDoneConfigure) || (dwLastIP != AppConfig.MyIPAddr.Val))
        {
            if(dwLastIP != AppConfig.MyIPAddr.Val)
                dwLastIP = AppConfig.MyIPAddr.Val;
            if(updateDisplay && CFGCXT.isWifiDoneConfigure)
                updateDisplay = 0;
            
            #if defined(STACK_USE_ANNOUNCE)
                AnnounceIP();
            #endif
            #if defined(STACK_USE_ZEROCONF_MDNS_SD)
                mDNSFillHostRecord();
            #endif
            DisplaySSID();


        }

    }
}
Esempio n. 15
0
/*
 * Main entry point.
 */
void main(void)
{
    static TICK8 t = 0;
    BYTE i;
    char strBuf[10];

    /*
     * Initialize any application specific hardware.
     */
    InitializeBoard();

    /*
     * Initialize all stack related components.
     * Following steps must be performed for all applications using
     * PICmicro TCP/IP Stack.
     */
    TickInit();

    /*
     * Initialize file system.
     */
    fsysInit();

    //Intialize HTTP Execution unit
    htpexecInit();

    //Initialze serial port
    serInit();
    
    /*
     * Initialize Stack and application related NV variables.
     */
    appcfgInit();
    appcfgUSART();              //Configure the USART
    #ifdef SER_USE_INTERRUPT    //Interrupt enabled serial ports have to be enabled
    serEnable();
    #endif
    appcfgCpuIO();          //Configure the CPU's I/O port pin directions - input or output
    appcfgCpuIOValues();    //Configure the CPU's I/O port pin default values
    appcfgADC();            //Configure ADC unit

    //Serial configuration menu - display it for configured time and allow user to enter configuration menu
    scfInit(appcfgGetc(APPCFG_STARTUP_SER_DLY));

    StackInit();

#if defined(STACK_USE_HTTP_SERVER)
    HTTPInit();
#endif

#if defined(STACK_USE_FTP_SERVER)
    FTPInit();
#endif


#if defined(STACK_USE_DHCP) || defined(STACK_USE_IP_GLEANING)
    //If DHCP is NOT enabled
    if ((appcfgGetc(APPCFG_NETFLAGS) & APPCFG_NETFLAGS_DHCP) == 0)
    {
        //Force IP address display update.
        myDHCPBindCount = 1;
        
        #if defined(STACK_USE_DHCP)
        DHCPDisable();
        #endif
    }
#endif

    #if (DEBUG_MAIN >= LOG_DEBUG)
        debugPutMsg(1); //@mxd:1:Starting main loop
    #endif

    
    /*
     * Once all items are initialized, go into infinite loop and let
     * stack items execute their tasks.
     * If application needs to perform its own task, it should be
     * done at the end of while loop.
     * Note that this is a "co-operative mult-tasking" mechanism
     * where every task performs its tasks (whether all in one shot
     * or part of it) and returns so that other tasks can do their
     * job.
     * If a task needs very long time to do its job, it must broken
     * down into smaller pieces so that other tasks can have CPU time.
     */
    while(1)
    {
        //Blink SYSTEM LED every second.
        if (appcfgGetc(APPCFG_SYSFLAGS) & APPCFG_SYSFLAGS_BLINKB6) {
            if ( TickGetDiff8bit(t) >= ((TICK8)(TICKS_PER_SECOND/2)) )
            {
                t = TickGet8bit();
                TRISB_RB6 = 0;
                LATB6 ^= 1;
            }
        }

        //This task performs normal stack task including checking for incoming packet,
        //type of packet and calling appropriate stack entity to process it.
        StackTask();

#if defined(STACK_USE_HTTP_SERVER)
        //This is a TCP application.  It listens to TCP port 80
        //with one or more sockets and responds to remote requests.
        HTTPServer();
#endif

#if defined(STACK_USE_FTP_SERVER)
        FTPServer();
#endif

        //Add your application speicifc tasks here.
        ProcessIO();

        //For DHCP information, display how many times we have renewed the IP
        //configuration since last reset.
        if ( DHCPBindCount != myDHCPBindCount )
        {
            #if (DEBUG_MAIN >= LOG_INFO)
                debugPutMsg(2); //@mxd:2:DHCP Bind Count = %D
                debugPutByteHex(DHCPBindCount);
            #endif
            
            //Display new IP address
            #if (DEBUG_MAIN >= LOG_INFO)
                debugPutMsg(3); //@mxd:3:DHCP complete, IP = %D.%D.%D.%D
                debugPutByteHex(AppConfig.MyIPAddr.v[0]);
                debugPutByteHex(AppConfig.MyIPAddr.v[1]);
                debugPutByteHex(AppConfig.MyIPAddr.v[2]);
                debugPutByteHex(AppConfig.MyIPAddr.v[3]);
            #endif
            myDHCPBindCount = DHCPBindCount;
        }
    }
}
Esempio n. 16
0
int main(void)
#endif
{
    static DWORD t = 0;
    static DWORD dwLastIP = 0;

    #if defined (EZ_CONFIG_STORE)
    static DWORD ButtonPushStart = 0;
    #endif

    #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)
    UINT8            channelList[] = MY_DEFAULT_CHANNEL_LIST_PRESCAN;  // WF_PRESCAN
    tWFScanResult     bssDesc;
    #endif

    // Initialize application specific hardware
    InitializeBoard();

    #if defined(USE_LCD)
    // Initialize and display the stack version on the LCD
    LCDInit();
    DelayMs(100);
    strcpypgm2ram((char*)LCDText, "TCPStack " TCPIP_STACK_VERSION "  "
        "                ");
    LCDUpdate();
    #endif

    // Initialize stack-related hardware components that may be
    // required by the UART configuration routines
    TickInit();
    #if defined(STACK_USE_MPFS2)
    MPFSInit();
    #endif

    // Initialize Stack and application related NV variables into AppConfig.
    InitAppConfig();

    // Initiates board setup process if button is depressed 
    // on startup
    if(BUTTON0_IO == 0u)
    {
        #if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS)
        // Invalidate the EEPROM contents if BUTTON0 is held down for more than 4 seconds
        DWORD StartTime = TickGet();
        LED_PUT(0x00);

        while(BUTTON0_IO == 0u)
        {
            if(TickGet() - StartTime > 4*TICK_SECOND)
            {
                #if defined(EEPROM_CS_TRIS)
                XEEBeginWrite(0x0000);
                XEEWrite(0xFF);
                XEEWrite(0xFF);
                XEEEndWrite();
                #elif defined(SPIFLASH_CS_TRIS)
                SPIFlashBeginWrite(0x0000);
                SPIFlashWrite(0xFF);
                SPIFlashWrite(0xFF);
                #endif

                #if defined(STACK_USE_UART)
                putrsUART("\r\n\r\nBUTTON0 held for more than 4 seconds.  Default settings restored.\r\n\r\n");
                #endif

                LED_PUT(0x0F);
                while((LONG)(TickGet() - StartTime) <= (LONG)(9*TICK_SECOND/2));
                LED_PUT(0x00);
                while(BUTTON0_IO == 0u);
                Reset();
                break;
            }
        }
        #endif

        #if defined(STACK_USE_UART)
        DoUARTConfig();
        #endif
    }

    // Initialize core stack layers (MAC, ARP, TCP, UDP) and
    // application modules (HTTP, SNMP, etc.)
    StackInit();

    #if defined ( EZ_CONFIG_SCAN )
    WFInitScan();
    #endif

    #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)
    // WF_PRESCAN: Pre-scan before starting up as SoftAP mode  
    WF_CASetScanType(MY_DEFAULT_SCAN_TYPE);
    WF_CASetChannelList(channelList, sizeof(channelList));

    if (WFStartScan() == WF_SUCCESS)
    {
        SCAN_SET_DISPLAY(SCANCXT.scanState);
        SCANCXT.displayIdx = 0;
        //putsUART("main: Prescan WFStartScan() success ................. \r\n");
    }

    // Needed to trigger g_scan_done
    WFRetrieveScanResult(0, &bssDesc);
    #else

    #if defined(WF_CS_TRIS)
    WF_Connect();
    #endif // defined(WF_CS_TRIS)

    #endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)

    // Initialize any application-specific modules or functions/
    // For this demo application, this only includes the
    // UART 2 TCP Bridge
    #if defined(STACK_USE_UART2TCP_BRIDGE)
    UART2TCPBridgeInit();
    #endif

    #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
    ZeroconfLLInitialize();
    #endif

    #if defined(STACK_USE_ZEROCONF_MDNS_SD)
    mDNSInitialize(MY_DEFAULT_HOST_NAME);
	#if defined(STACK_USE_TCP_MOBILE_APP_SERVER)
		mDNSServiceRegister(
        	(const char *) "HomeControlServer",    // base name of the service
        	"_home-control._tcp.local",                // type of the service
        	27561,                                // TCP or UDP port, at which this service is available
        	((const BYTE *)"control home devices"),    // TXT info
        	1,                                    // auto rename the service when if needed
        	NULL,                                // no callback function
        	NULL                                // no application context
        	);
	#else	/* !defined(STACK_USE_TCP_MOBILE_APP_SERVER) */
    	mDNSServiceRegister(
        	(const char *) "DemoWebServer",    // base name of the service
        	"_http._tcp.local",                // type of the service
        	80,                                // TCP or UDP port, at which this service is available
        	((const BYTE *)"path=/index.htm"),    // TXT info
        	1,                                    // auto rename the service when if needed
        	NULL,                                // no callback function
        	NULL                                // no application context
        	);
	#endif	/* defined(STACK_USE_TCP_MOBILE_APP_SERVER) */
    mDNSMulticastFilterRegister();
    #endif

    #if defined(WF_CONSOLE)
    WFConsoleInit();
    #endif

    // Now that all items are initialized, begin the co-operative
    // multitasking loop.  This infinite loop will continuously
    // execute all stack-related tasks, as well as your own
    // application's functions.  Custom functions should be added
    // at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.
    while(1)
    {
        #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)    
        if (g_scan_done) {
           if (g_prescan_waiting) {
               putrsUART((ROM char*)"\n SoftAP prescan results ........ \r\n\n");
               SCANCXT.displayIdx = 0;
               while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) {
                   WFDisplayScanMgr();
               }
               putrsUART((ROM char*)"\r\n ");

               #if defined(WF_CS_TRIS)
               WF_Connect();
               #endif
               g_scan_done = 0;
               g_prescan_waiting = 0;
           }
        }
        #endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)   

        #if defined(WF_PRE_SCAN_IN_ADHOC)
        if(g_prescan_adhoc_done)
        {
            WFGetScanResults();
            g_prescan_adhoc_done = 0;
        }
        #endif

        #if defined (EZ_CONFIG_STORE)
        // Hold button3 for 4 seconds to reset to defaults.
        if (BUTTON3_IO == 0u) {  // Button is pressed
            if (ButtonPushStart == 0)  //Just pressed
                ButtonPushStart = TickGet();
            else
                if(TickGet() - ButtonPushStart > 4*TICK_SECOND)
                    RestoreWifiConfig();
        } 
        else 
        {
            ButtonPushStart = 0; //Button release reset the clock
        } 

        if (AppConfig.saveSecurityInfo)
        {
            // set true by WF_ProcessEvent after connecting to a new network
            // get the security info, and if required, push the PSK to EEPROM
            if ((AppConfig.SecurityMode == WF_SECURITY_WPA_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA2_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE))
            {
                // only need to save when doing passphrase
                tWFCPElements profile;
                UINT8 connState;
                UINT8 connID;
                WF_CMGetConnectionState(&connState, &connID);
                WF_CPGetElements(connID, &profile);
                
                memcpy((char*)AppConfig.SecurityKey, (char*)profile.securityKey, 32);
                AppConfig.SecurityMode--; // the calc psk is exactly one below for each passphrase option
                AppConfig.SecurityKeyLength = 32;                

                SaveAppConfig(&AppConfig);
            }
            
            AppConfig.saveSecurityInfo = FALSE;
        }
        #endif // EZ_CONFIG_STORE

        #if defined (STACK_USE_EZ_CONFIG)
        // Blink LED0 twice per sec when unconfigured, once per sec after config
        if((TickGet() - t >= TICK_SECOND/(4ul - (CFGCXT.isWifiDoneConfigure*2ul))))
        #else
        // Blink LED0 (right most one) every second.
        if(TickGet() - t >= TICK_SECOND/2ul)
        #endif // STACK_USE_EZ_CONFIG
        {
            t = TickGet();
            LED0_IO ^= 1;
        }

        // This task performs normal stack task including checking
        // for incoming packet, type of packet and calling
        // appropriate stack entity to process it.
        StackTask();

        // This tasks invokes each of the core stack application tasks
        StackApplications();

        #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
        ZeroconfLLProcess();
        #endif

        #if defined(STACK_USE_ZEROCONF_MDNS_SD)
        mDNSProcess();
        // Use this function to exercise service update function
        // HTTPUpdateRecord();
        #endif

        // Process application specific tasks here.
        // For this demo app, this will include the Generic TCP
        // client and servers, and the SNMP, Ping, and SNMP Trap
        // demos.  Following that, we will process any IO from
        // the inputs on the board itself.
        // Any custom modules or processing you need to do should
        // go here.

        #if defined(WF_CONSOLE)
        WFConsoleProcess();
        WFConsoleProcessEpilogue();
        #endif

        #if defined(STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE)
        GenericTCPClient();
        #endif

        #if defined(STACK_USE_GENERIC_TCP_SERVER_EXAMPLE)
        GenericTCPServer();
        #endif

		#if defined(STACK_USE_TCP_MOBILE_APP_SERVER)
		MobileTCPServer();
		#endif
		
        #if defined(STACK_USE_SMTP_CLIENT)
        SMTPDemo();
        #endif

        #if defined(STACK_USE_ICMP_CLIENT)
        PingDemo();
        PingConsole();
        #endif

        #if defined(STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED)
        //User should use one of the following SNMP demo
        // This routine demonstrates V1 or V2 trap formats with one variable binding.
        SNMPTrapDemo();

        #if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3)
        //This routine provides V2 format notifications with multiple (3) variable bindings
        //User should modify this routine to send v2 trap format notifications with the required varbinds.
        //SNMPV2TrapDemo();
        #endif
        if(gSendTrapFlag)
            SNMPSendTrap();
        #endif

        #if defined(STACK_USE_BERKELEY_API)
        BerkeleyTCPClientDemo();
        BerkeleyTCPServerDemo();
        BerkeleyUDPClientDemo();
        #endif


        // If the local IP address has changed (ex: due to DHCP lease change)
        // write the new IP address to the LCD display, UART, and Announce 
        // service
        if(dwLastIP != AppConfig.MyIPAddr.Val)
        {
            dwLastIP = AppConfig.MyIPAddr.Val;

            #if defined(STACK_USE_UART)
                putrsUART((ROM char*)"\r\nNew IP Address: ");
            #endif

            DisplayIPValue(AppConfig.MyIPAddr);

            #if defined(STACK_USE_UART)
                putrsUART((ROM char*)"\r\n");
            #endif


            #if defined(STACK_USE_ANNOUNCE)
                AnnounceIP();
            #endif

            #if defined(STACK_USE_ZEROCONF_MDNS_SD)
                mDNSFillHostRecord();
            #endif
        }
    }
}
Esempio n. 17
0
/*
 * Main entry point.
 */
void main(void)
{
    static TICK8 t = 0;

#ifdef	HEATHERD
	NODE_INFO tcpServerNode;
	static TCP_SOCKET tcpSocketUser = INVALID_SOCKET;
	BYTE c;
#endif

    static BYTE testLED;
    testLED = 1;

    //Set SWDTEN bit, this will enable the watch dog timer
    WDTCON_SWDTEN = 1;
    aliveCntrMain = 0xff;   //Disable alive counter during initialization. Setting to 0xff disables it.

    //Initialize any application specific hardware.
    InitializeBoard();

    //Initialize all stack related components. Following steps must
    //be performed for all applications using PICmicro TCP/IP Stack.
    TickInit();    

    //Initialize buses
    busInit();

    //Initialize serial ports early, because they could be required for debugging
    if (appcfgGetc(APPCFG_USART1_CFG & APPCFG_USART_ENABLE)) {
        appcfgUSART();              //Configure the USART1
    }

    if (appcfgGetc(APPCFG_USART2_CFG & APPCFG_USART_ENABLE)) {
        appcfgUSART2();             //Configure the USART2
    }

    //After initializing all modules that use interrupts, enable global interrupts
    INTCON_GIEH = 1;
    INTCON_GIEL = 1;

    //Initialize file system.
    fsysInit();

    //Intialize HTTP Execution unit
    htpexecInit();

    //Initialize Stack and application related NV variables.
    appcfgInit();

    //First call appcfgCpuIOValues() and then only appcfgCpuIO()!!! This ensures the value are set, before enabling ports.
    appcfgCpuIOValues();    //Configure the CPU's I/O port pin default values
    appcfgCpuIO();          //Configure the CPU's I/O port pin directions - input or output
    
    appcfgADC();            //Configure ADC unit
    appcfgPWM();            //Configure PWM Channels

    //Serial configuration menu - display it for configured time and allow user to enter configuration menu
    scfInit(appcfgGetc(APPCFG_STARTUP_SER_DLY));
    
    //LCD Display Initialize
    lcdInit();

    //Initialize expansion board
    appcfgXboard();

    StackInit();

#if defined(STACK_USE_HTTP_SERVER)
    HTTPInit();
#endif

#if defined(STACK_USE_FTP_SERVER)
    FTPInit();
#endif

    //Intialise network componet of buses - only call after StackInit()!
    busNetInit();

    //Initializes events.
    evtInit();

    //Initializes "UDP Command Port" and "UDP Even Port".
    cmdInit();

    ioInit();

    #if (DEBUG_MAIN >= LOG_DEBUG)
        debugPutMsg(1); //@mxd:1:Starting main loop
    #endif

    /*
     * Once all items are initialized, go into infinite loop and let
     * stack items execute their tasks.
     * If application needs to perform its own task, it should be
     * done at the end of while loop.
     * Note that this is a "co-operative mult-tasking" mechanism
     * where every task performs its tasks (whether all in one shot
     * or part of it) and returns so that other tasks can do their
     * job.
     * If a task needs very long time to do its job, it must broken
     * down into smaller pieces so that other tasks can have CPU time.
     */

#ifdef HEATHERD
    //Create a TCP socket that listens on port 54123
    tcpSocketUser = TCPListen(HEATHERD);

#define HEATHERD_ENABLE (!(appcfgGetc(APPCFG_TRISA) & 1))
#define HEATHERD_WRITE_ENABLE (!(appcfgGetc(APPCFG_TRISA) & 2))

#endif
    
    while(1)
    {
        aliveCntrMain = 38;     //Reset if not services in 52.42ms x 38 = 2 seconds

        //Blink SYSTEM LED every second.
        if (appcfgGetc(APPCFG_SYSFLAGS) & APPCFG_SYSFLAGS_BLINKB6) {
            //Configure RB6 as output, and blink it every 500ms
            if ( TickGetDiff8bit(t) >= ((TICK8)TICKS_PER_SECOND / (TICK8)2) )
            {
                t = TickGet8bit();
                
                //If B6 is configured as input, change to output
                if (appcfgGetc(APPCFG_TRISB) & 0x40) {
                    appcfgPutc(APPCFG_TRISB, appcfgGetc(APPCFG_TRISB) & 0b10111111);
                }
          
                TRISB_RB6 = 0;
                LATB6 ^= 1;     //Toggle
                
                //Toggle IOR5E LED, if IOR5E is present
                if (appcfgGetc(APPCFG_XBRD_TYPE) == XBRD_TYPE_IOR5E) {
                    ior5eLatchData.bits.ledPWR ^= 1;    // Toggle
                }
            }
        }

        //This task performs normal stack task including checking for incoming packet,
        //type of packet and calling appropriate stack entity to process it.
        StackTask();

        //Service LCD display
        lcdService();
        
        //Process commands
        cmdTask();
        
        //Process events
        evtTask();

        //Process serial busses
        busTask();

        //I2C Task
        i2cTask();


#ifdef HEATHERD
        //Has a remote node made connection with the port we are listening on
        if ((tcpSocketUser != INVALID_SOCKET) && TCPIsConnected(tcpSocketUser)) {
    		if (HEATHERD_ENABLE) {
	
	            //Is there any data waiting for us on the TCP socket?
	            //Because of the design of the Modtronix TCP/IP stack we have to
	            //consume all data sent to us as soon as we detect it.
	            while(TCPIsGetReady(tcpSocketUser)) {
	                //We are only interrested in the first byte of the message.
	                TCPGet(tcpSocketUser, &c);
					if (HEATHERD_WRITE_ENABLE) serPutByte(c);
	            }
	            //Discard the socket buffer.
	            TCPDiscard(tcpSocketUser);
			    while (serIsGetReady() && TCPIsPutReady(tcpSocketUser)) {
					TCPPut(tcpSocketUser,serGetByte());
				}
				TCPFlush(tcpSocketUser);
	        } else {
				TCPDisconnect(tcpSocketUser);
			}
		}
#endif

#if defined(STACK_USE_HTTP_SERVER)
        //This is a TCP application.  It listens to TCP port 80
        //with one or more sockets and responds to remote requests.
        HTTPServer();
#endif

#if defined(STACK_USE_FTP_SERVER)
        FTPServer();
#endif

#if defined(STACK_USE_ANNOUNCE)
        DiscoveryTask();
#endif

#if defined(STACK_USE_NBNS)
        NBNSTask();
#endif

        //Add your application speicifc tasks here.
        ProcessIO();

        //For DHCP information, display how many times we have renewed the IP
        //configuration since last reset.
        if ( DHCPBindCount != myDHCPBindCount )
        {
            #if (DEBUG_MAIN >= LOG_INFO)
                debugPutMsg(2); //@mxd:2:DHCP Bind Count = %D
                debugPutByteHex(DHCPBindCount);
            #endif
            
            //Display new IP address
            #if (DEBUG_MAIN >= LOG_INFO)
                debugPutMsg(3); //@mxd:3:DHCP complete, IP = %D.%D.%D.%D
                debugPutByteHex(AppConfig.MyIPAddr.v[0]);
                debugPutByteHex(AppConfig.MyIPAddr.v[1]);
                debugPutByteHex(AppConfig.MyIPAddr.v[2]);
                debugPutByteHex(AppConfig.MyIPAddr.v[3]);
            #endif
            myDHCPBindCount = DHCPBindCount;
            
            #if defined(STACK_USE_ANNOUNCE)
                AnnounceIP();
            #endif             
        }
    }
}
Esempio n. 18
0
/*
 * Main entry point.
 */
void main(void)
{
    static TICK t = 0;
    BYTE c, i;

    /*
     * Initialize any application specific hardware.
     */
    InitializeBoard();

    /*
     * Initialize all stack related components.
     * Following steps must be performed for all applications using
     * PICmicro TCP/IP Stack.
     */
    TickInit();

    /*
     * Following steps must be performed for all applications using
     * PICmicro TCP/IP Stack.
     */
    MPFSInit();


    /*
     * Initialize Stack and application related NV variables.
     */
    InitAppConfig();


    /*
     * Depending on whether internal program memor is used or external
     * EEPROM is used, keep/remove these block.
     */

    /*
     * Wait a couple of seconds for user input.
	 * - If something is detected, start config.
	 * - If nothing detected, start main program.
     */
	USARTPutROMString(PressKeyForConfig);
	for (i = 60; i > 0; --i)	//Delay for 50mS x 60 = 3 sec
	{
		if ((i % 8) == 0) USARTPut('.');
		if (USARTIsGetReady())
		{
			#if defined(APP_USE_LCD)
	       	XLCDGoto(1, 0);
	       	XLCDPutROMString(SetupMsg);
			#endif
	
	        SetConfig();
			break;
		}
		DelayMs(50);
	}
	USARTPut('\r');
	USARTPut('\n');

    StackInit();

#if defined(STACK_USE_HTTP_SERVER)
    HTTPInit();
#endif

#if defined(STACK_USE_FTP_SERVER) && defined(MPFS_USE_EEPROM)
    FTPInit();
#endif


#if defined(STACK_USE_DHCP) || defined(STACK_USE_IP_GLEANING)
    if ( AppConfig.Flags.bIsDHCPEnabled )
    {
		#if defined(APP_USE_LCD)
        XLCDGoto(1, 0);
   	    XLCDPutROMString(DHCPMsg);
		#endif
    }
    else
    {
        /*
         * Force IP address display update.
         */
        myDHCPBindCount = 1;
#if defined(STACK_USE_DHCP)
        DHCPDisable();
#endif
    }
#endif

    /*
     * Once all items are initialized, go into infinite loop and let
     * stack items execute their tasks.
     * If application needs to perform its own task, it should be
     * done at the end of while loop.
     * Note that this is a "co-operative mult-tasking" mechanism
     * where every task performs its tasks (whether all in one shot
     * or part of it) and returns so that other tasks can do their
     * job.
     * If a task needs very long time to do its job, it must broken
     * down into smaller pieces so that other tasks can have CPU time.
     */
    while(1)
    {
        //Turn off the heater after about 1min to prevent over heating
        if(heater_started ==1)
        {
            if ( TickGetDiff(TickGet(), t) >= 9000 )
            {
                LATB4 = 0;
    			heater_started = 0;
            }   
        }else
		{
		    t = TickGet();
		}
         
        /*
         * This task performs normal stack task including checking
         * for incoming packet, type of packet and calling
         * appropriate stack entity to process it.
         */
        StackTask();

#if defined(STACK_USE_HTTP_SERVER)
        /*
         * This is a TCP application.  It listens to TCP port 80
         * with one or more sockets and responds to remote requests.
         */
        HTTPServer();
#endif

#if defined(STACK_USE_FTP_SERVER) && defined(MPFS_USE_EEPROM)
        FTPServer();
#endif

        /*
         * In future, as new TCP/IP applications are written, it
         * will be added here as new tasks.
         */

         /*
          * Add your application speicifc tasks here.
          */
        ProcessIO();

        /*
         * For DHCP information, display how many times we have renewed the IP
         * configuration since last reset.
         */
        if ( DHCPBindCount != myDHCPBindCount )
        {
            DisplayIPValue(&AppConfig.MyIPAddr, TRUE);
            myDHCPBindCount = DHCPBindCount;

			#if defined(APP_USE_LCD)
            if ( AppConfig.Flags.bIsDHCPEnabled )
            {
                XLCDGoto(1, 14);
   	            if ( myDHCPBindCount < 0x0a )
       	            XLCDPut(myDHCPBindCount + '0');
           	    else
               	    XLCDPut(myDHCPBindCount + 'A');
            }
			#endif
        }

    }
}
Esempio n. 19
0
int main()
{
	// declare variables
	char board[ROWS][COLS];

	// Produce a NoWin condition
	// initialize board
	InitializeBoard(board);
	// populate board
	PlayerMove(1, 1, board, MARKONE);
	PlayerMove(1, 2, board, MARKONE);

	// display the board
	DisplayBoard(board);
	// display victory message
	DisplayVictoryMessage( VictoryCheck(CONSECUTIVE_MARKS_REQUIRED, board) );

	// Produce a horizontal victory
	// initialize board
	InitializeBoard(board);
	// populate board
	PlayerMove(1, 1, board, MARKONE);
	PlayerMove(1, 2, board, MARKONE);
	PlayerMove(1, 3, board, MARKONE);
	// display the board
	DisplayBoard(board);
	// display victory message
	DisplayVictoryMessage( VictoryCheck(CONSECUTIVE_MARKS_REQUIRED, board) );

	// Produce a vertical victory
	// initialize board
	InitializeBoard(board);
	// populate board
	PlayerMove(1, 1, board, MARKTWO);
	PlayerMove(2, 1, board, MARKTWO);
	PlayerMove(3, 1, board, MARKTWO);
	// display the board
	DisplayBoard(board);
	// display victory message
	DisplayVictoryMessage( VictoryCheck(CONSECUTIVE_MARKS_REQUIRED, board) );

	// Produce a diagonal-down victory
	// initialize board
	InitializeBoard(board);
	// populate board
	PlayerMove(1, 1, board, MARKONE);
	PlayerMove(2, 2, board, MARKONE);
	PlayerMove(3, 3, board, MARKONE);
	// display the board
	DisplayBoard(board);
	// display victory message
	DisplayVictoryMessage( VictoryCheck(CONSECUTIVE_MARKS_REQUIRED, board) );

	// Produce a diagonal-up victory
	// initialize board
	InitializeBoard(board);
	// populate board
	PlayerMove(3, 1, board, MARKTWO);
	PlayerMove(2, 2, board, MARKTWO);
	PlayerMove(1, 3, board, MARKTWO);
	// display the board
	DisplayBoard(board);
	// display victory message
	DisplayVictoryMessage( VictoryCheck(CONSECUTIVE_MARKS_REQUIRED, board) );

	// Produce a multiple player victory
	// initialize board
	InitializeBoard(board);
	// populate board
	PlayerMove(4, 1, board, MARKONE);
	PlayerMove(4, 2, board, MARKONE);
	PlayerMove(4, 3, board, MARKONE);
	PlayerMove(3, 1, board, MARKTWO);
	PlayerMove(2, 2, board, MARKTWO);
	PlayerMove(1, 3, board, MARKTWO);
	// display the board
	DisplayBoard(board);
	// display victory message
	DisplayVictoryMessage( VictoryCheck(CONSECUTIVE_MARKS_REQUIRED, board) );

	// Produce a tie
	// initialize board
	// InitializeBoard(board);
	// populate board
	// for (int k = 0; k < COLS; ) {
		/* code */
		// k % 2 == 0 ? k+=1 : k += 3;
	// }
	// display the board
	// DisplayBoard(board);
	// display victory message
	// DisplayVictoryMessage( VictoryCheck(CONSECUTIVE_MARKS_REQUIRED, board) );

	// exit program
	return 0;
}
Esempio n. 20
0
void UNIFLoad(Stream *fp, NESGameType *gt)
{
  try
  {
	uint8 magic[4];

	if(fp->read(magic, 4, false) != 4 || memcmp(magic, "UNIF", 4))
	 throw MDFN_Error(0, _("Not a valid UNIF file."));

	ResetCartMapping();

        ResetUNIF();
	memset(WantInput, 0, sizeof(WantInput));

        unhead.info = fp->get_LE<uint32>();
        fp->seek(0x20, SEEK_SET);

        LoadUNIFChunks(fp);

	{
	 md5_context md5;
	 
	 md5.starts();

	 for(int x = 0; x < 32; x++)
	 {
	  if(malloced[x])
	  {
	   md5.update(malloced[x],mallocedsizes[x]);
	  }
	 }
	 md5.finish(UNIFCart.MD5);
         MDFN_printf(_("ROM MD5:  0x%s\n"), md5_context::asciistr(UNIFCart.MD5, 0).c_str());
	 memcpy(MDFNGameInfo->MD5,UNIFCart.MD5,sizeof(UNIFCart.MD5));
	 MDFN_printf("\n");
	}

        InitializeBoard();

	MDFN_LoadGameSave(&UNIFCart);

	gt->Power = UNIF_Power;
	gt->Reset = UNIF_Reset;
	gt->SaveNV = UNIF_SaveNV;
	gt->Kill = UNIF_Kill;
	gt->StateAction = UNIF_StateAction;

        if(UNIFCart.CartExpSound.HiFill)
         GameExpSound.push_back(UNIFCart.CartExpSound);

	MDFNGameInfo->DesiredInput.push_back(WantInput[0]);
        MDFNGameInfo->DesiredInput.push_back(WantInput[1]);
        MDFNGameInfo->DesiredInput.push_back("gamepad");
        MDFNGameInfo->DesiredInput.push_back("gamepad");

        MDFNGameInfo->DesiredInput.push_back(WantInput[2]);
  }
  catch(...)
  {
   if(UNIFCart.Close)
    UNIFCart.Close();

   FreeUNIF();
   ResetUNIF();
   throw;
  }
}
Esempio n. 21
0
int main(int argc, char const *argv[]) {
	InitializeBoard();
	PVP();
	
	return 0;
}
Esempio n. 22
0
void main(void)
{
    static TICK t = 0;
    
    // Initialize any application specific hardware.
    InitializeBoard();

	canInit();

    // Initialize Stack and application related NV variables.
    InitAppConfig();

    StackInit();

#if defined(STACK_USE_HTTP_SERVER)
    HTTPInit();
#endif

#if defined(STACK_USE_SGP_SERVER)
	SGPInit();
#endif


    // Once all items are initialized, go into infinite loop and let
    // stack items execute their tasks.
    // If application needs to perform its own task, it should be
    // done at the end of while loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must broken
    // down into smaller pieces so that other tasks can have CPU time.
    while(1)
    {
        // Blink SYSTEM LED every second.
        if ( tickGet()-t >= TICK_1S/2 )
        {
            t = tickGet();
            LED0_IO ^= 1;
        }

        // This task performs normal stack task including checking
        // for incoming packet, type of packet and calling
        // appropriate stack entity to process it.
        StackTask();

#if defined(STACK_USE_HTTP_SERVER)
        // This is a TCP application.  It listens to TCP port 80
        // with one or more sockets and responds to remote requests.
        HTTPServer();
#endif

#if defined(STACK_USE_SGP_SERVER)
        // This is a TCP application.  It listens to TCP port 6666
        // with one or more sockets and responds to remote requests.
        SGPServer();
#endif

#if defined(STACK_USE_TIMESYNC)
	timeSync();
#endif

        // In future, as new TCP/IP applications are written, it
        // will be added here as new tasks.

        // Add your application speicifc tasks here.
        ProcessIO();

    }
}
Esempio n. 23
0
/*
 * Main entry point.
 */
void main(void)
{
    TICK8  tsecWait = 0;           //General purpose wait timer
    TICK16 tsecMsgSent = 0;        //Time last message was sent
    TICK16 tsecBlinker = 0;  
    BYTE main_state;				// what are the inputs
	BYTE main_inputs;				// who has the transmit
    char c;
    NODE_INFO udpServerNode;

    //Initialize AppConfig structure
    appcfgInit();
    
    //Initialize any application specific hardware.
    InitializeBoard();

    //Initialize all stack related components.
    TickInit();

    //Initialize the TCP/IP stack
    StackInit();


    /////////////////////////////////////////////////
    //Initialize UDP socket

    //Initialize remote IP and address with 10.1.0.101. The MAC address is
    //is not intialized yet, but after we receive an ARP responce.
    //Configure for local port 54123 and remote port 54124.
    udpServerNode.IPAddr.v[0] = 255;
    udpServerNode.IPAddr.v[1] = 255;
    udpServerNode.IPAddr.v[2] = 255;
    udpServerNode.IPAddr.v[3] = 255;
    udpSocketUser = UDPOpen(54123, &udpServerNode, 54124);
	//udpSocketUser = UDPOpen(54123, NULL, 54124);
	smUdp = SM_UDP_RESOLVED;
    
    //An error occurred during the UDPOpen() function
    if (udpSocketUser == INVALID_UDP_SOCKET) {
        //Add user code here to take action if required!
    }

    /*
     * Once all items are initialized, go into infinite loop and let stack items execute
     * their tasks. If the application needs to perform its own task, it should be done at
     * the end of while loop. Note that this is a "co-operative mult-tasking" mechanism where
     * every task performs its tasks (whether all in one shot or part of it) and returns so
     * that other tasks can do their job. If a task needs very long time to do its job, it
     * must broken down into smaller pieces so that other tasks can have CPU time.
     */
    while(1)
    {
	    ServiceBoard();
		if (TickGetSecDiff(tsecBlinker) >= (TICK16)1) 
		{
			tsecBlinker = TickGetSec();     //Update with current time
			//Toggle system LED 
#ifdef BLINKTIME
            TRISB_RB6 = 0;
            LATB6 ^= 1;
#endif
		}
        switch (smUdp) {
        case SM_UDP_SEND_ARP:
            if (ARPIsTxReady()) {
                tsecWait = TickGet8bitSec();   //Remember when we sent last request
                
                //Send ARP request for given IP address
                ARPResolve(&udpServerNode.IPAddr);
                
                smUdp = SM_UDP_WAIT_RESOLVE;
            }
            break;
        case SM_UDP_WAIT_RESOLVE:
            //The IP address has been resolved, we now have the MAC address of the
            //node at 10.1.0.101
            if (ARPIsResolved(&udpServerNode.IPAddr, &udpServerNode.MACAddr)) {
                smUdp = SM_UDP_RESOLVED;
            }
            //If not resolved after 2 seconds, send next request
            else {
                if (TickGetDiff8bitSec(tsecWait) >= (TICK8)2) {
                    smUdp = SM_UDP_SEND_ARP;
                }
            }
            break;
        case SM_UDP_RESOLVED:
            if ( 1 || !PORTB_RB0) {
                //Send a message every second for as long as PIC port pin B0 is = 0
                if ((TickGetSecDiff(tsecMsgSent) >= (TICK16)1) ||
					((main_state != old_state) || (main_inputs != old_inputs))) {
                    //Checks if there is a transmit buffer ready for accepting data, and that the given socket
                    //is valid (not equal to INVALID_UDP_SOCKET for example)
                    if (UDPIsPutReady(udpSocketUser)) {
                        tsecMsgSent = TickGetSec();     //Update with current time

                        //Send a UDP Datagram with one byte only indicating the status We are only interrested in the first byte of the message.
                        UDPPut('H');UDPPut('E');UDPPut('L');UDPPut('L');UDPPut('O');
						UDPPut(old_state);
						UDPPut(old_inputs);
						main_state = old_state;
						main_inputs = old_inputs;
                        //Send contents of transmit buffer, and free buffer
                        UDPFlush();
                       	
						//Toggle system LED each time a message is sent
                    	TRISB_RB6 = 0;
                    	LATB6 ^= 1; 
                    }

                    
                }
            }
            break;
        }

        //This task performs normal stack task including checking for incoming packet,
        //type of packet and calling appropriate stack entity to process it.
        StackTask();

        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // ADD USER CODE HERE
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    }
}
Esempio n. 24
0
void partie(Joueur joueur1,Joueur joueur2) {
	Board leBoard;
	int finDePartie = 0;
	int tourDeJeu = 0;					// tour de jeu a 0 = joueur1;
	char positionNouveauPion[3];
	int retourVerifPos;

	leBoard  = InitializeBoard(leBoard);
	leBoard.player1Name = joueur1.Nom;
	leBoard.player2Name = joueur2.Nom;
	leBoard.player1Score = 2;
	leBoard.player2Score = 2;
	
	leBoard = InitializeBoardOthello(leBoard);
	while (!finDePartie) {
		printf("Le score de %s vaut : %d\n",joueur1.Nom, leBoard.player1Score);
		printf("Le score de %s vaut : %d\n",joueur2.Nom, leBoard.player2Score);
		afficherBoard(leBoard);


		///// Tour de jeu du joueur1
		if(tourDeJeu == 0)
		{
			printf("C'est a %s de jouer : \n", joueur1.Nom);
			printf("Entrez les coordonnes du pion que vous souhaitez rentrez (d'abord ligne puis colonne)\n");
			scanf("%s",positionNouveauPion);
			positionNouveauPion[2] = 0;
			//Verif Position correcte
			while ((retourVerifPos = verifPositionOk(positionNouveauPion,leBoard,tourDeJeu)) == 0) {
				printf("Ceci n'est pas une position valide, rentrez en une autre(d'abord ligne puis colonne)\n");
				scanf("%s",positionNouveauPion);
				positionNouveauPion[2] = 0;
			}


			// Change les nombres de pions des joueurs, change la valeur pour les cases sur le board
			leBoard = updateBoard(leBoard,retourVerifPos,tourDeJeu,positionNouveauPion);
			
			//leBoard.tabBoard[positionNouveauPion[0]-97][positionNouveauPion[1]] = 'O';








			tourDeJeu = -1;
		}else {
			printf("C'est a %s de jouer : \n", joueur2.Nom);		
			printf("Entrez les coordonnes du pion que vous souhaitez rentrez (d'abord ligne puis colonne)\n");
			scanf("%s",positionNouveauPion);
			positionNouveauPion[2] = 0;
			//Verif Position correcte
			while ((retourVerifPos = verifPositionOk(positionNouveauPion,leBoard,tourDeJeu)) == 0) {
				printf("Ceci n'est pas une position valide, rentrez en une autre(d'abord ligne puis colonne)\n");
				scanf("%s",positionNouveauPion);
				positionNouveauPion[2] = 0;
			}	
			leBoard = updateBoard(leBoard,retourVerifPos,tourDeJeu,positionNouveauPion);
			tourDeJeu = 0;
		}

		






		// quand fin de partie?
		if(leBoard.player1Score + leBoard.player2Score == 64)
			finDePartie = -1;
	}
	if (leBoard.player1Score > leBoard.player2Score)
		printf("Bravo a %s qui a gagne sur un score de %d a %d\n",joueur1.Nom,leBoard.player1Score,leBoard.player2Score);
	else if(leBoard.player2Score > leBoard.player1Score)
		printf("Bravo a %s qui a gagne sur un score de %d a %d\n",joueur2.Nom,leBoard.player2Score,leBoard.player1Score);
	else
		printf("C'est une egalite parfaite au score, bravo aux deux joueurs !");
	

}
Esempio n. 25
0
int main(void)
#endif
{
static TICK t = 0;
TICK nt = 0;  //TICK is DWORD, thus 32 bits
BYTE loopctr = 0;  //ML Debugging
WORD lloopctr = 14; //ML Debugging

static DWORD dwLastIP = 0;

    // Initialize interrupts and application specific hardware
    InitializeBoard();

    // Initialize and display message on the LCD
    LCDInit();
    DelayMs(100);
    DisplayString (0,"Olimex"); //first arg is start position on 32 pos LCD

    // Initialize Timer0, and low priority interrupts, used as clock.
    TickInit();

    // Initialize Stack and application related variables in AppConfig.
    InitAppConfig();

    // Initialize core stack layers (MAC, ARP, TCP, UDP) and
    // application modules (HTTP, SNMP, etc.)
    StackInit();


    // Now that all items are initialized, begin the co-operative
    // multitasking loop.  This infinite loop will continuously
    // execute all stack-related tasks, as well as your own
    // application's functions.  Custom functions should be added
    // at the end of this loop.

    // Note that this is a "co-operative multi-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.


    while(1)
    {
       // Blink LED0 (right most one) every second.
      nt =  TickGetDiv256();
      if((nt - t) >= (DWORD)(TICK_SECOND/1024ul))
      {
          t = nt;
          LED0_IO ^= 1;
          ClrWdt();  //Clear the watchdog
      }

      // This task performs normal stack task including checking
      // for incoming packet, type of packet and calling
      // appropriate stack entity to process it.
      StackTask();

      // This tasks invokes each of the core stack application tasks
      StackApplications();

      // Process application specific tasks here.

      // If the local IP address has changed (ex: due to DHCP lease change)
      // write the new IP address to the LCD display, UART, and Announce
      // service
    	if(dwLastIP != AppConfig.MyIPAddr.Val)
    	{
    	     dwLastIP = AppConfig.MyIPAddr.Val;
                 #if defined(__SDCC__)
                     DisplayIPValue(dwLastIP); // must be a WORD: sdcc does not
                                               // pass aggregates
                 #else
                     DisplayIPValue(AppConfig.MyIPAddr);
                 #endif
     	}
    }//end of while(1)
}//end of main()
Esempio n. 26
0
/*
 * Main entry point.
 */
void main(void)
{
    static TICK tickHeartBeat = 0xffffffff;
    static BYTE testLED;
   
    testLED = 1;

    // Destination address - Always MAC broadcast address
    broadcastTargetMACAddr.v[ 0 ] = 0xff;
    broadcastTargetMACAddr.v[ 1 ] = 0xff;
    broadcastTargetMACAddr.v[ 2 ] = 0xff;
    broadcastTargetMACAddr.v[ 3 ] = 0xff;
    broadcastTargetMACAddr.v[ 4 ] = 0xff;
    broadcastTargetMACAddr.v[ 5 ] = 0xff;

    //Set SWDTEN bit, this will enable the watch dog timer
    WDTCON_SWDTEN = 1;
    aliveCntrMain = 0xff;   //Disable alive counter during initialization. Setting to 0xff disables it.

    //Initialize any application specific hardware.
    InitializeBoard();

    //Initialize all stack related components. Following steps must
    //be performed for all applications using PICmicro TCP/IP Stack.
    TickInit();

    //Initialize serial ports early, because they could be required for debugging
    if (appcfgGetc(APPCFG_USART1_CFG & APPCFG_USART_ENABLE)) {
        appcfgUSART();              //Configure the USART1
    }

    #if defined(BRD_SBC65EC)
    if (appcfgGetc(APPCFG_USART2_CFG & APPCFG_USART_ENABLE)) {
        appcfgUSART2();             //Configure the USART2
    }
    #endif

    //After initializing all modules that use interrupts, enable global interrupts
    INTCON_GIEH = 1;
    INTCON_GIEL = 1;

    //Initialize Stack and application related NV variables.
    appcfgInit();

    //First call appcfgCpuIOValues() and then only appcfgCpuIO()!!! This ensures the value are set, before enabling ports.
    appcfgCpuIOValues();    //Configure the CPU's I/O port pin default values
    appcfgCpuIO();          //Configure the CPU's I/O port pin directions - input or output
    
    appcfgADC();            //Configure ADC unit
    appcfgPWM();            //Configure PWM Channels

    MACInit();

    #if (DEBUG_MAIN >= LOG_DEBUG)
        debugPutMsg(1); //@mxd:1:Starting main loop
    #endif

    /*
     * Once all items are initialized, go into infinite loop and let
     * stack items execute their tasks.
     * If application needs to perform its own task, it should be
     * done at the end of while loop.
     * Note that this is a "co-operative mult-tasking" mechanism
     * where every task performs its tasks (whether all in one shot
     * or part of it) and returns so that other tasks can do their
     * job.
     * If a task needs very long time to do its job, it must broken
     * down into smaller pieces so that other tasks can have CPU time.
     */
    while ( 1 ) {

        //aliveCntrMain = 38;     //Reset if not services in 52.42ms x 38 = 2 seconds
        aliveCntrMain = 0xff;
        CLRWDT();

        // Check for event
        if ( vscp_getRawPacket() ) {
            feedVSCP();
        }

        // Send heartbeat every 30 seconds
        if ( TickGetDiff( tickHeartBeat ) >= ( TICKS_PER_SECOND * 30 ) ) {

            //vscpevent.head = VSCP_PRIORITY_NORMAL;
            //vscpevent.vscp_class = VSCP_CLASS2_LEVEL1_INFORMATION;
            //vscpevent.vscp_type = VSCP_TYPE_INFORMATION_NODE_HEARTBEAT;
            //vscpevent.sizeData = 3;
            //vscpevent.data[ 0 ] = 0;
            //vscpevent.data[ 1 ] = 0; // Zone
            //vscpevent.data[ 2 ] = 0; // subzone
            //vscp_sendRawPacket( &vscpevent );
            //SendTestVSCPPacket();
	            
            tickHeartBeat = TickGet();
/*                
          	//If B6 is configured as input, change to output
            if (appcfgGetc(APPCFG_TRISB) & 0x40) {
            	appcfgPutc(APPCFG_TRISB, appcfgGetc(APPCFG_TRISB) & 0b10111111);
            }
          
            TRISB_RB6 = 0;
            LATB6 ^= 1;     //Toggle
                
          	//Toggle IOR5E LED, if IOR5E is present
          	if (appcfgGetc(APPCFG_XBRD_TYPE) == XBRD_TYPE_IOR5E) {
            	ior5eLatchData.bits.ledPWR ^= 1;    // Toggle
           	}
*/           	
      	}

        // Do MAC work
        StackTask();
        //MACTask();;

        //I2C Task
        i2cTask();

        //Add your application specific tasks here.
        ProcessIO();

        // Do VSCP periodic tasks
        periodicVSCPWork();

    }
}
Esempio n. 27
0
//função principal
void main(void)
{
    static TICK t = 0;

    //inicializa todas as configuraçoes de hardware
    InitializeBoard();

    #if defined(USE_LCD)
    //inicializa configs do LCD se acaso estiver habilitado
    LCDInit();
    DelayMs(100);
    strcpypgm2ram((char*)LCDText, "APP TCPIP");
    LCDUpdate();
    #endif

    //inicializa um tick de tempo usado para TICK,SPI,UAT
    TickInit();

    //inicializa MPSF para upload de paginas web se acaso estiver habilitado
    #if defined(STACK_USE_MPFS) || defined(STACK_USE_MPFS2)
    MPFSInit();
    #endif

    //inicializa variaveis da aplicação AppConfig (IP, MASCARA, GATWAY, ETC)
    InitAppConfig();

    //inicializa a layer da pilha TCPIP (MAC, ARP, TCP, UDP)
    //e tambem as aplicaçoes habilitadas (HTTP, SNMP, SOCKET, ETC)
    StackInit();

    //inicializa UART 2 TCP Bridge
    #if defined(STACK_USE_UART2TCP_BRIDGE)
    UART2TCPBridgeInit();
    #endif

    //laço principal (nunca use delays, apenas maquinas de estado)
    //todos os processos devem estar executando paralelamente
    while(1)
    {
        //pisca o led para informar a pilha rodando
        if(TickGet() - t >= TICK_SECOND/2ul)
        {
            t = TickGet();
            LED0_IO ^= 1;
        }

        //processa coisas relacionadas ao hardware, leitura de pinos,etc.
        ProcessIO();

        //chama tarefas da pilha TCPIP
        StackTask();

        //chama tarefas das aplicaçoes habilitadas
        StackApplications();

        //exemplo de aplicação Cliente Socket
        #if defined(STACK_USE_TCP_CLIENT)
        ClientSocketTCP();
        #endif

        //exemplo de aplicação Servidor Socket
        #if defined(STACK_USE_TCP_SERVER)
        ServerSocketTCP();
        #endif
    }
}
Esempio n. 28
0
int main(void)
#endif
{
//	static DWORD t = 0;
	static DWORD dwLastIP = 0;

    #if defined (EZ_CONFIG_STORE)
   // static DWORD ButtonPushStart = 0;
    #endif

	// Initialize application specific hardware
	InitializeBoard();
	

	// Initialize stack-related hardware components that may be 
	// required by the UART configuration routines
    TickInit();
	MPFSInit();
	InitDataBuffers();
	Slave_SpiInit();

	// Initialize Stack and application related NV variables into AppConfig.
	InitAppConfig();

    // Initiates board setup process if button is depressed 
	// on startup
	

/*			    
	#if defined (WIFI_BOARD_FOC_HUB)
		XEEBeginWrite(0x0000);
	    XEEWrite(0xFF);
	    XEEWrite(0xFF);
	    XEEEndWrite();
	#else
	
	
    if(BUTTON0_IO == 0u)
    {
		#if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS)
		// Invalidate the EEPROM contents if BUTTON0 is held down for more than 4 seconds
		DWORD StartTime = TickGet();
		LED_PUT(0x00);
				
		while(BUTTON0_IO == 0u)
		{
			if(TickGet() - StartTime > 4*TICK_SECOND)
			{
				#if defined(EEPROM_CS_TRIS)
			    XEEBeginWrite(0x0000);
			    XEEWrite(0xFF);
			    XEEWrite(0xFF);
			    XEEEndWrite();
			    #elif defined(SPIFLASH_CS_TRIS)
			    SPIFlashBeginWrite(0x0000);
			    SPIFlashWrite(0xFF);
			    SPIFlashWrite(0xFF);
			    #endif
			    
				#if defined(STACK_USE_UART)
				putrsUART("\r\n\r\nBUTTON0 held for more than 4 seconds.  Default settings restored.\r\n\r\n");
				#endif

				LED_PUT(0x0F);
				while((LONG)(TickGet() - StartTime) <= (LONG)(9*TICK_SECOND/2));
				LED_PUT(0x00);
				while(BUTTON0_IO == 0u);
				Reset();
				break;
			}
		}
		#endif

		#if defined(STACK_USE_UART)
        DoUARTConfig();
		#endif
    }
	#endif
	*/
	
	
	// Initialize core stack layers (MAC, ARP, TCP, UDP) and
	// application modules (HTTP, SNMP, etc.)
    StackInit();
    
    #if defined ( EZ_CONFIG_SCAN )
    WFInitScan();
    #endif

    #if defined(WF_CS_TRIS)
    WF_Connect();
    #endif

	#if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
    ZeroconfLLInitialize();
	#endif

	#if defined(STACK_USE_ZEROCONF_MDNS_SD)
	mDNSInitialize(MY_DEFAULT_HOST_NAME);
	mDNSServiceRegister(
		(const char *) "DemoWebServer",	// base name of the service
		"_http._tcp.local",			    // type of the service
		80,				                // TCP or UDP port, at which this service is available
		((const BYTE *)"path=/index.htm"),	// TXT info
		1,								    // auto rename the service when if needed
		NULL,							    // no callback function
		NULL							    // no application context
		);

    mDNSMulticastFilterRegister();			
	#endif


	// Now that all items are initialized, begin the co-operative
	// multitasking loop.  This infinite loop will continuously 
	// execute all stack-related tasks, as well as your own
	// application's functions.  Custom functions should be added
	// at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.
    while(1)
    {
	    /*
        #if defined (EZ_CONFIG_STORE)
        // Hold button3 for 4 seconds to reset to defaults.
		if (BUTTON3_IO == 0u) {  // Button is pressed
            if (ButtonPushStart == 0)  //Just pressed
                ButtonPushStart = TickGet();
            else
			    if(TickGet() - ButtonPushStart > 4*TICK_SECOND)
                    RestoreWifiConfig();
        } 
        else 
        {
            ButtonPushStart = 0; //Button release reset the clock
        } 

        if (AppConfig.saveSecurityInfo)
        {
            // set true by WF_ProcessEvent after connecting to a new network
            // get the security info, and if required, push the PSK to EEPROM
            if ((AppConfig.SecurityMode == WF_SECURITY_WPA_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA2_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE))
            {
                // only need to save when doing passphrase
                tWFCPElements profile;
                UINT8 connState;
                UINT8 connID;
                WF_CMGetConnectionState(&connState, &connID);
                WF_CPGetElements(connID, &profile);
                
                memcpy((char*)AppConfig.SecurityKey, (char*)profile.securityKey, 32);
                AppConfig.SecurityMode--; // the calc psk is exactly one below for each passphrase option
                AppConfig.SecurityKeyLength = 32;                

                SaveAppConfig(&AppConfig);
            }
            
            AppConfig.saveSecurityInfo = FALSE;
        }
        #endif // EZ_CONFIG_STORE
        

        #if defined (STACK_USE_EZ_CONFIG)
        // Blink LED0 twice per sec when unconfigured, once per sec after config
        if((TickGet() - t >= TICK_SECOND/(4ul - (CFGCXT.isWifiDoneConfigure*2ul))))
        #else
        // Blink LED0 (right most one) every second.
        if(TickGet() - t >= TICK_SECOND/2ul)
        #endif // STACK_USE_EZ_CONFIG
        {
            t = TickGet();
            LED0_IO ^= 1;
        }
        */

        // This task performs normal stack task including checking
        // for incoming packet, type of packet and calling
        // appropriate stack entity to process it.
        StackTask();

        // This tasks invokes each of the core stack application tasks
        StackApplications();
        
        // Process command received from Motherboad via SPI interface.
        //ProcessReceivedSpiCmds();

        #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
		ZeroconfLLProcess();
        #endif

        #if defined(STACK_USE_ZEROCONF_MDNS_SD)
        mDNSProcess();
		// Use this function to exercise service update function
		// HTTPUpdateRecord();
        #endif

		// Process application specific tasks here.
		// For this demo app, this will include the Generic TCP 
		// client and servers, and the SNMP, Ping, and SNMP Trap
		// demos.  Following that, we will process any IO from
		// the inputs on the board itself.
		// Any custom modules or processing you need to do should
		// go here.
		#if defined (WIFI_BOARD_FOC_HUB)
		ProcessWiFiTransfers();					// Handles TCP/IP transfers
		DoWiFiWork();							// Handles SPI incoming requests
		#endif

        #if defined(WF_CONSOLE)
		WFConsoleProcess();
		IperfAppCall();
		WFConsoleProcessEpilogue();
		#endif

		#if defined(STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE)
		GenericTCPClient();
		#endif
		
		#if defined(STACK_USE_GENERIC_TCP_SERVER_EXAMPLE)
		GenericTCPServer();
		#endif
		
		#if defined(STACK_USE_SMTP_CLIENT)
		SMTPDemo();
		#endif
		
		#if defined(STACK_USE_ICMP_CLIENT)
		PingDemo();
		#endif
		
		#if defined(STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED)
		//User should use one of the following SNMP demo
		// This routine demonstrates V1 or V2 trap formats with one variable binding.
		SNMPTrapDemo();
		
		#if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3)
		//This routine provides V2 format notifications with multiple (3) variable bindings
		//User should modify this routine to send v2 trap format notifications with the required varbinds.
		//SNMPV2TrapDemo();
		#endif 
		if(gSendTrapFlag)
			SNMPSendTrap();
		#endif
		
		#if defined ( WF_CONSOLE ) && defined ( EZ_CONFIG_SCAN ) 
        WFDisplayScanMgr();
        #endif
		
		#if defined(STACK_USE_BERKELEY_API)
		BerkeleyTCPClientDemo();
		BerkeleyTCPServerDemo();
		BerkeleyUDPClientDemo();
		#endif


        // If the local IP address has changed (ex: due to DHCP lease change)
        // write the new IP address to the LCD display, UART, and Announce 
        // service
		if(dwLastIP != AppConfig.MyIPAddr.Val)
		{
			dwLastIP = AppConfig.MyIPAddr.Val;
			WiFiInfo.CurrentConfigPtr->MyIPAddr.Val = AppConfig.MyIPAddr.Val;
			
			#if defined(STACK_USE_UART)
				putrsUART((ROM char*)"\r\nNew IP Address: ");
			#endif
			
			DisplayIPValue(AppConfig.MyIPAddr);

			#if defined(STACK_USE_UART)
				putrsUART((ROM char*)"\r\n");
			#endif

			#if defined(STACK_USE_ANNOUNCE)
				AnnounceIP();
			#endif

            #if defined(STACK_USE_ZEROCONF_MDNS_SD)
				mDNSFillHostRecord();
			#endif
		}
	}
}
Esempio n. 29
0
/*
 * Main entry point.
 */
void main(void)
{
    static TICK t = 0;
    BYTE c, i;
    WORD w;
    BYTE buf[10];
    
    /*
     * Initialize any application specific hardware.
     */
    InitializeBoard();

    /*
     * Initialize all stack related components.
     * Following steps must be performed for all applications using
     * PICmicro TCP/IP Stack.
     */
    TickInit();

    /*
     * Initialize MPFS file system.
     */
    MPFSInit();

    //Intialize HTTP Execution unit
    htpexecInit();

    //Initialze serial port
    serInit();

    /*
     * Initialize Stack and application related NV variables.
     */
    appcfgInit();
    appcfgUSART();  //Configure the USART
#ifdef SER_USE_INTERRUPT    //Interrupt enabled serial ports have to be enabled
    serEnable();
#endif
    appcfgCpuIO();  // Configure the CPU's I/O port pins
    appcfgADC();    // Configure ADC unit
    appcfgPWM();	// Configure PWM unit

    //Clear Screen
    serPutRomString(AnsiEscClearScreen);

    /*
     * Wait a couple of seconds for user input.
	 * - If something is detected, start config.
	 * - If nothing detected, start main program.
     */
	serPutRomString(PressKeyForConfig);

	for (i = 60; i > 0; --i)	//Delay for 50mS x 60 = 3 sec
	{
		if ((i % 8) == 0) serPutByte('.');
		if (serIsGetReady())
		{
	        SetConfig();
			break;
		}
		DelayMs(50);
	}
	serPutByte('\r');
	serPutByte('\n');

    StackInit();

#if defined(STACK_USE_HTTP_SERVER)
    HTTPInit();
#endif

#if defined(STACK_USE_FTP_SERVER) && defined(MPFS_USE_EEPROM)
    FTPInit();
#endif


#if defined(STACK_USE_DHCP) || defined(STACK_USE_IP_GLEANING)
    if (!AppConfig.Flags.bIsDHCPEnabled )
    {
        /*
         * Force IP address display update.
         */
        myDHCPBindCount = 1;
#if defined(STACK_USE_DHCP)
        DHCPDisable();
#endif
    }
#endif

#if defined( STACK_USE_VSCP )
	vscp2_udpinit();	// init VSCP subsystem
#endif

    /*
     * Once all items are initialized, go into infinite loop and let
     * stack items execute their tasks.
     * If application needs to perform its own task, it should be
     * done at the end of while loop.
     * Note that this is a "co-operative mult-tasking" mechanism
     * where every task performs its tasks (whether all in one shot
     * or part of it) and returns so that other tasks can do their
     * job.
     * If a task needs very long time to do its job, it must broken
     * down into smaller pieces so that other tasks can have CPU time.
     */
    while ( 1 )
    {
        /*
         * Blink SYSTEM LED every second.
         */
        if ( TickGetDiff( TickGet(), t ) >= TICK_SECOND/2 )
        {
            t = TickGet();
            LATB6 ^= 1;
        }

        //Perform routine tasks
        MACTask();

        /*
         * This task performs normal stack task including checking
         * for incoming packet, type of packet and calling
         * appropriate stack entity to process it.
         */
        StackTask();

#if defined(STACK_USE_HTTP_SERVER)
        /*
         * This is a TCP application.  It listens to TCP port 80
         * with one or more sockets and responds to remote requests.
         */
        HTTPServer();
#endif

#if defined(STACK_USE_FTP_SERVER) && defined(MPFS_USE_EEPROM)
        FTPServer();
#endif

        /*
         * In future, as new TCP/IP applications are written, it
         * will be added here as new tasks.
         */

         /*
          * Add your application speicifc tasks here.
          */
        ProcessIO();
       /* 
        XEEBeginRead( EEPROM_CONTROL, 0x0530 );
        while ( 1 ) {
	        c = XEERead();
        	c = 1;
        }
        //c = XEERead();
        XEEEndRead();
        */
#if defined( STACK_USE_VSCP )
		vscp2_Task();
#endif        
        

        /*
         * For DHCP information, display how many times we have renewed the IP
         * configuration since last reset.
         */
        if ( DHCPBindCount != myDHCPBindCount )
        {
            DisplayIPValue(&AppConfig.MyIPAddr, TRUE);
            myDHCPBindCount = DHCPBindCount;
        }
    }
}
Esempio n. 30
0
///////////////////////////////////////////////////////////////////////////////
// Main entry point.
//
void main(void)
{
    static TICK8 t = 0;
    BYTE i;
    char strBuf[10];

    // Initialize any application specific hardware.
    InitializeBoard();

    // Initialize all stack related components.
    // Following steps must be performed for all applications using
    // PICmicro TCP/IP Stack.
    TickInit();

    // Initialize file system.
    fsysInit();

    // Intialize HTTP Execution unit
    htpexecInit();

    // Initialze serial port
    serInit();
    
    // Initialize Stack and application related NV variables.
    appcfgInit();
    appcfgUSART();        	// Configure the USART

#ifdef SER_USE_INTERRUPT    // Interrupt enabled serial ports have to be enabled
    serEnable();
#endif

    appcfgCpuIO();          // Configure the CPU's I/O port pin directions - input or output
    appcfgCpuIOValues();    // Configure the CPU's I/O port pin default values
    appcfgADC();            // Configure ADC unit
	appcfgPWM();			// Configure PWM unit
	
    // Serial configuration menu - display it for configured time and 
    // allow user to enter configuration menu
    scfInit( appcfgGetc( APPCFG_STARTUP_SER_DLY ) );

    StackInit();

#if defined(STACK_USE_HTTP_SERVER)
    HTTPInit();
#endif


#if defined( STACK_USE_DHCP ) || defined( STACK_USE_IP_GLEANING )
    // If DHCP is NOT enabled
    if ( ( appcfgGetc( APPCFG_NETFLAGS ) & APPCFG_NETFLAGS_DHCP ) == 0 ) {
		// Force IP address display update.
        myDHCPBindCount = 1;
        
#if defined( STACK_USE_DHCP )
        DHCPDisable();
#endif
    }
#endif

#if ( DEBUG_MAIN >= LOG_DEBUG )
        debugPutMsg(1); //@mxd:1:Starting main loop
#endif

	// Init VSCP functionality
	vscp_init();

	bInitialized = FALSE;	// Not initialized
    
#if defined(STACK_USE_NTP_SERVER)    
    // Initialize time 
    hour = 0;
	minute = 0;
	second = 0;
#endif	
	
	appcfgPutc( VSCP_DM_MATRIX_BASE, 0x00 );
 	appcfgPutc( VSCP_DM_MATRIX_BASE+1, 0x00 );
 	appcfgPutc( VSCP_DM_MATRIX_BASE+2, 0x00 );
 	appcfgPutc( VSCP_DM_MATRIX_BASE+3, 0x00 );
    
    
	//
    // Once all items are initialized, go into infinite loop and let
    // stack items execute their tasks.
    // If application needs to perform its own task, it should be
    // done at the end of while loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must broken
    // down into smaller pieces so that other tasks can have CPU time.
    //
    while ( 1 ) {
	    
	    // Used for initial delay to give stack and chip some time to
	    // initialize. If not used messages sent during this time will 
	    // fail.
        if  ( TickGet() > ( 5 * TICK_SECOND ) ) {
        	bInitialized = TRUE;
        }
	    
	    // We should do the ftp download every three hours
        //if ( TickGetDiff( TickGet(), loadTime ) >= ( 3 * 3600 * TICK_SECOND ) ) {
	    //	loadTime = TickGet();
	    //	bftpLoadWork = TRUE;
	    //}
	    
        // Blink SYSTEM LED every second.
        if ( appcfgGetc( APPCFG_SYSFLAGS ) & APPCFG_SYSFLAGS_BLINKB6 ) {
            if ( TickGetDiff8bit( t ) >= ((TICK8)( TICKS_PER_SECOND / 2 ) ) ) {
                t = TickGet8bit();
                TRISB_RB6 = 0;
                LATB6 ^= 1;
            }
        }

        // This task performs normal stack task including checking for incoming packet,
        // type of packet and calling appropriate stack entity to process it.
        StackTask();

#if defined(STACK_USE_HTTP_SERVER)
        // This is a TCP application.  It listens to TCP port 80
        // with one or more sockets and responds to remote requests.
        HTTPServer();
#endif

#if defined(STACK_USE_FTP_SERVER)
        FTPServer();
#endif

        // Add your application speicifc tasks here.
        ProcessIO();
        
#if defined(VSCP_USE_TCP )        
        // VSCP Task
        if ( bInitialized ) {
        	vscp_tcp_task();
        }
#endif        
        
        if ( bInitialized ) {
        	vscp_main_task();
			process_can_message();
			if ( g_can_error )
			{
				send_can_error_message( g_can_error );
				g_can_error = 0;
			}
        }
        
#if defined(STACK_USE_NTP_SERVER)        
        if ( bInitialized ) {
        	//ntp_task();
        }	
#endif        

        // For DHCP information, display how many times we have renewed the IP
        // configuration since last reset.
        if ( DHCPBindCount != myDHCPBindCount ) {
#if (DEBUG_MAIN >= LOG_INFO)
        	debugPutMsg( 2 ); 		// @mxd:2:DHCP Bind Count = %D
            debugPutByteHex(DHCPBindCount);
#endif
            
            // Display new IP address
#if (DEBUG_MAIN >= LOG_INFO)
            debugPutMsg( 3 ); 	//@mxd:3:DHCP complete, IP = %D.%D.%D.%D
            debugPutByteHex( AppConfig.MyIPAddr.v[ 0 ] );
            debugPutByteHex( AppConfig.MyIPAddr.v[ 1 ] );
            debugPutByteHex( AppConfig.MyIPAddr.v[ 2 ] );
            debugPutByteHex( AppConfig.MyIPAddr.v[ 3 ] );
#endif
            myDHCPBindCount = DHCPBindCount;
        }
    }
}