LinPac - Packet Radio Terminal for Linux


Version 0.28

(c) Martin Cooper KD6YAM 2020
(c) David Ranch KI6ZHD (linpac@trinnet.net) 2002 - 2020
(c) 1998 - 2001 by Radek Burget OK2JBG

External Application Programming Guide

Contents

1 Introduction

2 What is an external program?

3 Basic concepts of the API

4 How 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 to 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

8 The shell interface
8.1 Writing the script
8.1.1 Ensuring that LinPac is running
8.1.2 Accessing configuration and state
8.1.3 Executing commands
8.1.4 Simple shell example
8.2 Creating the command

1 Introduction

This guide is written for programmers who want to add some new functions to LinPac. In the following text, basic knowledge of Linux programming is assumed. Reading the LinPac User Manual before proceeding is also recommended.

2 What is an external program?

An external program is a standard Linux application which uses LinPac to communicate with remote stations. There are basically two types of LinPac external programs: No special knowledge of LinPac is needed for creating the first type of programs, because no LinPac functions are used. The remainder of this guide is dedicated to the second type of applications.

3 Basic concepts of the API

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

All the events generated by any object are put into the common event queue. The 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 of the objects. The reaction of each object fully depends on its functionality, but of course it can include generation of other 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 a shared variable environment. This is a set of variables that is shared with LinPac; the values are automatically synchronized with all the external programs. These variables are accessed using special functions of the API as described below.

4 How applications communicate with LinPac

LinPac uses TCP/IP sockets for communication with external programs (applications). The connection is always initiated by the application after it starts. There are basically two ways that an application may be started: In both cases, the start of an application causes the creation of a new object in LinPac called an event gate. This object represents the application within LinPac. Bearing in mind the previous chapter, this means that the application is forwarded all of the events generated by any LinPac object, and all of the events generated by the application are forwarded to all LinPac objects.

NOTE: All of the communication via TCP/IP sockets is provided by the LinPac application library. The user application should not attempt to 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 file lpapp.h, which is installed by default to /usr/local/include/linpac. The next chapter illustrates how to use the library within a user application.

5.1 The simplest application

The following application example just tries to contact LinPac, and prints the result.

#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 success or 0 when a connection to LinPac cannot be made (probably because it's not running). This function should precede the usage of any other application library functions.

The function lp_end_appl() closes the connection to LinPac.

To compile this example, use:

$ 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 appears to run on channel 0 of LinPac. This is useful for some applications that are used to control LinPac from outside. However this is not a typical use case.

For most applications, it is better to copy the executable to the $LINPACDIR/bin directory and then add it to the file $LINPACDIR/bin/commands as described in the User Manual. After this, the application can be executed as a LinPac command. In this scenario, the streams are properly redirected and the application output is visible in the LinPac QSO window. It is also possible to select the channel on which to run 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 applications, can generate events to inform other parts (internal modules or applications) that something has happened. Each event is sent to all LinPac components and applications. For example when some station connects to some LinPac channel, the internal AX.25 interface generates an event reporting that the station has connected and includes its callsign. All components and applications now know who has connected, and they can take some actions. For example, the output window prints information about the connection, the macro processor executes the cinit.mac macro, and so on. Each application can handle all of the events too, and can generate events which are handled by other components.

An 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 as follows:

type
Specifies the type of the event. Actually it determines what happened. There is a symbolic constant defined for each known event type.
chn
Specifies the channel to which the event applies. For example, if the type of the event specifies that some data was received, the chn field contains the number of the channel which has received that data. There are many events that apply for all the channels. For those events, this field is not significant.
x, y
The meaning of these fields depends on the event type. The y field is usually not used, other than by some internal events.
ch
This field is used only by some internal events.
data
Depends on the type of the event. It usually points to some string data or a char buffer.

All of the event types are described in the event list.

6.2 Sending and receiving events

For sending events the following function is used:

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

This generates a new event using the specified values. Each argument corresponds to one of the fields in the Event structure.

There are two modes for handling incoming events:

a) Reading each event on demand

This mode is started by the lp_event_handling_off() call. In this mode, events are read explicitly using the function:

int get_event(Event *ev);

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

WARNING #1: The data field in your Event structure must point to a dynamically allocated buffer. The size of the buffer is reallocated automatically after receiving an event. When the data field is set to NULL, a new buffer is allocated. This field must be initialized.

