LinPac - Packet Radio Terminal for Linux 

Version 0.16

(c) 1998 - 2001 by Radek Burget OK2JBG


 

Extrenal Application Programming Guide

Contents

1 Introduction

2 What is an extrenal program

3 How do applications communicate with LinPac

4 Using the application library
4.1 The simplest application

5 Application programming
5.1 Events
5.2 Sending and receiving events
5.3 Synchronization
5.4 Shared memory
5.5 Connection status

6 The application library interface
6.1 Constants
6.2 Data structures
6.3 Global variables
6.4 Functions
6.4.1 Uninterruptable versions of some system calls
6.4.2 Basic communication functions
6.4.3 Automatic event handling functions
6.4.4 Environment functions
6.4.5 User functions
6.4.6 Tool functions

1 Introduction

This guide is written for programmers who want to add some new functions to LinPac. In following text the basic knowledge about Linux programming is assumed. It's also recommended to read the user manual first.

2 What is an external program

An external program is a standard Linux application which uses LinPac to communicate with remote user. There are basicaly two types of LinPac external programs: There are no specialities when creating an application of the first type. Just write the program to work on the Linux console and add it to LinPac. Following sections of this guide are dedicated to the second type of applications.

3 How do applications communicate with LinPac

There are two types of communication between LinPac and the application: Shared memory and the pipes are maintained by the application interface library and shouldn't be contrlled directly.

4 Using the application library

During LinPac installation the application library liblinpac is created and installed by default to /usr/local/lib. The interface to this library is contained in the file lpapp.h and it's installed by default to /usr/local/include/linpac. Next chapter shows how to use the library with the user program.

4.1 The simplest application

Following application example just tries to contact LinPac and prints the result.

---------------------------- File test1.cc ---------------------------
#include <stdio.h>
#include <unistd.h>
#include <linpac/lpapp.h>

int main()
{
  if (start_appl(LP_PIPE_PATH))
  {
     printf("Application started\n");
     sleep(1);
     printf("Application finished\n");
     end_appl();
  }
  else
  {
     printf("LinPac is not running\n");
     return 1;
  }

  return 0;
}

-----------------------------------------------------------------

The function start_appl() tries to contact LinPac and returns 1 in case of succes or 0 when LinPac cannot be connected (probably it's not running). This function should precede the usage of any other application library function. The LP_PIPE_PATH constant contains the path to LinPac named pipe.

The function end_appl() closes the connection to LinPac.

How to compile this example:

gcc -o test1 test1.cc -llinpac

This example just detects if LinPac is running and it can be executed directly from the shell. When running from the shell, no streams are redirected to LinPac and the application seems to run on channel 0 of LinPac. It's useful for some applications that are used to control linpac from outside. However it's not a typical case.

For most of the applications it's better to copy the executable to the $LINPACDIR/bin directory and add it to the file
$LINPACDIR/bin/commands as described in the user manual. After this the application can be executed as the LinPac command. In this case the streams are properly redirected and the application output is visible in LinPac window. It's also possible to select the channel for running the application.

5 Application programming

5.1 Events

LinPac is completely driven by events. Each part of LinPac including the application can generate the event to inform other parts (internal modules or applications) that something has happend. Each event is sent to all LinPac components and application. For example when some station connects to some LinPac channel, the internal AX.25 interface generates the event reporting that the station has connected and includes its callsign. All components and applications now know who has connected and they can do some actions (the output window prints the information about the connect, the macro processor executes the cinit.mac macro ...). Each application can handle all the events too and it can generate events which are handled by other components.

The event is represented by the following structure:

struct Event
{
  int type;
  int chn;
  int x,y;
  char ch;
  void *data;
};

The meaning of each field is following:

type - Determines the type of the event. Actually it says what happend. There is a symbolic constant defined for each known event.
chn - It says the channel for which the event applies (for example if the type of the event reports some data received, the chn field contains the number of the channel which has received data). There are many events that apply for all the channels. For this events this field is not significant.
x, y - The meaning of field depends on the event type. The y field is usually not used (it's used by some internale events only).
ch - This field is used by some internal events only.
data - Depends on the type of the event too. It usually points to some string data or a char buffer.

All the event types are described in the event list.

5.2 Sending and receiving events

For sending events the function

int emit_event(int chn, int type, int x, void *data);

is used. This generates new event using specified values. Each argument corresponds with one of the fields in the Event structure.

There are two modes of handling the incomming events:

a) Reading each event on demand
This mode is started by the event_handling_off() call. In this mode events are read using the function

int get_event(Event *ev);

This function returns 0 when no event is available. When there is some event available, it returns 1 and fills the Event structure with the received event data.

WARNING1: The data field in your Event structure must point to some dynamicaly allocated buffer. The size of the buffer is reallocated automaticaly after receiving an event. When the data field is set to NULL, new buffer is allocated. This field must not be uninitialized.

WARNING2: The application _must_ read all events in this mode. It's not a good idea to stop reading the events because the event queue can overflow and cause serious problems.

b) Automatical event processing
This mode is started by the event_handling_on() call. All the events are read automaticaly. The user can define his own function that is called automaticaly when an event occurs. When there's no such function defined, all events are discarted.

