Ohara Lab

Saving measurement files on the caller’s computer with gRPC

Transparent API contract · gRPC guide · 日本語

When used directly, the DeviceClass’s export_data(filename) writes the measurement to the specified location and returns the file path. With a DeviceServer on the instrument host, simply forwarding the same call would interpret filename on that host and leave the caller without a local file.

SUSANOO divides the adaptations between the server and client. The ServerClass inherits the DeviceClass, invokes the original save, and returns the file contents. The ClientClass writes those contents at the caller’s destination. The DeviceClass remains unchanged, and callers retain the original argument, return value, and destination semantics.

Ordinary reads such as read_value() preserve their meaning as-is. This tutorial focuses on changing only the methods that need adaptation.

1. Decide what to change on each side

Operation Server side Client side Reason
read_value() and other operations that keep their meaning remotely Inherit the existing method Use automatic binding The value or instrument-side operation keeps its meaning
export_data(filename) saves at the caller’s destination Run the original save in a temporary directory and return the contents Receive and write the contents at the caller’s destination The instrument and destination are on different hosts
save_parameters(path) when get_parameters() returns a dictionary May need no adaptation Fetch the dictionary and save it locally No temporary server file is needed
Long-running stream of data Use stream_obj where needed Use stream_call() where needed Successive delivery is required

The ServerClass overrides the private exchange behind export_data() to return transferable data. The ClientClass turns those data back into a file. The reply format is an implementation agreement between the two classes. read_value() uses the original implementation and ordinary dispatch.

2. Project layout and installation

file_export_demo/
├── file_device.py    # Transport-independent DeviceClass
├── server.py         # ServerClass derived from the DeviceClass
└── client.py         # ClientClass derived from GrpcClient
python -m pip install grpc-frame

grpc-frame is the PyPI distribution name, and grpc_frame is the Python import name. Place all three files in one directory. The example assumes Python 3.8 or later. Check the dependencies and supported versions of the distribution you use.

3. file_device.py: the existing transport-independent DeviceClass

#!/usr/bin/env python
from pathlib import Path

class FileDevice:
    def read_value(self) -> int:
        return 42

    def export_data(self, filename: str = "result.dat") -> str:
        path = Path(filename)
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(b"device result\n")
        return str(path)

FileDevice().export_data("local.dat") creates a file on the caller’s computer. The server module below inherits the class from this file.

4. server.py: convert the instrument-side result for transfer

#!/usr/bin/env python
import hashlib
from pathlib import Path
from tempfile import TemporaryDirectory

from grpc_frame.grpc_server import create_grpc_server

from file_device import FileDevice

class FileServerDevice(FileDevice):
    def export_data(self, filename: str = "result.dat") -> dict:
        # The caller's filename does not determine the instrument-side path.
        with TemporaryDirectory(prefix="grpc_frame_export_") as directory:
            server_path = Path(directory) / "result.dat"
            generated = Path(super().export_data(str(server_path)))
            if not generated.is_file():
                raise FileNotFoundError(str(generated))
            data = generated.read_bytes()
            return {
                "name": generated.name,
                "data": data,
                "size": len(data),
                "sha256": hashlib.sha256(data).hexdigest(),
            }

def main() -> None:
    ctrl = FileServerDevice()
    server = create_grpc_server(
        ctrl_obj=ctrl,
        max_workers=4,
        grpc_options=(("grpc.max_send_message_length", 32 * 1024 * 1024),),
    )
    if server.add_insecure_port("127.0.0.1:50051") == 0:
        raise RuntimeError("gRPCポートを確保できません")
    server.start()
    try:
        server.wait_for_termination()
    finally:
        server.stop(grace=2)

if __name__ == "__main__":
    main()

super().export_data() reuses the DeviceClass save. The override changes the instrument-side location to temporary storage and returns transferable data. TemporaryDirectory removes its contents after the read. An export failure produces no successful reply. The example assumes one synchronously generated file. For a device that names files automatically, check the return value of super() against the output and confirm completion using the instrument’s own mechanism.

