summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: ce1c19e563ffdd4be0cd0393615e54721e189c28 (plain)
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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// use crate::ASICamera2::BayerPattern;
//
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![feature(alloc_layout_extra)]
mod asicam;
mod qhyccd;

#[macro_use]
extern crate crossbeam_channel;

use crossbeam_channel::{Sender, Receiver};
use crossbeam_channel::unbounded;

use std::time::Duration;
use std::time::Instant;

use crate::asicam::ASICamera2::{ControlType, ImageType};
use crate::asicam::Camera;

use crate::qhyccd::QHYResponse;
use crate::qhyccd::QHYMessage;

use std::path::Path;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;

use png::HasParameters;

fn record_image(data: &[u8], dimensions: Dimensions, target: &'static str, image_id: u32, properties: &Properties) {
    let props_path = format!("{}_{}.json", target, image_id);
    let props_dest = Path::new(&props_path);
    let mut props_file = File::create(props_dest).unwrap();
    // TODO: serde_json::serialize
    props_file.write(properties.stringy().as_bytes()).unwrap();
    let path_string = format!("{}_{}.png", target, image_id);
    println!("writing {}..", path_string);
    let dest = Path::new(&path_string);
    let file = File::create(dest).unwrap();
    let ref mut w = BufWriter::new(file);
    let mut encoder = png::Encoder::new(w, dimensions.width, dimensions.height);
    let color_type = if dimensions.channels == 3 {
        png::ColorType::RGB
    } else if dimensions.channels == 1 {
        png::ColorType::Grayscale
    } else { panic!("Unsupported channel count: {}", dimensions.channels); };

    let bitness = if dimensions.bpp == 8 {
        png::BitDepth::Eight
    } else if dimensions.bpp == 16 {
        png::BitDepth::Sixteen
    } else {
        panic!("Unknwon bitness: {}", dimensions.bpp);
    };
    encoder.set(color_type).set(bitness);
    let mut writer = encoder.write_header().unwrap();
    writer.write_image_data(data).unwrap();
    println!("image written!");
    println!(".. writing raw");
    let raw_path = format!("{}_{}.raw", target, image_id);
    let raw_dest = Path::new(&raw_path);
//    let mut file = File::create(raw_dest).unwrap();
//    file.write(data);
}

fn main() {
    let test = true;
    println!("Doing qhy...");
    let (image_writer, image_reader) = unbounded();
    let (frame_sender, free_frames) = unbounded();

    std::thread::spawn(move || {
        loop {
            select! {
                recv(image_reader) -> msg => {
                    match msg {
                        Ok(ImageInfo { mut data, dimensions, target, image_id, properties }) => {
                            match dimensions.channels {
                                1 => {
                                    qhyccd::fix_endianness(data.as_mut_slice());
                                },
                                3 => {
                                    qhyccd::fix_channels_and_endianness(data.as_mut_slice());
                                }
                                c => { panic!("unsupported channel count: {}", c); }
                            }
                            record_image(data.as_slice(), dimensions, target, image_id, &properties);
                            println!("pretend i wrote image {}_{}", target, image_id);
                            frame_sender.send(data).unwrap();
                        }
                        Err(RecvError) => {
                            // something in the application has crashed. time 2 die
                            return;
                        }
                    }
                }
            }
        }
    });

    operate_qhy("settings", None, free_frames, image_writer);
//    println!("Doing asi...");
//    operate_asi(test);
}

#[derive(Debug, Copy, Clone)]
struct Dimensions {
    width: u32,
    height: u32,
    bpp: u8,
    channels: u8,
}

impl Dimensions {
    pub fn new(width: u32, height: u32, bpp: u8, channels: u8) -> Self {
        Dimensions { width, height, bpp, channels }
    }
}

#[derive(Debug)]
struct Properties {
    pub device: &'static str,
    pub exposure_ms: u32,
    pub gain: u16,
    pub offset: u16,
    pub gamma: u16,
    pub temp: u16, // in hundredths of degrees, C. eg, 100 => 1deg C,
}

impl Properties {
    pub fn stringy(&self) -> String {
        format!("{{\n  \"device\": \"{}\",\n  \"exposure_ms\": {},\n  \"gain\": {},\n  \"offset\": {},\n  \"gamma\": {},\n  \"temp\": {}\n}}",
            self.device,
            self.exposure_ms,
            self.gain,
            self.offset,
            self.gamma,
            self.temp
        )
    }
}

struct ImageInfo {
    data: Vec<u8>,
    dimensions: Dimensions,
    properties: Properties,
    target: &'static str,
    image_id: u32
}

