From 4192fc7f02b3349c116d46c6d1ccdd8735bbfbd9 Mon Sep 17 00:00:00 2001 From: Edward Emelianov Date: Tue, 10 Nov 2026 15:43:44 +0300 Subject: [PATCH] v1.2.2: a lot of bugs fixed --- APOGEE_cameras/apogee.c | 8 +- Astar_cameras/artifical_star.c | 62 ++-- BASLER_cameras/basler.c | 20 +- CMakeLists.txt | 8 +- Dummy_cameras/dummyfunc.c | 4 +- EXAMPLE_for_cameras/example.c | 9 +- FLI_cameras/flifunc.c | 13 +- GRH_cameras/grasshopper.c | 13 +- HIKROBOT_cameras/mvsfunc.c | 14 +- Readme.md | 309 +++++++++++-------- TOUPCAM_cameras/toupcam.c | 9 +- ZWO_cameras/zwofunc.c | 11 +- ccdcapture.c | 147 ++++++--- ccdcapture.h | 11 +- ccdfunc.c | 71 +++-- client.c | 106 +++---- cmdlnopts.c | 15 +- cmdlnopts.h | 9 +- events.h | 2 - examples/CMakeLists.txt | 3 + examples/ccd_client.c | 20 +- examples/centroids.c | 37 +-- examples/centroids16.c | 257 ++++++++++++++++ imageview.c | 40 ++- imageview.h | 3 +- locale/ru/LC_MESSAGES/ccd_capture.mo | Bin 24496 -> 22456 bytes locale/ru/messages.po | 376 ++++++++++++----------- locale/ru/ru.po | 436 +++++++++++++++------------ main.c | 134 +++++--- server.c | 202 ++++++++----- server.h | 5 +- 31 files changed, 1454 insertions(+), 900 deletions(-) create mode 100644 examples/centroids16.c diff --git a/APOGEE_cameras/apogee.c b/APOGEE_cameras/apogee.c index cf25ff8..043a549 100644 --- a/APOGEE_cameras/apogee.c +++ b/APOGEE_cameras/apogee.c @@ -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; } diff --git a/Astar_cameras/artifical_star.c b/Astar_cameras/artifical_star.c index 2a903e1..3350b9a 100644 --- a/Astar_cameras/artifical_star.c +++ b/Astar_cameras/artifical_star.c @@ -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}, diff --git a/BASLER_cameras/basler.c b/BASLER_cameras/basler.c index 8a28390..a76f0a9 100644 --- a/BASLER_cameras/basler.c +++ b/BASLER_cameras/basler.c @@ -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); } diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f18703..ef2a547 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) diff --git a/Dummy_cameras/dummyfunc.c b/Dummy_cameras/dummyfunc.c index 7b50825..5e6aec5 100644 --- a/Dummy_cameras/dummyfunc.c +++ b/Dummy_cameras/dummyfunc.c @@ -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 diff --git a/EXAMPLE_for_cameras/example.c b/EXAMPLE_for_cameras/example.c index f96de22..dab1f95 100644 --- a/EXAMPLE_for_cameras/example.c +++ b/EXAMPLE_for_cameras/example.c @@ -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; } /** diff --git a/FLI_cameras/flifunc.c b/FLI_cameras/flifunc.c index bead86c..9baf044 100644 --- a/FLI_cameras/flifunc.c +++ b/FLI_cameras/flifunc.c @@ -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; } diff --git a/GRH_cameras/grasshopper.c b/GRH_cameras/grasshopper.c index fdb8952..7d656b2 100644 --- a/GRH_cameras/grasshopper.c +++ b/GRH_cameras/grasshopper.c @@ -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)); } } diff --git a/HIKROBOT_cameras/mvsfunc.c b/HIKROBOT_cameras/mvsfunc.c index e0f2adb..a64a159 100644 --- a/HIKROBOT_cameras/mvsfunc.c +++ b/HIKROBOT_cameras/mvsfunc.c @@ -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; } diff --git a/Readme.md b/Readme.md index 151e77c..1915d84 100644 --- a/Readme.md +++ b/Readme.md @@ -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: + 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 . diff --git a/TOUPCAM_cameras/toupcam.c b/TOUPCAM_cameras/toupcam.c index 7fb788a..d60ff2d 100644 --- a/TOUPCAM_cameras/toupcam.c +++ b/TOUPCAM_cameras/toupcam.c @@ -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"); diff --git a/ZWO_cameras/zwofunc.c b/ZWO_cameras/zwofunc.c index f86e4d7..cb244d4 100644 --- a/ZWO_cameras/zwofunc.c +++ b/ZWO_cameras/zwofunc.c @@ -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; } diff --git a/ccdcapture.c b/ccdcapture.c index 9260226..71ec23f 100644 --- a/ccdcapture.c +++ b/ccdcapture.c @@ -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){ diff --git a/ccdcapture.h b/ccdcapture.h index 69642ec..0261146 100644 --- a/ccdcapture.h +++ b/ccdcapture.h @@ -21,12 +21,16 @@ #include // FLEN_CARD #include #include +#include #include #include // 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); diff --git a/ccdfunc.c b/ccdfunc.c index fba1aa9..12c3102 100644 --- a/ccdfunc.c +++ b/ccdfunc.c @@ -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; - if(sock < 0){ - LOGERR("Can't open socket"); - ERRX(_("start_socket(): can't open socket")); + 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 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){ diff --git a/client.c b/client.c index cef499b..25d4d0e 100644 --- a/client.c +++ b/client.c @@ -22,7 +22,6 @@ #include #include #include -#include #include #include @@ -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; + DBG("Try to read %zd bytes", need); double t0 = sl_dtime(); - while(sl_dtime() - t0 < CC_CLIENT_TIMEOUT /*&& sl_canread(fd)*/ && need){ - DBG("Try to read %zd bytes", need); + 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); - if(!ret){ - WARNX(_("Can't read image data")); - goto eofg; - } + }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)); } diff --git a/cmdlnopts.c b/cmdlnopts.c index aa85b08..fece3c4 100644 --- a/cmdlnopts.c +++ b/cmdlnopts.c @@ -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,21 +119,20 @@ 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 - {"display", NO_ARGS, NULL, 'D', arg_int, APTR(&G.showimage), N_("Display image in OpenGL window")}, + {"display", NO_ARGS, NULL, 'D', arg_int, APTR(&G.showimage), N_("Display image in OpenGL window")}, #endif //{"", NEED_ARG, NULL, '', arg_double, APTR(&G.), N_("")}, diff --git a/cmdlnopts.h b/cmdlnopts.h index 8ddcaaf..16a6611 100644 --- a/cmdlnopts.h +++ b/cmdlnopts.h @@ -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); diff --git a/events.h b/events.h index ed7fa0b..09b2b27 100644 --- a/events.h +++ b/events.h @@ -24,8 +24,6 @@ #include #include -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); diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index aed2095..7e20718 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -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) diff --git a/examples/ccd_client.c b/examples/ccd_client.c index 65bcfa7..800a967 100644 --- a/examples/ccd_client.c +++ b/examples/ccd_client.c @@ -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); diff --git a/examples/centroids.c b/examples/centroids.c index 3fbd4bf..e441dc5 100644 --- a/examples/centroids.c +++ b/examples/centroids.c @@ -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); diff --git a/examples/centroids16.c b/examples/centroids16.c new file mode 100644 index 0000000..b317dff --- /dev/null +++ b/examples/centroids16.c @@ -0,0 +1,257 @@ +/* + * This file is part of the CCD_Capture project. + * Copyright 2026 Edward V. Emelianov . + * + * 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 . + */ + +/* + * 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 // DBL_EPSILON +#include +#include +#include +#include + +#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; +} diff --git a/imageview.c b/imageview.c index 93dd24b..d35ed7c 100644 --- a/imageview.c +++ b/imageview.c @@ -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"); - win->image->rawdata = raw; + pthread_mutex_unlock(&win->mutex); pthread_mutex_unlock(&img->mutex); return; } + win->image->rawdata = raw; 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 } diff --git a/imageview.h b/imageview.h index 4f7bf02..f228217 100644 --- a/imageview.h +++ b/imageview.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -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; /* diff --git a/locale/ru/LC_MESSAGES/ccd_capture.mo b/locale/ru/LC_MESSAGES/ccd_capture.mo index a43b3e089bc59e245b29d26a7953bdfa91a60ab5..f08471e1a270e04f9a3f67c84ed7c31ade723a79 100644 GIT binary patch delta 4386 zcmYk-3s9A19>?)NH$n1}fQX1(MZzl}1SSgJP!TVnh?$6+pg@{dhAt}}m0EShHanZy z#oK1Irme;?Gb3B7nccRU*;$>+W{uKqXR~&3cW1geyR+ZlIS(_w!|!~a=RNQHKG*kf z`mLaIr-D46MTI_T9Pf|>lH12DJjkr9pU#@q-)`0)8!!bo;V^s}WARlSjvt`zzm72& zKFDk^Cg4EK!J#ahnYjN^+|Ovet)z)$cFv?#M|$V8pL2X(#`)xb$i!nbh@ zUd3n}$j1;&!$h2f>c}!whZ`}0_H7phHT(jqhwo!5eu>E#!EiM4Ow9ZYm=Y1GQ{asW?uV5km2lc!xP7bDhtDumE^*9>aFd5IGdVU$X$G%53*q?dV z)F<+x@AFVIuoyM6jqdyts2O+#8H>G#@puI_;P26+FA}**4dkGDJPT>dR^nJ}LjLR+ zA6olPdFo`8TMJMDkRb zgz8`}YHDYre+^L&YDA5w1vR1rI1(@52>cQ?kVr04hm%py%}1KDvUujdfI=N72H+vo zCVJUj_$g{H^q@u-#qf1w8cxPS)Cilg0(YYJ$fwAp*mtN759B0$u_V+$C!#u5<)NUF ztwZ%(b$!u}YOvG!A?mu%P#wB~dT=yP(}>bgGgW|^nKIPggyy}cg4!rO4QE$g4)B~PJP3e26AE;}nHUAe@V=V8OHrYnh%pJgN zd9DzUV0u@pjZECypXYE$K+E}V*Lr~}phqV
IuJ8JVp^OQSrB&xw`%)+&(&2$j?v-5oX7r#Kw zU^l>&mP5m*{b3Q`;EIgC>XZ9?M?rC!@!a2AWHFalEKR|!OWf(&* zi*P;ax>KkIf52H-z-aUuZo|2F5%V#Lb<_1#*o;R}=M%;<|LW0VT3LaQqSo-QI1fX| z1x8STb<}s`0_?$ZETWgXZXZ@*H!i|_9y%NMpc=Y_ld&JupbnR!&hPe6D5KDY+WiA^ z%xZB47UOZ}bzDk)H1oO|A3=@yYn+A?a@jA~#D^L?3;|wFIwWF@Eff;~is?>~7S9_aJYQy@9FNjru(ZE)4v8O+fau zO+nhUTI5l72sLAu{dLwqfrZi3RXN+7UC6B4xA-t-GOxq&Fs{Hik$q_iMf|7464b7K z5t$tO6Y9Q*;=tRm70*-eKrP9-sa)@&@H&Mgyozj03#NPO(0F8@SuJYny?8fvp=My% z^uSWgMP7B=j=H}c@576z4i&M`tftkYt~-pp81^oD(kR@ZpdQ7ra2nxCOvJ5NjR)QN zo2U^FWkD-&I;!LQaUq^XCdIGhQ)Xexzv7`#rv-j7PE6$K3k94Tqm#? zzd$WPDlhLgti(n5k#iI~RQ0W>CHXUI2C^BAmS6?)=GlH6hQG(9cnv$Su#EZFg*|L> zbtHp#Ll0Pjy0I12u`{lI16d_YnI9PWDrBQuE9&*?#9|zh0Ktk6<^_w$(CS z^wmy#C{$9oiJHoCo}#sX0JSvj&Oc%V^?za?{0=pu|KT8vXFYg?jX^D83+n!7F$dp5 zJ^$ah4x^a1`_QwEf?k_%@F&=3aiBx>sQLxeS|!uV2XGClgO_nL4q$kra3`wXfs=7` zl^K&^4H$&KBD)C_?SCFvJMByRDbc&xduW%dcXcGwoqXQeiR?rFv6@dc%B8>2F_Mf7nZY*~v-@v7$iR>rZVE2=gRsL~B1nm0OMzl*haJahyhK$ug2bULs*6 zn)DvpY`w=b6nOQ`OA^Vx-t~Wh$~JNbx%EhJmA<%=yh$dI{zN~eI%3HbqD{DwoFng$ zNHT=1AbZF{l1d&Wy~j?s|NO7g%bdNJoFY-Al^i31;On2sRd2eDH_yd&bHeY4}+f_+~ngavtn62FaJ z*s!^7ZSq46&2@Jrr>{xg%!kjL)EMMVN}1%_l2RPvtxR9#`#3!^)E6@9$8hiCIZ?jC zoSINyc>eit@3kqZzTrjbVcvx^hxxi@Bn10zmaGi+hLooJHkRgvc>gi4$+u&tCHF^o(`xqqA9^O=rT_o{ delta 6146 zcmaKud303O9mj775WodwM*_S+Fabi?WM2&Xz9|933YknM3nViznFs=QAb=|dbi`IG zq!Dn#C1xNA2?j!cN8n&Es@3d2j>{gzv*NXu24a4$|QWxD;xBhckZ!>VV(F ze((~^fE_rUt{Dq^!1=H*bVC_Z4rTDeFq!jBH63mA7L);>L0Q_K$^LKvwBRhL2oykh zdLLw|c?#l*X@uBr&O(A=K62*2fjt?wB3yJ$Z#W5#fGM1BymW@cz0QJDZ~)_X;Sl%( zv|t+U$dfrx2NyscycM#1Qn6fP@aC~%qL(4U1LE-XdDb)PiFxgd0yZ=co6D< zD#)Lypju$t> z(U2)~Z;*~cc^Jy_CP;M5TTmN*4*4_R@gqaK6ApQr0p-aQsCf_6`YjH3L#^8nW#CIt z`=5t0{8Q+H!GF_H2ydlgv|$NU=pKRE@M$PZ>!H@Y1GT{ya1i_vDl+L-YOTJ&&WGdKWGvhTwY~{%hDlhV z`En?O8u(cazYNk*F6UwHLbw*ngL;Tf=4jB?W7yl2K^^oQoCm*vip-7UV}@^oGWeS&3-r`NatNT z(_rVROu%fYQ0{g3n#1oQX*a`ITn2MtANU?z4gUqXFeZCCHv$Hss{Uh0mP~u%?S@mK z-aoAPQ!l1B@oIpJp>oxMcY8Js;;Z~@K`~i-J zZOKb2oCLLx3#zs%<`91!^gR>Qml?pFc^a;QdZ85sAcNB25LgNaz)ENSG?YOdS=1K} zg}1{6Q1j10MdS^5GyFT0Lo+F;CD5~g_>)#s%S3UqZ%&b5O(8COE0Yf`a}teEwXtxO}-zSmJ0s+kc`Da?;C zXzr)ej)@mxTUZC>X*0YIz7GkC`3fqhlUKzyxD6__L8t?2U^+dlxD#Wb_`|KtshjD&Oqo#}xm7!mu9Z2ns80`N*I$iU))4?h8DmsYPqvw&l zR8#&7kfQMzI)?ORw2;~f)N=k|2EWiOZ6AuFTGS7{gyL-@ouOzgB5*A&KrbJ?;>@VX zZgTo5@CDR}?sn!Lg+woCo}%-tGs$PbE~W#_WgH3wRz}w=p;%+@umXofp(!s(63Pu@}lvmEh8klrGK#mGoz81;3p$JL zLaC?;sa=KmXTbjWbc4l6trL1n`G3eB@&$Cb1}<~@`yJlrumg-Z{RMCon(K_ypxf!k z(S=T5)Xtf>7T%8DM9WcF`5#T^%61Qf4QMr*?>zW9+=J>+E?S9NqbJbAXa-VS5rh5D z_)@1o2G*m=s53f+N|4$$!})m|sSX}M526rCLh*JloipgSnh1M3%}NYabV+Jg>?^SH zi;6wrLtTz149qVpF189it~`%F!z%Cvtbv>JEWgL?^XHXX`F>xCCc;a*EleDl>n|!O z40t`Ir4y`y1!j7g-|z7TtbCup#1&wwv}LNmRpiy0@H0L4wd%HL<}$0O#8u$2N`3Bi zo`AL9=MRJ@_D)Jja@HLjmz)q>ygpFm^OjmUdYogqym@q8fx;Zi?eeAttXz*(R_e*K z0=@!IpwQz_v6lFXINw>18P>AtOX6oRa^BX1>_u}|W|}2Mn>@um1bB0f0@_q3KV$@LgBuX zQ*>6`3a_igW2L)&CA^mBOb!Zv-FIqY5VPF!h}WFx1PcAWvVy|+y8*w;TUw-;Se`pP zUaKfyflv&rTjne@1i{L6F(~rJGN6U7Twhtha{Ihqk2^rD3SIuZjV?bnxQa`CEOq-m zF8j!y0nes@RYEdJOsQ4O5ygbo8X3y$?@4yMimkcI+fPl8Wo~c(Yg(t223-EYnplL= z2TgEtZDXW45*`}e8L5sOk2HqGVteFRx42dv$b=72Olv7HNnyvwwMXx3V3oosik~xTVSrpPw+c&3ulCZi|*{^JbP}L3DSd zNv1}cEo~kx=K#!!PiU1Ut7YCX_CFRm8mX3vp-*P_3Wc+Jhf}kXTU}j`RV^1FbDF=^ z-~*A9(YrCUK3=PK&n|6FJZ42s=oH*751k#~%Z<@^u${RYo+w7;GAzZ49JCFs#d&ON z+3YB$?@{d!wO@)^$;*ljk&E90tkpXEDufQqNSpW5-G1USaczlDY!h6-K4q)H-r|b0 zqC3K;XN*mpRu#*W;vP96r{dAHQ$|?rP}kVcYwSBjrkf)#+o7Zeq7|Xacgt&Nls6TOVnP?!Xy42=T00_BPd_zYXs-j<@ZqxFQI`(hsDlq zogMpHnQDciM@?r~BL~Uu&_5QQNoz^s|1a`TzZ<)Sn-+Q7b^hOL9cc<38JXN(#c0=6 JXz+@P{{m3?5m^8L diff --git a/locale/ru/messages.po b/locale/ru/messages.po index fc7e6d2..952173a 100644 --- a/locale/ru/messages.po +++ b/locale/ru/messages.po @@ -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 \n" "Language-Team: LANGUAGE \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 "" diff --git a/locale/ru/ru.po b/locale/ru/ru.po index e2a288a..d611122 100644 --- a/locale/ru/ru.po +++ b/locale/ru/ru.po @@ -7,7 +7,7 @@ msgid "" msgstr "Project-Id-Version: 0.0.1\n" "Report-Msgid-Bugs-To: \n" - "POT-Creation-Date: 2026-07-24 12:15+0300\n" + "POT-Creation-Date: 2026-11-10 15:41+0300\n" "PO-Revision-Date: 2026-07-24 08:59+0300\n" "Last-Translator: Edward V. Emelianov \n" "Language: russian\n" @@ -15,32 +15,32 @@ msgstr "Project-Id-Version: 0.0.1\n" "Content-Type: text/plain; charset=koi8-r\n" "Content-Transfer-Encoding: 8bit\n" -#: ccdfunc.c:618 +#: ccdfunc.c:619 #, c-format msgid " returns \"%s\"" msgstr " возвращает \"%s\"" -#: ccdfunc.c:540 +#: ccdfunc.c:541 #, c-format msgid "%.1f seconds till exposition ends" msgstr "%.1f секунд до окончания экспозиции" -#: ccdfunc.c:885 client.c:569 +#: ccdfunc.c:886 client.c:546 #, c-format msgid "%d seconds till pause ends\n" msgstr "%d секунд до окончания паузы\n" -#: cmdlnopts.c:160 +#: cmdlnopts.c:159 #, c-format msgid "%d unused parameters:\n" msgstr "%d неиспользуемых параметров:\n" -#: ccdfunc.c:226 +#: ccdfunc.c:227 #, c-format msgid "Added %d FITS records from %s" msgstr "Добавлено %d записей FITS из %s" -#: ccdfunc.c:225 +#: ccdfunc.c:226 #, c-format msgid "Added 0 FITS records from %s" msgstr "Добавлено 0 записей FITS из %s" @@ -57,54 +57,54 @@ msgstr " msgid "CMOS gain level" msgstr "уровень Gain CMOS" -#: ccdfunc.c:555 +#: ccdfunc.c:556 msgid "Camera device not pointed" msgstr "Устройство свеоприемника не подключено" -#: server.c:222 +#: server.c:217 #, fuzzy msgid "Camera disconnected" msgstr "Таймаут сервера" -#: client.c:632 +#: client.c:608 msgid "Camera in error state" msgstr "Камера в состоянии ошибки" -#: ccdfunc.c:638 +#: ccdfunc.c:639 #, c-format msgid "Camera model: %s" msgstr "Модель светоприемника: %s" -#: ccdfunc.c:534 +#: ccdfunc.c:535 msgid "Camera plugin have no capture polling funtion." msgstr "У плагина камеры нет функции захвата изображений" -#: ccdfunc.c:604 +#: ccdfunc.c:605 msgid "Camera plugin have no custom commands" msgstr "У плагина камеры нет особых команд" -#: ccdfunc.c:738 +#: ccdfunc.c:739 msgid "Camera plugin have no exposition setter" msgstr "У плагина камеры нет сеттера экспозиции" -#: ccdfunc.c:629 +#: ccdfunc.c:630 #, fuzzy msgid "Camera plugin have no fun speed setter" 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 "У плагина камеры нет функции `capture`" -#: 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 "У плагина камеры нет функции `start exposition`" -#: ccdfunc.c:583 +#: ccdfunc.c:584 msgid "Camera plugin have no model name getter" msgstr "У плагина камеры нет геттера названия модели" -#: ccdfunc.c:672 +#: ccdfunc.c:673 msgid "Camera plugin have no temperature setter" msgstr "У плагина камеры нет сеттера температуры" @@ -112,448 +112,451 @@ msgstr " msgid "Can't allocate buffer" msgstr "Не могу захватить изображение" -#: ccdfunc.c:848 +#: ccdfunc.c:849 #, fuzzy msgid "Can't allocate image memory" msgstr "Не могу заблокировать разделяемую память" -#: server.c:167 +#: server.c:161 msgid "Can't allocate memory for image" msgstr "Не могу выделить память для изображения" -#: main.c:124 +#: main.c:155 msgid "Can't be client and standalone in same time!" msgstr "Не могу одновременно быть клиентом и самостоятельным приложением!" -#: ccdfunc.c:865 +#: ccdfunc.c:866 msgid "Can't capture image" msgstr "Не могу захватить изображение" -#: ccdfunc.c:743 +#: ccdfunc.c:744 msgid "Can't change frame type" msgstr "Не могу изменить тип кадра" -#: ccdfunc.c:688 +#: ccdfunc.c:689 msgid "Can't configure (unsupported?)" msgstr "Не могу сконфигурировать (опция не поддерживается?)" -#: server.c:1263 +#: server.c:1321 #, c-format msgid "Can't create %s" msgstr "Не могу создать %s" -#: client.c:694 client.c:701 +#: client.c:669 client.c:676 msgid "Can't create capturing thread" msgstr "Не могу создать поток захвата изображений" -#: ccdfunc.c:981 +#: ccdfunc.c:983 msgid "Can't create grabbing thread" msgstr "Не могу создать поток захвата" -#: main.c:131 -msgid "Can't create log file" +#: main.c:164 +#, fuzzy, c-format +msgid "Can't create log file %s" msgstr "Не могу создать лог-файл" -#: ccdfunc.c:849 +#: ccdfunc.c:850 #, fuzzy msgid "Can't fill headers with camera data" msgstr "Не могу считать данные изображения" -#: ccdfunc.c:694 +#: ccdfunc.c:695 msgid "Can't get IOport state (unsupported?)" msgstr "Не могу получить состояние порта I/O (не поддерживается?)" -#: ccdfunc.c:753 +#: ccdfunc.c:754 msgid "Can't get current binning" msgstr "Не могу получить текущее значение биннинга" -#: ccdfunc.c:414 +#: ccdfunc.c:415 msgid "Can't get current focuser position" msgstr "Не могу определить текущую позицию фокусера" -#: ccdfunc.c:518 +#: ccdfunc.c:519 msgid "Can't get current wheel position" msgstr "Не могу определить текущую позицию турели" -#: ccdfunc.c:370 +#: ccdfunc.c:371 msgid "Can't get focuser limit positions" msgstr "Не могу определить предельную позицию фокусера" -#: ccdfunc.c:475 +#: ccdfunc.c:476 msgid "Can't get max wheel position" msgstr "Не могу определить предельную позицию турели" -#. TRUE -#: client.c:549 +#: client.c:526 msgid "Can't get next image" msgstr "Не могу получить очередное изображение" -#: ccdfunc.c:872 ccdfunc.c:949 +#: ccdfunc.c:873 ccdfunc.c:951 msgid "Can't grab image" msgstr "Не могу захватить изображение" -#: ccdfunc.c:432 +#: ccdfunc.c:433 msgid "Can't home focuser" msgstr "Не могу установить фокусер в нуль" -#: server.c:169 +#: server.c:163 #, fuzzy msgid "Can't init camera data" msgstr "Не могу инициализировать мьютекс!" -#: imageview.c:314 +#: imageview.c:316 msgid "Can't init mutex!" msgstr "Не могу инициализировать мьютекс!" -#: server.c:1299 +#: server.c:1357 msgid "Can't lock mutex" msgstr "Не могу заблокировать мьютекс" -#: client.c:333 +#: client.c:340 msgid "Can't lock shared memory" msgstr "Не могу заблокировать разделяемую память" -#: client.c:527 +#: client.c:504 msgid "Can't make exposition" msgstr "Не могу выполнить экспозицию" -#: imageview.c:722 +#: imageview.c:730 msgid "Can't open OpenGL window, image preview will be inaccessible" msgstr "Не могу открыть окно OpenGL, отображение будет недоступно" -#: client.c:352 +#: client.c:359 msgid "Can't open image transport socket" msgstr "Не могу открыть транспортный сокет" -#: client.c:446 -#, c-format -msgid "Can't read full header, got %zd records from %zd" -msgstr "Не могу считать весь залогово, получил лишь %zd записей из %zd" - -#: client.c:392 client.c:422 +#: client.c:403 client.c:431 msgid "Can't read image data" msgstr "Не могу считать данные изображения" -#: client.c:358 +#: client.c:365 msgid "Can't read image header over socket" msgstr "Не могу считать заголовок изображения по сокету" -#: ccdfunc.c:683 +#: main.c:129 +msgid "Can't run in client and server modes simultaneously" +msgstr "" + +#: ccdfunc.c:684 #, c-format msgid "Can't run shutter command %s (unsupported?)" msgstr "Не могу выполнить команду затвора %s (не поддерживается?)" -#: client.c:487 client.c:587 +#: client.c:464 client.c:564 msgid "Can't run without command socket" msgstr "Не могу работать без командного сокета" -#: ccdfunc.c:108 +#: ccdfunc.c:109 #, c-format msgid "Can't save file with prefix %s" msgstr "Не могу сохранить файл с префиксом %s" -#: ccdfunc.c:735 +#: ccdfunc.c:736 #, c-format msgid "Can't set %d flushes" msgstr "Не могу установить %d сбросов" -#: ccdfunc.c:699 +#: ccdfunc.c:700 msgid "Can't set IOport" msgstr "Не могу поменять значения порта I/O" -#: ccdfunc.c:673 +#: ccdfunc.c:674 #, c-format msgid "Can't set T to %g degC" msgstr "Не могу установить температуру в %g градЦ" -#: ccdfunc.c:598 +#: ccdfunc.c:599 msgid "Can't set active camera number" msgstr "Не могу установить номер активной камеры" -#: ccdfunc.c:363 +#: ccdfunc.c:364 msgid "Can't set active focuser number" msgstr "Не могу установить номер активного фокусера" -#: ccdfunc.c:469 +#: ccdfunc.c:470 msgid "Can't set active wheel number" msgstr "Не могу установить номер активного колеса" -#: main.c:99 +#: main.c:124 #, c-format msgid "Can't set answer timeout to %g" msgstr "Не могу установить таймаут ответа в %g" -#: ccdfunc.c:719 server.c:359 +#: ccdfunc.c:720 server.c:357 #, c-format msgid "Can't set binning %dx%d" msgstr "Не могу установить биннинг %dx%d" -#: ccdfunc.c:746 +#: ccdfunc.c:747 msgid "Can't set bit depth" msgstr "Не могу установить разрядность АЦП" -#: ccdfunc.c:713 +#: ccdfunc.c:714 #, c-format msgid "Can't set brightness to %g" msgstr "Не могу установить яркость в %g" -#: ccdfunc.c:740 +#: ccdfunc.c:741 #, c-format msgid "Can't set exposure time to %f seconds" msgstr "Не могу установить экспозицию в %f секунд" -#: ccdfunc.c:632 +#: ccdfunc.c:633 msgid "Can't set fan speed" msgstr "Не могу установить скорость вентиляторов" -#: ccdfunc.c:707 +#: ccdfunc.c:708 #, c-format msgid "Can't set gain to %g" msgstr "Не могу установить gain в %g" -#: ccdfunc.c:731 server.c:361 +#: ccdfunc.c:732 server.c:359 msgid "Can't set given geometry" msgstr "Не могу установить геометрию" -#: ccdfunc.c:434 +#: ccdfunc.c:435 #, c-format msgid "Can't set position %g" msgstr "Не могу изменить позицию на %g" -#: ccdfunc.c:428 +#: ccdfunc.c:429 #, c-format msgid "Can't set position %g: out of limits [%g, %g]" msgstr "Не могу установить позицию %g: вне пределов [%g, %g]" -#: ccdfunc.c:748 +#: ccdfunc.c:749 msgid "Can't set readout speed" msgstr "Не могу установить скорость считывания" -#: ccdfunc.c:527 +#: ccdfunc.c:528 #, c-format msgid "Can't set wheel position %d" msgstr "Не могу установить положение колеса %d" -#: ccdfunc.c:860 ccdfunc.c:937 server.c:214 +#: ccdfunc.c:861 ccdfunc.c:939 server.c:209 msgid "Can't start exposition" msgstr "Не могу начать экспозицию" -#: server.c:129 +#: server.c:123 msgid "Can't unlock socket mutex" msgstr "Не могу разблокировать мьютекс сокета" -#: main.c:93 +#: main.c:112 msgid "Can't use outfile name and prefix together" msgstr "Не могу одновременно использовать имя файла и префикс" -#: ccdfunc.c:857 +#: ccdfunc.c:858 #, c-format msgid "Capture frame %d" msgstr "Захват кадра %d" -#: server.c:1165 +#: server.c:1213 msgid "Client wants an image, but there's no data" msgstr "Клиент ждет изображения, но данные отсутствуют" -#: ccdfunc.c:613 ccdfunc.c:616 +#: ccdfunc.c:614 ccdfunc.c:617 #, c-format msgid "Command '%s'" msgstr "Команда '%s'" -#: ccdfunc.c:660 +#: ccdfunc.c:661 #, c-format msgid "Current binning: %d x %d" msgstr "Текущий биннинг: %d x %d" -#: ccdfunc.c:666 -#, c-format -msgid "Current brightness: %g" +#: ccdfunc.c:667 +#, fuzzy, c-format +msgid "Current brightness: %f" msgstr "Текущая яркость: %g" -#: ccdfunc.c:651 +#: ccdfunc.c:652 #, c-format msgid "Current format: %s" msgstr "Текущий формат: %s" -#: ccdfunc.c:668 -#, c-format -msgid "Current gain: %g" +#: ccdfunc.c:669 +#, fuzzy, c-format +msgid "Current gain: %f" msgstr "Текущий gain: %s" -#: ccdfunc.c:663 +#: ccdfunc.c:664 #, c-format msgid "Current settings: %d bits per pixel" msgstr "Текущие настройки: %d бит на пиксель" -#: cmdlnopts.c:136 +#: cmdlnopts.c:135 msgid "Display image in OpenGL window" msgstr "Отображение изображения в окне OpenGL" -#: imageview.c:773 +#: imageview.c:781 #, c-format msgid "Equalization of histogram: %s" msgstr "Эквализация гистограммы: %s" -#: ccdfunc.c:269 +#: ccdfunc.c:270 #, c-format msgid "Error saving file %s" msgstr "Ошибка сохранения файла %s" #. 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 "Экспонирую кадр %d..." -#: client.c:506 +#: client.c:483 msgid "Exposing frame 1..." msgstr "Экспонирую кадр 1..." -#: ccdfunc.c:648 +#: ccdfunc.c:649 #, c-format msgid "Field of view: %s" msgstr "Поле зрения: %s" -#: main.c:96 ccdfunc.c:100 +#: main.c:118 ccdfunc.c:101 #, c-format msgid "File %s exists!" msgstr "Файл %s существует!" -#: ccdfunc.c:260 +#: ccdfunc.c:261 #, c-format msgid "File saved as '%s'" msgstr "Файл сохранен как '%s'" -#: ccdfunc.c:333 +#: ccdfunc.c:334 msgid "Focuser device not pointed" msgstr "Устройство фокусера не указано" -#: ccdfunc.c:594 +#: ccdfunc.c:595 #, c-format msgid "Found %d cameras, you point number %d" msgstr "Обнаружено %d камер, вы указали %d" -#: ccdfunc.c:358 +#: ccdfunc.c:359 #, c-format msgid "Found %d focusers, you point number %d" msgstr "Обнаружено %d фокусеров, вы указали %d" -#: ccdfunc.c:464 +#: ccdfunc.c:465 #, c-format msgid "Found %d wheels, you point number %d" msgstr "Обнаружено %d колес, вы указали %d" -#: ccdfunc.c:588 +#: ccdfunc.c:589 #, c-format msgid "Found camera #%d: %s\n" msgstr "Обнаружена камера номер %d: %s\n" -#: ccdfunc.c:396 +#: ccdfunc.c:397 #, c-format msgid "Found focuser #%d: %s\n" msgstr "Обнаружен фокусер номер %d: %s\n" -#: ccdfunc.c:500 +#: ccdfunc.c:501 #, c-format msgid "Found wheel #%d: %s\n" msgstr "Обнаружена турель номер %d: %s\n" -#: client.c:547 +#: client.c:524 msgid "Frame ready, try to grab" 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 "%.2f кадров в секунду (%g секунд на экспозицию); средняя скорость " "%.2f" -#: ccdfunc.c:645 +#: ccdfunc.c:646 #, c-format msgid "Full array: %s" msgstr "Полный формат: %s" -#: ccdfunc.c:656 +#: ccdfunc.c:657 #, c-format msgid "Geometry steps: offset - %dx%d, size - %dx%d" msgstr "Шаг измерения геометрии: смещения - %dx%d, размера - %dx%d" -#. slave: cancel exposition #: main.c:60 #, c-format msgid "Get signal %d - exit" msgstr "Полуен сигнал %d - выход" -#: client.c:557 +#: client.c:534 msgid "Got already saved image, wait next" msgstr "Получил уже сохраненное изображение, жду следующего" -#: client.c:157 +#: client.c:159 msgid "Got empty string" msgstr "Получил пустую строку" -#: imageview.c:427 +#: imageview.c:429 #, c-format msgid "Histogram conversion: %s" msgstr "Преобразование гистограммы: %s" +#: cmdlnopts.c:123 +msgid "INET command socket port (omit if use on same host with server)" +msgstr "" + #: cmdlnopts.c:124 -msgid "INET image socket port" +#, fuzzy +msgid "INET image socket port (default: port+1)" msgstr "порт локального сетевого сокета передачи изображения" -#: ccdfunc.c:89 +#: ccdfunc.c:90 msgid "Image not saved: neither filename nor filename prefix pointed" msgstr "Изображение не сохранено: не указано ни имени файла, ни префикса" -#: ccdfunc.c:324 +#: ccdfunc.c:325 #, c-format msgid "Image stat:\n" msgstr "Статистика по изображению: \n" -#: client.c:634 +#: client.c:610 #, c-format msgid "Image wasn't received, state: %d, waiting: %g, lastNo: %d, curNo: %d " "(timeout: %g)" msgstr "Изображение не было получено. Состояние: %d, ожидание: %g, последний " "номер: %d, текущий номер: %d (таймаут: %g)" -#: server.c:1194 +#: server.c:1245 msgid "Limit of connections reached" msgstr "Достигнут предел количества подключений" -#: main.c:129 +#: main.c:162 #, c-format msgid "Log file %s @ level %d\n" msgstr "Лог-файл %s с уровнем %d\n" #. save image -#: imageview.c:756 +#: imageview.c:764 msgid "Make screenshot" msgstr "Сделать скриншот" -#: main.c:55 +#: main.c:54 #, c-format msgid "Master killed with sig=%d" msgstr "Хозяин убит с сигналом %d" -#: ccdfunc.c:670 -#, c-format -msgid "Maximal gain: %g" +#: ccdfunc.c:671 +#, fuzzy, c-format +msgid "Maximal gain: %f" msgstr "Наибольший gain: %g" -#: ccdfunc.c:654 +#: ccdfunc.c:655 #, c-format msgid "Maximal geometry (WxH): %dx%d" msgstr "Наибольшая геометрия (WxH): %dx%d" -#: ccdfunc.c:655 +#: ccdfunc.c:656 #, c-format msgid "Minimal offset: %dx%d" msgstr "Минимальное смещение: %dx%d" -#: imageview.c:617 +#: imageview.c:625 #, c-format msgid "Missed %zd images" msgstr "Пропущено %zd изображений" @@ -562,165 +565,158 @@ msgstr " msgid "N flushes before exposing (default: 1)" msgstr "N засвечиваний перед экспозицией (по умолчанию: 1)" -#: ccdfunc.c:1023 +#: ccdfunc.c:1042 msgid "Need exposition time!" msgstr "Укажите время экспозиции!" -#: server.c:276 +#: server.c:272 msgid "No camera device" msgstr "Не указано устройство камеры" -#: ccdfunc.c:562 ccdfunc.c:563 +#: ccdfunc.c:563 ccdfunc.c:564 msgid "No cameras found" msgstr "Камер не обнаружено" -#: server.c:1120 +#: server.c:1150 #, fuzzy msgid "No devices found" msgstr "Турелей не обнаружено" -#: ccdfunc.c:340 +#: ccdfunc.c:341 msgid "No focusers found" msgstr "Фокусеров не обнаружено" -#: imageview.c:715 +#: imageview.c:723 msgid "No image changing function defined" msgstr "Не определена функция, ответственная за смену изображений" -#: ccdfunc.c:447 +#: ccdfunc.c:448 msgid "No wheels found" msgstr "Турелей не обнаружено" -#: ccdfunc.c:750 +#: ccdfunc.c:751 msgid "Only show statistics" msgstr "Только отобразить статистику" -#: main.c:103 -msgid "Options `port` and `path` can't be used together! Point `port` for " - "TCP socket or `path` for UNIX." -msgstr "Опции `port` и `path` не могут использоваться совместно! Укажите " - "`port` для TCP-сокетов или `path` для UNIX." - -#: ccdfunc.c:639 +#: ccdfunc.c:640 #, c-format msgid "Pixel size: %g x %g" msgstr "Размер пикселя: %g x %g" -#: ccdfunc.c:1010 -msgid "Point network port or UNIX-socket path" -msgstr "Укажите сетевой порт или путь к UNIX-сокету" +#. TODO - simple file viewer +#: main.c:185 +#, fuzzy +msgid "Point camera device plugin to run viewer" +msgstr "особые команды плагина камеры" -#: ccdfunc.c:868 +#: ccdfunc.c:869 msgid "Read grabbed image" msgstr "Считывание изображения" -#: ccdfunc.c:749 +#: ccdfunc.c:750 #, c-format msgid "Readout mode: %s" msgstr "Режим считывания: %s" -#: client.c:186 +#: client.c:188 msgid "Send custom plugin commands\n" msgstr "Отправить особые команды плагина камеры\n" #. 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 "Сервер отключен" -#: client.c:149 +#: client.c:151 msgid "Server disconnected?" msgstr "Сервер отключен?" -#: server.c:1089 +#: server.c:1114 msgid "Server run without image transport socket" msgstr "Сервер запущен без транспортного сокета (только SHM)" -#: client.c:581 +#: client.c:558 msgid "Server timeout" msgstr "Таймаут сервера" -#: ccdfunc.c:712 +#: ccdfunc.c:713 #, c-format msgid "Set brightness to %g" msgstr "Установить яркость в %g" -#: ccdfunc.c:633 +#: ccdfunc.c:634 #, c-format msgid "Set fan speed to %d" msgstr "Не могу установить скорость вентиляторов в %d" -#: ccdfunc.c:706 +#: ccdfunc.c:707 #, c-format msgid "Set gain to %g" msgstr "Установить Gain в %g" -#: main.c:121 +#: main.c:151 #, c-format msgid "Set image port to %s\n" msgstr "Устанавливаю номер транспортного порта в %d\n" -#: imageview.c:760 +#: imageview.c:768 #, c-format msgid "Set output prefix to %s" msgstr "Устанавливаю выходной префикс в %s" -#: ccdfunc.c:681 +#: ccdfunc.c:682 #, c-format msgid "Shutter command: %s\n" msgstr "Команда затвора: %s\n" -#: ccdfunc.c:946 +#: ccdfunc.c:948 msgid "Some error when capture" msgstr "Ошибка при захвате" -#: server.c:228 +#: server.c:223 msgid "Something's wrong with camera" msgstr "Что-то камере поплохело" -#: client.c:462 +#: client.c:439 msgid "Still got old image" msgstr "Все еще получаю старые изображения" -#: client.c:435 -msgid "Too many FITS headers, truncating" -msgstr "Слишком много заголовков FITS, обрезаю" - -#: ccdfunc.c:686 +#: ccdfunc.c:687 #, c-format msgid "Try to configure I/O port as %d" msgstr "Попытка сконфигурировать порт I/O как %d" -#: ccdfunc.c:697 +#: ccdfunc.c:698 #, c-format msgid "Try to write %d to I/O port" msgstr "Попытка записи %d в порт I/O" -#: cmdlnopts.c:122 -msgid "UNIX socket name (command socket)" -msgstr "имя UNIX-сокета" - -#: client.c:508 +#: client.c:485 msgid "Wait for exposition end" msgstr "Жду, пока не кончится экспозиция" -#: ccdfunc.c:440 +#: ccdfunc.c:441 msgid "Wheel device not pointed" msgstr "Устройство турели не указано" -#: ccdfunc.c:509 +#: ccdfunc.c:510 #, fuzzy, c-format msgid "Wheel model: %s" msgstr "Модель светоприемника: %s" -#: ccdfunc.c:523 +#: ccdfunc.c:524 #, c-format msgid "Wheel position should be from 0 to %d" msgstr "Позиция колеса должна быть от 0 до %d" -#: main.c:108 +#: main.c:138 +#, fuzzy, c-format +msgid "Wrong image port value: %d" +msgstr "Неправильный номер порта: %d" + +#: main.c:145 #, c-format msgid "Wrong port value: %d" msgstr "Неправильный номер порта: %d" @@ -793,17 +789,6 @@ msgstr " msgid "focuser device plugin (e.g. devzwo.so)" msgstr "плагин фокусера (например, devzwo.so)" -#: cmdlnopts.c:132 -msgid "force using image through socket transition even if can use SHM" -msgstr "принудительно брать изображения из сокета даже если возможно " - "пользоваться разделяемой памятью" - -#: cmdlnopts.c:129 -msgid "get base information about connected hardware (also increasing text " - "messages level to 2)" -msgstr "получить базовую информацию о подключенном оборудовании (также " - "включая текстовые сообщения с уровнемя до 2)" - #: cmdlnopts.c:107 msgid "get value of I/O port pins" msgstr "получить значение порта I/O" @@ -820,10 +805,6 @@ msgstr " msgid "list connected devices" msgstr "список подключенных устройств" -#: cmdlnopts.c:123 -msgid "local INET command socket port" -msgstr "порт локального сетевого сокета" - #: cmdlnopts.c:121 msgid "logging file name (if run as server)" msgstr "имя файла логгирования (если запущен сервер)" @@ -849,7 +830,7 @@ msgstr " msgid "move stepper motor asynchronous" msgstr "асинхронное движение шагового двигателя" -#: cmdlnopts.c:128 +#: cmdlnopts.c:129 msgid "network answer timeout (default: 0.1s)" msgstr "таймаут ответа по сети (по умолчанию: 0.1с)" @@ -873,11 +854,11 @@ msgstr " msgid "observing program name" msgstr "название программы" -#: imageview.c:773 +#: imageview.c:781 msgid "off" msgstr "выкл" -#: imageview.c:773 +#: imageview.c:781 msgid "on" msgstr "вкл" @@ -889,7 +870,7 @@ msgstr " msgid "output file name" msgstr "имя файла" -#: cmdlnopts.c:126 +#: cmdlnopts.c:127 msgid "passive viewer (only get last images)" msgstr "пассивный просмотр (только последние кадры)" @@ -897,7 +878,7 @@ msgstr " msgid "program author" msgstr "автор программы" -#: cmdlnopts.c:127 +#: cmdlnopts.c:128 msgid "restart image server" msgstr "перезапуск сервера" @@ -909,6 +890,11 @@ msgstr " msgid "run as client" msgstr "запустить клиент" +#: cmdlnopts.c:126 +#, fuzzy +msgid "run as server" +msgstr "запустить клиент" + #: cmdlnopts.c:106 msgid "run exposition on HIGH @ pin5 I/O port" msgstr "запуск экспозиции по ВЫСОКОМУ сигналу на контакте 5 порта I/O" @@ -921,7 +907,12 @@ msgstr " msgid "run in 8-bit mode" msgstr "8-битный режим" -#: server.c:1088 +#: cmdlnopts.c:122 +#, fuzzy +msgid "server's host name" +msgstr "имена наблюдателей" + +#: server.c:1106 msgid "server(): need at least command socket fd" msgstr "server(): нужен как минимум дескриптор командного сокета" @@ -953,12 +944,23 @@ msgstr " msgid "show this help" msgstr "отобразить эту справку" -#: cmdlnopts.c:133 +#: cmdlnopts.c:132 msgid "start (!=0) or stop(==0) infinity capturing loop" msgstr "начать (!=0) или закончить (==0) бесконечный цикл захвата изображений" -#: ccdfunc.c:1014 -msgid "start_socket(): can't open socket" +#: ccdfunc.c:1029 +#, fuzzy +msgid "start_socket(): can't open command INET socket" +msgstr "start_socket(): не могу открыть сокет" + +#: ccdfunc.c:1014 ccdfunc.c:1034 +#, fuzzy +msgid "start_socket(): can't open command UNIX socket" +msgstr "start_socket(): не могу открыть сокет" + +#: ccdfunc.c:1020 +#, fuzzy +msgid "start_socket(): can't open image INET socket" msgstr "start_socket(): не могу открыть сокет" #: cmdlnopts.c:75 @@ -974,3 +976,35 @@ msgstr " #: cmdlnopts.c:68 msgid "wheel device plugin (e.g. devdummy.so)" msgstr "плагин устройства турели (например, devdummy.so)" + +#, c-format +#~ msgid "Can't read full header, got %zd records from %zd" +#~ msgstr "Не могу считать весь залогово, получил лишь %zd записей из " +#~ "%zd" + +#~ msgid "Options `port` and `path` can't be used together! Point " +#~ "`port` for TCP socket or `path` for UNIX." +#~ msgstr "Опции `port` и `path` не могут использоваться совместно! " +#~ "Укажите `port` для TCP-сокетов или `path` для UNIX." + +#~ msgid "Point network port or UNIX-socket path" +#~ msgstr "Укажите сетевой порт или путь к UNIX-сокету" + +#~ msgid "Too many FITS headers, truncating" +#~ msgstr "Слишком много заголовков FITS, обрезаю" + +#~ msgid "UNIX socket name (command socket)" +#~ msgstr "имя UNIX-сокета" + +#~ msgid "force using image through socket transition even if can use " +#~ "SHM" +#~ msgstr "принудительно брать изображения из сокета даже если возможно " +#~ "пользоваться разделяемой памятью" + +#~ msgid "get base information about connected hardware (also " +#~ "increasing text messages level to 2)" +#~ msgstr "получить базовую информацию о подключенном оборудовании " +#~ "(также включая текстовые сообщения с уровнемя до 2)" + +#~ msgid "local INET command socket port" +#~ msgstr "порт локального сетевого сокета" diff --git a/main.c b/main.c index 2f093fc..22febbc 100644 --- a/main.c +++ b/main.c @@ -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(); + 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->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)) 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(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->imageport){ // make default: port + 1 + GP->imageport = MALLOC(char, 32); + snprintf(GP->imageport, 31, "%d", 1 + port); + verbose(VERBOSE_PRIMARY, _("Set image port to %s\n"), GP->imageport); + } } - 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){ - GP->imageport = MALLOC(char, 32); - if(!GP->port) sprintf(GP->imageport, "12345"); - else snprintf(GP->imageport, 31, "%d", 1+atoi(GP->port)); - verbose(VERBOSE_PRIMARY, _("Set image port to %s\n"), GP->imageport); + 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->client && (GP->commondev || GP->focuserdev || GP->cameradev || GP->wheeldev)) - ERRX(_("Can't be client and standalone in same time!")); 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 - wheels(); - camerainit = prepare_ccds(); - }else{ // client mode - return start_socket(isserver); - } + if(mode == STANDALONE_MODE){ + focusers(); + wheels(); + 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); } diff --git a/server.c b/server.c index 9fcc51d..78a0bc4 100644 --- a/server.c +++ b/server.c @@ -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; } @@ -388,9 +388,11 @@ static cc_hresult camlisthandler(int fd, _U_ const char *key, _U_ const char *va if(!camera->getModelName) return CC_RESULT_FAIL; for(int i = 0; i < camera->Ndevices; ++i){ 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; + camera->getModelName(modname, 255); + snprintf(buf, BUFSIZ-1, CC_CMD_CAMLIST "='%s'", modname); + 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(listen(sock, CC_MAXCLIENTS) == -1){ - WARN("listen()"); - LOGERR("server(): error in listen() for command 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()"); + 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 - poll_set[fdidx] = poll_set[nfd - 1]; + 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(); } diff --git a/server.h b/server.h index 4abe272..df46be7 100644 --- a/server.h +++ b/server.h @@ -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();