1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
/*!
 * # Generic Camera Server
 * This module contains the implementation of a generic camera server that can manage multiple cameras.
 */
use rand::{thread_rng, Rng};
use std::collections::HashMap;

use crate::AnyGenCam;
#[allow(unused_imports)]
use crate::GenCam;
use crate::GenCamCtrl;
use crate::GenCamDescriptor;
use crate::GenCamError;
use crate::GenCamResult;
use crate::GenCamRoi;
use crate::GenCamState;
use crate::Property;
use crate::PropertyValue;
use refimage::GenericImage;
use serde::{Deserialize, Serialize};

/// The result of a generic camera server call.
pub type GenSrvOutput<'a> = GenCamResult<GenSrvValue<'a>>;

/// The Ok variant of a generic camera server call.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum GenSrvValue<'a> {
    /// No return value.
    Unit,
    /// Camera information in a [`GenCamDescriptor`].
    Info(GenCamDescriptor),
    /// A single [`PropertyValue`].
    Property {
        /// The value of the property.
        value: PropertyValue,
        /// The auto setting of the property, if applicable.
        auto: Option<bool>,
    },
    #[serde(borrow)]
    /// A captured image from the camera.
    Image(GenericImage<'a>),
    /// Region of interest defined on the camera.
    Roi(GenCamRoi),
    /// The current state of the camera.
    State(GenCamState),
    /// A list of properties available on the camera.
    PropertyList(HashMap<GenCamCtrl, Property>),
}

impl<'a> From<()> for GenSrvValue<'a> {
    fn from(_: ()) -> Self {
        GenSrvValue::Unit
    }
}

impl<'a> From<&GenCamDescriptor> for GenSrvValue<'a> {
    fn from(info: &GenCamDescriptor) -> Self {
        GenSrvValue::Info(info.clone())
    }
}

impl<'a> From<GenCamDescriptor> for GenSrvValue<'a> {
    fn from(info: GenCamDescriptor) -> Self {
        GenSrvValue::Info(info)
    }
}

impl<'a> From<(PropertyValue, bool)> for GenSrvValue<'a> {
    fn from(value: (PropertyValue, bool)) -> Self {
        let (value, auto) = value;
        GenSrvValue::Property {
            value,
            auto: Some(auto),
        }
    }
}

impl<'a> From<(&PropertyValue, bool)> for GenSrvValue<'a> {
    fn from(value: (&PropertyValue, bool)) -> Self {
        let (value, auto) = value;
        GenSrvValue::Property {
            value: value.clone(),
            auto: Some(auto),
        }
    }
}

impl<'a> From<PropertyValue> for GenSrvValue<'a> {
    fn from(value: PropertyValue) -> Self {
        GenSrvValue::Property { value, auto: None }
    }
}

impl<'a> From<GenericImage<'a>> for GenSrvValue<'a> {
    fn from(image: GenericImage<'a>) -> Self {
        GenSrvValue::Image(image)
    }
}

impl<'a> From<GenCamRoi> for GenSrvValue<'a> {
    fn from(roi: GenCamRoi) -> Self {
        GenSrvValue::Roi(roi)
    }
}

impl<'a> From<GenCamState> for GenSrvValue<'a> {
    fn from(state: GenCamState) -> Self {
        GenSrvValue::State(state)
    }
}

impl<'a> From<HashMap<GenCamCtrl, Property>> for GenSrvValue<'a> {
    fn from(properties: HashMap<GenCamCtrl, Property>) -> Self {
        GenSrvValue::PropertyList(properties)
    }
}

