-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathccdcapture.c
More file actions
1074 lines (1031 loc) · 33.9 KB
/
Copy pathccdcapture.c
File metadata and controls
1074 lines (1031 loc) · 33.9 KB
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
/*
* This file is part of the CCD_Capture project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ctype.h> // isspace
#include <dlfcn.h> // dlopen/close
#include <fcntl.h>
#include <float.h> // for float max
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/un.h> // unix socket
#include <unistd.h>
#include <usefull_macros.h>
#include "socket.h"
#ifdef EBUG
double __t0 = 0.;
#endif
static int ntries = 2; // amount of tries to send messages controlling the answer
double answer_timeout = 0.1; // timeout of waiting answer from server (not static for client.c)
static sem_t *sem = SEM_FAILED;
// client-side SHM lock
int cc_lock_shm(int isserver){
if(sem == SEM_FAILED){
LOGERR("cc_lock_shm(): can't lock NULL");
DBG("Can't lock NULL");
return FALSE;
}
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts); // sem_timedwait waits for absolute time!
ts.tv_nsec += 100000000; // 100 ms
if(ts.tv_nsec > 999999999){
ts.tv_nsec -= 1000000000;
++ts.tv_sec;
}
#ifdef EBUG
double tstart = sl_dtime();
#endif
DBG("Try to lock");
int locked = TRUE;
while(locked){
if(0 == sem_timedwait(sem, &ts)){
locked = FALSE;
break;
}
DBG("Errno=%d (%s)", errno, strerror(errno));
if(errno == EINTR){
DBG("Interrupt -> try to lock again");
}else{
if(errno == ENOENT || errno == EINVAL){
DBG("No semaphore -> can't lock");
LOGERR("cc_lock_shm(): no semaphore -> can't lock");
return FALSE;
}
DBG("Error locking -> %s", (isserver) ? "force unlock" : "exit");
break;
}
}
DBG("locked=%d; time=%g", locked, sl_dtime() - tstart);
if(!locked){
DBG("Semaphore locked");
return TRUE;
}
if(isserver){
double t0 = sl_dtime();
LOGERR("cc_lock_shm(): still locked -> force unlock");
while(sem_trywait(sem) && sl_dtime() - t0 < 0.1) sem_post(sem); // force locking
if(sl_dtime() - t0 >= 0.1){
LOGERR("cc_lock_shm(): failed to unlock");
}
}else{
DBG("Image semaphore is locked too long by other side");
}
return FALSE; // can't lock
}
void cc_unlock_shm(){
if(sem == SEM_FAILED){
DBG("Can't unlock NULL");
return;
}
if(sem_post(sem)){
switch(errno){
case EOVERFLOW: // already unlocked
DBG("Already unlocked");
break;
default: // not a valid? or other?
LOGERR("Can't unlock image semaphore");
ERR(_("Can't unlock image semaphore (is server alive?)"));
return;
}
}
DBG("Semaphore unlocked");
}
void cc_init_sem(int isserver){
if(sem != SEM_FAILED) return;
umask(0); // for read-write semaphore
// create samaphore if no
if(isserver){
sem = sem_open(SEM_NAME, O_CREAT, 0666, 1);
}else{
sem = sem_open(SEM_NAME, 0);
}
if(sem == SEM_FAILED){
WARNX("sem_open() failed: %s", strerror(errno));
LOGERR("sem_open() failed: %s", strerror(errno));
}
}
void cc_remove_sem(){
if(sem != SEM_FAILED){
sem_post(sem); // try to unlock if it was locked
sem_close(sem);
}
DBG("semaphore closed\n");
if(-1 == sem_unlink(SEM_NAME)){
LOGERR("Can't delete semaphore");
WARNX(_("Can't delete semaphore"));
}
}
/**
* @brief cc_open_socket - create socket and open it
* @param isserver - TRUE for server, FALSE for client
* @param path - UNIX-socket path or local INET socket port
* @param isnet - 1/2 for INET socket (1 - localhost, 2 - network), 0 for UNIX
* @return socket FD or -1 if failed
*/
int cc_open_socket(int isserver, char *path, int isnet){
DBG("isserver=%d, path=%s, isnet=%d", isserver, path, isnet);
if(!path) return 1;
//DBG("path/port: %s", path);
int sock = -1;
struct addrinfo hints = {0}, *res;
struct sockaddr_un unaddr = {0};
if(isnet){
//DBG("Network socket");
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
const char *node = (isnet == 2) ? NULL : "127.0.0.1";
if(getaddrinfo(node, path, &hints, &res) != 0){
WARN("getaddrinfo");
return -1;
}
}else{
DBG("UNIX socket");
char apath[128];
int len = sizeof(sa_family_t);
if(*path == 0){
DBG("convert name");
apath[0] = 0;
strncpy(apath+1, path+1, 126);
len += strlen(path+1);
}else if(strncmp("\\0", path, 2) == 0){
DBG("convert name");
apath[0] = 0;
strncpy(apath+1, path+2, 126);
len += strlen(path+2);
}else strcpy(apath, path);
//unlink(apath);
unaddr.sun_family = AF_UNIX;
hints.ai_addr = (struct sockaddr*) &unaddr;
hints.ai_addrlen = sizeof(unaddr);
memcpy(unaddr.sun_path, apath, len); // if sun_path[0] == 0 we don't create a file
hints.ai_family = AF_UNIX;
hints.ai_socktype = SOCK_SEQPACKET;
res = &hints;
}
for(struct addrinfo *p = res; p; p = p->ai_next){
if((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0){ // or SOCK_STREAM?
LOGWARN("socket()");
WARN("socket()");
continue;
}
int bufsz = 33554432; // 32MB for buffer size
setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &bufsz, sizeof(int));
bufsz = 33554432;
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &bufsz, sizeof(int));
if(isserver){
int reuseaddr = 1;
if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)) == -1){
WARN("setsockopt()");
LOGWARN("setsockopt()");
close(sock); sock = -1;
continue;
}
//fcntl(sock, F_SETFL, O_NONBLOCK);
if(bind(sock, p->ai_addr, p->ai_addrlen) == -1){
WARN("bind()");
LOGWARN("bind()");
close(sock); sock = -1;
continue;
}
/*
int enable = 1;
if(ioctl(sock, FIONBIO, (void *)&enable) < 0){ // make socket nonblocking
WARN("ioctl()");
LOGWARN("Can't make socket nonblocking");
}
*/
}else{
if(connect(sock, p->ai_addr, p->ai_addrlen) == -1){
WARN("connect()");
LOGWARN("connect()");
close(sock); sock = -1;
}
}
break;
}
if(isnet) freeaddrinfo(res);
return sock;
}
// send data through the socket
int cc_senddata(int fd, void *data, size_t l){
DBG("fd=%d, l=%zd", fd, l);
if(fd < 1 || !data || l < 1) return TRUE; // empty message
DBG("send new data (size=%zd) to fd %d", l, fd);
size_t total = 0;
while(total < l){
ssize_t sent = send(fd, (char*)data + total, l - total, MSG_NOSIGNAL);
if(sent <= 0){
if(errno == EAGAIN){
usleep(1000);
continue;
}
WARN("send()");
LOGWARN("send()");
break; // error
}
total += sent;
}
if(total != l) return FALSE;
DBG("success");
LOGDBG("SEND data (size=%d) to fd %d", l, fd);
return TRUE;
}
// simple wrapper over write: add missed newline and log data
int cc_sendmessage(int fd, const char *msg, int l){
if(fd < 1 || !msg || l < 1) return TRUE; // empty message
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // thread safe
pthread_mutex_lock(&mutex);
static char *tmpbuf = NULL;
static int buflen = 0;
if(l + 1 > buflen){
buflen = 1024 * (1 + l/1024);
char *newbuf = realloc(tmpbuf, buflen);
if(!newbuf){
WARN("realloc()");
LOGERR("realloc()");
return FALSE;
}
tmpbuf = newbuf;
}
DBG("send to fd %d:\n%s[%d]", fd, msg, l);
memcpy(tmpbuf, msg, l);
if(msg[l-1] != '\n') tmpbuf[l++] = '\n';
int total = 0;
while(total < l){
ssize_t sent = send(fd, tmpbuf + total, l - total, MSG_NOSIGNAL);
if(sent <= 0){
WARN("send()");
LOGWARN("send()");
break; // error
}
total += sent;
}
int ret = FALSE;
if(total == l){
ret = TRUE;
if(sl_globlog){ // logging turned ON
tmpbuf[l-1] = 0; // remove trailing '\n' for logging
LOGDBG("SEND '%s'", tmpbuf);
}
}
pthread_mutex_unlock(&mutex);
return ret;
}
int cc_sendstrmessage(int fd, const char *msg){
if(fd < 1 || !msg) return TRUE; // empty message
int l = strlen(msg);
return cc_sendmessage(fd, msg, l);
}
// text messages for `cc_hresult`
// WARNING! You should initialize ABSOLUTELY ALL members of `cc_hresult` or some pointers would give segfault
static const char *resmessages[CC_RESULT_NUM] = {
[CC_RESULT_OK] = "OK",
[CC_RESULT_BUSY] = "BUSY",
[CC_RESULT_FAIL] = "FAIL",
[CC_RESULT_BADVAL] = "BADVAL",
[CC_RESULT_BADKEY] = "BADKEY",
[CC_RESULT_SILENCE] = "",
[CC_RESULT_DISCONNECTED] = "DISCONNECTED",
};
const char *cc_hresult2str(cc_hresult r){
if(r < 0 || r >= CC_RESULT_NUM) return "BADRESULT";
return resmessages[r];
}
cc_hresult cc_str2hresult(const char *str){
for(cc_hresult res = 0; res < CC_RESULT_NUM; ++res){
if(!resmessages[res]) continue;
if(0 == strcmp(resmessages[res], str)) return res;
}
return CC_RESULT_NUM; // didn't find
}
/**
* @brief cc_get_keyval - get value of `key = val`
* @param keyval (io) - pair `key = val`, return `key`
* @return `val`
*/
char *cc_get_keyval(char **keyval){
DBG("Got string %s", *keyval);
// remove starting spaces in key
while(isspace(**keyval)) ++(*keyval);
char *val = strchr(*keyval, '=');
if(val){ // got value: remove starting spaces in val
*val++ = 0;
while(isspace(*val)) ++val;
}
DBG("val = %s (%zd bytes)", val, (val)?strlen(val):0);
// remove trailing spaces in key
char *e = *keyval + strlen(*keyval) - 1; // last key symbol
while(isspace(*e) && e > *keyval) --e;
e[1] = 0;
// now we have key (`str`) and val (or NULL)
//DBG("key=%s, val=%s", keyval, val);
return val;
}
/**
* @brief cc_getshm - get shared memory segment for image
* @param imsize - size of image data (in bytes): if !=0 allocate as server, else - as client (readonly)
* @return pointer to shared memory region or NULL if failed
*/
cc_IMG *cc_getshm(key_t key, size_t imsize){
size_t shmsize = sizeof(cc_IMG) + imsize;
shmsize = 1024 * (1 + shmsize / 1024);
DBG("Shared memory; sizeof(cc_IMG)=%zd, imsize=%zd", sizeof(cc_IMG), imsize);
int shmid = -1;
int flags = (imsize) ? IPC_CREAT | 0666 : 0;
shmid = shmget(key, 0, flags);
struct shmid_ds buf;
if(imsize){ // check if segment exists and its size equal to needs
if(shmctl(shmid, IPC_STAT, &buf) > -1 && shmsize != buf.shm_segsz){ // remove already existing segment
DBG("Need to remove already existing segment");
shmctl(shmid, IPC_RMID, NULL);
}
shmid = shmget(key, shmsize, flags);
if(shmid < 0){
WARN(_("Can't create shared memory segment %d"), key);
return NULL;
}
}else{
if(shmid < 0){ // no SHM segment for client
WARN(_("Can't get shared memory segment %d"), key);
return NULL;
}
if(shmctl(shmid, IPC_STAT, &buf)){
WARNX(_("Can't get SHM data"));
return NULL;
}else DBG("SHM size = %zd", buf.shm_segsz);
if(buf.shm_perm.mode & SHM_DEST){
WARNX(_("SHM buffer marked for deletion"));
return NULL;
}
}
flags = (imsize) ? 0 : SHM_RDONLY; // client opens memory in readonly mode
cc_IMG *ptr = shmat(shmid, NULL, 0);
if(ptr == (void*)-1){
if(imsize) WARN(_("Can't attach SHM segment %d"), key);
return NULL;
}
if(!imsize){
if(ptr->MAGICK != CC_SHM_MAGIC || buf.shm_segsz < ptr->bytelen + sizeof(cc_IMG)){
WARNX(_("Shared memory %d isn't belongs to image server"), key);
shmdt(ptr);
return NULL;
}
return ptr;
}
bzero(ptr, sizeof(cc_IMG));
ptr->data = (void*)((uint8_t*)ptr + sizeof(cc_IMG));
ptr->MAGICK = CC_SHM_MAGIC;
ptr->datasize = imsize;
return ptr;
}
// find plugin
void *cc_open_plugin(const char *name){
DBG("try to open lib %s", name);
void* dlh = dlopen(name, RTLD_NOLOAD); // library may be already opened
if(!dlh){
DBG("Not loaded - load");
dlh = dlopen(name, RTLD_NOW);
}
if(!dlh){
WARNX(_("Can't find plugin %s: %s"), name, dlerror());
return NULL;
}
return dlh;
}
cc_Focuser *cc_open_focuser(const char *pluginname){
FNAME();
void* dlh = cc_open_plugin(pluginname);
if(!dlh) return NULL;
cc_Focuser* f = (cc_Focuser*) dlsym(dlh, "focuser");
if(!f){
WARNX(_("Can't find focuser in plugin %s: %s"), pluginname, dlerror());
return NULL;
}
return f;
}
cc_Camera *cc_open_camera(const char *pluginname){
FNAME();
void* dlh = cc_open_plugin(pluginname);
if(!dlh) return NULL;
cc_Camera *c = (cc_Camera*) dlsym(dlh, "camera");
if(!c){
WARNX(_("Can't find camera in plugin %s: %s"), pluginname, dlerror());
return NULL;
}
return c;
}
cc_Wheel *cc_open_wheel(const char *pluginname){
FNAME();
void* dlh = cc_open_plugin(pluginname);
if(!dlh) return NULL;
cc_Wheel *w = (cc_Wheel*) dlsym(dlh, "wheel");
if(!w){
WARNX(_("Can't find wheel in plugin %s: %s"), pluginname, dlerror());
return NULL;
}
return w;
}
/**
* @brief cc_getNbytes - calculate amount of bytes to store bitpix (1/2)
* @param image - image
* @return 1 for bitpix<8 or 2
*/
int cc_getNbytes(cc_IMG *image){
int n = (image->bitpix + 7) / 8;
if(n < 1) n = 1;
if(n > 2) n = 2;
return n;
}
/**
* @brief cc_strbufnew - allocate new buffer
* @param bufsize - size of full socket buffer
* @param stringsize - max length of string from buffer (excluding \0)
* @return allocated buffer
*/
cc_strbuff *cc_strbufnew(size_t bufsize, size_t stringsize){
if(bufsize < 8 || stringsize < 8){
WARNX(_("Need to allocate at least 8 bytes in buffers"));
return NULL;
}
DBG("Allocate new string buffer with size %zd and string size %zd", bufsize, stringsize);
cc_strbuff *b = MALLOC(cc_strbuff, 1);
b->bufsize = bufsize;
b->buf = MALLOC(char, bufsize);
b->string = MALLOC(char, stringsize + 1); // for terminated zero
b->strlen = stringsize;
return b;
}
void cc_strbufdel(cc_strbuff **buf){
FREE((*buf)->buf);
FREE((*buf)->string);
FREE(*buf);
}
cc_charbuff *cc_charbufnew(){
DBG("Allocate new char buffer with size %d", BUFSIZ);
cc_charbuff *b = MALLOC(cc_charbuff, 1);
b->bufsize = BUFSIZ;
b->buf = MALLOC(char, BUFSIZ);
return b;
}
// set buflen to 0
void cc_charbufclr(cc_charbuff *buf){
if(!buf) return;
buf->buflen = 0;
}
// put `l` bytes of `s` to b->buf and add terminated zero
void cc_charbufput(cc_charbuff *b, const char *s, size_t l){
if(!cc_charbuftest(b, l+1)) return;
//DBG("add %zd bytes to buff", l);
memcpy(b->buf + b->buflen, s, l);
b->buflen += l;
b->buf[b->buflen] = 0;
}
void cc_charbufaddline(cc_charbuff *b, const char *s){
if(!b || !s) return;
size_t l = strlen(s);
if(l < 1 || !cc_charbuftest(b, l+2)) return;
cc_charbufput(b, s, l);
if(s[l-1] != '\n'){ // add trailing '\n'
b->buf[b->buflen++] = '\n';
b->buf[b->buflen] = 0;
}
}
// realloc buffer if its free size less than maxsize
int cc_charbuftest(cc_charbuff *b, size_t maxsize){
if(!b) return FALSE;
if(b->bufsize - b->buflen > maxsize + 1) return TRUE;
size_t newblks = (maxsize + BUFSIZ) / BUFSIZ;
b->bufsize += BUFSIZ * newblks;
DBG("Realloc charbuf to %zd", b->bufsize);
b->buf = realloc(b->buf, b->bufsize);
return TRUE;
}
void cc_charbufdel(cc_charbuff **buf){
FREE((*buf)->buf);
FREE(*buf);
}
/**
* @brief cc_read2buf - try to read next data portion from POLLED socket
* @param fd - socket fd to read from
* @param buf - buffer to read
* @return FALSE in case of buffer overflow or client disconnect, TRUE if got 0..n bytes of data
*/
int cc_read2buf(int fd, cc_strbuff *buf){
int ret = FALSE;
if(!buf) return FALSE;
pthread_mutex_lock(&buf->mutex);
if(!buf->buf || buf->buflen >= buf->bufsize) goto ret;
size_t maxlen = buf->bufsize - buf->buflen;
ssize_t rd;
do{
rd = read(fd, buf->buf + buf->buflen, maxlen);
if(rd <= 0){
if(errno == EINTR){
DBG("errno=%d, '%s'", errno, strerror(errno));
continue;
}
goto ret; // EAGAIN or other error -> client disconnected
}else break;
}while(1);
DBG("got %zd bytes", rd);
if(rd) buf->buflen += rd;
ret = TRUE;
ret:
pthread_mutex_unlock(&buf->mutex);
return ret;
}
/**
* @brief cc_refreshbuf - same as cc_read2buf, but with polling
* @param fd - socket fd
* @param buf - buffer
* @return TRUE if got data
*/
int cc_refreshbuf(int fd, cc_strbuff *buf){
if(!sl_canread(fd)) return FALSE;
return cc_read2buf(fd, buf);
}
/**
* @brief cc_getline - read '\n'-terminated string from `b` and substitute '\n' by 0
* @param b - input charbuf
* @param len - length of `str` (including terminating zero)
* @return amount of bytes read (idx > b->strlen in case of string buffer overflow)
*/
size_t cc_getline(cc_strbuff *b){
if(!b) return 0;
size_t idx = 0;
pthread_mutex_lock(&b->mutex);
if(!b->buf || !b->string) goto ret;
char *ptr = b->buf;
for(; idx < b->buflen; ++idx) if(*ptr++ == '\n') break;
if(idx == b->buflen){
idx = 0; // didn't fount '\n'
goto ret;
}
size_t minlen = (b->strlen > idx) ? idx : b->strlen; // prevent `str` overflow
memcpy(b->string, b->buf, minlen);
b->string[minlen] = 0;
if(++idx < b->buflen){ // move rest of data in buffer to beginning
memmove(b->buf, b->buf+idx, b->buflen-idx);
b->buflen -= idx;
}else b->buflen = 0;
DBG("got string `%s`", b->string);
ret:
pthread_mutex_unlock(&b->mutex);
return idx;
}
/**
* @brief cc_setNtries, cc_getNtries - ntries setter and getter
* @param n - new amount of tries
* @return cc_setNtries returns TRUE if succeed, cc_getNtries returns current ntries value
*/
int cc_setNtries(int n){
if(n > 1000 || n < 1) return FALSE;
ntries = n;
return TRUE;
}
int cc_getNtries(){return ntries;}
/**
* @brief cc_setAnsTmout, cc_getAnsTmout - answer timeout setter/getter
* @param t - timeout, s (not less than 0.001s)
* @return true/timeout
*/
int cc_setAnsTmout(double t){
if(t < 0.001) return FALSE;
answer_timeout = t;
return TRUE;
}
double cc_getAnsTmout(){return answer_timeout;}
/**
* @brief ask4cmd - send string `cmdwargs` like "par=val"
* @param fd - fd of socket
* @param buf - buffer to store data read from socket
* @param cmdwargs (i) - "par=val"
* @return CC_RESULT_OK if got same string or other error
*/
static cc_hresult ask4cmd(int fd, cc_strbuff *buf, const char *cmdwargs){
DBG("ask for command %s", cmdwargs);
char *keyptr = strdup(cmdwargs), *key = keyptr;
cc_get_keyval(&key); // pick out key from `cmdwargs`
int l = strlen(key);
cc_hresult ret = CC_RESULT_FAIL;
for(int i = 0; i < ntries; ++i){
DBG("Try %d time", i+1);
if(!cc_sendstrmessage(fd, cmdwargs)) continue;
double t0 = sl_dtime();
while(sl_dtime() - t0 < answer_timeout){
int r = sl_canread(fd);
if(r == 0) continue;
else if(r < 0){
LOGERR("Socket disconnected");
WARNX(_("Socket disconnected"));
ret = CC_RESULT_DISCONNECTED;
goto rtn;
}
while(cc_refreshbuf(fd, buf));
DBG("read");
size_t got = 0;
while((got = cc_getline(buf))){
if(got >= BUFSIZ){
DBG("Client fd=%d gave buffer overflow", fd);
LOGMSG("SERVER client fd=%d buffer overflow", fd);
}else if(got){
if(strncmp(buf->string, key, l) == 0){
ret = CC_RESULT_OK;
goto rtn;
}else{ // answers like 'OK' etc
cc_hresult r = cc_str2hresult(buf->string);
if(r != CC_RESULT_NUM){ // some other data
ret = r;
goto rtn;
}
}
}
cc_refreshbuf(fd, buf);
}
}
}
rtn:
DBG("returned with `%s`", cc_hresult2str(ret));
FREE(keyptr);
return ret;
}
#define BBUFS (63)
/**
* @brief cc_setint - send integer value over socket
* @param fd - socket fd
* @param cmd - setter
* @param val - new value
* @return answer received
*/
cc_hresult cc_setint(int fd, cc_strbuff *cbuf, const char *cmd, int val){
char buf[BBUFS+1];
snprintf(buf, BBUFS, "%s=%d\n", cmd, val);
return ask4cmd(fd, cbuf, buf);
}
/**
* @brief cc_getint - getter for integer value
*/
cc_hresult cc_getint(int fd, cc_strbuff *cbuf, const char *cmd, int *val){
char buf[BBUFS+1];
snprintf(buf, BBUFS, "%s\n", cmd);
cc_hresult r = ask4cmd(fd, cbuf, buf);
if(r == CC_RESULT_OK){
char *p = cbuf->string;
char *sv = cc_get_keyval(&p);
if(!sv) return CC_RESULT_FAIL;
char *ep;
long L = strtol(sv, &ep, 0);
if(sv == ep || L < INT_MIN || L > INT_MAX) return CC_RESULT_BADVAL;
if(val) *val = (int) L;
}
return r;
}
/**
* @brief cc_setfloat - send float value over socket
* @param fd - socket fd
* @param cmd - setter
* @param val - new value
* @return answer received
*/
cc_hresult cc_setfloat(int fd, cc_strbuff *cbuf, const char *cmd, float val){
char buf[BBUFS+1];
snprintf(buf, BBUFS, "%s=%g\n", cmd, val);
return ask4cmd(fd, cbuf, buf);
}
/**
* @brief cc_getfloat - getter for float value
*/
cc_hresult cc_getfloat(int fd, cc_strbuff *cbuf, const char *cmd, float *val){
char buf[BBUFS+1];
snprintf(buf, BBUFS, "%s\n", cmd);
cc_hresult r = ask4cmd(fd, cbuf, buf);
if(r == CC_RESULT_OK){
char *p = cbuf->string;
char *sv = cc_get_keyval(&p);
if(!sv) return CC_RESULT_FAIL;
char *ep;
double d = strtod(sv, &ep);
if(sv == ep || d < (-FLT_MAX) || d > FLT_MAX) return CC_RESULT_BADVAL;
if(val) *val = (float)d;
}
return r;
}
/**
* @brief cc_addrecord - add pre-formated record to FITS file
* @param fp - pointer to FITS file
* @param rec - record to add
* @return
*/
int cc_addrecord(fitsfile *fp, char *rec){
if(!fp || !rec) return -1;
char key[FLEN_KEYWORD];
char *eq = strchr(rec, '=');
int status = 0;
if(eq){ // found 'key = value / comment'
size_t l = eq - rec;
if(l > FLEN_KEYWORD-1) l = FLEN_KEYWORD-1;
memcpy(key, rec, l); key[l] = 0;
fits_update_card(fp, key, rec, &status);
}else fits_write_record(fp, rec, &status);
if(status) fits_report_error(stderr, status);
return status;
}
// get next record from external buffer, newlines==1 if every record ends with '\n'
char *cc_nextkw(char *buf, char record[FLEN_CARD], int newlines){
char *nextline = NULL;
int l = FLEN_CARD;
if(newlines){
char *e = strchr(buf, '\n');
if(e){
if(e - buf < FLEN_CARD) l = e - buf + 1;
nextline = e + 1;
}
}else nextline = buf + (FLEN_CARD - 1);
strncpy(record, buf, l);
if(l < FLEN_CARD) record[l] = 0;
return nextline;
}
/**
* @brief cc_kwfromfile - add records from file
* @param fp - FITS file
* @param filename - file name with FITS headers ('\n'-terminated or by 80 chars)
* @return amount of records added
*/
int cc_kwfromfile(fitsfile *fp, char *filename){
if(!fp || !filename) return 0;
sl_mmapbuf_t *buf = sl_mmap(filename);
if(!buf || buf->len < 1){
WARNX(_("Can't add FITS records from file %s"), filename);
LOGWARN("Can't add FITS records from file %s", filename);
return 0;
}
char rec[FLEN_CARD], card[FLEN_CARD];
char *data = buf->data, *x = strchr(data, '\n'), *eodata = buf->data + buf->len;
int newlines = 0;
if(x && (x - data) < FLEN_CARD){ // we found newline -> this is a format with newlines
newlines = 1;
}
int written = 0;
do{
data = cc_nextkw(data, rec, newlines);
if(data > eodata) break;
int status = 0, kt = 0;
fits_parse_template(rec, card, &kt, &status);
if(status) fits_report_error(stderr, status);
else{
if(0 == cc_addrecord(fp, card)) ++written;
}
}while(data && *data);
sl_munmap(buf);
return written;
}
static size_t print_val(cc_partype_t t, void *val, char *buf, size_t bufl){
size_t l = 0;
switch(t){
case CC_PAR_INT:
l = snprintf(buf, bufl, "%d", *(int*)val);
break;
case CC_PAR_FLOAT:
l = snprintf(buf, bufl, "%g", *(float*)val);
break;
case CC_PAR_DOUBLE:
l = snprintf(buf, bufl, "%g", *(double*)val);
break;
case CC_PAR_STRING:
l = snprintf(buf, bufl, "%s", *(char**)val);
break;
default:
l = snprintf(buf, bufl, "(undefined)");
break;
}
return l;
}
/**
* @brief cc_plugin_customcmd - common handler for custom plugin commands
* @param str - string like "par" (getter/cmd) or "par=val" (setter)
* @param handlers - NULL-terminated array of handlers for custom commands
* @param ans - buffer for output string
* @return CC_RESULT_OK if all OK or error code
*/
cc_hresult cc_plugin_customcmd(const char *str, cc_parhandler_t *handlers, cc_charbuff *ans){
if(!str || !handlers) return CC_RESULT_FAIL;
char key[256], *kptr = key;
snprintf(key, 255, "%s", str);
char *val = cc_get_keyval(&kptr);
cc_parhandler_t *phptr = handlers;
cc_hresult result = CC_RESULT_BADKEY;
char buf[512];
#define ADDL(...) do{if(ans){size_t l = snprintf(bptr, L, __VA_ARGS__); bptr += l; L -= l;}}while(0)
#define PRINTVAL(v) do{if(ans){size_t l = print_val(phptr->type, phptr->v, bptr, L); bptr += l; L -= l;}}while(0)
while(phptr->cmd){
if(0 == strcmp(kptr, phptr->cmd)){
char *bptr = buf; size_t L = 511;
result = CC_RESULT_OK;
if(phptr->checker) result = phptr->checker(str, ans);
if(phptr->ptr){ // setter/getter
if(val){if(result == CC_RESULT_OK){// setter: change value only if [handler] returns OK (`handler` could be value checker)
int ival; float fval; double dval;
#define UPDATE_VAL(type, val, pr) do{ \
if(phptr->max && val > *(type*)phptr->max){ADDL("max=" pr, *(type*)phptr->max); result = CC_RESULT_BADVAL;} \
if(phptr->min && val < *(type*)phptr->min){ADDL("min=" pr, *(type*)phptr->min); result = CC_RESULT_BADVAL;} \
if(result == CC_RESULT_OK) *(type*)phptr->ptr = val; \
}while(0)
switch(phptr->type){
case CC_PAR_INT:
ival = atoi(val);
UPDATE_VAL(int, ival, "%d");
break;
case CC_PAR_FLOAT:
fval = (float)atof(val);
UPDATE_VAL(float, fval, "%g");
break;
case CC_PAR_DOUBLE:
dval = atof(val);
UPDATE_VAL(double, dval, "%g");
break;
case CC_PAR_STRING:
if(*(char**)phptr->ptr) free(*(char**)phptr->ptr);
*(char**)phptr->ptr = strdup(val);
break;
default:
result = CC_RESULT_FAIL;
}
#undef UPDATE_VAL
}}else result = CC_RESULT_SILENCE; // getter - don't show "OK"
DBG("res=%d", result);
if(result == CC_RESULT_SILENCE || result == CC_RESULT_OK){
ADDL("%s=", phptr->cmd);
PRINTVAL(ptr);
}
if(ans) cc_charbufaddline(ans, buf);
}
break;
}
++phptr;
}
if(ans && result == CC_RESULT_BADKEY){ // cmd not found - display full help
cc_charbufaddline(ans, "Custom plugin commands:\n");
phptr = handlers;
while(phptr->cmd){
char *bptr = buf; size_t L = 511;
ADDL("\t%s", phptr->cmd);
if(phptr->type != CC_PAR_NONE){
ADDL(" = (");
switch(phptr->type){
case CC_PAR_INT:
ADDL("int");
break;
case CC_PAR_FLOAT:
ADDL("float");
break;
case CC_PAR_DOUBLE:
ADDL("double");
break;
case CC_PAR_STRING:
ADDL("string");
break;
default:
ADDL("undefined");
}
ADDL(")");
if(phptr->min || phptr->max){
ADDL(" [");
if(phptr->min) PRINTVAL(min);
else ADDL("-inf");
ADDL(", ");
if(phptr->max) PRINTVAL(max);
else ADDL("inf");
ADDL("]");
}
}
ADDL(" - ");
ADDL("%s\n", phptr->helpstring);
cc_charbufaddline(ans, buf);
++phptr;
}
}
#undef ADDL
return result;
}
/**
* @brief cc_newimage - create new empty image
* @param bitpix - 8 or 16
* @param w - width
* @param h - height
* @return pointer to allocated image or NULL if failed
*/
cc_IMG *cc_newimage(uint8_t bitpix, int w, int h){
FNAME();
if(w < 1 || h < 1){
DBG("Error: w=%d, h=%d", w, h);
return NULL;
}
cc_IMG *newima = calloc(1, sizeof(cc_IMG));
if(!newima){
WARN("calloc()");
return FALSE;
}
int N = bitpix / 8;
if(N < 1 || N > 2){
DBG("Error: %d bytes per pixel", N);
free(newima);
return NULL;
}
size_t ds = N * w * h;
newima->data = calloc(1, ds);
if(!newima->data){
WARN("calloc()");
free(newima);
return NULL;
}
newima->datasize = newima->bytelen = ds;
newima->w = w;