smartlab-studio-ctrl 0.2.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ """SmartLab Studio II のデバイス制御。"""
2
+
3
+ import sys
4
+
5
+ from smartlab_studio_ctrl.desktop_capture import DesktopCapture
6
+
7
+ if sys.platform == "win32":
8
+ from smartlab_studio_ctrl.smartlab_ctrl import SmartLabCtrl
9
+ from smartlab_studio_ctrl.smartlab_uia import SmartLabUIA
10
+
11
+ from smartlab_studio_ctrl.smartlab_config import SmartLabConfig
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env python
2
+ """SmartLab control and gRPC connection configuration.
3
+
4
+ GUI element paths remain in smartlab_config.SmartLabConfig.
5
+ """
6
+ from pathlib import Path
7
+ from typing import Union
8
+ import yaml
9
+
10
+
11
+ class Config:
12
+ SERVER_IP = "127.0.0.1"
13
+ SERVER_PORT = 50051
14
+ TIMEOUT = None
15
+ LOGGER_LEVEL = "INFO"
16
+
17
+ def __init__(self, yaml_path=None):
18
+ if yaml_path is not None:
19
+ self._load_yaml(yaml_path)
20
+
21
+ def _load_yaml(self, yaml_path):
22
+ path = Path(yaml_path).expanduser()
23
+ with path.open(encoding="utf-8") as f:
24
+ data = yaml.safe_load(f)
25
+ if not isinstance(data, dict):
26
+ raise ValueError("設定ファイルの内容はYAMLマッピングで指定してください")
27
+ for key, value in data.items():
28
+ if not hasattr(type(self), key):
29
+ raise ValueError(f"不明な設定項目: {key}")
30
+ setattr(self, key, value)
31
+
32
+ @classmethod
33
+ def load_yaml(cls, yaml_path):
34
+ """Cobottaと同様、クラスのデフォルト値を一括更新する。"""
35
+ values = cls(yaml_path)
36
+ for key in ("SERVER_IP", "SERVER_PORT", "TIMEOUT", "LOGGER_LEVEL"):
37
+ setattr(cls, key, getattr(values, key))
@@ -0,0 +1,215 @@
1
+ """デスクトップを直接撮影し、PNGを返す。"""
2
+
3
+ from io import BytesIO
4
+ import logging
5
+ from pathlib import Path
6
+ from platform import machine
7
+ import sys
8
+ from tempfile import TemporaryDirectory
9
+ from threading import Event, Lock
10
+ from typing import Any, Optional, Union
11
+
12
+ from PIL import Image, ImageGrab
13
+
14
+
15
+ class DesktopCapture:
16
+ """デスクトップを直接撮影し、PNGをメモリに取得する。
17
+
18
+ Windows x64ではWindows Graphics Captureで各モニターから1枚ずつ
19
+ 取得し、画面配置に沿って1枚に合成する。撮影と任意の保存が終わるまで
20
+ 同時実行を拒否する。
21
+ """
22
+
23
+ _capture_lock = Lock()
24
+ _phase = "READY"
25
+
26
+ def __init__(
27
+ self,
28
+ logger: Optional[Any] = None,
29
+ log_level: Optional[str] = None,
30
+ ) -> None:
31
+ """ロガーを設定する。
32
+
33
+ Args:
34
+ logger: 既存のロガー。省略時は標準loggingを使用する。
35
+ log_level: 標準ロガーを使う場合のログレベル。
36
+ """
37
+ if logger is None:
38
+ if log_level is None:
39
+ log_level = "INFO"
40
+ logging.basicConfig(level=log_level.upper())
41
+ logger = logging.getLogger(__name__)
42
+ self._logger = logger
43
+
44
+ def get_state(self) -> str:
45
+ """プロセス内で共有する撮影状態を返す。
46
+
47
+ Returns:
48
+ 待機中はREADY、保存先の確認中はSTARTING、画像取得・PNG変換中は
49
+ CAPTURING、指定先への書き込み中はSAVING。
50
+ """
51
+ return DesktopCapture._phase
52
+
53
+ def get_screenshot_state(self) -> str:
54
+ """SmartLabCtrlと同じメソッド名で撮影状態を返す。"""
55
+ return self.get_state()
56
+
57
+ def capture_screenshot(
58
+ self,
59
+ output_directory: Optional[Union[str, Path]] = None,
60
+ ) -> bytes:
61
+ """デスクトップを撮影し、指定先への保存が終わってから返す。
62
+
63
+ Args:
64
+ output_directory: PNGを保存する既存フォルダ。指定時は
65
+ screenshot_local.png を書き、同名ファイルを置き換える。
66
+
67
+ Returns:
68
+ 撮影したPNG画像のバイト列。
69
+
70
+ Raises:
71
+ FileNotFoundError: 指定した保存先フォルダが存在しない場合。
72
+ RuntimeError: 別の撮影・保存が進行中の場合。
73
+ OSError: デスクトップの撮影やファイルの保存に失敗した場合。
74
+ """
75
+ if not self._capture_lock.acquire(blocking=False):
76
+ raise RuntimeError("スクリーンショットの撮影または保存が進行中です")
77
+ try:
78
+ DesktopCapture._phase = "STARTING"
79
+ directory = None
80
+ if output_directory is not None:
81
+ directory = Path(output_directory).expanduser().resolve()
82
+ if not directory.is_dir():
83
+ raise FileNotFoundError(
84
+ f"スクリーンショットの保存先がありません: {directory}"
85
+ )
86
+
87
+ DesktopCapture._phase = "CAPTURING"
88
+ self._logger.info("Capturing desktop")
89
+ data = self._capture_screenshot_png()
90
+ if directory is not None:
91
+ DesktopCapture._phase = "SAVING"
92
+ target = directory / "screenshot_local.png"
93
+ # 書き込みが完了したPNGだけで既存ファイルを置き換える。
94
+ temporary = TemporaryDirectory(dir=directory)
95
+ try:
96
+ pending = Path(temporary.name) / target.name
97
+ pending.write_bytes(data)
98
+ pending.replace(target)
99
+ finally:
100
+ temporary.cleanup()
101
+ self._logger.info(f"Screenshot saved: {target}")
102
+ self._logger.info(f"Desktop capture completed ({len(data)} bytes)")
103
+ return data
104
+ except Exception as exc:
105
+ self._logger.error(f"Desktop capture failed: {exc}")
106
+ raise
107
+ finally:
108
+ DesktopCapture._phase = "READY"
109
+ self._capture_lock.release()
110
+
111
+ def _capture_screenshot_png(self) -> bytes:
112
+ """プラットフォームの撮影処理を呼び、メモリ上でPNGに変換する。"""
113
+ buffer = BytesIO()
114
+ try:
115
+ if sys.platform == "win32" and machine() == "AMD64":
116
+ image = self._capture_screenshot_windows()
117
+ else:
118
+ image = ImageGrab.grab(all_screens=True)
119
+ try:
120
+ image.save(buffer, format="PNG")
121
+ finally:
122
+ image.close()
123
+ return buffer.getvalue()
124
+ finally:
125
+ buffer.close()
126
+
127
+ def _capture_screenshot_windows(self) -> Image.Image:
128
+ """各モニターの物理座標とWGCのフレームから全画面を合成する。"""
129
+ import win32api
130
+ import win32con
131
+
132
+ # WGCのモニター番号はEnumDisplayMonitorsの列挙順で1から始まる。
133
+ # EnumDisplaySettingsはDPI倍率によらず、配置とサイズを物理ピクセルで返す。
134
+ displays = []
135
+ for monitor, _, _ in win32api.EnumDisplayMonitors():
136
+ device = win32api.GetMonitorInfo(monitor)["Device"]
137
+ mode = win32api.EnumDisplaySettings(device, win32con.ENUM_CURRENT_SETTINGS)
138
+ origin = (mode.Position_x, mode.Position_y)
139
+ size = (mode.PelsWidth, mode.PelsHeight)
140
+ displays.append((origin, size))
141
+ if not displays:
142
+ raise OSError("撮影可能なモニターがありません")
143
+
144
+ left = min(x for (x, _), _ in displays)
145
+ top = min(y for (_, y), _ in displays)
146
+ right = max(x + w for (x, _), (w, _) in displays)
147
+ bottom = max(y + h for (_, y), (_, h) in displays)
148
+ desktop = Image.new("RGB", (right - left, bottom - top))
149
+ try:
150
+ for index, ((x, y), size) in enumerate(displays, start=1):
151
+ pixels = self._capture_screenshot_monitor(index, size)
152
+ frame = Image.frombytes("RGB", size, pixels, "raw", "BGRX")
153
+ try:
154
+ desktop.paste(frame, (x - left, y - top))
155
+ finally:
156
+ frame.close()
157
+ return desktop
158
+ except BaseException:
159
+ desktop.close()
160
+ raise
161
+
162
+ @staticmethod
163
+ def _capture_screenshot_monitor(index: int, size: tuple[int, int]) -> bytes:
164
+ """WGCで指定モニターの最初のフレームをコピーし、取得を終了する。"""
165
+ from windows_capture import WindowsCapture
166
+
167
+ capture = WindowsCapture(cursor_capture=False, monitor_index=index)
168
+ completed = Event()
169
+ pixels = None
170
+ failure = None
171
+
172
+ @capture.event
173
+ def on_frame_arrived(frame, capture_control):
174
+ """コールバックが所有するフレームからBGRAの値をコピーする。"""
175
+ nonlocal pixels, failure
176
+ try:
177
+ if (frame.width, frame.height) != size:
178
+ raise OSError(f"撮影中にモニター {index} のサイズが変わりました")
179
+ pixels = frame.frame_buffer.tobytes()
180
+ except Exception as exc:
181
+ failure = exc
182
+ finally:
183
+ capture_control.stop()
184
+ completed.set()
185
+
186
+ @capture.event
187
+ def on_closed():
188
+ """フレームの取得前に撮影対象が閉じた場合も待機を解除する。"""
189
+ completed.set()
190
+
191
+ control = capture.start_free_threaded()
192
+ received = False
193
+ try:
194
+ received = completed.wait(timeout=5)
195
+ finally:
196
+ if received:
197
+ control.wait()
198
+ else:
199
+ control.stop()
200
+ if not received:
201
+ raise TimeoutError(f"モニター {index} のフレーム取得がタイムアウトしました")
202
+ if failure is not None:
203
+ raise failure
204
+ if pixels is None:
205
+ raise OSError(f"モニター {index} のフレームを取得できませんでした")
206
+ return pixels
207
+
208
+
209
+ if __name__ == "__main__":
210
+ # カレントディレクトリにPNGを保存し、同じ画像をバイト列でも取得する。
211
+ # バイト列だけが必要な場合は output_directory を省略する。
212
+ capture = DesktopCapture()
213
+ output_directory = Path.cwd()
214
+ png = capture.capture_screenshot(output_directory=output_directory)
215
+ print(f"保存先: {output_directory / 'screenshot_local.png'} ({len(png)} バイト)")
@@ -0,0 +1 @@
1
+ """grpc_frame による SmartLab デバイスサーバー。"""
@@ -0,0 +1,230 @@
1
+ #!/usr/bin/env python
2
+ """SmartLab Studio II専用gRPCクライアント。"""
3
+
4
+ from pathlib import Path, PureWindowsPath
5
+ from tempfile import TemporaryDirectory
6
+ import os
7
+ from typing import Any, Optional, Union
8
+
9
+ from smartlab_studio_ctrl.config import Config
10
+ from grpc_frame.grpc_client import GrpcClient
11
+ from grpc_frame.device_proxy import DeviceProxy, register_device_proxy
12
+
13
+
14
+ _GRPC_OPTIONS = (
15
+ ("grpc.max_receive_message_length", 64 * 1024 * 1024),
16
+ ("grpc.max_send_message_length", 64 * 1024 * 1024),
17
+ )
18
+
19
+
20
+ class SmartLabGrpcClient(GrpcClient):
21
+ """ファイル保存だけをオーバーライドし、他は動的RPCを使用する。"""
22
+
23
+ def __init__(
24
+ self,
25
+ server_ip: Optional[str] = None,
26
+ server_port: Optional[int] = None,
27
+ timeout_sec: Optional[float] = None,
28
+ logger: Optional[Any] = None,
29
+ log_level: Optional[str] = None,
30
+ config: Optional[Config] = None,
31
+ ) -> None:
32
+ cfg = Config
33
+ if config is not None:
34
+ cfg = config
35
+
36
+ if server_ip is None:
37
+ server_ip = cfg.SERVER_IP
38
+ if server_port is None:
39
+ server_port = cfg.SERVER_PORT
40
+ if timeout_sec is None:
41
+ timeout_sec = cfg.TIMEOUT
42
+ if log_level is None:
43
+ log_level = cfg.LOGGER_LEVEL
44
+ super().__init__(
45
+ server_ip=server_ip,
46
+ server_port=server_port,
47
+ timeout_sec=timeout_sec,
48
+ logger=logger,
49
+ log_level=log_level,
50
+ grpc_options=_GRPC_OPTIONS,
51
+ )
52
+ self._logger.info(
53
+ f"SmartLab gRPC client接続: {server_ip}:{server_port}"
54
+ )
55
+ # Describeが登録したインスタンス属性を除去し、継承先のメソッドを有効化。
56
+ # _raw_export_dataには元のリモート呼び出しが保持されている。
57
+ if "export_data" not in self.__dict__:
58
+ raise RuntimeError("サーバーにexport_dataが公開されていません")
59
+ self._raw_export_data = self.__dict__["export_data"]
60
+ del self.__dict__["export_data"]
61
+ # 同名の単発RPCより、クライアントのストリーム版を優先する。
62
+ self.__dict__.pop("capture_screenshot", None)
63
+
64
+ def capture_screenshot(
65
+ self,
66
+ output_directory: Optional[Union[str, Path]] = None,
67
+ ) -> bytes:
68
+ """サーバーで撮影したPNGを受信し、指定時はクライアント側に保存する。
69
+
70
+ Args:
71
+ output_directory: クライアント側の既存フォルダ。指定時は
72
+ screenshot_local.png を保存し、同名ファイルを置き換える。
73
+
74
+ Returns:
75
+ 受信したPNGのバイト列。
76
+
77
+ Raises:
78
+ FileNotFoundError: クライアント側の保存先が存在しない場合。
79
+ RuntimeError: サーバーの撮影またはストリームが失敗した場合。
80
+ """
81
+ target = None
82
+ if output_directory is not None:
83
+ directory = Path(output_directory).expanduser().resolve()
84
+ if not directory.is_dir():
85
+ raise FileNotFoundError(f"クライアント側の保存先がありません: {directory}")
86
+ target = directory / "screenshot_local.png"
87
+
88
+ self._logger.info(f"Requesting desktop screenshot: {target}")
89
+ try:
90
+ buffer = bytearray()
91
+ chunks = self.stream_call("capture_screenshot")
92
+ try:
93
+ for chunk in chunks:
94
+ if not isinstance(chunk, bytes):
95
+ raise TypeError("スクリーンショットの応答がバイト列ではありません")
96
+ buffer.extend(chunk)
97
+ finally:
98
+ chunks.close()
99
+ data = bytes(buffer)
100
+ if not data:
101
+ raise RuntimeError("スクリーンショットの応答が空です")
102
+ if target is not None:
103
+ # 受信が最後まで成功したPNGだけを保存先に公開する。
104
+ temporary = TemporaryDirectory(dir=target.parent)
105
+ try:
106
+ pending = Path(temporary.name) / target.name
107
+ pending.write_bytes(data)
108
+ pending.replace(target)
109
+ finally:
110
+ temporary.cleanup()
111
+ self._logger.info(f"Desktop screenshot received: {len(data)} bytes, path={target}")
112
+ return data
113
+ except Exception as exc:
114
+ self._logger.error(f"Desktop screenshot request failed: {exc}")
115
+ raise
116
+
117
+ def export_data(
118
+ self,
119
+ filename: Optional[str] = None,
120
+ save: bool = False,
121
+ server_filename: Optional[str] = None,
122
+ graph: str = "2theta",
123
+ file_timeout_sec: float = 120.0,
124
+ client_overwrite: bool = False,
125
+ server_overwrite: bool = False,
126
+ ) -> Optional[str] | bool:
127
+ """サーバー保存先とクライアント保存先を独立に指定する。
128
+
129
+ filename はクライアント側、server_filename は装置PC側のパス。
130
+ filename=None ではサーバーが返したファイル名を使い、
131
+ クライアントのカレントディレクトリに保存する。
132
+ server_filename=None ではサーバー側の一時ディレクトリを使用する。
133
+ client_overwrite はクライアント側ファイルの上書きを許可する。
134
+ server_overwrite は装置PC側ファイルの上書きを許可する。
135
+ 通信全体のタイムアウトは生成時の timeout_sec で指定する。
136
+ """
137
+ if file_timeout_sec <= 0:
138
+ raise ValueError("file_timeout_secは正の数を指定してください")
139
+ if not save:
140
+ return self._raw_export_data(
141
+ filename=None, save=False, server_filename=server_filename,
142
+ graph=graph, file_timeout_sec=file_timeout_sec,
143
+ server_overwrite=server_overwrite,
144
+ )
145
+ if filename is not None and not filename.strip():
146
+ raise ValueError("filenameが空です")
147
+ if server_filename is not None and not server_filename.strip():
148
+ raise ValueError("server_filenameが空です")
149
+ # リモート操作前にクライアント側の保存先を確認する。
150
+ # WindowsパスをmacOS/Linuxで指定すると、通常のファイル名として
151
+ # 解釈されるため、明示的に拒否する。
152
+ if filename is not None:
153
+ if os.name != "nt" and PureWindowsPath(filename).drive:
154
+ raise ValueError(
155
+ f"クライアント側にWindows形式のパスが指定されています: {filename}"
156
+ )
157
+ target = Path(filename)
158
+ if not target.parent.is_dir():
159
+ raise FileNotFoundError(
160
+ f"クライアント側保存ディレクトリがありません: {target.parent}"
161
+ )
162
+ if target.exists() and not client_overwrite:
163
+ raise FileExistsError(
164
+ f"クライアント側保存ファイルが既に存在します: {target}"
165
+ )
166
+ elif not Path.cwd().is_dir():
167
+ raise FileNotFoundError(
168
+ f"クライアントのカレントディレクトリがありません: {Path.cwd()}"
169
+ )
170
+
171
+ self._logger.info(
172
+ f"gRPC export_data開始: filename={filename!r}, "
173
+ f"server_filename={server_filename!r}, graph={graph!r}, "
174
+ f"client_overwrite={client_overwrite}, server_overwrite={server_overwrite}"
175
+ )
176
+ try:
177
+ result = self._raw_export_data(
178
+ filename=None, save=True, server_filename=server_filename,
179
+ graph=graph, file_timeout_sec=file_timeout_sec,
180
+ server_overwrite=server_overwrite,
181
+ )
182
+ self._logger.info(f"gRPC export_data: サーバー応答type={type(result).__name__}, "
183
+ f"cancelled={result is False}")
184
+ # ===== 一時調査: サーバー起動以来のログを表示(削除対象) =====
185
+ if isinstance(result, dict) and result.get("_export_data_rightclick_diagnostic"):
186
+ print("\n===== Windowsサーバーログ(起動から調査停止まで)=====", flush=True)
187
+ print(result.get("server_log", ""), flush=True)
188
+ print("===== Windowsサーバーログ終了 =====\n", flush=True)
189
+ return False
190
+ # ===== 一時調査ここまで =====
191
+ if result is False:
192
+ self._logger.info("gRPC export_data結果: False(サーバーGUIでキャンセル。クライアント保存なし)")
193
+ return False
194
+ if not isinstance(result, dict):
195
+ raise TypeError("エクスポート結果が辞書ではありません")
196
+ data = result.get("data")
197
+ remote_name = result.get("filename")
198
+ if not isinstance(data, bytes) or not isinstance(remote_name, str):
199
+ raise TypeError("エクスポート結果の形式が不正です")
200
+ if filename is not None:
201
+ target = Path(filename)
202
+ else:
203
+ target = Path(PureWindowsPath(remote_name).name)
204
+ if not str(target).strip():
205
+ raise ValueError("保存ファイル名が空です")
206
+ # filename=None の場合はリモート応答後にファイル名が確定する。
207
+ if not Path(target).parent.is_dir():
208
+ raise FileNotFoundError(
209
+ f"クライアント側保存ディレクトリがありません: {Path(target).parent}"
210
+ )
211
+ if Path(target).exists() and not client_overwrite:
212
+ raise FileExistsError(
213
+ f"クライアント側保存ファイルが既に存在します: {target}"
214
+ )
215
+ mode = "wb" if client_overwrite else "xb"
216
+ with Path(target).open(mode) as stream:
217
+ stream.write(data)
218
+ self._logger.info(f"gRPC export_data保存完了: {target}")
219
+ return str(target)
220
+ except Exception as exc:
221
+ self._logger.error(f"gRPC export_data失敗: {type(exc).__name__}: {exc}")
222
+ raise
223
+
224
+
225
+ # SmartLabCtrl の遠隔クライアントを DeviceProxy に登録する。
226
+ register_device_proxy(
227
+ "SmartLabCtrl",
228
+ sync_client_cls=SmartLabGrpcClient,
229
+ default_async_mode=False,
230
+ )