Skip to content

server

CameraServer #

Camera web server.

Handle FastAPI server to stream camera video and SocketIO client to send detected samples to server.

Source code in cogip/tools/robotcam/server.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
class CameraServer:
    """
    Camera web server.

    Handle FastAPI server to stream camera video and SocketIO client to send detected samples to server.
    """

    _exiting: bool = False  # True if Uvicorn server was ask to shutdown
    _last_frame: SharedMemory = None  # Last generated frame to stream on web server
    _original_uvicorn_exit_handler = UvicornServer.handle_exit

    def __init__(self):
        """
        Class constructor.

        Create FastAPI application and SocketIO client.
        """
        self.settings = Settings()
        CameraServer._exiting = False

        self.app = FastAPI(title="COGIP Robot Camera Streamer", debug=False)
        self.register_endpoints()

        UvicornServer.handle_exit = self.handle_exit

        self.records_dir = Path.home() / "records"
        self.records_dir.mkdir(exist_ok=True)
        # Keep only 100 last records
        for old_record in sorted(self.records_dir.glob("*.jpg"))[:-100]:
            old_record.unlink()

        # Load camera intrinsic parameters
        self.camera_matrix: cv2.typing.MatLike | None = None
        self.dist_coefs: cv2.typing.MatLike | None = None
        if self.settings.camera_intrinsic_params:
            params_filename = self.settings.camera_intrinsic_params
        else:
            params_filename = get_camera_intrinsic_params_filename(
                self.settings.id,
                CameraName[self.settings.camera_name],
                VideoCodec[self.settings.camera_codec],
                self.settings.camera_width,
                self.settings.camera_height,
            )

        if not params_filename.exists():
            logger.warning(f"Camera intrinsic parameters file not found: {params_filename}")
        else:
            self.camera_matrix, self.dist_coefs = load_camera_intrinsic_params(params_filename)

        # Load camera extrinsic parameters
        self.extrinsic_params: CameraExtrinsicParameters | None = None
        if self.settings.camera_extrinsic_params:
            params_filename = self.settings.camera_extrinsic_params
        else:
            params_filename = get_camera_extrinsic_params_filename(
                self.settings.id,
                CameraName[self.settings.camera_name],
                VideoCodec[self.settings.camera_codec],
                self.settings.camera_width,
                self.settings.camera_height,
            )

        if not params_filename.exists():
            logger.warning(f"Camera extrinsic parameters file not found: {params_filename}")
        else:
            self.extrinsic_params = load_camera_extrinsic_params(params_filename)

        self.aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
        self.parameters = cv2.aruco.DetectorParameters()
        self.detector = cv2.aruco.ArucoDetector(self.aruco_dict, self.parameters)

    @staticmethod
    def handle_exit(*args, **kwargs):
        """Overload function for Uvicorn handle_exit"""
        CameraServer._exiting = True

        if CameraServer._last_frame:
            try:
                CameraServer._last_frame.close()
                logger.info("Camera server: Detached shared memory for last frame.")
            except FileNotFoundError:
                pass

        CameraServer._original_uvicorn_exit_handler(*args, **kwargs)

    def camera_connect(self) -> bool:
        if self._exiting:
            return True

        try:
            CameraServer._last_frame = SharedMemory(name="last_frame")
        except Exception:
            CameraServer._last_frame = None
            logger.warning("Camera server: Failed to attach to shared memory last_frame, retrying in 1s.")
            return False
        logger.info("Camera server: Attached to shared memory last_frame.")
        return True

    async def camera_streamer(self):
        """
        Frame generator.
        Yield frames produced by [camera_handler][cogip.tools.robotcam.camera.CameraHandler.camera_handler].
        """
        while not self._exiting:
            yield b"--frame\r\n"
            yield b"Content-Type: image/bmp\r\n\r\n"
            yield bytes(self._last_frame.buf)
            yield b"\r\n"

    def register_endpoints(self) -> None:
        @self.app.on_event("startup")
        async def startup_event():
            """
            Function called at FastAPI server startup.
            """
            # Poll in background to wait for camera server connection through shared memory.
            Thread(
                target=lambda: polling2.poll(
                    self.camera_connect,
                    step=1,
                    poll_forever=True,
                )
            ).start()

        @self.app.on_event("shutdown")
        async def shutdown_event():
            """
            Function called at FastAPI server shutdown.
            """
            pass

        @self.app.get("/")
        def index():
            """
            Camera stream.
            """
            stream = self.camera_streamer() if CameraServer._last_frame else ""
            return StreamingResponse(stream, media_type="multipart/x-mixed-replace;boundary=frame")

        @self.app.get("/snapshot", status_code=200)
        async def snapshot():
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            basename = f"robot{self.settings.id}-{timestamp}-snapshot"

            jpg_as_np = np.frombuffer(self._last_frame.buf, dtype=np.uint8)
            frame = cv2.imdecode(jpg_as_np, flags=1)
            record_filename = self.records_dir / f"{basename}.jpg"
            cv2.imwrite(str(record_filename), frame)

        @self.app.get("/camera_calibration", status_code=200)
        async def camera_calibration(x: float, y: float, angle: float) -> Vertex:
            jpg_as_np = np.frombuffer(self._last_frame.buf, dtype=np.uint8)
            frame = cv2.imdecode(jpg_as_np, flags=1)
            dst = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            # Detect marker corners
            marker_corners, marker_ids, _ = self.detector.detectMarkers(dst)

            # Draw detected markers
            cv2.aruco.drawDetectedMarkers(frame, marker_corners, marker_ids)

            # Record image
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            basename = f"robot{self.settings.id}-{timestamp}-calibration"
            record_filename = self.records_dir / f"{basename}.jpg"
            cv2.imwrite(str(record_filename), frame)

            if marker_ids is None:
                raise HTTPException(status_code=404, detail="No marker found")

            robot_pose = Pose(x=x, y=y, O=angle)

            # Keep table markers only
            table_markers = {
                id[0]: corners for id, corners in zip(marker_ids, marker_corners) if id[0] in [20, 21, 22, 23]
            }

            if len(table_markers) == 0:
                raise HTTPException(status_code=404, detail="No table marker found")

            # Compute camera position on table
            table_camera_tvec, table_camera_angle = get_camera_position_on_table(
                table_markers,
                self.camera_matrix,
                self.dist_coefs,
            )

            # Compute camera position in robot if robot position is given
            camera_position = get_camera_position_in_robot(
                robot_pose,
                table_camera_tvec,
                table_camera_angle,
            )

            return camera_position

        @self.app.get("/solar_panels", status_code=200)
        async def solar_panels(x: float, y: float, angle: float) -> dict[int, float]:
            jpg_as_np = np.frombuffer(self._last_frame.buf, dtype=np.uint8)
            frame = cv2.imdecode(jpg_as_np, flags=1)
            dst = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            # Detect marker corners
            marker_corners, marker_ids, rejected = self.detector.detectMarkers(dst)

            # Draw detected markers
            cv2.aruco.drawDetectedMarkers(frame, marker_corners, marker_ids)

            # Record image
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            basename = f"robot{self.settings.id}-{timestamp}-panels"
            record_filename = self.records_dir / f"{basename}.jpg"
            cv2.imwrite(str(record_filename), frame)

            if marker_ids is None:
                return {}

            robot_pose = Pose(x=x, y=y, O=angle)

            # Keep solar panel markers only
            solar_panel_markers = [corners for id, corners in zip(marker_ids, marker_corners) if id[0] == 47]

            if len(solar_panel_markers) == 0:
                return {}

            panels = get_solar_panel_positions(
                solar_panel_markers,
                self.camera_matrix,
                self.dist_coefs,
                self.extrinsic_params,
                robot_pose,
            )

            return panels

        @self.app.get("/robot_position", status_code=200)
        async def robot_position() -> Pose:
            jpg_as_np = np.frombuffer(self._last_frame.buf, dtype=np.uint8)
            frame = cv2.imdecode(jpg_as_np, flags=1)
            dst = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            # Detect marker corners
            marker_corners, marker_ids, _ = self.detector.detectMarkers(dst)

            # Draw detected markers
            cv2.aruco.drawDetectedMarkers(frame, marker_corners, marker_ids)

            # Record image
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            basename = f"robot{self.settings.id}-{timestamp}-position"
            record_filename = self.records_dir / f"{basename}.jpg"
            cv2.imwrite(str(record_filename), frame)

            if marker_ids is None:
                raise HTTPException(status_code=404, detail="No marker found")

            # Keep table markers only
            table_markers = {
                id[0]: corners for id, corners in zip(marker_ids, marker_corners) if id[0] in [20, 21, 22, 23]
            }

            if len(table_markers) == 0:
                raise HTTPException(status_code=404, detail="No table marker found")

            # Compute camera position on table
            camera_tvec, camera_angle = get_camera_position_on_table(
                table_markers,
                self.camera_matrix,
                self.dist_coefs,
            )

            # Compute robot position on table
            delta_tvec = np.array([self.extrinsic_params.x, self.extrinsic_params.y])
            camera_tvec_rotated = rotate_2d(camera_tvec[0:2], -camera_angle)
            robot_tvec_rotated = camera_tvec_rotated + delta_tvec
            robot_tvec = rotate_2d(robot_tvec_rotated, camera_angle)
            camera_angle_degrees = np.rad2deg(camera_angle)
            logger.info(
                "Robot position: "
                f"X={robot_tvec[0]:.0f} Y={robot_tvec[1]:.0f} Z={camera_tvec[2]:.0f} Angle={camera_angle_degrees:.0f}"
            )
            return Pose(x=robot_tvec[0], y=robot_tvec[1], z=camera_tvec[2], O=camera_angle_degrees)

