Implementation of NMT (Nordic Mobile Telephoe) network

This commit is contained in:
Andreas Eversberg 2016-02-21 18:13:30 +01:00
parent cbfc818cce
commit 57caa536cf
19 changed files with 10866 additions and 3 deletions

1
.gitignore vendored
View File

@ -22,3 +22,4 @@ m4
src/common/libcommon.a
src/anetz/anetz
src/bnetz/bnetz
src/nmt/nmt

View File

@ -30,6 +30,7 @@ AC_OUTPUT(
src/common/Makefile
src/anetz/Makefile
src/bnetz/Makefile
src/nmt/Makefile
src/Makefile
Makefile)

View File

@ -1,3 +1,3 @@
AUTOMAKE_OPTIONS = foreign
SUBDIRS = common anetz bnetz
SUBDIRS = common anetz bnetz nmt

View File

@ -39,6 +39,8 @@ struct debug_cat {
{ "audio", "\033[0;31m" },
{ "anetz", "\033[1;34m" },
{ "bnetz", "\033[1;34m" },
{ "nmt", "\033[1;34m" },
{ "frame", "\033[0;36m" },
{ "call", "\033[1;37m" },
{ "mncc", "\033[1;32m" },
};

View File

@ -10,8 +10,10 @@
#define DAUDIO 3
#define DANETZ 4
#define DBNETZ 5
#define DCALL 6
#define DMNCC 7
#define DNMT 6
#define DFRAME 7
#define DCALL 8
#define DMNCC 9
#define PDEBUG(cat, level, fmt, arg...) _printdebug(__FILE__, __FUNCTION__, __LINE__, cat, level, fmt, ## arg)
void _printdebug(const char *file, const char *function, int line, int cat, int level, const char *fmt, ...);

19
src/nmt/Makefile.am Normal file
View File

@ -0,0 +1,19 @@
AM_CPPFLAGS = -Wall -g $(all_includes)
bin_PROGRAMS = \
nmt
nmt_SOURCES = \
nmt.c \
dsp.c \
frame.c \
image.c \
tones.c \
announcement.c \
main.c
nmt_LDADD = \
$(COMMON_LA) \
$(ALSA_LIBS) \
$(top_builddir)/src/common/libcommon.a \
-lm

7161
src/nmt/announcement.c Normal file

File diff suppressed because it is too large Load Diff

3
src/nmt/announcement.h Normal file
View File

@ -0,0 +1,3 @@
void init_announcement(void);

596
src/nmt/dsp.c Normal file
View File

