lists.osmocom.org
Sign In Sign Up
Manage this list Sign In Sign Up

Keyboard Shortcuts

Thread View

  • j: Next unread message
  • k: Previous unread message
  • j a: Jump to all threads
  • j l: Jump to MailingList overview

gerrit-log

Thread Start a new thread
Download
Threads by month
  • ----- 2026 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2025 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2024 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2023 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2022 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
gerrit-log@lists.osmocom.org

  • 1 participants
  • 97203 discussions
[M] Change in osmo-msc[master]: vlr: fail TMSI allocation if no NRI range fits the NRI bitlen
by bucketking657 02 Dec '26

02 Dec '26
Attention is currently required from: neels, pespin. bucketking657 has posted comments on this change by bucketking657. ( https://gerrit.osmocom.org/c/osmo-msc/+/44220?usp=email ) Change subject: vlr: fail TMSI allocation if no NRI range fits the NRI bitlen ...................................................................... Patch Set 2: (1 comment) Commit Message: https://gerrit.osmocom.org/c/osmo-msc/+/44220/comment/eb9ab1d7_48553faa?usp… : PS1, Line 15: osmo-sgsn's copy of libvlr has the same unchecked call, but osmo-sgsn > Done and ported in https://gerrit.osmocom. […] Done -- To view, visit https://gerrit.osmocom.org/c/osmo-msc/+/44220?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: osmo-msc Gerrit-Branch: master Gerrit-Change-Id: I24b71c8d568477680f735dc4044ec267385156ab Gerrit-Change-Number: 44220 Gerrit-PatchSet: 2 Gerrit-Owner: bucketking657 <joshuashilts(a)gmail.com> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: neels <nhofmeyr(a)sysmocom.de> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de> Gerrit-Attention: pespin <pespin(a)sysmocom.de> Gerrit-Attention: neels <nhofmeyr(a)sysmocom.de> Gerrit-Comment-Date: Wed, 02 Dec 2026 23:51:03 +0000 Gerrit-HasComments: Yes Gerrit-Has-Labels: No Comment-In-Reply-To: pespin <pespin(a)sysmocom.de> Comment-In-Reply-To: bucketking657 <joshuashilts(a)gmail.com>
1 0
0 0
[XL] Change in osmocom-bb[master]: trx_toolkit: move to separate repository
by fixeria 02 Dec '26

02 Dec '26
Attention is currently required from: osmith, pespin. fixeria has posted comments on this change by osmith. ( https://gerrit.osmocom.org/c/osmocom-bb/+/44224?usp=email ) Change subject: trx_toolkit: move to separate repository ...................................................................... Patch Set 1: Code-Review+1 (1 comment) Patchset: PS1: Thank you for working on that! -- To view, visit https://gerrit.osmocom.org/c/osmocom-bb/+/44224?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: osmocom-bb Gerrit-Branch: master Gerrit-Change-Id: Iba2a9242af052b2283b8a09fe98a2529b1955ab4 Gerrit-Change-Number: 44224 Gerrit-PatchSet: 1 Gerrit-Owner: osmith <osmith(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de> Gerrit-Attention: pespin <pespin(a)sysmocom.de> Gerrit-Attention: osmith <osmith(a)sysmocom.de> Gerrit-Comment-Date: Wed, 02 Dec 2026 20:16:40 +0000 Gerrit-HasComments: Yes Gerrit-Has-Labels: Yes
1 0
0 0
[L] Change in libosmocore[master]: gsm: new struct and en/decoding functions for BC-IE
by falconia 02 Dec '26

02 Dec '26
Attention is currently required from: fixeria, laforge, pespin. falconia has posted comments on this change by falconia. ( https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email ) Change subject: gsm: new struct and en/decoding functions for BC-IE ...................................................................... Patch Set 6: (1 comment) File include/osmocom/gsm/gsm48_ie.h: https://gerrit.osmocom.org/c/libosmocore/+/44192/comment/54243946_ed302c73?… : PS5, Line 110: int gsm48_encode_bearer_cap(struct msgb *msg, int lv_only, > I added a shorter version, without reference to `osmo_gsm48_bcap_apply_ms_rules()`. […] In terms of OsmocomBB potentially using the new API, I just created this feature ticket: https://osmocom.org/issues/7153 Can this comment thread be marked as resolved now? -- To view, visit https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: libosmocore Gerrit-Branch: master Gerrit-Change-Id: Ie864734fe1dfd1587bafddd4248ce69a7e066525 Gerrit-Change-Number: 44192 Gerrit-PatchSet: 6 Gerrit-Owner: falconia <falcon(a)freecalypso.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de> Gerrit-CC: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: pespin <pespin(a)sysmocom.de> Gerrit-Attention: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: laforge <laforge(a)osmocom.org> Gerrit-Comment-Date: Wed, 02 Dec 2026 19:34:01 +0000 Gerrit-HasComments: Yes Gerrit-Has-Labels: No Comment-In-Reply-To: pespin <pespin(a)sysmocom.de> Comment-In-Reply-To: falconia <falcon(a)freecalypso.org>
1 0
0 0
[L] Change in libosmocore[master]: gsm: new struct and en/decoding functions for BC-IE
by pespin 02 Dec '26

02 Dec '26
Attention is currently required from: falconia, fixeria, laforge. pespin has posted comments on this change by falconia. ( https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email ) Change subject: gsm: new struct and en/decoding functions for BC-IE ...................................................................... Patch Set 6: Code-Review+1 -- To view, visit https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: libosmocore Gerrit-Branch: master Gerrit-Change-Id: Ie864734fe1dfd1587bafddd4248ce69a7e066525 Gerrit-Change-Number: 44192 Gerrit-PatchSet: 6 Gerrit-Owner: falconia <falcon(a)freecalypso.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de> Gerrit-CC: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: falconia <falcon(a)freecalypso.org> Gerrit-Attention: laforge <laforge(a)osmocom.org> Gerrit-Comment-Date: Wed, 02 Dec 2026 19:06:33 +0000 Gerrit-HasComments: No Gerrit-Has-Labels: Yes
1 0
0 0
[L] Change in libosmocore[master]: gsm: new struct and en/decoding functions for BC-IE
by falconia 02 Dec '26

02 Dec '26
Attention is currently required from: fixeria, laforge, pespin. falconia has posted comments on this change by falconia. ( https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email ) Change subject: gsm: new struct and en/decoding functions for BC-IE ...................................................................... Patch Set 5: (1 comment) File include/osmocom/gsm/gsm48_ie.h: https://gerrit.osmocom.org/c/libosmocore/+/44192/comment/22f97d1c_7ba22fe7?… : PS5, Line 110: int gsm48_encode_bearer_cap(struct msgb *msg, int lv_only, > IIUC this and the one in L105 are now deprecatd in favour of the new ones right? […] I added a shorter version, without reference to `osmo_gsm48_bcap_apply_ms_rules()`. The only party in Osmocom universe who may wish to apply those MS rules - or choose not to - is OsmocomBB, and it is not my place to tell that entity what they should and should not do in this regard. The old BC encoding API does not apply those rules, nor does the current OsmocomBB mobile app. -- To view, visit https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: libosmocore Gerrit-Branch: master Gerrit-Change-Id: Ie864734fe1dfd1587bafddd4248ce69a7e066525 Gerrit-Change-Number: 44192 Gerrit-PatchSet: 5 Gerrit-Owner: falconia <falcon(a)freecalypso.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de> Gerrit-CC: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: pespin <pespin(a)sysmocom.de> Gerrit-Attention: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: laforge <laforge(a)osmocom.org> Gerrit-Comment-Date: Wed, 02 Dec 2026 16:56:39 +0000 Gerrit-HasComments: Yes Gerrit-Has-Labels: No Comment-In-Reply-To: pespin <pespin(a)sysmocom.de>
1 0
0 0
[L] Change in libosmocore[master]: gsm: new struct and en/decoding functions for BC-IE
by falconia 02 Dec '26

02 Dec '26
Attention is currently required from: falconia, fixeria, laforge, pespin. Hello Jenkins Builder, laforge, pespin, I'd like you to reexamine a change. Please visit https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email to look at the new patch set (#6). The following approvals got outdated and were removed: Code-Review+1 by laforge, Code-Review+1 by pespin, Verified+1 by Jenkins Builder Change subject: gsm: new struct and en/decoding functions for BC-IE ...................................................................... gsm: new struct and en/decoding functions for BC-IE Legacy struct gsm_mncc_bearer_cap is unable to represent 14.4 kbit/s mode of CSD, which is now supported by Osmocom BSS, and even for the mandatory set of BC-IE octets for all data modes, it lacks some of the bits. Introduce a new set of structures to serve as a replacement, as well as new encoding and decoding functions using the new structs. These new structures and functions were originally developed by American 2G Cooperative as part of Hera MSC back end, interfacing to OsmoMSC via the proposed MNCC raw mode and doing our own encoding and decoding of GSM 04.08 CC messages. The present patch is a small step toward making these ThemWi functional improvements available in pure Osmocom, in addition to Osmocom+ThemWi hybrid. The structures and functions have also been extended to be usable on the mobile side of GSM, in addition to the network side. Change-Id: Ie864734fe1dfd1587bafddd4248ce69a7e066525 --- M TODO-RELEASE M include/osmocom/gsm/gsm48_ie.h M src/gsm/gsm48_ie.c M src/gsm/libosmogsm.map 4 files changed, 666 insertions(+), 4 deletions(-) git pull ssh://gerrit.osmocom.org:29418/libosmocore refs/changes/92/44192/6 -- To view, visit https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newpatchset Gerrit-Project: libosmocore Gerrit-Branch: master Gerrit-Change-Id: Ie864734fe1dfd1587bafddd4248ce69a7e066525 Gerrit-Change-Number: 44192 Gerrit-PatchSet: 6 Gerrit-Owner: falconia <falcon(a)freecalypso.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de> Gerrit-CC: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: pespin <pespin(a)sysmocom.de> Gerrit-Attention: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: falconia <falcon(a)freecalypso.org> Gerrit-Attention: laforge <laforge(a)osmocom.org>
1 0
0 0
[L] Change in libosmocore[master]: gsm: new struct and en/decoding functions for BC-IE
by pespin 02 Dec '26

02 Dec '26
Attention is currently required from: falconia, fixeria. pespin has posted comments on this change by falconia. ( https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email ) Change subject: gsm: new struct and en/decoding functions for BC-IE ...................................................................... Patch Set 5: Code-Review+1 (1 comment) File include/osmocom/gsm/gsm48_ie.h: https://gerrit.osmocom.org/c/libosmocore/+/44192/comment/9cd24277_f1276020?… : PS5, Line 110: int gsm48_encode_bearer_cap(struct msgb *msg, int lv_only, IIUC this and the one in L105 are now deprecatd in favour of the new ones right? Can you please add here: OSMO_DEPRECATED("Use osmo_gsm48_encode_bcap() (and osmo_gsm48_bcap_apply_ms_rules()) instead") -- To view, visit https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: libosmocore Gerrit-Branch: master Gerrit-Change-Id: Ie864734fe1dfd1587bafddd4248ce69a7e066525 Gerrit-Change-Number: 44192 Gerrit-PatchSet: 5 Gerrit-Owner: falconia <falcon(a)freecalypso.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de> Gerrit-CC: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: falconia <falcon(a)freecalypso.org> Gerrit-Comment-Date: Wed, 02 Dec 2026 16:26:47 +0000 Gerrit-HasComments: Yes Gerrit-Has-Labels: Yes
1 0
0 0
[XL] Change in osmocom-bb[master]: trx_toolkit: move to separate repository
by osmith 02 Dec '26

02 Dec '26
osmith has uploaded this change for review. ( https://gerrit.osmocom.org/c/osmocom-bb/+/44224?usp=email ) Change subject: trx_toolkit: move to separate repository ...................................................................... trx_toolkit: move to separate repository osmo-trx-proxy is the replacement for fake_trx / trx_toolkit. Remove it from this repository and stop running tests in contrib/jenkins.sh (which are sometimes failing). New location: https://gitea.osmocom.org/phone-side/trx_toolkit Related: OS#7152 Change-Id: Iba2a9242af052b2283b8a09fe98a2529b1955ab4 --- M contrib/jenkins.sh M debian/control D debian/osmocom-bb-trx-toolkit.install M src/README.development D src/target/trx_toolkit/.gitignore D src/target/trx_toolkit/README D src/target/trx_toolkit/app_common.py D src/target/trx_toolkit/burst_fwd.py D src/target/trx_toolkit/burst_gen.py D src/target/trx_toolkit/burst_send.py D src/target/trx_toolkit/clck_gen.py D src/target/trx_toolkit/codec.py D src/target/trx_toolkit/ctrl_cmd.py D src/target/trx_toolkit/ctrl_if.py D src/target/trx_toolkit/ctrl_if_trx.py D src/target/trx_toolkit/data_dump.py D src/target/trx_toolkit/data_if.py D src/target/trx_toolkit/data_msg.py D src/target/trx_toolkit/fake_pm.py D src/target/trx_toolkit/fake_trx.py D src/target/trx_toolkit/gsm_shared.py D src/target/trx_toolkit/rand_burst_gen.py D src/target/trx_toolkit/test_clck_gen.py D src/target/trx_toolkit/test_codec.py D src/target/trx_toolkit/test_data_dump.py D src/target/trx_toolkit/test_data_msg.py D src/target/trx_toolkit/transceiver.py D src/target/trx_toolkit/trx_list.py D src/target/trx_toolkit/trx_sniff.py D src/target/trx_toolkit/trxd_proto.py D src/target/trx_toolkit/udp_link.py 31 files changed, 2 insertions(+), 5,506 deletions(-) git pull ssh://gerrit.osmocom.org:29418/osmocom-bb refs/changes/24/44224/1 diff --git a/contrib/jenkins.sh b/contrib/jenkins.sh index 2846a46..6c32d6a 100755 --- a/contrib/jenkins.sh +++ b/contrib/jenkins.sh @@ -66,10 +66,6 @@ cd "$base/src" make firmware -# TRX Toolkit unit tests -cd "$base/src/target/trx_toolkit" -python3 -m unittest discover -v - # Upload firmware to downloads.osmocom.org if [ "$PUBLISH" = "1" ]; then "$base"/contrib/upload_firmware.sh diff --git a/debian/control b/debian/control index aabe874..ba28dc2 100644 --- a/debian/control +++ b/debian/control @@ -49,12 +49,6 @@ Depends: ${misc:Depends}, ${shlibs:Depends} Description: Firmware loading and communication utility -Package: osmocom-bb-trx-toolkit -Architecture: any -Multi-Arch: foreign -Depends: python3 -Description: Tools for the TRX interface and emulating a virtual Um-interface - Package: osmocom-bb-trxcon Architecture: any Multi-Arch: foreign diff --git a/debian/osmocom-bb-trx-toolkit.install b/debian/osmocom-bb-trx-toolkit.install deleted file mode 100644 index f323b17..0000000 --- a/debian/osmocom-bb-trx-toolkit.install +++ /dev/null @@ -1 +0,0 @@ -src/target/trx_toolkit/* /usr/share/osmocom-bb/trx_toolkit diff --git a/src/README.development b/src/README.development index e09793b..8ddc529 100644 --- a/src/README.development +++ b/src/README.development @@ -67,13 +67,8 @@ === src/target/trx_toolkit === -A set of tools in Python for debugging TRX interface and creating -a virtual Um-interface between OsmocomBB and OsmoBTS. For details, -please refer: - -https://osmocom.org/projects/baseband/wiki/TRX_Interface -https://osmocom.org/projects/baseband/wiki/FakeTRX -target/trx_toolkit/README +Deprecated in favor of osmo-trx-proxy. Find the old sources here: +https://gitea.osmocom.org/phone-side/trx_toolkit === src/target_dsp/calypso === diff --git a/src/target/trx_toolkit/.gitignore b/src/target/trx_toolkit/.gitignore deleted file mode 100644 index 749ccda..0000000 --- a/src/target/trx_toolkit/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class diff --git a/src/target/trx_toolkit/README b/src/target/trx_toolkit/README deleted file mode 100644 index 769c9c2..0000000 --- a/src/target/trx_toolkit/README +++ /dev/null @@ -1,40 +0,0 @@ -TRX toolkit is a set of tools intended for hacking and debugging -a TRX interface between both transceiver and L1 software, and -emulating a virtual Um-interface between OsmocomBB and OsmoBTS. - -Brief description of available applications: - - - fake_trx.py - main application, that allows to connect both - OsmocomBB and OsmoBTS without actual RF hardware. It's also - possible to emulate more than two transceivers, so multiple - MS and/or BTS instances can be connected. - - - clck_gen.py - a peripheral tool aimed to emulate TDMA frame - clock generator. Could be used for testing and clock - synchronization of multiple applications. It should be noted, - that one relays on generic system timer (via Python), so - a random clock jitter takes place. - - - ctrl_cmd.py - another peripheral tool, which could be used - for sending CTRL commands directly in manual mode, and also - for application fuzzing. - - - burst_gen.py - a tool for sending GSM bursts either to L1 - (OsmoBTS or OsmocomBB) or to TRX (OsmoTRX and GR-GSM TRX). - Currently it is only possible to generate random bursts of - different types: NB, FB, SB, AB. - - - burst_send.py - a tool for sending existing bursts from a - capture file either to L1 (OsmoBTS or OsmocomBB) or to - TRX (e.g. OsmoTRX or GR-GSM TRX). - - - trx_sniff.py - Scapy-based TRX protocol sniffer. Allows one - to observe a single connection between TRX and L1, and vice - versa. Also provides some capabilities for filtering bursts - by direction, frame and timeslot numbers, and for recording - captured messages to a binary file. - -Please note that TRX toolkit is not using libosmocore's CTRL -interface, so 'CTRL' in scope of this code base actually means -control interface of TRX or control protocol. In order to avoid -possible confusion, we use 'TRXC' and 'TRXD' in logging. diff --git a/src/target/trx_toolkit/app_common.py b/src/target/trx_toolkit/app_common.py deleted file mode 100644 index 75dd5a2..0000000 --- a/src/target/trx_toolkit/app_common.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Common helpers for applications -# -# (C) 2018-2020 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -import logging as log - -class ApplicationBase: - # Osmocom-style logging message format - # Example: [DEBUG] ctrl_if_bts.py:71 Recv POWEROFF cmd - LOG_FMT_DEFAULT = "[%(levelname)s] %(filename)s:%(lineno)d %(message)s" - - # Default time / date format (e.g. 2003-01-23 00:29:50) - LOG_TIME_FMT_DEFAULT = "%Y-%m-%d %H:%M:%S" - - def app_print_copyright(self, holders = []): - # Print copyright holders if any - for date, author in holders: - print("Copyright (C) %s by %s" % (date, author)) - - # Print the license header itself - print("License GPLv2+: GNU GPL version 2 or later " \ - "<http://gnu.org/licenses/gpl.html>\n" \ - "This is free software: you are free to change and redistribute it.\n" \ - "There is NO WARRANTY, to the extent permitted by law.\n") - - def add_log_handler(self, lh, log_level, log_fmt, time_fmt, log_time = False): - log_fmt = "%(asctime)s.%(msecs)03d " + log_fmt if log_time else log_fmt - lf = log.Formatter(log_fmt, time_fmt) - ll = log.getLevelName(log_level) - - log.root.addHandler(lh) - lh.setFormatter(lf) - lh.setLevel(ll) - - def app_init_logging(self, argv): - # Default logging handler (stderr) - lo = (argv.log_level, argv.log_fmt, argv.log_time_fmt, argv.log_time) - lh = log.StreamHandler() - self.add_log_handler(lh, *lo) - - # Optional file handler - if argv.log_file_name is not None: - lo = (argv.log_file_level, argv.log_file_fmt, - argv.log_file_time_fmt, argv.log_file_time) - lh = log.FileHandler(argv.log_file_name) - self.add_log_handler(lh, *lo) - - # Set DEBUG for the root logger - log.root.setLevel(log.DEBUG) - - def app_reg_logging_options(self, parser): - parser.add_argument("--log-level", metavar = "LVL", - dest = "log_level", type = str, default = "DEBUG", - choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], - help = "Set logging level (default %(default)s)") - parser.add_argument("--log-time", - dest = "log_time", action = "store_true", - help = "Prefix each log message with the current time") - parser.add_argument("--log-time-format", metavar = "FMT", - dest = "log_time_fmt", type = str, - default = self.LOG_TIME_FMT_DEFAULT, - help = "Set time format (default %(default)s)") - parser.add_argument("--log-format", metavar = "FMT", - dest = "log_fmt", type = str, default = self.LOG_FMT_DEFAULT, - help = "Set logging message format") - - parser.add_argument("--log-file-name", metavar = "FILE", - dest = "log_file_name", type = str, - help = "Set logging file name") - parser.add_argument("--log-file-level", metavar = "LVL", - dest = "log_file_level", type = str, default = "DEBUG", - choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], - help = "Set logging level for file (default %(default)s)") - parser.add_argument("--log-file-time", - dest = "log_file_time", action = "store_true", - help = "Prefix each log message with the current time") - parser.add_argument("--log-file-time-format", metavar = "FMT", - dest = "log_file_time_fmt", type = str, - default = self.LOG_TIME_FMT_DEFAULT, - help = "Set time format for file (default %(default)s)") - parser.add_argument("--log-file-format", metavar = "FMT", - dest = "log_file_fmt", type = str, default = self.LOG_FMT_DEFAULT, - help = "Set logging message format for file") diff --git a/src/target/trx_toolkit/burst_fwd.py b/src/target/trx_toolkit/burst_fwd.py deleted file mode 100644 index 2824e0a..0000000 --- a/src/target/trx_toolkit/burst_fwd.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Burst forwarding between transceivers -# -# (C) 2017-2020 by Vadim Yanitskiy <axilirator(a)gmail.com> -# Contributions by sysmocom - s.f.m.c. GmbH -# -# 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 2 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. - -import logging as log - -from trx_list import TRXList - -class BurstForwarder(TRXList): - """ Performs burst forwarding between transceivers. - - BurstForwarder distributes bursts between the list of given - FakeTRX (Transceiver) instances depending on the following - parameters of each transceiver: - - - execution state (running or idle), - - actual RX / TX frequencies, - - list of active timeslots. - - Each to be distributed 'TxMsg' message is being transformed - into a 'RxMsg' message, and then forwarded to transceivers - with partially initialized header. All uninitialized header - fields (such as rssi and toa256) shall be set by each - transceiver individually before sending towards the L1. - - """ - - def forward_msg(self, src_trx, rx_msg): - # Originating Transceiver may use frequency hopping, - # so let's precalculate its Tx frequency in advance - tx_freq = src_trx.get_tx_freq(rx_msg.fn) - - if src_trx.rf_muted: - rx_msg.burst = None # burst bits are omited - - # Iterate over all known transceivers - for trx in self.trx_list: - if trx is src_trx: - continue - - # Check transceiver state - if not trx.running: - continue - - # Match Tx/Rx frequencies of the both transceivers - if trx.get_rx_freq(rx_msg.fn) != tx_freq: - continue - - # Transform from TxMsg to RxMsg and forward - tx_msg = rx_msg.trans(ver = trx.data_if._hdr_ver) - trx.handle_data_msg(src_trx, rx_msg, tx_msg) diff --git a/src/target/trx_toolkit/burst_gen.py b/src/target/trx_toolkit/burst_gen.py deleted file mode 100755 index 22f7205..0000000 --- a/src/target/trx_toolkit/burst_gen.py +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Auxiliary tool to generate and send random bursts via TRX DATA -# interface, which may be useful for fuzzing and testing -# -# (C) 2017-2019 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -APP_CR_HOLDERS = [("2017-2019", "Vadim Yanitskiy <axilirator(a)gmail.com>")] - -import logging as log -import signal -import argparse -import sys - -from app_common import ApplicationBase -from rand_burst_gen import RandBurstGen -from data_dump import DATADumpFile -from data_if import DATAInterface -from gsm_shared import * -from data_msg import * - -class Application(ApplicationBase): - def __init__(self): - self.app_print_copyright(APP_CR_HOLDERS) - self.argv = self.parse_argv() - - # Set up signal handlers - signal.signal(signal.SIGINT, self.sig_handler) - - # Configure logging - self.app_init_logging(self.argv) - - # Open requested capture file - if self.argv.output_file is not None: - self.ddf = DATADumpFile(self.argv.output_file) - - def run(self): - # Init DATA interface with TRX or L1 - if self.argv.conn_mode == "TRX": - self.data_if = DATAInterface( - self.argv.remote_addr, self.argv.base_port + 2, - self.argv.bind_addr, self.argv.base_port + 102) - elif self.argv.conn_mode == "L1": - self.data_if = DATAInterface( - self.argv.remote_addr, self.argv.base_port + 102, - self.argv.bind_addr, self.argv.base_port + 2) - - # Init random burst generator - burst_gen = RandBurstGen() - - # Init an empty DATA message - if self.argv.conn_mode == "TRX": - msg = TxMsg(ver = self.argv.hdr_ver) - elif self.argv.conn_mode == "L1": - msg = RxMsg(ver = self.argv.hdr_ver) - - # Generate a random frame number or use provided one - fn_init = msg.rand_fn() if self.argv.tdma_fn is None \ - else self.argv.tdma_fn - - # Send as much bursts as required - for i in range(self.argv.burst_count): - # Randomize the message header - msg.rand_hdr() - - # Increase and set frame number - msg.fn = (fn_init + i) % GSM_HYPERFRAME - - # Set timeslot number - if self.argv.tdma_tn is not None: - msg.tn = self.argv.tdma_tn - - # Set transmit power level - if self.argv.pwr is not None: - msg.pwr = self.argv.pwr - - # Set time of arrival - if self.argv.toa is not None: - msg.toa256 = int(float(self.argv.toa) * 256.0 + 0.5) - elif self.argv.toa256 is not None: - msg.toa256 = self.argv.toa256 - - # Set RSSI - if self.argv.rssi is not None: - msg.rssi = self.argv.rssi - - if msg.ver >= 0x01: - # TODO: Only GMSK and TSC set 0 for now - msg.mod_type = Modulation.ModGMSK - self.tsc_set = 0 - - if self.argv.tsc is not None: - msg.tsc = self.argv.tsc - - if self.argv.ci is not None: - msg.ci = self.argv.ci - - # Generate a random burst - if self.argv.burst_type == "NB": - burst = burst_gen.gen_nb() - elif self.argv.burst_type == "FB": - burst = burst_gen.gen_fb() - elif self.argv.burst_type == "SB": - burst = burst_gen.gen_sb() - elif self.argv.burst_type == "AB": - burst = burst_gen.gen_ab() - - # Convert to soft-bits in case of TRX -> L1 message - if self.argv.conn_mode == "L1": - burst = msg.ubit2sbit(burst) - - # Set burst - msg.burst = burst - - log.info("Sending %d/%d %s burst %s to %s..." - % (i + 1, self.argv.burst_count, self.argv.burst_type, - msg.desc_hdr(), self.argv.conn_mode)) - - # Send message - self.data_if.send_msg(msg) - - # Append a new message to the capture - if self.argv.output_file is not None: - self.ddf.append_msg(msg) - - def parse_argv(self): - parser = argparse.ArgumentParser(prog = "burst_gen", - description = "Auxiliary tool to generate and send random bursts") - - # Register common logging options - self.app_reg_logging_options(parser) - - trx_group = parser.add_argument_group("TRX interface") - trx_group.add_argument("-r", "--remote-addr", - dest = "remote_addr", type = str, default = "127.0.0.1", - help = "Set remote address (default %(default)s)") - trx_group.add_argument("-b", "--bind-addr", - dest = "bind_addr", type = str, default = "0.0.0.0", - help = "Set bind address (default %(default)s)") - trx_group.add_argument("-p", "--base-port", - dest = "base_port", type = int, default = 6700, - help = "Set base port number (default %(default)s)") - trx_group.add_argument("-m", "--conn-mode", - dest = "conn_mode", type = str, - choices = ["TRX", "L1"], default = "TRX", - help = "Where to send bursts (default %(default)s)") - trx_group.add_argument("-o", "--output-file", - dest = "output_file", type = str, - help = "Write bursts to a capture file") - - bg_group = parser.add_argument_group("Burst generation") - bg_group.add_argument("-B", "--burst-type", - dest = "burst_type", type = str, - choices = ["NB", "FB", "SB", "AB"], default = "NB", - help = "Random burst type (default %(default)s)") - bg_group.add_argument("-c", "--burst-count", metavar = "N", - dest = "burst_count", type = int, default = 1, - help = "How many bursts to send (default %(default)s)") - bg_group.add_argument("-v", "--hdr-version", metavar = "VER", - dest = "hdr_ver", type = int, - default = 0, choices = Msg.KNOWN_VERSIONS, - help = "TRXD header version (default %(default)s)") - bg_group.add_argument("-f", "--frame-number", metavar = "FN", - dest = "tdma_fn", type = int, - help = "Set TDMA frame number (default random)") - bg_group.add_argument("-t", "--timeslot", metavar = "TN", - dest = "tdma_tn", type = int, choices = range(0, 8), - help = "Set TDMA timeslot (default random)") - - bg_pwr_group = bg_group.add_mutually_exclusive_group() - bg_pwr_group.add_argument("--pwr", metavar = "dBm", - dest = "pwr", type = int, - help = "Set power level (default random)") - bg_pwr_group.add_argument("--rssi", metavar = "dBm", - dest = "rssi", type = int, - help = "Set RSSI (default random)") - - bg_toa_group = bg_group.add_mutually_exclusive_group() - bg_toa_group.add_argument("--toa", - dest = "toa", type = int, - help = "Set Timing of Arrival in symbols (default random)") - bg_toa_group.add_argument("--toa256", - dest = "toa256", type = int, - help = "Set Timing of Arrival in 1/256 symbol periods") - - bg_group.add_argument("--tsc", metavar = "TSC", - dest = "tsc", type = int, choices = range(0, 8), - help = "Set Training Sequence Code (default random)") - bg_group.add_argument("--ci", metavar = "CI", - dest = "ci", type = int, - help = "C/I: Carrier-to-Interference ratio " - "in centiBels (default random)") - - return parser.parse_args() - - def sig_handler(self, signum, frame): - log.info("Signal %d received" % signum) - if signum == signal.SIGINT: - sys.exit(0) - -if __name__ == '__main__': - app = Application() - app.run() diff --git a/src/target/trx_toolkit/burst_send.py b/src/target/trx_toolkit/burst_send.py deleted file mode 100755 index 27f585e..0000000 --- a/src/target/trx_toolkit/burst_send.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Auxiliary tool to send existing bursts via TRX DATA interface -# -# (C) 2017-2018 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -APP_CR_HOLDERS = [("2017-2018", "Vadim Yanitskiy <axilirator(a)gmail.com>")] - -import logging as log -import signal -import argparse -import sys - -from app_common import ApplicationBase -from data_dump import DATADumpFile -from data_if import DATAInterface -from data_msg import * - -class Application(ApplicationBase): - def __init__(self): - self.app_print_copyright(APP_CR_HOLDERS) - self.argv = self.parse_argv() - - # Set up signal handlers - signal.signal(signal.SIGINT, self.sig_handler) - - # Configure logging - self.app_init_logging(self.argv) - - # Open requested capture file - self.ddf = DATADumpFile(self.argv.capture_file) - - def run(self): - # Init DATA interface with TRX or L1 - if self.argv.conn_mode == "TRX": - self.data_if = DATAInterface( - self.argv.remote_addr, self.argv.base_port + 2, - self.argv.bind_addr, self.argv.base_port + 102) - elif self.argv.conn_mode == "L1": - self.data_if = DATAInterface( - self.argv.remote_addr, self.argv.base_port + 102, - self.argv.bind_addr, self.argv.base_port + 2) - - # Read messages from the capture - messages = self.ddf.parse_all( - skip = self.argv.cnt_skip, count = self.argv.cnt_count) - if messages is False: - log.error("Parsing failed, nothing to send") - sys.exit(1) - - for msg in messages: - # Pass filter - if not self.msg_pass_filter(msg): - continue - - log.info("Sending a burst %s to %s..." - % (msg.desc_hdr(), self.argv.conn_mode)) - - # Send message - self.data_if.send_msg(msg) - - def msg_pass_filter(self, msg): - # Direction filter - if isinstance(msg, RxMsg) and self.argv.conn_mode == "TRX": - return False # cannot send RxMsg to TRX - if isinstance(msg, TxMsg) and self.argv.conn_mode == "L1": - return False # cannot send TxMsg to L1 - - # Timeslot filter - if self.argv.pf_tn is not None: - if msg.tn != self.argv.pf_tn: - return False - - # Frame number filter - if self.argv.pf_fn_lt is not None: - if msg.fn > self.argv.pf_fn_lt: - return False - if self.argv.pf_fn_gt is not None: - if msg.fn < self.argv.pf_fn_gt: - return False - - # Burst passed ;) - return True - - def parse_argv(self): - parser = argparse.ArgumentParser(prog = "burst_send", - description = "Auxiliary tool to send (reply) captured bursts") - - # Register common logging options - self.app_reg_logging_options(parser) - - trx_group = parser.add_argument_group("TRX interface") - trx_group.add_argument("-r", "--remote-addr", - dest = "remote_addr", type = str, default = "127.0.0.1", - help = "Set remote address (default %(default)s)") - trx_group.add_argument("-b", "--bind-addr", - dest = "bind_addr", type = str, default = "0.0.0.0", - help = "Set bind address (default %(default)s)") - trx_group.add_argument("-p", "--base-port", - dest = "base_port", type = int, default = 6700, - help = "Set base port number (default %(default)s)") - trx_group.add_argument("-m", "--conn-mode", - dest = "conn_mode", type = str, - choices = ["TRX", "L1"], default = "TRX", - help = "Where to send bursts (default %(default)s)") - trx_group.add_argument("-i", "--capture-file", metavar = "FILE", - dest = "capture_file", type = str, required = True, - help = "Capture file to read bursts from") - - cnt_group = parser.add_argument_group("Count limitations (optional)") - cnt_group.add_argument("--skip", metavar = "N", - dest = "cnt_skip", type = int, - help = "Skip N messages before sending") - cnt_group.add_argument("--count", metavar = "N", - dest = "cnt_count", type = int, - help = "Stop after sending N messages") - - pf_group = parser.add_argument_group("Filtering (optional)") - pf_group.add_argument("--timeslot", metavar = "TN", - dest = "pf_tn", type = int, choices = range(0, 8), - help = "TDMA timeslot number (equal TN)") - pf_group.add_argument("--frame-num-lt", metavar = "FN", - dest = "pf_fn_lt", type = int, - help = "TDMA frame number (lower than FN)") - pf_group.add_argument("--frame-num-gt", metavar = "FN", - dest = "pf_fn_gt", type = int, - help = "TDMA frame number (greater than FN)") - - return parser.parse_args() - - def sig_handler(self, signum, frame): - log.info("Signal %d received" % signum) - if signum == signal.SIGINT: - sys.exit(0) - -if __name__ == '__main__': - app = Application() - app.run() diff --git a/src/target/trx_toolkit/clck_gen.py b/src/target/trx_toolkit/clck_gen.py deleted file mode 100755 index f769c3e..0000000 --- a/src/target/trx_toolkit/clck_gen.py +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Simple TDMA frame clock generator -# -# (C) 2017-2019 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -APP_CR_HOLDERS = [("2017-2019", "Vadim Yanitskiy <axilirator(a)gmail.com>")] - -import logging as log -import threading -import time -import signal -import os - -from app_common import ApplicationBase -from udp_link import UDPLink -from gsm_shared import * - -class CLCKGen: - # GSM TDMA definitions - SEC_DELAY_US = 1000 * 1000 - GSM_FRAME_US = 4615.0 - - def __init__(self, clck_links, clck_start = 0, ind_period = 102, sched_rr_prio = None): - # This event is needed to control the thread - self._breaker = threading.Event() - self._thread = None - - self.clck_links = clck_links - self.ind_period = ind_period - self.clck_start = clck_start - - # Calculate counter time - self.ctr_interval = self.GSM_FRAME_US - self.ctr_interval /= self.SEC_DELAY_US - - # (Optional) clock consumer - self.clck_handler = None - - # RR Scheduler priority of thread. None = don't set it. - self.sched_rr_prio = sched_rr_prio - - @property - def running(self): - if self._thread is None: - return False - return self._thread.is_alive() - - def start(self): - # Make sure we won't start two threads - assert(self._thread is None) - - # (Re)set the clock counter - self.clck_src = self.clck_start - - # Initialize and start a new thread - self._thread = threading.Thread(target = self._worker) - self._thread.daemon = True - self._thread.start() - - def stop(self): - # No thread, no problem ;) - if self._thread is None: - return - - # Stop the thread first - self._breaker.set() - self._thread.join() - - # Free memory, reset breaker - self._thread = None - self._breaker.clear() - - def _worker(self): - if self.sched_rr_prio is not None: - sched_param = os.sched_param(self.sched_rr_prio) - try: - log.info("CLCKGen: Setting real time process scheduler to SCHED_RR, priority %u" % (self.sched_rr_prio)) - os.sched_setscheduler(0, os.SCHED_RR, sched_param) - except OSError: - log.error("CLCKGen: Failed to set real time process scheduler to SCHED_RR, priority %u" % (self.sched_rr_prio)) - # run .send_clck_ind() every .ctr_interval - # be careful not to accumulate timing error when organizing the clock loop - ns = 1e-9 - us = 1e-6 - t_tick = int(self.ctr_interval // ns) - t_next = time.monotonic_ns() - while 1: - t_next += t_tick - t = time.monotonic_ns() - dt = (t_next - t) - if dt < 0: - log.warning("CLCKGen: time overrun by %dus; resetting the clock" % (dt * ns // us)) - t_next = time.monotonic_ns() - dt = 0 - - if self._breaker.wait(dt * ns): - break - - self.send_clck_ind() - - def send_clck_ind(self): - # We don't need to send so often - if self.clck_src % self.ind_period == 0: - # Create UDP payload - payload = "IND CLOCK %u\0" % self.clck_src - - # Send indication to all UDP links - for link in self.clck_links: - link.send(payload) - - # Debug print - log.debug(payload.rstrip("\0")) - - if self.clck_handler is not None: - self.clck_handler(self.clck_src) - - # Increase frame count (modular arithmetic) - self.clck_src = (self.clck_src + 1) % GSM_HYPERFRAME - -# Just a wrapper for independent usage -class Application(ApplicationBase): - def __init__(self): - # Print copyright - self.app_print_copyright(APP_CR_HOLDERS) - - # Set up signal handlers - signal.signal(signal.SIGINT, self.sig_handler) - - # Configure logging - log.basicConfig(level = log.DEBUG, - format = "[%(levelname)s] TID#%(thread)s %(filename)s:%(lineno)d %(message)s") - - def run(self): - self.link = UDPLink("127.0.0.1", 5800, "0.0.0.0", 5700) - self.clck = CLCKGen([self.link], ind_period = 51) - self.clck.start() - - # Block unless we receive a signal - self.clck._thread.join() - - def sig_handler(self, signum, frame): - log.info("Signal %d received" % signum) - if signum == signal.SIGINT: - self.clck.stop() - -if __name__ == '__main__': - app = Application() - app.run() diff --git a/src/target/trx_toolkit/codec.py b/src/target/trx_toolkit/codec.py deleted file mode 100644 index c570600..0000000 --- a/src/target/trx_toolkit/codec.py +++ /dev/null @@ -1,404 +0,0 @@ -# -*- coding: utf-8 -*- - -''' -Very simple (performance oriented) declarative message codec. -Inspired by Pycrate and Scapy. -''' - -# TRX Toolkit -# -# (C) 2021 by sysmocom - s.f.m.c. GmbH <info(a)sysmocom.de> -# Author: Vadim Yanitskiy <vyanitskiy(a)sysmocom.de> -# -# 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 2 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. - -from typing import Optional, Callable, Tuple, Any -import abc - -class ProtocolError(Exception): - ''' Error in a protocol definition. ''' - -class DecodeError(Exception): - ''' Error during decoding of a field/message. ''' - -class EncodeError(Exception): - ''' Error during encoding of a field/message. ''' - - -class Codec(abc.ABC): - ''' Base class providing encoding and decoding API. ''' - - @abc.abstractmethod - def from_bytes(self, vals: dict, data: bytes) -> int: - ''' Decode value(s) from the given buffer of bytes. ''' - - @abc.abstractmethod - def to_bytes(self, vals: dict) -> bytes: - ''' Encode value(s) into bytes. ''' - - -class Field(Codec): - ''' Base class representing one field in a Message. ''' - - # Default length (0 means the whole buffer) - DEF_LEN = 0 # type: int - - # Default parameters - DEF_PARAMS = { } # type: dict - - # Presence of a field during decoding and encoding - ## get_pres: Callable[[dict], bool] - # Length of a field for self.from_bytes() - ## get_len: Callable[[dict, bytes], int] - # Value of a field for self.to_bytes() - ## get_val: Callable[[dict], Any] - - def __init__(self, name: str, **kw) -> None: - self.name = name - - self.len = kw.get('len', self.DEF_LEN) - if self.len == 0: # flexible field - self.get_len = lambda _, data: len(data) - else: # fixed length - self.get_len = lambda vals, _: self.len - - # Field is unconditionally present by default - self.get_pres = lambda vals: True - # Field takes its value from the given dict by default - self.get_val = lambda vals: vals[self.name] - - # Additional parameters for derived field types - self.p = { key : kw.get(key, self.DEF_PARAMS[key]) - for key in self.DEF_PARAMS } - - def from_bytes(self, vals: dict, data: bytes) -> int: - if self.get_pres(vals) is False: - return 0 - length = self.get_len(vals, data) - if len(data) < length: - raise DecodeError('Short read') - self._from_bytes(vals, data[:length]) - return length - - def to_bytes(self, vals: dict) -> bytes: - if self.get_pres(vals) is False: - return b'' - data = self._to_bytes(vals) - if self.len > 0 and len(data) != self.len: - raise EncodeError('Field length mismatch') - return data - - @abc.abstractmethod - def _from_bytes(self, vals: dict, data: bytes) -> None: - ''' Decode value(s) from the given buffer of bytes. ''' - raise NotImplementedError - - @abc.abstractmethod - def _to_bytes(self, vals: dict) -> bytes: - ''' Encode value(s) into bytes. ''' - raise NotImplementedError - - -class Buf(Field): - ''' A sequence of octets. ''' - - def _from_bytes(self, vals: dict, data: bytes) -> None: - vals[self.name] = data - - def _to_bytes(self, vals: dict) -> bytes: - # TODO: handle len(self.get_val()) < self.get_len() - return self.get_val(vals) - - -class Spare(Field): - ''' Spare filling for RFU fields or padding. ''' - - # Default parameters - DEF_PARAMS = { - 'filler' : b'\x00', - } - - def _from_bytes(self, vals: dict, data: bytes) -> None: - pass # Just ignore it - - def _to_bytes(self, vals: dict) -> bytes: - return self.p['filler'] * self.get_len(vals, b'') - - -class Uint(Field): - ''' An integer field: unsigned, N bits, big endian. ''' - - # Uint8 by default - DEF_LEN = 1 - - # Default parameters - DEF_PARAMS = { - 'offset' : 0, - 'mult' : 1, - } - - # Big endian, unsigned - SIGN = False - BO = 'big' - - def _from_bytes(self, vals: dict, data: bytes) -> None: - val = int.from_bytes(data, self.BO, signed=self.SIGN) - vals[self.name] = val * self.p['mult'] + self.p['offset'] - - def _to_bytes(self, vals: dict) -> bytes: - val = (self.get_val(vals) - self.p['offset']) // self.p['mult'] - return val.to_bytes(self.len, self.BO, signed=self.SIGN) - -class Uint16BE(Uint): - DEF_LEN = 16 // 8 - -class Uint16LE(Uint16BE): - BO = 'little' - -class Uint32BE(Uint): - DEF_LEN = 32 // 8 - -class Uint32LE(Uint32BE): - BO = 'little' - -class Int(Uint): - SIGN = True - -class Int16BE(Int): - DEF_LEN = 16 // 8 - -class Int16LE(Int16BE): - BO = 'little' - -class Int32BE(Int): - DEF_LEN = 32 // 8 - -class Int32LE(Int32BE): - BO = 'little' - - -class BitFieldSet(Field): - ''' A set of bit-fields. ''' - - # Default parameters - DEF_PARAMS = { - # Default field order (MSB first) - 'order' : 'big', - } - - # To be defined by derived types - STRUCT = () # type: Tuple['BitField', ...] - - def __init__(self, **kw) -> None: - Field.__init__(self, self.__class__.__name__, **kw) - - self._fields = kw.get('set', self.STRUCT) - if type(self._fields) is not tuple: - raise ProtocolError('Expected a tuple') - - # LSB first is basically reversed order - if self.p['order'] in ('little', 'lsb'): - self._fields = self._fields[::-1] - - # Calculate the overall field length - if self.len == 0: - bl_sum = sum([f.bl for f in self._fields]) - self.len = bl_sum // 8 - if bl_sum % 8 > 0: - self.len += 1 - - # Re-define self.get_len() since we always know the length - self.get_len = lambda vals, data: self.len - - # Pre-calculate offset and mask for each field - offset = self.len * 8 - for f in self._fields: - if f.bl > offset: - raise ProtocolError(f, 'BitFieldSet overflow') - f.offset = offset - f.bl - f.mask = 2 ** f.bl - 1 - offset -= f.bl - - def _from_bytes(self, vals: dict, data: bytes) -> None: - blob = int.from_bytes(data, byteorder='big') # intentionally using 'big' here - for f in self._fields: - f.dec_val(vals, blob) - - def _to_bytes(self, vals: dict) -> bytes: - blob = 0x00 - for f in self._fields: # TODO: use functools.reduce()? - blob |= f.enc_val(vals) - return blob.to_bytes(self.len, byteorder='big') - -class BitField: - ''' One field in a BitFieldSet. ''' - - # Special fields for BitFieldSet - offset = 0 # type: int - mask = 0 # type: int - - class Spare: - ''' Spare filling in a BitFieldSet. ''' - - def __init__(self, bl: int) -> None: - self.name = None - self.bl = bl - - def enc_val(self, vals: dict) -> int: - return 0 - - def dec_val(self, vals: dict, blob: int) -> None: - pass # Just ignore it - - def __init__(self, name: str, bl: int, **kw) -> None: - if bl < 1: # Ensure proper length - raise ProtocolError('Incorrect bit-field length') - - self.name = name - self.bl = bl - - # (Optional) fixed value for encoding and decoding - self.val = kw.get('val', None) # type: Optional[int] - - def enc_val(self, vals: dict) -> int: - if self.val is None: - val = vals[self.name] - else: - val = self.val - return (val & self.mask) << self.offset - - def dec_val(self, vals: dict, blob: int) -> None: - vals[self.name] = (blob >> self.offset) & self.mask - if (self.val is not None) and (vals[self.name] != self.val): - raise DecodeError('Unexpected value %d, expected %d' - % (vals[self.name], self.val)) - - -class Envelope: - ''' A group of related fields. ''' - - STRUCT = () # type: Tuple[Codec, ...] - - def __init__(self, check_len: bool = True): - # TODO: ensure uniqueue field names in self.STRUCT - self.c = { } # type: dict - self.check_len = check_len - - def __getitem__(self, key: str) -> Any: - return self.c[key] - - def __setitem__(self, key: str, val: Any) -> None: - self.c[key] = val - - def __delitem__(self, key: str) -> None: - del self.c[key] - - def check(self, vals: dict) -> None: - ''' Check the content before encoding and after decoding. - Raise exceptions (e.g. ValueError) if something is wrong. - - Do not assert for every possible error (e.g. a negative value - for a Uint field) if an exception will be thrown by the field's - to_bytes() method anyway. Only additional constraints here. - ''' - - def from_bytes(self, data: bytes) -> int: - self.c.clear() # forget the old content - return self._from_bytes(self.c, data) - - def to_bytes(self) -> bytes: - return self._to_bytes(self.c) - - def _from_bytes(self, vals: dict, data: bytes, offset: int = 0) -> int: - try: # Fields throw exceptions - for f in self.STRUCT: - offset += f.from_bytes(vals, data[offset:]) - except Exception as e: - # Add contextual info - raise DecodeError(self, f, offset) from e - if self.check_len and len(data) != offset: - raise DecodeError(self, 'Unhandled tail octets: %s' - % data[offset:].hex()) - self.check(vals) # Check the content after decoding (raises exceptions) - return offset - - def _to_bytes(self, vals: dict) -> bytes: - def proc(f: Codec): - try: # Fields throw exceptions - return f.to_bytes(vals) - except Exception as e: - # Add contextual info - raise EncodeError(self, f) from e - self.check(vals) # Check the content before encoding (raises exceptions) - return b''.join([proc(f) for f in self.STRUCT]) - - class F(Field): - ''' Field wrapper. ''' - - def __init__(self, e: 'Envelope', name: str, **kw) -> None: - Field.__init__(self, name, **kw) - self.e = e - - def _from_bytes(self, vals: dict, data: bytes) -> None: - vals[self.name] = { } - self.e._from_bytes(vals[self.name], data) - - def _to_bytes(self, vals: dict) -> bytes: - return self.e._to_bytes(self.get_val(vals)) - - def f(self, name: str, **kw) -> Field: - return self.F(self, name, **kw) - - -class Sequence: - ''' A sequence of repeating elements (e.g. TLVs). ''' - - # The item of sequence - ITEM = None # type: Optional[Envelope] - - def __init__(self, **kw) -> None: - if (self.ITEM is None) and ('item' not in kw): - raise ProtocolError('Missing Sequence item') - self._item = kw.get('item', self.ITEM) # type: Envelope - self._item.check_len = False - - def from_bytes(self, data: bytes) -> list: - proc = self._item._from_bytes - vseq, offset = [], 0 - length = len(data) - - while offset < length: - vseq.append({ }) # new item of sequence - offset += proc(vseq[-1], data[offset:]) - - return vseq - - def to_bytes(self, vseq: list) -> bytes: - proc = self._item._to_bytes - return b''.join([proc(v) for v in vseq]) - - class F(Field): - ''' Field wrapper. ''' - - def __init__(self, s: 'Sequence', name: str, **kw) -> None: - Field.__init__(self, name, **kw) - self.s = s - - def _from_bytes(self, vals: dict, data: bytes) -> None: - vals[self.name] = self.s.from_bytes(data) - - def _to_bytes(self, vals: dict) -> bytes: - return self.s.to_bytes(self.get_val(vals)) - - def f(self, name: str, **kw) -> Field: - return self.F(self, name, **kw) diff --git a/src/target/trx_toolkit/ctrl_cmd.py b/src/target/trx_toolkit/ctrl_cmd.py deleted file mode 100755 index c6ac6d8..0000000 --- a/src/target/trx_toolkit/ctrl_cmd.py +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Auxiliary tool to send custom commands via TRX CTRL interface, -# which may be useful for testing and fuzzing -# -# (C) 2017-2018 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -APP_CR_HOLDERS = [("2017-2018", "Vadim Yanitskiy <axilirator(a)gmail.com>")] - -import logging as log -import signal -import argparse -import select -import sys - -from app_common import ApplicationBase -from udp_link import UDPLink - -class Application(ApplicationBase): - def __init__(self): - self.app_print_copyright(APP_CR_HOLDERS) - self.argv = self.parse_argv() - - # Set up signal handlers - signal.signal(signal.SIGINT, self.sig_handler) - - # Configure logging - self.app_init_logging(self.argv) - - # Init UDP connection - self.ctrl_link = UDPLink( - self.argv.remote_addr, self.argv.base_port + 1, - self.argv.bind_addr, self.argv.bind_port) - - # Debug print - log.info("Init TRXC interface (%s)" \ - % self.ctrl_link.desc_link()) - - def parse_argv(self): - parser = argparse.ArgumentParser(prog = "ctrl_cmd", - description = "Auxiliary tool to send control commands") - - # Register common logging options - self.app_reg_logging_options(parser) - - trx_group = parser.add_argument_group("TRX interface") - trx_group.add_argument("-r", "--remote-addr", - dest = "remote_addr", type = str, default = "127.0.0.1", - help = "Set remote address (default %(default)s)") - trx_group.add_argument("-b", "--bind-addr", - dest = "bind_addr", type = str, default = "0.0.0.0", - help = "Set bind address (default %(default)s)") - trx_group.add_argument("-p", "--base-port", - dest = "base_port", type = int, default = 6700, - help = "Set base port number (default %(default)s)") - trx_group.add_argument("-P", "--bind-port", - dest = "bind_port", type = int, default = 0, - help = "Set bind port number (default random)") - trx_group.add_argument("-f", "--fuzzing", - dest = "fuzzing", action = "store_true", - help = "Send raw payloads (without CMD)") - - return parser.parse_args() - - def run(self): - while True: - self.print_prompt() - - # Wait until we get any data on any socket - socks = [sys.stdin, self.ctrl_link.sock] - r_event, w_event, x_event = select.select(socks, [], []) - - # Check for incoming CTRL commands - if sys.stdin in r_event: - cmd = sys.stdin.readline() - self.handle_cmd(cmd) - - if self.ctrl_link.sock in r_event: - data, addr = self.ctrl_link.sock.recvfrom(128) - sys.stdout.write("\r%s\n" % data.decode()) - sys.stdout.flush() - - def handle_cmd(self, cmd): - # Strip spaces, tabs, etc. - cmd = cmd.strip().strip("\0") - - # Send a command - if self.argv.fuzzing: - self.ctrl_link.send("%s" % cmd) - else: - self.ctrl_link.send("CMD %s\0" % cmd) - - def print_prompt(self): - sys.stdout.write("TRXC# ") - sys.stdout.flush() - - def sig_handler(self, signum, frame): - log.info("Signal %d received" % signum) - if signum == signal.SIGINT: - sys.exit(0) - -if __name__ == '__main__': - app = Application() - app.run() diff --git a/src/target/trx_toolkit/ctrl_if.py b/src/target/trx_toolkit/ctrl_if.py deleted file mode 100644 index f9d30c1..0000000 --- a/src/target/trx_toolkit/ctrl_if.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# CTRL interface implementation -# -# (C) 2016-2020 by Vadim Yanitskiy <axilirator(a)gmail.com> -# Contributions by sysmocom - s.f.m.c. GmbH -# -# 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 2 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. - -import logging as log -import time - -from udp_link import UDPLink - -class CTRLInterface(UDPLink): - def __init__(self, *udp_link_args): - UDPLink.__init__(self, *udp_link_args) - log.debug("Init TRXC interface (%s)" % self.desc_link()) - - # Do not delay RSP messages by default - self.rsp_delay_ms = 0 - - def handle_rx(self): - # Read data from socket - data, remote = self.sock.recvfrom(128) - data = data.decode() - - if not self.verify_req(data): - log.error("Wrong data on TRXC interface") - return - - # Attempt to parse a command - request = self.prepare_req(data) - rc = self.parse_cmd(request) - - if type(rc) is tuple: - self.send_response(request, remote, rc[0], rc[1]) - else: - self.send_response(request, remote, rc) - - def verify_req(self, data): - # Verify command signature - return data.startswith("CMD") - - def prepare_req(self, data): - # Strip signature, paddings and \0 - request = data[4:].strip().strip("\0") - # Split into a command and arguments - request = request.split(" ") - # Now we have something like ["TXTUNE", "941600"] - return request - - # If va is True, the command can have variable number of arguments - def verify_cmd(self, request, cmd, argc, va = False): - # Check if requested command matches - if request[0] != cmd: - return False - - # And has enough arguments - req_len = len(request[1:]) - if not va and req_len != argc: - return False - elif va and req_len < argc: - return False - - return True - - def send_response(self, request, remote, response_code, params = None): - # Include status code, for example ["TXTUNE", "0", "941600"] - request.insert(1, str(response_code)) - - # Optionally append command specific parameters - if params is not None: - request += params - - # Add the response signature, and join back to string - response = "RSP " + " ".join(request) + "\0" - # If configured, delay sending the RSP message - if self.rsp_delay_ms > 0: - time.sleep(self.rsp_delay_ms / 1000.0) - # Now we have something like "RSP TXTUNE 0 941600" - self.sendto(response, remote) - - def parse_cmd(self, request): - raise NotImplementedError diff --git a/src/target/trx_toolkit/ctrl_if_trx.py b/src/target/trx_toolkit/ctrl_if_trx.py deleted file mode 100644 index e6fdaf1..0000000 --- a/src/target/trx_toolkit/ctrl_if_trx.py +++ /dev/null @@ -1,230 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# CTRL interface implementation (common commands) -# -# (C) 2016-2020 by Vadim Yanitskiy <axilirator(a)gmail.com> -# Contributions by sysmocom - s.f.m.c. GmbH -# -# 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 2 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. - -import logging as log - -from ctrl_if import CTRLInterface -from data_msg import Msg - -class CTRLInterfaceTRX(CTRLInterface): - """ CTRL interface handler for common transceiver management commands. - - The following set of commands is mandatory for every transceiver: - - - POWERON / POWEROFF - state management (running / idle), - - RXTUNE / TXTUNE - RX / TX frequency management, - - SETSLOT - timeslot management. - - Additionally, there is an optional MEASURE command, which is used - by OsmocomBB to perform power measurement on a given frequency. - - A given transceiver may also define its own command handler, - that is prioritized, i.e. it can overwrite any commands mentioned - above. If None is returned, a command is considered as unhandled. - - == TRXD header version negotiation - - Messages on DATA interface may have different header formats, - defined by a version number, which can be negotiated on the - control interface. By default, the Transceiver will use the - legacy header version (0). - - The header format negotiation can be initiated by the L1 - using 'SETFORMAT' command. If the requested version is not - supported by the transceiver, status code of the response - message should indicate a preferred (basically, the latest) - version. The format of this message is the following: - - L1 -> TRX: CMD SETFORMAT VER_REQ - L1 <- TRX: RSP SETFORMAT VER_RSP VER_REQ - - where: - - - VER_REQ is the requested version (suggested by the L1), - - VER_RSP is either the applied version if matches VER_REQ, - or a preferred version if VER_REQ is not supported. - - If the transceiver indicates VER_RSP different than VER_REQ, - the L1 is supposed to reinitiate the version negotiation - using the suggested VER_RSP. For example: - - L1 -> TRX: CMD SETFORMAT 2 - L1 <- TRX: RSP SETFORMAT 1 2 - - L1 -> TRX: CMD SETFORMAT 1 - L1 <- TRX: RSP SETFORMAT 1 1 - - If no suitable VER_RSP is found, or the VER_REQ is incorrect, - the status code in the response shall be -1. - - As soon as VER_RSP matches VER_REQ in the response, the process - of negotiation is complete. Changing the header version is - supposed to be done before POWERON, but can be also done after. - - """ - - def __init__(self, trx, *udp_link_args): - CTRLInterface.__init__(self, *udp_link_args) - - # Link with Transceiver instance we belong to - self.trx = trx - - def parse_cmd(self, request): - # Custom command handlers (prioritized) - res = self.trx.ctrl_cmd_handler(request) - if res is not None: - return res - - # Power control - if self.verify_cmd(request, "POWERON", 0): - log.debug("(%s) Recv POWERON CMD" % self.trx) - - # Ensure transceiver isn't working - if self.trx.running: - log.error("(%s) Transceiver already started" % self.trx) - return -1 - - # Ensure that transceiver is ready - if not self.trx.ready: - log.error("(%s) Transceiver is not ready" % self.trx) - return -1 - - log.info("(%s) Starting transceiver..." % self.trx) - self.trx.power_event_handler(poweron=True) - - return 0 - - elif self.verify_cmd(request, "POWEROFF", 0): - log.debug("(%s) Recv POWEROFF cmd" % self.trx) - - log.info("(%s) Stopping transceiver..." % self.trx) - self.trx.power_event_handler(poweron=False) - - return 0 - - # Tuning Control - elif self.verify_cmd(request, "RXTUNE", 1): - log.debug("(%s) Recv RXTUNE cmd" % self.trx) - - # TODO: check freq range - self.trx._rx_freq = int(request[1]) * 1000 - return 0 - - elif self.verify_cmd(request, "TXTUNE", 1): - log.debug("(%s) Recv TXTUNE cmd" % self.trx) - - # TODO: check freq range - self.trx._tx_freq = int(request[1]) * 1000 - return 0 - - # Power measurement - if self.verify_cmd(request, "MEASURE", 1): - log.debug("(%s) Recv MEASURE cmd" % self.trx) - - # Power Measurement interface is optional - # for Transceiver, thus may be uninitialized - if self.trx.pwr_meas is None: - log.error("(%s) Power Measurement interface is not " - "initialized => rejecting command" % self.trx) - return -1 - - # TODO: check freq range - meas_freq = int(request[1]) * 1000 - meas_dbm = self.trx.pwr_meas.measure(meas_freq) - - return (0, [str(meas_dbm)]) - - # Frequency hopping configuration (variable length list): - # - # CMD SETFH <HSN> <MAIO> <RXF1> <TXF1> [... <RXFN> <TXFN>] - # - # where <RXFN> and <TXFN> is a pair of Rx/Tx frequencies (in kHz) - # corresponding to one ARFCN the Mobile Allocation. Note that the - # channel list is expected to be sorted in ascending order. - if self.verify_cmd(request, "SETFH", 4, va = True): - log.debug("(%s) Recv SETFH cmd" % self.trx) - - # Parse HSN and MAIO - hsn = int(request[1]) - maio = int(request[2]) - - # Parse the list of hopping frequencies - ma = [int(f) * 1000 for f in request[3:]] # kHz -> Hz - ma = [(rx, tx) for rx, tx in zip(ma[0::2], ma[1::2])] - - # Configure the hopping sequence generator - try: - self.trx.enable_fh(hsn, maio, ma) - return 0 - except: - log.error("(%s) Failed to configure frequency hopping" % self.trx) - return -1 - - # TRXD header version negotiation - if self.verify_cmd(request, "SETFORMAT", 1): - log.debug("(%s) Recv SETFORMAT cmd" % self.trx) - - # Parse the requested version - ver_req = int(request[1]) - # ... and store current for logging - ver_cur = self.trx.data_if._hdr_ver - - if ver_req < 0 or ver_req > Msg.CHDR_VERSION_MAX: - log.error("(%s) Incorrect TRXD header version %u" - % (self.trx, ver_req)) - return -1 - - if not self.trx.data_if.set_hdr_ver(ver_req): - ver_rsp = self.trx.data_if.pick_hdr_ver(ver_req) - log.warn("(%s) Requested TRXD header version %u " - "is not supported, suggesting %u..." - % (self.trx, ver_req, ver_rsp)) - return ver_rsp - - log.info("(%s) TRXD header version %u -> %u" - % (self.trx, ver_cur, ver_req)) - return ver_req - - # Set Power Attenuation - if self.verify_cmd(request, "SETPOWER", 1): - log.debug("(%s) Recv SETPOWER cmd" % self.trx) - # Parse the requested Tx Power Attenuation - att_req = int(request[1]) - self.trx.tx_att_base = att_req - return 0 - - # Retrieve Nominal Tx power - if self.verify_cmd(request, "NOMTXPOWER", 0): - log.debug("(%s) Recv NOMTXPOWER cmd" % self.trx) - return (0, [str(self.trx.tx_power_base)]) - - # Lock/Unlock RF emission+reception - if self.verify_cmd(request, "RFMUTE", 1): - log.debug("(%s) Recv RFMUTE cmd" % self.trx) - # Parse the requested RFMUTE state (1=locked, 0=unlocked) - self.trx.rf_muted = int(request[1]) > 0 - return 0 - - # Wrong / unknown command - else: - # We don't care about other commands, - # so let's merely ignore them ;) - log.debug("(%s) Ignore CMD %s" % (self.trx, request[0])) - return 0 diff --git a/src/target/trx_toolkit/data_dump.py b/src/target/trx_toolkit/data_dump.py deleted file mode 100644 index 8475ceb..0000000 --- a/src/target/trx_toolkit/data_dump.py +++ /dev/null @@ -1,213 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Helpers for DATA capture management -# -# (C) 2018 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -import logging as log -import struct - -from data_msg import * - -class DATADump: - # Constants - TAG_TxMsg = b'\x01' - TAG_RxMsg = b'\x02' - HDR_LENGTH = 3 - - # Generates raw bytes from a DATA message - # Return value: raw message bytes - def dump_msg(self, msg): - # Determine a message type - if isinstance(msg, TxMsg): - tag = self.TAG_TxMsg - elif isinstance(msg, RxMsg): - tag = self.TAG_RxMsg - else: - raise ValueError("Unknown message type") - - # Generate a message payload - msg_raw = msg.gen_msg() - - # Calculate and pack the message length - msg_len = len(msg_raw) - - # Pack to unsigned short (2 bytes, BE) - msg_len = struct.pack(">H", msg_len) - - # Concatenate a message with header - return bytearray(tag + msg_len) + msg_raw - - def parse_hdr(self, hdr): - # Extract the header info - msg_len = struct.unpack(">H", hdr[1:3])[0] - tag = hdr[:1] - - # Check if tag is known - if tag == self.TAG_TxMsg: - msg = TxMsg() - elif tag == self.TAG_RxMsg: - msg = RxMsg() - else: - # Unknown tag - return False - - return (msg, msg_len) - -class DATADumpFile(DATADump): - def __init__(self, capture): - # Check if capture file is already opened - if isinstance(capture, str): - log.info("Opening capture file '%s'..." % capture) - self.f = open(capture, "a+b") - else: - self.f = capture - - def __del__(self): - log.info("Closing the capture file") - self.f.close() - - # Moves the file descriptor before a specified message - # Return value: - # True in case of success, - # or False in case of EOF or header parsing error. - def _seek2msg(self, idx): - # Seek to the beginning of the capture - self.f.seek(0) - - # Read the capture in loop... - for _ in range(idx): - # Attempt to read a message header - hdr_raw = self.f.read(self.HDR_LENGTH) - if len(hdr_raw) != self.HDR_LENGTH: - return False - - # Attempt to parse it - rc = self.parse_hdr(hdr_raw) - if rc is False: - log.error("Couldn't parse a message header") - return False - - # Expand the header - (_, msg_len) = rc - - # Skip a message - self.f.seek(msg_len, 1) - - return True - - # Parses a single message at the current descriptor position - # Return value: - # a parsed message in case of success, - # or None in case of EOF or header parsing error, - # or False in case of message parsing error. - def _parse_msg(self): - # Attempt to read a message header - hdr_raw = self.f.read(self.HDR_LENGTH) - if len(hdr_raw) != self.HDR_LENGTH: - return None - - # Attempt to parse it - rc = self.parse_hdr(hdr_raw) - if rc is False: - log.error("Couldn't parse a message header") - return None - - # Expand the header - (msg, msg_len) = rc - - # Attempt to read a message - msg_raw = self.f.read(msg_len) - if len(msg_raw) != msg_len: - log.error("Message length mismatch") - return None - - # Attempt to parse a message - try: - msg_raw = bytearray(msg_raw) - msg.parse_msg(msg_raw) - except: - log.error("Couldn't parse a message, skipping...") - return False - - # Success - return msg - - # Parses a particular message defined by index idx - # Return value: - # a parsed message in case of success, - # or None in case of EOF, out of range, or header parsing error, - # or False in case of message parsing error. - def parse_msg(self, idx): - # Move descriptor to the beginning of requested message - rc = self._seek2msg(idx) - if not rc: - log.error("Couldn't find requested message") - return None - - # Attempt to parse a message - return self._parse_msg() - - # Parses all messages from a given file - # Return value: - # list of parsed messages, - # or False in case of range error. - def parse_all(self, skip = None, count = None): - result = [] - - # Should we skip some messages? - if skip is None: - # Seek to the beginning of the capture - self.f.seek(0) - else: - rc = self._seek2msg(skip) - if not rc: - log.error("Couldn't find requested message") - return False - - # Read the capture in loop... - while True: - # Attempt to parse a message - msg = self._parse_msg() - - # EOF or broken header - if msg is None: - break - - # Skip unparsed messages - if msg is False: - continue - - # Success, append a message - result.append(msg) - - # Count limitation - if count is not None: - if len(result) == count: - break - - return result - - # Writes a new message at the end of the capture - def append_msg(self, msg): - # Generate raw bytes and write - msg_raw = self.dump_msg(msg) - self.f.write(msg_raw) - - # Writes a list of messages at the end of the capture - def append_all(self, msgs): - for msg in msgs: - self.append_msg(msg) diff --git a/src/target/trx_toolkit/data_if.py b/src/target/trx_toolkit/data_if.py deleted file mode 100644 index f59ca17..0000000 --- a/src/target/trx_toolkit/data_if.py +++ /dev/null @@ -1,114 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# DATA interface implementation -# -# (C) 2017-2019 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -import logging as log - -from udp_link import UDPLink -from data_msg import * - -class DATAInterface(UDPLink): - def __init__(self, *udp_link_args): - # Default header version (legacy) - self._hdr_ver = 0x00 - - UDPLink.__init__(self, *udp_link_args) - log.debug("Init TRXD interface (%s)" % self.desc_link()) - - def set_hdr_ver(self, ver): - if not ver in Msg.KNOWN_VERSIONS: - return False - - self._hdr_ver = ver - return True - - def pick_hdr_ver(self, ver_req): - # Pick a version that is lower or equal to ver_req - for ver in Msg.KNOWN_VERSIONS[::-1]: - if ver <= ver_req: - return ver - - # No suitable version found - return -1 - - def match_hdr_ver(self, msg): - if msg.ver == self._hdr_ver: - return True - - log.error("(%s) Rx DATA message (%s) with unexpected header " - "version %u (!= expected %u), ignoring..." - % (self.desc_link(), msg.desc_hdr(), - msg.ver, self._hdr_ver)) - return False - - def recv_raw_data(self): - data, _ = self.sock.recvfrom(512) - return data - - def recv_tx_msg(self): - # Read raw data from socket - data = self.recv_raw_data() - - # Attempt to parse a TRXD Tx message - try: - msg = TxMsg() - msg.parse_msg(data) - except: - log.error("Failed to parse a TRXD Tx message " - "from R:%s" % self.desc_remote()) - return None - - # Make sure the header version matches - # the configured one (self._hdr_ver) - if not self.match_hdr_ver(msg): - return None - - return msg - - def recv_rx_msg(self): - # Read raw data from socket - data = self.recv_raw_data() - - # Attempt to parse a TRXD Rx message - try: - msg = RxMsg() - msg.parse_msg(bytearray(data)) - except: - log.error("Failed to parse a TRXD Rx message " - "from R:%s" % self.desc_remote()) - return None - - # Make sure the header version matches - # the configured one (self._hdr_ver) - if not self.match_hdr_ver(msg): - return None - - return msg - - def send_msg(self, msg, legacy = False): - try: - # Validate and encode a TRXD message - payload = msg.gen_msg(legacy) - except ValueError as e: - log.error("Failed to encode a TRXD message ('%s') " - "due to error: %s" % (msg.desc_hdr(), e)) - # TODO: we may want to send a NOPE.ind here - return - - # Send message - self.send(payload) diff --git a/src/target/trx_toolkit/data_msg.py b/src/target/trx_toolkit/data_msg.py deleted file mode 100644 index b1673f5..0000000 --- a/src/target/trx_toolkit/data_msg.py +++ /dev/null @@ -1,689 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# DATA interface message definitions and helpers -# -# (C) 2018-2019 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -import random -import struct -import abc - -from typing import List -from enum import Enum -from array import array -from gsm_shared import * - -# _bu2s converts unsigned byte to signed. -def _bu2s(x): - return struct.unpack('b', struct.pack('B', x))[0] - -class Modulation(Enum): - """ Modulation types defined in 3GPP TS 45.002 """ - ModGMSK = (0b0000, 1 * GMSK_BURST_LEN) - Mod8PSK = (0b0100, 3 * GMSK_BURST_LEN) - ModGMSK_AB = (0b0110, 1 * GMSK_BURST_LEN) - # ModRFU = (0b0111, 0) # Reserved for Future Use - Mod16QAM = (0b1000, 4 * GMSK_BURST_LEN) - Mod32QAM = (0b1010, 5 * GMSK_BURST_LEN) - ModAQPSK = (0b1100, 2 * GMSK_BURST_LEN) - - def __init__(self, coding, bl): - # Coding in TRXD header - self.coding = coding - # Burst length - self.bl = bl - - @classmethod - def pick(self, coding): - for mod in list(self): - if mod.coding == coding: - return mod - return None - - @classmethod - def pick_by_bl(self, bl): - for mod in list(self): - if mod.bl == bl: - return mod - return None - -class Msg(abc.ABC): - ''' TRXD (DATA) message coding API (common part). ''' - - # NOTE: up to 16 versions can be encoded - CHDR_VERSION_MAX = 0b1111 - KNOWN_VERSIONS = (0, 1) - - def __init__(self, fn = None, tn = None, burst = None, ver = 0): - self.burst = burst # bytes|bytearray for ubit, array[b] for sbit, array[B] for usbit - self.ver = ver - self.fn = fn - self.tn = tn - - @property - def CHDR_LEN(self): - ''' The common header length. ''' - return 1 + 4 # (VER + TN) + FN - - @abc.abstractmethod - def append_hdr_to(self, buf): - ''' Generate message specific header by appending it to buf. ''' - - @abc.abstractmethod - def parse_hdr(self, hdr): - ''' Parse message specific header. ''' - - @abc.abstractmethod - def append_burst_to(self, buf): - ''' Generate message specific burst by appending it to buf. ''' - - @abc.abstractmethod - def parse_burst(self, burst): - ''' Parse message specific burst. ''' - - @abc.abstractmethod - def rand_burst(self): - ''' Generate a random message specific burst. ''' - - def rand_fn(self): - ''' Generate a random frame number. ''' - return random.randint(0, GSM_HYPERFRAME) - - def rand_tn(self): - ''' Generate a random timeslot number. ''' - return random.randint(0, 7) - - def rand_hdr(self): - ''' Randomize the message header. ''' - self.fn = self.rand_fn() - self.tn = self.rand_tn() - - def desc_hdr(self): - ''' Generate human-readable header description. ''' - - result = "" - - if self.ver > 0: - result += ("ver=%u " % self.ver) - - if self.fn is not None: - result += ("fn=%u " % self.fn) - - if self.tn is not None: - result += ("tn=%u " % self.tn) - - if self.burst is not None and len(self.burst) > 0: - result += ("bl=%u " % len(self.burst)) - - return result - - @staticmethod - def usbit2sbit(bits): # array[B] -> array[b] - ''' Convert unsigned soft-bits {254..0} to soft-bits {-127..127}. ''' - return array('b', bits.tobytes().translate(Msg._tab_usbit2sbit)) - _tab_usbit2sbit = array('b', [-127 if (b == 0xff) else 127 - b for b in range(0x100)]) - - @staticmethod - def sbit2usbit(bits): # array[b] -> array[B] - ''' Convert soft-bits {-127..127} to unsigned soft-bits {254..0}. ''' - return array('B', bits.tobytes().translate(Msg._tab_sbit2usbit)) - _tab_sbit2usbit = array('B', [127 - _bu2s(b) for b in range(0x100)]) - - @staticmethod - def sbit2ubit(bits): # array[b] -> bytearray - ''' Convert soft-bits {-127..127} to bits {1..0}. ''' - return bytearray(bits).translate(Msg._tab_sbit2ubit) - _tab_sbit2ubit = array('B', [int(_bu2s(b) < 0) for b in range(0x100)]) - - @staticmethod - def ubit2sbit(bits: bytearray): # -> array[b] - ''' Convert bits {1..0} to soft-bits {-127..127}. ''' - return array('b', bits.translate(Msg._tab_ubit2sbit)) - _tab_ubit2sbit = array('b', [-127 if b else 127 for b in range(0x100)]) - - - def validate(self): - ''' Validate the message fields (throws ValueError). ''' - - if not self.ver in self.KNOWN_VERSIONS: - raise ValueError("Unknown TRXD header version %d" % self.ver) - - if self.fn is None: - raise ValueError("TDMA frame-number is not set") - - if self.fn < 0 or self.fn > GSM_HYPERFRAME: - raise ValueError("TDMA frame-number %d is out of range" % self.fn) - - if self.tn is None: - raise ValueError("TDMA time-slot is not set") - - if self.tn < 0 or self.tn > 7: - raise ValueError("TDMA time-slot %d is out of range" % self.tn) - - def gen_msg(self, legacy = False): - ''' Generate a TRX DATA message. ''' - - # Validate all the fields - self.validate() - - # Allocate an empty byte-array - buf = bytearray() - - # Put version (4 bits) and TDMA TN (3 bits) - buf.append((self.ver << 4) | (self.tn & 0x07)) - - # Put TDMA FN (4 octets, BE) - buf += struct.pack(">L", self.fn) - - # Generate message specific header part - self.append_hdr_to(buf) - - # Generate burst - if self.burst is not None: - self.append_burst_to(buf) - - # This is a rudiment from (legacy) OpenBTS transceiver, - # some L1 implementations still expect two dummy bytes. - if legacy and self.ver == 0x00: - buf += bytearray(2) - - return buf - - def parse_msg(self, msg): - ''' Parse a TRX DATA message. ''' - - # Make sure we have at least common header - if len(msg) < self.CHDR_LEN: - raise ValueError("Message is to short: missing common header") - - # Parse the header version first - self.ver = (msg[0] >> 4) - if not self.ver in self.KNOWN_VERSIONS: - raise ValueError("Unknown TRXD header version %d" % self.ver) - - # Parse TDMA TN and FN - self.tn = (msg[0] & 0x07) - self.fn = struct.unpack(">L", msg[1:5])[0] - - # Make sure we have the whole header, - # including the version specific fields - if len(msg) < self.HDR_LEN: - raise ValueError("Message is to short: missing version specific header") - - # Specific message part - self.parse_hdr(msg) - - # Copy burst, skipping header - if len(msg) == self.HDR_LEN: - self.burst = None - return - msg_burst = memoryview(msg)[self.HDR_LEN:] - self.parse_burst(msg_burst) - -class TxMsg(Msg): - ''' Tx (L1 -> TRX) message coding API. ''' - - # Constants - PWR_MIN = 0x00 - PWR_MAX = 0xff - - # Specific message fields - pwr = None - - @property - def HDR_LEN(self): - ''' Calculate header length depending on its version. ''' - - # Common header length - length = self.CHDR_LEN - - # Message specific header length - if self.ver in (0x00, 0x01): - length += 1 # PWR - else: - raise IndexError("Unhandled version %u" % self.ver) - - return length - - def validate(self): - ''' Validate the message fields (throws ValueError). ''' - - # Validate common fields - Msg.validate(self) - - if self.pwr is None: - raise ValueError("Tx Attenuation level is not set") - - if self.pwr < self.PWR_MIN or self.pwr > self.PWR_MAX: - raise ValueError("Tx Attenuation %d is out of range" % self.pwr) - - # FIXME: properly handle IDLE / NOPE indications - if self.burst is None: - raise ValueError("Tx burst bits are not set") - - # FIXME: properly handle IDLE / NOPE indications - if len(self.burst) not in (GMSK_BURST_LEN, EDGE_BURST_LEN): - raise ValueError("Tx burst has odd length %u" % len(self.burst)) - - def rand_pwr(self, min = None, max = None): - ''' Generate a random power level. ''' - - if min is None: - min = self.PWR_MIN - - if max is None: - max = self.PWR_MAX - - return random.randint(min, max) - - def rand_hdr(self): - ''' Randomize message specific header. ''' - - Msg.rand_hdr(self) - self.pwr = self.rand_pwr() - - def desc_hdr(self): - ''' Generate human-readable header description. ''' - - # Describe the common part - result = Msg.desc_hdr(self) - - if self.pwr is not None: - result += ("pwr=%u " % self.pwr) - - # Strip useless whitespace and return - return result.strip() - - def append_hdr_to(self, buf): - ''' Generate message specific header by appending it to buf. ''' - - # Put power - buf.append(self.pwr) - - def parse_hdr(self, hdr): - ''' Parse message specific header part. ''' - - # Parse power level - self.pwr = hdr[5] - - def append_burst_to(self, buf): - ''' Generate message specific burst by appending it to buf. ''' - - # Copy burst 'as is' - return buf.extend(self.burst) - - def parse_burst(self, burst): - ''' Parse message specific burst. ''' - - length = len(burst) - - # Distinguish between GSM and EDGE - if length >= EDGE_BURST_LEN: - if length > EDGE_BURST_LEN: - burst = memoryview(burst)[:EDGE_BURST_LEN] - else: - if length > GMSK_BURST_LEN: - burst = memoryview(burst)[:GMSK_BURST_LEN] - - self.burst = bytearray(burst) - - def rand_burst(self, length = GMSK_BURST_LEN): - ''' Generate a random message specific burst. ''' - self.burst = bytearray([random.randint(0, 1) for _ in range(length)]) - - def trans(self, ver = None): - ''' Transform this message into RxMsg. ''' - - # Allocate a new message - msg = RxMsg(fn = self.fn, tn = self.tn, - ver = self.ver if ver is None else ver) - - # Convert burst bits - if self.burst is not None: - msg.burst = self.ubit2sbit(self.burst) - else: - msg.nope_ind = True - - return msg - -class RxMsg(Msg): - ''' Rx (TRX -> L1) message coding API. ''' - - # rxlev2dbm(0..63) gives us [-110..-47], plus -10 dbm for noise - RSSI_MIN = -120 - RSSI_MAX = -47 - - # Min and max values of int16_t - TOA256_MIN = -32768 - TOA256_MAX = 32767 - - # TSC (Training Sequence Code) range - TSC_RANGE = range(0, 8) - - # C/I range (in centiBels) - CI_MIN = -1280 - CI_MAX = 1280 - - # IDLE frame / nope detection indicator - NOPE_IND = (1 << 7) - - # Specific message fields - rssi = None - toa256 = None - - # Version 0x01 specific (default values) - mod_type = Modulation.ModGMSK - nope_ind = False - - tsc_set = None - tsc = None - ci = None - - @property - def HDR_LEN(self): - ''' Calculate header length depending on its version. ''' - - # Common header length - length = self.CHDR_LEN - - # Message specific header length - if self.ver == 0x00: - # RSSI + ToA - length += 1 + 2 - elif self.ver == 0x01: - # RSSI + ToA + TS + C/I - length += 1 + 2 + 1 + 2 - else: - raise IndexError("Unhandled version %u" % self.ver) - - return length - - def _validate_burst_v0(self): - # Burst is mandatory - if self.burst is None: - raise ValueError("Rx burst bits are not set") - - # ... and can be either of GSM (GMSK) or EDGE (8-PSK) - if len(self.burst) not in (GMSK_BURST_LEN, EDGE_BURST_LEN): - raise ValueError("Rx burst has odd length %u" % len(self.burst)) - - def _validate_burst_v1(self): - # Burst is omitted in case of an IDLE / NOPE indication - if self.nope_ind and self.burst is None: - return - - if self.nope_ind and self.burst is not None: - raise ValueError("NOPE.ind comes with burst?!?") - if self.burst is None: - raise ValueError("Rx burst bits are not set") - - # Burst length depends on modulation type - if len(self.burst) != self.mod_type.bl: - raise ValueError("Rx burst has odd length %u" % len(self.burst)) - - def validate_burst(self): - ''' Validate the burst (throws ValueError). ''' - - if self.ver == 0x00: - self._validate_burst_v0() - elif self.ver >= 0x01: - self._validate_burst_v1() - - def validate(self): - ''' Validate the message header fields (throws ValueError). ''' - - # Validate common fields - Msg.validate(self) - - if self.rssi is None: - raise ValueError("RSSI is not set") - - if self.rssi < self.RSSI_MIN or self.rssi > self.RSSI_MAX: - raise ValueError("RSSI %d is out of range" % self.rssi) - - if self.toa256 is None: - raise ValueError("ToA256 is not set") - - if self.toa256 < self.TOA256_MIN or self.toa256 > self.TOA256_MAX: - raise ValueError("ToA256 %d is out of range" % self.toa256) - - # Version specific parameters (omited for NOPE.ind) - if self.ver >= 0x01 and not self.nope_ind: - if type(self.mod_type) is not Modulation: - raise ValueError("Unknown Rx modulation type") - - if self.tsc_set is None: - raise ValueError("TSC set is not set") - - if self.mod_type is Modulation.ModGMSK: - if self.tsc_set not in range(0, 4): - raise ValueError("TSC set %d is out of range" % self.tsc_set) - else: - if self.tsc_set not in range(0, 2): - raise ValueError("TSC set %d is out of range" % self.tsc_set) - - if self.tsc is None: - raise ValueError("TSC is not set") - - if self.tsc not in self.TSC_RANGE: - raise ValueError("TSC %d is out of range" % self.tsc) - - # Version specific parameters (also present in NOPE.ind) - if self.ver >= 0x01: - if self.ci is None: - raise ValueError("C/I is not set") - - if self.ci < self.CI_MIN or self.ci > self.CI_MAX: - raise ValueError("C/I %d is out of range" % self.ci) - - self.validate_burst() - - def rand_rssi(self, min = None, max = None): - ''' Generate a random RSSI value. ''' - - if min is None: - min = self.RSSI_MIN - - if max is None: - max = self.RSSI_MAX - - return random.randint(min, max) - - def rand_toa256(self, min = None, max = None): - ''' Generate a random ToA (Time of Arrival) value. ''' - - if min is None: - min = self.TOA256_MIN - - if max is None: - max = self.TOA256_MAX - - return random.randint(min, max) - - def rand_hdr(self): - ''' Randomize message specific header. ''' - - Msg.rand_hdr(self) - self.rssi = self.rand_rssi() - self.toa256 = self.rand_toa256() - - if self.ver >= 0x01: - self.mod_type = random.choice(list(Modulation)) - if self.mod_type is Modulation.ModGMSK: - self.tsc_set = random.randint(0, 3) - else: - self.tsc_set = random.randint(0, 1) - self.tsc = random.choice(self.TSC_RANGE) - - # C/I: Carrier-to-Interference ratio - self.ci = random.randint(self.CI_MIN, self.CI_MAX) - - def desc_hdr(self): - ''' Generate human-readable header description. ''' - - # Describe the common part - result = Msg.desc_hdr(self) - - if self.rssi is not None: - result += ("rssi=%d " % self.rssi) - - if self.toa256 is not None: - result += ("toa256=%d " % self.toa256) - - if self.ver >= 0x01: - if not self.nope_ind: - if self.mod_type is not None: - result += ("%s " % self.mod_type) - if self.tsc_set is not None: - result += ("set=%u " % self.tsc_set) - if self.tsc is not None: - result += ("tsc=%u " % self.tsc) - if self.ci is not None: - result += ("C/I=%d cB " % self.ci) - else: - result += "(IDLE / NOPE IND) " - - # Strip useless whitespace and return - return result.strip() - - def gen_mts(self): - ''' Encode Modulation and Training Sequence info. ''' - - # IDLE / nope indication has no MTS info - if self.nope_ind: - return self.NOPE_IND - - # TSC: . . . . . X X X - mts = self.tsc & 0b111 - - # MTS: . X X X X . . . - mts |= self.mod_type.coding << 3 - mts |= self.tsc_set << 3 - - return mts - - def parse_mts(self, mts): - ''' Parse Modulation and Training Sequence info. ''' - - # IDLE / nope indication has no MTS info - self.nope_ind = (mts & self.NOPE_IND) > 0 - if self.nope_ind: - self.mod_type = None - self.tsc_set = None - self.tsc = None - return - - # TSC: . . . . . X X X - self.tsc = mts & 0b111 - - # MTS: . X X X X . . . - mts = (mts >> 3) & 0b1111 - if (mts & 0b1100) > 0: - # Mask: . . . . M M M S - self.mod_type = Modulation.pick(mts & 0b1110) - self.tsc_set = mts & 0b1 - else: - # GMSK: . . . . 0 0 S S - self.mod_type = Modulation.ModGMSK - self.tsc_set = mts & 0b11 - - def append_hdr_to(self, buf): - ''' Generate message specific header by appending it to buf. ''' - - # Put RSSI - buf.append(-self.rssi) - - # Encode ToA (Time of Arrival) - # Big endian, 2 bytes (int32_t) - buf += struct.pack(">h", self.toa256) - - if self.ver >= 0x01: - # Modulation and Training Sequence info - mts = self.gen_mts() - buf.append(mts) - - # C/I: Carrier-to-Interference ratio (in centiBels) - buf += struct.pack(">h", self.ci) - - def parse_hdr(self, hdr): - ''' Parse message specific header part. ''' - - # Parse RSSI - self.rssi = -(hdr[5]) - - # Parse ToA (Time of Arrival) - self.toa256 = struct.unpack(">h", hdr[6:8])[0] - - if self.ver >= 0x01: - # Modulation and Training Sequence info - self.parse_mts(hdr[8]) - - # C/I: Carrier-to-Interference ratio (in centiBels) - self.ci = struct.unpack(">h", hdr[9:11])[0] - - def append_burst_to(self, buf): - ''' Generate message specific burst appending it to buf. ''' - - # Convert soft-bits to unsigned soft-bits - buf.extend( self.sbit2usbit(self.burst) ) # XXX copies; can probably remove them with numpy - - def _parse_burst_v0(self, burst): - ''' Parse message specific burst for header version 0. ''' - - bl = len(burst) - - # We need to guess modulation by the length of burst - self.mod_type = Modulation.pick_by_bl(bl) - if self.mod_type is None: - # Some old transceivers append two dummy bytes - self.mod_type = Modulation.pick_by_bl(bl - 2) - - if self.mod_type is None: - raise ValueError("Odd burst length %u" % bl) - - return burst[:self.mod_type.bl] - - def parse_burst(self, burst): - ''' Parse message specific burst. ''' - - burst = array('B', burst) - - if self.ver == 0x00: - burst = self._parse_burst_v0(burst) - - # Convert unsigned soft-bits to soft-bits - self.burst = self.usbit2sbit(burst) - - def rand_burst(self, length = None): - ''' Generate a random message specific burst. ''' - - if length is None: - length = self.mod_type.bl - - self.burst = array('b', [random.randint(-127, 127) for _ in range(length)]) - - def trans(self, ver = None): - ''' Transform this message to TxMsg. ''' - - # Allocate a new message - msg = TxMsg(fn = self.fn, tn = self.tn, - ver = self.ver if ver is None else ver) - - # Convert burst bits - if self.burst is not None: - msg.burst = self.sbit2ubit(self.burst) - - return msg diff --git a/src/target/trx_toolkit/fake_pm.py b/src/target/trx_toolkit/fake_pm.py deleted file mode 100644 index 205596a..0000000 --- a/src/target/trx_toolkit/fake_pm.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Power measurement emulation -# -# (C) 2017-2018 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -from random import randint - -class FakePM: - """ Power measurement emulation for fake transceivers. - - There is no such thing like RF signal level in fake Um-interface, - so we need to emulate this. The main idea is to have a list of - all running and idle transceivers. As soon as a measurement - request is received, FakePM will attempt to find a running - transceiver on a given frequency. - - The result of such "measurement" is a random RSSI value - in one of the following ranges: - - - trx_min ... trx_max - if at least one TRX was found, - - noise_min ... noise_max - no TRX instances were found. - - FIXME: it would be great to average the rate of bursts - and indicated power / attenuation values for all - matching transceivers, so "pure traffic" ARFCNs - would be handled properly. - - """ - - def __init__(self, noise_min, noise_max, trx_min, trx_max): - # Init list of transceivers - self.trx_list = [] - - # RSSI randomization ranges - self.noise_min = noise_min - self.noise_max = noise_max - self.trx_min = trx_min - self.trx_max = trx_max - - @property - def rssi_noise(self): - return randint(self.noise_min, self.noise_max) - - @property - def rssi_trx(self): - return randint(self.trx_min, self.trx_max) - - def measure(self, freq, fn = None): - # Iterate over all known transceivers - for trx in self.trx_list: - if not trx.running: - continue - - # FIXME: we need to know current TDMA frame number here, - # because some transceivers may use frequency hopping - if trx.fh is not None and fn is None: - continue - - # Match by given frequency - if trx.get_tx_freq(fn) == freq: - return self.rssi_trx - - return self.rssi_noise diff --git a/src/target/trx_toolkit/fake_trx.py b/src/target/trx_toolkit/fake_trx.py deleted file mode 100755 index ebb8c23..0000000 --- a/src/target/trx_toolkit/fake_trx.py +++ /dev/null @@ -1,572 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Virtual Um-interface (fake transceiver) -# -# (C) 2017-2019 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -APP_CR_HOLDERS = [("2017-2019", "Vadim Yanitskiy <axilirator(a)gmail.com>")] - -import logging as log -import signal -import argparse -import random -import select -import sys -import re -import os - -from app_common import ApplicationBase -from burst_fwd import BurstForwarder -from transceiver import Transceiver -from data_msg import Modulation -from clck_gen import CLCKGen -from trx_list import TRXList -from fake_pm import FakePM -from gsm_shared import * - -class FakeTRX(Transceiver): - """ Fake transceiver with RF path (burst loss, RSSI, TA, ToA) simulation. - - == ToA / RSSI measurement simulation - - Since this is a virtual environment, we can simulate different - parameters of the physical RF interface: - - - ToA (Timing of Arrival) - measured difference between expected - and actual time of burst arrival in units of 1/256 of GSM symbol - periods. A pair of both base and threshold values defines a range - of ToA value randomization: - - from (toa256_base - toa256_rand_threshold) - to (toa256_base + toa256_rand_threshold). - - - RSSI (Received Signal Strength Indication) - measured "power" of - the signal (per burst) in dBm. A pair of both base and threshold - values defines a range of RSSI value randomization: - - from (rssi_base - rssi_rand_threshold) - to (rssi_base + rssi_rand_threshold). - - - C/I (Carrier-to-Interference ratio) - value in cB (centiBels), - computed from the training sequence of each received burst, by - comparing the "ideal" training sequence with the actual one. - A pair of both base and threshold values defines a range of - C/I randomization: - - from (ci_base - ci_rand_threshold) - to (ci_base + ci_rand_threshold). - - Please note that the randomization is optional and disabled by default. - - == Timing Advance handling - - The BTS is using ToA measurements for UL bursts in order to calculate - Timing Advance value, that is then indicated to a MS, which in its turn - shall apply this value to the transmitted signal in order to compensate - the delay. Basically, every burst is transmitted in advance defined by - the indicated Timing Advance value. The valid range is 0..63, where - each unit means one GSM symbol advance. The actual Timing Advance value - is set using SETTA control command from MS. By default, it's set to 0. - - == Path loss simulation - - === Burst dropping - - In some cases, e.g. due to a weak signal or high interference, a burst - can be lost, i.e. not detected by the receiver. This can also be - simulated using FAKE_DROP command on the control interface: - - - burst_drop_amount - the amount of DL/UL bursts - to be dropped (i.e. not forwarded towards the MS/BTS), - - - burst_drop_period - drop a DL/UL burst if its (fn % period) == 0. - - == Configuration - - All simulation parameters mentioned above can be changed at runtime - using the commands with prefix 'FAKE_' on the control interface. - All of them are handled by our custom CTRL command handler. - - """ - - NOMINAL_TX_POWER_DEFAULT = 50 # dBm - TX_ATT_DEFAULT = 0 # dB - PATH_LOSS_DEFAULT = 110 # dB - - TOA256_BASE_DEFAULT = 0 - CI_BASE_DEFAULT = 90 - - # Default values for NOPE / IDLE indications - TOA256_NOISE_DEFAULT = 0 - RSSI_NOISE_DEFAULT = -110 - CI_NOISE_DEFAULT = -30 - - def __init__(self, *trx_args, **trx_kwargs): - super().__init__(*trx_args, **trx_kwargs) - self.reset_params() - - def reset_params(self): - """ Reset/initialize all parameters """ - super().reset_params() - - # fake RSSI is disabled by default, only enabled through TRXC FAKE_RSSI. - # When disabled, RSSI is calculated based on Tx power and Rx path loss - self.fake_rssi_enabled = False - - self.rf_muted = False - - # Actual ToA, RSSI, C/I, TA values - self.tx_power_base = self.NOMINAL_TX_POWER_DEFAULT - self.tx_att_base = self.TX_ATT_DEFAULT - self.toa256_base = self.TOA256_BASE_DEFAULT - self.rssi_base = self.NOMINAL_TX_POWER_DEFAULT - self.TX_ATT_DEFAULT - self.PATH_LOSS_DEFAULT - self.ci_base = self.CI_BASE_DEFAULT - self.ta = 0 - - # ToA, RSSI, C/I randomization thresholds - self.toa256_rand_threshold = 0 - self.rssi_rand_threshold = 0 - self.ci_rand_threshold = 0 - - # Path loss simulation (burst dropping) - self.burst_drop_amount = 0 - self.burst_drop_period = 1 - - @property - def toa256(self): - # Check if randomization is required - if self.toa256_rand_threshold == 0: - return self.toa256_base - - # Generate a random ToA value in required range - toa256_min = self.toa256_base - self.toa256_rand_threshold - toa256_max = self.toa256_base + self.toa256_rand_threshold - return random.randint(toa256_min, toa256_max) - - @property - def rssi(self): - # Check if randomization is required - if self.rssi_rand_threshold == 0: - return self.rssi_base - - # Generate a random RSSI value in required range - rssi_min = self.rssi_base - self.rssi_rand_threshold - rssi_max = self.rssi_base + self.rssi_rand_threshold - return random.randint(rssi_min, rssi_max) - - @property - def tx_power(self): - return self.tx_power_base - self.tx_att_base - - @property - def ci(self): - # Check if randomization is required - if self.ci_rand_threshold == 0: - return self.ci_base - - # Generate a random C/I value in required range - ci_min = self.ci_base - self.ci_rand_threshold - ci_max = self.ci_base + self.ci_rand_threshold - return random.randint(ci_min, ci_max) - - # Path loss simulation: burst dropping - # Returns: True - drop, False - keep - def sim_burst_drop(self, msg): - # Check if dropping is required - if self.burst_drop_amount == 0: - return False - - if msg.fn % self.burst_drop_period == 0: - log.info("(%s) Simulation: dropping burst (fn=%u %% %u == 0)" - % (self, msg.fn, self.burst_drop_period)) - self.burst_drop_amount -= 1 - return True - - return False - - def _handle_data_msg_v1(self, src_msg, msg): - # C/I (Carrier-to-Interference ratio) - msg.ci = self.ci - - # Pick modulation type by burst length - bl = len(src_msg.burst) - msg.mod_type = Modulation.pick_by_bl(bl) - - # Pick TSC (Training Sequence Code) and TSC set - if msg.mod_type is Modulation.ModGMSK: - ss = TrainingSeqGMSK.pick(src_msg.burst) - msg.tsc = ss.tsc if ss is not None else 0 - msg.tsc_set = ss.tsc_set if ss is not None else 0 - else: # TODO: other modulation types (at least 8-PSK) - msg.tsc_set = 0 - msg.tsc = 0 - - # Takes (partially initialized) TRXD Rx message, - # simulates RF path parameters (such as RSSI), - # and sends towards the L1 - def handle_data_msg(self, src_trx, src_msg, msg): - if self.rf_muted: - msg.nope_ind = True - elif not msg.nope_ind: - # Path loss simulation - msg.nope_ind = self.sim_burst_drop(msg) - if msg.nope_ind: - # Before TRXDv1, we simply drop the message - if msg.ver < 0x01: - del msg - return - - # Since TRXDv1, we should send a NOPE.ind - msg.burst = None # burst bits are omited - - # TODO: shoud we make these values configurable? - msg.toa256 = self.TOA256_NOISE_DEFAULT - msg.rssi = self.RSSI_NOISE_DEFAULT - msg.ci = self.CI_NOISE_DEFAULT - - self.data_if.send_msg(msg) - return - - # Complete message header - msg.toa256 = self.toa256 - - # Apply RSSI based on transmitter: - if not self.fake_rssi_enabled: - msg.rssi = src_trx.tx_power - src_msg.pwr - self.PATH_LOSS_DEFAULT - else: # Apply fake RSSI - msg.rssi = self.rssi - - # Version specific fields - if msg.ver >= 0x01: - self._handle_data_msg_v1(src_msg, msg) - - # Apply optional Timing Advance - if src_trx.ta != 0: - msg.toa256 -= src_trx.ta * 256 - - Transceiver.handle_data_msg(self, msg) - - # Simulation specific CTRL command handler - def ctrl_cmd_handler(self, request): - # Timing Advance - # Syntax: CMD SETTA <TA> - if self.ctrl_if.verify_cmd(request, "SETTA", 1): - log.debug("(%s) Recv SETTA cmd" % self) - - # Store indicated value - self.ta = int(request[1]) - return 0 - - # Timing of Arrival simulation - # Absolute form: CMD FAKE_TOA <BASE> <THRESH> - elif self.ctrl_if.verify_cmd(request, "FAKE_TOA", 2): - log.debug("(%s) Recv FAKE_TOA cmd" % self) - - # Parse and apply both base and threshold - self.toa256_base = int(request[1]) - self.toa256_rand_threshold = int(request[2]) - return 0 - - # Timing of Arrival simulation - # Relative form: CMD FAKE_TOA <+-BASE_DELTA> - elif self.ctrl_if.verify_cmd(request, "FAKE_TOA", 1): - log.debug("(%s) Recv FAKE_TOA cmd" % self) - - # Parse and apply delta - self.toa256_base += int(request[1]) - return 0 - - # RSSI simulation - # Absolute form: CMD FAKE_RSSI <BASE> <THRESH> - elif self.ctrl_if.verify_cmd(request, "FAKE_RSSI", 2): - log.debug("(%s) Recv FAKE_RSSI cmd" % self) - - # Use negative threshold to disable fake_rssi if previously enabled: - if int(request[2]) < 0: - self.fake_rssi_enabled = False - return 0 - - # Parse and apply both base and threshold - self.rssi_base = int(request[1]) - self.rssi_rand_threshold = int(request[2]) - self.fake_rssi_enabled = True - return 0 - - # RSSI simulation - # Relative form: CMD FAKE_RSSI <+-BASE_DELTA> - elif self.ctrl_if.verify_cmd(request, "FAKE_RSSI", 1): - log.debug("(%s) Recv FAKE_RSSI cmd" % self) - - # Parse and apply delta - self.rssi_base += int(request[1]) - return 0 - - # C/I simulation - # Absolute form: CMD FAKE_CI <BASE> <THRESH> - elif self.ctrl_if.verify_cmd(request, "FAKE_CI", 2): - log.debug("(%s) Recv FAKE_CI cmd" % self) - - # Parse and apply both base and threshold - self.ci_base = int(request[1]) - self.ci_rand_threshold = int(request[2]) - return 0 - - # C/I simulation - # Relative form: CMD FAKE_CI <+-BASE_DELTA> - elif self.ctrl_if.verify_cmd(request, "FAKE_CI", 1): - log.debug("(%s) Recv FAKE_CI cmd" % self) - - # Parse and apply delta - self.ci_base += int(request[1]) - return 0 - - # Path loss simulation: burst dropping - # Syntax: CMD FAKE_DROP <AMOUNT> - # Dropping pattern: fn % 1 == 0 - elif self.ctrl_if.verify_cmd(request, "FAKE_DROP", 1): - log.debug("(%s) Recv FAKE_DROP cmd" % self) - - # Parse / validate amount of bursts - num = int(request[1]) - if num < 0: - log.error("(%s) FAKE_DROP amount shall not " - "be negative" % self) - return -1 - - self.burst_drop_amount = num - self.burst_drop_period = 1 - return 0 - - # Path loss simulation: burst dropping - # Syntax: CMD FAKE_DROP <AMOUNT> <FN_PERIOD> - # Dropping pattern: fn % period == 0 - elif self.ctrl_if.verify_cmd(request, "FAKE_DROP", 2): - log.debug("(%s) Recv FAKE_DROP cmd" % self) - - # Parse / validate amount of bursts - num = int(request[1]) - if num < 0: - log.error("(%s) FAKE_DROP amount shall not " - "be negative" % self) - return -1 - - # Parse / validate period - period = int(request[2]) - if period <= 0: - log.error("(%s) FAKE_DROP period shall " - "be greater than zero" % self) - return -1 - - self.burst_drop_amount = num - self.burst_drop_period = period - return 0 - - # Artificial delay for the TRXC interface - # Syntax: CMD FAKE_TRXC_DELAY <DELAY_MS> - elif self.ctrl_if.verify_cmd(request, "FAKE_TRXC_DELAY", 1): - log.debug("(%s) Recv FAKE_TRXC_DELAY cmd", self) - - self.ctrl_if.rsp_delay_ms = int(request[1]) - log.info("(%s) Artificial TRXC delay set to %d", - self, self.ctrl_if.rsp_delay_ms) - - # Unhandled command - return None - -class Application(ApplicationBase): - def __init__(self): - self.app_print_copyright(APP_CR_HOLDERS) - self.argv = self.parse_argv() - - # Set up signal handlers - signal.signal(signal.SIGINT, self.sig_handler) - - # Configure logging - self.app_init_logging(self.argv) - - # List of all transceivers - self.trx_list = TRXList() - - # Init shared clock generator - self.clck_gen = CLCKGen([], sched_rr_prio = None if self.argv.sched_rr_prio is None else self.argv.sched_rr_prio + 1) - # This method will be called on each TDMA frame - self.clck_gen.clck_handler = self.clck_handler - - # Power measurement emulation - # Noise: -120 .. -105 - # BTS: -75 .. -50 - self.fake_pm = FakePM(-120, -105, -75, -50) - self.fake_pm.trx_list = self.trx_list - - # Init TRX instance for BTS - self.append_trx(self.argv.bts_addr, self.argv.bts_base_port, name = "BTS") - - # Init TRX instance for BB - self.append_trx(self.argv.bb_addr, self.argv.bb_base_port, name = "MS", child_mgt = False) - - # Additional transceivers (optional) - if self.argv.trx_list is not None: - for trx_def in self.argv.trx_list: - (name, addr, port, idx) = trx_def - self.append_child_trx(addr, port, name = name, child_idx = idx) - - # Burst forwarding between transceivers - self.burst_fwd = BurstForwarder(self.trx_list.trx_list) - - log.info("Init complete") - - def append_trx(self, remote_addr, base_port, **kwargs): - trx = FakeTRX(self.argv.trx_bind_addr, remote_addr, base_port, - clck_gen = self.clck_gen, pwr_meas = self.fake_pm, **kwargs) - self.trx_list.add_trx(trx) - - def append_child_trx(self, remote_addr, base_port, **kwargs): - child_idx = kwargs.get("child_idx", 0) - if child_idx == 0: # Index 0 indicates parent transceiver - self.append_trx(remote_addr, base_port, **kwargs) - return - - # Find 'parent' transceiver for a new child - trx_parent = self.trx_list.find_trx(remote_addr, base_port) - if trx_parent is None: - raise IndexError("Couldn't find parent transceiver " - "for '%s:%d/%d'" % (remote_addr, base_port, child_idx)) - - # Allocate a new child - trx_child = FakeTRX(self.argv.trx_bind_addr, remote_addr, base_port, - pwr_meas = self.fake_pm, **kwargs) - self.trx_list.add_trx(trx_child) - - # Link a new 'child' with its 'parent' - trx_parent.child_trx_list.add_trx(trx_child) - - def run(self): - if self.argv.sched_rr_prio is not None: - sched_param = os.sched_param(self.argv.sched_rr_prio) - try: - log.info("Setting real time process scheduler to SCHED_RR, priority %u" % (self.argv.sched_rr_prio)) - os.sched_setscheduler(0, os.SCHED_RR, sched_param) - except OSError: - log.error("Failed to set real time process scheduler to SCHED_RR, priority %u" % (self.argv.sched_rr_prio)) - - # Compose list of to be monitored sockets - sock_list = [] - for trx in self.trx_list.trx_list: - sock_list.append(trx.ctrl_if.sock) - sock_list.append(trx.data_if.sock) - - # Enter main loop - while True: - # Wait until we get any data on any socket - r_event, _, _ = select.select(sock_list, [], []) - - # Iterate over all transceivers - for trx in self.trx_list.trx_list: - # DATA interface - if trx.data_if.sock in r_event: - trx.recv_data_msg() - - # CTRL interface - if trx.ctrl_if.sock in r_event: - trx.ctrl_if.handle_rx() - - # This method will be called by the clock thread - def clck_handler(self, fn): - # We assume that this list is immutable at run-time - for trx in self.trx_list.trx_list: - trx.clck_tick(self.burst_fwd, fn) - - def shutdown(self): - log.info("Shutting down...") - - # Stop clock generator - self.clck_gen.stop() - - # Parses a TRX definition of the following - # format: REMOTE_ADDR:BIND_PORT[/TRX_NUM] - # e.g. [2001:0db8:85a3:0000:0000:8a2e:0370:7334]:5700/5 - # e.g. 127.0.0.1:5700 or 127.0.0.1:5700/1 - # e.g. foo@127.0.0.1:5700 or bar@127.0.0.1:5700/1 - @staticmethod - def trx_def(val): - try: - result = re.match(r"(.+@)?(.+):([0-9]+)(/[0-9]+)?", val) - (name, addr, port, idx) = result.groups() - except: - raise argparse.ArgumentTypeError("Invalid TRX definition: %s" % val) - - if idx is not None: - idx = int(idx[1:]) - else: - idx = 0 - - # Cut '@' from TRX name - if name is not None: - name = name[:-1] - - return (name, addr, int(port), idx) - - def parse_argv(self): - parser = argparse.ArgumentParser(prog = "fake_trx", - description = "Virtual Um-interface (fake transceiver)") - - # Register common logging options - self.app_reg_logging_options(parser) - - trx_group = parser.add_argument_group("TRX interface") - trx_group.add_argument("-b", "--trx-bind-addr", - dest = "trx_bind_addr", type = str, default = "0.0.0.0", - help = "Set FakeTRX bind address (default %(default)s)") - trx_group.add_argument("-R", "--bts-addr", - dest = "bts_addr", type = str, default = "127.0.0.1", - help = "Set BTS remote address (default %(default)s)") - trx_group.add_argument("-r", "--bb-addr", - dest = "bb_addr", type = str, default = "127.0.0.1", - help = "Set BB remote address (default %(default)s)") - trx_group.add_argument("-P", "--bts-base-port", - dest = "bts_base_port", type = int, default = 5700, - help = "Set BTS base port number (default %(default)s)") - trx_group.add_argument("-p", "--bb-base-port", - dest = "bb_base_port", type = int, default = 6700, - help = "Set BB base port number (default %(default)s)") - trx_group.add_argument("-s", "--sched-rr-prio", - dest = "sched_rr_prio", type = int, default = None, - help = "Set Scheduler RR Priority (default None)") - - mtrx_group = parser.add_argument_group("Additional transceivers") - mtrx_group.add_argument("--trx", - metavar = "REMOTE_ADDR:BASE_PORT[/TRX_NUM]", - dest = "trx_list", type = self.trx_def, action = "append", - help = "Add a transceiver for BTS or MS (e.g. 127.0.0.1:5703)") - - argv = parser.parse_args() - - # Make sure there is no overlap between ports - if argv.bts_base_port == argv.bb_base_port: - parser.error("BTS and BB base ports shall be different") - - return argv - - def sig_handler(self, signum, frame): - log.info("Signal %d received" % signum) - if signum == signal.SIGINT: - self.shutdown() - sys.exit(0) - -if __name__ == '__main__': - app = Application() - app.run() diff --git a/src/target/trx_toolkit/gsm_shared.py b/src/target/trx_toolkit/gsm_shared.py deleted file mode 100644 index 977d2aa..0000000 --- a/src/target/trx_toolkit/gsm_shared.py +++ /dev/null @@ -1,174 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Common GSM constants and helpers -# -# (C) 2018-2020 by Vadim Yanitskiy <axilirator(a)gmail.com> -# Contributions by sysmocom - s.f.m.c. GmbH -# -# 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 2 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. - -from enum import Enum - -# TDMA definitions -GSM_SUPERFRAME = 26 * 51 -GSM_HYPERFRAME = 2048 * GSM_SUPERFRAME - -# Burst length -GMSK_BURST_LEN = 148 -EDGE_BURST_LEN = GMSK_BURST_LEN * 3 - -class BurstType(Enum): - """ Burst types defined in 3GPP TS 45.002 """ - DUMMY = ("DB") # Dummy burst (5.2.6) - SYNC = ("SB") # Synchronization Burst (5.2.5) - FREQ = ("FB") # Frequency correction Burst (5.2.4) - ACCESS = ("AB") # Access Burst (5.2.7) - NORMAL = ("NB") # Normal Burst (5.2.3) - # HSR = ("HB") # Higher symbol rate burst (5.2.3a) - -class TrainingSeqGMSK(Enum): - """ Training Sequences defined in 3GPP TS 45.002 """ - - # Training Sequences for Access Burst (table 5.2.7-3) - AB_TS0 = (0, BurstType.ACCESS, "01001011011111111001100110101010001111000") - AB_TS1 = (1, BurstType.ACCESS, "01010100111110001000011000101111001001101") - AB_TS2 = (2, BurstType.ACCESS, "11101111001001110101011000001101101110111") - AB_TS4 = (4, BurstType.ACCESS, "11001001110001001110000000001101010110010") - - # Training Sequences for Access Burst (table 5.2.7-4) - AB_TS3 = (3, BurstType.ACCESS, "10001000111010111011010000010000101100010") - AB_TS5 = (5, BurstType.ACCESS, "01010000111111110101110101101100110010100") - AB_TS6 = (6, BurstType.ACCESS, "01011110011101011110110100010011000010111") - AB_TS7 = (7, BurstType.ACCESS, "01000010110000011101001010111011100010000") - - # Training Sequences for Synchronization Burst (table 5.2.5-3) - SB_TS0 = (0, BurstType.SYNC, "1011100101100010000001000000111100101101010001010111011000011011") - SB_TS1 = (1, BurstType.SYNC, "1110111001101011001010000011111011110100011111101100101100010101") - SB_TS2 = (2, BurstType.SYNC, "1110110000110111010100010101101001111000000100000010001101001110") - SB_TS3 = (3, BurstType.SYNC, "1011101000111101110101101111010010001011010000001000111010011000") - - # Training Sequences for Normal Burst (table 5.2.3a, TSC set 1) - NB_TS0 = (0, BurstType.NORMAL, "00100101110000100010010111") - NB_TS1 = (1, BurstType.NORMAL, "00101101110111100010110111") - NB_TS2 = (2, BurstType.NORMAL, "01000011101110100100001110") - NB_TS3 = (3, BurstType.NORMAL, "01000111101101000100011110") - NB_TS4 = (4, BurstType.NORMAL, "00011010111001000001101011") - NB_TS5 = (5, BurstType.NORMAL, "01001110101100000100111010") - NB_TS6 = (6, BurstType.NORMAL, "10100111110110001010011111") - NB_TS7 = (7, BurstType.NORMAL, "11101111000100101110111100") - - # TODO: more TSC sets from tables 5.2.3b-d - - def __init__(self, tsc, bt, seq_str, tsc_set = 0): - # Training Sequence Code - self.tsc = tsc - # Burst type - self.bt = bt - - # Training Sequence Code set - # NOTE: unlike the specs. we count from zero - self.tsc_set = tsc_set - - # Generate Training Sequence bits - self.seq = bytearray(int(x) for x in seq_str) - - @classmethod - def pick(self, burst): - # Normal burst TS (26 bits) - nb_seq = burst[3 + 57 + 1:][:26] - # Access burst TS (41 bits) - ab_seq = burst[8:][:41] - # Sync Burst TS (64 bits) - sb_seq = burst[3 + 39:][:64] - - for ts in list(self): - # Ugly Python way of writing 'switch' statement - if ts.bt is BurstType.NORMAL and ts.seq == nb_seq: - return ts - elif ts.bt is BurstType.ACCESS and ts.seq == ab_seq: - return ts - elif ts.bt is BurstType.SYNC and ts.seq == sb_seq: - return ts - - return None - -class HoppingParams: - """ Hopping sequence generation as per 3GPP TS 45.002, section 6.2.3. - - Based on firmware/layer1/rfch.c:rfch_hop_seq_gen() by Sylvain Munaut. - - """ - - # Magic numbers for pseudo-random hopping sequence generation - RNTABLE = [ - 48, 98, 63, 1, 36, 95, 78, 102, 94, 73, - 0, 64, 25, 81, 76, 59, 124, 23, 104, 100, - 101, 47, 118, 85, 18, 56, 96, 86, 54, 2, - 80, 34, 127, 13, 6, 89, 57, 103, 12, 74, - 55, 111, 75, 38, 109, 71, 112, 29, 11, 88, - 87, 19, 3, 68, 110, 26, 33, 31, 8, 45, - 82, 58, 40, 107, 32, 5, 106, 92, 62, 67, - 77, 108, 122, 37, 60, 66, 121, 42, 51, 126, - 117, 114, 4, 90, 43, 52, 53, 113, 120, 72, - 16, 49, 7, 79, 119, 61, 22, 84, 9, 97, - 91, 15, 21, 24, 46, 39, 93, 105, 65, 70, - 125, 99, 17, 123, - ] - - def __init__(self, hsn, maio, ma): - # Make sure MA is not empty - ma_len = len(ma) - if ma_len == 0: # TODO: or rather > 1? - raise ValueError("Mobile Allocation is empty") - - self.hsn = hsn - self.maio = maio - self.ma = ma - - # Pre-calculate 2 ** NBIN in advance - self._pnm = (ma_len >> 0) | (ma_len >> 1) \ - | (ma_len >> 2) | (ma_len >> 3) \ - | (ma_len >> 4) | (ma_len >> 5) \ - | (ma_len >> 6) - - def __str__(self): - fmt = "hsn=%u, maio=%u, ma_len=%u" - return fmt % (self.hsn, self.maio, len(self.ma)) - - @staticmethod - def fn2gsm_time(fn): - t1 = fn // (26 * 51) - t2 = fn % 26 - t3 = fn % 51 - tc = (fn // 51) % 8 - return (t1, t2, t3, tc) - - # Resolve current ARFCN using the given TDMA frame number - def resolve(self, fn): - # Cyclic hopping - if self.hsn == 0: - mai = (fn + self.maio) % len(self.ma) - return self.ma[mai] - - # Pseudo random hopping - (t1, t2, t3, tc) = self.fn2gsm_time(fn) - ma_len = len(self.ma) - - rn_idx = (self.hsn ^ (t1 & 63)) + t3 - m = t2 + self.RNTABLE[rn_idx] - mp = m & self._pnm - - s = mp if mp < ma_len else (mp + t3 & self._pnm) % ma_len - mai = (s + self.maio) % ma_len - return self.ma[mai] diff --git a/src/target/trx_toolkit/rand_burst_gen.py b/src/target/trx_toolkit/rand_burst_gen.py deleted file mode 100644 index 6cdab30..0000000 --- a/src/target/trx_toolkit/rand_burst_gen.py +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Random burst (NB, FB, SB, AB) generator -# -# (C) 2017 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -import random - -from gsm_shared import * - -class RandBurstGen: - - # GSM 05.02 Chapter 5.2.6 Dummy Burst - db_bits = bytearray([ - 0, 0, 0, - 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, - 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, - 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, - 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, - 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, - 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, - 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, - 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, - 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, - 0, 0, 0, - ]) - - # Pick a random TSC for a given burst type - def get_rand_tsc(self, bt): - tsc_list = filter(lambda seq: seq.bt == bt, list(TrainingSeqGMSK)) - tsc_list = list(tsc_list) # In Python 3 filter() returns an iterator - return random.choice(tsc_list) - - # Generate a normal burst - def gen_nb(self, tsc = None): - buf = [] - - # Tailing bits - buf += [0] * 3 - - # Random data 1 / 2 - buf += [random.randint(0, 1) for _ in range(57)] - - # Steal flag 1 / 2 - buf.append(random.randint(0, 1)) - - # Training sequence - if tsc is None: - tsc = self.get_rand_tsc(BurstType.NORMAL) - buf += tsc.seq - - # Steal flag 2 / 2 - buf.append(random.randint(0, 1)) - - # Random data 2 / 2 - buf += [random.randint(0, 1) for _ in range(57)] - - # Tailing bits - buf += [0] * 3 - - return bytearray(buf) - - # Generate a frequency correction burst - def gen_fb(self): - return bytearray([0] * GMSK_BURST_LEN) - - # Generate a synchronization burst - def gen_sb(self, tsc = None): - buf = [] - - # Tailing bits - buf += [0] * 3 - - # Random data 1 / 2 - buf += [random.randint(0, 1) for _ in range(39)] - - # Training sequence - if tsc is None: - tsc = self.get_rand_tsc(BurstType.SYNC) - buf += tsc.seq - - # Random data 2 / 2 - buf += [random.randint(0, 1) for _ in range(39)] - - # Tailing bits - buf += [0] * 3 - - return bytearray(buf) - - # Generate a dummy burst - def gen_db(self): - return self.db_bits - - # Generate an access burst - def gen_ab(self, tsc = None): - buf = [] - - # Tailing bits - buf += [0] * 8 - - # Training sequence - if tsc is None: - tsc = self.get_rand_tsc(BurstType.ACCESS) - buf += tsc.seq - - # Random data - buf += [random.randint(0, 1) for _ in range(36)] - - # Tailing bits - buf += [0] * 3 - - # Guard period - buf += [0] * 60 - - return bytearray(buf) diff --git a/src/target/trx_toolkit/test_clck_gen.py b/src/target/trx_toolkit/test_clck_gen.py deleted file mode 100644 index 92e5e55..0000000 --- a/src/target/trx_toolkit/test_clck_gen.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Unit test for CLCKGen -# -# 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 2 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. - -import threading -import time -import unittest - -import clck_gen - - -class CLCKGen_Test(unittest.TestCase): - - # verify that timing error is not accumulated in the clock gen loop - def test_no_timing_error_accumulated(self): - # observe many ticks with spending some noticeable time in clock handler each tick - # assert that t(last) - t(first) ≈ ntick·dt(tick) - # this will break if the clock generator is not careful to prevent timing error from accumulating - clck = clck_gen.CLCKGen([]) - ntick = 200 # ~ 1 s - tick = 0 - tstart = tend = None - done = threading.Event() - - def _(fn): - nonlocal tick, tstart, tend - if tick == 0: - tstart = time.monotonic() - if tick == ntick: - tend = time.monotonic() - done.set() - tick += 1 - time.sleep(clck.ctr_interval / 2) - clck.clck_handler = _ - - clck.start() - try: - ok = done.wait(10) - self.assertTrue(ok, "clck_gen stuck") - - self.assertIsNotNone(tstart) - self.assertIsNotNone(tend) - dT = tend - tstart - dTok = ntick * clck.ctr_interval - dTerr = dT - dTok - self.assertTrue((ntick-1)*clck.ctr_interval < dT, "tick #%d: time underrun by %dus total" % - (ntick, dTerr // 1e-6)) - self.assertTrue((ntick+1)*clck.ctr_interval > dT, "tick #%d: time overrun by %dus total" % - (ntick, dTerr // 1e-6)) - - finally: - clck.stop() - - # verify that default tick interval is 1 TDMA frame exactly - def test_period_is_gsm_frame(self): - clck = clck_gen.CLCKGen([]) - self.assertEqual(clck.ctr_interval, 4.615e-3) - - -if __name__ == '__main__': - unittest.main() diff --git a/src/target/trx_toolkit/test_codec.py b/src/target/trx_toolkit/test_codec.py deleted file mode 100644 index 5049f52..0000000 --- a/src/target/trx_toolkit/test_codec.py +++ /dev/null @@ -1,592 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -''' -Unit tests for declarative message codec. -''' - -# (C) 2021 by sysmocom - s.f.m.c. GmbH <info(a)sysmocom.de> -# Author: Vadim Yanitskiy <vyanitskiy(a)sysmocom.de> -# -# 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 2 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. - -import unittest -import struct -import codec - -class TestField(codec.Field): - DEF_PARAMS = { 'key' : 0xde } - DEF_LEN = 4 - - @staticmethod - def xor(data: bytes, key: int = 0x00): - return bytes([x ^ key for x in data]) - - def _from_bytes(self, vals: dict, data: bytes) -> None: - vals[self.name] = self.xor(data, self.p['key']) - - def _to_bytes(self, vals: dict) -> bytes: - return self.xor(self.get_val(vals), self.p['key']) - -class Field(unittest.TestCase): - MAGIC = b'\xde\xad\xbe\xef' - - def test_to_bytes(self): - vals = { 'magic' : self.MAGIC, 'other' : 'unrelated' } - encoded_de = TestField.xor(self.MAGIC, 0xde) - encoded_88 = TestField.xor(self.MAGIC, 0x88) - - with self.subTest('default length=4, default key=0xde'): - field = TestField('magic') - self.assertEqual(field.to_bytes(vals), encoded_de) - - with self.subTest('default length=4, different key=0x88'): - field = TestField('magic', key=0x88) - self.assertEqual(field.to_bytes(vals), encoded_88) - - with self.subTest('different length=2, default key=0xde'): - field = TestField('magic', len=2) - vals['magic'] = vals['magic'][:2] - self.assertEqual(field.to_bytes(vals), encoded_de[:2]) - - with self.subTest('EncodeError due to length mismatch'): - field = TestField('magic', len=8) - with self.assertRaises(codec.EncodeError): - field.to_bytes(vals) - - def test_from_bytes(self): - encoded_de = TestField.xor(self.MAGIC, 0xde) + b'\xff' * 60 - encoded_88 = TestField.xor(self.MAGIC, 0x88) + b'\xff' * 60 - vals = { 'magic' : 'overrien', 'other' : 'unchanged' } - - with self.subTest('default length=4, default key=0xde'): - field = TestField('magic') - offset = field.from_bytes(vals, encoded_de) - self.assertEqual(vals['other'], 'unchanged') - self.assertEqual(vals['magic'], self.MAGIC) - self.assertEqual(offset, len(self.MAGIC)) - - with self.subTest('default length=4, different key=0x88'): - field = TestField('magic', key=0x88) - offset = field.from_bytes(vals, encoded_88) - self.assertEqual(vals['other'], 'unchanged') - self.assertEqual(vals['magic'], self.MAGIC) - self.assertEqual(offset, len(self.MAGIC)) - - with self.subTest('different length=2, default key=0xde'): - field = TestField('magic', len=2) - offset = field.from_bytes(vals, encoded_de) - self.assertEqual(vals['other'], 'unchanged') - self.assertEqual(vals['magic'], self.MAGIC[:2]) - self.assertEqual(offset, 2) - - with self.subTest('full length, different key=0x88'): - field = TestField('magic', len=0, key=0x88) - offset = field.from_bytes(vals, encoded_88) - self.assertEqual(vals['other'], 'unchanged') - self.assertEqual(vals['magic'], self.MAGIC + b'\x77' * 60) - self.assertEqual(offset, len(encoded_88)) - - with self.subTest('DecodeError due to short read'): - field = TestField('magic', len=4) - with self.assertRaises(codec.DecodeError): - field.from_bytes(vals, b'\x00') - - def test_get_pres(self): - vals = { 'magic' : self.MAGIC } - - with self.subTest('to_bytes() for a non-existing field'): - field = TestField('not-there') - with self.assertRaises(KeyError): - field.to_bytes(vals) - - with self.subTest('to_bytes() for a field with get_pres()'): - field = TestField('magic', key=0x00) - field.get_pres = lambda v: not v['omit'] - - data = field.to_bytes({ **vals, 'omit' : False }) - self.assertEqual(data, self.MAGIC) - - data = field.to_bytes({ **vals, 'omit' : True }) - self.assertEqual(data, b'') - - with self.subTest('from_bytes() for a field with get_pres()'): - field = TestField('magic', key=0x00) - field.get_pres = lambda v: not v['omit'] - - vals = { 'omit' : False } - offset = field.from_bytes(vals, self.MAGIC) - self.assertEqual(vals['magic'], self.MAGIC) - self.assertEqual(offset, len(self.MAGIC)) - - vals = { 'omit' : True } - offset = field.from_bytes(vals, self.MAGIC) - self.assertFalse('magic' in vals) - self.assertEqual(offset, 0) - - def test_get_len(self): - vals = { 'len' : 32, 'unrelated' : 'foo' } - - field = TestField('magic', key=0x00) - field.get_len = lambda v, _: v['len'] - - with self.subTest('not enough octets in the buffer: 16 < 32'): - with self.assertRaises(codec.DecodeError): - field.from_bytes(vals, b'\xff' * 16) - - with self.subTest('more than enough octets in the buffer'): - offset = field.from_bytes(vals, b'\xff' * 64) - self.assertEqual(vals['magic'], b'\xff' * 32) - self.assertEqual(offset, 32) - - with self.subTest('length field does not exist'): - with self.assertRaises(KeyError): - field.from_bytes({ }, b'\xff' * 64) - - def test_get_val(self): - field = TestField('magic', key=0x00, len=0) - field.get_val = lambda v: v.get('val', self.MAGIC) - - with self.subTest('value is present in the dict'): - data = field.to_bytes({ 'val' : b'\xd0\xde' }) - self.assertEqual(data, b'\xd0\xde') - - with self.subTest('value is not present in the dict'): - data = field.to_bytes({ }) - self.assertEqual(data, self.MAGIC) - -class Buf(unittest.TestCase): - MAGIC = b'\xde\xad' * 4 - - def test_to_bytes(self): - vals = { 'buf' : self.MAGIC } - - with self.subTest('with no length constraints'): - field = codec.Buf('buf') # default: len=0 - self.assertEqual(field.to_bytes(vals), self.MAGIC) - - with self.subTest('with length constraints'): - field = codec.Buf('buf', len=len(self.MAGIC)) - self.assertEqual(field.to_bytes(vals), self.MAGIC) - - with self.subTest('EncodeError due to length mismatch'): - field = codec.Buf('buf', len=4) - with self.assertRaises(codec.EncodeError): - field.to_bytes(vals) - - def test_from_bytes(self): - vals = { } - - with self.subTest('with no length constraints'): - field = codec.Buf('buf') # default: len=0 - offset = field.from_bytes(vals, self.MAGIC) - self.assertEqual(vals['buf'], self.MAGIC) - self.assertEqual(offset, len(self.MAGIC)) - - with self.subTest('with length constraints'): - field = codec.Buf('buf', len=2) - offset = field.from_bytes(vals, self.MAGIC) - self.assertEqual(vals['buf'], self.MAGIC[:2]) - self.assertEqual(offset, len(self.MAGIC[:2])) - - with self.subTest('DecodeError due to not enough bytes'): - field = codec.Buf('buf', len=64) - with self.assertRaises(codec.DecodeError): - field.from_bytes(vals, self.MAGIC) - -class Spare(unittest.TestCase): - # Fixed length with custom filler - SAA = codec.Spare('pad', len=4, filler=b'\xaa') - # Auto-calculated length with custom filler - SFF = codec.Spare('pad', filler=b'\xff') - SFF.get_len = lambda v, _: v['len'] - # Fixed length with default filler - S00 = codec.Spare('pad', len=2) - - def test_to_bytes(self): - self.assertEqual(self.SFF.to_bytes({ 'len' : 8 }), b'\xff' * 8) - self.assertEqual(self.SAA.to_bytes({ }), b'\xaa' * 4) - self.assertEqual(self.S00.to_bytes({ }), b'\x00' * 2) - - def test_from_bytes(self): - with self.assertRaises(codec.DecodeError): - self.S00.from_bytes({ }, b'\x00') # Short read - self.assertEqual(self.SFF.from_bytes({ 'len' : 8 }, b'\xff' * 8), 8) - self.assertEqual(self.SAA.from_bytes({ }, b'\xaa' * 64), 4) - self.assertEqual(self.S00.from_bytes({ }, b'\x00' * 64), 2) - -class Uint(unittest.TestCase): - def _test_uint(self, field, fmt, vals): - for i in vals: - with self.subTest('to_bytes()'): - val = field.to_bytes({ field.name : i }) - self.assertEqual(val, struct.pack(fmt, i)) - - with self.subTest('from_bytes()'): - data, parsed = struct.pack(fmt, i), { } - offset = field.from_bytes(parsed, data) - self.assertEqual(offset, len(data)) - self.assertEqual(parsed[field.name], i) - - def test_uint8(self): - self._test_uint(codec.Uint('foo'), 'B', range(2 ** 8)) - - def test_int8(self): - self._test_uint(codec.Int('foo'), 'b', range(-128, 128)) - - def test_uint16(self): - vals = (0, 65, 128, 255, 512, 1023, 2 ** 16 - 1) - self._test_uint(codec.Uint16BE('foo'), '>H', vals) - self._test_uint(codec.Uint16LE('foo'), '<H', vals) - - def test_int16(self): - vals = (-32767, -16384, 0, 16384, 32767) - self._test_uint(codec.Int16BE('foo'), '>h', vals) - self._test_uint(codec.Int16LE('foo'), '<h', vals) - - def test_uint32(self): - vals = (0, 33, 255, 1024, 1337, 4099, 2 ** 32 - 1) - self._test_uint(codec.Uint32BE('foo'), '>I', vals) - self._test_uint(codec.Uint32LE('foo'), '<I', vals) - - def test_int32(self): - vals = (-2147483647, 0, 2147483647) - self._test_uint(codec.Int32BE('foo'), '>i', vals) - self._test_uint(codec.Int32LE('foo'), '<i', vals) - - def test_offset_mult(self): - with self.subTest('encode / decode with offset=5'): - field = codec.Uint('foo', offset=5) - - self.assertEqual(field.to_bytes({ 'foo' : 10 }), b'\x05') - self.assertEqual(field.to_bytes({ 'foo' : 5 }), b'\x00') - - vals = { 'foo' : 'overriden' } - field.from_bytes(vals, b'\xff') - self.assertEqual(vals['foo'], 260) - field.from_bytes(vals, b'\x00') - self.assertEqual(vals['foo'], 5) - - with self.subTest('encode / decode with mult=2'): - field = codec.Uint('foo', mult=2) - - self.assertEqual(field.to_bytes({ 'foo' : 0 }), b'\x00') - self.assertEqual(field.to_bytes({ 'foo' : 3 }), b'\x01') - self.assertEqual(field.to_bytes({ 'foo' : 32 }), b'\x10') - self.assertEqual(field.to_bytes({ 'foo' : 64 }), b'\x20') - - vals = { 'foo' : 'overriden' } - field.from_bytes(vals, b'\x00') - self.assertEqual(vals['foo'], 0 * 2) - field.from_bytes(vals, b'\x0f') - self.assertEqual(vals['foo'], 15 * 2) - field.from_bytes(vals, b'\xff') - self.assertEqual(vals['foo'], 255 * 2) - -class BitFieldSet(unittest.TestCase): - S16 = codec.BitFieldSet(set=( - codec.BitField('f4a', bl=4), - codec.BitField('f8', bl=8), - codec.BitField('f4b', bl=4), - )) - - S8M = codec.BitFieldSet(order='msb', set=( - codec.BitField('f4', bl=4), - codec.BitField('f1', bl=1), - codec.BitField('f3', bl=3), - )) - - S8L = codec.BitFieldSet(order='lsb', set=( - codec.BitField('f4', bl=4), - codec.BitField('f1', bl=1), - codec.BitField('f3', bl=3), - )) - - S8V = codec.BitFieldSet(set=( - codec.BitField('f4', bl=4, val=2), - codec.BitField('f1', bl=1, val=0), - codec.BitField('f3', bl=3), - )) - - S8P = codec.BitFieldSet(set=( - codec.BitField.Spare(bl=4), - codec.BitField('f4', bl=4), - )) - - @staticmethod - def from_bytes(s: codec.BitFieldSet, data: bytes) -> dict: - vals = { } - s.from_bytes(vals, data) - return vals - - def test_len_auto(self): - with self.subTest('1 + 2 = 3 bits => 1 octet (with padding)'): - s = codec.BitFieldSet(set=( - codec.BitField('f1', bl=1), - codec.BitField('f2', bl=2), - )) - self.assertEqual(s.len, 1) - - with self.subTest('4 + 2 + 2 = 8 bits => 1 octet'): - s = codec.BitFieldSet(set=( - codec.BitField('f4', bl=4), - codec.BitField('f2a', bl=2), - codec.BitField('f2b', bl=2), - )) - self.assertEqual(s.len, 1) - - with self.subTest('12 + 4 + 2 = 18 bits => 3 octets (with padding)'): - s = codec.BitFieldSet(set=( - codec.BitField('f12', bl=12), - codec.BitField('f4', bl=4), - codec.BitField('f2', bl=2), - )) - self.assertEqual(s.len, 3) - - def test_overflow(self): - with self.assertRaises(codec.ProtocolError): - s = codec.BitFieldSet(len=1, set=( - codec.BitField('f6', bl=6), - codec.BitField('f4', bl=4), - )) - - def test_offset_mask(self): - calc = lambda s: [(f.name, f.offset, f.mask) for f in s._fields] - - with self.subTest('16 bit total (MSB): f4a + f8 + f4b'): - om = [('f4a', 8 + 4, 0x0f), ('f8', 4, 0xff), ('f4b', 0, 0x0f)] - self.assertEqual(len(self.S16._fields), 3) - self.assertEqual(calc(self.S16), om) - - with self.subTest('8 bit total (MSB): f4 + f1 + f3'): - om = [('f4', 1 + 3, 0x0f), ('f1', 3, 0x01), ('f3', 0, 0x07)] - self.assertEqual(len(self.S8M._fields), 3) - self.assertEqual(calc(self.S8M), om) - - with self.subTest('8 bit total (LSB): f4 + f1 + f3'): - om = [('f3', 1 + 4, 0x07), ('f1', 4, 0x01), ('f4', 0, 0x0f)] - self.assertEqual(len(self.S8L._fields), 3) - self.assertEqual(calc(self.S8L), om) - - with self.subTest('8 bit total (LSB): s4 + f4'): - om = [(None, 4, 0x0f), ('f4', 0, 0x0f)] - self.assertEqual(len(self.S8P._fields), 2) - self.assertEqual(calc(self.S8P), om) - - def test_to_bytes(self): - with self.subTest('16 bit total (MSB): f4a + f8 + f4b'): - vals = { 'f4a' : 0x0f, 'f8' : 0xff, 'f4b' : 0x0f } - self.assertEqual(self.S16.to_bytes(vals), b'\xff\xff') - vals = { 'f4a' : 0x00, 'f8' : 0x00, 'f4b' : 0x00 } - self.assertEqual(self.S16.to_bytes(vals), b'\x00\x00') - vals = { 'f4a' : 0x0f, 'f8' : 0x00, 'f4b' : 0x0f } - self.assertEqual(self.S16.to_bytes(vals), b'\xf0\x0f') - vals = { 'f4a' : 0x00, 'f8' : 0xff, 'f4b' : 0x00 } - self.assertEqual(self.S16.to_bytes(vals), b'\x0f\xf0') - - with self.subTest('8 bit total (MSB): f4 + f1 + f3'): - vals = { 'f4' : 0x0f, 'f1' : 0x01, 'f3' : 0x07 } - self.assertEqual(self.S8M.to_bytes(vals), b'\xff') - vals = { 'f4' : 0x00, 'f1' : 0x00, 'f3' : 0x00 } - self.assertEqual(self.S8M.to_bytes(vals), b'\x00') - vals = { 'f4' : 0x0f, 'f1' : 0x00, 'f3' : 0x00 } - self.assertEqual(self.S8M.to_bytes(vals), b'\xf0') - - with self.subTest('8 bit total (LSB): f4 + f1 + f3'): - vals = { 'f4' : 0x0f, 'f1' : 0x01, 'f3' : 0x07 } - self.assertEqual(self.S8L.to_bytes(vals), b'\xff') - vals = { 'f4' : 0x00, 'f1' : 0x00, 'f3' : 0x00 } - self.assertEqual(self.S8L.to_bytes(vals), b'\x00') - vals = { 'f4' : 0x0f, 'f1' : 0x00, 'f3' : 0x00 } - self.assertEqual(self.S8L.to_bytes(vals), b'\x0f') - - def test_from_bytes(self): - pad = b'\xff' * 64 - - with self.subTest('16 bit total (MSB): f4a + f8 + f4b'): - vals = { 'f4a' : 0x0f, 'f8' : 0xff, 'f4b' : 0x0f } - self.assertEqual(self.from_bytes(self.S16, b'\xff\xff' + pad), vals) - vals = { 'f4a' : 0x00, 'f8' : 0x00, 'f4b' : 0x00 } - self.assertEqual(self.from_bytes(self.S16, b'\x00\x00' + pad), vals) - vals = { 'f4a' : 0x0f, 'f8' : 0x00, 'f4b' : 0x0f } - self.assertEqual(self.from_bytes(self.S16, b'\xf0\x0f' + pad), vals) - vals = { 'f4a' : 0x00, 'f8' : 0xff, 'f4b' : 0x00 } - self.assertEqual(self.from_bytes(self.S16, b'\x0f\xf0' + pad), vals) - - with self.subTest('8 bit total (MSB): f4 + f1 + f3'): - vals = { 'f4' : 0x0f, 'f1' : 0x01, 'f3' : 0x07 } - self.assertEqual(self.from_bytes(self.S8M, b'\xff' + pad), vals) - vals = { 'f4' : 0x00, 'f1' : 0x00, 'f3' : 0x00 } - self.assertEqual(self.from_bytes(self.S8M, b'\x00' + pad), vals) - vals = { 'f4' : 0x0f, 'f1' : 0x00, 'f3' : 0x00 } - self.assertEqual(self.from_bytes(self.S8M, b'\xf0' + pad), vals) - - with self.subTest('8 bit total (LSB): f4 + f1 + f3'): - vals = { 'f4' : 0x0f, 'f1' : 0x01, 'f3' : 0x07 } - self.assertEqual(self.from_bytes(self.S8L, b'\xff' + pad), vals) - vals = { 'f4' : 0x00, 'f1' : 0x00, 'f3' : 0x00 } - self.assertEqual(self.from_bytes(self.S8L, b'\x00' + pad), vals) - vals = { 'f4' : 0x0f, 'f1' : 0x00, 'f3' : 0x00 } - self.assertEqual(self.from_bytes(self.S8L, b'\x0f' + pad), vals) - - def test_to_bytes_val(self): - with self.subTest('fixed values in absence of user-supplied values'): - vals = { 'f3' : 0x00 } # | { 'f4' : 2, 'f1' : 0 } - self.assertEqual(self.S8V.to_bytes(vals), b'\x20') - - with self.subTest('fixed values take precedence'): - vals = { 'f4' : 1, 'f1' : 1, 'f3' : 0 } - self.assertEqual(self.S8V.to_bytes(vals), b'\x20') - - def test_from_bytes_val(self): - with self.assertRaises(codec.DecodeError): - self.S8V.from_bytes({ }, b'\xf0') # 'f4': 15 vs 2 - - with self.assertRaises(codec.DecodeError): - self.S8V.from_bytes({ }, b'\x08') # 'f1': 1 vs 0 - - # Field 'f3' takes any value, no exceptions shall be raised - for i in range(8): - data, vals = bytes([0x20 + i]), { 'f4' : 2, 'f1' : 0, 'f3' : i } - self.assertEqual(self.from_bytes(self.S8V, data), vals) - - def test_to_bytes_spare(self): - self.assertEqual(self.S8P.to_bytes({ 'f4' : 0x00 }), b'\x00') - self.assertEqual(self.S8P.to_bytes({ 'f4' : 0x0f }), b'\x0f') - self.assertEqual(self.S8P.to_bytes({ 'f4' : 0xff }), b'\x0f') - - def test_from_bytes_spare(self): - self.assertEqual(self.from_bytes(self.S8P, b'\x00'), { 'f4' : 0x00 }) - self.assertEqual(self.from_bytes(self.S8P, b'\x0f'), { 'f4' : 0x0f }) - self.assertEqual(self.from_bytes(self.S8P, b'\xff'), { 'f4' : 0x0f }) - -class TestPDU(codec.Envelope): - STRUCT = ( - codec.BitFieldSet(len=2, set=( - codec.BitField('ver', bl=4), - codec.BitField('flag', bl=1), - )), - codec.Uint16BE('len'), - codec.Buf('data'), - codec.Buf('tail', len=2), - ) - - def __init__(self, *args, **kw): - codec.Envelope.__init__(self, *args, **kw) - self.STRUCT[-3].get_val = lambda v: len(v['data']) - self.STRUCT[-2].get_len = lambda v, _: v['len'] - self.STRUCT[-1].get_pres = lambda v: bool(v['flag']) - - def check(self, vals: dict) -> None: - if not vals['ver'] in (0, 1, 2): - raise ValueError('Unknown version %d' % vals['ver']) - -class Envelope(unittest.TestCase): - def test_rest_octets(self): - pdu = TestPDU(check_len=False) - pdu.from_bytes(b'\x00' * 64) - - with self.assertRaises(codec.DecodeError): - pdu = TestPDU(check_len=True) - pdu.from_bytes(b'\x00' * 64) # 'len' : 0 - - def test_field_raises(self): - pdu = TestPDU() - with self.assertRaises(codec.EncodeError): - pdu.c = { 'ver' : 0, 'flag' : 1, 'data' : b'\xff' * 16 } - pdu.to_bytes() # KeyError: 'tail' not found - - def test_to_bytes(self): - pdu = TestPDU() - - # No content in the new instances - self.assertEqual(pdu.c, { }) - - pdu.c = { 'ver' : 0, 'flag' : 1, 'data' : b'', 'tail' : b'\xde\xbe' } - self.assertEqual(pdu.to_bytes(), b'\x08\x00\x00\x00' + b'\xde\xbe') - - pdu.c = { 'ver' : 1, 'flag' : 0, 'data' : b'\xff' * 15 } - self.assertEqual(pdu.to_bytes(), b'\x10\x00\x00\x0f' + b'\xff' * 15) - - pdu.c = { 'ver' : 2, 'flag' : 1, 'data' : b'\xf0', 'tail' : b'\xbe\xed' } - self.assertEqual(pdu.to_bytes(), b'\x28\x00\x00\x01\xf0\xbe\xed') - - def test_from_bytes(self): - pdu = TestPDU() - - # No content in the new instances - self.assertEqual(pdu.c, { }) - - c = { 'ver' : 0, 'flag' : 1, 'len' : 0, 'data' : b'', 'tail' : b'\xde\xbe' } - pdu.from_bytes(b'\x08\x00\x00\x00' + b'\xde\xbe') - self.assertEqual(pdu.c, c) - - c = { 'ver' : 1, 'flag' : 0, 'len' : 15, 'data' : b'\xff' * 15 } - pdu.from_bytes(b'\x10\x00\x00\x0f' + b'\xff' * 15) - self.assertEqual(pdu.c, c) - - c = { 'ver' : 2, 'flag' : 1, 'len' : 1, 'data' : b'\xf0', 'tail' : b'\xbe\xed' } - pdu.from_bytes(b'\x28\x00\x00\x01\xf0\xbe\xed') - self.assertEqual(pdu.c, c) - - def test_to_bytes_check(self): - pdu = TestPDU() - - pdu.c = { 'ver' : 8, 'flag' : 1, 'data' : b'', 'tail' : b'\xde\xbe' } - with self.assertRaises(ValueError): - pdu.to_bytes() - - def test_from_bytes_check(self): - pdu = TestPDU() - - with self.assertRaises(ValueError): - pdu.from_bytes(b'\xf0\x00\x00\x00') - -class Sequence(unittest.TestCase): - class TLV(codec.Envelope): - STRUCT = ( - codec.Uint('T'), - codec.Uint('L'), - codec.Buf('V'), - ) - - def __init__(self, *args, **kw) -> None: - codec.Envelope.__init__(self, *args, **kw) - self.STRUCT[-2].get_val = lambda v: len(v['V']) - self.STRUCT[-1].get_len = lambda v, _: v['L'] - - # Sequence of TLVs - SEQ = codec.Sequence(item=TLV()) - - Vseq, Bseq = [ - { 'T' : 0xde, 'L' : 4, 'V' : b'\xde\xad\xbe\xef' }, - { 'T' : 0xbe, 'L' : 2, 'V' : b'\xbe\xef' }, - { 'T' : 0xbe, 'L' : 2, 'V' : b'\xef\xbe' }, - { 'T' : 0x00, 'L' : 0, 'V' : b'' }, - ], b''.join([ - b'\xde\x04\xde\xad\xbe\xef', - b'\xbe\x02\xbe\xef', - b'\xbe\x02\xef\xbe', - b'\x00\x00', - ]) - - def test_to_bytes(self): - res = self.SEQ.to_bytes(self.Vseq) - self.assertEqual(res, self.Bseq) - - def test_from_bytes(self): - res = self.SEQ.from_bytes(self.Bseq) - self.assertEqual(res, self.Vseq) - -if __name__ == '__main__': - unittest.main() diff --git a/src/target/trx_toolkit/test_data_dump.py b/src/target/trx_toolkit/test_data_dump.py deleted file mode 100644 index 67ff32b..0000000 --- a/src/target/trx_toolkit/test_data_dump.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Unit tests for DATA capture management -# -# (C) 2019 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -import unittest -import tempfile -import random - -from gsm_shared import * -from data_dump import * - -class DATADump_Test(unittest.TestCase): - def setUp(self): - # Create a temporary file - self._tf = tempfile.TemporaryFile(mode = 'w+b') - - # Create an instance of DATA dump manager - self._ddf = DATADumpFile(self._tf) - - # Compare message a with message b - def _compare_msg(self, a, b): - # Make sure we're comparing messages of the same type - self.assertEqual(a.__class__, b.__class__) - - # Compare common header fields - self.assertEqual(a.ver, b.ver) - self.assertEqual(a.fn, b.fn) - self.assertEqual(a.tn, b.tn) - - # Burst bits (if present) - self.assertEqual(a.burst, b.burst) - - # TxMsg specific fields - if isinstance(a, TxMsg): - self.assertEqual(a.pwr, b.pwr) - - # RxMsg specific fields - if isinstance(a, RxMsg): - # Version independent fields - self.assertEqual(a.toa256, b.toa256) - self.assertEqual(a.rssi, b.rssi) - - # Version specific fields - if a.ver >= 1: - self.assertEqual(a.nope_ind, b.nope_ind) - self.assertEqual(a.mod_type, b.mod_type) - self.assertEqual(a.tsc_set, b.tsc_set) - self.assertEqual(a.tsc, b.tsc) - self.assertEqual(a.ci, b.ci) - - # Generate a random message of a given type / version - def _gen_rand_message(self, cls, ver = 1): - msg = cls(ver = ver) - msg.rand_hdr() - msg.rand_burst() - return msg - - # Generate a list of random messages - def _gen_rand_messages(self, cls, count, ver = 1): - msg_list = [] - - for _ in range(count): - msg = self._gen_rand_message(cls, ver) - msg_list.append(msg) - - return msg_list - - # Generate a mixed list of random messages - def _gen_rand_message_mix(self, count, ver = 1): - msg_list = [] - msg_list += self._gen_rand_messages(RxMsg, count) - msg_list += self._gen_rand_messages(TxMsg, count) - random.shuffle(msg_list) - return msg_list - - def _test_store_and_parse(self, cls): - msg_ref = self._gen_rand_message(cls) - self._ddf.append_msg(msg_ref) - - msg = self._ddf.parse_msg(0) - self._compare_msg(msg, msg_ref) - - # Store one Rx message in a file, read it back and compare - def test_store_and_parse_rx_msg(self): - self._test_store_and_parse(RxMsg) - - # Store one Tx message in a file, read it back and compare - def test_store_and_parse_tx_msg(self): - self._test_store_and_parse(TxMsg) - - # Store multiple Rx/Tx messages in a file, read them back and compare - def test_store_and_parse_all(self): - # Store a mixed list of random messages (19 + 19) - msg_list_ref = self._gen_rand_message_mix(19) - self._ddf.append_all(msg_list_ref) - - # Retrieve and compare stored messages - msg_list = self._ddf.parse_all() - for i in range(len(msg_list_ref)): - self._compare_msg(msg_list[i], msg_list_ref[i]) - - # Verify random access to stored messages - def test_parse_msg_idx(self): - # Store a mixed list of random messages (19 + 19) - msg_list_ref = self._gen_rand_message_mix(19) - self._ddf.append_all(msg_list_ref) - - # Random access - for _ in range(100): - idx = random.randrange(len(msg_list_ref)) - msg = self._ddf.parse_msg(idx) - self._compare_msg(msg, msg_list_ref[idx]) - - def test_parse_empty(self): - with self.assertLogs(level = 'ERROR'): - for idx in range(100): - msg = self._ddf.parse_msg(idx) - self.assertEqual(msg, None) - - def test_parse_all_empty(self): - msg_list = self._ddf.parse_all() - self.assertEqual(msg_list, []) - - def test_parse_len_overflow(self): - # Write a malformed message directly - self._tf.write(DATADump.TAG_TxMsg) - self._tf.write(b'\x00\x63') # 99 - self._tf.write(b'\xff' * 90) - - with self.assertLogs(level = 'ERROR'): - msg = self._ddf.parse_msg(0) - self.assertEqual(msg, None) - - def test_parse_unknown_tag(self): - # Write a malformed message directly - self._tf.write(b'\x33') - self._tf.write(b'\x00\x63') # 99 - self._tf.write(b'\xff' * 90) - - with self.assertLogs(level = 'ERROR'): - msg = self._ddf.parse_msg(0) - self.assertEqual(msg, None) - -if __name__ == '__main__': - unittest.main() diff --git a/src/target/trx_toolkit/test_data_msg.py b/src/target/trx_toolkit/test_data_msg.py deleted file mode 100644 index 13a64a6..0000000 --- a/src/target/trx_toolkit/test_data_msg.py +++ /dev/null @@ -1,190 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Unit test for TRXD message codec -# -# (C) 2019 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -import unittest -from array import array - -from data_msg import Msg, TxMsg, RxMsg - -class Msg_Test(unittest.TestCase): - # Compare message a with message b - def _compare_msg(self, a, b): - # Make sure we're comparing messages of the same type - self.assertEqual(a.__class__, b.__class__) - - # Compare common header fields - self.assertEqual(a.ver, b.ver) - self.assertEqual(a.fn, b.fn) - self.assertEqual(a.tn, b.tn) - - # Burst bits (if present) - self.assertEqual(a.burst, b.burst) - - # TxMsg specific fields - if isinstance(a, TxMsg): - self.assertEqual(a.pwr, b.pwr) - - # RxMsg specific fields - if isinstance(a, RxMsg): - # Version independent fields - self.assertEqual(a.toa256, b.toa256) - self.assertEqual(a.rssi, b.rssi) - - # Version specific fields - if a.ver >= 1: - self.assertEqual(a.nope_ind, b.nope_ind) - self.assertEqual(a.mod_type, b.mod_type) - self.assertEqual(a.tsc_set, b.tsc_set) - self.assertEqual(a.tsc, b.tsc) - self.assertEqual(a.ci, b.ci) - - # Make sure that message validation throws a ValueError - def test_validate(self): - # Unknown version - with self.assertRaises(ValueError): - msg = RxMsg(fn = 0, tn = 0, ver = 100) - msg.validate() - - # Uninitialized field - with self.assertRaises(ValueError): - msg = RxMsg() - msg.validate() - with self.assertRaises(ValueError): - msg = RxMsg(fn = None, tn = 0) - msg.validate() - - # Out-of-range value(s) - with self.assertRaises(ValueError): - msg = RxMsg(fn = -1, tn = 0) - msg.validate() - with self.assertRaises(ValueError): - msg = RxMsg(fn = 0, tn = 10) - msg.validate() - - # Validate header and burst randomization - def test_rand_hdr_burst(self): - tx_msg = TxMsg() - rx_msg = RxMsg() - - for i in range(100): - tx_msg.rand_burst() - rx_msg.rand_burst() - tx_msg.rand_hdr() - rx_msg.rand_hdr() - - tx_msg.validate() - rx_msg.validate() - - def _test_enc_dec(self, msg, legacy = False, nope_ind = False): - # Prepare a given message (randomize) - msg.rand_hdr() - - # NOPE.ind contains no burst - if not nope_ind: - msg.rand_burst() - else: - msg.nope_ind = True - msg.mod_type = None - msg.tsc_set = None - msg.tsc = None - - # Encode a given message to bytes - msg_enc = msg.gen_msg(legacy) - - # Decode a new message from bytes - msg_dec = msg.__class__() - msg_dec.parse_msg(msg_enc) - - # Compare decoded vs the original - self._compare_msg(msg, msg_dec) - - # Validate encoding and decoding - def test_enc_dec(self): - for ver in Msg.KNOWN_VERSIONS: - with self.subTest("TxMsg", ver = ver): - msg = TxMsg(ver = ver) - self._test_enc_dec(msg) - - with self.subTest("RxMsg", ver = ver): - msg = RxMsg(ver = ver) - self._test_enc_dec(msg) - - if ver >= 1: - with self.subTest("RxMsg NOPE.ind", ver = ver): - msg = RxMsg(ver = ver) - self._test_enc_dec(msg, nope_ind = True) - - with self.subTest("RxMsg (legacy transceiver)"): - msg = RxMsg(ver = 0) - self._test_enc_dec(msg, legacy = True) - - # Validate bit conversations - def test_bit_conv(self): - usbits_ref = array('B', range(0, 256)) - sbits_ref = array('b', range(-127, 128)) - - # Test both usbit2sbit() and sbit2usbit() - sbits = Msg.usbit2sbit(usbits_ref) - usbits = Msg.sbit2usbit(sbits) - self.assertEqual(usbits[:255], usbits_ref[:255]) - self.assertEqual(usbits[255], 254) - - # Test both sbit2ubit() and ubit2sbit() - ubits = Msg.sbit2ubit(sbits_ref) - self.assertEqual(ubits, bytearray([1] * 127 + [0] * 128)) - - sbits = Msg.ubit2sbit(ubits) - self.assertEqual(sbits, array('b', [-127] * 127 + [127] * 128)) - - def _test_transform(self, msg): - # Prepare given messages - msg.rand_hdr() - msg.rand_burst() - - # Perform message transformation - if isinstance(msg, TxMsg): - msg_trans = msg.trans() - else: - msg_trans = msg.trans() - - self.assertEqual(msg_trans.ver, msg.ver) - self.assertEqual(msg_trans.fn, msg.fn) - self.assertEqual(msg_trans.tn, msg.tn) - - if isinstance(msg, RxMsg): - burst = Msg.sbit2ubit(msg.burst) - self.assertEqual(msg_trans.burst, burst) - else: - burst = Msg.ubit2sbit(msg.burst) - self.assertEqual(msg_trans.burst, burst) - - # Validate message transformation - def test_transform(self): - for ver in Msg.KNOWN_VERSIONS: - with self.subTest("TxMsg", ver = ver): - msg = TxMsg(ver = ver) - self._test_transform(msg) - - with self.subTest("RxMsg", ver = ver): - msg = RxMsg(ver = ver) - self._test_transform(msg) - -if __name__ == '__main__': - unittest.main() diff --git a/src/target/trx_toolkit/transceiver.py b/src/target/trx_toolkit/transceiver.py deleted file mode 100644 index 20d9cde..0000000 --- a/src/target/trx_toolkit/transceiver.py +++ /dev/null @@ -1,338 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Transceiver implementation -# -# (C) 2018-2020 by Vadim Yanitskiy <axilirator(a)gmail.com> -# Contributions by sysmocom - s.f.m.c. GmbH -# -# 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 2 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. - -import logging as log -import threading - -from ctrl_if_trx import CTRLInterfaceTRX -from data_if import DATAInterface -from udp_link import UDPLink -from trx_list import TRXList - -from gsm_shared import HoppingParams - -class Transceiver: - """ Base transceiver implementation. - - Represents a single transceiver, that can be used as for the BTS side, - as for the MS side. Each individual instance of Transceiver unifies - three basic interfaces built on three independent UDP connections: - - - CLCK (base port + 100/0) - clock indications from TRX to L1, - - CTRL (base port + 101/1) - control interface for L1, - - DATA (base port + 102/2) - bidirectional data interface for bursts. - - A transceiver can be either in active (i.e. working), or in idle mode. - The active mode should ensure that both RX/TX frequencies are set. - - NOTE: CLCK is not required for some L1 implementations, so it is optional. - - == Child transceivers - - A BTS can (optionally) have more than one transceiver. In this case - additional (let's say child) transceivers basically share the same - clock source of the first transceiver, so UDP port mapping is a bit - different, for example: - - (trx_0) clck=5700, ctrl=5701, data=5702, - (trx_1) ctrl=5703, data=5704, - (trx_2) ctrl=5705, data=5706. - ... - - By default, powering on/off a parent transceiver (child_idx=0) will - automatically power on/off its child transceivers (if any). This - behavior can be disabled by setting "child_mgt" param to False. - - == Clock distribution (optional) - - The clock indications are not expected by L1 when transceiver - is not running, so we monitor both POWERON / POWEROFF events - from the control interface, and keep the list of CLCK links - in a given CLCKGen instance updated. The clock generator is - started and stopped automatically. - - NOTE: a single instance of CLCKGen can be shared between multiple - transceivers, as well as multiple transceivers may use - individual CLCKGen instances. - - == Power Measurement (optional) - - Transceiver may have an optional power measurement interface, - that shall provide at least one method: measure(freq). This - is required for the MS side (i.e. OsmocomBB). - - == Frequency hopping (optional) - - There are two ways to implement frequency hopping: - - a) The Transceiver is configured with the hopping parameters, in - particular HSN, MAIO, and the list of ARFCNs (channels), so the - actual Rx/Tx frequencies are changed by the Transceiver itself - depending on the current TDMA frame number. - - b) The L1 maintains several Transceivers (two or more), so each - instance is assigned one dedicated RF carrier frequency, and - hence the number of available hopping frequencies is equal to - the number of Transceivers. In this case, it's the task of - the L1 to commutate bursts between Transceivers (frequencies). - - Variant a) is commonly known as "synthesizer frequency hopping" - whereas b) is known as "baseband frequency hopping". - - For the MS side, a) is preferred, because a phone usually has only - one Transceiver (per RAT). On the other hand, b) is more suitable - for the BTS side, because it's relatively easy to implement and - there is no technical limitation on the amount of Transceivers. - - FakeTRX obviously does support b) since multi-TRX feature has been - implemented, as well as a) by resolving UL/DL frequencies using a - preconfigured (by the L1) set of the hopping parameters. The later - can be enabled using the SETFH control command. - - NOTE: in the current implementation, mode a) applies to the whole - Transceiver and all its timeslots, so using in for the BTS side - does not make any sense (imagine BCCH hopping together with DCCH). - - == The transmit burst queue - - According to 3GPP 45.002, the time difference between Uplink and - Downlink corresponds to three TDMA timeslot periods. However, - in general the L1 implementations (such as osmo-bts-trx and trxcon) - never schedule to be transmitted bursts for the current TDMA frame - immediately. Instead, they are being scheduled prematurely. - - The rationale is that both transceiver and the L1 implementation - are separate processes that are not perfectly synchronized in time. - Moreover, the transceiver needs some time to prepare a burst for - transmission. This is why the time difference between Uplink and - Downlink is actually much higher on practice (currently 2 TDMA - frame periods for both trxcon and osmo-bts-trx). - - In order to reflect that delay in a virtual environment, this - implementation, just like osmo-trx, queues all to be transmitted - (L12TRX) bursts, so that they remain in the transmit queue until - the appropriate time of transmission. - - The API user is supposed to call recv_data_msg() in order to obtain - a L12TRX message on the TRXD (data) interface, so it gets queued by - this function. Then, to ensure the timeous transmission, the user - of this implementation needs to call clck_tick() on each TDMA - frame. Both functions are thread-safe (queue mutex). - - In a multi-trx configuration, the use of queue additionally ensures - proper burst aggregation on multiple TRXD connections, so all L12TRX - messages are guaranteed to be sent in the right order, i.e. with - monolithically-increasing TDMA frame numbers. - - """ - - def __init__(self, bind_addr, remote_addr, base_port, **kwargs): - # Connection info - self.remote_addr = remote_addr - self.bind_addr = bind_addr - self.base_port = base_port - self.child_idx = kwargs.get("child_idx", 0) - self.child_mgt = kwargs.get("child_mgt", True) - - # Meta info - self.name = kwargs.get("name", None) - - log.info("Init transceiver '%s'" % self) - - # Child transceiver cannot have its own clock - self.clck_gen = kwargs.get("clck_gen", None) - if self.clck_gen is not None and self.child_idx > 0: - raise TypeError("Child transceiver cannot have its own clock") - - # Init DATA interface - self.data_if = DATAInterface( - remote_addr, base_port + self.child_idx * 2 + 102, - bind_addr, base_port + self.child_idx * 2 + 2) - - # Init CTRL interface - self.ctrl_if = CTRLInterfaceTRX(self, - remote_addr, base_port + self.child_idx * 2 + 101, - bind_addr, base_port + self.child_idx * 2 + 1) - - # Init optional CLCK interface - if self.clck_gen is not None: - self.clck_if = UDPLink( - remote_addr, base_port + 100, - bind_addr, base_port) - - # Optional Power Measurement interface - self.pwr_meas = kwargs.get("pwr_meas", None) - - # Internal state - self.running = False - - # Actual RX / TX frequencies - self._rx_freq = None - self._tx_freq = None - - # Frequency hopping parameters (set by CTRL) - self.fh = None - - # List of child transceivers - self.child_trx_list = TRXList() - - # Tx (L12TRX) burst queue and mutex - self._tx_queue_lock = threading.Lock() - self._tx_queue = [] - - def __str__(self): - desc = "%s:%d" % (self.remote_addr, self.base_port) - if self.child_idx > 0: - desc += "/%d" % self.child_idx - if self.name is not None: - desc = "%s@%s" % (self.name, desc) - - return desc - - @property - def ready(self): - # Make sure that either both Rx/Tx frequencies are set - if self._rx_freq is None or self._tx_freq is None: - # ... or frequency hopping is in use - if self.fh is None: - return False - - return True - - def get_rx_freq(self, fn): - if self.fh is None: - return self._rx_freq - - # Frequency hopping in use, resolve by TDMA fn - (rx_freq, _) = self.fh.resolve(fn) - return rx_freq - - def get_tx_freq(self, fn): - if self.fh is None: - return self._tx_freq - - # Frequency hopping in use, resolve by TDMA fn - (_, tx_freq) = self.fh.resolve(fn) - return tx_freq - - def enable_fh(self, *args): - self.fh = HoppingParams(*args) - log.info("(%s) Frequency hopping configured: %s" % (self, self.fh)) - - def disable_fh(self): - if self.fh is not None: - log.info("(%s) Frequency hopping disabled" % self) - self.fh = None - - def reset_params(self): - """ Reset/initialize all parameters """ - self.running = False - self._rx_freq = None - self._tx_freq = None - self.disable_fh() - - # To be overwritten if required, - # no custom command handlers by default - def ctrl_cmd_handler(self, request): - return None - - def power_event_handler(self, poweron: bool) -> None: - # If self.child_mgt is True, automatically power on/off children - if self.child_mgt and self.child_idx == 0: - trx_list = [self, *self.child_trx_list.trx_list] - else: - trx_list = [self] - # Update self and optionally child transceivers - for trx in trx_list: - trx.running = poweron - if not poweron: - trx.tx_queue_clear() - trx.reset_params() - - # Trigger clock generator if required - if self.clck_gen is not None: - clck_links = self.clck_gen.clck_links - if not self.running and (self.clck_if in clck_links): - # Transceiver was stopped - clck_links.remove(self.clck_if) - elif self.running and (self.clck_if not in clck_links): - # Transceiver was started - clck_links.append(self.clck_if) - - if not self.clck_gen.running and len(clck_links) > 0: - log.info("Starting clock generator") - self.clck_gen.start() - elif self.clck_gen.running and not clck_links: - log.info("Stopping clock generator") - self.clck_gen.stop() - - def recv_data_msg(self): - # Read and parse data from socket - msg = self.data_if.recv_tx_msg() - if not msg: - return None - - # Make sure that transceiver is configured and running - if not self.running: - log.warning("(%s) RX TRXD message (%s), but transceiver " - "is not running => dropping..." % (self, msg.desc_hdr())) - return None - - # Enqueue the message, it will be sent later - self.tx_queue_append(msg) - return msg - - def handle_data_msg(self, msg): - # TODO: make legacy mode configurable (via argv?) - self.data_if.send_msg(msg, legacy = True) - - def tx_queue_append(self, msg): - with self._tx_queue_lock: - self._tx_queue.append(msg) - - def tx_queue_clear(self): - with self._tx_queue_lock: - self._tx_queue.clear() - - def clck_tick(self, fwd, fn): - if not self.running: - return - - drop = [] - emit = [] - wait = [] - - with self._tx_queue_lock: - for msg in self._tx_queue: - if msg.fn < fn: - drop.append(msg) - elif msg.fn == fn: - emit.append(msg) - else: - wait.append(msg) - - self._tx_queue = wait - - for msg in emit: - fwd.forward_msg(self, msg) - - for msg in drop: - log.warning("(%s) Stale TRXD message (fn=%u): %s" - % (self, fn, msg.desc_hdr())) diff --git a/src/target/trx_toolkit/trx_list.py b/src/target/trx_toolkit/trx_list.py deleted file mode 100644 index c476a7d..0000000 --- a/src/target/trx_toolkit/trx_list.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Transceiver list implementation -# -# (C) 2019 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -class TRXList: - """ Transceiver list implementation. - - This class is a simple wrapper around generic Python's list. - The aim is to simplify management of multiple Transceiver - instances, e.g. appending, removing and finding them. - - """ - - def __init__(self, trx_list = None): - self.trx_list = trx_list or [] - - # NOTE: do not use this in performance critical parts - def __getitem__(self, i): - return self.trx_list[i] - - def find_trx(self, remote_addr, base_port, child_idx = 0): - for trx in self.trx_list: - if trx.remote_addr != remote_addr: - continue - if trx.base_port != base_port: - continue - if trx.child_idx != child_idx: - continue - return trx - - return None - - def add_trx(self, trx): - if trx in self.trx_list: - raise IndexError("TRX '%s' is already in the list" % trx) - if self.find_trx(trx.remote_addr, trx.base_port, trx.child_idx): - raise IndexError("TRX '%s' has duplicate in the list" % trx) - - self.trx_list.append(trx) - - def del_trx(self, trx): - if trx not in self.trx_list: - raise IndexError("TRX '%s' is not in the list" % trx) - self.trx_list.remove(trx) diff --git a/src/target/trx_toolkit/trx_sniff.py b/src/target/trx_toolkit/trx_sniff.py deleted file mode 100755 index c91e3e0..0000000 --- a/src/target/trx_toolkit/trx_sniff.py +++ /dev/null @@ -1,284 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# TRX Toolkit -# Scapy-based TRX interface sniffer -# -# (C) 2018-2020 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -APP_CR_HOLDERS = [("2018-2020", "Vadim Yanitskiy <axilirator(a)gmail.com>")] - -import logging as log -import argparse -import sys - -import scapy.all - -from app_common import ApplicationBase -from data_dump import DATADumpFile -from data_msg import * - -class Application(ApplicationBase): - # Counters - cnt_burst_dropped_num = 0 - cnt_burst_num = 0 - - cnt_frame_last = None - cnt_frame_num = 0 - - # Internal variables - lo_trigger = False - - def __init__(self): - self.app_print_copyright(APP_CR_HOLDERS) - self.argv = self.parse_argv() - - # Configure logging - self.app_init_logging(self.argv) - - # Open requested capture file - if self.argv.output_file is not None: - self.ddf = DATADumpFile(self.argv.output_file) - - def run(self): - # Compose a list of permitted UDP ports - rx_port_list = ["port %d" % (port + 102) for port in self.argv.base_ports] - tx_port_list = ["port %d" % (port + 2) for port in self.argv.base_ports] - - # Arguments to be passed to scapy.all.sniff() - sniff_args = { - "filter" : "udp and (%s)" % " or ".join(rx_port_list + tx_port_list), - "prn" : self.pkt_handler, - "store" : 0, - } - - if self.argv.cap_file is not None: - log.info("Reading packets from '%s'..." % self.argv.cap_file) - sniff_args["offline"] = self.argv.cap_file - else: - log.info("Listening on interface '%s'..." % self.argv.sniff_if) - sniff_args["iface"] = self.argv.sniff_if - - if self.argv.cap_filter is not None: - log.info("Using additional capture filter '%s'" % self.argv.cap_filter) - sniff_args["filter"] += " and (%s)" % self.argv.cap_filter - - # Start sniffing... - scapy.all.sniff(**sniff_args) - - # Scapy registers its own signal handler - self.shutdown() - - def pkt_handler(self, ether): - # Prevent loopback packet duplication - if self.argv.sniff_if == "lo" and self.argv.cap_file is None: - self.lo_trigger = not self.lo_trigger - if not self.lo_trigger: - return - - # Extract a TRX payload - ip = ether.payload - udp = ip.payload - trx = udp.payload - - # Convert to bytearray - msg_raw = bytearray(trx.load) - - # Determine a burst direction (L1 <-> TRX) - tx_dir = udp.sport > udp.dport - - # Create an empty DATA message - msg = TxMsg() if tx_dir else RxMsg() - - # Attempt to parse the payload as a DATA message - try: - msg.parse_msg(msg_raw) - msg.validate() - except ValueError as e: - desc = msg.desc_hdr() - if desc == "": - desc = "parsing error" - log.warning("Ignoring an incorrect message (%s): %s" % (desc, e)) - self.cnt_burst_dropped_num += 1 - return - - # Poke burst pass filter - if not self.burst_pass_filter(msg): - self.cnt_burst_dropped_num += 1 - return - - # Debug print - log.debug("%s burst: %s", "L1 -> TRX" if tx_dir else "TRX -> L1", msg.desc_hdr()) - - # Poke message handler - self.msg_handle(msg) - - # Poke burst counter - rc = self.burst_count(msg.fn, msg.tn) - if rc is True: - self.shutdown() - - def burst_pass_filter(self, msg): - # Direction filter - if self.argv.direction is not None: - if self.argv.direction == "TRX": # L1 -> TRX - if not isinstance(msg, TxMsg): - return False - elif self.argv.direction == "L1": # TRX -> L1 - if not isinstance(msg, RxMsg): - return False - - # Timeslot filter - if self.argv.pf_tn is not None: - if msg.tn != self.argv.pf_tn: - return False - - # Frame number filter - if self.argv.pf_fn_lt is not None: - if msg.fn > self.argv.pf_fn_lt: - return False - if self.argv.pf_fn_gt is not None: - if msg.fn < self.argv.pf_fn_gt: - return False - - # Message type specific filtering - if isinstance(msg, RxMsg): - # NOPE.ind filter - if not self.argv.pf_nope_ind and msg.nope_ind: - return False - - # RSSI filter - if self.argv.pf_rssi_min is not None: - if msg.rssi < self.argv.pf_rssi_min: - return False - if self.argv.pf_rssi_max is not None: - if msg.rssi > self.argv.pf_rssi_max: - return False - - # Burst passed ;) - return True - - def msg_handle(self, msg): - if self.argv.verbose: - print(msg.burst) - - # Append a new message to the capture - if self.argv.output_file is not None: - self.ddf.append_msg(msg) - - def burst_count(self, fn, tn): - # Update frame counter - if self.cnt_frame_last is None: - self.cnt_frame_last = fn - self.cnt_frame_num += 1 - else: - if fn != self.cnt_frame_last: - self.cnt_frame_num += 1 - - # Update burst counter - self.cnt_burst_num += 1 - - # Stop sniffing after N bursts - if self.argv.burst_count is not None: - if self.cnt_burst_num == self.argv.burst_count: - log.info("Collected required amount of bursts") - return True - - # Stop sniffing after N frames - if self.argv.frame_count is not None: - if self.cnt_frame_num == self.argv.frame_count: - log.info("Collected required amount of frames") - return True - - return False - - def shutdown(self): - log.info("Shutting down...") - - # Print statistics - log.info("%u bursts handled, %u dropped" \ - % (self.cnt_burst_num, self.cnt_burst_dropped_num)) - - # Exit - sys.exit(0) - - def parse_argv(self): - parser = argparse.ArgumentParser(prog = "trx_sniff", - description = "Scapy-based TRX interface sniffer") - - parser.add_argument("-v", "--verbose", - dest = "verbose", action = "store_true", - help = "Print burst bits to stdout") - - # Register common logging options - self.app_reg_logging_options(parser) - - trx_group = parser.add_argument_group("TRX interface") - trx_group.add_argument("-p", "--base-port", "--base-ports", - dest = "base_ports", type = int, metavar = "PORT", - default = [5700, 6700], nargs = "*", - help = "Set base port number (default %(default)s)") - trx_group.add_argument("-o", "--output-file", metavar = "FILE", - dest = "output_file", type = str, - help = "Write bursts to a capture file") - - input_group = trx_group.add_mutually_exclusive_group() - input_group.add_argument("-i", "--sniff-interface", - dest = "sniff_if", type = str, default = "lo", metavar = "IF", - help = "Set network interface (default '%(default)s')") - input_group.add_argument("-r", "--capture-file", - dest = "cap_file", type = str, metavar = "FILE", - help = "Read packets from a PCAP file") - - trx_group.add_argument("-f", "--capture-filter", - dest = "cap_filter", type = str, metavar = "FILTER", - help = "Set additional capture filter (e.g. 'host 192.168.1.2')") - - cnt_group = parser.add_argument_group("Count limitations (optional)") - cnt_group.add_argument("--frame-count", metavar = "N", - dest = "frame_count", type = int, - help = "Stop after sniffing N frames") - cnt_group.add_argument("--burst-count", metavar = "N", - dest = "burst_count", type = int, - help = "Stop after sniffing N bursts") - - pf_group = parser.add_argument_group("Filtering (optional)") - pf_group.add_argument("--direction", - dest = "direction", type = str, choices = ["TRX", "L1"], - help = "Burst direction") - pf_group.add_argument("--timeslot", metavar = "TN", - dest = "pf_tn", type = int, choices = range(0, 8), - help = "TDMA timeslot number (equal TN)") - pf_group.add_argument("--frame-num-lt", metavar = "FN", - dest = "pf_fn_lt", type = int, - help = "TDMA frame number (lower than FN)") - pf_group.add_argument("--frame-num-gt", metavar = "FN", - dest = "pf_fn_gt", type = int, - help = "TDMA frame number (greater than FN)") - pf_group.add_argument("--no-nope-ind", - dest = "pf_nope_ind", action = "store_false", - help = "Ignore NOPE.ind (NOPE / IDLE indications)") - pf_group.add_argument("--rssi-min", metavar = "RSSI", - dest = "pf_rssi_min", type = int, - help = "Minimum RSSI value (e.g. -75)") - pf_group.add_argument("--rssi-max", metavar = "RSSI", - dest = "pf_rssi_max", type = int, - help = "Maximum RSSI value (e.g. -50)") - - return parser.parse_args() - -if __name__ == '__main__': - app = Application() - app.run() diff --git a/src/target/trx_toolkit/trxd_proto.py b/src/target/trx_toolkit/trxd_proto.py deleted file mode 100644 index a1bf1b5..0000000 --- a/src/target/trx_toolkit/trxd_proto.py +++ /dev/null @@ -1,175 +0,0 @@ -# -*- coding: utf-8 -*- - -''' -TRXD PDU definitions based on declarative codec. -''' - -# TRX Toolkit -# -# (C) 2021 by sysmocom - s.f.m.c. GmbH <info(a)sysmocom.de> -# Author: Vadim Yanitskiy <vyanitskiy(a)sysmocom.de> -# -# 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 2 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. - -import codec - -class Header(codec.BitFieldSet): - ''' Header constructor for TRXD PDUs. ''' - - def __init__(self, ver: int, batched: bool = False): - f = [ # Dynamically generated field list - codec.BitField('ver', bl=4, val=ver) if not batched - else codec.BitField.Spare(bl=4), # RFU - codec.BitField.Spare(bl=1), - codec.BitField('tn', bl=3), - ] - - if ver >= 2: # TRXDv2 and higher - f.append(codec.BitField('batch', bl=1)) - f.append(codec.BitField('shadow', bl=1) if batched - else codec.BitField.Spare(bl=1)) - f.append(codec.BitField('trxn', bl=6)) - - codec.BitFieldSet.__init__(self, set=tuple(f)) - -class MTS(codec.BitFieldSet): - ''' Modulation and Training Sequence. ''' - - DEF_LEN = 1 - STRUCT = ( - codec.BitField('nope', bl=1), - codec.BitField('mod', bl=4), - codec.BitField('tsc', bl=3), - ) - - @staticmethod - def get_burst_len(mod: int) -> int: - ''' Get burst length by modulation type. ''' - - GMSK_BURST_LEN = 148 - - if (mod >> 2) == 0b00: # GMSK - return 1 * GMSK_BURST_LEN - elif (mod >> 2) == 0b11: # AQPSK - return 2 * GMSK_BURST_LEN - elif (mod >> 1) == 0b010: # 8-PSK - return 3 * GMSK_BURST_LEN - elif (mod >> 1) == 0b100: # 16QAM - return 4 * GMSK_BURST_LEN - elif (mod >> 1) == 0b101: # 32QAM - return 5 * GMSK_BURST_LEN - elif mod == 0b0110: # GMSK (Access Burst) - return 1 * GMSK_BURST_LEN - raise ValueError('Unknown modulation type') - -class BurstBits(codec.Buf): - ''' Soft-/hard-bits with variable length. ''' - - def __init__(self, name: str, *args, **kw): - codec.Buf.__init__(self, name, *args, **kw) - - # This field has a variable length that depends on moduletion type - self.get_len = lambda v, _: MTS.get_burst_len(v['mod']) - # This field is not present in NOPE / IDLE indications - self.get_pres = lambda v: not v['nope'] - - -class PDUv0Rx(codec.Envelope): - STRUCT = ( - Header(ver=0), - codec.Uint32BE('fn'), - codec.Uint('rssi', mult=-1), - codec.Int16BE('toa256'), - codec.Buf('soft-bits'), - codec.Buf('pad'), # Optional - ) - - def __init__(self, *args, **kw): - codec.Envelope.__init__(self, *args, **kw) - - # Field 'soft-bits' is either 148 (GMSK) or 444 (8-PSK) octets long - self.STRUCT[-2].get_len = lambda _, data: 444 if len(data) > 148 else 148 - -class PDUv0Tx(codec.Envelope): - STRUCT = ( - Header(ver=0), - codec.Uint32BE('fn'), - codec.Uint('pwr'), - codec.Buf('hard-bits'), - ) - - -class PDUv1Rx(codec.Envelope): - STRUCT = ( - Header(ver=1), - codec.Uint32BE('fn'), - codec.Uint('rssi', mult=-1), - codec.Int16BE('toa256'), - MTS(), - codec.Int16BE('cir'), - BurstBits('soft-bits'), - ) - -class PDUv1Tx(PDUv0Tx): - # Same structure as PDUv0Tx, only the version is different - STRUCT = ( - Header(ver=1), - *PDUv0Tx.STRUCT[1:] - ) - - -class PDUv2Rx(codec.Envelope): - class BPDU(codec.Envelope): - ''' Batched PDU part. ''' - STRUCT = ( - Header(ver=2, batched=True), - MTS(), - codec.Uint('rssi', mult=-1), - codec.Int16BE('toa256'), - codec.Int16BE('cir'), - BurstBits('soft-bits'), - ) - - STRUCT = ( - Header(ver=2), - MTS(), - codec.Uint('rssi', mult=-1), - codec.Int16BE('toa256'), - codec.Int16BE('cir'), - codec.Uint32BE('fn'), - BurstBits('soft-bits'), - codec.Sequence(item=BPDU()).f('bpdu'), - ) - -class PDUv2Tx(codec.Envelope): - class BPDU(codec.Envelope): - ''' Batched PDU part. ''' - STRUCT = ( - Header(ver=2, batched=True), - MTS(), - codec.Uint('pwr'), - codec.Int('scpir'), - codec.Spare('spare', len=3), - BurstBits('hard-bits'), - ) - - STRUCT = ( - Header(ver=2), - MTS(), - codec.Uint('pwr'), - codec.Int('scpir'), - codec.Spare('spare', len=3), - codec.Uint32BE('fn'), - BurstBits('hard-bits'), - codec.Sequence(item=BPDU()).f('bpdu'), - ) diff --git a/src/target/trx_toolkit/udp_link.py b/src/target/trx_toolkit/udp_link.py deleted file mode 100644 index 8690109..0000000 --- a/src/target/trx_toolkit/udp_link.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- - -# TRX Toolkit -# UDP link implementation -# -# (C) 2017 by Vadim Yanitskiy <axilirator(a)gmail.com> -# -# 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 2 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. - -import logging as log -import socket - -class UDPLink: - def __init__(self, remote_addr, remote_port, bind_addr = '0.0.0.0', bind_port = 0): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.sock.bind((bind_addr, bind_port)) - self.sock.setblocking(False) - - # Save remote info - self.remote_addr = remote_addr - self.remote_port = remote_port - - def __del__(self): - self.sock.close() - - def desc_local(self): - (bind_addr, bind_port) = self.sock.getsockname() - return "%s:%u" % (bind_addr, bind_port) - - def desc_remote(self): - return "%s:%u" % (self.remote_addr, self.remote_port) - - def desc_link(self): - return "L:%s <-> R:%s" % (self.desc_local(), self.desc_remote()) - - def send(self, data): - self.sendto(data, (self.remote_addr, self.remote_port)) - - def sendto(self, data, remote): - if type(data) not in [bytearray, bytes]: - data = data.encode() - try: - self.sock.sendto(data, remote) - except BlockingIOError: - # When the message does not fit into the send buffer of the socket, send() - # normally blocks, unless the socket has been placed in nonblocking I/O mode. - # In nonblocking mode it would fail with the BlockingIOError in this case. - log.error('(%s) BlockingIOError: dropping Tx data', self.desc_link()) -- To view, visit https://gerrit.osmocom.org/c/osmocom-bb/+/44224?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newchange Gerrit-Project: osmocom-bb Gerrit-Branch: master Gerrit-Change-Id: Iba2a9242af052b2283b8a09fe98a2529b1955ab4 Gerrit-Change-Number: 44224 Gerrit-PatchSet: 1 Gerrit-Owner: osmith <osmith(a)sysmocom.de>
1 0
0 0
[L] Change in libosmocore[master]: gsm: new struct and en/decoding functions for BC-IE
by laforge 02 Dec '26

02 Dec '26
Attention is currently required from: falconia, fixeria, pespin. laforge has posted comments on this change by falconia. ( https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email ) Change subject: gsm: new struct and en/decoding functions for BC-IE ...................................................................... Patch Set 5: Code-Review+1 -- To view, visit https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: libosmocore Gerrit-Branch: master Gerrit-Change-Id: Ie864734fe1dfd1587bafddd4248ce69a7e066525 Gerrit-Change-Number: 44192 Gerrit-PatchSet: 5 Gerrit-Owner: falconia <falcon(a)freecalypso.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de> Gerrit-CC: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: pespin <pespin(a)sysmocom.de> Gerrit-Attention: falconia <falcon(a)freecalypso.org> Gerrit-Comment-Date: Wed, 02 Dec 2026 14:47:35 +0000 Gerrit-HasComments: No Gerrit-Has-Labels: Yes
1 0
0 0
[M] Change in osmo-msc[master]: vlr: fail TMSI allocation if no NRI range fits the NRI bitlen
by laforge 02 Dec '26

02 Dec '26
Attention is currently required from: bucketking657, neels. laforge has posted comments on this change by bucketking657. ( https://gerrit.osmocom.org/c/osmo-msc/+/44220?usp=email ) Change subject: vlr: fail TMSI allocation if no NRI range fits the NRI bitlen ...................................................................... Patch Set 2: Code-Review+1 -- To view, visit https://gerrit.osmocom.org/c/osmo-msc/+/44220?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: osmo-msc Gerrit-Branch: master Gerrit-Change-Id: I24b71c8d568477680f735dc4044ec267385156ab Gerrit-Change-Number: 44220 Gerrit-PatchSet: 2 Gerrit-Owner: bucketking657 <joshuashilts(a)gmail.com> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: neels <nhofmeyr(a)sysmocom.de> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de> Gerrit-Attention: neels <nhofmeyr(a)sysmocom.de> Gerrit-Attention: bucketking657 <joshuashilts(a)gmail.com> Gerrit-Comment-Date: Wed, 02 Dec 2026 14:45:48 +0000 Gerrit-HasComments: No Gerrit-Has-Labels: Yes
1 0
0 0
  • ← Newer
  • 1
  • ...
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • ...
  • 9721
  • Older →

HyperKitty Powered by HyperKitty version 1.3.12.