Merge branch 'develop' into update_check

This commit is contained in:
Bastian Schroll 2019-10-22 08:23:02 +02:00
commit 9b027d371a
64 changed files with 976 additions and 880 deletions

27
.github/workflows/run_pytest.yml vendored Normal file
View file

@ -0,0 +1,27 @@
name: pytest
on: [push]
jobs:
build:
strategy:
max-parallel: 3
matrix:
os: [ubuntu-latest]
python-version: [3.5, 3.6, 3.7]
runs-on: ${{matrix.os}}
steps:
- uses: actions/checkout@v1
- name: Set up Python ${{matrix.python-version}} at ${{matrix.os}}
uses: actions/setup-python@v1
with:
python-version: ${{matrix.python-version}}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
mkdir log/
- name: Test with pytest
run: |
pytest -c 'test/pytest.ini'

15
.gitignore vendored
View file

@ -6,12 +6,13 @@
# German BOS Information Script
# by Bastian Schroll
# virtual environment
\venv/
# generated files
log/
_docu/
_bin/win/zadig/
_bin/win/rtl_sdr/
_bin/win/multimon_1_1_1/
_bin/win/kalibrate/
docu/docs/api/html
docu/site/
# Logo Photoshop file
*.psd
@ -22,6 +23,10 @@ _bin/win/kalibrate/
# Python precompiled
*.pyc
# Visual Studio Code
\.vscode/
\.pytest_cache/
# PyCharm IDE
\.cache/
\.idea/

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -1,19 +0,0 @@
@echo off
echo " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "
echo " ____ ____ ______ __ __ __ _____ "
echo " / __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ / "
echo " / __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ < "
echo " / /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ / "
echo " /_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/ "
echo " German BOS Information Script "
echo " by Bastian Schroll "
echo " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "
echo.
echo Run 'count lines of code' ...
echo.
cd ..
_bin\win\cloc_1_72\cloc-1.72.exe . --exclude-lang=XML --exclude-dir=_docu,_config,_info,doxygen.ini --by-file-by-lang
echo.
echo.
pause

View file

@ -1,19 +0,0 @@
@echo off
echo " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "
echo " ____ ____ ______ __ __ __ _____ "
echo " / __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ / "
echo " / __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ < "
echo " / /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ / "
echo " /_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/ "
echo " German BOS Information Script "
echo " by Bastian Schroll "
echo " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "
echo.
echo Build Doxygen Documentation
echo.
cd ..
_bin\win\doxygen\doxygen.exe _gen/doxygen.ini
echo.
echo.
pause

View file