@ -0,0 +1,596 @@
/* NMT audio processing
*
* (C) 2016 by Andreas Eversberg <jolly@eversberg.eu>
* All Rights Reserved
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <math.h>
#include "../common/debug.h"
#include "../common/timer.h"
#include "../common/call.h"
#include "../common/goertzel.h"
#include "nmt.h"
#include "dsp.h"
#define PI M_PI
/* signalling */
#define TX_PEAK_FSK 16384 /* peak amplitude of signalling FSK */
#define TX_PEAK_SUPER 1638 /* peak amplitude of supervisory signal */
#define BIT_RATE 1200 /* baud rate */
#define STEPS_PER_BIT 10 /* step every 1/12000 sec */
#define DIALTONE_HZ 425.0 /* dial tone frequency */
#define TX_PEAK_DIALTONE 16000 /* dial tone peak */
#define SUPER_DURATION 0.25 /* duration of supervisory signal measurement */
#define SUPER_DETECT_COUNT 4 /* number of measures to detect supervisory signal */
#define MUTE_DURATION 0.280 /* a tiny bit more than two frames */
/* two signalling tones */
static double fsk_bits[2] = {
1800.0,
1200.0,
};
/* two supervisory tones */
static double super_freq[5] = {
3955.0, /* 0-Signal 1 */
3985.0, /* 0-Signal 2 */
4015.0, /* 0-Signal 3 */
4045.0, /* 0-Signal 4 */
3900.0, /* noise level to check against */
};
/* table for fast sine generation */
int dsp_sine_super[256];
int dsp_sine_dialtone[256];
/* global init for FSK */
void dsp_init(void)
{
int i;
double s;
PDEBUG(DFSK, DEBUG_DEBUG, "Generating sine table for supervisory signal.\n");
for (i = 0; i < 256; i++) {
s = sin((double)i / 256.0 * 2.0 * PI);
dsp_sine_super[i] = (int)(s * TX_PEAK_SUPER);
dsp_sine_dialtone[i] = (int)(s * TX_PEAK_DIALTONE);
}
}
/* Init FSK of transceiver */
int dsp_init_sender(nmt_t *nmt)
{
double coeff;
int16_t *spl;
int i;
init_compander(&nmt->cstate, 8000, 3.0, 13.5);
if ((nmt->sender.samplerate % (BIT_RATE * STEPS_PER_BIT))) {
PDEBUG(DFSK, DEBUG_ERROR, "Sample rate must be a multiple of %d bits per second.\n", BIT_RATE * STEPS_PER_BIT);
return -EINVAL;
}
/* this should not happen. it is implied by previous check */
if (nmt->supervisory && nmt->sender.samplerate < 12000) {
PDEBUG(DFSK, DEBUG_ERROR, "Sample rate must be at least 12000 Hz to process supervisory signal.\n");
return -EINVAL;
}
PDEBUG(DFSK, DEBUG_DEBUG, "Init DSP for Transceiver.\n");
/* allocate sample for 2 bits with 2 polarities */
nmt->samples_per_bit = nmt->sender.samplerate / BIT_RATE;
PDEBUG(DFSK, DEBUG_DEBUG, "Using %d samples per bit duration.\n", nmt->samples_per_bit);
nmt->fsk_filter_step = nmt->samples_per_bit / STEPS_PER_BIT;
PDEBUG(DFSK, DEBUG_DEBUG, "Using %d samples per filter step.\n", nmt->fsk_filter_step);
nmt->fsk_sine[0][0] = calloc(4, nmt->samples_per_bit * sizeof(int16_t));
nmt->fsk_sine[0][1] = nmt->fsk_sine[0][0] + nmt->samples_per_bit;
nmt->fsk_sine[1][0] = nmt->fsk_sine[0][1] + nmt->samples_per_bit;
nmt->fsk_sine[1][1] = nmt->fsk_sine[1][0] + nmt->samples_per_bit;
if (!nmt->fsk_sine[0][0]) {
PDEBUG(DFSK, DEBUG_ERROR, "No memory!\n");
return -ENOMEM;
}
/* generate sines */
for (i = 0; i < nmt->samples_per_bit; i++) {
nmt->fsk_sine[0][0][i] = TX_PEAK_FSK * sin(3.0 * PI * (double)i / (double)nmt->samples_per_bit); /* 1.5 waves */
nmt->fsk_sine[0][1][i] = TX_PEAK_FSK * sin(2.0 * PI * (double)i / (double)nmt->samples_per_bit); /* 1 wave */
nmt->fsk_sine[1][0][i] = -nmt->fsk_sine[0][0][i];
nmt->fsk_sine[1][1][i] = -nmt->fsk_sine[0][1][i];
}
/* allocate ring buffers, one bit duration */
spl = calloc(1, nmt->samples_per_bit * sizeof(*spl));
if (!spl) {
PDEBUG(DFSK, DEBUG_ERROR, "No memory!\n");
return -ENOMEM;
}
nmt->fsk_filter_spl = spl;
nmt->fsk_filter_bit = -1;
/* allocate transmit buffer for a complete frame */
spl = calloc(166, nmt->samples_per_bit * sizeof(*spl));
if (!spl) {
PDEBUG(DFSK, DEBUG_ERROR, "No memory!\n");
return -ENOMEM;
}
nmt->frame_spl = spl;
/* allocate ring buffer for supervisory signal detection */
nmt->super_samples = (int)((double)nmt->sender.samplerate * SUPER_DURATION + 0.5);
spl = calloc(166, nmt->super_samples * sizeof(*spl));
if (!spl) {
PDEBUG(DFSK, DEBUG_ERROR, "No memory!\n");
return -ENOMEM;
}
nmt->super_filter_spl = spl;
/* count symbols */
for (i = 0; i < 2; i++) {
coeff = 2.0 * cos(2.0 * PI * fsk_bits[i] / (double)nmt->sender.samplerate);
nmt->fsk_coeff[i] = coeff * 32768.0;
PDEBUG(DFSK, DEBUG_DEBUG, "coeff[%d] = %d\n", i, (int)nmt->fsk_coeff[i]);
}
/* count supervidory tones */
for (i = 0; i < 5; i++) {
coeff = 2.0 * cos(2.0 * PI * super_freq[i] / (double)nmt->sender.samplerate);
nmt->super_coeff[i] = coeff * 32768.0;
PDEBUG(DFSK, DEBUG_DEBUG, "supervisory coeff[%d] = %d\n", i, (int)nmt->super_coeff[i]);
if (i < 4) {
nmt->super_phaseshift256[i] = 256.0 / ((double)nmt->sender.samplerate / super_freq[i]);
PDEBUG(DFSK, DEBUG_DEBUG, "phaseshift_super[%d] = %.4f\n", i, nmt->super_phaseshift256[i]);
}
}
super_reset(nmt);
/* dial tone */
nmt->dial_phaseshift256 = 256.0 / ((double)nmt->sender.samplerate / DIALTONE_HZ);
/* dtmf */
dtmf_init(&nmt->dtmf, 8000);
return 0;
}
/* Cleanup transceiver instance. */
void dsp_cleanup_sender(nmt_t *nmt)
{
PDEBUG(DFSK, DEBUG_DEBUG, "Cleanup DSP for 'Sender'.\n");
if (nmt->frame_spl) {
free(nmt->frame_spl);
nmt->frame_spl = NULL;
}
if (nmt->fsk_filter_spl) {
free(nmt->fsk_filter_spl);
nmt->fsk_filter_spl = NULL;
}
if (nmt->super_filter_spl) {
free(nmt->super_filter_spl);
nmt->super_filter_spl = NULL;
}
}
/* Check for SYNC bits, then collect data bits */
static void fsk_receive_bit(nmt_t *nmt, int bit, double quality, double level)
{
double frames_elapsed;
// printf("bit=%d quality=%.4f\n", bit, quality);
if (!nmt->fsk_filter_in_sync) {
nmt->fsk_filter_sync = (nmt->fsk_filter_sync << 1) | bit;
/* check if pattern 1010111100010010 matches */
if (nmt->fsk_filter_sync != 0xaf12)
return;
// printf("sync\n");
/* sync time */
nmt->rx_sample_count_last = nmt->rx_sample_count_current;
nmt->rx_sample_count_current = nmt->rx_sample_count - nmt->samples_per_bit * 26;
/* rest sync register */
nmt->fsk_filter_sync = 0;
nmt->fsk_filter_in_sync = 1;
nmt->fsk_filter_count = 0;
nmt->fsk_filter_levelsum = 0;
nmt->fsk_filter_qualitysum = 0;
/* set muting of receive path */
nmt->fsk_filter_mute = (int)((double)nmt->sender.samplerate * MUTE_DURATION);
return;
}
/* read bits */
nmt->fsk_filter_frame[nmt->fsk_filter_count++] = bit + '0';
nmt->fsk_filter_levelsum += level;
nmt->fsk_filter_qualitysum += quality;
if (nmt->fsk_filter_count != 140)
return;
/* end of frame */
nmt->fsk_filter_frame[140] = '\0';
nmt->fsk_filter_in_sync = 0;
/* send telegramm */
frames_elapsed = (double)(nmt->rx_sample_count_current - nmt->rx_sample_count_last) / (double)(nmt->samples_per_bit * 166);
nmt_receive_frame(nmt, nmt->fsk_filter_frame, nmt->fsk_filter_qualitysum / 140.0, nmt->fsk_filter_levelsum / 140.0, frames_elapsed);
}
char *show_level(int value)
{
static char text[22];
value /= 5;
if (value < 0)
value = 0;
if (value > 20)
value = 20;
strcpy(text, " ");
text[value] = '*';
return text;
}
//#define DEBUG_MODULATOR
//#define DEBUG_FILTER
//#define DEBUG_QUALITY
/* Filter one chunk of audio an detect tone, quality and loss of signal.
* The chunk is a window of 10ms. This window slides over audio stream
* and is processed every 1ms. (one step) */
static inline void fsk_decode_step(nmt_t *nmt, int pos)
{
double level, result[2], softbit, quality;
int max;
int16_t *spl;
int bit;
max = nmt->samples_per_bit;
spl = nmt->fsk_filter_spl;
/* count time in samples*/
nmt->rx_sample_count += nmt->fsk_filter_step;
level = audio_level(spl, max);
// level = 0.63662 / 2.0;
audio_goertzel(spl, max, pos, nmt->fsk_coeff, result, 2);
/* calculate soft bit from both frequencies */
softbit = (result[1] / level - result[0] / level + 1.0) / 2.0;
/* scale it, since both filters overlap by some percent */
#define MIN_QUALITY 0.33
softbit = (softbit - MIN_QUALITY) / (1.0 - MIN_QUALITY - MIN_QUALITY);
if (softbit > 1)
softbit = 1;
if (softbit < 0)
softbit = 0;
#ifdef DEBUG_FILTER
// printf("|%s", show_level(result[0]/level*100));
// printf("|%s| low=%.3f high=%.3f level=%d\n", show_level(result[1]/level*100), result[0]/level, result[1]/level, (int)level);
printf("|%s| softbit=%.3f\n", show_level(softbit * 100), softbit);
#endif
if (softbit > 0.5)
bit = 1;
else
bit = 0;
if (nmt->fsk_filter_bit != bit) {
#ifdef DEBUG_FILTER
puts("bit change");
#endif
/* if we have a bit change, reset sample counter to one half bit duration */
nmt->fsk_filter_bit = bit;
nmt->fsk_filter_sample = 5;
} else if (--nmt->fsk_filter_sample == 0) {
#ifdef DEBUG_FILTER
puts("sample");
#endif
/* if sample counter bit reaches 0, we reset sample counter to one bit duration */
// quality = result[bit] / level;
if (softbit > 0.5)
quality = softbit * 2.0 - 1.0;
else
quality = 1.0 - softbit * 2.0;
#ifdef DEBUG_QUALITY
printf("|%s| quality=%.2f ", show_level(softbit * 100), quality);
printf("|%s|\n", show_level(quality * 100));
#endif
/* adjust level, so a peak level becomes 100% */
fsk_receive_bit(nmt, bit, quality, level / 0.63662);
nmt->fsk_filter_sample = 10;
}
}
/* compare supervisory signal against noise floor on 3900 Hz */
static void super_decode(nmt_t *nmt, int16_t *samples, int length)
{
int coeff[2];
double result[2], quality;
coeff[0] = nmt->super_coeff[nmt->supervisory - 1];
coeff[1] = nmt->super_coeff[4]; /* noise floor detection */
audio_goertzel(samples, length, 0, coeff, result, 2);
#if 0
/* normalize levels */
result[0] *= 32768.0 / (double)TX_PEAK_SUPER / 0.63662;
result[1] *= 32768.0 / (double)TX_PEAK_SUPER / 0.63662;
printf("signal=%.4f noise=%.4f\n", result[0], result[1]);
#endif
quality = (result[0] - result[1]) / result[0];
if (quality < 0)
quality = 0;
if (nmt->sender.loopback)
PDEBUG(DFSK, DEBUG_NOTICE, "Supervisory level %.2f%% quality %.0f%%\n", result[0] / 0.63662 * 100.0, quality * 100.0);
if (quality > 0.5) {
if (nmt->super_detected == 0) {
nmt->super_detect_count++;
if (nmt->super_detect_count == SUPER_DETECT_COUNT) {
nmt->super_detected = 1;
nmt->super_detect_count = 0;
PDEBUG(DFSK, DEBUG_DEBUG, "Supervisory signal detected with level=%.0f%%, quality=%.0f%%.\n", result[0] / 0.63662 * 100.0, quality * 100.0);
nmt_rx_super(nmt, 1, quality);
}
} else
nmt->super_detect_count = 0;
} else {
if (nmt->super_detected == 1) {
nmt->super_detect_count++;
if (nmt->super_detect_count == SUPER_DETECT_COUNT) {
nmt->super_detected = 0;
nmt->super_detect_count = 0;
PDEBUG(DFSK, DEBUG_DEBUG, "Supervisory signal lost.\n");
nmt_rx_super(nmt, 0, 0.0);
}
} else
nmt->super_detect_count = 0;
}
}
/* Reset supervisory detection states, so ongoing tone will be detected again. */
void super_reset(nmt_t *nmt)
{
PDEBUG(DFSK, DEBUG_DEBUG, "Supervisory detector reset.\n");
nmt->super_detected = 0;
nmt->super_detect_count = 0;
}
/* Process received audio stream from radio unit. */
void sender_receive(sender_t *sender, int16_t *samples, int length)
{
nmt_t *nmt = (nmt_t *) sender;
int16_t *spl;
int max, pos, step;
int i;
/* write received samples to decode buffer */
max = nmt->super_samples;
spl = nmt->super_filter_spl;
pos = nmt->super_filter_pos;
for (i = 0; i < length; i++) {
spl[pos++] = samples[i];
if (pos == max) {
pos = 0;
if (nmt->supervisory)
super_decode(nmt, spl, max);
}
}
nmt->super_filter_pos = pos;
/* write received samples to decode buffer */
max = nmt->samples_per_bit;
pos = nmt->fsk_filter_pos;
step = nmt->fsk_filter_step;
spl = nmt->fsk_filter_spl;
for (i = 0; i < length; i++) {
#ifdef DEBUG_MODULATOR
printf("|%s|\n", show_level((int)((samples[i] / (double)TX_PEAK_FSK) * 50)+50));
#endif
spl[pos++] = samples[i];
if (nmt->fsk_filter_mute) {
samples[i] = 0;
nmt->fsk_filter_mute--;
}
if (pos == max)
pos = 0;
/* if filter step has been reched */
if (!(pos % step)) {
fsk_decode_step(nmt, pos);
}
}
nmt->fsk_filter_pos = pos;
if ((nmt->dsp_mode == DSP_MODE_AUDIO || nmt->dsp_mode == DSP_MODE_DTMF)
&& nmt->sender.callref) {
int16_t down[length]; /* more than enough */
int count;
count = samplerate_downsample(&nmt->sender.srstate, samples, length, down);
if (nmt->compander)
expand_audio(&nmt->cstate, down, count);
if (nmt->dsp_mode == DSP_MODE_DTMF)
dtmf_tone(&nmt->dtmf, down, count);
spl = nmt->sender.rxbuf;
pos = nmt->sender.rxbuf_pos;
for (i = 0; i < count; i++) {
spl[pos++] = down[i];
if (pos == 160) {
call_tx_audio(nmt->sender.callref, spl, 160);
pos = 0;
}
}
nmt->sender.rxbuf_pos = pos;
} else
nmt->sender.rxbuf_pos = 0;
}
static int fsk_frame(nmt_t *nmt, int16_t *samples, int length)
{
int16_t *spl;
const char *frame;
int i;
int bit, polarity;
int count, max;
next_frame:
if (!nmt->frame) {
/* request frame */
frame = nmt_get_frame(nmt);
if (!frame) {
PDEBUG(DFSK, DEBUG_DEBUG, "Stop sending frames.\n");
return length;
}
nmt->frame = 1;
nmt->frame_pos = 0;
spl = nmt->frame_spl;
/* render frame */
polarity = nmt->fsk_polarity;
for (i = 0; i < 166; i++) {
bit = (frame[i] == '1');
memcpy(spl, nmt->fsk_sine[polarity][bit], nmt->samples_per_bit * sizeof(*spl));
spl += nmt->samples_per_bit;
/* flip polarity when we have 1.5 sine waves */
if (bit == 0)
polarity = 1 - polarity;
}
nmt->fsk_polarity = polarity;
}
/* send audio from frame */
max = nmt->samples_per_bit * 166;
count = max - nmt->frame_pos;
if (count > length)
count = length;
spl = nmt->frame_spl + nmt->frame_pos;
for (i = 0; i < count; i++) {
*samples++ = *spl++;
}
length -= count;
nmt->frame_pos += count;
/* check for end of telegramm */
if (nmt->frame_pos == max) {
nmt->frame = 0;
/* we need more ? */
if (length)
goto next_frame;
}
return length;
}
/* Generate audio stream with supervisory signal. Keep phase for next call of function. */
static void super_encode(nmt_t *nmt, int16_t *samples, int length)
{
double phaseshift, phase;
int32_t sample;
int i;
phaseshift = nmt->super_phaseshift256[nmt->supervisory - 1];
phase = nmt->super_phase256;
for (i = 0; i < length; i++) {
sample = *samples;
sample += dsp_sine_super[((uint8_t)phase) & 0xff];
if (sample > 32767)
sample = 32767;
else if (sample < -32767)
sample = -32767;
*samples++ = sample;
phase += phaseshift;
if (phase >= 256)
phase -= 256;
}
nmt->super_phase256 = phase;
}
/* Generate audio stream from dial tone. Keep phase for next call of function. */
static void dial_tone(nmt_t *nmt, int16_t *samples, int length)
{
double phaseshift, phase;
int i;
phaseshift = nmt->dial_phaseshift256;
phase = nmt->dial_phase256;
for (i = 0; i < length; i++) {
*samples++ = dsp_sine_dialtone[((uint8_t)phase) & 0xff];
phase += phaseshift;
if (phase >= 256)
phase -= 256;
}
nmt->dial_phase256 = phase;
}
/* Provide stream of audio toward radio unit */
void sender_send(sender_t *sender, int16_t *samples, int length)
{
nmt_t *nmt = (nmt_t *) sender;
int len;
again:
switch (nmt->dsp_mode) {
case DSP_MODE_AUDIO:
case DSP_MODE_DTMF:
jitter_load(&nmt->sender.audio, samples, length);
if (nmt->supervisory)
super_encode(nmt, samples, length);
break;
case DSP_MODE_DIALTONE:
dial_tone(nmt, samples, length);
break;
case DSP_MODE_SILENCE:
memset(samples, 0, length * sizeof(*samples));
break;
case DSP_MODE_FRAME:
/* Encode frame into audio stream. If frames have
* stopped, process again for rest of stream. */
len = fsk_frame(nmt, samples, length);
/* special case: add supervisory signal to frame at loop test */
if (nmt->sender.loopback && nmt->supervisory)
super_encode(nmt, samples, length);
if (len) {
samples += length - len;
length = len;
goto again;
}
break;
}
}
void nmt_set_dsp_mode(nmt_t *nmt, enum dsp_mode mode)
{
/* reset telegramm */
if (mode == DSP_MODE_FRAME && nmt->dsp_mode != mode)
nmt->frame = 0;
nmt->dsp_mode = mode;
}