The event handling function must have following prototype:

void some_function(Event *ev);

(the function name can be different). After initializing the application the event handling function must be registered using the function set_event_handler() from the apllication library.

Following example is an application that prints the types of all events received and stops when an event EV_ABORT is received. This event can be generated using the :ABort command in LinPac.

---------------------------------------------------------------------------
#include <stdio.h>
#include <linpac/lpapp.h>

int aborted = 0;

//User event handling function. This function is called each time
//an event occurs
void my_event_handler(Event *ev)
{
  printf("The event of type %i has been received\n", ev->type);
  if (ev->type == EV_ABORT) aborted = 1;
}

int main()
{
  if (start_appl(LP_PIPE_PATH))
  {
    event_handling_on(); //turn on automatical event handling            set_event_handler(my_event_handler); //define own event handler

    printf("Application started\n");
    printf("Stop with the ':Abort' command\n");

    do ; while(!aborted); //wait until application is aborted

    printf("Application finished\n");

    end_appl();
  }
  else
  {
    printf("LinPac is not running\n");
    return 1;
  }

  return 0;
}

----------------------------------------------------------------------------

WARNING: Note that some system calls can be interrupted when the event is received. Interrupted system call returns the error result and sets errno to EAGAIN (for example the read() call returns -1) and it must be called again. To avoid this use the interrupt-safe versions of the system calls contained in the application library (see chapter 6.3.1)

5.3 Synchronization

The event generated by an applicatoin is sent to all the modules and applications including the application that has generated the event. When there's the need to wait until the event is accepted by LinPac, the simplest way is to wait until the event we have sent is received back.

For testing that all the events were processed there is an event EV_VOID. It's not handled by any module. After sending all events just generate the EV_VOID event and wait until it returns. After that it's sure that all previous events have been processed.

5.4 Shared memory

All the shared data are represented by folowing structure:

struct shared_data
{
  /* channel info */
  char call[10];       /* callsign for each channel */
  char cwit[10];       /* connected with callsign */
  char cphy[10];       /* physical connection to */
  int port;            /* connected on which port */
  int state;           /* connection status */
};

The fields have following meaning:

call - callsign of the channel that was set using the :mycall command cwit - callsign of station connected to the channel
cphy - callsign of the station we are physicaly connected to. In case of direct connection cphy is equal to cwit.
port - port used for the connection. 0 means the first port in axports, 1 is the second one...
state - connection status. Following states can occur:
ST_DISC - disconnected
ST_DISP - disconnecting
ST_TIME - disconnecting for timeout
ST_CONN - connected
ST_CONP - connecting in progress

When the application is initialized, the start_appl() function creates the array of these structures:

shared_data []shd

Thus the callsign of the first channel is shd[1].call etc.
The contents of the structure is managed by LinPac and it's not recommended to modify the fields within an application (except some special cases). Better way to change this fields is to generate appropriate event (e.g. EV_CALL_CHANGE).

5.5 Connection status

There are two special events reserved for obtaining the AX.25 connection status. When the application wants to get the status of the connection on certain LinPac channel, it generates the EV_STAT_REQ event on this channel. As the answer LinPac generates the EV_STATUS event. The data field of this event points to the ax25_status structure (see chapter 6.2). When there is no active connection on the channel, no EV_STATUS event is generated.

6 The application library interface

6.1 Constants

LPAPP_VERSION - version of LinPac that the linrary came with
MAX_CHN - number of regular LinPac's channels
ENV_SIZE - environment size for channel
AXPORTS - path to axports file

ST_xxxx - connection status constants (see chapter 5.4)

6.2 Data structures

struct ax25_status - contains the AX.25 connection status:

typedef struct
{
  char devname[8];
  int state;
  int vs, vr, va;
  int t1, t2, t3, t1max, t2max, t3max;
  int idle, idlemax;
  int n2, n2max;
  int rtt;
  int window;
  int paclen;
  bool dama;
  int sendq, recvq;
} ax25_status;

struct shared_config - contains the information of current linpac configuration. There is the pointer lp_config defined, which points to this structure.

typedef struct
{
  bool remote;         //Remote is on

  bool cbell;          //connection bell on
  bool knax;           //incomming frame bell on

  char def_port[32];   //Default port name
  char unportname[32]; //Unproto port name
  int unport;          //Unproto port number (0..n)

  int info_level;          //Statusline: 0=none 1=short 2=full
  char no_name[32];                 //Default name of stn (%N)
  char timezone[8];                 //Local timezone name
  int qso_start_line, qso_end_line, //Screen divisions
      mon_start_line, mon_end_line,
      edit_start_line, edit_end_line,
      stat_line, chn_line;
  int max_x;                         //screen length
  bool swap_edit;                    //swap editor with qso-window
  bool fixpath;                      //use fixed paths only
  bool daemon;                       //linpac works as daemon
  bool monitor;                      //monitor on/off
  bool no_monitor;                   //monitor not installed
  bool listen;                       //listening to connection requests
  bool disable_spyd;                 //disable ax25spyd usage
  bool mon_bin;                      //monitor shows binary data
  char monparms[10];                 //arguments to 'listen' program
  int maxchn;                        //number of channels
  int envsize;                       //environment size
  time_t last_act;                   //last activity (seconds)
} shared_config;