@ -1,45 +0,0 @@
@echo off
cd ..
if not exist "log/" mkdir log
echo " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "
echo " ____ ____ ______ __ __ __ _____ "
echo " / __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ / "
echo " / __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ < "
echo " / /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ / "
echo " /_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/ "
echo " German BOS Information Script "
echo " by Bastian Schroll "
echo " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "
echo.
echo BOSWatch 3 Unittest framework
echo.
echo Which test? [ENTER] for all
echo Or name a specific test test_[###].py
echo.
set /p test=Testcase:
if "%test%" == "" (
goto start
) else (
goto start_spec
)
:start
echo.
python -m pytest -c "_gen/pytest.ini"
echo.
echo --- Hit any key to repeat ---
pause
cls
goto start
:start_spec
echo.
python -m pytest test/test_%test%.py -c "_gen/pytest.ini"
echo.
echo --- Hit any key to repeat ---
pause
cls
goto start_spec

View file

@ -1,46 +0,0 @@
## Generatoren
Im Verzeichnis `_gen/` befinden sich Windows Batch-Scripte um bestimmt Aufgaben zu
vereinfachen und zu automatisieren.
---
### cloc.bat
`CLoC` steht für Count Lines of Code
Dieses Tool erstellt einen kurzen Report über die Anzahl der Dateien, Codezeilen,
Kommentare und Leerzeilen sortiert nach jeweiliger Programmiersprache
---
### doxygen.bat
Doxygen ist ein Dokumentationswerkzeug zum automatischen dokumentieren von Quellcode.
Nach dem ausführen wird der gesamte Quellcode geparst und eine HTML Dokumentation
im Verzeichnis `_docu/html/` angelegt.
Die Konfigurations Datei für Doxygen findet sich unter `_gen/doxygen.ini`
---
### pytest.bat
pytest ist ein Python Testframework
Damit ist es möglich, automatisierte Tests laufen zu lassen.
Vorher müssen die benötigten Plugins welche unter `_info/requirements.txt` gelistet sind
mittels `pip` installiert werden.
Nach dem Start kann man mit einem Druck auf `[ENTER]` direkt alle bekannten Tests
laufen lassen, oder durch die Eingabe eines spezifischen Tests auch nur diesen
ausführen. Die Tests werden dabei in zufälliger Reihenfolge abgearbeitet um auch
Fehler durch Abhängigkeiten voneinander zu erfassen.
Die Testfälle befinden sich im Unterordner `test/`
Einzeltests werden durch Eingabe des Namens ohne `test_` und `.py` aufgerufen.
Zum Beispiel `decoder` statt `test_decoder.py`
Zusätzlich werden alle Quellcode Dateien mittels eines PEP8 Parsers auf die Einhaltung
der Code-Sytel Vorgaben von Python hin untersucht und etwaige Fehler ausgegeben.
Vom Testverlauf wird ein Logfile erstellt welches in `log/test.log` befindet.
Die Konfigurationsdatei für pytest findet sich unter `_gen/pytest.ini`

View file

View file

@ -1,117 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
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.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice

View file

@ -1,88 +0,0 @@
## Eigene Module und Plugins schreiben
Um ein eigenes Modul oder Plugin zu schreiben, sollte man sich
am besten zuerst einmal das das `template` im entsprechenden Ordner ansehen.
Dies kann als Vorlage für das eigene Plugin genutzt werden.
### 1 Informationen anpassen
- Dateikopf anpassen
### 2 Benötigte Methoden überschreiben
#### 2.1 Modul
Die Modul Basisklasse bietet einige Methoden, welche vom Modul überschrieben werden können.
- `onLoad()` wird direkt beim Import des Moduls ausgeführt
- `doWork(bwPacket)` wird bei der Ausführung aufgerufen
- `onUnload()` wird beim Zerstören der Plugin Modul zum Programmende ausgeführt
#### 2.2 Plugin
Die Plugin Basisklasse bietet einige Methoden, welche vom Plugin überschrieben werden können.
- `onLoad()` wird direkt beim Import des Plugins ausgeführt
- `setup()` wird vor jeder Ausführung gerufen
- `fms(bwPacket)` wird bei einem FMS Paket ausgeführt
- `pocsag(bwPacket)` wird bei einem POCSAG Paket ausgeführt
- `zvei(bwPacket)` wird bei einem ZVEI Packet ausgeführt
- `msg(bwPacket)` wird bei einem Nachrichten Packet ausgeführt
- `teardown()` wird nach jeder Ausführung gerufen
- `onUnload()` wird beim Zerstören der Plugin Instanz zum Programmende ausgeführt
### 3 Konfiguration
#### 3.1 Konfiguration anlegen
Jedes Modul oder Plugin wird in einem Router folgendermaßen deklariert:
```yaml
- type: module # oder plugin
name: template_module # Name der Python Datei
config: # config-Sektion
option1: value 1
option2: value 2
underOption1: value 21
underOption2: value 22
list:
- list 1
- list 2
```
Eine entsprechende Dokumentation der Parameter ist in der Config-Readme zu hinterlegen.
#### 3.2 Konfiguration nutzen
Wird der Instanz eine Konfiguration übergeben wird diese in `self.config`
abgelegt und kann folgendermaßen abgerufen werden:
- `self.config.get("option1")` einzelnes Feld
- liefert `value 1`
- `self.config.get("option2", "underOption1")` verschachteltes Feld (beliebig viele möglich)
- liefert `value 21`
- `self.config.get("notSet", default="defValue")` Es kann ein Default Wert angegeben werden (wenn Eintrag in Config fehlt)
- liefert `defValue`
- `for item in self.config.get(FIELD):` Über Listen kann iteriert werden
- liefert ein Element je Durchgang - hier `list1` und `list2`
Wird ein End-Wert ausgelesen, wird dieser direkt zurück gegeben.
Sollten weitere Unterelemente oder eine Liste exisitieren
wird erneut ein Element der Klasse `Config()` zurück gegeben
### 4 Arbeiten mit dem bwPacket
An das Modul bzw. Plugin wird eine Instanz eines BOSWatch-Packet Objekts übergeben.
Aus dieser kann mittels `bwPacket.get(FIELDNAME)` das entsprechende Feld
ausgelesen werden.
Mittels `bwPacket.set(FIELDNAME, VALUE)` kann es hinzugefügt/modifiziert werden.
Eine Auflistung der bereitgestellten Informationen
findet sich im entsprechenden BOSWatch-Packet Dokument.
#### 4.1 Zu beachten bei Module
Module können Pakete beliebig verändern.
Diese Änderungen werden im Router entsprechend weitergeleitet.
Mögliche Rückgabewerte eines Moduls:
- `return bwPacket` gibt das modifizierte bwPacket an den Router zurück
- `return None` Router fährt mit dem unveränderten bwPacket fort (Input = Output)
- `return False` Router stopt sofort die Ausführung (zB. in Filtern verwendet)
#### 4.2 Zu beachten bei Plugins
Plugins geben keine Pakete mehr zurück. Sie fungieren ausschließlich als Endpunkt.
Die Plugin Basisklasse liefert intern immer ein `None` an den Router zurück,
was zur weiteren Ausführung des Routers führt.
### 5 Wildcards parsen (NUR IN PLUGIN)
Das parsen der Wildcars funktioniert komfortabel über die interne Methode `self.parseWildcards(MSG)`.
Die Platzhalter für die Wildcards findet man in `boswatch/utils/wildcard.py` oder in der `packet.md`.

View file

@ -1,289 +0,0 @@
## Format of the BOSWatch packets
<table>
<tr>
<td>field</td>
<td>fms</td>
<td>pocsag</td>
<td>zvei</td>
<td>msg</td>
<td>wildcard</td>
<td>description</td>
</tr>
<tr>
<td>serverName</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{SNAME}</td>
<td>name of the boswatch server instance</td>
</tr>
<tr>
<td>serverVersion</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{SVERS}</td>
<td>in case of new version, server can notify</td>
</tr>
<tr>
<td>serverBuildDate</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{SDATE}</td>
<td></td>
</tr>
<tr>
<td>serverBranch</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{SBRCH}</td>
<td></td>
</tr>
<tr>
<td>clientName</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{CNAME}</td>
<td>name of the boswatch client instance</td>
</tr>
<tr>
<td>clientIP</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{CIP}</td>
<td></td>
</tr>
<tr>
<td>clientVersion</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{CVERS}</td>
<td>in case of new version, server can notify</td>
</tr>
<tr>
<td>clientBuildDate</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{CDATE}</td>
<td></td>
</tr>
<tr>
<td>clientBranch</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{CBRCH}</td>
<td></td>
</tr>
<tr>
<td>inputSource</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{INSRC}</td>
<td>(stick, audio)</td>
</tr>
<tr>
<td>timestamp</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{TIMES}</td>
<td></td>
</tr>
<tr>
<td>frequency</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{FREQ}</td>
<td></td>
</tr>
<tr>
<td>mode</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>{MODE}</td>
<td>(fms, pocsag, zvei, msg)</td>
</tr>
<tr>
<td>descriptionShort</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td></td>
<td>{DESCS}</td>
<td>loaded from optional CSV file</td>
</tr>
<tr>
<td>descriptionLong</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td></td>
<td>{DESCL}</td>
<td>loaded from optional CSV file</td>
</tr>
<tr>
<td>bitrate</td>
<td></td>
<td>X</td>
<td></td>
<td></td>
<td>{BIT}</td>
<td></td>
</tr>
<tr>
<td>ric</td>
<td></td>
<td>X</td>
<td></td>
<td></td>
<td>{RIC}</td>
<td></td>
</tr>
<tr>
<td>subric</td>
<td></td>
<td>X</td>
<td></td>
<td></td>
<td>{SRIC}</td>
<td>(1, 2, 3, 4)</td>
</tr>
<tr>
<td>subricText</td>
<td></td>
<td>X</td>
<td></td>
<td></td>
<td>{SRICT}</td>
<td>(a, b, c, d)</td>
</tr>
<tr>
<td>message</td>
<td></td>
<td>X</td>
<td></td>
<td>X</td>
<td>{MSG}</td>
<td></td>
</tr>
<tr>
<td>tone</td>
<td></td>
<td></td>
<td>X</td>
<td></td>
<td>{TONE}</td>
<td>5-tone sequence</td>
</tr>
<tr>
<td>fms</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>{FMS}</td>
<td></td>
</tr>
<tr>
<td>service</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>{SERV}</td>
<td></td>
</tr>
<tr>
<td>country</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>{COUNT}</td>
<td></td>
</tr>
<tr>
<td>location</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>{LOC}</td>
<td></td>
</tr>
<tr>
<td>vehicle</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>{VEHC}</td>
<td></td>
</tr>
<tr>
<td>status</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>{STAT}</td>
<td></td>
</tr>
<tr>
<td>direction</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>{DIR}</td>
<td></td>
</tr>
<tr>
<td>dirextionText</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>{DIRT}</td>
<td>(Fhz-&gt;Lst, Lst-&gt;Fhz)</td>
</tr>
<tr>
<td>tacticalInfo</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>{TACI}</td>
<td>(I, II, III, IV)</td>
</tr>
</table>
<br><br>
### Other possible wildcards:
- {BR} - Line break (\\r\\n)
- {LPAR} - Left parenthesis (
- {RPAR} - Right parenthesis )
- {TIME} - Actual timestamp

View file

@ -1,29 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""!
____ ____ ______ __ __ __ _____
/ __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ /
/ __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ <
/ /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ /
/_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/
German BOS Information Script
by Bastian Schroll
@file: watchdog.py
@date: ##.##.2018
@author: Bastian Schroll
@description: Watchdog to _check if BOSWatch client, server, rtl_fm or multimon-ng is still running
"""
import logging
logging.debug("- %s loaded", __name__)
class Watchdog:
"""!Class for an Watchdog to observe,
if needed subprocess still running"""
def __init__(self):
"""!Create a new instance"""
pass

View file

@ -34,6 +34,7 @@ class ConfigYAML:
yield item
def __str__(self):
"""!Returns the string representation of the internal config dict"""
return str(self._config)
def loadConfigFile(self, configPath):
@ -54,6 +55,12 @@ class ConfigYAML:
return False
def get(self, *args, default=None):
"""!Get a single value from the config
or a value set in a new configYAML class instance
@param *args: Config section (one ore more strings)
@param default: Default value if section not found (None)
@return: A single value, a value set in an configYAML instance, the default value"""
tmp = self._config
try:
for arg in args:
@ -62,5 +69,5 @@ class ConfigYAML:
return ConfigYAML(tmp)
else:
return tmp
except AttributeError:
except AttributeError: # pragma: no cover
return default

View file

@ -16,9 +16,9 @@
"""
import logging
from boswatch.decoder.fmsdecoder import FmsDecoder
from boswatch.decoder.pocsagdecoder import PocsagDecoder
from boswatch.decoder.zveidecoder import ZveiDecoder
from boswatch.decoder.fmsDecoder import FmsDecoder
from boswatch.decoder.pocsagDecoder import PocsagDecoder
from boswatch.decoder.zveiDecoder import ZveiDecoder
logging.debug("- %s loaded", __name__)
@ -32,6 +32,7 @@ class Decoder:
@param data: data to decode
@return bwPacket instance"""
logging.debug("search decoder")
data = str(data)
if "FMS" in data:
return FmsDecoder.decode(data)
elif "POCSAG" in data:
@ -39,5 +40,5 @@ class Decoder:
elif "ZVEI" in data:
return ZveiDecoder.decode(data)
else:
logging.error("no decoder found for: %s", data)
logging.warning("no decoder found for: %s", data)
return None

View file

@ -70,20 +70,20 @@ class PocsagDecoder:
@return bitrate
@return ric
@return subric"""
bitrate, ric, subric = 0, 0, 0
bitrate, ric, subric = "0", "0", "0"
if "POCSAG512:" in data:
bitrate = 512
bitrate = "512"
ric = data[20:27].replace(" ", "").zfill(7)
subric = str(int(data[39]) + 1)
elif "POCSAG1200:" in data:
bitrate = 1200
bitrate = "1200"
ric = data[21:28].replace(" ", "").zfill(7)
subric = str(int(data[40]) + 1)
elif "POCSAG2400:" in data:
bitrate = 2400
bitrate = "2400"
ric = data[21:28].replace(" ", "").zfill(7)
subric = str(int(data[40]) + 1)

View file

@ -99,7 +99,7 @@ class BroadcastServer:
self._serverShutdown = False
self._servePort = servePort
def __del__(self):
def __del__(self): # pragma: no cover
if self.isRunning:
self.stop()
while self.isRunning:

View file

@ -16,9 +16,12 @@
"""
import logging
import socket
import select
logging.debug("- %s loaded", __name__)
HEADERSIZE = 10
class TCPClient:
"""!TCP client class"""
@ -27,8 +30,8 @@ class TCPClient:
"""!Create a new instance
@param timeout: timeout for the client in sec. (3)"""
self._sock = None
self._timeout = timeout
socket.setdefaulttimeout(timeout)
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self, host="localhost", port=8080):
"""!Connect to the server
@ -38,17 +41,14 @@ class TCPClient:
@return True or False"""
try:
if not self.isConnected:
self._sock = socket
self._sock.setdefaulttimeout(self._timeout)
self._sock = socket.create_connection((host, port))
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect((host, port))
logging.debug("connected to %s:%s", host, port)
return True
logging.warning("client always connected")
return True
except ConnectionRefusedError:
logging.error("cannot connect to %s:%s - connection refused", host, port)
except socket.timeout: # pragma: no cover
logging.warning("cannot connect to %s:%s - timeout after %s sec", host, port, self._timeout)
except socket.error as e:
logging.error(e)
return False
def disconnect(self):
@ -58,13 +58,12 @@ class TCPClient:
try:
if self.isConnected:
self._sock.close()
self._sock = None
logging.debug("disconnected")
return True
logging.warning("client not connected")
logging.warning("client always disconnected")
return True
except AttributeError:
logging.error("cannot disconnect - no connection established")
except socket.error as e:
logging.error(e)
return False
def transmit(self, data):
@ -74,13 +73,12 @@ class TCPClient:
@return True or False"""
try:
logging.debug("transmitting: %s", data)
self._sock.sendall(bytes(data + "\n", "utf-8"))
header = str(len(data)).ljust(HEADERSIZE)
self._sock.sendall(bytes(header + data, "utf-8"))
logging.debug("transmitted...")
return True
except AttributeError:
logging.error("cannot transmit - no connection established")
except ConnectionResetError:
logging.error("cannot transmit - host closed connection")
except socket.error as e:
logging.error(e)
return False
def receive(self):
@ -88,20 +86,30 @@ class TCPClient:
@return received data"""
try:
received = str(self._sock.recv(1024), "utf-8")
logging.debug("received: %s", received)
read, _, _ = select.select([self._sock], [], [], 1)
if not read: # check if there is something to read
return False
header = self._sock.recv(HEADERSIZE)
if not len(header): # check if there data
return False
length = int(header.decode("utf-8").strip())
received = self._sock.recv(length).decode("utf-8")
logging.debug("received %d bytes: %s", length, received)
return received
except AttributeError:
logging.error("cannot receive - no connection established")
except ConnectionResetError:
logging.error("cannot receive - host closed connection")
except socket.timeout: # pragma: no cover
logging.warning("cannot receive - timeout after %s sec", self._timeout)
except socket.error as e:
logging.error(e)
return False
@property
def isConnected(self):
"""!Property of client connected state"""
if self._sock:
try:
aliveMsg = "<alive>"
header = str(len(aliveMsg)).ljust(HEADERSIZE)
self._sock.sendall(bytes(header + aliveMsg, "utf-8"))
return True
except socket.error as e:
if e.errno is 32: # broken pipe - no one will read from this pipe anymore
return False
logging.error(e)
return False

View file

@ -15,14 +15,18 @@
@description: Class implementation for a threaded TCP socket server
"""
import logging
import socket
import socketserver
import threading
import time
import select
logging.debug("- %s loaded", __name__)
HEADERSIZE = 10
class _ThreadedTCPRequestHandler(socketserver.ThreadingMixIn, socketserver.BaseRequestHandler):
class _ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
"""!ThreadedTCPRequestHandler class for our TCPServer class."""
def handle(self):
@ -33,26 +37,41 @@ class _ThreadedTCPRequestHandler(socketserver.ThreadingMixIn, socketserver.BaseR
self.server.clientsConnected[threading.current_thread().name] = {"address": self.client_address[0], "timestamp": time.time()}
logging.info("Client connected: %s", self.client_address[0])
data = 1 # to enter while loop
cur_thread = threading.current_thread().name
req_name = str(cur_thread) + " " + self.client_address[0]
try:
while data:
data = str(self.request.recv(1024).strip(), 'utf-8')
if data != "":
logging.debug("%s recv: %s", req_name, data)
while self.server.isActive:
read, _, _ = select.select([self.request], [], [], 0.5)
if not read:
continue # nothing to read on the socket
# add a new entry and the decoded data dict as an string in utf-8 and an timestamp
self.server.alarmQueue.put_nowait((self.client_address[0], data, time.time())) # queue is threadsafe
logging.debug("Add data to queue")
header = self.request.recv(HEADERSIZE)
if not len(header):
break # empty data -> socked closed
logging.debug("%s send: [ack]", req_name)
self.request.sendall(bytes("[ack]", "utf-8"))
length = int(header.decode("utf-8").strip())
data = self.request.recv(length).decode("utf-8")
if data == "<alive>":
continue
logging.debug("%s recv %d bytes: %s", req_name, length, data)
# add a new entry and the decoded data dict as an string in utf-8 and an timestamp
self.server.alarmQueue.put_nowait((self.client_address[0], data, time.time())) # queue is threadsafe
logging.debug("Add data to queue")
logging.debug("%s send: [ack]", req_name)
data = "[ack]"
header = str(len(data)).ljust(HEADERSIZE)
self.request.sendall(bytes(header + data, "utf-8"))
self.request.close()
except (ConnectionResetError, ConnectionAbortedError): # pragma: no cover
logging.debug("%s connection closed", req_name)
except socket.error as e:
logging.error(e)
return False
finally:
del self.server.clientsConnected[threading.current_thread().name]
logging.info("Client disconnected: %s", self.client_address[0])
@ -96,9 +115,11 @@ class TCPServer:
@return True or False"""
if not self.isRunning:
try:
socketserver.TCPServer.allow_reuse_address = False # because we can start two instances on same port elsewhere
self._server = _ThreadedTCPServer(("", port), _ThreadedTCPRequestHandler)
self._server.timeout = self._timeout
self._server.alarmQueue = self._alarmQueue
self._server.isActive = True
self._server.clientsConnectedLock = self._clientsConnectedLock
self._server.clientsConnected = self._clientsConnected
@ -109,9 +130,9 @@ class TCPServer:
self._server_thread.start()
logging.debug("TCPServer started in Thread: %s", self._server_thread.name)
return True
except OSError:
logging.exception("Socket Error")
except socket.error as e:
logging.error(e)
return False
else:
logging.warning("server always started")
return True
@ -122,6 +143,7 @@ class TCPServer:
@return True or False"""
if self.isRunning:
self._server.shutdown()
self._server.isActive = False
self._server_thread.join()
self._server_thread = None
self._server = None

View file

@ -16,7 +16,6 @@
"""
import logging
import time
from boswatch import version
logging.debug("- %s loaded", __name__)
@ -58,38 +57,6 @@ class Packet:
logging.warning("field not found: %s", fieldName)
return None
def addClientData(self, config):
"""!Add the client information to the decoded data
This function adds the following data to the bwPacket:
- clientName
- clientVersion
- clientBuildDate
- clientBranch
- inputSource
- frequency"""
logging.debug("add client data to bwPacket")
self.set("clientName", config.get("client", "name"))
self.set("clientVersion", version.client)
self.set("clientBuildDate", version.date)
self.set("clientBranch", version.branch)
self.set("inputSource", config.get("client", "inoutSource"))
self.set("frequency", config.get("inputSource", "sdr", "frequency"))
def addServerData(self, config):
"""!Add the server information to the decoded data
This function adds the following data to the bwPacket:
- serverName
- serverVersion
- serverBuildDate
- serverBranch"""
logging.debug("add server data to bwPacket")
self.set("serverName", config.get("server", "name"))
self.set("serverVersion", version.server)
self.set("serverBuildDate", version.date)
self.set("serverBranch", version.branch)
def printInfo(self):
"""!Print a info message to the log on INFO level.
Contains the most useful info about this packet.

144
boswatch/processManager.py Normal file
View file

@ -0,0 +1,144 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""!
____ ____ ______ __ __ __ _____
/ __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ /
/ __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ <
/ /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ /
/_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/
German BOS Information Script
by Bastian Schroll
@file: processManager.py
@date: 04.03.2018
@author: Bastian Schroll
@description: Class for managing sub processes
"""
import logging
import subprocess
logging.debug("- %s loaded", __name__)
class ProcessManager:
"""!class to manage a extern sub process"""
def __init__(self, process, textMode=False):
logging.debug("create process instance %s - textMode: %s", process, textMode)
self._args = []
self._args.append(process)
self._stdin = None
self._stdout = subprocess.PIPE
self._stderr = subprocess.STDOUT
self._processHandle = None
self._textMode = textMode
def __del__(self):
self.stop()
def addArgument(self, arg):
"""!add a new argument
@param arg: argument to add as string"""
logging.debug("add argument to process: %s -> %s", self._args[0], arg)
for splitArg in arg.split():
self._args.append(splitArg)
def clearArguments(self):
"""!clear all arguments"""
self._args = self._args[0:1] # kept first element (process name)
def start(self):
"""!start the new process
@return: True or False"""
logging.debug("start new process: %s %s", self._args[0], self._args[1:])
try:
self._processHandle = subprocess.Popen(self._args,
stdin=self._stdin,
stdout=self._stdout,
stderr=self._stderr,
universal_newlines=self._textMode,
shell=False)
if not self.isRunning:
logging.error("cannot start process")
return False
logging.debug("process started with PID %d", self._processHandle.pid)
return True
except FileNotFoundError:
logging.error("File not found: %s", self._args[0])
return False
def stop(self):
"""!Stop the process by sending SIGTERM and wait for ending"""
logging.debug("stopping process: %s", self._args[0])
if self.isRunning:
self._processHandle.terminate()
while self.isRunning:
pass
logging.debug("process %s returned %d", self._args[0], self._processHandle.returncode)
def readline(self):
"""!Read one line from stdout stream
@return singe line or None"""
if self.isRunning and self._stdout is not None:
try:
line = self._processHandle.stdout.readline().strip()
except UnicodeDecodeError:
return None
return line
return None
def skipLines(self, lineCount=1):
"""!Skip given number of lines from the output
@param lineCount: number of lines to skip
"""
logging.debug("skip %d lines from output", lineCount)
while self.isRunning and lineCount:
self.readline()
lineCount -= 1
def skipLinesUntil(self, matchText):
"""!Skip lines from the output until the given string is in it
@param matchText: string to search for in output
"""
logging.debug("skip lines till '%s' from output", matchText)
if not self._textMode:
matchText = bytes(matchText, "utf-8")
while self.isRunning and matchText not in self.readline():
pass
def setStdin(self, stdin):
"""!Set the stdin stream instance"""
self._stdin = stdin
def setStdout(self, stdout):
"""!Set the stdout stream instance"""
self._stdout = stdout
def setStderr(self, stderr):
"""!Set the stderr stream instance"""
self._stderr = stderr
@property
def stdout(self):
"""!Property to get the stdout stream"""
return self._processHandle.stdout
@property
def stderr(self):
"""!Property to get the stderr stream"""
return self._processHandle.stderr
@property
def isRunning(self):
"""!Property to get process running state
@return True or False"""
if self._processHandle:
if self._processHandle.poll() is None:
return True
return False

View file

@ -58,7 +58,7 @@ class Router:
bwPacket = bwPacket_tmp
logging.debug("[%s] <- bwPacket returned: %s", self._name, bwPacket)
logging.debug("[%s] ended", self._name)
logging.debug("[%s] finished", self._name)
return bwPacket
@property

View file

@ -109,6 +109,8 @@ class RouterManager:
for routerName in routerRunList:
if routerName in self._routerDict:
self._routerDict[routerName].runRouter(bwPacket)
else:
logging.warning("unknown router: %s", routerName)
def _showRouterRoute(self):
"""!Show the routes of all routers"""

View file

@ -17,7 +17,7 @@
import logging
import platform # for python version nr
import boswatch.version
from boswatch.utils import version
logging.debug("- %s loaded", __name__)
@ -43,19 +43,19 @@ def infoToLog():
@return True or False on error"""
logging.debug("BOSWatch and environment information")
logging.debug("- Client version: %d.%d.%d",
boswatch.version.client["major"],
boswatch.version.client["minor"],
boswatch.version.client["patch"])
version.client["major"],
version.client["minor"],
version.client["patch"])
logging.debug("- Server version: %d.%d.%d",
boswatch.version.server["major"],
boswatch.version.server["minor"],
boswatch.version.server["patch"])
version.server["major"],
version.server["minor"],
version.server["patch"])
logging.debug("- Branch: %s",
boswatch.version.branch)
version.branch)
logging.debug("- Release date: %02d.%02d.%4d",
boswatch.version.date["day"],
boswatch.version.date["month"],
boswatch.version.date["year"])
version.date["day"],
version.date["month"],
version.date["year"])
logging.debug("- Python version: %s", platform.python_version())
logging.debug("- Python build: %s", platform.python_build())
logging.debug("- System: %s", platform.system())