7
src/nmt/dsp.h Normal file
View File

@ -0,0 +1,7 @@
void dsp_init(void);
int dsp_init_sender(nmt_t *nmt);
void dsp_cleanup_sender(nmt_t *nmt);
void nmt_set_dsp_mode(nmt_t *nmt, enum dsp_mode mode);
void super_reset(nmt_t *nmt);

977
src/nmt/frame.c Normal file
View File

@ -0,0 +1,977 @@
/* NMT frame transcoding
*
* (C) 2016 by Andreas Eversberg <jolly@eversberg.eu>
* All Rights Reserved
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "../common/debug.h"
#include "../common/timer.h"
#include "nmt.h"
#include "frame.h"
uint64_t nmt_encode_channel(int channel, int power)
{
uint64_t value = 0;
if (channel >= 200) {
value |= 0x800;
channel -= 200;
}
if (channel >= 100) {
value |= 0x100;
channel -= 100;
}
value |= channel;
value |= power << 9;
return value;
}
int nmt_decode_channel(uint64_t value, int *channel, int *power)
{
if ((value & 0xff) > 99)
return -1;
*channel = (value & 0xff) +
((value & 0x100) >> 8) * 100 +
((value & 0x800) >> 11) * 200;
*power = (value & 0x600) >> 9;
return 0;
}
void nmt_value2digits(uint64_t value, char *digits, int num)
{
int digit, i;
for (i = 0; i < num; i++) {
digit = (value >> ((num - 1 - i) << 2)) & 0xf;
if (digit == 10)
digits[i] = '0';
else if (digit == 0 || digit > 10)
digits[i] = '?';
else
digits[i] = digit + '0';
}
}
uint64_t nmt_digits2value(const char *digits, int num)
{
int digit, i;
uint64_t value = 0;
for (i = 0; i < num; i++) {
value <<= 4;
digit = *digits++;
if (digit >= '1' && digit <= '9')
value |= digit - '0';
else
value |= 10;
}
return value;
}
char nmt_value2digit(uint64_t value)
{
return "D1234567890*#ABC"[value & 0x0000f];
}
uint16_t nmt_encode_area_no(uint8_t area_no)
{
switch (area_no) {
case 1:
return 0x3f3;
case 2:
return 0x3f4;
case 3:
return 0x3f5;
case 4:
return 0x3f6;
default:
return 0x000;
}
}
/* NMT Doc 450-1 4.3.2 */
static struct nmt_frame {
const char *digits;
enum nmt_direction direction;
int prefix;
const char *nr;
const char *description;
} nmt_frame[] = {
/* Digits Dir. Prefix Nr. Description */
/*0*/ { "NNNPYYHHHHHHHHHH", MTX_TO_MS, 12, "1a", "Calling channel indication" },
/*1*/ { "NNNPYYHHHHHHHHHH", MTX_TO_MS, 4, "1b", "Combined calling and traffic channel indication" },
/*2*/ { "NNNPYYZXXXXXXHHH", MTX_TO_MS, 12, "2a", "Call to mobile subscriber on calling channel" },
/*3*/ { "NNNPYYZXXXXXXnnn", MTX_TO_MS, 12, "2b", "Traffic channel allocation on calling channel" },
/*4*/ { "NNNPYYZXXXXXXHHH", MTX_TO_MS, 12, "2c", "Queueing information to MS with priority on calling channel" },
/*5*/ { "NNNPYYZXXXXXXHHH", MTX_TO_MS, 12, "2d", "Traffic channel scanning order on calling channel" },
/*6*/ { "NNNPYYZXXXXXXHHH", MTX_TO_MS, 12, "2f", "Queuing information to ordinary MS" },
/*7*/ { "NNNPYYZXXXXXXnnn", MTX_TO_MS, 5, "3a", "Traffic channel allocation on traffic channel" },
/*8*/ { "NNNPYYZXXXXXXHHH", MTX_TO_MS, 5, "3b", "Identity request on traffic channel" },
/*9*/ { "NNNPYYZXXXXXXnnn", MTX_TO_MS, 9, "3c", "Traffic channel allocation on traffic channel, short procedure" },
/*10*/ { "NNNPYYJJJJJJJHHH", MTX_TO_MS, 3, "4", "Free traffic channel indication" },
/*11*/ { "NNNPYYZXXXXXXLLL", MTX_TO_MS, 6, "5a", "Line signal" },
/*12*/ { "NNNPYYZXXXXXXLQQ", MTX_TO_MS, 6, "5b", "Line signal: Answer to coin-box" },
/*13*/ { "JJJPJJJJJJJJJJJJ", MTX_TO_XX, 0, "6", "Idle frame" },
/*14*/ { "NNNPYYCCCCCCCJJJ", MTX_TO_MS, 8, "7", "Authentication request" },
/*15*/ { "NNNPZXXXXXXTJJJJ", MS_TO_MTX, 1, "10a", "Call acknowledgement from MS on calling channel (shortened frame)" },
/*16*/ { "NNNPZXXXXXXTYKKK", MS_TO_MTX, 1, "10b", "Seizure from ordinary MS and identity on traffic channel" },
/*17*/ { "NNNPZXXXXXXTYKKK", MS_TO_MTX, 6, "10c", "Seizure and identity from called MS on traffic channel" },
/*18*/ { "NNNPZXXXXXXTYKKK", MS_TO_MTX, 14, "11a", "Roaming updating seizure and identity on traffic channel" },
/*19*/ { "NNNPZXXXXXXTYKKK", MS_TO_MTX, 15, "11b", "Seizure and call achnowledgement on calling channel from MS with priority (shortened frame)" },
/*20*/ { "NNNPZXXXXXXTYKKK", MS_TO_MTX, 11, "12", "Seizure from coin-box on traffic channel" },
/*21*/ { "NNNPZXXXXXXLLLLL", MS_TO_MTX, 8, "13a", "Line signal" },
/*22*/ { "NNNPZXXXXXXLLLQQ", MS_TO_MTX, 8, "13b", "Line signal: Answer acknowledgement from coin box" },
/*23*/ { "NNNPZXXXXXXSSSSS", MS_TO_MTX, 7, "14a", "Digit signal (1st, 3rd, 5th ........digit)" },
/*24*/ { "NNNPZXXXXXXSSSSS", MS_TO_MTX, 7, "14b", "Digit signal (2nd, 4th, 6th ........digit)" },
/*25*/ { "JJJPJJJJJJJJJJJJ", XX_TO_MTX, 0, "15", "Idle frame" },
/*26*/ { "NNNPRRRRRRRRRRRR", MS_TO_MTX, 12, "16", "Signed response" },
/*27*/ { "NNNPYYZJJJAfffff", MTX_TO_BS, 15, "20", "Channel activation order" },
/*28*/ { "NNNPYYZJJJAJJJJJ", MTX_TO_BS, 15, "20", "Channel activation order" },
/*29*/ { "NNNPYYZJJJAfffff", MTX_TO_BS, 15, "20", "Channel activation order" },
/*30*/ { "NNNPYYZJJJAlllff", MTX_TO_BS, 15, "20", "Channel activation order" },
/*31*/ { "NNNPYYZJJJAlllJJ", MTX_TO_BS, 15, "20", "Channel activation order" },
/*32*/ { "NNNPYYZJJJVJJnnn", MTX_TO_BS, 3, "21b", "Signal strength measurement order on data channel or idle or free marked traffic channel" },
/*33*/ { "NNNPYYZJJJVJJnnn", MTX_TO_BS, 5, "21c", "Signal strength measurement order on traffic actually used" },
/*34*/ { "NNNPYYZJJJVVVVVV", MTX_TO_BS, 14, "22", "Order management/maintenance order on idle channel or data channel" },
/*35*/ { "NNNPZJJAJJJJJJJJ", BS_TO_MTX, 9, "25", "Channel status information" },
/*36*/ { "NNNPZJJAJJJfllJJ", BS_TO_MTX, 9, "25", "Channel status information" },
/*37*/ { "NNNPZJJAJJJJllJJ", BS_TO_MTX, 9, "25", "Channel status information" },
/*38*/ { "NNNPZJJAJJJcccJJ", BS_TO_MTX, 9, "25", "Channel status information" },
/*39*/ { "NNNPZJJnnnrrrrrr", BS_TO_MTX, 2, "26", "Signal strength measurement result" },
/*40*/ { "NNNPZJJVVVVJJJJJ", BS_TO_MTX, 4, "27", "Response on other management/maintenance order on idle channel or data channel" },
/*41*/ { "NNNPZJJVVVVJJJJJ", BS_TO_MTX, 13, "28", "Other maintenance information from BS" },
/*42*/ { "NNNPYYJJJJJJJHHH", MTX_TO_MS, 10, "30", "Test channel indication" },
/*43*/ { "---P------------", MTX_TO_XX, 0, "", "illegal (Spare)" },
/*44*/ { "---P------------", XX_TO_MTX, 0, "", "illegal (Spare)" },
{ NULL, 0, 0, NULL, NULL }
};
/* store actual number of frames for run-time range check */
static int num_frames;
const char *nmt_frame_name(int index)
{
if (index < 0 || index >= num_frames)
return "invalid";
return nmt_frame[index].nr;
}
static const char *param_integer(uint64_t value, int ndigits, enum nmt_direction direction)
{
static char result[32];
sprintf(result, "%" PRIu64, value);
return result;
}
static const char *param_hex(uint64_t value, int ndigits, enum nmt_direction direction)
{
static char result[32];
sprintf(result, "0x%" PRIx64, value);
return result;
}
static const char *param_channel_no(uint64_t value, int ndigits, enum nmt_direction direction)
{
static char result[32];
int rc, channel, power;
rc = nmt_decode_channel(value, &channel, &power);
if (rc < 0)
sprintf(result, "invalid(%" PRIu64 ")", value);
else
sprintf(result, "channel=%d power=%d", channel, power);
return result;
}
static const char *param_country(uint64_t value, int ndigits, enum nmt_direction direction)
{
static char result[32];
switch (value) {
case 0:
return "no additional info";
case 4:
return "Iceland";
case 5:
return "Denmark";
case 6:
return "Sweden";
case 7:
return "Norway";
case 8:
return "Finland";
case 9:
return "nordic country";
case 14:
return "additional info";
case 15:
return "information to/from BS";
default:
sprintf(result, "%" PRIu64 " (unknown)", value);
return result;
}
}
static const char *param_number(uint64_t value, int ndigits, enum nmt_direction direction)
{
static char result[32];
nmt_value2digits(value, result, ndigits);
result[ndigits] = '\0';
return result;
}
static const char *param_ta(uint64_t value, int ndigits, enum nmt_direction direction)
{
static char result[32];
nmt_value2digits(value, result, ndigits);
result[ndigits] = '\0';
return result;
}
static const char *param_line_signal(uint64_t value, int ndigits, enum nmt_direction direction)
{
static char result[64], *desc = "Spare";
if (direction == MTX_TO_MS) {
switch (value & 0xf) {
case 0:
desc = "Answer to coin-box";
break;
case 3:
desc = "Proceed to send unencrypted digits";
break;
case 4:
desc = "Acknowledge MFT converter in";
break;
case 5:
desc = "Switch compander in";
break;
case 6:
desc = "Address complete";
break;
case 7:
desc = "Switch compander out";
break;
case 9:
desc = "Ringing order";
break;
case 10:
desc = "Acknowledge MFT converter out";
break;
case 11:
desc = "Proceed to send enctrypted digits";
break;
case 13:
desc = "Clearing, call transfer activated";
break;
case 15:
desc = "Clearing, call transfer not activated";
break;
}
} else {
switch (value & 0xf) {
case 1:
desc = "Clearing, release guard";
break;
case 2:
desc = "Answer acknowledgement, (coin-box)";
break;
case 5:
desc = "Register recall ";
break;
case 7:
desc = "MFT converter out acknowledge";
break;
case 8:
desc = "MFT converter in";
break;
case 14:
desc = "Answer";
break;
}
}
sprintf(result, "L(%" PRIu64 ") %s", value & 0xf, desc);
return result;
}
static const char *param_digit(uint64_t value, int ndigits, enum nmt_direction direction)
{
static char result[32];
if ((value & 0xf0000) != 0x00000 && (value & 0xf0000) != 0xf0000)
return "Invalid digit";
if ((value & 0xf0000) != ((value & 0x0f000) << 4)
|| (value & 0x00f00) != ((value & 0x000f0) << 4)
|| (value & 0x000f0) != ((value & 0x0000f) << 4))
return "Inconsistent digit";
result[0] = nmt_value2digit(value);
result[1] = '\0';
return result;
}
static const char *param_supervisory(uint64_t value, int ndigits, enum nmt_direction direction)
{
switch (value) {
case 0:
return "Reserved";
case 3:
return "Frequency 1";
case 12:
return "Frequency 2";
case 9:
return "Frequency 3";
case 6:
return "Frequency 4";
default:
return "Invalid";
}
}
static const char *param_password(uint64_t value, int ndigits, enum nmt_direction direction)
{
static char result[32];
nmt_value2digits(value, result, ndigits);
result[ndigits] = '\0';
return result;
}
static struct nmt_parameter {
char digit;
const char *description;
const char *(*decoder)(uint64_t value, int ndigits, enum nmt_direction direction);
} nmt_parameter[] = {
{ 'N', "Channel No.", param_channel_no },
{ 'n', "TC No.", param_channel_no },
{ 'Y', "Traffic area", param_ta },
{ 'Z', "Mobile subscriber country", param_country },
{ 'X', "Mobile subscriber No.", param_number },
{ 'Q', "Tariff class", param_integer },
{ 'L', "Line signal", param_line_signal },
{ 'S', "Digit signals", param_digit },
{ 'J', "Idle information", param_hex },
{ 'A', "Channel activation", param_hex },
{ 'V', "Management order", param_hex },
{ 'r', "Measurement results", param_hex },
{ 'P', "Prefix", param_integer },
{ 'f', "Supervisory signal", param_supervisory },
{ 'K', "Mobile subscriber password", param_password },
{ 'T', "Area info", param_hex },
{ 'H', "Additional info", param_hex },
{ 'C', "Random challenge", param_hex },
{ 'R', "Signed response", param_hex },
{ 'l', "Limit strength evaluation", param_hex },
{ 'c', "c", param_hex },
{ 0, NULL }
};
/* Depending on P-value, direction and additional info, frame index (used for
* nmt_frame[]) is recoded.
*/
static int decode_frame_index(const uint8_t *digits, enum nmt_direction direction, int callack)
{
if (direction == MS_TO_MTX || direction == BS_TO_MTX || direction == XX_TO_MTX) {
/* MS/BS TO MTX */
switch (digits[3]) {
case 0:
return 25;
case 1:
if (callack)
return 15;
return 16;
case 2:
return 39;
case 3:
break;
case 4:
return 40;
case 5:
break;
case 6:
return 17;
case 7:
if (digits[11] == 0)
return 23;
if (digits[11] == 15)
return 24;
return -1;
case 8:
if (digits[11] == 2)
return 22;
return 21;
case 9:
switch((digits[13] << 8) + (digits[14] << 4) + digits[15]) {
case 2:
case 6:
return 36;
case 14:
return 37;
case 7:
case 8:
return 38;
default:
return 35;
}
case 10:
break;
case 11:
return 20;
case 12:
return 26;
case 13:
return 41;
case 14:
return 18;
case 15:
return 19;
}
return 44;
} else {
/* MTX to MS/BS */
switch (digits[3]) {
case 0:
return 13;
case 1:
break;
case 2:
break;
case 3:
if (digits[6] == 15)
return 32;
return 10;
case 4:
return 1;
case 5:
if (digits[6] == 15)
return 33;
switch((digits[13] << 8) + (digits[14] << 4) + digits[15]) {
case 0x3f3:
case 0x3f4:
case 0x3f5:
case 0x3f6:
case 0x000:
return 8;
default:
return 7;
}
case 6:
if (digits[13] == 0)
return 12;
return 11;
case 7:
break;
case 8:
return 14;
case 9:
return 9;
case 10:
return 42;
case 11:
break;
case 12:
/* no subscriber */
if (digits[6] == 0)
return 0;
/* battery saving */
if (digits[6] == 14)
return 0;
/* info to BS (should not happen here) */
if (digits[6] == 15)
return 0;
switch((digits[13] << 8) + (digits[14] << 4) + digits[15]) {
case 0x3f3:
case 0x3f4:
case 0x3f5:
case 0x3f6:
case 0x000:
return 2;
case 0x3f0:
return 6;
case 0x3f1:
return 4;
case 0x3f2:
return 5;
default:
return 3;
}
case 13:
break;
case 14:
if (digits[13] != 15)
break;
return 34;
case 15:
if (digits[13] != 15)
break;
switch (digits[10]) {
case 3:
return 27;
case 6:
case 13:
return 29;
case 7:
case 14:
return 30;
case 15:
return 31;
default:
return 28;
}
}
return 43;
}
}
int init_frame(void)
{
int i, j, k;
char digit;
/* check if all digits actually exist */
for (i = 0; nmt_frame[i].digits; i++) {
for (j = 0; j < 16; j++) {
digit = nmt_frame[i].digits[j];
if (digit == '-')
continue;
for (k = 0; nmt_parameter[k].digit; k++) {
if (nmt_parameter[k].digit == digit)
break;
}
if (!nmt_parameter[k].digit) {
PDEBUG(DFRAME, DEBUG_ERROR, "Digit '%c' in message index %d does not exist, please fix!\n", digit, i);
return -1;
}
}
}
num_frames = i;
return 0;
}
/* decode 16 digits frame */
static void disassemble_frame(frame_t *frame, const uint8_t *digits, enum nmt_direction direction, int callack)
{
int index;
int i, j, ndigits;
char digit;
uint64_t value;
memset(frame, 0, sizeof(*frame));
/* index of frame */
index = decode_frame_index(digits, direction, callack);
frame->index = index;
/* update direction */
direction = nmt_frame[index].direction;
PDEBUG(DFRAME, DEBUG_DEBUG, "Decoding %s %s %s\n", nmt_dir_name(direction), nmt_frame[index].nr, nmt_frame[index].description);
for (i = 0; i < 16; i++) {
digit = nmt_frame[index].digits[i];
if (digit == '-')
continue;
value = digits[i];
ndigits = 1;
for (j = i + 1; j < 16; j++) {
if (nmt_frame[index].digits[j] != digit)
break;
value = (value << 4) | digits[j];
ndigits++;
i++;
}
switch (digit) {
case 'N':
frame->channel_no = value;
break;
case 'n':
frame->tc_no = value;
break;
case 'Y':
frame->traffic_area = value;
break;
case 'Z':
frame->ms_country = value;
break;
case 'X':
frame->ms_number = value;
break;
case 'Q':
frame->tariff_class = value;
break;
case 'L':
frame->line_signal = value;
break;
case 'S':
frame->digit = value;
break;
case 'J':
frame->idle = value;
break;
case 'A':
frame->chan_act = value;
break;
case 'V':
frame->meas_order = value;
break;
case 'r':
frame->meas = value;
break;
case 'P':
frame->prefix = value;
break;
case 'f':
frame->supervisory = value;
break;
case 'K':
frame->ms_password = value;
break;
case 'T':
frame->area_info = value;
break;
case 'H':
frame->additional_info = value;
break;
case 'C':
frame->rand = value;
break;
case 'R':
frame->sres = value;
break;
case 'l':
frame->limit_strength_eval = value;
break;
case 'c':
frame->c = value;
break;
default:
PDEBUG(DFRAME, DEBUG_ERROR, "Digit '%c' does not exist, please fix!\n", digit);
abort();
}
if (debuglevel <= DEBUG_DEBUG) {
for (j = 0; nmt_parameter[j].digit; j++) {
if (nmt_parameter[j].digit == digit) {
PDEBUG(DFRAME, DEBUG_DEBUG, " %c: %s\n", digit, nmt_parameter[j].decoder(value, ndigits, direction));
}
}
}
}
if (debuglevel <= DEBUG_DEBUG) {
char debug_digits[17];
for (i = 0; i < 16; i++)
debug_digits[i] = "0123456789abcdef"[digits[i]];
debug_digits[i] = '\0';
PDEBUG(DFRAME, DEBUG_DEBUG, "%s\n", nmt_frame[index].digits);
PDEBUG(DFRAME, DEBUG_DEBUG, "%s\n", debug_digits);
}
}
/* encode 16 digits frame */
static void assemble_frame(frame_t *frame, uint8_t *digits, int debug)
{
int index;
int i, j;
char digit;
uint64_t value;
enum nmt_direction direction;
index = frame->index;
if (index >= num_frames) {
PDEBUG(DFRAME, DEBUG_ERROR, "Frame index %d out of range (0..%d), please fix!\n", index, num_frames - 1);
abort();
}
/* set prefix of frame */
frame->prefix = nmt_frame[index].prefix;
/* retrieve direction */
direction = nmt_frame[index].direction;
if (debug)
PDEBUG(DFRAME, DEBUG_DEBUG, "Coding %s %s %s\n", nmt_dir_name(direction), nmt_frame[index].nr, nmt_frame[index].description);
for (i = 15; i >= 0; i--) {
digit = nmt_frame[index].digits[i];
if (digit == '-') {
digits[i] = 0;
continue;
}
switch (digit) {
case 'N':
value = frame->channel_no;
break;
case 'n':
value = frame->tc_no;
break;
case 'Y':
value = frame->traffic_area;
break;
case 'Z':
value = frame->ms_country;
break;
case 'X':
value = frame->ms_number;
break;
case 'Q':
value = frame->tariff_class;
break;
case 'L':
value = frame->line_signal;
break;
case 'S':
value = frame->digit;
break;
case 'J':
value = frame->idle;
break;
case 'A':
value = frame->chan_act;
break;
case 'V':
value = frame->meas_order;
break;
case 'r':
value = frame->meas;
break;
case 'P':
value = frame->prefix;
break;
case 'f':
value = frame->supervisory;
break;
case 'K':
value = frame->ms_password;
break;
case 'T':
value = frame->area_info;
break;
case 'H':
value = frame->additional_info;
break;
case 'C':
value = frame->rand;
break;
case 'R':
value = frame->sres;
break;
case 'l':
value = frame->limit_strength_eval;
break;
case 'c':
value = frame->c;
break;
default:
PDEBUG(DFRAME, DEBUG_ERROR, "Digit '%c' does not exist, please fix!\n", digit);
abort();
}
digits[i] = (value & 0xf);
value >>= 4;
for (j = i - 1; j >= 0; j--) {
if (nmt_frame[index].digits[j] != digit)
break;
digits[j] = (value & 0xf);
value >>= 4;
i--;
}
}
if (debug && debuglevel <= DEBUG_DEBUG) {
char debug_digits[17];
int ndigits;
for (i = 0; i < 16; i++) {
digit = nmt_frame[index].digits[i];
if (digit == '-')
continue;
value = digits[i];
ndigits = 1;
for (j = i + 1; j < 16; j++) {
if (nmt_frame[index].digits[j] != digit)
break;
value = (value << 4) | digits[j];
ndigits++;
i++;
}
for (j = 0; nmt_parameter[j].digit; j++) {
if (nmt_parameter[j].digit == digit) {
PDEBUG(DFRAME, DEBUG_DEBUG, " %c: %s\n", digit, nmt_parameter[j].decoder(value, ndigits, direction));
}
}
}
for (i = 0; i < 16; i++)
debug_digits[i] = "0123456789abcdef"[digits[i]];
debug_digits[i] = '\0';
PDEBUG(DFRAME, DEBUG_DEBUG, "%s\n", nmt_frame[index].digits);
PDEBUG(DFRAME, DEBUG_DEBUG, "%s\n", debug_digits);
}
}
/* encode digits of a frame to 166 bits */
static void encode_digits(const uint8_t *digits, char *bits)
{
uint8_t x[64];
int i;
uint8_t digit;
/* copy bit sync and frame sync */
memcpy(bits, "10101010101010111100010010", 26);
bits += 26;
for (i = 0; i < 16; i++) {
digit = *digits++;
x[(i << 2) + 0] = (digit >> 3) & 1;
x[(i << 2) + 1] = (digit >> 2) & 1;
x[(i << 2) + 2] = (digit >> 1) & 1;
x[(i << 2) + 3] = digit & 1;
}
/* parity check bits */
for (i = 0; i < 3; i++)
bits[(i << 1)] = '1' - x[i];
for (i = 3; i < 64; i++)
bits[(i << 1)] = '1' - (x[i] ^ x[i - 3]);
for (i = 64; i < 67; i++)
bits[(i << 1)] = '1' - x[i - 3];
for (i = 67; i < 70; i++)
bits[(i << 1)] = '1';
/* information bits */
for (i = 0; i < 6; i++)
bits[(i << 1) + 1] = '0';
for (i = 6; i < 70; i++)
bits[(i << 1) + 1] = x[i - 6] + '0';
}
/* decode digits from 140 bits (not including sync) */
// FIXME: do real convolutional decoding
static int decode_digits(uint8_t *digits, const char *bits, int callack)
{
uint8_t x[64];
int i, short_frame = 0;
/* information bits */
for (i = 0; i < 6; i++) {
if (bits[(i << 1) + 1] != '0')
return -1;
}
for (i = 6; i < 70; i++)
x[i - 6] = bits[(i << 1) + 1] - '0';
/* create digits */
for (i = 0; i < 16; i++) {
digits[i] = ((x[(i << 2) + 0] & 1) << 3)
| ((x[(i << 2) + 1] & 1) << 2)
| ((x[(i << 2) + 2] & 1) << 1)
| (x[(i << 2) + 3] & 1);
}
/* check for short frame */
if (callack && (digits[3] == 1 || digits[3] == 15)) {
digits[13] = 0;
digits[14] = 0;
digits[15] = 0;
short_frame = 1;
}
/* parity check bits */
for (i = 0; i < 3; i++) {
if (bits[(i << 1)] != '1' - x[i])
return -1;
}
for (i = 3; i < ((short_frame) ? 52 : 64); i++) {
if (bits[(i << 1)] != '1' - (x[i] ^ x[i - 3])) {
/* According to NMT Doc 450-3, bits after Y(114) shall
* be omitted for short frame. It would make more sense
* to stop after Y(116), so only the last three digits
* are omitted and not the last bit of digit13 also.
* Tests have showed that it we receive correctly up to
* Y(116), but we ignore an error, if only up to Y(114)
* is received.
*/
if (short_frame && i == 51) {
PDEBUG(DFRAME, DEBUG_DEBUG, "Frame bad after bit Y(114), ignoring.\n");
digits[13] = 0;
break;
}
return -1;
}
}
if (short_frame)
return 0;
for (i = 64; i < 67; i++) {
if (bits[(i << 1)] != '1' - x[i - 3])
return -1;
}
for (i = 67; i < 70; i++) {
if (bits[(i << 1)] != '1')
return -1;
}
return 0;
}
/* encode frame to bits
* debug can be turned on or off
*/
const char *encode_frame(frame_t *frame, int debug)
{
uint8_t digits[16];
static char bits[166];
assemble_frame(frame, digits, debug);
encode_digits(digits, bits);
return bits;
}
/* decode bits to frame */
int decode_frame(frame_t *frame, const char *bits, enum nmt_direction direction, int callack)
{
uint8_t digits[16];
int rc;
rc = decode_digits(digits, bits, callack);
if (rc < 0)
return rc;
disassemble_frame(frame, digits, direction, callack);
return 0;
}