WARNING #2: In this mode, the application must read all events. It is not a good idea to stop reading events, because the event queue may overflow. LinPac will automatically kill the application when the event queue exceeds some reasonable number of events.

b) Automatic event processing

This mode is started by the lp_event_handling_on() call. All events are read automatically. Programmers can define their own function that will be called automatically when an event occurs. When no such function is defined, all events are discarded.

The event handling function must have following prototype:

void my_event_handler(Event *ev);

(The function name may be different.) After initializing the application, the event handling function must be registered using the function:

lp_set_event_handler()

from the application library.

The following example is an application that prints the types of all events received and stops when an EV_ABORT event 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 automatic 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 and inefficient. For this reason, the LinPac API offers an alternative for waiting for events, namely 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 automatic 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 may be interrupted when an event is received. An interrupted system call returns an error result (for example the read() call returns -1), sets errno to EAGAIN, and must be called again. To avoid this, use the interrupt-safe versions of the system calls contained in this application library. (See Chapter 7.3.1.)

6.3 Synchronization

An event generated by an application is sent to all modules and applications, including the application that generated the event. When there is a 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 events were processed, there is an EV_VOID event. It is not handled by any module. After sending all events, just generate an EV_VOID event and wait until it returns. After that, you can be assured that all previous events have been processed.

6.4 Shared variables and configuration

Each shared variable is denoted by its name (string) and channel number. Each variable has a value represented by a string (char[]). Access to these 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 specified name.

The value of each variable is automatically 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.

NOTE: Many of the variables contain boolean values. Their value is 1 when true, 0 otherwise.

Currently the following system variables are defined (in channel 0):

_remote
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 arguments for 'listen' program
_maxchn
maximal number of channels
_last_act
time of last user activity (same format as the time() system call).

These variables may be read using the lp_get_var() function defined above. Furthermore there are two special functions defined for reading these variables. These functions expect the name of the system variable without the leading underscore.

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

The 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. The following status constants are 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.

The 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 an application wants to get the status of the connection on a certain LinPac channel, it generates the EV_STAT_REQ event on this channel. In response, 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

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

6.6.1 Connecting to a remote station

When initiating the connection, the first step is to check that the channel is free (i.e. it is not in use for another 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 the appropriate channel. The data field of the event contains a C string with the destination address in the form port:callsign [digi [digi ...]].

The last step is to wait until the connection is established. For this the function lp_wait_connect() can be 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 application may run LinPac commands by emitting the EV_DO_COMMAND event. For example, to download 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);

Another option is to use the EV_WANT_RESULT event. The usage is similar to the previous example, but the x field of the event has special meaning: as a response to this event, LinPac will generate an EV_CMD_RESULT event with the same x field and with the data field containing the 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
the version of LinPac that the library 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

