Home
NetBurner User`s Manual - Bluewater Designworks, LLC
Contents
1. L cc l Lz L l c int FindFreeFifoStruct int index 1 int i 0 do if StructArray i free index i else itt while i lt NUM POSTS amp amp index 1 return index p A M FIFO Post Task ee ee E EE E EEEE E E ENE E void FifoPostTask void pdata while 1 iprintf r n FIPOPostTask lt r n gt for int count 0 count lt NUM POSTS count int i while i FindFreeFifoStruct lt 0 iprintf Waiting for free FIFO structure r n OSTimeDly TICKS PER SECOND 2 StructArray i x count StructArray i free FALSE Put a message in the Fifo OSFifoPost amp MyFIFO OS FIFO EL amp StructArray i iprintf Posted FIFO StructArray d x d r n i count This delay simulates a resource taking time to pend iprintf Delaying 9 seconds before next FIFO post r n r n OSTimeDly TICKS PER SECOND 9 Page 108 void UserMain void pd DWORD FifoCnt 0 InitializeStack NetBurner Programmers Guide if EthernetIP iprintf Trying DHCP r n GetDHCPAddress iprintf DHCP assigned the IP address of ShowIP EthernetIP iprintf r n else iprintf Static IP address set to Sh
2. 135 int main int argc char argv 136 137 SOCKET sListen sClient 138 WSADATA WSAData 139 struct sockaddr_in sinListen sinClient 140 141 142 ProcessCmdLine argc argv 143 144 if WSAStartup MAKEWORD 1 1 amp WSAData 0 145 146 printf Error loading Winsock n 147 return 1 148 149 150 Create socket to listen on 151 sListen socket AF_INET SOCK STREAM 0 152 if sListen SOCKET ERROR 153 154 printf Error creating sListen socket d n WSAGetLastError 155 return 1 156 157 158 Setup listen address structure 159 sinListen sin addr s addr htonl INADDR ANY 160 sinListen sin family AF INET 161 sinListen sin port htons dListenPort 162 163 Bind socket to listen address 164 if bind sListen struct sockaddr amp sinListen sizeof sinListen SOCKET ERROR 165 166 printf bind error for sListen d n WSAGetLastError 167 return 1 168 169 170 Listen to interface and port 171 if listen sListen 5 SOCKET ERROR 172 173 printf listen error for sListen d n WSAGetLastError 174 return 1 175 176 177 printf Listening on port d Mn dListenPort 178 while 1 179 180 int len sizeof sinClient 181 sClient accept sListen struct sockaddr amp sinClient amp len Is if sClient INVALID SOCKET Page 66 184 185 186 187 188 189 190 191 192 193 194 195
3. The order of these configuration records is fixed regardless of the Interface Block number For example if you have only a WiFi interface you still use Configuration Record 1 Configuration Records are numbered 0 1 and 2 Interface Blocks are numbered 1 2 3 There is no correlation between this numbering Interface Block 3 could reference Configuration Record 1 depending on the order of interface registration calls by your application This example will provide a menu through the serial debug port that enables you to set clear static IP settings and start stop the DHCP Client service XCKCKkCkCkCk Ck k kk kCk kk kk kk kk kk kk kk kk kk kk kk kk kk kk kk kc k kc k kc k kc k kc k kc kckckckckokckok kok ko ke ke e kx f include predef h include lt stdio h gt include lt ctype h gt include lt startnet h gt Page 24 NetBurner Programmers Guide include autoupdate h include dhcpclient h Make sure to include these header files include bsp h include lt string h gt include utils h include system h include netinterface h extern C void UserMain void pd Application name const char AppName Change IP Example Variable to indicate if appliction tried to obtain runtime IP settings from a DHCP server bool AssignedDHCP FALSE Since we want to be able to start and stop DHCP we need to create out own
4. Loop forever displaying UDP data while 1 iprintf Enter a string to send gets buffer iprintf r n iprintf Sending s using UDP to buffer ShowIP ipaddr iprintf d r n portnum sendto UdpFd BYTE buffer strlen buffer ipaddr portnum iprintf r n Page 85 NetBurner Programmers Guide 13 3 Writing a Windows UDP Client Server Application While Windows does support a UDP class it is more difficult to use than the NetBurner class This example will use the sendto and receivefrom functions to send and receive UDP datagrams Server Open a socket socket Name the socket bind Send and receive data sendto and receivefrom Close connection close Client Open a socket socket Send and receive data sendto and recrivefrom Close connection close OV UA 4 UO C NDo00 1ON UA 4 UP 17 NetBurner Programmers Guide 13 3 1 Windows UDP Application Source Code BRR KKK KKK RK KR RK KK A A A A RRA A A EE k k LE k k UDP Windows Application File Name UDPWin cpp DESCRIPTION This Win32 console application will send and receive UDP packets COMMAND LINE PARAMETERS Usage UDPWin listen port dest ip dest port where listen port port number to monitor for incoming datagrams dest ip destination IP address dest port destination port number COMPILILATION INSTRUCTIONS Compile as Windows c
5. void UserMain void pd InitializeStack Init TCP IP Stack Get a DHCP address if the stored IP Address in flash memory is set to 0 0 0 0 set via IPSetup or serial interface You may want to add a check for the return value from this function See the function definition in nburn include dhcpclient h GetDHCPAddressIfNecessary OSChangePrio MAIN PRIO Change priority EnableAutoUpdate Enable the ability to update code over the network StartHTTP Start the web serrver Page 126 NetBurner Programmers Guide EnableTaskMonitor Enable the Task scan utility Add the multihome interface at fixed ip address AddInterface AsciiToIp 10 1 1 240 AsciiToIp 255 255 255 0 0 int DhcpInterface GetFirstInterface Get first interface identifier DhcpIb GetInterFaceBlock DhcpInterface Get interface data iprintf DHCP IP Address ShowIP DhcpIb netIP iprintf r n int StaticInterface GetnextInterface DhcpInterface Get next interfac identifier StaticIb GetInterFaceBlock StaticInterface Get interface data iprintf Static IP Address ShowIP StaticIb gt netIP iprintf r n while 1 OSTimeDly TICKS_PER_SECOND 5 Page 127 NetBurner Programmers Guide 18 Using the ColdFire Processor On Chip SRAM 18 1 Introduction In addition to the SDRAM on NetBurner mod
6. 39 Check NV Settings 40 Assign default values if VerifyKey is not valid otherwise load 41 stored flash values 42 43 void CheckNVSettings 44 45 NV SettingsStruct pData NV SettingsStruct GetUserParameters 46 NV Settings VerifyKey pData gt VerifyKey Page 36 NetBurner Programmers Guide NV_Settings bUTC pData gt bUTC NV Settings nLocalOffset pData nLocalOffset NV Settings bCkboxLeapSecDay pData gt bCkboxLeapSecDay NV Settings nLeapSecDay pData nLeapSecDay NV Settings bLeapSecDayAdd pData gt bLeapSecDayAdd NV Settings bEnableDST pData gt bEnableDST if NV_Settings VerifyKey VERIFY_KEY iprintf Reset NV Memory Defaults n NV_Settings VerifyKey VERIFY KEY NV Settings bUTC TRUE NV Settings nLocalOffset 0 Vi b n NV Settings bCkboxLeapSecDay FALS n b b Fl M NV Settings nLeapSecDay 0 NV_Settings bLeapSecDayAdd TRU NV_Settings bEnableDST TRU M p pH mM SaveUserParameters amp NV Settings sizeof NV Settings void WebUTC int sock PCSTR url iprintf Entered WebUTC r n if NV Settings bUTC writestring sock CHECKED N 1N void WebLocal int sock PCSTR url if NV Settings bUTC writestring sock CHECKED N 1N void WebLocalOffset int sock PCSTR url
7. Q iprintf Closing connection fd d r n i writestring fd array i Bye r n close fd array i fd array i 0 else iprintf Read Ss from fd Sd r n buffer i siprintf buffer Server read d byte s r n rv writestring fd array i buffer else iprintf ReadError on fd d r n fd arrayli FD SET fd array i amp error fds Check for errors if FD ISSET fd_array i amp error fds iprintf Error on fd d closing connection r n i Page 62 NetBurner Programmers Guide close fd array i fd array i 0 Page 63 WOWDADMABRWNK NetBurner Programmers Guide 12 3 Writing a Windows TCP Server Writing a TCP server on the Windows platform involves a few more steps As with the NetBurner TCP Server the windows TCP server application will create a thread that listens for incoming connections on a specific port number The basic steps are as follows Create a socket structure variable with socket Initialize the socket structure Bind the socket to a listen address with bind Listen for incoming connections with listen Accept an incoming connection with accept Gcr Cobo Note The TcpServerWin exe and source code are located in the nburn pctools directory 12 3 1 Windows TCP Server Application Source Code This example program allows you to specify the listen port Any client connecting to your server will
8. ee eese ee ee en eee eoo e eee tn sese tato sese esee seta aee seen eese ea se eese en ae eS 22 7 1 THECONFIGURATION REC ORD a a a ac a n ieni 22 7 2 READING THE CONFIGURATION RECORD cccccccecececececesecececececececesesecesecesesecesecesesesesesecesesesssssssesseseseseeeeeass 23 7 3 STATIC AND DHCP IP ADDRESS MODIFICATION EXAMPLE cccccccececececececececececececscscececececececececseeeeeeeeess 24 8 BASIC WEB SERVER FUNCTIONS seesseoeessecessscossoceessoceessecesssecesooesssooeesseceessecsssoecssocecsseceesoecssoseessoseessese 31 8 1 INTRODUGTION 2 TA EEE BEE SEE EE EOE S EE E E AET E ET EE E EET E T 31 8 2 EDIT THEINDEX HTM WEBPAGE E ETE E T AE ETE E E TE T 32 9 INTERACTIVE WEB FORM EXAMPLE sseoessseessoceessoceessecesssecssooeessoceesseceeceecsssoeessoceesseceesseesssoeessoceesseee 33 9 1 INTRODUCTION cna e E E E E tae et A E E E ete e EE EE E EEEE ea 33 9 2 HOW TO USE HI ML FORMS oann ea e A E a aaea sage a SEOs ei Tea nena T 34 9 3 COLLECTING USER INPUT WEB FORMS VS URL S u cccccccccccccccccccececececececececesesecesecesesecesesessessesesesseseeeaeseaes 35 9 4 APPLICATIONS OBJECTIVES 5 eel czeeetetekecetteneeetetecee eise a Ea A a EE a iced aee ER Pee vie eee 35 9 5 APPLICATION PIEES 3 tree reete tete ite eptetece eicit et ede eee ee ER PEE Ee ED 35 9 6 INTERACTIVE WEB FUNCTION Snine oa rear ectutea eee e recente peek ee eia eae a te perge epevEe cec ve ea ewe vi tp RES 36 10 DYNAMIC WEB CONTENT USING THE
9. ifndef DEBUG EnableSmartTraps endif ifdef DEBUG InitializeNetworkGDB and Wait endif while TRUE There are two pending functions we can use OSFlagPendAny returns if one or more of the flags are set OSFlagPendAll returns only if all flags are set This example will use the Any version which is useful for a task that is reporting on multiple events It will return if any of the flags in TASK1 TASK2 or TASK3 are set iat OSFlagPendAny amp gOsFlag TASK FLAG 1 TASK FLAG 2 TASK FLAG 3 O0 Only ONE of the OSFlagPend functions can be used at a time OSFlagPendAll amp gOsFlag TASK FLAG 1 TASK FLAG 2 TASK FLAG 3 0 iprintf OSFlagPendAny detected the following flag s are set Get the state of the flags so we can determine which ones are set gOsFlagState OSFlagState amp gOsFlag Now test each flag bit position if gOsFlagState amp TASK FLAG 1 TASK FLAG 1 Page 114 NetBurner Programmers Guide iprintf TASKI if gOsFlagState amp TASK FLAG 2 TASK FLAG 2 iprintf TASK2 if gOsFlagState amp TASK FLAG 3 TASK FLAG 3 iprintf TASK3 iprintf Nr Nin Clear the Flag mask You might need to signal the setting task when done in a real application y OSFlagClear amp gOsFlag gOsFlagState Page 115 NetBurner Programmers Guide 16 F
10. 64 exit 1 65 67 dListenPort WORD atoi argv 1 69 if argc 2 70 71 if stremp argv 2 echo 0 12 bEcho TRUE 79 FUNCTION ProcessClient 81 DESCRIPTION 82 This function is called as a thread to handle client connections 84 PARAMETERS 85 lpParam is a pointer to the client socket handle 87 RETURNS 32 bit thread exit code 89 DWORD WINAPI ProcessClient LPVOID lpParam 90 91 SOCKET s SOCKET 1pParam 92 int SampleCtr 0 94 dwTotalBytesRead 0 95 while 1 96 97 int bytes read recv s RxBuf RX BUFSIZE 1 0 98 RxBuf bytes read 0 99 printf Received d bytes s n bytes read RxBuf 100 dwTotalBytesRead bytes read 102 if bytes read 0 amp amp bEcho 103 104 if send s RxBuf strlen RxBuf 0 SOCKET ERROR 105 106 printf Error sending echo data d n WSAGetLastError 107 108 109 else if bytes read 0 110 111 closesocket s 112 exit 0 Page 65 NetBurner Programmers Guide 113 114 else if bytes read SOCKET ERROR 115 116 printf recv error in ProcessClient dMn WSAGetLastError 117 break 118 119 120 return 0 121 122 123 124 125 126 127 128 FUNCTION main 129 130 DESCRIPTION 131 Main routine to start network services and listen for connections 132 133 RETURNS integer exit code 134
11. char buf 80 sprintf buf VALUE N dN NV Settings nLocalOffset writestring sock buf void WebLeapCkbox int sock PCSTR url if NV Settings bCkboxLeapSecDay writestring sock checked Page 37 NetBurner Programmers Guide void WebLeapSecDay int sock PCSTR url char buf 80 sprintf buf VALUE d NV Settings nLeapSecDay writestring sock buf void WebLeapSecDayAdd int sock PCSTR url if NV_Settings bLeapSecDayAdd writestring sock CHECKED N 1N void WebLeapSecDaySub int sock PCSTR url if NV Settings bLeapSecDayAdd writestring sock CHECKED N 1N void WebEnableDST int sock PCSTR url if NV Settings bEnableDST writestring sock CHECKED N 1N void WebDisableDST int sock PCSTR url if NV Settings bEnableDST writestring sock CHECKED N 1N r Handle HTTP Post WARNING WARNING WARNING CAUTION CAUTION CAUTION The User data space is 8K in size The object we are storing is less than 200 bytes long thus it is probably ok to make an automatic variable out of it It would NOT BE OK to make an 8K automatic variable The choices for doing this with an 8K object First choice make a global variable this way the linker will allocate space for it All errors will be at link time not run time Second
12. n dListenPort The recvfrom API function has the following parameters recvfrom SOCKET s socket to receive from char buf point to buffer to store rec d data size t len length of buffer or of bytes to read int flags flags normally use 0 struct sockaddr from client data returned int fromlen size of client data struct x int len sizeof sinFrom int bytes recvfrom s RxBuf RX BUFSIZE 1 0 struct sockaddr amp sinFrom amp len if bytes SOCKET ERROR printf recvfrom error d n WSAGetLastError break printf Received packet from s d n inet ntoa sinFrom sin addr ntohs sinFrom sin port printf Bytes read d bytes for int i20 i lt bytes i printf c RxBuf i printf n i return 0 FUNCTION main DESCRIPTION Main routine to start network services and listen for connections RETURNS integer exit code int main int argc char argv SOCKET sListen sSend WSADATA WSAData struct sockaddr_in sinListen sinSend Page 88 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 NetBurner Programmers Guide Proce
13. under your project directory 21 4 Compiling the Application At this point you should have a directory called c netburner template that contains two files main cpp and makefile First we will run make to verify the application compiles correctly Once all errors have been corrected we will download this application to your NetBurner device To compile the source code and create the application image 1 If you have not done so already open a command prompt and move to the c netburner template directory cd c netburner template If you did not select the automatic variable configuration during the installation process you must run c nburn setenv bat manually A simple method to determine if your system is configured correctly is to type set at the command prompt then press the Enter key Look for an environment variable called NBROOT If NBROOT is defined then you should be ready to go If NBROOT is not defined just type setenv at the command prompt in the c nburn directory and press the Enter key Now if you type set at the command prompt and press the Enter key you will see that NBROOT is defined i e NBROOT nburn 2 At the command prompt in the c netburner template directory type make and press the Enter key This will invoke the compiler to compile and link your code and build the code image If you have any coding or syntax errors correct them now and continue to run
14. New IP mask AsciiToIp 0 0 0 0 New IP gateway AsciiToIp 0 0 0 0 New IP dns break case 6 Start DHCP Client service if AssignedDHCP Page 29 NetBurner Programmers Guide iprintf Contacting DHCP Server r n MyStartDHCP ib else iprintf r n Error DHCP Client service is alredy running r n break case 7 Stop DHCP Client service if AssignedDHCP pDhcpObj StopDHCP Stop DHCP AssignedDHCP FALSE Flag for this application n iprintf r nDHCP Release sent and DHCP Client service has b stopped r n DisplayRuntimeIPSettings FirstInterface else iprintf r n Error DHCP Client service is not running r n break default DisplayUserMenu Page 30 NetBurner Programmers Guide 8 Basic Web Server Functions 8 1 Introduction The NetBurner tools handle HTML pages JAVA applets Flash and images automatically Any project that makes use of the Web Server features must have a subdirectory immediately under the project directory named html Just put all HTML files JAVA applets images etc in this html subdirectory and the NetBurner tools will automatically compile and link them into the application image that you download into your NetBurner device The Template program is now at the point where it will boot up display its IP address static or acquired by DHCP and loop forever printing messag
15. ShowIP cr ip GateWay iprintf NrNin iprintf DNS ShowIP cr ip DNS server iprintf r n You do not need to reboot if you change both the runtime and flash values This function call requires include bsp h if ForceReboot DisplayUserMenu Displays menu through the serial port to interact with program Page 27 NetBurner Programmers Guide men ak SI A ets oe aS PME TE void DisplayUserMenu iprintf r n Main Menu r n iprintf l Display Runtime Settings r n iprintf 2 Display Flash Settings r n iprintf 3 Change Runtime Static Settings r n iprintf 4 Change Flash Static Settings r n iprintf 5 Change Flash amp Runtime Static Settings to 0 0 0 0 r n iprintf 6 Start DHCP Client Servce r n iprintf and attempt to get a DHCP address r n iprintf 7 Stop DHCP Client Service r n Peso MyStartDHCP Most applications can just use the GetDHCPAddress function at boot time to enable the DHCP Client If you require more control over the DHCP service such as starting and stopping then a few lines of code are required to create a DhcpObject and check a semaphore to determine if the DHCP request was successful This is essentially what the GetDHCPAddress function does void MyStartDHCP InterfaceBlock ib int FirstInterface GetFirstInterface Get
16. iprintf Attempting DHCP r n if GetDHCPAddress DHCP OK iprintf DHCP Failed r n else iprintf DHCP IP Address else iprintf Static IP Address ShowIP EthernetIP iprintf r n OSChangePrio MAIN PRIO EnableAutoUpdate We want to hve the UserInputTask block on fgets so we need to be in serial interrupt mode rather than the default polled mode To enable interrupts close the serial port and call OpenSerial OSTimeDly TICKS PER SECOND delay to allow previous prints SerialClose 0 int fd OpenSerial 0 115200 1 8 eParityNone ReplaceStdio 0 fd ReplaceStdio 1 fd ReplaceStdio 2 fd Initialize the mailbox OSMboxInit amp UserInputMbox NULL bExitUserInputTask FALSE if OSTaskCreate UserInputTask NULL void amp UserInputTaskStack USER TASK STK SIZE void UserInputTaskStack MAIN PRIO 1 OS NO ERR iprintf Error creating task r n BYTE i 0 Page 105 iprintf Enter String while 1 ye BYTE err In this example we will use NoWait so that we show how multiple tasks can operate and count LEDs while we are waiting for user input The version of the function is void pmsg OSMboxPend amp UserlInputMbox 0 0X X void pmsg if pmsg OSMboxPendNoWait l NULL amp UserInputMbox iprintf r nUserMain Received
17. 138 139 while 140 141 142 catch Exception e 143 System err println Exception e toString 144 145 return s 146 147 148 149 public void run 150 151 while true 152 153 String msg GetUserInput 154 byte buffer msg getBytes 155 System out println Sending Message msg 156 DatagramPacket packet new DatagramPacket buffer 157 buffer length DestAddr DestPort 158 try 159 dgSocket send packet 160 catch Exception e 161 System err println Exception e toString 162 163 164 165 Page 94 NetBurner Programmers Guide 13 4 2 Running the Windows Java UDP Application To run the application you will need to have the Java SDK installed If you need to obtain the software package go to http www javasoft com and download it free of charge Once installed verify you have the correct path by opening a DOS window and typing java at the prompt and press the Enter key If your path is correct you will see the Java usage information message If your path is incorrect you will see an error message indicating the command is not recognized Follow the Java installation documents to perform a correct installation To compile the application open a command prompt and go to the directory containing the source code The default directory is java JavaWin To compile the example type javac udpserv java The compilation will produce
18. 14 2 Pre emptive Operation and Blocking In a pre emptive RTOS the highest priority task ready to run will always run This is an extremely important point so I will mention it again the highest priority task ready to run will always run This is different than a Windows or Unix system that employs a round robin approach in which each task will run based on its time slice If you create a high priority task that can always run then no lower priority tasks will ever run Lower priority tasks can only run when a higher priority task blocks on a resource or time delay uC OS functions that can cause a task to block OSTimeDly OSSemPend OSMBoxPend OSQPend OSFlagPendAny OSFlagPendAl1l Page 96 NetBurner Programmers Guide I O system calls that can cause a task to block select read including all variants with timeouts write unitl at least one char can be written gets getchar fgets Network calls can cause a task to block Accept Creation of a UDP packet when initialized with received data Functions that can be used to enable a task to be ready to run OSMBoxPost OSQPost OSSemPost OSTimeTick Lets say you have two tasks A and B Task A has priority 50 and Task B has priority 51 Since Task A is of higher priority it will always run and Task B will never run unless it calls a blocking function Task B will then run for as long as Task A blocks this could be 1 second due
19. 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 NetBurner Programmers Guide printf accept error d n WSAGetLastError break printf Accepted connection from s d n inet ntoa sinClient sin addr ntohs sinClient sin port HANDLE CreateThread LPSECURITY ATTRIBUTES lpThreadAttributes pointer to thread security attributes DWORD dwStackSize initial thread stack size in bytes LPTHREAD START ROUTINE lpStartAddress pointer to thread function LPVOID lpParameter argument for new thread DWORD dwCreationFlags creation flags LPDWORD lpThreadId pointer to returned thread identifier x HANDLE hThread DWORD dwThreadId hThread CreateThread NULL 0 ProcessClient LPVOID sClient 0 amp dwThreadId if hThread NULL printf Error creating Client thread d n GetLastError break closesocket sListen WSACleanup return 0 Line 59 The void ProcessCmdLine int argc char argv function is called at the beginning of main to do what you would expect process any command line parameters Specifically you will pass the listening port number Whether or not to echo the data sent from the client is optional Line 89 The DWORD WINAPI ProcessClient LP VOID IpParam function is run as a separate thread spawned for the incoming connection The recv function is used to obtain the d
20. Host Ethernet red cross over cable NetBurner Computer Hardware Connection using standard blue Ethernet cables Ethernet Host Ethernet Switch Ethernet NetBurner RS 232 The Ethernet connection should be between your host computer and your NetBurner device s RJ 45 connector The RS 232 connection should be made between your host computer s Serial port and the Debug Serial port of your NetBurner device The Serial port connection on the NetBurner device will vary with each hardware platform but it should be a DB9 connector on the processor board itself or on a separate Adapter board or Carrier board supplied with your kit Please refer to your Quick Start Guide for additional details on how to make and download files to your NetBurner device 5 3 1 Testing the RS 232 Debug Connection You can determine if you are properly connected to the debug port with the following test 1 Start the dumb terminal program MTTTY which is included in your NetBurner tools You can start it from within NBEclipse from the NBEclipe menu item or MTTTY icon or from the Windows start menu Start gt Programs gt Netburner NNDK gt Mttty Serial Terminal Set the com port to whichever port you are using on your computer usually com1 and set the baud rate to 115 200 Make sure to click on the Connect button in the MTTTY window to establish the connection 2 Power on or reset your NetBurner device The MTTTY screen should display a sign on mess
21. This would most commonly be used to display a use defines structure Lets say you have a Class you want to display on a web page called MyClass struct my struct int i char buf 80 DWORD dVal MY STRUCT MY STRUCT MyStruct In your include file add the function definition void WriteHtmlVariable int fd MY STRUCT MyStruct You can display it on the web page with the VARIABLE tag lt VARIABLE MyStruct gt What this look like behind the scenes is WriteHtmlVariable fd MyStruct Note that you still have to write the implementation of the above function The function below is the source code for the MAC address type already defined void WriteHtmlVariable int fd MACADR ma PBYTE lpb PBYTE amp ma for int TI 04 I 57 TFE fd writehex fd lpb i write tay meti fd writehex fd lpb 6 Page 46 NetBurner Programmers Guide 11 TCP vs UDP A very common question that arises when designing a network application is whether to use TCP Transmission Control Protocol or UDP User Datagram Protocol There are a few guidelines and features that can determine which would be the preferred protocol Some of the issues discussed may not mean much before your read the TCP and UDP sections later in this guide but discussing these issues now may make you aware of certain issues as you read those sections In general TCP is a connection oriented byte stream used fo
22. Use the API function int AddInterface IPADDR addr IPADDR mask IPADDR gateway int root_if 0 to add additional interfaces You must specify the first 3 parameters 4 Select your project in NBEclipse then from the main menu select NBEclipse gt Rebuild System Files to rebuild the the system library 17 2 1 Multi Home Example Program BRK KK Ck Ck Ck kCk Ck kk Ck kCk Ck kk kCk kk kCk kk kk kk kk kk kk kk kk kc k kk kc k ck kckck KK KK ok Multihome application example This program will demonstrate how to implement both a DHCP address and static IP addres using the Multihome functionality of the NetBurner TCP IP Stack The NetBurner device will try to obtain a dynamic IP address from a DHCP Server for the first Network Interface and set a static IP address for the second Network Interface The end result is that the NetBurner device will respond to either IP address Th xample will print debug information out the debug serial port and display the IP address information on a web page that can be accessed from either IP address To enable multihome capability you must uncomment the MULTIHOME definition in the include file nburn include predef h and rebuild the system files If using the IDE select Build gt Rebuild All If using the command line go to nburn system and run make clean FE Ck k kk kk kk kk kk kk kk kk kk kk kk kk kk kk k k kc k kc k kc k kc k kc k kc k ck kckckckckokckok ck kk ke ke e kx
23. const char AppName SRAMPointer SDRAM Base Address starting after the 0x400 vector table define SRAM BASE 0x20000400 typedef struct dnt iL long 1 char str 100 sram struct sram struct pSram sram struct SRAM BASE Set pointer address void UserMain void pd InitializeStack if EthernetIP 0 GetDHCPAddress OSChangePrio MAIN PRIO EnableAutoUpdate iprintf Application started r n It is the Programmer s responsibility to ensure the structure fits within the available physical SRAM space pSram gt i 1234 strcpy pSram gt str Hello World iprintf pSram str s r n pSram str iprintf pSram i d r n pSram gt i while 1 OSTimeDly TICKS PER SECOND Page 130 NetBurner Programmers Guide 19 Time Functions Embedded systems have a number of options to set and access time Your NetBurner kit will enable you to set the time manually through a real time clock if available and using a network connection and the Network Time Protocol NTP 19 1 Standard C Time Functions The following standard C time structures and functions are supported by the development tools and libraries To use these functions you will need to include both time h and nbtime h in your application The tm structure is used to store time and date information typedef struct tm int tm_hour hour 0 23 int tm isdst
24. daylight saving time enabled disabled int tm mday day of month 1 31 int tm min minutes 0 59 int tm mon month 0 11 0 January int tm sec seconds 0 59 int tm wday Day of week 0 6 0 Sunday int tm yday Day of year 0 365 int tm year Year less 1900 The time t variable type is a DWORD value The time functions in nbtime h are time t time time t time Get current calendar time as single number of type time t set time time t time Sets the system time to values in time t structure The functions in time h are char asctime const struct tm time Convert tm structure to string ctime Convert time t value to string difftime Return difference between two times gmtime Convert time t value to tm structure as UTC time localtime Convert time t value to tm structure as local time mktime Convert tm structure to time t value strf me Flexible calendar time formatter Page 131 NetBurner Programmers Guide 20 Dynamic Memroy Allocation and Free Space The 3 main types of RAM memory available to an embedded system are e Statically allocated variables at compile time e Task and system stack space e Dynamic memory used by malloc and new Statically allocated memory at compile time is the safest to use since the system does not need to notify the user or recover from a failure if a dynamic memory allocation call fails For those cases when dynamic memory allocation
25. define CONFIG IF ID ETHERNET 0 define CONFIG IF ID WIFI 1 define CONFIG IF ID ETHERNET2 2 The Configuration Record is a structure that contains all the system configuration parameters When your NetBurner device boots it copies these parameters to run time variables that are used during normal system operation called Interface Blocks This application illustrated how to read and modify both runtime and stored flash configuration parameters NOTE This application note was written for tools release 1 95 If you are using a later revision please check the system file references to verify specific information on function calls and structures This application note does not apply to prior releases 7 1 THE CONFIGURATION RECORD Configuration Records are stored in an 8k bytes sector of flash memory There is one ConfigRecord structure for each network interface in your NetBurner device In the 1 95 release the each ConfigRecord occupies 256 bytes To enable an application to modify and save the network settings you must retrieve the ConfigRecord for a specific interface modify it and save it to flash The ConfigRecord structure is defined in nburn include system h typedef struct unsigned long recordsize The stored size of the struct unsigned long ip Addr The device IP Address unsigned long ip Mask The IP Address Mask unsigned long ip GateWay The address of the P gateway un
26. localport is the local port number of the TCP Client Remember 4 items are needed for a connection and the TCP Client needs to tell the Server what port number it is using e destport is the destination port number the one the server is listening on e timeout allows the connect call to exit if a connection is not made within a specified amount of time A timeout value of 0 will wait forever This example program will combine a number of features covered to this point e The application will create a web page interface with input fields for a message to send to the server the server IP address and the server port number e HTML forms will be used to submit user data e The web page interface will invoke the connect function to create an outgoing connection to a TCP Server and send the message Page 69 Server Call listen function Returns file descriptor Call accept function Will block until accepting incoming connection then return the connection s file descriptor Send and Receive data using read and write Call close to close the connection NetBurner Programmers Guide Client Call connect function to connect to server Returns connection s file descriptor Send and Receive data using read and write Call close to close the connection A screen shot of the web interface is shown below Page 70 NetBurner Programmers Guide J NetBurner TCP Client Example Program Microsoft I
27. must be used the spaceleft and mallinfo functions can be used to determine the amount of free memory available The spaceleft function returns the amount of free space between the amount of memory allocated to the heap the heap pointer and the top of the system stack However there may be free space available inside the heap as well from previous malloc calls that have been freed The mallinfo function provides information on heap memory blocks that are not in use An example program demonstrating the use of these functions is shown below SRevision 1 0 Copyright Date 2009 10 05 22 53 41 lam This example demonstrates the usage of malloc and free It identifies way s to track your heap space used by calling spaceleft and mallinfo Use these function to help ensure that applications do not run out of heap space It is important to use both spaceleft and mallinfo to calculate the size of your heap As this application demonstrates spaceleft alone will not always give the total space available to malloc In this example the application will allocate 3 chunks of space The first is 1MB then a 3MB then a 512KB chunk It will then free the data in a different order After every malloc and free a heapinfo print will occur This shows the current heapspace used heapspace free and space reported by spaceleft X F F Xo Xo X Xo Ro Ro X X F HF Sox include predef h include lt s
28. pd InitializeStack EnableAutoupdate OSChangePrio MAIN PRIO NR e e e SR SR e DPOWMDANDMBPWNK ODODGCOEON DURARON while 1 21 22 iprintf Hello World n 23 OSTimeDly TICKS PER SECOND 1 24 25 The above program is a fully functional network application in just a few lines of code The only application specific code is on lines 20 and 21 the remainder of the program is what we will refer to as the Template Program Although the purpose of our application is to print Hello World out the debug serial port adding the network support will allow fast code development using the NetBurner make load build command and also allow network configuration using the NetBurner IPSetup utility i e IPSetup tool For additional information on make load and AutoUpdate please refer to your NNDK User Manual From Windows Start gt Programs gt Netburner NNDK gt NNDK Users Manual Lines 5 9 specify the include files predef h defines constants for debugging covered in the Debugging chapter and version info stdio h defines standard input and output functions startnet h defines the function calls necessary to start the TCP IP Stack and HTTP autoupdate h defines the functions necessary to download firmware updates over a network connection Line 10 tells the C compiler to declare the UserMain function as a C type function call Note This is done to allow straight C programming as oppos
29. 1 1 17 1 Multiple Hardware Interfaces Ethernet WiFi PPP You can have up to 3 network interfaces on a single NetBurner device For example you can have a primary Ethernet interface and also a WiFi interface If you are designing your own hardware you can also add an additional Ethernet interface for a total of 2 or 3 Unlike Multi home these additional hardware interfaces will have their own MAC address and can use DHCP simultaneously To add interfaces we will use the netinterface API as previoiusly discussed in the Change IP section of this document In this example we will add a WiFi interface which is accomplished with the following API call from nburn include wifi h int AddWiFilnterface BOOL adhoc FALSE In this case the SSID and WEP key would be configured in IPSetup You can also set up the WiFi parameters and start the interface separately See the include file and NNDK Users Guide for more information 17 1 1 WiFi Interface Example The following example adds a WiFi interface to a NetBurner module with an existing Ethernet interface include predef h include stdio h include ctype h include lt startnet h gt include autoupdate h include dhcpclient h include wifi h include netinterface h include taskmon h extern C void UserMain void pd void ShowArp const char AppName wifi infrastructure int nwifi if void DisplayMenu
30. 2 3 STATIGIP ADDRESS nore tee eres eni ued eis ee inea tobe Moe A tees dv ive cob ax tie bia oe eee eee cele 10 2 4 DYNAMIC IPF ADDRESS DHCP 5 oet too ER it a ec etiain testetur 10 2 5 NETWORK CONFIGURATION STEP BY STEP INSTRUCTIONS eeeeeeneeee e e ene emen enne n nsns ise esses nsns ee 10 3 HOW DO TSELECT AN IP ADDRESS eee reete eee eo eee tao so eaae e eee ae Urso ee Pasa see e eo ee aa e UR Ee oe eo ME aa eee inn aee Ea a 11 4 WEB BROWSERS AND PROXY SERVERS e eeeee eene eese tnos en eee ee tones ee to se eee ee eese en Pee seen eese ee see seen ae eS 12 5 USING THE NBECLIPSE IDE TO CREATE THE TEMPLATE PROGRAM eeeeee ee ee eene eee enne 13 5 1 CREATE A NEW PROJECT WITH THE APPWIZARD eceeeetere eere enememennnnn ener nnns nsn ese esa nsn usn ese nsns nennen esee 13 5 2 TEMPLATE PROGRAM SOURCE CODE eeeeeee ee e e e enenen nnnm nn nnns nsns e esi nsi ise iss ese ese ese ases e etes seses neee 15 5 3 TEMPLATE PROGRAM SETUP tuedecerencudute aded adeua rei o Rueda Pagani vers 18 2 921 Testing the RS 232 Debug Connection eese eene ener nennen nennen ens 18 5 4 COMPILING AND RUNNING THE APPLICATION eerte enenenemennnnn ener nn nn nnns nsns ese ese esu ese ese ese nsns esas esee 19 6 DHCP DYNAMIC HOST CONFIGURATION PROTOCOL cce ee ee eee ee eese eo oeste toss eee te sete en ae ee 20 7 CHANGING IP ADDRESSES AT RUN TIME
31. 45 while true 46 47 byte buffer new byte 65536 48 DatagramPacket dgPacket new DatagramPacket buffer buffer length 49 dgSocket receive dgPacket 50 51 System out print Rec d From dgPacket getAddress 52 System out print dgPacket getPort 53 System out print dgPacket getLength bytes 54 String msg new String buffer 0 dgPacket getLength 55 System out println msg n 56 57 58 59 60 public static void main String args throws IOException 61 int ListenPort DestPort 62 String DestIP 63 64 if args length 3 65 throw new RuntimeException Syntax udpserv listen port dest IP dest 66 port 67 ListenPort Integer parseInt args 0 68 DestIP args 1 69 DestPort Integer parseInt args 2 70 71 Display command line parameters 72 System out println Listen Port ListenPort 73 System out println Dest IP DestIP ps System out println Dest Port DestPort 76 InetAddress LocalHost InetAddress getLocalHost TT System out println Local Host Name LocalHost getHostName D System out println Local Host IP Addr LocalHost getHostAddress 80 Create instance of udpserv class 81 udpserv serverUDP new udpserv ListenPort 82 System out println Starting UDP echo server listening on port ListenPort 83 84 85 Convert destination IP string to InetAddress type 2 InetA
32. EOF Sent RX Chars o Page 56 NetBurner Programmers Guide 12 2 3 Simple TCP Server Using the select Function In the previous example the TCP server processed only a single incoming connection The select function has the ability to pend on multiple file descriptors which are used for TCP or serial connections The example below demonstrates how the TCP Server can be written using select Description NetBurner TCP IP Server Example Program This program will create a TCP server task which listens on port 23 by default To test the application you can use Telnet For example from a windows commpan prompt type telent ip address of netburner gt This example uses the select function to process the TCP connection The real value of select is that it can pend on multiple file descriptors not just one as in this example We are using one just to illustrate how it can be used A timeout is used to close the connection if no data is received in 10 timeout periods include predef h include lt stdio h gt include lt startnet h gt include lt autoupdate h gt include lt startnet h gt include lt dhcpclient h gt include lt tcp h gt define TCP LISTEN PORT 23 Telent port number define RX BUFSIZE 4096 const char AppName TCP Server with Select Example fc Global Vars char RXBuffer RX BUFSIZE extern C void UserMain void pd void IPtoString IPADDR i
33. Ethernet NetBurner 1 5 3 Network Configuration Once the hardware and software installations are complete you will need to either verify automatic network settings or assign static network settings of the NetBurner device 1 Verify the hardware is connected correctly A link light is located near the RJ 45 Ethernet connector on your NetBurner board The link light will be lit if the network cable is connected correctly to both the host computer and the NetBurner device Note If the link light is not lit network communication will not be possible 2 Run the NetBurner IPSetup program From Windows Start gt Programs gt Netburner NNDK IP Setup tool IPSetup will allow you to view your NetBurner device s current settings or modify the settings If you are using DHCP then the values in the left pane in the IP Setup window will be zero and the IP address assigned by the DHCP server will appear in the Select a Unit pane as shown below The name following the IP address indicates the NetBurner platform name If your running application supports a web interface the Launch Webpage button will open up when clicked your default web browser to display your NetBurner device s home page Page 8 NetBurner Programmers Guide mm NetBurner IPSetup NDK Settings m Select a Unit IP 0 0 0 0 0 10 8B F1 FA 5B IP 0 0 0 0 DHCP 10 1 1 101 CFY 2 40 Network Mask 0 O 0 0 GaeWa 0 0 0 0 pss 0 0 0 0 Baudrate fi 15200 Y S
34. Hello World Flash and RAM application files When your code compiles correctly two files are created template s19 and template APP s19 The template s19 file is memory mapped to run from RAM while template APP s19 is memory mapped to run from Flash memory Note All compiled images will be located in the c nburn bin directory This guide will focus on Flash downloads Please refer to the section on Downloading to RAM in your User Manual for more information on downloading applications to RAM From Windows Start gt Programs NetBurner NNDK gt NNDK Users Manual Page 19 NetBurner Programmers Guide 6 DHCP Dynamic Host Configuration Protocol DHCP is used to provide host configuration parameters on a TCP IP network DHCP is built on a client server architecture in which one or more designated DHCP Servers allocate network addresses and other configuration information to hosts DHCP Clients Note All NetBurner devices can function as a DCHP Client For additional information about DHCP please refer to your NNDK User Manual From Windows Start gt Programs gt NetBurner NNDK gt NNDK Users Manual To enable DHPC Client services your application code must contain DHCP Client API function calls to enable the service DHCP can dynamically configure many parameters including 1 IP Address 2 Subnet Mask 3 Gateway Address 4 DNS Server Address The example code below checks the first interface but you can modify it t
35. InterfaceMASK int InterfaceNumber IPADDR InterfaceGate int InterfaceNumber MACADR InterfaceMAC int InterfaceNumber Page 23 NetBurner Programmers Guide Where InterfaceNumber is the interface number 1 2 3 etc If all you wish to do is to change a network parameter at run time then you only need to change the InterfaceBlock value EXAMPLE MODIFY AND CHANGE NETWORK SETTINGS The following is an example program illustrating how modify and save a network setting Read ConfigRecord Read InterfaceBlock Modify InterfaceBlock to affect run time values Save ConfigRecord to store new parameters P G2 So 7 3 Static and DHCP IP Address Modification Example KK RK KK KK KK KK Kk Example program to illustrate how an application can change the run time and stored Flash values for Ethernet IP mask Gateway and DNS THIS EXAMPLE APPLIES TO TOOLS RELEASE 1 95 OR LATER INTRODUCTION FOR CONFIGURATION RECORDS AND INTERFACE BLOCKS The NetBurner device contains runtime and stored Flash system configuration parameters Interface Blocks are used at runtime and Configuration Records are stored in Flash At boot time data from the Configuration Records are copied to Interface Blocks There are 3 Configuration Records as defined in netinterface h define CONFIG IF ID ETHERNET 0 define CONFIG IF ID WIFI 1 define CONFIG IF ID ETHERNET2 2
36. RTOS is pre configured integrated and running a default user task named UserMain that can be used as your main program task Detailed information can be found in the uC OS Reference Library document in nburn docs NetBurnerRuntimeLibrary directory The RTOS provides 63 priority levels numbered from 1 to 63 The lower the number the higher the priority Some of these tasks are reserved by the system such as the idle task at level 63 You can specify a priority when the task is created and change the priority later if you wish A priority level can only be used by one task at a time Be sure to check the return values when creating a task or changing a task priority to verify that the operation was successful The uC OS system files are located in the nburn system directory They are UCOS C uC OS function source code ucosmain c uC OS helper debug and start up functions Also has the stack definition for the idle task ucosmcfc c ColdFire specific uC OS functions Specifically this code module contains the OSTaskCreate function initializes the Task Control Blocks and contains the stack checking code ucosmfca s Contains the assembler functions for the ColdFire port of uC OS including functions for task switching and the timer Note that the file extension of s designates an assembly language file main c Contains the main function that does some system initialization and creates UserMain
37. Trying DHCP r n GetDHCPAddress iprintf DHCP assigned the IP address of ShowIP EthernetIP iprintf XrXn OSChangePrio MAIN PRIO ifdef DEBUG InitializeNetworkGDB endif iprintf Starting UDP Sockets Example r n Page 84 NetBurner Programmers Guide Get desination IP address iprintf Enter the UDP Server destination IP address buffer 0 0O while buffer 0 N0 Keep looping until something is entered gets buffer ipaddr AsciiToIp buffer iprintf Aryan Get the port number This application uses the same port number for send and receive iprintf Enter the source destination port number gets buffer portnum atoi buffer iprintf rin Create a UDP socket for sending receiving int UdpFd CreateTxUdpSocket ipaddr portnum portnum if UdpFd lt 0 iprintf Error Creating UDP Socket d r n UdpFd while 1 OSTimeDly TICKS PER SECOND else iprintf Sending Recieving with host ShowIP ipaddr iprintf d r n portnum Create task to recieve UDP packets We will pass the destination port number in the optional second parameter field and set the priority to 1 less than the UserMain priority so packets get processed as they are received OSTaskCreate UdpReaderTask void portnum amp UdpReaderStack USER TASK STK SIZE UdpReaderStack MAIN PRIO 1
38. VARIABLE T AG eee ee eren ee eee nee tn seen esee tn ae ee 42 10 1 THE FUNCTIONCALL TAG eene emen emen emen enne enne enne ee sn seen ses r sre r sana eae a see r eese ea ea eese trea eren en en en 42 10 2 THE WARTABIGESEAG ih tenet itti n easi ittivti a 42 10 2 1 The INCLUDE Tag and htmlvar h Header File eerte 43 10 2 2 Calling a Function with Parameters eese seen enne ennt nennen trennen rennen 45 10 2 35 Creating Custom Structures or Classes eerie enne enne tene teen neen teste en rennen 46 Page 2 NetBurner Programmers Guide 11 M8 HIS ues 47 12 TCP TRANSMISSION CONTROL PROTOCOL e eeee eese eene eee en eese en esee ense eee te e ee en aee seen seen 49 12 1 TCP SERVER INTRODUCTION ra ertet eerte nm e ee tere dre te ine Tere i Een eere 49 12 2 WRITING A NETBURNER TCP SERVER cccccecssssssscecececeessauececececsenensececececeesesseaececececsesaaececeesceessaaececeeeceenes 50 12 2 1 Simple TCP Server Application Source Code esee nennen nennen rennen 51 12 2 2 Running the NetBurner TCP Server Application eese eene nennen rennen 54 12 2 5 Simple TCP Server Using the select Function eese eene 57 12 2 4 Advanced TCP Server Using the select Function eese eene neret nente 60 12 3 WRITING A WINDOWS TCP SERVER scssccccccecsessssecesececseseseeeeececeesensaaeeeeccecsesaaeeecececees
39. a file called udpserv class To run the application now type Java udpserv listen port dest IP dest port gt where listen port is the local port number to listen for incoming datagrams dest IP gt and dest port are the IP address and port number of the host or device you wish to send datagrams to For example udpserv 2500 10 1 1 15 2501 will listen on port 2500 and send any data you type into the console to the host or device at 10 1 1 15 2501 As a quick test you can run two instances of the application on your host pc In the following example you will need to replace the IP address with the correct IP address for your host computer Open two command windows In the first window type java udpserv 3000 10 1 1 100 4000 In the second window type java udpserv 4000 10 1 1 100 3000 Now anything you type in one window will appear in the other Note that user input will only be sent once the enter key is pressed BU For additional information on UDP please refer to your User Manual From Windows Start gt Programs gt Netburner NNDK NNKD Users Manual Page 95 NetBurner Programmers Guide 14 uC OS Real Time Operating System 14 1 Overview The uC OS Operating system is a full featured pre emptive multitasking Real Time Operating System RTOS You can easily create tasks semaphores mail boxes and queues just to name a few features As part of the NetBurner development package the
40. before connecting many port numbers have been defined for common protocols and are called well known port numbers Some of these values are shown below FTP 21 Telnet 23 SMTP 25 DNS 53 TFTP 69 HTTP 80 POP3 110 NTP 123 Page 49 NetBurner Programmers Guide An important thing to remember is that it takes 4 parameters to define any TCP connection Source IP address Source port number Destination IP address and Destination port number 12 2 Writing a NetBurner TCP Server Writing a TCP server on the NetBurner platform is very straightforward 1 Create a listening socket with the Listen function 2 Wait for an incoming connection with the blocking call accept Server Client Call listen function Returns file descriptor Call accept function Will block until accepting Call connect function incoming connection then to connect to server Returns return the connection s file connection s file descriptor descriptor Send and Receive data using Send and Receive data using read and write read and write Call close to close the Call close to close the connection connection Page 50 NetBurner Programmers Guide 12 2 1 Simple TCP Server Application Source Code This example program will listen on port 23 for incoming connections send a sign on message to the client when a connection is made and display all received data to the debug serial port A telnet program
41. closesocket sListen closesocket sSend WSACleanup return 0 Starting in main the ProcessCmdLine int argc char argv function is called at the beginning of main to do what you would expect process any command line parameters Specifically you will pass the listening port number destination port number and destination IP address Before you can call any winsock functions you must load a winsock library The call to initialize winsock is WSAStartup when this function returns the WSADATA structure contains the information about the version of winsock that was loaded The MAKEWORD 1 1 macro specifies winsock version 1 1 you could specify 2 2 for version 2 2 The listen socket sListen is then created with sListen socket AF INET SOCK DGRAM 0 AF INET specifies the Internet Protocol The socket type is set to SOCK_DGRAM for TCP you would use SOCK STREAM The last parameter specifies protocol and a value of 0 tells the system to pick one based on the other two parameters Winsock applications specify IP addresses and ports using the SOCKADDR IN structure which is declared as sinListen in our program The functions htonl and htons stand for host to network long and host to network short and convert the byte order of long and short variables from the host platform little endian for a typical pc running Windows to standard network byte order big endian The INADDR ANY parameter specifies
42. cow 115200 None e fi v Display Errors M N CR CRALF TN Font Comm Events Flow Control Timeouts Disconect v Autowrap TN aiting 2sec to start fi to abort Ethernet IP 6 6 6 6 ask 6 6 6 6 AC Address 88 83 f 4 01 24 3c Application startedMy IP Address is 18 1 1 109 ainting for connection on port 23 gt Modem Status r Comm Status cts f DSR J RING RLSD CD CTSHold XOFFHold TX Char E s iiia DSRHold XOFF Sent TX Chars o RLSDHold EOF Sent Rx Chars Page 54 NetBurner Programmers Guide Run the telnet program on your host computer This can be done from the Windows Start menu by selecting Start gt Run or by opening a DOS window and simply typing telnet lt ip_addr gt where lt ip_adder gt is replaced by the IP address of your NetBurner device when finished press the Enter key For example telnet 10 1 1 117 Note You do not need to specify the port number since the telnet default port number is 23 If you use a different port number then specify it in the telnet command after the IP address for example telnet 10 1 1 117 4332 You should see the following screen on a successful connection cx Telnet 10 1 1 109 Welcome to the NetBurner TCP Server Vou are connected to IP Address 18 1 1 109 port 23 The MTTTY window should confirm the connection E Multi threaded TTY DoR Port Baud Parity Data Bi
43. else iprintf Static IP address set to ShowIP EthernetIP iprintf XrXn y EnableAutoUpdate Enable network code updates OSChangePrio MAIN PRIO Set this task priority ifdef DEBUG InitializeNetworkGDB and Wait endif Create TCP Server task OSTaskCreate TcpServerTask void TCP LISTEN PORT amp TcpServerTaskStack USER TASK STK SIZE TcpServerTaskStack MAIN PRIO 1 higher priority than UserMain while 1 OSTimeDly TICKS PER SECOND 5 This is an extremely simple example designed to illustrate how the accept and listen calls operate It only listens to a single port number and processes a single connection at a time Any information sent from the Client will be displayed in the MTTTY window The application does not have the capability to terminate the incoming connection We have added the defines for the TCP listen port number and the incoming TCP buffer storage array size RXBuffer is then declared and will hold the received data The listen function call sets up a socket to listen for an incoming connection from any IP address on port number 23 the Telnet port number If the listen succeeds we then enter a second while loop The application will then block at the accept function call until an incoming connection is detected such as when we run the Telnet program on the PC When this connection is establis
44. family AF INET sinSend sin addr s addr inet addr szDestIPAddr sinSend sin port htons dDestPort printf Enter data to send to s d n szDestIPAddr dListenPort while 1 The sendto function is used to write outgoing data on a socket For message oriented sockets care must be taken not to exceed the maximum packet size of the underlying subnets You can get the size information from the getsockopt API call See the microsoft documentation for more information The sendto API function has the following parameters Page 89 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 NetBurner Programmers Guide int sendto SOCKET s const char buf buffer containing the data to be transmitted int len length of data in buf int flags indicator specifying the way in which the call is made const struct sockaddr to optional ptr to dest address structure int tolen size of address structure in bytes x char TxBuf 512 gets TxBuf if TxBuf 0 0 break else int len sizeof sinSend sendto sSend TxBuf strlen TxBuf 0 struct sockaddr amp sinSend len if sSend INVALID SOCKET printf sendto error d n WSAGetLastError break printf Sent packet to s d n inet ntoa sinSend sin addr ntohs sinSend sin port
45. first interface identifier The following lines of code are essentially what the GetDHCPAddress function does to make the DHCP process easier pDhcpObj new DhcpObject FirstInterface pDhcpObj StartDHCP Start DHCP Pend on semaphore to verify an address was obtained if OSSemPend amp pDhcpObj gt NotifySem 10 TICKS PER SECOND OS TIMEOUT Wait 10 seconds iprintf r n r n WARNING r n iprintf IP Address was set to 0 0 0 0 and a DHCP server could not be found r n iprintf Device does not have a valid IP address r n r n else iprintf DHCP assigned the following values r n iprintf IP ShowIP ib netIP iprintf r n iprintf Mask ShowIP ib netIpMask iprintf r n iprintf Gate ShowIP ib netlIpGate iprintf r n iprintf DNS ShowIP ib netDNS iprintf r n iprintf Interface Name s r n ib gt InterfaceName iprint r n AssignedDHCP TRUE void UserMain void pd InitializeStack pDHCPOfferName DeviceName Host name for DNS Page 28 NetBurner Programmers Guide int FirstInterface GetFirstInterface Get first interface identifier InterfaceBlock ib GetInterFaceBlock FirstInterface Get interface data if ib gt netIP 0 Check IP address for 0 0 0 0 and use DHCP if necessary iprintf r nNo static IP address set attempting DHCP r
46. iprintf r n iprintf Mask ShowIP cr ip Mask iprintf r n iprintf Gate ShowIP cr ip GateWay iprintf r n iprintf DNS ShowIP cr ip DNS server iprintf NrNin Change the runtime IP settings This function will display the current IP address and mask change the runtime variables to new values then display the new values void ChangeRuntimeIPSettings int InterfaceNumber IPADDR IpAddr IPADDR IpMask IPADDR IpGate IPADDR IpDNS iprintf r nChanging IP runtime settings for interface d r n InterfaceNumber Display current values InterfaceBlock ib GetInterFaceBlock InterfaceNumber iprintf Old Settings r n iprintf IP ShowIP ib netIP iprintf r n iprintf Mask ShowIP ib netIpMask iprintf r n iprintf Gway ShowIP ib netlIpGate iprintf r n iprintf DNS ShowIP ib netDNS iprintf r n iprintf Interface Name s r n ib gt InterfaceName Change to new values ib gt netIP IpAddr ib gt netIpMask IpMask ib gt netIpGate IpGate Page 26 NetBurner Programmers Guide ib gt netDNS IpDNS Display new values At this point you can communicate with the device using the new ip address and mask iprintf New Settings r n iprintf IP ShowIP ib netIP iprintf r n iprintf Mask ShowIP ib netIpMask iprintf r n iprintf Gway ShowIP ib netlIpGat
47. lt TD gt Destination Port lt TD gt lt TD gt lt INPUT NAME tfDestPortNum FUNCTIONCALL WebDestPort TYPE text SIZE 6 TD TR TR TD Destination IP TD lt TD gt lt INPUT NAME tfDestIpAddr lt FUNCTIONCALL WebDestIp TYPE text SIZE 15 Page 76 NetBurner Programmers Guide Your IP address is lt FUNCTIONCALL WebShowClientIp gt lt TD gt lt TR gt lt TR gt lt TD gt lt br gt lt TD gt lt TR gt lt TR gt lt TD gt lt INPUT NAME SendMessage TYPE submit VALUE Send Message gt lt TD gt TR lt BR gt lt BR gt lt TABLE gt lt FORM gt lt BODY gt lt HTML gt 12 4 2 NetBurner TCP Client Application Operation The application boots and executes the initialization functions in main cpp From that point forward any information sent will occur through the web server interface When a user connects to the device using a web server the information retrieved is defined by the index htm file Examining index htm we can see that the WebDestPort and WebDestIp functions are used to supply the current information into the web page text fields Looking at the functions WebDestPort and WebDestIp in clientweb cpp we can see the current settings are stored in two global variables int gDestPort IPADDR gDestlIp The function WebShowClientIp extracts the IP address from the TCP connector of the web page
48. make until your code compiles correctly When your code compiles correctly two files are created template s19 and template_APP s19 The template s19 file is memory mapped to run from RAM while template_APP s19 is memory mapped to run from Flash memory Note All compiled images will be located in the c nburn bin directory This guide will focus on Flash downloads Please refer to the section on Downloading to RAM in your User Manual for more information on downloading applications to RAM From Windows Start gt Programs gt NetBurner NNDK gt NNDK Users Manual Page 138 NetBurner Programmers Guide 21 5 Template Program Setup Before running our program lets make sure your hardware is set up correctly To run the Template program you will need your hardware to be set up as shown below Host Ethernet NetBurner Computer Hardware RS 232 The Ethernet connection should be between your host computer and your NetBurner device s RJ 45 connector The RS 232 connection should be made between your host computer s Serial port and the Debug Serial port of your NetBurner device The Serial port connection on the NetBurner device will vary with each hardware platform but it should be a DB9 connector on the processor board itself or on a separate Adapter board or Carrier board supplied with your kit Please refer to your Quick Start Guide for additional details on how to make and download files to your NetBurner device 21 5 1 Testi
49. need to know this port number in order to make a connection BKK KR KKK ARK k kkk kk kk kkk kkk ARR kkk k kk kk kk ko ko kk ICI ok ke KG KG TCP IP Server Application DESCRIPTION This Win32 console application is a TCP IP server that will listen for connections on the specified port number The application is written for Winsock 1 1 compliance COMMAND LINE PARAMETERS Usage tcpsrvWin lt port gt lt echo gt port port number to monitor for incoming connections echo yes to echo request to client no is default COMPILILATION INSTRUCTIONS Compile as Windows console application with MS Visual C 5 Include WS2_32 1lib in linker configuration REVISION HISTORY 1 12 2003 Initial Release KKK RRR RRR RRR RR ARR ARR AAR AA f include lt winsock h gt include lt stdio h gt include lt stdlib h gt include lt time h gt include lt memory h gt define RX_BUFSIZE 10000 Jmn functions void ProcessCmdLine int argc char argv DWORD WINAPI ProcessClient LPVOID lpParam Page 64 NetBurner Programmers Guide 42 WORD dListenPort 43 char szIPAddress 80 44 BOOL bEcho FALSE 45 DWORD dwStartTick dwEndTick 46 DWORD dwTotalBytesRead 48 char RxBuf RX BUFSIZE 52 FUNCTION ProcessCmdLine 54 DESCRIPTION 55 Process command line arguments 57 RETURNS Nothing 59 void ProcessCmdLine int argc char argv 60 61 if argc 2 62 63 printf Usage TCPServer port lt echo gt n
50. of the example programs you will notice that the point at which you take control of the device is at the function called UserMain The UserMain task is a uC OS task created by the system for you to use in your application Normally the first few lines will consist of system initialization functions such as the functions described in the Template example Page 97 NetBurner Programmers Guide To create additional tasks you use the OSTaskCreate function The following is an example program that allocates the task stack implements a new task function and launches the new task J KCKCKCECKCKCk Ck Ck Ck Ck Ck kk Ck Ck Ck kk CkCk kk kk kCk kk kk kCk kCk kCk kk kCk kk kk k k kk k k kk k k kc k kc k ck kckck ck KK Multiple task exampl This program creates 2 tasks and send prints messages from each FA A A A A A A A A A A A A A A A A A A A Ck Ck Ck k ck k ck k ck ck ck ckckckckck ck k kk f include predef h include lt stdio h gt include lt ctype h gt include lt startnet h gt include lt autoupdate h gt include lt ucos h gt include lt dhcpclient h gt function prototypes extern C void UserMain void pd DWORD MyTaskStack USER TASK STK SIZE Jka psonn et nooo See Se ee ee ee eE MyTask lut ee ee ee ee ee EU ee ee e void MyTask void pdata WORD data WORD pdata cast passed parameter iprintf Data passed to MyTask Sd r n data
51. on a host PC will be used to connect to the server as a client Description NetBurner Simple TCP IP Server Example Program This program will create a TCP server task which listens on port 23 by default To test the application you can use Telnet For example from a windows commpan prompt type telent lt ip address of netburner gt This example uses a simple read function to receive data from a TCP Client include predef h include lt stdio h gt include lt startnet h gt include lt autoupdate h gt include lt startnet h gt include lt dhcpclient h gt include lt tcp h gt define TCP LISTEN PORT 23 Telent port number define RX BUFSIZE 4096 const char AppName Simple TCP Server Example d Global Vars char RXBuffer RX BUFSIZE extern C void UserMain void pd void IPtoString IPADDR ia char s PBYTE ipb PBYTE amp ia siprintf s d d d d int ipb 0 int ipb 1 int ipb 2 int ipb 3 Allocate task stack for UDP listen task DWORD TcpServerTaskStack USER TASK STK SIZE void TcpServerTask void pd int ListenPort int pd Set up the listening TCP socket int fdListen listen INADDR ANY ListenPort 5 if fdListen gt 0 Page 51 NetBurner Programmers Guide IPADDR client addr WORD port while 1 The accept function will block until a TCP client requests a connection Once a client connection is acce
52. that any incoming IP address will be accepted the AF INET specifies the Internet Protocol family and the dListenPort parameter contains the value of the port the server will listen to The bind function associates the listen socket with the listen port number Page 90 NetBurner Programmers Guide A separate thread is created to handle an incoming datagrams The CreateThread API call takes the following parameters e ReceiveUDP A pointer to the thread function to execute e LPVOID sListen When creating a thread it is possible to pass a parameter to the function as a pointer In this case we are passing the listening socket sListen as pointer It is later cast back to a socket in the ReceiveUDP thread e amp dwThreadld A pointer to a variable that will hold the thread ID once it is created When CreateThread is called successfully the thread will start and begin listening for incoming datagrams Each time a datagram arrives the sender information and data will be displayed Now that the application can receive incoming datagrams we need to have a method of sending outgoing datagrams An outgoing socket is created with the line sSend socket AF INET SOCK DGRAM 0 As with sListen the sSend socket needs a SOCKADDR IN structure The sinSend is declared and initialized to allow datagrams to be sent to the host destination IP address and destination port number specified on the command line The application then e
53. the terms and conditions of these agreements return this development kit and all components to NetBurner 1 All embedded software and source code provided in this Network development kit is subject to one of four possible licenses The NetBurner Tools License most restrictive The NetBurner Embedded Software License The GNU Public License The Newlib License least restrictive 2 The GNU development executables provided in the nburn GCC M68k directory branch are subject to the GNU public license This license can be found in nburn docs GNULicense txt file 3 The runtime libraries and include files provided in the nburn GCC M68k directory branch are subject to the Newlib license This license can be found in nburn docs NetlibLicense txt file 4 The compcode application provided in the nburn pctools compcode directory is subject to the GNU public license This license can be found in the nburn docs GNULicense txt file 5 The other programs in the nburn pctools directory are subject to the NetBurner Tools License provided below 6 Allother provided source code and libraries are subject to the NetBurner Embedded Software License provided below 22 2 The NetBurner Tools Software License Copyright 1998 2008 NetBurner Inc All Rights Reserved Permission is hereby granted to purchasers of the NetBurner Network Development Kit to use these programs on one computer and only to support the development of embedded applications tha
54. to a call to OSTimeDIy TICKS PER SECOND until a shared resource is available due to a call to OSSemPend or until data is available from a network connection due to a select call It both tasks were in a blocking state then the idle task 63 would run 14 3 Default Configuration and Resources The number and types of system tasks that will be running depends on which options and features you are using in your specific application For example if your application called StartHTTP to enable web services then a system task will be created that handles web server requests The following is a list of system tasks The default values are specified in nburn include constants h The table below shows the information for the SB72 platform Name Default Description Priority Ethernet Driver 38 Handles packets sent to the Ethernet hardware IP Protocol 39 Handles the IP layer of the TCP IP protocol stack TCP Protocol 40 Handles the TCP layer of the TCP IP protocol stack PPP Protocol 44 Handles the PPP layer of the TCP IP protocol stack HTTP Protocol 45 Handles the HTTP application for the web server Main Priority 50 This is a macro used for the default UserMain priority Idle 63 What does the RTOS do when it has nothing important to do It runs the Idle Task which just loops and does nothing 14 4 Creating Tasks Whether you use the AppWizard in the IDE to create a new application or start with one
55. 10 Max number of file descriptors connections int fd_array NFDS Array of TCP file descriptors void UserMain void pd InitializeStack if EthernetIP 0 iprintf Trying DHCP r n GetDHCPAddress iprintf DHCP assigned the IP address of ShowIP EthernetIP iprintf Arn OSChangePrio MAIN PRIO EnableAutoUpdate StartHTTP EnableSmartTraps EnableTaskMonitor ifdef DEBUG InitializeNetworkGDB InitializeNetworkGDB and Wait Page 60 endif Listen for incoming TCP connections listen one time Any IP address Port number PORT Queue up to 5 incoming connection ui NetBurner Programmers Guide You only need to call requests int fdl listen 0 PORT 5 iprintf Listening for incoming connections on port d r n PORT while 1 Declare file descriptor sets for select fd_set read_fds fd_set error fds Init the fd sets FD ZERO amp read fds FD ZERO amp error fds Configure the fd sets so select knows what to process In this case any fd data to be read for inti 0 i NFDS itt if fd array i FD SET fd arrayli FD SET fd arrayli select FD SET fdl FD SET fdl amp read fds amp error fds select has an error When select will block until any fd has data to be read returns read_fds an
56. 3 THE NETBURNER EMBEDDED SOFTWARE LICENSE cccsecesecececececececececececececececececececececececececececececscececececs 141 23 NETBURNER CONTACT INFORMATION ccssssccsssscccssscccsssscccessssccccssccccsssscccessnsccecsscescssseccccssseecs 141 24 NETBURNER SUPPORT INFORMATION cssssccssssscccssscccsssscccessssccccssccccessaccccssnsccecsceccsssaccccssssecs 141 25 REVISION IRAKO SA EPL 5 Page 4 NetBurner Programmers Guide Revision History Revision Date Description 3 1 10 27 2007 Added HTML Variable tag section 3 2 2 8 2008 Updated SRAM section 18 with description of 2 1 RC6 implemenation of SRAM usage 3 3 4 18 2008 Added OSFlags and updated examples in RTOS 3 31 3 8 2010 Fixed example code in section 12 so that read function using RX_BUFSIZE would read a maximum of RX_BUFSIZE 1 so that a NULL can be appended without overflowing the buffer 3 32 10 29 2010 Added text in intro paragraph explaining this document applies only to the NetBurner Standard TCP IP Stack Added Dynamic Memory section and mallinfo example 3 33 2 9 2011 Corrected Error in File Descriptor section 5 37 changed to 5 36 e 5 36for TCP 32 in total e 37 63 for expansion additional UARTs TCP sockets or custom Page 5 NetBurner Programmers Guide 1 Introduction 1 1 How to Use This Guide The NetBurner Programming Guide is intended to provi
57. CKCKCKCkCkCkCkCk Ck k Ck ck k ck ck ck ckckckckck ck kk f include predef h include stdio h include ctype h include startnet h include autoupdate h include dhcpclient h include smarttrap h include taskmon h Page 117 NetBurner Programmers Guide include lt iointernal h gt const char AppName ExtraFD Example static IoExpandStruct cb ioexpand extern C void UserMain void pd A circular buffer object referred to as a cbo struct CircularBufferObject OS CRIT critical section Critical section to make it task safe BYTE get pointer Where we get chars in the buffer BYTE put pointer Where we put chars in the buffer char data buffer 256 Data storage space J acnsescolvaliltepecleulnu s es c ee See ee Function to read from the circular buffer Be a ae See EEN E E A A AS int cbo read int fd char buf int nbytes Get the cbo object associated with this fd CircularBufferObject pCbo CircularBufferObject GetExtraData fd int number read 0 Set up the critical section so we have exclusive access OSCritEnter amp pCbo critical section 0 If both get and put pointers point at each other there is nothing in the buffer otherwise we can read the data if pCbo get pointer pCbo put pointer Read as long as data is availible and we have not read the max all
58. DHCP Object instead of using the GetDHCPAdderss function which handles this automatically DhcpObject pDhcpObj Add a device name for DNS const char DeviceName NetBurner extern const char pDHCPOfferName point this at above name in UserMain UR Display runtime IP values This function demonstrates two methods to read the runtime IP values 1 Using the read only Interface function calls 2 Using the GetInterfaceBlock function to get a pointer to an Interface Record void DisplayRuntimeIPSettings int InterfaceNumber iprintf r n r n RUNTIME IP SETTINGS r n if AssignedDHCP iprintf Values assigned by DHCP Server r n Display current runtime values using Interface read only functions iprintf IP runtime settings using Interface Functions for interface d r n InterfaceNumber iprintf IP ShowIP InterfaceIP InterfaceNumber iprintf r n iprintf Mask ShowIP InterfaceMASK InterfaceNumber iprintf r n iprintf Gate ShowIP InterfaceGate InterfaceNumber iprintf r n iprintf DNS ShowIP InterfaceDNS InterfaceNumber iprintf r n Display current runtime values by getting a pointer to the Interface Block and accessing it s variables iprintf r nIP runtime settings using GetInterfaceBlock for interface d r n InterfaceNumber InterfaceBlock ib GetInterFaceBlock InterfaceNumber ip
59. IME FUNCTIONS csisvescetde ette leueu cuoc a etenotva va eei E cubep aet ees tva eee e Qe ee bey ene eub Vete cveves 131 20 DYNAMIC MEMROY ALLOCATION AND FREE SPACE 4 eere ee esee en eese enne e eee tn oeste tese etta a 132 21 THE TEMPLATE PROGRAM COMMAND LINE MODE eee ee eren eee enne eee tn eese ta esset tn ae ee 135 21 1 TEMPLATE PROGRAM SOURCE CODE ccccccecececececececececececececececececececececececececececececececececeeeceeecececececeeseseeeecs 136 21 2 COMPILING AND RUNNING THE APPLICATION OVERVIEW cccccccecececececececececececececececececececececececececececesecs 137 213 CREATING A MAKBEILE e rere er etae eee ete bee ere desee e e beet ene eee esee eere e be ER e 137 214 COMPILING THE lt APPLICA TION ve A hetodteeee deese ore dee tte eee ore edet desee diee dore ode deaedianss 138 2 1 5 STEMPEATE PROGRAM SBTUP 4 iere ette dee nore eet eese eere diode iaee 139 21 5 1 Testing the RS 232 Debug Connection eese enne nennen eene ene 139 22 SOFFWARE LICENSING 5 ewe eseeceecesveee eu iosu ce coro Vae op eUoo D es Vo ae e ep sva Po ea Fo VeL sb soits sso bebei SoSe e ce oS Vea oi eae 140 22 NETBURNER LICENSE AGREEMENT ccccccccececececececececececececececececececececececececececececececececececececececececececececevecs 140 22 2 THE NETBURNER TOOLS SOFTWARE LICENSE ccccccccecececececececececececececececececececececececececececececseececeeecececesecs 140 22
60. InitializeNetworkGDB and Wait endif Create TCP Server task OSTaskCreate TcpServerTask void TCP_ LISTEN PORT amp TcpServerTaskStack USER TASK STK SIZE TcpServerTaskStack MAIN PRIO 1 higher priority than UserMain while 1 OSTimeDly TICKS_PER_SECOND 5 Page 59 NetBurner Programmers Guide 12 2 4 Advanced TCP Server Using the select Function The following example will use the select function to process up to 10 simultaneous TCP connections Description NetBurner TCP IP Server Multiple Socket Example Program Filename main cpp This example creates a CP server that listens on the specified CP port number and can handle multiple TCP connections simultaneously 10 in this example An easy way to test th xample is to use multiple Telnet sessions to create simultaneous connections to the NetBurner device Status messages are sent out stdio to the debug serial port and to the client TCP connections include predef h include lt stdio h gt include lt ctype h gt include lt startnet h gt include lt autoupdate h gt include lt dhcpclient h gt include lt smarttrap h gt include lt taskmon h gt include lt tcp h gt include lt networkdebug h gt extern C void UserMain void pd const char AppName TCP Multiple Sockets Example define PORT 1000 TCP port number to listen on define NFDS
61. KK This is a UDP example Java application to send and receive UDP datagrams It will listen on a port for incoming UDP packets and allow the user to send strings as UDP datagrams to another host This application can run on Windows Unix or Linux hosts with the Java Virtual Machine installed It is not designed to run on the NetBurner platform Revision 1 0 May 31 2003 eK A A A A A RAR A A k k k k k k k k k KKK import java net import java io UDP Server Class This class will 1 Parse command line parameters for the local port number destination ip address and destination port number 2 Obtain the local host name and ip address then display all parameters to the console 3 Declare an instance of the client UDP class which will handle local host user input and allow the user to send strings 4 Start the UDP server thread that will loop forever listening for incoming UDP packets on the designated port All incoming messages will be displayed to the console window along with the sender s ip address and port number nae rA EM DNUS HITS ICE ETE public class udpserv protected DatagramSocket dgSocket declare socket Constructor public udpserv int port throws IOException dgSocket new DatagramSocket port allocate socket Page 92 NetBurner Programmers Guide 42 43 execute loop to wait for incoming datagram packets 44 public void execute throws IOException
62. LICATION ccce nennen enne ether enn 92 13 4 1 Windows Java UDP Application Source Code esee nennen nene 92 13 4 2 Running the Windows Java UDP Application cesses nennen nenne 95 14 UC OS REAL TIME OPERATING SYSTEM eere ee eee eene eee enne eet to sese ea see seen ases esee esee aee seen seen 96 TAM J OVER VIEW A 96 14 2 PRE EMPTIVE OPERATION AND BLOCKING ccsessssecececeesensecececececseueceeececeesesssaesecececseaaececececeeneaasseseceeeenes 96 14 3 DEFAULT CONFIGURATION AND RESOURCES ccsssssscseceesessscecececsesesseaececececsesseaesecececeeseaececeeeceenenssaeseeeeeenes 97 14 4 CREATING TASKS eerte SE ete eee pee to terere ie pre eee Poe eee PU eee pe Ee ee ee FART 97 142 5 INTERRU PTS aee te AET ET ee erbe e eee E Mh AN bee ates D OPES E E ESE EEEE O EOE 99 15 PROTECTING SHARED DATA STRUCTURES eee eeee ee ee eese enne sete ense etta sese teen Pese ee to eese ea sese seen ae ee 100 15 1 1 OT RUTAS EN UNES 100 AS AZ Semaphore Example tte a DE EEEE DUE ESEE EUPQU E ROUGE 102 LS ADB Mailbox Example sete doeet v DERE e etae e RE PR rA SEP EIER ee 104 ISLA RBIFOsEx mple 5 ede e d ea RD EE EA DUE ERE ERU EE DEOR ROC 107 ISAS OSCritObject Example tede ete v ERE M Cete TUE PvE PA REP EXER RU 110 15 16 OSFlags Example tee e da ei ORO RU DRE EE rr ERE A EUG ER OUR 112 16 IgIB
63. M e iBurner Networking in 1 Day NetBurner Network Development Kit Programming Guide Document Number 350080 003 NetBurner Programmers Guide T INTRODUCTION eer eee eee do eee epe e vaa ae ce eeu oa eoe aoc Dun aao eer eau ee CERE Rue Casa eoo ech ives adesedsccseseuescvestadedssuteasosesscesdeaseua 6 1 1 HOW TO USE THIS GUDE nnti ect recette oe ce cc Lene tr reo ce exte Lope ce epe EHE Ee 6 1 2 SOURCE CODE FOR EXAMPLE PROGRAMS ccccccecececececececececececececececececececececscececscscecscececececececececeeecesececeeecess 6 1 3 How TO USE THE NETBURNER REFERENCE DOCUMENTS eceeeee ee ee ene enenenen eren nsns nsns ese ese n nsns nsns erue 6 1 4 NETBURNER NETWORK DEVELOPMENT KIT CONTENTS eeeeeeeeeneene e eme emen ener esent ese ese e ese nsns nsns nsu 7 1 5 GETTING STARTED Ss c eectceten citet eive ioc ten Oe eren i cete BE ER ED EL HER ton AG a a 7 1 5 1 Software Installation i SO RSEN OR Ae SR er E 7 1 5 2 Hardware INSIGUOQHON ieee ES OR A BO eS 8 1 5 3 Network Configuration oer ERE REED EREU PO HERE 8 1 5 4 Debug Port ies a Dh aene a despa Ea RR E DR EPI e etd 9 2 NETWORKING DEVICE CONFIGURATION e eee ee eese eese seen sese ee tn sesta ense sete eese enne e seen eese ee se eee etna e eS 10 2 1 OVERVIEW cic acetate tte tete et deti tete te cele det te etii uet dele e diet tette t de acts 10 2 OBTAINING AN IP ADDRESS i eee etes te cede cete cde t cedet se a eub a tee cede te ae been 10
64. SocketRemoteAddr sock buf writestring sock buf P n Handle HTTP Post WARNING The User data space is 8K in size The object we are storing is less than 200 bytes long thus it is probably ok to make an automatic variable out of it It would NOT BE OK to make an 8K automatic variable The coices for doing this with an 8K object First choice make a global variable this way the linker will allocate space for it All errors will be at link time not run time Second choice Increase the HTTP stack size in constants h and recompile the whole system directory Third choice use malloc and free The only problem is what do you do if malloc fails int MyDoPost int sock char url char pData char rxBuffer int max chars 40 This buffer is 4096 bytes so make it a static so that it does not take up task stack space but instead uses global space static char buf POST BUFSIZE iprintf Post Data s r n pData print all data sent from app The SendMessage button on the web page initiates a form POST to send the message to the TCP server if ExtractPostData SendMessage pData buf max chars gt 0 iprintf Processing SendMessage Post r n if ExtractPostData tfDestPort pData buf max chars 1 iprintf Error reading post data tfDestPort
65. Tools Help aw Q eR X x E EA p Search Sie Favorites media E2 R f S zm E gt Address http 10 1 1 114 INDEX HTM Go Google Search Web Goes Norton Antivirus x Ak gt D enun ur Networking in 1 Day Internet Page 32 NetBurner Programmers Guide 9 Interactive Web Form Example 9 1 Introduction Dynamic HTML is generated at run time on your NetBurner device it is not a static web page For example if you wanted to create a front panel for an instrument in which the HTML page would change depending on the current operating parameters and measurements that would be Dynamic HTML This can be as simple as putting values into predefined slots or generating whole pages from scratch at run time For more information about Dynamic HTML see the flashform and tictactoe example projects in C Nburn examples The short version of Dynamic HTML Dynamic HTML works just like normal HTML It just requires a special TAG within the HTML files Anywhere you want to include Dynamic HTML in your HTML files you would add the TAG lt FUNCTIONCALL YourFunctionName gt Then in your project source code you must include this C function void YourFunctionName int sock PCSTR url l writestring sock buffer Data to output goes here Your function name is assumed to be a C function by the linker Therefore if you are using C you must include the following before your f
66. a char s PBYTE ipb PBYTE amp ia siprintf s d d d d int ipb 0 int ipb 1 int ipb 2 int ipb 3 Allocate task stack for UDP listen task DWORD TcpServerTaskStack USER TASK STK SIZE void TcpServerTask void pd Page 57 NetBurner Programmers Guide int ListenPort int pd Set up the listening TCP socket int fdListen listen INADDR_ANY ListenPort 5 if fdListen gt 0 IPADDR client_addr WORD port while 1 The accept function will block until a TCP client requests a connection Once a client connection is accepting the file descriptor fdnet is used to read write to it iprintf Wainting for connection on port d Mn ListenPort int fdnet accept fdListen amp client addr amp port 0 iprintf Connected to ShowIP client addr iprintf dWMn port writestring fdnet Welcome to the NetBurner TCP Server r n char s 20 IPtoString EthernetIP s siprintf RXBuffer You are connected to IP Address s port dNrMn s TCP LISTEN PORT writestring fdnet RXBuffer int tcp timeout 0 while fdnet gt 0 declare file descriptor sets fd_set read_fds fd_set error fds Clear all bits in fd sets FD ZERO amp read fds FD ZERO amp error fds Set bits in fd sets for our fd fdnet FD SET fdnet amp read fds FD SET fdnet amp error fds Select will block until an event occurs and a fd se
67. a cpp Include the file that does all of the automagic work include NBROOT make main mak htmldata cpp wildcard html comphtml html ohtmldata cpp m BWNRKTODNDMNBRWNE Page 137 NetBurner Programmers Guide Once you have created a single makefile you can copy it to the project directories of any applications you create in the future Note If you application does not use HTML the only lines you will need to change will be the name of the application line 2 and the list of source code files line 3 If your application uses the Web Server and HTML simply uncomment lines 8 13 and 14 you do not need to modify these lines Line 2 specifies the name of the application image file that will be built Ours is called template Note there is not a semicolon after the here Line 3 specifies the C source code files that need to be compiled We only have one file in this example If your project has more than one source code file you would just add them to this line separated by spaces Lines 6 and 7 specify C and S assembly language source files Line 8 is used for applications that use HTML and the web server You do not need to change the file name Line 11 calls additional make files that are part of your NetBurner tool set Lines 13 and 14 are used to process code used by the Web Server such as HTML Note Do not uncomment these lines unless you have a directory named html
68. aaseeseesesesenaeaeseeeeeenes 64 12 3 1 Windows TCP Server Application Source Code esee enne nennen nenne 64 12 3 2 Running the Windows TCP Server Application essent 68 12 4 WRITING ANETBU RNER TCP CLIENT si 5 estie tete coo rit co Ps rore Sie deesuenv ints este xe ere R ee eee deed ve redi 69 12 4 1 NetBurner TCP Client Application Source Code eese eene nennen nennen 71 12 4 2 NetBurner TCP Client Application Operation eese esee eene tenerent entente tnnt 77 13 UDP USER DATAGRAM PROTOCOL e eere ee ee ee en ee etta ese ee tone sete tn sese ease e ee eo ases een eee enne eee tnos esta 78 13 1 UDP CLIENT SERVER APPLICATION USING THE UDP CLASS cccccsscccccecsessnsececececeessnececececeenenseaeeeeeeeenes 78 13 1 1 NetBurner UDP Class Application Source Code esee 79 13 12 Running the Application sut o er sep rm e RR E ERR EAT A E E ET CU EAS ENE aani 82 13 2 UDP CLIENT SERVER APPLICATION USING UDP SOCKETS cccssccccsssseeesssececeessececseceecessneeecsesaeeeeseeaeeess 83 13 3 WRITING A WINDOWS UDP CLIENT SERVER APPLICATION eese enne nennen nennen nennen ener nnne en 86 13 3 1 Windows UDP Application Source Code cessent enne nennen nenne entren 67 13 3 2 Running the Windows UDP Application cessent enne nennen renes 91 13 4 WRITING A WINDOWS JAVA UDP CLIENT SERVER APP
69. address and destination port number When the web page first loads it will automatically fill in the IP address from the source requesting the web page because in most cases it will also be the address of the TCP Server The web page is a form and when a user presses the submit button the SendMsg function will open a TCP connection to the server send the message and close the connection Any error messages will be sent to stdout and can be viewed with MTTTY A TCP server program must already be listening at the specified IP address and port number for the message to be sent A simple TCP Server called TcpServerWin exe is located in the nburn pctools directory of your NetBurner installation X 0 F X F XR X F F Xo Xo X X include predef h include lt stdio h gt include lt stdlib h gt include lt ctype h gt include lt startnet h gt include lt iosys h gt include lt utils h gt include lt ip h gt include lt tcp h gt include lt string h gt include clientweb h define APP VERSION Version 1 1 4 23 2008 define POST BUFSIZE 4096 form post buffer size gt function prototypes extern C void WebDestPort int sock PCSTR url void WebDestIp int sock PCSTR url void WebShowClientIp int sock PCSTR url Page 73 NetBurner Programmers Guide int gDestPort IPADDR gDestIp void IPtoString IPADDR ia char s PBYTE ipb PBYTE amp ia si
70. age similar to Waiting to boot If you see this message then you are connected correctly For additional information please refer to your User Manual From Windows Start gt Programs gt Netburner NNDK gt NNDK Users Manual Page 18 NetBurner Programmers Guide 5 4 Compiling and Running the Application Now that we have the application source code file we need to compile it into a code image and download it to your NetBurner device There are four methods to download your applications 1 Through the serial port 2 Through a network connection using AutoUpdate This is the preferred method and can be run from within the IDE or as a stand alone application 3 Through a network connection using TFTP 4 Through a network connection using FTP In order to execute your application on your NetBurner device you will need to do the following 1 Compile the source code into an application image 2 Download the application image to the flash memory of the NetBurner device 3 Reboot the NetBurner device so the application can begin execution The NBEclipse IDE uses the AutoUpdate functionality to download code to your NetBurner device by using a Run Configuration The device will then reboot and begin execution of the new application If you are unfamiliar with this process please reference the NBEclipse Getting Started Guide Once the download is complete you will see the debug messages appear in MTTTY along with
71. alls OSCritLeave iprintf GlobalVariable d r n GlobalVariable while 1 OSTimeDly TICKS PER SECOND 5 this is a blocking call Page 111 NetBurner Programmers Guide 15 1 6 OSFlags Example OSFlags enables a function or task to pend on multiple flags events in contrast to a OSSemaphore which which can pend on only a single event The OSFlag implementation is basically a 32 bit bitmap in which each bit position represents a flag You create a OSFlag object with OSFlagCreate then set clean and read the flags with the appropriate functions There are a number of functions used to monitor or pend on the flags and provide the ability to pend on any one or more of the flags being set or pending on all of flags being set at one time Flag Functions OSFlagCreate Creates and initializes an OS_FLAGS object OSFlagSet Sets the bits asserted bits_to_set OSFlagState Returns the current value of flags OSFlagClear Clears the bits asserted in bits_to_clr OSFlagPendAll Waits until all of the flags indicated by mask are set OSFlagPendNoWait Checks but does not wait if all of the flags indicated by the mask are set OSFlagPendAny Waits until any of the flags indicated by the mask are set OSFlagPendAnyNo Wait Checks but does not wait if any of the flags indicated by the mask are set This illustrates how OSFlags can be used to pend on multiple events UserMain creats 3 tasks each of which w
72. amming tutorial for network platforms NetBurner Runtime Libraries Library reference guide for network and non network platforms uC OS Reference Manual Library reference for uC OS Real time operating system Mod5213 Programmers Guide Programming tutorial for Mod5213 devices EFFS Programmers Guide Embedded Flash File System programming tutorial Freescale Processor Manual Freescale detailed manuals for ColdFire microprocessors GNU Manuals Manuals for GNU C C libraries compiler an linker This includes the C C language API functions NetBurner PC Tools Reference manual for NetBurner tools that run on the PC such as IPSetup Autoupdate and MTTTY Platform Manuals for NetBurner Hardware These are the NetBurner hardware manuals that include schematic information memory maps and design guides There are a number of very useful resources available e Your support account at http support netburner com e The NetBurner public newsgroup located at groups yahoo com Page 6 NetBurner Programmers Guide 1 4 NetBurner Network Development Kit Contents You development kit contains everything you need to immediately begin writing network applications NetBurner Hardware Platform uC OS Real Time Operating System NetBurner TCP IP Stack NetBurner Web Server NBEclipse Integrated Development Environment IDE Command Line Tools for those who prefer not to use Eclipse GNU C C Compiler and Linker NetBurner Configuration Utilities in
73. an be downloaded over a network connection instead of through a serial port or a BDM Background Debug Mode port The Debug Monitor The NetBurner device contains a flash memory boot sector loaded with a boot program called the Debug Monitor This program is designed to be very small and takes up less than 16 Kbytes of memory space The Debug Monitor is not designed to provide full TCP network communications although it does support the TFTP protocol The full TCP IP Stack functionality is compiled as part of your application If you download an application that immediately crashes when it boots full network services will not be available In this case the NetBurner Debug Monitor comes to the rescue Once in the Debug Monitor at the NB prompt you can download a working application through the serial debug port See the section on serial downloads using the Debug Monitor for more information 5 1 Create a New Project with the AppWizard The NetBurner Application Wizard will create a project and C C source code for your application This is a great way to start a new project since you can add functions like DHCP and HTML processing by selecting the appropriate checkbox items in the Application Wizard dialog box The screenshot below shows the features selected in the NBEclipse Application Wizard to produce the code for the Template Program Page 13 NetBurner Programmers Guide New Project NetBurner Project Options Set the va
74. ata and number of characters The data and amount is then displayed to the console window with a printf If data has been read and the echo option enabled the data is sent back to the client If the number of bytes read is zero or an error has occurred the socket is closed Line 137 Declaration of the listen and client sockets The client socket will be passed to the thread when it is created Line 138 Before you can call any winsock functions you must load a winsock library The call to initialize winsock is WSAStartup when this function returns the WSADATA structure contains the information about the version of winsock that was loaded The MAKEWORD 1 1 macro specifies winsock version 1 1 you could specify 2 2 for version 2 2 Line 139 Winsock applications specify IP addresses and ports using the SOCKADDR IN structure This line declares structures for the listen and client sockets Page 67 NetBurner Programmers Guide Line 151 Create the listen socket AF_INET specifies the Internet Protocol The socket type is set to SOCK_STREAM for UDP you would use SOCK_DGRAM The last parameter specifies protocol and a value of 0 tells the system to pick one based on the other two parameters Lines 159 161 Assign values to socket address structure The functions htonl and htons stand for host to network long and host to network short and convert the byte order of long and short variables from the host platform
75. cation on your NetBurner device you will need to do the following Create a makefile which is used to compile and link your source code Download your code to your NetBurner device Burn this code into the Flash memory Reboot your NetBurner device TO Thankfully this is a very simple process that can be accomplished with a single build command The first step is to create a makefile which is used to tell the compiler how to compile the source code Once we create the first makefile it can be used as a template for your future projects For additional information please refer to your User Manual From Windows Start gt Programs gt Netburner NNDK gt NNDK Users Manual 21 3 Creating a makefile Below is the makefile for the template example application The file name is makefile with no extension Simply copy and paste the code below using your editor of choice and save this file as makefile in the c netburner template directory Note The makefile should always be located in the same directory as your application source code The makefile below will work for applications with or without HTML support as described in the comments Note A comment in C is signified by the character at the beginning of a line Build NAME x and save it as NBROOT bin NAME x NAME template CXXSRCS main cpp Uncomment and modify these lines if you have C or S files CSRCS foo c ASRCS foo s CREATEDTARGS htmldat
76. choice Increase the HTTP stack size in constants h and recompile the whole system directory Third choice use malloc and free The only problem is what do you do if malloc fails int MyDoPost int sock char url char pData char rxBuffer Page 38 NetBurner Programmers Guide int max_chars 40 char buf gPostBuf post buffer is global iprintf pData print all data sent from app Process UTC Local radio buttons if ExtractPostData radioUTC Local pData buf max chars 1 iprintf Error reading post data radioUTC r n else if strcmp buf UTC 0 NV_Settings bUTC TRUE else NV_Settings bUTC FALSE Process Local Offset Hours text field if ExtractPostData tfLocalOffHours pData buf max chars 1 iprintf Error reading post data tfLocalOffHours r n else NV Settings nLocalOffset atoi buf Process Leap Second Day checkbox if ExtractPostData ckboxLeapSecDay pData buf max chars 1 NV Settings bCkboxLeapSecDay FALSE else NV Settings bCkboxLeapSecDay TRUE Process Leap Second Day text field if ExtractPostData tfLeapSecDay pData buf max chars 1 iprintf Error reading post data tfLeapSecDay r n else NV Settings nLeapSecDay atoi buf Process Leap Sec Day Add Sub radio buttons if ExtractPostData radioLeapAddSub pData buf max chars 1 iprintf Error reading p
77. cluding IPSetup and AutoUpdate Power Supply Serial Cable Standard Network Cable blue and Cross wired Network Cable red 1 5 Getting Started This guide will provide an overview of how to install and configure your NetBurner tools and devices but please refer to the Quick Start Guide and User Manual from Windows Start Programs Netburner NNDK gt NNDK Users Manual that came with your development kit for additional details 1 5 1 Software Installation NetBurner software and tools run on Windows 2000 XP and Vista Insert the CD into the CD ROM drive The Autorun feature should automatically start the install If it does not run setup exe from the CD ROM In addition you will need Java JRE 1 5 or later to run the NBEclipse IDE Page 7 NetBurner Programmers Guide 1 5 2 Hardware Installation Your Network Development Kit includes one of several possible NetBurner hardware platforms Each platform will require a power connection an Ethernet network connection and an optional serial connection Please refer to the Quick Start Guide that came with your hardware platform for detailed instructions Once the hardware installation is complete you should have the equivalent of one of the two block diagrams below Connection using cross over Ethernet cable red Host Ethernet red cross over cable NetBurner Computer Hardware RS 232 Connection using standard blue Ethernet cables Ethernet Host Ethernet Switch
78. ctive web functions iadweb h Header file for iadweb cpp Html index htm HTML source file Page 35 NetBurner Programmers Guide 9 6 Interactive Web Functions The source code file iadweb cpp handles the web functions and interface for the application It has the following functions e Definition and initialization of non volatile flash storage e Handles FUNCTIONCALL tags from the web page index htm e Handles web page POSTs and extracts form data The source code for iadweb cpp is shown below 1 include predef h 2 include lt stdio h gt 3 include lt stdlib h gt 4 include lt startnet h gt 5 include lt iosys h gt 6 include lt utils h gt J include lt ip h gt 8 include lt tcp h gt 9 include lt htmlfiles h gt 10 include lt http h gt 11 include lt string h gt 12 include lt basictypes h gt 13 include iadweb h 14 15 16 define VERIFY KEY 0x10220002 NV Settings key code 17 18 19 typedef struct NV SettingsStruct non volatile storage structure 20 21 DWORD VerifyKey 22 BOOL bUTC 23 int nLocalOffset 24 BOOL bCkboxLeapSecDay 25 int nLeapSecDay 26 BOOL bLeapSecDayAdd 27 BOOL bEnableDST 28 h 29 30 31 Himas global vars 32 char gPostBuf 1000 33 NV SettingsStruct NV Settings 34 const char FirmwareVersion 1 0 12 17 2002 35 36 37 38 f
79. d or or an error amp read fds amp error fds should also process the listen fd or error fds variables will have been modified to reflect the events sf select FD SETSIZE amp read fds If the listen fd has a connection request fd set 0 amp error fds 0 accept it if FD ISSET fdl amp read fds IPADDR client ip WORD client port int fda accept fdl amp client ip amp client port 0 If accept succeeded find an open fd array slot if fda gt 0 for int i 0 i lt NFDS i if fd_array i 0 fd_array i fda writestring fda Welcome Q to quit iprintf Added connection on fd d d i fda Page 61 NetBurner Programmers Guide ShowIP client_ip iprintf sd n client port fda 0 break If no array positions are open close the connection if fda writestring fda Server Full iprintf Server Full r n close fda If the listen fd has an error close it and reopen if FD ISSET fdl amp error fds close fdl fdl listen 0 PORT 5 Process each fd array element and check it against read fds and error fds for int i 0 i lt NFDS i if fd arrayli Check for data to be read if FD ISSET fd_array i amp read fds char buffer 21 int rv read fd_array i buffer 20 if rv gt o0O buffer rv 0 if buffer 0
80. ddress DestAddr InetAddress getByName DestIP 88 Start thread to accept user input strings and send them 89 as UDP datagrams This is the client side of this example 90 clientUDPThread ct new clientUDPThread DestAddr DestPort 9 Gt start sg 92 93 Start server execution to receive UDP datagrams 94 serverUDP execute 95 96 97 98 99 0Uc UsstaScecuesrdpendcecsaecspecEpecdce ee ee ee sa ee oe end eee 101 UDP Client Class 102 This class simply waits for user input from the console creates 103 a UDP datagram with the input data and sends the datagram to 104 the designated destination host COS ee a M EN MEME ee a as 106 class clientUDPThread extends Thread 107 108 int DestPort 109 InetAddress DestAddr n protected DatagramSocket dgSocket declare socket Page 93 NetBurner Programmers Guide 112 public clientUDPThread InetAddress DestinationAddr int DestinationPort throws 113 IOException 114 115 dgSocket new DatagramSocket DestPort allocate socket 116 DestAddr DestinationAddr 117 DestPort DestinationPort 118 119 120 public String GetUserInput 121 122 String s 123 124 try 125 while true 126 char c char System in read 127 if c r 128 c char System in read 129 if c An 130 break 131 else 132 continue 133 134 else if c WMn 135 break 136 else 137 S C store char
81. de lt startnet h gt include lt autoupdate h gt include lt startnet h gt include lt dhcpclient h gt include clientweb h Function Prototypes extern C void UserMain void pd void UserMain void pd InitializeStack Initialize the TCP IP Stack if EthernetIP 0 iprintf Trying DHCP r n GetDHCPAddress iprintf DHCP assigned the IP address of ShowIP EthernetIP iprintf XrXn else iprintf Static IP address set to ShowIP EthernetIP iprintf r n StartHTTP Start the Web Server EnableAutoUpdate Enable network code updates OSChangePrio MAIN PRIO Set this task priority RegisterPost Register HTML Post function while 1 OSTimeDly TICKS PER SECOND Page 72 NetBurner Programmers Guide ClientWeb h This is the header file for clientweb cpp and contains the declarations for functions called by main cpp ifndef NB CLIENTWEB H define NB CLIENTWEB H Function Prototypes void RegisterPost endif ClientWeb cpp This code module handles the dynamic content and web server interface When the web page is displayed current values for the port numbers and IP addresses must be displayed The user must be able to change these values and also be able to send a message with the submit button This code implements the web pag ntries for the message desination IP
82. de an overview of the features and capabilities of the NetBurner Network Development Kits that use the NetBurner Standard TCP IP Stack If you have a development kit that uses the SBL2e hardware platform and NetBurner Single Chip TCP IP Stack please refer to the SBL2e Programmers Guide The primary goal of this guide is to provide a brief explanation of common network applications and illustrate how you can implement these applications using NetBurner hardware software and development tools The approach of this guide is to learn by example The first program example called Template can be used as a starting point for most applications and each application in this guide uses it as a base This guide should be useful to those new to embedded networking and to experienced network professionals who are unfamiliar with the NetBurner tools 1 2 Source Code for Example Programs Source code for all the examples in this manual as well as the latest manual revision can be downloaded from http www netburner com in the support section 1 3 How to Use the NetBurner Reference Documents All documentation is located in the doc directory of your tools installation The default location is c nburn docs These documents include NBEclipse Getting Started Guide Installation instructions and users guide for NBEclipse This is required reading before using NBEclipse Network Programmers Guide Progr
83. e iprintf r n iprintf DNS ShowIP ib netDNS iprintf r n iprintf Interface Name s r n ib gt InterfaceName Store new IP address and mask settings to the configuration record in Flash In most cases you would have already changed the runtime values to the same settings void ChangeFlashIPSettings int RecordNumber IPADDR IpAddr IPADDR IpMask IPADDR IpGate IPADDR IpDNS iprintf r nChanging Flash settings using RawGetConfig for Record d r n RecordNumber Get pointer to Configuration Record ConfigRecord cr RawGetConfig RecordNumber Display current Flash values iprintf Old Settings rin iprintf IP ShowIP cr ip Addr iprintf NrMn iprintt Mask ShowIP cr ip Mask iprintf r n iprintf Gate ShowIP cr ip GateWay iprintf NrNin iprintf DNS ShowIP cr ip DNS server iprintf r n create new config record and copy data ConfigRecord NewRec memcpy amp NewRec cr sizeof NewRec Change parameters NewRec ip Addr IpAddr NewRec ip Mask IpMask NewRec ip GateWay IpGate NewRec ip DNS server IpDNS Write new values to Flash system configuration sector UpdateConfigRecord Num amp NewRec RecordNumber Display current Flash values iprintf New Settings r n iprintf IP ShowIP cr ip Addr iprintf r n iprintf Mask ShowIP cr ip Mask iprintf r n iprintf Gate
84. e created by the AppWizard The page will contain some text and an image Using HTML Tools You can use HTML tools such as Dreamweaver to create your web content However remember that EVERYTHING in the html directory is included in the application image Some HTML tools can leave large project files in the html directory that will take up a large portion of your application space You should remove any such files before building your project Edit the index htm file as shown below HTML BODY lt IMG SRC Logo jpg BORDER 0 gt lt IMG SRC SB7210 jpg BORDER 0 gt lt H1 gt Thank you for NetBurning lt H1 gt lt BR gt lt BODY gt lt HTML gt The lt HTML gt and lt BODY gt tags define the file as containing HTML content and provide delimiters for the body of the web page The lt IMG gt tags are used to display the logo and board pictures The text message Thank you for NetBurning is then displayed The lt H1 gt tags specify that the text be displayed as a header in larger bold font Note The images are available with the project files as a download from www netburner com If you do not have these files you can simply delete the two lines with the lt IMG gt tags and display only the text Now compile and download the application When you view the web page the output should look like the screen shot below Zh http 10 1 1 114 INDEX HTM Microsoft Internet Explorer DES File Edit View Favorites
85. e run time copy for the first interface it is recommended you use the Getlfconfig function to get a fresh copy for the specific interface you want to modify THE NETWORK INTRFACE BLOCK While the ConfigRecord described in the previous section is used to store parameters in flash the InterfaceBlock structure is used during system run time to store the network configuration settings for each network interface At boot time the network settings from the ConfigRecord are read and copied to the InterfaceBlock As of tools revision 1 95 the values of the device IP address mask gateway DNS etc are controlled by a structure located in nburn include netinterface h The netinterface method was created to enable devices to have multiple network interfaces such as multiple Ethernet ports and WiFi The configuration information is kept in a linked list of structures with the following format struct InterfaceBlock MACADR theMac PADDR netIP PADDR netIpMask PADDR netIpGate PADDR netDNS ndNetBuffer send func illInterface kill if EnableMulticast enab multicast const char InterfaceName int config num Fh AX UO HH HH be The functions to get an existing structure or save a modified structure are int GetFirstInterface int GetnextInterface int last Functions to read InterfaceBlock parameters are IPADDR InterfaceIP int InterfaceNumber IPADDR InterfaceDNS int InterfaceNumber IPADDR
86. e the GDB stub function The section of code for the debugger with check for the definition DEBUG If defined the build is a Debug build as opposed to a Release build and the network debug stub will be initialized The wait in the function call name refers to the fact that the application will wait until the debugger connects then continue execution ifdef DEBUG Enable GDB stub if Debug build InitializeNetworkGDB and Wait fendif The inside of the while loop is where you would place your application code Modify main cpp to add the iprintf shown below while 1 iprintf Hello World r n integer version of printf OSTimeDly 20 Page 17 NetBurner Programmers Guide The iprintf and OSTimeDly 20 are just there for the example you would replace those lines with whatever you want your application to do Note that you should never return from this while loop if you did then your application would lose control of the hardware There are 20 ticks per second by default The definition TICKS PER SECOND is defined as 20 and can be used in place of a numeric value For example a delay of 2 seconds is OSTimeDly TICKS PER SECOND 2 5 3 Template Program Setup Before running our program let s make sure your hardware is set up correctly To run the Template program you will need your hardware to be set up as shown below Connection using cross over Ethernet cable red
87. earch Again Mac Address 00 1 0 8B F1 F4 6B Launch Webpage Advanced Close 3 If you wish to assign a static IP address enter the information into the NDK Settings pane as shown below and click on the Set button There will be a short pause while parameters are updated If you do not see your device in the Select a Unit window click on the Search Again button If your running application supports a web interface the Launch Webpage button when clicked will open up your default web browser to display your NetBurner board s home page mm NetBurner IPSetup NDK Settings m Select a Unit IP fo 1 1 3 MAC 00 10 8B F1 FA BB P 10 1 1 30 CP2 40 Network Mask 255 255 255 0 Gateway 10 d 4 1 DNS 0 0 0 0 Baudrate E 15200 Search Again Mac Address oo D 8B F1 FA 5B Launch Webpage Advanced Close 1 5 4 Debug Port Throughout this guide we will refer to the debug port The debug port is one of the RS 232 ports that can be used to interact with your NetBurner device in the example programs By default stdout stdin and stderr are mapped to the debug port so when you use functions like printf scanf gets etc they read and write to the debug port All of this is configurable You can also disable the debug port and use the port as a general purpose UART or you can reassign the stdio file descriptors to use other serial or network in
88. ed to C Line 14 declares the UserMain function The parameter passed to UserMain is a void pointer to some type of data This is a feature of the uC OS RTOS Note This example does not use the passed parameter Line 16 initializes the TCP IP stack Line 17 enables the code development AutoUpdate feature using make load Line 18 sets the task priority to the defined value of MAIN PRIO which defaults to 50 More information on the RTOS will be covered in the RTOS section of your NNDK User Manual From Windows Start gt Programs Netburner NNDK NNDK Users Manual Page 136 NetBurner Programmers Guide Lines 20 24 create an infinite loop that prints the message Hello World to stdout which defaults to the debug port of your NetBurner device once per second Line 21 is a while loop that loops forever Note Your application should never return from UserMain that would mean your application has lost control of the system 21 2 Compiling and Running the Application Overview Now that we have the application source code file we need to compile it into a code image and download it to your NetBurner device There are four methods to download your applications Through the serial port Through a network connection using AutoUpdate preferred method Through a network connection using TFTP Through a network connection using FTP TE In this example we will use the AutoUpdate method In order to run your appli
89. elivers code to a client these tags are processed in real time so that the dynamic content is transmitted in place of the tag The tags are as follows FUNCTIONCALL Calls a C function in your application VARIABLE lt var gt Displays the specified variable VARIABLE lt func param gt Calls a C function with parameters 10 1 The FUNCTIONCALL Tag The HTML FUNCTIONCALL tag will cause the web server to call the C function associated with the tag The C function is passed the socket file descriptor and URL and can use these parameters to do whatever the application needs to do such as displaying real time data text and graphics The previous section covered the FUNCTIONCALL tag It is mentioned in this section because of its similarity with dynamic content If you need specify a function call with parameters please refer to the following section on using the VARIABLE tag to create a function call with parameters 10 2 The VARIABLE Tag Variables in an application can be displayed on a web page using the VARIABLE tag This can be useful for displaying the dynamic information used in the application such as time IP address temperature etc The format of the tag is lt VARIABLE name Where name is the name of the application variable or an expression For example the system time tick variable TimeTick can be displayed with lt VARIABLE TimeTick gt Or you can display the time in sec
90. end A Queue is basically an array of mailboxes It is used to post one or OSQPost more messages When you initialize a Queue you must specify the maximum number of messages The first message posted to the queue will be the first message extracted from the queue FIFO OSFifoPend A FIFO is similar to a queue but is specifically designed to pass OSFifoPost pointers to OS FIFO structures The first parameter of the structure OSFifoPostFirst must be a void element which is used by the operating system to OSFifoPendNoWait create a linked list of FIFOs When initializing a FIFO you do not specify the maximum number of entries as with a queue Instead your application has the ability and responsibility to allocate memory static or dynamic in which to store the structures This can be done statically by declaring global variables or dynamically by allocating memory from the heap As with a queue the first message posted to the FIFO will be the first message extracted from the queue OSCritEnter This is a counted critical section that restricts access to resources to OSCritExit one task at a time sometimes called a mutex For example you OSCritObj have a linked list that is maintained by 3 separate tasks If one task is manipulating the list you could first call OSCirtEnter for that object the list If any other task tries to manipulate the list it will block at the OSCritEnter until the task that pre
91. er to the function as a pointer In this case we are passing the client socket sClient as pointer It is later cast back to a socket in line 91 e amp dwThreadld A pointer to a variable that will hold the thread ID once it is created When CreateThread is called successfully the thread will start and the client connection will be processed When the client connection is terminated the thread will return and be deleted The program will then return to the top of the while loop and block at the accept call 12 3 2 Running the Windows TCP Server Application The application was built as a Win32 console application To run it open a command prompt and type tcpsrvWin lt port gt where port is the listening port number e g 2000 The port number is a 16 bit value and numbers less than 1024 are reserved Page 68 NetBurner Programmers Guide 12 4 Writing a NetBurner TCP Client While a TCP Server waits for incoming connections a TCP Client handles the opposite end it initiates a connection In order to initiate a connection the TCP Client must know the destination IP address and port number of the server to which is wishes to make a connection Writing a TCP Client application on the NetBurner platform only requires one function call to connect int connect IPADDR dest ipaddr WORD localport WORD destport DWORD timeout where e dest ipaddr is the destination IP address the TCP server in this example e
92. es to stdout the debug serial port In this chapter we will use the web server to display some very simple static content The NetBurner Web Server excels at providing dynamic content as well which will be discussed in the next chapter A web server is a specialized case of a generic TCP server that listens on the well known port number 80 The web server operates as a task that waits for incoming TCP connections on port 80 then delivers the requested content to the client which is usually a web browser To initiate the transfer the web browser sends a GET request If no file name is specified in the GET request a default file named index htm or index html is returned The NetBurner Web Server assumes a default of index htm you can change this to html if you desire Once the web server sends the requested data it terminates the TCP connection To enable the web server and serve up pages to a web browser an application needs the following 1 Add the startHTTP function call to start the Web Server 2 A directory named html in the project directory 3 Create a web page called index htm All of the above steps are done automatically by the AppWizard if you select the appropriate checkbox items Since we did this with the initial template program all we need to do now is edit the HTML content in the index htm file Page 31 NetBurner Programmers Guide 8 2 Edit the index htm Web Page Next we will edit the index htm fil
93. essage would bog down the network leaving little room for other traffic A second example of when UDP is a better choice is when an application handles its own reliability at the application layer Using TCP in this instance would be redundant The NetBurner UDP Class implementation also has a speed advantage over TCP Data stored in a UDP packet is dispatched by providing the stack functions with a pointer to the data it does not copy the data to separate buffer locations This factor alone should provide a 30 speed increase over TCP which must be buffered In addition TCP is a stream based protocol and UDP is a datagram based protocol Let s take an example of an application in which a NetBurner device takes A D readings and sends them to another network device or host PC Using UDP each output operation i e creating and sending a UDP packet results in exactly one IP packet being created and sent The result of taking and sending 10 A D readings is that the host will receive 10 individual packets each containing one reading The host PC can then easily identify each reading although each reading will have to be sent with a sequence number so that the reading order can be recreated If TCP is used with a single continuous network connection i e the connection is not closed and reestablished for each reading you do not have control over how many readings are send with each IP packet You would need to add start message and stop message iden
94. f include predef h include stdio h include ctype h include startnet h include autoupdate h include dhcpclient h include tcp h include taskmon h include multihome h include netinterface h Page 125 NetBurner Programmers Guide Check for Multihome options and display compiler warnings if not enabled ifndef MULTIHOME error This example requires that MULTIHOME be uncommented error in the header file nburn include predef h and that the error system files be rebuilt fendif App name for IPSetup const char AppName Multihome Example extern C void UserMain void pd void WebDisplayIpSettings int sock PCSTR url Global variables InterfaceBlock DhcpIb StaticIb External function void ShowIPOnFd int fd IPADDR ia void WebDisplayIpSettings int sock PCSTR url Show header message indicating source and destination writestring sock Received request from ShowlIPOnFd sock GetSocketRemoteAddr sock writestring sock on IP address ShowlPOnFd sock GetSocketLocalAddr sock writestring sock r n lt br gt lt br gt Show both IP address for multihome writestring sock Valid IP Address for this device lt br gt r n ShowlPOnFd sock DhcpIb netIP writestring sock lt br gt r n ShowlPOnFd sock StaticIb gt netIP writestring sock lt br gt r n
95. f DHCP assigned the IP address of ShowIP EthernetIP iprintf Xrin Jy else Page 110 NetBurner Programmers Guide iprintf Static IP address set to ShowIP EthernetIP iprintr YeXn OSChangePrio MAIN PRIO EnableAutoUpdate Implement critical section with OSCritEnter amp OSCritLeave OS CRIT cs The critical section identifer OSCritInit amp cs The second parameter is a timeout value the number of time ticks to wait for cs to be available if another task currently ownes it A value of 0 waits forever OSCritEnter amp cs 0 GlobalVariable 1 You need to call OSCritLeave for each call to OSCritEnter While easy to see in this case in larger applications it becomes easier to get out of sync wy OSCritLeave amp cs iprintf GlobalVariable d r n GlobalVariable OS CRIT cs2 The critical section identifer OSCritInit amp cs2 opening scope operator Now create an OSCriticalSectionObj object When the object gets created the constructor will be called which will call OSCritEnter This call always sets the timeout to wait forever R4 OSCriticalSectionObj UserMainCriticalSection cs2 GlobalVariable 2 Note that the OSCritLeave call is not required so you can never get out of sync with OSCritEnter destructor gets call when object goes out of scope which c
96. feature of the FIFO Jk A A A A A A AE kCkck kc k kc k kc A kc k kc k kc k kc k kc ke A ck k ck k ck k ck ck ee ee a eo ea include predef h include lt stdio h gt include lt ctype h gt include lt startnet h gt include lt autoupdate h gt include lt ucos h gt include lt serial h gt include lt dhcpclient h gt include lt netinterface h gt define NUM POSTS 5 Zf function prototypes extern C void UserMain void pd gt structs typedef struct Pointers to this structure will be passed in the FIFO void pUsedByFifo Don t modify this value and keep it first int x Any other members come after the pointer BOOL free free TRUE if structure is fr to be used MyStructure f9 9m global vars DWORD FifoPostTaskStack USER TASK STK SIZE OS FIFO MyFIFO MyStructure StructArray 5 void InitFifoMembers for int i 0 i lt NUM POSTS i Page 107 NetBurner Programmers Guide StructArray i x 0 StructArray i free TRUE Find free FIFO structure Rather than use dynamic memory allocation this example uses a declared array of structures with a structure element that indicates if a particular structure is being used This function will return the index of the first free structure array member or 1 if all members are being used L
97. fference is that a Queue has a predefined number of entries The FIFO implementation uses a linked list so the only limit to the number of entries is available memory Using a FIFO is not as simple as any of the other mechanisms because your application must implement some type of memory management to allocate and deallocate the FIFO objects This is usually done by managing a predeclared array of objects or through dynamic memory allocation We encourage all embedded designers to avoid dynamic memory allocation if at all possible since in any embedded system memory fragmentation could eventually occur and the call to allocate a new object could fail If you create an array of objects at compile time you will always be guaranteed the maximum number can exist Page 101 NetBurner Programmers Guide 15 1 2 Semaphore Example A semaphore is a protected variable that is used to control access to shared system resources such as memory or serial ports to signal the occurrence of events and task synchronization A task can request a semaphore and wait until the resource or event takes place called pending A task can also post to a semaphore to indicate it no longer needs a resource or to signal an event has taken place To create a semaphore you declare one of type OS_SEM and initialize with OSSemlnit OS SEM MySemaphore OSSemInit amp MySemaphore 0 set initial value to 0 Your application tasks can now use the post and pend func
98. functions are shown below Name Interrupt Description Level Serial ports 3 Interrupts when a character is received or transmitted UARTS Note The NetBurner monitor operates in polled mode To enable interrupts your application must close the serial ports with SerialClose then open them with OpenSerial Ethernet 4 Ethernet receive and transmit System Timer 5 This is the RTOS system timer By default it generates an interrupt 20 times per second If necessary this rate can be changed in nburn include constants h with define TICKS PER SECOND This value should stay within the range of 10 to 200 For high resolution timing we recommend using a different timer Page 99 NetBurner Programmers Guide 15 Protecting Shared Data Structures 15 1 1 Overview The following RTOS mechanisms can be used to protect shared data resources They are listed in a decreasing order of severity as regarding system latency all pend and post functions are at the same level OSSemPend Protects an area of memory or resource A task calls OSSemPend OSSemPost which will block until the resource is available OSSemPost releases the resource OSMboxPend Same as semaphore except a pointer variable is passed as the OSMboxPost message A task or ISR can post a message but only a task can pend on a message Both the posting task and pending task must agree on what the pointer points to OSQP
99. hcpclient h gt include lt networkdebug h gt const char AppName UDP Sockets Example extern C void UserMain void pd Declare a task stack for the UDP Reader task DWORD UdpReaderStack USER TASK STK SIZE void UdpReaderTask void pd int port int pd iprintf UdpReaderTask monitoring port d r n port Create a UDP socket for receiving int UdpFd CreateRxUdpSocket port if UdpFd lt 0 Page 83 NetBurner Programmers Guide iprintf Error Creating UDP Listen Socket d r n UdpFd while 1 OSTimeDly TICKS PER SECOND else iprintf Listening for UDP packets on port d r n port while 1 IPADDR SrcIpAddr UDP packet source IP address WORD LocalPort Port number UDP packet was sent to WORD SrcPort UDP packet source port number char buffer 80 int len recvfrom UdpFd BYTE buffer 80 amp SrcIpAddr amp LocalPort amp SrcPort buffer len 0 iprintf r nReceived a UDP packet with d bytes from len ShowIP SrcIpAddr iprintf r n Ss r n buffer UserMain Task This is the first task to be executed and will create the UDP Reader Task Pw A M void UserMain void pd int portnum IPADDR ipaddr char buffer 80 InitializeStack EnableAutoUpdate EnableTaskMonitor if EthernetIP 0 iprintf
100. he web server then parses the data and takes appropriate action If you have ever purchased anything on the web filled out the order information and clicked on a button like confirm order or buy you most likely submitted form information and were then redirected to a page confirming the order A form is defined in HTML by the lt FORM gt lt FORMS tags User input is accomplished using the INPUTS tag representing text fields checkboxes radio buttons etc For example lt FORM ACTION name htm METHOD POST gt lt INPUT TYPE radio VALUE UTC NAME RadioGroupl CHECKED 1 gt UTC Time lt INPUT TYPE radio VALUE Local NAME RadioGroupl Local Offset lt INPUT NAME tfHours VALUE 9 TYPE text SIZE 20 Hours lt INPUT TYPE submit VALUE Submit lt FORM gt The above HTML source code shows the first few form items of the example explained in this chapter The above form has two mutually exclusive radio buttons one text field and the form submit button The web browser will Page 34 NetBurner Programmers Guide identify the input types and create the respective graphics on the web page Note The items in bold text will be created dynamically by the application source code in our example program The user will select a radio button enter text in the text field and finally click on the submit button The user form values will then be sent to the web server as a POST 9 3 Collect
101. hed the accept function returns and the sign on message is sent to the Telnet application We now enter the do loop while n 0 The read function will block until data is received or an error occurs such as the client terminating the connection When data is sent from the Telnet application the read function will return with the data in the RXBuffer array The application will stay in this while loop until the connection is terminated by the Telnet client or you reset the NetBurner device If the connection is broken by the Telnet client the application will then loop back to the accept function call and wait for another incoming connection Once application initialization is compete and we are running inside the while loop the application will block on the accept function call The IPtoString function is used to convert a numerical IP address of type IPADDR to an ASCII string so it can be sent to the client as a sign on message Page 53 NetBurner Programmers Guide 12 2 2 Running the NetBurner TCP Server Application 1 If you have not already done so Connect a serial cable from your host computer s serial port to your NetBurner board s debug serial port 2 Start MTTTY and connect 3 Compile and download your application to your NetBurner board 4 Verify that you can see the debug messages for the TCP Server Note the IP address EA Multi threaded TTY DAR Port Baud Parity Data Bits Stop Bits IEA IE
102. iece of data and parse the data stream UDP is connectionless the devices do not establish a connection or establish a data stream Data is sent as individual datagrams The NetBurner API provides for two mechanisms to implement UDP sockets and a C class The choice of which to use is depenant of which method you find most comfortable using There is not a performance difference 13 1 UDP Client Server Application Using the UDP Class The NetBurner UDP API is a C Class To create a UDP Server on the NetBurner platform we need to 1 Create an OS_FIFO to hold incoming packets Register the UDP FIFO with RegisterUDPFifo port amp fifo so it listens to a specific port number This is where incoming UDP packets will be stored If you are listening on multiple UDP ports you can use one FIFO to store them all by calling Register UDPFifo for each port number You can also have multiple OS FIFOs for each port if you wish 3 Calla UDP constructor such as UDPPacket upkt amp fifo timeout which will block until a packet is received then accept and store the packet To send a UDP datagram on the NetBurner platform we need to 1 Declare an instance of a UDP packet Specify the source and destination port numbers and add data to the packet using the class member functions 3 Sendto a specified IP address using the Send member function Looking at the above description and the flow chart below you will notice an important difference fro
103. ile Descriptors 16 1 Overview The NetBurner development package integrates the uC OS operating system TCP IP stack and other system peripherals with a file I O system and file descriptors A file descriptor is a handle to a network socket serial port or other system peripheral May of the API functions pass a file descriptor to your application functions such as the web server MyGet function example in this guide There are a maximum of 64 file descriptors e 0 2 for stdin stdout and stderr e 3 4 for the first two UART serial ports 0 and 1 e 5 36 for TCP 32 in total e 37 63 for expansion additional UARTs TCP sockets or custom The expansion file descriptor positions can be used for many things including additional serial ports such as an external UART or TCP ports 16 2 Creating Custom I O Drivers Using File Descriptors The header file in nburn include iointernal h defines the programming interface functions to create a custom file descriptor The header file content for tools release 1 98 is shown below but be sure to check the header file for your particular tools installation for the latest function definitions void SetDataAvail int fd void ClrDataAvail int fd void SetWriteAvail int fd void ClrWriteAvail int fd void SetHaveError int fd void ClrHaveError int fd struct IoExpandStruct int read int fd char buf int nbytes int write int fd const char buf in
104. ill set a OSFlag after a time delay of some number of seconds UserMain will then pend and block until ANY of the 3 flags are set You can also modify the example to pend until ALL of the 3 flags are set NB Library Definitions include predef h C Standard Library include lt ctype h gt include lt stdio h gt include lt string h gt Portability amp uCos Definitions include lt basictypes h gt include lt ucos h gt include lt ucosmcfc h gt include lt utils h gt NB Runtime Libraries include lt constants h gt include lt system h gt include lt iosys h gt include lt http h gt NB Network Stack include nettypes h include lt ip h gt include lt tcp h gt Features include lt autoupdate h gt include lt dhcpclient h gt include lt smarttrap h gt include lt taskmon h gt Page 112 NetBurner Programmers Guide ifdef DEBUG include lt NetworkDebug h gt endif OSFlag gOsFlag assigned bits a define TASK FLAG 1 DWORD 0x00000001 define TASK FLAG 2 DWORD 0x00000002 define TASK FLAG 3 DWORD 0x00000004 extern C void UserMain void notUsed const char AppName OSFlags Example Declare OSFlag f OS FLAGS gOsFlag void OsFlagTaskl void notUsed while TRUE OSTimeDly 2 TICKS_PER_SECOND OSFlagSet amp gOsFlag TASK FLAG 1 v
105. in void pd InitializeStack if EthernetIP GetDHCPAddress OSChangePrio MAIN PRIO EnableAutoUpdate EnableSmartTraps EnableTaskMonitor Create the circular buffer objects In this example we will create 2 static struct CircularBufferObject cbl cb2 Open the buffers int fdcbl OpenCircularBuffer amp cbl int fdcb2 OpenCircularBuffer amp cb2 iprintf Application started r n while 1 Write to the circular buffers writestring fdcbl Testing circular buffer 41 writestring fdcb2 Testing circular buffer 42 OSTimeDly TICKS PER SECOND Delay so loop runs slow Read the data out of buffer 1 while dataavail fdcbl char buf 2 int rv read fdcbl buf 1 if rv Page 120 NetBurner Programmers Guide iprintf c buf 0 iprintf r n Read the data out of buffer 2 while dataavail fdcb2 char buf 2 int rv read fdcb2 buf 1 if rv iprintf c buf 0 Fprinttq xeNEM Page 121 NetBurner Programmers Guide 17 Multiple Network Interfaces The NetBurner network devices can have multiple interfaces both in software as multi home and in hardware such as a WiFi or second Ethernet port Multi home means that you can enable your NetBurner device to have more than one IP address For example you could be 10 1 1 1 and 192 168
106. ing User Input Web Forms vs URL s There are two common methods for moving data from the client web browser to the web server on an embedded platform HTML Forms using POST and storing the data in the URL The previous section described form operation You have probably seen the URL method many times in e commerce applications For example the URL hittp Avww store com orderform type order1 23 is storing the data type order123 in the URL Basically everything following the character is ignored by the browser so your application can store whatever data it needs after the character A big advantage of this method is that the application is stateful meaning multiple users can access the same application and each user s session maintains its specific data in the URL 9 4 Application Objectives We will create a web page interface using forms that can Modify and recall text fields checkboxes and radio buttons Store and recall settings in flash memory using the Get Set API function calls Use the Submit web page feature to modify settings Parse web form data submissions Use the FUNCTIONCALL HTML tag to link HTML I O to C C code 9 5 Application Files Our application is divided up into the following files File Name Description main cpp This is the same as in the basic web example with one modification the IP Address only prints to the debug port one time iadweb cpp Source code module for the intera
107. iprintf Main Menu r n iprintf A Show ARP Cache r n Page 122 C Show Counters r n I Show WiFi ID r n P IP Address Ping r n Display Menu r n iprintf W Show WiFi networks availible r n pings the address given in buffer void ProcessPing char buffer IPADDR addr to ping char cp buffer Trim leading white space while cp amp amp isspace cp cptt Get the address or use the default if cp 0 addr to ping AsciiToIp cp else addr to ping EthernetIpGate iprintf nPinging ShowIP addr to ping iprinbtf Xn ys int rv PingViaInterface addr to ping 1 Id nwifi if if rv 1 iprintf Failed Mn else iprintf Response Took d ticks n rv Handle commands with a trivially simple command dispatcher void ProcessCommand char buffer switch toupper buffer 0 case A ShowArp break case C ShowCounters break case I char SSID Test 40 if GetCurrentSSID SSID Test 40 gt 0 Page 123 NetBurner Programmers Guide 1 Seq 100 Max Ticks NetBurner Programmers Guide iprintf Current SSID s r n SSID Test else iprintf Failed to read SSID r n if WiFiConnected iprintf Currently connected r n else iprintf Not c
108. iprintf Enter String If user input was exit if strcmp const char pmsg bExitUserInputTask TRUE exit else Vee nen NetBurner Programmers Guide We can use the Wait or No Wait version of OSMboxPend can on the Wait ye amp err amp err const char pmsg then send exit signal to UserInputTask 0 Count on 8 LEDs on dev board while wainting for input putleds OSTimeDly itt l1 Page 106 NetBurner Programmers Guide 15 1 4 FIFO Example A FIFO is similar to a queue but is specifically designed to pass pointers to OS_FIFO structures The first parameter of the structure must be a void element which is used by the operating system to create a linked list of FIFOs When initializing a FIFO you do not specify the maximum number of entries as with a queue Instead your application has the ability and responsibility to allocate memory static or dynamic in which to store the structures This can be done statically by declaring global variables or dynamically by allocating memory from the heap As with a queue the first message posted to the FIFO will be the first message extracted from the queue J KCKCK Ck KK KR A A kA A kck kc k A A A I I FIFO Example Program This program creates two tasks and a FIFO Messages are sent from one task to another using the FIFO A timeout value for the pend function is used to illustrate the timeout
109. isten task OSTaskCreate UdpReaderMain void portnum amp UdpTestStk USER TASK STK SIZE UdpTestStk MAIN PRIO 1 higher priority than send task Main while loop will take any user input and send it as a UDP datagram while 1 gets buffer iprintf Sent Ss to buffer ShowIP ipaddr Page 81 iprintf Sd r n portnum UDPPacket pkt pkt pkt AddData buffer AddDataByte 0 pkt pkt pkt SetSourcePort portnum SetDestinationPort portnum Send ipaddr iprintf r n 13 1 2 Running the Application Qu quo e NetBurner Programmers Guide If you have not already done so Connect a serial cable from your host computer s serial port to your NetBurner board s debug serial port Start MTTTY from Windows Start Programs Netburner NNDK gt Mttty Serial Terminal Compile and download the application to your NetBurner board Verify that you see the debug messages for the UDP Client Server Note the IP address Answer the prompts asking for the listening port number and destination IP address and port number of the host PC you will communicate with Run the NetBurner UDP Terminal Tool available in the NetBurner NNDK program group in the windows start menu Enter the values for the IP address local and remote ports ports will be the same Alternatively you can run the windows UDP application described in the section If everything is working prope
110. lable In must this case the NetBurner Debug Monitor comes to the rescue Once in the Debug Monitor at the rene NB prompt you can download a working application through the serial debug port See the SA section on serial downloads using the Debug Monitor for more information FEE project directory can be located anywhere on your hard drive For this example 1 Create a directory with a path of c netburner 2 Create a subdirectory with the path of c netburner template Now lets look at the template program First you will need to create a file using your editor of choice called main cpp in the c netburner template directory Simply copy and paste the code below in section 5 1 and save this file as main cpp in the c netburner template directory Using C File Extensions Throughout this manual we will always use the cpp extension to indicate the source files are C This is done to take advantage of the benefits of the C compiler as well as support those programmers using C Note You do not need to know any C to use the NetBurner Development Kit and the majority of examples in this guide do not use C Page 135 NetBurner Programmers Guide 21 1 Template Program Source Code Description The Template Program Filename main cpp include predef h include lt stdio h gt include lt startnet h gt include lt autoupdate h gt extern C void UserMain void pd void UserMain void
111. little endian for a typical pc running Windows to standard network byte order big endian The INADDR_ANY parameter specifies that any incoming IP address will be accepted the AF_INET specifies the Internet Protocol family and the dListenPort parameter contains the value of the port the server will listen to Line 164 The bind function associates the listen socket with the listen port number Line 171 The listen function puts the socket into listen mode so it will accept incoming connections The second parameter 5 is the number of connections that can be queued to handle simultaneous incoming connection requests Line 181 The accept call accepts an incoming connection Any pending connections will be serviced first The second parameter is a pointer to an address structure that will contain the connection information such as IP address and port number In this case we pass a pointer to sinClient The third parameter is a pointer to a variable that will contain the length of the address structure The accept function returns a socket descriptor that corresponds to the new client connection which can then be used for communication with the client Line 208 This example creates a thread to handle an incoming client connection The CreateThread API call takes the following parameters e ProcessClient A pointer to the thread function to execute e LPVOID sClient When creating a thread it is possible to pass a paramet
112. m TCP communication since there is not a connection between the client and sever you cannot simply send and receive data using read and write functions You will need to create a UDP packet for each transmission specifying the port numbers and destination IP address Page 78 NetBurner Programmers Guide Server Client Create OS_FIFO initialize with RegisterUDPFifo Send data by creating instance of UDP class initializing and using Send member functions to transmit Call UDP constructor which will block until a packet is received Process incoming data with Validate and GetDataBuffer member functions 13 1 1 NetBurner UDP Class Application Source Code S EKK KK kk k k kk kk kk kk Ck k k Ck Ck kk k k kc k Ck ck kc k kk Ck ck k k Ck ck k k k k k k kc k k k kc k k k k ck k k k ck kCk k ck k k k ck k ck k ck ck ck ck k k k NetBurner simple UDP send receiv xampl This example program will allow you to send and receive UDP packets to another device or host computer To run th xample connect a serial port to the debug serial port on your NetBurner device and run a dumb terminal program such as MTTTY On the PC run the NetBurner UDP Terminal be sure to set the IP address and port numbers to match You will then be able to type characters in the UDP Termainal and see them in MTTTY and vice versa You will be prompted for the port number to send receive data and the destination IP address of the other de
113. mmented system tasks will be stored in SRAM otherwise SDRAM will be used define FAST IDLE STACK define FAST MAIN STACK define FAST ETHERNET VARIABLES define FAST ETHERNET STACK define FAST BUFFERS VARIABLES define FAST BUFFERS define FAST IP VARIABLES define FAST IP STACK define FAST TCP VARIABLES define FAST TCP STACK define FAST HTTP STACK define FAST FTP STACK define FAST WIFI STACK define FAST PPP STACK define FAST COMMAND STACK If these defines ar nabled any user variables or tasks declared with FAST USR STK or FAST USR VAR will be stored in SRAM KY define FAST USER VARIABLES define FAST USER STACK fendif Page 129 NetBurner Programmers Guide 18 3 Using SRAM in Tools Release Prior to 2 1 RC6 Declare a structure that contains the variables you want to locate in SRAM and a pointer to the SRAM base address plus 0x400 The default SRAM base address for NetBurner platforms is 0x20000400 This can be verified by checking the memory map in the platform documents for your NetBurner platform located in nburn docs platform An example program for this method is shown below include predef h include lt stdio h gt include lt ctype h gt include lt startnet h gt include lt autoupdate h gt include lt dhcpclient h gt include lt string h gt extern C void UserMain void pd
114. mplate header description as shown below Comments have been added to the source code to explain the function of important functions Description The Template Program Filename main cpp E include predef h include lt stdio h gt include lt ctype h gt include lt startnet h gt include lt autoupdate h gt include lt dhcpclient h gt include lt smarttrap h gt include lt taskmon h gt include lt NetworkDebug h gt extern C void UserMain void pd const char AppName Template Program Name for IPSetup void UserMain void pd InitializeStack Initialize TCP Stack if EthernetIP 0 Enable DHCP if no static IP GetDHCPAddress OSChangePrio MAIN PRIO Set UserMain task priority EnableAutoUpdate Enable network updates StartHTTP Start Web Server EnableSmartTraps Enable Smart Traps EnableTaskMonitor Enable Task Scan ifdef DEBUG Enable GDB stub if Debug build InitializeNetworkGDB and Wait endif iprintf Application started n while 1 OSTimeDly 20 The above program is a fully functional network application in just a few lines of code The only application specific code is inside the while 1 loop the remainder of the program is what we will refer to as the Template Program Although the purpose of our application is to print Hello World out the debug serial port adding the network s
115. n MyStartDHCP ib OSChangePrio MAIN PRIO EnableAutoUpdate StartHTTP DisplayUserMenu while 1 char c getchar switch c case 1 Display runtime IP values DisplayRuntimeIPSettings FirstInterface break case 2 Display Flash IP values This example uses only 1 Configuration Record 0 DisplayFlashIPSettings 0 break case 3 Change the runtime IP address and mask After this function the device will respond to the new IP settings ChangeRuntimeIPSettings FirstInterface Interface Block AsciiToIp 10 1 1 24 New IP address AsciiToIp 255 255 255 0 New IP mask AsciiToIp 10 1 1 1 New IP gateway AsciiToIp 10 1 1 2 New IP dns break case 4 Change the Flash IP address and mask If the device reboots the new values will be in effect ChangeFlashIPSettings 0 Use first Config Record 0 AsciiToIp 10 1 1 24 New IP address AsciiToIp 255 255 255 0 New IP mask AsciiToIp 10 1 1 1 New IP gateway AsciiToIp 10 1 1 2 New IP dns break case 5 Set all flash values to 0 0 0 0 ChangeFlashIPSettings 0 Use first Config Record 0 AsciiToIp 0 0 0 0 New IP address AsciiToIp 0 0 0 0 New IP mask AsciiToIp 0 0 0 0 New IP gateway AsciiToIp 0 0 0 0 New IP dns ChangeRuntimeIPSettings FirstInterface Interface Block AsciiToIp 0 0 0 0 New IP address AsciiToIp 0 0 0 0
116. n a packet has been received The second parameter is a timeout value timeticks A value of O0 will wait forever The TICKS PER SECOND definition can be used for code readability UDPPacket upkt amp fifo 0 TICKS PER SECOND Did we get a valid packet or just time out if upkt Validate WORD len upkt GetDataSize iprintf Received UDP packet with d bytes from int len ShowIP upkt GetSourceAddress show ip address iprintf XrXn ShowData upkt GetDataBuffer len hex dump function iprintt rin Page 80 NetBurner Programmers Guide void UserMain void pd int portnum IPADDR ipaddr char buffer 80 InitializeStack if EthernetIP 0 iprintf Trying DHCP r n GetDHCPAddress iprintf DHCP assigned the IP address of ShowIP EthernetIP jiprrintf ewe J else iprintf Static IP address set to ShowIP EthernetIP iprrintf yen j EnableAutoUpdate OSChangePrio MAIN PRIO iprintf Starting NetBurner UDP Example r n iprintf Enter the UDP port number will be used for send amp receive iscanf Sd amp portnum iprintf r nEnter the destination IP Address buffer 0 0 while buffer 0 0 gets buffer ipaddr AsciiToIp buffer iprintf Listening Sending on UDP Port d Sending to IP address portnum ShowIP ipaddr iprintf XrXmu Create UDP l
117. nate a task include predef h include lt stdio h gt include lt ctype h gt include lt startnet h gt include lt autoupdate h gt include lt ucos h gt include lt serial h gt include lt string h gt include lt dhcpclient h gt 1 Oy ae oa function prototypes extern C void UserMain void pd ff global vars DWORD UserInputTaskStack USER TASK STK SIZE OS MBOX UserInputMbox BOOL bExitUserInputTask UserlInputTask Once created this task will loop unitl bExitUserInputTask FALSE The fgets will block until the user enters a string in mttty This task will have a higher priority than UserMain void UserInputTask void pdata static char strInput 1024 while bExitUserInputTask fgets strInput 80 stdin block until user enters a string int len strlen strInput iprintf Received d bytes r n len Remove any trailing r or n if len gt 2 for int i 0 i lt 2 i Page 104 NetBurner Programmers Guide if strInput len i r strInput len i n strInput len i 0 Post pointer to input string in mailbox OSMboxPost amp UserInputMbox void strInput Not much to do in this example once the task exits iprintf UserInputTask terminated Please reset program r n void UserMain void pd putleds 0 InitializeStack if EthernetIP
118. ng the RS 232 Debug Connection You can determine if you are properly connected to the debug port with the following test 1 Start the dumb terminal program MTTTY which is included in your NetBurner tools From Windows Start gt Programs gt NetBurner NNDK gt Mttty Serial Terminal From the command line type C Nburn pcbin mttty and then press the Enter key Set the baud rate to 115 200 and make sure to click on the Connect button in the MTTTY window 2 Power on or reset your NetBurner device The MTTTY screen should display a sign on message similar to Waiting to boot If you see this message then you are connected correctly For additional information please refer to your User Manual From Windows Start gt Programs gt NetBurner NNDK NNDK Users Manual Page 139 NetBurner Programmers Guide 22 Software Licensing The Software included in this development kit is licensed to run only on NetBurner provided hardware If your application involves manufacturing your own hardware please contact NetBurner Sales for details on a royalty free software license The following sections describe the agreements presented during installation of the development kit 22 1 NetBurner License Agreement Notice to Developer This is a contract By installing the NetBurner Tools you accept all the terms and conditions of the NetBurner Tools Software and NetBurner Embedded Software Agreements If you do not agree with
119. ntation the number of enter calls must match number of exit calls for each task OSCritObj is a C implementation that uses scoping to automatically call the enter and exit functions so you do not need to manually match each enter with an ext In comparison with OsLock OsCritEnter does not restrict task swapping unless two tasks want to access the same resource If you used OsLock then ALL task swapping would be prevented This example will show how to create critical sections with the standard C type function calls OSCritEnter and OSCritLeave and compare them to the the C object type which eliminates the problem of matching each OSCritEnter to a corresponsing OSCritLeave While this example is trivial with only a simple global variable critical sections need to be used for objects such as linked lists that could be changed by multiple tasks In such cases each task would use a critical section to ensure the modifications could be completed befor a task switch occurred include predef h include lt stdio h gt include lt startnet h gt include lt autoupdate h gt include lt dhcpclient h gt include lt ucos h gt extern C void UserMain void pd const char AppName OsCritObj Example int GlobalVariable 0 A global variable void UserMain void pd InitializeStack if EthernetIP iprintf Trying DHCP r n GetDHCPAddress iprint
120. nternet Explorer E m Eile Edit View Favorites Tools Help a A e im Qw O HAO As eres O 2 G aA Address amp http 10 1 1 193 INDEX HTM v Go Links Google G Goo EX YF Bookmarks QSettingsy Qe etBurner Networking in 1 Day TCP Client Example Program This example program will open a TCP connection to a TCP Server at the specified IP address and send a message A simple TCP Server TepServerWin exe is included in the nburn pctools directory Enter Message to send Destination Port 2000 Destination IP 10 1 1 121 Your IP address is 10 1 1 121 Send Message 12 4 1 NetBurner TCP Client Application Source Code The TCP Client example code is organized in the following code modules File Description main cpp Application initialization DHCP and check of flash memory stored parameters clientweb cpp Handles the dynamic content for the web server interface index htm HTML code for the web server interface Page 71 NetBurner Programmers Guide Main cpp Since all of the action occurs through the web server interface main cpp is very simple It initializes the system and does a check for DHCP This program demonstrates how to create a TCP Client All interaction is through the web page interface which allows a user to type in a message and send it to a TCP Server include predef h include lt stdio h gt inclu
121. nters a while 1 loop that waits for user input strings and sends those strings using the sendto function 13 3 2 Running the Windows UDP Application The application was built as a Win32 console application To run it open a command prompt and type UDPWin listen port dest IP dest port gt and then press the Enter Key where listen port is the local port number to listen for incoming datagrams dest IP gt and dest port are the IP address and port number of the host or device you wish to send datagrams to For example UDPWin 2500 10 1 1 15 2501 will listen on port 2500 and send any data you type into the console to the host or device at 10 1 1 15 2501 Page 91 WOWDADMABRWNK NetBurner Programmers Guide 13 4 Writing a Windows JAVA UDP Client Server Application This example is a UDP Client Server written in Java that can be run on any host computer running the Java Virtual Machine JVM This includes Windows Unix Linux etc Note The NetBurner platform does not run the JVM To create a UDP Server on the NetBurner platform 1 Create a DatagramSocket 2 Create a DatagramPacket 3 Use the receive member function to block for incoming packets and store the packet To send a UDP datagram on the NetBurner platform 1 Create a DatagramPacket 2 Use the send member function to send the packet 13 4 1 Windows Java UDP Application Source Code BRK KKK KR RK KK KH RK A A RRR A A A A AR A k K
122. nts h define MAIN PRIO 50 define HTTP PRIO 45 define PPP PRIO 44 define TCP PRIO 40 define IP PRIO 39 define ETHER SEND PRIO 38 Page 16 NetBurner Programmers Guide In addition task 0 and task 63 are reserved Tasks available for user applications are any of the remaining task priority numbers Some network modules such as FTP and Telnet Command will also use task priorities but the priority will be an option passed to the function that starts the task Always check the return value when creating a task If you call a function that creates a new task and you specify a task priority that is already in use the function will return an error An easy way to keep track of priority levels for user applications is to use the MAIN_PRIO definition and add or subtract a number from it For example if you create a new task and want it to be of higher priority than UserMain then use MAIN PRIO 1 If you want it to be of lower priority the add 1 etc The function EnableAutoUpdate willenable the network flash memory update capability of the device The Autoupdate utility is used both during development to quickly download code to flash memory and also as an update mechanism once the device is deployed The StartHTTP function starts the HTTP Web Server task When you build your project the web page data in your project s html directory will be processed and made available to be served u
123. o check for the second or third interfaces Typically the first interface will be your primary Ethernet interface To use the network interface functions you must include netinterface h Get first interface identifier Use GetNextInterface lt last interface gt to obtain additional interface numbers if necessary int FirstInterface GetFirstInterface InterfaceBlock ib GetInterFaceBlock FirstInterface Get interface data if ib gt netIP 0 Check IP address for 0 0 0 0 and use DHCP if necessary iprintf r nNo static IP address set attempting DHCP r n if GetDHCPAddress FirstInterface DHCP_OK iprintf DHCP address ShowIP ib netIP iprintf r n else iprintf Error could not obtain a DHCP address r n The code checks the interface block variable ib gt netIP to determine if the host IP address is O If the IP address is 0 then the DHCP Client should be invoked to obtain a dynamic IP parameters If EthernetIP is not 0 then the system assumes a static IP address has been assigned and DHCP is not used In previous tools releases that did not include multiple network interface support a global variable named EthernetIP was used to access the Ethernet IP address of the device While this variable will still work for backward compatibility it is recommended that the interface functions be used for all new applications An easy way to check your NetBurner board to dete
124. oMDO IS HOLT H 116 I6 I OVERVIEW 5 dottrina Rete OO ERE 116 16 2 CREATING CUSTOM I O DRIVERS USING FILE DESCRIPTORS ccssscccsessececeeseeceesececseseeecseseeeneseeeesenaees 116 16 3 USING FILE DESCRIPTORS TO PEND ON MULTIPLE EVENTS ccsessscecececeesessececececeesenssceeececeenenseaeeeeseeenes 117 16 4 EXAMPLE CIRCULAR BUFFER IMPLEMENTATION USING FILE DESCRIPTORS ccceesssseeececeesensaeeeeeceenes 117 17 MULTIPLE NETWORK INTERFACES sscccsssssccssssccccssssccsssscccesssccscssscccsssacccessnsccscsscescsssaccccssssecs 122 17 1 MULTIPLE HARDWARE INTERFACES ETHERNET WIFI PPP enne 122 LTDA WiPilnterface Examples eR Bae AS OT PRU RR 122 17 2 MULETI HOME 5n ertet e S vtr Da eo vere eMe Ui wea see URGE S E ok Saas UE Ure RA 125 17 2 1 Multi Home Example Program eee eese eene enne tnnt nennen eene etre enne nnne 125 18 USING THE COLDFIRE PROCESSOR ON CHIP SRAM eee eese ee ee ee eno e eee to oeste toss ette eese snae ee 128 Page 3 NetBurner Programmers Guide 182124 SINTRODUCTIONS E ERE E OEE Bie E 128 18 2 USING FAST SRAM IN TOOLS RELEASE 2 2 AND LATER ccccecesececececececececececececececececececececececececeeeeececesess 128 18 3 USING SRAM IN TOOLS RELEASE PRIOR TO 2 1 RC6 ssssssssseeeeeeenememem nennen eene enin enin ener ense 130 19 TIME FUNCTIONS c 131 19 1 STANDARD C T
125. oid OsFlagTask2 void notUsed while TRUE OSTimeDly 4 TICKS_PER_SECOND OSFlagSet amp gOsFlag TASK FLAG 2 void OsFlagTask3 void notUsed while TRUE OSTimeDly 6 TICKS_PER_SECOND OSFlagSet amp gOsFlag TASK FLAG 3 void UserMain void notUsed Page 113 NetBurner Programmers Guide DWORD gOsFlagState 0 InitializeStack if EthernetIP iprintf Attempting DHCP r n if GetDHCPAddress DHCP OK iprintf DHCP Failed r n else iprintf DHCP IP Address else iprintf Static IP Address ShowIP EthernetIP iprintf r n OSChangePrio MAIN PRIO EnableAutoUpdate EnableTaskMonitor Create and initialize flags OSFlagCreate amp gOsFlag Create example tasks With release 2 2 and later you can create tasks with names Otherwise create without names MAIN PRIO is the priority of UserMain so each of the tasks are of lower priority and UserMain must block to allow them to run OSSimpleTaskCreatewName OsFlagTaskl MAIN PRIO 1 OsFlagTaskl OSSimpleTaskCreatewName OsFlagTask2 MAIN PRIO 2 OsFlagTask2 OSSimpleTaskCreatewName OsFlagTask3 MAIN PRIO 3 OsFlagTask3 OSSimpleTaskCreate OsFlagTaskl MAIN PRIO 1 OSSimpleTaskCreate OsFlagTask2 MAIN PRIO 2 OSSimpleTaskCreate OsFlagTask3 MAIN PRIO 3
126. om support netburner com Support and Product Registration Web Site http support netburner com 24 NetBurner Support Information Each NetBurner Network Development kit includes 90 days of email support To access support resources and to register your product please go to http support netburner com or you can send an E Mail to support netburner com Note You must register your product before you can request support You will need to include the software release number on your NetBurner Tools CD the hardware Ethernet address and the hardware revision number of your NetBurner board The NetBurner web site is a good source for answers to frequently asked questions and design examples Annual support and software maintenance agreements can also be purchased on the NetBurner web site at http www netburner com Page 141
127. onds with the equation lt VARIABLE TimeTick TICKS PER SECOND gt Page 42 NetBurner Programmers Guide The VARIABLE tag is processed during the compilation of the application by parsing the text between lt VARIABLE and the trailing and converting it into a function call like WriteHtmlVariable fd TimeTick TICKS PER SECOND The variable types are handled with C but you do not need to know anything about C to use this feature The parameter types are defined by the function definitions located in c nburn include htmlfiles h void WriteHtml Variable int fd char c void WriteHtmlV ariable int fd int i void WriteHtmlV ariable int fd short i void WriteHtml Variable int fd long i void WriteHtmlVariable int fd BYTE b void WriteHtmlVariable int fd WORD w void WriteHtmlVariable int fd unsigned long dw void WriteHtmlVariable int fd const char void WriteHtmlVariable int fd MACADR ip In addition we have included a class named IPCAST that takes a 32 bit value and converts it into an IP address format e g 192 168 1 2 The example below will display the IP address in dotted notation rather than a 32 bit integer IP address VARIABLE IPCAST gConfigRec ip Addr gt 10 2 1 The INCLUDE Tag and htmlvar h Header File Now that we understand the resultant code is a function with the variable name it should be apparent that the resultant htmldata cpp file c
128. onsole application with MS Visual C 5 0 Include WS2_32 1lib in linker configuration REVISION HISTORY 2 3 2003 Initial Release KA KA A A KARA AA A k k k k k k k k k k k k k k k k k k kk k k k kk KK f include lt winsock h gt include lt stdio h gt include lt stdlib h gt define RX_BUFSIZE 10000 kirssa functions void ProcessCmdLine int argc char argv DWORD WINAPI ReceiveUDP LPVOID lpParam Blas ce global vars WORD dListenPort dDestPort char szDestIPAddr 80 char RxBuf RX BUFSIZE FUNCTION ProcessCmdLine DESCRIPTION Process command line arguments RETURNS Nothing void ProcessCmdLine int argc char argv if argc 4 printf Usage UDPWin listen port dest ip dest port gt n exit 1 dListenPort WORD atoi argv 1 strncpy szDestIPAddr argv 2 80 dDestPort WORD atoi argv 3 Page 87 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 NetBurner Programmers Guide flee eee FUNCTION ProcessClient DESCRIPTION This function is called as a thread to handle client connections PARAMETERS lpParam is a pointer to the client socket handle RETURNS 32 bit thread exit code DWORD WINAPI ReceiveUDP LPVOID lpParam SOCKET s SOCKET lpParam struct sockaddr_in sinFrom while 1 printf Listening on port d
129. ork buffers will use SRAM if at all possible If network buffering requirements increase beyond the size of the SRAM then the system will automatically begin using SDRAM for additional storage System use of SRAM is only enabled for release builds Debug builds will automatically disable system SRAM use You can specify that your application s variables and task stacks be located in SRAM by declaring them with with the FAST_USER_STK and FAST_USER_VAR macros If you exceed the amount of SRAM on your system a linker warning will be generated To declare a variable in SRAM BYTE MyByte FAST USER VAR MyByte will be located in SRAM To declare a task stack in SRAM DWORD MyTaskStacK MY TASK STACK SIZE attribute aligned 4 FAST USER STK Page 128 NetBurner Programmers Guide The use of SRAM by the system variables and stacks is defined in nburn include constans h By modifying the defnitions in constants h you can disable the system use of SRAM completely or control which system tasks are able to use the SRAM Any stacks or variables that do not use SRAM will be located in SDRAM If you make any changes to constants h you must rebuild the system library for the change to take effect ifndef DEBUG define ENABLE SRAM SYS SRAM use is only enabled in release builds endif ifdef ENABLE SRAM SYS define FAST SYST Gl VARIABLES locate critical system variables in SRAM Unco
130. ost data radioLeapAddSub r n else if strcmp buf Add 0 NV_Settings bLeapSecDayAdd TRUE else NV_Settings bLeapSecDayAdd FALSE Process DST radio buttons if ExtractPostData radioDST pData buf max chars 1 iprintf Error reading post data radioDSTNr An else if strcmp buf Enable 0 NV Settings bEnableDST TRUE else NV Settings bEnableDST FALSE Now to store it in flash WARNING If new settings are added remember to add them to NV Settings default initialization NV Settings VerifyKey VERIFY KEY if SaveUserParameters amp NV Settings sizeof NV Settings 0 Page 39 NetBurner Programmers Guide 236 iprintf New Settings Saved r n 237 else 238 iprintf ERROR Could not save new settings r n 239 240 241 We have to respond to the post with a new HTML page In 242 this case we will redirect so the browser will go to 243 that URL for the response 244 RedirectResponse sock index htm 245 246 return 0 247 248 249 250 251 Register Post 252 This function sets the HTTP POST handler to point to our 253 function 254 255 void RegisterPost 256 257 SetNewPostHandler MyDoPost 258 Line 16 VERIFY_KEY i
131. ou can view the HTML source in your web browser All the FUNCTIONCALL tags should be replaced with HTML data In this example application most of the functions fill in a piece of a HTML tag to show text field data or remember which radio button was selected in a group Your application does not need to explicitly call any of these functions As the web sever is delivering the web content to the web browser it will automatically call each function with a FUNCTIONCALL tag Line 171 The MyDoPost function will be called whenever a HTML form is submitted which occurs when a user selects the submit button in a HTML form The web server has a standard function to handle POSTS the function RegisterPost is used to intercept a POST and send it to MyDoPost The return value of MyDoPost is not currently used but currently should return a value of 0 to be compatible with possible future expansin Page 40 NetBurner Programmers Guide The parameters passed in MyDoPost are Parameter Type Description sock The file descriptor for the socket that this function should send a response to url A string containing the URL of the POST destination This field is used to determine which form the POST came from pData A pointer to a string containing the form data i e text fields radio button and check box selections etc rxbuffer A pointer to the entire HTTP request This is not normally needed Data is e
132. owIP EthernetIP iprintf XrXn OSChangePrio MAIN PRIO EnableAutoUpdate OSFifoInit amp MyFIFO InitFifoMembers if OSTaskCreate FifoPostTask NULL void amp FifoPostTaskStack USER TASK STK SIZE void FifoPostTaskStack MAIN PRIO 1 OS NO ERR iprintf Error creating FIFO task r n while 1 iprintf r n gt gt gt Calling OSFifoPend r n MyStructure pData MyStructure OSFifoPend amp MyFIFO TICKS PER SECOND 5 if pData NULL Because of the OSTimeDly in the post task we will timeout once per sequence on purpose iprintf Timeout in OSFifoPend waiting for next FIFO Post r n else iprzntf FIFO Read d pData gt x d r n FifoCnt pData gt x pData gt free TRUE Page 109 NetBurner Programmers Guide 15 1 5 OSCritObject Example OSCritEnter OSCritExit and an OSCritObj are enably an application to use counted critical sections that restrict access to resources to one task at a time also called a mutex For example you have a linked list that is maintained by 3 separate tasks If one task is manipulating the list you could first call OSCritEnter for that object the list If any other task tries to manipulate the list it will block at the OSCritEnter call in that task until the task that previously called OSCritEnter calls OSCritExit Since this is a counting critical section impleme
133. owed while pCbo get pointer pCbo put pointer amp amp number read lt nbytes buf pCbo gt data_buffer pCbo gt get_pointer number readt if pCbo get pointer pCbo put pointer We have read everything Now update the status so fd functions like select will work properly ClrDataAvail fd We had some data to read if number read gt 0 We have read something so there should now be space in the write buffer update status for select function SetWriteAvail fd Page 118 NetBurner Programmers Guide OSCritLeave amp pCbo gt critical section return number read pr Function to write to the circular buffer Euer MM ce MK eT RU m LOREM Lm ee int cbo write int fd const char buf int nbytes Get the cbo object associated with this fd CircularBufferObject pCbo CircularBufferObject GetExtraData fd int number written 0 Enter the critical section OSCritEnter amp pCbo critical section 0 if BYTE pCbo put pointer 1 pCbo get pointer We can write data while there is space and we have bytes to write while BYTE pCbo put pointer 1 pCbo get pointer amp amp number written nbytes pCbo gt data_buffer pCbo gt put_pointer buf number writtent if BYTE pCbo
134. p as a web page For example you will probably have a web page called index htm The StartHTTP function will start a task that listens on port 80 for incoming HTTP requests such as those from a web browser An optional parameter may be passed to the function to select a different port number For example StartHTTP 81 will start the Web Server and tell it to listen on port 81 StartHTTP may only be called once The EnableTaskMonitor enables TaskScan a network debugging tool that is used to view tasks and their status in a running application To use TaskScan you must add include lt taskmon h gt in your application s main cpp file and EnableTaskMonitor in user main When the TaskScan utility is run on your Windows computer you can view the running tasks their status and current source code line number There are no performance hits if you include TaskScan in your application the only time it will be invoked is when you run the TaskScan utility and connect to your NetBurner device TaskScan is covered later in this manual The NetBurner system will catch programming errors that cause traps such as null pointers and display debug information such as the program counter address registers and data registers The EnableSmartTraps function call provides more detailed debugging information when a trap occurs such as the RTOS task information Note that if you are using GDB Insight Debugging EnableSmartTraps must called befor
135. ple Events Once you have created a file descriptor you can use the select function call just as you would for network or serial file descriptors In fact you can pend on a mixture of them all at the same time 16 4 Example Circular Buffer Implementation Using File Descriptors The following example uses file descriptors to implement a circular buffer BRK RK KK kk Ck Ck Ck Ck Ck kCk Ck kCk kk kCk kk kk kk kk kc k kk kk kk kk k k kc k kc k ck k ck k KK KK The NetBurner sytem software has support for creating your own custom I O device as a file descriptor It is encapsulated in the nburn include iointernal h header file This is a trivial example of creating a circular buffer file descriptor It will create a 256 byte circular buffer that you can write to and read from The 256 byte size makes th circular buffer wrap around easy just use bytes and the rollover math is simple In any real world example of a new I O dvice the device would probably be interrupt driven For interrupts you should use USER ENTER CRITICAL and USER EXIT CRITICAL to protect the internal data structures The 6 fd status functions are interrupt safe void SetDataAvail int fd void ClrDataAvail int fd void SetWriteAvail int fd void ClrWriteAvail int fd void SetHaveError int fd void ClrHaveError int fd XKCKCKCKCKCKCKCKCkCKCkCKCkCKCKCKCkCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCkCkCkCkCkCkCKCkCkCkCKCk
136. printf s d d d d int ipb 0 int ipb 1 int ipb 2 int ipb 3 Sends a message to the specified host void SendMsg IPADDR DestIp int DestPort char msg iprintf Connecting to ShowIP DestIp iprintf dWMrMn DestPort iprintf Attempting to write s r n msg int fd connect DestIp 0 DestPort TICKS PER SECOND 5 if fd 0 iprintf Error Connection failed r n else int n write fd msg strlen msg iprintf Wrote d bytes r n n close fd void WebDestPort int sock PCSTR url char buf 80 If no dest port is specified use a default if gDestPort 0 gDestPort 2000 siprintf buf VALUE d gDestPort writestring sock buf void WebDestIp int sock PCSTR url char buf 80 char szDestIp 40 If no dest ip address has been entered use the one that Page 74 NetBurner Programmers Guide requested the web pag if gDestIp 0 IPtoString GetSocketRemoteAddr sock szDestIp else IPtoString gDestIp szDestIp siprintf buf VALUE s szDestIp writestring sock buf ag s e ea a Show destination ip address on web page ee a e R S void WebShowClientIp int sock PCSTR url char buf 80 TPtoString Get
137. pt to connect to a web page on the LAN will fail because the proxy server will attempt to route the request outside the LAN For most web browsers this can be accomplished in the advanced settings for the proxy server configuration If you are using IE 6 x click on Tools gt Internet Options gt Connections gt LAN Settings gt Proxy server For additional information please contact your IT Department Page 12 NetBurner Programmers Guide 5 Using the NBEclipse IDE to Create the Template Program The NBEclipse Application Wizard can quickly create a project and generate source code for a fully functional network enabled application This application can be used as a starting point and modified to suit your product requirements The tutorial on the NBEclipse Application Wizard is covered in detail in the NBEclipse Getting Started Guide and is not repeated in this document If you prefer command line tools you can do all of your development using the make utility Please see the section entitled Using the NetBurner Command Line Tools to Create the Template Program for details Traditionally called the Hello World program the Template Program will specify a minimal code base from which you can write your future applications The objective of this template program is to print the characters Hello World out the debug port of your NetBurner device In addition this template program will enable network services so that it c
138. pting the file descriptor fdnet is used to read write to it iprintf Wainting for connection on port d n ListenPort int fdnet accept fdListen amp client_addr amp port 0 iprintf Connected to ShowIP client addr iprintf dXn port writestring fdnet Welcome to the NetBurner TCP Server r n char s 20 IPtoString EthernetIP s siprintf RXBuffer You are connected to IP Address s port Sd r n s TCP LISTEN PORT writestring fdnet RXBuffer while fdnet gt 0 Loop while connection is valid The read function will return 0 or a negative number if the client closes the connection we test the return value in the loop Note you can also use ReadWithTimout in place of read to enable the connection to terminate after a period of inactivity p int n 0 do n read fdnet RXBuffer RX BUFSIZE 1 RXBuffer n 0 iprintf Read d bytes s n n RXBuffer while n gt 0 Don t foreget to close iprintf Closing client connection ShowIP client addr Lprantt Trdin port close fdnet fdnet 0 while 1 while listen void UserMain void pd InitializeStack Initialize the TCP IP Stack if EthernetIP iprintf Trying DHCP r n GetDHCPAddress iprintf DHCP assigned the IP address of ShowIP EthernetIP iprintf Mew J Page 52 NetBurner Programmers Guide
139. put pointer 1 pCbo get pointer Buffer is full so mark the fd as full ClrWriteAvail fd if number written We wrote something so we have data ready to be read SetDataAvail fd OSCritLeave amp pCbo gt critical section return number written int cbo close int fd Normally you would have to clean up your I O device before closing it Here we just close the fd FreeExtraFd fd return 0 Function to open the circular buffer which returns the file descriptor that will be associated with the circular buffer object passed as the function parameter Page 119 NetBurner Programmers Guide 2 Sees eet Sk ele 8 he Sos Sah tent et A a a int OpenCircularBuffer CircularBufferObject pCbo First initialize my circular buffer pCbo get pointer 0 pCbo put pointer 0 OSCritInit amp pCbo critical section Set up the I O expand function to point at the cbo functions cb ioexpand read cbo read cb ioexpand write cbo write cb ioexpand close cbo close Get the fd for the cbo int fde GetExtraFD void pCbo amp cb ioexpand Now set up the file descriptor state for our fd ClrDataAvail fde no data to be read SetWriteAvail fde space available for writes ClrHaveError fde no errors yet return fde Geos lnce eee S Sonos e Sih cose Se Sets See eee eae tele See See oe UserMain Bow cT re Se a ee NET M e RE void UserMa
140. r n else gDestPort int atoi buf if ExtractPostData tfDestIpAddr pData buf max chars 1 iprintf Error reading post data tfDestIpAddr r n else Page 75 NetBurner Programmers Guide gDestIp AsciiToIp buf if ExtractPostData tfMessage pData buf max chars lt 0 iprintf Error reading post data tfDestPort r n else SendMsg gDestIp gDestPort buf We have to respond to the post with a new HTML page In this case we will redirect so the browser will go to that URL for the response RedirectResponse sock index htm return 0 Specify the function to call when a user clicks Submit on the web page form void RegisterPost SetNewPostHandler MyDoPost Index htm lt HTML gt lt HEAD gt lt TITLE gt NetBurner TCP Client Example Program lt TITLE gt lt HEAD gt lt BODY BGCOLOR ffffff gt lt img src logo jpg gt lt br gt lt H1 gt TCP Client Example Program lt H1 gt This example program will open a TCP connection to a TCP Server at lt br gt the specified IP address and send a message A simple TCP Server lt br gt TcpServerWin exe is included in the nburn pctools directory lt FORM ACTION bogus htm METHOD POST gt lt br gt lt TABLE gt lt TR gt lt TD gt Enter Message to send lt TD gt lt TD gt lt INPUT NAME tfMessage TYPE text SIZE 30 gt lt TD gt lt TR gt lt TR gt
141. r point to point communications where reliability and sequencing of data is required TCP handles retransmission of data acknowledgements error detection and will guarantee the data received will be sequenced in the same order as it was sent UDP can be thought of as a scaled down protocol as compared with TCP It is a connectionless protocol that does not guarantee delivery and does not sequence the segments although each segment is numbered UDP is a send and forget protocol that does not use acknowledgements A common comparison is that TCP is similar to a phone call and UDP is similar to a post card although the time difference between a phone call and the mail must be ignored With TCP you connect to a specific destination phone number When that person answers they say hello you say Hi my name is Bob and then the conversation continues with each side speaking and responding in a well behaved conversation With UDP you essentially transmit a datagram like writing on a post card and send it without verifying it was received or undamaged along the way When choosing between TCP and UDP some major concerns are the overhead it takes to establish a TCP connection speed and the reliability of data transmission For example SNMP uses UDP SNMP is used to monitor a network and sends a lot of messages for status updates and alerts If TCP were used the overhead of establishing maintaining and closing a connection for each m
142. reated by the HTML source code needs to be able to link to the variable name For example to display TimeTick the application would need to include utils h otherwise a linker error will occur Include files can be handled two ways you can use an INCLUDE tag in the HTML code or you can create a header file with the name htmlvar h that will be automatically included if no INCLUDE tags are detected in the HTML source code If you choose to use the htmlvar h header file it must be located in the same directory as the htmldata cpp file or if you are using NBEclipse it must be in the include file path To add the include file path using NBEclipse Right click on your project and select properties Select C C Build options Select GNU C Compiler gt Directories Use the icon in the include path box to add the project s HtmlVariablesWMtml folder to the list of include paths A screen capture of NBEclipse with the path added is shown below Page 43 NetBurner Programmers Guide 2 Properties for HtmlVariables aB Example htmlvar h file ifndef HTMLVARS H_ define HTMLVARS_H_ include lt constants h gt include lt system h gt include lt startnet h gt const char FooWithParameters int fd int v endif HTMLVARS H Page 44 NetBurner Programmers Guide Example HTML file using the INCLUDE tag lt HTML gt lt BODY gt lt INCLUDE foobar h Value VARIABLE MyVar gt l
143. request and fills it in as a default value for the destination IP address to send the message The message to send is entered as a text field The message is not stored in the NetBurner device it is just a temporary string displayed in the web browser To send a message a user clicks on the Send Message submit button This is a special HTML command that sends a POST message to the web server containing the message to send This is where the MyDoPost function in clientweb cpp comes into play It intercepts the post and takes the appropriate action In the case of sending a message it extracts the message data and calls the SendMsg function SendMsg in clientweb cpp makes a connect call using the passed message and stored values of destination port number and IP address Once the connection is made SendMsg calls write to send the message followed by close to terminate the connection Page 77 NetBurner Programmers Guide 13 UDP User Datagram Protocol UDP is a datagram oriented protocol that does not guarantee delivery TCP is a stream oriented protocol with guaranteed delivery With TCP you do not have control over what data will be sent with each IP datagram but with UDP datagram will produce one IP datagram The advantage with UDP is that each datagram can contain one standard piece of data such as a measurement or command With TCP you would have to implement a protocol to identify the beginning end and type of each p
144. ress section of this guide 2 4 Dynamic IP Address DHCP When the factory program boots it will first attempt to obtain an address from a DHCP server If you are connected to a network with a DHCP server everything should get configured automatically 2 5 Network Configuration Step by Step Instructions Get a static IP address or use DHCP Install the NetBurner Development Tools on your host computer 3 Connect the 12 VDC power supply US and Canadian customers only to the board by inserting the P5 male connector on the power supply cord into the P5 female connector on the board assembly on the edge of the board near the DB 9 connector Please refer to your Quick Start Guide for additional information 4 If you are part of an existing network or are using a hub Use the blue RJ 45 patch cord to connect your NetBurner board to an unused network jack or hub port Note You cannot use the blue patch cable to connect directly to a network card in a computer When finished skip to step 6 5 Ifyou do not have a hub and want to connect directly to your host computer Use the red RJ 45 patch cable to connect your NetBurner board to your host computer Note You cannot use the red patch cable to connect to a network hub or existing network jack 6 Plugin the power supply 120VAC input nm Page 10 NetBurner Programmers Guide 7 Execute the IPSetup exe program From the Windows Start gt NetBurner gt IPSetup tool If you
145. rintf IP ShowIP ib netIP iprintf r n iprintf Mask ShowIP ib netIpMask iprintf r n Page 25 NetBurner Programmers Guide iprintf Gate ShowIP ib gt netIpGate iprintf r n iprintf DNS ShowIP ib gt netDNS iprintf r n iprintf Interface Name s r n ib gt InterfaceName iprintf r n Display Flash IP values This function demonstrates two methods to read the IP settings stored in the Flash Configuration Record 1 Using the gConfigRec global read only structure 2 Using the RawGetConfig functoin to obtain a pointer to a specific Configuration Record Saaai Foe Ne an De oe Be TC MT IO TRE void DisplayFlashIPSettings int RecordNumber Note that gConfigRec only applies to ConfigRecord 0 iprintf r n FLASH IP SETTINGS r n iprintf These values will be 0 if you are using DHCP r n iprintf d Flash settings using gConfigRec for Record 0 r n iprimtf l ShowIP gConfigRec ip Addr iprintf r n iprintf ae ShowIP gConfigRec ip Mask iprintf r n iprintf Gate ShowIP gConfigRec ip GateWay iprintf r n iprintf DNS ShowIP gConfigRec ip DNS server iprintf r n Note that ConfigRecord structures start at 0 for the first interface ConfigRecord cr RawGetConfig RecordNumber iprintf r nIP Flash settings using RawGetConfig for Record d NrMn RecordNumber iprintf IP ShowIP cr ip Addr
146. rious options for the new NetBurner project Project Configuration Options Target platform MOD5270 v Target IP NetBurner Application Wizard If you would like NBEclipse to generate your project please select your configuri Not all options are avaiable for every platform Options v AutoUpdate g a WiFi Jv DHCP Network Debugging v WebServer Im V TaskScan The features we selected are AutoUpdate Enables application updates through a network connection DHCP Ability to get a DHCP address from a DHCP server Web Server Enables HTTP web services Task Scan Task Scan enables you to get a snapshot of what RTOS tasks are running in the Release build of your application including the call stack and source code line numbers for each task To use Task Scan you run the Windows TaskScan exe program on a PC which communicates with your NetBurner device Smart Trap Provides additional debug information if your application crashes For example a null pointer assignment stack overflow or bus error The information is displayed through the debug serial port and can be viewed with a utility such as MTTTY The default serial port is UART 0 Network Adds function call to enable network debugging if a Debug build of the code is Debugging compiled and downloaded to the target device Page 14 NetBurner Programmers Guide 5 2 Template Program Source Code Edit the top of the file to add the Te
147. rly anything you type in the MTTTY window will be sent as UDP datagrams to the host PC and vice versa Page 82 NetBurner Programmers Guide 13 2 UDP Client Server Application Using UDP Sockets To listen for incoming UDP packets use the function int UdpFd CreateRxUdpSocket port then use recvFrom to block and wait for incoming packets Note that the standard Berkley Sockets implementation will block forever on the receive function If you want to allow the task to have control you can wrap the recvFrom function inside a select function using the UDP file descriptor and a timeout To send outgoing UDP packets use the sendto function BRK KK KK Kk UDP Sockets Example This application will send receive UDP packets with another host on a network such as a PC Use the MTTTY serial port program to access the menu and prompts to specify the destination IP address and port number NetBurner supplies an API for handling UDP as a C Class using UDPPacket or you can use a UDP socets API see UDP socet example For an external UDP host you can use the NetBurner java example or the NetBurner UDP terminal program FER A I ok sk ke ke e kk f include predef h include lt stdio h gt include lt stdlib h gt include lt ctype h gt include lt startnet h gt include lt ucos h gt include lt udp h gt include lt autoupdate h gt include lt string h gt include lt taskmon h gt include lt d
148. rmine if it has a DHCP assigned IP address is to use the IPSetup program from Windows Start gt Programs gt Netburner NNDK gt IP Setup tool In the screenshot below the IP address field representing the static IP address is shown as 0 0 0 0 followed by the DHCP assigned IP address i e 10 1 1 101 Other parameters such as the network mask gateway and DNS are also assigned and can be accessed as parameters in your application The NDK Settings section left pane of the IPSetup window represents the static settings Page 20 me NetBurner IPSetup NDK Settings P 0 Network Mask Gateway OF 0 0 DNS 0 0 0 0 Baudrate fi 15200 Mac Address 00 1 D 8B F1 FA 5B NetBurner Programmers Guide Select a Unit D 10 8B F1 FA BB IP 0 0 0 0 DHCP 10 1 1 101 CFY 2 40 Search Again Launch Webpage Advanced Close For additional information about IP Setup please refer to your NNDK User Manual From Windows Start gt Programs gt Netburner NNDK gt NNDK Users Manual Page 21 NetBurner Programmers Guide 7 Changing IP Addresses at Run Time System configuration parameters such as IP address mask gateway and DNS are stored in two places 1 Configuration Records used by the system to store configuration parameters in flash memory 2 Interface Blocks used by the system at run time There are 3 Configuration Records numbered 0 1 and 2 as defined in nburn include netinterface h
149. rnetIP iprintf Attempting DHCP r n if GetDHCPAddress DHCP OK iprintf DHCP Failed r n else iprintf DHCP IP Address else iprintf Static IP Address ShowIP EthernetIP iprintf r n OSChangePrio MAIN PRIO EnableAutoUpdate OSSemInit amp MySemaphore O0 if OSTaskCreate MyTask NULL void amp MyTaskStack USER TASK STK SIZE void MyTaskStack MAIN PRIO 1 OS NO ERR iprinttf Error creating task r n The while loop will pend on MySemaphore and display a message when a post is detected while 1 iprintf gt gt gt UserMain Pending on Semaphore from MyTask r n OSSemPend amp MySemaphore 0 iprintf lt lt lt UserMain Semaphore was posted from MyTask r n r n Page 103 NetBurner Programmers Guide 15 1 3 Mailbox Example A mailbox is similar to a semaphore except a pointer variable is passed as the message A task or ISR can post a message but only a task can pend on a message Both the posting task and pending task must agree on what the pointer points to Multiple task user input example This program illustrates how to create a task and use a mailbox to accept user input from a serial port 1 UserMain task will wait pend on a mailbox for user input 2 UserInput task will block waiting for a user to type in data from the serial port 3 This example also illustrates how to termi
150. s 4 digits it would not know where one ended and the next began In contrast to TCP UDP covered in the next chapter is an unreliable datagram oriented connectionless protocol Delivery is not guaranteed but each output operation creates and sends one UDP datagram In the above A D example each reading or some number of multiple readings could be sent as a single datagram and the client could then process one datagram at a time Network Bandwidth and Packet Size Network bandwidth and packet size are significant considerations when writing an application In practice an application such as the A D example would probably create packets with a number of reading field or send a fixed multiple number of readings in each packet 12 1 TCP Server Introduction A TCP server is basically an application that creates a listening socket and then listens on the socket for incoming connections When an incoming connection is detected the connection is then accepted A web server is an example of a familiar TCP server A web server listens on well known port number 80 for incoming connections Once a connection is established the web browser will send a GET request to the web server which will then send the requested information and terminate the connection A web server is just a specific case of a TCP server To connect to a TCP server you must specify a port number A port number is a 16 bit value Since you must know the port number
151. s used to determine if the flash memory space contains valid data If the key is not found then the flash memory is initialized with default values This is useful to handle two conditions when the hardware is used for the first time and when a software modification changes the non volatile data structure the key would be incremented to a new value to force initialization again Lines 19 28 This is the non volatile memory structure The user parameter flash storage area is an 8k flash sector 8k by default but can be expanded Applications store and recall data to this sector by writing the entire structure with the API calls SaveUserParameters and GetUserParameters Lines 72 150 Each FUNCTIONCALL tag in the index htm file has a corresponding function defined in the format void foo int sock PCSTR url where foo is the name of the function sock is a handle to the network socket connection and url is the actual URL that was sent to the web server from the web browser Some or all of these parameters will be used depending on your application If the function needs to write data to the web client then the write function can be used with the sock parameter This can be useful for filling in data fields or generating graphs The important thing to remember is that the client web browser will not see the FUNCTIONCALL tag As far as the browser is concerned all the data is just an input stream from a TCP connection To verify this y
152. se iprintf Static IP address ShowIP EthernetIP iprintf XrXn Jy OSChangePrio MAIN PRIO EnableAutoUpdate while 1 iprintf Ken ra BYTE pA pB pC NULL Pointers to allocated memory blocks iprintf Allocating 1 000 000 bytes pA r n Page 133 NetBurner Programmers Guide pA BYTE malloc sizeof BYTE 1000000 if pA NULL iprintf malloc failed r n showHeapSpace iprintf Allocating 3 000 000 bytes pB r n pB BYTE malloc sizeof BYTE 3000000 if pB NULL iprintf malloc failed r n showHeapSpace iprintf Allocating 512 000 bytes pC r n pC BYTE malloc sizeof BYTE 512000 if pC NULL iprintf malloc failed r n showHeapSpace Now freeing data in order B A C This illustrates that the spaceleft value can not increase until the last block allocated pC is freed if pB NULL iprintf Free pB r n free pB showHeapSpace if pA NULL iprintf Free pA r n free pA showHeapSpace if pC NULL iprintf Free pC r n free pC showHeapSpace OSTimeDly TICKS PER SECOND 10 Page 134 NetBurner Programmers Guide 21 The Template Program Command Line Mode You have two options for code development using the NetBurner Tools The first is the IDE discussed earlier The second is using the make utility from a command promp
153. signed long ip TftpServer The address of the TFTP server to load data from unsigned long baud rate The initial system Baud rate unsigned char wait seconds The number of seconds to wait before booting unsigned char bBoot To Application True app False monitor unsigned char bException Action What should we do when w have an exception unsigned char m FileName 80 The file name of the TFTP file to load unsigned char mac address 6 The Ethernet MAC address unsigned char ser boot unsigned long ip DNS server unsigned char core mac address 6 The Base unit MAC address unsigned char direct Tx unsigned long m ExtraData 4 unsigned char m bUnused 3 unsigned char m q boot True to boot without messages unsigned short checksum A Checksum for this structure attribute packed ConfigRecord c c c I c unsigned char typeof if c 1 G c s Page 22 NetBurner Programmers Guide The read only system config record extern const ConfigRecord gConfigRec 7 2 Heading the Configuration Record The functions to retrieve and save a ConfigRecord are ConfigRecord GetIfConfig int num void SavelfConfig ConfigRecord cr int num where num represents the interface number 0 1 or 2 The cr pointer would point to the new ConfigRecord you wish to save in flash memory Although the gConfigRec is available as th
154. ssCmdLine argc argv if WSAStartup MAKEWORD 1 1 amp WSAData 0 printf Error loading Winsock n return 1 Create socket to listen for UDP datagrams sListen socket AF INET SOCK DGRAM 0 if sListen SOCKET ERROR printf Error creating sListen socket d n WSAGetLastError return 1 Setup listen address structure sinListen sin addr s addr htonl INADDR ANY sinListen sin family AF_INET sinListen sin port htons dListenPort Bind socket to listen address if bind sListen struct sockaddr amp sinListen sizeof sinListen SOCKET ERROR printf bind error for sListen d n WSAGetLastError return 1 Create and start thread to receive UDP packets HANDLE CreateThread LPSECURITY ATTRIBUTES lpThreadAttributes ptr to attributes DWORD dwStackSize initial thread stack size in bytes LPTHREAD START ROUTINE lpStartAddress pointer to thread function LPVOID lpParameter argument for new thread DWORD dwCreationFlags creation flags LPDWORD lpThreadId pointer to returned thread identifier 4 DWORD dwThreadId HANDLE hThread hThread CreateThread NULL 0 ReceiveUDP LPVOID sListen 0 amp dwThreadId Create socket to send UDP datagrams sSend socket AF INET SOCK DGRAM 0 if sSend INVALID SOCKET printf Error creating sSend socket d n WSAGetLastError return 1 name the socket sinSend sin
155. stop reading now and go get an IP address and network mask from your network administrator If you follow the advice in this paragraph on an existing network without an assigned IP address the Administrator will hunt you down IP addresses are used to route packets from place to place on Intranets Internet If you are not part of an established network and your Ethernet segment is isolated you can choose just about any IP address you desire The powers that be have actually set aside some addresses for isolated networks They are documented in RFC1918 The reserved ranges are 10 0 0 0 to 10 255 255 255 Class A 172 16 0 0 to 172 31 255 255 Class B 192 168 0 0 to 192 168 255 255 Class C Page 11 NetBurner Programmers Guide If you are doing development on an isolated network you can use the following addresses they will be used for all of the examples in the documentation e Set Your PC s Network Adapter Card IP Address to 10 1 1 10 only change the Network Adapter Card do not change your Dial Up Adapter settings e Set the IP address of the NetBurner board to 10 1 1 11 e Set the network mask for both the PC network adapter and the NetBurner board to 255 255 255 0 4 Web Browsers and Proxy Servers If you are working on a corporate LAN that uses a proxy server for Internet web browsing you will need to exclude the IP address of your NetBurner hardware in your web browser s proxy server settings preferences Otherwise an attem
156. t Typical reasons for choosing the command prompt mode are that some developers simple prefer this method or you may have a favorite editor IDE that you prefer over the NetBurner IDE Most editors can invoke an external compiler to build the project This section will detail how to write compile and download a program using the command line tools The details of the make utility makefile will also be covered Traditionally called the Hello World program our Template Program will specify a minimal code base from which you can write your future applications The objective of this template program is to print the characters Hello World out the debug port of your NetBurner device In addition this template program will enable network services so that it can be downloaded over a network connection instead of through a serial port or a BDM Background Debug Mode port The Debug Monitor The NetBurner device contains a flash memory boot sector loaded with a boot program called Bejote the Debug Monitor This program is designed to be very small and takes up less than 16 STUDIES Kbytes of memory space Note The Debug Monitor is not designed to provide full TCP network write communications although it does support the TFTP protocol JOU applicatio The full TCP IP Stack functionality is compiled as part of your application If you download an OM application that immediately crashes when it boots full network services will not be avai
157. t BR gt lt BODY gt lt HTML gt 10 2 2 Calling a Function with Parameters If you need to specify a function call but need to pass a parameter the FUNCTIONCALL tag will not work because the parameters are fixed as the socket fd and URL In this case we can use the VARIABLE tag to achieve the functionality of calling a function with a variable The include file e g htmlvar h must specify the function definition in the format below In this case we are passing an integer value v The first parameter must always be the socket fd const char MyFunction int fd int v The HTML source code then used the VARIABLE tag with the function definition below In this example we are passing the integer value of 1 lt VARIABLE MyFunction fd 1 gt When the application is compiled the resultant function call will be WriteHtmlVariable fd MyFunction fd 1 This function returns an empty string which will have no effect on the web page An example of what a function might do is shown below const char MyFunction int fd int v char buffer 255 siprintf buffer MyFunction was called with v d r n v writestring fd buffer return X0 Return a const char here of zero length so it wont print anything to the HTML page Page 45 NetBurner Programmers Guide 10 2 3 Creating Custom Structures or Classes The VARIABLE functionality can be extended to support user defined types
158. t bit is set or a timeout occurs A timeout is ok in this situation we just use it to illustrate the task is still running if select FD SETSIZE amp read fds fd set 0 amp error fds 30 TICKS PER SECOND if FD ISSET fdnet amp read fds Network data available int n read fdnet RXBuffer RX BUFSIZE 1 RXBuffer n 0 iprintf Read d bytes s n n RXBuffer writestring fdnet RXBuffer if FD ISSET fdnet amp error fds amp amp FD ISSET fdnet amp read fds Network error condition iprintf Network Error closing socket n close fdnet fdnet 0 Page 58 NetBurner Programmers Guide else Select timed out If timeout exceeds 10 timeout periods the connection will be closed iprintf select timeout n tcp timeout t if tcp timeout gt 10 iprintf Connection timed out closing socket n close fdnet fdnet 0 Select While fdnet is valid while 1 while listen void UserMain void pd InitializeStack Initialize the TCP IP Stack if EthernetIP iprintf Trying DHCP r n GetDHCPAddress iprintf DHCP assigned the IP address of ShowIP EthernetIP iprintf Pent J else iprintf Static IP address set to ShowIP EthernetIP iprintf XrXn EnableAutoUpdate Enable network code updates OSChangePrio MAIN PRIO Set this task priority ifdef DEBUG
159. t nbytes int close int fd void extra uH int GetExtraFD void extra data struct IoExpandStruct pFuncs void GetExtraData int fd void FreeExtraFd int fd The TCP state call back fd socket has new data fd 0 means error typedef void tcp read notify handler int tcp fd When data comes in or the TCP connection enters an error state register a callback to handle the event void RegisterTCPReadNotify int tcp fd tcp read notify handler newhandler Page 116 NetBurner Programmers Guide The Set and Clr functions are used to update the state of your fd device for file I O functions such as select read and write The IoExpandStruct is used to declare function pointers for the read write and close functions that will be implemented in your application as well as an extra void pointer that you can use for whatever you wish GetExtraFD is the function that will return a fd for the object passed as the IoExpandStruct The extra data void pointer is optional and can be used to pass data into your fd You can read the extra data value at any time with the GetExtraData function FreeExtraFd will release the fd back to the pool of available fds The tcp read notify handler and RegisterTCPReadNotify are callback functions These functions will get called by the system if you define them for the corresponding TCP event 16 3 Using File Descriptors to Pend on Multi
160. t will run on NetBurner provided hardware No other rights to use this program or its derivatives in part or in whole are granted It may be possible to license this or other NetBurner software for use on non NetBurner hardware Please contact sales netburner com for more information NetBurner makes no representation or warranties with respect to the performance of this computer program and specifically disclaims any responsibility for any damages special or consequential connected with the use of this program Page 140 NetBurner Programmers Guide 22 3 The NetBurner Embedded Software License Copyright 1998 2008 NetBurner Inc All Rights Reserved Permission is hereby granted to purchasers of NetBurner hardware to use or modify this computer program for any use as long as the resultant program is only executed on NetBurner provided hardware No other rights to use this program or its derivatives in part or in whole are granted It may be possible to license this or other NetBurner software for use on non NetBurner hardware Please contact sales netnurner com for more information NetBurner makes no representation or warranties with respect to the performance of this computer program and specifically disclaims any responsibility for any damages special or consequential connected with the use of this program 23 NetBurner Contact Information Main Web Site http www netburner com E Mail sales netburner c
161. tdio h gt include lt ctype h gt include lt startnet h gt include lt autoupdate h gt include lt dhcpclient h gt include lt smarttrap h gt include lt NetworkDebug h gt include lt stdlib h gt include lt string h gt include lt bsp h gt include lt malloc h gt extern C void UserMain void pd const char AppName Malloc Example Page 132 NetBurner Programmers Guide showHeapSpace Uses the mallinfo funcation call to return the following structure struct mallinfo int arena total space allocated from system int ordblks number of non inuse chunks int smblks unused always zero int hblks number of mmapped regions int hblkhd total space in mmapped regions int usmblks unused always zero int fsmblks unused always zero int uordblks total allocated space int fordblks total non inuse space int keepcost top most releasable via malloc_trim space void showHeapSpace struct mallinfo mi mi mallinfo printf heapinig ss ss ss s Nae ha s iprintf used SdXrXn mi wordblks iprintf spaceleft Sd r n spaceleft iprintf free sd r n r n spaceleft mi fordblks void UserMain void pd InitializeStack if EthernetIP 0 iprintf Trying DECP 2 e n GetDHCPAddress iprintf DHCP assigned the IP address of ShowIP EthernetIP iprintf XrXn el
162. terfaces Page 9 NetBurner Programmers Guide 2 Networking Device Configuration 2 1 Overview The NetBurner hardware and software solution supports Ethernet and PPP network connections The Ethernet connection is made through the RJ 45 connector on your NetBurner device which then will connect directly to your host computer use the red crossover cable for direct connections without a hub switch or router to your Local Area Network LAN through a hub switch or router the Internet or both A PPP connection can be made using a RS 232 serial port as a hard wired connection or through a modem The NNDK supports the modem initialization for a ZOOM 56K modem If you are using a different modem you may need to modify the modem initialization string Contact the manufacturer of your modem for additional information 2 2 Obtaining an IP Address To get your NetBurner Network Development Kit NNDK up and running as quickly as possible you must have an IP Address for both your host computer and your NetBurner device The NetBurner factory application supports both static and DHCP assigned IP addresses 2 3 Static IP Address If you are part of an existing network and want to use a static IP address you must get the address from your network administrator If you connecting your NetBurner hardware to a single computer or are on an isolated network you should select one of the reserved addresses described in the How do I select an IP add
163. tes StartHTTP Start Web Server EnableSmartTraps Enable Smart Traps EnableTaskMonitor Enable Task Scan InitializeStack initializes the TCP IP Stack This is required for any network communications to take place The line if EthernetIP 0 GetDHCPA ddress checks the NetBurner device s IP address setting and if the IP address is 0 0 0 0 the device will attempt to contact a DHCP Server and obtain a dynamic IP configuration including the IP address mask gateway and DNS Server What if DHCP fails If you run IPSetup and notice that the IP address of your device is 0 0 0 1 this is an indication that a DHCP Server could not be found on your network The DHCP Client runs as a separate task so it will keep trying to get a DHCP address until it succeeds or the application explicitly calls StopDHCP The function call OSChangePrio MAIN PRIO sets the UserMain task priority to the default which is 50 The RTOS has a total of 63 priority levels Level 1 is the highest and level 63 is the lowest priority In a preemptive RTOS the highest priority task ready to run will execute For example the TCP IP stack task is a higher priority task lower priority number and will interrupt UserMain when necessary to process network data Some of the tasks are reserved For example task 63 is the system idle task which runs when no other tasks are ready to run The system defines the following tasks in nburn include consta
164. tifiers to separate the data from each reading Page 47 NetBurner Programmers Guide An example of sending data of different sizes using TCP vs UDP is illustrated below UDP Transfer TCP Transfer Device Stack Host Stack Device oak Tost Stack 32 Bytes 128 Bytes 224 Bytes 64 Bytes 64 Bytes 128 Bytes 128 Bytes HH Applications that use TCP are HTTP FTP Telnet and SMTP Applications that use UDP are DHCP BOOTP SNMP and DNS Page 48 NetBurner Programmers Guide 12 TCP Transmission Control Protocol TCP is used to create a reliable byte stream connection between two devices Usually one device is called a server and the other a client The first sentence contains important descriptive words that you need to consider when choosing between TCP and UDP Connection oriented The devices must establish a connection before they can exchange data Reliable TCP uses acknowledgements retransmissions checksums and flow control Stream based Although TCP and UDP both use IP TCP sends information as a byte stream There are no record markers to delimit the data For example if a server device is sending analog to digital A D readings to a client device the client will see a stream of digits TCP will not automatically insert delimiters to allow the client to determine where one measurement ends and the next begins To the client the stream may look like 98273129323424 Even if the client knew each reading wa
165. tions on the semaphore OSSemPost amp MySemaphore post to a semaphore OSSemPend amp MySemaphore 0 pend on a semaphore The second parameter in the OSSemPend function specifies the number of time ticks to wait A value of 0 waits forever A good way to express a wait value is to use the TICKS PER SECOND definition provided by the RTOS OSSemPend amp MySemaphore TICKS PER SECOND 5 to wait 5 seconds Semaphore Example Program This program will create 2 tasks and a semaphore The UserMain task will block for a semaphore posted from MyTask The output for this example is displayed through the serial debug port which can be viewed with the MTTTY program include predef h include lt stdio h gt include lt ctype h gt include lt startnet h gt include lt autoupdate h gt include lt ucos h gt include lt serial h gt include lt dhcpclient h gt p function prototypes extern C void UserMain void pd pe Global Variables const char AppName Semaphore Example DWORD MyTaskStack USER TASK STK SIZE OS SEM MySemaphore MyTask This task will post to a semaphor very 3 seconds void MyTask void pdata while 1 Page 102 NetBurner Programmers Guide OSTimeDly TICKS PER SECOND 3 iprintf MyTask Posted to Semaphore r n OSSemPost amp MySemaphore void UserMain void pd InitializeStack if Ethe
166. ts Stop Bits ANENA 1520 None 8 x 1 Iv Display Errors CR gt CR LF Font Comm Events Flow Control Timeouts Disconect V Autowrap aiting 2sec to start A to abort Ethernet IP 6 6 6 6 ask 6 6 6 6 AC fiddress 80 03 f4 01 24 3c pplication startedMy IP Address is 16 1 1 169 ainting for connection on port 23 onnected to 18 1 1 182 2649 Modem Status Comm Status TM EU cis DSRS RING RLSD CD CTS Hold XOFFHold TX Char 2 dis here DSRHold XOFF Sent TX Chars RLSDHold EOF Sent RX Chars Page 55 NetBurner Programmers Guide Now type some characters in the Telnet window You should see those characters displayed in the MTTTY window as shown below EP Multithreaded TTY DE Port Baud Parity Data Bits Stop Bits mico Tii cow 115200 None IB fi IV DisplayEnors Now CR gt CRALF FT NoEver Font Comm Events Flow Control Timeouts Disconect V Autowrap No Stat aiting 2sec to start fi to abort Ethernet IP 0 0 0 8 u AC fiddress 3 f 4 01 24 3c Application startedMy IP Address is 18 1 1 109 ainting for connection on port 23 18 1 1 102 2649 1 1 e 1 1 1 1 1 0 i 1 W 1 0 1 r 1 1 1 d 2 cts DSR RING RLSD CD I CTS Hold I XOFFHold I TXChar ps wis message g0 Modem Status Comm Status DSRHold XOFF Sent TX Chars o IL RLSD Hold
167. ules the ColdFire processor on your NetBurner device may have on chip SRAM available for your application to use For example the 5272 has 4k and the 5234 5270 and 5282 have 64k bytes of SRAM The primary reason to use the on chip SRAM is that it has single cycle access time The SRAM is initialized by the NetBurner system software and the first 0x400 bytes of SRAM is reserved for the vector table IMPORTANT The NetBurner system uses the first 400 bytes of the SRAM for the application vector table Your application must not write to that space Starting with tools release 2 1 RC6 the NetBurner system software uses the on chip SRAM by default for fast network buffering and OS task switching This provides a system speed increase of up to 50 and is the recommended use for the SRAM Using this SRAM in this way will provide a faster overall system performance increase than if you use the SRAM for a specific application function If you prefer the system use of SRAM can be disabled In addition to the fast buffering and task switching you can specify that certain variable be located in the SRAM with the FAST_USER_VAR and FAST_USER_STK macros as described in the following section 18 2 Using Fast SRAM in Tools Release 2 2 and Later The default setting for SRAM is to use it for the critical system variables stacks and network buffers In this default mode of operation the critical system variables will be always be stored in SRAM and the netw
168. unction definition extern C void YourFunctionName int sock PCSTR url This directive tells the C compiler to leave the function names intact by disabling C name mangling Page 33 NetBurner Programmers Guide In the previous chapter our basic web page example demonstrated static web content Your NetBurner platform can easily do dynamic content as well In this example we will create a configuration web page interface that will provide submission and recall of changeable data by using HTML forms Below is a screen shot of this application E Interactive Configuration Example Microsoft Internet Explorer SEE File Edit View Favorites Tools Help x j gt Yl 3 Q Back lt 2 x g p Search rd Favorites a Media 2 7 Se Address http 10 1 1 103 INDEX HTM Bo Google esearch Web Ge Norton AntiVirus El Links Interactive Configuration Example UTC Time OLocal Offset 0 Hours CI Leap Second Day 0 Add O Subtract DST 9 Enable Disable Submit New Settings Cancel Changes 4B Internet 9 2 How to Use HTML Forms You have probably encountered forms many times on the web especially for ecommerce and feedback forms The format is typically some number of text fields checkboxes radio buttons combo boxes and a submit button When you click on the submit button the data from the form is sent to the web server as a HTTP POST T
169. upport will allow fast code development using NBEclipse and also allow network configuration using the NetBurner IPSetup utility i e IPSetup tool For additional information on IPSetup and AutoUpdate please refer to your NNDK User Manual From Windows Start gt Programs Netburner NNDK gt NNDK Users Manual Page 15 NetBurner Programmers Guide The extern C declaration is used to so that UserMain is compatible with both C and C applications it prevents the name mangling associated with C extern C void UserMain void pd The line const char AppName Template Program will enable the IPSetup utility to display the application name You can change Template Program to any string you wish If this variable is not set IPSetup will not display a value for this field The maximum string length is 40 characters The UserMain function is a thread created by the system to be your application s main entry point for taking control over the function of the device The parameter passed to UserMain is a void pointer to some type of data This is a feature of the uC OS RTOS but it is not needed for the NetBurner tool set The next group of function calls handle system initialization InitializeStack Initialize TCP Stack if EthernetIP 0 Enable DHCP if no static IP GetDHCPAddress OSChangePrio MAIN PRIO Set UserMain task priority EnableAutoUpdate Enable network upda
170. urrently connected r n break case W WiFiShowScanForAP break case P ProcessPing buffer 1 break case DisplayMenu break default break Switch void UserMain void pd InitializeStack if EthernetIP 0 GetDHCPAddress nwifi if AddWiFiInterface if InterfaceIP nwifi if GetDHCPAddress nwifi if OSChangePrio MAIN PRIO EnableAutoUpdate StartHTTP EnableTaskMonitor iprintf Application started n DisplayMenu while 1 char buffer 255 buffer 0 0 Remove blank lines from r n conversions and ignore whitespace while buffer 0 gets buffer ProcessCommand buffer Page 124 NetBurner Programmers Guide 17 2 Multi Home Multi home means that your device can respond to more then one IP address However your device has only one MAC address so there are some limitations such as the fact DHCP can only be used on one of your interfaces since a separate MAC address is required for each DHCP client To add Multi Home functionality to your application 1 Uncomment the define MULTIHOMF in nburn include predef h Multi home is disabled by default at a system level so that non multi home applications do not incur the overhead of the Multi home functionality 2 Add the following includes in your application include lt multihome h gt include lt netinterface h gt 3
171. used the default installation settings the program is located in the C nburn pctools ipsetup directory 8 The IPSetup program will automatically locate all NetBurner devices on your network If more than one device appears select your device by matching the MAC address displayed in IPSetup with the MAC address sticker on your NetBurner board If using a static IP address Enter your IP Address and Mask in the corresponding IPSetup text boxes For example if you are on an isolated network the IP Address could be 10 1 1 11 and the Mask could be 255 255 255 0 see How Do I Select an IP Address Select the Set button to send the modifications in the CFV2 40 If using DHCP Verify that the IP address and mask have been set 9 Your NetBurner hardware is now configured Simply click on the Launch Webpage page button in the IPSetup window to view the factory application me NetBurner IPSetup NDK Settings Select a Unit IP fo 1 1 30 MAC 00 10 98 F1 FA 6B IP 10 1 1 30 CF 2 40 Network Mask 255 255 255 Q0 Set gt Gateway 18 Ps T 1 sss DNs 0 8 B Baudrate 115200 Search Again Mac Address 00 1 D 8B F1 FA BB Launch Webpage Advanced Close For additional information please refer to your User Manual From the Windows Start Menu Start Programs NetBurner NNDK 2 NNDK Users Manual 3 How Dol Select an IP Address If you are part of an existing network and are not using DHCP
172. vice or host Note that the application uses the same port number to send and receive data but you can change this to any other port number you wish The application will create a thread to recive packets and display them on the debug port while the main task will take any data you type in to the MTTTY dumb terminal and send it as a udp packet to the destination IP address Page 79 NetBurner Programmers Guide eK A A A A A I AA RR A I A A I ko ke ek A ke e ke e e ee x x include predef h include lt stdio h gt include lt ctype h gt include lt startnet h gt include lt ucos h gt include lt udp h gt include lt autoupdate h gt include lt dhcpclient h gt extern C void UserMain void pd const char AppName UDP Send Receive Example Allocate task stack for UDP listen task DWORD UdpTestStk USER_TASK STK SIZE UDP Server task will wait for incoming packets on the designated port number which is passed as a OSTaskCreate void parameter void UdpReaderMain void pd int port int pd cast void param as int port number iprintf Listening on UDP port d r n port Create a FIFO for the UDP packet and initialize it OS FIFO fifo OSFifoInit amp fifo Register to listen for UDP packets on port number port RegisterUDPFifo port amp fifo Construct a UDP packet object using the previously declared FIFO The UDP constructor will only return whe
173. viously called OSCritEnter calls OSCritExit Note that the number of enter calls must match number of exit calls OSCritObj is a C implementation that uses scoping to automatically call the enter and exit functions See example below OSLock Disables other tasks but not interrupts Increments for each OSLock OSUnlock decrements for each OSUnlock The C object OSLockObj was OSLockObj created to assist in making sure that an unlock is called for each lock When an OSLockObj is created the constructor calls OSLock When the object goes out of scope OSUnlock is automatically called by the destructor USER ENTER CRITICAL USER EXIT CRITICAL Macro that disables other tasks and interrupts Increments count on enter decrements on exit Page 100 NetBurner Programmers Guide How do you decide which type of mechanism to use Some guidelines are If you need some type of signal but do not need to pass any data use a Semaphore A semaphore is a single 32 bit integer that increments and decrements for each pend or post If you want to pass a single 32 bit number you can use a Mailbox or Queue Most applications use the 32 bit number as the data but it could also be a pointer to a structure or object A queue is like an array of mailboxes You declare the number of queue entrys a compile time If you want to pass a structure or object then use a FIFO You may be wondering how a FIFO differs from a Queue The di
174. while 1 iprintf Message from MyTask r n OSTimeDly TICKS PER SECOND this is a blocking call p RE UserMain D cc EN void UserMain void pd InitializeStack OSChangePrio MAIN PRIO if EthernetIP 0 iprintf Attempting DHCP r n if GetDHCPAddress DHCP OK iprintf DHCP Failed r n else iprintf DHCP IP Address else Page 98 NetBurner Programmers Guide iprintf Static IP Address ShowIP EthernetIP iprintf r n EnableAutoUpdate This example passes data to the task but this is optional WORD MyTaskData 1234 Create and launch the task Note that we selected a priority of MAIN PRIO 1 which means the new task is of lower priority than UserMain The implication is that if UserMain does not block MyTask will never run x if OSTaskCreate MyTask void amp MyTaskData void amp MyTaskStack USER TASK STK SIZE void MyTaskStack MAIN PRIO 1 OS NO ERR iprintf while 1 OSTimeDly TICKS P Error creating task r n ER SECOND 2 iprintf Message from UserMain r n 14 5 Interrupts To obtain specific information on interrupts used in your specific NetBurner device please reference the Platform Documents that came with the development kit Some common values and their
175. xtracted from the form using the function int ExtractPostData PCSTR name PCSTR data PSTR dest buffer int maxlen This function takes the HTML post data sent to the POST function extracts the data associated with a specific name and returns it in dest buffer For example ExtractPostData radioUTC Local pData buf max chars looks for the name radioUTC Local in the string pData and returns the data portion in buf The max chars parameter specifies the maximum length of characters to store in buf to avoid an overflow Once the data is stored in buf the example application stores the value in an array and the array is written to the user flash storage area with the function SaveUserParameters amp NV Settings sizeof NV Settings SaveUserParameters is an API function that will take a pointer to the data to be stored in this case the address of NV Settings and a second parameter representing the size of the data This is easily done by using a structure and the sizeof function Page 41 NetBurner Programmers Guide 10 Dynamic Web Content using the VARIABLE Tag Most applications using the web server have a need to display dynamic content for users who connect to the web server Dynamic content can be presented in a web page by embedding VARIABLE and FUNCTIONCALL HTML tags in the web page source code The tags are embedded in and HTML comments so they do not affect the HTML presentation As the NetBurner web server d
Download Pdf Manuals
Related Search
Related Contents
参考資料g ポータブル電源 取扱説明書 株 主 各 位 柴野恒雄 第67期定時株主総会招集ご通知 Harbor Freight Tools 46225 User's Manual User Guide BluRay Player Genius DX-6020 Diplomarbeit - Telle Dell OpenManage Server Administrator Version 7.3 SNMP Reference Guide MERKMALE: FEATURES: RUNNER EN NL SE PT.qxp:ENGY Man FR Copyright © All rights reserved.
Failed to retrieve file