__init__() #

Class constructor.

Create FastAPI application and SocketIO client.

Source code in cogip/tools/robotcam/server.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def __init__(self):
    """
    Class constructor.

    Create FastAPI application and SocketIO client.
    """
    self.settings = Settings()
    CameraServer._exiting = False

    self.app = FastAPI(title="COGIP Robot Camera Streamer", debug=False)
    self.register_endpoints()

    UvicornServer.handle_exit = self.handle_exit

    self.records_dir = Path.home() / "records"
    self.records_dir.mkdir(exist_ok=True)
    # Keep only 100 last records
    for old_record in sorted(self.records_dir.glob("*.jpg"))[:-100]:
        old_record.unlink()

    # Load camera intrinsic parameters
    self.camera_matrix: cv2.typing.MatLike | None = None
    self.dist_coefs: cv2.typing.MatLike | None = None
    if self.settings.camera_intrinsic_params:
        params_filename = self.settings.camera_intrinsic_params
    else:
        params_filename = get_camera_intrinsic_params_filename(
            self.settings.id,
            CameraName[self.settings.camera_name],
            VideoCodec[self.settings.camera_codec],
            self.settings.camera_width,
            self.settings.camera_height,
        )

    if not params_filename.exists():
        logger.warning(f"Camera intrinsic parameters file not found: {params_filename}")
    else:
        self.camera_matrix, self.dist_coefs = load_camera_intrinsic_params(params_filename)

    # Load camera extrinsic parameters
    self.extrinsic_params: CameraExtrinsicParameters | None = None
    if self.settings.camera_extrinsic_params:
        params_filename = self.settings.camera_extrinsic_params
    else:
        params_filename = get_camera_extrinsic_params_filename(
            self.settings.id,
            CameraName[self.settings.camera_name],
            VideoCodec[self.settings.camera_codec],
            self.settings.camera_width,
            self.settings.camera_height,
        )

    if not params_filename.exists():
        logger.warning(f"Camera extrinsic parameters file not found: {params_filename}")
    else:
        self.extrinsic_params = load_camera_extrinsic_params(params_filename)

    self.aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
    self.parameters = cv2.aruco.DetectorParameters()
    self.detector = cv2.aruco.ArucoDetector(self.aruco_dict, self.parameters)

camera_streamer() async #

Frame generator. Yield frames produced by camera_handler.

Source code in cogip/tools/robotcam/server.py
131
132
133
134
135
136
137
138
139
140
async def camera_streamer(self):
    """
    Frame generator.
    Yield frames produced by [camera_handler][cogip.tools.robotcam.camera.CameraHandler.camera_handler].
    """
    while not self._exiting:
        yield b"--frame\r\n"
        yield b"Content-Type: image/bmp\r\n\r\n"
        yield bytes(self._last_frame.buf)
        yield b"\r\n"

handle_exit(*args, **kwargs) staticmethod #

Overload function for Uvicorn handle_exit

Source code in cogip/tools/robotcam/server.py
104
105
106
107
108
109
110
111
112
113
114
115
116
@staticmethod
def handle_exit(*args, **kwargs):
    """Overload function for Uvicorn handle_exit"""
    CameraServer._exiting = True

    if CameraServer._last_frame:
        try:
            CameraServer._last_frame.close()
            logger.info("Camera server: Detached shared memory for last frame.")
        except FileNotFoundError:
            pass

    CameraServer._original_uvicorn_exit_handler(*args, **kwargs)