1
0
mirror of https://github.com/craigerl/aprsd.git synced 2026-08-16 16:43:52 -04:00

Compare commits

..

98 Commits

Author SHA1 Message Date
hemna 658e6b6202 Updated Changelog for v1.5.1 2021-01-15 13:35:04 -05:00
hemna 98e3c246ad Updated README to fix pypi page
This patch updates the README to fix the overview image for
pypi.  This patch also updates the makefile to force broken
tox -p commands
2021-01-15 13:35:04 -05:00
Craig Lamparter 47ccce53ea Update INSTALL.txt 2021-01-15 09:36:30 -08:00
hemna 33a0e6c18d Updated Changelog for v1.5.0 release 2021-01-15 12:12:41 -05:00
hemna 278e258648 Merge pull request #33 from craigerl/craiger-stable
add null reply for send_email
2021-01-15 12:09:55 -05:00
hemna 0e9cfdd847 Fix tox tests. 2021-01-15 12:06:09 -05:00
Craig Lamparter f538fb26ae fix usage statement 2021-01-15 08:51:12 -08:00
hemna d81bfd6fd5 Enabled some emailthread messages and added timestamp
This patch re-enables some log.debug messages for email, to ensure
we can see emailthread is running correctly.  Also adds a timestamp
to the query pending messages, so radios don't think it's a duplicate
message.
2021-01-15 11:12:43 -05:00
hemna 7486770bdc Fixed main server client initialization
This fixes the usage of the singleton client class which
houses/creates the aprslib client.  We were getting multiple
logins, now we get one.
2021-01-14 15:44:07 -05:00
Craig Lamparter 53bb6bed2b Merge branch 'craiger-stable' of https://github.com/craigerl/aprsd into craiger-stable 2021-01-14 12:26:15 -08:00
Craig Lamparter 3be373d7fc test plugin expect responses update to match query output 2021-01-14 12:06:57 -08:00
hemna 74be4f853e Fixed the queryPlugin unit test 2021-01-14 14:40:45 -05:00
hemna 72fa550250 Removed flask code 2021-01-14 14:36:36 -05:00
hemna 0aa905ebba Changed default log level to INFO
Also adjusted some of the logging for main, messaging and threads
to be more sane
2021-01-14 14:32:59 -05:00
Craig Lamparter e7dc537900 fix plugin tests to expect new strings 2021-01-14 11:28:59 -08:00
Craig Lamparter 0b5c9dacf0 fix query command syntax ?, ?3, ?d(elete), ?a(ll) 2021-01-14 11:21:26 -08:00
hemna 4ca5c29d49 Fixed latitude reporting in locationPlugin
The latitude was always 0, because it was the
altitude.
2021-01-14 14:02:43 -05:00
Craig Lamparter 7e3b95fd01 get rid of some debug noise from tracker and email delay 2021-01-14 10:51:00 -08:00
hemna 18acd64334 fixed sample-config double print 2021-01-14 13:43:10 -05:00
Craig Lamparter e11a84bf05 make sample config easier to interpret 2021-01-14 10:41:40 -08:00
hemna 42b2e227e1 Fixed comments 2021-01-14 12:44:58 -05:00
hemna cdde9c290b Added the ability to add comments to the config file
This patch adds a new add_config_comments() function in utils.py
that allows you to insert a comment string in a raw_yaml string
that's already been created from the yaml.dump() call.
2021-01-14 12:38:30 -05:00
hemna 264b7536b4 Updated docker run.sh script
This updates the run.sh script during container start time
to change the env var APRS_PLUGINS to APRSD_PLUGINS
2021-01-12 16:17:11 -05:00
hemna 54072a2103 Added --raw format for sending messages
aprsd send-message --raw "RAW APRS MESSAGE HERE"
2021-01-12 14:50:49 -05:00
hemna f022a3e421 Fixed --quiet option
This patch fixes the --quiet option for both send-message
and server commands.   Don't write anything to STDOUT.
2021-01-12 11:26:12 -05:00
hemna 90c4c6c59d Added send-message login checking and --no-ack
This patch adds the login failure checking for the
send-message command as well as a new command line option
--no-ack.   The new option enables sending the message directly
to aprs-is servers and then exiting immediately.  It doesn't wait
for an ack to come back.
2021-01-12 11:18:17 -05:00
hemna bdeaf6348a Added new config for aprs.fi API Key
This patch adds the new required aprs.fi api key.  This key is used
by 2 of the core plugins, locationPlugin and weatherPlugin.

You must set the apiKey in the config, or aprsd won't start.
2021-01-12 09:51:36 -05:00
hemna 3dd23fa2ad Added a fix for failed logins to APRS-IS
This patch adds a check for a failed login to ARPS due to
LoginError.  This accounts for bad accounts or username/password
failures.  aprsd server will exit immediately upon failed login now.
2021-01-12 09:31:04 -05:00
hemna 94708024da Fixed unit test for fortune plugin 2021-01-11 14:29:02 -05:00
hemna 7ab26135c2 Fixed fortune plugin failures
On alpine containers the fortune options aren't all available
and we were silently failing.  Updated the fortune plugin to capture
shell failures.
2021-01-11 14:14:16 -05:00
Craig Lamparter 76bbdfc728 getting out of git hell with client.py problems 2021-01-11 10:14:02 -08:00
hemna ac4c3d6562 Extend APRS.IS object to change login string
This patch copies the aprslib.inet IS object's _send_login()
method so we can change the login app identification string.
2021-01-11 13:08:30 -05:00
hemna 5de1b3e305 Extend APRS.IS object to change login string
This patch copies the aprslib.inet IS object's _send_login()
method so we can change the login app identification string.
2021-01-11 12:43:51 -05:00
Craig Lamparter e1a292d8e0 expect different reply from query plugin 2021-01-11 09:20:25 -08:00
Craig Lamparter 839256c76d Merge branch 'craiger-stable' of https://github.com/craigerl/aprsd into craiger-stable 2021-01-11 09:13:51 -08:00
Craig Lamparter d9141dc2d0 update query plugin to resend last N messages. syntax: ?rN 2021-01-11 09:13:37 -08:00
hemna 68e6f5b986 Added unit test for QueryPlugin
This patch adds a simple test for the QueryPlugin
2021-01-11 12:09:29 -05:00
hemna 1ce2a56140 Updated MsgTrack restart_delayed
This patch updates the restart_delayed method to accept the count of
messages to restart as well as the most_recent flag that sorts the
messages based on most recent first.  If you want the oldest first,
then pass in False
2021-01-11 11:03:41 -05:00
hemna a385d171bd refactor Plugin objects to plugins directory
This patch moves all of the plugins out of plugin.py
into their own separate plugins/<plugin>.py file.  This
makes it easier to maintain each plugin.

NOTE:  You will have to update your ~/.config/aprsd/aprsd.yml

to change the python location path for each plugin enabled.

For example:
OLD:
  enabled_plugins:
   - aprsd.plugin.EmailPlugin

TO NEW
  enabled_plugins:
   - aprsd.plugins.email.EmailPlugin
2021-01-11 08:28:08 -05:00
hemna f534646288 Updated README with more workflow details 2021-01-11 08:26:30 -05:00
Craig Lamparter fdf59b31e1 Merge branch 'craiger-stable' of https://github.com/craigerl/aprsd into craiger-stable 2021-01-10 14:50:41 -08:00
Craig Lamparter 0aa7fe7a14 change query character syntax, don't reply that we're resending stuff 2021-01-10 14:44:40 -08:00
hemna cc0d0fd523 Added APRSD system diagram to docs
This patch adds the aprsd overview diagram to the
main README as well as the generated docs.
2021-01-10 16:11:53 -05:00
hemna e6dee3a5b0 Disable MX record validation
This patch disables the MX record checking for
email address shortcuts.  verizon is a shit
smtp host that won't let you check emails as
existing/valid.  Email validation still is checked
against RFC based regex for email address as
well as blacklist checking.

TODO(hemna): make this optionally enabled
by config file.
2021-01-10 13:22:23 -05:00
Craig Lamparter 5db3c8c9b9 Merge pull request #31 from craigerl/update_readme
Updated README with more workflow details
2021-01-10 08:23:53 -08:00
hemna 7423df6b25 Added some more badges to readme files
Added badges for both docs/readme.rst and main README.rst
2021-01-09 20:12:23 -05:00
hemna bd35a610ff Updated build for docs tox -edocs
Can now run tox -edocs
2021-01-09 19:36:55 -05:00
Craig Lamparter e7f2ebf17e switch command characters for query plugin 2021-01-09 15:50:04 -08:00
hemna 1763e94f93 Fix broken test 2021-01-09 18:44:36 -05:00
Craig Lamparter 45dd3f0205 undo git disaster 2021-01-09 15:39:37 -08:00
Craig Lamparter a33462327a swap Query command characters a bit 2021-01-09 14:02:16 -08:00
hemna ee2aeb5157 Added Sphinx based documentation
This patch adds the docuemntation source tree in docs.

You can build the documentation with

tox -edocs

View the documentation by opening a browser and viewing
aprsd/docs/_build/index.html
2021-01-09 14:12:13 -05:00
hemna d5a34b4d11 refactor Plugin objects to plugins directory
This patch moves all of the plugins out of plugin.py
into their own separate plugins/<plugin>.py file.  This
makes it easier to maintain each plugin.

NOTE:  You will have to update your ~/.config/aprsd/aprsd.yml

to change the python location path for each plugin enabled.

For example:
OLD:
  enabled_plugins:
   - aprsd.plugin.EmailPlugin

TO NEW
  enabled_plugins:
   - aprsd.plugins.email.EmailPlugin
2021-01-09 10:00:37 -05:00
hemna df7a4b1fd7 Merge branch 'master' into craiger-stable 2021-01-08 21:09:41 -05:00
hemna c51a9452d9 Updated Makefile
This patch updates the Makefile to only run deps if certain files
don't exist already.   Also added the build and upload tasks to
make it easier to test, build and upload a release to pypi
2021-01-08 20:58:21 -05:00
hemna a7c20430fe removed double-quote-string-fixer 2021-01-08 20:58:21 -05:00
hemna 231c15b1af Lots of fixes 2021-01-08 20:58:18 -05:00
hemna 4c0150dd97 Added more pre-commit hook tests
also added pre-commit job for tox.
2021-01-08 20:57:58 -05:00
hemna 9f4cc27a11 Fixed email shortcut lookup
This patch fixes the email.get_email_from_shortcut.  It ensures that
if the lookup isn't found in the shortcut list, it simply returns
the original value.  This patch also adds a unit test to specifically
test this function to always return the correct value.
2021-01-08 19:35:16 -05:00
hemna f976a1c320 Added Makefile for easy dev setup
This patch adds a Makefile for helping setup a dev environment
as well as running tox tests for those that aren't used to python
development.
2021-01-08 17:46:28 -05:00
hemna 0a741cedd5 Merge pull request #34 from craigerl/makefile
Added Makefile for easy dev setup
2021-01-08 17:30:19 -05:00
hemna d084360599 Added Makefile for easy dev setup
This patch adds a Makefile for helping setup a dev environment
as well as running tox tests for those that aren't used to python
development.
2021-01-08 17:23:35 -05:00
hemna dbc891f738 Cleaned out old ack_dict
This patch removes remnants of ack_dict from the code.
The new mechanism is the MsgTrack object queue.
2021-01-08 15:11:27 -05:00
Craig Lamparter 1697395e84 add null reply for send_email 2021-01-08 11:02:57 -08:00
Craig Lamparter 7b51c36f65 Merge pull request #32 from craigerl/craiger-test
backout my patch that broke tox, trying to push to craiger-test branch
2021-01-08 09:35:39 -08:00
hemna 441ac15a0a Updated README with more workflow details 2021-01-08 12:28:17 -05:00
Craig Lamparter 96c8422990 backout my patch that broke tox, trying to push to craiger-test branch 2021-01-08 09:24:51 -08:00
hemna e83ee31310 Fixed failures caused by last commit
This patch fixes test failures caused by last commit.
2021-01-08 10:57:34 -05:00
Craig Lamparter 99c5867162 don't tell radio emails were sent, ack is enuf 2021-01-07 16:22:45 -08:00
hemna 25d948b0ee Updated README to include development env
This patch shows how to setup a development environment.

Please use the steps as laid out and install the pre-commit
hooks to ensure the code is clean prior to commit.
2021-01-06 20:03:25 -05:00
hemna 75f610d971 Added pre-commit hooks
This patch adds pre-commit hook support to ensure
code passes basic checks prior to allowing a commit.
2021-01-06 17:54:50 -05:00
hemna 8bd8b95b35 Update Changelog for v1.5.0 2020-12-30 09:29:01 -05:00
hemna 40ab7a7a94 Merge pull request #26 from craigerl/threads
Threads
2020-12-30 09:23:17 -05:00
hemna af0d4491c3 Added QueryPlugin resend all delayed msgs or Flush
This patch also updates the QueryPlugin to allow the configured user
to immediately resend all Delayed messages!

This patch updates the QueryPlugin to allow the configured user
to immediately Flush/delete all messages!
2020-12-30 09:12:38 -05:00
hemna 28f3daf6d0 Added QueryPlugin
Query Plugin looks for ^/?.* and currently only responds with
the list of pending messages in the MsgTrack queue.
2020-12-30 08:15:49 -05:00
hemna 2659a0b3b9 Added support to save/load MsgTrack on exit/start
This patch added saving of the MsgTrack list of messages at aprsd exit.
The will be loaded at startup unless you pass in the --flush option.
2020-12-30 07:41:34 -05:00
hemna 2e90c0bdbb Creation of MsgTrack object and other stuff
This patch adds the new MsgTrack object replacing the
global ack_dict.  the ack_dict was not thread safe.
the new MsgTrack is a singleton object that keeps track of
all outbound TextMessage objects.  When a TextMessage.send() is called
it is added to the MsgTrack object, and when an ack is received for that
message, the message is removed from the MsgTrack object.

TODO:  Add an automatic mechanism for saving the messages in MsgTrack
so that when CTRL-C is called to exit aprsd server, then the MsgTrack
state is saved to storage.   When aprsd server is started up again, add
the option to try and reload state of MsgTrack.

This patch also reworked the email thread into an APRSDThread object
that can exit gracefully with CTRL-C.

NOTE: Don't call sleep() with a long time (greater than 5 seconds), as
it causes a delay in exiting aprsd until the last sleep() finishes.
Since aprsd has so many threads now for processing incoming messages and
outgoing messages, we need to coordinate all thread operations so that
they don't block the exiting of the app.
2020-12-29 10:40:38 -05:00
hemna 9d3ede6e71 Added FortunePlugin unit test
this patch adds te FortunePlugin unit tests.
2020-12-25 18:13:52 -05:00
hemna 171703ac1a Added some plugin unit tests
This patch adds some real unit tests for the following plugins
PingPlugin
TimePlugin
VersionPlugin
2020-12-25 16:54:46 -05:00
hemna f65707cb8c reworked threading
This patch reworks the threading code for processing
messages.   This patch also extends the aprslib IS class
to allow us to stop processing the consumer packets when
someone hits CTRL-C correctly.  Alloing the app to exit.
2020-12-24 13:40:59 -05:00
hemna 9768003c2a Reworked messaging lib
This patch updates the messaging lib to use Message Objects
for each message type (text, ack) that know how to send
themselves with the same interface.
2020-12-23 13:12:04 -05:00
hemna 1d898ea20f Refactored the main process_packet method
This patch refactored the process_packet method
and adjusted the logic for determining if we got
a message to filter on.  We now look at the format
to make a determination.  Also isolated the processing
of message packets, ack packets and mic-e packets into
their own functions.
2020-12-21 11:59:58 -05:00
hemna 8161719697 Update README with version 1.1.0 related info
This patch adds more detailed information about the aprsd app, and
plugins.
2020-12-20 21:19:43 -05:00
hemna b2609548f2 Added fix for an unknown packet type
If we get a packet that doesn't have a message in it, nor an ack,
we don't know what to do with it, so log it and then stop processing it.
2020-12-20 20:28:56 -05:00
hemna e68d3f92e1 Merge pull request #25 from johng42/patch-1
Update .gitignore
2020-12-20 19:17:06 -05:00
hemna 18b269a39d Ensure fortune is installed
This patch uses python3's shutil to find the path
to fortune app, which can be very different depending on
the host OS that aprsd is running on.
2020-12-20 19:04:33 -05:00
hemna c39fddef67 Updated docker-compose
This patch update the docker-compose file to use the
host system's $HOME/.config/aprsd directory as the container's
config directory by default.
2020-12-20 16:46:19 -05:00
hemna 6d2160c7b7 Added Changelog
The changelog is generated by pbr automatically when you run

python setup.py sdist bdist_wheel

So when you are ready for a new release, run
python setup.py sdist bdist_wheel

git add Changelog && git commit -m "Updated ChangeLog for version XXXX"

git tag -a vXXXX -m "Release version XXX"

git push origin --tags

Then release to pypi

