Home
SDK User Guide, internal draft 11
Contents
1. int fileno FILE fp Return file descriptor for this FILE int fputc int c FILE fp Send a character to file blocking output int fputs const char s FILE fp Send a string to file blocking output size t fread void buf size t elsize size t nelems FILE fp Read a block of data from file blocking input long ftell FILE fp int fseek FILE fp long off int origin Get current position in file Set file position from beginning or end of file int fsetpos FILE fp long off Set file position size t fwrite const void buf size t elsize Size t nelems FILE fp Write a block of data to a file blocking output int getchar Get character from stdin blocking input void perror const char msg Print message followed by strerror errno to stderr int putchar char Cc int rename const char oldname const char newname Put character to stdout blocking output Rename a file void rewind FILE fp Set file pointer to beginning of the file API Reference 31 UO Interfaces File and Serial lt stdio h gt I O Interfaces File and Serial Non ANSI fopen fprintf getc printf putc puts sscanf setbuf sprintf vfprintf vprintf vsprintf FILI E fopen const char name const char mode Open a file NOTE our fopen onl
2. Error TFTP error code 5 message Access violation Error Couldn t find lt test c gt FI tU oe de 17 Interactive Mode Help 4 2 Interactive Mode Help 18 There are three PUC features that can help you debug your code in interactive mode return values the show command and the trace command In addition you can type help for general PUC help 4 2 1 Return Values Each line will return its runtime value when entered at the command prompt in interactive mode Use this fea ture to check the values of your variables and whether your functions were able to execute PUC 2 t 7 returned 7 4 2 2 Show Command The PUC show command displays the expected function prototypes of any function whether built in or user defined PUC 3 show printf printf Builtin Func fmt const char returning int returned void 4 2 3 Trace Command The trace command shows when and where a new function is called If your code is getting stuck somewhere you can probably find out where by using this command Local 2 cc PUC Interactive mod type help for help or exit to exit PUC 1 include example3 c PUC looking for puc example3 c on TFTP host returned void PUC 2 trace 2 returned void PUC 3 main 3 main 11 foo 5 hello 6 main 12 DsPUCIT 3 returned void PUC 4 Debugging Alternate Compiling Environment 4 3
3. close sockfd Daytime client if sockfd tcp_connect argv 1 SOCK_DAYTIME gt 1 while n recv sockfd line MAXLINE 0 gt 0 line n 0 null terminate printf The time is s n r line close sockfd 2 Log into your MSS and become the privileged user 3 Run the timecli c file in PUC s command line mode You must include the name of the host you wish to connect to as an argument in your command line In this case the desired host is delphi Local_2 gt gt ce timecli c delphi PUC Compiling lt timecli c gt PUC looking for lt puc timecli c gt on TFTP host seconds since 1900 3150123680 The time is Thu Oct 28 11 21 20 1999 PUC exit 0 12 Getting Started Example 5 Network Serial Combination 3 6 Example 5 Network Serial Combination This example accepts a TCP client and bidirectionally echoes data back and forth between the client and the MSS serial port Anything presented on the serial port gets sent to the client anything sent from the client gets pushed out the serial port The code is divided up into three files all of which must be loaded in order to run 3 4 network tcpserv c This file sets up the MSS as a TCP server listening for connections on port 9877 You would connect to this server from UNIX with a command like telnet mss name gt 9877 or nc v mss name gt 9877 wrapper c tcpserv c automaticall
4. Files opened with fopen should never be set to nonblocking modes open should be used if nonblocking modes are required 1 2 4 Known Bugs When initializing a static structure function pointers and extern forward references may not be set to the correct value Try to avoid using the addresses of functions or unallocated variables when statically initializing global structures 1 2 5 Important Limits RAM Depends on MSS model but at least 512 KB Maximum RAM disk file size Depends on MSS model but at least 64 KB Maximum simultaneous file opens 32 Maximum filename size 40 characters Introduction 3 What is PUC 1 2 6 Operating Requirements You need four things to run PUC 1 A Lantronix MSS100 or MSS VIA thin server running code v3 6 2 991020 or later or an MSSLite with hardware revision X X or later To check you current software version enter the Show Version command 2 A text editor used to write the code 3 Telnet functionality on your development host used to access the MSS Note You cannot use the serial terminal to control the MSS in PUC mode 4 A TFTP server or FTP client used to download code into the MSS You can develop applications on any host that can access the MSS and its TFTP loadhost The next chapter will step you through a sample development cycle 4 Introduction 2 Installing the PUC Files 2 1 What s Included in the Distribution The PUC files are distributed partially
5. clock ulong rv clock System timeticks since boot For timeticks use CLOCKS_PER_SECOND NOTE ANSI C specifies microseconds Since our resolution is currently 10 milliseconds this gives us much more range before it overflows 32 bits difftime long difftime time_t tl time_t t2 Difference in seconds between two times NOTE ANSI C specifies a double return value but we don t support doubles 6 11 Debugging Functions lt assert h gt Debugging Functions ANSI assert assert expression If expression evaluates to false or zero prints Assertion failed expression file xxx line n and aborts the program If the NDEBUG macro is defined none of the assert messages will appear nor will the program abort if the expression evaluates to false API Reference 35 SNMP Functions 6 12 SNMP Functions The MSS operating system includes a handler or agent that will reply to queries for some SNMP objects See the MSS Reference Manual for a list of the object databases or MIBs that the MSS can handle internally If the MSS receives an SNMP query for an object that is after the last MSS native MIB object an SDK appli cation can obtain and reply to that query This allows SDK users to implement their own MIBs as long as the MIBs are outside of the MIBs that the MSS supports locally If the SDK application acts as a backup SNMP handler it is responsible for replying to all queries t
6. if ret amp SERIAL IDTR printf DSR is asserted n r termios h IO GSTATUS Constants SE ERIA ERIA ERIAL ERIAL ERIA ERIA RIAL CD IDTR IGAG IRTS ODTR OGAG ORTS Carrier Detect is asserted Input on the DSR pin is asserted Input is flow controlled we have stopped receiving Our CTS Input is asserted Our current DTR output is asserted Output is flow controlled the device attached has stopped recv Our RTS output is asserted 30 API Reference I O Interfaces File and Serial lt stdio h gt I O Interfaces File and Serial ANSI clearerr fclose feof ferror fflush fgetc fgetpos fgets fileno fputc fputs fread ftell fseek fsetpos fwrite getchar perrorr putchar rename rewind void clearerr FILE fp int fclose FILE fp Clear any errors on file stream Close this file int feof FILE fp True if end of file reached int ferror FILE fp True if there s an error on that file stream int fflush FILE fp int fgetc FILE fp Flush any pending output to the device file Get next character from file blocking input int fgetpos FILE fp long off LH char fgets char s int n FILE fp Retrieve current file position Read line from file up to n or V See Section 1 2 3
7. dst const char SE const char s2 size t n size_t n Compare strings to n characters Copy a string of n or fewer characters char strpbrk const char s const char accept Find any character of string accept char strrchr const char s int c Return last instance of character c in string s size_t strspn const char s const char accept Return the length of the initial seg ment of string s which consists entirely of characters from not from string accept char strstr const char haystack const char needle Find needle in haystack API Reference 27 Math Functions lt string h gt String Functions Non ANSI strrev char strrev char s Reverse a string 6 4 Math Functions lt math h gt Math Functions Non ANSI random int random void Returns rand not a different algorithm as in ANSI srandom int srandom int Calls srand int not a different algorithm 6 5 Character Type Functions lt ctype h gt Character Type Functions ANSI isalnum isalnum c Is alphanumeric isalpha isalpha c Is alphabetic iscntrl iscntrl c Is control isdigit isdigit c Is a digit isgraph isgraph c Is a graphics character islower islower c Is lowercase isprint isprint c Is printable ispunct ispunct c Is punctuation isspace isspace c Is space or whitespace isupper isup
8. stdout and stderr will be directed to a null device Further printf functions won t display anything and attempts to read from stdin will return EOF end of file 2 Reboot the server Local init delay 0 MSS Rebooting in 0 seconds To disable autorun mode enter the following command Local cc noauto PUC Autorun is Disabled Local 14 Getting Started Example 6 Autorun Mode 3 7 2 Autorun Example The C file example2 c shows a simple network serial interaction the MSS queries a remote network daytime server and sends the result to the serial port User entries are bolded if you wish to follow along enter the bold items into your Telnet window 1 Connect a display device such as a serial terminal to the serial port of your MSS The display device should match the MSS serial port settings 9600 baud 8 bits no parity and one stop bit Connect to the MSS via FTP using root as your username and system as your password tftpboot puc ftp mymss100 Connected to mymss100 220 FTP Version 0 1 Punix version V3 6 2 991020 on ipO0 Name mymssi00 myname root 331 Password required Password system 230 logged in with privs proceed Remote system type is MSS100 ftp Load the file example2 c into the MSS Flash disk ftp cd flash 250 directory is now flash ftp put example2 c local example2 c remote example2 c 250 PORT set to ip address 20 7522 150 Op
9. 19 40 A LR M M 19 ACC E EA 3 AINSI eui AU NI ues 19 25 40 Eed DEET 25 Arguments iieri ideiei 7 12 14 15 Assigning values to integers ocococononononononononinnnos 9 auto auto Tag 7 14 Autoloading eee 2 13 Autorun mode ooccoccnncnnccnnocnnocnnoncnccnnccnnanos 7 14 15 Disabling iiie tete eie 14 Autorun mode disabling usss 16 B Berkeley sockets eene 33 Bi directional echo 20 0 0 ceseseseseseseseseneseeeeeeees 13 Binary iode entendu 3 BUSS ENEE eei ets 3 Byte ordering eere ete 2 C C language emorg sese 17 C differences from 2 cc Commande 7 8 14 15 Character type functions cococococoncnononononononononos 28 Checking software version ocococononcnononononononnnonos 4 Child ET 2 eI 13 Command line mode eese 7 11 12 Compile time erorg cee eeeeeeeeesenerereneneeeeeeeeees 19 Configuration cccconcncncnenenenenininoninonenenininininess 7 16 Creating Tiles unan 10 D Daytime server 15 34 DDEFINEME macro A 14 Debugging iia eterne dire 17 Functions iere rese teer ie 35 Declaring integers A 9 Directory read functions eee 34 Disk commande 39 40 gr 40 C RE E 40 CHMOD isset ette Re I e reed Rag 40 E TEE 41 EE 41 Format Flash eio onere teet 41 Ie WEE 41 jT 41 pp ERE 41 MKDIR eit eegene 41 MORE ene 42 MIN gidd EE
10. Alternate Compiling Environment Because PUC C is almost identical to ANSI C you can set up an alternate compiling environment and compile SDK code on your PC or UNIX host That way you may see different compile time error messages for prob lems in your code and it may be faster to try out different code snippets These instructions assume you are running UNIX and have the gcc compiler available 1 Set up a directory under tftpboot puc called localinc 2 Putalternate versions of the header files lt startpuc h gt and unp h in localinc You may have to modify these files slightly to reflect different header files in your environment 3 Add the line define wo Puc to your lt startpuc h gt file and use this definition within your source files if you need to make any environment related changes 4 Add the definitions for PUC s special features to lt startpuc h gt as desired See the NON ANSI sections of the API Reference chapter for more information 5 When you are ready to compile in your custom environment add the new path to use to look for include files unixi gcc I tftpboot puc localinc test c When you compile you ll get a file a out that should do the same thing your MSS would do if you were to com pile on it but a out will run on your PC or UNIX host instead of on the MSS You will probably have to do something special to read from the serial port in your custom environment since tt0 will fail Add
11. baud 8 bits no parity and one stop bit If you boot your MSS and hit return a few times on the serial terminal you should see a response from the MSS on your terminal 3 Log into your MSS and become the privileged user 4 Run the spin c file in PUC s command line mode Local gt gt ce spin c You should see characters on the terminal Getting Started 11 Example 4 Network Socket Connection 3 5 Example 4 Network Socket Connection This example show how to connect to a remote host using network sockets User entries are bolded if you wish to follow along enter the bold items into your Telnet window The tcp connect function is contained in the file tcp connect c this function handles the actual socket connection 1 Place the sample timecli c and tcp connect c files on your loadhost in the tftpboot puc directory The contents of timecli c are included here for reference tinclude lt unp h gt automatically include needed c files in PUC Note that these files must be in the search path ifndef NO PUC tinclude tcp Connect ch tendif void main int argc char argv int sockfd n long seconds char line MAXLINE if argc 2 printf usage a out lt IPaddress gt exit 1 Time server client if sockfd tcp_connect argv 1 SOCK_TIMESERVER gt 1 while n recv sockfd char amp seconds MAXLINE 0 gt 0 printf seconds since 1900 u n r seconds
12. on a CD ROM and partially on the MSS internal ROM disk The PUC distribution CD ROM contains a subdirectory called tftpboot puc You should place the contents of this directory on your TFTP loadhost in a directory called tftpboot puc You do not need to copy the include subdirectory but it may be helpful to refer to the files during development The MSS operating system contains a ROM filesystem in which it stores all of the necessary include files This lets PUC access the include files without referring to the TFTP loadhost rom puc rom puc include rom puc include netinet rom puc include sys unp h asserth math h string h in h socket h ctype h netdb h termios h stat h direnth stdarg h time h stdtypes h errno h startpuc h unistd h types h fentl h stdio h unp h limits h stdlib h Note The values of constants in the header file are subject to change in future releases of the SDK unp h is the header file used by all of Stevens code with definitions for some common TCP sockets Adding this file to the beginning of your program allows you to code and test without figuring out which specific include files you need or in which order you need to specify them Include this file any time you want to use sockets 2 2 MSS Optimization There is only one required configuration item for SDK development on the MSS you must configure your load host with the Change Loadhost command The following example
13. operations under C because that is how the serial and network data is handled If you have used sockets libraries under Unix or Windows that knowledge will help 1 1 2 What Can the Lantronix SDK Do The Lantronix SDK is intended to take over the MSS basic function moving data from serial to network and vice versa The user s C code can read from or write to the serial port accept network connections make decisions based on serial or network data and more Applications have access to most of the built in functionality of the MSS Note Some built in functions on the MSS such as hostlist support and modem mode are not available from the SDK What is PUC Amazing things can be accomplished with application level programming You do not need to learn implement modify or debug any of the OS Level code Instead you can rely upon the proven technology of the MSS to provide a TCP IP protocol stack serial flow control NVR and filesystems network time timer FTP server web server and SNMP functionality all in a familiar UNIX like way You can use these core building blocks to implement a wide variety of functionality The SDK does have its limits First it has no hard real time abilities This means that you cannot write an SDK application to control high speed or high precision serial devices that need microsecond level decision making capability Second there is no direct access to any of the MSS hardware You could not for e
14. sio 5 25 JEE E o E ege T RER de 9 Interactive mode 7 8 9 18 IO GTTY constants sisena oe anaana 30 IO STTY constants eese 30 L Label HRS 2 Lantronix contact information esee 37 Linkang errors mercato 17 Loadhost nene 4 5 6 10 40 Local versus global variables 10 Local prompt 7 9 M M N DEE 10 11 17 Maketle cit ti gege 2 Math functions oocoooccnnncnonnconnnnononccnnnncnnonononanos 28 NEE 36 48 N Network sockets ooooocccoconcnnconononcnnconnononnnoons 33 Network Time Protocol 34 Newline character 3 9 noauto noauto flag eese 14 16 Non blocking eite 13 Newer ott tT HEMOS 34 KM UE te 14 KAN Te ER 34 O Opening files 5 iet oes 3 Overview PIC es eege 2 joi E 1 P O ee ee 19 Port OS liura iia 13 Pte toas 8 9 Privileged status 7 8 11 12 15 Prototype defmgons sesesesesesesereees 2 10 18 PUE Rea 2 4 7 DISKS cest estere ev IR Hee en E 40 Distribution Dies 5 Executing code cese 10 16 e e TE 8 10 AA eter too EEN 2 Non standard behaviors esses 3 UNIX installation eere 6 Windows installation eere 6 PUC e EE 7 8 9 R Ramdisk EE 29 39 LOAD E EE 3 TGCV iii ieieccis ge ecce zb ao cuca os at sedate EA 3 AO o de eene tee reo o tans ees 3 Reference SQUICES eene 43 Return character 3 9 Ret rn Vale coccion cistitis 9 Return
15. uint n char str int radix Unsigned int to string 6 3 String Functions lt string h gt String Functions ANSI memchr memcmp memcpy memmove memset strcat strchr strcmp strcpy strcspn Strerror strlen strncat strncmp strncpy strpbrk strrchr strspn strstr void memchr const void s int c size t n Find a character in memory int memcmp const void sl const void s2 size t n Compare memory contents void memcpy void dst const void src size t n Copy data void memmove void dst const void src size t n Copy overlapping data void memset void s int c size t n Set memory to value char strcat char sl const char s2 Concatenate string s2 to end of string sl char strchr const char s int c Find character in string int strcmp const char sl char strcpy char dst const char 82 const char sra Compare strings Copy a string size t strcspn const char s const char reject Return length until first character in string reject char strerror int n Generate error message string from error number n size t strlen const char s Return length of string char strncat char sl const char s2 size_t n Concatenate up to n characters from string s2 to the end of string sl int strncmp const char sl char strncpy char
16. values eee 8 18 30 RONMP diskie eee 5 39 Runtime library eese 25 R ntime valles o cocoa asis 18 S Sample code davtpmetcpch 23 CITC CHED Casini inais dotada Eeer Ne 22 Cit Ee 21 do buffet c i ra een 22 do Bilebuf e n ibid eater 22 ui X 21 raCtOa C 4 ite nene teer ESA 21 Itpclt e iai ect ette E 22 getiDCs ut ETES TU tetti Cete e 21 et PLONE nandi anita Ent 23 foreros acia dene ai 21 nuria exeat supo bu 21 ENT EE 22 Miscellaneous ns nin n a inan 21 Network PUC ei iii A 22 Network Stevens 23 PATA Cu 21 IT 22 lia gr 22 SNMP hit tipicas 22 PMC a 21 MARA A 22 e EE 22 A ENNEN ENEE EEN 22 tCpservOl Cuidado aiii 23 MEC Corina 21 dpseryc oie c elei em tere edel 22 dpservO l c eene 23 tils 6 e eet ede 21 Wrapper E ceto EU EE 23 CDi EUER 10 SDK OVetEVIeW EE 1 Search paliar teet 8 19 SOMO ssecciissseceaiseseccdadieeccaceseecdiaseVeceadeaseccacnsvbecs 3 Serial port 7 11 13 15 19 29 Serial settngs siete ete dien 11 15 SAD ea ecu eu ve eege 3 Show commande 10 18 Sia acia dd das 2 SNMP functions isinna nnana 36 SNMP Object database eee 36 E 36 Socket a 26 PICA TIAS 11 EE A e E 3 Standard library functions 0 0 0 2 26 Startpuc bh 5 9 17 19 25 26 Mi A Ee dees 14 SEdID ia reete ee EN 14 Eis EE 14 KEE 33 43 String Ne le ET 27 T Een ee 13 TGP EE 13 EP COMME dites rete Perrier 12 tCDCconnecbe onuran ege degen i
17. IX operating system and MSS setup If you have trouble following any of these steps contact your system administrator 1 Create a directory on your TFTP loadhost named tftpboot puc 2 Make sure the permissions for tftpboot puc are set to 775 full permissions for owner and group read and execute permissions for world 3 Copy the PUC files to the tftpboot puc directory 4 Make sure the permissions of all of the files in tftpboot puc are set to 664 read write permissions for owner and group read permissions for world 5 Make sure your MSS is configured to use the proper loadhost Note Instructions for configuring and checking the TFTP loadhost are located in your MSS Installation Guide and the MSS Reference Manual Filenames on UNIX TFTP loadhosts are typically case sensitive Keep this in mind when specifying filenames for files that are located on your TFTP loadhost 2 4 Windows Installation This section assumes familiarity with the Windows operating system If you have trouble following any of these steps contact your system administrator 1 Create a directory on your TFTP loadhost named lt tftp gt tftpboot puc You will need to consult your TFTP documentation to find out where the download directory is located 2 Copy the PUC files to the lt tftp gt tftpboot puc directory 3 Make sure your MSS is configured to use the proper loadhost Note Instructions for configuring and checking the TFTP loadhost are located in
18. Lantronix SDK User Guide For the Lantronix Software Developers Kit The information in this guide may change without notice The manufacturer assumes no responsibility for any errors which may appear in this guide UNIX is a registered trademark of The Open Group Ethernet is a trademark of XEROX Corporation Portions of Portable Universal C are derived from EiC an online bytecode C interpreter www anarchos com eic and are used with permission Copyright 1999 Lantronix All rights reserved No part of the contents of this book may be transmitted or re produced in any form or by any means without the written permission of Lantronix Printed in the United States of America The revision date for this manual is November 3 1999 Part Number 900 171 Rev A WARNING This equipment has been tested and found to comply with the limits for a Class A digital device pursuant to Part 15 of FCC Rules These limits are designed to provide reasonable protection against such interference when operating in a commercial environment This equipment generates uses and can radiate radio frequency ener gy and if not installed and used in accordance with this guide may cause harmful interference to radio com munications Operation of this equipment in a residential area is likely to cause interference in which case the user at his or her own expense will be required to take whatever measures may be required to correct the interference Changes o
19. N 42 OD o 42 PWD ie aere ina 42 RM EN 42 RMDIR eegnen 42 SN Citi 42 Display terminal eee 15 le Be TEE 13 do socket acne rene ie tee isis 13 Double data type ee en ch reet 2 E o 2 43 BOE cene o ERG S Da 14 EOL Sucia 17 19 Error trapping fUNCtiONS ooooococonononononononononononons 13 Examples DEE dee ee 14 15 Hello Worlds 8 Interactive mode 9 Network socket connection 12 MNetworkisertal tinmagan ases 13 Serial EDU T 11 Exit command eerie dE 8 10 F tentando tank 3 O E 3 File permissions ococococononononononononononononononononos 6 17 File e e 3 Filesystem snieter a ne EA E aiee 39 Flashidisk cinco Eege 15 29 34 39 Flash le te EE 34 47 Index fopen ile 3 EOrkig 22 ipft ates 2 FTP usine eee pedo BW 4 15 tt EE 2 Built in iso e etre Sessa secon aes 25 Character type eet a 28 IR ET 35 Directory fedd nets 34 I Oamtetrfaces ii AAA 29 Mathias iia 28 Network socket oooccccooccnocononoconcnocnnnconnnns 33 NVB Elash ees ege retener teorie e 34 Prototype nsis fiorini e ted ertet 18 Kik JE 36 Standard library A 26 E 27 Du rm 34 Wrapper error rap 13 G Global versus local variables 10 Go EE 2 H Header files 3 3 e rere ei 2 19 25 lu 17 VO functions t ir esa ria 29 A X 5 Include UE aia re aaa r a
20. Socket FUNCUONS cotilla i E OO P ER SER REO Here URLs 33 6 8 Directory Read Functions nite d t e e t EE A cett 34 6 9 NV R Elasli tette eR PR AA ite ne de e RO PEE 34 6 10 Time Functions eere tenete nee ee olea tieu ee e eve obe Ue ER TRE epe E Ee Ne bna 34 6 11 Debtigging Functions lira modesta eid 35 6 12 SNMP e le EE 36 Az Technical zIl To ojo RS iaa in idad iaa 37 Az The SDK Support Planilla 37 A 2 Problem Report Procedure 4 2 tee tt e t reet et apa 37 A S Other Contact te e TEE 38 B Disk ManadgemenL iieri rin a 39 MS Xu d E 39 Bi2 The EE 39 B 3 Using Disks im PUC eerste owe ba grep Ee Wa iet e nn ne 40 B 4 Disk We EE 40 e Ee 43 Cal Stevens Network Examples 2 pugne GP RBS dE 43 C2 FiC Doc imentatioti 2 ttm dise tet Het pe o etia NEO tod a pepe eet el 43 3 Other Usef l Sources uranio e d iO Eee 43 Function NC E 45 i do XX 47 1 Introduction 1 1 What is the Lantronix SDK The Lantronix Software Developers Kit SDK allows you to customize the behavior of your MSS in more ways than are available via the standard command set You can write programs for the MSS that handle serial and network data and store the finished programs on the MSS Flash ROM so they always run when the MSS boots For example you could write an application that monitors industrial or medical equipment and sends email when certain conditions are met Example A hospi
21. a section to your code that is similar to the following to open the host s serial port ifdef NO PUC int fd open dev ttyq1 O_RDWR else int fd open tt0 O_RDWR endif Debugging 19 5 Sample Code The samples described in this chapter and contained on the Lantronix SDK distribution disk allow you to do many useful things with the MSS SDK For example you can create an SMTP mail client a simple FTP client an SNMP agent a UDP server and more Lantronix recommends basing your custom applications on these samples Note Some of the examples won t work correctly unless a Nameserver and Domain have been defined on your MSS See your Installation Guide for information about configuring these items The files are grouped into subdirectories on the distribution CD ROM However they must be placed at the top level of tftpboot puc in order to work properly This chapter may not be all inclusive For a list of the samples that are included in your distribution please refer to the readme on the distribution disk 5 1 Miscellaneous Samples spin c echo c log c timecli c param c fractoa c utils c getip c ioctl c dirwatch c Spins characters out of the serial port Shows all of the possible ways to read and write to the serial port using file descriptors and file pointers and all of the I O commands Saves incoming serial data to a file on the ramdisk Enter data on the serial port end
22. active mod type help for help or exit to exit PUC 1 gt Note When you enter the cc command the prompt changes to PUC n gt where n represents the num ber of the current user entry 3 Atthe PUC gt prompt enter compiler directives commands or C commands For this example enter the following items PUC 1 gt include lt startpuc h gt returned void PUC 2 printf Hello world n r Hello world returned 14 PUC 3 gt The include command causes PUC to load the SDK header file lt startpuc h gt PUC will look through the flash ram rom and tftpboot puc directories in that order until it finds the file In this case lt startpuc h gt is a standard header file so it is found with other include files on the MSS rom directory After loading the header file PUC returns the next prompt When you enter the printf statement PUC executes it displays the appropriate output and displays a return value In this case printf returns the value 14 which is the number of characters printed The return value of every statement is reported in interactive mode Exit PUC by typing exit at the PUC gt prompt If this does not work or your code hangs you can usually abort PUC by typing Ctrl C Aborting a running program using Ctrl C may not work if your code is blocked waiting for input or output which is one of the reasons Lantronix recommends using non blocking I O If you cannot use Ctrl C you ma
23. arity and sets it for Even sets the character size for 8 bits and sets the stop bit count to 1 int newset B19200 CRTSCTS PARENB CS8 int fd open tt0 O_RDWR ioctl fd IO_STTY amp newset lt termios h gt IO GTTY IO STTY Constants B300 els B600 CS7 CS8 CST CRI OPB SCT S CXONXOFF CDT RDS ER EC PA PA PA RENB RODD REXT R HO ER PASSFLOW Sets the baud rate The possible values are B300 B600 B1200 B2400 B4800 B9600 B19200 B38400 B57600 B115200 B230400 AND the result of IO GTTY with CBAUD to get the baud rate field Sets the character size CS8 is the default AND the result of IO GTTY with CSIZE to get the character size field Sets the MSS for two stop bits one stop bit is the default Enables CTS RTS hardware flow control Enables XON XOFF software flow control Enables DTR DSR hardware flow control Automatically echoes serial input Adds XON XOFF characters to stream Enables parity and sets it for Even unless PARODD is also set PARENB alone Even Changes to Odd parity PARENB must also be set PARENB PARODD Odd Makes PARODD toggle between Mark and Space PARENB must also be set PARENB PAREXT Space PARENB PAREXT PARODD Mark AND any of the serial status constants with the ret value int ret int fd open tt0 O_RDWR int rv ioctl fd IO_GSTATUS amp ret
24. as 12 A bee Ed 13 Teleton rias 4 8 9 11 13 Derminal AA da 11 Text editor eiii pits 4 RK RE coca std 4 5 6 40 me LUCO LR A 34 MEC aa 12 MIMESELV ERs oO eer OO EON ias 34 Trace commande 18 uU EA CL 19 29 U UDP socket 33 iii 3 UND at eei 13 14 19 39 Installation uhp ere 6 UI EE 5 19 25 26 V A aaas 18 Variables siii ee See 18 Global versus local eene 10 VOI i iii i nn 9 W Windows installation eee 6 WIAPPOL C A 13 49
25. customize behavior using mypipe c without having to open any sockets or serial lines The user functions serIn and netIn are repeatedly called with any pending data Outgoing data can be sent to serOut or netOut Sample Code Stevens Network Samples 5 3 Stevens Network Samples The examples in this section are taken from Unix Network Programming Volume 1 2nd Ed by W Richard Stevens Full bibliographic information can be found in Appendix C Some of the examples are modified from the original Stevens examples in order to comply fully with PUC The higher level functions were modified as little as possible the wrappers were modified more significantly Differences are noted wrapper c Error trapping wrappers for socket I O functions The wrappers are mainly useful for debugging since they exit program execution on failures daytimetcpcli c A daytime client that queries a remote daytime server using inet_pton Returns a formatted time string See Stevens Figure 4 5 The client establishes a TCP connection with a server and the server sends back the current time and date in a human readable format inet_pton c Converts dotted quad presentation format IP addresses to network format Required by daytimetcpcli c tcpserv01 c TPC echo server using the unassigned port 9877 Modified to run under PUC by removing the fork See Stevens Figure 5 2 udpserv01 c UDP echo server that handles multiple clients simultaneously echoin
26. e tet tpi 11 3 5 Example 4 Network Socket Connection ener 12 3 6 Example 5 Network Serial Combination eese nennen nennen 13 3 7 Example 6 Autorun Mode eee ee tete eee Oe Eege EEN de conde 14 3 7 LAON OVervie W cce tte cedet tente e tie poet eet ee Re ay ude suet ee pe ER eR edd 14 Ee E eee op b e dte de i E eti e eee 15 O T M 17 Ar A EOTS E EE eee tut eb EE e dete dues ech Na deti IP etc cette Ue LU ea x sabes dade 17 41 1 Common C Language Brrors ccoo b eoe o DE ERE 17 4 1 2 Common Linking Errors ee tia aid pia 17 4 2 Interactive Mode Help entier R ce oic eden eni De qe ated 18 42 1 Return Valles 2 5 endete RR e e de eee s 18 42 2 Show Command ensen eee ep teet detecte eerte 18 42 3 Trace Command eee dia 18 4 3 Alternate Compiling Environment 19 Sample e rana 21 5 1 Miscellaneous Samples iot ppc tette te eo desa ida 21 KEREN eer 22 5 3 Stevens Network Samples cuca eua to dde iei 23 Contents 6 API BefelelniCo nr Sa 25 6 1 Header destinations 25 6 2 Standard Library Eneps ue i net ud aee tei ba dede 26 6 5 String Functions eet etd mh tee idet eerte eot ne eee etre pee be uod peg ee 27 6 4 Math Functions e dp de ee t tha tc nee hei iio bloc ale needy 28 6 5 Character Type Functions ENEE ect 28 6 6 VO Intettaces Eieand Setial 2 e eit a vete ee eic e elec e ardor aestas eene e oos 29 6 7 Network
27. ened port 7522 226 transfer complete 1344 bytes transferred 1344 bytes sent in 0 00 seconds 685 38 Kbytes s ftp Exit FTP mode ftp close 221 Goodbye tftpboot puc Log into your MSS and become the privileged user Set the file example2 c for autorun mode You must include the name of the desired daytime server after the code file name In the example belowe the daytime server is delphi Local cc auto example2 c delphi PUC Autorun is Enabled Local gt gt Reboot the MSS Local gt gt init delay 0 Initializing server Getting Started 15 Example 6 Autorun Mode 8 When your MSS reboots you will see the following on the serial port terminal oe oe Lantronix MSS100 Ethernet Address 00 80 a3 xx xx xxInternet Address ip address oo oe Thu Oct 28 12 29 38 1999 Thu Oct 28 12 29 48 1999 Thu Oct 28 12 29 59 1999 Thu Oct 28 12 30 09 1999 Note the repetition of the time display The auto switch will re execute the program if it exits You could use an infinite loop like while 1 sleep 10 inside the program to only print the time once 9 Disable autoboot mode Local cc noauto PUC Autorun is Disabled Local 16 Getting Started 4 Debugging This chapter includes tips on debugging your code and interpreting errors received from the MSS or PUC Please read this section before contacting Lantronix Technical Support Support contac
28. fstat int fd struct stat buf File status from file descriptor int mkdir const char path mode t mode Make a directory with a specified mode int Note stat const char file name struct stat buf Get file status Only world read matters since PUC can only support two levels of privilege root and anonymous As such although you can set other modes on files only read world and read write execute root permissions will be obeyed by the filesystem API Reference Network Socket Functions 6 7 Network Socket Functions These functions are Berkeley Sockets functions For more information see Stevens bibliographic information is included in Appendix C or the UNIX man pages lt sys socket h gt Network Socket Functions Non ANSI accept int accept int fd struct sockaddr_in addr addrlen Allocate a new file descriptor for first pending connection bind int bind int fd struct sockaddr name connect int connect int fd struct sockaddr name namelen int namelen Assign name to unnamed socket Make a connection to another socket gethostbyname HOS NT gethostbyname char name E Look up hostent in nameserver gethostname int gethostname char name int namelen Get local host name getprotobyname PROTOENT getprotobyname const char protoname Look up protocol name getservb
29. g back any incoming data to each specific client See Stevens Figure 8 3 Sample Code 23 6 API Reference This chapter lists the functions that are built into the Lantronix SDK environment You will be able to see each function s calling convention purpose and return values Functions are arranged by the include file in which they are found and further divided into those that adhere to the ANSI standard calling convention ANSD and those that differ from the standard C API runtime library Non ANSI Some Non ANSI functions are simply implementation differences others are custom API functions created by Lantronix The functions are grouped into major sections as follows Standard Library Functions page 26 String Functions page 27 e Math Functions page 28 e Character Type Functions page 28 e I O Interfaces File and Serial page 29 Network Socket Functions page 33 Directory Read Functions page 34 NVR Flash page 34 Time Functions page 34 e Debugging Functions page 35 SNMP Functions page 36 Note 6 1 Header files The required header files are stored in the MSS ROM disk rom An alphabetical index of functions can be found on page 45 rom puc rom puc include rom puc include netinet rom puc include sys unp h asserth math h string h in h socket h ctype h netdb h termios h stat h direnth stdarg h time h stdtypes h errno h startpuc h unistd h types h fcntl h s
30. h Change current directory close void close int fd Close a file dup int dup int fd Copy a file descriptor link int link const char oldpath const char newpath Create new path linked to old Jeck off t curpos lseek int fd off t offset int whence Move the file pointer read ssize_t nread read int fd void buf int len Read from a file rmdir int rmdir const char path Remove empty directory unlink int unlink const char fname Delete a file write ssize t nwritten write int fd const void buf int len Write to a file lt unistd h gt I O Interfaces File and Serial Non ANSI ioctl int rv ioctl int fd IO_INPPEND NULL Input pending int rv ioctl int fd IO_OUTPEND NULL Output pending int rv ioctl int fd IO_GSTATUS int ret Status of DSR CD RI flow int rv ioctl int fd IO_GTTY int ret Get current baud parity charsize int rv ioctl int fd IO_STTY int ret Set baud parity charsize etc NOTE lt termios h gt contains constants for IO_GTTY IO_STTY sync void sync void Write all pending data to all files on all devices API Reference 29 UO Interfaces File and Serial For IO_GTTY you should AND the return values with the status constants to determine if they are set For IO_STTY you should OR the constants together to define your settings The example below sets the baud rate to 19200 enables CTS RTS flow control enables p
31. hat it receives This could include generating the appropriate SNMP errors for unknown or malformed objects enforcing any security needed and so on Familiarity with SNMP is needed to implement a custom MIB using the SDK Note See chapter 25 of Stevens TCP IP Illustrated Vol 1 for more information about the SNMP protocol The sample SNMP code on the SDK CD ROM snmp c provides basic decoding encoding MIB setup re quest handling and trap sending code you can start with this code and modify it to meet your needs If you do not need support for the more complex objects you can simply change the MIB and handler at mymib c fol lowing the example there lt socket h gt SNMP Functions Non ANSI snmpDeregister void snmpDeregister int fd Closes the SNMP connection snmpRead int len snmpRead int fd char buffer int Receives incoming SNMP packets The first max_buffer_len byte placed in the passed in buffer will be the first byte of the snmp portion of the UDP packet Non blocking Returns 0 if nothing is pend ing Returns lt 0 if there is an error call snmpDeregister Returns the length of the data copied to the user buffer snmpRegister int fd snmpRegister void Registers your application as the handler for all non built in OIDs fd is gt 0 for success or 1 for failure snmpSendTrap int snmpSendTrap char host char trap_pkt Allows your application to send traps int len alerts
32. ing no flag creates a hard link Adding the s flag creates a soft link Local gt gt DISK LN newapp c unp h Local gt gt DISK LN s newapp c unp h DISK LS flag file Lists the contents of a directory The available flags are l Returns a list in long form which includes information about modification date size owner and permissions t Sorts the list by modification date with the newest file appear ing first r Reverses the order of the file listing For example if t was also specified r would list the oldest file first Local gt gt DISK LS 1 rom puc include DISK MKDIR directory Creates a new directory on the MSS RAM disk or Flash disk Local gt gt DISK MKDIR flash customapps Disk Management 41 Disk Commande DISK MORE file Displays the contents of a file on the terminal 24 lines of text at a time Normally the display pauses after each screen and prints MORE at the bottom of the screen To access the next screen press the Space bar TO abort press Ctrl C Local gt gt DISK MORE rom puc unp h DISK MV file target Moves files or directories on the MSS RAM and Flash disks You can also rename files with this com mand by inserting the new filename for target Local gt gt DISK MV rom puc unp h flash customapps DISK OD flag file Displays the contents of the specified file in bytes format The possible flags are b Prints the b
33. ing with Z Check the results from the MSS command line Local gt gt DISK MORE ram outf Simple TCP client examples using timeservers Provides param_read param_write and param_commit to store parameters in a local Flash disk file Parameters can be arbitrary length Convert a fraction into a decimal string Useful since the PUC does not use the float data type this is intended to reduce the size requirements of the software dprintf is a printf specialized for debugging upTime reports uptime in seconds since it was first called fdprintf acts like fprintf but takes a filedescriptor instead of a file pointer Gets the MSS s IP address via gethostbyname Shows usage of platform specific IOCTL calls Examines modification times for all files in all disk subdirectories 21 PUC Network Samples 5 2 PUC Network Samples tcpserv c tcpcli c tcp connect c do buffer c do filebuf c udpserv c mailcli c ftpcli c snmp c directed c rs491 c piper c 22 Genericized TCP server running under PUC The function do socket services the connection It is based on Stevens figure 5 2 Genericized TCP client running under PUC The function do socket services the connection Opens a TCP connection to a remote network server This file is called by many of the examples tcpserv c or tcpcli c along with do buffer c collects incoming serial data until one of three conditions is met buffer full
34. ll react to any file having a similar extension prefix suffix or pattern For ex ample the command DISK Ls h will list all of the header files from your current working directory provided they have the n extension Unlike UNIX Disk commands MSS Disk commands are not case sensitive In the examples required com mand keywords appear in uppercase and user supplied parameters appear in lowercase However the com mands can be entered in any case B 2 TheFilesystem There are four directories that are used by the SDK The MSS contains three directories two of which can be used for your custom application files The fourth directory lives on the MSS s loadhost The directories are scanned at runtime in the following order ram The RAM disk stores temporary information for the MSS The MSS will hold infor mation stored on this disk until it is turned off or rebooted At startup the RAM disk will be empty FTP connections automatically use the RAM disk as the default working directory flash Flash is re writable memory that allows you to customize your MSS Any data that you want the MSS to save after it is rebooted should be put on the Flash disk When your applications are stable you can put them on the MSS Flash disk Depending upon your custom settings the Flash disk may contain new settings for the MSS At start up the MSS will change the MSS settings based on what it finds on the Flash disk If the MSS does not find any new i
35. lue of t is 15 because that is the value you defined in the main function of example1 c 11 Try checking the value of t again PUC 8 gt t returned 7 PUC 9 gt Notice that t is not 15 as you might expect It is 7 because the scope of int t in main is internal to main it has nothing to do with your earlier globally decalred int t Once main finishes its local variables disappear From the command line you can only see global variables 12 Exit PUC by typing exit at the PUC gt prompt PUC 8 gt exit Local gt gt 10 Getting Started Example 3 Serial Output 3 4 Example 3 Serial Output This example opens the serial port sends characters to it and then closes it User entries in examples are bolded if you wish to follow along enter the bold items into your Telnet window 1 Place the sample spin c file on your loadhost in the tftpboot puc directory The contents of the file are included here for reference include lt startpuc h gt void main int fd char c int i open serial port 0 fd open tt0 O WRONLY spin through printable chars from spc to lt gt 50 times for i 0 i lt 50 i while c lt write fd amp c 1 c always close any files you open close fd 2 Connect a display device such as a serial terminal to the serial port of your MSS The display device should match the MSS serial port settings 9600
36. nformation on the Flash disk it will use the files stored in ROM Note The Flash disk has a large but limited write life rom The ROM disk is read only and cannot be modified by users It contains all of the stan dard header files h 39 Using Disks in PUC tftpboot puc The loadhost s t ftpboot puc directory is a good place to work on files Any source or include files that are placed here will be loaded into the MSS automatically When looking for include files or source files the MSS will look at the RAM disk then the Flash disk then the ROM disk If it has not located the files it will use TFTP to try to look for the files on the configured loadhost There are no files on the loadhost by default You must place files there explicitly You must also make sure the files have world read permissions the default is no world privileges B 3 Using Disks in PUC Disk files can be read from or written to from PUC using ANSI standard file commands For example open flash index txt O_RDONLY Directory access functions are available in lt dirent h gt B 4 Disk Commands DISK CAT file Allows you to display an entire file in your terminal window Local gt gt DISK CAT flash index txt DISK CD directory Allows you to change the current working directory Local gt gt DISK CD ram DISK CHMOD code file Allows you to change permissions for a file or directory To assign permissions en
37. obyname 33 getservbyname 33 getsockname 33 gmtime 35 H htonl 33 htons 33 inet addr 33 inet ntoa 33 ioctl 29 isalnum 28 isalpha 28 iscntrl 28 isdigit 28 isgraph 28 islower 28 isprint 28 ispunct 28 isspace 28 isupper 28 isxdigit 28 itoa 27 L labs 26 link 29 listen 33 localtime 35 Jeck 29 ltoa 27 malloc 26 memchr 27 memcmp 27 memcpy 27 memmove 27 memset 27 mkdir 32 mktime 35 N ntohl 33 ntohs 33 O open 29 opendir 34 P perror 31 printf 32 putc 32 putchar 31 puts 32 Q qsort 26 R rand 26 random 28 read 29 readdir 34 realloc 26 recv 33 recvfrom 33 rename 31 rewind 31 rewinddir 34 rmdir 29 S seekdir 34 send 33 sendto 33 setbuf 32 setsockopt 33 shutdown 33 sleep 34 sleepMS 34 snmpDeregister 36 snmpRead 36 snmpRegister 36 snmpSendTrap 36 snmpWrite 36 socket 33 sprintf 32 srand 26 srandom 28 sscanf 32 stat 32 strcat 27 strchr 27 strcmp 27 strcpy 27 strcspn 27 strerror 27 strlen 27 strncat 27 strncmp 27 stmcpy 27 strpbrk 27 strrchr 27 strrev 28 strspn 27 strstr 27 strtol 26 strtoul 26 sync 29 T telldir 34 time 35 tolower 28 toupper 28 U ultoa 27 unlink 29 utoa 27 V vfprintf 32 vprintf 32 vsprintf 32 W write 29 45 Index Symbols Adel tii ai lid 19 FANCIUGE rica esancen aset 2 5 8 9 aiii 8 14 15 29 34 39 MO die 8 14 29 39 JARON 0a is 8 25 39 Atftpboot puc 5 6 8 10 11 13 14
38. orun mode you tell the MSS to run specific C code files at every startup see Example 5 The command is similar to the one used for command line mode except for an auto flag Use this mode to run finished applications on the MSS Autorun mode will start the application 5 seconds after the MSS boots If the program exits or aborts the MSS will restart it 5 seconds later Compile time delays will add a few seconds to these times depending on program size You must be the privileged user to run PUC regardless of which mode you choose In addition you must be connected to the MSS via a network connection you cannot run PUC from the serial port Example 1 Simple Hello World 3 2 Example 1 Simple Hello World This is a basic interactive mode example that uses an include file and a printf statement User entries are bolded if you wish to follow along enter the bold items into your Telnet window If you need help type help at the PUC gt prompt 1 Telnet into your MSS enter a username and become the privileged user telnet mymss100 Trying 192 0 1 125 Connected to mymss100 Escape character is J Lantronix MSS100 Version V3 6 2 991020 Type HELP at the Local gt prompt for assistance Username Bob Local set priv Password system not echoed Local gt gt Note You cannot start PUC from the serial port 2 Enter PUC s interactive mode by typing cc Local gt gt ce PUC Inter
39. per c Is uppercase isxdigit isxdigit c Is a hexadecimal digit 0 9 a f A F lt ctype h gt Character Type Functions Non ANSI tolower tolower c If uppercase convert to lowercase macro toupper toupper c If lowercase convert to uppercase macro 28 API Reference I O Interfaces File and Serial 6 6 I O Interfaces File and Serial Files can be read written and or created on the flash disk non volatile RAM or on the ram disk temporary The serial port can also be opened for read write or both at tt0 lt fcnil h gt I O Interfaces File and Serial ANSI creat in open in EX EX t fd creat const char path unsigned short amode t fd open const char path int oflag mode_t Opens a file mode int fd open tt0 O_RDWR Opens the serial port read write mode int fd open filename O WRONLY O CREAT 0664 Returns an error or a file descriptor fcntl h I O Interfaces File and Serial Non ANSI fcntl int ret fcntl int fd F GETFL Always returns zero See Section 1 2 3 int ret fcntl int fd F SETFL O NONBLOCK Enables non blocking I O int ret fcntl int fd F SETFL O Disables non blocking I O NOTE No other cnt1 commands are allowed lt unistd h gt I O Interfaces File and Serial ANSI chdir int chdir const char pat
40. r modifications to this device not explicitly approved by Lantronix will void the user s authority to operate this device Cet appareil doit se soumettre avec la section 15 des statuts et reglements de FCC Le fonctionnement est sub ject aux conditions suivantes 1 Cet appareil ne doit pas causer une interf rence malfaisante 2 Cet appareil doit accepter n import quelle interf rence reiue qui peut causer uneop ration ind sirable Contents A A ul 0a xE Luca Nae E RD EU Dn ivan Manu atn o 1 1 1 What ts the L ntronix SR ee 1 1 1 1 Who Would Use the Lantronix SDK esee 1 1 1 2 What Can the Lantronix SDK Do sess nennen eren 1 AE PU 127r E cote tects cack se EE tite teet ao Ceu EE H 1241 Difterences from C teet itp td Eed 2 1 22 Ee EE 2 1 2 3 Non Standard Behaviors iia inicial 3 12 4 Known Bugs uere p ene IHRE e e tee cederent 3 1 2 5 Important Eer EE 3 1 2 6 Operating Requirements edere ee eed ete ti deese ge E Pe e gen tae ga 4 2 Installing the PUG UE 5 2 1 What s Included in the Distribution eese nennen rennen enne 5 22 MSS Optinization soi ie ip ge ee EES E EEN EE teh Ur ded 5 2 3 UNIX Installato EE 6 2 4 Windows Installation cidad ida 6 3 GOING Sa ii aaa 7 3 1 Howto Run nt RE H 3 2 Example 1 Simple Hello World nenin rainn neret eren eec 8 3 3 Example 2 More Interactive Mode AAA 9 34 Example 3 Serial Optica re E dte fe eee pte ter
41. rstood Use ANSI standards e There are no makefiles but you can include source files from other source files so you can make them automatically load in the right order Some of the standard library functions are not implemented See Chapter 6 for a list of implemented functions and their prototypes 2 Introduction What is PUC 1 2 3 Non Standard Behaviors There are some important non standard behaviors to be aware of read and recv return 1 on remote disconnect whereas most flavors of unix expect a 0 Terminal settings require both a newline On and a carriage return 1 to move to the beginning of the next line fgets terminates at either character In general files are opened in binary mode rather than text mode setbuf can only be changed to NULL from its default setting sscanf doesn t terminate when the input fails to match the control specification instead it assigns O values to the unmatched variables When accept copies socket information it does not copy blocking status Blocking status must be set explicitly after the accept fentl is only used to change blocking status and has no other behaviors UDP sockets never block on recvfrom or sendto Files can only be fopened as read only write only or append only To use a file in read write mode it must be opened twice using two different file pointers FILE fpr fopen dev r FILE fpw fopen dev w
42. send flag encountered or no data received for a specified time delay This prevents the MSS from sending single character packets for slow serial data which reduces network traffic Buffers a network file into a local ramdisk file then sends it out the serial port in one piece when the network connection closes Queryable UDP server Responds to simple commands from multiple simultaneous clients An SMTP mail client that connects to an SMTP mailserver and sends email An FTP file transfer client This limited implementation can only use PASV mode for file get put and directory listings Fairly complete and complex SNMP agent Requires mib c asn1 c agent c and mymib c which should be customized for your specific purposes Supports traps but doesn t handle tables Accepts multiple TCP clients to the same port and sends all incoming client messages out the serial line one at a time Each incoming message needs a return address identification header serial incoming messages are scanned for matching identification headers and sent back to the original sender only Input is buffered to send only full messages Implements local MSS control of an RS491 serial protocol device so that raw files can simply be sent from a remote network client Allows you to use the SDK to buffer network data for a timing critical serial protocol Acts as a kind of wrapper for generalized serial and network I O Users can intercept the data streams to
43. t API Reference 33 Directory Read Functions 6 8 Directory Read Functions lt direct h gt Directory Read Functions ANSI closedir int closedir DIR dirp Close directory opendir DIR opendir const char filename Open a directory to read Null if error readdir struct dirent readdir DIR dirp Read next directory entry rewinddir void rewinddir DIR dirp Reset to first directory entry seekdir void seekdir DIR dirp Seek to the results of a previous telldir telldir long telldir DIR dirp Retrieve current position within direc tory list 6 9 NVR Flash To keep persistent data across reboots write files to the Flash disk flash filename There will be approximate ly one second of lag time as files are written Note The Flash disk has a large but limited read write life cycle 6 10 Time Functions You must configure and enable a timeserver for time functions to give meaningful time information See the MSS Reference Manual for information on how to configure your timeserver options If you use an NTP Network Time Protocol server the date and time will be correct provided the NTP server is on line when the MSS boots If not the MSS will check periodically for it to become available If you use a daytime server the time of day will be set but not the current date To correctly report both the date and time use the Change Timeserver command to configure your MSS for NTP with
44. t Getting Started 13 Example 6 Autorun Mode 5 On the UNIX terminal type some data and hit Return You should see the data on the serial terminal You should also see some status messages on your PUC session 6 On the serial terminal type some data and hit Return You should see the data on the UNIX terminal You should also see some status messages on your PUC session 7 Quit the Telnet session Your MSS should display the following Transferred xx bytes closing socket waiting for connection At this point the server is waiting for new connections 3 7 Example 6 Autorun Mode 3 7 1 Autorun Overview Once you have verified that your application works you can tell the MSS to run the code at each startup Autorun mode is similar to running a file in command line mode but you must add the auto flag 1 Specify the file you wish to run Place the auto flag between cc and the name of your c file Local cc auto myapp c PUC Autorun is Enabled Local The code must be stored either on the MSS flash disk or on the loadhost in tftpboot puc If you place code on the MSS ram disk it will be cleared before the MSS reboots Note Put a DDEFINEME between cc and the filename to define the DEFINEME macro You can also specify arguments after the filename if your function is defined to accept arguments Arguments are passed using the standard C argc and argv variables Once you enable autorun mode stdin
45. t information is noted in Appendix A Note To view a list of available MSS commands type Help at the Local prompt For help when PUC is running in interactive or command line mode type help at the PUC n gt prompt 4 1 Errors 4 1 1 Common C Language Errors Flow reaches end of non void function You will get an error if there is no return statement in main when it has been declared to return a value Local_2 gt gt cc test c PUC Compiling lt test c gt PUC looking for lt puc test c gt on TFTP host Warning in test c near line 13 Flow reaches end of non void function main Incorrect function usage You will get an incorrect function usage error if you forget to include the proper header file such as lt startpuc h gt before calling a function such as printf PUC 2 gt printf hello Error in PUC near line 2 Incorrect function usage printf 4 1 2 Common Linking Errors Couldn t find You will get a couldn t find error if the file such as test c was not found in the search path Local_2 gt gt cc test c UC Compiling lt test c gt UC looking for lt puc test c gt on TFTP host SError Couldn t find lt test c gt P P Access violation You will get an access violation error is the file you specify such as test c does not have world read permissions Local 2 cc test c UC Compiling test c UC looking for lt puc test c gt on TFTP host
46. tal blood sugar meter has a serial port and it is able to send sugar level updates out of its serial port at regular intervals You attach the meter to an MSS You then write an application that checks for low sugar levels and creates and sends an email to alert hospital staff of the low sugar condition You can also write an application that keeps track of sugar level data over time runs statistics on it or saves it to a file A hospital worker or lab technician could transfer the data from the MSS to his or her own PC via FTP for further analysis The most important part of the Lantronix SDK is a set of software in the MSS called PUC Portable Universal C that provides a C language environment for programming The user writes standard C code with some limitations The MSS compiles the C code into a bytecode and then executes the bytecode The Lantronix SDK also includes documentation sample code and an OEM customization guide to assist developers in writing their own applications for the MSS 1 1 1 Who Would Use the Lantronix SDK The SDK is for anyone who needs customized software that is not available on the MSS whether it be a network wrapper for a serial device a custom protocol or a non standard means of access or control such as generating email transferring a file via FTP or creating an SNMP MIB Using the SDK comfortably requires some experience with programming in C SDK users should have experience using file I O
47. tart unpv12e html C 2 EiC Documentation Portable Universal C PUC is based on Extensible interactive C E1C The most current version of the EiC documentation can be found on the World Wide Web at http www anarchos com eic C 3 Other Useful Sources The following reference materials were not directly used to complete this manual but are valuable resources for C programmers You may wish to refer to these books for additional help Note UNIX users can look for specific terms in the UNIX man pages TCP IP Illustrated Stevens W Richard TCP IP Illustrated Volume I The Protocols 1984 Addison Wesley Longman Inc Reading MA USA ISBN 0 201 63346 9 The C Programming Language Kernighan Brian and Dennis M Ritchie The C Programming Language 2nd Ed 1998 Prentice Hall PTR Englewood Cliffs NJ USA ISBN 0 13 110362 8 paperback ISBN 0 13 110370 9 hardcover 43 A abort 26 abs 26 accept 33 asctime 35 assert 35 atexit 26 atoi 26 atol 26 bind 33 bsearch 26 C calloc 26 chdir 29 chmod 32 clearerr 31 clock 35 close 29 closedir 34 connect 33 creat 29 ctime 35 D difftime 35 dup 29 E exit 26 F fclose 31 fentl 29 feoff 31 ferror 31 fflush 31 fgetc 31 fgetpos 31 fgets 31 fileno 31 fopen 32 fprintf 32 fputc 31 fputs 31 fread 31 free 26 Function List fseek 31 fsetpos 31 fstat 32 ftell 31 fwrite 31 G getc 32 getchar 31 gethostbyname 33 gethostname 33 getprot
48. tdio h unp h limits h stdlib h Note Do not rely on the values of any constants in the header files They may change in future releases of the SDK 25 Standard Library Functions The header files unp h and lt startpuc h gt include other header files Therefore many of the functions de scribed in this chapter can be gained from including either unp h or lt startpuc h gt in your program Basically lt startpuc h gt includes all non socket files and unp h includes lt startpuc h gt and the socket related files Note unp h includes lt startpuc h gt includes startpuc h gt stdio h string h time h netdb h stdlib h limits h unistd h netinet in h ctype h assert h termios h sys socket h dirent h errno h fentl h sys stat h The error Incorrect Function Usage usually means that the function hasn t been prototyped which means that you haven t included the necessary header files For sockets and general usage you should only have to include unp h it will include everything you need 6 2 Standard Library Functions lt stdlib h gt Standard Library Functions ANSI abort abs atexit atoi atol bsearch calloc exit free labs malloc qsort realloc rand srand strtol strtoul 26 void abort void Abort program without running atexit functions int abs int Return absolute value of int int ate
49. ter a 3 digit number The first digit represents the owner s permissions The second digit represents the group s permissions The third digit represents the world s permissions Local gt gt DISK CHMOD 755 flash index txt Digit Meaning 0 No permissions 1 Execute permission only 2 Write permission only 3 Write and Execute permissions 4 Read permission only 5 Read and Execute permissions 6 Read and Write permissions 7 All permissions 40 Disk Management Disk Commande DISK CP file1 file2 Allows you to copy or move a file To copy a file enter the filename for file and the new file name as file2 To move a file specify the filename as file and the destination directory as file2 The following examples rename a file and then move it to a new directory Local gt gt DISK CP customapp txt app txt Local gt gt DISK CP app txt ram DISK DF disk Displays the blocks of free disk space on the MSS disks When you add the i switch the display in cludes in the display the number of inodes used versus the number still available Local gt gt DISK DF i flash DISK FSCK Checks the MSS filesystem and corrects any problems Local gt gt DISK FSCK DISK FORMAT FLASH Allows you to format or erase the MSS flash disk Local DISK FORMAT FLASH DISK LN flag file1 file2 Creates a hard or soft link for files thus linking a file or set of files to another file Us
50. the appropriate GMT offset Local gt gt CHANGE TIMESERVER NTP BROADCAST Local gt gt CHANGE TIMESERVER GMTOFFSET 7 In the example above the Broadcast keyword could be replaced with the IP keyword and the numeric IP ad dress of the desired timeserver that is CHANGE TIMESERVER NTP IP 192 0 1 22 lt unistd h gt Time Functions ANSI sleep ulong sleep ulong seconds lt unistd h gt Time Functions Non ANSI sleepMS ulong sleepMS ulong milliseconds NOTE The system clock on the MSS doesn t allow precision timing for inter vals less than 20msec 34 API Reference Debugging Functions lt time h gt Time Functions ANSI asctime char asctime struct tm ts ASCII date time from time structure ctime char ctime ulong rv ASCII date time gmtime struct tm ts gmtime ulong rv Time structure for current Greenwich Mean localtime struct tm ts localtime ulong rv Time structure for current local time mktime ulong rv mktime struct tm ts Time in seconds from a time structure time ulong rv time NULL amp rv Seconds since 1 1 1970 learned from NTP RTC daytime etc Daytime servers will update the time of day but not the date Note If you are using NTP and time NULL returns a value less than 914544000 Jan 1 1999 then the time should be ignored because it cannot be valid lt time h gt Time Functions Non ANSI
51. to an arbitrary host The host is either a text hostname if there is a DNS available for name resolution or an ASCII string host IP address If rv lt 0 there was an error snmp Write int rv snmpWrite int fd char reply_pkt Replies to the last read packet int len If rv lt 0 there was an error call snmpDeregister and start over Note If your application does not know how to handle a packet it should be configured to send the appropriate SNMP error frame back to the sender The MSS will not reply to any SNMP queries accepted by a custom application 36 API Reference A Technical Support A 1 The SDK Support Plan Lantronix supports the SDK on a fee basis Please consult your service agreement or contact Lantronix at 949 453 3990 for more information SDK Sales TBD Internet sdk sales lantronix com SDK Support TBD Internet TBD A 2 Problem Report Procedure When you report a problem please provide the following information Your name and your company name address and phone number Lantronix MSS model number Lantronix MSS serial number Software version use the Show Version command to display Network configuration including the information from a Netstat command Description of the problem Example source code that demonstrates the problem Debug report stack dump if applicable Status of the unit when the problem occurred please try to include information on user and network activi
52. ty at the time of the problem A description of the serial device connected to the MSS serial port if applicable 37 Other Contact Information A 3 Other Contact Information Address 15353 Barranca Parkway Irvine CA 92618 USA Phone 949 453 3990 Fax 949 453 3995 World Wide Web http www lantronix com North American Direct Sales 800 422 7055 North American Reseller Sales 800 422 7015 North American Sales Fax 949 450 7232 Internet sales lantronix com International Sales 949 450 7227 International Sales Fax 949 450 7231 Internet intsales lantronix com Technical Support 800 422 7044 or 949 453 3990 Technical Support Fax 949 450 7226 Internet support lantronix com 38 Technical Support B Disk Management B 1 Overview The Disk commands are very similar to the file management commands in UNIX environments If you are not familiar with UNIX environments refer to an introduction to UNIX before you proceed Note Unlike the similar UNIX commands each disk command must be preceded by the word DISK Each of the MSS disks support all of the commands listed in this appendix unless otherwise noted Some of the Disk commands support the various flags used by the same UNIX command Additionally flags can be grouped together For example 1t would be equivalent to 1 and t Some of the Disk commands support the UNIX wildcard convention When you enter a into a command it specifies that the command wi
53. ue of t PUC 4 printf t sdinXr t t 7 returned 5 PUC 5 gt In this case t is still 7 so the printf statement causes PUC to display t 7 The following line is the return value of the printf statement There are 5 characters printed including the in and V newline characters so the number 5 is displayed Getting Started 9 Example 2 More Interactive Mode 7 Use the PUC show command to get more information about the printf statement PUC 5 gt show printf printf gt Builtin Func fmt constchar returning int void PUC 6 gt PUC displays the prototype definition of the function 8 Take a break from PUC for a moment Create a file on your loadhost that contains the following code and save it as examplel c under tftpboot puc Make sure the file has 664 permissions include lt startpuc h gt void main int t t 15 printf t dinir t You can use any text editor to create the file If you use a word processor be sure to save the file as plain text otherwise the formatting commands and other spurious characters will confuse PUC 9 Now go back to your PUC session and read in examplel c PUC 6 gt include examplel c returned void PUC 7 gt PUC will load the file from your TFTP loadhost and interpret the file but will not execute main yet 10 Execute the main function PUC 7 gt main t 15 returned void PUC 8 gt The return va
54. uses a TFTP loadhost The rest of the con figuration in this section is optional or only required for certain situations Local gt gt CHANGE LOADHOST 192 0 1 123 Touse the functions gethostname and gethostbyname you must set a nameserver It is also a good idea to set a secondary nameserver in case the primary one is unavailable and a default domain name ocal gt gt CHANGE NAMESERVER 192 0 1 55 local gt gt CHANGE SECONDARY NAMESERVER 192 0 1 56 ocal gt gt CHANGE DOMAIN supercorp com e Touse the function time you must set a timeserver NTP servers give date and time information Day time servers give only time of day information Choose one of the following sets of commands Ocal gt gt CHANGE TIMESERVER NTP 192 0 1 101 ocal gt gt CHANGE TIMESERVER GMTOFFSET 1 Oocal gt gt CHANGE IMESERVER DAYTIME 192 0 1 102 UNIX Installation To speed reboots of the MSS you may wish to temporarily disable BOOTP and RARP queries How ever keep in mind that EZWebCon cannot set the IP address of a server that has BOOTP disabled Local gt gt CHANGE BOOTP DISABLED Local gt gt CHANGE RARP DISABLED e To prevent hosing up attached serial devices turn off boot messages Local gt gt CHANGE SILENTBOOT ENABLED 2 3 UNIX Installation This section assumes familiarity with the UN
55. xample write a custom PC card driver for the MSS VIA Third there is no access to the core of the MSS operating system You would not be able to implement your own non IP protocol stacks 1 2 What is PUC Portable Universal C PUC is the interactive online bytecode interpreter that executes the C code you write for the MSS PUC is an implementation of Extensible Interactive C EiC a command line interpreted C PUC shares some of EiC s limitations but also adds APIs that were not included in EiC such as a Berkeley sockets library and SNMP functions Note For more information about EiC see Appendix C 1 2 1 Differences from C PUC generally functions the same way as regular C functions file I O header files pointers and sockets are all available Chapter 6 API Reference lists all of the functions that are currently available The products that currently support the SDK the MSS models are all big endian hardware However future implementations of the SDK will be available on little endian hardware SDK developers should use the supplied functions htonl ntohl etc to ensure that communications with external devices will work regardless of the byte ordering of the hardware 1 2 2 Limitations There are a few significant limitations to PUC PUC does not support float and double data types forking child processes labels signals or gotos due to size limitations Some older prototype definition styles are not unde
56. xit void f void Set a function to run at exit time int atoi const char s String to integer long atol const char s String to long void bsearch const void key const void base Binary search a sorted list Size t nelem size t size int _cmp const void keyval const void datum void ptr calloc size t nelem size t elsize Allocate memory init to zero void exit int eval Exit your program returns eval void free void ptr Free memory block long labs long Return absolute value of long void ptr malloc size t size Allocate uninitialized memory void qsort void base size t n size t size int Quicksort function cmp const void const void void ptr realloc void ptr size t size Resize memory block int rand void Generate a random number from 1 to RAND MAX void srand unsigned int seed Seed the random number generator long strtol const char str char endptr int base String to long int unsigned long strtoul const char str endptr char int base API Reference Str to ulong String Functions lt stdlib h gt Standard Library Functions Non ANSI itoa ltoa ultoa utoa char itoa int n char str int radix Integer to string char ltoa long n char str int radix Long int to string char ultoa ulong n char str int radix Unsigned long to string char utoa
57. y have to cycle power on the MSS Getting Started Example 2 More Interactive Mode 3 3 Example 2 More Interactive Mode This example expands your understanding of interactive mode by looking at return values and teaching you how to write and execute your own code snippets User entries are bolded if you wish to follow along enter the bold items into your Telnet window 1 2 Telnet into your MSS enter a username and become the privileged user Enter PUC s interactive mode by typing cc at the Local gt prompt You will see the PUC gt prompt for the remainder of this example Include the header file lt startpuc h gt PUC 1 gt include lt startpuc h gt returned void PUC 2 Notice that a returned line is displayed below the command line before the next prompt Normally returned displays the return value of the item entered In this case void means that there is no return value for the include entry Declare an integer named t PUC 2 gt int t returned void PUC 3 gt Assign integer t a value of 7 PUC 3 gt t 7 returned 7 PUC 4 gt PUC will display the value of t before the next prompt Since you just assigned t s value as 7 PUC returns 7 After you assign a value to an integer you can check the value by entering the integer name followed by a semicolon PUC 3 t returned 7 PUC 4 Enter the following printf statement which also shows you the current val
58. y loads wrapper c which includes a series of error trapping wrapper functions for many common commands All of the wrapper functions are named for the command they wrap with the first letter capitalized For example Close wraps the built in command close network do buffer c tcpserv c also requires the inclusion of function do socket It calls this function whenever a new client connects to the server In this case you would load the file network do_buffer c which opens the serial port in nonblocking mode sets the network socket to nonblocking mode and then watches them both for incoming data Incoming network data is sent out the serial port immediately while incoming serial data is buffered until a specified stop character is read or a certain amount of time has passed with no data received Put the 3 files listed above into tftpboot puc Load the files into PUC Note that you do not have to load wrapper c it is loaded automatically by tcpserv c Local 2 cc PUC Interactive mod type help for help or exit to exit PUC 1 include tcpserv c PUC Looking for puc tcpserv c on TFTP host returned void PUC 2 include do buffer c returned void PUC 3 Start your new server running on the MSS PUC 3 main waiting for connection Connect to the new server from a UNIX host telnet mymss100 9877 HI Back on the PUC session you will see the message Accepted socke
59. y supports a single character mode r w or a and files are always opened in binary mode No text translation takes place See Section 1 2 3 int fprintf FILE fp const char fmt D Formatted print to file stream NOTE None of the printf scanf functions support float or double variables int getc FILE fp Get character from file NOT implemented as a macro int printf const char fmt Formatted print to console int putc char c FILE fp Put character to file NOT a macro int puts char str Print string to console automatically adds n r int sscanf const char str const char fmt 5 Formatted scan from string See Section 1 2 3 int setbuf FILE fp char buf Can only be used set buffer to NULL See Section 1 2 3 int int Sprintf char buf vfprintf FILE args const char fmt fp const char fmt s va_list Formatted print to string Print formatted output of varargs to file varargs int vprintf const char fmt va list args Print formatted output of varargs int vsprintf char str const char fmt args va list Print formatted output of varargs to string varargs lt sys stat h gt I O Interfaces File and Serial Non ANSI chmod fstat mkdir stat 32 int chmod const char path mode t mode Change mode of file int
60. yname SERVENT getservbyname const char servname const Look up service name char protoname getsockname int getsockname int sockfd struct sockaddr name Get socket name int namelen inet_addr unsigned long inet_addr char cp ASCII to internet address inet_ntoa char inet ntoa unsigned long struct in addr in Internet address to ASCII listen int listen int fd int backlog Set to accept queue recv int recv int fd char buf int len int flags Read message from connected socket recvfrom int recvfrom int fd char buf int len int flags Read from any socket struct sockaddr in from int fromlen send int send int fd char msg int len int flags sendto int sendto int fd char msg int len struct sockaddr in to int tolen int flags Write to connected socket Write to any socket setsockopt int setsockopt int fd int level int optname optval int optlen char Set socket options shutdown int shutdown int s int how Shut down a socket socket int socket int domain int type int protocol Create a socket endpoint lt netinet in h gt Network Socket Functions Non ANSI htonl ulong htonl ulong Host to network byte order long htons ushort htons ushort Host to network byte order short ntohl ulong ntohl ulong Network to host byte order long ntohs ushort ntohs ushort Network to host byte order shor
61. your MSS Installation Guide and the MSS Reference Manual Installing the PUC Files 3 Getting Started This chapter contains several development examples that will teach you how to use PUC The explanations and examples in this chapter assume that you have followed the instructions in Chapter 2 for installing the PUC files on your loadhost Example 1 Simple Hello World page 8 Example 2 More Interactive Mode page 9 Example 3 Serial Output page 11 Example 4 Network Socket Connection page 12 Example 5 Network Serial Combination page 13 Example 6 Autorun Mode page 14 3 1 How to Run PUC You can use PUC in three different modes interactive command line and autorun The examples in this chapter detail all three modes You start interactive mode by typing cc at the MSS Local prompt See Examples 1 2 Then you enter instructions one at a time at the PUC gt prompt PUC will execute each instruction as it is entered and show return values which is useful for debugging Use this mode for general development In command line mode you execute an existing C code file by typing a single command line at the Local prompt see Examples 3 4 PUC will execute the program immediately and only once Use this mode to test nearly finished applications Command line arguments can follow the source filename They will be passed to the program as standard argc and argv arguments to the main function In aut
62. ytes in octal format ct Prints the bytes in ASCII format X Prints the bytes in hexadecimal format Local gt gt DISK OD x unp h DISK PWD Shows you the full pathname of your current directory Local DISK PWD DISK RM flag file Removes files and or directories from the MSS RAM and Flash disks i Prompts for a Y yes or N no before the file is removed T Removes an entire directory and all of its subdirectories Local DISK RM i unp h DISK RMDIR directory Removes a directory on the MSS RAM or Flash disks This command can only be used if the directory is empty If the directory is full you must add the DISK RM rf directory command Local DISK RMDIR flash customapps DISK SYNC Forces the MSS to write files to flash immediately Normally when the MSS is rewriting files to the Flash disk it will buffer data before initiating a write sequence Write sequences are automatically writ ten after 5 seconds of disk inactivity Local DISK SYNC 42 Disk Management C References C 1 Stevens Network Examples All example code referred to as Stevens in this manual is taken from the following book Stevens W Richard UNIX Network Programming 2nd Ed Volume I Networking APIs Sockets and XTI 1998 Prentice Hall PTR Upper Saddle River NJ USA ISBN 0 13 490012 X Source code is available from the following WWW address http www kohala com s
Download Pdf Manuals
Related Search
Related Contents
Frühjahrsprogramm 2014 - Deutsches Institut für Erwachsenenbildung Philips SpotOn Ultra LED Copyright © All rights reserved.
Failed to retrieve file