Skip to content

Commit

Permalink
add narodmon example
Browse files Browse the repository at this point in the history
  • Loading branch information
cdump committed Jun 12, 2021
1 parent 377d74f commit df4f5bf
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 5 deletions.
1 change: 1 addition & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,4 @@ ignore =
WPS336, # explicit string concat
WPS432, # magic numbers
WPS237, # too complex `f` string
WPS229, # more than 1 line try block
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ $ python3 -m radiacode-examples.webserver --bluetooth-mac 52:43:01:02:03:04
# или то же самое, но по usb
$ sudo python3 -m radiacode-examples.webserver
# или простой пример с выводом информации в терминал, опции аналогичны webserver
# простой пример с выводом информации в терминал, опции аналогичны webserver
$ python3 -m radiacode-examples.basic
# отправка показания в народный мониторинг narodmon.ru
$ python3 -m radiacode-examples.narodmon --bluetooth-mac 52:43:01:02:03:04
```

### Разработка
Expand Down
6 changes: 3 additions & 3 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "radiacode"
version = "0.1.1"
version = "0.1.2"
description = "Library for RadiaCode-101"
authors = ["Maxim Andreev <[email protected]>"]
license = "MIT"
Expand Down
25 changes: 25 additions & 0 deletions radiacode-examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Примеры использования библиотеки

Устанавливаются с пакетом если указать `pip install radiacode[examples]` (вместо `pip install radiacode`)

У каждого примера есть справка по `--help`


### 1. [basic.py](./basic.py)
Минимальный пример, показывающий соединение с устройством по USB или Bluetooth и получение серийного номера, спектра и измерений числа частиц/дозы
```
$ python3 -m radiacode-examples.basic --bluetooth-mac 52:43:01:02:03:04
```

### 2. [webserver.py](./webserver.py) & [webserver.html](./webserver.html)
Спектр и число частиц/доза в веб интерфейсе с автоматическим обновлением
```
$ python3 -m radiacode-examples.webserver --bluetooth-mac 52:43:01:02:03:04 --listen-port 8080
```


### 3. [narodmon.py](./narodmon.py)
Отправка измерений в сервис [народный мониторинг narodmon.ru](https://narodmon.ru)
```
$ python3 -m radiacode-examples.narodmon --bluetooth-mac 52:43:01:02:03:04
```
93 changes: 93 additions & 0 deletions radiacode-examples/narodmon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import argparse
import asyncio
import time

import aiohttp

from radiacode import CountRate, DoseRate, RadiaCode


def sensors_data(rc_conn):
databuf = rc_conn.data_buf()

last_countrate, last_doserate = None, None
for v in databuf:
if isinstance(v, CountRate):
if last_countrate is None or last_countrate.dt < v.dt:
last_countrate = v
elif isinstance(v, DoseRate):
if last_doserate is None or last_doserate.dt < v.dt:
last_doserate = v

ret = []
if last_countrate is not None:
ret.append(
{
'id': 'S1',
'name': 'CountRate',
'value': last_countrate.count_rate,
'unit': 'CPS',
'time': int(last_countrate.dt.timestamp()),
}
)
if last_doserate is not None:
ret.append(
{
'id': 'S2',
'name': 'R_DoseRate',
'value': 1000000 * last_doserate.dose_rate,
'unit': 'μR/h',
'time': int(last_doserate.dt.timestamp()),
}
)
return ret


async def send_data(d):
# use aiohttp because we already have it as dependency in webserver.py, don't want add 'requests' here
async with aiohttp.ClientSession() as session:
async with session.post('https://narodmon.ru/json', json=d) as resp:
return await resp.text()


def main():
parser = argparse.ArgumentParser()
parser.add_argument('--bluetooth-mac', type=str, required=True, help='MAC address of radiascan device')
parser.add_argument('--connection', choices=['usb', 'bluetooth'], default='bluetooth', help='device connection type')
parser.add_argument('--interval', type=int, required=False, default=600, help='send interval, seconds')
args = parser.parse_args()

if args.connection == 'usb':
print('will use USB connection')
rc_conn = RadiaCode()
else:
print('will use Bluetooth connection')
rc_conn = RadiaCode(bluetooth_mac=args.bluetooth_mac)

device_data = {
'mac': args.bluetooth_mac.replace(':', '-'),
'name': 'RadiaCode-101',
}

while True:
d = {
'devices': [
{
**device_data,
'sensors': sensors_data(rc_conn),
},
],
}
print(f'Sending {d}')

try:
r = asyncio.run(send_data(d))
print(f'NarodMon Response: {r}')
except Exception as ex:
print(f'NarodMon send error: {ex}')

time.sleep(args.interval)


if __name__ == '__main__':
main()

0 comments on commit df4f5bf

Please sign in to comment.