/// The possible calls that can be made to a generic camera server.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum GenSrvCmd {
    /// Get the vendor of the camera. Calls the [`GenCam::vendor`] method.
    Vendor,
    /// Check if the camera is ready. Calls the [`GenCam::camera_ready`] method.
    CameraReady,
    /// Get the name of the camera. Calls the [`GenCam::camera_name`] method.
    CameraName,
    /// Get the camera info. Calls the [`GenCam::info`] method.
    Info,
    /// List all properties available on the camera. Calls the [`GenCam::list_properties`] method.
    ListProperties,
    /// Get a specific property from the camera. Calls the [`GenCam::get_property`] method.
    GetProperty(GenCamCtrl),
    /// Set a specific property on the camera. Calls the [`GenCam::set_property`] method.
    SetProperty(GenCamCtrl, PropertyValue, bool),
    /// Cancel a capture in progress. Calls the [`GenCam::cancel_capture`] method.
    CancelCapture,
    /// Check if the camera is currently capturing. Calls the [`GenCam::is_capturing`] method.
    IsCapturing,
    /// Capture an image from the camera. Calls the [`GenCam::capture`] method.
    Capture,
    /// Start an exposure on the camera. Calls the [`GenCam::start_exposure`] method.
    StartExposure,
    /// Download an image from the camera. Calls the [`GenCam::download_image`] method.
    DownloadImage,
    /// Check if an image is ready to be downloaded. Calls the [`GenCam::image_ready`] method.
    ImageReady,
    /// Get the current state of the camera. Calls the [`GenCam::camera_state`] method.
    CameraState,
    /// Set the region of interest on the camera. Calls the [`GenCam::set_roi`] method.
    SetRoi(GenCamRoi),
    /// Get the current region of interest. Calls the [`GenCam::get_roi`] method.
    GetRoi,
}

/// A generic camera server that can manage multiple cameras.
///
/// Once a camera is added to the server, it can be accessed by its assigned ID.
///
/// # Examples
/// ```rust,ignore
/// use generic_camera::server::GenCamServer;
/// use generic_camera::GenCam;
///
/// let mut server = GenCamServer::default();
/// let id = server.add_camera(...);
/// ```
#[derive(Debug, Default)]
pub struct GenCamServer {
    cameras: HashMap<i32, AnyGenCam>,
}

impl GenCamServer {
    /// Add a camera to the server and return the camera's assigned ID.
    pub fn add_camera(&mut self, camera: AnyGenCam) -> i32 {
        let id = thread_rng().gen();
        self.cameras.insert(id, camera);
        id
    }

    /// Get a reference to a camera by its ID.
    pub fn get_camera(&self, id: i32) -> Option<&AnyGenCam> {
        self.cameras.get(&id)
    }

    /// Get a mutable reference to a camera by its ID.
    pub fn get_camera_mut(&mut self, id: i32) -> Option<&mut AnyGenCam> {
        self.cameras.get_mut(&id)
    }

    /// Remove a camera from the server by its ID.
    pub fn remove_camera(&mut self, id: i32) -> Option<AnyGenCam> {
        self.cameras.remove(&id)
    }

    /// Get the number of cameras currently connected to the server.
    pub fn num_cameras(&self) -> usize {
        self.cameras.len()
    }

    /// Execute a client call on a camera by its ID.
    pub fn execute_fn(&mut self, id: i32, sig: GenSrvCmd) -> GenCamResult<GenSrvValue> {
        let Some(camera) = self.get_camera_mut(id) else {
            return Err(GenCamError::InvalidId(id));
        };
        use GenSrvCmd::*;
        let res = match sig {
            Vendor => {
                let vendor = camera.vendor();
                PropertyValue::EnumStr(vendor.to_string()).into()
            }
            CameraReady => {
                let ready = camera.camera_ready();
                PropertyValue::Bool(ready).into()
            }
            CameraName => {
                let name = camera.camera_name();
                PropertyValue::EnumStr(name.to_string()).into()
            }
            Info => {
                let info = camera.info()?.clone();
                info.into()
            }
            ListProperties => {
                let properties = camera.list_properties();
                GenSrvValue::PropertyList(properties.clone())
            }
            GetProperty(ctrl) => camera.get_property(ctrl)?.into(),
            SetProperty(ctrl, value, auto) => camera.set_property(ctrl, &value, auto)?.into(),
            CancelCapture => camera.cancel_capture()?.into(),
            IsCapturing => PropertyValue::Bool(camera.is_capturing()).into(),
            Capture => camera.capture()?.into(),
            StartExposure => camera.start_exposure()?.into(),
            DownloadImage => camera.download_image()?.into(),
            ImageReady => PropertyValue::Bool(camera.image_ready()?).into(),
            CameraState => camera.camera_state()?.into(),
            SetRoi(roi) => (*camera.set_roi(&roi)?).into(),
            GetRoi => (*camera.get_roi()).into(),
        };
        Ok(res)
    }
}