5. client.py: save the received contents at the caller’s destination

#!/usr/bin/env python
import hashlib
import os
from pathlib import Path
from tempfile import NamedTemporaryFile

from grpc_frame.grpc_client import GrpcClient

class FileGrpcClient(GrpcClient):
    def __init__(self, server_ip: str, server_port: int) -> None:
        options = (
            ("grpc.max_receive_message_length", 32 * 1024 * 1024),
            ("grpc.max_send_message_length", 32 * 1024 * 1024),
        )
        super().__init__(
            server_ip=server_ip,
            server_port=server_port,
            grpc_options=options,
        )
        if "export_data" not in self.__dict__:
            raise RuntimeError("サーバーがexport_dataを公開していません")
        # Remove the dynamic attribute so the subclass method is selected.
        del self.__dict__["export_data"]
        # The original dispatcher stays in self._raw_export_data.

    def export_data(self, filename: str = "result.dat") -> str:
        # Keep the destination filename on the caller's host.
        response = self._raw_export_data()
        if not isinstance(response, dict):
            raise TypeError("export_dataの応答は辞書である必要があります")
        data = response.get("data")
        if not isinstance(data, bytes):
            raise TypeError("dataはbytesである必要があります")
        if response.get("size") != len(data):
            raise ValueError("受信サイズが一致しません")
        if response.get("sha256") != hashlib.sha256(data).hexdigest():
            raise ValueError("受信データのハッシュが一致しません")

        path = Path(filename)
        path.parent.mkdir(parents=True, exist_ok=True)
        temporary = None
        try:
            with NamedTemporaryFile(
                mode="wb",
                prefix=".grpc_frame_",
                dir=path.parent,
                delete=False,
            ) as handle:
                temporary = Path(handle.name)
                handle.write(data)
            os.replace(temporary, path)
        finally:
            if temporary is not None:
                temporary.unlink(missing_ok=True)
        return str(path)

def main() -> None:
    client = FileGrpcClient(server_ip="127.0.0.1", server_port=50051)
    try:
        assert client.read_value() == 42
        saved = client.export_data("output/result.dat")
        assert Path(saved).read_bytes() == b"device result\n"
        print(saved)
    finally:
        client.close()

if __name__ == "__main__":
    main()

The caller’s filename stays on the client. The raw result from FileServerDevice.export_data() is an internal dictionary agreed between the ServerClass and ClientClass. The public FileGrpcClient.export_data() returns the saved path, like the original DeviceClass. read_value() uses dynamic dispatch.

This example constructs FileGrpcClient directly. It serves as the DeviceProxy. Consider factory registration when several devices must be selected by name.

GrpcClient.__init__() installs self.export_data as an instance attribute from the server’s Describe response. That attribute shadows a same-name method in the subclass. After super().__init__(), remove only the targeted attribute. The original remote dispatcher remains in _raw_export_data. CapInspector uses the same attribute-removal pattern.

The ClientClass owns the destination path. os.replace() moves the completed temporary file to that path on the same filesystem. This replaces an existing destination. If overwrites must be prohibited, enforce that policy separately.

6. Run the example and verify the result

Start the server in the first terminal. To verify the destination, invoke client.py by its full path from another working directory.

python server.py

While the server is listening, run the client in another terminal.

python client.py

The client creates output/result.dat containing device result followed by a newline. read_value() returns 42 through Describe and Call. For comparison, call FileDevice().export_data("local.dat") directly.

Expected execution sequence

Step Host Operation What to verify
1 Client FileGrpcClient.__init__() Describe returns read_value and export_data
2 Client del self.__dict__["export_data"] The ClientClass override is selected
3 Client _raw_export_data(...) Call reaches the server
4 Server FileServerDevice.export_data() The original save runs in a temporary directory
5 Server read_bytes() File contents are returned in the dictionary
6 Client Type, length, and SHA-256 checks The received data pass validation
7 Client os.replace() The file appears at the caller’s destination

7. Connect the example to the frame implementation

