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 Basic concepts of the API

4 How do applications communicate with LinPac

5 Using the application library
5.1 The simplest application

6 Application programming
6.1 Events
6.2 Sending and receiving events
6.3 Synchronization
6.4 Shared variables and configuration
6.5 Connection status
6.6 Event usage examples
6.6.1 Connecting a remote station
6.6.2 Using LinPac commands in programs

7 The application library interface
7.1 Constants
7.2 Data structures
7.3 Functions
7.3.1 Uninterruptable versions of some system calls
7.3.2 Basic communication functions
7.3.3 Automatic event handling functions
7.3.4 Environment functions
7.3.5 User functions
7.3.6 Tool functions
7.3.7 Application information functions
 

1 Introduction

This guide is written for the 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 station. There are basicaly two types of LinPac external programs: No special knowledge about LinPac is needed for creating the first type of programs because no LinPac functions are used. Following sections of this guide are dedicated to the second type of applications.
 

3 Basic concepts of the API

The application interface of LinPac is based on events. Every action in LinPac such as pressing a key, receiving a data, executing a command, etc. is represented by a data structure called event which describes what exactly happened. LinPac's internal structure consists of separate objects which communicate with each other using the events. Each object provides its own functionality, it often generates events - e.g. the object Keyscan produces an event each time any key is pressed.

All the events generated by any object are put to the common event queue. LinPac kernel simply takes the events from the queue one by one and sends them to all the objects (including the one that generated the event). Thus each event generated by any part of LinPac is forwarded to all the objects. The reaction of each object fully depends on its functionality but of course it can include generation of another events.

The list of LinPac internal objects and their names can be found in the file objects.txt.

An additional feature of the API is shared variable environment. This is a set of variables that are shared with linpac - their values are automaticaly synchronized in all the external programs. These variables are accessed using special functions of interface library as described below.
 

4 How do applications communicate with LinPac

LinPac uses the TCP/IP sockets for the communication with the external programs (applications). The connection is always initiated by the application after it starts. There are basicaly two ways how the application is started:
  1. The application is started by LinPac (it is associated to some LinPac command). In this case LinPac registers the channel where the application was started and expects the connection attempt from the application. After the application initializes and contacts LinPac, it is told the working channel and whether it was started by remote or local user. LinPac may also redirect the input and output streams of the application (depends on LinPac settings).
  2. The application is started without using LinPac. In this case LinPac assumes that the application runs on channel 0 and was started by local user. The input and output streams of the application are not redirected.
In both cases the start of an application causes the creation of a new object in LinPac called event gate. This object represents the application within LinPac. Considering previous chapter it means that the application is forwarded all the events generated by any LinPac object and all the events generated by an application are forwarded to all the objects.

NOTE: All the communication via TCP/IP sockets is provided by the LinPac application library. The user application shouldn't access the sockets directly.
 

5 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 files 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.

5.1 The simplest application

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

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

int main()
{
  if (lp_start_appl())
  {
     printf("Application started\n");
     sleep(10);
     printf("Application finished\n");
     lp_end_appl();
  }
  else
  {
     printf("LinPac is not running\n");
     return 1;
  }

  return 0;
}

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

The function lp_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 function lp_end_appl() closes the connection to LinPac.

How to compile this example:

gcc -o test1 test1.c -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.

NOTE: the LinPac application library (liblinpac) can be linked without problems with both C and C++ code.
 

6 Application programming

6.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.

6.2 Sending and receiving events

For sending events the function

int lp_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 lp_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. LinPac automatically kills the application when the event queue exceeds some reasonable number of events.

b) Automatical event processing
This mode is started by the lp_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 lp_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 (lp_start_appl())
  {
    lp_event_handling_on(); //turn on automatical event handling
    lp_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");

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

  return 0;
}

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

This example contains "active waiting" (the do ; while(...) construction). This is very ugly. For this reasons LinPac API offers an alternative for waiting for the events: the lp_wait_event() function. Let's change the example to use this function:

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