84
src/nmt/frame.h Normal file
View File

@ -0,0 +1,84 @@
#define NMT_MESSAGE_1a 0
#define NMT_MESSAGE_1b 1
#define NMT_MESSAGE_2a 2
#define NMT_MESSAGE_2b 3
#define NMT_MESSAGE_2c 4
#define NMT_MESSAGE_2d 5
#define NMT_MESSAGE_2f 6
#define NMT_MESSAGE_3a 7
#define NMT_MESSAGE_3b 8
#define NMT_MESSAGE_3c 9
#define NMT_MESSAGE_4 10
#define NMT_MESSAGE_5a 11
#define NMT_MESSAGE_5b 12
#define NMT_MESSAGE_6 13
#define NMT_MESSAGE_7 14
#define NMT_MESSAGE_10a 15
#define NMT_MESSAGE_10b 16
#define NMT_MESSAGE_10c 17
#define NMT_MESSAGE_11a 18
#define NMT_MESSAGE_11b 19
#define NMT_MESSAGE_12 20
#define NMT_MESSAGE_13a 21
#define NMT_MESSAGE_13b 22
#define NMT_MESSAGE_14a 23
#define NMT_MESSAGE_14b 24
#define NMT_MESSAGE_15 25
#define NMT_MESSAGE_16 26
#define NMT_MESSAGE_20a 27
#define NMT_MESSAGE_20b 28
#define NMT_MESSAGE_20c 29
#define NMT_MESSAGE_20d 30
#define NMT_MESSAGE_20e 31
#define NMT_MESSAGE_21b 32
#define NMT_MESSAGE_21c 33
#define NMT_MESSAGE_22 34
#define NMT_MESSAGE_25a 35
#define NMT_MESSAGE_25b 36
#define NMT_MESSAGE_25c 37
#define NMT_MESSAGE_25d 38
#define NMT_MESSAGE_26 39
#define NMT_MESSAGE_27 40
#define NMT_MESSAGE_28 41
#define NMT_MESSAGE_30 42
typedef struct frame {
uint8_t index;
uint16_t channel_no;
uint16_t tc_no;
uint8_t traffic_area;
uint8_t ms_country;
uint32_t ms_number;
uint8_t tariff_class;
uint32_t line_signal;
uint32_t digit;
uint64_t idle;
uint8_t chan_act;
uint32_t meas_order;
uint32_t meas;
uint8_t prefix;
uint32_t supervisory;
uint16_t ms_password;
uint8_t area_info;
uint64_t additional_info;
uint32_t rand;
uint64_t sres;
uint16_t limit_strength_eval;
uint16_t c;
} frame_t;
int init_frame(void);
uint64_t nmt_encode_channel(int channel, int power);
int nmt_decode_channel(uint64_t value, int *channel, int *power);
void nmt_value2digits(uint64_t value, char *digits, int num);
uint64_t nmt_digits2value(const char *digits, int num);
char nmt_value2digit(uint64_t value);
uint16_t nmt_encode_area_no(uint8_t area_no);
const char *nmt_frame_name(int index);
const char *encode_frame(frame_t *frame, int debug);
int decode_frame(frame_t *frame, const char *bits, enum nmt_direction direction, int callack);