The following functions work the same way as the original system calls, but they are interrupt-safe. That is, 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 communication with LinPac. A non-zero return value means success; a zero value means that LinPac cannot be contacted (probably because it's not running).
int lp_get_event(Event *ev)
Read an event from the queue. A non-zero return value means a successful read; a 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 should not be used when automatic event processing is used.
int lp_emit_event(int chn, int type, int x, void *data)
Generate a new event. The arguments correspond to the fields in the event structure. The return value is always 0.
void lp_wait_event(int chn, int type)
Wait until an event with the same chn and type values are received.
void lp_wait_init(int chn, int type)
The same as lp_wait_event() but returns immediately. Waiting is provided by following function lp_wait_realize().
void lp_wait_realize()
Realizes waiting initialized by lp_wait_init(). All the events that arrived since the last lp_wait_init() call are ignored. lp_wait_realize() may exit immediately if the event has already arrived.
Event *lp_awaited_event()
After return from a call to 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 (using a deep copy).
void lp_discard_event(Event *ev)
Free the memory used by the data field of Event structure received using lp_get_event().
void lp_clear_event_queue()
Remove all events from the event queue. This has no purpose when automatic event processing is enabled.
void lp_end_appl()
Closes the connection to LinPac.

7.3.3 Automatic event handling functions

void lp_event_handling_on()
Enables automatic event handling. From this point onwards, each event is automatically read from the queue, treated with an event handler function (if defined) and then discarded.
void lp_event_handling_off()
Disables automatic event handling. 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 with signature void my_event_handler(Event *ev). The event handler is called automatically each time an event is received, when automatic event handling is enabled.

7.3.4 Environment functions

LinPac has its own environment for storing variables. Each application can share and modify this environment using environment-related functions. Each channel has its own environment. See Chapter 6.4 for a detailed description and list of functions.

7.3.5 User functions

void lp_appl_result(const char *fmt, ...)
Set the final result of the application. This function generates an EV_APP_RESULT event with the specified message string. The argument format is the same as for printf().
void lp_statline(const char *fmt, ...)
Displays or changes the additional status line in the LinPac user interface. Only one additional status line is displayed. This function generates a EV_CHANGE_STLINE event with the x field (line ID) containing the PID of the application. To display more than one status line for the application, additional EV_CHANGE_STLINE events must be generated manually.
void lp_remove_statline()
Removes the additional status line.
void lp_disable_screen()
Disables displaying data in the QSO window on application's channel. The EV_DISABLE_SCREEN event is used to accomplish this.
void lp_enable_screen()
Enables displaying data in the QSO window. The EV_ENABLE_SCREEN event is used to accomplish this.
void lp_wait_connect(int chn, const char *call)
Waits for a connection with the specified callsign on the specified channel.

7.3.6 Tool functions

char *time_stamp(int utc)
Returns a pointer to a C string that contains the actual time. If utc is 0, then local time is used; otherwise UTC time is used.
char *date_stamp(int utc)
Returns the date-string.
void replace_macros(int chn, char *s)
Replaces macro variables in the string (i.e. %xxx) with their values. The %(command) macro is not replaced.
void get_port_name(int n)
Returns the name of the nth port in axports (starting from 0).

7.3.7 Application information functions

char *lp_version()
Returns the current LinPac version.
int lp_channel()
Returns the channel number on which the application was started. Returns 0 when the application was not started using LinPac.
int lp_app_remote()
Returns a non-zero value if the application was started using a remote command in LinPac (i.e. the application is communicating with a remote user).

8 The shell interface

In addition to the C API described in the above chapters, LinPac also provides a set of functions that allow programmers to create new LinPac commands using bash shell scripts. While this set of functions is limited, it is sufficient to enable quite sophisticated and complex commands to be added to LinPac without requiring programming in C or C++.

8.1 Writing the script

The shell functions are all accessed through the lpapi command, which has the following form:

lpapi <channel> [command] [arguments]

The specifics of the available commands are described in the following sections.

The channel on which the script application is running is made available to the script as the $LPCHN shell environment variable. The use of this variable is demonstrated below.

8.1.1 Ensuring that LinPac is running

The first step in any LinPac shell command should be to ensure that LinPac is running, such that subsequent use of the shell interface can proceed. This is accomplished by calling the API as follows:

lpapi 0

This command will exit with a 0 result code if LinPac is running. Any other result code indicates that LinPac is not running, in which case the script should most likely echo an error message to the user and exit. As usual, the result code can be determined by examining the special $? value.

8.1.2 Accessing configuration and state

It is important that a shell script be able to determine the current status of LinPac and retrieve configuration values. The API provides several functions to enable this.

All of these functions return values that can be assigned to a shell variable, and are used in the following manner (using "call" as an example here):

MYVAR=`lpapi $LPCHN call`

The available functions are as follows:

call
Return the callsign for the specified channel.
cwit
Return the callsign of the station connected on the specified channel.
port
Return the port of the station connected on the specified channel.
state
Return current status of the specified channel (as a number).
pname <number>
Return the name of port with the specified number.
get <variable>
Return the value of specified variable on the specified channel.

8.1.3 Executing commands

Accomplishing real work with the shell interface will usually require calling into LinPac to execute other LinPac commands. This is achieved using the do command, which is functionally equivalent to generating the EV_DO_COMMAND event from the C API.

The do command has the following form:

lpapi <channel> do <command> [arguments]

However, since do is a reserved word in Bash shell scripts, it is necessary to use Bash's eval command to invoke it as a LinPac function, as follows:

eval lpapi <channel> do "<command> [arguments]"

IMPORTANT: The do command is asynchronous. That is, the shell command may return before the command issued to LinPac has completed. A script will need to account for this in considering subsequent actions.

8.1.4 Simple shell example

TBD

8.2 Creating the command

The steps to add the script to LinPac as a new command are essentially the same as for an application written in C, described in Chapter 5.1 above. That is:
  1. Copy the script to the $LINPACDIR/bin directory, making sure that the permissions allow execution.
  2. Add the new command to the file $LINPACDIR/bin/commands as described in the User Manual.

Last update: 16 Feb 2020