54
boswatch/utils/misc.py Normal file
View file

@ -0,0 +1,54 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""!
____ ____ ______ __ __ __ _____
/ __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ /
/ __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ <
/ /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ /
/_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/
German BOS Information Script
by Bastian Schroll
@file: misc.py
@date: 11.03.2019
@author: Bastian Schroll
@description: Some misc functions
"""
import logging
from boswatch.utils import version
logging.debug("- %s loaded", __name__)
def addClientDataToPacket(bwPacket, config):
"""!Add the client information to the decoded data
This function adds the following data to the bwPacket:
- clientName
- clientVersion
- clientBuildDate
- clientBranch
- inputSource
- frequency"""
logging.debug("add client data to bwPacket")
bwPacket.set("clientName", config.get("client", "name"))
bwPacket.set("clientVersion", version.client)
bwPacket.set("clientBuildDate", version.date)
bwPacket.set("clientBranch", version.branch)
bwPacket.set("inputSource", config.get("client", "inputSource"))
bwPacket.set("frequency", config.get("inputSource", "sdr", "frequency"))
def addServerDataToPacket(bwPacket, config):
"""!Add the server information to the decoded data
This function adds the following data to the bwPacket:
- serverName
- serverVersion
- serverBuildDate
- serverBranch"""
logging.debug("add server data to bwPacket")
bwPacket.set("serverName", config.get("server", "name"))
bwPacket.set("serverVersion", version.server)
bwPacket.set("serverBuildDate", version.date)
bwPacket.set("serverBranch", version.branch)

View file

@ -22,6 +22,9 @@ import time
logging.debug("- %s loaded", __name__)
# todo check function and document + write an test
# todo maybe can be a module instead of a native boswatch piece
# idea: maybe this can be a class with a register_wildcard() method
# so the list with wildcards can be modified by other modules
def replaceWildcards(message, bwPacket):
@ -38,6 +41,7 @@ def replaceWildcards(message, bwPacket):
"{SVERS}": bwPacket.getField("serverVersion"),
"{SDATE}": bwPacket.getField("serverBuildDate"),
"{SBRCH}": bwPacket.getField("serverBranch"),
# client
"{CNAME}": bwPacket.getField("clientName"),
"{CIP}": bwPacket.getField("clientIP"),
@ -50,8 +54,6 @@ def replaceWildcards(message, bwPacket):
"{TIMES}": bwPacket.getField("mode"),
"{FREQ}": bwPacket.getField("frequency"),
"{MODE}": bwPacket.getField("mode"),
"{DESCS}": bwPacket.getField("descriptionShort"),
"{DESCL}": bwPacket.getField("descriptionLong"),
# fms wildcards
"{FMS}": bwPacket.getField("fms"),

11
build_docu.sh Normal file
View file

@ -0,0 +1,11 @@
#!/bin/bash
echo "clean api documentation"
rm -r docu/docs/api/html
echo "generate api documentation"
doxygen docu/doxygen.ini
echo "build documentation"
source ./venv/bin/activate
python3 -m mkdocs build -f docu/mkdocs.yml
deactivate

View file

@ -32,8 +32,10 @@ logging.debug("BOSWatch client has started ...")
logging.debug("Import python modules")
import argparse
logging.debug("- argparse")
import subprocess
logging.debug("- subprocess")
import threading
logging.debug("- threading")
import queue
logging.debug("- queue")
import time
logging.debug("- time")
@ -41,8 +43,10 @@ logging.debug("Import BOSWatch modules")
from boswatch.configYaml import ConfigYAML
from boswatch.network.client import TCPClient
from boswatch.network.broadcast import BroadcastClient
from boswatch.processManager import ProcessManager
from boswatch.decoder.decoder import Decoder
from boswatch.utils import header
from boswatch.utils import misc
header.logoToLog()
@ -56,6 +60,7 @@ parser = argparse.ArgumentParser(prog="bw_client.py",
epilog="""More options you can find in the extern client.ini
file in the folder /config""")
parser.add_argument("-c", "--config", help="Name to configuration File", required=True)
parser.add_argument("-t", "--test", help="Start Client with testdata-set")
args = parser.parse_args()
bwConfig = ConfigYAML()
@ -63,10 +68,8 @@ if not bwConfig.loadConfigFile(paths.CONFIG_PATH + args.config):
logging.error("cannot load config file")
exit(1)
# ############################# begin client system
# ========== CLIENT CODE ==========
try:
ip = bwConfig.get("server", "ip", default="127.0.0.1")
port = bwConfig.get("server", "port", default="8080")
@ -76,41 +79,101 @@ try:
ip = broadcastClient.serverIP
port = broadcastClient.serverPort
inputQueue = queue.Queue()
inputThreadRunning = True
# ========== INPUT CODE ==========
def handleSDRInput(dataQueue, sdrConfig, decoderConfig): # todo exception handling inside
sdrProc = ProcessManager(str(sdrConfig.get("rtlPath", default="rtl_fm")))
sdrProc.addArgument("-d " + str(sdrConfig.get("device", default="0"))) # device id
sdrProc.addArgument("-f " + sdrConfig.get("frequency")) # frequencies
sdrProc.addArgument("-p " + str(sdrConfig.get("error", default="0"))) # frequency error in ppm
sdrProc.addArgument("-l " + str(sdrConfig.get("squelch", default="1"))) # squelch
sdrProc.addArgument("-g " + str(sdrConfig.get("gain", default="100"))) # gain
sdrProc.addArgument("-M fm") # set mode to fm
sdrProc.addArgument("-E DC") # set DC filter
sdrProc.addArgument("-s 22050") # bit rate of audio stream
sdrProc.start()
sdrProc.skipLinesUntil("Output at")
mmProc = ProcessManager(str(sdrConfig.get("mmPath", default="multimon-ng")), textMode=True)
if decoderConfig.get("fms", default=0):
mmProc.addArgument("-a FMSFSK")
if decoderConfig.get("zvei", default=0):
mmProc.addArgument("-a ZVEI1")
if decoderConfig.get("poc512", default=0):
mmProc.addArgument("-a POCSAG512")
if decoderConfig.get("poc1200", default=0):
mmProc.addArgument("-a POCSAG1200")
if decoderConfig.get("poc2400", default=0):
mmProc.addArgument("-a POCSAG2400")
mmProc.addArgument("-f alpha")
mmProc.addArgument("-t raw -")
mmProc.setStdin(sdrProc.stdout)
mmProc.start()
mmProc.skipLinesUntil("Available demodulators:")
logging.info("start decoding")
while inputThreadRunning:
if not sdrProc.isRunning:
logging.warning("rtl_fm was down - try to restart")
sdrProc.start()
sdrProc.skipLinesUntil("Output at") # last line form rtl_fm before data
elif not mmProc.isRunning:
logging.warning("multimon was down - try to restart")
mmProc.start()
mmProc.skipLinesUntil("Available demodulators:") # last line from mm before data
elif sdrProc.isRunning and mmProc.isRunning:
line = mmProc.readline()
if line:
dataQueue.put_nowait((line, time.time()))
logging.debug("Add data to queue")
print(line)
logging.debug("stopping thread")
mmProc.stop()
sdrProc.stop()
# ========== INPUT CODE ==========
mmThread = threading.Thread(target=handleSDRInput, name="mmReader", args=(inputQueue, bwConfig.get("inputSource", "sdr"), bwConfig.get("decoder")))
mmThread.daemon = True
mmThread.start()
bwClient = TCPClient()
if bwClient.connect(ip, port):
bwClient.connect(ip, port)
while 1:
testFile = open(paths.TEST_PATH + "testdata.list", "r")
if not bwClient.isConnected:
logging.warning("connection to server lost - sleep %d seconds", bwConfig.get("client", "reconnectDelay", default="3"))
time.sleep(bwConfig.get("client", "reconnectDelay", default="3"))
bwClient.connect(ip, port)
while 1:
elif not inputQueue.empty():
data = inputQueue.get()
logging.info("get data from queue (waited %0.3f sec.)", time.time() - data[1])
logging.debug("%s packet(s) still waiting in queue", inputQueue.qsize())
for testData in testFile:
bwPacket = Decoder.decode(data[0])
inputQueue.task_done()
if (len(testData.rstrip(' \t\n\r')) == 0) or ("#" in testData[0]):
continue
if bwPacket is None:
continue
logging.debug("Test: %s", testData)
bwPacket = Decoder.decode(testData)
if bwPacket:
bwPacket.printInfo()
bwPacket.addClientData(bwConfig)
bwClient.transmit(str(bwPacket))
# todo should we do this in an thread, to not block receiving ??? but then we should use transmit() and receive() with Lock()
failedTransmits = 0
while not bwClient.receive() == "[ack]": # wait for ack or timeout
if failedTransmits >= 3:
logging.error("cannot transmit after 3 retires")
break
failedTransmits += 1
logging.warning("attempt %d to resend packet", failedTransmits)
bwClient.transmit(str(bwPacket)) # try to resend
bwPacket.printInfo()
misc.addClientDataToPacket(bwPacket, bwConfig)
for sendCnt in range(bwConfig.get("client", "sendTries", default="3")):
bwClient.transmit(str(bwPacket))
if bwClient.receive() == "[ack-]":
logging.debug("ack ok")
break
logging.warning("cannot send packet - sleep %d seconds", bwConfig.get("client", "sendDelay", default="3"))
time.sleep(bwConfig.get("client", "sendDelay", default="3"))
else:
time.sleep(0.1) # reduce cpu load (wait 100ms)
# in worst case a packet have to wait 100ms until it will be processed
bwClient.disconnect()
break
# test for server ####################################
except KeyboardInterrupt: # pragma: no cover
logging.warning("Keyboard interrupt")
@ -118,5 +181,9 @@ except SystemExit: # pragma: no cover
logging.error("BOSWatch interrupted by an error")
except: # pragma: no cover
logging.exception("BOSWatch interrupted by an error")
finally: # pragma: no cover
logging.debug("BOSWatch has ended ...")
finally:
logging.debug("Starting shutdown routine")
bwClient.disconnect()
inputThreadRunning = False
mmThread.join()
logging.debug("BOSWatch client has stopped ...")

View file

@ -44,6 +44,7 @@ from boswatch.packet import Packet
from boswatch.utils import header
from boswatch.network.broadcast import BroadcastServer
from boswatch.router.routerManager import RouterManager
from boswatch.utils import misc
header.logoToLog()
@ -62,7 +63,7 @@ args = parser.parse_args()
bwConfig = ConfigYAML()
if not bwConfig.loadConfigFile(paths.CONFIG_PATH + args.config):
logging.error("cannot load config file")
logging.fatal("cannot load config file")
exit(1)
# ############################# begin server system
@ -70,10 +71,11 @@ try:
bwRoutMan = RouterManager()
if not bwRoutMan.buildRouter(bwConfig):
exit()
logging.fatal("Error while building routers")
exit(1)
bcServer = BroadcastServer()
if bwConfig.get("server", "useBroadcast", default=False):
bcServer = BroadcastServer()
bcServer.start()
incomingQueue = queue.Queue()
@ -93,7 +95,7 @@ try:
bwPacket = Packet((data[1]))
bwPacket.set("clientIP", data[0])
bwPacket.addServerData(bwConfig)
misc.addServerDataToPacket(bwPacket, bwConfig)
bwRoutMan.runRouter(bwConfig.get("alarmRouter"), bwPacket)
@ -105,20 +107,9 @@ except SystemExit: # pragma: no cover
logging.error("BOSWatch interrupted by an error")
except: # pragma: no cover
logging.exception("BOSWatch interrupted by an error")
finally: # pragma: no cover
try:
bwServer.stop()
except NameError:
pass
except:
raise
try:
bcServer.stop()
except NameError:
pass
except:
raise
logging.debug("BOSWatch has ended ...")
finally:
logging.debug("Starting shutdown routine")
del bwRoutMan
bwServer.stop()
bcServer.stop()
logging.debug("BOSWatch server has stopped ...")

View file

@ -11,6 +11,9 @@ client:
name: BW3 Client # name of the BW3 Client instance
inputSource: sdr # atm only 'sdr' is possible
useBroadcast: no # use broadcast to find server automatically
reconnectDelay: 3 # time in seconds to delay reconnect try
sendTries: 3 # how often should tried to send a packet
sendDelay: 3 # time in seconds to delay the resend try
server: # only used if useBroadcast = no
ip: 127.0.0.1
@ -19,10 +22,12 @@ server: # only used if useBroadcast = no
inputSource:
sdr:
device: 0
frequency: 85.000M
frequency: 85M
error: 0
squelch: 0
squelch: 1
gain: 100
rtlPath: /usr/bin/rtl_fm
mmPath: /opt/multimon/multimon-ng
decoder:
fms: yes

32
docu/docs/changelog.md Normal file
View file

@ -0,0 +1,32 @@
# <center>Changelog</center>
---
## Version [2.9.0] - date
Functions implemented in initial version:
- Multithreaded Server/Client infrastructure for alarm handling
- Client can auto fetch connection information over bradocast from server
- Easy configuration with YAML file for all components
- Simple module and plugin system to extend functionality
- Alarmpacket routing system for flexible chains of modules nd plugins
### Modules
- Mode filter to filter at specific packet types such as FMS, POCSAG, ZVEI or MSG packets
### Filter
---
Zum schreiben des Changelog's siehe: [http://keepachangelog.com/de/1.0.0/](http://keepachangelog.com/de/1.0.0/)
<!--
## Version [#.#.#] - date
### Added
### Changed
### Deprecated
### Removed
### Fixed
### Security
-->

View file

@ -1,52 +1,69 @@
## Konfiguration
# <center>Konfiguration</center>
Die Konfiguration von BOSWatch 3 ist im YAML Format abgelegt und wird nachfolgend beschrieben.
Die Konfiguration von BOSWatch 3 ist im YAML Format abgelegt und wird nachfolgend beschrieben.
Immer wenn für eine Einstellung ein **Default** Wert angegeben ist, muss diese Einstellung nicht
zwingend in die Konfiguration eingetragen werden.
## Client
### Client
Nachfolgend alle Paramater der Client Konfiguration
#### `client:`
---
### `client:`
|Feld|Beschreibung|Default|
|----|------------|-------|
|name|Name zur Identifizierung der Client Instanz||
|inoutSource|Art der zu nutzenden Input Quelle (aktuell nur `sdr`)||
|useBroadcast|Verbindungsdaten per Broadcast beziehen|no|
|inputSource|Art der zu nutzenden Input Quelle (aktuell nur `sdr`)|sdr|
|useBroadcast|Verbindungsdaten per [Broadcast](information/broadcast.md) beziehen|no|
|reconnectDelay|Verzögerung für erneuten Verbindungsversuch zum Server|3|
|sendTries|Anzahl der Sendeversuche eines Pakets|3|
|sendDelay|Verzögerung für einen erneuten Sendeversuch|3|
#### `server:`
Der Abschnitt `server:` wird nur genutzt, wenn `useBroadcast: no` gesetzt ist.
---
### `server:`
Der Abschnitt `server:` wird nur genutzt, wenn `useBroadcast: no` gesetzt ist.
Ansonsten wird versucht die Verbindungsdaten per Broadcast Paket direkt vom Server zu beziehen.
|Feld|Beschreibung|Default|
|----|------------|-------|
|ip|IP Adresse des Servers|127.0.0.1|
|port|Port des Sever|8080|
#### `inputSource:`
**Beispiel:**
```yaml
server:
ip: 10.10.10.2
port: 9123
```
---
### `inputSource:`
Aktuell gibt es nur `sdr:` als Input Quelle
##### `sdr:`
#### `sdr:`
|Feld|Beschreibung|Default|
|----|------------|-------|
|device|rtl_fm Device ID|0|
|frequency|Frequenz des Empfängers||
|frequency|Zu empfangende Frequenz||
|error|Frequenz Abweichung in ppm|0|
|squelch|Einstellung der Rauschsperre|0|
|squelch|Einstellung der Rauschsperre|1|
|gain|Verstärkung des Eingangssignals|100|
|rtlPath|Pfad zur rtl_fm Binary|rtl_fm|
|mmPath|Pfad zur multimon-ng Binary|multimon-ng|
Bsp:
**Beispiel:**
```yaml
inputSource:
sdr:
device: 0
frequency: 85.000M
frequency: 85M
error: 0
squelch: 0
squelch: 1
gain: 100
rtlPath: /usr/bin/rtl-fm
mmPath: /opt/multimon/multimon-ng
```
#### `decoder:`
---
### `decoder:`
|Feld|Beschreibung|Default|
|----|------------|-------|
|fms|FMS Decoder|no|
@ -56,44 +73,47 @@ inputSource:
|poc2400|POCSAG Decoder (Bitrate 2400)|no|
---
### Server
## Server
Nachfolgend alle Paramater der Server Konfiguration
#### `server:`
### `server:`
|Feld|Beschreibung|Default|
|----|------------|-------|
|port|Port auf dem der Server lauscht|8080
|name|Name zur Identifizierung der Server Instanz||
|useBroadcast|Verbindungsdaten per Broadcast Server bereitstellen|no|
#### `alarmRouter:`
---
### `alarmRouter:`
Enthält eine Liste der Router Namen, welche bei einem Alarm direkt gestartet werden sollen.
Bsp:
**Beispiel:**
```yaml
alarmRouter:
- Name des Routers
- ein weiter Router
- Name des Routers
- ein weiter Router
```
#### `router:`
Mit den Routern kann der Verarbeitungsweg eines Alarm-Paketes festgelegt werden.
Diese werden als Liste angegeben
---
### `router:`
Mit den Routern kann der Verarbeitungsweg eines Alarm-Paketes festgelegt werden. Es können beliebig viele Router in Form einer Liste angegeben werden.
|Feld|Beschreibung|Default|
|----|------------|-------|
|name|Name des Routers||
|route|Definiten des Routenverlaufs
Die einzelnen Routen werden wie folgt definiert
#### `route:`
Jeder Router kann eine beliebige Anzahl einzelner Routenpunkte enthalten. Diese werden innerhalb des Routers sequentiel abgearbeitet. Mögliche Typen der Routenpunkte sind dabei ein Modul, ein Plugin oder ein anderer Router. Sie werden ebenfalls in Form einer Liste definiert.
|Feld|Beschreibung|Default|
|----|------------|-------|
|type|Art des Routenpunktes (module, plugin, router)||
|name|Zu ladende Resource (vollständige Liste siehe !!!TBD!!!)||
|config|Konfigurationseinstellungen des Routenpunktes||
|name|Zu ladende Resource (Siehe entsprechende Kapitel)||
|config|Konfigurationseinstellungen des Routenpunktes (Siehe entsprechende Kapitel)||
Bsp:
**Beispiel:**
```yaml
router:
- name: Router 1
@ -106,22 +126,6 @@ router:
```
---
### Module
Nachfolgend alle Paramater der Modul Konfigurationen
#### `filter.modeFilter`
## Module/Plugins
|Feld|Beschreibung|Default|
|----|------------|-------|
|allowed|Liste der erlaubten Paket Typen `fms` `zvei` `pocsag`||
Bsp:
```yaml
config:
allowed:
- fms
- zvei
```
---
### Plugins
Nachfolgend alle Paramater der Plugin Konfigurationen
Die möglichen Einstellungen der einzelnen Module und Plugins sind im jeweiligen Kapitel aufgelistet.

View file

@ -0,0 +1,104 @@
# <center>Eigenes Modul/Plugin schreiben</center>
Um ein eigenes Modul oder Plugin zu schreiben, sollte man sich am besten zuerst einmal das das `template` im entsprechenden Ordner ansehen. Dies kann als Vorlage für das eigene Modul oder Plugin genutzt werden.
---
## Allgemeine Informationen
Im ersten Schritt sollte eine Kopie des jeweiligen Templates (Modul oder Plugin) erstellt werden. Nun sollten im Dateikopf die Angaben angepasst werden.
---
## Benötigte Methoden überschreiben
### Modul
Die Modul Basisklasse bietet einige Methoden, welche vom Modul überschrieben werden können.
- `onLoad()` wird direkt beim Import des Moduls ausgeführt
- `doWork(bwPacket)` wird bei der Ausführung aufgerufen
- `onUnload()` wird beim Zerstören der Plugin Modul zum Programmende ausgeführt
### Plugin
Die Plugin Basisklasse bietet einige Methoden, welche vom Plugin überschrieben werden können.
- `onLoad()` wird direkt beim Import des Plugins ausgeführt
- `setup()` wird vor jeder Ausführung gerufen
- `fms(bwPacket)` wird bei einem FMS Paket ausgeführt
- `pocsag(bwPacket)` wird bei einem POCSAG Paket ausgeführt
- `zvei(bwPacket)` wird bei einem ZVEI Packet ausgeführt
- `msg(bwPacket)` wird bei einem Nachrichten Packet ausgeführt
- `teardown()` wird nach jeder Ausführung gerufen
- `onUnload()` wird beim Zerstören der Plugin Instanz zum Programmende ausgeführt
---
## Konfiguration
### Konfiguration anlegen
Jedes Modul oder Plugin wird in einem Router folgendermaßen deklariert:
```yaml
- type: module # oder 'plugin'
name: template_module # Name der Python Datei (ohne .py)
config: # config-Sektion
option1: value 1
option2:
underOption1: value 21
underOption2: value 22
list:
- list 1
- list 2
```
Eine entsprechende Dokumentation der Parameter ist in der Dokumentation der [Konfiguration](../config.md) zu hinterlegen.
### Konfiguration verwenden
Wird der Instanz eine Konfiguration übergeben wird diese in `self.config` abgelegt und kann wie folgt abgerufen werden:
(Dies Ergebnisse beziehen sich auf das Konfigurationsbeispiel oben)
- Einzelnes Feld auslesen
`self.config.get("option1")`
> liefert `value 1`
- Verschachteltes Feld auslesen (beliebige tiefe möglich)
`self.config.get("option2", "underOption1")`
> liefert `value 21`
- Es kann ein Default Wert angegeben werden
`self.config.get("notSet", default="defValue")`
> liefert `defValue`
- Über Listen kann einfach iteriert werden
`for item in self.config.get(FIELD):`
> liefert ein Element je Iteration - hier `list 1` und `list 2`
Wird ein End-Wert ausgelesen, wird dieser direkt zurück gegeben.
Sollten weitere Unterelemente oder eine Liste exisitieren wird erneut ein Objekt der Klasse `Config()` zurück gegeben, auf welches wiederum nach obigem Schema zugegriffen werden kann.
---
## Arbeiten mit dem bwPacket
An das Modul bzw. Plugin wird eine Instanz eines BOSWatch-Paket Objekts übergeben.
Aus dieser kann mittels `bwPacket.get(FIELDNAME)` das entsprechende Feld ausgelesen werden.
Mittels `bwPacket.set(FIELDNAME, VALUE)` kann ein Wert hinzugefügt oder modifiziert werden.
Eine Auflistung der bereitgestellten Informationen findet sich im entsprechenden [BOSWatch Paket](packet.md) Dokumentation.
Bitte beachten:
- Selbst vom Modul hinzugefügte Felder **müssen** in der Modul Dokumentation unter `Paket Modifikation` aufgeführt werden.
- Sollte ein Modul oder Plugin Felder benutzen, welche in einem anderen Modul erstellt werden, **muss** dies im Punkt `Abhänigkeiten` des jeweiligen Moduls oder Plugins zu dokumentieren.
### Zu beachten bei Module
Module können Pakete beliebig verändern. Diese Änderungen werden im Router entsprechend weitergeleitet.
Mögliche Rückgabewerte eines Moduls:
- `return bwPacket` gibt das modifizierte bwPacket an den Router zurück
- `return None` Router fährt mit dem unveränderten bwPacket fort (Input = Output)
- `return False` Router stopt sofort die Ausführung (zB. in Filtern verwendet)
### Zu beachten bei Plugins
Plugins geben keine Pakete mehr zurück. Sie fungieren ausschließlich als Endpunkt.
Die Plugin Basisklasse liefert intern immer ein `None` an den Router zurück,
was zur weiteren Ausführung des Routers mit dem original Paket führt. Daher macht es in Plugins keinen Sinn ein Paket zu modifizieren.
---
## Richtiges Logging
tbd ...
---
## Wildcards parsen (Plugin only)
Das parsen der Wildcars funktioniert komfortabel über die interne Methode `self.parseWildcards(MSG)`.
Die Platzhalter der Wildcards findet man in der [BOSWatch Paket](packet.md) Dokumentation.

View file

@ -0,0 +1,60 @@
# <center>BOSWatch Packet Format</center>
Ein BOSWatch Datenpaket wird in einem Python Dict abgebildet. In der nachfolgenden Tabelle sind die genutzten Felder abgebildet.
---
## Allgemeine Informationen
|Feldname|FMS|POCSAG|ZVEI|MSG|Wildcard|Beschreibung|
|--------|:-:|:----:|:--:|:-:|--------|------------|
|serverName|X|X|X|X|`{SNAME}`|Name der BOSWatch Server Instanz|
|serverVersion|X|X|X|X|`{SVERS}`||
|serverBuildDate|X|X|X|X|`{SDATE}`||
|serverBranch|X|X|X|X|`{SBRCH}`||
|clientName|X|X|X|X|`{CNAME}`|Name der BOSWatch Client Instanz|
|clientIP|X|X|X|X|`{CIP}`||
|clientVersion|X|X|X|X|`{CVERS}`||
|clientBuildDate|X|X|X|X|`{CDATE}`||
|clientBranch|X|X|X|X|`{CBRCH}`||
|inputSource|X|X|X|X|`{INSRC}`|(sdr, audio)|
|timestamp|X|X|X|X|`{TIMES}`||
|frequency|X|X|X|X|`{FREQ}`||
|mode|X|X|X|X|`{MODE}`|(fms, pocsag, zvei, msg)|
---
## Speziell für POCSAG
|Feldname|FMS|POCSAG|ZVEI|MSG|Wildcard|Beschreibung|
|--------|:-:|:----:|:--:|:-:|--------|------------|
|bitrate||X|||`{BIT}`||
|ric||X|||`{RIC}`||
|subric||X|||`{SRIC}`|(1, 2, 3, 4)|
|subricText||X|||`{SRICT}`|(a, b, c, d)|
|message||X||X|`{MSG}`|Kann außerdem für ein Message Paket genutzt werden|
---
## Speziell für ZVEI
|Feldname|FMS|POCSAG|ZVEI|MSG|Wildcard|Beschreibung|
|--------|:-:|:----:|:--:|:-:|--------|------------|
|tone|||X||`{TONE}`|5-Ton Sequenz nach ZVEI|
---
## Speziell für FMS
|Feldname|FMS|POCSAG|ZVEI|MSG|Wildcard|Beschreibung|
|--------|:-:|:----:|:--:|:-:|--------|------------|
|fms|X||||`{FMS}`||
|service|X||||`{SERV}`||
|country|X||||`{COUNT}`||
|location|X||||`{LOC}`||
|vehicle|X||||`{VEC}`||
|status|X||||`{STAT}`||
|direction|X||||`{DIR}`||
|dirextionText|X||||`{DIRT}`|(Fhz->Lst, Lst->Fhz)|
|vehicle|X||||`{VEC}`||
|vehicle|X||||`{VEC}`||
|tacticalInfo|X||||`{TACI}`|(I, II, III, IV)|
---
## Weitere Wildcards
- `{BR}` - Zeilenumbruch `\r\n`
- `{LPAR}` - öffnende Klammer `(`
- `{RPAR}` - schließende Klammer `)`
- `{TIME}` - Aktueller zeitstempel

View file

@ -0,0 +1 @@
<mxfile modified="2019-09-20T09:41:55.464Z" host="www.draw.io" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36" etag="JWctItHCjYtE4wFsANak" version="11.2.9" pages="1"><diagram id="dOOvDc07wKykiP7z2FdT" name="Page-1">7Vpbb9owFP41PK6K49x4bGm3adrWakzaeJpMYsBdEiNjCuzXzybO1VBCExo2WlVqfGyf2N93bnbTg4No/YGh+ewLDXDYM41g3YO3PdMEwLPFHynZJBIHOolgykigBuWCIfmDldBQ0iUJ8KI0kFMacjIvC30ax9jnJRlijK7KwyY0LL91jqZYEwx9FOrSHyTgs0TqmW4u/4jJdJa+GTj9pCdC6WC1k8UMBXRVEMG7HhwwSnnyFK0HOJTgpbgk897v6c0WxnDM60zof3K/umN0jwfcur8fGeNvv27eKS1PKFyqDavF8k2KAKPLOMBSidGDN6sZ4Xg4R77sXQnOhWzGo1C0gHickDAc0JCy7Vw48Xzs+0K+4Iz+xoWesWdbtlSoFoAZx+u9OwMZXsLQMI0wZxsxRE2wHQWxsjFLbWKVEwYsNWRWIMtMhUgZyTRTneMoHhSUR8BqnhbWAGFvshNWx/fweNIOrMA8N1gdDdYhZmKPGrhi07yMYBmpmMa4AqsSoZBMY9H0BUhCMbyREBIRD65VR0SCQL5mJ2VlUpN3pmFjyyONuYpxEvmkrZYNWqCs6gm2VZOyUzHmaYwNiNzLG2G7faxzwqChcYMDkRFVkzI+o1Mao/Aul1ZQfFxG8xQz0cynfKZ0rnB9xJxv1CC05LTMPV4T/lNqu7JVa1TouV2rF20bm7QRi+0XJsnmqNiXT9u2NrU5TwCRKDxPsgCNLpmPn0u3KoJxxKaYPzewv9tsGA4RJ0/llbRuBEAPtAz7T9uqZkr8M/Xe3by1Gk+B7XTtn0BD/80/2/PP9Ihx0D+dTv1TL9sXYsl8Ob9g1zSMjl0TWDorOA4uL2pWixpgu11T099Hjbw3kNcTiKPLIajqO4KxegS5J0tr+gH59dPa4VRTSGLmUVmsfo46mHogbJh61NQHSuRBLHPavnEFCz+WVzIRCCvUJ+tUSorXTrresq25/bKiJClrirZmlG2vwVWMsa+WvUjXr8bm7l3f1IsZPRbEwbW8zJW4hmixIP7RnqtK1rRIHZXK190la5uFpdGwsCzQY+9gJ5U1DQIV64B2hfU9zqorciuKjHrhozWvr3ED255RGUcYVZZCQCl/5IeixhnkoDGadk1jLPyf4s0YGxijdwbFzX97Zjdh3dBqNSycmqU5qEWkizuzawfD7s/senU4ZhQFPlqc6z8pTsALtM7twG7qdylnUhTmMbGz/J1eNB2OeJ3mb7N6Q+e4L8vf2lWf41wBr5//Oq+bzm3NNgPC5McnpvF98NDLPkYhNL7cGGLCzmOI+5ox5B87A6Q3oofPAHaXMUS7qbSsl8WQajDSFJ04aEC9/PNRnMcK8SSjhRFTFiGpbYU2lxM8ALBL7GTBpGBl2amtYfAQzfyju4Te/NNFePcX</diagram></mxfile>

BIN
docu/docs/img/broadcast.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

BIN
docu/docs/img/bw3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

17
docu/docs/index.md Normal file
View file

@ -0,0 +1,17 @@
# <center>BOSWatch 3</center>
---
<center>
![BOSWatch](img/bw3.png "BOSWatch 3 Logo")
Falls du uns unterstützen möchtest würden wir uns über eine Spende freuen.
Server, Hosting, Domain sowie Kaffee kosten leider Geld ;-)
[![](https://www.paypalobjects.com/de_DE/DE/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=CLK9VBN2MSLZY&source=url)
</center>
**Es wird darauf hingewiesen, dass für die Teilnahme am BOS-Funk nur nach den Technischen Richtlinien der BOS zugelassene Funkanlagen verwendet werden dürfen.**
**Der BOS-Funk ist ein nichtöffentlicher mobiler Landfunk. Privatpersonen gehören nicht zum Kreis der berechtigten Funkteilnehmer.** _(Quelle: TR-BOS)_
---
**The intercept of the German BOS radio is strictly prohibited and will be prosecuted. The use is only permitted for authorized personnel.**

View file

@ -0,0 +1,31 @@
# <center>Broadcast Service</center>
Durch den Broadcast Service haben CLients die Möglichkeit, automatisch den Server zu finden und sich mit diesem zu verbinden. Dazu stellt der Server die benötigten Verbinungsinformationen per Broadcast Service bereit.
**Hinweis:** *Server und Client müssen sich im selben Subnetz befinden.*
---
## Aufbau
Der Broadcast Service besteht aus 2 Teilen - einem Server und einem Clienten.
Nachfolgend soll der Ablauf einer Verbunding des Clienen zum Server mittels des Broadcast Services erklärt werden.
<center>![](../img/broadcast.png)</center>
---
## Ablauf
### Schritt 1 - Broadcast Server starten
Im ersten Schritt wird auf dem Server ein zusätzlicher Broadcast Server in einem seperaten Thread gestartet. Dieser lauscht auf einem festgelegten Port auf UDP Broadcast Pakete. Nun kann eine beliebige Anzahl von Clienten mittels des Broadcast Services die Verbinundgdaten des Server abfragen.
### Schritt 2 - Broadcast durch Clienten
Die Client Applikation startet nun zur Abfrage der Verbindungsdaten einen BC Clienten und sendet dort auf dem festgelegten Port ein Paket per UDP Boradcast. Der Inhalt des Paketes ist das Magic-Word `<BW3-Request>` und wird von allen im selben Subnetz vohandenen Gegenstellen empfangen. Nun wird auf eine Antwort des Broadcast Server mit den Verbindungsdaten gewartet.
### Schritt 3 - Verbindungsdaten senden
Wird nun ein Broadcast Paket empfangen, prüft der BC Server die Daten auf das Magic-Word `<BW3-Request>`. Wird dieses erkannt, liest der Server die Absender-IP-Addresse aus dem Paket aus und sendet eine Antwort direkt an diesen Clienten. Dieses Antwortpaket sieht folgendermaßen aus: `<BW3-Result>;8080` wobei die `8080` hier den normalen TCP Kommunikationsport des Server darstellt.
### Schritt 4 - Verbindungsdaten empfangen
Nachdem der Client das direkt an ihn gerichtete Paket mit den Verbindungsdaten vom Server empfangen hat, prüft er auf das Magic-Word `<BW3-Result>`. Ist dieses enthalten wird der Port für die TCP Verbundindung aus dem Paket extrahiert. Außerdem wird die IP-Addresse des Absenders aus dem Paket gelesen.
Anschließend stehen dem Clienten die Verbindungsdaten des Servers zur Verfügung und er kann sich per TCP über den angegebenen Port mit dem BOSWatch Server verbindden um seine Alarmierungs-Pakete zu versenden.
Da der Broadcast Server in einem eigenen Thread, unabhängig vom Hauptprogram läuft, können ganz einfach weitere Clienten per Broadcast Service die Verbindungsdaten des Servers abrufen.

View file

@ -0,0 +1,29 @@
# <center>Server/Client Prinzip</center>
BOSWatch 3 wurde als Server/Client Anwedung entwickelt.
Dies ermöglicht es, mehrere Empfangsstationen an einer Auswerte- und Verteilereinheit zu bündeln.
---
## BOSWatch Client
Der **BOSWatch Client** übernimmt den Empfang und die Dekodierung der Daten. Anschließend werden die Daten mittels der implemetierten
Dekoder ausgewertet und in ein sogenanntes bwPacket verpackt.
Dieses Paket wird anschließend in einer Sende-Queue abgelegt. Nun werden Pakete aus der Queue an den BOSWatch Server per TCP-Socket
gesendet. Der Ansatz, Pakete statt dem direkten versenden vorher in einer Queue zwischen zu speichern, verhindert den Verlust von
Paketen, sollte die Verbindung zum Server einmal abreisen. Nach einer erfolgreichen Wiederverbdingun können die wartenden Pakete nun
nachträglich an den Server übermittelt werden.
Dabei überwacht der Client selbstständig die benötigten Programme zum Empfang der Daten und startet diese bei einem Fehler ggf. neu.
---
## BOSWatch Server
Nachdem die Daten vom Clienten über die TCP-Socket Verbindung empfangen wurden, übernimmt der **BOSWatch Server** die weitere
Verarbeitung der Daten.
Auch hier werden die empfangenen Daten in From von bwPacket's in einer Queue abelegt um zu gewährleisten, das auch während einer länger
dauernden Plugin Ausführung alle Pakete korrekt empfangen werden können und es zu keinen Verlusten kommt.
Die Verarbeitung der Pakete geschieht anschließend in sogenannten Routern, welche aufgrund ihres Umfangs jedoch in einem eigenen Kapitel
erklärt werden. Diese steuern die Verteilung der Daten an die einzelnen Plugins.

View file

@ -0,0 +1,34 @@
# <center>Mode Filter</center>
---
## Beschreibung
Mit diesem Modul ist es Möglich, die Pakete auf bestimmte Modes (FMS, POCSAG, ZVEI) zu Filtern. Je nach Konfiguration werden Pakete eines bestimmten Modes im aktuellen Router weitergeleitet oder verworfen.
## Resource
`filter.modeFilter`
## Konfiguration
|Feld|Beschreibung|Default|
|----|------------|-------|
|allowed|Liste der erlaubten Paket Typen `fms` `zvei` `pocsag` `msg`||
**Beispiel:**
```yaml
- type: module
name: filter.modeFilter
config:
allowed:
- fms
- pocsag
```
---
## Abhängigkeiten
- keine
---
## Paket Modifikationen
- keine

4
docu/docs/tbd.md Normal file
View file

@ -0,0 +1,4 @@
# <center>To be done ...</center>
---
Hier existiert noch kein Inhalt, gerne kannst du uns aber Helfen die Dokumentation zu vervollständigen.

View file

@ -58,7 +58,7 @@ PROJECT_LOGO =
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.
OUTPUT_DIRECTORY = _docu
OUTPUT_DIRECTORY = docu/docs/api/
# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-
# directories (in 2 levels) under the output directory of each output format and
@ -92,6 +92,7 @@ ALLOW_UNICODE_NAMES = NO
# The default value is: English.
OUTPUT_LANGUAGE = English
#German
# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
# descriptions after the members that are listed in the file and class
@ -666,21 +667,21 @@ MAX_INITIALIZER_LINES = 30
# list will mention the files that were used to generate the documentation.
# The default value is: YES.
SHOW_USED_FILES = YES
SHOW_USED_FILES = NO
# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
# will remove the Files entry from the Quick Index and from the Folder Tree View
# (if specified).
# The default value is: YES.
SHOW_FILES = YES
SHOW_FILES = NO
# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
# page. This will remove the Namespaces entry from the Quick Index and from the
# Folder Tree View (if specified).
# The default value is: YES.
SHOW_NAMESPACES = YES
SHOW_NAMESPACES = NO
# The FILE_VERSION_FILTER tag can be used to specify a program or script that
# doxygen should invoke to get the current version for each file (typically from
@ -756,7 +757,7 @@ WARN_IF_DOC_ERROR = YES
# parameter documentation, but not about the absence of documentation.
# The default value is: NO.
WARN_NO_PARAMDOC = NO
WARN_NO_PARAMDOC = YES
# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
# a warning is encountered.
@ -875,7 +876,9 @@ RECURSIVE = YES
EXCLUDE = bw_client.py \
bw_server.py \
_info/FileHead.template.py
FileHead.template.py \
venv \
docu
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded

36
docu/mkdocs.yml Normal file
View file

@ -0,0 +1,36 @@
site_name: BOSWatch3 Core
site_author: Bastian Schroll & BW3 Dev team
repo_url: https://github.com/BOSWatch/BW3-Core
edit_uri: edit/develop/docu/docs/
nav:
# - BW3: index.md
- Quick Start:
- Installation: tbd.md
- Konfiguration: config.md
# - BOSWatch benutzen: tbd.md
# - Als Service einrichten: tbd.md
- Informationen:
- Server/Cient Prinzip: information/serverclient.md
- Broadcast Service: information/broadcast.md
# - Modul/Plugin Konzept: tbd.md
# - Routing Mechanismus: tbd.md
- Changelog: changelog.md
- Module:
- Mode Filter: modul/mode_filter.md
- Plugins: tbd.md
- Entwickler:
- Eigenes Modul/Plugin schreiben: develop/ModulPlugin.md
- BOSWatch Alarmpaket Format: develop/packet.md
- BW3 Quellcode Dokumentation: api/html/index.html
use_directory_urls: false
theme:
name: mkdocs
highlightjs: true
hljs_style: github

View file

@ -36,7 +36,7 @@ class BoswatchModule(Module):
pass
def doWork(self, bwPacket):
"""!start an rund of the module.
"""!start an run of the module.
@param bwPacket: A BOSWatch packet instance
@return bwPacket or False"""

