Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webserver_logger example, and shutdown events #35

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
163 changes: 162 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,166 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add only related records or revert this file.

.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
dist/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# Ignore SSL keys
*.pem
*.p12
4 changes: 4 additions & 0 deletions install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/bash
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like it's your test script, which should not have been committed to the repo.

version=0.3.4
poetry build
sudo pip install --force-reinstall dist/radiacode-${version}-py3-none-any.whl
555 changes: 291 additions & 264 deletions poetry.lock

Large diffs are not rendered by default.

19 changes: 15 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[tool.poetry]
name = "radiacode"
version = "0.3.3"
description = "Library for RadiaCode-101"
version = "0.3.4"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current release pipeline includes setting an annotated tag and pushing to GitHub to build a pip package with GitHub Actions.
I will publish the release later, so please revert the version bump (but changes in the description are okay).

description = "Library for RadiaCode-10x"
authors = ["Maxim Andreev <[email protected]>"]
license = "MIT"
readme = "README.md"
@@ -11,7 +11,10 @@ classifiers = [
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3 :: Only",
]
include = ["radiacode-examples/*"]
packages = [
{ include = "radiacode" },
{ include = "radiacode_examples" }
]

[tool.poetry.dependencies]
python = "^3.9"
@@ -30,6 +33,14 @@ mypy = "^1.7"
[tool.poetry.extras]
examples = ["aiohttp", "prometheus-client", "matplotlib", "numpy", "pyyaml"]

[tool.poetry.scripts]
radiacode_basic = "radiacode_examples.basic:main"
radiacode_exporter = "radiacode_examples.radiacode_exporter:main"
radiacode_show_spectrum = "radiacode_examples.show_spectrum:main"
radiacode_webserver = "radiacode_examples.webserver:main"
radiacode_webserver_logger = "radiacode_examples.webserver_logger:main"
radiacode_narodmon = "radiacode_examples.narodmon:main"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
@@ -46,4 +57,4 @@ inline-quotes = "single"
quote-style = "single"

[tool.ruff.per-file-ignores]
"__init__.py" = ["F401", "F403"]
"__init__.py" = ["F401", "F403"]
3 changes: 3 additions & 0 deletions radiacode/radiacode.py
Original file line number Diff line number Diff line change
@@ -220,3 +220,6 @@ def set_vibro_ctrl(self, ctrls: List[CTRL]) -> None:
assert c != CTRL.CLICKS, 'CTRL.CLICKS not supported for vibro'
flags |= int(c)
self.write_request(VSFR.VIBRO_CTRL, struct.pack('<I', flags))

def close(self):
self._connection.close()
11 changes: 11 additions & 0 deletions radiacode/transports/bluetooth.py
Original file line number Diff line number Diff line change
@@ -12,6 +12,11 @@ class Bluetooth:
def __init__(self):
# Create an empty class if we are on MacOS
pass

def close(self):
# No resources to release on MacOS
pass

else:
from bluepy.btle import BTLEDisconnectError, DefaultDelegate, Peripheral
from radiacode.bytes_buffer import BytesBuffer
@@ -57,3 +62,9 @@ def execute(self, req) -> BytesBuffer:
br = BytesBuffer(self._response)
self._response = None
return br

def close(self):
"""Disconnect from the Bluetooth device and release resources."""
if hasattr(self, 'p') and self.p is not None:
self.p.disconnect()
self.p = None
6 changes: 6 additions & 0 deletions radiacode/transports/usb.py
Original file line number Diff line number Diff line change
@@ -58,3 +58,9 @@ def execute(self, request: bytes) -> BytesBuffer:
data += r

return BytesBuffer(data)

def close(self):
"""Release the USB device resources."""
if self._device is not None:
usb.util.dispose_resources(self._device)
self._device = None
File renamed without changes.
File renamed without changes.
22 changes: 22 additions & 0 deletions radiacode_examples/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
RadiaCode Examples

This package contains example scripts for using the RadiaCode library.

Available examples:
- basic: A simple command-line interface for RadiaCode
- show_spectrum: Reads spectrum data from Radiacode 102 device, displays and
stores the count rate history and the spectrum of deposited energies.
- webserver: A web-based interface for RadiaCode data
- webserver_logger: ...with rotating file logging
- radiacode_exporter: Stores radiacode data in a Prometheus database
- narodmon: Script for sending data to the narodmon.ru monitoring project

To run an example, use:
python -m radiacode_examples.<example_name>

For instance:
python -m radiacode_examples.webserver
"""

__all__ = ['basic', 'show_spectrum', 'webserver', 'webserver_logger', 'radiacode_exporter', 'narodmon']
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
52 changes: 27 additions & 25 deletions radiacode-examples/webserver.py → radiacode_examples/webserver.py
Original file line number Diff line number Diff line change
@@ -7,6 +7,32 @@

from radiacode import RadiaCode, RealTimeData

def main():
parser = argparse.ArgumentParser()
parser.add_argument('--bluetooth-mac', type=str, required=False, help='bluetooth MAC address of radiascan device')
parser.add_argument('--listen-host', type=str, required=False, default='0.0.0.0', help='listen host for webserver')
parser.add_argument('--listen-port', type=int, required=False, default=8102, help='listen port for webserver')
args = parser.parse_args()

app = web.Application()
app.ws_clients = []
if args.bluetooth_mac:
print('will use Bluetooth connection')
app.rc_conn = RadiaCode(bluetooth_mac=args.bluetooth_mac)
else:
print('will use USB connection')
app.rc_conn = RadiaCode()

app.on_startup.append(on_startup)
app.add_routes(
[
web.get('/', handle_index),
web.get('/spectrum', handle_spectrum),
web.post('/spectrum/reset', handle_spectrum_reset),
web.get('/ws', handle_ws),
],
)
web.run_app(app, host=args.listen_host, port=args.listen_port)

async def handle_index(request):
return web.FileResponse(pathlib.Path(__file__).parent.absolute() / 'webserver.html')
@@ -79,28 +105,4 @@ async def on_startup(app):


if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--bluetooth-mac', type=str, required=False, help='bluetooth MAC address of radiascan device')
parser.add_argument('--listen-host', type=str, required=False, default='0.0.0.0', help='listen host for webserver')
parser.add_argument('--listen-port', type=int, required=False, default=8080, help='listen port for webserver')
args = parser.parse_args()

app = web.Application()
app.ws_clients = []
if args.bluetooth_mac:
print('will use Bluetooth connection')
app.rc_conn = RadiaCode(bluetooth_mac=args.bluetooth_mac)
else:
print('will use USB connection')
app.rc_conn = RadiaCode()

app.on_startup.append(on_startup)
app.add_routes(
[
web.get('/', handle_index),
web.get('/spectrum', handle_spectrum),
web.post('/spectrum/reset', handle_spectrum_reset),
web.get('/ws', handle_ws),
],
)
web.run_app(app, host=args.listen_host, port=args.listen_port)
main()
Loading