"""Read experiment temperature history from the local tempproxy service. Example: client = TemperatureProxyClient() temperature = client.get_history(start_epoch, end_epoch) """ import http.client import json import logging from urllib.parse import urlencode from urllib.request import urlopen from damaris.data.Temperature import TemperatureResult logger = logging.getLogger(__name__) class TemperatureProxyClient: """Retrieve experiment-bounded readings from ``localhost:8000``.""" URL = "http://localhost:8000/v1/readings" TIMEOUT = 5 def get_history(self, start_epoch: float, end_epoch: float) -> TemperatureResult | None: """Return temperature history relative to the experiment start, or ``None``. Readings retain the proxy's ``pv`` units; an empty result or failed request returns ``None``. Example: temperature = TemperatureProxyClient().get_history(1000.0, 1060.0) """ query = urlencode({"start": start_epoch, "end": end_epoch}) url = f"{self.URL}?{query}" try: with urlopen(url, timeout=self.TIMEOUT) as response: payload = json.loads(response.read()) readings = payload["readings"] if not isinstance(readings, list): raise ValueError("response 'readings' must be a list") if not readings: return None x = [float(reading["t"]) - start_epoch for reading in readings] y = [float(reading["pv"]) for reading in readings] return TemperatureResult(x=x, y=y) except (OSError, http.client.HTTPException, ValueError, TypeError, KeyError) as error: logger.warning("Unable to retrieve temperature history from tempproxy: %s", error) return None