Compare commits
62 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
9048b156e5 | ||
|
3229360f70 | ||
|
ff25a032c6 | ||
|
60c790f5cb | ||
|
13d86a5b88 | ||
|
949f9b4404 | ||
|
dd45e351c3 | ||
|
4343677843 | ||
|
0698417682 | ||
|
20444b7de0 | ||
|
979fedb218 | ||
|
11a296252d | ||
|
e756efcaa1 | ||
|
570efa04ce | ||
|
582fe1e0ac | ||
|
458f115de3 | ||
|
71f5bd7a04 | ||
|
de5192ab6b | ||
|
890e52bfd2 | ||
|
867a50a4f1 | ||
|
75d2b9ccc2 | ||
|
7f4844299d | ||
|
dd2879a1a9 | ||
|
425d77c83c | ||
|
f937581e49 | ||
|
285eec5267 | ||
|
0664c4124a | ||
|
6875d95475 | ||
|
ca0e8927c1 | ||
|
e3b74c6cbb | ||
|
b4de3650fc | ||
|
09c2ee5b4c | ||
|
4e335e2831 | ||
|
7263c41ac6 | ||
|
a0176551b8 | ||
|
906ada085a | ||
|
12169a1065 | ||
|
dd4c7d91a1 | ||
|
aa3ae3d3a1 | ||
|
03552877ef | ||
|
7002c79c8b | ||
|
5aa8a14269 | ||
|
4ef4e78599 | ||
|
3cc71a4040 | ||
|
a1fa625df5 | ||
|
c5ea8f625b | ||
|
6d7cc08559 | ||
|
4881380132 | ||
|
3b945ab886 | ||
|
9946b7ee53 | ||
|
830799db2c | ||
|
5031d7d4aa | ||
|
7b2b33b2d9 | ||
|
e15169b09c | ||
|
eb06c9c268 | ||
|
1540b3e806 | ||
|
e3817980ec | ||
|
1ce6c26d84 | ||
|
0719db4e77 | ||
|
5632ad507b | ||
|
c8c8ccc4d0 | ||
|
5815e1993c |
1
.gitattributes
vendored
1
.gitattributes
vendored
@ -1,2 +1,3 @@
|
||||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
*.html ident
|
||||
|
132
README.md
132
README.md
@ -1,82 +1,79 @@
|
||||
# GPS/Data Application
|
||||
##### This is the development version that supports the sending of SMS. This is a work in progress and is not meant to be used in production at this time. This will become the 2nd genreation of the project.
|
||||
|
||||
This repository contains everything needed to decode DMR GPS packets and SMS for HBLink3. This application can act as a master or peer and receive data as a group call or private call. It is designed to work in a multi system/user network.
|
||||
# HBLink3 with APRS/SMS Features
|
||||
|
||||
Files modified from original master branch of HBLink3:
|
||||
This is a **fork** of the [HBLink project](https://hblink-org.github.io/) that supports APRS and DMR SMS functions.
|
||||
|
||||
* bridge.py
|
||||
* config.py
|
||||
This repository contains everything needed to setup an HBLink server with APRS/SMS features.
|
||||
|
||||
The development server can be found at [https://hbl.ink](https://hbl.ink).
|
||||
|
||||
## Features
|
||||
|
||||
* Decode GPS locations and upload APRS position packets
|
||||
* Each user/DMR ID can customize APRS options (SSID, icon, comment)
|
||||
* Send and receive APRS messages as DMR SMS
|
||||
* Ability to receive data as a private call or group call
|
||||
* Trigger a command or script via DMR SMS
|
||||
* Optional web dashboard to show APRS packets uploaded
|
||||
* See location of radios on dashboard map
|
||||
* Use built in API to send SMS to other HBLink servers
|
||||
* Ability to disable APRS and just use dashboard map
|
||||
* Use [external applications](https://github.com/kf7eel/hblink_sms_external_apps) (see [API Documentation](https://kf7eel.github.io/hblink3/api_doc.html)) for weather reports, email, and other information.
|
||||
|
||||
#### Required modules
|
||||
|
||||
* pynmea2
|
||||
* aprslib
|
||||
* maidenhead
|
||||
* libscrc
|
||||
|
||||
#### Optional Modules
|
||||
* Flask - Required for dashboard
|
||||
* smtplib - Required for sending email. If pip fails to install module, it may already be installed as most Linux distributions have this module by default.
|
||||
* traceback - If pip fails to install module, it may already be installed as most Linux distrobutions have this module by default.
|
||||
* slixmpp - Required for upcoming XMPP gateway.
|
||||
* folium - Required for mapping on dashboard.
|
||||
|
||||
This should work for DMR radios that send location data as a UTF-8 NMEA sentence. I am hopping to add support for more radios in the future.
|
||||
|
||||
### Differences in branches
|
||||
|
||||
* **GPS**: Contains the GPS/Data Application.
|
||||
* **aprs_features**: Contains the GPS/Data Application and a modified version of the APRS implementation for repeaters and hotspots by **IU7IGU**. (See [https://github.com/iu7igu/hblink3-aprs](https://github.com/iu7igu/hblink3-aprs) for his work). I combined these for convenience.
|
||||
# Radio Compatibility
|
||||
|
||||
## Confirmed working:
|
||||
Actually tested
|
||||
|
||||
| Radio | GPS | SMS |
|
||||
|-------|:---:|:---:|
|
||||
| Anytone D878| YES | YES |
|
||||
| Anytone D578| YES | YES |
|
||||
| BTech DMR-6x2 | YES | Most likely |
|
||||
| MD-380 (MD380tools, no GPS) | - | YES |
|
||||
| MD-380 (stock firmware, GPS) | YES | Most likely |
|
||||
| MD-390 (stock firmware) | YES | YES |
|
||||
| Retevis RT73* | YES | YES |
|
||||
| Ailunce HD1 | YES | YES |
|
||||
| Radio | GPS | SMS Decode | SMS Encode |
|
||||
|-------|:---:|:---:|:---:|
|
||||
| Anytone D878| YES | YES | YES |
|
||||
| Anytone D578| YES | YES | Most Likely |
|
||||
| BTech DMR-6x2 | YES | Most likely | Not Tested |
|
||||
| MD-380 (MD380tools, no GPS) | - | YES | WIP |
|
||||
| MD-380 (stock firmware, GPS) | YES | Most likely | Not Tested |
|
||||
| MD-390 (stock firmware) | YES | YES | Not Tested |
|
||||
| Retevis RT73* | YES | YES | Not Tested |
|
||||
| Ailunce HD1 | YES | YES | Not Tested |
|
||||
|
||||
*RT73 must have unconfirmed data setting enabled.
|
||||
|
||||
## Highly suspected to work:
|
||||
Not tested yet, but will most likely work.
|
||||
|
||||
| Radio | GPS | SMS |
|
||||
|-------|:---:|:---:|
|
||||
| Anytone D868 | Most likely | Most likely |
|
||||
| TYT MD-2017 | Most likely | Likely |
|
||||
| TYT MD-9600 | Most likely | Likely |
|
||||
| Retevis RT8 | Most likely | Likely |
|
||||
| Radio | GPS | SMS Decode | SMS Encode |
|
||||
|-------|:---:|:---:|:---:|
|
||||
| Anytone D868 | Most likely | Most Likely | Most Likely |
|
||||
| TYT MD-2017 | Most likely | Likely | Unknown |
|
||||
| TYT MD-9600 | Most likely | Likely | Unknown |
|
||||
| Retevis RT8 | Most likely | Likely | Unknown |
|
||||
|
||||
|
||||
## Tested, but with issues.
|
||||
Tested, but with bugs present.
|
||||
|
||||
| Radio | GPS | SMS |
|
||||
|-------|:---:|:---:|
|
||||
| Alinco DJ-MD5TGP | WIP | Most likely |
|
||||
| Motorola DP3601| WIP | WIP |
|
||||
| Radio | GPS | SMS Decode | SMS Encode
|
||||
|-------|:---:|:---:|:---:|
|
||||
| Alinco DJ-MD5TGP | WIP | Most likely | Not Tested |
|
||||
| Motorola DP3601| WIP | WIP | Not Tested |
|
||||
|
||||
|
||||
## Would like to test:
|
||||
|
||||
Connect Systems GPS enabled radios
|
||||
|
||||
## Features
|
||||
|
||||
* Decode GPS locations and upload APRS position packets
|
||||
* Each user/DMR ID can customize APRS position
|
||||
* Ability to receive data as a private call or group call
|
||||
* Trigger a command or script via DMR SMS
|
||||
* Optional web dashboard to show APRS packets uploaded
|
||||
* Display bulletins sent via SMS on web dashboard
|
||||
|
||||
|
||||
## How it works
|
||||
|
||||
A user should configure their radio for the DMR ID of the application and private or group call. When a position is received by the application, it will extract the coordinates and create an APRS position packet. The application will find the callsign of the user based on the sending radio's DMR ID. It is essential to have an up to date subscriber_ids file for this to work. A predefined APRS SSID is appended to the callsign. The APRS location packet is then uploaded to APRS-IS. No setup is required beforehand on the part of the user. This is pretty much "plug and play."
|
||||
@ -91,22 +88,41 @@ The comment, SSID, and icon can be set for each individual user/DMR ID the appli
|
||||
|
||||
| Command | Description | Example |
|
||||
|-------|:---:|:---:|
|
||||
|**@SSID**|Change SSID of user callsign.|`@SSID 7`|
|
||||
|**@ICON**|Change the icon of the APRS position. *See [http://aprs.net/vm/DOS/SYMBOLS.HTM](http://aprs.net/vm/DOS/SYMBOLS.HTM) for icon list.|`@icon /p`|
|
||||
|**@COM**|Change the comment of the APRS.|`@COM This is a test comment.`|
|
||||
|**@MH**|Set you location by maidenhead grid square. Designed for radios with no GPS or that are not compatable yet.|`@MH DN97uk`|
|
||||
|**@BB**|Post a bulliten to the web dashboard.|`@BB This is a test bulletin.`|
|
||||
|**@[CALLSIGN W/ SSID] A-[MESSAGE]**|Send a message to another station via APRS.|`@N0CALL-15 A-This is a test.`|
|
||||
|**[EMAIL ADDRESS] E-[MESSAGE]**|Send an email to an email address.|`test@example.org E-This is a test.`|
|
||||
|**SSID**|Change SSID of user callsign.|`SSID 7`|
|
||||
|**ICON**|Change the icon of the APRS position. *See [http://aprs.net/vm/DOS/SYMBOLS.HTM](http://aprs.net/vm/DOS/SYMBOLS.HTM) for icon list.|`icon /p`|
|
||||
|**COM**|Change the comment of the APRS.|`COM This is a test comment.`|
|
||||
|**MH**|Set you location by maidenhead grid square. Designed for radios with no GPS or that are not compatable yet.|`MH DN97uk`|
|
||||
|**BB**|Post a bulliten to the web dashboard.|`BB This is a test bulletin.`|
|
||||
|**@[CALLSIGN W/ SSID] [MESSAGE]**|Send a message to another station via APRS.|`@N0CALL-15 This is a test.`|
|
||||
|**[EMAIL ADDRESS] [MESSAGE]**|Send an email to an email address.|`test@example.org This is a test.`|
|
||||
|**REM MAIL**|Remove all mail (APRS messages, SMS, etc) addressed to you.|`REM MAIL`|
|
||||
**@NOTICE**|Used to prominantly display a notice, similar to EMERGENCY activation.|`@NOTICE Server going down at 1800`|
|
||||
|**@SOS**|EMERGENCY activation displays a banner on the main dashboard page.|`THIS IS AN EMERGENCY. @SOS`|
|
||||
|**REM SOS**|Removes an EMERGENCY or notice.|`REM SOS`|
|
||||
|**ID**|Responds by send an SMS containing your DMR ID.|`ID`|
|
||||
|**TEST**| Responds with "This is a test." as an SMS.|`TEST`|
|
||||
|**?[Network Shortcut] [DMR ID] [Message]**| Send an SMS to a user on another network.|`?XYZ 123456789 This is a test`|
|
||||
|**?[App Shortcut] [Input]**|Send SMS to an external application.|`?BBD This is a test post.`|
|
||||
|**APRS ON**|Enable sending and receiving of APRS messages.|`@APRS ON`|
|
||||
|**APRS OFF**|Disable sending and receiving of APRS messages.|`@APRS OFF`|
|
||||
|
||||
|
||||
|
||||
Send a DMR SMS to the configured dmr_data_id in the application with the desired command followed by the value. For example, to change your icon to a dog, the command would be `@ICON /p` (see the icon table for values). Changing your SSID is as simple as `@SSID 7`, and `@COM Testing 123` will change the comment.
|
||||
|
||||
Sending `@BB Test` will result in a post to the bulletin board with the messaage of "Test".
|
||||
Sending `@BB Test` will result in a post to the bulletin board with the message of "Test".
|
||||
|
||||
|
||||
**To remove any of the stored values, just send the appropriate command without any input.** `@COM` will remove the stored comment, `@ICON` will remove the stored icon, and `@COM` will remove the strored comment. Any position now reports sent will have the default settings.
|
||||
**To remove any of the stored values, just send the appropriate command without any input.** `@COM` will remove the stored comment, `@ICON` will remove the stored icon, and `@COM` will remove the stored comment. Any position now reports sent will have the default settings.
|
||||
|
||||
## API
|
||||
The API built in to the dashboard can be used to exchange SMS with other HBLink servers/networks or be used to access external applications that provide functionality via SMS. Multiple servers/networks can share a single external application.
|
||||
|
||||
See [hbl.ink](https://hbl.ink) for publicly accessible external applications that you can use.
|
||||
|
||||
See [API documentation](https://kf7eel.github.io/hblink3/).
|
||||
|
||||
Repository for [external applications](https://github.com/kf7eel/hblink_sms_external_apps), if you want to host your own.
|
||||
|
||||
|
||||
## Web Dashboard
|
||||
@ -115,7 +131,7 @@ The web dashboard is completely optional. Python module flask is required for th
|
||||
|
||||
## APRS messaging
|
||||
|
||||
**At this time, only sending of messages from DMR SMS to APRS-IS is supported.** I find this feature very pointless because it will only go one way, but someone else may find it important. **Messages from sent from APRS-IS to DMR SMS will not work.** I have not written the code for this yet. It will likley be a long time before this is a possibility.
|
||||
You can send and receive APRS messages via DMR SMS. APRS messages received by the gateway are automatically sent to your DMR ID as a private SMS.
|
||||
|
||||
## APRS TOCALL
|
||||
|
||||
@ -123,7 +139,7 @@ The project was granted a [tocall](http://www.aprs.org/aprs11/tocalls.txt) of **
|
||||
|
||||
* **APHBL3** - HBlink3 D-APRS gateway
|
||||
* **APHBLD** - DMRlink D-APRS gateway (the IPSC version of the project)
|
||||
* **_APHBLS_** - Planned, but not in use: HBLink3 via KISS TNC
|
||||
|
||||
|
||||
## Configuration
|
||||
|
||||
@ -145,6 +161,12 @@ See hblink_SAMPLE.cfg, rules_SAMPLE.py, and gps_data_SAMPLE.cfg for examples.
|
||||
|
||||
**M0GLJ** - For assisting with Motorola testing.
|
||||
|
||||
**W4DBG** - For early testing.
|
||||
|
||||
**IW7EDX** - For contributing code.
|
||||
|
||||
**Xavier FRS2013** - For contributing and cleaning up code.
|
||||
|
||||
## Resources for DMR data
|
||||
|
||||
I spent many hours looking at the following for this project. You may find these links useful.
|
||||
|
@ -2,6 +2,7 @@
|
||||
#
|
||||
###############################################################################
|
||||
# Copyright (C) 2016-2019 Cortney T. Buffington, N0MJS <n0mjs@me.com>
|
||||
# Copyright 2021, Eric, KF7EEL <KF7EEL@qsl.net>
|
||||
#
|
||||
# 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
|
||||
|
32
config.py
Executable file → Normal file
32
config.py
Executable file → Normal file
@ -106,7 +106,6 @@ def build_config(_config_file):
|
||||
CONFIG['GLOBAL'] = {}
|
||||
CONFIG['REPORTS'] = {}
|
||||
CONFIG['LOGGER'] = {}
|
||||
CONFIG['GPS_DATA'] = {}
|
||||
CONFIG['ALIASES'] = {}
|
||||
CONFIG['SYSTEMS'] = {}
|
||||
|
||||
@ -142,35 +141,6 @@ def build_config(_config_file):
|
||||
if not CONFIG['LOGGER']['LOG_FILE']:
|
||||
CONFIG['LOGGER']['LOG_FILE'] = '/dev/null'
|
||||
|
||||
elif section == 'GPS_DATA':
|
||||
CONFIG['GPS_DATA'].update({
|
||||
'DATA_DMR_ID': config.get(section, 'DATA_DMR_ID'),
|
||||
'USER_APRS_SSID': config.get(section, 'USER_APRS_SSID'),
|
||||
'CALL_TYPE': config.get(section, 'CALL_TYPE'),
|
||||
'USER_APRS_COMMENT': config.get(section, 'USER_APRS_COMMENT'),
|
||||
'APRS_LOGIN_CALL': config.get(section, 'APRS_LOGIN_CALL'),
|
||||
'APRS_LOGIN_PASSCODE': config.get(section, 'APRS_LOGIN_PASSCODE'),
|
||||
'APRS_SERVER': config.get(section, 'APRS_SERVER'),
|
||||
'APRS_PORT': config.get(section, 'APRS_PORT'),
|
||||
'IGATE_BEACON_TIME': config.get(section, 'IGATE_BEACON_TIME'),
|
||||
'IGATE_BEACON_ICON': config.get(section, 'IGATE_BEACON_ICON'),
|
||||
'IGATE_BEACON_COMMENT': config.get(section, 'IGATE_BEACON_COMMENT'),
|
||||
'IGATE_LATITUDE': config.get(section, 'IGATE_LATITUDE'),
|
||||
'IGATE_LONGITUDE': config.get(section, 'IGATE_LONGITUDE'),
|
||||
'EMAIL_SENDER': config.get(section, 'EMAIL_SENDER'),
|
||||
'EMAIL_PASSWORD': config.get(section, 'EMAIL_PASSWORD'),
|
||||
'SMTP_SERVER': config.get(section, 'SMTP_SERVER'),
|
||||
'SMTP_PORT': config.get(section, 'SMTP_PORT'),
|
||||
'LOCATION_FILE': config.get(section, 'LOCATION_FILE'),
|
||||
'BULLETIN_BOARD_FILE': config.get(section, 'BULLETIN_BOARD_FILE'),
|
||||
'MAILBOX_FILE': config.get(section, 'MAILBOX_FILE'),
|
||||
'EMERGENCY_SOS_FILE': config.get(section, 'EMERGENCY_SOS_FILE'),
|
||||
'USER_SETTINGS_FILE': config.get(section, 'USER_SETTINGS_FILE'),
|
||||
|
||||
})
|
||||
if not CONFIG['LOGGER']['LOG_FILE']:
|
||||
CONFIG['LOGGER']['LOG_FILE'] = '/dev/null'
|
||||
|
||||
elif section == 'ALIASES':
|
||||
CONFIG['ALIASES'].update({
|
||||
'TRY_DOWNLOAD': config.getboolean(section, 'TRY_DOWNLOAD'),
|
||||
@ -212,7 +182,7 @@ def build_config(_config_file):
|
||||
'SOFTWARE_ID': bytes(config.get(section, 'SOFTWARE_ID').ljust(40)[:40], 'utf-8'),
|
||||
'PACKAGE_ID': bytes(config.get(section, 'PACKAGE_ID').ljust(40)[:40], 'utf-8'),
|
||||
'GROUP_HANGTIME': config.getint(section, 'GROUP_HANGTIME'),
|
||||
'OPTIONS': bytes(config.get(section, 'OPTIONS'), 'utf-8'),
|
||||
'OPTIONS': b''.join([b'Type=HBlink;', bytes(config.get(section, 'OPTIONS'), 'utf-8')]),
|
||||
'USE_ACL': config.getboolean(section, 'USE_ACL'),
|
||||
'SUB_ACL': config.get(section, 'SUB_ACL'),
|
||||
'TG1_ACL': config.get(section, 'TGID_TS1_ACL'),
|
||||
|
138
dev/json_templates.py
Normal file
138
dev/json_templates.py
Normal file
@ -0,0 +1,138 @@
|
||||
# Types: App, msg_xfer, raw
|
||||
# Auth: public, private
|
||||
|
||||
import json
|
||||
|
||||
|
||||
msg_xfer = {
|
||||
'mode':'msg_xfer',
|
||||
'system_shortcut':'ABC',
|
||||
'server_name':'Test HBlink Network',
|
||||
'response_url':'http://localhost:8093/api/',
|
||||
'auth_type':'private',
|
||||
'credentials': {
|
||||
'user':'test_name',
|
||||
'password':'passw0rd',
|
||||
},
|
||||
'data':{
|
||||
1:{'source_id':1234,
|
||||
'destination_id':3153591,
|
||||
'slot':2,
|
||||
'msg_type':'unit',
|
||||
'msg_format':'motorola',
|
||||
'message':'text of the message'
|
||||
},
|
||||
2:{'source_id':1234,
|
||||
'destination_id':3153591,
|
||||
'slot':2,
|
||||
'msg_type':'unit',
|
||||
'msg_format':'motorola',
|
||||
'message':'text of the 2nd message'
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
json_object = json.dumps(msg_xfer, indent = 4)
|
||||
print('-----------------------------------------')
|
||||
print('msg_xfer')
|
||||
print(json_object)
|
||||
print('-----------------------------------------')
|
||||
|
||||
##msg_xfer_public = {
|
||||
## 'mode':'msg_xfer',
|
||||
## 'system_shortcut':'ABC',
|
||||
## 'server_name':'Test HBlink Network',
|
||||
## 'response_url':'http://localhost:8093/api/',
|
||||
## 'auth_type':'public',
|
||||
## 'auth_token':'1234567899',
|
||||
## 'data':{
|
||||
## 1:{'source_id':1234,
|
||||
## 'destination_id':3153591,
|
||||
## 'slot':2,
|
||||
## 'msg_type':'unit',
|
||||
## 'msg_format':'motorola',
|
||||
## 'message':'text of the message'
|
||||
## },
|
||||
## 2:{'source_id':1234,
|
||||
## 'destination_id':3153591,
|
||||
## 'slot':2,
|
||||
## 'msg_type':'unit',
|
||||
## 'msg_format':'motorola',
|
||||
## 'message':'text of the 2nd message'
|
||||
## }
|
||||
##
|
||||
## }
|
||||
##
|
||||
##}
|
||||
##
|
||||
##json_object = json.dumps(msg_xfer_public, indent = 4)
|
||||
##print('-----------------------------------------')
|
||||
##print('msg_xfer public')
|
||||
##print(json_object)
|
||||
##print('-----------------------------------------')
|
||||
|
||||
app_request = {
|
||||
'mode':'app',
|
||||
'system_shortcut':'ABC',
|
||||
'server_name':'Test HBlink Network',
|
||||
'response_url':'http://localhost:8093/api/',
|
||||
'auth_token':'1234567899',
|
||||
'data':{
|
||||
'source_id':1234,
|
||||
'slot':2,
|
||||
'msg_type':'unit',
|
||||
'msg_format':'motorola',
|
||||
'message':'text of the message'
|
||||
}
|
||||
}
|
||||
|
||||
json_object = json.dumps(app_request, indent = 4)
|
||||
print('-----------------------------------------')
|
||||
print('app, request, sent to the APP server')
|
||||
print(json_object)
|
||||
print('-----------------------------------------')
|
||||
|
||||
app_response = {
|
||||
'mode':'app',
|
||||
'app_name':'Test HBlink App',
|
||||
'app_shortcut':'APP',
|
||||
'auth_token':'736a9ced7e7688c951490a7f8e1ebdd4',
|
||||
'data':{
|
||||
1:{ 'destination_id':3153591,
|
||||
'slot':2,
|
||||
'msg_type':'unit',
|
||||
'msg_format':'motorola',
|
||||
'message':'text of the message'
|
||||
},
|
||||
2:{ 'destination_id':3153591,
|
||||
'slot':2,
|
||||
'msg_type':'unit',
|
||||
'msg_format':'motorola',
|
||||
'message':'text of the 2nd message'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
json_object = json.dumps(app_response, indent = 4)
|
||||
print('-----------------------------------------')
|
||||
print('app, response, sent to your dashboard')
|
||||
print(json_object)
|
||||
print('-----------------------------------------')
|
||||
raw_msg_xfer = {
|
||||
'mode':'raw',
|
||||
'system_shortcut':'ABC',
|
||||
'response_url':'http://localhost:8093/api/',
|
||||
'auth_type':'private',
|
||||
'credentials': {
|
||||
'user':'test_name',
|
||||
'password':'passw0rd',
|
||||
},
|
||||
'data':{
|
||||
1:{'MMDVM Packet 1'},
|
||||
2:{'MMDVM Packet 2'}
|
||||
|
||||
}
|
||||
|
||||
}
|
334
dev/send_sms_md380.py
Normal file
334
dev/send_sms_md380.py
Normal file
@ -0,0 +1,334 @@
|
||||
# Functions to encode DMR and MMDVM
|
||||
from dmr_utils3 import bptc, decode
|
||||
from bitarray import bitarray
|
||||
from binascii import b2a_hex as ahex
|
||||
from bitarray.util import hex2ba as hex2bits
|
||||
import random
|
||||
from dmr_utils3.utils import bytes_3, int_id, get_alias, bytes_2, bytes_4
|
||||
import re
|
||||
import libscrc
|
||||
from pathlib import Path
|
||||
|
||||
def create_crc16(fragment_input):
|
||||
crc16 = libscrc.gsm16(bytearray.fromhex(fragment_input))
|
||||
return fragment_input + re.sub('x', '0', str(hex(crc16 ^ 0xcccc))[-4:])
|
||||
|
||||
def create_crc32(fragment_input):
|
||||
# Create and append CRC32 to data
|
||||
# Create list of hex
|
||||
word_list = []
|
||||
count_index = 0
|
||||
while count_index < len(fragment_input):
|
||||
word_list.append((fragment_input[count_index:count_index + 2]))
|
||||
count_index = count_index + 2
|
||||
# Create string of rearranged word_list to match ETSI 102 361-1 pg 141
|
||||
lst_index = 0
|
||||
crc_string = ''
|
||||
for i in (word_list):
|
||||
#print(lst_index)
|
||||
if lst_index % 2 == 0:
|
||||
crc_string = crc_string + word_list[lst_index + 1]
|
||||
#print(crc_string)
|
||||
if lst_index % 2 == 1:
|
||||
crc_string = crc_string + word_list[lst_index - 1]
|
||||
#print(crc_string)
|
||||
lst_index = lst_index + 1
|
||||
# Create bytearray of word_list_string
|
||||
# print(crc_string)
|
||||
word_array = libscrc.posix(bytearray.fromhex(crc_string))
|
||||
# XOR to get almost final CRC
|
||||
pre_crc = str(hex(word_array ^ 0xffffffff))[2:]
|
||||
# Rearrange pre_crc for transmission
|
||||
crc = ''
|
||||
c = 8
|
||||
while c > 0:
|
||||
crc = crc + pre_crc[c-2:c]
|
||||
c = c - 2
|
||||
crc = crc.ljust(8, '0')
|
||||
print(crc)
|
||||
# Return original data and append CRC32
|
||||
print('Output: ' + fragment_input + crc)
|
||||
#print(len(crc.zfill(9)))
|
||||
return fragment_input + crc
|
||||
def create_crc16_csbk(fragment_input):
|
||||
crc16_csbk = libscrc.gsm16(bytearray.fromhex(fragment_input))
|
||||
return fragment_input + re.sub('x', '0', str(hex(crc16_csbk ^ 0xa5a5))[-4:])
|
||||
def csbk_gen(to_id, from_id):
|
||||
csbk_lst = ['BD00801a', 'BD008019', 'BD008018', 'BD008017', 'BD008016']
|
||||
|
||||
send_seq_list = ''
|
||||
for block in csbk_lst:
|
||||
block = block + to_id + from_id
|
||||
block = create_crc16_csbk(block)
|
||||
print(block)
|
||||
send_seq_list = send_seq_list + block
|
||||
print(send_seq_list)
|
||||
return send_seq_list
|
||||
def mmdvm_encapsulate(dst_id, src_id, peer_id, _seq, _slot, _call_type, _dtype_vseq, _stream_id, _dmr_data):
|
||||
signature = 'DMRD'
|
||||
# needs to be in bytes
|
||||
frame_type = 0x10 #bytes_2(int(10))
|
||||
#print((frame_type))
|
||||
dest_id = bytes_3(int(dst_id, 16))
|
||||
# print((dest_id))
|
||||
|
||||
#print(ahex(dest_id))
|
||||
source_id = bytes_3(int(src_id, 16))
|
||||
via_id = bytes_4(int(peer_id, 16))
|
||||
# print((source_id))
|
||||
#print(ahex(via_id))
|
||||
seq = int(_seq).to_bytes(1, 'big')
|
||||
#print(ahex(seq))
|
||||
# Binary, 0 for 1, 1 for 2
|
||||
slot = bitarray(str(_slot))
|
||||
#print(slot)
|
||||
# binary, 0 for group, 1 for unit, bin(1)
|
||||
# print(_call_type)
|
||||
call_type = bitarray(str(_call_type))
|
||||
#print(call_type)
|
||||
#0x00 for voice, 0x01 for voice sync, 0x10 for data
|
||||
#frame_type = int(16).to_bytes(1, 'big')
|
||||
frame_type = bitarray('10')
|
||||
#print(frame_type)
|
||||
# Observed to be always 7, int. Will be 6 for header
|
||||
#dtype_vseq = hex(int(_dtype_vseq)).encode()
|
||||
if _dtype_vseq == 6:
|
||||
dtype_vseq = bitarray('0110')
|
||||
if _dtype_vseq == 7:
|
||||
dtype_vseq = bitarray('0111')
|
||||
if _dtype_vseq == 3:
|
||||
dtype_vseq = bitarray('0011')
|
||||
# 9 digit integer in hex
|
||||
stream_id = bytes_4(_stream_id)
|
||||
#print(ahex(stream_id))
|
||||
|
||||
middle_guts = slot + call_type + frame_type + dtype_vseq
|
||||
#print(middle_guts)
|
||||
dmr_data = str(_dmr_data)[2:-1] #str(re.sub("b'|'", '', str(_dmr_data)))
|
||||
complete_packet = signature.encode() + seq + dest_id + source_id + via_id + middle_guts.tobytes() + stream_id + bytes.fromhex((dmr_data)) + bitarray('0000000000101111').tobytes()#bytes.fromhex(dmr_data)
|
||||
#print('Complete: ' + type(ahex(complete_packet)))
|
||||
## #print(hex2bits(ahex(complete_packet))[119:120])
|
||||
#print(bitarray.frombytes(ahex(complete_packet)))
|
||||
return complete_packet
|
||||
|
||||
|
||||
### Sequence MMDVM packets from encoded DMR
|
||||
##def seq_mmdvm(dmr_list):
|
||||
## cap_in = 0
|
||||
## mmdvm_send_seq = []
|
||||
## for i in dmr_list:
|
||||
## if cap_in < 8:
|
||||
##
|
||||
## if cap_in == 8:
|
||||
## #print('header')
|
||||
## the_mmdvm_pkt = mmdvm_encapsulate(3153597, 3153591, 9099, cap_in, 1, 1, 6, rand_seq, i) #(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
## else:
|
||||
## #print('block')
|
||||
## the_mmdvm_pkt = mmdvm_encapsulate(3153597, 3153591, 9099, cap_in, 1, 1, 7, rand_seq, i)#(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
## new_send_seq.append(ahex(the_mmdvm_pkt))
|
||||
## cap_in = cap_in + 1
|
||||
|
||||
# Break long string into block sequence
|
||||
def block_sequence(input_string):
|
||||
seq_blocks = len(input_string)/24
|
||||
n = 0
|
||||
block_seq = []
|
||||
while n < seq_blocks:
|
||||
if n == 0:
|
||||
block_seq.append(bytes.fromhex(input_string[:24].ljust(24,'0')))
|
||||
n = n + 1
|
||||
else:
|
||||
block_seq.append(bytes.fromhex(input_string[n*24:n*24+24].ljust(24,'0')))
|
||||
n = n + 1
|
||||
return block_seq
|
||||
|
||||
# Takes list of DMR packets, 12 bytes, then encodes them
|
||||
def dmr_encode(packet_list, _slot):
|
||||
send_seq = []
|
||||
for i in packet_list:
|
||||
stitched_pkt = bptc.interleave_19696(bptc.encode_19696(i))
|
||||
l_slot = bitarray('0111011100')
|
||||
#MS
|
||||
#sync_data = bitarray('110101011101011111110111011111111101011101010111')
|
||||
if _slot == 0:
|
||||
# TS1 - F7FDD5DDFD55
|
||||
sync_data = bitarray('111101111111110111010101110111011111110101010101')
|
||||
if _slot == 1:
|
||||
#TS2 - D7557F5FF7F5
|
||||
sync_data = bitarray('110101110101010101111111010111111111011111110101')
|
||||
if _slot == 3:
|
||||
sync_data = bitarray('110101011101011111110111011111111101011101010111')
|
||||
# TS1
|
||||
#sync_data = bitarray('111101111111110111010101110111011111110101010101')
|
||||
#TS2
|
||||
#sync_data = bitarray('110101110101010101111111010111111111011111110101')
|
||||
r_slot = bitarray('1101110001')
|
||||
# Data sync? 110101011101011111110111011111111101011101010111 - D5D7F77FD757
|
||||
new_pkt = ahex(stitched_pkt[:98] + l_slot + sync_data + r_slot + stitched_pkt[98:])
|
||||
send_seq.append(new_pkt)
|
||||
return send_seq
|
||||
|
||||
|
||||
def create_sms_seq(dst_id, src_id, peer_id, _slot, _call_type, dmr_string):
|
||||
rand_seq = random.randint(1, 999999)
|
||||
block_seq = block_sequence(dmr_string)
|
||||
dmr_list = dmr_encode(block_seq, _slot)
|
||||
cap_in = 0
|
||||
mmdvm_send_seq = []
|
||||
for i in dmr_list:
|
||||
#print(i)
|
||||
if use_csbk == True:
|
||||
if cap_in < 5:
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 3, rand_seq, i)
|
||||
#print(block_seq[cap_in])
|
||||
#print(3)
|
||||
if cap_in == 5:
|
||||
#print(block_seq[cap_in])
|
||||
#print(6)
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 6, rand_seq, i) #(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
if cap_in > 5:
|
||||
#print(block_seq[cap_in])
|
||||
#print(7)
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 7, rand_seq, i)#(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
mmdvm_send_seq.append(ahex(the_mmdvm_pkt))
|
||||
cap_in = cap_in + 1
|
||||
if use_csbk == False:
|
||||
if cap_in == 0:
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 6, rand_seq, i) #(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
else:
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 7, rand_seq, i)#(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
mmdvm_send_seq.append(ahex(the_mmdvm_pkt))
|
||||
cap_in = cap_in + 1
|
||||
with open('/tmp/.hblink_data_que/' + str(random.randint(1000, 9999)) + '.mmdvm_seq', "w") as packet_write_file:
|
||||
packet_write_file.write(str(mmdvm_send_seq))
|
||||
|
||||
return mmdvm_send_seq
|
||||
try:
|
||||
Path('/tmp/.hblink_data_que/').mkdir(parents=True, exist_ok=True)
|
||||
except:
|
||||
pass
|
||||
|
||||
# Built for max length msg
|
||||
def sms_headers(to_id, from_id):
|
||||
## #ETSI 102 361-2 uncompressed ipv4
|
||||
## # UDP header, src and dest ports are 4007, 0fa7
|
||||
## udp_ports = '0fa70fa7'
|
||||
## # Length, of what?
|
||||
## udp_length = '00da'
|
||||
## # Checksum
|
||||
## udp_checksum = '4b37'
|
||||
##
|
||||
## # IPV4
|
||||
## #IPV4 version and header length, always 45
|
||||
## ipv4_v_l = '45'
|
||||
## #Type of service, always 00
|
||||
## ipv4_svc = '00'
|
||||
## #length, always 00ee
|
||||
## ipv4_len = '00ee'
|
||||
## #ID always 000d
|
||||
## ipv4_id = '000d'
|
||||
## #Flags and offset always0
|
||||
## ipv4_flag_off = '0000'
|
||||
## #TTL and Protocol always 4011, no matter what
|
||||
## ipv4_ttl_proto = '4011'
|
||||
#ipv4 = '450000ee000d0000401100000c' + from_id + '0c' + to_id
|
||||
#ipv4 = '450000ee00000000401100000c' + from_id + '0c' + to_id
|
||||
ipv4 = '450000ee00000000401100000c' + from_id + '0c' + to_id
|
||||
print(from_id)
|
||||
print(to_id)
|
||||
count_index = 0
|
||||
hdr_lst = []
|
||||
while count_index < len(ipv4):
|
||||
hdr_lst.append((ipv4[count_index:count_index + 4]))
|
||||
count_index = count_index + 4
|
||||
sum = 0
|
||||
for i in hdr_lst:
|
||||
sum = sum + int(i, 16)
|
||||
flipped = ''
|
||||
for i in str(bin(sum))[2:]:
|
||||
if i == '1':
|
||||
flipped = flipped + '0'
|
||||
if i == '0':
|
||||
flipped = flipped + '1'
|
||||
ipv4_chk_sum = str(hex(int(flipped, 2)))[2:]
|
||||
print(ipv4_chk_sum)
|
||||
|
||||
|
||||
|
||||
#'0fa70fa7001a8b810010e0008f040d000a'
|
||||
#'0fa70fa7001a5b810010e00090040d000a'
|
||||
#'0fa70fa7001a5a810010e00091040d000a'
|
||||
header = ipv4[:20] + ipv4_chk_sum + ipv4[24:] + '0fa70fa700da583100d0a00081040d000a'
|
||||
return header
|
||||
|
||||
def format_sms(msg, to_id, from_id):
|
||||
msg_bytes = str.encode(msg)
|
||||
encoded = "".join([str('00' + x) for x in re.findall('..',bytes.hex(msg_bytes))] )
|
||||
final = encoded
|
||||
while len(final) < 400:
|
||||
final = final + '002e'
|
||||
final = final + '0000000000000000000000'
|
||||
headers = sms_headers(to_id, from_id)
|
||||
return headers + final
|
||||
|
||||
def gen_header(to_id, from_id, call_type):
|
||||
#print(call_type)
|
||||
if call_type == 1:
|
||||
seq_header = '024A' + to_id + from_id + '9550'
|
||||
if call_type == 0:
|
||||
seq_header = '824A' + to_id + from_id + '9550'
|
||||
return seq_header
|
||||
|
||||
def send_sms(csbk, to_id, from_id, peer_id, call_type, slot, msg):
|
||||
global use_csbk
|
||||
#to_id = str(hex(to_id))[2:].zfill(6)
|
||||
#from_id = str(hex(from_id))[2:].zfill(6)
|
||||
to_id = str(hex(to_id))[2:].zfill(6)
|
||||
from_id = str(hex(from_id))[2:].zfill(6)
|
||||
peer_id = str(hex(peer_id))[2:].zfill(8)
|
||||
# Weird fix for redio not decoding, will fix later
|
||||
if len(str(int(cli_args.SRC))) >= 4 and len(str(int(cli_args.SRC))) <= 6:
|
||||
from_id = str('000000')
|
||||
if call_type == 'unit':
|
||||
new_call_type = 1
|
||||
if call_type == 'group':
|
||||
new_call_type = 0
|
||||
if csbk == 'yes':
|
||||
use_csbk = True
|
||||
create_sms_seq(to_id, from_id, peer_id, int(slot), new_call_type, csbk_gen(to_id, from_id) + create_crc16(gen_header(to_id, from_id, new_call_type)) + create_crc32(format_sms(msg, to_id, from_id)))
|
||||
else:
|
||||
use_csbk = False
|
||||
create_sms_seq(to_id, from_id, peer_id, int(slot), new_call_type, create_crc16(gen_header(to_id, from_id, new_call_type)) + create_crc32(format_sms(msg, to_id, from_id)))
|
||||
print('Call type: ' + call_type)
|
||||
print('Destination: ' + str(to_id))
|
||||
print('Source: ' + str(from_id))
|
||||
print('Message: ' + msg)
|
||||
print('Use CSBK: ' + str(use_csbk))
|
||||
#send_sms(1234567, 1234, 0000, 'unit', '...............................................................................................')
|
||||
|
||||
|
||||
#create_sms_seq('301ebd', '301eb7', '0000', 1, 1, '024A301EBD301EB7851093184500003400020000401124e40c301eb70c301ebd0fa70fa70020326f0016a00083040d000a00540045005300540049004e00470000000000c3d8b05d')
|
||||
|
||||
if __name__ == '__main__':
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-d', '--dest', action='store', dest='DEST', help='Destination DMR ID')
|
||||
parser.add_argument('-s', '--src', action='store', dest='SRC', help='Source DMR ID (Sender)')
|
||||
parser.add_argument('-m', '--msg', action='store', dest='MSG', help='Message to be sent')
|
||||
parser.add_argument('-t', '--type', action='store', dest='TYPE', help='Unit (private) or Group message')
|
||||
parser.add_argument('-ts', '--slot', action='store', dest='TS', help='Unit (private) or Group message')
|
||||
parser.add_argument('-c', '--csbk', dest='CSBK', action="store_true", help='Send CSBK Preambles')
|
||||
cli_args = parser.parse_args()
|
||||
|
||||
if not cli_args.SRC:
|
||||
cli_args.SRC = 0000
|
||||
if cli_args.CSBK:
|
||||
cli_args.CSBK = "yes"
|
||||
if not cli_args.CSBK:
|
||||
cli_args.CSBK = "no"
|
||||
send_sms(cli_args.CSBK, int(cli_args.DEST), int(cli_args.SRC), 0000, str(cli_args.TYPE), int(cli_args.TS), str(cli_args.MSG)[:100])
|
||||
|
||||
|
||||
|
439
full_bridge-SAMPLE.cfg
Normal file
439
full_bridge-SAMPLE.cfg
Normal file
@ -0,0 +1,439 @@
|
||||
# PROGRAM-WIDE PARAMETERS GO HERE
|
||||
# PATH - working path for files, leave it alone unless you NEED to change it
|
||||
# PING_TIME - the interval that peers will ping the master, and re-try registraion
|
||||
# - how often the Master maintenance loop runs
|
||||
# MAX_MISSED - how many pings are missed before we give up and re-register
|
||||
# - number of times the master maintenance loop runs before de-registering a peer
|
||||
#
|
||||
# ACLs:
|
||||
#
|
||||
# Access Control Lists are a very powerful tool for administering your system.
|
||||
# But they consume packet processing time. Disable them if you are not using them.
|
||||
# But be aware that, as of now, the configuration stanzas still need the ACL
|
||||
# sections configured even if you're not using them.
|
||||
#
|
||||
# REGISTRATION ACLS ARE ALWAYS USED, ONLY SUBSCRIBER AND TGID MAY BE DISABLED!!!
|
||||
#
|
||||
# The 'action' May be PERMIT|DENY
|
||||
# Each entry may be a single radio id, or a hypenated range (e.g. 1-2999)
|
||||
# Format:
|
||||
# ACL = 'action:id|start-end|,id|start-end,....'
|
||||
# --for example--
|
||||
# SUB_ACL: DENY:1,1000-2000,4500-60000,17
|
||||
#
|
||||
# ACL Types:
|
||||
# REG_ACL: peer radio IDs for registration (only used on HBP master systems)
|
||||
# SUB_ACL: subscriber IDs for end-users
|
||||
# TGID_TS1_ACL: destination talkgroup IDs on Timeslot 1
|
||||
# TGID_TS2_ACL: destination talkgroup IDs on Timeslot 2
|
||||
#
|
||||
# ACLs may be repeated for individual systems if needed for granularity
|
||||
# Global ACLs will be processed BEFORE the system level ACLs
|
||||
# Packets will be matched against all ACLs, GLOBAL first. If a packet 'passes'
|
||||
# All elements, processing continues. Packets are discarded at the first
|
||||
# negative match, or 'reject' from an ACL element.
|
||||
#
|
||||
# If you do not wish to use ACLs, set them to 'PERMIT:ALL'
|
||||
# TGID_TS1_ACL in the global stanza is used for OPENBRIDGE systems, since all
|
||||
# traffic is passed as TS 1 between OpenBridges
|
||||
[GLOBAL]
|
||||
PATH: ./
|
||||
PING_TIME: 5
|
||||
MAX_MISSED: 3
|
||||
USE_ACL: True
|
||||
REG_ACL: PERMIT:ALL
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
||||
|
||||
# NOT YET WORKING: NETWORK REPORTING CONFIGURATION
|
||||
# Enabling "REPORT" will configure a socket-based reporting
|
||||
# system that will send the configuration and other items
|
||||
# to a another process (local or remote) that may process
|
||||
# the information for some useful purpose, like a web dashboard.
|
||||
#
|
||||
# REPORT - True to enable, False to disable
|
||||
# REPORT_INTERVAL - Seconds between reports
|
||||
# REPORT_PORT - TCP port to listen on if "REPORT_NETWORKS" = NETWORK
|
||||
# REPORT_CLIENTS - comma separated list of IPs you will allow clients
|
||||
# to connect on. Entering a * will allow all.
|
||||
#
|
||||
# ****FOR NOW MUST BE TRUE - USE THE LOOPBACK IF YOU DON'T USE THIS!!!****
|
||||
[REPORTS]
|
||||
REPORT: True
|
||||
REPORT_INTERVAL: 60
|
||||
REPORT_PORT: 4321
|
||||
REPORT_CLIENTS: 127.0.0.1
|
||||
|
||||
|
||||
# SYSTEM LOGGER CONFIGURAITON
|
||||
# This allows the logger to be configured without chaning the individual
|
||||
# python logger stuff. LOG_FILE should be a complete path/filename for *your*
|
||||
# system -- use /dev/null for non-file handlers.
|
||||
# LOG_HANDLERS may be any of the following, please, no spaces in the
|
||||
# list if you use several:
|
||||
# null
|
||||
# console
|
||||
# console-timed
|
||||
# file
|
||||
# file-timed
|
||||
# syslog
|
||||
# LOG_LEVEL may be any of the standard syslog logging levels, though
|
||||
# as of now, DEBUG, INFO, WARNING and CRITICAL are the only ones
|
||||
# used.
|
||||
#
|
||||
[LOGGER]
|
||||
LOG_FILE: /tmp/gps_data.log
|
||||
LOG_HANDLERS: console-timed
|
||||
LOG_LEVEL: DEBUG
|
||||
LOG_NAME: HBlink3 GPS/Data
|
||||
|
||||
# DOWNLOAD AND IMPORT SUBSCRIBER, PEER and TGID ALIASES
|
||||
# Ok, not the TGID, there's no master list I know of to download
|
||||
# This is intended as a facility for other applcations built on top of
|
||||
# HBlink to use, and will NOT be used in HBlink directly.
|
||||
# STALE_DAYS is the number of days since the last download before we
|
||||
# download again. Don't be an ass and change this to less than a few days.
|
||||
[ALIASES]
|
||||
TRY_DOWNLOAD: True
|
||||
PATH: ./
|
||||
PEER_FILE: peer_ids.json
|
||||
SUBSCRIBER_FILE: subscriber_ids.json
|
||||
TGID_FILE: talkgroup_ids.json
|
||||
PEER_URL: https://www.radioid.net/static/rptrs.json
|
||||
SUBSCRIBER_URL: https://www.radioid.net/static/users.json
|
||||
STALE_DAYS: 1
|
||||
|
||||
#####################################################################
|
||||
# GPS/Data Application - by KF7EEL
|
||||
# Configure the settings for the DMR GPS to APRS position application here.
|
||||
#
|
||||
# DATA_DMR_ID - This is the DMR ID that users send SMS and GPS data.
|
||||
# CALL_TYPE - group, unit, or both. Group if you want users to send data to a talkgroup,
|
||||
# unit if you want users to send data as a private call, or both if you want both options.
|
||||
# UNIT_SMS_TS - Default timeslot for private SMS, where the subscriber's last TS is not known.
|
||||
# UNIT_SMS_TS can be 1 or 2
|
||||
[GPS_DATA]
|
||||
DATA_DMR_ID: 9099
|
||||
CALL_TYPE: unit
|
||||
UNIT_SMS_TS: 2
|
||||
|
||||
# APRS configuration
|
||||
# This section contains APRS configuration for the gateway.
|
||||
# USER_APRS_SSID - Default APRS SSID assigned to user APRS positions.
|
||||
# USER_APRS_COMMENT - Default Comment attached to user APRS positions.
|
||||
# APRS_LOGIN_CALL, PASSCODE, SERVER, and PORT - Gateway login settings for APRS-IS.
|
||||
USER_APRS_SSID: 15
|
||||
USER_APRS_COMMENT: HBLink3 D-APRS -
|
||||
# Setting APRS_LOGIN_CALL to N0CALL will cause the gateway to not upload packets to APRS server.
|
||||
# Set to N0CALL if you wish to disable APRS.
|
||||
APRS_LOGIN_CALL: N0CALL
|
||||
APRS_LOGIN_PASSCODE: 12345
|
||||
APRS_SERVER: rotate.aprs2.net
|
||||
APRS_PORT: 14580
|
||||
|
||||
# The APRS filter below is used for receiving messages.
|
||||
#See http://www.aprs-is.net/javAPRSFilter.aspx for details about APRS filters.
|
||||
APRS_FILTER: r/47/-120/500 t/m
|
||||
|
||||
# The following configuration options are for uploading a position of the gateway itself.
|
||||
# When the gateway uploads a position, APRS software such as aprs.fi will see it as an Igate,
|
||||
# this is useful if you want aprs.fi to keep statistics.
|
||||
# Time in minutes. Set IGATE_BEACON_TIME to 0 to disable Igate beaconing.
|
||||
IGATE_BEACON_TIME = 45
|
||||
IGATE_BEACON_COMMENT = HBLink3 D-APRS Gateway
|
||||
IGATE_BEACON_ICON = /I
|
||||
IGATE_LATITUDE = 0000.00N
|
||||
IGATE_LONGITUDE = 00000.00W
|
||||
|
||||
# The following settings are for the static positions only, for hotspots or repeaters connected to MASTER stanzas.
|
||||
# Implementation by IU7IGU
|
||||
# REPORT_INTERVAL in Minute (ALLOW only > 3 Minutes)
|
||||
# MESSAGE: This message will print on APRS description together RX and TX Frequency
|
||||
APRS_STATIC_REPORT_INTERVAL: 15
|
||||
APRS_STATIC_MESSAGE:Connected to HBLink
|
||||
|
||||
|
||||
###### Removing Soon ###################
|
||||
# The email gateway settingns below are OPTIONAL. They are NOT REQUIRED if you don't want
|
||||
# http://www.aprs-is.net/javAPRSFilter.aspx# to enable the email gateway. Leave as is to disable.
|
||||
EMAIL_SENDER: test@example.org
|
||||
EMAIL_PASSWORD: letmein
|
||||
SMTP_SERVER: smtp.gmail.com
|
||||
SMTP_PORT: 465
|
||||
########################################
|
||||
|
||||
|
||||
# The options below are required for operation of the dashboard and will cause errors if configures incorrectly.
|
||||
# Leave them as default unless you know what you are doing.
|
||||
# If you do change, you MUST use absolute paths.
|
||||
LOCATION_FILE: /tmp/gps_data_user_loc.txt
|
||||
BULLETIN_BOARD_FILE: /tmp/gps_data_user_bb.txt
|
||||
MAILBOX_FILE: /tmp/gps_data_user_mailbox.txt
|
||||
EMERGENCY_SOS_FILE: /tmp/gps_data_user_sos.txt
|
||||
|
||||
# REQUIRED TO CHANGE
|
||||
# User settings file, MUST configure using absolute path.
|
||||
USER_SETTINGS_FILE: /path/to/user_settings.txt
|
||||
|
||||
# API Configuration
|
||||
# MY_SERVER_SHORTCUT - Short abbreviation, must match other users access.
|
||||
# Server name - can be different than dashboard title, used to identify this network/server.
|
||||
# AUTHORIZED_TOKENS_FILE, OK to leave as default. This is the file where one time tokens are saved.
|
||||
# MY_SERVER_SHORTCUT, should be something short, ideally 3 or 4 letters. This is used in the authentication and
|
||||
# sending process. Should be unique from other servers, especially if you plan on allowing public access.
|
||||
# SERVER_NAME, the name of your server or network. This is used to identify your server with some external applications.
|
||||
# USE_PUBLIC_APPS, Allow your users to use publically accessible external applications.
|
||||
# PUBLIC_APPS_LIST, URL to list of public external applications. Leave as default.
|
||||
USE_API: True
|
||||
AUTHORIZED_TOKENS_FILE: /tmp/hblink_auth_tokens.txt
|
||||
MY_SERVER_SHORTCUT: ABC
|
||||
SERVER_NAME: Regional HBLink3 Server
|
||||
USE_PUBLIC_APPS: True
|
||||
PUBLIC_APPS_LIST: https://raw.githubusercontent.com/kf7eel/hblink_sms_external_apps/main/public_systems.txt
|
||||
|
||||
# REQUIRED TO CHANGE
|
||||
RULES_PATH: /path/to/rules.py
|
||||
|
||||
|
||||
# The following options are used for the dashboard. The dashboard is optional.
|
||||
# Title of the Dashboard
|
||||
DASHBOARD_TITLE: HBLink3 D-APRS Dashboard
|
||||
|
||||
# Used for API, RSS feed link, etc. This MUST be accessible.
|
||||
# Do not add a trailing /
|
||||
# You must set this if you are using the API.
|
||||
DASHBOARD_URL: http://localhost:8092
|
||||
|
||||
# Logo used on dashboard page
|
||||
LOGO: https://raw.githubusercontent.com/kf7eel/hblink3/gps/HBlink.png
|
||||
|
||||
# Port to run server
|
||||
DASH_PORT: 8092
|
||||
|
||||
# IP to run server on
|
||||
DASH_HOST: 127.0.0.1
|
||||
|
||||
#Description of dashboard to show on main page
|
||||
DESCRIPTION: Welcome to the dashboard.
|
||||
|
||||
# Gateway contact info displayed on about page.
|
||||
CONTACT_NAME: your name
|
||||
CONTACT_CALL: N0CALL
|
||||
CONTACT_EMAIL: email@example.org
|
||||
CONTACT_WEBSITE: https://hbl.ink
|
||||
|
||||
# Time format for display
|
||||
TIME_FORMAT: %%H:%%M:%%S - %%m/%%d/%%y
|
||||
|
||||
# Center dashboard map over these coordinates
|
||||
MAP_CENTER_LAT: 47.00
|
||||
MAP_CENTER_LON: -120.00
|
||||
ZOOM_LEVEL: 7
|
||||
|
||||
# List and preview of some map themes at http://leaflet-extras.github.io/leaflet-providers/preview/
|
||||
# The following are options for map themes and just work, you should use one of these: “OpenStreetMap”, “Stamen” (Terrain, Toner, and Watercolor).
|
||||
MAP_THEME: Stamen Toner
|
||||
|
||||
#####################################################################
|
||||
# OPENBRIDGE INSTANCES - DUPLICATE SECTION FOR MULTIPLE CONNECTIONS
|
||||
# OpenBridge is a protocol originall created by DMR+ for connection between an
|
||||
# IPSC2 server and Brandmeister. It has been implemented here at the suggestion
|
||||
# of the Brandmeister team as a way to legitimately connect HBlink to the
|
||||
# Brandemiester network.
|
||||
# It is recommended to name the system the ID of the Brandmeister server that
|
||||
# it connects to, but is not necessary. TARGET_IP and TARGET_PORT are of the
|
||||
# Brandmeister or IPSC2 server you are connecting to. PASSPHRASE is the password
|
||||
# that must be agreed upon between you and the operator of the server you are
|
||||
# connecting to. NETWORK_ID is a number in the format of a DMR Radio ID that
|
||||
# will be sent to the other server to identify this connection.
|
||||
# other parameters follow the other system types.
|
||||
#
|
||||
# ACLs:
|
||||
# OpenBridge does not 'register', so registration ACL is meaningless.
|
||||
# Proper OpenBridge passes all traffic on TS1.
|
||||
# HBlink can extend OPB to use both slots for unit calls only.
|
||||
# Setting "BOTH_SLOTS" True ONLY affects unit traffic!
|
||||
# Otherwise ACLs work as described in the global stanza
|
||||
|
||||
[OBP-1]
|
||||
MODE: OPENBRIDGE
|
||||
ENABLED: True
|
||||
IP:
|
||||
PORT: 62035
|
||||
NETWORK_ID: 3129100
|
||||
PASSPHRASE: password
|
||||
TARGET_IP: 1.2.3.4
|
||||
TARGET_PORT: 62035
|
||||
BOTH_SLOTS: True
|
||||
USE_ACL: True
|
||||
SUB_ACL: DENY:1
|
||||
TGID_ACL: PERMIT:ALL
|
||||
|
||||
# MASTER INSTANCES - DUPLICATE SECTION FOR MULTIPLE MASTERS
|
||||
# HomeBrew Protocol Master instances go here.
|
||||
# IP may be left blank if there's one interface on your system.
|
||||
# Port should be the port you want this master to listen on. It must be unique
|
||||
# and unused by anything else.
|
||||
# Repeat - if True, the master repeats traffic to peers, False, it does nothing.
|
||||
#
|
||||
# MAX_PEERS -- maximun number of peers that may be connect to this master
|
||||
# at any given time. This is very handy if you're allowing hotspots to
|
||||
# connect, or using a limited computer like a Raspberry Pi.
|
||||
#
|
||||
# ACLs:
|
||||
# See comments in the GLOBAL stanza
|
||||
[MASTER-1]
|
||||
MODE: MASTER
|
||||
ENABLED: False
|
||||
STATIC_APRS_POSITION_ENABLED: False
|
||||
REPEAT: True
|
||||
MAX_PEERS: 10
|
||||
EXPORT_AMBE: False
|
||||
IP:
|
||||
PORT: 54000
|
||||
PASSPHRASE: password
|
||||
GROUP_HANGTIME: 5
|
||||
USE_ACL: True
|
||||
REG_ACL: DENY:1
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
||||
|
||||
# Utilizing the hotspot proxy modified and used from FreeDMR
|
||||
[HOTSPOT]
|
||||
MODE: PROXY
|
||||
ENABLED: False
|
||||
# Configure as you would for a normal MASTER. These options will apply to all connected peers.
|
||||
STATIC_APRS_POSITION_ENABLED: False
|
||||
REPEAT: True
|
||||
EXPORT_AMBE: False
|
||||
PASSPHRASE: passw0rd
|
||||
GROUP_HANGTIME: 5
|
||||
USE_ACL: True
|
||||
REG_ACL: DENY:1
|
||||
SUB_ACL: DENY:1
|
||||
TG1_ACL: PERMIT:ALL
|
||||
TG2_ACL: PERMIT:ALL
|
||||
# Use the provided proxy script as opposed to starting a new thread at start.
|
||||
# Set to False if you are not worried about performance issues.
|
||||
EXTERNAL_PROXY_SCRIPT: False
|
||||
# Port that peers will connect on. This port should be opened in your firewall.
|
||||
EXTERNAL_PORT: 62028
|
||||
# Internal ports used for generated master instances. Peers shouldn't connect directly to these ports.
|
||||
# There is no need to open these ports in your server's firewall. A MASTER instance will be generated for each port in the range below.
|
||||
INTERNAL_PORT_START: 58000
|
||||
INTERNAL_PORT_STOP: 58005
|
||||
|
||||
|
||||
# PEER INSTANCES - DUPLICATE SECTION FOR MULTIPLE PEERS
|
||||
# There are a LOT of errors in the HB Protocol specifications on this one!
|
||||
# MOST of these items are just strings and will be properly dealt with by the program
|
||||
# The TX & RX Frequencies are 9-digit numbers, and are the frequency in Hz.
|
||||
# Latitude is an 8-digit unsigned floating point number.
|
||||
# Longitude is a 9-digit signed floating point number.
|
||||
# Height is in meters
|
||||
# Setting Loose to True relaxes the validation on packets received from the master.
|
||||
# This will allow HBlink to connect to a non-compliant system such as XLXD, DMR+ etc.
|
||||
#
|
||||
# ACLs:
|
||||
# See comments in the GLOBAL stanza
|
||||
|
||||
[REPEATER-1]
|
||||
MODE: PEER
|
||||
ENABLED: False
|
||||
LOOSE: False
|
||||
EXPORT_AMBE: False
|
||||
IP:
|
||||
PORT: 54001
|
||||
MASTER_IP: 172.16.1.1
|
||||
MASTER_PORT: 54000
|
||||
PASSPHRASE: homebrew
|
||||
CALLSIGN: W1ABC
|
||||
RADIO_ID: 312000
|
||||
RX_FREQ: 449000000
|
||||
TX_FREQ: 444000000
|
||||
TX_POWER: 25
|
||||
COLORCODE: 1
|
||||
SLOTS: 1
|
||||
LATITUDE: 38.0000
|
||||
LONGITUDE: -095.0000
|
||||
HEIGHT: 75
|
||||
LOCATION: Anywhere, USA
|
||||
DESCRIPTION: This is a cool repeater
|
||||
URL: www.w1abc.org
|
||||
SOFTWARE_ID: 20170620
|
||||
PACKAGE_ID: MMDVM_HBlink
|
||||
GROUP_HANGTIME: 5
|
||||
OPTIONS:
|
||||
USE_ACL: True
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
||||
[ECHO]
|
||||
MODE: PEER
|
||||
ENABLED: True
|
||||
LOOSE: False
|
||||
EXPORT_AMBE: False
|
||||
IP:
|
||||
PORT: 54073
|
||||
MASTER_IP: localhost
|
||||
MASTER_PORT: 54072
|
||||
passphrase: passw0rd
|
||||
CALLSIGN: ECHO
|
||||
RADIO_ID: 9999
|
||||
RX_FREQ: 000000000
|
||||
TX_FREQ: 000000000
|
||||
TX_POWER: 0
|
||||
COLORCODE: 1
|
||||
SLOTS: 1
|
||||
LATITUDE: 00.0000
|
||||
LONGITUDE: 000.0000
|
||||
HEIGHT: 0
|
||||
LOCATION: This Server
|
||||
DESCRIPTION: Echo Server
|
||||
URL: www.github.com/kf7eel/hblink3
|
||||
SOFTWARE_ID: 20170620
|
||||
PACKAGE_ID: MMDVM_HBlink
|
||||
GROUP_HANGTIME: 5
|
||||
OPTIONS:
|
||||
USE_ACL: True
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
||||
[XLX-1]
|
||||
MODE: XLXPEER
|
||||
ENABLED: False
|
||||
LOOSE: True
|
||||
EXPORT_AMBE: False
|
||||
IP:
|
||||
PORT: 54002
|
||||
MASTER_IP: 172.16.1.1
|
||||
MASTER_PORT: 62030
|
||||
PASSPHRASE: passw0rd
|
||||
CALLSIGN: W1ABC
|
||||
RADIO_ID: 312000
|
||||
RX_FREQ: 449000000
|
||||
TX_FREQ: 444000000
|
||||
TX_POWER: 25
|
||||
COLORCODE: 1
|
||||
SLOTS: 1
|
||||
LATITUDE: 38.0000
|
||||
LONGITUDE: -095.0000
|
||||
HEIGHT: 75
|
||||
LOCATION: Anywhere, USA
|
||||
DESCRIPTION: This is a cool repeater
|
||||
URL: www.w1abc.org
|
||||
SOFTWARE_ID: 20170620
|
||||
PACKAGE_ID: MMDVM_HBlink
|
||||
GROUP_HANGTIME: 5
|
||||
XLXMODULE: 4004
|
||||
USE_ACL: True
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
2968
full_bridge.py
Normal file
2968
full_bridge.py
Normal file
File diff suppressed because it is too large
Load Diff
204
hotspot_proxy_v2.py
Normal file
204
hotspot_proxy_v2.py
Normal file
@ -0,0 +1,204 @@
|
||||
from twisted.internet.protocol import DatagramProtocol
|
||||
from twisted.internet import reactor, task
|
||||
from time import time
|
||||
from resettabletimer import ResettableTimer
|
||||
from dmr_utils3.utils import int_id
|
||||
import random
|
||||
|
||||
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
|
||||
__author__ = 'Simon Adlem - G7RZU'
|
||||
__copyright__ = 'Copyright (c) Simon Adlem, G7RZU 2020,2021'
|
||||
__credits__ = 'Jon Lee, G4TSN; Norman Williams, M6NBP'
|
||||
__license__ = 'GNU GPLv3'
|
||||
__maintainer__ = 'Simon Adlem G7RZU'
|
||||
__email__ = 'simon@gb7fr.org.uk'
|
||||
|
||||
class Proxy(DatagramProtocol):
|
||||
|
||||
def __init__(self,Master,ListenPort,connTrack,blackList,Timeout,Debug,DestportStart,DestPortEnd):
|
||||
self.master = Master
|
||||
self.connTrack = connTrack
|
||||
self.peerTrack = {}
|
||||
self.timeout = Timeout
|
||||
self.debug = Debug
|
||||
self.blackList = blackList
|
||||
self.destPortStart = DestportStart
|
||||
self.destPortEnd = DestPortEnd
|
||||
self.numPorts = DestPortEnd - DestportStart
|
||||
|
||||
|
||||
def reaper(self,_peer_id):
|
||||
if self.debug:
|
||||
print("dead",_peer_id)
|
||||
self.transport.write(b'RPTCL'+_peer_id, ('127.0.0.1',self.peerTrack[_peer_id]['dport']))
|
||||
self.connTrack[self.peerTrack[_peer_id]['dport']] = False
|
||||
del self.peerTrack[_peer_id]
|
||||
|
||||
|
||||
def datagramReceived(self, data, addr):
|
||||
|
||||
# HomeBrew Protocol Commands
|
||||
DMRD = b'DMRD'
|
||||
DMRA = b'DMRA'
|
||||
MSTCL = b'MSTCL'
|
||||
MSTNAK = b'MSTNAK'
|
||||
MSTPONG = b'MSTPONG'
|
||||
MSTN = b'MSTN'
|
||||
MSTP = b'MSTP'
|
||||
MSTC = b'MSTC'
|
||||
RPTL = b'RPTL'
|
||||
RPTPING = b'RPTPING'
|
||||
RPTCL = b'RPTCL'
|
||||
RPTL = b'RPTL'
|
||||
RPTACK = b'RPTACK'
|
||||
RPTK = b'RPTK'
|
||||
RPTC = b'RPTC'
|
||||
RPTP = b'RPTP'
|
||||
RPTA = b'RPTA'
|
||||
RPTO = b'RPTO'
|
||||
|
||||
host,port = addr
|
||||
|
||||
nowtime = time()
|
||||
|
||||
Debug = self.debug
|
||||
|
||||
#If the packet comes from the master
|
||||
if host == self.master:
|
||||
_command = data[:4]
|
||||
|
||||
if _command == DMRD:
|
||||
_peer_id = data[11:15]
|
||||
elif _command == RPTA:
|
||||
if data[6:10] in self.peerTrack:
|
||||
_peer_id = data[6:10]
|
||||
else:
|
||||
_peer_id = self.connTrack[port]
|
||||
elif _command == MSTN:
|
||||
_peer_id = data[6:10]
|
||||
self.peerTrack[_peer_id]['timer'].cancel()
|
||||
self.reaper(_peer_id)
|
||||
return
|
||||
elif _command == MSTP:
|
||||
_peer_id = data[7:11]
|
||||
elif _command == MSTC:
|
||||
_peer_id = data[5:9]
|
||||
self.peerTrack[_peer_id]['timer'].cancel()
|
||||
self.reaper(_peer_id)
|
||||
return
|
||||
|
||||
# _peer_id = self.connTrack[port]
|
||||
if self.debug:
|
||||
print(data)
|
||||
if _peer_id and _peer_id in self.peerTrack:
|
||||
self.transport.write(data,(self.peerTrack[_peer_id]['shost'],self.peerTrack[_peer_id]['sport']))
|
||||
#self.peerTrack[_peer_id]['timer'].reset()
|
||||
return
|
||||
|
||||
|
||||
|
||||
else:
|
||||
_command = data[:4]
|
||||
|
||||
if _command == DMRD: # DMRData -- encapsulated DMR data frame
|
||||
_peer_id = data[11:15]
|
||||
elif _command == DMRA: # DMRAlias -- Talker Alias information
|
||||
_peer_id = _data[4:8]
|
||||
elif _command == RPTL: # RPTLogin -- a repeater wants to login
|
||||
_peer_id = data[4:8]
|
||||
elif _command == RPTK: # Repeater has answered our login challenge
|
||||
_peer_id = data[4:8]
|
||||
elif _command == RPTC: # Repeater is sending it's configuraiton OR disconnecting
|
||||
if data[:5] == RPTCL: # Disconnect command
|
||||
_peer_id = data[5:9]
|
||||
else:
|
||||
_peer_id = data[4:8] # Configure Command
|
||||
elif _command == RPTO: # options
|
||||
_peer_id = data[4:8]
|
||||
elif _command == RPTP: # RPTPing -- peer is pinging us
|
||||
_peer_id = data[7:11]
|
||||
else:
|
||||
return
|
||||
|
||||
if _peer_id in self.peerTrack:
|
||||
_dport = self.peerTrack[_peer_id]['dport']
|
||||
self.peerTrack[_peer_id]['sport'] = port
|
||||
self.peerTrack[_peer_id]['shost'] = host
|
||||
self.transport.write(data, ('127.0.0.1',_dport))
|
||||
self.peerTrack[_peer_id]['timer'].reset()
|
||||
if self.debug:
|
||||
print(data)
|
||||
print(_dport)
|
||||
return
|
||||
else:
|
||||
|
||||
if int_id(_peer_id) in self.blackList:
|
||||
return
|
||||
#for _dport in self.connTrack:
|
||||
while True:
|
||||
_dport = random.randint(1,(self.numPorts - 1))
|
||||
_dport = _dport + self.destPortStart
|
||||
if not self.connTrack[_dport]:
|
||||
break
|
||||
self.connTrack[_dport] = _peer_id
|
||||
self.peerTrack[_peer_id] = {}
|
||||
self.peerTrack[_peer_id]['dport'] = _dport
|
||||
self.peerTrack[_peer_id]['sport'] = port
|
||||
self.peerTrack[_peer_id]['shost'] = host
|
||||
self.peerTrack[_peer_id]['timer'] = ResettableTimer(self.timeout,self.reaper,[_peer_id])
|
||||
self.peerTrack[_peer_id]['timer'].start()
|
||||
self.transport.write(data, (self.master,_dport))
|
||||
if self.debug:
|
||||
print(data)
|
||||
return
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
#*** CONFIG HERE ***
|
||||
|
||||
Master = "127.0.0.1"
|
||||
ListenPort = 62031
|
||||
DestportStart = 54100
|
||||
DestPortEnd = 54102
|
||||
Timeout = 30
|
||||
Stats = True
|
||||
Debug = True
|
||||
BlackList = [1234567]
|
||||
|
||||
#*******************
|
||||
|
||||
|
||||
CONNTRACK = {}
|
||||
|
||||
for port in range(DestportStart,DestPortEnd+1,1):
|
||||
CONNTRACK[port] = False
|
||||
|
||||
|
||||
reactor.listenUDP(ListenPort,Proxy(Master,ListenPort,CONNTRACK,BlackList,Timeout,Debug,DestportStart,DestPortEnd))
|
||||
|
||||
def loopingErrHandle(failure):
|
||||
print('(GLOBAL) STOPPING REACTOR TO AVOID MEMORY LEAK: Unhandled error innowtimed loop.\n {}'.format(failure))
|
||||
reactor.stop()
|
||||
|
||||
def stats():
|
||||
count = 0
|
||||
nowtime = time()
|
||||
for port in CONNTRACK:
|
||||
if CONNTRACK[port]:
|
||||
count = count+1
|
||||
|
||||
totalPorts = DestPortEnd - DestportStart
|
||||
freePorts = totalPorts - count
|
||||
|
||||
print("{} ports out of {} in use ({} free)".format(count,totalPorts,freePorts))
|
||||
|
||||
|
||||
|
||||
if Stats == True:
|
||||
stats_task = task.LoopingCall(stats)
|
||||
statsa = stats_task.start(30)
|
||||
statsa.addErrback(loopingErrHandle)
|
||||
|
||||
reactor.run()
|
||||
|
@ -1,5 +1,5 @@
|
||||
#! /bin/bash
|
||||
|
||||
# Install the required support programs
|
||||
apt-get install python3 python3-pip -y
|
||||
sudo apt-get install python3 python3-pip -y
|
||||
pip3 install -r requirements.txt
|
||||
|
283
ipsc_to_mmdvm.py
Normal file
283
ipsc_to_mmdvm.py
Normal file
@ -0,0 +1,283 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
###############################################################################
|
||||
# Copyright (C) 2016-2019 Cortney T. Buffington, N0MJS <n0mjs@me.com>
|
||||
# GPS/Data - Copyright (C) 2021 Eric Craw, KF7EEL <kf7eel@qsl.net>
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software Foundation,
|
||||
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
###############################################################################
|
||||
|
||||
# Python modules we need
|
||||
import sys
|
||||
from bitarray import bitarray
|
||||
from time import time
|
||||
from importlib import import_module
|
||||
|
||||
# Twisted is pretty important, so I keep it separate
|
||||
from twisted.internet.protocol import Factory, Protocol
|
||||
from twisted.protocols.basic import NetstringReceiver
|
||||
from twisted.internet import reactor, task
|
||||
|
||||
# Things we import from the main hblink module
|
||||
from hblink import HBSYSTEM, OPENBRIDGE, systems, hblink_handler, reportFactory, REPORT_OPCODES, mk_aliases
|
||||
from dmr_utils3.utils import bytes_3, int_id, get_alias
|
||||
from dmr_utils3 import decode, bptc, const
|
||||
import config
|
||||
import log
|
||||
from const import *
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
# Stuff for socket reporting
|
||||
import pickle
|
||||
# REMOVE LATER from datetime import datetime
|
||||
# The module needs logging, but handlers, etc. are controlled by the parent
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
import ast, os, time
|
||||
|
||||
|
||||
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
|
||||
__author__ = 'Eric Craw, KF7EEL'
|
||||
__copyright__ = 'Eric Craw, kf7eel@qsl.net'
|
||||
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
|
||||
__license__ = 'GNU GPLv3'
|
||||
__maintainer__ = 'Eric Craw, kf7eel@qsl.net'
|
||||
__email__ = 'kf7eel@qsl.net'
|
||||
|
||||
def build_unit(CONFIG):
|
||||
UNIT = []
|
||||
for i in CONFIG['SYSTEMS'].items():
|
||||
if i[1]['ENABLED'] == True and i[1]['MODE'] != 'XLXPEER': # and i[0] not in exclude:
|
||||
UNIT.append(i[0])
|
||||
return UNIT
|
||||
# Functions
|
||||
def data_que_check():
|
||||
l=task.LoopingCall(data_que_send)
|
||||
l.start(1)
|
||||
def data_que_send():
|
||||
#logger.info('Check SMS que')
|
||||
try:
|
||||
#logger.info(UNIT_MAP)
|
||||
for packet_file in os.listdir('/tmp/.hblink_data_que_ipsc/'):
|
||||
logger.info('Sending SMS')
|
||||
data_file = ast.literal_eval(os.popen('cat /tmp/.hblink_data_que_ipsc/' + str(packet_file)).read())
|
||||
|
||||
for i in data_file:
|
||||
#print(bytes.fromhex(str(i)))
|
||||
for d in UNIT:
|
||||
systems[d].send_system(bytes.fromhex(i))
|
||||
os.system('rm /tmp/.hblink_data_que_ipsc/' + packet_file)
|
||||
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.info(e)
|
||||
|
||||
def mmdvm_encapsulate(dst_id, src_id, peer_id, _seq, _slot, _call_type, _dtype_vseq, _stream_id, _dmr_data):
|
||||
signature = 'DMRD'
|
||||
# needs to be in bytes
|
||||
frame_type = 0x10 #bytes_2(int(10))
|
||||
#print((frame_type))
|
||||
dest_id = bytes_3(int(dst_id, 16))
|
||||
# print((dest_id))
|
||||
|
||||
#print(ahex(dest_id))
|
||||
source_id = bytes_3(int(src_id, 16))
|
||||
via_id = bytes_4(int(peer_id, 16))
|
||||
# print((source_id))
|
||||
#print(ahex(via_id))
|
||||
seq = int(_seq).to_bytes(1, 'big')
|
||||
#print(ahex(seq))
|
||||
# Binary, 0 for 1, 1 for 2
|
||||
slot = bitarray(str(_slot))
|
||||
#print(slot)
|
||||
# binary, 0 for group, 1 for unit, bin(1)
|
||||
# print(_call_type)
|
||||
call_type = bitarray(str(_call_type))
|
||||
#print(call_type)
|
||||
#0x00 for voice, 0x01 for voice sync, 0x10 for data
|
||||
#frame_type = int(16).to_bytes(1, 'big')
|
||||
frame_type = bitarray('10')
|
||||
#print(frame_type)
|
||||
# Observed to be always 7, int. Will be 6 for header
|
||||
#dtype_vseq = hex(int(_dtype_vseq)).encode()
|
||||
if _dtype_vseq == 6:
|
||||
dtype_vseq = bitarray('0110')
|
||||
if _dtype_vseq == 7:
|
||||
dtype_vseq = bitarray('0111')
|
||||
if _dtype_vseq == 3:
|
||||
dtype_vseq = bitarray('0011')
|
||||
# 9 digit integer in hex
|
||||
stream_id = bytes_4(_stream_id)
|
||||
#print(ahex(stream_id))
|
||||
|
||||
middle_guts = slot + call_type + frame_type + dtype_vseq
|
||||
#print(middle_guts)
|
||||
dmr_data = str(_dmr_data)[2:-1] #str(re.sub("b'|'", '', str(_dmr_data)))
|
||||
complete_packet = signature.encode() + seq + dest_id + source_id + via_id + middle_guts.tobytes() + stream_id + bytes.fromhex((dmr_data)) + bitarray('0000000000101111').tobytes()#bytes.fromhex(dmr_data)
|
||||
|
||||
return complete_packet
|
||||
|
||||
def dmr_encode(packet_list, _slot):
|
||||
send_seq = []
|
||||
for i in packet_list:
|
||||
stitched_pkt = bptc.interleave_19696(bptc.encode_19696(i))
|
||||
l_slot = bitarray('0111011100')
|
||||
#MS
|
||||
#sync_data = bitarray('110101011101011111110111011111111101011101010111')
|
||||
if _slot == 0:
|
||||
# TS1 - F7FDD5DDFD55
|
||||
sync_data = bitarray('111101111111110111010101110111011111110101010101')
|
||||
if _slot == 1:
|
||||
#TS2 - D7557F5FF7F5
|
||||
sync_data = bitarray('110101110101010101111111010111111111011111110101')
|
||||
# TS1
|
||||
#sync_data = bitarray('111101111111110111010101110111011111110101010101')
|
||||
#TS2
|
||||
#sync_data = bitarray('110101110101010101111111010111111111011111110101')
|
||||
r_slot = bitarray('1101110001')
|
||||
# Data sync? 110101011101011111110111011111111101011101010111 - D5D7F77FD757
|
||||
new_pkt = ahex(stitched_pkt[:98] + l_slot + sync_data + r_slot + stitched_pkt[98:])
|
||||
send_seq.append(new_pkt)
|
||||
return send_seq
|
||||
|
||||
# Module gobal varaibles
|
||||
|
||||
def config_reports(_config, _factory):
|
||||
if True: #_config['REPORTS']['REPORT']:
|
||||
def reporting_loop(logger, _server):
|
||||
logger.debug('(REPORT) Periodic reporting loop started')
|
||||
_server.send_config()
|
||||
_server.send_bridge()
|
||||
|
||||
logger.info('(REPORT) HBlink TCP reporting server configured')
|
||||
|
||||
report_server = _factory(_config)
|
||||
report_server.clients = []
|
||||
reactor.listenTCP(_config['REPORTS']['REPORT_PORT'], report_server)
|
||||
|
||||
reporting = task.LoopingCall(reporting_loop, logger, report_server)
|
||||
reporting.start(_config['REPORTS']['REPORT_INTERVAL'])
|
||||
|
||||
return report_server
|
||||
|
||||
class bridgeReportFactory(reportFactory):
|
||||
|
||||
def send_bridge(self):
|
||||
serialized = pickle.dumps(BRIDGES, protocol=2) #.decode("utf-8", errors='ignore')
|
||||
self.send_clients(REPORT_OPCODES['BRIDGE_SND']+serialized)
|
||||
|
||||
def send_bridgeEvent(self, _data):
|
||||
if isinstance(_data, str):
|
||||
_data = _data.decode('utf-8', error='ignore')
|
||||
self.send_clients(REPORT_OPCODES['BRDG_EVENT']+_data)
|
||||
|
||||
class OBP(OPENBRIDGE):
|
||||
|
||||
def __init__(self, _name, _config, _report):
|
||||
OPENBRIDGE.__init__(self, _name, _config, _report)
|
||||
|
||||
|
||||
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
|
||||
pass
|
||||
|
||||
|
||||
class HBP(HBSYSTEM):
|
||||
|
||||
def __init__(self, _name, _config, _report):
|
||||
HBSYSTEM.__init__(self, _name, _config, _report)
|
||||
|
||||
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
|
||||
pass
|
||||
|
||||
|
||||
|
||||
#************************************************
|
||||
# MAIN PROGRAM LOOP STARTS HERE
|
||||
#************************************************
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import os
|
||||
import signal
|
||||
|
||||
# Change the current directory to the location of the application
|
||||
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
|
||||
|
||||
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually hblink.cfg)')
|
||||
parser.add_argument('-l', '--logging', action='store', dest='LOG_LEVEL', help='Override config file logging level.')
|
||||
cli_args = parser.parse_args()
|
||||
|
||||
# Ensure we have a path for the config file, if one wasn't specified, then use the default (top of file)
|
||||
if not cli_args.CONFIG_FILE:
|
||||
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/ipsc_to_mmdvm.cfg'
|
||||
|
||||
# Call the external routine to build the configuration dictionary
|
||||
CONFIG = config.build_config(cli_args.CONFIG_FILE)
|
||||
|
||||
# Start the system logger
|
||||
if cli_args.LOG_LEVEL:
|
||||
CONFIG['LOGGER']['LOG_LEVEL'] = cli_args.LOG_LEVEL
|
||||
logger = log.config_logging(CONFIG['LOGGER'])
|
||||
logger.info('\n\nCopyright (c) 2013, 2014, 2015, 2016, 2018\n\tThe Regents of the K0USY Group. All rights reserved.\n')
|
||||
logger.debug('(GLOBAL) Logging system started, anything from here on gets logged')
|
||||
|
||||
# Set up the signal handler
|
||||
def sig_handler(_signal, _frame):
|
||||
logger.info('(GLOBAL) SHUTDOWN: CONFBRIDGE IS TERMINATING WITH SIGNAL %s', str(_signal))
|
||||
hblink_handler(_signal, _frame)
|
||||
logger.info('(GLOBAL) SHUTDOWN: ALL SYSTEM HANDLERS EXECUTED - STOPPING REACTOR')
|
||||
reactor.stop()
|
||||
|
||||
# Set signal handers so that we can gracefully exit if need be
|
||||
for sig in [signal.SIGINT, signal.SIGTERM]:
|
||||
signal.signal(sig, sig_handler)
|
||||
|
||||
# Create the name-number mapping dictionaries
|
||||
peer_ids, subscriber_ids, talkgroup_ids = mk_aliases(CONFIG)
|
||||
|
||||
# INITIALIZE THE REPORTING LOOP
|
||||
if CONFIG['REPORTS']['REPORT']:
|
||||
report_server = config_reports(CONFIG, bridgeReportFactory)
|
||||
else:
|
||||
report_server = None
|
||||
logger.info('(REPORT) TCP Socket reporting not configured')
|
||||
|
||||
# HBlink instance creation
|
||||
logger.info('(GLOBAL) HBlink \'bridge.py\' -- SYSTEM STARTING...')
|
||||
for system in CONFIG['SYSTEMS']:
|
||||
if CONFIG['SYSTEMS'][system]['ENABLED']:
|
||||
if CONFIG['SYSTEMS'][system]['MODE'] == 'OPENBRIDGE':
|
||||
systems[system] = OBP(system, CONFIG, report_server)
|
||||
else:
|
||||
systems[system] = HBP(system, CONFIG, report_server)
|
||||
reactor.listenUDP(CONFIG['SYSTEMS'][system]['PORT'], systems[system], interface=CONFIG['SYSTEMS'][system]['IP'])
|
||||
logger.debug('(GLOBAL) %s instance created: %s, %s', CONFIG['SYSTEMS'][system]['MODE'], system, systems[system])
|
||||
|
||||
def loopingErrHandle(failure):
|
||||
logger.error('(GLOBAL) STOPPING REACTOR TO AVOID MEMORY LEAK: Unhandled error in timed loop.\n %s', failure)
|
||||
reactor.stop()
|
||||
Path('/tmp/.hblink_data_que_ipsc/').mkdir(parents=True, exist_ok=True)
|
||||
UNIT = build_unit(CONFIG)
|
||||
data_que_check()
|
||||
|
||||
|
||||
reactor.run()
|
@ -8,3 +8,6 @@ pynmea2
|
||||
maidenhead
|
||||
flask
|
||||
folium
|
||||
libscrc
|
||||
requests
|
||||
|
||||
|
378
retired/gps_data-SAMPLE.cfg
Normal file
378
retired/gps_data-SAMPLE.cfg
Normal file
@ -0,0 +1,378 @@
|
||||
# PROGRAM-WIDE PARAMETERS GO HERE
|
||||
# PATH - working path for files, leave it alone unless you NEED to change it
|
||||
# PING_TIME - the interval that peers will ping the master, and re-try registraion
|
||||
# - how often the Master maintenance loop runs
|
||||
# MAX_MISSED - how many pings are missed before we give up and re-register
|
||||
# - number of times the master maintenance loop runs before de-registering a peer
|
||||
#
|
||||
# ACLs:
|
||||
#
|
||||
# Access Control Lists are a very powerful tool for administering your system.
|
||||
# But they consume packet processing time. Disable them if you are not using them.
|
||||
# But be aware that, as of now, the configuration stanzas still need the ACL
|
||||
# sections configured even if you're not using them.
|
||||
#
|
||||
# REGISTRATION ACLS ARE ALWAYS USED, ONLY SUBSCRIBER AND TGID MAY BE DISABLED!!!
|
||||
#
|
||||
# The 'action' May be PERMIT|DENY
|
||||
# Each entry may be a single radio id, or a hypenated range (e.g. 1-2999)
|
||||
# Format:
|
||||
# ACL = 'action:id|start-end|,id|start-end,....'
|
||||
# --for example--
|
||||
# SUB_ACL: DENY:1,1000-2000,4500-60000,17
|
||||
#
|
||||
# ACL Types:
|
||||
# REG_ACL: peer radio IDs for registration (only used on HBP master systems)
|
||||
# SUB_ACL: subscriber IDs for end-users
|
||||
# TGID_TS1_ACL: destination talkgroup IDs on Timeslot 1
|
||||
# TGID_TS2_ACL: destination talkgroup IDs on Timeslot 2
|
||||
#
|
||||
# ACLs may be repeated for individual systems if needed for granularity
|
||||
# Global ACLs will be processed BEFORE the system level ACLs
|
||||
# Packets will be matched against all ACLs, GLOBAL first. If a packet 'passes'
|
||||
# All elements, processing continues. Packets are discarded at the first
|
||||
# negative match, or 'reject' from an ACL element.
|
||||
#
|
||||
# If you do not wish to use ACLs, set them to 'PERMIT:ALL'
|
||||
# TGID_TS1_ACL in the global stanza is used for OPENBRIDGE systems, since all
|
||||
# traffic is passed as TS 1 between OpenBridges
|
||||
[GLOBAL]
|
||||
PATH: ./
|
||||
PING_TIME: 5
|
||||
MAX_MISSED: 3
|
||||
USE_ACL: True
|
||||
REG_ACL: PERMIT:ALL
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
||||
|
||||
# NOT YET WORKING: NETWORK REPORTING CONFIGURATION
|
||||
# Enabling "REPORT" will configure a socket-based reporting
|
||||
# system that will send the configuration and other items
|
||||
# to a another process (local or remote) that may process
|
||||
# the information for some useful purpose, like a web dashboard.
|
||||
#
|
||||
# REPORT - True to enable, False to disable
|
||||
# REPORT_INTERVAL - Seconds between reports
|
||||
# REPORT_PORT - TCP port to listen on if "REPORT_NETWORKS" = NETWORK
|
||||
# REPORT_CLIENTS - comma separated list of IPs you will allow clients
|
||||
# to connect on. Entering a * will allow all.
|
||||
#
|
||||
# ****FOR NOW MUST BE TRUE - USE THE LOOPBACK IF YOU DON'T USE THIS!!!****
|
||||
[REPORTS]
|
||||
REPORT: True
|
||||
REPORT_INTERVAL: 60
|
||||
REPORT_PORT: 4323
|
||||
REPORT_CLIENTS: 127.0.0.1
|
||||
|
||||
|
||||
# SYSTEM LOGGER CONFIGURAITON
|
||||
# This allows the logger to be configured without chaning the individual
|
||||
# python logger stuff. LOG_FILE should be a complete path/filename for *your*
|
||||
# system -- use /dev/null for non-file handlers.
|
||||
# LOG_HANDLERS may be any of the following, please, no spaces in the
|
||||
# list if you use several:
|
||||
# null
|
||||
# console
|
||||
# console-timed
|
||||
# file
|
||||
# file-timed
|
||||
# syslog
|
||||
# LOG_LEVEL may be any of the standard syslog logging levels, though
|
||||
# as of now, DEBUG, INFO, WARNING and CRITICAL are the only ones
|
||||
# used.
|
||||
#
|
||||
[LOGGER]
|
||||
LOG_FILE: /tmp/gps_data.log
|
||||
LOG_HANDLERS: console-timed
|
||||
LOG_LEVEL: DEBUG
|
||||
LOG_NAME: HBlink3 GPS/Data
|
||||
|
||||
# DOWNLOAD AND IMPORT SUBSCRIBER, PEER and TGID ALIASES
|
||||
# Ok, not the TGID, there's no master list I know of to download
|
||||
# This is intended as a facility for other applcations built on top of
|
||||
# HBlink to use, and will NOT be used in HBlink directly.
|
||||
# STALE_DAYS is the number of days since the last download before we
|
||||
# download again. Don't be an ass and change this to less than a few days.
|
||||
[ALIASES]
|
||||
TRY_DOWNLOAD: True
|
||||
PATH: ./
|
||||
PEER_FILE: peer_ids.json
|
||||
SUBSCRIBER_FILE: subscriber_ids.json
|
||||
TGID_FILE: talkgroup_ids.json
|
||||
PEER_URL: https://www.radioid.net/static/rptrs.json
|
||||
SUBSCRIBER_URL: https://www.radioid.net/static/users.json
|
||||
STALE_DAYS: 1
|
||||
|
||||
#####################################################################
|
||||
# GPS/Data Application - by KF7EEL
|
||||
# Configure the settings for the DMR GPS to APRS position application here.
|
||||
#
|
||||
# DATA_DMR_ID - This is the DMR ID that users send DMR GPS data.
|
||||
# CALL_TYPE - group, unit, or both. Group if you want users to send data to a talkgroup,
|
||||
# unit if you want users to send data as a private call, or both if you want both options.
|
||||
# USER_APRS_SSID - Default APRS SSID assigned to user APRS positions.
|
||||
# USER_APRS_COMMENT - Default Comment attached to user APRS positions.
|
||||
# APRS_LOGIN_CALL, PASSCODE, SERVER, and PORT - Login settings for APRS-IS.
|
||||
[GPS_DATA]
|
||||
DATA_DMR_ID: 9099
|
||||
CALL_TYPE: unit
|
||||
USER_APRS_SSID: 15
|
||||
USER_APRS_COMMENT: HBLink3 D-APRS -
|
||||
|
||||
# Setting APRS_LOGIN_CALL to N0CALL will cause the gateway to not upload packets to APRS server.
|
||||
APRS_LOGIN_CALL: N0CALL
|
||||
APRS_LOGIN_PASSCODE: 12345
|
||||
APRS_SERVER: rotate.aprs2.net
|
||||
APRS_PORT: 14580
|
||||
|
||||
# The APRS filter below is used for the message received script. See http://www.aprs-is.net/javAPRSFilter.aspx for details
|
||||
# about APRS filters.
|
||||
APRS_FILTER: r/47/-120/500 t/m
|
||||
|
||||
# The following settings are only applicable if you are using the gps_data_beacon_igate script.
|
||||
# They do not affect the operation gps_data itself.
|
||||
# Time in minutes.
|
||||
IGATE_BEACON_TIME = 45
|
||||
IGATE_BEACON_COMMENT = HBLink3 D-APRS Gateway
|
||||
IGATE_BEACON_ICON = /I
|
||||
IGATE_LATITUDE = 0000.00N
|
||||
IGATE_LONGITUDE = 00000.00W
|
||||
|
||||
# The following settings are for the static positions only, for hotspots or repeaters connected to MASTER stanzas.
|
||||
# Implementation by IU7IGU
|
||||
# REPORT_INTERVAL in Minute (ALLOW only > 3 Minutes)
|
||||
# MESSAGE: This message will print on APRS description together RX and TX Frequency
|
||||
APRS_STATIC_REPORT_INTERVAL: 15
|
||||
MESSAGE:Connected to HBLink
|
||||
|
||||
# The email gateway settingns below are OPTIONAL. They are NOT REQUIRED if you don't want
|
||||
http://www.aprs-is.net/javAPRSFilter.aspx# to enable the email gateway. Leave as is to disable.
|
||||
EMAIL_SENDER: test@example.org
|
||||
EMAIL_PASSWORD: letmein
|
||||
SMTP_SERVER: smtp.gmail.com
|
||||
SMTP_PORT: 465
|
||||
|
||||
# The options below are required for operation of the dashboard and will cause errors in gps_data.py
|
||||
# if configured wrong. Leave them as default unless you know what you are doing.
|
||||
# If you do change, you must use absolute paths.
|
||||
LOCATION_FILE: /tmp/gps_data_user_loc.txt
|
||||
BULLETIN_BOARD_FILE: /tmp/gps_data_user_bb.txt
|
||||
MAILBOX_FILE: /tmp/gps_data_user_mailbox.txt
|
||||
EMERGENCY_SOS_FILE: /tmp/gps_data_user_sos.txt
|
||||
|
||||
# User settings file, MUST configure using absolute path.
|
||||
USER_SETTINGS_FILE: /path/to/user_settings.txt
|
||||
|
||||
# The following options are used for the dashboard. The dashboard is optional.
|
||||
# Title of the Dashboard
|
||||
DASHBOARD_TITLE: HBLink3 D-APRS Dashboard
|
||||
|
||||
# Logo used on dashboard page
|
||||
LOGO: https://raw.githubusercontent.com/kf7eel/hblink3/gps/HBlink.png
|
||||
|
||||
# Port to run server
|
||||
DASH_PORT: 8092
|
||||
|
||||
# IP to run server on
|
||||
DASH_HOST: 127.0.0.1
|
||||
|
||||
#Description of dashboard to show on main page
|
||||
DESCRIPTION: Welcome to the dashboard.
|
||||
|
||||
# Gateway contact info displayed on about page.
|
||||
CONTACT_NAME: your name
|
||||
CONTACT_CALL: N0CALL
|
||||
CONTACT_EMAIL: email@example.org
|
||||
CONTACT_WEBSITE: https://hbl.ink
|
||||
|
||||
# Time format for display
|
||||
TIME_FORMAT: %%H:%%M:%%S - %%m/%%d/%%y
|
||||
|
||||
# Center dashboard map over these coordinates
|
||||
MAP_CENTER_LAT: 47.00
|
||||
MAP_CENTER_LON: -120.00
|
||||
ZOOM_LEVEL: 7
|
||||
|
||||
# List and preview of some map themes at http://leaflet-extras.github.io/leaflet-providers/preview/
|
||||
# The following are options for map themes and just work, you should use one of these: “OpenStreetMap”, “Stamen” (Terrain, Toner, and Watercolor),
|
||||
MAP_THEME: Stamen Toner
|
||||
|
||||
# RSS feed link, shows in the link section of each RSS item.
|
||||
RSS_LINK: http://localhost:8092
|
||||
|
||||
#####################################################################
|
||||
# OPENBRIDGE INSTANCES - DUPLICATE SECTION FOR MULTIPLE CONNECTIONS
|
||||
# OpenBridge is a protocol originall created by DMR+ for connection between an
|
||||
# IPSC2 server and Brandmeister. It has been implemented here at the suggestion
|
||||
# of the Brandmeister team as a way to legitimately connect HBlink to the
|
||||
# Brandemiester network.
|
||||
# It is recommended to name the system the ID of the Brandmeister server that
|
||||
# it connects to, but is not necessary. TARGET_IP and TARGET_PORT are of the
|
||||
# Brandmeister or IPSC2 server you are connecting to. PASSPHRASE is the password
|
||||
# that must be agreed upon between you and the operator of the server you are
|
||||
# connecting to. NETWORK_ID is a number in the format of a DMR Radio ID that
|
||||
# will be sent to the other server to identify this connection.
|
||||
# other parameters follow the other system types.
|
||||
#
|
||||
# ACLs:
|
||||
# OpenBridge does not 'register', so registration ACL is meaningless.
|
||||
# Proper OpenBridge passes all traffic on TS1.
|
||||
# HBlink can extend OPB to use both slots for unit calls only.
|
||||
# Setting "BOTH_SLOTS" True ONLY affects unit traffic!
|
||||
# Otherwise ACLs work as described in the global stanza
|
||||
|
||||
[OBP-1]
|
||||
MODE: OPENBRIDGE
|
||||
ENABLED: True
|
||||
IP:
|
||||
PORT: 62035
|
||||
NETWORK_ID: 3129100
|
||||
PASSPHRASE: password
|
||||
TARGET_IP: 1.2.3.4
|
||||
TARGET_PORT: 62035
|
||||
BOTH_SLOTS: True
|
||||
USE_ACL: True
|
||||
SUB_ACL: DENY:1
|
||||
TGID_ACL: PERMIT:ALL
|
||||
|
||||
# MASTER INSTANCES - DUPLICATE SECTION FOR MULTIPLE MASTERS
|
||||
# HomeBrew Protocol Master instances go here.
|
||||
# IP may be left blank if there's one interface on your system.
|
||||
# Port should be the port you want this master to listen on. It must be unique
|
||||
# and unused by anything else.
|
||||
# Repeat - if True, the master repeats traffic to peers, False, it does nothing.
|
||||
#
|
||||
# MAX_PEERS -- maximun number of peers that may be connect to this master
|
||||
# at any given time. This is very handy if you're allowing hotspots to
|
||||
# connect, or using a limited computer like a Raspberry Pi.
|
||||
#
|
||||
# ACLs:
|
||||
# See comments in the GLOBAL stanza
|
||||
[MASTER-1]
|
||||
MODE: MASTER
|
||||
ENABLED: False
|
||||
STATIC_APRS_POSITION_ENABLED: False
|
||||
REPEAT: True
|
||||
MAX_PEERS: 10
|
||||
EXPORT_AMBE: False
|
||||
IP:
|
||||
PORT: 54000
|
||||
PASSPHRASE: password
|
||||
GROUP_HANGTIME: 5
|
||||
USE_ACL: True
|
||||
REG_ACL: DENY:1
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
||||
# PEER INSTANCES - DUPLICATE SECTION FOR MULTIPLE PEERS
|
||||
# There are a LOT of errors in the HB Protocol specifications on this one!
|
||||
# MOST of these items are just strings and will be properly dealt with by the program
|
||||
# The TX & RX Frequencies are 9-digit numbers, and are the frequency in Hz.
|
||||
# Latitude is an 8-digit unsigned floating point number.
|
||||
# Longitude is a 9-digit signed floating point number.
|
||||
# Height is in meters
|
||||
# Setting Loose to True relaxes the validation on packets received from the master.
|
||||
# This will allow HBlink to connect to a non-compliant system such as XLXD, DMR+ etc.
|
||||
#
|
||||
# ACLs:
|
||||
# See comments in the GLOBAL stanza
|
||||
|
||||
[REPEATER-1]
|
||||
MODE: PEER
|
||||
ENABLED: False
|
||||
LOOSE: False
|
||||
EXPORT_AMBE: False
|
||||
IP:
|
||||
PORT: 54001
|
||||
MASTER_IP: 172.16.1.1
|
||||
MASTER_PORT: 54000
|
||||
PASSPHRASE: homebrew
|
||||
CALLSIGN: W1ABC
|
||||
RADIO_ID: 312000
|
||||
RX_FREQ: 449000000
|
||||
TX_FREQ: 444000000
|
||||
TX_POWER: 25
|
||||
COLORCODE: 1
|
||||
SLOTS: 1
|
||||
LATITUDE: 38.0000
|
||||
LONGITUDE: -095.0000
|
||||
HEIGHT: 75
|
||||
LOCATION: Anywhere, USA
|
||||
DESCRIPTION: This is a cool repeater
|
||||
URL: www.w1abc.org
|
||||
SOFTWARE_ID: 20170620
|
||||
PACKAGE_ID: MMDVM_HBlink
|
||||
GROUP_HANGTIME: 5
|
||||
OPTIONS:
|
||||
USE_ACL: True
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
||||
[ECHO]
|
||||
MODE: PEER
|
||||
ENABLED: True
|
||||
LOOSE: False
|
||||
EXPORT_AMBE: False
|
||||
IP:
|
||||
PORT: 54073
|
||||
MASTER_IP: localhost
|
||||
MASTER_PORT: 54072
|
||||
passphrase: passw0rd
|
||||
CALLSIGN: ECHO
|
||||
RADIO_ID: 9999
|
||||
RX_FREQ: 000000000
|
||||
TX_FREQ: 000000000
|
||||
TX_POWER: 0
|
||||
COLORCODE: 1
|
||||
SLOTS: 1
|
||||
LATITUDE: 00.0000
|
||||
LONGITUDE: 000.0000
|
||||
HEIGHT: 0
|
||||
LOCATION: This Server
|
||||
DESCRIPTION: Echo Server
|
||||
URL: www.github.com/kf7eel/hblink3
|
||||
SOFTWARE_ID: 20170620
|
||||
PACKAGE_ID: MMDVM_HBlink
|
||||
GROUP_HANGTIME: 5
|
||||
OPTIONS:
|
||||
USE_ACL: True
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
||||
[XLX-1]
|
||||
MODE: XLXPEER
|
||||
ENABLED: False
|
||||
LOOSE: True
|
||||
EXPORT_AMBE: False
|
||||
IP:
|
||||
PORT: 54002
|
||||
MASTER_IP: 172.16.1.1
|
||||
MASTER_PORT: 62030
|
||||
PASSPHRASE: passw0rd
|
||||
CALLSIGN: W1ABC
|
||||
RADIO_ID: 312000
|
||||
RX_FREQ: 449000000
|
||||
TX_FREQ: 444000000
|
||||
TX_POWER: 25
|
||||
COLORCODE: 1
|
||||
SLOTS: 1
|
||||
LATITUDE: 38.0000
|
||||
LONGITUDE: -095.0000
|
||||
HEIGHT: 75
|
||||
LOCATION: Anywhere, USA
|
||||
DESCRIPTION: This is a cool repeater
|
||||
URL: www.w1abc.org
|
||||
SOFTWARE_ID: 20170620
|
||||
PACKAGE_ID: MMDVM_HBlink
|
||||
GROUP_HANGTIME: 5
|
||||
XLXMODULE: 4004
|
||||
USE_ACL: True
|
||||
SUB_ACL: DENY:1
|
||||
TGID_TS1_ACL: PERMIT:ALL
|
||||
TGID_TS2_ACL: PERMIT:ALL
|
||||
|
820
retired/gps_data.py
Normal file
820
retired/gps_data.py
Normal file
@ -0,0 +1,820 @@
|
||||
#!/usr/bin/env python3
|
||||
#
|
||||
###############################################################################
|
||||
# HBLink - Copyright (C) 2020 Cortney T. Buffington, N0MJS <n0mjs@me.com>
|
||||
# GPS/Data - Copyright (C) 2020 Eric Craw, KF7EEL <kf7eel@qsl.net>
|
||||
# Annotated modifications Copyright (C) 2021 Xavier FRS2013
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software Foundation,
|
||||
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
###############################################################################
|
||||
|
||||
'''
|
||||
This is a GPS and Data application. It decodes and reassambles DMR GPS packets and
|
||||
uploads them th APRS-IS.
|
||||
'''
|
||||
|
||||
# Python modules we need
|
||||
import sys
|
||||
from bitarray import bitarray
|
||||
from time import time
|
||||
from importlib import import_module
|
||||
from types import ModuleType
|
||||
|
||||
# Twisted is pretty important, so I keep it separate
|
||||
from twisted.internet.protocol import Factory, Protocol
|
||||
from twisted.protocols.basic import NetstringReceiver
|
||||
from twisted.internet import reactor, task
|
||||
|
||||
# Things we import from the main hblink module
|
||||
from hblink import HBSYSTEM, OPENBRIDGE, systems, hblink_handler, reportFactory, REPORT_OPCODES, config_reports, mk_aliases, acl_check
|
||||
from dmr_utils3.utils import bytes_3, int_id, get_alias
|
||||
from dmr_utils3 import decode, bptc, const
|
||||
import config
|
||||
import log
|
||||
import const
|
||||
|
||||
# The module needs logging logging, but handlers, etc. are controlled by the parent
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
import traceback
|
||||
|
||||
# Other modules we need for data and GPS
|
||||
from bitarray import bitarray
|
||||
from binascii import b2a_hex as ahex
|
||||
import re
|
||||
##from binascii import a2b_hex as bhex
|
||||
import aprslib
|
||||
import datetime
|
||||
from bitarray.util import ba2int as ba2num
|
||||
from bitarray.util import ba2hex as ba2hx
|
||||
import codecs
|
||||
import time
|
||||
#Needed for working with NMEA
|
||||
import pynmea2
|
||||
|
||||
# Modules for executing commands/scripts
|
||||
import os
|
||||
from gps_functions import cmd_list
|
||||
|
||||
# Module for maidenhead grids
|
||||
try:
|
||||
import maidenhead as mh
|
||||
except Exception as error_exception:
|
||||
logger.info('Error importing maidenhead module, make sure it is installed.')
|
||||
# Module for sending email
|
||||
try:
|
||||
import smtplib
|
||||
except Exception as error_exception:
|
||||
logger.info('Error importing smtplib module, make sure it is installed.')
|
||||
|
||||
#Modules for APRS settings
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
|
||||
__author__ = 'Cortney T. Buffington, N0MJS; Eric Craw, KF7EEL'
|
||||
__copyright__ = 'Copyright (c) 2020 Cortney T. Buffington'
|
||||
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
|
||||
__license__ = 'GNU GPLv3'
|
||||
__maintainer__ = 'Eric Craw, KF7EEL'
|
||||
__email__ = 'kf7eel@qsl.net'
|
||||
__status__ = 'pre-alpha'
|
||||
|
||||
# Known to work with: AT-D878
|
||||
|
||||
# Must have the following at line 1054 in bridge.py to forward group vcsbk, also there is a typo there:
|
||||
# self.group_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _frame_type, _dtype_vseq, _stream_id, _data)
|
||||
|
||||
##################################################################################################
|
||||
|
||||
# Headers for GPS by model of radio:
|
||||
# AT-D878 - Compressed UDP
|
||||
# MD-380 - Unified Data Transport
|
||||
hdr_type = ''
|
||||
btf = -1
|
||||
ssid = ''
|
||||
|
||||
# From dmr_utils3, modified to decode entire packet. Works for 1/2 rate coded data.
|
||||
def decode_full(_data):
|
||||
binlc = bitarray(endian='big')
|
||||
binlc.extend([_data[136],_data[121],_data[106],_data[91], _data[76], _data[61], _data[46], _data[31]])
|
||||
binlc.extend([_data[152],_data[137],_data[122],_data[107],_data[92], _data[77], _data[62], _data[47], _data[32], _data[17], _data[2] ])
|
||||
binlc.extend([_data[123],_data[108],_data[93], _data[78], _data[63], _data[48], _data[33], _data[18], _data[3], _data[184],_data[169]])
|
||||
binlc.extend([_data[94], _data[79], _data[64], _data[49], _data[34], _data[19], _data[4], _data[185],_data[170],_data[155],_data[140]])
|
||||
binlc.extend([_data[65], _data[50], _data[35], _data[20], _data[5], _data[186],_data[171],_data[156],_data[141],_data[126],_data[111]])
|
||||
binlc.extend([_data[36], _data[21], _data[6], _data[187],_data[172],_data[157],_data[142],_data[127],_data[112],_data[97], _data[82] ])
|
||||
binlc.extend([_data[7], _data[188],_data[173],_data[158],_data[143],_data[128],_data[113],_data[98], _data[83]])
|
||||
#This is the rest of the Full LC data -- the RS1293 FEC that we don't need
|
||||
# This is extremely important for SMS and GPS though.
|
||||
binlc.extend([_data[68],_data[53],_data[174],_data[159],_data[144],_data[129],_data[114],_data[99],_data[84],_data[69],_data[54],_data[39]])
|
||||
binlc.extend([_data[24],_data[145],_data[130],_data[115],_data[100],_data[85],_data[70],_data[55],_data[40],_data[25],_data[10],_data[191]])
|
||||
return binlc
|
||||
|
||||
|
||||
n_packet_assembly = 0
|
||||
|
||||
packet_assembly = ''
|
||||
|
||||
final_packet = ''
|
||||
|
||||
#Convert DMR packet to binary from MMDVM packet and remove Slot Type and EMB Sync stuff to allow for BPTC 196,96 decoding
|
||||
def bptc_decode(_data):
|
||||
binary_packet = bitarray(decode.to_bits(_data[20:]))
|
||||
del binary_packet[98:166]
|
||||
return decode_full(binary_packet)
|
||||
# Placeholder for future header id
|
||||
def header_ID(_data):
|
||||
hex_hdr = str(ahex(bptc_decode(_data)))
|
||||
return hex_hdr[2:6]
|
||||
# Work in progress, used to determine data format
|
||||
## pass
|
||||
|
||||
def aprs_send(packet):
|
||||
if aprs_callsign == 'N0CALL':
|
||||
logger.info('APRS callsighn set to N0CALL, packet not sent.')
|
||||
pass
|
||||
else:
|
||||
AIS = aprslib.IS(aprs_callsign, passwd=aprs_passcode,host=aprs_server, port=aprs_port)
|
||||
AIS.connect()
|
||||
AIS.sendall(packet)
|
||||
AIS.close()
|
||||
logger.info('Packet sent to APRS-IS.')
|
||||
# For future use
|
||||
##def position_timer(aprs_call):
|
||||
## dash_entries = ast.literal_eval(os.popen('cat ' + loc_file).read())
|
||||
## for i in dash_entries:
|
||||
## if aprs_call == i['call']:
|
||||
## if time.time()
|
||||
|
||||
|
||||
def dashboard_loc_write(call, lat, lon, time, comment):
|
||||
dash_entries = ast.literal_eval(os.popen('cat /tmp/gps_data_user_loc.txt').read())
|
||||
dash_entries.insert(0, {'call': call, 'lat': lat, 'lon': lon, 'time':time, 'comment':comment})
|
||||
# Clear old entries
|
||||
list_index = 0
|
||||
call_count = 0
|
||||
new_dash_entries = []
|
||||
for i in dash_entries:
|
||||
if i['call'] == call:
|
||||
if call_count >= 25:
|
||||
pass
|
||||
else:
|
||||
new_dash_entries.append(i)
|
||||
call_count = call_count + 1
|
||||
|
||||
if call != i['call']:
|
||||
new_dash_entries.append(i)
|
||||
pass
|
||||
list_index = list_index + 1
|
||||
with open(loc_file, 'w') as user_loc_file:
|
||||
user_loc_file.write(str(new_dash_entries[:500]))
|
||||
user_loc_file.close()
|
||||
logger.info('User location saved for dashboard')
|
||||
#logger.info(dash_entries)
|
||||
|
||||
def dashboard_bb_write(call, dmr_id, time, bulletin):
|
||||
#try:
|
||||
dash_bb = ast.literal_eval(os.popen('cat ' + bb_file).read())
|
||||
# except:
|
||||
# dash_entries = []
|
||||
dash_bb.insert(0, {'call': call, 'dmr_id': dmr_id, 'time': time, 'bulletin':bulletin})
|
||||
with open(bb_file, 'w') as user_bb_file:
|
||||
user_bb_file.write(str(dash_bb[:20]))
|
||||
user_bb_file.close()
|
||||
logger.info('User bulletin entry saved.')
|
||||
#logger.info(dash_bb)
|
||||
|
||||
def mailbox_write(call, dmr_id, time, message, recipient):
|
||||
#try:
|
||||
mail_file = ast.literal_eval(os.popen('cat ' + the_mailbox_file).read())
|
||||
mail_file.insert(0, {'call': call, 'dmr_id': dmr_id, 'time': time, 'message':message, 'recipient': recipient})
|
||||
with open(the_mailbox_file, 'w') as mailbox_file:
|
||||
mailbox_file.write(str(mail_file[:100]))
|
||||
mailbox_file.close()
|
||||
logger.info('User mail saved.')
|
||||
|
||||
def mailbox_delete(dmr_id):
|
||||
mail_file = ast.literal_eval(os.popen('cat ' + the_mailbox_file).read())
|
||||
call = str(get_alias((dmr_id), subscriber_ids))
|
||||
new_data = []
|
||||
for message in mail_file:
|
||||
if message['recipient'] != call:
|
||||
new_data.append(message)
|
||||
with open(the_mailbox_file, 'w') as mailbox_file:
|
||||
mailbox_file.write(str(new_data[:100]))
|
||||
mailbox_file.close()
|
||||
logger.info('Mailbox updated. Delete occurred.')
|
||||
|
||||
|
||||
def sos_write(dmr_id, time, message):
|
||||
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
|
||||
try:
|
||||
if user_settings[dmr_id][1]['ssid'] == '':
|
||||
sos_call = user_settings[dmr_id][0]['call'] + '-' + user_ssid
|
||||
else:
|
||||
sos_call = user_settings[dmr_id][0]['call'] + '-' + user_settings[dmr_id][1]['ssid']
|
||||
except:
|
||||
sos_call = str(get_alias((dmr_id), subscriber_ids))
|
||||
sos_info = {'call': sos_call, 'dmr_id': dmr_id, 'time': time, 'message':message}
|
||||
with open(emergency_sos_file, 'w') as sos_file:
|
||||
sos_file.write(str(sos_info))
|
||||
sos_file.close()
|
||||
logger.info('Saved SOS.')
|
||||
|
||||
# Send email via SMTP function
|
||||
def send_email(to_email, email_subject, email_message):
|
||||
global smtp_server
|
||||
sender_address = email_sender
|
||||
account_password = email_password
|
||||
smtp_server = smtplib.SMTP_SSL(smtp_server, int(smtp_port))
|
||||
smtp_server.login(sender_address, account_password)
|
||||
message = "From: " + aprs_callsign + " D-APRS Gateway\nTo: " + to_email + "\nContent-type: text/html\nSubject: " + email_subject + "\n\n" + '<strong>' + email_subject + '</strong><p> </p><h3>' + email_message + '</h3><p> </p><p>This message was sent to you from a D-APRS gateway operated by <strong>' + aprs_callsign + '</strong>. Do not reply as this gateway is only one way at this time.</p>'
|
||||
smtp_server.sendmail(sender_address, to_email, message)
|
||||
smtp_server.close()
|
||||
|
||||
# Thanks for this forum post for this - https://stackoverflow.com/questions/2579535/convert-dd-decimal-degrees-to-dms-degrees-minutes-seconds-in-python
|
||||
|
||||
def decdeg2dms(dd):
|
||||
is_positive = dd >= 0
|
||||
dd = abs(dd)
|
||||
minutes,seconds = divmod(dd*3600,60)
|
||||
degrees,minutes = divmod(minutes,60)
|
||||
degrees = degrees if is_positive else -degrees
|
||||
return (degrees,minutes,seconds)
|
||||
|
||||
def user_setting_write(dmr_id, setting, value):
|
||||
## try:
|
||||
# Open file and load as dict for modification
|
||||
with open(user_settings_file, 'r') as f:
|
||||
## if f.read() == '{}':
|
||||
## user_dict = {}
|
||||
user_dict = ast.literal_eval(f.read())
|
||||
logger.info('Current settings: ' + str(user_dict))
|
||||
if dmr_id not in user_dict:
|
||||
user_dict[dmr_id] = [{'call': str(get_alias((dmr_id), subscriber_ids))}, {'ssid': ''}, {'icon': ''}, {'comment': ''}]
|
||||
if setting.upper() == 'ICON':
|
||||
user_dict[dmr_id][2]['icon'] = value
|
||||
if setting.upper() == 'SSID':
|
||||
user_dict[dmr_id][1]['ssid'] = value
|
||||
if setting.upper() == 'COM':
|
||||
user_comment = user_dict[dmr_id][3]['comment'] = value[0:35]
|
||||
if setting.upper() == 'APRS':
|
||||
user_dict[dmr_id] = [{'call': str(get_alias((dmr_id), subscriber_ids))}, {'ssid': ''}, {'icon': ''}, {'comment': ''}]
|
||||
if setting.upper() == 'PIN':
|
||||
try:
|
||||
if user_dict[dmr_id]:
|
||||
user_dict[dmr_id][4]['pin'] = value
|
||||
if not user_dict[dmr_id]:
|
||||
user_dict[dmr_id] = [{'call': str(get_alias((dmr_id), subscriber_ids))}, {'ssid': ''}, {'icon': ''}, {'comment': ''}, {'pin': pin}]
|
||||
except:
|
||||
user_dict[dmr_id].append({'pin': value})
|
||||
f.close()
|
||||
logger.info('Loaded user settings. Preparing to write...')
|
||||
# Write modified dict to file
|
||||
with open(user_settings_file, 'w') as user_dict_file:
|
||||
user_dict_file.write(str(user_dict))
|
||||
user_dict_file.close()
|
||||
logger.info('User setting saved')
|
||||
f.close()
|
||||
packet_assembly = ''
|
||||
|
||||
# Process SMS, do something bases on message
|
||||
|
||||
def process_sms(_rf_src, sms):
|
||||
if sms == 'ID':
|
||||
logger.info(str(get_alias(int_id(_rf_src), subscriber_ids)) + ' - ' + str(int_id(_rf_src)))
|
||||
elif sms == 'TEST':
|
||||
logger.info('It works!')
|
||||
elif '@ICON' in sms:
|
||||
user_setting_write(int_id(_rf_src), re.sub(' .*|@','',sms), re.sub('@ICON| ','',sms))
|
||||
elif '@SSID' in sms:
|
||||
user_setting_write(int_id(_rf_src), re.sub(' .*|@','',sms), re.sub('@SSID| ','',sms))
|
||||
elif '@COM' in sms:
|
||||
user_setting_write(int_id(_rf_src), re.sub(' .*|@','',sms), re.sub('@COM |@COM','',sms))
|
||||
elif '@PIN' in sms:
|
||||
user_setting_write(int_id(_rf_src), re.sub(' .*|@','',sms), int(re.sub('@PIN |@PIN','',sms)))
|
||||
# Write blank entry to cause APRS receive to look for packets for this station.
|
||||
elif '@APRS' in sms:
|
||||
user_setting_write(int_id(_rf_src), 'APRS', '')
|
||||
elif '@BB' in sms:
|
||||
dashboard_bb_write(get_alias(int_id(_rf_src), subscriber_ids), int_id(_rf_src), time.time(), re.sub('@BB|@BB ','',sms))
|
||||
elif '@' and ' E-' in sms:
|
||||
email_message = str(re.sub('.*@|.* E-', '', sms))
|
||||
to_email = str(re.sub(' E-.*', '', sms))
|
||||
email_subject = 'New message from ' + str(get_alias(int_id(_rf_src), subscriber_ids))
|
||||
logger.info('Email to: ' + to_email)
|
||||
logger.info('Message: ' + email_message)
|
||||
try:
|
||||
send_email(to_email, email_subject, email_message)
|
||||
logger.info('Email sent.')
|
||||
except Exception as error_exception:
|
||||
logger.info('Failed to send email.')
|
||||
logger.info(error_exception)
|
||||
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
|
||||
elif '@SOS' in sms or '@NOTICE' in sms:
|
||||
sos_write(int_id(_rf_src), time.time(), sms)
|
||||
elif '@REM SOS' == sms:
|
||||
os.remove(emergency_sos_file)
|
||||
logger.info('Removing SOS or Notice')
|
||||
elif '@' and 'M-' in sms:
|
||||
message = re.sub('^@|.* M-|','',sms)
|
||||
recipient = re.sub('@| M-.*','',sms)
|
||||
mailbox_write(get_alias(int_id(_rf_src), subscriber_ids), int_id(_rf_src), time.time(), message, str(recipient).upper())
|
||||
elif '@REM MAIL' == sms:
|
||||
mailbox_delete(_rf_src)
|
||||
elif '@MH' in sms:
|
||||
grid_square = re.sub('@MH ', '', sms)
|
||||
if len(grid_square) < 6:
|
||||
pass
|
||||
else:
|
||||
lat = decdeg2dms(mh.to_location(grid_square)[0])
|
||||
lon = decdeg2dms(mh.to_location(grid_square)[1])
|
||||
|
||||
if lon[0] < 0:
|
||||
lon_dir = 'W'
|
||||
if lon[0] > 0:
|
||||
lon_dir = 'E'
|
||||
if lat[0] < 0:
|
||||
lat_dir = 'S'
|
||||
if lat[0] > 0:
|
||||
lat_dir = 'N'
|
||||
#logger.info(lat)
|
||||
#logger.info(lat_dir)
|
||||
aprs_lat = str(str(re.sub('\..*|-', '', str(lat[0]))) + str(re.sub('\..*', '', str(lat[1])) + '.')).zfill(5) + ' ' + lat_dir
|
||||
aprs_lon = str(str(re.sub('\..*|-', '', str(lon[0]))) + str(re.sub('\..*', '', str(lon[1])) + '.')).zfill(6) + ' ' + lon_dir
|
||||
logger.info('Latitude: ' + str(aprs_lat))
|
||||
logger.info('Longitude: ' + str(aprs_lon))
|
||||
# 14FRS2013 simplified and moved settings retrieval
|
||||
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
|
||||
if int_id(_rf_src) not in user_settings:
|
||||
ssid = str(user_ssid)
|
||||
icon_table = '/'
|
||||
icon_icon = '['
|
||||
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
|
||||
else:
|
||||
if user_settings[int_id(_rf_src)][1]['ssid'] == '':
|
||||
ssid = user_ssid
|
||||
if user_settings[int_id(_rf_src)][3]['comment'] == '':
|
||||
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
|
||||
if user_settings[int_id(_rf_src)][2]['icon'] == '':
|
||||
icon_table = '/'
|
||||
icon_icon = '['
|
||||
if user_settings[int_id(_rf_src)][2]['icon'] != '':
|
||||
icon_table = user_settings[int_id(_rf_src)][2]['icon'][0]
|
||||
icon_icon = user_settings[int_id(_rf_src)][2]['icon'][1]
|
||||
if user_settings[int_id(_rf_src)][1]['ssid'] != '':
|
||||
ssid = user_settings[int_id(_rf_src)][1]['ssid']
|
||||
if user_settings[int_id(_rf_src)][3]['comment'] != '':
|
||||
comment = user_settings[int_id(_rf_src)][3]['comment']
|
||||
aprs_loc_packet = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid + '>APHBL3,TCPIP*:@' + str(datetime.datetime.utcnow().strftime("%H%M%Sh")) + str(aprs_lat) + icon_table + str(aprs_lon) + icon_icon + '/' + str(comment)
|
||||
logger.info(aprs_loc_packet)
|
||||
logger.info('User comment: ' + comment)
|
||||
logger.info('User SSID: ' + ssid)
|
||||
logger.info('User icon: ' + icon_table + icon_icon)
|
||||
try:
|
||||
aprslib.parse(aprs_loc_packet)
|
||||
aprs_send(aprs_loc_packet)
|
||||
dashboard_loc_write(str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid, aprs_lat, aprs_lon, time.time(), comment)
|
||||
#logger.info('Sent manual position to APRS')
|
||||
except Exception as error_exception:
|
||||
logger.info('Exception. Not uploaded')
|
||||
logger.info(error_exception)
|
||||
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
|
||||
packet_assembly = ''
|
||||
|
||||
|
||||
elif 'A-' in sms and '@' in sms:
|
||||
#Example SMS text: @ARMDS A-This is a test.
|
||||
aprs_dest = re.sub('@| A-.*','',sms)
|
||||
aprs_msg = re.sub('^@|.* A-|','',sms)
|
||||
logger.info('APRS message to ' + aprs_dest.upper() + '. Message: ' + aprs_msg)
|
||||
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
|
||||
if int_id(_rf_src) in user_settings and user_settings[int_id(_rf_src)][1]['ssid'] != '':
|
||||
ssid = user_settings[int_id(_rf_src)][1]['ssid']
|
||||
else:
|
||||
ssid = user_ssid
|
||||
aprs_msg_pkt = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + str(ssid) + '>APHBL3,TCPIP*::' + str(aprs_dest).ljust(9).upper() + ':' + aprs_msg[0:73]
|
||||
logger.info(aprs_msg_pkt)
|
||||
try:
|
||||
aprslib.parse(aprs_msg_pkt)
|
||||
aprs_send(aprs_msg_pkt)
|
||||
#logger.info('Packet sent.')
|
||||
except Exception as error_exception:
|
||||
logger.info('Error uploading MSG packet.')
|
||||
logger.info(error_exception)
|
||||
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
|
||||
try:
|
||||
if sms in cmd_list:
|
||||
logger.info('Executing command/script.')
|
||||
os.popen(cmd_list[sms]).read()
|
||||
packet_assembly = ''
|
||||
except Exception as error_exception:
|
||||
logger.info('Exception. Command possibly not in list, or other error.')
|
||||
packet_assembly = ''
|
||||
logger.info(error_exception)
|
||||
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
|
||||
else:
|
||||
pass
|
||||
|
||||
###########
|
||||
|
||||
|
||||
class DATA_SYSTEM(HBSYSTEM):
|
||||
## global n_packet_assembly, packet_assembly
|
||||
|
||||
def __init__(self, _name, _config, _report):
|
||||
HBSYSTEM.__init__(self, _name, _config, _report)
|
||||
|
||||
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
|
||||
# Capture data headers
|
||||
global n_packet_assembly, hdr_type
|
||||
#logger.info(_dtype_vseq)
|
||||
logger.info(time.strftime('%H:%M:%S - %m/%d/%y'))
|
||||
#logger.info('Special debug for developement:')
|
||||
#logger.info(ahex(bptc_decode(_data)))
|
||||
#logger.info(hdr_type)
|
||||
#logger.info((ba2num(bptc_decode(_data)[8:12])))
|
||||
if int_id(_dst_id) == data_id:
|
||||
#logger.info(type(_seq))
|
||||
if type(_seq) is bytes:
|
||||
pckt_seq = int.from_bytes(_seq, 'big')
|
||||
else:
|
||||
pckt_seq = _seq
|
||||
# Try to classify header
|
||||
# UDT header has DPF of 0101, which is 5.
|
||||
# If 5 is at position 3, then this should be a UDT header for MD-380 type radios.
|
||||
# Coordinates are usually in the very next block after the header, we will discard the rest.
|
||||
#logger.info(ahex(bptc_decode(_data)[0:10]))
|
||||
if _call_type == call_type and header_ID(_data)[3] == '5' and ba2num(bptc_decode(_data)[69:72]) == 0 and ba2num(bptc_decode(_data)[8:12]) == 0 or (_call_type == 'vcsbk' and header_ID(_data)[3] == '5' and ba2num(bptc_decode(_data)[69:72]) == 0 and ba2num(bptc_decode(_data)[8:12]) == 0):
|
||||
global udt_block
|
||||
logger.info('MD-380 type UDT header detected. Very next packet should be location.')
|
||||
hdr_type = '380'
|
||||
if _dtype_vseq == 6 and hdr_type == '380' or _dtype_vseq == 'group' and hdr_type == '380':
|
||||
udt_block = 1
|
||||
if _dtype_vseq == 7 and hdr_type == '380':
|
||||
udt_block = udt_block - 1
|
||||
if udt_block == 0:
|
||||
logger.info('MD-380 type packet. This should contain the GPS location.')
|
||||
logger.info('Packet: ' + str(ahex(bptc_decode(_data))))
|
||||
if ba2num(bptc_decode(_data)[1:2]) == 1:
|
||||
lat_dir = 'N'
|
||||
if ba2num(bptc_decode(_data)[1:2]) == 0:
|
||||
lat_dir = 'S'
|
||||
if ba2num(bptc_decode(_data)[2:3]) == 1:
|
||||
lon_dir = 'E'
|
||||
if ba2num(bptc_decode(_data)[2:3]) == 0:
|
||||
lon_dir = 'W'
|
||||
lat_deg = ba2num(bptc_decode(_data)[11:18])
|
||||
lon_deg = ba2num(bptc_decode(_data)[38:46])
|
||||
lat_min = ba2num(bptc_decode(_data)[18:24])
|
||||
lon_min = ba2num(bptc_decode(_data)[46:52])
|
||||
lat_min_dec = str(ba2num(bptc_decode(_data)[24:38])).zfill(4)
|
||||
lon_min_dec = str(ba2num(bptc_decode(_data)[52:66])).zfill(4)
|
||||
# Old MD-380 coordinate format, keep here until new is confirmed working.
|
||||
#aprs_lat = str(str(lat_deg) + str(lat_min) + '.' + str(lat_min_dec)[0:2]).zfill(7) + lat_dir
|
||||
#aprs_lon = str(str(lon_deg) + str(lon_min) + '.' + str(lon_min_dec)[0:2]).zfill(8) + lon_dir
|
||||
# Fix for MD-380 by G7HIF
|
||||
aprs_lat = str(str(lat_deg) + str(lat_min).zfill(2) + '.' + str(lat_min_dec)[0:2]).zfill(7) + lat_dir
|
||||
aprs_lon = str(str(lon_deg) + str(lon_min).zfill(2) + '.' + str(lon_min_dec)[0:2]).zfill(8) + lon_dir
|
||||
|
||||
# Form APRS packet
|
||||
#logger.info(aprs_loc_packet)
|
||||
logger.info('Lat: ' + str(aprs_lat) + ' Lon: ' + str(aprs_lon))
|
||||
# 14FRS2013 simplified and moved settings retrieval
|
||||
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
|
||||
if int_id(_rf_src) not in user_settings:
|
||||
ssid = str(user_ssid)
|
||||
icon_table = '/'
|
||||
icon_icon = '['
|
||||
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
|
||||
else:
|
||||
if user_settings[int_id(_rf_src)][1]['ssid'] == '':
|
||||
ssid = user_ssid
|
||||
if user_settings[int_id(_rf_src)][3]['comment'] == '':
|
||||
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
|
||||
if user_settings[int_id(_rf_src)][2]['icon'] == '':
|
||||
icon_table = '/'
|
||||
icon_icon = '['
|
||||
if user_settings[int_id(_rf_src)][2]['icon'] != '':
|
||||
icon_table = user_settings[int_id(_rf_src)][2]['icon'][0]
|
||||
icon_icon = user_settings[int_id(_rf_src)][2]['icon'][1]
|
||||
if user_settings[int_id(_rf_src)][1]['ssid'] != '':
|
||||
ssid = user_settings[int_id(_rf_src)][1]['ssid']
|
||||
if user_settings[int_id(_rf_src)][3]['comment'] != '':
|
||||
comment = user_settings[int_id(_rf_src)][3]['comment']
|
||||
aprs_loc_packet = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid + '>APHBL3,TCPIP*:@' + str(datetime.datetime.utcnow().strftime("%H%M%Sh")) + str(aprs_lat) + icon_table + str(aprs_lon) + icon_icon + '/' + str(comment)
|
||||
logger.info(aprs_loc_packet)
|
||||
logger.info('User comment: ' + comment)
|
||||
logger.info('User SSID: ' + ssid)
|
||||
logger.info('User icon: ' + icon_table + icon_icon)
|
||||
# Attempt to prevent malformed packets from being uploaded.
|
||||
try:
|
||||
aprslib.parse(aprs_loc_packet)
|
||||
float(lat_deg) < 91
|
||||
float(lon_deg) < 121
|
||||
aprs_send(aprs_loc_packet)
|
||||
dashboard_loc_write(str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid, aprs_lat, aprs_lon, time.time(), comment)
|
||||
#logger.info('Sent APRS packet')
|
||||
except Exception as error_exception:
|
||||
logger.info('Error. Failed to send packet. Packet may be malformed.')
|
||||
logger.info(error_exception)
|
||||
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
|
||||
udt_block = 1
|
||||
hdr_type = ''
|
||||
else:
|
||||
pass
|
||||
#NMEA type packets for Anytone like radios.
|
||||
#if _call_type == call_type or (_call_type == 'vcsbk' and pckt_seq > 3): #int.from_bytes(_seq, 'big') > 3 ):
|
||||
# 14FRS2013 contributed improved header filtering, KF7EEL added conditions to allow both call types at the same time
|
||||
if _call_type == call_type or (_call_type == 'vcsbk' and pckt_seq > 3 and call_type != 'unit') or (_call_type == 'group' and pckt_seq > 3 and call_type != 'unit') or (_call_type == 'group' and pckt_seq > 3 and call_type == 'both') or (_call_type == 'vcsbk' and pckt_seq > 3 and call_type == 'both') or (_call_type == 'unit' and pckt_seq > 3 and call_type == 'both'): #int.from_bytes(_seq, 'big') > 3 ):
|
||||
global packet_assembly, btf
|
||||
if _dtype_vseq == 6 or _dtype_vseq == 'group':
|
||||
global btf, hdr_start
|
||||
hdr_start = str(header_ID(_data))
|
||||
logger.info('Header from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + '. DMR ID: ' + str(int_id(_rf_src)))
|
||||
logger.info(ahex(bptc_decode(_data)))
|
||||
logger.info('Blocks to follow: ' + str(ba2num(bptc_decode(_data)[65:72])))
|
||||
btf = ba2num(bptc_decode(_data)[65:72])
|
||||
# Try resetting packet_assembly
|
||||
packet_assembly = ''
|
||||
# Data blocks at 1/2 rate, see https://github.com/g4klx/MMDVM/blob/master/DMRDefines.h for data types. _dtype_seq defined here also
|
||||
if _dtype_vseq == 7:
|
||||
btf = btf - 1
|
||||
logger.info('Block #: ' + str(btf))
|
||||
#logger.info(_seq)
|
||||
logger.info('Data block from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + '. DMR ID: ' + str(int_id(_rf_src)))
|
||||
logger.info(ahex(bptc_decode(_data)))
|
||||
if _seq == 0:
|
||||
n_packet_assembly = 0
|
||||
packet_assembly = ''
|
||||
|
||||
#if btf < btf + 1:
|
||||
# 14FRS2013 removed condition, works great!
|
||||
n_packet_assembly = n_packet_assembly + 1
|
||||
packet_assembly = packet_assembly + str(bptc_decode(_data)) #str((decode_full_lc(b_packet)).strip('bitarray('))
|
||||
# Use block 0 as trigger. $GPRMC must also be in string to indicate NMEA.
|
||||
# This triggers the APRS upload
|
||||
if btf == 0:
|
||||
final_packet = str(bitarray(re.sub("\)|\(|bitarray|'", '', packet_assembly)).tobytes().decode('utf-8', 'ignore'))
|
||||
sms_hex = str(ba2hx(bitarray(re.sub("\)|\(|bitarray|'", '', packet_assembly))))
|
||||
sms_hex_string = re.sub("b'|'", '', str(sms_hex))
|
||||
#NMEA GPS sentence
|
||||
if '$GPRMC' in final_packet or '$GNRMC' in final_packet:
|
||||
logger.info(final_packet + '\n')
|
||||
# Eliminate excess bytes based on NMEA type
|
||||
# GPRMC
|
||||
if 'GPRMC' in final_packet:
|
||||
logger.info('GPRMC location')
|
||||
#nmea_parse = re.sub('A\*.*|.*\$', '', str(final_packet))
|
||||
nmea_parse = re.sub('A\*.*|.*\$|\n.*', '', str(final_packet))
|
||||
# GNRMC
|
||||
if 'GNRMC' in final_packet:
|
||||
logger.info('GNRMC location')
|
||||
nmea_parse = re.sub('.*\$|\n.*|V\*.*', '', final_packet)
|
||||
loc = pynmea2.parse(nmea_parse, check=False)
|
||||
logger.info('Latitude: ' + str(loc.lat) + str(loc.lat_dir) + ' Longitude: ' + str(loc.lon) + str(loc.lon_dir) + ' Direction: ' + str(loc.true_course) + ' Speed: ' + str(loc.spd_over_grnd) + '\n')
|
||||
try:
|
||||
# Begin APRS format and upload
|
||||
# Disable opening file for reading to reduce "collision" or reading and writing at same time.
|
||||
# 14FRS2013 simplified and moved settings retrieval
|
||||
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
|
||||
if int_id(_rf_src) not in user_settings:
|
||||
ssid = str(user_ssid)
|
||||
icon_table = '/'
|
||||
icon_icon = '['
|
||||
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
|
||||
else:
|
||||
if user_settings[int_id(_rf_src)][1]['ssid'] == '':
|
||||
ssid = user_ssid
|
||||
if user_settings[int_id(_rf_src)][3]['comment'] == '':
|
||||
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
|
||||
if user_settings[int_id(_rf_src)][2]['icon'] == '':
|
||||
icon_table = '/'
|
||||
icon_icon = '['
|
||||
if user_settings[int_id(_rf_src)][2]['icon'] != '':
|
||||
icon_table = user_settings[int_id(_rf_src)][2]['icon'][0]
|
||||
icon_icon = user_settings[int_id(_rf_src)][2]['icon'][1]
|
||||
if user_settings[int_id(_rf_src)][1]['ssid'] != '':
|
||||
ssid = user_settings[int_id(_rf_src)][1]['ssid']
|
||||
if user_settings[int_id(_rf_src)][3]['comment'] != '':
|
||||
comment = user_settings[int_id(_rf_src)][3]['comment']
|
||||
aprs_loc_packet = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid + '>APHBL3,TCPIP*:@' + str(datetime.datetime.utcnow().strftime("%H%M%Sh")) + str(loc.lat[0:7]) + str(loc.lat_dir) + icon_table + str(loc.lon[0:8]) + str(loc.lon_dir) + icon_icon + str(round(loc.true_course)).zfill(3) + '/' + str(round(loc.spd_over_grnd)).zfill(3) + '/' + str(comment)
|
||||
logger.info(aprs_loc_packet)
|
||||
logger.info('User comment: ' + comment)
|
||||
logger.info('User SSID: ' + ssid)
|
||||
logger.info('User icon: ' + icon_table + icon_icon)
|
||||
except Exception as error_exception:
|
||||
logger.info('Error or user settings file not found, proceeding with default settings.')
|
||||
aprs_loc_packet = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + str(user_ssid) + '>APHBL3,TCPIP*:@' + str(datetime.datetime.utcnow().strftime("%H%M%Sh")) + str(loc.lat[0:7]) + str(loc.lat_dir) + '/' + str(loc.lon[0:8]) + str(loc.lon_dir) + '[' + str(round(loc.true_course)).zfill(3) + '/' + str(round(loc.spd_over_grnd)).zfill(3) + '/' + aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
|
||||
logger.info(error_exception)
|
||||
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
|
||||
try:
|
||||
# Try parse of APRS packet. If it fails, it will not upload to APRS-IS
|
||||
aprslib.parse(aprs_loc_packet)
|
||||
# Float values of lat and lon. Anything that is not a number will cause it to fail.
|
||||
float(loc.lat)
|
||||
float(loc.lon)
|
||||
aprs_send(aprs_loc_packet)
|
||||
dashboard_loc_write(str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid, str(loc.lat[0:7]) + str(loc.lat_dir), str(loc.lon[0:8]) + str(loc.lon_dir), time.time(), comment)
|
||||
except Exception as error_exception:
|
||||
logger.info('Failed to parse packet. Packet may be deformed. Not uploaded.')
|
||||
logger.info(error_exception)
|
||||
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
|
||||
#final_packet = ''
|
||||
# Get callsign based on DMR ID
|
||||
# End APRS-IS upload
|
||||
# Assume this is an SMS message
|
||||
elif '$GPRMC' not in final_packet or '$GNRMC' not in final_packet:
|
||||
|
||||
#### # Motorola type SMS header
|
||||
## if '824a' in hdr_start or '024a' in hdr_start:
|
||||
## logger.info('\nMotorola type SMS')
|
||||
## sms = codecs.decode(bytes.fromhex(''.join(sms_hex[74:-8].split('00'))), 'utf-8')
|
||||
## logger.info('\n\n' + 'Received SMS from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + ', DMR ID: ' + str(int_id(_rf_src)) + ': ' + str(sms) + '\n')
|
||||
## process_sms(_rf_src, sms)
|
||||
## packet_assembly = ''
|
||||
## # ETSI? type SMS header
|
||||
## elif '0244' in hdr_start or '8244' in hdr_start:
|
||||
## logger.info('ETSI? type SMS')
|
||||
## sms = codecs.decode(bytes.fromhex(''.join(sms_hex[64:-8].split('00'))), 'utf-8')
|
||||
## logger.info('\n\n' + 'Received SMS from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + ', DMR ID: ' + str(int_id(_rf_src)) + ': ' + str(sms) + '\n')
|
||||
## #logger.info(final_packet)
|
||||
## #logger.info(sms_hex[64:-8])
|
||||
## process_sms(_rf_src, sms)
|
||||
## packet_assembly = ''
|
||||
####
|
||||
## else:
|
||||
logger.info('\nSMS detected. Attempting to parse.')
|
||||
#logger.info(final_packet)
|
||||
logger.info(sms_hex)
|
||||
## logger.info(type(sms_hex))
|
||||
logger.info('Attempting to find command...')
|
||||
## sms = codecs.decode(bytes.fromhex(''.join(sms_hex[:-8].split('00'))), 'utf-8', 'ignore')
|
||||
sms = codecs.decode(bytes.fromhex(''.join(sms_hex_string[:-8].split('00'))), 'utf-8', 'ignore')
|
||||
msg_found = re.sub('.*\n', '', sms)
|
||||
logger.info('\n\n' + 'Received SMS from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + ', DMR ID: ' + str(int_id(_rf_src)) + ': ' + str(msg_found) + '\n')
|
||||
process_sms(_rf_src, msg_found)
|
||||
#packet_assembly = ''
|
||||
pass
|
||||
#logger.info(bitarray(re.sub("\)|\(|bitarray|'", '', str(bptc_decode(_data)).tobytes().decode('utf-8', 'ignore'))))
|
||||
#logger.info('\n\n' + 'Received SMS from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + ', DMR ID: ' + str(int_id(_rf_src)) + ': ' + str(sms) + '\n')
|
||||
# Reset the packet assembly to prevent old data from returning.
|
||||
# 14FRS2013 moved variable reset
|
||||
hdr_start = ''
|
||||
n_packet_assembly = 0
|
||||
packet_assembly = ''
|
||||
btf = 0
|
||||
#logger.info(_seq)
|
||||
#packet_assembly = '' #logger.info(_dtype_vseq)
|
||||
#logger.info(ahex(bptc_decode(_data)).decode('utf-8', 'ignore'))
|
||||
#logger.info(bitarray(re.sub("\)|\(|bitarray|'", '', str(bptc_decode(_data)).tobytes().decode('utf-8', 'ignore'))))
|
||||
|
||||
else:
|
||||
pass
|
||||
|
||||
|
||||
#************************************************
|
||||
# MAIN PROGRAM LOOP STARTS HERE
|
||||
#************************************************
|
||||
|
||||
if __name__ == '__main__':
|
||||
#global aprs_callsign, aprs_passcode, aprs_server, aprs_port, user_ssid, aprs_comment, call_type, data_id
|
||||
import argparse
|
||||
import sys
|
||||
import os
|
||||
import signal
|
||||
from dmr_utils3.utils import try_download, mk_id_dict
|
||||
|
||||
# Change the current directory to the location of the application
|
||||
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
|
||||
|
||||
|
||||
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually gps_data.cfg)')
|
||||
parser.add_argument('-l', '--logging', action='store', dest='LOG_LEVEL', help='Override config file logging level.')
|
||||
cli_args = parser.parse_args()
|
||||
|
||||
# Ensure we have a path for the config file, if one wasn't specified, then use the default (top of file)
|
||||
if not cli_args.CONFIG_FILE:
|
||||
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/gps_data.cfg'
|
||||
|
||||
# Call the external routine to build the configuration dictionary
|
||||
CONFIG = config.build_config(cli_args.CONFIG_FILE)
|
||||
|
||||
data_id = int(CONFIG['GPS_DATA']['DATA_DMR_ID'])
|
||||
|
||||
# Group call or Unit (private) call
|
||||
call_type = CONFIG['GPS_DATA']['CALL_TYPE']
|
||||
# APRS-IS login information
|
||||
aprs_callsign = CONFIG['GPS_DATA']['APRS_LOGIN_CALL']
|
||||
aprs_passcode = int(CONFIG['GPS_DATA']['APRS_LOGIN_PASSCODE'])
|
||||
aprs_server = CONFIG['GPS_DATA']['APRS_SERVER']
|
||||
aprs_port = int(CONFIG['GPS_DATA']['APRS_PORT'])
|
||||
user_ssid = CONFIG['GPS_DATA']['USER_APRS_SSID']
|
||||
aprs_comment = CONFIG['GPS_DATA']['USER_APRS_COMMENT']
|
||||
# EMAIL variables
|
||||
email_sender = CONFIG['GPS_DATA']['EMAIL_SENDER']
|
||||
email_password = CONFIG['GPS_DATA']['EMAIL_PASSWORD']
|
||||
smtp_server = CONFIG['GPS_DATA']['SMTP_SERVER']
|
||||
smtp_port = CONFIG['GPS_DATA']['SMTP_PORT']
|
||||
|
||||
# Dashboard files
|
||||
bb_file = CONFIG['GPS_DATA']['BULLETIN_BOARD_FILE']
|
||||
loc_file = CONFIG['GPS_DATA']['LOCATION_FILE']
|
||||
the_mailbox_file = CONFIG['GPS_DATA']['MAILBOX_FILE']
|
||||
emergency_sos_file = CONFIG['GPS_DATA']['EMERGENCY_SOS_FILE']
|
||||
|
||||
# User APRS settings
|
||||
user_settings_file = CONFIG['GPS_DATA']['USER_SETTINGS_FILE']
|
||||
|
||||
# Check if user_settings (for APRS settings of users) exists. Creat it if not.
|
||||
if Path(user_settings_file).is_file():
|
||||
pass
|
||||
else:
|
||||
Path(user_settings_file).touch()
|
||||
with open(user_settings_file, 'w') as user_dict_file:
|
||||
user_dict_file.write("{1: [{'call': 'N0CALL'}, {'ssid': ''}, {'icon': ''}, {'comment': ''}]}")
|
||||
user_dict_file.close()
|
||||
# Check to see if dashboard files exist
|
||||
if Path(loc_file).is_file():
|
||||
pass
|
||||
else:
|
||||
Path(loc_file).touch()
|
||||
with open(loc_file, 'w') as user_loc_file:
|
||||
user_loc_file.write("[]")
|
||||
user_loc_file.close()
|
||||
if Path(bb_file).is_file():
|
||||
pass
|
||||
else:
|
||||
Path(bb_file).touch()
|
||||
with open(bb_file, 'w') as user_bb_file:
|
||||
user_bb_file.write("[]")
|
||||
user_bb_file.close()
|
||||
if Path(the_mailbox_file).is_file():
|
||||
pass
|
||||
else:
|
||||
Path(the_mailbox_file).touch()
|
||||
with open(the_mailbox_file, 'w') as user_mail_file:
|
||||
user_mail_file.write("[]")
|
||||
user_mail_file.close()
|
||||
|
||||
# Start the system logger
|
||||
if cli_args.LOG_LEVEL:
|
||||
CONFIG['LOGGER']['LOG_LEVEL'] = cli_args.LOG_LEVEL
|
||||
logger = log.config_logging(CONFIG['LOGGER'])
|
||||
logger.info('\n\nCopyright (c) 2013, 2014, 2015, 2016, 2018, 2019\n\tThe Regents of the K0USY Group. All rights reserved.\n GPS and Data decoding by Eric, KF7EEL')
|
||||
logger.debug('Logging system started, anything from here on gets logged')
|
||||
|
||||
# Set up the signal handler
|
||||
def sig_handler(_signal, _frame):
|
||||
logger.info('SHUTDOWN: >>>GPS and Data Decoder<<< IS TERMINATING WITH SIGNAL %s', str(_signal))
|
||||
hblink_handler(_signal, _frame)
|
||||
logger.info('SHUTDOWN: ALL SYSTEM HANDLERS EXECUTED - STOPPING REACTOR')
|
||||
reactor.stop()
|
||||
|
||||
# Set signal handers so that we can gracefully exit if need be
|
||||
for sig in [signal.SIGTERM, signal.SIGINT]:
|
||||
signal.signal(sig, sig_handler)
|
||||
|
||||
# Create the name-number mapping dictionaries
|
||||
peer_ids, subscriber_ids, talkgroup_ids = mk_aliases(CONFIG)
|
||||
|
||||
|
||||
# INITIALIZE THE REPORTING LOOP
|
||||
if CONFIG['REPORTS']['REPORT']:
|
||||
report_server = config_reports(CONFIG, reportFactory)
|
||||
else:
|
||||
report_server = None
|
||||
logger.info('(REPORT) TCP Socket reporting not configured')
|
||||
|
||||
# HBlink instance creation
|
||||
logger.info('HBlink \'gps_data.py\' -- SYSTEM STARTING...')
|
||||
for system in CONFIG['SYSTEMS']:
|
||||
if CONFIG['SYSTEMS'][system]['ENABLED']:
|
||||
if CONFIG['SYSTEMS'][system]['MODE'] == 'OPENBRIDGE':
|
||||
systems[system] = OPENBRIDGE(system, CONFIG, report_server)
|
||||
else:
|
||||
systems[system] = DATA_SYSTEM(system, CONFIG, report_server)
|
||||
|
||||
reactor.listenUDP(CONFIG['SYSTEMS'][system]['PORT'], systems[system], interface=CONFIG['SYSTEMS'][system]['IP'])
|
||||
logger.debug('%s instance created: %s, %s', CONFIG['SYSTEMS'][system]['MODE'], system, systems[system])
|
||||
|
||||
reactor.run()
|
||||
|
||||
|
||||
# John 3:16 - For God so loved the world, that he gave his only Son,
|
||||
# that whoever believes in him should not perish but have eternal life.
|
5
rules_SAMPLE.py
Executable file → Normal file
5
rules_SAMPLE.py
Executable file → Normal file
@ -51,7 +51,7 @@ BRIDGES = {
|
||||
list the names of each system that should bridge unit to unit (individual) calls.
|
||||
'''
|
||||
|
||||
UNIT = ['MASTER-1', 'CHANGE_ME']
|
||||
UNIT = ['MASTER-1', 'PEER-1']
|
||||
|
||||
'''
|
||||
Unit Call flood timeout:
|
||||
@ -69,12 +69,9 @@ Input the DMR ID and SYSTEM of a subscriber that you would like to have always h
|
||||
This will not flood all systems.
|
||||
'''
|
||||
STATIC_UNIT = [
|
||||
# [ 456, 'CLIENT-1'],
|
||||
# [ 123, 'MASTER-1'],
|
||||
[ 9099, 'D-APRS']
|
||||
]
|
||||
|
||||
|
||||
'''
|
||||
This is for testing the syntax of the file. It won't eliminate all errors, but running this file
|
||||
like it were a Python program itself will tell you if the syntax is correct!
|
||||
|
162
rules_full_bridge-SAMPLE.py
Executable file
162
rules_full_bridge-SAMPLE.py
Executable file
@ -0,0 +1,162 @@
|
||||
'''
|
||||
THIS EXAMPLE WILL NOT WORK AS IT IS - YOU MUST SPECIFY YOUR OWN VALUES!!!
|
||||
|
||||
This file is organized around the "Conference Bridges" that you wish to use. If you're a c-Bridge
|
||||
person, think of these as "bridge groups". You might also liken them to a "reflector". If a particular
|
||||
system is "ACTIVE" on a particular conference bridge, any traffid from that system will be sent
|
||||
to any other system that is active on the bridge as well. This is not an "end to end" method, because
|
||||
each system must independently be activated on the bridge.
|
||||
|
||||
The first level (e.g. "WORLDWIDE" or "STATEWIDE" in the examples) is the name of the conference
|
||||
bridge. This is any arbitrary ASCII text string you want to use. Under each conference bridge
|
||||
definition are the following items -- one line for each HBSystem as defined in the main HBlink
|
||||
configuration file.
|
||||
|
||||
* SYSTEM - The name of the sytem as listed in the main hblink configuration file (e.g. hblink.cfg)
|
||||
This MUST be the exact same name as in the main config file!!!
|
||||
* TS - Timeslot used for matching traffic to this confernce bridge
|
||||
XLX connections should *ALWAYS* use TS 2 only.
|
||||
* TGID - Talkgroup ID used for matching traffic to this conference bridge
|
||||
XLX connections should *ALWAYS* use TG 9 only.
|
||||
* ON and OFF are LISTS of Talkgroup IDs used to trigger this system off and on. Even if you
|
||||
only want one (as shown in the ON example), it has to be in list format. None can be
|
||||
handled with an empty list, such as " 'ON': [] ".
|
||||
* TO_TYPE is timeout type. If you want to use timers, ON means when it's turned on, it will
|
||||
turn off afer the timout period and OFF means it will turn back on after the timout
|
||||
period. If you don't want to use timers, set it to anything else, but 'NONE' might be
|
||||
a good value for documentation!
|
||||
* TIMOUT is a value in minutes for the timout timer. No, I won't make it 'seconds', so don't
|
||||
ask. Timers are performance "expense".
|
||||
* RESET is a list of Talkgroup IDs that, in addition to the ON and OFF lists will cause a running
|
||||
timer to be reset. This is useful if you are using different TGIDs for voice traffic than
|
||||
triggering. If you are not, there is NO NEED to use this feature.
|
||||
'''
|
||||
# REQUIRED! - Path to your full_bridge.cfg
|
||||
config_file = './full_bridge.cfg'
|
||||
|
||||
BRIDGES_TEMPLATE = {
|
||||
'STATEWIDE': [
|
||||
{'SYSTEM': 'MASTER-1', 'TS': 2, 'TGID': 3129, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'NONE', 'ON': [4,], 'OFF': [7,10], 'RESET': []},
|
||||
{'SYSTEM': 'PEER-2', 'TS': 2, 'TGID': 3129, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'NONE', 'ON': [4,], 'OFF': [7,10], 'RESET': []},
|
||||
],
|
||||
'ECHO': [
|
||||
{'SYSTEM': 'MASTER-1', 'TS': 2, 'TGID': 9999, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'ON', 'ON': [9999,], 'OFF': [9,10], 'RESET': []},
|
||||
{'SYSTEM': 'PEER-1', 'TS': 2, 'TGID': 9999, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'ON', 'ON': [9999,], 'OFF': [9,10], 'RESET': []},
|
||||
# For proxy MASTERs, just put in the name of the stanza, and rules will be generated automatically
|
||||
{'SYSTEM': 'HOTSPOT', 'TS': 2, 'TGID': 9, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'NONE', 'ON': [4], 'OFF': [7,10], 'RESET': []},
|
||||
]
|
||||
}
|
||||
|
||||
'''
|
||||
list the names of each system that should NOT be bridged unit to unit (individual) calls.
|
||||
'''
|
||||
|
||||
EXCLUDE_FROM_UNIT = ['OBP-1', 'PEER-1']
|
||||
|
||||
'''
|
||||
Unit Call flood timeout:
|
||||
The amount of time to keep sending private calls to a single system before
|
||||
flooding all systems with the call. A higher value should be set for systems where subscribers
|
||||
are not moving between systems often. A lower value should be set for systems that have subscribers
|
||||
moving between systems often.
|
||||
|
||||
Time is in minutes.
|
||||
'''
|
||||
UNIT_TIME = 1
|
||||
|
||||
'''
|
||||
Input the DMR ID and SYSTEM of a subscriber that you would like to have always have private calls routed.
|
||||
This will not flood all systems. The last item in the entry is the timeslot. It has no effect on STATIC_UNIT. It
|
||||
is only there to prevent an error in another function.
|
||||
'''
|
||||
STATIC_UNIT = [
|
||||
# [ 9099, 'MASTER-1', 2]
|
||||
]
|
||||
|
||||
'''
|
||||
Manually specify other networks/servers that are authorized to send SMS to your server
|
||||
'''
|
||||
|
||||
authorized_users = {
|
||||
## 'ABC':{
|
||||
## 'mode':'msg_xfer',
|
||||
## 'user':'test_name',
|
||||
## 'password':'passw0rd'
|
||||
## },
|
||||
## 'XYZ':{
|
||||
## 'mode':'msg_xfer',
|
||||
## 'user':'test_name',
|
||||
## 'password':'passw0rd'
|
||||
## }
|
||||
}
|
||||
|
||||
'''
|
||||
List of external servers/networks or external applications that your users can access. The list below can be used in conjunction
|
||||
with or instead of the public list.
|
||||
'''
|
||||
|
||||
local_systems = {
|
||||
# Shortcut used in SMS message
|
||||
## 'XYZ':{
|
||||
# Mode of transfer, this case, message transfer
|
||||
## 'mode':'msg_xfer',
|
||||
# Public or Private auth
|
||||
## 'auth_type':'public',
|
||||
# Name of the server/network
|
||||
## 'network_name':'My HBlink Server',
|
||||
# URL to the dashboard of the server/network
|
||||
## 'url':'http://example.net/',
|
||||
# Username and password given to you by network operator
|
||||
## 'user':'test_name',
|
||||
## 'password':'passw0rd'
|
||||
## },
|
||||
# Shortcut used in SMS message
|
||||
## 'BBD':{
|
||||
# Mode for application, operates differently than msg_xfer
|
||||
## 'mode':'app',
|
||||
# Name of external application
|
||||
## 'app_name':'Multi Network Bulletin Board',
|
||||
# Endpoint URL of API
|
||||
## 'url':'http://hbl.ink/bb/post',
|
||||
# Website for users to get info
|
||||
## 'website':'http://hbl.ink',
|
||||
## },
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
#################### Function used to build bridges for PROXY stanzas, leave alone ####################
|
||||
def build_bridges():
|
||||
import sms_aprs_config, random
|
||||
CONFIG = sms_aprs_config.build_config(config_file)
|
||||
built_bridge = BRIDGES_TEMPLATE.copy()
|
||||
proxy_list = []
|
||||
unique = str('_' + str(random.randint(100, 999)))
|
||||
for i in CONFIG['SYSTEMS']:
|
||||
print(CONFIG['SYSTEMS'][i])
|
||||
if CONFIG['SYSTEMS'][i]['ENABLED'] == True:
|
||||
if CONFIG['SYSTEMS'][i]['MODE'] == 'PROXY':
|
||||
proxy_list.append(i + unique)
|
||||
for p in proxy_list:
|
||||
for b in BRIDGES_TEMPLATE:
|
||||
for s in BRIDGES_TEMPLATE[b]:
|
||||
if s['SYSTEM'] + unique in proxy_list:
|
||||
n_systems = CONFIG['SYSTEMS'][p[:-4]]]['INTERNAL_PORT_STOP'] - CONFIG['SYSTEMS'][p[:-4]]]['INTERNAL_PORT_START']
|
||||
n_count = 0
|
||||
while n_count < n_systems:
|
||||
built_bridge[b].append({'SYSTEM': s['SYSTEM'] + '-' + str(n_count), 'TS': s['TS'], 'TGID': s['TGID'], 'ACTIVE': s['ACTIVE'], 'TIMEOUT': s['TIMEOUT'], 'TO_TYPE': s['TO_TYPE'], 'ON': s['ON'], 'OFF': s['OFF'], 'RESET': s['RESET']})
|
||||
n_count = n_count + 1
|
||||
built_bridge[b].remove(s)
|
||||
return built_bridge
|
||||
############################################################################################################33
|
||||
|
||||
'''
|
||||
This is for testing the syntax of the file. It won't eliminate all errors, but running this file
|
||||
like it were a Python program itself will tell you if the syntax is correct!
|
||||
'''
|
||||
|
||||
if __name__ == '__main__':
|
||||
from pprint import pprint
|
||||
pprint(BRIDGES)
|
||||
pprint(EXCLUDE_FROM_UNIT)
|
@ -21,7 +21,7 @@
|
||||
This is a web dashboard for the GPS/Data application.
|
||||
'''
|
||||
|
||||
from flask import Flask, render_template, request, Response, Markup
|
||||
from flask import Flask, render_template, request, Response, Markup, jsonify, make_response
|
||||
import ast, os
|
||||
#from dashboard_settings import *
|
||||
import folium
|
||||
@ -30,6 +30,9 @@ import re
|
||||
from datetime import datetime
|
||||
import argparse
|
||||
from configparser import ConfigParser
|
||||
from send_sms import *
|
||||
import importlib.util
|
||||
import requests
|
||||
|
||||
|
||||
|
||||
@ -80,7 +83,7 @@ def get_loc_data():
|
||||
last_known_loc_list.append(e['call'])
|
||||
display_number = display_number - 1
|
||||
tmp_loc = tmp_loc + '''<tr>
|
||||
<td style="text-align: center;"><a href="view_map?track=''' + e['call'] + '''"target="_blank"><strong>''' + e['call'] + '''</strong></a></td>
|
||||
<td style="text-align: center;"><a href="''' + dashboard_url + '''/view_map?track=''' + e['call'] + '''"target="_blank"><strong>''' + e['call'] + '''</strong></a></td>
|
||||
<td style="text-align: center;"><strong> ''' + str(e['lat']) + ''' </strong></td>
|
||||
<td style="text-align: center;"><strong> ''' + str(e['lon']) + ''' </strong></td>
|
||||
<td style="text-align: center;"> ''' + loc_time + ''' </td>
|
||||
@ -89,6 +92,52 @@ def get_loc_data():
|
||||
except:
|
||||
return str('<h1 style="text-align: center;">No data</h1>')
|
||||
|
||||
def get_sms_data():
|
||||
try:
|
||||
dash_sms = ast.literal_eval(os.popen('cat ' + sms_file).read())
|
||||
tmp_sms = ''
|
||||
|
||||
sms_hdr = '''
|
||||
|
||||
<tr>
|
||||
<td style="text-align: center;">
|
||||
<h2><strong> Source <br /></strong></h2>
|
||||
</td>
|
||||
<td style="text-align: center;">
|
||||
<h2> <strong>Destination</strong> </h2>
|
||||
</td>
|
||||
<td style="text-align: center;">
|
||||
<h2> <strong>SMS</strong> </h2>
|
||||
</td>
|
||||
<td style="text-align: center;">
|
||||
<h2> <strong>Local Time</strong> </h2>
|
||||
</td>
|
||||
</tr>
|
||||
'''
|
||||
|
||||
for e in dash_sms:
|
||||
if type(e['time']) == str:
|
||||
loc_time = str(e['time'])
|
||||
if type(e['time']) == int or type(e['time']) == float:
|
||||
loc_time = datetime.fromtimestamp(e['time']).strftime(time_format)
|
||||
tmp_sms = tmp_sms + '''
|
||||
<tr>
|
||||
<td style="text-align: center;">
|
||||
<p><strong> ''' + e['snd_call'] + ''' <br /></strong>''' + e['snd_dmr_id'] + '''<strong><br /></strong></p>
|
||||
</td>
|
||||
<td style="text-align: center;">
|
||||
<p><strong>''' + e['rcv_call'] + '''</strong><br />''' + e['rcv_dmr_id'] + '''</p>
|
||||
</td>
|
||||
<td style="text-align: center;"><strong> ''' + e['sms'] + ''' </strong></td>
|
||||
<td style="text-align: center;"> ''' + loc_time + ''' </td>
|
||||
</tr>
|
||||
'''
|
||||
|
||||
return str('<h1 style="text-align: center;">SMS</h1>' + tbl_hdr + sms_hdr + tmp_sms + tbl_ftr)
|
||||
except:
|
||||
return str('<h1 style="text-align: center;">No data</h1>')
|
||||
|
||||
|
||||
|
||||
def get_bb_data():
|
||||
try:
|
||||
@ -178,15 +227,19 @@ def aprs_to_latlon(x):
|
||||
minutes = x - 100*degrees
|
||||
return degrees + minutes/60
|
||||
|
||||
def user_setting_write(dmr_id, input_ssid, input_icon, input_comment):
|
||||
def user_setting_write(dmr_id, input_ssid, input_icon, input_comment, input_aprs):
|
||||
dmr_id = int(dmr_id)
|
||||
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
|
||||
new_dict = user_settings
|
||||
new_dict[dmr_id][1]['ssid'] = input_ssid
|
||||
new_dict[dmr_id][2]['icon'] = input_icon
|
||||
new_dict[dmr_id][3]['comment'] = input_comment
|
||||
print(input_comment)
|
||||
print(new_dict[dmr_id])
|
||||
if input_aprs == 'True':
|
||||
new_dict[dmr_id][5]['APRS'] = True
|
||||
if input_aprs == 'False':
|
||||
new_dict[dmr_id][5]['APRS'] = False
|
||||
#print(input_comment)
|
||||
#print(new_dict[dmr_id])
|
||||
|
||||
# Write modified dict to file
|
||||
with open(user_settings_file, 'w') as user_dict_file:
|
||||
@ -194,11 +247,34 @@ def user_setting_write(dmr_id, input_ssid, input_icon, input_comment):
|
||||
user_dict_file.close()
|
||||
|
||||
|
||||
|
||||
def generate_apps():
|
||||
global access_systems, authorized_users
|
||||
mod = importlib.util.spec_from_file_location("rules_data", parser.get('GPS_DATA', 'RULES_PATH'))
|
||||
rules = importlib.util.module_from_spec(mod)
|
||||
mod.loader.exec_module(rules)
|
||||
local_apps = rules.local_apps
|
||||
authorized_users = rules.authorized_users
|
||||
print(authorized_users)
|
||||
|
||||
public_systems_file = requests.get(parser.get('GPS_DATA', 'PUBLIC_APPS_LIST'))
|
||||
public_apps = ast.literal_eval(public_systems_file.text)
|
||||
access_systems = {}
|
||||
print(type(parser.get('GPS_DATA', 'USE_PUBLIC_APPS')))
|
||||
if parser.get('GPS_DATA', 'USE_PUBLIC_APPS') == 'True':
|
||||
for i in public_apps.items():
|
||||
key = str(i[0])
|
||||
access_systems[key] = i[1]
|
||||
for i in local_apps.items():
|
||||
key = str(i[0])
|
||||
access_systems[key] = i[1]
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
value = Markup('<strong>The HTML String</strong>')
|
||||
#return get_data()
|
||||
return render_template('index.html', title = dashboard_title, logo = logo, emergency = check_emergency())
|
||||
return render_template('index.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, emergency = check_emergency(), api = use_api)
|
||||
@app.route('/bulletin_board')
|
||||
def dash_bb():
|
||||
return get_bb_data()
|
||||
@ -210,11 +286,86 @@ def dash_loc():
|
||||
@app.route('/help/')
|
||||
def help():
|
||||
#return get_data()
|
||||
return render_template('help.html', title = dashboard_title, logo = logo, description = description, data_call_type = data_call_type, data_call_id = data_call_id, aprs_ssid = aprs_ssid)
|
||||
return render_template('help.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, description = description, api = use_api, data_call_type = data_call_type, data_call_id = data_call_id, aprs_ssid = aprs_ssid)
|
||||
@app.route('/sms/')
|
||||
def dash_template_sms():
|
||||
#return get_data()
|
||||
#return render_template('sms.html', title = dashboard_title, logo = logo)
|
||||
return render_template('generic.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, content = Markup(get_sms_data()))
|
||||
|
||||
@app.route('/about/')
|
||||
def about():
|
||||
#return get_data()
|
||||
return render_template('about.html', title = dashboard_title, logo = logo, contact_name = contact_name, contact_call = contact_call, contact_email = contact_email, contact_website = contact_website)
|
||||
return render_template('about.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, contact_name = contact_name, api = use_api, contact_call = contact_call, contact_email = contact_email, contact_website = contact_website)
|
||||
|
||||
@app.route('/external_apps')
|
||||
def external_apps():
|
||||
#access_systems = ast.literal_eval(os.popen('cat ' + access_systems_file).read())
|
||||
msg_lst = ''
|
||||
app_lst = ''
|
||||
for i_msg in access_systems.items():
|
||||
if i_msg[1]['mode'] == 'msg_xfer':
|
||||
msg_lst = msg_lst + '''
|
||||
<tr>
|
||||
<td style="text-align: center;"> ''' + i_msg[1]['network_name'] + '''</td>
|
||||
<td style="text-align: center;"> <strong>?''' + str(i_msg[0]) + '''</strong></td>
|
||||
<td style="text-align: center;"><a href="''' + i_msg[1]['url'] + '''">''' + i_msg[1]['url'] + '''</a></td>
|
||||
</tr> '''
|
||||
for i_app in access_systems.items():
|
||||
if i_app[1]['mode'] == 'app':
|
||||
app_lst = app_lst + '''
|
||||
<tr>
|
||||
<td style="text-align: center;"> ''' + i_app[1]['app_name'] + '''</td>
|
||||
<td style="text-align: center;"> ''' + i_app[1]['app_description'] + '''</td>
|
||||
<td style="text-align: center;"> <strong>?''' + str(i_app[0]) + '''</strong></td>
|
||||
<td style="text-align: center;"><a href="''' + i_app[1]['website'] + '''">''' + i_app[1]['website'] + '''</a></td>
|
||||
</tr> '''
|
||||
content = '''
|
||||
<p> </p>
|
||||
External applications and other HBLink networks that can be accessed via SMS from this gateway:
|
||||
<h2 style="text-align: center;">External Networks/Servers</h2>
|
||||
<table style="border-color: black; width: 600px; margin-left: auto; margin-right: auto;" border="3">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td style="text-align: center;">
|
||||
<h3>Network/Server</h3>
|
||||
</td>
|
||||
<td style="text-align: center;">
|
||||
<h3>Shortcut</h3>
|
||||
</td>
|
||||
<td style="text-align: center;">
|
||||
<h3>URL</h3>
|
||||
</td>
|
||||
</tr>
|
||||
''' + msg_lst + '''
|
||||
</tbody>
|
||||
</table>
|
||||
<p> </p>
|
||||
<h2 style="text-align: center;"> External Applications</h2>
|
||||
<table style="border-color: black; width: 600px; margin-left: auto; margin-right: auto;" border="3">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td style="text-align: center;">
|
||||
<h3>Application</h3>
|
||||
</td>
|
||||
<td style="text-align: center;">
|
||||
<h3>Description</h3>
|
||||
</td>
|
||||
<td style="text-align: center;">
|
||||
<h3>Shortcut</h3>
|
||||
</td>
|
||||
<td style="text-align: center;">
|
||||
<h3>Website</h3>
|
||||
</td>
|
||||
</tr>
|
||||
''' + app_lst + '''
|
||||
</tbody>
|
||||
</table>
|
||||
<p> </p>
|
||||
'''
|
||||
## content = 'yo'
|
||||
return render_template('generic.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, content = Markup(content), api = use_api)
|
||||
|
||||
@app.route('/view_map')
|
||||
def view_map():
|
||||
reload_time = request.args.get('reload')
|
||||
@ -315,12 +466,12 @@ def view_map():
|
||||
<p style="text-align: center;"><button onclick="self.close()">Close</button><!--<button onclick="history.back()">Back</button>-->
|
||||
</p>
|
||||
""" + map_view
|
||||
return render_template('generic.html', title = dashboard_title, logo = logo, content = Markup(content))
|
||||
return render_template('generic.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, content = Markup(content))
|
||||
except Exception as e:
|
||||
content = """<h1 style="text-align: center;">Station not found.</h1>
|
||||
#<p style="text-align: center;"><button onclick="self.close()">Close Window</button>
|
||||
#</p>"""
|
||||
return render_template('generic.html', title = dashboard_title, logo = logo, content = Markup(content))
|
||||
return render_template('generic.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, content = Markup(content))
|
||||
|
||||
if not track_call:
|
||||
folium_map = folium.Map(location=(map_center_lat, map_center_lon), tiles=map_theme, zoom_start=int(zoom_level))
|
||||
@ -361,7 +512,7 @@ def view_map():
|
||||
</tr>
|
||||
""" + loc_comment + """
|
||||
<tr>
|
||||
<td style="text-align: center;"><strong><A href="view_map?track=""" + user_coord['call'] + """" target="_blank">Track Station</A></strong></td>
|
||||
<td style="text-align: center;"><strong><A href='""" + dashboard_url + """/view_map?track=""" + user_coord['call'] + """' target="_blank">Track Station</A></strong></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@ -389,7 +540,7 @@ def view_map():
|
||||
|
||||
@app.route('/map/')
|
||||
def map():
|
||||
return render_template('map.html', title = dashboard_title, logo = logo)
|
||||
return render_template('map.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, api = use_api)
|
||||
|
||||
@app.route('/user', methods = ['GET', 'POST'])
|
||||
def user_settings():
|
||||
@ -401,8 +552,11 @@ def user_settings():
|
||||
ssid = user_settings[int(request.form.get('dmr_id'))][1]['ssid']
|
||||
icon = user_settings[int(request.form.get('dmr_id'))][2]['icon']
|
||||
comment = user_settings[int(request.form.get('dmr_id'))][3]['comment']
|
||||
try:
|
||||
pin = user_settings[int(request.form.get('dmr_id'))][4]['pin']
|
||||
pin = user_settings[int(request.form.get('dmr_id'))][4]['pin']
|
||||
aprs_msg_status = str(user_settings[int(request.form.get('dmr_id'))][5]['APRS'])
|
||||
|
||||
if pin != '':
|
||||
|
||||
if ssid == '':
|
||||
ssid = aprs_ssid
|
||||
if icon == '':
|
||||
@ -432,6 +586,15 @@ def user_settings():
|
||||
<td style="width: 319.367px; text-align: center;"><input id="comment" name="comment" type="text" placeholder='""" + comment + """'/></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="width: 82px;"><strong>APRS Messaging:</strong></td>
|
||||
<td style="width: 319.367px; text-align: center;"><select name="aprs" id="aprs">
|
||||
<option value='""" + aprs_msg_status + """' selected>""" + aprs_msg_status + """</option>
|
||||
<option value="True"> True (Enabled) </option>
|
||||
<option value="False"> False (Disabled) </option>
|
||||
</select>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="width: 82px;"><strong>DMR ID:</strong></td>
|
||||
<td style="width: 319.367px; text-align: center;"><input id="dmr_id" name="dmr_id" type="text" value='""" + user_id + """'/></td>
|
||||
</tr>
|
||||
@ -447,7 +610,7 @@ def user_settings():
|
||||
|
||||
|
||||
"""
|
||||
except:
|
||||
if pin == '':
|
||||
user_result = """<h2 style="text-align: center;">No PIN set for """ + str(user_settings[int(user_id)][0]['call']) + """ - """ + request.form.get('dmr_id') + """</h2>
|
||||
<p style="text-align: center;"><button onclick="history.back()">Back</button>
|
||||
</p>"""
|
||||
@ -462,7 +625,7 @@ def user_settings():
|
||||
ssid = request.form.get('ssid')
|
||||
icon = request.form.get('icon')
|
||||
comment = request.form.get('comment')
|
||||
user_setting_write(request.form.get('dmr_id'), request.form.get('ssid'), request.form.get('icon'), request.form.get('comment'))
|
||||
user_setting_write(request.form.get('dmr_id'), request.form.get('ssid'), request.form.get('icon'), request.form.get('comment'), request.form.get('aprs'))
|
||||
user_result = """<h2 style="text-align: center;">Changed settings for """ + str(user_settings[int(user_id)][0]['call']) + """ - """ + request.form.get('dmr_id') + """</h2>
|
||||
<p style="text-align: center;"><button onclick="history.back()">Back</button>
|
||||
</p>"""
|
||||
@ -525,6 +688,7 @@ def user_settings():
|
||||
ssid = user_settings[int(user_id)][1]['ssid']
|
||||
icon = user_settings[int(user_id)][2]['icon']
|
||||
comment = user_settings[int(user_id)][3]['comment']
|
||||
aprs_msg_status = str(user_settings[int(user_id)][5]['APRS'])
|
||||
if ssid == '':
|
||||
ssid = aprs_ssid
|
||||
if icon == '':
|
||||
@ -554,6 +718,10 @@ def user_settings():
|
||||
<td style="width: 82px;"><strong>Comment:</strong></td>
|
||||
<td style="width: 319.367px; text-align: center;">""" + comment + """</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="width: 82px;"><strong>APRS Messaging:</strong></td>
|
||||
<td style="width: 319.367px; text-align: center;">""" + aprs_msg_status + """</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p style="text-align: center;"><button onclick="history.back()">Back</button>
|
||||
@ -564,7 +732,7 @@ def user_settings():
|
||||
<p style="text-align: center;"><button onclick="history.back()">Back</button>
|
||||
</p>'''
|
||||
|
||||
return render_template('generic.html', title = dashboard_title, logo = logo, content = Markup(user_result))
|
||||
return render_template('generic.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, content = Markup(user_result), api = use_api)
|
||||
|
||||
@app.route('/mailbox')
|
||||
def mailbox():
|
||||
@ -572,7 +740,7 @@ def mailbox():
|
||||
if not recipient:
|
||||
mail_content = """
|
||||
<p>The Mailbox is a place where users can leave messages via DMR SMS. A user can leave a message for someone else by sending a specially formatted SMS to <strong>""" + data_call_id + """</strong>.
|
||||
The message recipient can then use the mailbox to check for messages. You can also check for APRS mesages addressed to your DMR radio. Enter your call sign (without APRS SSID) below to check for messages. See the <a href="help">help</a> page for more information.</p>
|
||||
The message recipient can then use the mailbox to check for messages. You can also check for APRS mesages addressed to your DMR radio. Enter your call sign (without APRS SSID) below to check for messages. See the <a href='""" + dashboard_url + """/help'>help</a> page for more information.</p>
|
||||
<form action="mailbox" method="get">
|
||||
<table style="margin-left: auto; margin-right: auto;">
|
||||
<tbody>
|
||||
@ -640,7 +808,7 @@ def mailbox():
|
||||
<p> </p>
|
||||
|
||||
"""
|
||||
return render_template('generic.html', title = dashboard_title, logo = logo, content = Markup(mail_content))
|
||||
return render_template('generic.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, content = Markup(mail_content), api = use_api)
|
||||
|
||||
|
||||
@app.route('/bulletin_rss.xml')
|
||||
@ -652,7 +820,7 @@ def bb_rss():
|
||||
<rss version="2.0">
|
||||
<channel>
|
||||
<title>""" + dashboard_title + """ - Bulletin Board Feed</title>
|
||||
<link>""" + rss_link + """</link>
|
||||
<link>""" + dashboard_url + """</link>
|
||||
<description>This is the Bulletin Board feed from """ + dashboard_title + """</description>"""
|
||||
for entry in dash_bb:
|
||||
if type(entry['time']) == str:
|
||||
@ -662,7 +830,7 @@ def bb_rss():
|
||||
post_data = post_data + """
|
||||
<item>
|
||||
<title>""" + entry['call'] + ' - ' + str(entry['dmr_id']) + """</title>
|
||||
<link>""" + rss_link + """</link>
|
||||
<link>""" + dashboard_url + """</link>
|
||||
<description>""" + entry['bulletin'] + """ - """ + loc_time + """</description>
|
||||
<pubDate>""" + datetime.fromtimestamp(entry['time']).strftime('%a, %d %b %y') +"""</pubDate>
|
||||
</item>
|
||||
@ -681,7 +849,7 @@ def mail_rss():
|
||||
<rss version="2.0">
|
||||
<channel>
|
||||
<title>""" + dashboard_title + """ - Mailbox Feed for """ + recipient + """</title>
|
||||
<link>""" + rss_link + """</link>
|
||||
<link>""" + dashboard_url + """</link>
|
||||
<description>This is a Mailbox feed from """ + dashboard_title + """ for """ + recipient + """.</description>"""
|
||||
for entry in mailbox_file:
|
||||
if type(entry['time']) == str:
|
||||
@ -692,14 +860,138 @@ def mail_rss():
|
||||
post_data = post_data + """
|
||||
<item>
|
||||
<title>""" + entry['call'] + ' - ' + str(entry['dmr_id']) + """</title>
|
||||
<link>""" + rss_link + """</link>
|
||||
<link>""" + dashboard_url + """</link>
|
||||
<description>""" + entry['message'] + """ - """ + loc_time + """</description>
|
||||
<pubDate>""" + datetime.fromtimestamp(entry['time']).strftime('%a, %d %b %y') +"""</pubDate>
|
||||
</item>
|
||||
"""
|
||||
return Response(rss_header + post_data + "\n</channel>\n</rss>", mimetype='text/xml')
|
||||
|
||||
@app.route('/api', methods=['GET'])
|
||||
@app.route('/api/<api_mode>', methods=['POST'])
|
||||
def api(api_mode=None):
|
||||
if request.method == 'GET':
|
||||
api_content = '<h3 style="text-align: center;"><strong>API Enabled: ' + str(use_api) + '</strong></h3>'
|
||||
return render_template('generic.html', title = dashboard_title, dashboard_url = dashboard_url, logo = logo, content = Markup(api_content), api = use_api)
|
||||
if use_api == True: #'True' or use_api == "true":
|
||||
#access_systems = ast.literal_eval(os.popen('cat ' + access_systems_file).read())
|
||||
#authorized_users = ast.literal_eval(os.popen('cat ' + authorized_users_file).read())
|
||||
api_data = request.json
|
||||
#print(type(api_data))
|
||||
#print((api_data))
|
||||
|
||||
# Find out mode of JSON
|
||||
## try:
|
||||
# Filter msg_xfer
|
||||
if api_data['mode'] == 'msg_xfer':
|
||||
# Handle authorization
|
||||
if api_data['auth_type'] == 'private':
|
||||
#Authenticate
|
||||
if api_data['system_shortcut'] in authorized_users:
|
||||
if api_data['credentials']['user'] == authorized_users[api_data['system_shortcut']]['user'] and api_data['credentials']['password'] == authorized_users[api_data['system_shortcut']]['password']:
|
||||
print(api_data['credentials']['user'])
|
||||
print(api_data['credentials']['password'])
|
||||
for sms in api_data['data'].items():
|
||||
sms_data = sms[1]
|
||||
print((sms_data['destination_id']))
|
||||
print((sms_data['source_id']))
|
||||
print((sms_data['message']))
|
||||
print((sms_data['slot']))
|
||||
if sms_data['slot'] == 0:
|
||||
send_slot = int(unit_sms_ts) - 1
|
||||
if sms_data['slot'] == 1:
|
||||
send_slot = 0
|
||||
if sms_data['slot'] == 2:
|
||||
send_slot = 1
|
||||
send_sms(False, sms_data['destination_id'], sms_data['source_id'], 0000, 'unit', send_slot, sms_data['message'], que_dir)
|
||||
return jsonify(
|
||||
mode=api_data['mode'],
|
||||
status='Generated SMS',
|
||||
)
|
||||
else:
|
||||
message = jsonify(message='Authentication error')
|
||||
return make_response(message, 401)
|
||||
else:
|
||||
message = jsonify(message='System not authorized')
|
||||
return make_response(message, 401)
|
||||
if api_data['auth_type'] == 'public':
|
||||
## auth_file = ast.literal_eval(os.popen('cat ' + auth_token_file).read())
|
||||
## for token in auth_file:
|
||||
## print()
|
||||
## print(token)
|
||||
## print(api_data['auth_token'])
|
||||
## print()
|
||||
## if token == api_data['auth_token']:
|
||||
##
|
||||
## auth_file.remove(api_data['auth_token'])
|
||||
## for i in api_data['data'].items():
|
||||
## sms_data = i[1]
|
||||
## if sms_data['slot'] == 0:
|
||||
## send_slot = int(unit_sms_ts) - 1
|
||||
## if sms_data['slot'] == 1:
|
||||
## send_slot = 0
|
||||
## if sms_data['slot'] == 2:
|
||||
## send_slot = 1
|
||||
## send_sms(False, sms_data['destination_id'], 0000, 0000, 'unit', send_slot, sms_data['message'])
|
||||
## new_auth_file = auth_file
|
||||
## with open(auth_token_file, 'w') as auth_token:
|
||||
## auth_token.write(str(auth_file))
|
||||
## auth_token.close()
|
||||
|
||||
return jsonify(
|
||||
mode=api_data['mode'],
|
||||
status='GNot implemented yet',
|
||||
)
|
||||
else:
|
||||
message = jsonify(message='Not an authentication method')
|
||||
return make_response(message, 400)
|
||||
if api_data['mode'] == 'app':
|
||||
auth_file = ast.literal_eval(os.popen('cat ' + auth_token_file).read())
|
||||
print(auth_file)
|
||||
for token in auth_file:
|
||||
print()
|
||||
print(token)
|
||||
print(api_data['auth_token'])
|
||||
print()
|
||||
if token == api_data['auth_token']:
|
||||
|
||||
auth_file.remove(api_data['auth_token'])
|
||||
for i in api_data['data'].items():
|
||||
sms_data = i[1]
|
||||
if sms_data['slot'] == 0:
|
||||
send_slot = int(unit_sms_ts) - 1
|
||||
if sms_data['slot'] == 1:
|
||||
send_slot = 0
|
||||
if sms_data['slot'] == 2:
|
||||
send_slot = 1
|
||||
send_sms(False, sms_data['destination_id'], 0000, 0000, 'unit', send_slot, sms_data['message'], que_dir)
|
||||
new_auth_file = auth_file
|
||||
with open(auth_token_file, 'w') as auth_token:
|
||||
auth_token.write(str(auth_file))
|
||||
auth_token.close()
|
||||
|
||||
|
||||
return jsonify(
|
||||
mode=api_data['mode'],
|
||||
status='Token accepted, SMS generated',
|
||||
)
|
||||
## if token != api_data['auth_token']:
|
||||
## message = jsonify(message='Auth token not found')
|
||||
## return make_response(message, 401)
|
||||
|
||||
else:
|
||||
message = jsonify(message='Mode not found')
|
||||
return make_response(message, 404)
|
||||
if use_api == False: #"False" or use_api == "false":
|
||||
message = jsonify(message='API is disabled for this server')
|
||||
return make_response(message, 502)
|
||||
## except Exception as e:
|
||||
## message = jsonify(message='Error:' + str(e))
|
||||
## return make_response(message, 400)
|
||||
|
||||
#################### Run App ############################
|
||||
if __name__ == '__main__':
|
||||
global use_api
|
||||
arg_parser = argparse.ArgumentParser()
|
||||
arg_parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually gps_data.cfg)')
|
||||
cli_args = arg_parser.parse_args()
|
||||
@ -747,7 +1039,7 @@ if __name__ == '__main__':
|
||||
time_format = parser.get('GPS_DATA', 'TIME_FORMAT')
|
||||
|
||||
# RSS feed link, shows in the link section of each RSS item.
|
||||
rss_link = parser.get('GPS_DATA', 'RSS_LINK')
|
||||
dashboard_url = parser.get('GPS_DATA', 'DASHBOARD_URL')
|
||||
|
||||
# Default APRS comment for users.
|
||||
default_comment = parser.get('GPS_DATA', 'USER_APRS_COMMENT')
|
||||
@ -759,6 +1051,35 @@ if __name__ == '__main__':
|
||||
emergency_sos_file = parser.get('GPS_DATA', 'EMERGENCY_SOS_FILE')
|
||||
the_mailbox_file = parser.get('GPS_DATA', 'MAILBOX_FILE')
|
||||
user_settings_file = parser.get('GPS_DATA', 'USER_SETTINGS_FILE')
|
||||
|
||||
auth_token_file = parser.get('GPS_DATA', 'AUTHORIZED_TOKENS_FILE')
|
||||
sms_file = parser.get('GPS_DATA', 'SMS_FILE')
|
||||
|
||||
use_api = parser.get('GPS_DATA', 'USE_API')
|
||||
#access_systems_file = parser.get('GPS_DATA', 'ACCESS_SYSTEMS_FILE')
|
||||
#authorized_users_file = parser.get('GPS_DATA', 'AUTHORIZED_USERS_FILE')
|
||||
|
||||
que_dir = '/tmp/.hblink_data_que_' + str(parser.get('GPS_DATA', 'APRS_LOGIN_CALL').upper()) + '/'
|
||||
#Only create if API enabled
|
||||
print(type(use_api))
|
||||
unit_sms_ts = parser.get('GPS_DATA', 'UNIT_SMS_TS')
|
||||
if use_api == 'True':
|
||||
use_api = True
|
||||
if use_api == 'False':
|
||||
use_api = False
|
||||
if use_api == True:
|
||||
generate_apps()
|
||||
if Path(auth_token_file).is_file():
|
||||
pass
|
||||
else:
|
||||
Path(auth_token_file).touch()
|
||||
with open(auth_token_file, 'w') as auth_token:
|
||||
auth_token.write("[]")
|
||||
auth_token.close()
|
||||
if unit_sms_ts == 2:
|
||||
unit_sms_ts = 1
|
||||
if unit_sms_ts == 1:
|
||||
unit_sms_ts = 0
|
||||
########################
|
||||
|
||||
app.run(debug = True, port=dash_port, host=dash_host)
|
||||
|
299
scripts/dashboard/send_sms.py
Normal file
299
scripts/dashboard/send_sms.py
Normal file
@ -0,0 +1,299 @@
|
||||
# Functions to encode DMR and MMDVM
|
||||
from dmr_utils3 import bptc, decode
|
||||
from bitarray import bitarray
|
||||
from binascii import b2a_hex as ahex
|
||||
from bitarray.util import hex2ba as hex2bits
|
||||
import random
|
||||
from dmr_utils3.utils import bytes_3, int_id, get_alias, bytes_2, bytes_4
|
||||
import re
|
||||
import libscrc
|
||||
from pathlib import Path
|
||||
|
||||
def create_crc16(fragment_input):
|
||||
crc16 = libscrc.gsm16(bytearray.fromhex(fragment_input))
|
||||
return fragment_input + re.sub('x', '0', str(hex(crc16 ^ 0xcccc))[-4:])
|
||||
|
||||
def create_crc32(fragment_input):
|
||||
# Create and append CRC32 to data
|
||||
# Create list of hex
|
||||
word_list = []
|
||||
count_index = 0
|
||||
while count_index < len(fragment_input):
|
||||
word_list.append((fragment_input[count_index:count_index + 2]))
|
||||
count_index = count_index + 2
|
||||
# Create string of rearranged word_list to match ETSI 102 361-1 pg 141
|
||||
lst_index = 0
|
||||
crc_string = ''
|
||||
for i in (word_list):
|
||||
#print(lst_index)
|
||||
if lst_index % 2 == 0:
|
||||
crc_string = crc_string + word_list[lst_index + 1]
|
||||
#print(crc_string)
|
||||
if lst_index % 2 == 1:
|
||||
crc_string = crc_string + word_list[lst_index - 1]
|
||||
#print(crc_string)
|
||||
lst_index = lst_index + 1
|
||||
# Create bytearray of word_list_string
|
||||
# print(crc_string)
|
||||
word_array = libscrc.posix(bytearray.fromhex(crc_string))
|
||||
# XOR to get almost final CRC
|
||||
pre_crc = str(hex(word_array ^ 0xffffffff))[2:]
|
||||
# Rearrange pre_crc for transmission
|
||||
crc = ''
|
||||
c = 8
|
||||
while c > 0:
|
||||
crc = crc + pre_crc[c-2:c]
|
||||
c = c - 2
|
||||
crc = crc.ljust(8, '0')
|
||||
print(crc)
|
||||
# Return original data and append CRC32
|
||||
print('Output: ' + fragment_input + crc)
|
||||
#print(len(crc.zfill(9)))
|
||||
return fragment_input + crc
|
||||
def create_crc16_csbk(fragment_input):
|
||||
crc16_csbk = libscrc.gsm16(bytearray.fromhex(fragment_input))
|
||||
return fragment_input + re.sub('x', '0', str(hex(crc16_csbk ^ 0xa5a5))[-4:])
|
||||
def csbk_gen(to_id, from_id):
|
||||
csbk_lst = ['BD00801a', 'BD008019', 'BD008018', 'BD008017', 'BD008016']
|
||||
|
||||
send_seq_list = ''
|
||||
for block in csbk_lst:
|
||||
block = block + to_id + from_id
|
||||
block = create_crc16_csbk(block)
|
||||
print(block)
|
||||
send_seq_list = send_seq_list + block
|
||||
print(send_seq_list)
|
||||
return send_seq_list
|
||||
def mmdvm_encapsulate(dst_id, src_id, peer_id, _seq, _slot, _call_type, _dtype_vseq, _stream_id, _dmr_data):
|
||||
signature = 'DMRD'
|
||||
# needs to be in bytes
|
||||
frame_type = 0x10 #bytes_2(int(10))
|
||||
#print((frame_type))
|
||||
dest_id = bytes_3(int(dst_id, 16))
|
||||
# print((dest_id))
|
||||
|
||||
#print(ahex(dest_id))
|
||||
source_id = bytes_3(int(src_id, 16))
|
||||
via_id = bytes_4(int(peer_id, 16))
|
||||
# print((source_id))
|
||||
#print(ahex(via_id))
|
||||
seq = int(_seq).to_bytes(1, 'big')
|
||||
#print(ahex(seq))
|
||||
# Binary, 0 for 1, 1 for 2
|
||||
slot = bitarray(str(_slot))
|
||||
#print(slot)
|
||||
# binary, 0 for group, 1 for unit, bin(1)
|
||||
# print(_call_type)
|
||||
call_type = bitarray(str(_call_type))
|
||||
#print(call_type)
|
||||
#0x00 for voice, 0x01 for voice sync, 0x10 for data
|
||||
#frame_type = int(16).to_bytes(1, 'big')
|
||||
frame_type = bitarray('10')
|
||||
#print(frame_type)
|
||||
# Observed to be always 7, int. Will be 6 for header
|
||||
#dtype_vseq = hex(int(_dtype_vseq)).encode()
|
||||
if _dtype_vseq == 6:
|
||||
dtype_vseq = bitarray('0110')
|
||||
if _dtype_vseq == 7:
|
||||
dtype_vseq = bitarray('0111')
|
||||
if _dtype_vseq == 3:
|
||||
dtype_vseq = bitarray('0011')
|
||||
# 9 digit integer in hex
|
||||
stream_id = bytes_4(_stream_id)
|
||||
#print(ahex(stream_id))
|
||||
|
||||
middle_guts = slot + call_type + frame_type + dtype_vseq
|
||||
#print(middle_guts)
|
||||
dmr_data = str(_dmr_data)[2:-1] #str(re.sub("b'|'", '', str(_dmr_data)))
|
||||
complete_packet = signature.encode() + seq + dest_id + source_id + via_id + middle_guts.tobytes() + stream_id + bytes.fromhex((dmr_data)) + bitarray('0000000000101111').tobytes()#bytes.fromhex(dmr_data)
|
||||
#print('Complete: ' + type(ahex(complete_packet)))
|
||||
## #print(hex2bits(ahex(complete_packet))[119:120])
|
||||
#print(bitarray.frombytes(ahex(complete_packet)))
|
||||
return complete_packet
|
||||
|
||||
|
||||
### Sequence MMDVM packets from encoded DMR
|
||||
##def seq_mmdvm(dmr_list):
|
||||
## cap_in = 0
|
||||
## mmdvm_send_seq = []
|
||||
## for i in dmr_list:
|
||||
## if cap_in < 8:
|
||||
##
|
||||
## if cap_in == 8:
|
||||
## #print('header')
|
||||
## the_mmdvm_pkt = mmdvm_encapsulate(3153597, 3153591, 9099, cap_in, 1, 1, 6, rand_seq, i) #(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
## else:
|
||||
## #print('block')
|
||||
## the_mmdvm_pkt = mmdvm_encapsulate(3153597, 3153591, 9099, cap_in, 1, 1, 7, rand_seq, i)#(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
## new_send_seq.append(ahex(the_mmdvm_pkt))
|
||||
## cap_in = cap_in + 1
|
||||
|
||||
# Break long string into block sequence
|
||||
def block_sequence(input_string):
|
||||
seq_blocks = len(input_string)/24
|
||||
n = 0
|
||||
block_seq = []
|
||||
while n < seq_blocks:
|
||||
if n == 0:
|
||||
block_seq.append(bytes.fromhex(input_string[:24].ljust(24,'0')))
|
||||
n = n + 1
|
||||
else:
|
||||
block_seq.append(bytes.fromhex(input_string[n*24:n*24+24].ljust(24,'0')))
|
||||
n = n + 1
|
||||
return block_seq
|
||||
|
||||
# Takes list of DMR packets, 12 bytes, then encodes them
|
||||
def dmr_encode(packet_list, _slot):
|
||||
send_seq = []
|
||||
for i in packet_list:
|
||||
stitched_pkt = bptc.interleave_19696(bptc.encode_19696(i))
|
||||
l_slot = bitarray('0111011100')
|
||||
#MS
|
||||
#sync_data = bitarray('110101011101011111110111011111111101011101010111')
|
||||
if _slot == 0:
|
||||
# TS1 - F7FDD5DDFD55
|
||||
sync_data = bitarray('111101111111110111010101110111011111110101010101')
|
||||
if _slot == 1:
|
||||
#TS2 - D7557F5FF7F5
|
||||
sync_data = bitarray('110101110101010101111111010111111111011111110101')
|
||||
# TS1
|
||||
#sync_data = bitarray('111101111111110111010101110111011111110101010101')
|
||||
#TS2
|
||||
#sync_data = bitarray('110101110101010101111111010111111111011111110101')
|
||||
r_slot = bitarray('1101110001')
|
||||
# Data sync? 110101011101011111110111011111111101011101010111 - D5D7F77FD757
|
||||
new_pkt = ahex(stitched_pkt[:98] + l_slot + sync_data + r_slot + stitched_pkt[98:])
|
||||
send_seq.append(new_pkt)
|
||||
return send_seq
|
||||
|
||||
|
||||
def create_sms_seq(dst_id, src_id, peer_id, _slot, _call_type, dmr_string, que_dir):
|
||||
rand_seq = random.randint(1, 999999)
|
||||
block_seq = block_sequence(dmr_string)
|
||||
dmr_list = dmr_encode(block_seq, _slot)
|
||||
cap_in = 0
|
||||
mmdvm_send_seq = []
|
||||
for i in dmr_list:
|
||||
#print(i)
|
||||
if use_csbk == True:
|
||||
if cap_in < 5:
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 3, rand_seq, i)
|
||||
#print(block_seq[cap_in])
|
||||
#print(3)
|
||||
if cap_in == 5:
|
||||
#print(block_seq[cap_in])
|
||||
#print(6)
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 6, rand_seq, i) #(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
if cap_in > 5:
|
||||
#print(block_seq[cap_in])
|
||||
#print(7)
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 7, rand_seq, i)#(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
mmdvm_send_seq.append(ahex(the_mmdvm_pkt))
|
||||
cap_in = cap_in + 1
|
||||
if use_csbk == False:
|
||||
if cap_in == 0:
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 6, rand_seq, i) #(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
else:
|
||||
the_mmdvm_pkt = mmdvm_encapsulate(dst_id, src_id, peer_id, cap_in, _slot, _call_type, 7, rand_seq, i)#(bytes.fromhex(re.sub("b'|'", '', str(orig_cap[cap_in][20:-4])))))
|
||||
mmdvm_send_seq.append(ahex(the_mmdvm_pkt))
|
||||
cap_in = cap_in + 1
|
||||
with open(que_dir + str(random.randint(1000, 9999)) + '.mmdvm_seq', "w") as packet_write_file:
|
||||
packet_write_file.write(str(mmdvm_send_seq))
|
||||
|
||||
return mmdvm_send_seq
|
||||
try:
|
||||
Path(que_dir).mkdir(parents=True, exist_ok=True)
|
||||
except:
|
||||
pass
|
||||
|
||||
# Built for max length msg
|
||||
def sms_headers(to_id, from_id):
|
||||
## #ETSI 102 361-2 uncompressed ipv4
|
||||
## # UDP header, src and dest ports are 4007, 0fa7
|
||||
## udp_ports = '0fa70fa7'
|
||||
## # Length, of what?
|
||||
## udp_length = '00da'
|
||||
## # Checksum
|
||||
## udp_checksum = '4b37'
|
||||
##
|
||||
## # IPV4
|
||||
## #IPV4 version and header length, always 45
|
||||
## ipv4_v_l = '45'
|
||||
## #Type of service, always 00
|
||||
## ipv4_svc = '00'
|
||||
## #length, always 00ee
|
||||
## ipv4_len = '00ee'
|
||||
## #ID always 000d
|
||||
## ipv4_id = '000d'
|
||||
## #Flags and offset always0
|
||||
## ipv4_flag_off = '0000'
|
||||
## #TTL and Protocol always 4011, no matter what
|
||||
## ipv4_ttl_proto = '4011'
|
||||
#ipv4 = '450000ee000d0000401100000c' + from_id + '0c' + to_id
|
||||
#ipv4 = '450000ee00000000401100000c' + from_id + '0c' + to_id
|
||||
ipv4 = '450000ee00000000401100000c' + from_id + '0c' + to_id
|
||||
print(from_id)
|
||||
print(to_id)
|
||||
count_index = 0
|
||||
hdr_lst = []
|
||||
while count_index < len(ipv4):
|
||||
hdr_lst.append((ipv4[count_index:count_index + 4]))
|
||||
count_index = count_index + 4
|
||||
sum = 0
|
||||
for i in hdr_lst:
|
||||
sum = sum + int(i, 16)
|
||||
flipped = ''
|
||||
for i in str(bin(sum))[2:]:
|
||||
if i == '1':
|
||||
flipped = flipped + '0'
|
||||
if i == '0':
|
||||
flipped = flipped + '1'
|
||||
ipv4_chk_sum = str(hex(int(flipped, 2)))[2:]
|
||||
print(ipv4_chk_sum)
|
||||
header = ipv4[:20] + ipv4_chk_sum + ipv4[24:] + '0fa70fa700da583100d0a00081040d000a'
|
||||
return header
|
||||
|
||||
def format_sms(msg, to_id, from_id):
|
||||
msg_bytes = str.encode(msg)
|
||||
encoded = "".join([str('00' + x) for x in re.findall('..',bytes.hex(msg_bytes))] )
|
||||
final = encoded
|
||||
while len(final) < 400:
|
||||
final = final + '002e'
|
||||
final = final + '0000000000000000000000'
|
||||
headers = sms_headers(to_id, from_id)
|
||||
return headers + final
|
||||
|
||||
def gen_header(to_id, from_id, call_type):
|
||||
#print(call_type)
|
||||
if call_type == 1:
|
||||
seq_header = '024A' + to_id + from_id + '9550'
|
||||
if call_type == 0:
|
||||
seq_header = '824A' + to_id + from_id + '9550'
|
||||
return seq_header
|
||||
|
||||
def send_sms(csbk, to_id, from_id, peer_id, call_type, slot, msg, que_dir):
|
||||
global use_csbk
|
||||
#to_id = str(hex(to_id))[2:].zfill(6)
|
||||
#from_id = str(hex(from_id))[2:].zfill(6)
|
||||
to_id = str(hex(to_id))[2:].zfill(6)
|
||||
from_id = str(hex(from_id))[2:].zfill(6)
|
||||
peer_id = str(hex(peer_id))[2:].zfill(8)
|
||||
# Weird fix for redio not decoding, will fix later
|
||||
if len(str(int(from_id, 16))) >= 4 and len(str(int(from_id, 16))) <= 6:
|
||||
from_id = str('000000')
|
||||
if call_type == 'unit':
|
||||
new_call_type = 1
|
||||
if call_type == 'group':
|
||||
new_call_type = 0
|
||||
if csbk == 'yes':
|
||||
use_csbk = True
|
||||
create_sms_seq(to_id, from_id, peer_id, int(slot), new_call_type, csbk_gen(to_id, from_id) + create_crc16(gen_header(to_id, from_id, new_call_type)) + create_crc32(format_sms(msg, to_id, from_id)), que_dir)
|
||||
else:
|
||||
use_csbk = False
|
||||
create_sms_seq(to_id, from_id, peer_id, int(slot), new_call_type, create_crc16(gen_header(to_id, from_id, new_call_type)) + create_crc32(format_sms(msg, to_id, from_id)), que_dir)
|
||||
print('Call type: ' + call_type)
|
||||
print('Destination: ' + str(to_id))
|
||||
print('Source: ' + str(from_id))
|
||||
print('Message: ' + msg)
|
||||
print('Use CSBK: ' + str(use_csbk))
|
||||
print('Slot: ' + str(int(slot)))
|
@ -7,7 +7,7 @@
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><strong>Name</strong></td>
|
||||
<td>{{contact_name}} </td>
|
||||
<td> {{contact_name}} </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Callsign</strong></td>
|
||||
|
@ -1,5 +1,5 @@
|
||||
<div>
|
||||
<hr />
|
||||
<div style="text-align: center;">Dashboard created by KF7EEL - <a href="https://kf7eel.github.io/hblink3/">https://github.com/kf7eel/hblink3</a><br />HBLink created by N0MJS.<br /><a href="https://github.com/HBLink-org">HBLink GitHub page</a><br />This is branch: <strong>gps<strong></div>
|
||||
</body>
|
||||
<div style="text-align: center;">Dashboard created by KF7EEL - <a href="https://kf7eel.github.io/hblink3/">https://github.com/kf7eel/hblink3</a><br />HBLink created by N0MJS.<br /><a href="https://github.com/HBLink-org">HBLink GitHub page</a><br />This is branch: <strong>sms_dev</strong></div>
|
||||
<div style="text-align: center;"><strong>$Id$</strong></div></body>
|
||||
</html>
|
||||
|
@ -4,12 +4,16 @@
|
||||
<table style="width: 500px; margin-left: auto; margin-right: auto;" border="black" cellspacing="3" cellpadding="3">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='/';"> Dashboard Home </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='/map';"> Station Map </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='/mailbox';"> The Mailbox </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='/user';"> User Settings </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='/help';"> Dashboard Help </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='/about';"> Gateway Contact </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='{{dashboard_url}}/';"> Dashboard Home </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='{{dashboard_url}}/map';"> Station Map </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='{{dashboard_url}}/mailbox';"> The Mailbox </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='{{dashboard_url}}/sms';"> SMS Capture </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='{{dashboard_url}}/user';"> User Settings </button></td>
|
||||
{% if api %}
|
||||
<td style="text-align: center;"><button onclick="window.location.href='{{dashboard_url}}/external_apps';"> External Applications </button></td>
|
||||
{% endif %}
|
||||
<td style="text-align: center;"><button onclick="window.location.href='{{dashboard_url}}/help';"> Dashboard Help </button></td>
|
||||
<td style="text-align: center;"><button onclick="window.location.href='{{dashboard_url}}/about';"> Gateway Contact </button></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
@ -66,39 +66,39 @@
|
||||
<td><em><code>@BB This is a test bulletin.</code></em></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>@[CALLSIGN W/ SSID] A-[MESSAGE]</strong></td>
|
||||
<td><strong>@[CALLSIGN W/ SSID] [MESSAGE]</strong></td>
|
||||
<td>Send a message to another station via APRS.</td>
|
||||
<td><em><code>@N0CALL-15 A-This is a test.</code></em></td>
|
||||
<td><em><code>@N0CALL-15 This is a test.</code></em></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>[EMAIL ADDRESS] E-[MESSAGE]</strong></td>
|
||||
<td><strong>[EMAIL ADDRESS] [MESSAGE]</strong></td>
|
||||
<td>Send an email to an email address.</td>
|
||||
<td><em><code>test@example.org E-This is a test.</code></em></td>
|
||||
<td><em><code>test@example.org This is a test.</code></em></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>@[RECIPIENT CALLSIGN] M-[MESSAGE]</strong></td>
|
||||
<td>Post a message to the Mailbox.</td>
|
||||
<td><em>@N0CALL M-This is a test.</em></td>
|
||||
<td><em><code>@N0CALL M-This is a test.</code></em></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>@REM MAIL</strong></td>
|
||||
<td>Remove all mail addressed to you.</td>
|
||||
<td><em>@REM MAIL</em></td>
|
||||
<td><em><code>@REM MAIL</code></em></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>@SOS</strong></td>
|
||||
<td>EMERGENCY activation displays a banner on the main dashboard page.</td>
|
||||
<td><em>THIS IS AN EMERGENCY. @SOS</em></td>
|
||||
<td><em><code>THIS IS AN EMERGENCY. @SOS</code></em></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>@NOTICE</strong></td>
|
||||
<td>Used to prominantly display a notice, similar to EMERGENCY activation.</td>
|
||||
<td><em>@NOTICE Server going down at 1800</em></td>
|
||||
<td><em><code>@NOTICE Server going down at 1800</code></em></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>@REM SOS</strong></td>
|
||||
<td>Removes an EMERGENCY or notice.</td>
|
||||
<td><em>@REM SOS</em></td>
|
||||
<td><em><code>@REM SOS</code></em></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
@ -2,7 +2,7 @@
|
||||
{% include 'header.html' %}
|
||||
<p style="text-align: center;"><span style="color: #ff0000;"><strong>Red</strong></span>: Last location received. <span style="color: #0000ff;"><strong>Blue</strong></span>: Location history.</p>
|
||||
<p style="text-align: center;"> </p>
|
||||
<div><p align="center"><iframe style="border: none;" title="Map" src="/view_map?track=" width="1100" height="700"></iframe></p></div>
|
||||
<div><p align="center"><iframe style="border: none;" title="Map" src="{{dashboard_url}}/view_map?track=" width="1100" height="700"></iframe></p></div>
|
||||
<p> </p>
|
||||
{% include 'footer.html' %}
|
||||
|
||||
|
390
sms_aprs_config.py
Executable file
390
sms_aprs_config.py
Executable file
@ -0,0 +1,390 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
###############################################################################
|
||||
# Copyright (C) 2016-2018 Cortney T. Buffington, N0MJS <n0mjs@me.com>
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software Foundation,
|
||||
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
###############################################################################
|
||||
|
||||
'''
|
||||
This module generates the configuration data structure for hblink.py and
|
||||
assoicated programs that use it. It has been seaparated into a different
|
||||
module so as to keep hblink.py easeier to navigate. This file only needs
|
||||
updated if the items in the main configuraiton file (usually hblink.cfg)
|
||||
change.
|
||||
'''
|
||||
|
||||
import configparser
|
||||
import sys
|
||||
import const
|
||||
|
||||
from socket import gethostbyname
|
||||
|
||||
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
|
||||
__author__ = 'Cortney T. Buffington, N0MJS'
|
||||
__copyright__ = 'Copyright (c) 2016-2018 Cortney T. Buffington, N0MJS and the K0USY Group'
|
||||
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
|
||||
__license__ = 'GNU GPLv3'
|
||||
__maintainer__ = 'Cort Buffington, N0MJS'
|
||||
__email__ = 'n0mjs@me.com'
|
||||
|
||||
# Processing of ALS goes here. It's separated from the acl_build function because this
|
||||
# code is hblink config-file format specific, and acl_build is abstracted
|
||||
def process_acls(_config):
|
||||
# Global registration ACL
|
||||
_config['GLOBAL']['REG_ACL'] = acl_build(_config['GLOBAL']['REG_ACL'], const.PEER_MAX)
|
||||
|
||||
# Global subscriber and TGID ACLs
|
||||
for acl in ['SUB_ACL', 'TG1_ACL', 'TG2_ACL']:
|
||||
_config['GLOBAL'][acl] = acl_build(_config['GLOBAL'][acl], const.ID_MAX)
|
||||
|
||||
# System level ACLs
|
||||
for system in _config['SYSTEMS']:
|
||||
# Registration ACLs (which make no sense for peer systems)
|
||||
if _config['SYSTEMS'][system]['MODE'] == 'MASTER' or _config['SYSTEMS'][system]['MODE'] == 'PROXY':
|
||||
_config['SYSTEMS'][system]['REG_ACL'] = acl_build(_config['SYSTEMS'][system]['REG_ACL'], const.PEER_MAX)
|
||||
|
||||
# Subscriber and TGID ACLs (valid for all system types)
|
||||
for acl in ['SUB_ACL', 'TG1_ACL', 'TG2_ACL']:
|
||||
_config['SYSTEMS'][system][acl] = acl_build(_config['SYSTEMS'][system][acl], const.ID_MAX)
|
||||
|
||||
# Create an access control list that is programatically useable from human readable:
|
||||
# ORIGINAL: 'DENY:1-5,3120101,3120124'
|
||||
# PROCESSED: (False, set([(1, 5), (3120124, 3120124), (3120101, 3120101)]))
|
||||
def acl_build(_acl, _max):
|
||||
#print(_max)
|
||||
if not _acl:
|
||||
return(True, set((const.ID_MIN, _max)))
|
||||
|
||||
acl = [] #set()
|
||||
sections = _acl.split(':')
|
||||
|
||||
if sections[0] == 'PERMIT':
|
||||
action = True
|
||||
else:
|
||||
action = False
|
||||
|
||||
for entry in sections[1].split(','):
|
||||
if entry == 'ALL':
|
||||
acl.append((const.ID_MIN, _max))
|
||||
break
|
||||
|
||||
elif '-' in entry:
|
||||
start,end = entry.split('-')
|
||||
start,end = int(start), int(end)
|
||||
if (const.ID_MIN <= start <= _max) or (const.ID_MIN <= end <= _max):
|
||||
acl.append((start, end))
|
||||
else:
|
||||
sys.exit('ACL CREATION ERROR, VALUE OUT OF RANGE ({} - {})IN RANGE-BASED ENTRY: {}'.format(const.ID_MIN, _max, entry))
|
||||
else:
|
||||
id = int(entry)
|
||||
if (const.ID_MIN <= id <= _max):
|
||||
acl.append((id, id))
|
||||
else:
|
||||
sys.exit('ACL CREATION ERROR, VALUE OUT OF RANGE ({} - {}) IN SINGLE ID ENTRY: {}'.format(const.ID_MIN, _max, entry))
|
||||
|
||||
return (action, acl)
|
||||
|
||||
def build_config(_config_file):
|
||||
config = configparser.ConfigParser()
|
||||
|
||||
if not config.read(_config_file):
|
||||
sys.exit('Configuration file \''+_config_file+'\' is not a valid configuration file! Exiting...')
|
||||
|
||||
CONFIG = {}
|
||||
CONFIG['GLOBAL'] = {}
|
||||
CONFIG['REPORTS'] = {}
|
||||
CONFIG['LOGGER'] = {}
|
||||
CONFIG['GPS_DATA'] = {}
|
||||
CONFIG['ALIASES'] = {}
|
||||
CONFIG['SYSTEMS'] = {}
|
||||
|
||||
try:
|
||||
for section in config.sections():
|
||||
if section == 'GLOBAL':
|
||||
CONFIG['GLOBAL'].update({
|
||||
'PATH': config.get(section, 'PATH'),
|
||||
'PING_TIME': config.getint(section, 'PING_TIME'),
|
||||
'MAX_MISSED': config.getint(section, 'MAX_MISSED'),
|
||||
'USE_ACL': config.get(section, 'USE_ACL'),
|
||||
'REG_ACL': config.get(section, 'REG_ACL'),
|
||||
'SUB_ACL': config.get(section, 'SUB_ACL'),
|
||||
'TG1_ACL': config.get(section, 'TGID_TS1_ACL'),
|
||||
'TG2_ACL': config.get(section, 'TGID_TS2_ACL')
|
||||
})
|
||||
|
||||
elif section == 'REPORTS':
|
||||
CONFIG['REPORTS'].update({
|
||||
'REPORT': config.getboolean(section, 'REPORT'),
|
||||
'REPORT_INTERVAL': config.getint(section, 'REPORT_INTERVAL'),
|
||||
'REPORT_PORT': config.getint(section, 'REPORT_PORT'),
|
||||
'REPORT_CLIENTS': config.get(section, 'REPORT_CLIENTS').split(',')
|
||||
})
|
||||
|
||||
elif section == 'LOGGER':
|
||||
CONFIG['LOGGER'].update({
|
||||
'LOG_FILE': config.get(section, 'LOG_FILE'),
|
||||
'LOG_HANDLERS': config.get(section, 'LOG_HANDLERS'),
|
||||
'LOG_LEVEL': config.get(section, 'LOG_LEVEL'),
|
||||
'LOG_NAME': config.get(section, 'LOG_NAME')
|
||||
})
|
||||
if not CONFIG['LOGGER']['LOG_FILE']:
|
||||
CONFIG['LOGGER']['LOG_FILE'] = '/dev/null'
|
||||
|
||||
elif section == 'GPS_DATA':
|
||||
CONFIG['GPS_DATA'].update({
|
||||
'DATA_DMR_ID': config.get(section, 'DATA_DMR_ID'),
|
||||
'USER_APRS_SSID': config.get(section, 'USER_APRS_SSID'),
|
||||
'CALL_TYPE': config.get(section, 'CALL_TYPE'),
|
||||
'UNIT_SMS_TS': config.get(section, 'UNIT_SMS_TS'),
|
||||
'USER_APRS_COMMENT': config.get(section, 'USER_APRS_COMMENT'),
|
||||
'APRS_LOGIN_CALL': config.get(section, 'APRS_LOGIN_CALL'),
|
||||
'APRS_LOGIN_PASSCODE': config.get(section, 'APRS_LOGIN_PASSCODE'),
|
||||
'APRS_SERVER': config.get(section, 'APRS_SERVER'),
|
||||
'APRS_PORT': config.get(section, 'APRS_PORT'),
|
||||
'APRS_FILTER': config.get(section, 'APRS_FILTER'),
|
||||
'IGATE_BEACON_TIME': config.get(section, 'IGATE_BEACON_TIME'),
|
||||
'IGATE_BEACON_ICON': config.get(section, 'IGATE_BEACON_ICON'),
|
||||
'IGATE_BEACON_COMMENT': config.get(section, 'IGATE_BEACON_COMMENT'),
|
||||
'IGATE_LATITUDE': config.get(section, 'IGATE_LATITUDE'),
|
||||
'IGATE_LONGITUDE': config.get(section, 'IGATE_LONGITUDE'),
|
||||
'APRS_STATIC_REPORT_INTERVAL': config.get(section, 'APRS_STATIC_REPORT_INTERVAL'),
|
||||
'APRS_STATIC_MESSAGE': config.get(section, 'APRS_STATIC_MESSAGE'),
|
||||
'EMAIL_SENDER': config.get(section, 'EMAIL_SENDER'),
|
||||
'EMAIL_PASSWORD': config.get(section, 'EMAIL_PASSWORD'),
|
||||
'SMTP_SERVER': config.get(section, 'SMTP_SERVER'),
|
||||
'SMTP_PORT': config.get(section, 'SMTP_PORT'),
|
||||
'LOCATION_FILE': config.get(section, 'LOCATION_FILE'),
|
||||
'BULLETIN_BOARD_FILE': config.get(section, 'BULLETIN_BOARD_FILE'),
|
||||
'MAILBOX_FILE': config.get(section, 'MAILBOX_FILE'),
|
||||
'SMS_FILE': config.get(section, 'SMS_FILE'),
|
||||
'EMERGENCY_SOS_FILE': config.get(section, 'EMERGENCY_SOS_FILE'),
|
||||
'USER_SETTINGS_FILE': config.get(section, 'USER_SETTINGS_FILE'),
|
||||
'USE_API': config.getboolean(section, 'USE_API'),
|
||||
'AUTHORIZED_TOKENS_FILE': config.get(section, 'AUTHORIZED_TOKENS_FILE'),
|
||||
'USE_PUBLIC_APPS': config.getboolean(section, 'USE_PUBLIC_APPS'),
|
||||
'PUBLIC_APPS_LIST': config.get(section, 'PUBLIC_APPS_LIST'),
|
||||
'MY_SERVER_SHORTCUT': config.get(section, 'MY_SERVER_SHORTCUT'),
|
||||
'DASHBOARD_URL': config.get(section, 'DASHBOARD_URL'),
|
||||
'SERVER_NAME': config.get(section, 'SERVER_NAME'),
|
||||
'RULES_PATH': config.get(section, 'RULES_PATH'),
|
||||
|
||||
|
||||
})
|
||||
if not CONFIG['LOGGER']['LOG_FILE']:
|
||||
CONFIG['LOGGER']['LOG_FILE'] = '/dev/null'
|
||||
|
||||
elif section == 'ALIASES':
|
||||
CONFIG['ALIASES'].update({
|
||||
'TRY_DOWNLOAD': config.getboolean(section, 'TRY_DOWNLOAD'),
|
||||
'PATH': config.get(section, 'PATH'),
|
||||
'PEER_FILE': config.get(section, 'PEER_FILE'),
|
||||
'SUBSCRIBER_FILE': config.get(section, 'SUBSCRIBER_FILE'),
|
||||
'TGID_FILE': config.get(section, 'TGID_FILE'),
|
||||
'PEER_URL': config.get(section, 'PEER_URL'),
|
||||
'SUBSCRIBER_URL': config.get(section, 'SUBSCRIBER_URL'),
|
||||
'STALE_TIME': config.getint(section, 'STALE_DAYS') * 86400,
|
||||
})
|
||||
|
||||
elif config.getboolean(section, 'ENABLED'):
|
||||
if config.get(section, 'MODE') == 'PEER':
|
||||
CONFIG['SYSTEMS'].update({section: {
|
||||
'MODE': config.get(section, 'MODE'),
|
||||
'ENABLED': config.getboolean(section, 'ENABLED'),
|
||||
'LOOSE': config.getboolean(section, 'LOOSE'),
|
||||
'SOCK_ADDR': (gethostbyname(config.get(section, 'IP')), config.getint(section, 'PORT')),
|
||||
'IP': gethostbyname(config.get(section, 'IP')),
|
||||
'PORT': config.getint(section, 'PORT'),
|
||||
'MASTER_SOCKADDR': (gethostbyname(config.get(section, 'MASTER_IP')), config.getint(section, 'MASTER_PORT')),
|
||||
'MASTER_IP': gethostbyname(config.get(section, 'MASTER_IP')),
|
||||
'MASTER_PORT': config.getint(section, 'MASTER_PORT'),
|
||||
'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE'), 'utf-8'),
|
||||
'CALLSIGN': bytes(config.get(section, 'CALLSIGN').ljust(8)[:8], 'utf-8'),
|
||||
'RADIO_ID': config.getint(section, 'RADIO_ID').to_bytes(4, 'big'),
|
||||
'RX_FREQ': bytes(config.get(section, 'RX_FREQ').ljust(9)[:9], 'utf-8'),
|
||||
'TX_FREQ': bytes(config.get(section, 'TX_FREQ').ljust(9)[:9], 'utf-8'),
|
||||
'TX_POWER': bytes(config.get(section, 'TX_POWER').rjust(2,'0'), 'utf-8'),
|
||||
'COLORCODE': bytes(config.get(section, 'COLORCODE').rjust(2,'0'), 'utf-8'),
|
||||
'LATITUDE': bytes(config.get(section, 'LATITUDE').ljust(8)[:8], 'utf-8'),
|
||||
'LONGITUDE': bytes(config.get(section, 'LONGITUDE').ljust(9)[:9], 'utf-8'),
|
||||
'HEIGHT': bytes(config.get(section, 'HEIGHT').rjust(3,'0'), 'utf-8'),
|
||||
'LOCATION': bytes(config.get(section, 'LOCATION').ljust(20)[:20], 'utf-8'),
|
||||
'DESCRIPTION': bytes(config.get(section, 'DESCRIPTION').ljust(19)[:19], 'utf-8'),
|
||||
'SLOTS': bytes(config.get(section, 'SLOTS'), 'utf-8'),
|
||||
'URL': bytes(config.get(section, 'URL').ljust(124)[:124], 'utf-8'),
|
||||
'SOFTWARE_ID': bytes(config.get(section, 'SOFTWARE_ID').ljust(40)[:40], 'utf-8'),
|
||||
'PACKAGE_ID': bytes(config.get(section, 'PACKAGE_ID').ljust(40)[:40], 'utf-8'),
|
||||
'GROUP_HANGTIME': config.getint(section, 'GROUP_HANGTIME'),
|
||||
'OPTIONS': bytes(config.get(section, 'OPTIONS'), 'utf-8'),
|
||||
'USE_ACL': config.getboolean(section, 'USE_ACL'),
|
||||
'SUB_ACL': config.get(section, 'SUB_ACL'),
|
||||
'TG1_ACL': config.get(section, 'TGID_TS1_ACL'),
|
||||
'TG2_ACL': config.get(section, 'TGID_TS2_ACL')
|
||||
}})
|
||||
CONFIG['SYSTEMS'][section].update({'STATS': {
|
||||
'CONNECTION': 'NO', # NO, RTPL_SENT, AUTHENTICATED, CONFIG-SENT, YES
|
||||
'CONNECTED': None,
|
||||
'PINGS_SENT': 0,
|
||||
'PINGS_ACKD': 0,
|
||||
'NUM_OUTSTANDING': 0,
|
||||
'PING_OUTSTANDING': False,
|
||||
'LAST_PING_TX_TIME': 0,
|
||||
'LAST_PING_ACK_TIME': 0,
|
||||
}})
|
||||
|
||||
if config.get(section, 'MODE') == 'XLXPEER':
|
||||
CONFIG['SYSTEMS'].update({section: {
|
||||
'MODE': config.get(section, 'MODE'),
|
||||
'ENABLED': config.getboolean(section, 'ENABLED'),
|
||||
'LOOSE': config.getboolean(section, 'LOOSE'),
|
||||
'SOCK_ADDR': (gethostbyname(config.get(section, 'IP')), config.getint(section, 'PORT')),
|
||||
'IP': gethostbyname(config.get(section, 'IP')),
|
||||
'PORT': config.getint(section, 'PORT'),
|
||||
'MASTER_SOCKADDR': (gethostbyname(config.get(section, 'MASTER_IP')), config.getint(section, 'MASTER_PORT')),
|
||||
'MASTER_IP': gethostbyname(config.get(section, 'MASTER_IP')),
|
||||
'MASTER_PORT': config.getint(section, 'MASTER_PORT'),
|
||||
'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE'), 'utf-8'),
|
||||
'CALLSIGN': bytes(config.get(section, 'CALLSIGN').ljust(8)[:8], 'utf-8'),
|
||||
'RADIO_ID': config.getint(section, 'RADIO_ID').to_bytes(4, 'big'),
|
||||
'RX_FREQ': bytes(config.get(section, 'RX_FREQ').ljust(9)[:9], 'utf-8'),
|
||||
'TX_FREQ': bytes(config.get(section, 'TX_FREQ').ljust(9)[:9], 'utf-8'),
|
||||
'TX_POWER': bytes(config.get(section, 'TX_POWER').rjust(2,'0'), 'utf-8'),
|
||||
'COLORCODE': bytes(config.get(section, 'COLORCODE').rjust(2,'0'), 'utf-8'),
|
||||
'LATITUDE': bytes(config.get(section, 'LATITUDE').ljust(8)[:8], 'utf-8'),
|
||||
'LONGITUDE': bytes(config.get(section, 'LONGITUDE').ljust(9)[:9], 'utf-8'),
|
||||
'HEIGHT': bytes(config.get(section, 'HEIGHT').rjust(3,'0'), 'utf-8'),
|
||||
'LOCATION': bytes(config.get(section, 'LOCATION').ljust(20)[:20], 'utf-8'),
|
||||
'DESCRIPTION': bytes(config.get(section, 'DESCRIPTION').ljust(19)[:19], 'utf-8'),
|
||||
'SLOTS': bytes(config.get(section, 'SLOTS'), 'utf-8'),
|
||||
'URL': bytes(config.get(section, 'URL').ljust(124)[:124], 'utf-8'),
|
||||
'SOFTWARE_ID': bytes(config.get(section, 'SOFTWARE_ID').ljust(40)[:40], 'utf-8'),
|
||||
'PACKAGE_ID': bytes(config.get(section, 'PACKAGE_ID').ljust(40)[:40], 'utf-8'),
|
||||
'GROUP_HANGTIME': config.getint(section, 'GROUP_HANGTIME'),
|
||||
'XLXMODULE': config.getint(section, 'XLXMODULE'),
|
||||
'OPTIONS': '',
|
||||
'USE_ACL': config.getboolean(section, 'USE_ACL'),
|
||||
'SUB_ACL': config.get(section, 'SUB_ACL'),
|
||||
'TG1_ACL': config.get(section, 'TGID_TS1_ACL'),
|
||||
'TG2_ACL': config.get(section, 'TGID_TS2_ACL')
|
||||
}})
|
||||
CONFIG['SYSTEMS'][section].update({'XLXSTATS': {
|
||||
'CONNECTION': 'NO', # NO, RTPL_SENT, AUTHENTICATED, CONFIG-SENT, YES
|
||||
'CONNECTED': None,
|
||||
'PINGS_SENT': 0,
|
||||
'PINGS_ACKD': 0,
|
||||
'NUM_OUTSTANDING': 0,
|
||||
'PING_OUTSTANDING': False,
|
||||
'LAST_PING_TX_TIME': 0,
|
||||
'LAST_PING_ACK_TIME': 0,
|
||||
}})
|
||||
|
||||
elif config.get(section, 'MODE') == 'MASTER':
|
||||
CONFIG['SYSTEMS'].update({section: {
|
||||
'MODE': config.get(section, 'MODE'),
|
||||
'ENABLED': config.getboolean(section, 'ENABLED'),
|
||||
'STATIC_APRS_POSITION_ENABLED': config.getboolean(section, 'STATIC_APRS_POSITION_ENABLED'),
|
||||
'REPEAT': config.getboolean(section, 'REPEAT'),
|
||||
'MAX_PEERS': config.getint(section, 'MAX_PEERS'),
|
||||
'IP': gethostbyname(config.get(section, 'IP')),
|
||||
'PORT': config.getint(section, 'PORT'),
|
||||
'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE'), 'utf-8'),
|
||||
'GROUP_HANGTIME': config.getint(section, 'GROUP_HANGTIME'),
|
||||
'USE_ACL': config.getboolean(section, 'USE_ACL'),
|
||||
'REG_ACL': config.get(section, 'REG_ACL'),
|
||||
'SUB_ACL': config.get(section, 'SUB_ACL'),
|
||||
'TG1_ACL': config.get(section, 'TGID_TS1_ACL'),
|
||||
'TG2_ACL': config.get(section, 'TGID_TS2_ACL')
|
||||
}})
|
||||
CONFIG['SYSTEMS'][section].update({'PEERS': {}})
|
||||
|
||||
elif config.get(section, 'MODE') == 'PROXY':
|
||||
CONFIG['SYSTEMS'].update({section: {
|
||||
'MODE': config.get(section, 'MODE'),
|
||||
'ENABLED': config.getboolean(section, 'ENABLED'),
|
||||
'EXTERNAL_PROXY_SCRIPT': config.getboolean(section, 'EXTERNAL_PROXY_SCRIPT'),
|
||||
'STATIC_APRS_POSITION_ENABLED': config.getboolean(section, 'STATIC_APRS_POSITION_ENABLED'),
|
||||
'REPEAT': config.getboolean(section, 'REPEAT'),
|
||||
'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE'), 'utf-8'),
|
||||
'EXTERNAL_PORT': config.getint(section, 'EXTERNAL_PORT'),
|
||||
'INTERNAL_PORT_START': config.getint(section, 'INTERNAL_PORT_START'),
|
||||
'INTERNAL_PORT_STOP': config.getint(section, 'INTERNAL_PORT_STOP'),
|
||||
'GROUP_HANGTIME': config.getint(section, 'GROUP_HANGTIME'),
|
||||
'USE_ACL': config.getboolean(section, 'USE_ACL'),
|
||||
'REG_ACL': config.get(section, 'REG_ACL'),
|
||||
'SUB_ACL': config.get(section, 'SUB_ACL'),
|
||||
'TG1_ACL': config.get(section, 'TG1_ACL'),
|
||||
'TG2_ACL': config.get(section, 'TG2_ACL')
|
||||
}})
|
||||
CONFIG['SYSTEMS'][section].update({'PEERS': {}})
|
||||
|
||||
elif config.get(section, 'MODE') == 'OPENBRIDGE':
|
||||
CONFIG['SYSTEMS'].update({section: {
|
||||
'MODE': config.get(section, 'MODE'),
|
||||
'ENABLED': config.getboolean(section, 'ENABLED'),
|
||||
'NETWORK_ID': config.getint(section, 'NETWORK_ID').to_bytes(4, 'big'),
|
||||
'IP': gethostbyname(config.get(section, 'IP')),
|
||||
'PORT': config.getint(section, 'PORT'),
|
||||
'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE').ljust(20,'\x00')[:20], 'utf-8'),
|
||||
'TARGET_SOCK': (gethostbyname(config.get(section, 'TARGET_IP')), config.getint(section, 'TARGET_PORT')),
|
||||
'TARGET_IP': gethostbyname(config.get(section, 'TARGET_IP')),
|
||||
'TARGET_PORT': config.getint(section, 'TARGET_PORT'),
|
||||
'BOTH_SLOTS': config.getboolean(section, 'BOTH_SLOTS'),
|
||||
'USE_ACL': config.getboolean(section, 'USE_ACL'),
|
||||
'SUB_ACL': config.get(section, 'SUB_ACL'),
|
||||
'TG1_ACL': config.get(section, 'TGID_ACL'),
|
||||
'TG2_ACL': 'PERMIT:ALL'
|
||||
}})
|
||||
|
||||
|
||||
except configparser.Error as err:
|
||||
sys.exit('Error processing configuration file -- {}'.format(err))
|
||||
|
||||
process_acls(CONFIG)
|
||||
|
||||
return CONFIG
|
||||
|
||||
# Used to run this file direclty and print the config,
|
||||
# which might be useful for debugging
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
import os
|
||||
import argparse
|
||||
from pprint import pprint
|
||||
from dmr_utils3.utils import int_id
|
||||
|
||||
# Change the current directory to the location of the application
|
||||
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
|
||||
|
||||
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually hblink.cfg)')
|
||||
cli_args = parser.parse_args()
|
||||
|
||||
|
||||
# Ensure we have a path for the config file, if one wasn't specified, then use the execution directory
|
||||
if not cli_args.CONFIG_FILE:
|
||||
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/hblink.cfg'
|
||||
|
||||
CONFIG = build_config(cli_args.CONFIG_FILE)
|
||||
pprint(CONFIG)
|
||||
|
||||
def acl_check(_id, _acl):
|
||||
id = int_id(_id)
|
||||
for entry in _acl[1]:
|
||||
if entry[0] <= id <= entry[1]:
|
||||
return _acl[0]
|
||||
return not _acl[0]
|
||||
|
||||
print(acl_check(b'\x00\x01\x37', CONFIG['GLOBAL']['TG1_ACL']))
|
Loading…
Reference in New Issue
Block a user