Home

Dynamic Web Pages With The Embedded Web

image

Contents

1. sessesseseseseeeeenennn nnne nennen nnne 9 Duel M M 9 Chapter 4 Serving a Basic Web Page sess enne neni ii nasa s enses risa sa ssa s nennen 10 Prep Work Building a Project Tweaking Files and PBuilder c ccccccccssssssseceeeceseesessaeeeeeeeseesees 10 NOW What M M 25 TIP Do Not Choke Your Embedded Web Server sssesseseeeeeeeeennnnee nnne 27 Chapter 5 Sneaky but Useful Comment Tags ccccccccccscssssssssececececessecseeeceeecsesesesneaeeeeeceseesesneaeeeeeeeseesees 28 Get information from the embedded device to display in the browser eeseeeeee 28 Set information from the browser on the embedded device eese 29 Chapter 6 Introducing Stub Functions eese ener en neni nn nennen nennt nass assess ne an 30 Chapter 7 Using Comment RpGet Tags with a Basic Web Page ccsscccccccessssessceeececeseesesnsaeeeeeeeseeeees 31 Ded 31 Be erereseiSop REED 32 Chapter 8 Our First Dynamic Web Page sess nennt nn nasse nsi ti sana asas aae 34 Chapter 9 Interactive Web Pages Made Easy eene nennen entera nasse nra 36 Adding an HTML Form and a Submit Button esses ener enne tana nasse aa 36 dgsr u H rr aea eane ESAE ae suaceuscutshined
2. lt RpEnd gt lt br gt Enter Data lt This comment block configures our form and what variables we will use gt lt RpFormInput type text name NameField size 32 maxlength 32 RpGetType Function RpGetPtr GetMyData RpSetType Function RpSetPtr SetMyData_ gt lt input type text name NameField size 32 maxlength 32 gt lt RpEnd gt lt br gt lt This comment block configures our submit button gt lt RpFormInput type submit value Submit gt input type submit value Submit gt lt RpEnd gt lt This comment block closes the form gt lt RpEndForm gt lt form gt lt RpEnd gt lt body gt lt html gt The only change is that instead of pointing my RpGet and RpSet tags to memory directly using the direct value am pointing them to functions which have named GetMyData and SetMyData RpGetType Function RpGetPtr GetMyData RpSetType Function RpSetPtr SetMyData After running the trigger cb html web page through Pbuilder it will create two related files called trigger cb c which represents the logical web page in C code and trigger cb v c which provides us with placeholder functions ready for us to flesh out Page 40 Copyright Digi International 2011 Here is the trigger cb v c file as PBuilder originally created it Created with PageBuilder version 4 04 on Fri Jan 21 10 16 38 2011 incl
3. 0 Call while waiting for TCP IP stack Not called after stack has started xou applicationTcpDown void static int ticksPassed 0 ticksPassed Page 48 Copyright Digi International 2011 Then we will add a function to root c named CreateXMLFile to create a dogs xml file in the RAM file system using standard C functions used to manipulate files That process will follow three basic steps which are open which creates the file write and close eae an XML file to store in FS RAMO vel CreateXMLFile void int status Return value buffer for writeQ and close functions fd File descriptor populated by open function printfC nCreating XML File in FS RAMO filesystem n Open Cor create file for reads or writes fd open RAMO dogs xml O CREAT O RDWR iu fd 0 Error handling printf APP Failed to open FS RAMO dogs xml d n getErrnoQ return Write XML data to file status write fd XML Data strlen XML Data if status strlen XML Data Error handling printf APP Failed d writing FS RAMO dogs xml d Nn status getErrno return Close file status close fd if status 0 Error handling printf APP Failed to close FS RAMO dogs xml d n getErrnoQ return printfC n n FILE CREATED n n s n n XML_Data First we will create the file with read and write permissions using the open function and th
4. 012345ABCD WEP Key 3 012345ABCD WEP Key 4 012345ABCD Page 12 Copyright Digi International 2011 4 Next choose the Services you wish to include with your project and click Next In this example only chose the Web Server esr NET OS Project Services Selection Select the services your application will use E CPU Load Monitor Web Server Secure Web Server Turn this option on to enable the HTTP server A set of device management web pages is provided that allow configuring network FTP Server parameters File management and other administrative tasks CLI Telnet CLI Serial CLI SSHv2 SSL SNTP SMTP RealPort Watchdog Timer TCP Serial Transfer ADDP Server iDigi connectivity M 5 NET OS will prompt you for additional settings which you might be able to accept by default If your environment settings are different you can change them here ese NET OS Project Additional Parameters Configure optional parameters your application will use General Settings Application Name l Ch4 Basic Web Page STDIO Port Serial Port D Enable c Dialog Settings Dialog Port Serial Port D Dialog Baud Rate 9600 Dialog Delay 5 Security Settings Root Account Password password E Debug Settings Automatically launch STDIO Dialog Console when Debugging this application Host Serial Console Port CoM
5. For my examples used an Ethernet cable and a static IP address without using Wi Fi ese NET OS Project Network Configuration Configure the default options your application will use For each network interface Ethernet TCP IP Options Ireless r C Bridge Obtain an IP address automatically DHCP Use the following IP address IP Address 192 168 1 197 Subnet Mask 255 255 255 0 Default Gateway 192 168 1 1 Primary DNS 192 168 1 1 Secondary DNS 192 168 1 2 Note Static DNS must be configured when using static IP Address to ensure all services work properly Enable Auto IP Page 11 Copyright Digi International 2011 To configure a Wi Fi connection select the Wireless option on the menu to the left ese NET OS Project Network Configuration Configure the default options your application will use For each network interface Ethernet Wireless Network TCP IP C Bridge Wireless Network Options Wireless Network Type Infrastructure v Wireless Network Name SSID 802 11 Band Enable Default Banc v Country Code v Channel Search 802 11 d h Options Authentication Open System Data Encryption Open no encryptio v Passphrase Wireless Login username Wireless Password password WEP Encryption 64 Default WEP Key Index 1 WEP Key 1 012345ABCD WEP Key 2
6. Q X a UI http siit92 168 1 196 B Most visited IM Gmail Hotmail ES News 3 Latest Headlines W Wikipedia What Kind of Dog is Scoobie Doo Scoobie Doo is a Great Dane Where is the Magic AJAX The important thing to notice is that all this occurred without a page refresh This is a method of web programming known as Asynchronous JavaScript and XML or AJAX Page 57 Copyright Digi International 2011 Chapter 13 Embedded devices and XML The Holy Grail of Embedded Web Developers With XML and our Digi embedded web server we can create a powerful combination As an example our embedded web server might have the following web resources that it needs to serve to a browser e HTML file 500k e 3jpegs 250k each e JavaScript file 100k e Style sheet 50k e XML file 1k We want a dynamic page and we could use this HTML code in the lt head gt to force the entire page to refresh every 5 seconds lt meta http equiv refresh content 5 gt Unfortunately in this case a single page refresh requires 1401k of data That is not efficient at all If we use the previous option of manually refreshing the entire page every 5 seconds with a meta tag we place a serious burden on the web server If we can refresh only the XML file we create the ability to update only the data in the web page without refreshing the entire page The Teeny Tiny and yet Magical my_data xml file Consider this simple XML
7. Simple counter i d var timer id Global timeout ID so we can exit later if we wish Quen Inc CO Gea Cals document getElementById c_variable innerHTML c timer id setTimeout Inc_c Q 500 calling function again to loop lt script gt lt head gt lt body gt lt p gt c span id c_variable gt lt span gt lt p gt lt p gt lt button onclick Inc_CQ gt Start C up lt button gt lt p gt lt body gt lt html gt Exiting the Loop If we wanted to exit the infinite loop we could use the clearTimeout function like this clearTimeout timer id Page 64 Copyright Digi International 2011 For example we could create another button that exits the loop I have placed the code used to exit the loop in bold text below html lt title gt some title lt title gt lt head gt script type text javascript gt var c 0 Simple counter var timer_id Global timeout ID so we can exit later if we wish function Inc C degunt USE men EbN N ene einne ramia CE MEER timer id setrTimeout Inc C 500 calling function again to loop function Done clearrimeout timer id script head body lt p gt c span id c_variable gt lt span gt lt p gt lt p gt lt button onclick Inc_C Q gt Start C up lt button gt lt p gt lt p gt lt button onclick Done gt Stop C lt button gt lt p gt lt body g
8. This code does not do much that is different from our previous examples with the exception that it has four variables and we are only updating the My Data variables every 475 ms Our goal is to request a refreshed version of this file from the embedded web server in an infinite loop We can use the setTimeout function to achieve this goal by combining it with the XML code we have already used Page 68 Copyright Digi International 2011 The Amazing JavaScript Program have created four buffer variables to make the code easier to read In practice would set the id with the tag in a single line without using a buffer variable The looping statement is shown in bold text htmT lt title gt some title lt title gt lt head gt script type text javascript gt function loadXMLDoc dname Magic function creating local XML copy if C window XMLHttpRequest Create local XML document xhttp new XMLHttpRequestQ else Use for older browsers xhttp new ActiveXxobject Microsoft XMLHTTP Request the XML file from server with GET xhttp open GET dname t Math random false xhttp send return xhttp responseXML Return the local copy E Get XML These are optional buffer variables that make the code easier to read var XML Datal var XML Data2 var XML Data3 var XML Data4 xmlDoc loadXMLDoc my data2 xml1 Creates a client copy of XML Store the value of My Data
9. comment tags in bold green text lt html gt lt title gt some title lt title gt lt head gt lt head gt lt body gt lt This comment block sets up our form to pass data with a get gt lt RpFormHeader method get RpNextPa e Pgformsubmitted gt form action formsubmitted html method get gt lt RpEnd gt lt br gt Enter Data lt This comment block configures our form and what variables we will use gt lt RpFormInput type text name Namerield size 32 maxlength 32 RpGetType Direct RpGetPtr MyData RpSetType Direct RpSetPtr MyData gt lt input type text name NamerField size 32 maxlength 32 gt lt RpEnd gt lt br gt lt This comment block configures our submit button gt lt RpFormInput type submit value submit gt input type submit value Submit gt lt RpEnd gt lt This comment block closes the form gt lt RpEndForm gt lt form gt lt RpEnd gt lt body gt lt html gt First notice that our NET OS comment tags are broken up into pairs with an opening tag RpFormHeader RpForm Input and RpEndForm paired with an RpEnd closing tag Page 36 Copyright Digi International 2011 By using an HTML form element we allow the user to enter information and we send this back to the web server as an HTTP post transaction All the normal parts of an HTML form are combined
10. dname t Math random Q false xhttp send return xhttp responseXML Return the local copy function Get XML xmlDoc loadXMLDoc FS RAMO my data xml1 Creates a local copy of XML This can all be done without a buffer variable in a single pass like this document getElementById Switch 1 innerHTML xmlDoc getElementsByTagName Swi tch 1 0 chi 1dNodes 0 nodevalue setrimeout Get XML 500 Loop every 500 milliseconds lt script gt The HTML Body The HTML body is again merely a variation on the same theme lt body gt lt hil gt Press Switch 1 on the Protoboard h1 p b Switch 1 b span id Switch_1 gt lt span gt lt br gt lt p gt lt p gt lt button onclick2 Get XML gt Start Dynamic Data lt button gt lt p gt body lt html gt Page 76 Copyright Digi International 2011 How Does it Look Here is the page before we turn on the infinite loop in our JavaScript 192 168 1 197 C fi 192 168 1 197 ZA For quick access place your bookmarks here on the bookmarks bar I C Other bookmarks Press Switch 1 on the Protoboard Switch_1 Start Dynamic Data After we press the Start Dynamic Data button we begin updating the page every 500 milliseconds by repeatedly calling the Get XML function The page below shows our page automatically refreshing after the Start Dynamic Data button press but have not pressed dow
11. include AsExtern h fif RomPagerServer Yo Rx vU EE js Built from html Vformsubri tted html a 7 For usage see root c trigger cb html andi a html char MyData 50 Is endif RomPagerServer Now whenever the user requests or changes the data these two stub functions will automatically provide us debugging notes indicating that they have been called Note that when I use the Function keyword in the RpSetType attribute need to ensure that correctly assign and return my values in the stub functions Other Possibilities Remember that you can create complicated behavior with your callback functions When the client changes a value the callback function could e Set a flag to trigger some behavior in the root c code e Send data from a serial port TCP socket or UPD socket e Change the state of a digital output e Setapinas either a digital input or an output e Anything else the controller could do with a normal function call Page 42 Copyright Digi International 2011 Chapter 11 Adding JavaScript with comment tags to your HTML Pages It is important to remember that comment tags are not restricted to HTML code and can also be useful when working with JavaScript Initializing JavaScript Variables with comment tags This JavaScript code shown below does not do much but initialize and display variables however it does provide a useful demonstration JavaScript items are in bold black text and the
12. HTML file Here is the same page with the meta tag in the header asking for an automatic refresh A meta tag is an HTML tag with metadata or data about other data The meta tags are placed in the head section of the HTML file When the page is loaded in the browser it will automatically request a refreshed page from the server every 5 seconds You will see the automatic refresh request in bold text and the comment tags in bold green text htmT lt title gt some title lt title gt lt head gt lt meta http equiv refresh content 5 gt lt head gt lt body gt lt Display a 16 bit signed value gt My Data lt RpDisplayText RpTextType Signed16 RpGetType Direct RpGetPtr MyData gt lt RpEnd gt lt br gt lt Display a string gt My String lt RpDisplayText RpTextType ASCII RpGetType Direct RpGetPtr MyString gt lt RpEnd gt lt br gt lt body gt lt html gt Note Remember if you add the refreshing metatag you will need to rerun the Pbuilder utility again and make any changes to the filename_v c file created as we did in the previous chapter PBuilder will automatically overwrite the files which might cause you to lose any custom code in the filename_v c file Assuming the MyData integer variable starts at 2009 and MyString starts at Output String after they are served from the controller the HTML file will look like this
13. The HTML Code Here is a simple web page called showdata html with comment RpGet tags included that point back directly to the C variables I have placed the comment tags in bold green text lt html gt lt title gt some title lt title gt lt head gt lt head gt lt body gt lt Display a 16 bit signed value gt My Data lt RpDisplayText RpTextType Signed16 RpGetType Direct RpGetPtr MyData gt lt RpEnd gt lt br gt lt Display a string gt My String lt RpDisplayText RpTextType ASCII RpGetType Direct RpGetPtr MyString gt lt RpEnd gt lt br gt lt body gt lt html gt This HTML code will need to be run through the Pbuilder utility in order to link it logically to the C code running on the controller Once Pbuilder has been run successfully we can pass variable information from the controller to the browser directly Running the showdata html web page through Pbuilder will produce a showdata c file in the web gt result gt fixed gt html folder which represents a C language version of the web page This file might be intellectually interesting because it shows how NET OS represents HTML as C code but for our purposes we can ignore it for the moment Pbuilder will also produce another c file which we are interested in called the showdata v c You will find this file in the file in the web gt result gt stubs gt html folder The showdata v c file cr
14. allow easy integration with the embedded device Because the special tags are tucked into comments the browser will never see them and they will not interfere with your standard HTML code if you preview it a browser After you run the HTML code through PBuilder the tags will be compiled and won t show up in the final web page served by the Digi controller Get information from the embedded device to display in the browser Assuming I have a variable named MyData defined on my embedded device can access and display it with matched pairs of RpGet tags as shown here lt html gt lt title gt some title lt title gt lt head gt lt head gt lt body gt lt Display a 16 bit signed value gt See Riel DIGNARE RpTextType Signed16 RpGetType Direct RpGetPtr MyData gt lt RpEnd gt lt body gt lt html gt o RpDisplayText will display the value stored on the controller and also functions as an opening tag to be paired with the closing tag RpEnd o RpTextType defines what type of value is displayed In this case it is a 16 bit signed integer o RPGetType specified as Direct indicates that we are directly referencing the memory location of the data by the variable name indicated by the next tag RpGetPtr o RpGetPtr is the name of the variable on the controller and works like a pointer to the data o RpEndisa closing comment tag paired with the opening tag RpDisplayText Remember that the RpGet tags will
15. amp result M webcontents Rename ie hemil dg Import helo h he P PbSetup t Ei Export EN RpUsrDet t Build Project ae PBuilder pbb Clean Project amp E appconf anie Refresh R appconf h im cee A root c lose rojec E readme lose Unre lude From build 48 NET OS Update Flash NET OS MIB Compiler PE ree NN FS d d Convert To NET OS Debug Team Compare With Properties Copyright Digi International 2011 q Show resource in Windows Explorer Restore From Local History Alt Enter Page 20 19 After running the PBuilder program note that In the web result fixed directory the file RpPages c has been created In the web result fixed html directory the file hello c has been created In the web result stubs directory the files RoUsrDct c and RpUsrDct h have been created In the web result stubs html directory the file hello v c has been created gw Ch4 Basic Web Page Binaries H Archives in Includes amp bsp E Debug sys web gt result Fixed B E html Lic helo C fe RpPages c stubs B E html Wc RpUsrDct c webcontents B E html hello html PbSetUp txt RpUsrDct txt PBuilder pbb w 6 appconf api c ih appconf h G root c f readme Page 21 Copyright Digi International 2011 20 Build the project by right clicking on your project in the Project Explorer and selecting NET OS Build Th
16. comment tag is in bold green text lt html gt lt title gt some title lt title gt lt head gt lt meta http equiv refresh content 5 gt lt head gt lt body gt MyData script type text javascript gt var Controller Datal Controller Dpatal mm ME pu RpTextType ASCII RpGetType Direct RpGetPtr MyData gt lt RpEnd gt document write controller_Datal1 lt script gt lt br gt lt body gt lt html gt If we assume the value of MyData is 2011 the controller would serve this edited form of the file to the client with a changed JavaScript function I have shown the changes to the JavaScript in bold text lt htmT gt lt title gt some title lt title gt lt head gt lt meta http equiv refresh content 5 gt lt head gt lt body gt MyData lt script type text javascript gt var Controller_Datal Controller Datal 2011 document write Ccontroller Datal script br body lt html gt Page 43 Copyright Digi International 2011 How to Create the Most Annoying Pop up Box in History You can combine comment tags with JavaScript code to make a pop up box that is shown every time the page loads Because we have a refreshing meta tag in the HTML head element this pop up will reappear every 5 seconds Why is this interesting Our alert box is showing the value of our MyData variable JavaScript items are in bold text and the com
17. in the root c file The code below may look intimidating but we can trim that down a bit to make it easier to work with include lt stdio h gt include lt stdlib h gt include lt tx_api h gt include lt appservices h gt include lt wxroot h gt include bsp api h include bsp sys h Zinclude bsp services h include appconf h if BSP IDIGI ENABLED TRUE include netosIo h include stringUtil h include idigi api h include ssl cert h endif if BSP IDIGI ENABLED TRUE 7 thus tuncbron gets SSL Certiricates trom the fille System l 0p this function 1s able to read all SSE certiticates are in the mile system it will add all certificates in SSL Cert database and initialize cert for iDigi Device Protocol int ssl cert init void if FLASH_FILESYSTEM_ENABLED TRUE NaStatus ccode if NABspFilesystemForCLib 0 printf Please enable BSP INCLUDE FILESYSTEM FOR CLIBRARY to include SSL certificate for iDigi n else ccode sslCertificate_Init O if ccode NASTATUS SUCCESS iDigiRegisterSsICertQ else printf sslCertificate Init fails error Ox x n unsigned ccode Page 25 Copyright Digi International 2011 else printfC Please enable FLASH_FILESYSTEM_ENABLED and BSP_INCLUDE_FILESYSTEM_FOR_CLIBRARY to include SSL certificate for iDigi n endif return 0 endif this function is defined for APP_IDIGI_INIT in appco
18. n lt Digi gt n sprintf Data Buffer lt My_Datal gt d lt My_Datal gt n MyDatal strcat XML Data Data Buffer sStrcat XML Data Digi remove RAMO my data xml Delete the previous file if it exists fd open RAMO my data xml O CREAT O RDWR Create file if Cfd 0 Error handling printf C Error d Open failure FS RAMO my_data xml n getErrnoO return status write fd XML Data strlen XML Data write XML data to file if status strlen XML Data Error handling printf APP write Fail d FS RAMO my data xml 96d Nn status getErrno return status close fd close file if status 0 Error handling printf APP Failed to close FS RAMO my_data xml d n getErrno return Page 59 Copyright Digi International 2011 Now that we can create dynamic XML files in the RAM file system we only need to edit the ApplicationStart function to add a loop that periodically tweaks the value of the MyData1 variable and recreates the XML file bole applicationStart void initAppServices Init web server amp go printf Point your browser to s n APP IP ADDRESS printf serving Dynamic XML file n rd Each loop creates a new file with fresh data CreateXMLFile O Create XML file MyDatal Update MyDatal tx thread sleep 50 Rewrite file every 50 ms The Magic HTML file with Special Kung Fu JavaScript This looks alm
19. 0k 0k kk kk Ck Ck Ck Sk Ck kk Sk kk kk kk Rok ko ko oko char MyData endif RomPagerServer Which I will edit to change the MyData string Created with PageBuilder version 4 04 on Thu Jan 20 13 45 58 2011 include AsExtern h dif RomPagerServer KKK KKK KKK KKK KKK KK KKK KKK KKK KK KKK KKK KKK ko kx ko kockok po A Built from html changedata html wow C c0 kk 0k 0k 0k 0k kk kk Ck ck Ck cC 0k kk kk Sk E Sk x ko AR ko kx ko ko char MyData 50 endif RomPagerServer Page 38 Copyright Digi International 2011 Updating the root c code If we change the root c code in the applicationStart function from the previous example we can watch the value of the MyData variable change in the STDIO window in response to the changes entered by the user on the web page d applicationstart void int i 0 initAppServices Init web server amp go printf Point your browser to s n APP IP ADDRESS strcpy MyData Send some data whi 1e 1 DE i printf n n d s n i MyData Print string value tx thread sleep 1000 Yield to create a delay Note the tx thread sleep function tells the function to intelligently yield the processor to the other threads for a set number of ticks In this case the thread will sleep for 1000 ticks The number of ticks used here is not measured in milliseconds but you could adjust this to a discrete time
20. 4 new lines to the file for MyDatal MyData4 for Ci 1 1 lt 5 i sprintf Data_Buffer lt My_Data d gt d lt My_Data d gt n i MyData i 1 i strcat XML Data Data Buffer Strcat XML Data lt Digi gt Be careful not to exceed buffer size 200 char Delete the previous file if it exists remove RAMO my data xm1 Open or create file for reads or writes fd open RAMO my data xml O_CREAT O_RDWR if fd lt 0 Error handling printf C Error d Open failure FS RAMO my data xmlNn getErrno return Write XML data to file from string constant status write fd XML Data strlen XML Data if status strlen XML Data Error handling printf APP write Fail d FS RAMO my_data xm1 d n status getErrno return Close file status close fd if status 0 Error handling printf APP Failed to close FS RAMO my_data xm1 d n getErrno return Page 67 Copyright Digi International 2011 And the ApplicationStart code Mo applicationStart void MyData 0 1 MyData 1 10 MyData 2 100 MyData 3 1000 initAppServices Init web server amp go printf Point your browser to_ s n APP IP ADDRESS printf serving Dynamic XML file n Every loop creates a new file with fresh data se CreateXMLFile O MyData 0 MyData 1 MyData 2 MyData 3 tx thread sleep 475 Rewrite file every 475 ms
21. 60 variables 22 96 Breakpoints Eis Register Inspector O gt m S SY amp ti E E E Ch04 Basic Web Page Debug image elf NET OS Debug d NET OS GDB 1 21 11 9 58 AM Suspended i a Thread 0 Suspended 1 wectors 0x00004000 p Debugger Process 1 21 11 9 58 AM root c 3 include lt stdio h gt include lt stdlib h gt include lt tx_api h gt include lt appservices h gt include lt wxroot h gt include bsp api h J Tasks D Terminal 1 B Problems 3 Executables J Link GDB Server sl STDIO Serial Console 22 El Console m Serial COM1 9600 8 1 None None CONNECTED by Ek BB IS Ba fa WH ET Writable Smart Insert ig Page 24 Copyright Digi International 2011 23 In order to switch between the debugging perspective and the NET OS perspective you can click on the three icons in the tab located in the upper right corner From left to right the first Icon is the Open Perspective which you will not use the Debugger Perspective shown above and the NET OS Perspective which is where you will do the majority of your editing ES Sha Now What With the program running on your embedded device you should now be able to point a browser to the IP address of your controller to view the web page Assuming you have configured your TCP IP settings correctly in step 3 above you can now serve the basic web page with a Digi device Next we can take a look at the automatic code generated
22. ALOG APP NAME Here is a much reduced version of the root c file that is just big enough to meet our needs include lt stdio h gt include lt stdlib h gt include lt tx_api h gt include lt appservices h gt include lt wxroot h gt include bsp api h include bsp sys h include bsp services h include appconf h Dummy function as a placeholder for iDigi See APP IDIGI INIT in appconf h int app idigi init void return 0 Call while waiting for TCP IP stack Not called after stack has started ren applicationTcpDown void static int ticksPassed 0 ticksPassed Display message in STDIO indicating web page is ready Hou applicationstart void initAppservicesO Init web server amp go printf web page is active Point your browser to s n APP IP ADDRESS This shorter version of root c also works and will serve your web page without any issue TIP Do Not Choke Your Embedded Web Server Make note here that the threaded OS automatically services the web server without you having to do anything but start it up in the root c file If your web server is not responsive it may be because you are calling a blocking function or an interrupt that prevents the CPU from servicing requests for the web server Page 27 Copyright Digi International 2011 Chapter 5 Sneaky but Useful Comment Tags Digi has created HTML tags you can use within the comments of your web page that
23. Dynamic Web Pages With The Embedded Web Server The Digi Geek s AJAX Workbook NET OS XML amp JavaScript Version 1 0 5 4 2011 Page 1 Copyright Digi International 2011 Table of Contents Chapter 1 How to Usethis Guide eec ss aineena eine eo oba sei ER co eoo ease ERR EET a an pera Red des 5 Prerequisites If You Can Ping You Can Use This Thing ccccccssssccecececeesessaesesecesesseseaeeeeeeeseeeees 5 Getting Help with TCP IP and Wi Fi Setup ssssssesseeeeeeeeeneen eee en nnne netten nnne 5 The Study Guide or the Short CUt etes ertet de outer ade Pieces de aged ec aie dde aiee 5 CS acetic ae tere mieu I Ec tede ELE 6 sje 6 MUNI I 6 Provide us with Your Feedback cecscccesceesseeeesaeceeeceseeeeeesaeeeeaaeeeeaaessaeeeeaaeseeaaesseeaessaeeeeaaeeeeaaeneenenens 6 Chapter 2 The Server Client Relationship ccccccccccscssssssssecececescesecseaeeeeecessesesaeaeeeeecesseeeaeseeseseessessnaeess 7 Example An Analogy for a Normal HTML page ccccssssssccececeesesssaececeeecessesaeaececeessessenasaeeeeeeeseeees 8 TIP Auto refreshing the Page is an Option ccccccccccsssssssscecececessesesaeseeeescessesaaeeeeeesseeseaaaeeeeeesseesees 8 Chapter 3 Embedded Devices have a limited CPU budget nnns 9 Question How Much Can this Little Guy Handle
24. ML data from Scoobie Doo tag and stash it in Breed Breed xmlDoc getElementsByTagName Scoobie poo 0 chi IdNodes 0 nodevalue Now that we have the data in the program we need a method for writing it to the web page The document getElementById function lets you tuck variable information into a place on your web page that has the correct attribute ID Ihave placed the attribute ID in bold red text to make it easy to spot Write the contents of Breed at the span tag with the id Dog Breed document getElementById Dog_Breed innerHTML Breed Page 54 Copyright Digi International 2011 Adding an ID to the HTML Attributes An HTML element can have attributes An attribute is made up of a name and a value The value is in quotes Here you can see an HTML paragraph indicated by the p tag with a unique ID attribute You can add an ID attribute to any HTML element I have placed the ID attribute in bold red text to make it easy to see p id my unique paragraph id some Stuff lt p gt Attributes allow us to provide additional information about the element and we can use these as handles for plugging things into our page with XML In the HTML code for handling our XML file have included an ID using a lt span gt tag The lt span gt tag does not do anything to modify the appearance of the web page by itself Instead it provides us a convenient hook we can use to drop our data into the pa
25. a blue background lt My XML file gt lt Stuff gt lt My_File gt I am an XML File lt My_File gt Stuff Provide us with Your Feedback If there is something that e Does not work e Could be explained better e Youthink is missing e Youlike Please let us know by contacting our team at the following URL Digi Support http www digi com support Copyright Digi International 2011 Page 6 Chapter 2 The Server Client Relationship Web pages are not dynamic in nature With some clever coding we can produce dynamic behavior but first we should understand the inherent limitations of the relationship between the HTTP server and the client running a browser like Microsoft s Internet Explorer or Mozilla s Firefox HTTP Server PC Client HTML No Connection t HTTP Server PC Client HTML Client Requests HTML File Server Delivers HTTP Server Copy of HTML PC Client HTML File HTML Copy 3 HTTP Server PC Client HTML No Connection HTML Copy The important thing to notice is that there is no continuous connection between the client and the web server After the HTML page has been served we could shoot the server with a shotgun and the client would not notice because it already has the data Page7 Copyright Digi International 2011 Example An Analogy for a Normal HTML page If we pretend that am the server and you are the client we can recreate this relatio
26. ata gt lt input type text name NamerField size 32 maxlength 32 gt lt RpEnd gt To create a button for submitting the data we will use the HTML lt input gt tag again and define the type attribute to submit to create the submit button You can change the text displayed on the submit button by editing the quoted text after the value attribute Again the paired comment tags are shown in green bolded text lt This comment block configures our submit button gt lt RpFormInput type submit value Submit gt input type submit value Submit gt lt RpEnd gt Page 37 Copyright Digi International 2011 Finally the form tag must be closed and we achieve that with comment tags and a standard HTML closing tag of lt form gt lt This comment block closes the form gt lt RpEndForm gt lt form gt lt RpEnd gt With a submit button on the page any changes will be passed back to the server automatically using a get transaction when the user presses Submit PBuilder Created Files Running the HTML code through PBuilder will produce the following changedata_v c file Created with PageBuilder version 4 04 on Thu Jan 20 13 45 58 2011 include AsExtern h dif RomPagerServer Ck Ck Ck KKK KK KKK KKK KKK KKK KKK KKK KKK KKK kx ko k ko k ko kokok LEES Built from html changedata html woe CK CK Ck C CC
27. by using the NS MILLISECONDS TO TICKS macro The updated while loop might look like this whi 1e 1 i printf n n d s n i MyData Print string value tx thread sleep NS MILLISECONDS TO TICKS 1000 Yield to delay The Final Result A Web Form Interacting with our Controller 192 168 1 197 gt C fi 192 168 1 197 SA For quick access place your bookmarks here on the Other bookmarks Enter Data Send some data Page 39 Copyright Digi International 2011 Chapter 10 Detecting User Input from the Web Page With an embedded controller it is not unusual to want to trigger an interrupt service routine based on an external feedback Stub functions are user defined callback functions that are initially generated by the pbuilder utility compiling your html file Digi s Advanced Web Server will automatically call the stub function associated with a value on your web page when that value changes In order to demonstrate this we can use the same HTML code with the Submit button as before have named this file trigger cb html and have left the comment tags in green bold letters lt html gt lt title gt some title lt title gt lt head gt lt head gt lt body gt lt This comment block sets up our form to pass data with a post gt lt RpFormHeader method get RpNextPage Pgformsubmi tted gt lt form action formsubmitted html method get gt
28. cationStart code we configure the switch and then poll the value and write the XML file in a loop a applicationstart void int result 0 Store return value from GPIO configuration initAppServices Init web server amp go printf Point your browser to s n APP IP ADDRESS printf serving Dynamic XML file n Configure the IO Pin as input result NAconfigureGPIOpin APP INPUT PIN NA GPIO INPUT STATE 0 if Cresult 0 printf NAconfigurecGPIOpin failure d n result Every loop read switch and create a new file with fresh data while 1 NAgetGPIOpin APP_INPUT_PIN amp Switch 1 Read input amp store value in Switch 1 CreateXMLFile O Write an XML file tx thread sleep 475 Rewrite file every 475 ms Page 75 Copyright Digi International 2011 The JavaScript Code Our JavaScript program should merely be a variation on what we have already done In this case am skipping the buffer variable in order to assign the ID attribute to the value from the XML tag in a single statement I have placed the single line of code that assigns the value in bold text script type text javascript function loadxMLDoc dname Magic function creates a local copy of XML if window XMLHttpRequest Create local XML document xhttp new XMLHttpRequest else Use for older browsers xhttp new Activexobject Microsoft XMLHTTP Request the XML file from server with GET xhttp open GET
29. e ette he ned tidie aene 64 Looking atthe Page gd Re e RR GHI NI 65 Using a JavaScript Loop to Pass Dynamic XML Data in Real Time cccccessssecececeseessstaeeeeeeeseesees 66 gue pn LEE 66 Page 3 Copyright Digi International 2011 The Amazing JavaScript Program cccsccccccscsssessssesececessesesssaeeesecesseseeaeeeeeesessseeaseseeeesseeseensaeseeeeesesees 69 The HIME BOY itte eee eerte ette ied tene Mtem reete ca oa een ate 70 Watching it All WOrk eevee nite ive ee ee ee eet teta i ee NINE 70 Want more ierit reete pe eie FRE nter P HAE e ee ar desde e arae AATE aeaa Eaa Aaaa aani EEEH E deeds 72 Chapter 15 Dynamic Web Interface to Hardware in Real Time cccsssccccccessesssnsaeeececeseesesneaeeeeeeeseesees 73 A Simple XML file for Our Little Switch useesesesseseseseeee nennen nnne nnne nnn nnns nnn nean 73 Editing the CreateXMLFile Function esses eene enhn enhn enhn seen nh nn sinn nh rase ninis 74 Tie Javascript Codes et tec te eco ta eis mes ave cu e a etas eie ated ttn 76 The HTML BOG s Ai eet he o hin n 76 How Does it Look rei xai e ete e ne i e en Dis val accu ena chides Tape e eaaa aches 77 Page4 Copyright Digi International 2011 Chapter 1 How to Use this Guide This Guide is not a user s manual in the traditional sense Instead it is an informal workbook for a variety of different embedded web server projects Sample Code for this Guide can be found
30. e fron jild E readme 4 NET 05 Build amp NET 05 ReBuild NET 05 MIB Compiler PEuilder Build Configurations d Index gt Show resource in Windows Explorer Convert To NET OS Debug Team Compare With d Restore from Local History Properties Alt Enter Page 23 Copyright Digi International 2011 22 When the debugger starts it will switch the GUI to the debugger view On the upper left side you will see the program s threads display as well as a series of buttons that resemble the controls on a DVD player The debugger will automatically insert two break points into your code and will pause at each one to wait for you to press the green play button In the image below the debugger is waiting for the user to press the green play button shown in the Debug tab o gt When the button is pressed once you will see information scrolling through the bottom window in the STDIO Serial Console tab There will be a planned pause for 5 seconds as the program waits to see if you want to change any settings After the pause execution will continue until you hit the second break point Press the green play button again and your program will execute and continue running freely EsP Debug ChO4_Basic_Web_Page root c Digi ESP for NET OS C Documents and Settings pcurti iA DEAR File Edit Refactor Navigate Search Run Package Manager Project Window Help ri M v 4 e8 ES Ey 9 59 o Debug p A
31. eate an XML file for my switch The only real change is that am using an if statement to write text to the XML file instead of an integer youd CreatexXMLFile void Char XML_Data 500 XML data buffer char Data Buffer 100 Buffer for MyData variable int status Return value for write amp close int fd File descriptor populated by open Create formatted XML string to write to file strcpy XML Data XML File gt n lt Digi gt n Begin file Create line for Switch 1 if Switch 1 1 sprintf Data Buffer switch 1 0FF Switch 1 Xn else sprintf Data Buffer Switch 1 0N Switch 1 X5n strcat XML Data Data Buffer sStrcat XML Data lt Digi gt Delete the previous file if it exists remove RAMO my data xm1 Create the file for reads or writes fd open RAMO my data xml O CREAT O RDWR if fd lt 0 Error handling printf Error Xd Open failure FS RAMO my data xml Nn getErrno return Write XML data to file from string constant status write fd XML Data strlen XML Data if status strlen XML Data Error handling printf APP write Faile d FS RAMO my data xml 9 d Nn status getErrno return Close file status close fd if status 0 Error handling printf APP Failed to close FS RAMO my_data xml d n getErrno return Page 74 Copyright Digi International 2011 In the appli
32. eated by PBuilder will initially look like this Created with PageBuilder version 4 04 on Thu Jan 20 13 25 14 2011 include AsExtern h fif RomPagerServer 7 Yee ge yegygygxx ii ie eeeg bul lt from html showdata html 7 Signed16 MyData 0 char MyString endif RomPagerServer have edited the showdata_v c file to define my variables as an integer and an array of characters with fifty elements Page 31 Copyright Digi International 2011 Created with PageBuilder version 4 04 on wed Dec 15 13 30 26 2010 include AsExtern h fif RomPagerServer qe eee ee eee eX ct KAK Ka T Built from hn yshoudata hem D See oo GG and honat html for usage int MyData 0 Edited to change Unsignedl6 type to int char MyString 50 Edited to set size Zendif RomPagerServer The root c Code The code in root c below demonstrates how to set the variables This is a stripped down version of root c created just as we did in Chapter 4 include lt stdio h gt include lt stdlib h gt include lt tx_api h gt include lt appservices h gt include lt wxroot h gt include bsp api h include bsp sys h Zinclude bsp services h include appconf h web variables defined in web result stubs html showdata v c file extern int MyData extern char MyString 50 Dummy function as a placeholder for iDigi See APP IDIGI INIT in appconf h i
33. en we will place the file in FS RAMO dogs xml directory by using RAMO dogs xml as the filename Here we can omit the FS which is the root directory and stands for file system The open function returns a file descriptor that am storing in the fd variable which we can use to write to the file later Open or create file for reads or writes fd open RAMO dogs xml O CREAT O RDWR Page 49 Copyright Digi International 2011 Next we will write our string constant to the data file with the write function by passing in the file descriptor fd and the string constant XML Data and the length of the data we want to write write XML data to file status write fd XML Data strlen XML Data Finally we will close the file using the close function and the file descriptor fd Close file status close fd If we assume my web server has an IP address of 192 168 1 197 should be able to access the XML file from a browser by typing the following URL into my browser http 192 168 1 197 FS RAMO dogs xml http 192 168 1 197 FS RAMO dogs xml Internet Explorer optimized for Bing and MSN Ge jw http jji92 168 1 197 FS RAMO dogs xml Y El 4r X S sn s File Edit View Favorites Tools Help T z gt vy Favorites 8http 192 168 1 197 F5 RAMOsdogs xml fe 8 mm Page Safety Toos amp l My XML fi
34. end Send request without extra data return xhttp responseXML Return the local copy Page 53 Copyright Digi International 2011 The Primary JavaScript Function function Get Dog Tags Function to get XML place it in the HTML page var Breed This optional buffer makes the code easier to read xmlDboc loadXMLDoc FS RAMO dogs xml Creates a local copy of XML Get the XML data from Scoobie Doo tag and stash it in Breed Breed xmlDoc getElementsByTagName Scoobie_Doo 0 childNodes 0 nodevalue write the contents of Breed at the span tag with the id Dog_Breed document getElementById Dog_Breed innerHTML Breed Breaking down the Scary Looking JavaScript HTML DOM First we are going to store the breed of the dog in a JavaScript variable If we wanted to manipulate the data with our JavaScript code this is useful If we just want to output the data we might not need this variable var Breed This optional buffer makes the code easier to read Next will call my magic function to go get my XML data and store it into my xmlDoc buffer We already described how this function works earlier xmlDoc 2loadXMLDoc FS RAMO dogs xml Creates a local copy of XML With the XML file loaded we can use the XML tag to latch onto a key piece of data by specifying the tag name I have placed the unique XML tag in bold blue text to make it easy to spot Get the X
35. ere are many different ways to select the Build option within the GUI including the toolbar and the main menu HA Archives a y Indudes Open in New Window W E bsp H E Debug Copy Ctrl C H E sys f Paste trl4 g er web J Delete Delete S result d Fixe l B Q stu Rename F2 dy Import amp Z3 Export t 8 LI Exp 8 B Build Project webcor Clean Project EN F E PBuilde 5 Refresh F5 8 appconf a Close Project lh appconf h a Unrelated 7 E 6 root c E readme Exclude From bui NET OS ReBuild NET OS MIB Compiler E PBuilder Build Configurations gt Index d lay Show resource in Windows Explorer Convert To 355 NET OS Debug Team gt Compare With Restore from Local History Properties Alt Enter Page 22 Copyright Digi International 2011 21 Run the debugger for your project by right clicking on your project in the Project Explorer and selecting NET OS Debug There are many different ways to select the Debug option within the GUI including the toolbar and the main menu H H Archive iiid S Include Openin New Window H E bsp amp G Debug B Copy Ctrl C B E sys Ug Paste SER EG web Delete Delete res ae Rename F2 ae E gxg Import t Export I Build Project wel Clean Project E PBL Refresh FS E appcon Close Project n appcon la Ea d root c A clud
36. es bsp H E Debug sys S web e 3 6 webcontents 2 html PbSetUp txt RpUsrDct txt 5 PBuilder pbb fe appconf api c n appconf h i root c Ej readme 12 Right click on the web webcontents html directory and select New and then File to add a web page to the directory m Jl root c 3 ggg sinciude lt stdio h gt 3 i a Ch4 Basic Web Page include stdl ib h P Binaries include tx api n gt i A Archives include lt appservices h gt 5 AN Includes include lt wxroot h gt bsp include bsp api h E E Debug include bsp sys h H E sys include bsp services h S web include appconf nh result Call while waiting for TCP IP stack Not called void applicationTcpDown void e A i PbS F3 Project B webcontents Rpu E PBuilder p Bi Fie appconf_ap ES Copy Ctrl C C9 Folder e R appconf h f paste Wa E Header File amp Le i E Bp X Delete Delete 1B NET OS Platform Project id Move E NET 05 Project Rename F2 fe NET 05 Sample Project Sin SE NET OS Tree Project mport ef Source File L Export Other Ctrl N Refresh F5 ri Exclude from build Index gt Build Configurations id ay Show resource in Windows Explorer Team gt Compare With Restore from Local History Properties Alt Enter Page 15 C
37. firmware htm html reboot htm html reboot status htm html filelist htm html cwm connections config htm html cwm advanced config htm html cwm certificate config htm help cwm config help htm mesh mesh config htm mesh mesh legacy serial config htm mesh mesh zigbee advanced config htm mesh mesh zigbee config htm mesh mesh zigbee config table htm mesh mesh network view htm mesh mesh device state htm mesh mesh fw update htm css stylesheet css img logo gif img back gif img back off gif img forward gif img forward off gif img tabclose gif img tabopen gif img help gif scripts errhandler js scripts utils js scripts validation js Here is the updated PBuilder pbb file htmT heTTo htmT Reminder Ensure that the PBuilder pbb file has one and only one carriage return following the final line Page 19 Copyright Digi International 2011 18 Next run the PBuilder utility by right clicking on the name of your project and selecting PBuilder from the list of options If you run PBuilder without deleting the old files you can make use of the merge utility to combine the old file and the new one For more information about the merge utility consult the NET OS documentation Ctrl C tre Delete F2 Build Configurations Index e H Binaries ij 8 Archives m Ail Includes Open in New Window i bsp BB copy H E Debug E E sys UE S x uet XX Delete
38. g RpEnd o RpSetType specified as Direct indicates that we are directly referencing the memory location of the data by the variable name indicated by the next tag RpSetPtr o RpSetPtr is a pointer to the name of the variable on the controller and works like a pointer to the data o RpEnd is a closing comment tag paired with the opening tag RpFormlnput As the comments in the snippet indicate there is more that must be done before this is working code but for now it provides us an understanding of how to pass information back and forth between the browser and the server Remember that the RpSet comment tags will send information from the browser to the embedded controller For more information on how to use the RpDisplayText comment tag consult the Advanced Web Server Toolkit manual located by default in the C netos75 Documentation directory Page 29 Copyright Digi International 2011 Chapter 6 Introducing Stub Functions Beyond reading or changing values on the controller you can also reference callback functions called Stub Functions to handle tasks related to your web page Instead of using the Direct keyword with the RPGetType and RpSetType comment tags to reference memory locations directly you will use the Function keyword to reference a stub function htmT lt title gt some title lt title gt lt head gt lt head gt lt body gt lt more stuff up here having to do with forms gt lt This c
39. ge using the ID attribute Here is a span tag with the ID attribute in bold red text to make it easy to see span id Dog_Breed gt lt span gt If wanted to directly set the value between my two span tags to Some Dog I could use the following JavaScript statement document getElementById Dbog Breed innerHTML Some Dog By using our Breed JavaScript variable we can set this value with data from the XML file Write the contents of Breed at the span tag with the id Dog Breed document getElementById Dog Breed innerHTML Breed We could skip the Breed variable completely and use a single line of code to assign the XML data to the ID attribute just as easily if we wished This line of code assigns the value directly without any buffer variable document getElementById Dbog Breed innerHTML xmlDoc getElementsByTagName Scoobie Doo 0 chi TdNodes 0 nodevalue chose to break this single line up because it is easier to read and explain if we take it in smaller steps Page 55 Copyright Digi International 2011 The HTML body that works with the JavaScript Program body lt b gt what Kind of Dog is Scoobie Doo lt b gt lt p gt Scoobie Doo is a span id Dog_Breed gt lt span gt lt p gt lt p gt lt button onclick Get_XML_Dog gt Snag an XML Dog Tag lt button gt lt p gt lt body gt In the body of the HTML the
40. gi devices usually have access to a push button switch on the prototyping board To configure a Digital input two steps are required e Configure the pin as an input e Read the pin If we assume have access to a switch on pin 81 we can configure the pin with this statement NAconfigureGPlOpin 81 NA GPIO INPUT STATE 0 The first parameter is the pin number the second is a macro for setting it up as an input and final parameter is the desired initial state If we assume have created an integer named Switch 1 we can read the value of the switch with this statement NAgetGPlOpin 81 amp Switch 1 The first parameter is the pin number the second is the variable where want to store the result We can then use the same method as before to create a dynamic web page to display the status of the hardware A Simple XML file for Our Little Switch Here is our dynamic XML file where have placed a zero to represent the current value of the switch lt XML File Digi Swi tch1 0 Swi tch1 Digi Page 73 Copyright Digi International 2011 Editing the CreateXMLFile Function First will create a macro for my input pin and a global variable for the current switch data define APP INPUT PIN 81 This is switch S6 on my development board unsigned int Switch 1 0 Dynamic data for XML file global Next will update the CreateXMLFile function to cr
41. hat tricks the cache and we get the current version of the XML file rather than using one stored locally When you are using an XML file that changes dynamically this is important to ensure that your browser gets the fresh data Request the XML file from server with GET xhttp open GET dname t Math randomQ false Request the XML file from server with POST xhttp open POST dname t Math random false Note Some web browsers will not need the random number trick and automatically request the file from the server If your application never uses one of these browsers you could call the same function without the random number trick like this Request the XML file from server with GET xhttp open GET dname false Request the XML file from server with POST xhttp open POST dname false If your XML file is very large you may want the JavaScript code to wait until the XML file is completely loaded You can make the JavaScript program wait for the file to load by specifying that you do not want an asynchronous load By passing in the false parameter you can load the XML file into your xhttp object and the program will wait for you to finish before it continues execution un The send function sends the request to the server and the empty quotes tell us we do not want to send any data with the request Finally we pass our XML data back out of the function xhttp s
42. here Prerequisites If You Can Ping You Can Use This Thing This guide is not intended to teach a user basic Internet and TCP IP networking skills In order to use the information in this guide you should be able to configure your Digi device for your network so that you can ping it with a PC connected to the same network Getting Help with TCP IP and Wi Fi Setup You have plenty of options if you need to get help with basic TCP IP and Wi Fi 1 Anonline TCP IP Tutorial http www w3schools com tcpip default as 2 Digi has a guide for Wi Fi available here 3 In addition your device s user manual should have a chapter dedicated to TCP IP and networking The Study Guide or the Short Cut The chapters build on each other and one good approach would be to work from the beginning of the workbook to the end as a learning experience Another equally valid approach would be to scan the chapter headings to find something similar to your project and use the example there as a starting point Page 5 Copyright Digi International 2011 C Code A text box containing code written in C will have a gray background void some function printf I am C code n HTML Code A text box containing HTML code will have a light green background html lt title gt some title lt title gt lt head gt lt head gt lt body gt I am HTML Code lt body gt lt html gt XML File A text box containing XML will have
43. i embedded computer serve interactive web pages with an ARM processor Answer Quite a Bit Just looking at the example web pages served by the Digi devices will show you a collection of cascading style sheets JavaScript files and more You will probably be surprised by how much performance you can get out of an embedded web server Page 9 Copyright Digi International 2011 Chapter 4 Serving a Basic Web Page Serving a web page with Digi Embedded devices is very easy Here is an example of a simple web page The page should generate the following in the browser Hello World How can we serve this page with a Digi Embedded device running NET OS Prep Work Building a Project Tweaking Files and PBuilder Starting from a fresh project here are the steps required using NET OS version 7 5 1 Open a new NET OS project by selecting File gt New gt NET OS Project from the main menu This will load the NET OS Project window ese NET OS Project Create NET 0S Project Select values for your NET 05 project Project Name Ch4 Basic Web Pagel NET OS Version z s Platform ConnectCore wi 9P 9215 Debugger Digi JTAG Link Page 10 Copyright Digi International 2011 2 Enter a name for your project select your version of NET OS your hardware and click Next 3 The Network Configuration window will be displayed Configure your TCP IP connection and select Next
44. le gt Famous Animals lt Dogs gt Scoobie Doo Great Dane Scoobie Doo lt Lassie gt Collie lt Lassie gt Rin Tin Tin German Shepherd lt Rin_Tin_Tin gt lt Stimpy gt Chihuahua lt Stimpy gt lt Dogs gt lt Famous_Animals gt Internet This demonstrates that the device can serve up an XML file in a way that makes some sense to the browser Now we need a web page that can do something with it Page 50 Copyright Digi International 2011 Putting together JavaScript Code to Read your XML data Different browsers will handle an XML file in different ways but the process will break down into five basic steps Create a local XML document Do you want your read to be synchronous or asynchronous Get the XML file from the server and store the contents in your local version Grab a specific piece of data from the file Ur de Qu ME ga Do something with that data like show it in your web page Scary Looking JavaScript Code have put together a small HTML file with JavaScript code to access the dogs xml file This may look intimidating so we are going to break it down piece by piece You will notice the XML tag in bold blue text and the ID attribute referenced in bold red text The Magic Go Get My XML File Function Inside the head section of the HTML file we are going to write two functions e The first function will be a generic and reusable function to create a local XML document and then po
45. lt htm1 gt lt title gt some title lt title gt lt head gt lt meta http equiv refresh content 5 gt lt head gt lt body gt lt Display a 16 bit signed value gt My Data 2009 lt br gt lt Display a string gt My String Output String br gt lt body gt lt html gt Page 34 Copyright Digi International 2011 And the browser will display this My Data 2009 My String Output String The page will still refresh every 5 seconds and the controller will still send a copy of fresh data even if it has not changed If we assume that after 5 seconds the value of MyData has changed to 1967 the file will change showing the new I have placed the updated data in bold text If the value on the controller has changed when the page refreshes it will display new data like this My Data 1967 My String Output String Page 35 Copyright Digi International 2011 Chapter 9 Interactive Web Pages Made Easy Displaying data is great but in order to use a web page as a user interface we need the ability to both display and change data from the web page Fortunately we can do this with RpSet tags Here is a simple web page called changedata html with comment RpSet tags included that point back directly to the C variables Adding an HTML Form and a Submit Button We will create a variation of our web page with a form and a Submit button added You will see the
46. ment tags in bold green text htmT lt title gt some title lt title gt lt head gt lt meta http equiv refresh content 5 gt lt script type application x javascript gt function disp alert alert My Data ds Ee RpTextType ASCII RpGetType Direct RpGetPtr MyData lt RpEnd gt lt script gt lt head gt body onload disp_alertQ gt lt body gt lt html gt If we assume the value of MyData is 2011 the controller would serve this edited form of the file to the client with a changed JavaScript function I have shown the changes to the JavaScript in bold text htmT lt title gt some title lt title gt lt head gt lt meta http equiv refresh content 5 gt script type application x javascript function disp alert alert My Data 2011 lt script gt lt head gt body onload disp alert body lt html gt Page 44 Copyright Digi International 2011 The Annoying Pop up Box The page at http www w3schools com says fx My Data 34180 5 This Pop up is guaranteed to be terribly annoying but it is also terribly interesting to see data from the controller appear in the alert box of your browser Saving the Annoying Pop Up Box With a little more work we might be able to make this more useful by including a JavaScript if statement to qualify when the pop up occurs htmT lt title gt s
47. n on Switch 1 on the prototyping board 192 168 1 197 C fi 192 168 1 197 Yr 4 For quick access place your bookmarks here on the bookmarks bar I Press Switch 1 on the Protoboard C Other bookmarks Switch 1 OFF Start Dynamic Data Page 77 Copyright Digi International 2011 When I press down on the switch on the prototyping board the continuously refreshing stream of XML data updates the data on the web page to show the change 7 192 168 1 197 C fi 192 168 1 197 Yr 04 For quick access place your bookmarks here on the bookmarks bar I CJ Other bookmarks Press Switch 1 on the Protoboard Switch 1 ON Start Dynamic Data Page 78 Copyright Digi International 2011
48. ne 51 The Primary JavaScript FUNCOM Ase aaee raa tI aa teres ete EU IEEE e EMT E AY RENE EREN 54 Breaking down the Scary Looking JavaScript HTML DOM ccsccccccecesesssnseceeeeecessesseaeeeeeeeseeeees 54 Adding an ID to the HTML AttribUtes cccccssccccccecssssssseeececesseseseaeeeeeessessnasaeseeeeeseensasaeeeeeeesseees 55 The HTML body that works with the JavaScript Program esses enne 56 Updating the root c Code eee tet ec estere re esee e etes taret umen 56 Let s See the Dog Tags Workl eor Rote RT RI RE E ER d TUE een 57 Where is the Magic AJAX arrene renna aerarii aand enne en nennen nennen n a aaar a a aaaea aaa riranki 57 Chapter 13 Embedded devices and XML The Holy Grail of Embedded Web Developers 58 The Teeny Tiny and yet Magical my data xml file esses 58 Updating the root c Code i siete e tem es d A 59 The Magic HTML file with Special Kung Fu JavaScript essere 60 The Magic Page in Action ire eae P ER GI 61 Isthis Really Magie ire eene det ei UE AU ies RE E Passa 62 Chapter 14 Loopy JavaScripts irc tee ettet mette e eee edwin 63 The Joy of the setTimeout Function eese eene ARA EE ANE EAE EA 63 Easy setTimeout Function Example csinos En ASARANA EA S EEE PA TARTA 63 Using the setTimeout Function to create an Infinite Loop sssseeseseeeeeeeeenn nennen 64 Exiting the LOO Dis e
49. nf h and is called by BSP to initialize the command callback function int app_idigi_init void if BSP IDIGI ENABLED TRUE ssl_cert_initQ endif return 0 Sy Function void applicationTcpDown void Description This routine will be called by the NET OS root thread once every clock tick while it is waiting for the TCP IP stack to come up This function can increment a counter everytime it s called to keep track of how long we ve been waiting for the stack to start If we ve been waiting too long then this function can do something to handle the error This function will not be called once the stack has started Parameters none Return Values 5 none a us applicationTcpDown void static int ticksPassed 0 ticksPassed E Code to handle error condition if the stack doesn t come up goes here 7 Function void applicationStart void Description n This routine is responsible for starting the user application It should a create any threads or other resources the application needs 55 ThreadX the NET OS device drivers and the TCP IP stack will be running when this function is called Parameters i none Return Values us none cay Page 26 Copyright Digi International 2011 a applicationstart void A Tictalize the system Services for the application initAppServices Code to start the user application goes here printf Hello world s Ready n APP DI
50. nship 0 You are in your car and am home watching my TV No connection between client and server 1 If you want directions to the pizza parlor you call me Client requests data 2 tell you how to get there Server supplies data 3 We hang up No connection between client and server 4 You get there but now you cannot find the parking so you call me back Client makes new request for data 5 tell you where to park Server supplies data 6 Wehang up No connection between client and server The key concept here is that there will be no fresh data without a new request to the server This is how a web server typically works An easy way to demonstrate this is to load a web page and then unplug your PC s Ethernet cable The web page will not notice that it does not have access to the web server anymore because it has already been loaded Later we will see that web pages can execute programs that change this behavior TIP Auto refreshing the Page is an Option With a bit of HTML code in the head element you can have the page automatically refresh itself in a given time interval lt head gt lt meta http equiv refresh content 300 gt lt head gt The value in quotes after the content attribute is the number of seconds until the page automatically refreshes itself If you want a different time interval we could change the value of content in our refreshing meta tag This example would refre
51. nt app idigi init void return 0 Call while waiting for TCP IP stack Not called after stack has started vole applicationTcpDown void static int ticksPassed 0 ticksPassed Display message in STDIO indicating web page is ready ae applicationStart void ini tAppServices Init web server amp go printf Point your browser to s n APP_IP_ADDRESS strcpy MyString Output Data Set MyString variable Le MyData Tweak the value of the MyData variable Page 32 Copyright Digi International 2011 With these Pbuilder files created and root c tweaked we can now serve fresh data from the controller to the page If the MyData integer variable is equal to 2009 on the embedded device and the MyString string variable is equal to Output Data the web server will automatically edit the HTML file before it is served to a browser I have shown the new data in bold text The page generates the following in the browser My Data 2009 My String Some String If the data changes on the embedded controller you will need to manually reload the page in order to see the new data displayed in the browser Page 33 Copyright Digi International 2011 Chapter 8 Our First Dynamic Web Page In order to show new data we can include a meta tag to request that the page automatically reload This has the advantage of being very easy to do with a single line of HTML code in the head element of the
52. o Great Dane c Scoobie Doo lt Lassie gt Collie lt Lassie gt lt Rin_Tin_Tin gt German Shepherd lt Rin_Tin_Tin gt lt Stimpy gt Chihuahua lt Stimpy gt lt Dogs gt lt Famous_Animals gt Each defined tag must have a closing tag with a like this lt my_nifty_xml_tag gt some nifty data lt my_nifty_xml_tag gt With this understanding we can add an XML data file into our embedded web server by creating it in the embedded device s RAM file system Copyright Digi International 2011 Page 47 Here in root c we define the contents of our XML file with a string constant include include include include include include include include include include include String lt stdio h gt lt stdlib h gt tx api h lt appservices h gt lt wxroot h gt fs api h bsp api h bsp sys h bsp services h appconf h netosIo h constant to place in file created in CreateXxMLFile function below const char XML Data l My XML file gt n lt Famous_Animals gt n lt Dogs gt n lt Scoobie_Doo gt Great Dane lt Scoobie_Doo gt n lt Lassie gt Col lie lt Lassie gt n lt Rin_Tin_Tin gt German Shepherd lt Rin_Tin_Tin gt n lt Stimpy gt chi huahua lt Stimpy gt n lt Dogs gt n lt Famous_Animals gt n Dummy function as a placeholder for iDigi See APP_IDIGI_INIT in appconf h int app_idigi_init void return
53. ome title lt title gt lt head gt lt meta http equiv refresh content 5 gt lt script type x LUE javascript function disp alert var alarm flag lt RpDi 2 ayText RpTextType ASCII RpGetType Direct RpGetPtr MyData lt RpEnd gt if alarm flag 1 alertC ALARM lt script gt lt head gt lt body onload disp_alertQ gt lt body gt lt html gt If I encounter an alarm condition can set the MyData variable to 1 and my pop up box will trigger when the page reloads with the refreshing meta tag htmT lt title gt some title lt title gt lt head gt lt meta http equiv refresh content 5 gt lt script type PELOTER javascript gt function disp_alert var alarm flag 1 ni alarm flag 1 alert ALARM Page 45 Copyright Digi International 2011 With just a bit of imagination you can do almost anything Page 46 Copyright Digi International 2011 Chapter 12 Basic XML with the Digi Embedded Web Server XML is a method of transmitting and presenting data in an organized way It uses XML tags the same way you or might use the handles on a suitcase to grab onto it If you know the XML tag you can get to the data very easily and the best thing is you will create your own tags for your file I have put the data in bold text For example lt My XML file gt Famous Animals Dogs Scoobie Do
54. omment block configures our form and what variables we will use gt lt RpFormInput type text name NameField size 32 maxlength 32 RpGetType Function RpGetPtr GetMyData RpSetType Function RpSetPtr SetMyData gt lt input type text name NameField size 32 maxlength 32 gt lt RpEnd gt lt more stuff down here having to do with forms gt lt body gt lt html gt After running the web page through the Pbuilder utility empty placeholder functions will be created for your project in the web gt result gt stubs gt html folder In this example have added some minor functionality to each of the functions We will create a working sample with a stub function later after we try working with more basic examples Created with PageBuilder version 4 04 on Mon Dec 20 11 10 27 2010 include AsExtern h fif RomPagerServer Jes eR KR ekk LE E d Built from n html trigger _ lt cb html a as 2 exteri T MyData 50 D EIER in Web eS TE UE Sane neni CO DTSUDII Ee dE V C extern char GetMyData void da GetMyData void return MyData extern void x np har thevaluePtr oe SetMyData c thevaluePtr strcpy MyData thevaluePtr return endif RomPagerServer Page 30 Copyright Digi International 2011 Chapter 7 Using Comment RpGet Tags with a Basic Web Page Create a new project using the steps described in Chapter 4 or edit the existing project
55. opyright Digi International 2011 13 Name the file and select Finish ES New File File Create a new file resource Ch4 Basic Web Page web webcontents html Page 16 Copyright Digi International 2011 14 To edit the HTML file right click on it in the Project Explorer and choose Open With Text Editor gt root c 38 N E include lt stdio h gt include lt stdlib h gt E Ch4 Basic Web Page GE Binaries ginctuas bin ARE RE A Archives pele lt appservices h gt Includes pneeeee SEGOE NP amp bsp include bsp_api h H E Debug include bsp sys h HS sys include bsp services h 3 6 web include appconf h amp result o webcontents d bonga while pinata for bath stack N Sc html void applicationTcpDown void gpm Pbsety Me MEN gt Bd 0 RpUsrl Open PBuilder pt Q Web Browser w d appconf api c E A root c Paste Ctrl System Editor readme X Delete Delete In Place Editor Move Default Editor Rename F2 Other Import e Export Refresh F5 ag Show resource in Windows Explorer Clean Selected File s Build Selected File s Team Compare With Replace With Properties Alt Enter Exclude from build Build Configurations Page 17 Copyright Digi International 2011 15 Create your HTML file in the editing window and save it ese NET OS Ch4 Basic Web Page web
56. ost the same as the previous HTML file You will notice the XML tag in bold blue text and the ID attribute referenced in bold red text lt html gt lt title gt some title lt title gt lt head gt script type text javascript function loadXMLDoc dname Magic function creates local copy of XML file if window XMLHttpRequest Create local XML document xhttp new XMLHttpRequestQ Tise Use for older browsers xhttp new Activexobject Microsoft XMLHTTP Request the XML file from server with GET xhttp open GET dname t Math random false xhttp send return xhttp responseXML Return the local copy function Read XML File var XML Data This optional buffer makes the code easier to read xmlDoc loadXMLDoc FS RAMO my data xml Create local copy of XML data Store the value of My Data tag in the XML Data variable XML Data xmlDboc getElementsByTagName My Data 0 childNodes 0 nodevalue Write the contents of the buffer variable at the span tag with the appropriate id document getElementById My Data ID innerHTML XML_Data script head body lt p gt lt b gt My_Datal lt b gt lt span id My_Data_ID gt lt span gt lt p gt button onclick Read_XML_FileQ gt Get XML lt button gt lt body gt lt htm1 gt Page 60 Copyright Digi International 2011 Each time the user clicks the Get XML button it will trigger a call
57. ox File Edit View History Bookmarks Tools Help m Q X da O htt siit92 168 1 196 B Most visited V Gmail Hotmail News Ai Latest Headlines W Wikipedia Dynamic XML Test My Datal 3150 My Data2 3159 My Data3 3249 My Data4 4149 Every 500 milliseconds it will continue to update automatically without any button presses Mozilla Firefox File Edit View History Bookmarks Tools Help lt C X d L ihttp y192 168 1 196 LE Most visited IM Gmail A Hotmail A News 3 Latest Headlines W Wikipedia Dynamic XML Test My Datal 24354 My Data2 24345 My Data3 24255 My Datad4 23355 Copyright Digi International 2011 Page 71 And again Mozilla Firefox File Edit View History Bookmarks Tools Help Q X d http it192 168 1 196 B Most visited V Gmail Hotmail News 3x Latest Headlines W Wikipedia Dynamic XML Test My Datal 31090 My Data2 31099 My Data3 31189 My Data4 32089 Get XML Want more With the ability to swap data in real time with your embedded controller you have the potential to create dynamic charts graphs and other animations with Flash or extensions to the JavaScript language like the Yahoo User Interface and Canvas Page 72 Copyright Digi International 2011 Chapter 15 Dynamic Web Interface to Hardware in Real Time The next natural step is to move from an abstract variable like My Data to a value defined by the hardware itself Di
58. passing in the name of the XML file in the beginning of the function like this function loadXMLDoc dname That allows us to use the same function to request any XML file from the server by calling my loadXMLDoc function with different files and stashing the result in a local variable myXMLData loadXMLDoc FS RAMO dogs xm1 SomeXMLStuff loadXMLDoc FS RAMO my data xm1 LocalXML loadXMLDoc FS RAMO my xm1 xm1 Next we need to have a plan for handling different web browsers If we are using a newer browser our local XML buffer called xhttp will be created by this code If we are running an older browser this if statement will fail and return a false value moving us onto the next option if window XMLHttpRequest Create local XML document xhttp new XMLHttpRequest The older browsers will be handled by our else statement Here we try creating the local version again using an older method for Microsoft s Internet Explorer versions 5 and 6 else Use for older browsers xhttp new ActiveXobject Microsoft XMLHTTP Page 52 Copyright Digi International 2011 To actually retrieve the XML data we will use the open function The open function requires you to list your method GET or POST shown here the URL and then choose false or true have added a small trick that ensures that each GET request has a unique URL by adding a random number at the end T
59. press is interesting but it would be more impressive to continually refresh the data behind the scenes with an infinite loop JavaScript has a mechanism for this called a timing event The Joy of the setTimeout Function The setTimeout function can be used to execute a JavaScript function after an interval has expired It accepts two parameters 1 AJavaScript statement 2 Atime interval in milliseconds The function returns a unique ID number that will allow you to shut down the timed process You can think of this as a way of putting a C code style break into your infinite loop as an escape hatch A call to the setTimeout might look like this var t setTimeout c c 1 5000 increment c in 5 seconds Easy setTimeout Function Example Here is a short HTML file that uses the setTimeout Function to display an alert box 5 seconds after the user presses a button on the web page Page 63 Copyright Digi International 2011 Using the setTimeout Function to create an Infinite Loop A more interesting construction would be to use setTimeout to call another function in an infinite loop Here we are using the same ID attribute from the previous examples as a mechanism for creating an infinite loop that continues to update the value of the c variable as displayed on the web page twice per second lt htm1 gt lt title gt some title lt title gt lt head gt i A lt script type text javascript gt var c 0
60. pulate it with data it gets from the server e The second function will walk through our local copy of the XML file to get some data and then place it into the body of the HTML page htmT lt title gt some title lt title gt lt head gt script type text javascript gt The magic function to request an XML file and return a local copy function loadXMLDoc dname if window XMLHttpRequest Create local XML document xhttp new XMLHttpRequest else Use for older browsers xhttp new Activexobject Microsoft XMLHTTP Request the XML file from server with GET xhttp open GET dname t Math random false Request the XML file from server with POST xhttp open POST dname t Math random false xhttp send return xhttp responseXML Return the local copy Page 51 Copyright Digi International 2011 In this document am going to treat the complicated topic of the HTML Document Object Model DOM as we would a hammer am going to show you a basic method of using these tools but am not going to get into extensive detail about what makes them work If we use the hammer analogy we are interested in hitting our nails into a board but we do not need to know equations for kinetic energy or how Newtonian physics explains a lever If you want more information on HTML DOM you can find a tutorial here http www w3schools com htmldom default as You should notice that we are
61. re are two lines that are important The first is our lt span gt tag with its ID attribute lt p gt Scoobie Doo is a span id Dog_Breed gt lt span gt lt p gt The last key piece is HTML code to add a button When the button is clicked our JavaScript function Get_XML_Dog will execute lt p gt lt button onclick Get_XML_Dog gt Snag an XML Dog Tag lt button gt lt p gt Updating the root c Code After running the web page through the Pbuilder you still need to edit the root c file again to call your CreateXMLFile function in the applicationStart function Display message in STDIO indicating web page is ready Mu applicationstart void initAppServices Init web server amp go CreateXMLFi le Create XML file in RAMO printf Point your browser to s n APP IP ADDRESS Page 56 Copyright Digi International 2011 Let s See the Dog Tags Work When the page is loaded initially the browser will display this text Mozilla Firefox File Edit View History Bookmarks Tools Help Q X da D httsiit92 168 1 196 L Most Visited V Gmail Hotmail Ee News 5 Latest Headlines W Wikipedia What Kind of Dog 1s Scoobie Doo Scoobie Doo is a Snag an XML Dog Taq When the user clicks the button the Get XML Dog JavaScript function will execute and our magic XML code will produce this Mozilla Firefox File Edit view History Bookmarks Tools Help
62. retrieve information from the embedded controller to display in the browser For more information on how to use the RpDisplayText comment tag consult the Advanced Web ServerToolkit manual located by default in the C netos75 Documentation directory Page 28 Copyright Digi International 2011 Set information from the browser on the embedded device Assuming have a variable named MyData defined on my embedded device can both change and display it with comment matched pairs tags as shown here htmT lt title gt some title lt title gt lt head gt lt head gt lt body gt lt more stuff up here having to do with forms gt lt This comment block configures our form and the variables we will use gt lt RpFormInput type text name NameField size 32 maxlength 32 RpGetType Direct RpGetPtr MyData RpSetType Direct RpSetPtr MyData gt lt input type text name NameField size 32 maxlength 32 gt lt RpEnd gt lt more stuff down here having to do with forms gt body html All of this needs to be combined with other tags to build an HTML form but to start with you can see that the various RpGet tags are matched by RpSet tags which send data back to the controller o RpForminput will provide PBuilder with the information it needs to prepare the C code that supports the HTML INPUTS tags It also functions as an opening tag to be paired with the closing ta
63. sh the page every 5 minutes 300 seconds In an auto refreshing example you would call my phone every 5 minutes for new instructions to the pizza parlor Page 8 Copyright Digi International 2011 Chapter 3 Embedded Devices have a limited CPU budget The PC viewing the web page typically has more resources than the embedded web server You can use that to your advantage by pushing the heavy lifting out to the browser By calling on the PC s memory and CPU we can have very complicated script code or animation and still be very responsive as a web server without overly taxing our embedded device You can create very complicated code in the browser using e HTML e Java Applets e JavaScript and AJAX e Flash e AJAX e Yahoo User Interface e Canvas e Plenty more to boot The Digi Advanced Web Server AWS does not support server side scripting While these might work just fine on a more powerful web server the embedded computer will not be able to run them Even if it could the processing power required to handle them might make it a bad choice A good rule of thumb to remember is that anything that runs on the server side will not work because it would require a special command interpreter from the web server You cannot use the following server side scripting languages or programs e Java Servlets e PHP e SQL e Apache e MediaWiki e WordPress e Etc Question How Much Can this Little Guy Handle Can the Dig
64. svazeesaeee gt 38 Updating thetoot c COde tec eite uade ente aee e aeee ae E aeaa a aee SaaS 39 The Final Result A Web Form Interacting with our Controller cccccccccsssssceceesesssessaeeeeeessesees 39 Page 2 Copyright Digi International 2011 Chapter 10 Detecting User Input from the Web Page ssssssssseseeenerenen nennen nennen nnn nnns nnne nian 40 Other Possibilities iradiere Tai t erret tette i ree eee p ie eto eH rete 42 Chapter 11 Adding JavaScript with comment tags to your HTML Pages seeseeeneenneenen nnne 43 Initializing JavaScript Variables with comment tags csscccccccessssessceeececesseseeeseeeessessesesaeeeeseeseesees 43 How to Create the Most Annoying Pop Up Box in History eeseeeeeeeeeennene nene nnne 44 The Annoying Pop Up BOX ete te teet eer ce eot ea ree tes deba gea v ee e Venen us 45 Saving the Annoying Pop Up BOX ccccccssssssceececessessneceeececeseeseeaeseeeeeceseessuaeseeeessesseeuaeseesesenssesnaaeess 45 Chapter 12 Basic XML with the Digi Embedded Web Servel cccecsessssscececeesesenneaeeececeseesenneaeeeesesseeseas 47 Putting together JavaScript Code to Read your XML data sesssssseseseen eene 51 Scary Looking JavaScript Code ciprini nresnain aa aiani aaeh A aranais eir aeeoa ro aeiaai 51 The Magic Go Get My XML File Function sssssssssssssseserensrssssesrrerrnssssesereesnssssenrreesnssssreereesnssssen
65. t lt html gt Looking at the Page Here is a screenshot of how the page will look c 6 Page 65 Copyright Digi International 2011 Using a JavaScript Loop to Pass Dynamic XML Data in Real Time Now that we understand how to start and stop loops in JavaScript we can apply this to our dynamic XML files Here is a more interesting XML file where have populated the XML tags with the current values of variables lt XML File Digi My Data1 2011 My Datal My Data2 1792 My Data2 lt My_Data3 gt 1066 lt My_Data3 gt lt My_Data4 gt 95 lt My_Data4 gt lt Digi gt C Code Again we will need some global variables to write into our XML file Dynamic data for XML file global int MyData 4 Next we need to update our CreateXMLFile function to create files with fresh data from multiple variables We will use the same sequence for working with files e remove e open e write e close Page 66 Copyright Digi International 2011 But now we add a small for loop to create a line of XML for each variable vun CreateXMLFile void char XML Data 200 XML data buffer char Data Buffer 50 Buffer for MyData variable int status Return value for write amp close int fd File descriptor populated by open Create formatted XML string to write to file strcpy XML Data XML File gt n lt Digi gt n Begin file Create
66. tag in the XML Data buffer variables XML Datal xmlboc getElementsByTagName My Data1 0 childNodes 0 nodevalue XML Data2 xmlboc getElementsByTagName My Data2 0 chi ldNodes 0 nodevalue XML Data3 xmlDboc getElementsByTagName My Data3 0 chi ldNodes 0 nodevalue XML Data4 xmlDboc getElementsByTagName My Data4 0 chi 1dNodes 0 nodevalue Write the buffer variables at the span tags with the appropriate ids document getElementById My Datal innerHTML XML Datal document getElementById My Data2 innerHTML XML Data2 document getElementById My Data3 innerHTML XML Data3 document getElementById My Data4 innerHTML XML Data4 setTimeout Get XML O 500 Loop every 500 milliseconds script head The second part of the HTML file is on the next page Page 69 Copyright Digi International 2011 The HTML Body This is very similar to the previous example with the exception that we are accessing four variables Watching it All Work Here is the page before the button is pressed Mozilla Firefox File Edit View History Bookmarks Tools Help Qu c x eem Most Visited M Gmail A Dynamic XML Test My_Datal My Data2 My Data3 My Datad4 Get XML Page 70 Copyright Digi International 2011 When the button is pressed the client requests the XML file from the server and the page is automatically updated Mozilla Firef
67. to the Read XML File JavaScript function which requests a fresh copy of the XML file Unlike our previous example the XML file is being refreshed with new data every 50 milliseconds When the value of the My Data variable changes so will the XML file and we can see that in the browser The Magic Page in Action Here is the page before the button is pressed Mozilla Firefox File Edit View History Bookmarks Tools Help Q X a O hipu92 169 1 196 L Most Visited V Gmail d Hotmail u Mews N Latest Headlines My_Datal Here is the page after the button is pressed the first time without any page refresh Mozilla Firefox File Edit View History Bookmarks Tools Help Gn Q 25 da O hetpyit92 168 1 196 LA Most Visited M Gmail Hotmail 4 News 3 Latest Headlines My Datal 26210 iGet XML Page 61 Copyright Digi International 2011 Here is the page after the button is pressed the second time without any page refresh Mozilla Firefox File Edit View History Bookmarks Tools Help QB Q X qi O http z 192 168 1 196 18 Most Visited M Gmail A Hotmail 3 News 3 Latest Headlit My Datal 8101 Get XML Is this Really Magic Each click of the button requests a new copy of the XML file which we have created every 50 milliseconds It is fast and effective Can we make it more interesting Copyright Digi International 2011 Page 62 Chapter 14 Loopy JavaScript Updating the data on a button
68. ude AsExtern h if RomPagerServer KKK vem dE Ji Built trom hem trigger cb hem RC extern har GetMyData votd char GetMyData void char theResult ES return theResult extern void cae iDataCCHan thevaluePtr void SetMyData char thevaluePtr return endif RomPagerServer Here is the trigger cb v c file with two functions have updated Created with PageBuilder version 4 04 on Mon Dec 20 11 10 27 2010 7 include AsExtern h if RomPagerServer Jes Yee EE vw fe built from hemlVerigger cb html m rui s Z deh e defined in e eM ee ed v c file extern char MyData 50 extern char GetMyData void char GetMyData void printfC n n get callback n n Debugging note for STDIO return MyData Return value of MyData extern void separe thevaluePtr void SetMyData char thevaluePtr printfC n n set callback n n Debugging note for STDIO strcpy MyData thevaluePtr A ssign value to MyData return endif RomPagerServer Page 41 Copyright Digi International 2011 Notice that the MyData variable is defined in another PBuilder generated file and just as we did in Chapter 4 updated the formatsubmitted v c file to better define my variable VE Created with PageBui Ider version 4 04 on Mon Dec 20 11 10 27 2010 include AsExtern h Created with PageBuilder version 4 04 on Mon Dec 20 11 10 27 2010
69. v Cancel Copyright Digi International 2011 6 The final screen will show you a brief summary of your choices Finish ese NET OS Project Review Review your selections Press Finish to create the NET OS application Press Back to make changes You have selected the Following project values Project name Ch4_Basic_Web_Page NET 05 Version 7 5 Platform ConnectCore Wi 9P 9215 Debugger Digi JTAG Link You have selected the Following network options Ethernet IP Address 192 168 1 197 You have selected the Following services Web Server To create the project select Cancel 7 With the project created you can view the files in the Project Explorer on the left hand side of the screen ce iS Project Explorer 23 ES H Bu Ch4 Basic Web Page i i Includes ui 2 oO 6 web appconf api c ih appconf h root c fs readme E E E Ee E d ed o 8 Using Project Explorer Open the web webcontents directory 9 Remove all the files in the web webcontents html directory Note that the files PbSetup txt and RpUsrDct txt present in the web webcontents directory should be not be deleted 10 Open the web result directory and remove all the files Copyright Digi International 2011 Page 14 11 Remove all the remaining files from the web directory except PBuilder pbb as shown here ggjg tSs E Ch4 Basic Web Page of Binaries E ER Archives E Includ
70. webcontents htmUhello html Digi ESP for File Edit Navigate Search Package Manager Project Window Help F3 d idisr C 6 5 5 4 09 4 Es Project Explorer 23 d m E B EB uu ev lt html gt E WS ch4_Basic_Web_Page shead gt lt head gt rs ur Binaries amp Ef archives lt body gt E Includes Hello World H E bsp lt body gt a m oe lt html gt o web result webcontents B html hello html PbSetUp txt E RpusrDct txt B PBuilder pbb appconf api c 5 appconf h d root c a readme H D H 16 Next open the PBuilder pbb file by double clicking on it and then remove all references to anything except your web page RS Project Explorer 23 e ELI bb os E E BE 34 v html hello html c3 Ch4 Basic Web Page amp Ee Binaries 7 EB Archives E K Includes H bsp amp Debug H S sys web amp result webcontents B E html hello html B PbSetUp txt RpUsrDct txt Lc B appconf h A Page 18 Copyright Digi International 2011 17 The initial contents of the PBuilder pbb file are shown below Note that there is one carriage return at the end of the file You need a single carriage return at the end of the pbb file and only one carriage return Anything else will cause trouble htmT 1index htm html network config htm html wireless network config htm html wireless ip config htm html upload
71. where 2011 is the current value of MyData1 lt XML File gt lt Digi gt lt My_Datal gt 2011 lt My_Datal gt lt Digi gt This file is very small and our embedded web server can serve this up much more quickly than the entire page with all the supporting files Best of all the HTML pages do not completely reload and the data will change before our eyes like magic Page 58 Copyright Digi International 2011 Updating the root c code Instead of using a predefined string constant we can now create our XML file in RAM dynamically with fresh data every time First we will need a variable with the interesting data int MyDatal 0 Dynamic data for XML file global Then we need to update our CreateXMLFile function to create files with fresh data This time we add an additional step to the sequence for working with files by deleting any previous files with the remove function By removing any previous copy of the file we ensure that our file is fresh and clean every time Here is the sequence we will use to create a new XML file in each loop e remove e open e write e close vote CreatexMLFile void char XML_Data 200 XML data buffer char Data Buffer 50 Buffer for MyData variable int status Return value for write amp close int fd File descriptor populated by open Create formatted XML string to write to file strcpy XML Data XML File gt
72. with comment tags shown in green bolded text which enable the data passing for the server Here we see that we will be passing data using a get defined in the method attribute and that when the submit button is pressed we will transition to a new page called formsubmitted html lt This comment block sets up our form to pass data with a get gt lt RpFormHeader method get RpNextPage Pgformsubmitted form action z formsubmitted html method get gt lt RpEnd gt To create a box where we can enter data we can use the HTML lt input gt tag which is part of a standard form This input tag is defined by the type attribute to be our text box The name attribute allows you to assign a name to the input element The size attribute tells us the width of the input field 32 while the maxlength attribute provides us with the maximum number of characters we can type into the input field 32 The comment tags are shown in green bolded text In addition you will see that the MyData variable is included for sending and receiving data directly from the controller with RpGet and RpSet tags Again you can see that our comment tags are provided in pairs with each opening tag paired with an RpEnd tag lt This comment block configures our form and what variables we will use gt lt RpFormInput type text name NameField size 32 maxlength 32 RpGetType Direct RpGetPtr MyData RpSetType Direct RpSetPtr MyD

Download Pdf Manuals

image

Related Search

Related Contents

renlig fwm5  f9k1102_8820nt00777_n600_es  ASUS K200MA GK8798 User's Manual  the Kosmos mininova User Manual.  DOCK 5 - UCSF DOCK  Inhaltsverzeichnis - Lidl Service Website  testo 317-2 manual  und Montageanleitung Installation and Operating  Ct-Tracker-08 SPEC V0.4 - Connectec Electronics Co., Ltd.  Se brancher sans fil - Liaison - Université de  

Copyright © All rights reserved.
Failed to retrieve file