68
src/nmt/image.c Normal file
View File

@ -0,0 +1,68 @@
#include <stdio.h>
#include <string.h>
#include "image.h"
const char *image[] = {
"",
"@g ______ @r####@w##@r########",
" @g/ \\___ @r__ @r####@w##@r########",
" @g/ Hej! __\\ @r/ ) @r####@w##@r########",
" @g\\ / @r/ / @wNMT @w##############",
" @g\\______/ @r/ / @r####@w##@r########",
" @y_@G_@r/@G__@r/@y_ @b####@y##@b##@r####@w##@r########",
" @y/@G/ \\ @y\\ @b####@y##@b##@r####@w##@r########",
" @y/.@G\\____/@y// @b####@y##@b########",
" @y/@G_@r/@G__@r/@y..// @y##############",
" @y/@G/ \\@y.// @b####@y##@b########",
" @y/.@G\\____/@y// @r####@w|@b#@w|@r#@b####@y##@b########",
" @y/@G_@r/@G__@r/@y..// @r####@w|@b#@w|@r#@b####@y##@b########",
" @y/@G/ \\@y.// @r####@w|@b#@w|@r#######",
" @y\\@G\\____/@y// @b##############",
" @r/ /@y__/ @r####@w|@b#@w|@r#######",
" @r/ / @w####@b##@w##@r####@w|@b#@w|@r#######",
" @r/ / @w####@b##@w##@r####@w|@b#@w|@r#######",
" @r(__/ @w####@b##@w########",
" @b##############",
" @w####@b##@w########",
" @w####@b##@w########",
" @w####@b##@w########",
"",
NULL
};
void print_image(void)
{
int i, j;
for (i = 0; image[i]; i++) {
for (j = 0; j < strlen(image[i]); j++) {
if (image[i][j] == '@') {
j++;
switch(image[i][j]) {
case 'r': /* red */
printf("\033[0;31m");
break;
case 'g': /* gray */
printf("\033[0;37m");
break;
case 'G': /* green */
printf("\033[0;32m");
break;
case 'w': /* white */
printf("\033[1;37m");
break;
case 'y': /* yellow */
printf("\033[0;33m");
break;
case 'b': /* blue */
printf("\033[0;34m");
break;
}
} else
printf("%c", image[i][j]);
}
printf("\n");
}
printf("\033[0;39m");
}