enum ImageWriter {
    FrameReady(Vec<u8>, Dimensions, &'static str, u32)
}

fn operate_qhy(target: &'static str, count: Option<u32>, free_frames: Receiver<Vec<u8>>, image_writer: Sender<ImageInfo>) {
    use crate::qhyccd::Control;
    println!("Operating on qhy camera ... or i'll die trying");
    let (mut camera_rx, mut camera_tx) = qhyccd::connect(0).unwrap();

    let mut image_id = 0u32;
    let mut settings_copy = qhyccd::Settings::default();

    // qhy376c settings
    camera_tx.send(QHYMessage::SetControl(Control::Exposure, 20000.0 * 1000.0)).unwrap();
//    camera_tx.send(QHYMessage::SetControl(Control::Exposure, 200.0 * 1000.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Cooler, 0.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Color, 1.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Gain, 4000.0)).unwrap();

    /*
    camera_tx.send(QHYMessage::SetControl(Control::Exposure, 60000.0 * 1000.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Cooler, 0.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Color, 0.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Gain, 110.0)).unwrap();
    */

    /*
    camera_tx.send(QHYMessage::SetControl(Control::Exposure, 20000.0 * 1000.0)).unwrap();
//    camera_tx.send(QHYMessage::SetControl(Control::Offset, 00.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Gamma, 1.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Brightness, 00.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Contrast, 00.0)).unwrap();
//    camera_tx.send(QHYMessage::SetControl(Control::Gamma, 2.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Cooler, 0.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::USBTraffic, 60.0)).unwrap();
    camera_tx.send(QHYMessage::SetControl(Control::Color, 0.0)).unwrap(); // disable color
    camera_tx.send(QHYMessage::SetControl(Control::Gain, 4000.0)).unwrap();
//    camera_tx.send(QHYMessage::SetControl(Control::Gain, 140.0)).unwrap();
//    camera_tx.send(QHYMessage::SetControl(Control::Gain, 4000.0)).unwrap();
//    camera.set_roi(0, 0, 1920 * 2, 1080 * 2).unwrap();
    */
//    println!("Gain: {:?}", camera.get_param_limits(Control::ManulPwm));
//    println!("cur pwm ???: {}", camera.get_param(Control::CurPWM));


    camera_tx.send(QHYMessage::BeginCapture(None)).unwrap();
    let LAPSE_PERIOD = Duration::from_millis(0);

    let mut capture_start = Instant::now().checked_sub(Duration::from_millis(10)).unwrap().checked_sub(LAPSE_PERIOD).unwrap();;
    loop {
        /*
        if capture_start.elapsed() > LAPSE_PERIOD {
            println!("Lapsing!!");
            camera_tx.send(QHYMessage::BeginCapture(Some(1))).unwrap();
            capture_start = Instant::now();
        }
        */
        select! {
            recv(free_frames) -> msg => {
                match msg {
                    Ok(buffer) => {
                        camera_tx.send(QHYMessage::FrameAvailable(buffer)).unwrap();
                    },
                    Err(RecvError) => {
                        // disconnected. nothing we can do but to..
                        return;
                    }
                }
            },
            recv(camera_rx) -> msg => {
                match msg {
                    Ok(QHYResponse::CurrentControlValue(control, value)) => {
                        println!("Control {:?} value: {}", control, value);
                    }
                    Ok(QHYResponse::InitializationError) => {
                        println!("Failed to initialize camera, exiting...");
                        return;
                    }
                    Ok(QHYResponse::Shutdown) => {
                        return;
                    }
                    Ok(QHYResponse::UpdatedSettings(settings)) => {
                        settings_copy = settings;
                    }
                    Ok(QHYResponse::Data(data, dimensions, properties)) => {
                        image_writer.send(ImageInfo { data, dimensions, target, image_id: image_id, properties}).unwrap();
                        // images.log(target, image_id, settings_copy);
                        image_id += 1;
                        if Some(image_id) == count {
                            camera_tx.send(QHYMessage::Shutdown);
                        }
                    }
                    Ok(QHYResponse::DroppedFrame) => {
                        println!("Dropped frame...");
                    }
                    Err(RecvError) => {
                        // camera is closed. hopefully it just shut down? but maybe crashed!!
                        return;
                    }
                }
            }
            default(Duration::from_millis(2000)) => {
                camera_tx.send(
                    QHYMessage::QueryControl(Control::CurTemp)
                );
            }
        }
    }
    /*
    let t = std::thread::spawn(move || {
        let mut camera = qhyccd::acquire(0).unwrap();
        camera.set_defaults().unwrap();
        camera.set_exposure_ms(400).unwrap();
    //    camera.set_param(Control::Exposure, 10.0).unwrap();
        camera.set_param(Control::Gain, 4000.0); //.unwrap();
        camera.set_param(Control::Offset, 00.0).unwrap();
    //    camera.set_param(Control::USBTraffic, 50.0).unwrap();
    //    camera.set_param(Control::ManulPwm, 0.0).unwrap();
    //    camera.set_target_temp(0.0).unwrap();
        camera.set_param(Control::Cooler, -25.0).unwrap();
    //    camera.set_roi(0, 0, 1920 * 2, 1080 * 2).unwrap();
        println!("Gain: {:?}", camera.get_param_limits(Control::ManulPwm));
        println!("cur pwm ???: {}", camera.get_param(Control::CurPWM));
        println!("current temp: {}", camera.get_param(Control::CurTemp));
    //    camera.set_param(Control::CONTROL_WBR, 2750.0).unwrap();
    //    camera.set_param(Control::CONTROL_WBG, 2500.0).unwrap();
    //    camera.set_param(Control::CONTROL_WBB, 3000.0).unwrap();
    //    camera.set_bin_mode(2).unwrap();
        if !test {
            let object = "veil";
            for i in 0..10 {
               camera.take_image(&format!("{}_{}.png", object, i));//, i));
            }
        } else {
                camera.take_image("qhy_test_2.png").unwrap();
        println!("exposing: {:x}", camera.get_param(Control::IS_EXPOSING_DONE) as u64);
        }
        camera.release().unwrap();
    });
    t.join();
    */
}

fn operate_asi(test: bool) {
    println!("Operating on asi camera ... or i'll die trying");
    let mut camera = asicam::acquire(0).unwrap();

    println!("{:?}", camera);
    camera.set_control_value(ControlType::CoolerOn, 1).unwrap();
    camera.set_control_value(ControlType::TargetTemp, -200).unwrap();
    std::thread::sleep(std::time::Duration::from_millis(500));
    println!("Camera temperature is currently {:?}", camera.get_control_value(ControlType::Temperature).unwrap());

    /*
    for exposure in [2000, 5000, 10000, 30000].iter() {
        camera.set_control_value(ControlType::Exposure, *exposure).unwrap();
        for gain in [450, 375, 325, 250, 200].iter() {
            camera.set_control_value(ControlType::Gain, *gain).unwrap();
            for offset in [100, 80, 60, 40, 20, 0].iter() {
                camera.set_control_value(ControlType::Offset, *offset).unwrap();
                take_calibration_images(&camera, 1, &format!("roof_gain_{:03}_offset_{:03}_exposure_{:06}", gain, offset, exposure));
            }
        }
    }
    */
    camera.set_exposure_ms(30000).unwrap();
//    camera.set_control_value(ControlType::Exposure, 70000000).unwrap();
    camera.set_control_value(ControlType::Gain, 250).unwrap();
    camera.set_control_value(ControlType::Offset, 0).unwrap();
    camera.set_control_value(ControlType::HardwareBin, 1).unwrap();
    camera.set_roi_format(camera.width, camera.height, 1, ImageType::RAW16).unwrap();
    for i in 0..240 {
        println!("doing image {}", i);
        println!("Camera temperature is currently {:?}", camera.get_control_value(ControlType::Temperature).unwrap());
        camera.take_image(&format!("ngc7380_{}.png", i)).unwrap();
    }
//    take_calibration_images(&camera, 40, "dark_gain_350_exposure_45000");
    /*
    for exposure in [1000 * 1000 * 10].iter() {
        camera.set_control_value(ControlType::Exposure, *exposure).unwrap();
        for gain in [450, 375, 325, 250, 200].iter() {
            camera.set_control_value(ControlType::Gain, *gain).unwrap();
            for offset in [100, 80, 70, 60, 40, 0].iter() {
                camera.set_control_value(ControlType::Offset, *offset).unwrap();
                take_calibration_images(
                    &camera,
                    30,
                    &format!("images/gain_{:03}_offset_{:03}_exposure_{:06}", gain, offset, exposure));
            }
        }
    }
    */

    println!("Done!");
}

fn take_calibration_images(camera: &Camera, count: u32, path_fragment: &str) {
    for i in 0..count {
        println!("{} image {:06}", path_fragment,  i);
        let temp = camera.get_control_value(ControlType::Temperature).unwrap();
        println!("Camera temperature is currently {:?}", temp);
        camera.take_image(&format!("{}_{:06}_temp_{:03}.png", path_fragment, i, temp)).unwrap();
    }
}