When LinPac runs in daemon mode all the screen-depended fields have undefined values.

6.3 Global variables

shared_data *shd - pointer to shared structure (see chapter 5.4)
shared_config *lp_config - pointer to linpac config structure (see chapter 6.2)
int app_chn - channel number this application is running on
int app_pid - the PID of this application

6.4 Functions

6.4.1 Uninterruptable versions of some system calls

Following functions work the same way as the original system calls, but they are interrupt-safe (they don't fail with errno == EAGAIN).

size_t safe_read(int fd, void *buf, size_t count);
size_t safe_write(int fd, const void *buf, size_t count);
char *safe_fgets(char *s, int size, FILE *stream);
int safe_fgetc(FILE *stream);

6.4.2 Basic communication functions

int start_appl(char *pipename)
Starts the communication with LinPac. The pipename parameter contains the name of the named pipe used for communication (use LP_PIPE_PATH here). Non-zero return value means success, zero value means that LinPac cannot be contacted (probably it's not running).

int get_event(Event *ev)
Read the event from the queue. Non-zero return value means succesful read, zero value means that the event queue is empty. The data field of the event structure must be initialized before using this function (to NULL or to some buffer). This function shouldn't be used when automatic event processing is used.

int emit_event(int chn, int type, int x, void *data)
Generate new event. The arguments correspond with the fields in the event structure. Return value is always 0.

void wait_event(int chn, int type)
Wait until the event with the same chn and type values are received.

void wait_init(int chn, int type)
The same as wait_event() but returns immediately, waiting is provided by following function wait_realize().

void wait_realize()
Realizes waiting initialized by wait_init(). All the events that arrived since last wait_init() call are registered. wait_realize() can exit immediately if the event has already arrived.

void discard_event(Event *ev)
Free the memory used by the data field of Event structure received using get_event().

void clear_pipe()
Removes all events from the event queue. This has no use when automatic event processing is on.

void end_appl()
Closes the connection to LinPac.

6.4.3 Automatic event handling functions

void event_handling_on()
Switches the automatic event handling on. From this point each event is automaticaly read from the queue, treated with an event handler function (if defined) and discarted.

void event_handling_off()
Switches the automatic event handling off. Events must be read from the queue using the get_event() function.

void set_event_handler(handler_type handler)
Defines the event handler function - a function like
void my_handler(Event *ev)

The event handler is called automaticaly each time some event is received and the automatic event handling is on.

6.4.4 Environment functions

LinPac owns its own environment for storing the variables. Each application can share and modify this environment using following functions. The environment is separated for each channel.

void set_var(int chn, char *name, char *contents)
Change the value of the variable. 'name' is the name of the variable, contents is the new value. chn is the channel number (0..MAXCHN) When the variable doesn't exist, it's created.

void del_var(int chn, char *var)
Delete the variable. 'var' is the pointer to the begining of the variable in the environment (pointer to the statement NAME=VALUE)

char *find_var(int chn, char *name)
Returns the poiner to the begining of the variable in channel environment.

char *get_var(int chn, char *name)
Returns the pointer to the value of the variable. name is the name of the variable.

char *env_end(int chn)
Returns the pointer to end of the environment (behind the last variable).

char *clear_var_names(int chn, char *name)
Delete all variables for which the contents of 'name' is the left substring of their name. ($name*)

6.4.5 User functions

void appl_result(const char *fmt, ...)
Set the result of the application. This function generates the EV_APP_RESULT event with the message string. The argument format is the same as for printf()

void statline(const char *fmt, ...)
Displays or changes the additional status line. Using this function can be displayed one status line only. This function generates the EV_CHANGE_STLINE event with the x field (line ID) containing the PID of the application. For displaying more than one status line for the application other EV_CHANGE_STLINE events must be generated manualy.

void remove_statline()
Removes the status line.

void disable_screen()
Disables displaying the data in the QSO window on application's channel. The EV_DISABLE_SCREEN event is used.

void enable_screen()
Enables displaying the data in the QSO window. The EV_ENABLE_SCREEN event is generated.

6.4.6 Tool functions

char *time_stamp(int utc)
Returns the pointer to a c-string that contains actual time. If utc=0 then local time is used else the UTC time is used.

char *date_stamp(int utc)
Returns the date-string.

void replace_macros(int chn, char *s)
Replaces the variables in the string (%xxx) with their values. The %(command) macro is not replaced.

void get_port_name(int n)
Returns the name of the n-th port in axports (starting with 0).


Last update: 29.1.2001