3
src/nmt/image.h Normal file
View File

@ -0,0 +1,3 @@
void print_image(void);

291
src/nmt/main.c Normal file
View File

@ -0,0 +1,291 @@
/* NMT main
*
* (C) 2016 by Andreas Eversberg <jolly@eversberg.eu>
* All Rights Reserved
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdint.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sched.h>
#include "../common/main.h"
#include "../common/debug.h"
#include "../common/timer.h"
#include "../common/call.h"
#include "../common/mncc_sock.h"
#include "nmt.h"
#include "frame.h"
#include "dsp.h"
#include "image.h"
#include "tones.h"
#include "announcement.h"
/* settings */
enum nmt_chan_type chan_type = CHAN_TYPE_CC_TC;
int ms_power = 1; /* 1..3 */
char traffic_area[3] = "";
char area_no = 0;
int compander = 1;
int supervisory = 0;
void print_help(const char *arg0)
{
print_help_common(arg0, "-y <traffic area> | list ");
/* - - */
printf(" -t --channel-type <channel type> | list\n");
printf(" Give channel type, use 'list' to get a list. (default = '%s')\n", chan_type_short_name(chan_type));
printf(" -P --ms-power <power level>\n");
printf(" Give power level of the mobile station 1..3. (default = '%d')\n", ms_power);
printf(" 3 = 15 W / 7 W (handheld), 2 = 1.5 W, 1 = 150 mW\n");
printf(" -y --traffic-area <traffic area> | list\n");
printf(" NOTE: MUST MATCH WITH YOUR ROAMING SETTINGS IN THE PHONE!\n");
printf(" Your phone will not connect, if country code is different!\n");
printf(" Give two digits of traffic area, the first digit defines the country\n");
printf(" code, the second defines the cell area. (Example: 61 = Sweden, cell 1)\n");
printf(" Alternatively you can give the short code for country and the cell\n");
printf(" area seperated by comma. (Example: SE,1 = Sweden, cell 1)\n");
printf(" Use 'list' to get a list of available short country code names\n");
printf(" -a --area-number <area no> | 0\n");
printf(" Give area number 1..4 or 0 for no area number. (default = '%d')\n", area_no);
printf(" -C --compander 1 | 0\n");
printf(" Make use of the compander to reduce noise during call. (default = '%d')\n", compander);
printf(" -0 --supervisory 1..4 | 0\n");
printf(" Use supervisory signal 1..4 to detect loss of signal from mobile\n");
printf(" station, use 0 to disable. (default = '%d')\n", supervisory);
printf("\nstation-id: Give 7 digits of station-id, you don't need to enter it\n");
printf(" for every start of this program.\n");
}
static int handle_options(int argc, char **argv)
{
char country[32], *p;
int skip_args = 0;
static struct option long_options_special[] = {
{"channel-type", 1, 0, 't'},
{"ms-power", 1, 0, 'P'},
{"area-number", 1, 0, 'a'},
{"traffic-area", 1, 0, 'y'},
{"compander", 1, 0, 'C'},
{"supervisory", 1, 0, '0'},
{0, 0, 0, 0}
};
set_options_common("t:P:a:y:C:0:", long_options_special);
while (1) {
int option_index = 0, c, rc;
c = getopt_long(argc, argv, optstring, long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 't':
if (!strcmp(optarg, "list")) {
nmt_channel_list();
exit(0);
}
rc = nmt_channel_by_short_name(optarg);
if (rc < 0) {
fprintf(stderr, "Error, channel type '%s' unknown. Please use '-t list' to get a list. I suggest to use the default.\n", optarg);
exit(0);
}
chan_type = rc;
skip_args += 2;
break;
case 'P':
ms_power = atoi(optarg);
if (ms_power > 3)
ms_power = 3;
if (ms_power < 1)
ms_power = 1;
skip_args += 2;
break;
case 'a':
area_no = optarg[0] - '0';
if (area_no > 4) {
fprintf(stderr, "Area number '%s' out of range, please use 1..4 or 0 for no area\n", optarg);
exit(0);
}
skip_args += 2;
break;
case 'y':
if (!strcmp(optarg, "list")) {
nmt_country_list();
exit(0);
}
/* digits */
if (optarg[0] >= '0' && optarg[0] <= '9') {
traffic_area[0] = optarg[0];
if (optarg[1] < '0' || optarg[1] > '9') {
error_ta:
fprintf(stderr, "Illegal traffic area '%s', see '-h' for help\n", optarg);
exit(0);
}
traffic_area[1] = optarg[1];
if (optarg[2] != '\0')
goto error_ta;
traffic_area[2] = '\0';
} else {
strncpy(country, optarg, sizeof(country) - 1);
country[sizeof(country) - 1] = '\0';
p = strchr(country, ',');
if (!p)
goto error_ta;
*p++ = '\0';
rc = nmt_country_by_short_name(country);
if (!rc)
goto error_ta;
if (*p < '0' || *p > '9')
goto error_ta;
traffic_area[0] = rc + '0';
traffic_area[1] = *p;
traffic_area[2] = '\0';
}
skip_args += 2;
break;
case 'C':
compander = atoi(optarg);
skip_args += 2;
break;
case '0':
supervisory = atoi(optarg);
if (supervisory < 0 || supervisory > 4) {
fprintf(stderr, "Given supervisory signal is wrong, use '-h' for help!\n");
exit(0);
}
skip_args += 2;
break;
default:
opt_switch_common(c, argv[0], &skip_args);
}
}
free(long_options);
return skip_args;
}
int main(int argc, char *argv[])
{
int rc;
int skip_args;
const char *station_id = "";
/* init common tones */
init_nmt_tones();
init_announcement();
skip_args = handle_options(argc, argv);
argc -= skip_args;
argv += skip_args;
if (argc > 1)
station_id = argv[1];
if (!kanal) {
printf("No channel (\"Kanal\") is specified, I suggest channel 1.\n\n");
print_help(argv[0]);
return 0;
}
if (!traffic_area[0]) {
printf("No traffic area is specified, I suggest to use 'SE' for Sweden and set the phone's roaming to 'SE' also.\n\n");
print_help(argv[0]);
return 0;
}
if (!loopback)
print_image();
/* init functions */
if (use_mncc_sock) {
rc = mncc_init("/tmp/bsc_mncc");
if (rc < 0) {
fprintf(stderr, "Failed to setup MNCC socket. Quitting!\n");
return -1;
}
}
init_frame();
dsp_init();
rc = call_init(station_id, call_sounddev, samplerate, latency, 7, loopback);
if (rc < 0) {
fprintf(stderr, "Failed to create call control instance. Quitting!\n");
goto fail;
}
/* create transceiver instance */
rc = nmt_create(sounddev, samplerate, kanal, (loopback) ? CHAN_TYPE_TEST : chan_type, ms_power, nmt_digits2value(traffic_area, 2), area_no, compander, supervisory, loopback);
if (rc < 0) {
fprintf(stderr, "Failed to create transceiver instance. Quitting!\n");
goto fail;
}
if (kanal > 200) {
printf("Base station ready, please tune transmitter to %.4f MHz and receiver "
"to %.4f MHz.\n", nmt_channel2freq(kanal, 0),
nmt_channel2freq(kanal, 1));
} else {
printf("Base station ready, please tune transmitter to %.3f MHz and receiver "
"to %.3f MHz.\n", nmt_channel2freq(kanal, 0),
nmt_channel2freq(kanal, 1));
}
signal(SIGINT,sighandler);
signal(SIGHUP,sighandler);
signal(SIGTERM,sighandler);
signal(SIGPIPE,sighandler);
if (rt_prio > 0) {
struct sched_param schedp;
int rc;
memset(&schedp, 0, sizeof(schedp));
schedp.sched_priority = rt_prio;
rc = sched_setscheduler(0, SCHED_RR, &schedp);
if (rc)
fprintf(stderr, "Error setting SCHED_RR with prio %d\n", rt_prio);
}
main_loop(&quit, latency);
if (rt_prio > 0) {
struct sched_param schedp;
memset(&schedp, 0, sizeof(schedp));
schedp.sched_priority = 0;
sched_setscheduler(0, SCHED_OTHER, &schedp);
}
fail:
/* cleanup functions */
call_cleanup();
if (use_mncc_sock)
mncc_exit();
/* destroy transceiver instance */
while (sender_head)
nmt_destroy(sender_head);
return 0;
}

