Beispiel #1
0
int main() {
	DWORD t = 0;

	//Needed because a bug in picc-18?
	MIWRL=0;
	MIWRH=0;

	TRISA = 0;
	TRISB = 0;
	TRISC = 0;
	TRISD = 0;
	TRISE = 0;
	TRISF = 0;
	TRISG = 0;
	PORTA=0;
	PORTB=0;
	PORTC=0;
	PORTD=0;
	PORTE=0;
	PORTF=0;

	OSCTUNE = 0x40; //Speed up to 41.67 MHz

	//Turn off AD
	ADCON1 = 0x0F;

#if defined(DEBUG) && defined(_18F87J60)
	initUsart2();
#endif

	initTransmitter();
	initReceiver();
	initPwm();
	initInterrupts();
	initAppConfig();
	initWDT();
	TickInit();
	StackInit();
	//Set the LED on the connector
	SetLEDConfig(0x3742); //See MAC.h for the values

	printf("Telldus TellStick Net v%s\r\n", FIRMWARE_VERSION);

	while(1) {
		StackTask();
		StackApplications();
		if(TickGet() - t >= TICK_SECOND) {
			t = TickGet();
		}
#if defined(DEBUG)
		debugTask();
#endif
		rfReceiveTask();
		discoveryTask();
		ClrWdt();
	}
	return 42;
}
Beispiel #2
0
void main()
{
   union {
      unsigned int32 hours;
      unsigned int8 minutes;
      unsigned int8 seconds;} upTime;
   
   
   TICK_TYPE CurrentTick,PreviousUDPTick,PreviousSATick;
   resetStatus = (RCON & 0b00111111) | !(STKPTR & 0b11000000); // Get the Reset Status
   RCON = RCON | 0b00111111; //Reset RCON Reset flags... (Reset Register)
   STKPTR = STKPTR & 0b00111111; // Clear Stack Overflow/Underflow flags
   PortInit(); 
   OutputInit();  
   restart_wdt();
   romEZHRInit();    //set up default ezhr settings
   eeROMinit();      //set up default eprom settings
   IPAddressInit();  //set up MAC and default IP addresses
   delay_ms(500); 
   ADCInit();        //set up ADC ports
   iniADCParams();    
   SerialInit();     //set up serial ports
   TickInit();       //set up tick timer
   enable_interrupts(INT_RDA);
   enable_interrupts(GLOBAL);
   StackInit();   
   WritePHYReg(ERXFCON,EthernetRXfilterSetting); // Allow only uni & multi
   SetLEDConfig(E_LED_CONFIG);   // swap LED's 
   output_high(E_SW_PWR_DN);     // Power Ethernet Switch
   output_high(E_SW_RST);
   output_low(RS485_TXEN);
   output_high(RS485_RXDIS);
   output_high(RS232_F_OFF);
   output_high(RS232_F_ON);
   CurrentTick = PreviousUDPTick = get_ticks();
   UDPSampleRate = eeReadUDPRate() * TICKS_PER_MILLISECOND;
   portControlInit();
   while(TRUE)
   {
      CurrentTick = get_ticks();
      restart_wdt();
      StackTask();
      restart_wdt();
      MyTCPTask();//handles TCP connections
      restart_wdt();
      setIO();// checks voltage status and sets ports accordingly
//!      if(CurrentTick-PreviousUDPTick >= UDPSampleRate)
//!      {
//!         currentRoutine=UDPTASK;
//!         BOOL UDPDone = MyUDPTask();
//!         if(UDPDone) 
//!         {
//!            PreviousUDPTick=CurrentTick;
//!         }
//!      }
      StackApplications();
   }
}
Beispiel #3
0
void SYS_Initialize ( void* data )
{

       /* Initializethe interrupt system  */
    SYS_INT_Initialize();

    /* Initialize the global interrupts */
    SYS_INT_Enable();

    SYS_MSG_MESSAGING_OBJECT oSysMsg;
    SYS_MSG_INIT sSysMsgInit;
    uint16_t nQSizes[] = SYS_MSG_BUFFER_SIZES;

    sSysMsgInit.nMaxMsgsDelivered  = SYS_MSG_MAX_MSGS_DELIVERED;
    sSysMsgInit.nMessagePriorities = SYS_MSG_MAX_PRIORITY+1;
    sSysMsgInit.nQSizes = nQSizes;

    hSysMsg = SYS_MSG_Initialize(iSysMsg,(SYS_OBJ_HANDLE)&sSysMsgInit);
    oSysMsg = *(SYS_MSG_MESSAGING_OBJECT *)hSysMsg;

    hMsgType = SYS_MSG_TypeCreate(iSysMsg, TYPE_TOUCHSCREEN , 0);
    hMailbox = SYS_MSB_MailboxOpen( iSysMsg, (SYS_MSG_RECEIVE_CALLBACK)&TouchMessageCallback );

    SYS_MSG_MailboxMsgAdd(hMailbox,hMsgType);

    /////////////////////////////////////////////////////////////////////////////
    //                  DRIVER SPECIFIC INITIALIZATION DATA
    /////////////////////////////////////////////////////////////////////////////

    // initialize the timer that manages the tick counter
    TickInit();

    /////////////////////////////////////////////////////////////////////////////
    //                  DRIVER SPECIFIC INITIALIZATION DATA
    /////////////////////////////////////////////////////////////////////////////

    GFX_DRV_lcc_Initialize(0); //Initialize the Graphics Driver

    while (handle != 0)
    {
        handle = GFX_DRV_lcc_Open(0);
    }

    GFX_Initialize();

    // initialize the components for Resistive Touch Screen
    TouchInit((void *)0, (void *)0, (void *)0, NULL);

    ImageDecoderInit();

    JPEGInit();                  // Initialize JPEG

    /* Initialize the Application */
    APP_Initialize ( );
    
}
Beispiel #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();
	}
}
Beispiel #5
0
int main( void )
{
    GOL_MSG msg;                                    // GOL message structure to interact with GOL

    RGBMapColorPins();

    TRISBbits.TRISB1 = 0; // Debug
    LATBbits.LATB1   = 0;

    #ifdef USE_FRC
        OSCCON = 0x1102;    // Enable secondary oscillator, use FRC oscillator
        CLKDIV = 0x0000;    // FRC post-scaler (1:1), USB postscaler (1:1), CPU postscaler (1:1)
    #else
        #ifdef GO_SLOW
            OSCCON = 0x3302;    // Enable secondary oscillator, use HS oscillator
            CLKDIV = 0x0080;    // (not needed - FRC post-scaler (1:1)), USB postscaler (4:1), CPU postscaler (1:1)
        #else
            OSCCON = 0x3302;    // Enable secondary oscillator, use HS oscillator
            CLKDIV = 0x0000;    // (not needed - FRC post-scaler (1:1)), USB postscaler (1:1), CPU postscaler (1:1)
        #endif
    #endif
    RCON = 0;

    // Initialize USB Embedded Host
    USBInitialize( 0 );

    // Initialize the RTCC
    RTCCInit();

    // Initialize the graphics library
    GOLInit();

    // Initialize the touch pads.
    CTMUInit();

    // Initialize the reference timer.
    TickInit();


    while (1)
    {
        if (GOLDraw())                          // Draw the screen
        {
            TouchSenseButtonsMsg( &msg );       // Get a raw touchpad message
            if ((msg.uiEvent != EVENT_INVALID) && ((tick - displayChangeTime) > MESSAGE_DEAD_TIME))
            {
                TranslateTouchpad( &msg );      // Translate the raw message
                GOLMsg( &msg );                 // Process the message
            }
        }
    }
}
bool platform_initialize() {
    uint32_t lastIp;
    nabto_stamp_t timeout;

    // Configure TCP/IP stack stuff
    AppConfig.Flags.bIsDHCPEnabled = true;
    AppConfig.Flags.bInConfigMode = true;
    AppConfig.MyIPAddr.Val = MY_DEFAULT_IP_ADDR_BYTE1 | MY_DEFAULT_IP_ADDR_BYTE2 << 8ul | MY_DEFAULT_IP_ADDR_BYTE3 << 16ul | MY_DEFAULT_IP_ADDR_BYTE4 << 24ul;
    AppConfig.DefaultIPAddr.Val = AppConfig.MyIPAddr.Val;
    AppConfig.MyMask.Val = MY_DEFAULT_MASK_BYTE1 | MY_DEFAULT_MASK_BYTE2 << 8ul | MY_DEFAULT_MASK_BYTE3 << 16ul | MY_DEFAULT_MASK_BYTE4 << 24ul;
    AppConfig.DefaultMask.Val = AppConfig.MyMask.Val;
    AppConfig.MyGateway.Val = MY_DEFAULT_GATE_BYTE1 | MY_DEFAULT_GATE_BYTE2 << 8ul | MY_DEFAULT_GATE_BYTE3 << 16ul | MY_DEFAULT_GATE_BYTE4 << 24ul;
    AppConfig.PrimaryDNSServer.Val = MY_DEFAULT_PRIMARY_DNS_BYTE1 | MY_DEFAULT_PRIMARY_DNS_BYTE2 << 8ul | MY_DEFAULT_PRIMARY_DNS_BYTE3 << 16ul | MY_DEFAULT_PRIMARY_DNS_BYTE4 << 24ul;
    AppConfig.SecondaryDNSServer.Val = MY_DEFAULT_SECONDARY_DNS_BYTE1 | MY_DEFAULT_SECONDARY_DNS_BYTE2 << 8ul | MY_DEFAULT_SECONDARY_DNS_BYTE3 << 16ul | MY_DEFAULT_SECONDARY_DNS_BYTE4 << 24ul;

    TickInit();
    
    StackInit();

    
    unabto_microchip_arp_reset();
    

// Wait for dhcp.
    lastIp = AppConfig.MyIPAddr.Val;

#if ENABLE_DHCP_BUG_WORKAROUND == 1
    nabtoSetFutureStamp(&timeout, 5000);
#endif

    NABTO_LOG_DEBUG(("Acquiring IP from DHCP server..."));

    while (lastIp == AppConfig.MyIPAddr.Val) {
        StackTask();

#if ENABLE_DHCP_BUG_WORKAROUND == 1
        if (nabtoIsStampPassed(&timeout)) {
            Reset();
        }
#endif
    }

    READ_U32(lastIp, &AppConfig.MyIPAddr.Val);

    NABTO_LOG_DEBUG(("Got IP from DHCP server: "PRIip, MAKE_IP_PRINTABLE(lastIp)));

    return true;
}
Beispiel #7
0
void MyWIFI_Start(void) {
        
    // Initialize stack-related hardware components
    TickInit();
    #if defined(STACK_USE_MPFS2)
        MPFSInit();
    #endif

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

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

    // Connect to the my WIFI Network
    MyWIFI_Connect();
}
Beispiel #8
0
void EthernetInit(void)
{
	// Initialize hardware
	InitBoard();

    // 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();

	// Seed the LFSRRand() function.
	LFSRSeedRand(GenerateRandomDWORD());

	// Initialize the MAC library.
    MACInit();

	// Initialize the ARP library.
    ARPInit();

	// Initialize UDP.
    UDPInit();

	// Open up a socket for our UDP server.
	localServerSocket = UDPOpenEx(NULL, UDP_OPEN_SERVER, UDP_SERVER_PORT, UDP_SERVER_PORT);
	if (localServerSocket == INVALID_UDP_SOCKET) {
		FATAL_ERROR();
	}

	// Open up a socket for our UDP client.
	remoteServerSocket = UDPOpenEx(NULL, UDP_OPEN_IP_ADDRESS, UDP_CLIENT_PORT, UDP_CLIENT_PORT);
	if (remoteServerSocket == INVALID_UDP_SOCKET) {
		FATAL_ERROR();
	}
}
/*****************************************************************************
 FUNCTION 	GSMTask
			Main function to handle the HiLo stack
 
 RETURNS  	None
 
 PARAMS		None
*****************************************************************************/
void GSMTask()
{
	//	Function pointers for the callback function of the HiLo stack 
	FP_GSM[1] = cSMSSend;
	FP_GSM[2] = cSMSRead;
	FP_GSM[3] = cSMSDelete;

	FP_GSM[5] = cSMTPParamsClear;
	FP_GSM[6] = cSMTPParamsSet;
	FP_GSM[7] = cSMTPEmailTo;
	FP_GSM[8] = cSMTPEmailSend;
	FP_GSM[10] = cCALLHangUp;
	FP_GSM[11] = cCALLVoiceStart;
	FP_GSM[12] = cFTPConfig;
	FP_GSM[13] = cFTPReceive;
	FP_GSM[14] = cFTPSend;
	FP_GSM[15] = cFTPDelete;
	
	FP_GSM[17] = cLLWrite;
	FP_GSM[18] = cLLModeEnable;		// it will be executed only if Standard mode is enabled
	FP_GSM[19] = cSTDModeEnable;	// it will be executed only if LowLevel mode is enabled
	FP_GSM[20] = cTCPClientOpen;
	FP_GSM[21] = cTCPClientClose;
	FP_GSM[22] = cTCPStatus;
	FP_GSM[23] = cTCPWrite;
	FP_GSM[24] = cTCPRead;
	FP_GSM[25] = cTCPRxFlush;
	FP_GSM[26] = cAPNConfig;
	FP_GSM[27] = cHTTPRequest;
	FP_GSM[28] = cGSMHibernate;
	FP_GSM[29] = cGSMOn;
	FP_GSM[30] = cFSWrite;
	FP_GSM[31] = cFSRead;
	FP_GSM[32] = cFSDelete;
	FP_GSM[33] = cFSSize;
	FP_GSM[34] = cFSAppend;
	
	
	// Initialization of tick only at the startup of the device
	if (hFlyTask == NULL)
	{
	    TickInit();
	}  
	
	if (hFlyTask == NULL)
	{
		#if defined	(STACK_USE_UART)
		UARTWrite(1, "Flyport GPRS/3G starting...\r\n");
		UARTWrite(1, "setting up HiLo module...\r\n");
		#endif
		
		// Enter Standard Mode:
		while(HiloStdModeOn(baudComp[7])); // 115200 baud...
	}
	
	if (hFlyTask == NULL)
	{
		//	Creates the task dedicated to user code
		xTaskCreate(FlyportTask,(signed char*) "FLY" , (configMINIMAL_STACK_SIZE *4 ), 
		NULL, tskIDLE_PRIORITY + 1, &hFlyTask);	

		//xTaskHandle hPostTask;
		//xTaskCreate(PostTask,(signed char*) "Post" , (configMINIMAL_STACK_SIZE * 4), NULL, tskIDLE_PRIORITY + 1, &hPostTask);
	}

//-------------------------------------------------------------------------------------------
//|							--- COOPERATIVE MULTITASKING LOOP ---							|
//-------------------------------------------------------------------------------------------
    while(1)
    {
	    switch(mainGSMStateMachine)
	    {
	    	case SM_GSM_IDLE:
	    		GSMUnsol(NO_ERR);
	    		// Check on the queue to verify if other task have requested some stack function
				xStatus = xQueueReceive(xQueue,&Cmd,0);
				CmdCheck(OP_EXECUTION);
				break;
			
			case SM_GSM_CMD_PENDING:
				GSMUnsol(CMD_UNEXPECTED);
	    		// Check on the queue to verify if other task have requested some stack function
				CmdCheck(OP_EXECUTION);
				break;
			
			case SM_GSM_LL_MODE:
				CmdCheck(OP_LL);
				break;
				
			case SM_GSM_HW_FAULT:
				mainGSM.HWReady = FALSE;
				HiloReset();
				
				// Enter Standard Mode:
				while(HiloStdModeOn(baudComp[7])); // 115200 baud...
				
				mainGSMStateMachine = SM_GSM_IDLE;
				mainOpStatus.Function = 0;
				mainOpStatus.ExecStat = OP_SUCCESS;
				mainOpStatus.ErrorCode = 0;
				mainGSM.HWReady = TRUE;
				break;
				
			case SM_GSM_HIBERNATE:
				// GSMUnsol(NO_ERR);
				// Accept only function 29 (cGSMOn)
				if(mainOpStatus.Function == 29)
					CmdCheck(OP_EXECUTION);
				else if(mainOpStatus.Function != 0)
				{
					mainOpStatus.ExecStat = OP_HIB_ERR;
					mainOpStatus.Function = 0;
					mainOpStatus.ErrorCode = -1;
				}
				break;
	    }
		
		//UARTWrite(1, " U.c ");
		SampleTask();
		
	}
}
Beispiel #10
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
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    }
}
Beispiel #11
0
//
// Main application entry point.
//
int main(void)
{
	static DWORD t = 0;

	// Initialize application specific hardware
	InitializeBoard();

 	//Initialize the DB_UTILS IO channel
	/* Must add "PIC32_STARTER_KIT" macro definition to the project
      * build options for the C compiler for debug output to work. */
	DBINIT();
	
    // Display the introduction
    DBPRINTF("Smart Outlet Started\n");
	fprintf(stdout, "stdout up\n");
	fprintf(stderr, "stderr up\n");

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

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

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

	// Initialize any application-specific modules or functions/
	// SmartWall Init
	/* Local Temp Vars */
    unsigned int i = 0;

    /* Setup Temporary Processor Storage Vars */
    /* Chan Storage */
    struct SWChannelEntry tmpChnEntries[MYSWCHAN];
    memset(&tmpChnEntries, 0, sizeof(tmpChnEntries));
    struct SWChannelData tmpChnData;
    memset(&tmpChnData, 0, sizeof(tmpChnData));
    union outletChanArg tmpChanArgs[MYSWCHAN];
    memset(&tmpChanArgs, 0, sizeof(tmpChanArgs));
    tmpChnData.data = tmpChnEntries;
    /* Init chanData Buffer */
    for(i = 0; i < MYSWCHAN; i++){
        tmpChnData.data[i].chanValue = &(tmpChanArgs[i]);
    }
    struct SWChannelLimits limits;
    limits.maxNumChan = MYSWCHAN;
    limits.maxDataLength = sizeof(*tmpChanArgs);
    
    /* Setup Processors */
    struct SWDevProcessor processors[NUMOUTLETPROCESSORS];
    memset(processors, 0, sizeof(processors));
    processors[0].processorScope = SW_SCP_CHANNEL;
    processors[0].data = &tmpChnData;
    processors[0].dataLimits = &limits;
    processors[0].decoder = (readSWBody)readSWChannelBody;
    processors[0].handeler = (swDevHandeler)outletChnDevHandeler;
    processors[0].encoder = (writeSWBody)writeSWChannelBody;
    
    /* Setup State Vars */
    struct outletDeviceState myState;
    memset(&myState, 0, sizeof(myState));
    outletChanState_t chState[MYSWCHAN];
    memset(&chState, 0, sizeof(chState));
    outletChanPower_t chPower[MYSWCHAN];
    memset(&chPower, 0, sizeof(chPower));
    struct SWDeviceInfo myDevice;
    memset(&myDevice, 0, sizeof(myDevice));
    myState.myDev = &myDevice;
    myState.chState = chState;
    myState.chPower = chPower;
    enum SWReceiverState machineState = RST_SETUP;
    
    /* Setup SW Vars */
    struct SWDeviceInfo tgtDevice;
    myState.myDev->devInfo.swAddr = MYSWADDRESS;
    myState.myDev->devInfo.devTypes = MYSWTYPE;
    myState.myDev->devInfo.numChan = MYSWCHAN;
    myState.myDev->devInfo.version = SW_VERSION;
    myState.myDev->devInfo.uid = MYSWUID;
    myState.myDev->devInfo.groupID = MYSWGROUP;
    
    /* My IP */
    myState.myDev->devIP.sin_family = AF_INET;
    myState.myDev->devIP.sin_port = LISTENPORT;
    myState.myDev->devIP.sin_addr.s_addr = hton32(INADDR_ANY);
    tgtDevice.devIP.sin_family = AF_INET;
    tgtDevice.devIP.sin_port = SENDPORT;
    tgtDevice.devIP.sin_addr.s_addr = hton32(INADDR_ANY);

	// 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();

		// Process application specific tasks here.
		// Any custom modules or processing you need to do should
		// go here.
        machineState = swReceiverStateMachine(machineState,
                                            myState.myDev, &tgtDevice,
                                            &myState,
                                            processors, NUMOUTLETPROCESSORS);

		updateDeviceState(&myState);

	}
}
/*
 * 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;
        }
    }
}
Beispiel #13
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();


        }

    }
}
void main(void)
{
    static DWORD currentTick = 0;
	static DWORD bsdTick = 0;
    static DWORD dwLastIP = 0;
	UINT8 i;

    // Initialize application specific hardware
    BRD_init();

    // 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();

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

   

	#ifdef __MODBUS__
	APP_init( );
	UART_init( 62500 );
	#endif

	EnableInterrupts( );

/*	for( i = 0; i < 26; i++ )
	{
		UART_write( 'A' + i );
		UART_transmit();
	}*/



    // 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 lgong 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() - currentTick >= TICK_SECOND/2ul)
        {
            currentTick = TickGet();
//			COM_task( );
 //           LED0_IO ^= 1;
//			TxData = TRUE;
        }

        // 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.
        // 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(STACK_USE_ICMP_CLIENT)
        PingDemo();
        #endif
     
        #if defined(STACK_USE_BERKELEY_API)
       // BerkeleyTCPClientDemo();
		if(TickGet() - bsdTick >= TICK_SECOND)
        {
			bsdTick = currentTick;
            BerkeleyTCPServerDemo();
        }
        
        //BerkeleyUDPClientDemo();
        #endif

      

		#ifdef __MODBUS__
		eMBPoll( );
		COM_task( );

		#endif
	
    }
}
Beispiel #15
0
/////////////////////////////////////////////////////////////////////////////
// Function: InitializeBoard()
// Input: none
// Output: none
// Overview: Initializes the hardware components including the PIC device
//           used.
/////////////////////////////////////////////////////////////////////////////
void InitializeBoard(void)
{    
     CLKDIVbits.RCDIV = 0;
     CLKDIVbits.DOZE = 0;
     CLKDIVbits.PLLEN = 1;
     CLKDIVbits.CPDIV = 0;
     OSCCONbits.COSC = 0b001;
     
     ANSA = 0x0000;
     ANSB = 0x0000;
     ANSC = 0x0010;		// RC4 as touch screen X+
     ANSD = 0x0000;
     ANSE = 0x0200;		// RE9 used as Y+
     ANSF = 0x0000;
     ANSG = 0x0000;
	
	LED_TRIS = 0;
	
    // Initialize graphics library and create default style scheme for GOL
    GOLInit();
	_DPTEST = 0b00;
	
	i2cInit();
	SPI1CON1 = 0b0000000100111110;
    SPI1STAT = 0x8000;
    
    RFIF = 0;
    if( RF_INT_PIN == 0 )
    {
        RFIF = 1;
    }

    //The following are PIC device specific settings for the SPI channel
    //used. 
    //Set IOs directions for SST25 SPI
        SST25_CS_LAT = 1;
        Nop();
        SST25_CS_TRIS = 0;

        SST25_SCK_TRIS = 0;
        Nop();
        SST25_SDO_TRIS = 0;
        Nop();
        SST25_SDI_TRIS = 1;

		//radio pins
		_RP11R = 8; // assign RP11 for SCK1
     	_RP2R = 7; // assign RP2 for SDO1
     	_SDI1R = 36; // assign RP36 for SDI1
     	_INT1R = 37;
    // set the peripheral pin select for the PSI channel used
        __builtin_write_OSCCONL(OSCCON & 0xbf); // unlock PPS
    	#if (SST25_SPI_CHANNEL == 1)
    	    RPOR3bits.RP6R = 8;                 // assign RP6 for SCK1
    	    RPOR9bits.RP18R = 7;                 // assign RP18 for SDO1
    	    RPINR20bits.SDI1R = 32;              // assign RP18 for SDI1
        #elif (SST25_SPI_CHANNEL == 2)
            _RP6R = 11;                // assign RP11 for SCK2
    	    _RP18R = 10;                // assign RP2 for SDO2
    	    _SDI2R = 32;              // assign RP36 for SDI2
    	#endif
		

     	
        __builtin_write_OSCCONL(OSCCON | 0x40); // lock   PPS
	
	//radio
	PHY_CS_TRIS = 0;
    Nop();
    PHY_CS = 1;
    Nop();
    PHY_RESETn_TRIS = 0;
    PHY_RESETn = 1;
    RF_INT_TRIS = 1;
    SDI_TRIS = 1;
    SDO_TRIS = 0;
    SCK_TRIS = 0;
    SPI_SDO = 0;        
    SPI_SCK = 0; 
    PHY_WAKE_TRIS = 0;
    PHY_WAKE = 1;
    
	LED = 1;
	TRISAbits.TRISA1 = 0;
	Nop();
	PORTAbits.RA1 = 1;
	
	// initialize the Flash Memory driver
    FlashInit(&SPI_Init_Data);
    LED = 0;
    // initialize the timer that manages the tick counter
    TickInit(); 
                     
    // initialize the components for Resistive Touch Screen
    TouchInit(NVMWrite, NVMRead, NVMSectorErase, TOUCH_INIT_VALUES);
    LED = 0;
}    
Beispiel #16
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
		}
	}
}
Beispiel #17
0
int main(void)
{
    GOL_MSG msg;                    // GOL message structure to interact with GOL
    
    Nop();
    
    #if defined(PIC24FJ256DA210_DEV_BOARD)
    
    _ANSG8 = 0; /* S1 */
    _ANSE9 = 0; /* S2 */
    _ANSB5 = 0; /* S3 */
        
    #else
    /////////////////////////////////////////////////////////////////////////////
    // ADC Explorer 16 Development Board Errata (work around 2)
    // RB15 should be output
    /////////////////////////////////////////////////////////////////////////////
	#ifndef MULTI_MEDIA_BOARD_DM00123
    LATBbits.LATB15 = 0;
    TRISBbits.TRISB15 = 0;
    #endif
	#endif
    /////////////////////////////////////////////////////////////////////////////
    #if defined(__dsPIC33F__) || defined(__PIC24H__)

    // Configure Oscillator to operate the device at 40Mhz
    // Fosc= Fin*M/(N1*N2), Fcy=Fosc/2
    // Fosc= 8M*40(2*2)=80Mhz for 8M input clock
    PLLFBD = 38;                    // M=40
    CLKDIVbits.PLLPOST = 0;         // N1=2
    CLKDIVbits.PLLPRE = 0;          // N2=2
    OSCTUN = 0;                     // Tune FRC oscillator, if FRC is used

    // Disable Watch Dog Timer
    RCONbits.SWDTEN = 0;

    // Clock switching to incorporate PLL
    __builtin_write_OSCCONH(0x03);  // Initiate Clock Switch to Primary

    // Oscillator with PLL (NOSC=0b011)
    __builtin_write_OSCCONL(0x01);  // Start clock switching
    while(OSCCONbits.COSC != 0b011);

    // Wait for Clock switch to occur	
    // Wait for PLL to lock
    while(OSCCONbits.LOCK != 1)
    { };
    
    // Set PMD0 pin functionality to digital
    AD1PCFGL = AD1PCFGL | 0x1000;
    
    #elif defined(__PIC32MX__)
    INTEnableSystemMultiVectoredInt();
    SYSTEMConfigPerformance(GetSystemClock());
    #ifdef MULTI_MEDIA_BOARD_DM00123
    CPLDInitialize();
    CPLDSetGraphicsConfiguration(GRAPHICS_HW_CONFIG);
    CPLDSetSPIFlashConfiguration(SPI_FLASH_CHANNEL);
    #endif // #ifdef MULTI_MEDIA_BOARD_DM00123
    #endif // #if defined(__dsPIC33F__) || defined(__PIC24H__)

    GOLInit();                      // initialize graphics library &
                                    // create default style scheme for GOL

    #if defined (GFX_PICTAIL_V1) || defined (GFX_PICTAIL_V2)
    EEPROMInit();                   // initialize Exp.16 EEPROM SPI
    BeepInit();
    #else
	    #if defined (USE_SST25VF016)
            SST25Init();            // initialize GFX3 SST25 flash SPI
        #endif
    #endif
    
    TouchInit();                    // initialize touch screen
    HardwareButtonInit();           // Initialize the hardware buttons

    // create default style scheme for GOL
    TickInit();                     // initialize tick counter (for random number generation)

    // create default style scheme for GOL
    #if defined(__dsPIC33FJ128GP804__) || defined(__PIC24HJ128GP504__)

    // If S3 button on Explorer 16 board is pressed calibrate touch screen
    TRISAbits.TRISA9 = 1;
    if(PORTAbits.RA9 == 0)
    {
        TRISAbits.TRISA9 = 0;
        TouchCalibration();
        TouchStoreCalibration();
    }

    TRISAbits.TRISA9 = 0;
	#else

	    /**
	     * Force a touchscreen calibration by pressing the switch
	     * Explorer 16 + GFX PICTail    - S3 (8 bit PMP)
	     * Explorer 16 + GFX PICTail    - S5 (16 bit PMP)
	     * Starter Kit + GFX PICTail    - S0 (8 bit PMP)
	     * Multimedia Expansion Board   - Fire Button
	     * DA210 Developement Board     - S1
	     * NOTE:    Starter Kit + GFX PICTail will switches are shared
	     *          with the 16 bit PMP data bus.
	     **/
	    if(GetHWButtonTouchCal() == HW_BUTTON_PRESS)
	    {
	        TouchCalibration();
	        TouchStoreCalibration();
	    }
    #endif

    // If it's a new board (EEPROM_VERSION byte is not programed) calibrate touch screen
    #if defined (GFX_PICTAIL_V1) || defined (GFX_PICTAIL_V2)
    if(GRAPHICS_LIBRARY_VERSION != EEPROMReadWord(ADDRESS_VERSION))
    {
        TouchCalibration();
        TouchStoreCalibration();
    }

    #else
        #if defined (USE_SST25VF016)
        if(GRAPHICS_LIBRARY_VERSION != SST25ReadWord(ADDRESS_VERSION))
        {
            TouchCalibration();
            TouchStoreCalibration();
        }
        #elif defined (USE_SST39LF400)
        WORD tempArray[12], tempWord = 0x1234;

        SST39LF400Init(tempArray);
        tempWord = SST39LF400ReadWord(ADDRESS_VERSION);
        SST39LF400DeInit(tempArray);

        if(GRAPHICS_LIBRARY_VERSION != tempWord)
        {
            TouchCalibration();
            TouchStoreCalibration();
        }
        #endif
    #endif

    // Load touch screen calibration parameters from memory
    TouchLoadCalibration();

    GDDDemoCreateFirstScreen();

    while(1)
    {
        if(GOLDraw())               // Draw GOL object
        {
            TouchGetMsg(&msg);      // Get message from touch screen
			
            #if (NUM_GDD_SCREENS > 1)
			// GDD Readme:
			// The following line of code allows a GDD user to touch the touchscreen
			// to cycle through different static screens for viewing. This is useful as a
			// quick way to view how each screen looks on the physical target hardware.
			// This line of code should eventually be commented out for actual development.
			// Also note that widget/object names can be found in GDD_Screens.h
			if(msg.uiEvent == EVENT_RELEASE) GDDDemoNextScreen();
			#endif
			
            GOLMsg(&msg);           // Process message
        }
    }//end while
}
Beispiel #18
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();

    }
}
Beispiel #19
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
		}
	}
}
Beispiel #20
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
        }
    }
}
Beispiel #21
0
/*****************************************************************************
 FUNCTION 	TCPIPTask
			Main function to handle the TCPIP stack
 
 RETURNS  	None
 
 PARAMS		None
*****************************************************************************/
void TCPIPTask()
{
	WFConnection = WF_CUSTOM;
	ConnectionProfileID = 0;
	static DWORD dwLastIP = 0;
	WFStatus = NOT_CONNECTED;
	dwLastIP = 0;
	//	Function pointers for the callback function of the TCP/IP and WiFi stack 

#if defined (FLYPORT)
	FP[1] = cWFConnect;
	FP[2] = cWFDisconnect;
	FP[3] = cWFScan;
	FP[5] = cWFPsPollDisable;
	FP[6] = cWFPsPollEnable;
	FP[7] = cWFScanList;
	FP[10] = cWFStopConnecting;
	
#endif
#if defined (FLYPORTETH)
	FP[1] = cETHRestart;
#endif
	FP[16] = cTCPRxFlush;
	FP[17] = cTCPpRead;
	FP[18] = cTCPRemote;
	FP[19] = cTCPServerDetach;
	FP[20] = cTCPGenericOpen;
	FP[21] = cTCPRead;
	FP[22] = cTCPWrite;
	FP[23] = cTCPGenericClose;
	FP[24] = cTCPisConn;
	FP[25] = cTCPRxLen;


	#if defined(STACK_USE_SMTP_CLIENT)
	FP[26] = cSMTPStart;
	FP[27] = cSMTPSetServer;
	FP[28] = cSMTPSetMsg;
	FP[29] = cSMTPSend;
	FP[30] = cSMTPBusy;
	FP[31] = cSMTPStop;
	FP[32] = cSMTPReport;
	#endif
	
	FP[ARP_RESOLVE] = cARPResolveMAC;
	#if MAX_UDP_SOCKETS_FREERTOS>0	
	FP[35] = cUDPGenericOpen;
	FP[36] = cUDPWrite;
	FP[37] = cUDPGenericClose;
	#endif
	
	// Initialize stack-related hardware components that may be 
	// required by the UART configuration routines
	
	// Initialization of tick only at the startup of the device
	if (hFlyTask == NULL)
	{
	    TickInit();
	}
	#if defined(STACK_USE_MPFS) || defined(STACK_USE_MPFS2)
	MPFSInit();
	#endif
	
	// Initialize Stack and application related NV variables into AppConfig.
	InitAppConfig();

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

	if (hFlyTask == NULL)
	{
		NETConf[0] = AppConfig;
		NETConf[1] = AppConfig;
	}
	
	#if defined(WF_CS_TRIS)
	if (WFStatus == CONNECTION_LOST)	
		WF_Connect(WFConnection);
    #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

	//	INITIALIZING UDP
	#if MAX_UDP_SOCKETS_FREERTOS>0
	#if defined	(STACK_USE_UART)
	UARTWrite(1, "Initializing UDP...\r\n");
	#endif
	UDPInit();
	activeUdpSocket=0;
	while (activeUdpSocket < MAX_UDP_SOCKETS_FREERTOS) 
	{
		tmp_len[activeUdpSocket]=0;
		if (activeUdpSocket == 0) 
		{
			BUFFER_UDP_LEN[0] = BUFFER1_UDP_LEN;
			udpBuffer[activeUdpSocket] = udpBuffer1;
			udpSocket[0] = INVALID_UDP_SOCKET;
		}
		#if MAX_UDP_SOCKETS_FREERTOS>1
		if (activeUdpSocket == 1)
		{
			BUFFER_UDP_LEN[1] = BUFFER2_UDP_LEN;
			udpBuffer[activeUdpSocket] = udpBuffer2;
			udpSocket[1] = INVALID_UDP_SOCKET;
		}
		#endif
		#if MAX_UDP_SOCKETS_FREERTOS>2
		if (activeUdpSocket == 2)
		{
			BUFFER_UDP_LEN[2] = BUFFER3_UDP_LEN;
			udpBuffer[activeUdpSocket] = udpBuffer3;
			udpSocket[2] = INVALID_UDP_SOCKET;
		}
		#endif
		#if MAX_UDP_SOCKETS_FREERTOS>3
		if (activeUdpSocket == 3)
		{
			BUFFER_UDP_LEN[3] = BUFFER4_UDP_LEN;
			udpBuffer[activeUdpSocket] = udpBuffer4;
			udpSocket[3] = INVALID_UDP_SOCKET;
		}
		#endif
		p_udp_wifiram[activeUdpSocket] = udpBuffer[activeUdpSocket];
		p_udp_data[activeUdpSocket] = udpBuffer[activeUdpSocket];
		activeUdpSocket++;
	}
	#endif
	if (hFlyTask == NULL)
	{
		//	Creates the task dedicated to user code
		xTaskCreate(FlyportTask,(signed char*) "FLY" , (configMINIMAL_STACK_SIZE * 4), 
		NULL, tskIDLE_PRIORITY + 1, &hFlyTask);	
	}
//-------------------------------------------------------------------------------------------
//|							--- COOPERATIVE MULTITASKING LOOP ---							|
//-------------------------------------------------------------------------------------------
    while(1)
    {
        #if defined (FLYPORT)
		if (WFStatus != TURNED_OFF)
		{
			//	Check to verify the connection. If it's lost or failed, the device tries to reconnect
			if ((WFStatus == CONNECTION_LOST) || (WFStatus == CONNECTION_FAILED)) 	
				WF_Connect(WFConnection);
        #else
        {
        #endif
				
				
	        // This task performs normal stack task including checking
	        // for incoming packet, type of packet and calling
	        // appropriate stack entity to process it.
			vTaskSuspendAll();
			StackTask();
			xTaskResumeAll();
			#if defined(STACK_USE_HTTP_SERVER) || defined(STACK_USE_HTTP2_SERVER)
			vTaskSuspendAll();
			HTTPServer();
			xTaskResumeAll();
			#endif
			// 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
	
			#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)
			//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
			
			// Check on the queue to verify if other task have requested some stack function
			xStatus = xQueueReceive(xQueue,&Cmd,0);
			CmdCheck();
	
	        // 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)
					UARTWrite(1,"\r\nNew IP Address: ");
				#endif

				DisplayIPValue(AppConfig.MyIPAddr);
	
				#if defined(STACK_USE_UART)
					UARTWrite(1,"\r\n");
				#endif
	
	
				#if defined(STACK_USE_ANNOUNCE)
					AnnounceIP();
				#endif
	
	            #if defined(STACK_USE_ZEROCONF_MDNS_SD)
					mDNSFillHostRecord();
				#endif
			}
		} //end check turnoff	
	}
}
Beispiel #22
0
/////////////////////////////////////////////////////////////////////////////
// Function: InitializeBoard()
// Input: none
// Output: none
// Overview: Initializes the hardware components including the PIC device
//           used.
/////////////////////////////////////////////////////////////////////////////
void InitializeBoard(void)
{
        /////////////////////////////////////////////////////////////////////////////
        // ADC Explorer 16 Development Board Errata (work around 2)
        // RB15 should be output
        /////////////////////////////////////////////////////////////////////////////
            LATBbits.LATB15 = 0;
            TRISBbits.TRISB15 = 0;

    #if defined(__dsPIC33F__) || defined(__PIC24H__)

        // Configure Oscillator to operate the device at 40Mhz
        // Fosc= Fin*M/(N1*N2), Fcy=Fosc/2
        // Fosc= 8M*40(2*2)=80Mhz for 8M input clock
        PLLFBD = 38;                    // M=40
        CLKDIVbits.PLLPOST = 0;         // N1=2
        CLKDIVbits.PLLPRE = 0;          // N2=2
        OSCTUN = 0;                     // Tune FRC oscillator, if FRC is used
    
        // Disable Watch Dog Timer
        RCONbits.SWDTEN = 0;
    
        // Clock switching to incorporate PLL
        __builtin_write_OSCCONH(0x03);  // Initiate Clock Switch to Primary
    
        // Oscillator with PLL (NOSC=0b011)
        __builtin_write_OSCCONL(0x01);  // Start clock switching
        while(OSCCONbits.COSC != 0b011);
    
        // Wait for Clock switch to occur	
        // Wait for PLL to lock
        while(OSCCONbits.LOCK != 1)
        { };
        
        // Set PMD0 pin functionality to digital
        AD1PCFGL = AD1PCFGL | 0x1000;

        #if defined(__dsPIC33FJ128GP804__) || defined(__PIC24HJ128GP504__)
            AD1PCFGLbits.PCFG6 = 1;
            AD1PCFGLbits.PCFG7 = 1;
            AD1PCFGLbits.PCFG8 = 1;
        #endif
        
    #elif defined(__PIC32MX__)
        INTEnableSystemMultiVectoredInt();
        SYSTEMConfigPerformance(GetSystemClock());
    #endif // #if defined(__dsPIC33F__) || defined(__PIC24H__)
    

    #if defined (EXPLORER_16)
/************************************************************************
* For Explorer 16 RD12 is connected to EEPROM chip select.
* To prevent a conflict between this EEPROM and SST25 flash
* the chip select of the EEPROM SPI should be pulled up.
************************************************************************/
        // Set IOs directions for EEPROM SPI
        MCHP25LC256_CS_LAT = 1;			    // set initial CS value to 1 (not asserted)
    	MCHP25LC256_CS_TRIS = 0;			// set CS pin to output
	#endif // #if defined (EXPLORER_16)


     //The following are PIC device specific settings for the SPI channel
     //used. 
    
     //Set IOs directions for SST25 SPI   
        SST25_CS_LAT = 1;
        SST25_CS_TRIS = 0;
 
       #ifndef __PIC32MX__
            SST25_SCK_TRIS = 0;
            SST25_SDO_TRIS = 0;
            SST25_SDI_TRIS = 1;
            #if defined(__PIC24FJ256GB210__)
            	SST25_SDI_ANS = 0;
    	    #endif
       #endif
    // set the peripheral pin select for the PSI channel used
    #if defined(__dsPIC33FJ128GP804__) || defined(__PIC24HJ128GP504__)
        AD1PCFGL = 0xFFFF;
        RPOR9bits.RP18R = 11;                   // assign RP18 for SCK2
        RPOR8bits.RP16R = 10;                   // assign RP16 for SDO2
        RPINR22bits.SDI2R = 17;                 // assign RP17 for SDI2	
    #elif defined(__PIC24FJ256GB110__) || defined(__PIC24FJ256GA110__) || defined (__PIC24FJ256GB210__)
        __builtin_write_OSCCONL(OSCCON & 0xbf); // unlock PPS
        RPOR10bits.RP21R = 11;                  // assign RP21 for SCK2
        RPOR9bits.RP19R = 10;                   // assign RP19 for SDO2
        RPINR22bits.SDI2R = 26;                 // assign RP26 for SDI2
        __builtin_write_OSCCONL(OSCCON | 0x40); // lock   PPS
    #elif defined(__PIC24FJ256DA210__)

        __builtin_write_OSCCONL(OSCCON & 0xbf); // unlock PPS

    	#if (SST25_SPI_CHANNEL == 1)
    	    RPOR1bits.RP2R = 8;                 // assign RP2 for SCK1
    	    RPOR0bits.RP1R = 7;                 // assign RP1 for SDO1
    	    RPINR20bits.SDI1R = 0;              // assign RP0 for SDI1
        #elif (SST25_SPI_CHANNEL == 2)
            RPOR1bits.RP2R = 11;                // assign RP2 for SCK2
    	    RPOR0bits.RP1R = 10;                // assign RP1 for SDO2
    	    RPINR22bits.SDI2R = 0;              // assign RP0 for SDI2
    	#endif

        __builtin_write_OSCCONL(OSCCON | 0x40); // lock   PPS

    #endif

    /////////////////////////////////////////////////////////////////////////////
    //                  DRIVER SPECIFIC INITIALIZATION DATA
    /////////////////////////////////////////////////////////////////////////////

	GOLInit();                      // Initialize graphics library and create default style scheme for GOL

    // initialize GFX3 SST25 flash SPI
    SST25Init((void*) &SPI_Init_Data);                    
   
    TickInit();                     	

	
#if defined(SPI_CHANNEL_1_ENABLE) && defined(__PIC32MX__)          //SPI1 shares pins with the PMP CS. Not recommended for use
    SPI1TouchInit();

/****
 * AR1020 Touch Screen Controller
 *
 * Because the AR1020 needs to use the SPI channel to retrieve data and 
 * SPI channel 1 shares the PMP CS pin, this combination is not supported.
 * The user will receive a compile time error to avoid run time errors 
 * with this combination.
 ****/
#ifdef USE_TOUCHSCREEN_AR1020
#error "The combination of AR1020 touch screen controller and SPI 1 channel is not supported.  Please use SPI channel 2 with the AR1020 controller, or resistive touch."
#endif

#else	
    // initialize the components for Resistive Touch Screen
    TouchInit(NVMWrite, NVMRead, NVMSectorErase, TOUCH_INIT_VALUES);  
#endif	

    HardwareButtonInit();           	// Initialize the hardware buttons

}   
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()
Beispiel #24
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;
        }
    }
}
Beispiel #25
0
//
// Main application entry point.
//
int main(void)
{
	static TICK t = 0;
	static DWORD dwLastIP = 0;
	
	// Initialize application specific hardware
	InitializeBoard();

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

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

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

	// Initialize any application-specific modules or functions/
	// For this demo application, this only includes the
	// UART 2 TCP Bridge

	//************** PIC32-WEB ********************
	//***** Additional initializations Start: *****
	// 1. UART1
	USART_Init(115200,(GetPeripheralClock()));
	USART_Test_Menu_Begin();
	// 2. Timer1
	// configure Timer 1 using external clock(32768Hz), 1:1 prescale, 
	// period 0x8000, thus set interrupt on every 1sec
	// Blink LED0 (right most one) with frequency 2Hz at every one Timer1 interrupt.
    OpenTimer1(T1_ON | T1_SOURCE_EXT | T1_PS_1_1, 0x8000);
    // set up the timer interrupt with a priority of 3
    ConfigIntTimer1(T1_INT_ON | T1_INT_PRIOR_3);
	//CloseTimer1(); // Switches off the Timer1
	mPORTASetPinsDigitalOut(BIT_2);	// Set RA2 like out -> LED1

	// 3. Enable interrupts at the end of initialization
	// enable multi-vector interrupts
    INTEnableSystemMultiVectoredInt();
	//***** Additional initializations End: *****
	

	// 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){

	// Run all enabled web demo applications:
		
    // 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.
	// 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(STACK_USE_ICMP_CLIENT)
	PingDemo();
	#endif
		
	#if defined(STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED)
	SNMPTrapDemo();
	if(gSendTrapFlag)
		SNMPSendTrap();
	#endif
		
	#if defined(STACK_USE_BERKELEY_API)
	BerkeleyTCPClientDemo();
	BerkeleyTCPServerDemo();
	BerkeleyUDPClientDemo();
	#endif

	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)
	{
		#if defined(STACK_USE_ANNOUNCE)
			AnnounceIP();
		#endif
	}
  }       
}
Beispiel #26
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             
        }
    }
}
//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
    }
}
Beispiel #28
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
        }

    }
}
Beispiel #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;
        }
    }
}
Beispiel #30
0
// ************************************************************
// Main application entry point.
// ************************************************************
int main(void)
{
    static DWORD t = 0;	
    static DWORD dwLastIP = 0;
#if defined (EZ_CONFIG_STORE)
    static DWORD ButtonPushStart = 0;
#endif
    UINT8         channelList[] = MY_DEFAULT_CHANNEL_LIST_PRESCAN;  // WF_PRESCAN
    tWFScanResult bssDesc;
#if 0	
    INT8 TxPower;   // Needed to change MRF24WG transmit power. 
#endif

    // Initialize application specific hardware
    InitializeBoard();

    // Initialize TCP/IP stack timer
    TickInit();                        //  Timer 3 interrupt for refreshing motor status inside here
    demo_TickInit();

    #if defined(STACK_USE_MPFS2)
    // Initialize the MPFS File System
	// Generate a WifiGDemoMPFSImg.c file using the MPFS utility (refer to Convert WebPages to MPFS.bat)
	// that gets compiled into source code and programmed into the flash of the uP.
    MPFSInit();
    #endif
	
    // Initialize Stack and application related NV variables into AppConfig.
    InitAppConfig();

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

    Exosite_Init("microchip","dv102412",IF_WIFI, 0);

#if 0	
    // Below is used to change MRF24WG transmit power. 
    // This has been verified to be functional (Jan 2013) 
    if (AppConfig.networkType == WF_SOFT_AP)
    {
        WF_TxPowerGetMax(&TxPower);                       
        WF_TxPowerSetMax(TxPower);       
    }
#endif

    // Run Self Test if SW0 pressed on startup
    if(SW0_IO == 1)
        SelfTest();

    #ifdef STACK_USE_TELNET_SERVER
        // Initialize Telnet and
        // Put Remote client in Remote Character Echo Mode
        TelnetInit();
        putc(0xff, stdout);     // IAC = Interpret as Command
        putc(0xfe, stdout);     // Type of Operation = DONT
        putc(0x22, stdout);     // Option = linemode
        putc(0xff, stdout);     // IAC = Interpret as Command
        putc(0xfb, stdout);     // Type of Operation = DO
        putc(0x01, stdout);     // Option = echo
    #endif


    #if defined ( EZ_CONFIG_SCAN )
    // Initialize WiFi Scan State Machine NV variables
    WFInitScan();
    #endif
	
    // 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;
    }
	
    // Needed to trigger g_scan_done		
    WFRetrieveScanResult(0, &bssDesc);		
  	
    #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
    // Initialize Zeroconf Link-Local state-machine, regardless of network type.
    ZeroconfLLInitialize();
    #endif
	
    #if defined(STACK_USE_ZEROCONF_MDNS_SD)
    // Initialize DNS Host-Name from TCPIPConfig.h, regardless of network type.
    mDNSInitialize(MY_DEFAULT_HOST_NAME);
    mDNSServiceRegister(
            // (const char *) AppConfig.NetBIOSName,        // base name of the service. Ensure uniformity with CheckHibernate().
            (const char *) "DemoWebServer",          // base name of the service. Ensure uniformity with CheckHibernate().
            "_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)
    // Initialize the WiFi Console App
    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.
   #ifndef PERIOD
#define PERIOD  3120        //  set 3120 for get to timer interrupt every 20ms, 40MHz PBUS, div by 256
#endif
    OpenTimer3(T3_ON | T3_SOURCE_INT | T3_PS_1_256, PERIOD);
    while(1)
    {
         if (AppConfig.networkType == 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
                     g_scan_done = 0;
                     g_prescan_waiting = 0;
                }
            }
         }

        #if defined (EZ_CONFIG_STORE)
        // Hold SW0 for 4 seconds to reset to defaults.
        if (SW0_IO == 1u) {  // Button is pressed
            button_state = 1;
            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
		
        // Blink LED0 twice per sec when unconfigured, once per sec after config
        if((TickGet() - t >= TICK_SECOND/(4ul - (CFGCXT.isWifiDoneConfigure*3ul))))
        {
            t = TickGet();
            LED0_INV();
        }

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

        // This task invokes each of the core stack application tasks
        if (cloud_mode == 0)
          StackApplications();

        // Enable WF_USE_POWER_SAVE_FUNCTIONS 
        WiFiTask();

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

        #if defined(STACK_USE_ZEROCONF_MDNS_SD)
        mDNSProcess();
        #endif

        Exosite_Demo();
        // Process application specific tasks here.
        // Any custom modules or processing you need to do should
        // go here.
        #if defined(WF_CONSOLE)
		WFConsoleProcess();
		WFConsoleProcessEpilogue();
		#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;	
			DisplayIPValue(AppConfig.MyIPAddr);			
		
			#if defined(STACK_USE_ANNOUNCE)
			AnnounceIP();
	 		#endif
		
			#if defined(STACK_USE_ZEROCONF_MDNS_SD)
			mDNSFillHostRecord();
	 		#endif
		}

    }
}