int main()
{
  if (lp_start_appl())
  {
    lp_event_handling_on(); //turn on automatical event handling

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

    lp_wait_event(lp_channel(), EV_ABORT); //wait for the abort event

    printf("Application finished\n");
    lp_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 7.3.1)

6.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.

6.4 Shared variables and configuration

Each shared variable denoted by its name (string) and channel number. Each variable has its value represented by a string (char[]). The access to the variables is provided by following functions:

void lp_set_var(int chn, const char *name, const char *value)
Changes the value of the variable. If the variable doesn't exist, it is created.

char *lp_get_var(int chn, const char *name)
Reads the value of the variable. Returns NULL if the variable doesn't exist.

void lp_del_var(int chn, const char *name)
Deletes the variable.

void lp_clear_var_names(int chn, const char *prefix)
Deletes all variables with the name

The value of each variable is automaticaly synchronized with LinPac and all running applications. The variables whose names start with "_" are reserved for system use. These variables can be used for obtaining system configuration and status but it may be potentialy dangerous to change some of these variables. Currently following system variables are defined (in channel 0):

_remote - contains 1 when remote commands are enabled

_cbell - 1 when connect sound is enabled
_knax  - 1 when sound signal for each frame is enabled

_def_port - default port name
_unportname - port name for unproto frames
_unport - port number for unproto frames

_info_level - status-line level (0 to 2)
_no_name - default station name
_timezone - local timezone name
_swap_edit - 1 when swapedit is on
_fixpath - 1 when fixpath is on
_daemon - 1 when linpac works as a daemon
_monitor - 1 when monitor is enabled
_no_monitor - 1 when monitor is disabled from command line
_listen - 1 when accepting connections is enabled
_disable_spyd - 1 when ax25spyd support is disabled from command line
_mon_bin - 1 when monitor filters binary characters
_monparms - command line of 'listen' program
_maxchn - maximal number of channels
_last_act - time of last user activity (same format as the time() call).

These variables can be read using the get_var function defined above. Furthermore there are two special functions defined for reading these variables. This functions expect the name of the system variable without the initial _.

char *lp_sconfig(const char *name)
Returns the value of configuration variable as a string.

int lp_iconfig(const char *name)
Returns the value of configuration variable as an integer.

Following system variables are defined for each channel:
_call - callsign for each channel
_cwit - connected with callsign
_cphy - physical connection to
_port - connected on which port
_state - connection status

There are also special functions for reading values of these variables:

int lp_chn_status(int chn)
Returns the status of a channel. There are following status constants defined:
ST_DISC - channel disconnected
ST_DISP - disconnect in progress
ST_TIME - disconnecting for timeout
ST_CONN - channel connected
ST_CONP - connecting in progress

char *lp_chn_call(int chn)
Returns channel callsign.

char *lp_chn_cwit(int chn)
Returns the callsign of connected station.

char *lp_chn_cphy(int chn)
Returns the callsign of physicaly connected station (the first connected station).

int lp_chn_port(int chn)
Returns the number of the port used for connection.

Last two functions enable changing the time of last users's response:

time_t lp_last_activity()
Returns the time of last activity of the user.

void lp_set_last_activity(time_t timeval)
Sets the last activity time.

6.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 7.2). When there is no active connection on the channel, no EV_STATUS event is generated.

6.6 Event usage examples

Following examples show how to use the events for controlling LinPac. The complete list of events can be found in the file events.txt.

6.6.1 Connecting a remote station

When initiating the connection, the first step is to check, if the channel is free (it is not used for other connection). The status of a channel can be checked using the lp_chn_status() function (see chapter 6.4).

The second step is emiting the EV_CONN_LOC event on apropriate channel. The data field of the event contains a c-string with the destination address like port:callsign [digi [digi ...]].

The last step is to wait until the connection establishes. For this the function lp_wait_connect() can ve used. An example piece of code follows:

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

int chn = lp_channel();
if (lp_chn_status(chn) == ST_DISC)
{
   char addr[30];
   strcpy(addr, "kiss:OK0PAB OK0NMA");
   lp_emit_event(chn, EV_CONN_LOC, 0, addr);
   lp_wait_connect(chn, "OK0PAB");
   /* ... connection established ... */
}

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

6.6.2 Using LinPac commands in programs

Any of the applications can run LinPac commands by emiting the EV_DO_COMMAND event. E.g. for downloading a message from a BBS using the getmsg command following code can be used:

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

char cmd[30];
sprintf(cmd, "getmsg %i", message_number);
lp_emit_event(lp_channel(), EV_DO_COMMAND, 0, cmd);

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

Other posibility is using the EV_WAND_RESULT event. The usage is similar to previous exaple, but the x field of the event has special meaning: as an reaction to this event LinPac will generate an event EV_CMD_RESULT with the same x field and with the data field containing a result of the command.
An example follows:

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

char cmd[30];
int id = 0;
Event *ev;

sprintf(cmd, "getmsg %i", message_number);
lp_emit_event(lp_channel(), EV_WANT_RESULT, 1234, cmd);
while (id != 1234)  /* wait for the command result */
{
   lp_wait_event(lp_channel(), EV_CMD_RESULT);
   ev = lp_awaited_event();
   id = ev->x;
}
printf("The result is: %s\n", (char *)ev.data);
 

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

7 The application library interface

7.1 Constants

LPAPP_VERSION - version of LinPac that the linrary came with
ST_xxxx - connection status constants (see chapter 6.4)

7.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;

7.3 Functions

7.3.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);

7.3.2 Basic communication functions

int lp_start_appl()
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 lp_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 lp_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 lp_wait_event(int chn, int type)
Wait until the event with the same chn and type values are received.

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

void lp_wait_realize()
Realizes waiting initialized by lp_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.

Event *lp_awaited_event()
After return from lp_wait_event() or lp_wait_realize() this function returns the event that stopped the waiting.

Event *lp_copy_event(Event *dest, const Event *src)
Copy the event structure (deep copy).

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

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

void lp_end_appl()
Closes the connection to LinPac.

7.3.3 Automatic event handling functions

void lp_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 lp_event_handling_off()
Switches the automatic event handling off. Events must be read from the queue using the lp_get_event() function.

void lp_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.

7.3.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. See chapter 6.4 for more detailed description and list of functions.

7.3.5 User functions

void lp_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 lp_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 lp_remove_statline()
Removes the status line.

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

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

void lp_wait_connect(int chn, const char *call)
Waits for a connection with specified callsign on specified channel.

7.3.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).

7.3.7 Application information functions

char *lp_version()
Returns current LinPac version.

int lp_channel()
Returns the channel number where the application was started. Returns 0 when tha application was not started using linpac.

int lp_app_remote()
Returns non-zero value if the application was started using a remote command in LinPac (application communicates with remote user).


Last update: 15.9.2001