1460
src/nmt/nmt.c Normal file

File diff suppressed because it is too large Load Diff

142
src/nmt/nmt.h Normal file
View File

@ -0,0 +1,142 @@
#include "../common/sender.h"
#include "../common/compander.h"
#include "../common/dtmf.h"
enum dsp_mode {
DSP_MODE_DIALTONE, /* stream dial tone to mobile phone */
DSP_MODE_AUDIO, /* stream audio */
DSP_MODE_SILENCE, /* stream nothing */
DSP_MODE_FRAME, /* send frames */
DSP_MODE_DTMF, /* send DTMF tones */
};
enum nmt_chan_type {
CHAN_TYPE_CC, /* calling channel */
CHAN_TYPE_TC, /* traffic channel */
CHAN_TYPE_CC_TC, /* combined CC + TC */
CHAN_TYPE_TEST, /* test channel */
};
enum nmt_state {
STATE_NULL, /* power off state */
STATE_IDLE, /* channel is not in use */
STATE_ROAMING_IDENT, /* seizure received, waiting for identity */
STATE_ROAMING_CONFIRM, /* identity received, sending confirm */
STATE_MO_IDENT, /* seizure of mobile originated call, waiting for identity */
STATE_MO_CONFIRM, /* identity received, sending confirm */
STATE_MO_DIALING, /* receiving digits from phone */
STATE_MO_COMPLETE, /* all digits received, completing call */
STATE_MT_PAGING, /* paging mobile phone */
STATE_MT_CHANNEL, /* assigning traffic channel */
STATE_MT_IDENT, /* waiting for identity */
STATE_MT_RINGING, /* mobile phone is ringing, waiting for answer */
STATE_MT_COMPLETE, /* mobile phone has answered, completing call */
STATE_ACTIVE, /* during active call */
STATE_MO_RELEASE, /* acknowlegde release from mobile phone */
STATE_MT_RELEASE, /* sending release toward mobile phone */
};
enum nmt_active_state {
ACTIVE_STATE_VOICE, /* normal conversation */
ACTIVE_STATE_MFT_IN, /* ack MFT converter in */
ACTIVE_STATE_MFT, /* receive digits in MFT mode */
ACTIVE_STATE_MFT_OUT, /* ack MFT converter out */
};
enum nmt_direction {
MTX_TO_MS,
MTX_TO_BS,
MTX_TO_XX,
BS_TO_MTX,
MS_TO_MTX,
XX_TO_MTX,
};
typedef struct nmt_sysinfo {
enum nmt_chan_type chan_type; /* channel type */
int ms_power; /* ms power level 3 = full */
uint8_t traffic_area; /* two digits traffic area, encoded as YY */
uint8_t area_no; /* Area no. 1..4, 0 = no Area no. */
} nmt_sysinfo_t;
typedef struct nmt_subscriber {
/* NOTE: country must be followed by number, so both represent a string */
char country; /* country digit */
char number[7]; /* phone suffix */
char password[4]; /* phone's password + '\0' */
int coinbox; /* phone is a coinbox and accept tariff information */
} nmt_subscriber_t;
const char *nmt_dir_name(enum nmt_direction dir);
typedef struct nmt {
sender_t sender;
nmt_sysinfo_t sysinfo;
compander_t cstate;
dtmf_t dtmf;
/* sender's states */
enum nmt_state state;
enum nmt_active_state active_state;
nmt_subscriber_t subscriber; /* current subscriber */
struct timer timer;
int rx_frame_count; /* receive frame counter */
int tx_frame_count; /* transmit frame counter */
char dialing[33]; /* dialed digits */
int page_try; /* number of paging try */
/* features */
int compander; /* if compander shall be used */
int supervisory; /* if set, use supervisory signal 1..4 */
/* dsp states */
enum dsp_mode dsp_mode; /* current mode: audio, durable tone 0 or 1, paging */
int samples_per_bit; /* number of samples for one bit (1200 Baud) */
int super_samples; /* number of samples in buffer for supervisory detection */
int fsk_coeff[2]; /* coefficient k = 2*cos(2*PI*f/samplerate), k << 15 */
int super_coeff[5]; /* coefficient for supervisory signal */
int16_t *fsk_sine[2][2]; /* 4 pointers to 4 precalc. sine curves */
int fsk_polarity; /* current polarity state of bit */
int samples_per_chunk; /* how many samples lasts one chunk */
int16_t *fsk_filter_spl; /* array with samples_per_chunk */
int fsk_filter_pos; /* current sample position in filter_spl */
int fsk_filter_step; /* number of samples for each analyzation */
int fsk_filter_bit; /* last bit, so we detect a bit change */
int fsk_filter_sample; /* count until it is time to sample bit */
uint16_t fsk_filter_sync; /* shift register to detect sync */
int fsk_filter_in_sync; /* if we are in sync and receive bits */
int fsk_filter_mute; /* mute count down after sync */
char fsk_filter_frame[141]; /* receive frame (one extra byte to terminate string) */
int fsk_filter_count; /* next bit to receive */
double fsk_filter_levelsum; /* sum of 140 level infos */
double fsk_filter_qualitysum; /* sum of 140 quality infos */
int16_t *super_filter_spl; /* array with sample buffer for supervisory detection */
int super_filter_pos; /* current sample position in filter_spl */
double super_phaseshift256[4]; /* how much the phase of sine wave changes per sample */
double super_phase256; /* current phase */
double dial_phaseshift256; /* how much the phase of sine wave changes per sample */
double dial_phase256; /* current phase */
int frame; /* set, if there is a valid frame */
int16_t *frame_spl; /* 166 * fsk_bit_length */
int frame_pos; /* current sample position in frame_spl */
uint64_t rx_sample_count; /* sample counter */
uint64_t rx_sample_count_current;/* sample counter of current frame */
uint64_t rx_sample_count_last; /* sample counter of last frame */
int super_detected; /* current detection state flag */
int super_detect_count; /* current number of consecutive detections/losses */
int mft_num; /* counter for digit */
} nmt_t;
void nmt_channel_list(void);
int nmt_channel_by_short_name(const char *short_name);
const char *chan_type_short_name(enum nmt_chan_type chan_type);
const char *chan_type_long_name(enum nmt_chan_type chan_type);
double nmt_channel2freq(int channel, int uplink);
void nmt_country_list(void);
uint8_t nmt_country_by_short_name(const char *short_name);
int nmt_create(const char *sounddev, int samplerate, int channel, enum nmt_chan_type chan_type, uint8_t ms_power, uint8_t traffic_area, uint8_t area_no, int compander, int supervisory, int loopback);
void nmt_destroy(sender_t *sender);
void nmt_receive_frame(nmt_t *nmt, const char *bits, double quality, double level, double frames_elapsed);
const char *nmt_get_frame(nmt_t *nmt);
void nmt_rx_super(nmt_t *nmt, int tone, double quality);

