Skip to content

Commit

Permalink
use absolute datetime
Browse files Browse the repository at this point in the history
  • Loading branch information
cdump committed Jun 7, 2021
1 parent 1e5402d commit c473cc3
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 24 deletions.
1 change: 1 addition & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,4 @@ ignore =
WPS114, # underscore in name
WPS336, # explicit string concat
WPS432, # magic numbers
WPS237, # too complex `f` string
8 changes: 6 additions & 2 deletions example.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import argparse
import sys
import time

from radiacode import RadiaCode

Expand All @@ -24,8 +26,10 @@ def main():
print('--------')

print('### DataBuf:')
for v in rc.data_buf():
print(v)
while True:
for v in rc.data_buf():
print(v.dt.isoformat(), v)
time.sleep(2)


if __name__ == '__main__':
Expand Down
15 changes: 8 additions & 7 deletions radiacode/decoders/databuf.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,40 @@
import datetime
from typing import List, Union

from radiacode.bytes_buffer import BytesBuffer
from radiacode.types import CountRate, DoseRate, DoseRateDB, Event, RareData


def decode_VS_DATA_BUF(br: BytesBuffer) -> List[Union[CountRate, DoseRate, DoseRateDB, RareData, Event]]:
def decode_VS_DATA_BUF(br: BytesBuffer, base_time: datetime.datetime) -> List[Union[CountRate, DoseRate, DoseRateDB, RareData, Event]]:
ret: List[Union[CountRate, DoseRate, DoseRateDB, RareData, Event]] = []
next_seq = None
while br.size() > 0:
seq, eid, gid, ts_offset = br.unpack('<BBBi')
timestamp = ts_offset / 1000 # TODO: get base time
dt = base_time + datetime.timedelta(milliseconds=ts_offset)
if next_seq is not None and next_seq != seq:
raise Exception(f'seq jump, expect:{next_seq}, got:{seq}')

