/
uca-phantom-camera.c
4142 lines (3539 loc) · 154 KB
/
uca-phantom-camera.c
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2018 Matthias Vogelgesang <matthias.vogelgesang@kit.edu>
(Karlsruhe Institute of Technology)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along
with this library; if not, write to the Free Software Foundation, Inc., 51
Franklin St, Fifth Floor, Boston, MA 02110, USA */
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
//#include <math.h>
#include <gio/gio.h>
#include <gmodule.h>
#include <string.h>
#include <unistd.h>
#include <nmmintrin.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
//#include <netinet/if_ether.h>
#include <poll.h>
#include <net/if.h> // This is making trouble
#include <linux/ip.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <netdb.h>
#include <uca/uca-camera.h>
#include "uca-phantom-camera.h"
// SSE(128) instructions AVX(256); library intrisincs
// UCA UFO SSE
// TODO:
//// NOTE: JUST ACCESS THE trigger-source directly over g_object_get (important)
//// Post trigger frames setzen setzt auch gleichzeitig memread count
// TRIGGER FLANKE EVTL EINSTELLEN (low)
//// PROPERTY DIE MAX COUNT AUSLIEST
// ERRORS FOR MAX ROI SIZE ALSO BOUNDRIES WITH ROI OFSETS (medium)
//// BEVORE MEMREAD REQUEST SEND CHECK IF AMOUNT OF READ FRAMES UP TO THIS POIMNT IS ENOUGH FOR CHUNK SIZE
// SENSOR PIXEL HEIGHT AUCH VON DER CAMERA AUSLESEN (low)
// PUBLIC GITHUB ZIEHEN (medium)
// DOCUMENTATION SCHREIBEN (medium)
// KEINE ROOT RECHTE FUER PACKET_MAP brauchen? CAP_NET_RAW permission setting for user
// CAP_NET_RAW, CAP_IPC_LOCK
// **************************************
// HARDCODING CONFIGURATION OF THE CAMERA
// **************************************
#define PROTOCOL ETH_P_ALL
//#define PROTOCOL 0x88b7
// 26.06.2019
// Changed the Chunk size from 400 to 100, because after testing with the 2048 pixel width image settings. 400 images
// cause the ring buffer to overflow.
#define MEMREAD_CHUNK_SIZE 100
// 04.11.2019
// This macro will define the index which will be used as the start index for the very first packet request of the
// memread requests
#define INTERNAL_START_INDEX 0
#define UCA_PHANTOM_CAMERA_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), UCA_TYPE_PHANTOM_CAMERA, UcaPhantomCameraPrivate))
#define CHECK_ETHERNET_HEADER 0
static void uca_phantom_camera_initable_iface_init (GInitableIface *iface);
G_DEFINE_TYPE_WITH_CODE (UcaPhantomCamera, uca_phantom_camera, UCA_TYPE_CAMERA,
G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
uca_phantom_camera_initable_iface_init))
GQuark uca_phantom_camera_error_quark ()
{
return g_quark_from_static_string("uca-net-camera-error-quark");
}
// *************************************
// STRUCTS FOR THE RAW SOCKET CONNECTION
// *************************************
uint8_t zero[4] = {0,0,0,0};
uint8_t *zero_pointer = (uint8_t *) zero;
struct block_desc {
uint32_t version;
uint32_t offset_to_priv;
struct tpacket_hdr_v1 h1;
};
struct ring {
struct iovec *rd;
uint8_t *map;
struct tpacket_req3 req;
};
typedef union {
uint8_t *in;
uint64_t *out;
} xbuffer;
// ***************************
// STRUCT AND ENUM DEFINITIONS
// ***************************
enum {
/* 4.2. info structure */
PROP_SENSOR_TYPE = N_BASE_PROPERTIES,
/* 4.2.1 sensor information */
PROP_SENSOR_VERSION,
/* 4.2.2 version and identification */
PROP_HARDWARE_VERSION,
PROP_KERNEL_VERSION,
PROP_FIRMWARE_VERSION,
PROP_FPGA_VERSION,
PROP_MODEL,
PROP_PROTOCOL_VERSION,
PROP_SYSTEM_RELEASE_VERSION,
PROP_FIRMWARE_RELEASE_VERSION,
PROP_SERIAL_NUMBER,
/* 4.2.3 capabilities */
PROP_FEATURES,
PROP_IMAGE_FORMATS,
PROP_MAX_NUM_CINES,
/* 4.2.6 status */
PROP_SENSOR_TEMPERATURE,
PROP_CAMERA_TEMPERATURE,
/* 4.4 cam structure */
PROP_FRAME_SYNCHRONIZATION,
PROP_FRAME_DELAY,
PROP_NUM_CINES,
/* 4.6 defc */
PROP_POST_TRIGGER_FRAMES,
/* 4.7.1 cine status */
PROP_CINE_STATE,
/* our own */
PROP_ACQUISITION_MODE,
PROP_IMAGE_FORMAT,
PROP_ENABLE_10GE,
PROP_NETWORK_INTERFACE,
// 26.05.2019
// Adding this additional property for the IP address string. This can be used to manually assign the IP address
// in case the discovery protocol does not work
PROP_NETWORK_ADDRESS,
// 11.06.2019
// Instead of using the "start_recording" function to connect to the camera (this would break existing programs
// using libuca with other cameras), The camera is now connected by setting a boolean flag to True
PROP_CONNECT,
// This will be a boolean value, that returns, whether or not the triggered frame acquisition is done yet or not
PROP_TRIGGER_RELEASED,
// 07.05.2019
// Introducing an additional mode of operation for the camera: "memread" mode.
// In this mode the camera is not actively recording. Instead the memory of the camera is being
// read. The amount of frames to be read can be specified and each consecutive call to the
// "grab" function of the camera after entering this call will be used to read one of these images.
PROP_ENABLE_MEMREAD,
PROP_MEMREAD_CINE,
PROP_MEMREAD_START,
PROP_MEMREAD_COUNT,
// 30.06.2019
// This property will be used to set the "cam.aux1mode" attribute of the camera. This is an integer property, where
// the integer value set configures what functionality the first auxiliary port of the camera will have
PROP_AUX_ONE_MODE,
// 16.07.2019
// This property will contain the boolean flag, which will indicate if a external trigger will be used for the
// recording. If not strictly software triggers enabled
PROP_EXTERNAL_TRIGGER,
// 22.07.2019
// This property is a boolean flag, which will be used to enable and disable memgate mode. This is one of the
// special programmable functions of the first auxiliary port. When it is enabled no frames are being
// saved to memory if the port 1 of the camera is put to HIGH
PROP_ENABLE_MEMGATE,
PROP_HARDWARE_MEMGATE_ENABLED,
PROP_AUX_ONE_PARAMETERS,
// 05.11.2019
// PROP_FRAME_SIZE will be used to store the value of "c1.frsize", which is the size of a single frame within the
// first cine partition. PROP_MEMORY_SIZE will hold the value of "c1.frspace", which is the total space within the
// cine. PROP_MAX_FRAMES will be a computed property from the two previous ones and it will tell, what the maxmimum
// amount of frames is to be put into the cine.
PROP_FRAME_SIZE,
PROP_MEMORY_SIZE,
PROP_MAX_FRAMES,
N_PROPERTIES
};
static gint base_overrideables[] = {
PROP_NAME, /* info.name */
PROP_SENSOR_WIDTH,
PROP_SENSOR_HEIGHT,
PROP_SENSOR_BITDEPTH,
PROP_ROI_X,
PROP_ROI_Y,
PROP_ROI_WIDTH,
PROP_ROI_HEIGHT,
PROP_ROI_WIDTH_MULTIPLIER, /* info.xinc */
PROP_ROI_HEIGHT_MULTIPLIER, /* info.yinc */
PROP_EXPOSURE_TIME, /* defc.exp */
PROP_TRIGGER_SOURCE,
PROP_FRAMES_PER_SECOND, /* defc.rate */
PROP_RECORDED_FRAMES,
PROP_HAS_STREAMING,
PROP_HAS_CAMRAM_RECORDING,
0
};
static GParamSpec *phantom_properties[N_PROPERTIES] = { NULL, };
typedef enum {
SYNC_MODE_FREE_RUN = 0,
SYNC_MODE_FSYNC,
SYNC_MODE_IRIG,
SYNC_MODE_VIDEO_FRAME_RATE,
} SyncMode;
// 27.03.2019
// Added the two formats "IMAGE_FORMAT_P10" and "IMAGE_FORMAT_P8"
typedef enum {
IMAGE_FORMAT_P16,
IMAGE_FORMAT_P12L,
IMAGE_FORMAT_P10,
IMAGE_FORMAT_P8
} ImageFormat;
typedef enum {
ACQUISITION_MODE_STANDARD = 0,
ACQUISITION_MODE_STANDARD_BINNED = 2,
ACQUISITION_MODE_HS = 5,
ACQUISITION_MODE_HS_BINNED = 7,
} AcquisitionMode;
static GEnumValue sync_mode_values[] = {
{ SYNC_MODE_FREE_RUN, "SYNC_MODE_FREE_RUN", "sync_mode_free_run" },
{ SYNC_MODE_FSYNC, "SYNC_MODE_FSYNC", "sync_mode_fsync" },
{ SYNC_MODE_IRIG, "SYNC_MODE_IRIG", "sync_mode_irig" },
{ SYNC_MODE_VIDEO_FRAME_RATE, "SYNC_MODE_VIDEO_FRAME_RATE", "sync_mode_video_frame_rate" },
{ 0, NULL, NULL }
};
// 27.03.2019
// Added the two formats "IMAGE_FORMAT_P10" and "IMAGE_FORMAT_P8"
static GEnumValue image_format_values[] = {
{ IMAGE_FORMAT_P16, "IMAGE_FORMAT_P16", "image_format_p16" },
{ IMAGE_FORMAT_P12L, "IMAGE_FORMAT_P12L", "image_format_p12l" },
{ IMAGE_FORMAT_P10, "IMAGE_FORMAT_P10", "image_format_p10"},
{ IMAGE_FORMAT_P8, "IMAGE_FORMAT_P8", "image_format_p8"},
{ 0, NULL, NULL }
};
static GEnumValue acquisition_mode_values[] = {
{ ACQUISITION_MODE_STANDARD, "ACQUISITION_MODE_STANDARD", "acquisition_mode_standard" },
{ ACQUISITION_MODE_STANDARD_BINNED, "ACQUISITION_MODE_STANDARD_BINNED", "acquisition_mode_standard_binned" },
{ ACQUISITION_MODE_HS, "ACQUISITION_MODE_HS", "acquisition_mode_hs" },
{ ACQUISITION_MODE_HS_BINNED, "ACQUISITION_MODE_HS_BINNED", "acquisition_mode_hs_binned" },
{ 0, NULL, NULL }
};
// 06.04.2019
// Added the additional attribute 10g_buffer, which will be used to store the unpacked data (with the transfer format
// already decoded into the pixel values)
struct _UcaPhantomCameraPrivate {
GError *construct_error;
gchar *host;
GSocketClient *client;
GSocketConnection *connection;
GSocketListener *listener;
GCancellable *accept;
GThread *accept_thread;
GThread *unpack_thread;
GAsyncQueue *message_queue;
GAsyncQueue *result_queue;
GRegex *response_pattern;
GRegex *res_pattern;
guint roi_width;
guint roi_height;
guint8 *buffer;
gchar *features;
gboolean have_ximg;
gboolean enable_10ge;
gchar *iface;
gchar *ip_address;
guint8 mac_address[6];
ImageFormat format;
AcquisitionMode acquisition_mode;
UcaCameraTriggerSource uca_trigger_source;
// 11.06.2019
// The boolean flag indicating if the plugin is actaully connected (via socket on the ethernet interface) to the
// camera
gboolean connected;
struct block_desc *xg_current_block;
gsize xg_total;
gsize xg_expected;
gboolean xg_block_finished;
gboolean xg_packet_skipped;
gint xg_block_index;
gint xg_packet_index;
gint xg_data_index;
struct tpacket3_hdr *xg_packet_header;
xbuffer xg_data_buffer;
uint8_t *xg_data_in;
uint16_t *xg_buffer;
gint xg_buffer_index;
guint8 *xg_packet_data;
guint8 xg_remaining_data[40];
gsize xg_packet_length;
gsize xg_remaining_length;
// 29.05.2019
// We need to keep track of the amount of packages inside a block of the ring buffer as an attribute of the camera
// object, because it is used in several different methods.
gsize xg_packet_amount;
gint xg_unpack_length;
gint xg_unpack_index;
// 10.05.2019
// These are the attributes needed for the "memread" mode.
// This mode can be entered by setting a boolean flag on the camera object. In this mode an amount of frames to
// be read can be specified and after the first "grab" call, the camera will send a continuous stream of images
// (faster image transfer mode, for reading images already stored in the cameras memory)
gboolean enable_memread;
gboolean memread_request_sent;
guint memread_count;
guint memread_cine; // not implemented yet
guint memread_start; // not implemented yet
// 29.05.2019
guint memread_remaining;
guint memread_index;
// 11.06.2019
// This is the index, that is being incremented by the unpacking thread, when the program is in memread mode.
// The theory is to delay the sending of the next chunk request until the last image has been unpacked.
// To hopefully not overflow the ring buffer
guint memread_unpack_index;
// 30.06.2019
// The aux1mode is a property of the camera, which defines the function of the first configurable auxiliary port
// of the camera.
guint aux1mode;
// 16.07.2019
// This flag will indicate, whether an external trigger source is to be used. If an external trigger source is to
// be used the "rec" command, which has to be sent in preparation of a trigger, will be sent during the
// "start_recording" process.. Otherwise the "rec" command will be sent together with the software trigger command
gboolean triggered_externally;
};
typedef struct {
const gchar *name;
GType type;
GParamFlags flags;
gint property_id;
gboolean handle_automatically;
} UnitVariable;
// 05.11.2019
// Set the "defc.ptframes" to NOT be handled automatically, as the memread count has to be set as well in a manual
// implementation of the setter handling.
// The last item in the list is the boolean flag to indicate, whether the property should be handled automatically.
// for automatically handled properties there does not have to be new case defined/ does not have to be manually
// implemented. The handling is automtically done by sending the according requests to the camera.
static UnitVariable variables[] = {
{ "info.sensor", G_TYPE_UINT, G_PARAM_READABLE, PROP_SENSOR_TYPE, TRUE },
{ "info.snsversion", G_TYPE_UINT, G_PARAM_READABLE, PROP_SENSOR_VERSION, TRUE },
{ "info.hwver", G_TYPE_UINT, G_PARAM_READABLE, PROP_HARDWARE_VERSION, TRUE },
{ "info.kernel", G_TYPE_UINT, G_PARAM_READABLE, PROP_KERNEL_VERSION, TRUE },
{ "info.swver", G_TYPE_UINT, G_PARAM_READABLE, PROP_FIRMWARE_VERSION, TRUE },
{ "info.xver", G_TYPE_UINT, G_PARAM_READABLE, PROP_FPGA_VERSION, TRUE },
{ "info.model", G_TYPE_STRING, G_PARAM_READABLE, PROP_MODEL, TRUE },
{ "info.pver", G_TYPE_UINT, G_PARAM_READABLE, PROP_PROTOCOL_VERSION, TRUE },
{ "info.sver", G_TYPE_UINT, G_PARAM_READABLE, PROP_SYSTEM_RELEASE_VERSION, TRUE },
{ "info.fver", G_TYPE_UINT, G_PARAM_READABLE, PROP_FIRMWARE_RELEASE_VERSION, TRUE },
{ "info.serial", G_TYPE_UINT, G_PARAM_READABLE, PROP_SERIAL_NUMBER, TRUE },
{ "info.xmax", G_TYPE_UINT, G_PARAM_READABLE, PROP_SENSOR_WIDTH, TRUE },
{ "info.ymax", G_TYPE_UINT, G_PARAM_READABLE, PROP_SENSOR_HEIGHT, TRUE },
{ "info.name", G_TYPE_STRING, G_PARAM_READABLE, PROP_NAME, TRUE },
{ "info.imgformats", G_TYPE_STRING, G_PARAM_READABLE, PROP_IMAGE_FORMATS, TRUE },
{ "info.maxcines", G_TYPE_UINT, G_PARAM_READABLE, PROP_MAX_NUM_CINES, TRUE },
{ "info.xinc", G_TYPE_UINT, G_PARAM_READABLE, PROP_ROI_WIDTH_MULTIPLIER, TRUE },
{ "info.yinc", G_TYPE_UINT, G_PARAM_READABLE, PROP_ROI_HEIGHT_MULTIPLIER, TRUE },
{ "info.snstemp", G_TYPE_UINT, G_PARAM_READABLE, PROP_SENSOR_TEMPERATURE, TRUE },
{ "info.camtemp", G_TYPE_UINT, G_PARAM_READABLE, PROP_CAMERA_TEMPERATURE, TRUE },
{ "cam.syncimg", G_TYPE_ENUM, G_PARAM_READWRITE, PROP_FRAME_SYNCHRONIZATION, TRUE },
{ "cam.frdelay", G_TYPE_UINT, G_PARAM_READWRITE, PROP_FRAME_DELAY, FALSE },
{ "cam.cines", G_TYPE_UINT, G_PARAM_READWRITE, PROP_NUM_CINES, FALSE },
{ "defc.rate", G_TYPE_FLOAT, G_PARAM_READWRITE, PROP_FRAMES_PER_SECOND, TRUE },
{ "defc.exp", G_TYPE_UINT, G_PARAM_READWRITE, PROP_EXPOSURE_TIME, FALSE },
{ "defc.ptframes", G_TYPE_UINT, G_PARAM_READWRITE, PROP_POST_TRIGGER_FRAMES, FALSE },
{ "c1.frcount", G_TYPE_UINT, G_PARAM_READABLE, PROP_RECORDED_FRAMES, TRUE },
{ "c1.state", G_TYPE_STRING, G_PARAM_READABLE, PROP_CINE_STATE, TRUE },
{ "cam.aux1mode", G_TYPE_UINT, G_PARAM_READWRITE, PROP_AUX_ONE_MODE, TRUE },
{ "hw.memgateen", G_TYPE_UINT, G_PARAM_READWRITE, PROP_HARDWARE_MEMGATE_ENABLED, TRUE },
{ "cam.aux1pp", G_TYPE_STRING, G_PARAM_READWRITE, PROP_AUX_ONE_PARAMETERS, TRUE },
// 05.11.2019
{ "c1.frsize", G_TYPE_UINT, G_PARAM_READABLE, PROP_FRAME_SIZE, TRUE },
{ "c1.frspace", G_TYPE_UINT, G_PARAM_READABLE, PROP_FRAME_SPACE, TRUE },
{ NULL, }
};
typedef struct {
enum {
MESSAGE_READ_IMAGE = 1,
MESSAGE_UNPACK_IMAGE = 2,
MESSAGE_READ_TIMESTAMP,
MESSAGE_STOP,
} type;
gpointer data;
} InternalMessage;
typedef struct {
enum {
RESULT_READY = 1,
RESULT_IMAGE,
} type;
gboolean success;
GError *error;
} Result;
#define DEFINE_CAST(suffix, trans_func) \
static void \
value_transform_##suffix (const GValue *src_value, \
GValue *dest_value) \
{ \
const gchar* src = g_value_get_string (src_value); \
g_value_set_##suffix (dest_value, trans_func (src)); \
}
static gboolean
str_to_boolean (const gchar *s)
{
return g_ascii_strncasecmp (s, "true", 4) == 0;
}
DEFINE_CAST (uchar, atoi)
DEFINE_CAST (int, atoi)
DEFINE_CAST (long, atol)
DEFINE_CAST (uint, atoi)
DEFINE_CAST (uint64, atoi)
DEFINE_CAST (ulong, atol)
DEFINE_CAST (float, atof)
DEFINE_CAST (double, atof)
DEFINE_CAST (enum, atoi) /* not super type safe */
DEFINE_CAST (boolean, str_to_boolean)
// ***************************************
// BASIC NETWORK INTERACTIONS WITH PHANTOM
// ***************************************
static UnitVariable *
phantom_lookup_by_id (gint property_id)
{
for (guint i = 0; variables[i].name != NULL; i++) {
if (variables[i].property_id == property_id)
return &variables[i];
}
return NULL;
}
/**
* @brief Sends the given request to the phantom and returns the response
*
* This function sends the given request string @p request to the phantom camera using the socket streams and then
* received the response and returns it.
*
* @author Matthias Vogelgesang
*
* @param priv
* @param request
* @param reply_loc
* @param reply_loc_size
* @param error_loc
* @return
*/
static gchar *
phantom_talk (UcaPhantomCameraPrivate *priv,
const gchar *request,
gchar *reply_loc,
gsize reply_loc_size,
GError **error_loc)
{
GOutputStream *ostream;
GInputStream *istream;
gsize size;
gsize reply_size;
GError *error = NULL;
gchar *reply = NULL;
ostream = g_io_stream_get_output_stream ((GIOStream *) priv->connection);
istream = g_io_stream_get_input_stream ((GIOStream *) priv->connection);
// Here we are actually pushing the request string to the output stream, which will send over the nertwork to
// the phantom. The output of the write all function is a boolean indicator, of whether it worked or not.
gboolean output_write_success;
output_write_success = g_output_stream_write_all (ostream, request, strlen (request), &size, NULL, &error);
g_warning("C REQUEST: %s", request);
// In case the write did not work, we will inform the user first and then return NULL, terminating this function.
if (!output_write_success) {
if (error_loc == NULL) {
g_warning ("Could not write request: %s\n", error->message);
g_error_free (error);
}
else {
if (error != NULL)
g_propagate_error (error_loc, error);
}
return NULL;
}
// So this seems like, we are either using the reply size/string, that has been passed to the this function already
// and essentially append to it. But in case no already existing reply string has been passed we are creating a new
// buffer where the reply will later be saved into
reply_size = reply_loc ? reply_loc_size : 512;
reply = reply_loc ? reply_loc : g_malloc0 (reply_size);
// Here we are actually reading from the input stream/receiving the response from the camera. The actual characters
// string will be saved into the "reply" buffer (passed as pointer argument). The return value of the function is a
// boolean value indicating of whether there was an issue or not.
gboolean input_read_success;
input_read_success = g_input_stream_read (istream, reply, reply_size, NULL, &error);
if (!input_read_success) {
if (error_loc == NULL) {
g_warning ("Could not read reply: %s\n", error->message);
g_error_free (error);
}
else {
if (error != NULL)
g_propagate_error (error_loc, error);
}
g_free (reply);
return NULL;
}
// Of course, things cant only go wrong on this end. A malformed request or other things may cause an error inside
// The phantom. The phantom will tell us so, by sending an error message, always (!) starting with "ERR:".
// So here we are detecting, if the response is an error message and if so, the uses is notified.
gboolean is_phantom_error;
is_phantom_error = g_str_has_prefix (reply, "ERR: ");
if (is_phantom_error) {
if (error_loc != NULL) {
g_set_error (error_loc, UCA_CAMERA_ERROR, UCA_CAMERA_ERROR_DEVICE,
"Phantom error: %s", reply + 5);
}
else
g_warning ("Error: %s", reply + 5);
}
// Returning the final reply
g_warning("C REPLY: %s", reply);
return reply;
}
/**
* @brief Acquires the value of the attribute given by its name from the phantom
*
* Given the @p name of the attribute to be fetched, this function will talk to the phantom, by sending a get request
* for that value and then return the response result.
*
* @author Matthias Vogelgesang
*
* @param priv
* @param name
* @return
*/
static gchar *
phantom_get_string_by_name (UcaPhantomCameraPrivate *priv, const gchar *name)
{
GMatchInfo *info;
gchar *request;
gchar *cr;
gchar *value = NULL;
gchar *reply = NULL;
gboolean regex_matches;
// This will assemble the request command by using the "get" keyword and the given attribute name of the camera
request = g_strdup_printf ("get %s\r\n", name);
// Actually sending the request to the camera and receiving its reply.
reply = phantom_talk (priv, request, NULL, 0, NULL);
g_free (request);
if (reply == NULL)
return NULL;
cr = strchr (reply, '\r');
if (cr != NULL)
*cr = '\0';
// g_warning(reply);
// This function will apply the response pattern defined using the phantom camera network protocol (the regex
// format string is now stored in priv->response_pattern) to the reply from the camera.
// The function returns a value of whether the match worked or not, but the actual info about the match is being
// stored into the info object.
regex_matches = g_regex_match (priv->response_pattern, reply, 0, &info);
if (!regex_matches) {
g_warning ("Cannot parse `%s'", reply);
g_free (reply);
return NULL;
}
// The return from the phantom camera always prepends the name of the attribute we asked for like this:
// "defc.res: 1500 x 1000". Thus here we take the second value.
value = g_match_info_fetch (info, 2);
g_match_info_free (info);
g_free (reply);
g_warning("GET STRING VALUE: %s", value);
return value;
}
/**
* @brief Given the camera and the attribute to acqquire from it, this will return the string reponse
*
* This function will return the string response for getting the given vriable from it
*
* @param priv
* @param var
* @return
*/
static gchar *
phantom_get_string (UcaPhantomCameraPrivate *priv, UnitVariable *var)
{
return phantom_get_string_by_name (priv, var->name);
}
/**
* @brief Given the camera object gets the height and width of the images
*
* This function will send a request to the camera for its resolution property and then extract the height and width
* integer values from the response string. The values will be passed out of this function using the two references
* @p *width and @p *height passed to the function as arguments. The actual return value of the function is a boolean
* indicating the succcess of retrieving the values.
*
* @param priv
* @param name
* @param width
* @param height
* @return
*/
static gboolean
phantom_get_resolution_by_name (UcaPhantomCameraPrivate *priv,
const gchar *name,
guint *width,
guint *height)
{
// For extracting the resolution from the returned result string, we are going to need yet another regex match,
// because the resolution will be encoded in a string like "1500 x 1000", with the numbers being separated by an
// x character
GMatchInfo *info;
gchar *result_string;
if (width)
*width = 0;
if (height)
*height = 0;
// This will send the actual request for the resolution property to the phantom an return the response string sent
// by the camera
result_string = phantom_get_string_by_name (priv, name);
// Of course if the camera response is not even a string we return FALSE, to indicate, that getting the resolution
// failed
if (result_string == NULL)
return FALSE;
// Also if the regex match on the given string fails, FALSE is also returned, because then again, getting the
// resolution didnt work.
if (!g_regex_match (priv->res_pattern, result_string, 0, &info)) {
g_free (result_string);
return FALSE;
}
if (width)
// The width of the image will be in the first field of the regex match info object, but as a string so we need
// to convert it to an integer first
*width = atoi (g_match_info_fetch (info, 1));
if (height)
// The height of the image will be in the second field of the regex match info object, but as a string so we need
// to convert it to an integer first
*height = atoi (g_match_info_fetch (info, 2));
g_free (result_string);
g_match_info_free (info);
return TRUE;
}
static void
phantom_get (UcaPhantomCameraPrivate *priv, UnitVariable *var, GValue *value)
{
GValue reply_value = {0,};
gchar *var_value;
var_value = phantom_get_string (priv, var);
g_warning("TR VALUE: %s", var_value);
g_warning("TRIGGER SOURCE %i", priv->uca_trigger_source == UCA_CAMERA_TRIGGER_SOURCE_SOFTWARE);
g_value_init (&reply_value, G_TYPE_STRING);
g_value_set_string (&reply_value, var_value);
if (!g_value_transform (&reply_value, value))
g_warning ("Could not transform `%s' to target value type %s", var_value, G_VALUE_TYPE_NAME (value));
g_free (var_value);
g_value_unset (&reply_value);
}
static void
phantom_set_string (UcaPhantomCameraPrivate *priv, UnitVariable *var, const gchar *value)
{
gchar *request;
gchar reply[256];
if (!(var->flags & G_PARAM_WRITABLE)) {
g_warning ("%s cannot be written", var->name);
return;
}
request = g_strdup_printf ("set %s %s\r\n", var->name, value);
phantom_talk (priv, request, reply, sizeof (reply), NULL);
g_free (request);
}
static void
phantom_set (UcaPhantomCameraPrivate *priv, UnitVariable *var, const GValue *value)
{
GValue request_value = {0,};
g_value_init (&request_value, G_TYPE_STRING);
g_value_transform (value, &request_value);
phantom_set_string (priv, var, g_value_get_string (&request_value));
g_value_unset (&request_value);
}
static void
phantom_set_resolution_by_name (UcaPhantomCameraPrivate *priv,
const gchar *name,
guint width,
guint height)
{
gchar *request;
gchar reply[256];
request = g_strdup_printf ("set %s %u x %u\r\n", name, width, height);
phantom_talk (priv, request, reply, sizeof (reply), NULL);
g_free (request);
}
/**
* @brief Returns the size of the expected data to be received for the given camera config
*
* Depending on the total amount of pixels in the image (width * height / resolution) and the used data transfer
* format, this function will return the amount of bytes to expect from the transmission.
*
* @authors Matthias Vogelgesang, Jonas Teufel
*
* @param priv
* @return
*/
static gsize
get_buffer_size (UcaPhantomCameraPrivate *priv)
{
// This will hold the actual size of the buffer later on and wil be returned
int buffer_size;
// Depending on the transfer format used, the buffer needs a different size, because the formats use a different
// amount of bits to represent a single pixel. Of course the basis of all the buffer sizes is the total amount of
// pixels in the image (width * height) but the P16 uses 16 Bit (2 bytes), the P10 uses 10 bit (1.25 bytes) per
// pixel etc. These will be the multipliers for the final size.
switch (priv->format) {
case IMAGE_FORMAT_P16:
buffer_size = priv->roi_width * priv->roi_height * 2;
break;
case IMAGE_FORMAT_P10:
buffer_size = (priv->roi_width * priv->roi_height * 5) / 4;
break;
case IMAGE_FORMAT_P12L:
buffer_size = (priv->roi_width * priv->roi_height * 3) / 2;
break;
default:
buffer_size = (priv->roi_width * priv->roi_height);
}
return buffer_size;
}
static void print_buffer(guint8 *buffer, int length) {
char string[100000];
char temp[20];
for (int i = 0; i < length; i++) {
sprintf(temp, "%02x ", buffer[i]);
strcat(string, temp);
}
//g_warning("BUFFER: %s", string);
}
// *********************************************
// "NORMAL" NETWORK INTERFACE IMAGE TRANSMISSION
// *********************************************
/**
* @brief Actually receives the image data for normal network connection
*
* This function receives all the image bytes from the given @p istream (the socket connected to the camera).
* The finished bytes for the image are stored int the "buffer" of the @p priv camera.
*
* @author Matthias Vogelgesang
*
* @param priv
* @param istream
* @param error
*/
static void
read_data (UcaPhantomCameraPrivate *priv, GInputStream *istream, GError **error)
{
gsize to_read;
to_read = get_buffer_size (priv);
// This loop exits after all the bytes of the image have been received. The "to_read" variable contains the amount
// of bytes to be received in the beginning and is then step by step decremented by the amount, that has been
// received.
while (to_read > 0) {
gsize bytes_read;
if (!g_input_stream_read_all (istream, priv->buffer, to_read, &bytes_read, NULL, error))
return;
to_read -= bytes_read;
}
}
/**
* @brief Thread, which will listen for new data connections from phantom and receive image data.
*
* This function will create a new listening socket, waiting for the phantom to make a new data connection.
* This thread is connected to the main program using a async message queue. This thread will receive image data until
* the main program sends a stop message. The end of one transmission is indicated by this thread pushing a message
* to the queue. The actual image data will be saved in the buffer of shared object @p priv
*
* @author Matthias Vogelgesang
*
* @param priv
* @return
*/
static gpointer
accept_img_data (UcaPhantomCameraPrivate *priv)
{
GSocketConnection *connection;
GSocketAddress *remote_addr;
GInetAddress *inet_addr;
Result *result;
gchar *addr;
gboolean stop = FALSE;
GError *error = NULL;
g_debug ("Accepting data connection ...");
result = g_new0 (Result, 1);
result->type = RESULT_READY;
g_async_queue_push (priv->result_queue, result);
// Listening on the socket, waiting for the phantom to establish a new connection
connection = g_socket_listener_accept (priv->listener, NULL, priv->accept, &error);
if (g_cancellable_is_cancelled (priv->accept)) {
g_warning ("Listen cancelled\n");
g_error_free (error);
return NULL;
}
if (error != NULL) {
g_warning ("Error: %s\n", error->message);
g_error_free (error);
return NULL;
}
// In case a connection has been established on the listening port, we are extracting the IP address of the client,
// that has connected (this will be the IP address of the phantom).
remote_addr = g_socket_connection_get_remote_address (connection, NULL);
inet_addr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (remote_addr));
addr = g_inet_address_to_string (inet_addr);
g_debug ("%s connected", addr);
g_warning("%s connected", addr);
g_object_unref (remote_addr);
g_free (addr);
while (!stop) {
InternalMessage *message;
GInputStream *istream;
istream = g_io_stream_get_input_stream (G_IO_STREAM (connection));
message = g_async_queue_pop (priv->message_queue);
switch (message->type) {
case MESSAGE_READ_IMAGE:
result = g_new0 (Result, 1);
// This function, actually does the job of receiving the bytes over the socket connection. The function
// will be blocking, until all bytes have been received. The received image data will be saved into
// the "priv->buffer".
read_data (priv, istream, &result->error);
// After all the image data has been received, a message indicating the success will be put into the
// queue, so that the main thread knows, that it can retrieve the image data from the "buffer" now.
result->type = RESULT_IMAGE;
result->success = TRUE;
g_async_queue_push (priv->result_queue, result);
// g_warning("receive error %s", result->error);
break;
case MESSAGE_READ_TIMESTAMP:
// not implemented
break;
case MESSAGE_STOP:
// If a "stop message" has been put into the queue by the main thread, then the "stop" variable will
// be set, which will break the loop and the whole function exits.
stop = TRUE;
break;
}
g_free (message);
}
//g_warning("EXITS THE RECEIVE LOOP");
if (!g_io_stream_close (G_IO_STREAM (connection), NULL, &error)) {
g_warning ("Could not close connection: %s\n", error->message);
g_error_free (error);
}
g_object_unref (connection);
return NULL;
}
// ******************************
// 10G NETWORK IMAGE TRANSMISSION
// ******************************
/**
*
* @deprecated
* @param priv
*/
void unpack_packet(UcaPhantomCameraPrivate *priv) {