43
src/nmt/tones.c Normal file
View File

@ -0,0 +1,43 @@
#include <stdint.h>
static int16_t pattern[] = {
0, 5320, 10063, 13716, 15883, 16328, 15004, 12054, 7798, 2697, -2697, -7798, -12054, -15004, -16328, -15883, -13716, -10063, -5320,
//0, 2660, 5032, 6858, 7941, 8164, 7502, 6027, 3899, 1348, -1348, -3899, -6027, -7502, -8164, -7941, -6858, -5032, -2660,
};
static int16_t tone[7999];
extern int16_t *ringback_spl;
extern int ringback_size;
extern int ringback_max;
extern int16_t *busy_spl;
extern int busy_size;
extern int busy_max;
extern int16_t *congestion_spl;
extern int congestion_size;
extern int congestion_max;
void init_nmt_tones(void)
{
int i, j;
for (i = 0, j = 0; i < 7999; i++) {
tone[i] = pattern[j++];
if (j == 19)
j = 0;
}
ringback_spl = tone;
ringback_size = 7999;
ringback_max = 8 * 5000; /* 1000 / 4000 */
busy_spl = tone;
busy_size = 1995;
busy_max = 8 * 500; /* 250 / 250 */
congestion_spl = tone;
congestion_size = 1995;
congestion_max = 8 * 500; /* 250 / 250 */
}

3
src/nmt/tones.h Normal file
View File

@ -0,0 +1,3 @@
void init_nmt_tones(void);