Files
seismo-relay/sfm/device_access/s4.py
T

237 lines
8.5 KiB
Python

"""Series-4 sessions: call up once, stay on the line, hang up when idle.
⚠ Imports only minimateplus.transport from the Series-3 package. Nothing
here may build or send a Series-3 frame -- SESSION_RESET (41 03) has never
been sent to a Micromate.
"""
from __future__ import annotations
import logging
import time
from typing import Any, Callable, Optional, TypeVar
from micromate.client import MicromateClient
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
from .errors import CallHomeInProgress, WrongUnit, translate
from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus
from .series import normalise_serial
log = logging.getLogger("sfm.device_access")
T = TypeVar("T")
RING = b"RADIO RING"
S4_DEFAULT_BAUD = 115200
class RingDetected(Exception):
"""The unit sent RADIO RING: it is calling home up this connection."""
class RingWatchTransport(BaseTransport):
"""Passes bytes through; raises RingDetected the moment RADIO RING appears
OUTSIDE a frame, including when it is split across two reads.
Inside a frame the bytes are data: the 0x2C call-home config block's dial
string is literally "RADIO RING". A frame runs from STX to an unescaped
ETX; inside it DLE escapes the next byte.
"""
_STX, _ETX, _DLE = 0x02, 0x03, 0x10
def __init__(self, inner: BaseTransport) -> None:
self._inner = inner
self._tail = b""
self._in_frame = False
self._escaped = False
def connect(self) -> None:
self._inner.connect()
def disconnect(self) -> None:
self._inner.disconnect()
@property
def is_connected(self) -> bool:
return self._inner.is_connected
def write(self, data: bytes) -> None:
self._inner.write(data)
def read(self, n: int) -> bytes:
data = self._inner.read(n)
for b in data:
if self._in_frame:
if self._escaped:
self._escaped = False
elif b == self._DLE:
self._escaped = True
elif b == self._ETX:
self._in_frame = False
elif b == self._STX:
self._in_frame = True
self._tail = b""
else:
self._tail = (self._tail + bytes([b]))[-len(RING):]
if self._tail == RING:
self._tail = b""
raise RingDetected("RADIO RING")
return data
def default_s4_client_factory(address: UnitAddress, recv_timeout: float = 10.0) -> MicromateClient:
if address.host:
inner: BaseTransport = TcpTransport(address.host, port=address.tcp_port)
else:
inner = SerialTransport(address.port, address.baud or S4_DEFAULT_BAUD)
return MicromateClient(RingWatchTransport(inner), recv_timeout=recv_timeout)
def _close(client: Any) -> None:
try:
client.close()
except Exception: # noqa: BLE001
log.debug("close failed", exc_info=True)
_RING_MESSAGE = ("the unit started calling home; SFM hung up so the call can "
"reach THOR -- try again in a few minutes")
class Series4Session:
"""One held line to one Micromate.
`last_used` is the last *user* request: the idle hang-up measures it.
`last_traffic` is any exchange, keep-alives included: the keep-alive
schedule measures it. If keep-alives counted as use, the line would never
go idle.
"""
def __init__(self, address: UnitAddress, serial: str,
client_factory: Callable[[UnitAddress], Any],
clock: Callable[[], float] = time.monotonic) -> None:
self.address = address
self.serial = normalise_serial(serial)
self._factory = client_factory
self._clock = clock
self._client: Optional[Any] = None
self.info = None
self.last_used = clock()
self.last_traffic = self.last_used
@property
def is_open(self) -> bool:
return self._client is not None and self._client.is_open()
def call_up(self):
client = self._factory(self.address)
try:
client.open()
info = client.connect()
except RingDetected as exc:
_close(client)
log.warning("RADIO RING from %s during call-up -- released the line", self.address.key)
raise CallHomeInProgress(_RING_MESSAGE) from exc
except Exception as exc:
_close(client)
raise translate(exc, connecting=True) from exc
if normalise_serial(info.serial) != self.serial:
_close(client)
raise WrongUnit(f"asked for {self.serial} but {info.serial} answered at {self.address.key}")
self._client, self.info = client, info
self.last_used = self.last_traffic = self._clock()
log.info("call-up: %s at %s, staying on the line", self.serial, self.address.key)
return info
def _exchange(self, op: Callable[[Any], T]) -> T:
try:
return op(self._client)
except RingDetected as exc:
self.hang_up()
log.warning("RADIO RING from %s -- released the line so the call reaches THOR",
self.address.key)
raise CallHomeInProgress(_RING_MESSAGE) from exc
except Exception as exc:
self.hang_up()
raise translate(exc, connecting=False) from exc
def run(self, op: Callable[[Any], T]) -> T:
"""A user request. Calls up first if the line is not open."""
if not self.is_open:
self.call_up()
result = self._exchange(op)
self.last_used = self.last_traffic = self._clock()
return result
def keepalive(self) -> None:
"""A POLL so the modem's idle timer does not drop the line. Not use."""
if not self.is_open:
return
self._exchange(lambda c: c.protocol.poll())
self.last_traffic = self._clock()
def listen(self) -> None:
"""Read anything the unit sent unprompted; send nothing. Not use."""
if not self.is_open:
return
self._exchange(lambda c: c.read_unsolicited())
def hang_up(self) -> None:
if self._client is not None:
_close(self._client)
self._client = None
log.info("hang-up: %s at %s", self.serial, self.address.key)
# ── Operations (each runs inside Series4Session.run) ──────────────────────────
def s4_identify(client: Any, serial: str) -> UnitInfo:
info = client.connect()
return UnitInfo(
serial=info.serial, series=4, model=info.model,
firmware=None, # the version string lives in 0x01, undecoded
monitoring=info.monitoring, active_setup=info.active_setup,
detail={"manufacturer": info.manufacturer, "firmware_line": info.firmware_line},
)
def s4_status(client: Any, serial: str) -> UnitStatus:
st = client.get_state()
count = client.get_event_count()
return UnitStatus(
serial=serial, series=4, monitoring=st.monitoring, battery_volts=st.battery_volts,
memory_total_bytes=st.memory_total_bytes, memory_free_bytes=st.memory_free_bytes,
device_time=st.device_time.isoformat() if st.device_time else None,
event_count=count,
)
def s4_settings(client: Any, serial: str) -> UnitSettings:
s = client.get_setup()
return UnitSettings(
serial=serial, series=4, setup_name=s.name, record_mode=s.record_mode_name,
sample_rate=s.sample_rate, record_time_s=s.record_time_s,
histogram_interval_s=s.histogram_interval_s,
geo_trigger_ips=s.geo_trigger_ips[0], # the keypad writes all three the same
notes=dict(s.notes),
detail={
"pretrigger_s": s.pretrigger_s,
"auto_record_stop": s.auto_record_stop,
"auto_stop_after_s": s.auto_stop_after_s,
"geophones_active": s.geophones_active,
"mic_active": s.mic_active,
"trigger_on_geophones": s.trigger_on_geophones,
"trigger_on_mic": s.trigger_on_mic,
"geo_trigger_ips_per_channel": list(s.geo_trigger_ips),
"mic_type": s.mic_type,
"mic_trigger_psi": s.mic_trigger_psi,
"mic_trigger_db": s.mic_trigger_db,
"job_number_enabled": s.job_number_enabled,
"job_number": s.job_number,
"scaled_distance_enabled": s.scaled_distance_enabled,
"distance_ft": s.distance_ft,
"charge_weight_lb": s.charge_weight_lb,
"scaled_distance": s.scaled_distance,
},
)