v1.2.2: a lot of bugs fixed

This commit is contained in:
2026-11-10 15:43:44 +03:00
parent 3db005bcae
commit 4192fc7f02
31 changed files with 1454 additions and 900 deletions

View File

@@ -207,7 +207,7 @@ static int setfastspeed(int fast){
}
static int setgeometry(cc_frameformat *f){
if(!f) return FALSE;
if(!f || f->h < 1 || f->w < 1) return FALSE;
if(f->xoff > camera.field.w - 1) f->xoff = camera.field.w - 1;
if(f->yoff > camera.field.h - 1) f->yoff = camera.field.h - 1;
if(f->w - f->xoff > camera.array.w) f->w = camera.array.w - f->xoff;
@@ -309,7 +309,7 @@ static int pollcapt(cc_capture_status *st, float *remain){
ApnGlueExpAbort();
//ApnGlueStopExposure();
DBG("ABORTED!");
if(*st) *st = CAPTURE_ABORTED;
if(st) *st = CAPTURE_ABORTED;
return FALSE;
}
if(d < 0.) d = 0.1;
@@ -320,13 +320,13 @@ static int pollcapt(cc_capture_status *st, float *remain){
static int capture(cc_IMG *ima){
FNAME();
if(!ima || !ima->data) return FALSE;
int bitpix = is16bit ? 16 : 12;
if(!ima || !ima->data || !cc_fiximage(bitpix, imW, imH, ima)) return FALSE;
DBG("ApnGlueReadPixels(%dx%d=%d)", imW, imH, imW * imH);
if(ApnGlueReadPixels((uint16_t*)ima->data, imW * imH, whynot)){
WARNX("Can't read image: %s", whynot);
return FALSE;
}
ima->bitpix = is16bit ? 16 : 12;
return TRUE;
}

View File

@@ -51,7 +51,7 @@ static int filterpos = 0;
static float focuserpos = 1., brightness = 1., gain = 0.;
static float camtemp = -30., exptime = 0.1;
static cc_capture_status capstat = CAPTURE_NO;
static double texpstart = 0.;
static double texpstart = -1.;
static uint8_t bitpix = 16; // bit depth: 8 or 16
static il_Image *imagemask = NULL, *imagebg; // mask & background
static char *maskfilename = NULL, *bgfilename = NULL; // filenames
@@ -60,6 +60,7 @@ typedef struct{
int Nstars; // amount of stars (1..MAX_STARS)
int curstarno; // current star number
int x0, y0; // center of field in array coordinates
int bias;
double rotan0; // starting rotation angle
double xs[MAX_STARS], ys[MAX_STARS]; // center of star field in array coordinates
double fwhm; // stars min FWHM, arcsec
@@ -77,6 +78,7 @@ typedef struct{
static settings_t settings = {
.Nstars = 1,
.bias = 1000,
.x0 = 512, .y0 = 512,
.fwhm = 1.5, .beta = 1., .scale = 0.03,
.fluct = 0.3, .noiselambda = 1.1, .darklambda = 1.
@@ -96,6 +98,7 @@ static il_Image *star = NULL; // template of star 0m
static double FWHM0 = 0., scale0 = 0., BETA0 = 0.; // template fwhm/scale
static int templ_wh = 0; // template width/height in pixels
static double lambdamin = 1.;
static int biasmin = 0, biasmax = 30000;
/**
* @brief test_template - test star template and recalculate new if need
@@ -166,7 +169,7 @@ DBG("MAKE STAR, wh=%d, beta=%g", templ_wh, settings.beta);
if(X0 < 0 || X0 > templ_wh - 1 || Y0 < 0 || Y0 > templ_wh - 1) continue;\
if(x0 < 0 || x0 > w-1 || y0 < 0 || y0 > h-1) continue;\
if(X1 < 0 || X1 > templ_wh || Y1 < 0 || Y1 > templ_wh) continue;\
if(X0 > X1 || Y0 > Y1) return;\
if(X0 > X1 || Y0 > Y1) continue;\
OMP_FOR()\
for(int y = Y0; y < Y1; ++y){\
type *out = &((type*)ima->data)[(y-Y0+y0)*w + x0];\
@@ -185,7 +188,7 @@ DBG("MAKE STAR, wh=%d, beta=%g", templ_wh, settings.beta);
OMP_FOR()\
for(int y = Y0; y < Y1; ++y){\
type *out = &((type*)ima->data)[(y-Y0)*w];\
uint8_t *in = &((uint8_t*)imagebg->data)[y*imagemask->width + X0];\
uint8_t *in = &((uint8_t*)imagebg->data)[y*imagebg->width + X0];\
for(int x = X0; x < X1; ++x, ++in, ++out){\
*out = (*out + *in > maxval) ? maxval : *out + *in;\
}\
@@ -205,6 +208,12 @@ DBG("MAKE STAR, wh=%d, beta=%g", templ_wh, settings.beta);
}\
} \
}\
if(settings.bias > 0){/* add bias */ \
int lvl = settings.bias; if(maxval == 0xff) lvl >>= 8; size_t WH = w * h;\
type *out = (type*)ima->data;\
OMP_FOR()\
for(size_t i = 0; i < WH; ++i) out[i] = (out[i] + lvl > maxval) ? maxval : out[i] + lvl;\
}\
if(settings.noiselambda > 1. || settings.darklambda > 1.){ /* apply noise */ \
w *= h; \
type *out = (type*)ima->data;\
@@ -245,9 +254,11 @@ static int campoll(cc_capture_status *st, float *remain){
static int startexp(){
if(capstat == CAPTURE_PROCESS) return FALSE;
capstat = CAPTURE_PROCESS;
double Tnow = sl_dtime(), dT = Tnow - texpstart, Xcd, Ycd;
if(dT < 0.) dT = 0.;
else if(dT > 1.) dT = 1.; // dT for fluctuations amplitude
double Tnow = sl_dtime();
if(texpstart < 0) texpstart = Tnow;
double dT = Tnow - texpstart, Xcd, Ycd;
if(dT < 0.) dT = 0.; // dT for fluctuations amplitude after last exposition
else if(dT > 1.) dT = 1.; // don't allow very large fluctuations as `star` could leave image
if(Tstart < 0.) Tstart = Tnow;
texpstart = Tnow;
double Tfromstart = Tnow - Tstart;
@@ -280,22 +291,20 @@ static int startexp(){
static int camcapt(cc_IMG *ima){
DBG("Prepare, xc=%d, yc=%d, bitpix=%d", Xc, Yc, bitpix);
if(!ima || !ima->data) return FALSE;
if(!ima || !ima->data || !cc_fiximage(bitpix, camera.geometry.w, camera.geometry.h, ima)) return FALSE;
#ifdef EBUG
double t0 = sl_dtime();
#endif
ima->bitpix = bitpix;
ima->w = camera.geometry.w;
ima->h = camera.geometry.h;
size_t nbytes = cc_getNbytes(ima);
size_t bytelen = ima->w * ima->h * nbytes;
if(bytelen > ima->datasize){
WARNX(_("Image size greater than buffer!"));
WARNX(_("Image size (%zd) greater than buffer (%zd)!"), bytelen, ima->datasize);
LOGWARN("ArtStar: Image size greater than buffer!");
ima->h = ima->datasize / ima->w;
ima->h = ima->datasize / ima->w / nbytes;
bytelen = ima->w * ima->h * nbytes;
}
LOGDBG("ArtStar: create new artifical star image: %zdx%zd pix", ima->w, ima->h);
ima->bytelen = ima->w * ima->h * nbytes;
ima->bytelen = bytelen;
bzero(ima->data, ima->datasize);
if(!star) ERRX(_("No star template - die"));
if(bitpix == 16) gen16(ima);
@@ -373,11 +382,22 @@ static int camshutter(_U_ cc_shutter_op s){
}
static int camsetgeom(cc_frameformat *f){
FNAME();
if(!f) return FALSE;
if(f->xoff > ARRAYW-2 || f->yoff > ARRAYH-2) return FALSE;
if(f->xoff < 0 || f->yoff < 0 || f->h < 0 || f->w < 0) return FALSE;
if(f->h + f->yoff >= ARRAYH || f->w + f->xoff >= ARRAYW) return FALSE;
LOGDBG("ArtStar: geometry changed to: %zdx%zd (offset) - %zdx%zd (w/h)",
DBG("offset: %d/%d; w/h: %d/%d", f->xoff, f->yoff, f->w, f->h);
if(f->xoff > ARRAYW-2 || f->yoff > ARRAYH-2){
DBG("Offset too large");
return FALSE;
}
if(f->xoff < 0 || f->yoff < 0 || f->h < 0 || f->w < 0){
DBG("Negative values");
return FALSE;
}
if(f->h + f->yoff > ARRAYH || f->w + f->xoff > ARRAYW){
DBG("h+off too high");
return FALSE;
}
LOGDBG("ArtStar: geometry changed to: %dx%d (offset) - %dx%d (w/h)",
f->xoff, f->yoff, f->w, f->h);
camera.geometry = *f;
return TRUE;
@@ -509,6 +529,7 @@ static cc_hresult setXYs(const char *str, cc_charbuff *ans){
}
static cc_hresult setmag(const char *str, cc_charbuff *ans){
if(!str || !ans) return CC_RESULT_BADKEY;
char buf[256], *bptr = buf;
strncpy(buf, str, 255);
char *val = cc_get_keyval(&bptr);
@@ -528,15 +549,17 @@ static cc_hresult setmag(const char *str, cc_charbuff *ans){
}
DBG("mag[%d]=%g", settings.curstarno, dval);
settings.mag[settings.curstarno] = dval;
snprintf(buf, 255, "mag[%d]=%g\n", settings.curstarno, dval);
snprintf(buf, 255, "mag[%d]=%g", settings.curstarno, dval);
cc_charbufaddline(ans, buf);
return CC_RESULT_SILENCE;
}
static cc_hresult loadmask(const char *str, cc_charbuff *ans){
if(!str || !ans) return CC_RESULT_BADKEY;
char buf[FILENAME_MAX+32], *bptr = buf;
strncpy(buf, str, FILENAME_MAX+31);
char *val = cc_get_keyval(&bptr);
if(!val || !*val) return CC_RESULT_BADVAL;
if(strcmp(bptr, "mask") != 0) return CC_RESULT_BADKEY;
if(imagemask) il_Image_free(&imagemask);
imagemask = il_Image_read(val);
@@ -558,9 +581,11 @@ static cc_hresult loadmask(const char *str, cc_charbuff *ans){
}
static cc_hresult loadbg(const char *str, cc_charbuff *ans){
if(!str || !ans) return CC_RESULT_BADKEY;
char buf[FILENAME_MAX+32], *bptr = buf;
strncpy(buf, str, FILENAME_MAX+31);
char *val = cc_get_keyval(&bptr);
if(!val || !*val) return CC_RESULT_BADVAL;
if(strcmp(bptr, "bkg") != 0) return CC_RESULT_BADKEY;
if(imagebg) il_Image_free(&imagebg);
imagebg = il_Image_read(val);
@@ -580,6 +605,7 @@ static cc_hresult loadbg(const char *str, cc_charbuff *ans){
// cmd, help, handler, ptr, min, max, type
static cc_parhandler_t handlers[] = {
{"beta", "Moffat `beta` parameter", NULL, (void*)&settings.beta, (void*)&betamin, NULL, CC_PAR_DOUBLE},
{"bias", "bias value", NULL, (void*)&settings.bias, (void*)&biasmin, (void*)&biasmax, CC_PAR_INT},
{"bkg", "load background image", loadbg, (void*)&bgfilename, NULL, NULL, CC_PAR_STRING},
{"curstar", "set number of current star to change parameters", NULL, (void*)&settings.curstarno, (void*)&nomin, (void*)&nomax, CC_PAR_INT},
{"fluct", "stars position fluctuations (arcsec per sec)", NULL, (void*)&settings.fluct, (void*)&fluctmin, (void*)&fluctmax, CC_PAR_DOUBLE},

View File

@@ -238,11 +238,11 @@ static int getgeom(){
if(!getInt("OffsetX", &i)) return FALSE;
camera.field.xoff = i.val;
camera.array.xoff = i.val;
camera.array.w -= i.val;
//camera.array.w -= i.val;
if(!getInt("OffsetY", &i)) return FALSE;
camera.field.yoff = i.val;
camera.array.yoff = i.val;
camera.array.h -= i.val;
//camera.array.h -= i.val;
camera.geometry = camera.field;
return TRUE;
}
@@ -266,7 +266,7 @@ static int geometrylimits(cc_frameformat *max, cc_frameformat *step){
static int setdevno(int N){
if(N > camera.Ndevices - 1) return FALSE;
PYLONFN(PylonCreateDeviceByIndex, 0, &hDev);
PYLONFN(PylonCreateDeviceByIndex, N, &hDev);
isopened = TRUE;
PYLONFN(PylonDeviceOpen, hDev, PYLONC_ACCESS_MODE_CONTROL | PYLONC_ACCESS_MODE_STREAM | PYLONC_ACCESS_MODE_EXCLUSIVE);
disableauto();
@@ -345,7 +345,7 @@ static int pollcapt(cc_capture_status *st, float *remain){
static int capture(cc_IMG *ima){
FNAME();
//double __t0 = dtime();
if(!ima || !ima->data || !imgBuf || !isopened) return FALSE;
if(!ima || !ima->data || !imgBuf || !isopened || !cc_fiximage(bitdepth, camera.geometry.w, camera.geometry.h, ima)) return FALSE;
static int toohot = FALSE;
float_values f;
//TIMESTAMP("start capt");
@@ -377,19 +377,17 @@ static int capture(cc_IMG *ima){
int width = grabResult.SizeX, height = grabResult.SizeY, stride = grabResult.SizeX + grabResult.PaddingX;
//TIMESTAMP("start converting");
if(bitdepth > 8){
int s2 = stride<<1;
int s2 = stride<<1, w2 = width*2;
OMP_FOR()
for(int y = 0; y < height; ++y){
uint8_t *Out = &((uint8_t*)ima->data)[y*width];
const uint8_t *In = &imgBuf[y*s2];
for(int x = 0; x < width; ++x){
*Out++ = *In; In += 2;
}
uint16_t *Out = &((uint16_t*)ima->data)[y*width];
const uint16_t *In = (uint16_t*)&imgBuf[y*s2];
memcpy(Out, In, w2);
}
}else{
OMP_FOR()
for(int y = 0; y < height; ++y){
uint16_t *Out = &((uint16_t*)ima->data)[y*width];
uint8_t *Out = &((uint8_t*)ima->data)[y*width];
const uint8_t *In = &imgBuf[y*stride];
memcpy(Out, In, width);
}

View File

@@ -1,9 +1,9 @@
cmake_minimum_required(VERSION 3.20)
cmake_minimum_required(VERSION 4.0)
set(PROJ ccd_capture)
set(PROJLIB ccdcapture)
set(MAJOR_VERSION "1")
set(MID_VERSION "2")
set(MINOR_VERSION "1")
set(MINOR_VERSION "2")
set(LIBSRC ccdcapture.c)
set(SOURCES main.c cmdlnopts.c ccdfunc.c server.c client.c)
@@ -28,7 +28,7 @@ option(EXAMPLES "Some examples" OFF)
option(ASTAR "Artifical star plugin" OFF)
# default flags
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -Wall -W -Wextra -fno-builtin-strlen")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -W -Wextra -fno-builtin-strlen")
message("Install dir prefix: ${CMAKE_INSTALL_PREFIX}")
if(NOT DEFINED LOCALEDIR)
@@ -42,7 +42,7 @@ endif()
add_definitions(-D_XOPEN_SOURCE=1234 -D_DEFAULT_SOURCE -D_GNU_SOURCE -DLOCALEDIR=\"${LOCALEDIR}\"
-DPACKAGE_VERSION=\"${VERSION}\" -DGETTEXT_PACKAGE=\"${PROJ}\"
-DMINOR_VERSION=\"${MINOR_VERSION}\" -DMID_VERSION=\"${MID_VERSION}\"
-DMAJOR_VERSION=\"${MAJOR_VESION}\")
-DMAJOR_VERSION=\"${MAJOR_VERSION}\")
set(CMAKE_COLOR_MAKEFILE ON)

View File

@@ -49,7 +49,7 @@ static int campoll(cc_capture_status *st, float *remain){
if(capstat != CAPTURE_PROCESS){
if(st) *st = capstat;
if(remain) *remain = 0.;
return FALSE;
return TRUE;
}
if(sl_dtime() - texpstart > exptime){
if(st) *st = CAPTURE_READY;
@@ -71,7 +71,7 @@ static int startexp(){
static int camcapt(cc_IMG *ima){
static int n = 0;
if(!ima || !ima->data) return FALSE;
if(!ima || !ima->data || !cc_fiximage(bitpix, camera.geometry.w, camera.geometry.h, ima)) return FALSE;
#ifdef EBUG
double t0 = sl_dtime();
#endif

View File

@@ -24,6 +24,8 @@ extern cc_Camera camera;
extern cc_Focuser focuser;
extern cc_Wheel wheel;
static int bitdepth = 8;
/**
* @brief campoll - camera.pollcapture - polling of capture process status
* @param st (o) - status of capture process
@@ -48,6 +50,7 @@ static int startexp(){
* @return FALSE if failed or bad `ima`
*/
static int camcapt(cc_IMG _U_ *ima){
if(!ima || !ima->data || !cc_fiximage(bitdepth, camera.geometry.w, camera.geometry.h, ima)) return FALSE;
return FALSE;
}
@@ -56,8 +59,10 @@ static int camcapt(cc_IMG _U_ *ima){
* @param b - bit depth, 1 - high (16 bit), 0 - low (8 or other bit)
* @return FALSE if failed
*/
static int camsetbit(int _U_ b){
return FALSE;
static int camsetbit(int b){
if(b) bitdepth = 16;
else bitdepth = 8;
return TRUE;
}
/**

View File

@@ -292,7 +292,7 @@ static int fli_fhome(int async){
static int fli_fgoto(int async, float pos){
long tagpos = pos * FOCSCALE;
if(tagpos > focmaxpos) return FALSE;
if(tagpos > focmaxpos || tagpos < 0) return FALSE;
DBG("tagpos: %ld, focuserpos: %ld", tagpos, focuserpos);
tagpos -= focuserpos;
if(labs(tagpos) < 2) return TRUE;
@@ -461,7 +461,8 @@ retn:
}
static int fli_capt(cc_IMG *ima){
if(!ima || !ima->data) return FALSE;
int bitpix = is16bit ? 16 : 8;
if(!ima || !ima->data || !cc_fiximage(bitpix, camera.geometry.w, camera.geometry.h, ima)) return FALSE;
for(int row = 0; row < ima->h; row++){
void *ptr = NULL;
if(is16bit) ptr = (void*)(((uint16_t*)ima->data) + row * ima->w);
@@ -469,7 +470,6 @@ static int fli_capt(cc_IMG *ima){
TRYFUNC(FLIGrabRow, camdev, ptr, ima->w);
if(fli_err) return FALSE;
}
ima->bitpix = is16bit ? 16 : 8;
return TRUE;
}
@@ -571,10 +571,10 @@ static int fli_shutter(cc_shutter_op cmd){
case SHUTTER_CLOSE:
break;
case SHUTTER_OPENATHIGH:
shtr = FLI_SHUTTER_EXTERNAL_EXPOSURE_CONTROL|FLI_SHUTTER_EXTERNAL_TRIGGER_HIGH;
shtr = FLI_SHUTTER_EXTERNAL_EXPOSURE_CONTROL | FLI_SHUTTER_EXTERNAL_TRIGGER_HIGH;
break;
case SHUTTER_OPENATLOW:
shtr = FLI_SHUTTER_EXTERNAL_EXPOSURE_CONTROL|FLI_SHUTTER_EXTERNAL_TRIGGER_HIGH;
shtr = FLI_SHUTTER_EXTERNAL_EXPOSURE_CONTROL | FLI_SHUTTER_EXTERNAL_TRIGGER_LOW;
break;
default:
return FALSE;
@@ -592,9 +592,10 @@ static int fli_confio(int io){
static int fli_getio(int *io){
if(!io) return FALSE;
long lio = (long)*io;
long lio;
TRYFUNC(FLIReadIOPort, camdev, &lio);
if(fli_err) return FALSE;
*io = (int) lio;
return TRUE;
}

View File

@@ -231,7 +231,7 @@ static int geometrylimits(cc_frameformat *max, cc_frameformat *step){
static int setdevno(int N){
if(N > camera.Ndevices - 1) return FALSE;
FC2FN(fc2GetCameraFromIndex, 0, &guid);
FC2FN(fc2GetCameraFromIndex, N, &guid);
FC2FN(fc2Connect, &guid);
isopened = TRUE;
disableauto();
@@ -291,7 +291,8 @@ rtn:
static int capture(cc_IMG *ima){
FNAME();
if(canceled) return FALSE;
if(!ima || !ima->data || !isopened) return FALSE;
int bitpix = (is16bit) ? 16 : 8;
if(!ima || !ima->data || !isopened || !cc_fiximage(bitpix, camera.geometry.w, camera.geometry.h, ima)) return FALSE;
static int toohot = FALSE;
float f;
if(getfloat(FC2_TEMPERATURE, &f)){
@@ -323,18 +324,16 @@ static int capture(cc_IMG *ima){
OMP_FOR()
for(int y = 0; y < height; ++y){
uint16_t *Out = &((uint16_t*)(ima->data))[y*width];
const uint8_t *In = (uint8_t*)&convertedImage.pData[y*stride];
const uint16_t *In = (uint16_t*)&convertedImage.pData[y*stride];
memcpy(Out, In, w2);
//DBG("Row %d copied. First byte: %d", y, *((uint16_t*)In));
}
}else{
OMP_FOR()
for(int y = 0; y < height; ++y){
uint16_t *Out = &((uint16_t*)(ima->data))[y*width];
uint8_t *Out = &((uint8_t*)(ima->data))[y*width];
const uint8_t *In = (uint8_t*)&convertedImage.pData[y*stride];
for(int x = 0; x < width; ++x){
*Out++ = *In++;
}
memcpy(Out, In, width);
//DBG("Row %d copied. Last byte: %d", y, *((uint16_t*)In));
}
}

View File

@@ -267,7 +267,7 @@ static int cam_findCCD(){
if(!pDeviceInfo) continue;
PrintDeviceInfo(pDeviceInfo);
}
} else{
}else{
WARNX("No HIKROBOT cameras found");
return FALSE;
}
@@ -444,21 +444,23 @@ retn:
static int cam_capt(cc_IMG *ima){
if(!handle || !pdata) return FALSE;
if(!ima || !ima->data) return FALSE;
MVCC_ENUMVALUE EnumValue;
TRY(GetEnumValue, "PixelSize", &EnumValue);
DBG("PixelSize = %u", EnumValue.nCurValue);
ONOK(){
int bytes = ima->h*ima->w * ((7 + ima->bitpix) / 8), stbytes = stImageInfo.nWidth * stImageInfo.nHeight;
int bitpix = 16;
int stbytes = stImageInfo.nWidth * stImageInfo.nHeight;
if(EnumValue.nCurValue == 16){
ima->bitpix = 12;
bitpix = 12;
stbytes *= 2;
}else if(EnumValue.nCurValue == 8){
ima->bitpix = 8;
bitpix = 8;
}else{
WARNX("Unsupported pixel size");
return FALSE;
}
if(!ima || !ima->data || !cc_fiximage(bitpix, stImageInfo.nWidth, stImageInfo.nHeight, ima)) return FALSE;
int bytes = cc_getNbytes(ima);
if(bytes > pdatasz) bytes = pdatasz;
if(bytes != stbytes) WARNX("Different sizes of image buffer & grabbed image");
DBG("Copy %d bytes (stbytes=%d)", bytes, stbytes);
@@ -490,7 +492,7 @@ static int cam_setgeometry(cc_frameformat *f){
static int cam_settemp(float t){
if(!handle) return FALSE;
if(!changeenum("DeviceTemperatureSelector", 0)) return FALSE;
if(!changeenum("DeviceTemperature", t)) return FALSE;
if(!changefloat("DeviceTemperature", t)) return FALSE;
return TRUE;
}

307
Readme.md
View File

@@ -1,7 +1,7 @@
CCD/CMOS imaging server
=======================
Supports FLI cameras/focusers/wheels and cameras: ZWO, Basler, HikRobot, PointGrey, Apogee.
Supports FLI cameras/focusers/wheels and cameras: ZWO, Basler, HikRobot, PointGrey, Apogee, ToupCam.
Allows to run as standalone application or imaging server/client.
To restart server (e.g. if hardware was off) kill it with SIGUSR1 or send command `restartTheServer`.
@@ -9,8 +9,8 @@ To restart server (e.g. if hardware was off) kill it with SIGUSR1 or send comman
## Compile
The tool itself depends on [usefull_macros](https://github.com/eddyem/snippets_library) librariy.
"Artifical star" plugin depends on my [improclib](https://github.com/eddyem/improclib).
Image viewer depends on OpenGL and GLUT libraries (also depending on X11).
All other plugins (excluding "dummy camera") depends on third-party libraries. Apogee plugin also
The image viewer depends on OpenGL and GLUT libraries (also depending on X11).
All other plugins (excluding "dummy camera") depends on third-party libraries. The Apogee plugin also
depends on [apogee C wrapper](https://github.com/eddyem/apogee_control/tree/master/apogee_C_wrapper).
I will try later to combine all third-party libraries in this repository.
@@ -28,12 +28,15 @@ cmake options:
- `-DFLYCAP=ON` - compile GrassHopper PointGrey plugin
- `-DHIKROBOT=ON` - compile HikRobot support plugin
- `-DIMAGEVIEW=OFF` - compile without image viewer support (OpenGL!!!)
- `-DTOUPCAM=ON` - compile ToupCam support plugin
- `-DZWO=ON` - compile ZWO support plugin
## Usage
```
Usage: ccd_capture [args] [output file prefix]
Args are:
-0, --timeout=arg network answer timeout (default: 0.1s)
-8, --8bit run in 8-bit mode
-A, --author=arg program author
-C, --cameradev=arg camera device plugin (e.g. devfli.so)
@@ -44,10 +47,10 @@ Usage: ccd_capture [args] [output file prefix]
-N, --obsname=arg observers' names
-O, --object=arg object name
-P, --prog-id=arg observing program name
-V, --verbose verbose level (-V - messages, -VV - debug, -VVV - all shit)
-V, --verbose verbose level (-V - main messages, -VV - secondary messages, -VVV - debug)
-W, --wheeldev=arg wheel device plugin (e.g. devdummy.so)
-Y, --objtype=arg object type (neon, object, flat etc)
-_, --plugincmd custom camera device plugin command
-_, --plugincmd=arg custom camera device plugin command (can occur multiple times)
-a, --addsteps=arg move focuser to relative position, mm (only for standalone)
-c, --conf-ioport=arg configure I/O port pins to given value (decimal number, pin1 is LSB, 1 == output, 0 == input)
-d, --dark not open shutter, when exposing ("dark frames")
@@ -60,7 +63,7 @@ Usage: ccd_capture [args] [output file prefix]
-n, --nframes=arg make series of N frames
-o, --outfile=arg output file name
-p, --pause=arg make pause for N seconds between expositions
-r, --addrec add records to header from given file[s]
-r, --addrec=arg add records to header from given file[s] (can occur multiple times)
-s, --set-ioport=arg set I/O port pins to given value (decimal number, pin1 is LSB)
-t, --set-temp=arg set CCD temperature to given value (degr C)
-v, --vbin=arg vertical binning to N pixels
@@ -77,26 +80,37 @@ Usage: ccd_capture [args] [output file prefix]
--client run as client
--close-shutter close shutter
--focdevno=arg focuser device number (if many: 0, 1, 2 etc)
--forceimsock force using image through socket transition even if can use SHM
--gain=arg CMOS gain level
--help show this help
--imageport=arg INET image socket port
--host=arg server's host name
--imageport=arg INET image socket port (default: port+1)
--infty=arg start (!=0) or stop(==0) infinity capturing loop
--logfile=arg logging file name (if run as server)
--open-shutter open shutter
--path=arg UNIX socket name (command socket)
--plugin=arg common device plugin (e.g devfli.so)
--port=arg local INET command socket port
--port=arg INET command socket port (omit if use on same host with server)
--restart restart image server
--rewrite rewrite output file if exists
--server run as server
--set-fan=arg set fan speed (0 - off, 1 - low, 2 - high)
--shutter-on-high run exposition on HIGH @ pin5 I/O port
--shutter-on-low run exposition on LOW @ pin5 I/O port
--viewer passive viewer (only get last images)
--wait wait while exposition ends
--wheeldevno=arg filter wheel device number (if many: 0, 1, 2 etc)
```
Notes:
- A UNIX command socket named `@ccd_capture` is created/used automatically
(abstract namespace, no file on disk). There is no `--path` option; the
name is hardcoded in `socket.h` as `UNIX_SOCK_NAME`.
- If neither `--port` nor `--imageport` is given, the client receives images
through shared memory (see `-k/--shmkey`). To force image transmission over
INET, point `--host`, `--port` and/or `--imageport` (this replaces the removed `--forceimsock`).
If server run without `--port`, there's only shared memory mechanism to grab images for client.
- If `--port` is given without `--imageport`, the latter is set to `port+1` automatically.
## Image viewer
In image view mode you can display menu by clicking of right mouse key or use shortcuts:
@@ -124,105 +138,126 @@ Mouse functions:
When you run the server you need at least to point:
- camera plugin (`-C libdev….so`);
- command socket: it could be local INET socket (then by default image socket will have next number),
just point `--port=port`, or UNIX socket, then point `--path=path` (for unnamed sockets use "\0" as first
path letter);
- image socket (optionally): `--imageport=port` - to have ability to transmit image to other PCs by
network INET socket (default value: 12345 if no command socket port used, or cmdport+1);
- shared memory key for fast local image transmission, `-k=key` (default value: 7777777).
- a way to accept commands:
- UNIX socket `@ccd_capture` - always opened by the server; the local client
connects to it by default when no `--port` is given;
- optionally an INET command socket, via `--port=port`;
- optionally an INET image socket, via `--imageport=port`; if you point `--port`
but not `--imageport`, the latter defaults to `port+1`;
- shared memory key for fast local image transmission, `-k=key` (default: `7777777`).
To send commands to server you can use client, open `netcat` session, use my [tty_term](https://github.com/eddyem/tty_term)
or any other tools. Server have text protocol (send `help\n` to see full list):
To send commands to server you can use the client, `netcat` session, my
[tty_term](https://github.com/eddyem/tty_term) or any other tool. The server speaks a simple
line-based text protocol (send `help` to see the full list).
- 8bit - run in 8 bit mode instead of 16 bit
- author - FITS 'AUTHOR' field
- brightness - camera brightness
- camdevno - camera device number
- camlist - list all connected cameras
- ccdfanspeed - fan speed of camera
- confio - camera IO configuration
- dark - don't open shutter @ exposure
- expstate - get exposition state
- exptime - exposition time
- fastspeed - fast readout speed
- filename - save file with this name, like file.fits
- filenameprefix - prefix of files, like ex (will be saved as exXXXX.fits)
- focdevno - focuser device number
- foclist - list all connected focusers
- focpos - focuser position
- format - camera frame format (X0,Y0,X1,Y1)
- gain - camera gain
- getheaders - get last file FITS headers
- hbin - horizontal binning
- headerfiles - add FITS records from these files (comma-separated list)
- help - show this help
- imheight - last image height
- imwidth - last image width
- info - connected devices state
- infty - an infinity loop taking images until there's connected clients
- instrument - FITS 'INSTRUME' field
- io - get/set camera IO
- lastfilename - path to last saved file
- maxformat - camera maximal available format
- nflushes - camera number of preflushes
- object - FITS 'OBJECT' field
- objtype - FITS 'IMAGETYP' field
- observer - FITS 'OBSERVER' field
- plugincmd - custom camera plugin command
- program - FITS 'PROG-ID' field
- restartTheServer - restart server
- rewrite - rewrite file (if give `filename`, not `filenameprefix`)
- shmemkey - get shared memory key
- shutter - camera shutter's operations
- tcold - camera chip temperature
- tremain - time (in seconds) of exposition remained
- vbin - vertical binning
- wdevno - wheel device number
- wlist - list all connected wheels
- wpos - wheel position
### Protocol
Each request is a single line, terminated by `\n`:
Send `expstate=1` to start capture. As only the frame is ready server will send `expstate=4` to all
clients connected.
- `key` - getter or command without arguments
- `key=value` - setter
When you send a command to server you will receive:
The server answers with one line (or several, for `help`, `camlist`, `foclist`,
`wlist`):
- one of answers - "OK" (all OK), "BUSY" (can't run setter because camera is busy), "FAIL" (some error
occurred), "BADKEY" (wrong key name) or "BADVAL" (wrong key's value) - for procedures and setters
(instead of "OK" you will give "parameter=value" for setter if all OK);
- "parameter=value" for getters.
- `OK` - the command completed successfully
- `BUSY` - cannot run the command now (camera is busy)
- `FAIL` - some error occurred
- `BADKEY` - unknown key
- `BADVAL` - invalid value for the key
- `key=value` - for getters (and setters, as echo of the new value)
Command `info` equivalent to sequential commands `camlist`, `hbin`, `vbin`, `tcold`, `tbody`, `thot`,
`exptime`, `lastfilename`, `expstate` and `camflags`.
### Supported commands
Command `getheaders` returns base FITS-header of last file.
| Command | Description |
|---------------------|-------------|
| `brightness[=V]` | get/set camera brightness |
| `camdevno[=N]` | get/set active camera number |
| `camfanspeed[=N]` | get/set camera fan speed (0..2) |
| `camflags` | get flags: bit0 - start capture, bit1 - cancel, bit2 - restart server |
| `camlist` | list all connected cameras (one `camlist='model'` line per camera) |
| `confio[=N]` | configure I/O port |
| `dark[=0/1]` | don't open shutter on exposure (dark frames) |
| `expstate[=N]` | see below |
| `exptime[=V]` | get/set exposure time (s) |
| `fastspeed[=0/1]` | get/set fast readout mode |
| `focdevno[=N]` | get/set active focuser |
| `foclist` | list all connected focusers |
| `focmaxpos` | get maximal focuser position |
| `focminpos` | get minimal focuser position |
| `focpos[=V]` | get/set focuser position (mm) |
| `foctemp` | get focuser body temperature |
| `format[=X0,Y0,X1,Y1]` | get/set camera frame format |
| `gain[=V]` | get/set camera gain |
| `hbin[=N]` | get/set horizontal binning |
| `help` | show this help |
| `imnumber` | number of grabbed images since the server start |
| `imwidth` / `imheight` | width/height of the last image |
| `infty[=0/1]` | run/stop the infinity capturing loop |
| `io[=N]` | get/set I/O port state |
| `lowres[=0/1]` | run in 8-bit mode instead of 16-bit |
| `maxformat` | get maximal available frame format |
| `nflushes[=N]` | get/set number of pre-flushes |
| `plugincmd=KEY[=VAL]` | custom camera plugin command |
| `restartTheServer` | restart the server |
| `shmemkey` | get shared memory key |
| `shutter=N` | run shutter command (0=open, 1=close, 2=expose @HIGH, 3=expose @LOW) |
| `tcold[=V]` | get/set cold-side temperature; also returns `tbody=` and `thot=` if supported |
| `tremain` | remaining exposure time (s) |
| `vbin[=N]` | get/set vertical binning |
| `wdevno[=N]` | get/set active wheel |
| `wlist` | list all connected wheels |
| `wmaxpos` | get maximal wheel position |
| `wpos[=N]` | get/set wheel position |
| `wtemp` | get wheel body temperature |
`expstate` values:
- `0` - idle (sending `expstate=0` cancels the current exposition);
- `1` - capturing (sending `expstate=1` starts an exposition);
- `2` - frame is ready (invalid for setter);
- `3` - error (invalid for setter).
Server doesn't sends to client any asynchronous data.
### Custom plugin commands
Since version 1.2.0 a custom plugin command system is available. To list the available commands,
run the client/server with `--plugincmd=help`, or send `plugincmd=help` to a running server.
Commands can be procedures/flags (`plugincmd=cmd`) or setters/getters (`plugincmd=key` and
`plugincmd=key=value`).
To transmit these custom commands to the server use `plugincmd=key[=value]`.
## Client
To run client you should point `--client` and same ports' options like for server (command socket and
image SHM key or socket).
Use `--forceimsock` to forse getting image through INET socket even if run on the same PC as server.
Client have no options to connect to server on other host, so you need to make proxy with ssh or other
tool. Maybe later I will add `--host` option for these purposes (but for security you will still have
to use ssh-proxy for command socket).
To run the client you should point `--client` and the same port options as for
the server (command socket and image SHM key or image socket):
Using client as pure viewer (using `--viewer` option) you can't run expositions - just can view last
files done by command from other clients. But if you will send to server `infty=1`, it will run in
infinity mode, making frame by frame while at least one client connected. To turn this off send
`infty=0`.
- `--host=HOST` (optional) - server host name / IP for INET command socket;
- `--port=PORT` (optional) - INET command socket port; if omitted, the client
connects to the UNIX socket `@ccd_capture` on the local host;
- `--imageport=PORT` (optional) - INET image socket port; if omitted, the client
receives images through the shared memory segment `-k/--shmkey`;
- `-k/--shmkey=KEY` (optional) - shared memory key for image data.
Without image view options (`--viewer` or `-D`) client just send given options to server and shuts down,
but you can wait until image done with option `--wait` (be careful: when reading process takes too long
time taking server in busy state, client can decide to shut down by timeout).
Client modes:
## Plugins custom commands
Since version 1.2.0 introduced custom camera plugin commands system. Commonly to read help just
type `-_help`. You can point as much custom commands in one commandline as you need. They can be a
procedures/flags (like `-_cmd`) or a setters/getters (like `-_key` and `-_key=value`).
- with `--viewer` - opens the OpenGL viewer and passively receives
images from the server (in this mode the client cannot start expositions);
to produce images continuously the server must be set to `infty=1`, or other
clients must send `expstate=1`;
- with `--display` (or `-D`) - opens the OpenGL window and continuously requests server for
new images (you should point `--exptime=T` (or `-x T`) for specific exposition time;
- without viewer options - sends the given options to the server and exits;
if you specify `--outfile`, `--outfileprefix` or `--nframes>0`, the client
starts an exposition, waits for the image, and optionally saves it as FITS.
To transmit these custom commands to server use `plugincmd=key[=value]`.
`--forceimsock` was removed; use `--port` and optionally `--imageport` to force image transfer over
INET socket instead of shared memory
### Dummy camera plugin custom commands
This plugin simply emulates image aqcuisition process where images are 2-D sinusoide with given periods.
Each next frame will be shifted by one pixel.
## Dummy camera plugin
The plugin simply emulates the acquisition process: images are a 2-D sinusoid
with given periods, shifted by one pixel each frame.
Commands:
@@ -230,29 +265,31 @@ Commands:
- py = (double) [1, inf] - set/get sin period over Y axis (pix)
### Artifical star plugin custom commands
This plugin lets you to emulate star field with up to 32 stars. You can shift center of field emulating
telescope correction, also you can rotate field emulating derotation.
All stars (Moffat) have the same FWHM and scale parameters. Their coordinates (arcsec) are given by arrays `x`
and `y` with a hardware magnitude `mag`. You can emulate image drift and rotation. Also you can add
a little image position (full frame position) fluctuations. To emulate poisson noice just point its `lambda`
value (`lambda==1` means no noise).
## Artifical star plugin
The plugin emulates a star field with up to `MAX_STARS` (32) stars. You can shift the center of the
field to emulate telescope correction and rotate the field to emulate derotation. All stars are
Moffat profiles with the same FWHM and scale parameters. Their coordinates (arcsec) are stored in
arrays `x` and `y`, with magnitudes in `mag`. You can emulate image drift, rotation, short-exposure
position fluctuations, and Poisson noise (`lambda==1` means "no noise").
Two additional commands - `mask` and `bkg` allows you to load binary mask and background.
The background image (8-bit monochrome) will be added to generated star field. After that if you
pointed an mask image it will be AND-ed with result: all non-zero pixels on mask remains the same
pixels of resulting image, but zeros will clean them emulating holes or screens.
And at last Poisson noice will be added to full frame.
Two additional commands - `mask` and `bkg` - allow you to load a binary mask and a background
image. The background (8-bit monochrome) is added to the generated star field. The mask is then
AND-ed with the result: zero mask pixels force the output to zero, non-zero pixels are preserved.
After that, the bias level is added and (optionally) Poisson noise is applied to the full frame.
Commands:
- beta = (double) [0.5, inf] - Moffat `beta` parameter
- bias = (int) [0, 30000] - bias value
- bkg = (string) - load background image
- curstar = (int) [0, MAX_STARS-1] - set number of current star to change parameters
- fluct = (double) [0, 3] - stars position fluctuations (arcsec per sec)
- fwhm = (double) [0.1, 10] - stars min FWHM, arcsec
- lambda = (double) [1, inf] - Poisson noice lambda value (>1)
- lambda0 = (double) [1, inf] - Poisson noice lambda value (>1) for dark noise
- mag = (double) [-30, 30] - Next star magnitude: 0m is 0xffff/0xff (16/8 bit) ADUs per second
- mask = (string) - load mask image (binary, ANDed)
- nstars = (int) [1, MAX_STARS] - set amount of stars (not more than MAX_STARS)
- rotangle = (double) [0, 1.296e+06] - Starting rotation angle (arcsec)
- scale = (double) [0.001, 3600] - CCD scale: arcsec/pix
- vr = (double) [-36000, 36000] - rotation speed (arcsec/s)
@@ -267,16 +304,52 @@ Commands:
## Examples
### ccd_client
Connect to server, send `infty` and simply get up to N images (or quit if no images in 5 seconds).
Connects to the server, optionally enables `infty`, and takes up to `N` images (or quits if no
image is available for a few seconds).
Usage:
```
-U, --isun use UNIX socket
-h, --help show this help
-i, --infty run in infinity capturing loop (else - request each frame)
-k, --shmkey=arg shared memory (with image data) key (default: 7777777)
-n, --nframes=arg make series of N frames (2 default)
-s, --sock=arg command socket name or port
-x, --exptime=arg set exposure time to given value (seconds!)
-N, --node=arg server's host (if working over net) or UNIX-socket path
-P, --import=arg image socket port (if not 'port+1'
-h, --help show this help
-i, --infty run in infinity capturing loop (else - request each frame)
-k, --shmkey=arg shared memory (with image data) key (default: 7777777)
-n, --nframes=arg make series of N frames
-p, --port=arg command socket port
-x, --exptime=arg set exposure time to given value (seconds!)
```
### centroids / centroids16
Get images from the server (only over shared memory) and calculate the gravity center and moments
of the first-order/second-order brightness. `centroids` works only in 8-bit mode and `centroids16`
only in 16-bit mode.
Usage:
```
-N, --node=arg INET command socket host or UNIX socket name
-b, --background=arg fixed background level
-h, --help show this help
-i, --infty run in infinity capturing loop (else - request each frame)
-k, --shmkey=arg shared memory (with image data) key (default: 7777777)
-n, --nframes=arg make series of N frames (default: 10)
-o, --output=arg output file with T/x/y/w
-p, --port=arg port of INET command socket
-s, --sigmas=arg amount of sigmas [-5..15] added to image median for background calculation (default: 1)
-x, --exptime=arg set exposure time to given value (seconds!)
```
Option `--sigmas` works only for 16-bit version, as in 8-bit background calculation use
`il_Image_background` (calculates background by histogram curve).
## Known issues
- The server requires at least one command socket (`@ccd_capture` UNIX socket
is always created; INET command socket is optional).
- If both `--outfile` and an output-file prefix (positional argument) are given,
the program exits.
- The image viewer uses OpenGL and freeglut; it needs an X11 display.
## License
This repository is provided under the GNU General Public License v3 or later.
Full text of the GPLv3 is available at <https://www.gnu.org/licenses/gpl-3.0.html>.

View File

@@ -247,6 +247,7 @@ static void EventCallback(unsigned nEvent, void _U_ *pCallbackCtx){
case TOUPCAM_EVENT_ERROR:
WARNX(_("Error occured"));
camcancel();
return;
case TOUPCAM_EVENT_IMAGE:
break;
default:
@@ -263,7 +264,7 @@ static void EventCallback(unsigned nEvent, void _U_ *pCallbackCtx){
++toupcam.imseqno;
DBG("Image %lu (%dx%d) ready!", toupcam.imseqno, info.v3.width, info.v3.height);
toupcam.state = IM_READY;
toupcam.imsz = info.v3.height * info.v3.width * toupcam.bytepix;
toupcam.imsz = (size_t)info.v3.height * info.v3.width * toupcam.bytepix;
// geometry.h/w WITHOUT binning!
camera.geometry.h = info.v3.height * toupcam.curbin;
camera.geometry.w = info.v3.width * toupcam.curbin;
@@ -311,7 +312,8 @@ static int startexp(){
*/
static int camcapt(cc_IMG *ima){
TCHECK();
if(!ima || !ima->data || !toupcam.data) return FALSE;
int bitpix = toupcam.bytepix * 8;
if(!ima || !ima->data || !toupcam.data || !cc_fiximage(bitpix, camera.geometry.w, camera.geometry.h, ima)) return FALSE;
//DBG("LOCK");
pthread_mutex_lock(&toupcam.mutex);
size_t fullsz = ima->w * ima->h * toupcam.bytepix;
@@ -324,7 +326,6 @@ static int camcapt(cc_IMG *ima){
ima->w * ima->h * toupcam.bytepix, toupcam.imsz, ima->w, ima->h);
}
memcpy(ima->data, toupcam.data, fullsz);
ima->bitpix = toupcam.bytepix * 8;
toupcam.lastcapno = toupcam.imseqno;
pthread_mutex_unlock(&toupcam.mutex);
//DBG("UNLOCK");
@@ -474,7 +475,7 @@ static int camsett(float t){
if(Toupcam_put_Option(toupcam.hcam, TOUPCAM_OPTION_TEC, onoff) < 0) return FALSE;
if(!onoff) return TRUE; // just turn off TEC if user wants >= 20degC
}
short T = (short) t * 10.f;
short T = (short) (t * 10.f);
DBG("Try to set T=%g", t);
if(Toupcam_put_Temperature(toupcam.hcam, T) < 0) return FALSE;
DBG("OK");

View File

@@ -86,6 +86,7 @@ static int campoll(cc_capture_status *st, float *remain){
if(!st) return FALSE;
ASI_EXPOSURE_STATUS s;
if(ASI_SUCCESS != ASIGetExpStatus(caminfo.CameraID, &s)){
*st = CAPTURE_ABORTED;
DBG("Can't get exp status");
return FALSE;
}
@@ -113,14 +114,13 @@ static int campoll(cc_capture_status *st, float *remain){
}
static int camcapt(cc_IMG *ima){
if(!ima || !ima->data) return FALSE;
if(!ima || !ima->data || !cc_fiximage(16, camera.geometry.w, camera.geometry.h, ima)) return FALSE;
unsigned char *d = (unsigned char *)ima->data;
long image_size = ima->h * ima->w * 2;
if(ASI_SUCCESS != ASIGetDataAfterExp(caminfo.CameraID, d, image_size)){
WARNX("Couldn't read exposure data\n");
return FALSE;
}
ima->bitpix = 16;
return TRUE;
}
@@ -324,6 +324,7 @@ static int camsetbin(int h, int v){
if(h > extrvalues.maxbin){
WARNX(_("Maximal binning value is %d"), extrvalues.maxbin);
}
// TODO: fix real binning
if(zwo_setfloat(1., ASI_HARDWARE_BIN)){
curbin = h;
return TRUE;
@@ -350,6 +351,8 @@ static int camsetgeom(cc_frameformat *f){ // w,h, xoff, yoff
DBG(_("Can't get geometry"));
return FALSE;
}
f->w *= curbin;
f->h *= curbin;
DBG("curformat: w=%d, h=%d, bin=%d", f->w, f->h, curbin);
DBG("w=%d, h=%d, bin=%d", f->w, f->h, curbin);
if(ASI_SUCCESS != ASISetStartPos(caminfo.CameraID, f->xoff/curbin, f->yoff/curbin)){
@@ -360,8 +363,12 @@ static int camsetgeom(cc_frameformat *f){ // w,h, xoff, yoff
DBG("Can't get start pos");
return FALSE;
}
f->xoff *= curbin;
f->yoff *= curbin;
DBG("curstartpos: x=%d, y=%d", f->xoff, f->yoff);
camera.geometry = *f;
//camera.geometry.w *= curbin; // unbinned geometry
//camera.geometry.h *= curbin;
return TRUE;
}

View File

@@ -88,7 +88,7 @@ int cc_lock_shm(int isserver){
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 return TRUE;
}else{
DBG("Image semaphore is locked too long by other side");
}
@@ -144,49 +144,63 @@ void cc_remove_sem(){
/**
* @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
* @param node - UNIX-socket path or server's name / IP
* @param port - server's port
* @param isnet - 0 for UNIX-socket, 1 for INET
* @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;
int cc_open_socket(int isserver, char *node, char *port, int isnet){
DBG("isserver=%d, node=%s, isnet=%d", isserver, node, isnet);
//DBG("path/port: %s", path);
int sock = -1;
struct addrinfo hints = {0}, *res;
struct sockaddr_un unaddr = {0};
if(isnet){
//DBG("Network socket");
if(!port){
WARNX(_("Not pointed port to open"));
return -1;
}
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){
if(!isserver){
if(!node){
WARNX(_("Server's node not pointed"));
return -1;
}
}else node = NULL;
if(getaddrinfo(node, port, &hints, &res) != 0){
WARN("getaddrinfo");
return -1;
}
}else{
DBG("UNIX socket");
char apath[128];
int len = sizeof(sa_family_t);
if(*path == 0){
char apath[UNIX_SOCK_PATH_MAX];
size_t len = offsetof(struct sockaddr_un, sun_path);
// check for anonymous socket
if(*node == 0 || *node == '@'){
DBG("convert name");
apath[0] = 0;
strncpy(apath+1, path+1, 126);
len += strlen(path+1);
}else if(strncmp("\\0", path, 2) == 0){
strncpy(apath+1, node + 1, UNIX_SOCK_PATH_MAX-2);
len += 1 + strlen(node + 1); // +NUL-prefix
}else if(strncmp("\\0", node, 2) == 0){
DBG("convert name");
apath[0] = 0;
strncpy(apath+1, path+2, 126);
len += strlen(path+2);
}else strcpy(apath, path);
strncpy(apath+1, node + 2, UNIX_SOCK_PATH_MAX-2);
len += 1 + strlen(node + 2);
}else{
strncpy(apath, node, UNIX_SOCK_PATH_MAX);
len += strlen(node);
}
if(len > UNIX_SOCK_PATH_MAX) len = UNIX_SOCK_PATH_MAX;
//unlink(apath);
unaddr.sun_family = AF_UNIX;
hints.ai_addr = (struct sockaddr*) &unaddr;
hints.ai_addrlen = sizeof(unaddr);
hints.ai_addrlen = len;
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;
hints.ai_socktype = SOCK_STREAM;
//hints.ai_socktype = SOCK_SEQPACKET;
res = &hints;
}
for(struct addrinfo *p = res; p; p = p->ai_next){
@@ -267,14 +281,16 @@ int cc_sendmessage(int fd, const char *msg, int l){
static char *tmpbuf = NULL;
static int buflen = 0;
if(l + 1 > buflen){
buflen = 1024 * (1 + l/1024);
char *newbuf = realloc(tmpbuf, buflen);
int newlen = 1024 * (1 + l/1024);
char *newbuf = realloc(tmpbuf, newlen);
if(!newbuf){
WARN("realloc()");
LOGERR("realloc()");
pthread_mutex_unlock(&mutex);
return FALSE;
}
tmpbuf = newbuf;
buflen = newlen;
}
DBG("send to fd %d:\n%s[%d]", fd, msg, l);
memcpy(tmpbuf, msg, l);
@@ -337,6 +353,7 @@ cc_hresult cc_str2hresult(const char *str){
* @return `val`
*/
char *cc_get_keyval(char **keyval){
if(!keyval || !*keyval || !**keyval) return NULL;
DBG("Got string %s", *keyval);
// remove starting spaces in key
while(isspace(**keyval)) ++(*keyval);
@@ -345,9 +362,11 @@ char *cc_get_keyval(char **keyval){
*val++ = 0;
while(isspace(*val)) ++val;
}
DBG("val = %s (%zd bytes)", val, (val)?strlen(val):0);
DBG("val = %s (%zd bytes)", val, (val) ? strlen(val) : 0);
size_t len = strlen(*keyval);
if(len < 1) return NULL;
// remove trailing spaces in key
char *e = *keyval + strlen(*keyval) - 1; // last key symbol
char *e = *keyval + len - 1; // last key symbol
while(isspace(*e) && e > *keyval) --e;
e[1] = 0;
// now we have key (`str`) and val (or NULL)
@@ -393,7 +412,7 @@ cc_IMG *cc_getshm(key_t key, size_t imsize){
}
}
flags = (imsize) ? 0 : SHM_RDONLY; // client opens memory in readonly mode
cc_IMG *ptr = shmat(shmid, NULL, 0);
cc_IMG *ptr = shmat(shmid, NULL, flags);
if(ptr == (void*)-1){
if(imsize) WARN(_("Can't attach SHM segment %d"), key);
return NULL;
@@ -492,6 +511,7 @@ cc_strbuff *cc_strbufnew(size_t bufsize, size_t stringsize){
b->buf = MALLOC(char, bufsize);
b->string = MALLOC(char, stringsize + 1); // for terminated zero
b->strlen = stringsize;
pthread_mutex_init(&b->mutex, NULL);
return b;
}
void cc_strbufdel(cc_strbuff **buf){
@@ -505,6 +525,7 @@ cc_charbuff *cc_charbufnew(){
cc_charbuff *b = MALLOC(cc_charbuff, 1);
b->bufsize = BUFSIZ;
b->buf = MALLOC(char, BUFSIZ);
pthread_mutex_init(&b->mutex, NULL);
return b;
}
// set buflen to 0
@@ -535,9 +556,12 @@ 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);
size_t newsize = b->bufsize + BUFSIZ * newblks;
DBG("Realloc charbuf to %zd", newsize);
char *newbuf = realloc(b->buf, newsize);
if(!newbuf) return FALSE;
b->buf = newbuf;
b->bufsize = newsize;
return TRUE;
}
void cc_charbufdel(cc_charbuff **buf){
@@ -778,6 +802,7 @@ int cc_addrecord(fitsfile *fp, char *rec){
size_t l = eq - rec;
if(l > FLEN_KEYWORD-1) l = FLEN_KEYWORD-1;
memcpy(key, rec, l); key[l] = 0;
while(l > 0 && isspace((unsigned char)key[l-1])) key[--l] = 0;
fits_update_card(fp, key, rec, &status);
}else fits_write_record(fp, rec, &status);
if(status) fits_report_error(stderr, status);
@@ -785,18 +810,19 @@ int cc_addrecord(fitsfile *fp, char *rec){
}
// 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 *cc_nextkw(char *buf, char record[FLEN_CARD], int newlines, ptrdiff_t rest){
char *nextline = NULL;
int l = FLEN_CARD;
int l = FLEN_CARD > (int)rest ? (int)rest : 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);
}else nextline = buf + (l - 1);
strncpy(record, buf, l);
if(l < FLEN_CARD) record[l] = 0;
else record[FLEN_CARD-1] = 0;
return nextline;
}
@@ -817,26 +843,25 @@ int cc_kwfromfile(fitsfile *fp, char *filename){
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
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;
data = cc_nextkw(data, rec, newlines, eodata - data);
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);
}while(data && data < eodata && *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;
static int print_val(cc_partype_t t, void *val, char *buf, size_t bufl){
int l = 0;
switch(t){
case CC_PAR_INT:
l = snprintf(buf, bufl, "%d", *(int*)val);
@@ -872,14 +897,14 @@ cc_hresult cc_plugin_customcmd(const char *str, cc_parhandler_t *handlers, cc_ch
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)
#define ADDL(...) do{if(ans){int l = snprintf(bptr, L, __VA_ARGS__); bptr += l; L -= l; if(L <= 0){buf[511] = 0; L = 0; bptr = &buf[511];}}}while(0)
#define PRINTVAL(v) do{if(ans){int l = print_val(phptr->type, phptr->v, bptr, L); bptr += l; L -= l; if(L <= 0){buf[511] = 0; L = 0; bptr = &buf[511];}}}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(result == CC_RESULT_OK && 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{ \
@@ -924,8 +949,8 @@ cc_hresult cc_plugin_customcmd(const char *str, cc_parhandler_t *handlers, cc_ch
cc_charbufaddline(ans, "Custom plugin commands:\n");
phptr = handlers;
while(phptr->cmd){
char *bptr = buf; size_t L = 511;
ADDL("\t%s", phptr->cmd);
char *bptr = buf; int L = 511;
ADDL(" %s", phptr->cmd);
if(phptr->type != CC_PAR_NONE){
ADDL(" = (");
switch(phptr->type){
@@ -956,7 +981,7 @@ cc_hresult cc_plugin_customcmd(const char *str, cc_parhandler_t *handlers, cc_ch
}
}
ADDL(" - ");
ADDL("%s\n", phptr->helpstring);
ADDL("%s", phptr->helpstring);
cc_charbufaddline(ans, buf);
++phptr;
}
@@ -981,9 +1006,9 @@ cc_IMG *cc_newimage(uint8_t bitpix, int w, int h){
cc_IMG *newima = calloc(1, sizeof(cc_IMG));
if(!newima){
WARN("calloc()");
return FALSE;
return NULL;
}
int N = bitpix / 8;
int N = (bitpix + 7) / 8;
if(N < 1 || N > 2){
DBG("Error: %d bytes per pixel", N);
free(newima);
@@ -996,7 +1021,9 @@ cc_IMG *cc_newimage(uint8_t bitpix, int w, int h){
free(newima);
return NULL;
}
newima->bitpix = bitpix;
newima->datasize = newima->bytelen = ds;
DBG("Allocated image %d/%d (%zd bytes)", w, h, ds);
newima->w = w;
newima->h = h;
newima->MAGICK = CC_SHM_MAGIC;
@@ -1005,6 +1032,31 @@ cc_IMG *cc_newimage(uint8_t bitpix, int w, int h){
return newima;
}
/**
* @brief cc_fiximage - fix data size of target image (realloc if need)
* @param bitpix - 8/12/16
* @param w - target width
* @param h - target height
* @param i - image
* @return FALSE if failed
*/
int cc_fiximage(uint8_t bitpix, int w, int h, cc_IMG *i){
int N = (bitpix + 7) / 8;
if(N < 1 || N > 2) return FALSE;
size_t total = N * w * h;
if(i->datasize < total){
void *buf = realloc(i->data, total);
if(!buf) return FALSE;
i->data = buf;
i->datasize = total;
}
i->bitpix = bitpix;
i->bytelen = total;
i->w = w;
i->h = h;
return TRUE;
}
void cc_freeimage(cc_IMG **i){
if(!i || !*i) return;
cc_IMG *ptr = *i;
@@ -1032,8 +1084,9 @@ int cc_copyimage(cc_IMG *dest, cc_IMG *src, int isshm){
return FALSE;
}
DBG("Lock");
if(isshm) cc_lock_shm(FALSE);
else pthread_mutex_lock(&src->mutex);
if(isshm){
if(!cc_lock_shm(FALSE)) return FALSE;
}else pthread_mutex_lock(&src->mutex);
pthread_mutex_lock(&dest->mutex);
dest->MAGICK = CC_SHM_MAGIC;
if(!dest->data || dest->datasize < src->bytelen){

View File

@@ -21,12 +21,16 @@
#include <fitsio.h> // FLEN_CARD
#include <pthread.h>
#include <semaphore.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h> // for size_t
// max strings in header
#define FITS_HEADER_STRINGS_MAX (1000)
// local command socket name
#define UNIX_SOCK_NAME "@ccd_capture"
// magic to mark our SHM
#define CC_SHM_MAGIC (0xdeadbeef)
@@ -54,12 +58,12 @@ typedef struct{
typedef struct { // __attribute__((packed))
uint32_t MAGICK; // magick (DEADBEEF) - to mark our shm
pthread_mutex_t mutex; // mutex for working with image data
size_t datasize; // size of `data` buffer
uint8_t start_of_copyable_data; // service field - start of copyable data
double timestamp; // timestamp of image taken
int w, h; // image size
int gotstat; // stat counted
size_t bytelen; // size of image in bytes
size_t datasize; // size of `data` buffer
size_t imnumber; // counter of images captured from server's start
uint8_t bitpix; // bits per pixel (8 or 16)
uint16_t max, min; // min/max values
@@ -347,6 +351,7 @@ cc_strbuff *cc_strbufnew(size_t size, size_t stringsize);
void cc_strbufdel(cc_strbuff **buf);
cc_IMG *cc_newimage(uint8_t bitpix, int w, int h);
int cc_fiximage(uint8_t bitpix, int w, int h, cc_IMG *i);
int cc_copyimage(cc_IMG *dest, cc_IMG *src, int isshm);
void cc_freeimage(cc_IMG **i);
@@ -361,7 +366,7 @@ int cc_getNbytes(cc_IMG *image);
int cc_read2buf(int fd, cc_strbuff *buf);
int cc_refreshbuf(int fd, cc_strbuff *buf);
size_t cc_getline(cc_strbuff *b);
int cc_open_socket(int isserver, char *path, int isnet);
int cc_open_socket(int isserver, char *path, char *port, int isnet);
int cc_senddata(int fd, void *data, size_t l);
int cc_sendmessage(int fd, const char *msg, int l);
int cc_sendstrmessage(int fd, const char *msg);
@@ -373,7 +378,7 @@ cc_hresult cc_setfloat(int fd, cc_strbuff *cbuf, const char *cmd, float val);
cc_hresult cc_getfloat(int fd, cc_strbuff *cbuf, const char *cmd, float *val);
int cc_addrecord(fitsfile *fp, char *rec);
char *cc_nextkw(char *buf, char record[FLEN_CARD], int newlines);
char *cc_nextkw(char *buf, char record[FLEN_CARD], int newlines, ptrdiff_t rest);
int cc_kwfromfile(fitsfile *fp, char *filename);
//int cc_charbuf2kw(cc_charbuff *b, fitsfile *f);

View File

@@ -65,8 +65,9 @@ static size_t curtime(char *s_time){ // current date/time
// check if I can create file prefix_XXXX.fits
static int check_filenameprefix(char *buff, int buflen){
for(int num = 1; num < 1000000; num++){
if(snprintf(buff, buflen-1, "%s_%06d.fits", GP->outfileprefix, num) < 1)
return FALSE;
int copied = snprintf(buff, buflen-1, "%s_%06d.fits", GP->outfileprefix, num);
if(copied < 1) return FALSE;
if(copied >= buflen) buff[buflen-1] = 0;
struct stat filestat;
if(stat(buff, &filestat)) // no such file or can't stat()
return TRUE;
@@ -117,7 +118,7 @@ int saveFITS(cc_IMG *img, char **outp){
struct tm *tm_time;
double dsavetime = sl_dtime();
time_t savetime = time(NULL);
fitsfile *fp;
fitsfile *fp = NULL;
fitserror = 0;
TRYFITS(fits_create_file, &fp, fnam);
if(fitserror) goto cloerr;
@@ -253,7 +254,7 @@ int saveFITS(cc_IMG *img, char **outp){
else TRYFITS(fits_write_img, fp, TUSHORT, 1, width * height, img->data);
cloerr:
TRYFITS(fits_close_file, fp);
if(fp) TRYFITS(fits_close_file, fp);
pthread_mutex_unlock(&img->mutex);
if(fitserror == 0){
LOGMSG("Save file '%s'", fnam);
@@ -528,7 +529,7 @@ void wheels(){
}
static cc_capture_status capt(){
cc_capture_status cs;
cc_capture_status cs = CAPTURE_NO;
float tremain, tmpf;
if(!camera || !camera->pollcapture){
WARNX(_("Camera plugin have no capture polling funtion."));
@@ -663,11 +664,11 @@ int prepare_ccds(){
verbose(VERBOSE_SECONDARY, _("Current settings: %d bits per pixel"), u8);
float tmpf;
if(camera->getbrightness && camera->getbrightness(&tmpf))
verbose(VERBOSE_SECONDARY, _("Current brightness: %g"), tmpf);
verbose(VERBOSE_SECONDARY, _("Current brightness: %f"), tmpf);
if(camera->getgain && camera->getgain(&tmpf))
verbose(VERBOSE_SECONDARY, _("Current gain: %g"), &tmpf);
verbose(VERBOSE_SECONDARY, _("Current gain: %f"), tmpf);
if(camera->getmaxgain && camera->getmaxgain(&tmpf))
verbose(VERBOSE_SECONDARY, _("Maximal gain: %g"), tmpf);
verbose(VERBOSE_SECONDARY, _("Maximal gain: %f"), tmpf);
if(!isnan(GP->temperature)){
if(!camera->setT)WARNX(_("Camera plugin have no temperature setter"));
else{if(!camera->setT((float)GP->temperature)) WARNX(_("Can't set T to %g degC"), GP->temperature);
@@ -747,7 +748,7 @@ int prepare_ccds(){
if(!camera->setfastspeed || !camera->setfastspeed(GP->fast))
WARNX(_("Can't set readout speed"));
else verbose(VERBOSE_PRIMARY, _("Readout mode: %s"), GP->fast ? "fast" : "normal");
if(!GP->outfile) verbose(VERBOSE_PRIMARY, _("Only show statistics"));
if(!GP->outfile && !GP->outfileprefix) verbose(VERBOSE_PRIMARY, _("Only show statistics"));
// GET binning should be AFTER setgeometry!
if(!camera->getbin || !camera->getbin(&GP->hbin, &GP->vbin))
WARNX(_("Can't get current binning"));
@@ -923,15 +924,16 @@ void framerate(){
static volatile int exitgrab = FALSE;
static volatile size_t lastgrabno = 0;
static pthread_t grabthread = 0;
static void *grabnext(void *arg){
FNAME();
if(!arg) return NULL;
cc_IMG *ima = (cc_IMG*)arg;
do{
if(exitgrab) return NULL;
if(exitgrab) break;
TIMESTAMP("Start next exp");
TIMEINIT();
if(!camera) return NULL;
if(!camera) break;
if(!camera->startexposition) ERRX(_("Camera plugin have no function `start exposition`"));
if(!camera->startexposition()){
ERRX(_("Can't start exposition"));
@@ -941,9 +943,9 @@ static void *grabnext(void *arg){
while(camera->pollcapture && camera->pollcapture(&cs, NULL)){
if(cs != CAPTURE_PROCESS) break;
usleep(10000);
if(!camera) return NULL;
if(!camera) break;
}
if(cs != CAPTURE_READY){ WARNX(_("Some error when capture")); return NULL;}
if(cs != CAPTURE_READY){ WARNX(_("Some error when capture")); break;}
TIMESTAMP("get");
if(!camera->capture) ERRX(_("Camera plugin have no function `capture`"));
if(!camera->capture(ima)){ WARNX(_("Can't grab image")); continue; }
@@ -951,6 +953,7 @@ static void *grabnext(void *arg){
//calculate_stat(ima);
TIMESTAMP("OK");
}while(1);
grabthread = 0;
return NULL;
}
@@ -962,7 +965,6 @@ static void *grabnext(void *arg){
int ccdcaptured(cc_IMG *imgptr){
if(!imgptr) return FALSE;
//TIMESTAMP("ccdcaptured() start");
static pthread_t grabthread = 0;
if(imgptr == (void*)-1){ // kill `grabnext`
DBG("Wait for grabbing thread ends");
if(grabthread){
@@ -1003,20 +1005,37 @@ int ccdcaptured(cc_IMG *imgptr){
* @return 0 if OK
*/
int start_socket(int isserver){
char *path = NULL;
int isnet = 0;
if(GP->path) path = GP->path;
else if(GP->port){ path = GP->port; isnet = 1; }
else ERRX(_("Point network port or UNIX-socket path"));
int sock = cc_open_socket(isserver, path, isnet), imsock = -1;
int locsock = -1, sock = -1, imsock = -1;
if(isserver){
// open local UNIX socket
locsock = cc_open_socket(isserver, UNIX_SOCK_NAME, NULL, FALSE);
if(locsock < 0){
LOGERR("Can't open command UNIX socket");
ERRX(_("start_socket(): can't open command UNIX socket"));
}
if(GP->imageport){
imsock = cc_open_socket(isserver, NULL, GP->imageport, TRUE);
if(imsock < 0){
LOGERR("Can't open image INET socket");
ERRX(_("start_socket(): can't open image INET socket"));
}
}
}
// if user pointed, open network sockets
if(GP->port){
sock = cc_open_socket(isserver, isserver ? NULL : GP->host, GP->port, TRUE);
if(sock < 0){
LOGERR("Can't open socket");
ERRX(_("start_socket(): can't open socket"));
LOGERR("Can't open command INET socket");
ERRX(_("start_socket(): can't open command INET socket"));
}
}else if(!isserver){ // default: open UNIX socket for client
sock = cc_open_socket(FALSE, UNIX_SOCK_NAME, NULL, FALSE);
if(sock < 0){
ERRX(_("start_socket(): can't open command UNIX socket"));
}
}
if(isserver){
imsock = cc_open_socket(TRUE, GP->imageport, 2); // image socket should be networked
DBG("imsock=%d, image port=%s", imsock, GP->imageport);
server(sock, imsock);
server(locsock, sock, imsock);
}else{
#ifdef IMAGEVIEW
if(GP->showimage){

100
client.c
View File

@@ -22,7 +22,6 @@
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <sys/socket.h>
#include <usefull_macros.h>
@@ -132,7 +131,9 @@ static int getans(int sock, const char *msg){
cc_hresult res = CC_RESULT_FAIL;
char buf[256];
while(sl_dtime() - t0 < tmout){
if(1 == sl_canread(sock)){
int R = sl_canread(sock);
if(R < 0) break;
if(1 == R){
ssize_t got = read(sock, buf, 255);
if(got > 0){
DBG("Got %zd bytes (%s)", got, buf);
@@ -198,7 +199,7 @@ static void send_headers(int sock){
// common information
if(GP->listdevices) SENDCMDW(CC_CMD_CAMLIST);
if(GP->camdevno > -1) SENDMSGW(CC_CMD_CAMDEVNO, "=%d", GP->camdevno);
if(GP->info){
if(GP->verbose > VERBOSE_PRIMARY){
SENDCMDW(CC_CMD_HBIN);
SENDCMDW(CC_CMD_VBIN);
SENDCMDW(CC_CMD_CAMTEMPER);
@@ -208,7 +209,7 @@ static void send_headers(int sock){
// focuser
if(GP->listdevices) SENDMSG(CC_CMD_FOCLIST);
if(GP->focdevno > -1) SENDMSG(CC_CMD_FDEVNO "=%d", GP->focdevno);
if(GP->info){
if(GP->verbose > VERBOSE_PRIMARY){
SENDCMDW(CC_CMD_FGOTO);
SENDCMDW(CC_CMD_FMINPOS);
SENDCMDW(CC_CMD_FMAXPOS);
@@ -220,7 +221,7 @@ static void send_headers(int sock){
// wheel
if(GP->listdevices) SENDCMDW(CC_CMD_WLIST);
if(GP->whldevno > -1) SENDMSGW(CC_CMD_WDEVNO, "=%d", GP->whldevno);
if(GP->info){
if(GP->verbose > VERBOSE_PRIMARY){
SENDCMDW(CC_CMD_WPOS);
SENDCMDW(CC_CMD_WMAXPOS);
SENDCMDW(CC_CMD_WTEMP);
@@ -272,9 +273,13 @@ static void send_headers(int sock){
*/
static int readNbytes(int fd, size_t N, uint8_t *buf){
size_t got = 0, need = N;
double t0 = sl_dtime();
while(sl_dtime() - t0 < CC_CLIENT_TIMEOUT /*&& sl_canread(fd)*/ && need){
DBG("Try to read %zd bytes", need);
double t0 = sl_dtime();
while(sl_dtime() - t0 < CC_CLIENT_TIMEOUT && need){
if(!sl_canread(fd)){
usleep(1000);
continue;
}
ssize_t rd = read(fd, buf + got, need);
DBG("readNbytes() got %zd; errno=%d", rd, errno);
if(rd == 0) return FALSE; // connection closed
@@ -289,7 +294,8 @@ static int readNbytes(int fd, size_t N, uint8_t *buf){
return TRUE;
}
static int refresh_shm(){
static int refresh_shm(int depthctr){
if(depthctr > 5) return FALSE;
if(!shmima){
shmima = cc_getshm(GP->shmkey, 0); // try to init client shm
if(shmima){
@@ -305,14 +311,14 @@ static int refresh_shm(){
shmdt(shmima);
shmima = NULL;
// refresh connection
return refresh_shm();
return refresh_shm(++depthctr);
}
struct shmid_ds buf;
if(shmctl(shmid, IPC_STAT, &buf) == 0){
if(buf.shm_perm.mode & SHM_DEST){ // marked for deletion
shmdt(shmima);
shmima = NULL;
return refresh_shm();
return refresh_shm(++depthctr);
}
// valid segment
return TRUE;
@@ -335,10 +341,10 @@ static int lockshm(){
return locked;
}
static int getshmimage(int *shmlocked){
if(!shmlocked || !shmima) return FALSE;
if(!refresh_shm()) return FALSE;
if(!*shmlocked && !(*shmlocked = lockshm())) return FALSE;
static int getshmimage(/*int *shmlocked*/){
if(/*!shmlocked ||*/ !shmima) return FALSE;
if(!refresh_shm(0)) return FALSE;
//if(!*shmlocked && !(*shmlocked = lockshm())) return FALSE;
DBG("Server's imno: %zd, bytelen: %zd", shmima->imnumber, shmima->bytelen);
int ret = cc_copyimage(locima, shmima, TRUE);
TIMESTAMP("Got by shared memory");
@@ -348,7 +354,7 @@ static int getshmimage(int *shmlocked){
static int getsocksizes(int *imsock){
if(!imsock || *imsock > -1) return FALSE;
DBG("Open socket @ %s", GP->imageport);
*imsock = cc_open_socket(FALSE, GP->imageport, TRUE);
*imsock = cc_open_socket(FALSE, GP->host, GP->imageport, TRUE);
if(*imsock < 0){
WARNX(_("Can't open image transport socket"));
return FALSE;
@@ -361,6 +367,7 @@ static int getsocksizes(int *imsock){
}
if(ima.MAGICK != CC_SHM_MAGIC || ima.bytelen < 1) return FALSE;
// now copy fields
pthread_mutex_lock(&locima->mutex);
size_t oldsz = locima->datasize;
DBG("Copy %zd bytes of fields", offsetof(cc_IMG, end_of_copyable_data) - offsetof(cc_IMG, start_of_copyable_data));
uint8_t *tagaddr = (uint8_t*)locima + offsetof(cc_IMG, start_of_copyable_data);
@@ -370,6 +377,7 @@ static int getsocksizes(int *imsock){
locima->datasize = oldsz; // restore size
DBG("image number: %zd, timestamp: %.3f; w/h: %d/%d",
locima->imnumber, locima->timestamp, locima->w, locima->h);
pthread_mutex_unlock(&locima->mutex);
return TRUE;
}
@@ -378,6 +386,7 @@ static int getsockimage(int *imsock){
pthread_mutex_lock(&locima->mutex);
if(locima->datasize < locima->bytelen){
size_t newsz = 1024 * (1 + locima->bytelen / 1024);
WARNX("Realloc from %zd to %zd", locima->datasize, newsz);
void *nxt = realloc(locima->data, newsz);
if(!nxt){
LOGERR("realloc() failed");
@@ -386,6 +395,7 @@ static int getsockimage(int *imsock){
return FALSE;
}
locima->data = nxt;
locima->datasize = newsz;
}
int ok = readNbytes(*imsock, locima->bytelen, locima->data);
pthread_mutex_unlock(&locima->mutex);
@@ -399,12 +409,11 @@ static int getsockimage(int *imsock){
/**
* @brief getimage - read image from shared memory or socket
* @param askheader == TRUE for storing FITS-header
* @return FALSE if failed to catch image
*/
static int getimage(/*int askheader*/){
static int getimage(){
FNAME();
int imsock = -1, shmlocked = FALSE, ret = FALSE;
int imsock = -1/*, shmlocked = FALSE*/, ret = FALSE;
static double oldtimestamp = -1.;
TIMESTAMP("Get image sizes (or full image over SHM)");
if(!locima){
@@ -413,57 +422,24 @@ static int getimage(/*int askheader*/){
WARN("calloc()"); return FALSE;
}
}
ret = getshmimage(&shmlocked);
if(!ret){ // can't get by shm -> try over NET
DBG("Try to get image over network");
if(GP->imageport){
if(!getsocksizes(&imsock)) goto eofg;
TIMESTAMP("Start of data read");
ret = getsockimage(&imsock);
}else ret = getshmimage(/*&shmlocked*/);
if(!ret){
WARNX(_("Can't read image data"));
goto eofg;
}
}
DBG("timestamps new-old=%g; imno: %zd", locima->timestamp - oldtimestamp, locima->imnumber);
if(locima->timestamp != oldtimestamp){ // test if image is really new
oldtimestamp = locima->timestamp;
atomic_store(&grabno, locima->imnumber);
TIMESTAMP("Got image #%zd", locima->imnumber);
#if 0
if(askheader){ // read FITS-header for later saving
if(shmima){
if(locima->headerstrings > FITS_HEADER_STRINGS_MAX){
WARNX(_("Too many FITS headers, truncating"));
locima->headerstrings = FITS_HEADER_STRINGS_MAX;
}
size_t rsz = FLEN_CARD * locima->headerstrings;
memcpy(locima->fitsheader, shmima->fitsheader, rsz);
cc_unlock_shm();
shmlocked = FALSE;
}else{
uint8_t card[FLEN_CARD];
for(size_t i = 0; i < locima->headerstrings; ++i){
if(!readNbytes(imsock, FLEN_CARD, card)){
WARNX(_("Can't read full header, got %zd records from %zd"), i, locima->headerstrings);
break;
}
memcpy(&locima->fitsheader[i], card, FLEN_CARD);
}
close(imsock);
imsock = -1;
}
if(GP->addhdr){ // add records from client-side files
char **nxtfile = GP->addhdr;
while(*nxtfile){
cc_kwfromfile(locima, *(nxtfile++));
}
}
}else locima->headerstrings = 0;
#endif
}else WARNX(_("Still got old image"));
eofg:
if(imsock > -1) close(imsock); // reopen in next time in case of error
if(shmlocked) cc_unlock_shm();
//if(shmlocked) cc_unlock_shm();
return ret;
}
@@ -486,7 +462,7 @@ static int curImNo(int sock){
void client(int sock){
if(sock < 0) ERRX(_("Can't run without command socket"));
if(!GP->forceimsock) refresh_shm(); // init shm buffer if user don't ask to force workign through image socket
if(!GP->imageport) refresh_shm(0); // init shm buffer if user don't ask to work through INET sockets
if(GP->restart){
SENDCMDW(CC_CMD_RESTART);
return;
@@ -546,7 +522,7 @@ void client(int sock){
if(lastImNo != cur){
lastImNo = cur;
verbose(VERBOSE_SECONDARY, _("Frame ready, try to grab"));
if(!getimage(/*TRUE*/)){
if(!getimage()){
WARNX(_("Can't get next image"));
}else{
if(saveFITS(locima, &lastfilename)){
@@ -588,7 +564,7 @@ void init_grab_sock(int sock){
if(sock < 0) ERRX(_("Can't run without command socket"));
controlfd = sock;
send_headers(sock);
if(!GP->forceimsock && !shmima){ // init shm buffer if user don't ask to work through image socket
if(!GP->imageport && !shmima){ // init shm buffer if user don't ask to work through image socket
shmima = cc_getshm(GP->shmkey, 0); // try to init client shm
cc_init_sem(FALSE);
}
@@ -600,8 +576,7 @@ static void *grabnext(void _U_ *arg){
if(controlfd < 0) return NULL;
int sock = controlfd;
int lastImNo = curImNo(sock);
while(1){
if(!getWin()) exit(1);
while(getWin()){
TIMESTAMP("Start of capturing cycle");
atomic_store(&expstate, CAMERA_IDLE);
TIMEINIT();
@@ -637,7 +612,7 @@ static void *grabnext(void _U_ *arg){
}
lastImNo = cur;
TIMESTAMP("Frame ready (%d from start)", cur);
getimage(/*FALSE*/);
getimage();
}
return NULL;
}
@@ -649,8 +624,7 @@ static void *waitimage(void _U_ *arg){
int sock = controlfd;
int lastImNo = curImNo(sock);
double t0 = sl_dtime();
while(1){
if(!getWin()) exit(1);
while(getWin()){
double tcur = sl_dtime();
if(tcur - t0 >= CC_WAIT_TIMEOUT){
SENDCMDW(CC_CMD_EXPSTATE); // `ping` server to know if it disconnected
@@ -664,7 +638,7 @@ static void *waitimage(void _U_ *arg){
lastImNo = cur;
TIMESTAMP("End of cycle #%d, start new", cur);
TIMEINIT();
getimage(/*FALSE*/);
getimage();
atomic_store(&expstate, CAMERA_IDLE);
DBG("Current state: %d", atomic_load(&expstate));
}

View File

@@ -66,7 +66,7 @@ sl_option_t cmdlnopts[] = {
{"cameradev", NEED_ARG, NULL, 'C', arg_string, APTR(&G.cameradev), N_("camera device plugin (e.g. devfli.so)")},
{"focuserdev", NEED_ARG,NULL, 'F', arg_string, APTR(&G.focuserdev),N_("focuser device plugin (e.g. devzwo.so)")},
{"wheeldev", NEED_ARG, NULL, 'W', arg_string, APTR(&G.wheeldev), N_("wheel device plugin (e.g. devdummy.so)")},
{"list", NO_ARGS, NULL, 'L', arg_int, APTR(&G.listdevices),N_("list connected devices")},
{"list", NO_ARGS, NULL, 'L', arg_none, APTR(&G.listdevices),N_("list connected devices")},
{"camdevno",NEED_ARG, NULL, NA, arg_int, APTR(&G.camdevno), N_("camera device number (if many: 0, 1, 2 etc)")},
{"wheeldevno",NEED_ARG, NULL, NA, arg_int, APTR(&G.whldevno), N_("filter wheel device number (if many: 0, 1, 2 etc)")},
{"focdevno",NEED_ARG, NULL, NA, arg_int, APTR(&G.focdevno), N_("focuser device number (if many: 0, 1, 2 etc)")},
@@ -75,7 +75,7 @@ sl_option_t cmdlnopts[] = {
{"verbose", NO_ARGS, NULL, 'V', arg_none, APTR(&G.verbose), N_("verbose level (-V - main messages, -VV - secondary messages, -VVV - debug)")},
{"dark", NO_ARGS, NULL, 'd', arg_int, APTR(&G.dark), N_("not open shutter, when exposing (\"dark frames\")")},
{"8bit", NO_ARGS, NULL, '8', arg_int, APTR(&G._8bit), N_("run in 8-bit mode")},
{"fast", NO_ARGS, NULL, 'f', arg_none, APTR(&G.fast), N_("fast readout mode")},
{"fast", NO_ARGS, NULL, 'f', arg_int, APTR(&G.fast), N_("fast readout mode")},
{"set-temp",NEED_ARG, NULL, 't', arg_double, APTR(&G.temperature),N_("set CCD temperature to given value (degr C)")},
{"set-fan", NEED_ARG, NULL, NA, arg_int, APTR(&G.fanspeed), N_("set fan speed (0 - off, 1 - low, 2 - high)")},
@@ -119,17 +119,16 @@ sl_option_t cmdlnopts[] = {
{"brightness",NEED_ARG, NULL, NA, arg_float, APTR(&G.brightness),N_("CMOS brightness level")},
{"logfile", NEED_ARG, NULL, NA, arg_string, APTR(&G.logfile), N_("logging file name (if run as server)")},
{"path", NEED_ARG, NULL, NA, arg_string, APTR(&G.path), N_("UNIX socket name (command socket)")},
{"port", NEED_ARG, NULL, NA, arg_string, APTR(&G.port), N_("local INET command socket port")},
{"imageport",NEED_ARG, NULL, NA, arg_string, APTR(&G.imageport), N_("INET image socket port")},
{"host", NEED_ARG, NULL, NA, arg_string, APTR(&G.host), N_("server's host name")},
{"port", NEED_ARG, NULL, NA, arg_string, APTR(&G.port), N_("INET command socket port (omit if use on same host with server)")},
{"imageport",NEED_ARG, NULL, NA, arg_string, APTR(&G.imageport), N_("INET image socket port (default: port+1)")},
{"client", NO_ARGS, &G.client,1, arg_none, NULL, N_("run as client")},
{"server", NO_ARGS, &G.server,1, arg_none, NULL, N_("run as server")},
{"viewer", NO_ARGS, &G.viewer,1, arg_none, NULL, N_("passive viewer (only get last images)")},
{"restart", NO_ARGS, &G.restart,1, arg_none, NULL, N_("restart image server")},
{"timeout", NEED_ARG, NULL, '0', arg_double, APTR(&G.anstmout), N_("network answer timeout (default: 0.1s)")},
{"info", NO_ARGS, &G.info, 1, arg_none, NULL, N_("get base information about connected hardware (also increasing text messages level to 2)")},
{"shmkey", NEED_ARG, NULL, 'k', arg_int, APTR(&G.shmkey), N_("shared memory (with image data) key (default: 7777777)")},
{"forceimsock",NO_ARGS, &G.forceimsock,1, arg_none, NULL, N_("force using image through socket transition even if can use SHM")},
{"infty", NEED_ARG, NULL, NA, arg_int, APTR(&G.infty), N_("start (!=0) or stop(==0) infinity capturing loop")},
#ifdef IMAGEVIEW

View File

@@ -45,15 +45,15 @@ typedef struct{
char *prog_id; // programm identificator
char *author; // programm author
char *logfile; // when run as server log here
char *path; // UNIX socket name
char *host; // server's host name
char *port; // local INET socket port
char *imageport; // port to send/receive images (by default == port+1)
char **addhdr; // list of files from which to add header records
char **plugincmd; // plugin commands
int restart; // restart server
int cancelexpose; // cancel exp (for Grasshopper - forbid forever)
int client; // run as client
int info; // show main information about camera etc. in client's terminal
int client; // run as client instead of standalone-mode
int server; // run as server
int viewer; // passive client (only get last images)
int listdevices; // list connected devices
int fanspeed; // fan speed: 0-2
@@ -92,8 +92,7 @@ typedef struct{
} glob_pars;
// default & global parameters
extern glob_pars const Gdefault;
// global parameters
extern glob_pars *GP;
glob_pars *parse_args(int argc, char **argv);

View File

@@ -24,8 +24,6 @@
#include <GL/glext.h>
#include <GL/freeglut.h>
extern float Z; // Z coordinate (zoom)
void keyPressed(unsigned char key, int x, int y);
void mousePressed(int key, int state, int x, int y);
void mouseMove(int x, int y);

View File

@@ -6,3 +6,6 @@ target_link_libraries(ccd_client ccdcapture usefull_macros)
add_executable(centroids centroids.c)
target_link_libraries(centroids ccdcapture usefull_macros improc m)
add_executable(centroids16 centroids16.c)
target_link_libraries(centroids16 ccdcapture usefull_macros m)

View File

@@ -28,8 +28,9 @@
#include "socket.h"
typedef struct{
char *sockname; // UNIX socket name of command socket or port of local socket
int isun; // command socket is UNIX socket instead of INET
char *node; // socket server's name/IP
char *port; // port of INET socket
char *import; // image port
int shmkey; // shared memory (with image data) key
int infty; // run in infinity loop (if not - run by requests)
int nframes; // amount of frames to take
@@ -49,8 +50,9 @@ static glob_pars G = {
* name has_arg flag val type argptr help
*/
sl_option_t cmdlnopts[] = {
{"sock", NEED_ARG, NULL, 's', arg_string, APTR(&G.sockname), "command socket name or port"},
{"isun", NO_ARGS, NULL, 'U', arg_int, APTR(&G.isun), "use UNIX socket"},
{"node", NEED_ARG, NULL, 'N', arg_string, APTR(&G.node), "server's host (if working over net) or UNIX-socket path"},
{"port", NEED_ARG, NULL, 'p', arg_string, APTR(&G.port), "command socket port"},
{"import", NEED_ARG, NULL, 'P', arg_string, APTR(&G.import), "image socket port (if not 'port+1'"},
{"shmkey", NEED_ARG, NULL, 'k', arg_int, APTR(&G.shmkey), "shared memory (with image data) key (default: 7777777)"},
{"infty", NO_ARGS, NULL, 'i', arg_int, APTR(&G.infty), "run in infinity capturing loop (else - request each frame)"},
{"nframes", NEED_ARG, NULL, 'n', arg_int, APTR(&G.nframes), "make series of N frames"},
@@ -86,10 +88,14 @@ int main(int argc, char **argv){
printf("%4d: %s\n", i, argv[i]);
}
if(G.nframes < 1) ERRX("nframes should be > 0");
if(!G.sockname) ERRX("Point socket name or port");
cc_strbuff *cbuf = cc_strbufnew(BUFSIZ, STRBUFSZ);
int sock = cc_open_socket(FALSE, G.sockname, !G.isun);
if(sock < 0) ERR("Can't open socket %s", G.sockname);
int sock = -1;
if(G.node){
sock = cc_open_socket(FALSE, G.node, G.port, TRUE);
}else{
sock = cc_open_socket(FALSE, G.node, NULL, FALSE);
}
if(sock < 0) ERR("Can't open command socket");
int shmemkey = 0;
if(CC_RESULT_OK == cc_getint(sock, cbuf, CC_CMD_SHMEMKEY, &shmemkey)){
green("Got shm key: %d\n", shmemkey);

View File

@@ -31,13 +31,13 @@
#define STRBUFSZ (256)
typedef struct{
int isun; // command socket is UNIX socket instead of INET
int shmkey; // shared memory (with image data) key
int infty; // run in infinity loop (if not - run by requests)
int nframes; // amount of frames to take
int help; // show this help
double exptime; // time of exposition in seconds
double background; // fixed bg
char *port; // net port
char *sockname; // UNIX socket name of command socket or port of local socket
char *outfile; // output file name
} glob_pars;
@@ -47,7 +47,7 @@ static glob_pars G = {
.shmkey = 7777777,
.nframes = 10,
.background = -1.,
.exptime = -1.
.exptime = -1.,
};
/*
@@ -56,8 +56,8 @@ static glob_pars G = {
*/
sl_option_t cmdlnopts[] = {
{"background",NEED_ARG, NULL, 'b', arg_double, APTR(&G.background),"fixed background level"},
{"sock", NEED_ARG, NULL, 's', arg_string, APTR(&G.sockname), "command socket name or port"},
{"isun", NO_ARGS, NULL, 'U', arg_int, APTR(&G.isun), "use UNIX socket"},
{"node", NEED_ARG, NULL, 'N', arg_string, APTR(&G.sockname), "INET command socket host or UNIX socket name"},
{"port", NEED_ARG, NULL, 'p', arg_string, APTR(&G.port), "port of INET command socket"},
{"shmkey", NEED_ARG, NULL, 'k', arg_int, APTR(&G.shmkey), "shared memory (with image data) key (default: 7777777)"},
{"infty", NO_ARGS, NULL, 'i', arg_int, APTR(&G.infty), "run in infinity capturing loop (else - request each frame)"},
{"nframes", NEED_ARG, NULL, 'n', arg_int, APTR(&G.nframes), "make series of N frames (default: 10)"},
@@ -94,25 +94,7 @@ static void calcimg(){
}else bg = 5.;
}
}
printf("bg=%g\n", bg);
/* SYNC lasts too long!
#pragma omp parallel
{
double Xsp = 0., X2sp = 0., Ysp = 0., Y2sp = 0., Isp = 0;
#pragma omp for nowait
for(int x = 0; x < W; ++x){
for(int y = 0; y < H; ++y){
double val = *d++ - bg;
if(val < DBL_EPSILON) continue;
Xsp += val * x; Ysp += val * y; X2sp += val * x * x; Y2sp += val * y * y;
Isp += val;
}
}
#pragma omp critical
{
Xs += Xsp; Ys += Ysp; X2s += X2sp; Y2s += Y2sp; Is += Isp;
}
}*/
green("Background=%g\n", bg);
for(int y = 0; y < H; ++y){
for(int x = 0; x < W; ++x){
// *d = (*d > bg) ? *d - bg : 0;
@@ -165,8 +147,13 @@ int main(int argc, char **argv){
fprintf(out, "# Time\t\tXc\tYc\tI\tsX\tsY\t\n");
}
cc_strbuff *cbuf = cc_strbufnew(BUFSIZ, STRBUFSZ);
int sock = cc_open_socket(FALSE, G.sockname, !G.isun);
if(sock < 0) ERR("Can't open socket %s", G.sockname);
int sock = -1;
if(G.port){
sock = cc_open_socket(FALSE, G.sockname, G.port, TRUE);
}else{
sock = cc_open_socket(FALSE, G.sockname, NULL, FALSE);
}
if(sock < 0) ERR("Can't open command socket");
int shmemkey = 0;
if(CC_RESULT_OK == cc_getint(sock, cbuf, CC_CMD_SHMEMKEY, &shmemkey)){
green("Got shm key: %d\n", shmemkey);

257
examples/centroids16.c Normal file
View File

@@ -0,0 +1,257 @@
/*
* This file is part of the CCD_Capture project.
* Copyright 2026 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/>.
*/
/*
* A 16-bit analog of `centroids`: get images from the server (in 16-bit mode)
* and calculate their gravity center and second moments.
*
* The background is estimated as `median + 1 sigma` over the whole frame
* (improclib does not yet provide an il_Image wrapper for 16-bit data).
* The estimate is computed once and cached; you can override it with --background.
*/
#include <float.h> // DBL_EPSILON
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <usefull_macros.h>
#include "socket.h"
#define STRBUFSZ (256)
typedef struct{
int shmkey; // shared memory (with image data) key
int infty; // run in infinity loop (if not - run by requests)
int nframes; // amount of frames to take
int help; // show this help
double nsigmas; // calculate backround as `median + nsigmas*RMS`
double exptime; // time of exposition in seconds
double background; // fixed bg (-1 -> auto: median + 1 sigma)
char *port; // net port
char *sockname; // UNIX socket name of command socket or port of local socket
char *outfile; // output file name
} glob_pars;
static glob_pars G = {
.shmkey = 7777777,
.sockname = UNIX_SOCK_NAME,
.nframes = 10,
.nsigmas = 1,
.background = -1.,
.exptime = -1.
};
/*
* Define command line options by filling structure:
* name has_arg flag val type argptr help
*/
sl_option_t cmdlnopts[] = {
{"background",NEED_ARG, NULL, 'b', arg_double, APTR(&G.background),"fixed background level (default: median + 1 sigma)"},
{"sigmas", NEED_ARG, NULL, 's', arg_double, APTR(&G.nsigmas), "amount of sigmas [-5..15] added to image median for background calculation (default: 1)"},
{"node", NEED_ARG, NULL, 'N', arg_string, APTR(&G.sockname), "INET command socket node or UNIX socket name"},
{"port", NEED_ARG, NULL, 'p', arg_string, APTR(&G.port), "port of INET command socket"},
{"shmkey", NEED_ARG, NULL, 'k', arg_int, APTR(&G.shmkey), "shared memory (with image data) key (default: 7777777)"},
{"infty", NO_ARGS, NULL, 'i', arg_int, APTR(&G.infty), "run in infinity capturing loop (else - request each frame)"},
{"nframes", NEED_ARG, NULL, 'n', arg_int, APTR(&G.nframes), "make series of N frames (default: 10)"},
{"exptime", NEED_ARG, NULL, 'x', arg_double, APTR(&G.exptime), "set exposure time to given value (seconds!)"},
{"help", NO_ARGS, NULL, 'h', arg_int, APTR(&G.help), "show this help"},
{"output", NEED_ARG, NULL, 'o', arg_string, APTR(&G.outfile), "output file with T/x/y/w"},
};
static cc_IMG *shimg = NULL, img = {0};
static FILE *out = NULL;
/**
* @brief calc_bg - estimate background as "median + 1 sigma" over the whole frame
* @param data (i) - 16-bit image data
* @param n - number of pixels
* @return background level (median + 1 sigma)
*
* Uses a full 65536-bin histogram, so both median and sigma are computed in
* O(n + 65536). The histogram lives in static storage because it is 512 KB
* and we do not want it on the stack.
*/
static double calc_bg(const uint16_t *data, size_t n){
static size_t hist[0x10000];
memset(hist, 0, sizeof(hist));
for(size_t i = 0; i < n; ++i) ++hist[data[i]];
// Find median (upper median, standard convention)
size_t half = (n + 1) / 2, cum = 0;
int median = 0;
for(int i = 0; i < 0x10000; ++i){
cum += hist[i];
if(cum >= half){ median = i; break; }
}
// Second central moment around median = robust sigma estimate
double sq = 0.;
for(int i = 0; i < 0x10000; ++i){
if(!hist[i]) continue;
double dv = (double)i - (double)median;
sq += dv * dv * (double)hist[i];
}
double sigma = sqrt(sq / (double)n);
double bg = (double)median + sigma * G.nsigmas;
printf("bg: median=%d, sigma=%.2f, bg=%.2f\n", median, sigma, bg);
return bg;
}
static void calcimg(){
int H = img.h, W = img.w, npix = 0;
double Xs = 0., X2s = 0., Ys = 0., Y2s = 0., Is = 0;
static double tstart = -1.;
if(tstart < 0.) tstart = img.timestamp;
uint16_t *d = (uint16_t*)img.data;
static double bg = -1.;
double t0 = sl_dtime(); // measure one pass time
if(G.background > 0.){
bg = G.background;
}else{
bg = calc_bg(d, (size_t)W * H);
}
printf("bg=%g\n", bg);
for(int y = 0; y < H; ++y){
for(int x = 0; x < W; ++x){
double val = (double)(*d++) - bg;
if(val < DBL_EPSILON) continue;
Xs += val * x; Ys += val * y; X2s += val * x * x; Y2s += val * y * y;
Is += val;
++npix;
}
}
DBG("Xs=%g, X2s=%g, Ys=%g, Y2s=%g, Is=%g\n", Xs, X2s, Ys, Y2s, Is);
double xc = Xs/Is, yc = Ys/Is, sX = sqrt(X2s/Is-xc*xc), sY = sqrt(Y2s/Is-yc*yc);
green("Xc = %.2f, Yc=%.2f, Xcs=%.2f, Ycs=%.2f, Isum=%.1f, Tcalcs=%gms; npix=%d\n",
xc, yc, sX, sY, Is, (sl_dtime() - t0)*1e3, npix);
if(out) fprintf(out, "%08.2f\t%.1f\t%.1f\t%.1f\t%.1f\t%.1f\n",
img.timestamp - tstart, xc, yc, Is, sX, sY);
}
static int refresh_img(){
if(!shimg) return FALSE;
static size_t imnumber = 0;
if(shimg->imnumber == imnumber) return FALSE;
double ts = sl_dtime();
if(ts - shimg->timestamp > G.exptime + 1.) return FALSE; // too old image
imnumber = shimg->imnumber;
void *optr = img.data;
memcpy(&img, shimg, sizeof(img));
img.data = realloc(optr, img.bytelen);
memcpy(img.data, (uint8_t*)shimg + sizeof(cc_IMG), img.bytelen);
if(img.bitpix < 9){
WARNX("Server sent 8-bit image, but 16-bit mode was requested; skip frame");
return FALSE;
}
calcimg();
return TRUE;
}
int main(int argc, char **argv){
sl_init();
sl_parseargs(&argc, &argv, cmdlnopts);
if(G.help) sl_showhelp(-1, cmdlnopts);
if(argc > 0){
WARNX("%d unused parameters:", argc);
for(int i = 0; i < argc; ++i)
printf("%4d: %s\n", i, argv[i]);
}
if(G.nframes < 1) ERRX("nframes should be > 0");
if(!G.sockname) ERRX("Point socket name or port");
if(G.outfile){
out = fopen(G.outfile, "w");
if(!out) ERR("Can't open %s for writing");
fprintf(out, "# Time\t\tXc\tYc\tI\tsX\tsY\t\n");
}
if(G.nsigmas < -5.) G.nsigmas = -5.;
else if(G.nsigmas > 15.) G.nsigmas = 15.;
cc_strbuff *cbuf = cc_strbufnew(BUFSIZ, STRBUFSZ);
int sock = -1;
if(G.port){
sock = cc_open_socket(FALSE, G.sockname, G.port, TRUE);
}else{
sock = cc_open_socket(FALSE, G.sockname, NULL, FALSE);
}
if(sock < 0) ERR("Can't open command socket");
int shmemkey = 0;
if(CC_RESULT_OK == cc_getint(sock, cbuf, CC_CMD_SHMEMKEY, &shmemkey)){
green("Got shm key: %d\n", shmemkey);
}else{
red("Can't read shmkey, try yours\n");
shmemkey = G.shmkey;
}
// Explicitly request 16-bit mode (lowres=0)
if(CC_RESULT_OK != cc_setint(sock, cbuf, CC_CMD_8BIT, 0)){
ERRX("Can't set 16 bit mode");
}
if(G.infty){
if(CC_RESULT_OK == cc_setint(sock, cbuf, CC_CMD_INFTY, 1)) green("ask for INFTY\n");
else red("Can't ask for INFTY\n");
}
float xt = 0.f;
if(CC_RESULT_OK == cc_getfloat(sock, cbuf, CC_CMD_EXPOSITION, &xt)){
green("Old exp time: %gs\n", xt);
}
fflush(stdout);
if(G.exptime > 0.){
if(CC_RESULT_OK == cc_setfloat(sock, cbuf, CC_CMD_EXPOSITION, G.exptime)) green("ask for exptime %gs\n", G.exptime);
else red("Can't change exptime to %gs\n", G.exptime);
}else G.exptime = xt;
shimg = cc_getshm(shmemkey, 0);
if(!shimg) ERRX("Can't get shared memory segment");
int i = 0;
time_t oldtime = time(NULL);
double waittime = ((int)G.exptime) + 5.;
do{
if(!G.infty){ // ask new image in non-infty mode
if(CC_RESULT_OK != cc_setint(sock, cbuf, CC_CMD_EXPSTATE, CAMERA_CAPTURE)){
WARNX("Can't ask new image\n");
usleep(1000);
continue;
}
usleep(1000);
}
if(cc_refreshbuf(sock, cbuf)){
while(cc_getline(cbuf)) printf("\t\tServer sent: `%s`\n", cbuf->string);
}
time_t now = time(NULL);
if(now - oldtime > waittime){
WARNX("No new images for %g seconds", waittime);
break;
}
if(!refresh_img()){
cc_setint(sock, cbuf, CC_CMD_8BIT, 0);
usleep(1000);
continue;
}
++i;
oldtime = now;
printf("Got image #%zd, size %dx%d, bitpix %d, time %.2f\n",
img.imnumber, img.w, img.h, img.bitpix, img.timestamp);
}while(i < G.nframes);
if(G.infty){
if(CC_RESULT_OK != cc_setint(sock, cbuf, CC_CMD_INFTY, 0)) red("Can't clear INFTY\n");
}
if(xt > 0.){
if(CC_RESULT_OK != cc_setfloat(sock, cbuf, CC_CMD_EXPOSITION, xt)) red("Can't return exptime to %gs\n", xt);
}
cc_strbufdel(&cbuf);
if(out) fclose(out);
close(sock);
return 0;
}

View File

@@ -133,10 +133,13 @@ static void createWindow(){
static void killwindow(){
if(!win) return;
pthread_mutex_lock(&win->mutex);
if(!win->killthread){
// say threads to die
win->killthread = 1;
}
usleep(100000);
pthread_mutex_unlock(&win->mutex);
if(win->menu){
DBG("Destroy menu");
glutDestroyMenu(win->menu);
@@ -202,6 +205,7 @@ static void RedrawWindow(){
//DBG("ini=%d, win=%s", initialized, win ? "yes" : "no");
if(!initialized || !win || win->killthread) return;
//if(pthread_mutex_trylock(&win->mutex)) return;
pthread_mutex_lock(&win->mutex);
GLfloat w = win->image->w, h = win->image->h;
glutSetWindow(win->ID);
glClearColor(0.0, 0.0, 0.5, 1.0);
@@ -212,7 +216,6 @@ static void RedrawWindow(){
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, win->Tex);
if(win->image->changed){
pthread_mutex_lock(&win->mutex);
DBG("Image changed!");
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, win->image->w, win->image->h, 0,
@@ -220,7 +223,6 @@ static void RedrawWindow(){
/* glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, win->image->w, win->image->h,
GL_RGB, GL_UNSIGNED_BYTE, win->image->rawdata);*/
win->image->changed = 0;
pthread_mutex_unlock(&win->mutex);
}
w /= 2.f; h /= 2.f;
float lr = 1., ud = -1.; // flipping coefficients (mirror image around Y by default)
@@ -235,7 +237,7 @@ static void RedrawWindow(){
glDisable(GL_TEXTURE_2D);
glFinish();
glutSwapBuffers();
//pthread_mutex_unlock(&win->mutex);
pthread_mutex_unlock(&win->mutex);
//DBG("redraw: %gs", dtime()-t0);
usleep(1000);
}
@@ -450,8 +452,12 @@ result: 0.0014689s
* @param img (i) - input image
*/
static void equalize(cc_IMG *img){
double orig_hysto[0x10000] = {0.}; // original hystogram
uint8_t eq_levls[0x10000] = {0}; // levels to convert: newpix = eq_levls[oldpix]
static double *orig_hysto = NULL; // original hystogram
static uint8_t *eq_levls = NULL; // levels to convert: newpix = eq_levls[oldpix]
if(!orig_hysto) orig_hysto = MALLOC(double, 0x10000);
else memset(orig_hysto, 0, sizeof(double)*0x10000);
if(!eq_levls) eq_levls = MALLOC(uint8_t, 0x10000);
else memset(eq_levls, 0, 0x10000);
int s = img->h * img->w;
//double t0 = dtime();
/* -- takes too long because of sync
@@ -518,7 +524,9 @@ cuts: 0.00188208s
// count image cuts as [median-sigma median+5sigma]
static void mkcuts(cc_IMG *img){
int orig_hysto[0x10000] = {0.}; // original hystogram
static double *orig_hysto = NULL; // original hystogram
if(!orig_hysto) orig_hysto = MALLOC(double, 0x10000);
else memset(orig_hysto, 0, sizeof(double)*0x10000);
int s = img->h * img->w;
double sum = 0., sum2 = 0.;
int bytes = cc_getNbytes(img);
@@ -621,25 +629,25 @@ static void change_displayed_image(cc_IMG *img){
if(!win->image || ! win->rawdata || (win->image->h != h) || (win->image->w != w)){ // realloc image & raw image to new size
//pthread_mutex_lock(&win->mutex);
DBG("\n\nRealloc rawdata");
uint8_t *raw = win->image->rawdata;
win->image->rawdata = realloc(win->image->rawdata, s*3);
if(!win->image->rawdata){
uint8_t *raw = realloc(win->image->rawdata, s*3);
if(!raw){
WARN("realloc()");
LOGERR("Realloc() error");
pthread_mutex_unlock(&win->mutex);
pthread_mutex_unlock(&img->mutex);
return;
}
win->image->rawdata = raw;
pthread_mutex_unlock(&img->mutex);
return;
}
win->image->h = h; win->image->w = w;
raw = win->rawdata;
win->rawdata = realloc(win->rawdata, s);
if(!win->rawdata){
raw = realloc(win->rawdata, s);
if(!raw){
WARN("realloc()");
LOGERR("Realloc() error");
win->rawdata = raw;
pthread_mutex_unlock(&win->mutex);
pthread_mutex_unlock(&img->mutex);
return;
}
win->rawdata = raw;
DBG("win->image changed");
//pthread_mutex_unlock(&win->mutex);
}
@@ -697,8 +705,8 @@ void closeGL(){ // killed by external signal or ctrl+c
if(!initialized) return;
DBG("KILLL");
camstop(); // cancel expositions
win->killthread = 1;
while(initialized){
if(win) win->killthread = 1;
while(initialized && win){
usleep(100000);
if(initialized) killwindow(); // kill here, if `viewer` died
}

View File

@@ -21,6 +21,7 @@
#include <GL/gl.h>
#include <math.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <string.h>
@@ -66,7 +67,7 @@ typedef struct{
uint8_t flip; // flipping settings
pthread_t thread; // identificator of thread that changes window data
pthread_mutex_t mutex;// mutex for operations with image
int killthread; // flag for killing data changing thread & also signal that there's no threads
volatile sig_atomic_t killthread; // flag for killing data changing thread & also signal that there's no threads
} windowData;
/*

Binary file not shown.

View File

@@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-07-24 12:24+0300\n"
"POT-Creation-Date: 2026-11-10 15:41+0300\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@@ -17,58 +17,66 @@ msgstr ""
"Content-Type: text/plain; charset=koi8-r\n"
"Content-Transfer-Encoding: 8bit\n"
#: main.c:55
#: main.c:54
#, c-format
msgid "Master killed with sig=%d"
msgstr ""
#. slave: cancel exposition
#: main.c:60
#, c-format
msgid "Get signal %d - exit"
msgstr ""
#: main.c:93
#: main.c:112
msgid "Can't use outfile name and prefix together"
msgstr ""
#: main.c:96 ccdfunc.c:100
#: main.c:118 ccdfunc.c:101
#, c-format
msgid "File %s exists!"
msgstr ""
#: main.c:99
#: main.c:124
#, c-format
msgid "Can't set answer timeout to %g"
msgstr ""
#: main.c:103
msgid ""
"Options `port` and `path` can't be used together! Point `port` for TCP "
"socket or `path` for UNIX."
#: main.c:129
msgid "Can't run in client and server modes simultaneously"
msgstr ""
#: main.c:108
#: main.c:138
#, c-format
msgid "Wrong image port value: %d"
msgstr ""
#: main.c:145
#, c-format
msgid "Wrong port value: %d"
msgstr ""
#: main.c:121
#: main.c:151
#, c-format
msgid "Set image port to %s\n"
msgstr ""
#: main.c:124
#: main.c:155
msgid "Can't be client and standalone in same time!"
msgstr ""
#: main.c:129
#: main.c:162
#, c-format
msgid "Log file %s @ level %d\n"
msgstr ""
#: main.c:131
msgid "Can't create log file"
#: main.c:164
#, c-format
msgid "Can't create log file %s"
msgstr ""
#. TODO - simple file viewer
#: main.c:185
msgid "Point camera device plugin to run viewer"
msgstr ""
#: cmdlnopts.c:64
@@ -277,15 +285,15 @@ msgid "logging file name (if run as server)"
msgstr ""
#: cmdlnopts.c:122
msgid "UNIX socket name (command socket)"
msgid "server's host name"
msgstr ""
#: cmdlnopts.c:123
msgid "local INET command socket port"
msgid "INET command socket port (omit if use on same host with server)"
msgstr ""
#: cmdlnopts.c:124
msgid "INET image socket port"
msgid "INET image socket port (default: port+1)"
msgstr ""
#: cmdlnopts.c:125
@@ -293,21 +301,19 @@ msgid "run as client"
msgstr ""
#: cmdlnopts.c:126
msgid "passive viewer (only get last images)"
msgid "run as server"
msgstr ""
#: cmdlnopts.c:127
msgid "restart image server"
msgid "passive viewer (only get last images)"
msgstr ""
#: cmdlnopts.c:128
msgid "network answer timeout (default: 0.1s)"
msgid "restart image server"
msgstr ""
#: cmdlnopts.c:129
msgid ""
"get base information about connected hardware (also increasing text messages "
"level to 2)"
msgid "network answer timeout (default: 0.1s)"
msgstr ""
#: cmdlnopts.c:131
@@ -315,506 +321,506 @@ msgid "shared memory (with image data) key (default: 7777777)"
msgstr ""
#: cmdlnopts.c:132
msgid "force using image through socket transition even if can use SHM"
msgstr ""
#: cmdlnopts.c:133
msgid "start (!=0) or stop(==0) infinity capturing loop"
msgstr ""
#: cmdlnopts.c:136
#: cmdlnopts.c:135
msgid "Display image in OpenGL window"
msgstr ""
#: cmdlnopts.c:160
#: cmdlnopts.c:159
#, c-format
msgid "%d unused parameters:\n"
msgstr ""
#: ccdfunc.c:89
#: ccdfunc.c:90
msgid "Image not saved: neither filename nor filename prefix pointed"
msgstr ""
#: ccdfunc.c:108
#: ccdfunc.c:109
#, c-format
msgid "Can't save file with prefix %s"
msgstr ""
#: ccdfunc.c:225
#: ccdfunc.c:226
#, c-format
msgid "Added 0 FITS records from %s"
msgstr ""
#: ccdfunc.c:226
#: ccdfunc.c:227
#, c-format
msgid "Added %d FITS records from %s"
msgstr ""
#: ccdfunc.c:260
#: ccdfunc.c:261
#, c-format
msgid "File saved as '%s'"
msgstr ""
#: ccdfunc.c:269
#: ccdfunc.c:270
#, c-format
msgid "Error saving file %s"
msgstr ""
#: ccdfunc.c:324
#: ccdfunc.c:325
#, c-format
msgid "Image stat:\n"
msgstr ""
#: ccdfunc.c:333
#: ccdfunc.c:334
msgid "Focuser device not pointed"
msgstr ""
#: ccdfunc.c:340
#: ccdfunc.c:341
msgid "No focusers found"
msgstr ""
#: ccdfunc.c:358
#: ccdfunc.c:359
#, c-format
msgid "Found %d focusers, you point number %d"
msgstr ""
#: ccdfunc.c:363
#: ccdfunc.c:364
msgid "Can't set active focuser number"
msgstr ""
#: ccdfunc.c:370
#: ccdfunc.c:371
msgid "Can't get focuser limit positions"
msgstr ""
#: ccdfunc.c:396
#: ccdfunc.c:397
#, c-format
msgid "Found focuser #%d: %s\n"
msgstr ""
#: ccdfunc.c:414
#: ccdfunc.c:415
msgid "Can't get current focuser position"
msgstr ""
#: ccdfunc.c:428
#: ccdfunc.c:429
#, c-format
msgid "Can't set position %g: out of limits [%g, %g]"
msgstr ""
#: ccdfunc.c:432
#: ccdfunc.c:433
msgid "Can't home focuser"
msgstr ""
#: ccdfunc.c:434
#: ccdfunc.c:435
#, c-format
msgid "Can't set position %g"
msgstr ""
#: ccdfunc.c:440
#: ccdfunc.c:441
msgid "Wheel device not pointed"
msgstr ""
#: ccdfunc.c:447
#: ccdfunc.c:448
msgid "No wheels found"
msgstr ""
#: ccdfunc.c:464
#: ccdfunc.c:465
#, c-format
msgid "Found %d wheels, you point number %d"
msgstr ""
#: ccdfunc.c:469
#: ccdfunc.c:470
msgid "Can't set active wheel number"
msgstr ""
#: ccdfunc.c:475
#: ccdfunc.c:476
msgid "Can't get max wheel position"
msgstr ""
#: ccdfunc.c:500
#: ccdfunc.c:501
#, c-format
msgid "Found wheel #%d: %s\n"
msgstr ""
#: ccdfunc.c:509
#: ccdfunc.c:510
#, c-format
msgid "Wheel model: %s"
msgstr ""
#: ccdfunc.c:518
#: ccdfunc.c:519
msgid "Can't get current wheel position"
msgstr ""
#: ccdfunc.c:523
#: ccdfunc.c:524
#, c-format
msgid "Wheel position should be from 0 to %d"
msgstr ""
#: ccdfunc.c:527
#: ccdfunc.c:528
#, c-format
msgid "Can't set wheel position %d"
msgstr ""
#: ccdfunc.c:534
#: ccdfunc.c:535
msgid "Camera plugin have no capture polling funtion."
msgstr ""
#: ccdfunc.c:540
#: ccdfunc.c:541
#, c-format
msgid "%.1f seconds till exposition ends"
msgstr ""
#: ccdfunc.c:555
#: ccdfunc.c:556
msgid "Camera device not pointed"
msgstr ""
#: ccdfunc.c:562 ccdfunc.c:563
#: ccdfunc.c:563 ccdfunc.c:564
msgid "No cameras found"
msgstr ""
#: ccdfunc.c:583
#: ccdfunc.c:584
msgid "Camera plugin have no model name getter"
msgstr ""
#: ccdfunc.c:588
#: ccdfunc.c:589
#, c-format
msgid "Found camera #%d: %s\n"
msgstr ""
#: ccdfunc.c:594
#: ccdfunc.c:595
#, c-format
msgid "Found %d cameras, you point number %d"
msgstr ""
#: ccdfunc.c:598
#: ccdfunc.c:599
msgid "Can't set active camera number"
msgstr ""
#: ccdfunc.c:604
#: ccdfunc.c:605
msgid "Camera plugin have no custom commands"
msgstr ""
#: ccdfunc.c:613 ccdfunc.c:616
#: ccdfunc.c:614 ccdfunc.c:617
#, c-format
msgid "Command '%s'"
msgstr ""
#: ccdfunc.c:618
#: ccdfunc.c:619
#, c-format
msgid " returns \"%s\""
msgstr ""
#: ccdfunc.c:629
#: ccdfunc.c:630
msgid "Camera plugin have no fun speed setter"
msgstr ""
#: ccdfunc.c:632
#: ccdfunc.c:633
msgid "Can't set fan speed"
msgstr ""
#: ccdfunc.c:633
#: ccdfunc.c:634
#, c-format
msgid "Set fan speed to %d"
msgstr ""
#: ccdfunc.c:638
#: ccdfunc.c:639
#, c-format
msgid "Camera model: %s"
msgstr ""
#: ccdfunc.c:639
#: ccdfunc.c:640
#, c-format
msgid "Pixel size: %g x %g"
msgstr ""
#: ccdfunc.c:645
#: ccdfunc.c:646
#, c-format
msgid "Full array: %s"
msgstr ""
#: ccdfunc.c:648
#: ccdfunc.c:649
#, c-format
msgid "Field of view: %s"
msgstr ""
#: ccdfunc.c:651
#: ccdfunc.c:652
#, c-format
msgid "Current format: %s"
msgstr ""
#: ccdfunc.c:654
#: ccdfunc.c:655
#, c-format
msgid "Maximal geometry (WxH): %dx%d"
msgstr ""
#: ccdfunc.c:655
#: ccdfunc.c:656
#, c-format
msgid "Minimal offset: %dx%d"
msgstr ""
#: ccdfunc.c:656
#: ccdfunc.c:657
#, c-format
msgid "Geometry steps: offset - %dx%d, size - %dx%d"
msgstr ""
#: ccdfunc.c:660
#: ccdfunc.c:661
#, c-format
msgid "Current binning: %d x %d"
msgstr ""
#: ccdfunc.c:663
#: ccdfunc.c:664
#, c-format
msgid "Current settings: %d bits per pixel"
msgstr ""
#: ccdfunc.c:666
#: ccdfunc.c:667
#, c-format
msgid "Current brightness: %g"
msgid "Current brightness: %f"
msgstr ""
#: ccdfunc.c:668
#: ccdfunc.c:669
#, c-format
msgid "Current gain: %g"
msgid "Current gain: %f"
msgstr ""
#: ccdfunc.c:670
#: ccdfunc.c:671
#, c-format
msgid "Maximal gain: %g"
msgstr ""
#: ccdfunc.c:672
msgid "Camera plugin have no temperature setter"
msgid "Maximal gain: %f"
msgstr ""
#: ccdfunc.c:673
msgid "Camera plugin have no temperature setter"
msgstr ""
#: ccdfunc.c:674
#, c-format
msgid "Can't set T to %g degC"
msgstr ""
#: ccdfunc.c:681
#: ccdfunc.c:682
#, c-format
msgid "Shutter command: %s\n"
msgstr ""
#: ccdfunc.c:683
#: ccdfunc.c:684
#, c-format
msgid "Can't run shutter command %s (unsupported?)"
msgstr ""
#: ccdfunc.c:686
#: ccdfunc.c:687
#, c-format
msgid "Try to configure I/O port as %d"
msgstr ""
#: ccdfunc.c:688
#: ccdfunc.c:689
msgid "Can't configure (unsupported?)"
msgstr ""
#: ccdfunc.c:694
#: ccdfunc.c:695
msgid "Can't get IOport state (unsupported?)"
msgstr ""
#: ccdfunc.c:697
#: ccdfunc.c:698
#, c-format
msgid "Try to write %d to I/O port"
msgstr ""
#: ccdfunc.c:699
#: ccdfunc.c:700
msgid "Can't set IOport"
msgstr ""
#: ccdfunc.c:706
#, c-format
msgid "Set gain to %g"
msgstr ""
#: ccdfunc.c:707
#, c-format
msgid "Can't set gain to %g"
msgid "Set gain to %g"
msgstr ""
#: ccdfunc.c:712
#: ccdfunc.c:708
#, c-format
msgid "Set brightness to %g"
msgid "Can't set gain to %g"
msgstr ""
#: ccdfunc.c:713
#, c-format
msgid "Set brightness to %g"
msgstr ""
#: ccdfunc.c:714
#, c-format
msgid "Can't set brightness to %g"
msgstr ""
#: ccdfunc.c:719 server.c:359
#: ccdfunc.c:720 server.c:357
#, c-format
msgid "Can't set binning %dx%d"
msgstr ""
#: ccdfunc.c:731 server.c:361
#: ccdfunc.c:732 server.c:359
msgid "Can't set given geometry"
msgstr ""
#: ccdfunc.c:735
#: ccdfunc.c:736
#, c-format
msgid "Can't set %d flushes"
msgstr ""
#: ccdfunc.c:738
#: ccdfunc.c:739
msgid "Camera plugin have no exposition setter"
msgstr ""
#: ccdfunc.c:740
#: ccdfunc.c:741
#, c-format
msgid "Can't set exposure time to %f seconds"
msgstr ""
#: ccdfunc.c:743
#: ccdfunc.c:744
msgid "Can't change frame type"
msgstr ""
#: ccdfunc.c:746
#: ccdfunc.c:747
msgid "Can't set bit depth"
msgstr ""
#: ccdfunc.c:748
#: ccdfunc.c:749
msgid "Can't set readout speed"
msgstr ""
#: ccdfunc.c:749
#: ccdfunc.c:750
#, c-format
msgid "Readout mode: %s"
msgstr ""
#: ccdfunc.c:750
#: ccdfunc.c:751
msgid "Only show statistics"
msgstr ""
#: ccdfunc.c:753
#: ccdfunc.c:754
msgid "Can't get current binning"
msgstr ""
#: ccdfunc.c:848
#: ccdfunc.c:849
msgid "Can't allocate image memory"
msgstr ""
#: ccdfunc.c:849
#: ccdfunc.c:850
msgid "Can't fill headers with camera data"
msgstr ""
#: ccdfunc.c:857
#: ccdfunc.c:858
#, c-format
msgid "Capture frame %d"
msgstr ""
#: ccdfunc.c:858 ccdfunc.c:935 server.c:209
#: ccdfunc.c:859 ccdfunc.c:937 server.c:205
msgid "Camera plugin have no function `start exposition`"
msgstr ""
#: ccdfunc.c:860 ccdfunc.c:937 server.c:214
#: ccdfunc.c:861 ccdfunc.c:939 server.c:209
msgid "Can't start exposition"
msgstr ""
#: ccdfunc.c:865
#: ccdfunc.c:866
msgid "Can't capture image"
msgstr ""
#: ccdfunc.c:868
#: ccdfunc.c:869
msgid "Read grabbed image"
msgstr ""
#: ccdfunc.c:870 ccdfunc.c:948 server.c:248
#: ccdfunc.c:871 ccdfunc.c:950 server.c:243
msgid "Camera plugin have no function `capture`"
msgstr ""
#: ccdfunc.c:872 ccdfunc.c:949
#: ccdfunc.c:873 ccdfunc.c:951
msgid "Can't grab image"
msgstr ""
#: ccdfunc.c:885 client.c:569
#: ccdfunc.c:886 client.c:546
#, c-format
msgid "%d seconds till pause ends\n"
msgstr ""
#. for(int i = 0; i < NFRM; ++i) printf("last[%d]=%g\n", i, lastn[i]);
#: ccdfunc.c:920
#: ccdfunc.c:921
#, c-format
msgid "Framerate=%.2f (%g seconds for exp); mean framerate=%.2f"
msgstr ""
#: ccdfunc.c:946
#: ccdfunc.c:948
msgid "Some error when capture"
msgstr ""
#: ccdfunc.c:981
#: ccdfunc.c:983
msgid "Can't create grabbing thread"
msgstr ""
#: ccdfunc.c:1010
msgid "Point network port or UNIX-socket path"
#: ccdfunc.c:1014 ccdfunc.c:1034
msgid "start_socket(): can't open command UNIX socket"
msgstr ""
#: ccdfunc.c:1014
msgid "start_socket(): can't open socket"
#: ccdfunc.c:1020
msgid "start_socket(): can't open image INET socket"
msgstr ""
#: ccdfunc.c:1023
#: ccdfunc.c:1029
msgid "start_socket(): can't open command INET socket"
msgstr ""
#: ccdfunc.c:1042
msgid "Need exposition time!"
msgstr ""
#: server.c:129
#: server.c:123
msgid "Can't unlock socket mutex"
msgstr ""
#: server.c:167
#: server.c:161
msgid "Can't allocate memory for image"
msgstr ""
#: server.c:169
#: server.c:163
msgid "Can't init camera data"
msgstr ""
#: server.c:222
#: server.c:217
msgid "Camera disconnected"
msgstr ""
#: server.c:228
#: server.c:223
msgid "Something's wrong with camera"
msgstr ""
#: server.c:276
#: server.c:272
msgid "No camera device"
msgstr ""
#: server.c:1088
#: server.c:1106
msgid "server(): need at least command socket fd"
msgstr ""
#: server.c:1089
#: server.c:1114
msgid "Server run without image transport socket"
msgstr ""
#: server.c:1120
#: server.c:1150
msgid "No devices found"
msgstr ""
#: server.c:1165
#: server.c:1213
msgid "Client wants an image, but there's no data"
msgstr ""
#: server.c:1194
#: server.c:1245
msgid "Limit of connections reached"
msgstr ""
#: server.c:1263
#: server.c:1321
#, c-format
msgid "Can't create %s"
msgstr ""
#: server.c:1299
#: server.c:1357
msgid "Can't lock mutex"
msgstr ""
#. send message and wait any answer
#. send message and wait answer starting with 'cmd'
#. send command and wait for answer on it
#: client.c:42 client.c:44 client.c:46 client.c:282
#: client.c:42 client.c:44 client.c:46 client.c:288
msgid "Server disconnected"
msgstr ""
@@ -822,99 +828,89 @@ msgstr ""
msgid "Can't allocate buffer"
msgstr ""
#: client.c:149
#: client.c:151
msgid "Server disconnected?"
msgstr ""
#: client.c:157
#: client.c:159
msgid "Got empty string"
msgstr ""
#: client.c:186
#: client.c:188
msgid "Send custom plugin commands\n"
msgstr ""
#: client.c:333
#: client.c:340
msgid "Can't lock shared memory"
msgstr ""
#: client.c:352
#: client.c:359
msgid "Can't open image transport socket"
msgstr ""
#: client.c:358
#: client.c:365
msgid "Can't read image header over socket"
msgstr ""
#: client.c:392 client.c:422
#: client.c:403 client.c:431
msgid "Can't read image data"
msgstr ""
#: client.c:435
msgid "Too many FITS headers, truncating"
msgstr ""
#: client.c:446
#, c-format
msgid "Can't read full header, got %zd records from %zd"
msgstr ""
#: client.c:462
#: client.c:439
msgid "Still got old image"
msgstr ""
#: client.c:487 client.c:587
#: client.c:464 client.c:564
msgid "Can't run without command socket"
msgstr ""
#: client.c:506
#: client.c:483
msgid "Exposing frame 1..."
msgstr ""
#: client.c:508
#: client.c:485
msgid "Wait for exposition end"
msgstr ""
#: client.c:527
#: client.c:504
msgid "Can't make exposition"
msgstr ""
#. start next capture
#. last image -> should re-expose
#: client.c:529 client.c:540 client.c:559
#: client.c:506 client.c:517 client.c:536
#, c-format
msgid "Exposing frame %d..."
msgstr ""
#: client.c:547
#: client.c:524
msgid "Frame ready, try to grab"
msgstr ""
#. TRUE
#: client.c:549
#: client.c:526
msgid "Can't get next image"
msgstr ""
#: client.c:557
#: client.c:534
msgid "Got already saved image, wait next"
msgstr ""
#: client.c:581
#: client.c:558
msgid "Server timeout"
msgstr ""
#: client.c:632
#: client.c:608
msgid "Camera in error state"
msgstr ""
#: client.c:634
#: client.c:610
#, c-format
msgid ""
"Image wasn't received, state: %d, waiting: %g, lastNo: %d, curNo: %d "
"(timeout: %g)"
msgstr ""
#: client.c:694 client.c:701
#: client.c:669 client.c:676
msgid "Can't create capturing thread"
msgstr ""
@@ -922,47 +918,47 @@ msgstr ""
msgid "Already initialized!"
msgstr ""
#: imageview.c:314
#: imageview.c:316
msgid "Can't init mutex!"
msgstr ""
#: imageview.c:427
#: imageview.c:429
#, c-format
msgid "Histogram conversion: %s"
msgstr ""
#: imageview.c:617
#: imageview.c:625
#, c-format
msgid "Missed %zd images"
msgstr ""
#: imageview.c:715
#: imageview.c:723
msgid "No image changing function defined"
msgstr ""
#: imageview.c:722
#: imageview.c:730
msgid "Can't open OpenGL window, image preview will be inaccessible"
msgstr ""
#. save image
#: imageview.c:756
#: imageview.c:764
msgid "Make screenshot"
msgstr ""
#: imageview.c:760
#: imageview.c:768
#, c-format
msgid "Set output prefix to %s"
msgstr ""
#: imageview.c:773
#: imageview.c:781
#, c-format
msgid "Equalization of histogram: %s"
msgstr ""
#: imageview.c:773
#: imageview.c:781
msgid "on"
msgstr ""
#: imageview.c:773
#: imageview.c:781
msgid "off"
msgstr ""

File diff suppressed because it is too large Load Diff

130
main.c
View File

@@ -37,7 +37,6 @@
#include "server.h"
#include "socket.h"
static int isserver = FALSE;
static pid_t childpid = 0;
// get struct size
@@ -57,21 +56,40 @@ void signals(int signo){
exit(signo);
}
// slave: cancel exposition
if(signo) WARNX(_("Get signal %d - exit"), signo);
if(!GP->client){
if(signo){
WARNX(_("Get signal %d - exit"), signo);
#ifdef IMAGEVIEW
if(!GP->server){
windowData *win = getWin();
if(win){
win->killthread = 1;
return;
}
}
#endif
}
if(GP->server){
DBG("Cancel capturing and close all");
stop_server();
stop_server(); // wait until 1s for server to stopped
}else{
#ifdef IMAGEVIEW
DBG("KILL GL");
closeGL();
#endif
exit(signo);
closewheel();
focclose();
closecam();
}
//DBG("exit(%d)", signo);
//exit(signo);
DBG("exit(%d)", signo);
exit(signo);
}
typedef enum{
SERVER_MODE,
CLIENT_MODE,
STANDALONE_MODE
} working_mode_t;
int main(int argc, char **argv){
sl_init();
#if defined GETTEXT_PACKAGE && defined LOCALEDIR
@@ -90,48 +108,62 @@ int main(int argc, char **argv){
GP->client = 1;
GP->showimage = 1;
}
if(GP->outfile && GP->outfileprefix) ERRX(_("Can't use outfile name and prefix together"));
if(GP->outfile && !GP->rewrite){
struct stat filestat;
if(0 == stat(GP->outfile, &filestat)) ERRX(_("File %s exists!"), GP->outfile);
}
if(GP->anstmout > 0.){
if(!cc_setAnsTmout(GP->anstmout)) ERRX(_("Can't set answer timeout to %g"), GP->anstmout);
}
if(GP->port){
if(GP->path){
WARNX(_("Options `port` and `path` can't be used together! Point `port` for TCP socket or `path` for UNIX."));
if(GP->outfile && GP->outfileprefix){
WARNX(_("Can't use outfile name and prefix together"));
return 1;
}
if(GP->outfile && !GP->rewrite){
struct stat filestat;
if(0 == stat(GP->outfile, &filestat)){
WARNX(_("File %s exists!"), GP->outfile);
return 1;
}
}
if(GP->anstmout > 0.){
if(!cc_setAnsTmout(GP->anstmout)){
WARNX(_("Can't set answer timeout to %g"), GP->anstmout);
return 1;
}
}
if(GP->client && GP->server){
WARNX(_("Can't run in client and server modes simultaneously"));
return 1;
}
working_mode_t mode = STANDALONE_MODE;
if(GP->client) mode = CLIENT_MODE;
else if(GP->server) mode = SERVER_MODE;
if(GP->imageport){
int port = atoi(GP->imageport);
if(port < CC_PORTN_MIN || port > CC_PORTN_MAX){
WARNX(_("Wrong image port value: %d"), port);
return 1;
}
}
if(GP->port){ // open TCP socket besides (or instead - for client) UNIX-socket
int port = atoi(GP->port);
if(port < CC_PORTN_MIN || port > CC_PORTN_MAX){
WARNX(_("Wrong port value: %d"), port);
return 1;
}
if(!GP->client) isserver = TRUE;
}
if(GP->path && !GP->client) isserver = TRUE;
/*if(!GP->path && !GP->port){ // standalone
WARNX("Point one of options: `port` or `path` for command socket");
}*/
if((isserver || GP->client) && !GP->imageport){
if(!GP->imageport){ // make default: port + 1
GP->imageport = MALLOC(char, 32);
if(!GP->port) sprintf(GP->imageport, "12345");
else snprintf(GP->imageport, 31, "%d", 1+atoi(GP->port));
snprintf(GP->imageport, 31, "%d", 1 + port);
verbose(VERBOSE_PRIMARY, _("Set image port to %s\n"), GP->imageport);
}
if(GP->client && (GP->commondev || GP->focuserdev || GP->cameradev || GP->wheeldev))
ERRX(_("Can't be client and standalone in same time!"));
}
if(mode == CLIENT_MODE && (GP->commondev || GP->focuserdev || GP->cameradev || GP->wheeldev)){
WARNX(_("Can't be client and standalone in same time!"));
return 1;
}
if(GP->logfile){
int lvl = LOGLEVEL_ERR + GP->verbose;
DBG("level = %d", lvl);
if(lvl > LOGLEVEL_ANY) lvl = LOGLEVEL_ANY;
verbose(VERBOSE_PRIMARY, _("Log file %s @ level %d\n"), GP->logfile, lvl);
OPENLOG(GP->logfile, lvl, 1);
if(!sl_globlog) WARNX(_("Can't create log file"));
if(!sl_globlog) WARN(_("Can't create log file %s"), GP->logfile);
else LOGMSG("Started");
}
if(GP->info && GP->verbose < VERBOSE_SECONDARY) // increase verbose messages level for `info`
GP->verbose = VERBOSE_SECONDARY;
signal(SIGINT, signals);
signal(SIGQUIT, signals);
signal(SIGABRT, signals);
@@ -140,20 +172,21 @@ int main(int argc, char **argv){
signal(SIGTSTP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
signal(SIGUSR1, signals); // restart server
if(!isserver){ // run in standalone or client mode
int camerainit = FALSE;
if(!GP->client){ // standalone mode
focusers(); // run focusers and wheels before showimage
if(mode == STANDALONE_MODE){
focusers();
wheels();
camerainit = prepare_ccds();
}else{ // client mode
return start_socket(isserver);
}
int camerainit = prepare_ccds();
#ifdef IMAGEVIEW
if(GP->showimage){ // activate image window in capture or simple viewer mode
imagefunc imfn = NULL;
if(GP->cameradev || GP->commondev){if(camerainit) imfn = ccdcaptured;} // capture mode
else imfn = NULL; // TODO - simple file viewer
if(camerainit) imfn = ccdcaptured; // capture mode
if(!imfn){
// TODO - simple file viewer
WARNX(_("Point camera device plugin to run viewer"));
closewheel();
focclose();
return 1;
}
return viewer(imfn);
}
#endif
@@ -161,12 +194,21 @@ int main(int argc, char **argv){
closewheel();
focclose();
return 0;
} else if(mode == CLIENT_MODE){
return start_socket(FALSE);
}
LOGMSG("Started");
// server mode
LOGMSG("Started image server");
#ifndef EBUG
unsigned int pause = 5;
while(1){
childpid = fork();
if(childpid < 0){
WARN("fork() error");
LOGERR("fork() error");
sleep(1);
continue;
}
if(childpid){ // master
double t0 = sl_dtime();
LOGMSG("Created child with pid %d", childpid);
@@ -183,6 +225,6 @@ int main(int argc, char **argv){
}
#endif
return start_socket(isserver);
return start_socket(TRUE);
}

192
server.c
View File

@@ -36,7 +36,7 @@
static int parsestring(int fd, cc_handleritem *handlers, char *str);
static atomic_int camdevno = 0, wheeldevno = 0, focdevno = 0; // current devices numbers
static _Atomic cc_camera_state camstate = CAMERA_IDLE;
static cc_camera_state camstate = CAMERA_IDLE;
#define FLAG_STARTCAPTURE (1<<0)
#define FLAG_CANCEL (1<<1)
#define FLAG_RESTARTSERVER (1<<2)
@@ -64,9 +64,9 @@ strpair allcommands[] = {
//{ CC_CMD_AUTHOR, "FITS 'AUTHOR' field" },
{ CC_CMD_BRIGHTNESS, "camera brightness" },
{ CC_CMD_CAMDEVNO, "camera device number" },
{ CC_CMD_CAMFANSPD, "fan speed of camera" },
{ CC_CMD_CAMFLAGS, "get camflags (bits: 0-start capture, 1-cancel, 2-restart server"},
{ CC_CMD_CAMLIST, "list all connected cameras" },
{ CC_CMD_CAMFANSPD, "fan speed of camera" },
{ CC_CMD_CONFIO, "camera IO configuration" },
{ CC_CMD_DARK, "don't open shutter @ exposure" },
{ CC_CMD_EXPSTATE, "get exposition state (0: cancel, 1: capturing, 2: frame ready, 3: error) "
@@ -81,23 +81,17 @@ strpair allcommands[] = {
{ CC_CMD_FTEMP, "get focuser body temperature"},
{ CC_CMD_FRAMEFORMAT, "camera frame format (X0,Y0,X1,Y1)" },
{ CC_CMD_GAIN, "camera gain" },
//{ CC_CMD_GETHEADERS, "get last file FITS headers" },
{ CC_CMD_HBIN, "horizontal binning" },
{ CC_CMD_HELP, "show this help" },
{ CC_CMD_IMHEIGHT, "last image height" },
{ CC_CMD_IMNUMBER, "grabbed image number from server start"},
{ CC_CMD_IMWIDTH, "last image width" },
{ CC_CMD_INFTY, "an infinity loop taking images until there's connected clients" },
//{ CC_CMD_INSTRUMENT, "FITS 'INSTRUME' field" },
{ CC_CMD_IO, "get/set camera IO" },
{ CC_CMD_8BIT, "run in 8 bit mode instead of 16 bit" },
{ CC_CMD_FRAMEMAX, "camera maximal available format" },
{ CC_CMD_NFLUSHES, "camera number of preflushes" },
//{ CC_CMD_OBJECT, "FITS 'OBJECT' field" },
//{ CC_CMD_OBJTYPE, "FITS 'IMAGETYP' field" },
//{ CC_CMD_OBSERVER, "FITS 'OBSERVER' field" },
{ CC_CMD_PLUGINCMD, "custom camera plugin command" },
//{ CC_CMD_PROGRAM, "FITS 'PROG-ID' field" },
{ CC_CMD_RESTART, "restart server" },
{ CC_CMD_SHMEMKEY, "get shared memory key" },
{ CC_CMD_SHUTTER, "camera shutter's operations" },
@@ -199,17 +193,18 @@ static void fixima(){
// functions for processCAM finite state machine
static inline void cameraidlestate(){ // idle - wait for capture commands
static double Tcheck = 0.;
if(camflags & FLAG_STARTCAPTURE){ // start capturing
int curflags = atomic_load(&camflags);
if(curflags & FLAG_STARTCAPTURE){ // start capturing
TIMESTAMP("Start exposition");
camflags &= ~(FLAG_STARTCAPTURE | FLAG_CANCEL);
curflags &= ~(FLAG_STARTCAPTURE | FLAG_CANCEL);
atomic_store(&camflags, curflags);
camstate = CAMERA_CAPTURE;
fixima();
if(!camera->startexposition){
LOGERR("Camera plugin have no function `start exposition`");
WARNX(_("Camera plugin have no function `start exposition`"));
camstate = CAMERA_ERROR;
}
if(!camera->startexposition()){
}else if(!camera->startexposition()){
LOGERR("Can't start exposition");
WARNX(_("Can't start exposition"));
camstate = CAMERA_ERROR;
@@ -255,13 +250,14 @@ static inline void cameracapturestate(){ // capturing - wait for exposition ends
if(!camera->capture(ima)){
LOGERR("Can't capture image");
camstate = CAMERA_ERROR;
cc_unlock_shm();
return;
}
fill_image_fields(ima);
LOGDBG("Captured new image %zdx%zd pix", ima->w, ima->h);
++ima->imnumber; // increment counter
cc_unlock_shm();
LOGDBG("cameracapturestate(): SHM UNlocked");
LOGDBG("cameracapturestate(): SHM UNlocked; image number %d", ima->imnumber);
TIMESTAMP("Captured and unlocked");
}
camstate = CAMERA_FRAMERDY;
@@ -280,7 +276,8 @@ static void* processCAM(_U_ void *d){
double T = sl_dtime();
#endif
while(isrunning){
if(camflags & FLAG_RESTARTSERVER){
int curflags = atomic_load(&camflags);
if(curflags & FLAG_RESTARTSERVER){
LOGERR("User asks to restart");
signals(1);
}
@@ -307,10 +304,11 @@ static void* processCAM(_U_ void *d){
LOGMSG("BODYTEMP=%.1f", t);
}
}
if(camflags & FLAG_CANCEL){ // cancel all expositions
if(curflags & FLAG_CANCEL){ // cancel all expositions
DBG("Cancel exposition");
LOGMSG("User canceled exposition");
camflags &= ~(FLAG_STARTCAPTURE | FLAG_CANCEL);
curflags &= ~(FLAG_STARTCAPTURE | FLAG_CANCEL);
atomic_store(&camflags, curflags);
if(camera->cancel) camera->cancel();
camstate = CAMERA_IDLE;
infty = 0; // also cancel infinity loop
@@ -368,7 +366,9 @@ static int camdevini(int n){
*************************** Service handlers **********************************
******************************************************************************/
static cc_hresult restarthandler(_U_ int fd, _U_ const char *key, _U_ const char *val){
camflags |= FLAG_RESTARTSERVER;
int curflags = atomic_load(&camflags);
curflags |= FLAG_RESTARTSERVER;
atomic_store(&camflags, curflags);
return CC_RESULT_OK;
}
@@ -390,7 +390,9 @@ static cc_hresult camlisthandler(int fd, _U_ const char *key, _U_ const char *va
if(camera->setDevNo && !camera->setDevNo(i)) continue;
camera->getModelName(modname, 255);
snprintf(buf, BUFSIZ-1, CC_CMD_CAMLIST "='%s'", modname);
if(!cc_sendstrmessage(fd, buf)) return CC_RESULT_DISCONNECTED;
if(!cc_sendstrmessage(fd, buf)){
return CC_RESULT_DISCONNECTED;
}
}
int devno = atomic_load(&camdevno);
if(devno > -1 && camera->setDevNo) camera->setDevNo(devno);
@@ -404,6 +406,7 @@ static cc_hresult camsetNhandler(_U_ int fd, _U_ const char *key, _U_ const char
return CC_RESULT_BADVAL;
}
if(!camdevini(num)) return CC_RESULT_FAIL;
atomic_store(&camdevno, num);
}
snprintf(buf, 63, CC_CMD_CAMDEVNO "=%d", atomic_load(&camdevno));
if(!cc_sendstrmessage(fd, buf)) return CC_RESULT_DISCONNECTED;
@@ -415,7 +418,7 @@ static cc_hresult exphandler(int fd, _U_ const char *key, const char *val){
if(val){
DBG("setexp to %s", val);
double v = atof(val);
if(v < DBL_EPSILON) return CC_RESULT_BADVAL;
if(v < 0.) return CC_RESULT_BADVAL;
if(!camera->setexp) return CC_RESULT_FAIL;
if(camera->setexp(v)){
GP->exptime = v;
@@ -627,8 +630,9 @@ static cc_hresult expstatehandler(int fd, _U_ const char *key, const char *val){
char buf[64];
if(val){
int n = atoi(val);
int curflags = atomic_load(&camflags);
if(n == CAMERA_IDLE){ // cancel expositions
camflags |= FLAG_CANCEL;
curflags |= FLAG_CANCEL;
}
else if(n == CAMERA_CAPTURE){ // start exposition
if(GP->exptime < 1e-9){ // need exposition time to be set
@@ -640,23 +644,25 @@ static cc_hresult expstatehandler(int fd, _U_ const char *key, const char *val){
}*/
TIMESTAMP("Get FLAG_STARTCAPTURE");
TIMEINIT();
camflags |= FLAG_STARTCAPTURE;
curflags |= FLAG_STARTCAPTURE;
}
else return CC_RESULT_BADVAL;
atomic_store(&camflags, curflags);
}
snprintf(buf, 63, CC_CMD_EXPSTATE "=%d", camstate);
if(!cc_sendstrmessage(fd, buf)) return CC_RESULT_DISCONNECTED;
return CC_RESULT_SILENCE;
}
static cc_hresult camflagshandler(int fd, _U_ const char *key, _U_ const char *val){
static cc_hresult camflagshandler(int fd, const char *key, _U_ const char *val){
char buf[64];
snprintf(buf, 63, "camflags=%d", camflags);
int curflags = atomic_load(&camflags);
snprintf(buf, 63, "%s=%d", key, curflags);
if(!cc_sendstrmessage(fd, buf)) return CC_RESULT_DISCONNECTED;
return CC_RESULT_SILENCE;
}
static cc_hresult tremainhandler(_U_ int fd, _U_ const char *key, _U_ const char *val){
static cc_hresult tremainhandler(_U_ int fd, const char *key, _U_ const char *val){
char buf[64];
snprintf(buf, 63, CC_CMD_TREMAIN "=%g", tremain);
snprintf(buf, 63, "%s=%g", key, tremain);
if(!cc_sendstrmessage(fd, buf)) return CC_RESULT_DISCONNECTED;
return CC_RESULT_SILENCE;
}
@@ -784,6 +790,7 @@ static cc_hresult wsetNhandler(int fd, _U_ const char *key, const char *val){
return CC_RESULT_BADVAL;
}
if(!setWheelNo(num, &wmaxpos)) return CC_RESULT_FAIL;
atomic_store(&wheeldevno, num);
}
snprintf(buf, 63, CC_CMD_WDEVNO "=%d", atomic_load(&wheeldevno));
if(!cc_sendstrmessage(fd, buf)) return CC_RESULT_DISCONNECTED;
@@ -856,6 +863,7 @@ static cc_hresult fsetNhandler(int fd, _U_ const char *key, const char *val){
return CC_RESULT_BADVAL;
}
if(!setFocuserNo(num, &focminpos, &focmaxpos)) return CC_RESULT_FAIL;
atomic_store(&focdevno, num);
}
snprintf(buf, 63, CC_CMD_FDEVNO "=%d", atomic_load(&focdevno));
if(!cc_sendstrmessage(fd, buf)) return CC_RESULT_DISCONNECTED;
@@ -913,7 +921,11 @@ static cc_hresult inftyhandler(int fd, _U_ const char *key, const char *val){
if(val){
int i = atoi(val);
infty = (i) ? 1 : 0;
if(!infty) camflags |= FLAG_CANCEL;
if(!infty){
int curflags = atomic_load(&camflags);
curflags |= FLAG_CANCEL;
atomic_store(&camflags, curflags);
}
}
snprintf(buf, 63, CC_CMD_INFTY "=%d", infty);
if(!cc_sendstrmessage(fd, buf)) return CC_RESULT_DISCONNECTED;
@@ -967,16 +979,14 @@ static cc_hresult chkcam(char *val){
return CC_RESULT_FAIL;
}
static cc_hresult chkcc(_U_ char *val){ // just check that camera connected
if(camera) return CC_RESULT_OK;
if(camera && camstate != CAMERA_ERROR) return CC_RESULT_OK;
return CC_RESULT_FAIL;
}
static cc_hresult chkwhl(char *val){
if(val && CAMbusy()) return CC_RESULT_BUSY;
static cc_hresult chkwhl(_U_ char *val){
if(wheel) return CC_RESULT_OK;
return CC_RESULT_FAIL;
}
static cc_hresult chkfoc(char *val){
if(val && CAMbusy()) return CC_RESULT_BUSY;
static cc_hresult chkfoc(_U_ char *val){
if(focuser) return CC_RESULT_OK;
return CC_RESULT_FAIL;
}
@@ -1010,15 +1020,6 @@ static cc_handleritem items[] = {
{chkcc, inftyhandler, CC_CMD_INFTY},
{chkcc, pluginhandler, CC_CMD_PLUGINCMD},
{NULL, tremainhandler, CC_CMD_TREMAIN},
#if 0
{chkcc, gethdrshandler, CC_CMD_GETHEADERS},
{NULL, FITSparhandler, CC_CMD_AUTHOR},
{NULL, FITSparhandler, CC_CMD_INSTRUMENT},
{NULL, FITSparhandler, CC_CMD_OBSERVER},
{NULL, FITSparhandler, CC_CMD_OBJECT},
{NULL, FITSparhandler, CC_CMD_PROGRAM},
{NULL, FITSparhandler, CC_CMD_OBJTYPE},
#endif
{chkfoc, foclisthandler, CC_CMD_FOCLIST},
{chkfoc, fsetNhandler, CC_CMD_FDEVNO},
{chkfoc, fgotohandler, CC_CMD_FGOTO},
@@ -1039,12 +1040,15 @@ static cc_handleritem items[] = {
// send image as raw data
static void *sendimage(void *C){
if(!C || !ima || !ima->data) return NULL;
int client = *(int*)C;
if(ima->h < 1 || ima->w < 1) return NULL;
int client = (int)((intptr_t)C);
if(ima->h < 1 || ima->w < 1){
close(client);
return NULL;
}
DBG("client fd: %d", client);
double t0 = sl_dtime();
int locked = FALSE;
while(!(locked = cc_lock_shm(FALSE)) && sl_dtime() - t0 < MUTEX_LOCK_TMOUT);
while(!(locked = cc_lock_shm(TRUE)) && sl_dtime() - t0 < MUTEX_LOCK_TMOUT);
if(!locked){
LOGERR("sendimage(): can't lock SHM");
close(client);
@@ -1054,8 +1058,10 @@ static void *sendimage(void *C){
cc_IMG *locimage = cc_newimage(ima->bitpix, ima->w, ima->h);
if(!locimage || !cc_copyimage(locimage, ima, FALSE)){
cc_unlock_shm();
if(locimage) cc_freeimage(&locimage);
LOGDBG("sendimage(): SHM UNlocked");
LOGERR("Can't copy new frame to local image");
close(client);
return NULL;
}
cc_unlock_shm();
@@ -1075,7 +1081,13 @@ static void *sendimage(void *C){
}
DBG("OK, wait until client receives data");
shutdown(client, SHUT_WR); // tell client we are closing socket
recv(client, locimage->data, locimage->bytelen, MSG_NOSIGNAL); // block until client close his side
t0 = sl_dtime();
while(sl_dtime() - t0 < CLIENT_CLOSE_TMOUT){
// block until client close his side or by timeout
ssize_t r = recv(client, locimage->data, locimage->bytelen, MSG_NOSIGNAL | MSG_DONTWAIT);
if(r == 0 || (r < 0 && errno != EAGAIN)) break; // client closed or got an error
usleep(1000);
}
cc_freeimage(&locimage);
close(client); // OK, we can close socket
TIMESTAMP("Image sent");
@@ -1083,20 +1095,38 @@ static void *sendimage(void *C){
return NULL;
}
void server(int sock, int imsock){
DBG("sockfd=%d, imsockfd=%d", sock, imsock);
if(sock < 0) ERRX(_("server(): need at least command socket fd"));
if(imsock < 0) WARNX(_("Server run without image transport socket"));
else if(listen(imsock, CC_MAXCLIENTS) == -1){
/**
* @brief server - main server
* @param unixsock - command UNIX socket fd
* @param sock - command INET socket fd or -1
* @param imsock - image INET socket fd or -1
*/
void server(int unixsock, int sock, int imsock){
DBG("unixsockfd=%d, sockfd=%d, imsockfd=%d", unixsock, sock, imsock);
if(unixsock < 0) ERRX(_("server(): need at least command socket fd"));
if(listen(unixsock, CC_MAXCLIENTS) == -1){
WARN("listen()");
LOGERR("server(): error in listen() for image socket");
LOGERR("server(): error in listen() for command UNIX socket");
return;
}
if(sock > -1){
if(imsock < 0){
WARNX(_("Server run without image transport socket"));
LOGWARN("Server run with command INET socket, but without image transport socket");
}else if(listen(imsock, CC_MAXCLIENTS) == -1){
WARN("listen()");
LOGWARN("server(): error in listen() for image socket");
close(imsock);
imsock = -1;
}
if(listen(sock, CC_MAXCLIENTS) == -1){
WARN("listen()");
LOGERR("server(): error in listen() for command socket");
return;
LOGWARN("server(): error in listen() for command INET socket");
close(sock);
sock = -1;
}
}
TIMEINIT();
// init everything
int ctr = 3;
@@ -1119,6 +1149,7 @@ void server(int sock, int imsock){
LOGERR("server(): no devices found");
ERRX(_("No devices found"));
}
// start camera thread
pthread_t camthread;
if(camera){
@@ -1127,18 +1158,35 @@ void server(int sock, int imsock){
LOGERR("server(): pthread_create()");
}
}
int nfd = 2; // only two listening sockets @start: command and image
struct pollfd poll_set[CC_MAXCLIENTS+2];
int nfd = 0, Nopened = 1; // only one listening socket @start: main command UNIX-socket
// amount of local connections
#define NLOCCONN 3
int locIDX = -1, cmdIDX = -1, imgIDX = -1;
struct pollfd poll_set[CC_MAXCLIENTS + NLOCCONN]; // 3 - for command UNIN, INET and image INET sockets
cc_strbuff *buffers[CC_MAXCLIENTS];
for(int i = 0; i < CC_MAXCLIENTS; ++i){
buffers[i] = cc_strbufnew(CLBUFSZ, STRBUFSZ);
}
bzero(poll_set, sizeof(poll_set));
// ZERO - listening server socket
poll_set[0].fd = sock;
poll_set[0].events = POLLIN;
poll_set[1].fd = imsock;
poll_set[1].events = POLLIN;
// ZERO - command UNIX socket
locIDX = nfd++;
poll_set[locIDX].fd = unixsock;
poll_set[locIDX].events = POLLIN;
if(sock > -1){
// ONE - command INET socket
cmdIDX = nfd++;
poll_set[cmdIDX].fd = sock;
poll_set[cmdIDX].events = POLLIN;
++Nopened;
if(imsock > -1){
// TWO - image INET socket
imgIDX = nfd++;
poll_set[imgIDX].fd = imsock;
poll_set[imgIDX].events = POLLIN;
++Nopened;
}
}
#ifdef EBUG
double T = sl_dtime();
#endif
@@ -1151,7 +1199,7 @@ void server(int sock, int imsock){
#endif
poll(poll_set, nfd, 1); // max timeout - 1ms
//if(imsock > -1 && sl_canread(imsock) > 0){
if(imsock > -1 && (poll_set[1].revents & POLLIN)){
if(imsock > -1 && (poll_set[imgIDX].revents & POLLIN)){
//uint8_t buf[32];
//int l = read(imsock, buf, 32);
DBG("Somebody wants an image");
@@ -1166,7 +1214,7 @@ void server(int sock, int imsock){
close(client);
}else{
pthread_t sendthread;
if(pthread_create(&sendthread, NULL, sendimage, (void*)&client)){
if(pthread_create(&sendthread, NULL, sendimage, (void*)(intptr_t)client)){
WARN("pthread_create()");
LOGWARN("pthread_create() error");
close(client);
@@ -1182,14 +1230,17 @@ void server(int sock, int imsock){
}
}else{WARN("accept()"); DBG("disconnected");}
}
if(poll_set[0].revents & POLLIN){ // check main for accept()
int connfd = -1;
if(poll_set[locIDX].revents & POLLIN) connfd = unixsock;
else if(sock > -1 && (poll_set[cmdIDX].revents & POLLIN)) connfd = sock;
if(connfd > -1){ // check main for accept()
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
int client = accept(sock, (struct sockaddr*)&addr, &len);
int client = accept(connfd, (struct sockaddr*)&addr, &len);
if(client > -1){
DBG("New connection");
LOGMSG("SERVER got connection, fd=%d", client);
if(nfd == CC_MAXCLIENTS + 1){
if(nfd == CC_MAXCLIENTS + NLOCCONN){
LOGWARN("Max amount of connections, disconnect fd=%d", client);
WARNX(_("Limit of connections reached"));
close(client);
@@ -1202,11 +1253,11 @@ void server(int sock, int imsock){
}
}
// scan connections
for(int fdidx = 2; fdidx < nfd; ++fdidx){
for(int fdidx = Nopened; fdidx < nfd; ++fdidx){
if((poll_set[fdidx].revents & POLLIN) == 0) continue;
int fd = poll_set[fdidx].fd;
DBG("Got active fd=%d", fd);
cc_strbuff *curbuff = buffers[fdidx-1];
cc_strbuff *curbuff = buffers[fdidx-Nopened];
int disconnected = 0;
if(cc_read2buf(fd, curbuff)){
size_t got = cc_getline(curbuff);
@@ -1223,7 +1274,12 @@ void server(int sock, int imsock){
curbuff->buflen = 0; // clear rest of data in buffer
close(fd);
// move last FD to current position
if(fdidx != nfd - 1){
poll_set[fdidx] = poll_set[nfd - 1];
cc_strbuff *lastbuf = buffers[nfd - 1 - Nopened];
curbuff->buflen = lastbuf->buflen;
memcpy(curbuff->buf, lastbuf->buf, lastbuf->buflen);
}
--nfd;
}
}
@@ -1231,7 +1287,9 @@ void server(int sock, int imsock){
if(camstate != CAMERA_CAPTURE && infty){ // start new exposition
// mark to start new capture in infinity loop when at least one client connected
if(nfd > 2){
camflags |= FLAG_STARTCAPTURE;
int curflags = atomic_load(&camflags);
curflags |= FLAG_STARTCAPTURE;
atomic_store(&camflags, curflags);
TIMESTAMP("start new capture due to `infty`");
TIMEINIT();
}

View File

@@ -23,11 +23,14 @@
// timeout of trying to lock mutex (if gone, force locking for server)
#define MUTEX_LOCK_TMOUT 0.5
// timeout of closing client's image socket - 5s
#define CLIENT_CLOSE_TMOUT 5.
// pause (seconds) between temperature logging
#define TLOG_PAUSE 60.
// server-side functions
void server(int fd, int imsock);
void server(int unixsock, int fd, int imsock);
char *makeabspath(const char *path, int shouldbe);
void stop_server();