> For the complete documentation index, see [llms.txt](https://prosbcdocs.telcobridges.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://prosbcdocs.telcobridges.com/telecom-references/protocols/cas-r2-scripting.md).

# CAS R2 scripting

### Introduction

This page contains information about TelcoBridges CAS R2 variant scripting.

Refer to the default script (itu.lua) in the Toolpack Web Portal for a complete working variant script example.

In this page, using the term "application" may refer to Toolpack or any other application using the basic TelcoBridges CAS R2 stack API.

## Overview

[CAS R2](https://github.com/telcobridges-main/tmedia-wiki/tree/main/reference/protocols/cas/README.md) signaling is done in two parts: line signaling and register signaling. In CAS R2 for E1 trunks, line signaling uses a single [timeslot](https://github.com/telcobridges-main/tmedia-wiki/tree/main/reference/transmission/timeslot/README.md) to communicate call states (such as off-hook, answering) for the remaining timeslots. Register signaling is the exchange of MFR2 tones to convey information such as the calling number, called number and calling party category. TelcoBridges CAS R2 scripts allow complete customization of the register signaling process, while having some characteristics of the line signaling process customizable. Scripts also contain information relative to the conversion of register signaling data - group B signals and categories - into a format that the application can interpret. The scripting language is Lua.

## Mandatory elements

In order for CAS R2 variant scripts to work, some variables, tables and events must be defined from scripts. All of the following elements are required. If one of these elements is not present, it will not be possible to save the script in the Toolpack Web Portal or load it on the adapter.

#### VARIANT\_ID

The VARIANT\_ID variable must be filled to distinguish variants from each other. More precisely, it is used when transporting \[\[#Group B conversion information|group B]] and \[\[#Category conversion information|category]] information with calls in order to convert information meaning across variants.

Default CAS R2 TelcoBridges scripts have variant IDs starting from 1. To avoid future conflicts, user scripts variant IDs should be prefixed with a sufficiently high value. For example, a modified ITU variant could have a ID equal to 0x0001001. Scripts may only share the same variant ID as other scripts if the category and group B meanings are exactly identical.

### Group B conversion information

Group B conversion information in scripts is used to convert group B information between CAS R2 variants and between other signaling types. The following elements must be filled so that these conversions can be completed successfully.

#### GROUPB\_DIGIT\_TO\_MEANING

Each GROUPB\_DIGIT\_TO\_MEANING table element must contain two values: a digit and a meaning. The digit must be a valid digit value (1 to 15) and the meaning must be a valid meaning (see \[\[#Group B meanings|Group B meanings]]). Each digit must be present in the table.

This table is used to convert group B digits to meaning in the context of an outgoing call. For a given digit, the specified meaning will be propagated to the application.

#### GROUPB\_MEANING\_TO\_DIGIT

Each GROUPB\_MEANING\_TO\_DIGIT table element must contain two values: a meaning and a digit. Meanings must not appear more than once in the table.

This table is used to convert meanings to digits for an incoming call. This is mostly used for calls where the other call legs belong to another signaling type. It will be used if the other leg's signaling type is CAS R2 but the variant is different and there was no match in the \[\[#GROUPB\_OTHER\_DIGITS|GROUPB\_OTHER\_DIGITS]] table.

If a meaning is not found in this table, the meaning corresponding to \[\[#GROUPB\_DEFAULT\_DIGIT|GROUPB\_DEFAULT\_DIGIT]] will be used.

#### GROUPB\_DEFAULT\_DIGIT

This variable must be filled with a valid digit value. It will be used when lookups in the \[\[#GROUPB\_MEANING\_TO\_DIGIT|GROUPB\_MEANING\_TO\_DIGIT]] table fail.

#### GROUPB\_OTHER\_DIGITS

Each GROUPB\_OTHER\_DIGITS table element must contain three values: a variant ID and two valid digit values. This table may be empty but cannot be omitted.

This table is used to convert a variant ID and a digit combination to a digit for the current variant in an outgoing call scenario.

### Category conversion information

Category conversion information in scripts is used to convert category information between CAS R2 variants and between other signaling types. The following elements must be filled so that these conversions can be completed successfully.

The pattern used to handle categories is identical to the one used for \[\[#Group B conversion information|group B conversions]].

#### CATEGORY\_DIGIT\_TO\_MEANING

Each CATEGORY\_DIGIT\_TO\_MEANING table element must contain two values: a digit and a meaning. The digit must be a valid digit value (1 to 15) and the meaning must be a valid meaning (see \[\[#Category meanings|Category meanings]]). Each digit must be present in the table.

This table is used to convert category digits to meaning in the context of an outgoing call. For a given digit, the specified meaning will be propagated to the application.

#### CATEGORY\_MEANING\_TO\_DIGIT

Each CATEGORY\_MEANING\_TO\_DIGIT table element must contain two values: a meaning and a digit. Meanings must not appear more than once in the table.

This table is used to convert meanings to digits for an incoming call. This is mostly used for calls where the other leg belongs to another signaling type, although it will be used if the other leg's signaling type is CAS R2 but the variant is different and there was no match in the \[\[#CATEGORY\_OTHER\_DIGITS|CATEGORY\_OTHER\_DIGITS]] table.

If a meaning is not found in this table, the meaning corresponding to \[\[#CATEGORY\_DEFAULT\_DIGIT|CATEGORY\_DEFAULT\_DIGIT]] will be used.

#### CATEGORY\_DEFAULT\_DIGIT

This variable must be filled with a valid digit value. It will be used when lookups in the \[\[#CATEGORY\_MEANING\_TO\_DIGIT|CATEGORY\_MEANING\_TO\_DIGIT]] table fail.

#### CATEGORY\_OTHER\_DIGITS

Each CATEGORY\_OTHER\_DIGITS table element must contain three values: a variant ID and two valid digit values. This table may be empty but cannot be omitted.

This table is used to convert a variant ID and a digit combination to a digit for the current variant in an outgoing call scenario.

### Event handlers

Four register signaling event handlers must be defined in the script.

#### Call context table

Each event handler will have a table passed as a parameter. This table is the call context table, and contains critical information about the state of the call. Once calls are created (through Bwd\_HandleNewCall and Fwd\_HandleNewCall), the script must initialize the table with its own state information. Also, for incoming calls, as they go on, the script must fill the table with the collected signaling information. For outgoing calls, the table already contains this signaling information. The signaling information fields contained in the table are as follows:

| Table element     | Description                                                                                                                 |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------- |
| DestinationNumber | String of digits representing the called (destination) number.                                                              |
| OriginNumber      | String of digits representing the calling (origin) number.                                                                  |
| Category          | Digit representing the calling party category. See \[\[#Category conversion information\|Category conversion information]]. |

#### Return values

Each event handlers must return two values. The first value is the action to take immediately or shortly following the call of the event. It must be set to one of the four following values:

| First return value | Description                                                                                                               |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| WAIT\_SIGNAL       | Generally emits the digit provided as the second return value, and waits for the response or the next compelled sequence. |
| END\_SIGNALING     | Ends the call with the provided digit.                                                                                    |
| VALIDATE\_CALL     | (Incoming only) Sends the cumulated signaling information to the application and ends the signaling.                      |
| PULSE\_SIGNAL      | (Incoming only) Emits a pulsed signal.                                                                                    |

The second return value is the digit that accompanies the action, or **NO\_DIGIT** if no digit must be emitted. Its meaning depends on the first return value.

#### Backward event handlers

The following event functions must be defined so that the CAS R2 stack can proceed with register signaling for incoming calls.

**Bwd\_HandleNewCall**

The Bwd\_HandleNewCall event is called whenever an incoming call is discovered on a timeslot. The purpose of this event is for the script to initialize local variables that will be used throughout the tone exchanges.

The event will have the call context table passed as a parameter. This table must be filled with the call state information required by the script for a new incoming call.

The event must return two values as described in the following table:

| First return value | Description                                                                                            |
| ------------------ | ------------------------------------------------------------------------------------------------------ |
| WAIT\_SIGNAL       | Waits for the first compelled sequence to be initiated. The second return value must be **NO\_DIGIT**. |
| END\_SIGNALING     | Ends the call immediately. The second return value must be **NO\_DIGIT**.                              |

**Bwd\_HandleFwdSignal**

The Bwd\_HandleFwdSignal is called whenever a tone signal has been received, which is most likely the beginning of a compelled sequence.

The event will receive two parameters: the call context table (which was also passed to Bwd\_HandleNewCall) and the received tone signal. The event must use the received tone signal to fill the DestinationNumber, OriginNumber and Category fields of the call context table.

The event must return two values as described in the following table:

| First return value | Description                                                                                                                                                                                                                                                                                                                                                                                            |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| WAIT\_SIGNAL       | Waits for the next compelled sequence to be initiated. The second return value must be a valid digit as it is emitted as a response to the current compelled sequence.                                                                                                                                                                                                                                 |
| END\_SIGNALING     | Ends the call immediately. The second return value can be either **NO\_DIGIT** or a valid digit. If the digit is valid and has an acceptance meaning (see the \[\[#Group B conversion information\|Group B conversion information section]]), the call will be accepted without explicit validation by the application. Otherwise, the call will be refused. In both cases, the digit will be emitted. |
| VALIDATE\_CALL     | Sends the cumulated signaling information to the application. The application will then provide a group B meaning (or digit) that will be sent to the outgoing end.                                                                                                                                                                                                                                    |
| PULSE\_SIGNAL      | Instead of waiting for the next compelled sequence, the event handler will be called again with **NO\_DIGIT** as a second parameter. The second return value must be a valid digit since it will be sent to complete the current compelled sequence.                                                                                                                                                   |

#### Forward event handlers

The following event functions must be defined so that the CAS R2 stack can proceed with register signaling for outgoing calls.

**Fwd\_HandleNewCall**

The Fwd\_HandleNewCall event is called whenever an outgoing call is initiated on a timeslot. The purpose of this event is for the script to initialize local variables that will be used throughout the tone exchanges.

The event will have the call context table passed as a parameter. This table must be filled with the call state information required by the script for a new incoming call.

The event must return two values as described in the following table:

| First return value | Description                                                                                                                                                                                                                              |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| WAIT\_SIGNAL       | Waits for the response to the compelled sequence to be received. The second return value can be **NO\_DIGIT** if a pulsed signal is expected. Otherwise, it must be a valid digit that is used to initiate the first compelled sequence. |
| END\_SIGNALING     | Ends the call immediately. The second return value must be **NO\_DIGIT**.                                                                                                                                                                |

**Fwd\_HandleBwdSignal**

The Fwd\_HandleBwdSignal event is called whenever a tone signal has been received as a response to the current compelled sequence, which is most likely the beginning of a compelled sequence.

The event will receive two parameters: the call context table (which was also passed to Fwd\_HandleNewCall) and the received tone signal. The event must use the available DestinationNumber, OriginNumber and Category fields from the call context table to communicate information to the incoming end.

The event must return two values as described in the following table:

| First return value | Description                                                                                                                                                                                                                              |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| WAIT\_SIGNAL       | Waits for the response to the compelled sequence to be received. The second return value can be **NO\_DIGIT** if a pulsed signal is expected. Otherwise, it must be a valid digit that is used to initiate the first compelled sequence. |
| END\_SIGNALING     | Ends the call immediately. The second value must be **NO\_DIGIT**.                                                                                                                                                                       |

## Optional elements

The following elements may, or may not be, defined in a CAS R2 script.

#### SCRIPT\_FILE\_NAME

When affecting a value to this variable, the Toolpack Web Portal will automatically replace the value to the script name followed by the script revision. If the following piece of code is appended at the end of the script (this is done for default scripts), it will print a trace when loading a CAS R2 stack which can be recovered using an application such as [tblogtrace](https://github.com/telcobridges-main/tmedia-wiki/tree/main/tmedia/operations/tblogtrace/README.md).

#### VARIABLES

The VARIABLES table is used to declare variables which can be altered through the Toolpack Web Portal. Typically, variables declared here contain parameters that affect particular trunks. Each row of this table must contain three elements: the variable name, the variable's default value and the variable's description.

## Good practices

* Use the **local** keyword for declaring variables as much as possible. Non-local variables will stay alive outside the scope of event handlers, which in turn will take more CPU time in the form of garbage collection.

## Tone generation module selection

By default the VoIP DSP devices are used to generate the MFCR2 tones. If the unit has only IVR DSP devices, or for other reasons, this can be changed by adding these lines to the scripts:

```
BWD_VP_GROUP = 0
FWD_VP_GROUP = 0
```

## Script keyword reference

### Stack variables

These variables are declared before the VARIABLES table is parsed in a script. A single script will modify the value one of these variables. It is also possible to edit these variables in the Toolpack Web Portal.

| Variable name                         | Default value | Description                                                                                                        |
| ------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------ |
| TIMER\_BWD\_TONE                      | 15000         | Maximum time before a call is closed because the forward end did not emit a tone.                                  |
| TIMER\_BWD\_PULSE                     | 250           | Length of a pulsed digit.                                                                                          |
| TIMER\_BWD\_PULSE\_GUARD              | 100           | Time between the end of a compelled sequence and the beginning of a pulsed digit.                                  |
| TIMER\_BWD\_PULSE\_DETECTION          | 3000          | Time elapsed after a compelled sequence that triggers a pulsed digit.                                              |
| TIMER\_BWD\_ALERT                     | 14000         | Maximum wait time for an ALERT API message.                                                                        |
| TIMER\_BWD\_ANSWER                    | 300000        | Maximum wait time for an ANSWER API message.                                                                       |
| TIMER\_BWD\_FIRST\_METERING\_INTERVAL | 150           | Maximum time for which the CAS bits should stay in the ANSWER state before changing to METERING.                   |
| TIMER\_BWD\_METERING\_INTERVAL        | 60000         | Maximum time for which the CAS bits should stay in the ANSWER state before changing to METERING.                   |
| TIMER\_BWD\_METERING\_PULSE           | 150           | Maximum time for which the CAS bits should stay in the METERING state before changing to ANSWER.                   |
| TIMER\_BWD\_TERMINATE                 | 3000          | Maximum wait time for an TERMINATE API message.                                                                    |
| TIMER\_BWD\_WAIT\_CLEAR\_FORWARD      | 2000          | Maximum wait time for CLEAR\_FORWARD CAS bits change when closing a call.                                          |
| TIMER\_BWD\_HOLD\_ANSWER              | 100           | Maximum time for which the CAS bits should stay in the ANSWER state before changing to CLEAR\_BACKWARD.            |
| TIMER\_BWD\_HOLD\_CLEAR\_BACKWARD     | 200           | Maximum time for which the CAS bits should stay in the CLEAR\_BACKWARD state.                                      |
| TIMER\_BWD\_HOLD\_FORCED\_RELEASE     | 200           | Maximum time for which the CAS bits should stay in the FORCED\_RELEASE state.                                      |
| TIMER\_BWD\_HOLD\_IDLE                | 100           | Maximum time for which the CAS bits should stay in the IDLE state before starting a new call on the same timeslot. |
| TIMER\_FWD\_TONE                      | 15000         | Maximum time before a call is closed because the forward end did not emit a tone.                                  |
| TIMER\_FWD\_TONE\_GUARD               | 0             | Time between the end of a compelled sequence and the beginning of the next one.                                    |
| TIMER\_FWD\_SEIZURE\_ACK\_BIT         | 200           | Maximum time for which the forward end should wait for a CAS bits SEIZURE\_ACKNOWLEDGE state.                      |
| TIMER\_FWD\_ANSWER\_BIT               | 300000        | Maximum time for which the forward end should wait for a CAS bits ANSWER state.                                    |
| TIMER\_FWD\_METERING\_PULSE           | 0             | Maximum wait time for an ANSWER CAS bit state to be triggered before a call is terminated.                         |
| TIMER\_FWD\_TERMINATE                 | 3000          | Maximum wait time for an TERMINATE API message.                                                                    |
| TIMER\_FWD\_HOLD\_SEIZURE             | 100           | Maximum time for which the SEIZURE CAS bits state should be held in case of a collision.                           |
| TIMER\_FWD\_HOLD\_IDLE                | 100           | Maximum time for which the CAS bits should stay in the IDLE state before starting a new call on the same timeslot. |
| TIMER\_CAS\_CHANGE                    | 20            | Time required for a CAS bits state change to take effect.                                                          |
| ABCD\_PATTERN\_IDLE                   | 0x1001        | CAS R2 bit pattern for the IDLE state.                                                                             |
| ABCD\_PATTERN\_BLOCKED                | 0x1101        | CAS R2 bit pattern for the BLOCKED state.                                                                          |
| ABCD\_PATTERN\_FWD\_SEIZURE           | 0x0001        | CAS R2 bit pattern for the forward SEIZURE state.                                                                  |
| ABCD\_PATTERN\_FWD\_CLEAR\_FWD        | 0x1001        | CAS R2 bit pattern for the forward CLEAR state.                                                                    |
| ABCD\_PATTERN\_BWD\_SEIZURE\_ACK      | 0x1101        | CAS R2 bit pattern for the backward SEIZURE ACKNOWLEDGE state.                                                     |
| ABCD\_PATTERN\_BWD\_ANSWERED          | 0x0101        | CAS R2 bit pattern for the backward ANSWERED state.                                                                |
| ABCD\_PATTERN\_BWD\_CLEAR\_BWD        | 0x1101        | CAS R2 bit pattern for the backward CLEAR state.                                                                   |
| ABCD\_PATTERN\_BWD\_FORCED\_RELEASE   | 0x0001        | CAS R2 bit pattern for the backward FORCED RELEASE state.                                                          |
| ABCD\_PATTERN\_MATCH\_MASK            | 0x1100        | CAS R2 bit match mask pattern.                                                                                     |
| USE\_FORCED\_RELEASE                  | 0             | Flag indicating if the CAS R2 line signaling state machine should use the forced release method.                   |
| BWD\_METERING\_PULSE\_COUNT           | 0             | Number of metering pulses that the CAS R2 line signaling state machine should emit.                                |

### Group B meanings

Here is the list of all defined group B meanings:

```
ACCEPT_CHARGE
ACCEPT_NO_CHARGE
REJECT_UNSPECIFIED
REJECT_UNALLOCATED_NUMBER
REJECT_NO_ROUTE_TO_NETWORK
REJECT_NO_ROUTE_TO_DESTINATION
REJECT_USER_BUSY
REJECT_SUBSCRIBER_ABSENT
REJECT_CALL_REJECTED
REJECT_NUMBER_CHANGED
REJECT_EXCHANGE_ROUTING_ERROR
REJECT_DESTINATION_OUT_OF_ORDER
REJECT_ADDRESS_INCOMPLETE
REJECT_NO_CIRCUIT_AVAILABLE
REJECT_NETWORK_OUT_OF_ORDER
REJECT_TEMPORARY_FAILURE
REJECT_SWITCHING_EQUIP_CONGESTION
REJECT_REQUESTED_CIRCUIT_NOT_AVAILABLE
REJECT_RESOURCE_UNAVAILABLE
REJECT_SERVICE_NOT_AVAILABLE
REJECT_CALL_IDENTITY_DOES_NOT_EXIST
REJECT_CALL_IDENTITY_IN_USE
REJECT_PROTOCOL_ERROR
REJECT_INTERWORKING_UNSPECIFIED
```

### Category meanings

Here is the list of all defined category meanings:

```
CATEGORY_UNKNOWN
CATEGORY_OPERATOR_FRENCH
CATEGORY_OPERATOR_ENGLISH
CATEGORY_OPERATOR_GERMAN
CATEGORY_OPERATOR_RUSSIAN
CATEGORY_OPERATOR_SPANISH
CATEGORY_SUBSCRIBER
CATEGORY_SUBSCRIBER_WITH_PRIORITY
CATEGORY_DATA
CATEGORY_TEST
CATEGORY_PAYPHONE
```

[Link to Routing script calling party categories](https://github.com/telcobridges-main/tmedia-wiki/tree/main/reference/api/routing-script-tutorial-development-guide/README.md#calling-party-category)

## References

* [Lua Programming Language official website](http://www.lua.org)
* [Line signaling Wikipedia article](http://en.wikipedia.org/wiki/Line_signaling)
* [Register signaling Wikipedia article](http://en.wikipedia.org/wiki/Register_signaling)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://prosbcdocs.telcobridges.com/telecom-references/protocols/cas-r2-scripting.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