View file

@ -36,10 +36,19 @@ class BoswatchModule(Module):
pass
def doWork(self, bwPacket):
"""!start an rund of the module.
"""!start an run of the module.
@param bwPacket: A BOSWatch packet instance
@return bwPacket or False"""
if bwPacket.get("mode") == "fms":
pass
elif bwPacket.get("mode") == "zvei":
pass
elif bwPacket.get("mode") == "pocsag":
pass
elif bwPacket.get("mode") == "msg":
pass
return bwPacket
def onUnload(self):

View file

@ -17,7 +17,7 @@
import logging
import time
from boswatch.utils import wildcard
from boswatch import wildcard
logging.debug("- %s loaded", __name__)

View file

@ -3,6 +3,9 @@
pyyaml
# for documentation generating
mkdocs
# for develope only
pytest
pytest-cov

3
some_old_stuff.txt Normal file
View file

@ -0,0 +1,3 @@
python -m pytest -c "_gen/pytest.ini"
_bin\win\doxygen\doxygen.exe _gen/doxygen.ini
_bin\win\cloc_1_72\cloc-1.72.exe . --exclude-lang=XML --exclude-dir=_docu,_config,_info,doxygen.ini --by-file-by-lang

View file

@ -82,6 +82,13 @@ def test_clientConnect(getClient, getRunningServer):
assert getClient.disconnect()
def test_doubleConnect(getClient, getRunningServer):
"""!Connect to a server twice"""
assert getClient.connect()
assert getClient.connect()
assert getClient.disconnect()
def test_clientReconnect(getClient, getRunningServer):
"""!Try a reconnect after a established connection"""
assert getClient.connect()
@ -149,17 +156,40 @@ def test_serverStopFailed(getServer):
assert getServer.stop()
def test_serverDoubleStart():
def test_serverDoubleStart(getServer):
"""!Test to start the server twice"""
assert getServer.start()
assert getServer.start()
assert getServer.stop()
def test_serverStartTwoInstances():
"""!Test to start two server different server instances"""
dataQueue = queue.Queue()
testServer1 = TCPServer(dataQueue)
testServer2 = TCPServer(dataQueue)
assert testServer1.start()
assert testServer1.isRunning
assert not testServer2.start()
assert testServer1.isRunning
assert not testServer2.isRunning
assert testServer1.stop()
assert testServer2.stop()
def test_serverStopsWhileConnected(getRunningServer, getClient):
"""!Shutdown server while client is connected"""
getClient.connect()
getRunningServer.stop()
timeout = 10
while getClient.isConnected:
time.sleep(0.1)
timeout = timeout - 1
if timeout is 0:
break
assert timeout
@pytest.mark.skip("needs fixture for more than one client")
def test_serverGetOutput(getRunningServer):
"""!Send data to server with 2 clients, check '[ack]' and data on server queue"""

View file

@ -56,6 +56,12 @@ def test_loadConfigFileNotFound(getConfig):
assert getConfig.loadConfigFile(paths.TEST_PATH + "test_configNotFound.yaml") is False
def test_getConfigAsString(getFilledConfig):
"""!Get the string representation of the config"""
assert type(str(getFilledConfig)) is str
logging.debug(getFilledConfig)
def test_getTypes(getFilledConfig):
"""!Get and check different data types in config"""
assert type(getFilledConfig.get("types")) is ConfigYAML
@ -65,6 +71,11 @@ def test_getTypes(getFilledConfig):
assert type(getFilledConfig.get("types", "float")) is float
def test_getDefaultValue(getFilledConfig):
"""!Get the default value of an not existent entry"""
assert getFilledConfig.get("notExistent", default="defaultValue") == "defaultValue"
def test_getNestedConfig(getFilledConfig):
"""!Work with nested sub-config elements"""
nestedConfig = getFilledConfig.get("types")
@ -78,4 +89,17 @@ def test_configIterationList(getFilledConfig):
for item in getFilledConfig.get("list"):
assert type(item) is str
counter += 1
assert counter == 3
assert counter is 3
def test_configIterationListWithNestedList(getFilledConfig):
"""!Try to iterate over a list in the config where its elements are lists itself"""
listCnt = 0
strCnt = 0
for item in getFilledConfig.get("list1"):
if type(item) is ConfigYAML:
listCnt += 1
if type(item) is str:
strCnt += 1
assert listCnt == 2
assert strCnt == 1

View file

@ -20,7 +20,7 @@ import logging
import time
import pytest
from boswatch.utils.timer import RepeatedTimer
from boswatch.timer import RepeatedTimer
def setup_method(method):

View file

@ -18,4 +18,15 @@ types:
list:
- one
- two
- three
- three
list1:
- list11:
- one
- two
- three
- list12:
- one
- two
- three
- string1

View file

@ -29,7 +29,7 @@ def fixtureTemplate():
return None
@pytest.mark.skip
@pytest.mark.skip("Reason why i will skipped")
def test_skippedTest():
pass

View file

@ -21,7 +21,7 @@
#
# bitrate
POCSAG512: Address: 1000512 Function: 1 Alpha: BOSWatch-Test ÖÄÜß: okay
POCSAG512: Address: 1000512 Function: 1 Alpha: BOSWatch-Test ÖÄÜß: okay
POCSAG1200: Address: 1001200 Function: 1 Alpha: BOSWatch-Test: okay
POCSAG2400: Address: 1002400 Function: 1 Alpha: BOSWatch-Test: okay
@ -32,8 +32,8 @@ POCSAG512: Address: 1000002 Function: 2 Alpha: BOSWatch-Test: okay
POCSAG512: Address: 1000003 Function: 3 Alpha: BOSWatch-Test: okay
# german special sign
POCSAG512: Address: 1200001 Function: 1 Alpha: BOSWatch-Test ÖÄÜß: okay
POCSAG512: Address: 1200001 Function: 1 Alpha: BOSWatch-Test öäü: okay
POCSAG512: Address: 1200001 Function: 1 Alpha: BOSWatch-Test ÖÄÜß: okay
POCSAG512: Address: 1200001 Function: 1 Alpha: BOSWatch-Test öäü: okay
# with csv
POCSAG512: Address: 1234567 Function: 1 Alpha: BOSWatch-Test: with csv
@ -100,7 +100,7 @@ POCSAG1200: Address: 0860007 Function: 0
POCSAG1200: Address: 0860008 Function: 0
POCSAG1200: Address: 0860009 Function: 0
POCSAG1200: Address: 0860010 Function: 0
POCSAG1200: Address: 0871003 Function: 0 Alpha: B2 Feuer Gebäude Pers in Gefahr. bla bla bla<NUL>
POCSAG1200: Address: 0871003 Function: 0 Alpha: B2 Feuer Gebäude Pers in Gefahr. bla bla bla<NUL>
# regEx-Filter?