Source Behavior Effect in this example
dispatch_core.py Enumerates public callables with dir() and inspect.getattr_static() and excludes properties export_data is discovered. @property is not automatically exposed
grpc_server.py Implements Describe, Call, StreamCall, and create_grpc_server Providing ctrl_obj is sufficient
grpc_client.py _bind_remote_methods() installs setattr(self, name, dispatcher) and _raw_ bindings Remove only the targeted instance attribute
adapter.py Prefers JSON, uses base64 for bytes, and falls back to pickle The dictionary can carry bytes. Base64 increases its encoded size
grpc_com.py create_com_grpc_server(ctrl_factory=...) constructs the object and routes calls on a dedicated thread Consider this for thread-affine COM control
ctrl.proto Defines common Describe, Call, and StreamCall RPCs No device-specific .proto is needed

_raw_<name> is the dynamic binding name in the version of grpc_frame used here. Check it against the version you use.

Transport boundary and data checks in this example

This sample uses add_insecure_port() and grpc.insecure_channel() over 127.0.0.1. These are unencrypted connections intended for the local example. Changing only the bind address to make the server accessible from another host is not a secure deployment strategy. The operational environment must separately address which clients may connect, how they are authenticated, and how the communication channel is protected.

The SHA-256 comparison on the receiving side checks whether the returned data agrees with the hash supplied in the same response. It does not authenticate the sender or prevent a malicious peer from changing both the payload and the hash. Moreover, adapter.py falls back to pickle for values that cannot be encoded as JSON. The dictionary and bytes used here fit the JSON representation, but that does not make the Frame as a whole a JSON-only deserializer. Do not expose this serialization boundary to untrusted peers without an appropriate security design.

8. Choose between Call and StreamCall

Call is one request and one response. It suffices when the file fits in one byte string and both peers can accommodate its message size and memory use. StreamCall sends values yielded by a stream_obj iterator. Use it for large or successive data and consider chunk indices, the final chunk, validation, and cancellation handling at the application level.

When setting server grpc.max_send_message_length and client grpc.max_receive_message_length through grpc_options, include base64 and JSON overhead, not only the original file size. The 32 MiB values configured on both sides of the sample do not guarantee that a 32 MiB file can be transferred. This example is for small files, not an unrestricted file-transfer service.

9. Review the contract for a real instrument

Here FileDevice saves synchronously and returns the generated path. Verify these details for the actual DeviceClass before implementing the ServerClass:

  1. Whether export_data() accepts a file path or operates a save dialog.
  2. Whether the operation returns a path, a success code, or None.
  3. Whether the instrument chooses the destination directory and filename.
  4. Whether one operation generates more than one file.
  5. What confirms completion. Successfully pressing a GUI button does not confirm that the file was written.
  6. Whether instrument-side work continues after a timeout and whether a retry can generate duplicate files.
  7. How concurrent calls and temporary-file conflicts are handled.
  8. Whether exceptions, return values, logging, and local save semantics carry over.
  9. The transfer size, message limits on each side, and whether chunking is needed.
  10. Caller-side permissions, overwrites, partial files, and integrity checks.

Design dialog handling, automatic naming, and completion detection around the actual DeviceClass and instrument behavior. Completion of a frame call alone does not establish that the instrument has finished generating the file.

10. Troubleshooting

Symptom Cause Where to check
The client override is skipped GrpcClient installed an instance attribute of the same name self.__dict__ and _bind_remote_methods()
The method recurses The override calls self.export_data() Call _raw_export_data()
The file appears only on the server Only a path string was returned Read the bytes on the server and write them on the client
@property is unavailable Describe excludes properties dispatch_core.py and any explicit getter
Large files fail over RPC Message limit or base64 overhead grpc_options on both sides or StreamCall
The file is empty or partial It was read before export completed The device’s completion condition
GUI or COM fails on startup Instrument-side thread requirements grpc_com.py and the instrument’s requirements
A client method is missing It is absent from Describe or is not public list_public_methods() and the published API

Return to the DeviceServer development guide