openflexure-microscope-server/src/openflexure_microscope_server/server/legacy_api.py
2025-12-02 16:26:15 +00:00

47 lines
1.5 KiB
Python

"""Provide endpoints that mimic the v2 API for OpenFlexure Connect discoverability."""
from socket import gethostname
from fastapi import Response
import labthings_fastapi as lt
FAKE_ROUTES = [
"/api/v2/",
"/api/v2/streams/snapshot",
"/api/v2/instrument/settings/name",
]
class JPEGResponse(Response):
"""A FastAPI response with media_type set for a JPEG image."""
media_type = "image/jpeg"
def add_v2_endpoints(thing_server: lt.ThingServer) -> None:
"""Add the v2 API endpoints for OpenFlexure Connect discoverability."""
app = thing_server.app
# The endpoints below fool OpenFlexure Connect into thinking we are a
# v2 microscope, so we show up correctly.
# This is necessary until Connect is rebuilt. See #557.
@app.get("/routes")
def routes_stub() -> dict[str, dict]:
"""Return a stub list of routes.
This is used by OF Connect to identify the microscope.
"""
return {url: {"url": url, "methods": ["GET"]} for url in FAKE_ROUTES}
@app.get("/api/v2/streams/snapshot")
@app.head("/api/v2/streams/snapshot")
async def thumbnail() -> JPEGResponse:
"""Return a low-resolution snapshot, for compatibility with OF connect."""
blob = await thing_server.things["/camera/"].lores_mjpeg_stream.grab_frame()
return JPEGResponse(blob)
@app.get("/api/v2/instrument/settings/name")
def get_hostname() -> str:
"""Get the hostname of the device, for compatibility with OF connect."""
return gethostname()