twine check dist/*
twine upload dist/*
2020-12-20 16:41:24 -05:00
hemna d3ee1b78bc Fixed issue when RX ack
This patch ensures that after we get an ACK, then proessing of the ack
message is complete and we don't try and send the ack through plugin
filtering.

Created send_ack_direct for the send-message command.

Also added logic to the send-message command to ensure we wait for an
ack from the command sent to APRSD and we also wait for a response
message and send an ack to that response before we exit.
2020-12-20 16:35:23 -05:00
hemna 0992ab8176 Updated the aprsd-slack-plugin required version
this patch updates the docker-compose file to use
the 1.0.2 or > version of aprsd-slack-plugin
2020-12-20 15:29:16 -05:00
hemna 6a61765eba Updated README.rst
This patch updates the README.rst with sample help and output from
various commands
2020-12-20 12:36:47 -05:00
hemna 3261710bf8 Fixed send-message with email command and others
This patch fixes a minor issue with the new send-message command
You now should use nargs to send the email command because it includes
a - as the start.  click assumed that any -<foo>  looks ike an argument.
So call aprsd with

aprsd send-command <callsign> -- -wb sendmap

This patch also adds -h as a help option for aprsd to make it simpler to
type.

This patch adds the VersionPlugin so you can remotely request the
version of aprsd that's running.
2020-12-20 12:21:30 -05:00
John a566990a2f Update .gitignore
I want to add some tests but before that I want git to ignore the venv folder and all the Idea (Pycharm) settings that get created in the home folder by default.
2020-12-19 17:25:27 -08:00
Craig Lamparter 923e1a7c3d Merge pull request #23 from craigerl/aprslib
Major refactor
2020-12-19 14:00:01 -08:00
hemna fa51f8fdf2 Big patch
This commit adds the new send-message command for sending messages.
This also redoes the logging of sent/rx'd packets to a single method
which is syncrhonized, so we don't get intermixed log messages for
packets.

Also adds email address validation during startup, and
optionally disables the validation via a command line switch.  without
email validation for production running aprsd, emails sent can turn up
garbage and cause issues when those emails are received by aprsd
message processing as invalid content.
2020-12-19 16:35:53 -05:00
hemna 08c73a17d1 Major refactor
This branch refactors the majority of main.py out into individual
modules to compartmentalize the code.  Migrated all email related
features unti email.py, sending of messages into messaging.py

Also refactored all of the socket code to use aprslib for all APRS-IS
communication as well as message/packet processing.

Moved the email command into it's own Plugin.
2020-12-18 16:21:35 -05:00
hemna 79d2139fe1 Merge pull request #24 from craigerl/docker_alpine
Updated the Dockerfile to use alpine
2020-12-17 10:22:22 -05:00
hemna b5fb248b46 Updated the Dockerfile to use alpine
The ubuntu images were running about 533MB in size, so
I refactored the Dockerfiles to use alpine linux, and they run
about 130MB.
2020-12-17 10:16:58 -05:00
59 changed files with 4895 additions and 1265 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [2.7, 3.6, 3.7, 3.8, 3.9]
python-version: [3.6, 3.7, 3.8, 3.9]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
+3 -1
View File
@@ -18,6 +18,7 @@ develop-eggs
.installed.cfg
lib
lib64
venv
# Installer logs
pip-log.txt
@@ -46,10 +47,11 @@ doc/build
# pbr generates these
AUTHORS
ChangeLog
# ChangeLog
# Editors
*~
.*.swp
.*sw?
.ropeproject
.idea
+47
View File
@@ -0,0 +1,47 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: detect-private-key
- id: check-merge-conflict
- id: check-case-conflict
- id: check-docstring-first
- id: check-builtin-literals
- repo: https://github.com/asottile/setup-cfg-fmt
rev: v1.16.0
hooks:
- id: setup-cfg-fmt
- repo: https://github.com/asottile/add-trailing-comma
rev: v2.0.2
hooks:
- id: add-trailing-comma
args: [--py36-plus]
- repo: https://github.com/asottile/pyupgrade
rev: v2.7.4
hooks:
- id: pyupgrade
args:
- --py3-plus
- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.7.0
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 20.8b1
hooks:
- id: black
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.4
hooks:
- id: flake8
additional_dependencies: [flake8-bugbear]
+230
View File
@@ -0,0 +1,230 @@
CHANGES
=======
v1.5.1
------
* Updated README to fix pypi page
v1.5.0
------
* Updated Changelog for v1.5.0 release
* Fix tox tests
* fix usage statement
* Enabled some emailthread messages and added timestamp
* Fixed main server client initialization
* test plugin expect responses update to match query output
* Fixed the queryPlugin unit test
* Removed flask code
* Changed default log level to INFO
* fix plugin tests to expect new strings
* fix query command syntax ?, ?3, ?d(elete), ?a(ll)
* Fixed latitude reporting in locationPlugin
* get rid of some debug noise from tracker and email delay
* fixed sample-config double print
* make sample config easier to interpret
* Fixed comments
* Added the ability to add comments to the config file
* Updated docker run.sh script
* Added --raw format for sending messages
* Fixed --quiet option
* Added send-message login checking and --no-ack
* Added new config for aprs.fi API Key
* Added a fix for failed logins to APRS-IS
* Fixed unit test for fortune plugin
* Fixed fortune plugin failures
* getting out of git hell with client.py problems
* Extend APRS.IS object to change login string
* Extend APRS.IS object to change login string
* expect different reply from query plugin
* update query plugin to resend last N messages. syntax: ?rN
* Added unit test for QueryPlugin
* Updated MsgTrack restart\_delayed
* refactor Plugin objects to plugins directory
* Updated README with more workflow details
* change query character syntax, don't reply that we're resending stuff
* Added APRSD system diagram to docs
* Disable MX record validation
* Added some more badges to readme files
* Updated build for docs tox -edocs
* switch command characters for query plugin
* Fix broken test
* undo git disaster
* swap Query command characters a bit
* Added Sphinx based documentation
* refactor Plugin objects to plugins directory
* Updated Makefile
* removed double-quote-string-fixer
* Lots of fixes
* Added more pre-commit hook tests
* Fixed email shortcut lookup
* Added Makefile for easy dev setup
* Added Makefile for easy dev setup
* Cleaned out old ack\_dict
* add null reply for send\_email
* Updated README with more workflow details
* backout my patch that broke tox, trying to push to craiger-test branch
* Fixed failures caused by last commit
* don't tell radio emails were sent, ack is enuf
* Updated README to include development env
* Added pre-commit hooks
* Update Changelog for v1.5.0
* Added QueryPlugin resend all delayed msgs or Flush
* Added QueryPlugin
* Added support to save/load MsgTrack on exit/start
* Creation of MsgTrack object and other stuff
* Added FortunePlugin unit test
* Added some plugin unit tests
* reworked threading
* Reworked messaging lib
v1.1.0
------
* Refactored the main process\_packet method
* Update README with version 1.1.0 related info
* Added fix for an unknown packet type
* Ensure fortune is installed
* Updated docker-compose
* Added Changelog
* Fixed issue when RX ack
* Updated the aprsd-slack-plugin required version
* Updated README.rst
* Fixed send-message with email command and others
* Update .gitignore
* Big patch
* Major refactor
* Updated the Dockerfile to use alpine
v1.0.1
------
* Fix unknown characterset emails
* Updated loggin timestamp to include []
* Updated README with a TOC
* Updates for building containers
* Don't use the dirname for the plugin path search
* Reworked Plugin loading
* Updated README with development information
* Fixed an issue with weather plugin
v1.0.0
------
* Rewrote the README.md to README.rst
* Fixed the usage string after plugins introduced
* Created plugin.py for Command Plugins
* Refactor networking and commands
* get rid of some debug statements
* yet another unicode problem, in resend\_email fixed
* reset default email check delay to 60, fix a few comments
* Update tox environment to fix formatting python errors
* fixed fortune. yet another unicode issue, tested in py3 and py2
* lose some logging statements
* completely off urllib now, tested locate/weather in py2 and py3
* add urllib import back until i replace all calls with requests
* cleaned up weather code after switch to requests ... from urllib. works on py2 and py3
* switch from urlib to requests for weather, tested in py3 and py2. still need to update locate, and all other http calls
* imap tags are unicode in py3. .decode tags
* Update INSTALL.txt
* Initial conversion to click
* Reconnect on socket timeout
* clean up code around closed\_socket and reconnect
* Update INSTALL.txt
* Fixed all pep8 errors and some py3 errors
* fix check\_email\_thread to do proper threading, take delay as arg
* found another .decode that didn't include errors='ignore'
* some failed attempts at getting the first txt or html from a multipart message, currently sends the last
* fix parse\_email unicode probs by using body.decode(errors='ignore').. again
* fix parse\_email unicode probs by using body.decode(errors='ignore')
* clean up code around closed\_socket and reconnect
* socket timeout 5 minutes
* Detect closed socket, reconnect, with a bit more grace
* can detect closed socket and reconnect now
* Update INSTALL.txt
* more debugging messages trying to find rare tight loop in main
* Update INSTALL.txt
* main loop went into tight loop, more debug prints
* main loop went into tight loop, added debug print before every continue
* Update INSTALL.txt
* Update INSTALL.txt
* George Carlin profanity filter
* added decaying email check timer which resets with activity
* Fixed all pep8 errors and some py3 errors
* Fixed all pep8 errors and some py3 errors
* Reconnect on socket timeout
* socket reconnect on timeout testing
* socket timeout of 300 instead of 60
* Reconnect on socket timeout
* socket reconnect on timeout testing
* Fixed all pep8 errors and some py3 errors
* fix check\_email\_thread to do proper threading, take delay as arg
* INSTALL.txt for the average person
* fix bugs after beautification and yaml config additions. Convert to sockets. case insensitive commands
* fix INBOX
* Update README.md
* Added tox support
* Fixed SMTP settings
* Created fake\_aprs.py
* select inbox if gmail server
* removed ASS
* Added a try block around imap login
* Added port and fixed telnet user
* Require ~/.aprsd/config.yml
* updated README for install and usage instructions
* added test to ensure shortcuts in config.yml
* added exit if missing config file
* Added reading of a config file
* update readme
* update readme
* sanitize readme
* readme again again
* readme again again
* readme again
* readme
* readme update
* First stab at migrating this to a pytpi repo
* First stab at migrating this to a pytpi repo
* Added password, callsign and host
* Added argparse for cli options
* comments
* Cleaned up trailing whitespace
* add tweaked fuzzyclock
* make tn a global
* Added standard python main()
* tweaks to readme
* drop virtenv on first line
* sanitize readme a bit more
* sanitize readme a bit more
* sanitize readme
* added weather and location 3
* added weather and location 2
* added weather and location
* mapme
* de-localize
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* de-localize
* Update README.md
* Update README.md
* Update aprsd.py
* Add files via upload
* Update README.md
* Update aprsd.py
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Add files via upload
* Initial commit
+3 -7
View File
@@ -1,4 +1,4 @@
FROM ubuntu:20.04 as aprsd
FROM alpine:latest as aprsd
ENV VERSION=1.0.0
ENV APRS_USER=aprs
@@ -6,11 +6,7 @@ ENV HOME=/home/aprs
ENV VIRTUAL_ENV=$HOME/.venv3
ENV INSTALL=$HOME/install
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get -y update
RUN apt-get install -y wget gnupg git-core
RUN apt-get install -y apt-utils pkg-config sudo vim
RUN apt-get install -y python3 python3-pip python3-virtualenv python3-venv
RUN apk add --update git wget py3-pip py3-virtualenv bash fortune
# Setup Timezone
ENV TZ=US/Eastern
@@ -20,7 +16,7 @@ RUN dpkg-reconfigure --frontend noninteractive tzdata
RUN addgroup --gid 1000 $APRS_USER
RUN useradd -m -u 1000 -g 1000 -p $APRS_USER $APRS_USER
RUN adduser -h $HOME -D -u 1001 -G $APRS_USER $APRS_USER
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8
+8 -13
View File
@@ -1,4 +1,4 @@
FROM ubuntu:20.04 as aprsd
FROM alpine:latest as aprsd
# Dockerfile for building a container during aprsd development.
@@ -6,25 +6,20 @@ ENV VERSION=1.0.0
ENV APRS_USER=aprs
ENV HOME=/home/aprs
ENV APRSD=http://github.com/craigerl/aprsd.git
ENV APRSD_BRANCH="master"
ENV APRSD_BRANCH="v1.1.0"
ENV VIRTUAL_ENV=$HOME/.venv3
ENV INSTALL=$HOME/install
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get -y update
RUN apt-get install -y wget gnupg git-core
RUN apt-get install -y apt-utils pkg-config sudo vim
RUN apt-get install -y python3 python3-pip python3-virtualenv python3-venv
RUN apk add --update git vim wget py3-pip py3-virtualenv bash fortune
# Setup Timezone
ENV TZ=US/Eastern
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN apt-get install -y tzdata
RUN dpkg-reconfigure --frontend noninteractive tzdata
#RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
#RUN apt-get install -y tzdata
#RUN dpkg-reconfigure --frontend noninteractive tzdata
RUN addgroup --gid 1000 $APRS_USER
RUN useradd -m -u 1000 -g 1000 -p $APRS_USER $APRS_USER
RUN addgroup --gid 1001 $APRS_USER
RUN adduser -h $HOME -D -u 1001 -G $APRS_USER $APRS_USER
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8
+4 -4
View File
@@ -13,12 +13,12 @@ cd ~/aprsd2
git clone https://github.com/craigerl/aprsd.git
cd aprsd
pip install -e .
cd ~/.venv_aprsd
cd ~/.venv_aprsd/bin
./bin/aprsd # generates a config.yml template on first run
./aprsd sample-config # generates a config.yml template
vi ~/.aprsd/config.yml
vi ~/.config/aprsd/config.yml # copy/edit config here
./bin/aprsd
./aprsd server
# profit! #
+175
View File
@@ -0,0 +1,175 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
+58
View File
@@ -0,0 +1,58 @@
.PHONY: virtual dev build-requirements black isort flake8
all: pip dev
virtual: .venv/bin/pip # Creates an isolated python 3 environment
.venv/bin/pip:
virtualenv -p /usr/bin/python3 .venv
.venv/bin/aprsd: virtual
test -s .venv/bin/aprsd || .venv/bin/pip install -q -e .
install: .venv/bin/aprsd
.venv/bin/pip install -Ur requirements.txt
dev-pre-commit:
test -s .git/hooks/pre-commit || .venv/bin/pre-commit install
dev-requirements:
test -s .venv/bin/twine || .venv/bin/pip install -q -r dev-requirements.txt
pip: virtual
.venv/bin/pip install -q -U pip
dev: pip .venv/bin/aprsd dev-requirements dev-pre-commit
pip-tools:
test -s .venv/bin/pip-compile || .venv/bin/pip install pip-tools
clean:
rm -rf dist/*
rm -rf .venv
test: dev
.venv/bin/pre-commit run --all-files
tox -p all
build: test
rm -rf dist/*
.venv/bin/python3 setup.py sdist bdist_wheel
.venv/bin/twine check dist/*
upload: build
.venv/bin/twine upload dist/*
update-requirements: dev pip-tools
.venv/bin/pip-compile -q -U requirements.in
.venv/bin/pip-compile -q -U dev-requirements.in
.venv/bin/tox: # install tox
test -s .venv/bin/tox || .venv/bin/pip install -q -U tox
check: .venv/bin/tox # Code format check with isort and black
tox -efmt-check
tox -epep8
fix: .venv/bin/tox # fixes code formatting with isort and black
tox -efmt
+247 -67
View File
@@ -2,6 +2,9 @@
APRSD
=====
.. image:: https://badge.fury.io/py/aprsd.svg
:target: https://badge.fury.io/py/aprsd
.. image:: https://github.com/craigerl/aprsd/workflows/python/badge.svg
:target: https://github.com/craigerl/aprsd/actions
@@ -11,15 +14,73 @@ APRSD
.. image:: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336
:target: https://timothycrosley.github.io/isort/
.. image:: https://img.shields.io/github/issues/craigerl/aprsd
.. image:: https://img.shields.io/github/last-commit/craigerl/aprsd
.. image:: https://static.pepy.tech/personalized-badge/aprsd?period=month&units=international_system&left_color=black&right_color=orange&left_text=Downloads
:target: https://pepy.tech/project/aprsd
.. contents:: :local:
Listen on amateur radio aprs-is network for messages and respond to them.
You must have an amateur radio callsign to use this software. Put your
callsign in the "USER" variable and update your aprs-is password in "PASS".
You must also have an imap email account available for polling.
`APRSD <http://github.com/craigerl/aprsd>`_ is a Ham radio `APRS <http://aprs.org>`_ message command gateway built on python.
APRSD listens on amateur radio aprs-is network for messages and respond to them.
It has a plugin architecture for extensibility. Users of APRSD can write their own
plugins that can respond to APRS-IS messages.
You must have an amateur radio callsign to use this software. APRSD gets
messages for the configured HAM callsign, and sends those messages to a
list of plugins for processing. There are a set of core plugins that
provide responding to messages to check email, get location, ping,
time of day, get weather, and fortune telling as well as version information
of aprsd itself.
APRSD Overview Diagram
----------------------
.. image:: https://raw.githubusercontent.com/craigerl/aprsd/master/docs/_static/aprsd_overview.svg?sanitize=true
Typical use case
================
Ham radio operator using an APRS enabled HAM radio sends a message to check
the weather. an APRS message is sent, and then picked up by APRSD. The
APRS packet is decoded, and the message is sent through the list of plugins
for processing. For example, the WeatherPlugin picks up the message, fetches the weather
for the area around the user who sent the request, and then responds with
the weather conditions in that area.
APRSD Capabilities
==================
* server - The main aprsd server processor. Send/Rx APRS messages to HAM callsign
* send-message - use aprsd to send a command/message to aprsd server. Used for development testing
* sample-config - generate a sample aprsd.yml config file for use/editing
* bash completion generation. Uses python click bash completion to generate completion code for your .bashrc/.zshrc
List of core server plugins
===========================
Plugins function by specifying a regex that is searched for in the APRS message.
If it matches, the plugin runs. IF the regex doesn't match, the plugin is skipped.
* EmailPlugin - Check email and reply with contents. Have to configure IMAP and SMTP settings in aprs.yml
* FortunePlugin - Replies with old unix fortune random fortune!
* LocationPlugin - Checks location of ham operator
* PingPlugin - Sends pong with timestamp
* QueryPlugin - Allows querying the list of delayed messages that were not ACK'd by radio
* TimePlugin - Current time of day
* WeatherPlugin - Get weather conditions for current location of HAM callsign
* VersionPlugin - Reports the version information for aprsd
Current messages this will respond to:
--------------------------------------
======================================
::
@@ -33,6 +94,7 @@ Current messages this will respond to:
-email_addr email text = send an email, say "mapme" to send a current position/map
-2 = resend the last 2 emails from your imap inbox to this radio
p(ing) = respond with Pong!/time
v(ersion) = Respond with current APRSD Version string
anything else = respond with usage
@@ -47,7 +109,7 @@ email server, and associated logins, passwords. search for "yourdomain",
Installation:
-------------
=============
pip install aprsd
@@ -56,8 +118,151 @@ Example usage:
aprsd -h
Help
====
::
└─[$] > aprsd -h
Usage: aprsd [OPTIONS] COMMAND [ARGS]...
Shell completion for click-completion-command Available shell types:
bash Bourne again shell fish Friendly interactive shell
powershell Windows PowerShell zsh Z shell Default type: auto
Options:
--version Show the version and exit.
-h, --help Show this message and exit.
Commands:
install Install the click-completion-command completion
sample-config This dumps the config to stdout.
send-message Send a message to a callsign via APRS_IS.
server Start the aprsd server process.
show Show the click-completion-command completion code
Commands
========
Configuration
=============
This command outputs a sample config yml formatted block that you can edit
and use to pass in to aprsd with -c. By default aprsd looks in ~/.config/aprsd/aprsd.yml
aprsd sample-config
Output
======
::
└─[$] > aprsd sample-config
aprs:
host: rotate.aprs.net
logfile: /tmp/arsd.log
login: someusername
password: somepassword
port: 14580
aprsd:
enabled_plugins:
- aprsd.plugin.EmailPlugin
- aprsd.plugin.FortunePlugin
- aprsd.plugin.LocationPlugin
- aprsd.plugin.PingPlugin
- aprsd.plugin.TimePlugin
- aprsd.plugin.WeatherPlugin
- aprsd.plugin.VersionPlugin
plugin_dir: ~/.config/aprsd/plugins
ham:
callsign: KFART
imap:
host: imap.gmail.com
login: imapuser
password: something here too
port: 993
use_ssl: true
shortcuts:
aa: 5551239999@vtext.com
cl: craiglamparter@somedomain.org
wb: 555309@vtext.com
smtp:
host: imap.gmail.com
login: something
password: some lame password
port: 465
use_ssl: false
server
======
This is the main server command that will listen to APRS-IS servers and
look for incomming commands to the callsign configured in the config file
::
└─[$] > aprsd server --help
Usage: aprsd server [OPTIONS]
Start the aprsd server process.
Options:
--loglevel [CRITICAL|ERROR|WARNING|INFO|DEBUG]
The log level to use for aprsd.log
[default: DEBUG]
--quiet Don't log to stdout
--disable-validation Disable email shortcut validation. Bad
email addresses can result in broken email
responses!!
-c, --config TEXT The aprsd config file to use for options.
[default: ~/.config/aprsd/aprsd.yml]
-h, --help Show this message and exit.
(.venv3) ┌─[waboring@dl360-1] - [~/devel/aprsd] - [Sun Dec 20, 12:32] -
└─[$] <git:(master*)> aprsd server
Load config
[12/20/2020 12:33:03 PM] [MainThread ] [INFO ] APRSD Started version: 1.0.2
[12/20/2020 12:33:03 PM] [MainThread ] [INFO ] Checking IMAP configuration
[12/20/2020 12:33:04 PM] [MainThread ] [INFO ] Checking SMTP configuration
send-message
============
This command is typically used for development to send another aprsd instance
test messages
::
└─[$] > aprsd send-message -h
Usage: aprsd send-message [OPTIONS] TOCALLSIGN [COMMAND]...
Send a message to a callsign via APRS_IS.
Options:
--loglevel [CRITICAL|ERROR|WARNING|INFO|DEBUG]
The log level to use for aprsd.log
[default: DEBUG]
--quiet Don't log to stdout
-c, --config TEXT The aprsd config file to use for options.
[default: ~/.config/aprsd/aprsd.yml]
--aprs-login TEXT What callsign to send the message from.
[env var: APRS_LOGIN]
--aprs-password TEXT the APRS-IS password for APRS_LOGIN [env
var: APRS_PASSWORD]
-h, --help Show this message and exit.
Example output:
---------------
===============
SEND EMAIL (radio to smtp server)
=================================
@@ -98,77 +303,58 @@ RECEIVE EMAIL (imap server to radio)
Msg number : 0
WEATHER
=======
::
Received message______________
Raw : KM6XXX>APY400,WIDE1-1,qAO,KM6XXX-1::KM6XXX-9 :weather{27
From : KM6XXX
Message : weather
Msg number : 27
Sending message_______________ 6(Tx3)
Raw : KM6XXX-9>APRS::KM6XXX :58F(58F/46F) Partly cloudy. Tonight, Heavy Rain.{6
To : KM6XXX
Message : 58F(58F/46F) Party Cloudy. Tonight, Heavy Rain.
Sending ack __________________ Tx(3)
Raw : KM6XXX-9>APRS::KM6XXX :ack27
To : KM6XXX
Ack number : 27
Received message______________
Raw : KM6XXX>APY400,WIDE1-1,qAO,KM6XXX-1::KM6XXX-9 :ack6
From : KM6XXX
Message : ack6
Msg number : 0
LOCATION
========
::
Received message______________
Raw : KM6XXX>APY400,WIDE1-1,qAO,KM6XXX-1::KM6XXX-9 :location{28
From : KM6XXX
Received Message _______________
Raw : KM6XXX-6>APRS,TCPIP*,qAC,T2CAEAST::KM6XXX-14:location{2
From : KM6XXX-6
Message : location
Msg number : 28
Msg number : 2
Received Message _______________ Complete
Sending message_______________ 7(Tx3)
Raw : KM6XXX-9>APRS::KM6XXX :8 Miles NE Auburn CA 1673' 39.91150,-120.93450 0.1h ago{7
To : KM6XXX
Message : 8 Miles E Auburn CA 1673' 38.91150,-120.93450 0.1h ago
Sending Message _______________
Raw : KM6XXX-14>APRS::KM6XXX-6 :KM6XXX-6: 8 Miles E Auburn CA 0' 0,-120.93584 1873.7h ago{2
To : KM6XXX-6
Message : KM6XXX-6: 8 Miles E Auburn CA 0' 0,-120.93584 1873.7h ago
Msg number : 2
Sending Message _______________ Complete
Sending ack __________________ Tx(3)
Raw : KM6XXX-9>APRS::KM6XXX :ack28
To : KM6XXX
Ack number : 28
Received message______________
Raw : KM6XXX>APY400,WIDE1-1,qAO,KM6XXX-1::KM6XXX-9 :ack7
From : KM6XXX
Message : ack7
Msg number : 0
Sending ack _______________
Raw : KM6XXX-14>APRS::KM6XXX-6 :ack2
To : KM6XXX-6
Ack : 2
Sending ack _______________ Complete
AND... ping, fortune, time.....
Development
-----------
===========
* git clone git@github.com:craigerl/aprsd.git
* cd aprsd
* make
Workflow
========
While working aprsd, The workflow is as follows
* Edit code, save file
* checkout a new branch to work on
* git checkout -b mybranch
* Edit code
* run tox -epep8
* run tox -efmt
* run tox -p
* git commit
* git commit ( This will run the pre-commit hooks which does checks too )
* Once you are done with all of your commits, then push up the branch to
github
* git push -u origin mybranch
* Create a pull request from your branch so github tests can run and we can do
a code review.
Release
@@ -176,7 +362,7 @@ Release
To do release to pypi:
* Tag release with
* Tag release with
git tag -v1.XX -m "New release"
@@ -184,22 +370,17 @@ To do release to pypi:
git push origin master --tags
* Build dist and wheel
* Do a test build and verify build is valid
python setup.py sdist bdist_wheel
* Verify build is valid for pypi (need twine installed )
pip install twine
twine check dist/*
make build
* Once twine is happy, upload release to pypi
twine upload dist/*
make upload
Docker Container
----------------
================
Building
========
@@ -234,4 +415,3 @@ Provide a csv list of pypi installable plugins. Then make sure the plugin
python file is in your /plugins volume and the plugin will be installed at
container startup. The plugin may have dependencies that are required.
The plugin file should be copied to /plugins for loading by aprsd
-2
View File
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
+182
View File
@@ -0,0 +1,182 @@
import logging
import select
import time
import aprsd
import aprslib
from aprslib import is_py3
from aprslib.exceptions import LoginError
LOG = logging.getLogger("APRSD")
class Client:
"""Singleton client class that constructs the aprslib connection."""
_instance = None
aprs_client = None
config = None
connected = False
def __new__(cls, *args, **kwargs):
"""This magic turns this into a singleton."""
if cls._instance is None:
cls._instance = super().__new__(cls)
# Put any initialization here.
return cls._instance
def __init__(self, config=None):
"""Initialize the object instance."""
if config:
self.config = config
@property
def client(self):
if not self.aprs_client:
self.aprs_client = self.setup_connection()
return self.aprs_client
def reset(self):
"""Call this to force a rebuild/reconnect."""
del self.aprs_client
def setup_connection(self):
user = self.config["aprs"]["login"]
password = self.config["aprs"]["password"]
host = self.config["aprs"].get("host", "rotate.aprs.net")
port = self.config["aprs"].get("port", 14580)
connected = False
backoff = 1
while not connected:
try:
LOG.info("Creating aprslib client")
aprs_client = Aprsdis(user, passwd=password, host=host, port=port)
# Force the logging to be the same
aprs_client.logger = LOG
aprs_client.connect()
connected = True
backoff = 1
except LoginError as e:
LOG.error("Failed to login to APRS-IS Server '{}'".format(e))
connected = False
raise e
except Exception as e:
LOG.error("Unable to connect to APRS-IS server. '{}' ".format(e))
time.sleep(backoff)
backoff = backoff * 2
continue
LOG.debug("Logging in to APRS-IS with user '%s'" % user)
return aprs_client
class Aprsdis(aprslib.IS):
"""Extend the aprslib class so we can exit properly."""
# flag to tell us to stop
thread_stop = False
# timeout in seconds
select_timeout = 10
def stop(self):
self.thread_stop = True
LOG.info("Shutdown Aprsdis client.")
def _socket_readlines(self, blocking=False):
"""
Generator for complete lines, received from the server
"""
try:
self.sock.setblocking(0)
except OSError as e:
self.logger.error("socket error when setblocking(0): %s" % str(e))
raise aprslib.ConnectionDrop("connection dropped")
while not self.thread_stop:
short_buf = b""
newline = b"\r\n"
# set a select timeout, so we get a chance to exit
# when user hits CTRL-C
readable, writable, exceptional = select.select(
[self.sock],
[],
[],
self.select_timeout,
)
if not readable:
continue
try:
short_buf = self.sock.recv(4096)
# sock.recv returns empty if the connection drops
if not short_buf:
self.logger.error("socket.recv(): returned empty")
raise aprslib.ConnectionDrop("connection dropped")
except OSError as e:
# self.logger.error("socket error on recv(): %s" % str(e))
if "Resource temporarily unavailable" in str(e):
if not blocking:
if len(self.buf) == 0:
break
self.buf += short_buf
while newline in self.buf:
line, self.buf = self.buf.split(newline, 1)
yield line
def _send_login(self):
"""
Sends login string to server
"""
login_str = "user {0} pass {1} vers github.com/craigerl/aprsd {3}{2}\r\n"
login_str = login_str.format(
self.callsign,
self.passwd,
(" filter " + self.filter) if self.filter != "" else "",
aprsd.__version__,
)
self.logger.info("Sending login information")
try:
self._sendall(login_str)
self.sock.settimeout(5)
test = self.sock.recv(len(login_str) + 100)
if is_py3:
test = test.decode("latin-1")
test = test.rstrip()
self.logger.debug("Server: %s", test)
_, _, callsign, status, _ = test.split(" ", 4)
if callsign == "":
raise LoginError("Server responded with empty callsign???")
if callsign != self.callsign:
raise LoginError("Server: %s" % test)
if status != "verified," and self.passwd != "-1":
raise LoginError("Password is incorrect")
if self.passwd == "-1":
self.logger.info("Login successful (receive only)")
else:
self.logger.info("Login successful")
except LoginError as e:
self.logger.error(str(e))
self.close()
raise
except Exception:
self.close()
self.logger.error("Failed to login")
raise LoginError("Failed to login")
def get_client():
cl = Client()
return cl.client
+443
View File
@@ -0,0 +1,443 @@
import datetime
import email
from email.mime.text import MIMEText
import imaplib
import logging
import re
import smtplib
import time
from aprsd import messaging, threads
import imapclient
from validate_email import validate_email
LOG = logging.getLogger("APRSD")
# This gets forced set from main.py prior to being used internally
CONFIG = None
def _imap_connect():
imap_port = CONFIG["imap"].get("port", 143)
use_ssl = CONFIG["imap"].get("use_ssl", False)
host = CONFIG["imap"]["host"]
msg = "{}{}:{}".format("TLS " if use_ssl else "", host, imap_port)
# LOG.debug("Connect to IMAP host {} with user '{}'".
# format(msg, CONFIG['imap']['login']))
try:
server = imapclient.IMAPClient(
CONFIG["imap"]["host"],
port=imap_port,
use_uid=True,
ssl=use_ssl,
)
except Exception:
LOG.error("Failed to connect IMAP server")
return
try:
server.login(CONFIG["imap"]["login"], CONFIG["imap"]["password"])
except (imaplib.IMAP4.error, Exception) as e:
msg = getattr(e, "message", repr(e))
LOG.error("Failed to login {}".format(msg))
return
server.select_folder("INBOX")
return server
def _smtp_connect():
host = CONFIG["smtp"]["host"]
smtp_port = CONFIG["smtp"]["port"]
use_ssl = CONFIG["smtp"].get("use_ssl", False)
msg = "{}{}:{}".format("SSL " if use_ssl else "", host, smtp_port)
LOG.debug(
"Connect to SMTP host {} with user '{}'".format(msg, CONFIG["imap"]["login"]),
)
try:
if use_ssl:
server = smtplib.SMTP_SSL(host=host, port=smtp_port)
else:
server = smtplib.SMTP(host=host, port=smtp_port)
except Exception:
LOG.error("Couldn't connect to SMTP Server")
return
LOG.debug("Connected to smtp host {}".format(msg))
try:
server.login(CONFIG["smtp"]["login"], CONFIG["smtp"]["password"])
except Exception:
LOG.error("Couldn't connect to SMTP Server")
return
LOG.debug("Logged into SMTP server {}".format(msg))
return server
def validate_shortcuts(config):
shortcuts = config.get("shortcuts", None)
if not shortcuts:
return
LOG.info(
"Validating {} Email shortcuts. This can take up to 10 seconds"
" per shortcut".format(len(shortcuts)),
)
delete_keys = []
for key in shortcuts:
LOG.info("Validating {}:{}".format(key, shortcuts[key]))
is_valid = validate_email(
email_address=shortcuts[key],
check_regex=True,
check_mx=False,
from_address=config["smtp"]["login"],
helo_host=config["smtp"]["host"],
smtp_timeout=10,
dns_timeout=10,
use_blacklist=True,
debug=False,
)
if not is_valid:
LOG.error(
"'{}' is an invalid email address. Removing shortcut".format(
shortcuts[key],
),
)
delete_keys.append(key)
for key in delete_keys:
del config["shortcuts"][key]
LOG.info("Available shortcuts: {}".format(config["shortcuts"]))
def get_email_from_shortcut(addr):
if CONFIG.get("shortcuts", False):
return CONFIG["shortcuts"].get(addr, addr)
else:
return addr
def validate_email_config(config, disable_validation=False):
"""function to simply ensure we can connect to email services.
This helps with failing early during startup.
"""
LOG.info("Checking IMAP configuration")
imap_server = _imap_connect()
LOG.info("Checking SMTP configuration")
smtp_server = _smtp_connect()
# Now validate and flag any shortcuts as invalid
if not disable_validation:
validate_shortcuts(config)
else:
LOG.info("Shortcuts email validation is Disabled!!, you were warned.")
if imap_server and smtp_server:
return True
else:
return False
def parse_email(msgid, data, server):
envelope = data[b"ENVELOPE"]
# email address match
# use raw string to avoid invalid escape secquence errors r"string here"
f = re.search(r"([\.\w_-]+@[\.\w_-]+)", str(envelope.from_[0]))
if f is not None:
from_addr = f.group(1)
else:
from_addr = "noaddr"
LOG.debug("Got a message from '{}'".format(from_addr))
m = server.fetch([msgid], ["RFC822"])
msg = email.message_from_string(m[msgid][b"RFC822"].decode(errors="ignore"))
if msg.is_multipart():
text = ""
html = None
# default in case body somehow isn't set below - happened once
body = b"* unreadable msg received"
# this uses the last text or html part in the email, phone companies often put content in an attachment
for part in msg.get_payload():
if part.get_content_charset() is None:
# or BREAK when we hit a text or html?
# We cannot know the character set,
# so return decoded "something"
LOG.debug("Email got unknown content type")
text = part.get_payload(decode=True)
continue
charset = part.get_content_charset()
if part.get_content_type() == "text/plain":
LOG.debug("Email got text/plain")
text = str(
part.get_payload(decode=True),
str(charset),
"ignore",
).encode("utf8", "replace")
if part.get_content_type() == "text/html":
LOG.debug("Email got text/html")
html = str(
part.get_payload(decode=True),
str(charset),
"ignore",
).encode("utf8", "replace")
if text is not None:
# strip removes white space fore and aft of string
body = text.strip()
else:
body = html.strip()
else: # message is not multipart
# email.uscc.net sends no charset, blows up unicode function below
LOG.debug("Email is not multipart")
if msg.get_content_charset() is None:
text = str(msg.get_payload(decode=True), "US-ASCII", "ignore").encode(
"utf8",
"replace",
)
else:
text = str(
msg.get_payload(decode=True),
msg.get_content_charset(),
"ignore",
).encode("utf8", "replace")
body = text.strip()
# FIXED: UnicodeDecodeError: 'ascii' codec can't decode byte 0xf0 in position 6: ordinal not in range(128)
# decode with errors='ignore'. be sure to encode it before we return it below, also with errors='ignore'
try:
body = body.decode(errors="ignore")
except Exception as e:
LOG.error("Unicode decode failure: " + str(e))
LOG.error("Unidoce decode failed: " + str(body))
body = "Unreadable unicode msg"
# strip all html tags
body = re.sub("<[^<]+?>", "", body)
# strip CR/LF, make it one line, .rstrip fails at this
body = body.replace("\n", " ").replace("\r", " ")
# ascii might be out of range, so encode it, removing any error characters
body = body.encode(errors="ignore")
return (body, from_addr)
# end parse_email
def send_email(to_addr, content):
global check_email_delay
shortcuts = CONFIG["shortcuts"]
email_address = get_email_from_shortcut(to_addr)
LOG.info("Sending Email_________________")
if to_addr in shortcuts:
LOG.info("To : " + to_addr)
to_addr = email_address
LOG.info(" (" + to_addr + ")")
subject = CONFIG["ham"]["callsign"]
# content = content + "\n\n(NOTE: reply with one line)"
LOG.info("Subject : " + subject)
LOG.info("Body : " + content)
# check email more often since there's activity right now
check_email_delay = 60
msg = MIMEText(content)
msg["Subject"] = subject
msg["From"] = CONFIG["smtp"]["login"]
msg["To"] = to_addr
server = _smtp_connect()
if server:
try:
server.sendmail(CONFIG["smtp"]["login"], [to_addr], msg.as_string())
except Exception as e:
msg = getattr(e, "message", repr(e))
LOG.error("Sendmail Error!!!! '{}'", msg)
server.quit()
return -1
server.quit()
return 0
# end send_email
def resend_email(count, fromcall):
global check_email_delay
date = datetime.datetime.now()
month = date.strftime("%B")[:3] # Nov, Mar, Apr
day = date.day
year = date.year
today = "{}-{}-{}".format(day, month, year)
shortcuts = CONFIG["shortcuts"]
# swap key/value
shortcuts_inverted = {v: k for k, v in shortcuts.items()}
try:
server = _imap_connect()
except Exception as e:
LOG.exception("Failed to Connect to IMAP. Cannot resend email ", e)
return
messages = server.search(["SINCE", today])
# LOG.debug("%d messages received today" % len(messages))
msgexists = False
messages.sort(reverse=True)
del messages[int(count) :] # only the latest "count" messages
for message in messages:
for msgid, data in list(server.fetch(message, ["ENVELOPE"]).items()):
# one at a time, otherwise order is random
(body, from_addr) = parse_email(msgid, data, server)
# unset seen flag, will stay bold in email client
server.remove_flags(msgid, [imapclient.SEEN])
if from_addr in shortcuts_inverted:
# reverse lookup of a shortcut
from_addr = shortcuts_inverted[from_addr]
# asterisk indicates a resend
reply = "-" + from_addr + " * " + body.decode(errors="ignore")
# messaging.send_message(fromcall, reply)
msg = messaging.TextMessage(CONFIG["aprs"]["login"], fromcall, reply)
msg.send()
msgexists = True
if msgexists is not True:
stm = time.localtime()
h = stm.tm_hour
m = stm.tm_min
s = stm.tm_sec
# append time as a kind of serial number to prevent FT1XDR from
# thinking this is a duplicate message.
# The FT1XDR pretty much ignores the aprs message number in this
# regard. The FTM400 gets it right.
reply = "No new msg {}:{}:{}".format(
str(h).zfill(2),
str(m).zfill(2),
str(s).zfill(2),
)
# messaging.send_message(fromcall, reply)
msg = messaging.TextMessage(CONFIG["aprs"]["login"], fromcall, reply)
msg.send()
# check email more often since we're resending one now
check_email_delay = 60
server.logout()
# end resend_email()
class APRSDEmailThread(threads.APRSDThread):
def __init__(self, msg_queues, config):
super().__init__("EmailThread")
self.msg_queues = msg_queues
self.config = config
def run(self):
global check_email_delay
LOG.debug("Starting")
check_email_delay = 60
past = datetime.datetime.now()
while not self.thread_stop:
time.sleep(5)
# always sleep for 5 seconds and see if we need to check email
# This allows CTRL-C to stop the execution of this loop sooner
# than check_email_delay time
now = datetime.datetime.now()
if now - past > datetime.timedelta(seconds=check_email_delay):
# It's time to check email
# slowly increase delay every iteration, max out at 300 seconds
# any send/receive/resend activity will reset this to 60 seconds
if check_email_delay < 300:
check_email_delay += 1
LOG.debug("check_email_delay is " + str(check_email_delay) + " seconds")
shortcuts = CONFIG["shortcuts"]
# swap key/value
shortcuts_inverted = {v: k for k, v in shortcuts.items()}
date = datetime.datetime.now()
month = date.strftime("%B")[:3] # Nov, Mar, Apr
day = date.day
year = date.year
today = "{}-{}-{}".format(day, month, year)
server = None
try:
server = _imap_connect()
except Exception as e:
LOG.exception("Failed to get IMAP server Can't check email.", e)
if not server:
continue
messages = server.search(["SINCE", today])
LOG.debug("{} messages received today".format(len(messages)))
for msgid, data in server.fetch(messages, ["ENVELOPE"]).items():
envelope = data[b"ENVELOPE"]
# LOG.debug('ID:%d "%s" (%s)' % (msgid, envelope.subject.decode(), envelope.date))
f = re.search(
r"'([[A-a][0-9]_-]+@[[A-a][0-9]_-\.]+)",
str(envelope.from_[0]),
)
if f is not None:
from_addr = f.group(1)
else:
from_addr = "noaddr"
# LOG.debug("Message flags/tags: " + str(server.get_flags(msgid)[msgid]))
# if "APRS" not in server.get_flags(msgid)[msgid]:
# in python3, imap tags are unicode. in py2 they're strings. so .decode them to handle both
taglist = [
x.decode(errors="ignore")
for x in server.get_flags(msgid)[msgid]
]
if "APRS" not in taglist:
# if msg not flagged as sent via aprs
server.fetch([msgid], ["RFC822"])
(body, from_addr) = parse_email(msgid, data, server)
# unset seen flag, will stay bold in email client
server.remove_flags(msgid, [imapclient.SEEN])
if from_addr in shortcuts_inverted:
# reverse lookup of a shortcut
from_addr = shortcuts_inverted[from_addr]
reply = "-" + from_addr + " " + body.decode(errors="ignore")
msg = messaging.TextMessage(
self.config["aprs"]["login"],
self.config["ham"]["callsign"],
reply,
)
self.msg_queues["tx"].put(msg)
# flag message as sent via aprs
server.add_flags(msgid, ["APRS"])
# unset seen flag, will stay bold in email client
server.remove_flags(msgid, [imapclient.SEEN])
# check email more often since we just received an email
check_email_delay = 60
# reset clock
past = datetime.datetime.now()
server.logout()
else:
# We haven't hit the email delay yet.
# LOG.debug("Delta({}) < {}".format(now - past, check_email_delay))
pass
# Remove ourselves from the global threads list
threads.APRSDThreadList().remove(self)
LOG.info("Exiting")
# end check_email()
+2 -2
View File
@@ -1,9 +1,9 @@
import argparse
import logging
from logging.handlers import RotatingFileHandler
import socketserver
import sys
import time
from logging.handlers import RotatingFileHandler
from aprsd import utils
@@ -73,7 +73,7 @@ def main():
ip = CONFIG["aprs"]["host"]
port = CONFIG["aprs"]["port"]
LOG.info("Start server listening on %s:%s" % (args.ip, args.port))
LOG.info("Start server listening on {}:{}".format(args.ip, args.port))
with socketserver.TCPServer((ip, port), MyAPRSTCPHandler) as server:
server.serve_forever()
+295 -749
View File
File diff suppressed because it is too large Load Diff
+566
View File
@@ -0,0 +1,566 @@
import abc
import datetime
import logging
from multiprocessing import RawValue
import os
import pathlib
import pickle
import re
import threading
import time
from aprsd import client, threads, utils
LOG = logging.getLogger("APRSD")
# What to return from a plugin if we have processed the message
# and it's ok, but don't send a usage string back
NULL_MESSAGE = -1
class MsgTrack:
"""Class to keep track of outstanding text messages.
This is a thread safe class that keeps track of active
messages.
When a message is asked to be sent, it is placed into this
class via it's id. The TextMessage class's send() method
automatically adds itself to this class. When the ack is
recieved from the radio, the message object is removed from
this class.
# TODO(hemna)
When aprsd is asked to quit this class should be serialized and
saved to disk/db to keep track of the state of outstanding messages.
When aprsd is started, it should try and fetch the saved state,
and reloaded to a live state.
"""
_instance = None
_start_time = None
lock = None
track = {}
total_messages_tracked = 0
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.track = {}
cls._start_time = datetime.datetime.now()
cls._instance.lock = threading.Lock()
return cls._instance
def add(self, msg):
with self.lock:
key = int(msg.id)
self.track[key] = msg
self.total_messages_tracked += 1
def get(self, id):
with self.lock:
if id in self.track:
return self.track[id]
def remove(self, id):
with self.lock:
key = int(id)
if key in self.track.keys():
del self.track[key]
def __len__(self):
with self.lock:
return len(self.track)
def __str__(self):
with self.lock:
result = "{"
for key in self.track.keys():
result += "{}: {}, ".format(key, str(self.track[key]))
result += "}"
return result
def save(self):
"""Save this shit to disk?"""
if len(self) > 0:
LOG.info("Saving {} tracking messages to disk".format(len(self)))
pickle.dump(self.dump(), open(utils.DEFAULT_SAVE_FILE, "wb+"))
else:
self.flush()
def dump(self):
dump = {}
with self.lock:
for key in self.track.keys():
dump[key] = self.track[key]
return dump
def load(self):
if os.path.exists(utils.DEFAULT_SAVE_FILE):
raw = pickle.load(open(utils.DEFAULT_SAVE_FILE, "rb"))
if raw:
self.track = raw
LOG.debug("Loaded MsgTrack dict from disk.")
LOG.debug(self)
def restart(self):
"""Walk the list of messages and restart them if any."""
for key in self.track.keys():
msg = self.track[key]
if msg.last_send_attempt < msg.retry_count:
msg.send()
def _resend(self, msg):
msg.last_send_attempt = 0
msg.send()
def restart_delayed(self, count=None, most_recent=True):
"""Walk the list of delayed messages and restart them if any."""
if not count:
# Send all the delayed messages
for key in self.track.keys():
msg = self.track[key]
if msg.last_send_attempt == msg.retry_count:
self._resend(msg)
else:
# They want to resend <count> delayed messages
tmp = sorted(
self.track.items(),
reverse=most_recent,
key=lambda x: x[1].last_send_time,
)
msg_list = tmp[:count]
for (_key, msg) in msg_list:
self._resend(msg)
def flush(self):
"""Nuke the old pickle file that stored the old results from last aprsd run."""
if os.path.exists(utils.DEFAULT_SAVE_FILE):
pathlib.Path(utils.DEFAULT_SAVE_FILE).unlink()
with self.lock:
self.track = {}
class MessageCounter:
"""
Global message id counter class.
This is a singleton based class that keeps
an incrementing counter for all messages to
be sent. All new Message objects gets a new
message id, which is the next number available
from the MessageCounter.
"""
_instance = None
max_count = 9999
def __new__(cls, *args, **kwargs):
"""Make this a singleton class."""
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.val = RawValue("i", 1)
cls._instance.lock = threading.Lock()
return cls._instance
def increment(self):
with self.lock:
if self.val.value == self.max_count:
self.val.value = 1
else:
self.val.value += 1
@property
def value(self):
with self.lock:
return self.val.value
def __repr__(self):
with self.lock:
return str(self.val.value)
def __str__(self):
with self.lock:
return str(self.val.value)
class Message(metaclass=abc.ABCMeta):
"""Base Message Class."""
# The message id to send over the air
id = 0
retry_count = 3
last_send_time = None
last_send_attempt = 0
def __init__(self, fromcall, tocall, msg_id=None):
self.fromcall = fromcall
self.tocall = tocall
if not msg_id:
c = MessageCounter()
c.increment()
msg_id = c.value
self.id = msg_id
@abc.abstractmethod
def send(self):
"""Child class must declare."""
pass
class RawMessage(Message):
"""Send a raw message.
This class is used for custom messages that contain the entire
contents of an APRS message in the message field.
"""
message = None
def __init__(self, message):
super().__init__(None, None, msg_id=None)
self.message = message
def __repr__(self):
return self.message
def __str__(self):
return self.message
def send(self):
tracker = MsgTrack()
tracker.add(self)
thread = SendMessageThread(message=self)
thread.start()
def send_direct(self):
"""Send a message without a separate thread."""
cl = client.get_client()
log_message(
"Sending Message Direct",
repr(self).rstrip("\n"),
self.message,
tocall=self.tocall,
fromcall=self.fromcall,
)
cl.sendall(repr(self))
class TextMessage(Message):
"""Send regular ARPS text/command messages/replies."""
message = None
def __init__(self, fromcall, tocall, message, msg_id=None, allow_delay=True):
super().__init__(fromcall, tocall, msg_id)
self.message = message
# do we try and save this message for later if we don't get
# an ack? Some messages we don't want to do this ever.
self.allow_delay = allow_delay
def __repr__(self):
"""Build raw string to send over the air."""
return "{}>APRS::{}:{}{{{}\n".format(
self.fromcall,
self.tocall.ljust(9),
self._filter_for_send(),
str(self.id),
)
def __str__(self):
delta = "Never"
if self.last_send_time:
now = datetime.datetime.now()
delta = now - self.last_send_time
return "{}>{} Msg({})({}): '{}'".format(
self.fromcall,
self.tocall,
self.id,
delta,
self.message,
)
def _filter_for_send(self):
"""Filter and format message string for FCC."""
# max? ftm400 displays 64, raw msg shows 74
# and ftm400-send is max 64. setting this to
# 67 displays 64 on the ftm400. (+3 {01 suffix)
# feature req: break long ones into two msgs
message = self.message[:67]
# We all miss George Carlin
return re.sub("fuck|shit|cunt|piss|cock|bitch", "****", message)
def send(self):
tracker = MsgTrack()
tracker.add(self)
LOG.debug("Length of MsgTrack is {}".format(len(tracker)))
thread = SendMessageThread(message=self)
thread.start()
def send_direct(self):
"""Send a message without a separate thread."""
cl = client.get_client()
log_message(
"Sending Message Direct",
repr(self).rstrip("\n"),
self.message,
tocall=self.tocall,
fromcall=self.fromcall,
)
cl.sendall(repr(self))
class SendMessageThread(threads.APRSDThread):
def __init__(self, message):
self.msg = message
name = self.msg.message[:5]
super().__init__("SendMessage-{}-{}".format(self.msg.id, name))
def loop(self):
"""Loop until a message is acked or it gets delayed.
We only sleep for 5 seconds between each loop run, so
that CTRL-C can exit the app in a short period. Each sleep
means the app quitting is blocked until sleep is done.
So we keep track of the last send attempt and only send if the
last send attempt is old enough.
"""
cl = client.get_client()
tracker = MsgTrack()
# lets see if the message is still in the tracking queue
msg = tracker.get(self.msg.id)
if not msg:
# The message has been removed from the tracking queue
# So it got acked and we are done.
LOG.info("Message Send Complete via Ack.")
return False
else:
send_now = False
if msg.last_send_attempt == msg.retry_count:
# we reached the send limit, don't send again
# TODO(hemna) - Need to put this in a delayed queue?
LOG.info("Message Send Complete. Max attempts reached.")
return False
# Message is still outstanding and needs to be acked.
if msg.last_send_time:
# Message has a last send time tracking
now = datetime.datetime.now()
sleeptime = (msg.last_send_attempt + 1) * 31
delta = now - msg.last_send_time
if delta > datetime.timedelta(seconds=sleeptime):
# It's time to try to send it again
send_now = True
else:
send_now = True
if send_now:
# no attempt time, so lets send it, and start
# tracking the time.
log_message(
"Sending Message",
repr(msg).rstrip("\n"),
msg.message,
tocall=self.msg.tocall,
retry_number=msg.last_send_attempt,
msg_num=msg.id,
)
cl.sendall(repr(msg))
msg.last_send_time = datetime.datetime.now()
msg.last_send_attempt += 1
time.sleep(5)
# Make sure we get called again.
return True
class AckMessage(Message):
"""Class for building Acks and sending them."""
def __init__(self, fromcall, tocall, msg_id):
super().__init__(fromcall, tocall, msg_id=msg_id)
def __repr__(self):
return "{}>APRS::{}:ack{}\n".format(
self.fromcall,
self.tocall.ljust(9),
self.id,
)
def __str__(self):
return "From({}) TO({}) Ack ({})".format(self.fromcall, self.tocall, self.id)
def send_thread(self):
"""Separate thread to send acks with retries."""
cl = client.get_client()
for i in range(self.retry_count, 0, -1):
log_message(
"Sending ack",
repr(self).rstrip("\n"),
None,
ack=self.id,
tocall=self.tocall,
retry_number=i,
)
cl.sendall(repr(self))
# aprs duplicate detection is 30 secs?
# (21 only sends first, 28 skips middle)
time.sleep(31)
# end_send_ack_thread
def send(self):
LOG.debug("Send ACK({}:{}) to radio.".format(self.tocall, self.id))
thread = SendAckThread(self)
thread.start()
# end send_ack()
def send_direct(self):
"""Send an ack message without a separate thread."""
cl = client.get_client()
log_message(
"Sending ack",
repr(self).rstrip("\n"),
None,
ack=self.id,
tocall=self.tocall,
fromcall=self.fromcall,
)
cl.sendall(repr(self))
class SendAckThread(threads.APRSDThread):
def __init__(self, ack):
self.ack = ack
super().__init__("SendAck-{}".format(self.ack.id))
def loop(self):
"""Separate thread to send acks with retries."""
send_now = False
if self.ack.last_send_attempt == self.ack.retry_count:
# we reached the send limit, don't send again
# TODO(hemna) - Need to put this in a delayed queue?
LOG.info("Ack Send Complete. Max attempts reached.")
return False
if self.ack.last_send_time:
# Message has a last send time tracking
now = datetime.datetime.now()
# aprs duplicate detection is 30 secs?
# (21 only sends first, 28 skips middle)
sleeptime = 31
delta = now - self.ack.last_send_time
if delta > datetime.timedelta(seconds=sleeptime):
# It's time to try to send it again
send_now = True
else:
LOG.debug("Still wating. {}".format(delta))
else:
send_now = True
if send_now:
cl = client.get_client()
log_message(
"Sending ack",
repr(self.ack).rstrip("\n"),
None,
ack=self.ack.id,
tocall=self.ack.tocall,
retry_number=self.ack.last_send_attempt,
)
cl.sendall(repr(self.ack))
self.ack.last_send_attempt += 1
self.ack.last_send_time = datetime.datetime.now()
time.sleep(5)
def log_packet(packet):
fromcall = packet.get("from", None)
tocall = packet.get("to", None)
response_type = packet.get("response", None)
msg = packet.get("message_text", None)
msg_num = packet.get("msgNo", None)
ack = packet.get("ack", None)
log_message(
"Packet",
packet["raw"],
msg,
fromcall=fromcall,
tocall=tocall,
ack=ack,
packet_type=response_type,
msg_num=msg_num,
)
def log_message(
header,
raw,
message,
tocall=None,
fromcall=None,
msg_num=None,
retry_number=None,
ack=None,
packet_type=None,
uuid=None,
):
"""
Log a message entry.
This builds a long string with newlines for the log entry, so that
it's thread safe. If we log each item as a separate log.debug() call
Then the message information could get multiplexed with other log
messages. Each python log call is automatically synchronized.
"""
log_list = [""]
if retry_number:
# LOG.info(" {} _______________(TX:{})".format(header, retry_number))
log_list.append(" {} _______________(TX:{})".format(header, retry_number))
else:
# LOG.info(" {} _______________".format(header))
log_list.append(" {} _______________".format(header))
# LOG.info(" Raw : {}".format(raw))
log_list.append(" Raw : {}".format(raw))
if packet_type:
# LOG.info(" Packet : {}".format(packet_type))
log_list.append(" Packet : {}".format(packet_type))
if tocall:
# LOG.info(" To : {}".format(tocall))
log_list.append(" To : {}".format(tocall))
if fromcall:
# LOG.info(" From : {}".format(fromcall))
log_list.append(" From : {}".format(fromcall))
if ack:
# LOG.info(" Ack : {}".format(ack))
log_list.append(" Ack : {}".format(ack))
else:
# LOG.info(" Message : {}".format(message))
log_list.append(" Message : {}".format(message))
if msg_num:
# LOG.info(" Msg number : {}".format(msg_num))
log_list.append(" Msg number : {}".format(msg_num))
if uuid:
log_list.append(" UUID : {}".format(uuid))
# LOG.info(" {} _______________ Complete".format(header))
log_list.append(" {} _______________ Complete".format(header))
LOG.info("\n".join(log_list))
+158 -269
View File
@@ -1,21 +1,15 @@
# The base plugin class
import abc
import fnmatch
import importlib
import inspect
import json
import logging
import os
import re
import subprocess
import time
import pluggy
import requests
import six
from thesmuggler import smuggle
from aprsd.fuzzyclock import fuzzy
# setup the global logger
LOG = logging.getLogger("APRSD")
@@ -23,107 +17,17 @@ hookspec = pluggy.HookspecMarker("aprsd")
hookimpl = pluggy.HookimplMarker("aprsd")
CORE_PLUGINS = [
"FortunePlugin",
"LocationPlugin",
"PingPlugin",
"TimePlugin",
"WeatherPlugin",
"aprsd.plugins.email.EmailPlugin",
"aprsd.plugins.fortune.FortunePlugin",
"aprsd.plugins.location.LocationPlugin",
"aprsd.plugins.ping.PingPlugin",
"aprsd.plugins.query.QueryPlugin",
"aprsd.plugins.time.TimePlugin",
"aprsd.plugins.weather.WeatherPlugin",
"aprsd.plugins.version.VersionPlugin",
]
def setup_plugins(config):
"""Create the plugin manager and register plugins."""
LOG.info("Loading Core APRSD Command Plugins")
enabled_plugins = config["aprsd"].get("enabled_plugins", None)
pm = pluggy.PluginManager("aprsd")
pm.add_hookspecs(APRSDCommandSpec)
for p_name in CORE_PLUGINS:
plugin_obj = None
if enabled_plugins:
if p_name in enabled_plugins:
plugin_obj = globals()[p_name](config)
else:
# Enabled plugins isn't set, so we default to loading all of
# the core plugins.
plugin_obj = globals()[p_name](config)
if plugin_obj:
LOG.info(
"Registering Command plugin '{}'({}) '{}'".format(
p_name, plugin_obj.version, plugin_obj.command_regex
)
)
pm.register(plugin_obj)
plugin_dir = config["aprsd"].get("plugin_dir", None)
if plugin_dir:
LOG.info("Trying to load custom plugins from '{}'".format(plugin_dir))
cpm = PluginManager(config)
plugins_list = cpm.load_plugins(plugin_dir)
LOG.info("Discovered {} modules to load".format(len(plugins_list)))
for o in plugins_list:
plugin_obj = None
if enabled_plugins:
if o["name"] in enabled_plugins:
plugin_obj = o["obj"]
else:
LOG.info(
"'{}' plugin not listed in config aprsd:enabled_plugins".format(
o["name"]
)
)
else:
# not setting enabled plugins means load all?
plugin_obj = o["obj"]
if plugin_obj:
LOG.info(
"Registering Command plugin '{}'({}) '{}'".format(
o["name"], o["obj"].version, o["obj"].command_regex
)
)
pm.register(o["obj"])
else:
LOG.info("Skipping Custom Plugins.")
LOG.info("Completed Plugin Loading.")
return pm
class PluginManager(object):
def __init__(self, config):
self.obj_list = []
self.config = config
def load_plugins(self, module_path):
dir_path = os.path.realpath(module_path)
pattern = "*.py"
self.obj_list = []
for path, subdirs, files in os.walk(dir_path):
for name in files:
if fnmatch.fnmatch(name, pattern):
LOG.debug("MODULE? '{}' '{}'".format(name, path))
module = smuggle("{}/{}".format(path, name))
for mem_name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and self.is_plugin(obj):
self.obj_list.append(
{"name": mem_name, "obj": obj(self.config)}
)
return self.obj_list
def is_plugin(self, obj):
for c in inspect.getmro(obj):
if issubclass(c, APRSDPluginBase):
return True
return False
class APRSDCommandSpec:
"""A hook specification namespace."""
@@ -133,8 +37,7 @@ class APRSDCommandSpec:
pass
@six.add_metaclass(abc.ABCMeta)
class APRSDPluginBase(object):
class APRSDPluginBase(metaclass=abc.ABCMeta):
def __init__(self, config):
"""The aprsd config object is stored."""
self.config = config
@@ -169,176 +72,162 @@ class APRSDPluginBase(object):
pass
class FortunePlugin(APRSDPluginBase):
"""Fortune."""
class PluginManager:
# The singleton instance object for this class
_instance = None
version = "1.0"
command_regex = "^[fF]"
command_name = "fortune"
# the pluggy PluginManager
_pluggy_pm = None
def command(self, fromcall, message, ack):
LOG.info("FortunePlugin")
reply = None
# aprsd config dict
config = None
def __new__(cls, *args, **kwargs):
"""This magic turns this into a singleton."""
if cls._instance is None:
cls._instance = super().__new__(cls)
# Put any initialization here.
return cls._instance
def __init__(self, config=None):
self.obj_list = []
if config:
self.config = config
def load_plugins_from_path(self, module_path):
if not os.path.exists(module_path):
LOG.error("plugin path '{}' doesn't exist.".format(module_path))
return None
dir_path = os.path.realpath(module_path)
pattern = "*.py"
self.obj_list = []
for path, _subdirs, files in os.walk(dir_path):
for name in files:
if fnmatch.fnmatch(name, pattern):
LOG.debug("MODULE? '{}' '{}'".format(name, path))
module = smuggle("{}/{}".format(path, name))
for mem_name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and self.is_plugin(obj):
self.obj_list.append(
{"name": mem_name, "obj": obj(self.config)},
)
return self.obj_list
def is_plugin(self, obj):
for c in inspect.getmro(obj):
if issubclass(c, APRSDPluginBase):
return True
return False
def _create_class(self, module_class_string, super_cls: type = None, **kwargs):
"""
Method to create a class from a fqn python string.
:param module_class_string: full name of the class to create an object of
:param super_cls: expected super class for validity, None if bypass
:param kwargs: parameters to pass
:return:
"""
module_name, class_name = module_class_string.rsplit(".", 1)
try:
process = subprocess.Popen(
["/usr/games/fortune", "-s", "-n 60"], stdout=subprocess.PIPE
)
reply = process.communicate()[0]
# send_message(fromcall, reply.rstrip())
reply = reply.decode(errors="ignore").rstrip()
module = importlib.import_module(module_name)
except Exception as ex:
reply = "Fortune command failed '{}'".format(ex)
LOG.error(reply)
LOG.error("Failed to load Plugin '{}' : '{}'".format(module_name, ex))
return
return reply
class LocationPlugin(APRSDPluginBase):
"""Location!"""
version = "1.0"
command_regex = "^[lL]"
command_name = "location"
def command(self, fromcall, message, ack):
LOG.info("Location Plugin")
# get last location of a callsign, get descriptive name from weather service
try:
a = re.search(
r"^.*\s+(.*)", message
) # optional second argument is a callsign to search
if a is not None:
searchcall = a.group(1)
searchcall = searchcall.upper()
else:
searchcall = (
fromcall # if no second argument, search for calling station
)
url = (
"http://api.aprs.fi/api/get?name="
+ searchcall
+ "&what=loc&apikey=104070.f9lE8qg34L8MZF&format=json"
)
response = requests.get(url)
# aprs_data = json.loads(response.read())
aprs_data = json.loads(response.text)
lat = aprs_data["entries"][0]["lat"]
lon = aprs_data["entries"][0]["lng"]
try: # altitude not always provided
alt = aprs_data["entries"][0]["altitude"]
except Exception:
alt = 0
altfeet = int(alt * 3.28084)
aprs_lasttime_seconds = aprs_data["entries"][0]["lasttime"]
aprs_lasttime_seconds = aprs_lasttime_seconds.encode(
"ascii", errors="ignore"
) # unicode to ascii
delta_seconds = time.time() - int(aprs_lasttime_seconds)
delta_hours = delta_seconds / 60 / 60
url2 = (
"https://forecast.weather.gov/MapClick.php?lat="
+ str(lat)
+ "&lon="
+ str(lon)
+ "&FcstType=json"
)
response2 = requests.get(url2)
wx_data = json.loads(response2.text)
reply = "{}: {} {}' {},{} {}h ago".format(
searchcall,
wx_data["location"]["areaDescription"],
str(altfeet),
str(alt),
str(lon),
str("%.1f" % round(delta_hours, 1)),
).rstrip()
except Exception as e:
LOG.debug("Locate failed with: " + "%s" % str(e))
reply = "Unable to find station " + searchcall + ". Sending beacons?"
return reply
class PingPlugin(APRSDPluginBase):
"""Ping."""
version = "1.0"
command_regex = "^[pP]"
command_name = "ping"
def command(self, fromcall, message, ack):
LOG.info("PINGPlugin")
stm = time.localtime()
h = stm.tm_hour
m = stm.tm_min
s = stm.tm_sec
reply = (
"Pong! " + str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)
assert hasattr(module, class_name), "class {} is not in {}".format(
class_name,
module_name,
)
return reply.rstrip()
# click.echo('reading class {} from module {}'.format(
# class_name, module_name))
cls = getattr(module, class_name)
if super_cls is not None:
assert issubclass(cls, super_cls), "class {} should inherit from {}".format(
class_name,
super_cls.__name__,
)
# click.echo('initialising {} with params {}'.format(class_name, kwargs))
obj = cls(**kwargs)
return obj
class TimePlugin(APRSDPluginBase):
"""Time command."""
version = "1.0"
command_regex = "^[tT]"
command_name = "time"
def command(self, fromcall, message, ack):
LOG.info("TIME COMMAND")
stm = time.localtime()
h = stm.tm_hour
m = stm.tm_min
cur_time = fuzzy(h, m, 1)
reply = "{} ({}:{} PDT) ({})".format(
cur_time, str(h), str(m).rjust(2, "0"), message.rstrip()
)
return reply
class WeatherPlugin(APRSDPluginBase):
"""Weather Command"""
version = "1.0"
command_regex = "^[wW]"
command_name = "weather"
def command(self, fromcall, message, ack):
LOG.info("Weather Plugin")
def _load_plugin(self, plugin_name):
"""
Given a python fully qualified class path.name,
Try importing the path, then creating the object,
then registering it as a aprsd Command Plugin
"""
plugin_obj = None
try:
url = (
"http://api.aprs.fi/api/get?"
"&what=loc&apikey=104070.f9lE8qg34L8MZF&format=json"
"&name=%s" % fromcall
plugin_obj = self._create_class(
plugin_name,
APRSDPluginBase,
config=self.config,
)
response = requests.get(url)
# aprs_data = json.loads(response.read())
aprs_data = json.loads(response.text)
lat = aprs_data["entries"][0]["lat"]
lon = aprs_data["entries"][0]["lng"]
url2 = (
"https://forecast.weather.gov/MapClick.php?lat=%s"
"&lon=%s&FcstType=json" % (lat, lon)
)
response2 = requests.get(url2)
# wx_data = json.loads(response2.read())
wx_data = json.loads(response2.text)
reply = (
"%sF(%sF/%sF) %s. %s, %s."
% (
wx_data["currentobservation"]["Temp"],
wx_data["data"]["temperature"][0],
wx_data["data"]["temperature"][1],
wx_data["data"]["weather"][0],
wx_data["time"]["startPeriodName"][1],
wx_data["data"]["weather"][1],
if plugin_obj:
LOG.info(
"Registering Command plugin '{}'({}) '{}'".format(
plugin_name,
plugin_obj.version,
plugin_obj.command_regex,
),
)
).rstrip()
LOG.debug("reply: '{}' ".format(reply))
except Exception as e:
LOG.debug("Weather failed with: " + "%s" % str(e))
reply = "Unable to find you (send beacon?)"
self._pluggy_pm.register(plugin_obj)
except Exception as ex:
LOG.exception("Couldn't load plugin '{}'".format(plugin_name), ex)
return reply
def setup_plugins(self):
"""Create the plugin manager and register plugins."""
LOG.info("Loading Core APRSD Command Plugins")
enabled_plugins = self.config["aprsd"].get("enabled_plugins", None)
self._pluggy_pm = pluggy.PluginManager("aprsd")
self._pluggy_pm.add_hookspecs(APRSDCommandSpec)
if enabled_plugins:
for p_name in enabled_plugins:
self._load_plugin(p_name)
else:
# Enabled plugins isn't set, so we default to loading all of
# the core plugins.
for p_name in CORE_PLUGINS:
self._load_plugin(p_name)
plugin_dir = self.config["aprsd"].get("plugin_dir", None)
if plugin_dir:
LOG.info("Trying to load custom plugins from '{}'".format(plugin_dir))
plugins_list = self.load_plugins_from_path(plugin_dir)
if plugins_list:
LOG.info("Discovered {} modules to load".format(len(plugins_list)))
for o in plugins_list:
plugin_obj = None
# not setting enabled plugins means load all?
plugin_obj = o["obj"]
if plugin_obj:
LOG.info(
"Registering Command plugin '{}'({}) '{}'".format(
o["name"],
o["obj"].version,
o["obj"].command_regex,
),
)
self._pluggy_pm.register(o["obj"])
else:
LOG.info("Skipping Custom Plugins directory.")
LOG.info("Completed Plugin Loading.")
def run(self, *args, **kwargs):
"""Execute all the pluguns run method."""
return self._pluggy_pm.hook.run(*args, **kwargs)
def register(self, obj):
"""Register the plugin."""
self._pluggy_pm.register(obj)
def get_plugins(self):
return self._pluggy_pm.get_plugins()
View File
+88
View File
@@ -0,0 +1,88 @@
import logging
import re
import time
from aprsd import email, messaging, plugin
LOG = logging.getLogger("APRSD")
class EmailPlugin(plugin.APRSDPluginBase):
"""Email Plugin."""
version = "1.0"
command_regex = "^-.*"
command_name = "email"
# message_number:time combos so we don't resend the same email in
# five mins {int:int}
email_sent_dict = {}
def command(self, fromcall, message, ack):
LOG.info("Email COMMAND")
reply = None
searchstring = "^" + self.config["ham"]["callsign"] + ".*"
# only I can do email
if re.search(searchstring, fromcall):
# digits only, first one is number of emails to resend
r = re.search("^-([0-9])[0-9]*$", message)
if r is not None:
LOG.debug("RESEND EMAIL")
email.resend_email(r.group(1), fromcall)
reply = messaging.NULL_MESSAGE
# -user@address.com body of email
elif re.search(r"^-([A-Za-z0-9_\-\.@]+) (.*)", message):
# (same search again)
a = re.search(r"^-([A-Za-z0-9_\-\.@]+) (.*)", message)
if a is not None:
to_addr = a.group(1)
content = a.group(2)
email_address = email.get_email_from_shortcut(to_addr)
if not email_address:
reply = "Bad email address"
return reply
# send recipient link to aprs.fi map
if content == "mapme":
content = "Click for my location: http://aprs.fi/{}".format(
self.config["ham"]["callsign"],
)
too_soon = 0
now = time.time()
# see if we sent this msg number recently
if ack in self.email_sent_dict:
# BUG(hemna) - when we get a 2 different email command
# with the same ack #, we don't send it.
timedelta = now - self.email_sent_dict[ack]
if timedelta < 300: # five minutes
too_soon = 1
if not too_soon or ack == 0:
LOG.info("Send email '{}'".format(content))
send_result = email.send_email(to_addr, content)
reply = messaging.NULL_MESSAGE
if send_result != 0:
reply = "-{} failed".format(to_addr)
# messaging.send_message(fromcall, "-" + to_addr + " failed")
else:
# clear email sent dictionary if somehow goes over 100
if len(self.email_sent_dict) > 98:
LOG.debug(
"DEBUG: email_sent_dict is big ("
+ str(len(self.email_sent_dict))
+ ") clearing out.",
)
self.email_sent_dict.clear()
self.email_sent_dict[ack] = now
else:
LOG.info(
"Email for message number "
+ ack
+ " recently sent, not sending again.",
)
else:
reply = "Bad email address"
# messaging.send_message(fromcall, "Bad email address")
return reply
+40
View File
@@ -0,0 +1,40 @@
import logging
import shutil
import subprocess
from aprsd import plugin
LOG = logging.getLogger("APRSD")
class FortunePlugin(plugin.APRSDPluginBase):
"""Fortune."""
version = "1.0"
command_regex = "^[fF]"
command_name = "fortune"
def command(self, fromcall, message, ack):
LOG.info("FortunePlugin")
reply = None
fortune_path = shutil.which("fortune")
if not fortune_path:
reply = "Fortune command not installed"
return reply
try:
cmnd = [fortune_path, "-s", "-n 60"]
command = " ".join(cmnd)
output = subprocess.check_output(
command,
shell=True,
timeout=3,
universal_newlines=True,
)
except subprocess.CalledProcessError as ex:
reply = "Fortune command failed '{}'".format(ex.output)
else:
reply = output
return reply
+78
View File
@@ -0,0 +1,78 @@
import json
import logging
import re
import time
from aprsd import plugin
import requests
LOG = logging.getLogger("APRSD")
class LocationPlugin(plugin.APRSDPluginBase):
"""Location!"""
version = "1.0"
command_regex = "^[lL]"
command_name = "location"
config_items = {"apikey": "aprs.fi api key here"}
def command(self, fromcall, message, ack):
LOG.info("Location Plugin")
# get last location of a callsign, get descriptive name from weather service
api_key = self.config["aprs.fi"]["apiKey"]
try:
# optional second argument is a callsign to search
a = re.search(r"^.*\s+(.*)", message)
if a is not None:
searchcall = a.group(1)
searchcall = searchcall.upper()
else:
# if no second argument, search for calling station
searchcall = fromcall
url = (
"http://api.aprs.fi/api/get?name="
+ searchcall
+ "&what=loc&apikey={}&format=json".format(api_key)
)
response = requests.get(url)
# aprs_data = json.loads(response.read())
aprs_data = json.loads(response.text)
LOG.debug("LocationPlugin: aprs_data = {}".format(aprs_data))
lat = aprs_data["entries"][0]["lat"]
lon = aprs_data["entries"][0]["lng"]
try: # altitude not always provided
alt = aprs_data["entries"][0]["altitude"]
except Exception:
alt = 0
altfeet = int(alt * 3.28084)
aprs_lasttime_seconds = aprs_data["entries"][0]["lasttime"]
# aprs_lasttime_seconds = aprs_lasttime_seconds.encode(
# "ascii", errors="ignore"
# ) # unicode to ascii
delta_seconds = time.time() - int(aprs_lasttime_seconds)
delta_hours = delta_seconds / 60 / 60
url2 = (
"https://forecast.weather.gov/MapClick.php?lat="
+ str(lat)
+ "&lon="
+ str(lon)
+ "&FcstType=json"
)
response2 = requests.get(url2)
wx_data = json.loads(response2.text)
reply = "{}: {} {}' {},{} {}h ago".format(
searchcall,
wx_data["location"]["areaDescription"],
str(altfeet),
str(lat),
str(lon),
str("%.1f" % round(delta_hours, 1)),
).rstrip()
except Exception as e:
LOG.debug("Locate failed with: " + "%s" % str(e))
reply = "Unable to find station " + searchcall + ". Sending beacons?"
return reply
+25
View File
@@ -0,0 +1,25 @@
import logging
import time
from aprsd import plugin
LOG = logging.getLogger("APRSD")
class PingPlugin(plugin.APRSDPluginBase):
"""Ping."""
version = "1.0"
command_regex = "^[pP]"
command_name = "ping"
def command(self, fromcall, message, ack):
LOG.info("PINGPlugin")
stm = time.localtime()
h = stm.tm_hour
m = stm.tm_min
s = stm.tm_sec
reply = (
"Pong! " + str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)
)
return reply.rstrip()
+64
View File
@@ -0,0 +1,64 @@
import datetime
import logging
import re
from aprsd import messaging, plugin
LOG = logging.getLogger("APRSD")
class QueryPlugin(plugin.APRSDPluginBase):
"""Query command."""
version = "1.0"
command_regex = r"^\?.*"
command_name = "query"
def command(self, fromcall, message, ack):
LOG.info("Query COMMAND")
tracker = messaging.MsgTrack()
now = datetime.datetime.now()
reply = "Pending messages ({}) {}".format(
len(tracker),
now.strftime("%H:%M:%S"),
)
searchstring = "^" + self.config["ham"]["callsign"] + ".*"
# only I can do admin commands
if re.search(searchstring, fromcall):
# resend last N most recent: "?3"
r = re.search(r"^\?([0-9]).*", message)
if r is not None:
if len(tracker) > 0:
last_n = r.group(1)
reply = messaging.NULL_MESSAGE
LOG.debug(reply)
tracker.restart_delayed(count=int(last_n))
else:
reply = "No pending msgs to resend"
LOG.debug(reply)
return reply
# resend all: "?a"
r = re.search(r"^\?[aA].*", message)
if r is not None:
if len(tracker) > 0:
reply = messaging.NULL_MESSAGE
LOG.debug(reply)
tracker.restart_delayed()
else:
reply = "No pending msgs"
LOG.debug(reply)
return reply
# delete all: "?d"
r = re.search(r"^\?[dD].*", message)
if r is not None:
reply = "Deleted ALL pending msgs."
LOG.debug(reply)
tracker.flush()
return reply
return reply
+28
View File
@@ -0,0 +1,28 @@
import logging
import time
from aprsd import fuzzyclock, plugin
LOG = logging.getLogger("APRSD")
class TimePlugin(plugin.APRSDPluginBase):
"""Time command."""
version = "1.0"
command_regex = "^[tT]"
command_name = "time"
def command(self, fromcall, message, ack):
LOG.info("TIME COMMAND")
stm = time.localtime()
h = stm.tm_hour
m = stm.tm_min
cur_time = fuzzyclock.fuzzy(h, m, 1)
reply = "{} ({}:{} PDT) ({})".format(
cur_time,
str(h),
str(m).rjust(2, "0"),
message.rstrip(),
)
return reply
+22
View File
@@ -0,0 +1,22 @@
import logging
import aprsd
from aprsd import plugin
LOG = logging.getLogger("APRSD")
class VersionPlugin(plugin.APRSDPluginBase):
"""Version of APRSD Plugin."""
version = "1.0"
command_regex = "^[vV]"
command_name = "version"
# message_number:time combos so we don't resend the same email in
# five mins {int:int}
email_sent_dict = {}
def command(self, fromcall, message, ack):
LOG.info("Version COMMAND")
return "APRSD version '{}'".format(aprsd.__version__)
+54
View File
@@ -0,0 +1,54 @@
import json
import logging
from aprsd import plugin
import requests
LOG = logging.getLogger("APRSD")
class WeatherPlugin(plugin.APRSDPluginBase):
"""Weather Command"""
version = "1.0"
command_regex = "^[wW]"
command_name = "weather"
def command(self, fromcall, message, ack):
LOG.info("Weather Plugin")
api_key = self.config["aprs.fi"]["apiKey"]
try:
url = (
"http://api.aprs.fi/api/get?"
"&what=loc&apikey={}&format=json"
"&name={}".format(api_key, fromcall)
)
response = requests.get(url)
# aprs_data = json.loads(response.read())
aprs_data = json.loads(response.text)
lat = aprs_data["entries"][0]["lat"]
lon = aprs_data["entries"][0]["lng"]
url2 = (
"https://forecast.weather.gov/MapClick.php?lat=%s"
"&lon=%s&FcstType=json" % (lat, lon)
)
response2 = requests.get(url2)
# wx_data = json.loads(response2.read())
wx_data = json.loads(response2.text)
reply = (
"%sF(%sF/%sF) %s. %s, %s."
% (
wx_data["currentobservation"]["Temp"],
wx_data["data"]["temperature"][0],
wx_data["data"]["temperature"][1],
wx_data["data"]["weather"][0],
wx_data["time"]["startPeriodName"][1],
wx_data["data"]["weather"][1],
)
).rstrip()
LOG.debug("reply: '{}' ".format(reply))
except Exception as e:
LOG.debug("Weather failed with: " + "%s" % str(e))
reply = "Unable to find you (send beacon?)"
return reply
+234
View File
@@ -0,0 +1,234 @@
import abc
import logging
import queue
import threading
import time
from aprsd import client, messaging, plugin
import aprslib
LOG = logging.getLogger("APRSD")
RX_THREAD = "RX"
TX_THREAD = "TX"
EMAIL_THREAD = "Email"
class APRSDThreadList:
"""Singleton class that keeps track of application wide threads."""
_instance = None
threads_list = []
lock = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls.lock = threading.Lock()
cls.threads_list = []
return cls._instance
def add(self, thread_obj):
with self.lock:
self.threads_list.append(thread_obj)
def remove(self, thread_obj):
with self.lock:
self.threads_list.remove(thread_obj)
def stop_all(self):
"""Iterate over all threads and call stop on them."""
with self.lock:
for th in self.threads_list:
th.stop()
class APRSDThread(threading.Thread, metaclass=abc.ABCMeta):
def __init__(self, name):
super().__init__(name=name)
self.thread_stop = False
APRSDThreadList().add(self)
def stop(self):
self.thread_stop = True
def run(self):
LOG.debug("Starting")
while not self.thread_stop:
can_loop = self.loop()
if not can_loop:
self.stop()
APRSDThreadList().remove(self)
LOG.debug("Exiting")
class APRSDRXThread(APRSDThread):
def __init__(self, msg_queues, config):
super().__init__("RX_MSG")
self.msg_queues = msg_queues
self.config = config
def stop(self):
self.thread_stop = True
client.get_client().stop()
def callback(self, packet):
try:
packet = aprslib.parse(packet)
print(packet)
except (aprslib.ParseError, aprslib.UnknownFormat):
pass
def loop(self):
aprs_client = client.get_client()
# setup the consumer of messages and block until a messages
try:
# This will register a packet consumer with aprslib
# When new packets come in the consumer will process
# the packet
# Do a partial here because the consumer signature doesn't allow
# For kwargs to be passed in to the consumer func we declare
# and the aprslib developer didn't want to allow a PR to add
# kwargs. :(
# https://github.com/rossengeorgiev/aprs-python/pull/56
aprs_client.consumer(self.process_packet, raw=False, blocking=False)
except aprslib.exceptions.ConnectionDrop:
LOG.error("Connection dropped, reconnecting")
time.sleep(5)
# Force the deletion of the client object connected to aprs
# This will cause a reconnect, next time client.get_client()
# is called
client.Client().reset()
# Continue to loop
return True
def process_ack_packet(self, packet):
ack_num = packet.get("msgNo")
LOG.info("Got ack for message {}".format(ack_num))
messaging.log_message(
"ACK",
packet["raw"],
None,
ack=ack_num,
fromcall=packet["from"],
)
tracker = messaging.MsgTrack()
tracker.remove(ack_num)
return
def process_mic_e_packet(self, packet):
LOG.info("Mic-E Packet detected. Currenlty unsupported.")
messaging.log_packet(packet)
return
def process_message_packet(self, packet):
fromcall = packet["from"]
message = packet.get("message_text", None)
msg_id = packet.get("msgNo", "0")
messaging.log_message(
"Received Message",
packet["raw"],
message,
fromcall=fromcall,
msg_num=msg_id,
)
found_command = False
# Get singleton of the PM
pm = plugin.PluginManager()
try:
results = pm.run(fromcall=fromcall, message=message, ack=msg_id)
for reply in results:
found_command = True
# A plugin can return a null message flag which signals
# us that they processed the message correctly, but have
# nothing to reply with, so we avoid replying with a usage string
if reply is not messaging.NULL_MESSAGE:
LOG.debug("Sending '{}'".format(reply))
msg = messaging.TextMessage(
self.config["aprs"]["login"],
fromcall,
reply,
)
self.msg_queues["tx"].put(msg)
else:
LOG.debug("Got NULL MESSAGE from plugin")
if not found_command:
plugins = pm.get_plugins()
names = [x.command_name for x in plugins]
names.sort()
# reply = "Usage: {}".format(", ".join(names))
reply = "Usage: weather, locate [call], time, fortune, ping"
msg = messaging.TextMessage(
self.config["aprs"]["login"],
fromcall,
reply,
)
self.msg_queues["tx"].put(msg)
except Exception as ex:
LOG.exception("Plugin failed!!!", ex)
reply = "A Plugin failed! try again?"
msg = messaging.TextMessage(self.config["aprs"]["login"], fromcall, reply)
self.msg_queues["tx"].put(msg)
# let any threads do their thing, then ack
# send an ack last
ack = messaging.AckMessage(
self.config["aprs"]["login"],
fromcall,
msg_id=msg_id,
)
self.msg_queues["tx"].put(ack)
LOG.debug("Packet processing complete")
def process_packet(self, packet):
"""Process a packet recieved from aprs-is server."""
try:
LOG.info("Got message: {}".format(packet))
msg = packet.get("message_text", None)
msg_format = packet.get("format", None)
msg_response = packet.get("response", None)
if msg_format == "message" and msg:
# we want to send the message through the
# plugins
self.process_message_packet(packet)
return
elif msg_response == "ack":
self.process_ack_packet(packet)
return
if msg_format == "mic-e":
# process a mic-e packet
self.process_mic_e_packet(packet)
return
except (aprslib.ParseError, aprslib.UnknownFormat) as exp:
LOG.exception("Failed to parse packet from aprs-is", exp)
class APRSDTXThread(APRSDThread):
def __init__(self, msg_queues, config):
super().__init__("TX_MSG")
self.msg_queues = msg_queues
self.config = config
def loop(self):
try:
msg = self.msg_queues["tx"].get(timeout=0.1)
msg.send()
except queue.Empty:
pass
# Continue to loop
return True
+78 -20
View File
@@ -1,39 +1,42 @@
"""Utilities and helper functions."""
import errno
import functools
import os
from pathlib import Path
import sys
import threading
from aprsd import plugin
import click
import yaml
from aprsd import plugin
# an example of what should be in the ~/.aprsd/config.yml
DEFAULT_CONFIG_DICT = {
"ham": {"callsign": "KFART"},
"ham": {"callsign": "CALLSIGN"},
"aprs": {
"login": "someusername",
"password": "somepassword",
"host": "noam.aprs2.net",
"login": "CALLSIGN",
"password": "00000",
"host": "rotate.aprs.net",
"port": 14580,
"logfile": "/tmp/arsd.log",
"logfile": "/tmp/aprsd.log",
},
"aprs.fi": {"apiKey": "set me"},
"shortcuts": {
"aa": "5551239999@vtext.com",
"cl": "craiglamparter@somedomain.org",
"wb": "555309@vtext.com",
},
"smtp": {
"login": "something",
"password": "some lame password",
"host": "imap.gmail.com",
"login": "SMTP_USERNAME",
"password": "SMTP_PASSWORD",
"host": "smtp.gmail.com",
"port": 465,
"use_ssl": False,
},
"imap": {
"login": "imapuser",
"password": "something here too",
"login": "IMAP_USERNAME",
"password": "IMAP_PASSWORD",
"host": "imap.gmail.com",
"port": 993,
"use_ssl": True,
@@ -44,7 +47,21 @@ DEFAULT_CONFIG_DICT = {
},
}
DEFAULT_CONFIG_FILE = "~/.config/aprsd/aprsd.yml"
home = str(Path.home())
DEFAULT_CONFIG_DIR = "{}/.config/aprsd/".format(home)
DEFAULT_SAVE_FILE = "{}/.config/aprsd/aprsd.p".format(home)
DEFAULT_CONFIG_FILE = "{}/.config/aprsd/aprsd.yml".format(home)
def synchronized(wrapped):
lock = threading.Lock()
@functools.wraps(wrapped)
def _wrap(*args, **kwargs):
with lock:
return wrapped(*args, **kwargs)
return _wrap
def env(*vars, **kwargs):
@@ -69,6 +86,34 @@ def mkdir_p(path):
raise
def insert_str(string, str_to_insert, index):
return string[:index] + str_to_insert + string[index:]
def end_substr(original, substr):
"""Get the index of the end of the <substr>.
So you can insert a string after <substr>
"""
idx = original.find(substr)
if idx != -1:
idx += len(substr)
return idx
def add_config_comments(raw_yaml):
end_idx = end_substr(raw_yaml, "aprs.fi:")
if end_idx != -1:
# lets insert a comment
raw_yaml = insert_str(
raw_yaml,
"\n # Get the apiKey from your aprs.fi account here: http://aprs.fi/account",
end_idx,
)
return raw_yaml
def create_default_config():
"""Create a default config file."""
# make sure the directory location exists
@@ -78,20 +123,21 @@ def create_default_config():
click.echo("Config dir '{}' doesn't exist, creating.".format(config_dir))
mkdir_p(config_dir)
with open(config_file_expanded, "w+") as cf:
yaml.dump(DEFAULT_CONFIG_DICT, cf)
raw_yaml = yaml.dump(DEFAULT_CONFIG_DICT)
cf.write(add_config_comments(raw_yaml))
def get_config(config_file):
"""This tries to read the yaml config from <config_file>."""
config_file_expanded = os.path.expanduser(config_file)
if os.path.exists(config_file_expanded):
with open(config_file_expanded, "r") as stream:
with open(config_file_expanded) as stream:
config = yaml.load(stream, Loader=yaml.FullLoader)
return config
else:
if config_file == DEFAULT_CONFIG_FILE:
click.echo(
"{} is missing, creating config file".format(config_file_expanded)
"{} is missing, creating config file".format(config_file_expanded),
)
create_default_config()
msg = (
@@ -126,7 +172,10 @@ def parse_config(config_file):
if name and name not in config[section]:
if not default:
fail(
"'%s' was not in '%s' section of config file" % (name, section)
"'{}' was not in '{}' section of config file".format(
name,
section,
),
)
else:
config[section][name] = default
@@ -148,12 +197,21 @@ def parse_config(config_file):
# special check here to make sure user has edited the config file
# and changed the ham callsign
check_option(
config, "ham", "callsign", default_fail=DEFAULT_CONFIG_DICT["ham"]["callsign"]
config,
"ham",
"callsign",
default_fail=DEFAULT_CONFIG_DICT["ham"]["callsign"],
)
check_option(
config,
"aprs.fi",
"apiKey",
default_fail=DEFAULT_CONFIG_DICT["aprs.fi"]["apiKey"],
)
check_option(config, "aprs", "login")
check_option(config, "aprs", "password")
check_option(config, "aprs", "host")
check_option(config, "aprs", "port")
# check_option(config, "aprs", "host")
# check_option(config, "aprs", "port")
check_option(config, "aprs", "logfile", "./aprsd.log")
check_option(config, "imap", "host")
check_option(config, "imap", "login")
+3 -3
View File
@@ -5,11 +5,11 @@ export PATH=$PATH:$HOME/.local/bin
export VIRTUAL_ENV=$HOME/.venv3
source $VIRTUAL_ENV/bin/activate
if [ ! -z "${APRS_PLUGINS}" ]; then
if [ ! -z "${APRSD_PLUGINS}" ]; then
OLDIFS=$IFS
IFS=','
echo "Installing pypi plugins '$APRS_PLUGINS'";
for plugin in ${APRS_PLUGINS}; do
echo "Installing pypi plugins '$APRSD_PLUGINS'";
for plugin in ${APRSD_PLUGINS}; do
IFS=$OLDIFS
# call your procedure/other scripts here below
echo "Installing '$plugin'"
+6 -6
View File
@@ -1,10 +1,10 @@
tox
black
flake8
isort
mypy
pytest
pytest-cov
mypy
flake8
pep8-naming
black
isort
Sphinx
thesmuggler
tox
twine
+160 -53
View File
@@ -4,59 +4,166 @@
#
# pip-compile dev-requirements.in
#
alabaster==0.7.12 # via sphinx
appdirs==1.4.4 # via black, virtualenv
attrs==20.3.0 # via pytest
babel==2.9.0 # via sphinx
black==20.8b1 # via -r dev-requirements.in
certifi==2020.12.5 # via requests
chardet==3.0.4 # via requests
click==7.1.2 # via black
coverage==5.3 # via pytest-cov
distlib==0.3.1 # via virtualenv
docutils==0.16 # via sphinx
filelock==3.0.12 # via tox, virtualenv
flake8-polyfill==1.0.2 # via pep8-naming
flake8==3.8.4 # via -r dev-requirements.in, flake8-polyfill
idna==2.10 # via requests
imagesize==1.2.0 # via sphinx
iniconfig==1.1.1 # via pytest
isort==5.6.4 # via -r dev-requirements.in
jinja2==2.11.2 # via sphinx
markupsafe==1.1.1 # via jinja2
mccabe==0.6.1 # via flake8
mypy-extensions==0.4.3 # via black, mypy
mypy==0.790 # via -r dev-requirements.in
packaging==20.8 # via pytest, sphinx, tox
pathspec==0.8.1 # via black
pep8-naming==0.11.1 # via -r dev-requirements.in
pluggy==0.13.1 # via pytest, tox
py==1.10.0 # via pytest, tox
pycodestyle==2.6.0 # via flake8
pyflakes==2.2.0 # via flake8
pygments==2.7.3 # via sphinx
pyparsing==2.4.7 # via packaging
pytest-cov==2.10.1 # via -r dev-requirements.in
pytest==6.2.0 # via -r dev-requirements.in, pytest-cov
pytz==2020.4 # via babel
regex==2020.11.13 # via black
requests==2.25.0 # via sphinx
six==1.15.0 # via tox, virtualenv
snowballstemmer==2.0.0 # via sphinx
sphinx==3.3.1 # via -r dev-requirements.in
sphinxcontrib-applehelp==1.0.2 # via sphinx
sphinxcontrib-devhelp==1.0.2 # via sphinx
sphinxcontrib-htmlhelp==1.0.3 # via sphinx
sphinxcontrib-jsmath==1.0.1 # via sphinx
sphinxcontrib-qthelp==1.0.3 # via sphinx
sphinxcontrib-serializinghtml==1.1.4 # via sphinx
thesmuggler==1.0.1 # via -r dev-requirements.in
toml==0.10.2 # via black, pytest, tox
tox==3.20.1 # via -r dev-requirements.in
typed-ast==1.4.1 # via black, mypy
typing-extensions==3.7.4.3 # via black, mypy
urllib3==1.26.2 # via requests
virtualenv==20.2.2 # via tox
alabaster==0.7.12
# via sphinx
appdirs==1.4.4
# via
# black
# virtualenv
attrs==20.3.0
# via pytest
babel==2.9.0
# via sphinx
black==20.8b1
# via -r dev-requirements.in
bleach==3.2.1
# via readme-renderer
certifi==2020.12.5
# via requests
chardet==4.0.0
# via requests
click==7.1.2
# via black
colorama==0.4.4
# via twine
coverage==5.3.1
# via pytest-cov
distlib==0.3.1
# via virtualenv
docutils==0.16
# via
# readme-renderer
# sphinx
filelock==3.0.12
# via
# tox
# virtualenv
flake8-polyfill==1.0.2
# via pep8-naming
flake8==3.8.4
# via
# -r dev-requirements.in
# flake8-polyfill
idna==2.10
# via requests
imagesize==1.2.0
# via sphinx
iniconfig==1.1.1
# via pytest
isort==5.7.0
# via -r dev-requirements.in
jinja2==2.11.2
# via sphinx
keyring==21.8.0
# via twine
markupsafe==1.1.1
# via jinja2
mccabe==0.6.1
# via flake8
mypy-extensions==0.4.3
# via
# black
# mypy
mypy==0.790
# via -r dev-requirements.in
packaging==20.8
# via
# bleach
# pytest
# sphinx
# tox
pathspec==0.8.1
# via black
pep8-naming==0.11.1
# via -r dev-requirements.in
pkginfo==1.6.1
# via twine
pluggy==0.13.1
# via
# pytest
# tox
py==1.10.0
# via
# pytest
# tox
pycodestyle==2.6.0
# via flake8
pyflakes==2.2.0
# via flake8
pygments==2.7.3
# via
# readme-renderer
# sphinx
pyparsing==2.4.7
# via packaging
pytest-cov==2.10.1
# via -r dev-requirements.in
pytest==6.2.1
# via
# -r dev-requirements.in
# pytest-cov
pytz==2020.5
# via babel
readme-renderer==28.0
# via twine
regex==2020.11.13
# via black
requests-toolbelt==0.9.1
# via twine
requests==2.25.1
# via
# requests-toolbelt
# sphinx
# twine
rfc3986==1.4.0
# via twine
six==1.15.0
# via
# bleach
# readme-renderer
# tox
# virtualenv
snowballstemmer==2.0.0
# via sphinx
sphinx==3.4.3
# via -r dev-requirements.in
sphinxcontrib-applehelp==1.0.2
# via sphinx
sphinxcontrib-devhelp==1.0.2
# via sphinx
sphinxcontrib-htmlhelp==1.0.3
# via sphinx
sphinxcontrib-jsmath==1.0.1
# via sphinx
sphinxcontrib-qthelp==1.0.3
# via sphinx
sphinxcontrib-serializinghtml==1.1.4
# via sphinx
toml==0.10.2
# via
# black
# pytest
# tox
tox==3.21.0
# via -r dev-requirements.in
tqdm==4.55.1
# via twine
twine==3.3.0
# via -r dev-requirements.in
typed-ast==1.4.2
# via
# black
# mypy
typing-extensions==3.7.4.3
# via
# black
# mypy
urllib3==1.26.2
# via requests
virtualenv==20.2.2
# via tox
webencodings==0.5.1
# via bleach
# The following packages are considered to be unsafe in a requirements file:
# setuptools
+2 -3
View File
@@ -4,9 +4,8 @@ services:
image: hemna6969/aprsd:latest
container_name: aprsd
volumes:
- /opt/docker/aprsd/config:/config
- /opt/docker/aprsd/plugins:/plugins
- $HOME/.config/aprsd:/config
restart: unless-stopped
environment:
- TZ=America/New_York
- APRS_PLUGINS=aprsd-slack-plugin
- APRS_PLUGINS=aprsd-slack-plugin>=1.0.2
View File
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 26 KiB

View File
+77
View File
@@ -0,0 +1,77 @@
aprsd.plugins package
=====================
Submodules
----------
aprsd.plugins.email module
--------------------------
.. automodule:: aprsd.plugins.email
:members:
:undoc-members:
:show-inheritance:
aprsd.plugins.fortune module
----------------------------
.. automodule:: aprsd.plugins.fortune
:members:
:undoc-members:
:show-inheritance:
aprsd.plugins.location module
-----------------------------
.. automodule:: aprsd.plugins.location
:members:
:undoc-members:
:show-inheritance:
aprsd.plugins.ping module
-------------------------
.. automodule:: aprsd.plugins.ping
:members:
:undoc-members:
:show-inheritance:
aprsd.plugins.query module
--------------------------
.. automodule:: aprsd.plugins.query
:members:
:undoc-members:
:show-inheritance:
aprsd.plugins.time module
-------------------------
.. automodule:: aprsd.plugins.time
:members:
:undoc-members:
:show-inheritance:
aprsd.plugins.version module
----------------------------
.. automodule:: aprsd.plugins.version
:members:
:undoc-members:
:show-inheritance:
aprsd.plugins.weather module
----------------------------
.. automodule:: aprsd.plugins.weather
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: aprsd.plugins
:members:
:undoc-members:
:show-inheritance:
+93
View File
@@ -0,0 +1,93 @@
aprsd package
=============
Subpackages
-----------
.. toctree::
:maxdepth: 4
aprsd.plugins
Submodules
----------
aprsd.client module
-------------------
.. automodule:: aprsd.client
:members:
:undoc-members:
:show-inheritance:
aprsd.email module
------------------
.. automodule:: aprsd.email
:members:
:undoc-members:
:show-inheritance:
aprsd.fake\_aprs module
-----------------------
.. automodule:: aprsd.fake_aprs
:members:
:undoc-members:
:show-inheritance:
aprsd.fuzzyclock module
-----------------------
.. automodule:: aprsd.fuzzyclock
:members:
:undoc-members:
:show-inheritance:
aprsd.main module
-----------------
.. automodule:: aprsd.main
:members:
:undoc-members:
:show-inheritance:
aprsd.messaging module
----------------------
.. automodule:: aprsd.messaging
:members:
:undoc-members:
:show-inheritance:
aprsd.plugin module
-------------------
.. automodule:: aprsd.plugin
:members:
:undoc-members:
:show-inheritance:
aprsd.threads module
--------------------
.. automodule:: aprsd.threads
:members:
:undoc-members:
:show-inheritance:
aprsd.utils module
------------------
.. automodule:: aprsd.utils
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: aprsd
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
aprsd
=====
.. toctree::
:maxdepth: 4
aprsd
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Removes temporary Sphinx build artifacts to ensure a clean build.
This is needed if the Python source being documented changes significantly. Old sphinx-apidoc
RST files can be left behind.
"""
from pathlib import Path
import shutil
def main() -> None:
docs_dir = Path(__file__).resolve().parent
for folder in ("_build", "apidoc"):
delete_dir = docs_dir / folder
if delete_dir.exists():
shutil.rmtree(delete_dir)
if __name__ == "__main__":
main()
+188
View File
@@ -0,0 +1,188 @@
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
import os
import sys
sys.path.insert(0, os.path.abspath("../src"))
# -- Project information -----------------------------------------------------
project = "APRSD"
copyright = ""
author = "Craig Lamparter"
# The short X.Y version
version = "v1.5.0"
# The full version, including alpha/beta/rc tags
release = ""
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.doctest",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
"sphinx.ext.napoleon",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"
# The master toctree document.
master_doc = "index"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = None
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
# Override the default alabaster line wrap, which wraps tightly at 940px.
"page_width": "auto",
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = "adoc"
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, "a.tex", "a Documentation", "a", "manual"),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "a", "a Documentation", [author], 1)]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
"a",
"a Documentation",
author,
"a",
"One line description of project.",
"Miscellaneous",
),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ["search.html"]
# -- Extension configuration -------------------------------------------------
# -- Options for todo extension ----------------------------------------------
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
+71
View File
@@ -0,0 +1,71 @@
APRSD Configure
===============
Configure APRSD
------------------------
Once APRSD is :doc:`installed <install>` You will need to configure the config file
for running.
Generate config file
---------------------
If you have never run the server, running it the first time will generate
a sample config file in the default location of ~/.config/aprsd/aprsd.yml
.. code-block:: shell
└─[$] -> aprsd server
Load config
/home/aprsd/.config/aprsd/aprsd.yml is missing, creating config file
Default config file created at /home/aprsd/.config/aprsd/aprsd.yml. Please edit with your settings.
You can see the sample config file output
Sample config file
------------------
.. code-block:: shell
└─[$] -> cat ~/.config/aprsd/aprsd.yml
aprs:
host: rotate.aprs.net
logfile: /tmp/arsd.log
login: someusername
password: somepassword
port: 14580
aprsd:
enabled_plugins:
- aprsd.plugins.email.EmailPlugin
- aprsd.plugins.fortune.FortunePlugin
- aprsd.plugins.location.LocationPlugin
- aprsd.plugins.ping.PingPlugin
- aprsd.plugins.query.QueryPlugin
- aprsd.plugins.time.TimePlugin
- aprsd.plugins.weather.WeatherPlugin
- aprsd.plugins.version.VersionPlugin
plugin_dir: ~/.config/aprsd/plugins
ham:
callsign: KFART
imap:
host: imap.gmail.com
login: imapuser
password: something here too
port: 993
use_ssl: true
shortcuts:
aa: 5551239999@vtext.com
cl: craiglamparter@somedomain.org
wb: 555309@vtext.com
smtp:
host: imap.gmail.com
login: something
password: some lame password
port: 465
use_ssl: false
Note, You must edit the config file and change the ham callsign to your
legal FCC HAM callsign, or aprsd server will not start.
.. include:: links.rst
+30
View File
@@ -0,0 +1,30 @@
.. a documentation master file, created by
sphinx-quickstart on Wed Dec 19 18:34:22 2018.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
``APRSD`` Documentation
=======================
.. include:: readme.rst
.. toctree::
:maxdepth: 2
:caption: Contents:
readme
install
configure
server
plugin
apidoc/modules.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. include:: links.rst
+67
View File
@@ -0,0 +1,67 @@
APRSD installation
==================
Install info in a nutshell
--------------------------
**Pythons**: Python 3.6 or later
**Operating systems**: Linux, OSX, Unix
**Installer Requirements**: setuptools_
**License**: Apache license
**git repository**: https://github.com/craigerl/aprsd
Installation with pip
--------------------------------------
Use the following command:
.. code-block:: shell
pip install aprsd
It is fine to install ``aprsd`` itself into a virtualenv_ environment.
Install from clone
-------------------------
Consult the GitHub page how to clone the git repository:
https://github.com/craigerl/aprsd
and then install in your environment with something like:
.. code-block:: shell
$ cd <path/to/clone>
$ pip install .
or install it `editable <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_ if you want code changes to propagate automatically:
.. code-block:: shell
$ cd <path/to/clone>
$ pip install --editable .
so that you can do changes and submit patches.
Install for development
----------------------------
For developers you should clone the repo from github, then use the Makefile
.. code-block:: shell
$ cd <path/to/clone>
$ make
This creates a virtualenv_ directory, install all the requirements for
development as well as aprsd in `editable <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_ mode.
It will install all of the pre-commit git hooks required to test prior to committing code.
.. include:: links.rst
+31
View File
@@ -0,0 +1,31 @@
.. _`Cookiecutter`: https://cookiecutter.readthedocs.io
.. _`pluggy`: https://pluggy.readthedocs.io
.. _`cookiecutter-tox-plugin`: https://github.com/tox-dev/cookiecutter-tox-plugin
.. _devpi: https://doc.devpi.net
.. _Python: https://www.python.org
.. _virtualenv: https://pypi.org/project/virtualenv
.. _`pytest`: https://pytest.org
.. _nosetests:
.. _`nose`: https://pypi.org/project/nose
.. _`Holger Krekel`: https://twitter.com/hpk42
.. _`pytest-xdist`: https://pypi.org/project/pytest-xdist
.. _ConfigParser: https://docs.python.org/3/library/configparser.html
.. _`easy_install`: http://peak.telecommunity.com/DevCenter/EasyInstall
.. _pip: https://pypi.org/project/pip
.. _setuptools: https://pypi.org/project/setuptools
.. _`jenkins`: https://jenkins.io/index.html
.. _sphinx: https://pypi.org/project/Sphinx
.. _discover: https://pypi.org/project/discover
.. _unittest2: https://pypi.org/project/unittest2
.. _mock: https://pypi.org/project/mock/
.. _flit: https://flit.readthedocs.io/en/latest/
.. _poetry: https://poetry.eustace.io/
.. _pypy: https://pypy.org
.. _`Python Packaging Guide`: https://packaging.python.org/tutorials/packaging-projects/
.. _`tox.ini`: :doc:configfile
.. _`PEP-508`: https://www.python.org/dev/peps/pep-0508/
.. _`PEP-517`: https://www.python.org/dev/peps/pep-0517/
.. _`PEP-518`: https://www.python.org/dev/peps/pep-0518/
+55
View File
@@ -0,0 +1,55 @@
APRSD Command Plugin Development
================================
APRSDPluginBase
------------------------
Plugins are written as python objects that extend the APRSDPluginBase class.
This is an abstract class that has several properties and a method that must be implemented
by your subclass.
Properties
----------
* name - the Command name
* regex - The regular expression that if matched against the incoming APRS message,
will cause your plugin to be called.
Methods
-------
* command - This method is called when the regex matches the incoming message from APRS.
If you want to send a message back to the sending, just return a string
in your method implementation. If you get called and don't want to reply, then
you should return a messaging.NULL_MESSAGE to signal to the plugin processor
that you got called and processed the message correctly. Otherwise a usage
string may get returned to the sender.
Example Plugin
--------------
There is an example plugin in the aprsd source code here:
aprsd/examples/plugins/example_plugin.py
.. code-block:: python
import logging
from aprsd import plugin
LOG = logging.getLogger("APRSD")
class HelloPlugin(plugin.APRSDPluginBase):
"""Hello World."""
version = "1.0"
# matches any string starting with h or H
command_regex = "^[hH]"
command_name = "hello"
def command(self, fromcall, message, ack):
LOG.info("HelloPlugin")
reply = "Hello '{}'".format(fromcall)
return reply
+410
View File
@@ -0,0 +1,410 @@
APRSD
-----
.. image:: https://badge.fury.io/py/aprsd.svg
:target: https://badge.fury.io/py/aprsd
.. image:: https://github.com/craigerl/aprsd/workflows/python/badge.svg
:target: https://github.com/craigerl/aprsd/actions
.. image:: https://img.shields.io/pypi/pyversions/aprsd.svg
:target: https://pypi.python.org/pypi/aprsd
.. image:: https://img.shields.io/:license-apache-blue.svg
:target: http://www.apache.org/licenses/LICENSE-2.0
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://black.readthedocs.io/en/stable/
.. image:: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336
:target: https://timothycrosley.github.io/isort/
.. image:: https://img.shields.io/github/issues/craigerl/aprsd
.. image:: https://img.shields.io/github/last-commit/craigerl/aprsd
.. image:: https://static.pepy.tech/personalized-badge/aprsd?period=month&units=international_system&left_color=black&right_color=orange&left_text=Downloads
:target: https://pepy.tech/project/aprsd
Summary
=======
`APRSD <http://github.com/craigerl/aprsd>`_ is a Ham radio `APRS <http://aprs.org>`_ message command gateway built on python.
APRSD listens on amateur radio aprs-is network for messages and respond to them.
It has a plugin architecture for extensibility. Users of APRSD can write their own
plugins that can respond to APRS-IS messages.
You must have an amateur radio callsign to use this software. APRSD gets
messages for the configured HAM callsign, and sends those messages to a
list of plugins for processing. There are a set of core plugins that
provide responding to messages to check email, get location, ping,
time of day, get weather, and fortune telling as well as version information
of aprsd itself.
APRSD overview diagram
----------------------
.. figure:: _static/aprsd_overview.svg
:align: center
:width: 800px
Typical use case
================
Ham radio operator using an APRS enabled HAM radio sends a message to check
the weather. an APRS message is sent, and then picked up by APRSD. The
APRS packet is decoded, and the message is sent through the list of plugins
for processing. For example, the WeatherPlugin picks up the message, fetches the weather
for the area around the user who sent the request, and then responds with
the weather conditions in that area.
APRSD Capabilities
==================
* server - The main aprsd server processor. Send/Rx APRS messages to HAM callsign
* send-message - use aprsd to send a command/message to aprsd server. Used for development testing
* sample-config - generate a sample aprsd.yml config file for use/editing
* bash completion generation. Uses python click bash completion to generate completion code for your .bashrc/.zshrc
List of core server plugins
===========================
Plugins function by specifying a regex that is searched for in the APRS message.
If it matches, the plugin runs. IF the regex doesn't match, the plugin is skipped.
* EmailPlugin - Check email and reply with contents. Have to configure IMAP and SMTP settings in aprs.yml
* FortunePlugin - Replies with old unix fortune random fortune!
* LocationPlugin - Checks location of ham operator
* PingPlugin - Sends pong with timestamp
* QueryPlugin - Allows querying the list of delayed messages that were not ACK'd by radio
* TimePlugin - Current time of day
* WeatherPlugin - Get weather conditions for current location of HAM callsign
* VersionPlugin - Reports the version information for aprsd
Current messages this will respond to:
======================================
::
APRS messages:
l(ocation) [callsign] = descriptive current location of your radio
8 Miles E Auburn CA 1673' 39.92150,-120.93950 0.1h ago
w(eather) = weather forecast for your radio's current position
58F(58F/46F) Partly Cloudy. Tonight, Heavy Rain.
t(ime) = respond with the current time
f(ortune) = respond with a short fortune
-email_addr email text = send an email, say "mapme" to send a current position/map
-2 = resend the last 2 emails from your imap inbox to this radio
p(ing) = respond with Pong!/time
v(ersion) = Respond with current APRSD Version string
anything else = respond with usage
Meanwhile this code will monitor a single imap mailbox and forward email
to your BASECALLSIGN over the air. Only radios using the BASECALLSIGN are allowed
to send email, so consider this security risk before using this (or Amatuer radio in
general). Email is single user at this time.
There are additional parameters in the code (sorry), so be sure to set your
email server, and associated logins, passwords. search for "yourdomain",
"password". Search for "shortcuts" to setup email aliases as well.
Example usage:
==============
aprsd -h
Help
====
::
└─[$] > aprsd -h
Usage: aprsd [OPTIONS] COMMAND [ARGS]...
Shell completion for click-completion-command Available shell types:
bash Bourne again shell fish Friendly interactive shell
powershell Windows PowerShell zsh Z shell Default type: auto
Options:
--version Show the version and exit.
-h, --help Show this message and exit.
Commands:
install Install the click-completion-command completion
sample-config This dumps the config to stdout.
send-message Send a message to a callsign via APRS_IS.
server Start the aprsd server process.
show Show the click-completion-command completion code
Configuration
-------------
This command outputs a sample config yml formatted block that you can edit
and use to pass in to aprsd with -c. By default aprsd looks in ~/.config/aprsd/aprsd.yml
aprsd sample-config
Output
======
::
└─[$] > aprsd sample-config
aprs:
host: rotate.aprs.net
logfile: /tmp/arsd.log
login: someusername
password: somepassword
port: 14580
aprsd:
enabled_plugins:
- aprsd.plugin.EmailPlugin
- aprsd.plugin.FortunePlugin
- aprsd.plugin.LocationPlugin
- aprsd.plugin.PingPlugin
- aprsd.plugin.TimePlugin
- aprsd.plugin.WeatherPlugin
- aprsd.plugin.VersionPlugin
plugin_dir: ~/.config/aprsd/plugins
ham:
callsign: KFART
imap:
host: imap.gmail.com
login: imapuser
password: something here too
port: 993
use_ssl: true
shortcuts:
aa: 5551239999@vtext.com
cl: craiglamparter@somedomain.org
wb: 555309@vtext.com
smtp:
host: imap.gmail.com
login: something
password: some lame password
port: 465
use_ssl: false
server
------
This is the main server command that will listen to APRS-IS servers and
look for incomming commands to the callsign configured in the config file
::
└─[$] > aprsd server --help
Usage: aprsd server [OPTIONS]
Start the aprsd server process.
Options:
--loglevel [CRITICAL|ERROR|WARNING|INFO|DEBUG]
The log level to use for aprsd.log
[default: DEBUG]
--quiet Don't log to stdout
--disable-validation Disable email shortcut validation. Bad
email addresses can result in broken email
responses!!
-c, --config TEXT The aprsd config file to use for options.
[default: ~/.config/aprsd/aprsd.yml]
-h, --help Show this message and exit.
(.venv3) ┌─[waboring@dl360-1] - [~/devel/aprsd] - [Sun Dec 20, 12:32] -
└─[$] <git:(master*)> aprsd server
Load config
[12/20/2020 12:33:03 PM] [MainThread ] [INFO ] APRSD Started version: 1.0.2
[12/20/2020 12:33:03 PM] [MainThread ] [INFO ] Checking IMAP configuration
[12/20/2020 12:33:04 PM] [MainThread ] [INFO ] Checking SMTP configuration
send-message
------------
This command is typically used for development to send another aprsd instance
test messages
::
└─[$] > aprsd send-message -h
Usage: aprsd send-message [OPTIONS] TOCALLSIGN [COMMAND]...
Send a message to a callsign via APRS_IS.
Options:
--loglevel [CRITICAL|ERROR|WARNING|INFO|DEBUG]
The log level to use for aprsd.log
[default: DEBUG]
--quiet Don't log to stdout
-c, --config TEXT The aprsd config file to use for options.
[default: ~/.config/aprsd/aprsd.yml]
--aprs-login TEXT What callsign to send the message from.
[env var: APRS_LOGIN]
--aprs-password TEXT the APRS-IS password for APRS_LOGIN [env
var: APRS_PASSWORD]
-h, --help Show this message and exit.
Example Message output:
-----------------------
SEND EMAIL (radio to smtp server)
=================================
::
Received message______________
Raw : KM6XXX>APY400,WIDE1-1,qAO,KM6XXX-1::KM6XXX-9 :-user@host.com test new shortcuts global, radio to pc{29
From : KM6XXX
Message : -user@host.com test new shortcuts global, radio to pc
Msg number : 29
Sending Email_________________
To : user@host.com
Subject : KM6XXX
Body : test new shortcuts global, radio to pc
Sending ack __________________ Tx(3)
Raw : KM6XXX-9>APRS::KM6XXX :ack29
To : KM6XXX
Ack number : 29
RECEIVE EMAIL (imap server to radio)
====================================
::
Sending message_______________ 6(Tx3)
Raw : KM6XXX-9>APRS::KM6XXX :-somebody@gmail.com email from internet to radio{6
To : KM6XXX
Message : -somebody@gmail.com email from internet to radio
Received message______________
Raw : KM6XXX>APY400,WIDE1-1,qAO,KM6XXX-1::KM6XXX-9 :ack6
From : KM6XXX
Message : ack6
Msg number : 0
LOCATION
========
::
Received Message _______________
Raw : KM6XXX-6>APRS,TCPIP*,qAC,T2CAEAST::KM6XXX-14:location{2
From : KM6XXX-6
Message : location
Msg number : 2
Received Message _______________ Complete
Sending Message _______________
Raw : KM6XXX-14>APRS::KM6XXX-6 :KM6XXX-6: 8 Miles E Auburn CA 0' 0,-120.93584 1873.7h ago{2
To : KM6XXX-6
Message : KM6XXX-6: 8 Miles E Auburn CA 0' 0,-120.93584 1873.7h ago
Msg number : 2
Sending Message _______________ Complete
Sending ack _______________
Raw : KM6XXX-14>APRS::KM6XXX-6 :ack2
To : KM6XXX-6
Ack : 2
Sending ack _______________ Complete
AND... ping, fortune, time.....
Development
-----------
* git clone git@github.com:craigerl/aprsd.git
* cd aprsd
* make
Workflow
========
While working aprsd, The workflow is as follows
* Edit code, save file
* run tox -efmt
* run tox -p
* git commit ( This will run the pre-commit hooks which does checks too )
Release
=======
To do release to pypi:
* Tag release with
git tag -v1.XX -m "New release"
* push release tag up
git push origin master --tags
* Do a test build and verify build is valid
make build
* Once twine is happy, upload release to pypi
make upload
Docker Container
----------------
Building
========
There are 2 versions of the container Dockerfile that can be used.
The main Dockerfile, which is for building the official release container
based off of the pip install version of aprsd and the Dockerfile-dev,
which is used for building a container based off of a git branch of
the repo.
Official Build
==============
docker build -t hemna6969/aprsd:latest .
Development Build
=================
docker build -t hemna6969/aprsd:latest -f Dockerfile-dev .
Running the container
=====================
There is a docker-compose.yml file that can be used to run your container.
There are 2 volumes defined that can be used to store your configuration
and the plugins directory: /config and /plugins
If you want to install plugins at container start time, then use the
environment var in docker-compose.yml specified as APRS_PLUGINS
Provide a csv list of pypi installable plugins. Then make sure the plugin
python file is in your /plugins volume and the plugin will be installed at
container startup. The plugin may have dependencies that are required.
The plugin file should be copied to /plugins for loading by aprsd
+53
View File
@@ -0,0 +1,53 @@
APRSD server
============
Running the APRSD server
------------------------
Once APRSD is :doc:`installed <install>` and :doc:`configured <configure>` the server can be started by
running.
.. code-block:: shell
aprsd server
The server will start several threads to deal handle incoming messages, outgoing
messages, checking and sending email.
.. code-block:: shell
[MainThread ] [INFO ] APRSD Started version: 1.5.1
[MainThread ] [INFO ] Checking IMAP configuration
[MainThread ] [INFO ] Checking SMTP configuration
[MainThread ] [DEBUG] Connect to SMTP host SSL smtp.gmail.com:465 with user 'test@hemna.com'
[MainThread ] [DEBUG] Connected to smtp host SSL smtp.gmail.com:465
[MainThread ] [DEBUG] Logged into SMTP server SSL smtp.gmail.com:465
[MainThread ] [INFO ] Validating 2 Email shortcuts. This can take up to 10 seconds per shortcut
[MainThread ] [ERROR] 'craiglamparter@somedomain.org' is an invalid email address. Removing shortcut
[MainThread ] [INFO ] Available shortcuts: {'wb': 'waboring@hemna.com'}
[MainThread ] [INFO ] Loading Core APRSD Command Plugins
[MainThread ] [INFO ] Registering Command plugin 'aprsd.plugins.email.EmailPlugin'(1.0) '^-.*'
[MainThread ] [INFO ] Registering Command plugin 'aprsd.plugins.fortune.FortunePlugin'(1.0) '^[fF]'
[MainThread ] [INFO ] Registering Command plugin 'aprsd.plugins.location.LocationPlugin'(1.0) '^[lL]'
[MainThread ] [INFO ] Registering Command plugin 'aprsd.plugins.ping.PingPlugin'(1.0) '^[pP]'
[MainThread ] [INFO ] Registering Command plugin 'aprsd.plugins.query.QueryPlugin'(1.0) '^\?.*'
[MainThread ] [INFO ] Registering Command plugin 'aprsd.plugins.time.TimePlugin'(1.0) '^[tT]'
[MainThread ] [INFO ] Registering Command plugin 'aprsd.plugins.weather.WeatherPlugin'(1.0) '^[wW]'
[MainThread ] [INFO ] Registering Command plugin 'aprsd.plugins.version.VersionPlugin'(1.0) '^[vV]'
[MainThread ] [INFO ] Skipping Custom Plugins directory.
[MainThread ] [INFO ] Completed Plugin Loading.
[MainThread ] [DEBUG] Loading saved MsgTrack object.
[RX_MSG ] [INFO ] Starting
[TX_MSG ] [INFO ] Starting
[MainThread ] [DEBUG] KeepAlive Tracker(0): {}
[RX_MSG ] [INFO ] Creating aprslib client
[RX_MSG ] [INFO ] Attempting connection to noam.aprs2.net:14580
[RX_MSG ] [INFO ] Connected to ('198.50.198.139', 14580)
[RX_MSG ] [DEBUG] Banner: # aprsc 2.1.8-gf8824e8
[RX_MSG ] [INFO ] Sending login information
[RX_MSG ] [DEBUG] Server: # logresp KM6XXX-14 verified, server T2VAN
[RX_MSG ] [INFO ] Login successful
[RX_MSG ] [DEBUG] Logging in to APRS-IS with user 'KM6XXX-14'
.. include:: links.rst
+36
View File
@@ -0,0 +1,36 @@
[build-system]
requires = ["setuptools>=46.0", "wheel"]
build-backend = "setuptools.build_meta"
[tool.black]
# Use the more relaxed max line length permitted in PEP8.
line-length = 88
target-version = ["py36", "py37", "py38"]
# black will automatically exclude all files listed in .gitignore
include = '\.pyi?$'
exclude = '''
/(
\.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
)/
'''
[tool.isort]
profile = "black"
line_length = 88
force_sort_within_sections = true
# Inform isort of paths to import names that should be considered part of the "First Party" group.
src_paths = ["src/openstack_loadtest"]
skip_gitignore = true
# If you need to skip/exclude folders, consider using skip_glob as that will allow the
# isort defaults for skip to remain without the need to duplicate them.
[tool.coverage.run]
branch = true
+3
View File
@@ -7,3 +7,6 @@ pyyaml
six
requests
thesmuggler
aprslib
py3-validate-email
pre-commit
+69 -17
View File
@@ -2,21 +2,73 @@
# This file is autogenerated by pip-compile
# To update, run:
#
# pip-compile
# pip-compile requirements.in
#
certifi==2020.12.5 # via requests
chardet==3.0.4 # via requests
click-completion==0.5.2 # via -r requirements.in
click==7.1.2 # via -r requirements.in, click-completion
idna==2.10 # via requests
imapclient==2.1.0 # via -r requirements.in
jinja2==2.11.2 # via click-completion
markupsafe==1.1.1 # via jinja2
pbr==5.5.1 # via -r requirements.in
pluggy==0.13.1 # via -r requirements.in
pyyaml==5.3.1 # via -r requirements.in
requests==2.25.0 # via -r requirements.in
shellingham==1.3.2 # via click-completion
six==1.15.0 # via -r requirements.in, click-completion, imapclient
thesmuggler==1.0.1 # via -r requirements.in
urllib3==1.26.2 # via requests
appdirs==1.4.4
# via virtualenv
aprslib==0.6.47
# via -r requirements.in
certifi==2020.12.5
# via requests
cfgv==3.2.0
# via pre-commit
chardet==4.0.0
# via requests
click-completion==0.5.2
# via -r requirements.in
click==7.1.2
# via
# -r requirements.in
# click-completion
distlib==0.3.1
# via virtualenv
dnspython==2.1.0
# via py3-validate-email
filelock==3.0.12
# via
# py3-validate-email
# virtualenv
identify==1.5.11
# via pre-commit
idna==2.10
# via
# py3-validate-email
# requests
imapclient==2.1.0
# via -r requirements.in
jinja2==2.11.2
# via click-completion
markupsafe==1.1.1
# via jinja2
nodeenv==1.5.0
# via pre-commit
pbr==5.5.1
# via -r requirements.in
pluggy==0.13.1
# via -r requirements.in
pre-commit==2.9.3
# via -r requirements.in
py3-validate-email==0.2.12
# via -r requirements.in
pyyaml==5.3.1
# via
# -r requirements.in
# pre-commit
requests==2.25.1
# via -r requirements.in
shellingham==1.3.2
# via click-completion
six==1.15.0
# via
# -r requirements.in
# click-completion
# imapclient
# virtualenv
thesmuggler==1.0.1
# via -r requirements.in
toml==0.10.2
# via pre-commit
urllib3==1.26.2
# via requests
virtualenv==20.2.2
# via pre-commit
+25 -9
View File
@@ -1,15 +1,28 @@
[metadata]
name = aprsd
summary = Amateur radio APRS daemon which listens for messages and responds
description-file =
README.rst
long-description-content-type = text/x-rst; charset=UTF-8
long_description = file: README.rst
long_description_content_type = text/x-rst
url = http://aprsd.readthedocs.org
author = Craig Lamparter
author-email = something@somewhere.com
author_email = something@somewhere.com
license = Apache
license_file = LICENSE
classifier =
License :: OSI Approved :: Apache Software License
Topic :: Communications :: Ham Radio
Operating System :: POSIX :: Linux
Programming Language :: Python
Programming Language :: Python :: 3 :: Only
Programming Language :: Python :: 3
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
description_file =
README.rst
project_urls =
Source=https://github.com/craigerl/aprsd
Tracker=https://github.com/craigerl/aprsd/issues
summary = Amateur radio APRS daemon which listens for messages and responds
[global]
setup-hooks =
@@ -25,9 +38,12 @@ console_scripts =
fake_aprs = aprsd.fake_aprs:main
[build_sphinx]
source-dir = doc/source
build-dir = doc/build
source-dir = docs
build-dir = docs/_build
all_files = 1
[upload_sphinx]
upload-dir = doc/build/html
upload-dir = docs/_build
[bdist_wheel]
universal = 1
-3
View File
@@ -1,3 +0,0 @@
flake8
pytest
mock
-2
View File
@@ -1,2 +0,0 @@
flake8
pytest
+25
View File
@@ -0,0 +1,25 @@
import unittest
from aprsd import email
class TestEmail(unittest.TestCase):
def test_get_email_from_shortcut(self):
email.CONFIG = {"shortcuts": {}}
email_address = "something@something.com"
addr = "-{}".format(email_address)
actual = email.get_email_from_shortcut(addr)
self.assertEqual(addr, actual)
email.CONFIG = {"nothing": "nothing"}
actual = email.get_email_from_shortcut(addr)
self.assertEqual(addr, actual)
email.CONFIG = {"shortcuts": {"not_used": "empty"}}
actual = email.get_email_from_shortcut(addr)
self.assertEqual(addr, actual)
email.CONFIG = {"shortcuts": {"-wb": email_address}}
short = "-wb"
actual = email.get_email_from_shortcut(short)
self.assertEqual(email_address, actual)
+7 -9
View File
@@ -1,23 +1,21 @@
# -*- coding: utf-8 -*-
import sys
import unittest
import pytest
from aprsd import main
from aprsd import email
if sys.version_info >= (3, 2):
from unittest import mock
else:
import mock
from unittest import mock
class testMain(unittest.TestCase):
@mock.patch("aprsd.main._imap_connect")
@mock.patch("aprsd.main._smtp_connect")
class TestMain(unittest.TestCase):
@mock.patch("aprsd.email._imap_connect")
@mock.patch("aprsd.email._smtp_connect")
def test_validate_email(self, imap_mock, smtp_mock):
"""Test to make sure we fail."""
imap_mock.return_value = None
smtp_mock.return_value = {"smaiof": "fire"}
config = mock.MagicMock()
main.validate_email()
email.validate_email_config(config, True)
+150
View File
@@ -0,0 +1,150 @@
import datetime
import unittest
from unittest import mock
from aprsd import messaging
class TestMessageTrack(unittest.TestCase):
def _clean_track(self):
track = messaging.MsgTrack()
track.track = {}
track.total_messages_tracked = 0
return track
def test_create(self):
track1 = messaging.MsgTrack()
track2 = messaging.MsgTrack()
self.assertEqual(track1, track2)
def test_add(self):
track = self._clean_track()
fromcall = "KFART"
tocall = "KHELP"
message = "somthing"
msg = messaging.TextMessage(fromcall, tocall, message)
track.add(msg)
self.assertEqual(msg, track.get(msg.id))
def test_remove(self):
track = self._clean_track()
fromcall = "KFART"
tocall = "KHELP"
message = "somthing"
msg = messaging.TextMessage(fromcall, tocall, message)
track.add(msg)
track.remove(msg.id)
self.assertEqual(None, track.get(msg.id))
def test_len(self):
"""Test getting length of tracked messages."""
track = self._clean_track()
fromcall = "KFART"
tocall = "KHELP"
message = "somthing"
msg = messaging.TextMessage(fromcall, tocall, message)
track.add(msg)
self.assertEqual(1, len(track))
msg2 = messaging.TextMessage(tocall, fromcall, message)
track.add(msg2)
self.assertEqual(2, len(track))
track.remove(msg.id)
self.assertEqual(1, len(track))
@mock.patch("aprsd.messaging.TextMessage.send")
def test__resend(self, mock_send):
"""Test the _resend method."""
track = self._clean_track()
fromcall = "KFART"
tocall = "KHELP"
message = "somthing"
msg = messaging.TextMessage(fromcall, tocall, message)
msg.last_send_attempt = 3
track.add(msg)
track._resend(msg)
msg.send.assert_called_with()
self.assertEqual(0, msg.last_send_attempt)
@mock.patch("aprsd.messaging.TextMessage.send")
def test_restart_delayed(self, mock_send):
"""Test the _resend method."""
track = self._clean_track()
fromcall = "KFART"
tocall = "KHELP"
message1 = "something"
message2 = "something another"
message3 = "something another again"
mock1_send = mock.MagicMock()
mock2_send = mock.MagicMock()
mock3_send = mock.MagicMock()
msg1 = messaging.TextMessage(fromcall, tocall, message1)
msg1.last_send_attempt = 3
msg1.last_send_time = datetime.datetime.now()
msg1.send = mock1_send
track.add(msg1)
msg2 = messaging.TextMessage(tocall, fromcall, message2)
msg2.last_send_attempt = 3
msg2.last_send_time = datetime.datetime.now()
msg2.send = mock2_send
track.add(msg2)
track.restart_delayed(count=None)
msg1.send.assert_called_once()
self.assertEqual(0, msg1.last_send_attempt)
msg2.send.assert_called_once()
self.assertEqual(0, msg2.last_send_attempt)
msg1.last_send_attempt = 3
msg1.send.reset_mock()
msg2.last_send_attempt = 3
msg2.send.reset_mock()
track.restart_delayed(count=1)
msg1.send.assert_not_called()
msg2.send.assert_called_once()
self.assertEqual(3, msg1.last_send_attempt)
self.assertEqual(0, msg2.last_send_attempt)
msg3 = messaging.TextMessage(tocall, fromcall, message3)
msg3.last_send_attempt = 3
msg3.last_send_time = datetime.datetime.now()
msg3.send = mock3_send
track.add(msg3)
msg1.last_send_attempt = 3
msg1.send.reset_mock()
msg2.last_send_attempt = 3
msg2.send.reset_mock()
msg3.last_send_attempt = 3
msg3.send.reset_mock()
track.restart_delayed(count=2)
msg1.send.assert_not_called()
msg2.send.assert_called_once()
msg3.send.assert_called_once()
self.assertEqual(3, msg1.last_send_attempt)
self.assertEqual(0, msg2.last_send_attempt)
self.assertEqual(0, msg3.last_send_attempt)
msg1.last_send_attempt = 3
msg1.send.reset_mock()
msg2.last_send_attempt = 3
msg2.send.reset_mock()
msg3.last_send_attempt = 3
msg3.send.reset_mock()
track.restart_delayed(count=2, most_recent=False)
msg1.send.assert_called_once()
msg2.send.assert_called_once()
msg3.send.assert_not_called()
self.assertEqual(0, msg1.last_send_attempt)
self.assertEqual(0, msg2.last_send_attempt)
self.assertEqual(3, msg3.last_send_attempt)
+152
View File
@@ -0,0 +1,152 @@
import unittest
from unittest import mock
import aprsd
from aprsd import messaging
from aprsd.fuzzyclock import fuzzy
from aprsd.plugins import fortune as fortune_plugin
from aprsd.plugins import ping as ping_plugin
from aprsd.plugins import query as query_plugin
from aprsd.plugins import time as time_plugin
from aprsd.plugins import version as version_plugin
class TestPlugin(unittest.TestCase):
def setUp(self):
self.fromcall = "KFART"
self.ack = 1
self.config = {"ham": {"callsign": self.fromcall}}
@mock.patch("shutil.which")
def test_fortune_fail(self, mock_which):
fortune = fortune_plugin.FortunePlugin(self.config)
mock_which.return_value = None
message = "fortune"
expected = "Fortune command not installed"
actual = fortune.run(self.fromcall, message, self.ack)
self.assertEqual(expected, actual)
@mock.patch("subprocess.check_output")
@mock.patch("shutil.which")
def test_fortune_success(self, mock_which, mock_output):
fortune = fortune_plugin.FortunePlugin(self.config)
mock_which.return_value = "/usr/bin/games"
mock_output.return_value = "Funny fortune"
message = "fortune"
expected = "Funny fortune"
actual = fortune.run(self.fromcall, message, self.ack)
self.assertEqual(expected, actual)
@mock.patch("aprsd.messaging.MsgTrack.flush")
def test_query_flush(self, mock_flush):
message = "?delete"
query = query_plugin.QueryPlugin(self.config)
expected = "Deleted ALL pending msgs."
actual = query.run(self.fromcall, message, self.ack)
mock_flush.assert_called_once()
self.assertEqual(expected, actual)
@mock.patch("aprsd.messaging.MsgTrack.restart_delayed")
def test_query_restart_delayed(self, mock_restart):
track = messaging.MsgTrack()
track.track = {}
message = "?4"
query = query_plugin.QueryPlugin(self.config)
expected = "No pending msgs to resend"
actual = query.run(self.fromcall, message, self.ack)
mock_restart.assert_not_called()
self.assertEqual(expected, actual)
mock_restart.reset_mock()
# add a message
msg = messaging.TextMessage(self.fromcall, "testing", self.ack)
track.add(msg)
actual = query.run(self.fromcall, message, self.ack)
mock_restart.assert_called_once()
@mock.patch("time.localtime")
def test_time(self, mock_time):
fake_time = mock.MagicMock()
h = fake_time.tm_hour = 16
m = fake_time.tm_min = 12
fake_time.tm_sec = 55
mock_time.return_value = fake_time
time = time_plugin.TimePlugin(self.config)
fromcall = "KFART"
message = "location"
ack = 1
actual = time.run(fromcall, message, ack)
self.assertEqual(None, actual)
cur_time = fuzzy(h, m, 1)
message = "time"
expected = "{} ({}:{} PDT) ({})".format(
cur_time,
str(h),
str(m).rjust(2, "0"),
message.rstrip(),
)
actual = time.run(fromcall, message, ack)
self.assertEqual(expected, actual)
@mock.patch("time.localtime")
def test_ping(self, mock_time):
fake_time = mock.MagicMock()
h = fake_time.tm_hour = 16
m = fake_time.tm_min = 12
s = fake_time.tm_sec = 55
mock_time.return_value = fake_time
ping = ping_plugin.PingPlugin(self.config)
fromcall = "KFART"
message = "location"
ack = 1
result = ping.run(fromcall, message, ack)
self.assertEqual(None, result)
def ping_str(h, m, s):
return (
"Pong! "
+ str(h).zfill(2)
+ ":"
+ str(m).zfill(2)
+ ":"
+ str(s).zfill(2)
)
message = "Ping"
actual = ping.run(fromcall, message, ack)
expected = ping_str(h, m, s)
self.assertEqual(expected, actual)
message = "ping"
actual = ping.run(fromcall, message, ack)
self.assertEqual(expected, actual)
def test_version(self):
expected = "APRSD version '{}'".format(aprsd.__version__)
version = version_plugin.VersionPlugin(self.config)
fromcall = "KFART"
message = "No"
ack = 1
actual = version.run(fromcall, message, ack)
self.assertEqual(None, actual)
message = "version"
actual = version.run(fromcall, message, ack)
self.assertEqual(expected, actual)
message = "Version"
actual = version.run(fromcall, message, ack)
self.assertEqual(expected, actual)
+17 -25
View File
@@ -2,7 +2,7 @@
minversion = 2.9.0
skipdist = True
skip_missing_interpreters = true
envlist = py{27,36,37,38},pep8,fmt-check
envlist = pre-commit,pep8,fmt-check,py{36,37,38}
# Activate isolated build environment. tox will use a virtual environment
# to build a source distribution from the source tree. For build tools and
@@ -14,7 +14,6 @@ setenv = VIRTUAL_ENV={envdir}
usedevelop = True
install_command = pip install {opts} {packages}
deps = -r{toxinidir}/requirements.txt
-r{toxinidir}/test-requirements.txt
-r{toxinidir}/dev-requirements.txt
commands =
# Use -bb to enable BytesWarnings as error to catch str/bytes misuse.
@@ -23,32 +22,21 @@ commands =
# --cov="{envsitepackagesdir}/aprsd" --cov-report=html --cov-report=term {posargs}
{envpython} -bb -m pytest {posargs}
[testenv:py27]
setenv = VIRTUAL_ENV={envdir}
usedevelop = True
install_command = pip install {opts} {packages}
deps = -r{toxinidir}/requirements.txt
-r{toxinidir}/test-requirements-py2.txt
commands =
# Use -bb to enable BytesWarnings as error to catch str/bytes misuse.
# Use -Werror to treat warnings as errors.
# {envpython} -bb -Werror -m pytest \
# --cov="{envsitepackagesdir}/aprsd" --cov-report=html --cov-report=term {posargs}
{envpython} -bb -Werror -m pytest
[testenv:docs]
deps = -r{toxinidir}/test-requirements.txt
commands = sphinx-build -b html docs/source docs/html
[testenv:pep8-27]
deps = -r{toxinidir}/requirements.txt
-r{toxinidir}/test-requirements-py2.txt
skip_install = true
deps =
-r{toxinidir}/requirements.txt
-r{toxinidir}/dev-requirements.txt
{toxinidir}/.
changedir = {toxinidir}/docs
commands =
flake8 {posargs} aprsd
{envpython} clean_docs.py
sphinx-apidoc --force --output-dir apidoc {toxinidir}/aprsd
sphinx-build -a -W . _build
[testenv:pep8]
commands =
flake8 {posargs} aprsd
flake8 {posargs} aprsd tests
[testenv:fast8]
basepython = python3
@@ -63,7 +51,7 @@ skip_install = true
deps =
-r{toxinidir}/dev-requirements.txt
commands =
flake8 aprsd
flake8 aprsd tests
[flake8]
max-line-length = 99
@@ -78,7 +66,6 @@ exclude = .venv,.git,.tox,dist,doc,.ropeproject
# This section is not needed if not using GitHub Actions for CI.
[gh-actions]
python =
2.7: py27, pep8-27
3.6: py36, pep8, fmt-check
3.7: py38, pep8, fmt-check
3.8: py38, pep8, fmt-check, type-check, docs
@@ -112,3 +99,8 @@ deps =
-r{toxinidir}/dev-requirements.txt
commands =
mypy aprsd
[testenv:pre-commit]
skip_install = true
deps = pre-commit
commands = pre-commit run --all-files --show-diff-on-failure