Home

S.Ha.R.K. User Manual Volume II PROGRAMMING LIBRARIES

image

Contents

1. Description It sends an UDP packet with size nbytes whose body is pointed by buf to an address specified by to The last parameter has UDP_ADDR type and identifier either the destination IP address or the port see udp_bind for further information on UDP_ADDR In order to send a packet a local socket has to be created by calling the udp_bind primitive its identifier shall be passed by the s parameter Example void txsessiontask void arg int sock UDP_ADDR local to socket creation for 55 prepares the destination address to s_port 1030 ip_str2Addr 127 0 0 1 amp to s_addr udp_sendto sock msg msglen amp to task_endcycle UDP RECVFROM int udp_recvfrom int s char buf UDP_ADDR from Description It receives a UDP packet from the socket identified by s the packet body is copied into the buffer pointed by buf the sender address composed of the pair port IPaddress is copied into the variable pointed by from The primitive returns the number of bytes composing the packet Example 37 TASK rxsessiontask 4 int sock UDP ADDR local from The non real time rxsessiontask creates a receiving socket and enters an infinite loop waiting for the incoming packets During initialization the socket is created for udp recvfrom sock inmsg amp from from contains the sender address task endcycle UDP_NOTIFY int udp_
2. Description It fills the header of the frame pointed by b with the destination address dest and the frame type type It also returns a pointer to the body of the ethernet frame ETH GETFDB void eth getFDB void p 41 Description Get First Data Byte It returns a pointer to the body of the frame pointed by the p parameter ETH SENDPKT int eth sendPkt void p int len Description It transmits the Ethernet frame pointed by p having lenght 1en The destination and the frame type must be previously specified using eth setHeader Example void arp sendRequest int i 1 ARP_PKT pkt ETH_ADDR broadcast nulladdr eth_str2Addr FF FF FF FF FF FF broadcast eth str2Addr 00 00 00 00 00 00 amp nulladdr eth setHeader arpBuff broadcast ETH_ARP_TYPE pkt ARP_PKT eth_getFDB arpBuff pkt gt htype htons ARP_ETH_TYPE pkt gt ptype htons ARP IP TYPE pkt gt hlen sizeof ETH ADDR pkt gt plen sizeof IP ADDR pkt gt operation htons ARP REQUEST setEthAddr pkt gt sha myEthAddr setEthAddr pkt gt tha nulladdr set IpAddr pkt gt sip myIpAddr set IpAddr pkt gt tip arpTable i ip eth_sendPkt arpBuff sizeof ARP_PKT ETH CLOSE int eth close void Description It closes the Ethernet protocol If it is not explicitly called by the user it is automat ically executed through sys atexit 42 Chapter 8 The CMOS real time clock In all PCs there is a real
3. Description Reset the internal speaker making it silent 23 Chapter 4 The Frame Buffer Library The S Ha R K system provides support for all modern SVGA cards through the Linux Frame Buffer driver Using the grx graphic library upon it is possible to draw points lines rectangles boxes circles and text on 16 bit per plane bpp SVGA graphic modes In order to use graphics a program must include the drivers shark fb26 h header file Then it must initialize the Frame Buffer using FB26_init At this point the drawing library must be connected to the frame buffer with the function FB26 use grx Now a graphic mode can be opened using FB26 setmode and then the drawing functions can be used The num number needed as a parameter indicate which frame buffer is used At the end the program can switch back to text mode through FB26 close FB26 INIT int FB26_init void Description It initializes the rame buffer and internal data structures to access the hardware The function returns 1 on error 0 otherwise In order to use the graphic primitives a program must call this function FB26 OPEN int FB26 open int num Description Open the frame buffer number num The function returns 1 on error O otherwise The frame buffer must be already initialized with FB26 init FB26 SETMODE int grx setmode int num unsigned chat mode Description It opens the graphic mode identified by the mode parameter The mode num
4. MOUSE_PARMS mouse BASE_MOUSE mouse initialization MOUSE26_init amp mouse a resolution of 640x480 is used mouse setlimit XMINLIMIT 640 480 YMINLIMIT 640 480 XMAXLIMIT 640 480 YMAXLIMIT 640 480 initial position mouse_setposition 320 280 mouse threshold mouse_setthreshold 2 my new mouse shape mouse grxshape my mouse cursor my mouse mask 2 automatic graphics mouse cursor enabled mouse grxcursor ENABLE 2 mouse displayed into the screen mouse on a MOUSE OFF MOUSE ON void mouse_off void void mouse_on void Description This functions disables and enables the display of the mouse cursor on the screen the mouse events are handled Warning These functions must be called before after calling any graphic function that modifies the screen 3 3 The joystick library In order to use the gameport handling functions the drivers shark_joy26 h header file containing the interface functions prototypes has to be included in the application program First of all the joystick needs be initialized by the calling JOY26_init primitive into the __init__ function in the initialization file or in any other point of the application code 21 ATTENTION The driver only work with gameport that emulate the old SoundBlaster gameport interface Other kind of gameports will not be identified JOY26 INIT int JOY26_init void Description I
5. VIDEODEV26_open FRAME_GRABBER_NUMBER Select the input channel res VIDEODEV26_ioctl FRAME_GRABBER_NUMBER VIDIOCGCHAN unsigned long amp chan chan channel channel chan type VIDEO_VC_TUNER chan norm VIDEO TYPE CAMERA res VIDEODEV26_ioct1 FRAME_GRABBER_NUMBER VIDIOCSCHAN unsigned long amp chan 29 Enable the tuner tuner tuner 0 tuner mode VIDEO MODE PAL res VIDEODEV26_ioctl FRAME_GRABBER_NUMBER VIDIOCSTUNER unsigned long amp tuner Select palette and depth res VIDEODEV26_ioctl FRAME_GRABBER_NUMBER VIDIOCGPICT unsigned long amp vpic ifdef COLOR vpic palette VIDEO PALETTE RGB24 vpic depth 24 else vpic palette VIDEO PALETTE GREY vpic depth 8 endif vpic brightness 35000 vpic hue 32000 vpic contrast 32000 vpic colour 32000 res VIDEODEV26_ioctl FRAME_GRABBER_NUMBER VIDIOCSPICT unsigned long amp vpic Set window dimensions res VIDEODEV26_ioctl FRAME_GRABBER_NUMBER VIDIOCGWIN unsigned long amp win win x O win y 0 win width FG_W win height FG_H res VIDEODEV26_ioctl FRAME_GRABBER_NUMBER VIDIOCSWIN unsigned long amp win Set the buffer res VIDEODEV26_ioct1 FRAME_GRABBER_NUMBER VIDIOCSFBUF unsigned long fbuf IMPORTANT Set the aperiodic elaboration task When the new frame is ready the task elaborate PID aperiodic is activated VIDEODEV26 ioct1 FRAME GRABBER NUMBER VIDIOCSYNC unsigned long
6. Description It send the command cmd with argument arg to the device number num Return value It depends from the command executed 5 2 1 Video Devices Commands This is a list of most commond videodev commands Most of them are supported by the BTTV low lever driver There is only a major change implemented during the porting phase the VIDIOCSYNC function requires an aperiodic task PID as input When the new frame is ready the task is activated The full command list is VIDIOCSYNC Synchronize with memory mapped capture VIDIOCGCAP Get video radio device capabilities VIDIOCGCHAN Get source properties VIDIOCSCHAN Select source and set properties VIDIOCGTUNER Get tuner properties VIDIOCSTUNER Select tuner and set properties VIDIOCGPICT Get video image picture properties VIDIOCSPICT Set video image picture properties VIDIOCCAPTURE Enable or disable video capturing VIDIOCGWIN Get video output window properties VIDIOCSWIN Set video output properties VIDIOCGFBUF Get direct video output frame buffer properties VIDIOCSFBUF Set direct video output frame buffer properties VIDIOCGFREQ Get tuner frequency property VIDIOCSFREQ Set tuner frequency property i e tune to new frequency VIDIOCGAUDIO Get audio properties VIDIOCSAUDIO Set audio properties VIDIOCMCAPTURE Initiate memory mapped capture VIDIOCGMBUF Get memory mapped buffer properties Example Init videodev driver
7. grx getimage 26 grx getpixel 25 grx_line 26 grx_plot 25 grx putimage 25 grx_rect 26 grx_text 26 htons 40 INPUT26_init 9 ip_str2addr 35 isCentralButton 18 isLeftButton 18 isRightButton 18 JOY26 close 22 JOY26_init 22 JOY26 installed 22 joy disable 22 joy enable 22 joy getstatus 22 joy setstatus 22 KEY EVT structure 14 KEYB26 close 11 KEYB26_init 11 KEYB26_installed 11 keyb def ctrlC 12 keyb def map 12 keyb def task 12 keyb default parm 12 keyb_ disable 14 keyb_enable 14 keyb get map 14 keyb getch 12 keyb getchar 12 keyb getcode 12 keyb hook 13 keyb set map 14 linuxc26 register module 7 MOUSE26 close 15 MOUSE26_init 15 MOUSE26_ installed 15 mouse def task 16 mouse default parm 15 mouse disable 17 mouse enable 17 MOUSE EVT structure 18 mouse _ getlimits 17 mouse getstatus 17 mouse getthreshold 17 mouse _ grxcursor 19 mouse grxshape 19 mouse hook 17 mouse off 21 mouse on 21 mouse _ setlimits 17 mouse setstatus 17 mouse setthreshold 17 mouse _txtcursor 19 mouse txtshape 19 mousedef def threshold 16 mousedef def x0 16 mousedef def xmax 16 mousedef def xmin 16 mousedef def y0 16 mousedef def ymax 16 mousedef def ymin 16 mousedef def z0 16 net init 34 netbuff_get 40 netbuff init 39 netbu
8. The File Management 12 The Snapshot Library eo 28 28 28 29 31 31 32 34 43 44 49 51 53 Chapter 1 Introduction Device drivers are a critical part of Real Time Systems Trying to fit an IRQ and a timer handler coming from a device inside a task context it is a priority for OS like S Ha R K If we design these drivers considering possible preemptions exectution times and other Real Time contraints a schedulability test can guarantie our system Buf if we must reuse a source code from third party drivers makers without having no knowledge about the driver timing behaviour with possible non preemptable critical section it is very difficult to impose contraints for a schedulability analisys The S Ha R K drivers are mainly ported from Linux 2 6 We projected and tested a Linux 2 6 Emulation Layer This Layer gives an indipendent environement where it is possible to compile the original drivers without conflicts with S Ha R K and OSlib An interface glue code allows to access the drivers API S Ha R K Kernel DRIVER HARDWARE i The Emulation Layer needs a specific kernel module to run This module has two important objectives e To create an high priority execution context for the drivers IRQ and timer handlers e To maintain the drivers behaviour inside specific Real Time constraints avoiding that a possible malfuncition or resource abuse cause a system failure Both of these points are guar
9. elaborate PID 30 Chapter 6 The CPU frequency scaling library This driver allow the application to change the CPU speed in order to reduce power consumption After the driver initialization is possible to know the list of supported frequencies the minimin and maximun allowed frequncy Is possible to get and set the current frequecy and obtaind the deoretical value of the transition duration 6 1 CPU Information utility These functions allow the application to know informations about the CPU like manufacturer model capabilities etc CPU26 INIT int CPU26_init void Description Initialize the driver and all internal structures The function returns 0 if the procedure was succesfully 1 otherwise CPU26 CLOSE int CPU26 close void Description It close the CPU driver Return value 0 if the operation is performed successfully 1 if the keyboard in not installed CPU26 INSTALLED int CPU26 installed void Description Return if the event debugger is actually installed Return value 0 if the module is installed 1 otherwise CPU26 SHOWINFO void CPU26_installed void Description Print the CPU informations retrived by the driver 31 6 2 CPU scaling functions These functions allow to get set parameter about the CPU frequency and its behavior The low level must be initialized with the CPU26 init function before using scaling funtionalities CPU26 DVS INIT int CPU26_DVS_init void Des
10. the acquisition board hardware control and supplies a generic interface for the higher level The second layer supplies some API function for a comunication between the application and a generir video device framegrammer webcam etc 5 1 BTTV low lever driver At the actual stage of developement is the only low lever driver ported from Linux to S Ha R K Support acquisition boards based on BookTree BT8x8 chips Presents only 2 functions for opening and closing cards BTTV26 INIT int BTTV26_init void Description It initializes the acquisition board interface and the library s internal data structures BTTV26 CLOSE int BTTV26_close void Description It close the acquisition board interface 5 2 VideoDevice high lever interface This library supplies an abstract layer created to obtain a common interface between different low level driver The interaction with an application is quite simple and implies only 2 functions the first one open the comunication between the application and the hardware through the low level driver the second one send commands to the device VIDEODEV26 OPEN int VIDEODEV26 open int num Description It initializes the acquisition board interface and the library s internal data structures The parametetr num define the device that must be opened 28 Return value 0 if the module is installed 1 otherwise VIDEODEV26 IOCTL int VIDEODEV26 ioctl int num unsigned int cmd unsigned long arg
11. the ASCII code of any stroken key by calling the keyb_getch function This function requires a parameter which determines whether the task should block until a key is hit or not In the latter case if no key has been hit the function returns O behaving like kbhit If we are interested in the key s scan code we can call the keyb getcode function which returns a struct containing either the scan code or the ascii code and a byte containing information on the ALT SHIFT or CTRL key being pressed The following code shows an example of usage for the function Example KEY EVT k if keyb getcode amp k NON BLOCK 4 if isRightCtrl k isLeftCtrl k amp amp k ascii x Ctrl x has been pressed Finally it is possible to define a function to be automatically called every time a specific key or a specific combination of keys is pressed This is done by calling the keyb_hook function which receives as arguments a data structure containing the required combination of keys and the function to be called KEYB26 INIT int KEYB26_init KEYB_PARMS parms Description It initializes the keyboard interface and the library s internal data structures It can be called using NULL as parms to initialize the keyboard interface to default values Note that to be proper initialized you need also to initialize the HARTPORT modules Return value 0 if the operation is performed successfully a value les
12. the UDP IP stack on an Ethernet network The library is organized in three layers e low level driver this layer is hardware dependent since it interacts with the network card e ethernet layer this layer allows the upper layer to send and receive ethernet frames Tt is not intended to be used by a user program but only by the code implementing the network protocol e high level layer this layer implements the network IP and the transport UDP protocols Tt provides the interface used by a user program to access the network through the UDP protocol The low level driver is implemented in order to respect the system real time requirements avoiding unpredictable delays in sending receiving frames This result is achieved by solving two different problems the interrupt handling in the receive phase and the mutual exclusion needed for accessing the network card in the transmission phase The first problem is solved by using a SOFT task to handle the network card interrupts on a frame arrival a task handling the reception is activated Such a task is guaranteed along with all the other tasks in the system thus it cannot jeopardize their schedulability Since a minimum interarrival time for the frames cannot be predicted the receiving task cannot be a sporadic HARD task therefore the task uses a SOFT TASK MODEL and we have used a Constant Bandwidth Server CBS to serve it The second problem can be solved using two different method
13. tick Description It initializes the audio driver by allocating the internal buffer for the DMA Double buffering and DMA Self Buffering modes The rawbufsize parameter contains the dimension of this buffer Higher values reduce the CPU load and are thus advised when using the DMA Double buffering mode Lower values on the contrary can be used to shorten the latency between sampling and data delivering particularly when using DMA Self buffering The tick parameter contains the value of the system tick its correctness is fundamental for the PIO mode SOUND INFO void sound info void Description It outputs on the screen some information concerning the soundcard and the drivers SOUND SETFUN void sound setfun int infun BYTE rawbuff int outfun BYTE rawbuff Description It specifies the functions to be called when the DMA finishes working on one of the two internal buffer s halves when using DMA Self Buffering mode The function pointed by infun is used when performing sampling operations whereas outfun is used for playing operations Both functions receive a pointer to the hal buffer not currently acted upon by the DMA the half buffer sizes are equal to one half of the sound_init parameter and have to return O if the operation has not yet been finished 1 if it is going to finish in the next DMA cycle and 2 if it finishes immediately Attention should be paid to the fact that these functions are periodically call
14. time clock with a resolution of 1 second that can be read or written This clock usually has a drift of about some seconds in 24 hours The following functions that can be found into rtc h can be used to set get values all values are passed using a struct rtc time that contains variables for seconds minutes hours days months and years GET RTC TIME int get rtc time struct rtc time time Description The actual time is read from the CMOS real time clock and written into the structure pointed by time The function returns zero on success other values on error SET RTC TIME int set rtc time struct rtc time time Description The values contained in the structure pointed by time are converted in seconds and written into the CMOS real time clock the function returns zero on success other values on error RTC TIME Description it is a data structure containing the following fields tm sec seconds from 0 to 59 tm min minutes from 0 to 59 tm hour hours from 0 to 23 tm mday day from 1 to 31 tm mon month from 1 to 12 tm year year is an integer number no Y2K problem tm wday day of the week from 1 to 7 tm yday day of the year from 1 to 365 tm_ isdst 0 if legal hour 1 if solar hour not used yet 43 Chapter 9 The Sound Library If a SoundBlaster16 sound card is available S Ha R K allows to sample and play sounds by using the functions provided by the sound library The library current
15. with 2 BYTE for pixel 19 WHITE RED GREEN and MAGENTA are defined into lt cons h gt define W rgb16 255 255 255 define R rgb16 255 0 0 0 define G rgb16 0 255 define M rbg16 255 0 255 mouse shape 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 W W W W 0 0 0 0 0 0 W W W W O 0 W M 0 0 0 0 0 0 0 0 0 0 M W 0 0 W 0 M 0 0 0 0 0 0 0 0 M 0 W 0 0 W WORD my_mouse_cursor 16 16 0 0 M 0 0 0 0 0 0 M 0 0 W 0 a ooo ooo ooo ooo ooo o Su SU SU Su do ooo ooo ooo 33 0 0 0 0 0 M M M M 0 0 0 0 0 0 0 0 0 0 0 M M M M 0 0 0 0 0 0 Soo Soo Soo Soo sso o Sao o Sao Sao Sao sso Soo Soo 33 SoooooooOooSoo o mask for pixels 2 bytes in this case Oxffff means that the background image is used 0x0000 means tha the background image is cleared prior to draw the mouse cursor define F Oxffff define B 0x0000 mouse mask 4 WORD my mouse mask 16 16 B B B B B B F F F F B B B B B B B 0 0 0 0 B F F F F B 0 0 0 0 B B 0 0 B B F F F F F B B B 0 0 B B 0 B 0 B F F F F F F B 0 B 0 B B 0 B B 0 B F F F F B 0 B B 0 B B B B F B 0 B B B B 0 B F B B B F F F F F B 0 0 0 0 B F F F F F F F F F F B 0 B B 0 B F F F F F F F F F F B 0 B B 0 B F F F F F F F F F F B 0 B B 0 B F F F F F F F F F F B 0 0 0 0 B F F F F F F F F F F B 0 0 0 0 B F F F F F F F F F F B 0 0 0 0 B F F F F F 20 int main int argc char argv
16. BUFF netb void buff Description It marks the buffer pointed by buff as free in the netb pool ETH_INIT void eth_init int mode TASK MODEL m Description It initializes the Ethernet layer in order to transmit or receive ethernet frames If the Ethernet layer has already been initialized it does nothing Each network level protocol that needs to access the network card must pass through the Eth ernet layer which must be initialized before receiving or sending anything The Ethernet layer will search for a supported network card enable it and initalize some internal structures At the moment the mode parameter is not used in the future it will be used to select an operating mode mutual exclusion on send operation through a dedicated server task or through mutexes This library function is called by net_init in the standard UDP IP configuration The task model used for the task that handles the network card interrupts can be passed with the m parameter If it is NULL a SOFT TASK MODEL obtained initializing such a model with these arguments will be used soft task default model m soft task def wcet m 1000 soft task def period m 20000 soft task def met m 1000 soft task def aperiodic m soft task def system m soft task def nokill m HTONS amp NTOHS WORD htons WORD host WORD ntohs WORD net Description These two utility functions convert a WORD from the host format to the net format hto
17. Chapter 10 The Console Library The output on the screen in text mode is supported by a group of functions that act on the whole screen and modify each time the cursor s position Since such functions are not reentrant they must be used in mutual exclusion In order to use the library for displaying on the screen the cons h file must be included This file contains the values for the usable colors whose symbolic names are listed below BLACK BLUE GREEN CYAN RED MAGENTA BROWN GRAY LIGHTGRAY LIGHTBLUE LIGHTGREEN LIGHTCYAN LIGHTRED LIGHIMAGENTA YELLOW WHITE Two global read only variables cons_columns and cons_rows contain the number of screen columns and the number of screen rows respectively They can be used to write applications that are indipen dent from the screen dimensions CPUTC CPUTS CPRINTF void cputc char c void cputs char s int cprintf char fmt Description cputc cupts and cprintf are used to print on the screen a character a string or a formatted string respectively In the latter case the standard C I O formatting conventions are used Warning since these functions modify the cursor position they are not reentrant and must be used in a mutually exclusive fashion PUTC XY PUTS XY PRINTF XY GETC XY void putc xy int x int y char attr char c void puts xy int x int y char attr char s int printf xy int x int y char attr char fmt char getc xy int x int y char attr
18. Description Whenever the key combination specified in key is pressed the function hook is invoked getting key as input parameter If lock is set to FALSE after executing the function hook the key will be lost otherwise it will be inserted in the queue Example tinclude lt drivers shark keyb26 h gt void hook func KEY EVT keypressed 1 switch keypressed gt ascii 1 case w if CTRL w is pressed break case x if isLeftAlt keypressed isRightAlt keypressed 1 if ALT x is pressed else if x is pressed int main int argc char argv KEY_EVT key keyboard initialization to hook CTRL w key key ascii w key scan KEY_W key status KEY_PRESSED key flag CNTR_BIT keyb_hook key hook_func FALSE to hook key x key ascii x key scan KEY_X key status KEY_PRESSED key flag 0 keyb_hook key hook_func FALSE to hook ALT x key key flag ALTL_BIT ALTR_BIT 13 keyb_hook key hook_func FALSE KEYB DISABLE void keyb_disable void Description Trow away the data arriving from the hardware instead of processing them inside the driver KEYB ENABLE void keyb_enable void Description Allow the driver to receive data from the hardware KEYB SET MAP int keyb set map unsigned char map Description It changes the default map used for the keyboard map can be KEYMAP US for an eng
19. RD num DOS FILE f Description It writes num objects of size bytes into file f Data are picked from the buffer pointed by buf This function returns the actual number of bytes written it can be less than num size bytes Zero is returned if an error occurs DOS ERROR unsigned DOS_error void Description Returns the error code of the latest DOS_xxx function 52 Chapter 12 The Snapshot Library The library allow applications to save up to 16 screen snapshot to file Before the grabbing is necessary to allocate the memory for a snapshot slot and files can be created only at the end of execution when the system return in real mode SNAPSHOT GETSLOT void snapshot getslot int nbuff int wx int wy int byesperpixel Description This function allocate the memory for a snapshot of given dimensions The nbuff parameter indicate which slot must be allocated wx and wy are width and height of the screen resolution while bytesperpixel is the depth of the screen SNAPSHOT FREESLOT void snapshot freeslot int nbuff Description This function free the memory reserved for the slot indicated by the nbuff parameter SNAPSHOT GRAB void snapshot grab int nbuff Description This function get a snap of the video memory and copy it inside the slot specified by the nbuff parameter SNAPSHOT SAVEPGM int snapshot savepgm int nbuff char fname Description This function save the screen snapshot saved inside the nbuff sl
20. S Ha R K User Manual Volume II PROGRAMMING LIBRARIES Written by Giorgio Buttazzo giorgio sssup it Paolo Gai pj sssup it Luigi Palopoli luigi gandalf sssup it Luca Abeni luca gandalf sssup it Giuseppe Lipari lipari gandalf sssup it Gerardo Lamastra lamastra sssup it Antonino Casile casile sssup it Massimiliano Giorgi massy gandalf sssup it Scuola Superiore di Studi e Perfezionamento S Anna RETIS Lab Via Carducci 40 56100 Pisa Contents 8 9 Introduction TE Driver Initializationi A LG Ag O O eae a 1 2 Driver Shutdown A Oe E ee BE ER e The Linux Compatibility Layer The Input Library 3 1 The keyboard library ee eee 3 2 Thesmouse libtary sa eine a OI ee A 3 2 1 The mouse graphics functions 2 2 e e e ee 3 3 The Joystick library i ANE RE Ee a ee Ee O R A sA The speaker libraty 3 foe fea a Gee OS ae a SESS BE RS SS The Frame Buffer Library 4 1 The Frame Buffer graphics functions 2 2 2 2 2 2 000002 0 000008 The Frame Grabber Library 5ST BEEV low leverdriver cagare FA BO OOOH REESE aw Re ee ee E 5 2 VideoDevice high lever interface 2 0 00 ee es 5 2 1 Video Devices Commands 0000 a The CPU frequency scaling library 6 1 CPU Information utility e 6 2 CRU scaling functions 2 ante ie ae eee E ARRE ee Hidde we ee e The Network Library The CMOS real time clock The Sound Library 10 The Console Library 11
21. S params BASE MOUSE result MOUSE26_init amp params if result 0 the mouse can t be initialized other mouse functions MOUSE26_close The MOUSE26_close function is not required but can be used to release all the hardware resources that the library acquires The NULL constant can be passed to the MOUSE26_init function for a default initialization The params variable can be used to change the default setting of the initialization procedure using some macros whose names start with mouse_def_ All the mouse functions can be found in the include file drivers shark_mouse26 h MOUSE26_ INIT int MOUSE26_init KEYB_PARMS parms Description It initializes the mouse interface and the library s internal data structures It can be called using NULL as parms to initialize the mouse interface to default values Note that to be proper initialized you need also to initialize the HARTPORT modules Return value 0 if the operation is performed successfully a value less than 0 otherwise MOUSE26 CLOSE int MOUSE26_close void Description lt close the mouse interface Return value 0 if the operation is performed successfully 1 if the mouse in not installed MOUSE26_ INSTALLED int MOUSE26_installed void Description Return if the mouse driver is actually installed Return value 0 if the mouse is installed 1 otherwise MOUSE DEFAULT PARM 15 void mouse default parm KEYB PARMS parms Des
22. al status EVBUG26_ INIT int KEYB26_init void Description It initializes the event debugger interface and the library s internal data structures Return value 0 if the operation is performed successfully a value less than 0 otherwise EVBUG26 CLOSE int EVBUG26 close void Description It close the event debugger interface Return value 0 if the operation is performed successfully 1 if the interface in not installed EVBUG26 INSTALLED int EVBUG26 installed void Description Return if the event debugger is actually installed Return value 0 if the module is installed 1 otherwise 3 1 The keyboard library In order to use the keyboard handling functions the drivers shark_keyb26 h header file containing the interface functions prototypes has to be included in the application program First of all the keyboard needs be initialized by the calling KEYB26_init primitive into the init function in the initialization file or in any other point of the application code and the input low level driver must be already installed A programmer can either initialize the keyboard using the default settings or define his own parameters which are encapsulated into a structure having 10 KEY PARMS type The strucuture can be initialized with the default set of values by setting it equal to BASE KEYB the keyb_def_ macros can be used before calling KEYB26_init to modify each set ting Afterwards it is possible to read
23. anteed through the INTDRIVE module As described inside the module documentation INTDRIVE is an high priority module specifi cally designed to handle the drivers requests Usign the hierarchial capabilities of S Ha R K the INTDRIVE module is indepented from the main system scheduler so EDF RM and all the other modules can be used to schedule the application tasks To load the Emulation Layer INTDRIVE must be present inside the system TIME kernel register levels void arg INTDRIVE register level INTDRIVE Q INTDRIVE T INTDRIVE FLAG EDF register level EDF ENABLE ALL After the INTDRIVE registration the initialization procedure can begin 1 1 Driver Initialization The initialization of a drivers should be done inside the initfile before entering inside the real time application During initialization the devices can lock the system for an unpredictable amount of time so any used device should be ready before the real time tasks are scheduled S Ha R K standard initfile suggests a possible implementation TASK init void arg struct multiboot info mb struct multiboot info arg set shutdown task device drivers init sys atrunlevel call shutdown task NULL RUNLEVEL_SHUTDOWN call main mb return NULL int device drivers init0O1 KEYB PARMS kparms BASE KEYB LINUXC26 register module PCI26 init INPUT26 init KEYB26 init amp kparms return O The device
24. ber can be obtained using grx_getmode The parameter mode is a string in the format widthxheight bpp ex 640x480 16 If the mode is supported and can be opened the function returns 1 oth erwise it returns 1 FB26 CLOSE int FB26 close int num Description It closes the frame buffer num returning to text mode 24 4 1 The Frame Buffer graphics functions The GRX library allows to use graphics with 16 bpp the number of bits per pixel the graphic depth determines the number of colors that can be simultaneously displayed on a single screen In 16 bpp modes each pixel is represented by two bytes Since 16 is not divisible by 3 a component the green one is described by 6 bits whereas the other two are described by 5 bits The RGB16 macros help to code RGB values in a pixel value for all these graph functions RGB16 WORD rgb16 WORD r WORD g WORD b Description It returns the color value defined by the 3 parameters red green and blue in the format required by drawing function GRX CLEAR void grx clear DWORD color Description It clears the graphic screen by filling it with the color specified in the parameter color GRX PLOT void grx plot WORD x WORD y DWORD col Description It draws a pixel of color c at coordinates x y on the screen For efficiency reasons no checks are performed on x and y Only the bpp less significative bits of col are used where bpp is the number of bits per p
25. char c Description These functions are similar to the previously defined ones the only difference is that since they re reentrant can be used concurrently by multiple tasks the others cannot be used for this purpose because they modify the cursor s state getc_xy is used to read the charcater and its attribute at a specific position on the screen 49 CLEAR CLEAR SCROLL SCROLL void _clear char c char attr int x1 int yl int x2 int y2 void clear void void _scroll char attr int x1 int y1 int x2 int y2 void scroll void Description the clear and scroll functions are used for clearing the screen and for scrolling it upwards They are based on the _clear and _scrol11 functions used for clearing or scrolling a window defined by x1 y1 x2 y2 by filling the area with attr color and in the case of clear with character c as well SET ACTIVE PAGE SET VISUAL PAGE GET ACTIVE PAGE GET VISUAL PAGE void set active page int page void set visual page int page int get active page void int get visual page void Description The video cards working in text mode use the CGA hardware scheme In this scheme every screen occupies 4000 bytes 80 columns x 25 rows each position is associated with two bytes one for codifying the character and another for codifying the color The video card memory is in general bigger therefore multiple screen pages can be used simultaneously The currently visualized screen is called the visual
26. cription Initialize the driver and all internal structures The function returns the CPU identifyer if that present DVS capabilities 1 otherwise CPU26 DVS CLOSE int CPU26_DVS_close void Description It close the CPU driver Return value 0 if the operation is performed successfully 1 if the driver in not installed CPU26 DVS INSTALLED int CPU26 DVS installed void Description Return if the DVS driver is actually installed Return value The function returns the CPU identifyer if that present DVS capabilities 1 other wise CPU26 GET LATENCY int CPU26 get latency void Description Return the value of the latency time needed to change between two frequencies CPU26 GET MIN FREQUENCY CPU26 GET MAX FREQUENCY int CPU26 get min frequency void int CPU26 get max frequency void Description Are used to obtain minumum and maximum allowed frequencies CPU26 GET CUR FREQUENCY int CPU26 get cur frequency void Description Return the value of the actual frequency of the processor CPU26 SET FREQUENCY int CPU26_set_frequency int target unsigned int relation Description Return 32 CPU26 GET FREQUENCIES int CPU26 set frequency int freqs Description Return CPU26 SHOW FREQUENCIES int CPU26 show frequency char buff Description Return 33 Chapter 7 The Network Library To allow communication among different computers S Ha R K provides a Network Library imple menting
27. cription It changes the values of parms to the same vales as the BASE MOUSE default ini tializer MOUSE DEF THRESHOLD void mouse def threshold MOUSE PARMS parms int thr Description It changes the default threshold i e the mouse sensitivity value used in the mouse driver Is a scaling factor between the hardware position increment and the logical increment in the mouse position The higher the value the lower the sensitivity The default is 10 MOUSE DEF X0 MOUSE DEF YO MOUSE DEF ZO void mouse def xO MOUSE PARMS parms int xvalue void mouse def yO MOUSE PARMS parms int yvalue void mouse def zO MOUSE PARMS parms int zvalue Description These functions change the initial value of the mouse position The default vilue for each parameter is O if permitted by mouse position bounds MOUSE DEF XMIN MOUSE DEF XMAX void mouse def xmin MOUSE PARMS parms int minvalue void mouse def xmax MOUSE PARMS parms int maxvalue Description It changes the minimum and maximum allowed value for the x coordinate MOUSE DEF YMIN MOUSE DEF YMAX void mouse_def_ymin MOUSE_PARMS parms int minvalue void mouse def ymax MOUSE_PARMS parms int maxvalue Description It changes the minimum and maximum allowed value for the y coordinate MOUSE_DEF_ TASK void mouse_def_task MOUSE_PARMS parms TASK MODEL m Description This macro defines the parameters for the mouse handling task The TASK_MODEL should be a valid po
28. drivers init calls all the initialization functions LINUXC26 is the Linux Emulation Layer and it must be loaded as first The initialization order follows the driver dependence tree of figure 1 1 If this order is not respected the initialization procedure fails LINUXC26 Linux 2 6 Emulation Layer PCI26 FB26 PCI is not required with VESA 2 0 video mode 12026 E errvze NETWORK CPUFREQ26 PCI6025E INPUT26 KEYB26 MOUSE26 GAMEPORT26 SPEAKER26 DIRECT ACCESS SERIAL PARALLEL PCL812 PCL833 Figure 1 1 Drivers dependeces tree 1 2 Driver Shutdown Another critical point is the shutdown sequence When a sys_end or exit is called the system should close the device drivers as soon as possible Unfortunately the driver shutdown must be executed when the kernel is still in multitasking mode int device drivers close 4 KEYB26 close INPUT26 close return O The RUNLEVELS of S Ha R K gives the possibility to implement a safe and trasparent procedure to shutdown the system without compromise the drivers stability As the initiliazation the shutdown sequence must follow the dependence order The flow chart of figure 1 2 shows the steps to reach a safe exit Anyway if the system is overloaded during the exit procedure the shutdown task cannot be scheduled A possible solution is to give high priority to the shutdown task or to design an application that doesn t reach the CPU saturation If the shutdown task doe
29. e case of errors a NULL or zero value is returned DOS ferror can be used to get the DOS error code the header file lt 11 i1386 x dos h gt must be included to use these functions A running we hope well documented example can be foun in the demos dosfs directory DOS FOPEN DOS FILE DOS fopen char name char mode Description It opens a file and returns a pointer to a file structure The name parameter contains the name of the file to be opened The mode parameter contains a string whose value can be one of the following constants r to read w to write and rw to read and write In the case of error NULL is returned otherwise the returned value can be used as last parameter in the functions listed below DOS FCLOSE void DOS fclose DOS FILE f Description It closes the specified file and releases all allocated DOS resources DOS FREAD DWORD DOS fread void buf DWORD size DWORD num DOS FILE f Description It reads num objects of size bytes from file f and place them in a buffer pointed by buf This function returns the actual number of bytes read from the file it can be less than num x size bytes Zero is returned if an error occurs or end of file is found 1These callbacks are useful when you don t have any partition that can be read by the filesystem for example when running S Ha R K applications from a FAT32 filesystem ol DOS FWRITE DWORD DOS fwrite void buf DWORD size DWO
30. eaker library The system provide a driver to use the internal PC speaker It can play a note at a given frequency for a predefined period or in a endless loop In order to use the speaker handling functions the drivers shark spk26 h header file containing the interface functions prototypes has to be included in the application program First of all the mouse needs be initialized by the calling SPEAK26_init primitive into the __init__ function in the initialization file or in any other point of the application code and the input low level driver must be already installed SPEAK26 INIT int SPEAK26_init void Description It initializes the speaker interface and the library s internal data structures Return value 0 if the operation is performed successfully a value less than 0 otherwise SPEAK26 CLOSE int SPEAK26_close void Description It close the speaker interface Return value 0 if the operation is performed successfully 1 if the speaker in not installed SPEAK26 INSTALLED int SPEAK26_installed void Description Return if the speaker driver is actually installed Return value 0 if the speaker is installed 1 otherwise SPEAKER SOUND void speaker sound unsigned int hz unsigned int ticks Description Generate a note at a frequency given using the parameter hz The parameter ticks is the duration of the note if set to O the note is repeated in an endless loop SPEAKER MUTE int speaker mute void
31. ecessary that the audio driver be initialized with the tick parameter set to the system tick expressed in microseconds see sound_init for more details 46 e DMA OP operates using one of the DMA modes the default is DMA Double Buffering The internal buffer size is specified in sound_init e PCM8 operates using 8 bit PCM format it is the default It is the only possible format in PIO mode e PCM16 operates using 16 bit PCM format This choice is meaningless in PIO mode e SYNCH synchronous operation it is necessary to call sound_wait after sound sample e ASYNCH asynchronous operation e MYFUN operates with DMA Self buffering mode it makes sense only if DMA OP has been set e NOBUFF operates in DMA Raw Mode it makes sense only if DMA OP has been set Example BYTE buff 0xFFFFF buffer for sampling void main sys_init amp s keyb_init NULL clear sound_init 0x4000 TICK sound info cprintf Recording sound sample buff 44000 Ox8FFFF DMA OP PCM8 SYNCH SOUND PLAY void sound play BYTE buff DWORD sps DWORD len BYTE t Description It plays len bytes taken from the b buffer at the frequency of sps samples per second with the mode expressed by t As far as the values of t are concerned the reader can refer to sound sample DMA GETPAGE BYTE dma_getpage DWORD dim Description It allocates a buffer having size dim fitting for use in DMA operations Such a usage
32. ed with a frequency equal to the operation s frequency divided by the half buffer s size thus they should be very short in order not to overload the system Example 45 int osc_fun BYTE b int i int sum 0 BYTE p Averages the values read from the buffer and writes the result on a CAB shared with a task for i 0 i lt BUFFDIM gt 1 i sum bli sum BUFFDIM gt 1 p cab reserve cc p BYTE sum cab putmes cc p return 0 void io_task void arg int x y BYTE p BYTE page 0 char str 50 short int talk silencecount This task reads the value put on the CAB by the self buffering function sets the self buffering function sound_setfun osc_infun 1 starts the sampling operation sound_sample NULL 20000 0 DMA OP PCM8 MYFUN cc cab_create osc_cab sizeof BYTE 3 for 1 reads and proccesses the CAB s value task endcycle return 0 SOUND_ SAMPLE void sound_sample BYTE buf DWORD sps DWORD len BYTE t Description It samples len bytes in the buf buffer at the frequency of sps samples per second with the mode expressed by t The latter can be assigned one of the following constants e PIO_OP operates using PIO mode as said earlier in this mode values for sps higher than 10000 make no sense Moreover for the sampling and playing to happen with the correct timing it is n
33. er to a Task Model or KEYB DEFAULT if you want to specify the default behaviour This macro should be used every time the default server Task Model does not adapt well to the configuration of the scheduling modules registered in the system The default server Task Model is equivalent to this initialization soft task default model base m soft task def wcet base m 2000 soft task def met base m 800 soft task def period base m 25000 soft task def system base m soft task def nokill base m soft task def aperiodic base m KEYB GETCH KEYB GETCHAR int keyb getch BYTE wait int keyb getchar void macro Description If the keyboard queue is not empty keyb_getch returns the ASCII code of the pressed key If the queue is empty the function s behaviour depends on the value of the wait parameter if it is BLOCK then the calling task is blocked until a key is pressed if it is NON BLOCK the function returns 0 keyb getchar is a macro for keyb_getch BLOCK Return value the ASCII code of the pressed key if the buffer is not empty O otherwise KEYB GETCODE int keyb getcode KEY EVT k BYTE wait 12 Description It fetches the KEY EVT from the keyboard s queue and copies it into the structure pointed by k If the queue is empty the function behaves as key getch Return value 1 if a key was pressed 0 otherwise KEYB HOOK void keyb hook KEY EVT key void hook KEY EVT keypressed unsigned char lock
34. evt gt dz gt 0 4 Wheel position changed int main int argc char argv mouse hook initialization mouse_hook hook_func dia ISLEFTBUTTON ISCENTRALBUTTON ISRIGHTBUTTON isLeftButton int button isCentralButton int button isRightButton int button Description These macros are used to test whether a specific mouse button is pressed 18 3 2 1 The mouse graphics functions The system provide a set of function to quickly draw the mouse cursor both in text and graphic mode For each mode we can find 2 functions The first used to set the cursor shape and the second to enable disable the cursor visualization ATTENTION In text mode the mouse position is taken considering characters while in graphics values are pixels as mining MOUSE TXTCURSOR MOUSE GRXCURSOR void mouse txtcursor int cmd void mouse grxcursor int cmd int bpp Description This function enables disables the textual grafical autocursor features of the library cmd can be DISABLE disable cursor ENABLE enable a cursor The graphic version need and other parameter bpp which is depth of the screen in bytes These commands can be composite with two flags e AUTOOFF if a user mouse handler is called then during this call the mouse is off if you use a mouse off you can hang the mouse task e WITHOUTSEM the autocursor mouse functions are not protected by a semaphore so tasks cannot be blocked but garbage can be d
35. ff_release 40 ntohs 40 place 50 printf xy 49 putc_xy 49 puts xy 49 rgb16 25 RTC TIME struttura 43 set active page 50 set rtc time 43 set visual page 50 snapshot freeslot 53 snapshot getslot 53 snapshot grab 53 snapshot savepgm 53 snapshot saveppm 53 sound info 45 sound _init 45 sound play 47 sound sample 46 sound setfun 45 sound wait 48 SPEAK26 close 23 SPEAK26_init 23 SPEAK26 installed 23 speaker mute 23 speaker sound 23 udp bind 35 udp notify 38 udp recvfrom 37 udp sendto 37 VIDEODEV26_ ioctl 29 VIDEODEV26 open 28 55
36. ginning On top of this layer we can find different peripherals e Keyboard e Mouse Joystick Speaker e Event debuger Each one can work independently from the others In order to use the low lever functions the files drivers shark_input26 h must be included It contains the prototypes of the declared functions First of all the keyboard needs be initialized by the calling KEYB26_init primitive into the __init__ function in the initialization file or in any other point of the application code INPUT26 INIT int INPUT26_init void Description It initializes the low lever input interface and the library s internal data structures Return value 0 if the operation is performed successfully a value less than 0 otherwise The following code shows an example of input drivers initialization for the system Example int res KEYB_PARMS kparms BASE_KEYB MOUSE_PARMS mparms BASE_MOUSE LINUXC26_register_module INPUT26_init keyb def map kparms KEYMAP IT keyb def ctrlC kparms NULL KEYB26_init amp kparms mouse_def_threshold mparms 5 mouse_def_xmin mparms 0 mouse_def_ymin mparms 0 mouse_def_xmax mparms 639 mouse_def_ymax mparms 479 MOUSE26_init amp mparms SPEAK26_init JOY26_init The event debugger is used to have an output of the raw data coming from an input device for which a driver is not present It can be stanter stopper and is possible to control the actu
37. has to be associated to a frame type the frame type is a field of a frame each time that a frame of the specified type will arrive the callback function will be called A callback can be bound to a frame type using the eth_setHeader library call In order to transmit Ethernet frames a transmission buffer must be allocated and filled the header can be filled using eth setHeader while the body must be explicitly filled after obtaining a pointer to it through eth_getFDB At this point the frame can be sent using eth_sendPKT Transmission buffers can be allocated using the netbuff module this module usable including the netbuff h header file permits to manage pools of pre allocated buffers in order to minimize the unpredictability due to dynamic allocation NETBUFF INIT void netbuff_init NETBUFF netb BYTE nbuffs WORD buffdim Description It initializes a pool composed of nbuffs buffers each of them have buffdim size The pool is identified by the netb descriptor 39 NETBUFF GET void netbuff get NETBUFF netb BYTE flag Description It returns a pointer to the first free buffer in the pool identified by netb The flag parameter which can assume values BLOCK or NON BLOCK indicates whether the operation is a blocking or non blocking allocation If a non blocking netbuff get is performed when the pool does not contain any free buffer a NULL pointer is returned NETBUFF RELEASE void netbuff release NET
38. he bindlist parameter are loaded into the ARP table The port is identified by the a parameter which is composed of the fields named s_addr having IP_ADDR type and s port having WORD type The s port parameter is the most meaningful since it specifies the port the function binds to Further details can be found in any UNIX manual The possibility of specifying the hosts that will be accessed through the bindlist parameter permits to add ARP table entries in the network initialization phase In this way the timing impredictability introduced by ARP can be reduced This possibility can be discarded by chosing a NULL value for the bindlist parameter Otherwise such a parameter has to be a pointer to a NULL terminated IP ADDR array As we said earlier the returned socket identifier can be fed into the udp sendto primitive 35 Example void txsessiontask void arg UDP_ADDR local IP_ADDR b1 5 int sock The periodic txsessiontask upon its creation creates a socket befor entering the infinite cycle typical of all periodic tasks local s_port 1030 local port It loads the eth address of the hosts the task will communicate with into the ARP table ip_str2addr 193 205 82 47 bl terminates bind list by NULL DWORD amp b1 1 NULL sock udp_bind amp local bl 36 UDP SENDTO int udp sendto int s char buf int nbytes UDP ADDR to
39. ideo box The memory buffer must be large enough to contain the box in general the correct buffer dimension is y2 y1 1 2 x1 1 bpp See also grx putimage GRX_RECT int grx rect WORD x1 WORD y1 WORD x2 WORD y2 DWORD col Description It draws an empty rectangle with top left corner at x1 y1 and bottom right corner at x2 y2 The rectangle is drawn with color col GRX_BOX int grx_box WORD x1 WORD y1 WORD x2 WORD y2 DWORD col Description It draws a filled rectangle with top left corner at x1 y1 and bottom right corner at x2 y2 The box is drawn with color col GRX LINE void grx_line WORD x1 WORD y1 WORD x2 WORD y2 DWORD col Description It draws a line from x1 y1 to x2 y2 using color col GRX TEXT void grx text char text WORD x WORD y DWORD fg DWORD bg Description It writes a O terminated text string in graphic mode at position x y The string is pointed by text fg is the foreground color and bg is the background color GRX CIRCLE void grx circle WORD x WORD y WORD r DWORD col 26 Description It draws a circle of radius r and color col centered at x y GRX DISC void grx disc WORD x WORD y WORD r DWORD col Description It draws a filled circle of radius r and color col centered at x y 27 Chapter 5 The Frame Grabber Library The library is divided in 2 layers the low level and the high level The first one is in charge of
40. inter to a Task Model or MOUSE_DEFAULT if you want to specify the default behaviour This macro should be used every time the default Task Model does not adapt well to the configuration of the scheduling modules registered in the system The default Task Model is equivalent to this initialization soft task default model base m soft task def wcet base m 2000 soft task def met base m 500 soft task def period base m 8000 soft task def system base m soft task def nokill base m soft task def aperiodic base m 16 MOUSE ENABLE void mouse_enable void Description Allow the driver to receive data from the hardware MOUSE DISABLE void mouse_disable void Description This function disable the mouse the driver stop to respond to the data arriving from the hardware MOUSE_ SETPOSITION void mouse setposition int x int y int z Description Set values for axes and wheel Values for x and y axis are compared against bounds for the allowed zone MOUSE GETPOSITION void mouse getposition int x int y int z unsigned long buttons Description Get values for axes wheel and buttons In the buttons variable each bit rappresent the status of a button MOUSE SETLIMITS void mouse setlimits int xmin int ymin int xmax int ymax Description It changes the minimum and maximum allowed value for x and y coordinate MOUSE GETLIMITS void mouse getlimits int xmin int ymin int xmax int yma
41. is possible only if the buffer does not contain bytes whose address differs in the Most Significant Bits The best way to achieve this feature is to allocate buffers sized less than 64K starting from addresses having the LSB equal to 0 This job is performed by dma_getpage It should be noted that such a feature is necessary only using DMA Raw Mode since the buffer allocation is automatically performed by sound_init when using DMA Double Buffering and DMA Self Bufering modes Example 47 void main void 1 BYTE p int i Monitors the time stolen by the DMA to the CPU during a 10 Khz sampling sys_init amp s keyb_init NULL clear p dma_getpage 0xFFFF sound_init 0x200 TICK sound_info for i 0 i lt 80 i cprintf _ cprintf ref_time f myrif cprintf Unloaded system f load amp myrif cprintf DMA Recording sound_sample p 10000 OxFFFF DMA_OP PCM8 NOBUFF SOUND WAIT void sound wait void Description It is the synchronization primitive for synchronous operations The task calling sound wait blocks itself until the synchronous operation is finished The call to this function is mandatory for synchronous operations On the other hand using the function in conjunction with an asynchronous operation is an error Example sound sample buff 44000 Ox8FFFF DMA OP PCM8 SYNCH waits until the sampling termination sound wait 48
42. isplayed MOUSE TXTSHAPE void mouse txtshape DWORD shape Description This function defines the shape of the text cursor shape is a DWORD that is used to display the cursor the text character and attributes are taken from the text memory these values are and ed with the low word of shape and the result is xor ed with the high word of shape the result is written into the text memory For examples the default mouse cursor shape is 0x7700ffff the character and attribute that are taken from the the memory are and ed with Oxffff so they do not change and then are xor ed with 0x7700 the character is xor ed with 0x00 and the attribute byte is xor ed with 0x77 the character remains the same but the attribute byte is inverted so the mouse cursor is displayed inverting the colors of the character the attribute byte contains the character foreground and background color and is coded in the usually EGA VGA mode you can read a book about VGA display adapters to find more informations MOUSE GRXSHAPE void mouse grxshape BYTE img BYTE mask int bpp Description This function defines the shape of the graphical cursor img is a pointer to an image of 16x16 that can be used with the grx putimage function or can be NULL in this case a default cursor is used before putting the image into the screen s memory the image is and ed with mask The parameter bpp is depth of the screen in bytes Example x the resolution is 640x480
43. lane in the current graphic mode GRX GETPIXEL DWORD grx getpixel WORD x WORD y Description It returns the color of pixel at coordinates x y on the screen For efficiency reasons no checks are performed on x and y Only the bpp less significative bits of the returned value are used where bpp is the number of bits per plane in the current graphic mode GRX PUTIMAGE void grx putimage WORD x1 WORD y1 WORD x2 WORD y2 BYTE img Description It writes a rectangular bitmap from system memory to video memory x1 y1 is the top left corner while x2 y2 is the right bottom corner Tt fills the specified box with the data in the buffer pointed by img The memory buffer must contain the pixels in the same representation used in the video memory starting at the top left corner from left to right and then line by line from up to down without any gaps and interline spaces See also grx getimage Example 25 BYTE videobuff 200 200 void videotask void arg int done 0 while done 4 done decodeframe videobuff 200 200 grx_put X Y X 200 Y 200 videobuff task_endcycle GRX GETIMAGE void grx_getimage WORD x1 WORD y1 WORD x2 WORD y2 BYTE img Description It reads a rectangular bitmap from video memory to system memory x1 y1 is the top left corner while x2 y2 is the right bottom corner It fills the specified buffer pointed by img with the data contained in the selected v
44. lish keyboard or KEYMAP IT for an italian keyboard Return value the keyboard map identifier effectively applied KEYB GET MAP int keyb get map void Description Return the identifier of the keyboard map actually in use KEY EVT Description it is a data structure containing the following fields ascii ascii code of the key scan scan code of the key status the key can be pressed repeated or released When used to set an hook more than one status can be selected The status field can be accessed by one of the following macros whose usage is self explaining e isPressed amp k e isRepeated amp k e isReleased amp k flag codes of the ALT SHIFT and CTRL keys The flag field can be accessed by one of the following macros whose usage is self explaining e isScanCode amp k decides whether the hit key has an ASCII code or not e isLeftShift amp k e isRightShift amp k e isLeft Alt amp k e isRightAlt amp k e isLeftCtrl amp k e isRightCtrl amp k 14 3 2 The mouse library To use the mouse into an application program the user must call the MOUSE26_init function Then all mouse functions are available until a call to the MOUSE26 close function The initialization of the mouse library is performed by MOUSE26_init which requires a parameter of MOUSE_PARMS type to initialize the mouse The following example shows a possible mouse initialization int main int argc char argv 1 int result MOUSE_PARM
45. ly supports either program or DMA controlled sampling an playing according to 4 possible operating modes e PIO mode e DMA Raw mode e DMA Double buffering mode e DMA Self buffering mode Working under PIO mode sounds can be sampled and played only with 8 bit PCM The frequence depends on the hardware speeds but cannot in any case overcome 10 Khz This mode is reserved for the pure classical hard real time approach which refuses the usage of DMA controlled I O The DMA Raw mode uses DMA controller to sample and play directly on a memory buffer Owing to technical problems related to the structure of the PC DMA controller the buffer s size can be no bigger than 64K This mode is the one that minimizes the DMA operations impact on CPU The DMA Double Buffering mode uses an internal buffer in order to overcome the 64k limitation The internal buffer is split into two parts while the DMA tranfers data to one half an ad hoc task moves data between the second half and a user provided external memory region In this way it is possible for a user to work on samples much bigger than 64K paying the fee of a higher CPU load The DMA Self Buffering mode allows the user to directly handle the internal buffer The user specifies a function to be activated every time the DMA controller has finished transferring data on one half of the internal buyffer In this mode the user can obtain the data while they are being sampled the time lag between sam
46. notify int s int f int len BYTE buf void p Desription the notifying function f is associated with the s socket When a packet addressed to the port the socket is bound to arrives such a function is invoked Upon its invocation the function receives as arguments a pointer to the received packet buf the packet size len and The notifying function is executed a pointer specified along with the udp_notify call p within the context of the receiving task therefore it should not consume too much time Example 38 int hrtp recvfun int len BYTE b void p i struct HRTP_SESSION s struct HRTP_HDR h Notifying function used for receiving packets from a session level protocol p is a pointer to the descriptor of the session involved in the transmission s p the received packet is copied into a private buffer belonging to the session h struct HRTP HDR amp s gt b s gt recvd instance dim memcpy h b len return 0 void hrtp_recv struct HRTP SESSION s void f void udp_notify s gt sock hrtp_recvfun void s s gt notifyparm f s gt active HRTP_RCVIN A programmer that wants to implement a new transport network level stack different from UDP IP needs to directly access the Ethernet services This can be done using the Ethernet layer accessible through the eth h header file In order to receive Ethernet frames a callback function
47. ns and vice versa ntohs ETH GETADDRESS void eth getAddress ETH ADDR eth Description It returns the net card Ethernet address in the ETH_ADDR structure pointed by eth 40 ETH STR2ADDR void eth str2addr char add struct ETH_ADDR ds Description It converts an Ethernet address from the string format xx xx xx xx xx xx to the byte ETH_ADDR format The add string contains the address in text format while ds is a pointer to the ETH_ADDR structure where the output is placed ETH SETPROTOCOL int eth setProtocol WORD type void recv void frame Description It is used to specify the callback function recv to be called when a frame of type type is received It returns TRUE in the case of success FALSE otherwise When the Ethernet layer will call the recv callback it will pass to the function a pointer to the received frame The callback function runs in the context of the driver task served by a CBS Each high level protocol must use this library call to register itself in order to process incoming packets Example void ip server recv void pkt 1 IP HEADER iphd This callback is invoked when an IP packet is received iphd IP HEADER eth_getFDB pkt void ip init char localAddr 1 int i Initializes IP Registers the protocol to the ethernet layer eth setProtocol ETH IP TYPE ip server recv ETH SETHEADER void eth setHeader void b ETH ADDR dest WORD type
48. ols that are going to be activated along with the parameters to be passed to their initializing fucntions The predefined net base value if used as net init parameter causes the ethernet level to be solely intialized by using a mutex semaphore for enforcing mutual exclusion Moreover the net setudpip m addr macro is defined to select the UDP IP protocols stack with local IP address addr expressed in string format The task used to handle network card interrupts has a SOFT TASK MODEL obtained initializing such a model with these arguments soft task default model m soft task def wcet m 1000 soft task def period m 20000 soft task def met m 1000 soft task def aperiodic m soft task def system m soft task def nokill m Example int main int argc char argvvoid NET_MODEL m net_base char talk_myipaddr 50 strcpy talk myipaddr 193 205 82 47 net setudpip m talk myipaddr net_init amp m IP STR2ADDR int ip srt2addr char str IP ADDR ip Description It converts the IP address contained in the str string parameter into IP ADDR format The result is returned in the variable pointed by ip The function returns TRUE if the operation has been succesful FALSE otherwise UDP BIND int udp bind UDP ADDR a IP ADDR bindlist Description It binds the receiving program on the specified UDP port A socket is created and its identifier is returned Moreover the host addresses specified through t
49. ot to a PGM greyscale file The filename passed to the function using the fname parameter SNAPSHOT SAVEPPM int snapshot_saveppm int nbuff char fname Description This function save the screen snapshot saved inside the nbuff slot to a PPM color file The filename passed to the function using the fname parameter 53 Index _clear 50 _scroll 50 BTTV26_close 28 BTTV26_init 28 clear 50 cprintf 49 CPU26 close 31 CPU26 DVS close 32 CPU26 DVS init 32 CPU26 DVS instaled 32 CPU26 get cur frequency 32 CPU26 get frequencies 33 CPU26 get latency 32 CPU26 get max frequency 32 CPU26 get min frequency 32 CPU26_init 31 CPU26_ instaled 31 CPU26 set frequency 32 CPU26 show frequencies 33 CPU26 showinfo 31 cputc 49 cputs 49 cursor 50 cursor blob 50 cursor info 50 cursor off 50 cursor std 50 dma getpage 47 DOS error 52 DOS fclose 51 DOS fopen 51 DOS fread 51 DOS fwrite 52 eth close 42 eth getAddress 40 eth getFDB 41 eth init 40 eth sendPkt 42 eth setHeader 41 54 eth_setProtocol 41 eth_str2addr 41 EVBUG26_close 10 EVBUG26_init 10 EVBUG26_installed 10 FB26 close 24 FB26_init 24 fb26 open 24 FB26 setmode 24 get active page 50 get rtc time 43 get visual page 50 getc_xy 49 grx_box 26 grx_circle 26 grx clear 25 grx_disc 27
50. page whereas the screen the output is directed to is called the active page The cited functions are essentially used for handling at a given instant the visual page or the active page SUGGESTION if the active page or the visual page are modified they should be restored to the original 0 value on exit the same is true for the cursor PLACE CURSOR CURSOR INFO void place int x int y void cursor int start scanline int end scanline void cursor info int x int y Description These functions are used for handling the cursor More specifically place sets the cursor position x belongs to the range 0 79 y to 0 24 CURSOR BLOB CURSOR STD CURSOR OFF void cursor blob void void cursor std void void cursor off void Description These macros call the cursor function to set the cursor shape to be a big rectangle the standard underscore or invisible 50 Chapter 11 The File Management S Ha R K provides a built in File System that currently supports Hard Disk Drivers and FAT16 partitions If you are using the DOS eXtender X to run the application you can use some callback to the DOS 0x21 interrupt to write read some bytes from the filesystem These functions directly interact with the underlying DOS and can not be used when the system is in protected mode In partic ular you can only use these functions into the kernel register levels function and in the RUNLEVEL AFTER EXIT exit functions In th
51. pling and data delivery is thus reduced Such a feature makes this working mode interesting for real time applications Independently of the chosen working mode an operation can be either synchronous or asyn chronous A synchronous operation provides the task invoking the operation with a synchronizing point located at its ending In order to use the sound library functions the files drivers sound h and drivers dma h must be included The former contains the prototypes of the declared functions the latter is necessary because the sound library uses DMA The first step to be performed is initializing the audio drivers by the sound_init function Then if one wishes to work in DMA Raw mode it is necessary to allocate a memory buffer and align it by 1Currently only the sound blaster 16 is supported the code of the library is directly inherited from the Hartik 3 3 0 Kernel 2This is possible only if the protected mode is used 44 calling dma getpage in the remaining modes no particular alignment is required for the buffer If the DMA Self buffering mode is chosen the programmer has to properly set the functions to be called every time the DMA finishes working on one half of the internal buffer this can be done by calling the sound setfun primitive As soon as these operations have been performed sampling or playing can be made through sound sample and sound play respectively SOUND INIT void sound init WORD rawbufsize WORD
52. s The first method adopts a shared memory programming paradigm a task willing to transmit is allowed to access the network card mutually exclusive accesses are guaranteed by semaphores This solution is very simple and the introduced overhead is very low The second soultion is based on the utilization of a server task devoted to send frames on the network on behalf of other tasks Each task posts its frames in a mailbox whence the sender task picks them up At the moment only the first solution is implemented but in order to provide a good degree of flexibility both approaches will be supported as soon as possible The most diffused higher level protocols have been implemented upon the ethernet level In order to use them within a S Ha R K application the drivers udpip h file containing the functions prototypes and the data structures has to be included in the application program As a first step the network drivers have to be initialized This is done by the net_init primitive that requires the machine s IP address After initialization the program has to bind itself to a port by a socket in UNIX s fashion by the udp_bind primitive Afterwards it is possible eihter to receive packets by using udp_recvfrom or to send them by using udp sendto NET_INIT 34 void net init NET MODEL m Description It is an interface function used for calling the different layers initializing functions The m parameter specifies the protoc
53. s than 0 otherwise KEYB26 CLOSE int KEYB26 close void Description It close the keyboard interface Return value 0 if the operation is performed successfully 1 if the keyboard in not installed KEYB26 INSTALLED int KEYB26 installed void Description Return if the keyboard driver is actually installed Return value 0 if the keyboard is installed 1 otherwise 11 KEYB DEFAULT PARM void keyb default parm KEYB PARMS parms Description It changes the values of parms to the same vales as the BASE_ KEYB default initializer KEYB DEF MAP void keyb def map KEYB PARMS parms unsigned char map Description It changes the default map used for the keyboard map can be KEYMAP_US for an english keyboard or KEYMAP_IT for an italian keyboard The default is english keyboard layout KEYB DEF CTRLC void keyb def ctrlC KEYB PARMS parms void ctrlcfunc KEY EVT k Description It enables the execution of a function when the ctrlC combination is pressed By default if this macro is not used the ctr1C combination results in calling sys end Note that a small message is printed also on the console The message is only visible if the system is in text mode If you are running a graphic application remember to redefine the Ctrl C Handler KEYB DEF TASK void keyb def task KEYB PARMS parms TASK MODEL m Description It specifies the parameters of the keyboard server The TASK MODEL should be a valid point
54. sn t execute a timeout default 3 seconds force the system exit MULTITASKING MODE SINGLE MODE SYS END OR EXIT CALLED RUNLEVEL SHUTDOWN task activate shutdown task pid RUNLEVEL SHUTDOWN background execution of shutdown task DRIVERS SHUTDOWN 1 l RUNLEVEL BEFORE EXIT completing the system shutdown BACK TO REAL MODE RUNLEVEL AFTER EXIT Figure 1 2 Shutdown sequence Chapter 2 The Linux Compatibility Layer Is the glue code used for the interaction between the kernel and the linux code Is mandatory to use drivers ported from the linux 2 6 kernel tree LINUXC26 REGISTER MODULE void LINUXC26 register module void Description It initializes the compatibility layer interface and the library s internal data structures Return value 0 if the module is installed 1 otherwise Example int device_drivers_init 1 int res KEYB_PARMS kparms BASE_KEYB LINUXC26 register module PCI26 init INPUT26_init keyb def ctrlC kparms NULL KEYB26_init amp kparms FB26 init res FB26 open FRAME BUFFER DEVICE if res cprintf Error Cannot open graphical mode n KEYB26_close INPUT26 close sys end FB26 use grx FRAME BUFFER DEVICE FB26 setmode FRAME BUFFER DEVICE 640x480 16 return 0 Chapter 3 The Input Library This library allow the user to interact with applications Is composed by a lower lever which must be initialized at the be
55. t initializes the joystick interface and the library s internal data structures Return value 0 if the operation is performed successfully a value less than 0 otherwise JOY26 CLOSE int MOUSE26_close void Description It close the joystick interface Return value 0 if the operation is performed successfully 1 if the joystick in not installed JOY26 INSTALLED int JOY26_installed void Description Return if the joystick driver is actually installed Return value 0 if the joystick is installed 1 otherwise JOY ENABLE void joy enable void Description Allow the driver to receive data from the hardware JOY DISABLE void joy disable void Description Trow away the data arriving from the hardware instead of processing them inside the driver JOY SETSTATUS void joy_setstatus int axe0 int axel int axe2 int axe3 int buttons Description Set values for axes and buttons Usually axe0 and axel are x and y axis for the first joystick while axe2 and axe3 are x and y axis for the second one In the buttons parameter each bit rappresent the status of one button JOY GETSTATUS void joy_getstatus int axe0 int axel int axe2 int axe3 int buttons Description Get values for axes and buttons Usually axe0 and axel are x and y axis for the first joystick while axe2 and axe3 are x and y axis for the second one In the buttons parameter each bit rappresent the status of one button 22 3 4 The sp
56. x Description Allow to obtain the minimum and maximum permited value for x and y coordinate MOUSE SETTHRESHOLD void mouse setthreshold int th Description It changes the threshold value used in the mouse driver Is a scaling factor between the hardware position increment and the logical increment in the mouse position The default is 10 MOUSE GETTHRESHOLD void mouse getthreshold int th Description Return the threshold value used in the mouse driver Is a scaling factor between the hardware position increment and the logical increment in the mouse position The default is 10 MOUSE HOOK 17 void mouse hook MOUSE HANDLER hook Description Whenever the driver receive data from the hardware the function hook is invoked with a MOUSE_EVT as parameter To detach a previously defined hook with NULL as parameter MOUSE EVT Description it is a data structure containing the following fields X Y Z actual mouse position dx dy dz increments from the last event buttons each bit in the parameter rappresent the status of one button of the mouse The following code shows an example of usage for the function mouse hook and the structure MOUSE EVT Example include lt drivers shark_mouse26 h gt void hook_func MOUSE_EVT mevt if mevt gt buttonk0x1 The 1st button is pressed if mevt gt dx gt 10 mevt gt dx gt 10 Increment on x or y axis major than 10 if m

Download Pdf Manuals

image

Related Search

Related Contents

ViewSonic vg1930wm User's Manual  mania scx600/700 specifications  「リスニング」を選んで  FujiFilm FinePix S700 Digital Camera User Manual  User Manual  Utilizzo del tasto TITLE LIST - Migros  

Copyright © All rights reserved.
Failed to retrieve file