next_seq = (seq + 1) % 256
if eid == 0 and gid == 0: # GRP_CountRate
count, count_rate, flags = br.unpack('<HfH')
ret.append(CountRate(
timestamp=timestamp,
dt=dt,
count=count,
count_rate=count_rate,
flags=flags,
))
elif eid == 0 and gid == 1: # GRP_DoseRate
dose_rate, dose_rate_err, flags = br.unpack('<fHH')
ret.append(DoseRate(
timestamp=timestamp,
dt=dt,
dose_rate=dose_rate,
dose_rate_err=dose_rate_err * 0.1,
flags=flags,
))
elif eid == 0 and gid == 2: # GRP_DoseRateDB
count, count_rate, dose_rate, dose_rate_err, flags = br.unpack('<HffHH')
ret.append(DoseRateDB(
timestamp=timestamp,
dt=dt,
count=count,
count_rate=count_rate,
dose_rate=dose_rate,
Expand All @@ -43,7 +44,7 @@ def decode_VS_DATA_BUF(br: BytesBuffer) -> List[Union[CountRate, DoseRate, DoseR
elif eid == 0 and gid == 3: # GRP_RareData
duration, dose, temperature, charge_level, flags = br.unpack('<IfHHH')
ret.append(RareData(
timestamp=timestamp,
dt=dt,
duration=duration,
dose=dose,
temperature=temperature * 0.01 - 20,
Expand All @@ -53,7 +54,7 @@ def decode_VS_DATA_BUF(br: BytesBuffer) -> List[Union[CountRate, DoseRate, DoseR
elif eid == 0 and gid == 7: # GRP_Event
event, event_param1, flags = br.unpack('<BBH')
ret.append(Event(
timestamp=timestamp,
dt=dt,
event=event,
event_param1=event_param1,
flags=flags,
Expand Down
4 changes: 3 additions & 1 deletion radiacode/decoders/spectrum.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import datetime

from radiacode.bytes_buffer import BytesBuffer
from radiacode.types import Spectrum

Expand All @@ -8,7 +10,7 @@ def decode_RC_VS_SPECTRUM(br: BytesBuffer) -> Spectrum:
while br.size() > 0:
counts.append(br.unpack('<I')[0])
return Spectrum(
timestamp=ts,
duration=datetime.timedelta(seconds=ts),
a0=a0,
a1=a1,
a2=a2,
Expand Down
15 changes: 9 additions & 6 deletions radiacode/radiacode.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,12 @@ def __init__(self, bluetooth_mac: str = None):

# init
self.execute(b'\x07\x00', b'\x01\xff\x12\xff')
# self.status()
# self.device_time(0)
# self.set_local_time(datetime.datetime.now())
self._base_time = datetime.datetime.now()
self.set_local_time(self._base_time)
self.device_time(0)

def base_time(self) -> datetime.datetime:
return self._base_time

def execute(self, reqtype: bytes, args: bytes = None) -> BytesBuffer:
assert len(reqtype) == 2
Expand All @@ -43,7 +46,7 @@ def execute(self, reqtype: bytes, args: bytes = None) -> BytesBuffer:

response = self._connection.execute(full_request)
resp_header = response.unpack('<4s')[0]
assert req_header == resp_header, f'req={str(req_header)} resp={str(resp_header)}'
assert req_header == resp_header, f'req={req_header.hex()} resp={resp_header.hex()}'
return response

def read_request(self, command_id: Union[int, VS, VSFR]) -> BytesBuffer:
Expand Down Expand Up @@ -114,11 +117,11 @@ def commands(self) -> str:

# called with 0 after init!
def device_time(self, v: int) -> None:
self.write_request(VSFR.DEVICE_TIME, struct.pack('<H', v))
self.write_request(VSFR.DEVICE_TIME, struct.pack('<I', v))

def data_buf(self) -> List[Union[CountRate, DoseRate, DoseRateDB, RareData, Event]]:
r = self.read_request(VS.DATA_BUF)
return decode_VS_DATA_BUF(r)
return decode_VS_DATA_BUF(r, self._base_time)

def spectrum(self) -> Spectrum:
r = self.read_request(VS.SPECTRUM)
Expand Down
12 changes: 10 additions & 2 deletions radiacode/transports/bluetooth.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import struct

from bluepy.btle import DefaultDelegate, Peripheral
from bluepy.btle import BTLEDisconnectError, DefaultDelegate, Peripheral

from radiacode.bytes_buffer import BytesBuffer


class DeviceNotFound(Exception):
pass


class Bluetooth(DefaultDelegate):
def __init__(self, mac):
self._resp_buffer = b''
self._resp_size = 0
self._response = None

self.p = Peripheral(mac)
try:
self.p = Peripheral(mac)
except BTLEDisconnectError:
raise DeviceNotFound('Device not found or bluetooth adapter is not powered on')

self.p.withDelegate(self)

service = self.p.getServiceByUUID('e63215e5-7003-49d8-96b0-b024798fb901')
Expand Down
13 changes: 7 additions & 6 deletions radiacode/types.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
import datetime
from dataclasses import dataclass
from enum import Enum
from typing import List


@dataclass
class CountRate:
timestamp: float
dt: datetime.datetime
count: int
count_rate: int
flags: int


@dataclass
class DoseRate:
timestamp: float
dt: datetime.datetime
dose_rate: int
dose_rate_err: int
flags: int


@dataclass
class DoseRateDB:
timestamp: float
dt: datetime.datetime
count: int
count_rate: int
dose_rate: int
Expand All @@ -31,7 +32,7 @@ class DoseRateDB:

@dataclass
class RareData:
timestamp: float
dt: datetime.datetime
duration: int # for dose, in seconds
dose: int
temperature: int
Expand All @@ -41,15 +42,15 @@ class RareData:

@dataclass
class Event:
timestamp: float
dt: datetime.datetime
event: int
event_param1: int
flags: int


@dataclass
class Spectrum:
timestamp: float
duration: datetime.timedelta
a0: float
a1: float
a2: float
Expand Down

0 comments on commit c473cc3

Please sign in to comment.