From 91d4af05416797ee45d2a0289b68b2abcd57b953 Mon Sep 17 00:00:00 2001 From: koennecke Date: Fri, 13 Feb 2009 09:00:03 +0000 Subject: [PATCH] - Adapted indenation to new agreed upon system - Added support for second generation scriptcontext based counter --- Busy.c | 81 +- Busy.h | 7 +- Dbg.c | 1665 ++++++------ Dbg.h | 40 +- Dbg_cmd.c | 65 +- HistMem.h | 99 +- SCinter.c | 1793 +++++++------ SCinter.h | 196 +- SICSmain.c | 100 +- Scommon.h | 37 +- access.c | 40 +- alias.c | 324 ++- alias.h | 13 +- anticollider.c | 307 +-- anticollider.h | 13 +- ascon.c | 282 ++- ascon.h | 18 +- asyncprotocol.c | 136 +- asyncprotocol.h | 62 +- asyncqueue.c | 364 ++- asyncqueue.h | 41 +- background.c | 132 +- background.h | 10 +- bit.h | 2 +- callback.c | 629 +++-- cell.c | 152 +- cell.h | 16 +- chadapter.c | 815 +++--- chadapter.h | 46 +- choco.c | 381 ++- choco.h | 34 +- circular.c | 172 +- circular.h | 24 +- codri.h | 43 +- comentry.h | 77 +- commandcontext.h | 8 +- commandlog.c | 915 ++++--- commandlog.h | 17 +- cone.c | 270 +- cone.h | 10 +- configfu.h | 20 +- confvirtmot.h | 9 +- confvirtualmot.c | 569 +++-- conman.c | 3682 +++++++++++++-------------- conman.h | 214 +- costa.c | 273 +- costa.h | 18 +- countdriv.c | 97 +- countdriv.h | 96 +- counter.c | 2104 ++++++++-------- counter.h | 84 +- countersec.c | 504 ++++ crysconv.c | 567 ++--- cryst.c | 104 +- d_mod.c | 42 +- d_sign.c | 14 +- danu.c | 625 +++-- danu.h | 22 +- definealias.c | 272 +- definealias.h | 88 +- defines.h | 4 +- devexec.c | 2296 ++++++++--------- devexec.h | 170 +- devser.c | 154 +- devser.h | 31 +- dict.c | 108 +- diffscan.c | 378 +-- diffscan.h | 34 +- difrac.c | 854 +++---- difrac.h | 4 +- drive.c | 819 +++--- drive.h | 46 +- dynstring.c | 464 ++-- dynstring.h | 118 +- ecbcounter.c | 407 +-- ecbcounter.h | 2 +- ecode.c | 31 +- emon.c | 609 +++-- emon.h | 30 +- errormsg.c | 20 +- errormsg.h | 2 +- eurodriv.h | 18 +- evcontroller.c | 2665 ++++++++++---------- evcontroller.h | 42 +- evdriver.c | 47 +- evdriver.h | 4 +- event.c | 80 +- event.h | 6 +- exebuf.c | 237 +- exebuf.h | 28 +- exeman.c | 1418 ++++++----- exeman.h | 21 +- f2c.h | 222 +- fitcenter.c | 886 ++++--- fitcenter.h | 37 +- fomerge.c | 1359 +++++----- fomerge.h | 69 +- fortify.c | 1087 ++++---- fortify.h | 54 +- fourlib.c | 936 +++---- fourlib.h | 75 +- fourmess.c | 1425 ++++++----- fourmess.h | 3 +- fourtable.c | 274 +- fourtable.h | 18 +- frame.c | 228 +- frame.h | 8 +- fupa.c | 215 +- fupa.h | 53 +- genericcontroller.c | 1151 ++++----- genericcontroller.h | 34 +- geninter.c | 9 +- geninter.h | 8 +- gpibcontroller.c | 462 ++-- gpibcontroller.h | 34 +- hdbqueue.c | 925 +++---- hdbqueue.h | 6 +- help.c | 131 +- help.h | 7 +- hipadaba.c | 1799 ++++++------- hipadaba.h | 158 +- histdriv.c | 134 +- histmem.c | 3109 +++++++++++------------ histregress.c | 454 ++-- histsim.c | 500 ++-- histsim.h | 2 +- hkl.c | 1756 +++++++------ hkl.h | 54 +- hklmot.c | 208 +- hklmot.h | 20 +- hklscan.c | 761 +++--- hklscan.h | 14 +- hmcontrol.c | 308 ++- hmcontrol.h | 29 +- hmdata.c | 790 +++--- hmdata.h | 75 +- hmslave.c | 390 +-- ifile.c | 348 ++- ifile.h | 33 +- init8.c | 580 ++--- initcl.c | 578 ++--- initializer.c | 133 +- initializer.h | 9 +- intcli.c | 62 +- integrate.c | 550 ++-- integrate.h | 4 +- interface.c | 230 +- interface.h | 113 +- interrupt.h | 28 +- intserv.c | 144 +- lin2ang.c | 509 ++-- lin2ang.h | 7 +- lld.c | 1020 ++++---- lld.h | 100 +- lld_blob.c | 156 +- lld_blob.h | 14 +- logger.c | 203 +- logger.h | 19 +- logreader.c | 287 ++- logsetup.c | 46 +- lomax.c | 658 +++-- lomax.h | 34 +- macro.c | 1751 +++++++------ macro.h | 63 +- make_gen | 2 +- maximize.c | 900 +++---- maximize.h | 18 +- mccontrol.c | 847 ++++--- mccontrol.h | 59 +- mclist.c | 26 +- mclist.h | 16 +- mcreader.c | 839 ++++--- mcreader.h | 22 +- mcstascounter.c | 260 +- mcstashm.c | 348 +-- mcstashm.h | 4 +- mesure.c | 3097 +++++++++++------------ mesure.h | 45 +- modriv.h | 107 +- moregress.c | 299 +-- motor.c | 2300 ++++++++--------- motor.h | 95 +- motorlist.c | 383 +-- motorlist.h | 21 +- motorsec.c | 1361 +++++----- motorsec.h | 8 +- motreg.c | 106 +- motreg.h | 42 +- motreglist.c | 89 +- motreglist.h | 18 +- multicounter.c | 438 ++-- multicounter.h | 6 +- mumo.c | 1493 +++++------ mumo.h | 31 +- mumoconf.c | 550 ++-- napi.c | 1959 +++++++-------- napi.h | 283 ++- napi4.c | 3517 +++++++++++++------------- napi4.h | 84 +- napi5.c | 3425 ++++++++++++------------- napi5.h | 75 +- napiconfig.h | 20 +- napiu.c | 208 +- napiu.h | 60 +- network.c | 1632 ++++++------ network.h | 152 +- nigpib.c | 76 +- nintf.c | 63 +- nread.c | 2555 +++++++++---------- nread.h | 32 +- nserver.c | 907 ++++--- nserver.h | 44 +- nwatch.c | 121 +- nwatch.h | 17 +- nxcopy.c | 488 ++-- nxcopy.h | 4 +- nxdata.c | 1512 ++++++----- nxdata.h | 19 +- nxdataset.c | 336 +-- nxdataset.h | 54 +- nxdict.c | 3409 ++++++++++++------------- nxdict.h | 71 +- nxdump.c | 105 +- nxinter_wrap.c | 4607 +++++++++++++++++++--------------- nxinterhelper.c | 477 ++-- nxinterhelper.h | 20 +- nxio.c | 525 ++-- nxio.h | 13 +- nxscript.c | 1861 +++++++------- nxscript.h | 10 +- nxstack.c | 62 +- nxstack.h | 5 +- nxupdate.c | 294 +-- nxupdate.h | 11 +- nxutil.c | 563 ++--- nxutil.h | 44 +- nxxml.c | 1352 +++++----- nxxml.h | 88 +- o2t.c | 534 ++-- o2t.h | 16 +- obdes.c | 271 +- obdes.h | 50 +- obpar.c | 301 ++- obpar.h | 60 +- ofac.c | 681 +++-- ofac.h | 5 +- optimise.c | 1906 +++++++------- optimise.h | 29 +- oscillate.c | 258 +- oscillate.h | 33 +- outcode.c | 37 +- passwd.c | 210 +- passwd.h | 18 +- perfmon.c | 377 ++- perfmon.h | 18 +- polldriv.c | 257 +- polldriv.h | 34 +- protocol.c | 1278 +++++----- protocol.h | 32 +- proxy.c | 873 +++---- proxy.h | 4 +- regresscter.c | 431 ++-- remob.c | 585 +++-- remob.h | 7 +- rmlead.c | 48 +- rmtrail.c | 20 +- rs232controller.c | 957 ++++--- rs232controller.h | 74 +- s_rnge.c | 36 +- savehdb.c | 42 +- scaldate.c | 55 +- scaldate.h | 38 +- scan.c | 3976 ++++++++++++++--------------- scan.h | 97 +- scanvar.c | 253 +- scanvar.h | 49 +- script.c | 932 ++++--- script.h | 54 +- scriptcontext.c | 697 +++--- scriptcontext.h | 14 +- sctdriveadapter.c | 468 ++-- sctdriveobj.c | 562 +++-- sdynar.c | 333 ++- sdynar.h | 21 +- sel2.c | 589 +++-- selector.c | 1414 +++++------ selector.h | 53 +- selvar.c | 1088 ++++---- selvar.h | 37 +- serialsinq.h | 32 +- serialwait.c | 375 ++- serialwait.h | 4 +- servlog.c | 425 ++-- servlog.h | 12 +- sgclib.c | 2545 ++++++++++--------- sgfind.c | 966 +++---- sghkl.c | 204 +- sginfo.c | 1567 ++++++------ sginfo.h | 2904 +++++++++++---------- sgio.c | 1609 ++++++------ sgsi.c | 530 ++-- sics.h | 15 +- sicscron.c | 341 ++- sicscron.h | 4 +- sicsdata.c | 993 ++++---- sicsdata.h | 48 +- sicsexit.c | 67 +- sicsexit.h | 6 +- sicshdbadapter.c | 1466 +++++------ sicshdbadapter.h | 10 +- sicshdbfactory.c | 633 ++--- sicshipadaba.c | 5850 ++++++++++++++++++++++--------------------- sicshipadaba.h | 97 +- sicslist.c | 989 ++++---- sicslist.h | 8 +- sicsobj.c | 898 +++---- sicsobj.h | 40 +- sicspoll.c | 647 ++--- sicspoll.h | 21 +- sicsvar.h | 87 +- sicvar.c | 1053 ++++---- sig_die.c | 48 +- simchop.c | 507 ++-- simcter.c | 589 +++-- simdriv.c | 562 ++--- simev.c | 391 ++- simev.h | 4 +- simidx.c | 517 ++-- simidx.h | 8 +- sinfox.c | 2073 ++++++++------- sinfox.h | 148 +- singletas.c | 483 ++-- singletas.h | 2 +- sinqhmtcl.c | 982 ++++---- site.h | 43 +- splitter.c | 862 ++++--- splitter.h | 103 +- statemon.c | 646 ++--- statemon.h | 12 +- statistics.c | 64 +- statistics.h | 6 +- status.c | 538 ++-- status.h | 58 +- statusfile.c | 443 ++-- statusfile.h | 19 +- stdscan.c | 1884 +++++++------- stdscan.h | 58 +- stptok.c | 68 +- stptok.h | 4 +- strdup.c | 33 +- stringdict.c | 480 ++-- stringdict.h | 30 +- strrepl.c | 43 +- synchronize.c | 307 +-- synchronize.h | 8 +- tacov.c | 710 +++--- tasdrive.c | 823 +++--- tasdrive.h | 9 +- task.c | 647 +++-- task.h | 107 +- tasscanub.c | 1438 +++++------ tasscanub.h | 38 +- tasub.c | 2302 +++++++++-------- tasub.h | 54 +- tasublib.c | 770 +++--- tasublib.h | 61 +- tcldrivable.c | 522 ++-- tcldrivable.h | 51 +- tclev.c | 936 ++++--- tclev.h | 15 +- tclintimpl.c | 145 +- tclintimpl.h | 10 +- tclmotdriv.c | 624 ++--- tclmotdriv.h | 58 +- telnet.c | 765 +++--- telnet.h | 15 +- token.c | 263 +- token.h | 34 +- trigd.c | 66 +- trigd.h | 20 +- trim.c | 92 +- ubcalc.c | 612 ++--- ubcalc.h | 15 +- ubfour.c | 533 ++-- ubfour.h | 35 +- udpquieck.c | 180 +- udpquieck.h | 8 +- ufortify.h | 34 +- uselect.c | 9 +- uselect.h | 4 +- userscan.c | 29 +- userscan.h | 2 +- uubuffer.c | 270 +- uubuffer.h | 17 +- uusend.c | 127 +- varlog.c | 663 +++-- varlog.h | 24 +- vector.c | 146 +- velo.c | 2234 ++++++++--------- velo.h | 34 +- velodriv.h | 47 +- velosim.c | 457 ++-- wwildcard.c | 83 +- xytable.c | 502 ++-- xytable.h | 20 +- 405 files changed, 88101 insertions(+), 88173 deletions(-) create mode 100644 countersec.c diff --git a/Busy.c b/Busy.c index 55e7c817..44b0d315 100644 --- a/Busy.c +++ b/Busy.c @@ -12,104 +12,119 @@ typedef struct BUSY__ { pObjectDescriptor pDes; int iBusy; - }Busy; +} Busy; /*---------------------------------------------------------------------*/ -busyPtr makeBusy(void){ +busyPtr makeBusy(void) +{ busyPtr result = NULL; - result = (busyPtr)malloc(sizeof(Busy)); - if(!result){ + result = (busyPtr) malloc(sizeof(Busy)); + if (!result) { return NULL; } result->pDes = CreateDescriptor("BusyFlag"); - if(!result->pDes){ + if (!result->pDes) { free(result); return NULL; } result->iBusy = 0; return result; } + /*---------------------------------------------------------------------*/ -void killBusy(void *self){ +void killBusy(void *self) +{ busyPtr busy; - if(self != NULL){ - busy = (busyPtr)self; - if(busy->pDes != NULL){ + if (self != NULL) { + busy = (busyPtr) self; + if (busy->pDes != NULL) { DeleteDescriptor(busy->pDes); } free(busy); } } + /*---------------------------------------------------------------------*/ -void incrementBusy(busyPtr self){ +void incrementBusy(busyPtr self) +{ assert(self != NULL); self->iBusy++; } + /*--------------------------------------------------------------------*/ -void decrementBusy(busyPtr self){ +void decrementBusy(busyPtr self) +{ assert(self != NULL); self->iBusy--; - if(self->iBusy < 0){ + if (self->iBusy < 0) { self->iBusy = 0; } } + /*--------------------------------------------------------------------*/ -void clearBusy(busyPtr self){ +void clearBusy(busyPtr self) +{ assert(self != NULL); self->iBusy = 0; } + /*--------------------------------------------------------------------*/ -void setBusy(busyPtr self, int val){ +void setBusy(busyPtr self, int val) +{ assert(self != NULL); self->iBusy = val; } + /*--------------------------------------------------------------------*/ -int isBusy(busyPtr self){ +int isBusy(busyPtr self) +{ assert(self != NULL); return self->iBusy; } + /*--------------------------------------------------------------------*/ -int BusyAction(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int BusyAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ busyPtr self = NULL; char pBuffer[80]; - self = (busyPtr)pData; + self = (busyPtr) pData; assert(self != NULL); - if(argc > 1){ + if (argc > 1) { strtolower(argv[1]); - if(usUser < SCGetRights(pCon)){ - SCWrite(pCon,"ERROR: no privilege to manipulate busy flag",eError); + if (usUser < SCGetRights(pCon)) { + SCWrite(pCon, "ERROR: no privilege to manipulate busy flag", eError); return 0; } - if(strcmp(argv[1],"incr") == 0){ + if (strcmp(argv[1], "incr") == 0) { incrementBusy(self); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"decr") == 0){ + } else if (strcmp(argv[1], "decr") == 0) { decrementBusy(self); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"clear") == 0){ + } else if (strcmp(argv[1], "clear") == 0) { clearBusy(self); SCSendOK(pCon); return 1; } } - - sprintf(pBuffer,"Busy = %d", isBusy(self)); - SCWrite(pCon,pBuffer,eValue); + + sprintf(pBuffer, "Busy = %d", isBusy(self)); + SCWrite(pCon, pBuffer, eValue); return 1; } + /*---------------------------------------------------------------------*/ -busyPtr findBusy(SicsInterp *pInter){ +busyPtr findBusy(SicsInterp * pInter) +{ CommandList *pCom = NULL; - pCom = FindCommand(pInter,"busy"); - if(pCom != NULL){ - return (busyPtr)pCom->pData; + pCom = FindCommand(pInter, "busy"); + if (pCom != NULL) { + return (busyPtr) pCom->pData; } } - - diff --git a/Busy.h b/Busy.h index 6718146d..65a48c5d 100644 --- a/Busy.h +++ b/Busy.h @@ -20,9 +20,8 @@ void setBusy(busyPtr self, int val); int isBusy(busyPtr self); -int BusyAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int BusyAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -busyPtr findBusy(SicsInterp *pInter); +busyPtr findBusy(SicsInterp * pInter); #endif - diff --git a/Dbg.c b/Dbg.c index eb0f6105..71d5c71d 100644 --- a/Dbg.c +++ b/Dbg.c @@ -40,8 +40,8 @@ char *Dbg_VarName = "dbg"; #define DEFAULT_COMPRESS 0 static int compress = DEFAULT_COMPRESS; -#define DEFAULT_WIDTH 75 /* leave a little space for printing */ - /* stack level */ +#define DEFAULT_WIDTH 75 /* leave a little space for printing */ + /* stack level */ static int buf_width = DEFAULT_WIDTH; static int main_argc = 1; @@ -49,148 +49,151 @@ static char *default_argv = "application"; static char **main_argv = &default_argv; static Tcl_Trace debug_handle; -static int step_count = 1; /* count next/step */ +static int step_count = 1; /* count next/step */ -#define FRAMENAMELEN 10 /* enough to hold strings like "#4" */ -static char viewFrameName[FRAMENAMELEN];/* destination frame name for up/down */ +#define FRAMENAMELEN 10 /* enough to hold strings like "#4" */ +static char viewFrameName[FRAMENAMELEN]; /* destination frame name for up/down */ -static CallFrame *goalFramePtr; /* destination for next/return */ -static int goalNumLevel; /* destination for Next */ +static CallFrame *goalFramePtr; /* destination for next/return */ +static int goalNumLevel; /* destination for Next */ static enum debug_cmd { - none, step, next, ret, cont, up, down, where, Next + none, step, next, ret, cont, up, down, where, Next } debug_cmd; /* this acts as a strobe (while testing breakpoints). It is set to true */ /* every time a new debugger command is issued that is an action */ static debug_new_action; -#define NO_LINE -1 /* if break point is not set by line number */ +#define NO_LINE -1 /* if break point is not set by line number */ struct breakpoint { - int id; - char *file; /* file where breakpoint is */ - int line; /* line where breakpoint is */ - char *pat; /* pattern defining where breakpoint can be */ - regexp *re; /* regular expression to trigger breakpoint */ - char *expr; /* expr to trigger breakpoint */ - char *cmd; /* cmd to eval at breakpoint */ - struct breakpoint *next, *previous; + int id; + char *file; /* file where breakpoint is */ + int line; /* line where breakpoint is */ + char *pat; /* pattern defining where breakpoint can be */ + regexp *re; /* regular expression to trigger breakpoint */ + char *expr; /* expr to trigger breakpoint */ + char *cmd; /* cmd to eval at breakpoint */ + struct breakpoint *next, *previous; }; static struct breakpoint *break_base = 0; static int breakpoint_max_id = 0; -static struct breakpoint * -breakpoint_new() +static struct breakpoint *breakpoint_new() { - struct breakpoint *b = (struct breakpoint *)ckalloc(sizeof(struct breakpoint)); - if (break_base) break_base->previous = b; - b->next = break_base; - b->previous = 0; - b->id = breakpoint_max_id++; - b->file = 0; - b->line = NO_LINE; - b->pat = 0; - b->re = 0; - b->expr = 0; - b->cmd = 0; - break_base = b; - return(b); + struct breakpoint *b = + (struct breakpoint *) ckalloc(sizeof(struct breakpoint)); + if (break_base) + break_base->previous = b; + b->next = break_base; + b->previous = 0; + b->id = breakpoint_max_id++; + b->file = 0; + b->line = NO_LINE; + b->pat = 0; + b->re = 0; + b->expr = 0; + b->cmd = 0; + break_base = b; + return (b); } static -void -breakpoint_print(interp,b) +void breakpoint_print(interp, b) Tcl_Interp *interp; struct breakpoint *b; { - print(interp,"breakpoint %d: ",b->id); + print(interp, "breakpoint %d: ", b->id); - if (b->re) { - print(interp,"-re \"%s\" ",b->pat); - } else if (b->pat) { - print(interp,"-glob \"%s\" ",b->pat); - } else if (b->line != NO_LINE) { - if (b->file) { - print(interp,"%s:",b->file); - } - print(interp,"%d ",b->line); - } + if (b->re) { + print(interp, "-re \"%s\" ", b->pat); + } else if (b->pat) { + print(interp, "-glob \"%s\" ", b->pat); + } else if (b->line != NO_LINE) { + if (b->file) { + print(interp, "%s:", b->file); + } + print(interp, "%d ", b->line); + } - if (b->expr) - print(interp,"if {%s} ",b->expr); + if (b->expr) + print(interp, "if {%s} ", b->expr); - if (b->cmd) - print(interp,"then {%s}",b->cmd); + if (b->cmd) + print(interp, "then {%s}", b->cmd); - putchar('\n'); + putchar('\n'); } -static void -save_re_matches(interp,re) +static void save_re_matches(interp, re) Tcl_Interp *interp; regexp *re; { - int i; - char name[20]; - char match_char;/* place to hold char temporarily */ - /* uprooted by a NULL */ + int i; + char name[20]; + char match_char; /* place to hold char temporarily */ + /* uprooted by a NULL */ - for (i=0;istartp[i] == 0) break; + for (i = 0; i < NSUBEXP; i++) { + if (re->startp[i] == 0) + break; - sprintf(name,"%d",i); - /* temporarily null-terminate in middle */ - match_char = *re->endp[i]; - *re->endp[i] = 0; - Tcl_SetVar2(interp,Dbg_VarName,name,re->startp[i],0); + sprintf(name, "%d", i); + /* temporarily null-terminate in middle */ + match_char = *re->endp[i]; + *re->endp[i] = 0; + Tcl_SetVar2(interp, Dbg_VarName, name, re->startp[i], 0); - /* undo temporary null-terminator */ - *re->endp[i] = match_char; - } + /* undo temporary null-terminator */ + *re->endp[i] = match_char; + } } /* return 1 to break, 0 to continue */ -static int -breakpoint_test(interp,cmd,bp) +static int breakpoint_test(interp, cmd, bp) Tcl_Interp *interp; -char *cmd; /* command about to be executed */ -struct breakpoint *bp; /* breakpoint to test */ +char *cmd; /* command about to be executed */ +struct breakpoint *bp; /* breakpoint to test */ { - if (bp->re) { + if (bp->re) { #if TCL_MAJOR_VERSION == 6 - if (0 == regexec(bp->re,cmd)) return 0; + if (0 == regexec(bp->re, cmd)) + return 0; #else - if (0 == TclRegExec(bp->re,cmd,cmd)) return 0; + if (0 == TclRegExec(bp->re, cmd, cmd)) + return 0; #endif - save_re_matches(interp,bp->re); - } else if (bp->pat) { - if (0 == Tcl_StringMatch(cmd,bp->pat)) return 0; - } else if (bp->line != NO_LINE) { - /* not yet implemented - awaiting support from Tcl */ - return 0; - } + save_re_matches(interp, bp->re); + } else if (bp->pat) { + if (0 == Tcl_StringMatch(cmd, bp->pat)) + return 0; + } else if (bp->line != NO_LINE) { + /* not yet implemented - awaiting support from Tcl */ + return 0; + } - if (bp->expr) { - int value; + if (bp->expr) { + int value; - /* ignore errors, since they are likely due to */ - /* simply being out of scope a lot */ - if (TCL_OK != Tcl_ExprBoolean(interp,bp->expr,&value)) return 0; - } + /* ignore errors, since they are likely due to */ + /* simply being out of scope a lot */ + if (TCL_OK != Tcl_ExprBoolean(interp, bp->expr, &value)) + return 0; + } - if (bp->cmd) { + if (bp->cmd) { #if TCL_MAJOR_VERSION == 6 - Tcl_Eval(interp,bp->cmd,0,(char **)0); + Tcl_Eval(interp, bp->cmd, 0, (char **) 0); #else - Tcl_Eval(interp,bp->cmd); + Tcl_Eval(interp, bp->cmd); #endif - } else { - breakpoint_print(interp,bp); - } + } else { + breakpoint_print(interp, bp); + } - return 1; + return 1; } static char *already_at_top_level = "already at top level"; @@ -201,243 +204,258 @@ If direction is down, simulate searching down stack by seaching up stack from origFrame */ static -int -TclGetFrame2(interp, origFramePtr, string, framePtrPtr, dir) - Tcl_Interp *interp; - CallFrame *origFramePtr; /* frame that is true top-of-stack */ - char *string; /* String describing frame. */ - CallFrame **framePtrPtr; /* Store pointer to frame here (or NULL - * if global frame indicated). */ - enum debug_cmd dir; /* look up or down the stack */ +int TclGetFrame2(interp, origFramePtr, string, framePtrPtr, dir) +Tcl_Interp *interp; +CallFrame *origFramePtr; /* frame that is true top-of-stack */ +char *string; /* String describing frame. */ +CallFrame **framePtrPtr; /* Store pointer to frame here (or NULL + * if global frame indicated). */ +enum debug_cmd dir; /* look up or down the stack */ { - Interp *iPtr = (Interp *) interp; - int level, result; - CallFrame *framePtr; /* frame currently being searched */ + Interp *iPtr = (Interp *) interp; + int level, result; + CallFrame *framePtr; /* frame currently being searched */ - CallFrame *curFramePtr = iPtr->varFramePtr; + CallFrame *curFramePtr = iPtr->varFramePtr; - /* - * Parse string to figure out which level number to go to. - */ + /* + * Parse string to figure out which level number to go to. + */ - result = 1; - if (*string == '#') { - if (Tcl_GetInt(interp, string+1, &level) != TCL_OK) { - return TCL_ERROR; - } - if (level < 0) { - levelError: - Tcl_AppendResult(interp, "bad level \"", string, "\"", - (char *) NULL); - return TCL_ERROR; - } - framePtr = origFramePtr; /* start search here */ - - } else if (isdigit(*string)) { - if (Tcl_GetInt(interp, string, &level) != TCL_OK) { - return TCL_ERROR; - } - if (dir == up) { - if (curFramePtr == 0) { - Tcl_SetResult(interp,already_at_top_level,TCL_STATIC); - return TCL_ERROR; - } - level = curFramePtr->level - level; - framePtr = curFramePtr; /* start search here */ - } else { - if (curFramePtr != 0) { - level = curFramePtr->level + level; - } - framePtr = origFramePtr; /* start search here */ - } - } else { - level = curFramePtr->level - 1; - result = 0; + result = 1; + if (*string == '#') { + if (Tcl_GetInt(interp, string + 1, &level) != TCL_OK) { + return TCL_ERROR; } - - /* - * Figure out which frame to use. - */ - - if (level == 0) { - framePtr = NULL; - } else { - for (;framePtr != NULL; framePtr = framePtr->callerVarPtr) { - if (framePtr->level == level) { - break; - } - } - if (framePtr == NULL) { - goto levelError; - } + if (level < 0) { + levelError: + Tcl_AppendResult(interp, "bad level \"", string, "\"", + (char *) NULL); + return TCL_ERROR; } - *framePtrPtr = framePtr; - return result; + framePtr = origFramePtr; /* start search here */ + + } else if (isdigit(*string)) { + if (Tcl_GetInt(interp, string, &level) != TCL_OK) { + return TCL_ERROR; + } + if (dir == up) { + if (curFramePtr == 0) { + Tcl_SetResult(interp, already_at_top_level, TCL_STATIC); + return TCL_ERROR; + } + level = curFramePtr->level - level; + framePtr = curFramePtr; /* start search here */ + } else { + if (curFramePtr != 0) { + level = curFramePtr->level + level; + } + framePtr = origFramePtr; /* start search here */ + } + } else { + level = curFramePtr->level - 1; + result = 0; + } + + /* + * Figure out which frame to use. + */ + + if (level == 0) { + framePtr = NULL; + } else { + for (; framePtr != NULL; framePtr = framePtr->callerVarPtr) { + if (framePtr->level == level) { + break; + } + } + if (framePtr == NULL) { + goto levelError; + } + } + *framePtrPtr = framePtr; + return result; } static char *printify(s) char *s; { - static int destlen = 0; - char *d; /* ptr into dest */ - unsigned int need; - static char buf_basic[DEFAULT_WIDTH+1]; - static char *dest = buf_basic; + static int destlen = 0; + char *d; /* ptr into dest */ + unsigned int need; + static char buf_basic[DEFAULT_WIDTH + 1]; + static char *dest = buf_basic; - if (s == 0) return(""); + if (s == 0) + return (""); - /* worst case is every character takes 4 to printify */ - need = strlen(s)*4; - if (need > destlen) { - if (dest && (dest != buf_basic)) free(dest); - dest = (char *)ckalloc(need+1); - destlen = need; - } + /* worst case is every character takes 4 to printify */ + need = strlen(s) * 4; + if (need > destlen) { + if (dest && (dest != buf_basic)) + free(dest); + dest = (char *) ckalloc(need + 1); + destlen = need; + } - for (d = dest;*s;s++) { - /* since we check at worst by every 4 bytes, play */ - /* conservative and subtract 4 from the limit */ - if (d-dest > destlen-4) break; + for (d = dest; *s; s++) { + /* since we check at worst by every 4 bytes, play */ + /* conservative and subtract 4 from the limit */ + if (d - dest > destlen - 4) + break; - if (*s == '\b') { - strcpy(d,"\\b"); d += 2; - } else if (*s == '\f') { - strcpy(d,"\\f"); d += 2; - } else if (*s == '\v') { - strcpy(d,"\\v"); d += 2; - } else if (*s == '\r') { - strcpy(d,"\\r"); d += 2; - } else if (*s == '\n') { - strcpy(d,"\\n"); d += 2; - } else if (*s == '\t') { - strcpy(d,"\\t"); d += 2; - } else if ((unsigned)*s < 0x20) { /* unsigned strips parity */ - sprintf(d,"\\%03o",*s); d += 4; - } else if (*s == 0177) { - strcpy(d,"\\177"); d += 4; - } else { - *d = *s; d += 1; - } - } - *d = '\0'; - return(dest); + if (*s == '\b') { + strcpy(d, "\\b"); + d += 2; + } else if (*s == '\f') { + strcpy(d, "\\f"); + d += 2; + } else if (*s == '\v') { + strcpy(d, "\\v"); + d += 2; + } else if (*s == '\r') { + strcpy(d, "\\r"); + d += 2; + } else if (*s == '\n') { + strcpy(d, "\\n"); + d += 2; + } else if (*s == '\t') { + strcpy(d, "\\t"); + d += 2; + } else if ((unsigned) *s < 0x20) { /* unsigned strips parity */ + sprintf(d, "\\%03o", *s); + d += 4; + } else if (*s == 0177) { + strcpy(d, "\\177"); + d += 4; + } else { + *d = *s; + d += 1; + } + } + *d = '\0'; + return (dest); } static -char * -print_argv(interp,argc,argv) +char *print_argv(interp, argc, argv) Tcl_Interp *interp; int argc; char *argv[]; { - static int buf_width_max = DEFAULT_WIDTH; - static char buf_basic[DEFAULT_WIDTH+1]; /* basic buffer */ - static char *buf = buf_basic; - int space; /* space remaining in buf */ - int len; - char *bufp; - int proc; /* if current command is "proc" */ - int arg_index; + static int buf_width_max = DEFAULT_WIDTH; + static char buf_basic[DEFAULT_WIDTH + 1]; /* basic buffer */ + static char *buf = buf_basic; + int space; /* space remaining in buf */ + int len; + char *bufp; + int proc; /* if current command is "proc" */ + int arg_index; - if (buf_width > buf_width_max) { - if (buf && (buf != buf_basic)) ckfree(buf); - buf = (char *)ckalloc(buf_width + 1); - buf_width_max = buf_width; - } + if (buf_width > buf_width_max) { + if (buf && (buf != buf_basic)) + ckfree(buf); + buf = (char *) ckalloc(buf_width + 1); + buf_width_max = buf_width; + } - proc = (0 == strcmp("proc",argv[0])); - sprintf(buf,"%.*s",buf_width,argv[0]); - len = strlen(buf); - space = buf_width - len; - bufp = buf + len; - argc--; argv++; - arg_index = 1; - - while (argc && (space > 0)) { - char *elementPtr; - char *nextPtr; - int wrap; + proc = (0 == strcmp("proc", argv[0])); + sprintf(buf, "%.*s", buf_width, argv[0]); + len = strlen(buf); + space = buf_width - len; + bufp = buf + len; + argc--; + argv++; + arg_index = 1; - /* braces/quotes have been stripped off arguments */ - /* so put them back. We wrap everything except lists */ - /* with one argument. One exception is to always wrap */ - /* proc's 2nd arg (the arg list), since people are */ - /* used to always seeing it this way. */ + while (argc && (space > 0)) { + char *elementPtr; + char *nextPtr; + int wrap; - if (proc && (arg_index > 1)) wrap = TRUE; - else { - (void) TclFindElement(interp,*argv,&elementPtr, - &nextPtr,(int *)0,(int *)0); - if (*elementPtr == '\0') wrap = TRUE; - else if (*nextPtr == '\0') wrap = FALSE; - else wrap = TRUE; - } + /* braces/quotes have been stripped off arguments */ + /* so put them back. We wrap everything except lists */ + /* with one argument. One exception is to always wrap */ + /* proc's 2nd arg (the arg list), since people are */ + /* used to always seeing it this way. */ - /* wrap lists (or null) in braces */ - if (wrap) { - sprintf(bufp," {%.*s}",space-3,*argv); - } else { - sprintf(bufp," %.*s",space-1,*argv); - } - len = strlen(buf); - space = buf_width - len; - bufp = buf + len; - argc--; argv++; - arg_index++; - } + if (proc && (arg_index > 1)) + wrap = TRUE; + else { + (void) TclFindElement(interp, *argv, &elementPtr, + &nextPtr, (int *) 0, (int *) 0); + if (*elementPtr == '\0') + wrap = TRUE; + else if (*nextPtr == '\0') + wrap = FALSE; + else + wrap = TRUE; + } - if (compress) { - /* this copies from our static buf to printify's static buf */ - /* and back to our static buf */ - strncpy(buf,printify(buf),buf_width); - } + /* wrap lists (or null) in braces */ + if (wrap) { + sprintf(bufp, " {%.*s}", space - 3, *argv); + } else { + sprintf(bufp, " %.*s", space - 1, *argv); + } + len = strlen(buf); + space = buf_width - len; + bufp = buf + len; + argc--; + argv++; + arg_index++; + } - /* usually but not always right, but assume truncation if buffer is */ - /* full. this avoids tiny but odd-looking problem of appending "}" */ - /* to truncated lists during {}-wrapping earlier */ - if (strlen(buf) == buf_width) { - buf[buf_width-1] = buf[buf_width-2] = buf[buf_width-3] = '.'; - } + if (compress) { + /* this copies from our static buf to printify's static buf */ + /* and back to our static buf */ + strncpy(buf, printify(buf), buf_width); + } - return(buf); + /* usually but not always right, but assume truncation if buffer is */ + /* full. this avoids tiny but odd-looking problem of appending "}" */ + /* to truncated lists during {}-wrapping earlier */ + if (strlen(buf) == buf_width) { + buf[buf_width - 1] = buf[buf_width - 2] = buf[buf_width - 3] = '.'; + } + + return (buf); } static -void -PrintStackBelow(interp,curf,viewf) +void PrintStackBelow(interp, curf, viewf) Tcl_Interp *interp; -CallFrame *curf; /* current FramePtr */ -CallFrame *viewf; /* view FramePtr */ +CallFrame *curf; /* current FramePtr */ +CallFrame *viewf; /* view FramePtr */ { - char ptr; /* graphically indicate where we are in the stack */ + char ptr; /* graphically indicate where we are in the stack */ - /* indicate where we are in the stack */ - ptr = ((curf == viewf)?'*':' '); + /* indicate where we are in the stack */ + ptr = ((curf == viewf) ? '*' : ' '); - if (curf == 0) { - print(interp,"%c0: %s\n", - ptr,print_argv(interp,main_argc,main_argv)); - } else { - PrintStackBelow(interp,curf->callerVarPtr,viewf); - print(interp,"%c%d: %s\n",ptr,curf->level, - print_argv(interp,curf->argc,curf->argv)); - } + if (curf == 0) { + print(interp, "%c0: %s\n", + ptr, print_argv(interp, main_argc, main_argv)); + } else { + PrintStackBelow(interp, curf->callerVarPtr, viewf); + print(interp, "%c%d: %s\n", ptr, curf->level, + print_argv(interp, curf->argc, curf->argv)); + } } static -void -PrintStack(interp,curf,viewf,argc,argv,level) +void PrintStack(interp, curf, viewf, argc, argv, level) Tcl_Interp *interp; -CallFrame *curf; /* current FramePtr */ -CallFrame *viewf; /* view FramePtr */ +CallFrame *curf; /* current FramePtr */ +CallFrame *viewf; /* view FramePtr */ int argc; char *argv[]; char *level; { - PrintStackBelow(interp,curf,viewf); - - print(interp," %s: %s\n",level,print_argv(interp,argc,argv)); + PrintStackBelow(interp, curf, viewf); + + print(interp, " %s: %s\n", level, print_argv(interp, argc, argv)); } /* return 0 if goal matches current frame or goal can't be found */ @@ -448,759 +466,778 @@ char *level; /* or Tcl_Eval. These builtin calls to Tcl_Eval lose any knowledge */ /* the FramePtr from the proc, so we have to search the entire */ /* stack frame to see if it's still there. */ -static int -GoalFrame(goal,iptr) +static int GoalFrame(goal, iptr) CallFrame *goal; Interp *iptr; { - CallFrame *cf = iptr->varFramePtr; + CallFrame *cf = iptr->varFramePtr; - /* if at current level, return success immediately */ - if (goal == cf) return 0; + /* if at current level, return success immediately */ + if (goal == cf) + return 0; - while (cf) { - cf = cf->callerVarPtr; - if (goal == cf) { - /* found, but since it's above us, fail */ - return 1; - } - } - return 0; + while (cf) { + cf = cf->callerVarPtr; + if (goal == cf) { + /* found, but since it's above us, fail */ + return 1; + } + } + return 0; } /* debugger's trace handler */ -/*ARGSUSED*/ -static void -debugger_trap(clientData,interp,level,command,cmdProc,cmdClientData,argc,argv) -ClientData clientData; /* not used */ + /*ARGSUSED*/ + static void +debugger_trap(clientData, interp, level, command, cmdProc, cmdClientData, + argc, argv) +ClientData clientData; /* not used */ Tcl_Interp *interp; -int level; /* positive number if called by Tcl, -1 if */ - /* called by Dbg_On in which case we don't */ - /* know the level */ +int level; /* positive number if called by Tcl, -1 if */ + /* called by Dbg_On in which case we don't */ + /* know the level */ char *command; -int (*cmdProc)(); /* not used */ +int (*cmdProc) (); /* not used */ ClientData cmdClientData; int argc; char *argv[]; { - char level_text[6]; /* textual representation of level */ + char level_text[6]; /* textual representation of level */ - int break_status; - Interp *iPtr = (Interp *)interp; + int break_status; + Interp *iPtr = (Interp *) interp; - CallFrame *trueFramePtr; /* where the pc is */ - CallFrame *viewFramePtr; /* where up/down are */ + CallFrame *trueFramePtr; /* where the pc is */ + CallFrame *viewFramePtr; /* where up/down are */ - int print_command_first_time = TRUE; - static int debug_suspended = FALSE; + int print_command_first_time = TRUE; + static int debug_suspended = FALSE; - struct breakpoint *b; + struct breakpoint *b; - /* skip commands that are invoked interactively */ - if (debug_suspended) return; + /* skip commands that are invoked interactively */ + if (debug_suspended) + return; - /* skip debugger commands */ - if (argv[0][1] == '\0') { - switch (argv[0][0]) { - case 'n': - case 's': - case 'c': - case 'r': - case 'w': - case 'b': - case 'u': - case 'd': return; - } - } + /* skip debugger commands */ + if (argv[0][1] == '\0') { + switch (argv[0][0]) { + case 'n': + case 's': + case 'c': + case 'r': + case 'w': + case 'b': + case 'u': + case 'd': + return; + } + } - if ((*ignoreproc)(interp,argv[0])) return; + if ((*ignoreproc) (interp, argv[0])) + return; - /* if level is unknown, use "?" */ - sprintf(level_text,(level == -1)?"?":"%d",level); + /* if level is unknown, use "?" */ + sprintf(level_text, (level == -1) ? "?" : "%d", level); - /* save so we can restore later */ - trueFramePtr = iPtr->varFramePtr; + /* save so we can restore later */ + trueFramePtr = iPtr->varFramePtr; - /* test all breakpoints to see if we should break */ - debug_suspended = TRUE; + /* test all breakpoints to see if we should break */ + debug_suspended = TRUE; - /* if any successful breakpoints, start interactor */ - debug_new_action = FALSE; /* reset strobe */ - break_status = FALSE; /* no successful breakpoints yet */ - for (b = break_base;b;b=b->next) { - break_status |= breakpoint_test(interp,command,b); - } - if (!debug_new_action && break_status) goto start_interp; + /* if any successful breakpoints, start interactor */ + debug_new_action = FALSE; /* reset strobe */ + break_status = FALSE; /* no successful breakpoints yet */ + for (b = break_base; b; b = b->next) { + break_status |= breakpoint_test(interp, command, b); + } + if (!debug_new_action && break_status) + goto start_interp; - /* if s or n triggered by breakpoint, make "s 1" (and so on) */ - /* refer to next command, not this one */ - if (debug_new_action) step_count++; + /* if s or n triggered by breakpoint, make "s 1" (and so on) */ + /* refer to next command, not this one */ + if (debug_new_action) + step_count++; - switch (debug_cmd) { - case cont: - goto finish; - case step: - step_count--; - if (step_count > 0) goto finish; - goto start_interp; - case next: - /* check if we are back at the same level where the next */ - /* command was issued. Also test */ - /* against all FramePtrs and if no match, assume that */ - /* we've missed a return, and so we should break */ + switch (debug_cmd) { + case cont: + goto finish; + case step: + step_count--; + if (step_count > 0) + goto finish; + goto start_interp; + case next: + /* check if we are back at the same level where the next */ + /* command was issued. Also test */ + /* against all FramePtrs and if no match, assume that */ + /* we've missed a return, and so we should break */ /* if (goalFramePtr != iPtr->varFramePtr) goto finish;*/ - if (GoalFrame(goalFramePtr,iPtr)) goto finish; - step_count--; - if (step_count > 0) goto finish; - goto start_interp; - case Next: - /* check if we are back at the same level where the next */ - /* command was issued. */ - if (goalNumLevel < iPtr->numLevels) goto finish; - step_count--; - if (step_count > 0) goto finish; - goto start_interp; - case ret: - /* same comment as in "case next" */ - if (goalFramePtr != iPtr->varFramePtr) goto finish; - goto start_interp; - } + if (GoalFrame(goalFramePtr, iPtr)) + goto finish; + step_count--; + if (step_count > 0) + goto finish; + goto start_interp; + case Next: + /* check if we are back at the same level where the next */ + /* command was issued. */ + if (goalNumLevel < iPtr->numLevels) + goto finish; + step_count--; + if (step_count > 0) + goto finish; + goto start_interp; + case ret: + /* same comment as in "case next" */ + if (goalFramePtr != iPtr->varFramePtr) + goto finish; + goto start_interp; + } start_interp: - if (print_command_first_time) { - print(interp,"%s: %s\n", - level_text,print_argv(interp,1,&command)); - print_command_first_time = FALSE; - } - /* since user is typing a command, don't interrupt it immediately */ - debug_cmd = cont; - debug_suspended = FALSE; + if (print_command_first_time) { + print(interp, "%s: %s\n", level_text, print_argv(interp, 1, &command)); + print_command_first_time = FALSE; + } + /* since user is typing a command, don't interrupt it immediately */ + debug_cmd = cont; + debug_suspended = FALSE; - /* interactor won't return until user gives a debugger cmd */ - (*interactor)(interp); + /* interactor won't return until user gives a debugger cmd */ + (*interactor) (interp); - /* save this so it can be restored after "w" command */ - viewFramePtr = iPtr->varFramePtr; + /* save this so it can be restored after "w" command */ + viewFramePtr = iPtr->varFramePtr; - if (debug_cmd == up || debug_cmd == down) { - /* calculate new frame */ - if (-1 == TclGetFrame2(interp,trueFramePtr,viewFrameName, - &iPtr->varFramePtr,debug_cmd)) { - print(interp,"%s\n",interp->result); - Tcl_ResetResult(interp); - } - goto start_interp; - } + if (debug_cmd == up || debug_cmd == down) { + /* calculate new frame */ + if (-1 == TclGetFrame2(interp, trueFramePtr, viewFrameName, + &iPtr->varFramePtr, debug_cmd)) { + print(interp, "%s\n", interp->result); + Tcl_ResetResult(interp); + } + goto start_interp; + } - /* reset view back to normal */ - iPtr->varFramePtr = trueFramePtr; + /* reset view back to normal */ + iPtr->varFramePtr = trueFramePtr; - /* allow trapping */ - debug_suspended = FALSE; + /* allow trapping */ + debug_suspended = FALSE; - switch (debug_cmd) { - case cont: - case step: - goto finish; - case next: - goalFramePtr = iPtr->varFramePtr; - goto finish; - case Next: - goalNumLevel = iPtr->numLevels; - goto finish; - case ret: - goalFramePtr = iPtr->varFramePtr; - if (goalFramePtr == 0) { - print(interp,"nowhere to return to\n"); - break; - } - goalFramePtr = goalFramePtr->callerVarPtr; - goto finish; - case where: - PrintStack(interp,iPtr->varFramePtr,viewFramePtr,argc,argv,level_text); - break; - } + switch (debug_cmd) { + case cont: + case step: + goto finish; + case next: + goalFramePtr = iPtr->varFramePtr; + goto finish; + case Next: + goalNumLevel = iPtr->numLevels; + goto finish; + case ret: + goalFramePtr = iPtr->varFramePtr; + if (goalFramePtr == 0) { + print(interp, "nowhere to return to\n"); + break; + } + goalFramePtr = goalFramePtr->callerVarPtr; + goto finish; + case where: + PrintStack(interp, iPtr->varFramePtr, viewFramePtr, argc, argv, + level_text); + break; + } - /* restore view and restart interactor */ - iPtr->varFramePtr = viewFramePtr; - goto start_interp; + /* restore view and restart interactor */ + iPtr->varFramePtr = viewFramePtr; + goto start_interp; - finish: - debug_suspended = FALSE; +finish: + debug_suspended = FALSE; } -/*ARGSUSED*/ -static -int -cmdNext(clientData, interp, argc, argv) + /*ARGSUSED*/ static +int cmdNext(clientData, interp, argc, argv) ClientData clientData; Tcl_Interp *interp; int argc; char **argv; { - debug_cmd = *(enum debug_cmd *)clientData; - debug_new_action = TRUE; + debug_cmd = *(enum debug_cmd *) clientData; + debug_new_action = TRUE; - step_count = (argc == 1)?1:atoi(argv[1]); - return(TCL_RETURN); + step_count = (argc == 1) ? 1 : atoi(argv[1]); + return (TCL_RETURN); } -/*ARGSUSED*/ -static -int -cmdDir(clientData, interp, argc, argv) + /*ARGSUSED*/ static +int cmdDir(clientData, interp, argc, argv) ClientData clientData; Tcl_Interp *interp; int argc; char **argv; { - debug_cmd = *(enum debug_cmd *)clientData; + debug_cmd = *(enum debug_cmd *) clientData; - if (argc == 1) argv[1] = "1"; - strncpy(viewFrameName,argv[1],FRAMENAMELEN); + if (argc == 1) + argv[1] = "1"; + strncpy(viewFrameName, argv[1], FRAMENAMELEN); - return TCL_RETURN; + return TCL_RETURN; } -/*ARGSUSED*/ -static -int -cmdSimple(clientData, interp, argc, argv) + /*ARGSUSED*/ static +int cmdSimple(clientData, interp, argc, argv) ClientData clientData; Tcl_Interp *interp; int argc; char **argv; { - debug_cmd = *(enum debug_cmd *)clientData; - debug_new_action = TRUE; - return TCL_RETURN; + debug_cmd = *(enum debug_cmd *) clientData; + debug_new_action = TRUE; + return TCL_RETURN; } static -void -breakpoint_destroy(b) +void breakpoint_destroy(b) struct breakpoint *b; { - if (b->file) ckfree(b->file); - if (b->pat) ckfree(b->pat); - if (b->re) ckfree((char *)b->re); - if (b->cmd) ckfree(b->cmd); + if (b->file) + ckfree(b->file); + if (b->pat) + ckfree(b->pat); + if (b->re) + ckfree((char *) b->re); + if (b->cmd) + ckfree(b->cmd); - /* unlink from chain */ - if ((b->previous == 0) && (b->next == 0)) { - break_base = 0; - } else if (b->previous == 0) { - break_base = b->next; - b->next->previous = 0; - } else if (b->next == 0) { - b->previous->next = 0; - } else { - b->previous->next = b->next; - b->next->previous = b->previous; - } + /* unlink from chain */ + if ((b->previous == 0) && (b->next == 0)) { + break_base = 0; + } else if (b->previous == 0) { + break_base = b->next; + b->next->previous = 0; + } else if (b->next == 0) { + b->previous->next = 0; + } else { + b->previous->next = b->next; + b->next->previous = b->previous; + } - ckfree((char *)b); + ckfree((char *) b); } -static void -savestr(straddr,str) +static void savestr(straddr, str) char **straddr; char *str; { - *straddr = ckalloc(strlen(str)+1); - strcpy(*straddr,str); + *straddr = ckalloc(strlen(str) + 1); + strcpy(*straddr, str); } /* return 1 if a string is substring of a flag */ -static int -flageq(flag,string,minlen) +static int flageq(flag, string, minlen) char *flag; char *string; -int minlen; /* at least this many chars must match */ +int minlen; /* at least this many chars must match */ { - for (;*flag;flag++,string++,minlen--) { - if (*string == '\0') break; - if (*string != *flag) return 0; - } - if (*string == '\0' && minlen <= 0) return 1; - return 0; + for (; *flag; flag++, string++, minlen--) { + if (*string == '\0') + break; + if (*string != *flag) + return 0; + } + if (*string == '\0' && minlen <= 0) + return 1; + return 0; } -/*ARGSUSED*/ -static -int -cmdWhere(clientData, interp, argc, argv) + /*ARGSUSED*/ static +int cmdWhere(clientData, interp, argc, argv) ClientData clientData; Tcl_Interp *interp; int argc; char **argv; { - if (argc == 1) { - debug_cmd = where; - return TCL_RETURN; - } + if (argc == 1) { + debug_cmd = where; + return TCL_RETURN; + } - argc--; argv++; + argc--; + argv++; - while (argc) { - if (flageq("-width",*argv,2)) { - argc--; argv++; - if (*argv) { - buf_width = atoi(*argv); - argc--; argv++; - } else print(interp,"%d\n",buf_width); - } else if (flageq("-compress",*argv,2)) { - argc--; argv++; - if (*argv) { - compress = atoi(*argv); - argc--; argv++; - } else print(interp,"%d\n",compress); - } else { - print(interp,"usage: w [-width #] [-compress 0|1]\n"); - return TCL_ERROR; - } - } - return TCL_OK; + while (argc) { + if (flageq("-width", *argv, 2)) { + argc--; + argv++; + if (*argv) { + buf_width = atoi(*argv); + argc--; + argv++; + } else + print(interp, "%d\n", buf_width); + } else if (flageq("-compress", *argv, 2)) { + argc--; + argv++; + if (*argv) { + compress = atoi(*argv); + argc--; + argv++; + } else + print(interp, "%d\n", compress); + } else { + print(interp, "usage: w [-width #] [-compress 0|1]\n"); + return TCL_ERROR; + } + } + return TCL_OK; } #define breakpoint_fail(msg) {error_msg = msg; goto break_fail;} -/*ARGSUSED*/ -static -int -cmdBreak(clientData, interp, argc, argv) + /*ARGSUSED*/ static +int cmdBreak(clientData, interp, argc, argv) ClientData clientData; Tcl_Interp *interp; int argc; char **argv; { - struct breakpoint *b; - char *error_msg; + struct breakpoint *b; + char *error_msg; - argc--; argv++; + argc--; + argv++; - if (argc < 1) { - for (b = break_base;b;b=b->next) breakpoint_print(interp,b); - return(TCL_OK); - } + if (argc < 1) { + for (b = break_base; b; b = b->next) + breakpoint_print(interp, b); + return (TCL_OK); + } - if (argv[0][0] == '-') { - if (argv[0][1] == '\0') { - while (break_base) { - breakpoint_destroy(break_base); - } - breakpoint_max_id = 0; - return(TCL_OK); - } else if (isdigit(argv[0][1])) { - int id = atoi(argv[0]+1); + if (argv[0][0] == '-') { + if (argv[0][1] == '\0') { + while (break_base) { + breakpoint_destroy(break_base); + } + breakpoint_max_id = 0; + return (TCL_OK); + } else if (isdigit(argv[0][1])) { + int id = atoi(argv[0] + 1); - for (b = break_base;b;b=b->next) { - if (b->id == id) { - breakpoint_destroy(b); - if (!break_base) breakpoint_max_id = 0; - return(TCL_OK); - } - } - Tcl_SetResult(interp,"no such breakpoint",TCL_STATIC); - return(TCL_ERROR); - } - } + for (b = break_base; b; b = b->next) { + if (b->id == id) { + breakpoint_destroy(b); + if (!break_base) + breakpoint_max_id = 0; + return (TCL_OK); + } + } + Tcl_SetResult(interp, "no such breakpoint", TCL_STATIC); + return (TCL_ERROR); + } + } - b = breakpoint_new(); + b = breakpoint_new(); - if (flageq("-regexp",argv[0],2)) { - argc--; argv++; + if (flageq("-regexp", argv[0], 2)) { + argc--; + argv++; #if TCL_MAJOR_VERSION == 6 - if ((argc > 0) && (b->re = regcomp(argv[0]))) { + if ((argc > 0) && (b->re = regcomp(argv[0]))) { #else - if ((argc > 0) && (b->re = TclRegComp(argv[0]))) { + if ((argc > 0) && (b->re = TclRegComp(argv[0]))) { #endif - savestr(&b->pat,argv[0]); - argc--; argv++; - } else { - breakpoint_fail("bad regular expression") - } - } else if (flageq("-glob",argv[0],2)) { - argc--; argv++; - if (argc > 0) { - savestr(&b->pat,argv[0]); - argc--; argv++; - } else { - breakpoint_fail("no pattern?"); - } - } else if ((!(flageq("if",*argv,1)) && (!(flageq("then",*argv,1))))) { - /* look for [file:]line */ - char *colon; - char *linep; /* pointer to beginning of line number */ + savestr(&b->pat, argv[0]); + argc--; + argv++; + } else { + breakpoint_fail("bad regular expression") + } + } else if (flageq("-glob", argv[0], 2)) { + argc--; + argv++; + if (argc > 0) { + savestr(&b->pat, argv[0]); + argc--; + argv++; + } else { + breakpoint_fail("no pattern?"); + } + } else if ((!(flageq("if", *argv, 1)) && (!(flageq("then", *argv, 1))))) { + /* look for [file:]line */ + char *colon; + char *linep; /* pointer to beginning of line number */ - colon = strchr(argv[0],':'); - if (colon) { - *colon = '\0'; - savestr(&b->file,argv[0]); - *colon = ':'; - linep = colon + 1; - } else { - linep = argv[0]; - /* get file from current scope */ - /* savestr(&b->file, ?); */ - } + colon = strchr(argv[0], ':'); + if (colon) { + *colon = '\0'; + savestr(&b->file, argv[0]); + *colon = ':'; + linep = colon + 1; + } else { + linep = argv[0]; + /* get file from current scope */ + /* savestr(&b->file, ?); */ + } - if (TCL_OK == Tcl_GetInt(interp,linep,&b->line)) { - argc--; argv++; - print(interp,"setting breakpoints by line number is currently unimplemented - use patterns or expressions\n"); - } else { - /* not an int? - unwind & assume it is an expression */ + if (TCL_OK == Tcl_GetInt(interp, linep, &b->line)) { + argc--; + argv++; + print(interp, + "setting breakpoints by line number is currently unimplemented - use patterns or expressions\n"); + } else { + /* not an int? - unwind & assume it is an expression */ - if (b->file) ckfree(b->file); - } - } + if (b->file) + ckfree(b->file); + } + } - if (argc > 0) { - int do_if = FALSE; + if (argc > 0) { + int do_if = FALSE; - if (flageq("if",argv[0],1)) { - argc--; argv++; - do_if = TRUE; - } else if (!flageq("then",argv[0],1)) { - do_if = TRUE; - } + if (flageq("if", argv[0], 1)) { + argc--; + argv++; + do_if = TRUE; + } else if (!flageq("then", argv[0], 1)) { + do_if = TRUE; + } - if (do_if) { - if (argc < 1) { - breakpoint_fail("if what"); - } + if (do_if) { + if (argc < 1) { + breakpoint_fail("if what"); + } - savestr(&b->expr,argv[0]); - argc--; argv++; - } - } + savestr(&b->expr, argv[0]); + argc--; + argv++; + } + } - if (argc > 0) { - if (flageq("then",argv[0],1)) { - argc--; argv++; - } + if (argc > 0) { + if (flageq("then", argv[0], 1)) { + argc--; + argv++; + } - if (argc < 1) { - breakpoint_fail("then what?"); - } + if (argc < 1) { + breakpoint_fail("then what?"); + } - savestr(&b->cmd,argv[0]); - } + savestr(&b->cmd, argv[0]); + } - sprintf(interp->result,"%d",b->id); - return(TCL_OK); + sprintf(interp->result, "%d", b->id); + return (TCL_OK); - break_fail: - breakpoint_destroy(b); - Tcl_SetResult(interp,error_msg,TCL_STATIC); - return(TCL_ERROR); +break_fail: + breakpoint_destroy(b); + Tcl_SetResult(interp, error_msg, TCL_STATIC); + return (TCL_ERROR); } static char *help[] = { -"s [#] step into procedure", -"n [#] step over procedure", -"N [#] step over procedures, commands, and arguments", -"c continue", -"r continue until return to caller", -"u [#] move scope up level", -"d [#] move scope down level", -" go to absolute frame if # is prefaced by \"#\"", -"w show stack (\"where\")", -"w -w [#] show/set width", -"w -c [0|1] show/set compress", -"b show breakpoints", -"b [-r regexp-pattern] [if expr] [then command]", -"b [-g glob-pattern] [if expr] [then command]", -"b [[file:]#] [if expr] [then command]", -" if pattern given, break if command resembles pattern", -" if # given, break on line #", -" if expr given, break if expr true", -" if command given, execute command at breakpoint", -"b -# delete breakpoint", -"b - delete all breakpoints", -0}; + "s [#] step into procedure", + "n [#] step over procedure", + "N [#] step over procedures, commands, and arguments", + "c continue", + "r continue until return to caller", + "u [#] move scope up level", + "d [#] move scope down level", + " go to absolute frame if # is prefaced by \"#\"", + "w show stack (\"where\")", + "w -w [#] show/set width", + "w -c [0|1] show/set compress", + "b show breakpoints", + "b [-r regexp-pattern] [if expr] [then command]", + "b [-g glob-pattern] [if expr] [then command]", + "b [[file:]#] [if expr] [then command]", + " if pattern given, break if command resembles pattern", + " if # given, break on line #", + " if expr given, break if expr true", + " if command given, execute command at breakpoint", + "b -# delete breakpoint", + "b - delete all breakpoints", + 0 +}; -/*ARGSUSED*/ -static -int -cmdHelp(clientData, interp, argc, argv) + /*ARGSUSED*/ static +int cmdHelp(clientData, interp, argc, argv) ClientData clientData; Tcl_Interp *interp; int argc; char **argv; { - char **hp; + char **hp; - for (hp=help;*hp;hp++) { - print(interp,"%s\n",*hp); - } + for (hp = help; *hp; hp++) { + print(interp, "%s\n", *hp); + } - return(TCL_OK); + return (TCL_OK); } /* this may seem excessive, but this avoids the explicit test for non-zero */ /* in the caller, and chances are that that test will always be pointless */ -/*ARGSUSED*/ -static int zero(interp,string) + /*ARGSUSED*/ static int zero(interp, string) Tcl_Interp *interp; char *string; { - return 0; + return 0; } -static int -simple_interactor(interp) +static int simple_interactor(interp) Tcl_Interp *interp; { - int rc; - char *ccmd; /* pointer to complete command */ - char line[BUFSIZ+1]; /* space for partial command */ - int newcmd = TRUE; - Interp *iPtr = (Interp *)interp; + int rc; + char *ccmd; /* pointer to complete command */ + char line[BUFSIZ + 1]; /* space for partial command */ + int newcmd = TRUE; + Interp *iPtr = (Interp *) interp; #if TCL_MAJOR_VERSION == 6 - Tcl_CmdBuf buffer; + Tcl_CmdBuf buffer; - if (!(buffer = Tcl_CreateCmdBuf())) { - Tcl_AppendElement(interp,"no more space for cmd buffer",0); - return(TCL_ERROR); - } + if (!(buffer = Tcl_CreateCmdBuf())) { + Tcl_AppendElement(interp, "no more space for cmd buffer", 0); + return (TCL_ERROR); + } #else - Tcl_DString dstring; - Tcl_DStringInit(&dstring); + Tcl_DString dstring; + Tcl_DStringInit(&dstring); #endif - newcmd = TRUE; - while (TRUE) { - if (newcmd) { - print(interp,"dbg%d.%d> ",iPtr->numLevels,iPtr->curEventNum+1); - } else { - print(interp,"dbg+> "); - } - fflush(stdout); + newcmd = TRUE; + while (TRUE) { + if (newcmd) { + print(interp, "dbg%d.%d> ", iPtr->numLevels, iPtr->curEventNum + 1); + } else { + print(interp, "dbg+> "); + } + fflush(stdout); - if (0 >= (rc = read(0,line,BUFSIZ))) { - if (!newcmd) line[0] = 0; - else exit(0); - } else line[rc] = '\0'; + if (0 >= (rc = read(0, line, BUFSIZ))) { + if (!newcmd) + line[0] = 0; + else + exit(0); + } else + line[rc] = '\0'; #if TCL_MAJOR_VERSION == 6 - if (NULL == (ccmd = Tcl_AssembleCmd(buffer,line))) { + if (NULL == (ccmd = Tcl_AssembleCmd(buffer, line))) { #else - ccmd = Tcl_DStringAppend(&dstring,line,rc); - if (!Tcl_CommandComplete(ccmd)) { + ccmd = Tcl_DStringAppend(&dstring, line, rc); + if (!Tcl_CommandComplete(ccmd)) { #endif - newcmd = FALSE; - continue; /* continue collecting command */ - } - newcmd = TRUE; + newcmd = FALSE; + continue; /* continue collecting command */ + } + newcmd = TRUE; - rc = Tcl_RecordAndEval(interp,ccmd,0); + rc = Tcl_RecordAndEval(interp, ccmd, 0); #if TCL_MAJOR_VERSION != 6 - Tcl_DStringFree(&dstring); + Tcl_DStringFree(&dstring); #endif - switch (rc) { - case TCL_OK: - if (*interp->result != 0) - print(interp,"%s\n",interp->result); - continue; - case TCL_ERROR: - print(interp,"%s\n",Tcl_GetVar(interp,"errorInfo",TCL_GLOBAL_ONLY)); - /* since user is typing by hand, we expect lots - of errors, and want to give another chance */ - continue; - case TCL_BREAK: - case TCL_CONTINUE: + switch (rc) { + case TCL_OK: + if (*interp->result != 0) + print(interp, "%s\n", interp->result); + continue; + case TCL_ERROR: + print(interp, "%s\n", + Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY)); + /* since user is typing by hand, we expect lots + of errors, and want to give another chance */ + continue; + case TCL_BREAK: + case TCL_CONTINUE: #define finish(x) {rc = x; goto done;} - finish(rc); - case TCL_RETURN: - finish(TCL_OK); - default: - /* note that ccmd has trailing newline */ - print(interp,"error %d: %s\n",rc,ccmd); - continue; - } - } - /* cannot fall thru here, must jump to label */ - done: + finish(rc); + case TCL_RETURN: + finish(TCL_OK); + default: + /* note that ccmd has trailing newline */ + print(interp, "error %d: %s\n", rc, ccmd); + continue; + } + } + /* cannot fall thru here, must jump to label */ +done: #if TCL_MAJOR_VERSION == 6 - /* currently, code guarantees buffer is valid */ - Tcl_DeleteCmdBuf(buffer); + /* currently, code guarantees buffer is valid */ + Tcl_DeleteCmdBuf(buffer); #else - Tcl_DStringFree(&dstring); + Tcl_DStringFree(&dstring); #endif - return(rc); + return (rc); } /* occasionally, we print things larger buf_max but not by much */ /* see print statements in PrintStack routines for examples */ #define PAD 80 -static void -print(va_alist ) +static void print(va_alist) va_dcl { - Tcl_Interp *interp; - char *fmt; - va_list args; + Tcl_Interp *interp; + char *fmt; + va_list args; - va_start(args); - interp = va_arg(args,Tcl_Interp *); - fmt = va_arg(args,char *); - if (!printproc) vprintf(fmt,args); - else { - static int buf_width_max = DEFAULT_WIDTH+PAD; - static char buf_basic[DEFAULT_WIDTH+PAD+1]; - static char *buf = buf_basic; + va_start(args); + interp = va_arg(args, Tcl_Interp *); + fmt = va_arg(args, char *); + if (!printproc) + vprintf(fmt, args); + else { + static int buf_width_max = DEFAULT_WIDTH + PAD; + static char buf_basic[DEFAULT_WIDTH + PAD + 1]; + static char *buf = buf_basic; - if (buf_width+PAD > buf_width_max) { - if (buf && (buf != buf_basic)) ckfree(buf); - buf = (char *)ckalloc(buf_width+PAD+1); - buf_width_max = buf_width+PAD; - } + if (buf_width + PAD > buf_width_max) { + if (buf && (buf != buf_basic)) + ckfree(buf); + buf = (char *) ckalloc(buf_width + PAD + 1); + buf_width_max = buf_width + PAD; + } - vsprintf(buf,fmt,args); - (*printproc)(interp,buf); - } - va_end(args); + vsprintf(buf, fmt, args); + (*printproc) (interp, buf); + } + va_end(args); } -/*ARGSUSED*/ -Dbg_InterProc * -Dbg_Interactor(interp,inter_proc) + /*ARGSUSED*/ Dbg_InterProc * Dbg_Interactor(interp, inter_proc) Tcl_Interp *interp; Dbg_InterProc *inter_proc; { - Dbg_InterProc *tmp = interactor; - interactor = (inter_proc?inter_proc:simple_interactor); - return tmp; + Dbg_InterProc *tmp = interactor; + interactor = (inter_proc ? inter_proc : simple_interactor); + return tmp; } -/*ARGSUSED*/ -Dbg_IgnoreFuncsProc * -Dbg_IgnoreFuncs(interp,proc) + /*ARGSUSED*/ Dbg_IgnoreFuncsProc * Dbg_IgnoreFuncs(interp, proc) Tcl_Interp *interp; Dbg_IgnoreFuncsProc *proc; { - Dbg_IgnoreFuncsProc *tmp = ignoreproc; - ignoreproc = (proc?proc:zero); - return tmp; + Dbg_IgnoreFuncsProc *tmp = ignoreproc; + ignoreproc = (proc ? proc : zero); + return tmp; } -/*ARGSUSED*/ -Dbg_OutputProc * -Dbg_Output(interp,proc) + /*ARGSUSED*/ Dbg_OutputProc * Dbg_Output(interp, proc) Tcl_Interp *interp; Dbg_OutputProc *proc; { - Dbg_OutputProc *tmp = printproc; - printproc = (proc?proc:0); - return tmp; + Dbg_OutputProc *tmp = printproc; + printproc = (proc ? proc : 0); + return tmp; } -/*ARGSUSED*/ -int -Dbg_Active(interp) + /*ARGSUSED*/ int Dbg_Active(interp) Tcl_Interp *interp; { - return debugger_active; + return debugger_active; } -char ** -Dbg_ArgcArgv(argc,argv,copy) +char **Dbg_ArgcArgv(argc, argv, copy) int argc; char *argv[]; int copy; { - char **alloc; + char **alloc; - if (!copy) { - main_argv = argv; - alloc = 0; - } else { - main_argv = alloc = (char **)ckalloc((argc+1)*sizeof(char *)); - while (argc-- >= 0) { - *main_argv++ = *argv++; - } - main_argv = alloc; - } - return alloc; + if (!copy) { + main_argv = argv; + alloc = 0; + } else { + main_argv = alloc = (char **) ckalloc((argc + 1) * sizeof(char *)); + while (argc-- >= 0) { + *main_argv++ = *argv++; + } + main_argv = alloc; + } + return alloc; } static struct cmd_list { - char *cmdname; - Tcl_CmdProc *cmdproc; - enum debug_cmd cmdtype; -} cmd_list[] = {{"n", cmdNext, next}, - {"s", cmdNext, step}, - {"N", cmdNext, Next}, - {"c", cmdSimple, cont}, - {"r", cmdSimple, ret}, - {"w", cmdWhere, none}, - {"b", cmdBreak, none}, - {"u", cmdDir, up}, - {"d", cmdDir, down}, - {"h", cmdHelp, none}, - {0} + char *cmdname; + Tcl_CmdProc *cmdproc; + enum debug_cmd cmdtype; +} cmd_list[] = { { +"n", cmdNext, next}, { +"s", cmdNext, step}, { +"N", cmdNext, Next}, { +"c", cmdSimple, cont}, { +"r", cmdSimple, ret}, { +"w", cmdWhere, none}, { +"b", cmdBreak, none}, { +"u", cmdDir, up}, { +"d", cmdDir, down}, { +"h", cmdHelp, none}, { +0} }; -static void -init_debugger(interp) +static void init_debugger(interp) Tcl_Interp *interp; { - struct cmd_list *c; + struct cmd_list *c; - for (c = cmd_list;c->cmdname;c++) { - Tcl_CreateCommand(interp,c->cmdname,c->cmdproc, - (ClientData)&c->cmdtype,(Tcl_CmdDeleteProc *)0); - } + for (c = cmd_list; c->cmdname; c++) { + Tcl_CreateCommand(interp, c->cmdname, c->cmdproc, + (ClientData) & c->cmdtype, (Tcl_CmdDeleteProc *) 0); + } - debug_handle = Tcl_CreateTrace(interp, - 10000,debugger_trap,(ClientData)0); + debug_handle = Tcl_CreateTrace(interp, + 10000, debugger_trap, (ClientData) 0); - debugger_active = TRUE; - Tcl_SetVar2(interp,Dbg_VarName,"active","1",0); + debugger_active = TRUE; + Tcl_SetVar2(interp, Dbg_VarName, "active", "1", 0); } /* allows any other part of the application to jump to the debugger */ -/*ARGSUSED*/ -void -Dbg_On(interp,immediate) + /*ARGSUSED*/ void Dbg_On(interp, immediate) Tcl_Interp *interp; -int immediate; /* if true, stop immediately */ - /* should only be used in safe places */ - /* i.e., when Tcl_Eval can be called */ +int immediate; /* if true, stop immediately */ + /* should only be used in safe places */ + /* i.e., when Tcl_Eval can be called */ { - if (!debugger_active) init_debugger(interp); + if (!debugger_active) + init_debugger(interp); - debug_cmd = step; - step_count = 1; + debug_cmd = step; + step_count = 1; - if (immediate) { - static char *fake_cmd = "--interrupted-- (command_unknown)"; + if (immediate) { + static char *fake_cmd = "--interrupted-- (command_unknown)"; - debugger_trap((ClientData)0,interp,-1,fake_cmd,(int (*)())0, - (ClientData)0,1,&fake_cmd); + debugger_trap((ClientData) 0, interp, -1, fake_cmd, (int (*)()) 0, + (ClientData) 0, 1, &fake_cmd); /* (*interactor)(interp);*/ - } + } } -void -Dbg_Off(interp) +void Dbg_Off(interp) Tcl_Interp *interp; { - struct cmd_list *c; + struct cmd_list *c; - if (!debugger_active) return; + if (!debugger_active) + return; - for (c = cmd_list;c->cmdname;c++) { - Tcl_DeleteCommand(interp,c->cmdname); - } + for (c = cmd_list; c->cmdname; c++) { + Tcl_DeleteCommand(interp, c->cmdname); + } - Tcl_DeleteTrace(interp,debug_handle); - debugger_active = FALSE; - Tcl_UnsetVar(interp,Dbg_VarName,TCL_GLOBAL_ONLY); + Tcl_DeleteTrace(interp, debug_handle); + debugger_active = FALSE; + Tcl_UnsetVar(interp, Dbg_VarName, TCL_GLOBAL_ONLY); } diff --git a/Dbg.h b/Dbg.h index 29364f4d..34add8e2 100644 --- a/Dbg.h +++ b/Dbg.h @@ -14,13 +14,11 @@ would appreciate credit if this program or parts of it are used. #include "tcl.h" -typedef int (Dbg_InterProc) _ANSI_ARGS_((Tcl_Interp *interp)); -typedef int (Dbg_IgnoreFuncsProc) _ANSI_ARGS_(( - Tcl_Interp *interp, - char *funcname)); -typedef void (Dbg_OutputProc) _ANSI_ARGS_(( - Tcl_Interp *interp, - char *output)); +typedef int (Dbg_InterProc) _ANSI_ARGS_((Tcl_Interp * interp)); +typedef int (Dbg_IgnoreFuncsProc) _ANSI_ARGS_((Tcl_Interp * interp, + char *funcname)); +typedef void (Dbg_OutputProc) _ANSI_ARGS_((Tcl_Interp * interp, + char *output)); EXTERN char *Dbg_VarName; EXTERN char *Dbg_DefaultCmdName; @@ -28,19 +26,15 @@ EXTERN char *Dbg_DefaultCmdName; /* trivial interface, creates a "debug" command in your interp */ EXTERN int Dbg_Init _ANSI_ARGS_((Tcl_Interp *)); -EXTERN void Dbg_On _ANSI_ARGS_((Tcl_Interp *interp, - int immediate)); -EXTERN void Dbg_Off _ANSI_ARGS_((Tcl_Interp *interp)); -EXTERN char **Dbg_ArgcArgv _ANSI_ARGS_((int argc,char *argv[], - int copy)); -EXTERN int Dbg_Active _ANSI_ARGS_((Tcl_Interp *interp)); -EXTERN Dbg_InterProc *Dbg_Interactor _ANSI_ARGS_(( - Tcl_Interp *interp, - Dbg_InterProc *interactor)); -EXTERN Dbg_IgnoreFuncsProc *Dbg_IgnoreFuncs _ANSI_ARGS_(( - Tcl_Interp *interp, - Dbg_IgnoreFuncsProc *)); -EXTERN Dbg_OutputProc *Dbg_Output _ANSI_ARGS_(( - Tcl_Interp *interp, - Dbg_OutputProc *)); -#endif /* _NIST_DBG */ +EXTERN void Dbg_On _ANSI_ARGS_((Tcl_Interp * interp, int immediate)); +EXTERN void Dbg_Off _ANSI_ARGS_((Tcl_Interp * interp)); +EXTERN char **Dbg_ArgcArgv _ANSI_ARGS_((int argc, char *argv[], int copy)); +EXTERN int Dbg_Active _ANSI_ARGS_((Tcl_Interp * interp)); +EXTERN Dbg_InterProc *Dbg_Interactor _ANSI_ARGS_((Tcl_Interp * interp, + Dbg_InterProc * + interactor)); +EXTERN Dbg_IgnoreFuncsProc *Dbg_IgnoreFuncs +_ANSI_ARGS_((Tcl_Interp * interp, Dbg_IgnoreFuncsProc *)); +EXTERN Dbg_OutputProc *Dbg_Output +_ANSI_ARGS_((Tcl_Interp * interp, Dbg_OutputProc *)); +#endif /* _NIST_DBG */ diff --git a/Dbg_cmd.c b/Dbg_cmd.c index 9ab2ceda..e1a3a28b 100644 --- a/Dbg_cmd.c +++ b/Dbg_cmd.c @@ -14,51 +14,48 @@ would appreciate credit if this program or parts of it are used. char *Dbg_DefaultCmdName = "debug"; -/*ARGSUSED*/ -static int -App_DebugCmd(clientData, interp, argc, argv) + /*ARGSUSED*/ static int App_DebugCmd(clientData, interp, argc, argv) ClientData clientData; Tcl_Interp *interp; int argc; char **argv; { - int now = 0; /* soon if 0, now if 1 */ + int now = 0; /* soon if 0, now if 1 */ - if (argc > 3) goto usage; + if (argc > 3) + goto usage; - argv++; + argv++; - while (*argv) { - if (0 == strcmp(*argv,"-now")) { - now = 1; - argv++; - } - else break; - } + while (*argv) { + if (0 == strcmp(*argv, "-now")) { + now = 1; + argv++; + } else + break; + } - if (!*argv) { - if (now) { - Dbg_On(interp,1); - } else { - goto usage; - } - } else if (0 == strcmp(*argv,"0")) { - Dbg_Off(interp); - } else { - Dbg_On(interp,now); - } - return(TCL_OK); - usage: - interp->result = "usage: [[-now] 1|0]"; - return TCL_ERROR; + if (!*argv) { + if (now) { + Dbg_On(interp, 1); + } else { + goto usage; + } + } else if (0 == strcmp(*argv, "0")) { + Dbg_Off(interp); + } else { + Dbg_On(interp, now); + } + return (TCL_OK); +usage: + interp->result = "usage: [[-now] 1|0]"; + return TCL_ERROR; } -int -Dbg_Init(interp) +int Dbg_Init(interp) Tcl_Interp *interp; { - Tcl_CreateCommand(interp,Dbg_DefaultCmdName,App_DebugCmd, - (ClientData)0,(void (*)())0); - return TCL_OK; + Tcl_CreateCommand(interp, Dbg_DefaultCmdName, App_DebugCmd, + (ClientData) 0, (void (*)()) 0); + return TCL_OK; } - diff --git a/HistMem.h b/HistMem.h index 6ffc568b..6ceb50ab 100644 --- a/HistMem.h +++ b/HistMem.h @@ -13,34 +13,34 @@ #define SICSHISTMEM #define MAXDIM 3 - typedef struct __HistDriver *pHistDriver; - typedef struct __HistMem *pHistMem; +typedef struct __HistDriver *pHistDriver; +typedef struct __HistMem *pHistMem; /*-------------------------------------------------------------------------*/ - typedef int HistInt; +typedef int HistInt; /* 32 bit integer on a DigitalUnix */ #line 9 "histogram.w" - typedef enum { - eHTransparent, - eHNormal, - eHTOF, - eHStrobo, - eHRPT, - ePSD, - eSANSTOF - } HistMode; +typedef enum { + eHTransparent, + eHNormal, + eHTOF, + eHStrobo, + eHRPT, + ePSD, + eSANSTOF +} HistMode; #line 36 "histogram.w" - typedef enum { - eOIgnore, - eOCeil, - eOCount, - eReflect - } OverFlowMode; +typedef enum { + eOIgnore, + eOCeil, + eOCount, + eReflect +} OverFlowMode; #line 460 "histogram.w" @@ -48,51 +48,52 @@ #line 292 "histogram.w" - pHistMem CreateHistMemory(char *drivername); - void DeleteHistMemory(void *self); +pHistMem CreateHistMemory(char *drivername); +void DeleteHistMemory(void *self); #line 308 "histogram.w" - int HistGetOption(pHistMem self, char *name, char *result, int iResultLen); - int HistSetOption(pHistMem self, char *name, char *value); - int HistConfigure(pHistMem self, SConnection *pCon, SicsInterp *pSics); +int HistGetOption(pHistMem self, char *name, char *result, int iResultLen); +int HistSetOption(pHistMem self, char *name, char *value); +int HistConfigure(pHistMem self, SConnection * pCon, SicsInterp * pSics); #line 336 "histogram.w" - float GetHistPreset(pHistMem self); - int SetHistPreset(pHistMem self, float fVal); - CounterMode GetHistCountMode(pHistMem self); - int SetHistCountMode(pHistMem self, CounterMode eNew); - long GetHistMonitor(pHistMem self, int i, SConnection *pCon); - const float *GetHistTimeBin(pHistMem self, int *iLength); - int GetHistLength(pHistMem self); - int GetHistDim(pHistMem self, int iDim[MAXDIM], int *nDim); - float GetHistCountTime(pHistMem self,SConnection *pCon); - int HistDoCount(pHistMem self, SConnection *pCon); - int HistBlockCount(pHistMem self, SConnection *pCon); - void HistDirty(pHistMem self); +float GetHistPreset(pHistMem self); +int SetHistPreset(pHistMem self, float fVal); +CounterMode GetHistCountMode(pHistMem self); +int SetHistCountMode(pHistMem self, CounterMode eNew); +long GetHistMonitor(pHistMem self, int i, SConnection * pCon); +const float *GetHistTimeBin(pHistMem self, int *iLength); +int GetHistLength(pHistMem self); +int GetHistDim(pHistMem self, int iDim[MAXDIM], int *nDim); +float GetHistCountTime(pHistMem self, SConnection * pCon); +int HistDoCount(pHistMem self, SConnection * pCon); +int HistBlockCount(pHistMem self, SConnection * pCon); +void HistDirty(pHistMem self); #line 366 "histogram.w" - int SetHistogram(pHistMem self, SConnection *pCon, - int i,int iStart, int iEnd, HistInt *lData); - int GetHistogram(pHistMem self, SConnection *pCon, - int i,int iStart, int iEnd, HistInt *lData, int iDataLen); - HistInt *GetHistogramPointer(pHistMem self,SConnection *pCon); - int GetHistogramDirect(pHistMem self, SConnection *pCon, - int i, int iStart, int iEnd, - HistInt *lData, int iDataLen); - int PresetHistogram(pHistMem self, SConnection *pCon, HistInt lVal); +int SetHistogram(pHistMem self, SConnection * pCon, + int i, int iStart, int iEnd, HistInt * lData); +int GetHistogram(pHistMem self, SConnection * pCon, + int i, int iStart, int iEnd, HistInt * lData, + int iDataLen); +HistInt *GetHistogramPointer(pHistMem self, SConnection * pCon); +int GetHistogramDirect(pHistMem self, SConnection * pCon, + int i, int iStart, int iEnd, + HistInt * lData, int iDataLen); +int PresetHistogram(pHistMem self, SConnection * pCon, HistInt lVal); #line 409 "histogram.w" - int MakeHistMemory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeHistMemory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +int HistAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - int HistAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - #line 462 "histogram.w" diff --git a/SCinter.c b/SCinter.c index aa64ea9f..5103bb21 100644 --- a/SCinter.c +++ b/SCinter.c @@ -77,7 +77,7 @@ /* pvh */ #include "lld_str.h" -static void printList(SConnection *pCon, int listID); +static void printList(SConnection * pCon, int listID); static void freeList(int listID); #define MAXLEN 256 @@ -85,939 +85,862 @@ static void freeList(int listID); #define MAXBUF 128 /*--------------------------------------------------------------------------*/ - SicsInterp *InitInterp(void) - { - SicsInterp *pInter = NULL; - int i; - - pInter = (SicsInterp *)malloc(sizeof(SicsInterp)); - if(!pInter) - { - SICSLogWrite("Error allocating memory for Interpreter",eInternal); - return NULL; - } - memset(pInter,0,sizeof(SicsInterp)); - pInter->pCList = NULL; - pInter->AList.pFirst = NULL; /* M.Z. */ - pInter->pTcl = (void *)MacroInit(pInter); - if(!pInter->pTcl) - { - free(pInter); - return NULL; - } +SicsInterp *InitInterp(void) +{ + SicsInterp *pInter = NULL; + int i; - pInter->iDeleting = 0; - return pInter; + pInter = (SicsInterp *) malloc(sizeof(SicsInterp)); + if (!pInter) { + SICSLogWrite("Error allocating memory for Interpreter", eInternal); + return NULL; + } + memset(pInter, 0, sizeof(SicsInterp)); + pInter->pCList = NULL; + pInter->AList.pFirst = NULL; /* M.Z. */ + pInter->pTcl = (void *) MacroInit(pInter); + if (!pInter->pTcl) { + free(pInter); + return NULL; } -/*------------------------------------------------------------------------*/ - int AddCommandWithFlag(SicsInterp *pInterp, char *pName, ObjectFunc pFunc, - KillFunc pKFunc, void *pData, int startupOnly) - { - CommandList *pNew = NULL; - CommandList *p, *tail; - char pBueffel[512]; - assert(pName); - assert(pFunc); - assert(pInterp); - - strcpy(pBueffel,pName); - strtolower(pBueffel); - RemoveAlias(&pInterp->AList,pBueffel); /* M.Z. */ - if(FindCommand(pInterp,pBueffel) != NULL) - { - return 0; + pInter->iDeleting = 0; + return pInter; +} + +/*------------------------------------------------------------------------*/ +int AddCommandWithFlag(SicsInterp * pInterp, char *pName, ObjectFunc pFunc, + KillFunc pKFunc, void *pData, int startupOnly) +{ + CommandList *pNew = NULL; + CommandList *p, *tail; + char pBueffel[512]; + + assert(pName); + assert(pFunc); + assert(pInterp); + + strcpy(pBueffel, pName); + strtolower(pBueffel); + RemoveAlias(&pInterp->AList, pBueffel); /* M.Z. */ + if (FindCommand(pInterp, pBueffel) != NULL) { + return 0; + } + + /* new memory */ + pNew = (CommandList *) malloc(sizeof(CommandList)); + if (!pNew) { + sprintf(pBueffel, "Out of memory creating command - %s -", pName); + SICSLogWrite(pBueffel, eInternal); + return 0; + } + memset(pNew, 0, sizeof(CommandList)); + + /* if no data given, initialise with Dummy struct */ + if (!pData) { + pData = (void *) CreateDummy(pBueffel); + if (!pKFunc) { + pKFunc = KillDummy; } - - /* new memory */ - pNew = (CommandList *)malloc(sizeof(CommandList)); - if(!pNew) - { - sprintf(pBueffel, - "Out of memory creating command - %s -", pName); - SICSLogWrite(pBueffel,eInternal); - return 0; - } - memset(pNew,0,sizeof(CommandList)); + } - /* if no data given, initialise with Dummy struct */ - if(!pData) - { - pData = (void *)CreateDummy(pBueffel); - if(!pKFunc) - { - pKFunc = KillDummy; - } - } - - /* initialise datastructures */ - pNew->pName = strdup(pBueffel); - pNew->OFunc = pFunc; - pNew->KFunc = pKFunc; - pNew->pData = pData; - pNew->pNext = NULL; - pNew->startupOnly = startupOnly; - pNew->stat = StatisticsNew(pBueffel); + /* initialise datastructures */ + pNew->pName = strdup(pBueffel); + pNew->OFunc = pFunc; + pNew->KFunc = pKFunc; + pNew->pData = pData; + pNew->pNext = NULL; + pNew->startupOnly = startupOnly; + pNew->stat = StatisticsNew(pBueffel); - /* find end of list */ - tail = NULL; - p = pInterp->pCList; - while(p != NULL) - { - tail = p; - p = p->pNext; - } - if (tail==NULL) { /* first entry */ - pInterp->pCList = pNew; - } else { /* insert at tail */ - tail->pNext = pNew; - } - pNew->pPrevious = tail; - - return 1; + /* find end of list */ + tail = NULL; + p = pInterp->pCList; + while (p != NULL) { + tail = p; + p = p->pNext; } -/*------------------------------------------------------------------------*/ - int AddCommand(SicsInterp *pInterp, char *pName, ObjectFunc pFunc, - KillFunc pKFunc, void *pData) - { - return AddCommandWithFlag(pInterp, pName, pFunc, pKFunc, pData, 0); + if (tail == NULL) { /* first entry */ + pInterp->pCList = pNew; + } else { /* insert at tail */ + tail->pNext = pNew; } -/*------------------------------------------------------------------------*/ - int AddIniCmd(char *pName, ObjectFunc pFunc) - { - return AddCommandWithFlag(pServ->pSics, pName, pFunc, NULL, NULL, 1); - } -/*------------------------------------------------------------------------*/ - int AddCmd(char *pName, ObjectFunc pFunc) - { - return AddCommandWithFlag(pServ->pSics, pName, pFunc, NULL, NULL, 0); - } -/*------------------------------------------------------------------------*/ - int RemoveCommand(SicsInterp *pInterp, char *pName) - { - CommandList *pVictim = NULL; - char pBueffel[256]; + pNew->pPrevious = tail; - assert(pInterp); - assert(pName); - - strcpy(pBueffel,pName); - strtolower(pBueffel); - - if(pInterp->iDeleting) - { - return 0; - } - - /* find our victim */ - pVictim = FindCommand(pInterp, pBueffel); - if(!pVictim) - return 0; - - /* found, remove it */ - /* kall KillFunction first */ - if(pVictim->KFunc) - { - pVictim->KFunc(pVictim->pData); - } - - /* delete and unlink data */ - if(pVictim->pName) - { - free(pVictim->pName); - } - if(pVictim->pPrevious) - { - pVictim->pPrevious->pNext = pVictim->pNext; - } - if(pVictim->pNext) - { - pVictim->pNext->pPrevious = pVictim->pPrevious; - } - /* adjust headpointer if necessary */ - if(pVictim == pInterp->pCList) - { - pInterp->pCList = pVictim->pNext; - } - if (pVictim->stat) { - StatisticsKill(pVictim->stat); - } - free(pVictim); - return 1; - } + return 1; +} + +/*------------------------------------------------------------------------*/ +int AddCommand(SicsInterp * pInterp, char *pName, ObjectFunc pFunc, + KillFunc pKFunc, void *pData) +{ + return AddCommandWithFlag(pInterp, pName, pFunc, pKFunc, pData, 0); +} + +/*------------------------------------------------------------------------*/ +int AddIniCmd(char *pName, ObjectFunc pFunc) +{ + return AddCommandWithFlag(pServ->pSics, pName, pFunc, NULL, NULL, 1); +} + +/*------------------------------------------------------------------------*/ +int AddCmd(char *pName, ObjectFunc pFunc) +{ + return AddCommandWithFlag(pServ->pSics, pName, pFunc, NULL, NULL, 0); +} + +/*------------------------------------------------------------------------*/ +int RemoveCommand(SicsInterp * pInterp, char *pName) +{ + CommandList *pVictim = NULL; + char pBueffel[256]; + + assert(pInterp); + assert(pName); + + strcpy(pBueffel, pName); + strtolower(pBueffel); + + if (pInterp->iDeleting) { + return 0; + } + + /* find our victim */ + pVictim = FindCommand(pInterp, pBueffel); + if (!pVictim) + return 0; + + /* found, remove it */ + /* kall KillFunction first */ + if (pVictim->KFunc) { + pVictim->KFunc(pVictim->pData); + } + + /* delete and unlink data */ + if (pVictim->pName) { + free(pVictim->pName); + } + if (pVictim->pPrevious) { + pVictim->pPrevious->pNext = pVictim->pNext; + } + if (pVictim->pNext) { + pVictim->pNext->pPrevious = pVictim->pPrevious; + } + /* adjust headpointer if necessary */ + if (pVictim == pInterp->pCList) { + pInterp->pCList = pVictim->pNext; + } + if (pVictim->stat) { + StatisticsKill(pVictim->stat); + } + free(pVictim); + return 1; +} #define MAXLEN 256 #define MAXCOM 50 -extern char *stptok(char *s, char *tok, unsigned int toklen, char *brk); +extern char *stptok(char *s, char *tok, unsigned int toklen, char *brk); extern char *SkipSpace(char *pPtr); /*-----------------------------------------------------------------------*/ - int InterpExecute(SicsInterp *self,SConnection *pCon, char *pText) - { - int iCount = 0; - int iRet; - int i, argc; - char pBueffel[1024]; - CommandList *pCommand = NULL; - char pBrk[] = {" \r\n\0"}; - char *pPtr; - char **argv = NULL; - commandContext comCon; - Statistics *old; - - - assert(self); - assert(pCon); +int InterpExecute(SicsInterp * self, SConnection * pCon, char *pText) +{ + int iCount = 0; + int iRet; + int i, argc; + char pBueffel[1024]; + CommandList *pCommand = NULL; + char pBrk[] = { " \r\n\0" }; + char *pPtr; + char **argv = NULL; + commandContext comCon; + Statistics *old; - /* write info to Log */ - if(pCon->sockHandle >= 0) - { - sprintf(pBueffel,"Executing -> %s <- from socket %d",pText, - pCon->sockHandle); - SICSLogWrite(pBueffel,eCommand); - } - else - { - sprintf(pBueffel, "Executing -> %s <- from dummy socket\n", pText); - SICSLogWrite(pBueffel,eCommand); - } - - /* convert to argc, argv */ - argc = 0; - argv = NULL; - Text2Arg(pText,&argc,&argv); - - /* the first one must be the target object. If not given an empty - command string was given which will be silently ignored */ - if(argc < 1) - { - iRet = 1; - goto deleteArgv; - } + assert(self); + assert(pCon); - if(argv[0] == NULL) - { - SCWrite(pCon,"ERROR: failed to parse command",eError); - iRet = -1; - goto deleteArgv; - } - - /* find it */ - pCommand = FindCommand(self,argv[0]); - if(!pCommand) - { - sprintf(pBueffel,"ERROR: Object -> %s <- NOT found", - argv[0]); - SCWrite(pCon,pBueffel,eError); - iRet = -1; - goto deleteArgv; - } - - - /* invoke the command */ - self->eOut = eValue; - Tcl_ResetResult((Tcl_Interp *)self->pTcl); - MacroPush(pCon); - pCon->conStatus = 0; - old = StatisticsBegin(pCommand->stat); - iRet = pCommand->OFunc(pCon, self, pCommand->pData, argc, argv); - StatisticsEnd(old); - /* If a task is registered with the dev exec then conStatus is HWBusy*/ - if (pCon->conStatus != HWBusy) { - /*comCon = SCGetContext(pCon);*/ - if (0 != strcmp("contextdo",pCon->deviceID)) - SCWrite(pCon,"",eFinish); - } - MacroPop(); - - deleteArgv: - if (argv) { - /* delete argv */ - for(i = 0; i < argc; i++) - { - if(argv[i] != NULL) - { - free(argv[i]); - } - } - free(argv); - } - return iRet; + /* write info to Log */ + if (pCon->sockHandle >= 0) { + sprintf(pBueffel, "Executing -> %s <- from socket %d", pText, + pCon->sockHandle); + SICSLogWrite(pBueffel, eCommand); + } else { + sprintf(pBueffel, "Executing -> %s <- from dummy socket\n", pText); + SICSLogWrite(pBueffel, eCommand); } + + + /* convert to argc, argv */ + argc = 0; + argv = NULL; + Text2Arg(pText, &argc, &argv); + + /* the first one must be the target object. If not given an empty + command string was given which will be silently ignored */ + if (argc < 1) { + iRet = 1; + goto deleteArgv; + } + + if (argv[0] == NULL) { + SCWrite(pCon, "ERROR: failed to parse command", eError); + iRet = -1; + goto deleteArgv; + } + + /* find it */ + pCommand = FindCommand(self, argv[0]); + if (!pCommand) { + sprintf(pBueffel, "ERROR: Object -> %s <- NOT found", argv[0]); + SCWrite(pCon, pBueffel, eError); + iRet = -1; + goto deleteArgv; + } + + + /* invoke the command */ + self->eOut = eValue; + Tcl_ResetResult((Tcl_Interp *) self->pTcl); + MacroPush(pCon); + pCon->conStatus = 0; + old = StatisticsBegin(pCommand->stat); + iRet = pCommand->OFunc(pCon, self, pCommand->pData, argc, argv); + StatisticsEnd(old); + /* If a task is registered with the dev exec then conStatus is HWBusy */ + if (pCon->conStatus != HWBusy) { + /*comCon = SCGetContext(pCon); */ + if (0 != strcmp("contextdo", pCon->deviceID)) + SCWrite(pCon, "", eFinish); + } + MacroPop(); + +deleteArgv: + if (argv) { + /* delete argv */ + for (i = 0; i < argc; i++) { + if (argv[i] != NULL) { + free(argv[i]); + } + } + free(argv); + } + return iRet; +} + /*------------------------------------------------------------------------*/ - CommandList *FindCommand(SicsInterp *self, char *pName) - { - CommandList *pCurrent = NULL; - char pBueffel[256], *pCmd; +CommandList *FindCommand(SicsInterp * self, char *pName) +{ + CommandList *pCurrent = NULL; + char pBueffel[256], *pCmd; - assert(self); - - if(self->iDeleting) - { - return NULL; - } - - strcpy(pBueffel,pName); - strtolower(pBueffel); + assert(self); - pCmd=TranslateAlias(&self->AList, pBueffel); /* M.Z. */ - - pCurrent = self->pCList; - while(pCurrent) - { - if(pCurrent->pName != NULL) - { - if(strcmp(pCurrent->pName, pCmd) == 0 ) /* M.Z. */ - { - return pCurrent; - } - } - pCurrent = pCurrent->pNext; - } + if (self->iDeleting) { return NULL; - } + } + + strcpy(pBueffel, pName); + strtolower(pBueffel); + + pCmd = TranslateAlias(&self->AList, pBueffel); /* M.Z. */ + + pCurrent = self->pCList; + while (pCurrent) { + if (pCurrent->pName != NULL) { + if (strcmp(pCurrent->pName, pCmd) == 0) { /* M.Z. */ + return pCurrent; + } + } + pCurrent = pCurrent->pNext; + } + return NULL; +} + /*------------------------------------------------------------------------*/ - int WriteSicsStatus(SicsInterp *self, char *file, int iMot) - { - CommandList *pCurrent = NULL; - FILE *fd = NULL; - Dummy *pDum = NULL; - float fVal; - pIDrivable pDriv = NULL; - void *pTest = NULL; - char tmpfile[PATH_MAX]; - int l; - - assert(self); - assert(file); - - /* make sure that status file is always valid M.Z. Apr 2005 */ - /* create a temporary file first */ - l=strlen(file); - if (l >= sizeof tmpfile - 2) { - return 0; - } - strcpy(tmpfile, file); - tmpfile[l]='.'; - tmpfile[l+1]='\0'; - remove(tmpfile); /* remove already existing file */ - - fd = fopen(tmpfile,"w"); - if(!fd) - { - return 0; - } - - /* cycle through the list */ - pCurrent = self->pCList; - while(pCurrent) - { - pDum = (Dummy *)pCurrent->pData; - if(pDum) - { - pDum->pDescriptor->SaveStatus(pCurrent->pData,pCurrent->pName,fd); - if(iMot) - { - /* - save values of motors but not of environment devices as they - may not be present the next time round - */ - pDriv = pDum->pDescriptor->GetInterface(pDum,DRIVEID); - pTest = pDum->pDescriptor->GetInterface(pDum,ENVIRINTERFACE); - if(pDriv && !pTest) - { - if(strcmp(pDum->pDescriptor->name,"Motor") == 0) - { - MotorGetSoftPosition((pMotor)pDum,pServ->dummyCon,&fVal); - } - else - { - fVal = pDriv->GetValue(pDum,pServ->dummyCon); - } - if(fVal > -990.) - { - fprintf(fd,"drive %s %f\n",pCurrent->pName, fVal); - } +int WriteSicsStatus(SicsInterp * self, char *file, int iMot) +{ + CommandList *pCurrent = NULL; + FILE *fd = NULL; + Dummy *pDum = NULL; + float fVal; + pIDrivable pDriv = NULL; + void *pTest = NULL; + char tmpfile[PATH_MAX]; + int l; + + assert(self); + assert(file); + + /* make sure that status file is always valid M.Z. Apr 2005 */ + /* create a temporary file first */ + l = strlen(file); + if (l >= sizeof tmpfile - 2) { + return 0; + } + strcpy(tmpfile, file); + tmpfile[l] = '.'; + tmpfile[l + 1] = '\0'; + remove(tmpfile); /* remove already existing file */ + + fd = fopen(tmpfile, "w"); + if (!fd) { + return 0; + } + + /* cycle through the list */ + pCurrent = self->pCList; + while (pCurrent) { + pDum = (Dummy *) pCurrent->pData; + if (pDum) { + pDum->pDescriptor->SaveStatus(pCurrent->pData, pCurrent->pName, fd); + if (iMot) { + /* + save values of motors but not of environment devices as they + may not be present the next time round + */ + pDriv = pDum->pDescriptor->GetInterface(pDum, DRIVEID); + pTest = pDum->pDescriptor->GetInterface(pDum, ENVIRINTERFACE); + if (pDriv && !pTest) { + if (strcmp(pDum->pDescriptor->name, "Motor") == 0) { + MotorGetSoftPosition((pMotor) pDum, pServ->dummyCon, &fVal); + } else { + fVal = pDriv->GetValue(pDum, pServ->dummyCon); + } + if (fVal > -990.) { + fprintf(fd, "drive %s %f\n", pCurrent->pName, fVal); } } } - pCurrent = pCurrent->pNext; - } - if(iMot) - { - fprintf(fd,"Success \n"); - } - fclose(fd); - /* rename temporary to final file (this is an atomic action) */ - if (0 > rename(tmpfile, file)) { - return 0; - } - return 1; - } -/*------------------------------------------------------------------------*/ - void DeleteInterp(SicsInterp *self) - { - CommandList *pCurrent = NULL; - CommandList *pTemp, *tail; - Tcl_Interp *pTcl = NULL; - int i; - - assert(self); - self->iDeleting = 1; - - /* find end of list */ - tail = NULL; - pCurrent = self->pCList; - while(pCurrent != NULL) - { - tail = pCurrent; - pCurrent = pCurrent->pNext; - } - - /* delete Commandlist (reversed order) */ - if (tail) { - pCurrent = tail; - while(pCurrent) - { - /* the line below fixes problems with kill functions - * traversing the command list - */ - pCurrent->pNext = NULL; - if(pCurrent->KFunc) - { - pCurrent->KFunc(pCurrent->pData); - } - if(pCurrent->pName) - { - /* printf("Deleting %s\n",pCurrent->pName); */ - free(pCurrent->pName); - } - if (pCurrent->stat) { - StatisticsKill(pCurrent->stat); - } - pTemp = pCurrent->pPrevious; - free(pCurrent); - pCurrent = pTemp; - } - } - - FreeAliasList(&self->AList); /* M.Z. */ - - /* clear Tcl_Interpreter. Must be AFTER deleting command list because - some devices may have Tcl drivers which need to be accessed for - proper closing of devices. - */ - pTcl = (Tcl_Interp *)self->pTcl; - if(pTcl) - { - /* - uncommented: the current versions of Tcl (8.3,4) dump core with a - memory problem deep in the Tcl library. This causes a core dump on - each SICS restart and breaks the use of external tools. - Tcl_DeleteInterp(pTcl); - - call KillSicsUnknown instead to clean up all memory properly. M.Z., Apr 05 - */ - KillSicsUnknown(); - } - - free(self); - } -/*------------------------------------------------------------------------*/ -static void printAll(SicsInterp *pSics, SConnection *pCon) -{ - CommandList *pCurrent; - char pBueffel[256]; - int iNum = 0; - - assert(pSics); - assert(pCon); - - pCurrent = pSics->pCList; - while(pCurrent) - { - if(iNum == 0) - { - strcpy(pBueffel,pCurrent->pName); - iNum++; - } - else if(iNum < 4) - { - strcat(pBueffel," "); - strcat(pBueffel,pCurrent->pName); - iNum++; - } - else - { - strcat(pBueffel," "); - strcat(pBueffel,pCurrent->pName); - strcat(pBueffel,"\r\n"); - SCWrite(pCon,pBueffel,eValue); - iNum = 0; - pBueffel[0]='\0'; - } - pCurrent = pCurrent->pNext; - } - - /* write final entries */ - if(strlen(pBueffel) > 2) - { - strcat(pBueffel,"\r\n"); - SCWrite(pCon,pBueffel,eValue); } + pCurrent = pCurrent->pNext; + } + if (iMot) { + fprintf(fd, "Success \n"); + } + fclose(fd); + /* rename temporary to final file (this is an atomic action) */ + if (0 > rename(tmpfile, file)) { + return 0; + } + return 1; } + +/*------------------------------------------------------------------------*/ +void DeleteInterp(SicsInterp * self) +{ + CommandList *pCurrent = NULL; + CommandList *pTemp, *tail; + Tcl_Interp *pTcl = NULL; + int i; + + assert(self); + self->iDeleting = 1; + + /* find end of list */ + tail = NULL; + pCurrent = self->pCList; + while (pCurrent != NULL) { + tail = pCurrent; + pCurrent = pCurrent->pNext; + } + + /* delete Commandlist (reversed order) */ + if (tail) { + pCurrent = tail; + while (pCurrent) { + /* the line below fixes problems with kill functions + * traversing the command list + */ + pCurrent->pNext = NULL; + if (pCurrent->KFunc) { + pCurrent->KFunc(pCurrent->pData); + } + if (pCurrent->pName) { + /* printf("Deleting %s\n",pCurrent->pName); */ + free(pCurrent->pName); + } + if (pCurrent->stat) { + StatisticsKill(pCurrent->stat); + } + pTemp = pCurrent->pPrevious; + free(pCurrent); + pCurrent = pTemp; + } + } + + FreeAliasList(&self->AList); /* M.Z. */ + + /* clear Tcl_Interpreter. Must be AFTER deleting command list because + some devices may have Tcl drivers which need to be accessed for + proper closing of devices. + */ + pTcl = (Tcl_Interp *) self->pTcl; + if (pTcl) { + /* + uncommented: the current versions of Tcl (8.3,4) dump core with a + memory problem deep in the Tcl library. This causes a core dump on + each SICS restart and breaks the use of external tools. + Tcl_DeleteInterp(pTcl); + + call KillSicsUnknown instead to clean up all memory properly. M.Z., Apr 05 + */ + KillSicsUnknown(); + } + + free(self); +} + +/*------------------------------------------------------------------------*/ +static void printAll(SicsInterp * pSics, SConnection * pCon) +{ + CommandList *pCurrent; + char pBueffel[256]; + int iNum = 0; + + assert(pSics); + assert(pCon); + + pCurrent = pSics->pCList; + while (pCurrent) { + if (iNum == 0) { + strcpy(pBueffel, pCurrent->pName); + iNum++; + } else if (iNum < 4) { + strcat(pBueffel, " "); + strcat(pBueffel, pCurrent->pName); + iNum++; + } else { + strcat(pBueffel, " "); + strcat(pBueffel, pCurrent->pName); + strcat(pBueffel, "\r\n"); + SCWrite(pCon, pBueffel, eValue); + iNum = 0; + pBueffel[0] = '\0'; + } + pCurrent = pCurrent->pNext; + } + + /* write final entries */ + if (strlen(pBueffel) > 2) { + strcat(pBueffel, "\r\n"); + SCWrite(pCon, pBueffel, eValue); + } +} + /*------------------------------------------------------------------------*/ /* compareStringNode wraps strcmp for use in findNode(LLD module) calls */ int compareStringNode(const void *pStr1, const void *ppStr2) { - return strcmp((char *)pStr1,*(char **)ppStr2); + return strcmp((char *) pStr1, *(char **) ppStr2); } + /*------------------------------------------------------------------------ printAllTypes prints the list of types of objects instantiated on the CommandList. iFiltered=0 gives all objects including interpreter command objects iFiltered=1 gives types where object name is not the same as its type -------------------------------------------------------------------------*/ -static void printAllTypes(SicsInterp *pSics, SConnection *pCon, int iFiltered) +static void printAllTypes(SicsInterp * pSics, SConnection * pCon, + int iFiltered) { - CommandList *pCurrent = NULL; - char pBueffel[256]; - char pName_lc[256]; - char pType_lc[256]; - char *pType; - Dummy *pTest; - int typeListID; - - assert(pSics); - assert(pCon); + CommandList *pCurrent = NULL; + char pBueffel[256]; + char pName_lc[256]; + char pType_lc[256]; + char *pType; + Dummy *pTest; + int typeListID; - pBueffel[0] = '\0'; - - typeListID = LLDstringCreate(); - if(-1==typeListID) - { - strcpy(pBueffel,"ERROR: Cannot generate list of object types\r\n"); - SCWrite(pCon,pBueffel,eValue); - return; - } - - pCurrent = pSics->pCList; - while(pCurrent) - { - if(NULL != pCurrent->pData) - { - pTest = (pDummy)pCurrent->pData; - if(NULL != pTest->pDescriptor) - { - pType = pTest->pDescriptor->name; - strcpy(pType_lc,pType); - strtolower(pType_lc); - - LLDnodePtr2First(typeListID); + assert(pSics); + assert(pCon); - /* int LLDnodeFind( int List, CompFunPtr Compare, void * DataPtr ); */ - /* */ - /* Find *DataPtr in the List using the *Compare function. */ - /* Returns the return value of *Compare. */ - /* 0 == equal == found. */ - /* non-zero == not found. Current node is set to found node. */ - /* Returns 2 for an empty list. */ - /* NB: First checked node is current node, then search to end of list*/ - - if(0!=LLDnodeFind(typeListID,compareStringNode,(void *)pType)) - { /* empty list or 'typename' not found */ - strcpy(pName_lc, pCurrent->pName); - strtolower(pName_lc); - if((0==iFiltered)||((1==iFiltered)&&(0!=strcmp(pType_lc,pName_lc)))) - { /*ie Add if unfiltered or pass filter(name!=typename) */ - LLDstringAdd(typeListID,pType); - } - } - } - } - pCurrent = pCurrent->pNext; + pBueffel[0] = '\0'; + + typeListID = LLDstringCreate(); + if (-1 == typeListID) { + strcpy(pBueffel, "ERROR: Cannot generate list of object types\r\n"); + SCWrite(pCon, pBueffel, eValue); + return; + } + + pCurrent = pSics->pCList; + while (pCurrent) { + if (NULL != pCurrent->pData) { + pTest = (pDummy) pCurrent->pData; + if (NULL != pTest->pDescriptor) { + pType = pTest->pDescriptor->name; + strcpy(pType_lc, pType); + strtolower(pType_lc); + + LLDnodePtr2First(typeListID); + + /* int LLDnodeFind( int List, CompFunPtr Compare, void * DataPtr ); */ + /* */ + /* Find *DataPtr in the List using the *Compare function. */ + /* Returns the return value of *Compare. */ + /* 0 == equal == found. */ + /* non-zero == not found. Current node is set to found node. */ + /* Returns 2 for an empty list. */ + /* NB: First checked node is current node, then search to end of list */ + + if (0 != LLDnodeFind(typeListID, compareStringNode, (void *) pType)) { /* empty list or 'typename' not found */ + strcpy(pName_lc, pCurrent->pName); + strtolower(pName_lc); + if ((0 == iFiltered) || ((1 == iFiltered) && (0 != strcmp(pType_lc, pName_lc)))) { /*ie Add if unfiltered or pass filter(name!=typename) */ + LLDstringAdd(typeListID, pType); + } + } + } } - printList(pCon,typeListID); - freeList(typeListID); + pCurrent = pCurrent->pNext; + } + printList(pCon, typeListID); + freeList(typeListID); } + /*----------------------------------------------------------------------- printInterface prints only those objects which implement an interface as specified bi the id given -------------------------------------------------------------------------*/ -static void printInterface(SicsInterp *pSics, SConnection *pCon, int id) +static void printInterface(SicsInterp * pSics, SConnection * pCon, int id) { - CommandList *pCurrent; - char pBueffel[256]; - int iNum = 0; - pObjectDescriptor pObj = NULL; + CommandList *pCurrent; + char pBueffel[256]; + int iNum = 0; + pObjectDescriptor pObj = NULL; - assert(pSics); - assert(pCon); + assert(pSics); + assert(pCon); - pBueffel[0] = '\0'; - pCurrent = pSics->pCList; - while(pCurrent) - { - pObj = FindDescriptor(pCurrent->pData); - if(pObj != NULL) - { - if(pObj->GetInterface(pObj,id) != NULL) - { - if(iNum == 0) - { - strcpy(pBueffel,pCurrent->pName); - iNum++; - } - else if(iNum < 4) - { - strcat(pBueffel," "); - strcat(pBueffel,pCurrent->pName); - iNum++; - } - else - { - strcat(pBueffel," "); - strcat(pBueffel,pCurrent->pName); - strcat(pBueffel,"\r\n"); - SCWrite(pCon,pBueffel,eValue); - iNum = 0; - pBueffel[0]='\0'; - } - } + pBueffel[0] = '\0'; + pCurrent = pSics->pCList; + while (pCurrent) { + pObj = FindDescriptor(pCurrent->pData); + if (pObj != NULL) { + if (pObj->GetInterface(pObj, id) != NULL) { + if (iNum == 0) { + strcpy(pBueffel, pCurrent->pName); + iNum++; + } else if (iNum < 4) { + strcat(pBueffel, " "); + strcat(pBueffel, pCurrent->pName); + iNum++; + } else { + strcat(pBueffel, " "); + strcat(pBueffel, pCurrent->pName); + strcat(pBueffel, "\r\n"); + SCWrite(pCon, pBueffel, eValue); + iNum = 0; + pBueffel[0] = '\0'; + } } - pCurrent = pCurrent->pNext; } - - /* write final entries */ - strcat(pBueffel,"\r\n"); - SCWrite(pCon,pBueffel,eValue); + pCurrent = pCurrent->pNext; + } + + /* write final entries */ + strcat(pBueffel, "\r\n"); + SCWrite(pCon, pBueffel, eValue); } + /*----------------------------------------------------------------------- printMatch prints only those objects which match the wildcard string given -------------------------------------------------------------------------*/ -extern int match(const char *mask, const char *name); /* from wwildcard.c */ +extern int match(const char *mask, const char *name); /* from wwildcard.c */ -static void printMatch(SicsInterp *pSics, SConnection *pCon, char *mask) +static void printMatch(SicsInterp * pSics, SConnection * pCon, char *mask) { - CommandList *pCurrent; - char pBueffel[256]; - int iNum = 0; - pObjectDescriptor pObj = NULL; + CommandList *pCurrent; + char pBueffel[256]; + int iNum = 0; + pObjectDescriptor pObj = NULL; - assert(pSics); - assert(pCon); + assert(pSics); + assert(pCon); - pBueffel[0] = '\0'; - pCurrent = pSics->pCList; - while(pCurrent) - { - pObj = FindDescriptor(pCurrent->pData); - if(pObj != NULL) - { - if(!match(mask,pObj->name)) - { - if(iNum == 0) - { - strcpy(pBueffel,pCurrent->pName); - iNum++; - } - else if(iNum < 4) - { - strcat(pBueffel," "); - strcat(pBueffel,pCurrent->pName); - iNum++; - } - else - { - strcat(pBueffel," "); - strcat(pBueffel,pCurrent->pName); - strcat(pBueffel,"\r\n"); - SCWrite(pCon,pBueffel,eValue); - pBueffel[0]='\0'; - iNum = 0; - } - } + pBueffel[0] = '\0'; + pCurrent = pSics->pCList; + while (pCurrent) { + pObj = FindDescriptor(pCurrent->pData); + if (pObj != NULL) { + if (!match(mask, pObj->name)) { + if (iNum == 0) { + strcpy(pBueffel, pCurrent->pName); + iNum++; + } else if (iNum < 4) { + strcat(pBueffel, " "); + strcat(pBueffel, pCurrent->pName); + iNum++; + } else { + strcat(pBueffel, " "); + strcat(pBueffel, pCurrent->pName); + strcat(pBueffel, "\r\n"); + SCWrite(pCon, pBueffel, eValue); + pBueffel[0] = '\0'; + iNum = 0; + } } - pCurrent = pCurrent->pNext; } - - /* write final entries */ - strcat(pBueffel,"\r\n"); - SCWrite(pCon,pBueffel,eValue); + pCurrent = pCurrent->pNext; + } + + /* write final entries */ + strcat(pBueffel, "\r\n"); + SCWrite(pCon, pBueffel, eValue); } + /*----------------------------------------------------------------------- printType prints only those objects whose descriptor match the type given -------------------------------------------------------------------------*/ -static void printType(SicsInterp *pSics, SConnection *pCon, char *typeName) +static void printType(SicsInterp * pSics, SConnection * pCon, + char *typeName) { - CommandList *pCurrent; - Tcl_DString txt; - char pBueffel[256]; - int iNum = 0; + CommandList *pCurrent; + Tcl_DString txt; + char pBueffel[256]; + int iNum = 0; - assert(pSics); - assert(pCon); + assert(pSics); + assert(pCon); - Tcl_DStringInit(&txt); - pBueffel[0] = '\0'; - pCurrent = pSics->pCList; - while(pCurrent) - { - if(pCurrent->pData != NULL) - { - if(iHasType(pCurrent->pData,typeName)) - { - if(iNum == 0) - { - strcpy(pBueffel,pCurrent->pName); - iNum++; - } - else if(iNum < 4) - { - strcat(pBueffel," "); - strcat(pBueffel,pCurrent->pName); - iNum++; - } - else - { - strcat(pBueffel," "); - strcat(pBueffel,pCurrent->pName); - strcat(pBueffel,"\r\n"); - Tcl_DStringAppend(&txt,pBueffel,-1); - pBueffel[0]='\0'; - iNum = 0; - } - } + Tcl_DStringInit(&txt); + pBueffel[0] = '\0'; + pCurrent = pSics->pCList; + while (pCurrent) { + if (pCurrent->pData != NULL) { + if (iHasType(pCurrent->pData, typeName)) { + if (iNum == 0) { + strcpy(pBueffel, pCurrent->pName); + iNum++; + } else if (iNum < 4) { + strcat(pBueffel, " "); + strcat(pBueffel, pCurrent->pName); + iNum++; + } else { + strcat(pBueffel, " "); + strcat(pBueffel, pCurrent->pName); + strcat(pBueffel, "\r\n"); + Tcl_DStringAppend(&txt, pBueffel, -1); + pBueffel[0] = '\0'; + iNum = 0; + } } - pCurrent = pCurrent->pNext; } - - /* write final entries */ - strcat(pBueffel,"\r\n"); - SCWrite(pCon,Tcl_DStringValue(&txt),eValue); - Tcl_DStringFree(&txt); + pCurrent = pCurrent->pNext; + } + + /* write final entries */ + strcat(pBueffel, "\r\n"); + SCWrite(pCon, Tcl_DStringValue(&txt), eValue); + Tcl_DStringFree(&txt); } + /*--------------------------------------------------------------------------*/ - int ListObjects(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pType[256]; - int i; - - if(argc < 2) - { - printAll(pSics,pCon); - return 1; - } - - strtolower(argv[1]); - /* - stand alone subcommands - */ - if(strstr(argv[1],"var") != NULL) - { - printType(pSics,pCon,"SicsVariable"); - return 1; - } - if(strstr(argv[1],"mot") != NULL) - { - printType(pSics,pCon,"Motor"); - return 1; - } - /* Start Mod by Paul Hathaway May 2004 */ - if(0 == strcmp(argv[1],"types")) - { - printAllTypes(pSics,pCon,1); - return 1; - } - /* End Mod by Paul Hathaway May 2004*/ - - - /* - subcommand with three args - */ - if(argc < 3) - { - SCWrite(pCon,"ERROR: missing parameter to command or bad subcommand", - eError); - return 0; - } - - /* - interface - */ - if(strcmp(argv[1],"inter") == 0) - { - strtolower(argv[2]); - if(strstr(argv[2],"driv") != NULL) - { - printInterface(pSics,pCon,DRIVEID); - return 1; - } - if(strstr(argv[2],"coun") != NULL) - { - printInterface(pSics,pCon,COUNTID); - return 1; - } - if(strstr(argv[2],"env") != NULL) - { - printInterface(pSics,pCon,ENVIRINTERFACE); - return 1; - } - SCWrite(pCon,"ERROR: interface description not recognized",eError); - return 0; - } - /* - match - */ - if(strcmp(argv[1],"match") == 0) - { - printMatch(pSics,pCon,argv[2]); - return 1; - } - - /* Start Mod by Paul Hathaway May 2004 */ - /* - * type-based dir - */ - if(0 == strcmp(argv[1],"type")) - { - if(0==strcmp(argv[2],"*")) - { - printAllTypes(pSics,pCon,0); - return 1; - } - strcpy(pType,argv[2]); - /* Cater for multi-word types eg 'Environment Monitor' */ - if(argc > 3) - { - for(i=3;ipTcl; - Tcl_SetResult(pTcl,buffer,TCL_VOLATILE); + + strtolower(argv[1]); + /* + stand alone subcommands + */ + if (strstr(argv[1], "var") != NULL) { + printType(pSics, pCon, "SicsVariable"); return 1; } -/*---------------------------------------------------------------------------*/ - Tcl_Interp *InterpGetTcl(SicsInterp *pSics) - { - Tcl_Interp *pTcl = NULL; - - pTcl = (Tcl_Interp *)pSics->pTcl; - return pTcl; + if (strstr(argv[1], "mot") != NULL) { + printType(pSics, pCon, "Motor"); + return 1; } -/*---------------------------------------------------------------------------*/ - void strtolower(char *pText) - { - assert(pText); - - while(*pText != '\0') - { - *pText = tolower(*pText); - pText++; - } + /* Start Mod by Paul Hathaway May 2004 */ + if (0 == strcmp(argv[1], "types")) { + printAllTypes(pSics, pCon, 1); + return 1; } -/*---------------------------------------------------------------------------*/ - void argtolower(int argc, char *argv[]) - { - int i; - - for(i = 0; i < argc; i++) - { - strtolower(argv[i]); - } - } - -/*------------------------------------------------------------------------*/ - char *FindAlias(SicsInterp *self, void *pData) - { - CommandList *pCurrent = NULL; + /* End Mod by Paul Hathaway May 2004 */ - assert(self); - - if(self->iDeleting) - { - return NULL; + + /* + subcommand with three args + */ + if (argc < 3) { + SCWrite(pCon, "ERROR: missing parameter to command or bad subcommand", + eError); + return 0; + } + + /* + interface + */ + if (strcmp(argv[1], "inter") == 0) { + strtolower(argv[2]); + if (strstr(argv[2], "driv") != NULL) { + printInterface(pSics, pCon, DRIVEID); + return 1; } - - pCurrent = self->pCList; - while(pCurrent) - { - if(pCurrent->pData == pData) - { - return pCurrent->pName; + if (strstr(argv[2], "coun") != NULL) { + printInterface(pSics, pCon, COUNTID); + return 1; + } + if (strstr(argv[2], "env") != NULL) { + printInterface(pSics, pCon, ENVIRINTERFACE); + return 1; + } + SCWrite(pCon, "ERROR: interface description not recognized", eError); + return 0; + } + /* + match + */ + if (strcmp(argv[1], "match") == 0) { + printMatch(pSics, pCon, argv[2]); + return 1; + } + + /* Start Mod by Paul Hathaway May 2004 */ + /* + * type-based dir + */ + if (0 == strcmp(argv[1], "type")) { + if (0 == strcmp(argv[2], "*")) { + printAllTypes(pSics, pCon, 0); + return 1; + } + strcpy(pType, argv[2]); + /* Cater for multi-word types eg 'Environment Monitor' */ + if (argc > 3) { + for (i = 3; i < argc; i++) { + strcat(pType, " "); + strcat(pType, argv[i]); } - pCurrent = pCurrent->pNext; } - return NULL; - } -/*---------------------------------------------------------------------------*/ - void *FindCommandData(SicsInterp *pSics, char *name, char *cclass) - { - CommandList *pCom; - pDummy pDum = NULL; - - pCom = FindCommand(pSics,name); - if(!pCom) - { - return NULL; - } - if(!pCom->pData) - return NULL; - - if (cclass == NULL) - { - return pCom->pData; - } - - pDum = (pDummy)pCom->pData; - if(strcmp(pDum->pDescriptor->name,cclass) == 0) - { - return pCom->pData; - } - return NULL; + printType(pSics, pCon, pType); + return 1; } + /* End Mod by Paul Hathaway May 2004 */ + + return 1; +} + /*---------------------------------------------------------------------------*/ - pObjectDescriptor FindCommandDescriptor(SicsInterp *pSics, char *name) - { - CommandList *pCom; - - pCom = FindCommand(pSics,name); - if(pCom == NULL || pCom->pData == NULL) - { - return NULL; - } - - return ((pDummy)pCom->pData)->pDescriptor; +int InterpWrite(SicsInterp * pSics, char *buffer) +{ + Tcl_Interp *pTcl = NULL; + + assert(pSics); + pTcl = (Tcl_Interp *) pSics->pTcl; + Tcl_SetResult(pTcl, buffer, TCL_VOLATILE); + return 1; +} + +/*---------------------------------------------------------------------------*/ +Tcl_Interp *InterpGetTcl(SicsInterp * pSics) +{ + Tcl_Interp *pTcl = NULL; + + pTcl = (Tcl_Interp *) pSics->pTcl; + return pTcl; +} + +/*---------------------------------------------------------------------------*/ +void strtolower(char *pText) +{ + assert(pText); + + while (*pText != '\0') { + *pText = tolower(*pText); + pText++; } +} + +/*---------------------------------------------------------------------------*/ +void argtolower(int argc, char *argv[]) +{ + int i; + + for (i = 0; i < argc; i++) { + strtolower(argv[i]); + } +} + /*------------------------------------------------------------------------*/ -void *FindDrivable(SicsInterp *pSics, char *name){ +char *FindAlias(SicsInterp * self, void *pData) +{ + CommandList *pCurrent = NULL; + + assert(self); + + if (self->iDeleting) { + return NULL; + } + + pCurrent = self->pCList; + while (pCurrent) { + if (pCurrent->pData == pData) { + return pCurrent->pName; + } + pCurrent = pCurrent->pNext; + } + return NULL; +} + +/*---------------------------------------------------------------------------*/ +void *FindCommandData(SicsInterp * pSics, char *name, char *cclass) +{ + CommandList *pCom; + pDummy pDum = NULL; + + pCom = FindCommand(pSics, name); + if (!pCom) { + return NULL; + } + if (!pCom->pData) + return NULL; + + if (cclass == NULL) { + return pCom->pData; + } + + pDum = (pDummy) pCom->pData; + if (strcmp(pDum->pDescriptor->name, cclass) == 0) { + return pCom->pData; + } + return NULL; +} + +/*---------------------------------------------------------------------------*/ +pObjectDescriptor FindCommandDescriptor(SicsInterp * pSics, char *name) +{ + CommandList *pCom; + + pCom = FindCommand(pSics, name); + if (pCom == NULL || pCom->pData == NULL) { + return NULL; + } + + return ((pDummy) pCom->pData)->pDescriptor; +} + +/*------------------------------------------------------------------------*/ +void *FindDrivable(SicsInterp * pSics, char *name) +{ pIDrivable pDriv; pDummy pDum = NULL; CommandList *pCom = NULL; - pCom = FindCommand(pSics,name); - if(pCom != NULL){ - pDum = (pDummy)pCom->pData; - if(pDum != NULL){ - return pDum->pDescriptor->GetInterface(pDum,DRIVEID); + pCom = FindCommand(pSics, name); + if (pCom != NULL) { + pDum = (pDummy) pCom->pData; + if (pDum != NULL) { + return pDum->pDescriptor->GetInterface(pDum, DRIVEID); } } @@ -1030,121 +953,111 @@ void *FindDrivable(SicsInterp *pSics, char *name){ * linked list module. May extend toallow different output formats * (eg multi/single column) via switches */ -static void printList(SConnection *pCon, int listID) +static void printList(SConnection * pCon, int listID) { - char pBueffel[MAXBUF]; - int retCode; + char pBueffel[MAXBUF]; + int retCode; - if(0!=LLDnodePtr2First(listID)) - { - do - { - retCode = LLDstringData(listID,NULL); - if ((MAXBUF-3) > retCode) { - retCode = LLDstringData(listID,pBueffel); - strcat(pBueffel,"\r\n"); - SCWrite(pCon,pBueffel,eValue); - } - } while(0!=LLDnodePtr2Next(listID)); - } + if (0 != LLDnodePtr2First(listID)) { + do { + retCode = LLDstringData(listID, NULL); + if ((MAXBUF - 3) > retCode) { + retCode = LLDstringData(listID, pBueffel); + strcat(pBueffel, "\r\n"); + SCWrite(pCon, pBueffel, eValue); + } + } while (0 != LLDnodePtr2Next(listID)); + } } /*------------------------------------------------------------------------*/ static void freeList(int listID) { - do { - LLDstringDelete(listID); - } while(0!=LLDnodePtr2First(listID)); - LLDdelete(listID); + do { + LLDstringDelete(listID); + } while (0 != LLDnodePtr2First(listID)); + LLDdelete(listID); } /*------------------------------------------------------------------------*/ - void RemoveStartupCommands(void) - { - CommandList *pCurrent, *pNext; - pCurrent = pServ->pSics->pCList; - while(pCurrent) - { - pNext = pCurrent->pNext; - if (pCurrent->startupOnly) { - RemoveCommand(pServ->pSics, pCurrent->pName); - } - pCurrent = pNext; - } - } -/*---------------------------------------------------------------------*/ -char *FindAliases(SicsInterp *pSics, char *name) +void RemoveStartupCommands(void) { - pDynString result = NULL; - CommandList *pOri = NULL, *pCom = NULL; - char *pTrans = NULL, *charResult = NULL; - int first; - - pOri = FindCommand(pSics, name); - if(pOri == NULL) - { - return NULL; - } - if(pOri->pData == NULL) - { - return NULL; - } - - result = CreateDynString(64,64); - if(result == NULL) - { - return NULL; - } - - /* try first to locate Markus style aliases */ - pTrans = TranslateAlias(&pSics->AList,name); - if(strcmp(pTrans,name) != 0) - { - DynStringCopy(result,pTrans); - charResult = strdup(GetCharArray(result)); - DeleteDynString(result); - return charResult; - } - - /* - * locate SicsAlias style aliases by comparing the original - * data pointer with the data pointers of other commands - */ - first = 1; - pCom = pSics->pCList; - while(pCom != NULL) - { - if(pCom != pOri && pCom->pData == pOri->pData) - { - if(first) - { - DynStringCopy(result,pCom->pName); - first = 0; - } - else - { - DynStringConcat(result,","); - DynStringConcat(result,pCom->pName); - } - } - pCom = pCom->pNext; - } - charResult = strdup(GetCharArray(result)); - DeleteDynString(result); - return charResult; + CommandList *pCurrent, *pNext; + pCurrent = pServ->pSics->pCList; + while (pCurrent) { + pNext = pCurrent->pNext; + if (pCurrent->startupOnly) { + RemoveCommand(pServ->pSics, pCurrent->pName); + } + pCurrent = pNext; + } } + /*---------------------------------------------------------------------*/ -void ForEachCommand(int (*scanFunction)(char *name, pDummy object, void *userData) - , void *userData) +char *FindAliases(SicsInterp * pSics, char *name) +{ + pDynString result = NULL; + CommandList *pOri = NULL, *pCom = NULL; + char *pTrans = NULL, *charResult = NULL; + int first; + + pOri = FindCommand(pSics, name); + if (pOri == NULL) { + return NULL; + } + if (pOri->pData == NULL) { + return NULL; + } + + result = CreateDynString(64, 64); + if (result == NULL) { + return NULL; + } + + /* try first to locate Markus style aliases */ + pTrans = TranslateAlias(&pSics->AList, name); + if (strcmp(pTrans, name) != 0) { + DynStringCopy(result, pTrans); + charResult = strdup(GetCharArray(result)); + DeleteDynString(result); + return charResult; + } + + /* + * locate SicsAlias style aliases by comparing the original + * data pointer with the data pointers of other commands + */ + first = 1; + pCom = pSics->pCList; + while (pCom != NULL) { + if (pCom != pOri && pCom->pData == pOri->pData) { + if (first) { + DynStringCopy(result, pCom->pName); + first = 0; + } else { + DynStringConcat(result, ","); + DynStringConcat(result, pCom->pName); + } + } + pCom = pCom->pNext; + } + charResult = strdup(GetCharArray(result)); + DeleteDynString(result); + return charResult; +} + +/*---------------------------------------------------------------------*/ +void +ForEachCommand(int (*scanFunction) + (char *name, pDummy object, void *userData) + , void *userData) { CommandList *pCurrent; - - - for(pCurrent = pServ->pSics->pCList; - pCurrent != NULL; - pCurrent = pCurrent->pNext) - { - if(scanFunction(pCurrent->pName, pCurrent->pData, userData) == 0) { + + + for (pCurrent = pServ->pSics->pCList; + pCurrent != NULL; pCurrent = pCurrent->pNext) { + if (scanFunction(pCurrent->pName, pCurrent->pData, userData) == 0) { return; } } diff --git a/SCinter.h b/SCinter.h index 1b24ce24..02b790e0 100644 --- a/SCinter.h +++ b/SCinter.h @@ -9,149 +9,148 @@ ---------------------------------------------------------------------------*/ #ifndef SICSINTERPRETER #define SICSINTERPRETER -#include "obdes.h" -#include "Scommon.h" +#include "obdes.h" +#include "Scommon.h" #include "statistics.h" #include /* M.Z. */ #include "definealias.i" typedef struct __SConnection *pSConnection; -typedef struct __SINTER *pSicsInterp; +typedef struct __SINTER *pSicsInterp; -typedef int (*ObjectFunc)(pSConnection pCon, pSicsInterp pInter, void - *pData, int argc, char *argv[]); +typedef int (*ObjectFunc) (pSConnection pCon, pSicsInterp pInter, void + *pData, int argc, char *argv[]); -typedef void (*KillFunc)(void *pData); +typedef void (*KillFunc) (void *pData); typedef struct __Clist { - char *pName; - ObjectFunc OFunc; - KillFunc KFunc; - void *pData; - struct __Clist *pNext; - struct __Clist *pPrevious; - int startupOnly; - Statistics *stat; - } CommandList; + char *pName; + ObjectFunc OFunc; + KillFunc KFunc; + void *pData; + struct __Clist *pNext; + struct __Clist *pPrevious; + int startupOnly; + Statistics *stat; +} CommandList; + +typedef struct __SINTER { + CommandList *pCList; + OutCode eOut; + void *pTcl; + int iDeleting; + AliasList AList; /* M.Z. */ +} SicsInterp; -typedef struct __SINTER - { - CommandList *pCList; - OutCode eOut; - void *pTcl; - int iDeleting; - AliasList AList; /* M.Z. */ - }SicsInterp; - /*-------------------------------------------------------------------------*/ - SicsInterp *InitInterp(void); +SicsInterp *InitInterp(void); /* makes a new interpreter. Returns him on success, else NULL - */ -/*------------------------------------------------------------------------*/ - int AddCommand(SicsInterp *pInterp, char *pName, ObjectFunc pFunc, - KillFunc pKFunc, void *pData); + */ +/*------------------------------------------------------------------------*/ +int AddCommand(SicsInterp * pInterp, char *pName, ObjectFunc pFunc, + KillFunc pKFunc, void *pData); /* adds a new command, Returns True or False, depending on success Parameters: - pInterp : the interpreter to add the command to. - pName : the commands name - pFunc : the object function to call when this command is - invoked. Definition of type: see above - pKFunc : function to call in order to delete command data. - type definition: above - pData : pointer to the command's own datastructure. Will be - passed as pData with each call to Ofunc. - */ -/*-------------------------------------------------------------------------*/ - int RemoveCommand(SicsInterp *pInterp, char *pName); + pInterp : the interpreter to add the command to. + pName : the commands name + pFunc : the object function to call when this command is + invoked. Definition of type: see above + pKFunc : function to call in order to delete command data. + type definition: above + pData : pointer to the command's own datastructure. Will be + passed as pData with each call to Ofunc. + */ +/*-------------------------------------------------------------------------*/ +int RemoveCommand(SicsInterp * pInterp, char *pName); /* kills the command name from the interpreter pInterp - */ -/*-------------------------------------------------------------------------*/ - int AddCommandWithFlag(SicsInterp *pInterp, char *pName, ObjectFunc pFunc, - KillFunc pKFunc, void *pData, int startupFlag); - int AddIniCmd(char *pName, ObjectFunc pFunc); /* command will be deleted after startup */ - int AddCmd(char *pName, ObjectFunc pFunc); /* syntactic sugar for AddCommand without data */ - void RemoveStartupCommands(void); /* called after startup to delete startup commands */ -/*-------------------------------------------------------------------------*/ - int InterpExecute(SicsInterp *self,pSConnection pCon,char *pCommand); - + */ +/*-------------------------------------------------------------------------*/ +int AddCommandWithFlag(SicsInterp * pInterp, char *pName, ObjectFunc pFunc, + KillFunc pKFunc, void *pData, int startupFlag); +int AddIniCmd(char *pName, ObjectFunc pFunc); /* command will be deleted after startup */ +int AddCmd(char *pName, ObjectFunc pFunc); /* syntactic sugar for AddCommand without data */ +void RemoveStartupCommands(void); /* called after startup to delete startup commands */ +/*-------------------------------------------------------------------------*/ +int InterpExecute(SicsInterp * self, pSConnection pCon, char *pCommand); + /* - executes a command in the interpreter self. Essentially converts - pCommand in an argc, argv[] pair, sets various status things and - invokes the object function. Takes care of status and error reporting - afterwards. - - Parameters: - self : interpreter to invoke command in. - The connection pCon will be used for I/O and status reporting. - The command to invoke is the string pCommand. - Returns -1 if the command can not be found. - If the command is found, 1 is returned on success, 0 on failure in - the command. -----------------------------------------------------------------------------*/ - CommandList *FindCommand(SicsInterp *pInterp, char *name); + executes a command in the interpreter self. Essentially converts + pCommand in an argc, argv[] pair, sets various status things and + invokes the object function. Takes care of status and error reporting + afterwards. + + Parameters: + self : interpreter to invoke command in. + The connection pCon will be used for I/O and status reporting. + The command to invoke is the string pCommand. + Returns -1 if the command can not be found. + If the command is found, 1 is returned on success, 0 on failure in + the command. + ---------------------------------------------------------------------------- */ +CommandList *FindCommand(SicsInterp * pInterp, char *name); /* Searches the Interpreters pInterp command list for a command with name. Returns ist datastructure if found, NULL else - */ + */ /*-------------------------------------------------------------------------*/ - int WriteSicsStatus(SicsInterp *pSics,char *file, int iMot); +int WriteSicsStatus(SicsInterp * pSics, char *file, int iMot); /* - SICS needs a way to save the status of each object into a file. - This is done by invoking for each object the object descriptor - function SaveStatus. This function does just that. - - Parameters: - pSics : the interpreter to use. - file : the file to write the information to. - iMot : flag if motor position shall be saved or not - Returns: 1 on success, 0 on failure. ----------------------------------------------------------------------------*/ - int InterpWrite(SicsInterp *pSics, char *buffer); + SICS needs a way to save the status of each object into a file. + This is done by invoking for each object the object descriptor + function SaveStatus. This function does just that. + + Parameters: + pSics : the interpreter to use. + file : the file to write the information to. + iMot : flag if motor position shall be saved or not + Returns: 1 on success, 0 on failure. + --------------------------------------------------------------------------- */ +int InterpWrite(SicsInterp * pSics, char *buffer); /* writes result to Tcl, used for Macro mechanism. This is an internal function and should not be used. -----------------------------------------------------------------------------*/ - - void DeleteInterp(SicsInterp *self); + ---------------------------------------------------------------------------- */ + +void DeleteInterp(SicsInterp * self); /* deletes the interpreter self aand clears all asoociated datastructures. self will no longer be valid after this. ---------------------------------------------------------------------------- */ - void strtolower(char *pText); + --------------------------------------------------------------------------- */ +void strtolower(char *pText); /* - strtolower converts a string to lowercase ---------------------------------------------------------------------------- */ - void argtolower(int argc, char *argv[]); + strtolower converts a string to lowercase + --------------------------------------------------------------------------- */ +void argtolower(int argc, char *argv[]); /* - converts an argc, argv[] pair to lowercase - */ + converts an argc, argv[] pair to lowercase + */ /*-------------------------------------------------------------------------- FindAlias tries to find an alias to the datastructure given as second parameter. Returns the command name on success, else NULL. Be warned, this is very special */ - - char *FindAlias(SicsInterp *pSics, void *pData); + +char *FindAlias(SicsInterp * pSics, void *pData); /*---------------------------------------------------------------------- FindAliases locates alle aliases related to a gibe name. The result is returned as a komma separated list. */ - char *FindAliases(SicsInterp *pSics, char *name); +char *FindAliases(SicsInterp * pSics, char *name); /*------------------------------------------------------------------------- FindCommandData finds a command with the name given. It tests the name in the ObjectDescriptor to be of name class. If all this succeeds a pointer to the commands data structure is retuned. Else NULL. Do not test the Object Descriptor name when comclass == NULL. */ - void *FindCommandData(SicsInterp *pSics, char *name, char *comclass); +void *FindCommandData(SicsInterp * pSics, char *name, char *comclass); /*------------------------------------------------------------------------- FindCommandDescriptor finds the descriptor of a command with the name given. */ - pObjectDescriptor FindCommandDescriptor(SicsInterp *pSics, char *name); +pObjectDescriptor FindCommandDescriptor(SicsInterp * pSics, char *name); /*------------------------------------------------------------------------ FindDrivable tries to find Drivable object by the name given. Returns a @@ -159,18 +158,19 @@ typedef struct __SINTER case of failure. In order to save me fixing header files the pointer must be cast to the drivable interface pointer. */ -void *FindDrivable(SicsInterp *pics, char *name); +void *FindDrivable(SicsInterp * pics, char *name); /*------------------------------------------------------------------------ Go through the command list and call scanFunction for every command until the return value is 0. */ -void ForEachCommand(int (*scanFunction)(char *name, pDummy object, void *userData) - , void *userData); +void +ForEachCommand(int (*scanFunction) + (char *name, pDummy object, void *userData) + , void *userData); /*----------------------------------------------------------------------- Get a copy of the Tcl interpreter - ------------------------------------------------------------------------*/ -Tcl_Interp *InterpGetTcl(SicsInterp *pSics); + ------------------------------------------------------------------------*/ +Tcl_Interp *InterpGetTcl(SicsInterp * pSics); #endif - diff --git a/SICSmain.c b/SICSmain.c index 08639957..f6187cf7 100644 --- a/SICSmain.c +++ b/SICSmain.c @@ -25,9 +25,9 @@ /***************************** Necessary Globals ****************************/ - IPair *pSICSOptions = NULL; - pServer pServ = NULL; - +IPair *pSICSOptions = NULL; +pServer pServ = NULL; + /* ========================= Less dreadful file statics =================== */ #define DEFAULTINIFILE "servo.tcl" @@ -36,55 +36,57 @@ The Servers Main program. May take one argument: the name of an initialisation file */ - - int main(int argc, char *argv[]) - { - int iRet; - char *file=NULL; - int i; - /* initialise, will die on you if problems */ - for (i=1; ipSics; + iRet = InitServer(file, &pServ); + if (!iRet) { + printf("Unrecoverable error on server startup, exiting.........\n"); + exit(1); } + + + RunServer(pServ); + + StopServer(pServ); + pServ = NULL; + exit(0); +} + /*--------------------------------------------------------------------------*/ - pExeList GetExecutor(void) - { - return pServ->pExecutor; - } +SicsInterp *GetInterpreter(void) +{ + return pServ->pSics; +} + +/*--------------------------------------------------------------------------*/ +pExeList GetExecutor(void) +{ + return pServ->pExecutor; +} + /*------------------------------------------------------------------------*/ - void StopExit(void) - { - if(pServ) - { - StopServer(pServ); - } - } +void StopExit(void) +{ + if (pServ) { + StopServer(pServ); + } +} + /*-------------------------------------------------------------------------*/ - pTaskMan GetTasker(void) - { - return pServ->pTasker; - } +pTaskMan GetTasker(void) +{ + return pServ->pTasker; +} diff --git a/Scommon.h b/Scommon.h index c65443d0..4d356e7e 100644 --- a/Scommon.h +++ b/Scommon.h @@ -40,23 +40,23 @@ /* this enum defines the output types in SICS */ typedef enum { - eInternal, /* internal */ - eCommand, /* reserved, not used */ - eHWError, /* reserved, used only for SICSLog */ - eInError, /* reserved, used as a mark in the handling of output codes */ - eStatus, /* reserved, deprecated */ - eValue, /* value reponse: copied into Tcl */ - eStart, /* start message */ - eFinish, /* finish message */ - eEvent, /* some callback messages */ - eWarning, /* warnings */ - eError, /* error: copied into Tcl */ - eHdbValue, /* hipadaba value chnage */ - eHdbEvent, /* Hipadaba event */ - eLog, /* log message: is always written to client */ - eLogError /* error message to log: is always written to client */ - } OutCode; - + eInternal, /* internal */ + eCommand, /* reserved, not used */ + eHWError, /* reserved, used only for SICSLog */ + eInError, /* reserved, used as a mark in the handling of output codes */ + eStatus, /* reserved, deprecated */ + eValue, /* value reponse: copied into Tcl */ + eStart, /* start message */ + eFinish, /* finish message */ + eEvent, /* some callback messages */ + eWarning, /* warnings */ + eError, /* error: copied into Tcl */ + eHdbValue, /* hipadaba value chnage */ + eHdbEvent, /* Hipadaba event */ + eLog, /* log message: is always written to client */ + eLogError /* error message to log: is always written to client */ +} OutCode; + #include "interrupt.h" /* define some user rights codes */ @@ -84,6 +84,5 @@ typedef enum { */ #include "ifile.h" extern IPair *pSICSOptions; - -#endif +#endif diff --git a/access.c b/access.c index 110947e9..51e62db0 100644 --- a/access.c +++ b/access.c @@ -7,26 +7,28 @@ #include #include - static char *aCode[] = { - "internal", - "mugger", - "user", - "spy", - NULL }; - static int iCodes = 4; +static char *aCode[] = { + "internal", + "mugger", + "user", + "spy", + NULL +}; +static int iCodes = 4; /*--------------------------------------------------------------------------*/ -int decodeSICSPriv(char *privText){ - int code = 0; - - strtolower(privText); - while(aCode[code] != NULL){ - if(strcmp(aCode[code], privText) == 0){ - return code; - } - code++; - } - if(code >= iCodes){ - return -1; +int decodeSICSPriv(char *privText) +{ + int code = 0; + + strtolower(privText); + while (aCode[code] != NULL) { + if (strcmp(aCode[code], privText) == 0) { + return code; } + code++; + } + if (code >= iCodes) { return -1; + } + return -1; } diff --git a/alias.c b/alias.c index 45155e15..f5e26762 100644 --- a/alias.c +++ b/alias.c @@ -45,72 +45,69 @@ /* Usage: SicsAlias object newname -*/ +*/ - int SicsAlias(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - CommandList *pCom = NULL; - char pBueffel[256]; - int iRet; - - if(!SCMatchRights(pCon,usMugger)) - { - SCWrite(pCon,"ERROR: aliasing only allowed to Managers", - eError); - return 0; - } - - if(argc < 3) - { - SCWrite(pCon,"ERROR: insufficient number of arguments to SicsAlias", - eError); - return 0; - } +int SicsAlias(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL; + char pBueffel[256]; + int iRet; + + if (!SCMatchRights(pCon, usMugger)) { + SCWrite(pCon, "ERROR: aliasing only allowed to Managers", eError); + return 0; + } + + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient number of arguments to SicsAlias", + eError); + return 0; + } + + argtolower(argc, argv); + /* first parameter should be an registered SICS object */ + pCom = FindCommand(pSics, argv[1]); + if (!pCom) { + sprintf(pBueffel, "ERROR: cannot find %s, no alias created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* alright: create the alias */ + iRet = AddCommand(pSics, argv[2], pCom->OFunc, NULL, pCom->pData); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} - argtolower(argc,argv); - /* first parameter should be an registered SICS object */ - pCom = FindCommand(pSics,argv[1]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: cannot find %s, no alias created",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* alright: create the alias */ - iRet = AddCommand(pSics,argv[2],pCom->OFunc,NULL,pCom->pData); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } /*-------------------------------------------------------------------- Make Alias: a command which installs a general alias into SICS. */ - typedef struct { - pObjectDescriptor pDes; - char *pCommand; - }Alias, *pAlias; +typedef struct { + pObjectDescriptor pDes; + char *pCommand; +} Alias, *pAlias; /*----------------------------------------------------------------------*/ - static void FreeAlias(void *pData) - { - pAlias self = (pAlias)pData; - if(!self) - return; +static void FreeAlias(void *pData) +{ + pAlias self = (pAlias) pData; + if (!self) + return; - if(self->pDes) - DeleteDescriptor(self->pDes); + if (self->pDes) + DeleteDescriptor(self->pDes); - if(self->pCommand) - free(self->pCommand); + if (self->pCommand) + free(self->pCommand); + + free(self); +} - free(self); - } /*---------------------------------------------------------------------- In order to make alias most general alias tries to find the interfaces defined by the object corresponding to the first word in the command. @@ -118,116 +115,113 @@ will be called refers to the alias and not the proper thing: core dump! Therefore disabled! */ - static void *AliasInterface(void *pData, int iID) - { - CommandList *pCom = NULL; - pDummy pDum = NULL; - char *pPtr = NULL; - pAlias self = (pAlias)pData; +static void *AliasInterface(void *pData, int iID) +{ + CommandList *pCom = NULL; + pDummy pDum = NULL; + char *pPtr = NULL; + pAlias self = (pAlias) pData; - assert(self); - pPtr = strtok(self->pCommand," \t\n"); - pCom = FindCommand(pServ->pSics,pPtr); - if(!pCom) - return NULL; + assert(self); + pPtr = strtok(self->pCommand, " \t\n"); + pCom = FindCommand(pServ->pSics, pPtr); + if (!pCom) + return NULL; - pDum = (pDummy)pCom->pData; - if(!pDum) - return NULL; + pDum = (pDummy) pCom->pData; + if (!pDum) + return NULL; - return pDum->pDescriptor->GetInterface(pDum,iID); - } -/*-----------------------------------------------------------------------*/ - static int AliasAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) - { - pAlias self = NULL; - int status; - char pLine[512]; - char *pPtr; - Tcl_DString command; - - self = (pAlias)pData; - assert(self); - - /* - build command by appending the alias command and any possible - arguments given. - */ - Tcl_DStringInit(&command); - Tcl_DStringAppend(&command, self->pCommand,-1); - Tcl_DStringAppend(&command," ",-1); - Arg2Text(argc-1,&argv[1],pLine,511); - Tcl_DStringAppend(&command,pLine,-1); - - /* execute the command on the current connection */ - status = SCInvoke(pCon,pSics,Tcl_DStringValue(&command)); - - /* finish */ - Tcl_DStringFree(&command); - return status; - } -/*-----------------------------------------------------------------------*/ - int MakeAlias(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - int iRet; - pAlias pNew = NULL; - - if(argc < 3) - { - SCWrite(pCon,"ERROR: insufficient number of arguments to alias", - eError); - return 0; - } - - Arg2Text(argc-2,&argv[2],pBueffel,511); - - /* create data structure */ - pNew = (pAlias)malloc(sizeof(Alias)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory while creating alias",eError); - return 0; - } - pNew->pDes = CreateDescriptor("Alias"); - pNew->pCommand = strdup(pBueffel); - if( !pNew->pDes || !pNew->pCommand) - { - SCWrite(pCon,"ERROR: out of memory while creating alias",eError); - return 0; - } - - iRet = AddCommand(pSics, - argv[1], - AliasAction, - FreeAlias, - pNew); - if(!iRet) - { - FreeAlias(pNew); - SCWrite(pCon,"ERROR: duplicate object name NOT created",eError); - return 0; - } - return 1; - } -/*-------------------------------------------------------------------------------*/ -int LocateAliasAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - char *aliases = NULL; - - if(argc < 2){ - SCWrite(pCon,"ERROR: missing argument aliasname for locating aliases",eError); - return 0; - } - - strtolower(argv[1]); - aliases = FindAliases(pSics,argv[1]); - if(aliases == NULL){ - SCWrite(pCon,"NONE", eValue); - } else { - SCPrintf(pCon,eValue,"%s = %s",argv[1], aliases); - } - return 1; + return pDum->pDescriptor->GetInterface(pDum, iID); +} + +/*-----------------------------------------------------------------------*/ +static int AliasAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pAlias self = NULL; + int status; + char pLine[512]; + char *pPtr; + Tcl_DString command; + + self = (pAlias) pData; + assert(self); + + /* + build command by appending the alias command and any possible + arguments given. + */ + Tcl_DStringInit(&command); + Tcl_DStringAppend(&command, self->pCommand, -1); + Tcl_DStringAppend(&command, " ", -1); + Arg2Text(argc - 1, &argv[1], pLine, 511); + Tcl_DStringAppend(&command, pLine, -1); + + /* execute the command on the current connection */ + status = SCInvoke(pCon, pSics, Tcl_DStringValue(&command)); + + /* finish */ + Tcl_DStringFree(&command); + return status; +} + +/*-----------------------------------------------------------------------*/ +int MakeAlias(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512]; + int iRet; + pAlias pNew = NULL; + + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient number of arguments to alias", + eError); + return 0; + } + + Arg2Text(argc - 2, &argv[2], pBueffel, 511); + + /* create data structure */ + pNew = (pAlias) malloc(sizeof(Alias)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory while creating alias", eError); + return 0; + } + pNew->pDes = CreateDescriptor("Alias"); + pNew->pCommand = strdup(pBueffel); + if (!pNew->pDes || !pNew->pCommand) { + SCWrite(pCon, "ERROR: out of memory while creating alias", eError); + return 0; + } + + iRet = AddCommand(pSics, argv[1], AliasAction, FreeAlias, pNew); + if (!iRet) { + FreeAlias(pNew); + SCWrite(pCon, "ERROR: duplicate object name NOT created", eError); + return 0; + } + return 1; +} + +/*-------------------------------------------------------------------------------*/ +int LocateAliasAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + char *aliases = NULL; + + if (argc < 2) { + SCWrite(pCon, "ERROR: missing argument aliasname for locating aliases", + eError); + return 0; + } + + strtolower(argv[1]); + aliases = FindAliases(pSics, argv[1]); + if (aliases == NULL) { + SCWrite(pCon, "NONE", eValue); + } else { + SCPrintf(pCon, eValue, "%s = %s", argv[1], aliases); + } + return 1; } diff --git a/alias.h b/alias.h index 4a70827c..d9d4ac55 100644 --- a/alias.h +++ b/alias.h @@ -12,11 +12,10 @@ #ifndef SICSALIAS #define SICSALIAS - int SicsAlias(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int MakeAlias(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int LocateAliasAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SicsAlias(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int MakeAlias(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int LocateAliasAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif - diff --git a/anticollider.c b/anticollider.c index 6c58dbee..2080c3ce 100644 --- a/anticollider.c +++ b/anticollider.c @@ -27,14 +27,16 @@ static pAntiCollider myCollider = NULL; the replacement function for the motor's drivable interface SetValue function. It enters the new target into the motor list. ---------------------------------------------------------------------*/ -static long ReplacementSetValue(void *pData, SConnection *pCon, float fTarget){ +static long ReplacementSetValue(void *pData, SConnection * pCon, + float fTarget) +{ pMotReg pMot = NULL; - + assert(myCollider != NULL); - pMot = FindMotFromDataStructure(myCollider->motorList,pData); - if(pMot != NULL){ - SetRegMotTarget(pMot,fTarget); + pMot = FindMotFromDataStructure(myCollider->motorList, pData); + if (pMot != NULL) { + SetRegMotTarget(pMot, fTarget); myCollider->isDirty = 1; } else { return 0; @@ -42,33 +44,34 @@ static long ReplacementSetValue(void *pData, SConnection *pCon, float fTarget){ return 1; } + /*--------------------------------------------------------------------- The replacement CheckStatus function for controlled motors. Start AntiCollider if not running and finish. Rest of work done by AntiCollider. -----------------------------------------------------------------------*/ -static int ReplacementCheckStatus(void *pData, SConnection *pCon){ +static int ReplacementCheckStatus(void *pData, SConnection * pCon) +{ pMotReg pMot = NULL; - + assert(myCollider != NULL); - if(myCollider->isDirty == 1){ + if (myCollider->isDirty == 1) { myCollider->isDirty = 0; StartDevice(pServ->pExecutor, - "anticollider", - myCollider->pDes, - myCollider, - pCon, - 77.77); + "anticollider", myCollider->pDes, myCollider, pCon, 77.77); return HWIdle; } else { return HWIdle; } } + /*------------------------------------------------------------------------ The collider SetValue function -------------------------------------------------------------------------*/ -static long ColliderSetValue(void *pData, SConnection *pCon, float fTarget){ +static long ColliderSetValue(void *pData, SConnection * pCon, + float fTarget) +{ pAntiCollider self = (pAntiCollider) pData; int iRet; pMotReg pMot = NULL; @@ -78,79 +81,80 @@ static long ColliderSetValue(void *pData, SConnection *pCon, float fTarget){ Tcl_DString command; /* - build command list - */ - if(self->colliderScript == NULL){ - SCWrite(pCon,"ERROR: no collider script defined",eError); + build command list + */ + if (self->colliderScript == NULL) { + SCWrite(pCon, "ERROR: no collider script defined", eError); return 0; } Tcl_DStringInit(&command); - Tcl_DStringAppend(&command,self->colliderScript,-1); + Tcl_DStringAppend(&command, self->colliderScript, -1); iRet = LLDnodePtr2First(self->motorList); - while(iRet != 0){ - LLDnodeDataTo(self->motorList,&pMot); - if(pMot != NULL){ - if(pMot->iActive){ - CreateTargetString(pMot,pBueffel); - Tcl_DStringAppend(&command, pBueffel,-1); - pMot->iActive = 0; + while (iRet != 0) { + LLDnodeDataTo(self->motorList, &pMot); + if (pMot != NULL) { + if (pMot->iActive) { + CreateTargetString(pMot, pBueffel); + Tcl_DStringAppend(&command, pBueffel, -1); + pMot->iActive = 0; } } iRet = LLDnodePtr2Next(self->motorList); } - - /* - kill old collider sequence - */ - LLDdelete(self->sequenceList); - self->sequenceList = LLDcreate(sizeof(Sequence)); - self->level = -1; /* otherwise level 0 will not be started */ /* - evaluate colliderScript - */ - iRet = Tcl_Eval(pServ->pSics->pTcl,Tcl_DStringValue(&command)); - if(iRet != TCL_OK){ - SCWrite(pCon,"ERROR: Movement not possible or bad collider script",eError); - SCWrite(pCon,Tcl_DStringValue(&command),eError); + kill old collider sequence + */ + LLDdelete(self->sequenceList); + self->sequenceList = LLDcreate(sizeof(Sequence)); + self->level = -1; /* otherwise level 0 will not be started */ + + /* + evaluate colliderScript + */ + iRet = Tcl_Eval(pServ->pSics->pTcl, Tcl_DStringValue(&command)); + if (iRet != TCL_OK) { + SCWrite(pCon, "ERROR: Movement not possible or bad collider script", + eError); + SCWrite(pCon, Tcl_DStringValue(&command), eError); /* - SCWrite(pCon,pServ->pSics->pTcl->result,eError); - */ - SCSetInterrupt(pCon,eAbortOperation); + SCWrite(pCon,pServ->pSics->pTcl->result,eError); + */ + SCSetInterrupt(pCon, eAbortOperation); return 0; } /* - we are set - */ + we are set + */ Tcl_DStringFree(&command); return 1; } + /*---------------------------------------------------------------------- The Collider CheckStatus function -----------------------------------------------------------------------*/ -static int ColliderCheckStatus(void *pData, SConnection *pCon){ +static int ColliderCheckStatus(void *pData, SConnection * pCon) +{ int count = 0; pAntiCollider self = (pAntiCollider) pData; assert(self); - if(SCGetInterrupt(pCon) != eContinue){ + if (SCGetInterrupt(pCon) != eContinue) { return HWIdle; } - count = CheckAllMotors(self->motorList,pCon); - if(count == 0){ + count = CheckAllMotors(self->motorList, pCon); + if (count == 0) { self->level++; count = StartLevel(self->level, - self->sequenceList, - self->motorList, - pCon); - if(count == 0){ + self->sequenceList, self->motorList, pCon); + if (count == 0) { /* - no more levels. All done - */ + no more levels. All done + */ return HWIdle; } else { return HWBusy; @@ -159,27 +163,35 @@ static int ColliderCheckStatus(void *pData, SConnection *pCon){ return HWBusy; } } + /*---------------------------------------------------------------------- Most of these are dummies........ -----------------------------------------------------------------------*/ -static int ColliderHalt(void *pData){ +static int ColliderHalt(void *pData) +{ pAntiCollider self = (pAntiCollider) pData; StopAllMotors(self->motorList); self->level = 999999999; return 1; } + /*---------------------------------------------------------------------*/ -static int ColliderLimits(void *self, float fVal, char *error, - int iErren){ +static int ColliderLimits(void *self, float fVal, char *error, int iErren) +{ return 1; } + /*--------------------------------------------------------------------*/ -static float ColliderGetValue(void *self, SConnection *pCon){ +static float ColliderGetValue(void *self, SConnection * pCon) +{ return 77.77; } + /*--------------------------------------------------------------------*/ -int StartLevel(int level, int sequenceList, int motorList, SConnection *pCon){ +int StartLevel(int level, int sequenceList, int motorList, + SConnection * pCon) +{ Sequence seq; pMotReg pMot = NULL; int iRet, status; @@ -187,99 +199,109 @@ int StartLevel(int level, int sequenceList, int motorList, SConnection *pCon){ char pBueffel[132]; iRet = LLDnodePtr2First(sequenceList); - while(iRet != 0){ - LLDnodeDataTo(sequenceList,&seq); - if(seq.level == level){ - pMot = FindMotEntry(motorList,seq.pMotor); - if(pMot){ - status = StartRegMot(pMot,pCon,seq.target); + while (iRet != 0) { + LLDnodeDataTo(sequenceList, &seq); + if (seq.level == level) { + pMot = FindMotEntry(motorList, seq.pMotor); + if (pMot) { + status = StartRegMot(pMot, pCon, seq.target); /* * I have to ignore the problem here: if I do not increment the count * all the other levels will not be drive and the anticollider * gets into a mess */ - count++; + count++; } else { - sprintf(pBueffel,"ERROR: motor %s, requested from anticollider script", - seq.pMotor); - SCWrite(pCon,pBueffel,eError); - SCWrite(pCon,"ERROR: motor NOT found, fix script!",eError); + sprintf(pBueffel, + "ERROR: motor %s, requested from anticollider script", + seq.pMotor); + SCWrite(pCon, pBueffel, eError); + SCWrite(pCon, "ERROR: motor NOT found, fix script!", eError); } } iRet = LLDnodePtr2Next(sequenceList); } return count; } + /*--------------------------------------------------------------------*/ -static void ListSequence(int sequenceList, SConnection *pCon){ +static void ListSequence(int sequenceList, SConnection * pCon) +{ Sequence seq; int iRet; char pBueffel[132]; - SCWrite(pCon,"level motor target",eValue); + SCWrite(pCon, "level motor target", eValue); iRet = LLDnodePtr2First(sequenceList); - while(iRet != 0){ - LLDnodeDataTo(sequenceList,&seq); - sprintf(pBueffel,"%d %s %f",seq.level,seq.pMotor,seq.target); - SCWrite(pCon,pBueffel,eValue); + while (iRet != 0) { + LLDnodeDataTo(sequenceList, &seq); + sprintf(pBueffel, "%d %s %f", seq.level, seq.pMotor, seq.target); + SCWrite(pCon, pBueffel, eValue); iRet = LLDnodePtr2Next(sequenceList); } } + /*-------------------------------------------------------------------------*/ -static void *ColliderGetInterface(void *pData, int iID) { +static void *ColliderGetInterface(void *pData, int iID) +{ pAntiCollider self = NULL; - - self = (pAntiCollider)pData; + + self = (pAntiCollider) pData; assert(self); - if(iID == DRIVEID){ - return self->pDriv; + if (iID == DRIVEID) { + return self->pDriv; } - return NULL; -} + return NULL; +} + /*----------------------------------------------------------------------*/ -void KillCollider(void *pData){ - pAntiCollider self = (pAntiCollider)pData; - - if(self == NULL){ +void KillCollider(void *pData) +{ + pAntiCollider self = (pAntiCollider) pData; + + if (self == NULL) { return; } - if(self->pDes != NULL){ + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); } - if(self->pDriv != NULL){ + if (self->pDriv != NULL) { free(self->pDriv); } - if(self->colliderScript != NULL){ + if (self->colliderScript != NULL) { free(self->colliderScript); } - if(self->motorList > 0){ + if (self->motorList > 0) { KillMotList(self->motorList); } - if(self->sequenceList > 0){ + if (self->sequenceList > 0) { LLDdelete(self->sequenceList); } free(self); myCollider = NULL; } -/*-----------------------------------------------------------------------*/ -int AntiColliderFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]){ - myCollider = (pAntiCollider)malloc(sizeof(AntiCollider)); - if(myCollider == NULL){ - SCWrite(pCon,"ERROR: out of memory when generating AntiCollider",eError); +/*-----------------------------------------------------------------------*/ +int AntiColliderFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + + myCollider = (pAntiCollider) malloc(sizeof(AntiCollider)); + if (myCollider == NULL) { + SCWrite(pCon, "ERROR: out of memory when generating AntiCollider", + eError); return 0; } - memset(myCollider,0,sizeof(AntiCollider)); + memset(myCollider, 0, sizeof(AntiCollider)); myCollider->pDes = CreateDescriptor("AntiCollider"); myCollider->pDriv = CreateDrivableInterface(); - if(!myCollider->pDes || !myCollider->pDriv){ + if (!myCollider->pDes || !myCollider->pDriv) { KillCollider(myCollider); - SCWrite(pCon,"ERROR: out of memory when generating AntiCollider",eError); + SCWrite(pCon, "ERROR: out of memory when generating AntiCollider", + eError); return 0; } @@ -293,91 +315,90 @@ int AntiColliderFactory(SConnection *pCon, SicsInterp *pSics, myCollider->motorList = LLDcreate(sizeof(void *)); myCollider->sequenceList = LLDcreate(sizeof(Sequence)); - AddCommand(pSics,"anticollision",AntiColliderAction, - KillCollider, - myCollider); + AddCommand(pSics, "anticollision", AntiColliderAction, + KillCollider, myCollider); return 1; } + /*------------------------------------------------------------------------*/ -int AntiColliderAction(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]){ - pAntiCollider self = (pAntiCollider)pData; +int AntiColliderAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pAntiCollider self = (pAntiCollider) pData; Sequence seq; char pBueffel[256]; pMotReg pMot = NULL; - + assert(self != NULL); - if(argc > 1){ - if(strcmp(argv[1],"clear") == 0){ - if(!SCMatchRights(pCon,usUser)){ - return 0; + if (argc > 1) { + if (strcmp(argv[1], "clear") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; } LLDdelete(self->sequenceList); self->sequenceList = LLDcreate(sizeof(Sequence)); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"list") == 0){ - ListSequence(self->sequenceList,pCon); + } else if (strcmp(argv[1], "list") == 0) { + ListSequence(self->sequenceList, pCon); return 1; } } - if(argc < 3){ - SCWrite(pCon,"ERROR : insufficient number of arguments to anticollision", - eError); + if (argc < 3) { + SCWrite(pCon, + "ERROR : insufficient number of arguments to anticollision", + eError); return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"script") == 0){ - if(!SCMatchRights(pCon,usMugger)){ + if (strcmp(argv[1], "script") == 0) { + if (!SCMatchRights(pCon, usMugger)) { return 0; } - if(self->colliderScript != NULL){ + if (self->colliderScript != NULL) { free(self->colliderScript); } self->colliderScript = strdup(argv[2]); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"register") == 0){ - if(!SCMatchRights(pCon,usMugger)){ + } else if (strcmp(argv[1], "register") == 0) { + if (!SCMatchRights(pCon, usMugger)) { return 0; } - if(FindDrivable(pSics,argv[2]) == NULL){ - sprintf(pBueffel,"ERROR: %s is NOT drivable, cannot register",argv[2]); - SCWrite(pCon,pBueffel,eError); + if (FindDrivable(pSics, argv[2]) == NULL) { + sprintf(pBueffel, "ERROR: %s is NOT drivable, cannot register", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } - pMot = RegisterMotor(argv[2],pSics, - ReplacementSetValue, - ReplacementCheckStatus); - if(pMot){ - LLDnodeAppendFrom(self->motorList,&pMot); + pMot = RegisterMotor(argv[2], pSics, + ReplacementSetValue, ReplacementCheckStatus); + if (pMot) { + LLDnodeAppendFrom(self->motorList, &pMot); SCSendOK(pCon); return 1; } else { - SCWrite(pCon,"ERROR: out of memory registering motor",eError); + SCWrite(pCon, "ERROR: out of memory registering motor", eError); return 0; } - } else if(strcmp(argv[1],"add") == 0){ - if(argc < 5){ + } else if (strcmp(argv[1], "add") == 0) { + if (argc < 5) { SCWrite(pCon, - "ERROR: InsUfficient number of arguments to anticollicion add", - eError); + "ERROR: InsUfficient number of arguments to anticollicion add", + eError); return 0; } seq.level = atoi(argv[2]); - strncpy(seq.pMotor,argv[3],79); + strncpy(seq.pMotor, argv[3], 79); seq.target = atof(argv[4]); - LLDnodeAppendFrom(self->sequenceList,&seq); + LLDnodeAppendFrom(self->sequenceList, &seq); SCSendOK(pCon); return 1; - } - SCWrite(pCon,"ERROR: anticollider command not understood",eError); + } + SCWrite(pCon, "ERROR: anticollider command not understood", eError); return 0; } - - diff --git a/anticollider.h b/anticollider.h index f526789c..76c8cb22 100644 --- a/anticollider.h +++ b/anticollider.h @@ -11,15 +11,10 @@ #define ANTICOLLIDER - int AntiColliderFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]); - int AntiColliderAction(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]); +int AntiColliderFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); +int AntiColliderAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); #endif - - - diff --git a/ascon.c b/ascon.c index fd333752..b6e1d1c2 100644 --- a/ascon.c +++ b/ascon.c @@ -18,13 +18,12 @@ CreateSocketAdress stolen from Tcl. Thanks to John Ousterhout */ -static int CreateSocketAdress( - struct sockaddr_in *sockaddrPtr, /* Socket address */ - char *host, /* Host. NULL implies INADDR_ANY */ - int port) /* Port number */ -{ - struct hostent *hostent; /* Host database entry */ - struct in_addr addr; /* For 64/32 bit madness */ +static int CreateSocketAdress(struct sockaddr_in *sockaddrPtr, /* Socket address */ + char *host, /* Host. NULL implies INADDR_ANY */ + int port) +{ /* Port number */ + struct hostent *hostent; /* Host database entry */ + struct in_addr addr; /* For 64/32 bit madness */ (void) memset((char *) sockaddrPtr, '\0', sizeof(struct sockaddr_in)); sockaddrPtr->sin_family = AF_INET; @@ -35,11 +34,11 @@ static int CreateSocketAdress( hostent = gethostbyname(host); if (hostent != NULL) { memcpy((char *) &addr, - (char *) hostent->h_addr_list[0], (size_t) hostent->h_length); + (char *) hostent->h_addr_list[0], (size_t) hostent->h_length); } else { addr.s_addr = inet_addr(host); - if (addr.s_addr == (unsigned long)-1) { - return 0; /* error */ + if (addr.s_addr == (unsigned long) -1) { + return 0; /* error */ } } } @@ -51,39 +50,45 @@ static int CreateSocketAdress( return 1; } -double DoubleTime(void) { +double DoubleTime(void) +{ struct timeval now; /* the resolution of this function is usec, if the machine supports this and the mantissa of a double is 51 bits or more (31 for sec and 20 for micro) - */ + */ gettimeofday(&now, NULL); return now.tv_sec + now.tv_usec / 1e6; } -void AsconError(Ascon *a, char *msg, int errorno) { - static char *stateText[]={ +void AsconError(Ascon * a, char *msg, int errorno) +{ + static char *stateText[] = { "state 0", "kill", "state 2", "notConnected", - "connect", "start connect", "connect finished", "connect failed", - "write", "start write", "write finished", "write failed", - "read", "start read", "read finished", "read failed", + "connect", "start connect", "connect finished", "connect failed", + "write", "start write", "write finished", "write failed", + "read", "start read", "read finished", "read failed", "state 16", "state 17", "state 18", "idle" }; char *state; - + if (a->state < 0 || a->state > 19) { state = "bad state"; } else { state = stateText[a->state]; } if (errorno != 0) { - a->errList = ErrPutMsg(a->errList, "ASCERR: %s %s (during %s)", msg, strerror(errorno), state); + a->errList = + ErrPutMsg(a->errList, "ASCERR: %s %s (during %s)", msg, + strerror(errorno), state); } else { - a->errList = ErrPutMsg(a->errList, "ASCERR: %s (during %s)", msg, state); + a->errList = + ErrPutMsg(a->errList, "ASCERR: %s (during %s)", msg, state); } a->state |= AsconFailed; } -static void AsconConnect(Ascon *a) { +static void AsconConnect(Ascon * a) +{ /* input state: AsconConnectStart output state: AsconFailed or AsconConnecting */ int ret; @@ -91,17 +96,18 @@ static void AsconConnect(Ascon *a) { char *colon; int port; int oldopts; - + if (a->fd < 0) { - a->fd = socket(AF_INET,SOCK_STREAM,0); + a->fd = socket(AF_INET, SOCK_STREAM, 0); if (a->fd < 0) { AsconError(a, "socket failed:", errno); return; } } colon = strchr(a->hostport, ':'); - if (colon == NULL) return; - port = atoi(colon+1); + if (colon == NULL) + return; + port = atoi(colon + 1); if (port <= 0) { AsconError(a, "bad port number", 0); return; @@ -116,48 +122,50 @@ static void AsconConnect(Ascon *a) { /* should we insert the workaround for lantronix server ? see network.c */ oldopts = fcntl(a->fd, F_GETFL, 0); fcntl(a->fd, F_SETFL, oldopts | O_NONBLOCK); - ret = connect(a->fd, (struct sockaddr *)&adr, sizeof(struct sockaddr_in)); + ret = + connect(a->fd, (struct sockaddr *) &adr, sizeof(struct sockaddr_in)); if (ret < 0) { - switch(errno) { - case EINPROGRESS: - case EALREADY: - case EISCONN: - a->state = AsconConnecting; - break; - default: - AsconError(a, "connect failed:", errno); - return; - } + switch (errno) { + case EINPROGRESS: + case EALREADY: + case EISCONN: + a->state = AsconConnecting; + break; + default: + AsconError(a, "connect failed:", errno); + return; + } } a->state = AsconConnecting; return; } -int AsconStdInit(Ascon *a, SConnection *con, - int argc, char *argv[]) { +int AsconStdInit(Ascon * a, SConnection * con, int argc, char *argv[]) +{ a->fd = -1; a->state = AsconConnectStart; a->reconnectInterval = 10; a->hostport = strdup(argv[1]); - if(argc > 2){ - a->sendTerminator = strdup(argv[2]); + if (argc > 2) { + a->sendTerminator = strdup(argv[2]); } else { - a->sendTerminator = strdup("\n"); + a->sendTerminator = strdup("\n"); } - if(argc > 3){ - a->timeout = atof(argv[3]); + if (argc > 3) { + a->timeout = atof(argv[3]); } else { - a->timeout = 2.0; /* sec */ + a->timeout = 2.0; /* sec */ } return 1; } -int AsconReadGarbage(int fd) { +int AsconReadGarbage(int fd) +{ fd_set rmask; - struct timeval tmo = {0,0}; + struct timeval tmo = { 0, 0 }; int l, ret, result; char garbage[100]; - + FD_ZERO(&rmask); result = 0; do { @@ -179,7 +187,8 @@ int AsconReadGarbage(int fd) { return result; } -void PrintChar(char chr) { +void PrintChar(char chr) +{ if (chr <= 32 || chr >= 127) { printf("%2.2x ", chr); } else { @@ -187,15 +196,16 @@ void PrintChar(char chr) { } } -int AsconConnectSuccess(int fd) { +int AsconConnectSuccess(int fd) +{ fd_set wmask, rmask; - struct timeval tmo = {0,0}; + struct timeval tmo = { 0, 0 }; int oldopts; int ret; - + oldopts = fcntl(fd, F_GETFL, 0); assert(oldopts | O_NONBLOCK); /* fd must be in non-blocking mode */ - + FD_ZERO(&wmask); FD_ZERO(&rmask); FD_SET(fd, &wmask); @@ -203,33 +213,36 @@ int AsconConnectSuccess(int fd) { ret = uselect(fd + 1, &rmask, &wmask, NULL, &tmo); if (ret > 0) { assert(FD_ISSET(fd, &wmask)); - if (FD_ISSET(fd, &rmask)) { /* there may already be data for read */ - if (recv(fd, NULL, 0, 0) < 0) { /* zero length, check only return value */ + if (FD_ISSET(fd, &rmask)) { /* there may already be data for read */ + if (recv(fd, NULL, 0, 0) < 0) { /* zero length, check only return value */ ret = ASCON_RECV_ERROR; /* first recv failed */ } } else { - if (send(fd, NULL, 0, 0) < 0) { /* zero length, check only return value */ + if (send(fd, NULL, 0, 0) < 0) { /* zero length, check only return value */ ret = ASCON_SEND_ERROR; /* first send failed */ } } } - fcntl(fd, F_SETFL, oldopts & ~ O_NONBLOCK); /* reset to blocking mode */ + fcntl(fd, F_SETFL, oldopts & ~O_NONBLOCK); /* reset to blocking mode */ return ret; } -int AsconReadChar(int fd, char *chr) { +int AsconReadChar(int fd, char *chr) +{ fd_set rmask; - struct timeval tmo = {0,0}; + struct timeval tmo = { 0, 0 }; int ret; - + FD_ZERO(&rmask); FD_SET(fd, &rmask); ret = uselect(fd + 1, &rmask, NULL, NULL, &tmo); - if (ret <= 0) return ret; + if (ret <= 0) + return ret; ret = recv(fd, chr, 1, 0); /* PrintChar(*chr); */ fflush(stdout); - if (ret > 0) return 1; + if (ret > 0) + return 1; if (ret == 0) { errno = ECONNRESET; return ASCON_DISCONNECTED; @@ -237,26 +250,30 @@ int AsconReadChar(int fd, char *chr) { return ASCON_RECV_ERROR; } -int AsconWriteChars(int fd, char *data, int length) { +int AsconWriteChars(int fd, char *data, int length) +{ fd_set wmask; - struct timeval tmo = {0,0}; + struct timeval tmo = { 0, 0 }; int ret; - - if (length <= 0) return 0; + + if (length <= 0) + return 0; /* - { int i; - for (i=0; i 0) return ret; + if (ret > 0) + return ret; if (ret == 0) { errno = ECONNRESET; return ASCON_DISCONNECTED; @@ -266,14 +283,15 @@ int AsconWriteChars(int fd, char *data, int length) { static double lastCall = 0; -int AsconStdHandler(Ascon *a) { +int AsconStdHandler(Ascon * a) +{ int ret; int l; char chr; double now = DoubleTime(); - - if (now > lastCall + 0.5) { /* AsconStdHandler was not called since a long time (0.5 sec) */ - if (lastCall != 0) { /* extend timeout time (for debugging purposes) */ + + if (now > lastCall + 0.5) { /* AsconStdHandler was not called since a long time (0.5 sec) */ + if (lastCall != 0) { /* extend timeout time (for debugging purposes) */ a->start += now - lastCall - 0.5; } } @@ -287,17 +305,18 @@ int AsconStdHandler(Ascon *a) { if (ret == 0) { /* in progress */ } else if (ret > 0) { - a->state = AsconConnectDone; /* success */ + a->state = AsconConnectDone; /* success */ } else if (ret < 0) { AsconError(a, "AsconConnectSuccess failed:", errno); } break; case AsconWriteStart: - DynStringConcat(a->wrBuffer, a->sendTerminator); - a->wrPos = 0; - a->state = AsconWriting; - if(strstr(GetCharArray(a->wrBuffer),"@@NOSEND@@") != NULL){ - a->state = AsconWriteDone; + if (strstr(GetCharArray(a->wrBuffer), "@@NOSEND@@") != NULL) { + a->state = AsconWriteDone; + } else { + DynStringConcat(a->wrBuffer, a->sendTerminator); + a->wrPos = 0; + a->state = AsconWriting; } break; case AsconWriting: @@ -305,8 +324,8 @@ int AsconStdHandler(Ascon *a) { l = GetDynStringLength(a->wrBuffer) - a->wrPos; ret = AsconWriteChars(a->fd, GetCharArray(a->wrBuffer) + a->wrPos, l); if (ret < 0) { - if(errno != EINTR && errno != EAGAIN){ - AsconError(a, "send failed:", errno); + if (errno != EINTR && errno != EAGAIN) { + AsconError(a, "send failed:", errno); } /* * Ooops: which state shall we go to after a write fail? @@ -328,7 +347,7 @@ int AsconStdHandler(Ascon *a) { ret = AsconReadChar(a->fd, &chr); while (ret > 0) { a->start = DoubleTime(); - + if (chr == '\n') { if (a->readState) { /* swallow LF after CR */ @@ -355,8 +374,8 @@ int AsconStdHandler(Ascon *a) { } if (ret < 0) { /* EINTR means we shall retry */ - if(errno != EINTR && errno != EAGAIN){ - AsconError(a, "AsconReadChar failed:", errno); + if (errno != EINTR && errno != EAGAIN) { + AsconError(a, "AsconReadChar failed:", errno); } return 1; } @@ -373,7 +392,7 @@ int AsconStdHandler(Ascon *a) { break; default: return 1; - } + } return 1; } @@ -381,28 +400,32 @@ int AsconStdHandler(Ascon *a) { #define MC_NAME(T) AsconProtocol##T #include "mclist.c" -static AsconProtocolList protocols={0}; +static AsconProtocolList protocols = { 0 }; -void AsconInsertProtocol(AsconProtocol *protocol) { +void AsconInsertProtocol(AsconProtocol * protocol) +{ AsconProtocolAdd(&protocols, protocol); } -AsconHandler AsconSetHandler(Ascon *a, SConnection *con, - int argc, char *argv[]) { +AsconHandler AsconSetHandler(Ascon * a, SConnection * con, + int argc, char *argv[]) +{ AsconProtocol *p; - - if (argc < 1) return NULL; + + if (argc < 1) + return NULL; if (strcasecmp(argv[0], "std") == 0) { - if (argc < 2) return NULL; + if (argc < 2) + return NULL; AsconStdInit(a, con, argc, argv); return AsconStdHandler; } - for (p = protocols.head; p!= NULL; p=p->next) { + for (p = protocols.head; p != NULL; p = p->next) { if (strcasecmp(p->name, argv[0]) == 0) { - if(p->init(a, con, argc, argv)){ - return p->handler; + if (p->init(a, con, argc, argv)) { + return p->handler; } else { - return NULL; + return NULL; } } } @@ -411,14 +434,16 @@ AsconHandler AsconSetHandler(Ascon *a, SConnection *con, /* --- implementation of higher level interface ---- */ -char *ConcatArgs(int argc, char *argv[]) { +char *ConcatArgs(int argc, char *argv[]) +{ return Arg2Tcl(argc, argv, NULL, -1); } -Ascon *AsconMake(SConnection *con, int argc, char *argv[]) { +Ascon *AsconMake(SConnection * con, int argc, char *argv[]) +{ Ascon *a; char *args; - + a = calloc(1, sizeof(*a)); if (a == NULL) { SCWrite(con, "ERROR: no memory", eError); @@ -427,7 +452,8 @@ Ascon *AsconMake(SConnection *con, int argc, char *argv[]) { a->handler = AsconSetHandler(a, con, argc, argv); if (a->handler == NULL) { args = ConcatArgs(argc, argv); - if (!args) return NULL; + if (!args) + return NULL; SCPrintf(con, eError, "ERROR: illegal protocol: %s", args); free(args); return NULL; @@ -441,7 +467,8 @@ Ascon *AsconMake(SConnection *con, int argc, char *argv[]) { return a; } -void AsconKill(Ascon *a) { +void AsconKill(Ascon * a) +{ if (a->fd > 0) { close(a->fd); } @@ -450,25 +477,28 @@ void AsconKill(Ascon *a) { if (a->hostport) { free(a->hostport); } - if(a->sendTerminator){ - free(a->sendTerminator); + if (a->sendTerminator) { + free(a->sendTerminator); } - if(a->private != NULL && a->killPrivate != NULL){ - a->killPrivate(a->private); + if (a->private != NULL && a->killPrivate != NULL) { + a->killPrivate(a->private); } free(a); } -void AsconDisconnect(Ascon *a){ - if(a->fd > 0){ - close(a->fd); - } - a->fd = -1; - a->state = AsconConnectStart; + +void AsconDisconnect(Ascon * a) +{ + if (a->fd > 0) { + close(a->fd); + } + a->fd = -1; + a->state = AsconConnectStart; } -AsconStatus AsconTask(Ascon *a) { +AsconStatus AsconTask(Ascon * a) +{ double now; - + while (a->handler(a)) { switch (a->state) { case AsconReading: @@ -503,7 +533,7 @@ AsconStatus AsconTask(Ascon *a) { if (now > a->lastReconnect + a->reconnectInterval) { a->lastReconnect = now; close(a->fd); - /* allow the system to cleanup the socket, otherwise a reconnect will fail*/ + /* allow the system to cleanup the socket, otherwise a reconnect will fail */ sleep(1); a->fd = -1; a->state = AsconConnectStart; @@ -521,8 +551,10 @@ AsconStatus AsconTask(Ascon *a) { return AsconIdle; } -int AsconWrite(Ascon *a, char *command, int noResponse) { - if (a->state <= AsconConnectFailed || a->state % 4 < AsconFinished) return 0; +int AsconWrite(Ascon * a, char *command, int noResponse) +{ + if (a->state <= AsconConnectFailed || a->state % 4 < AsconFinished) + return 0; DynStringCopy(a->wrBuffer, command); a->noResponse = noResponse; a->state = AsconWriteStart; @@ -531,9 +563,10 @@ int AsconWrite(Ascon *a, char *command, int noResponse) { return 1; } -char *AsconRead(Ascon *a) { +char *AsconRead(Ascon * a) +{ if (a->noResponse) { - a->noResponse=0; + a->noResponse = 0; return ""; } if (a->state % 4 == AsconFailed) { @@ -547,6 +580,7 @@ char *AsconRead(Ascon *a) { return NULL; } -ErrMsg *AsconGetErrList(Ascon *a) { +ErrMsg *AsconGetErrList(Ascon * a) +{ return a->errList; } diff --git a/ascon.h b/ascon.h index e54306e1..5a2f9af9 100644 --- a/ascon.h +++ b/ascon.h @@ -8,7 +8,7 @@ * \brief Asynchronous connection handling for devices controlled over tcp-ip * connections. Interface for higher level modules. */ - + /** \brief the asynchronous connection */ typedef struct Ascon Ascon; @@ -30,22 +30,22 @@ typedef enum { * are protocol specific, but argv[1] is usually host::port * \return the created connection or NULL on failure */ -Ascon *AsconMake(SConnection *con, int argc, char *argv[]); +Ascon *AsconMake(SConnection * con, int argc, char *argv[]); /** \brief kill function * \param a the connection to be killed */ -void AsconKill(Ascon *a); +void AsconKill(Ascon * a); /** \brief Disconnect function * \param a the connection to disconnect */ -void AsconDisconnect(Ascon *a); +void AsconDisconnect(Ascon * a); /** \brief the task handler. To be called repeatedly. * \param a the connection * \return the state of the connection - */ -AsconStatus AsconTask(Ascon *a); + */ +AsconStatus AsconTask(Ascon * a); /** \brief write to the connection. allowed only when the state is AsconReady * \param a the connection @@ -53,7 +53,7 @@ AsconStatus AsconTask(Ascon *a); * \param noResponse 0 normally, 1 if no reponse is expected * \return 1 on success, 0 when not ready */ -int AsconWrite(Ascon *a, char *command, int noResponse); +int AsconWrite(Ascon * a, char *command, int noResponse); /** \brief read from the connection. allowed only when a response is available * \param a the connection @@ -63,12 +63,12 @@ int AsconWrite(Ascon *a, char *command, int noResponse); * The result is only valid until the next call to other AsconXxx functions * and has to be duplicated if needed later. */ -char *AsconRead(Ascon *a); +char *AsconRead(Ascon * a); /** \brief get the connections error list * \return the error list */ -ErrMsg *AsconGetErrList(Ascon *a); +ErrMsg *AsconGetErrList(Ascon * a); /** \brief a helper function * \param argc the number of args diff --git a/asyncprotocol.c b/asyncprotocol.c index 211dba1c..49a0118c 100644 --- a/asyncprotocol.c +++ b/asyncprotocol.c @@ -2,7 +2,8 @@ #include #include -int defaultSendCommand(pAsyncProtocol p, pAsyncTxn txn) { +int defaultSendCommand(pAsyncProtocol p, pAsyncTxn txn) +{ int i, iRet; int state; const char *term = "\r\n"; @@ -10,10 +11,9 @@ int defaultSendCommand(pAsyncProtocol p, pAsyncTxn txn) { term = p->sendTerminator; state = 0; for (i = 0; i < txn->out_len; ++i) { - if (txn->out_buf[i] == 0x00) { /* end of transmission */ + if (txn->out_buf[i] == 0x00) { /* end of transmission */ break; - } - else if (txn->out_buf[i] == term[state]) { + } else if (txn->out_buf[i] == term[state]) { ++state; continue; } @@ -24,11 +24,12 @@ int defaultSendCommand(pAsyncProtocol p, pAsyncTxn txn) { if (iRet <= 0) return iRet; if (term[state] != 0) - iRet = AsyncUnitWrite(txn->unit,(void *) term, strlen(term)); + iRet = AsyncUnitWrite(txn->unit, (void *) term, strlen(term)); return iRet; } -int defaultHandleInput(pAsyncProtocol p, pAsyncTxn txn, int ch) { +int defaultHandleInput(pAsyncProtocol p, pAsyncTxn txn, int ch) +{ const char *term = "\r\n"; if (p->replyTerminator) term = p->replyTerminator; @@ -47,12 +48,15 @@ int defaultHandleInput(pAsyncProtocol p, pAsyncTxn txn, int ch) { return 1; } -int defaultHandleEvent(pAsyncProtocol p, pAsyncTxn txn, int event) { +int defaultHandleEvent(pAsyncProtocol p, pAsyncTxn txn, int event) +{ /* TODO: what could or should we do to handle the event */ return AQU_POP_CMD; } -int defaultPrepareTxn(pAsyncProtocol p, pAsyncTxn txn, const char* cmd, int cmd_len, int rsp_len) { +int defaultPrepareTxn(pAsyncProtocol p, pAsyncTxn txn, const char *cmd, + int cmd_len, int rsp_len) +{ int i; int state; const char *term = "\r\n"; @@ -60,11 +64,10 @@ int defaultPrepareTxn(pAsyncProtocol p, pAsyncTxn txn, const char* cmd, int cmd_ term = p->sendTerminator; state = 0; for (i = 0; i < cmd_len; ++i) { - if (cmd[i] == 0x00) { /* end of transmission */ + if (cmd[i] == 0x00) { /* end of transmission */ cmd_len = i; break; - } - else if (cmd[i] == term[state]) { + } else if (cmd[i] == term[state]) { ++state; continue; } @@ -74,17 +77,18 @@ int defaultPrepareTxn(pAsyncProtocol p, pAsyncTxn txn, const char* cmd, int cmd_ /* outgoing command is correctly terminated */ txn->out_buf = malloc(cmd_len + 1); if (txn->out_buf == NULL) { - SICSLogWrite("Out of memory in AsyncProtocol::defaultPrepareTxn", eError); + SICSLogWrite("Out of memory in AsyncProtocol::defaultPrepareTxn", + eError); return 0; } memcpy(txn->out_buf, cmd, cmd_len + 1); - } - else { + } else { /* outgoing command is NOT correctly terminated */ int tlen = strlen(term); txn->out_buf = malloc(cmd_len + tlen + 1); if (txn->out_buf == NULL) { - SICSLogWrite("Out of memory in AsyncProtocol::defaultPrepareTxn", eError); + SICSLogWrite("Out of memory in AsyncProtocol::defaultPrepareTxn", + eError); return 0; } memcpy(txn->out_buf, cmd, cmd_len); @@ -93,12 +97,13 @@ int defaultPrepareTxn(pAsyncProtocol p, pAsyncTxn txn, const char* cmd, int cmd_ } txn->out_len = cmd_len; txn->out_idx = 0; - if(txn->inp_buf != NULL){ + if (txn->inp_buf != NULL) { free(txn->inp_buf); } txn->inp_buf = malloc(rsp_len); if (txn->inp_buf == NULL) { - SICSLogWrite("Out of memory in AsyncProtocol::defaultPrepareTxn", eError); + SICSLogWrite("Out of memory in AsyncProtocol::defaultPrepareTxn", + eError); free(txn->out_buf); txn->out_buf = NULL; return 0; @@ -110,7 +115,7 @@ int defaultPrepareTxn(pAsyncProtocol p, pAsyncTxn txn, const char* cmd, int cmd_ return 1; } -static const char* hex = "0123456789ABCDEF"; +static const char *hex = "0123456789ABCDEF"; /*--------------------------------------------------------------------*/ static void encodeTerminator(char *result, char *terminator) @@ -119,15 +124,16 @@ static void encodeTerminator(char *result, char *terminator) while (*terminator) { *result++ = '0'; *result++ = 'x'; - *result++ = hex[(*terminator >> 4) &0xF]; - *result++ = hex[(*terminator) &0xF]; + *result++ = hex[(*terminator >> 4) & 0xF]; + *result++ = hex[(*terminator) & 0xF]; ++terminator; } *result = '\0'; return; } -static int fromHex(const char* code) { +static int fromHex(const char *code) +{ int icode = -1; int result = -1; if (code[0] == '0' && (code[1] == 'x' || code[1] == 'X')) { @@ -154,53 +160,52 @@ static int fromHex(const char* code) { } return -1; } + /*--------------------------------------------------------------------*/ static char *decodeTerminator(char *code) { int count = 0, icode; char *pResult; - char* pCh; - char* pQt = NULL; /* pointer to quote character if found */ + char *pCh; + char *pQt = NULL; /* pointer to quote character if found */ if (code == NULL) return NULL; count = strlen(code); pResult = (char *) malloc(count + 1); if (!pResult) { - SICSLogWrite("Out of memory in AsyncProtocol::decodeTerminator", eError); + SICSLogWrite("Out of memory in AsyncProtocol::decodeTerminator", + eError); return NULL; } memset(pResult, 0, count + 1); pCh = pResult; - if (*code == '\'' || *code == '"') /* check for leading quote */ + if (*code == '\'' || *code == '"') /* check for leading quote */ pQt = code++; while (*code) { - if (pQt && *code == *pQt) /* check for trailing quote */ + if (pQt && *code == *pQt) /* check for trailing quote */ break; - if (code[0] == '\\' && code[1] == 'r') { /* CR */ + if (code[0] == '\\' && code[1] == 'r') { /* CR */ *pCh++ = '\r'; code += 2; - } - else if (code[0] == '\\' && code[1] == 'n') { /* LF */ + } else if (code[0] == '\\' && code[1] == 'n') { /* LF */ *pCh++ = '\n'; code += 2; - } - else if ((icode = fromHex(code)) >= 0) { /* Hex: 0xFF */ + } else if ((icode = fromHex(code)) >= 0) { /* Hex: 0xFF */ *pCh++ = icode; code += 4; - } - else /* literal */ + } else /* literal */ *pCh++ = *code++; } *pCh = '\0'; return pResult; } -int AsyncProtocolNoAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) +int AsyncProtocolNoAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) { char line[132]; pAsyncProtocol self = (pAsyncProtocol) pData; @@ -209,7 +214,7 @@ int AsyncProtocolNoAction(SConnection *pCon, SicsInterp *pSics, return 0; } -int AsyncProtocolAction(SConnection *pCon, SicsInterp *pSics, +int AsyncProtocolAction(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]) { char line[132]; @@ -218,16 +223,14 @@ int AsyncProtocolAction(SConnection *pCon, SicsInterp *pSics, /* handle genecic parameters like terminators */ if (strcasecmp(argv[1], "sendterminator") == 0) { if (argc > 2) { - char* pPtr = decodeTerminator(argv[2]); + char *pPtr = decodeTerminator(argv[2]); if (pPtr) { if (self->sendTerminator) free(self->sendTerminator); self->sendTerminator = pPtr; } SCSendOK(pCon); - } - else - { + } else { char term[132]; char line[1024]; encodeTerminator(term, self->sendTerminator); @@ -235,19 +238,16 @@ int AsyncProtocolAction(SConnection *pCon, SicsInterp *pSics, SCWrite(pCon, line, eValue); } return 1; - } - else if (strcasecmp(argv[1], "replyterminator") == 0) { + } else if (strcasecmp(argv[1], "replyterminator") == 0) { if (argc > 2) { - char* pPtr = decodeTerminator(argv[2]); + char *pPtr = decodeTerminator(argv[2]); if (pPtr) { if (self->replyTerminator) free(self->replyTerminator); self->replyTerminator = pPtr; } SCSendOK(pCon); - } - else - { + } else { char term[132]; char line[1024]; encodeTerminator(term, self->replyTerminator); @@ -256,10 +256,9 @@ int AsyncProtocolAction(SConnection *pCon, SicsInterp *pSics, } return 1; } - } - else if (strcasecmp(argv[1], "list") == 0) { + } else if (strcasecmp(argv[1], "list") == 0) { int ac = 2; - char* av[3] = { argv[0], 0, 0 }; + char *av[3] = { argv[0], 0, 0 }; av[1] = "sendterminator"; AsyncProtocolAction(pCon, pSics, pData, ac, av); av[1] = "replyterminator"; @@ -267,35 +266,41 @@ int AsyncProtocolAction(SConnection *pCon, SicsInterp *pSics, return 1; } /* handle any other actions here */ - return AsyncProtocolNoAction(pCon, pSics, pData, argc,argv); + return AsyncProtocolNoAction(pCon, pSics, pData, argc, argv); } -void defaultKillPrivate(pAsyncProtocol p) { +void defaultKillPrivate(pAsyncProtocol p) +{ if (p->privateData) { /* TODO: should we do anything? */ free(p->privateData); } } -void AsyncProtocolKill(void *pData) { +void AsyncProtocolKill(void *pData) +{ pAsyncProtocol self = (pAsyncProtocol) pData; - if(self->pDes) + if (self->pDes) DeleteDescriptor(self->pDes); - if(self->sendTerminator != NULL) + if (self->sendTerminator != NULL) free(self->sendTerminator); - if(self->replyTerminator != NULL) + if (self->replyTerminator != NULL) free(self->replyTerminator); if (self->killPrivate) self->killPrivate(self); } -pAsyncProtocol AsyncProtocolCreate(SicsInterp *pSics, const char* protocolName, - ObjectFunc pFunc, KillFunc pKFunc) { +pAsyncProtocol AsyncProtocolCreate(SicsInterp * pSics, + const char *protocolName, + ObjectFunc pFunc, KillFunc pKFunc) +{ int iRet; pAsyncProtocol self = NULL; /* try to find an existing queue with this name */ - self = (pAsyncProtocol) FindCommandData(pServ->pSics,(char *)protocolName, "AsyncProtocol"); + self = + (pAsyncProtocol) FindCommandData(pServ->pSics, (char *) protocolName, + "AsyncProtocol"); if (self != NULL) { return self; } @@ -311,8 +316,8 @@ pAsyncProtocol AsyncProtocolCreate(SicsInterp *pSics, const char* protocolName, pFunc = AsyncProtocolNoAction; if (pKFunc == NULL) pKFunc = AsyncProtocolKill; - iRet = AddCommand(pSics, (char *)protocolName, pFunc, pKFunc, self); - if (!iRet ) { + iRet = AddCommand(pSics, (char *) protocolName, pFunc, pKFunc, self); + if (!iRet) { SICSLogWrite("AddCommand failed in AsyncProtocolCreate", eError); AsyncProtocolKill(self); return NULL; @@ -327,14 +332,17 @@ pAsyncProtocol AsyncProtocolCreate(SicsInterp *pSics, const char* protocolName, return self; } -int AsyncProtocolFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) { +int AsyncProtocolFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ if (argc < 2) { - SCWrite(pCon,"ERROR: insufficient arguments to AsyncProtocolFactory", eError); + SCWrite(pCon, "ERROR: insufficient arguments to AsyncProtocolFactory", + eError); return 0; } pAsyncProtocol pNew = AsyncProtocolCreate(pSics, argv[1], - AsyncProtocolAction, AsyncProtocolKill); + AsyncProtocolAction, + AsyncProtocolKill); /* handle any extra arguments here */ pNew->privateData = NULL; return 1; diff --git a/asyncprotocol.h b/asyncprotocol.h index 528dcb98..3c943666 100644 --- a/asyncprotocol.h +++ b/asyncprotocol.h @@ -4,40 +4,41 @@ typedef struct __AsyncUnit AsyncUnit, *pAsyncUnit; typedef struct __async_txn AsyncTxn, *pAsyncTxn; -typedef int (*AsyncTxnHandler)(pAsyncTxn pTxn); +typedef int (*AsyncTxnHandler) (pAsyncTxn pTxn); typedef struct __async_protocol AsyncProtocol, *pAsyncProtocol; -pAsyncProtocol AsyncProtocolCreate(SicsInterp *pSics, const char* protocolName, - ObjectFunc pFunc, KillFunc pKFunc); +pAsyncProtocol AsyncProtocolCreate(SicsInterp * pSics, + const char *protocolName, + ObjectFunc pFunc, KillFunc pKFunc); -int AsyncProtocolAction(SConnection *pCon, SicsInterp *pSics, +int AsyncProtocolAction(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]); -int AsyncProtocolFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int AsyncProtocolFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); typedef enum { - ATX_NULL=0, - ATX_TIMEOUT=-1, - ATX_ACTIVE=1, - ATX_COMPLETE=2, - ATX_DISCO=3 + ATX_NULL = 0, + ATX_TIMEOUT = -1, + ATX_ACTIVE = 1, + ATX_COMPLETE = 2, + ATX_DISCO = 3 } ATX_STATUS; struct __async_txn { - pAsyncUnit unit; /**< unit that transaction is associated with */ - int txn_state; /**< protocol handler transaction parse state */ - ATX_STATUS txn_status; /**< status of the transaction OK, Error, ... */ - int txn_timeout; /**< transaction timeout in milliseconds */ - char* out_buf; /**< output buffer for sendCommand */ - int out_len; /**< length of data to be sent */ - int out_idx; /**< index of next character to transmit */ - char* inp_buf; /**< input buffer for transaction response */ - int inp_len; /**< length of input buffer */ - int inp_idx; /**< index of next character (number already received) */ + pAsyncUnit unit; /**< unit that transaction is associated with */ + int txn_state; /**< protocol handler transaction parse state */ + ATX_STATUS txn_status; /**< status of the transaction OK, Error, ... */ + int txn_timeout; /**< transaction timeout in milliseconds */ + char *out_buf; /**< output buffer for sendCommand */ + int out_len; /**< length of data to be sent */ + int out_idx; /**< index of next character to transmit */ + char *inp_buf; /**< input buffer for transaction response */ + int inp_len; /**< length of input buffer */ + int inp_idx; /**< index of next character (number already received) */ AsyncTxnHandler handleResponse; /**< Txn response handler of command sender */ - void* cntx; /**< opaque context used by command sender */ + void *cntx; /**< opaque context used by command sender */ /* The cntx field may be used by protocol handler from sendCommand * as long as it is restored when response is complete */ @@ -48,15 +49,16 @@ struct __async_txn { */ struct __async_protocol { pObjectDescriptor pDes; - char* protocolName; + char *protocolName; char *sendTerminator; char *replyTerminator; - void* privateData; - int (* sendCommand)(pAsyncProtocol p, pAsyncTxn txn); - int (* handleInput)(pAsyncProtocol p, pAsyncTxn txn, int ch); - int (* handleEvent)(pAsyncProtocol p, pAsyncTxn txn, int event); - int (* prepareTxn)(pAsyncProtocol p, pAsyncTxn txn, const char* cmd, int cmd_len, int rsp_len); - void (* killPrivate)(pAsyncProtocol p); + void *privateData; + int (*sendCommand) (pAsyncProtocol p, pAsyncTxn txn); + int (*handleInput) (pAsyncProtocol p, pAsyncTxn txn, int ch); + int (*handleEvent) (pAsyncProtocol p, pAsyncTxn txn, int event); + int (*prepareTxn) (pAsyncProtocol p, pAsyncTxn txn, const char *cmd, + int cmd_len, int rsp_len); + void (*killPrivate) (pAsyncProtocol p); }; -#endif /* ASYNCPROTOCOL */ +#endif /* ASYNCPROTOCOL */ diff --git a/asyncqueue.c b/asyncqueue.c index 62ec857e..6b75a9f8 100644 --- a/asyncqueue.c +++ b/asyncqueue.c @@ -25,38 +25,38 @@ typedef struct __async_command AQ_Cmd, *pAQ_Cmd; struct __async_command { - pAQ_Cmd next; - pAsyncTxn tran; - pAsyncUnit unit; - int timeout; - int retries; - int active; + pAQ_Cmd next; + pAsyncTxn tran; + pAsyncUnit unit; + int timeout; + int retries; + int active; }; struct __AsyncUnit { - pAsyncUnit next; + pAsyncUnit next; pAsyncQueue queue; - AQU_Notify notify_func; - void* notify_cntx; + AQU_Notify notify_func; + void *notify_cntx; }; struct __AsyncQueue { pObjectDescriptor pDes; - char* queue_name; - char* pHost; - int iPort; - int iDelay; /* intercommand delay in milliseconds */ - int timeout; - int retries; - struct timeval tvLastCmd; /* time of completion of last command */ - int unit_count; /* number of units connected */ - pAsyncUnit units; /* head of unit chain */ - pAQ_Cmd command_head; /* first/next command in queue */ - pAQ_Cmd command_tail; /* last command in queue */ - pNWContext nw_ctx; /* NetWait context handle */ - pNWTimer nw_tmr; /* NetWait timer handle */ - mkChannel* pSock; /* socket address */ - pAsyncProtocol protocol; + char *queue_name; + char *pHost; + int iPort; + int iDelay; /* intercommand delay in milliseconds */ + int timeout; + int retries; + struct timeval tvLastCmd; /* time of completion of last command */ + int unit_count; /* number of units connected */ + pAsyncUnit units; /* head of unit chain */ + pAQ_Cmd command_head; /* first/next command in queue */ + pAQ_Cmd command_tail; /* last command in queue */ + pNWContext nw_ctx; /* NetWait context handle */ + pNWTimer nw_tmr; /* NetWait timer handle */ + mkChannel *pSock; /* socket address */ + pAsyncProtocol protocol; }; static pAsyncQueue queue_array[FD_SETSIZE]; @@ -66,39 +66,37 @@ static int queue_index = 0; CreateSocketAdress stolen from Tcl. Thanks to John Ousterhout */ -static int -CreateSocketAdress( - struct sockaddr_in *sockaddrPtr, /* Socket address */ - char *host, /* Host. NULL implies INADDR_ANY */ - int port) /* Port number */ -{ - struct hostent *hostent; /* Host database entry */ - struct in_addr addr; /* For 64/32 bit madness */ +static int CreateSocketAdress(struct sockaddr_in *sockaddrPtr, /* Socket address */ + char *host, /* Host. NULL implies INADDR_ANY */ + int port) +{ /* Port number */ + struct hostent *hostent; /* Host database entry */ + struct in_addr addr; /* For 64/32 bit madness */ - (void) memset((char *) sockaddrPtr, '\0', sizeof(struct sockaddr_in)); - sockaddrPtr->sin_family = AF_INET; - sockaddrPtr->sin_port = htons((unsigned short) (port & 0xFFFF)); - if (host == NULL) { - addr.s_addr = INADDR_ANY; + (void) memset((char *) sockaddrPtr, '\0', sizeof(struct sockaddr_in)); + sockaddrPtr->sin_family = AF_INET; + sockaddrPtr->sin_port = htons((unsigned short) (port & 0xFFFF)); + if (host == NULL) { + addr.s_addr = INADDR_ANY; + } else { + hostent = gethostbyname(host); + if (hostent != NULL) { + memcpy((char *) &addr, + (char *) hostent->h_addr_list[0], (size_t) hostent->h_length); } else { - hostent = gethostbyname(host); - if (hostent != NULL) { - memcpy((char *) &addr, - (char *) hostent->h_addr_list[0], (size_t) hostent->h_length); - } else { - addr.s_addr = inet_addr(host); - if (addr.s_addr == (unsigned long)-1) { - return 0; /* error */ - } - } + addr.s_addr = inet_addr(host); + if (addr.s_addr == (unsigned long) -1) { + return 0; /* error */ + } } - /* - * There is a rumor that this assignment may require care on - * some 64 bit machines. - */ + } + /* + * There is a rumor that this assignment may require care on + * some 64 bit machines. + */ - sockaddrPtr->sin_addr.s_addr = addr.s_addr; - return 1; + sockaddrPtr->sin_addr.s_addr = addr.s_addr; + return 1; } static void AQ_Notify(pAsyncQueue self, int event) @@ -129,14 +127,14 @@ static int AQ_Reconnect(pAsyncQueue self) return 1; } -static int CommandTimeout(void* cntx, int mode); -static int DelayedStart(void* cntx, int mode); +static int CommandTimeout(void *cntx, int mode); +static int DelayedStart(void *cntx, int mode); static int PopCommand(pAsyncQueue self); static int StartCommand(pAsyncQueue self) { pAQ_Cmd myCmd = self->command_head; - mkChannel* sock = self->pSock; + mkChannel *sock = self->pSock; if (myCmd == NULL) return OKOK; @@ -166,8 +164,7 @@ static int StartCommand(pAsyncQueue self) int delay = when.tv_sec - now.tv_sec; delay *= 1000; delay += (when.tv_usec - now.tv_usec + (1000 - 1)) / 1000; - NetWatchRegisterTimer(&self->nw_tmr, delay, - DelayedStart, self); + NetWatchRegisterTimer(&self->nw_tmr, delay, DelayedStart, self); return OKOK; } } @@ -180,12 +177,12 @@ static int StartCommand(pAsyncQueue self) char reply[1]; int iRet; iRet = NETRead(sock, reply, 1, 0); - if (iRet < 0) { /* EOF */ + if (iRet < 0) { /* EOF */ iRet = AQ_Reconnect(self); if (iRet <= 0) { myCmd->tran->txn_state = ATX_DISCO; - if(myCmd->tran->handleResponse){ - myCmd->tran->handleResponse(myCmd->tran); + if (myCmd->tran->handleResponse) { + myCmd->tran->handleResponse(myCmd->tran); } PopCommand(self); return 0; @@ -197,10 +194,9 @@ static int StartCommand(pAsyncQueue self) */ if (myCmd->timeout > 0) NetWatchRegisterTimer(&self->nw_tmr, myCmd->timeout, - CommandTimeout, self); + CommandTimeout, self); else - NetWatchRegisterTimer(&self->nw_tmr, 30000, - CommandTimeout, self); + NetWatchRegisterTimer(&self->nw_tmr, 30000, CommandTimeout, self); myCmd->active = 1; return self->protocol->sendCommand(self->protocol, myCmd->tran); } @@ -219,8 +215,7 @@ static int QueCommandHead(pAsyncQueue self, pAQ_Cmd cmd) if (self->command_head->active) { cmd->next = self->command_head->next; self->command_head->next = cmd; - } - else { + } else { cmd->next = self->command_head; self->command_head = cmd; } @@ -258,8 +253,7 @@ static int PopCommand(pAsyncQueue self) pAQ_Cmd pNew = myCmd->next; self->command_head = pNew; StartCommand(self); - } - else + } else self->command_head = self->command_tail = NULL; free(myCmd->tran->out_buf); free(myCmd->tran->inp_buf); @@ -268,7 +262,7 @@ static int PopCommand(pAsyncQueue self) return 1; } -static int CommandTimeout(void* cntx, int mode) +static int CommandTimeout(void *cntx, int mode) { pAsyncQueue self = (pAsyncQueue) cntx; pAQ_Cmd myCmd = self->command_head; @@ -276,24 +270,24 @@ static int CommandTimeout(void* cntx, int mode) if (myCmd->retries > 0) { --myCmd->retries; StartCommand(self); - } - else { + } else { int iRet; - iRet = self->protocol->handleEvent(self->protocol, myCmd->tran, AQU_TIMEOUT); + iRet = + self->protocol->handleEvent(self->protocol, myCmd->tran, + AQU_TIMEOUT); if (iRet == AQU_POP_CMD) { if (myCmd->tran->handleResponse) myCmd->tran->handleResponse(myCmd->tran); - PopCommand(self); /* remove command */ - } - else if (iRet == AQU_RETRY_CMD) - StartCommand(self); /* restart command */ + PopCommand(self); /* remove command */ + } else if (iRet == AQU_RETRY_CMD) + StartCommand(self); /* restart command */ else if (iRet == AQU_RECONNECT) AQ_Reconnect(self); } return 1; } -static int DelayedStart(void* cntx, int mode) +static int DelayedStart(void *cntx, int mode) { pAsyncQueue self = (pAsyncQueue) cntx; self->nw_tmr = 0; @@ -301,7 +295,7 @@ static int DelayedStart(void* cntx, int mode) return 1; } -static int MyCallback(void* context, int mode) +static int MyCallback(void *context, int mode) { pAsyncQueue self = (pAsyncQueue) context; @@ -311,40 +305,40 @@ static int MyCallback(void* context, int mode) iRet = NETRead(self->pSock, reply, 1, 0); /* printf(" iRet, char = %d, %d\n", iRet, (int)reply[0]); */ - if (iRet < 0) { /* EOF */ + if (iRet < 0) { /* EOF */ iRet = AQ_Reconnect(self); - if (iRet <= 0){ - /* changed to call handleResponse with a bad status code: MK - */ - pAQ_Cmd myCmd = self->command_head; - if(myCmd){ - myCmd->tran->txn_state = ATX_DISCO; - if(myCmd->tran->handleResponse){ - myCmd->tran->handleResponse(myCmd->tran); - } - PopCommand(self); - } + if (iRet <= 0) { + /* changed to call handleResponse with a bad status code: MK + */ + pAQ_Cmd myCmd = self->command_head; + if (myCmd) { + myCmd->tran->txn_state = ATX_DISCO; + if (myCmd->tran->handleResponse) { + myCmd->tran->handleResponse(myCmd->tran); + } + PopCommand(self); + } return iRet; } /* restart the command */ StartCommand(self); return 1; } - if (iRet == 0) { /* TODO: timeout or error */ + if (iRet == 0) { /* TODO: timeout or error */ return 0; } else { pAQ_Cmd myCmd = self->command_head; if (myCmd) { - iRet = self->protocol->handleInput(self->protocol, myCmd->tran, reply[0]); + iRet = + self->protocol->handleInput(self->protocol, myCmd->tran, + reply[0]); if (iRet == 0 || iRet == AQU_POP_CMD) { /* end of command */ if (myCmd->tran->handleResponse) myCmd->tran->handleResponse(myCmd->tran); PopCommand(self); - } - else if (iRet < 0) /* TODO: error */ + } else if (iRet < 0) /* TODO: error */ ; - } - else { + } else { /* TODO: handle unsolicited input */ } } @@ -391,9 +385,9 @@ int AsyncUnitEnqueueTxn(pAsyncUnit unit, pAsyncTxn pTxn) } pAsyncTxn AsyncUnitPrepareTxn(pAsyncUnit unit, - const char* command, int cmd_len, - AsyncTxnHandler callback, void* context, - int rsp_len) + const char *command, int cmd_len, + AsyncTxnHandler callback, void *context, + int rsp_len) { pAsyncTxn myTxn = NULL; @@ -406,10 +400,11 @@ pAsyncTxn AsyncUnitPrepareTxn(pAsyncUnit unit, memset(myTxn, 0, sizeof(AsyncTxn)); if (unit->queue->protocol->prepareTxn) { int iRet; - iRet = unit->queue->protocol->prepareTxn(unit->queue->protocol, myTxn, command, cmd_len, rsp_len); - } - else { - myTxn->out_buf = (char*) malloc(cmd_len + 5); + iRet = + unit->queue->protocol->prepareTxn(unit->queue->protocol, myTxn, + command, cmd_len, rsp_len); + } else { + myTxn->out_buf = (char *) malloc(cmd_len + 5); if (myTxn->out_buf == NULL) { SICSLogWrite("ERROR: Out of memory in AsyncUnitPrepareTxn", eError); free(myTxn); @@ -428,8 +423,8 @@ pAsyncTxn AsyncUnitPrepareTxn(pAsyncUnit unit, if (rsp_len == 0) myTxn->inp_buf = NULL; else { - if(myTxn->inp_buf != NULL){ - free(myTxn->inp_buf); + if (myTxn->inp_buf != NULL) { + free(myTxn->inp_buf); } myTxn->inp_buf = malloc(rsp_len + 1); if (myTxn->inp_buf == NULL) { @@ -448,13 +443,12 @@ pAsyncTxn AsyncUnitPrepareTxn(pAsyncUnit unit, } int AsyncUnitSendTxn(pAsyncUnit unit, - const char* command, int cmd_len, - AsyncTxnHandler callback, void* context, - int rsp_len) + const char *command, int cmd_len, + AsyncTxnHandler callback, void *context, int rsp_len) { pAsyncTxn myTxn = NULL; myTxn = AsyncUnitPrepareTxn(unit, command, cmd_len, - callback, context, rsp_len); + callback, context, rsp_len); if (myTxn == NULL) return -1; return AsyncUnitEnqueueTxn(unit, myTxn); @@ -462,15 +456,16 @@ int AsyncUnitSendTxn(pAsyncUnit unit, typedef struct txn_s { - char* transReply; + char *transReply; int transWait; } TXN, *pTXN; /** * \brief TransCallback is the callback for the general command transaction. */ -static int TransCallback(pAsyncTxn pCmd) { - char* resp = pCmd->inp_buf; +static int TransCallback(pAsyncTxn pCmd) +{ + char *resp = pCmd->inp_buf; int resp_len = pCmd->inp_idx; pTXN self = (pTXN) pCmd->cntx; @@ -479,8 +474,7 @@ static int TransCallback(pAsyncTxn pCmd) { self->transReply[resp_len] = '\0'; self->transReply[0] = '\0'; self->transWait = -1; - } - else { + } else { memcpy(self->transReply, resp, resp_len); self->transReply[resp_len] = '\0'; self->transWait = 0; @@ -489,16 +483,14 @@ static int TransCallback(pAsyncTxn pCmd) { } int AsyncUnitTransact(pAsyncUnit unit, - const char* command, int cmd_len, - char* response, int rsp_len) + const char *command, int cmd_len, + char *response, int rsp_len) { TXN txn; assert(unit); txn.transReply = response; txn.transWait = 1; - AsyncUnitSendTxn(unit, - command, cmd_len, - TransCallback, &txn, rsp_len); + AsyncUnitSendTxn(unit, command, cmd_len, TransCallback, &txn, rsp_len); while (txn.transWait == 1) TaskYield(pServ->pTasker); if (txn.transWait < 0) @@ -506,17 +498,17 @@ int AsyncUnitTransact(pAsyncUnit unit, return 1; } -int AsyncUnitWrite(pAsyncUnit unit, void* buffer, int buflen) +int AsyncUnitWrite(pAsyncUnit unit, void *buffer, int buflen) { int iRet; - mkChannel* sock; + mkChannel *sock; assert(unit); assert(unit->queue); if (buflen > 0) { sock = AsyncUnitGetSocket(unit); iRet = NETWrite(sock, buffer, buflen); /* TODO handle errors */ - if (iRet < 0) { /* EOF */ + if (iRet < 0) { /* EOF */ iRet = AQ_Reconnect(unit->queue); if (iRet == 0) return 0; @@ -525,7 +517,7 @@ int AsyncUnitWrite(pAsyncUnit unit, void* buffer, int buflen) return 1; } -void AsyncUnitSetNotify(pAsyncUnit unit, void* context, AQU_Notify notify) +void AsyncUnitSetNotify(pAsyncUnit unit, void *context, AQU_Notify notify) { assert(unit); unit->notify_func = notify; @@ -578,7 +570,7 @@ void AsyncUnitSetProtocol(pAsyncUnit unit, pAsyncProtocol protocol) unit->queue->protocol = protocol; } -mkChannel* AsyncUnitGetSocket(pAsyncUnit unit) +mkChannel *AsyncUnitGetSocket(pAsyncUnit unit) { assert(unit); assert(unit->queue); @@ -595,8 +587,8 @@ int AsyncUnitReconnect(pAsyncUnit unit) return iRet; } -int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) +int AsyncQueueAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) { char line[132]; pAsyncQueue self = (pAsyncQueue) pData; @@ -610,8 +602,7 @@ int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, cmd[0] = '\0'; for (i = 2; i < argc; ++i) { j = snprintf(&cmd[idx], 10240 - idx, "%s%s", - (i > 2) ? " " : "", - argv[i]); + (i > 2) ? " " : "", argv[i]); if (j < 0) break; idx += j; @@ -635,8 +626,7 @@ int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, snprintf(line, 132, "Invalid argument: %s", argv[2]); SCWrite(pCon, line, eError); return 0; - } - else { + } else { if (delay < 0 || delay > 30000) { snprintf(line, 132, "Value out of range: %d", delay); SCWrite(pCon, line, eError); @@ -645,8 +635,7 @@ int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, self->iDelay = delay; return OKOK; } - } - else { + } else { snprintf(line, 132, "%s.delay = %d", argv[0], self->iDelay); SCWrite(pCon, line, eValue); return OKOK; @@ -662,8 +651,7 @@ int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, snprintf(line, 132, "Invalid argument: %s", argv[2]); SCWrite(pCon, line, eError); return 0; - } - else { + } else { if (timeout < 0 || timeout > 30000) { snprintf(line, 132, "Value out of range: %d", timeout); SCWrite(pCon, line, eError); @@ -672,8 +660,7 @@ int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, self->timeout = timeout; return OKOK; } - } - else { + } else { snprintf(line, 132, "%s.timeout = %d", argv[0], self->timeout); SCWrite(pCon, line, eValue); return OKOK; @@ -689,8 +676,7 @@ int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, snprintf(line, 132, "Invalid argument: %s", argv[2]); SCWrite(pCon, line, eError); return 0; - } - else { + } else { if (retries < 0 || retries > 30000) { snprintf(line, 132, "Value out of range: %d", retries); SCWrite(pCon, line, eError); @@ -699,8 +685,7 @@ int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, self->retries = retries; return OKOK; } - } - else { + } else { snprintf(line, 132, "%s.retries = %d", argv[0], self->retries); SCWrite(pCon, line, eValue); return OKOK; @@ -713,40 +698,43 @@ int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, return 0; } -static pAsyncQueue AQ_Create(const char* host, const char* port) +static pAsyncQueue AQ_Create(const char *host, const char *port) { int i; pAsyncQueue self = NULL; - mkChannel* channel = NULL; + mkChannel *channel = NULL; if (host == NULL) return NULL; /* try the AsyncQueue with this name */ - self = (pAsyncQueue) FindCommandData(pServ->pSics,(char *) host, "AsyncQueue"); + self = + (pAsyncQueue) FindCommandData(pServ->pSics, (char *) host, + "AsyncQueue"); /* try host and port */ if (self == NULL && port) { int port_no = atoi(port); if (port_no == 0) { - struct servent *sp=NULL; + struct servent *sp = NULL; sp = getservbyname(port, NULL); if (sp) port_no = ntohs(sp->s_port); } if (port_no > 0) { struct sockaddr_in sa; - if (CreateSocketAdress(&sa,(char *) host, port_no)) { + if (CreateSocketAdress(&sa, (char *) host, port_no)) { /* look for queue with same address */ for (i = 0; i < queue_index; ++i) if (queue_array[i]->pSock->adresse.sin_port == sa.sin_port - && queue_array[i]->pSock->adresse.sin_addr.s_addr == sa.sin_addr.s_addr) { + && queue_array[i]->pSock->adresse.sin_addr.s_addr == + sa.sin_addr.s_addr) { self = queue_array[i]; break; } } if (self == NULL) { - channel = NETConnectWithFlags((char *)host, port_no, 0); + channel = NETConnectWithFlags((char *) host, port_no, 0); /* TODO handle asynchronous connection */ } } @@ -780,13 +768,11 @@ static int AQ_Init(pAsyncQueue self) /* Init the controller */ if (self->nw_ctx == NULL) NetWatchRegisterCallback(&self->nw_ctx, - self->pSock->sockid, - MyCallback, - self); + self->pSock->sockid, MyCallback, self); return 1; } -static void AQ_Kill(void* pData) +static void AQ_Kill(void *pData) { int i; pAsyncQueue self = (pAsyncQueue) pData; @@ -814,42 +800,48 @@ static void AQ_Kill(void* pData) * * MakeAsyncQueue queueName protocolName hostName portname */ -int AsyncQueueFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) +int AsyncQueueFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) { pAsyncQueue pNew = NULL; - mkChannel* channel = NULL; + mkChannel *channel = NULL; pAsyncProtocol pPro = NULL; int port_no; int iRet = 0; if (argc < 5) { - SCWrite(pCon,"ERROR: insufficient arguments to AsyncQueueFactory", eError); + SCWrite(pCon, "ERROR: insufficient arguments to AsyncQueueFactory", + eError); return 0; } /* try to find an existing queue with this name */ - pNew = (pAsyncQueue) FindCommandData(pServ->pSics, argv[1], "AsyncQueue"); + pNew = + (pAsyncQueue) FindCommandData(pServ->pSics, argv[1], "AsyncQueue"); if (pNew != NULL) { char line[132]; - snprintf(line, 132, "WARNING: AsyncQueue '%s' already exists", argv[1]); + snprintf(line, 132, "WARNING: AsyncQueue '%s' already exists", + argv[1]); SCWrite(pCon, line, eError); SCSendOK(pCon); return 1; } /* try to find an existing protocol with this name */ - pPro = (pAsyncProtocol) FindCommandData(pServ->pSics, argv[2], "AsyncProtocol"); + pPro = + (pAsyncProtocol) FindCommandData(pServ->pSics, argv[2], + "AsyncProtocol"); if (pPro == NULL) { char line[132]; - snprintf(line, 132, "WARNING: AsyncQueue protocol '%s' not found", argv[2]); + snprintf(line, 132, "WARNING: AsyncQueue protocol '%s' not found", + argv[2]); SCWrite(pCon, line, eError); return 0; } port_no = atoi(argv[4]); if (port_no == 0) { - struct servent *sp=NULL; + struct servent *sp = NULL; sp = getservbyname(argv[4], NULL); if (sp) port_no = ntohs(sp->s_port); @@ -861,17 +853,18 @@ int AsyncQueueFactory(SConnection *pCon, SicsInterp *pSics, /* look for queue with same address */ for (i = 0; i < queue_index; ++i) if (queue_array[i]->pSock->adresse.sin_port == sa.sin_port - && queue_array[i]->pSock->adresse.sin_addr.s_addr == sa.sin_addr.s_addr) { + && queue_array[i]->pSock->adresse.sin_addr.s_addr == + sa.sin_addr.s_addr) { char line[132]; - snprintf(line, 132, "WARNING: AsyncQueue '%s' has same address as %s", - argv[1], - queue_array[i]->queue_name); + snprintf(line, 132, + "WARNING: AsyncQueue '%s' has same address as %s", + argv[1], queue_array[i]->queue_name); SCWrite(pCon, line, eError); } - } + } /* TODO: implement asynchronous connection */ channel = NETConnectWithFlags(argv[3], port_no, 0); - } + } if (channel == NULL) { char line[132]; @@ -896,13 +889,12 @@ int AsyncQueueFactory(SConnection *pCon, SicsInterp *pSics, queue_array[queue_index++] = pNew; AQ_Init(pNew); - + /* - create the command - */ + create the command + */ iRet = AddCommand(pSics, argv[1], AsyncQueueAction, AQ_Kill, pNew); - if(!iRet) - { + if (!iRet) { char line[132]; snprintf(line, 123, "ERROR: add command %s failed", argv[1]); SCWrite(pCon, line, eError); @@ -920,7 +912,8 @@ int AsyncQueueFactory(SConnection *pCon, SicsInterp *pSics, * \param handle the handle to the AsyncQueue object * \return 0 for FAILURE, 1 for SUCCESS */ -int AsyncUnitCreateHost(const char* host, const char* port, pAsyncUnit* handle) +int AsyncUnitCreateHost(const char *host, const char *port, + pAsyncUnit * handle) { int status; pAsyncQueue self = NULL; @@ -948,7 +941,8 @@ int AsyncUnitCreateHost(const char* host, const char* port, pAsyncUnit* handle) return 1; } -int AsyncUnitCreate(const char* host, pAsyncUnit* handle) { +int AsyncUnitCreate(const char *host, pAsyncUnit * handle) +{ return AsyncUnitCreateHost(host, NULL, handle); } @@ -957,7 +951,7 @@ int AsyncUnitDestroy(pAsyncUnit unit) assert(unit); assert(unit->queue); pAsyncQueue self = unit->queue; - pAsyncUnit* pNxt = &self->units; + pAsyncUnit *pNxt = &self->units; while (*pNxt) { if (*pNxt == unit) { *pNxt = (*pNxt)->next; @@ -973,15 +967,15 @@ int AsyncUnitDestroy(pAsyncUnit unit) return 1; } -pAsyncUnit AsyncUnitFromQueue(pAsyncQueue queue){ - pAsyncUnit result = NULL; - - result = malloc(sizeof(AsyncUnit)); - if(result == NULL){ - return NULL; - } - memset(result,0,sizeof(AsyncUnit)); - result->queue = queue; - return result; -} +pAsyncUnit AsyncUnitFromQueue(pAsyncQueue queue) +{ + pAsyncUnit result = NULL; + result = malloc(sizeof(AsyncUnit)); + if (result == NULL) { + return NULL; + } + memset(result, 0, sizeof(AsyncUnit)); + result->queue = queue; + return result; +} diff --git a/asyncqueue.h b/asyncqueue.h index 4f5bfc53..2359d575 100644 --- a/asyncqueue.h +++ b/asyncqueue.h @@ -26,7 +26,7 @@ typedef struct __AsyncQueue AsyncQueue, *pAsyncQueue; * \param unit pointer to the AsyncUnit created on positive return * \return positive if successful */ -int AsyncUnitCreate(const char* queueName, pAsyncUnit* unit); +int AsyncUnitCreate(const char *queueName, pAsyncUnit * unit); /** \brief Get an AsyncUnit from a given AsyncQueue * \param queue The AsyncQueue fro which this AsyncUnit is valid * \return a new AsyncUnit or NULL on error @@ -40,9 +40,8 @@ pAsyncUnit AsyncUnitFromQueue(pAsyncQueue queue); * \param unit pointer to the AsyncUnit created on positive return * \return positive if successful */ -int AsyncUnitCreateHost(const char* host, - const char* port, - pAsyncUnit* unit); +int AsyncUnitCreateHost(const char *host, + const char *port, pAsyncUnit * unit); /** \brief destroys an AsyncUnit * @@ -74,9 +73,9 @@ int AsyncUnitEnqueueTxn(pAsyncUnit unit, pAsyncTxn pTxn); * \param resp_len maximum length to be allowed for response */ pAsyncTxn AsyncUnitPrepareTxn(pAsyncUnit unit, - const char* command, int cmd_len, - AsyncTxnHandler responseHandler, void* context, - int rsp_len); + const char *command, int cmd_len, + AsyncTxnHandler responseHandler, + void *context, int rsp_len); /** \brief prepare and queue a transaction * @@ -88,9 +87,9 @@ pAsyncTxn AsyncUnitPrepareTxn(pAsyncUnit unit, * \param resp_len maximum length to be allowed for response */ int AsyncUnitSendTxn(pAsyncUnit unit, - const char* command, int cmd_len, - AsyncTxnHandler responseHandler, void* context, - int rsp_len); + const char *command, int cmd_len, + AsyncTxnHandler responseHandler, void *context, + int rsp_len); /** \brief send a transaction and wait for the response * @@ -102,8 +101,8 @@ int AsyncUnitSendTxn(pAsyncUnit unit, * \param resp_len maximum length to be allowed for response */ int AsyncUnitTransact(pAsyncUnit unit, - const char* command, int cmd_len, - char* response, int rsp_len); + const char *command, int cmd_len, + char *response, int rsp_len); /** \brief write to the AsyncQueue file descriptor * @@ -115,7 +114,7 @@ int AsyncUnitTransact(pAsyncUnit unit, * \param data to be transmitted * \param buflen lenght of data */ -int AsyncUnitWrite(pAsyncUnit unit, void* buffer, int buflen); +int AsyncUnitWrite(pAsyncUnit unit, void *buffer, int buflen); /** \brief registers a notification callback * @@ -125,8 +124,8 @@ int AsyncUnitWrite(pAsyncUnit unit, void* buffer, int buflen); * \param context passed in callback * \param notify function to be called */ -typedef void (*AQU_Notify)(void* context, int event); -void AsyncUnitSetNotify(pAsyncUnit unit, void* context, AQU_Notify notify); +typedef void (*AQU_Notify) (void *context, int event); +void AsyncUnitSetNotify(pAsyncUnit unit, void *context, AQU_Notify notify); /** \brief get the intertransaction delay in milliseconds */ @@ -165,7 +164,7 @@ void AsyncUnitSetProtocol(pAsyncUnit unit, pAsyncProtocol protocol); * \param unit AsyncUnit * \return channel or NULL */ -mkChannel* AsyncUnitGetSocket(pAsyncUnit unit); +mkChannel *AsyncUnitGetSocket(pAsyncUnit unit); /** \brief attempt to reconnect the socket of the associated AsyncQueue * @@ -175,12 +174,12 @@ int AsyncUnitReconnect(pAsyncUnit handle); /** \brief create an AsyncQueue from the SICS command MakeAsyncQueue */ -int AsyncQueueFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int AsyncQueueFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); /** \brief SICS command handler for the AsyncQueue object */ -int AsyncQueueAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int AsyncQueueAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); -#endif /* SICSASYNCQUEUE */ +#endif /* SICSASYNCQUEUE */ diff --git a/background.c b/background.c index ec67e2a1..77fd7121 100644 --- a/background.c +++ b/background.c @@ -12,76 +12,76 @@ /*---------------------------------------------------------------------------*/ typedef struct { - SConnection *con; - char *command; + SConnection *con; + char *command; } BckTask, *pBckTask; /*---------------------------------------------------------------------------*/ -static void KillBckTask(void *data){ - pBckTask self = (pBckTask)data; - if(self == NULL){ - return; - } - if(self->con){ - SCDeleteConnection(self->con); - } - if(self->command){ - free(self->command); - } +static void KillBckTask(void *data) +{ + pBckTask self = (pBckTask) data; + if (self == NULL) { + return; + } + if (self->con) { + SCDeleteConnection(self->con); + } + if (self->command) { + free(self->command); + } } -/*---------------------------------------------------------------------------*/ -static int BackgroundTask(void *data){ - pBckTask self = (pBckTask)data; - - assert(self != NULL); - - InterpExecute(pServ->pSics,self->con,self->command); - return 0; -} -/*----------------------------------------------------------------------------*/ -int BackgroundCommand(SConnection *pCon, char *command){ - pBckTask self = NULL; - - self = calloc(1,sizeof(BckTask)); - if(self == NULL){ - return 0; - } - - self->con = SCCopyConnection(pCon); - self->command = strdup(command); - if(self->con == NULL || self->command == NULL){ - free(self); - return 0; - } - - TaskRegister(pServ->pTasker, - BackgroundTask, - NULL, - KillBckTask, - self, - 1); - return 1; -} -/*------------------------------------------------------------------------*/ -int BackgroundAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - int status; - char command[1024]; - memset(command,0,1024); - Arg2Text(argc-1,&argv[1], command, 1024); - status = BackgroundCommand(pCon,command); - if(status == 0){ - SCWrite(pCon,"ERROR: out of memory starting task", eError); - return 0; - } - SCSendOK(pCon); - return 1; +/*---------------------------------------------------------------------------*/ +static int BackgroundTask(void *data) +{ + pBckTask self = (pBckTask) data; + + assert(self != NULL); + + InterpExecute(pServ->pSics, self->con, self->command); + return 0; } + +/*----------------------------------------------------------------------------*/ +int BackgroundCommand(SConnection * pCon, char *command) +{ + pBckTask self = NULL; + + self = calloc(1, sizeof(BckTask)); + if (self == NULL) { + return 0; + } + + self->con = SCCopyConnection(pCon); + self->command = strdup(command); + if (self->con == NULL || self->command == NULL) { + free(self); + return 0; + } + + TaskRegister(pServ->pTasker, BackgroundTask, NULL, KillBckTask, self, 1); + return 1; +} + +/*------------------------------------------------------------------------*/ +int BackgroundAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + int status; + char command[1024]; + + memset(command, 0, 1024); + Arg2Text(argc - 1, &argv[1], command, 1024); + status = BackgroundCommand(pCon, command); + if (status == 0) { + SCWrite(pCon, "ERROR: out of memory starting task", eError); + return 0; + } + SCSendOK(pCon); + return 1; +} + /*--------------------------------------------------------------------------*/ -void InstallBackground(SicsInterp *pSics){ - AddCommand(pSics, - "bg", - BackgroundAction, - NULL, - NULL); +void InstallBackground(SicsInterp * pSics) +{ + AddCommand(pSics, "bg", BackgroundAction, NULL, NULL); } diff --git a/background.h b/background.h index fb065cab..8467e6e6 100644 --- a/background.h +++ b/background.h @@ -12,15 +12,15 @@ /** * interpreter inteface */ -int BackgroundAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int BackgroundAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); /* * actual function which does the backgrounding */ -int BackgroundCommand(SConnection *pCon, char *command); +int BackgroundCommand(SConnection * pCon, char *command); /* * used only once for installing Background */ -void InstallBackground(SicsInterp *pSics); +void InstallBackground(SicsInterp * pSics); -#endif /*BACKGROUND_H_*/ +#endif /*BACKGROUND_H_ */ diff --git a/bit.h b/bit.h index 45b3cbf3..2e35778f 100644 --- a/bit.h +++ b/bit.h @@ -8,7 +8,7 @@ ----------------------------------------------------------------------------*/ -#include /* for CHAR_BIT */ +#include /* for CHAR_BIT */ #define BITMASK(bit) (1 << ((bit) % CHAR_BIT)) #define BITSLOT(bit) ((bit) / CHAR_BIT) diff --git a/callback.c b/callback.c index e1bef5a9..b3b65cca 100644 --- a/callback.c +++ b/callback.c @@ -53,280 +53,270 @@ static int debug = 0; /*-------------- The data stored for a single callback ------------------*/ - typedef struct __CBItem{ - long iID; - SICSCallBack pFunc; - void *pUserData; - KillFuncIT pKill; - int iEvent; - int killFlag; - struct __CBItem *next; - } CallBackItem, *pCallBackItem; +typedef struct __CBItem { + long iID; + SICSCallBack pFunc; + void *pUserData; + KillFuncIT pKill; + int iEvent; + int killFlag; + struct __CBItem *next; +} CallBackItem, *pCallBackItem; /*--------------------- The interface datastructure ---------------------*/ - typedef struct __ICallBack { - int iID; - pCallBackItem head; - } ICallBack; - -/*------------------------------------------------------------------------*/ - static int CheckPointer(pICallBack self) - { - if(self == NULL) return 0; - if(self->iID != CALLBACK) - { - return 0; - } - return 1; - } -/*-------------------------------------------------------------------------*/ +typedef struct __ICallBack { + int iID; + pCallBackItem head; +} ICallBack; - pICallBack CreateCallBackInterface(void) - { - pICallBack pNew = NULL; - - pNew = (pICallBack)malloc(sizeof(ICallBack)); - if(!pNew) - { - return 0; - } - - pNew->iID = CALLBACK; - pNew->head = NULL; - return pNew; - } -/*--------------------------------------------------------------------------*/ - void DeleteCallBackInterface(pICallBack self) - { - int iRet; - pCallBackItem pItem, pTmp; - - if(!CheckPointer(self)) - { - return; - } - - /* kill all userdata associated with callbacks */ - pItem = self->head; - while(pItem != NULL) - { - pTmp = pItem->next; - if(pItem->pKill != NULL) - { - pItem->pKill(pItem->pUserData); - } - free(pItem); - pItem = pTmp; - } - free(self); - } -/*--------------------------------------------------------------------------*/ -static void markUserdata4Kill(pICallBack self, void *pData) -{ - pCallBackItem pItem = NULL; - - pItem = self->head; - while(pItem != NULL){ - if(pData != NULL && pItem->pUserData == pData) - { - pItem->killFlag = 1; - } - pItem = pItem->next; - } -} -/*-------------------------------------------------------------------------*/ -static void cleanCallbackList(pICallBack self) -{ - pCallBackItem toKill, current; - - /* - * killing at the head - */ - while(self->head != NULL && self->head->killFlag == 0){ - toKill = self->head; - self->head = toKill->next; - if(toKill->pKill != NULL){ - toKill->pKill(toKill->pUserData); - } - free(toKill); - } - - if(self->head == NULL){ - return; - } - - /* - * killing in the middle and the end - */ - current = self->head; - while(current->next != NULL){ - if(current->next->killFlag == 1){ - toKill = current->next; - current->next = toKill->next; - if(toKill->pKill != NULL){ - toKill->pKill(toKill->pUserData); - } - free(toKill); - } else { - current = current->next; - } - } -} -/*--------------------------------------------------------------------------*/ - int InvokeCallBack(pICallBack self, int iEvent, void *pEventData) - { - pCallBackItem pItem; - int iCurrent, iRet; - int iResult = 1, iKill = 0;; - - if(!CheckPointer(self)) - { - return 0; - } - - pItem = self->head; - while(pItem != NULL) - { - if(pItem->iEvent == iEvent && pItem->killFlag == 0) - { - iRet = pItem->pFunc(iEvent, pEventData,pItem->pUserData); - if(iRet < 0) - { - pItem->killFlag = 1; - if(pItem->pUserData != NULL) - { - markUserdata4Kill(self, pItem->pUserData); - iKill = 1; - } - } - else if(iRet != 1) - { - iResult = 0; - } - } - pItem = pItem->next; - } - - /* kill run */ - if(iKill == 1){ - cleanCallbackList(self); - } - - return iResult; - } -/*--------------------------------------------------------------------------*/ - static long lCount = 1L; - - long RegisterCallback(pICallBack self, int iEvent, - SICSCallBack pFunc, - void *pUserData, KillFunc pKFunc) - { - pCallBackItem pItem = NULL; - - if(!CheckPointer(self)) - { - return 0; - } - - pItem = calloc(1,sizeof(CallBackItem)); - if(pItem == NULL){ - return -1; - } - pItem->iID = lCount++; - assert(pFunc); - pItem->pFunc = pFunc; - pItem->iEvent = iEvent; - pItem->pUserData = pUserData; - pItem->pKill = pKFunc; - pItem->killFlag = 0; - pItem->next = self->head; - self->head = pItem; - if(debug){ - printf("Registered callback at %p\n",self); - } - return pItem->iID; - } /*------------------------------------------------------------------------*/ -static void markById(pICallBack self, int lID) +static int CheckPointer(pICallBack self) { - pCallBackItem pItem = NULL; - - pItem = self->head; - while(pItem != NULL) - { - if(pItem->iID == lID) - { - pItem->killFlag = 1; - } - pItem = pItem->next; - } -} -/*-------------------------------------------------------------------------*/ - int RemoveCallback(pICallBack self, long lID) - { - CallBackItem sItem; - int iCurrent; - - if(!CheckPointer(self)) - { - return 0; - } - markById(self,lID); - cleanCallbackList(self); - return 0; - } -/*--------------------------------------------------------------------------*/ - int RemoveCallback2(pICallBack self, void *pUserData) - { - CallBackItem sItem; - int iCurrent; - - if(!CheckPointer(self)) - { - return 0; - } - markUserdata4Kill(self,pUserData); - cleanCallbackList(self); - return 1; - } - /*--------------------------------------------------------------------------*/ - int RemoveCallbackCon(pICallBack self, SConnection *con) - { - pCallBackItem pItem; - SConnection *tst = NULL; - - if(!CheckPointer(self)) - { - return 0; - } - - pItem = self->head; - while(pItem != NULL) - { - tst = (SConnection *)pItem->pUserData; - if(VerifyConnection(tst) && tst->ident == con->ident) - { - if(debug){ - printf("Killing callback on connection.ident = %ld\n", con->ident); - } - pItem->killFlag = 1; - } - pItem = pItem->next; - } - cleanCallbackList(self); - return 1; - } -/*------------------------------------------------------------------- - a write function for the connection which writes to stdout - -------------------------------------------------------------------*/ -static int CallbackWrite(SConnection *pCon,char *message, int outCode) -{ - if(outCode >= eWarning) - { - fputs(message,stdout); - fputs("\n",stdout); + if (self == NULL) + return 0; + if (self->iID != CALLBACK) { + return 0; } return 1; } + +/*-------------------------------------------------------------------------*/ + +pICallBack CreateCallBackInterface(void) +{ + pICallBack pNew = NULL; + + pNew = (pICallBack) malloc(sizeof(ICallBack)); + if (!pNew) { + return 0; + } + + pNew->iID = CALLBACK; + pNew->head = NULL; + return pNew; +} + +/*--------------------------------------------------------------------------*/ +void DeleteCallBackInterface(pICallBack self) +{ + int iRet; + pCallBackItem pItem, pTmp; + + if (!CheckPointer(self)) { + return; + } + + /* kill all userdata associated with callbacks */ + pItem = self->head; + while (pItem != NULL) { + pTmp = pItem->next; + if (pItem->pKill != NULL) { + pItem->pKill(pItem->pUserData); + } + free(pItem); + pItem = pTmp; + } + free(self); +} + +/*--------------------------------------------------------------------------*/ +static void markUserdata4Kill(pICallBack self, void *pData) +{ + pCallBackItem pItem = NULL; + + pItem = self->head; + while (pItem != NULL) { + if (pData != NULL && pItem->pUserData == pData) { + pItem->killFlag = 1; + } + pItem = pItem->next; + } +} + +/*-------------------------------------------------------------------------*/ +static void cleanCallbackList(pICallBack self) +{ + pCallBackItem toKill, current; + + /* + * killing at the head + */ + while (self->head != NULL && self->head->killFlag == 0) { + toKill = self->head; + self->head = toKill->next; + if (toKill->pKill != NULL) { + toKill->pKill(toKill->pUserData); + } + free(toKill); + } + + if (self->head == NULL) { + return; + } + + /* + * killing in the middle and the end + */ + current = self->head; + while (current->next != NULL) { + if (current->next->killFlag == 1) { + toKill = current->next; + current->next = toKill->next; + if (toKill->pKill != NULL) { + toKill->pKill(toKill->pUserData); + } + free(toKill); + } else { + current = current->next; + } + } +} + +/*--------------------------------------------------------------------------*/ +int InvokeCallBack(pICallBack self, int iEvent, void *pEventData) +{ + pCallBackItem pItem; + int iCurrent, iRet; + int iResult = 1, iKill = 0;; + + if (!CheckPointer(self)) { + return 0; + } + + pItem = self->head; + while (pItem != NULL) { + if (pItem->iEvent == iEvent && pItem->killFlag == 0) { + iRet = pItem->pFunc(iEvent, pEventData, pItem->pUserData); + if (iRet < 0) { + pItem->killFlag = 1; + if (pItem->pUserData != NULL) { + markUserdata4Kill(self, pItem->pUserData); + iKill = 1; + } + } else if (iRet != 1) { + iResult = 0; + } + } + pItem = pItem->next; + } + + /* kill run */ + if (iKill == 1) { + cleanCallbackList(self); + } + + return iResult; +} + +/*--------------------------------------------------------------------------*/ +static long lCount = 1L; + +long RegisterCallback(pICallBack self, int iEvent, + SICSCallBack pFunc, void *pUserData, KillFunc pKFunc) +{ + pCallBackItem pItem = NULL; + + if (!CheckPointer(self)) { + return 0; + } + + pItem = calloc(1, sizeof(CallBackItem)); + if (pItem == NULL) { + return -1; + } + pItem->iID = lCount++; + assert(pFunc); + pItem->pFunc = pFunc; + pItem->iEvent = iEvent; + pItem->pUserData = pUserData; + pItem->pKill = pKFunc; + pItem->killFlag = 0; + pItem->next = self->head; + self->head = pItem; + if (debug) { + printf("Registered callback at %p\n", self); + } + return pItem->iID; +} + +/*------------------------------------------------------------------------*/ +static void markById(pICallBack self, int lID) +{ + pCallBackItem pItem = NULL; + + pItem = self->head; + while (pItem != NULL) { + if (pItem->iID == lID) { + pItem->killFlag = 1; + } + pItem = pItem->next; + } +} + +/*-------------------------------------------------------------------------*/ +int RemoveCallback(pICallBack self, long lID) +{ + CallBackItem sItem; + int iCurrent; + + if (!CheckPointer(self)) { + return 0; + } + markById(self, lID); + cleanCallbackList(self); + return 0; +} + +/*--------------------------------------------------------------------------*/ +int RemoveCallback2(pICallBack self, void *pUserData) +{ + CallBackItem sItem; + int iCurrent; + + if (!CheckPointer(self)) { + return 0; + } + markUserdata4Kill(self, pUserData); + cleanCallbackList(self); + return 1; +} + + /*--------------------------------------------------------------------------*/ +int RemoveCallbackCon(pICallBack self, SConnection * con) +{ + pCallBackItem pItem; + SConnection *tst = NULL; + + if (!CheckPointer(self)) { + return 0; + } + + pItem = self->head; + while (pItem != NULL) { + tst = (SConnection *) pItem->pUserData; + if (VerifyConnection(tst) && tst->ident == con->ident) { + if (debug) { + printf("Killing callback on connection.ident = %ld\n", con->ident); + } + pItem->killFlag = 1; + } + pItem = pItem->next; + } + cleanCallbackList(self); + return 1; +} + +/*------------------------------------------------------------------- + a write function for the connection which writes to stdout + -------------------------------------------------------------------*/ +static int CallbackWrite(SConnection * pCon, char *message, int outCode) +{ + if (outCode >= eWarning) { + fputs(message, stdout); + fputs("\n", stdout); + } + return 1; +} + /*----------------------------------------------------------------------- the actual callback function invoking the script ------------------------------------------------------------------------*/ @@ -337,25 +327,24 @@ static int ScriptCallback(int iEvent, void *pEventData, void *pUserData) int status; pCon = SCCreateDummyConnection(pServ->pSics); - if(!pCon) - { - fprintf(stdout,"ERROR: failed to create dummy connection\n"); + if (!pCon) { + fprintf(stdout, "ERROR: failed to create dummy connection\n"); return 0; } - if(pUserData == NULL) - { - fprintf(stdout,"ERROR: ScriptCallback: no script to execute\n"); + if (pUserData == NULL) { + fprintf(stdout, "ERROR: ScriptCallback: no script to execute\n"); return 0; } - SCSetRights(pCon,usInternal); - status = InterpExecute(pServ->pSics,pCon,(char *)pUserData); + SCSetRights(pCon, usInternal); + status = InterpExecute(pServ->pSics, pCon, (char *) pUserData); SCDeleteConnection(pCon); return 1; } + /*------------------------------------------------------------------------*/ -int CallbackScript(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) +int CallbackScript(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) { long lID; int iEvent, status; @@ -363,88 +352,76 @@ int CallbackScript(SConnection *pCon, SicsInterp *pSics, void *pData, CommandList *pCom = NULL; char pBuffer[132]; - if(argc < 2) - { - SCWrite(pCon,"ERROR: insufficient number of arguments to callbackScript", - eError); + if (argc < 2) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to callbackScript", + eError); return 0; } /* - only managers may do this - */ - if(!SCMatchRights(pCon,usMugger)) - { + only managers may do this + */ + if (!SCMatchRights(pCon, usMugger)) { return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"connect") == 0) - { - if(argc < 4) - { - SCWrite(pCon,"ERROR: not enough arguments to CallbackScript connect", - eError); + if (strcmp(argv[1], "connect") == 0) { + if (argc < 4) { + SCWrite(pCon, + "ERROR: not enough arguments to CallbackScript connect", + eError); return 0; } strtolower(argv[2]); - pCom = FindCommand(pSics,argv[2]); - if(!pCom) - { - SCWrite(pCon,"ERROR: object to connect to not found",eError); + pCom = FindCommand(pSics, argv[2]); + if (!pCom) { + SCWrite(pCon, "ERROR: object to connect to not found", eError); return 0; } pCall = GetCallbackInterface(pCom->pData); - if(!pCall) - { - SCWrite(pCon,"ERROR: object has no callback interface",eError); + if (!pCall) { + SCWrite(pCon, "ERROR: object has no callback interface", eError); return 0; } iEvent = Text2Event(argv[3]); - if(iEvent < 0) - { - SCWrite(pCon,"ERROR: event type not known",eError); + if (iEvent < 0) { + SCWrite(pCon, "ERROR: event type not known", eError); return 0; } - Arg2Text(argc-4,&argv[4],pBuffer,131); + Arg2Text(argc - 4, &argv[4], pBuffer, 131); lID = RegisterCallback(pCall, - iEvent,ScriptCallback, - strdup(pBuffer),free); - sprintf(pBuffer,"callback = %ld", lID); - SCWrite(pCon,pBuffer,eValue); + iEvent, ScriptCallback, strdup(pBuffer), free); + sprintf(pBuffer, "callback = %ld", lID); + SCWrite(pCon, pBuffer, eValue); return 1; - } - else if(strcmp(argv[1],"remove") == 0) - { - if(argc < 4) - { - SCWrite(pCon,"ERROR: not enough arguments to CallbackScript remove", - eError); + } else if (strcmp(argv[1], "remove") == 0) { + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough arguments to CallbackScript remove", + eError); return 0; } strtolower(argv[2]); - pCom = FindCommand(pSics,argv[2]); - if(!pCom) - { - SCWrite(pCon,"ERROR: object to remove to not found",eError); + pCom = FindCommand(pSics, argv[2]); + if (!pCom) { + SCWrite(pCon, "ERROR: object to remove to not found", eError); return 0; } pCall = GetCallbackInterface(pCom->pData); - if(!pCall) - { - SCWrite(pCon,"ERROR: object has no callback interface",eError); + if (!pCall) { + SCWrite(pCon, "ERROR: object has no callback interface", eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[3],&iEvent); - if(status != TCL_OK) - { - SCWrite(pCon,"ERROR: failed to convert callback ID to int",eError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[3], &iEvent); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert callback ID to int", eError); return 0; } - RemoveCallback(pCall,(long)iEvent); + RemoveCallback(pCall, (long) iEvent); SCSendOK(pCon); return 1; } - SCWrite(pCon,"ERROR: subcommand to CallbackScript not known",eError); + SCWrite(pCon, "ERROR: subcommand to CallbackScript not known", eError); return 0; } diff --git a/cell.c b/cell.c index d9c73391..b0ba8958 100644 --- a/cell.c +++ b/cell.c @@ -16,11 +16,12 @@ #ifndef PI #define PI (3.1415926536) /* pi */ #endif -#define TWOPI (2*PI) /* 2*pi */ +#define TWOPI (2*PI) /* 2*pi */ /***************************************************************************** * default value for a cell ****************************************************************************/ -void defaultCell(plattice cell){ +void defaultCell(plattice cell) +{ cell->a = 1.; cell->b = 1.; cell->c = 1.; @@ -28,6 +29,7 @@ void defaultCell(plattice cell){ cell->beta = 90.; cell->gamma = 90.; } + /******************************************************************************* * Transform direct lattice to reciprocal lattice. *******************************************************************************/ @@ -43,37 +45,39 @@ int directToReciprocalLattice(lattice direct, plattice reciprocal) beta = direct.beta; gamma = direct.gamma; - cos_alfa = Cosd (alfa); - cos_beta = Cosd (beta); - cos_gamma = Cosd (gamma); + cos_alfa = Cosd(alfa); + cos_beta = Cosd(beta); + cos_gamma = Cosd(gamma); - sin_alfa = Sind (alfa); - sin_beta = Sind (beta); - sin_gamma = Sind (gamma); + sin_alfa = Sind(alfa); + sin_beta = Sind(beta); + sin_gamma = Sind(gamma); - reciprocal->alpha = Acosd ((cos_beta*cos_gamma - cos_alfa)/sin_beta/sin_gamma); - reciprocal->beta =Acosd ((cos_alfa*cos_gamma - cos_beta)/sin_alfa/sin_gamma); - reciprocal->gamma = Acosd ((cos_alfa*cos_beta - cos_gamma)/sin_alfa/sin_beta); + reciprocal->alpha = + Acosd((cos_beta * cos_gamma - cos_alfa) / sin_beta / sin_gamma); + reciprocal->beta = + Acosd((cos_alfa * cos_gamma - cos_beta) / sin_alfa / sin_gamma); + reciprocal->gamma = + Acosd((cos_alfa * cos_beta - cos_gamma) / sin_alfa / sin_beta); ad = direct.a; bd = direct.b; cd = direct.c; - arg = 1 + 2*cos_alfa*cos_beta*cos_gamma - cos_alfa*cos_alfa - - cos_beta*cos_beta - - cos_gamma*cos_gamma; - if (arg < 0.0) - { - return REC_NO_VOLUME; - } + arg = 1 + 2 * cos_alfa * cos_beta * cos_gamma - cos_alfa * cos_alfa - + cos_beta * cos_beta - cos_gamma * cos_gamma; + if (arg < 0.0) { + return REC_NO_VOLUME; + } - vol = ad*bd*cd*sqrt (arg); - reciprocal->a = bd*cd*sin_alfa/vol; - reciprocal->b = ad*cd*sin_beta/vol; - reciprocal->c = bd*ad*sin_gamma/vol; + vol = ad * bd * cd * sqrt(arg); + reciprocal->a = bd * cd * sin_alfa / vol; + reciprocal->b = ad * cd * sin_beta / vol; + reciprocal->c = bd * ad * sin_gamma / vol; return (0); } + /******************************************************************************* * Transform reciprocal lattice to direct lattice. *******************************************************************************/ @@ -89,89 +93,94 @@ int reciprocalToDirectLattice(lattice reciprocal, plattice direct) beta = reciprocal.beta; gamma = reciprocal.gamma; - cos_alfa = Cosd (alfa); - cos_beta = Cosd (beta); - cos_gamma = Cosd (gamma); + cos_alfa = Cosd(alfa); + cos_beta = Cosd(beta); + cos_gamma = Cosd(gamma); - sin_alfa = Sind (alfa); - sin_beta = Sind (beta); - sin_gamma = Sind (gamma); + sin_alfa = Sind(alfa); + sin_beta = Sind(beta); + sin_gamma = Sind(gamma); - direct->alpha = Acosd ((cos_beta*cos_gamma - cos_alfa)/sin_beta/sin_gamma); - direct->beta = Acosd ((cos_alfa*cos_gamma - cos_beta)/sin_alfa/sin_gamma); - direct->gamma = Acosd ((cos_alfa*cos_beta - cos_gamma)/sin_alfa/sin_beta); + direct->alpha = + Acosd((cos_beta * cos_gamma - cos_alfa) / sin_beta / sin_gamma); + direct->beta = + Acosd((cos_alfa * cos_gamma - cos_beta) / sin_alfa / sin_gamma); + direct->gamma = + Acosd((cos_alfa * cos_beta - cos_gamma) / sin_alfa / sin_beta); ar = reciprocal.a; br = reciprocal.b; cr = reciprocal.c; - arg = 1 + 2*cos_alfa*cos_beta*cos_gamma - cos_alfa*cos_alfa - - cos_beta*cos_beta - - cos_gamma*cos_gamma; - if (arg < 0.0) - { - return REC_NO_VOLUME; - } + arg = 1 + 2 * cos_alfa * cos_beta * cos_gamma - cos_alfa * cos_alfa - + cos_beta * cos_beta - cos_gamma * cos_gamma; + if (arg < 0.0) { + return REC_NO_VOLUME; + } - vol = ar*br*cr*sqrt (arg); - direct->a = br*cr*sin_alfa/vol; - direct->b = ar*cr*sin_beta/vol; - direct->c = br*ar*sin_gamma/vol; + vol = ar * br * cr * sqrt(arg); + direct->a = br * cr * sin_alfa / vol; + direct->b = ar * cr * sin_beta / vol; + direct->c = br * ar * sin_gamma / vol; return (0); } + /*************************************************************************************** * Build a B matrix ***************************************************************************************/ -int calculateBMatrix(lattice direct, MATRIX B) { +int calculateBMatrix(lattice direct, MATRIX B) +{ lattice reciprocal; int status; assert(MatRow(B) == 3); assert(MatCol(B) == 3); - status = directToReciprocalLattice(direct,&reciprocal); - if(status < 0) { + status = directToReciprocalLattice(direct, &reciprocal); + if (status < 0) { return status; } - - mat_fill(B,ZERO_MATRIX); - - /* - top row - */ - B[0][0] = reciprocal.a; - B[0][1] = reciprocal.b*Cosd(reciprocal.gamma); - B[0][2] = reciprocal.c*Cosd(reciprocal.beta); + + mat_fill(B, ZERO_MATRIX); /* - middle row - */ - B[1][1] = reciprocal.b*Sind(reciprocal.gamma); - B[1][2] = -reciprocal.c*Sind(reciprocal.beta)*Cosd(direct.alpha); - + top row + */ + B[0][0] = reciprocal.a; + B[0][1] = reciprocal.b * Cosd(reciprocal.gamma); + B[0][2] = reciprocal.c * Cosd(reciprocal.beta); + /* - bottom row - */ - B[2][2] = 1./direct.c; - + middle row + */ + B[1][1] = reciprocal.b * Sind(reciprocal.gamma); + B[1][2] = -reciprocal.c * Sind(reciprocal.beta) * Cosd(direct.alpha); + + /* + bottom row + */ + B[2][2] = 1. / direct.c; + return 1; } + /*--------------------------------------------------------------------------*/ -int cellFromUB(MATRIX UB, plattice direct){ +int cellFromUB(MATRIX UB, plattice direct) +{ MATRIX UBTRANS, GINV, G; UBTRANS = mat_tran(UB); - if(UBTRANS == NULL){ + if (UBTRANS == NULL) { return CELLNOMEMORY; } - GINV = mat_mul(UBTRANS,UB); - if(GINV == NULL){ + GINV = mat_mul(UBTRANS, UB); + if (GINV == NULL) { mat_free(UBTRANS); return CELLNOMEMORY; } G = mat_inv(GINV); - if(G == NULL){ + if (G == NULL) { mat_free(UBTRANS); mat_free(GINV); return CELLNOMEMORY; @@ -179,9 +188,8 @@ int cellFromUB(MATRIX UB, plattice direct){ direct->a = sqrt(G[0][0]); direct->b = sqrt(G[1][1]); direct->c = sqrt(G[2][2]); - direct->alpha = Acosd(G[1][2]/(direct->b * direct->c)); - direct->beta = Acosd(G[2][0]/(direct->a * direct->c)); - direct->gamma = Acosd(G[0][1]/(direct->a * direct->c)); + direct->alpha = Acosd(G[1][2] / (direct->b * direct->c)); + direct->beta = Acosd(G[2][0] / (direct->a * direct->c)); + direct->gamma = Acosd(G[0][1] / (direct->a * direct->c)); return 1; } - diff --git a/cell.h b/cell.h index 40e74c2b..83ff02de 100644 --- a/cell.h +++ b/cell.h @@ -18,10 +18,10 @@ /** * lattice parameters: either reciprocal or direct */ - typedef struct { - double a,b,c; - double alpha, beta, gamma; - }lattice, *plattice; +typedef struct { + double a, b, c; + double alpha, beta, gamma; +} lattice, *plattice; /** * defaultCell assigns defualt values to cell parameters * @param cell The lattice to assign default too @@ -32,15 +32,15 @@ void defaultCell(plattice cell); * @param direct The input direct cell parameters. * @param reciprocal The output reciprocal cell constants * @return 0 on success, > 0 else - */ - int directToReciprocalLattice(lattice direct, plattice reciprocal); + */ +int directToReciprocalLattice(lattice direct, plattice reciprocal); /** * conversion from a reciprocal lattice to the directone. * @param reciprocal The input reciprocal cell parameters. * @param direct The output direct cell constants * @return 0 on success, > 0 else - */ - int reciprocalToDirectLattice(lattice reciprocal, plattice direct); + */ +int reciprocalToDirectLattice(lattice reciprocal, plattice direct); /** * calculate a crystallographic B matrix from the cell constants * @param direct The direct cell lattice to calculate B from diff --git a/chadapter.c b/chadapter.c index 3e5753d6..f4dd8738 100644 --- a/chadapter.c +++ b/chadapter.c @@ -24,488 +24,455 @@ #define NOTIMPLEMENTED -11555 /*-------------------------------------------------------------------------*/ - static void *AdapterGetInterface(void *pData, int iID) - { - pCHAdapter self = NULL; - - self = (pCHAdapter)pData; - assert(self); - if(iID == DRIVEID) - { - return self->pInt; - } - return NULL; +static void *AdapterGetInterface(void *pData, int iID) +{ + pCHAdapter self = NULL; + + self = (pCHAdapter) pData; + assert(self); + if (iID == DRIVEID) { + return self->pInt; } + return NULL; +} + /*-------------------------------------------------------------------------*/ - static int CHHalt(void *pData) - { - pCHAdapter self = NULL; +static int CHHalt(void *pData) +{ + pCHAdapter self = NULL; - self = (pCHAdapter)pData; - assert(self); + self = (pCHAdapter) pData; + assert(self); - self->pDriv->Halt(self->pDriv); + self->pDriv->Halt(self->pDriv); + + return 1; +} - return 1; - } /*-------------------------------------------------------------------------*/ - static int CHLimits(void *pData, float fVal, char *error, int iErrlen) - { - pCHAdapter self = NULL; +static int CHLimits(void *pData, float fVal, char *error, int iErrlen) +{ + pCHAdapter self = NULL; - self = (pCHAdapter)pData; - assert(self); + self = (pCHAdapter) pData; + assert(self); - if(fVal < self->fLower) - { - strncpy(error,"Lower limit violated",iErrlen); - return 0; - } - if(fVal > self->fUpper) - { - strncpy(error,"Upper limit violated",iErrlen); - return 0; - } - return 1; + if (fVal < self->fLower) { + strncpy(error, "Lower limit violated", iErrlen); + return 0; } + if (fVal > self->fUpper) { + strncpy(error, "Upper limit violated", iErrlen); + return 0; + } + return 1; +} + /*------------------------------------------------------------------------*/ - static float CHGetValue(void *pData, SConnection *pCon) - { - pCHAdapter self = NULL; - float fVal; - int iRet; - char pBueffel[80]; +static float CHGetValue(void *pData, SConnection * pCon) +{ + pCHAdapter self = NULL; + float fVal; + int iRet; + char pBueffel[80]; - self = (pCHAdapter)pData; - assert(self); + self = (pCHAdapter) pData; + assert(self); - iRet = self->pDriv->GetPar(self->pDriv,self->pParName,pBueffel,79); - if(!iRet) - { - fVal = -9999999.99; - self->pDriv->GetError(self->pDriv,&iRet,pBueffel,79); - SCWrite(pCon,pBueffel,eError); - return fVal; - } - sscanf(pBueffel,"%f",&fVal); - return fVal; + iRet = self->pDriv->GetPar(self->pDriv, self->pParName, pBueffel, 79); + if (!iRet) { + fVal = -9999999.99; + self->pDriv->GetError(self->pDriv, &iRet, pBueffel, 79); + SCWrite(pCon, pBueffel, eError); + return fVal; } + sscanf(pBueffel, "%f", &fVal); + return fVal; +} + /*-----------------------------------------------------------------------*/ - static int CHStatus(void *pData, SConnection *pCon) - { - pCHAdapter self = NULL; - int iRet, iCode; - static int iRetry = 0; - char pBueffel[80], pError[132]; +static int CHStatus(void *pData, SConnection * pCon) +{ + pCHAdapter self = NULL; + int iRet, iCode; + static int iRetry = 0; + char pBueffel[80], pError[132]; - self = (pCHAdapter)pData; - assert(self); + self = (pCHAdapter) pData; + assert(self); - iRet = self->pDriv->CheckPar(self->pDriv,self->pParName); - switch(iRet) - { - case OKOK: - case HWIdle: - iRetry = 0; - return HWIdle; - case HWFault: - self->pDriv->GetError(self->pDriv,&iCode,pBueffel,79); - iRet = self->pDriv->TryFixIt(self->pDriv,iCode); - sprintf(pError,"ERROR: %s",pBueffel); - SCWrite(pCon,pError,eError); - if(iRet == CHFAIL || iRetry >= 3) - { - iRetry = 0; - return HWFault; - } - else - { - iRetry++; - self->pDriv->SetPar(self->pDriv,self->pParName, - self->fTarget); - return HWBusy; - } - break; - case HWBusy: - return HWBusy; - } - return HWFault; + iRet = self->pDriv->CheckPar(self->pDriv, self->pParName); + switch (iRet) { + case OKOK: + case HWIdle: + iRetry = 0; + return HWIdle; + case HWFault: + self->pDriv->GetError(self->pDriv, &iCode, pBueffel, 79); + iRet = self->pDriv->TryFixIt(self->pDriv, iCode); + sprintf(pError, "ERROR: %s", pBueffel); + SCWrite(pCon, pError, eError); + if (iRet == CHFAIL || iRetry >= 3) { + iRetry = 0; + return HWFault; + } else { + iRetry++; + self->pDriv->SetPar(self->pDriv, self->pParName, self->fTarget); + return HWBusy; + } + break; + case HWBusy: + return HWBusy; } + return HWFault; +} + /*-------------------------------------------------------------------------*/ - static long CHSetValue(void *pData, SConnection *pCon, float fValue) - { - pCHAdapter self = NULL; - char pBueffel[80], pError[132]; - int iRet, iCode, i; +static long CHSetValue(void *pData, SConnection * pCon, float fValue) +{ + pCHAdapter self = NULL; + char pBueffel[80], pError[132]; + int iRet, iCode, i; - self = (pCHAdapter)pData; - assert(self); + self = (pCHAdapter) pData; + assert(self); - /* check privilege */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: Insufficient privilege for driving",eError); - return 0; - } - - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->SetPar(self->pDriv,self->pParName,fValue); - if(iRet) - { - self->fTarget = fValue; - return 1; - } - self->pDriv->GetError(self->pDriv,&iCode,pBueffel,79); - sprintf(pError,"ERROR: %s",pBueffel); - SCWrite(pCon,pError,eError); - iRet = self->pDriv->TryFixIt(self->pDriv,iCode); - if(iRet == CHFAIL) - return 0; - } - return 0; - } -/*------------------------------------------------------------------------*/ - static void KillAdapter(void *pData) - { - pCHAdapter self = NULL; - - self = (pCHAdapter)pData; - if(!self) - return; - - if(self->pDes) - DeleteDescriptor(self->pDes); - - if(self->pInt) - free(self->pInt); - - if(self->pParName); - free(self->pParName); - - free(self); + /* check privilege */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: Insufficient privilege for driving", eError); + return 0; } + + for (i = 0; i < 3; i++) { + iRet = self->pDriv->SetPar(self->pDriv, self->pParName, fValue); + if (iRet) { + self->fTarget = fValue; + return 1; + } + self->pDriv->GetError(self->pDriv, &iCode, pBueffel, 79); + sprintf(pError, "ERROR: %s", pBueffel); + SCWrite(pCon, pError, eError); + iRet = self->pDriv->TryFixIt(self->pDriv, iCode); + if (iRet == CHFAIL) + return 0; + } + return 0; +} + +/*------------------------------------------------------------------------*/ +static void KillAdapter(void *pData) +{ + pCHAdapter self = NULL; + + self = (pCHAdapter) pData; + if (!self) + return; + + if (self->pDes) + DeleteDescriptor(self->pDes); + + if (self->pInt) + free(self->pInt); + + if (self->pParName); + free(self->pParName); + + free(self); +} + /*----------------------------------------------------------------------- Syntax: ChopperAdapter name choppercontroller parname upper lower */ - int CHAdapterFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[256]; - pCHAdapter pNew = NULL; - pChoco pChopper = NULL; - CommandList *pCom = NULL; - pDummy pDum = NULL; - double dUpper, dLower; - int iRet; +int CHAdapterFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[256]; + pCHAdapter pNew = NULL; + pChoco pChopper = NULL; + CommandList *pCom = NULL; + pDummy pDum = NULL; + double dUpper, dLower; + int iRet; - /* do we have enough arguments? */ - if(argc < 6) - { - SCWrite(pCon, - "ERROR: Insufficient number of arguments to ChopperAdapter", + /* do we have enough arguments? */ + if (argc < 6) { + SCWrite(pCon, + "ERROR: Insufficient number of arguments to ChopperAdapter", eError); - return 0; - } - - /* find the chopper first */ - pCom = FindCommand(pSics,argv[2]); - if(pCom) - { - pDum = (pDummy)pCom->pData; - if(pDum) - { - if(strcmp(pDum->pDescriptor->name,"Chopper") == 0) - { - pChopper = (pChoco)pCom->pData; - } - } - } - if(!pChopper) - { - sprintf(pBueffel,"ERROR: %s is NO chopper controller", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* interpret limits */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[5],&dUpper); - if(iRet != TCL_OK) - { - sprintf(pBueffel, - "ERROR: expected numeric argument for upper limit, got %s", - argv[4]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[4],&dLower); - if(iRet != TCL_OK) - { - sprintf(pBueffel, - "ERROR: expected numeric argument for lower limit, got %s", - argv[5]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* allocate new adapter data structure */ - pNew = (pCHAdapter)malloc(sizeof(CHAdapter)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory in ChopperAdapter",eError); - return 0; - } - memset(pNew,0,sizeof(CHAdapter)); - - pNew->pDes = CreateDescriptor("ChopperAdapter"); - pNew->pDriv = CHGetDriver(pChopper); - pNew->pInt = CreateDrivableInterface(); - pNew->pParName = strdup(argv[3]); - if( !pNew->pDes || !pNew->pDriv || !pNew->pInt || !pNew->pParName) - { - SCWrite(pCon,"ERROR: out of memory in ChopperAdapter",eError); - return 0; - } - - /* initialize other fields */ - pNew->fTarget = 0.; - pNew->fLower = (float)dLower; - pNew->fUpper = (float)dUpper; - pNew->pDes->GetInterface = AdapterGetInterface; - pNew->pInt->Halt = CHHalt; - pNew->pInt->CheckLimits = CHLimits; - pNew->pInt->SetValue = CHSetValue; - pNew->pInt->CheckStatus = CHStatus; - pNew->pInt->GetValue = CHGetValue; - - /* install command */ - iRet = AddCommand(pSics, argv[1],CHAdapterAction,KillAdapter,pNew); - if(!iRet) - { - sprintf(pBueffel, - "ERROR: duplicate ChopperAdapter command %s NOT created", - argv[1]); - SCWrite(pCon,pBueffel,eError); - KillAdapter(pNew); - return 0; - } - return 1; + return 0; } + + /* find the chopper first */ + pCom = FindCommand(pSics, argv[2]); + if (pCom) { + pDum = (pDummy) pCom->pData; + if (pDum) { + if (strcmp(pDum->pDescriptor->name, "Chopper") == 0) { + pChopper = (pChoco) pCom->pData; + } + } + } + if (!pChopper) { + sprintf(pBueffel, "ERROR: %s is NO chopper controller", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* interpret limits */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[5], &dUpper); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: expected numeric argument for upper limit, got %s", + argv[4]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[4], &dLower); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: expected numeric argument for lower limit, got %s", + argv[5]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* allocate new adapter data structure */ + pNew = (pCHAdapter) malloc(sizeof(CHAdapter)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory in ChopperAdapter", eError); + return 0; + } + memset(pNew, 0, sizeof(CHAdapter)); + + pNew->pDes = CreateDescriptor("ChopperAdapter"); + pNew->pDriv = CHGetDriver(pChopper); + pNew->pInt = CreateDrivableInterface(); + pNew->pParName = strdup(argv[3]); + if (!pNew->pDes || !pNew->pDriv || !pNew->pInt || !pNew->pParName) { + SCWrite(pCon, "ERROR: out of memory in ChopperAdapter", eError); + return 0; + } + + /* initialize other fields */ + pNew->fTarget = 0.; + pNew->fLower = (float) dLower; + pNew->fUpper = (float) dUpper; + pNew->pDes->GetInterface = AdapterGetInterface; + pNew->pInt->Halt = CHHalt; + pNew->pInt->CheckLimits = CHLimits; + pNew->pInt->SetValue = CHSetValue; + pNew->pInt->CheckStatus = CHStatus; + pNew->pInt->GetValue = CHGetValue; + + /* install command */ + iRet = AddCommand(pSics, argv[1], CHAdapterAction, KillAdapter, pNew); + if (!iRet) { + sprintf(pBueffel, + "ERROR: duplicate ChopperAdapter command %s NOT created", + argv[1]); + SCWrite(pCon, pBueffel, eError); + KillAdapter(pNew); + return 0; + } + return 1; +} + /*------------------------------------------------------------------------*/ - int CHAdapterAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pCHAdapter self = NULL; - int iRet; - char pBueffel[132]; - float fValue; +int CHAdapterAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pCHAdapter self = NULL; + int iRet; + char pBueffel[132]; + float fValue; - self = (pCHAdapter)pData; - assert(self); + self = (pCHAdapter) pData; + assert(self); - /* only action: get value */ - fValue = CHGetValue(self,pCon); - if(fValue < -99000) - { - return 0; - } - else - { - sprintf(pBueffel,"%s = %f",argv[0],fValue); - SCWrite(pCon,pBueffel,eValue); - } - - return 1; + /* only action: get value */ + fValue = CHGetValue(self, pCon); + if (fValue < -99000) { + return 0; + } else { + sprintf(pBueffel, "%s = %f", argv[0], fValue); + SCWrite(pCon, pBueffel, eValue); } + + return 1; +} + /*========================================================================= An environment driver based on top of a controller object. -------------------------------------------------------------------------*/ - static int AVEVSetValue(pEVDriver self, float fNew) - { - pCHev myData; +static int AVEVSetValue(pEVDriver self, float fNew) +{ + pCHev myData; - assert(self); - myData = (pCHev)self->pPrivate; - assert(myData); - myData->iLastError = 0; + assert(self); + myData = (pCHev) self->pPrivate; + assert(myData); + myData->iLastError = 0; + + return myData->pDriv->SetPar(myData->pDriv, myData->pParName, fNew); +} - return myData->pDriv->SetPar(myData->pDriv,myData->pParName,fNew); - } /*-----------------------------------------------------------------------*/ - static int AVEVGetValue(pEVDriver self, float *fNew) - { - pCHev myData; - int iRet; - char pBueffel[80]; +static int AVEVGetValue(pEVDriver self, float *fNew) +{ + pCHev myData; + int iRet; + char pBueffel[80]; - assert(self); - myData = (pCHev)self->pPrivate; - assert(myData); + assert(self); + myData = (pCHev) self->pPrivate; + assert(myData); + + iRet = myData->pDriv->GetPar(myData->pDriv, myData->pParName, + pBueffel, 79); + sscanf(pBueffel, "%f", fNew); + return iRet; +} - iRet = myData->pDriv->GetPar(myData->pDriv,myData->pParName, - pBueffel,79); - sscanf(pBueffel,"%f",fNew); - return iRet; - } /*-----------------------------------------------------------------------*/ - static int AVEVSend(pEVDriver self, char *pCommand, - char *pReply, int iLen) - { - pCHev myData; +static int AVEVSend(pEVDriver self, char *pCommand, char *pReply, int iLen) +{ + pCHev myData; - assert(self); - myData = (pCHev)self->pPrivate; - assert(myData); - myData->iLastError = NOTIMPLEMENTED; + assert(self); + myData = (pCHev) self->pPrivate; + assert(myData); + myData->iLastError = NOTIMPLEMENTED; + + return 0; +} - return 0; - } /*-----------------------------------------------------------------------*/ - static int AVEVGetError(pEVDriver self, int *iCode, - char *pReply, int iLen) - { - pCHev myData; +static int AVEVGetError(pEVDriver self, int *iCode, char *pReply, int iLen) +{ + pCHev myData; - assert(self); - myData = (pCHev)self->pPrivate; - assert(myData); + assert(self); + myData = (pCHev) self->pPrivate; + assert(myData); + + if (myData->iLastError == NOTIMPLEMENTED) { + strncpy(pReply, "ERROR: Not Implemented here!", iLen); + *iCode = NOTIMPLEMENTED; + myData->iLastError = 0; + return 1; + } else { + return myData->pDriv->GetError(myData->pDriv, iCode, pReply, iLen); + } +} - if(myData->iLastError == NOTIMPLEMENTED) - { - strncpy(pReply,"ERROR: Not Implemented here!", iLen); - *iCode = NOTIMPLEMENTED; - myData->iLastError = 0; - return 1; - } - else - { - return myData->pDriv->GetError(myData->pDriv, iCode, - pReply, iLen); - } - } /*------------------------------------------------------------------------*/ - static int AVEVTryFixIt(pEVDriver self, int iCode) - { - pCHev myData; +static int AVEVTryFixIt(pEVDriver self, int iCode) +{ + pCHev myData; - assert(self); - myData = (pCHev)self->pPrivate; - assert(myData); + assert(self); + myData = (pCHev) self->pPrivate; + assert(myData); + + if (iCode == NOTIMPLEMENTED) { + return DEVFAULT; + } else { + return myData->pDriv->TryFixIt(myData->pDriv, iCode); + } +} - if(iCode == NOTIMPLEMENTED) - { - return DEVFAULT; - } - else - { - return myData->pDriv->TryFixIt(myData->pDriv, iCode); - } - } /*---------------------------------------------------------------------*/ - static int AVEVInit(pEVDriver self) - { - pCHev myData; +static int AVEVInit(pEVDriver self) +{ + pCHev myData; - assert(self); - myData = (pCHev)self->pPrivate; - assert(myData); + assert(self); + myData = (pCHev) self->pPrivate; + assert(myData); + + return myData->pDriv->Init(myData->pDriv); +} - return myData->pDriv->Init(myData->pDriv); - } /*---------------------------------------------------------------------*/ - static int AVEVClose(pEVDriver self) - { - pCHev myData; +static int AVEVClose(pEVDriver self) +{ + pCHev myData; - assert(self); - myData = (pCHev)self->pPrivate; - assert(myData); + assert(self); + myData = (pCHev) self->pPrivate; + assert(myData); + + return myData->pDriv->Close(myData->pDriv); +} - return myData->pDriv->Close(myData->pDriv); - } /*----------------------------------------------------------------------*/ - static void AVEVKillPrivate(void *pData) - { - pCHev myData; +static void AVEVKillPrivate(void *pData) +{ + pCHev myData; + + if (pData != NULL) { + myData = (pCHev) pData; + if (myData != NULL) { + if (myData->pParName) + free(myData->pParName); + free(myData); + } + } +} - if(pData != NULL) - { - myData = (pCHev)pData; - if(myData != NULL) - { - if(myData->pParName) - free(myData->pParName); - free(myData); - } - } - } /*---------------------------------------------------------------------*/ - pEVDriver MakeControllerEnvironmentDriver(int argc, char *argv[]) - { - pEVDriver pNew = NULL; - pCHev myData = NULL; - CommandList *pCom = NULL; - pDummy pDum = NULL; - pChoco pChop; - - /* - Two arguments are needed: the name of the controller and the - name of the parameter - */ - if(argc < 2) - { - return NULL; - } - pCom = FindCommand(pServ->pSics,argv[0]); - if(!pCom) - { - return NULL; - } - pDum = pCom->pData; - if(!pDum) - { - return NULL; - } - if(strcmp(pDum->pDescriptor->name,"Chopper") != 0) - { - return NULL; - } - - /* alright: I think we got a controller now, let us create our - act - */ - pNew = CreateEVDriver(argc,argv); - if(!pNew) - { - return NULL; - } - myData = (pCHev)malloc(sizeof(CHev)); - if(!myData) - { - return NULL; - } - - pChop = (pChoco)pCom->pData; - myData->iLastError = 0; - myData->pDriv = pChop->pDriv; - myData->pParName = strdup(argv[1]); - pNew->pPrivate = myData; - pNew->SetValue =AVEVSetValue; - pNew->GetValue =AVEVGetValue; - pNew->Send = AVEVSend; - pNew->GetError =AVEVGetError; - pNew->TryFixIt =AVEVTryFixIt; - pNew->Init =AVEVInit; - pNew->Close =AVEVClose; - pNew->KillPrivate =AVEVKillPrivate; - - return pNew; - } - - - +pEVDriver MakeControllerEnvironmentDriver(int argc, char *argv[]) +{ + pEVDriver pNew = NULL; + pCHev myData = NULL; + CommandList *pCom = NULL; + pDummy pDum = NULL; + pChoco pChop; + /* + Two arguments are needed: the name of the controller and the + name of the parameter + */ + if (argc < 2) { + return NULL; + } + pCom = FindCommand(pServ->pSics, argv[0]); + if (!pCom) { + return NULL; + } + pDum = pCom->pData; + if (!pDum) { + return NULL; + } + if (strcmp(pDum->pDescriptor->name, "Chopper") != 0) { + return NULL; + } + /* alright: I think we got a controller now, let us create our + act + */ + pNew = CreateEVDriver(argc, argv); + if (!pNew) { + return NULL; + } + myData = (pCHev) malloc(sizeof(CHev)); + if (!myData) { + return NULL; + } + pChop = (pChoco) pCom->pData; + myData->iLastError = 0; + myData->pDriv = pChop->pDriv; + myData->pParName = strdup(argv[1]); + pNew->pPrivate = myData; + pNew->SetValue = AVEVSetValue; + pNew->GetValue = AVEVGetValue; + pNew->Send = AVEVSend; + pNew->GetError = AVEVGetError; + pNew->TryFixIt = AVEVTryFixIt; + pNew->Init = AVEVInit; + pNew->Close = AVEVClose; + pNew->KillPrivate = AVEVKillPrivate; + return pNew; +} diff --git a/chadapter.h b/chadapter.h index ec3319f8..83cd822a 100644 --- a/chadapter.h +++ b/chadapter.h @@ -11,37 +11,35 @@ #define SICSCHADA #include "codri.h" - typedef struct __CHADAPTER *pCHAdapter; +typedef struct __CHADAPTER *pCHAdapter; /*-----------------------------------------------------------------------*/ - int CHAdapterFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]); - - int CHAdapterAction(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]); +int CHAdapterFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + +int CHAdapterAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + +pEVDriver MakeControllerEnvironmentDriver(int argc, char *argv[]); - pEVDriver MakeControllerEnvironmentDriver(int argc, char *argv[]); - #ifdef CHADAINTERNAL - typedef struct __CHADAPTER { - pObjectDescriptor pDes; - pCodri pDriv; - pIDrivable pInt; - float fUpper; - float fLower; - float fTarget; - char *pParName; - }CHAdapter; +typedef struct __CHADAPTER { + pObjectDescriptor pDes; + pCodri pDriv; + pIDrivable pInt; + float fUpper; + float fLower; + float fTarget; + char *pParName; +} CHAdapter; - typedef struct __CHEV { - char *pParName; - pCodri pDriv; - int iLastError; - }CHev, *pCHev; +typedef struct __CHEV { + char *pParName; + pCodri pDriv; + int iLastError; +} CHev, *pCHev; #endif #endif diff --git a/choco.c b/choco.c index 65ca8d01..6007e2fa 100644 --- a/choco.c +++ b/choco.c @@ -17,234 +17,209 @@ #include "choco.h" - + /*------------------------------------------------------------------------*/ - int CHGetParameter(pChoco self, char *parname, char *pParValue, - int iBuflen) - { - int iRet, iCode; +int CHGetParameter(pChoco self, char *parname, char *pParValue, + int iBuflen) +{ + int iRet, iCode; - assert(self); + assert(self); - iRet = self->pDriv->GetPar(self->pDriv, parname, pParValue, - iBuflen); - if(!iRet) - { - iRet = 0; - self->pDriv->GetError(self->pDriv,&iCode,pParValue, iBuflen); - } - return iRet; + iRet = self->pDriv->GetPar(self->pDriv, parname, pParValue, iBuflen); + if (!iRet) { + iRet = 0; + self->pDriv->GetError(self->pDriv, &iCode, pParValue, iBuflen); } + return iRet; +} + /*------------------------------------------------------------------------*/ - pCodri CHGetDriver(pChoco self) - { - assert(self); - - return self->pDriv; +pCodri CHGetDriver(pChoco self) +{ + assert(self); + + return self->pDriv; +} + +/*------------------------------------------------------------------------*/ +int CHList(pChoco self, SConnection * pCon, char *name) +{ + char *pPar, *pCopy = NULL; + char pValue[80]; + char pMessage[256]; + int iRet, iLen; + Tcl_DString tlist; + + assert(self); + + /* copy pParList as it will be destroyed by strtok */ + iLen = strlen(self->pDriv->pParList); + pCopy = (char *) malloc((iLen + 10) * sizeof(char)); + if (!pCopy) { + SCWrite(pCon, "ERROR: out of memory in CHList", eError); + return 0; } -/*------------------------------------------------------------------------*/ - int CHList(pChoco self, SConnection *pCon, char *name) - { - char *pPar, *pCopy = NULL; - char pValue[80]; - char pMessage[256]; - int iRet, iLen; - Tcl_DString tlist; + memset(pCopy, 0, iLen + 10); + strcpy(pCopy, self->pDriv->pParList); + Tcl_DStringInit(&tlist); - assert(self); - - /* copy pParList as it will be destroyed by strtok */ - iLen = strlen(self->pDriv->pParList); - pCopy = (char *)malloc((iLen+10)*sizeof(char)); - if(!pCopy) - { - SCWrite(pCon,"ERROR: out of memory in CHList",eError); - return 0; + pPar = strtok(pCopy, ","); + while (pPar != NULL) { + iRet = CHGetParameter(self, pPar, pValue, 79); + if (iRet) { + sprintf(pMessage, "%s.%s = %s \n", name, pPar, pValue); + } else { + sprintf(pMessage, "ERROR: %s : while reading parameter %s \n", + pValue, pPar); } - memset(pCopy,0,iLen+10); - strcpy(pCopy,self->pDriv->pParList); - Tcl_DStringInit(&tlist); - - pPar = strtok(pCopy,","); - while(pPar != NULL) - { - iRet = CHGetParameter(self,pPar,pValue,79); - if(iRet) - { - sprintf(pMessage,"%s.%s = %s \n",name,pPar,pValue); - } - else - { - sprintf(pMessage,"ERROR: %s : while reading parameter %s \n", - pValue,pPar); - } - Tcl_DStringAppend(&tlist, pMessage,-1); - pPar = strtok(NULL,","); - } - SCWrite(pCon,Tcl_DStringValue(&tlist),eValue); - Tcl_DStringFree(&tlist); - free(pCopy); - return 1; + Tcl_DStringAppend(&tlist, pMessage, -1); + pPar = strtok(NULL, ","); } + SCWrite(pCon, Tcl_DStringValue(&tlist), eValue); + Tcl_DStringFree(&tlist); + free(pCopy); + return 1; +} + /*-----------------------------------------------------------------------*/ - int ChocoAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pChoco self = NULL; - char pValue[80], pMessage[256]; - int iRet; +int ChocoAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pChoco self = NULL; + char pValue[80], pMessage[256]; + int iRet; - self = (pChoco)pData; - assert(self); + self = (pChoco) pData; + assert(self); - if(argc < 2) - { - sprintf(pMessage, "ERROR: argument required for %s",argv[0]); - SCWrite(pCon,pMessage,eError); - return 0; - } - - /* argument can either be list or parameter name */ - strtolower(argv[1]); - if(strcmp(argv[1],"list") == 0) - { - return CHList(self,pCon,argv[0]); - } - else - { - if(argc > 2) - { - /* set case */ - iRet = self->pDriv->SetPar2(self->pDriv,argv[1],argv[2]); - if(!iRet) - { - self->pDriv->GetError(self->pDriv,&iRet,pValue,79); - sprintf(pMessage,"ERROR: %s",pValue); - SCWrite(pCon,pMessage,eError); - return 0; - } - else - { - SCSendOK(pCon); - return 1; - } - } - else - { - /* get case */ - iRet = CHGetParameter(self,argv[1],pValue,79); - if(iRet) - { - sprintf(pMessage,"%s.%s = %s",argv[0],argv[1],pValue); - } - else - { - sprintf(pMessage,"ERROR: %s : while reading parameter %s", - pValue,argv[1]); - } - SCWrite(pCon,pMessage,eValue); - return iRet; - } - } - return 0; + if (argc < 2) { + sprintf(pMessage, "ERROR: argument required for %s", argv[0]); + SCWrite(pCon, pMessage, eError); + return 0; } + + /* argument can either be list or parameter name */ + strtolower(argv[1]); + if (strcmp(argv[1], "list") == 0) { + return CHList(self, pCon, argv[0]); + } else { + if (argc > 2) { + /* set case */ + iRet = self->pDriv->SetPar2(self->pDriv, argv[1], argv[2]); + if (!iRet) { + self->pDriv->GetError(self->pDriv, &iRet, pValue, 79); + sprintf(pMessage, "ERROR: %s", pValue); + SCWrite(pCon, pMessage, eError); + return 0; + } else { + SCSendOK(pCon); + return 1; + } + } else { + /* get case */ + iRet = CHGetParameter(self, argv[1], pValue, 79); + if (iRet) { + sprintf(pMessage, "%s.%s = %s", argv[0], argv[1], pValue); + } else { + sprintf(pMessage, "ERROR: %s : while reading parameter %s", + pValue, argv[1]); + } + SCWrite(pCon, pMessage, eValue); + return iRet; + } + } + return 0; +} + /*----------------------------------------------------------------------*/ - void KillChoco(void *pData) - { - pChoco self = NULL; +void KillChoco(void *pData) +{ + pChoco self = NULL; - self = (pChoco)pData; - if(!self) - return; + self = (pChoco) pData; + if (!self) + return; - if(self->pDriv) - { - self->pDriv->Close(self->pDriv); - self->pDriv->Delete(self->pDriv); - free(self->pDriv); - } - if(self->pDes) - DeleteDescriptor(self->pDes); - - free(self); + if (self->pDriv) { + self->pDriv->Close(self->pDriv); + self->pDriv->Delete(self->pDriv); + free(self->pDriv); } + if (self->pDes) + DeleteDescriptor(self->pDes); + + free(self); +} + /*----------------------------------------------------------------------- DRIVERS */ extern pCodri MakeSimChopper(void); /*-----------------------------------------------------------------------*/ - int ChocoFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pChoco pNew = NULL; - pCodri pDriv = NULL; - pObjectDescriptor pDes = NULL; - char pBueffel[132]; - int iRet, iPort, iChannel; - int iSingle = 0; - pSite site = NULL; +int ChocoFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pChoco pNew = NULL; + pCodri pDriv = NULL; + pObjectDescriptor pDes = NULL; + char pBueffel[132]; + int iRet, iPort, iChannel; + int iSingle = 0; + pSite site = NULL; - if(argc < 3) - { - SCWrite(pCon, + if (argc < 3) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to MakeController", - eError); - return 0; - } - - - /* first try to get everything done */ - pNew = (pChoco)malloc(sizeof(Choco)); - pDes = CreateDescriptor("Chopper"); - /* do driver */ - strtolower(argv[2]); - if(strcmp(argv[2],"sim") == 0) - { - pDriv = MakeSimChopper(); - } - else - { - site = getSite(); - if(site != NULL){ - pDriv = site->CreateControllerDriver(pCon,argc-2,&argv[2]); - } else { - pDriv = NULL; - } - if(pDriv == NULL){ - sprintf(pBueffel,"ERROR: Driver %s NOT supported for MakeController", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - if( (pNew == NULL) || (pDes == NULL) || (pDriv == NULL) ) - { - SCWrite(pCon,"ERROR: No memory left to create controller",eError); - return 0; - } - pNew->pDes = pDes; - pNew->pDriv = pDriv; - - /* initialize driver */ - iRet = pDriv->Init(pDriv); - if(!iRet) - { - SCWrite(pCon,"ERROR: Failed to initialize driver",eError); - KillChoco(pNew); - return 0; - } - - /* install as command */ - iRet = AddCommand(pSics, argv[1],ChocoAction,KillChoco,pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s NOT created", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; + eError); + return 0; } + /* first try to get everything done */ + pNew = (pChoco) malloc(sizeof(Choco)); + pDes = CreateDescriptor("Chopper"); + /* do driver */ + strtolower(argv[2]); + if (strcmp(argv[2], "sim") == 0) { + pDriv = MakeSimChopper(); + } else { + site = getSite(); + if (site != NULL) { + pDriv = site->CreateControllerDriver(pCon, argc - 2, &argv[2]); + } else { + pDriv = NULL; + } + if (pDriv == NULL) { + sprintf(pBueffel, + "ERROR: Driver %s NOT supported for MakeController", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + if ((pNew == NULL) || (pDes == NULL) || (pDriv == NULL)) { + SCWrite(pCon, "ERROR: No memory left to create controller", eError); + return 0; + } + pNew->pDes = pDes; + pNew->pDriv = pDriv; + + /* initialize driver */ + iRet = pDriv->Init(pDriv); + if (!iRet) { + SCWrite(pCon, "ERROR: Failed to initialize driver", eError); + KillChoco(pNew); + return 0; + } + + /* install as command */ + iRet = AddCommand(pSics, argv[1], ChocoAction, KillChoco, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s NOT created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} diff --git a/choco.h b/choco.h index 94bbe7e2..3a9eff7a 100644 --- a/choco.h +++ b/choco.h @@ -11,27 +11,27 @@ #define CHOCOSICS #include "codri.h" - typedef struct __CHOCO *pChoco; +typedef struct __CHOCO *pChoco; /*------------------------------------------------------------------------*/ - int CHGetParameter(pChoco self, char *pParName, - char *pParValue, int iBuflen); - - pCodri CHGetDriver(pChoco self); - int CHList(pChoco self, SConnection *pCon, char *name); +int CHGetParameter(pChoco self, char *pParName, + char *pParValue, int iBuflen); + +pCodri CHGetDriver(pChoco self); +int CHList(pChoco self, SConnection * pCon, char *name); /*------------------------------------------------------------------------*/ - void KillChoco(void *pData); - int ChocoAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int ChocoFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +void KillChoco(void *pData); +int ChocoAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int ChocoFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + #ifdef CHOCOINTERNAL - typedef struct __CHOCO { - pObjectDescriptor pDes; - pCodri pDriv; - } Choco; +typedef struct __CHOCO { + pObjectDescriptor pDes; + pCodri pDriv; +} Choco; #endif -#endif +#endif diff --git a/circular.c b/circular.c index 5a855a66..13597967 100644 --- a/circular.c +++ b/circular.c @@ -12,111 +12,111 @@ Definitions of Structures */ - typedef struct __CircularItem { - void *pData; - struct __CircularItem *next; - struct __CircularItem *previous; - }CircularItem, *pCircularItem; +typedef struct __CircularItem { + void *pData; + struct __CircularItem *next; + struct __CircularItem *previous; +} CircularItem, *pCircularItem; - typedef struct __CIRCULAR { - pCircularItem pPointer; - CirKillFunc killer; - }Circular; +typedef struct __CIRCULAR { + pCircularItem pPointer; + CirKillFunc killer; +} Circular; /*========================================================================= Functions for Birth and Death */ - pCircular createCircular(int iSize, CirKillFunc kf) - { - pCircular pNew = NULL; - pCircularItem pItem = NULL, pFirst = NULL; - int i; - - - assert(iSize > 0); +pCircular createCircular(int iSize, CirKillFunc kf) +{ + pCircular pNew = NULL; + pCircularItem pItem = NULL, pFirst = NULL; + int i; - /* create data structure */ - pNew = (pCircular)malloc(sizeof(Circular)); - if(!pNew) - return NULL; - memset(pNew,0,sizeof(Circular)); - /* create all the members of the circular buffer */ - pItem = (pCircularItem)malloc(sizeof(CircularItem)); - if(!pItem) - return NULL; - memset(pItem,0,sizeof(CircularItem)); - pNew->pPointer = pItem; - pFirst = pItem; - for(i = 1; i < iSize; i++) - { - pItem = (pCircularItem)malloc(sizeof(CircularItem)); - if(!pItem) - return NULL; - memset(pItem,0,sizeof(CircularItem)); - pItem->previous = pNew->pPointer; - pNew->pPointer->next = pItem; - pNew->pPointer = pItem; - } - pItem->next = pFirst; - pFirst->previous = pItem; - pNew->killer = kf; - return pNew; + assert(iSize > 0); + + /* create data structure */ + pNew = (pCircular) malloc(sizeof(Circular)); + if (!pNew) + return NULL; + memset(pNew, 0, sizeof(Circular)); + + /* create all the members of the circular buffer */ + pItem = (pCircularItem) malloc(sizeof(CircularItem)); + if (!pItem) + return NULL; + memset(pItem, 0, sizeof(CircularItem)); + pNew->pPointer = pItem; + pFirst = pItem; + for (i = 1; i < iSize; i++) { + pItem = (pCircularItem) malloc(sizeof(CircularItem)); + if (!pItem) + return NULL; + memset(pItem, 0, sizeof(CircularItem)); + pItem->previous = pNew->pPointer; + pNew->pPointer->next = pItem; + pNew->pPointer = pItem; } + pItem->next = pFirst; + pFirst->previous = pItem; + pNew->killer = kf; + return pNew; +} + /*---------------------------------------------------------------------*/ - void deleteCircular(pCircular self) - { - pCircularItem pNext = NULL, pCurrent = NULL; +void deleteCircular(pCircular self) +{ + pCircularItem pNext = NULL, pCurrent = NULL; - assert(self); + assert(self); + + self->pPointer->previous->next = NULL; + pNext = self->pPointer; + while (pNext != NULL) { + pCurrent = pNext; + pNext = pCurrent->next; + if (pCurrent->pData && self->killer) { + self->killer(pCurrent->pData); + } + free(pCurrent); + } + free(self); +} - self->pPointer->previous->next = NULL; - pNext = self->pPointer; - while(pNext != NULL) - { - pCurrent = pNext; - pNext = pCurrent->next; - if(pCurrent->pData && self->killer) - { - self->killer(pCurrent->pData); - } - free(pCurrent); - } - free(self); - } /*======================================================================== Data Manipulation functions */ - void setCircular(pCircular self, void *pData) - { - assert(self); +void setCircular(pCircular self, void *pData) +{ + assert(self); - /* delete if present */ - if(self->pPointer->pData && self->killer) - { - self->killer(self->pPointer->pData); - } - self->pPointer->pData = pData; + /* delete if present */ + if (self->pPointer->pData && self->killer) { + self->killer(self->pPointer->pData); } + self->pPointer->pData = pData; +} + /*----------------------------------------------------------------------*/ - void *getCircular(pCircular self) - { - assert(self); - return self->pPointer->pData; - } +void *getCircular(pCircular self) +{ + assert(self); + return self->pPointer->pData; +} + /*======================================================================== Pointer movement */ - void nextCircular(pCircular self) - { - assert(self); - self->pPointer = self->pPointer->next; - } -/*---------------------------------------------------------------------*/ - void previousCircular(pCircular self) - { - assert(self); - self->pPointer = self->pPointer->previous; - } +void nextCircular(pCircular self) +{ + assert(self); + self->pPointer = self->pPointer->next; +} +/*---------------------------------------------------------------------*/ +void previousCircular(pCircular self) +{ + assert(self); + self->pPointer = self->pPointer->previous; +} diff --git a/circular.h b/circular.h index b4bdac3b..5edd7b73 100644 --- a/circular.h +++ b/circular.h @@ -8,24 +8,24 @@ #ifndef CIRCULAR #define CIRCULAR - typedef struct __CIRCULAR *pCircular; - typedef void (*CirKillFunc)(void *pData); +typedef struct __CIRCULAR *pCircular; +typedef void (*CirKillFunc) (void *pData); /* ----------------- birth and death -----------------------------------*/ - pCircular createCircular(int iSize,CirKillFunc kf); +pCircular createCircular(int iSize, CirKillFunc kf); /* - iSize is the size of the circular Buffer. - KillFunc is a function which can safely delete the data item held - as content of the circular buffer. - */ - void deleteCircular(pCircular self); + iSize is the size of the circular Buffer. + KillFunc is a function which can safely delete the data item held + as content of the circular buffer. + */ +void deleteCircular(pCircular self); /*-------------- access and modify data item at current position ----------*/ - void setCircular(pCircular self, void *pData); - void *getCircular(pCircular self); +void setCircular(pCircular self, void *pData); +void *getCircular(pCircular self); /*---------------- pointer movement --------------------------------------*/ - void nextCircular(pCircular self); - void previousCircular(pCircular self); +void nextCircular(pCircular self); +void previousCircular(pCircular self); #endif diff --git a/codri.h b/codri.h index a44f1e0e..991efb95 100644 --- a/codri.h +++ b/codri.h @@ -13,32 +13,21 @@ #define CHREDO -2 #define CHOK -3 - typedef struct __CODRI *pCodri; - typedef struct __CODRI { - int (*Init)(pCodri self); - int (*Close)(pCodri self); - int (*Delete)(pCodri self); - int (*SetPar)(pCodri self, - char *parname, - float fValue); - int (*SetPar2)(pCodri self, - char *parname, - char *value); - int (*GetPar)(pCodri self, - char *parname, - char *pBuffer, - int iBufLen); - int (*CheckPar)(pCodri self, - char *parname); - int (*GetError)(pCodri self, int *iCode, - char *pError, - int iErrLen); - int (*TryFixIt)(pCodri self, int iCode); - int (*Halt)(pCodri self); - char *pParList; - void *pPrivate; - }Codri; - +typedef struct __CODRI *pCodri; +typedef struct __CODRI { + int (*Init) (pCodri self); + int (*Close) (pCodri self); + int (*Delete) (pCodri self); + int (*SetPar) (pCodri self, char *parname, float fValue); + int (*SetPar2) (pCodri self, char *parname, char *value); + int (*GetPar) (pCodri self, char *parname, char *pBuffer, int iBufLen); + int (*CheckPar) (pCodri self, char *parname); + int (*GetError) (pCodri self, int *iCode, char *pError, int iErrLen); + int (*TryFixIt) (pCodri self, int iCode); + int (*Halt) (pCodri self); + char *pParList; + void *pPrivate; +} Codri; + #endif - diff --git a/comentry.h b/comentry.h index 1aebd28a..40beb9cc 100644 --- a/comentry.h +++ b/comentry.h @@ -8,47 +8,46 @@ ---------------------------------------------------------------------------*/ #ifndef COMENTRY #define COMENTRY - + #define MAXDEV 10 - typedef struct { - void *pData; - char name[80]; - pObjectDescriptor pDescriptor; - float fVal; - int iCount; - } DevEntry; - +typedef struct { + void *pData; + char name[80]; + pObjectDescriptor pDescriptor; + float fVal; + int iCount; +} DevEntry; + /* -------------------The Entry per registered command --------------------*/ - typedef struct __ComEntry { - char name[10]; - char *pCommand; - int iDevice; - DevEntry pDevice[MAXDEV]; - struct __ComEntry *pNext; - struct __ComEntry *pPrevious; - }ComEntry, *pComEntry; +typedef struct __ComEntry { + char name[10]; + char *pCommand; + int iDevice; + DevEntry pDevice[MAXDEV]; + struct __ComEntry *pNext; + struct __ComEntry *pPrevious; +} ComEntry, *pComEntry; - typedef struct __NAMPOS { - char *name; /* the name */ - pComEntry pCom; /* the positions */ - char *text; /* explanatory text */ - struct __NAMPOS *pNext; - struct __NAMPOS *pPrevious; - } NamPos, *pNamPos; +typedef struct __NAMPOS { + char *name; /* the name */ + pComEntry pCom; /* the positions */ + char *text; /* explanatory text */ + struct __NAMPOS *pNext; + struct __NAMPOS *pPrevious; +} NamPos, *pNamPos; - typedef struct __NAMMAP { - char *alias; - char *motname; - pMotor pMot; - } NamMap, *pNamMap; - - int CheckComEntryBounds(pComEntry self, SConnection *pCon); - int AddExeEntry(pExeList self, pComEntry pNew, SConnection *pCon); - pComEntry CreateComEntry(void); - pComEntry CopyComEntry(pComEntry pOld); - int AddDevEntry(pComEntry pCom, char *name, void *pData, pObjectDescriptor pDes, - float fVal); - pNamPos LinkNamPos(pNamPos pHead, pNamPos pNew); - pNamPos UnlinkNamPos(pNamPos pHead, pNamPos pOld); +typedef struct __NAMMAP { + char *alias; + char *motname; + pMotor pMot; +} NamMap, *pNamMap; + +int CheckComEntryBounds(pComEntry self, SConnection * pCon); +int AddExeEntry(pExeList self, pComEntry pNew, SConnection * pCon); +pComEntry CreateComEntry(void); +pComEntry CopyComEntry(pComEntry pOld); +int AddDevEntry(pComEntry pCom, char *name, void *pData, + pObjectDescriptor pDes, float fVal); +pNamPos LinkNamPos(pNamPos pHead, pNamPos pNew); +pNamPos UnlinkNamPos(pNamPos pHead, pNamPos pOld); #endif - diff --git a/commandcontext.h b/commandcontext.h index 1a293ba9..af7eea4c 100644 --- a/commandcontext.h +++ b/commandcontext.h @@ -7,10 +7,10 @@ #ifndef SICSCOMCONTEXT #define SICSCOMCONTEXT -typedef struct{ - int transID; - char deviceID[256]; - }commandContext, *pCommandContext; +typedef struct { + int transID; + char deviceID[256]; +} commandContext, *pCommandContext; #define SCDEVIDLEN 256 #endif diff --git a/commandlog.c b/commandlog.c index 1f315529..503a2c7d 100644 --- a/commandlog.c +++ b/commandlog.c @@ -31,515 +31,476 @@ /* in conman.c */ - int TelnetWrite(mkChannel *pSock, char *pText); +int TelnetWrite(mkChannel * pSock, char *pText); /*-------------------- the command log file pointer ---------------------*/ - static FILE *fd = NULL; - static FILE *fauto = NULL; - static char pFile[256]; +static FILE *fd = NULL; +static FILE *fauto = NULL; +static char pFile[256]; /*-------------------- the tail buffer ---------------------------------*/ - static pCircular pTail = NULL; +static pCircular pTail = NULL; #define MAXTAIL 1000 #define NOID -1964 - static time_t lastStamp = 0; - static time_t iCompact = 0; - static time_t tLastWrite = 0; - char *cmdPrompt=">"; - static int lastId=NOID; - - static time_t tLogfile = 0; - static time_t tStamp = 0; - static int iEnd = 1; - static int iAutoActive = 0; - static int iIntervall = 60; +static time_t lastStamp = 0; +static time_t iCompact = 0; +static time_t tLastWrite = 0; +char *cmdPrompt = ">"; +static int lastId = NOID; + +static time_t tLogfile = 0; +static time_t tStamp = 0; +static int iEnd = 1; +static int iAutoActive = 0; +static int iIntervall = 60; /*----------------------------------------------------------------------*/ - void WriteToCommandLogId(char *prompt, int id, char *text) - { - int l, iPos; - char *pPtr = NULL, *pCopy = NULL, *strippedText = text; - struct tm *nowTm; - time_t now; - char stamp1[32], stamp2[32], buffer[80]; - int doStamp, doStampId; - - /* suppress status messages */ - if (strstr(text,"status =") != NULL) { - return; - } - - /* suppress TRANSACTIONFINISHED as well in order to make the WWW - commandlog work and TRANSACTIONSTART in order to make the logfiles - shorter - */ - if (strstr(text,"TRANSACTIONSTART") != NULL) { - return; - } - if (strstr(text,"TRANSACTIONFINISHED") != NULL) { - return; - } - - /* we make a local copy, stripping off the newline at the - end. We anyway need a copy later for the circular buffer */ - l = strlen(text); - pPtr = strrchr(text,'\n'); - if (pPtr != NULL && (pPtr[1]=='\0' || pPtr[2] == '\0')) { - l = pPtr - text; - } - pCopy = malloc(l+1); - if (pCopy == NULL) return; - strncpy(pCopy, text, l); - pCopy[l]='\0'; +void WriteToCommandLogId(char *prompt, int id, char *text) +{ + int l, iPos; + char *pPtr = NULL, *pCopy = NULL, *strippedText = text; + struct tm *nowTm; + time_t now; + char stamp1[32], stamp2[32], buffer[80]; + int doStamp, doStampId; - if (prompt == cmdPrompt && iCompact) { - pPtr = strstr(pCopy, "fulltransact "); - if (pPtr && pPtr < pCopy+3) { - strippedText = pPtr + 13; - } - pPtr = strstr(pCopy, "transact "); - if (pPtr && pPtr < pCopy+3) { - strippedText = pPtr + 9; - } - } + /* suppress status messages */ + if (strstr(text, "status =") != NULL) { + return; + } - /* create tail buffer as needed */ - if (!pTail) { - pTail = createCircular(MAXTAIL,free); - } + /* suppress TRANSACTIONFINISHED as well in order to make the WWW + commandlog work and TRANSACTIONSTART in order to make the logfiles + shorter + */ + if (strstr(text, "TRANSACTIONSTART") != NULL) { + return; + } + if (strstr(text, "TRANSACTIONFINISHED") != NULL) { + return; + } - now = time(NULL); + /* we make a local copy, stripping off the newline at the + end. We anyway need a copy later for the circular buffer */ + l = strlen(text); + pPtr = strrchr(text, '\n'); + if (pPtr != NULL && (pPtr[1] == '\0' || pPtr[2] == '\0')) { + l = pPtr - text; + } + pCopy = malloc(l + 1); + if (pCopy == NULL) + return; + strncpy(pCopy, text, l); + pCopy[l] = '\0'; - doStamp = 0; - doStampId = 0; - - if (id == NOID) { - if (!prompt) { - prompt=""; - } else { - snprintf(buffer, sizeof buffer, "%s ", prompt); - prompt = buffer; - } - } else if (iCompact == 0) { - if (!prompt) { - snprintf(buffer, sizeof buffer, "To sock %d : ", id); - } else { - snprintf(buffer, sizeof buffer, "sock %d>%s ", id, prompt); - } - prompt = buffer; - } else { - if (id != lastId) { - lastId = id; - doStampId = 1; - } - if (!prompt) { - prompt=""; - } else { - snprintf(buffer, sizeof buffer, "%s ", prompt); - prompt = buffer; - } - } - - if (iCompact > 0) { /* write time stamp */ - if (now/iCompact != lastStamp/iCompact) { - doStamp = 1; - doStampId = 1; - } - if (doStampId) { - lastStamp = now; - nowTm = localtime(&now); - strftime(stamp1, sizeof stamp1, "=== %H:%M:%S ===", nowTm); - if (id != NOID) { - snprintf(stamp2, sizeof stamp2, " socket %d ===", id); - } else { - stamp2[0] = '\0'; - } - } - } + if (prompt == cmdPrompt && iCompact) { + pPtr = strstr(pCopy, "fulltransact "); + if (pPtr && pPtr < pCopy + 3) { + strippedText = pPtr + 13; + } + pPtr = strstr(pCopy, "transact "); + if (pPtr && pPtr < pCopy + 3) { + strippedText = pPtr + 9; + } + } - /* user file */ - if (fd != NULL) { - if (doStampId) { - fprintf(fd,"%s %s\n", stamp1, stamp2); - } - fprintf(fd,"%s%s\n", prompt, pCopy); - } + /* create tail buffer as needed */ + if (!pTail) { + pTail = createCircular(MAXTAIL, free); + } - /* automatic file */ - if (fauto != NULL) { - tLastWrite = now; - if (doStampId) { - fprintf(fauto,"%s%s\n", stamp1, stamp2); - } - fprintf(fauto,"%s%s\n", prompt, strippedText); - } + now = time(NULL); - /* to all listening sockets. The check is necessary to resolve a shutdown problem */ - if (pServ->pTasker != NULL) { - if (doStamp) { - TaskSignal(pServ->pTasker,COMLOG,stamp1); - } - TaskSignal(pServ->pTasker,COMLOG,pCopy); - } + doStamp = 0; + doStampId = 0; - /* tail buffer */ - if (pTail != NULL) { - if (doStamp) { - setCircular(pTail,strdup(stamp1)); - nextCircular(pTail); - } - setCircular(pTail,pCopy); - nextCircular(pTail); - } + if (id == NOID) { + if (!prompt) { + prompt = ""; + } else { + snprintf(buffer, sizeof buffer, "%s ", prompt); + prompt = buffer; + } + } else if (iCompact == 0) { + if (!prompt) { + snprintf(buffer, sizeof buffer, "To sock %d : ", id); + } else { + snprintf(buffer, sizeof buffer, "sock %d>%s ", id, prompt); + } + prompt = buffer; + } else { + if (id != lastId) { lastId = id; - } -/*------------------------------------------------------------------------*/ - void WriteToCommandLog(char *prompt, char *text) - { - WriteToCommandLogId(prompt, NOID, text); - } -/*------------------------------------------------------------------------*/ - void WriteToCommandLogCmd(int id, char *text) - { - WriteToCommandLogId(cmdPrompt, id, text); - } -/*------------------------------------------------------------------------*/ - int CompactCommandLog(void) { - return iCompact > 0; - } -/*------------------------------------------------------------------------*/ - static void PrintTail(int iNum, SConnection *pCon) - { - char *pPtr = NULL; - int i; + doStampId = 1; + } + if (!prompt) { + prompt = ""; + } else { + snprintf(buffer, sizeof buffer, "%s ", prompt); + prompt = buffer; + } + } - if(pTail == NULL) - { - SCWrite(pCon,"Nothing to print",eError); - return; - } + if (iCompact > 0) { /* write time stamp */ + if (now / iCompact != lastStamp / iCompact) { + doStamp = 1; + doStampId = 1; + } + if (doStampId) { + lastStamp = now; + nowTm = localtime(&now); + strftime(stamp1, sizeof stamp1, "=== %H:%M:%S ===", nowTm); + if (id != NOID) { + snprintf(stamp2, sizeof stamp2, " socket %d ===", id); + } else { + stamp2[0] = '\0'; + } + } + } - /* step back */ - for(i = 0; i < iNum; i++) - { - previousCircular(pTail); - } + /* user file */ + if (fd != NULL) { + if (doStampId) { + fprintf(fd, "%s %s\n", stamp1, stamp2); + } + fprintf(fd, "%s%s\n", prompt, pCopy); + } + + /* automatic file */ + if (fauto != NULL) { + tLastWrite = now; + if (doStampId) { + fprintf(fauto, "%s%s\n", stamp1, stamp2); + } + fprintf(fauto, "%s%s\n", prompt, strippedText); + } + + /* to all listening sockets. The check is necessary to resolve a shutdown problem */ + if (pServ->pTasker != NULL) { + if (doStamp) { + TaskSignal(pServ->pTasker, COMLOG, stamp1); + } + TaskSignal(pServ->pTasker, COMLOG, pCopy); + } + + /* tail buffer */ + if (pTail != NULL) { + if (doStamp) { + setCircular(pTail, strdup(stamp1)); + nextCircular(pTail); + } + setCircular(pTail, pCopy); + nextCircular(pTail); + } + lastId = id; +} - /* now step ahead and print. I have to use a trick here: I do not - want the tail stuff to show up in log files. Thus I write it - directly to the connection socket. - */ - for(i = 0; i < iNum; i++) - { - pPtr = (char *)getCircular(pTail); - if(pCon->pSock && pPtr != NULL) - { - TelnetWrite(pCon->pSock, pPtr); - } - nextCircular(pTail); - } - } /*------------------------------------------------------------------------*/ - void CLFormatTime(char *pBuffer, int iBufLen) - { - time_t iDate; - struct tm *psTime; +void WriteToCommandLog(char *prompt, char *text) +{ + WriteToCommandLogId(prompt, NOID, text); +} + +/*------------------------------------------------------------------------*/ +void WriteToCommandLogCmd(int id, char *text) +{ + WriteToCommandLogId(cmdPrompt, id, text); +} + +/*------------------------------------------------------------------------*/ +int CompactCommandLog(void) +{ + return iCompact > 0; +} + +/*------------------------------------------------------------------------*/ +static void PrintTail(int iNum, SConnection * pCon) +{ + char *pPtr = NULL; + int i; + + if (pTail == NULL) { + SCWrite(pCon, "Nothing to print", eError); + return; + } + + /* step back */ + for (i = 0; i < iNum; i++) { + previousCircular(pTail); + } + + /* now step ahead and print. I have to use a trick here: I do not + want the tail stuff to show up in log files. Thus I write it + directly to the connection socket. + */ + for (i = 0; i < iNum; i++) { + pPtr = (char *) getCircular(pTail); + if (pCon->pSock && pPtr != NULL) { + TelnetWrite(pCon->pSock, pPtr); + } + nextCircular(pTail); + } +} + +/*------------------------------------------------------------------------*/ +void CLFormatTime(char *pBuffer, int iBufLen) +{ + time_t iDate; + struct tm *psTime; + + /* make time string */ + iDate = time(NULL); + psTime = localtime(&iDate); + memset(pBuffer, 0, iBufLen); + strftime(pBuffer, iBufLen, "%Y-%m-%d@%H-%M-%S", psTime); +} - /* make time string */ - iDate = time(NULL); - psTime = localtime(&iDate); - memset(pBuffer,0,iBufLen); - strftime(pBuffer,iBufLen,"%Y-%m-%d@%H-%M-%S",psTime); - } /*---------------------------------------------------------------------- Build an automatically generated log file name and open it. */ - static void AutoLog(void) - { - char pBueffel[1024]; - char pTime[80]; - pSicsVariable pInst = NULL; - char *pPtr = NULL; - SConnection *pIntern = NULL; +static void AutoLog(void) +{ + char pBueffel[1024]; + char pTime[80]; + pSicsVariable pInst = NULL; + char *pPtr = NULL; + SConnection *pIntern = NULL; - if(fauto) - { - fclose(fauto); - fauto = NULL; - } + if (fauto) { + fclose(fauto); + fauto = NULL; + } - /* find path */ - pPtr = IFindOption(pSICSOptions,"LogFileDir"); - if(!pPtr) - { - pPtr = strdup("~/log"); - printf("WARNING: Required SICS option LogFileDir not found"); - } + /* find path */ + pPtr = IFindOption(pSICSOptions, "LogFileDir"); + if (!pPtr) { + pPtr = strdup("~/log"); + printf("WARNING: Required SICS option LogFileDir not found"); + } - /* get time */ - CLFormatTime(pTime,79); - - /* build file name */ - sprintf(pBueffel,"%s/auto%s.log",pPtr,pTime); - - /* open file */ - fauto = fopen(pBueffel,"w"); - if(!fauto) - { - ServerWriteGlobal("ERROR: failed to open autolog file",eError); - } + /* get time */ + CLFormatTime(pTime, 79); - /* write the instrument name to it for identification */ - pInst = FindVariable(pServ->pSics,"instrument"); - if(pInst) - { - sprintf(pBueffel,"Logfile started at instrument %s at %s", - pInst->text,pTime); - WriteToCommandLog("SYS>>", pBueffel); - } + /* build file name */ + sprintf(pBueffel, "%s/auto%s.log", pPtr, pTime); + + /* open file */ + fauto = fopen(pBueffel, "w"); + if (!fauto) { + ServerWriteGlobal("ERROR: failed to open autolog file", eError); + } + + /* write the instrument name to it for identification */ + pInst = FindVariable(pServ->pSics, "instrument"); + if (pInst) { + sprintf(pBueffel, "Logfile started at instrument %s at %s", + pInst->text, pTime); + WriteToCommandLog("SYS>>", pBueffel); + } + + /* if a file to execute is configured, execute it */ + pPtr = NULL; + pPtr = IFindOption(pSICSOptions, "logstartfile"); + if (pPtr != NULL) { + pIntern = SCCreateDummyConnection(pServ->pSics); + if (!pIntern) { + return; + } + SCnoSock(pIntern); + SCSetRights(pIntern, usUser); + sprintf(pBueffel, "fileeval %s", pPtr); + InterpExecute(pServ->pSics, pIntern, pBueffel); + SCDeleteConnection(pIntern); + } +} - /* if a file to execute is configured, execute it */ - pPtr = NULL; - pPtr = IFindOption(pSICSOptions,"logstartfile"); - if(pPtr != NULL) - { - pIntern = SCCreateDummyConnection(pServ->pSics); - if(!pIntern) - { - return; - } - SCnoSock(pIntern); - SCSetRights(pIntern,usUser); - sprintf(pBueffel,"fileeval %s",pPtr); - InterpExecute(pServ->pSics,pIntern,pBueffel); - SCDeleteConnection(pIntern); - } - } /*---------------------------------------------------------------------- AutoTask puts a time stamp into the auto log file any hour and creates a new log file any 24 hours */ - static int AutoTask(void *pData) - { - time_t tNow; - char pTime[80]; - struct tm *sTime; - long julian; - unsigned yr, mo, dd; +static int AutoTask(void *pData) +{ + time_t tNow; + char pTime[80]; + struct tm *sTime; + long julian; + unsigned yr, mo, dd; - tNow = time(NULL); - if(tNow > tLogfile) - { - AutoLog(); - sTime = localtime(&tNow); - /* find next day, do so by converting to julian Date, add one - and calculate back. The (stolen) julian calculations will - take care of all the leaps and month and year etc. - */ - julian = ymd_to_scalar(sTime->tm_year+1900, sTime->tm_mon+1, - sTime->tm_mday); - julian++; - scalar_to_ymd(julian, &yr, &mo, &dd); - sTime->tm_sec = 0; - sTime->tm_min = 1; - sTime->tm_hour = 0; - sTime->tm_mday = dd; - sTime->tm_mon = mo - 1; - sTime->tm_year = yr - 1900; - tLogfile = mktime(sTime); - if(tLogfile < 0) - tLogfile = tNow + 60*60*24; + tNow = time(NULL); + if (tNow > tLogfile) { + AutoLog(); + sTime = localtime(&tNow); + /* find next day, do so by converting to julian Date, add one + and calculate back. The (stolen) julian calculations will + take care of all the leaps and month and year etc. + */ + julian = ymd_to_scalar(sTime->tm_year + 1900, sTime->tm_mon + 1, + sTime->tm_mday); + julian++; + scalar_to_ymd(julian, &yr, &mo, &dd); + sTime->tm_sec = 0; + sTime->tm_min = 1; + sTime->tm_hour = 0; + sTime->tm_mday = dd; + sTime->tm_mon = mo - 1; + sTime->tm_year = yr - 1900; + tLogfile = mktime(sTime); + if (tLogfile < 0) + tLogfile = tNow + 60 * 60 * 24; + } + if (tNow > tStamp && iIntervall > 0) { + CLFormatTime(pTime, 79); + WriteToCommandLog("TIMESTAMP>> ", pTime); + sTime = localtime(&tNow); + sTime->tm_sec = 0; + sTime->tm_min += iIntervall; + if (sTime->tm_min >= 60) { + sTime->tm_min = 0; + sTime->tm_hour++; + } + if (sTime->tm_hour >= 24) + sTime->tm_hour = 0; + tStamp = mktime(sTime); + if ((tStamp < 0) || ((tStamp - tNow) < 100)) { + tStamp = tNow + iIntervall * 60; + } + if (fauto) + fflush(fauto); + } + + if (fauto && tLastWrite > 0 && tNow > tLastWrite) { + fflush(fauto); + tLastWrite = 0; + } + return iEnd; +} + +/*----------- a command to configure the log --------------------------*/ +int CommandLog(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char *pPtr = NULL; + char pBueffel[1024]; + int iVal, iRet; + + if (argc == 1) { + if (fd) { + sprintf(pBueffel, "Command log ACTIVE at %s", pFile); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + SCWrite(pCon, "Command logging DISABLED", eValue); + return 1; + } + } + + /* handle tail */ + strtolower(argv[1]); + if (strcmp(argv[1], "tail") == 0) { + /* check for optional number of lines argument */ + iVal = 20; + if (argc >= 3) { + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iVal); + if (iRet != TCL_OK) + iVal = 20; + } + PrintTail(iVal, pCon); + return 1; + } + + /* check rights */ + if (!SCMatchRights(pCon, usMugger)) { + SCWrite(pCon, "ERROR: only managers may configure the logfile", + eError); + SCWrite(pCon, "ERROR: Request refused", eError); + return 0; + } + + /* check no of args */ + if (argc < 2) { + SCWrite(pCon, + "ERROR: Insufficient number or arguments to commandlog", + eError); + return 0; + } + + if (strcmp(argv[1], "new") == 0) { /* new command */ + if (argc < 3) { + SCWrite(pCon, + "ERROR: Insufficient number or arguments to commandlog new", + eError); + return 0; + } + if (fd) { + fclose(fd); + fd = NULL; + } + /* make the filename */ + pPtr = IFindOption(pSICSOptions, "LogFileDir"); + if (!pPtr) { + SCWrite(pCon, "WARNING: no log file directory specified", eWarning); + sprintf(pBueffel, "%s", argv[2]); + + } else { + sprintf(pBueffel, "%s/%s", pPtr, argv[2]); + } + fd = fopen(pBueffel, "w"); + if (!fd) { + sprintf(pBueffel, "ERROR: cannot open %s/%s for writing", pPtr, + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + strcpy(pFile, argv[2]); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "auto") == 0) { + if (iAutoActive) { + SCWrite(pCon, "ERROR: autologging is already active", eError); + return 0; + } + TaskRegister(pServ->pTasker, AutoTask, NULL, NULL, NULL, 1); + SCSendOK(pCon); + iAutoActive = 1; + return 1; + } else if (strcmp(argv[1], "intervall") == 0) { + if (argc > 2) { + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iVal); + if (iRet != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert new intervall to number", + eError); + return 0; } - if(tNow > tStamp && iIntervall > 0) - { - CLFormatTime(pTime,79); - WriteToCommandLog("TIMESTAMP>> ",pTime); - sTime = localtime(&tNow); - sTime->tm_sec = 0; - sTime->tm_min += iIntervall; - if(sTime->tm_min >= 60) - { - sTime->tm_min = 0; - sTime->tm_hour++; - } - if(sTime->tm_hour >= 24) - sTime->tm_hour = 0; - tStamp = mktime(sTime); - if((tStamp < 0) || ( (tStamp-tNow) < 100) ) - { - tStamp = tNow + iIntervall*60; - } - if(fauto) - fflush(fauto); - } + iIntervall = iVal; + } + SCPrintf(pCon, eValue, "%s.intervall [min] = %d", argv[0], iIntervall); + return 1; + } else if (strcmp(argv[1], "compact") == 0) { + if (argc > 2) { + iCompact = atoi(argv[2]); + if (iCompact > 0) + iIntervall = 0; + } + SCPrintf(pCon, eValue, "%s.compact [sec] = %d", argv[0], iCompact); + return 1; + } else if (strcmp(argv[1], "close") == 0) { /* close command */ + fclose(fd); + fd = NULL; + SCSendOK(pCon); + return 1; + } + sprintf(pBueffel, "ERROR: subcommand %s to commandlog unknown", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; +} - if (fauto && tLastWrite > 0 && tNow > tLastWrite) { - fflush(fauto); - tLastWrite = 0; - } - return iEnd; - } -/*----------- a command to configure the log --------------------------*/ - int CommandLog(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char *pPtr = NULL; - char pBueffel[1024]; - int iVal, iRet; - - if(argc == 1) - { - if(fd) - { - sprintf(pBueffel,"Command log ACTIVE at %s",pFile); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { - SCWrite(pCon,"Command logging DISABLED",eValue); - return 1; - } - } - - /* handle tail */ - strtolower(argv[1]); - if(strcmp(argv[1],"tail") == 0) - { - /* check for optional number of lines argument */ - iVal = 20; - if(argc >= 3) - { - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iVal); - if(iRet != TCL_OK) - iVal = 20; - } - PrintTail(iVal,pCon); - return 1; - } - - /* check rights */ - if(!SCMatchRights(pCon,usMugger)) - { - SCWrite(pCon,"ERROR: only managers may configure the logfile", - eError); - SCWrite(pCon,"ERROR: Request refused",eError); - return 0; - } - - /* check no of args */ - if(argc < 2) - { - SCWrite(pCon, - "ERROR: Insufficient number or arguments to commandlog", - eError); - return 0; - } - - if(strcmp(argv[1],"new") == 0) /* new command */ - { - if(argc < 3) - { - SCWrite(pCon, - "ERROR: Insufficient number or arguments to commandlog new", - eError); - return 0; - } - if(fd) - { - fclose(fd); - fd = NULL; - } - /* make the filename */ - pPtr = IFindOption(pSICSOptions,"LogFileDir"); - if(!pPtr) - { - SCWrite(pCon,"WARNING: no log file directory specified",eWarning); - sprintf(pBueffel,"%s",argv[2]); - - } - else - { - sprintf(pBueffel,"%s/%s",pPtr,argv[2]); - } - fd = fopen(pBueffel,"w"); - if(!fd) - { - sprintf(pBueffel,"ERROR: cannot open %s/%s for writing",pPtr, - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - strcpy(pFile,argv[2]); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"auto") == 0) - { - if(iAutoActive) - { - SCWrite(pCon,"ERROR: autologging is already active",eError); - return 0; - } - TaskRegister(pServ->pTasker, - AutoTask, - NULL, - NULL, - NULL, - 1); - SCSendOK(pCon); - iAutoActive = 1; - return 1; - } - else if(strcmp(argv[1],"intervall") == 0) - { - if(argc > 2) - { - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iVal); - if(iRet != TCL_OK) - { - SCWrite(pCon,"ERROR: failed to convert new intervall to number", - eError); - return 0; - } - iIntervall = iVal; - } - SCPrintf(pCon,eValue,"%s.intervall [min] = %d", argv[0], iIntervall); - return 1; - } - else if(strcmp(argv[1],"compact") == 0) - { - if(argc > 2) - { - iCompact = atoi(argv[2]); - if (iCompact > 0) iIntervall = 0; - } - SCPrintf(pCon,eValue,"%s.compact [sec] = %d", argv[0], iCompact); - return 1; - } - else if(strcmp(argv[1],"close") == 0) /* close command */ - { - fclose(fd); - fd = NULL; - SCSendOK(pCon); - return 1; - } - sprintf(pBueffel,"ERROR: subcommand %s to commandlog unknown", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } /*-------------------------------------------------------------------------*/ - void CommandLogClose(void *pData) - { - if(fd) - { - fclose(fd); - } - if(fauto) - fclose(fauto); - if(pData) - KillDummy(pData); - if(pTail) - deleteCircular(pTail); - } - - - +void CommandLogClose(void *pData) +{ + if (fd) { + fclose(fd); + } + if (fauto) + fclose(fauto); + if (pData) + KillDummy(pData); + if (pTail) + deleteCircular(pTail); +} diff --git a/commandlog.h b/commandlog.h index 704a264a..db23bb23 100644 --- a/commandlog.h +++ b/commandlog.h @@ -9,13 +9,12 @@ --------------------------------------------------------------------------*/ #ifndef COMMANDLOG #define COMMANDLOG - void WriteToCommandLog(char *prompt,char *pText); - void WriteToCommandLogId(char *prompt, int id, char *text); - void WriteToCommandLogCmd(int id, char *text); - int CompactCommandLog(void); - int CommandLog(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - - void CommandLogClose(void *pData); -#endif +void WriteToCommandLog(char *prompt, char *pText); +void WriteToCommandLogId(char *prompt, int id, char *text); +void WriteToCommandLogCmd(int id, char *text); +int CompactCommandLog(void); +int CommandLog(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +void CommandLogClose(void *pData); +#endif diff --git a/cone.c b/cone.c index b0f4fe8f..8a70c103 100644 --- a/cone.c +++ b/cone.c @@ -20,69 +20,78 @@ #include "sicsobj.h" #include "sicshipadaba.h" /*=================== Object Descriptor Interface ===================================================*/ -static void *ConeGetInterface(void *pData, int iID){ +static void *ConeGetInterface(void *pData, int iID) +{ pConeData self = NULL; - pSICSOBJ obj = (pSICSOBJ)pData; + pSICSOBJ obj = (pSICSOBJ) pData; - self = (pConeData)obj->pPrivate; - if(self == NULL){ + self = (pConeData) obj->pPrivate; + if (self == NULL) { return NULL; } - if(iID == DRIVEID){ + if (iID == DRIVEID) { return self->pDriv; } return NULL; } + /*=================== Drivable Interface ============================================================*/ -static int ConeHalt(void *pData){ +static int ConeHalt(void *pData) +{ pSICSOBJ obj = pData; pConeData self = NULL; - self = (pConeData)obj->pPrivate; + self = (pConeData) obj->pPrivate; assert(self != NULL); stopHKLMotors(self->pHkl); return 1; } + /*-----------------------------------------------------------------------------------------------------*/ -static int ConeCheckLimits(void *self, float fVal, char *error, int errLen){ +static int ConeCheckLimits(void *self, float fVal, char *error, int errLen) +{ /* - There is no meaningful implementation here. This gets called when starting the motor. - At that stage not all other values may be known. If the calculation fails, this will die - at status check time. - */ + There is no meaningful implementation here. This gets called when starting the motor. + At that stage not all other values may be known. If the calculation fails, this will die + at status check time. + */ return 1; } + /*------------------------------------------------------------------------*/ -static MATRIX makeCsToPsiMatrix(reflection center, double lambda){ - MATRIX psiToCs = NULL, csToPsi = NULL, t1, t2; - double z1[3], u; - - psiToCs = makeInstToConeVectorMatrix(center,lambda); - if(psiToCs == NULL){ +static MATRIX makeCsToPsiMatrix(reflection center, double lambda) +{ + MATRIX psiToCs = NULL, csToPsi = NULL, t1, t2; + double z1[3], u; + + psiToCs = makeInstToConeVectorMatrix(center, lambda); + if (psiToCs == NULL) { return NULL; } csToPsi = mat_inv(psiToCs); /* * this is debugging code: remove together with variables */ - z1FromAngles(lambda,center.s2t,center.om,center.chi,center.phi,z1); + z1FromAngles(lambda, center.s2t, center.om, center.chi, center.phi, z1); t1 = makeVectorInit(z1); - t2 = mat_mul(psiToCs,t1); + t2 = mat_mul(psiToCs, t1); normalizeVector(t2); t1[0][0] = .0; t1[1][0] = .0; t1[2][0] = 1.; - u = angleBetween(t1,t2); - + u = angleBetween(t1, t2); + mat_free(psiToCs); return csToPsi; } + /*---------------------------------------------------------------------------------------------------- * I am lazy in this function: I calculate anew from all the data. This saves * me a lot of trouble keeping track of parameter changes in UBCALC etc. - * ---------------------------------------------------------------------------*/ -static long ConeSetValue(void *pData, SConnection *pCon, float fVal){ + * ---------------------------------------------------------------------------*/ +static long ConeSetValue(void *pData, SConnection * pCon, float fVal) +{ pSICSOBJ obj = pData, refList; pConeData self = NULL; double fSet[4]; @@ -96,18 +105,18 @@ static long ConeSetValue(void *pData, SConnection *pCon, float fVal){ double hkl[3], ang[4]; lattice direct; hdbValue v; - - if(!SCMatchRights(pCon,usUser)){ + + if (!SCMatchRights(pCon, usUser)) { return 0; } - self = (pConeData)obj->pPrivate; + self = (pConeData) obj->pPrivate; assert(self != NULL); /* * calculate opening angle */ - B = mat_creat(3,3,UNIT_MATRIX); + B = mat_creat(3, 3, UNIT_MATRIX); cell = SXGetCell(); direct.a = cell[0]; direct.b = cell[1]; @@ -115,145 +124,155 @@ static long ConeSetValue(void *pData, SConnection *pCon, float fVal){ direct.alpha = cell[3]; direct.beta = cell[4]; direct.gamma = cell[5]; - status = calculateBMatrix(direct,B); - if(status < 0){ - SCWrite(pCon,"ERROR: cell has no volume",eError); + status = calculateBMatrix(direct, B); + if (status < 0) { + SCWrite(pCon, "ERROR: cell has no volume", eError); return 0; } /* * get center from the main reflection list */ refList = SXGetReflectionList(); - SICSHdbGetPar(obj,pCon,"center", &v); - if(!GetRefIndexID(refList,v.v.text,hkl)){ - SCPrintf(pCon,eError,"ERROR: cannot find reflection with ID: %s", v.v.text); - return 0; + SICSHdbGetPar(obj, pCon, "center", &v); + if (!GetRefIndexID(refList, v.v.text, hkl)) { + SCPrintf(pCon, eError, "ERROR: cannot find reflection with ID: %s", + v.v.text); + return 0; } center.h = hkl[0]; center.k = hkl[1]; center.l = hkl[2]; - GetRefAnglesID(refList,v.v.text,ang); + GetRefAnglesID(refList, v.v.text, ang); center.s2t = ang[0]; center.om = ang[1]; center.chi = ang[2]; center.phi = ang[3]; - - SICSHdbGetPar(obj,pCon,"target",&v); + + SICSHdbGetPar(obj, pCon, "target", &v); target.h = v.v.floatArray[0]; target.k = v.v.floatArray[1]; target.l = v.v.floatArray[2]; - openingAngle = angleBetweenReflections(B,center,target); - + openingAngle = angleBetweenReflections(B, center, target); + /* * calculate conversion matrix from cone system to PSI system */ - csToPsi = makeCsToPsiMatrix(center,SXGetLambda()); - if(csToPsi == NULL){ - SCWrite(pCon,"ERROR: bad parameters: failed to generate conversion matrix", + csToPsi = makeCsToPsiMatrix(center, SXGetLambda()); + if (csToPsi == NULL) { + SCWrite(pCon, + "ERROR: bad parameters: failed to generate conversion matrix", eError); - return 0; + return 0; } - + /* * calculate scattering vector on cone and make its length * match the length of the apropriate scattering vector */ - SICSHdbGetPar(obj,pCon,"target",&v); + SICSHdbGetPar(obj, pCon, "target", &v); target.h = v.v.floatArray[0]; target.k = v.v.floatArray[1]; target.l = v.v.floatArray[2]; - SICSHdbGetPar(obj,pCon,"qscale",&v); + SICSHdbGetPar(obj, pCon, "qscale", &v); /* - * calculate scattering vector on cone and make its length - * match the length of the apropriate scattering vector - */ - length = scatteringVectorLength(B,target) * v.v.doubleValue; + * calculate scattering vector on cone and make its length + * match the length of the apropriate scattering vector + */ + length = scatteringVectorLength(B, target) * v.v.doubleValue; newScat = calcConeVector(openingAngle, fVal, length, csToPsi); - if(newScat == NULL){ - SCWrite(pCon,"ERROR: fails to calculate cone vector",eError); + if (newScat == NULL) { + SCWrite(pCon, "ERROR: fails to calculate cone vector", eError); return 0; } /* * try to find setting angles for this vector */ - status = findAllowedBisecting(SXGetLambda(),newScat, fSet, - hklInRange, self->pHkl); + status = findAllowedBisecting(SXGetLambda(), newScat, fSet, + hklInRange, self->pHkl); /* * clean up matrices */ - mat_free(B); - mat_free(newScat); - mat_free(csToPsi); - if(status != 1){ - SCWrite(pCon,"ERROR: cannot get cone vector into scattering position", - eError); - SCSetInterrupt(pCon,eAbortOperation); - return 0; - } - self->lastConeAngle = fVal; + mat_free(B); + mat_free(newScat); + mat_free(csToPsi); + if (status != 1) { + SCWrite(pCon, "ERROR: cannot get cone vector into scattering position", + eError); + SCSetInterrupt(pCon, eAbortOperation); + return 0; + } + self->lastConeAngle = fVal; /* * start motors */ - for(i = 0; i < 4; i++){ - ffSet[i] = fSet[i]; + for (i = 0; i < 4; i++) { + ffSet[i] = fSet[i]; } - return startHKLMotors(self->pHkl, pCon,ffSet); + return startHKLMotors(self->pHkl, pCon, ffSet); } + /*---------------------------------------------------------------------------------------------------*/ -static int checkMotors(pConeData self, SConnection *pCon){ +static int checkMotors(pConeData self, SConnection * pCon) +{ int status, i; pMotor pMot = NULL; - MotorFunction mots[] = {TwoTheta, Omega, Chi, Phi}; - - for(i = 0; i < 4; i++){ - pMot = SXGetMotor(mots[i]); - if(pMot != NULL){ - status = pMot->pDrivInt->CheckStatus(pMot, pCon); - if(status != HWIdle && status != OKOK){ - return status; - } - } + MotorFunction mots[] = { TwoTheta, Omega, Chi, Phi }; + + for (i = 0; i < 4; i++) { + pMot = SXGetMotor(mots[i]); + if (pMot != NULL) { + status = pMot->pDrivInt->CheckStatus(pMot, pCon); + if (status != HWIdle && status != OKOK) { + return status; + } + } } return HWIdle; } + /*-----------------------------------------------------------------------------------------------------*/ -static int ConeCheckStatus(void *pData, SConnection *pCon){ +static int ConeCheckStatus(void *pData, SConnection * pCon) +{ pSICSOBJ obj = pData; pConeData self = NULL; int status; - self = (pConeData)obj->pPrivate; + self = (pConeData) obj->pPrivate; assert(self != NULL); - return checkMotors(self,pCon); + return checkMotors(self, pCon); } + /*-----------------------------------------------------------------------------------------------------*/ -static float ConeGetValue(void *pData, SConnection *pCon){ - pSICSOBJ obj = pData; +static float ConeGetValue(void *pData, SConnection * pCon) +{ + pSICSOBJ obj = pData; pConeData self = NULL; float fVal[3]; int status; - self = (pConeData)obj->pPrivate; + self = (pConeData) obj->pPrivate; assert(self != NULL); - return self->lastConeAngle; + return self->lastConeAngle; } + /*=============================== Live and Death ====================================*/ -static pConeData MakeConeMot(){ +static pConeData MakeConeMot() +{ pConeData self = NULL; - self = (pConeData)malloc(sizeof(coneData)); - if(self == NULL){ + self = (pConeData) malloc(sizeof(coneData)); + if (self == NULL) { return NULL; } - memset(self,0,sizeof(coneData)); + memset(self, 0, sizeof(coneData)); self->pDriv = CreateDrivableInterface(); - if(self->pDriv == NULL){ + if (self->pDriv == NULL) { free(self); return NULL; } - + self->pDriv->Halt = ConeHalt; self->pDriv->CheckLimits = ConeCheckLimits; self->pDriv->SetValue = ConeSetValue; @@ -261,53 +280,62 @@ static pConeData MakeConeMot(){ self->pDriv->GetValue = ConeGetValue; return self; } + /*------------------------------------------------------------------------------------------*/ -int MakeCone(SConnection *pCon, SicsInterp *pSics, void *pData, int argc, char *argv[]){ +int MakeCone(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, + char *argv[]) +{ pSICSOBJ pNew = NULL; pConeData pMot = NULL; char pBuffer[131], pName[80]; int status; pHdb cmd; - - if(argc > 1){ - strcpy(pName,argv[1]); + + if (argc > 1) { + strcpy(pName, argv[1]); } else { - strcpy(pName,"cone"); + strcpy(pName, "cone"); } - pNew = MakeSICSOBJ(pName,"Cone"); + pNew = MakeSICSOBJ(pName, "Cone"); pMot = MakeConeMot(); - if(pNew == NULL || pMot == NULL){ - SCWrite(pCon,"ERROR: out of memory creating cone virtual motor",eError); + if (pNew == NULL || pMot == NULL) { + SCWrite(pCon, "ERROR: out of memory creating cone virtual motor", + eError); return 0; - } + } pNew->pDes->GetInterface = ConeGetInterface; pNew->pPrivate = pMot; pNew->KillPrivate = DefaultFree; - - cmd = AddSICSHdbPar(pNew->objectNode,"target", usUser, makeHdbValue(HIPFLOATAR,3)); - SetHdbProperty(cmd,"__save", "true"); - cmd = AddSICSHdbPar(pNew->objectNode,"qscale", usUser, MakeHdbFloat(1.)); - SetHdbProperty(cmd,"__save", "true"); - cmd = AddSICSHdbPar(pNew->objectNode,"center", usUser, MakeHdbText("unknown")); - SetHdbProperty(cmd,"__save", "true"); - - - if(argc > 2){ - pMot->pHkl = FindCommandData(pSics,argv[2],"4-Circle-Calculus"); + + cmd = + AddSICSHdbPar(pNew->objectNode, "target", usUser, + makeHdbValue(HIPFLOATAR, 3)); + SetHdbProperty(cmd, "__save", "true"); + cmd = + AddSICSHdbPar(pNew->objectNode, "qscale", usUser, MakeHdbFloat(1.)); + SetHdbProperty(cmd, "__save", "true"); + cmd = + AddSICSHdbPar(pNew->objectNode, "center", usUser, + MakeHdbText("unknown")); + SetHdbProperty(cmd, "__save", "true"); + + + if (argc > 2) { + pMot->pHkl = FindCommandData(pSics, argv[2], "4-Circle-Calculus"); } else { - pMot->pHkl = FindCommandData(pSics,"hkl","4-Circle-Calculus"); + pMot->pHkl = FindCommandData(pSics, "hkl", "4-Circle-Calculus"); } - if(pMot->pHkl == NULL){ - snprintf(pBuffer,131,"ERROR: %s is no hkl object" , argv[2]); - SCWrite(pCon,pBuffer,eError); - return 0; + if (pMot->pHkl == NULL) { + snprintf(pBuffer, 131, "ERROR: %s is no hkl object", argv[2]); + SCWrite(pCon, pBuffer, eError); + return 0; } - - status = AddCommand(pSics,pName,InterInvokeSICSOBJ,KillSICSOBJ,pNew); - if(status != 1){ - SCWrite(pCon,"ERROR: failed to create duplicate cone motor",eError); + + status = AddCommand(pSics, pName, InterInvokeSICSOBJ, KillSICSOBJ, pNew); + if (status != 1) { + SCWrite(pCon, "ERROR: failed to create duplicate cone motor", eError); } return status; } diff --git a/cone.h b/cone.h index 9f59a426..4aa49263 100644 --- a/cone.h +++ b/cone.h @@ -14,11 +14,11 @@ /*-----------------------------------------------------------------------*/ typedef struct { - pIDrivable pDriv; - float lastConeAngle; - pHKL pHkl; + pIDrivable pDriv; + float lastConeAngle; + pHKL pHkl; } coneData, *pConeData; /*----------------------------------------------------------------------*/ -int MakeCone(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeCone(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/configfu.h b/configfu.h index 998e7567..d84100df 100644 --- a/configfu.h +++ b/configfu.h @@ -8,23 +8,23 @@ --------------------------------------------------------------------------*/ #ifndef SICSCONFIG #define SICSCONFIG - - int AddHalt(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); + +int AddHalt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* configuration command: enters argv objects into Halt List of Interrupt. This is the means how the server knows which hardware to halt in an case of emergency. Implemented in intserv.c - */ + */ - int ListObjects(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int ListObjects(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* lists all avialable objects. Realised in Scinter.c - */ - int SicsAtt(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); + */ +int SicsAtt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* handling of SICS object attributes. In SCinter.c - */ + */ #endif diff --git a/confvirtmot.h b/confvirtmot.h index 919a18aa..a9fa2c44 100644 --- a/confvirtmot.h +++ b/confvirtmot.h @@ -13,9 +13,8 @@ #include "sics.h" -int MakeConfigurableVirtualMotor(SConnection *pCon, SicsInterp *pSics, - void *data, int aargc, char *argv[]); -int ConfigurableVirtualMotorAction(SConnection *pCon, SicsInterp *pSics, - void *data, int argc, char *argv[]); +int MakeConfigurableVirtualMotor(SConnection * pCon, SicsInterp * pSics, + void *data, int aargc, char *argv[]); +int ConfigurableVirtualMotorAction(SConnection * pCon, SicsInterp * pSics, + void *data, int argc, char *argv[]); #endif - diff --git a/confvirtualmot.c b/confvirtualmot.c index 84d4ef72..bca60967 100644 --- a/confvirtualmot.c +++ b/confvirtualmot.c @@ -37,193 +37,206 @@ typedef struct { typedef struct { float fVal; char *pName; -} EventInfo; +} EventInfo; /* Data available when registering interest */ typedef struct { char *pName; SConnection *pCon; - float lastValue; -} RegisteredInfo, *pRegisteredInfo; + float lastValue; +} RegisteredInfo, *pRegisteredInfo; /*---------------------------------------------------------------------*/ -static int HaltMotors(void *pData){ - pConfigurableVirtualMotor self = (pConfigurableVirtualMotor)pData; +static int HaltMotors(void *pData) +{ + pConfigurableVirtualMotor self = (pConfigurableVirtualMotor) pData; RealMotor tuktuk; int iRet; iRet = LLDnodePtr2First(self->motorList); - while(iRet != 0) - { - LLDnodeDataTo(self->motorList,&tuktuk); + while (iRet != 0) { + LLDnodeDataTo(self->motorList, &tuktuk); tuktuk.pDriv->Halt(tuktuk.data); iRet = LLDnodePtr2Next(self->motorList); } return 1; } + /*----------------------------------------------------------------------*/ -static char *invokeMotorScript(pConfigurableVirtualMotor self, - float newValue){ +static char *invokeMotorScript(pConfigurableVirtualMotor self, + float newValue) +{ char pBueffel[512]; Tcl_Interp *pTcl; int status; self->parseOK = 1; - if(self->scriptName == NULL){ - snprintf(self->scriptError,511, - "ERROR: no script configured for configurable virtual motor"); + if (self->scriptName == NULL) { + snprintf(self->scriptError, 511, + "ERROR: no script configured for configurable virtual motor"); self->parseOK = 0; return NULL; } - snprintf(pBueffel,510,"%s %f",self->scriptName, newValue); + snprintf(pBueffel, 510, "%s %f", self->scriptName, newValue); pTcl = InterpGetTcl(pServ->pSics); status = Tcl_Eval(pTcl, pBueffel); - if(status != TCL_OK){ - snprintf(self->scriptError,510,"ERROR: Tcl subsystem reported %s", - Tcl_GetStringResult(pTcl)); + if (status != TCL_OK) { + snprintf(self->scriptError, 510, "ERROR: Tcl subsystem reported %s", + Tcl_GetStringResult(pTcl)); self->parseOK = 0; return NULL; } - return (char *)Tcl_GetStringResult(pTcl); + return (char *) Tcl_GetStringResult(pTcl); } /*--------------------------------------------------------------------*/ -static int parseEntry(pConfigurableVirtualMotor self, - char *entry){ +static int parseEntry(pConfigurableVirtualMotor self, char *entry) +{ RealMotor tuktuk; char *pPtr = NULL; char number[80], pError[256]; CommandList *pCom = NULL; int status; - + pPtr = entry; - pPtr = stptok(pPtr,tuktuk.name,131,"="); - if(pPtr == NULL){ - snprintf(self->scriptError,510,"ERROR: cannot interpret %s, %s", entry, - "require format: motor=value"); + pPtr = stptok(pPtr, tuktuk.name, 131, "="); + if (pPtr == NULL) { + snprintf(self->scriptError, 510, "ERROR: cannot interpret %s, %s", + entry, "require format: motor=value"); self->parseOK = 0; return 0; } - tuktuk.pDriv = (pIDrivable)FindDrivable(pServ->pSics,tuktuk.name); - pCom = FindCommand(pServ->pSics,tuktuk.name); - if(!pCom){ - snprintf(self->scriptError,510,"ERROR: %s not found",tuktuk.name); + tuktuk.pDriv = (pIDrivable) FindDrivable(pServ->pSics, tuktuk.name); + pCom = FindCommand(pServ->pSics, tuktuk.name); + if (!pCom) { + snprintf(self->scriptError, 510, "ERROR: %s not found", tuktuk.name); self->parseOK = 0; return 0; } tuktuk.data = pCom->pData; - - if(tuktuk.pDriv == NULL){ - snprintf(self->scriptError,510,"ERROR: %s is not drivable",tuktuk.name); + + if (tuktuk.pDriv == NULL) { + snprintf(self->scriptError, 510, "ERROR: %s is not drivable", + tuktuk.name); self->parseOK = 0; return 0; } - pPtr = stptok(pPtr,number,79,"="); + pPtr = stptok(pPtr, number, 79, "="); tuktuk.value = atof(number); - LLDnodeAppendFrom(self->motorList,&tuktuk); + LLDnodeAppendFrom(self->motorList, &tuktuk); return 1; } + /*----------------------------------------------------------------------*/ static int parseCommandList(pConfigurableVirtualMotor self, - char *commandList){ + char *commandList) +{ char pEntry[256], *pPtr; int status; LLDdelete(self->motorList); self->motorList = LLDcreate(sizeof(RealMotor)); - + pPtr = commandList; - while((pPtr = stptok(pPtr,pEntry,255,",")) != NULL){ - status = parseEntry(self,pEntry); - if(status != 1){ + while ((pPtr = stptok(pPtr, pEntry, 255, ",")) != NULL) { + status = parseEntry(self, pEntry); + if (status != 1) { return 0; } - } + } return 1; } + /*-----------------------------------------------------------------------*/ -static int startMotorList(pConfigurableVirtualMotor self, SConnection *pCon){ +static int startMotorList(pConfigurableVirtualMotor self, + SConnection * pCon) +{ RealMotor tuktuk; int status, iRet; iRet = LLDnodePtr2First(self->motorList); - while(iRet != 0) - { - LLDnodeDataTo(self->motorList,&tuktuk); - status = tuktuk.pDriv->SetValue(tuktuk.data,pCon,tuktuk.value); - if(status != 1){ + while (iRet != 0) { + LLDnodeDataTo(self->motorList, &tuktuk); + status = tuktuk.pDriv->SetValue(tuktuk.data, pCon, tuktuk.value); + if (status != 1) { return status; } tuktuk.running = 1; - LLDnodeDataFrom(self->motorList,&tuktuk); + LLDnodeDataFrom(self->motorList, &tuktuk); iRet = LLDnodePtr2Next(self->motorList); } return OKOK; } + /*------------------------------------------------------------------------*/ -static long ConfSetValue(void *pData, SConnection *pCon, float newValue){ - pConfigurableVirtualMotor self = (pConfigurableVirtualMotor)pData; +static long ConfSetValue(void *pData, SConnection * pCon, float newValue) +{ + pConfigurableVirtualMotor self = (pConfigurableVirtualMotor) pData; char *commandList = NULL; - int status; + int status; assert(self != NULL); - commandList = invokeMotorScript(self,newValue); - if(commandList == NULL){ - SCWrite(pCon,self->scriptError,eError); + commandList = invokeMotorScript(self, newValue); + if (commandList == NULL) { + SCWrite(pCon, self->scriptError, eError); return 0; } - status = parseCommandList(self,commandList); - if(status != 1){ - SCWrite(pCon,self->scriptError,eError); + status = parseCommandList(self, commandList); + if (status != 1) { + SCWrite(pCon, self->scriptError, eError); return 0; } self->targetValue = newValue; self->targetReached = 0; self->posCount = 0; - status = startMotorList(self,pCon); - if(status != OKOK){ + status = startMotorList(self, pCon); + if (status != OKOK) { HaltMotors(self); } return OKOK; } + /*-----------------------------------------------------------------------*/ -static int ConfCheckLimits(void *pData, float fVal, char *error, int errLen){ - pConfigurableVirtualMotor self = (pConfigurableVirtualMotor)pData; +static int ConfCheckLimits(void *pData, float fVal, char *error, + int errLen) +{ + pConfigurableVirtualMotor self = (pConfigurableVirtualMotor) pData; char *commandList = NULL; int status, iRet; RealMotor tuktuk; assert(self != NULL); - if(self->targetValue != fVal){ - commandList = invokeMotorScript(self,fVal); - if(commandList == NULL){ - strncpy(error,self->scriptError,errLen); + if (self->targetValue != fVal) { + commandList = invokeMotorScript(self, fVal); + if (commandList == NULL) { + strncpy(error, self->scriptError, errLen); return 0; } - status = parseCommandList(self,commandList); - if(status != 1){ - strncpy(error,self->scriptError,errLen); + status = parseCommandList(self, commandList); + if (status != 1) { + strncpy(error, self->scriptError, errLen); return 0; } } iRet = LLDnodePtr2First(self->motorList); - while(iRet != 0) - { - LLDnodeDataTo(self->motorList,&tuktuk); - status = tuktuk.pDriv->CheckLimits(tuktuk.data,tuktuk.value,error,errLen); - if(status != 1){ + while (iRet != 0) { + LLDnodeDataTo(self->motorList, &tuktuk); + status = + tuktuk.pDriv->CheckLimits(tuktuk.data, tuktuk.value, error, + errLen); + if (status != 1) { return status; } iRet = LLDnodePtr2Next(self->motorList); @@ -231,189 +244,196 @@ static int ConfCheckLimits(void *pData, float fVal, char *error, int errLen){ return 1; } - static void KillInfo(void *pData) - { - pRegisteredInfo self = NULL; - - assert(pData); - self = (pRegisteredInfo)pData; - if(self->pName) - { - free(self->pName); - } - if(self->pCon) - { - SCDeleteConnection(self->pCon); - } - free(self); - } +static void KillInfo(void *pData) +{ + pRegisteredInfo self = NULL; + + assert(pData); + self = (pRegisteredInfo) pData; + if (self->pName) { + free(self->pName); + } + if (self->pCon) { + SCDeleteConnection(self->pCon); + } + free(self); +} + /*------------------- The CallBack function for interest ------------------ * iEvent: Event ID, see event.h for SICS events * pEvent: May contain data from event generating object * pUser: Data available when registering interest, see RegisteredInfo struct * defined above for available info --------------------------------------------------------------------------*/ - static int InterestCallback(int iEvent, void *pEvent, void *pUser) - { - pRegisteredInfo pInfo = NULL; - char pBueffel[80]; - EventInfo *pEventData; - - assert(pEvent); - assert(pUser); +static int InterestCallback(int iEvent, void *pEvent, void *pUser) +{ + pRegisteredInfo pInfo = NULL; + char pBueffel[80]; + EventInfo *pEventData; - if(!SCisConnected(pInfo->pCon)){ - return -1; - } - - pEventData = (EventInfo *)pEvent; - pInfo = (RegisteredInfo *)pUser; + assert(pEvent); + assert(pUser); + + if (!SCisConnected(pInfo->pCon)) { + return -1; + } + + pEventData = (EventInfo *) pEvent; + pInfo = (RegisteredInfo *) pUser; + + if (pInfo->lastValue != pEventData->fVal) { + pInfo->lastValue = pEventData->fVal; + (pInfo->pCon)->conEventType = POSITION; + sprintf(pBueffel, "%s.position = %f ", pInfo->pName, pInfo->lastValue); + SCWrite(pInfo->pCon, pBueffel, eEvent); + } + return 1; +} - if (pInfo->lastValue != pEventData->fVal) { - pInfo->lastValue = pEventData->fVal; - (pInfo->pCon)->conEventType=POSITION; - sprintf(pBueffel,"%s.position = %f ", pInfo->pName, pInfo->lastValue); - SCWrite(pInfo->pCon,pBueffel,eEvent); - } - return 1; - } /*------------------------------------------------------------------------*/ -static int ConfCheckStatus(void *pData, SConnection *pCon){ - pConfigurableVirtualMotor self = (pConfigurableVirtualMotor)pData; +static int ConfCheckStatus(void *pData, SConnection * pCon) +{ + pConfigurableVirtualMotor self = (pConfigurableVirtualMotor) pData; RealMotor tuktuk; int iRet, status, result; EventInfo event; result = HWIdle; iRet = LLDnodePtr2First(self->motorList); - while(iRet != 0) - { - LLDnodeDataTo(self->motorList,&tuktuk); - if(tuktuk.running == 1){ + while (iRet != 0) { + LLDnodeDataTo(self->motorList, &tuktuk); + if (tuktuk.running == 1) { status = tuktuk.pDriv->CheckStatus(tuktuk.data, pCon); - switch(status){ + switch (status) { case HWIdle: - tuktuk.running = 0; - LLDnodeDataFrom(self->motorList,&tuktuk); - break; + tuktuk.running = 0; + LLDnodeDataFrom(self->motorList, &tuktuk); + break; case HWBusy: - result = HWBusy; - break; + result = HWBusy; + break; case HWFault: case HWPosFault: - return status; - break; + return status; + break; default: - /* - this is a programming error and has to be fixed - */ - assert(0); + /* + this is a programming error and has to be fixed + */ + assert(0); } } iRet = LLDnodePtr2Next(self->motorList); } if (result == HWIdle) { - event.pName = self->name; - event.fVal = self->pDriv->GetValue(self,pCon); - InvokeCallBack(self->pCall, MOTDRIVE, &event); + event.pName = self->name; + event.fVal = self->pDriv->GetValue(self, pCon); + InvokeCallBack(self->pCall, MOTDRIVE, &event); } else if (result == HWBusy) { self->posCount++; - if(self->posCount >= 10/*ObVal(self->ParArray,MOVECOUNT)*/) - { + if (self->posCount >= 10 /*ObVal(self->ParArray,MOVECOUNT) */ ) { event.pName = self->name; - event.fVal = self->pDriv->GetValue(self,pCon); + event.fVal = self->pDriv->GetValue(self, pCon); InvokeCallBack(self->pCall, MOTDRIVE, &event); self->posCount = 0; } } return result; } + /*---------------------------------------------------------------------*/ -static float invokeReadScript(pConfigurableVirtualMotor self, - SConnection *pCon){ +static float invokeReadScript(pConfigurableVirtualMotor self, + SConnection * pCon) +{ Tcl_Interp *pTcl; int status; pTcl = InterpGetTcl(pServ->pSics); status = Tcl_Eval(pTcl, self->readScript); - if(status != TCL_OK){ - snprintf(self->scriptError,510,"ERROR: Tcl subsystem reported %s", - Tcl_GetStringResult(pTcl)); - SCWrite(pCon,self->scriptError,eError); + if (status != TCL_OK) { + snprintf(self->scriptError, 510, "ERROR: Tcl subsystem reported %s", + Tcl_GetStringResult(pTcl)); + SCWrite(pCon, self->scriptError, eError); } return atof(Tcl_GetStringResult(pTcl)); } + /*---------------------------------------------------------------------*/ -static void checkMotorValues(pConfigurableVirtualMotor self, - SConnection *pCon){ +static void checkMotorValues(pConfigurableVirtualMotor self, + SConnection * pCon) +{ int iRet; float value; RealMotor tuktuk; char pBueffel[512]; iRet = LLDnodePtr2First(self->motorList); - while(iRet != 0) - { - LLDnodeDataTo(self->motorList,&tuktuk); - value = tuktuk.pDriv->GetValue(tuktuk.data,pCon); + while (iRet != 0) { + LLDnodeDataTo(self->motorList, &tuktuk); + value = tuktuk.pDriv->GetValue(tuktuk.data, pCon); value -= tuktuk.value; - if(value < .0){ + if (value < .0) { value *= -1; } - if(value > .1) { - snprintf(pBueffel,510,"WARNING: motor %s of position by %f", - tuktuk.name,value); - SCWrite(pCon,pBueffel,eWarning); + if (value > .1) { + snprintf(pBueffel, 510, "WARNING: motor %s of position by %f", + tuktuk.name, value); + SCWrite(pCon, pBueffel, eWarning); return; } iRet = LLDnodePtr2Next(self->motorList); } self->targetReached = 1; -} +} + /*-----------------------------------------------------------------------*/ -static float ConfGetValue(void *pData, SConnection *pCon){ - pConfigurableVirtualMotor self = (pConfigurableVirtualMotor)pData; +static float ConfGetValue(void *pData, SConnection * pCon) +{ + pConfigurableVirtualMotor self = (pConfigurableVirtualMotor) pData; float currentValue = -9999.99; assert(self != NULL); - if(self->readScript != NULL){ - currentValue = invokeReadScript(self,pCon); + if (self->readScript != NULL) { + currentValue = invokeReadScript(self, pCon); } else { - if(self->targetReached == 1){ + if (self->targetReached == 1) { return self->targetValue; } else { - checkMotorValues(self,pCon); - if(self->targetReached){ - currentValue = self->targetValue; + checkMotorValues(self, pCon); + if (self->targetReached) { + currentValue = self->targetValue; } } } return currentValue; } + /*-----------------------------------------------------------------------*/ -static void *GetConfigurableVirtualMotorInterface(void *pData, int iID){ +static void *GetConfigurableVirtualMotorInterface(void *pData, int iID) +{ pConfigurableVirtualMotor self = NULL; - self = (pConfigurableVirtualMotor)pData; + self = (pConfigurableVirtualMotor) pData; assert(self); - if(iID == DRIVEID){ + if (iID == DRIVEID) { return self->pDriv; - } else if(iID == CALLBACKINTERFACE) - { + } else if (iID == CALLBACKINTERFACE) { return self->pCall; } return NULL; } + /*-----------------------------------------------------------------------*/ -static void KillConfigurableVirtualMotor(void *data){ +static void KillConfigurableVirtualMotor(void *data) +{ pConfigurableVirtualMotor self = NULL; - - self = (pConfigurableVirtualMotor)data; - if(self != NULL){ - if(self->pDes != NULL){ + + self = (pConfigurableVirtualMotor) data; + if (self != NULL) { + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); self->pDes = NULL; } @@ -422,11 +442,11 @@ static void KillConfigurableVirtualMotor(void *data){ free(self->name); self->name = NULL; } - if(self->scriptName != NULL){ + if (self->scriptName != NULL) { free(self->scriptName); self->scriptName = NULL; } - if(self->readScript != NULL){ + if (self->readScript != NULL) { free(self->readScript); self->readScript = NULL; } @@ -434,39 +454,42 @@ static void KillConfigurableVirtualMotor(void *data){ self = NULL; } } + /*------------------------------------------------------------------------*/ -int MakeConfigurableVirtualMotor(SConnection *pCon, SicsInterp *pSics, - void *data, int argc, char *argv[]){ +int MakeConfigurableVirtualMotor(SConnection * pCon, SicsInterp * pSics, + void *data, int argc, char *argv[]) +{ pConfigurableVirtualMotor pNew = NULL; char pBueffel[512]; - if(argc < 2){ - SCWrite(pCon,"ERROR: need name to create configurable motor",eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: need name to create configurable motor", eError); return 0; } - pNew = (pConfigurableVirtualMotor)malloc(sizeof(ConfigurableVirtualMotor)); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: no memory to create configurable virtual motor", - eError); + pNew = + (pConfigurableVirtualMotor) malloc(sizeof(ConfigurableVirtualMotor)); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: no memory to create configurable virtual motor", + eError); return 0; } - memset(pNew,0,sizeof(ConfigurableVirtualMotor)); + memset(pNew, 0, sizeof(ConfigurableVirtualMotor)); pNew->name = strdup(argv[1]); pNew->posCount = 0; pNew->pDes = CreateDescriptor("ConfigurableVirtualMotor"); pNew->pDriv = CreateDrivableInterface(); pNew->motorList = LLDcreate(sizeof(RealMotor)); - if(pNew->pDes == NULL || pNew->pDriv == NULL || pNew->motorList < 0){ - SCWrite(pCon,"ERROR: no memory to create configurable virtual motor", - eError); + if (pNew->pDes == NULL || pNew->pDriv == NULL || pNew->motorList < 0) { + SCWrite(pCon, "ERROR: no memory to create configurable virtual motor", + eError); return 0; } /* - assign functions - */ + assign functions + */ pNew->pDes->GetInterface = GetConfigurableVirtualMotorInterface; pNew->pDriv->Halt = HaltMotors; pNew->pDriv->CheckLimits = ConfCheckLimits; @@ -474,21 +497,20 @@ int MakeConfigurableVirtualMotor(SConnection *pCon, SicsInterp *pSics, pNew->pDriv->CheckStatus = ConfCheckStatus; pNew->pDriv->GetValue = ConfGetValue; - /* initialise callback interface */ - pNew->pCall = CreateCallBackInterface(); - if(!pNew->pCall) - { - KillConfigurableVirtualMotor(pNew); - return 0; - } + /* initialise callback interface */ + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pCall) { + KillConfigurableVirtualMotor(pNew); + return 0; + } /* - install command - */ - if( AddCommand(pSics,argv[1],ConfigurableVirtualMotorAction, - KillConfigurableVirtualMotor,pNew) != 1){ - snprintf(pBueffel,510,"ERROR: duplicate command %s not created", - argv[1]); - SCWrite(pCon,pBueffel,eError); + install command + */ + if (AddCommand(pSics, argv[1], ConfigurableVirtualMotorAction, + KillConfigurableVirtualMotor, pNew) != 1) { + snprintf(pBueffel, 510, "ERROR: duplicate command %s not created", + argv[1]); + SCWrite(pCon, pBueffel, eError); return 0; } else { SCSendOK(pCon); @@ -496,9 +518,11 @@ int MakeConfigurableVirtualMotor(SConnection *pCon, SicsInterp *pSics, return 1; } + /*-----------------------------------------------------------------------*/ -int ConfigurableVirtualMotorAction(SConnection *pCon, SicsInterp *pSics, - void *data, int argc, char *argv[]){ +int ConfigurableVirtualMotorAction(SConnection * pCon, SicsInterp * pSics, + void *data, int argc, char *argv[]) +{ pConfigurableVirtualMotor self = NULL; char pBueffel[512]; float value; @@ -506,84 +530,83 @@ int ConfigurableVirtualMotorAction(SConnection *pCon, SicsInterp *pSics, long lID; pRegisteredInfo pRegInfo = NULL; - self = (pConfigurableVirtualMotor)data; + self = (pConfigurableVirtualMotor) data; assert(self != NULL); - if(argc > 1){ + if (argc > 1) { strtolower(argv[1]); - if(strcmp(argv[1],"drivescript") == 0){ - if(argc > 2){ - /* set case */ - Arg2Text(argc-2,&argv[2],pBueffel,510); - self->scriptName = strdup(pBueffel); - SCSendOK(pCon); - return 1; - } else { - /* inquiry */ - if(self->scriptName == NULL){ - snprintf(pBueffel,510,"%s.drivescript = UNDEFINED", argv[0]); - SCWrite(pCon,pBueffel,eValue); - return 1; - } else { - snprintf(pBueffel,510,"%s.drivescript = %s", argv[0], - self->scriptName); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - }else if(strcmp(argv[1],"readscript") == 0){ - if(argc > 2){ - /* set case */ - Arg2Text(argc-2,&argv[2],pBueffel,510); - self->readScript = strdup(pBueffel); - SCSendOK(pCon); - return 1; - } else { - /* inquiry */ - if(self->readScript == NULL){ - snprintf(pBueffel,510,"%s.readscript = UNDEFINED", argv[0]); - SCWrite(pCon,pBueffel,eValue); - return 1; - } else { - snprintf(pBueffel,510,"%s.readscript = %s", argv[0], - self->readScript); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - } else if(strcmp(argv[1],"interest") == 0) - { - pRegInfo = (pRegisteredInfo)malloc(sizeof(RegisteredInfo)); - if(!pRegInfo) - { - SCWrite(pCon,"ERROR: out of memory in confvirtualmot.c",eError); - return 0; - } - pRegInfo->pName = strdup(argv[0]); - pRegInfo->pCon = SCCopyConnection(pCon); - value = ConfGetValue(self,pCon); - if(!iRet) - { - sprintf(pBueffel,"Failed to register interest, Reason:Error obtaining current position for %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pRegInfo->lastValue = value; - - lID = RegisterCallback(self->pCall, MOTDRIVE, - InterestCallback, pRegInfo, KillInfo); + if (strcmp(argv[1], "drivescript") == 0) { + if (argc > 2) { + /* set case */ + Arg2Text(argc - 2, &argv[2], pBueffel, 510); + self->scriptName = strdup(pBueffel); SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,5120,"ERROR: subcommand %s to %s unknown", - argv[1],argv[0]); - SCWrite(pCon,pBueffel,eError); + return 1; + } else { + /* inquiry */ + if (self->scriptName == NULL) { + snprintf(pBueffel, 510, "%s.drivescript = UNDEFINED", argv[0]); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + snprintf(pBueffel, 510, "%s.drivescript = %s", argv[0], + self->scriptName); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + } else if (strcmp(argv[1], "readscript") == 0) { + if (argc > 2) { + /* set case */ + Arg2Text(argc - 2, &argv[2], pBueffel, 510); + self->readScript = strdup(pBueffel); + SCSendOK(pCon); + return 1; + } else { + /* inquiry */ + if (self->readScript == NULL) { + snprintf(pBueffel, 510, "%s.readscript = UNDEFINED", argv[0]); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + snprintf(pBueffel, 510, "%s.readscript = %s", argv[0], + self->readScript); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + } else if (strcmp(argv[1], "interest") == 0) { + pRegInfo = (pRegisteredInfo) malloc(sizeof(RegisteredInfo)); + if (!pRegInfo) { + SCWrite(pCon, "ERROR: out of memory in confvirtualmot.c", eError); + return 0; + } + pRegInfo->pName = strdup(argv[0]); + pRegInfo->pCon = SCCopyConnection(pCon); + value = ConfGetValue(self, pCon); + if (!iRet) { + sprintf(pBueffel, + "Failed to register interest, Reason:Error obtaining current position for %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pRegInfo->lastValue = value; + + lID = RegisterCallback(self->pCall, MOTDRIVE, + InterestCallback, pRegInfo, KillInfo); + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 5120, "ERROR: subcommand %s to %s unknown", + argv[1], argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } } else { - value = self->pDriv->GetValue(self,pCon); - snprintf(pBueffel,510,"%s = %f", argv[0],value); - SCWrite(pCon,pBueffel,eValue); + value = self->pDriv->GetValue(self, pCon); + snprintf(pBueffel, 510, "%s = %f", argv[0], value); + SCWrite(pCon, pBueffel, eValue); return 1; } } diff --git a/conman.c b/conman.c index e0cef426..26876b2c 100644 --- a/conman.c +++ b/conman.c @@ -80,7 +80,7 @@ extern pServer pServ; -#include "outcode.c" /* text for OutCode */ +#include "outcode.c" /* text for OutCode */ /*------ Max Size of Command Stack */ @@ -90,609 +90,580 @@ extern pServer pServ; /*------------------------------------------------------------------------- a structure for holding callback info */ - typedef struct { - long lID; - pICallBack pInterface; - } Item; +typedef struct { + long lID; + pICallBack pInterface; +} Item; /*------------- a number for generating automatic names --------------------*/ - static int iName = 0; - static long lastIdent = 0; +static int iName = 0; +static long lastIdent = 0; /*------------- sending connection (prevent double write when listening) ----*/ - static SConnection *sendingConnection = NULL; +static SConnection *sendingConnection = NULL; /*------------- storing connection and context for later use ----*/ - struct SCStore { - SConnection *pCon; - long ident; - int inMacro; - long macroStack; - commandContext cc; - }; +struct SCStore { + SConnection *pCon; + long ident; + int inMacro; + long macroStack; + commandContext cc; +}; /*===========================================================================*/ - static char *ConName(long ident) { - static char name[32]; - snprintf(name, sizeof(name), "CON%ld", ident); - return name; - } +static char *ConName(long ident) +{ + static char name[32]; + snprintf(name, sizeof(name), "CON%ld", ident); + return name; +} + /*--------------------------------------------------------------------------*/ - static void FreeConnection(SConnection *pCon) - { - free(pCon); - } +static void FreeConnection(SConnection * pCon) +{ + free(pCon); +} + /*------------------------------------------------------------------------*/ - void KillFreeConnections() - { - } +void KillFreeConnections() +{ +} + /*-------------------------------------------------------------------------*/ static SConnection *SCMakeConnection() { - SConnection *pRes = NULL; - - pRes = (SConnection *)malloc(sizeof(SConnection)); - if(!pRes) - { - /* This is a serious, very serious error! */ - SICSLogWrite("ERROR: No memory to allocate connection!!",eInternal); - return NULL; - } - memset(pRes,0,sizeof(SConnection)); - return pRes; -} -/*--------------------------------------------------------------------------*/ - static SConnection *CreateConnection(SicsInterp *pSics) - { - int i; - SConnection *pRes = NULL; - char pBueffel[253]; - char pHost[132]; - - pRes = SCMakeConnection(); - - do - { /* loop until an unused ident is found. This test needed only for - the case there some object has already the name con. - In a live cycle of SICS, no connection ever can get an earlier - used name */ - if (lastIdent == LONG_MAX) - { - /* This is a serious, very serious error! */ - SICSLogWrite("ERROR: Run out of connection identifiers!!",eInternal); - return NULL; - } - lastIdent++; - } while (FindCommand(pSics, ConName(lastIdent))); - pRes->ident = lastIdent; - - /* a descriptor */ - pRes->pDes = CreateDescriptor("Connection"); - if(!pRes->pDes) - { - /* This is a serious, very serious error! */ - SICSLogWrite("ERROR: No memory to allocate connection!!",eInternal); - FreeConnection(pRes); - return NULL; - } - - /* the callback registry */ - pRes->iList = LLDcreate(sizeof(Item)); - - /* the command stack */ - pRes->pStack = CreateCommandStack(); - if( (pRes->iList <0) || (!pRes->pStack)) - { - /* This is a serious, very serious error! */ - SICSLogWrite("ERROR: No memory to allocate connection!!",eInternal); - DeleteDescriptor(pRes->pDes); - FreeConnection(pRes); - return NULL; - } + SConnection *pRes = NULL; - pRes->iOutput = eInError; /* gets everything except internal messages */ - pRes->inUse = 0; - pRes->iMacro = 0; - pRes->iTelnet = 0; - pRes->eInterrupt = eContinue; - pRes->lMagic = CONMAGIC; - pRes->iLogin = 0; - pRes->listening = 0; - pRes->conStart = time(NULL); - pRes->write = SCNormalWrite; - - /* initialise context variables */ - pRes->iCmdCtr = 0; - pRes->conEventType=-1; - pRes->conStatus=-1; - pRes->contextStack = LLDcreate(sizeof(commandContext)); - - /* install command */ - AddCommand(pSics, ConName(pRes->ident), ConSicsAction, NULL,pRes); - return pRes; - + pRes = (SConnection *) malloc(sizeof(SConnection)); + if (!pRes) { + /* This is a serious, very serious error! */ + SICSLogWrite("ERROR: No memory to allocate connection!!", eInternal); + return NULL; } -/*--------------------------------------------------------------------------*/ - SConnection *SCreateConnection(SicsInterp *pSics,int sockHandle, int iUser) - { - SConnection *pRes = NULL; - char pBueffel[253]; - char pHost[132]; - - pRes = CreateConnection(pSics); - - SetCommandStackMaxSize(pRes->pStack,MAXSTACK); + memset(pRes, 0, sizeof(SConnection)); + return pRes; +} - pRes->sockHandle = sockHandle; - pRes->iUserRights = iUser; - pRes->iGrab = TokenGrabActive(); - return pRes; +/*--------------------------------------------------------------------------*/ +static SConnection *CreateConnection(SicsInterp * pSics) +{ + int i; + SConnection *pRes = NULL; + char pBueffel[253]; + char pHost[132]; + + pRes = SCMakeConnection(); + + do { /* loop until an unused ident is found. This test needed only for + the case there some object has already the name con. + In a live cycle of SICS, no connection ever can get an earlier + used name */ + if (lastIdent == LONG_MAX) { + /* This is a serious, very serious error! */ + SICSLogWrite("ERROR: Run out of connection identifiers!!", + eInternal); + return NULL; + } + lastIdent++; + } while (FindCommand(pSics, ConName(lastIdent))); + pRes->ident = lastIdent; + + /* a descriptor */ + pRes->pDes = CreateDescriptor("Connection"); + if (!pRes->pDes) { + /* This is a serious, very serious error! */ + SICSLogWrite("ERROR: No memory to allocate connection!!", eInternal); + FreeConnection(pRes); + return NULL; } + + /* the callback registry */ + pRes->iList = LLDcreate(sizeof(Item)); + + /* the command stack */ + pRes->pStack = CreateCommandStack(); + if ((pRes->iList < 0) || (!pRes->pStack)) { + /* This is a serious, very serious error! */ + SICSLogWrite("ERROR: No memory to allocate connection!!", eInternal); + DeleteDescriptor(pRes->pDes); + FreeConnection(pRes); + return NULL; + } + + pRes->iOutput = eInError; /* gets everything except internal messages */ + pRes->inUse = 0; + pRes->iMacro = 0; + pRes->iTelnet = 0; + pRes->eInterrupt = eContinue; + pRes->lMagic = CONMAGIC; + pRes->iLogin = 0; + pRes->listening = 0; + pRes->conStart = time(NULL); + pRes->write = SCNormalWrite; + + /* initialise context variables */ + pRes->iCmdCtr = 0; + pRes->conEventType = -1; + pRes->conStatus = -1; + pRes->contextStack = LLDcreate(sizeof(commandContext)); + + /* install command */ + AddCommand(pSics, ConName(pRes->ident), ConSicsAction, NULL, pRes); + return pRes; + +} + /*--------------------------------------------------------------------------*/ - SConnection *SCCreateDummyConnection(SicsInterp *pSics) - { - SConnection *pRes = NULL; - - pRes = CreateConnection(pSics); - - pRes->sockHandle = -1; - pRes->iUserRights = usInternal; - pRes->iGrab = 0; - - SICSLogWrite("Accepted dummy connection ",eInternal); - - return pRes; - } +SConnection *SCreateConnection(SicsInterp * pSics, int sockHandle, + int iUser) +{ + SConnection *pRes = NULL; + char pBueffel[253]; + char pHost[132]; + + pRes = CreateConnection(pSics); + + SetCommandStackMaxSize(pRes->pStack, MAXSTACK); + + pRes->sockHandle = sockHandle; + pRes->iUserRights = iUser; + pRes->iGrab = TokenGrabActive(); + return pRes; +} + /*--------------------------------------------------------------------------*/ - int VerifyConnection(SConnection *self) - { - if(!self) - { - SICSLogWrite("MAGICERROR: Invalid call to NULL connection",eError); - return 0; - } - if(self->lMagic != CONMAGIC) - { - SICSLogWrite("MAGICERROR: corrupted connection object",eError); - return 0; - } - return 1; - } +SConnection *SCCreateDummyConnection(SicsInterp * pSics) +{ + SConnection *pRes = NULL; + + pRes = CreateConnection(pSics); + + pRes->sockHandle = -1; + pRes->iUserRights = usInternal; + pRes->iGrab = 0; + + SICSLogWrite("Accepted dummy connection ", eInternal); + + return pRes; +} + +/*--------------------------------------------------------------------------*/ +int VerifyConnection(SConnection * self) +{ + if (!self) { + SICSLogWrite("MAGICERROR: Invalid call to NULL connection", eError); + return 0; + } + if (self->lMagic != CONMAGIC) { + SICSLogWrite("MAGICERROR: corrupted connection object", eError); + return 0; + } + return 1; +} + /*----------------------------------------------------------------------------*/ - void SCSetOutputClass(SConnection *self, int iClass) - { - if(!VerifyConnection(self)) - { - return; - } - self->iOutput = iClass; +void SCSetOutputClass(SConnection * self, int iClass) +{ + if (!VerifyConnection(self)) { + return; } + self->iOutput = iClass; +} + /*---------------------------------------------------------------------------*/ - int SCinMacro(SConnection *self) - { - if(!VerifyConnection(self)) - { - return 0; - } - - if(self->iMacro) - { +int SCinMacro(SConnection * self) +{ + if (!VerifyConnection(self)) { + return 0; + } + + if (self->iMacro) { + return 1; + } else { + return 0; + } +} + +/*---------------------------------------------------------------------------*/ +int SCsetMacro(SConnection * self, int iMode) +{ + if (!VerifyConnection(self)) { + return 0; + } + assert((iMode == 0) || (iMode == 1)); + self->iMacro = iMode; +/* SCPrintf(self,eError, "SCsetMacro = %lx, %d\n", (long int)self, iMode); */ + return 1; +} + + /*--------------------------------------------------------------------------*/ +void SCDeleteMasterFields(SConnection * pVictim) +{ + int iRet; + Item sItem; + pHdb root = NULL; + char pBueffel[512]; + + if (pVictim->pDes == NULL) { + return; + } + + if (SCActive(pVictim)) { + SCnoSock(pVictim); + ANETclose(pVictim->sockHandle); + WriteToCommandLog("SYS>", + "ERROR: Erraneous deletion of used Connection stopped"); + pVictim->sockHandle = -1; + return; + } + + /* remove the connection from the server log if it has captured + something + */ + KillCapture(pVictim); + + /* + * remove any callbacks which might still be active in the Hipadaba + */ + root = GetHipadabaRoot(); + if (root != NULL) { + RemoveConnectionCallbacks(root, pVictim); + } + + /* + If we have a grab, release it ! + */ + if (!pVictim->iGrab) { + if (pServ->pTasker) { + TaskSignal(pServ->pTasker, TOKENRELEASE, NULL); + TokenRelease(); + } + } + + /* log the kill */ + if (pVictim->sockHandle >= 0 && pVictim->iLogin == 1 && + (pVictim->iUserRights < 3 || !CompactCommandLog())) { + sprintf(pBueffel, "Deleting connection %d", pVictim->sockHandle); + WriteToCommandLog("SYS>", pBueffel); + SICSLogWrite(pBueffel, eInternal); + } + + /* close all open files and sockets */ + if (pVictim->sockHandle > 0) { + ANETwrite(pVictim->sockHandle, "SICSCLOSE", sizeof("SICSCLOSE")); + ANETprocess(); + ANETclose(pVictim->sockHandle); + } + RemoveCommand(pServ->pSics, ConName(pVictim->ident)); + /* remove all callbacks on this connection */ + iRet = LLDnodePtr2First(pVictim->iList); + while (iRet != 0) { + LLDnodeDataTo(pVictim->iList, &sItem); + RemoveCallback(sItem.pInterface, sItem.lID); + iRet = LLDnodePtr2Next(pVictim->iList); + } + LLDdelete(pVictim->iList); + LLDdelete(pVictim->contextStack); + DeleteDescriptor(pVictim->pDes); + +} + +/*---------------------------------------------------------------------------*/ +void SCDeleteConnection(void *pData) +{ + int i, iRet; + char pBueffel[132]; + SConnection *pVictim = NULL; + + pVictim = (SConnection *) pData; + if (!VerifyConnection(pVictim)) { + return; + } + + SCDeleteMasterFields(pVictim); + + /* remove command stack */ + if (pVictim->pStack != NULL) { + DeleteCommandStack(pVictim->pStack); + } + + /* remove possible buffers */ + if (pVictim->data != NULL) { + DeleteDynString(pVictim->data); + } + + pVictim->lMagic = 0; /* make a write to a freed connection harmless */ + /* finally free pVictim */ + FreeConnection(pVictim); +} + +/*--------------------------------------------------------------------------*/ +SConnection *SCCopyConnection(SConnection * pCon) +{ + SConnection *result = NULL; + + result = SCMakeConnection(); + if (result == NULL) { + return NULL; + } + result->sockHandle = pCon->sockHandle; + result->lMagic = pCon->lMagic; + result->iUserRights = pCon->iUserRights; + result->ident = pCon->ident; + result->iMacro = pCon->iMacro; + result->iTelnet = pCon->iTelnet; + result->iOutput = pCon->iOutput; + result->write = pCon->write; + result->listening = pCon->listening; + result->eInterrupt = pCon->eInterrupt; + result->inUse = pCon->inUse; + result->sicsError = pCon->sicsError; + result->iCmdCtr = pCon->iCmdCtr; + result->conEventType = pCon->conEventType; + result->conStatus = pCon->conStatus; + result->iProtocolID = pCon->iProtocolID; + result->transID = pCon->transID; + strcpy(result->deviceID, pCon->deviceID); + result->conStart = pCon->conStart; + result->contextStack = -1; + result->iList = -1; + return result; +} + +/*---------------------------------------------------------------------------*/ +SConnection *SCfindMaster(SConnection * pCon) +{ + SConnection *result = NULL; + result = + (SConnection *) FindCommandData(pServ->pSics, ConName(pCon->ident), + "Connection"); + if (result == NULL) { + printf("VERY, Very, very serious programming error!\n"); + printf("I continue but things may be wrong! Please debug ASAP!\n"); + if (pServ->dummyCon == NULL) { + pServ->dummyCon = SCCreateDummyConnection(pServ->pSics); + } + result = pServ->dummyCon; + } + return result; +} + +/*---------------------------------------------------------------------------*/ +int SCisConnected(SConnection * pCon) +{ + if (!VerifyConnection(pCon)) { + return 0; + } + return ANETvalidHandle(pCon->sockHandle); +} + +/*---------------------------------------------------------------------------*/ +static int HasNL(char *buffer) +{ + int i; + for (i = strlen(buffer); i > 0; i--) { + if (isprint(buffer[i])) { + break; + } + if (buffer[i] == '\n') { return 1; } - else - { - return 0; - } - } -/*---------------------------------------------------------------------------*/ - int SCsetMacro(SConnection *self, int iMode) - { - if(!VerifyConnection(self)) - { - return 0; - } - assert( (iMode == 0) || (iMode == 1)); - self->iMacro = iMode; -/* SCPrintf(self,eError, "SCsetMacro = %lx, %d\n", (long int)self, iMode); */ - return 1; - } - /*--------------------------------------------------------------------------*/ - void SCDeleteMasterFields(SConnection *pVictim) - { - int iRet; - Item sItem; - pHdb root = NULL; - char pBueffel[512]; - - if(pVictim->pDes == NULL) - { - return; - } - - if(SCActive(pVictim)) - { - SCnoSock(pVictim); - ANETclose(pVictim->sockHandle); - WriteToCommandLog("SYS>", - "ERROR: Erraneous deletion of used Connection stopped"); - pVictim->sockHandle = -1; - return; - } - - /* remove the connection from the server log if it has captured - something - */ - KillCapture(pVictim); - - /* - * remove any callbacks which might still be active in the Hipadaba - */ - root = GetHipadabaRoot(); - if(root != NULL) - { - RemoveConnectionCallbacks(root,pVictim); - } - - /* - If we have a grab, release it ! - */ - if(!pVictim->iGrab) - { - if(pServ->pTasker) - { - TaskSignal(pServ->pTasker,TOKENRELEASE,NULL); - TokenRelease(); - } - } - - /* log the kill */ - if(pVictim->sockHandle >= 0 && pVictim->iLogin == 1 && - (pVictim->iUserRights < 3 || !CompactCommandLog()) ) - { - sprintf(pBueffel,"Deleting connection %d",pVictim->sockHandle); - WriteToCommandLog("SYS>",pBueffel); - SICSLogWrite(pBueffel,eInternal); - } - - /* close all open files and sockets */ - if(pVictim->sockHandle > 0) - { - ANETwrite(pVictim->sockHandle,"SICSCLOSE",sizeof("SICSCLOSE")); - ANETprocess(); - ANETclose(pVictim->sockHandle); - } - RemoveCommand(pServ->pSics,ConName(pVictim->ident)); - /* remove all callbacks on this connection */ - iRet = LLDnodePtr2First(pVictim->iList); - while(iRet != 0) - { - LLDnodeDataTo(pVictim->iList,&sItem); - RemoveCallback(sItem.pInterface, sItem.lID); - iRet = LLDnodePtr2Next(pVictim->iList); - } - LLDdelete(pVictim->iList); - LLDdelete(pVictim->contextStack); - DeleteDescriptor(pVictim->pDes); - } -/*---------------------------------------------------------------------------*/ - void SCDeleteConnection(void *pData) - { - int i, iRet; - char pBueffel[132]; - SConnection *pVictim = NULL; - - pVictim = (SConnection *)pData; - if(!VerifyConnection(pVictim)) - { - return; - } - - SCDeleteMasterFields(pVictim); - - /* remove command stack */ - if(pVictim->pStack != NULL) - { - DeleteCommandStack(pVictim->pStack); - } - - /* remove possible buffers */ - if(pVictim->data != NULL) - { - DeleteDynString(pVictim->data); - } - - pVictim->lMagic=0; /* make a write to a freed connection harmless */ - /* finally free pVictim*/ - FreeConnection(pVictim); - } -/*--------------------------------------------------------------------------*/ -SConnection *SCCopyConnection(SConnection *pCon){ - SConnection *result = NULL; - - result = SCMakeConnection(); - if(result == NULL){ - return NULL; - } - result->sockHandle = pCon->sockHandle; - result->lMagic = pCon->lMagic; - result->iUserRights = pCon->iUserRights; - result->ident = pCon->ident; - result->iMacro = pCon->iMacro; - result->iTelnet = pCon->iTelnet; - result->iOutput = pCon->iOutput; - result->write = pCon->write; - result->listening = pCon->listening; - result->eInterrupt = pCon->eInterrupt; - result->inUse = pCon->inUse; - result->sicsError = pCon->sicsError; - result->iCmdCtr = pCon->iCmdCtr; - result->conEventType = pCon->conEventType; - result->conStatus = pCon->conStatus; - result->iProtocolID = pCon->iProtocolID; - result->transID = pCon->transID; - strcpy(result->deviceID, pCon->deviceID); - result->conStart = pCon->conStart; - result->contextStack = -1; - result->iList = -1; - return result; + return 0; } -/*---------------------------------------------------------------------------*/ -SConnection *SCfindMaster(SConnection *pCon) -{ - SConnection *result = NULL; - result = (SConnection *)FindCommandData(pServ->pSics,ConName(pCon->ident),"Connection"); - if(result == NULL) - { - printf("VERY, Very, very serious programming error!\n"); - printf("I continue but things may be wrong! Please debug ASAP!\n"); - if(pServ->dummyCon == NULL){ - pServ->dummyCon = SCCreateDummyConnection(pServ->pSics); - } - result = pServ->dummyCon; - } - return result; -} -/*---------------------------------------------------------------------------*/ -int SCisConnected(SConnection *pCon) -{ - if(!VerifyConnection(pCon)) - { - return 0; - } - return ANETvalidHandle(pCon->sockHandle); -} -/*---------------------------------------------------------------------------*/ - static int HasNL(char *buffer) - { - int i; - for(i = strlen(buffer); i > 0; i--) - { - if(isprint(buffer[i])) - { - break; - } - if(buffer[i] == '\n') - { - return 1; - } - } - return 0; - } + /*------------------------------------------------------------------------- TelnetWrite makes sure, that all lines are properly terminated with a as required by the telnet protocoll. There may be a problem here at long messages. 7.5.1998 MK ---------------------------------------------------------------------------*/ +--------------------------------------------------------------------------*/ #define TXT 0 #define LF 1 - int TelnetWrite(mkChannel *pSock, char *pBuffer) - { - char *pStart = NULL, *pPtr; - int iCount, iState; - int iRet = 1; - - pStart = pBuffer; - pPtr = pStart; - iState = TXT; - iCount = 0; - while(*pPtr != '\0') - { - switch(iState) - { - case TXT: - if( (*pPtr == '\r') || (*pPtr == '\n') ) - { - iState = LF; - iRet = NETWrite(pSock,pStart,iCount); - iRet = NETWrite(pSock,"\r\n",2); - iCount = 0; - } - else - { - iCount++; - } - break; - case LF: - if( (*pPtr != '\r') && (*pPtr != '\n') ) - { - pStart = pPtr; - iCount = 1; - iState = TXT; - } - else - { - /* do nothing */ - } - break; - } - pPtr++; - } - if(iCount > 0) - { - iRet = NETWrite(pSock,pStart,iCount); - iRet = NETWrite(pSock,"\r\n",2); - } - return iRet; - } +int TelnetWrite(mkChannel * pSock, char *pBuffer) +{ + char *pStart = NULL, *pPtr; + int iCount, iState; + int iRet = 1; + + pStart = pBuffer; + pPtr = pStart; + iState = TXT; + iCount = 0; + while (*pPtr != '\0') { + switch (iState) { + case TXT: + if ((*pPtr == '\r') || (*pPtr == '\n')) { + iState = LF; + iRet = NETWrite(pSock, pStart, iCount); + iRet = NETWrite(pSock, "\r\n", 2); + iCount = 0; + } else { + iCount++; + } + break; + case LF: + if ((*pPtr != '\r') && (*pPtr != '\n')) { + pStart = pPtr; + iCount = 1; + iState = TXT; + } else { + /* do nothing */ + } + break; + } + pPtr++; + } + if (iCount > 0) { + iRet = NETWrite(pSock, pStart, iCount); + iRet = NETWrite(pSock, "\r\n", 2); + } + return iRet; +} + /*-----------------------------------------------------------*/ - int TelnetWriteANET(int sockHandle, char *pBuffer) - { - char *pStart = NULL, *pPtr; - int iCount, iState; - int iRet = 1; - - pStart = pBuffer; - pPtr = pStart; - iState = TXT; - iCount = 0; - while(*pPtr != '\0') - { - switch(iState) - { - case TXT: - if( (*pPtr == '\r') || (*pPtr == '\n') ) - { - iState = LF; - iRet = ANETwrite(sockHandle,pStart,iCount); - iRet = ANETwrite(sockHandle,"\r\n",2); - iCount = 0; - } - else - { - iCount++; - } - break; - case LF: - if( (*pPtr != '\r') && (*pPtr != '\n') ) - { - pStart = pPtr; - iCount = 1; - iState = TXT; - } - else - { - /* do nothing */ - } - break; - } - pPtr++; - } - if(iCount > 0) - { - iRet = ANETwrite(sockHandle,pStart,iCount); - iRet = ANETwrite(sockHandle,"\r\n",2); - } - return iRet; - } -/*-------------------------------------------------------------------------*/ - int SCWrite(SConnection *self, char *pBuffer, int iOut) - { - if(!VerifyConnection(self)) - { - return 0; +int TelnetWriteANET(int sockHandle, char *pBuffer) +{ + char *pStart = NULL, *pPtr; + int iCount, iState; + int iRet = 1; + + pStart = pBuffer; + pPtr = pStart; + iState = TXT; + iCount = 0; + while (*pPtr != '\0') { + switch (iState) { + case TXT: + if ((*pPtr == '\r') || (*pPtr == '\n')) { + iState = LF; + iRet = ANETwrite(sockHandle, pStart, iCount); + iRet = ANETwrite(sockHandle, "\r\n", 2); + iCount = 0; + } else { + iCount++; } - /* - Do not die if no data - */ - if(pBuffer == NULL) - { - return 0; + break; + case LF: + if ((*pPtr != '\r') && (*pPtr != '\n')) { + pStart = pPtr; + iCount = 1; + iState = TXT; + } else { + /* do nothing */ } - return self->write(self,pBuffer,iOut); + break; + } + pPtr++; } + if (iCount > 0) { + iRet = ANETwrite(sockHandle, pStart, iCount); + iRet = ANETwrite(sockHandle, "\r\n", 2); + } + return iRet; +} + +/*-------------------------------------------------------------------------*/ +int SCWrite(SConnection * self, char *pBuffer, int iOut) +{ + if (!VerifyConnection(self)) { + return 0; + } + /* + Do not die if no data + */ + if (pBuffer == NULL) { + return 0; + } + return self->write(self, pBuffer, iOut); +} + /*-----------------------------------------------------------------------*/ -int SCWriteInContext(SConnection *pCon, char *pBuffer, int out, commandContext cc) +int SCWriteInContext(SConnection * pCon, char *pBuffer, int out, + commandContext cc) { - int status; - int transID; - char oldDevice[256]; - - transID = pCon->transID; - strcpy(oldDevice,pCon->deviceID); - pCon->transID = cc.transID; - strncpy(pCon->deviceID, cc.deviceID,SCDEVIDLEN); - status = SCWrite(pCon,pBuffer,out); - pCon->transID = transID; - strncpy(pCon->deviceID, oldDevice,SCDEVIDLEN); - return status; + int status; + int transID; + char oldDevice[256]; + + transID = pCon->transID; + strcpy(oldDevice, pCon->deviceID); + pCon->transID = cc.transID; + strncpy(pCon->deviceID, cc.deviceID, SCDEVIDLEN); + status = SCWrite(pCon, pBuffer, out); + pCon->transID = transID; + strncpy(pCon->deviceID, oldDevice, SCDEVIDLEN); + return status; } + /*-------------------------------------------------------------------------*/ - int SCPrintf(SConnection *self, int iOut, char *fmt, ...) - { - va_list ap; - char buf[256]; - char *dyn; - int l; - int res; - +int SCPrintf(SConnection * self, int iOut, char *fmt, ...) +{ + va_list ap; + char buf[256]; + char *dyn; + int l; + int res; + + va_start(ap, fmt); + l = vsnprintf(buf, sizeof buf, fmt, ap); + va_end(ap); + if (l >= sizeof buf) { + /* we have probably a C99 conforming snprintf and + need a larger buffer + */ + dyn = malloc(l + 1); + if (dyn != NULL) { va_start(ap, fmt); - l = vsnprintf(buf, sizeof buf, fmt, ap); + vsnprintf(dyn, l + 1, fmt, ap); va_end(ap); - if (l >= sizeof buf) { - /* we have probably a C99 conforming snprintf and - need a larger buffer - */ - dyn = malloc(l+1); - if (dyn != NULL) { - va_start(ap, fmt); - vsnprintf(dyn, l+1, fmt, ap); - va_end(ap); - res = SCWrite(self, dyn, iOut); - free(dyn); - return res; - } - } - return SCWrite(self, buf, iOut); + res = SCWrite(self, dyn, iOut); + free(dyn); + return res; + } } -/*-------------------------------------------------------------------------*/ -writeFunc SCGetWriteFunc(SConnection *self) -{ - if(!VerifyConnection(self)) - { - return 0; - } - return self->write; + return SCWrite(self, buf, iOut); } + /*-------------------------------------------------------------------------*/ -void SCSetWriteFunc(SConnection *self, writeFunc x) +writeFunc SCGetWriteFunc(SConnection * self) { - if(!VerifyConnection(self)) - { - return; - } - self->write = x; + if (!VerifyConnection(self)) { + return 0; + } + return self->write; } + +/*-------------------------------------------------------------------------*/ +void SCSetWriteFunc(SConnection * self, writeFunc x) +{ + if (!VerifyConnection(self)) { + return; + } + self->write = x; +} + /*------------------------------------------------------------------------*/ -static int doSockWrite(SConnection *self, char *buffer) +static int doSockWrite(SConnection * self, char *buffer) { int iRet = 1; - if(self->sockHandle >= 0) - { - if(self->iTelnet) - { - iRet = TelnetWriteANET(self->sockHandle,buffer); - } - else - { - iRet = ANETwrite(self->sockHandle,buffer,strlen(buffer)); - if(!HasNL(buffer)) - { - iRet = ANETwrite(self->sockHandle,"\n",strlen("\n")); - } - } - if(!iRet) - { - SCnoSock(self); - if(!self->listening && self->iLogin == 1 && - (self->iUserRights < 3 || !CompactCommandLog()) ) - { - WriteToCommandLog("SYS>","Connection broken on send"); + if (self->sockHandle >= 0) { + if (self->iTelnet) { + iRet = TelnetWriteANET(self->sockHandle, buffer); + } else { + iRet = ANETwrite(self->sockHandle, buffer, strlen(buffer)); + if (!HasNL(buffer)) { + iRet = ANETwrite(self->sockHandle, "\n", strlen("\n")); } } - } - else - { + if (!iRet) { + SCnoSock(self); + if (!self->listening && self->iLogin == 1 && + (self->iUserRights < 3 || !CompactCommandLog())) { + WriteToCommandLog("SYS>", "Connection broken on send"); + } + } + } else { if (HasNL(buffer)) { fputs(buffer, stdout); } else { @@ -701,736 +672,710 @@ static int doSockWrite(SConnection *self, char *buffer) } return iRet; } + /*--------------------------------------------------------------------------*/ -static void testAndWriteCommandLog(SConnection *pCon, char *buffer, int iOut) +static void testAndWriteCommandLog(SConnection * pCon, char *buffer, + int iOut) { - if(SCGetRights(pCon) <= usUser){ - if(SCinMacro(pCon) != 1){ - WriteToCommandLogId(NULL,pCon->sockHandle, buffer); - } else { - if(iOut == eLog || iOut == eLogError){ - WriteToCommandLogId(NULL,pCon->sockHandle, buffer); - } - } - } + if (SCGetRights(pCon) <= usUser) { + if (SCinMacro(pCon) != 1) { + WriteToCommandLogId(NULL, pCon->sockHandle, buffer); + } else { + if (iOut == eLog || iOut == eLogError) { + WriteToCommandLogId(NULL, pCon->sockHandle, buffer); + } + } + } } + /*--------------------------------------------------------------------------*/ -static void testAndStoreInTcl(SConnection *pCon, char *buffer, int iOut) +static void testAndStoreInTcl(SConnection * pCon, char *buffer, int iOut) { - if(SCinMacro(pCon)){ - if(iOut == eValue || iOut == eError){ - InterpWrite(pServ->pSics,buffer); - } - } + if (SCinMacro(pCon)) { + if (iOut == eValue || iOut == eError) { + InterpWrite(pServ->pSics, buffer); + } + } } + /*-------------------------------------------------------------------------*/ -static int testAndWriteSocket(SConnection *pCon, char *buffer, int iOut) +static int testAndWriteSocket(SConnection * pCon, char *buffer, int iOut) { - switch(iOut){ - case eStatus: - case eStart: - case eFinish: - case eEvent: - case eHdbValue: - case eHdbEvent: - case eLog: - case eLogError: - return doSockWrite(pCon,buffer); - break; - case eValue: - case eError: - case eWarning: - if(!SCinMacro(pCon) && iOut >= pCon->iOutput){ - return doSockWrite(pCon,buffer); - } else { - return 0; - } - break; - } - printf("Unrecognized ouput code in testAndWriteSocket: FIX!!!\n"); - return 0; + switch (iOut) { + case eStatus: + case eStart: + case eFinish: + case eEvent: + case eHdbValue: + case eHdbEvent: + case eLog: + case eLogError: + return doSockWrite(pCon, buffer); + break; + case eValue: + case eError: + case eWarning: + if (!SCinMacro(pCon) && iOut >= pCon->iOutput) { + return doSockWrite(pCon, buffer); + } else { + return 0; + } + break; + } + printf("Unrecognized ouput code %d in testAndWriteSocket: FIX!!!\n", iOut); + return 0; } + /*--------------------------------------------------------------------------*/ - int SCNormalWrite(SConnection *self, char *buffer, int iOut) - { - int i, iPtr, iRet; +int SCNormalWrite(SConnection * self, char *buffer, int iOut) +{ + int i, iPtr, iRet; - if(!VerifyConnection(self)) - { - return 0; - } - - if (buffer[0] == '\0' && iOut >= eStart && iOut <= eEvent) { - return 1; /* do not write empty line */ - } - - /* log it for any case */ - SICSLogWrite(buffer,iOut); - - testAndWriteCommandLog(self,buffer,iOut); - - testAndStoreInTcl(self,buffer,iOut); - - testAndWriteSocket(self,buffer,iOut); - - return 1; + if (!VerifyConnection(self)) { + return 0; } + + if (buffer[0] == '\0' && iOut >= eStart && iOut <= eEvent) { + return 1; /* do not write empty line */ + } + + /* log it for any case */ + SICSLogWrite(buffer, iOut); + + testAndWriteCommandLog(self, buffer, iOut); + + testAndStoreInTcl(self, buffer, iOut); + + testAndWriteSocket(self, buffer, iOut); + + return 1; +} + /*--------------------------------------------------------------------------*/ - int SCACTWrite(SConnection *self, char *buffer, int iOut) - { - int i, iPtr, iRet; - char pBueffel[1024]; - char *pPtr = pBueffel; - commandContext cx; - - if(!VerifyConnection(self)) - { - return 0; - } +int SCACTWrite(SConnection * self, char *buffer, int iOut) +{ + int i, iPtr, iRet; + char pBueffel[1024]; + char *pPtr = pBueffel; + commandContext cx; - if (buffer[0] == '\0' && iOut >= eStart && iOut <= eEvent) { - return 1; /* do not write empty line */ - } - - /* log it for any case */ - sprintf(pBueffel,"Next line intended for socket: %d",self->sockHandle); - SICSLogWrite(buffer,iOut); - - testAndWriteCommandLog(self,buffer,iOut); - - testAndStoreInTcl(self,buffer, iOut); - - /* - * copy in ACT - */ - if(strlen(buffer) + 30 > 1024){ - pPtr = (char *)malloc((strlen(buffer)+30)*sizeof(char)); - memset(pPtr,0,strlen(buffer)+20); - } - sprintf(pPtr,"%d::>%s<::", self->transID, buffer); - - testAndWriteSocket(self,pPtr, iOut); - - if(pPtr != pBueffel){ - free(pPtr); - } - return 1; + if (!VerifyConnection(self)) { + return 0; } + + if (buffer[0] == '\0' && iOut >= eStart && iOut <= eEvent) { + return 1; /* do not write empty line */ + } + + /* log it for any case */ + sprintf(pBueffel, "Next line intended for socket: %d", self->sockHandle); + SICSLogWrite(buffer, iOut); + + testAndWriteCommandLog(self, buffer, iOut); + + testAndStoreInTcl(self, buffer, iOut); + + /* + * copy in ACT + */ + if (strlen(buffer) + 30 > 1024) { + pPtr = (char *) malloc((strlen(buffer) + 30) * sizeof(char)); + memset(pPtr, 0, strlen(buffer) + 20); + } + sprintf(pPtr, "%d::>%s<::", self->transID, buffer); + + testAndWriteSocket(self, pPtr, iOut); + + if (pPtr != pBueffel) { + free(pPtr); + } + return 1; +} + /*--------------------------------------------------------------------------*/ - int SCWriteWithOutcode(SConnection *self, char *buffer, int iOut) - { - int i, iPtr, iRet, length; - char pBueffel[80]; - char *bufPtr = NULL; +int SCWriteWithOutcode(SConnection * self, char *buffer, int iOut) +{ + int i, iPtr, iRet, length; + char pBueffel[80]; + char *bufPtr = NULL; - if(!VerifyConnection(self)) - { - return 0; - } - - if (buffer[0] == '\0' && iOut >= eStart && iOut <= eEvent) { - return 1; /* do not write empty line */ - } - - /* log it for any case */ - sprintf(pBueffel,"Next line intended for socket: %d",self->sockHandle); - SICSLogWrite(pBueffel,eInternal); - SICSLogWrite(buffer,iOut); - - testAndWriteCommandLog(self,buffer,iOut); - - testAndStoreInTcl(self, buffer, iOut); - /* - prepare the message with the outcode appended. - */ - length = strlen(buffer) + strlen(pCode[iOut]) + 10; - bufPtr = (char *)malloc(length * sizeof(char)); - if(!bufPtr) - { - SICSLogWrite("SYS>>ERROR: out of memory in SCWriteWithOutcode",eError); - return 0; - } - memset(bufPtr,0,length*sizeof(char)); - strcpy(bufPtr,buffer); - i = strlen(bufPtr); - while(i-- > 0) - { - if(!isspace(bufPtr[i])) - break; - } - i++; - bufPtr[i] = '\0'; - strcat(bufPtr,"@@"); - strcat(bufPtr,pCode[iOut]); - strcat(bufPtr,"\r\n"); - - testAndWriteSocket(self, bufPtr, iOut); - - free(bufPtr); - return 1; + if (!VerifyConnection(self)) { + return 0; } + + if (buffer[0] == '\0' && iOut >= eStart && iOut <= eEvent) { + return 1; /* do not write empty line */ + } + + /* log it for any case */ + sprintf(pBueffel, "Next line intended for socket: %d", self->sockHandle); + SICSLogWrite(pBueffel, eInternal); + SICSLogWrite(buffer, iOut); + + testAndWriteCommandLog(self, buffer, iOut); + + testAndStoreInTcl(self, buffer, iOut); + /* + prepare the message with the outcode appended. + */ + length = strlen(buffer) + strlen(pCode[iOut]) + 10; + bufPtr = (char *) malloc(length * sizeof(char)); + if (!bufPtr) { + SICSLogWrite("SYS>>ERROR: out of memory in SCWriteWithOutcode", + eError); + return 0; + } + memset(bufPtr, 0, length * sizeof(char)); + strcpy(bufPtr, buffer); + i = strlen(bufPtr); + while (i-- > 0) { + if (!isspace(bufPtr[i])) + break; + } + i++; + bufPtr[i] = '\0'; + strcat(bufPtr, "@@"); + strcat(bufPtr, pCode[iOut]); + strcat(bufPtr, "\r\n"); + + testAndWriteSocket(self, bufPtr, iOut); + + free(bufPtr); + return 1; +} + /*-------------------------------------------------------------------------*/ -static int SCBufferWrite(SConnection *self, char *buffer, int iOut) +static int SCBufferWrite(SConnection * self, char *buffer, int iOut) { - if(!VerifyConnection(self)) - { - return 0; - } - assert(self->data != NULL); - DynStringConcat(self->data,buffer); - if(strchr(buffer,'\n') == NULL){ - DynStringConcat(self->data,"\n"); - } - return 1; -} -/*-------------------------------------------------------------------------*/ -int SCStartBuffering(SConnection *pCon) -{ - if(!VerifyConnection(pCon)) - { - return 0; - } - if(pCon->data != NULL) - { - DeleteDynString(pCon->data); - } - pCon->data = CreateDynString(128,128); - if(pCon->data == NULL) - { - return 0; - } - pCon->oldWriteFunc = pCon->write; - pCon->write = SCBufferWrite; - return 1; -} -/*-------------------------------------------------------------------------*/ -pDynString SCEndBuffering(SConnection *pCon) -{ - if(!VerifyConnection(pCon)) - { - return 0; - } - assert(pCon->oldWriteFunc != NULL); - pCon->write = pCon->oldWriteFunc; - pCon->oldWriteFunc = NULL; - return pCon->data; -} -/*--------------------------------------------------------------------------*/ - int SCOnlySockWrite(SConnection *self, char *buffer, int iOut) - { - int i, iPtr, iRet; - char pBueffel[80]; - - if(!VerifyConnection(self)) - { - return 0; - } - - /* log it for any case */ - sprintf(pBueffel,"Next line intended for socket: %d",self->sockHandle); - SICSLogWrite(pBueffel,eInternal); - SICSLogWrite(buffer,iOut); - - testAndStoreInTcl(self, buffer, iOut); - - testAndWriteSocket(self, buffer, iOut); - - return 1; + if (!VerifyConnection(self)) { + return 0; } -/*--------------------------------------------------------------------------*/ - int SCNotWrite(SConnection *self, char *buffer, int iOut) - { - int i, iPtr, iRet; - char pBueffel[80]; - - if(!VerifyConnection(self)) - { - return 0; - } - - /* log it for any case */ - sprintf(pBueffel,"Next line intended for socket: %d",self->sockHandle); - SICSLogWrite(pBueffel,eInternal); - SICSLogWrite(buffer,iOut); - - testAndStoreInTcl(self, buffer, iOut); - return 1; + assert(self->data != NULL); + DynStringConcat(self->data, buffer); + if (strchr(buffer, '\n') == NULL) { + DynStringConcat(self->data, "\n"); } + return 1; +} + +/*-------------------------------------------------------------------------*/ +int SCStartBuffering(SConnection * pCon) +{ + if (!VerifyConnection(pCon)) { + return 0; + } + if (pCon->data != NULL) { + DeleteDynString(pCon->data); + } + pCon->data = CreateDynString(128, 128); + if (pCon->data == NULL) { + return 0; + } + pCon->oldWriteFunc = pCon->write; + pCon->write = SCBufferWrite; + return 1; +} + +/*-------------------------------------------------------------------------*/ +pDynString SCEndBuffering(SConnection * pCon) +{ + if (!VerifyConnection(pCon)) { + return 0; + } + assert(pCon->oldWriteFunc != NULL); + pCon->write = pCon->oldWriteFunc; + pCon->oldWriteFunc = NULL; + return pCon->data; +} + +/*--------------------------------------------------------------------------*/ +int SCOnlySockWrite(SConnection * self, char *buffer, int iOut) +{ + int i, iPtr, iRet; + char pBueffel[80]; + + if (!VerifyConnection(self)) { + return 0; + } + + /* log it for any case */ + sprintf(pBueffel, "Next line intended for socket: %d", self->sockHandle); + SICSLogWrite(pBueffel, eInternal); + SICSLogWrite(buffer, iOut); + + testAndStoreInTcl(self, buffer, iOut); + + testAndWriteSocket(self, buffer, iOut); + + return 1; +} + +/*--------------------------------------------------------------------------*/ +int SCNotWrite(SConnection * self, char *buffer, int iOut) +{ + int i, iPtr, iRet; + char pBueffel[80]; + + if (!VerifyConnection(self)) { + return 0; + } + + /* log it for any case */ + sprintf(pBueffel, "Next line intended for socket: %d", self->sockHandle); + SICSLogWrite(pBueffel, eInternal); + SICSLogWrite(buffer, iOut); + + testAndStoreInTcl(self, buffer, iOut); + return 1; +} + /*-------------------------------------------------------------------------- This version writes only to configured log files but not to sockets. Used for automatic file execution for the WWW interface */ - int SCFileWrite(SConnection *self, char *buffer, int iOut) - { - int i, iPtr, iRet; - char pBueffel[80]; +int SCFileWrite(SConnection * self, char *buffer, int iOut) +{ + int i, iPtr, iRet; + char pBueffel[80]; - if(!VerifyConnection(self)) - { - return 0; - } - - /* log it for any case */ - sprintf(pBueffel,"Next line intended for socket: %d",self->sockHandle); - SICSLogWrite(pBueffel,eInternal); - - SICSLogWrite(buffer,iOut); - - testAndWriteCommandLog(self,buffer,iOut); - - testAndStoreInTcl(self, buffer, iOut); - - testAndWriteSocket(self, buffer, iOut); - - return 1; + if (!VerifyConnection(self)) { + return 0; } + + /* log it for any case */ + sprintf(pBueffel, "Next line intended for socket: %d", self->sockHandle); + SICSLogWrite(pBueffel, eInternal); + + SICSLogWrite(buffer, iOut); + + testAndWriteCommandLog(self, buffer, iOut); + + testAndStoreInTcl(self, buffer, iOut); + + testAndWriteSocket(self, buffer, iOut); + + return 1; +} + /*-----------------------------------------------------------------------*/ - int SCnoSock(SConnection *self) - { - if(!VerifyConnection(self)) - { - return 0; - } - self->write = SCFileWrite; - return 0; +int SCnoSock(SConnection * self) +{ + if (!VerifyConnection(self)) { + return 0; + } + self->write = SCFileWrite; + return 0; +} + +/*------------------------------------------------------------------------*/ +int SCWriteUUencoded(SConnection * pCon, char *pName, void *pData, + int iDataLen) +{ + void *pPtr = NULL; + int iLength = 0; + int iRet = 1; + FILE *fd; + char *pTest; + + iRet = UUencodeBuffer(pData, iDataLen, pName, &pPtr, &iLength); + if (iRet != 1) { + SCWrite(pCon, "ERROR: no memory for uuencoder", eError); + return 0; + } + pTest = (char *) pPtr; + + /* the uuencoder ensures proper telnet */ + if (pCon->iTelnet) { + ANETwrite(pCon->sockHandle, pPtr, iLength); + } else { + ANETwrite(pCon->sockHandle, pPtr, iLength); } -/*------------------------------------------------------------------------*/ - int SCWriteUUencoded(SConnection *pCon, char *pName, void *pData, - int iDataLen) - { - void *pPtr = NULL; - int iLength = 0; - int iRet = 1; - FILE *fd; - char *pTest; - - iRet = UUencodeBuffer(pData,iDataLen,pName, &pPtr, &iLength); - if(iRet != 1) - { - SCWrite(pCon,"ERROR: no memory for uuencoder",eError); - return 0; - } - pTest = (char *)pPtr; - /* the uuencoder ensures proper telnet */ - if(pCon->iTelnet) - { - ANETwrite(pCon->sockHandle,pPtr,iLength); - } - else - { - ANETwrite(pCon->sockHandle,pPtr,iLength); - } - #ifdef UUDEB - fd = fopen("uubuffer.uu","w"); - fputs(pPtr,fd); - fclose(fd); -#endif - - free(pPtr); - return iRet; - } + fd = fopen("uubuffer.uu", "w"); + fputs(pPtr, fd); + fclose(fd); +#endif + + free(pPtr); + return iRet; +} + /*------------------------------------------------------------------------*/ #define ZIPBUF 8192 - int SCWriteZipped(SConnection *self, char *pName, void *pData, int iDataLen) - { - char outBuf[65546], *pBuf = NULL, noutBuf[ZIPBUF], *pHeader = NULL; - int compressedLength, iRet, iRet2, iCount, protocolID; - z_stream compStream; - commandContext cc; - - /* check for a valid connection */ - if(!VerifyConnection(self)) - { - return 0; - } +int SCWriteZipped(SConnection * self, char *pName, void *pData, + int iDataLen) +{ + char outBuf[65546], *pBuf = NULL, noutBuf[ZIPBUF], *pHeader = NULL; + int compressedLength, iRet, iRet2, iCount, protocolID; + z_stream compStream; + commandContext cc; - /* a telnet connection will corrupt the compressed stream, so - stop it! - */ - if(self->iTelnet) - { - SCWrite(self, - "ERROR: the telnet protocoll will currupt compressed data!", - eError); - return 0; - } - - /* - do nothing if no data - */ - if(pName == NULL || pData == NULL) - { - SCWrite(self,"ERROR: no data to write in SCWriteZiped",eError); - return 0; - } - - /* initialize the compression stuff */ - compStream.zalloc = (alloc_func)NULL; - compStream.zfree = (free_func)NULL; - compStream.opaque = (voidpf)NULL; - - iRet = deflateInit(&compStream,Z_DEFAULT_COMPRESSION); - if(iRet != Z_OK) - { - sprintf(outBuf,"ERROR: zlib error: %d",iRet); - SCWrite(self,outBuf,eError); - return 0; - } - - /* first pass: find out how the long the compressed buffer will be */ - compressedLength = 0; - compStream.next_in = (Bytef *)pData; - compStream.next_out = (Bytef *)outBuf; - compStream.avail_in = iDataLen; - compStream.avail_out = 65536; - while(compStream.total_in < iDataLen) - { - iRet = deflate(&compStream,Z_NO_FLUSH); - if(iRet != Z_OK) - { - sprintf(outBuf,"ERROR: zlib error: %d",iRet); - SCWrite(self,outBuf,eError); - return 0; - } - compStream.next_out = (Bytef *)outBuf; - compStream.avail_out = 65536; - } - for(;;) - { - iRet = deflate(&compStream,Z_FINISH); - if(iRet == Z_STREAM_END) break; - if(iRet != Z_OK) - { - sprintf(outBuf,"ERROR: zlib error: %d",iRet); - SCWrite(self,outBuf,eError); - return 0; - } - } - compressedLength = compStream.total_out; - deflateEnd(&compStream); - - /* write header line */ - memset(outBuf,0,65536); - - protocolID = GetProtocolID(self); - if(protocolID == 5){ - cc = SCGetContext(self); - sprintf(outBuf,"SICSBIN ZIP %s %d %d\r\n",pName, - compressedLength, cc.transID); - } else { - sprintf(outBuf,"SICSBIN ZIP %s %d \r\n",pName,compressedLength); - } - pHeader = strdup(outBuf); - if(pHeader == NULL) - { - SCWrite(self,"ERROR: out of memory in SCWriteZipped",eError); - return 0; - } - - /* now reset the deflater and do the same with writing data */ - compStream.zalloc = (alloc_func)NULL; - compStream.zfree = (free_func)NULL; - compStream.opaque = (voidpf)NULL; - - - /* - This is writing everything in one go as I found that writing in - several chunks did not ensure that all the data arrived at the - Java side. - */ - - iRet = deflateInit(&compStream,Z_DEFAULT_COMPRESSION); - if(iRet != Z_OK) - { - sprintf(outBuf,"ERROR: zlib error: %d",iRet); - SCWrite(self,outBuf,eError); - return 0; - } - - pBuf = (char *)malloc((iDataLen + iDataLen/10 + 50)*sizeof(char)); - memset(pBuf,0,(iDataLen + iDataLen/10 + 50)*sizeof(char) ); - compStream.next_in = (Bytef *)pData; - compStream.next_out = (Bytef *)pBuf; - compStream.avail_in = iDataLen; - compStream.avail_out = iDataLen + iDataLen/10 + 50; - iRet = deflate(&compStream,Z_FINISH); - if(iRet != Z_STREAM_END) - { - sprintf(outBuf,"ERROR: zlib error: %d",iRet); - SCWrite(self,outBuf,eError); - return 0; - } - iRet = ANETwrite(self->sockHandle,pHeader,strlen(pHeader)); - iRet = ANETwrite(self->sockHandle,pBuf,compStream.total_out); - if(iRet != 1) - { - sprintf(outBuf,"ERROR: network error %d on zipped send",iRet); - SCWrite(self,outBuf,eError); - return 0; - } - deflateEnd(&compStream); - free(pHeader); - free(pBuf); - - return 1; + /* check for a valid connection */ + if (!VerifyConnection(self)) { + return 0; } -/*-------------------------------------------------------------------------*/ - int SCSendOK(SConnection *self) - { - return SCWrite(self,"OK",eValue); - } -/*--------------------------------------------------------------------------*/ - int SCRead(SConnection *self, char *buffer, int iLen) - { - - int iRet; - if(!VerifyConnection(self)) - { - return 0; + /* a telnet connection will corrupt the compressed stream, so + stop it! + */ + if (self->iTelnet) { + SCWrite(self, + "ERROR: the telnet protocoll will currupt compressed data!", + eError); + return 0; + } + + /* + do nothing if no data + */ + if (pName == NULL || pData == NULL) { + SCWrite(self, "ERROR: no data to write in SCWriteZiped", eError); + return 0; + } + + /* initialize the compression stuff */ + compStream.zalloc = (alloc_func) NULL; + compStream.zfree = (free_func) NULL; + compStream.opaque = (voidpf) NULL; + + iRet = deflateInit(&compStream, Z_DEFAULT_COMPRESSION); + if (iRet != Z_OK) { + sprintf(outBuf, "ERROR: zlib error: %d", iRet); + SCWrite(self, outBuf, eError); + return 0; + } + + /* first pass: find out how the long the compressed buffer will be */ + compressedLength = 0; + compStream.next_in = (Bytef *) pData; + compStream.next_out = (Bytef *) outBuf; + compStream.avail_in = iDataLen; + compStream.avail_out = 65536; + while (compStream.total_in < iDataLen) { + iRet = deflate(&compStream, Z_NO_FLUSH); + if (iRet != Z_OK) { + sprintf(outBuf, "ERROR: zlib error: %d", iRet); + SCWrite(self, outBuf, eError); + return 0; } - - if(self->sockHandle < 0) - { - printf("SICS>> "); - fgets(buffer,iLen-1,stdin); + compStream.next_out = (Bytef *) outBuf; + compStream.avail_out = 65536; + } + for (;;) { + iRet = deflate(&compStream, Z_FINISH); + if (iRet == Z_STREAM_END) + break; + if (iRet != Z_OK) { + sprintf(outBuf, "ERROR: zlib error: %d", iRet); + SCWrite(self, outBuf, eError); + return 0; + } + } + compressedLength = compStream.total_out; + deflateEnd(&compStream); + + /* write header line */ + memset(outBuf, 0, 65536); + + protocolID = GetProtocolID(self); + if (protocolID == 5) { + cc = SCGetContext(self); + sprintf(outBuf, "SICSBIN ZIP %s %d %d\r\n", pName, + compressedLength, cc.transID); + } else { + sprintf(outBuf, "SICSBIN ZIP %s %d \r\n", pName, compressedLength); + } + pHeader = strdup(outBuf); + if (pHeader == NULL) { + SCWrite(self, "ERROR: out of memory in SCWriteZipped", eError); + return 0; + } + + /* now reset the deflater and do the same with writing data */ + compStream.zalloc = (alloc_func) NULL; + compStream.zfree = (free_func) NULL; + compStream.opaque = (voidpf) NULL; + + + /* + This is writing everything in one go as I found that writing in + several chunks did not ensure that all the data arrived at the + Java side. + */ + + iRet = deflateInit(&compStream, Z_DEFAULT_COMPRESSION); + if (iRet != Z_OK) { + sprintf(outBuf, "ERROR: zlib error: %d", iRet); + SCWrite(self, outBuf, eError); + return 0; + } + + pBuf = (char *) malloc((iDataLen + iDataLen / 10 + 50) * sizeof(char)); + memset(pBuf, 0, (iDataLen + iDataLen / 10 + 50) * sizeof(char)); + compStream.next_in = (Bytef *) pData; + compStream.next_out = (Bytef *) pBuf; + compStream.avail_in = iDataLen; + compStream.avail_out = iDataLen + iDataLen / 10 + 50; + iRet = deflate(&compStream, Z_FINISH); + if (iRet != Z_STREAM_END) { + sprintf(outBuf, "ERROR: zlib error: %d", iRet); + SCWrite(self, outBuf, eError); + return 0; + } + iRet = ANETwrite(self->sockHandle, pHeader, strlen(pHeader)); + iRet = ANETwrite(self->sockHandle, pBuf, compStream.total_out); + if (iRet != 1) { + sprintf(outBuf, "ERROR: network error %d on zipped send", iRet); + SCWrite(self, outBuf, eError); + return 0; + } + deflateEnd(&compStream); + free(pHeader); + free(pBuf); + + return 1; +} + +/*-------------------------------------------------------------------------*/ +int SCSendOK(SConnection * self) +{ + return SCWrite(self, "OK", eValue); +} + +/*--------------------------------------------------------------------------*/ +int SCRead(SConnection * self, char *buffer, int iLen) +{ + + int iRet; + + if (!VerifyConnection(self)) { + return 0; + } + + if (self->sockHandle < 0) { + printf("SICS>> "); + fgets(buffer, iLen - 1, stdin); + return 1; + } + + if (self->sockHandle >= 0) { + iRet = ANETread(self->sockHandle, buffer, iLen); + if (iRet == 0) { /* no data */ + return 0; + } else if (iRet < 0) { /* eof */ + return EOF; + } else { /* data */ + return 1; } - - if(self->sockHandle >= 0) - { - iRet = ANETread(self->sockHandle,buffer,iLen); - if(iRet == 0) /* no data */ - { - return 0; - } - else if(iRet < 0) /* eof */ - { - return EOF; - } - else /* data */ - { - return 1; - } - } - else - { - return EOF; - /* fgets(buffer,iLen,stdin); */ - } - return 1; + } else { + return EOF; + /* fgets(buffer,iLen,stdin); */ } -/*----------------------------------------------------------------------------*/ - int SCMatchRights(SConnection *pCon, int iCode) - { - char pBueffel[132]; - - if(!VerifyConnection(pCon)) - { - return 0; - } - - if(iCode < SCGetRights(pCon)) - { - sprintf(pBueffel,"ERROR: you are not authorised for this operation"); - SCWrite(pCon, pBueffel, eError); - return 0; - } - if(pCon->iGrab) - { - sprintf(pBueffel, - "ERROR: Request refused, control has been grabbed by somebody else"); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } + return 1; +} /*----------------------------------------------------------------------------*/ - int SCPrompt(SConnection *pCon, char *pPrompt, char *pResult, int iLen) - { - - int iRet, i; - char *pPtr = NULL; - char pFrom[50]; - Status eOld; - int oldMode; +int SCMatchRights(SConnection * pCon, int iCode) +{ + char pBueffel[132]; - if(!VerifyConnection(pCon)) - { - return 0; - } + if (!VerifyConnection(pCon)) { + return 0; + } - SCWrite(pCon,pPrompt,eWarning); - eOld = GetStatus(); - SetStatus(eInput); - CostaUnlock(pCon->pStack); - while(1) - { - /* - wait a second. We want to wait even in a simulation, otherwise - we go into an endless loop. This is why there is the hack with - oldMode and pServ->simMode. - */ - oldMode = pServ->simMode; - pServ->simMode = 0; - SicsWait(1); - pServ->simMode = oldMode; + if (iCode < SCGetRights(pCon)) { + sprintf(pBueffel, "ERROR: you are not authorised for this operation"); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (pCon->iGrab) { + sprintf(pBueffel, + "ERROR: Request refused, control has been grabbed by somebody else"); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} - /* is there an interrupt pending ? */ - if(SCGetInterrupt(pCon) != eContinue) - { - break; - } - /* do we have data ? */ - iRet = CostaPop(pCon->pStack,&pPtr); - if(iRet == 1) - { - SetStatus(eOld); - CostaLock(pCon->pStack); - strncpy(pResult,pPtr,iLen); - WriteToCommandLogId(" prompted>", pCon->sockHandle, pPtr); - return 1; - } - } - SetStatus(eOld); - CostaLock(pCon->pStack); - return 0; - } -/*---------------------------------------------------------------------------*/ - int SCGetRights(SConnection *self) - { - if(!VerifyConnection(self)) - { - return 0; - } - - return self->iUserRights; +/*----------------------------------------------------------------------------*/ +int SCPrompt(SConnection * pCon, char *pPrompt, char *pResult, int iLen) +{ + + int iRet, i; + char *pPtr = NULL; + char pFrom[50]; + Status eOld; + int oldMode; + + if (!VerifyConnection(pCon)) { + return 0; } -/*---------------------------------------------------------------------------*/ - int SCGetGrab(SConnection *self) - { - if(!VerifyConnection(self)) - { - return 0; - } - - return self->iGrab; - } -/*--------------------------------------------------------------------------*/ - int SCSetRights(SConnection *self, int iNew) - { - if(!VerifyConnection(self)) - { - return 0; - } - assert(iNew >= usInternal); - assert(iNew <= usSpy); - - self->iUserRights = iNew; - return 1; - } -/*---------------------------------------------------------------------------*/ - int SCGetOutClass(SConnection *self) - { - if(!VerifyConnection(self)) - { - return 0; - } - return self->iOutput; - } -/*--------------------------------------------------------------------------*/ - void SCSetInterrupt(SConnection *self, int eCode) - { - SConnection *pCon = NULL; - if(!VerifyConnection(self)) - { - return; - } - pCon = SCfindMaster(self); - pCon->eInterrupt = eCode; - } -/*---------------------------------------------------------------------------*/ - int SCGetInterrupt(SConnection *self) - { - SConnection *pCon = NULL; - if(!VerifyConnection(self)) - { - return 0; - } - pCon = SCfindMaster(self); - return pCon->eInterrupt; - } - /*----------------------------------------------------------------*/ - extern char *trim(char *in); -/* --------------------------------------------------------------------------*/ - int SCInvoke(SConnection *self, SicsInterp *pInter, char *pCommand) - { - int iRet; - long lLen; - const char *pResult = NULL; - char *pBuffer = NULL, *pFile = NULL; - char pBueffel[80]; - int i, iSpace; - SConnection *pCopy = NULL; - - if(!VerifyConnection(self)) - { - return 0; - } - assert(pInter); - - - /* print to command log if user or manager */ - if(SCGetRights(self) <= usUser) - { - /* - * This is a fix to suppress cron messages in the success - * case - */ - if(SCGetWriteFunc(self) != SCNotWrite) - { - sendingConnection = self; - if(self->sockHandle >= 0) - { - WriteToCommandLogCmd(self->sockHandle, pCommand); - } else { - WriteToCommandLog("CRON>>",pCommand); - } - sendingConnection = NULL; - } - } - - /* invoke */ - self->inUse++; - self->eInterrupt = eContinue; - /* - get first word of command + + SCWrite(pCon, pPrompt, eWarning); + eOld = GetStatus(); + SetStatus(eInput); + CostaUnlock(pCon->pStack); + while (1) { + /* + wait a second. We want to wait even in a simulation, otherwise + we go into an endless loop. This is why there is the hack with + oldMode and pServ->simMode. */ - memset(pBueffel,0,80); - stptok(trim(pCommand),pBueffel,79," "); - self->iCmdCtr++; - if(999999 < self->iCmdCtr){ - self->iCmdCtr = 0; - } - self->transID = self->iCmdCtr; - pCopy = SCCopyConnection(self); - if(pCopy == NULL){ - SCWrite(self,"ERROR: out of memory in SCInvoke",eError); - return 0; - } - strncpy(pCopy->deviceID, pBueffel,SCDEVIDLEN); - /* SCAdvanceContext(self,pBueffel); */ - iRet = InterpExecute(pInter,pCopy,pCommand); - /* SCPopContext(self); */ - SCDeleteConnection(pCopy); - StatusFileTask(NULL); /* save changed parameters */ + oldMode = pServ->simMode; + pServ->simMode = 0; + SicsWait(1); + pServ->simMode = oldMode; - self->inUse--; - return iRet; + /* is there an interrupt pending ? */ + if (SCGetInterrupt(pCon) != eContinue) { + break; + } + /* do we have data ? */ + iRet = CostaPop(pCon->pStack, &pPtr); + if (iRet == 1) { + SetStatus(eOld); + CostaLock(pCon->pStack); + strncpy(pResult, pPtr, iLen); + WriteToCommandLogId(" prompted>", pCon->sockHandle, pPtr); + return 1; + } } + SetStatus(eOld); + CostaLock(pCon->pStack); + return 0; +} + +/*---------------------------------------------------------------------------*/ +int SCGetRights(SConnection * self) +{ + if (!VerifyConnection(self)) { + return 0; + } + + return self->iUserRights; +} + +/*---------------------------------------------------------------------------*/ +int SCGetGrab(SConnection * self) +{ + if (!VerifyConnection(self)) { + return 0; + } + + return self->iGrab; +} + +/*--------------------------------------------------------------------------*/ +int SCSetRights(SConnection * self, int iNew) +{ + if (!VerifyConnection(self)) { + return 0; + } + assert(iNew >= usInternal); + assert(iNew <= usSpy); + + self->iUserRights = iNew; + return 1; +} + +/*---------------------------------------------------------------------------*/ +int SCGetOutClass(SConnection * self) +{ + if (!VerifyConnection(self)) { + return 0; + } + return self->iOutput; +} + +/*--------------------------------------------------------------------------*/ +void SCSetInterrupt(SConnection * self, int eCode) +{ + SConnection *pCon = NULL; + if (!VerifyConnection(self)) { + return; + } + pCon = SCfindMaster(self); + pCon->eInterrupt = eCode; +} + +/*---------------------------------------------------------------------------*/ +int SCGetInterrupt(SConnection * self) +{ + SConnection *pCon = NULL; + if (!VerifyConnection(self)) { + return 0; + } + pCon = SCfindMaster(self); + return pCon->eInterrupt; +} + + /*----------------------------------------------------------------*/ +extern char *trim(char *in); +/* --------------------------------------------------------------------------*/ +int SCInvoke(SConnection * self, SicsInterp * pInter, char *pCommand) +{ + int iRet; + long lLen; + const char *pResult = NULL; + char *pBuffer = NULL, *pFile = NULL; + char pBueffel[80]; + int i, iSpace; + SConnection *pCopy = NULL; + + if (!VerifyConnection(self)) { + return 0; + } + assert(pInter); + + + /* print to command log if user or manager */ + if (SCGetRights(self) <= usUser) { + /* + * This is a fix to suppress cron messages in the success + * case + */ + if (SCGetWriteFunc(self) != SCNotWrite) { + sendingConnection = self; + if (self->sockHandle >= 0) { + WriteToCommandLogCmd(self->sockHandle, pCommand); + } else { + WriteToCommandLog("CRON>>", pCommand); + } + sendingConnection = NULL; + } + } + + /* invoke */ + self->inUse++; + self->eInterrupt = eContinue; + /* + get first word of command + */ + memset(pBueffel, 0, 80); + stptok(trim(pCommand), pBueffel, 79, " "); + self->iCmdCtr++; + if (999999 < self->iCmdCtr) { + self->iCmdCtr = 0; + } + self->transID = self->iCmdCtr; + pCopy = SCCopyConnection(self); + if (pCopy == NULL) { + SCWrite(self, "ERROR: out of memory in SCInvoke", eError); + return 0; + } + strncpy(pCopy->deviceID, pBueffel, SCDEVIDLEN); + /* SCAdvanceContext(self,pBueffel); */ + iRet = InterpExecute(pInter, pCopy, pCommand); + /* SCPopContext(self); */ + SCDeleteConnection(pCopy); + StatusFileTask(NULL); /* save changed parameters */ + + self->inUse--; + return iRet; +} + /*--------------------------------------------------------------------------- For configuring connections. Syntax: config OutCode val sets an new output code @@ -1439,624 +1384,547 @@ pDynString SCEndBuffering(SConnection *pCon) config output normal | withcode | ACT Sets output mode config listen 0 | 1 enables commandlog listen mode ---------------------------------------------------------------------------*/ - - int ConfigCon(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - char pHost[132]; - int i, iRet; - int iNum; - SConnection *pMaster = NULL; - - if(!VerifyConnection(pCon)) - { - return 0; - } - assert(pSics); - - /* check no of args */ - if(argc < 2) - { - sprintf(pBueffel,"Insufficient number of args to %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pMaster = SCfindMaster(pCon); - - /* handle list*/ - strtolower(argv[1]); - if(strcmp(argv[1],"list") == 0) - { - sprintf(pBueffel,"OutCode = %s\nUserRights = %d", - pCode[pCon->iOutput], SCGetRights(pCon)); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else if(strcmp(argv[1],"myname") == 0) - { - sprintf(pBueffel,"MyName = %s",ConName(pCon->ident)); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else if(strcmp(argv[1],"myrights") == 0) - { - sprintf(pBueffel,"UserRights = %d",SCGetRights(pCon)); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else if(strcmp(argv[1],"listen") == 0) - { - if(argc < 3) - { - snprintf(pBueffel,511,"listen = %d", pCon->listening); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { - pCon->listening = atoi(argv[2]); - if(pCon->listening != 0 && pCon->listening != 1) - { - pCon->listening = 0; - SCWrite(pCon,"ERROR: config listen only accepts 0 or 1 as arguments",eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - } - /* check no or args */ - if(argc < 3) - { - sprintf(pBueffel,"Insufficient number of args to %s",argv[0]); - SCWrite(pCon,pBueffel,eInError); - return 0; - } - - if(strcmp(argv[1],"outcode") == 0) - { - i = 0; - strtolower(argv[2]); - while(pCode[i] != NULL) - { - if(strcmp(pCode[i],argv[2]) == 0) - { - break; - } - i++; - } - if( i > iNoCodes) - { - sprintf(pBueffel,"OutCode %s not recognized",argv[2]); - SCWrite(pCon,pBueffel,eInError); - return 0; - } - pCon->iOutput = i; - pMaster->iOutput = i; - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"output") == 0) - { - strtolower(argv[2]); - if(strcmp(argv[2],"normal") == 0) - { - SCSetWriteFunc(pCon,SCNormalWrite); - SCSetWriteFunc(pMaster,SCNormalWrite); - } - else if(strcmp(argv[2],"withcode") == 0) - { - SCSetWriteFunc(pCon,SCWriteWithOutcode); - SCSetWriteFunc(pMaster,SCWriteWithOutcode); - } - else if(strcmp(argv[2],"act") == 0) - { - SCSetWriteFunc(pCon,SCACTWrite); - SCSetWriteFunc(pMaster,SCACTWrite); - } - else - { - SCWrite(pCon,"ERROT: output mode not recognised",eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"rights") == 0) - { - if(argc < 4) - { - sprintf(pBueffel,"Insufficient number of args to %s",argv[0]); - SCWrite(pCon,pBueffel,eInError); - return 0; - } - i = IsValidUser(argv[2],argv[3]); - if(i < 0) - { - sprintf(pBueffel," %s with password ****** is NO valid User on SICS", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if (CompactCommandLog()) { - if (pCon->iUserRights < 3 || i < 3) { - ANETinfo(pCon->sockHandle,pHost,sizeof pHost); - sprintf(pBueffel,"User %s from %s switched to %d privilege", - argv[2],pHost,i); - snprintf(pBueffel,512,"User at %d switched to %d privilige", - pCon->sockHandle, i); - WriteToCommandLogId("SYS>",pCon->sockHandle,pBueffel); - } - } else { - sprintf(pBueffel,"User %s handle %d switched to %d privilege", - argv[2],pCon->sockHandle,i); - WriteToCommandLog("SYS>",pBueffel); - } - pCon->iUserRights = i; - pMaster->iUserRights = i; - SCWrite(pCon,"Change of Authorisation Acknowledged",eWarning); - return 1; - } - SCWrite(pCon,"Command not recognized",eError); - return 0; - } +int ConfigCon(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512]; + char pHost[132]; + int i, iRet; + int iNum; + SConnection *pMaster = NULL; + + if (!VerifyConnection(pCon)) { + return 0; + } + assert(pSics); + + /* check no of args */ + if (argc < 2) { + sprintf(pBueffel, "Insufficient number of args to %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pMaster = SCfindMaster(pCon); + + /* handle list */ + strtolower(argv[1]); + if (strcmp(argv[1], "list") == 0) { + sprintf(pBueffel, "OutCode = %s\nUserRights = %d", + pCode[pCon->iOutput], SCGetRights(pCon)); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (strcmp(argv[1], "myname") == 0) { + sprintf(pBueffel, "MyName = %s", ConName(pCon->ident)); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (strcmp(argv[1], "myrights") == 0) { + sprintf(pBueffel, "UserRights = %d", SCGetRights(pCon)); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (strcmp(argv[1], "listen") == 0) { + if (argc < 3) { + snprintf(pBueffel, 511, "listen = %d", pCon->listening); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + pCon->listening = atoi(argv[2]); + if (pCon->listening != 0 && pCon->listening != 1) { + pCon->listening = 0; + SCWrite(pCon, + "ERROR: config listen only accepts 0 or 1 as arguments", + eError); + return 0; + } + SCSendOK(pCon); + return 1; + } + } + + /* check no or args */ + if (argc < 3) { + sprintf(pBueffel, "Insufficient number of args to %s", argv[0]); + SCWrite(pCon, pBueffel, eInError); + return 0; + } + + if (strcmp(argv[1], "outcode") == 0) { + i = 0; + strtolower(argv[2]); + while (pCode[i] != NULL) { + if (strcmp(pCode[i], argv[2]) == 0) { + break; + } + i++; + } + if (i > iNoCodes) { + sprintf(pBueffel, "OutCode %s not recognized", argv[2]); + SCWrite(pCon, pBueffel, eInError); + return 0; + } + pCon->iOutput = i; + pMaster->iOutput = i; + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "output") == 0) { + strtolower(argv[2]); + if (strcmp(argv[2], "normal") == 0) { + SCSetWriteFunc(pCon, SCNormalWrite); + SCSetWriteFunc(pMaster, SCNormalWrite); + } else if (strcmp(argv[2], "withcode") == 0) { + SCSetWriteFunc(pCon, SCWriteWithOutcode); + SCSetWriteFunc(pMaster, SCWriteWithOutcode); + } else if (strcmp(argv[2], "act") == 0) { + SCSetWriteFunc(pCon, SCACTWrite); + SCSetWriteFunc(pMaster, SCACTWrite); + } else { + SCWrite(pCon, "ERROT: output mode not recognised", eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "rights") == 0) { + if (argc < 4) { + sprintf(pBueffel, "Insufficient number of args to %s", argv[0]); + SCWrite(pCon, pBueffel, eInError); + return 0; + } + i = IsValidUser(argv[2], argv[3]); + if (i < 0) { + sprintf(pBueffel, + " %s with password ****** is NO valid User on SICS", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (CompactCommandLog()) { + if (pCon->iUserRights < 3 || i < 3) { + ANETinfo(pCon->sockHandle, pHost, sizeof pHost); + sprintf(pBueffel, "User %s from %s switched to %d privilege", + argv[2], pHost, i); + snprintf(pBueffel, 512, "User at %d switched to %d privilige", + pCon->sockHandle, i); + WriteToCommandLogId("SYS>", pCon->sockHandle, pBueffel); + } + } else { + sprintf(pBueffel, "User %s handle %d switched to %d privilege", + argv[2], pCon->sockHandle, i); + WriteToCommandLog("SYS>", pBueffel); + } + pCon->iUserRights = i; + pMaster->iUserRights = i; + SCWrite(pCon, "Change of Authorisation Acknowledged", eWarning); + return 1; + } + SCWrite(pCon, "Command not recognized", eError); + return 0; +} + /*----------------------------------------------------------------------*/ - int SCRegister(SConnection *pCon, SicsInterp *pSics, - void *pData, long lID) - { - pICallBack pInter = NULL; - Item sItem; - SConnection *pMaster = NULL; - - pInter = (pICallBack)pData; - if(!VerifyConnection(pCon)) - { - return 0; - } - assert(pSics); - assert(pInter); - - sItem.lID = lID; - sItem.pInterface = pInter; - pMaster = SCfindMaster(pCon); - LLDnodeAppendFrom(pMaster->iList,&sItem); - return 1; - } -/*----------------------------------------------------------------------*/ - int SCUnregister(SConnection *pCon, void *pData) - { - int iRet; - Item sItem; - pICallBack pInter; - SConnection *pMaster = NULL; - - if(!VerifyConnection(pCon)) - { - return 0; - } - pInter = (pICallBack)pData; - pMaster = SCfindMaster(pCon); +int SCRegister(SConnection * pCon, SicsInterp * pSics, + void *pData, long lID) +{ + pICallBack pInter = NULL; + Item sItem; + SConnection *pMaster = NULL; - iRet = LLDnodePtr2First(pMaster->iList); - while(iRet != 0) - { - LLDnodeDataTo(pMaster->iList,&sItem); - if(sItem.pInterface == pInter) - { - LLDnodeDelete(pMaster->iList); - LLDnodePtr2Prev(pMaster->iList); - } - iRet = LLDnodePtr2Next(pMaster->iList); - } - return 1; + pInter = (pICallBack) pData; + if (!VerifyConnection(pCon)) { + return 0; } -/*----------------------------------------------------------------------*/ - int SCUnregisterID(SConnection *pCon, long ID) - { - int iRet; - Item sItem; - SConnection *pMaster = NULL; - - if(!VerifyConnection(pCon)) - { - return 0; - } - pMaster = SCfindMaster(pCon); - iRet = LLDnodePtr2First(pMaster->iList); - while(iRet != 0) - { - LLDnodeDataTo(pMaster->iList,&sItem); - if(sItem.lID == ID ) - { - LLDnodeDelete(pMaster->iList); - LLDnodePtr2Prev(pMaster->iList); - } - iRet = LLDnodePtr2Next(pMaster->iList); - } - return 1; + assert(pSics); + assert(pInter); + + sItem.lID = lID; + sItem.pInterface = pInter; + pMaster = SCfindMaster(pCon); + LLDnodeAppendFrom(pMaster->iList, &sItem); + return 1; +} + +/*----------------------------------------------------------------------*/ +int SCUnregister(SConnection * pCon, void *pData) +{ + int iRet; + Item sItem; + pICallBack pInter; + SConnection *pMaster = NULL; + + if (!VerifyConnection(pCon)) { + return 0; } -/*----------------------------------------------------------------------*/ - long SCgetCallbackID(SConnection *pCon, void *pData) - { - int iRet; - Item sItem; - pICallBack pInter; - SConnection *pMaster = NULL; - - if(!VerifyConnection(pCon)) - { - return 0; + pInter = (pICallBack) pData; + pMaster = SCfindMaster(pCon); + + iRet = LLDnodePtr2First(pMaster->iList); + while (iRet != 0) { + LLDnodeDataTo(pMaster->iList, &sItem); + if (sItem.pInterface == pInter) { + LLDnodeDelete(pMaster->iList); + LLDnodePtr2Prev(pMaster->iList); } - pMaster = SCfindMaster(pCon); - pInter = (pICallBack)pData; - iRet = LLDnodePtr2First(pMaster->iList); - while(iRet != 0) - { - LLDnodeDataTo(pMaster->iList,&sItem); - if(sItem.pInterface == pInter) - { - return sItem.lID; - } - iRet = LLDnodePtr2Next(pMaster->iList); - } - return -1; + iRet = LLDnodePtr2Next(pMaster->iList); } + return 1; +} + +/*----------------------------------------------------------------------*/ +int SCUnregisterID(SConnection * pCon, long ID) +{ + int iRet; + Item sItem; + SConnection *pMaster = NULL; + + if (!VerifyConnection(pCon)) { + return 0; + } + pMaster = SCfindMaster(pCon); + iRet = LLDnodePtr2First(pMaster->iList); + while (iRet != 0) { + LLDnodeDataTo(pMaster->iList, &sItem); + if (sItem.lID == ID) { + LLDnodeDelete(pMaster->iList); + LLDnodePtr2Prev(pMaster->iList); + } + iRet = LLDnodePtr2Next(pMaster->iList); + } + return 1; +} + +/*----------------------------------------------------------------------*/ +long SCgetCallbackID(SConnection * pCon, void *pData) +{ + int iRet; + Item sItem; + pICallBack pInter; + SConnection *pMaster = NULL; + + if (!VerifyConnection(pCon)) { + return 0; + } + pMaster = SCfindMaster(pCon); + pInter = (pICallBack) pData; + iRet = LLDnodePtr2First(pMaster->iList); + while (iRet != 0) { + LLDnodeDataTo(pMaster->iList, &sItem); + if (sItem.pInterface == pInter) { + return sItem.lID; + } + iRet = LLDnodePtr2Next(pMaster->iList); + } + return -1; +} /*---------------------- The callback data structure --------------------*/ - typedef struct { - SConnection *pCon; - SicsInterp *pSics; - char *pAction; - } CBAction, *pCBAction; +typedef struct { + SConnection *pCon; + SicsInterp *pSics; + char *pAction; +} CBAction, *pCBAction; /*---------------------- CBKill -----------------------------------------*/ - static void CBKill(void *pData) - { - pCBAction self = NULL; - self = (pCBAction)pData; - - if(self == NULL) - { - return; - } - - if(self->pCon){ - SCDeleteConnection(self->pCon); - } - if(self->pAction) - { - free(self->pAction); - } - free(self); - } +static void CBKill(void *pData) +{ + pCBAction self = NULL; + self = (pCBAction) pData; + + if (self == NULL) { + return; + } + + if (self->pCon) { + SCDeleteConnection(self->pCon); + } + if (self->pAction) { + free(self->pAction); + } + free(self); +} /*------------------------------------------------------------------------- The callback function for connection callbacks. Invokes command given at registration time. */ - static int ConCallBack(int iEvent, void *pEventData, void *pUserData) - { - pCBAction self = NULL; - - self = (pCBAction)pUserData; - assert(self); - - /* check kill condition */ - if(self->pCon == NULL) - { - return -1; - } - - if(self->pAction) - { - InterpExecute(pServ->pSics,self->pCon,self->pAction); - } - return 1; - } -/*--------------------------------------------------------------------------*/ - int ConSicsAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - SConnection *self = NULL; - pICallBack pInterface = NULL; - char pBueffel[1024]; - pDummy pDum; - int iEvent; - Item sItem; - pCBAction pCB = NULL; - CommandList *pCom = NULL; - int iMacro; - char *script; - - self = (SConnection *)pData; - if(!VerifyConnection(self)) - { - return 0; - } - - if(argc > 1) - { - /* put */ - if(strcmp(argv[1],"put") == 0) - { - Arg2Text(argc-2,&argv[2],pBueffel,1023); - iMacro = SCinMacro(pCon); - SCsetMacro(pCon,0); - SCWrite(self,pBueffel,eWarning); - SCsetMacro(pCon,iMacro); - return 1; - } - /* register object event action */ - if(strcmp(argv[1],"register") == 0) - { - if(argc < 5) - { - SCWrite(pCon,"ERROR: Insufficient arguments to register",eError); - return 0; - } - - /* get object */ - pCom = FindCommand(pSics,argv[2]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: object %s NOT found",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* get CallBack interface */ - pDum = (pDummy)pCom->pData; - assert(pDum); - pInterface = (pICallBack)pDum->pDescriptor->GetInterface(pDum, - CALLBACKINTERFACE); - if(!pInterface) - { - sprintf(pBueffel,"ERROR: %s does not support CallBacks", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* get Event */ - iEvent = Text2Event(argv[3]); - if(iEvent < 0) - { - sprintf(pBueffel,"ERROR: Unknown event code %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - script = Arg2Tcl(argc-4, &argv[4], NULL, 0); - - /* now we can install the callback */ - pCB = (pCBAction)malloc(sizeof(CBAction)); - if(!pCB || !script) - { - SCWrite(pCon,"ERROR: memory exhausted in SConnection",eError); - return 0; - } - pCB->pCon = SCCopyConnection(pCon); - if(!pCB->pCon) - { - SCWrite(pCon,"ERROR: memory exhausted in SConnection",eError); - return 0; - } - pCB->pSics = pSics; - pCB->pAction = script; - sItem.pInterface = pInterface; - sItem.lID = RegisterCallback(pInterface, iEvent, ConCallBack, - pCB, CBKill); - LLDnodeAppendFrom(self->iList,&sItem); - SCSendOK(pCon); - return 1; - } - } - return 0; - } -/*--------------------------------------------------------------------------*/ - int SCTaskFunction(void *pData) - { - SConnection *self = NULL; - char *pPtr = NULL; - int iRet; - char *pUser = NULL, *pPassword = NULL; - char pHost[132], pBueffel[512]; - - self = (SConnection *)pData; - if(!VerifyConnection(self)) - { - return 0; - } - - if(self->iEnd) - { - if(SCActive(self)) - { - return 1; - } - else - { - return 0; - } - } - - if(!SCisConnected(self)){ - self->iEnd = 1; - return 1; - } - - - /* a timeout check on logins */ - if(!self->iLogin && time(NULL) > self->conStart + 120) - { - ANETclose(self->sockHandle); - SCWrite(self, "No valid login in two minutes, closing..",eError); - self->iEnd = 1; - return 1; - } - - /* pop and execute */ - iRet = CostaPop(self->pStack,&pPtr); - if(iRet) - { - if(pPtr) - { - if(self->iLogin) - { - /* - normal processing, logged in - but check for logoff - */ - if(strstr(pPtr,"logoff") != NULL) - { - ANETclose(self->sockHandle); - self->iEnd = 1; - free(pPtr); - return 1; - } - /* invoke command */ - CostaLock(self->pStack); - SCInvoke(self,pServ->pSics,pPtr); - CostaUnlock(self->pStack); - } - else - { - /* response for monit check */ - if (strstr(pPtr,"How are you") == pPtr) - { - SCWrite(self,"I am fine",eError); - ANETclose(self->sockHandle); - self->iEnd = 1; - free(pPtr); - return 1; - } - /* check for username and password */ - pUser = strtok(pPtr," \t"); - pPassword = strtok(NULL," \t\r\n"); - iRet = IsValidUser(pUser,pPassword); - if(iRet >= 0) - { - SCWrite(self,"Login OK",eError); - self->iLogin = 1; - SCSetRights(self,iRet); - pHost[0] = '\0'; - if (CompactCommandLog()) { - if (iRet < 3) { - ANETinfo(self->sockHandle,pHost,131); - sprintf(pBueffel,"Accepted connection %s from %s as %s", - ConName(self->ident), pHost, pUser); - SICSLogWrite(pBueffel,eInternal); - WriteToCommandLogId("SYS>", self->sockHandle, pBueffel); - } - } else { - ANETinfo(self->sockHandle,pHost,131); - sprintf(pBueffel,"Accepted connection %s on socket %d from %s", - ConName(self->ident), self->sockHandle, pHost); - SICSLogWrite(pBueffel,eInternal); - WriteToCommandLog("SYS >", pBueffel); - } - free(pPtr); - return 1; - } - else - { - SCWrite(self,"ERROR: Bad login",eError); - printf("Bad login string %s\n", pPtr); - } - } - free(pPtr); - } - } - - if(self->iEnd) - { - if(SCActive(self)) - { - return 1; - } - else - { - return 0; - } - } - - return 1; - } -/*---------------------------------------------------------------------------*/ - void SCSignalFunction(void *pData, int iSignal, void *pSigData) - { - SConnection *self = NULL; - int *iInt; - char *pPtr; - - self = (SConnection *)pData; - if(!VerifyConnection(self)) - { - return; - } - - if(iSignal == SICSINT) - { - iInt = (int *)pSigData; - SCSetInterrupt(self,*iInt); - if(*iInt == eEndServer) - { - self->iEnd = 1; - } - } - else if(iSignal == SICSBROADCAST) - { - pPtr = (char *)pSigData; - if(pPtr != NULL) - { - SCWrite(self,pPtr,eWarning); - } - } - else if(iSignal == COMLOG && self->listening == 1) - { - pPtr = (char *)pSigData; - if(pPtr != NULL && self != sendingConnection) - { - doSockWrite(self,pPtr); - } - } - else if(iSignal == TOKENRELEASE) - { - self->iGrab = 0; - } - else if(iSignal == TOKENGRAB) - { - self->iGrab = 1; - } - } -/*-----------------------------------------------------------------------*/ -void SCparChange(SConnection *self) +static int ConCallBack(int iEvent, void *pEventData, void *pUserData) { - StatusFileDirty(); -} -/*------------------------------------------------------------------------*/ -int SCActive(SConnection *self) -{ - if(self->inUse != 0 ) - { - return 1; + pCBAction self = NULL; + + self = (pCBAction) pUserData; + assert(self); + + /* check kill condition */ + if (self->pCon == NULL) { + return -1; } - if(pServ->pExecutor != NULL) - { - if(GetExeOwner(pServ->pExecutor) == self) - { + + if (self->pAction) { + InterpExecute(pServ->pSics, self->pCon, self->pAction); + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int ConSicsAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + SConnection *self = NULL; + pICallBack pInterface = NULL; + char pBueffel[1024]; + pDummy pDum; + int iEvent; + Item sItem; + pCBAction pCB = NULL; + CommandList *pCom = NULL; + int iMacro; + char *script; + + self = (SConnection *) pData; + if (!VerifyConnection(self)) { + return 0; + } + + if (argc > 1) { + /* put */ + if (strcmp(argv[1], "put") == 0) { + Arg2Text(argc - 2, &argv[2], pBueffel, 1023); + iMacro = SCinMacro(pCon); + SCsetMacro(pCon, 0); + SCWrite(self, pBueffel, eWarning); + SCsetMacro(pCon, iMacro); + return 1; + } + /* register object event action */ + if (strcmp(argv[1], "register") == 0) { + if (argc < 5) { + SCWrite(pCon, "ERROR: Insufficient arguments to register", eError); + return 0; + } + + /* get object */ + pCom = FindCommand(pSics, argv[2]); + if (!pCom) { + sprintf(pBueffel, "ERROR: object %s NOT found", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* get CallBack interface */ + pDum = (pDummy) pCom->pData; + assert(pDum); + pInterface = (pICallBack) pDum->pDescriptor->GetInterface(pDum, + CALLBACKINTERFACE); + if (!pInterface) { + sprintf(pBueffel, "ERROR: %s does not support CallBacks", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* get Event */ + iEvent = Text2Event(argv[3]); + if (iEvent < 0) { + sprintf(pBueffel, "ERROR: Unknown event code %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + script = Arg2Tcl(argc - 4, &argv[4], NULL, 0); + + /* now we can install the callback */ + pCB = (pCBAction) malloc(sizeof(CBAction)); + if (!pCB || !script) { + SCWrite(pCon, "ERROR: memory exhausted in SConnection", eError); + return 0; + } + pCB->pCon = SCCopyConnection(pCon); + if (!pCB->pCon) { + SCWrite(pCon, "ERROR: memory exhausted in SConnection", eError); + return 0; + } + pCB->pSics = pSics; + pCB->pAction = script; + sItem.pInterface = pInterface; + sItem.lID = RegisterCallback(pInterface, iEvent, ConCallBack, + pCB, CBKill); + LLDnodeAppendFrom(self->iList, &sItem); + SCSendOK(pCon); return 1; } } return 0; } + /*--------------------------------------------------------------------------*/ -SCStore *SCSave(SConnection *pCon, SCStore *oldStore) { +int SCTaskFunction(void *pData) +{ + SConnection *self = NULL; + char *pPtr = NULL; + int iRet; + char *pUser = NULL, *pPassword = NULL; + char pHost[132], pBueffel[512]; + + self = (SConnection *) pData; + if (!VerifyConnection(self)) { + return 0; + } + + if (self->iEnd) { + if (SCActive(self)) { + return 1; + } else { + return 0; + } + } + + if (!SCisConnected(self)) { + self->iEnd = 1; + return 1; + } + + + /* a timeout check on logins */ + if (!self->iLogin && time(NULL) > self->conStart + 120) { + ANETclose(self->sockHandle); + SCWrite(self, "No valid login in two minutes, closing..", eError); + self->iEnd = 1; + return 1; + } + + /* pop and execute */ + iRet = CostaPop(self->pStack, &pPtr); + if (iRet) { + if (pPtr) { + if (self->iLogin) { + /* + normal processing, logged in + but check for logoff + */ + if (strstr(pPtr, "logoff") != NULL) { + ANETclose(self->sockHandle); + self->iEnd = 1; + free(pPtr); + return 1; + } + /* invoke command */ + CostaLock(self->pStack); + SCInvoke(self, pServ->pSics, pPtr); + CostaUnlock(self->pStack); + } else { + /* response for monit check */ + if (strstr(pPtr, "How are you") == pPtr) { + SCWrite(self, "I am fine", eError); + ANETclose(self->sockHandle); + self->iEnd = 1; + free(pPtr); + return 1; + } + /* check for username and password */ + pUser = strtok(pPtr, " \t"); + pPassword = strtok(NULL, " \t\r\n"); + iRet = IsValidUser(pUser, pPassword); + if (iRet >= 0) { + SCWrite(self, "Login OK", eError); + self->iLogin = 1; + SCSetRights(self, iRet); + pHost[0] = '\0'; + if (CompactCommandLog()) { + if (iRet < 3) { + ANETinfo(self->sockHandle, pHost, 131); + sprintf(pBueffel, "Accepted connection %s from %s as %s", + ConName(self->ident), pHost, pUser); + SICSLogWrite(pBueffel, eInternal); + WriteToCommandLogId("SYS>", self->sockHandle, pBueffel); + } + } else { + ANETinfo(self->sockHandle, pHost, 131); + sprintf(pBueffel, + "Accepted connection %s on socket %d from %s", + ConName(self->ident), self->sockHandle, pHost); + SICSLogWrite(pBueffel, eInternal); + WriteToCommandLog("SYS >", pBueffel); + } + free(pPtr); + return 1; + } else { + SCWrite(self, "ERROR: Bad login", eError); + printf("Bad login string %s\n", pPtr); + } + } + free(pPtr); + } + } + + if (self->iEnd) { + if (SCActive(self)) { + return 1; + } else { + return 0; + } + } + + return 1; +} + +/*---------------------------------------------------------------------------*/ +void SCSignalFunction(void *pData, int iSignal, void *pSigData) +{ + SConnection *self = NULL; + int *iInt; + char *pPtr; + + self = (SConnection *) pData; + if (!VerifyConnection(self)) { + return; + } + + if (iSignal == SICSINT) { + iInt = (int *) pSigData; + SCSetInterrupt(self, *iInt); + if (*iInt == eEndServer) { + self->iEnd = 1; + } + } else if (iSignal == SICSBROADCAST) { + pPtr = (char *) pSigData; + if (pPtr != NULL) { + SCWrite(self, pPtr, eWarning); + } + } else if (iSignal == COMLOG && self->listening == 1) { + pPtr = (char *) pSigData; + if (pPtr != NULL && self != sendingConnection) { + doSockWrite(self, pPtr); + } + } else if (iSignal == TOKENRELEASE) { + self->iGrab = 0; + } else if (iSignal == TOKENGRAB) { + self->iGrab = 1; + } +} + +/*-----------------------------------------------------------------------*/ +void SCparChange(SConnection * self) +{ + StatusFileDirty(); +} + +/*------------------------------------------------------------------------*/ +int SCActive(SConnection * self) +{ + if (self->inUse != 0) { + return 1; + } + if (pServ->pExecutor != NULL) { + if (GetExeOwner(pServ->pExecutor) == self) { + return 1; + } + } + return 0; +} + +/*--------------------------------------------------------------------------*/ +SCStore *SCSave(SConnection * pCon, SCStore * oldStore) +{ commandContext cc; - + if (oldStore == NULL) { - oldStore = calloc(1,sizeof(*oldStore)); + oldStore = calloc(1, sizeof(*oldStore)); assert(oldStore); } oldStore->pCon = pCon; @@ -2068,17 +1936,19 @@ SCStore *SCSave(SConnection *pCon, SCStore *oldStore) { } return oldStore; } + /*--------------------------------------------------------------------------*/ -SConnection *SCLoad(SCStore *conStore) { +SConnection *SCLoad(SCStore * conStore) +{ SConnection *pCon = NULL; commandContext old; - + if (conStore) { pCon = conStore->pCon; } if (pCon) { if (conStore->ident != pCon->ident) { - conStore->pCon = NULL; /* connection is dead */ + conStore->pCon = NULL; /* connection is dead */ pCon = NULL; } } @@ -2087,8 +1957,10 @@ SConnection *SCLoad(SCStore *conStore) { } return pServ->dummyCon; } + /*--------------------------------------------------------------------------*/ -SConnection *SCStorePush(SCStore *conStore) { +SConnection *SCStorePush(SCStore * conStore) +{ SConnection *pCon; pCon = SCLoad(conStore); @@ -2099,109 +1971,119 @@ SConnection *SCStorePush(SCStore *conStore) { SCPushContext2(pCon, conStore->cc); return pCon; } + /*--------------------------------------------------------------------------*/ -void SCStorePop(SCStore *conStore) { +void SCStorePop(SCStore * conStore) +{ SConnection *pCon; - + pCon = SCLoad(conStore); SCPopContext(pCon); /* pop macro flag from stack - SCsetMacro(pCon,conStore->macroStack); - */ + SCsetMacro(pCon,conStore->macroStack); + */ SCsetMacro(pCon, (conStore->macroStack & 1)); conStore->macroStack >>= 1; } + /*--------------------------------------------------------------------------*/ -int SCStoreConnected(SCStore *conStore) { +int SCStoreConnected(SCStore * conStore) +{ return (conStore && - conStore->pCon && - conStore->pCon->ident == conStore->ident); + conStore->pCon && conStore->pCon->ident == conStore->ident); } + /*--------------------------------------------------------------------------*/ -void SCStoreFree(SCStore *conStore) { +void SCStoreFree(SCStore * conStore) +{ free(conStore); } -/* --------------------------------------------------------------------------*/ -long SCTagContext(SConnection *self, char *tagName) -{ - commandContext a; - if(NULL==self) return -1; - a = SCGetContext(self); - strncpy(a.deviceID,tagName,SCDEVIDLEN); - /* - SCGetContext will already have advanced the stack pointer to the - last position - */ - LLDnodeDataTo(self->contextStack, &a); - return 1; -} /* --------------------------------------------------------------------------*/ -long SCAdvanceContext(SConnection *self, char *tagName) +long SCTagContext(SConnection * self, char *tagName) { - if(NULL==self) return -1; - self->iCmdCtr++; - if(999999iCmdCtr) - { - self->iCmdCtr = 0; - } - return SCPushContext(self, self->iCmdCtr, tagName); + commandContext a; + if (NULL == self) + return -1; + + a = SCGetContext(self); + strncpy(a.deviceID, tagName, SCDEVIDLEN); + /* + SCGetContext will already have advanced the stack pointer to the + last position + */ + LLDnodeDataTo(self->contextStack, &a); + return 1; } + +/* --------------------------------------------------------------------------*/ +long SCAdvanceContext(SConnection * self, char *tagName) +{ + if (NULL == self) + return -1; + self->iCmdCtr++; + if (999999 < self->iCmdCtr) { + self->iCmdCtr = 0; + } + return SCPushContext(self, self->iCmdCtr, tagName); +} + /*------------------------------------------------------------------------*/ -int SCVerifyConnection(SConnection *self) +int SCVerifyConnection(SConnection * self) { - return VerifyConnection(self); + return VerifyConnection(self); } + /*------------------------------------------------------------------------*/ -int SCDoSockWrite(SConnection *self, char *buffer) +int SCDoSockWrite(SConnection * self, char *buffer) { - return doSockWrite(self,buffer); + return doSockWrite(self, buffer); } + /*-------------------------------------------------------------------------*/ -int SCPushContext(SConnection *self, int ID, char *deviceID) +int SCPushContext(SConnection * self, int ID, char *deviceID) { - commandContext neu; + commandContext neu; - if(!VerifyConnection(self)) - { - return 0; - } + if (!VerifyConnection(self)) { + return 0; + } - neu.transID = ID; - strncpy(neu.deviceID,deviceID,SCDEVIDLEN); - LLDnodeAppendFrom(self->contextStack,&neu); - return 1; + neu.transID = ID; + strncpy(neu.deviceID, deviceID, SCDEVIDLEN); + LLDnodeAppendFrom(self->contextStack, &neu); + return 1; } -/*------------------------------------------------------*/ -int SCPushContext2(SConnection *self, commandContext cc) -{ - return SCPushContext(self,cc.transID, cc.deviceID); -} -/*------------------------------------------------------*/ -commandContext SCGetContext(SConnection *pCon) -{ - commandContext neu; - neu.transID = 0; - strcpy(neu.deviceID,"Undefined"); - if(!VerifyConnection(pCon)) - { - return neu; - } - neu.transID = pCon->transID; - strncpy(neu.deviceID,pCon->deviceID,SCDEVIDLEN); +/*------------------------------------------------------*/ +int SCPushContext2(SConnection * self, commandContext cc) +{ + return SCPushContext(self, cc.transID, cc.deviceID); +} + +/*------------------------------------------------------*/ +commandContext SCGetContext(SConnection * pCon) +{ + commandContext neu; + neu.transID = 0; + strcpy(neu.deviceID, "Undefined"); + + if (!VerifyConnection(pCon)) { return neu; + } + neu.transID = pCon->transID; + strncpy(neu.deviceID, pCon->deviceID, SCDEVIDLEN); + return neu; } + /*-----------------------------------------------------*/ -int SCPopContext(SConnection *pCon) +int SCPopContext(SConnection * pCon) { - if(!VerifyConnection(pCon)) - { - return 0; - } - if(LLDnodePtr2Last(pCon->contextStack) != 0) - { - LLDnodeDelete(pCon->contextStack); - } - return 1; + if (!VerifyConnection(pCon)) { + return 0; + } + if (LLDnodePtr2Last(pCon->contextStack) != 0) { + LLDnodeDelete(pCon->contextStack); + } + return 1; } diff --git a/conman.h b/conman.h index 12d46c82..c5754701 100644 --- a/conman.h +++ b/conman.h @@ -32,157 +32,159 @@ #define MAXLOGFILES 10 -typedef int (*writeFunc)(struct __SConnection *pCon, - char *pMessage, int iCode); +typedef int (*writeFunc) (struct __SConnection * pCon, + char *pMessage, int iCode); - typedef struct __SConnection { - /* Copy Object Fields*/ - pObjectDescriptor pDes; /* must be here */ - long lMagic; /* connection object ID */ - long ident; /* connection idetification */ - struct __SConnection *next; /* pointer for freeConnection managenment */ - int sockHandle; /* socket handle */ - int iTelnet; /* telnet flag */ - int iMacro; /* suppress I/O in macro */ - writeFunc write; /* function doing writing */ - int sicsError; /* Tcl interpreter requirement */ - pDynString data; /* for I/O buffering */ - writeFunc oldWriteFunc; /* saved write function used in I/O buffering */ - long iCmdCtr; /* sycamore protocol used */ - int conEventType; /* sycamore protocol support */ - int conStatus; /* should use status enum ffr */ - int transID; /* transaction ID */ - char deviceID[256]; /* transaction device ID */ - int iUserRights; /* user rights of the connection */ - - /* master connection object fields */ - int iList; /* callback registry, may go? */ - int iEnd; /* flag to end connection task */ - int iLogin; /* flag for successful login process */ - time_t conStart; /* time when connection was built: used during login */ - int iOutput; /* output filter flag */ - int listening; /* for listening to commandlog or other data */ - int eInterrupt; /* interrupts */ - int inUse; /* usage counter for the connection */ - int iGrab; /* grab flag for token*/ - int iProtocolID; /* ID of the protocol on this connection */ - pCosta pStack; /* stack of pending commands */ - int contextStack; /* context stack: may go? */ - mkChannel *pSock; /* for temporary backwards compatability */ - } SConnection; +typedef struct __SConnection { + /* Copy Object Fields */ + pObjectDescriptor pDes; /* must be here */ + long lMagic; /* connection object ID */ + long ident; /* connection idetification */ + struct __SConnection *next; /* pointer for freeConnection managenment */ + int sockHandle; /* socket handle */ + int iTelnet; /* telnet flag */ + int iMacro; /* suppress I/O in macro */ + writeFunc write; /* function doing writing */ + int sicsError; /* Tcl interpreter requirement */ + pDynString data; /* for I/O buffering */ + writeFunc oldWriteFunc; /* saved write function used in I/O buffering */ + long iCmdCtr; /* sycamore protocol used */ + int conEventType; /* sycamore protocol support */ + int conStatus; /* should use status enum ffr */ + int transID; /* transaction ID */ + char deviceID[256]; /* transaction device ID */ + int iUserRights; /* user rights of the connection */ + + /* master connection object fields */ + int iList; /* callback registry, may go? */ + int iEnd; /* flag to end connection task */ + int iLogin; /* flag for successful login process */ + time_t conStart; /* time when connection was built: used during login */ + int iOutput; /* output filter flag */ + int listening; /* for listening to commandlog or other data */ + int eInterrupt; /* interrupts */ + int inUse; /* usage counter for the connection */ + int iGrab; /* grab flag for token */ + int iProtocolID; /* ID of the protocol on this connection */ + pCosta pStack; /* stack of pending commands */ + int contextStack; /* context stack: may go? */ + mkChannel *pSock; /* for temporary backwards compatability */ +} SConnection; #include "nserver.h" /*------------------------------ live & death ----------------------------*/ - SConnection *SCreateConnection(SicsInterp *pSics, int sockHandle, - int iUserRights); - SConnection *SCCreateDummyConnection(SicsInterp *pSics); - void SCDeleteConnection(void *pVictim); - SConnection *SCCopyConnection(SConnection *pCon); - SConnection *SCfindMaster(SConnection *pCon); - int SCisConnected(SConnection *pCon); - int VerifyConnection(SConnection *pCon); - int SCVerifyConnection(SConnection *self); +SConnection *SCreateConnection(SicsInterp * pSics, int sockHandle, + int iUserRights); +SConnection *SCCreateDummyConnection(SicsInterp * pSics); +void SCDeleteConnection(void *pVictim); +SConnection *SCCopyConnection(SConnection * pCon); +SConnection *SCfindMaster(SConnection * pCon); +int SCisConnected(SConnection * pCon); +int VerifyConnection(SConnection * pCon); +int SCVerifyConnection(SConnection * self); /*------------------------------- tasking --------------------------------*/ - int SCTaskFunction(void *pCon); - void SCSignalFunction(void *pCon, int iSignal, void *pSigData); +int SCTaskFunction(void *pCon); +void SCSignalFunction(void *pCon, int iSignal, void *pSigData); /* ***************************** I/O ************************************** */ - void SCSetOutputClass(SConnection *self, int iClass); - int SCWrite(SConnection *self, char *pBuffer, int iOut); - int SCPrintf(SConnection *self, int iOut, char *fmt, ...); - int SCRead(SConnection *self, char *pBuffer, int iBufLen); - int SCPrompt(SConnection *pCon, char *pPrompt, char *pResult, int iLen); - int SCSendOK(SConnection *self); - int SCnoSock(SConnection *pCon); - int SCWriteUUencoded(SConnection *pCon, char *pName, void *iData, int iLen); - int SCWriteZipped(SConnection *pCon, char *pName, void *pData, int iDataLen); - writeFunc SCGetWriteFunc(SConnection *pCon); - void SCSetWriteFunc(SConnection *pCon, writeFunc x); - int SCOnlySockWrite(SConnection *self, char *buffer, int iOut); - int SCFileWrite(SConnection *self, char *buffer, int iOut); - int SCNotWrite(SConnection *self, char *buffer, int iOut); - int SCNormalWrite(SConnection *self, char *buffer, int iOut); - int SCWriteWithOutcode(SConnection *self, char *buffer, int iOut); - int SCACTWrite(SConnection *self, char *buffer, int iOut); +void SCSetOutputClass(SConnection * self, int iClass); +int SCWrite(SConnection * self, char *pBuffer, int iOut); +int SCPrintf(SConnection * self, int iOut, char *fmt, ...); +int SCRead(SConnection * self, char *pBuffer, int iBufLen); +int SCPrompt(SConnection * pCon, char *pPrompt, char *pResult, int iLen); +int SCSendOK(SConnection * self); +int SCnoSock(SConnection * pCon); +int SCWriteUUencoded(SConnection * pCon, char *pName, void *iData, + int iLen); +int SCWriteZipped(SConnection * pCon, char *pName, void *pData, + int iDataLen); +writeFunc SCGetWriteFunc(SConnection * pCon); +void SCSetWriteFunc(SConnection * pCon, writeFunc x); +int SCOnlySockWrite(SConnection * self, char *buffer, int iOut); +int SCFileWrite(SConnection * self, char *buffer, int iOut); +int SCNotWrite(SConnection * self, char *buffer, int iOut); +int SCNormalWrite(SConnection * self, char *buffer, int iOut); +int SCWriteWithOutcode(SConnection * self, char *buffer, int iOut); +int SCACTWrite(SConnection * self, char *buffer, int iOut); /*********************** I/O Buffering ***********************************/ - int SCStartBuffering(SConnection *pCon); - pDynString SCEndBuffering(SConnection *pCon); +int SCStartBuffering(SConnection * pCon); +pDynString SCEndBuffering(SConnection * pCon); /******************************* Error **************************************/ - void SCSetInterrupt(SConnection *self, int eCode); - int SCGetInterrupt(SConnection *self); +void SCSetInterrupt(SConnection * self, int eCode); +int SCGetInterrupt(SConnection * self); /****************************** Macro ***************************************/ - int SCinMacro(SConnection *pCon); - int SCsetMacro(SConnection *pCon, int iMode); +int SCinMacro(SConnection * pCon); +int SCsetMacro(SConnection * pCon, int iMode); /************************** parameters changed ? **************************/ - void SCparChange(SConnection *pCon); +void SCparChange(SConnection * pCon); /* *************************** Info *************************************** */ - int SCGetRights(SConnection *self); - int SCSetRights(SConnection *pCon, int iNew); - int SCMatchRights(SConnection *pCon, int iCode); - int SCGetOutClass(SConnection *self); - int SCGetGrab(SConnection *pCon); - int SCActive(SConnection *pCon); +int SCGetRights(SConnection * self); +int SCSetRights(SConnection * pCon, int iNew); +int SCMatchRights(SConnection * pCon, int iCode); +int SCGetOutClass(SConnection * self); +int SCGetGrab(SConnection * pCon); +int SCActive(SConnection * pCon); /* **************************** Invocation ******************************** */ - int SCInvoke(SConnection *self,SicsInterp *pInter,char *pCommand); - +int SCInvoke(SConnection * self, SicsInterp * pInter, char *pCommand); + /*************************** User Command **********************************/ - int ConfigCon(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int ConSicsAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int ConfigCon(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int ConSicsAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*------------------------------------------------------------------------*/ -int SCDoSockWrite(SConnection *self, char *buffer); -int SCWriteInContext(SConnection *pCon, char *buffer, int code, commandContext cc); +int SCDoSockWrite(SConnection * self, char *buffer); +int SCWriteInContext(SConnection * pCon, char *buffer, int code, + commandContext cc); /* ================== ===================================================== * These routines are obsolete and may not even work anymore. * Mark Koennecke, January 2009 * ==========================================================================*/ -void SCWriteToLogFiles(SConnection *self, char *buffer); -long SCTagContext(SConnection *self, char *tagName); -long SCAdvanceContext(SConnection *self, char *tagName); -int SCPushContext(SConnection *pCon, int ID, char *deviceID); -int SCPushContext2(SConnection *pCon, commandContext cc); -int SCPopContext(SConnection *pCon); -commandContext SCGetContext(SConnection *pCon); +void SCWriteToLogFiles(SConnection * self, char *buffer); +long SCTagContext(SConnection * self, char *tagName); +long SCAdvanceContext(SConnection * self, char *tagName); +int SCPushContext(SConnection * pCon, int ID, char *deviceID); +int SCPushContext2(SConnection * pCon, commandContext cc); +int SCPopContext(SConnection * pCon); +commandContext SCGetContext(SConnection * pCon); /******************************** Store ************************************/ typedef struct SCStore SCStore; -SCStore *SCSave(SConnection *pCon, SCStore *oldStore); +SCStore *SCSave(SConnection * pCon, SCStore * oldStore); /* save a connection and its context for later use. */ -SConnection *SCLoad(SCStore *conStore); +SConnection *SCLoad(SCStore * conStore); /* check con and return SConnection if still valid or a dummy connection otherwise. */ -SConnection *SCStorePush(SCStore *conStore); +SConnection *SCStorePush(SCStore * conStore); /* load connection and push stored context. Must be paired with an SCStorePop command */ -void SCStorePop(SCStore *conStore); +void SCStorePop(SCStore * conStore); /* pop context */ -int SCStoreConnected(SCStore *conStore); +int SCStoreConnected(SCStore * conStore); /* check if a stored connection is not closed */ -void SCStoreFree(SCStore *conStore); +void SCStoreFree(SCStore * conStore); /* free an SCStore */ void KillFreeConnections(void); /************************* CallBack *********************************** */ - int SCRegister(SConnection *pCon, SicsInterp *pSics, - void *pInter, long lID); - int SCUnregister(SConnection *pCon, void *pInter); +int SCRegister(SConnection * pCon, SicsInterp * pSics, + void *pInter, long lID); +int SCUnregister(SConnection * pCon, void *pInter); /** * delete a callback with the given ID */ - int SCUnregisterID(SConnection *pCon, long ID); +int SCUnregisterID(SConnection * pCon, long ID); /** * retrieve the ID of a callback on the callback interface * given in pData. This, together with SCUnregisterID allows to * ceanly remove all callbacks on a connection * returns -1 if no ID can be found. */ - long SCgetCallbackID(SConnection *pCon, void *pData); -#endif - +long SCgetCallbackID(SConnection * pCon, void *pData); +#endif diff --git a/costa.c b/costa.c index 44f7cfd8..875d80d5 100644 --- a/costa.c +++ b/costa.c @@ -45,154 +45,145 @@ #include "costa.h" #include "costa.i" - + /*-------------------------------------------------------------------------*/ - pCosta CreateCommandStack(void) - { - pCosta pNew = NULL; - - pNew = (pCosta)malloc(sizeof(Costa)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(Costa)); - pNew->iList = LLDcreate(sizeof(char *)); - if(pNew->iList < 0) - { - free(pNew); - return NULL; - } - pNew->iCount = 0; - pNew->iMaxSize = INT_MAX; - return pNew; - } -/*-------------------------------------------------------------------------*/ - void DeleteCommandStack(pCosta self) - { - int iRet; - char *pPtr; - - assert(self); - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - pPtr = NULL; - LLDnodeDataTo(self->iList,&pPtr); - if(pPtr) - { - free(pPtr); - } - iRet = LLDnodePtr2Next(self->iList); - } - LLDdelete(self->iList); - free(self); +pCosta CreateCommandStack(void) +{ + pCosta pNew = NULL; + + pNew = (pCosta) malloc(sizeof(Costa)); + if (!pNew) { + return NULL; } -/*--------------------------------------------------------------------------*/ - int SetCommandStackMaxSize(pCosta self, int iNew) - { - assert(self); - - if(iNew > 0) - { - self->iMaxSize = iNew; - return 1; + memset(pNew, 0, sizeof(Costa)); + pNew->iList = LLDcreate(sizeof(char *)); + if (pNew->iList < 0) { + free(pNew); + return NULL; + } + pNew->iCount = 0; + pNew->iMaxSize = INT_MAX; + return pNew; +} + +/*-------------------------------------------------------------------------*/ +void DeleteCommandStack(pCosta self) +{ + int iRet; + char *pPtr; + + assert(self); + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + pPtr = NULL; + LLDnodeDataTo(self->iList, &pPtr); + if (pPtr) { + free(pPtr); } - else - { - return 0; - } - } + iRet = LLDnodePtr2Next(self->iList); + } + LLDdelete(self->iList); + free(self); +} + /*--------------------------------------------------------------------------*/ - int CostaTop(pCosta self, char *pCommand) - { - char *pPtr = NULL; - int iRet, iRes = 1; - - assert(self); - - /* check for lock */ - if(self->iLock) - { - return 0; - } - /* check Size */ - if(self->iCount >= self->iMaxSize) - { - return 0; - } - - /* do not want 0 commands */ - if(strlen(pCommand) < 1) - { - return 1; - } - - pPtr = strdup(pCommand); - iRet = LLDnodeAppendFrom(self->iList,&pPtr); - if(iRet < 0) - { - iRes = 0; - } - self->iCount++; - return iRes; - } -/*--------------------------------------------------------------------------*/ - int CostaBottom(pCosta self, char *pCommand) - { - char *pPtr = NULL; - int iRet, iRes = 1; - assert(self); +int SetCommandStackMaxSize(pCosta self, int iNew) +{ + assert(self); - /* check for lock */ - if(self->iLock) - { - return 0; - } - - /* do not want 0 commands */ - if(strlen(pCommand) < 1) - { - return 1; - } - - pPtr = strdup(pCommand); - iRet = LLDnodePrependFrom(self->iList,&pPtr); - if(iRet < 0) - { - iRes = 0; - } - self->iCount++; - return iRes; - } -/*--------------------------------------------------------------------------*/ - int CostaPop(pCosta self, char **pBuf) - { - char *pPtr = NULL; - int iRet; - - assert(self); - iRet = LLDnodePtr2First(self->iList); - if(iRet != 0) - { - LLDnodeDataTo(self->iList,&pPtr); - *pBuf = pPtr; - LLDnodeDelete(self->iList); - self->iCount--; - return 1; - } - *pBuf = NULL; + if (iNew > 0) { + self->iMaxSize = iNew; + return 1; + } else { return 0; - } -/*--------------------------------------------------------------------------*/ - void CostaLock(pCosta self) - { - self->iLock = 1; } +} + /*--------------------------------------------------------------------------*/ - void CostaUnlock(pCosta self) - { - self->iLock = 0; +int CostaTop(pCosta self, char *pCommand) +{ + char *pPtr = NULL; + int iRet, iRes = 1; + + assert(self); + + /* check for lock */ + if (self->iLock) { + return 0; + } + /* check Size */ + if (self->iCount >= self->iMaxSize) { + return 0; } + /* do not want 0 commands */ + if (strlen(pCommand) < 1) { + return 1; + } + + pPtr = strdup(pCommand); + iRet = LLDnodeAppendFrom(self->iList, &pPtr); + if (iRet < 0) { + iRes = 0; + } + self->iCount++; + return iRes; +} + +/*--------------------------------------------------------------------------*/ +int CostaBottom(pCosta self, char *pCommand) +{ + char *pPtr = NULL; + int iRet, iRes = 1; + assert(self); + + /* check for lock */ + if (self->iLock) { + return 0; + } + + /* do not want 0 commands */ + if (strlen(pCommand) < 1) { + return 1; + } + + pPtr = strdup(pCommand); + iRet = LLDnodePrependFrom(self->iList, &pPtr); + if (iRet < 0) { + iRes = 0; + } + self->iCount++; + return iRes; +} + +/*--------------------------------------------------------------------------*/ +int CostaPop(pCosta self, char **pBuf) +{ + char *pPtr = NULL; + int iRet; + + assert(self); + iRet = LLDnodePtr2First(self->iList); + if (iRet != 0) { + LLDnodeDataTo(self->iList, &pPtr); + *pBuf = pPtr; + LLDnodeDelete(self->iList); + self->iCount--; + return 1; + } + *pBuf = NULL; + return 0; +} + +/*--------------------------------------------------------------------------*/ +void CostaLock(pCosta self) +{ + self->iLock = 1; +} + +/*--------------------------------------------------------------------------*/ +void CostaUnlock(pCosta self) +{ + self->iLock = 0; +} diff --git a/costa.h b/costa.h index 47bf3329..5703b210 100644 --- a/costa.h +++ b/costa.h @@ -12,18 +12,18 @@ #ifndef SICSCOSTA #define SICSCOSTA - typedef struct __costa *pCosta; +typedef struct __costa *pCosta; /*----------------------------- live & death ----------------------------*/ - pCosta CreateCommandStack(void); - void DeleteCommandStack(pCosta self); - int SetCommandStackMaxSize(pCosta self, int iNewSize); +pCosta CreateCommandStack(void); +void DeleteCommandStack(pCosta self); +int SetCommandStackMaxSize(pCosta self, int iNewSize); /*----------------------------------------------------------------------*/ - int CostaTop(pCosta self, char *pCommand); - int CostaBottom(pCosta self, char *pCommand); - int CostaPop(pCosta self,char **pPtr); +int CostaTop(pCosta self, char *pCommand); +int CostaBottom(pCosta self, char *pCommand); +int CostaPop(pCosta self, char **pPtr); /*----------------------------------------------------------------------*/ - void CostaLock(pCosta self); - void CostaUnlock(pCosta self); +void CostaLock(pCosta self); +void CostaUnlock(pCosta self); #endif diff --git a/countdriv.c b/countdriv.c index 2bf0d535..e9a3d6fa 100644 --- a/countdriv.c +++ b/countdriv.c @@ -45,55 +45,50 @@ #include "countdriv.h" /*-------------------------------------------------------------------------*/ - pCounterDriver CreateCounterDriver(char *name, char *type) - { - pCounterDriver pRes = NULL; - - pRes = (pCounterDriver)malloc(sizeof(CounterDriver)); - if(!pRes) - { - return NULL; - } - memset(pRes,0,sizeof(CounterDriver)); - - pRes->name = strdup(name); - pRes->type = strdup(type); - pRes->eMode = eTimer; - pRes->fPreset = 1000.; - pRes->fTime = 0.; - pRes->iNoOfMonitors = 0; - pRes->iPause = 0; - pRes->Start = NULL; - pRes->GetStatus = NULL; - pRes->ReadValues = NULL; - pRes->GetError = NULL; - pRes->TryAndFixIt = NULL; - pRes->Halt = NULL; - pRes->pData = NULL; - pRes->Pause = NULL; - pRes->Continue = NULL; - - return pRes; - } -/*-------------------------------------------------------------------------*/ - void DeleteCounterDriver(pCounterDriver self) - { - assert(self); - if(self->name) - { - free(self->name); - } - if(self->type) - { - free(self->type); - } - if(self->pData) - { - if(self->KillPrivate != NULL) - { - self->KillPrivate(self); - } - } - free(self); - } +pCounterDriver CreateCounterDriver(char *name, char *type) +{ + pCounterDriver pRes = NULL; + pRes = (pCounterDriver) malloc(sizeof(CounterDriver)); + if (!pRes) { + return NULL; + } + memset(pRes, 0, sizeof(CounterDriver)); + + pRes->name = strdup(name); + pRes->type = strdup(type); + pRes->eMode = eTimer; + pRes->fPreset = 1000.; + pRes->fTime = 0.; + pRes->iNoOfMonitors = 0; + pRes->iPause = 0; + pRes->Start = NULL; + pRes->GetStatus = NULL; + pRes->ReadValues = NULL; + pRes->GetError = NULL; + pRes->TryAndFixIt = NULL; + pRes->Halt = NULL; + pRes->pData = NULL; + pRes->Pause = NULL; + pRes->Continue = NULL; + + return pRes; +} + +/*-------------------------------------------------------------------------*/ +void DeleteCounterDriver(pCounterDriver self) +{ + assert(self); + if (self->name) { + free(self->name); + } + if (self->type) { + free(self->type); + } + if (self->pData) { + if (self->KillPrivate != NULL) { + self->KillPrivate(self); + } + } + free(self); +} diff --git a/countdriv.h b/countdriv.h index 4f7603aa..adf4344b 100644 --- a/countdriv.h +++ b/countdriv.h @@ -22,76 +22,74 @@ #define COTERM 0 #define COREDO 1 -#define MAXCOUNT 9 /* No of monitors + actual counter */ - +#define MAXCOUNT 9 /* No of monitors + actual counter */ -/* Parameter codes for the Set/Get pair of routines */ + +/* Parameter codes for the Set/Get pair of routines */ /*-------- threshold */ -#define PARTHRESHOLD 1 +#define PARTHRESHOLD 1 /* counter driver additional error codes*/ #define UNKNOWNPAR -5000 #define BADCOUNTER -5001 - typedef struct __COUNTER { - /* variables */ - char *name; - char *type; - CounterMode eMode; - float fPreset; - float fLastCurrent; - float fTime; - int iNoOfMonitors; - long lCounts[MAXCOUNT]; - int iPause; - int iErrorCode; - /* functions */ - int (*GetStatus)(struct __COUNTER *self, float *fControl); - int (*Start)(struct __COUNTER *self); - int (*Pause)(struct __COUNTER *self); - int (*Continue)(struct __COUNTER *self); - int (*Halt)(struct __COUNTER *self); - int (*ReadValues)(struct __COUNTER *self); - int (*GetError)(struct __COUNTER *self, int *iCode, - char *error, int iErrLen); - int (*TryAndFixIt)(struct __COUNTER *self, int iCode); - int (*Set)(struct __COUNTER *self,char *name, - int iCter, float fVal); - int (*Get)(struct __COUNTER *self,char *name, - int iCter, float *fVal); - int (*Send)(struct __COUNTER *self, char *pText, - char *pReply, int iReplyLen); - void (*KillPrivate)(struct __COUNTER *self); - void *pData; /* counter specific data goes here, ONLY for - internal driver use! +typedef struct __COUNTER { + /* variables */ + char *name; + char *type; + CounterMode eMode; + float fPreset; + float fLastCurrent; + float fTime; + int iNoOfMonitors; + long lCounts[MAXCOUNT]; + int iPause; + int iErrorCode; + /* functions */ + int (*GetStatus) (struct __COUNTER * self, float *fControl); + int (*Start) (struct __COUNTER * self); + int (*Pause) (struct __COUNTER * self); + int (*Continue) (struct __COUNTER * self); + int (*Halt) (struct __COUNTER * self); + int (*ReadValues) (struct __COUNTER * self); + int (*GetError) (struct __COUNTER * self, int *iCode, + char *error, int iErrLen); + int (*TryAndFixIt) (struct __COUNTER * self, int iCode); + int (*Set) (struct __COUNTER * self, char *name, int iCter, float fVal); + int (*Get) (struct __COUNTER * self, char *name, int iCter, float *fVal); + int (*Send) (struct __COUNTER * self, char *pText, + char *pReply, int iReplyLen); + void (*KillPrivate) (struct __COUNTER * self); + void *pData; /* counter specific data goes here, ONLY for + internal driver use! */ - } CounterDriver, *pCounterDriver; - +} CounterDriver, *pCounterDriver; + /*------------------------------------------------------------------------*/ /* countdriv.c */ - pCounterDriver CreateCounterDriver(char *name, char *type); - void DeleteCounterDriver(pCounterDriver self); - +pCounterDriver CreateCounterDriver(char *name, char *type); +void DeleteCounterDriver(pCounterDriver self); + /* PSI EL737 Counter */ - pCounterDriver NewEL737Counter(char *name, char *host, int iPort, - int iChannel); - void KillEL737Counter(pCounterDriver self); - +pCounterDriver NewEL737Counter(char *name, char *host, int iPort, + int iChannel); +void KillEL737Counter(pCounterDriver self); + /* PSI Simulation counter, if you have no hardware */ /* simcter.c */ - pCounterDriver NewSIMCounter(char *name, float fVal); - void KillSIMCounter(pCounterDriver self); - +pCounterDriver NewSIMCounter(char *name, float fVal); +void KillSIMCounter(pCounterDriver self); + /* * McStas simulation counter driver * file: mcstascounter.c */ - pCounterDriver NewMcStasCounter(char *name); +pCounterDriver NewMcStasCounter(char *name); /* * for regression testing * file: regresscter.c */ - pCounterDriver NewRegressCounter(char *name); +pCounterDriver NewRegressCounter(char *name); #endif diff --git a/counter.c b/counter.c index 28ac711e..b58c2ca3 100644 --- a/counter.c +++ b/counter.c @@ -53,1125 +53,1065 @@ #include "site.h" /*-------------------------------------------------------------------------*/ /* - The monitor callback data structure - */ - typedef struct { - float fPreset; - float fCurrent; - char *pName; - } MonEvent, *pMonEvent; + The monitor callback data structure + */ +typedef struct { + float fPreset; + float fCurrent; + char *pName; +} MonEvent, *pMonEvent; /*--------------------------------------------------------------------------*/ - static int Halt(void *pData) - { - pCounter self = NULL; - - assert(pData); - self = (pCounter)pData; - - return self->pDriv->Halt(self->pDriv); - } +static int Halt(void *pData) +{ + pCounter self = NULL; + + assert(pData); + self = (pCounter) pData; + + return self->pDriv->Halt(self->pDriv); +} + /*--------------------------------------------------------------------------*/ - static void SetCountParameters(void *pData, float fPreset, CounterMode eMode) - { - pCounter self = NULL; - - assert(pData); - self = (pCounter)pData; - - self->pDriv->fPreset = fPreset; - self->pDriv->eMode = eMode; - } +static void SetCountParameters(void *pData, float fPreset, + CounterMode eMode) +{ + pCounter self = NULL; + + assert(pData); + self = (pCounter) pData; + + SetCounterPreset(self, fPreset); + SetCounterMode(self, eMode); +} + /*-----------------------------------------------------------------------*/ - static int StartCount(void *pData, SConnection *pCon) - { - pCounter self; - char pBueffel[132]; - char pError[80]; - int iRet; - int i; - int iErr; - time_t tX; - - self = (pCounter)pData; - assert(self); +static int StartCount(void *pData, SConnection * pCon) +{ + pCounter self; + char pBueffel[132]; + char pError[80]; + int iRet; + int i; + int iErr; + time_t tX; - if(!GetCountLock(self->pCountInt, pCon)){ - return 0; + self = (pCounter) pData; + assert(self); + + if (!GetCountLock(self->pCountInt, pCon)) { + return 0; + } + + /* try at least three times to do it */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->Start(self->pDriv); + if (iRet == OKOK) { + self->isUpToDate = 0; + self->badStatusCount = 0; + self->tStart = time(&tX); + InvokeCallBack(self->pCall, COUNTSTART, pCon); + return iRet; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "WARNING: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + SCWrite(pCon, "ERROR: Cannot fix counter problem, aborting", + eError); + SCSetInterrupt(pCon, eAbortBatch); + ReleaseCountLock(self->pCountInt); + return HWFault; } - - /* try at least three times to do it */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->Start(self->pDriv); - if(iRet == OKOK) - { - self->isUpToDate = 0; - self->badStatusCount = 0; - self->tStart = time(&tX); - InvokeCallBack(self->pCall,COUNTSTART,pCon); - return iRet; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"WARNING: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - SCWrite(pCon,"ERROR: Cannot fix counter problem, aborting",eError); - SCSetInterrupt(pCon,eAbortBatch); - ReleaseCountLock(self->pCountInt); - return HWFault; - } - } + } + } + SCWrite(pCon, "ERROR: Cannot fix counter problem, aborting", eError); + SCSetInterrupt(pCon, eAbortBatch); + ReleaseCountLock(self->pCountInt); + return HWFault; +} + +/*-----------------------------------------------------------------------*/ +static int PauseCount(void *pData, SConnection * pCon) +{ + pCounter self; + char pBueffel[132]; + char pError[80]; + int iRet; + int i; + int iErr; + + self = (pCounter) pData; + assert(self); + + /* try at least three times to do it */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->Pause(self->pDriv); + if (iRet == OKOK) { + self->isUpToDate = 0; + return iRet; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "WARNING: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + SCWrite(pCon, "ERROR: Cannot fix counter problem, aborting", + eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; } - SCWrite(pCon,"ERROR: Cannot fix counter problem, aborting",eError); - SCSetInterrupt(pCon,eAbortBatch); + } + } + SCWrite(pCon, "ERROR: Cannot fix counter problem, aborting", eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; +} + +/*-----------------------------------------------------------------------*/ +static int ContinueCount(void *pData, SConnection * pCon) +{ + pCounter self; + char pBueffel[132]; + char pError[80]; + int iRet; + int i; + int iErr; + + self = (pCounter) pData; + assert(self); + + /* try at least three times to do it */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->Continue(self->pDriv); + if (iRet == OKOK) { + self->isUpToDate = 0; + return iRet; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "WARNING: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + SCWrite(pCon, "ERROR: Cannot fix counter problem, aborting", + eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; + } + } + } + SCWrite(pCon, "ERROR: Cannot fix counter problem, aborting", eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; +} + +/*--------------------------------------------------------------------------*/ +static int CheckCountStatus(void *pData, SConnection * pCon) +{ + pCounter self = NULL; + int i, iRet; + int eCt; + char pError[80], pBueffel[132]; + int iErr; + float fControl; + MonEvent sMon; + + self = (pCounter) pData; + assert(self); + assert(pCon); + + eCt = self->pDriv->GetStatus(self->pDriv, &fControl); + if (eCt == HWFault) { + self->badStatusCount++; + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "WARNING: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM || self->badStatusCount > 3) { + SCWrite(pCon, "ERROR: Cannot fix counter problem, aborting", eError); + SCSetInterrupt(pCon, eAbortBatch); + InvokeCallBack(self->pCall, COUNTEND, NULL); ReleaseCountLock(self->pCountInt); - return HWFault; - } -/*-----------------------------------------------------------------------*/ - static int PauseCount(void *pData, SConnection *pCon) - { - pCounter self; - char pBueffel[132]; - char pError[80]; - int iRet; - int i; - int iErr; - - self = (pCounter)pData; - assert(self); - - /* try at least three times to do it */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->Pause(self->pDriv); - if(iRet == OKOK) - { - self->isUpToDate = 0; - return iRet; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"WARNING: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - SCWrite(pCon,"ERROR: Cannot fix counter problem, aborting", - eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; - } - } - } - SCWrite(pCon,"ERROR: Cannot fix counter problem, aborting",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; - } -/*-----------------------------------------------------------------------*/ - static int ContinueCount(void *pData, SConnection *pCon) - { - pCounter self; - char pBueffel[132]; - char pError[80]; - int iRet; - int i; - int iErr; - - self = (pCounter)pData; - assert(self); - - /* try at least three times to do it */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->Continue(self->pDriv); - if(iRet == OKOK) - { - self->isUpToDate = 0; - return iRet; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"WARNING: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - SCWrite(pCon,"ERROR: Cannot fix counter problem, aborting",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; - } - } - } - SCWrite(pCon,"ERROR: Cannot fix counter problem, aborting",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; - } -/*--------------------------------------------------------------------------*/ - static int CheckCountStatus(void *pData, SConnection *pCon) - { - pCounter self = NULL; - int i, iRet; - int eCt; - char pError[80], pBueffel[132]; - int iErr; - float fControl; - MonEvent sMon; - - self = (pCounter)pData; - assert(self); - assert(pCon); - - eCt = self->pDriv->GetStatus(self->pDriv,&fControl); - if(eCt == HWFault) - { - self->badStatusCount++; - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"WARNING: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM || self->badStatusCount > 3) - { - SCWrite(pCon,"ERROR: Cannot fix counter problem, aborting",eError); - SCSetInterrupt(pCon,eAbortBatch); - InvokeCallBack(self->pCall,COUNTEND,NULL); - ReleaseCountLock(self->pCountInt); - return eCt; - } - else - { - return HWBusy; - } - } - - /* - handle count parameters and notify listeners on progress - */ - sMon.fCurrent = fControl; - sMon.fPreset = self->pDriv->fPreset; - sMon.pName = self->name; - self->badStatusCount = 0; /* clear: we managed to read OK */ - if(self->iCallbackCounter > 20) - { - InvokeCallBack(self->pCall,MONITOR,&sMon); - self->iCallbackCounter = 0; - } - else - { - self->iCallbackCounter++; - } - self->pDriv->fLastCurrent = fControl; - - /* - notification on finish - */ - if(eCt == HWIdle) - { - InvokeCallBack(self->pCall,COUNTEND,NULL); - ReleaseCountLock(self->pCountInt); - } return eCt; - } -/*------------------------------------------------------------------------*/ - static int SaveCounterStatus(void *pData, char *name, FILE *fd) - { - pCounter self = NULL; - char pBueffel[512]; - - assert(pData); - assert(fd); - - self = (pCounter)pData; - - sprintf(pBueffel,"# Counter %s\n",name); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s SetPreset %f\n",name, self->pDriv->fPreset); - fputs(pBueffel,fd); - if(self->pDriv->eMode == eTimer) - { - sprintf(pBueffel,"%s SetMode Timer\n",name); + } else { + return HWBusy; } - else - { - sprintf(pBueffel,"%s SetMode Monitor\n",name); - } - fputs(pBueffel,fd); - - return 1; - } -/*------------------------------------------------------------------------*/ - static int TransferData(void *pData, SConnection *pCon) - { - pCounter self = NULL; - int i, iRet; - char pError[80]; - char pBueffel[132]; - int iCode; - - self = (pCounter)pData; - assert(self); - assert(pCon); + } - /* try three times */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->ReadValues(self->pDriv); - if(iRet == OKOK) - { - self->isUpToDate = 1; - return OKOK; - } - else - { - self->pDriv->GetError(self->pDriv,&iCode,pError,79); - sprintf(pBueffel,"WARNING: %s",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iCode); - if(iRet == COTERM) - { - SCWrite(pCon,"ERROR: Cannot fix counter problem, aborting",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; - } - } - } - SCWrite(pCon,"ERROR: Cannot fix counter problem, aborting",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; + /* + handle count parameters and notify listeners on progress + */ + sMon.fCurrent = fControl; + sMon.fPreset = self->pDriv->fPreset; + sMon.pName = self->name; + self->badStatusCount = 0; /* clear: we managed to read OK */ + if (self->iCallbackCounter > 20) { + InvokeCallBack(self->pCall, MONITOR, &sMon); + self->iCallbackCounter = 0; + } else { + self->iCallbackCounter++; } -/*------------------------------------------------------------------------*/ - static void *CounterGetInterface(void *pData, int iID) - { - pCounter self = NULL; - - self = (pCounter)pData; - assert(self); - if(iID == COUNTID) - { - return self->pCountInt; - } - else if(iID == CALLBACKINTERFACE) - { - return self->pCall; - } - return NULL; - } -/*------------------------------------------------------------------------*/ - pCounter CreateCounter(char *name, pCounterDriver pDriv) - { - pCounter pRes = NULL; - - assert(pDriv); - - pRes = (pCounter)malloc(sizeof(Counter)); - if(!pRes) - { - return NULL; - } - pRes->pDes = CreateDescriptor("SingleCounter"); - if(!pRes->pDes) - { - free(pRes); - return NULL; - } - /* initialize Descriptor functions */ - pRes->pDes->GetInterface = CounterGetInterface; - pRes->pDes->SaveStatus = SaveCounterStatus; + self->pDriv->fLastCurrent = fControl; - /* initialise countable interface */ - pRes->pCountInt = CreateCountableInterface(); - if(!pRes->pCountInt) - { - DeleteDescriptor(pRes->pDes); - free(pRes); - return NULL; - } - pRes->pCountInt->SetCountParameters = SetCountParameters; - pRes->pCountInt->StartCount = StartCount; - pRes->pCountInt->CheckCountStatus = CheckCountStatus; - pRes->pCountInt->TransferData = TransferData; - pRes->pCountInt->Halt = Halt; - pRes->pCountInt->Pause = PauseCount; - pRes->pCountInt->Continue = ContinueCount; - pRes->iCallbackCounter = 20; - - pRes->pCall = CreateCallBackInterface(); - - pRes->pDriv = pDriv; - pRes->isUpToDate = 1; - pRes->iExponent = 0; - pRes->name = strdup(name); - return pRes; + /* + notification on finish + */ + if (eCt == HWIdle) { + InvokeCallBack(self->pCall, COUNTEND, NULL); + ReleaseCountLock(self->pCountInt); } + return eCt; +} + +/*------------------------------------------------------------------------*/ +static int SaveCounterStatus(void *pData, char *name, FILE * fd) +{ + pCounter self = NULL; + char pBueffel[512]; + + assert(pData); + assert(fd); + + self = (pCounter) pData; + + sprintf(pBueffel, "# Counter %s\n", name); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s SetPreset %f\n", name, self->pDriv->fPreset); + fputs(pBueffel, fd); + if (self->pDriv->eMode == eTimer) { + sprintf(pBueffel, "%s SetMode Timer\n", name); + } else { + sprintf(pBueffel, "%s SetMode Monitor\n", name); + } + fputs(pBueffel, fd); + + return 1; +} + +/*------------------------------------------------------------------------*/ +static int TransferData(void *pData, SConnection * pCon) +{ + pCounter self = NULL; + int i, iRet; + char pError[80]; + char pBueffel[132]; + int iCode; + + self = (pCounter) pData; + assert(self); + assert(pCon); + + /* try three times */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->ReadValues(self->pDriv); + if (iRet == OKOK) { + self->isUpToDate = 1; + return OKOK; + } else { + self->pDriv->GetError(self->pDriv, &iCode, pError, 79); + sprintf(pBueffel, "WARNING: %s", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iCode); + if (iRet == COTERM) { + SCWrite(pCon, "ERROR: Cannot fix counter problem, aborting", + eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; + } + } + } + SCWrite(pCon, "ERROR: Cannot fix counter problem, aborting", eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; +} + +/*------------------------------------------------------------------------*/ +static void *CounterGetInterface(void *pData, int iID) +{ + pCounter self = NULL; + + self = (pCounter) pData; + assert(self); + if (iID == COUNTID) { + return self->pCountInt; + } else if (iID == CALLBACKINTERFACE) { + return self->pCall; + } + return NULL; +} + + /*---------------------------------------------------------------------------*/ - void DeleteCounter(void *pData) - { - pCounter self = NULL; - - assert(pData); - self = (pCounter)pData; - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - - if(self->pCountInt) - { - free(self->pCountInt); - } - if(self->pCall) - { - DeleteCallBackInterface(self->pCall); - } - - if(self->name) - { - free(self->name); - } - if(self->pDriv) - { - DeleteCounterDriver(self->pDriv); - } - free(self); +void DeleteCounter(void *pData) +{ + pCounter self = NULL; + + assert(pData); + self = (pCounter) pData; + + if (self->pDes) { + DeleteDescriptor(self->pDes); } + + if (self->pCountInt) { + free(self->pCountInt); + } + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + } + + if (self->name) { + free(self->name); + } + if (self->pDriv) { + DeleteCounterDriver(self->pDriv); + } + free(self); +} + /*-------------------------------------------------------------------------*/ - int DoCount(pCounter self, float fPreset, SConnection *pCon, - int iBlock) - { - int iRet; - char pBueffel[132]; - Status eOld; - - assert(self); - - /* check authorisation */ - if(!SCMatchRights(pCon,usUser)) - { - sprintf(pBueffel,"ERROR: you are not authorised to count"); - SCWrite(pCon, pBueffel, eError); - return 0; - } - - eOld = GetStatus(); - SetStatus(eCounting); - - /* set Preset */ - SetCounterPreset(self,fPreset); - - iRet = StartDevice(GetExecutor(),self->name,self->pDes,self,pCon, - self->pDriv->fPreset); - if(!iRet) - { - SetStatus(eOld); - SCWrite(pCon,"Counting aborted",eError); - return 0; - } - - /* continue only if in blocking mode */ - if(!iBlock) - { - return 1; - } - - /* wait forever until done or interrupted */ - iRet = Wait4Success(GetExecutor()); - if(iRet == DEVINT) - { - SCWrite(pCon,"Counting aborted due to Interrupt",eError); - } - else if(iRet == DEVERROR) - { - SCWrite(pCon,"Counting finished with Problems",eError); - iRet = 1; - } - else - { - SCWrite(pCon,"Counting finished",eValue); - iRet = 1; - } - SetStatus(eOld); - return iRet; - } -/*-----------------------------------------------------------------------*/ - -/*-------------------------------------------------------------------------*/ +int DoCount(pCounter self, float fPreset, SConnection * pCon, int iBlock) +{ + int iRet; + char pBueffel[132]; + Status eOld; - int MakeCounter(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pCounter pNew = NULL; - pCounterDriver pDriv = NULL; - float fFail = -1; - int iRet; - char pBueffel[256]; - pSite site = NULL; + assert(self); - assert(pCon); - assert(pSics); + /* check authorisation */ + if (!SCMatchRights(pCon, usUser)) { + sprintf(pBueffel, "ERROR: you are not authorised to count"); + SCWrite(pCon, pBueffel, eError); + return 0; + } - argtolower(argc,argv); - if(argc < 3){ - SCWrite(pCon,"ERROR: insuficient number of arguments to MakeCounter", - eError); - return 0; - } - site = getSite(); - if(site != NULL){ - pDriv = site->CreateCounterDriver(pCon,argc,argv); - } + eOld = GetStatus(); + SetStatus(eCounting); - /* - test for simulation driver, which is for everybody - */ - if(strcmp(argv[2],"sim") == 0){ - if(argc > 3){ - fFail = atof(argv[3]); - pDriv = NewSIMCounter(argv[1],fFail); - } - } + /* set Preset */ + SetCounterPreset(self, fPreset); - /* - * test for regression testing counter - */ - if(strcmp(argv[2],"regress") == 0){ - pDriv = NewRegressCounter(argv[1]); - } + iRet = StartDevice(GetExecutor(), self->name, self->pDes, self, pCon, + fPreset); + if (!iRet) { + SetStatus(eOld); + SCWrite(pCon, "Counting aborted", eError); + return 0; + } - /* - * test for McStas simulation counter driver - */ - if(strcmp(argv[2],"mcstas") == 0){ - pDriv = NewMcStasCounter(argv[1]); - } - - if(!pDriv) - { - sprintf(pBueffel,"ERROR: cannot create requested driver %s", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* create Counter and command */ - pNew = CreateCounter(argv[1],pDriv); - if(!pNew) - { - sprintf(pBueffel,"ERROR: cannot create counter %s", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = AddCommand(pSics,argv[1],CountAction,DeleteCounter,(void *)pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } + /* continue only if in blocking mode */ + if (!iBlock) { return 1; - } + } + + /* wait forever until done or interrupted */ + iRet = Wait4Success(GetExecutor()); + if (iRet == DEVINT) { + SCWrite(pCon, "Counting aborted due to Interrupt", eError); + } else if (iRet == DEVERROR) { + SCWrite(pCon, "Counting finished with Problems", eError); + iRet = 1; + } else { + SCWrite(pCon, "Counting finished", eValue); + iRet = 1; + } + SetStatus(eOld); + return iRet; +} +/*-------------------------------------------------------------------------*/ + +int MakeCounter(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pCounter pNew = NULL; + pCounterDriver pDriv = NULL; + float fFail = -1; + int iRet; + char pBueffel[256]; + pSite site = NULL; + + assert(pCon); + assert(pSics); + + argtolower(argc, argv); + if (argc < 3) { + SCWrite(pCon, "ERROR: insuficient number of arguments to MakeCounter", + eError); + return 0; + } + site = getSite(); + if (site != NULL) { + pDriv = site->CreateCounterDriver(pCon, argc, argv); + } + + /* + test for simulation driver, which is for everybody + */ + if (strcmp(argv[2], "sim") == 0) { + if (argc > 3) { + fFail = atof(argv[3]); + pDriv = NewSIMCounter(argv[1], fFail); + } + } + + /* + * test for regression testing counter + */ + if (strcmp(argv[2], "regress") == 0) { + pDriv = NewRegressCounter(argv[1]); + } + + /* + * test for McStas simulation counter driver + */ + if (strcmp(argv[2], "mcstas") == 0) { + pDriv = NewMcStasCounter(argv[1]); + } + + if (!pDriv) { + sprintf(pBueffel, "ERROR: cannot create requested driver %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* create Counter and command */ + pNew = CreateCounter(argv[1], pDriv); + if (!pNew) { + sprintf(pBueffel, "ERROR: cannot create counter %s", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = + AddCommand(pSics, argv[1], CountAction, DeleteCounter, + (void *) pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} + /* --------------------------------------------------------------------------*/ - int SetCounterMode(pCounter self, CounterMode eNew) - { - int i; - - assert(self); - if(eNew == self->pDriv->eMode) - { - return 1; - } - - if(eNew == eTimer) - { - for(i = 0; i < self->iExponent; i++) - { - self->pDriv->fPreset /= 10.; - } - } - if(eNew == ePreset) - { - for(i = 0; i < self->iExponent; i++) - { - self->pDriv->fPreset *= 10.; - } - } - self->pDriv->eMode = eNew; +int SetCounterMode(pCounter self, CounterMode eNew) +{ + return self->setMode(self,eNew); +} +/*---------------------------------------------------------------------------*/ +static int SetCounterModeImpl(pCounter self, CounterMode eNew) +{ + int i; + + assert(self); + if (eNew == self->pDriv->eMode) { return 1; } -/*--------------------------------------------------------------------------*/ - CounterMode GetCounterMode(pCounter self) - { - assert(self); - return self->pDriv->eMode; + + if (eNew == eTimer) { + for (i = 0; i < self->iExponent; i++) { + self->pDriv->fPreset /= 10.; + } } + if (eNew == ePreset) { + for (i = 0; i < self->iExponent; i++) { + self->pDriv->fPreset *= 10.; + } + } + self->pDriv->eMode = eNew; + return 1; +} +/*-------------------------------------------------------------------------*/ +CounterMode GetCounterMode(pCounter self) +{ + return self->getMode(self); +} +/*--------------------------------------------------------------------------*/ +static CounterMode GetCounterModeImpl(pCounter self) +{ + assert(self); + return self->pDriv->eMode; +} /*------------------------------------------------------------------------*/ - int GetNMonitor(pCounter self) - { - assert(self); - return self->pDriv->iNoOfMonitors; - } +int GetNMonitor(pCounter self) +{ + return self->getNMonitor(self); +} +/*------------------------------------------------------------------------*/ +static int GetNMonitorImpl(pCounter self) +{ + assert(self); + return self->pDriv->iNoOfMonitors; +} + #ifdef NONINTF - extern float nintf(float f); -#endif -/*------------------------------------------------------------------------*/ - int SetCounterPreset(pCounter self, float fVal) - { - int i; - - assert(self); - - if(fVal < .0) - { - return 0; - } - if(GetCounterMode(self) == ePreset) - { - for(i = 0; i < self->iExponent;i++) - { - fVal *= 10.; - } - fVal = nintf(fVal); - } - self->pDriv->fPreset = fVal; - return 1; - } +extern float nintf(float f); +#endif /*------------------------------------------------------------------------*/ - float GetCounterPreset(pCounter self) - { - int i; - float fVal; - - assert(self); - - fVal = self->pDriv->fPreset; - if(self->pDriv->eMode == ePreset) - { - for(i = 0; i < self->iExponent; i++) - { - fVal /= 10.; - } - } - return fVal; - } -/*-----------------------------------------------------------------------*/ - long GetCounts(pCounter self, SConnection *pCon) - { - assert(self); - if(!self->isUpToDate) - { - self->pCountInt->TransferData(self,pCon); - } - return self->pDriv->lCounts[0]; - } -/*------------------------------------------------------------------------*/ - long GetMonitor(pCounter self, int iNum, SConnection *pCon) - { - assert(self); +int SetCounterPreset(pCounter self, float fVal) +{ + return self->setPreset(self,fVal); +} +/*------------------------------------------------------------------------*/ +static int SetCounterPresetImpl(pCounter self, float fVal) +{ + int i; - if(!self->isUpToDate) - { - self->pCountInt->TransferData(self,pCon); - } - if( (iNum < 0) || (iNum > self->pDriv->iNoOfMonitors) ) - { - return -1L; - } - else - { - return self->pDriv->lCounts[iNum]; - } - } - /*-----------------------------------------------------------------------*/ - void SetMonitorValue(pCounter self, int index, long value) - { - assert(self); - - if(index >= 0 && index < self->pDriv->iNoOfMonitors) - { - self->pDriv->lCounts[index] = value; - } - } -/*------------------------------------------------------------------------*/ - float GetCountTime(pCounter self,SConnection *pCon) - { - assert(self); + assert(self); - if(!self->isUpToDate) - { - self->pCountInt->TransferData(self,pCon); - } - return self->pDriv->fTime; + if (fVal < .0) { + return 0; } -/*----------------------------------------------------------------------*/ - static int isAuthorised(SConnection *pCon, int iCode) - { - char pBueffel[132]; - - if(!SCMatchRights(pCon,iCode)) - { - sprintf(pBueffel,"ERROR: you are not authorised to count"); - SCWrite(pCon, pBueffel, eError); - return 0; + if (GetCounterMode(self) == ePreset) { + for (i = 0; i < self->iExponent; i++) { + fVal *= 10.; } - return 1; - } -/*-----------------------------------------------------------------------*/ - static int CounterInterest(int iEvent, void *pEvent, void *pUser) - { - SConnection *pCon = NULL; - pMonEvent pMon = NULL; - char pBueffel[512]; - int rights; - - if(pCon == NULL || !SCisConnected(pCon)){ - return -1; - } + fVal = nintf(fVal); + } + self->pDriv->fPreset = fVal; + return 1; +} +/*------------------------------------------------------------------------*/ +float GetCounterPreset(pCounter self) +{ + return self->getPreset(self); +} +/*------------------------------------------------------------------------*/ +static float GetCounterPresetImpl(pCounter self) +{ + int i; + float fVal; - if(iEvent != MONITOR || pCon == NULL) - { - return 0; - } - - pCon = (SConnection *)pUser; - pMon = (pMonEvent)pEvent; - assert(pCon); - assert(pMon); - sprintf(pBueffel,"%s.CountStatus = %f %d",pMon->pName,pMon->fPreset, - (int)nintf(pMon->fCurrent)); + assert(self); + + fVal = self->pDriv->fPreset; + if (self->pDriv->eMode == ePreset) { + for (i = 0; i < self->iExponent; i++) { + fVal /= 10.; + } + } + return fVal; +} +/*-----------------------------------------------------------------------*/ +long GetCounts(pCounter self, SConnection * pCon) +{ + return self->getCounts(self, pCon); +} +/*-----------------------------------------------------------------------*/ +static long GetCountsImpl(pCounter self, SConnection * pCon) +{ + assert(self); + if (!self->isUpToDate) { + self->pCountInt->TransferData(self, pCon); + } + return self->pDriv->lCounts[0]; +} +/*------------------------------------------------------------------------*/ +long GetMonitor(pCounter self, int iNum, SConnection * pCon) +{ + return self->getMonitor(self, iNum, pCon); +} +/*------------------------------------------------------------------------*/ +static long GetMonitorImpl(pCounter self, int iNum, SConnection * pCon) +{ + assert(self); + + if (!self->isUpToDate) { + self->pCountInt->TransferData(self, pCon); + } + if ((iNum < 0) || (iNum > self->pDriv->iNoOfMonitors)) { + return -1L; + } else { + return self->pDriv->lCounts[iNum]; + } +} +/*-----------------------------------------------------------------------*/ +void SetMonitorValue(pCounter self, int index, long value) +{ + return self->setMonitor(self, index, value); +} + /*-----------------------------------------------------------------------*/ +static void SetMonitorValueImpl(pCounter self, int index, long value) +{ + assert(self); + + if (index >= 0 && index < self->pDriv->iNoOfMonitors) { + self->pDriv->lCounts[index] = value; + } +} +/*------------------------------------------------------------------------*/ +float GetCountTime(pCounter self, SConnection * pCon) +{ + return self->getTime(self, pCon); +} +/*------------------------------------------------------------------------*/ +static float GetCountTimeImpl(pCounter self, SConnection * pCon) +{ + assert(self); + + if (!self->isUpToDate) { + self->pCountInt->TransferData(self, pCon); + } + return self->pDriv->fTime; +} + +/*----------------------------------------------------------------------*/ +static int isAuthorised(SConnection * pCon, int iCode) +{ + char pBueffel[132]; + + if (!SCMatchRights(pCon, iCode)) { + sprintf(pBueffel, "ERROR: you are not authorised to count"); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} + +/*-----------------------------------------------------------------------*/ +static int CounterInterest(int iEvent, void *pEvent, void *pUser) +{ + SConnection *pCon = NULL; + pMonEvent pMon = NULL; + char pBueffel[512]; + int rights; + + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + if (iEvent != MONITOR || pCon == NULL) { + return 0; + } + + pCon = (SConnection *) pUser; + pMon = (pMonEvent) pEvent; + assert(pCon); + assert(pMon); + sprintf(pBueffel, "%s.CountStatus = %f %d", pMon->pName, pMon->fPreset, + (int) nintf(pMon->fCurrent)); /** * prevent this to be written to log files */ - SCSetRights(pCon,usSpy); - SCWrite(pCon,pBueffel,eWarning); - return 1; - } -/*-----------------------------------------------------------------------*/ - - int CountAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pCounter self = NULL; - int iRet, iRet2; - FuPaResult PaRes; - char pBueffel[256], pError[80]; - char **argx; - float fVal; - long lVal; - long lID; - CounterMode eMode; - FuncTemplate ActionTemplate[] = { - {"count",1,{FUPAFLOAT} }, - {"getpreset",0,{0.0} }, - {"setpreset",1,{FUPAFLOAT}}, - {"getmode",0,{0,0}}, - {"setmode",1,{FUPATEXT}}, - {"getcounts",0,{0,0}}, - {"getmonitor",1,{FUPAINT,0}}, - {"setexponent",1,{FUPAINT,0}}, - {"getexponent",0,{0,0}}, - {"interest",0,{0,0}}, - {"uninterest",0,{0,0}}, - {"status",0,{0,0}}, - {"gettime",0,{0,0}}, - {"countnb",1,{FUPAFLOAT} }, - {"getthreshold",1,{FUPAINT}}, - {"setthreshold",2,{FUPAINT,FUPAFLOAT}}, - {"stop",0,{0,0}}, - {"mode",1,{FUPAOPT}}, - {"preset",1,{FUPAOPT}}, - {"send",0,{0,0}}, - {"setpar",3,{FUPATEXT,FUPAINT,FUPAFLOAT}}, - {"getpar",2,{FUPATEXT,FUPAOPT}}, - {"getnmon",0,{0,0}} - }; - char *pMode[] = { - "timer", - "monitor", - NULL - }; - - self = (pCounter)pData; - assert(self); - assert(pCon); - assert(pSics); - - /* parse function args */ - argtolower(argc,argv); - argx = &argv[1]; - iRet = EvaluateFuPa((pFuncTemplate)&ActionTemplate,23,argc-1,argx,&PaRes); - if(iRet < 0) - { - sprintf(pBueffel,"%s",PaRes.pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* do something! */ - switch(iRet) - { - case 0: /* Count */ - return DoCount(self,PaRes.Arg[0].fVal,pCon,1); - break; - case 1: /* GetPreset */ - fVal = GetCounterPreset(self); - sprintf(pBueffel,"%s.Preset = %f",argv[0],fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - break; - case 2: /* Set Preset */ - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot change preset while counting", eError); - return 0; - } - if(isAuthorised(pCon,usUser)) - { - iRet2 = SetCounterPreset(self,PaRes.Arg[0].fVal); - SCparChange(pCon); - if(iRet2) - SCSendOK(pCon); - return iRet2; - } - else - { - return 0; - } - break; - case 3: /* GetMode */ - eMode = GetCounterMode(self); - if(eMode == eTimer) - { - sprintf(pBueffel,"%s.Mode = Timer",argv[0]); - } - else - { - sprintf(pBueffel,"%s.Mode = Monitor",argv[0]); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - break; - case 4: /* Set Mode */ - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot change mode while counting", eError); - return 0; - } - if(isAuthorised(pCon,usUser)) - { - if(strcmp(PaRes.Arg[0].text,"timer") == 0) - { - SetCounterMode(self,eTimer); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - else if(strcmp(PaRes.Arg[0].text,"monitor") == 0) - { - SetCounterMode(self,ePreset); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: %s not recognized as valid counter mode", - PaRes.Arg[0].text); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - else - { - return 0; - } - case 5: /* GetCounts */ - lVal = GetCounts(self,pCon); - sprintf(pBueffel,"%s.Counts = %ld",argv[0],lVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - - case 6: /* GetMonitor */ - lVal = GetMonitor(self,PaRes.Arg[0].iVal,pCon); - if(lVal < 0) - { - sprintf(pBueffel,"ERROR: %d out of range for monitors", - PaRes.Arg[0].iVal); - SCWrite(pCon,pBueffel,eError); - return 0; - } - sprintf(pBueffel,"%s.Monitor %d = %ld",argv[0],PaRes.Arg[0].iVal, - lVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - case 7: /* SetExponent */ - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - self->iExponent = PaRes.Arg[0].iVal; - SCparChange(pCon); - SCSendOK(pCon); - return 1; - case 8: /* GetExponent */ - sprintf(pBueffel,"%s.Exponent = %d",argv[0], self->iExponent); - SCWrite(pCon,pBueffel,eValue); - return 1; - case 9: /* interest */ - lID = RegisterCallback(self->pCall, MONITOR, CounterInterest, - SCCopyConnection(pCon), - SCDeleteConnection); - SCSendOK(pCon); - return 1; - case 10: /* uninterest */ - RemoveCallbackCon(self->pCall,pCon); - SCSendOK(pCon); - return 1; - case 11: /* status */ - self->pCountInt->TransferData(self,pCon); - if(GetCounterMode(self) == ePreset) - { - sprintf(pBueffel,"%s.CountStatus = %d %d Beam: %ld E6", - argv[0], - (int)nintf(self->pDriv->fPreset), - (int)nintf(self->pDriv->fLastCurrent), - GetMonitor(self,4,pCon)/100000); - } - else - { - sprintf(pBueffel,"%s.CountStatus = %8.2f %8.2f Beam %ld E6", - argv[0], - self->pDriv->fPreset, - self->pDriv->fLastCurrent, - GetMonitor(self,4,pCon)/100000); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - case 12: /* gettime */ - fVal = GetCountTime(self,pCon); - sprintf(pBueffel,"%s.CountTime = %f",argv[0],fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - case 13: - /* countnb, non blocking count */ - return DoCount(self,PaRes.Arg[0].fVal,pCon,0); - break; - case 14: - /* get threshold value */ - iRet = self->pDriv->Get(self->pDriv,"threshold", - PaRes.Arg[0].iVal,&fVal); - if(iRet <= 0) - { - self->pDriv->GetError(self->pDriv,&iRet, - pError,79); - sprintf(pBueffel,"ERROR: %s",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - else - { - sprintf(pBueffel,"%s.threshold%1.1d = %f", - argv[0],PaRes.Arg[0].iVal,fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - break; - case 15: - if(!SCMatchRights(pCon,usMugger)) - { - SCWrite(pCon, - "ERROR: Insufficient privilege to set threshold",eError); - return 0; - } - if(isInRunMode(pServ->pExecutor)) - { - SCWrite(pCon, - "ERROR: cannot change threshold while instrument is active", - eError); - return 0; - } - /* set threshold value */ - iRet = self->pDriv->Set(self->pDriv,"threshold", - PaRes.Arg[0].iVal,PaRes.Arg[1].fVal); - if(iRet <= 0) - { - self->pDriv->GetError(self->pDriv,&iRet, - pError,79); - sprintf(pBueffel,"ERROR: %s",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - else - { - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - break; - case 16: - /* stop */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - self->pCountInt->Halt(self); - SCSendOK(pCon); - return 1; - case 17: - /* mode */ - if(PaRes.Arg[0].iVal) /* set case */ - { - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot change mode while counting",eError); - return 0; - } - if(isAuthorised(pCon,usUser)) - { - if(strcmp(PaRes.Arg[0].text,"timer") == 0) - { - SetCounterMode(self,eTimer); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - else if(strcmp(PaRes.Arg[0].text,"monitor") == 0) - { - SetCounterMode(self,ePreset); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - else - { - sprintf(pBueffel, - "ERROR: %s not recognized as valid counter mode", - PaRes.Arg[0].text); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - } - else /* get case */ - { - eMode = GetCounterMode(self); - if(eMode == eTimer) - { - sprintf(pBueffel,"%s.Mode = Timer",argv[0]); - } - else - { - sprintf(pBueffel,"%s.Mode = Monitor",argv[0]); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - break; - } - break; - case 18: /* preset */ - if(PaRes.Arg[0].iVal) /* set case */ - { - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot set preset while counting", eError); - return 0; - } - if(isAuthorised(pCon,usUser)) - { - iRet2 = SetCounterPreset(self,PaRes.Arg[0].fVal); - if(iRet2) - SCSendOK(pCon); - SCparChange(pCon); - return iRet2; - } - else - { - return 0; - } - } - else /* read case */ - { - fVal = GetCounterPreset(self); - sprintf(pBueffel,"%s.Preset = %f",argv[0],fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - break; - case 19: /* send */ - /* only manager may use this */ - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - Arg2Text(argc-2,&argv[2],pError,79); - iRet = self->pDriv->Send(self->pDriv,pError,pBueffel,255); - if(iRet == 1) - { - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { - self->pDriv->GetError(self->pDriv,&iRet,pError,79); - SCWrite(pCon,pError,eError); - return 0; - } - break; - case 20: /* setpar*/ - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot change parameters while counting", eError); - return 0; - } - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - iRet = self->pDriv->Set(self->pDriv,PaRes.Arg[0].text, - PaRes.Arg[1].iVal, PaRes.Arg[2].fVal); - if(iRet == 1) - { - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - else - { - self->pDriv->GetError(self->pDriv,&iRet,pError,79); - SCWrite(pCon,pError,eError); - return 0; - } - break; - case 21: /* getpar*/ - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - iRet = self->pDriv->Get(self->pDriv,PaRes.Arg[0].text, - PaRes.Arg[1].iVal, &fVal); - if(iRet == 1) - { - sprintf(pBueffel,"%s.%s %d = %f",argv[0],PaRes.Arg[0].text, - PaRes.Arg[1].iVal, fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { - self->pDriv->GetError(self->pDriv,&iRet,pError,79); - SCWrite(pCon,pError,eError); - return 0; - } - break; - case 22: /* getnmon */ - snprintf(pBueffel,131,"%s.getnmon = %d", argv[0], GetNMonitor(self)); - SCWrite(pCon,pBueffel,eValue); - break; - default: - assert(0); /* internal error */ - } - return 0; - } + SCSetRights(pCon, usSpy); + SCWrite(pCon, pBueffel, eWarning); + return 1; +} +/*------------------------------------------------------------------------*/ +pCounter CreateCounter(char *name, pCounterDriver pDriv) +{ + pCounter pRes = NULL; - + assert(pDriv); + + pRes = (pCounter) malloc(sizeof(Counter)); + if (!pRes) { + return NULL; + } + pRes->pDes = CreateDescriptor("SingleCounter"); + if (!pRes->pDes) { + free(pRes); + return NULL; + } + /* initialize Descriptor functions */ + pRes->pDes->GetInterface = CounterGetInterface; + pRes->pDes->SaveStatus = SaveCounterStatus; + + /* initialise countable interface */ + pRes->pCountInt = CreateCountableInterface(); + if (!pRes->pCountInt) { + DeleteDescriptor(pRes->pDes); + free(pRes); + return NULL; + } + pRes->pCountInt->SetCountParameters = SetCountParameters; + pRes->pCountInt->StartCount = StartCount; + pRes->pCountInt->CheckCountStatus = CheckCountStatus; + pRes->pCountInt->TransferData = TransferData; + pRes->pCountInt->Halt = Halt; + pRes->pCountInt->Pause = PauseCount; + pRes->pCountInt->Continue = ContinueCount; + pRes->iCallbackCounter = 20; + + pRes->setMode = SetCounterModeImpl; + pRes->getMode = GetCounterModeImpl; + pRes->getNMonitor = GetNMonitorImpl; + pRes->setPreset = SetCounterPresetImpl; + pRes->getPreset = GetCounterPresetImpl; + pRes->getCounts = GetCountsImpl; + pRes->getMonitor = GetMonitorImpl; + pRes->setMonitor = SetMonitorValueImpl; + pRes->getTime = GetCountTimeImpl; + + pRes->pCall = CreateCallBackInterface(); + + pRes->pDriv = pDriv; + pRes->isUpToDate = 1; + pRes->iExponent = 0; + pRes->name = strdup(name); + return pRes; +} + +/*-----------------------------------------------------------------------*/ + +int CountAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pCounter self = NULL; + int iRet, iRet2; + FuPaResult PaRes; + char pBueffel[256], pError[80]; + char **argx; + float fVal; + long lVal; + long lID; + CounterMode eMode; + FuncTemplate ActionTemplate[] = { + {"count", 1, {FUPAFLOAT}}, + {"getpreset", 0, {0.0}}, + {"setpreset", 1, {FUPAFLOAT}}, + {"getmode", 0, {0, 0}}, + {"setmode", 1, {FUPATEXT}}, + {"getcounts", 0, {0, 0}}, + {"getmonitor", 1, {FUPAINT, 0}}, + {"setexponent", 1, {FUPAINT, 0}}, + {"getexponent", 0, {0, 0}}, + {"interest", 0, {0, 0}}, + {"uninterest", 0, {0, 0}}, + {"status", 0, {0, 0}}, + {"gettime", 0, {0, 0}}, + {"countnb", 1, {FUPAFLOAT}}, + {"getthreshold", 1, {FUPAINT}}, + {"setthreshold", 2, {FUPAINT, FUPAFLOAT}}, + {"stop", 0, {0, 0}}, + {"mode", 1, {FUPAOPT}}, + {"preset", 1, {FUPAOPT}}, + {"send", 0, {0, 0}}, + {"setpar", 3, {FUPATEXT, FUPAINT, FUPAFLOAT}}, + {"getpar", 2, {FUPATEXT, FUPAOPT}}, + {"getnmon", 0, {0, 0}} + }; + char *pMode[] = { + "timer", + "monitor", + NULL + }; + + self = (pCounter) pData; + assert(self); + assert(pCon); + assert(pSics); + + /* parse function args */ + argtolower(argc, argv); + argx = &argv[1]; + iRet = + EvaluateFuPa((pFuncTemplate) & ActionTemplate, 23, argc - 1, argx, + &PaRes); + if (iRet < 0) { + sprintf(pBueffel, "%s", PaRes.pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* do something! */ + switch (iRet) { + case 0: /* Count */ + return DoCount(self, PaRes.Arg[0].fVal, pCon, 1); + break; + case 1: /* GetPreset */ + fVal = GetCounterPreset(self); + sprintf(pBueffel, "%s.Preset = %f", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + break; + case 2: /* Set Preset */ + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot change preset while counting", eError); + return 0; + } + if (isAuthorised(pCon, usUser)) { + iRet2 = SetCounterPreset(self, PaRes.Arg[0].fVal); + SCparChange(pCon); + if (iRet2) + SCSendOK(pCon); + return iRet2; + } else { + return 0; + } + break; + case 3: /* GetMode */ + eMode = GetCounterMode(self); + if (eMode == eTimer) { + sprintf(pBueffel, "%s.Mode = Timer", argv[0]); + } else { + sprintf(pBueffel, "%s.Mode = Monitor", argv[0]); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + break; + case 4: /* Set Mode */ + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot change mode while counting", eError); + return 0; + } + if (isAuthorised(pCon, usUser)) { + if (strcmp(PaRes.Arg[0].text, "timer") == 0) { + SetCounterMode(self, eTimer); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } else if (strcmp(PaRes.Arg[0].text, "monitor") == 0) { + SetCounterMode(self, ePreset); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "ERROR: %s not recognized as valid counter mode", + PaRes.Arg[0].text); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } else { + return 0; + } + case 5: /* GetCounts */ + lVal = GetCounts(self, pCon); + sprintf(pBueffel, "%s.Counts = %ld", argv[0], lVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + + case 6: /* GetMonitor */ + lVal = GetMonitor(self, PaRes.Arg[0].iVal, pCon); + if (lVal < 0) { + sprintf(pBueffel, "ERROR: %d out of range for monitors", + PaRes.Arg[0].iVal); + SCWrite(pCon, pBueffel, eError); + return 0; + } + sprintf(pBueffel, "%s.Monitor %d = %ld", argv[0], PaRes.Arg[0].iVal, + lVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + case 7: /* SetExponent */ + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + self->iExponent = PaRes.Arg[0].iVal; + SCparChange(pCon); + SCSendOK(pCon); + return 1; + case 8: /* GetExponent */ + sprintf(pBueffel, "%s.Exponent = %d", argv[0], self->iExponent); + SCWrite(pCon, pBueffel, eValue); + return 1; + case 9: /* interest */ + lID = RegisterCallback(self->pCall, MONITOR, CounterInterest, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + case 10: /* uninterest */ + RemoveCallbackCon(self->pCall, pCon); + SCSendOK(pCon); + return 1; + case 11: /* status */ + self->pCountInt->TransferData(self, pCon); + if (GetCounterMode(self) == ePreset) { + sprintf(pBueffel, "%s.CountStatus = %d %d Beam: %ld E6", + argv[0], + (int) nintf(self->pDriv->fPreset), + (int) nintf(self->pDriv->fLastCurrent), + GetMonitor(self, 4, pCon) / 100000); + } else { + sprintf(pBueffel, "%s.CountStatus = %8.2f %8.2f Beam %ld E6", + argv[0], + self->pDriv->fPreset, + self->pDriv->fLastCurrent, + GetMonitor(self, 4, pCon) / 100000); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + case 12: /* gettime */ + fVal = GetCountTime(self, pCon); + sprintf(pBueffel, "%s.CountTime = %f", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + case 13: + /* countnb, non blocking count */ + return DoCount(self, PaRes.Arg[0].fVal, pCon, 0); + break; + case 14: + /* get threshold value */ + iRet = self->pDriv->Get(self->pDriv, "threshold", + PaRes.Arg[0].iVal, &fVal); + if (iRet <= 0) { + self->pDriv->GetError(self->pDriv, &iRet, pError, 79); + sprintf(pBueffel, "ERROR: %s", pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } else { + sprintf(pBueffel, "%s.threshold%1.1d = %f", + argv[0], PaRes.Arg[0].iVal, fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + break; + case 15: + if (!SCMatchRights(pCon, usMugger)) { + SCWrite(pCon, + "ERROR: Insufficient privilege to set threshold", eError); + return 0; + } + if (isInRunMode(pServ->pExecutor)) { + SCWrite(pCon, + "ERROR: cannot change threshold while instrument is active", + eError); + return 0; + } + /* set threshold value */ + iRet = self->pDriv->Set(self->pDriv, "threshold", + PaRes.Arg[0].iVal, PaRes.Arg[1].fVal); + if (iRet <= 0) { + self->pDriv->GetError(self->pDriv, &iRet, pError, 79); + sprintf(pBueffel, "ERROR: %s", pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } else { + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } + break; + case 16: + /* stop */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + self->pCountInt->Halt(self); + SCSendOK(pCon); + return 1; + case 17: + /* mode */ + if (PaRes.Arg[0].iVal) { /* set case */ + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot change mode while counting", eError); + return 0; + } + if (isAuthorised(pCon, usUser)) { + if (strcmp(PaRes.Arg[0].text, "timer") == 0) { + SetCounterMode(self, eTimer); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } else if (strcmp(PaRes.Arg[0].text, "monitor") == 0) { + SetCounterMode(self, ePreset); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, + "ERROR: %s not recognized as valid counter mode", + PaRes.Arg[0].text); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + } else { /* get case */ + + eMode = GetCounterMode(self); + if (eMode == eTimer) { + sprintf(pBueffel, "%s.Mode = Timer", argv[0]); + } else { + sprintf(pBueffel, "%s.Mode = Monitor", argv[0]); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + break; + } + break; + case 18: /* preset */ + if (PaRes.Arg[0].iVal) { /* set case */ + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot set preset while counting", eError); + return 0; + } + if (isAuthorised(pCon, usUser)) { + iRet2 = SetCounterPreset(self, PaRes.Arg[0].fVal); + if (iRet2) + SCSendOK(pCon); + SCparChange(pCon); + return iRet2; + } else { + return 0; + } + } else { /* read case */ + + fVal = GetCounterPreset(self); + sprintf(pBueffel, "%s.Preset = %f", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + break; + case 19: /* send */ + /* only manager may use this */ + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + Arg2Text(argc - 2, &argv[2], pError, 79); + iRet = self->pDriv->Send(self->pDriv, pError, pBueffel, 255); + if (iRet == 1) { + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + self->pDriv->GetError(self->pDriv, &iRet, pError, 79); + SCWrite(pCon, pError, eError); + return 0; + } + break; + case 20: /* setpar */ + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot change parameters while counting", + eError); + return 0; + } + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + iRet = self->pDriv->Set(self->pDriv, PaRes.Arg[0].text, + PaRes.Arg[1].iVal, PaRes.Arg[2].fVal); + if (iRet == 1) { + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } else { + self->pDriv->GetError(self->pDriv, &iRet, pError, 79); + SCWrite(pCon, pError, eError); + return 0; + } + break; + case 21: /* getpar */ + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + iRet = self->pDriv->Get(self->pDriv, PaRes.Arg[0].text, + PaRes.Arg[1].iVal, &fVal); + if (iRet == 1) { + sprintf(pBueffel, "%s.%s %d = %f", argv[0], PaRes.Arg[0].text, + PaRes.Arg[1].iVal, fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + self->pDriv->GetError(self->pDriv, &iRet, pError, 79); + SCWrite(pCon, pError, eError); + return 0; + } + break; + case 22: /* getnmon */ + snprintf(pBueffel, 131, "%s.getnmon = %d", argv[0], GetNMonitor(self)); + SCWrite(pCon, pBueffel, eValue); + break; + default: + assert(0); /* internal error */ + } + return 0; +} diff --git a/counter.h b/counter.h index 9c84f64c..46ceb3d5 100644 --- a/counter.h +++ b/counter.h @@ -13,47 +13,59 @@ #define SICSCOUNTER #include "countdriv.h" - typedef struct { - pObjectDescriptor pDes; - char *name; - int isUpToDate; - int iExponent; - pICountable pCountInt; - pCounterDriver pDriv; - pICallBack pCall; - unsigned long tStart; - int iCallbackCounter; - int badStatusCount; - } Counter, *pCounter; - +typedef struct __Counter{ + pObjectDescriptor pDes; + pHdb objectNode; + char *name; + int isUpToDate; + int iExponent; + pICountable pCountInt; + pCounterDriver pDriv; + pICallBack pCall; + unsigned long tStart; + int iCallbackCounter; + int badStatusCount; + int (*setMode)(struct __Counter *self, CounterMode eMode); + CounterMode (*getMode)(struct __Counter *self); + int (*getNMonitor)(struct __Counter *self); + int (*setPreset)(struct __Counter *self, float val); + float (*getPreset)(struct __Counter *self); + long (*getCounts)(struct __Counter *self, SConnection *pCon); + long (*getMonitor)(struct __Counter *self, int iNum, SConnection *pCon); + void (*setMonitor)(struct __Counter *self, int iNum, long val); + float (*getTime)(struct __Counter *self, SConnection *pCon); +} Counter, *pCounter; + /*----------------------------- birth & death -----------------------------*/ - pCounter CreateCounter(char *name, pCounterDriver pDriv); - void DeleteCounter(void *self); - int MakeCounter(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +pCounter CreateCounter(char *name, pCounterDriver pDriv); +void DeleteCounter(void *self); +int MakeCounter(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +/* in countersec.c */ +int MakeSecCter(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*------------------------- set/get Parameters ----------------------------*/ - int SetCounterMode(pCounter self, CounterMode eNew); - CounterMode GetCounterMode(pCounter self); - - int SetCounterPreset(pCounter self, float fVal); - float GetCounterPreset(pCounter self); - - long GetCounts(pCounter self, SConnection *pCon); - long GetMonitor(pCounter self, int iNum, SConnection *pCon); - int GetNMonitor(pCounter self); - void SetMonitorValue(pCounter self, int index, long value); - float GetCountTime(pCounter self, SConnection *pCon); +int SetCounterMode(pCounter self, CounterMode eNew); +CounterMode GetCounterMode(pCounter self); + +int SetCounterPreset(pCounter self, float fVal); +float GetCounterPreset(pCounter self); + +long GetCounts(pCounter self, SConnection * pCon); +long GetMonitor(pCounter self, int iNum, SConnection * pCon); +int GetNMonitor(pCounter self); +void SetMonitorValue(pCounter self, int index, long value); +float GetCountTime(pCounter self, SConnection * pCon); + +int DoCount(pCounter self, float fPreset, SConnection * pCon, int iBlock); - int DoCount(pCounter self,float fPreset, SConnection *pCon, - int iBlock); - /*------------------------------------------------------------------------- the real action: starting and checking is packaged with the ObjectDescriptor. */ - - int CountAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - -#endif + +int CountAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +#endif diff --git a/countersec.c b/countersec.c new file mode 100644 index 00000000..6f5c7630 --- /dev/null +++ b/countersec.c @@ -0,0 +1,504 @@ +/** + * This is a second generation style counter object. It is supposed to work + * nicely with a scriptcontext to drive the actual hardware. This is supposed + * to interface to single counters and histogram memories. This tries to be + * backwards compatible with the old style counter module; thus some + * fields in the data structure will not be used. + * + * copyright: see file COPYRIGHT + * + * Mark Koennecke, February 2009 + */ +#include +#include +#include +#include "sicshipadaba.h" +/*--------------------------------------------------------------------------- + * defines for commmands + * -------------------------------------------------------------------------*/ +#define START 1000 +#define STOP 1001 +#define PAUSE 1002 +#define CONT 1003 +/*---------------------------------------------------------------------------*/ +typedef struct { + float fPreset; + float fCurrent; + char *pName; +} MonEvent, *pMonEvent; +/*---------------------------------------------------------------------------*/ +static int SecCtrInvokeFunction(pCounter self, SConnection *pCon, int code) +{ + pHdb node = NULL; + hdbValue v; + + node = GetHipadabaNode(self->pDes->parNode, "control"); + assert(node != NULL); + v = MakeHdbFloat(code); + return SetHipadabaPar(node,v,pCon); +} +/*---------------------------------------------------------------------------*/ +static int SecCtrHalt(void *pData) +{ + pCounter self = (pCounter)pData; + assert(self != NULL); + + SecCtrInvokeFunction(self,pServ->dummyCon, STOP); + ReleaseCountLock(self->pCountInt); + return 1; +} +/*---------------------------------------------------------------------------*/ +static int SecStartCount(void *pData, SConnection *pCon) +{ + pCounter self = (pCounter)pData; + int status; + pHdb node; + + assert(self != NULL); + + if (!GetCountLock(self->pCountInt, pCon)) { + return 0; + } + + status = SecCtrInvokeFunction(self,pCon, START); + if(status == 1){ + self->isUpToDate = 0; + self->badStatusCount = 0; + self->tStart = time(NULL); + node = GetHipadabaNode(self->pDes->parNode, "status"); + UpdateHipadabaPar(node,MakeHdbText("run"), pCon); + SetHdbProperty(node,"geterror", NULL); + InvokeCallBack(self->pCall,COUNTSTART, pCon); + return 1; + } else { + ReleaseCountLock(self->pCountInt); + return HWFault; + } +} +/*---------------------------------------------------------------------------*/ +static int SecPause(void *pData, SConnection *pCon) +{ + pCounter self = (pCounter)pData; + + assert(self != NULL); + return SecCtrInvokeFunction(self,pCon, PAUSE); +} +/*---------------------------------------------------------------------------*/ +static int SecContinue(void *pData, SConnection *pCon) +{ + pCounter self = (pCounter)pData; + + assert(self != NULL); + return SecCtrInvokeFunction(self,pCon, CONT); +} +/*----------------------------------------------------------------------------*/ +static int SecCtrCheckStatus(void *pData, SConnection *pCon) +{ + pCounter self = (pCounter)pData; + pHdb node = NULL, control = NULL; + hdbValue v; + int status; + MonEvent sMon; + float fControl, fPreset; + + assert(self != NULL); + + node = GetHipadabaNode(self->pDes->parNode,"status"); + assert(node != NULL); + status = GetHipadabaPar(node,&v,pCon); + + if(status != 1){ + ReleaseCountLock(self->pCountInt); + return HWFault; + } + + if(v.v.text == NULL){ + return HWBusy; + } + if (strstr(v.v.text, "idle") != NULL) { + InvokeCallBack(self->pCall, COUNTEND, NULL); + ReleaseCountLock(self->pCountInt); + status = HWIdle; + } else if (strstr(v.v.text, "run") != NULL) { + status = HWBusy; + } else if (strstr(v.v.text, "nobeam") != NULL) { + status = HWNoBeam; + } else if (strstr(v.v.text, "pause") != NULL) { + status = HWPause; + } else if (strstr(v.v.text, "error") != NULL) { + InvokeCallBack(self->pCall, COUNTEND, NULL); + ReleaseCountLock(self->pCountInt); + status = HWFault; + } else { + SCPrintf(pCon, eError, "ERROR: unknown counter status %s found", + v.v.text); + ReleaseCountLock(self->pCountInt); + status = HWFault; + } + + /* + * check for overrun timers + */ + if(self->getMode(self) == eTimer && + time(NULL) > self->tStart + self->getPreset(self)){ + SecCtrHalt(self); + } + + node = GetHipadabaNode(self->pDes->parNode,"control"); + assert(node != NULL); + GetHipadabaPar(node,&v,pCon); + fControl = v.v.doubleValue; + node = GetHipadabaNode(self->pDes->parNode,"preset"); + assert(node != NULL); + GetHipadabaPar(node,&v,pCon); + fPreset = v.v.doubleValue; + + sMon.fCurrent = fControl; + sMon.fPreset = fPreset; + sMon.pName = self->name; + self->badStatusCount = 0; + if (self->iCallbackCounter > 20) { + InvokeCallBack(self->pCall, MONITOR, &sMon); + self->iCallbackCounter = 0; + } else { + self->iCallbackCounter++; + } + + return status; +} +/*--------------------------------------------------------------------------- + * Here is an issue: this ought to wait until data has arrived. Callers + * think now that the data is up to date. With scriptcontext this may not be + * the case. The update may come later or even never. Perhaps this needs + * to be emulated: + * - set a property to some value when starting + * - add an update callback which deletes the property when done. + * - Check that property or the geterror property here in a loop + * until done or we timeout. + * -----------------------------------------------------------------------*/ +static int SecCtrTransferData(void *pData, SConnection *pCon) +{ + pCounter self = (pCounter)pData; + assert(self != NULL); + pHdb node = NULL; + hdbValue v; + + node = GetHipadabaNode(self->pDes->parNode,"values"); + assert(node != NULL); + self->isUpToDate = 1; + return GetHipadabaPar(node,&v,pCon); +} +/*------------------------------------------------------------------------*/ +static void *SecCtrCounterGetInterface(void *pData, int iID) +{ + pCounter self = NULL; + + self = (pCounter) pData; + assert(self); + if (iID == COUNTID) { + return self->pCountInt; + } else if (iID == CALLBACKINTERFACE) { + return self->pCall; + } + return NULL; +} +/*--------------------------------------------------------------------------*/ +static int SecCtrSetMode(pCounter self, CounterMode eNew) +{ + hdbValue v; + pHdb node = NULL; + + node = GetHipadabaNode(self->pDes->parNode,"mode"); + assert(node != NULL); + switch(eNew){ + case eTimer: + v = MakeHdbText("timer"); + break; + case ePreset: + v = MakeHdbText("timer"); + break; + } + return SetHipadabaPar(node,v,NULL); +} +/*---------------------------------------------------------------------------*/ +static CounterMode SecCtrGetMode(pCounter self) +{ + hdbValue v; + pHdb node = NULL; + + node = GetHipadabaNode(self->pDes->parNode,"mode"); + assert(node != NULL); + GetHipadabaPar(node,&v,NULL); + assert(v.v.text != NULL); + if(strcmp(v.v.text,"timer") == 0){ + return eTimer; + } else { + return ePreset; + } +} +/*--------------------------------------------------------------------------*/ +static int SecCtrSetPreset(pCounter self, float val) +{ + hdbValue v; + pHdb node = NULL; + + node = GetHipadabaNode(self->pDes->parNode,"preset"); + assert(node != NULL); + v = MakeHdbFloat(val); + return SetHipadabaPar(node,v,NULL); +} +/*--------------------------------------------------------------------------*/ +static void SecCtrSetCountParameters(void *pData, float fPreset, + CounterMode eMode) +{ + pCounter self = NULL; + + assert(pData); + self = (pCounter) pData; + + SetCounterPreset(self, fPreset); + SetCounterMode(self, eMode); +} + +/*---------------------------------------------------------------------------*/ +static float SecCtrGetPreset(pCounter self) +{ + hdbValue v; + pHdb node = NULL; + + node = GetHipadabaNode(self->pDes->parNode,"preset"); + assert(node != NULL); + GetHipadabaPar(node,&v,NULL); + return (float)v.v.doubleValue; +} +/*--------------------------------------------------------------------------*/ +static int SecCtrGetNMonitor(pCounter self) +{ + hdbValue v; + pHdb node = NULL; + + node = GetHipadabaNode(self->pDes->parNode,"values"); + assert(node != NULL); + GetHipadabaPar(node,&v,NULL); + return v.arrayLength; +} +/*--------------------------------------------------------------------------*/ +static long SecCtrGetMonitor(pCounter self, int iNum, SConnection *pCon) +{ + hdbValue v; + pHdb node = NULL; + + if (!self->isUpToDate) { + self->pCountInt->TransferData(self, pCon); + } + node = GetHipadabaNode(self->pDes->parNode,"values"); + assert(node != NULL); + GetHipadabaPar(node,&v,pCon); + if(iNum >= 0 && iNum < v.arrayLength){ + return (long)v.v.intArray[iNum]; + } else { + return -1L; + } +} +/*--------------------------------------------------------------------------*/ +static long SecCtrGetCounts(pCounter self, SConnection *pCon) +{ + return SecCtrGetMonitor(self,0,pCon); +} +/*--------------------------------------------------------------------------*/ +static void SecCtrSetMonitor(pCounter self, int iNum, long val) +{ + hdbValue v; + pHdb node = NULL; + + node = GetHipadabaNode(self->pDes->parNode,"values"); + assert(node != NULL); + GetHipadabaPar(node,&v,NULL); + if(iNum >= 0 && iNum < v.arrayLength){ + v.v.intArray[iNum] = val; + UpdateHipadabaPar(node,v,NULL); + } +} +/*---------------------------------------------------------------------------*/ +static float SecCtrGetTime(pCounter self, SConnection *pCon) +{ + hdbValue v; + pHdb node = NULL; + + node = GetHipadabaNode(self->pDes->parNode,"time"); + assert(node != NULL); + GetHipadabaPar(node,&v,pCon); + return (float)v.v.doubleValue; +} +/*--------------------------------------------------------------------------*/ +static int CountCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ + float preset; + + if(nPar < 1){ + return 0; + } + + preset = par[0]->value.v.doubleValue; + return DoCount((pCounter)ccmd, preset, con, 1); +} +/*--------------------------------------------------------------------------*/ +static int CountNBCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ + float preset; + + if(nPar < 1){ + return 0; + } + + preset = par[0]->value.v.doubleValue; + return DoCount((pCounter)ccmd, preset, con, 0); +} +/*--------------------------------------------------------------------------*/ +static int StopCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ + pCounter self = (pCounter)ccmd; + return self->pCountInt->Halt(self); +} +/*--------------------------------------------------------------------------*/ +static int PauseCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ + pCounter self = (pCounter)ccmd; + return self->pCountInt->Pause(self,con); +} +/*--------------------------------------------------------------------------*/ +static int ContinueCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ + pCounter self = (pCounter)ccmd; + return self->pCountInt->Continue(self,con); +} +/*--------------------------------------------------------------------------*/ +int MakeSecCter(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pCounter pRes = NULL; + int status, length; + pHdb node, child; + + if(argc < 3) { + SCWrite(pCon,"ERROR: need at least a name and length to create a counter", + eError); + return 0; + } + length = atoi(argv[2]); + + pRes = (pCounter) malloc(sizeof(Counter)); + if (!pRes) { + SCWrite(pCon,"ERROR: out of memory in MakeSecCter", eError); + return 0; + } + memset(pRes,0,sizeof(Counter)); + pRes->pDes = CreateDescriptor("SingleCounter"); + if (!pRes->pDes) { + SCWrite(pCon,"ERROR: out of memory in MakeSecCter", eError); + return 0; + } + /* initialize Descriptor functions */ + pRes->pDes->GetInterface = SecCtrCounterGetInterface; + pRes->pDes->SaveStatus = SaveSICSOBJ; + + /* initialise countable interface */ + pRes->pCountInt = CreateCountableInterface(); + if (!pRes->pCountInt) { + DeleteDescriptor(pRes->pDes); + SCWrite(pCon,"ERROR: out of memory in MakeSecCter", eError); + return 0; + } + pRes->pCountInt->SetCountParameters = SecCtrSetCountParameters; + pRes->pCountInt->StartCount = SecStartCount; + pRes->pCountInt->CheckCountStatus = SecCtrCheckStatus; + pRes->pCountInt->TransferData = SecCtrTransferData; + pRes->pCountInt->Halt = SecCtrHalt; + pRes->pCountInt->Pause = SecPause; + pRes->pCountInt->Continue = SecContinue; + pRes->iCallbackCounter = 20; + + pRes->setMode = SecCtrSetMode; + pRes->getMode = SecCtrGetMode; + pRes->getNMonitor = SecCtrGetNMonitor; + pRes->setPreset = SecCtrSetPreset; + pRes->getPreset = SecCtrGetPreset; + pRes->getCounts = SecCtrGetCounts; + pRes->getMonitor = SecCtrGetMonitor; + pRes->setMonitor = SecCtrSetMonitor; + pRes->getTime = SecCtrGetTime; + + pRes->pCall = CreateCallBackInterface(); + + pRes->isUpToDate = 1; + pRes->iExponent = 0; + pRes->name = strdup(argv[1]); + + + node = MakeHipadabaNode(argv[1],HIPNONE, 0); + pRes->pDes->parNode = node; + pRes->objectNode = node; + + child = MakeSICSHdbPar("time", usInternal, MakeHdbFloat(.0)); + if (child == NULL) { + return 0; + } + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("preset", usUser, MakeHdbFloat(.0)); + if (child == NULL) { + return 0; + } + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("mode", usUser, MakeHdbText("monitor")); + if (child == NULL) { + return 0; + } + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("status", usInternal, MakeHdbText("idle")); + if (child == NULL) { + return 0; + } + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("control", usUser, MakeHdbFloat(.0)); + if (child == NULL) { + return 0; + } + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("values", usInternal, + makeHdbValue(HIPINTAR, length)); + if (child == NULL) { + return 0; + } + AddHipadabaChild(node, child, NULL); + + child = AddSICSHdbPar(node,"count", usUser, MakeSICSFunc(CountCmd)); + AddSICSHdbPar(child, "preset", usUser, MakeHdbFloat(2)); + + child = AddSICSHdbPar(node,"countnb", usUser, MakeSICSFunc(CountNBCmd)); + AddSICSHdbPar(child, "preset", usUser, MakeHdbFloat(2)); + + child = AddSICSHdbPar(node,"stop", usUser, MakeSICSFunc(StopCmd)); + child = AddSICSHdbPar(node,"pause", usUser, MakeSICSFunc(PauseCmd)); + child = AddSICSHdbPar(node,"continue", usUser, MakeSICSFunc(ContinueCmd)); + + status = + AddCommand(pSics, argv[1], InterInvokeSICSOBJ, DeleteCounter, + (void *) pRes); + if (status != 1) { + SCPrintf(pCon,eError, "ERROR: duplicate command %s not created", argv[1]); + return 0; + } + return 1; +} diff --git a/crysconv.c b/crysconv.c index 64def425..cfd9036c 100644 --- a/crysconv.c +++ b/crysconv.c @@ -8,8 +8,8 @@ /* Common Block Declarations */ struct { - doublereal s[16] /* was [4][4] */, sinv[16] /* was [4][4] */; - integer iok; + doublereal s[16] /* was [4][4] */ , sinv[16] /* was [4][4] */ ; + integer iok; } osolem_; #define osolem_1 osolem_ @@ -39,25 +39,25 @@ struct { /* SUBROUTINE INVS(S,SINV,IER) */ /* SUBROUTINE ERRESO(MODULE,IER) */ /* ------------------------------------------------------------------ */ -/* Subroutine */ int setrlp_(doublereal *sam, integer *ier) +/* Subroutine */ int setrlp_(doublereal * sam, integer * ier) { - /* System generated locals */ - doublereal d__1; + /* System generated locals */ + doublereal d__1; - /* Builtin functions */ - double cos(doublereal), sin(doublereal), sqrt(doublereal), atan( - doublereal); + /* Builtin functions */ + double cos(doublereal), sin(doublereal), sqrt(doublereal), + atan(doublereal); - /* Local variables */ - static doublereal alfa[3], cosa[3], cosb[3]; - static integer imod; - static doublereal sina[3], sinb[3], aspv[6] /* was [3][2] */; - extern /* Subroutine */ int invs_(doublereal *, doublereal *, integer *); - static doublereal a[3], b[3], c__[3], bb[9] /* was [3][3] */, cc; - static integer id, ie, jd, je, jf, kg, lf, lh, md, me, ne; - static doublereal zp, vv[9] /* was [3][3] */; - extern /* Subroutine */ int erreso_(integer *, integer *); - static doublereal rlb[6] /* was [3][2] */; + /* Local variables */ + static doublereal alfa[3], cosa[3], cosb[3]; + static integer imod; + static doublereal sina[3], sinb[3], aspv[6] /* was [3][2] */ ; + extern /* Subroutine */ int invs_(doublereal *, doublereal *, integer *); + static doublereal a[3], b[3], c__[3], bb[9] /* was [3][3] */ , cc; + static integer id, ie, jd, je, jf, kg, lf, lh, md, me, ne; + static doublereal zp, vv[9] /* was [3][3] */ ; + extern /* Subroutine */ int erreso_(integer *, integer *); + static doublereal rlb[6] /* was [3][2] */ ; /* ============================ */ @@ -95,186 +95,189 @@ struct { /* ----------------------------------------------------------------------- */ /* SOME TESTS AND INIT OF CALCUALTION */ - /* Parameter adjustments */ - --sam; + /* Parameter adjustments */ + --sam; - /* Function Body */ - *ier = 0; - imod = 1; - zp = 6.2831853071795862; - osolem_1.iok = 0; - for (id = 1; id <= 3; ++id) { - a[id - 1] = sam[id]; - alfa[id - 1] = sam[id + 3]; - aspv[id - 1] = sam[id + 6]; - aspv[id + 2] = sam[id + 9]; + /* Function Body */ + *ier = 0; + imod = 1; + zp = 6.2831853071795862; + osolem_1.iok = 0; + for (id = 1; id <= 3; ++id) { + a[id - 1] = sam[id]; + alfa[id - 1] = sam[id + 3]; + aspv[id - 1] = sam[id + 6]; + aspv[id + 2] = sam[id + 9]; /* L10: */ - } + } - for (id = 1; id <= 3; ++id) { - *ier = 1; - if ((d__1 = a[id - 1], abs(d__1)) <= 1e-8) { - goto L999; - } - *ier = 0; -/* L20: */ - } - for (id = 1; id <= 3; ++id) { - a[id - 1] /= zp; - alfa[id - 1] /= 57.29577951308232087679815481410517; - cosa[id - 1] = cos(alfa[id - 1]); - sina[id - 1] = sin(alfa[id - 1]); -/* L30: */ - } - cc = cosa[0] * cosa[0] + cosa[1] * cosa[1] + cosa[2] * cosa[2]; - cc = cosa[0] * 2. * cosa[1] * cosa[2] + 1. - cc; - *ier = 2; - if (cc <= .1) { - goto L999; + for (id = 1; id <= 3; ++id) { + *ier = 1; + if ((d__1 = a[id - 1], abs(d__1)) <= 1e-8) { + goto L999; } *ier = 0; - cc = sqrt(cc); - je = 2; - kg = 3; - for (id = 1; id <= 3; ++id) { - b[id - 1] = sina[id - 1] / (a[id - 1] * cc); - cosb[id - 1] = (cosa[je - 1] * cosa[kg - 1] - cosa[id - 1]) / (sina[ - je - 1] * sina[kg - 1]); - sinb[id - 1] = sqrt(1. - cosb[id - 1] * cosb[id - 1]); - rlb[id + 2] = (d__1 = atan(sinb[id - 1] / cosb[id - 1]), abs(d__1)) * - 57.29577951308232087679815481410517; - je = kg; - kg = id; +/* L20: */ + } + for (id = 1; id <= 3; ++id) { + a[id - 1] /= zp; + alfa[id - 1] /= 57.29577951308232087679815481410517; + cosa[id - 1] = cos(alfa[id - 1]); + sina[id - 1] = sin(alfa[id - 1]); +/* L30: */ + } + cc = cosa[0] * cosa[0] + cosa[1] * cosa[1] + cosa[2] * cosa[2]; + cc = cosa[0] * 2. * cosa[1] * cosa[2] + 1. - cc; + *ier = 2; + if (cc <= .1) { + goto L999; + } + *ier = 0; + cc = sqrt(cc); + je = 2; + kg = 3; + for (id = 1; id <= 3; ++id) { + b[id - 1] = sina[id - 1] / (a[id - 1] * cc); + cosb[id - 1] = + (cosa[je - 1] * cosa[kg - 1] - + cosa[id - 1]) / (sina[je - 1] * sina[kg - 1]); + sinb[id - 1] = sqrt(1. - cosb[id - 1] * cosb[id - 1]); + rlb[id + 2] = (d__1 = atan(sinb[id - 1] / cosb[id - 1]), abs(d__1)) * + 57.29577951308232087679815481410517; + je = kg; + kg = id; /* L40: */ - } - bb[0] = b[0]; - bb[1] = 0.; - bb[2] = 0.; - bb[3] = b[1] * cosb[2]; - bb[4] = b[1] * sinb[2]; - bb[5] = 0.; - bb[6] = b[2] * cosb[1]; - bb[7] = -b[2] * sinb[1] * cosa[0]; - bb[8] = 1. / a[2]; + } + bb[0] = b[0]; + bb[1] = 0.; + bb[2] = 0.; + bb[3] = b[1] * cosb[2]; + bb[4] = b[1] * sinb[2]; + bb[5] = 0.; + bb[6] = b[2] * cosb[1]; + bb[7] = -b[2] * sinb[1] * cosa[0]; + bb[8] = 1. / a[2]; - for (id = 1; id <= 3; ++id) { - rlb[id - 1] = 0.; - for (je = 1; je <= 3; ++je) { + for (id = 1; id <= 3; ++id) { + rlb[id - 1] = 0.; + for (je = 1; je <= 3; ++je) { /* Computing 2nd power */ - d__1 = bb[je + id * 3 - 4]; - rlb[id - 1] += d__1 * d__1; + d__1 = bb[je + id * 3 - 4]; + rlb[id - 1] += d__1 * d__1; /* L60: */ - } - *ier = 1; - if ((d__1 = rlb[id - 1], abs(d__1)) <= 1e-8) { - goto L999; - } - *ier = 0; - rlb[id - 1] = sqrt(rlb[id - 1]); -/* L50: */ } + *ier = 1; + if ((d__1 = rlb[id - 1], abs(d__1)) <= 1e-8) { + goto L999; + } + *ier = 0; + rlb[id - 1] = sqrt(rlb[id - 1]); +/* L50: */ + } /* ----------------------------------------------------------------------- */ /* GENERATION OF S ORIENTATION MATRIX REC. LATTICE TO SCATTERING PLANE */ - for (kg = 1; kg <= 2; ++kg) { - for (ie = 1; ie <= 3; ++ie) { - vv[kg + ie * 3 - 4] = 0.; - for (jf = 1; jf <= 3; ++jf) { - vv[kg + ie * 3 - 4] += bb[ie + jf * 3 - 4] * aspv[jf + kg * 3 - - 4]; + for (kg = 1; kg <= 2; ++kg) { + for (ie = 1; ie <= 3; ++ie) { + vv[kg + ie * 3 - 4] = 0.; + for (jf = 1; jf <= 3; ++jf) { + vv[kg + ie * 3 - 4] += bb[ie + jf * 3 - 4] * aspv[jf + kg * 3 - 4]; /* L90: */ - } + } /* L80: */ - } + } /* L70: */ - } - for (md = 3; md >= 2; --md) { - for (ne = 1; ne <= 3; ++ne) { - id = md % 3 + 1; - je = (md + 1) % 3 + 1; - kg = ne % 3 + 1; - lh = (ne + 1) % 3 + 1; - vv[md + ne * 3 - 4] = vv[id + kg * 3 - 4] * vv[je + lh * 3 - 4] - - vv[id + lh * 3 - 4] * vv[je + kg * 3 - 4]; + } + for (md = 3; md >= 2; --md) { + for (ne = 1; ne <= 3; ++ne) { + id = md % 3 + 1; + je = (md + 1) % 3 + 1; + kg = ne % 3 + 1; + lh = (ne + 1) % 3 + 1; + vv[md + ne * 3 - 4] = vv[id + kg * 3 - 4] * vv[je + lh * 3 - 4] - + vv[id + lh * 3 - 4] * vv[je + kg * 3 - 4]; /* L110: */ - } + } /* L100: */ - } + } - for (id = 1; id <= 3; ++id) { - c__[id - 1] = 0.; - for (je = 1; je <= 3; ++je) { + for (id = 1; id <= 3; ++id) { + c__[id - 1] = 0.; + for (je = 1; je <= 3; ++je) { /* Computing 2nd power */ - d__1 = vv[id + je * 3 - 4]; - c__[id - 1] += d__1 * d__1; + d__1 = vv[id + je * 3 - 4]; + c__[id - 1] += d__1 * d__1; /* L130: */ - } - *ier = 3; - if ((d__1 = c__[id - 1], abs(d__1)) <= 1e-6) { - goto L999; - } - *ier = 0; - c__[id - 1] = sqrt(c__[id - 1]); + } + *ier = 3; + if ((d__1 = c__[id - 1], abs(d__1)) <= 1e-6) { + goto L999; + } + *ier = 0; + c__[id - 1] = sqrt(c__[id - 1]); /* L120: */ - } + } - for (id = 1; id <= 3; ++id) { - for (je = 1; je <= 3; ++je) { - vv[je + id * 3 - 4] /= c__[je - 1]; + for (id = 1; id <= 3; ++id) { + for (je = 1; je <= 3; ++je) { + vv[je + id * 3 - 4] /= c__[je - 1]; /* L160: */ - } + } /* L150: */ - } - for (kg = 1; kg <= 3; ++kg) { - for (me = 1; me <= 3; ++me) { - osolem_1.s[kg + (me << 2) - 5] = 0.; - for (lf = 1; lf <= 3; ++lf) { - osolem_1.s[kg + (me << 2) - 5] += vv[kg + lf * 3 - 4] * bb[lf - + me * 3 - 4]; + } + for (kg = 1; kg <= 3; ++kg) { + for (me = 1; me <= 3; ++me) { + osolem_1.s[kg + (me << 2) - 5] = 0.; + for (lf = 1; lf <= 3; ++lf) { + osolem_1.s[kg + (me << 2) - 5] += vv[kg + lf * 3 - 4] * bb[lf + + + me * 3 - + 4]; /* L190: */ - } + } /* L180: */ - } + } /* L170: */ - } - osolem_1.s[15] = 1.; - for (jd = 1; jd <= 3; ++jd) { - osolem_1.s[(jd << 2) - 1] = 0.; - osolem_1.s[jd + 11] = 0.; + } + osolem_1.s[15] = 1.; + for (jd = 1; jd <= 3; ++jd) { + osolem_1.s[(jd << 2) - 1] = 0.; + osolem_1.s[jd + 11] = 0.; /* L200: */ - } + } /* ----------------------------------------------------------------------- */ /* INVERT TRANSFORMATION MATRIX S AND PU RESULT IN SINV */ - *ier = 3; - invs_(osolem_1.s, osolem_1.sinv, ier); - *ier = 0; - if (*ier != 0) { - goto L999; - } - osolem_1.iok = 123; + *ier = 3; + invs_(osolem_1.s, osolem_1.sinv, ier); + *ier = 0; + if (*ier != 0) { + goto L999; + } + osolem_1.iok = 123; /* --------------------------------------------------------------------------- */ /* SORTIE */ L999: - if (*ier != 0) { - erreso_(&imod, ier); - } - return 0; -} /* setrlp_ */ + if (*ier != 0) { + erreso_(&imod, ier); + } + return 0; +} /* setrlp_ */ /* =========================================================================== */ -/* Subroutine */ int rl2spv_(doublereal *qhkl, doublereal *qt, doublereal *qm, - doublereal *qs, integer *ier) +/* Subroutine */ int rl2spv_(doublereal * qhkl, doublereal * qt, + doublereal * qm, + doublereal * qs, integer * ier) { - /* System generated locals */ - doublereal d__1; + /* System generated locals */ + doublereal d__1; - /* Builtin functions */ - double sqrt(doublereal); + /* Builtin functions */ + double sqrt(doublereal); - /* Local variables */ - static integer id, je; + /* Local variables */ + static integer id, je; /* ========================================= */ @@ -302,61 +305,62 @@ L999: /* --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- */ /* INIT AND TEST IF TRANSFO MATRICES ARE OK */ - /* Parameter adjustments */ - --qt; - --qhkl; + /* Parameter adjustments */ + --qt; + --qhkl; - /* Function Body */ - *ier = 1; - if (osolem_1.iok != 123) { - goto L999; - } - *ier = 0; + /* Function Body */ + *ier = 1; + if (osolem_1.iok != 123) { + goto L999; + } + *ier = 0; /* ----------------------------------------------------------------------- */ - for (id = 1; id <= 3; ++id) { - qt[id] = 0.; - for (je = 1; je <= 3; ++je) { - qt[id] += qhkl[je] * osolem_1.s[id + (je << 2) - 5]; + for (id = 1; id <= 3; ++id) { + qt[id] = 0.; + for (je = 1; je <= 3; ++je) { + qt[id] += qhkl[je] * osolem_1.s[id + (je << 2) - 5]; /* L20: */ - } + } /* L10: */ - } - *ier = 2; - if (abs(qt[3]) > 1e-4) { - goto L999; - } - *ier = 0; - *qs = 0.; - for (id = 1; id <= 3; ++id) { + } + *ier = 2; + if (abs(qt[3]) > 1e-4) { + goto L999; + } + *ier = 0; + *qs = 0.; + for (id = 1; id <= 3; ++id) { /* Computing 2nd power */ - d__1 = qt[id]; - *qs += d__1 * d__1; + d__1 = qt[id]; + *qs += d__1 * d__1; /* L30: */ - } - if (*qs < 1e-8) { - *ier = 3; - } else { - *qm = sqrt(*qs); - } + } + if (*qs < 1e-8) { + *ier = 3; + } else { + *qm = sqrt(*qs); + } /* --------------------------------------------------------------------------- */ L999: - return 0; -} /* rl2spv_ */ + return 0; +} /* rl2spv_ */ /* =========================================================================== */ -/* Subroutine */ int sp2rlv_(doublereal *qhkl, doublereal *qt, doublereal *qm, - doublereal *qs, integer *ier) +/* Subroutine */ int sp2rlv_(doublereal * qhkl, doublereal * qt, + doublereal * qm, + doublereal * qs, integer * ier) { - /* System generated locals */ - doublereal d__1; + /* System generated locals */ + doublereal d__1; - /* Builtin functions */ - double sqrt(doublereal); + /* Builtin functions */ + double sqrt(doublereal); - /* Local variables */ - static integer id, je; + /* Local variables */ + static integer id, je; /* ========================================= */ @@ -384,59 +388,60 @@ L999: /* --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- */ /* INIT AND TEST IF TRANSFO MATRICES ARE OK */ - /* Parameter adjustments */ - --qt; - --qhkl; + /* Parameter adjustments */ + --qt; + --qhkl; - /* Function Body */ - *ier = 1; - if (osolem_1.iok != 123) { - goto L999; - } - *ier = 2; - if (abs(qt[3]) > 1e-4) { - goto L999; - } - *ier = 0; + /* Function Body */ + *ier = 1; + if (osolem_1.iok != 123) { + goto L999; + } + *ier = 2; + if (abs(qt[3]) > 1e-4) { + goto L999; + } + *ier = 0; /* ----------------------------------------------------------------------- */ - *qs = 0.; - for (id = 1; id <= 3; ++id) { + *qs = 0.; + for (id = 1; id <= 3; ++id) { /* Computing 2nd power */ - d__1 = qt[id]; - *qs += d__1 * d__1; + d__1 = qt[id]; + *qs += d__1 * d__1; /* L10: */ - } - if (*qs < 1e-8) { - *ier = 3; - } else { - *qm = sqrt(*qs); - } + } + if (*qs < 1e-8) { + *ier = 3; + } else { + *qm = sqrt(*qs); + } /* ----------------------------------------------------------------------- */ - for (id = 1; id <= 3; ++id) { - qhkl[id] = 0.; - for (je = 1; je <= 3; ++je) { - qhkl[id] += osolem_1.sinv[id + (je << 2) - 5] * qt[je]; + for (id = 1; id <= 3; ++id) { + qhkl[id] = 0.; + for (je = 1; je <= 3; ++je) { + qhkl[id] += osolem_1.sinv[id + (je << 2) - 5] * qt[je]; /* L30: */ - } -/* L20: */ } +/* L20: */ + } /* --------------------------------------------------------------------------- */ L999: - return 0; -} /* sp2rlv_ */ + return 0; +} /* sp2rlv_ */ /* ========================================================================== */ -/* Subroutine */ int invs_(doublereal *s, doublereal *sinv, integer *ier) +/* Subroutine */ int invs_(doublereal * s, doublereal * sinv, + integer * ier) { - /* Initialized data */ + /* Initialized data */ - static integer m[3] = { 2,3,1 }; - static integer n[3] = { 3,1,2 }; + static integer m[3] = { 2, 3, 1 }; + static integer n[3] = { 3, 1, 2 }; - static integer id, je, mi, mj, ni, nj; - static doublereal det; + static integer id, je, mi, mj, ni, nj; + static doublereal det; /* ============================== */ @@ -453,58 +458,61 @@ L999: /* Define the dummy arguments */ /* ------------------------------------------------------------------ */ - /* Parameter adjustments */ - sinv -= 5; - s -= 5; + /* Parameter adjustments */ + sinv -= 5; + s -= 5; - /* Function Body */ + /* Function Body */ /* ------------------------------------------------------------------ */ - *ier = 0; - for (id = 1; id <= 4; ++id) { - for (je = 1; je <= 4; ++je) { - sinv[id + (je << 2)] = 0.; + *ier = 0; + for (id = 1; id <= 4; ++id) { + for (je = 1; je <= 4; ++je) { + sinv[id + (je << 2)] = 0.; /* L20: */ - } + } /* L10: */ - } - det = 0.; - for (id = 1; id <= 3; ++id) { - for (je = 1; je <= 3; ++je) { - mi = m[id - 1]; - mj = m[je - 1]; - ni = n[id - 1]; - nj = n[je - 1]; - sinv[je + (id << 2)] = s[mi + (mj << 2)] * s[ni + (nj << 2)] - s[ - ni + (mj << 2)] * s[mi + (nj << 2)]; + } + det = 0.; + for (id = 1; id <= 3; ++id) { + for (je = 1; je <= 3; ++je) { + mi = m[id - 1]; + mj = m[je - 1]; + ni = n[id - 1]; + nj = n[je - 1]; + sinv[je + (id << 2)] = + s[mi + (mj << 2)] * s[ni + (nj << 2)] - s[ni + + (mj << 2)] * s[mi + + (nj << + 2)]; /* L40: */ - } - det += s[id + 4] * sinv[(id << 2) + 1]; + } + det += s[id + 4] * sinv[(id << 2) + 1]; /* L30: */ - } - if (abs(det) < 1e-6) { - *ier = 1; - } else { - for (id = 1; id <= 3; ++id) { - for (je = 1; je <= 3; ++je) { - sinv[id + (je << 2)] /= det; + } + if (abs(det) < 1e-6) { + *ier = 1; + } else { + for (id = 1; id <= 3; ++id) { + for (je = 1; je <= 3; ++je) { + sinv[id + (je << 2)] /= det; /* L70: */ - } + } /* L60: */ - } } - sinv[20] = 1.; - return 0; -} /* invs_ */ + } + sinv[20] = 1.; + return 0; +} /* invs_ */ /* ========================================================================= */ -/* Subroutine */ int erreso_(integer *module, integer *ier) +/* Subroutine */ int erreso_(integer * module, integer * ier) { - /* System generated locals */ - integer i__1; + /* System generated locals */ + integer i__1; - /* Local variables */ - static integer lmod, lier; + /* Local variables */ + static integer lmod, lier; /* ============================= */ @@ -524,15 +532,12 @@ L999: /* --------------------------------------------------------------------------- */ /* Computing MIN */ - i__1 = max(*ier,1); - lier = min(i__1,4); + i__1 = max(*ier, 1); + lier = min(i__1, 4); /* Computing MIN */ - i__1 = max(*module,1); - lmod = min(i__1,3); + i__1 = max(*module, 1); + lmod = min(i__1, 3); /* WRITE(6,501) MESER(LIER,LMOD) */ /* 501 FORMAT(A) */ - return 0; -} /* erreso_ */ - - - + return 0; +} /* erreso_ */ diff --git a/cryst.c b/cryst.c index 5ae01f8b..a47d4fdd 100644 --- a/cryst.c +++ b/cryst.c @@ -24,19 +24,19 @@ MATRIX chimat(double dAngle) { - MATRIX res; - double dChi; + MATRIX res; + double dChi; - res = mat_creat(3,3,ZERO_MATRIX); - dChi = dAngle/PIR; - - res[0][0] = cos(dChi); - res[0][2] = sin(dChi); - res[1][1] = 1.; - res[2][0] = -res[0][2]; - res[2][2] = res[0][0]; + res = mat_creat(3, 3, ZERO_MATRIX); + dChi = dAngle / PIR; - return res; + res[0][0] = cos(dChi); + res[0][2] = sin(dChi); + res[1][1] = 1.; + res[2][0] = -res[0][2]; + res[2][2] = res[0][0]; + + return res; } @@ -47,20 +47,21 @@ MATRIX chimat(double dAngle) MATRIX phimat(double dAngle) { - MATRIX res; - double dPhi; + MATRIX res; + double dPhi; - res = mat_creat(3,3,ZERO_MATRIX); - dPhi = dAngle/PIR; - - res[0][0] = cos(dPhi); - res[0][1] = sin(dChi); - res[2][2] = 1.; - res[1][0] = -res[0][1]; - res[1][1] = res[0][0]; + res = mat_creat(3, 3, ZERO_MATRIX); + dPhi = dAngle / PIR; - return res; + res[0][0] = cos(dPhi); + res[0][1] = sin(dChi); + res[2][2] = 1.; + res[1][0] = -res[0][1]; + res[1][1] = res[0][0]; + + return res; } + /*------------------------------------------------------------------------- psimat, calculate psi rotation matrix. The input angle is in degrees. The setting is Busing & Levy. @@ -68,19 +69,19 @@ MATRIX phimat(double dAngle) MATRIX psimat(double dAngle) { - MATRIX res; - double dPsi; + MATRIX res; + double dPsi; - res = mat_creat(3,3,ZERO_MATRIX); - dPsi = dAngle/PIR; - - res[0][0] = 1.; - res[1][1] = cos(dPsi); - res[1][2] = -sin(dPsi); - res[2][1] = -res[1][2]; - res[2][2] = res[1][1]; + res = mat_creat(3, 3, ZERO_MATRIX); + dPsi = dAngle / PIR; - return res; + res[0][0] = 1.; + res[1][1] = cos(dPsi); + res[1][2] = -sin(dPsi); + res[2][1] = -res[1][2]; + res[2][2] = res[1][1]; + + return res; } /*------------------------------------------------------------------------- @@ -88,27 +89,26 @@ MATRIX psimat(double dAngle) chi and phi. The angled need not be bissecting but it is assumed that the diffraction vector is in the equatorial plane. --------------------------------------------------------------------------*/ - -MATRIX diffFromAngles(double wave, double tth, double om, - double chi, double phi) + +MATRIX diffFromAngles(double wave, double tth, double om, + double chi, double phi) { - MATRIX res, rot, dum, z; - double dTh; + MATRIX res, rot, dum, z; + double dTh; - dTh = (tth/2.)/PIR; - res = mat_creat(3,1,ZERO_MATRIX); - res[0][0] = (2.*sin(dTh)*cos(dTh))/wave; - res[1][0] = (-2. *sin(dTh)*sin(dTh))/wave; + dTh = (tth / 2.) / PIR; + res = mat_creat(3, 1, ZERO_MATRIX); + res[0][0] = (2. * sin(dTh) * cos(dTh)) / wave; + res[1][0] = (-2. * sin(dTh) * sin(dTh)) / wave; - /* undo omega rotation */ - rot = phimat(om); - dum = mat_tran(rot); - mat_free(rot); - z = mat_mul(dum,res); - mat_free(dum); - mat_free(res); + /* undo omega rotation */ + rot = phimat(om); + dum = mat_tran(rot); + mat_free(rot); + z = mat_mul(dum, res); + mat_free(dum); + mat_free(res); + + /* result is now z */ - /* result is now z */ - } - diff --git a/d_mod.c b/d_mod.c index 3766d9fa..6c667a24 100644 --- a/d_mod.c +++ b/d_mod.c @@ -6,7 +6,8 @@ double drem(); #else double floor(); #endif -double d_mod(x,y) doublereal *x, *y; +double d_mod(x, y) +doublereal *x, *y; #else #ifdef IEEE_drem double drem(double, double); @@ -17,30 +18,29 @@ double drem(double, double); extern "C" { #endif #endif -double d_mod(doublereal *x, doublereal *y) + double d_mod(doublereal * x, doublereal * y) #endif -{ + { #ifdef IEEE_drem - double xa, ya, z; - if ((ya = *y) < 0.) - ya = -ya; - z = drem(xa = *x, ya); - if (xa > 0) { - if (z < 0) - z += ya; - } - else if (z > 0) - z -= ya; - return z; + double xa, ya, z; + if ((ya = *y) < 0.) + ya = -ya; + z = drem(xa = *x, ya); + if (xa > 0) { + if (z < 0) + z += ya; + } else if (z > 0) + z -= ya; + return z; #else - double quotient; - if( (quotient = *x / *y) >= 0) - quotient = floor(quotient); - else - quotient = -floor(-quotient); - return(*x - (*y) * quotient ); + double quotient; + if ((quotient = *x / *y) >= 0) + quotient = floor(quotient); + else + quotient = -floor(-quotient); + return (*x - (*y) * quotient); #endif -} + } #ifdef __cplusplus } #endif diff --git a/d_sign.c b/d_sign.c index d06e0d19..6f05e712 100644 --- a/d_sign.c +++ b/d_sign.c @@ -4,15 +4,15 @@ extern "C" { #endif #ifdef KR_headers -double d_sign(a,b) doublereal *a, *b; + double d_sign(a, b) doublereal *a, *b; #else -double d_sign(doublereal *a, doublereal *b) + double d_sign(doublereal * a, doublereal * b) #endif -{ -double x; -x = (*a >= 0 ? *a : - *a); -return( *b >= 0 ? x : -x); -} + { + double x; + x = (*a >= 0 ? *a : -*a); + return (*b >= 0 ? x : -x); + } #ifdef __cplusplus } #endif diff --git a/danu.c b/danu.c index de9ef6e7..b67a19be 100644 --- a/danu.c +++ b/danu.c @@ -51,11 +51,11 @@ #include "danu.h" /* ------------------ the data structure ----------------------------------*/ - typedef struct __DataNumber { - pObjectDescriptor pDes; - pICallBack pCall; - char *pFileName; - } DataNumber; +typedef struct __DataNumber { + pObjectDescriptor pDes; + pICallBack pCall; + char *pFileName; +} DataNumber; /*----------------------------------------------------------------------*/ static int readDataNumber(pDataNumber self) { @@ -63,360 +63,329 @@ static int readDataNumber(pDataNumber self) int iNum = 0; /* open file */ - fd = fopen(self->pFileName,"r"); - if(!fd) - { + fd = fopen(self->pFileName, "r"); + if (!fd) { return -1; } - + /* get and increment number */ - fscanf(fd,"%d",&iNum); + fscanf(fd, "%d", &iNum); fclose(fd); return iNum; } + /*-----------------------------------------------------------------------*/ static int writeDataNumber(pDataNumber self, int iNum) { FILE *fd = NULL; /* reopen for rewriting */ - fd = fopen(self->pFileName,"w"); - if(fd == NULL) - { + fd = fopen(self->pFileName, "w"); + if (fd == NULL) { return -1; } - + /* write file and leave */ - fprintf(fd," %d \n",iNum); - fprintf(fd,"NEVER, EVER modify or delete this file\n"); + fprintf(fd, " %d \n", iNum); + fprintf(fd, "NEVER, EVER modify or delete this file\n"); fprintf(fd, - "You'll risk eternal damnation and a reincarnation as a cockroach!|n"); + "You'll risk eternal damnation and a reincarnation as a cockroach!|n"); fclose(fd); return 1; } + /*------------------- The CallBack function for interest ------------------*/ - static int InterestCallback(int iEvent, void *pEvent, void *pUser) - { - pDataNumber self = NULL; - SConnection *pCon = NULL; - char pBueffel[132]; - int iNum; - - pCon = (SConnection *)pUser; - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } - - if(iEvent != VALUECHANGE) - { - return 1; - } - - assert(pEvent); - assert(pUser); - - self = (pDataNumber)pEvent; - - /* - read number - */ - iNum = readDataNumber(self); - if(iNum > 0) - { - snprintf(pBueffel,131,"sicsdatanumber = %d", iNum); - SCWrite(pCon,pBueffel,eValue); - } - return 1; - } -/*-------------------------------------------------------------------------*/ - pDataNumber CreateDataNumber(char *pFileName) - { - pDataNumber pNew = NULL; - FILE *fd = NULL; - - pNew = (pDataNumber)malloc(sizeof(DataNumber)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(DataNumber)); - - pNew->pDes = CreateDescriptor("DataNumber"); - pNew->pCall = CreateCallBackInterface(); - if(!pNew->pDes || !pNew->pCall) - { - free(pNew); - return NULL; - } - - /* check filename */ - fd = fopen(pFileName,"r"); - if(!fd) - { - printf("Serious error: cannot open file for Data Number!!!!\n"); - printf("I continue, but you should not write data files!\n"); - pNew->pFileName = strdup("default.num"); - return pNew; - } - fclose(fd); - pNew->pFileName = strdup(pFileName); - return pNew; - } -/*--------------------------------------------------------------------------*/ - void DeleteDataNumber(void *pData) - { - pDataNumber self = NULL; - - self = (pDataNumber)pData; - assert(self); - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->pCall) - { - DeleteCallBackInterface(self->pCall); - self->pCall = NULL; - } - if(self->pFileName) - { - free(self->pFileName); - } - free(self); - } -/*-------------------------------------------------------------------------*/ - int IncrementDataNumber(pDataNumber self, int *iYear) - { - FILE *fd = NULL; - int iNum; - time_t iTime; - struct tm *psTime; - - - iNum = readDataNumber(self); - if(iNum < 0) - { - return iNum; - } - - iNum++; - - /* get year */ - iTime = time(NULL); - psTime = localtime(&iTime); - *iYear = psTime->tm_year + 1900; - - if(writeDataNumber(self,iNum) < 0) - { - return -1; - } - - InvokeCallBack(self->pCall, VALUECHANGE, self); - - return iNum; - } -/*-------------------------------------------------------------------------*/ - int DecrementDataNumber(pDataNumber self) - { - FILE *fd = NULL; - int iNum, currentThousand; - - iNum = readDataNumber(self); - if(iNum < 0) - { - return iNum; - } - - /* - decrement DataNumber with restrictions: - - not at all lower 0 - - do not understep a thousand boundary - */ - currentThousand = (int)floor(iNum/1000.); - iNum--; - if((int)floor(iNum/1000.) < currentThousand) - { - iNum++; - } - - if(writeDataNumber(self,iNum) < 0) - { - return -1; - } - - return iNum; - } -/*------------------------------------------------------------------------*/ -int NewThousand(pDataNumber self) +static int InterestCallback(int iEvent, void *pEvent, void *pUser) { - int iNum, currentThousand; - + pDataNumber self = NULL; + SConnection *pCon = NULL; + char pBueffel[132]; + int iNum; + + pCon = (SConnection *) pUser; + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + if (iEvent != VALUECHANGE) { + return 1; + } + + assert(pEvent); + assert(pUser); + + self = (pDataNumber) pEvent; + + /* + read number + */ iNum = readDataNumber(self); - if(iNum < 0) - { + if (iNum > 0) { + snprintf(pBueffel, 131, "sicsdatanumber = %d", iNum); + SCWrite(pCon, pBueffel, eValue); + } + return 1; +} + +/*-------------------------------------------------------------------------*/ +pDataNumber CreateDataNumber(char *pFileName) +{ + pDataNumber pNew = NULL; + FILE *fd = NULL; + + pNew = (pDataNumber) malloc(sizeof(DataNumber)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(DataNumber)); + + pNew->pDes = CreateDescriptor("DataNumber"); + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pDes || !pNew->pCall) { + free(pNew); + return NULL; + } + + /* check filename */ + fd = fopen(pFileName, "r"); + if (!fd) { + printf("Serious error: cannot open file for Data Number!!!!\n"); + printf("I continue, but you should not write data files!\n"); + pNew->pFileName = strdup("default.num"); + return pNew; + } + fclose(fd); + pNew->pFileName = strdup(pFileName); + return pNew; +} + +/*--------------------------------------------------------------------------*/ +void DeleteDataNumber(void *pData) +{ + pDataNumber self = NULL; + + self = (pDataNumber) pData; + assert(self); + + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + self->pCall = NULL; + } + if (self->pFileName) { + free(self->pFileName); + } + free(self); +} + +/*-------------------------------------------------------------------------*/ +int IncrementDataNumber(pDataNumber self, int *iYear) +{ + FILE *fd = NULL; + int iNum; + time_t iTime; + struct tm *psTime; + + + iNum = readDataNumber(self); + if (iNum < 0) { return iNum; } - - /* set to next thousand number */ - currentThousand = (int)floor(iNum/1000.); - iNum = (currentThousand + 1)*1000; - if(writeDataNumber(self,iNum) < 0) - { + iNum++; + + /* get year */ + iTime = time(NULL); + psTime = localtime(&iTime); + *iYear = psTime->tm_year + 1900; + + if (writeDataNumber(self, iNum) < 0) { + return -1; + } + + InvokeCallBack(self->pCall, VALUECHANGE, self); + + return iNum; +} + +/*-------------------------------------------------------------------------*/ +int DecrementDataNumber(pDataNumber self) +{ + FILE *fd = NULL; + int iNum, currentThousand; + + iNum = readDataNumber(self); + if (iNum < 0) { + return iNum; + } + + /* + decrement DataNumber with restrictions: + - not at all lower 0 + - do not understep a thousand boundary + */ + currentThousand = (int) floor(iNum / 1000.); + iNum--; + if ((int) floor(iNum / 1000.) < currentThousand) { + iNum++; + } + + if (writeDataNumber(self, iNum) < 0) { return -1; } return iNum; -} -/*-------------------------------------------------------------------------*/ - int DNWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pDataNumber self = NULL; - FILE *fd = NULL; - int iNum, iYear; - char pBueffel[512]; - long lID; - - self = (pDataNumber)pData; - assert(self); - assert(pCon); - - argtolower(argc,argv); - if(argc < 2) /* value request */ - { - iNum = readDataNumber(self); - if(iNum < 0) - { - sprintf(pBueffel,"ERROR: cannot open file %s",self->pFileName); - SCWrite(pCon,pBueffel,eError); - return 0; - } - sprintf(pBueffel,"%s = %d",argv[0],iNum); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - - if(strcmp(argv[1],"incr") == 0) - { - iNum = IncrementDataNumber(self,&iYear); - if(iNum > 0) - { - SCSendOK(pCon); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: cannot increment %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - if(strcmp(argv[1],"nextthousand") == 0) - { - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - iNum = NewThousand(self); - if(iNum > 0) - { - SCSendOK(pCon); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: cannot increment %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - if(strcmp(argv[1],"interest") == 0) - { - lID = RegisterCallback(self->pCall, - VALUECHANGE, InterestCallback, - SCCopyConnection(pCon), - SCDeleteConnection); - SCSendOK(pCon); - return 1; - } - if(strcmp(argv[1],"uninterest") == 0) - { - RemoveCallbackCon(self->pCall,pCon); - SCSendOK(pCon); - } - - sprintf(pBueffel,"ERROR: unknown command %s supplied to %s", - argv[1], argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +} + /*------------------------------------------------------------------------*/ - int DEWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pDataNumber self = NULL; - int iNum; - char pBueffel[512]; - - self = (pDataNumber)pData; - assert(self); - assert(pCon); +int NewThousand(pDataNumber self) +{ + int iNum, currentThousand; - if(SCMatchRights(pCon,usMugger)) - { - iNum = DecrementDataNumber(self); - snprintf(pBueffel,511,"Data file %d killed", iNum+1); - SCWrite(pCon,pBueffel,eWarning); - return 1; - } - else - { - SCWrite(pCon,"ERROR: you are not authorized to kill data files", - eError); - return 0; - } - } + iNum = readDataNumber(self); + if (iNum < 0) { + return iNum; + } + + /* set to next thousand number */ + currentThousand = (int) floor(iNum / 1000.); + iNum = (currentThousand + 1) * 1000; + + if (writeDataNumber(self, iNum) < 0) { + return -1; + } + + return iNum; +} /*-------------------------------------------------------------------------*/ - int DNFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pDataNumber self = NULL; - char pBueffel[512]; - int iRet; - - if(argc < 3) - { - SCWrite(pCon, - "ERROR: not enough arguments provided to make DataNumber",eError); - return 0; - } - - self = CreateDataNumber(argv[2]); - if(!self) - { - SCWrite(pCon,"ERROR: no memory to create data number",eError); - return 0; - } - - iRet = AddCommand(pSics, argv[1],DNWrapper, DeleteDataNumber, self); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = AddCommand(pSics,"killfile",DEWrapper,NULL, self); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } +int DNWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pDataNumber self = NULL; + FILE *fd = NULL; + int iNum, iYear; + char pBueffel[512]; + long lID; - + self = (pDataNumber) pData; + assert(self); + assert(pCon); + + argtolower(argc, argv); + if (argc < 2) { /* value request */ + iNum = readDataNumber(self); + if (iNum < 0) { + sprintf(pBueffel, "ERROR: cannot open file %s", self->pFileName); + SCWrite(pCon, pBueffel, eError); + return 0; + } + sprintf(pBueffel, "%s = %d", argv[0], iNum); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + + if (strcmp(argv[1], "incr") == 0) { + iNum = IncrementDataNumber(self, &iYear); + if (iNum > 0) { + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "ERROR: cannot increment %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + if (strcmp(argv[1], "nextthousand") == 0) { + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + iNum = NewThousand(self); + if (iNum > 0) { + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "ERROR: cannot increment %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + if (strcmp(argv[1], "interest") == 0) { + lID = RegisterCallback(self->pCall, + VALUECHANGE, InterestCallback, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + } + if (strcmp(argv[1], "uninterest") == 0) { + RemoveCallbackCon(self->pCall, pCon); + SCSendOK(pCon); + } + + sprintf(pBueffel, "ERROR: unknown command %s supplied to %s", + argv[1], argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; +} + +/*------------------------------------------------------------------------*/ +int DEWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pDataNumber self = NULL; + int iNum; + char pBueffel[512]; + + self = (pDataNumber) pData; + assert(self); + assert(pCon); + + if (SCMatchRights(pCon, usMugger)) { + iNum = DecrementDataNumber(self); + snprintf(pBueffel, 511, "Data file %d killed", iNum + 1); + SCWrite(pCon, pBueffel, eWarning); + return 1; + } else { + SCWrite(pCon, "ERROR: you are not authorized to kill data files", + eError); + return 0; + } +} + +/*-------------------------------------------------------------------------*/ +int DNFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pDataNumber self = NULL; + char pBueffel[512]; + int iRet; + + if (argc < 3) { + SCWrite(pCon, + "ERROR: not enough arguments provided to make DataNumber", + eError); + return 0; + } + + self = CreateDataNumber(argv[2]); + if (!self) { + SCWrite(pCon, "ERROR: no memory to create data number", eError); + return 0; + } + + iRet = AddCommand(pSics, argv[1], DNWrapper, DeleteDataNumber, self); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = AddCommand(pSics, "killfile", DEWrapper, NULL, self); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} diff --git a/danu.h b/danu.h index 1e8c27d9..cddf4201 100644 --- a/danu.h +++ b/danu.h @@ -17,23 +17,23 @@ #line 15 "danu.w" - typedef struct __DataNumber *pDataNumber; +typedef struct __DataNumber *pDataNumber; - pDataNumber CreateDataNumber(char *pFilename); - void DeleteDataNumber(void *pData); +pDataNumber CreateDataNumber(char *pFilename); +void DeleteDataNumber(void *pData); - int IncrementDataNumber(pDataNumber self, int *iYear); +int IncrementDataNumber(pDataNumber self, int *iYear); - int DecrementDataNumber(pDataNumber self); +int DecrementDataNumber(pDataNumber self); - int DNWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int DNWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - int DEWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int DEWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - int DNFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int DNFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #line 67 "danu.w" diff --git a/definealias.c b/definealias.c index 5845cb9c..a9a61e7b 100644 --- a/definealias.c +++ b/definealias.c @@ -44,174 +44,156 @@ #include "definealias.h" typedef struct __Aitem { - struct __Aitem *pNext; - char *pName; - char *pCmd; - } AliasItem; + struct __Aitem *pNext; + char *pName; + char *pCmd; +} AliasItem; /*------------------------------------------------------------------------*/ - char *TranslateAlias(AliasList *pAList, char *pCmd) - { - AliasItem *pAlias; +char *TranslateAlias(AliasList * pAList, char *pCmd) +{ + AliasItem *pAlias; - assert(pAList!=NULL && pCmd!=NULL); + assert(pAList != NULL && pCmd != NULL); - pAlias=pAList->pFirst; - while (pAlias!=NULL) - { - if (0 == strcmp(pAlias->pName, pCmd)) - { - pCmd = pAlias->pCmd; /* note that there may be cascaded translations */ - } - pAlias = pAlias->pNext; + pAlias = pAList->pFirst; + while (pAlias != NULL) { + if (0 == strcmp(pAlias->pName, pCmd)) { + pCmd = pAlias->pCmd; /* note that there may be cascaded translations */ } - return(pCmd); + pAlias = pAlias->pNext; } + return (pCmd); +} + /*------------------------------------------------------------------------*/ - int RemoveAlias(AliasList *pAList, char *pCmd) - { - AliasItem *pAlias = NULL, *pPrev = NULL; +int RemoveAlias(AliasList * pAList, char *pCmd) +{ + AliasItem *pAlias = NULL, *pPrev = NULL; - assert(pAList!=NULL && pCmd!=NULL); + assert(pAList != NULL && pCmd != NULL); - pPrev=(AliasItem *)pAList; - pAlias=pAList->pFirst; - while (pAlias != NULL && 0 != strcmp(pAlias->pName, pCmd)) - { - pPrev = pAlias; - pAlias = pAlias->pNext; - } - if (pAlias==NULL) - { - return 0; /* not found */ - } + pPrev = (AliasItem *) pAList; + pAlias = pAList->pFirst; + while (pAlias != NULL && 0 != strcmp(pAlias->pName, pCmd)) { + pPrev = pAlias; + pAlias = pAlias->pNext; + } + if (pAlias == NULL) { + return 0; /* not found */ + } - /* remove it */ - pPrev->pNext = pAlias->pNext; + /* remove it */ + pPrev->pNext = pAlias->pNext; + free(pAlias->pName); + free(pAlias->pCmd); + free(pAlias); + return (1); +} + +/*------------------------------------------------------------------------*/ +void FreeAliasList(AliasList * pAList) +{ + AliasItem *pAlias = NULL, *pNext = NULL; + + assert(pAList != NULL); + + pAlias = pAList->pFirst; + while (pAlias != NULL) { + pNext = pAlias->pNext; free(pAlias->pName); free(pAlias->pCmd); free(pAlias); - return(1); - } -/*------------------------------------------------------------------------*/ - void FreeAliasList(AliasList *pAList) - { - AliasItem *pAlias = NULL, *pNext = NULL; - - assert(pAList!=NULL); - - pAlias=pAList->pFirst; - while (pAlias != NULL) - { - pNext=pAlias->pNext; - free(pAlias->pName); - free(pAlias->pCmd); - free(pAlias); - pAlias = pNext; - } - } -/*------------------------------------------------------------------------*/ - char *CreateAlias(AliasList *pAList, char *pName, char *pTranslation) - { /* arguments must be lower case */ - AliasItem *pAlias = NULL, *pNew = NULL, *pTail = NULL; - char *pCmd; - - /* translate 2nd argument */ - pCmd=TranslateAlias(pAList, pTranslation); - if (0==strcmp(pName, pCmd)) /* translation matches */ - { - return "recursive alias not allowed"; - } - - /* find last element pTail and check that alias does not yet exist */ - pTail = (AliasItem *)pAList; - pAlias = pAList->pFirst; - while (pAlias!=NULL) - { - pTail=pAlias; - if (0 == strcmp(pAlias->pName, pName)) - { - return "alias already exists"; - } - pAlias = pAlias->pNext; - } - - /* allocate the list entry */ - pNew = malloc(sizeof(AliasItem)); - if (pNew!=NULL) - { - pNew->pNext = NULL; - pNew->pName = strdup(pName); - if (pNew->pName!=NULL) - { - pNew->pCmd = strdup(pCmd); - if (pNew->pCmd!=NULL) - { - /* insert at tail */ - pTail->pNext = pNew; - return NULL; /* o.k. */ - } - } - } - return "not enough memory to create an alias"; - + pAlias = pNext; } +} /*------------------------------------------------------------------------*/ - int DefineAlias(pSConnection pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[256]; - int iRet; - CommandList *pCom = NULL; - char *pErr; +char *CreateAlias(AliasList * pAList, char *pName, char *pTranslation) +{ /* arguments must be lower case */ + AliasItem *pAlias = NULL, *pNew = NULL, *pTail = NULL; + char *pCmd; - if(!SCMatchRights(pCon,usMugger)) - { - SCWrite(pCon,"ERROR: only managers may define aliases", - eError); - return 0; + /* translate 2nd argument */ + pCmd = TranslateAlias(pAList, pTranslation); + if (0 == strcmp(pName, pCmd)) { /* translation matches */ + return "recursive alias not allowed"; + } + + /* find last element pTail and check that alias does not yet exist */ + pTail = (AliasItem *) pAList; + pAlias = pAList->pFirst; + while (pAlias != NULL) { + pTail = pAlias; + if (0 == strcmp(pAlias->pName, pName)) { + return "alias already exists"; } + pAlias = pAlias->pNext; + } - argtolower(argc,argv); - - if(argc == 2) /* remove case */ - { - iRet=RemoveAlias(&pSics->AList, argv[1]); - if (iRet==0) - { - SCWrite(pCon,"ERROR: alias not found", - eError); - return 0; + /* allocate the list entry */ + pNew = malloc(sizeof(AliasItem)); + if (pNew != NULL) { + pNew->pNext = NULL; + pNew->pName = strdup(pName); + if (pNew->pName != NULL) { + pNew->pCmd = strdup(pCmd); + if (pNew->pCmd != NULL) { + /* insert at tail */ + pTail->pNext = pNew; + return NULL; /* o.k. */ } - return 1; } - if(argc != 3) - { - SCWrite(pCon,"ERROR: illegal number of arguments to DefineAlias", - eError); + } + return "not enough memory to create an alias"; + +} + +/*------------------------------------------------------------------------*/ +int DefineAlias(pSConnection pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[256]; + int iRet; + CommandList *pCom = NULL; + char *pErr; + + if (!SCMatchRights(pCon, usMugger)) { + SCWrite(pCon, "ERROR: only managers may define aliases", eError); + return 0; + } + + argtolower(argc, argv); + + if (argc == 2) { /* remove case */ + iRet = RemoveAlias(&pSics->AList, argv[1]); + if (iRet == 0) { + SCWrite(pCon, "ERROR: alias not found", eError); return 0; } - - pCom = FindCommand(pSics, argv[1]); - if (pCom!=NULL) - { - SCWrite(pCon,"ERROR: an alias must not overwrite a command", - eError); - return 0; - } - - /* remove the old alias, if any */ - RemoveAlias(&pSics->AList, argv[1]); - - pErr=CreateAlias(&pSics->AList, argv[1], argv[2]); - if (pErr!=NULL) - { - sprintf(pBueffel,"ERROR: %s", pErr); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; } + if (argc != 3) { + SCWrite(pCon, "ERROR: illegal number of arguments to DefineAlias", + eError); + return 0; + } + pCom = FindCommand(pSics, argv[1]); + if (pCom != NULL) { + SCWrite(pCon, "ERROR: an alias must not overwrite a command", eError); + return 0; + } + + /* remove the old alias, if any */ + RemoveAlias(&pSics->AList, argv[1]); + + pErr = CreateAlias(&pSics->AList, argv[1], argv[2]); + if (pErr != NULL) { + sprintf(pBueffel, "ERROR: %s", pErr); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + return 1; +} diff --git a/definealias.h b/definealias.h index 9fbb5a55..a9d17adc 100644 --- a/definealias.h +++ b/definealias.h @@ -17,77 +17,77 @@ ---------------------------------------------------------------------------*/ #ifndef DEFINE_ALIAS #define DEFINE_ALIAS -#include "conman.h" +#include "conman.h" #include "definealias.i" /*---------------------------------------------------------------------------*/ - char *TranslateAlias(AliasList *pAList, char *pCmd); +char *TranslateAlias(AliasList * pAList, char *pCmd); /* - translate the command *pCmd - - the translation may go through several steps - - if no translation is found, the return value is equal to pCmd - - no strings are copied - - the return value becomes invalid when the corresponding alias is removed - - *pCmd must be lowercase - */ + translate the command *pCmd + - the translation may go through several steps + - if no translation is found, the return value is equal to pCmd + - no strings are copied + - the return value becomes invalid when the corresponding alias is removed + - *pCmd must be lowercase + */ /*---------------------------------------------------------------------------*/ - int RemoveAlias(AliasList *pAList, char *pCmd); +int RemoveAlias(AliasList * pAList, char *pCmd); /* - remove the alias *pCmd - - returns 1 when the alias existed, 0 otherwise - - *pCmd must be lowercase - */ + remove the alias *pCmd + - returns 1 when the alias existed, 0 otherwise + - *pCmd must be lowercase + */ /*---------------------------------------------------------------------------*/ - void FreeAliasList(AliasList *pAList); +void FreeAliasList(AliasList * pAList); /* - dispose the alias list - */ + dispose the alias list + */ /*---------------------------------------------------------------------------*/ - char *CreateAlias(AliasList *pAList, char *pName, char *pTranslation); +char *CreateAlias(AliasList * pAList, char *pName, char *pTranslation); /* - create a new alias *pName with the translation *pTranslation + create a new alias *pName with the translation *pTranslation - - the alias *pName must not yet exist - - *pTranslation is translated first - - recursive definitions are prohibited - - *pName and *pTranslation must be lowercase + - the alias *pName must not yet exist + - *pTranslation is translated first + - recursive definitions are prohibited + - *pName and *pTranslation must be lowercase - if the creation is successful, the return value is NULL, otherwise - it points to one of the following error messages: + if the creation is successful, the return value is NULL, otherwise + it points to one of the following error messages: - "recursive alias not allowed" - "alias already exists" - "not enough memory to create an alias" + "recursive alias not allowed" + "alias already exists" + "not enough memory to create an alias" - */ + */ /*---------------------------------------------------------------------------*/ - int DefineAlias(SConnection *pCon, SicsInterp *pSics, void *pData, +int DefineAlias(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]); /* this command requires manager privileges - argv[1]: the alias to define - - must not be a proper SICS command - - if an alias with this name exists already, it is removed first + argv[1]: the alias to define + - must not be a proper SICS command + - if an alias with this name exists already, it is removed first - argv[2]: the original command - - if omitted, the alias is removed - - if it is an alias the definiton refers to it's translation - - may be an unknown command (probably defined later) + argv[2]: the original command + - if omitted, the alias is removed + - if it is an alias the definiton refers to it's translation + - may be an unknown command (probably defined later) - - AddCommand removes an eventual alias matching the command name + - AddCommand removes an eventual alias matching the command name - - RemoveCommand does not remove it's aliases - Trying to use an alias of a removed command leads to the error message - "object > ... < NOT found" + - RemoveCommand does not remove it's aliases + Trying to use an alias of a removed command leads to the error message + "object > ... < NOT found" - - trying to define a recursive alias leads the error message - "recursive alias not allowed" - */ + - trying to define a recursive alias leads the error message + "recursive alias not allowed" + */ #endif diff --git a/defines.h b/defines.h index 064a4023..bce64662 100644 --- a/defines.h +++ b/defines.h @@ -8,8 +8,8 @@ /_|__| A.Reitsma, Delft, Nederland. / | \ --------------------------------------------------------------- */ -#include /* for malloc() prototype */ -#include /* for memcpy() prototype */ +#include /* for malloc() prototype */ +#include /* for memcpy() prototype */ #include "fortify.h" #define MALLOC(size,type) (type *) malloc( (size) * sizeof( type )) diff --git a/devexec.c b/devexec.c index d351b22f..6e54f432 100644 --- a/devexec.c +++ b/devexec.c @@ -70,1230 +70,1160 @@ /*======================== Logging stuff ==================================*/ static FILE *devLog = NULL; /*-------------------------------------------------------------------------*/ -int openDevexecLog(){ - char *fileName = NULL; - char fileBuffer[1024]; - time_t iDate; - struct tm *psTime; +int openDevexecLog() +{ + char *fileName = NULL; + char fileBuffer[1024]; + time_t iDate; + struct tm *psTime; - - if(devLog == NULL){ - fileName = IFindOption(pSICSOptions,"devexeclog"); - if(fileName != NULL){ - strcpy(fileBuffer,fileName); - } else { - iDate = time(NULL); - psTime = localtime(&iDate); - fileBuffer[0] = '\0'; - fileName = getenv("HOME"); - if(fileName != NULL){ - snprintf(fileBuffer,1023,"%s/log/devexec%4.4d.log", - fileName, psTime->tm_year + 1900); - } - } - devLog = fopen(fileBuffer,"a+"); - } - if(devLog == NULL){ - return 0; + + if (devLog == NULL) { + fileName = IFindOption(pSICSOptions, "devexeclog"); + if (fileName != NULL) { + strcpy(fileBuffer, fileName); } else { - return 1; - } -} -/*-------------------------------------------------------------------------*/ -void DevexecLog(char *operation, char *device) { - struct timeval tv; - struct timezone tm; - if(devLog != NULL){ - gettimeofday(&tv,&tm); - fprintf(devLog, "DEVEXEC:%s:%s:%ld:%ld\n",operation,device, - (long)tv.tv_sec, (long)tv.tv_usec); - fflush(devLog); - } -} -/*======================== internal data structures =======================*/ - typedef struct _DevEntry { - void *pData; - pObjectDescriptor pDescriptor; - float fVal; - char *name; - SConnection *pCon; - } DevEntry, *pDevEntry; -/*------------------------------------------------------------------------*/ -typedef struct { - pExeList self; - pDevEntry pDev; - pICountable pCountInt; - pIDrivable pDrivInt; -}checkContext, *pCheckContext; -/*-------------------------------------------------------------------------*/ - static pDevEntry CreateDevEntry(pObjectDescriptor pDes, SConnection *pCon, - void *pData, - float fVal, char *name) - { - pDevEntry pNew = NULL; - - assert(pDes); - - pNew = (pDevEntry)malloc(sizeof(DevEntry)); - if(!pNew) - { - return NULL; - } - pNew->pDescriptor = pDes; - pNew->pData = pData; - pNew->name = strdup(name); - pNew->fVal = fVal; - pNew->pCon = SCCopyConnection(pCon); - return pNew; - } -/*-------------------------------------------------------------------------*/ - static void DeleteDevEntry(pDevEntry self) - { - assert(self); - - if(self->name) - { - free(self->name); - } - if(self->pCon){ - SCDeleteConnection(self->pCon); - } - free(self); - } -/* ----------------- The Executor himself ---------------------------------*/ - typedef struct __EXELIST{ - pObjectDescriptor pDes; - SConnection *pOwner; - int iList; - int iRun; - int iStop; - int iStatus; - int iEnd; - int drivePrint; - long lTask; - pTaskMan pTask; - int iLock; - pICallBack pCall; - time_t lastRun; - int paused; - int taskRunning; - } ExeList; - - static pExeList pExecutor = NULL; -/*--------------------------------------------------------------------------*/ - static void *DevexecInterface(void *pData, int iInter) - { - pExeList self = NULL; - - self = (pExeList)pData; - assert(self); - - if(iInter == CALLBACKINTERFACE) - { - return self->pCall; - } - return NULL; - } -/*--------------------------------------------------------------------------*/ - pExeList CreateExeList(pTaskMan pTask) - { - pExeList pRes = NULL; - - assert(pTask); - - pRes = (pExeList)malloc(sizeof(ExeList)); - if(!pRes) - { - return NULL; - } - - pRes->pOwner = NULL; - pRes->pDes = CreateDescriptor("DeviceExecutor"); - if(!pRes->pDes) - { - free(pRes); - return NULL; - } - pRes->iList = LLDcreate(sizeof(pDevEntry)); - if(pRes->iList == -1) - { - free(pRes); - return NULL; - } - pRes->iRun = 0; - pRes->iStatus = DEVDONE; - pRes->pTask = pTask; - pRes->lTask = -1; - pRes->iLock = 0; - pRes->drivePrint = 0; - pRes->paused = 0; - pRes->taskRunning = 0; - pRes->pCall = CreateCallBackInterface(); - pRes->lastRun = time(NULL); - pRes->pDes->GetInterface = DevexecInterface; - return pRes; - } -/*-------------------------------------------------------------------------*/ - void DeleteExeList(void *pData) - { - pExeList self; - - assert(pData); - - self = (pExeList)pData; - if(self->pDes) - DeleteDescriptor(self->pDes); - ClearExecutor(self); - LLDdelete(self->iList); - if(self->pCall) - DeleteCallBackInterface(self->pCall); - - if(self->pOwner){ - SCDeleteConnection(self->pOwner); - self->pOwner = NULL; - } - - free(self); - pServ->pExecutor = NULL; - if(devLog != NULL){ - fclose(devLog); - devLog = NULL; - } - } -/*--------------------------------------------------------------------------*/ - void ExeInterest(pExeList self, pDevEntry pDev, char *text) { - char buf[128]; - - if(pDev) - { - snprintf(buf, sizeof(buf),"%s %s",pDev->name,text); - InvokeCallBack(self->pCall, DRIVSTAT, buf); - } - } -/*------------------------------------------------------------------------*/ - int StartDevice(pExeList self, char *name, pObjectDescriptor pDes, - void *pData, SConnection *pCon, float fNew) - { - pDevEntry pNew = NULL; - int iRet; - char pBueffel[132], pError[80]; - pIDrivable pDrivInt = NULL; - pICountable pCountInt = NULL; - static int overwriteOwner = -1; - char *overwriteOption; - float oldVal; - - assert(self); - assert(pDes); - assert(pCon); - - /* may we? */ - if(self->pOwner != NULL) - { - if(pCon->ident != self->pOwner->ident) - { - /* this hack helps on rita2, when using the sendsics script - which opens a client for every command */ - if (overwriteOwner < 0) { - overwriteOption = IFindOption(pSICSOptions, "overwriteOwner"); - overwriteOwner = overwriteOption && *overwriteOption != '0'; - } - if (overwriteOwner) { - SCDeleteConnection(self->pOwner); - self->pOwner = SCCopyConnection(pCon); - } else { - SCWrite(pCon, - "ERROR: somebody else is still driving, Request rejected",eError); - return 0; - } - } - } - else - { - self->pOwner = SCCopyConnection(pCon); - } - if(self->iLock == 1) - { - SCWrite(pCon,"ERROR: instrument is locked",eError); - return 0; - } - - /* well create a new entry */ - self->iStop = 0; - pNew = CreateDevEntry(pDes,pCon,pData,fNew,name); - if(!pNew) - { - SCWrite(pCon,"ERROR: memory exhausted in Device Executor ",eError); - return 0; - } - - /* start it */ - pDrivInt = pDes->GetInterface(pData,DRIVEID); - pCountInt = pDes->GetInterface(pData,COUNTID); - if(pDrivInt) - { - iRet = pDrivInt->SetValue(pData,pCon,fNew); - if(iRet == OKOK && self->drivePrint == 1) - { - oldVal = pDrivInt->GetValue(pData,pCon); - snprintf(pBueffel,131,"Driving %s from %8.3f to %8.3f", - name, oldVal, fNew); - SCWrite(pCon,pBueffel,eValue); - } - } - else if(pCountInt) - { - iRet = pCountInt->StartCount(pData,pCon); - } - else - { /* this is a programmers error */ - SCWrite(pCon,"ERROR: Programmer error in StartDevice ",eError); - iRet = 0; - } - - /* check return status */ - if(iRet == OKOK) - { - LLDnodeAppendFrom(self->iList,&pNew); - sprintf(pBueffel,"started"); - if(NULL!=pNew->pCon->deviceID) - { - snprintf(pBueffel,130,"started (%s)",pNew->pCon->deviceID); - } - ExeInterest(self, pNew, pBueffel); - self->iRun = 1; - self->iStatus = DEVDONE; - /* if no task: start it */ - if(self->lTask < 0) - { - self->lTask = TaskRegister(self->pTask, - DevExecTask, - DevExecSignal, - NULL, - self, - 1); - self->iEnd = 0; - pCon->conStatus = HWBusy; - } - DevexecLog("START",pNew->name); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: cannot start device %s",name); - SCWrite(pCon,pBueffel,eError); - DeleteDevEntry(pNew); - if(LLDcheck(self->iList) >= LIST_EMPTY) - { - if(self->pOwner != NULL){ - SCDeleteConnection(self->pOwner); - } - self->pOwner = NULL; - } - return 0; - } - return 0; - } -/*--------------------------------------------------------------------------*/ - int StartMotor(pExeList self, SicsInterp *pSics, SConnection *pCon, - char *name, float fVal) - { - pDummy pMot = NULL; - CommandList *pCom = NULL; - char pBueffel[256]; - - assert(self); - assert(pSics); - assert(name); - - pCom = FindCommand(pSics,name); - if(!pCom) - { - sprintf(pBueffel,"ERROR: cannot find motor %s",name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pMot = (pDummy)pCom->pData; - if(!pMot) - { - sprintf(pBueffel,"ERROR: %s is no motor ",name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - - if(!pMot->pDescriptor) - { - sprintf(pBueffel,"ERROR: cannot find motor %s",name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!pMot->pDescriptor->GetInterface(pMot,DRIVEID)) - { - sprintf(pBueffel,"ERROR: %s is no motor",name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return StartDevice(self,name,pMot->pDescriptor,(void *)pMot,pCon,fVal); - } -/*---------------------------------------------------------------------------*/ - int StartCounter(pExeList self, SicsInterp *pSics,SConnection *pCon, - char *name) - { - pCounter pCter = NULL; - CommandList *pCom = NULL; - char pBueffel[256]; - - assert(self); - assert(pSics); - assert(name); - - pCom = FindCommand(pSics,name); - if(!pCom) - { - sprintf(pBueffel,"ERROR: cannot find counter %s",name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pCter = (pCounter)pCom->pData; - if(!pCter) - { - sprintf(pBueffel,"ERROR: %s is no counter ",name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - - if(!pCter->pDes) - { - sprintf(pBueffel,"ERROR: cannot find counter %s",name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!pCter->pDes->GetInterface(pCter,COUNTID)) - { - sprintf(pBueffel,"ERROR: %s is no counter",name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return StartDevice(self,name,pCter->pDes,(void *)pCter, - pCon,pCter->pDriv->fPreset); - } -/*-------------------------------------------------------------------------*/ -static int checkInterrupt(pCheckContext pCheck, int targetStatus){ - if(SCGetInterrupt(pCheck->self->pOwner) != eContinue) { - pCheck->self->iStatus = DEVINT; - SetStatus(eEager); - return -1; - } else { - return targetStatus; - } -} -/*--------------------------------------------------------------------------*/ -static int initializeCheck(pCheckContext pCheck, pDevEntry pDev){ - int eCode = HWFault; - - pCheck->pDev = pDev; - pCheck->pDrivInt = pDev->pDescriptor->GetInterface(pDev->pData,DRIVEID); - pCheck->pCountInt = pDev->pDescriptor->GetInterface(pDev->pData,COUNTID); - if(pCheck->pDrivInt != NULL){ - eCode = pCheck->pDrivInt->CheckStatus(pDev->pData,pDev->pCon); - } else if(pCheck->pCountInt != NULL) { - eCode = pCheck->pCountInt->CheckCountStatus(pDev->pData,pDev->pCon); - } - return eCode; -} -/*--------------------------------------------------------------------------*/ -static int finishDevice(pCheckContext pCheck){ - int status; - - if(pCheck->pCountInt != NULL) { - pCheck->pCountInt->TransferData(pCheck->pDev->pData,pCheck->pDev->pCon); - } else if(pCheck->pDrivInt != NULL) { - pCheck->pDrivInt->iErrorCount = 0; - } - ExeInterest(pCheck->self, pCheck->pDev, "finished"); - DevexecLog("STOP",pCheck->pDev->name); - DeleteDevEntry(pCheck->pDev); - LLDnodeDelete(pCheck->self->iList); - status = LLDnodePtr2Prev(pCheck->self->iList); - SCWrite(pCheck->self->pOwner, "", eFinish); - pCheck->self->iStatus = DEVDONE; - return checkInterrupt(pCheck,status); -} -/*-------------------------------------------------------------------------*/ -static int errorDevice(pCheckContext pCheck){ - int status; - - ExeInterest(pCheck->self, pCheck->pDev, "finished with problem"); - DevexecLog("STOP",pCheck->pDev->name); - LLDnodeDelete(pCheck->self->iList); - status = LLDnodePtr2Prev(pCheck->self->iList); - SCWrite(pCheck->self->pOwner, "", eFinish); - pCheck->self->iStatus = DEVERROR; - if(pCheck->pDrivInt != NULL) { - pCheck->pDrivInt->iErrorCount++; - } - status = checkInterrupt(pCheck,status); - DeleteDevEntry(pCheck->pDev); - return status; -} -/*-------------------------------------------------------------------------*/ -static int testFinish(pExeList self){ - if((self->pOwner == NULL) || (LLDcheck(self->iList) == LIST_EMPTY)) { - if(self->pOwner != NULL){ - SCDeleteConnection(self->pOwner); - } - self->pOwner = NULL; - self->iRun = 0; - self->iEnd = 1; - self->iStop = 0; - self->lTask = -1; - return 1; - } else { - return 0; - } -} -/*--------------------------------------------------------------------------*/ - int CheckExeList(pExeList self) - { - int iRet, status; - checkContext check; - pDevEntry pDev = NULL; - pICountable pCountInt = NULL; - pIDrivable pDrivInt = NULL; - int eCode; - int isCounting=0, isDriving=0; - char pBueffel[512]; - - assert(self); - - /* Sometimes this gets called, though nothing is running. There are - cases where this is feasible for maintainance, but in some cases it - is pure rubbish, because nothing runs. This will be checked here. - */ - if(testFinish(self) == 1){ - return 1; - } - - /* - check the status of all registered devices. Remove when finished - */ - check.self = self; - status = LLDnodePtr2First(self->iList); - while(status != 0) - { - LLDnodeDataTo(self->iList,&pDev); - if(pDev) - { - eCode = initializeCheck(&check,pDev); - if(eCode != HWNoBeam && eCode != HWPause && self->paused == 1){ - DevexecLog("CONTINUE","ALL"); - self->paused = 0; - } - switch(eCode) - { - case HWIdle: - case OKOK: - status = finishDevice(&check); - if(status < 0){ - return status; - } - break; - case HWFault: /* real HW error: burning, no net etc.. */ - status = errorDevice(&check); - if(status < 0){ - return status; - } - break; - case HWNoBeam: - SetStatus(eOutOfBeam); - if(self->paused == 0){ - self->paused = 1; - DevexecLog("NOBEAM","ALL"); - } - status = checkInterrupt(&check,1); - if(status < 0){ - return status; - } - break; - case HWPause: - SetStatus(ePaused); - if(self->paused == 0){ - self->paused = 1; - DevexecLog("PAUSE","ALL"); - } - status = checkInterrupt(&check,1); - if(status < 0){ - /* - * continue in order to wait for devices to come to a stop - */ - ContinueExecution(self); - return status; - } - break; - case HWBusy: - if(check.pDrivInt != NULL) - { - isDriving = 1; - } - else if(check.pCountInt != NULL) - { - isCounting = 1; - } - self->iStatus = DEVBUSY; - break; - case HWPosFault: /* cannot get somewhere... */ - status = errorDevice(&check); - if(status < 0){ - return status; - } - break; - } - } - status = LLDnodePtr2Next(self->iList); - } - - if (isCounting) { - if (isDriving) { - SetStatus(eCountDrive); - } else { - SetStatus(eCounting); + iDate = time(NULL); + psTime = localtime(&iDate); + fileBuffer[0] = '\0'; + fileName = getenv("HOME"); + if (fileName != NULL) { + snprintf(fileBuffer, 1023, "%s/log/devexec%4.4d.log", + fileName, psTime->tm_year + 1900); } - } else if (isDriving) { - SetStatus(eDriving); } - - iRet = LLDnodePtr2First(self->iList); - return testFinish(self); + devLog = fopen(fileBuffer, "a+"); } -/*---------------------------------------------------------------------------*/ - int Wait4Success(pExeList self) - { - int iRet; - assert(self); - - /* do nothing if not running */ - if(self->lTask < 0) - { - printf("Nothing to wait for.... \n"); - self->iRun = 0; /* not sure if this is needed here, but does not harm */ - return self->iStatus; - } - - /* wait for Devexec task to finish */ - TaskWait(self->pTask,self->lTask); -#ifdef DEBUG - printf("Wait4Success finished\n"); -#endif - self->iRun = 0; - return self->iStatus; - } -/*--------------------------------------------------------------------------*/ - int ListPending(pExeList self, SConnection *pCon) - { - int iRet,i; - char pBueffel[512]; - pDevEntry pDev = NULL; - - assert(self); - assert(pCon); - - /* first make sure that the list is fully updated */ - iRet = CheckExeList(self); - if(iRet == 1) /* nothing to do! */ - { - SCWrite(pCon,"Machine idle",eValue); - return 1; - } - else if(iRet == -1) - { - SCWrite(pCon,"Handling Interrupt",eError); - return 0; - } - - - /* search the list for entries */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&pDev); - if(pDev) - { - sprintf(pBueffel,"\t%s %f",pDev->name,pDev->fVal); - SCWrite(pCon,pBueffel,eValue); - } - iRet = LLDnodePtr2Next(self->iList); - } + if (devLog == NULL) { + return 0; + } else { return 1; } -/* -----------------------------------------------------------------------*/ - long GetDevexecID(pExeList self) - { - assert(self); - - return self->lTask; - } -/*--------------------------------------------------------------------------*/ - int StopExe(pExeList self, char *name) - { - int i, iRet; - pDevEntry pDev = NULL; - pIDrivable pDrivInt = NULL; - pICountable pCountInt = NULL; - assert(self); - - /* if not active, nothing to do */ - if((self->pOwner == NULL) || (LLDcheck(self->iList) == LIST_EMPTY)) - { - self->iRun = 0; - return 1; - } +} - /* first the ALL case */ - if(strcmp(name,"all") == 0) - { - /* - check for stop flag. This is to stop unnecessary calls to StopExe. - There may be way to many, but each call is reasonable under certain - circumstances. - */ - if(self->iStop == 1) - { - return 0; - } - else - { - self->iStop = 1; - } - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - pDev = (pDevEntry)LLDnodePtr(self->iList); - if(pDev) - { - pDrivInt = pDev->pDescriptor->GetInterface(pDev->pData,DRIVEID); - pCountInt = pDev->pDescriptor->GetInterface(pDev->pData,COUNTID); - if(pDrivInt) - { - pDrivInt->Halt(pDev->pData); - } - else if(pCountInt) - { - pCountInt->Halt(pDev->pData); - } - } - iRet = LLDnodePtr2Next(self->iList); - } - SCWrite(self->pOwner,"ERROR: Full Stop called!!",eError); - if(SCGetInterrupt(self->pOwner) > eContinue) - { - self->iStatus = DEVINT; - } - return 1; - } - - /* now the special case: a well defined command */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - pDev = (pDevEntry)LLDnodePtr(self->iList); - if(pDev) - { - if(strcmp(pDev->name,name) == 0) - { - pDrivInt = pDev->pDescriptor->GetInterface(pDev->pData,DRIVEID); - pCountInt = pDev->pDescriptor->GetInterface(pDev->pData,COUNTID); - if(pDrivInt) - { - pDrivInt->Halt(pDev->pData); - } - else if(pCountInt) - { - pCountInt->Halt(pDev->pData); - } - return 1; - } - } - iRet = LLDnodePtr2Next(self->iList); - } - - return 0; - } /*-------------------------------------------------------------------------*/ - int StopExeWait(pExeList self) - { - StopExe(self,"all"); - Wait4Success(self); - return 1; +void DevexecLog(char *operation, char *device) +{ + struct timeval tv; + struct timezone tm; + if (devLog != NULL) { + gettimeofday(&tv, &tm); + fprintf(devLog, "DEVEXEC:%s:%s:%ld:%ld\n", operation, device, + (long) tv.tv_sec, (long) tv.tv_usec); + fflush(devLog); } -/*--------------------------------------------------------------------------*/ - int PauseExecution(pExeList self) - { - int i, iRet, iRes; - pDevEntry pDev = NULL; - pICountable pCountInt = NULL; - assert(self); - - /* step through the list */ - iRes = 1; - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - pDev = (pDevEntry)LLDnodePtr(self->iList); - if(pDev) - { - pCountInt = pDev->pDescriptor->GetInterface(pDev->pData,COUNTID); - if(pCountInt) - { - iRet = pCountInt->Pause(pDev->pData,pDev->pCon); - if(!iRet) - { - iRes = 0; - } - } - - } - iRet = LLDnodePtr2Next(self->iList); - } - SetStatus(ePaused); - return iRes; - } +} + +/*======================== internal data structures =======================*/ +typedef struct _DevEntry { + void *pData; + pObjectDescriptor pDescriptor; + float fVal; + char *name; + SConnection *pCon; +} DevEntry, *pDevEntry; /*------------------------------------------------------------------------*/ - int IsCounting(pExeList self) - { - int iRet; - pDevEntry pDev = NULL; - pICountable pCountInt = NULL; - assert(self); - - /* step through the list */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - pDev = (pDevEntry)LLDnodePtr(self->iList); - if(pDev) - { - pCountInt = pDev->pDescriptor->GetInterface(pDev->pData,COUNTID); - if(pCountInt) - { - return 1; - } - } - iRet = LLDnodePtr2Next(self->iList); - } +typedef struct { + pExeList self; + pDevEntry pDev; + pICountable pCountInt; + pIDrivable pDrivInt; +} checkContext, *pCheckContext; +/*-------------------------------------------------------------------------*/ +static pDevEntry CreateDevEntry(pObjectDescriptor pDes, SConnection * pCon, + void *pData, float fVal, char *name) +{ + pDevEntry pNew = NULL; + + assert(pDes); + + pNew = (pDevEntry) malloc(sizeof(DevEntry)); + if (!pNew) { + return NULL; + } + pNew->pDescriptor = pDes; + pNew->pData = pData; + pNew->name = strdup(name); + pNew->fVal = fVal; + pNew->pCon = SCCopyConnection(pCon); + return pNew; +} + +/*-------------------------------------------------------------------------*/ +static void DeleteDevEntry(pDevEntry self) +{ + assert(self); + + if (self->name) { + free(self->name); + } + if (self->pCon) { + SCDeleteConnection(self->pCon); + } + free(self); +} + +/* ----------------- The Executor himself ---------------------------------*/ +typedef struct __EXELIST { + pObjectDescriptor pDes; + SConnection *pOwner; + int iList; + int iRun; + int iStop; + int iStatus; + int iEnd; + int drivePrint; + long lTask; + pTaskMan pTask; + int iLock; + pICallBack pCall; + time_t lastRun; + int paused; + int taskRunning; +} ExeList; + +static pExeList pExecutor = NULL; +/*--------------------------------------------------------------------------*/ +static void *DevexecInterface(void *pData, int iInter) +{ + pExeList self = NULL; + + self = (pExeList) pData; + assert(self); + + if (iInter == CALLBACKINTERFACE) { + return self->pCall; + } + return NULL; +} + +/*--------------------------------------------------------------------------*/ +pExeList CreateExeList(pTaskMan pTask) +{ + pExeList pRes = NULL; + + assert(pTask); + + pRes = (pExeList) malloc(sizeof(ExeList)); + if (!pRes) { + return NULL; + } + + pRes->pOwner = NULL; + pRes->pDes = CreateDescriptor("DeviceExecutor"); + if (!pRes->pDes) { + free(pRes); + return NULL; + } + pRes->iList = LLDcreate(sizeof(pDevEntry)); + if (pRes->iList == -1) { + free(pRes); + return NULL; + } + pRes->iRun = 0; + pRes->iStatus = DEVDONE; + pRes->pTask = pTask; + pRes->lTask = -1; + pRes->iLock = 0; + pRes->drivePrint = 0; + pRes->paused = 0; + pRes->taskRunning = 0; + pRes->pCall = CreateCallBackInterface(); + pRes->lastRun = time(NULL); + pRes->pDes->GetInterface = DevexecInterface; + return pRes; +} + +/*-------------------------------------------------------------------------*/ +void DeleteExeList(void *pData) +{ + pExeList self; + + assert(pData); + + self = (pExeList) pData; + if (self->pDes) + DeleteDescriptor(self->pDes); + ClearExecutor(self); + LLDdelete(self->iList); + if (self->pCall) + DeleteCallBackInterface(self->pCall); + + if (self->pOwner) { + SCDeleteConnection(self->pOwner); + self->pOwner = NULL; + } + + free(self); + pServ->pExecutor = NULL; + if (devLog != NULL) { + fclose(devLog); + devLog = NULL; + } +} + +/*--------------------------------------------------------------------------*/ +void ExeInterest(pExeList self, pDevEntry pDev, char *text) +{ + char buf[128]; + + if (pDev) { + snprintf(buf, sizeof(buf), "%s %s", pDev->name, text); + InvokeCallBack(self->pCall, DRIVSTAT, buf); + } +} + +/*------------------------------------------------------------------------*/ +int StartDevice(pExeList self, char *name, pObjectDescriptor pDes, + void *pData, SConnection * pCon, float fNew) +{ + pDevEntry pNew = NULL; + int iRet; + char pBueffel[132], pError[80]; + pIDrivable pDrivInt = NULL; + pICountable pCountInt = NULL; + static int overwriteOwner = -1; + char *overwriteOption; + float oldVal; + + assert(self); + assert(pDes); + assert(pCon); + + /* may we? */ + if (self->pOwner != NULL) { + if (pCon->ident != self->pOwner->ident) { + /* this hack helps on rita2, when using the sendsics script + which opens a client for every command */ + if (overwriteOwner < 0) { + overwriteOption = IFindOption(pSICSOptions, "overwriteOwner"); + overwriteOwner = overwriteOption && *overwriteOption != '0'; + } + if (overwriteOwner) { + SCDeleteConnection(self->pOwner); + self->pOwner = SCCopyConnection(pCon); + } else { + SCWrite(pCon, + "ERROR: somebody else is still driving, Request rejected", + eError); return 0; - } -/*--------------------------------------------------------------------------*/ - int ContinueExecution(pExeList self) - { - int i, iRet, iRes; - pDevEntry pDev = NULL; - pICountable pCountInt = NULL; - assert(self); - - /* step through the list */ - iRes = 1; - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - pDev = (pDevEntry)LLDnodePtr(self->iList); - if(pDev) - { - pCountInt = pDev->pDescriptor->GetInterface(pDev->pData,COUNTID); - if(pCountInt) - { - iRet = pCountInt->Continue(pDev->pData,pDev->pCon); - if(!iRet) - { - iRes = 0; - } - } - - } - iRet = LLDnodePtr2Next(self->iList); - } - SetStatus(eCounting); - return iRes; - } -/*------------------------------------------------------------------------*/ - void ClearExecutor(pExeList self) - { - int iRet; - pDevEntry pDev = NULL; - - assert(self); - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - pDev = (pDevEntry)LLDnodePtr(self->iList); - if(pDev) - { - DeleteDevEntry(pDev); } - LLDnodeDelete(self->iList); - iRet = LLDnodePtr2Prev(self->iList); - iRet = LLDnodePtr2Next(self->iList); } - if(self->pOwner) - { - if(SCGetInterrupt(self->pOwner) > eContinue) - { - self->iStatus = DEVINT; + } else { + self->pOwner = SCCopyConnection(pCon); + } + if (self->iLock == 1) { + SCWrite(pCon, "ERROR: instrument is locked", eError); + return 0; + } + + /* well create a new entry */ + self->iStop = 0; + pNew = CreateDevEntry(pDes, pCon, pData, fNew, name); + if (!pNew) { + SCWrite(pCon, "ERROR: memory exhausted in Device Executor ", eError); + return 0; + } + + /* start it */ + pDrivInt = pDes->GetInterface(pData, DRIVEID); + pCountInt = pDes->GetInterface(pData, COUNTID); + if (pDrivInt) { + iRet = pDrivInt->SetValue(pData, pCon, fNew); + if (iRet == OKOK && self->drivePrint == 1) { + oldVal = pDrivInt->GetValue(pData, pCon); + snprintf(pBueffel, 131, "Driving %s from %8.3f to %8.3f", + name, oldVal, fNew); + SCWrite(pCon, pBueffel, eValue); + } + } else if (pCountInt) { + iRet = pCountInt->StartCount(pData, pCon); + } else { /* this is a programmers error */ + SCWrite(pCon, "ERROR: Programmer error in StartDevice ", eError); + iRet = 0; + } + + /* check return status */ + if (iRet == OKOK) { + LLDnodeAppendFrom(self->iList, &pNew); + sprintf(pBueffel, "started"); + if (NULL != pNew->pCon->deviceID) { + snprintf(pBueffel, 130, "started (%s)", pNew->pCon->deviceID); + } + ExeInterest(self, pNew, pBueffel); + self->iRun = 1; + self->iStatus = DEVDONE; + /* if no task: start it */ + if (self->lTask < 0) { + self->lTask = TaskRegister(self->pTask, + DevExecTask, + DevExecSignal, NULL, self, 1); + self->iEnd = 0; + pCon->conStatus = HWBusy; + } + DevexecLog("START", pNew->name); + return 1; + } else { + sprintf(pBueffel, "ERROR: cannot start device %s", name); + SCWrite(pCon, pBueffel, eError); + DeleteDevEntry(pNew); + if (LLDcheck(self->iList) >= LIST_EMPTY) { + if (self->pOwner != NULL) { + SCDeleteConnection(self->pOwner); } + self->pOwner = NULL; + } + return 0; + } + return 0; +} + +/*--------------------------------------------------------------------------*/ +int StartMotor(pExeList self, SicsInterp * pSics, SConnection * pCon, + char *name, float fVal) +{ + pDummy pMot = NULL; + CommandList *pCom = NULL; + char pBueffel[256]; + + assert(self); + assert(pSics); + assert(name); + + pCom = FindCommand(pSics, name); + if (!pCom) { + sprintf(pBueffel, "ERROR: cannot find motor %s", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pMot = (pDummy) pCom->pData; + if (!pMot) { + sprintf(pBueffel, "ERROR: %s is no motor ", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + + if (!pMot->pDescriptor) { + sprintf(pBueffel, "ERROR: cannot find motor %s", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!pMot->pDescriptor->GetInterface(pMot, DRIVEID)) { + sprintf(pBueffel, "ERROR: %s is no motor", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return StartDevice(self, name, pMot->pDescriptor, (void *) pMot, pCon, + fVal); +} + +/*---------------------------------------------------------------------------*/ +int StartCounter(pExeList self, SicsInterp * pSics, SConnection * pCon, + char *name) +{ + pCounter pCter = NULL; + CommandList *pCom = NULL; + char pBueffel[256]; + + assert(self); + assert(pSics); + assert(name); + + pCom = FindCommand(pSics, name); + if (!pCom) { + sprintf(pBueffel, "ERROR: cannot find counter %s", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pCter = (pCounter) pCom->pData; + if (!pCter) { + sprintf(pBueffel, "ERROR: %s is no counter ", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + + if (!pCter->pDes) { + sprintf(pBueffel, "ERROR: cannot find counter %s", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!pCter->pDes->GetInterface(pCter, COUNTID)) { + sprintf(pBueffel, "ERROR: %s is no counter", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return StartDevice(self, name, pCter->pDes, (void *) pCter, + pCon, pCter->pDriv->fPreset); +} + +/*-------------------------------------------------------------------------*/ +static int checkInterrupt(pCheckContext pCheck, int targetStatus) +{ + if (SCGetInterrupt(pCheck->self->pOwner) != eContinue) { + pCheck->self->iStatus = DEVINT; + SetStatus(eEager); + return -1; + } else { + return targetStatus; + } +} + +/*--------------------------------------------------------------------------*/ +static int initializeCheck(pCheckContext pCheck, pDevEntry pDev) +{ + int eCode = HWFault; + + pCheck->pDev = pDev; + pCheck->pDrivInt = pDev->pDescriptor->GetInterface(pDev->pData, DRIVEID); + pCheck->pCountInt = + pDev->pDescriptor->GetInterface(pDev->pData, COUNTID); + if (pCheck->pDrivInt != NULL) { + eCode = pCheck->pDrivInt->CheckStatus(pDev->pData, pDev->pCon); + } else if (pCheck->pCountInt != NULL) { + eCode = pCheck->pCountInt->CheckCountStatus(pDev->pData, pDev->pCon); + } + return eCode; +} + +/*--------------------------------------------------------------------------*/ +static int finishDevice(pCheckContext pCheck) +{ + int status; + + if (pCheck->pCountInt != NULL) { + pCheck->pCountInt->TransferData(pCheck->pDev->pData, + pCheck->pDev->pCon); + } else if (pCheck->pDrivInt != NULL) { + pCheck->pDrivInt->iErrorCount = 0; + } + ExeInterest(pCheck->self, pCheck->pDev, "finished"); + DevexecLog("STOP", pCheck->pDev->name); + DeleteDevEntry(pCheck->pDev); + LLDnodeDelete(pCheck->self->iList); + status = LLDnodePtr2Prev(pCheck->self->iList); + SCWrite(pCheck->self->pOwner, "", eFinish); + pCheck->self->iStatus = DEVDONE; + return checkInterrupt(pCheck, status); +} + +/*-------------------------------------------------------------------------*/ +static int errorDevice(pCheckContext pCheck) +{ + int status; + + ExeInterest(pCheck->self, pCheck->pDev, "finished with problem"); + DevexecLog("STOP", pCheck->pDev->name); + LLDnodeDelete(pCheck->self->iList); + status = LLDnodePtr2Prev(pCheck->self->iList); + SCWrite(pCheck->self->pOwner, "", eFinish); + pCheck->self->iStatus = DEVERROR; + if (pCheck->pDrivInt != NULL) { + pCheck->pDrivInt->iErrorCount++; + } + status = checkInterrupt(pCheck, status); + DeleteDevEntry(pCheck->pDev); + return status; +} + +/*-------------------------------------------------------------------------*/ +static int testFinish(pExeList self) +{ + if ((self->pOwner == NULL) || (LLDcheck(self->iList) == LIST_EMPTY)) { + if (self->pOwner != NULL) { SCDeleteConnection(self->pOwner); } self->pOwner = NULL; - self->iEnd = 1; - self->lTask = -1; self->iRun = 0; - self->iLock = 0; - } -/*-------------------------------------------------------------------------*/ - int StopCommand(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pExeList self = NULL; - int iRet; - char pBueffel[132]; - - assert(pCon); - assert(pSics); - assert(pData); - - /* check Privilege: Muggers may do it */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: NO Privilege to Stop operation ",eError); - return 0; - } + self->iEnd = 1; + self->iStop = 0; + self->lTask = -1; + return 1; + } else { + return 0; + } +} + +/*--------------------------------------------------------------------------*/ +int CheckExeList(pExeList self) +{ + int iRet, status; + checkContext check; + pDevEntry pDev = NULL; + pICountable pCountInt = NULL; + pIDrivable pDrivInt = NULL; + int eCode; + int isCounting = 0, isDriving = 0; + char pBueffel[512]; + + assert(self); + + /* Sometimes this gets called, though nothing is running. There are + cases where this is feasible for maintainance, but in some cases it + is pure rubbish, because nothing runs. This will be checked here. + */ + if (testFinish(self) == 1) { + return 1; + } + + /* + check the status of all registered devices. Remove when finished + */ + check.self = self; + status = LLDnodePtr2First(self->iList); + while (status != 0) { + LLDnodeDataTo(self->iList, &pDev); + if (pDev) { + eCode = initializeCheck(&check, pDev); + if (eCode != HWNoBeam && eCode != HWPause && self->paused == 1) { + DevexecLog("CONTINUE", "ALL"); + self->paused = 0; + } + switch (eCode) { + case HWIdle: + case OKOK: + status = finishDevice(&check); + if (status < 0) { + return status; + } + break; + case HWFault: /* real HW error: burning, no net etc.. */ + status = errorDevice(&check); + if (status < 0) { + return status; + } + break; + case HWNoBeam: + SetStatus(eOutOfBeam); + if (self->paused == 0) { + self->paused = 1; + DevexecLog("NOBEAM", "ALL"); + } + status = checkInterrupt(&check, 1); + if (status < 0) { + return status; + } + break; + case HWPause: + SetStatus(ePaused); + if (self->paused == 0) { + self->paused = 1; + DevexecLog("PAUSE", "ALL"); + } + status = checkInterrupt(&check, 1); + if (status < 0) { + /* + * continue in order to wait for devices to come to a stop + */ + ContinueExecution(self); + return status; + } + break; + case HWBusy: + if (check.pDrivInt != NULL) { + isDriving = 1; + } else if (check.pCountInt != NULL) { + isCounting = 1; + } + self->iStatus = DEVBUSY; + break; + case HWPosFault: /* cannot get somewhere... */ + status = errorDevice(&check); + if (status < 0) { + return status; + } + break; + } + } + status = LLDnodePtr2Next(self->iList); + } + + if (isCounting) { + if (isDriving) { + SetStatus(eCountDrive); + } else { + SetStatus(eCounting); + } + } else if (isDriving) { + SetStatus(eDriving); + } + + iRet = LLDnodePtr2First(self->iList); + return testFinish(self); +} + +/*---------------------------------------------------------------------------*/ +int Wait4Success(pExeList self) +{ + int iRet; + assert(self); + + /* do nothing if not running */ + if (self->lTask < 0) { + printf("Nothing to wait for.... \n"); + self->iRun = 0; /* not sure if this is needed here, but does not harm */ + return self->iStatus; + } + + /* wait for Devexec task to finish */ + TaskWait(self->pTask, self->lTask); +#ifdef DEBUG + printf("Wait4Success finished\n"); +#endif + self->iRun = 0; + return self->iStatus; +} + +/*--------------------------------------------------------------------------*/ +int ListPending(pExeList self, SConnection * pCon) +{ + int iRet, i; + char pBueffel[512]; + pDevEntry pDev = NULL; + + assert(self); + assert(pCon); + + /* first make sure that the list is fully updated */ + iRet = CheckExeList(self); + if (iRet == 1) { /* nothing to do! */ + SCWrite(pCon, "Machine idle", eValue); + return 1; + } else if (iRet == -1) { + SCWrite(pCon, "Handling Interrupt", eError); + return 0; + } + + + /* search the list for entries */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &pDev); + if (pDev) { + sprintf(pBueffel, "\t%s %f", pDev->name, pDev->fVal); + SCWrite(pCon, pBueffel, eValue); + } + iRet = LLDnodePtr2Next(self->iList); + } + return 1; +} + +/* -----------------------------------------------------------------------*/ +long GetDevexecID(pExeList self) +{ + assert(self); + + return self->lTask; +} + +/*--------------------------------------------------------------------------*/ +int StopExe(pExeList self, char *name) +{ + int i, iRet; + pDevEntry pDev = NULL; + pIDrivable pDrivInt = NULL; + pICountable pCountInt = NULL; + assert(self); + + /* if not active, nothing to do */ + if ((self->pOwner == NULL) || (LLDcheck(self->iList) == LIST_EMPTY)) { + self->iRun = 0; + return 1; + } + + /* first the ALL case */ + if (strcmp(name, "all") == 0) { + /* + check for stop flag. This is to stop unnecessary calls to StopExe. + There may be way to many, but each call is reasonable under certain + circumstances. + */ + if (self->iStop == 1) { + return 0; + } else { + self->iStop = 1; + } + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + pDev = (pDevEntry) LLDnodePtr(self->iList); + if (pDev) { + pDrivInt = pDev->pDescriptor->GetInterface(pDev->pData, DRIVEID); + pCountInt = pDev->pDescriptor->GetInterface(pDev->pData, COUNTID); + if (pDrivInt) { + pDrivInt->Halt(pDev->pData); + } else if (pCountInt) { + pCountInt->Halt(pDev->pData); + } + } + iRet = LLDnodePtr2Next(self->iList); + } + SCWrite(self->pOwner, "ERROR: Full Stop called!!", eError); + if (SCGetInterrupt(self->pOwner) > eContinue) { + self->iStatus = DEVINT; + } + return 1; + } + + /* now the special case: a well defined command */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + pDev = (pDevEntry) LLDnodePtr(self->iList); + if (pDev) { + if (strcmp(pDev->name, name) == 0) { + pDrivInt = pDev->pDescriptor->GetInterface(pDev->pData, DRIVEID); + pCountInt = pDev->pDescriptor->GetInterface(pDev->pData, COUNTID); + if (pDrivInt) { + pDrivInt->Halt(pDev->pData); + } else if (pCountInt) { + pCountInt->Halt(pDev->pData); + } + return 1; + } + } + iRet = LLDnodePtr2Next(self->iList); + } + + return 0; +} - argtolower(argc,argv); - self = (pExeList)pData; - if(argc < 2) - { - ListPending(self,pCon); - return 1; - } - - iRet = StopExe(self,argv[1]); - if(!iRet) - { - sprintf(pBueffel,"ERROR: %s not found, so could not halt", argv[1]); - SCWrite(pCon,pBueffel,eError); - } - return iRet; - } -/*------------------- The CallBack function for interest ------------------*/ - static int DrivStatCallback(int iEvent, void *text, void *pCon) - { - assert(pCon); - assert(text); - SConnection *con = (SConnection *)pCon; - - if(con == NULL || !SCisConnected(con)) - { - return -1; - } - SCWrite(pCon, text, eLog); - return 1; - } - /*--------------------------------------------------------------------------*/ - int ListExe(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pExeList self = NULL; - int list; - - if (argc == 1) { - return ListPending((pExeList)pData,pCon); - } - argtolower(argc,argv); - self = (pExeList)pData; - assert(self); - if (argc == 2) { - if (strcmp(argv[1], "interest") == 0) - { - list = RegisterCallback(self->pCall, - DRIVSTAT, DrivStatCallback, - SCCopyConnection(pCon), NULL); - SCSendOK(pCon); - return 1; - } - if (strcmp(argv[1], "uninterest") == 0) - { - RemoveCallbackCon(self->pCall,pCon); - SCSendOK(pCon); - return 1; - } - } - SCWrite(pCon, "ERROR: illegal arguments for ListExe", eError); - return 0; - } /*-------------------------------------------------------------------------*/ - int SicsIdle(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pExeList self = NULL; - int idle; - char pBueffel[80]; - - self = (pExeList)pData; - assert(self); - idle = time(NULL) - self->lastRun; - snprintf(pBueffel,79,"sicsidle = %d",idle); - SCWrite(pCon,pBueffel,eValue); - return 1; - } +int StopExeWait(pExeList self) +{ + StopExe(self, "all"); + Wait4Success(self); + return 1; +} + +/*--------------------------------------------------------------------------*/ +int PauseExecution(pExeList self) +{ + int i, iRet, iRes; + pDevEntry pDev = NULL; + pICountable pCountInt = NULL; + assert(self); + + /* step through the list */ + iRes = 1; + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + pDev = (pDevEntry) LLDnodePtr(self->iList); + if (pDev) { + pCountInt = pDev->pDescriptor->GetInterface(pDev->pData, COUNTID); + if (pCountInt) { + iRet = pCountInt->Pause(pDev->pData, pDev->pCon); + if (!iRet) { + iRes = 0; + } + } + + } + iRet = LLDnodePtr2Next(self->iList); + } + SetStatus(ePaused); + return iRes; +} + +/*------------------------------------------------------------------------*/ +int IsCounting(pExeList self) +{ + int iRet; + pDevEntry pDev = NULL; + pICountable pCountInt = NULL; + assert(self); + + /* step through the list */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + pDev = (pDevEntry) LLDnodePtr(self->iList); + if (pDev) { + pCountInt = pDev->pDescriptor->GetInterface(pDev->pData, COUNTID); + if (pCountInt) { + return 1; + } + } + iRet = LLDnodePtr2Next(self->iList); + } + return 0; +} + +/*--------------------------------------------------------------------------*/ +int ContinueExecution(pExeList self) +{ + int i, iRet, iRes; + pDevEntry pDev = NULL; + pICountable pCountInt = NULL; + assert(self); + + /* step through the list */ + iRes = 1; + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + pDev = (pDevEntry) LLDnodePtr(self->iList); + if (pDev) { + pCountInt = pDev->pDescriptor->GetInterface(pDev->pData, COUNTID); + if (pCountInt) { + iRet = pCountInt->Continue(pDev->pData, pDev->pCon); + if (!iRet) { + iRes = 0; + } + } + + } + iRet = LLDnodePtr2Next(self->iList); + } + SetStatus(eCounting); + return iRes; +} + +/*------------------------------------------------------------------------*/ +void ClearExecutor(pExeList self) +{ + int iRet; + pDevEntry pDev = NULL; + + assert(self); + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + pDev = (pDevEntry) LLDnodePtr(self->iList); + if (pDev) { + DeleteDevEntry(pDev); + } + LLDnodeDelete(self->iList); + iRet = LLDnodePtr2Prev(self->iList); + iRet = LLDnodePtr2Next(self->iList); + } + if (self->pOwner) { + if (SCGetInterrupt(self->pOwner) > eContinue) { + self->iStatus = DEVINT; + } + SCDeleteConnection(self->pOwner); + } + self->pOwner = NULL; + self->iEnd = 1; + self->lTask = -1; + self->iRun = 0; + self->iLock = 0; +} + +/*-------------------------------------------------------------------------*/ +int StopCommand(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pExeList self = NULL; + int iRet; + char pBueffel[132]; + + assert(pCon); + assert(pSics); + assert(pData); + + /* check Privilege: Muggers may do it */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: NO Privilege to Stop operation ", eError); + return 0; + } + + argtolower(argc, argv); + self = (pExeList) pData; + if (argc < 2) { + ListPending(self, pCon); + return 1; + } + + iRet = StopExe(self, argv[1]); + if (!iRet) { + sprintf(pBueffel, "ERROR: %s not found, so could not halt", argv[1]); + SCWrite(pCon, pBueffel, eError); + } + return iRet; +} + +/*------------------- The CallBack function for interest ------------------*/ +static int DrivStatCallback(int iEvent, void *text, void *pCon) +{ + assert(pCon); + assert(text); + SConnection *con = (SConnection *) pCon; + + if (con == NULL || !SCisConnected(con)) { + return -1; + } + SCWrite(pCon, text, eLog); + return 1; +} + + /*--------------------------------------------------------------------------*/ +int ListExe(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pExeList self = NULL; + int list; + + if (argc == 1) { + return ListPending((pExeList) pData, pCon); + } + argtolower(argc, argv); + self = (pExeList) pData; + assert(self); + if (argc == 2) { + if (strcmp(argv[1], "interest") == 0) { + list = RegisterCallback(self->pCall, + DRIVSTAT, DrivStatCallback, + SCCopyConnection(pCon), NULL); + SCSendOK(pCon); + return 1; + } + if (strcmp(argv[1], "uninterest") == 0) { + RemoveCallbackCon(self->pCall, pCon); + SCSendOK(pCon); + return 1; + } + } + SCWrite(pCon, "ERROR: illegal arguments for ListExe", eError); + return 0; +} + +/*-------------------------------------------------------------------------*/ +int SicsIdle(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pExeList self = NULL; + int idle; + char pBueffel[80]; + + self = (pExeList) pData; + assert(self); + idle = time(NULL) - self->lastRun; + snprintf(pBueffel, 79, "sicsidle = %d", idle); + SCWrite(pCon, pBueffel, eValue); + return 1; +} + /*-------------------------------------------------------------------------- Usage: Success */ - - int Success(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet; - Status eOld; - - eOld = GetStatus(); - SetStatus(eRunning); - iRet = Wait4Success((pExeList)pData); - if(iRet == DEVINT) - { - if(SCGetInterrupt(pCon) == eAbortOperation) - { - SCSetInterrupt(pCon,eContinue); - iRet = 0; - } - } - else if(iRet == DEVDONE) - { - SCWrite(pCon,"All done",eValue); - iRet = 1; - } - else if(iRet == DEVERROR) - { - SCWrite(pCon,"Finished with Problems",eValue); - iRet = 1; - } - SetStatus(eEager); - return iRet; - } -/*-------------------------------------------------------------------------*/ - int PauseAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int status; - status = PauseExecution((pExeList)pData); - if(status) - { - SCSendOK(pCon); - return 1; - } - else - { - SCWrite(pCon,"ERROR: failed to pause",eError); - return 0; - } - } - /*---------------------------------------------------------------------*/ - int DevexecAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int val; - char pBueffel[256]; - - pExeList self = (pExeList)pData; - if(argc < 2) - { - SCWrite(pCon,"ERROR: not enough argumentd to devexec command",eError); - return 0; +int Success(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet; + Status eOld; + + eOld = GetStatus(); + SetStatus(eRunning); + iRet = Wait4Success((pExeList) pData); + if (iRet == DEVINT) { + if (SCGetInterrupt(pCon) == eAbortOperation) { + SCSetInterrupt(pCon, eContinue); + iRet = 0; } - strtolower(argv[1]); - if(strcmp(argv[1],"driveprint") == 0) - { - if(argc > 2 && SCMatchRights(pCon,usUser)) - { - val = atoi(argv[2]); - self->drivePrint = val; - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,255,"devexe.drivePrint = %d", - self->drivePrint); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } else { - SCWrite(pCon,"ERROR: unknown subcommand to devexec",eError); - return 0; - } - } + } else if (iRet == DEVDONE) { + SCWrite(pCon, "All done", eValue); + iRet = 1; + } else if (iRet == DEVERROR) { + SCWrite(pCon, "Finished with Problems", eValue); + iRet = 1; + } + SetStatus(eEager); + return iRet; +} + /*-------------------------------------------------------------------------*/ - int ContinueAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int status; - Status eStat; +int PauseAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int status; - eStat = GetStatus(); - if(eStat != ePaused) - { - SCWrite(pCon,"ERROR: Not paused, ignored",eError); - return 0; - } - - status = ContinueExecution((pExeList)pData); - if(status) - { - SCSendOK(pCon); - return 1; - } - else - { - SCWrite(pCon,"ERROR: failed to pause",eError); - return 0; - } - } - -/*--------------------------------------------------------------------------*/ - int isInRunMode(pExeList self) - { - if(self == NULL) - { - return 0; - } - else - { - return self->iRun; - } + status = PauseExecution((pExeList) pData); + if (status) { + SCSendOK(pCon); + return 1; + } else { + SCWrite(pCon, "ERROR: failed to pause", eError); + return 0; } -/*--------------------------------------------------------------------------*/ - SConnection *GetExeOwner(pExeList self) - { - if(self == NULL) - return NULL; +} - return self->pOwner; + /*---------------------------------------------------------------------*/ +int DevexecAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int val; + char pBueffel[256]; + + pExeList self = (pExeList) pData; + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough argumentd to devexec command", + eError); + return 0; } -/*--------------------------------------------------------------------------*/ - int DevExecTask(void *pData) - { - pExeList self = NULL; - char pBueffel[132], pInterrupt[80]; - int iRet, iInterrupt; - - self = (pExeList)pData; - - /* am I bound to end ? */ - if(self->iEnd) - { - self->lTask = -1; - SetStatus(eEager); - return 0; - } - - if(self->taskRunning == 1){ - printf("DevexecTask reentrant protection triggered\n"); - return 1; - } - /* - * CheckExeList may cause waits and thus reentrant calls to - * this. Which can cause trouble - */ - self->taskRunning = 1; - iRet = CheckExeList(self); - self->taskRunning = 0; - - - self->lastRun = time(NULL); - switch(iRet) - { - case -1: /* some problem */ - iInterrupt = SCGetInterrupt(self->pOwner); - if(iInterrupt != eContinue) - { - if(iInterrupt > 1) - { - self->taskRunning = 1; - StopExe(self,"all"); - self->taskRunning = 0; - } -#ifdef DEBUG - printf("DevExecTask found an error\n"); -#endif - return 1; - } - else - { - return 1; - } - break; - case 1: /* Success */ - self->lTask = -1; - self->iEnd = 1; - SetStatus(eEager); -#ifdef DEBUG - printf("DevExecTask finishes on success\n"); -#endif - return 0; - break; - default: /* continue, still busy */ - return 1; - } - /* should not get here */ + strtolower(argv[1]); + if (strcmp(argv[1], "driveprint") == 0) { + if (argc > 2 && SCMatchRights(pCon, usUser)) { + val = atoi(argv[2]); + self->drivePrint = val; + SCSendOK(pCon); return 1; - } -/*---------------------------------------------------------------------------*/ - void DevExecSignal(void *pEL, int iSignal, void *pSigData) - { - int *iInt; - pExeList self = NULL; - SConnection *pCon = NULL; - - self = (pExeList)pEL; - assert(self); - - if(iSignal == SICSINT) - { - iInt = (int *)pSigData; - if(*iInt != eContinue) - { - if(self->pOwner) - { - pCon = SCCopyConnection(self->pOwner); - if(pCon != NULL){ - pCon->transID = 0; - strcpy(pCon->deviceID,"system"); - SCWrite(pCon, - "ERROR: Interrupting Current Hardware Operation", - eError); - SCSetInterrupt(pCon,*iInt); - SCDeleteConnection(pCon); - } - } - StopExe(self,"all"); - } + } else { + snprintf(pBueffel, 255, "devexe.drivePrint = %d", self->drivePrint); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else { + SCWrite(pCon, "ERROR: unknown subcommand to devexec", eError); + return 0; + } +} + +/*-------------------------------------------------------------------------*/ +int ContinueAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int status; + Status eStat; + + eStat = GetStatus(); + if (eStat != ePaused) { + SCWrite(pCon, "ERROR: Not paused, ignored", eError); + return 0; + } + + status = ContinueExecution((pExeList) pData); + if (status) { + SCSendOK(pCon); + return 1; + } else { + SCWrite(pCon, "ERROR: failed to pause", eError); + return 0; + } +} + +/*--------------------------------------------------------------------------*/ +int isInRunMode(pExeList self) +{ + if (self == NULL) { + return 0; + } else { + return self->iRun; + } +} + +/*--------------------------------------------------------------------------*/ +SConnection *GetExeOwner(pExeList self) +{ + if (self == NULL) + return NULL; + + return self->pOwner; +} + +/*--------------------------------------------------------------------------*/ +int DevExecTask(void *pData) +{ + pExeList self = NULL; + char pBueffel[132], pInterrupt[80]; + int iRet, iInterrupt; + + self = (pExeList) pData; + + /* am I bound to end ? */ + if (self->iEnd) { + self->lTask = -1; + SetStatus(eEager); + return 0; + } + + if (self->taskRunning == 1) { + printf("DevexecTask reentrant protection triggered\n"); + return 1; + } + /* + * CheckExeList may cause waits and thus reentrant calls to + * this. Which can cause trouble + */ + self->taskRunning = 1; + iRet = CheckExeList(self); + self->taskRunning = 0; + + + self->lastRun = time(NULL); + switch (iRet) { + case -1: /* some problem */ + iInterrupt = SCGetInterrupt(self->pOwner); + if (iInterrupt != eContinue) { + if (iInterrupt > 1) { + self->taskRunning = 1; + StopExe(self, "all"); + self->taskRunning = 0; } - } +#ifdef DEBUG + printf("DevExecTask found an error\n"); +#endif + return 1; + } else { + return 1; + } + break; + case 1: /* Success */ + self->lTask = -1; + self->iEnd = 1; + SetStatus(eEager); +#ifdef DEBUG + printf("DevExecTask finishes on success\n"); +#endif + return 0; + break; + default: /* continue, still busy */ + return 1; + } + /* should not get here */ + return 1; +} + +/*---------------------------------------------------------------------------*/ +void DevExecSignal(void *pEL, int iSignal, void *pSigData) +{ + int *iInt; + pExeList self = NULL; + SConnection *pCon = NULL; + + self = (pExeList) pEL; + assert(self); + + if (iSignal == SICSINT) { + iInt = (int *) pSigData; + if (*iInt != eContinue) { + if (self->pOwner) { + pCon = SCCopyConnection(self->pOwner); + if (pCon != NULL) { + pCon->transID = 0; + strcpy(pCon->deviceID, "system"); + SCWrite(pCon, + "ERROR: Interrupting Current Hardware Operation", + eError); + SCSetInterrupt(pCon, *iInt); + SCDeleteConnection(pCon); + } + } + StopExe(self, "all"); + } + } +} + /*--------------------------------------------------------------------*/ void LockDeviceExecutor(pExeList self) { assert(self); self->iLock = 1; -} +} + /*--------------------------------------------------------------------*/ void UnlockDeviceExecutor(pExeList self) { assert(self); self->iLock = 0; -} - - - - - +} diff --git a/devexec.h b/devexec.h index 028d5e37..59b662e7 100644 --- a/devexec.h +++ b/devexec.h @@ -28,7 +28,7 @@ #include "obdes.h" #include "task.h" - typedef struct __EXELIST *pExeList; +typedef struct __EXELIST *pExeList; /* Returncodes */ @@ -40,19 +40,19 @@ /*------------------------------------------------------------------------ B I R T H & D E A T H */ - pExeList CreateExeList(pTaskMan pTask); - void DeleteExeList(void *self); - +pExeList CreateExeList(pTaskMan pTask); +void DeleteExeList(void *self); + /* ================= Functions to talk to the above ====================== */ #line 43 "devexec.w" - int StartDevice(pExeList self, char *name, pObjectDescriptor pDes, - void *pData, SConnection *pCon, float fNew); - int StartMotor(pExeList self, SicsInterp *pSics, SConnection *pCon, - char *name, float fNew); - int StartCounter(pExeList self, SicsInterp *pSics, SConnection *pCon, - char *name); +int StartDevice(pExeList self, char *name, pObjectDescriptor pDes, + void *pData, SConnection * pCon, float fNew); +int StartMotor(pExeList self, SicsInterp * pSics, SConnection * pCon, + char *name, float fNew); +int StartCounter(pExeList self, SicsInterp * pSics, SConnection * pCon, + char *name); #line 239 "devexec.w" @@ -60,115 +60,115 @@ #line 88 "devexec.w" - int CheckExeList(pExeList self); +int CheckExeList(pExeList self); /* - checks the entries for success and deletes entries which have finished - operation. If there are none left, the pOwner will be set to NULL. - */ - int Wait4Success(pExeList self); + checks the entries for success and deletes entries which have finished + operation. If there are none left, the pOwner will be set to NULL. + */ +int Wait4Success(pExeList self); - long GetDevexecID(pExeList self); +long GetDevexecID(pExeList self); - int DevExecTask(void *pEL); - void DevExecSignal(void *pEL, int iSignal, void *pSigData); +int DevExecTask(void *pEL); +void DevExecSignal(void *pEL, int iSignal, void *pSigData); #line 241 "devexec.w" /* - Waits for execution to finish. returns 1 on Success, 0 if problems - ocurred. Than the Interrupt code shall be checked and acted upon - accordingly. - */ + Waits for execution to finish. returns 1 on Success, 0 if problems + ocurred. Than the Interrupt code shall be checked and acted upon + accordingly. + */ /*-------------------------------------------------------------------------*/ - SConnection *GetExeOwner(pExeList self); +SConnection *GetExeOwner(pExeList self); /*-------------------------------------------------------------------------*/ - int isInRunMode(pExeList self); +int isInRunMode(pExeList self); /*--------------------------------------------------------------------------*/ - int ListPending(pExeList self, SConnection *pCon); +int ListPending(pExeList self, SConnection * pCon); /* - lists the Operations still pending on pCon. - */ + lists the Operations still pending on pCon. + */ /*-------------------------------------------------------------------------*/ #line 137 "devexec.w" - int StopExe(pExeList self, char *name); - int StopExeWait(pExeList self); +int StopExe(pExeList self, char *name); +int StopExeWait(pExeList self); /* - will stop the entry name and its subentries from executing. - If ALL is specified as name, everything will be stopped and - the Executor cleared. - StopExeWait will stop all running things and wait for the stop - to complete. - */ + will stop the entry name and its subentries from executing. + If ALL is specified as name, everything will be stopped and + the Executor cleared. + StopExeWait will stop all running things and wait for the stop + to complete. + */ /*------------------------------------------------------------------------*/ - void ClearExecutor(pExeList self); +void ClearExecutor(pExeList self); /* - clears the executor without sending commands to the devices. - */ + clears the executor without sending commands to the devices. + */ /*-----------------------------------------------------------------------*/ - int IsCounting(pExeList self); - int PauseExecution(pExeList self); - int ContinueExecution(pExeList self); +int IsCounting(pExeList self); +int PauseExecution(pExeList self); +int ContinueExecution(pExeList self); #line 259 "devexec.w" /*-------------------------- Commands ------------------------------------*/ - int DevexecAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int StopCommand(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int DevexecAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int StopCommand(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* - implements the stop command - */ - - int ListExe(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - /* - lists all currently executing objects - */ - int SicsIdle(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - /* - prints the seconds since the device executor was running the last time - */ + implements the stop command + */ - int Success(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int ListExe(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* - waits until completion of all pending operations. Used in - connection with non blocking operation such as motors started - with run. - */ - int PauseAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); + lists all currently executing objects + */ +int SicsIdle(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + /* + prints the seconds since the device executor was running the last time + */ + +int Success(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* - pauses execution - */ - int ContinueAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); + waits until completion of all pending operations. Used in + connection with non blocking operation such as motors started + with run. + */ +int PauseAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* - continues execution - */ - + pauses execution + */ +int ContinueAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + /* + continues execution + */ + /*--------------------------- Locking ---------------------------------*/ - + #line 183 "devexec.w" - - void LockDeviceExecutor(pExeList self); - void UnlockDeviceExecutor(pExeList self); - - + +void LockDeviceExecutor(pExeList self); +void UnlockDeviceExecutor(pExeList self); + + #line 299 "devexec.w" - + /* -------------------------- Executor management -------------------------*/ - - pExeList GetExecutor(void); - void SetExecutor(pExeList pExe); + +pExeList GetExecutor(void); +void SetExecutor(pExeList pExe); /*----------------------- Logging -----------------------------------------*/ - void DevexecLog(char *op, char *device); -#endif +void DevexecLog(char *op, char *device); +#endif diff --git a/devser.c b/devser.c index 3bc74d21..040b1469 100644 --- a/devser.c +++ b/devser.c @@ -12,7 +12,7 @@ typedef struct DevAction { typedef struct SchedHeader { struct SchedHeader *next; - DevAction *actions; /* list of actions for given interval and prio */ + DevAction *actions; /* list of actions for given interval and prio */ DevAction *followingAction; double interval; double timeDue; @@ -20,48 +20,54 @@ typedef struct SchedHeader { } SchedHeader; struct DevSer { - Ascon *asyncConn; /* connection */ + Ascon *asyncConn; /* connection */ DevAction *current; int killCurrent; - DevAction *actions; /* the action queue */ + DevAction *actions; /* the action queue */ SchedHeader *headers; ErrMsg *errmsg; int steps; int stopTask; }; - + static char *devPrio[NumberOfPRIO] = { "null", "slow", "read", "progress", "write", "halt" }; -char *DevPrio2Text(DevPrio prio) { +char *DevPrio2Text(DevPrio prio) +{ if (prio <= 0 || prio >= NumberOfPRIO) { prio = NullPRIO; } - return devPrio[prio]; + return devPrio[prio]; } -DevPrio DevText2Prio(char *text) { +DevPrio DevText2Prio(char *text) +{ DevPrio prio; for (prio = 0; prio < NumberOfPRIO; prio++) { - if (strcasecmp(text, devPrio[prio]) == 0) return prio; + if (strcasecmp(text, devPrio[prio]) == 0) + return prio; } return NullPRIO; } -static void DevFreeActionList(DevAction *actions) { +static void DevFreeActionList(DevAction * actions) +{ DevAction *victim; while (actions != NULL) { victim = actions; actions = victim->next; - if (victim->kill != NULL) victim->kill(victim->data); + if (victim->kill != NULL) + victim->kill(victim->data); free(victim); } } -static void DevKillTask(void *ds) { +static void DevKillTask(void *ds) +{ DevSer *devser = ds; - + if (devser->stopTask) { free(devser); } else { @@ -69,11 +75,12 @@ static void DevKillTask(void *ds) { } } -DevAction *DevNextAction(DevSer *devser) { +DevAction *DevNextAction(DevSer * devser) +{ DevPrio prio; double now; SchedHeader *header; - + devser->current = NULL; if (devser->actions) { @@ -83,8 +90,7 @@ DevAction *DevNextAction(DevSer *devser) { } now = DoubleTime(); for (header = devser->headers; - header != NULL && header->prio > prio; - header = header->next) { + header != NULL && header->prio > prio; header = header->next) { if (header->followingAction == NULL) { if (now >= header->timeDue) { header->followingAction = header->actions; @@ -92,7 +98,7 @@ DevAction *DevNextAction(DevSer *devser) { header->timeDue = now; } else { header->timeDue = (floor(now / header->interval) + 1) - * header->interval; + * header->interval; } } } @@ -111,14 +117,16 @@ DevAction *DevNextAction(DevSer *devser) { return devser->current; } -int DevQueueTask(void *ds) { +int DevQueueTask(void *ds) +{ DevSer *devser = ds; AsconStatus status; DevAction *action; char *sendData; char *replyData; - - if (devser->steps == 0) return 1; + + if (devser->steps == 0) + return 1; if (devser->stopTask) { return 0; } @@ -134,10 +142,10 @@ int DevQueueTask(void *ds) { } else if (status != AsconReady) { return 1; } - if (devser->steps > 0) { /* debugging mode */ + if (devser->steps > 0) { /* debugging mode */ devser->steps--; } - if(status == AsconFailure){ + if (status == AsconFailure) { replyData = devser->errmsg->text; } else { replyData = AsconRead(devser->asyncConn); @@ -148,7 +156,8 @@ int DevQueueTask(void *ds) { return 1; } if (devser->killCurrent) { - if (action->kill != NULL) action->kill(action->data); + if (action->kill != NULL) + action->kill(action->data); devser->killCurrent = 0; free(action); devser->current = NULL; @@ -158,10 +167,11 @@ int DevQueueTask(void *ds) { return 1; } -DevSer *DevMake(SConnection *con, int argc, char *argv[]) { +DevSer *DevMake(SConnection * con, int argc, char *argv[]) +{ DevSer *devser = NULL; Ascon *asyncConn = NULL; - + asyncConn = AsconMake(con, argc, argv); if (!asyncConn) { return NULL; @@ -174,17 +184,19 @@ DevSer *DevMake(SConnection *con, int argc, char *argv[]) { devser->actions = NULL; devser->headers = NULL; devser->stopTask = 0; - devser->steps = -1; /* no debugging by default */ + devser->steps = -1; /* no debugging by default */ TaskRegister(pServ->pTasker, DevQueueTask, NULL, DevKillTask, devser, 0); return devser; } -void DevDebugMode(DevSer *devser, int steps) { +void DevDebugMode(DevSer * devser, int steps) +{ devser->steps = steps; } DevAction *DevNewAction(void *data, DevActionHandler hdl, - DevKillActionData *killFunc, DevPrio prio) { + DevKillActionData * killFunc, DevPrio prio) +{ DevAction *action; action = calloc(1, sizeof(*action)); assert(action); @@ -196,7 +208,8 @@ DevAction *DevNewAction(void *data, DevActionHandler hdl, return action; } -void DevKill(DevSer *devser) { +void DevKill(DevSer * devser) +{ SchedHeader *h, *victim; if (devser->asyncConn) { @@ -217,24 +230,29 @@ void DevKill(DevSer *devser) { } } -void DevDisconnect(DevSer *devser){ - if(devser->asyncConn){ - AsconDisconnect(devser->asyncConn); - } +void DevDisconnect(DevSer * devser) +{ + if (devser->asyncConn) { + AsconDisconnect(devser->asyncConn); + } } -int DevQueue(DevSer *devser, void *actionData, DevPrio prio, - DevActionHandler hdl, DevActionMatch *matchFunc, - DevKillActionData *killFunc) { +int DevQueue(DevSer * devser, void *actionData, DevPrio prio, + DevActionHandler hdl, DevActionMatch * matchFunc, + DevKillActionData * killFunc) +{ DevAction *action, **ptr2Last; DevAction *new; - - if (prio <= NullPRIO) prio = NullPRIO + 1; - if (prio >= NumberOfPRIO) prio = NumberOfPRIO - 1; + + if (prio <= NullPRIO) + prio = NullPRIO + 1; + if (prio >= NumberOfPRIO) + prio = NumberOfPRIO - 1; ptr2Last = &devser->actions; - for (action = devser->actions; action != NULL && action->prio >= prio; action = action->next) { + for (action = devser->actions; action != NULL && action->prio >= prio; + action = action->next) { if (action->hdl == hdl && matchFunc(actionData, action->data)) { - return 0; /* there is already an identical action */ + return 0; /* there is already an identical action */ } ptr2Last = &action->next; } @@ -244,30 +262,32 @@ int DevQueue(DevSer *devser, void *actionData, DevPrio prio, return 1; } -int DevUnschedule(DevSer *devser, void *actionData, - DevActionHandler hdl, DevActionMatch *matchFunc) { +int DevUnschedule(DevSer * devser, void *actionData, + DevActionHandler hdl, DevActionMatch * matchFunc) +{ SchedHeader *header = NULL; DevAction **ptr2Last = NULL; - DevAction *action = NULL; - int cnt=0; - + DevAction *action = NULL; + int cnt = 0; + /* scan through all headers */ for (header = devser->headers; header != NULL; header = header->next) { ptr2Last = &header->actions; for (action = header->actions; action != NULL; action = *ptr2Last) { if (action->hdl == hdl && matchFunc(actionData, action->data)) { if (action == header->followingAction) { - /* advance followingAction if equal*/ + /* advance followingAction if equal */ header->followingAction = action->next; } if (action == devser->current) { devser->current = NULL; - devser->killCurrent = 0; /* should already be 0 */ + devser->killCurrent = 0; /* should already be 0 */ } cnt++; /* remove from list */ *ptr2Last = action->next; - if (action->kill != NULL) action->kill(action->data); + if (action->kill != NULL) + action->kill(action->data); free(action); } else { ptr2Last = &action->next; @@ -277,10 +297,11 @@ int DevUnschedule(DevSer *devser, void *actionData, return cnt; } -int DevSchedule(DevSer *devser, void *actionData, +int DevSchedule(DevSer * devser, void *actionData, DevPrio prio, double interval, - DevActionHandler hdl, DevActionMatch *matchFunc, - DevKillActionData *killFunc) { + DevActionHandler hdl, DevActionMatch * matchFunc, + DevKillActionData * killFunc) +{ SchedHeader *header = NULL; SchedHeader **ptr2LastHeader = NULL; SchedHeader *newHeader; @@ -289,10 +310,12 @@ int DevSchedule(DevSer *devser, void *actionData, DevAction *newAction; int ret; - if (prio <= NullPRIO) prio = NullPRIO + 1; - if (prio >= NumberOfPRIO) prio = NumberOfPRIO - 1; + if (prio <= NullPRIO) + prio = NullPRIO + 1; + if (prio >= NumberOfPRIO) + prio = NumberOfPRIO - 1; ret = DevUnschedule(devser, actionData, hdl, matchFunc); - + newAction = DevNewAction(actionData, hdl, killFunc, prio); /* find matching header */ ptr2LastHeader = &devser->headers; @@ -300,7 +323,7 @@ int DevSchedule(DevSer *devser, void *actionData, if (header->prio == newAction->prio && header->interval == interval) { /* append new action at the tail */ ptr2Last = &header->actions; - for (action = header->actions; action != NULL; action=action->next) { + for (action = header->actions; action != NULL; action = action->next) { ptr2Last = &action->next; } *ptr2Last = newAction; @@ -319,7 +342,7 @@ int DevSchedule(DevSer *devser, void *actionData, ptr2LastHeader = &header->next; } } - + /* insert new header */ newHeader = calloc(1, sizeof(*newHeader)); assert(newHeader); @@ -333,19 +356,21 @@ int DevSchedule(DevSer *devser, void *actionData, return ret; } -int DevRemoveAction(DevSer *devser, void *actionData) { +int DevRemoveAction(DevSer * devser, void *actionData) +{ SchedHeader *header = NULL; DevAction **ptr2Last = NULL; - DevAction *action = NULL; - int cnt=0; - - + DevAction *action = NULL; + int cnt = 0; + + /* Remove current action, if matched. If a reply is pending, the next action will get the reply. But as in the inital state no reply is expected, this should not harm. */ action = devser->current; if (action != NULL && actionData == action->data) { if (devser->killCurrent) { - if (action->kill != NULL) action->kill(action->data); + if (action->kill != NULL) + action->kill(action->data); devser->killCurrent = 0; free(action); } @@ -358,7 +383,8 @@ int DevRemoveAction(DevSer *devser, void *actionData) { cnt++; /* remove from list */ *ptr2Last = action->next; - if (action->kill != NULL) action->kill(action->data); + if (action->kill != NULL) + action->kill(action->data); free(action); } else { ptr2Last = &action->next; diff --git a/devser.h b/devser.h index d5d42248..4bba95db 100644 --- a/devser.h +++ b/devser.h @@ -31,7 +31,8 @@ typedef void DevKillActionData(void *actionData); * NullPRIO and NumberOfPRIO must not be used as priority */ typedef enum { - NullPRIO, SlowPRIO, ReadPRIO, ProgressPRIO, WritePRIO, HaltPRIO, NumberOfPRIO + NullPRIO, SlowPRIO, ReadPRIO, ProgressPRIO, WritePRIO, HaltPRIO, + NumberOfPRIO } DevPrio; /** \brief Make a new device serializer and async connection. @@ -40,24 +41,24 @@ typedef enum { * \param argv the args * \return the created device serializer or NULL on failure */ -DevSer *DevMake(SConnection *con, int argc, char *argv[]); +DevSer *DevMake(SConnection * con, int argc, char *argv[]); /** \brief put the device serializer into debug mode * \param devser the device serializer * \param steps the number of steps to be executed or -1 for disable debugging mode */ -void DevDebugMode(DevSer *devser, int steps); +void DevDebugMode(DevSer * devser, int steps); /** \brief Kill the contents of the device serializer and its async connection. * * The data structure itself is killed at some time later * \param devser the device serializer */ -void DevKill(DevSer *devser); +void DevKill(DevSer * devser); /** \brief Disconnect * \param devser The device serializer to disconnect */ -void DevDisconnect(DevSer *devser); +void DevDisconnect(DevSer * devser); /** \brief Queue an action * @@ -74,9 +75,9 @@ void DevDisconnect(DevSer *devser); * \return 0 when not queued because a similar action is already on the queue, * 1 on success. */ -int DevQueue(DevSer *devser, void *actionData, DevPrio prio, - DevActionHandler hdl, DevActionMatch *matchFunc, - DevKillActionData *killFunc) ; +int DevQueue(DevSer * devser, void *actionData, DevPrio prio, + DevActionHandler hdl, DevActionMatch * matchFunc, + DevKillActionData * killFunc); /** \brief Schedule a periodic action * @@ -92,10 +93,10 @@ int DevQueue(DevSer *devser, void *actionData, DevPrio prio, * from DevUnschedule) or NULL if no kill function is needed. * \return 0 when this was a new action, > 0 when an action was overwritten */ -int DevSchedule(DevSer *devser, void *actionData, - DevPrio prio, double interval, - DevActionHandler hdl, DevActionMatch *matchFunc, - DevKillActionData *killFunc); +int DevSchedule(DevSer * devser, void *actionData, + DevPrio prio, double interval, + DevActionHandler hdl, DevActionMatch * matchFunc, + DevKillActionData * killFunc); /** \brief Unschedule matching actions * \param devser the device serializer @@ -104,14 +105,14 @@ int DevSchedule(DevSer *devser, void *actionData, * \param matchFunc the match function (callData does not need to have the same type as actionData) * \return the number of unscheduled actions */ -int DevUnschedule(DevSer *devser, void *actionData, - DevActionHandler hdl, DevActionMatch *matchFunc); +int DevUnschedule(DevSer * devser, void *actionData, + DevActionHandler hdl, DevActionMatch * matchFunc); /** \brief remove action from the serializer * \param devser the device serializer * \param actionData the action data to be compared for a match */ -int DevRemoveAction(DevSer *devser, void *actionData); +int DevRemoveAction(DevSer * devser, void *actionData); /** \brief Convert integer priority to text * \param prio diff --git a/dict.c b/dict.c index d850c288..86da6170 100644 --- a/dict.c +++ b/dict.c @@ -19,63 +19,61 @@ #include "napi.h" #include "nxdict.h" - int main(int argc, char *argv[]) - { - NXdict pDict = NULL; - NXhandle hfil; - void *pData = NULL; - float fTina[3] = { 0.123, 0.234, 0.456}; - float fTest[3], fDelta; - float fTust[20*20]; - char pBuffer[132]; - int i; +int main(int argc, char *argv[]) +{ + NXdict pDict = NULL; + NXhandle hfil; + void *pData = NULL; + float fTina[3] = { 0.123, 0.234, 0.456 }; + float fTest[3], fDelta; + float fTust[20 * 20]; + char pBuffer[132]; + int i; - /* test nxdict */ - NXDinitfromfile("test.dict",&pDict); - NXopen("test.hdf",NXACC_CREATE,&hfil); - NXDadd(pDict,"Gundula", - "/entry1,NXentry/SphereOmeter,NXinstrument/SDS"); - NXDupdate(pDict,"Bea","/entry1,NXentry/SDS"); - NXDget(pDict,"Bea",pBuffer,131); - printf("Bea = %s\n",pBuffer); - NXDget(pDict,"Linda",pBuffer,131); - NXDopendef(hfil,pDict,pBuffer); - NXDputalias(hfil,pDict,"Tina",fTina); - NXDputalias(hfil,pDict,"Gina",fTina); - NXDgetalias(hfil,pDict,"Tina",fTest); - NXDgetalias(hfil,pDict,"Gina",fTest); - NXDputalias(hfil,pDict,"Linda",fTust); - NXDaliaslink(hfil,pDict,"Eva","Linda"); - NXDclose(pDict,"close.dict"); - NXclose(&hfil); - printf("NXDICT seemed to have worked \n"); + /* test nxdict */ + NXDinitfromfile("test.dict", &pDict); + NXopen("test.hdf", NXACC_CREATE, &hfil); + NXDadd(pDict, "Gundula", + "/entry1,NXentry/SphereOmeter,NXinstrument/SDS"); + NXDupdate(pDict, "Bea", "/entry1,NXentry/SDS"); + NXDget(pDict, "Bea", pBuffer, 131); + printf("Bea = %s\n", pBuffer); + NXDget(pDict, "Linda", pBuffer, 131); + NXDopendef(hfil, pDict, pBuffer); + NXDputalias(hfil, pDict, "Tina", fTina); + NXDputalias(hfil, pDict, "Gina", fTina); + NXDgetalias(hfil, pDict, "Tina", fTest); + NXDgetalias(hfil, pDict, "Gina", fTest); + NXDputalias(hfil, pDict, "Linda", fTust); + NXDaliaslink(hfil, pDict, "Eva", "Linda"); + NXDclose(pDict, "close.dict"); + NXclose(&hfil); + printf("NXDICT seemed to have worked \n"); - /* test Utility functions */ - printf(" Proceeding to test of utility functions \n"); - NXopen("test2.hdf",NXACC_CREATE,&hfil); - NXUwriteglobals(hfil, - "test2.hdf", - "Willibald Wuergehals", - "Rue des Martyrs, 26505 Timbuktu, Legoland ", - "+41-56-3102512", - "Nobody@nowhere.edu", - " 755-898767", - "Dingsbums"); - NXUentergroup(hfil, "TestGroup", "NXtest"); - NXclosegroup(hfil); - NXUentergroup(hfil, "TestGroup", "NXtest"); + /* test Utility functions */ + printf(" Proceeding to test of utility functions \n"); + NXopen("test2.hdf", NXACC_CREATE, &hfil); + NXUwriteglobals(hfil, + "test2.hdf", + "Willibald Wuergehals", + "Rue des Martyrs, 26505 Timbuktu, Legoland ", + "+41-56-3102512", + "Nobody@nowhere.edu", " 755-898767", "Dingsbums"); + NXUentergroup(hfil, "TestGroup", "NXtest"); + NXclosegroup(hfil); + NXUentergroup(hfil, "TestGroup", "NXtest"); - i = 120; - NXUenterdata(hfil,"TestData",DFNT_INT8, 1,&i,"Testis"); - NXclosedata(hfil); - NXUenterdata(hfil,"TestData",DFNT_INT8, 1,&i,"Testis"); + i = 120; + NXUenterdata(hfil, "TestData", DFNT_INT8, 1, &i, "Testis"); + NXclosedata(hfil); + NXUenterdata(hfil, "TestData", DFNT_INT8, 1, &i, "Testis"); - NXUallocSDS(hfil,&pData); - NXUfreeSDS(&pData); - NXclose(&hfil); - printf("All tests seem to have worked OK, %s %s\n", - "but the test is pathetic\n", - "Do not rely, in any circumstances, on this test alone"); + NXUallocSDS(hfil, &pData); + NXUfreeSDS(&pData); + NXclose(&hfil); + printf("All tests seem to have worked OK, %s %s\n", + "but the test is pathetic\n", + "Do not rely, in any circumstances, on this test alone"); - - } + +} diff --git a/diffscan.c b/diffscan.c index 0d568401..b9b24f8b 100644 --- a/diffscan.c +++ b/diffscan.c @@ -19,133 +19,138 @@ #define SKIP 1 /*-------------------------------------------------------------------*/ -static void KillDiffScan(void *data){ - pDiffScan self = (pDiffScan)data; - - if(self == NULL){ +static void KillDiffScan(void *data) +{ + pDiffScan self = (pDiffScan) data; + + if (self == NULL) { return; } - - if(self->pDes != NULL){ + + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); } - if(self->parArray != NULL){ + if (self->parArray != NULL) { ObParDelete(self->parArray); } free(self); } + /*---------------------------------------------------------------------*/ -static int SaveDiffScan(void *data, char *name, FILE *fd){ - pDiffScan self = (pDiffScan)data; - if(self == NULL){ +static int SaveDiffScan(void *data, char *name, FILE * fd) +{ + pDiffScan self = (pDiffScan) data; + if (self == NULL) { return 0; } - fprintf(fd,"%s monitor %f\n",name,ObVal(self->parArray,DIFFMONITOR)); - fprintf(fd,"%s skip %f\n",name,ObVal(self->parArray,SKIP)); + fprintf(fd, "%s monitor %f\n", name, ObVal(self->parArray, DIFFMONITOR)); + fprintf(fd, "%s skip %f\n", name, ObVal(self->parArray, SKIP)); return 1; } + /*----------------------------------------------------------------------*/ -int MakeDiffScan(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int MakeDiffScan(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pDiffScan pNew = NULL; int status; - pNew = (pDiffScan)malloc(sizeof(DiffScan)); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating differential scan", - eError); + pNew = (pDiffScan) malloc(sizeof(DiffScan)); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating differential scan", + eError); return 0; } - memset(pNew,0,sizeof(DiffScan)); + memset(pNew, 0, sizeof(DiffScan)); pNew->pDes = CreateDescriptor("DiffScan"); pNew->parArray = ObParCreate(2); - if(!pNew->pDes || !pNew->parArray){ - SCWrite(pCon,"ERROR: out of memory creating differential scan", - eError); + if (!pNew->pDes || !pNew->parArray) { + SCWrite(pCon, "ERROR: out of memory creating differential scan", + eError); KillDiffScan(pNew); return 0; - } - ObParInit(pNew->parArray, DIFFMONITOR,"monitor",4.0,usUser); - ObParInit(pNew->parArray, SKIP,"skip",.0,usUser); + } + ObParInit(pNew->parArray, DIFFMONITOR, "monitor", 4.0, usUser); + ObParInit(pNew->parArray, SKIP, "skip", .0, usUser); pNew->pDes->SaveStatus = SaveDiffScan; - if(argc > 1) { - status = AddCommand(pSics,argv[1], - DiffScanWrapper, - KillDiffScan, - pNew); - + if (argc > 1) { + status = AddCommand(pSics, argv[1], + DiffScanWrapper, KillDiffScan, pNew); + } else { - status = AddCommand(pSics,"diffscan", - DiffScanWrapper, - KillDiffScan, - pNew); - + status = AddCommand(pSics, "diffscan", + DiffScanWrapper, KillDiffScan, pNew); + } - if(status != 1){ - SCWrite(pCon,"ERROR: duplicate diffscan not created",eError); + if (status != 1) { + SCWrite(pCon, "ERROR: duplicate diffscan not created", eError); return 0; } return 1; } + /*----------------------------------------------------------------------*/ -int DiffScanWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int DiffScanWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pDiffScan self = NULL; pScanData pScan = NULL; ObPar *par = NULL; char pBueffel[255]; int status; - self = (pDiffScan)pData; + self = (pDiffScan) pData; assert(self); - if(argc < 2){ - SCWrite(pCon,"ERROR: need arguments to diffscan",eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: need arguments to diffscan", eError); return 0; } - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } /* - first try to find a scan object and to run - */ + first try to find a scan object and to run + */ strtolower(argv[1]); - pScan = (pScanData)FindCommandData(pSics,argv[1],"ScanObject"); - if(pScan != NULL && argc > 2){ - status = RunDiffScan(self,pScan,pCon, atof(argv[2])); + pScan = (pScanData) FindCommandData(pSics, argv[1], "ScanObject"); + if (pScan != NULL && argc > 2) { + status = RunDiffScan(self, pScan, pCon, atof(argv[2])); return status; } /* - if we end here we are treating variables - */ - if(argc > 2){ + if we end here we are treating variables + */ + if (argc > 2) { /* - set case - */ - return ObParSet(self->parArray,argv[0],argv[1],atof(argv[2]),pCon); + set case + */ + return ObParSet(self->parArray, argv[0], argv[1], atof(argv[2]), pCon); } else { /* - get case - */ - par = ObParFind(self->parArray,argv[1]); - if(par != NULL){ - snprintf(pBueffel,255,"%s.%s = %f",argv[0],argv[1],par->fVal); - SCWrite(pCon,pBueffel,eValue); + get case + */ + par = ObParFind(self->parArray, argv[1]); + if (par != NULL) { + snprintf(pBueffel, 255, "%s.%s = %f", argv[0], argv[1], par->fVal); + SCWrite(pCon, pBueffel, eValue); return 1; } else { - snprintf(pBueffel,255,"ERROR: parameter %s not found",argv[1]); - SCWrite(pCon,pBueffel,eError); + snprintf(pBueffel, 255, "ERROR: parameter %s not found", argv[1]); + SCWrite(pCon, pBueffel, eError); return 0; } } return 1; } + /*--------------------------------------------------------------------*/ -static int StartDiffScan(pDiffScan self, pScanData pScan, - SConnection *pCon, float fEnd){ +static int StartDiffScan(pDiffScan self, pScanData pScan, + SConnection * pCon, float fEnd) +{ pVarEntry pVar = NULL; void *pPtr = NULL; pCounter pCount = NULL; @@ -153,103 +158,110 @@ static int StartDiffScan(pDiffScan self, pScanData pScan, int status; /* - error checks - */ - if(pScan->iScanVar < 1) { - SCWrite(pCon,"ERROR: no scan variable to diffscan",eError); + error checks + */ + if (pScan->iScanVar < 1) { + SCWrite(pCon, "ERROR: no scan variable to diffscan", eError); return 0; } - if(pScan->iScanVar > 1) { - snprintf(pBueffel,255, - "WARNING: diffscan handles only first scan variable, %d %s", - pScan->iScanVar - 1, - "scan variables ignored"); - SCWrite(pCon,pBueffel, eWarning); + if (pScan->iScanVar > 1) { + snprintf(pBueffel, 255, + "WARNING: diffscan handles only first scan variable, %d %s", + pScan->iScanVar - 1, "scan variables ignored"); + SCWrite(pCon, pBueffel, eWarning); } /* - initialize data structure - */ + initialize data structure + */ self->scanObject = pScan; self->scanObject->pCon = pCon; - self->skip = (int)ObVal(self->parArray,SKIP); - self->scaleMonitor = (int)ObVal(self->parArray,DIFFMONITOR); + self->skip = (int) ObVal(self->parArray, SKIP); + self->scaleMonitor = (int) ObVal(self->parArray, DIFFMONITOR); self->normalizationScale = -1; pScan->iCounts = 0; - + /* - get variable - */ - DynarGet(pScan->pScanVar,0,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar == NULL){ - SCWrite(pCon,"ERROR: cannot access scan variable",eError); - return 0; - } - - /* - drive to start position - */ - status = Drive(pCon,pServ->pSics,ScanVarName(pVar),ScanVarStart(pVar)); - if(status != 1){ + get variable + */ + DynarGet(pScan->pScanVar, 0, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar == NULL) { + SCWrite(pCon, "ERROR: cannot access scan variable", eError); return 0; } /* - Configure counter. We operate in timer mode with a very long - preset mode. Stopping is done explicitly in the diffscan task - */ - SetCounterMode(pScan->pCounterData,eTimer); - SetCounterPreset(pScan->pCounterData,3600.); + drive to start position + */ + status = + Drive(pCon, pServ->pSics, ScanVarName(pVar), ScanVarStart(pVar)); + if (status != 1) { + return 0; + } /* - start motor and counter - */ - status = pVar->pInter->SetValue(pVar->pObject,pCon,fEnd); - if(status != OKOK){ + Configure counter. We operate in timer mode with a very long + preset mode. Stopping is done explicitly in the diffscan task + */ + SetCounterMode(pScan->pCounterData, eTimer); + SetCounterPreset(pScan->pCounterData, 3600.); + + /* + start motor and counter + */ + status = pVar->pInter->SetValue(pVar->pObject, pCon, fEnd); + if (status != OKOK) { /* - errors will already have been reported in SetValue - */ + errors will already have been reported in SetValue + */ return 0; } - pCount = (pCounter)pScan->pCounterData; + pCount = (pCounter) pScan->pCounterData; assert(pCount); - status = pCount->pCountInt->StartCount(pCount,pCon); - if(status != OKOK){ + status = pCount->pCountInt->StartCount(pCount, pCon); + if (status != OKOK) { return 0; } return 1; } + /*--------------------------------------------------------------------*/ -static float normalizeEntry(pCountEntry pCount, pCountEntry last, - long monValue, int scaleMon){ +static float normalizeEntry(pCountEntry pCount, pCountEntry last, + long monValue, int scaleMon) +{ int i; float fScale; float value; long diff; /* - calculate scale - */ - diff = pCount->Monitors[scaleMon-1] - last->Monitors[scaleMon-1]; - if(diff > 0) { - fScale = (float)monValue/(float)diff; + calculate scale + */ + diff = pCount->Monitors[scaleMon - 1] - last->Monitors[scaleMon - 1]; + if (diff > 0) { + fScale = (float) monValue / (float) diff; } else { fScale = 0.; } - value = ((float)(pCount->lCount - last->lCount))*fScale; - pCount->lCount = (long)value; - for(i = 0; i < 10; i++){ - pCount->Monitors[i] = (pCount->Monitors[i] - last->Monitors[i])*fScale; + value = ((float) (pCount->lCount - last->lCount)) * fScale; + pCount->lCount = (long) value; + for (i = 0; i < 10; i++) { + pCount->Monitors[i] = + (pCount->Monitors[i] - last->Monitors[i]) * fScale; } return value; } + /*--------------------------------------------------------------------*/ -static void copyCountData(pCountEntry last, pCountEntry pCount){ - memcpy(last,pCount,sizeof(CountEntry)); +static void copyCountData(pCountEntry last, pCountEntry pCount) +{ + memcpy(last, pCount, sizeof(CountEntry)); } + /*---------------------------------------------------------------------*/ -static int DiffScanTask(void *pData){ +static int DiffScanTask(void *pData) +{ pCounter pCount = NULL; pCountEntry data; pVarEntry pVar = NULL; @@ -260,13 +272,13 @@ static int DiffScanTask(void *pData){ long rawCount, rawMon; CountEntry rawCopy; - pDiffScan self = (pDiffScan)pData; + pDiffScan self = (pDiffScan) pData; /* - manage skip - */ - if(self->skip > 0){ - if(self->skipCount > self->skip){ + manage skip + */ + if (self->skip > 0) { + if (self->skipCount > self->skip) { self->skipCount = 0; } else { self->skipCount++; @@ -275,67 +287,67 @@ static int DiffScanTask(void *pData){ } /* - read motor status - */ - DynarGet(self->scanObject->pScanVar,0,&pPtr); - pVar = (pVarEntry)pPtr; - status = pVar->pInter->CheckStatus(pVar->pObject,self->scanObject->pCon); - if(status != HWBusy) { + read motor status + */ + DynarGet(self->scanObject->pScanVar, 0, &pPtr); + pVar = (pVarEntry) pPtr; + status = + pVar->pInter->CheckStatus(pVar->pObject, self->scanObject->pCon); + if (status != HWBusy) { finish = 0; } /* - read values - */ - status = GetDrivablePosition(pVar->pObject,self->scanObject->pCon, - &fPos); - if(status == 0){ + read values + */ + status = GetDrivablePosition(pVar->pObject, self->scanObject->pCon, + &fPos); + if (status == 0) { return finish; } - AppendScanVar(pVar,fPos); - pCount = (pCounter)self->scanObject->pCounterData; - pCount->pCountInt->TransferData(pCount,self->scanObject->pCon); + AppendScanVar(pVar, fPos); + pCount = (pCounter) self->scanObject->pCounterData; + pCount->pCountInt->TransferData(pCount, self->scanObject->pCon); CollectCounterData(self->scanObject); /* - normalize (or not) - */ - DynarGet(self->scanObject->pCounts,self->scanObject->iCounts-1,&pPtr); - data = (pCountEntry)pPtr; - copyCountData(&rawCopy,data); - if(self->normalizationScale < 0){ - countValue = (float)data->lCount; + normalize (or not) + */ + DynarGet(self->scanObject->pCounts, self->scanObject->iCounts - 1, + &pPtr); + data = (pCountEntry) pPtr; + copyCountData(&rawCopy, data); + if (self->normalizationScale < 0) { + countValue = (float) data->lCount; rawCount = data->lCount; - rawMon = data->Monitors[self->scaleMonitor-1]; - self->normalizationScale = data->Monitors[self->scaleMonitor-1]; + rawMon = data->Monitors[self->scaleMonitor - 1]; + self->normalizationScale = data->Monitors[self->scaleMonitor - 1]; } else { - if(data->Monitors[self->scaleMonitor -1] - - self->last.Monitors[self->scaleMonitor-1] < 5) { - SCWrite(self->scanObject->pCon, - "WARNING: low count rate",eLog); + if (data->Monitors[self->scaleMonitor - 1] - + self->last.Monitors[self->scaleMonitor - 1] < 5) { + SCWrite(self->scanObject->pCon, "WARNING: low count rate", eLog); } rawCount = data->lCount; - rawMon = data->Monitors[self->scaleMonitor-1]; - countValue = normalizeEntry(data,&self->last, - self->normalizationScale, - self->scaleMonitor); + rawMon = data->Monitors[self->scaleMonitor - 1]; + countValue = normalizeEntry(data, &self->last, + self->normalizationScale, + self->scaleMonitor); } - copyCountData(&self->last,&rawCopy); + copyCountData(&self->last, &rawCopy); /* - print progress - */ - snprintf(pBueffel,255,"%5d %12.4f %12.4f RAW: %10ld %10ld", - self->scanObject->iCounts -1, - fPos, countValue, rawCount, - rawMon); - SCWrite(self->scanObject->pCon,pBueffel,eLog); - InvokeCallBack(self->scanObject->pCall,SCANPOINT,self->scanObject); + print progress + */ + snprintf(pBueffel, 255, "%5d %12.4f %12.4f RAW: %10ld %10ld", + self->scanObject->iCounts - 1, + fPos, countValue, rawCount, rawMon); + SCWrite(self->scanObject->pCon, pBueffel, eLog); + InvokeCallBack(self->scanObject->pCall, SCANPOINT, self->scanObject); /* - check for interrupt - */ - if(SCGetInterrupt(self->scanObject->pCon) >= eAbortScan){ + check for interrupt + */ + if (SCGetInterrupt(self->scanObject->pCon) >= eAbortScan) { pCount->pCountInt->Halt(pCount); pVar->pInter->Halt(pVar->pObject); SicsWait(1); @@ -344,25 +356,27 @@ static int DiffScanTask(void *pData){ return finish; } + /*----------------------------------------------------------------------*/ -int RunDiffScan(pDiffScan self, pScanData pScan, - SConnection *pCon, float fEnd){ +int RunDiffScan(pDiffScan self, pScanData pScan, + SConnection * pCon, float fEnd) +{ long lID; pCounter pCount = NULL; - - if(StartDiffScan(self,pScan,pCon,fEnd) != 1) { + + if (StartDiffScan(self, pScan, pCon, fEnd) != 1) { return 0; } - InvokeCallBack(self->scanObject->pCall,SCANSTART,self->scanObject); + InvokeCallBack(self->scanObject->pCall, SCANSTART, self->scanObject); - - lID = TaskRegister(pServ->pTasker,DiffScanTask,NULL,NULL,self,10); - TaskWait(pServ->pTasker,lID); - - pCount = (pCounter)self->scanObject->pCounterData; + lID = TaskRegister(pServ->pTasker, DiffScanTask, NULL, NULL, self, 10); + TaskWait(pServ->pTasker, lID); + + + pCount = (pCounter) self->scanObject->pCounterData; pCount->pCountInt->Halt(pCount); - InvokeCallBack(self->scanObject->pCall,SCANEND,self->scanObject); - + InvokeCallBack(self->scanObject->pCall, SCANEND, self->scanObject); + return 1; } diff --git a/diffscan.h b/diffscan.h index 17fa5e4f..75adce42 100644 --- a/diffscan.h +++ b/diffscan.h @@ -14,16 +14,16 @@ #include "scan.i" typedef struct { - pObjectDescriptor pDes; - ObPar *parArray; - int normalizationScale; - int scaleMonitor; - CountEntry last; - int skip; - int skipCount; - pScanData scanObject; - } DiffScan, *pDiffScan; - + pObjectDescriptor pDes; + ObPar *parArray; + int normalizationScale; + int scaleMonitor; + CountEntry last; + int skip; + int skipCount; + pScanData scanObject; +} DiffScan, *pDiffScan; + /*==================================================================*/ /** @@ -34,14 +34,14 @@ typedef struct { * @param pCon The connection to use for output and errors. * @param fEnd The end value for the diffscan */ - int RunDiffScan(pDiffScan self, pScanData pScan, - SConnection *pCon, float fEnd); +int RunDiffScan(pDiffScan self, pScanData pScan, + SConnection * pCon, float fEnd); /*==================== interpreter wrappers ==========================*/ - int DiffScanWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int MakeDiffScan(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int DiffScanWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int MakeDiffScan(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + - #endif diff --git a/difrac.c b/difrac.c index 4f09755a..8b3213fd 100644 --- a/difrac.c +++ b/difrac.c @@ -31,8 +31,8 @@ ---------------------------------------------------------------------------*/ #define MAXSTACK 50 - static SConnection *ConStack[MAXSTACK]; - static int iConStackPtr = -1; +static SConnection *ConStack[MAXSTACK]; +static int iConStackPtr = -1; /*-------------------------------------------------------------------------- In order to do the four circle work we need to know the motors of the @@ -41,358 +41,322 @@ These data structures are initialized by the installation routine. ---------------------------------------------------------------------------*/ - static pMotor pTTH, pOM, pCHI, pPHI; - static pCounter counter; +static pMotor pTTH, pOM, pCHI, pPHI; +static pCounter counter; /*--------------------------------------------------------------------------- The following routines will be called from F77. Their names take care of the system dependent name mangling scheme for calling C from F77. This may need adjustment when porting to another system ---------------------------------------------------------------------------*/ /*========= read angles */ - void sicsanget_(float *fTH, float *fOM, float *fCHI, float *fPHI) - { - int iRet; +void sicsanget_(float *fTH, float *fOM, float *fCHI, float *fPHI) +{ + int iRet; - /* this is just security, may never happen */ - if(iConStackPtr < 0) - { - return; - } - if(ConStack[iConStackPtr] == NULL) - { - return; - } - - iRet = MotorGetSoftPosition(pTTH,ConStack[iConStackPtr],fTH); - if(iRet != 1) - { - SCWrite(ConStack[iConStackPtr], - "ERROR: failed to read two theta, DIFRAC may be confused now", - eError); - } - iRet = MotorGetSoftPosition(pOM,ConStack[iConStackPtr],fOM); - if(iRet != 1) - { - SCWrite(ConStack[iConStackPtr], - "ERROR: failed to read omega, DIFRAC may be confused now", - eError); - } - iRet = MotorGetSoftPosition(pCHI,ConStack[iConStackPtr],fCHI); - if(iRet != 1) - { - SCWrite(ConStack[iConStackPtr], - "ERROR: failed to read chi, DIFRAC may be confused now", - eError); - } - iRet = MotorGetSoftPosition(pPHI,ConStack[iConStackPtr],fPHI); - if(iRet != 1) - { - SCWrite(ConStack[iConStackPtr], - "ERROR: failed to read two theta, DIFRAC may be confused now", - eError); - } + /* this is just security, may never happen */ + if (iConStackPtr < 0) { + return; } -#define ABS(x) (x < 0 ? -(x) : (x)) + if (ConStack[iConStackPtr] == NULL) { + return; + } + + iRet = MotorGetSoftPosition(pTTH, ConStack[iConStackPtr], fTH); + if (iRet != 1) { + SCWrite(ConStack[iConStackPtr], + "ERROR: failed to read two theta, DIFRAC may be confused now", + eError); + } + iRet = MotorGetSoftPosition(pOM, ConStack[iConStackPtr], fOM); + if (iRet != 1) { + SCWrite(ConStack[iConStackPtr], + "ERROR: failed to read omega, DIFRAC may be confused now", + eError); + } + iRet = MotorGetSoftPosition(pCHI, ConStack[iConStackPtr], fCHI); + if (iRet != 1) { + SCWrite(ConStack[iConStackPtr], + "ERROR: failed to read chi, DIFRAC may be confused now", + eError); + } + iRet = MotorGetSoftPosition(pPHI, ConStack[iConStackPtr], fPHI); + if (iRet != 1) { + SCWrite(ConStack[iConStackPtr], + "ERROR: failed to read two theta, DIFRAC may be confused now", + eError); + } +} + +#define ABS(x) (x < 0 ? -(x) : (x)) /*=========== check angles */ - void sicsangcheck_(float *fTH, float *fOM, float *fCHI, float *fPHI, - int *iInvalid) - { - int iRet; - SConnection *pCon = NULL; - float fHard; - char pBueffel[256], pError[131]; +void sicsangcheck_(float *fTH, float *fOM, float *fCHI, float *fPHI, + int *iInvalid) +{ + int iRet; + SConnection *pCon = NULL; + float fHard; + char pBueffel[256], pError[131]; - /* this is just security, may never happen */ - if(iConStackPtr < 0) - { - return; - } - if(ConStack[iConStackPtr] == NULL) - { - return; - } - pCon = ConStack[iConStackPtr]; - - *iInvalid = 0; - iRet = MotorCheckBoundary(pTTH,*fTH,&fHard,pError,131); - if(iRet != 1) - { - sprintf(pBueffel, - "ERROR: %6.2f %6.2f %6.2f %6.2f violates twotheta limits", - *fTH, *fOM, *fCHI, *fPHI); - SCWrite(pCon,pBueffel,eError); - *iInvalid = 4; - return; - } - iRet = MotorCheckBoundary(pOM,*fOM,&fHard,pError,131); - if(iRet != 1) - { - sprintf(pBueffel, - "ERROR: %6.2f %6.2f %6.2f %6.2f violates omega limits", - *fTH, *fOM, *fCHI, *fPHI); - SCWrite(pCon,pBueffel,eError); - *iInvalid = 4; - return; - } - iRet = MotorCheckBoundary(pCHI,*fCHI,&fHard,pError,131); - if(iRet != 1) - { - sprintf(pBueffel, - "ERROR: %6.2f %6.2f %6.2f %6.2f violates chi limits", - *fTH, *fOM, *fCHI, *fPHI); - SCWrite(pCon,pBueffel,eError); - *iInvalid = 4; - return; - } - iRet = MotorCheckBoundary(pPHI,*fPHI,&fHard,pError,131); - if(iRet != 1) - { - sprintf(pBueffel, - "ERROR: %6.2f %6.2f %6.2f %6.2f violates phi limits", - *fTH, *fOM, *fCHI, *fPHI); - SCWrite(pCon,pBueffel,eError); - *iInvalid = 4; - return; - } + /* this is just security, may never happen */ + if (iConStackPtr < 0) { + return; } + if (ConStack[iConStackPtr] == NULL) { + return; + } + pCon = ConStack[iConStackPtr]; + + *iInvalid = 0; + iRet = MotorCheckBoundary(pTTH, *fTH, &fHard, pError, 131); + if (iRet != 1) { + sprintf(pBueffel, + "ERROR: %6.2f %6.2f %6.2f %6.2f violates twotheta limits", + *fTH, *fOM, *fCHI, *fPHI); + SCWrite(pCon, pBueffel, eError); + *iInvalid = 4; + return; + } + iRet = MotorCheckBoundary(pOM, *fOM, &fHard, pError, 131); + if (iRet != 1) { + sprintf(pBueffel, + "ERROR: %6.2f %6.2f %6.2f %6.2f violates omega limits", + *fTH, *fOM, *fCHI, *fPHI); + SCWrite(pCon, pBueffel, eError); + *iInvalid = 4; + return; + } + iRet = MotorCheckBoundary(pCHI, *fCHI, &fHard, pError, 131); + if (iRet != 1) { + sprintf(pBueffel, + "ERROR: %6.2f %6.2f %6.2f %6.2f violates chi limits", + *fTH, *fOM, *fCHI, *fPHI); + SCWrite(pCon, pBueffel, eError); + *iInvalid = 4; + return; + } + iRet = MotorCheckBoundary(pPHI, *fPHI, &fHard, pError, 131); + if (iRet != 1) { + sprintf(pBueffel, + "ERROR: %6.2f %6.2f %6.2f %6.2f violates phi limits", + *fTH, *fOM, *fCHI, *fPHI); + SCWrite(pCon, pBueffel, eError); + *iInvalid = 4; + return; + } +} + /*======== set angles */ - void sicsangset_(float *fTTH, float *fOM, float *fCHI, float *fPHI, - int *icol) - { - pDummy pDum; - int iRet; - SConnection *pCon = NULL; - float fT1, fT2, fT3, fT4; +void sicsangset_(float *fTTH, float *fOM, float *fCHI, float *fPHI, + int *icol) +{ + pDummy pDum; + int iRet; + SConnection *pCon = NULL; + float fT1, fT2, fT3, fT4; - *icol = 0; + *icol = 0; - /* this is just security, may never happen */ - if(iConStackPtr < 0) - { - return; - } - if(ConStack[iConStackPtr] == NULL) - { - return; - } - pCon = ConStack[iConStackPtr]; - - - /* check if this is possible, if not complain */ - sicsangcheck_(fTTH, fOM,fCHI,fPHI, &iRet); - if(iRet >= 4) - { - *icol = 1; - return; - } - - /* start */ - pDum = (pDummy)pTTH; - iRet = StartDevice(pServ->pExecutor, "TTH", - pDum->pDescriptor, pDum,pCon, *fTTH); - if(!iRet) - { - SCWrite(pCon,"ERROR: cannot start two theta motor",eError); - StopExe(pServ->pExecutor,"all"); - *icol = 10; - } - pDum = (pDummy)pOM; - iRet = StartDevice(pServ->pExecutor, "OM", - pDum->pDescriptor, pDum,pCon, *fOM); - if(!iRet) - { - SCWrite(pCon,"ERROR: cannot start omega motor",eError); - StopExe(pServ->pExecutor,"all"); - *icol = 10; - } - pDum = (pDummy)pCHI; - iRet = StartDevice(pServ->pExecutor, "CHI", - pDum->pDescriptor, pDum,pCon, *fCHI); - if(!iRet) - { - SCWrite(pCon,"ERROR: cannot start chi motor",eError); - StopExe(pServ->pExecutor,"all"); - *icol = 10; - } - pDum = (pDummy)pPHI; - iRet = StartDevice(pServ->pExecutor, "PHI", - pDum->pDescriptor, pDum,pCon, *fPHI); - if(!iRet) - { - SCWrite(pCon,"ERROR: cannot start two theta motor",eError); - StopExe(pServ->pExecutor,"all"); - *icol = 10; - } - - /* wait for end of it */ - iRet = Wait4Success(pServ->pExecutor); - switch(iRet) - { - case DEVINT: - if(SCGetInterrupt(pCon) == eAbortOperation) - { - SCSetInterrupt(pCon,eContinue); - SCSetError(pCon,OKOK); - } - break; - case DEVDONE: - break; - default: - break; - } - - /* - As TRICS has such a shitty cradle check angles and report error - if bad - */ - sicsanget_(&fT1, &fT2, &fT3, &fT4); - if(ABS(fT1 - *fTTH) > .2) - { - *icol = 10; - } - if(ABS(fT2 - *fOM) > .2) - { - *icol = 10; - } - if(ABS(fT3 - *fCHI) > .2) - { - *icol = 10; - } - if(ABS(fT4 - *fPHI) > .2) - { - *icol = 10; - } + /* this is just security, may never happen */ + if (iConStackPtr < 0) { + return; } + if (ConStack[iConStackPtr] == NULL) { + return; + } + pCon = ConStack[iConStackPtr]; + + + /* check if this is possible, if not complain */ + sicsangcheck_(fTTH, fOM, fCHI, fPHI, &iRet); + if (iRet >= 4) { + *icol = 1; + return; + } + + /* start */ + pDum = (pDummy) pTTH; + iRet = StartDevice(pServ->pExecutor, "TTH", + pDum->pDescriptor, pDum, pCon, *fTTH); + if (!iRet) { + SCWrite(pCon, "ERROR: cannot start two theta motor", eError); + StopExe(pServ->pExecutor, "all"); + *icol = 10; + } + pDum = (pDummy) pOM; + iRet = StartDevice(pServ->pExecutor, "OM", + pDum->pDescriptor, pDum, pCon, *fOM); + if (!iRet) { + SCWrite(pCon, "ERROR: cannot start omega motor", eError); + StopExe(pServ->pExecutor, "all"); + *icol = 10; + } + pDum = (pDummy) pCHI; + iRet = StartDevice(pServ->pExecutor, "CHI", + pDum->pDescriptor, pDum, pCon, *fCHI); + if (!iRet) { + SCWrite(pCon, "ERROR: cannot start chi motor", eError); + StopExe(pServ->pExecutor, "all"); + *icol = 10; + } + pDum = (pDummy) pPHI; + iRet = StartDevice(pServ->pExecutor, "PHI", + pDum->pDescriptor, pDum, pCon, *fPHI); + if (!iRet) { + SCWrite(pCon, "ERROR: cannot start two theta motor", eError); + StopExe(pServ->pExecutor, "all"); + *icol = 10; + } + + /* wait for end of it */ + iRet = Wait4Success(pServ->pExecutor); + switch (iRet) { + case DEVINT: + if (SCGetInterrupt(pCon) == eAbortOperation) { + SCSetInterrupt(pCon, eContinue); + SCSetError(pCon, OKOK); + } + break; + case DEVDONE: + break; + default: + break; + } + + /* + As TRICS has such a shitty cradle check angles and report error + if bad + */ + sicsanget_(&fT1, &fT2, &fT3, &fT4); + if (ABS(fT1 - *fTTH) > .2) { + *icol = 10; + } + if (ABS(fT2 - *fOM) > .2) { + *icol = 10; + } + if (ABS(fT3 - *fCHI) > .2) { + *icol = 10; + } + if (ABS(fT4 - *fPHI) > .2) { + *icol = 10; + } +} + /*=========== count */ - void sicscount_(float *fPreset, float *fCounts) - { - pDummy pDum; - int iRet; - SConnection *pCon = NULL; - long lTask; +void sicscount_(float *fPreset, float *fCounts) +{ + pDummy pDum; + int iRet; + SConnection *pCon = NULL; + long lTask; - /* this is just security, may never happen */ - if(iConStackPtr < 0) - { - return; - } - if(ConStack[iConStackPtr] == NULL) - { - return; - } - pCon = ConStack[iConStackPtr]; - - pDum = (pDummy)counter; - SetCounterPreset(counter,*fPreset); - iRet = StartDevice(pServ->pExecutor, - "DifracCount", - pDum->pDescriptor, - counter, - pCon, - *fPreset); - if(!iRet) - { - SCWrite(pCon,"ERROR: Failed to start counting ",eError); - return; - } - SetStatus(eCounting); - /* wait for finish */ - lTask = GetDevexecID(pServ->pExecutor); - if(lTask > 0); - { - TaskWait(pServ->pTasker,lTask); - } - *fCounts = (float)GetCounts(counter,pCon); + /* this is just security, may never happen */ + if (iConStackPtr < 0) { + return; } + if (ConStack[iConStackPtr] == NULL) { + return; + } + pCon = ConStack[iConStackPtr]; + + pDum = (pDummy) counter; + SetCounterPreset(counter, *fPreset); + iRet = StartDevice(pServ->pExecutor, + "DifracCount", + pDum->pDescriptor, counter, pCon, *fPreset); + if (!iRet) { + SCWrite(pCon, "ERROR: Failed to start counting ", eError); + return; + } + SetStatus(eCounting); + /* wait for finish */ + lTask = GetDevexecID(pServ->pExecutor); + if (lTask > 0); + { + TaskWait(pServ->pTasker, lTask); + } + *fCounts = (float) GetCounts(counter, pCon); +} + /*========= sicswrite */ - void sicswrite_(int *iText, int *iLen) - { - SConnection *pCon = NULL; - char pBueffel[256]; - int i; +void sicswrite_(int *iText, int *iLen) +{ + SConnection *pCon = NULL; + char pBueffel[256]; + int i; - if(*iLen > 255) - return; + if (*iLen > 255) + return; - for(i = 0; i < *iLen; i++) - { - pBueffel[i] = (char)iText[i]; - } - pBueffel[i] = '\0'; - - /* this is just security, may never happen */ - if(iConStackPtr < 0) - { - puts(pBueffel); - return; - } - if(ConStack[iConStackPtr] == NULL) - { - puts(pBueffel); - return; - } - pCon = ConStack[iConStackPtr]; - - SCWrite(pCon,pBueffel,eValue); + for (i = 0; i < *iLen; i++) { + pBueffel[i] = (char) iText[i]; } + pBueffel[i] = '\0'; + + /* this is just security, may never happen */ + if (iConStackPtr < 0) { + puts(pBueffel); + return; + } + if (ConStack[iConStackPtr] == NULL) { + puts(pBueffel); + return; + } + pCon = ConStack[iConStackPtr]; + + SCWrite(pCon, pBueffel, eValue); +} + /*========== sicsgetline */ - void sicsgetline_(int *iText, int *iLen) - { - SConnection *pCon = NULL; - char pBueffel[256]; - int i, iRet; +void sicsgetline_(int *iText, int *iLen) +{ + SConnection *pCon = NULL; + char pBueffel[256]; + int i, iRet; - /* this is just security, may never happen */ - if(iConStackPtr < 0) - { - return; - } - if(ConStack[iConStackPtr] == NULL) - { - return; - } - pCon = ConStack[iConStackPtr]; - - iRet = SCPrompt(pCon,"Enter data please >>" , pBueffel, 255); - /* difrac cannot handle an interrupted input operation */ - if(iRet == 0) - { - SCSetInterrupt(pCon,eContinue); - } - for(i = 0; i < strlen(pBueffel); i++) - { - iText[i] = (int)pBueffel[i]; - } - *iLen = strlen(pBueffel); + /* this is just security, may never happen */ + if (iConStackPtr < 0) { + return; } + if (ConStack[iConStackPtr] == NULL) { + return; + } + pCon = ConStack[iConStackPtr]; + + iRet = SCPrompt(pCon, "Enter data please >>", pBueffel, 255); + /* difrac cannot handle an interrupted input operation */ + if (iRet == 0) { + SCSetInterrupt(pCon, eContinue); + } + for (i = 0; i < strlen(pBueffel); i++) { + iText[i] = (int) pBueffel[i]; + } + *iLen = strlen(pBueffel); +} + /*============= checkint */ - void checkint_(int *iK) - { - SConnection *pCon = NULL; - char pBueffel[256]; - int i; +void checkint_(int *iK) +{ + SConnection *pCon = NULL; + char pBueffel[256]; + int i; - /* this is just security, may never happen */ - if(iConStackPtr < 0) - { - *iK = 0; - return; - } - if(ConStack[iConStackPtr] == NULL) - { - return; - } - pCon = ConStack[iConStackPtr]; - - if(SCGetInterrupt(pCon) >= eAbortScan) - { - *iK = 0; - } - else - { - *iK = 1; - } + /* this is just security, may never happen */ + if (iConStackPtr < 0) { + *iK = 0; + return; } + if (ConStack[iConStackPtr] == NULL) { + return; + } + pCon = ConStack[iConStackPtr]; + + if (SCGetInterrupt(pCon) >= eAbortScan) { + *iK = 0; + } else { + *iK = 1; + } +} + /*-------------------------------------------------------------------------- DifracAction is the interface routine between the SICS interpreter and the DIFRAC subsystem. What it basically does is: pop the connection onto @@ -402,138 +366,116 @@ -------------------------------------------------------------------------*/ /* some protoypes for things defined in F77 */ - extern void difini_(void); - extern void difint_(int *iText, int *iLen); +extern void difini_(void); +extern void difint_(int *iText, int *iLen); - int DifracAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pInput[256]; - int iInput[256]; - int iLen, i; - - - if(argc < 2) - { - SCWrite(pCon,"ERROR: dif expects at least one argument",eError); - return 0; - } - - /* user privilege required */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - - /* steal: redirect the I/O to me */ - strcpy(pInput,argv[1]); - strtolower(pInput); - if(strcmp(pInput,"steal") == 0) - { - if(iConStackPtr >= 0) - { - ConStack[iConStackPtr] = pCon; - } - SCSendOK(pCon); - return 1; - } - - iConStackPtr++; - ConStack[iConStackPtr] = pCon; - - Arg2Text(argc-1, &argv[1],pInput,255); - iLen = strlen(pInput); - for(i = 0; i < iLen; i++) - { - iInput[i] = toupper((int)pInput[i]); - } - - /* do difrac */ - difint_(iInput, &iLen); - SCWrite(pCon,"Difrac subsystem finished",eWarning); - - iConStackPtr--; - if(SCGetInterrupt(pCon) != eContinue) - { - return 0; - } - else - { - return 1; - } - } -/*-------------------- The initialization routine ----------------------*/ - int MakeDifrac(SConnection *pCon, SicsInterp *pSics, void *pData, +int DifracAction(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]) - { - CommandList *pCom = NULL; - pICountable pCts = NULL; - int iRet; - - if(argc < 6) - { - SCWrite(pCon, - "ERROR: Insufficient number of arguments to MakeDifrac",eError); - return 0; - } - - /* find motors */ - pTTH = FindMotor(pSics,argv[1]); - if(!pTTH) - { - SCWrite(pCon,"ERROR: cannot find two theta motor",eError); - return 0; - } - pOM = FindMotor(pSics,argv[2]); - if(!pOM) - { - SCWrite(pCon,"ERROR: cannot find omega motor",eError); - return 0; - } - pCHI = FindMotor(pSics,argv[3]); - if(!pTTH) - { - SCWrite(pCon,"ERROR: cannot find chi motor",eError); - return 0; - } - pPHI = FindMotor(pSics,argv[4]); - if(!pTTH) - { - SCWrite(pCon,"ERROR: cannot find phi motor",eError); - return 0; - } +{ + char pInput[256]; + int iInput[256]; + int iLen, i; - /* locate counter */ - pCom = FindCommand(pSics,argv[5]); - if(pCom == NULL) - { - SCWrite(pCon,"ERROR: counter not found in MakeDifrac", - eError); - return 0; - } - pCts = GetCountableInterface(pCom->pData); - if(!pCts) - { - SCWrite(pCon,"ERROR: argument to MakeDifrac is no counter", - eError); - return 0; - } - counter = (pCounter)pCom->pData; - /* initialize difrac */ - difini_(); - - /* install command */ - iRet = AddCommand(pSics, - "dif", - DifracAction, - NULL, - NULL); - if(!iRet) - { - SCWrite(pCon,"ERROR: duplicate command dif NOT created", - eError); - } - return iRet; + if (argc < 2) { + SCWrite(pCon, "ERROR: dif expects at least one argument", eError); + return 0; } - + + /* user privilege required */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + + /* steal: redirect the I/O to me */ + strcpy(pInput, argv[1]); + strtolower(pInput); + if (strcmp(pInput, "steal") == 0) { + if (iConStackPtr >= 0) { + ConStack[iConStackPtr] = pCon; + } + SCSendOK(pCon); + return 1; + } + + iConStackPtr++; + ConStack[iConStackPtr] = pCon; + + Arg2Text(argc - 1, &argv[1], pInput, 255); + iLen = strlen(pInput); + for (i = 0; i < iLen; i++) { + iInput[i] = toupper((int) pInput[i]); + } + + /* do difrac */ + difint_(iInput, &iLen); + SCWrite(pCon, "Difrac subsystem finished", eWarning); + + iConStackPtr--; + if (SCGetInterrupt(pCon) != eContinue) { + return 0; + } else { + return 1; + } +} + +/*-------------------- The initialization routine ----------------------*/ +int MakeDifrac(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL; + pICountable pCts = NULL; + int iRet; + + if (argc < 6) { + SCWrite(pCon, + "ERROR: Insufficient number of arguments to MakeDifrac", + eError); + return 0; + } + + /* find motors */ + pTTH = FindMotor(pSics, argv[1]); + if (!pTTH) { + SCWrite(pCon, "ERROR: cannot find two theta motor", eError); + return 0; + } + pOM = FindMotor(pSics, argv[2]); + if (!pOM) { + SCWrite(pCon, "ERROR: cannot find omega motor", eError); + return 0; + } + pCHI = FindMotor(pSics, argv[3]); + if (!pTTH) { + SCWrite(pCon, "ERROR: cannot find chi motor", eError); + return 0; + } + pPHI = FindMotor(pSics, argv[4]); + if (!pTTH) { + SCWrite(pCon, "ERROR: cannot find phi motor", eError); + return 0; + } + + /* locate counter */ + pCom = FindCommand(pSics, argv[5]); + if (pCom == NULL) { + SCWrite(pCon, "ERROR: counter not found in MakeDifrac", eError); + return 0; + } + pCts = GetCountableInterface(pCom->pData); + if (!pCts) { + SCWrite(pCon, "ERROR: argument to MakeDifrac is no counter", eError); + return 0; + } + counter = (pCounter) pCom->pData; + + /* initialize difrac */ + difini_(); + + /* install command */ + iRet = AddCommand(pSics, "dif", DifracAction, NULL, NULL); + if (!iRet) { + SCWrite(pCon, "ERROR: duplicate command dif NOT created", eError); + } + return iRet; +} diff --git a/difrac.h b/difrac.h index b10a62f5..35ef1515 100644 --- a/difrac.h +++ b/difrac.h @@ -9,6 +9,6 @@ #ifndef DIFRAC #define DIFRAC - int MakeDifrac(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeDifrac(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/drive.c b/drive.c index 4d622a3c..6c0d2c6c 100644 --- a/drive.c +++ b/drive.c @@ -42,7 +42,7 @@ #include "fortify.h" #include "sics.h" #include "drive.h" -#include "nserver.h" /* for SicsWait */ +#include "nserver.h" /* for SicsWait */ #include "drive.h" #include "splitter.h" #include "status.h" @@ -50,452 +50,405 @@ #include "motor.h" /*---------------------------------------------------------------------------*/ - int Drive(SConnection *pCon, SicsInterp *pInter, char *name, float fNew) - { - CommandList *pObject = NULL; - pObjectDescriptor pDes = NULL; - pIDrivable pInt = NULL; - Dummy *pDum; - char pBueffel[512]; - int iRet; - float fDelta, fPos; - long lTime; - - assert(pCon); - assert(pInter); - - /* check if user is allowed to drive */ - if(!SCMatchRights(pCon,usUser)) - { - sprintf(pBueffel,"Insuficient Privilege to drive %s", - name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* first try to find the thing to drive */ - pObject = FindCommand(pInter,name); - if(!pObject) - { - sprintf(pBueffel,"Cannot find %s to drive ", name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* get the Descriptor, this RELIES on the descriptor being the first - thing in the struct - */ - pDum = (Dummy *)pObject->pData; - pDes = pDum->pDescriptor; - if(!pDes) - { - sprintf(pBueffel,"%s is NOT drivable!",pDes->name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* both scanable and drivable objects can be driven, check this - and act accordingly - */ +int Drive(SConnection * pCon, SicsInterp * pInter, char *name, float fNew) +{ + CommandList *pObject = NULL; + pObjectDescriptor pDes = NULL; + pIDrivable pInt = NULL; + Dummy *pDum; + char pBueffel[512]; + int iRet; + float fDelta, fPos; + long lTime; - pInt = pDes->GetInterface(pDum,DRIVEID); - if(!pInt) - { - sprintf(pBueffel,"%s is NOT drivable!",pDes->name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(pInt) - { - iRet = pInt->CheckLimits(pDum,fNew,pBueffel,511); - if(!iRet) - { - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,eAbortOperation); - return 0; - } - iRet = StartDevice(GetExecutor(),name,pDes,pDum,pCon,fNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: cannot start device %s",name); - SCWrite(pCon,pBueffel,eError); - return 0; - } + assert(pCon); + assert(pInter); - /* wait for finish */ - iRet = Wait4Success(GetExecutor()); - fPos = pInt->GetValue(pDum,pCon); - if(iRet == DEVINT) - { - if(SCGetInterrupt(pCon) == eAbortOperation) - { - SCSetInterrupt(pCon,eContinue); - sprintf(pBueffel,"Driving %s aborted at %9.3f",name, fPos); - SCWrite(pCon,pBueffel,eError); - } - return 0; - } - else if(iRet == DEVDONE) - { - sprintf(pBueffel,"Driving %s to %9.3f done", name, fPos); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { - sprintf(pBueffel, - "Driving %s finished with problems, position: %9.3f",name,fPos); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - sprintf(pBueffel,"%s is NOT drivable",pDes->name); - SCWrite(pCon,pBueffel,eError); + /* check if user is allowed to drive */ + if (!SCMatchRights(pCon, usUser)) { + sprintf(pBueffel, "Insuficient Privilege to drive %s", name); + SCWrite(pCon, pBueffel, eError); return 0; - } -/*---------------------------------------------------------------------------*/ - int Start2Run(SConnection *pCon, SicsInterp *pInter, char *name, float fNew) - { - CommandList *pObject = NULL; - pObjectDescriptor pDes = NULL; - pIDrivable pInt = NULL; - Dummy *pDum; - char pBueffel[512]; - int iRet; - float fDelta; - long lTime; - - assert(pCon); - assert(pInter); - - /* check if user is allowed to drive */ - if(!SCMatchRights(pCon,usUser)) - { - sprintf(pBueffel,"Insuficient Privilege to drive %s", - name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* first try to find the thing to drive */ - pObject = FindCommand(pInter,name); - if(!pObject) - { - sprintf(pBueffel,"Cannot find %s to drive ", name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* get the Descriptor, this RELIES on the descriptor being the first - thing in the struct - */ - pDum = (Dummy *)pObject->pData; - pDes = pDum->pDescriptor; - if(!pDes) - { - sprintf(pBueffel,"%s is NOT drivable!",pDes->name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* Only drivable objects can be driven, check this - and act accordingly - */ - pInt = pDes->GetInterface(pDum,DRIVEID); - if(!pInt) - { - sprintf(pBueffel,"%s is NOT drivable!",pDes->name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(pInt) - { - iRet = pInt->CheckLimits(pDum,fNew,pBueffel,511); - if(!iRet) - { - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,eAbortOperation); - return 0; - } - iRet = StartDevice(GetExecutor(),name,pDes,pDum,pCon,fNew); - if(!iRet) - { - return 0; - } - else - { - return 1; - } - } - else - { - sprintf(pBueffel,"%s is NOT drivable",pDes->name); - SCWrite(pCon,pBueffel,eError); + } + + /* first try to find the thing to drive */ + pObject = FindCommand(pInter, name); + if (!pObject) { + sprintf(pBueffel, "Cannot find %s to drive ", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* get the Descriptor, this RELIES on the descriptor being the first + thing in the struct + */ + pDum = (Dummy *) pObject->pData; + pDes = pDum->pDescriptor; + if (!pDes) { + sprintf(pBueffel, "%s is NOT drivable!", pDes->name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* both scanable and drivable objects can be driven, check this + and act accordingly + */ + + pInt = pDes->GetInterface(pDum, DRIVEID); + if (!pInt) { + sprintf(pBueffel, "%s is NOT drivable!", pDes->name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (pInt) { + iRet = pInt->CheckLimits(pDum, fNew, pBueffel, 511); + if (!iRet) { + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, eAbortOperation); return 0; - } - } + } + iRet = StartDevice(GetExecutor(), name, pDes, pDum, pCon, fNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: cannot start device %s", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* wait for finish */ + iRet = Wait4Success(GetExecutor()); + fPos = pInt->GetValue(pDum, pCon); + if (iRet == DEVINT) { + if (SCGetInterrupt(pCon) == eAbortOperation) { + SCSetInterrupt(pCon, eContinue); + sprintf(pBueffel, "Driving %s aborted at %9.3f", name, fPos); + SCWrite(pCon, pBueffel, eError); + } + return 0; + } else if (iRet == DEVDONE) { + sprintf(pBueffel, "Driving %s to %9.3f done", name, fPos); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + sprintf(pBueffel, + "Driving %s finished with problems, position: %9.3f", name, + fPos); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + sprintf(pBueffel, "%s is NOT drivable", pDes->name); + SCWrite(pCon, pBueffel, eError); + return 0; +} + +/*---------------------------------------------------------------------------*/ +int Start2Run(SConnection * pCon, SicsInterp * pInter, char *name, + float fNew) +{ + CommandList *pObject = NULL; + pObjectDescriptor pDes = NULL; + pIDrivable pInt = NULL; + Dummy *pDum; + char pBueffel[512]; + int iRet; + float fDelta; + long lTime; + + assert(pCon); + assert(pInter); + + /* check if user is allowed to drive */ + if (!SCMatchRights(pCon, usUser)) { + sprintf(pBueffel, "Insuficient Privilege to drive %s", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* first try to find the thing to drive */ + pObject = FindCommand(pInter, name); + if (!pObject) { + sprintf(pBueffel, "Cannot find %s to drive ", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* get the Descriptor, this RELIES on the descriptor being the first + thing in the struct + */ + pDum = (Dummy *) pObject->pData; + pDes = pDum->pDescriptor; + if (!pDes) { + sprintf(pBueffel, "%s is NOT drivable!", pDes->name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* Only drivable objects can be driven, check this + and act accordingly + */ + pInt = pDes->GetInterface(pDum, DRIVEID); + if (!pInt) { + sprintf(pBueffel, "%s is NOT drivable!", pDes->name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (pInt) { + iRet = pInt->CheckLimits(pDum, fNew, pBueffel, 511); + if (!iRet) { + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, eAbortOperation); + return 0; + } + iRet = StartDevice(GetExecutor(), name, pDes, pDum, pCon, fNew); + if (!iRet) { + return 0; + } else { + return 1; + } + } else { + sprintf(pBueffel, "%s is NOT drivable", pDes->name); + SCWrite(pCon, pBueffel, eError); + return 0; + } +} + /*------------------------------------------------------------------------- This is meant to be called specially from DriveWrapper at a stage when we already know, that name is a drivable motor. Thus no error checking is performed. Do not use this in any other context!!!! */ - static float findPosition(SicsInterp *pSics, SConnection *pCon, char *name) - { - CommandList *pObject = NULL; - pObjectDescriptor pDes = NULL; - pIDrivable pInt = NULL; - Dummy *pDum = NULL; - pMotor pMot = NULL; - float fPos; - int iRet; - char pBueffel[132]; +static float findPosition(SicsInterp * pSics, SConnection * pCon, + char *name) +{ + CommandList *pObject = NULL; + pObjectDescriptor pDes = NULL; + pIDrivable pInt = NULL; + Dummy *pDum = NULL; + pMotor pMot = NULL; + float fPos; + int iRet; + char pBueffel[132]; - /* - treat motors separately in order to correct for zero points - Sighh......... - */ - pMot = FindMotor(pSics,name); - if(pMot != NULL) - { - iRet = MotorGetSoftPosition(pMot,pCon,&fPos); - if(iRet) - { - return fPos; - } - else - { - return -999.; - } + /* + treat motors separately in order to correct for zero points + Sighh......... + */ + pMot = FindMotor(pSics, name); + if (pMot != NULL) { + iRet = MotorGetSoftPosition(pMot, pCon, &fPos); + if (iRet) { + return fPos; + } else { + return -999.; } - - pObject = FindCommand(pSics,name); - if(pObject) - { - pDum = (Dummy *)pObject->pData; - if(pDum) - { - pDes = pDum->pDescriptor; - if(pDes) - { - pInt = pDes->GetInterface(pDum,DRIVEID); - if(!pInt) - { - sprintf(pBueffel, - "ERROR: internal error in findPosition for %s", - name); - SCWrite(pCon,pBueffel,eError); - return -999.99; - } - else - { - return pInt->GetValue(pDum,pCon); - } - } - } - } - return -999.99; } -/*--------------------------------------------------------------------------*/ - int DriveWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - Tcl_Interp *tcl_interp; - int iRet,i; - double dTarget; - char pBueffel[512]; - Status eOld; - - assert(pCon); - assert(pSics); - tcl_interp = InterpGetTcl(pSics); - /* check Status */ - eOld = GetStatus(); - - - argtolower(argc,argv); - /* check no of args */ - if(argc < 3) - { - sprintf(pBueffel,"Insufficient number of args. Usage %s name val", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* check authorisation */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon, - "ERROR: You are not authorized to use the drive command",eError); - return 0; - } - - /* interprete arguments as pairs name value and try to start */ - SetStatus(eDriving); - for(i = 1; i < argc; i+=2) - { - if(argv[i+1] == NULL) - { - sprintf(pBueffel,"ERROR: no value found for driving %s", - argv[i]); - SCWrite(pCon,pBueffel,eError); - SetStatus(eOld); - return 0; + pObject = FindCommand(pSics, name); + if (pObject) { + pDum = (Dummy *) pObject->pData; + if (pDum) { + pDes = pDum->pDescriptor; + if (pDes) { + pInt = pDes->GetInterface(pDum, DRIVEID); + if (!pInt) { + sprintf(pBueffel, + "ERROR: internal error in findPosition for %s", name); + SCWrite(pCon, pBueffel, eError); + return -999.99; + } else { + return pInt->GetValue(pDum, pCon); } - iRet = Tcl_GetDouble(tcl_interp, argv[i+1], &dTarget); - if (iRet == TCL_ERROR) { - SCWrite(pCon, Tcl_GetStringResult(tcl_interp), eError); - StopExe(GetExecutor(),"ALL"); - SetStatus(eOld); - return 0; - } - iRet = Start2Run(pCon,pSics,argv[i],dTarget); - if(!iRet) - { - sprintf(pBueffel,"ERROR: cannot run %s to %s",argv[i],argv[i+1]); - SCWrite(pCon,pBueffel,eError); - StopExe(GetExecutor(),"ALL"); - SetStatus(eOld); - return 0; - } - } - - /* wait for completion */ - iRet = Wait4Success(GetExecutor()); - - /* print positions */ - for(i = 1; i < argc; i += 2) - { - sprintf(pBueffel,"New %s position: %9.3f",argv[i], - findPosition(pSics,pCon,argv[i])); - SCWrite(pCon,pBueffel,eValue); } - - /* check the completion status */ - if(!(eOld == eScanning || eOld == eBatch)) - { - eOld = eEager; - } - if(iRet == DEVERROR) - { - sprintf(pBueffel,"Driving finished with problem"); - SCWrite(pCon,pBueffel,eError); - ClearExecutor(GetExecutor()); - SetStatus(eOld); - return 0; - } - else if(iRet == DEVINT) - { - sprintf(pBueffel,"ERROR: Driving Interrupted!"); - SCWrite(pCon,pBueffel,eError); - ClearExecutor(GetExecutor()); - SetStatus(eOld); - return 0; - } - SCWrite(pCon,"Driving finished sucessfully",eValue); - SetStatus(eOld); - return 1; - } -/*---------------------------------------------------------------------------*/ - int RunWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - Tcl_Interp *tcl_interp; - int iRet, i; - double dTarget; - char pBueffel[512]; - Status eOld; - - assert(pCon); - assert(pSics); - tcl_interp = InterpGetTcl(pSics); - /* check Status */ - eOld = GetStatus(); - - - /* check no of args */ - if(argc < 3) - { - sprintf(pBueffel,"Insufficient number of args. Usage %s name val", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* check authorisation */ - if(!SCMatchRights(pCon, usUser)) - { - SCWrite(pCon, - "ERROR: You are not authorized to use the drive command",eError); - return 0; - } - - /* interprete arguments as pairs name value and try to start */ - SetStatus(eDriving); - for(i = 1; i < argc; i+=2) - { - if(argv[i+1] == NULL) - { - sprintf(pBueffel,"ERROR: no value found for driving %s", - argv[i]); - SCWrite(pCon,pBueffel,eError); - SetStatus(eOld); - return 0; - } - iRet = Tcl_GetDouble(tcl_interp, argv[i+1], &dTarget); - if (iRet == TCL_ERROR) { - SCWrite(pCon, Tcl_GetStringResult(tcl_interp), eError); - StopExe(GetExecutor(),"ALL"); - SetStatus(eOld); - return 0; - } - iRet = Start2Run(pCon,pSics,argv[i],dTarget); - if(!iRet) - { - sprintf(pBueffel,"ERROR: cannot run %s to %s",argv[i],argv[i+1]); - SCWrite(pCon,pBueffel,eError); - StopExe(GetExecutor(),"ALL"); - SetStatus(eOld); - return 0; - } - } - return 1; -} -/*---------------------------------------------------------------------------*/ - int MakeDrive(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet; - char pBueffel[512]; - - assert(pCon); - assert(pSics); - - if(argc > 1) - { - iRet = AddCommand(pSics,argv[1], DriveWrapper,NULL,NULL); - } else { - iRet = AddCommand(pSics,"drive", DriveWrapper,NULL,NULL); - } - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command drive not created"); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(argc > 2) - { - iRet = AddCommand(pSics,argv[2], RunWrapper,NULL,NULL); - } else { - iRet = AddCommand(pSics,"run", RunWrapper,NULL,NULL); - } - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command run not created"); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; } + } + return -999.99; +} +/*--------------------------------------------------------------------------*/ +int DriveWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + Tcl_Interp *tcl_interp; + int iRet, i; + double dTarget; + char pBueffel[512]; + Status eOld; + + assert(pCon); + assert(pSics); + tcl_interp = InterpGetTcl(pSics); + + /* check Status */ + eOld = GetStatus(); + + + argtolower(argc, argv); + /* check no of args */ + if (argc < 3) { + sprintf(pBueffel, "Insufficient number of args. Usage %s name val", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* check authorisation */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, + "ERROR: You are not authorized to use the drive command", + eError); + return 0; + } + + /* interprete arguments as pairs name value and try to start */ + SetStatus(eDriving); + for (i = 1; i < argc; i += 2) { + if (argv[i + 1] == NULL) { + sprintf(pBueffel, "ERROR: no value found for driving %s", argv[i]); + SCWrite(pCon, pBueffel, eError); + SetStatus(eOld); + return 0; + } + iRet = Tcl_GetDouble(tcl_interp, argv[i + 1], &dTarget); + if (iRet == TCL_ERROR) { + SCWrite(pCon, Tcl_GetStringResult(tcl_interp), eError); + StopExe(GetExecutor(), "ALL"); + SetStatus(eOld); + return 0; + } + iRet = Start2Run(pCon, pSics, argv[i], dTarget); + if (!iRet) { + sprintf(pBueffel, "ERROR: cannot run %s to %s", argv[i], + argv[i + 1]); + SCWrite(pCon, pBueffel, eError); + StopExe(GetExecutor(), "ALL"); + SetStatus(eOld); + return 0; + } + } + + /* wait for completion */ + iRet = Wait4Success(GetExecutor()); + + /* print positions */ + for (i = 1; i < argc; i += 2) { + sprintf(pBueffel, "New %s position: %9.3f", argv[i], + findPosition(pSics, pCon, argv[i])); + SCWrite(pCon, pBueffel, eValue); + } + + /* check the completion status */ + if (!(eOld == eScanning || eOld == eBatch)) { + eOld = eEager; + } + if (iRet == DEVERROR) { + sprintf(pBueffel, "Driving finished with problem"); + SCWrite(pCon, pBueffel, eError); + ClearExecutor(GetExecutor()); + SetStatus(eOld); + return 0; + } else if (iRet == DEVINT) { + sprintf(pBueffel, "ERROR: Driving Interrupted!"); + SCWrite(pCon, pBueffel, eError); + ClearExecutor(GetExecutor()); + SetStatus(eOld); + return 0; + } + SCWrite(pCon, "Driving finished sucessfully", eValue); + SetStatus(eOld); + return 1; +} + +/*---------------------------------------------------------------------------*/ +int RunWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + Tcl_Interp *tcl_interp; + int iRet, i; + double dTarget; + char pBueffel[512]; + Status eOld; + + assert(pCon); + assert(pSics); + tcl_interp = InterpGetTcl(pSics); + /* check Status */ + eOld = GetStatus(); + + + /* check no of args */ + if (argc < 3) { + sprintf(pBueffel, "Insufficient number of args. Usage %s name val", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* check authorisation */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, + "ERROR: You are not authorized to use the drive command", + eError); + return 0; + } + + /* interprete arguments as pairs name value and try to start */ + SetStatus(eDriving); + for (i = 1; i < argc; i += 2) { + if (argv[i + 1] == NULL) { + sprintf(pBueffel, "ERROR: no value found for driving %s", argv[i]); + SCWrite(pCon, pBueffel, eError); + SetStatus(eOld); + return 0; + } + iRet = Tcl_GetDouble(tcl_interp, argv[i + 1], &dTarget); + if (iRet == TCL_ERROR) { + SCWrite(pCon, Tcl_GetStringResult(tcl_interp), eError); + StopExe(GetExecutor(), "ALL"); + SetStatus(eOld); + return 0; + } + iRet = Start2Run(pCon, pSics, argv[i], dTarget); + if (!iRet) { + sprintf(pBueffel, "ERROR: cannot run %s to %s", argv[i], + argv[i + 1]); + SCWrite(pCon, pBueffel, eError); + StopExe(GetExecutor(), "ALL"); + SetStatus(eOld); + return 0; + } + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +int MakeDrive(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet; + char pBueffel[512]; + + assert(pCon); + assert(pSics); + + if (argc > 1) { + iRet = AddCommand(pSics, argv[1], DriveWrapper, NULL, NULL); + } else { + iRet = AddCommand(pSics, "drive", DriveWrapper, NULL, NULL); + } + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command drive not created"); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (argc > 2) { + iRet = AddCommand(pSics, argv[2], RunWrapper, NULL, NULL); + } else { + iRet = AddCommand(pSics, "run", RunWrapper, NULL, NULL); + } + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command run not created"); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} diff --git a/drive.h b/drive.h index 0b3a690b..46f70287 100644 --- a/drive.h +++ b/drive.h @@ -9,29 +9,29 @@ #ifndef SICSDRIVE #define SICSDRIVE #include "conman.h" - - int Drive(SConnection *pCon,SicsInterp *pSics, char *name, float fNew); - - int Start2Run(SConnection *pCon, SicsInterp *pSics, char *name, float - fNew); - - int DriveWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - /* - the wrapper function for the drive command - */ - int RunWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - /* - the wrapper function for the run command - */ - - - int MakeDrive(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - /* - the factory function for the Drive & Run command - */ +int Drive(SConnection * pCon, SicsInterp * pSics, char *name, float fNew); + +int Start2Run(SConnection * pCon, SicsInterp * pSics, char *name, float + fNew); + +int DriveWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + /* + the wrapper function for the drive command + */ + +int RunWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + /* + the wrapper function for the run command + */ + + +int MakeDrive(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + /* + the factory function for the Drive & Run command + */ #endif diff --git a/dynstring.c b/dynstring.c index 0fbbde52..7269eb2b 100644 --- a/dynstring.c +++ b/dynstring.c @@ -12,262 +12,254 @@ #include #include "dynstring.h" -#define DYNMAGIC 27031998 +#define DYNMAGIC 27031998 /*--------------------------------------------------------------------------*/ - typedef struct __DynString { - int iMAGIC; - char *pBuffer; - int iTextLen; - int iBufferSize; - int iResize; - } DynString; +typedef struct __DynString { + int iMAGIC; + char *pBuffer; + int iTextLen; + int iBufferSize; + int iResize; +} DynString; /*--------------------------------------------------------------------------*/ - pDynString CreateDynString(int iInitial, int iResize) - { - pDynString pNew = NULL; - - if(iInitial <= 0) - iInitial = 512; - if(iResize <= 0) - iResize = 512; - - /* new memory */ - pNew = (pDynString)malloc(sizeof(DynString)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(DynString)); - pNew->pBuffer = (char *)malloc(iInitial*sizeof(char)); - if(!pNew->pBuffer) - { - free(pNew); - return NULL; - } - memset(pNew->pBuffer,0,iInitial*sizeof(char)); - - /* initialise the rest */ - pNew->iMAGIC = DYNMAGIC; - pNew->iBufferSize = iInitial; - pNew->iResize = iResize; - pNew->iTextLen = 0; - - return pNew; - } +pDynString CreateDynString(int iInitial, int iResize) +{ + pDynString pNew = NULL; + + if (iInitial <= 0) + iInitial = 512; + if (iResize <= 0) + iResize = 512; + + /* new memory */ + pNew = (pDynString) malloc(sizeof(DynString)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(DynString)); + pNew->pBuffer = (char *) malloc(iInitial * sizeof(char)); + if (!pNew->pBuffer) { + free(pNew); + return NULL; + } + memset(pNew->pBuffer, 0, iInitial * sizeof(char)); + + /* initialise the rest */ + pNew->iMAGIC = DYNMAGIC; + pNew->iBufferSize = iInitial; + pNew->iResize = iResize; + pNew->iTextLen = 0; + + return pNew; +} + /*--------------------------------------------------------------------------*/ - static int Resize(pDynString self, int iRequested) - { - char *pNewBuffer; - int iNewSize; - - if(iRequested < self->iBufferSize) - { - return 1; - } - - /* get new data space */ - iNewSize = iRequested + self->iResize; - pNewBuffer = (char *)malloc(iNewSize *sizeof(char)); - if(!pNewBuffer) - { - return 0; - } - memset(pNewBuffer,0,iNewSize); - - /* copy data */ - memcpy(pNewBuffer,self->pBuffer,self->iTextLen); - - /* swap things around */ - if(self->pBuffer) - { - free(self->pBuffer); - } - self->pBuffer = pNewBuffer; - self->iBufferSize = iNewSize; - return 1; - } +static int Resize(pDynString self, int iRequested) +{ + char *pNewBuffer; + int iNewSize; + + if (iRequested < self->iBufferSize) { + return 1; + } + + /* get new data space */ + iNewSize = iRequested + self->iResize; + pNewBuffer = (char *) malloc(iNewSize * sizeof(char)); + if (!pNewBuffer) { + return 0; + } + memset(pNewBuffer, 0, iNewSize); + + /* copy data */ + memcpy(pNewBuffer, self->pBuffer, self->iTextLen); + + /* swap things around */ + if (self->pBuffer) { + free(self->pBuffer); + } + self->pBuffer = pNewBuffer; + self->iBufferSize = iNewSize; + return 1; +} + /*--------------------------------------------------------------------------*/ - void DeleteDynString(pDynString self) - { - assert(self); - assert(self->iMAGIC == DYNMAGIC); - - if(self->pBuffer) - free(self->pBuffer); - - free(self); - } +void DeleteDynString(pDynString self) +{ + assert(self); + assert(self->iMAGIC == DYNMAGIC); + + if (self->pBuffer) + free(self->pBuffer); + + free(self); +} + /*--------------------------------------------------------------------------*/ - int DynStringClear(pDynString self) - { - assert(self); - assert(self->iMAGIC == DYNMAGIC); - - self->iTextLen = 0; - memset(self->pBuffer,0,self->iBufferSize); - return 1; - } +int DynStringClear(pDynString self) +{ + assert(self); + assert(self->iMAGIC == DYNMAGIC); + + self->iTextLen = 0; + memset(self->pBuffer, 0, self->iBufferSize); + return 1; +} + /*-------------------------------------------------------------------------*/ - int DynStringCopy(pDynString self, char *pText) - { - int iRequested, iRet; +int DynStringCopy(pDynString self, char *pText) +{ + int iRequested, iRet; - assert(self); - assert(self->iMAGIC == DYNMAGIC); - - iRequested = strlen(pText); - if(iRequested >= self->iBufferSize) - { - iRet = Resize(self,iRequested); - if(!iRet) - { - return 0; - } - } - else /* safety: remove rubbish */ - { - memset(self->pBuffer,0,self->iBufferSize*sizeof(char)); - } - strcpy(self->pBuffer,pText); - self->iTextLen = iRequested; - return 1; - } -/*--------------------------------------------------------------------------*/ - int DynStringConcat(pDynString self, char *pText) - { - int iRequested, iRet; + assert(self); + assert(self->iMAGIC == DYNMAGIC); - assert(self); - assert(self->iMAGIC == DYNMAGIC); - - iRequested = strlen(pText) + self->iTextLen; - if(iRequested >= self->iBufferSize) - { - iRet = Resize(self,iRequested); - if(!iRet) - { - return 0; - } - } - - strcat(self->pBuffer,pText); - self->iTextLen = iRequested; - return 1; - } -/*--------------------------------------------------------------------------*/ - int DynStringConcatChar(pDynString self, char c) - { - int iRequested, iRet; - - assert(self); - assert(self->iMAGIC == DYNMAGIC); - - iRequested = self->iTextLen + 1; - if(iRequested >= self->iBufferSize) - { - iRet = Resize(self,iRequested); - if(!iRet) - { - return 0; - } - } - - self->pBuffer[self->iTextLen] = c; - self->iTextLen++; - return 1; - } -/*---------------------------------------------------------------------------*/ - int DynStringInsert(pDynString self, char *pText, int iPos) - { - int iRequested, iRet, iPush, iRest; - char *pPtr; - - assert(self); - assert(self->iMAGIC == DYNMAGIC); - - /* provide space */ - iPush = strlen(pText); - iRequested = self->iTextLen + iPush; - if(iRequested >= self->iBufferSize) - { - iRet = Resize(self,iRequested); - if(!iRet) - { - return 0; - } - } - - /* we need a temporary buffer to hold the backend of the string */ - iRest = self->iTextLen - iPos; - pPtr = (char *)malloc((iRest+10)*sizeof(char)); - if(!pPtr) - { + if(pText == 0){ + return 0; + } + iRequested = strlen(pText); + if (iRequested >= self->iBufferSize) { + iRet = Resize(self, iRequested); + if (!iRet) { return 0; } - memset(pPtr,0,(iRest+10)*sizeof(char)); - strcpy(pPtr,&self->pBuffer[iPos]); - - /* OK build the result string */ - memset(&self->pBuffer[iPos],0,iRest*sizeof(char)); - strcat(self->pBuffer,pText); - strcat(self->pBuffer,pPtr); - free(pPtr); - self->iTextLen = iRequested; - return 1; - } + } else { /* safety: remove rubbish */ + + memset(self->pBuffer, 0, self->iBufferSize * sizeof(char)); + } + strcpy(self->pBuffer, pText); + self->iTextLen = iRequested; + return 1; +} + /*--------------------------------------------------------------------------*/ - int DynStringReplace(pDynString self, char *pText, int iPos) - { - int iRequested, iRet; +int DynStringConcat(pDynString self, char *pText) +{ + int iRequested, iRet; - assert(self); - assert(self->iMAGIC == DYNMAGIC); - - iRequested = strlen(pText) + iPos; - if(iRequested >= self->iBufferSize) - { - iRet = Resize(self,iRequested); - if(!iRet) - { - return 0; - } + assert(self); + assert(self->iMAGIC == DYNMAGIC); + + iRequested = strlen(pText) + self->iTextLen; + if (iRequested >= self->iBufferSize) { + iRet = Resize(self, iRequested); + if (!iRet) { + return 0; } + } - memcpy(&self->pBuffer[iPos],pText,strlen(pText)*sizeof(char)); - self->iTextLen = strlen(self->pBuffer); - return 1; - } -/*---------------------------------------------------------------------------*/ - char *GetCharArray(pDynString self) - { - assert(self); - assert(self->iMAGIC == DYNMAGIC); + strcat(self->pBuffer, pText); + self->iTextLen = iRequested; + return 1; +} - return self->pBuffer; - } -/*---------------------------------------------------------------------------*/ - int GetDynStringLength(pDynString self) - { - assert(self); - assert(self->iMAGIC == DYNMAGIC); +/*--------------------------------------------------------------------------*/ +int DynStringConcatChar(pDynString self, char c) +{ + int iRequested, iRet; - return self->iTextLen; - } -/*---------------------------------------------------------------------------*/ - int DynStringBackspace(pDynString self) - { - assert(self); - assert(self->iMAGIC == DYNMAGIC); + assert(self); + assert(self->iMAGIC == DYNMAGIC); - if(self->iTextLen > 0) - { - self->pBuffer[self->iTextLen - 1] = '\0'; - self->iTextLen--; + iRequested = self->iTextLen + 1; + if (iRequested >= self->iBufferSize) { + iRet = Resize(self, iRequested); + if (!iRet) { + return 0; } - return 1; - } + } + self->pBuffer[self->iTextLen] = c; + self->iTextLen++; + return 1; +} +/*---------------------------------------------------------------------------*/ +int DynStringInsert(pDynString self, char *pText, int iPos) +{ + int iRequested, iRet, iPush, iRest; + char *pPtr; + assert(self); + assert(self->iMAGIC == DYNMAGIC); + /* provide space */ + iPush = strlen(pText); + iRequested = self->iTextLen + iPush; + if (iRequested >= self->iBufferSize) { + iRet = Resize(self, iRequested); + if (!iRet) { + return 0; + } + } + + /* we need a temporary buffer to hold the backend of the string */ + iRest = self->iTextLen - iPos; + pPtr = (char *) malloc((iRest + 10) * sizeof(char)); + if (!pPtr) { + return 0; + } + memset(pPtr, 0, (iRest + 10) * sizeof(char)); + strcpy(pPtr, &self->pBuffer[iPos]); + + /* OK build the result string */ + memset(&self->pBuffer[iPos], 0, iRest * sizeof(char)); + strcat(self->pBuffer, pText); + strcat(self->pBuffer, pPtr); + free(pPtr); + self->iTextLen = iRequested; + return 1; +} + +/*--------------------------------------------------------------------------*/ +int DynStringReplace(pDynString self, char *pText, int iPos) +{ + int iRequested, iRet; + + assert(self); + assert(self->iMAGIC == DYNMAGIC); + + iRequested = strlen(pText) + iPos; + if (iRequested >= self->iBufferSize) { + iRet = Resize(self, iRequested); + if (!iRet) { + return 0; + } + } + + memcpy(&self->pBuffer[iPos], pText, strlen(pText) * sizeof(char)); + self->iTextLen = strlen(self->pBuffer); + return 1; +} + +/*---------------------------------------------------------------------------*/ +char *GetCharArray(pDynString self) +{ + assert(self); + assert(self->iMAGIC == DYNMAGIC); + + return self->pBuffer; +} + +/*---------------------------------------------------------------------------*/ +int GetDynStringLength(pDynString self) +{ + assert(self); + assert(self->iMAGIC == DYNMAGIC); + + return self->iTextLen; +} + +/*---------------------------------------------------------------------------*/ +int DynStringBackspace(pDynString self) +{ + assert(self); + assert(self->iMAGIC == DYNMAGIC); + + if (self->iTextLen > 0) { + self->pBuffer[self->iTextLen - 1] = '\0'; + self->iTextLen--; + } + return 1; +} diff --git a/dynstring.h b/dynstring.h index a40b7acb..cc44feb8 100644 --- a/dynstring.h +++ b/dynstring.h @@ -23,74 +23,74 @@ ----------------------------------------------------------------------------*/ #ifndef DYNAMICSTRING #define DYNAMICSTRING - typedef struct __DynString *pDynString; - +typedef struct __DynString *pDynString; + /*----------------------- live and death ----------------------------------*/ - pDynString CreateDynString(int iInitialLength, int iResizeLength); +pDynString CreateDynString(int iInitialLength, int iResizeLength); /* - Create a new DynString Object. Its initial length will be iInitialLength. - It will be resized in iResizeLength steps. This allows for efficient - storage management. It woul be seriously inefficient to allocate - per added character. - */ - - void DeleteDynString(pDynString self); -/*----------------------- interface to it --------------------------------- */ + Create a new DynString Object. Its initial length will be iInitialLength. + It will be resized in iResizeLength steps. This allows for efficient + storage management. It woul be seriously inefficient to allocate + per added character. + */ + +void DeleteDynString(pDynString self); +/*----------------------- interface to it --------------------------------- */ + +int DynStringCopy(pDynString self, char *pText); - int DynStringCopy(pDynString self, char *pText); - /* - Copies the text in Text into the DynString starting at 0 and over - writing anything there beforehand. - */ - - int DynStringConcat(pDynString self, char *pText); - /* - Concatenates the string in DynString with the one supplied - in string. - */ + Copies the text in Text into the DynString starting at 0 and over + writing anything there beforehand. + */ - int DynStringConcatChar(pDynString self, char c); +int DynStringConcat(pDynString self, char *pText); /* - adds one character at the end of the string - */ - - int DynStringInsert(pDynString self, char *pText, int iPos); - - /* - inserts the text in pText at Position iPos in the DynString. - Everything behind iPos will be pushed outwards in order to create - space for pText. - */ + Concatenates the string in DynString with the one supplied + in string. + */ - int DynStringReplace(pDynString self, char *pText, int iPos); - +int DynStringConcatChar(pDynString self, char c); /* - Starting at iPos, replace everything after it with ptext. In - contrats to insert this won't push data backwards. - */ - - char *GetCharArray(pDynString self); - + adds one character at the end of the string + */ + +int DynStringInsert(pDynString self, char *pText, int iPos); + + /* + inserts the text in pText at Position iPos in the DynString. + Everything behind iPos will be pushed outwards in order to create + space for pText. + */ + +int DynStringReplace(pDynString self, char *pText, int iPos); + + /* + Starting at iPos, replace everything after it with ptext. In + contrats to insert this won't push data backwards. + */ + +char *GetCharArray(pDynString self); + /* - retrieves a pointer to the character array keeping the current - text. NEVER, ever free this pointer, otherwise you are rewarded - with a core dump. The pointer belongs to DynString and will be - deleted when deleting the DynString. - */ - - int GetDynStringLength(pDynString self); - - /* - returns the current length of the dynamic string. - */ + retrieves a pointer to the character array keeping the current + text. NEVER, ever free this pointer, otherwise you are rewarded + with a core dump. The pointer belongs to DynString and will be + deleted when deleting the DynString. + */ + +int GetDynStringLength(pDynString self); - int DynStringClear(pDynString self); /* - removes all old data from the dynstring - */ - int DynStringBackspace(pDynString self); + returns the current length of the dynamic string. + */ + +int DynStringClear(pDynString self); + /* + removes all old data from the dynstring + */ +int DynStringBackspace(pDynString self); /* - removes one character at the end from the dynstring - */ -#endif + removes one character at the end from the dynstring + */ +#endif diff --git a/ecbcounter.c b/ecbcounter.c index b5d21d95..18269dae 100644 --- a/ecbcounter.c +++ b/ecbcounter.c @@ -19,21 +19,21 @@ /*------------------ our private data structure ------------------------*/ typedef struct { - pECB ecb; /* the ECB system we talk to */ - unsigned char prescaler[8]; /* an array for the prescaler values */ - int tfreq; /* timer frequency */ - unsigned char control; /* marks the control monitor */ - int state; /* current counting state */ -}ECBCounter, *pECBCounter; + pECB ecb; /* the ECB system we talk to */ + unsigned char prescaler[8]; /* an array for the prescaler values */ + int tfreq; /* timer frequency */ + unsigned char control; /* marks the control monitor */ + int state; /* current counting state */ +} ECBCounter, *pECBCounter; /*----------------- private defines ------------------------------------*/ #define STFRD 137 #define STREAD 138 -#define STOPS 136 +#define STOPS 136 #define STCLEA 134 #define PRELOA 139 #define STLOAD 156 -#define STCPRE 133 +#define STCPRE 133 #define STARTS 135 #define SPCSTA 169 @@ -42,7 +42,7 @@ typedef struct { #define COUNT 2 #define NOBEAM 3 /*--------------------------------------------------------------------*/ -#define MAX_COUNT 4294967295.0 +#define MAX_COUNT 4294967295.0 /*------------------ error codes --------------------------------------*/ #define COMMERROR -300 #define TOMANYCOUNTS -301 @@ -51,14 +51,15 @@ typedef struct { #define INVALIDPRESCALER -305 #define BADFREQ -306 /*======================================================================*/ -static int readScaler(pECBCounter pPriv, int scaler, int *count){ +static int readScaler(pECBCounter pPriv, int scaler, int *count) +{ int status; Z80_reg in, out; Ecb_pack data; - - in.c = (unsigned char)scaler; - status = ecbExecute(pPriv->ecb,STREAD,in,&out); - if(status != 1){ + + in.c = (unsigned char) scaler; + status = ecbExecute(pPriv->ecb, STREAD, in, &out); + if (status != 1) { return COMMERROR; } @@ -66,111 +67,121 @@ static int readScaler(pECBCounter pPriv, int scaler, int *count){ data.b.byt2 = out.b; data.b.byt1 = out.d; data.b.byt0 = out.e; - if(scaler == 0){ - *count = data.result/pPriv->tfreq; + if (scaler == 0) { + *count = data.result / pPriv->tfreq; } else { *count = data.result; } return 1; } + /*---------------------------------------------------------------------*/ -static int check4Beam(struct __COUNTER *pCter, int *beam){ +static int check4Beam(struct __COUNTER *pCter, int *beam) +{ Z80_reg in, out; pECBCounter self = NULL; int status; - self = (pECBCounter)pCter->pData; + self = (pECBCounter) pCter->pData; assert(self); in.c = 1; - status = ecbExecute(self->ecb,SPCSTA,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, SPCSTA, in, &out); + if (status != 1) { pCter->iErrorCode = COMMERROR; return HWFault; } - *beam = (int)out.d; + *beam = (int) out.d; return 1; } + /*----------------------------------------------------------------------*/ -static int stopScalers(pECBCounter self){ +static int stopScalers(pECBCounter self) +{ int status; Z80_reg in, out; - status = ecbExecute(self->ecb,STOPS,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, STOPS, in, &out); + if (status != 1) { return COMMERROR; } return 1; } + /*======================================================================== These two functions currently rely on the idea that the ECB stops and starts without clearing counters in between. The sequence of things necessary to start it, suggests this. If this is not the case then this will not work. ===========================================================================*/ -static int ECBPause(struct __COUNTER *self){ +static int ECBPause(struct __COUNTER *self) +{ int status; pECBCounter pPriv = NULL; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); - if((status = stopScalers(pPriv)) <= 0){ + if ((status = stopScalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } return OKOK; } + /*=======================================================================*/ -static int ECBContinue(struct __COUNTER *self){ +static int ECBContinue(struct __COUNTER *self) +{ int status; pECBCounter pPriv = NULL; Z80_reg in, out; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); - status = ecbExecute(pPriv->ecb,STARTS,in,&out); - if(status != 1){ + status = ecbExecute(pPriv->ecb, STARTS, in, &out); + if (status != 1) { self->iErrorCode = status; return HWFault; } return OKOK; } + /*-----------------------------------------------------------------------*/ -static int ECBGetStatus(struct __COUNTER *self, float *fControl){ - pECBCounter pPriv = (pECBCounter)self->pData; +static int ECBGetStatus(struct __COUNTER *self, float *fControl) +{ + pECBCounter pPriv = (pECBCounter) self->pData; int status, result, scaler; Z80_reg in, out; int count, beam; - + assert(pPriv); /* - This can happen after a stop - */ - if(pPriv->state == IDLE){ + This can happen after a stop + */ + if (pPriv->state == IDLE) { return HWIdle; } /* - read status bit - */ - status = ecbExecute(pPriv->ecb,STFRD,in,&out); - if(status != 1){ + read status bit + */ + status = ecbExecute(pPriv->ecb, STFRD, in, &out); + if (status != 1) { self->iErrorCode = COMMERROR; pPriv->state = IDLE; return HWFault; } /* - read beam status - */ - status = check4Beam(self,&beam); - if(status != 1){ + read beam status + */ + status = check4Beam(self, &beam); + if (status != 1) { self->iErrorCode = COMMERROR; return HWFault; } @@ -181,23 +192,23 @@ static int ECBGetStatus(struct __COUNTER *self, float *fControl){ the thing can be in. Complicated by the fact that the status becomes idle (out.d = 0) when the measurement is paused due to the lack of beam. - */ - if(pPriv->state == COUNT && beam == 1){ + */ + if (pPriv->state == COUNT && beam == 1) { ECBPause(self); pPriv->state = NOBEAM; SetStatus(eOutOfBeam); result = HWNoBeam; } - if(pPriv->state == NOBEAM && beam == 0){ + if (pPriv->state == NOBEAM && beam == 0) { ECBContinue(self); pPriv->state = COUNT; SetStatus(eCounting); return HWBusy; } - if(pPriv->state == NOBEAM && beam == 1){ + if (pPriv->state == NOBEAM && beam == 1) { return HWNoBeam; } - if(out.d == 0 && pPriv->state == COUNT){ + if (out.d == 0 && pPriv->state == COUNT) { result = HWIdle; pPriv->state = IDLE; } else { @@ -206,97 +217,105 @@ static int ECBGetStatus(struct __COUNTER *self, float *fControl){ /* - select which scaler to read - */ - if(self->eMode == eTimer){ + select which scaler to read + */ + if (self->eMode == eTimer) { scaler = 0; - }else { + } else { scaler = pPriv->control; } - readScaler(pPriv,scaler,&count); + readScaler(pPriv, scaler, &count); /* - ignore errors on this one - */ - *fControl = (float)count; + ignore errors on this one + */ + *fControl = (float) count; return result; } + /*=====================================================================*/ -static int clearScalers(pECBCounter self){ +static int clearScalers(pECBCounter self) +{ int status; Z80_reg in, out; - status = ecbExecute(self->ecb,STCLEA,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, STCLEA, in, &out); + if (status != 1) { return COMMERROR; } return 1; } + /*----------------------------------------------------------------------*/ -static int loadPrescalers(pECBCounter self){ +static int loadPrescalers(pECBCounter self) +{ Z80_reg in, out; int status, i; - for(i = 0; i < 8; i++){ - in.c = (unsigned char)i; + for (i = 0; i < 8; i++) { + in.c = (unsigned char) i; in.d = self->prescaler[i]; - status = ecbExecute(self->ecb,PRELOA,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, PRELOA, in, &out); + if (status != 1) { return COMMERROR; } } return 1; } + /*----------------------------------------------------------------------*/ -static int loadPreset(pECBCounter self, int preset, unsigned char control){ +static int loadPreset(pECBCounter self, int preset, unsigned char control) +{ Z80_reg in, out; Ecb_pack data; int status, i; data.result = preset; - + in.c = data.b.byt3; in.b = data.b.byt2; in.e = data.b.byt1; in.d = data.b.byt0; - status = ecbExecute(self->ecb,STLOAD,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, STLOAD, in, &out); + if (status != 1) { return COMMERROR; } in.b = data.b.byt2; in.e = data.b.byt1; in.d = data.b.byt0; - in.c = 4*control; - status = ecbExecute(self->ecb,STCPRE,in,&out); - if(status != 1){ + in.c = 4 * control; + status = ecbExecute(self->ecb, STCPRE, in, &out); + if (status != 1) { return COMMERROR; } return 1; } + /*-----------------------------------------------------------------------*/ -static int ECBStart(struct __COUNTER *self){ +static int ECBStart(struct __COUNTER *self) +{ pECBCounter pPriv = NULL; int preset, status, controlUnit; Z80_reg in, out; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); /* - check if the preset is permissible - */ - preset = (int)rint(self->fPreset); - if(preset > MAX_COUNT){ + check if the preset is permissible + */ + preset = (int) rint(self->fPreset); + if (preset > MAX_COUNT) { self->iErrorCode = TOMANYCOUNTS; return HWFault; } - if(self->eMode == eTimer){ + if (self->eMode == eTimer) { controlUnit = 0; - preset *= pPriv->tfreq; - if(preset > MAX_COUNT){ + preset *= pPriv->tfreq; + if (preset > MAX_COUNT) { self->iErrorCode = TOMANYCOUNTS; return HWFault; } @@ -304,124 +323,133 @@ static int ECBStart(struct __COUNTER *self){ controlUnit = pPriv->control; } - if((status = stopScalers(pPriv)) <= 0){ + if ((status = stopScalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } - if((status = clearScalers(pPriv)) <= 0){ + if ((status = clearScalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } - if((status = loadPrescalers(pPriv)) <= 0){ + if ((status = loadPrescalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } - if((status = loadPreset(pPriv, preset,(unsigned char)controlUnit)) <= 0){ + if ((status = + loadPreset(pPriv, preset, (unsigned char) controlUnit)) <= 0) { self->iErrorCode = status; return HWFault; } - status = ecbExecute(pPriv->ecb,STARTS,in,&out); - if(status != 1){ + status = ecbExecute(pPriv->ecb, STARTS, in, &out); + if (status != 1) { self->iErrorCode = status; return HWFault; } - + pPriv->state = COUNT; return OKOK; } + /*=======================================================================*/ -static int ECBHalt(struct __COUNTER *self){ +static int ECBHalt(struct __COUNTER *self) +{ int status; pECBCounter pPriv = NULL; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); pPriv->state = IDLE; - if((status = stopScalers(pPriv)) <= 0){ + if ((status = stopScalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } return OKOK; } + /*=======================================================================*/ -static int ECBTransfer(struct __COUNTER *self){ +static int ECBTransfer(struct __COUNTER *self) +{ int status, count, i; pECBCounter pPriv = NULL; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); /* - read time - */ - status = readScaler(pPriv,0,&count); - if(status <= 0){ + read time + */ + status = readScaler(pPriv, 0, &count); + if (status <= 0) { self->iErrorCode = COMMERROR; return HWFault; } - self->fTime = (float)count; + self->fTime = (float) count; /* - read other scalers - */ - for(i = 1; i < 8; i++){ - status = readScaler(pPriv,i,&count); - if(status <= 0){ + read other scalers + */ + for (i = 1; i < 8; i++) { + status = readScaler(pPriv, i, &count); + if (status <= 0) { self->iErrorCode = COMMERROR; return HWFault; } - self->lCounts[i-1] = count; + self->lCounts[i - 1] = count; } return OKOK; } + /*======================================================================*/ static int ECBGetError(struct __COUNTER *self, int *iCode, - char *errorText, int errlen){ + char *errorText, int errlen) +{ char pBueffel[132]; *iCode = self->iErrorCode; - switch(self->iErrorCode){ + switch (self->iErrorCode) { case COMMERROR: - strncpy(errorText,"Communication error with ECB",errlen); + strncpy(errorText, "Communication error with ECB", errlen); break; case TOMANYCOUNTS: - strncpy(errorText,"Preset is to high!",errlen); + strncpy(errorText, "Preset is to high!", errlen); break; case NOSEND: - strncpy(errorText,"Cannot send naked data to ECB",errlen); + strncpy(errorText, "Cannot send naked data to ECB", errlen); break; case UNKNOWNPAR: - strncpy(errorText,"parameter unknown",errlen); + strncpy(errorText, "parameter unknown", errlen); break; case INVALIDCOUNTER: - strncpy(errorText,"Invalid counter number requested, 0-7 allowed", - errlen); + strncpy(errorText, "Invalid counter number requested, 0-7 allowed", + errlen); break; case INVALIDPRESCALER: - strncpy(errorText,"Invalid prescaler value, allowed 1 or 10", - errlen); + strncpy(errorText, "Invalid prescaler value, allowed 1 or 10", errlen); break; case BADFREQ: - strncpy(errorText,"Bad timer frequency: 10 or 1000 allowed",errlen); + strncpy(errorText, "Bad timer frequency: 10 or 1000 allowed", errlen); break; default: - sprintf(pBueffel,"Unknown error code %d", self->iErrorCode); - strncpy(errorText,pBueffel,errlen); + sprintf(pBueffel, "Unknown error code %d", self->iErrorCode); + strncpy(errorText, pBueffel, errlen); break; } return 1; } + /*=======================================================================*/ -static int ECBFixIt(struct __COUNTER *self, int iCode){ +static int ECBFixIt(struct __COUNTER *self, int iCode) +{ return COTERM; } + /*======================================================================*/ /******************************************************************************* @@ -430,72 +458,71 @@ static int ECBFixIt(struct __COUNTER *self, int iCode){ * of f.ex a motor position. 'divide' specifies how many times the po- * sition is to be divided by two before it is displayed. ******************************************************************************/ -static void -Dot_divide (int device, int data, pECB ecb) +static void Dot_divide(int device, int data, pECB ecb) { int function, dot, divide; Z80_reg x_inreg, out; - if (data == 0) /* If zero, dont send dot/divide) */ + if (data == 0) /* If zero, dont send dot/divide) */ return; dot = 0; - while ((data%10) == 0) - { - dot++; - data /= 10; - } + while ((data % 10) == 0) { + dot++; + data /= 10; + } divide = 0; - while ((data%2) == 0) - { - divide++; - data /= 2; - } - if (data != 1) /* If != 1, not a binary No. */ + while ((data % 2) == 0) { + divide++; + data /= 2; + } + if (data != 1) /* If != 1, not a binary No. */ return; if (dot > 0) dot = 8 - dot; - x_inreg.c = 0; /* Specify input */ + x_inreg.c = 0; /* Specify input */ x_inreg.b = (unsigned char) device; - x_inreg.d = (unsigned char) dot; /* Dot position */ - x_inreg.e = (unsigned char) divide; /* No. of times to divide by 2 */ + x_inreg.d = (unsigned char) dot; /* Dot position */ + x_inreg.e = (unsigned char) divide; /* No. of times to divide by 2 */ - ecbExecute(ecb,170,x_inreg,&out); + ecbExecute(ecb, 170, x_inreg, &out); return; } + /*-----------------------------------------------------------------------*/ -static int ECBSet(struct __COUNTER *self, char *name, - int iCter, float fVal){ +static int ECBSet(struct __COUNTER *self, char *name, + int iCter, float fVal) +{ pECBCounter pPriv = NULL; int iVal; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); - iVal = (int)rint(fVal); + iVal = (int) rint(fVal); - if(strcmp(name,"prescaler") == 0){ - if(iCter < 0 || iCter > 7){ + if (strcmp(name, "prescaler") == 0) { + if (iCter < 0 || iCter > 7) { self->iErrorCode = INVALIDCOUNTER; return HWFault; } - if(iVal != 1 && iVal != 10){ + if (iVal != 1 && iVal != 10) { self->iErrorCode = INVALIDPRESCALER; return HWFault; } - pPriv->prescaler[iCter] = (unsigned char)iVal; + pPriv->prescaler[iCter] = (unsigned char) iVal; return OKOK; - } else if(strcmp(name,"tfreq") == 0){ - if(fVal == 1000){ + } else if (strcmp(name, "tfreq") == 0) { + if (fVal == 1000) { pPriv->prescaler[0] = 1; pPriv->tfreq = 1000; - Dot_divide(64,1000,pPriv->ecb); + Dot_divide(64, 1000, pPriv->ecb); return OKOK; - } else if(fVal == 10){ + } else if (fVal == 10) { pPriv->tfreq = 10; pPriv->prescaler[0] = 10; - Dot_divide(64,10,pPriv->ecb); + Dot_divide(64, 10, pPriv->ecb); return OKOK; } else { self->iErrorCode = BADFREQ; @@ -506,59 +533,65 @@ static int ECBSet(struct __COUNTER *self, char *name, return HWFault; } } + /*===================================================================*/ -static int ECBGet(struct __COUNTER *self, char *name, - int iCter, float *fVal){ +static int ECBGet(struct __COUNTER *self, char *name, + int iCter, float *fVal) +{ pECBCounter pPriv = NULL; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); - if(strcmp(name,"prescaler") == 0){ - *fVal = (float)pPriv->prescaler[iCter]; + if (strcmp(name, "prescaler") == 0) { + *fVal = (float) pPriv->prescaler[iCter]; return OKOK; - } else if(strcmp(name,"tfreq") == 0){ - *fVal = (float)pPriv->tfreq; + } else if (strcmp(name, "tfreq") == 0) { + *fVal = (float) pPriv->tfreq; return OKOK; - } else{ + } else { self->iErrorCode = UNKNOWNPAR; return HWFault; } -} +} + /*=====================================================================*/ -static int ECBSend(struct __COUNTER *self, char *text, - char *reply, int replylen){ - strncpy(reply,"ECB does not feast on ASCII strings, refused!", - replylen); +static int ECBSend(struct __COUNTER *self, char *text, + char *reply, int replylen) +{ + strncpy(reply, "ECB does not feast on ASCII strings, refused!", + replylen); return OKOK; } + /*====================================================================*/ -pCounterDriver MakeECBCounter(char *ecb){ +pCounterDriver MakeECBCounter(char *ecb) +{ pECBCounter pPriv = NULL; pCounterDriver self = NULL; int i; /* - memory for everybody - */ - self = CreateCounterDriver("ecb","ecb"); - pPriv = (pECBCounter)malloc(sizeof(ECBCounter)); - if(self == NULL || pPriv == NULL){ + memory for everybody + */ + self = CreateCounterDriver("ecb", "ecb"); + pPriv = (pECBCounter) malloc(sizeof(ECBCounter)); + if (self == NULL || pPriv == NULL) { return NULL; } - memset(pPriv,0,sizeof(ECBCounter)); + memset(pPriv, 0, sizeof(ECBCounter)); /* - initialize private data structure - */ - pPriv->ecb = (pECB)FindCommandData(pServ->pSics,ecb,"ECB"); - if(pPriv->ecb == NULL){ + initialize private data structure + */ + pPriv->ecb = (pECB) FindCommandData(pServ->pSics, ecb, "ECB"); + if (pPriv->ecb == NULL) { DeleteCounterDriver(self); free(pPriv); return NULL; } - for(i = 0; i < 8; i++){ + for (i = 0; i < 8; i++) { pPriv->prescaler[i] = 1; } pPriv->tfreq = 1000; @@ -566,19 +599,19 @@ pCounterDriver MakeECBCounter(char *ecb){ /* - assign function pointers - */ - self->GetStatus = ECBGetStatus; - self->Start = ECBStart; - self->Pause = ECBPause; - self->Continue = ECBContinue; - self->Halt = ECBHalt; - self->ReadValues = ECBTransfer; - self->GetError = ECBGetError; + assign function pointers + */ + self->GetStatus = ECBGetStatus; + self->Start = ECBStart; + self->Pause = ECBPause; + self->Continue = ECBContinue; + self->Halt = ECBHalt; + self->ReadValues = ECBTransfer; + self->GetError = ECBGetError; self->TryAndFixIt = ECBFixIt; - self->Set = ECBSet; - self->Get = ECBGet; - self->Send = ECBSend; + self->Set = ECBSet; + self->Get = ECBGet; + self->Send = ECBSend; self->KillPrivate = NULL; self->pData = pPriv; diff --git a/ecbcounter.h b/ecbcounter.h index eb12145d..cbfad223 100644 --- a/ecbcounter.h +++ b/ecbcounter.h @@ -12,6 +12,6 @@ #include "countdriv.h" pCounterDriver MakeECBCounter(char *ecb); -void KillECBCounter(CounterDriver *pDriv); +void KillECBCounter(CounterDriver * pDriv); #endif diff --git a/ecode.c b/ecode.c index 50c7d552..d8ceb081 100644 --- a/ecode.c +++ b/ecode.c @@ -7,20 +7,19 @@ #ifndef ERRSTAT #define ERRSTAT - static char *pErrStat[] = { - " ", - "OK", - "HWIdle", - "HWBusy", - "HWFault", - "HWPosFault", - "HWCrash", - "Out of memory", - "No Beam", - "Paused", - NULL - }; - - -#endif +static char *pErrStat[] = { + " ", + "OK", + "HWIdle", + "HWBusy", + "HWFault", + "HWPosFault", + "HWCrash", + "Out of memory", + "No Beam", + "Paused", + NULL +}; + +#endif diff --git a/emon.c b/emon.c index 554c90d6..41df1127 100644 --- a/emon.c +++ b/emon.c @@ -39,7 +39,7 @@ #include #include #include -#include /* for DString */ +#include /* for DString */ #include "fortify.h" #include "lld.h" #include "sics.h" @@ -47,335 +47,316 @@ #include "emon.h" #include "event.h" /*--------------------------------------------------------------------------*/ - pEnvMon CreateEnvMon(void) - { - pEnvMon pNew = NULL; - - pNew = (pEnvMon)malloc(sizeof(EnvMon)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(EnvMon)); - - pNew->pDes = CreateDescriptor("Environment Monitor"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - pNew->iList = LLDcreate(sizeof(EVEntry)); - if(pNew->iList < 0) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - } - return pNew; - } -/*---------------------------------------------------------------------------*/ - void DeleteEnvMon(void *pData) - { - pEnvMon self; - int iRet; - EVEntry sEntry; - - self = (pEnvMon)pData; - assert(self); - - - /* remove all the names */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sEntry); - if(sEntry.pName) - { - free(sEntry.pName); - sEntry.pName = NULL; - } - iRet = LLDnodePtr2Next(self->iList); - } - /* remove list */ - LLDdelete(self->iList); - - /* remove descriptor */ - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - free(self); - } -/*---------------------------------------------------------------------------*/ - int EVRegisterController(pEnvMon self, char *pName, void *pData, - SConnection *pCon) - { - EVEntry sEntry; - char pBueffel[512]; - - assert(self); - assert(pData); - assert(pCon); - - sEntry.pDum = (pDummy)pData; - sEntry.pInter = sEntry.pDum->pDescriptor->GetInterface(pData, - ENVIRINTERFACE); - if(sEntry.pInter == NULL) - { - sprintf(pBueffel,"ERROR: cannot register %s, no environment interface", - pName); - SCWrite(pCon,pBueffel,eError); - return 0; - } - sEntry.pName = strdup(pName); - - LLDnodeAppendFrom(self->iList,&sEntry); - return 1; - } -/*------------------------------------------------------------------------*/ - int EVUnregister(pEnvMon self, char *pName) - { - EVEntry sEntry; - int iRet; +pEnvMon CreateEnvMon(void) +{ + pEnvMon pNew = NULL; - assert(self); - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList, &sEntry); - if(strcmp(sEntry.pName, pName) == 0) - { - free(sEntry.pName); - LLDnodeDelete(self->iList); - return 1; - } - iRet = LLDnodePtr2Next(self->iList); - } - return 0; - } -/*---------------------------------------------------------------------------*/ - static int EVMonitorSingle(pEnvMon self, EVEntry sEntry) - { - EVMode eMode; - int iRet, iStatus; - - eMode = sEntry.pInter->GetMode(sEntry.pDum); - if(eMode == EVMonitor) - { - iRet = sEntry.pInter->IsInTolerance(sEntry.pDum); - if(iRet == 0) - { - iStatus = sEntry.pInter->HandleError(sEntry.pDum); - return 0; - } - } - return 1; + pNew = (pEnvMon) malloc(sizeof(EnvMon)); + if (!pNew) { + return NULL; } + memset(pNew, 0, sizeof(EnvMon)); + + pNew->pDes = CreateDescriptor("Environment Monitor"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + pNew->iList = LLDcreate(sizeof(EVEntry)); + if (pNew->iList < 0) { + DeleteDescriptor(pNew->pDes); + free(pNew); + return NULL; + } + return pNew; +} + +/*---------------------------------------------------------------------------*/ +void DeleteEnvMon(void *pData) +{ + pEnvMon self; + int iRet; + EVEntry sEntry; + + self = (pEnvMon) pData; + assert(self); + + + /* remove all the names */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sEntry); + if (sEntry.pName) { + free(sEntry.pName); + sEntry.pName = NULL; + } + iRet = LLDnodePtr2Next(self->iList); + } + /* remove list */ + LLDdelete(self->iList); + + /* remove descriptor */ + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + free(self); +} + +/*---------------------------------------------------------------------------*/ +int EVRegisterController(pEnvMon self, char *pName, void *pData, + SConnection * pCon) +{ + EVEntry sEntry; + char pBueffel[512]; + + assert(self); + assert(pData); + assert(pCon); + + sEntry.pDum = (pDummy) pData; + sEntry.pInter = sEntry.pDum->pDescriptor->GetInterface(pData, + ENVIRINTERFACE); + if (sEntry.pInter == NULL) { + sprintf(pBueffel, + "ERROR: cannot register %s, no environment interface", pName); + SCWrite(pCon, pBueffel, eError); + return 0; + } + sEntry.pName = strdup(pName); + + LLDnodeAppendFrom(self->iList, &sEntry); + return 1; +} + +/*------------------------------------------------------------------------*/ +int EVUnregister(pEnvMon self, char *pName) +{ + EVEntry sEntry; + int iRet; + + assert(self); + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sEntry); + if (strcmp(sEntry.pName, pName) == 0) { + free(sEntry.pName); + LLDnodeDelete(self->iList); + return 1; + } + iRet = LLDnodePtr2Next(self->iList); + } + return 0; +} + +/*---------------------------------------------------------------------------*/ +static int EVMonitorSingle(pEnvMon self, EVEntry sEntry) +{ + EVMode eMode; + int iRet, iStatus; + + eMode = sEntry.pInter->GetMode(sEntry.pDum); + if (eMode == EVMonitor) { + iRet = sEntry.pInter->IsInTolerance(sEntry.pDum); + if (iRet == 0) { + iStatus = sEntry.pInter->HandleError(sEntry.pDum); + return 0; + } + } + return 1; +} + /*--------------------------------------------------------------------------*/ - int EVMonitorControllers(pEnvMon self) - { - int iRet, status; - int iRes = 1; - EVEntry sEntry; - - assert(self); - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sEntry); - status = EVMonitorSingle(self, sEntry); - if(status != 1) - { - iRes = 0; - } - iRet = LLDnodePtr2Next(self->iList); - } - return iRes; +int EVMonitorControllers(pEnvMon self) +{ + int iRet, status; + int iRes = 1; + EVEntry sEntry; + + assert(self); + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sEntry); + status = EVMonitorSingle(self, sEntry); + if (status != 1) { + iRes = 0; + } + iRet = LLDnodePtr2Next(self->iList); } + return iRes; +} + /*---------------------------------------------------------------------------*/ - int EVList(pEnvMon self, SConnection *pCon) - { - int iRet; - float fVal; - Tcl_DString xString, *pResult; - pIDrivable pDriv; - EVEntry sEntry; - EVMode eMode; - char pNumber[30]; - char *pPtr; - - assert(self); - assert(pCon); - - pResult = &xString; - Tcl_DStringInit(pResult); - Tcl_DStringAppend(pResult,"EMON={",-1); - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sEntry); - pDriv = sEntry.pDum->pDescriptor->GetInterface(sEntry.pDum, - DRIVEID); - assert(pDriv); /* a controller must have a drivable and - a environment interface! */ - fVal = pDriv->GetValue(sEntry.pDum,pCon); - sprintf(pNumber,",%f,",fVal); - eMode = sEntry.pInter->GetMode(sEntry.pDum); - Tcl_DStringAppend(pResult,sEntry.pName,-1); - Tcl_DStringAppend(pResult,pNumber,-1); - switch(eMode) - { - case EVIdle: - Tcl_DStringAppend(pResult,"Idle",-1); - break; - case EVDrive: - Tcl_DStringAppend(pResult,"Driving",-1); - break; - case EVMonitor: - Tcl_DStringAppend(pResult,"In Monitor",-1); - break; - case EVError: - Tcl_DStringAppend(pResult,"Out of range",-1); - break; - } - Tcl_DStringAppend(pResult,";\n",-1); - iRet = LLDnodePtr2Next(self->iList); - } - Tcl_DStringAppend(pResult,"}",-1); - pPtr = Tcl_DStringValue(pResult); - SCWrite(pCon,pPtr,eValue); - Tcl_DStringFree(pResult); - return 1; +int EVList(pEnvMon self, SConnection * pCon) +{ + int iRet; + float fVal; + Tcl_DString xString, *pResult; + pIDrivable pDriv; + EVEntry sEntry; + EVMode eMode; + char pNumber[30]; + char *pPtr; + + assert(self); + assert(pCon); + + pResult = &xString; + Tcl_DStringInit(pResult); + Tcl_DStringAppend(pResult, "EMON={", -1); + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sEntry); + pDriv = sEntry.pDum->pDescriptor->GetInterface(sEntry.pDum, DRIVEID); + assert(pDriv); /* a controller must have a drivable and + a environment interface! */ + fVal = pDriv->GetValue(sEntry.pDum, pCon); + sprintf(pNumber, ",%f,", fVal); + eMode = sEntry.pInter->GetMode(sEntry.pDum); + Tcl_DStringAppend(pResult, sEntry.pName, -1); + Tcl_DStringAppend(pResult, pNumber, -1); + switch (eMode) { + case EVIdle: + Tcl_DStringAppend(pResult, "Idle", -1); + break; + case EVDrive: + Tcl_DStringAppend(pResult, "Driving", -1); + break; + case EVMonitor: + Tcl_DStringAppend(pResult, "In Monitor", -1); + break; + case EVError: + Tcl_DStringAppend(pResult, "Out of range", -1); + break; + } + Tcl_DStringAppend(pResult, ";\n", -1); + iRet = LLDnodePtr2Next(self->iList); } + Tcl_DStringAppend(pResult, "}", -1); + pPtr = Tcl_DStringValue(pResult); + SCWrite(pCon, pPtr, eValue); + Tcl_DStringFree(pResult); + return 1; +} + /*-------------------------------------------------------------------------- The Environment Monitor understands a few commands: list : list the current state of affairs register name : registers name as a controller to emon unregister name : removes name from emon ----------------------------------------------------------------------------*/ - int EVWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pEnvMon self = NULL; - char pBueffel[512]; - int iRet; - CommandList *pCom = NULL; - - self = (pEnvMon)pData; - assert(self); - assert(pCon); - assert(pSics); +---------------------------------------------------------------------------*/ +int EVWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pEnvMon self = NULL; + char pBueffel[512]; + int iRet; + CommandList *pCom = NULL; - argtolower(argc,argv); - if(argc < 2) - { - SCWrite(pCon,"ERROR: Insufficient arguments specified for emon",eError); - return 0; - } - - if(strcmp(argv[1],"list") == 0) /* list command */ - { - EVList(self,pCon); - return 1; - } - else if(strcmp(argv[1],"register") == 0) - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: Insufficient arguments specified for emon register",eError); - return 0; - } - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: Insufficient privilege to register",eError); - return 0; - } - pCom = FindCommand(pSics,argv[2]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: object %s not found, not registered", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return EVRegisterController(self,argv[2],pCom->pData,pCon); - } - else if(strcmp(argv[1],"unregister") == 0) - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: Insufficient arguments specified for emon unregister",eError); - return 0; - } - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: Insufficient privilege to unregister",eError); - return 0; - } - iRet = EVUnregister(self,argv[2]); - if(!iRet) - { - sprintf(pBueffel,"WARNING: %s not found in emon",argv[2]); - SCWrite(pCon,pBueffel,eWarning); - } - return 1; - } - else - { - sprintf(pBueffel,"ERROR: %s not recognized as command to emon", - argv[1]); - SCWrite(pCon,pBueffel,eError); - } - return 0; - } -/*---------------------------------------------------------------------------*/ - pEnvMon FindEMON(SicsInterp *pSics) - { - CommandList *pCom = NULL; - - assert(pSics); - - pCom = FindCommand(pSics,"emon"); - assert(pCom); - - return (pEnvMon)pCom->pData; + self = (pEnvMon) pData; + assert(self); + assert(pCon); + assert(pSics); + + argtolower(argc, argv); + if (argc < 2) { + SCWrite(pCon, "ERROR: Insufficient arguments specified for emon", + eError); + return 0; } -/*---------------------------------------------------------------------------*/ - int EnvMonTask(void *pData) - { - pEnvMon self = NULL; - - self = (pEnvMon)pData; - assert(self); - - if(self->iEnd) - { + + if (strcmp(argv[1], "list") == 0) { /* list command */ + EVList(self, pCon); + return 1; + } else if (strcmp(argv[1], "register") == 0) { + if (argc < 3) { + SCWrite(pCon, + "ERROR: Insufficient arguments specified for emon register", + eError); return 0; } - - EVMonitorControllers(self); + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: Insufficient privilege to register", eError); + return 0; + } + pCom = FindCommand(pSics, argv[2]); + if (!pCom) { + sprintf(pBueffel, "ERROR: object %s not found, not registered", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return EVRegisterController(self, argv[2], pCom->pData, pCon); + } else if (strcmp(argv[1], "unregister") == 0) { + if (argc < 3) { + SCWrite(pCon, + "ERROR: Insufficient arguments specified for emon unregister", + eError); + return 0; + } + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: Insufficient privilege to unregister", eError); + return 0; + } + iRet = EVUnregister(self, argv[2]); + if (!iRet) { + sprintf(pBueffel, "WARNING: %s not found in emon", argv[2]); + SCWrite(pCon, pBueffel, eWarning); + } return 1; + } else { + sprintf(pBueffel, "ERROR: %s not recognized as command to emon", + argv[1]); + SCWrite(pCon, pBueffel, eError); } + return 0; +} + +/*---------------------------------------------------------------------------*/ +pEnvMon FindEMON(SicsInterp * pSics) +{ + CommandList *pCom = NULL; + + assert(pSics); + + pCom = FindCommand(pSics, "emon"); + assert(pCom); + + return (pEnvMon) pCom->pData; +} + +/*---------------------------------------------------------------------------*/ +int EnvMonTask(void *pData) +{ + pEnvMon self = NULL; + + self = (pEnvMon) pData; + assert(self); + + if (self->iEnd) { + return 0; + } + + EVMonitorControllers(self); + return 1; +} + /*------------------------------------------------------------------------*/ - void EnvMonSignal(void *pUser, int iSignal, void *pEventData) - { - pEnvMon self = NULL; - int *iInt; - - self = (pEnvMon)pUser; - assert(self); - iInt = (int *)pEventData; - - if(iSignal == SICSINT) - { - iInt = (int *)pEventData; - if(*iInt == eEndServer) - { - self->iEnd = 1; - } - } +void EnvMonSignal(void *pUser, int iSignal, void *pEventData) +{ + pEnvMon self = NULL; + int *iInt; + + self = (pEnvMon) pUser; + assert(self); + iInt = (int *) pEventData; + + if (iSignal == SICSINT) { + iInt = (int *) pEventData; + if (*iInt == eEndServer) { + self->iEnd = 1; + } } - +} diff --git a/emon.h b/emon.h index 816e7428..3a01e7b4 100644 --- a/emon.h +++ b/emon.h @@ -14,30 +14,30 @@ ----------------------------------------------------------------------------*/ #ifndef SICSEMON #define SICSEMON - typedef struct __EnvMon *pEnvMon; +typedef struct __EnvMon *pEnvMon; /*-------------------------------------------------------------------------*/ #line 85 "emonitor.w" - pEnvMon CreateEnvMon(void); - void DeleteEnvMon(void *pData); +pEnvMon CreateEnvMon(void); +void DeleteEnvMon(void *pData); - int EVRegisterController(pEnvMon self, char *pName, void *pData, - SConnection *pCon); - int EVUnregister(pEnvMon self, char *name); - - int EVMonitorControllers(pEnvMon self); +int EVRegisterController(pEnvMon self, char *pName, void *pData, + SConnection * pCon); +int EVUnregister(pEnvMon self, char *name); - int EVList(pEnvMon self, SConnection *pCon); +int EVMonitorControllers(pEnvMon self); - int EVWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int EVList(pEnvMon self, SConnection * pCon); - pEnvMon FindEMON(SicsInterp *pSics); - - int EnvMonTask(void *pEv); - void EnvMonSignal(void *pEndv, int iSignal, void *pSigData); +int EVWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +pEnvMon FindEMON(SicsInterp * pSics); + +int EnvMonTask(void *pEv); +void EnvMonSignal(void *pEndv, int iSignal, void *pSigData); #line 164 "emonitor.w" diff --git a/errormsg.c b/errormsg.c index d50cb3d6..59c5429b 100644 --- a/errormsg.c +++ b/errormsg.c @@ -5,9 +5,10 @@ #include "errormsg.h" /* compare two strings for euqality, ignoring text within square brackets */ -int ErrEqual(char *str1, char *str2) { +int ErrEqual(char *str1, char *str2) +{ char *p; - + while (*str1 != '\0' || *str2 != '\0') { if (*str1 != *str2) { return 0; @@ -25,14 +26,15 @@ int ErrEqual(char *str1, char *str2) { return 1; } -ErrMsg *ErrPutMsg(ErrMsg *dump, char *fmt, ...) { +ErrMsg *ErrPutMsg(ErrMsg * dump, char *fmt, ...) +{ ErrMsg *m = NULL; ErrMsg **last = NULL; va_list ap; char buf[256]; char *text = NULL; int l; - + va_start(ap, fmt); l = vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); @@ -48,18 +50,20 @@ ErrMsg *ErrPutMsg(ErrMsg *dump, char *fmt, ...) { last = &dump; for (m = dump; m != NULL; m = m->next) { if (ErrEqual(text, m->text)) { - *last = m->next; /* remove found item from list */ + *last = m->next; /* remove found item from list */ break; } last = &m->next; } - if (m == NULL) { /* make a new item */ - if (text == buf) text = strdup(buf); + if (m == NULL) { /* make a new item */ + if (text == buf) + text = strdup(buf); m = calloc(1, sizeof(*m)); m->text = text; m->cnt = 1; } else { - if (text != buf) free(text); + if (text != buf) + free(text); m->cnt++; } m->next = dump; diff --git a/errormsg.h b/errormsg.h index 470ebd5e..80b24c89 100644 --- a/errormsg.h +++ b/errormsg.h @@ -27,6 +27,6 @@ typedef struct ErrMsg { * \param fmt the format for the message * \return the new error message list head */ -ErrMsg *ErrPutMsg(ErrMsg *dump, char *fmt, ...); +ErrMsg *ErrPutMsg(ErrMsg * dump, char *fmt, ...); #endif diff --git a/eurodriv.h b/eurodriv.h index 132856fa..e220fb76 100644 --- a/eurodriv.h +++ b/eurodriv.h @@ -10,14 +10,14 @@ ---------------------------------------------------------------------------*/ #ifndef EURODRIV #define EURODRIV - pEVDriver CreateEURODriv(int argc, char *argv[]); +pEVDriver CreateEURODriv(int argc, char *argv[]); /* - these are hooks to implement further functionality which, - I'am sure, Joachim Kohlbrecher will request. - */ - int EuroGetParameter(void **pData, char *pPar, int iLen, float *fVal); - int EuroSetParameter(void **pData, char *pPar, int iLen, - char *pFormat, float fVal); - -#endif + these are hooks to implement further functionality which, + I'am sure, Joachim Kohlbrecher will request. + */ +int EuroGetParameter(void **pData, char *pPar, int iLen, float *fVal); +int EuroSetParameter(void **pData, char *pPar, int iLen, + char *pFormat, float fVal); + +#endif diff --git a/evcontroller.c b/evcontroller.c index 41707d08..e0a7384f 100644 --- a/evcontroller.c +++ b/evcontroller.c @@ -68,619 +68,576 @@ #include "site.h" #include "commandlog.h" /*--------------------- Functions needed to implement interfaces -----------*/ - static long EVIDrive(void *pData, SConnection *pCon, float fVal) - { - pEVControl self = NULL; - int iRet, iCode, i, iFix, savedStatus; - char pError[132], pBueffel[256]; - Tcl_Interp *pTcl = NULL; +static long EVIDrive(void *pData, SConnection * pCon, float fVal) +{ + pEVControl self = NULL; + int iRet, iCode, i, iFix, savedStatus; + char pError[132], pBueffel[256]; + Tcl_Interp *pTcl = NULL; - self = (pEVControl)pData; - assert(self); - assert(pCon); - - if (self->runScript != NULL) { - savedStatus = GetStatus(); - SetStatus(eBatch); - pTcl = InterpGetTcl(pServ->pSics); - snprintf(pBueffel, sizeof(pBueffel), "%s %f", self->runScript, fVal); - iRet = Tcl_Eval(pTcl,pBueffel); - SetStatus(savedStatus); - if(iRet != TCL_OK) - { - SCPrintf(pCon, eError, - "ERROR: %s while processing runscript for %s", - pTcl->result,self->pName); - } - } + self = (pEVControl) pData; + assert(self); + assert(pCon); - self->fTarget = fVal; - self->eMode = EVDrive; - self->iStop = 0; - self->start = time(NULL); - self->lastt = 0; - self->iWarned = 0; - if(self->conn != NULL){ - SCDeleteConnection(self->conn); - } - self->conn = SCCopyConnection(pCon); - if(self->conn == NULL){ - SCWrite(pCon,"ERROR: out of memory in EVIDrive", eError); - return 0; - } - - /* try at least three times to do it */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->SetValue(self->pDriv,fVal); - if(!iRet) - { - self->pDriv->GetError(self->pDriv,&iCode, pError,131); - iFix = self->pDriv->TryFixIt(self->pDriv,iCode); - switch(iFix) - { - case DEVOK: - return 1; - break; - case DEVFAULT: - sprintf(pBueffel,"ERROR: %s",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - case DEVREDO: - sprintf(pBueffel,"WARNING: Fixing problem %s",pError); - SCWrite(pCon,pBueffel,eWarning); - break; - } - } - else - { - return 1; - } - } - SCWrite(pCon,"ERROR: Failed to fix previous problems, Device Error", - eError); - return 0; - } -/*---------------------------------------------------------------------------*/ - static float EVIGet(void *pData, SConnection *pCon) - { - pEVControl self = NULL; - int iRet, iCode, i, iFix; - char pError[132], pBueffel[256]; - float fPos = -999.; - int iPendingCount = 0; - - self = (pEVControl)pData; - assert(self); - assert(pCon); - - /* try at least three times to do it */ - for(i = 0; i < 5; i++) - { - iRet = self->pDriv->GetValue(self->pDriv,&fPos); - if(iRet == 0) - { - self->pDriv->GetError(self->pDriv,&iCode, pError,131); - iFix = self->pDriv->TryFixIt(self->pDriv,iCode); - switch(iFix) - { - case DEVOK: - return fPos; - break; - case DEVFAULT: - sprintf(pBueffel,"ERROR: %s",pError); - SCWrite(pCon,pBueffel,eError); - return -999.; - case DEVREDO: - sprintf(pBueffel,"WARNING: Fixing problem %s",pError); - SCWrite(pCon,pBueffel,eWarning); - break; - } - } - else if(iRet == -1 ) /* pending */ - { - i--; - iPendingCount++; - if(iPendingCount > 300) - { - SCWrite(pCon,"ERROR: cannot get data from socket",eError); - return -999.; - } - } - else - { - return fPos; - } - } - SCWrite(pCon,"ERROR: Failed to fix previous problems, Device Error", - eError); - return -999.; + if (self->runScript != NULL) { + savedStatus = GetStatus(); + SetStatus(eBatch); + pTcl = InterpGetTcl(pServ->pSics); + snprintf(pBueffel, sizeof(pBueffel), "%s %f", self->runScript, fVal); + iRet = Tcl_Eval(pTcl, pBueffel); + SetStatus(savedStatus); + if (iRet != TCL_OK) { + SCPrintf(pCon, eError, + "ERROR: %s while processing runscript for %s", + pTcl->result, self->pName); + } } - static void notifyStatus(pEVControl self, SConnection *pCon, int status) { - if (self->pDrivInt->drivableStatus!=status) { - ((SConnection *)pCon)->conEventType=STATUS; - ((SConnection *)pCon)->conStatus=status; - SCWrite(pCon, "", eEvent); - self->pDrivInt->drivableStatus=status; - } + self->fTarget = fVal; + self->eMode = EVDrive; + self->iStop = 0; + self->start = time(NULL); + self->lastt = 0; + self->iWarned = 0; + if (self->conn != NULL) { + SCDeleteConnection(self->conn); + } + self->conn = SCCopyConnection(pCon); + if (self->conn == NULL) { + SCWrite(pCon, "ERROR: out of memory in EVIDrive", eError); + return 0; } -/*---------------------------------------------------------------------------*/ - static int EVIStatus(void *pData, SConnection *pCon) - { - pEVControl self = NULL; - float fPos, fDelta = .0; - int iRet, iCode, iFix; - char pBueffel[256], pError[132]; - static int callCount; - time_t now, tmo; - float tol; - - self = (pEVControl)pData; - assert(self); - assert(pCon); - - /* go to idle when stopped */ - if(self->iStop) - { - notifyStatus(self, pCon, HWIdle); - return HWIdle; - } - - /* get the current position */ - - iRet = self->pDriv->GetValues(self->pDriv,&self->fTarget,&fPos,&fDelta); - if(iRet == 0) - { - self->pDriv->GetError(self->pDriv,&iCode, pError,131); - iFix = self->pDriv->TryFixIt(self->pDriv,iCode); - switch(iFix) - { - case DEVOK: - return HWBusy; - break; - case DEVFAULT: - sprintf(pBueffel,"ERROR: %s",pError); - SCWrite(pCon,pBueffel,eError); - notifyStatus(self, pCon, HWFault); - return HWFault; - case DEVREDO: - sprintf(pBueffel,"WARNING: Fixing problem %s",pError); - SCWrite(pCon,pBueffel,eWarning); - notifyStatus(self, pCon, HWBusy); - return HWBusy; - break; - } - } - else if(iRet == -1 ) /* pending */ - { - notifyStatus(self, pCon, HWBusy); - return HWBusy; - } - - if(fPos < -990.) - { - sprintf(pBueffel,"ERROR: %s cannot read its current value", - self->pName); - SCWrite(pCon,pBueffel,eError); - self->eMode = EVIdle; - notifyStatus(self, pCon, HWFault); - return HWFault; - } - - if(fDelta < 0.) - { - fDelta = - fDelta; - } - - /* handle callback */ - callCount++; - if(callCount >= 10) - { - sprintf(pBueffel,"%s = %g", self->pName, fPos); - InvokeCallBack(self->pCall, VALUECHANGE,pBueffel); - callCount = 0; - } - - now = time(NULL); - tmo = (int)(ObVal(self->pParam, MAXWAIT)); - /* based on this: logic ! */ - if (tmo>0 && now > self->start+tmo ) /* time out */ - { - sprintf(pBueffel,"ERROR: wait time limit reached on %s", - self->pName); - SCWrite(pCon,pBueffel,eError); - self->eMode = EVMonitor; - notifyStatus(self, pCon, HWIdle); - return HWIdle; - } - tol = ObVal(self->pParam, TOLERANCE); - if (self->lastt > 0) { /* increase tol for hysteresis */ - tol=tol*1.1001; - } - tmo = (int)(ObVal(self->pParam, SETTLE)); - if(fDelta <= tol) /* inside tolerance */ - { - if (self->lastt <= 0) /* lastt negative: -seconds already waited */ - { - self->lastt += now; - if (tmo>0) - { - sprintf(pBueffel,"%s inside tolerance, wait %.2f sec to settle", - self->pName, (self->lastt + tmo - now)*1.0); - SCWrite(pCon,pBueffel,eLog); - } - notifyStatus(self, pCon, HWBusy); - return HWBusy; - } - if (now > self->lastt + tmo) - { - self->eMode = EVMonitor; - notifyStatus(self, pCon, HWIdle); - return HWIdle; - } - notifyStatus(self, pCon, HWBusy); - return HWBusy; - } - else - { - if (self->lastt > 0) { /* save time already waited */ - if (tmo > 0) { - sprintf(pBueffel,"%s outside tolerance, settling time suspended", - self->pName); - SCWrite(pCon,pBueffel,eLog); - } - self->lastt -= now; - } - notifyStatus(self, pCon, HWBusy); - return HWBusy; - } - } -/*--------------------------------------------------------------------------*/ - static int EVILimits(void *pData, float fVal, char *pError, int iErrLen) - { - pEVControl self = NULL; - char pBueffel[256]; - - self = (pEVControl)pData; - assert(self); - - /* lower limit */ - if( fVal < ObVal(self->pParam, LOWLIMIT)) - { - sprintf(pBueffel,"ERROR: %g violates lower limit of device",fVal); - strncpy(pError,pBueffel,iErrLen); + /* try at least three times to do it */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->SetValue(self->pDriv, fVal); + if (!iRet) { + self->pDriv->GetError(self->pDriv, &iCode, pError, 131); + iFix = self->pDriv->TryFixIt(self->pDriv, iCode); + switch (iFix) { + case DEVOK: + return 1; + break; + case DEVFAULT: + sprintf(pBueffel, "ERROR: %s", pError); + SCWrite(pCon, pBueffel, eError); return 0; + case DEVREDO: + sprintf(pBueffel, "WARNING: Fixing problem %s", pError); + SCWrite(pCon, pBueffel, eWarning); + break; } - - /* upper limit */ - if( fVal > ObVal(self->pParam, UPLIMIT)) - { - sprintf(pBueffel,"ERROR: %g violates upper limit of device",fVal); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - - /* OK */ + } else { return 1; + } } -/*---------------------------------------------------------------------------*/ - static int EVIHalt(void *pData) - { - pEVControl self = NULL; - float fPos; - int iRet, iRes; - - self = (pEVControl)pData; - assert(self); + SCWrite(pCon, "ERROR: Failed to fix previous problems, Device Error", + eError); + return 0; +} - iRes = 1; - self->eMode = EVIdle; - self->iStop = 1; - - return iRes; - } +/*---------------------------------------------------------------------------*/ +static float EVIGet(void *pData, SConnection * pCon) +{ + pEVControl self = NULL; + int iRet, iCode, i, iFix; + char pError[132], pBueffel[256]; + float fPos = -999.; + int iPendingCount = 0; + + self = (pEVControl) pData; + assert(self); + assert(pCon); + + /* try at least three times to do it */ + for (i = 0; i < 5; i++) { + iRet = self->pDriv->GetValue(self->pDriv, &fPos); + if (iRet == 0) { + self->pDriv->GetError(self->pDriv, &iCode, pError, 131); + iFix = self->pDriv->TryFixIt(self->pDriv, iCode); + switch (iFix) { + case DEVOK: + return fPos; + break; + case DEVFAULT: + sprintf(pBueffel, "ERROR: %s", pError); + SCWrite(pCon, pBueffel, eError); + return -999.; + case DEVREDO: + sprintf(pBueffel, "WARNING: Fixing problem %s", pError); + SCWrite(pCon, pBueffel, eWarning); + break; + } + } else if (iRet == -1) { /* pending */ + i--; + iPendingCount++; + if (iPendingCount > 300) { + SCWrite(pCon, "ERROR: cannot get data from socket", eError); + return -999.; + } + } else { + return fPos; + } + } + SCWrite(pCon, "ERROR: Failed to fix previous problems, Device Error", + eError); + return -999.; +} + +static void notifyStatus(pEVControl self, SConnection * pCon, int status) +{ + if (self->pDrivInt->drivableStatus != status) { + ((SConnection *) pCon)->conEventType = STATUS; + ((SConnection *) pCon)->conStatus = status; + SCWrite(pCon, "", eEvent); + self->pDrivInt->drivableStatus = status; + } +} + +/*---------------------------------------------------------------------------*/ +static int EVIStatus(void *pData, SConnection * pCon) +{ + pEVControl self = NULL; + float fPos, fDelta = .0; + int iRet, iCode, iFix; + char pBueffel[256], pError[132]; + static int callCount; + time_t now, tmo; + float tol; + + self = (pEVControl) pData; + assert(self); + assert(pCon); + + /* go to idle when stopped */ + if (self->iStop) { + notifyStatus(self, pCon, HWIdle); + return HWIdle; + } + + /* get the current position */ + + iRet = + self->pDriv->GetValues(self->pDriv, &self->fTarget, &fPos, &fDelta); + if (iRet == 0) { + self->pDriv->GetError(self->pDriv, &iCode, pError, 131); + iFix = self->pDriv->TryFixIt(self->pDriv, iCode); + switch (iFix) { + case DEVOK: + return HWBusy; + break; + case DEVFAULT: + sprintf(pBueffel, "ERROR: %s", pError); + SCWrite(pCon, pBueffel, eError); + notifyStatus(self, pCon, HWFault); + return HWFault; + case DEVREDO: + sprintf(pBueffel, "WARNING: Fixing problem %s", pError); + SCWrite(pCon, pBueffel, eWarning); + notifyStatus(self, pCon, HWBusy); + return HWBusy; + break; + } + } else if (iRet == -1) { /* pending */ + notifyStatus(self, pCon, HWBusy); + return HWBusy; + } + + if (fPos < -990.) { + sprintf(pBueffel, "ERROR: %s cannot read its current value", + self->pName); + SCWrite(pCon, pBueffel, eError); + self->eMode = EVIdle; + notifyStatus(self, pCon, HWFault); + return HWFault; + } + + if (fDelta < 0.) { + fDelta = -fDelta; + } + + /* handle callback */ + callCount++; + if (callCount >= 10) { + sprintf(pBueffel, "%s = %g", self->pName, fPos); + InvokeCallBack(self->pCall, VALUECHANGE, pBueffel); + callCount = 0; + } + + now = time(NULL); + tmo = (int) (ObVal(self->pParam, MAXWAIT)); + /* based on this: logic ! */ + if (tmo > 0 && now > self->start + tmo) { /* time out */ + sprintf(pBueffel, "ERROR: wait time limit reached on %s", self->pName); + SCWrite(pCon, pBueffel, eError); + self->eMode = EVMonitor; + notifyStatus(self, pCon, HWIdle); + return HWIdle; + } + tol = ObVal(self->pParam, TOLERANCE); + if (self->lastt > 0) { /* increase tol for hysteresis */ + tol = tol * 1.1001; + } + tmo = (int) (ObVal(self->pParam, SETTLE)); + if (fDelta <= tol) { /* inside tolerance */ + if (self->lastt <= 0) { /* lastt negative: -seconds already waited */ + self->lastt += now; + if (tmo > 0) { + sprintf(pBueffel, "%s inside tolerance, wait %.2f sec to settle", + self->pName, (self->lastt + tmo - now) * 1.0); + SCWrite(pCon, pBueffel, eLog); + } + notifyStatus(self, pCon, HWBusy); + return HWBusy; + } + if (now > self->lastt + tmo) { + self->eMode = EVMonitor; + notifyStatus(self, pCon, HWIdle); + return HWIdle; + } + notifyStatus(self, pCon, HWBusy); + return HWBusy; + } else { + if (self->lastt > 0) { /* save time already waited */ + if (tmo > 0) { + sprintf(pBueffel, "%s outside tolerance, settling time suspended", + self->pName); + SCWrite(pCon, pBueffel, eLog); + } + self->lastt -= now; + } + notifyStatus(self, pCon, HWBusy); + return HWBusy; + } +} + +/*--------------------------------------------------------------------------*/ +static int EVILimits(void *pData, float fVal, char *pError, int iErrLen) +{ + pEVControl self = NULL; + char pBueffel[256]; + + self = (pEVControl) pData; + assert(self); + + /* lower limit */ + if (fVal < ObVal(self->pParam, LOWLIMIT)) { + sprintf(pBueffel, "ERROR: %g violates lower limit of device", fVal); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + + /* upper limit */ + if (fVal > ObVal(self->pParam, UPLIMIT)) { + sprintf(pBueffel, "ERROR: %g violates upper limit of device", fVal); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + + /* OK */ + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int EVIHalt(void *pData) +{ + pEVControl self = NULL; + float fPos; + int iRet, iRes; + + self = (pEVControl) pData; + assert(self); + + iRes = 1; + self->eMode = EVIdle; + self->iStop = 1; + + return iRes; +} /*---------------------------- Error Handlers --------------------------------*/ -static void ErrWrite(char *txt, SConnection *conn) +static void ErrWrite(char *txt, SConnection * conn) { - pExeList pExe; - SConnection *pCon = NULL; + pExeList pExe; + SConnection *pCon = NULL; - pExe = GetExecutor(); - pCon = GetExeOwner(pExe); + pExe = GetExecutor(); + pCon = GetExeOwner(pExe); - if (pCon) - { - SCWrite(pCon,txt,eLog); - } - else - { - SCWrite(conn, txt, eLog); - } + if (pCon) { + SCWrite(pCon, txt, eLog); + } else { + SCWrite(conn, txt, eLog); + } } + /*-----------------------------------------------------------------------*/ static void ErrReport(pEVControl self) { - float fPos =.0, fDelta =.0; - char pBueffel[256]; - - self->pDriv->GetValues(self->pDriv,&self->fTarget,&fPos,&fDelta); - if(self->iWarned == 0) - { - sprintf(pBueffel,"WARNING: %s is out of range by %g", - self->pName,fDelta); - ErrWrite(pBueffel, self->conn); - self->iWarned = 1; - } - } + float fPos = .0, fDelta = .0; + char pBueffel[256]; + + self->pDriv->GetValues(self->pDriv, &self->fTarget, &fPos, &fDelta); + if (self->iWarned == 0) { + sprintf(pBueffel, "WARNING: %s is out of range by %g", + self->pName, fDelta); + ErrWrite(pBueffel, self->conn); + self->iWarned = 1; + } +} + /*-------------------------------------------------------------------------*/ - static int ErrLazy(void *pData) - { - pEVControl self = NULL; +static int ErrLazy(void *pData) +{ + pEVControl self = NULL; - self = (pEVControl)pData; - assert(self); + self = (pEVControl) pData; + assert(self); + + ErrReport(self); + return 1; +} - ErrReport(self); - return 1; - } /*--------------------------------------------------------------------------*/ - static int ErrPause(void *pData) - { - pEVControl self = NULL; - pExeList pExe; - int iRet; - - self = (pEVControl)pData; - assert(self); +static int ErrPause(void *pData) +{ + pEVControl self = NULL; + pExeList pExe; + int iRet; - ErrReport(self); + self = (pEVControl) pData; + assert(self); + + ErrReport(self); + + pExe = GetExecutor(); + if (IsCounting(pExe)) { + SCWrite(GetExeOwner(pExe), "Pausing till OK", eLogError); + PauseExecution(pExe); + + /* wait till OK */ + iRet = 0; + while (iRet == 0 && IsCounting(pExe)) { + SicsWait(5); + iRet = self->pEnvir->IsInTolerance(self); + } + + /* OK now, continue */ + SetStatus(eEager); + self->iWarned = 0; + ContinueExecution(pExe); + return 1; + } + return 1; +} - pExe = GetExecutor(); - if(IsCounting(pExe)) - { - SCWrite(GetExeOwner(pExe),"Pausing till OK",eLogError); - PauseExecution(pExe); - - /* wait till OK */ - iRet = 0; - while(iRet == 0 && IsCounting(pExe) ) - { - SicsWait(5); - iRet = self->pEnvir->IsInTolerance(self); - } - - /* OK now, continue */ - SetStatus(eEager); - self->iWarned = 0; - ContinueExecution(pExe); - return 1; - } - return 1; - } /*--------------------------------------------------------------------------*/ - static int ErrScript(void *pData) - { - pEVControl self = NULL; - int iRet; - Tcl_Interp *pTcl = NULL; - pExeList pExe; - char pBueffel[256]; +static int ErrScript(void *pData) +{ + pEVControl self = NULL; + int iRet; + Tcl_Interp *pTcl = NULL; + pExeList pExe; + char pBueffel[256]; - self = (pEVControl)pData; - assert(self); + self = (pEVControl) pData; + assert(self); - ErrReport(self); + ErrReport(self); + + pExe = GetExecutor(); + if (self->errorScript != NULL) { + pTcl = InterpGetTcl(pServ->pSics); + iRet = Tcl_Eval(pTcl, self->errorScript); + if (iRet != TCL_OK) { + snprintf(pBueffel, 255, + "ERROR: %s while processing errorscript for %s", + pTcl->result, self->pName); + ErrWrite(pBueffel, self->conn); + } + /* + assume that everything is fine again after the script + returns + */ + self->eMode = EVMonitor; + self->iWarned = 0; + } else { + snprintf(pBueffel, 255, + "ERROR: script error handling requested for %s, but no script given", + self->pName); + ErrWrite(pBueffel, self->conn); + } + + return 1; +} - pExe = GetExecutor(); - if(self->errorScript != NULL) - { - pTcl = InterpGetTcl(pServ->pSics); - iRet = Tcl_Eval(pTcl,self->errorScript); - if(iRet != TCL_OK) - { - snprintf(pBueffel,255, - "ERROR: %s while processing errorscript for %s", - pTcl->result,self->pName); - ErrWrite(pBueffel, self->conn); - } - /* - assume that everything is fine again after the script - returns - */ - self->eMode = EVMonitor; - self->iWarned = 0; - } - else - { - snprintf(pBueffel,255, - "ERROR: script error handling requested for %s, but no script given", - self->pName); - ErrWrite(pBueffel, self->conn); - } - - return 1; - } /*---------------------------------------------------------------------------*/ - static int ErrInterrupt(void *pData) - { - pEVControl self = NULL; +static int ErrInterrupt(void *pData) +{ + pEVControl self = NULL; - self = (pEVControl)pData; - assert(self); + self = (pEVControl) pData; + assert(self); - ErrReport(self); + ErrReport(self); + + /* interrupt */ + SetInterrupt((int) ObVal(self->pParam, INTERRUPT)); + self->iWarned = 0; + return 1; +} - /* interrupt */ - SetInterrupt((int)ObVal(self->pParam,INTERRUPT)); - self->iWarned = 0; - return 1; - } /*---------------------------------------------------------------------------*/ - static int ErrRun(void *pData) - { - pEVControl self = NULL; - - self = (pEVControl)pData; - assert(self); +static int ErrRun(void *pData) +{ + pEVControl self = NULL; + + self = (pEVControl) pData; + assert(self); + + ErrReport(self); + + ErrWrite("Running to safe value", self->conn); + self->pDriv->SetValue(self->pDriv, ObVal(self->pParam, SAFEVALUE)); + self->eMode = EVIdle; + self->iWarned = 0; + return 1; +} - ErrReport(self); - - ErrWrite("Running to safe value", self->conn); - self->pDriv->SetValue(self->pDriv, ObVal(self->pParam,SAFEVALUE)); - self->eMode = EVIdle; - self->iWarned = 0; - return 1; - } /*---------------------------------------------------------------------------*/ - static int EVIErrHandler(void *pData) - { - pEVControl self = NULL; - int iRet, iHandler, iStatus; - - self = (pEVControl)pData; - assert(self); +static int EVIErrHandler(void *pData) +{ + pEVControl self = NULL; + int iRet, iHandler, iStatus; - /* select an error handler according to the variable set - in Controller - */ - iHandler = (int)ObVal(self->pParam, ERRORHANDLER); - self->eMode = EVError; - switch(iHandler) - { - case 0: /* no op */ - iStatus = ErrLazy(pData); - break; - case 1: /* Pause */ - iStatus = ErrPause(pData); - break; - case 2: /* Interrupt */ - iStatus = ErrInterrupt(pData); - break; - case 3: /* run to a safe place, put him into idle afterwards */ - iStatus = ErrRun(pData); - return iStatus; - break; - case 4: /* invoke a script */ - iStatus = ErrScript(pData); - return iStatus; - break; - default: - return 0; - - } - /* reset mode to monitor again! */ + self = (pEVControl) pData; + assert(self); + + /* select an error handler according to the variable set + in Controller + */ + iHandler = (int) ObVal(self->pParam, ERRORHANDLER); + self->eMode = EVError; + switch (iHandler) { + case 0: /* no op */ + iStatus = ErrLazy(pData); + break; + case 1: /* Pause */ + iStatus = ErrPause(pData); + break; + case 2: /* Interrupt */ + iStatus = ErrInterrupt(pData); + break; + case 3: /* run to a safe place, put him into idle afterwards */ + iStatus = ErrRun(pData); + return iStatus; + break; + case 4: /* invoke a script */ + iStatus = ErrScript(pData); + return iStatus; + break; + default: + return 0; + + } + /* reset mode to monitor again! */ + self->eMode = EVMonitor; + return iStatus; +} + +/*---------------------------------------------------------------------------*/ +static EVMode EVIGetMode(void *pData) +{ + pEVControl self = NULL; + + self = (pEVControl) pData; + assert(self); + + return self->eMode; +} + +/*--------------------------------------------------------------------------*/ +static int EVIIsInTolerance(void *pData) +{ + pEVControl self = NULL; + float fPos, fDelta; + int iRet, iCode, iStat; + char pError[132], pBueffel[512]; + pExeList pExe = NULL; + SConnection *pCon = NULL; + float tol; + + self = (pEVControl) pData; + assert(self); + + + iRet = + self->pDriv->GetValues(self->pDriv, &self->fTarget, &fPos, &fDelta); + if (iRet == 1) { + if (self->iLog) { + VarlogAdd(self->pLog, fPos); + } + if (fDelta < 0.) { + fDelta = -fDelta; + } + tol = ObVal(self->pParam, TOLERANCE); + if (self->iWarned == 0) + tol = tol * 1.1001; + if (fDelta <= tol) { self->eMode = EVMonitor; - return iStatus; - } -/*---------------------------------------------------------------------------*/ - static EVMode EVIGetMode(void *pData) - { - pEVControl self = NULL; - - self = (pEVControl)pData; - assert(self); - - return self->eMode; - } -/*--------------------------------------------------------------------------*/ - static int EVIIsInTolerance(void *pData) - { - pEVControl self = NULL; - float fPos, fDelta; - int iRet, iCode, iStat; - char pError[132], pBueffel[512]; - pExeList pExe = NULL; - SConnection *pCon = NULL; - float tol; - - self = (pEVControl)pData; - assert(self); - - - iRet = self->pDriv->GetValues(self->pDriv,&self->fTarget,&fPos,&fDelta); - if( iRet == 1 ) - { - if(self->iLog) - { - VarlogAdd(self->pLog, fPos); - } - if(fDelta < 0.) - { - fDelta = -fDelta; - } - tol = ObVal(self->pParam,TOLERANCE); - if (self->iWarned == 0) tol=tol*1.1001; - if(fDelta <= tol) - { - self->eMode = EVMonitor; - if(self->iWarned) - { - sprintf(pBueffel,"Environment device %s back in tolerances again", - self->pName); - ErrWrite(pBueffel, self->conn); - self->iWarned = 0; - } - return 1; - } - else - { - return 0; - } - /* deal with callbacks */ - self->callCount++; - if(self->callCount >= 20) - { - sprintf(pBueffel,"%s = %g", self->pName, fPos); - InvokeCallBack(self->pCall,VALUECHANGE, pBueffel); - self->callCount = 0; - } - } - else if(iRet == -1) /* pending */ - { - /* pending means OK to me */ - return 1; - } - else - { - /* break down of connection to a environment device has to be - considered a problem as well - */ - memset(pError,0,132*sizeof(char)); - self->pDriv->GetError(self->pDriv, &iCode,pError,131); - WriteToCommandLog("emon>> ",pError); - iStat = self->pDriv->TryFixIt(self->pDriv, iCode); - if( (iStat == DEVOK) || (iStat == DEVREDO) ) - { - return 1; /* effectively a redo in some time */ - } - else - { - return 0; - } + if (self->iWarned) { + sprintf(pBueffel, "Environment device %s back in tolerances again", + self->pName); + ErrWrite(pBueffel, self->conn); + self->iWarned = 0; } + return 1; + } else { return 0; - } + } + /* deal with callbacks */ + self->callCount++; + if (self->callCount >= 20) { + sprintf(pBueffel, "%s = %g", self->pName, fPos); + InvokeCallBack(self->pCall, VALUECHANGE, pBueffel); + self->callCount = 0; + } + } else if (iRet == -1) { /* pending */ + /* pending means OK to me */ + return 1; + } else { + /* break down of connection to a environment device has to be + considered a problem as well + */ + memset(pError, 0, 132 * sizeof(char)); + self->pDriv->GetError(self->pDriv, &iCode, pError, 131); + WriteToCommandLog("emon>> ", pError); + iStat = self->pDriv->TryFixIt(self->pDriv, iCode); + if ((iStat == DEVOK) || (iStat == DEVREDO)) { + return 1; /* effectively a redo in some time */ + } else { + return 0; + } + } + return 0; +} + /*-------------------------------------------------------------------------*/ - static void *EVIInterface(void *pData, int iCode) - { - pEVControl self = NULL; - - self = (pEVControl)pData; - assert(self); - - if(iCode == DRIVEID) - { - return self->pDrivInt; - } - else if(iCode == ENVIRINTERFACE) - { - return self->pEnvir; - } - return NULL; - } +static void *EVIInterface(void *pData, int iCode) +{ + pEVControl self = NULL; + + self = (pEVControl) pData; + assert(self); + + if (iCode == DRIVEID) { + return self->pDrivInt; + } else if (iCode == ENVIRINTERFACE) { + return self->pEnvir; + } + return NULL; +} + /*--------------------------------------------------------------------------*/ /* this routine is the standard method of pEVDriver for GetValues. * it may be replaced by a device specific routine, for the case that @@ -688,409 +645,382 @@ static void ErrReport(pEVControl self) * (i.e.control not on sample sensor) * Oct. 2002 M.Zolliker */ - static int StdGetValues(pEVDriver self, float *fTarget, float *fPos, float *fDelta) - { - int iRet; - - assert(self); - iRet=self->GetValue(self, fPos); - if (iRet>0) *fDelta = *fTarget - *fPos; - return iRet; - } +static int StdGetValues(pEVDriver self, float *fTarget, float *fPos, + float *fDelta) +{ + int iRet; + + assert(self); + iRet = self->GetValue(self, fPos); + if (iRet > 0) + *fDelta = *fTarget - *fPos; + return iRet; +} + /*-------- All this done, we can actually implement the controller ---------*/ - pEVControl CreateEVController(pEVDriver pDriv, char *pName, int *iErr) - { - pEVControl pRes = NULL; - int iRet; - - assert(pDriv); - *iErr = 1; - - /* new memory first */ - pRes = (pEVControl)malloc(sizeof(EVControl)); - if(!pRes) - { - return NULL; - } - memset(pRes,0,sizeof(EVControl)); - - /* new Object Descriptor */ - pRes->pDes = CreateDescriptor("Environment Controller"); - if(!pRes->pDes) - { - free(pRes); - return NULL; - } - pRes->pDes->GetInterface = EVIInterface; - - /* new Drivable interface */ - pRes->pDrivInt = CreateDrivableInterface(); - if(!pRes->pDrivInt) - { - DeleteDescriptor(pRes->pDes); - free(pRes); - return NULL; - } - pRes->pDrivInt->Halt = EVIHalt; - pRes->pDrivInt->CheckLimits = EVILimits; - pRes->pDrivInt->SetValue = EVIDrive; - pRes->pDrivInt->CheckStatus = EVIStatus; - pRes->pDrivInt->GetValue = EVIGet; - - - /* new environment interface */ - pRes->pEnvir = CreateEVInterface(); - if(!pRes->pEnvir) - { - free(pRes->pDrivInt); - DeleteDescriptor(pRes->pDes); - free(pRes); - return NULL; - } - pRes->pEnvir->GetMode = EVIGetMode; - pRes->pEnvir->IsInTolerance = EVIIsInTolerance; - pRes->pEnvir->HandleError = EVIErrHandler; +pEVControl CreateEVController(pEVDriver pDriv, char *pName, int *iErr) +{ + pEVControl pRes = NULL; + int iRet; - /* callback interface */ - pRes->pCall = CreateCallBackInterface(); - if(!pRes->pCall) - { - free(pRes->pDrivInt); - DeleteDescriptor(pRes->pDes); - free(pRes); - return NULL; - } + assert(pDriv); + *iErr = 1; - /* new parameter space */ - pRes->pParam = ObParCreate(9); - if(!pRes->pParam) - { - free(pRes->pDrivInt); - free(pRes->pEnvir); - DeleteDescriptor(pRes->pDes); - free(pRes); - return NULL; - } - ObParInit(pRes->pParam, TOLERANCE, "tolerance", 2.0, usUser); - ObParInit(pRes->pParam, ACCESS, "access", usUser, usMugger); - ObParInit(pRes->pParam, ERRORHANDLER, "errorhandler", 0.0, usUser); - ObParInit(pRes->pParam, INTERRUPT, "interrupt", eContinue, usUser); - ObParInit(pRes->pParam, UPLIMIT, "upperlimit", 300.0, usUser); - ObParInit(pRes->pParam, LOWLIMIT, "lowerlimit", 1.0, usUser); - ObParInit(pRes->pParam, SAFEVALUE, "safevalue", 0., usUser); - ObParInit(pRes->pParam, MAXWAIT, "maxwait", 0., usUser); - ObParInit(pRes->pParam, SETTLE, "settle", 0., usUser); - - /* local initialisations */ - if (pDriv->GetValues==NULL) /* if GetValues is undefined, set to default */ - { - pDriv->GetValues=StdGetValues; - } - iRet = pDriv->Init(pDriv); - - *iErr = iRet; - - /* new var log for logging values */ - pRes->iLog = 1; - if(!VarlogInit(&pRes->pLog)) - { - DeleteEVController(pRes); - return NULL; - } - - pRes->pName = strdup(pName); - pRes->eMode = EVIdle; - pRes->iWarned = 0; - if(pRes->conn != NULL){ - SCDeleteConnection(pRes->conn); - pRes->conn = NULL; - } - - /* a terminal error gives a -1 in iRet */ - if(iRet < 0) - { - DeleteEVController(pRes); - return NULL; - } - pRes->pDriv = pDriv; /* moved here to avoid double freeing on evfactory del */ - return pRes; - } -/*---------------------------------------------------------------------------*/ - void DeleteEVController(void *pData) - { - pEVControl self = NULL; - - self = (pEVControl)pData; - assert(self); - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - self->pDes = NULL; - } - if(self->pDrivInt) - { - free(self->pDrivInt); - } - if(self->pEnvir) - { - free(self->pEnvir); - } - if(self->pCall) - { - DeleteCallBackInterface(self->pCall); - } - if(self->KillPrivate) - { - self->KillPrivate(self->pPrivate); - } - if(self->pDriv) - { - self->pDriv->Close(self->pDriv); - DeleteEVDriver(self->pDriv); - } - if(self->pName) - { - free(self->pName); - } - if(self->pParam) - { - ObParDelete(self->pParam); - } - if(self->pLog) - { - VarlogDelete(self->pLog); - } - if(self->driverName != NULL) - { - free(self->driverName); - } - if(self->errorScript != NULL) - { - free(self->errorScript); - } - if (self->creationArgs != NULL) - { - free(self->creationArgs); - } - if (self->runScript != NULL) - { - free(self->runScript); - } - if (self->conn != NULL) - { - SCDeleteConnection(self->conn); - } - free(self); - } -/*--------------------------------------------------------------------------*/ - int EVCDrive(pEVControl self, SConnection *pCon, float fVal) - { - char pBueffel[256], pError[132]; - int iRet; - - assert(self); - assert(pCon); - - /* Check Limits */ - iRet = self->pDrivInt->CheckLimits(self, fVal, pError,131); - if(!iRet) - { - SCWrite(pCon,pError,eError); - return 0; - } - - /* start executing */ - iRet = StartDevice(GetExecutor(), self->pName, self->pDes, - self, pCon, fVal); - if(!iRet) - { - sprintf(pBueffel,"ERROR: Failure to start %s",self->pName); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* Wait for success */ - iRet = Wait4Success(GetExecutor()); - if(iRet == DEVINT) - { - return 0; - } - return 1; - } -/*--------------------------------------------------------------------------*/ - int EVCGetPos(pEVControl self, SConnection *pCon, float *fPos) - { - float fVal; - - assert(self); - assert(pCon); - - fVal = self->pDrivInt->GetValue(self, pCon); - if(fVal < -990) - { - return 0; - } - *fPos = fVal; - return 1; + /* new memory first */ + pRes = (pEVControl) malloc(sizeof(EVControl)); + if (!pRes) { + return NULL; } + memset(pRes, 0, sizeof(EVControl)); + + /* new Object Descriptor */ + pRes->pDes = CreateDescriptor("Environment Controller"); + if (!pRes->pDes) { + free(pRes); + return NULL; + } + pRes->pDes->GetInterface = EVIInterface; + + /* new Drivable interface */ + pRes->pDrivInt = CreateDrivableInterface(); + if (!pRes->pDrivInt) { + DeleteDescriptor(pRes->pDes); + free(pRes); + return NULL; + } + pRes->pDrivInt->Halt = EVIHalt; + pRes->pDrivInt->CheckLimits = EVILimits; + pRes->pDrivInt->SetValue = EVIDrive; + pRes->pDrivInt->CheckStatus = EVIStatus; + pRes->pDrivInt->GetValue = EVIGet; + + + /* new environment interface */ + pRes->pEnvir = CreateEVInterface(); + if (!pRes->pEnvir) { + free(pRes->pDrivInt); + DeleteDescriptor(pRes->pDes); + free(pRes); + return NULL; + } + pRes->pEnvir->GetMode = EVIGetMode; + pRes->pEnvir->IsInTolerance = EVIIsInTolerance; + pRes->pEnvir->HandleError = EVIErrHandler; + + /* callback interface */ + pRes->pCall = CreateCallBackInterface(); + if (!pRes->pCall) { + free(pRes->pDrivInt); + DeleteDescriptor(pRes->pDes); + free(pRes); + return NULL; + } + + /* new parameter space */ + pRes->pParam = ObParCreate(9); + if (!pRes->pParam) { + free(pRes->pDrivInt); + free(pRes->pEnvir); + DeleteDescriptor(pRes->pDes); + free(pRes); + return NULL; + } + ObParInit(pRes->pParam, TOLERANCE, "tolerance", 2.0, usUser); + ObParInit(pRes->pParam, ACCESS, "access", usUser, usMugger); + ObParInit(pRes->pParam, ERRORHANDLER, "errorhandler", 0.0, usUser); + ObParInit(pRes->pParam, INTERRUPT, "interrupt", eContinue, usUser); + ObParInit(pRes->pParam, UPLIMIT, "upperlimit", 300.0, usUser); + ObParInit(pRes->pParam, LOWLIMIT, "lowerlimit", 1.0, usUser); + ObParInit(pRes->pParam, SAFEVALUE, "safevalue", 0., usUser); + ObParInit(pRes->pParam, MAXWAIT, "maxwait", 0., usUser); + ObParInit(pRes->pParam, SETTLE, "settle", 0., usUser); + + /* local initialisations */ + if (pDriv->GetValues == NULL) { /* if GetValues is undefined, set to default */ + pDriv->GetValues = StdGetValues; + } + iRet = pDriv->Init(pDriv); + + *iErr = iRet; + + /* new var log for logging values */ + pRes->iLog = 1; + if (!VarlogInit(&pRes->pLog)) { + DeleteEVController(pRes); + return NULL; + } + + pRes->pName = strdup(pName); + pRes->eMode = EVIdle; + pRes->iWarned = 0; + if (pRes->conn != NULL) { + SCDeleteConnection(pRes->conn); + pRes->conn = NULL; + } + + /* a terminal error gives a -1 in iRet */ + if (iRet < 0) { + DeleteEVController(pRes); + return NULL; + } + pRes->pDriv = pDriv; /* moved here to avoid double freeing on evfactory del */ + return pRes; +} + +/*---------------------------------------------------------------------------*/ +void DeleteEVController(void *pData) +{ + pEVControl self = NULL; + + self = (pEVControl) pData; + assert(self); + + if (self->pDes) { + DeleteDescriptor(self->pDes); + self->pDes = NULL; + } + if (self->pDrivInt) { + free(self->pDrivInt); + } + if (self->pEnvir) { + free(self->pEnvir); + } + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + } + if (self->KillPrivate) { + self->KillPrivate(self->pPrivate); + } + if (self->pDriv) { + self->pDriv->Close(self->pDriv); + DeleteEVDriver(self->pDriv); + } + if (self->pName) { + free(self->pName); + } + if (self->pParam) { + ObParDelete(self->pParam); + } + if (self->pLog) { + VarlogDelete(self->pLog); + } + if (self->driverName != NULL) { + free(self->driverName); + } + if (self->errorScript != NULL) { + free(self->errorScript); + } + if (self->creationArgs != NULL) { + free(self->creationArgs); + } + if (self->runScript != NULL) { + free(self->runScript); + } + if (self->conn != NULL) { + SCDeleteConnection(self->conn); + } + free(self); +} + +/*--------------------------------------------------------------------------*/ +int EVCDrive(pEVControl self, SConnection * pCon, float fVal) +{ + char pBueffel[256], pError[132]; + int iRet; + + assert(self); + assert(pCon); + + /* Check Limits */ + iRet = self->pDrivInt->CheckLimits(self, fVal, pError, 131); + if (!iRet) { + SCWrite(pCon, pError, eError); + return 0; + } + + /* start executing */ + iRet = StartDevice(GetExecutor(), self->pName, self->pDes, + self, pCon, fVal); + if (!iRet) { + sprintf(pBueffel, "ERROR: Failure to start %s", self->pName); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* Wait for success */ + iRet = Wait4Success(GetExecutor()); + if (iRet == DEVINT) { + return 0; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int EVCGetPos(pEVControl self, SConnection * pCon, float *fPos) +{ + float fVal; + + assert(self); + assert(pCon); + + fVal = self->pDrivInt->GetValue(self, pCon); + if (fVal < -990) { + return 0; + } + *fPos = fVal; + return 1; +} + /*-------------------------------------------------------------------------*/ - pVarLog EVCGetVarLog(pEVControl self) - { - - assert(self); - - return self->pLog; - } +pVarLog EVCGetVarLog(pEVControl self) +{ + + assert(self); + + return self->pLog; +} + /*---------------------------------------------------------------------------*/ - EVMode EVCGetMode(pEVControl self) - { - assert(self); - return self->eMode; - } +EVMode EVCGetMode(pEVControl self) +{ + assert(self); + return self->eMode; +} + /*--------------------------------------------------------------------------*/ - int EVCSetMode(pEVControl self, EVMode eNew) - { - assert(self); - self->eMode = eNew; - return 1; - } +int EVCSetMode(pEVControl self, EVMode eNew) +{ + assert(self); + self->eMode = eNew; + return 1; +} + /*---------------------------------------------------------------------------*/ - int EVCGetPar(pEVControl self, char *name, float *fVal) - { - ObPar *pPar = NULL; - assert(self); +int EVCGetPar(pEVControl self, char *name, float *fVal) +{ + ObPar *pPar = NULL; + assert(self); - - if(strcmp(name,"target") == 0) - { - *fVal = self->fTarget; - return 1; - } - pPar = ObParFind(self->pParam,name); - if(pPar) - { - *fVal = pPar->fVal; - return 1; - } - else - { - return 0; - } - } -/*---------------------------------------------------------------------------*/ - int EVCSetPar(pEVControl self, char *name, float fVal,SConnection *pCon) - { - ObPar *pPar = NULL; - char pBueffel[512]; - int iRet, savedStatus; - - assert(self); - assert(pCon); - - savedStatus = GetStatus(); /* fool status check in ObParSet (avoid "Cannot change parameter while running" message */ - SetStatus(eBatch); - iRet = ObParSet(self->pParam,self->pName,name,fVal,pCon); - SetStatus(savedStatus); - if(!iRet) - { - return iRet; - } - if(self->iTcl) - { - iRet = UpdateTclVariable(self->pDriv,name,fVal); - } - return iRet; - } -/*--------------------------------------------------------------------------*/ - int EVCList(pEVControl self, SConnection *pCon) - { - char pBueffel[256]; - float fPos; - - assert(self); - assert(pCon); - - snprintf(pBueffel,255,"Parameter listing for %s",self->pName); - SCWrite(pCon,pBueffel,eValue); - - snprintf(pBueffel,255,"%s.%s = %g ",self->pName, "tolerance", - ObVal(self->pParam,TOLERANCE)); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.%s = %g",self->pName, "access", - ObVal(self->pParam,ACCESS)); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.%s = %g",self->pName, "ErrorHandler", - ObVal(self->pParam,ERRORHANDLER)); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.%s = %g",self->pName, "interrupt", - ObVal(self->pParam,INTERRUPT)); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.%s = %g",self->pName, "UpperLimit", - ObVal(self->pParam,UPLIMIT)); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.%s = %g",self->pName, "LowerLimit", - ObVal(self->pParam,LOWLIMIT)); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.%s = %g",self->pName, "SafeValue", - ObVal(self->pParam,SAFEVALUE)); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.%s = %g (sec)",self->pName, "MaxWait", - ObVal(self->pParam,MAXWAIT)); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.%s = %g (sec)",self->pName, "Settle", - ObVal(self->pParam,SETTLE)); - SCWrite(pCon,pBueffel, eValue); - EVCGetPos(self,pCon,&fPos); - snprintf(pBueffel,255,"%s.%s = %g",self->pName, "CurrentValue", - fPos); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.%s = %g",self->pName, "TargetValue", - self->fTarget); - SCWrite(pCon,pBueffel, eValue); - snprintf(pBueffel,255,"%s.driver = %s",self->pName, self->driverName); - SCWrite(pCon,pBueffel, eValue); - if(self->errorScript != NULL) - { - snprintf(pBueffel,255,"%s.errorScript = %s", self->pName, - self->errorScript); - } - else - { - snprintf(pBueffel,255,"%s.errorScript = UNDEFINED", self->pName); - } - SCWrite(pCon,pBueffel, eValue); - if(self->runScript != NULL) - { - SCPrintf(pCon, eValue, "%s.runScript = %s", self->pName, self->runScript); - } - else - { - SCPrintf(pCon, eValue, "%s.runScript = none", self->pName); - } - return 1; - } -/*-------------------------------------------------------------------------*/ - static int EVCallBack(int iEvent, void *pEventData, void *pUserData) - { - char *pBuf = (char *)pEventData; - SConnection *pCon = (SConnection *)pUserData; - char pBueffel[132]; - - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } - - if(iEvent == VALUECHANGE && pCon != NULL) - { - pCon->conEventType=POSITION; - SCWrite(pCon,pBuf,eEvent); - return 1; - } + if (strcmp(name, "target") == 0) { + *fVal = self->fTarget; return 1; } + + pPar = ObParFind(self->pParam, name); + if (pPar) { + *fVal = pPar->fVal; + return 1; + } else { + return 0; + } +} + +/*---------------------------------------------------------------------------*/ +int EVCSetPar(pEVControl self, char *name, float fVal, SConnection * pCon) +{ + ObPar *pPar = NULL; + char pBueffel[512]; + int iRet, savedStatus; + + assert(self); + assert(pCon); + + savedStatus = GetStatus(); /* fool status check in ObParSet (avoid "Cannot change parameter while running" message */ + SetStatus(eBatch); + iRet = ObParSet(self->pParam, self->pName, name, fVal, pCon); + SetStatus(savedStatus); + if (!iRet) { + return iRet; + } + if (self->iTcl) { + iRet = UpdateTclVariable(self->pDriv, name, fVal); + } + return iRet; +} + +/*--------------------------------------------------------------------------*/ +int EVCList(pEVControl self, SConnection * pCon) +{ + char pBueffel[256]; + float fPos; + + assert(self); + assert(pCon); + + snprintf(pBueffel, 255, "Parameter listing for %s", self->pName); + SCWrite(pCon, pBueffel, eValue); + + snprintf(pBueffel, 255, "%s.%s = %g ", self->pName, "tolerance", + ObVal(self->pParam, TOLERANCE)); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.%s = %g", self->pName, "access", + ObVal(self->pParam, ACCESS)); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.%s = %g", self->pName, "ErrorHandler", + ObVal(self->pParam, ERRORHANDLER)); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.%s = %g", self->pName, "interrupt", + ObVal(self->pParam, INTERRUPT)); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.%s = %g", self->pName, "UpperLimit", + ObVal(self->pParam, UPLIMIT)); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.%s = %g", self->pName, "LowerLimit", + ObVal(self->pParam, LOWLIMIT)); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.%s = %g", self->pName, "SafeValue", + ObVal(self->pParam, SAFEVALUE)); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.%s = %g (sec)", self->pName, "MaxWait", + ObVal(self->pParam, MAXWAIT)); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.%s = %g (sec)", self->pName, "Settle", + ObVal(self->pParam, SETTLE)); + SCWrite(pCon, pBueffel, eValue); + EVCGetPos(self, pCon, &fPos); + snprintf(pBueffel, 255, "%s.%s = %g", self->pName, "CurrentValue", fPos); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.%s = %g", self->pName, "TargetValue", + self->fTarget); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.driver = %s", self->pName, self->driverName); + SCWrite(pCon, pBueffel, eValue); + if (self->errorScript != NULL) { + snprintf(pBueffel, 255, "%s.errorScript = %s", self->pName, + self->errorScript); + } else { + snprintf(pBueffel, 255, "%s.errorScript = UNDEFINED", self->pName); + } + SCWrite(pCon, pBueffel, eValue); + if (self->runScript != NULL) { + SCPrintf(pCon, eValue, "%s.runScript = %s", self->pName, + self->runScript); + } else { + SCPrintf(pCon, eValue, "%s.runScript = none", self->pName); + } + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int EVCallBack(int iEvent, void *pEventData, void *pUserData) +{ + char *pBuf = (char *) pEventData; + SConnection *pCon = (SConnection *) pUserData; + char pBueffel[132]; + + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + if (iEvent == VALUECHANGE && pCon != NULL) { + pCon->conEventType = POSITION; + SCWrite(pCon, pBuf, eEvent); + return 1; + } + return 1; +} + /*--------------------------------------------------------------------------- The wrapper understands the following syntax: EVControl : print current value @@ -1102,251 +1032,219 @@ static void ErrReport(pEVControl self) EVControl send bla bla ..... : sends everything after send to the device ---------------------------------------------------------------------------*/ - int EVControlWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pEVControl self = NULL; - char pBueffel[256], pReply[512]; - double dVal; - float fPos; - int iRet; - long lID; - - self = (pEVControl)pData; - assert(self); - assert(pSics); - assert(pCon); - - if(argc < 2) /* only value requested */ - { - iRet = EVCGetPos(self,pCon,&fPos); - if(iRet) - { +int EVControlWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pEVControl self = NULL; + char pBueffel[256], pReply[512]; + double dVal; + float fPos; + int iRet; + long lID; + + self = (pEVControl) pData; + assert(self); + assert(pSics); + assert(pCon); + + if (argc < 2) { /* only value requested */ + iRet = EVCGetPos(self, pCon, &fPos); + if (iRet) { /* sprintf(pBueffel,"%s.%s = %g",self->pName,"CurrentValue", fPos); SCWrite(pCon,pBueffel,eValue); */ - SCPrintf(pCon, eValue, "%s = %g", argv[0], fPos); - return 1; - } - return 0; + SCPrintf(pCon, eValue, "%s = %g", argv[0], fPos); + return 1; + } + return 0; + } else { + strtolower(argv[1]); + } + + /* analyse commands */ + if (strcmp(argv[1], "send") == 0) { /* send to controller */ + Arg2Text(argc - 2, &argv[2], pBueffel, 255); + iRet = self->pDriv->Send(self->pDriv, pBueffel, pReply, 511); + SCWrite(pCon, pReply, eValue); + return iRet; + } + /* install automatic notification */ + else if (strcmp(argv[1], "interest") == 0) { + lID = RegisterCallback(self->pCall, + VALUECHANGE, EVCallBack, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "uninterest") == 0) { + RemoveCallbackCon(self->pCall, pCon); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "log") == 0) { /* log commands */ + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient number of commands for varlog", + eError); + return 0; + } + iRet = VarlogWrapper(self->pLog, pCon, argv[2], argv[3], argv[0]); + return iRet; + } else if (argc < 3) { /* either parameter or drive */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[1], &dVal); + if (iRet == TCL_OK) { /* float Value: drive */ + if (!SCMatchRights(pCon, usUser)) { + return 0; } - else - { - strtolower(argv[1]); + iRet = EVCDrive(self, pCon, (float) dVal); + if (iRet) { + SCSendOK(pCon); } - - /* analyse commands */ - if(strcmp(argv[1],"send") == 0) /* send to controller */ - { - Arg2Text(argc-2,&argv[2],pBueffel,255); - iRet = self->pDriv->Send(self->pDriv,pBueffel,pReply, 511); - SCWrite(pCon,pReply,eValue); - return iRet; + return iRet; + } else if (strcmp(argv[1], "list") == 0) { + EVCList(self, pCon); + return 1; + } else if (strcmp(argv[1], "send") == 0) { /* send to controller */ + Arg2Text(argc - 2, &argv[2], pBueffel, 255); + iRet = self->pDriv->Send(self->pDriv, pBueffel, pReply, 511); + SCWrite(pCon, pReply, eValue); + return iRet; + } else if (strcmp(argv[1], "log") == 0) { /* log commands */ + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient number of commands for varlog", + eError); + return 0; } - /* install automatic notification */ - else if(strcmp(argv[1],"interest") == 0) - { - lID = RegisterCallback(self->pCall, - VALUECHANGE, EVCallBack, - SCCopyConnection(pCon), SCDeleteConnection); - SCSendOK(pCon); - return 1; + return VarlogWrapper(self->pLog, pCon, argv[2], argv[3], argv[0]); + } else { /* parameter request */ + + strtolower(argv[1]); + /* + catch case of errorScript + */ + if (strcmp(argv[1], "errorscript") == 0) { + if (self->errorScript != NULL) { + snprintf(pBueffel, 255, "%s.errorScript = %s", self->pName, + self->errorScript); + } else { + snprintf(pBueffel, 255, "%s.errorScript = UNDEFINED", + self->pName); + } + SCWrite(pCon, pBueffel, eValue); + return 1; } - else if(strcmp(argv[1],"uninterest") == 0) - { - RemoveCallbackCon(self->pCall,pCon); - SCSendOK(pCon); - return 1; + /* + catch case of runScript + */ + if (strcmp(argv[1], "runscript") == 0) { + if (self->runScript != NULL) { + SCPrintf(pCon, eValue, "%s.runScript = %s", self->pName, + self->runScript); + } else { + SCPrintf(pCon, eValue, "%s.runScript = none", self->pName); + } + return 1; } - else if(strcmp(argv[1],"log") == 0) /* log commands */ - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: insufficient number of commands for varlog",eError); - return 0; - } - iRet = VarlogWrapper(self->pLog,pCon, - argv[2],argv[3],argv[0]); - return iRet; + /* + catch case for drivername + */ + if (strcmp(argv[1], "driver") == 0) { + snprintf(pBueffel, 255, "%s.driver = %s", self->pName, + self->driverName); + SCWrite(pCon, pBueffel, eValue); + return 1; } - else if( argc < 3) /* either parameter or drive */ - { - iRet = Tcl_GetDouble(pSics->pTcl,argv[1],&dVal); - if(iRet == TCL_OK) /* float Value: drive */ - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = EVCDrive(self,pCon,(float)dVal); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - else if(strcmp(argv[1],"list") == 0) - { - EVCList(self,pCon); - return 1; - } - else if(strcmp(argv[1],"send") == 0) /* send to controller */ - { - Arg2Text(argc-2,&argv[2],pBueffel,255); - iRet = self->pDriv->Send(self->pDriv,pBueffel,pReply, 511); - SCWrite(pCon,pReply,eValue); - return iRet; - } - else if(strcmp(argv[1],"log") == 0) /* log commands */ - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: insufficient number of commands for varlog",eError); - return 0; - } - return VarlogWrapper(self->pLog,pCon, - argv[2],argv[3],argv[0]); - } - else /* parameter request */ - { - strtolower(argv[1]); - /* - catch case of errorScript - */ - if(strcmp(argv[1],"errorscript") == 0) - { - if(self->errorScript != NULL) - { - snprintf(pBueffel,255,"%s.errorScript = %s",self->pName, - self->errorScript); - } - else - { - snprintf(pBueffel,255,"%s.errorScript = UNDEFINED", - self->pName); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - } - /* - catch case of runScript - */ - if(strcmp(argv[1],"runscript") == 0) - { - if(self->runScript != NULL) - { - SCPrintf(pCon, eValue,"%s.runScript = %s",self->pName, - self->runScript); - } - else - { - SCPrintf(pCon, eValue,"%s.runScript = none",self->pName); - } - return 1; - } - /* - catch case for drivername - */ - if(strcmp(argv[1],"driver") == 0) - { - snprintf(pBueffel,255,"%s.driver = %s", self->pName, - self->driverName); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - iRet = EVCGetPar(self,argv[1],&fPos); - if(!iRet) - { - sprintf(pBueffel,"ERROR: parameter %s NOT found", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - else - { - sprintf(pBueffel,"%s.%s = %g",self->pName,argv[1],fPos); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } + iRet = EVCGetPar(self, argv[1], &fPos); + if (!iRet) { + sprintf(pBueffel, "ERROR: parameter %s NOT found", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } else { + sprintf(pBueffel, "%s.%s = %g", self->pName, argv[1], fPos); + SCWrite(pCon, pBueffel, eValue); + return 1; } - else /* try to set parameter */ - { - strtolower(argv[1]); - /* - first catch case of errorScript - */ - if(strcmp(argv[1],"errorscript") == 0) - { - if(self->errorScript != NULL) - { - free(self->errorScript); - } - self->errorScript = Arg2Tcl(argc-2,&argv[2],NULL,0); - SCSendOK(pCon); - SCparChange(pCon); - return 1; - } - /* - catch case of runScript - */ - if(strcmp(argv[1],"runscript") == 0) - { - if(self->runScript != NULL) - { - free(self->runScript); - } - if (strcasecmp(argv[2],"none") == 0) { - self->runScript = NULL; - } else { - self->runScript = Arg2Tcl(argc-2,&argv[2],NULL,0); - } - SCSendOK(pCon); - SCparChange(pCon); - return 1; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: %s no valid number", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = EVCSetPar(self, argv[1],(float)dVal,pCon); - if(iRet) - { - SCSendOK(pCon); - SCparChange(pCon); - } - return iRet; + } + } else { /* try to set parameter */ + + strtolower(argv[1]); + /* + first catch case of errorScript + */ + if (strcmp(argv[1], "errorscript") == 0) { + if (self->errorScript != NULL) { + free(self->errorScript); } - return 0; /* not reached */ - } + self->errorScript = Arg2Tcl(argc - 2, &argv[2], NULL, 0); + SCSendOK(pCon); + SCparChange(pCon); + return 1; + } + /* + catch case of runScript + */ + if (strcmp(argv[1], "runscript") == 0) { + if (self->runScript != NULL) { + free(self->runScript); + } + if (strcasecmp(argv[2], "none") == 0) { + self->runScript = NULL; + } else { + self->runScript = Arg2Tcl(argc - 2, &argv[2], NULL, 0); + } + SCSendOK(pCon); + SCparChange(pCon); + return 1; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: %s no valid number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = EVCSetPar(self, argv[1], (float) dVal, pCon); + if (iRet) { + SCSendOK(pCon); + SCparChange(pCon); + } + return iRet; + } + return 0; /* not reached */ +} + /*-----------------------------------------------------------------------*/ -static int EVSaveStatus(void *pData, char *name, FILE *fil) +static int EVSaveStatus(void *pData, char *name, FILE * fil) { pEVControl evc = pData; pEVDriver pD = evc->pDriv; - + assert(evc); assert(pD); if (evc->creationArgs && pD->SavePars) { - fprintf(fil, "if {[catch { evfactory replace %s %s }] == 0} {\n", name, evc->creationArgs); + fprintf(fil, "if {[catch { evfactory replace %s %s }] == 0} {\n", name, + evc->creationArgs); if (pD->SavePars(pD, fil) == 1) { - fprintf(fil, " %s %s %g\n",evc->pName, "tolerance", ObVal(evc->pParam,TOLERANCE)); - fprintf(fil, " %s %s %g\n",evc->pName, "access", ObVal(evc->pParam,ACCESS)); - fprintf(fil, " %s %s %g\n",evc->pName, "ErrorHandler", ObVal(evc->pParam,ERRORHANDLER)); - fprintf(fil, " %s %s %g\n",evc->pName, "interrupt", ObVal(evc->pParam,INTERRUPT)); - fprintf(fil, " %s %s %g\n",evc->pName, "UpperLimit", ObVal(evc->pParam,UPLIMIT)); - fprintf(fil, " %s %s %g\n",evc->pName, "LowerLimit", ObVal(evc->pParam,LOWLIMIT)); - fprintf(fil, " %s %s %g\n",evc->pName, "SafeValue", ObVal(evc->pParam,SAFEVALUE)); - fprintf(fil, " %s %s %g\n",evc->pName, "MaxWait", ObVal(evc->pParam,MAXWAIT)); - fprintf(fil, " %s %s %g\n",evc->pName, "Settle", ObVal(evc->pParam,SETTLE)); - if(evc->errorScript != NULL) { - fprintf(fil, " %s errorScript %s\n", evc->pName, evc->errorScript); + fprintf(fil, " %s %s %g\n", evc->pName, "tolerance", + ObVal(evc->pParam, TOLERANCE)); + fprintf(fil, " %s %s %g\n", evc->pName, "access", + ObVal(evc->pParam, ACCESS)); + fprintf(fil, " %s %s %g\n", evc->pName, "ErrorHandler", + ObVal(evc->pParam, ERRORHANDLER)); + fprintf(fil, " %s %s %g\n", evc->pName, "interrupt", + ObVal(evc->pParam, INTERRUPT)); + fprintf(fil, " %s %s %g\n", evc->pName, "UpperLimit", + ObVal(evc->pParam, UPLIMIT)); + fprintf(fil, " %s %s %g\n", evc->pName, "LowerLimit", + ObVal(evc->pParam, LOWLIMIT)); + fprintf(fil, " %s %s %g\n", evc->pName, "SafeValue", + ObVal(evc->pParam, SAFEVALUE)); + fprintf(fil, " %s %s %g\n", evc->pName, "MaxWait", + ObVal(evc->pParam, MAXWAIT)); + fprintf(fil, " %s %s %g\n", evc->pName, "Settle", + ObVal(evc->pParam, SETTLE)); + if (evc->errorScript != NULL) { + fprintf(fil, " %s errorScript %s\n", evc->pName, + evc->errorScript); } - if(evc->runScript != NULL) { + if (evc->runScript != NULL) { fprintf(fil, " %s runScript %s\n", evc->pName, evc->runScript); } } @@ -1354,184 +1252,169 @@ static int EVSaveStatus(void *pData, char *name, FILE *fil) } return 1; } + /*--------------------------------------------------------------------------*/ /* standard method for saving parameters */ -static int EVCSaveStd(void *pData, char *name, FILE *fil) +static int EVCSaveStd(void *pData, char *name, FILE * fil) { return 1; } + /*-----------------------------------------------------------------------*/ -pEVControl MakeEVController(pEVDriver pDriv, SConnection *pCon, +pEVControl MakeEVController(pEVDriver pDriv, SConnection * pCon, ObjectFunc wrapper, int argc, char *argv[]) { pEVControl pNew; int status = 1; char pBueffel[512]; char pError[132]; - + if (pDriv == NULL) { - SCWrite(pCon,"ERROR: failed to create driver",eError); + SCWrite(pCon, "ERROR: failed to create driver", eError); return NULL; } - pNew = CreateEVController(pDriv,argv[0],&status); + pNew = CreateEVController(pDriv, argv[0], &status); if (status != 1) { printf("CEVC error\n"); - SCWrite(pCon,"ERROR: failed to initialize device", eError); - pDriv->GetError(pDriv,&status,pError,sizeof pError -1); + SCWrite(pCon, "ERROR: failed to initialize device", eError); + pDriv->GetError(pDriv, &status, pError, sizeof pError - 1); printf("HW %s\n", pError); - sprintf(pBueffel,"HW reported: %s",pError); - SCWrite(pCon,pBueffel,eError); + sprintf(pBueffel, "HW reported: %s", pError); + SCWrite(pCon, pBueffel, eError); } if (pNew == NULL) { printf("CEVC failed\n"); - SCWrite(pCon,"ERROR: failed to create environment device object", + SCWrite(pCon, "ERROR: failed to create environment device object", eError); DeleteEVDriver(pDriv); return NULL; } if (wrapper == NULL) { - AddCommand(pServ->pSics,argv[0],EVControlWrapper,DeleteEVController,pNew); + AddCommand(pServ->pSics, argv[0], EVControlWrapper, DeleteEVController, + pNew); } else { - AddCommand(pServ->pSics,argv[0],wrapper,DeleteEVController,pNew); + AddCommand(pServ->pSics, argv[0], wrapper, DeleteEVController, pNew); } return pNew; } + /*-----------------------------------------------------------------------*/ -static pEVControl InstallCommonControllers(SicsInterp *pSics, - SConnection *pCon, - int argc, char *argv[], - int *found) +static pEVControl InstallCommonControllers(SicsInterp * pSics, + SConnection * pCon, + int argc, char *argv[], + int *found) { pEVControl pNew = NULL; - pEVDriver pDriv = NULL; - char pBueffel[512],pError[132]; + pEVDriver pDriv = NULL; + char pBueffel[512], pError[132]; int iRet; - int (*Wrapper)(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) = EVControlWrapper; + int (*Wrapper) (SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) = EVControlWrapper; - *found=1; - if(strcmp(argv[3],"sim") == 0) /* SIM driver */ - { + *found = 1; + if (strcmp(argv[3], "sim") == 0) { /* SIM driver */ /* Create a Sim Driver */ - pDriv = CreateSIMEVDriver(argc-4,&argv[4]); - if(!pDriv) - { + pDriv = CreateSIMEVDriver(argc - 4, &argv[4]); + if (!pDriv) { SCWrite(pCon, - "ERROR: failed to create Environment Device driver", - eError); - return NULL; + "ERROR: failed to create Environment Device driver", eError); + return NULL; } - } - else if(strcmp(argv[3],"tcl") == 0) /* Tcl driver */ - { - /* Create a Tcl driver */ - pDriv = CreateTclDriver(argc-4,&argv[4],argv[2], pCon); - if(!pDriv) - { - SCWrite(pCon,"ERROR: failed to create TCL device driver",eError); - return NULL; - } - /* got a driver, initialise everything */ - pNew = CreateEVController(pDriv,argv[2],&iRet); - if(!pNew) - { - SCWrite(pCon,"ERROR creating Environment Controller",eError); - DeleteEVDriver(pDriv); - return NULL; - } - if(!iRet) - { - SCWrite(pCon,"ERROR: problem initialising Environment controller", + } else if (strcmp(argv[3], "tcl") == 0) { /* Tcl driver */ + /* Create a Tcl driver */ + pDriv = CreateTclDriver(argc - 4, &argv[4], argv[2], pCon); + if (!pDriv) { + SCWrite(pCon, "ERROR: failed to create TCL device driver", eError); + return NULL; + } + /* got a driver, initialise everything */ + pNew = CreateEVController(pDriv, argv[2], &iRet); + if (!pNew) { + SCWrite(pCon, "ERROR creating Environment Controller", eError); + DeleteEVDriver(pDriv); + return NULL; + } + if (!iRet) { + SCWrite(pCon, "ERROR: problem initialising Environment controller", eError); - pDriv->GetError(pDriv,&iRet,pError,131); - sprintf(pBueffel,"HW reported: %s",pError); - SCWrite(pCon,pBueffel,eError); - } - Wrapper = TclEnvironmentWrapper; - pNew->iTcl = 1; - /* make ev parameters available to Tcl */ - UpdateTclVariable(pNew->pDriv,"tolerance", - ObVal(pNew->pParam,TOLERANCE)); - UpdateTclVariable(pNew->pDriv,"upperlimit", - ObVal(pNew->pParam,UPLIMIT)); - UpdateTclVariable(pNew->pDriv,"lowerlimit", - ObVal(pNew->pParam,LOWLIMIT)); - } - else if(strcmp(argv[3],"gencon") == 0) /* general controller */ - { + pDriv->GetError(pDriv, &iRet, pError, 131); + sprintf(pBueffel, "HW reported: %s", pError); + SCWrite(pCon, pBueffel, eError); + } + Wrapper = TclEnvironmentWrapper; + pNew->iTcl = 1; + /* make ev parameters available to Tcl */ + UpdateTclVariable(pNew->pDriv, "tolerance", + ObVal(pNew->pParam, TOLERANCE)); + UpdateTclVariable(pNew->pDriv, "upperlimit", + ObVal(pNew->pParam, UPLIMIT)); + UpdateTclVariable(pNew->pDriv, "lowerlimit", + ObVal(pNew->pParam, LOWLIMIT)); + } else if (strcmp(argv[3], "gencon") == 0) { /* general controller */ /* Create a driver */ - pDriv = MakeControllerEnvironmentDriver(argc-4,&argv[4]); - if(!pDriv) - { + pDriv = MakeControllerEnvironmentDriver(argc - 4, &argv[4]); + if (!pDriv) { SCWrite(pCon, - "ERROR: failed to create Controller Environment driver", - eError); + "ERROR: failed to create Controller Environment driver", + eError); return NULL; } } else { /* not recognized */ - *found=0; + *found = 0; return NULL; } - if(pNew == NULL) /* not yet initialized */ - { - pNew = CreateEVController(pDriv,argv[2],&iRet); - if(!pNew) - { - SCWrite(pCon,"ERROR creating Environment Controller",eError); + if (pNew == NULL) { /* not yet initialized */ + pNew = CreateEVController(pDriv, argv[2], &iRet); + if (!pNew) { + SCWrite(pCon, "ERROR creating Environment Controller", eError); DeleteEVDriver(pDriv); return NULL; } - if(!iRet) - { - SCWrite(pCon,"ERROR: problem initialising Environment controller", + if (!iRet) { + SCWrite(pCon, "ERROR: problem initialising Environment controller", eError); - pDriv->GetError(pDriv,&iRet,pError,131); - sprintf(pBueffel,"HW reported: %s",pError); - SCWrite(pCon,pBueffel,eError); + pDriv->GetError(pDriv, &iRet, pError, 131); + sprintf(pBueffel, "HW reported: %s", pError); + SCWrite(pCon, pBueffel, eError); } } /* install command */ - iRet = AddCommand(pSics,argv[2],Wrapper, - DeleteEVController, - pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created", - argv[2]); - DeleteEVController((void *)pNew); - SCWrite(pCon,pBueffel,eError); + iRet = AddCommand(pSics, argv[2], Wrapper, DeleteEVController, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[2]); + DeleteEVController((void *) pNew); + SCWrite(pCon, pBueffel, eError); return NULL; } return pNew; } -int RemoveEVController(SConnection *pCon, char *name) { +int RemoveEVController(SConnection * pCon, char *name) +{ char pBueffel[512]; int iRet; - - if(!pServ->pExecutor) - { + + if (!pServ->pExecutor) { return 1; } - if(isInRunMode(pServ->pExecutor)) - { - SCWrite(pCon,"ERROR: cannot delete while running",eError); - return 0; + if (isInRunMode(pServ->pExecutor)) { + SCWrite(pCon, "ERROR: cannot delete while running", eError); + return 0; } - EVUnregister(FindEMON(pServ->pSics),name); - iRet = RemoveCommand(pServ->pSics,name); - if(!iRet) - { - sprintf(pBueffel,"ERROR: %s not found, NOT deleted",name); - SCWrite(pCon,pBueffel,eError); + EVUnregister(FindEMON(pServ->pSics), name); + iRet = RemoveCommand(pServ->pSics, name); + if (!iRet) { + sprintf(pBueffel, "ERROR: %s not found, NOT deleted", name); + SCWrite(pCon, pBueffel, eError); return 0; } return 1; } + /*------------------------------------------------------------------------- EVControlFactory implements a SICS command which creates and deletes Controllers at run-time. Syntax: @@ -1540,107 +1423,99 @@ int RemoveEVController(SConnection *pCon, char *name) { -- creates a new controller name with a simulation driver ControlFactory del name -- deletes controller name --------------------------------------------------------------------------*/ - int EVControlFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pEVControl pNew = NULL; - char pBueffel[512],pError[132]; - int iRet, found; - CommandList *pCom = NULL; - pSite site = NULL; - - assert(pSics); - assert(pCon); - - if(argc < 3) - { - SCWrite(pCon,"ERROR: Insufficient number of arguments to EVFactory", - eError); - return 0; - } - - /* check rights */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - - strtolower(argv[1]); - if(strcmp(argv[1],"del") == 0) /* delete */ - { - if (RemoveEVController(pCon, argv[2])) { - SCSendOK(pCon); - return 1; - } else { - return 0; - } - } - else if(strcmp(argv[1],"new") == 0 || strcmp(argv[1], "replace") == 0) - /* make a new one */ - { - /* argv[2] = name */ - /* argv[3] must be type */ - if(argc < 4) - { - SCWrite(pCon,"ERROR: no type specified for Environment Controller", - eError); - return 0; - } - strtolower(argv[2]); - strtolower(argv[3]); - if (FindCommandData(pSics, argv[2], "Environment Controller")) { - if (strcmp(argv[1], "replace") == 0) { - if (!RemoveEVController(pCon, argv[2])) { - return 0; - } - } else { - sprintf(pBueffel, - "ERROR: environment device %s already installed, delete first", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - pCom = FindCommand(pSics,argv[2]); - if(pCom) - { - sprintf(pBueffel, "ERROR: command %s already exists", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pNew = InstallCommonControllers(pSics,pCon,argc,argv,&found); - if (!found) { - site = getSite(); - if(site != NULL){ - pNew = site->InstallEnvironmentController(pSics,pCon,argc,argv); - } else { - sprintf(pBueffel, - "ERROR: %s not recognized as a valid driver type", - argv[3]); - SCWrite(pCon,pBueffel,eError); - pNew = NULL; - } - } - if(pNew == NULL){ - /* error message is already written */ - return 0; - } - if (pNew->pDriv->SavePars) { - pNew->creationArgs = Arg2Tcl(argc-3, argv+3, NULL, 0); - pNew->pDes->SaveStatus = EVSaveStatus; - } else { - pNew->creationArgs = NULL; - } - - EVRegisterController(FindEMON(pSics),argv[2],pNew, pCon); - pNew->driverName = strdup(argv[3]); - SCSendOK(pCon); - return 1; - } - SCWrite(pCon,"ERROR: command not understood",eError); +-------------------------------------------------------------------------*/ +int EVControlFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pEVControl pNew = NULL; + char pBueffel[512], pError[132]; + int iRet, found; + CommandList *pCom = NULL; + pSite site = NULL; + + assert(pSics); + assert(pCon); + + if (argc < 3) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to EVFactory", + eError); + return 0; + } + + /* check rights */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + + strtolower(argv[1]); + if (strcmp(argv[1], "del") == 0) { /* delete */ + if (RemoveEVController(pCon, argv[2])) { + SCSendOK(pCon); + return 1; + } else { return 0; - } - - + } + } else if (strcmp(argv[1], "new") == 0 + || strcmp(argv[1], "replace") == 0) + /* make a new one */ + { + /* argv[2] = name */ + /* argv[3] must be type */ + if (argc < 4) { + SCWrite(pCon, "ERROR: no type specified for Environment Controller", + eError); + return 0; + } + strtolower(argv[2]); + strtolower(argv[3]); + if (FindCommandData(pSics, argv[2], "Environment Controller")) { + if (strcmp(argv[1], "replace") == 0) { + if (!RemoveEVController(pCon, argv[2])) { + return 0; + } + } else { + sprintf(pBueffel, + "ERROR: environment device %s already installed, delete first", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + pCom = FindCommand(pSics, argv[2]); + if (pCom) { + sprintf(pBueffel, "ERROR: command %s already exists", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pNew = InstallCommonControllers(pSics, pCon, argc, argv, &found); + if (!found) { + site = getSite(); + if (site != NULL) { + pNew = site->InstallEnvironmentController(pSics, pCon, argc, argv); + } else { + sprintf(pBueffel, + "ERROR: %s not recognized as a valid driver type", + argv[3]); + SCWrite(pCon, pBueffel, eError); + pNew = NULL; + } + } + if (pNew == NULL) { + /* error message is already written */ + return 0; + } + if (pNew->pDriv->SavePars) { + pNew->creationArgs = Arg2Tcl(argc - 3, argv + 3, NULL, 0); + pNew->pDes->SaveStatus = EVSaveStatus; + } else { + pNew->creationArgs = NULL; + } + EVRegisterController(FindEMON(pSics), argv[2], pNew, pCon); + pNew->driverName = strdup(argv[3]); + SCSendOK(pCon); + return 1; + } + SCWrite(pCon, "ERROR: command not understood", eError); + return 0; +} diff --git a/evcontroller.h b/evcontroller.h index 96fc8d08..560c1244 100644 --- a/evcontroller.h +++ b/evcontroller.h @@ -16,33 +16,33 @@ #line 153 "evcontroller.w" -/*--------------------------- live & death --------------------------------*/ - typedef struct __EVControl *pEVControl; - typedef struct __EVDriver *pEVDriver; +/*--------------------------- live & death --------------------------------*/ +typedef struct __EVControl *pEVControl; +typedef struct __EVDriver *pEVDriver; - pEVControl CreateEVController(pEVDriver pDriv, char *pName, int *iErr); - void DeleteEVController(void *pData); - pEVControl MakeEVController(pEVDriver pDriv, SConnection *pCon, - ObjectFunc wrapper, int argc, char *argv[]); +pEVControl CreateEVController(pEVDriver pDriv, char *pName, int *iErr); +void DeleteEVController(void *pData); +pEVControl MakeEVController(pEVDriver pDriv, SConnection * pCon, + ObjectFunc wrapper, int argc, char *argv[]); /*-------------------------- driving ---------------------------------*/ - int EVCDrive(pEVControl self,SConnection *pCon, float fNew); - int EVCGetPos(pEVControl self, SConnection *pCon,float *fVal); +int EVCDrive(pEVControl self, SConnection * pCon, float fNew); +int EVCGetPos(pEVControl self, SConnection * pCon, float *fVal); /*------------------------ parameters ----------------------------------*/ - EVMode EVCGetMode(pEVControl self); - int EVCSetMode(pEVControl self, EVMode eNew); - int EVCSetPar(pEVControl self, char *name, float fNew, SConnection *pCon); - int EVCGetPar(pEVControl self, char *name, float *fVal); - int EVCList(pEVControl self, SConnection *pCon); +EVMode EVCGetMode(pEVControl self); +int EVCSetMode(pEVControl self, EVMode eNew); +int EVCSetPar(pEVControl self, char *name, float fNew, SConnection * pCon); +int EVCGetPar(pEVControl self, char *name, float *fVal); +int EVCList(pEVControl self, SConnection * pCon); /*------------------------- logging -----------------------------------*/ - pVarLog EVCGetVarLog(pEVControl self); +pVarLog EVCGetVarLog(pEVControl self); /*----------------- Interface to SICS interpreter -----------------------*/ - int EVControlWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - - int EVControlFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +int EVControlWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +int EVControlFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + #line 245 "evcontroller.w" diff --git a/evdriver.c b/evdriver.c index 337343e1..d7a1c3ba 100644 --- a/evdriver.c +++ b/evdriver.c @@ -45,28 +45,27 @@ #include "evdriver.h" /*------------------------------------------------------------------------*/ - pEVDriver CreateEVDriver(int argc, char *argv[]) - { - pEVDriver pNew = NULL; - - pNew = (pEVDriver)malloc(sizeof(EVDriver)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(EVDriver)); - pNew->GetValues = NULL; /* method will be replaced by default when NULL */ - pNew->SavePars = NULL; /* no save by default */ - return pNew; - } +pEVDriver CreateEVDriver(int argc, char *argv[]) +{ + pEVDriver pNew = NULL; + + pNew = (pEVDriver) malloc(sizeof(EVDriver)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(EVDriver)); + pNew->GetValues = NULL; /* method will be replaced by default when NULL */ + pNew->SavePars = NULL; /* no save by default */ + return pNew; +} + /*-------------------------------------------------------------------------*/ - void DeleteEVDriver(pEVDriver self) - { - assert(self); - - if(self->KillPrivate) - { - self->KillPrivate(self->pPrivate); - } - free(self); - } +void DeleteEVDriver(pEVDriver self) +{ + assert(self); + + if (self->KillPrivate) { + self->KillPrivate(self->pPrivate); + } + free(self); +} diff --git a/evdriver.h b/evdriver.h index f6d00d1f..9fbe7492 100644 --- a/evdriver.h +++ b/evdriver.h @@ -3,10 +3,10 @@ #ifndef SICSEVCONTROL -typedef struct __EVDriver *pEVDriver; +typedef struct __EVDriver *pEVDriver; #endif -#include +#include #endif diff --git a/event.c b/event.c index 98ab43be..e362b3e4 100644 --- a/event.c +++ b/event.c @@ -45,47 +45,43 @@ WATCHIT! see event.h for defines of event codes! The list below MUST match. */ - static char *pEvent[] = { - "VARCHANGE", - "MOTORDRIVE", - "MONITOR", - "ROTORSTART", - "ROTORMOVE", - "SCANEND", - "SCANSTART", - "SCANPOINT", - "WLCHANGE", - "REFLECTIONDONE", - "COUNTSTART", - "COUNTEND", - "FILELOADED", - "MOTEND", - "BATCHSTART", - "BATCHAREA", - "BATCHEND", - "DRIVSTAT", - "STATUS", - "POSITION", - "HDBVAL", - "STATESTART", - "STATEEND", - NULL - }; - +static char *pEvent[] = { + "VARCHANGE", + "MOTORDRIVE", + "MONITOR", + "ROTORSTART", + "ROTORMOVE", + "SCANEND", + "SCANSTART", + "SCANPOINT", + "WLCHANGE", + "REFLECTIONDONE", + "COUNTSTART", + "COUNTEND", + "FILELOADED", + "MOTEND", + "BATCHSTART", + "BATCHAREA", + "BATCHEND", + "DRIVSTAT", + "STATUS", + "POSITION", + "HDBVAL", + "STATESTART", + "STATEEND", + NULL +}; + /*---------------------------------------------------------------------------*/ - int Text2Event(char *pText) - { - int iVal = 0; - - while(pEvent[iVal] != NULL) - { - if(strcmp(pEvent[iVal],pText) == 0) - { - return iVal; - } - iVal++; - } - return -1; +int Text2Event(char *pText) +{ + int iVal = 0; + + while (pEvent[iVal] != NULL) { + if (strcmp(pEvent[iVal], pText) == 0) { + return iVal; + } + iVal++; } - - + return -1; +} diff --git a/event.h b/event.h index ee92c179..794b38f7 100644 --- a/event.h +++ b/event.h @@ -16,7 +16,7 @@ #line 13 "event.w" - int Text2Event(char *pText); +int Text2Event(char *pText); #line 113 "event.w" @@ -26,7 +26,7 @@ #define VALUECHANGE 0 #define MOTDRIVE 1 -#define MONITOR 2 +#define MONITOR 2 #define ROTSTART 3 #define ROTMOVE 4 #define SCANEND 5 @@ -63,5 +63,5 @@ #define CRONLIST 305 #line 118 "event.w" - + #endif diff --git a/exebuf.c b/exebuf.c index ddbe5f0d..f695e831 100644 --- a/exebuf.c +++ b/exebuf.c @@ -20,147 +20,164 @@ #include "status.h" /*-----------------------------------------------------------------------*/ -pExeBuf exeBufCreate(char *name){ +pExeBuf exeBufCreate(char *name) +{ pExeBuf pNew = NULL; - pNew = (pExeBuf)malloc(sizeof(ExeBuf)); - if(pNew == NULL){ + pNew = (pExeBuf) malloc(sizeof(ExeBuf)); + if (pNew == NULL) { return NULL; } - memset(pNew,0,sizeof(ExeBuf)); + memset(pNew, 0, sizeof(ExeBuf)); pNew->name = strdup(name); - pNew->bufferContent = CreateDynString(1024,1024); - if(!pNew->bufferContent){ + pNew->bufferContent = CreateDynString(1024, 1024); + if (!pNew->bufferContent) { return NULL; } return pNew; } + /*----------------------------------------------------------------------*/ -void exeBufKill(void *data){ - exeBufDelete((pExeBuf)data); +void exeBufKill(void *data) +{ + exeBufDelete((pExeBuf) data); } + /*-----------------------------------------------------------------------*/ -void exeBufDelete(pExeBuf self){ - if(self == NULL){ +void exeBufDelete(pExeBuf self) +{ + if (self == NULL) { return; } - if(self->name != NULL){ + if (self->name != NULL) { free(self->name); self->name = NULL; } - if(self->bufferContent != NULL){ + if (self->bufferContent != NULL) { DeleteDynString(self->bufferContent); self->bufferContent = NULL; } free(self); } + /*----------------------------------------------------------------------*/ -int exeBufAppend(pExeBuf self, char *line){ +int exeBufAppend(pExeBuf self, char *line) +{ int status; assert(self); - status = DynStringConcat(self->bufferContent,line); - if(strrchr(line,(int)'\n') == NULL){ - DynStringConcatChar(self->bufferContent,'\n'); + status = DynStringConcat(self->bufferContent, line); + if (strrchr(line, (int) '\n') == NULL) { + DynStringConcatChar(self->bufferContent, '\n'); } return status; } + /*-----------------------------------------------------------------------*/ -static char *locateName(char *filename){ +static char *locateName(char *filename) +{ char *pPtr; int i; - pPtr = filename + strlen(filename) -1; - for(i = strlen(filename) -1; i > 0; i--,pPtr--){ - if(*pPtr == '/'){ + pPtr = filename + strlen(filename) - 1; + for (i = strlen(filename) - 1; i > 0; i--, pPtr--) { + if (*pPtr == '/') { pPtr++; return pPtr; } } return filename; } + /*-----------------------------------------------------------------------*/ -int exeBufLoad(pExeBuf self, char *filename){ +int exeBufLoad(pExeBuf self, char *filename) +{ char line[256]; FILE *fd = NULL; int status; assert(self); - fd = fopen(filename,"r"); - if(fd == NULL){ + fd = fopen(filename, "r"); + if (fd == NULL) { return 0; } - while(fgets(line,255,fd) != NULL){ + while (fgets(line, 255, fd) != NULL) { /* Do not use exeBufAppend here. Lines longer than 255 would get newline characters within the line */ - status = DynStringConcat(self->bufferContent,line); - if(status != 1){ + status = DynStringConcat(self->bufferContent, line); + if (status != 1) { fclose(fd); return 0; } } fclose(fd); - if(self->name != NULL){ + if (self->name != NULL) { free(self->name); } self->name = strdup(locateName(filename)); return 1; } + /*----------------------------------------------------------------------*/ -int exeBufSave(pExeBuf self, char *filename){ +int exeBufSave(pExeBuf self, char *filename) +{ FILE *fd = NULL; - fd = fopen(filename,"w"); - if(fd == NULL){ + fd = fopen(filename, "w"); + if (fd == NULL) { return 0; } - fputs(GetCharArray(self->bufferContent),fd); + fputs(GetCharArray(self->bufferContent), fd); fclose(fd); self->name = strdup(locateName(filename)); return 1; } + /*================ process batch buffer ==============================*/ -static pDynString findBlockEnd(pExeBuf self){ +static pDynString findBlockEnd(pExeBuf self) +{ pDynString command = NULL; char *buffer = NULL; int i; assert(self); - command = CreateDynString(80,80); - if(command == NULL){ + command = CreateDynString(80, 80); + if (command == NULL) { return NULL; } buffer = GetCharArray(self->bufferContent); - if(self->end != -1){ + if (self->end != -1) { self->start = self->end + 1; } - for(i = self->start; i < strlen(buffer); i++){ - DynStringConcatChar(command,buffer[i]); - if(buffer[i] == '\n'){ + for (i = self->start; i < strlen(buffer); i++) { + DynStringConcatChar(command, buffer[i]); + if (buffer[i] == '\n') { self->lineno++; - if(Tcl_CommandComplete(GetCharArray(command))){ - self->end = i; - return command; + if (Tcl_CommandComplete(GetCharArray(command))) { + self->end = i; + return command; } } } DeleteDynString(command); return NULL; } + /*---------------------------------------------------------------------*/ -int exeBufProcess(pExeBuf self, SicsInterp *pSics, - SConnection *pCon, pICallBack pCall, int echo){ +int exeBufProcess(pExeBuf self, SicsInterp * pSics, + SConnection * pCon, pICallBack pCall, int echo) +{ pDynString command = NULL; Tcl_Interp *pTcl = NULL; int status; - + static int weWantLogging = 1; char *cmd; char cmdName[128]; char *ende; int l; - + assert(self); assert(pSics); @@ -169,19 +186,19 @@ int exeBufProcess(pExeBuf self, SicsInterp *pSics, self->lineno = 0; pTcl = InterpGetTcl(pSics); - if(pCall != NULL){ - InvokeCallBack(pCall,BATCHSTART,self->name); + if (pCall != NULL) { + InvokeCallBack(pCall, BATCHSTART, self->name); } - + if (echo) { - SCsetMacro(pCon,0); + SCsetMacro(pCon, 0); } - while((command = findBlockEnd(self)) != NULL){ - if(pCall != NULL){ - InvokeCallBack(pCall,BATCHAREA,NULL); + while ((command = findBlockEnd(self)) != NULL) { + if (pCall != NULL) { + InvokeCallBack(pCall, BATCHAREA, NULL); } cmd = GetCharArray(command); - + if (echo) { /* find first word */ while (*cmd == ' ') { @@ -196,55 +213,59 @@ int exeBufProcess(pExeBuf self, SicsInterp *pSics, strncpy(cmdName, cmd, l); cmdName[l] = '\0'; if (FindCommand(pSics, cmdName) != NULL) { - /* print only SICS commands */ - SCPrintf(pCon, eLog, "%s:%d>> %s",self->name,self->lineno,cmd); + /* print only SICS commands */ + SCPrintf(pCon, eLog, "%s:%d>> %s", self->name, self->lineno, + cmd); } else { - /* debugging */ - /* SCPrintf(pCon, eValue, "%s:%d>> %s",self->name,self->lineno,cmd); */ + /* debugging */ + /* SCPrintf(pCon, eValue, "%s:%d>> %s",self->name,self->lineno,cmd); */ } } } - - status = Tcl_Eval(pTcl,cmd); - if(status != TCL_OK){ - if(pCon->sicsError == 0){ - /* - Tcl Error - */ - if(strlen(pTcl->result) >= 2){ - SCPrintf(pCon,eLogError,"ERROR: Tcl reported: %s", pTcl->result); + + status = Tcl_Eval(pTcl, cmd); + if (status != TCL_OK) { + if (pCon->sicsError == 0) { + /* + Tcl Error + */ + if (strlen(pTcl->result) >= 2) { + SCPrintf(pCon, eLogError, "ERROR: Tcl reported: %s", + pTcl->result); } - SCWrite(pCon,"ERROR: Tcl error in block:",eLogError); - SCWrite(pCon,GetCharArray(command),eError); - SCWrite(pCon,"ERROR: end of Tcl error block",eLogError); + SCWrite(pCon, "ERROR: Tcl error in block:", eLogError); + SCWrite(pCon, GetCharArray(command), eError); + SCWrite(pCon, "ERROR: end of Tcl error block", eLogError); } else { - /* - SICS error: has already been reported - */ - pCon->sicsError = 0; + /* + SICS error: has already been reported + */ + pCon->sicsError = 0; } } DeleteDynString(command); - if(SCGetInterrupt(pCon) >= eAbortBatch){ - SCWrite(pCon,"ERROR: batch processing interrupted",eError); + if (SCGetInterrupt(pCon) >= eAbortBatch) { + SCWrite(pCon, "ERROR: batch processing interrupted", eError); SetStatus(eEager); return 0; } else { - SCSetInterrupt(pCon,eContinue); + SCSetInterrupt(pCon, eContinue); } } - if(pCall != NULL){ - InvokeCallBack(pCall,BATCHEND,self->name); + if (pCall != NULL) { + InvokeCallBack(pCall, BATCHEND, self->name); } return 1; } + /*---------------------------------------------------------------------*/ -int exeBufProcessErrList(pExeBuf self, SicsInterp *pSics, - SConnection *pCon, int errList){ +int exeBufProcessErrList(pExeBuf self, SicsInterp * pSics, + SConnection * pCon, int errList) +{ pDynString command = NULL; Tcl_Interp *pTcl = NULL; int status; - + static int weWantLogging = 1; char *cmd; char cmdName[128]; @@ -252,7 +273,7 @@ int exeBufProcessErrList(pExeBuf self, SicsInterp *pSics, char msg[132]; char *ende; int l; - + assert(self); assert(pSics); @@ -261,60 +282,64 @@ int exeBufProcessErrList(pExeBuf self, SicsInterp *pSics, self->lineno = 0; pTcl = InterpGetTcl(pSics); - while((command = findBlockEnd(self)) != NULL){ + while ((command = findBlockEnd(self)) != NULL) { cmd = GetCharArray(command); - - status = Tcl_Eval(pTcl,cmd); - if(status != TCL_OK){ - LLDstringAppend(errList,cmd); - error = (char *)Tcl_GetStringResult(pTcl); - snprintf(msg, sizeof msg, "#ERR: %s\n", error); - LLDstringAppend(errList,msg); + + status = Tcl_Eval(pTcl, cmd); + if (status != TCL_OK) { + LLDstringAppend(errList, cmd); + error = (char *) Tcl_GetStringResult(pTcl); + snprintf(msg, sizeof msg, "#ERR: %s\n", error); + LLDstringAppend(errList, msg); } DeleteDynString(command); - if(SCGetInterrupt(pCon) >= eAbortBatch){ - SCWrite(pCon,"ERROR: batch processing interrupted",eError); + if (SCGetInterrupt(pCon) >= eAbortBatch) { + SCWrite(pCon, "ERROR: batch processing interrupted", eError); SetStatus(eEager); return 0; } else { - SCSetInterrupt(pCon,eContinue); + SCSetInterrupt(pCon, eContinue); } } return 1; } + /*------------------------------------------------------------------------*/ -void exeBufRange(pExeBuf self, int *start, int *end, int *lineno){ +void exeBufRange(pExeBuf self, int *start, int *end, int *lineno) +{ assert(self); *start = self->start; *end = self->end; *lineno = self->lineno; } + /*------------------------------------------------------------------------*/ -pDynString exeBufText(pExeBuf self, int start, int end){ +pDynString exeBufText(pExeBuf self, int start, int end) +{ pDynString result = NULL; char *pPtr; int i; assert(self); - - result = CreateDynString(256,132); - if(result == NULL){ + + result = CreateDynString(256, 132); + if (result == NULL) { return NULL; } pPtr = GetCharArray(self->bufferContent); - if(end >= strlen(pPtr)){ - end = strlen(pPtr) -1; + if (end >= strlen(pPtr)) { + end = strlen(pPtr) - 1; + } + for (i = start; i < end; i++) { + DynStringConcatChar(result, pPtr[i]); } - for(i = start; i < end; i++){ - DynStringConcatChar(result,pPtr[i]); - } return result; } + /*-----------------------------------------------------------------------*/ -char *exeBufName(pExeBuf self){ +char *exeBufName(pExeBuf self) +{ assert(self); return self->name; } - - diff --git a/exebuf.h b/exebuf.h index fc9de594..bed450ff 100644 --- a/exebuf.h +++ b/exebuf.h @@ -16,27 +16,27 @@ #line 44 "exe.w" - typedef struct __EXEBUF *pExeBuf; +typedef struct __EXEBUF *pExeBuf; /** * create an exe buffer * @param The name to use for the exe buffer * @return A new exe buffer or NULL if out of memory */ - pExeBuf exeBufCreate(char *name); +pExeBuf exeBufCreate(char *name); /** * delete an exe buffer * @param data The exe buffer to delete */ - void exeBufKill(void *data); - void exeBufDelete(pExeBuf data); +void exeBufKill(void *data); +void exeBufDelete(pExeBuf data); /** * add a a line to the exe buffer * @param self The exe buffer the line is to be added to * @param line The text to add * @return 1 on success, 0 when out of memory */ - int exeBufAppend(pExeBuf self, char *line); +int exeBufAppend(pExeBuf self, char *line); /** * load an exe buffer from a file * @param self The exe buffer to load @@ -44,14 +44,14 @@ * @return 1 on success, 0 if the file could not be opened or * memory is exhausted. */ - int exeBufLoad(pExeBuf self, char *filename); +int exeBufLoad(pExeBuf self, char *filename); /** * save an exe buffer to a file. * @param self The exe buffer to laod * @param filename The name of the file to laod * @return 1 on success, 0 if the file could not be opened. */ - int exeBufSave(pExeBuf self, char *filename); +int exeBufSave(pExeBuf self, char *filename); /** * process an exe buffer * @param self The exe buffer to process @@ -61,8 +61,8 @@ * @pCall The callback interface to use for automatic notifications * @return 1 on success, 0 on error */ - int exeBufProcess(pExeBuf self, SicsInterp *pSics, - SConnection *pCon, pICallBack pCall, int echo); +int exeBufProcess(pExeBuf self, SicsInterp * pSics, + SConnection * pCon, pICallBack pCall, int echo); /** * Process an exe buffer, but store commands causing errors in a list. * This is used for restoring status files. @@ -74,8 +74,8 @@ * had errors. * @return 1 on success, 0 on error */ - int exeBufProcessErrList(pExeBuf self, SicsInterp *pSics, - SConnection *pCon, int errCommandList); +int exeBufProcessErrList(pExeBuf self, SicsInterp * pSics, + SConnection * pCon, int errCommandList); /** * retrieves the executing range * @param self The exe buffer to query @@ -83,7 +83,7 @@ * @param end The end of the executing range * @param lineno The current line number */ - void exeBufRange(pExeBuf self, int *start, int *end, int *lineno); +void exeBufRange(pExeBuf self, int *start, int *end, int *lineno); /** * retrieves some portion of text * @param self The exe buffer to query @@ -93,14 +93,14 @@ * the clients task to delete this buffer sfter use. Or NULL if out of * memory. */ - pDynString exeBufText(pExeBuf self, int start, int end); +pDynString exeBufText(pExeBuf self, int start, int end); /** * retrieves the name of the batch buffer * @param self The exe buffer to query * @return A pointer to the buffer name. Do not delete! The name * is still owned by the exe beuffer. */ - char *exeBufName(pExeBuf self); +char *exeBufName(pExeBuf self); #line 240 "exe.w" diff --git a/exeman.c b/exeman.c index f963b913..d62cb5ec 100644 --- a/exeman.c +++ b/exeman.c @@ -27,129 +27,133 @@ #include "commandlog.h" #include "protocol.h" /*-------------------------------------------------------------------*/ -static void KillExeMan(void *data){ - pExeMan self = (pExeMan)data; - if(!self){ +static void KillExeMan(void *data) +{ + pExeMan self = (pExeMan) data; + if (!self) { return; } - if(self->pDes){ + if (self->pDes) { DeleteDescriptor(self->pDes); } - if(self->pCall){ + if (self->pCall) { DeleteCallBackInterface(self->pCall); } - if(self->batchPath){ + if (self->batchPath) { free(self->batchPath); } - if(self->sysPath){ + if (self->sysPath) { free(self->sysPath); } - if(self->exeStack){ + if (self->exeStack) { DeleteDynar(self->exeStack); } LLDdelete(self->runList); free(self); } -/*-----------------------------------------------------------------*/ -static int SaveExeMan(void *data, char *name, FILE *fd){ - pExeMan self = (pExeMan)data; - if(!self){ +/*-----------------------------------------------------------------*/ +static int SaveExeMan(void *data, char *name, FILE * fd) +{ + pExeMan self = (pExeMan) data; + + if (!self) { return 0; } - fprintf(fd,"%s batchpath %s\n",name,self->batchPath); - fprintf(fd,"%s syspath %s\n",name,self->sysPath); + fprintf(fd, "%s batchpath %s\n", name, self->batchPath); + fprintf(fd, "%s syspath %s\n", name, self->sysPath); return 1; } -/*-----------------------------------------------------------------*/ -static void *ExeManInterface(void *data, int interfaceID){ - pExeMan self = (pExeMan)data; - if(self == NULL){ +/*-----------------------------------------------------------------*/ +static void *ExeManInterface(void *data, int interfaceID) +{ + pExeMan self = (pExeMan) data; + + if (self == NULL) { return NULL; } - if(interfaceID == CALLBACKINTERFACE){ + if (interfaceID == CALLBACKINTERFACE) { return self->pCall; } return NULL; } + /*------------------------------------------------------------------*/ -int MakeExeManager(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int MakeExeManager(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pExeMan pNew = NULL; int status; - pNew = (pExeMan)malloc(sizeof(ExeMan)); - if(!pNew){ - SCWrite(pCon,"ERROR: out of memory creating exe Manager",eError); + pNew = (pExeMan) malloc(sizeof(ExeMan)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory creating exe Manager", eError); return 0; } - memset(pNew,0,sizeof(ExeMan)); + memset(pNew, 0, sizeof(ExeMan)); pNew->pDes = CreateDescriptor("ExeManager"); pNew->pCall = CreateCallBackInterface(); pNew->sysPath = strdup("./"); pNew->batchPath = strdup("./"); - pNew->exeStack = CreateDynar(1,10,10,exeBufKill); + pNew->exeStack = CreateDynar(1, 10, 10, exeBufKill); pNew->exeStackPtr = -1; pNew->runList = LLDcreate(sizeof(pExeBuf)); - if(!pNew->pDes || !pNew->pCall || ! pNew->batchPath || - !pNew->exeStack || pNew->runList < 0){ - SCWrite(pCon,"ERROR: out of memory creating exe Manager",eError); + if (!pNew->pDes || !pNew->pCall || !pNew->batchPath || + !pNew->exeStack || pNew->runList < 0) { + SCWrite(pCon, "ERROR: out of memory creating exe Manager", eError); return 0; } pNew->pDes->SaveStatus = SaveExeMan; pNew->pDes->GetInterface = ExeManInterface; - if(argc > 1){ + if (argc > 1) { status = AddCommand(pSics, - argv[1], - ExeManagerWrapper, - KillExeMan, - pNew); + argv[1], ExeManagerWrapper, KillExeMan, pNew); } else { - status = AddCommand(pSics, - "exe", - ExeManagerWrapper, - KillExeMan, - pNew); + status = AddCommand(pSics, "exe", ExeManagerWrapper, KillExeMan, pNew); } - if(status != 1) { - SCWrite(pCon,"ERROR: duplicate exe manager not created",eError); + if (status != 1) { + SCWrite(pCon, "ERROR: duplicate exe manager not created", eError); return 0; } return 1; } + /*======================== buffer execution ==========================*/ -static int fileExists(char *path){ +static int fileExists(char *path) +{ FILE *fd = NULL; int status = 0; - fd = fopen(path,"r"); - if(fd != NULL){ + fd = fopen(path, "r"); + if (fd != NULL) { fclose(fd); status = 1; } return status; } + /*--------------------------------------------------------------------*/ extern char *stptok(char *s, char *t, int len, char *brk); -static pDynString locateBatchBuffer(pExeMan self, char *name){ +static pDynString locateBatchBuffer(pExeMan self, char *name) +{ pDynString result = NULL; char pPath[132], *pPtr = NULL; - result = CreateDynString(256,256); - if(!result){ + result = CreateDynString(256, 256); + if (!result) { return NULL; } /* - do not try to convert absolute paths - */ - if(name[0] == '/'){ - DynStringCopy(result,name); - if(fileExists(GetCharArray(result))){ + do not try to convert absolute paths + */ + if (name[0] == '/') { + DynStringCopy(result, name); + if (fileExists(GetCharArray(result))) { return result; } else { return NULL; @@ -157,265 +161,279 @@ static pDynString locateBatchBuffer(pExeMan self, char *name){ } pPtr = self->batchPath; - while((pPtr = stptok(pPtr,pPath,131,":")) != NULL){ - DynStringCopy(result,pPath); - DynStringConcatChar(result,'/'); - DynStringConcat(result,name); - if(fileExists(GetCharArray(result))){ + while ((pPtr = stptok(pPtr, pPath, 131, ":")) != NULL) { + DynStringCopy(result, pPath); + DynStringConcatChar(result, '/'); + DynStringConcat(result, name); + if (fileExists(GetCharArray(result))) { return result; } } pPtr = self->sysPath; - while((pPtr = stptok(pPtr,pPath,131,":")) != NULL){ - DynStringCopy(result,pPath); - DynStringConcatChar(result,'/'); - DynStringConcat(result,name); - if(fileExists(GetCharArray(result))){ + while ((pPtr = stptok(pPtr, pPath, 131, ":")) != NULL) { + DynStringCopy(result, pPath); + DynStringConcatChar(result, '/'); + DynStringConcat(result, name); + if (fileExists(GetCharArray(result))) { return result; } } DeleteDynString(result); return NULL; } + /*------------------------------------------------------------------- * Generate a full path name for the argument in the first * directory of batch path * -------------------------------------------------------------------*/ -static int makeExePath(pExeMan self, SConnection *pCon, int argc, char *argv[]){ - char buffer[512], *pPtr = NULL, pPath[132]; - - if(argc < 3) { - SCWrite(pCon,"ERROR: require a file name for makepath",eError); - return 0; - } - strcpy(buffer,"exe.makepath = "); - /* - * do nothing to absolute path - */ - if(argv[2][0] == '/'){ - strncat(buffer,argv[2],511-strlen(buffer)); - SCWrite(pCon,buffer,eValue); - return 1; - } - pPtr = self->batchPath; - pPtr = stptok(pPtr,pPath,131,":"); - strncat(buffer,pPath,511-strlen(buffer)); - strncat(buffer,"/",511-strlen(buffer)); - strncat(buffer,argv[2],511-strlen(buffer)); - SCWrite(pCon,buffer,eValue); - +static int makeExePath(pExeMan self, SConnection * pCon, int argc, + char *argv[]) +{ + char buffer[512], *pPtr = NULL, pPath[132]; + + if (argc < 3) { + SCWrite(pCon, "ERROR: require a file name for makepath", eError); + return 0; + } + strcpy(buffer, "exe.makepath = "); + /* + * do nothing to absolute path + */ + if (argv[2][0] == '/') { + strncat(buffer, argv[2], 511 - strlen(buffer)); + SCWrite(pCon, buffer, eValue); return 1; + } + pPtr = self->batchPath; + pPtr = stptok(pPtr, pPath, 131, ":"); + strncat(buffer, pPath, 511 - strlen(buffer)); + strncat(buffer, "/", 511 - strlen(buffer)); + strncat(buffer, argv[2], 511 - strlen(buffer)); + SCWrite(pCon, buffer, eValue); + + return 1; } + /*--------------------------------------------------------------------*/ -pDynString findBatchFile(SicsInterp *pSics, char *name){ - pExeMan self = (pExeMan)FindCommandData(pSics,"exe","ExeManager"); - if(self == NULL){ - return NULL; - } - return locateBatchBuffer(self,name); +pDynString findBatchFile(SicsInterp * pSics, char *name) +{ + pExeMan self = (pExeMan) FindCommandData(pSics, "exe", "ExeManager"); + if (self == NULL) { + return NULL; + } + return locateBatchBuffer(self, name); } + /*--------------------------------------------------------------------*/ -static int runBatchBuffer(pExeMan self, SConnection *pCon, - SicsInterp *pSics, char *name){ +static int runBatchBuffer(pExeMan self, SConnection * pCon, + SicsInterp * pSics, char *name) +{ pDynString filePath = NULL; char pBueffel[256]; pExeBuf buffer = NULL; int status; - if(!SCMatchRights(pCon,usUser)) { + if (!SCMatchRights(pCon, usUser)) { return 0; } - - if(self->runCon != NULL && self->runCon != pCon){ - SCWrite(pCon,"ERROR: another batch buffer is already runnig", eError); - return 0; + + if (self->runCon != NULL && self->runCon != pCon) { + SCWrite(pCon, "ERROR: another batch buffer is already runnig", eError); + return 0; } - - filePath = locateBatchBuffer(self,name); - if(filePath == NULL){ - snprintf(pBueffel,255,"ERROR: batch buffer %s not found in path", - name); - SCWrite(pCon,pBueffel,eError); + + filePath = locateBatchBuffer(self, name); + if (filePath == NULL) { + snprintf(pBueffel, 255, "ERROR: batch buffer %s not found in path", + name); + SCWrite(pCon, pBueffel, eError); return 0; } buffer = exeBufCreate(name); - if(!buffer){ + if (!buffer) { DeleteDynString(filePath); - SCWrite(pCon,"ERROR: out of memory creating batch buffer",eError); + SCWrite(pCon, "ERROR: out of memory creating batch buffer", eError); return 0; } - status = exeBufLoad(buffer,GetCharArray(filePath)); - if(!status){ + status = exeBufLoad(buffer, GetCharArray(filePath)); + if (!status) { DeleteDynString(filePath); - SCWrite(pCon,"ERROR: failed to load batch buffer",eError); + SCWrite(pCon, "ERROR: failed to load batch buffer", eError); return 0; } DeleteDynString(filePath); self->exeStackPtr++; - DynarPut(self->exeStack,self->exeStackPtr,buffer); - status = exeBufProcess(buffer,pSics,pCon,self->pCall,self->echo); + DynarPut(self->exeStack, self->exeStackPtr, buffer); + status = exeBufProcess(buffer, pSics, pCon, self->pCall, self->echo); self->exeStackPtr--; return status; -} +} + /*-------------------------------------------------------------------*/ static char bufferNode[512]; -static int SCHdbWrite(SConnection *self, char *message, int outCode){ - pHdb node = NULL; - char pBueffel[512]; - commandContext cc; - hdbValue v; - pDynString val = NULL; - writeFunc defWrite = NULL; - - - cc = SCGetContext(self); - node = GetHipadabaNode(GetHipadabaRoot(),cc.deviceID); - if(node == NULL || strstr(cc.deviceID,bufferNode) == NULL){ - /* - * this means the deviceId is wrong and the output is for another - * operation. - */ - defWrite = GetProtocolWriteFunc(self); - if(defWrite == NULL){ - defWrite = SCNormalWrite; - } - defWrite(self,message,outCode); - return 1; - } +static int SCHdbWrite(SConnection * self, char *message, int outCode) +{ + pHdb node = NULL; + char pBueffel[512]; + commandContext cc; + hdbValue v; + pDynString val = NULL; + writeFunc defWrite = NULL; - SCFileWrite(self,message,outCode); - if(SCinMacro(self) && (outCode != eError && outCode != eWarning) ){ - return 1; + cc = SCGetContext(self); + node = GetHipadabaNode(GetHipadabaRoot(), cc.deviceID); + if (node == NULL || strstr(cc.deviceID, bufferNode) == NULL) { + /* + * this means the deviceId is wrong and the output is for another + * operation. + */ + defWrite = GetProtocolWriteFunc(self); + if (defWrite == NULL) { + defWrite = SCNormalWrite; } - - v = MakeHdbText(strdup("")); - GetHipadabaPar(node,&v,NULL); - v.dataType = HIPTEXT; - val = CreateDynString(128,128); - if(val == NULL){ - WriteToCommandLog("INTERNAL ERROR>>", - "No memory to append to log in SCHdbWrite"); - return 0; - } - if(v.v.text != NULL){ - DynStringConcat(val,v.v.text); - if(strrchr(v.v.text,(int)'\n') == NULL && strlen(v.v.text) > 1){ - DynStringConcatChar(val,'\n'); - } - } - DynStringConcat(val,message); - if(strrchr(message,(int)'\n') == NULL && strlen(message) > 1){ - DynStringConcatChar(val,'\n'); - } - if(v.v.text != NULL){ - free(v.v.text); - } - v.v.text = GetCharArray(val); - UpdateHipadabaPar(node,v,NULL); - DeleteDynString(val); + defWrite(self, message, outCode); return 1; + } + + SCFileWrite(self, message, outCode); + + if (SCinMacro(self) && (outCode != eError && outCode != eWarning)) { + return 1; + } + + v = MakeHdbText(strdup("")); + GetHipadabaPar(node, &v, NULL); + v.dataType = HIPTEXT; + val = CreateDynString(128, 128); + if (val == NULL) { + WriteToCommandLog("INTERNAL ERROR>>", + "No memory to append to log in SCHdbWrite"); + return 0; + } + if (v.v.text != NULL) { + DynStringConcat(val, v.v.text); + if (strrchr(v.v.text, (int) '\n') == NULL && strlen(v.v.text) > 1) { + DynStringConcatChar(val, '\n'); + } + } + DynStringConcat(val, message); + if (strrchr(message, (int) '\n') == NULL && strlen(message) > 1) { + DynStringConcatChar(val, '\n'); + } + if (v.v.text != NULL) { + free(v.v.text); + } + v.v.text = GetCharArray(val); + UpdateHipadabaPar(node, v, NULL); + DeleteDynString(val); + return 1; } + /*--------------------------------------------------------------------*/ -int exeHdbNode(pHdb exeNode, SConnection *pCon){ +int exeHdbNode(pHdb exeNode, SConnection * pCon) +{ char pBueffel[512], *name = NULL; - pHdb node = NULL, log = NULL; + pHdb node = NULL, log = NULL; pExeBuf buffer = NULL; hdbValue v; int status; SConnection *conCon = NULL; - + /* * clear log buffer */ - log = GetHipadabaNode(exeNode,"log"); - if(log == NULL){ - SCWrite(pCon,"ERROR: Hdb node not found or in wrong format",eError); + log = GetHipadabaNode(exeNode, "log"); + if (log == NULL) { + SCWrite(pCon, "ERROR: Hdb node not found or in wrong format", eError); return 0; } v = MakeHdbText(strdup("")); - UpdateHipadabaPar(log,v,pCon); + UpdateHipadabaPar(log, v, pCon); /* * prepare context */ name = GetHipadabaPath(log); conCon = SCCopyConnection(pCon); - if(conCon == NULL){ - SCWrite(pCon,"ERROR: out of memory in exehdbNode", eError); - return 0; + if (conCon == NULL) { + SCWrite(pCon, "ERROR: out of memory in exehdbNode", eError); + return 0; } - strncpy(conCon->deviceID, name,255); - strncpy(bufferNode,name,511); + strncpy(conCon->deviceID, name, 255); + strncpy(bufferNode, name, 511); /* * load commands into buffer - */ - node = GetHipadabaNode(exeNode,"commands"); - if(node == NULL){ - SCWrite(pCon,"ERROR: Hdb node not found or in wrong format",eError); + */ + node = GetHipadabaNode(exeNode, "commands"); + if (node == NULL) { + SCWrite(pCon, "ERROR: Hdb node not found or in wrong format", eError); return 0; } - GetHipadabaPar(node,&v,pCon); - if(v.dataType != HIPTEXT || v.v.text == NULL){ - SCWrite(pCon,"ERROR: Hdb node is of wrong type or contains no data",eError); + GetHipadabaPar(node, &v, pCon); + if (v.dataType != HIPTEXT || v.v.text == NULL) { + SCWrite(pCon, "ERROR: Hdb node is of wrong type or contains no data", + eError); return 0; - + } - + buffer = exeBufCreate(name); - if(!buffer){ - SCWrite(pCon,"ERROR: out of memory creating batch buffer",eError); + if (!buffer) { + SCWrite(pCon, "ERROR: out of memory creating batch buffer", eError); return 0; } - exeBufAppend(buffer,v.v.text); + exeBufAppend(buffer, v.v.text); - strncpy(bufferNode,name,511); - SCSetWriteFunc(conCon,SCHdbWrite); - status = exeBufProcess(buffer,pServ->pSics,conCon,NULL,0); + strncpy(bufferNode, name, 511); + SCSetWriteFunc(conCon, SCHdbWrite); + status = exeBufProcess(buffer, pServ->pSics, conCon, NULL, 0); SCDeleteConnection(conCon); exeBufDelete(buffer); free(name); - if(strlen(log->value.v.text) < 2){ - v = MakeHdbText(strdup("OK\n")); - UpdateHipadabaPar(log,v,pCon); - ReleaseHdbValue(&v); + if (strlen(log->value.v.text) < 2) { + v = MakeHdbText(strdup("OK\n")); + UpdateHipadabaPar(log, v, pCon); + ReleaseHdbValue(&v); } return status; } + /*--------------------------------------------------------------------*/ -static int runHdbBuffer(pExeMan self, SConnection *pCon, - SicsInterp *pSics, char *name){ +static int runHdbBuffer(pExeMan self, SConnection * pCon, + SicsInterp * pSics, char *name) +{ char pBueffel[512]; pExeBuf buffer = NULL; pHdb node = NULL; hdbValue v; int status; SConnection *conCon = NULL; - - if(!SCMatchRights(pCon,usUser)) { + + if (!SCMatchRights(pCon, usUser)) { return 0; } - - if(self->runCon != NULL && self->runCon != pCon){ - SCWrite(pCon,"ERROR: another bacth buffer is still running", eError); - return 0; + + if (self->runCon != NULL && self->runCon != pCon) { + SCWrite(pCon, "ERROR: another bacth buffer is still running", eError); + return 0; } /* * clear log buffer */ - snprintf(pBueffel,511,"%s/log",name); - node = GetHipadabaNode(GetHipadabaRoot(),pBueffel); - if(node == NULL){ - SCWrite(pCon,"ERROR: Hdb node not found or in wrong format",eError); + snprintf(pBueffel, 511, "%s/log", name); + node = GetHipadabaNode(GetHipadabaRoot(), pBueffel); + if (node == NULL) { + SCWrite(pCon, "ERROR: Hdb node not found or in wrong format", eError); return 0; } v = MakeHdbText(strdup("")); - UpdateHipadabaPar(node,v,pCon); + UpdateHipadabaPar(node, v, pCon); /* * prepare context */ @@ -424,163 +442,178 @@ static int runHdbBuffer(pExeMan self, SConnection *pCon, /* * load commands into buffer - */ - snprintf(pBueffel,511,"%s/commands",name); - node = GetHipadabaNode(GetHipadabaRoot(),pBueffel); - if(node == NULL){ - SCWrite(pCon,"ERROR: Hdb node not found or in wrong format",eError); + */ + snprintf(pBueffel, 511, "%s/commands", name); + node = GetHipadabaNode(GetHipadabaRoot(), pBueffel); + if (node == NULL) { + SCWrite(pCon, "ERROR: Hdb node not found or in wrong format", eError); return 0; } - GetHipadabaPar(node,&v,pCon); - if(v.dataType != HIPTEXT || v.v.text == NULL){ - SCWrite(pCon,"ERROR: Hdb node is of wrong type or contains no data",eError); + GetHipadabaPar(node, &v, pCon); + if (v.dataType != HIPTEXT || v.v.text == NULL) { + SCWrite(pCon, "ERROR: Hdb node is of wrong type or contains no data", + eError); return 0; - + } - + buffer = exeBufCreate(name); - if(!buffer){ - SCWrite(pCon,"ERROR: out of memory creating batch buffer",eError); + if (!buffer) { + SCWrite(pCon, "ERROR: out of memory creating batch buffer", eError); return 0; } - exeBufAppend(buffer,v.v.text); + exeBufAppend(buffer, v.v.text); - strncpy(bufferNode,name,511); - SCSetWriteFunc(conCon,SCHdbWrite); + strncpy(bufferNode, name, 511); + SCSetWriteFunc(conCon, SCHdbWrite); self->exeStackPtr++; self->runCon = conCon; - DynarPut(self->exeStack,self->exeStackPtr,buffer); - status = exeBufProcess(buffer,pSics,conCon,self->pCall,self->echo); + DynarPut(self->exeStack, self->exeStackPtr, buffer); + status = exeBufProcess(buffer, pSics, conCon, self->pCall, self->echo); self->exeStackPtr--; self->runCon = NULL; SCDeleteConnection(conCon); return status; -} -/*--------------------------------------------------------------------*/ -int exeHdbBuffer(SConnection *pCon, - SicsInterp *pSics, char *name){ - pExeMan self = (pExeMan)FindCommandData(pSics,"exe","ExeManager"); - if(self != NULL){ - return runHdbBuffer(self,pCon,pSics,name); - } - return 0; } + +/*--------------------------------------------------------------------*/ +int exeHdbBuffer(SConnection * pCon, SicsInterp * pSics, char *name) +{ + pExeMan self = (pExeMan) FindCommandData(pSics, "exe", "ExeManager"); + if (self != NULL) { + return runHdbBuffer(self, pCon, pSics, name); + } + return 0; +} + /*-------------------------------------------------------------------*/ -int runExeBatchBuffer(void *pData, SConnection *pCon, - SicsInterp *pSics, char *name){ - int status, oldEcho; - pExeMan self = (pExeMan)pData; +int runExeBatchBuffer(void *pData, SConnection * pCon, + SicsInterp * pSics, char *name) +{ + int status, oldEcho; + pExeMan self = (pExeMan) pData; oldEcho = self->echo; self->echo = 1; - status = runBatchBuffer(self,pCon,pSics,name); + status = runBatchBuffer(self, pCon, pSics, name); self->echo = oldEcho; return status; } + /*========================== path management ========================*/ -static int handleBatchPath(pExeMan self, SConnection *pCon, int argc, - char *argv[]){ +static int handleBatchPath(pExeMan self, SConnection * pCon, int argc, + char *argv[]) +{ char pBuffer[1024]; - if(strcmp(argv[1],"batchpath") == 0) { - if(argc > 2) { - if(!SCMatchRights(pCon,usUser)){ - return 0; + if (strcmp(argv[1], "batchpath") == 0) { + if (argc > 2) { + if (!SCMatchRights(pCon, usUser)) { + return 0; } - if(self->batchPath != NULL){ - free(self->batchPath); + if (self->batchPath != NULL) { + free(self->batchPath); } self->batchPath = strdup(argv[2]); SCSendOK(pCon); SCparChange(pCon); return 1; } else { - snprintf(pBuffer,1023,"%s.batchpath = %s", argv[0],self->batchPath); - SCWrite(pCon,pBuffer,eValue); + snprintf(pBuffer, 1023, "%s.batchpath = %s", argv[0], + self->batchPath); + SCWrite(pCon, pBuffer, eValue); return 1; } } - if(strcmp(argv[1],"syspath") == 0) { - if(argc > 2) { - if(!SCMatchRights(pCon,usMugger)){ - return 0; + if (strcmp(argv[1], "syspath") == 0) { + if (argc > 2) { + if (!SCMatchRights(pCon, usMugger)) { + return 0; } - if(self->sysPath != NULL){ - free(self->sysPath); + if (self->sysPath != NULL) { + free(self->sysPath); } self->sysPath = strdup(argv[2]); SCSendOK(pCon); SCparChange(pCon); return 1; } else { - snprintf(pBuffer,1023,"%s.syspath = %s", argv[0],self->sysPath); - SCWrite(pCon,pBuffer,eValue); + snprintf(pBuffer, 1023, "%s.syspath = %s", argv[0], self->sysPath); + SCWrite(pCon, pBuffer, eValue); return 1; } } return -1; } + /*=========================== callbacks ==============================*/ typedef struct { SConnection *pCon; - pExeMan exe; -}exeInfo, *pExeInfo; + pExeMan exe; +} exeInfo, *pExeInfo; /*------------------------------------------------------------------*/ -static void killExeInfo(void *pData){ - pExeInfo self = (pExeInfo)pData; - if(self->pCon != NULL){ - SCDeleteConnection(self->pCon); +static void killExeInfo(void *pData) +{ + pExeInfo self = (pExeInfo) pData; + if (self->pCon != NULL) { + SCDeleteConnection(self->pCon); } - if(self != NULL){ + if (self != NULL) { free(self); } } + /*-----------------------------------------------------------------*/ -static pExeInfo makeExeInfo(SConnection *pCon, pExeMan self){ +static pExeInfo makeExeInfo(SConnection * pCon, pExeMan self) +{ pExeInfo pNew = NULL; pNew = malloc(sizeof(exeInfo)); - if(pNew == NULL){ + if (pNew == NULL) { SCWrite(pCon, - "ERROR: failed to allocate info structure for registering callbacks", - eError); + "ERROR: failed to allocate info structure for registering callbacks", + eError); return NULL; } - memset(pNew,0,sizeof(exeInfo)); + memset(pNew, 0, sizeof(exeInfo)); pNew->pCon = SCCopyConnection(pCon); - if(pNew->pCon == NULL){ + if (pNew->pCon == NULL) { SCWrite(pCon, - "ERROR: failed to allocate info structure for registering callbacks", - eError); + "ERROR: failed to allocate info structure for registering callbacks", + eError); return NULL; } pNew->exe = self; return pNew; } -/*------------------------------------------------------------------*/ -static int BufferCallback(int iEvent, void *pEvent, void *pUser){ - pExeInfo self = (pExeInfo)pUser; - char *name = (char *)pEvent; - char pBueffel[132]; - if(!SCisConnected(self->pCon)){ +/*------------------------------------------------------------------*/ +static int BufferCallback(int iEvent, void *pEvent, void *pUser) +{ + pExeInfo self = (pExeInfo) pUser; + char *name = (char *) pEvent; + char pBueffel[132]; + + if (!SCisConnected(self->pCon)) { return -1; } - if(iEvent == BATCHSTART){ - snprintf(pBueffel,131,"BATCHSTART=%s",name); - SCWrite(self->pCon,pBueffel,eLog); + if (iEvent == BATCHSTART) { + snprintf(pBueffel, 131, "BATCHSTART=%s", name); + SCWrite(self->pCon, pBueffel, eLog); return 1; } - if(iEvent == BATCHEND){ - snprintf(pBueffel,131,"BATCHEND=%s",name); - SCWrite(self->pCon,pBueffel,eLog); + if (iEvent == BATCHEND) { + snprintf(pBueffel, 131, "BATCHEND=%s", name); + SCWrite(self->pCon, pBueffel, eLog); return 1; } return 0; } + /*-------------------------------------------------------------------*/ -static int LineCallBack(int iEvent, void *pEvent, void *pUser){ - pExeInfo self = (pExeInfo)pUser; +static int LineCallBack(int iEvent, void *pEvent, void *pUser) +{ + pExeInfo self = (pExeInfo) pUser; char pBueffel[256]; int start, end, lineno; void *pPtr = NULL; @@ -588,179 +621,195 @@ static int LineCallBack(int iEvent, void *pEvent, void *pUser){ assert(self); - if(!SCisConnected(self->pCon)){ + if (!SCisConnected(self->pCon)) { return -1; } - if(iEvent == BATCHAREA){ - DynarGet(self->exe->exeStack,self->exe->exeStackPtr,&pPtr); - buf = (pExeBuf)pPtr; + if (iEvent == BATCHAREA) { + DynarGet(self->exe->exeStack, self->exe->exeStackPtr, &pPtr); + buf = (pExeBuf) pPtr; assert(buf); - exeBufRange(buf,&start,&end,&lineno); - snprintf(pBueffel,255,"%s.range = %d = %d",exeBufName(buf), - start,end); - SCWrite(self->pCon,pBueffel,eLog); + exeBufRange(buf, &start, &end, &lineno); + snprintf(pBueffel, 255, "%s.range = %d = %d", exeBufName(buf), + start, end); + SCWrite(self->pCon, pBueffel, eLog); return 1; } return 0; } + /*--------------------------------------------------------------------*/ -static void registerCallbacks(SConnection *pCon, SicsInterp *pSics, - pExeMan self){ +static void registerCallbacks(SConnection * pCon, SicsInterp * pSics, + pExeMan self) +{ pExeInfo info = NULL; long lID; - info = makeExeInfo(pCon,self); - if(info == NULL){ + info = makeExeInfo(pCon, self); + if (info == NULL) { return; } - lID = RegisterCallback(self->pCall,BATCHSTART, BufferCallback, - info, killExeInfo); + lID = RegisterCallback(self->pCall, BATCHSTART, BufferCallback, + info, killExeInfo); lID = RegisterCallback(self->pCall, BATCHEND, BufferCallback, - info, NULL); - lID = RegisterCallback(self->pCall, BATCHAREA, LineCallBack, - info, NULL); -} + info, NULL); + lID = RegisterCallback(self->pCall, BATCHAREA, LineCallBack, info, NULL); +} + /*--------------------------------------------------------------------*/ -static void unregisterCallbacks(SConnection *pCon, pExeMan self){ +static void unregisterCallbacks(SConnection * pCon, pExeMan self) +{ long lID; int i; - for(i = 0; i < 3; i++){ - lID = SCgetCallbackID(pCon,self->pCall); - if(lID >= 0){ - RemoveCallback(self->pCall,lID); + for (i = 0; i < 3; i++) { + lID = SCgetCallbackID(pCon, self->pCall); + if (lID >= 0) { + RemoveCallback(self->pCall, lID); } } } + /*========================= uploading ===============================*/ -static int startUpload(pExeMan self, SConnection *pCon){ - if(SCGetRights(pCon) > usUser){ - SCWrite(pCon,"ERROR: no permission to upload buffers",eError); +static int startUpload(pExeMan self, SConnection * pCon) +{ + if (SCGetRights(pCon) > usUser) { + SCWrite(pCon, "ERROR: no permission to upload buffers", eError); return 0; } - if(self->uploadBuffer != NULL){ - SCWrite(pCon,"ERRO: another upload is still in progress",eError); + if (self->uploadBuffer != NULL) { + SCWrite(pCon, "ERRO: another upload is still in progress", eError); return 0; } self->uploadBuffer = exeBufCreate("upload"); - if(self->uploadBuffer == NULL){ - SCWrite(pCon,"ERROR: failed to create upload buffer",eError); + if (self->uploadBuffer == NULL) { + SCWrite(pCon, "ERROR: failed to create upload buffer", eError); return 0; } return 1; } + /*-------------------------------------------------------------------*/ -static int clearUpload(pExeMan self, SConnection *pCon){ - if(SCGetRights(pCon) > usUser){ - SCWrite(pCon,"ERROR: no permission to clear buffer upload",eError); +static int clearUpload(pExeMan self, SConnection * pCon) +{ + if (SCGetRights(pCon) > usUser) { + SCWrite(pCon, "ERROR: no permission to clear buffer upload", eError); return 0; } - if(self->uploadBuffer != NULL){ + if (self->uploadBuffer != NULL) { exeBufDelete(self->uploadBuffer); self->uploadBuffer = NULL; } - return 1; -} -/*---------------------------------------------------------------------*/ -static int appendLine(pExeMan self, SConnection *pCon, - int argc, char *argv[]){ - char pLine[1024]; - - if(SCGetRights(pCon) > usUser){ - SCWrite(pCon,"ERROR: no permission to upload buffers",eError); - return 0; - } - if(self->uploadBuffer == NULL){ - SCWrite(pCon,"ERROR: no upload in operation",eError); - return 0; - } - Arg2Text(argc-2,&argv[2],pLine,1023); - exeBufAppend(self->uploadBuffer,pLine); return 1; } + +/*---------------------------------------------------------------------*/ +static int appendLine(pExeMan self, SConnection * pCon, + int argc, char *argv[]) +{ + char pLine[1024]; + + if (SCGetRights(pCon) > usUser) { + SCWrite(pCon, "ERROR: no permission to upload buffers", eError); + return 0; + } + if (self->uploadBuffer == NULL) { + SCWrite(pCon, "ERROR: no upload in operation", eError); + return 0; + } + Arg2Text(argc - 2, &argv[2], pLine, 1023); + exeBufAppend(self->uploadBuffer, pLine); + return 1; +} + /*--------------------------------------------------------------------*/ -static int uploadForceSave(pExeMan self, SConnection *pCon, - int argc, char *argv[]){ +static int uploadForceSave(pExeMan self, SConnection * pCon, + int argc, char *argv[]) +{ int status; char pPath[256], *pPtr; - if(SCGetRights(pCon) > usUser){ - SCWrite(pCon,"ERROR: no permission to save buffers",eError); + if (SCGetRights(pCon) > usUser) { + SCWrite(pCon, "ERROR: no permission to save buffers", eError); return 0; } - if(argc < 3) { - SCWrite(pCon,"ERROR: no file given to save upload buffer to",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: no file given to save upload buffer to", eError); return 0; } - if(self->uploadBuffer == NULL){ - SCWrite(pCon,"ERROR: no upload buffer to save exists",eError); + if (self->uploadBuffer == NULL) { + SCWrite(pCon, "ERROR: no upload buffer to save exists", eError); return 0; } - if(argv[2][0] != '/') { + if (argv[2][0] != '/') { pPtr = self->batchPath; - pPtr = stptok(pPtr,pPath,131,":"); - if(strlen(pPath) + 1 + strlen(argv[2]) <= 256){ - strcat(pPath,"/"); - strcat(pPath,argv[2]); - } else { - strncpy(pPath,argv[2],255); + pPtr = stptok(pPtr, pPath, 131, ":"); + if (strlen(pPath) + 1 + strlen(argv[2]) <= 256) { + strcat(pPath, "/"); + strcat(pPath, argv[2]); + } else { + strncpy(pPath, argv[2], 255); } } else { - strncpy(pPath,argv[2],131); + strncpy(pPath, argv[2], 131); } - status = exeBufSave(self->uploadBuffer,pPath); - if(status == 0){ - SCWrite(pCon,"ERROR: failed to save exe buffer, destroyed...",eError); + status = exeBufSave(self->uploadBuffer, pPath); + if (status == 0) { + SCWrite(pCon, "ERROR: failed to save exe buffer, destroyed...", + eError); } exeBufDelete(self->uploadBuffer); self->uploadBuffer = NULL; return status; } + /*--------------------------------------------------------------------*/ -static int uploadSave(pExeMan self, SConnection *pCon, - int argc, char *argv[]){ +static int uploadSave(pExeMan self, SConnection * pCon, + int argc, char *argv[]) +{ int status; char pPath[256], *pPtr; - if(SCGetRights(pCon) > usUser){ - SCWrite(pCon,"ERROR: no permission to save buffers",eError); + if (SCGetRights(pCon) > usUser) { + SCWrite(pCon, "ERROR: no permission to save buffers", eError); return 0; } - if(argc < 3) { - SCWrite(pCon,"ERROR: no file given to save upload buffer to",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: no file given to save upload buffer to", eError); return 0; } - if(self->uploadBuffer == NULL){ - SCWrite(pCon,"ERROR: no upload buffer to save exists",eError); + if (self->uploadBuffer == NULL) { + SCWrite(pCon, "ERROR: no upload buffer to save exists", eError); return 0; } - if(argv[2][0] != '/') { + if (argv[2][0] != '/') { pPtr = self->batchPath; - pPtr = stptok(pPtr,pPath,131,":"); - if(strlen(pPath) + 1 + strlen(argv[2]) <= 256){ - strcat(pPath,"/"); - strcat(pPath,argv[2]); - } else { - strncpy(pPath,argv[2],255); + pPtr = stptok(pPtr, pPath, 131, ":"); + if (strlen(pPath) + 1 + strlen(argv[2]) <= 256) { + strcat(pPath, "/"); + strcat(pPath, argv[2]); + } else { + strncpy(pPath, argv[2], 255); } } else { - strncpy(pPath,argv[2],131); + strncpy(pPath, argv[2], 131); } - if(fileExists(pPath)) { - SCWrite(pCon,"ERROR: file exists",eError); + if (fileExists(pPath)) { + SCWrite(pCon, "ERROR: file exists", eError); return 0; } - status = exeBufSave(self->uploadBuffer,pPath); - if(status == 0){ - SCWrite(pCon,"ERROR: failed to save exe buffer, destroyed...",eError); + status = exeBufSave(self->uploadBuffer, pPath); + if (status == 0) { + SCWrite(pCon, "ERROR: failed to save exe buffer, destroyed...", + eError); } exeBufDelete(self->uploadBuffer); self->uploadBuffer = NULL; return status; } + /*---------------------------------------------------------------------------------*/ /* See if a string matches a wildcard specification that uses * or ? (like "*.txt"), and return TRUE or FALSE, depending on the result. @@ -772,429 +821,457 @@ static int uploadSave(pExeMan self, SConnection *pCon, #define FALSE 0 #endif /*--------------------------------------------------------------------------------*/ -static int IsWildcardMatch (char *wildcardString, char *stringToCheck, int caseSensitive) +static int IsWildcardMatch(char *wildcardString, char *stringToCheck, + int caseSensitive) { - char wcChar; - char strChar; - // use the starMatchesZero variable to determine whether an asterisk - // matches zero or more characters (TRUE) or one or more characters - // (FALSE) - int starMatchesZero = TRUE; + char wcChar; + char strChar; + // use the starMatchesZero variable to determine whether an asterisk + // matches zero or more characters (TRUE) or one or more characters + // (FALSE) + int starMatchesZero = TRUE; - while ((strChar = *stringToCheck) && (wcChar = *wildcardString)) - { - // we only want to advance the pointers if we successfully assigned - // both of our char variables, so we'll do it here rather than in the - // loop condition itself - *stringToCheck++; - *wildcardString++; + while ((strChar = *stringToCheck) && (wcChar = *wildcardString)) { + // we only want to advance the pointers if we successfully assigned + // both of our char variables, so we'll do it here rather than in the + // loop condition itself + *stringToCheck++; + *wildcardString++; - // if this isn't a case-sensitive match, make both chars uppercase - // (thanks to David John Fielder (Konan) at http://innuendo.ev.ca - // for pointing out an error here in the original code) - if (!caseSensitive) - { - wcChar = toupper(wcChar); - strChar = toupper(strChar); - } + // if this isn't a case-sensitive match, make both chars uppercase + // (thanks to David John Fielder (Konan) at http://innuendo.ev.ca + // for pointing out an error here in the original code) + if (!caseSensitive) { + wcChar = toupper(wcChar); + strChar = toupper(strChar); + } + // check the wcChar against our wildcard list + switch (wcChar) { + // an asterisk matches zero or more characters + case '*': + // do a recursive call against the rest of the string, + // until we've either found a match or the string has + // ended + if (starMatchesZero) + *stringToCheck--; - // check the wcChar against our wildcard list - switch (wcChar) - { - // an asterisk matches zero or more characters - case '*' : - // do a recursive call against the rest of the string, - // until we've either found a match or the string has - // ended - if (starMatchesZero) - *stringToCheck--; + while (*stringToCheck) { + if (IsWildcardMatch + (wildcardString, stringToCheck++, caseSensitive)) + return TRUE; + } - while (*stringToCheck) - { - if (IsWildcardMatch(wildcardString, stringToCheck++, caseSensitive)) - return TRUE; - } + break; - break; + // a question mark matches any single character + case '?': + break; - // a question mark matches any single character - case '?' : - break; + // if we fell through, we want an exact match + default: + if (wcChar != strChar) + return FALSE; + break; + } - // if we fell through, we want an exact match - default : - if (wcChar != strChar) - return FALSE; - break; - } + } - } + // if we have any asterisks left at the end of the wildcard string, we can + // advance past them if starMatchesZero is TRUE (so "blah*" will match "blah") + while ((*wildcardString) && (starMatchesZero)) { + if (*wildcardString == '*') + wildcardString++; + else + break; + } - // if we have any asterisks left at the end of the wildcard string, we can - // advance past them if starMatchesZero is TRUE (so "blah*" will match "blah") - while ((*wildcardString) && (starMatchesZero)) - { - if (*wildcardString == '*') - wildcardString++; - else - break; - } - - // if we got to the end but there's still stuff left in either of our strings, - // return false; otherwise, we have a match - if ((*stringToCheck) || (*wildcardString)) - return FALSE; - else - return TRUE; + // if we got to the end but there's still stuff left in either of our strings, + // return false; otherwise, we have a match + if ((*stringToCheck) || (*wildcardString)) + return FALSE; + else + return TRUE; } + /*----------------------------------------------------------------------------*/ -static int wwmatch(char *pattern, char *name){ - return IsWildcardMatch(pattern,name,1); +static int wwmatch(char *pattern, char *name) +{ + return IsWildcardMatch(pattern, name, 1); } + /*-------------------------------------------------------------------- search the directory pPath for file matching pattern. Successfull files will be appended to result -----------------------------------------------------------------------*/ -static void searchDir(char *pPath, char *pattern, pDynString result){ +static void searchDir(char *pPath, char *pattern, pDynString result) +{ DIR *currentdir = NULL; struct dirent *currentFile = NULL; - + currentdir = opendir(pPath); - if(currentdir == NULL){ + if (currentdir == NULL) { return; } currentFile = readdir(currentdir); - while(currentFile != NULL){ - if(wwmatch(pattern, currentFile->d_name)){ - DynStringConcat(result,currentFile->d_name); - DynStringConcatChar(result,'\n'); + while (currentFile != NULL) { + if (wwmatch(pattern, currentFile->d_name)) { + DynStringConcat(result, currentFile->d_name); + DynStringConcatChar(result, '\n'); } currentFile = readdir(currentdir); } closedir(currentdir); } + /*--------------------------------------------------------------------*/ -static pDynString findDirEntries(pExeMan self, char *pattern){ +static pDynString findDirEntries(pExeMan self, char *pattern) +{ pDynString result = NULL; char pPath[132], *pPtr = NULL; - result = CreateDynString(256,256); - if(!result){ + result = CreateDynString(256, 256); + if (!result) { return NULL; } pPtr = self->batchPath; - while((pPtr = stptok(pPtr,pPath,131,":")) != NULL){ - searchDir(pPath,pattern,result); + while ((pPtr = stptok(pPtr, pPath, 131, ":")) != NULL) { + searchDir(pPath, pattern, result); } pPtr = self->sysPath; - while((pPtr = stptok(pPtr,pPath,131,":")) != NULL){ - searchDir(pPath,pattern,result); + while ((pPtr = stptok(pPtr, pPath, 131, ":")) != NULL) { + searchDir(pPath, pattern, result); } return result; } + /*=========================== info ===================================*/ -static void printExeStack(pExeMan self, SConnection *pCon){ +static void printExeStack(pExeMan self, SConnection * pCon) +{ int i, j; pDynString txt = NULL; pExeBuf buf; void *pPtr = NULL; - txt = CreateDynString(80,80); - if(txt == NULL){ - SCWrite(pCon,"ERROR: failed to allocate memory in printExeStack",eError); + txt = CreateDynString(80, 80); + if (txt == NULL) { + SCWrite(pCon, "ERROR: failed to allocate memory in printExeStack", + eError); return; } - for(i = 0; i <= self->exeStackPtr; i++){ - DynarGet(self->exeStack,i,&pPtr); - buf = (pExeBuf)pPtr; + for (i = 0; i <= self->exeStackPtr; i++) { + DynarGet(self->exeStack, i, &pPtr); + buf = (pExeBuf) pPtr; assert(buf); - for(j = 0; j < i; j++){ - DynStringConcat(txt," "); + for (j = 0; j < i; j++) { + DynStringConcat(txt, " "); } - DynStringConcat(txt,exeBufName(buf)); - DynStringConcatChar(txt,'\n'); + DynStringConcat(txt, exeBufName(buf)); + DynStringConcatChar(txt, '\n'); } - SCWrite(pCon,GetCharArray(txt),eValue); + SCWrite(pCon, GetCharArray(txt), eValue); DeleteDynString(txt); } + /*-----------------------------------------------------------------*/ -static int locateBuffer(pExeMan self, char *name){ +static int locateBuffer(pExeMan self, char *name) +{ int i; pExeBuf buf; void *pPtr = NULL; - for(i = 0; i <= self->exeStackPtr; i++){ - DynarGet(self->exeStack,i,&pPtr); - buf = (pExeBuf)pPtr; - if(strcmp(name,exeBufName(buf)) == 0) { + for (i = 0; i <= self->exeStackPtr; i++) { + DynarGet(self->exeStack, i, &pPtr); + buf = (pExeBuf) pPtr; + if (strcmp(name, exeBufName(buf)) == 0) { return i; } } return -1; } + /*------------------------------------------------------------------*/ -static void printExeRange(pExeMan self, SConnection *pCon, - int argc, char *argv[]){ +static void printExeRange(pExeMan self, SConnection * pCon, + int argc, char *argv[]) +{ int start, end, lineno, bufNo; pExeBuf buf; void *pPtr = NULL; char pBueffel[256]; - if(argc > 3) { - bufNo = locateBuffer(self,argv[3]); + if (argc > 3) { + bufNo = locateBuffer(self, argv[3]); } else { bufNo = self->exeStackPtr; } - if(bufNo < 0){ - SCWrite(pCon,"ERROR: named buffer not found",eError); + if (bufNo < 0) { + SCWrite(pCon, "ERROR: named buffer not found", eError); return; } - DynarGet(self->exeStack,bufNo,&pPtr); - buf = (pExeBuf)pPtr; + DynarGet(self->exeStack, bufNo, &pPtr); + buf = (pExeBuf) pPtr; assert(buf); - exeBufRange(buf,&start,&end,&lineno); - snprintf(pBueffel,255,"%s.range = %d = %d = %d",exeBufName(buf), - start,end,lineno); - SCWrite(pCon,pBueffel,eValue); + exeBufRange(buf, &start, &end, &lineno); + snprintf(pBueffel, 255, "%s.range = %d = %d = %d", exeBufName(buf), + start, end, lineno); + SCWrite(pCon, pBueffel, eValue); } + /*------------------------------------------------------------------*/ -static void printExeText(pExeMan self, SConnection *pCon, - int argc, char *argv[]){ +static void printExeText(pExeMan self, SConnection * pCon, + int argc, char *argv[]) +{ int start, end, lineno, bufNo; pExeBuf buf; void *pPtr = NULL; pDynString txt; - if(argc > 3) { - bufNo = locateBuffer(self,argv[3]); + if (argc > 3) { + bufNo = locateBuffer(self, argv[3]); } else { bufNo = self->exeStackPtr; } - if(bufNo < 0){ - SCWrite(pCon,"ERROR: named buffer not found",eError); + if (bufNo < 0) { + SCWrite(pCon, "ERROR: named buffer not found", eError); return; } - DynarGet(self->exeStack,bufNo,&pPtr); - buf = (pExeBuf)pPtr; + DynarGet(self->exeStack, bufNo, &pPtr); + buf = (pExeBuf) pPtr; assert(buf); - exeBufRange(buf,&start,&end,&lineno); - txt = exeBufText(buf,start,end); - if(txt != NULL){ - SCWrite(pCon,GetCharArray(txt),eValue); + exeBufRange(buf, &start, &end, &lineno); + txt = exeBufText(buf, start, end); + if (txt != NULL) { + SCWrite(pCon, GetCharArray(txt), eValue); DeleteDynString(txt); } else { - SCWrite(pCon,"ERROR: failed to allocate text buffer for operation",eError); + SCWrite(pCon, "ERROR: failed to allocate text buffer for operation", + eError); } } + /*------------------------------------------------------------------*/ -static void printQueue(pExeMan self, SConnection *pCon){ - pExeBuf buf= NULL; +static void printQueue(pExeMan self, SConnection * pCon) +{ + pExeBuf buf = NULL; pDynString text = NULL; int status; - text = CreateDynString(80,80); - if(text == NULL){ - SCWrite(pCon,"ERROR: out of memory",eError); + text = CreateDynString(80, 80); + if (text == NULL) { + SCWrite(pCon, "ERROR: out of memory", eError); return; } - + status = LLDnodePtr2First(self->runList); - while(status != 0) { - LLDnodeDataTo(self->runList,&buf); - if(buf != NULL){ - DynStringConcat(text,exeBufName(buf)); - DynStringConcatChar(text,'\n'); + while (status != 0) { + LLDnodeDataTo(self->runList, &buf); + if (buf != NULL) { + DynStringConcat(text, exeBufName(buf)); + DynStringConcatChar(text, '\n'); } status = LLDnodePtr2Next(self->runList); } - SCWrite(pCon,GetCharArray(text),eValue); + SCWrite(pCon, GetCharArray(text), eValue); DeleteDynString(text); } + /*-------------------------------------------------------------------*/ -static int infoHandler(pExeMan self, SConnection *pCon, - int argc, char *argv[]){ +static int infoHandler(pExeMan self, SConnection * pCon, + int argc, char *argv[]) +{ char pBueffel[256]; pExeBuf buf; void *pPtr = NULL; - - if(self->exeStackPtr < 0){ - SCWrite(pCon,"Idle",eValue); + + if (self->exeStackPtr < 0) { + SCWrite(pCon, "Idle", eValue); return 1; } - if(argc < 3){ - if(self->exeStackPtr >= 0){ - DynarGet(self->exeStack,self->exeStackPtr,&pPtr); - buf = (pExeBuf)pPtr; - if(buf != NULL){ - snprintf(pBueffel,255,"Executing %s",exeBufName(buf)); - SCWrite(pCon,pBueffel,eValue); - return 1; + if (argc < 3) { + if (self->exeStackPtr >= 0) { + DynarGet(self->exeStack, self->exeStackPtr, &pPtr); + buf = (pExeBuf) pPtr; + if (buf != NULL) { + snprintf(pBueffel, 255, "Executing %s", exeBufName(buf)); + SCWrite(pCon, pBueffel, eValue); + return 1; } - } - SCWrite(pCon,"Nothing to execute",eValue); + } + SCWrite(pCon, "Nothing to execute", eValue); return 1; } else { strtolower(argv[2]); - if(strcmp(argv[2],"stack") == 0){ - printExeStack(self,pCon); + if (strcmp(argv[2], "stack") == 0) { + printExeStack(self, pCon); return 1; - } else if(strcmp(argv[2],"range") == 0){ - printExeRange(self,pCon,argc,argv); + } else if (strcmp(argv[2], "range") == 0) { + printExeRange(self, pCon, argc, argv); return 1; - } else if(strcmp(argv[2],"text") == 0){ - printExeText(self,pCon,argc,argv); + } else if (strcmp(argv[2], "text") == 0) { + printExeText(self, pCon, argc, argv); return 1; } else { - SCWrite(pCon,"ERROR: subcommand to info unknown",eError); - return 0; + SCWrite(pCon, "ERROR: subcommand to info unknown", eError); + return 0; } } } + /*=========================== print ==================================*/ -static int printBuffer(pExeMan self, SConnection *pCon, - int argc, char *argv[]){ +static int printBuffer(pExeMan self, SConnection * pCon, + int argc, char *argv[]) +{ pDynString filePath = NULL; char pLine[512]; pExeBuf buf; void *pPtr = NULL; FILE *fd = NULL; - if(argc < 3){ - if(self->exeStackPtr >= 0) { - DynarGet(self->exeStack,self->exeStackPtr,&pPtr); + if (argc < 3) { + if (self->exeStackPtr >= 0) { + DynarGet(self->exeStack, self->exeStackPtr, &pPtr); buf = (pExeBuf) pPtr; - if(buf != NULL){ - filePath = locateBatchBuffer(self,exeBufName(buf)); + if (buf != NULL) { + filePath = locateBatchBuffer(self, exeBufName(buf)); } } else { - SCWrite(pCon,"ERROR: no default buffer to print, argument required",eError); + SCWrite(pCon, "ERROR: no default buffer to print, argument required", + eError); return 0; } } else { - filePath = locateBatchBuffer(self,argv[2]); + filePath = locateBatchBuffer(self, argv[2]); } - if(filePath == NULL){ - snprintf(pLine,255,"ERROR: batch buffer %s not found in path", - argv[2]); - SCWrite(pCon,pLine,eError); + if (filePath == NULL) { + snprintf(pLine, 255, "ERROR: batch buffer %s not found in path", + argv[2]); + SCWrite(pCon, pLine, eError); return 0; } - fd = fopen(GetCharArray(filePath),"r"); - if(fd == NULL){ - SCWrite(pCon,"ERROR: failed to open file for printing",eError); + fd = fopen(GetCharArray(filePath), "r"); + if (fd == NULL) { + SCWrite(pCon, "ERROR: failed to open file for printing", eError); DeleteDynString(filePath); return 0; } DeleteDynString(filePath); SCStartBuffering(pCon); - while(fgets(pLine,511,fd) != NULL){ - SCWrite(pCon,pLine,eValue); + while (fgets(pLine, 511, fd) != NULL) { + SCWrite(pCon, pLine, eValue); } fclose(fd); filePath = SCEndBuffering(pCon); - SCWrite(pCon,GetCharArray(filePath),eValue); + SCWrite(pCon, GetCharArray(filePath), eValue); return 1; } + /*========================== run stack ===============================*/ -static int enqueueBuffer(pExeMan self, SConnection *pCon, - int argc, char *argv[]){ +static int enqueueBuffer(pExeMan self, SConnection * pCon, + int argc, char *argv[]) +{ pExeBuf buf = NULL; int status; pDynString filePath = NULL; - if(SCGetRights(pCon) > usUser){ - SCWrite(pCon,"ERROR: no permission to enque buffers",eError); + if (SCGetRights(pCon) > usUser) { + SCWrite(pCon, "ERROR: no permission to enque buffers", eError); return 0; } - if(argc < 3) { - SCWrite(pCon,"ERROR: no buffer file given to enqueue ",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: no buffer file given to enqueue ", eError); return 0; } - - filePath = locateBatchBuffer(self,argv[2]); - if(filePath == NULL){ - SCWrite(pCon,"ERROR: failed to locate buffer to enqueue",eError); + + filePath = locateBatchBuffer(self, argv[2]); + if (filePath == NULL) { + SCWrite(pCon, "ERROR: failed to locate buffer to enqueue", eError); return 0; } buf = exeBufCreate("enqueue"); - if(buf == NULL){ - SCWrite(pCon,"ERROR: out of memory",eError); + if (buf == NULL) { + SCWrite(pCon, "ERROR: out of memory", eError); return 0; } - status = exeBufLoad(buf,GetCharArray(filePath)); + status = exeBufLoad(buf, GetCharArray(filePath)); DeleteDynString(filePath); - if(status != 1) { - SCWrite(pCon,"ERROR: failed to load buffer",eError); + if (status != 1) { + SCWrite(pCon, "ERROR: failed to load buffer", eError); return 0; } - LLDnodeAppendFrom(self->runList,&buf); + LLDnodeAppendFrom(self->runList, &buf); return 1; } + /*--------------------------------------------------------------------*/ -static void clearQueue(pExeMan self){ +static void clearQueue(pExeMan self) +{ pExeBuf buf = NULL; int status; status = LLDnodePtr2First(self->runList); - while(status != 0) { - LLDnodeDataTo(self->runList,&buf); - if(buf != NULL){ + while (status != 0) { + LLDnodeDataTo(self->runList, &buf); + if (buf != NULL) { exeBufDelete(buf); } LLDnodeDelete(self->runList); status = LLDnodePtr2Next(self->runList); } /* - A second time round. This is a workaround for some - dodgy behaviour of the list system. - */ + A second time round. This is a workaround for some + dodgy behaviour of the list system. + */ status = LLDnodePtr2First(self->runList); - while(status != 0) { - LLDnodeDataTo(self->runList,&buf); - if(buf != NULL){ + while (status != 0) { + LLDnodeDataTo(self->runList, &buf); + if (buf != NULL) { exeBufDelete(buf); } LLDnodeDelete(self->runList); status = LLDnodePtr2Next(self->runList); } } + /*--------------------------------------------------------------------*/ -static int execQueue(pExeMan self, SConnection *pCon, SicsInterp *pSics){ +static int execQueue(pExeMan self, SConnection * pCon, SicsInterp * pSics) +{ pExeBuf buf = NULL; int status; - if(self->exeStackPtr >= 0 || (self->runCon != NULL && self->runCon != pCon) ){ + if (self->exeStackPtr >= 0 + || (self->runCon != NULL && self->runCon != pCon)) { SCWrite(pCon, - "ERROR: cannot start queue while batch buffers are still running",eError); + "ERROR: cannot start queue while batch buffers are still running", + eError); return 0; } - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - + self->runCon = pCon; - while(LLDnodePtr2First(self->runList) != 0){ - LLDnodeDataTo(self->runList,&buf); + while (LLDnodePtr2First(self->runList) != 0) { + LLDnodeDataTo(self->runList, &buf); LLDnodeDelete(self->runList); self->exeStackPtr++; - if(buf == NULL){ + if (buf == NULL) { SCWrite(pCon, - "ERROR: serious trouble, buffer not in queue, inform programmer",eError); + "ERROR: serious trouble, buffer not in queue, inform programmer", + eError); self->runCon = NULL; return 0; } - DynarPut(self->exeStack,self->exeStackPtr,buf); - status = exeBufProcess(buf,pSics,pCon,self->pCall,self->echo); + DynarPut(self->exeStack, self->exeStackPtr, buf); + status = exeBufProcess(buf, pSics, pCon, self->pCall, self->echo); self->exeStackPtr--; - if(SCGetInterrupt(pCon) >= eAbortBatch){ - SCWrite(pCon,"ERROR: queue processing interrupted",eError); + if (SCGetInterrupt(pCon) >= eAbortBatch) { + SCWrite(pCon, "ERROR: queue processing interrupted", eError); self->runCon = NULL; return 0; } @@ -1202,122 +1279,125 @@ static int execQueue(pExeMan self, SConnection *pCon, SicsInterp *pSics){ self->runCon = 0; return 1; } + /*========================== interpreter action =======================*/ -int ExeManagerWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int ExeManagerWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pExeMan self = NULL; char pBufferName[256]; int status; pDynString dirList = NULL; pDynString fullPath = NULL; - self = (pExeMan)pData; + self = (pExeMan) pData; assert(self != NULL); - if(argc > 1){ - strncpy(pBufferName,argv[1],255); + if (argc > 1) { + strncpy(pBufferName, argv[1], 255); strtolower(argv[1]); - status = handleBatchPath(self,pCon,argc,argv); - if(status >= 0){ + status = handleBatchPath(self, pCon, argc, argv); + if (status >= 0) { return status; } - if(strcmp(argv[1],"interest") == 0){ - registerCallbacks(pCon,pSics,self); + if (strcmp(argv[1], "interest") == 0) { + registerCallbacks(pCon, pSics, self); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"uninterest") == 0){ - unregisterCallbacks(pCon,self); + } else if (strcmp(argv[1], "uninterest") == 0) { + unregisterCallbacks(pCon, self); SCSendOK(pCon); return 1; - }else if(strcmp(argv[1],"upload") == 0){ - status = startUpload(self,pCon); - if(status){ - SCSendOK(pCon); + } else if (strcmp(argv[1], "upload") == 0) { + status = startUpload(self, pCon); + if (status) { + SCSendOK(pCon); } return status; - }else if(strcmp(argv[1],"append") == 0){ - status = appendLine(self,pCon,argc,argv); - if(status){ - SCSendOK(pCon); + } else if (strcmp(argv[1], "append") == 0) { + status = appendLine(self, pCon, argc, argv); + if (status) { + SCSendOK(pCon); } return status; - }else if(strcmp(argv[1],"save") == 0){ - status = uploadSave(self,pCon,argc,argv); - if(status){ - SCSendOK(pCon); + } else if (strcmp(argv[1], "save") == 0) { + status = uploadSave(self, pCon, argc, argv); + if (status) { + SCSendOK(pCon); } return status; - }else if(strcmp(argv[1],"forcesave") == 0){ - status = uploadForceSave(self,pCon,argc,argv); - if(status){ - SCSendOK(pCon); + } else if (strcmp(argv[1], "forcesave") == 0) { + status = uploadForceSave(self, pCon, argc, argv); + if (status) { + SCSendOK(pCon); } return status; - }else if(strcmp(argv[1],"clearupload") == 0){ - status = clearUpload(self,pCon); - if(status){ - SCSendOK(pCon); + } else if (strcmp(argv[1], "clearupload") == 0) { + status = clearUpload(self, pCon); + if (status) { + SCSendOK(pCon); } return status; - }else if(strcmp(argv[1],"info") == 0){ - status = infoHandler(self,pCon,argc,argv); + } else if (strcmp(argv[1], "info") == 0) { + status = infoHandler(self, pCon, argc, argv); return status; - }else if(strcmp(argv[1],"print") == 0){ - status = printBuffer(self,pCon,argc,argv); + } else if (strcmp(argv[1], "print") == 0) { + status = printBuffer(self, pCon, argc, argv); return status; - }else if(strcmp(argv[1],"enqueue") == 0){ - status = enqueueBuffer(self,pCon,argc,argv); - if(status){ - SCSendOK(pCon); + } else if (strcmp(argv[1], "enqueue") == 0) { + status = enqueueBuffer(self, pCon, argc, argv); + if (status) { + SCSendOK(pCon); } return status; - } else if(strcmp(argv[1],"dir") == 0){ - if(argc <= 2){ - dirList = findDirEntries(self,"*"); + } else if (strcmp(argv[1], "dir") == 0) { + if (argc <= 2) { + dirList = findDirEntries(self, "*"); } else { - dirList = findDirEntries(self,argv[2]); + dirList = findDirEntries(self, argv[2]); } - if(dirList != NULL){ - SCWrite(pCon,GetCharArray(dirList),eValue); - DeleteDynString(dirList); + if (dirList != NULL) { + SCWrite(pCon, GetCharArray(dirList), eValue); + DeleteDynString(dirList); } else { - SCWrite(pCon,"Nothing found",eValue); + SCWrite(pCon, "Nothing found", eValue); } return 1; - }else if(strcmp(argv[1],"fullpath") == 0){ - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to exe fullpath",eError); + } else if (strcmp(argv[1], "fullpath") == 0) { + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to exe fullpath", + eError); return 0; - } - fullPath = locateBatchBuffer(self,argv[2]); - if(fullPath == NULL){ - SCWrite(pCon,"ERROR: buffer NOT found",eError); + } + fullPath = locateBatchBuffer(self, argv[2]); + if (fullPath == NULL) { + SCWrite(pCon, "ERROR: buffer NOT found", eError); return 0; } else { - DynStringInsert(fullPath,"exe.fullpath=",0); - SCWrite(pCon,GetCharArray(fullPath),eValue); + DynStringInsert(fullPath, "exe.fullpath=", 0); + SCWrite(pCon, GetCharArray(fullPath), eValue); DeleteDynString(fullPath); return 1; } return 1; - }else if(strcmp(argv[1],"makepath") == 0){ - return makeExePath(self,pCon,argc,argv); - }else if(strcmp(argv[1],"clear") == 0){ + } else if (strcmp(argv[1], "makepath") == 0) { + return makeExePath(self, pCon, argc, argv); + } else if (strcmp(argv[1], "clear") == 0) { clearQueue(self); SCSendOK(pCon); - return 1; - }else if(strcmp(argv[1],"queue") == 0){ - printQueue(self,pCon); + return 1; + } else if (strcmp(argv[1], "queue") == 0) { + printQueue(self, pCon); SCSendOK(pCon); return 1; - }else if(strcmp(argv[1],"run") == 0){ - status = execQueue(self,pCon,pSics); - if(status){ - SCSendOK(pCon); + } else if (strcmp(argv[1], "run") == 0) { + status = execQueue(self, pCon, pSics); + if (status) { + SCSendOK(pCon); } return status; - }else if(strcmp(argv[1],"echo") == 0){ + } else if (strcmp(argv[1], "echo") == 0) { if (argc > 2) { self->echo = atoi(argv[2]) != 0; SCSendOK(pCon); @@ -1325,25 +1405,25 @@ int ExeManagerWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, SCPrintf(pCon, eValue, "exe echo = %d", self->echo); } return 1; - }else if(strcmp(argv[1],"runhdb") == 0){ + } else if (strcmp(argv[1], "runhdb") == 0) { if (argc < 2) { - SCWrite(pCon,"ERROR: require path to root of queue node",eError); + SCWrite(pCon, "ERROR: require path to root of queue node", eError); SCSendOK(pCon); - } - status = runHdbBuffer(self,pCon,pSics,argv[2]); - if(self->exeStackPtr < 0){ - SCWrite(pCon,"EXE TERMINATED",eWarning); + } + status = runHdbBuffer(self, pCon, pSics, argv[2]); + if (self->exeStackPtr < 0) { + SCWrite(pCon, "EXE TERMINATED", eWarning); } return status; } else { - status = runBatchBuffer(self,pCon,pSics,pBufferName); - if(self->exeStackPtr < 0){ - SCWrite(pCon,"EXE TERMINATED",eWarning); + status = runBatchBuffer(self, pCon, pSics, pBufferName); + if (self->exeStackPtr < 0) { + SCWrite(pCon, "EXE TERMINATED", eWarning); } return status; } } else { - SCWrite(pCon,"ERROR: need argument to manage batch buffers",eError); + SCWrite(pCon, "ERROR: need argument to manage batch buffers", eError); return 0; } return 1; diff --git a/exeman.h b/exeman.h index ddee48dd..fc110a6e 100644 --- a/exeman.h +++ b/exeman.h @@ -9,15 +9,14 @@ #ifndef EXEMAN #define EXEMAN -int MakeExeManager(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int ExeManagerWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int runExeBatchBuffer(void *pData, SConnection *pCon, SicsInterp *pSics, - char *name); -pDynString findBatchFile(SicsInterp *pSics, char *name); -int exeHdbBuffer(SConnection *pCon, - SicsInterp *pSics, char *name); -int exeHdbNode(pHdb exeNode, SConnection *pCon); +int MakeExeManager(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int ExeManagerWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int runExeBatchBuffer(void *pData, SConnection * pCon, SicsInterp * pSics, + char *name); +pDynString findBatchFile(SicsInterp * pSics, char *name); +int exeHdbBuffer(SConnection * pCon, SicsInterp * pSics, char *name); +int exeHdbNode(pHdb exeNode, SConnection * pCon); -#endif +#endif diff --git a/f2c.h b/f2c.h index 2390d41b..ad830f0e 100644 --- a/f2c.h +++ b/f2c.h @@ -15,15 +15,19 @@ typedef float real; /* avoid irritating warnings when math functions are used, M.Z.08.2001 */ #define doublereal double /* typedef double doublereal; */ -typedef struct { real r, i; } complex; -typedef struct { doublereal r, i; } doublecomplex; +typedef struct { + real r, i; +} complex; +typedef struct { + doublereal r, i; +} doublecomplex; typedef long int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; -#ifdef INTEGER_STAR_8 /* Adjust for integer*8. */ -typedef long long longint; /* system-dependent */ -typedef unsigned long long ulongint; /* system-dependent */ +#ifdef INTEGER_STAR_8 /* Adjust for integer*8. */ +typedef long long longint; /* system-dependent */ +typedef unsigned long long ulongint; /* system-dependent */ #define qbit_clear(a,b) ((a) & ~((ulongint)1 << (b))) #define qbit_set(a,b) ((a) | ((ulongint)1 << (b))) #endif @@ -50,110 +54,110 @@ typedef long int ftnint; #endif /*external read, write*/ -typedef struct -{ flag cierr; - ftnint ciunit; - flag ciend; - char *cifmt; - ftnint cirec; +typedef struct { + flag cierr; + ftnint ciunit; + flag ciend; + char *cifmt; + ftnint cirec; } cilist; /*internal read, write*/ -typedef struct -{ flag icierr; - char *iciunit; - flag iciend; - char *icifmt; - ftnint icirlen; - ftnint icirnum; +typedef struct { + flag icierr; + char *iciunit; + flag iciend; + char *icifmt; + ftnint icirlen; + ftnint icirnum; } icilist; /*open*/ -typedef struct -{ flag oerr; - ftnint ounit; - char *ofnm; - ftnlen ofnmlen; - char *osta; - char *oacc; - char *ofm; - ftnint orl; - char *oblnk; +typedef struct { + flag oerr; + ftnint ounit; + char *ofnm; + ftnlen ofnmlen; + char *osta; + char *oacc; + char *ofm; + ftnint orl; + char *oblnk; } olist; /*close*/ -typedef struct -{ flag cerr; - ftnint cunit; - char *csta; +typedef struct { + flag cerr; + ftnint cunit; + char *csta; } cllist; /*rewind, backspace, endfile*/ -typedef struct -{ flag aerr; - ftnint aunit; +typedef struct { + flag aerr; + ftnint aunit; } alist; /* inquire */ -typedef struct -{ flag inerr; - ftnint inunit; - char *infile; - ftnlen infilen; - ftnint *inex; /*parameters in standard's order*/ - ftnint *inopen; - ftnint *innum; - ftnint *innamed; - char *inname; - ftnlen innamlen; - char *inacc; - ftnlen inacclen; - char *inseq; - ftnlen inseqlen; - char *indir; - ftnlen indirlen; - char *infmt; - ftnlen infmtlen; - char *inform; - ftnint informlen; - char *inunf; - ftnlen inunflen; - ftnint *inrecl; - ftnint *innrec; - char *inblank; - ftnlen inblanklen; +typedef struct { + flag inerr; + ftnint inunit; + char *infile; + ftnlen infilen; + ftnint *inex; /*parameters in standard's order */ + ftnint *inopen; + ftnint *innum; + ftnint *innamed; + char *inname; + ftnlen innamlen; + char *inacc; + ftnlen inacclen; + char *inseq; + ftnlen inseqlen; + char *indir; + ftnlen indirlen; + char *infmt; + ftnlen infmtlen; + char *inform; + ftnint informlen; + char *inunf; + ftnlen inunflen; + ftnint *inrecl; + ftnint *innrec; + char *inblank; + ftnlen inblanklen; } inlist; #define VOID void -union Multitype { /* for multiple entry points */ - integer1 g; - shortint h; - integer i; - /* longint j; */ - real r; - doublereal d; - complex c; - doublecomplex z; - }; +union Multitype { /* for multiple entry points */ + integer1 g; + shortint h; + integer i; + /* longint j; */ + real r; + doublereal d; + complex c; + doublecomplex z; +}; typedef union Multitype Multitype; -/*typedef long int Long;*/ /* No longer used; formerly in Namelist */ + /*typedef long int Long;*//* No longer used; formerly in Namelist */ -struct Vardesc { /* for Namelist */ - char *name; - char *addr; - ftnlen *dims; - int type; - }; +struct Vardesc { /* for Namelist */ + char *name; + char *addr; + ftnlen *dims; + int type; +}; typedef struct Vardesc Vardesc; struct Namelist { - char *name; - Vardesc **vars; - int nvars; - }; + char *name; + Vardesc **vars; + int nvars; +}; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) @@ -170,35 +174,35 @@ typedef struct Namelist Namelist; #define F2C_proc_par_types 1 #ifdef __cplusplus -typedef int /* Unknown procedure type */ (*U_fp)(...); -typedef shortint (*J_fp)(...); -typedef integer (*I_fp)(...); -typedef real (*R_fp)(...); -typedef doublereal (*D_fp)(...), (*E_fp)(...); -typedef /* Complex */ VOID (*C_fp)(...); -typedef /* Double Complex */ VOID (*Z_fp)(...); -typedef logical (*L_fp)(...); -typedef shortlogical (*K_fp)(...); -typedef /* Character */ VOID (*H_fp)(...); -typedef /* Subroutine */ int (*S_fp)(...); +typedef int /* Unknown procedure type */ (*U_fp) (...); +typedef shortint(*J_fp) (...); +typedef integer(*I_fp) (...); +typedef real(*R_fp) (...); +typedef doublereal(*D_fp) (...), (*E_fp) (...); +typedef /* Complex */ VOID(*C_fp) (...); +typedef /* Double Complex */ VOID(*Z_fp) (...); +typedef logical(*L_fp) (...); +typedef shortlogical(*K_fp) (...); +typedef /* Character */ VOID(*H_fp) (...); +typedef /* Subroutine */ int (*S_fp) (...); #else -typedef int /* Unknown procedure type */ (*U_fp)(); -typedef shortint (*J_fp)(); -typedef integer (*I_fp)(); -typedef real (*R_fp)(); -typedef doublereal (*D_fp)(), (*E_fp)(); -typedef /* Complex */ VOID (*C_fp)(); -typedef /* Double Complex */ VOID (*Z_fp)(); -typedef logical (*L_fp)(); -typedef shortlogical (*K_fp)(); -typedef /* Character */ VOID (*H_fp)(); -typedef /* Subroutine */ int (*S_fp)(); +typedef int /* Unknown procedure type */ (*U_fp) (); +typedef shortint(*J_fp) (); +typedef integer(*I_fp) (); +typedef real(*R_fp) (); +typedef doublereal(*D_fp) (), (*E_fp) (); +typedef /* Complex */ VOID(*C_fp) (); +typedef /* Double Complex */ VOID(*Z_fp) (); +typedef logical(*L_fp) (); +typedef shortlogical(*K_fp) (); +typedef /* Character */ VOID(*H_fp) (); +typedef /* Subroutine */ int (*S_fp) (); #endif /* E_fp is for real functions when -R is not specified */ -typedef VOID C_f; /* complex function */ -typedef VOID H_f; /* character function */ -typedef VOID Z_f; /* double complex function */ -typedef doublereal E_f; /* real function with -R not specified */ +typedef VOID C_f; /* complex function */ +typedef VOID H_f; /* character function */ +typedef VOID Z_f; /* double complex function */ +typedef doublereal E_f; /* real function with -R not specified */ /* undef any lower-case symbols that your C compiler predefines, e.g.: */ diff --git a/fitcenter.c b/fitcenter.c index 6f8f0c4c..607685f8 100644 --- a/fitcenter.c +++ b/fitcenter.c @@ -16,477 +16,451 @@ #include "fitcenter.h" #define THRESHOLD .1 /*--------------------------------------------------------------------------*/ - typedef struct __FitCenter { - pObjectDescriptor pDes; - pScanData pScan; - long *lCounts; - float *fAxis; - char pName[132]; - float fCenter; - float fStddev; - long lPeak; - float FWHM; - int iNP; - } FitCenter; +typedef struct __FitCenter { + pObjectDescriptor pDes; + pScanData pScan; + long *lCounts; + float *fAxis; + char pName[132]; + float fCenter; + float fStddev; + long lPeak; + float FWHM; + int iNP; +} FitCenter; /*-------------------------------------------------------------------------*/ - pFit CreateFitCenter(pScanData pScan) - { - pFit pNew = NULL; - - pNew = (pFit)malloc(sizeof(FitCenter)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(FitCenter)); - - pNew->pDes = CreateDescriptor("FitCenter"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - pNew->pScan = pScan; - return pNew; - } +pFit CreateFitCenter(pScanData pScan) +{ + pFit pNew = NULL; + + pNew = (pFit) malloc(sizeof(FitCenter)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(FitCenter)); + + pNew->pDes = CreateDescriptor("FitCenter"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + pNew->pScan = pScan; + return pNew; +} + /*-------------------------------------------------------------------------*/ - void DeleteFitCenter(void *pData) - { - pFit self = NULL; - - self = (pFit)pData; - assert(self); - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->lCounts) - { - free(self->lCounts); - } - if(self->fAxis) - { - free(self->fAxis); - } - free(self); - } +void DeleteFitCenter(void *pData) +{ + pFit self = NULL; + + self = (pFit) pData; + assert(self); + + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->lCounts) { + free(self->lCounts); + } + if (self->fAxis) { + free(self->fAxis); + } + free(self); +} + /*--------------------------------------------------------------------------*/ - static int Init(pFit self) - { - pMotor pMot = NULL; - float fZero, fSign; - int i; - - /* collect data first */ - self->iNP = GetScanNP(self->pScan); - if(self->lCounts) - { - free(self->lCounts); - self->lCounts = NULL; - } - if(self->fAxis) - { - free(self->fAxis); - self->fAxis = NULL; - } - self->lCounts = (long *)malloc(self->iNP * sizeof(long)); - self->fAxis = (float *)malloc(self->iNP * sizeof(float)); - if( (!self->lCounts) || (!self->fAxis) ) - { - return 0; - } - - GetScanCounts(self->pScan,self->lCounts, self->iNP); - GetScanVar(self->pScan,0,self->fAxis,self->iNP); - GetScanVarName(self->pScan,0,self->pName,131); - - return 1; - } +static int Init(pFit self) +{ + pMotor pMot = NULL; + float fZero, fSign; + int i; + + /* collect data first */ + self->iNP = GetScanNP(self->pScan); + if (self->lCounts) { + free(self->lCounts); + self->lCounts = NULL; + } + if (self->fAxis) { + free(self->fAxis); + self->fAxis = NULL; + } + self->lCounts = (long *) malloc(self->iNP * sizeof(long)); + self->fAxis = (float *) malloc(self->iNP * sizeof(float)); + if ((!self->lCounts) || (!self->fAxis)) { + return 0; + } + + GetScanCounts(self->pScan, self->lCounts, self->iNP); + GetScanVar(self->pScan, 0, self->fAxis, self->iNP); + GetScanVarName(self->pScan, 0, self->pName, 131); + + return 1; +} + /*-------------------------------------------------------------------------*/ - static int FindMax(pFit self) - { - long lMax = LONG_MIN; - int i, iMax; - - for(i = 0, iMax = 0; i < self->iNP; i++) - { - if(self->lCounts[i] > lMax) - { - lMax = self->lCounts[i]; - iMax = i; - } - } - - return iMax; - } -/*-------------------------------------------------------------------------*/ - static int CalculateFitIntern(pFit self) - { - int i,iLeft, iRight, iRet,iPeak, iLast; - long lHalf; - float fFrac, fDelta, fStep, fLeft, fRight, fNenner, fTest; - float fLFrac, fRFrac, fSum, fCI; +static int FindMax(pFit self) +{ + long lMax = LONG_MIN; + int i, iMax; - iLeft = 0; + for (i = 0, iMax = 0; i < self->iNP; i++) { + if (self->lCounts[i] > lMax) { + lMax = self->lCounts[i]; + iMax = i; + } + } - /* find the maximum counts */ - iRet = FindMax(self); - self->lPeak = self->lCounts[iRet]; - /* a default fit is the peak maximum. This - helps optimise to do the right thing if no proper calculation - could be performed - */ - self->fCenter = self->fAxis[iRet]; - iPeak = iRet; + return iMax; +} - if(self->lPeak < 3) - { - return -3; - } +/*-------------------------------------------------------------------------*/ +static int CalculateFitIntern(pFit self) +{ + int i, iLeft, iRight, iRet, iPeak, iLast; + long lHalf; + float fFrac, fDelta, fStep, fLeft, fRight, fNenner, fTest; + float fLFrac, fRFrac, fSum, fCI; - /* find FWHM, first from Right then from left */ - iRet =1; - lHalf = self->lPeak/2; - iLeft = iPeak; - while( (self->lCounts[iLeft] > lHalf) && (iLeft > 0) ) - { - iLeft--; - } - if(iLeft == 0) - { - iRet = -1; - iLeft++; - } - fNenner = (float)self->lCounts[iLeft+1] - (float)self->lCounts[iLeft]; - if(fNenner < 0.) - { - fTest = -fNenner; - } - else - { - fTest = fNenner; - } - if(fTest < .00001) - { - return -4; - } - fFrac = ((float)self->lCounts[iLeft+1] - (float)lHalf) / fNenner; - fLeft = self->fAxis[iLeft] + - fFrac * (self->fAxis[iLeft+1] - self->fAxis[iLeft]); - fLFrac = fFrac; - - iRight = iPeak; - while( (self->lCounts[iRight] > lHalf) && (iRight < self->iNP) ) - { - iRight++; - } - if(iRight >= self->iNP - 1) - { - iRet = -2; - iRight = self->iNP - 1; - } - fNenner = (float)self->lCounts[iRight-1] - (float)self->lCounts[iRight]; - if(fNenner < 0.) - { - fTest = -fNenner; - } - else - { - fTest = fNenner; - } - if(fTest < .00001) - { - return -4; - } - fFrac = ((float)self->lCounts[iRight-1] - (float)lHalf) / fNenner; - fRight = self->fAxis[iRight] - - fFrac * (self->fAxis[1] - self->fAxis[0]); - fRFrac = fFrac; - - if(iRight != iLeft) - { - self->FWHM = fRight - fLeft; - } - else - { - self->FWHM = 0.07; - } + iLeft = 0; + + /* find the maximum counts */ + iRet = FindMax(self); + self->lPeak = self->lCounts[iRet]; + /* a default fit is the peak maximum. This + helps optimise to do the right thing if no proper calculation + could be performed + */ + self->fCenter = self->fAxis[iRet]; + iPeak = iRet; + + if (self->lPeak < 3) { + return -3; + } + + /* find FWHM, first from Right then from left */ + iRet = 1; + lHalf = self->lPeak / 2; + iLeft = iPeak; + while ((self->lCounts[iLeft] > lHalf) && (iLeft > 0)) { + iLeft--; + } + if (iLeft == 0) { + iRet = -1; + iLeft++; + } + fNenner = + (float) self->lCounts[iLeft + 1] - (float) self->lCounts[iLeft]; + if (fNenner < 0.) { + fTest = -fNenner; + } else { + fTest = fNenner; + } + if (fTest < .00001) { + return -4; + } + fFrac = ((float) self->lCounts[iLeft + 1] - (float) lHalf) / fNenner; + fLeft = self->fAxis[iLeft] + + fFrac * (self->fAxis[iLeft + 1] - self->fAxis[iLeft]); + fLFrac = fFrac; + + iRight = iPeak; + while ((self->lCounts[iRight] > lHalf) && (iRight < self->iNP)) { + iRight++; + } + if (iRight >= self->iNP - 1) { + iRet = -2; + iRight = self->iNP - 1; + } + fNenner = + (float) self->lCounts[iRight - 1] - (float) self->lCounts[iRight]; + if (fNenner < 0.) { + fTest = -fNenner; + } else { + fTest = fNenner; + } + if (fTest < .00001) { + return -4; + } + fFrac = ((float) self->lCounts[iRight - 1] - (float) lHalf) / fNenner; + fRight = self->fAxis[iRight] - fFrac * (self->fAxis[1] - self->fAxis[0]); + fRFrac = fFrac; + + if (iRight != iLeft) { + self->FWHM = fRight - fLeft; + } else { + self->FWHM = 0.07; + } /* self->fCenter = fLeft + (fRight - fLeft)/2.; */ - fSum = lHalf*(fLFrac); - fNenner = lHalf; - /* center of gravity calculation between iLeft and iRight */ - for(i = iLeft+1; i < iRight; i++) - { - fSum += self->lCounts[i]*(fLFrac + i - iLeft); - fNenner += self->lCounts[i]; - } - fSum += (iRight - 1 + fRFrac + fLFrac - iLeft )*lHalf; - fNenner += lHalf; - fCI = fSum/fNenner; - /* iLeft is zero, zero point shift by lFrac */ - fCI -= fLFrac; - fTest = fNenner; - fNenner = modff(fCI, &fSum); - self->fCenter = self->fAxis[(int)(fSum)+iLeft] + - fNenner*(self->fAxis[iLeft+1] - self->fAxis[iLeft]); - - /* error calculation */ - fTest = 2*(sqrtf(fTest))/fTest; - /* because we are really summing from iLeft */ - fTest = fCI*fTest; - if(fTest < 0) - fTest = - fTest; - self->fStddev = fTest*(self->fAxis[iLeft+1] - self->fAxis[iLeft]); - - return iRet; - } -/*--------------------------------------------------------------------------*/ - int CalculateFit(pFit self) - { - int iRet; - - - /* initialise */ - iRet = Init(self); - if(!iRet) - { - return iRet; - } - return CalculateFitIntern(self); + fSum = lHalf * (fLFrac); + fNenner = lHalf; + /* center of gravity calculation between iLeft and iRight */ + for (i = iLeft + 1; i < iRight; i++) { + fSum += self->lCounts[i] * (fLFrac + i - iLeft); + fNenner += self->lCounts[i]; } -/*------------------------------------------------------------------------*/ - int CalculateFitFromData(pFit self, float *fAxis, long *lCounts, int iLength) - { - int iRet; - float *fOld; - long *lOld; - int iOld; - - /* save old data. The normal handling is to have a local copy of - data with fit. This is handled differently in this function, where - it is assumed, that the data is owned by the caller. In order not - to upset fit's scheme for data handling data pointers are swapped. - This is more efficient then copying the data around without real - need. - */ - iOld = self->iNP; - fOld = self->fAxis; - lOld = self->lCounts; - - /* put in new */ - self->iNP = iLength; - self->fAxis = fAxis; - self->lCounts = lCounts; - - iRet = CalculateFitIntern(self); - - /* reset data pointers */ - self->iNP = iOld; - self->fAxis = fOld; - self->lCounts = lOld; - - return iRet; - } -/*------------------------------------------------------------------------*/ - void GetFitResults(pFit self, float *fCenter, float *fStdDev, - float *FWHM, float *fMax) - { - assert(self); - *fCenter = self->fCenter; - *FWHM = self->FWHM; - *fMax = (float)self->lPeak; - *fStdDev = self->fStddev; - } + fSum += (iRight - 1 + fRFrac + fLFrac - iLeft) * lHalf; + fNenner += lHalf; + fCI = fSum / fNenner; + /* iLeft is zero, zero point shift by lFrac */ + fCI -= fLFrac; + fTest = fNenner; + fNenner = modff(fCI, &fSum); + self->fCenter = self->fAxis[(int) (fSum) + iLeft] + + fNenner * (self->fAxis[iLeft + 1] - self->fAxis[iLeft]); + + /* error calculation */ + fTest = 2 * (sqrtf(fTest)) / fTest; + /* because we are really summing from iLeft */ + fTest = fCI * fTest; + if (fTest < 0) + fTest = -fTest; + self->fStddev = fTest * (self->fAxis[iLeft + 1] - self->fAxis[iLeft]); + + return iRet; +} + /*--------------------------------------------------------------------------*/ - int DriveCenter(pFit self, SConnection *pCon, SicsInterp *pSics) - { - int iRet; - - assert(self); - assert(pCon); - assert(pSics); - - iRet = StartMotor(pServ->pExecutor, pSics,pCon,self->pName,self->fCenter); - if(!iRet) - { - return 0; - } - - iRet = Wait4Success(pServ->pExecutor); - switch(iRet) - { - case DEVINT: - if(SCGetInterrupt(pCon) == eAbortOperation) - { - SCSetInterrupt(pCon,eContinue); - SCWrite(pCon,"Driving Aborted",eError); - } - return 0; - break; - case DEVDONE: - SCWrite(pCon,"Driving to center done",eValue); - break; - default: - SCWrite(pCon, - "WARNING: driving to center finished with problems", - eWarning); - break; - - } - return 1; +int CalculateFit(pFit self) +{ + int iRet; + + + /* initialise */ + iRet = Init(self); + if (!iRet) { + return iRet; } - + return CalculateFitIntern(self); +} + +/*------------------------------------------------------------------------*/ +int CalculateFitFromData(pFit self, float *fAxis, long *lCounts, + int iLength) +{ + int iRet; + float *fOld; + long *lOld; + int iOld; + + /* save old data. The normal handling is to have a local copy of + data with fit. This is handled differently in this function, where + it is assumed, that the data is owned by the caller. In order not + to upset fit's scheme for data handling data pointers are swapped. + This is more efficient then copying the data around without real + need. + */ + iOld = self->iNP; + fOld = self->fAxis; + lOld = self->lCounts; + + /* put in new */ + self->iNP = iLength; + self->fAxis = fAxis; + self->lCounts = lCounts; + + iRet = CalculateFitIntern(self); + + /* reset data pointers */ + self->iNP = iOld; + self->fAxis = fOld; + self->lCounts = lOld; + + return iRet; +} + +/*------------------------------------------------------------------------*/ +void GetFitResults(pFit self, float *fCenter, float *fStdDev, + float *FWHM, float *fMax) +{ + assert(self); + *fCenter = self->fCenter; + *FWHM = self->FWHM; + *fMax = (float) self->lPeak; + *fStdDev = self->fStddev; +} + /*--------------------------------------------------------------------------*/ - int FitFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pFit self = NULL; - pScanData pScan = NULL; - pDummy pDum = NULL; - CommandList *pCom = NULL; - char pBueffel[132]; - int iRet, iRet1; - - if(argc < 2) - { - SCWrite(pCon, - "ERROR: MakeFit expected the name of a scan command as a parameter", - eError); - return 0; - } - - pCom = FindCommand(pSics,argv[1]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: scan command %s not found",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pDum = (pDummy)pCom->pData; - if(!pDum) - { - sprintf(pBueffel,"ERROR: scan command %s not found",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(strcmp(pDum->pDescriptor->name,"ScanObject") != 0) - { - sprintf(pBueffel,"ERROR: %s is no scan command",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - pScan = (pScanData)pDum; - self = CreateFitCenter(pScan); - if(!self) - { - SCWrite(pCon,"ERROR: Failure to allocate Peak & Center command",eError); - return 0; - } - - iRet = AddCommand(pSics,"peak",FitWrapper,DeleteFitCenter,self); - iRet1 = AddCommand(pSics,"center",CenterWrapper,NULL,self); - if(!iRet || !iRet1) - { - sprintf(pBueffel, +int DriveCenter(pFit self, SConnection * pCon, SicsInterp * pSics) +{ + int iRet; + + assert(self); + assert(pCon); + assert(pSics); + + iRet = + StartMotor(pServ->pExecutor, pSics, pCon, self->pName, + self->fCenter); + if (!iRet) { + return 0; + } + + iRet = Wait4Success(pServ->pExecutor); + switch (iRet) { + case DEVINT: + if (SCGetInterrupt(pCon) == eAbortOperation) { + SCSetInterrupt(pCon, eContinue); + SCWrite(pCon, "Driving Aborted", eError); + } + return 0; + break; + case DEVDONE: + SCWrite(pCon, "Driving to center done", eValue); + break; + default: + SCWrite(pCon, + "WARNING: driving to center finished with problems", eWarning); + break; + + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int FitFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pFit self = NULL; + pScanData pScan = NULL; + pDummy pDum = NULL; + CommandList *pCom = NULL; + char pBueffel[132]; + int iRet, iRet1; + + if (argc < 2) { + SCWrite(pCon, + "ERROR: MakeFit expected the name of a scan command as a parameter", + eError); + return 0; + } + + pCom = FindCommand(pSics, argv[1]); + if (!pCom) { + sprintf(pBueffel, "ERROR: scan command %s not found", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pDum = (pDummy) pCom->pData; + if (!pDum) { + sprintf(pBueffel, "ERROR: scan command %s not found", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (strcmp(pDum->pDescriptor->name, "ScanObject") != 0) { + sprintf(pBueffel, "ERROR: %s is no scan command", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + pScan = (pScanData) pDum; + self = CreateFitCenter(pScan); + if (!self) { + SCWrite(pCon, "ERROR: Failure to allocate Peak & Center command", + eError); + return 0; + } + + iRet = AddCommand(pSics, "peak", FitWrapper, DeleteFitCenter, self); + iRet1 = AddCommand(pSics, "center", CenterWrapper, NULL, self); + if (!iRet || !iRet1) { + sprintf(pBueffel, "ERROR: duplicate commands peak and center not created"); - SCWrite(pCon,pBueffel,eError); - DeleteFitCenter((void *)self); - return 0; - } - return 1; - } + SCWrite(pCon, pBueffel, eError); + DeleteFitCenter((void *) self); + return 0; + } + return 1; +} + /*--------------------------------------------------------------------------*/ - int FitWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pFit self = NULL; - int iRet; - char pBueffel[256]; - pDynString buf = NULL; - - self = (pFit)pData; - assert(self); - - iRet = CalculateFit(self); - switch(iRet) - { - case 0: - SCWrite(pCon,"ERROR: failure to fit your data!",eError); - return 0; - break; - case -1: - SCWrite(pCon,"WARNING: could not find left hand half width",eWarning); - SCWrite(pCon, - "Fit Results most certainly dodgy, SICS suggests measuring a full peak", - eWarning); - break; - case -2: - SCWrite(pCon,"WARNING: could not find right hand half width",eError); - SCWrite(pCon, - "Fit Results most certainly dodgy, SICS suggests measuring a full peak", - eWarning); - break; - case -3: - SCWrite(pCon,"ERROR: No counts found in Fit!",eError); - return 0; - break; - case -4: - SCWrite(pCon,"ERROR: Insufficient counts in peak",eError); - return 0; - break; - } - - /* - This is a little feature to get the peak without rubbish for - the TAS routines - */ - if(argc > 1) - { - strtolower(argv[1]); - if(strcmp(argv[1],"value") == 0) - { - sprintf(pBueffel,"%f", self->fCenter); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - if(strcmp(argv[1],"data") == 0) - { - snprintf(pBueffel,255,"%f,%f,%ld", - self->fCenter, self->FWHM, self->lPeak); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - - /* print results */ - SCStartBuffering(pCon); - sprintf(pBueffel,"Estimated Peak Center: %f, StdDev: %f \n", - self->fCenter,self->fStddev); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"Maximum peak height: %ld\n", self->lPeak); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"Approximate FWHM: %f\n",self->FWHM); - SCWrite(pCon,pBueffel,eValue); - buf = SCEndBuffering(pCon); - if(buf != NULL){ - SCWrite(pCon,GetCharArray(buf),eValue); - } - - return 1; - } +int FitWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pFit self = NULL; + int iRet; + char pBueffel[256]; + pDynString buf = NULL; + + self = (pFit) pData; + assert(self); + + iRet = CalculateFit(self); + switch (iRet) { + case 0: + SCWrite(pCon, "ERROR: failure to fit your data!", eError); + return 0; + break; + case -1: + SCWrite(pCon, "WARNING: could not find left hand half width", + eWarning); + SCWrite(pCon, + "Fit Results most certainly dodgy, SICS suggests measuring a full peak", + eWarning); + break; + case -2: + SCWrite(pCon, "WARNING: could not find right hand half width", eError); + SCWrite(pCon, + "Fit Results most certainly dodgy, SICS suggests measuring a full peak", + eWarning); + break; + case -3: + SCWrite(pCon, "ERROR: No counts found in Fit!", eError); + return 0; + break; + case -4: + SCWrite(pCon, "ERROR: Insufficient counts in peak", eError); + return 0; + break; + } + + /* + This is a little feature to get the peak without rubbish for + the TAS routines + */ + if (argc > 1) { + strtolower(argv[1]); + if (strcmp(argv[1], "value") == 0) { + sprintf(pBueffel, "%f", self->fCenter); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + if (strcmp(argv[1], "data") == 0) { + snprintf(pBueffel, 255, "%f,%f,%ld", + self->fCenter, self->FWHM, self->lPeak); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + + /* print results */ + SCStartBuffering(pCon); + sprintf(pBueffel, "Estimated Peak Center: %f, StdDev: %f \n", + self->fCenter, self->fStddev); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "Maximum peak height: %ld\n", self->lPeak); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "Approximate FWHM: %f\n", self->FWHM); + SCWrite(pCon, pBueffel, eValue); + buf = SCEndBuffering(pCon); + if (buf != NULL) { + SCWrite(pCon, GetCharArray(buf), eValue); + } + + return 1; +} + /*---------------------------------------------------------------------------*/ - int CenterWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pFit self = NULL; - int iRet; - - self = (pFit)pData; - assert(self); - - return DriveCenter(self,pCon,pSics); - } +int CenterWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pFit self = NULL; + int iRet; + + self = (pFit) pData; + assert(self); + + return DriveCenter(self, pCon, pSics); +} diff --git a/fitcenter.h b/fitcenter.h index 1d892d61..0d7285ff 100644 --- a/fitcenter.h +++ b/fitcenter.h @@ -12,29 +12,28 @@ #ifndef SICSFITCENTER #define SICSFITCENTER - typedef struct __FitCenter *pFit; +typedef struct __FitCenter *pFit; /*--------------------------------------------------------------------------*/ - pFit CreateFitCenter(pScanData pScan); - void DeleteFitCenter(void *pData); +pFit CreateFitCenter(pScanData pScan); +void DeleteFitCenter(void *pData); /*-------------------------------------------------------------------------*/ - int CalculateFit(pFit self); +int CalculateFit(pFit self); /* - CalcluateFit returns: -1 when left FWHM could not be found - -2 when right FWHM could not be found - 1 on success - */ - int CalculateFitFromData(pFit self, float fAxis[], long lSum[], - int iLen); - void GetFitResults(pFit self, float *fNewCenter, float *fStdDev, - float *FWHM, float *fMax); - int DriveCenter(pFit self, SConnection *pCon, SicsInterp *pSics); + CalcluateFit returns: -1 when left FWHM could not be found + -2 when right FWHM could not be found + 1 on success + */ +int CalculateFitFromData(pFit self, float fAxis[], long lSum[], int iLen); +void GetFitResults(pFit self, float *fNewCenter, float *fStdDev, + float *FWHM, float *fMax); +int DriveCenter(pFit self, SConnection * pCon, SicsInterp * pSics); /*-------------------------------------------------------------------------*/ - int FitFactory(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int FitWrapper(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int CenterWrapper(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int FitFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int FitWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int CenterWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/fomerge.c b/fomerge.c index b6dc9d20..6b1eaa3c 100644 --- a/fomerge.c +++ b/fomerge.c @@ -38,14 +38,14 @@ static pFit fitter = NULL; /*================== module static data items ==========================*/ - static HistInt *masterData, *upperData, *mediumData, *lowerData, - *mergedData = NULL; - static int timeBin, nUpper, nLower, nMedium, nMerged; - static float *upperTheta, *lowerTheta, *mediumTheta, *mergedTheta; - static int *mergeUp, *mergeMed, *mergeLow; - int iMerged; +static HistInt *masterData, *upperData, *mediumData, *lowerData, + *mergedData = NULL; +static int timeBin, nUpper, nLower, nMedium, nMerged; +static float *upperTheta, *lowerTheta, *mediumTheta, *mergedTheta; +static int *mergeUp, *mergeMed, *mergeLow; +int iMerged; - int medium, upper, lower; +int medium, upper, lower; /*------------------------------------------------------------------------ The tables with the theta values for the detector banks and the merge table living in mergeUp, mergeMed, mergeLow is initialized from a @@ -55,194 +55,170 @@ static pFit fitter = NULL; -------------------------------------------------------------------------*/ int initializeFM(char *mergefile) { - FILE *fd = NULL; - int i, j, iTest; - char pBuffer[132]; - char *pPtr = NULL; + FILE *fd = NULL; + int i, j, iTest; + char pBuffer[132]; + char *pPtr = NULL; - /* open the file */ - fd = fopen(mergefile,"r"); - if(!fd) - { - fprintf(stdout,"ERROR: merge data file not found!\n"); - return 0; - } + /* open the file */ + fd = fopen(mergefile, "r"); + if (!fd) { + fprintf(stdout, "ERROR: merge data file not found!\n"); + return 0; + } - /* skip first line */ - pPtr = fgets(pBuffer,131,fd); + /* skip first line */ + pPtr = fgets(pBuffer, 131, fd); - /* read the number of merged data points */ - fgets(pBuffer,131,fd); - iTest = sscanf(pBuffer,"%d",&nMerged); - if((iTest != 1) || (nMerged <= 0) ) - { - fprintf(stdout,"ERROR: Invalid or corrupt merge dat file"); - return 0; - } + /* read the number of merged data points */ + fgets(pBuffer, 131, fd); + iTest = sscanf(pBuffer, "%d", &nMerged); + if ((iTest != 1) || (nMerged <= 0)) { + fprintf(stdout, "ERROR: Invalid or corrupt merge dat file"); + return 0; + } - /* allocate space */ - mergedTheta = (float *)malloc(nMerged*sizeof(float)); - mergeUp = (int *)malloc(nMerged*sizeof(int)); - mergeMed = (int *)malloc(nMerged*sizeof(int)); - mergeLow = (int *)malloc(nMerged*sizeof(int)); - if( mergedTheta == NULL || mergeUp == NULL || mergeMed == NULL - || mergeLow == NULL ) - { - fprintf(stdout,"ERROR: out of memory in fomerge\n"); - return 0; - } + /* allocate space */ + mergedTheta = (float *) malloc(nMerged * sizeof(float)); + mergeUp = (int *) malloc(nMerged * sizeof(int)); + mergeMed = (int *) malloc(nMerged * sizeof(int)); + mergeLow = (int *) malloc(nMerged * sizeof(int)); + if (mergedTheta == NULL || mergeUp == NULL || mergeMed == NULL + || mergeLow == NULL) { + fprintf(stdout, "ERROR: out of memory in fomerge\n"); + return 0; + } - /* read the merge table */ - for(i = 0; i < nMerged; i++) - { - fgets(pBuffer,131,fd); - iTest = sscanf(pBuffer,"%d %f %d %d %d",&j, &mergedTheta[i], - &mergeUp[i], &mergeMed[i], &mergeLow[i]); - if(iTest != 5) - { - fprintf(stdout,"ERROR: Invalid or corrupt merge dat file"); + /* read the merge table */ + for (i = 0; i < nMerged; i++) { + fgets(pBuffer, 131, fd); + iTest = sscanf(pBuffer, "%d %f %d %d %d", &j, &mergedTheta[i], + &mergeUp[i], &mergeMed[i], &mergeLow[i]); + if (iTest != 5) { + fprintf(stdout, "ERROR: Invalid or corrupt merge dat file"); return 0; - } - } - - /* read upper bank two theta */ - fgets(pBuffer,131,fd); - fgets(pBuffer,131,fd); - iTest = sscanf(pBuffer,"%d",&nUpper); - if((iTest != 1) || (nUpper <= 0) ) - { - fprintf(stdout,"ERROR: Invalid or corrupt merge data file"); - return 0; - } - upperTheta = (float *)malloc(nUpper*sizeof(float)); - if(upperTheta == NULL) - { - fprintf(stdout,"ERROR: out of memory in fomerge\n"); - return 0; - } - for(i = 0; i < nUpper; i++) - { - fgets(pBuffer,131,fd); - sscanf(pBuffer,"%f",&upperTheta[i]); - } + } + } - /* read middle bank two theta */ - fgets(pBuffer,131,fd); - fgets(pBuffer,131,fd); - iTest = sscanf(pBuffer,"%d",&nMedium); - if((iTest != 1) || (nMedium <= 0) ) - { - fprintf(stdout,"ERROR: Invalid or corrupt merge data file"); - return 0; - } - mediumTheta = (float *)malloc(nMedium*sizeof(float)); - if(mediumTheta == NULL) - { - fprintf(stdout,"ERROR: out of memory in fomerge\n"); - return 0; - } - for(i = 0; i < nMedium; i++) - { - fgets(pBuffer,131,fd); - sscanf(pBuffer,"%f",&mediumTheta[i]); - } + /* read upper bank two theta */ + fgets(pBuffer, 131, fd); + fgets(pBuffer, 131, fd); + iTest = sscanf(pBuffer, "%d", &nUpper); + if ((iTest != 1) || (nUpper <= 0)) { + fprintf(stdout, "ERROR: Invalid or corrupt merge data file"); + return 0; + } + upperTheta = (float *) malloc(nUpper * sizeof(float)); + if (upperTheta == NULL) { + fprintf(stdout, "ERROR: out of memory in fomerge\n"); + return 0; + } + for (i = 0; i < nUpper; i++) { + fgets(pBuffer, 131, fd); + sscanf(pBuffer, "%f", &upperTheta[i]); + } - /* read lower bank two theta */ - fgets(pBuffer,131,fd); - fgets(pBuffer,131,fd); - iTest = sscanf(pBuffer,"%d",&nLower); - if((iTest != 1) || (nLower <= 0) ) - { - fprintf(stdout,"ERROR: Invalid or corrupt merge data file"); - return 0; - } - lowerTheta = (float *)malloc(nLower*sizeof(float)); - if(lowerTheta == NULL) - { - fprintf(stdout,"ERROR: out of memory in fomerge\n"); - return 0; - } - for(i = 0; i < nLower; i++) - { - fgets(pBuffer,131,fd); - sscanf(pBuffer,"%f",&lowerTheta[i]); - } - - /* done */ - timeBin = 0; - iMerged = 0; - medium =1; - upper = lower = 1; + /* read middle bank two theta */ + fgets(pBuffer, 131, fd); + fgets(pBuffer, 131, fd); + iTest = sscanf(pBuffer, "%d", &nMedium); + if ((iTest != 1) || (nMedium <= 0)) { + fprintf(stdout, "ERROR: Invalid or corrupt merge data file"); + return 0; + } + mediumTheta = (float *) malloc(nMedium * sizeof(float)); + if (mediumTheta == NULL) { + fprintf(stdout, "ERROR: out of memory in fomerge\n"); + return 0; + } + for (i = 0; i < nMedium; i++) { + fgets(pBuffer, 131, fd); + sscanf(pBuffer, "%f", &mediumTheta[i]); + } - fclose(fd); - return 1; + /* read lower bank two theta */ + fgets(pBuffer, 131, fd); + fgets(pBuffer, 131, fd); + iTest = sscanf(pBuffer, "%d", &nLower); + if ((iTest != 1) || (nLower <= 0)) { + fprintf(stdout, "ERROR: Invalid or corrupt merge data file"); + return 0; + } + lowerTheta = (float *) malloc(nLower * sizeof(float)); + if (lowerTheta == NULL) { + fprintf(stdout, "ERROR: out of memory in fomerge\n"); + return 0; + } + for (i = 0; i < nLower; i++) { + fgets(pBuffer, 131, fd); + sscanf(pBuffer, "%f", &lowerTheta[i]); + } + + /* done */ + timeBin = 0; + iMerged = 0; + medium = 1; + upper = lower = 1; + + fclose(fd); + return 1; } + /*-------------------------------------------------------------------------- sets the data pointer and finds the starting points for the different banks. This routine contains the knowledge how the detector banks are laid out in the histogram returned from the histogram memory. -------------------------------------------------------------------------*/ -int setFMDataPointer(HistInt *lData, int mytimeBins, int bank) +int setFMDataPointer(HistInt * lData, int mytimeBins, int bank) { HistInt *dataPtr; - if(lData == NULL) - return 0; + if (lData == NULL) + return 0; /* the first set is the medium bank */ masterData = dataPtr = lData; - if (bank==2){ - if(medium) - { + if (bank == 2) { + if (medium) { mediumData = masterData; - } - else - { + } else { mediumData = NULL; } } /* the next set is the upper bank */ - if (bank==1){ - if(upper) - { - upperData = masterData; - } - else - { - upperData = NULL; - } - } + if (bank == 1) { + if (upper) { + upperData = masterData; + } else { + upperData = NULL; + } + } /* the last is the lower bank */ - if (bank==3) { - if(lower) - { - lowerData = masterData; - } - else - { - lowerData = NULL; - } + if (bank == 3) { + if (lower) { + lowerData = masterData; + } else { + lowerData = NULL; + } } /* deal with data allocation for merged data */ - if(mytimeBins != timeBin) - { - if(mergedData != NULL) - { - free(mergedData); + if (mytimeBins != timeBin) { + if (mergedData != NULL) { + free(mergedData); } timeBin = mytimeBins; - mergedData = (HistInt *)malloc(nMerged*timeBin*sizeof(HistInt)); - if(mergedData == NULL) - { - fprintf(stdout,"ERROR: out of memory in fomerge.setFMdataPointer\n"); + mergedData = (HistInt *) malloc(nMerged * timeBin * sizeof(HistInt)); + if (mergedData == NULL) { + fprintf(stdout, + "ERROR: out of memory in fomerge.setFMdataPointer\n"); return 0; } } /* - clear mergedData to 0 - */ - memset(mergedData,0,nMerged*timeBin*sizeof(HistInt)); + clear mergedData to 0 + */ + memset(mergedData, 0, nMerged * timeBin * sizeof(HistInt)); iMerged = 0; return 1; } @@ -254,351 +230,331 @@ void setFMconfiguration(int up, int med, int low) medium = med; lower = low; } + /*-------------------------------------------------------------------------- The algorithm is suboptimal because we have to take care of the case of missing detector banks due to missing or broken electronics or whatever. -*/ +*/ static void mergeData(void) { - int i, j, nDiv; - HistInt *startMerge, *startData; + int i, j, nDiv; + HistInt *startMerge, *startData; - if(!mergedData) - return; + if (!mergedData) + return; - memset(mergedData,0,nMerged*sizeof(HistInt)); - for(i = 0; i < nMerged; i++) - { - startMerge = mergedData + i * timeBin; - nDiv = 0; - /* upper bank contribution */ - if( mergeUp[i] != 0 && upperData != NULL) - { - startData = upperData + (mergeUp[i]-1)*timeBin; - for(j = 0; j < timeBin; j++) - { - startMerge[j] += startData[j]; - } - nDiv++; - } - /* medium bank contribution */ - if( mergeMed[i] != 0 && mediumData != NULL) - { - startData = mediumData + (mergeMed[i]-1)*timeBin; - for(j = 0; j < timeBin; j++) - { - startMerge[j] += startData[j]; - } - nDiv++; - } - /* lower bank contribution */ - if( mergeLow[i] != 0 && lowerData != NULL) - { - startData = lowerData + (mergeLow[i]-1)*timeBin; - for(j = 0; j < timeBin; j++) - { - startMerge[j] += startData[j]; - } - nDiv++; - } - /* do we need to run a division? */ - if(nDiv > 1) - { - for(j = 0; j < timeBin; j++) - { - startMerge[j] /= nDiv; - } - } - } /* end of for */ + memset(mergedData, 0, nMerged * sizeof(HistInt)); + for (i = 0; i < nMerged; i++) { + startMerge = mergedData + i * timeBin; + nDiv = 0; + /* upper bank contribution */ + if (mergeUp[i] != 0 && upperData != NULL) { + startData = upperData + (mergeUp[i] - 1) * timeBin; + for (j = 0; j < timeBin; j++) { + startMerge[j] += startData[j]; + } + nDiv++; + } + /* medium bank contribution */ + if (mergeMed[i] != 0 && mediumData != NULL) { + startData = mediumData + (mergeMed[i] - 1) * timeBin; + for (j = 0; j < timeBin; j++) { + startMerge[j] += startData[j]; + } + nDiv++; + } + /* lower bank contribution */ + if (mergeLow[i] != 0 && lowerData != NULL) { + startData = lowerData + (mergeLow[i] - 1) * timeBin; + for (j = 0; j < timeBin; j++) { + startMerge[j] += startData[j]; + } + nDiv++; + } + /* do we need to run a division? */ + if (nDiv > 1) { + for (j = 0; j < timeBin; j++) { + startMerge[j] /= nDiv; + } + } + } /* end of for */ iMerged = 1; -} +} + /*-----------------------------------------------------------------------*/ void killFM(void) { - if(mergedData != NULL) - free(mergedData); + if (mergedData != NULL) + free(mergedData); - if(lowerTheta != NULL) - free(lowerTheta); + if (lowerTheta != NULL) + free(lowerTheta); - if(mediumTheta != NULL) - free(mediumTheta); + if (mediumTheta != NULL) + free(mediumTheta); - if(upperTheta != NULL) - free(upperTheta); + if (upperTheta != NULL) + free(upperTheta); - if(mergedTheta != NULL) - free(mergedTheta); + if (mergedTheta != NULL) + free(mergedTheta); - if(mergeUp != NULL) - free(mergeUp); + if (mergeUp != NULL) + free(mergeUp); - if(mergeMed != NULL) - free(mergeMed); + if (mergeMed != NULL) + free(mergeMed); - if(mergeLow != NULL) - free(mergeLow); + if (mergeLow != NULL) + free(mergeLow); } + /*-------------------------------------------------------------------------- Below are some not very interesting data access routines ---------------------------------------------------------------------------*/ HistInt *getFMBankPointer(int which) { - switch(which) - { - case UPPER: - return upperData; - break; - case MIDDLE: - return mediumData; - break; - case LOWER: - return lowerData; - break; - case MERGED: - if(!iMerged) - mergeData(); - return mergedData; - break; - default: - assert(0); + switch (which) { + case UPPER: + return upperData; + break; + case MIDDLE: + return mediumData; + break; + case LOWER: + return lowerData; + break; + case MERGED: + if (!iMerged) + mergeData(); + return mergedData; + break; + default: + assert(0); } } + /*-------------------------------------------------------------------------*/ float *getFMBankTheta(int which) { - switch(which) - { - case UPPER: - return upperTheta; - break; - case MIDDLE: - return mediumTheta; - break; - case LOWER: - return lowerTheta; - break; - case MERGED: - return mergedTheta; - break; - default: - assert(0); + switch (which) { + case UPPER: + return upperTheta; + break; + case MIDDLE: + return mediumTheta; + break; + case LOWER: + return lowerTheta; + break; + case MERGED: + return mergedTheta; + break; + default: + assert(0); } } + /*-------------------------------------------------------------------------*/ int getFMdim(int which) { - switch(which) - { - case UPPER: - return nUpper; - break; - case MIDDLE: - return nMedium; - break; - case LOWER: - return nLower; - break; - case MERGED: - return nMerged; - break; - case TIMEBIN: - return timeBin; - break; - default: - assert(0); + switch (which) { + case UPPER: + return nUpper; + break; + case MIDDLE: + return nMedium; + break; + case LOWER: + return nLower; + break; + case MERGED: + return nMerged; + break; + case TIMEBIN: + return timeBin; + break; + default: + assert(0); } } + /*---------------------------------------------------------------------*/ -int InstallFocusMerge(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) +int InstallFocusMerge(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) { int status; char pBueffel[256]; - if(argc < 2) - { - SCWrite(pCon,"ERROR: Insufficient arguments to InstallFocusMerge", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: Insufficient arguments to InstallFocusMerge", + eError); return 0; } - + status = initializeFM(argv[1]); - if(!status) - { - snprintf(pBueffel,255,"ERROR: failed to read mergefile %s", - argv[1]); - SCWrite(pCon,pBueffel,eError); + if (!status) { + snprintf(pBueffel, 255, "ERROR: failed to read mergefile %s", argv[1]); + SCWrite(pCon, pBueffel, eError); return 0; } /* Install command */ - AddCommand(pSics,"focusmerge",FocusMergeAction,NULL,NULL); - return 1; + AddCommand(pSics, "focusmerge", FocusMergeAction, NULL, NULL); + return 1; } + /*---------------------------------------------------------------------*/ -static pNXScript checkNXScript(SicsInterp *pSics, char *name) +static pNXScript checkNXScript(SicsInterp * pSics, char *name) { pNXScript result = NULL; - result = FindCommandData(pSics,name,"NXScript"); - if(result == NULL) - { + result = FindCommandData(pSics, name, "NXScript"); + if (result == NULL) { return NULL; } - if(result->fileHandle == NULL || result->dictHandle == NULL) - { + if (result->fileHandle == NULL || result->dictHandle == NULL) { return NULL; } return result; } + /*---------------------------------------------------------------------*/ -static int updateHMFMData(SicsInterp *pSics, SConnection *pCon) +static int updateHMFMData(SicsInterp * pSics, SConnection * pCon) { int status, iTime; const float *fTimeBin = NULL; HistInt *data = NULL; pHistMem pMem = NULL; - pMem = (pHistMem)FindCommandData(pSics,"hm2","HistMem"); - if(pMem == NULL) - { + pMem = (pHistMem) FindCommandData(pSics, "hm2", "HistMem"); + if (pMem == NULL) { return 0; } - fTimeBin = GetHistTimeBin(pMem,&iTime); - setFMDataPointer(GetHistogramPointer(pMem,pCon),iTime,MIDDLE); - - pMem = (pHistMem)FindCommandData(pSics,"hm1","HistMem"); - if(pMem == NULL) - { - return 0; - } - setFMDataPointer(GetHistogramPointer(pMem,pCon),iTime,LOWER); + fTimeBin = GetHistTimeBin(pMem, &iTime); + setFMDataPointer(GetHistogramPointer(pMem, pCon), iTime, MIDDLE); - pMem = (pHistMem)FindCommandData(pSics,"hm3","HistMem"); - if(pMem == NULL) - { + pMem = (pHistMem) FindCommandData(pSics, "hm1", "HistMem"); + if (pMem == NULL) { return 0; } - setFMDataPointer(GetHistogramPointer(pMem,pCon),iTime,UPPER); - setFMconfiguration(1,1,1); + setFMDataPointer(GetHistogramPointer(pMem, pCon), iTime, LOWER); + + pMem = (pHistMem) FindCommandData(pSics, "hm3", "HistMem"); + if (pMem == NULL) { + return 0; + } + setFMDataPointer(GetHistogramPointer(pMem, pCon), iTime, UPPER); + setFMconfiguration(1, 1, 1); return 1; } + /*-------------------------------------------------------------------*/ -static int *calculateDetSum(HistInt *data, int iDet, int iTime) +static int *calculateDetSum(HistInt * data, int iDet, int iTime) { int i, j, iIndex; int *sum = NULL; - sum = (int *)malloc(iDet*sizeof(int)); - if(!sum) - { + sum = (int *) malloc(iDet * sizeof(int)); + if (!sum) { return NULL; } - memset(sum,0,iDet*sizeof(int)); + memset(sum, 0, iDet * sizeof(int)); - for(i = 0; i < iDet; i++) - { - iIndex = i * iTime; - for(j = 0; j < iTime; j++) - { - sum[i] += data[iIndex+j]; - } + for (i = 0; i < iDet; i++) { + iIndex = i * iTime; + for (j = 0; j < iTime; j++) { + sum[i] += data[iIndex + j]; + } } return sum; } + /*-------------------------------------------------------------------*/ -static int *calculateTimeSum(HistInt *data, int iDet, int iTime) +static int *calculateTimeSum(HistInt * data, int iDet, int iTime) { int i, j; int *sum = NULL; - sum = (int *)malloc(iTime*sizeof(int)); - if(!sum) - { + sum = (int *) malloc(iTime * sizeof(int)); + if (!sum) { return NULL; } - memset(sum,0,iTime*sizeof(int)); + memset(sum, 0, iTime * sizeof(int)); - for(i = 0; i < iTime; i++) - { - for(j = 0; j < iDet; j++) - { - sum[i] += data[j*iTime + i]; - } + for (i = 0; i < iTime; i++) { + for (j = 0; j < iDet; j++) { + sum[i] += data[j * iTime + i]; + } } return sum; } /*--------------------------------------------------------------------*/ -static void checkSum(HistInt *sum, int iDet, char *name, SConnection *pCon){ +static void checkSum(HistInt * sum, int iDet, char *name, + SConnection * pCon) +{ int i, count; char pBueffel[256]; - for(i = 0, count = 0; i < iDet; i++){ - if(sum[i] == 0){ + for (i = 0, count = 0; i < iDet; i++) { + if (sum[i] == 0) { count++; } } - if(count == iDet || count == 0){ + if (count == iDet || count == 0) { return; } - snprintf(pBueffel,255,"WARNING: %d of %d detectors in bank %s are empty", - count, iDet, name); - SCWrite(pCon,pBueffel,eWarning); + snprintf(pBueffel, 255, + "WARNING: %d of %d detectors in bank %s are empty", count, iDet, + name); + SCWrite(pCon, pBueffel, eWarning); } + /*---------------------------------------------------------------------*/ -static int putSum(SicsInterp *pSics, SConnection *pCon, - pNXScript nxscript, char *name, char *alias) +static int putSum(SicsInterp * pSics, SConnection * pCon, + pNXScript nxscript, char *name, char *alias) { HistInt *data = NULL; HistInt *sum = NULL; int iDet, iTime, i, j, iIndex, status; iTime = getFMdim(TIMEBIN); - if(strcmp(name,"upper") == 0) - { + if (strcmp(name, "upper") == 0) { iDet = getFMdim(UPPER); data = getFMBankPointer(UPPER); - } - else if(strcmp(name,"middle") == 0) - { + } else if (strcmp(name, "middle") == 0) { iDet = getFMdim(MIDDLE); data = getFMBankPointer(MIDDLE); - } - else if(strcmp(name,"lower") == 0) - { + } else if (strcmp(name, "lower") == 0) { iDet = getFMdim(LOWER); data = getFMBankPointer(LOWER); - } - else if(strcmp(name,"merged") == 0) - { + } else if (strcmp(name, "merged") == 0) { iDet = getFMdim(MERGED); data = getFMBankPointer(MERGED); - } - else - { - SCWrite(pCon,"ERROR: detector bank to sum not recognised",eError); + } else { + SCWrite(pCon, "ERROR: detector bank to sum not recognised", eError); return NX_ERROR; } - sum = calculateDetSum(data,iDet,iTime); - if(!sum) - { - SCWrite(pCon,"ERROR: out of memory summing bank",eError); + sum = calculateDetSum(data, iDet, iTime); + if (!sum) { + SCWrite(pCon, "ERROR: out of memory summing bank", eError); return NX_ERROR; } - checkSum(sum,iDet, name,pCon); + checkSum(sum, iDet, name, pCon); - status = NXDputalias(nxscript->fileHandle,nxscript->dictHandle, - alias,sum); + status = NXDputalias(nxscript->fileHandle, nxscript->dictHandle, + alias, sum); free(sum); return status; } + /*---------------------------------------------------------------------*/ -static int TOFLambda(SicsInterp *pSics, SConnection *pCon, - int argc, char *argv[]){ +static int TOFLambda(SicsInterp * pSics, SConnection * pCon, + int argc, char *argv[]) +{ int status, iTime, iDet, i; const float *fTimeBin = NULL; int *sum = NULL; @@ -607,72 +563,63 @@ static int TOFLambda(SicsInterp *pSics, SConnection *pCon, float fCenter, fFWHM, fStdDev, fVal; float fMon, fData, distMonoDet, distFermiDet, tdiff, lambda; - pMem = (pHistMem)FindCommandData(pSics,"hm1","HistMem"); - if(pMem == NULL) - { + pMem = (pHistMem) FindCommandData(pSics, "hm1", "HistMem"); + if (pMem == NULL) { SCWrite(pCon, - "ERROR: need lower detector bank for lambda calculation", - eError); + "ERROR: need lower detector bank for lambda calculation", + eError); return 0; } - + /** * locate elastic position in data */ - fTimeBin = GetHistTimeBin(pMem,&iTime); + fTimeBin = GetHistTimeBin(pMem, &iTime); iDet = getFMdim(LOWER); - sum = calculateTimeSum(GetHistogramPointer(pMem,pCon),iDet,iTime); - if(!sum) - { - SCWrite(pCon,"ERROR: out of memory calculating lambda", - eError); + sum = calculateTimeSum(GetHistogramPointer(pMem, pCon), iDet, iTime); + if (!sum) { + SCWrite(pCon, "ERROR: out of memory calculating lambda", eError); return 0; } - if(fitter == NULL) - { + if (fitter == NULL) { fitter = CreateFitCenter(NULL); - if(!fitter) - { - SCWrite(pCon,"ERROR: cannot allocate fitting structure",eError); + if (!fitter) { + SCWrite(pCon, "ERROR: cannot allocate fitting structure", eError); return 0; } } /* - copy sum to make compiler happy - */ - lSum = (long *)malloc(iTime*sizeof(long)); - if(lSum == NULL) - { - SCWrite(pCon,"ERROR: out of memory in TOFLambda",eError); - free(sum); - return 0; + copy sum to make compiler happy + */ + lSum = (long *) malloc(iTime * sizeof(long)); + if (lSum == NULL) { + SCWrite(pCon, "ERROR: out of memory in TOFLambda", eError); + free(sum); + return 0; } - for(i = 0; i < iTime; i++) - { + for (i = 0; i < iTime; i++) { lSum[i] = sum[i]; } - status = CalculateFitFromData(fitter,(float *)fTimeBin,lSum,iTime); - if(status < 0) - { - SCWrite(pCon,"ERROR: no peak in data",eError); - free(sum); - free(lSum); - return 0; + status = CalculateFitFromData(fitter, (float *) fTimeBin, lSum, iTime); + if (status < 0) { + SCWrite(pCon, "ERROR: no peak in data", eError); + free(sum); + free(lSum); + return 0; } - GetFitResults(fitter,&fCenter,&fStdDev,&fFWHM,&fVal); + GetFitResults(fitter, &fCenter, &fStdDev, &fFWHM, &fVal); fData = fCenter; - + /* * locate elastic position in tofmon */ - GetHistogram(pMem, pCon, 0, iTime*iDet, iTime*(iDet+1), - sum, iTime*sizeof(HistInt)); - for(i = 0; i < iTime; i++) - { + GetHistogram(pMem, pCon, 0, iTime * iDet, iTime * (iDet + 1), + sum, iTime * sizeof(HistInt)); + for (i = 0; i < iTime; i++) { lSum[i] = sum[i]; } - status = CalculateFitFromData(fitter,(float *)fTimeBin,lSum,iTime); - GetFitResults(fitter,&fCenter,&fStdDev,&fFWHM,&fVal); + status = CalculateFitFromData(fitter, (float *) fTimeBin, lSum, iTime); + GetFitResults(fitter, &fCenter, &fStdDev, &fFWHM, &fVal); fMon = fCenter; free(sum); free(lSum); @@ -681,15 +628,16 @@ static int TOFLambda(SicsInterp *pSics, SConnection *pCon, * calculate */ distFermiDet = 3000.; - distMonoDet = distFermiDet - 215.7; + distMonoDet = distFermiDet - 215.7; tdiff = fData - fMon; - lambda = tdiff/(252.78*distMonoDet*.001); - SCPrintf(pCon,eValue, "toflambda = %f", lambda); - + lambda = tdiff / (252.78 * distMonoDet * .001); + SCPrintf(pCon, eValue, "toflambda = %f", lambda); + return 1; } + /*---------------------------------------------------------------------*/ -static float calcElastic(SicsInterp *pSics, SConnection *pCon) +static float calcElastic(SicsInterp * pSics, SConnection * pCon) { int status, iTime, iDet, i; const float *fTimeBin = NULL; @@ -698,211 +646,206 @@ static float calcElastic(SicsInterp *pSics, SConnection *pCon) pHistMem pMem = NULL; float fCenter, fFWHM, fStdDev, fVal; - pMem = (pHistMem)FindCommandData(pSics,"hm2","HistMem"); - if(pMem == NULL) - { + pMem = (pHistMem) FindCommandData(pSics, "hm2", "HistMem"); + if (pMem == NULL) { SCWrite(pCon, - "ERROR: need middle detector bank for elastic peak calculation", - eError); + "ERROR: need middle detector bank for elastic peak calculation", + eError); return -1.; } - fTimeBin = GetHistTimeBin(pMem,&iTime); + fTimeBin = GetHistTimeBin(pMem, &iTime); iDet = getFMdim(MIDDLE); - sum = calculateTimeSum(GetHistogramPointer(pMem,pCon),iDet,iTime); - if(!sum) - { - SCWrite(pCon,"ERROR: out of memory calculating elastic peak position", - eError); + sum = calculateTimeSum(GetHistogramPointer(pMem, pCon), iDet, iTime); + if (!sum) { + SCWrite(pCon, "ERROR: out of memory calculating elastic peak position", + eError); return -1; } - if(fitter == NULL) - { + if (fitter == NULL) { fitter = CreateFitCenter(NULL); - if(!fitter) - { - SCWrite(pCon,"ERROR: cannot allocate fitting structure",eError); + if (!fitter) { + SCWrite(pCon, "ERROR: cannot allocate fitting structure", eError); return -1.; } } /* - copy sum to make compiler happy - */ - lSum = (long *)malloc(iTime*sizeof(long)); - if(lSum == NULL) - { - SCWrite(pCon,"ERROR: out of memory in putElastic",eError); + copy sum to make compiler happy + */ + lSum = (long *) malloc(iTime * sizeof(long)); + if (lSum == NULL) { + SCWrite(pCon, "ERROR: out of memory in putElastic", eError); free(sum); return -1.; } - for(i = 0; i < iTime; i++) - { + for (i = 0; i < iTime; i++) { lSum[i] = sum[i]; } - status = CalculateFitFromData(fitter,(float *)fTimeBin,lSum,iTime); + status = CalculateFitFromData(fitter, (float *) fTimeBin, lSum, iTime); free(lSum); - GetFitResults(fitter,&fCenter,&fStdDev,&fFWHM,&fVal); + GetFitResults(fitter, &fCenter, &fStdDev, &fFWHM, &fVal); free(sum); return fCenter; } -/*---------------------------------------------------------------------*/ -#define ABS(x) (x < 0 ? -(x) : (x)) -static int putElastic(SicsInterp *pSics, SConnection *pCon, - pNXScript pNexus, char *alias, float fElastic) +/*---------------------------------------------------------------------*/ +#define ABS(x) (x < 0 ? -(x) : (x)) + +static int putElastic(SicsInterp * pSics, SConnection * pCon, + pNXScript pNexus, char *alias, float fElastic) { - float fCalc; - int status; - - fCalc = calcElastic(pSics,pCon); - if(ABS(fElastic -fCalc) < 20) { - fElastic = fCalc; - } - - status = NXDputalias(pNexus->fileHandle, pNexus->dictHandle,alias, - &fElastic); - return status; + float fCalc; + int status; + + fCalc = calcElastic(pSics, pCon); + if (ABS(fElastic - fCalc) < 20) { + fElastic = fCalc; + } + + status = NXDputalias(pNexus->fileHandle, pNexus->dictHandle, alias, + &fElastic); + return status; } + /*----------------------------------------------------------------------*/ -static int FMputTTH(SConnection *pCon, int argc, char *argv[]){ - pSICSData data = NULL; - int length = -1, i; - float *tthData = NULL; - - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient no of arguments to FMputTTH", - eError); - return 0; - } - - data = (pSICSData)FindCommandData(pServ->pSics,argv[3],"SICSData"); - if(data == NULL){ - SCWrite(pCon,"ERROR: SICSData object not found", eError); - return 0; - } - if(strcmp(argv[2],"upper") == 0) - { - length = getFMdim(UPPER); - tthData = getFMBankTheta(UPPER); - } - else if(strcmp(argv[2],"middle") == 0) - { - length = getFMdim(MIDDLE); - tthData = getFMBankTheta(MIDDLE); - } - else if(strcmp(argv[2],"lower") == 0) - { - length = getFMdim(LOWER); - tthData = getFMBankTheta(LOWER); - } - else if(strcmp(argv[2],"merged") == 0) - { - length = getFMdim(MERGED); - tthData = getFMBankTheta(MERGED); - } - else - { - SCWrite(pCon,"ERROR: requested two_theta for invalid detector bank", - eError); - return 0; - } - if(length < 0 || tthData == NULL){ - SCWrite(pCon,"ERROR: requested two_theta for invalid detector bank", - eError); - return 0; - } - clearSICSData(data); - for(i = 0; i < length; i++){ - setSICSDataFloat(data,i,tthData[i]); - } - SCSendOK(pCon); - return 1; -} -/*---------------------------------------------------------------------*/ -static int FMcopyMerged(SConnection *pCon, int argc, char *argv[]){ - pSICSData data = NULL; - int i, length; - HistInt *hmData = NULL; - - if(argc < 3){ - SCWrite(pCon,"ERROR: insufficient no of arguments to FMcopyMerged", - eError); - return 0; - } - - data = (pSICSData)FindCommandData(pServ->pSics,argv[2],"SICSData"); - if(data == NULL){ - SCWrite(pCon,"ERROR: SICSData object not found", eError); - return 0; - } - if(!updateHMFMData(pServ->pSics, pCon)){ - SCWrite(pCon,"ERROR: not enough HM's to merge or bad names in fomerge.c", - eError); - return 0; - } - - clearSICSData(data); - length = getFMdim(MERGED)*getFMdim(TIMEBIN); - hmData = getFMBankPointer(MERGED); - if(hmData == NULL){ - SCWrite(pCon,"ERROR: merged data not available", eError); - return 0; - } - for(i = 0; i < length; i++){ - setSICSDataInt(data,i,hmData[i]); - } - SCSendOK(pCon); - return 1; -} -/*---------------------------------------------------------------------*/ -static int FMcopyMergedSum(SConnection *pCon, int argc, char *argv[]){ - pSICSData data = NULL; - int i, length, tbin, j, row; - HistInt *hmData = NULL, *sumData = NULL; - - if(argc < 3){ - SCWrite(pCon,"ERROR: insufficient no of arguments to FMcopyMerged", - eError); - return 0; - } - - data = (pSICSData)FindCommandData(pServ->pSics,argv[2],"SICSData"); - if(data == NULL){ - SCWrite(pCon,"ERROR: SICSData object not found", eError); - return 0; - } - if(!updateHMFMData(pServ->pSics, pCon)){ - SCWrite(pCon,"ERROR: not enough HM's to merge or bad names in fomerge.c", - eError); - return 0; - } - - clearSICSData(data); +static int FMputTTH(SConnection * pCon, int argc, char *argv[]) +{ + pSICSData data = NULL; + int length = -1, i; + float *tthData = NULL; + + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient no of arguments to FMputTTH", + eError); + return 0; + } + + data = (pSICSData) FindCommandData(pServ->pSics, argv[3], "SICSData"); + if (data == NULL) { + SCWrite(pCon, "ERROR: SICSData object not found", eError); + return 0; + } + if (strcmp(argv[2], "upper") == 0) { + length = getFMdim(UPPER); + tthData = getFMBankTheta(UPPER); + } else if (strcmp(argv[2], "middle") == 0) { + length = getFMdim(MIDDLE); + tthData = getFMBankTheta(MIDDLE); + } else if (strcmp(argv[2], "lower") == 0) { + length = getFMdim(LOWER); + tthData = getFMBankTheta(LOWER); + } else if (strcmp(argv[2], "merged") == 0) { length = getFMdim(MERGED); - tbin = getFMdim(TIMEBIN); - hmData = getFMBankPointer(MERGED); - if(hmData == NULL){ - SCWrite(pCon,"ERROR: merged data not available", eError); - return 0; - } - sumData = malloc(tbin*sizeof(int)); - if(sumData == NULL){ - SCWrite(pCon,"ERROR: out-of-memory in FMcopyMergedSum", eError); - return 0; - } - memset(sumData,0,tbin*sizeof(int)); - for(j = 0; j < length; j++){ - row = j*tbin; - for(i = 0; i < tbin; i++){ - sumData[i] += hmData[row+i]; - } - } - for(i = 0; i < tbin; i++){ - setSICSDataInt(data,i,sumData[i]); - } - free(sumData); - SCSendOK(pCon); - return 1; + tthData = getFMBankTheta(MERGED); + } else { + SCWrite(pCon, "ERROR: requested two_theta for invalid detector bank", + eError); + return 0; + } + if (length < 0 || tthData == NULL) { + SCWrite(pCon, "ERROR: requested two_theta for invalid detector bank", + eError); + return 0; + } + clearSICSData(data); + for (i = 0; i < length; i++) { + setSICSDataFloat(data, i, tthData[i]); + } + SCSendOK(pCon); + return 1; } + +/*---------------------------------------------------------------------*/ +static int FMcopyMerged(SConnection * pCon, int argc, char *argv[]) +{ + pSICSData data = NULL; + int i, length; + HistInt *hmData = NULL; + + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient no of arguments to FMcopyMerged", + eError); + return 0; + } + + data = (pSICSData) FindCommandData(pServ->pSics, argv[2], "SICSData"); + if (data == NULL) { + SCWrite(pCon, "ERROR: SICSData object not found", eError); + return 0; + } + if (!updateHMFMData(pServ->pSics, pCon)) { + SCWrite(pCon, + "ERROR: not enough HM's to merge or bad names in fomerge.c", + eError); + return 0; + } + + clearSICSData(data); + length = getFMdim(MERGED) * getFMdim(TIMEBIN); + hmData = getFMBankPointer(MERGED); + if (hmData == NULL) { + SCWrite(pCon, "ERROR: merged data not available", eError); + return 0; + } + for (i = 0; i < length; i++) { + setSICSDataInt(data, i, hmData[i]); + } + SCSendOK(pCon); + return 1; +} + +/*---------------------------------------------------------------------*/ +static int FMcopyMergedSum(SConnection * pCon, int argc, char *argv[]) +{ + pSICSData data = NULL; + int i, length, tbin, j, row; + HistInt *hmData = NULL, *sumData = NULL; + + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient no of arguments to FMcopyMerged", + eError); + return 0; + } + + data = (pSICSData) FindCommandData(pServ->pSics, argv[2], "SICSData"); + if (data == NULL) { + SCWrite(pCon, "ERROR: SICSData object not found", eError); + return 0; + } + if (!updateHMFMData(pServ->pSics, pCon)) { + SCWrite(pCon, + "ERROR: not enough HM's to merge or bad names in fomerge.c", + eError); + return 0; + } + + clearSICSData(data); + length = getFMdim(MERGED); + tbin = getFMdim(TIMEBIN); + hmData = getFMBankPointer(MERGED); + if (hmData == NULL) { + SCWrite(pCon, "ERROR: merged data not available", eError); + return 0; + } + sumData = malloc(tbin * sizeof(int)); + if (sumData == NULL) { + SCWrite(pCon, "ERROR: out-of-memory in FMcopyMergedSum", eError); + return 0; + } + memset(sumData, 0, tbin * sizeof(int)); + for (j = 0; j < length; j++) { + row = j * tbin; + for (i = 0; i < tbin; i++) { + sumData[i] += hmData[row + i]; + } + } + for (i = 0; i < tbin; i++) { + setSICSDataInt(data, i, sumData[i]); + } + free(sumData); + SCSendOK(pCon); + return 1; +} + /*----------------------------------------------------------------------- Usage: focusmerge puttwotheta nxscriptmod bankname alias @@ -919,194 +862,158 @@ nxscriptmod = name of the nxscript module used for writing, must be open alias = The alias under which to write the data item theoelastic = theoretical elastic peak position ------------------------------------------------------------------------*/ -int FocusMergeAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) +int FocusMergeAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) { int status; pNXScript pNexus = NULL; float fElastic; char pNum[20]; - if(argc < 2) - { - SCWrite(pCon,"ERROR: Insufficient arguments to focusmerge", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: Insufficient arguments to focusmerge", eError); return 0; } strtolower(argv[1]); - - if(strcmp(argv[1],"puttth") == 0){ - return FMputTTH(pCon,argc,argv); + + if (strcmp(argv[1], "puttth") == 0) { + return FMputTTH(pCon, argc, argv); } - - if(strcmp(argv[1],"copymerged") == 0){ - return FMcopyMerged(pCon,argc,argv); + + if (strcmp(argv[1], "copymerged") == 0) { + return FMcopyMerged(pCon, argc, argv); } - if(strcmp(argv[1],"copymergedsum") == 0){ - return FMcopyMergedSum(pCon,argc,argv); + if (strcmp(argv[1], "copymergedsum") == 0) { + return FMcopyMergedSum(pCon, argc, argv); } - if(strcmp(argv[1],"toflambda") == 0){ - return TOFLambda(pSics, pCon,argc,argv); + if (strcmp(argv[1], "toflambda") == 0) { + return TOFLambda(pSics, pCon, argc, argv); } - if(strcmp(argv[1],"elastic") == 0){ - fElastic = calcElastic(pSics,pCon); - SCPrintf(pCon,eValue,"tofelastic = %f", fElastic); - return 1; + if (strcmp(argv[1], "elastic") == 0) { + fElastic = calcElastic(pSics, pCon); + SCPrintf(pCon, eValue, "tofelastic = %f", fElastic); + return 1; } - - if(strcmp(argv[1],"puttwotheta") == 0) - { - if(argc < 4) - { - SCWrite(pCon,"ERROR: Insufficient arguments to focusmerge puttwotheta", - eError); + + if (strcmp(argv[1], "puttwotheta") == 0) { + if (argc < 4) { + SCWrite(pCon, + "ERROR: Insufficient arguments to focusmerge puttwotheta", + eError); return 0; } pNexus = checkNXScript(pSics, argv[2]); - if(pNexus == NULL) - { - SCWrite(pCon,"ERROR: bad nxscript name or NeXus file not open",eError); + if (pNexus == NULL) { + SCWrite(pCon, "ERROR: bad nxscript name or NeXus file not open", + eError); return 0; } strtolower(argv[3]); - if(strcmp(argv[3],"upper") == 0) - { - status = NXDputalias(pNexus->fileHandle,pNexus->dictHandle, - argv[4],getFMBankTheta(UPPER)); - } - else if(strcmp(argv[3],"middle") == 0) - { - status = NXDputalias(pNexus->fileHandle,pNexus->dictHandle, - argv[4],getFMBankTheta(MIDDLE)); - } - else if(strcmp(argv[3],"lower") == 0) - { - status = NXDputalias(pNexus->fileHandle,pNexus->dictHandle, - argv[4],getFMBankTheta(LOWER)); - } - else if(strcmp(argv[3],"merged") == 0) - { - status = NXDputalias(pNexus->fileHandle,pNexus->dictHandle, - argv[4],getFMBankTheta(MERGED)); - } - else - { - SCWrite(pCon,"ERROR: requested two_theta for invalid detector bank", - eError); + if (strcmp(argv[3], "upper") == 0) { + status = NXDputalias(pNexus->fileHandle, pNexus->dictHandle, + argv[4], getFMBankTheta(UPPER)); + } else if (strcmp(argv[3], "middle") == 0) { + status = NXDputalias(pNexus->fileHandle, pNexus->dictHandle, + argv[4], getFMBankTheta(MIDDLE)); + } else if (strcmp(argv[3], "lower") == 0) { + status = NXDputalias(pNexus->fileHandle, pNexus->dictHandle, + argv[4], getFMBankTheta(LOWER)); + } else if (strcmp(argv[3], "merged") == 0) { + status = NXDputalias(pNexus->fileHandle, pNexus->dictHandle, + argv[4], getFMBankTheta(MERGED)); + } else { + SCWrite(pCon, "ERROR: requested two_theta for invalid detector bank", + eError); return 0; } - if(status == NX_OK) - { + if (status == NX_OK) { SCSendOK(pCon); return 1; - } - else - { - SCWrite(pCon,"ERROR: failed to write two theta array to file",eError); + } else { + SCWrite(pCon, "ERROR: failed to write two theta array to file", + eError); return 0; } - } - else if(strcmp(argv[1],"putmerged") == 0 ) - { - if(argc < 4) - { - SCWrite(pCon,"ERROR: Insufficient arguments to focusmerge", - eError); + } else if (strcmp(argv[1], "putmerged") == 0) { + if (argc < 4) { + SCWrite(pCon, "ERROR: Insufficient arguments to focusmerge", eError); return 0; } pNexus = checkNXScript(pSics, argv[2]); - if(pNexus == NULL) - { - SCWrite(pCon,"ERROR: bad nxscript name or NeXus file not open",eError); + if (pNexus == NULL) { + SCWrite(pCon, "ERROR: bad nxscript name or NeXus file not open", + eError); return 0; } - if(!updateHMFMData(pSics, pCon)) - { - SCWrite(pCon,"ERROR: not enough HM's to merge or bad names in fomerge.c", - eError); + if (!updateHMFMData(pSics, pCon)) { + SCWrite(pCon, + "ERROR: not enough HM's to merge or bad names in fomerge.c", + eError); return 0; } - snprintf(pNum,19,"%d",getFMdim(MERGED)); - NXDupdate(pNexus->dictHandle,"noofdetectors",pNum); - snprintf(pNum,19,"%d",getFMdim(TIMEBIN)); - NXDupdate(pNexus->dictHandle,"timebin",pNum); - status = NXDputalias(pNexus->fileHandle,pNexus->dictHandle, - argv[3],getFMBankPointer(MERGED)); - if(status == NX_OK) - { + snprintf(pNum, 19, "%d", getFMdim(MERGED)); + NXDupdate(pNexus->dictHandle, "noofdetectors", pNum); + snprintf(pNum, 19, "%d", getFMdim(TIMEBIN)); + NXDupdate(pNexus->dictHandle, "timebin", pNum); + status = NXDputalias(pNexus->fileHandle, pNexus->dictHandle, + argv[3], getFMBankPointer(MERGED)); + if (status == NX_OK) { SCSendOK(pCon); return 1; - } - else - { - SCWrite(pCon,"ERROR: failed to write merged data to file",eError); + } else { + SCWrite(pCon, "ERROR: failed to write merged data to file", eError); return 0; } - } - else if(strcmp(argv[1],"putsum") == 0 ) - { - if(argc < 4) - { - SCWrite(pCon,"ERROR: Insufficient arguments to focusmerge putsum", - eError); + } else if (strcmp(argv[1], "putsum") == 0) { + if (argc < 4) { + SCWrite(pCon, "ERROR: Insufficient arguments to focusmerge putsum", + eError); return 0; } pNexus = checkNXScript(pSics, argv[2]); - if(pNexus == NULL) - { - SCWrite(pCon,"ERROR: bad nxscript name or NeXus file not open",eError); + if (pNexus == NULL) { + SCWrite(pCon, "ERROR: bad nxscript name or NeXus file not open", + eError); return 0; } updateHMFMData(pSics, pCon); - status = putSum(pSics,pCon,pNexus,argv[3],argv[4]); - if(status == NX_OK) - { + status = putSum(pSics, pCon, pNexus, argv[3], argv[4]); + if (status == NX_OK) { SCSendOK(pCon); return 1; - } - else - { - SCWrite(pCon,"ERROR: failed to write summed data to file",eError); + } else { + SCWrite(pCon, "ERROR: failed to write summed data to file", eError); return 0; } - } - else if(strcmp(argv[1],"putelastic") == 0 ) - { - if(argc < 4) - { - SCWrite(pCon,"ERROR: Insufficient arguments to focusmerge putelastic", - eError); + } else if (strcmp(argv[1], "putelastic") == 0) { + if (argc < 4) { + SCWrite(pCon, + "ERROR: Insufficient arguments to focusmerge putelastic", + eError); return 0; } pNexus = checkNXScript(pSics, argv[2]); - if(pNexus == NULL) - { - SCWrite(pCon,"ERROR: bad nxscript name or NeXus file not open",eError); + if (pNexus == NULL) { + SCWrite(pCon, "ERROR: bad nxscript name or NeXus file not open", + eError); return 0; } fElastic = atof(argv[4]); - status = putElastic(pSics,pCon,pNexus,argv[3],fElastic); - if(status == NX_OK) - { + status = putElastic(pSics, pCon, pNexus, argv[3], fElastic); + if (status == NX_OK) { SCSendOK(pCon); return 1; - } - else - { - SCWrite(pCon,"ERROR: failed to write elastic peak position",eError); + } else { + SCWrite(pCon, "ERROR: failed to write elastic peak position", + eError); return 0; } - } - else - { - SCWrite(pCon,"ERROR: subcommand to focusmerge not understood",eError); + } else { + SCWrite(pCon, "ERROR: subcommand to focusmerge not understood", + eError); return 0; } return 0; } - - - - diff --git a/fomerge.h b/fomerge.h index 89972939..d133d675 100644 --- a/fomerge.h +++ b/fomerge.h @@ -24,58 +24,57 @@ #define MERGED 4 #define TIMEBIN 5 - int setFMDataPointer(HistInt *lData, int timeBins, int bank); +int setFMDataPointer(HistInt * lData, int timeBins, int bank); /* - sets the data array with the unmerged data. timeBins is the - length of the time binning used. upper, medium and lower are flags - which indicate the presence of the detector bank. - */ + sets the data array with the unmerged data. timeBins is the + length of the time binning used. upper, medium and lower are flags + which indicate the presence of the detector bank. + */ - void setFMconfiguration(int upper, int medium, int lower); +void setFMconfiguration(int upper, int medium, int lower); /* - sets the configuration of the histogram memory - */ + sets the configuration of the histogram memory + */ - HistInt *getFMBankPointer(int which); +HistInt *getFMBankPointer(int which); /* - returns a pointer to the counted data for the detector bank - specified by which. Possible values are given above. - - */ - float *getFMBankTheta(int which); + returns a pointer to the counted data for the detector bank + specified by which. Possible values are given above. + + */ +float *getFMBankTheta(int which); /* - returns a pointer to a float array with the two theta values for - the detector bank specified by which. - */ - - int initializeFM(char *mergefile); + returns a pointer to a float array with the two theta values for + the detector bank specified by which. + */ + +int initializeFM(char *mergefile); /* initializes the two-theta and merging data from the file mergefile. This must have been called before anything else. - */ - - void killFM(void); - /* - frees all merging data structures. - */ + */ - int getFMdim(int which); +void killFM(void); + /* + frees all merging data structures. + */ + +int getFMdim(int which); /* returns the dimension in two theta for the detector banks of the length of the time binning if TIMEBIN has been specified. - */ - - int InstallFocusMerge(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); + */ + +int InstallFocusMerge(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* install the standalone FocusMerge module - */ - int FocusMergeAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); + */ +int FocusMergeAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* FocusMerge interpreter wrapper function - */ + */ #endif - diff --git a/fortify.c b/fortify.c index 19dac50a..eed4664d 100644 --- a/fortify.c +++ b/fortify.c @@ -17,33 +17,35 @@ * */ #ifdef FORTIFY - + #include #include #include #include #include -#define __FORTIFY_C__ /* So fortify.h knows to not define the fortify macros */ +#define __FORTIFY_C__ /* So fortify.h knows to not define the fortify macros */ #include "fortify.h" -#include "ufortify.h" /* the user's options */ +#include "ufortify.h" /* the user's options */ -struct Header -{ - char *File; /* The sourcefile of the caller */ - unsigned long Line; /* The sourceline of the caller */ - size_t Size; /* The size of the malloc'd block */ - struct Header *Prev, /* List pointers */ - *Next; - int Scope; - int Checksum; /* For validating the Header structure; see ChecksumHeader() */ +struct Header { + char *File; /* The sourcefile of the caller */ + unsigned long Line; /* The sourceline of the caller */ + size_t Size; /* The size of the malloc'd block */ + struct Header *Prev, /* List pointers */ + *Next; + int Scope; + int Checksum; /* For validating the Header structure; see ChecksumHeader() */ }; static int CheckBlock(struct Header *h, char *file, unsigned long line); -static int CheckFortification(unsigned char *ptr, unsigned char value, size_t size); -static void SetFortification(unsigned char *ptr, unsigned char value, size_t size); -static void OutputFortification(unsigned char *ptr, unsigned char value, size_t size); +static int CheckFortification(unsigned char *ptr, unsigned char value, + size_t size); +static void SetFortification(unsigned char *ptr, unsigned char value, + size_t size); +static void OutputFortification(unsigned char *ptr, unsigned char value, + size_t size); static int IsHeaderValid(struct Header *h); static void MakeHeaderValid(struct Header *h); static int ChecksumHeader(struct Header *h); @@ -53,19 +55,19 @@ static void OutputMemory(struct Header *h); static void st_DefaultOutput(char *String) { - printf(String); + printf(String); } -static struct Header *st_Head = 0; /* Head of alloc'd memory list */ -static OutputFuncPtr st_Output = st_DefaultOutput; /* Output function for errors */ -static char st_Buffer[256]; /* Temporary buffer for sprintf's */ -static int st_Disabled = 0; /* If true, Fortify is inactive */ -static int st_MallocFailRate = 0; /* % of the time to fail mallocs */ +static struct Header *st_Head = 0; /* Head of alloc'd memory list */ +static OutputFuncPtr st_Output = st_DefaultOutput; /* Output function for errors */ +static char st_Buffer[256]; /* Temporary buffer for sprintf's */ +static int st_Disabled = 0; /* If true, Fortify is inactive */ +static int st_MallocFailRate = 0; /* % of the time to fail mallocs */ -static char *st_LastVerifiedFile = "unknown"; -static unsigned long st_LastVerifiedLine = 0; -static int st_Scope = 0; -static void OutputLastVerifiedPoint(void); +static char *st_LastVerifiedFile = "unknown"; +static unsigned long st_LastVerifiedLine = 0; +static int st_Scope = 0; +static void OutputLastVerifiedPoint(void); /* * Fortify_malloc() - Allocates a block of memory, with extra bits for @@ -86,135 +88,127 @@ static void OutputLastVerifiedPoint(void); void *FORTIFY_STORAGE Fortify_malloc(size_t size, char *file, unsigned long line) { - unsigned char *ptr; - struct Header *h; + unsigned char *ptr; + struct Header *h; - FORTIFY_LOCK(); - - if(st_Disabled) - { - ptr = malloc(size); - FORTIFY_UNLOCK(); - return(ptr); - } + FORTIFY_LOCK(); + if (st_Disabled) { + ptr = malloc(size); + FORTIFY_UNLOCK(); + return (ptr); + } #ifdef CHECK_ALL_MEMORY_ON_MALLOC - Fortify_CheckAllMemory(file, line); -#endif + Fortify_CheckAllMemory(file, line); +#endif - if(size == 0) - { + if (size == 0) { #ifdef WARN_ON_ZERO_MALLOC - sprintf(st_Buffer, - "\nFortify: %s.%ld\n malloc(0) attempted failed\n", - file, line); - st_Output(st_Buffer); + sprintf(st_Buffer, + "\nFortify: %s.%ld\n malloc(0) attempted failed\n", + file, line); + st_Output(st_Buffer); #endif - FORTIFY_UNLOCK(); - return(0); - } + FORTIFY_UNLOCK(); + return (0); + } - if(st_MallocFailRate > 0) - { - if(rand() % 100 < st_MallocFailRate) - { + if (st_MallocFailRate > 0) { + if (rand() % 100 < st_MallocFailRate) { #ifdef WARN_ON_FALSE_FAIL - sprintf(st_Buffer, - "\nFortify: %s.%ld\n malloc(%ld) \"false\" failed\n", - file, line, (unsigned long)size); - st_Output(st_Buffer); + sprintf(st_Buffer, + "\nFortify: %s.%ld\n malloc(%ld) \"false\" failed\n", + file, line, (unsigned long) size); + st_Output(st_Buffer); #endif - FORTIFY_UNLOCK(); - return(0); - } - } - - /* - * malloc the memory, including the space for the header and fortification - * buffers - */ -#ifdef WARN_ON_SIZE_T_OVERFLOW - { - size_t private_size = sizeof(struct Header) - + FORTIFY_BEFORE_SIZE + size + FORTIFY_AFTER_SIZE; + FORTIFY_UNLOCK(); + return (0); + } + } - if(private_size < size) /* Check to see if the added baggage is larger than size_t */ - { - sprintf(st_Buffer, - "\nFortify: %s.%ld\n malloc(%ld) has overflowed size_t.\n", - file, line, (unsigned long)size); - st_Output(st_Buffer); - FORTIFY_UNLOCK(); - return(0); - } - } -#endif + /* + * malloc the memory, including the space for the header and fortification + * buffers + */ +#ifdef WARN_ON_SIZE_T_OVERFLOW + { + size_t private_size = sizeof(struct Header) + + FORTIFY_BEFORE_SIZE + size + FORTIFY_AFTER_SIZE; - ptr = malloc(sizeof(struct Header) + - FORTIFY_BEFORE_SIZE + size + FORTIFY_AFTER_SIZE); - if(!ptr) - { + if (private_size < size) { /* Check to see if the added baggage is larger than size_t */ + sprintf(st_Buffer, + "\nFortify: %s.%ld\n malloc(%ld) has overflowed size_t.\n", + file, line, (unsigned long) size); + st_Output(st_Buffer); + FORTIFY_UNLOCK(); + return (0); + } + } +#endif + + ptr = malloc(sizeof(struct Header) + + FORTIFY_BEFORE_SIZE + size + FORTIFY_AFTER_SIZE); + if (!ptr) { #ifdef WARN_ON_MALLOC_FAIL - sprintf(st_Buffer, "\nFortify: %s.%ld\n malloc(%ld) failed\n", - file, line, (unsigned long)size); - st_Output(st_Buffer); + sprintf(st_Buffer, "\nFortify: %s.%ld\n malloc(%ld) failed\n", + file, line, (unsigned long) size); + st_Output(st_Buffer); #endif - FORTIFY_UNLOCK(); - return(0); - } + FORTIFY_UNLOCK(); + return (0); + } - /* - * Initialize and validate the header - */ - h = (struct Header *)ptr; + /* + * Initialize and validate the header + */ + h = (struct Header *) ptr; - h->Size = size; - - h->File = file; - h->Line = line; - - h->Next = st_Head; - h->Prev = 0; - - h->Scope = st_Scope; + h->Size = size; - if(st_Head) - { - st_Head->Prev = h; - MakeHeaderValid(st_Head); - } + h->File = file; + h->Line = line; - st_Head = h; - - MakeHeaderValid(h); + h->Next = st_Head; + h->Prev = 0; + + h->Scope = st_Scope; + + if (st_Head) { + st_Head->Prev = h; + MakeHeaderValid(st_Head); + } + + st_Head = h; + + MakeHeaderValid(h); - /* - * Initialize the fortifications - */ - SetFortification(ptr + sizeof(struct Header), - FORTIFY_BEFORE_VALUE, FORTIFY_BEFORE_SIZE); - SetFortification(ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE + size, - FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE); + /* + * Initialize the fortifications + */ + SetFortification(ptr + sizeof(struct Header), + FORTIFY_BEFORE_VALUE, FORTIFY_BEFORE_SIZE); + SetFortification(ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE + + size, FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE); -#ifdef FILL_ON_MALLOC - /* - * Fill the actual user memory - */ - SetFortification(ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE, - FILL_ON_MALLOC_VALUE, size); +#ifdef FILL_ON_MALLOC + /* + * Fill the actual user memory + */ + SetFortification(ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE, + FILL_ON_MALLOC_VALUE, size); #endif - /* - * We return the address of the user's memory, not the start of the block, - * which points to our magic cookies - */ + /* + * We return the address of the user's memory, not the start of the block, + * which points to our magic cookies + */ - FORTIFY_UNLOCK(); + FORTIFY_UNLOCK(); - return(ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE); + return (ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE); } /* @@ -230,83 +224,78 @@ Fortify_malloc(size_t size, char *file, unsigned long line) * + Checks the sentinals of the memory being freed. * + Can check the sentinals of all memory. */ - + void FORTIFY_STORAGE Fortify_free(void *uptr, char *file, unsigned long line) { - unsigned char *ptr = (unsigned char *)uptr - sizeof(struct Header) - FORTIFY_BEFORE_SIZE; - struct Header *h = (struct Header *)ptr; + unsigned char *ptr = + (unsigned char *) uptr - sizeof(struct Header) - FORTIFY_BEFORE_SIZE; + struct Header *h = (struct Header *) ptr; - FORTIFY_LOCK(); - - if(st_Disabled) - { - free(uptr); - FORTIFY_UNLOCK(); - return; - } + FORTIFY_LOCK(); + if (st_Disabled) { + free(uptr); + FORTIFY_UNLOCK(); + return; + } #ifdef CHECK_ALL_MEMORY_ON_FREE - Fortify_CheckAllMemory(file, line); -#endif - -#ifdef PARANOID_FREE - if(!IsOnList(h)) - { - sprintf(st_Buffer, - "\nFortify: %s.%ld\n Invalid pointer, corrupted header, or possible free twice\n", - file, line); - st_Output(st_Buffer); - OutputLastVerifiedPoint(); - goto fail; - } + Fortify_CheckAllMemory(file, line); #endif - if(!CheckBlock(h, file, line)) - goto fail; - - /* - * Remove the block from the list - */ - if(h->Prev) - { - if(!CheckBlock(h->Prev, file, line)) - goto fail; - - h->Prev->Next = h->Next; - MakeHeaderValid(h->Prev); - } - else - st_Head = h->Next; - - if(h->Next) - { - if(!CheckBlock(h->Next, file, line)) - goto fail; +#ifdef PARANOID_FREE + if (!IsOnList(h)) { + sprintf(st_Buffer, + "\nFortify: %s.%ld\n Invalid pointer, corrupted header, or possible free twice\n", + file, line); + st_Output(st_Buffer); + OutputLastVerifiedPoint(); + goto fail; + } +#endif - h->Next->Prev = h->Prev; - MakeHeaderValid(h->Next); - } + if (!CheckBlock(h, file, line)) + goto fail; + /* + * Remove the block from the list + */ + if (h->Prev) { + if (!CheckBlock(h->Prev, file, line)) + goto fail; + + h->Prev->Next = h->Next; + MakeHeaderValid(h->Prev); + } else + st_Head = h->Next; + + if (h->Next) { + if (!CheckBlock(h->Next, file, line)) + goto fail; + + h->Next->Prev = h->Prev; + MakeHeaderValid(h->Next); + } #ifdef FILL_ON_FREE - /* - * Nuke out all memory that is about to be freed - */ - SetFortification(ptr, FILL_ON_FREE_VALUE, - sizeof(struct Header) + FORTIFY_BEFORE_SIZE + h->Size + FORTIFY_AFTER_SIZE); -#endif + /* + * Nuke out all memory that is about to be freed + */ + SetFortification(ptr, FILL_ON_FREE_VALUE, + sizeof(struct Header) + FORTIFY_BEFORE_SIZE + h->Size + + FORTIFY_AFTER_SIZE); +#endif - /* - * And do the actual free - */ - free(ptr); - FORTIFY_UNLOCK(); - return; + /* + * And do the actual free + */ + free(ptr); + FORTIFY_UNLOCK(); + return; fail: - sprintf(st_Buffer, " free(%p) failed\n", uptr); - st_Output(st_Buffer); - FORTIFY_UNLOCK(); + sprintf(st_Buffer, " free(%p) failed\n", uptr); + st_Output(st_Buffer); + FORTIFY_UNLOCK(); } /* @@ -322,57 +311,56 @@ fail: void *FORTIFY_STORAGE Fortify_realloc(void *ptr, size_t new_size, char *file, unsigned long line) { - void *new_ptr; - struct Header *h = (struct Header *) - ((unsigned char *)ptr - sizeof(struct Header) - FORTIFY_BEFORE_SIZE); + void *new_ptr; + struct Header *h = (struct Header *) + ((unsigned char *) ptr - sizeof(struct Header) - + FORTIFY_BEFORE_SIZE); - if(st_Disabled) - { - FORTIFY_LOCK(); - new_ptr = realloc(ptr, new_size); - FORTIFY_UNLOCK(); - return(new_ptr); - } + if (st_Disabled) { + FORTIFY_LOCK(); + new_ptr = realloc(ptr, new_size); + FORTIFY_UNLOCK(); + return (new_ptr); + } - if(!ptr) - return(Fortify_malloc(new_size, file, line)); - - FORTIFY_LOCK(); + if (!ptr) + return (Fortify_malloc(new_size, file, line)); - if(!IsOnList(h)) - { - sprintf(st_Buffer, - "\nFortify: %s.%ld\n Invalid pointer or corrupted header passed to realloc\n", - file, line); - st_Output(st_Buffer); - goto fail; - } + FORTIFY_LOCK(); - if(!CheckBlock(h, file, line)) - goto fail; - - new_ptr = Fortify_malloc(new_size, file, line); - if(!new_ptr) - { - FORTIFY_UNLOCK(); - return(0); - } - - if(h->Size < new_size) - memcpy(new_ptr, ptr, h->Size); - else - memcpy(new_ptr, ptr, new_size); + if (!IsOnList(h)) { + sprintf(st_Buffer, + "\nFortify: %s.%ld\n Invalid pointer or corrupted header passed to realloc\n", + file, line); + st_Output(st_Buffer); + goto fail; + } + + if (!CheckBlock(h, file, line)) + goto fail; + + new_ptr = Fortify_malloc(new_size, file, line); + if (!new_ptr) { + FORTIFY_UNLOCK(); + return (0); + } + + if (h->Size < new_size) + memcpy(new_ptr, ptr, h->Size); + else + memcpy(new_ptr, ptr, new_size); + + Fortify_free(ptr, file, line); + FORTIFY_UNLOCK(); + return (new_ptr); - Fortify_free(ptr, file, line); - FORTIFY_UNLOCK(); - return(new_ptr); - fail: - sprintf(st_Buffer, " realloc(%p, %ld) failed\n", ptr, (unsigned long)new_size); - st_Output(st_Buffer); - FORTIFY_UNLOCK(); - return (NULL); -} + sprintf(st_Buffer, " realloc(%p, %ld) failed\n", ptr, + (unsigned long) new_size); + st_Output(st_Buffer); + FORTIFY_UNLOCK(); + return (NULL); +} /* * Fortifty_calloc() - Uses Fortify_malloc() to implement calloc(). Much @@ -381,14 +369,14 @@ fail: void *FORTIFY_STORAGE Fortify_calloc(size_t num, size_t size, char *file, unsigned long line) { - void *ptr; + void *ptr; - ptr = Fortify_malloc(num * size, file, line); - - if(ptr) - memset(ptr, 0, num * size); + ptr = Fortify_malloc(num * size, file, line); - return(ptr); + if (ptr) + memset(ptr, 0, num * size); + + return (ptr); } /* @@ -402,27 +390,27 @@ Fortify_calloc(size_t num, size_t size, char *file, unsigned long line) int FORTIFY_STORAGE Fortify_CheckPointer(void *uptr, char *file, unsigned long line) { - unsigned char *ptr = (unsigned char *)uptr - sizeof(struct Header) - FORTIFY_BEFORE_SIZE; - int r; - - if(st_Disabled) - return(1); + unsigned char *ptr = + (unsigned char *) uptr - sizeof(struct Header) - FORTIFY_BEFORE_SIZE; + int r; - FORTIFY_LOCK(); + if (st_Disabled) + return (1); - if(!IsOnList((struct Header *)ptr)) - { - sprintf(st_Buffer, - "\nFortify: %s.%ld\n Invalid pointer or corrupted header detected (%p)\n", - file, line, uptr); - st_Output(st_Buffer); - FORTIFY_UNLOCK(); - return(0); - } + FORTIFY_LOCK(); - r = CheckBlock((struct Header *)ptr, file, line); - FORTIFY_UNLOCK(); - return r; + if (!IsOnList((struct Header *) ptr)) { + sprintf(st_Buffer, + "\nFortify: %s.%ld\n Invalid pointer or corrupted header detected (%p)\n", + file, line, uptr); + st_Output(st_Buffer); + FORTIFY_UNLOCK(); + return (0); + } + + r = CheckBlock((struct Header *) ptr, file, line); + FORTIFY_UNLOCK(); + return r; } /* @@ -434,11 +422,11 @@ Fortify_CheckPointer(void *uptr, char *file, unsigned long line) Fortify_OutputFuncPtr FORTIFY_STORAGE Fortify_SetOutputFunc(Fortify_OutputFuncPtr Output) { - OutputFuncPtr Old = st_Output; + OutputFuncPtr Old = st_Output; - st_Output = (OutputFuncPtr)Output; - - return((Fortify_OutputFuncPtr)Old); + st_Output = (OutputFuncPtr) Output; + + return ((Fortify_OutputFuncPtr) Old); } /* @@ -447,111 +435,106 @@ Fortify_SetOutputFunc(Fortify_OutputFuncPtr Output) * available. Useful to "stress-test" an application. Returns the old * value. The fail rate defaults to 0. */ -int FORTIFY_STORAGE -Fortify_SetMallocFailRate(int Percent) +int FORTIFY_STORAGE Fortify_SetMallocFailRate(int Percent) { - int Old = st_MallocFailRate; - - st_MallocFailRate = Percent; - - return(Old); + int Old = st_MallocFailRate; + + st_MallocFailRate = Percent; + + return (Old); } - + /* * Fortify_CheckAllMemory() - Checks the sentinals of all malloc'd memory. * Returns the number of blocks that failed. * * (If Fortify is disabled, this function always returns 0). */ -int FORTIFY_STORAGE -Fortify_CheckAllMemory(char *file, unsigned long line) +int FORTIFY_STORAGE Fortify_CheckAllMemory(char *file, unsigned long line) { - struct Header *curr = st_Head; - int count = 0; + struct Header *curr = st_Head; + int count = 0; - if(st_Disabled) - return(0); + if (st_Disabled) + return (0); - FORTIFY_LOCK(); + FORTIFY_LOCK(); - while(curr) - { - if(!CheckBlock(curr, file, line)) - count++; + while (curr) { + if (!CheckBlock(curr, file, line)) + count++; - curr = curr->Next; - } - - if(file) - { - st_LastVerifiedFile = file; - st_LastVerifiedLine = line; - } + curr = curr->Next; + } - FORTIFY_UNLOCK(); - return(count); + if (file) { + st_LastVerifiedFile = file; + st_LastVerifiedLine = line; + } + + FORTIFY_UNLOCK(); + return (count); } /* Fortify_EnterScope - enters a new Fortify scope level. * returns the new scope level. */ -int FORTIFY_STORAGE -Fortify_EnterScope(char *file, unsigned long line) +int FORTIFY_STORAGE Fortify_EnterScope(char *file, unsigned long line) { - return(++st_Scope); + return (++st_Scope); } /* Fortify_LeaveScope - leaves a Fortify scope level, * also prints a memory dump of all non-freed memory that was allocated * during the scope being exited. */ -int FORTIFY_STORAGE -Fortify_LeaveScope(char *file, unsigned long line) +int FORTIFY_STORAGE Fortify_LeaveScope(char *file, unsigned long line) { - struct Header *curr = st_Head; - int count = 0; - unsigned long size = 0; + struct Header *curr = st_Head; + int count = 0; + unsigned long size = 0; - if(st_Disabled) - return(0); + if (st_Disabled) + return (0); - FORTIFY_LOCK(); + FORTIFY_LOCK(); - st_Scope--; - while(curr) - { - if(curr->Scope > st_Scope) - { - if(count == 0) - { - sprintf(st_Buffer, "\nFortify: Memory Dump at %s.%ld\n", file, line); - st_Output(st_Buffer); - OutputLastVerifiedPoint(); - sprintf(st_Buffer, "%11s %8s %s\n", "Address", "Size", "Allocator"); - st_Output(st_Buffer); - } - - OutputHeader(curr); - count++; - size += curr->Size; - } + st_Scope--; + while (curr) { + if (curr->Scope > st_Scope) { + if (count == 0) { + sprintf(st_Buffer, "\nFortify: Memory Dump at %s.%ld\n", file, + line); + st_Output(st_Buffer); + OutputLastVerifiedPoint(); + sprintf(st_Buffer, "%11s %8s %s\n", "Address", "Size", + "Allocator"); + st_Output(st_Buffer); + } - curr = curr->Next; - } + OutputHeader(curr); + count++; + size += curr->Size; + } - if(count) - { - sprintf(st_Buffer, "%11s %8ld bytes overhead\n", "and", - (unsigned long)(count * (sizeof(struct Header) + FORTIFY_BEFORE_SIZE + FORTIFY_AFTER_SIZE))); - st_Output(st_Buffer); + curr = curr->Next; + } - sprintf(st_Buffer,"%11s %8ld bytes in %d blocks\n", "total", size, count); - st_Output(st_Buffer); - } + if (count) { + sprintf(st_Buffer, "%11s %8ld bytes overhead\n", "and", + (unsigned long) (count * + (sizeof(struct Header) + FORTIFY_BEFORE_SIZE + + FORTIFY_AFTER_SIZE))); + st_Output(st_Buffer); - FORTIFY_UNLOCK(); - return(count); + sprintf(st_Buffer, "%11s %8ld bytes in %d blocks\n", "total", size, + count); + st_Output(st_Buffer); + } + + FORTIFY_UNLOCK(); + return (count); } /* @@ -564,44 +547,44 @@ Fortify_LeaveScope(char *file, unsigned long line) * It returns the number of blocks on the list, unless fortify has been * disabled, in which case it always returns 0. */ -int FORTIFY_STORAGE -Fortify_OutputAllMemory(char *file, unsigned long line) +int FORTIFY_STORAGE Fortify_OutputAllMemory(char *file, unsigned long line) { - struct Header *curr = st_Head; - int count = 0; - unsigned long size = 0; + struct Header *curr = st_Head; + int count = 0; + unsigned long size = 0; - if(st_Disabled) - return(0); + if (st_Disabled) + return (0); - FORTIFY_LOCK(); + FORTIFY_LOCK(); - if(curr) - { - sprintf(st_Buffer, "\nFortify: Memory Dump at %s.%ld\n", file, line); - st_Output(st_Buffer); - OutputLastVerifiedPoint(); - sprintf(st_Buffer, "%11s %8s %s\n", "Address", "Size", "Allocator"); - st_Output(st_Buffer); - - while(curr) - { - OutputHeader(curr); - count++; - size += curr->Size; - curr = curr->Next; - } - - sprintf(st_Buffer, "%11s %8ld bytes overhead\n", "and", - (unsigned long)(count * (sizeof(struct Header) + FORTIFY_BEFORE_SIZE + FORTIFY_AFTER_SIZE))); - st_Output(st_Buffer); + if (curr) { + sprintf(st_Buffer, "\nFortify: Memory Dump at %s.%ld\n", file, line); + st_Output(st_Buffer); + OutputLastVerifiedPoint(); + sprintf(st_Buffer, "%11s %8s %s\n", "Address", "Size", "Allocator"); + st_Output(st_Buffer); - sprintf(st_Buffer,"%11s %8ld bytes in %d blocks\n", "total", size, count); - st_Output(st_Buffer); - } - - FORTIFY_UNLOCK(); - return(count); + while (curr) { + OutputHeader(curr); + count++; + size += curr->Size; + curr = curr->Next; + } + + sprintf(st_Buffer, "%11s %8ld bytes overhead\n", "and", + (unsigned long) (count * + (sizeof(struct Header) + FORTIFY_BEFORE_SIZE + + FORTIFY_AFTER_SIZE))); + st_Output(st_Buffer); + + sprintf(st_Buffer, "%11s %8ld bytes in %d blocks\n", "total", size, + count); + st_Output(st_Buffer); + } + + FORTIFY_UNLOCK(); + return (count); } /* Fortify_DumpAllMemory(Scope) - Outputs the entire list of currently @@ -617,50 +600,51 @@ Fortify_OutputAllMemory(char *file, unsigned long line) int FORTIFY_STORAGE Fortify_DumpAllMemory(int scope, char *file, unsigned long line) { - struct Header *curr = st_Head; - int count = 0; - unsigned long size = 0; + struct Header *curr = st_Head; + int count = 0; + unsigned long size = 0; - if(st_Disabled) - return(0); + if (st_Disabled) + return (0); - FORTIFY_LOCK(); + FORTIFY_LOCK(); - while(curr) - { - if(curr->Scope >= scope) - { - if(count == 0) - { - sprintf(st_Buffer, "\nFortify: Memory Dump at %s.%ld\n", file, line); - st_Output(st_Buffer); - OutputLastVerifiedPoint(); - sprintf(st_Buffer, "%11s %8s %s\n", "Address", "Size", "Allocator"); - st_Output(st_Buffer); - } + while (curr) { + if (curr->Scope >= scope) { + if (count == 0) { + sprintf(st_Buffer, "\nFortify: Memory Dump at %s.%ld\n", file, + line); + st_Output(st_Buffer); + OutputLastVerifiedPoint(); + sprintf(st_Buffer, "%11s %8s %s\n", "Address", "Size", + "Allocator"); + st_Output(st_Buffer); + } - OutputHeader(curr); - OutputMemory(curr); - st_Output("\n"); - count++; - size += curr->Size; - } + OutputHeader(curr); + OutputMemory(curr); + st_Output("\n"); + count++; + size += curr->Size; + } - curr = curr->Next; - } + curr = curr->Next; + } - if(count) - { - sprintf(st_Buffer, "%11s %8ld bytes overhead\n", "and", - (unsigned long)(count * (sizeof(struct Header) + FORTIFY_BEFORE_SIZE + FORTIFY_AFTER_SIZE))); - st_Output(st_Buffer); + if (count) { + sprintf(st_Buffer, "%11s %8ld bytes overhead\n", "and", + (unsigned long) (count * + (sizeof(struct Header) + FORTIFY_BEFORE_SIZE + + FORTIFY_AFTER_SIZE))); + st_Output(st_Buffer); - sprintf(st_Buffer,"%11s %8ld bytes in %d blocks\n", "total", size, count); - st_Output(st_Buffer); - } + sprintf(st_Buffer, "%11s %8ld bytes in %d blocks\n", "total", size, + count); + st_Output(st_Buffer); + } - FORTIFY_UNLOCK(); - return(count); + FORTIFY_UNLOCK(); + return (count); } /* @@ -671,108 +655,106 @@ Fortify_DumpAllMemory(int scope, char *file, unsigned long line) * call this function when there IS memory on the Fortify malloc'd list, * it will issue an error, and fortify will not be disabled. */ -int FORTIFY_STORAGE -Fortify_Disable(char *file, unsigned long line) +int FORTIFY_STORAGE Fortify_Disable(char *file, unsigned long line) { - int result; - FORTIFY_LOCK(); + int result; + FORTIFY_LOCK(); - if(st_Head) - { - sprintf(st_Buffer, "Fortify: %s.%d\n", file, (int)line); - st_Output(st_Buffer); - st_Output(" Fortify_Disable failed\n"); - st_Output(" (because there is memory on the Fortify memory list)\n"); - - Fortify_OutputAllMemory(file, line); - result = 0; - } - else - { - st_Disabled = 1; - result = 1; - } - - FORTIFY_UNLOCK(); - return(result); + if (st_Head) { + sprintf(st_Buffer, "Fortify: %s.%d\n", file, (int) line); + st_Output(st_Buffer); + st_Output(" Fortify_Disable failed\n"); + st_Output + (" (because there is memory on the Fortify memory list)\n"); + + Fortify_OutputAllMemory(file, line); + result = 0; + } else { + st_Disabled = 1; + result = 1; + } + + FORTIFY_UNLOCK(); + return (result); } /* * Check a block's header and fortifications. */ static int CheckBlock(struct Header *h, char *file, unsigned long line) -{ - unsigned char *ptr = (unsigned char *)h; - int result = 1; +{ + unsigned char *ptr = (unsigned char *) h; + int result = 1; - if(!IsHeaderValid(h)) - { - sprintf(st_Buffer, - "\nFortify: %s.%ld\n Invalid pointer or corrupted header detected (%p)\n", - file, line, ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE); - st_Output(st_Buffer); - OutputLastVerifiedPoint(); - return(0); - } + if (!IsHeaderValid(h)) { + sprintf(st_Buffer, + "\nFortify: %s.%ld\n Invalid pointer or corrupted header detected (%p)\n", + file, line, ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE); + st_Output(st_Buffer); + OutputLastVerifiedPoint(); + return (0); + } - if(!CheckFortification(ptr + sizeof(struct Header), - FORTIFY_BEFORE_VALUE, FORTIFY_BEFORE_SIZE)) - { - sprintf(st_Buffer, - "\nFortify: %s.%ld\n Memory overrun detected before block\n", - file, line); - st_Output(st_Buffer); + if (!CheckFortification(ptr + sizeof(struct Header), + FORTIFY_BEFORE_VALUE, FORTIFY_BEFORE_SIZE)) { + sprintf(st_Buffer, + "\nFortify: %s.%ld\n Memory overrun detected before block\n", + file, line); + st_Output(st_Buffer); - sprintf(st_Buffer," (%p,%ld,%s.%ld)\n", - ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE, - (unsigned long)h->Size, h->File, h->Line); - st_Output(st_Buffer); - - OutputFortification(ptr + sizeof(struct Header), - FORTIFY_BEFORE_VALUE, FORTIFY_BEFORE_SIZE); - OutputLastVerifiedPoint(); - result = 0; - } - - if(!CheckFortification(ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE + h->Size, - FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE)) - { - sprintf(st_Buffer, "\nFortify: %s.%ld\n Memory overrun detected after block\n", - file, line); - st_Output(st_Buffer); + sprintf(st_Buffer, " (%p,%ld,%s.%ld)\n", + ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE, + (unsigned long) h->Size, h->File, h->Line); + st_Output(st_Buffer); - sprintf(st_Buffer," (%p,%ld,%s.%ld)\n", - ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE, - (unsigned long)h->Size, h->File, h->Line); - st_Output(st_Buffer); + OutputFortification(ptr + sizeof(struct Header), + FORTIFY_BEFORE_VALUE, FORTIFY_BEFORE_SIZE); + OutputLastVerifiedPoint(); + result = 0; + } - OutputFortification(ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE + h->Size, - FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE); - OutputLastVerifiedPoint(); - result = 0; - } - - return(result); + if (!CheckFortification + (ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE + h->Size, + FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE)) { + sprintf(st_Buffer, + "\nFortify: %s.%ld\n Memory overrun detected after block\n", + file, line); + st_Output(st_Buffer); + + sprintf(st_Buffer, " (%p,%ld,%s.%ld)\n", + ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE, + (unsigned long) h->Size, h->File, h->Line); + st_Output(st_Buffer); + + OutputFortification(ptr + sizeof(struct Header) + FORTIFY_BEFORE_SIZE + + h->Size, FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE); + OutputLastVerifiedPoint(); + result = 0; + } + + return (result); } /* * Checks if the _size_ bytes from _ptr_ are all set to _value_ */ -static int CheckFortification(unsigned char *ptr, unsigned char value, size_t size) +static int CheckFortification(unsigned char *ptr, unsigned char value, + size_t size) { - while(size--) - if(*ptr++ != value) - return(0); - - return(1); + while (size--) + if (*ptr++ != value) + return (0); + + return (1); } /* * Set the _size_ bytes from _ptr_ to _value_. */ -static void SetFortification(unsigned char *ptr, unsigned char value, size_t size) +static void SetFortification(unsigned char *ptr, unsigned char value, + size_t size) { - memset(ptr, value, size); + memset(ptr, value, size); } /* @@ -782,61 +764,56 @@ static void SetFortification(unsigned char *ptr, unsigned char value, size_t siz static void OutputFortification(unsigned char *ptr, unsigned char value, size_t size) { - unsigned long offset, column; - char ascii[17]; + unsigned long offset, column; + char ascii[17]; - st_Output("Address Offset Data"); + st_Output("Address Offset Data"); - offset = 0; - column = 0; + offset = 0; + column = 0; - while(offset < size) - { - if(column == 0) - { - sprintf(st_Buffer, "\n%8p %8d ", ptr, (int)offset); - st_Output(st_Buffer); - } + while (offset < size) { + if (column == 0) { + sprintf(st_Buffer, "\n%8p %8d ", ptr, (int) offset); + st_Output(st_Buffer); + } - sprintf(st_Buffer, "%02x ", *ptr); - st_Output(st_Buffer); + sprintf(st_Buffer, "%02x ", *ptr); + st_Output(st_Buffer); - ascii[ column ] = isprint( *ptr ) ? (char)(*ptr) : (char)(' '); - ascii[ column + 1 ] = '\0'; + ascii[column] = isprint(*ptr) ? (char) (*ptr) : (char) (' '); + ascii[column + 1] = '\0'; - ptr++; - offset++; - column++; + ptr++; + offset++; + column++; - if(column == 16) - { - st_Output( " \"" ); - st_Output( ascii ); - st_Output( "\"" ); - column = 0; - } - } + if (column == 16) { + st_Output(" \""); + st_Output(ascii); + st_Output("\""); + column = 0; + } + } - if ( column != 0 ) - { - while ( column ++ < 16 ) - { - st_Output( " " ); - } - st_Output( " \"" ); - st_Output( ascii ); - st_Output( "\"" ); - } + if (column != 0) { + while (column++ < 16) { + st_Output(" "); + } + st_Output(" \""); + st_Output(ascii); + st_Output("\""); + } - st_Output("\n"); + st_Output("\n"); } /* * Returns true if the supplied pointer does indeed point to a real Header */ -static int IsHeaderValid(struct Header *h) +static int IsHeaderValid(struct Header *h) { - return(!ChecksumHeader(h)); + return (!ChecksumHeader(h)); } /* @@ -844,8 +821,8 @@ static int IsHeaderValid(struct Header *h) */ static void MakeHeaderValid(struct Header *h) { - h->Checksum = 0; - h->Checksum = -ChecksumHeader(h); + h->Checksum = 0; + h->Checksum = -ChecksumHeader(h); } /* @@ -855,41 +832,40 @@ static void MakeHeaderValid(struct Header *h) */ static int ChecksumHeader(struct Header *h) { - int c, checksum, *p; - - for(c = 0, checksum = 0, p = (int *)h; c < sizeof(struct Header)/sizeof(int); c++) - checksum += *p++; - - return(checksum); -} + int c, checksum, *p; + + for (c = 0, checksum = 0, p = (int *) h; + c < sizeof(struct Header) / sizeof(int); c++) + checksum += *p++; + + return (checksum); +} /* * Examines the malloc'd list to see if the given header is on it. - */ + */ static int IsOnList(struct Header *h) { - struct Header *curr; - - curr = st_Head; - while(curr) - { - if(curr == h) - return(1); - - curr = curr->Next; - } - - return(0); + struct Header *curr; + + curr = st_Head; + while (curr) { + if (curr == h) + return (1); + + curr = curr->Next; + } + + return (0); } /* * Hex and ascii dump the memory */ -static void -OutputMemory(struct Header *h) +static void OutputMemory(struct Header *h) { - OutputFortification((unsigned char*)h + sizeof(struct Header) + FORTIFY_BEFORE_SIZE, - 0, h->Size); + OutputFortification((unsigned char *) h + sizeof(struct Header) + + FORTIFY_BEFORE_SIZE, 0, h->Size); } @@ -898,20 +874,19 @@ OutputMemory(struct Header *h) */ static void OutputHeader(struct Header *h) { - sprintf(st_Buffer, "%11p %8ld %s.%ld (%d)\n", - (unsigned char*)h + sizeof(struct Header) + FORTIFY_BEFORE_SIZE, - (unsigned long)h->Size, - h->File, h->Line, h->Scope); - st_Output(st_Buffer); + sprintf(st_Buffer, "%11p %8ld %s.%ld (%d)\n", + (unsigned char *) h + sizeof(struct Header) + + FORTIFY_BEFORE_SIZE, (unsigned long) h->Size, h->File, h->Line, + h->Scope); + st_Output(st_Buffer); } static void OutputLastVerifiedPoint() { - sprintf(st_Buffer, "\nLast Verified point: %s.%ld\n", - st_LastVerifiedFile, - st_LastVerifiedLine); - st_Output(st_Buffer); + sprintf(st_Buffer, "\nLast Verified point: %s.%ld\n", + st_LastVerifiedFile, st_LastVerifiedLine); + st_Output(st_Buffer); } -#endif /* FORTIFY */ +#endif /* FORTIFY */ diff --git a/fortify.h b/fortify.h index 3983fc57..debbb325 100644 --- a/fortify.h +++ b/fortify.h @@ -24,39 +24,38 @@ extern "C" { #endif -typedef void (*OutputFuncPtr)(char *); + typedef void (*OutputFuncPtr) (char *); -void *Fortify_malloc(size_t size, char *file, unsigned long line); -void *Fortify_realloc(void *ptr, size_t new_size, char *file, unsigned long line); -void *Fortify_calloc(size_t num, size_t size, char *file, unsigned long line); -void Fortify_free(void *uptr, char *file, unsigned long line); -char *Fortify_STRDUP(const char *in, char *file, unsigned long line); + void *Fortify_malloc(size_t size, char *file, unsigned long line); + void *Fortify_realloc(void *ptr, size_t new_size, char *file, + unsigned long line); + void *Fortify_calloc(size_t num, size_t size, char *file, + unsigned long line); + void Fortify_free(void *uptr, char *file, unsigned long line); + char *Fortify_STRDUP(const char *in, char *file, unsigned long line); -int Fortify_OutputAllMemory(char *file, unsigned long line); -int Fortify_CheckAllMemory(char *file, unsigned long line); -int Fortify_CheckPointer(void *uptr, char *file, unsigned long line); -int Fortify_Disable(char *file, unsigned long line); -int Fortify_SetMallocFailRate(int Percent); -int Fortify_EnterScope(char *file, unsigned long line); -int Fortify_LeaveScope(char *file, unsigned long line); -int Fortify_DumpAllMemory(int scope, char *file, unsigned long line); + int Fortify_OutputAllMemory(char *file, unsigned long line); + int Fortify_CheckAllMemory(char *file, unsigned long line); + int Fortify_CheckPointer(void *uptr, char *file, unsigned long line); + int Fortify_Disable(char *file, unsigned long line); + int Fortify_SetMallocFailRate(int Percent); + int Fortify_EnterScope(char *file, unsigned long line); + int Fortify_LeaveScope(char *file, unsigned long line); + int Fortify_DumpAllMemory(int scope, char *file, unsigned long line); -typedef void (*Fortify_OutputFuncPtr)(const char *); -Fortify_OutputFuncPtr Fortify_SetOutputFunc(Fortify_OutputFuncPtr Output); + typedef void (*Fortify_OutputFuncPtr) (const char *); + Fortify_OutputFuncPtr Fortify_SetOutputFunc(Fortify_OutputFuncPtr + Output); #ifdef __cplusplus } #endif - -#ifndef __FORTIFY_C__ /* Only define the macros if we're NOT in fortify.c */ - -#ifdef FORTIFY /* Add file and line information to the fortify calls */ - +#ifndef __FORTIFY_C__ /* Only define the macros if we're NOT in fortify.c */ +#ifdef FORTIFY /* Add file and line information to the fortify calls */ #define malloc(size) Fortify_malloc(size, __FILE__, __LINE__) #define realloc(ptr,new_size) Fortify_realloc(ptr, new_size, __FILE__, __LINE__) #define calloc(num,size) Fortify_calloc(num, size, __FILE__, __LINE__) #define free(ptr) Fortify_free(ptr, __FILE__, __LINE__) - #define Fortify_OutputAllMemory() Fortify_OutputAllMemory(__FILE__, __LINE__) #define Fortify_CheckAllMemory() Fortify_CheckAllMemory(__FILE__, __LINE__) #define Fortify_CheckPointer(ptr) Fortify_CheckPointer(ptr, __FILE__, __LINE__) @@ -65,9 +64,7 @@ Fortify_OutputFuncPtr Fortify_SetOutputFunc(Fortify_OutputFuncPtr Output); #define Fortify_LeaveScope() Fortify_LeaveScope(__FILE__, __LINE__) #define Fortify_DumpAllMemory(s) Fortify_DumpAllMemory(s,__FILE__, __LINE__) #define strdup(s) Fortify_STRDUP(s,__FILE__,__LINE__) - -#else /* FORTIFY Define the special fortify functions away to nothing */ - +#else /* FORTIFY Define the special fortify functions away to nothing */ #define Fortify_OutputAllMemory() 0 #define Fortify_CheckAllMemory() 0 #define Fortify_CheckPointer(ptr) 1 @@ -77,7 +74,6 @@ Fortify_OutputFuncPtr Fortify_SetOutputFunc(Fortify_OutputFuncPtr Output); #define Fortify_EnterScope() 0 #define Fortify_LeaveScope() 0 #define Fortify_DumpAllMemory(s) 0 - -#endif /* FORTIFY */ -#endif /* __FORTIFY_C__ */ -#endif /* __FORTIFY_H__ */ +#endif /* FORTIFY */ +#endif /* __FORTIFY_C__ */ +#endif /* __FORTIFY_H__ */ diff --git a/fourlib.c b/fourlib.c index ee4fc8d0..57734cca 100644 --- a/fourlib.c +++ b/fourlib.c @@ -31,98 +31,109 @@ #define PI 3.141592653589793 #define RD 57.30 -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*------------------------------------------------------------------------ a safe routine for calculating the atan of y/x ------------------------------------------------------------------------*/ -static double myatan(double y, double x){ - if(ABS(x) < 0.0001){ - if(y > .0){ - return PI/2; - }else { - return -PI/2; +static double myatan(double y, double x) +{ + if (ABS(x) < 0.0001) { + if (y > .0) { + return PI / 2; + } else { + return -PI / 2; } } - if(x > .0){ - return atan(y/x); + if (x > .0) { + return atan(y / x); } else { - if(y > .0){ - return PI + atan(y/x); - } else { - return -PI + atan(y/x); - } - } + if (y > .0) { + return PI + atan(y / x); + } else { + return -PI + atan(y / x); + } + } } + /*-------------------------------------------------------------------------*/ -static double rtan(double y, double x){ +static double rtan(double y, double x) +{ double val; - if( (x == 0.) && (y == 0.) ) { + if ((x == 0.) && (y == 0.)) { return .0; - } - if( x == 0.) { - if(y < 0.){ - return -PI/2.; - } else { - return PI/2.; - } } - if(ABS(y) < ABS(x)) { - val = atan(ABS(y/x)); - if(x < 0.) { - val = PI - val; + if (x == 0.) { + if (y < 0.) { + return -PI / 2.; + } else { + return PI / 2.; + } + } + if (ABS(y) < ABS(x)) { + val = atan(ABS(y / x)); + if (x < 0.) { + val = PI - val; + } + if (y < 0.) { + val = -val; } - if(y < 0.){ - val = -val; - } return val; } else { - val = PI/2. - atan(ABS(x/y)); - if(x < 0.) { + val = PI / 2. - atan(ABS(x / y)); + if (x < 0.) { val = PI - val; - } - if( y < 0.) { - val = - val; - } + } + if (y < 0.) { + val = -val; + } } return val; } + /*---------------------------------------------------------------------- clear3x3 sets a 3x3 matrix to 0 -----------------------------------------------------------------------*/ -static void clear3x3(MATRIX target){ +static void clear3x3(MATRIX target) +{ int i, j; - for(i = 0; i < 3; i++){ - for(j = 0; j < 3; j++){ + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { target[i][j] = .0; } } } + /*---------------------------------------------------------------------*/ -MATRIX vectorToMatrix(double z[3]){ +MATRIX vectorToMatrix(double z[3]) +{ int i; MATRIX res; - res = mat_creat(3,1,ZERO_MATRIX); - for(i = 0; i < 3; i++){ + res = mat_creat(3, 1, ZERO_MATRIX); + for (i = 0; i < 3; i++) { res[i][0] = z[i]; } return res; } + /*---------------------------------------------------------------------*/ -void matrixToVector(MATRIX zm, double z[3]){ +void matrixToVector(MATRIX zm, double z[3]) +{ int i; - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { z[i] = zm[i][0]; } } + /*---------------------------------------------------------------------- A Busing & levy PSI matrix ----------------------------------------------------------------------*/ -static void psimat(MATRIX target, double psi){ - double psird = psi/RD; +static void psimat(MATRIX target, double psi) +{ + double psird = psi / RD; clear3x3(target); @@ -132,11 +143,13 @@ static void psimat(MATRIX target, double psi){ target[2][1] = -target[1][2]; target[2][2] = target[1][1]; } + /*---------------------------------------------------------------------- A Busing & levy CHI matrix ----------------------------------------------------------------------*/ -void chimat(MATRIX target, double chi){ - double chird = chi/RD; +void chimat(MATRIX target, double chi) +{ + double chird = chi / RD; clear3x3(target); @@ -146,11 +159,13 @@ void chimat(MATRIX target, double chi){ target[2][0] = -target[0][2]; target[2][2] = target[0][0]; } + /*---------------------------------------------------------------------- A Busing & levy PHI matrix ----------------------------------------------------------------------*/ -void phimat(MATRIX target, double phi){ - double phird = phi/RD; +void phimat(MATRIX target, double phi) +{ + double phird = phi / RD; clear3x3(target); @@ -160,36 +175,40 @@ void phimat(MATRIX target, double phi){ target[1][1] = target[0][0]; target[2][2] = 1.; } + /*------------------- PSD specific code ----------------------------*/ -void det2pol(psdDescription *psd, int x, int y, double *gamma, double *nu) { +void det2pol(psdDescription * psd, int x, int y, double *gamma, double *nu) +{ double xobs, yobs, b, z, d; - assert(ABS(psd->distance ) > .001); + assert(ABS(psd->distance) > .001); - xobs = (x - psd->xZero)*psd->xScale; - yobs = (y - psd->yZero)*psd->yScale; + xobs = (x - psd->xZero) * psd->xScale; + yobs = (y - psd->yZero) * psd->yScale; - b = psd->distance*cos(yobs/psd->distance); - z = psd->distance*sin(yobs/psd->distance); - d = sqrt(xobs*xobs + b*b); - *gamma = psd->gamma + myatan(xobs,b)*RD; - *nu = psd->nu + myatan(z,d)*RD; + b = psd->distance * cos(yobs / psd->distance); + z = psd->distance * sin(yobs / psd->distance); + d = sqrt(xobs * xobs + b * b); + *gamma = psd->gamma + myatan(xobs, b) * RD; + *nu = psd->nu + myatan(z, d) * RD; } + /*----------------------------------------------------------------------*/ -void pol2det(psdDescription *psd, double gamma, double nu, int *x, int *y){ +void pol2det(psdDescription * psd, double gamma, double nu, int *x, int *y) +{ double delga, delnu, td, tn, e, f, g, zobs, xobs; delga = gamma - psd->gamma; - delnu = nu - psd->nu; - td = tan(delga/RD); - tn = tan(delnu/RD); - e = sqrt(1. + td*td); - f = tn*e; - g = psd->distance*(1. + tn*tn +tn*tn*td*td); - zobs = psd->distance*(atan(tn*e) + asin(f/g)); - xobs = td*(psd->distance*cos(zobs/psd->distance)); - *y = (int)rint(psd->yZero + zobs/psd->yScale); - *x = (int)rint(psd->xZero + xobs/psd->xScale); + delnu = nu - psd->nu; + td = tan(delga / RD); + tn = tan(delnu / RD); + e = sqrt(1. + td * td); + f = tn * e; + g = psd->distance * (1. + tn * tn + tn * tn * td * td); + zobs = psd->distance * (atan(tn * e) + asin(f / g)); + xobs = td * (psd->distance * cos(zobs / psd->distance)); + *y = (int) rint(psd->yZero + zobs / psd->yScale); + *x = (int) rint(psd->xZero + xobs / psd->xScale); } /*--------------- bisecting geometry code -----------------------------*/ @@ -197,84 +216,94 @@ void pol2det(psdDescription *psd, double gamma, double nu, int *x, int *y){ /* turn chi and phi in order to get Z1 into the equatorial plane */ -static void turnEquatorial(MATRIX z1, double *chi, double *phi){ - if(ABS(z1[0][0]) < .0001 && ABS(z1[1][0]) < .00001){ +static void turnEquatorial(MATRIX z1, double *chi, double *phi) +{ + if (ABS(z1[0][0]) < .0001 && ABS(z1[1][0]) < .00001) { *phi = .0; *chi = 90.; - if(z1[2][0] < .0){ - *chi = - *chi; + if (z1[2][0] < .0) { + *chi = -*chi; } } else { - *phi = myatan(z1[1][0],z1[0][0])*RD; + *phi = myatan(z1[1][0], z1[0][0]) * RD; *chi = myatan(z1[2][0], - sqrt(z1[0][0]*z1[0][0] + z1[1][0]*z1[1][0]))*RD; + sqrt(z1[0][0] * z1[0][0] + z1[1][0] * z1[1][0])) * RD; } } + /*---------------------------------------------------------------------- calculate d-spacing and theta from z1 -----------------------------------------------------------------------*/ -int calcTheta(double lambda, MATRIX z1, double *d, double *theta){ +int calcTheta(double lambda, MATRIX z1, double *d, double *theta) +{ double dstar, sintheta; - dstar = sqrt(z1[0][0]*z1[0][0] + z1[1][0]*z1[1][0] + z1[2][0]*z1[2][0]); - if(dstar < .0001){ + dstar = + sqrt(z1[0][0] * z1[0][0] + z1[1][0] * z1[1][0] + + z1[2][0] * z1[2][0]); + if (dstar < .0001) { *d = .0; *theta = 0; return 0; } - *d = 1./dstar; - sintheta = lambda * dstar/2.; - if(ABS(sintheta) > 1.0){ + *d = 1. / dstar; + sintheta = lambda * dstar / 2.; + if (ABS(sintheta) > 1.0) { *d = .0; *theta = .0; return 0; } - *theta = asin(sintheta)*RD; + *theta = asin(sintheta) * RD; return 1; } + /*-------------------------------------------------------------------*/ int z1ToBisecting(double lambda, double z1[3], double *stt, double *om, - double *chi, double *phi) { + double *chi, double *phi) +{ MATRIX zz1; int status; zz1 = vectorToMatrix(z1); - status = z1mToBisecting(lambda,zz1,stt,om,chi,phi); + status = z1mToBisecting(lambda, zz1, stt, om, chi, phi); mat_free(zz1); return status; } + /*------------------------------------------------------------------------*/ int z1mToBisecting(double lambda, MATRIX z1, double *stt, double *om, - double *chi, double *phi) { + double *chi, double *phi) +{ double d; int status; - - status = calcTheta(lambda,z1,&d,om); - if(!status){ + + status = calcTheta(lambda, z1, &d, om); + if (!status) { *stt = .0; *om = .0; *chi = .0; *phi = .0; return status; } - turnEquatorial(z1,chi,phi); - *stt = *om*2.; + turnEquatorial(z1, chi, phi); + *stt = *om * 2.; *chi = 180. - *chi; *phi = 180. + *phi; return 1; } + /*---------------------------------------------------------------------*/ -int z1ToAnglesWithOffset(double lambda, MATRIX z1m,double omOffset, - double *stt, double *om, - double *chi, double *phi){ +int z1ToAnglesWithOffset(double lambda, MATRIX z1m, double omOffset, + double *stt, double *om, double *chi, double *phi) +{ int status, i; double d, delOm, sinchi, q, cosp, sinp, dstar; MATRIX z1; - status = calcTheta(lambda,z1m,&d,om); - if(!status){ + status = calcTheta(lambda, z1m, &d, om); + if (!status) { *stt = .0; *om = .0; *chi = .0; @@ -284,158 +313,173 @@ int z1ToAnglesWithOffset(double lambda, MATRIX z1m,double omOffset, *stt = 2. * *om; *om += omOffset; - z1 = mat_copy(z1m); /* routine messes z1m up! */ - dstar = sqrt(z1[0][0]*z1[0][0] + z1[1][0]*z1[1][0] + z1[2][0]*z1[2][0]); - for(i = 0; i < 3; i++){ - z1[i][0] /= dstar; + z1 = mat_copy(z1m); /* routine messes z1m up! */ + dstar = + sqrt(z1[0][0] * z1[0][0] + z1[1][0] * z1[1][0] + + z1[2][0] * z1[2][0]); + for (i = 0; i < 3; i++) { + z1[i][0] /= dstar; } - delOm = -omOffset/RD; - sinchi = z1[2][0]/cos(delOm); - if(ABS(sinchi) > 1.){ + delOm = -omOffset / RD; + sinchi = z1[2][0] / cos(delOm); + if (ABS(sinchi) > 1.) { mat_free(z1); return 0; } *chi = asin(sinchi); *chi = PI - *chi; - if(*chi > PI){ - *chi = *chi - 2* PI; + if (*chi > PI) { + *chi = *chi - 2 * PI; } - - q = cos(delOm)*cos(*chi); - cosp = (sin(delOm)*z1[0][0] + q*z1[1][0])/ - (sin(delOm)*sin(delOm) + q*q); - sinp = (z1[0][0] - sin(delOm)*cosp)/ q; - *phi = rtan(cosp,sinp); + + q = cos(delOm) * cos(*chi); + cosp = (sin(delOm) * z1[0][0] + q * z1[1][0]) / + (sin(delOm) * sin(delOm) + q * q); + sinp = (z1[0][0] - sin(delOm) * cosp) / q; + *phi = rtan(cosp, sinp); *phi *= RD; *chi *= RD; mat_free(z1); - return 1; + return 1; } + /*---------------------------------------------------------------------*/ -int psiForOmegaOffset(MATRIX z1m, double omOffset, - double chi, double phi, double *psi){ - double chibi, sinps, cosps, sinchi, dstar; +int psiForOmegaOffset(MATRIX z1m, double omOffset, + double chi, double phi, double *psi) +{ + double chibi, sinps, cosps, sinchi, dstar; MATRIX z1; - z1 = mat_copy(z1m); /* routine messes z1m up! */ - dstar = sqrt(z1[0][0]*z1[0][0] + z1[1][0]*z1[1][0] + z1[2][0]*z1[2][0]); + z1 = mat_copy(z1m); /* routine messes z1m up! */ + dstar = + sqrt(z1[0][0] * z1[0][0] + z1[1][0] * z1[1][0] + + z1[2][0] * z1[2][0]); z1[2][0] /= dstar; omOffset /= RD; - if(-z1[2][0] == 1.){ + if (-z1[2][0] == 1.) { *psi = phi; } else { chibi = PI - asin(-z1[2][0]); - if(chibi > PI){ - chibi -= 2*PI; + if (chibi > PI) { + chibi -= 2 * PI; } - sinps = tan(chibi)*tan(-omOffset); - sinchi = -z1[2][0]/cos(-omOffset); - if(ABS(sinchi) > 1.){ + sinps = tan(chibi) * tan(-omOffset); + sinchi = -z1[2][0] / cos(-omOffset); + if (ABS(sinchi) > 1.) { mat_free(z1); return 0; } - cosps = (cos(chibi) - sinps*sin(-omOffset)*sinchi)/cos(chi/RD); - *psi = -rtan(sinps,cosps)*RD; + cosps = (cos(chibi) - sinps * sin(-omOffset) * sinchi) / cos(chi / RD); + *psi = -rtan(sinps, cosps) * RD; } mat_free(z1); - return 1; + return 1; } /*----------------------------------------------------------------------*/ void rotatePsi(double om, double chi, double phi, double psi, - double *newom, double *newchi, double *newphi){ + double *newom, double *newchi, double *newphi) +{ MATRIX chim, phim, psim, r0, r0psi; - chim = mat_creat(3,3,ZERO_MATRIX); - chimat(chim,chi); - phim = mat_creat(3,3,ZERO_MATRIX); - phimat(phim,phi); - r0 = mat_mul(chim,phim); - psim = mat_creat(3,3,ZERO_MATRIX); - psimat(psim,psi); - r0psi = mat_mul(psim,r0); - - *newchi = rtan(sqrt(r0psi[2][0]*r0psi[2][0] + r0psi[2][1]*r0psi[2][1]), - r0psi[2][2])*RD; - *newphi = rtan(-r0psi[2][1],-r0psi[2][0])*RD; - *newom = om + rtan(-r0psi[1][2],r0psi[0][2])*RD; + chim = mat_creat(3, 3, ZERO_MATRIX); + chimat(chim, chi); + phim = mat_creat(3, 3, ZERO_MATRIX); + phimat(phim, phi); + r0 = mat_mul(chim, phim); + psim = mat_creat(3, 3, ZERO_MATRIX); + psimat(psim, psi); + r0psi = mat_mul(psim, r0); + + *newchi = + rtan(sqrt(r0psi[2][0] * r0psi[2][0] + r0psi[2][1] * r0psi[2][1]), + r0psi[2][2]) * RD; + *newphi = rtan(-r0psi[2][1], -r0psi[2][0]) * RD; + *newom = om + rtan(-r0psi[1][2], r0psi[0][2]) * RD; mat_free(chim); mat_free(phim); mat_free(psim); mat_free(r0); mat_free(r0psi); } + /*-------------------------------------------------------------------- calculate Z1 = [PHI]TZ3 The T means transposed matrixes for the return calculation! ---------------------------------------------------------------------*/ -static void z1fromz2(double z1[3], MATRIX z2, - double phi){ +static void z1fromz2(double z1[3], MATRIX z2, double phi) +{ MATRIX phim, phimt, zz1; - phim = mat_creat(3,3,ZERO_MATRIX); + phim = mat_creat(3, 3, ZERO_MATRIX); phimat(phim, phi); phimt = mat_tran(phim); - zz1 = mat_mul(phimt,z2); - matrixToVector(zz1,z1); + zz1 = mat_mul(phimt, z2); + matrixToVector(zz1, z1); mat_free(phim); mat_free(phimt); mat_free(zz1); } + /*-------------------------------------------------------------------- calculate Z1 = [PHI]T*[CHI]T*Z3 The T means transposed matrixes for the return calculation! ---------------------------------------------------------------------*/ -static void z1fromz3(double z1[3], MATRIX z3, double chi, - double phi){ +static void z1fromz3(double z1[3], MATRIX z3, double chi, double phi) +{ MATRIX chim, chimt, z2; - chim = mat_creat(3,3,ZERO_MATRIX); + chim = mat_creat(3, 3, ZERO_MATRIX); chimat(chim, chi); chimt = mat_tran(chim); - z2 = mat_mul(chimt,z3); - z1fromz2(z1,z2,phi); + z2 = mat_mul(chimt, z3); + z1fromz2(z1, z2, phi); mat_free(chim); mat_free(chimt); mat_free(z2); } + /*-------------------------------------------------------------------- calculate Z1 = [PHI]T*[CHI]T*[OM]T*Z4 The T means transposed matrixes for the return calculation! ---------------------------------------------------------------------*/ static void z1fromz4(double z1[3], MATRIX z4, double om, double chi, - double phi){ + double phi) +{ MATRIX oma, oma2, z3; - oma = mat_creat(3,3,ZERO_MATRIX); + oma = mat_creat(3, 3, ZERO_MATRIX); phimat(oma, om); oma2 = mat_tran(oma); - z3 = mat_mul(oma2,z4); - z1fromz3(z1,z3,chi,phi); + z3 = mat_mul(oma2, z4); + z1fromz3(z1, z3, chi, phi); mat_free(oma); mat_free(oma2); mat_free(z3); } + /*---------------------------------------------------------------------*/ -void z1FromAngles(double lambda, double stt, double om, - double chi, double phi, double z1[3]){ +void z1FromAngles(double lambda, double stt, double om, + double chi, double phi, double z1[3]) +{ MATRIX z4; double th; - z4 = mat_creat(3,1,ZERO_MATRIX); - th = (stt/2.)/RD; - z4[0][0] = (2. * sin(th)*cos(th))/lambda; - z4[1][0] = (-2. *sin(th)*sin(th))/lambda; + z4 = mat_creat(3, 1, ZERO_MATRIX); + th = (stt / 2.) / RD; + z4[0][0] = (2. * sin(th) * cos(th)) / lambda; + z4[1][0] = (-2. * sin(th) * sin(th)) / lambda; z4[2][0] = .0; - z1fromz4(z1,z4,om,chi,phi); + z1fromz4(z1, z4, om, chi, phi); mat_free(z4); } + /*---------------------------------------------------------------------- Normal Beam geometry specific calculations. This means the reflection is expressed through the three angles omega, gamma (two theta detector) and @@ -443,247 +487,267 @@ void z1FromAngles(double lambda, double stt, double om, bisToNormalBeam was lifted from HKLGEN. -----------------------------------------------------------------------*/ -double sign(double a, double b){ - if(b >= .0){ +double sign(double a, double b) +{ + if (b >= .0) { return ABS(a); } else { return -ABS(a); } } -/*--------------------------------------------------------------------*/ -static void makeNull(double *gamma, double *om, double *nu){ - *gamma = .0; - *om = .0; - *nu = .0; -} -/*---------------------------------------------------------------------*/ -int z1mToNormalBeam(double lambda, MATRIX z1m, double *gamma, double *om, double *nu){ - MATRIX dum, znew; - double d, a, b, sint, theta, omdeg; - int status; - status = calcTheta(lambda,z1m,&d,&theta); - if(!status){ - makeNull(gamma,om,nu); - return status; - } - - /* Everything on omega axis is blind: test for this */ - a = sqrt(z1m[0][0] * z1m[0][0] + z1m[1][0] * z1m[1][0]); - if(ABS(a) < .0001) { - makeNull(gamma,om,nu); - return 0; - } - - sint = sin(theta/RD); - b = 2.*sint*sint/(lambda*a); - if(b >= 1.) { - makeNull(gamma,om,nu); - return 0; - } - a = -atan2(z1m[1][0], -z1m[0][0]); - b = -asin(b); - *om = a + b; - omdeg = *om*RD; - dum = mat_creat(3,3,ZERO_MATRIX); - phimat(dum,omdeg); - znew = mat_mul(dum,z1m); - if(znew[0][0] < 0) { - *om = *om -2.*atan2(-znew[0][0], -znew[1][0]); - omdeg = *om * RD; - } - b = (sign(180.,omdeg)+ omdeg)/360.; - b = sign(1,b)* floor(ABS(b)); - omdeg = omdeg - 360. * b ; - *nu = asin(lambda*z1m[2][0]); - *gamma = acos(cos(2.*(theta/RD)))/cos(*nu); - *om = omdeg; - *nu = *nu * RD; - *gamma = *gamma * RD; - mat_free(dum); - mat_free(znew); - return 1; +/*--------------------------------------------------------------------*/ +static void makeNull(double *gamma, double *om, double *nu) +{ + *gamma = .0; + *om = .0; + *nu = .0; } + +/*---------------------------------------------------------------------*/ +int z1mToNormalBeam(double lambda, MATRIX z1m, double *gamma, double *om, + double *nu) +{ + MATRIX dum, znew; + double d, a, b, sint, theta, omdeg; + int status; + + status = calcTheta(lambda, z1m, &d, &theta); + if (!status) { + makeNull(gamma, om, nu); + return status; + } + + /* Everything on omega axis is blind: test for this */ + a = sqrt(z1m[0][0] * z1m[0][0] + z1m[1][0] * z1m[1][0]); + if (ABS(a) < .0001) { + makeNull(gamma, om, nu); + return 0; + } + + sint = sin(theta / RD); + b = 2. * sint * sint / (lambda * a); + if (b >= 1.) { + makeNull(gamma, om, nu); + return 0; + } + a = -atan2(z1m[1][0], -z1m[0][0]); + b = -asin(b); + *om = a + b; + omdeg = *om * RD; + dum = mat_creat(3, 3, ZERO_MATRIX); + phimat(dum, omdeg); + znew = mat_mul(dum, z1m); + if (znew[0][0] < 0) { + *om = *om - 2. * atan2(-znew[0][0], -znew[1][0]); + omdeg = *om * RD; + } + b = (sign(180., omdeg) + omdeg) / 360.; + b = sign(1, b) * floor(ABS(b)); + omdeg = omdeg - 360. * b; + *nu = asin(lambda * z1m[2][0]); + *gamma = acos(cos(2. * (theta / RD))) / cos(*nu); + *om = omdeg; + *nu = *nu * RD; + *gamma = *gamma * RD; + mat_free(dum); + mat_free(znew); + return 1; +} + /*----------------------------------------------------------------------*/ int bisToNormalBeam(double twotheta, double omega, double chi, double phi, - double *omeganb, double *gamma, double *nu){ + double *omeganb, double *gamma, double *nu) +{ double tth, fom, fchi, fphi, sint, sinnu, del; - tth = twotheta/RD; - fom = omega/RD; - fchi = chi/RD; - fphi = phi/RD; - + tth = twotheta / RD; + fom = omega / RD; + fchi = chi / RD; + fphi = phi / RD; + /* nu calculation */ - sint = sin(tth/2.); - *nu = 2. * sin(fchi)*sint; - if(*nu > 1.){ + sint = sin(tth / 2.); + *nu = 2. * sin(fchi) * sint; + if (*nu > 1.) { return 0; } *nu = asin(*nu); - *nu = ABS(*nu)*sign(1.,fchi); + *nu = ABS(*nu) * sign(1., fchi); sinnu = sin(*nu); /* gamma calculation */ - *gamma = cos(tth)/cos(*nu); - if(ABS(*gamma) > 1.0){ + *gamma = cos(tth) / cos(*nu); + if (ABS(*gamma) > 1.0) { return 0; } *gamma = acos(*gamma); - *gamma = *gamma * sign(1.,tth); + *gamma = *gamma * sign(1., tth); /* omega normal beam */ - del = asin(sint/cos(fchi)); + del = asin(sint / cos(fchi)); *omeganb = del + fphi; - + *omeganb *= RD; *gamma *= RD; *nu *= RD; - if(ABS(*omeganb) > 180.){ - if(*omeganb < -180.){ + if (ABS(*omeganb) > 180.) { + if (*omeganb < -180.) { *omeganb += 360.; } - if(*omeganb > 180.){ + if (*omeganb > 180.) { *omeganb -= 360.; } } return 1; } + /* --------------------------------------------------------------------*/ static void z4FromNormalBeam(MATRIX z4, double lambda, double gamma, - double nu){ + double nu) +{ double gar, nur; - gar = gamma/RD; - nur = nu/RD; + gar = gamma / RD; + nur = nu / RD; /* - this is basically a conversion from polar coordinates to - x,y,z coordinates. However, sin and cos are exchanged in - comparison to textbook formulas for this conversion. But this - is only a shift of origin - */ - z4[0][0] = (sin(gar) * cos(nur))/lambda; - z4[1][0] = (cos (gar) * cos(nur) -1.)/lambda; - z4[2][0] = (sin(nur))/lambda; + this is basically a conversion from polar coordinates to + x,y,z coordinates. However, sin and cos are exchanged in + comparison to textbook formulas for this conversion. But this + is only a shift of origin + */ + z4[0][0] = (sin(gar) * cos(nur)) / lambda; + z4[1][0] = (cos(gar) * cos(nur) - 1.) / lambda; + z4[2][0] = (sin(nur)) / lambda; } + /*----------------------------------------------------------------------*/ -void z1FromNormalBeam(double lambda, double omega, double gamma, - double nu, double z1[3]){ +void z1FromNormalBeam(double lambda, double omega, double gamma, + double nu, double z1[3]) +{ MATRIX z4, omm, omt, z1m; - z4 = mat_creat(3,1,ZERO_MATRIX); - z4FromNormalBeam(z4,lambda, gamma,nu); - omm = mat_creat(3,3,ZERO_MATRIX); - phimat(omm,omega); + z4 = mat_creat(3, 1, ZERO_MATRIX); + z4FromNormalBeam(z4, lambda, gamma, nu); + omm = mat_creat(3, 3, ZERO_MATRIX); + phimat(omm, omega); omt = mat_tran(omm); - z1m = mat_mul(omt,z4); - matrixToVector(z1m,z1); + z1m = mat_mul(omt, z4); + matrixToVector(z1m, z1); mat_free(z4); mat_free(omm); mat_free(omt); mat_free(z1m); } + /*--------------------------------------------------------------------*/ -double circlify(double val){ - while(val > 360.){ +double circlify(double val) +{ + while (val > 360.) { val -= 360.; } - while(val < 0.){ - val += 360.; + while (val < 0.) { + val += 360.; } return val; } + /*----------------------------------------------------------------------*/ -void z1FromAllAngles(double lambda, double omega , double gamma, - double nu, double chi, double phi, double z1[3]){ +void z1FromAllAngles(double lambda, double omega, double gamma, + double nu, double chi, double phi, double z1[3]) +{ MATRIX z3; - z1FromNormalBeam(lambda, omega, gamma, nu, z1); + z1FromNormalBeam(lambda, omega, gamma, nu, z1); z3 = vectorToMatrix(z1); - z1fromz3(z1,z3,chi,phi); - mat_free(z3); + z1fromz3(z1, z3, chi, phi); + mat_free(z3); } + /*-----------------------------------------------------------------------*/ -int findAllowedBisecting(double lambda, MATRIX z1, double *fSet, - inRange testFunc, void *userData){ - int status, i, mask[4]; - double stt, om, chi, phi, psi, ompsi, chipsi, phipsi; - double fTest[4]; - - status = z1mToBisecting(lambda,z1, &stt, &om, &chi, &phi); - chi = circlify(chi); - phi = circlify(phi); - fSet[0] = stt; - fSet[1] = om; - fSet[2] = chi; - fSet[3] = phi; - if(status != 1) { - return 0; - } - - if(testFunc(userData, fSet, mask) == 1){ - return 1; - } - - for(psi = .0; psi < 360.; psi += .5){ - rotatePsi(om,chi,phi,psi,&ompsi,&chipsi,&phipsi); - fTest[0] = stt; - fTest[1] = ompsi; - fTest[2] = circlify(chipsi); - fTest[3] = circlify(phipsi); - status = testFunc(userData,fTest,mask); - if(status == 1){ - for(i = 0; i < 4; i++){ - fSet[i] = fTest[i]; - } - return 1; - } - /* - * if chi close to 0, or 180, try to wrap phi onto om - */ - if(ABS(fTest[2] - .0) < .1 || ABS(fTest[2] - 180.) < .1){ - fTest[1] -= fTest[3]; - fTest[3] = .0; - if(fTest[1] < 0.){ - fTest[1] += 360.; - } - if(fTest[1] > 360.0){ - fTest[1] -= 360.; - } - status = testFunc(userData,fTest,mask); - if(status == 1){ - for(i = 0; i < 4; i++){ - fSet[i] = fTest[i]; - } - return 1; - } - } - if(mask[0] == 0) { - /* - * useless: when two theta problem there is no solution - */ - return 0; - } - } +int findAllowedBisecting(double lambda, MATRIX z1, double *fSet, + inRange testFunc, void *userData) +{ + int status, i, mask[4]; + double stt, om, chi, phi, psi, ompsi, chipsi, phipsi; + double fTest[4]; + + status = z1mToBisecting(lambda, z1, &stt, &om, &chi, &phi); + chi = circlify(chi); + phi = circlify(phi); + fSet[0] = stt; + fSet[1] = om; + fSet[2] = chi; + fSet[3] = phi; + if (status != 1) { return 0; -} + } + + if (testFunc(userData, fSet, mask) == 1) { + return 1; + } + + for (psi = .0; psi < 360.; psi += .5) { + rotatePsi(om, chi, phi, psi, &ompsi, &chipsi, &phipsi); + fTest[0] = stt; + fTest[1] = ompsi; + fTest[2] = circlify(chipsi); + fTest[3] = circlify(phipsi); + status = testFunc(userData, fTest, mask); + if (status == 1) { + for (i = 0; i < 4; i++) { + fSet[i] = fTest[i]; + } + return 1; + } + /* + * if chi close to 0, or 180, try to wrap phi onto om + */ + if (ABS(fTest[2] - .0) < .1 || ABS(fTest[2] - 180.) < .1) { + fTest[1] -= fTest[3]; + fTest[3] = .0; + if (fTest[1] < 0.) { + fTest[1] += 360.; + } + if (fTest[1] > 360.0) { + fTest[1] -= 360.; + } + status = testFunc(userData, fTest, mask); + if (status == 1) { + for (i = 0; i < 4; i++) { + fSet[i] = fTest[i]; + } + return 1; + } + } + if (mask[0] == 0) { + /* + * useless: when two theta problem there is no solution + */ + return 0; + } + } + return 0; +} + /*------------------- a test program ------------------------------------*/ #ifdef TESTCODE -int main(int argc, char *argv[]){ +int main(int argc, char *argv[]) +{ psdDescription psd; - double gamma,nu, lambda, stt, om, chi, phi, z1[3], psi; + double gamma, nu, lambda, stt, om, chi, phi, z1[3], psi; double psiom, psichi, psiphi; double sttex, omex, chiex, phiex; int x, y, status, i; - MATRIX UB, UBinv, zz1,zz1b, hkl, hklback; + MATRIX UB, UBinv, zz1, zz1b, hkl, hklback; double gaex, omnbex, nuex, omeganb; /* initializations */ - UB = mat_creat(3,3,ZERO_MATRIX); + UB = mat_creat(3, 3, ZERO_MATRIX); UB[0][0] = 0.016169; UB[0][1] = 0.011969; UB[0][2] = 0.063195; @@ -695,7 +759,7 @@ int main(int argc, char *argv[]){ UB[2][2] = 0.006321; UBinv = mat_inv(UB); lambda = 1.179; - + /* test PSD code */ psd.xScale = .7; @@ -704,206 +768,176 @@ int main(int argc, char *argv[]){ psd.yZero = 64; psd.distance = 450.; psd.gamma = 43.; - psd.nu = 12.3; + psd.nu = 12.3; - det2pol(&psd,200, 111,&gamma, &nu); - pol2det(&psd,gamma,nu, &x, &y); - if(x == 200 && y == 111){ + det2pol(&psd, 200, 111, &gamma, &nu); + pol2det(&psd, gamma, nu, &x, &y); + if (x == 200 && y == 111) { printf("PSD test: OK\n"); } /* test bisecting calculations. The tests were taken from a system known to work - */ + */ status = 1; sttex = 30.58704; - omex = 15.293520; + omex = 15.293520; chiex = 129.053604; phiex = 134.191132; - hkl = mat_creat(3,1,ZERO_MATRIX); + hkl = mat_creat(3, 1, ZERO_MATRIX); hkl[0][0] = -2.; hkl[1][0] = -2.; hkl[2][0] = 4.; - zz1 = mat_mul(UB,hkl); - z1mToBisecting(lambda,zz1,&stt,&om,&chi,&phi); - if(ABS(stt - sttex) > .01 || - ABS(om - omex) > .01 || - ABS(chi - chiex) > .01 || - ABS(phi - phiex) > .01){ + zz1 = mat_mul(UB, hkl); + z1mToBisecting(lambda, zz1, &stt, &om, &chi, &phi); + if (ABS(stt - sttex) > .01 || + ABS(om - omex) > .01 || + ABS(chi - chiex) > .01 || ABS(phi - phiex) > .01) { printf("Bisecting Angles calculation FAILED!!!!!!!!!\n"); - printf("Expected: %12.4f %12.4f %12.4f %12.4f\n", sttex, omex, chiex,phiex); - printf("Got: %12.4f %12.4f %12.4f %12.4f\n", stt,om,chi,phi); + printf("Expected: %12.4f %12.4f %12.4f %12.4f\n", sttex, omex, chiex, + phiex); + printf("Got: %12.4f %12.4f %12.4f %12.4f\n", stt, om, chi, phi); status = 0; } - z1FromAngles(lambda,sttex,omex,chiex,phiex,z1); - for(i = 0; i < 3; i++){ - if(ABS(zz1[i][0] - z1[i]) > .0001){ - printf("Calculation of Z1 from Angles FAILED!!!!\n"); - printf("Expected: %8.4f %8.4f %8.4f\n", zz1[0][0], zz1[1][0], + z1FromAngles(lambda, sttex, omex, chiex, phiex, z1); + for (i = 0; i < 3; i++) { + if (ABS(zz1[i][0] - z1[i]) > .0001) { + printf("Calculation of Z1 from Angles FAILED!!!!\n"); + printf("Expected: %8.4f %8.4f %8.4f\n", zz1[0][0], zz1[1][0], zz1[2][0]); - printf("GOT: %8.4f %8.4f %8.4f\n",z1[0],z1[1],z1[2]); - status = 0; - } + printf("GOT: %8.4f %8.4f %8.4f\n", z1[0], z1[1], z1[2]); + status = 0; + } } - hklback = mat_mul(UBinv,zz1); - for(i = 0; i < 3; i++){ - if(ABS(hklback[i][0] - hkl[i][0]) > .0001){ + hklback = mat_mul(UBinv, zz1); + for (i = 0; i < 3; i++) { + if (ABS(hklback[i][0] - hkl[i][0]) > .0001) { printf("Back Calculation of HKL FAILED!!!!!!!!!\n"); - printf("Expected: %8.4f %8.4f %8.4f\n", hkl[0][0], hkl[1][0], + printf("Expected: %8.4f %8.4f %8.4f\n", hkl[0][0], hkl[1][0], hkl[2][0]); - printf("GOT: %8.4f %8.4f %8.4f\n",hklback[0][0], - hklback[1][0],hklback[2][0]); - status = 0; - } + printf("GOT: %8.4f %8.4f %8.4f\n", hklback[0][0], + hklback[1][0], hklback[2][0]); + status = 0; + } } - if(status == 1){ - printf("Bisecting test: OK\n"); + if (status == 1) { + printf("Bisecting test: OK\n"); } /* try turning in psi */ - rotatePsi(omex,chiex,phiex,30.,&psiom,&psichi,&psiphi); + rotatePsi(omex, chiex, phiex, 30., &psiom, &psichi, &psiphi); omex = 37.374298; chiex = 123.068192; phiex = 170.8209099; - if(ABS(psiom - omex) > .01 || - ABS(psichi - chiex) > .01 || - ABS(psiphi - phiex) > .01){ + if (ABS(psiom - omex) > .01 || + ABS(psichi - chiex) > .01 || ABS(psiphi - phiex) > .01) { printf("Psi Rotation test FAILED!!!!!!!!!\n"); - printf("Expected: %12.4f %12.4f %12.4f\n", omex, chiex,phiex); - printf("Got: %12.4f %12.4f %12.4f\n", psiom,psichi,psiphi); + printf("Expected: %12.4f %12.4f %12.4f\n", omex, chiex, phiex); + printf("Got: %12.4f %12.4f %12.4f\n", psiom, psichi, psiphi); status = 0; } else { printf("Psi rotation test: OK\n"); } /* - try to calculate a psi for a given omega offset - */ - omex = 15.293520; + try to calculate a psi for a given omega offset + */ + omex = 15.293520; chiex = 129.053604; phiex = 134.191132; - if(psiForOmegaOffset(zz1,-5.,chiex, phiex, &psi) != 1){ + if (psiForOmegaOffset(zz1, -5., chiex, phiex, &psi) != 1) { printf("Failed to calculate PSI for a Omega Offset\n"); } else { - rotatePsi(omex,chiex,phiex,psi,&psiom,&psichi,&psiphi); - if(ABS(psiom +5. - omex) > .5){ - printf("Failed to reach desired omega with calculated psi\n"); - printf("Expected: %12.4f Got: %12.4f PSI = %12.4f\n", omex -10., - psiom, psi); + rotatePsi(omex, chiex, phiex, psi, &psiom, &psichi, &psiphi); + if (ABS(psiom + 5. - omex) > .5) { + printf("Failed to reach desired omega with calculated psi\n"); + printf("Expected: %12.4f Got: %12.4f PSI = %12.4f\n", omex - 10., + psiom, psi); } else { printf("Psi for Omega Offset: OK\n"); } } /* - try to calculate angles with a omega offset - */ + try to calculate angles with a omega offset + */ omex = 10.29; chiex = 128.78; phiex = 126.24; sttex = 30.59; z1ToAnglesWithOffset(lambda, zz1, -5., &stt, &om, &chi, &phi); - if(ABS(stt - sttex) > .01 || - ABS(om - omex) > .01 || - ABS(chi - chiex) > .01 || - ABS(phi - phiex) > .01){ + if (ABS(stt - sttex) > .01 || + ABS(om - omex) > .01 || + ABS(chi - chiex) > .01 || ABS(phi - phiex) > .01) { printf("Angles calculation with Omega Offset FAILED!!!!!!!!!\n"); - printf("Expected: %12.4f %12.4f %12.4f %12.4f\n", sttex, omex, chiex,phiex); - printf("Got: %12.4f %12.4f %12.4f %12.4f\n", stt,om,chi,phi); + printf("Expected: %12.4f %12.4f %12.4f %12.4f\n", sttex, omex, chiex, + phiex); + printf("Got: %12.4f %12.4f %12.4f %12.4f\n", stt, om, chi, phi); status = 0; } else { printf("Angles with Omega Offset: OK\n"); } - + /* - test normal beam codes - */ + test normal beam codes + */ omex = 37.374298; gaex = 19.322; - omnbex = -21.057; - nuex = 24.186; - z1mToBisecting(lambda,zz1,&stt,&om,&chi,&phi); + omnbex = -21.057; + nuex = 24.186; + z1mToBisecting(lambda, zz1, &stt, &om, &chi, &phi); chi = 50.949; phi = -45.8088; - if(!bisToNormalBeam(stt,om,chi,phi, - &omeganb, &gamma, &nu)){ + if (!bisToNormalBeam(stt, om, chi, phi, &omeganb, &gamma, &nu)) { printf("Error on normal beam calculation!!\n"); } - if(ABS(omeganb - omnbex) > .01 || - ABS(gamma - gaex) > .01 || - ABS(nu - nuex) > .01){ + if (ABS(omeganb - omnbex) > .01 || + ABS(gamma - gaex) > .01 || ABS(nu - nuex) > .01) { printf("Normal Beam Calculation test FAILED!!!!!!!!!\n"); - printf("Expected: %12.4f %12.4f %12.4f\n", omnbex, gaex,nuex); - printf("Got: %12.4f %12.4f %12.4f\n", omeganb,gamma,nu); + printf("Expected: %12.4f %12.4f %12.4f\n", omnbex, gaex, nuex); + printf("Got: %12.4f %12.4f %12.4f\n", omeganb, gamma, nu); } else { printf("Normal Beam Angle Calculation: OK\n"); } - z1FromNormalBeam(lambda, omnbex, gaex, nuex,z1); + z1FromNormalBeam(lambda, omnbex, gaex, nuex, z1); status = 1; - for(i = 0; i < 3; i++){ - if(ABS(zz1[i][0] - z1[i]) > .0001){ - printf("Calculation of Z1 from Normal Beam Angles FAILED!!!!\n"); - printf("Expected: %8.4f %8.4f %8.4f\n", zz1[0][0], zz1[1][0], + for (i = 0; i < 3; i++) { + if (ABS(zz1[i][0] - z1[i]) > .0001) { + printf("Calculation of Z1 from Normal Beam Angles FAILED!!!!\n"); + printf("Expected: %8.4f %8.4f %8.4f\n", zz1[0][0], zz1[1][0], zz1[2][0]); - printf("GOT: %8.4f %8.4f %8.4f\n",z1[0],z1[1],z1[2]); - break; - status = 0; - } + printf("GOT: %8.4f %8.4f %8.4f\n", z1[0], z1[1], z1[2]); + break; + status = 0; + } } - if(status){ + if (status) { printf("Normal Beam Backwards Calculation: OK\n"); } /* - for interest: try to see how normal beam angles go if we rotate psi - */ + for interest: try to see how normal beam angles go if we rotate psi + */ /* - sttex = 30.58704; - om = 15.293520; - chi = 50.949; - phi = -45.8088; - printf(" PSI Omega Gamma Nu\n"); - for(i = 0; i < 36; i++){ - psi = i*10.; - rotatePsi(om,chi,phi,psi,&psiom,&psichi,&psiphi); - status = bisToNormalBeam(sttex,psiom,psichi,psiphi,&omeganb, &gamma, &nu); - if(status){ - printf("%12.4f%12.4f%12.4f%12.4f\n",psi,omeganb,gamma,nu); - } - } - */ + sttex = 30.58704; + om = 15.293520; + chi = 50.949; + phi = -45.8088; + printf(" PSI Omega Gamma Nu\n"); + for(i = 0; i < 36; i++){ + psi = i*10.; + rotatePsi(om,chi,phi,psi,&psiom,&psichi,&psiphi); + status = bisToNormalBeam(sttex,psiom,psichi,psiphi,&omeganb, &gamma, &nu); + if(status){ + printf("%12.4f%12.4f%12.4f%12.4f\n",psi,omeganb,gamma,nu); + } + } + */ } #endif - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/fourlib.h b/fourlib.h index ad3c50fa..37bcc0b0 100644 --- a/fourlib.h +++ b/fourlib.h @@ -34,29 +34,31 @@ functions for any further work. A lot of information about the detector is required for this transformation which is held in the datastruture as defined below - ----------------------------------------------------------------------*/ + ----------------------------------------------------------------------*/ -typedef struct{ - double xScale; /* scale factor pixel --> mm for x */ - double yScale; /* scale factor pixel --> mm for y */ - double distance; /* distance sample detector in mm */ - double gamma; /* gamma == two theta position of the detector */ - double nu; /* tilt angle of the detector */ - int xZero; /* x pixel coordinate of the zero point of the detector */ - int yZero; /* y pixel coordinate of the zero point of the detector */ +typedef struct { + double xScale; /* scale factor pixel --> mm for x */ + double yScale; /* scale factor pixel --> mm for y */ + double distance; /* distance sample detector in mm */ + double gamma; /* gamma == two theta position of the detector */ + double nu; /* tilt angle of the detector */ + int xZero; /* x pixel coordinate of the zero point of the detector */ + int yZero; /* y pixel coordinate of the zero point of the detector */ } psdDescription; /** * det2pol converts the pixel coordinates x and y on the detector described * by psd to polar coordinates gamma and nu. */ -void det2pol(psdDescription *psd, int x, int y, double *gamma, double *nu); +void det2pol(psdDescription * psd, int x, int y, double *gamma, + double *nu); /** * pol2det converts the polar coordinates gamma and nu to detector coordinates * x and y on the detector described psd */ -void pol2det(psdDescription *psd, double gamma, double nu, int *x, int *y); +void pol2det(psdDescription * psd, double gamma, double nu, int *x, + int *y); /*------------------------------------------------------------------------ calculation of four circle diffractometer angles stt, om, chi and phi @@ -75,26 +77,26 @@ void pol2det(psdDescription *psd, double gamma, double nu, int *x, int *y); * were invalid. The m version acts upon a matrix. */ int z1ToBisecting(double lambda, double z1[3], double *stt, double *om, - double *chi, double *phi); + double *chi, double *phi); int z1mToBisecting(double lambda, MATRIX z1, double *stt, double *om, - double *chi, double *phi); + double *chi, double *phi); /** * calculates diffraction angles to put z1 into a detector with a given * offset in omega against the bisecting position. Useful for tweaking * if omega is restricted. */ -int z1ToAnglesWithOffset(double lambda, MATRIX z1,double omOffset, - double *stt, double *om, +int z1ToAnglesWithOffset(double lambda, MATRIX z1, double omOffset, + double *stt, double *om, double *chi, double *phi); - + /** * calculates a PSI for a given offset in omega from the bisecting * position. This can be useful for tweaking reflections to be * measurable at omega restricted diffractometers. -*/ -int psiForOmegaOffset(MATRIX z1, double omOffset, - double chi, double phi, double *psi); +*/ +int psiForOmegaOffset(MATRIX z1, double omOffset, + double chi, double phi, double *psi); /** * calculate new setting angles for a psi rotation. Input are the angles @@ -110,8 +112,8 @@ void rotatePsi(double om, double chi, double phi, double psi, * a bissecting position, however it is required that the angles describe a * reflection measured in the horizontal plane. */ -void z1FromAngles(double lambda, double stt, double om, - double chi, double phi, double z1[3]); +void z1FromAngles(double lambda, double stt, double om, + double chi, double phi, double z1[3]); /*----------------------------------------------------------------------- Normal beam calculations. Here the diffraction vector is expressed as polar angles gamma and nu and omega. @@ -121,24 +123,25 @@ void z1FromAngles(double lambda, double stt, double om, * circle angles twotheta, omega, chi and phi. */ int bisToNormalBeam(double twotheta, double omega, double chi, double phi, - double *omeganb, double *gamma, double *nu); + double *omeganb, double *gamma, double *nu); /** * calculate normal beam angles from z1 */ -int z1mToNormalBeam(double lambda, MATRIX z1, double *gamma, double *om, double *nu); +int z1mToNormalBeam(double lambda, MATRIX z1, double *gamma, double *om, + double *nu); /** * calculate the vector z1 from the normal beam angles omega, gamma and nu. * chi and phi either do not exist or are 0. */ -void z1FromNormalBeam(double lambda, double omega, double gamma, - double nu, double z1[3]); +void z1FromNormalBeam(double lambda, double omega, double gamma, + double nu, double z1[3]); /** * calculate z1 from four circle angles plus gamma, nu */ -void z1FromAllAngles(double lambda, double omega, double gamma, - double nu, double chi, double phi, double z1[3]); +void z1FromAllAngles(double lambda, double omega, double gamma, + double nu, double chi, double phi, double z1[3]); /*------------------------------------------------------------------------ Utility -------------------------------------------------------------------------*/ @@ -186,17 +189,9 @@ int calcTheta(double lambda, MATRIX z1, double *d, double *theta); * @param userData A user specified pointer to some data which may be needed * in testing the range. * @return 0 on failure, 1 on success. - */ -typedef int (*inRange)(void *userData, double dSet[4], int mask[4]); -int findAllowedBisecting(double lambda, MATRIX z1, double fSet[4], - inRange testFunc, void *userData); - -#endif - - - - - - - + */ +typedef int (*inRange) (void *userData, double dSet[4], int mask[4]); +int findAllowedBisecting(double lambda, MATRIX z1, double fSet[4], + inRange testFunc, void *userData); +#endif diff --git a/fourmess.c b/fourmess.c index 03388aa9..98363264 100644 --- a/fourmess.c +++ b/fourmess.c @@ -35,744 +35,797 @@ extern void SNXFormatTime(char *pBueffel, int iLen); /*---------------------------------------------------------------------------*/ typedef struct { - FILE *profFile; /* file with reflection profiles, ccl */ - FILE *hklFile; /* file with integrated intensities */ - int stepTable; /* table with the scan parameters */ - char *currentFileRoot; - pSICSOBJ messList; - pHdb currentRefl; /* the current reflection being measured */ - int count; - pScanData pScanner; - int masterCount; /* the number of master reflection as craeted by indgen */ -}FourMess, *pFourMess; + FILE *profFile; /* file with reflection profiles, ccl */ + FILE *hklFile; /* file with integrated intensities */ + int stepTable; /* table with the scan parameters */ + char *currentFileRoot; + pSICSOBJ messList; + pHdb currentRefl; /* the current reflection being measured */ + int count; + pScanData pScanner; + int masterCount; /* the number of master reflection as craeted by indgen */ +} FourMess, *pFourMess; /*---------------------------------------------------------------------------*/ -static void KillFourMess(void *data){ - pFourMess priv = (pFourMess)data; - if(priv == NULL){ - return; - } - if(priv->profFile != NULL){ - fclose(priv->profFile); - } - if(priv->hklFile != NULL){ - fclose(priv->hklFile); - } - if(priv->currentFileRoot != NULL){ - free(priv->currentFileRoot); - } - if(priv->stepTable >= 0){ - DeleteFourCircleTable(priv->stepTable); - } - free(priv); +static void KillFourMess(void *data) +{ + pFourMess priv = (pFourMess) data; + if (priv == NULL) { + return; + } + if (priv->profFile != NULL) { + fclose(priv->profFile); + } + if (priv->hklFile != NULL) { + fclose(priv->hklFile); + } + if (priv->currentFileRoot != NULL) { + free(priv->currentFileRoot); + } + if (priv->stepTable >= 0) { + DeleteFourCircleTable(priv->stepTable); + } + free(priv); } -/*----------------------------------------------------------------------------*/ -static int FourMessAction(SConnection *pCon, SicsInterp *pSics, - void *data, int argc, char *argv[]){ - pFourMess priv = NULL; - pSICSOBJ self = (pSICSOBJ)data; - int err, status; - - assert(self != NULL); - priv = self->pPrivate; - assert(priv != NULL); - - if(argc < 2){ - SCWrite(pCon,"ERROR: insufficient number of arguments to fmess", - eError); - return 0; - } - - if(strcmp(argv[1],"table") == 0){ - return HandleFourCircleCommands(&priv->stepTable,pCon, - argc,argv,&err); - } - - status = InvokeSICSOBJ(pCon,pSics,data,argc,argv); - if(status < 0){ - SCPrintf(pCon,eError, "ERROR: %s no subcommand or parameter", - argv[1]); - return 0; - } - return status; -} -/*-----------------------------------------------------------------------------*/ -static int FourMessClose(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pFourMess priv = NULL; - priv = self->pPrivate; - if(priv->hklFile != NULL){ - fclose(priv->hklFile); - priv->hklFile = NULL; - } - if(priv->profFile != NULL){ - fclose(priv->profFile); - priv->profFile = NULL; - } - return 1; -} -/*-----------------------------------------------------------------------------*/ -static int FourMessStart(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pFourMess priv = NULL; - char pFilename[512], pRoot[512]; - char pBueffel[1024]; - double lambda; - const double *dUB; - pSicsVariable pVar = NULL; - char *pFile = NULL, *pPtr; - FILE *temp = NULL; - pHdb node; - hdbValue v; - - assert(self); - assert(pCon); - - priv = self->pPrivate; - - if(nPar < 1){ - SCWrite(pCon,"ERROR: need file name parameter to start",eError); - return 0; - } - - /* close open files if so */ - if(priv->hklFile != NULL){ - FourMessClose(self,pCon,commandNode,par,nPar); - } - - /* create filename root */ - GetHipadabaPar(par[0],&v, pCon); - pFile = strdup(v.v.text); - pPtr = strrchr(pFile,(int)'.'); - pPtr++; - *pPtr = '\0'; - if(priv->currentFileRoot != NULL){ - free(priv->currentFileRoot); - } - priv->currentFileRoot = strdup(pFile); - free(pFile); - strncpy(pRoot,priv->currentFileRoot,511); - - - /* open the reflection file */ - sprintf(pBueffel,"Writing to %s.ccl, .rfl",pRoot); - SCWrite(pCon,pBueffel,eValue); - strcpy(pFilename,pRoot); - strcat(pFilename,"ccl"); - priv->profFile = fopen(pFilename,"w"); - if(!priv->profFile){ - sprintf(pBueffel,"ERROR: SERIOUS TROUBLE: cannot open %s!", - pFilename); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,eAbortBatch); - return 0; - } - - node = GetHipadabaNode(self->objectNode,"template"); - assert(node != NULL); - GetHipadabaPar(node,&v,pCon); - temp = fopen(v.v.text,"r"); - if(temp == NULL) - { - SCWrite(pCon,"ERROR: failed to open header template",eError); - } - if(temp != NULL ) - { - WriteTemplate(priv->profFile, temp, pFilename, NULL, - pCon, pServ->pSics); - fclose(temp); - } - - /* open hkl-data file */ - strcpy(pFilename,pRoot); - strcat(pFilename,"rfl"); - priv->hklFile = fopen(pFilename,"w"); - if(!priv->hklFile){ - sprintf(pBueffel,"ERROR: SERIOUS TROUBLE: cannot open %s!", - pFilename); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,eAbortBatch); - return 0; - } - fputs(pFilename,priv->hklFile); - fputs("\n",priv->hklFile); - - /* write some header data */ - SNXFormatTime(pBueffel,1024); - fprintf(priv->hklFile,"filetime = %s\n",pBueffel); - lambda = SXGetLambda(); - fprintf(priv->hklFile,"lambda = %f Angstroem\n",lambda); - dUB = SXGetUB(); - fprintf(priv->hklFile, - "UB = %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f\n", - dUB[0], dUB[1],dUB[2],dUB[3],dUB[4],dUB[5],dUB[6],dUB[7],dUB[8]); - - /* write sample & user info */ - strcpy(pBueffel,"CCL, Instr=TRICS, "); - pVar = FindVariable(pServ->pSics,"sample"); - if(pVar){ - fprintf(priv->hklFile,"sample = %s\n",pVar->text); - } - pVar = FindVariable(pServ->pSics,"user"); - if(pVar){ - fprintf(priv->hklFile,"user = %s \n",pVar->text); - } - priv->count = 0; - return 1; -} /*----------------------------------------------------------------------------*/ -static int FourMessScanPar(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pFourMess priv = self->pPrivate; - char *scanvar; - double stt, dVal; - int np, preset; - pDynString data; - - assert(priv != NULL); - if(nPar < 1){ - SCWrite(pCon,"ERROR: need two theta parameter to scanpar", eError); - return 0; - } - stt = par[0]->value.v.doubleValue; - - scanvar = GetFourCircleScanVar(priv->stepTable,stt); - dVal = GetFourCircleStep(priv->stepTable,stt); - np = GetFourCircleScanNP(priv->stepTable,stt); - preset = GetFourCirclePreset(priv->stepTable,stt); - if(strcmp(scanvar,"NOT FOUND") == 0){ - SCPrintf(pCon,eValue,"%s,%f,%d,%d","om", dVal,np,preset); - } else { - SCPrintf(pCon,eValue,"%s,%f,%d,%d",scanvar,dVal,np,preset); - } - return 1; +static int FourMessAction(SConnection * pCon, SicsInterp * pSics, + void *data, int argc, char *argv[]) +{ + pFourMess priv = NULL; + pSICSOBJ self = (pSICSOBJ) data; + int err, status; + + assert(self != NULL); + priv = self->pPrivate; + assert(priv != NULL); + + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient number of arguments to fmess", + eError); + return 0; + } + + if (strcmp(argv[1], "table") == 0) { + return HandleFourCircleCommands(&priv->stepTable, pCon, + argc, argv, &err); + } + + status = InvokeSICSOBJ(pCon, pSics, data, argc, argv); + if (status < 0) { + SCPrintf(pCon, eError, "ERROR: %s no subcommand or parameter", + argv[1]); + return 0; + } + return status; } + +/*-----------------------------------------------------------------------------*/ +static int FourMessClose(pSICSOBJ self, SConnection * pCon, + pHdb commandNode, pHdb par[], int nPar) +{ + pFourMess priv = NULL; + + priv = self->pPrivate; + if (priv->hklFile != NULL) { + fclose(priv->hklFile); + priv->hklFile = NULL; + } + if (priv->profFile != NULL) { + fclose(priv->profFile); + priv->profFile = NULL; + } + return 1; +} + +/*-----------------------------------------------------------------------------*/ +static int FourMessStart(pSICSOBJ self, SConnection * pCon, + pHdb commandNode, pHdb par[], int nPar) +{ + pFourMess priv = NULL; + char pFilename[512], pRoot[512]; + char pBueffel[1024]; + double lambda; + const double *dUB; + pSicsVariable pVar = NULL; + char *pFile = NULL, *pPtr; + FILE *temp = NULL; + pHdb node; + hdbValue v; + + assert(self); + assert(pCon); + + priv = self->pPrivate; + + if (nPar < 1) { + SCWrite(pCon, "ERROR: need file name parameter to start", eError); + return 0; + } + + /* close open files if so */ + if (priv->hklFile != NULL) { + FourMessClose(self, pCon, commandNode, par, nPar); + } + + /* create filename root */ + GetHipadabaPar(par[0], &v, pCon); + pFile = strdup(v.v.text); + pPtr = strrchr(pFile, (int) '.'); + pPtr++; + *pPtr = '\0'; + if (priv->currentFileRoot != NULL) { + free(priv->currentFileRoot); + } + priv->currentFileRoot = strdup(pFile); + free(pFile); + strncpy(pRoot, priv->currentFileRoot, 511); + + + /* open the reflection file */ + sprintf(pBueffel, "Writing to %s.ccl, .rfl", pRoot); + SCWrite(pCon, pBueffel, eValue); + strcpy(pFilename, pRoot); + strcat(pFilename, "ccl"); + priv->profFile = fopen(pFilename, "w"); + if (!priv->profFile) { + sprintf(pBueffel, "ERROR: SERIOUS TROUBLE: cannot open %s!", + pFilename); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, eAbortBatch); + return 0; + } + + node = GetHipadabaNode(self->objectNode, "template"); + assert(node != NULL); + GetHipadabaPar(node, &v, pCon); + temp = fopen(v.v.text, "r"); + if (temp == NULL) { + SCWrite(pCon, "ERROR: failed to open header template", eError); + } + if (temp != NULL) { + WriteTemplate(priv->profFile, temp, pFilename, NULL, + pCon, pServ->pSics); + fclose(temp); + } + + /* open hkl-data file */ + strcpy(pFilename, pRoot); + strcat(pFilename, "rfl"); + priv->hklFile = fopen(pFilename, "w"); + if (!priv->hklFile) { + sprintf(pBueffel, "ERROR: SERIOUS TROUBLE: cannot open %s!", + pFilename); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, eAbortBatch); + return 0; + } + fputs(pFilename, priv->hklFile); + fputs("\n", priv->hklFile); + + /* write some header data */ + SNXFormatTime(pBueffel, 1024); + fprintf(priv->hklFile, "filetime = %s\n", pBueffel); + lambda = SXGetLambda(); + fprintf(priv->hklFile, "lambda = %f Angstroem\n", lambda); + dUB = SXGetUB(); + fprintf(priv->hklFile, + "UB = %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f\n", + dUB[0], dUB[1], dUB[2], dUB[3], dUB[4], dUB[5], dUB[6], dUB[7], + dUB[8]); + + /* write sample & user info */ + strcpy(pBueffel, "CCL, Instr=TRICS, "); + pVar = FindVariable(pServ->pSics, "sample"); + if (pVar) { + fprintf(priv->hklFile, "sample = %s\n", pVar->text); + } + pVar = FindVariable(pServ->pSics, "user"); + if (pVar) { + fprintf(priv->hklFile, "user = %s \n", pVar->text); + } + priv->count = 0; + return 1; +} + +/*----------------------------------------------------------------------------*/ +static int FourMessScanPar(pSICSOBJ self, SConnection * pCon, + pHdb commandNode, pHdb par[], int nPar) +{ + pFourMess priv = self->pPrivate; + char *scanvar; + double stt, dVal; + int np, preset; + pDynString data; + + assert(priv != NULL); + if (nPar < 1) { + SCWrite(pCon, "ERROR: need two theta parameter to scanpar", eError); + return 0; + } + stt = par[0]->value.v.doubleValue; + + scanvar = GetFourCircleScanVar(priv->stepTable, stt); + dVal = GetFourCircleStep(priv->stepTable, stt); + np = GetFourCircleScanNP(priv->stepTable, stt); + preset = GetFourCirclePreset(priv->stepTable, stt); + if (strcmp(scanvar, "NOT FOUND") == 0) { + SCPrintf(pCon, eValue, "%s,%f,%d,%d", "om", dVal, np, preset); + } else { + SCPrintf(pCon, eValue, "%s,%f,%d,%d", scanvar, dVal, np, preset); + } + return 1; +} + /*----------------------------------------------------------------------------*/ static hdbCallbackReturn SetScannerCB(pHdb node, void *userData, - pHdbMessage mm){ - pHdbDataMessage set = NULL; - pFourMess priv = (pFourMess)userData; - SConnection *pCon = NULL; - pScanData old; - - if((set = GetHdbSetMessage(mm)) != NULL){ - old = priv->pScanner; - priv->pScanner = FindCommandData(pServ->pSics,set->v->v.text,"ScanObject"); - if(priv->pScanner == NULL){ - priv->pScanner = old; - pCon = set->callData; - if(pCon != NULL){ - SCWrite(pCon,"ERROR: scan object not found", eError); - } - return hdbAbort; - } - } - return hdbContinue; -} -/*---------------------------------------------------------------------------*/ -static double getProtonAverage(pFourMess self){ - int np, i; - long *lData = NULL, lSum = 0; + pHdbMessage mm) +{ + pHdbDataMessage set = NULL; + pFourMess priv = (pFourMess) userData; + SConnection *pCon = NULL; + pScanData old; - np = GetScanNP(self->pScanner); - lData = (long *)malloc((np+1)*sizeof(long)); - if(lData == NULL || np == 0){ - return 0.; + if ((set = GetHdbSetMessage(mm)) != NULL) { + old = priv->pScanner; + priv->pScanner = + FindCommandData(pServ->pSics, set->v->v.text, "ScanObject"); + if (priv->pScanner == NULL) { + priv->pScanner = old; + pCon = set->callData; + if (pCon != NULL) { + SCWrite(pCon, "ERROR: scan object not found", eError); + } + return hdbAbort; } - memset(lData,0,(np+1)*sizeof(long)); - GetScanMonitor(self->pScanner,2,lData, np); - for(i = 0; i < np; i++){ - lSum += lData[i]; - } - free(lData); - return (double)lSum/(double)np; + } + return hdbContinue; } + /*---------------------------------------------------------------------------*/ -static int FourMessStoreIntern(pSICSOBJ self, SConnection *pCon, - double fHkl[3], double fPosition[4]){ - pFourMess priv = self->pPrivate; - float fSum, fSigma, fTemp, fStep, fPreset; - int i, iLF, iRet, iNP,ii; - long *lCounts = NULL; - pEVControl pEva = NULL; - pDummy pPtr = NULL; - pIDrivable pDriv = NULL; - char pBueffel[512], pTime[512], pNum[10]; - double prot; - - if(priv->pScanner == NULL){ - SCWrite(pCon,"ERROR: store: scan not configured", eLogError); - return 0; - } +static double getProtonAverage(pFourMess self) +{ + int np, i; + long *lData = NULL, lSum = 0; - if(priv->hklFile == NULL){ - SCWrite(pCon,"ERROR: store: no files open", eLogError); - return 0; - } - - /* get necessary data */ - fSum = 0.; - fSigma = 0.; - iRet = ScanIntegrate(priv->pScanner,&fSum, &fSigma); - if(iRet != 1){ - switch(iRet){ - case INTEGLEFT: - sprintf(pBueffel, - "WARNING: integration failed --> no left side to: %f %f %f", - fHkl[0], fHkl[1],fHkl[2]); - break; - case INTEGRIGHT: - sprintf(pBueffel, - "WARNING: integration failed -->no right side to: %f %f %f", - fHkl[0], fHkl[1],fHkl[2]); - break; - case INTEGNOPEAK: - sprintf(pBueffel, - "WARNING: integration failed -->no peak found: %f %f %f", - fHkl[0], fHkl[1],fHkl[2]); - break; - case INTEGFUNNYBACK: - sprintf(pBueffel, - "WARNING: integration problem, asymmetric background: %f %f %f", - fHkl[0], fHkl[1],fHkl[2]); - break; - } - SCWrite(pCon,pBueffel,eLog); - } - iNP = GetScanNP(priv->pScanner); - lCounts = malloc(iNP*sizeof(long)); - if(lCounts == NULL){ - SCWrite(pCon,"ERROR: out of memory in store", eLogError); - return 0; - } - GetScanCounts(priv->pScanner,lCounts,iNP); - - /* write it */ - if(priv->profFile){ - fprintf(priv->profFile,"%4d %7.3f %7.3f %7.3f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", - priv->count, fHkl[0],fHkl[1],fHkl[2], - fPosition[0], fPosition[1], - fPosition[2], fPosition[3], - fSum,fSigma); - } - if(priv->hklFile){ - fprintf(priv->hklFile,"%5d %6.2f %6.2f %6.2f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", - priv->count, fHkl[0],fHkl[1],fHkl[2], - fPosition[0], fPosition[1], - fPosition[2],fPosition[3], - fSum,fSigma); - } - sprintf(pBueffel,"%5d %6.2f %6.2f %6.2f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", - priv->count, fHkl[0],fHkl[1],fHkl[2], - fPosition[0], fPosition[1], - fPosition[2], fPosition[3], - fSum,fSigma); - SCWrite(pCon,pBueffel,eLog); - - /* get temperature */ - fTemp = -777.77; - pEva = (pEVControl)FindCommandData(pServ->pSics,"temperature", - "Environment Controller"); - if(pEva == NULL){ - pPtr = (pDummy)FindCommandData(pServ->pSics,"temperature", - "RemObject"); - if(pPtr != NULL){ - pDriv = pPtr->pDescriptor->GetInterface(pPtr,DRIVEID); - if(pDriv != NULL){ - fTemp = pDriv->GetValue(pPtr,pCon); - } - } - } else { - iRet = EVCGetPos(pEva, pCon,&fTemp); - } - - /* write profile */ - if(priv->profFile){ - /* collect data */ - SNXFormatTime(pBueffel,512); - GetScanVarStep(priv->pScanner,0,&fStep); - fPreset = GetScanPreset(priv->pScanner); - prot = getProtonAverage(priv); - fprintf(priv->profFile,"%3d %7.4f %9.0f %7.3f %12f %s\n",iNP,fStep, - fPreset,fTemp,prot, pBueffel); - for(i = 0; i < iNP; i++){ - for(ii = 0; ii < 10 && i < iNP; ii++){ - fprintf(priv->profFile," %7ld",lCounts[i]); - iLF = 1; - i++; - } - fprintf(priv->profFile,"\n"); - i--; - iLF = 0; - } - if(iLF){ - fprintf(priv->profFile,"\n"); - } - fflush(priv->profFile); - } - - strcpy(pTime,pBueffel); - sprintf(pBueffel,"%3d%8.4f%10.0f%8.3f %s\n",iNP,fStep, - fPreset,fTemp,pTime); - SCWrite(pCon,pBueffel,eLog); - pBueffel[0] = '\0'; - for(i = 0; i < iNP; i++){ - for(ii = 0; ii < 10 && i < iNP; ii++){ - sprintf(pNum," %6ld",lCounts[i]); - strcat(pBueffel,pNum); - iLF = 1; - i++; - } - SCWrite(pCon,pBueffel,eLog); - pBueffel[0] = '\0'; - i--; - iLF = 0; - } - if(iLF){ - SCWrite(pCon,pBueffel,eLog); - } - free(lCounts); - return 1; - + np = GetScanNP(self->pScanner); + lData = (long *) malloc((np + 1) * sizeof(long)); + if (lData == NULL || np == 0) { + return 0.; + } + memset(lData, 0, (np + 1) * sizeof(long)); + GetScanMonitor(self->pScanner, 2, lData, np); + for (i = 0; i < np; i++) { + lSum += lData[i]; + } + free(lData); + return (double) lSum / (double) np; } + +/*---------------------------------------------------------------------------*/ +static int FourMessStoreIntern(pSICSOBJ self, SConnection * pCon, + double fHkl[3], double fPosition[4]) +{ + pFourMess priv = self->pPrivate; + float fSum, fSigma, fTemp, fStep, fPreset; + int i, iLF, iRet, iNP, ii; + long *lCounts = NULL; + pEVControl pEva = NULL; + pDummy pPtr = NULL; + pIDrivable pDriv = NULL; + char pBueffel[512], pTime[512], pNum[10]; + double prot; + + if (priv->pScanner == NULL) { + SCWrite(pCon, "ERROR: store: scan not configured", eLogError); + return 0; + } + + if (priv->hklFile == NULL) { + SCWrite(pCon, "ERROR: store: no files open", eLogError); + return 0; + } + + /* get necessary data */ + fSum = 0.; + fSigma = 0.; + iRet = ScanIntegrate(priv->pScanner, &fSum, &fSigma); + if (iRet != 1) { + switch (iRet) { + case INTEGLEFT: + sprintf(pBueffel, + "WARNING: integration failed --> no left side to: %f %f %f", + fHkl[0], fHkl[1], fHkl[2]); + break; + case INTEGRIGHT: + sprintf(pBueffel, + "WARNING: integration failed -->no right side to: %f %f %f", + fHkl[0], fHkl[1], fHkl[2]); + break; + case INTEGNOPEAK: + sprintf(pBueffel, + "WARNING: integration failed -->no peak found: %f %f %f", + fHkl[0], fHkl[1], fHkl[2]); + break; + case INTEGFUNNYBACK: + sprintf(pBueffel, + "WARNING: integration problem, asymmetric background: %f %f %f", + fHkl[0], fHkl[1], fHkl[2]); + break; + } + SCWrite(pCon, pBueffel, eLog); + } + iNP = GetScanNP(priv->pScanner); + lCounts = malloc(iNP * sizeof(long)); + if (lCounts == NULL) { + SCWrite(pCon, "ERROR: out of memory in store", eLogError); + return 0; + } + GetScanCounts(priv->pScanner, lCounts, iNP); + + /* write it */ + if (priv->profFile) { + fprintf(priv->profFile, + "%4d %7.3f %7.3f %7.3f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", + priv->count, fHkl[0], fHkl[1], fHkl[2], fPosition[0], + fPosition[1], fPosition[2], fPosition[3], fSum, fSigma); + } + if (priv->hklFile) { + fprintf(priv->hklFile, + "%5d %6.2f %6.2f %6.2f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", + priv->count, fHkl[0], fHkl[1], fHkl[2], fPosition[0], + fPosition[1], fPosition[2], fPosition[3], fSum, fSigma); + } + sprintf(pBueffel, + "%5d %6.2f %6.2f %6.2f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", + priv->count, fHkl[0], fHkl[1], fHkl[2], fPosition[0], + fPosition[1], fPosition[2], fPosition[3], fSum, fSigma); + SCWrite(pCon, pBueffel, eLog); + + /* get temperature */ + fTemp = -777.77; + pEva = (pEVControl) FindCommandData(pServ->pSics, "temperature", + "Environment Controller"); + if (pEva == NULL) { + pPtr = (pDummy) FindCommandData(pServ->pSics, "temperature", + "RemObject"); + if (pPtr != NULL) { + pDriv = pPtr->pDescriptor->GetInterface(pPtr, DRIVEID); + if (pDriv != NULL) { + fTemp = pDriv->GetValue(pPtr, pCon); + } + } + } else { + iRet = EVCGetPos(pEva, pCon, &fTemp); + } + + /* write profile */ + if (priv->profFile) { + /* collect data */ + SNXFormatTime(pBueffel, 512); + GetScanVarStep(priv->pScanner, 0, &fStep); + fPreset = GetScanPreset(priv->pScanner); + prot = getProtonAverage(priv); + fprintf(priv->profFile, "%3d %7.4f %9.0f %7.3f %12f %s\n", iNP, fStep, + fPreset, fTemp, prot, pBueffel); + for (i = 0; i < iNP; i++) { + for (ii = 0; ii < 10 && i < iNP; ii++) { + fprintf(priv->profFile, " %7ld", lCounts[i]); + iLF = 1; + i++; + } + fprintf(priv->profFile, "\n"); + i--; + iLF = 0; + } + if (iLF) { + fprintf(priv->profFile, "\n"); + } + fflush(priv->profFile); + } + + strcpy(pTime, pBueffel); + sprintf(pBueffel, "%3d%8.4f%10.0f%8.3f %s\n", iNP, fStep, + fPreset, fTemp, pTime); + SCWrite(pCon, pBueffel, eLog); + pBueffel[0] = '\0'; + for (i = 0; i < iNP; i++) { + for (ii = 0; ii < 10 && i < iNP; ii++) { + sprintf(pNum, " %6ld", lCounts[i]); + strcat(pBueffel, pNum); + iLF = 1; + i++; + } + SCWrite(pCon, pBueffel, eLog); + pBueffel[0] = '\0'; + i--; + iLF = 0; + } + if (iLF) { + SCWrite(pCon, pBueffel, eLog); + } + free(lCounts); + return 1; + +} + /*----------------------------------------------------------------------------*/ -static int FourMessStore(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - double fHkl[3], fPosition[4]; - int i; - - if(nPar < 7) { - SCWrite(pCon,"ERROR: not enough arguments for store",eError); - return 0; - } - - /* load hkl */ - for(i = 0; i < 3; i++){ - fHkl[i] = par[i]->value.v.doubleValue; - } - - /* load positions */ - for(i = 0; i < 4; i++){ - fPosition[i] = par[i+3]->value.v.doubleValue; - } - - return FourMessStoreIntern(self, pCon,fHkl, fPosition); +static int FourMessStore(pSICSOBJ self, SConnection * pCon, + pHdb commandNode, pHdb par[], int nPar) +{ + double fHkl[3], fPosition[4]; + int i; + + if (nPar < 7) { + SCWrite(pCon, "ERROR: not enough arguments for store", eError); + return 0; + } + + /* load hkl */ + for (i = 0; i < 3; i++) { + fHkl[i] = par[i]->value.v.doubleValue; + } + + /* load positions */ + for (i = 0; i < 4; i++) { + fPosition[i] = par[i + 3]->value.v.doubleValue; + } + + return FourMessStoreIntern(self, pCon, fHkl, fPosition); } + /*------------------------------------------------------------------*/ -static int weakScan(pSICSOBJ self, SConnection *pCon){ +static int weakScan(pSICSOBJ self, SConnection * pCon) +{ int i, np; long low = 99999, high = -99999, *lCounts = NULL; pFourMess priv = self->pPrivate; hdbValue v; - + /* - the scan is always OK if we do not test for weak conditions or we are in psd mode - */ - SICSHdbGetPar(self,pCon,"weak",&v); - if(v.v.intValue == 0){ + the scan is always OK if we do not test for weak conditions or we are in psd mode + */ + SICSHdbGetPar(self, pCon, "weak", &v); + if (v.v.intValue == 0) { return 0; } - + np = GetScanNP(priv->pScanner); - lCounts = malloc(np*sizeof(long)); - if(lCounts == NULL){ - SCWrite(pCon,"ERROR: out of memory in weakScan test", eLogError); - return 0; + lCounts = malloc(np * sizeof(long)); + if (lCounts == NULL) { + SCWrite(pCon, "ERROR: out of memory in weakScan test", eLogError); + return 0; } - GetScanCounts(priv->pScanner,lCounts,np); - for(i = 0; i < np; i++){ - if(lCounts[i] < low){ + GetScanCounts(priv->pScanner, lCounts, np); + for (i = 0; i < np; i++) { + if (lCounts[i] < low) { low = lCounts[i]; } - if(lCounts[i] > high){ + if (lCounts[i] > high) { high = lCounts[i]; } } /* - I am using the weakest point here as a rough estimate of - the background - */ - SICSHdbGetPar(self,pCon,"weakthreshold",&v); - if(high - 2 * low > v.v.intValue){ + I am using the weakest point here as a rough estimate of + the background + */ + SICSHdbGetPar(self, pCon, "weakthreshold", &v); + if (high - 2 * low > v.v.intValue) { return 0; } else { return 1; } } -/*----------------------------------------------------------------------------*/ -static int FourMessWeak(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - int weak; - - weak = weakScan(self,pCon); - SCPrintf(pCon,eLog,"weak = %d", weak); - return 1; -} -/*----------------------------------------------------------------------------*/ -static int GenIndex(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - double lambda = SXGetLambda(), d, om, hkl[3]; - int h, k, l, minh, mink, minl, suppress; - hdbValue hkllim, sttlim; - T_SgInfo *sginfo = SXGetSpaceGroup(); - pFourMess priv = self->pPrivate; - int count = 0; - MATRIX B, H, Z1; - const double *cell; - lattice direct; - - if(nPar < 1) { - SCWrite(pCon,"ERROR: need a suppression flag for indgen", - eError); - return 0; - } - SICSHdbGetPar(self,pCon,"hkllim",&hkllim); - SICSHdbGetPar(self,pCon,"sttlim",&sttlim); - suppress = par[0]->value.v.intValue; - - minh = hkllim.v.intArray[3]; - mink = hkllim.v.intArray[4]; - minl = hkllim.v.intArray[5]; - SetListMin_hkl(sginfo,hkllim.v.intArray[1], hkllim.v.intArray[2], - &minh, &mink, &minl); - ClearReflectionList(priv->messList); - cell = SXGetCell(); - direct.a = cell[0]; - direct.b = cell[1]; - direct.c = cell[2]; - direct.alpha = cell[3]; - direct.beta = cell[4]; - direct.gamma = cell[5]; - B = mat_creat(3,3,UNIT_MATRIX); - if(!calculateBMatrix(direct,B)){ - SCWrite(pCon,"ERROR: invalid cell", eError); - return 0; - } - H = mat_creat(3,1,ZERO_MATRIX); - - - for(h = hkllim.v.intArray[0]; h < hkllim.v.intArray[3]; h++){ - for(k = hkllim.v.intArray[1]; k < hkllim.v.intArray[4]; k++){ - for(l = hkllim.v.intArray[2]; l < hkllim.v.intArray[5]; l++){ - /* first test: extinct */ - if(IsSysAbsent_hkl(sginfo,h,k,l,NULL) != 0 ){ - continue; - } - /* second test: a symmetrically equivalent already seen */ - if((suppress != 0) && IsSuppressed_hkl(sginfo,minh,mink,minl, - hkllim.v.intArray[1],hkllim.v.intArray[2],h,k,l ) != 0){ - continue; - } - /* third test: within stt limits */ - H[0][0] = (double)h; - H[1][0] = (double)k; - H[2][0] = (double)l; - Z1 = mat_mul(B,H); - calcTheta(lambda,Z1,&d,&om); - om *= 2.; - mat_free(Z1); - if(om > sttlim.v.floatArray[0] && om < sttlim.v.floatArray[1]){ - hkl[0] = (double)h; - hkl[1] = (double)k; - hkl[2] = (double)l; - AddRefIdx(priv->messList,hkl); - count++; - } - } - } - } - mat_free(B); - mat_free(H); - priv->masterCount = count; - SCPrintf(pCon,eValue,"%d reflections generated", count); - return 1; +/*----------------------------------------------------------------------------*/ +static int FourMessWeak(pSICSOBJ self, SConnection * pCon, + pHdb commandNode, pHdb par[], int nPar) +{ + int weak; + + weak = weakScan(self, pCon); + SCPrintf(pCon, eLog, "weak = %d", weak); + return 1; } + +/*----------------------------------------------------------------------------*/ +static int GenIndex(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + double lambda = SXGetLambda(), d, om, hkl[3]; + int h, k, l, minh, mink, minl, suppress; + hdbValue hkllim, sttlim; + T_SgInfo *sginfo = SXGetSpaceGroup(); + pFourMess priv = self->pPrivate; + int count = 0; + MATRIX B, H, Z1; + const double *cell; + lattice direct; + + if (nPar < 1) { + SCWrite(pCon, "ERROR: need a suppression flag for indgen", eError); + return 0; + } + SICSHdbGetPar(self, pCon, "hkllim", &hkllim); + SICSHdbGetPar(self, pCon, "sttlim", &sttlim); + suppress = par[0]->value.v.intValue; + + minh = hkllim.v.intArray[3]; + mink = hkllim.v.intArray[4]; + minl = hkllim.v.intArray[5]; + + SetListMin_hkl(sginfo, hkllim.v.intArray[1], hkllim.v.intArray[2], + &minh, &mink, &minl); + ClearReflectionList(priv->messList); + cell = SXGetCell(); + direct.a = cell[0]; + direct.b = cell[1]; + direct.c = cell[2]; + direct.alpha = cell[3]; + direct.beta = cell[4]; + direct.gamma = cell[5]; + B = mat_creat(3, 3, UNIT_MATRIX); + if (!calculateBMatrix(direct, B)) { + SCWrite(pCon, "ERROR: invalid cell", eError); + return 0; + } + H = mat_creat(3, 1, ZERO_MATRIX); + + + for (h = hkllim.v.intArray[0]; h < hkllim.v.intArray[3]; h++) { + for (k = hkllim.v.intArray[1]; k < hkllim.v.intArray[4]; k++) { + for (l = hkllim.v.intArray[2]; l < hkllim.v.intArray[5]; l++) { + /* first test: extinct */ + if (IsSysAbsent_hkl(sginfo, h, k, l, NULL) != 0) { + continue; + } + /* second test: a symmetrically equivalent already seen */ + if ((suppress != 0) && IsSuppressed_hkl(sginfo, minh, mink, minl, + hkllim.v.intArray[1], + hkllim.v.intArray[2], h, k, + l) != 0) { + continue; + } + /* third test: within stt limits */ + H[0][0] = (double) h; + H[1][0] = (double) k; + H[2][0] = (double) l; + Z1 = mat_mul(B, H); + calcTheta(lambda, Z1, &d, &om); + om *= 2.; + mat_free(Z1); + if (om > sttlim.v.floatArray[0] && om < sttlim.v.floatArray[1]) { + hkl[0] = (double) h; + hkl[1] = (double) k; + hkl[2] = (double) l; + AddRefIdx(priv->messList, hkl); + count++; + } + } + } + } + mat_free(B); + mat_free(H); + priv->masterCount = count; + SCPrintf(pCon, eValue, "%d reflections generated", count); + return 1; +} + /*-----------------------------------------------------------------------------*/ -static int GenInconsumerate(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - double hkl[3], qvec[3]; - pFourMess priv = self->pPrivate; - int i, j; - - if(nPar < 3) { - SCWrite(pCon, - "ERROR: need q displacement vector with three compononts", - eError); - return 0; - } - qvec[0] = par[0]->value.v.doubleValue; - qvec[1] = par[1]->value.v.doubleValue; - qvec[2] = par[2]->value.v.doubleValue; - - for(i = 0; i < priv->masterCount; i++){ - GetRefIndex(priv->messList,i,hkl); - for(j = 0; j < 3; j++){ - hkl[j] += qvec[j]; - } - AddRefIdx(priv->messList, hkl); - } - SCPrintf(pCon,eValue,"%d additional inconsumerate reflections generated", - priv->masterCount); - return 1; +static int GenInconsumerate(pSICSOBJ self, SConnection * pCon, + pHdb commandNode, pHdb par[], int nPar) +{ + double hkl[3], qvec[3]; + pFourMess priv = self->pPrivate; + int i, j; + + if (nPar < 3) { + SCWrite(pCon, + "ERROR: need q displacement vector with three compononts", + eError); + return 0; + } + qvec[0] = par[0]->value.v.doubleValue; + qvec[1] = par[1]->value.v.doubleValue; + qvec[2] = par[2]->value.v.doubleValue; + + for (i = 0; i < priv->masterCount; i++) { + GetRefIndex(priv->messList, i, hkl); + for (j = 0; j < 3; j++) { + hkl[j] += qvec[j]; + } + AddRefIdx(priv->messList, hkl); + } + SCPrintf(pCon, eValue, + "%d additional inconsumerate reflections generated", + priv->masterCount); + return 1; } + /*----------------------------------------------------------------------------*/ -static int hklCompare(const void *h1, const void *h2){ - const double *hkl1 = h1, *hkl2 = h2; - - if(hkl1[3] < hkl2[3]){ - return -1; - } else if (hkl1[3] == hkl2[3]) { - return 0; - } else { - return 1; - } +static int hklCompare(const void *h1, const void *h2) +{ + const double *hkl1 = h1, *hkl2 = h2; + + if (hkl1[3] < hkl2[3]) { + return -1; + } else if (hkl1[3] == hkl2[3]) { + return 0; + } else { + return 1; + } } + /*----------------------------------------------------------------------------*/ -static int SortRef(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - double *sortlist, d, lambda, om, hkl[4], ang[4]; - const double *cell; - int nRefl, i, j; - MATRIX B, H, Z1; - lattice direct; - pFourMess priv = self->pPrivate; - - lambda = SXGetLambda(); - cell = SXGetCell(); - direct.a = cell[0]; - direct.b = cell[1]; - direct.c = cell[2]; - direct.alpha = cell[3]; - direct.beta = cell[4]; - direct.gamma = cell[5]; - B = mat_creat(3,3,UNIT_MATRIX); - if(!calculateBMatrix(direct,B)){ - SCWrite(pCon,"ERROR: invalid cell", eError); - return 0; - } - H = mat_creat(3,1,ZERO_MATRIX); +static int SortRef(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + double *sortlist, d, lambda, om, hkl[4], ang[4]; + const double *cell; + int nRefl, i, j; + MATRIX B, H, Z1; + lattice direct; + pFourMess priv = self->pPrivate; - nRefl = ReflectionListCount(priv->messList); - sortlist = malloc(nRefl*4*sizeof(double)); - if(sortlist == NULL){ - SCWrite(pCon,"ERROR: out of memory in SortRef",eError); - return 0; - } - /* - * I am using hkl[3] for storing the theta value to sort for! */ - for(i = 0; i < nRefl; i++){ - GetRefIndex(priv->messList,i,hkl); - for(j = 0; j < 3; j++){ - H[j][0] = hkl[j]; - } - Z1 = mat_mul(B,H); - calcTheta(lambda,Z1,&d, &om); - mat_free(Z1); - hkl[3] = om; - memcpy(sortlist + i*4, hkl, 4*sizeof(double)); - } - - qsort(sortlist,nRefl,4*sizeof(double),hklCompare); - - ClearReflectionList(priv->messList); - for(i = 0; i < nRefl; i++){ - ang[1] = sortlist[i*4+3]; - ang[0] = 2.*ang[1]; - ang[2] = .0; - ang[3] = .0; - /* AddRefIdxAng(priv->messList, sortlist+i*4,ang); */ - AddRefIdx(priv->messList, sortlist+i*4); - } - free(sortlist); - mat_free(B); - mat_free(H); - SCSendOK(pCon); - return 1; + lambda = SXGetLambda(); + cell = SXGetCell(); + direct.a = cell[0]; + direct.b = cell[1]; + direct.c = cell[2]; + direct.alpha = cell[3]; + direct.beta = cell[4]; + direct.gamma = cell[5]; + B = mat_creat(3, 3, UNIT_MATRIX); + if (!calculateBMatrix(direct, B)) { + SCWrite(pCon, "ERROR: invalid cell", eError); + return 0; + } + H = mat_creat(3, 1, ZERO_MATRIX); + + nRefl = ReflectionListCount(priv->messList); + sortlist = malloc(nRefl * 4 * sizeof(double)); + if (sortlist == NULL) { + SCWrite(pCon, "ERROR: out of memory in SortRef", eError); + return 0; + } + /* + * I am using hkl[3] for storing the theta value to sort for! */ + for (i = 0; i < nRefl; i++) { + GetRefIndex(priv->messList, i, hkl); + for (j = 0; j < 3; j++) { + H[j][0] = hkl[j]; + } + Z1 = mat_mul(B, H); + calcTheta(lambda, Z1, &d, &om); + mat_free(Z1); + hkl[3] = om; + memcpy(sortlist + i * 4, hkl, 4 * sizeof(double)); + } + + qsort(sortlist, nRefl, 4 * sizeof(double), hklCompare); + + ClearReflectionList(priv->messList); + for (i = 0; i < nRefl; i++) { + ang[1] = sortlist[i * 4 + 3]; + ang[0] = 2. * ang[1]; + ang[2] = .0; + ang[3] = .0; + /* AddRefIdxAng(priv->messList, sortlist+i*4,ang); */ + AddRefIdx(priv->messList, sortlist + i * 4); + } + free(sortlist); + mat_free(B); + mat_free(H); + SCSendOK(pCon); + return 1; } + /*----------------------------------------------------------------------------*/ -static int FourMessSave(void *data, char *name, FILE *fd){ - pSICSOBJ self = data; - pFourMess priv = self->pPrivate; - - SaveSICSOBJ(data,name,fd); - SaveFourCircleTable(priv->stepTable, name, fd); - return 1; +static int FourMessSave(void *data, char *name, FILE * fd) +{ + pSICSOBJ self = data; + pFourMess priv = self->pPrivate; + + SaveSICSOBJ(data, name, fd); + SaveFourCircleTable(priv->stepTable, name, fd); + return 1; } + /*----------------------------------------------------------------------------*/ -void InstallFourMess(SConnection *pCon, SicsInterp *pSics){ - pFourMess priv = NULL; - pSICSOBJ pNew = NULL; - pHdb cmd = NULL; - int hkl[] = {-10,-10,10,10,10,10}; - double sttlim[] = {5.0, 180}; - - pNew = MakeSICSOBJ("fmess","FourMess"); - priv = calloc(1,sizeof(FourMess)); - if(pNew == NULL || priv == NULL){ - SCWrite(pCon,"ERROR: out of memory creating fourmess", eError); - } - pNew->pDes->SaveStatus = FourMessSave; - pNew->pPrivate = priv; - pNew->KillPrivate = KillFourMess; - - priv->stepTable = MakeFourCircleTable(); - priv->messList = CreateReflectionList(pCon,pSics,"messref"); - if(priv->stepTable < 0 || priv->messList == NULL){ - SCWrite(pCon,"ERROR: out of memory creating fourmess", eError); - } +void InstallFourMess(SConnection * pCon, SicsInterp * pSics) +{ + pFourMess priv = NULL; + pSICSOBJ pNew = NULL; + pHdb cmd = NULL; + int hkl[] = { -10, -10, 10, 10, 10, 10 }; + double sttlim[] = { 5.0, 180 }; - cmd = AddSICSHdbPar(pNew->objectNode,"weak", usUser, MakeHdbInt(0)); - SetHdbProperty(cmd,"__save","true"); - cmd = AddSICSHdbPar(pNew->objectNode,"weakthreshold", usUser, - MakeHdbInt(20)); - SetHdbProperty(cmd,"__save","true"); - cmd = AddSICSHdbPar(pNew->objectNode,"mode", usUser, MakeHdbText("Monitor")); + pNew = MakeSICSOBJ("fmess", "FourMess"); + priv = calloc(1, sizeof(FourMess)); + if (pNew == NULL || priv == NULL) { + SCWrite(pCon, "ERROR: out of memory creating fourmess", eError); + } + pNew->pDes->SaveStatus = FourMessSave; + pNew->pPrivate = priv; + pNew->KillPrivate = KillFourMess; - cmd = AddSICSHdbPar(pNew->objectNode,"hkllim", usUser, MakeHdbIntArray(6,hkl)); - SetHdbProperty(cmd,"__save","true"); - cmd = AddSICSHdbPar(pNew->objectNode,"sttlim", usUser, MakeHdbFloatArray(2,sttlim)); - SetHdbProperty(cmd,"__save","true"); - - cmd = AddSICSHdbPar(pNew->objectNode,"start", usUser, MakeSICSFunc(FourMessStart)); - cmd = AddSICSHdbPar(cmd,"filename", usUser, MakeHdbText("Unknown")); - cmd = AddSICSHdbPar(pNew->objectNode,"close", usUser, MakeSICSFunc(FourMessClose)); + priv->stepTable = MakeFourCircleTable(); + priv->messList = CreateReflectionList(pCon, pSics, "messref"); + if (priv->stepTable < 0 || priv->messList == NULL) { + SCWrite(pCon, "ERROR: out of memory creating fourmess", eError); + } - cmd = AddSICSHdbPar(pNew->objectNode,"scanpar", usUser, MakeSICSFunc(FourMessScanPar)); - cmd = AddSICSHdbPar(cmd,"twotheta", usUser, MakeHdbFloat(.0)); + cmd = AddSICSHdbPar(pNew->objectNode, "weak", usUser, MakeHdbInt(0)); + SetHdbProperty(cmd, "__save", "true"); + cmd = AddSICSHdbPar(pNew->objectNode, "weakthreshold", usUser, + MakeHdbInt(20)); + SetHdbProperty(cmd, "__save", "true"); + cmd = + AddSICSHdbPar(pNew->objectNode, "mode", usUser, + MakeHdbText("Monitor")); - cmd = AddSICSHdbPar(pNew->objectNode,"store", usUser, MakeSICSFunc(FourMessStore)); - AddSICSHdbPar(cmd,"h", usUser, MakeHdbFloat(.0)); - AddSICSHdbPar(cmd,"k", usUser, MakeHdbFloat(.0)); - AddSICSHdbPar(cmd,"l", usUser, MakeHdbFloat(.0)); - AddSICSHdbPar(cmd,"stt", usUser, MakeHdbFloat(.0)); - AddSICSHdbPar(cmd,"om", usUser, MakeHdbFloat(.0)); - AddSICSHdbPar(cmd,"chi", usUser, MakeHdbFloat(.0)); - AddSICSHdbPar(cmd,"phi", usUser, MakeHdbFloat(.0)); - cmd = AddSICSHdbPar(pNew->objectNode,"weak", usUser, MakeSICSFunc(FourMessWeak)); - - cmd = AddSICSHdbPar(pNew->objectNode,"indgen", usUser, MakeSICSFunc(GenIndex)); - AddSICSHdbPar(cmd,"sup", usUser, MakeHdbInt(1)); - - cmd = AddSICSHdbPar(pNew->objectNode,"genw", usUser, MakeSICSFunc(GenInconsumerate)); - AddSICSHdbPar(cmd,"hw", usUser, MakeHdbFloat(.0)); - AddSICSHdbPar(cmd,"kw", usUser, MakeHdbFloat(.0)); - AddSICSHdbPar(cmd,"lw", usUser, MakeHdbFloat(.0)); + cmd = + AddSICSHdbPar(pNew->objectNode, "hkllim", usUser, + MakeHdbIntArray(6, hkl)); + SetHdbProperty(cmd, "__save", "true"); + cmd = + AddSICSHdbPar(pNew->objectNode, "sttlim", usUser, + MakeHdbFloatArray(2, sttlim)); + SetHdbProperty(cmd, "__save", "true"); - cmd = AddSICSHdbPar(pNew->objectNode,"indsort", usUser, MakeSICSFunc(SortRef)); + cmd = + AddSICSHdbPar(pNew->objectNode, "start", usUser, + MakeSICSFunc(FourMessStart)); + cmd = AddSICSHdbPar(cmd, "filename", usUser, MakeHdbText("Unknown")); + cmd = + AddSICSHdbPar(pNew->objectNode, "close", usUser, + MakeSICSFunc(FourMessClose)); - - cmd = AddSICSHdbPar(pNew->objectNode,"template", usMugger, MakeHdbText("Unknown")); - cmd = AddSICSHdbPar(pNew->objectNode,"scanobj", usMugger, MakeHdbText("xxxscan")); - PrependHipadabaCallback(cmd, - MakeHipadabaCallback(SetScannerCB, priv,NULL)); - - priv->pScanner = FindCommandData(pSics,"xxxscan","ScanObject"); - - AddCommand(pSics, - "fmess", - FourMessAction, - KillSICSOBJ, - pNew); + cmd = + AddSICSHdbPar(pNew->objectNode, "scanpar", usUser, + MakeSICSFunc(FourMessScanPar)); + cmd = AddSICSHdbPar(cmd, "twotheta", usUser, MakeHdbFloat(.0)); + + cmd = + AddSICSHdbPar(pNew->objectNode, "store", usUser, + MakeSICSFunc(FourMessStore)); + AddSICSHdbPar(cmd, "h", usUser, MakeHdbFloat(.0)); + AddSICSHdbPar(cmd, "k", usUser, MakeHdbFloat(.0)); + AddSICSHdbPar(cmd, "l", usUser, MakeHdbFloat(.0)); + AddSICSHdbPar(cmd, "stt", usUser, MakeHdbFloat(.0)); + AddSICSHdbPar(cmd, "om", usUser, MakeHdbFloat(.0)); + AddSICSHdbPar(cmd, "chi", usUser, MakeHdbFloat(.0)); + AddSICSHdbPar(cmd, "phi", usUser, MakeHdbFloat(.0)); + cmd = + AddSICSHdbPar(pNew->objectNode, "weak", usUser, + MakeSICSFunc(FourMessWeak)); + + cmd = + AddSICSHdbPar(pNew->objectNode, "indgen", usUser, + MakeSICSFunc(GenIndex)); + AddSICSHdbPar(cmd, "sup", usUser, MakeHdbInt(1)); + + cmd = + AddSICSHdbPar(pNew->objectNode, "genw", usUser, + MakeSICSFunc(GenInconsumerate)); + AddSICSHdbPar(cmd, "hw", usUser, MakeHdbFloat(.0)); + AddSICSHdbPar(cmd, "kw", usUser, MakeHdbFloat(.0)); + AddSICSHdbPar(cmd, "lw", usUser, MakeHdbFloat(.0)); + + cmd = + AddSICSHdbPar(pNew->objectNode, "indsort", usUser, + MakeSICSFunc(SortRef)); + + + cmd = + AddSICSHdbPar(pNew->objectNode, "template", usMugger, + MakeHdbText("Unknown")); + cmd = + AddSICSHdbPar(pNew->objectNode, "scanobj", usMugger, + MakeHdbText("xxxscan")); + PrependHipadabaCallback(cmd, + MakeHipadabaCallback(SetScannerCB, priv, NULL)); + + priv->pScanner = FindCommandData(pSics, "xxxscan", "ScanObject"); + + AddCommand(pSics, "fmess", FourMessAction, KillSICSOBJ, pNew); } - diff --git a/fourmess.h b/fourmess.h index c3f3f6c6..357cbc17 100644 --- a/fourmess.h +++ b/fourmess.h @@ -19,7 +19,6 @@ #define _FOURMESS #include -void InstallFourMess(SConnection *pCon, SicsInterp *pSics); +void InstallFourMess(SConnection * pCon, SicsInterp * pSics); #endif - diff --git a/fourtable.c b/fourtable.c index 8fb1089c..17d4c62e 100644 --- a/fourtable.c +++ b/fourtable.c @@ -22,17 +22,22 @@ typedef struct { double step; int np; float preset; -}FourTableEntry, *pFourTableEntry; +} FourTableEntry, *pFourTableEntry; /*==================== functions =======================================*/ -int MakeFourCircleTable(){ +int MakeFourCircleTable() +{ return LLDcreate(sizeof(FourTableEntry)); } + /*-----------------------------------------------------------------------*/ -void DeleteFourCircleTable(int handle){ +void DeleteFourCircleTable(int handle) +{ LLDdelete(handle); } + /*------------------------------------------------------------------------*/ -static void printList(int handle, SConnection *pCon){ +static void printList(int handle, SConnection * pCon) +{ FourTableEntry entry; char pBueffel[132]; int status, printed = 0; @@ -40,125 +45,139 @@ static void printList(int handle, SConnection *pCon){ Tcl_DStringInit(&list); status = LLDnodePtr2First(handle); - while(status == 1) { - LLDnodeDataTo(handle,&entry); - snprintf(pBueffel,131,"%8.3f %10s %8.3f %d %8.3f\n", entry.twoThetaEnd, - entry.scanVar,entry.step, entry.np,entry.preset); - Tcl_DStringAppend(&list,pBueffel,-1); - printed = 1; + while (status == 1) { + LLDnodeDataTo(handle, &entry); + snprintf(pBueffel, 131, "%8.3f %10s %8.3f %d %8.3f\n", + entry.twoThetaEnd, entry.scanVar, entry.step, entry.np, + entry.preset); + Tcl_DStringAppend(&list, pBueffel, -1); + printed = 1; status = LLDnodePtr2Next(handle); } - if(printed == 0){ - Tcl_DStringAppend(&list,"table is empty",-1); + if (printed == 0) { + Tcl_DStringAppend(&list, "table is empty", -1); } - SCWrite(pCon,Tcl_DStringValue(&list), eValue); + SCWrite(pCon, Tcl_DStringValue(&list), eValue); Tcl_DStringFree(&list); } + /*--------------------------------------------------------------------- Make sure that the entry is added in a sorted way according to two_theta ----------------------------------------------------------------------*/ -static void insertEntry(int list, FourTableEntry newEntry){ +static void insertEntry(int list, FourTableEntry newEntry) +{ int status, count = 0, pos; FourTableEntry test; /* - locate the last entry bigger then us - */ + locate the last entry bigger then us + */ status = LLDnodePtr2First(list); - while(status == 1){ - LLDnodeDataTo(list,&test); + while (status == 1) { + LLDnodeDataTo(list, &test); count++; - if(test.twoThetaEnd == newEntry.twoThetaEnd){ - LLDnodeDataFrom(list,&newEntry); + if (test.twoThetaEnd == newEntry.twoThetaEnd) { + LLDnodeDataFrom(list, &newEntry); return; } - if(test.twoThetaEnd > newEntry.twoThetaEnd){ + if (test.twoThetaEnd > newEntry.twoThetaEnd) { break; } status = LLDnodePtr2Next(list); } /* - special case: empty list - */ - if(count == 0){ - LLDnodeAppendFrom(list,&newEntry); + special case: empty list + */ + if (count == 0) { + LLDnodeAppendFrom(list, &newEntry); return; } /* - special case: append after last - */ + special case: append after last + */ LLDnodePtr2Last(list); - LLDnodeDataTo(list,&test); - if(newEntry.twoThetaEnd > test.twoThetaEnd){ - LLDnodeAppendFrom(list,&newEntry); + LLDnodeDataTo(list, &test); + if (newEntry.twoThetaEnd > test.twoThetaEnd) { + LLDnodeAppendFrom(list, &newEntry); return; } status = LLDnodePtr2First(list); pos = 0; - while(status == 1){ - LLDnodeDataTo(list,&test); + while (status == 1) { + LLDnodeDataTo(list, &test); pos++; - if(pos == count){ - LLDnodeInsertFrom(list,&newEntry); + if (pos == count) { + LLDnodeInsertFrom(list, &newEntry); return; } status = LLDnodePtr2Next(list); } } + /*-----------------------------------------------------------------------*/ -static int addToList(int handle, SConnection *pCon, int argc, char *argv[]){ +static int addToList(int handle, SConnection * pCon, int argc, + char *argv[]) +{ FourTableEntry entry; char pBueffel[132]; - if(argc < 7){ - SCWrite(pCon,"ERROR: not enough arguments to table add",eError); + if (argc < 7) { + SCWrite(pCon, "ERROR: not enough arguments to table add", eError); return 0; } - if(isNumeric(argv[3])){ + if (isNumeric(argv[3])) { entry.twoThetaEnd = atof(argv[3]); } else { - snprintf(pBueffel,131,"ERROR: expected numeric argument, received %s", argv[3]); - SCWrite(pCon,pBueffel,eError); + snprintf(pBueffel, 131, + "ERROR: expected numeric argument, received %s", argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; } - strncpy(entry.scanVar,argv[4],29); + strncpy(entry.scanVar, argv[4], 29); strtolower(entry.scanVar); - if(strcmp(entry.scanVar,"om") != 0 && strstr(entry.scanVar,"o2t") == NULL){ - SCWrite(pCon,"ERROR: Invalied scan variable specified, only om, o2t allowed",eError); + if (strcmp(entry.scanVar, "om") != 0 + && strstr(entry.scanVar, "o2t") == NULL) { + SCWrite(pCon, + "ERROR: Invalied scan variable specified, only om, o2t allowed", + eError); return 0; } - if(isNumeric(argv[5])){ + if (isNumeric(argv[5])) { entry.step = atof(argv[5]); } else { - snprintf(pBueffel,131,"ERROR: expected numeric argument, received %s", argv[4]); - SCWrite(pCon,pBueffel,eError); + snprintf(pBueffel, 131, + "ERROR: expected numeric argument, received %s", argv[4]); + SCWrite(pCon, pBueffel, eError); return 0; } - if(isNumeric(argv[6])){ + if (isNumeric(argv[6])) { entry.np = atoi(argv[6]); } else { - snprintf(pBueffel,131,"ERROR: expected numeric argument, received %s", argv[6]); - SCWrite(pCon,pBueffel,eError); + snprintf(pBueffel, 131, + "ERROR: expected numeric argument, received %s", argv[6]); + SCWrite(pCon, pBueffel, eError); return 0; } entry.preset = -1.0; - if(argc > 7){ - if(isNumeric(argv[7])){ - entry.preset = atof(argv[7]); - } + if (argc > 7) { + if (isNumeric(argv[7])) { + entry.preset = atof(argv[7]); + } } - insertEntry(handle,entry); + insertEntry(handle, entry); return 1; } + /*-----------------------------------------------------------------------*/ -static void delEntry(int handle, int index){ +static void delEntry(int handle, int index) +{ int count = 0, status; status = LLDnodePtr2First(handle); - while(status == 1) { - if(count == index){ + while (status == 1) { + if (count == index) { LLDnodeDelete(handle); break; } else { @@ -167,20 +186,22 @@ static void delEntry(int handle, int index){ } } } -/*------------------------------------------------------------------------*/ -int HandleFourCircleCommands(int *table, SConnection *pCon, - int argc, char *argv[], int *err){ - int handle; - - *err = 1; - handle = *table; - /* - test if this is for us - */ - if(argc >= 3){ +/*------------------------------------------------------------------------*/ +int HandleFourCircleCommands(int *table, SConnection * pCon, + int argc, char *argv[], int *err) +{ + int handle; + + *err = 1; + handle = *table; + + /* + test if this is for us + */ + if (argc >= 3) { strtolower(argv[1]); - if(strcmp(argv[1],"table") != 0){ + if (strcmp(argv[1], "table") != 0) { return 0; } } else { @@ -188,127 +209,140 @@ int HandleFourCircleCommands(int *table, SConnection *pCon, } /* - what are we supposed to do? - */ + what are we supposed to do? + */ strtolower(argv[2]); - if(strcmp(argv[2],"clear") == 0){ - if(!SCMatchRights(pCon,usUser)){ + if (strcmp(argv[2], "clear") == 0) { + if (!SCMatchRights(pCon, usUser)) { *err = 0; return 1; } - LLDdelete(handle); - handle = LLDcreate(sizeof(FourTableEntry)); - *table = handle; + LLDdelete(handle); + handle = LLDcreate(sizeof(FourTableEntry)); + *table = handle; SCparChange(pCon); SCSendOK(pCon); - } else if (strcmp(argv[2],"list") == 0){ - printList(handle,pCon); - } else if(strcmp(argv[2],"add") == 0){ - if(!SCMatchRights(pCon,usUser)){ + } else if (strcmp(argv[2], "list") == 0) { + printList(handle, pCon); + } else if (strcmp(argv[2], "add") == 0) { + if (!SCMatchRights(pCon, usUser)) { *err = 0; return 1; } - *err = addToList(handle,pCon,argc,argv); - if(*err != 0) - { + *err = addToList(handle, pCon, argc, argv); + if (*err != 0) { SCparChange(pCon); SCSendOK(pCon); } - } else if(strcmp(argv[2],"del") == 0){ - if(!SCMatchRights(pCon,usUser)){ + } else if (strcmp(argv[2], "del") == 0) { + if (!SCMatchRights(pCon, usUser)) { *err = 0; return 1; } - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficnet number of arguments to table del",eError); + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficnet number of arguments to table del", + eError); *err = 0; } else { - if(isNumeric(argv[3])){ - delEntry(handle, atoi(argv[3])); - SCparChange(pCon); - SCSendOK(pCon); + if (isNumeric(argv[3])) { + delEntry(handle, atoi(argv[3])); + SCparChange(pCon); + SCSendOK(pCon); } else { - SCWrite(pCon,"ERROR: bad argument: expected numeric argument to table del",eError); - *err = 0; + SCWrite(pCon, + "ERROR: bad argument: expected numeric argument to table del", + eError); + *err = 0; } } } else { - SCWrite(pCon,"ERROR: subcommand to table not known",eError); + SCWrite(pCon, "ERROR: subcommand to table not known", eError); *err = 0; } return 1; } + /*-----------------------------------------------------------------------*/ -static FourTableEntry findEntry(int handle, double two_theta){ +static FourTableEntry findEntry(int handle, double two_theta) +{ int status; FourTableEntry entry; status = LLDnodePtr2First(handle); - while(status == 1) { - LLDnodeDataTo(handle,&entry); - if(entry.twoThetaEnd > two_theta){ + while (status == 1) { + LLDnodeDataTo(handle, &entry); + if (entry.twoThetaEnd > two_theta) { return entry; - } + } status = LLDnodePtr2Next(handle); } - strcpy(entry.scanVar,"NOT FOUND"); + strcpy(entry.scanVar, "NOT FOUND"); return entry; } + /*------------------------------------------------------------------------*/ -char *GetFourCircleScanVar(int handle, double two_theta){ +char *GetFourCircleScanVar(int handle, double two_theta) +{ FourTableEntry entry; - entry = findEntry(handle,two_theta); + entry = findEntry(handle, two_theta); return strdup(entry.scanVar); } + /*------------------------------------------------------------------------*/ -double GetFourCircleStep(int handle, double two_theta){ +double GetFourCircleStep(int handle, double two_theta) +{ FourTableEntry entry; - entry = findEntry(handle,two_theta); - if(strcmp(entry.scanVar,"NOT FOUND") == 0){ + entry = findEntry(handle, two_theta); + if (strcmp(entry.scanVar, "NOT FOUND") == 0) { return -999.99; } else { return entry.step; } } + /*------------------------------------------------------------------------*/ -float GetFourCirclePreset(int handle, double two_theta){ +float GetFourCirclePreset(int handle, double two_theta) +{ FourTableEntry entry; - entry = findEntry(handle,two_theta); - if(strcmp(entry.scanVar,"NOT FOUND") == 0){ + entry = findEntry(handle, two_theta); + if (strcmp(entry.scanVar, "NOT FOUND") == 0) { return -999.99; } else { return entry.preset; } } + /*------------------------------------------------------------------------*/ -int GetFourCircleScanNP(int handle, double two_theta){ +int GetFourCircleScanNP(int handle, double two_theta) +{ FourTableEntry entry; - entry = findEntry(handle,two_theta); - if(strcmp(entry.scanVar,"NOT FOUND") == 0){ + entry = findEntry(handle, two_theta); + if (strcmp(entry.scanVar, "NOT FOUND") == 0) { return -999; } else { return entry.np; } } + /*------------------------------------------------------------------------*/ -int SaveFourCircleTable(int handle, char *objName, FILE *fd){ +int SaveFourCircleTable(int handle, char *objName, FILE * fd) +{ FourTableEntry entry; int status; - fprintf(fd,"%s table clear\n",objName); + fprintf(fd, "%s table clear\n", objName); status = LLDnodePtr2Last(handle); - while(status != 0) { - LLDnodeDataTo(handle,&entry); - fprintf(fd,"%s table add %f %s %f %d %f\n",objName, - entry.twoThetaEnd,entry.scanVar, - entry.step,entry.np,entry.preset); - status = LLDnodePtr2Prev(handle); + while (status != 0) { + LLDnodeDataTo(handle, &entry); + fprintf(fd, "%s table add %f %s %f %d %f\n", objName, + entry.twoThetaEnd, entry.scanVar, + entry.step, entry.np, entry.preset); + status = LLDnodePtr2Prev(handle); } return 1; } - diff --git a/fourtable.h b/fourtable.h index 0348975d..a10e2423 100644 --- a/fourtable.h +++ b/fourtable.h @@ -11,14 +11,14 @@ #ifndef FOURTABLE #define FOURTABLE - int MakeFourCircleTable(); - void DeleteFourCircleTable(int handle); - int HandleFourCircleCommands(int *handle, SConnection *pCon, - int argc, char *argv[], int *err); - char *GetFourCircleScanVar(int handle, double two_theta); - double GetFourCircleStep(int handle, double two_theta); - int SaveFourCircleTable(int handle, char *objName, FILE *fd); - float GetFourCirclePreset(int handle, double twoTheta); - int GetFourCircleScanNP(int handle, double twoTheta); +int MakeFourCircleTable(); +void DeleteFourCircleTable(int handle); +int HandleFourCircleCommands(int *handle, SConnection * pCon, + int argc, char *argv[], int *err); +char *GetFourCircleScanVar(int handle, double two_theta); +double GetFourCircleStep(int handle, double two_theta); +int SaveFourCircleTable(int handle, char *objName, FILE * fd); +float GetFourCirclePreset(int handle, double twoTheta); +int GetFourCircleScanNP(int handle, double twoTheta); #endif diff --git a/frame.c b/frame.c index 20ef7293..094edf33 100644 --- a/frame.c +++ b/frame.c @@ -24,7 +24,8 @@ #include "nxdict.h" #include "frame.h" /*======================================================================*/ -static int readHMFrame(SConnection *pCon, pHistMem pHM, int nFrame){ +static int readHMFrame(SConnection * pCon, pHistMem pHM, int nFrame) +{ HistInt *buffer = NULL; int iDim[MAXDIM], rank, length, status, i, noTimeBins; pSINQHM pHist; @@ -32,211 +33,222 @@ static int readHMFrame(SConnection *pCon, pHistMem pHM, int nFrame){ const float *timeBin; /* - find dimensions and allocate data - */ - GetHistDim(pHM,iDim,&rank); - timeBin = GetHistTimeBin(pHM,&noTimeBins); + find dimensions and allocate data + */ + GetHistDim(pHM, iDim, &rank); + timeBin = GetHistTimeBin(pHM, &noTimeBins); - if(rank < 2){ - SCWrite(pCon,"ERROR: no PSD data present, cannot send frame",eError); + if (rank < 2) { + SCWrite(pCon, "ERROR: no PSD data present, cannot send frame", eError); return 0; } - length = iDim[0]*iDim[1]; - buffer = (HistInt *)malloc((length + 2)*sizeof(HistInt)); - if(!buffer){ - SCWrite(pCon,"ERROR: out of memory in readHMFrame",eError); + length = iDim[0] * iDim[1]; + buffer = (HistInt *) malloc((length + 2) * sizeof(HistInt)); + if (!buffer) { + SCWrite(pCon, "ERROR: out of memory in readHMFrame", eError); return 0; } - memset(buffer,0,(length+2)*sizeof(HistInt)); + memset(buffer, 0, (length + 2) * sizeof(HistInt)); /* - first two values are dimensions - */ + first two values are dimensions + */ buffer[0] = htonl(iDim[0]); buffer[1] = htonl(iDim[1]); - if(isSINQHMDriv(pHM->pDriv) && noTimeBins > 2) { + if (isSINQHMDriv(pHM->pDriv) && noTimeBins > 2) { /* - read from HM. The 5 is PROJECT__FRAME in Sinqhm_def.h - Again: be friendly: fix out of range frames - */ - if(nFrame < 0){ + read from HM. The 5 is PROJECT__FRAME in Sinqhm_def.h + Again: be friendly: fix out of range frames + */ + if (nFrame < 0) { nFrame = 0; } - if(nFrame >= noTimeBins){ - nFrame = noTimeBins-1; + if (nFrame >= noTimeBins) { + nFrame = noTimeBins - 1; } - pTata = (SinqHMDriv *)pHM->pDriv->pPriv; - pHist = (pSINQHM)pTata->pMaster; + pTata = (SinqHMDriv *) pHM->pDriv->pPriv; + pHist = (pSINQHM) pTata->pMaster; status = SINQHMProject(pHist, 0x0005, 0, nFrame, - 0, iDim[1], buffer+2,length*sizeof(HistInt)); - if(status != 1){ - SCWrite(pCon,"ERROR: SINQHM refused to deliver frame",eError); + 0, iDim[1], buffer + 2, + length * sizeof(HistInt)); + if (status != 1) { + SCWrite(pCon, "ERROR: SINQHM refused to deliver frame", eError); free(buffer); return 0; } } else { /* - be friendly, just read the 2D data which is there - */ - status = GetHistogram(pHM,pCon,0,0,length,buffer+2,length*sizeof(HistInt)); - if(!status){ + be friendly, just read the 2D data which is there + */ + status = + GetHistogram(pHM, pCon, 0, 0, length, buffer + 2, + length * sizeof(HistInt)); + if (!status) { free(buffer); return status; } } /* - enforce network byte order - */ - for(i = 0; i < length; i++){ - buffer[i+2] = htonl(buffer[i+2]); + enforce network byte order + */ + for (i = 0; i < length; i++) { + buffer[i + 2] = htonl(buffer[i + 2]); } - SCWriteUUencoded(pCon,"framedata", buffer,(length+2)*sizeof(HistInt)); + SCWriteUUencoded(pCon, "framedata", buffer, + (length + 2) * sizeof(HistInt)); free(buffer); return 1; } + /*=======================================================================*/ -static int readFileFrame(SConnection *pCon, - char *file, char *dictFile, - char *alias, int nFrame){ +static int readFileFrame(SConnection * pCon, + char *file, char *dictFile, + char *alias, int nFrame) +{ int status, iDim[NX_MAXRANK], rank = 0, type = 0; int iStart[3], iSize[3], length, i; int *buffer = NULL; NXhandle fileHandle; - NXdict dictHandle; + NXdict dictHandle; char error[512]; - status = NXopen(file,NXACC_READ,&fileHandle); - if(status != NX_OK){ - sprintf(error,"ERROR: failed to open %s", file); - SCWrite(pCon,error,eError); + status = NXopen(file, NXACC_READ, &fileHandle); + if (status != NX_OK) { + sprintf(error, "ERROR: failed to open %s", file); + SCWrite(pCon, error, eError); return 0; } status = NXDinitfromfile(dictFile, &dictHandle); - if(status != NX_OK){ - sprintf(error,"ERROR: failed to open dictionary %s", dictFile); + if (status != NX_OK) { + sprintf(error, "ERROR: failed to open dictionary %s", dictFile); NXclose(&fileHandle); - SCWrite(pCon,error,eError); + SCWrite(pCon, error, eError); return 0; } - - status = NXDopenalias(fileHandle,dictHandle,alias); - if(status != NX_OK){ - sprintf(error,"ERROR: failed to open alias %s", alias); + + status = NXDopenalias(fileHandle, dictHandle, alias); + if (status != NX_OK) { + sprintf(error, "ERROR: failed to open alias %s", alias); NXclose(&fileHandle); - NXDclose(dictHandle,NULL); - SCWrite(pCon,error,eError); + NXDclose(dictHandle, NULL); + SCWrite(pCon, error, eError); return 0; } - - status = NXgetinfo(fileHandle,&rank,iDim,&type); - if(type != NX_INT32 && type != NX_UINT32)type = -1; - if(status != NX_OK || rank < 2 || type < 0 ){ - sprintf(error,"ERROR: Dataset does not match!"); + + status = NXgetinfo(fileHandle, &rank, iDim, &type); + if (type != NX_INT32 && type != NX_UINT32) + type = -1; + if (status != NX_OK || rank < 2 || type < 0) { + sprintf(error, "ERROR: Dataset does not match!"); NXclose(&fileHandle); - NXDclose(dictHandle,NULL); - SCWrite(pCon,error,eError); + NXDclose(dictHandle, NULL); + SCWrite(pCon, error, eError); return 0; } /* - allocate space - */ - length = iDim[0]*iDim[1]; - buffer = (int *)malloc((length+2)*sizeof(int)); - if(!buffer){ + allocate space + */ + length = iDim[0] * iDim[1]; + buffer = (int *) malloc((length + 2) * sizeof(int)); + if (!buffer) { NXclose(&fileHandle); - NXDclose(dictHandle,NULL); - SCWrite(pCon,"ERROR: out of memory in readFrameFromFile",eError); + NXDclose(dictHandle, NULL); + SCWrite(pCon, "ERROR: out of memory in readFrameFromFile", eError); return 0; } - memset(buffer,0,(length+2)*sizeof(int)); + memset(buffer, 0, (length + 2) * sizeof(int)); /* - first two values: dimensions - */ + first two values: dimensions + */ buffer[0] = htonl(iDim[0]); buffer[1] = htonl(iDim[1]); - if(rank == 2){ + if (rank == 2) { /* - be friendly - */ - status = NXgetdata(fileHandle,buffer+2); + be friendly + */ + status = NXgetdata(fileHandle, buffer + 2); } else { iStart[0] = iStart[1] = 0; iStart[2] = nFrame; iSize[0] = iDim[0]; iSize[1] = iDim[1]; iSize[2] = 1; - status = NXgetslab(fileHandle,buffer+2,iStart,iSize); + status = NXgetslab(fileHandle, buffer + 2, iStart, iSize); } - if(status != NX_OK){ + if (status != NX_OK) { NXclose(&fileHandle); - NXDclose(dictHandle,NULL); + NXDclose(dictHandle, NULL); free(buffer); - SCWrite(pCon,"ERROR: failed to read data",eError); + SCWrite(pCon, "ERROR: failed to read data", eError); return 0; } /* - enforce network byte order - */ - for(i = 0; i < length; i++){ - buffer[2+i] = htonl(buffer[2+i]); + enforce network byte order + */ + for (i = 0; i < length; i++) { + buffer[2 + i] = htonl(buffer[2 + i]); } - SCWriteUUencoded(pCon,"framedata",buffer,(length+2)*sizeof(int)); + SCWriteUUencoded(pCon, "framedata", buffer, (length + 2) * sizeof(int)); NXclose(&fileHandle); - NXDclose(dictHandle,NULL); + NXDclose(dictHandle, NULL); free(buffer); return 1; } + /*=======================================================================*/ -int PSDFrameAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int PSDFrameAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pHistMem pHM; int nFrame; - if(argc < 2){ - SCWrite(pCon,"ERROR: Insufficient number of arguments to PSDFrame", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to PSDFrame", + eError); return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"hm") == 0){ - if(argc < 4){ - SCWrite(pCon,"ERROR: Insufficient number of arguments to PSDFrame", - eError); + if (strcmp(argv[1], "hm") == 0) { + if (argc < 4) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to PSDFrame", + eError); return 0; } - pHM = (pHistMem)FindCommandData(pSics,argv[2],"HistMem"); - if(pHM == NULL){ - SCWrite(pCon,"ERROR: Did not find histogram memory",eError); + pHM = (pHistMem) FindCommandData(pSics, argv[2], "HistMem"); + if (pHM == NULL) { + SCWrite(pCon, "ERROR: Did not find histogram memory", eError); return 0; } - nFrame = atoi(argv[3]); - return readHMFrame(pCon,pHM,nFrame); - } else if(strcmp(argv[1],"file") == 0){ - if(argc < 6 ){ - SCWrite(pCon,"ERROR: Insufficient number of arguments to PSDframe file", - eError); + nFrame = atoi(argv[3]); + return readHMFrame(pCon, pHM, nFrame); + } else if (strcmp(argv[1], "file") == 0) { + if (argc < 6) { + SCWrite(pCon, + "ERROR: Insufficient number of arguments to PSDframe file", + eError); return 0; } nFrame = atoi(argv[5]); - return readFileFrame(pCon,argv[2],argv[3],argv[4],nFrame); + return readFileFrame(pCon, argv[2], argv[3], argv[4], nFrame); } else { - SCWrite(pCon,"ERROR: subcommand to PSDframe not recognised",eError); + SCWrite(pCon, "ERROR: subcommand to PSDframe not recognised", eError); return 0; } } -/*======================================================================*/ -int MakeFrameFunc(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - return AddCommand(pSics,"PSDframe",PSDFrameAction,NULL,NULL); -} +/*======================================================================*/ +int MakeFrameFunc(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + return AddCommand(pSics, "PSDframe", PSDFrameAction, NULL, NULL); +} diff --git a/frame.h b/frame.h index af5a1efd..6788f09e 100644 --- a/frame.h +++ b/frame.h @@ -12,11 +12,11 @@ #ifndef SICSFRAME #define SICSFRAME -int MakeFrameFunc(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeFrameFunc(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -int PSDFrameAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int PSDFrameAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/fupa.c b/fupa.c index c77980a1..3db9b62c 100644 --- a/fupa.c +++ b/fupa.c @@ -47,127 +47,102 @@ #include "splitter.h" #include "fupa.h" - int EvaluateFuPa(pFuncTemplate pTemplate, int iFunc, int argc, char *argv[], - FuPaResult *pRes) - { - TokenList *pList = NULL; - TokenList *pCurrent; - int i; - int iRet = -1; - - pList = SplitArguments(argc,argv); - if(!pList) - { - strcpy(pRes->pError,"ERROR: cannot parse argument list"); - return iRet; - } +int EvaluateFuPa(pFuncTemplate pTemplate, int iFunc, int argc, + char *argv[], FuPaResult * pRes) +{ + TokenList *pList = NULL; + TokenList *pCurrent; + int i; + int iRet = -1; - /* first one must be name, try locate that one first */ - pCurrent = pList; - for(i = 0; i < iFunc; i++) - { - if(strcmp(pCurrent->text,pTemplate[i].name) == 0) - { - iRet = i; - break; - } - } - if(iRet == -1) - { - sprintf(pRes->pError,"ERROR: function %s not available",pCurrent->text); - goto end; - } + pList = SplitArguments(argc, argv); + if (!pList) { + strcpy(pRes->pError, "ERROR: cannot parse argument list"); + return iRet; + } - /* now try to find arguments */ - pRes->iArgs = pTemplate[iRet].iArgs; - for(i = 0; i < pRes->iArgs; i++) - { - pCurrent = pCurrent->pNext; - /* check presence */ - if(!pCurrent) - { - if(pTemplate[iRet].pArgs[i] == FUPAOPT) - { - pRes->Arg[i].iVal = 0; - goto end; - } - else - { - sprintf(pRes->pError,"ERROR: Insufficient number of arguments to %s", - pTemplate[iRet].name); - iRet = -1; - goto end; - } - } - /* check type, optional first */ - if(pTemplate[iRet].pArgs[i] == FUPAOPT) - { - pRes->Arg[i].iVal = 1; - strcpy(pRes->Arg[i].text,pCurrent->text); - if(pCurrent->Type == eInt) - { - pRes->Arg[i].fVal = pCurrent->iVal; - } - else if(pCurrent->Type == eFloat) - { - pRes->Arg[i].fVal = pCurrent->fVal; - } - goto end; - } - - /* now text */ - if(pTemplate[iRet].pArgs[i] == FUPATEXT) /* text is simple */ - { - strcpy(pRes->Arg[i].text,pCurrent->text); - continue; - } - - /* check integer */ - if(pTemplate[iRet].pArgs[i] == FUPAINT) - { - if(pCurrent->Type == eInt) - { - pRes->Arg[i].iVal = pCurrent->iVal; - continue; - } - else if(pCurrent->Type == eFloat) - { - pRes->Arg[i].iVal = (int)pCurrent->fVal; - continue; - } - else - { - sprintf(pRes->pError,"ERROR: expected integer parameter, got %s", - pCurrent->text); - iRet = -1; - goto end; - } - } + /* first one must be name, try locate that one first */ + pCurrent = pList; + for (i = 0; i < iFunc; i++) { + if (strcmp(pCurrent->text, pTemplate[i].name) == 0) { + iRet = i; + break; + } + } + if (iRet == -1) { + sprintf(pRes->pError, "ERROR: function %s not available", + pCurrent->text); + goto end; + } - /* check float */ - if(pTemplate[iRet].pArgs[i] == FUPAFLOAT) - { - if(pCurrent->Type == eInt) - { - pRes->Arg[i].fVal = (float)pCurrent->iVal; - continue; - } - else if(pCurrent->Type == eFloat) - { - pRes->Arg[i].fVal = pCurrent->fVal; - continue; - } - else - { - sprintf(pRes->pError,"ERROR: expected float parameter, got %s", - pCurrent->text); - iRet = -1; - goto end; - } - } - } + /* now try to find arguments */ + pRes->iArgs = pTemplate[iRet].iArgs; + for (i = 0; i < pRes->iArgs; i++) { + pCurrent = pCurrent->pNext; + /* check presence */ + if (!pCurrent) { + if (pTemplate[iRet].pArgs[i] == FUPAOPT) { + pRes->Arg[i].iVal = 0; + goto end; + } else { + sprintf(pRes->pError, + "ERROR: Insufficient number of arguments to %s", + pTemplate[iRet].name); + iRet = -1; + goto end; + } + } + /* check type, optional first */ + if (pTemplate[iRet].pArgs[i] == FUPAOPT) { + pRes->Arg[i].iVal = 1; + strcpy(pRes->Arg[i].text, pCurrent->text); + if (pCurrent->Type == eInt) { + pRes->Arg[i].fVal = pCurrent->iVal; + } else if (pCurrent->Type == eFloat) { + pRes->Arg[i].fVal = pCurrent->fVal; + } + goto end; + } + + /* now text */ + if (pTemplate[iRet].pArgs[i] == FUPATEXT) { /* text is simple */ + strcpy(pRes->Arg[i].text, pCurrent->text); + continue; + } + + /* check integer */ + if (pTemplate[iRet].pArgs[i] == FUPAINT) { + if (pCurrent->Type == eInt) { + pRes->Arg[i].iVal = pCurrent->iVal; + continue; + } else if (pCurrent->Type == eFloat) { + pRes->Arg[i].iVal = (int) pCurrent->fVal; + continue; + } else { + sprintf(pRes->pError, "ERROR: expected integer parameter, got %s", + pCurrent->text); + iRet = -1; + goto end; + } + } + + /* check float */ + if (pTemplate[iRet].pArgs[i] == FUPAFLOAT) { + if (pCurrent->Type == eInt) { + pRes->Arg[i].fVal = (float) pCurrent->iVal; + continue; + } else if (pCurrent->Type == eFloat) { + pRes->Arg[i].fVal = pCurrent->fVal; + continue; + } else { + sprintf(pRes->pError, "ERROR: expected float parameter, got %s", + pCurrent->text); + iRet = -1; + goto end; + } + } + } end: - DeleteTokenList(pList); - return iRet; - } - + DeleteTokenList(pList); + return iRet; +} diff --git a/fupa.h b/fupa.h index adcb0434..0d77f41b 100644 --- a/fupa.h +++ b/fupa.h @@ -28,31 +28,30 @@ #define FUPATEXT 0 #define FUPAINT 1 #define FUPAFLOAT 2 -#define FUPAOPT 3 /* optional argument, in this case text contains it - and iVal indicates its presence - */ - - typedef struct { - char *name; - int iArgs; - int pArgs[MAXARG]; - } FuncTemplate, *pFuncTemplate; - - typedef struct { - char text[80]; - int iVal; - float fVal; - } FuPaArg; - - typedef struct { - char pError[132]; - int iArgs; - FuPaArg Arg[MAXARG]; - } FuPaResult; - - int EvaluateFuPa(pFuncTemplate pTemplate,int iFunc, int argc, char *argv[], - FuPaResult *pRes); - - -#endif +#define FUPAOPT 3 /* optional argument, in this case text contains it + and iVal indicates its presence + */ +typedef struct { + char *name; + int iArgs; + int pArgs[MAXARG]; +} FuncTemplate, *pFuncTemplate; + +typedef struct { + char text[80]; + int iVal; + float fVal; +} FuPaArg; + +typedef struct { + char pError[132]; + int iArgs; + FuPaArg Arg[MAXARG]; +} FuPaResult; + +int EvaluateFuPa(pFuncTemplate pTemplate, int iFunc, int argc, + char *argv[], FuPaResult * pRes); + + +#endif diff --git a/genericcontroller.c b/genericcontroller.c index 028aa379..428b7c48 100644 --- a/genericcontroller.c +++ b/genericcontroller.c @@ -9,609 +9,634 @@ #include #include #include -#include +#include #include #include #include #include #include /*--------------------------------------------------------------------------*/ -static hdbCallbackReturn GenConSetCallback(pHdb node, void *userData, - pHdbMessage message){ - pSICSOBJ self = (pSICSOBJ)userData; - SConnection *pCon = NULL; - pGenController priv = NULL; - char command[1024]; - char value[80]; - int status, privilege; - pDynString data; - pHdbDataMessage mm = NULL; - - assert(self != NULL); - - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - - priv = (pGenController)self->pPrivate; - pCon = mm->callData; - - /* - * check rights - */ - memset(value,0,80); - if(GetHdbProperty(node,"priv",value,80) && pCon != NULL){ - privilege = usInternal; - if(strcmp(value,"manager") == 0){ - privilege = usMugger; - } - if(strcmp(value,"user") == 0){ - privilege = usUser; - } - if(!SCMatchRights(pCon,privilege)){ - return hdbAbort; - } - } - - /* - * check writeCommand - */ - memset(value,0,80); - GetHdbProperty(node,"writeCommand",value,80); - if(strlen(value) < 2){ - if(pCon != NULL){ - SCWrite(pCon,"ERROR: parameter is read-only",eError); - return hdbAbort; - } - return hdbAbort; - } +static hdbCallbackReturn GenConSetCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pSICSOBJ self = (pSICSOBJ) userData; + SConnection *pCon = NULL; + pGenController priv = NULL; + char command[1024]; + char value[80]; + int status, privilege; + pDynString data; + pHdbDataMessage mm = NULL; - /* - * check status - */ - memset(value,0,80); - GetHdbProperty(node,"status",value,80); - if(strstr(value,"idle") == NULL){ - return hdbAbort; + assert(self != NULL); + + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + + priv = (pGenController) self->pPrivate; + pCon = mm->callData; + + /* + * check rights + */ + memset(value, 0, 80); + if (GetHdbProperty(node, "priv", value, 80) && pCon != NULL) { + privilege = usInternal; + if (strcmp(value, "manager") == 0) { + privilege = usMugger; } - SetHdbProperty(node,"status","setting"); - data = formatValue(*(mm->v), node); - if(data != NULL){ - SetHdbProperty(node,"target",GetCharArray(data)); - DeleteDynString(data); + if (strcmp(value, "user") == 0) { + privilege = usUser; } - - /* - * issue command - */ - if(priv->enqueueNodeHead != NULL){ - priv->enqueueNodeHead(self,pCon,node); - } else { - if(pCon != NULL){ - SCWrite(pCon,"ERROR: generic controller NOT configured", - eError); - } - return hdbAbort; + if (!SCMatchRights(pCon, privilege)) { + return hdbAbort; } - - return hdbContinue; + } + + /* + * check writeCommand + */ + memset(value, 0, 80); + GetHdbProperty(node, "writeCommand", value, 80); + if (strlen(value) < 2) { + if (pCon != NULL) { + SCWrite(pCon, "ERROR: parameter is read-only", eError); + return hdbAbort; + } + return hdbAbort; + } + + /* + * check status + */ + memset(value, 0, 80); + GetHdbProperty(node, "status", value, 80); + if (strstr(value, "idle") == NULL) { + return hdbAbort; + } + SetHdbProperty(node, "status", "setting"); + data = formatValue(*(mm->v), node); + if (data != NULL) { + SetHdbProperty(node, "target", GetCharArray(data)); + DeleteDynString(data); + } + + /* + * issue command + */ + if (priv->enqueueNodeHead != NULL) { + priv->enqueueNodeHead(self, pCon, node); + } else { + if (pCon != NULL) { + SCWrite(pCon, "ERROR: generic controller NOT configured", eError); + } + return hdbAbort; + } + + return hdbContinue; } + /*--------------------------------------------------------------------------*/ -static hdbCallbackReturn GenConGetCallback(pHdb node, void *userData, - pHdbMessage message){ - pSICSOBJ self = (pSICSOBJ)userData; - SConnection *pCon = NULL; - pGenController priv = NULL; - char command[1024]; - char value[256]; - int status, privilege; - pHdbDataMessage mm = NULL; - - assert(self != NULL); - - if((mm = GetHdbGetMessage(message)) == NULL){ - return hdbContinue; - } - pCon = mm->callData; - - priv = (pGenController)self->pPrivate; - - /* - * check status - */ - memset(value,0,80); - GetHdbProperty(node,"status",value,80); - if(strstr(value,"idle") == NULL){ - return hdbContinue; - } - SetHdbProperty(node,"status","getting"); - - /* - * check readCommand - */ - memset(value,0,256); - GetHdbProperty(node,"readCommand",value,255); - if(strlen(value) < 2){ - return hdbAbort; +static hdbCallbackReturn GenConGetCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pSICSOBJ self = (pSICSOBJ) userData; + SConnection *pCon = NULL; + pGenController priv = NULL; + char command[1024]; + char value[256]; + int status, privilege; + pHdbDataMessage mm = NULL; + + assert(self != NULL); + + if ((mm = GetHdbGetMessage(message)) == NULL) { + return hdbContinue; + } + pCon = mm->callData; + + priv = (pGenController) self->pPrivate; + + /* + * check status + */ + memset(value, 0, 80); + GetHdbProperty(node, "status", value, 80); + if (strstr(value, "idle") == NULL) { + return hdbContinue; + } + SetHdbProperty(node, "status", "getting"); + + /* + * check readCommand + */ + memset(value, 0, 256); + GetHdbProperty(node, "readCommand", value, 255); + if (strlen(value) < 2) { + return hdbAbort; + } else { + if (priv->enqueueNode != NULL) { + priv->enqueueNode(self, pCon, node); } else { - if(priv->enqueueNode != NULL){ - priv->enqueueNode(self,pCon, node); - } else { - if(pCon != NULL){ - SCWrite(pCon,"ERROR: generic controller connection NOT configured", - eError); - } - return hdbAbort; - } - } - - /* - * Upper Level GetHipadabaPar will automatically return the - * node value. Which should have been updated through an update - * during the execution of enqueueNode - */ - - return hdbContinue; -} -/*---------------------------------------------------------------------------*/ -static pHdb MakeGenConPar(pSICSOBJ self, char *name, int type, int length){ - pHdb result = NULL; - pHdbCallback kalle = NULL; - - result = MakeHipadabaNode(name,type,length); - if(result == NULL){ - return NULL; - } - - kalle = MakeHipadabaCallback(GenConSetCallback, - self, - NULL); - if(kalle == NULL){ - return NULL; - } - AppendHipadabaCallback(result,kalle); - - kalle = MakeHipadabaCallback(GenConGetCallback, - self, - NULL); - - if(kalle == NULL){ - return NULL; - } - AppendHipadabaCallback(result,kalle); - - SetHdbProperty(result,"priv","manager"); - SetHdbProperty(result,"readCommand",""); - SetHdbProperty(result,"writeCommand",""); - SetHdbProperty(result,"replyCommand",""); - SetHdbProperty(result,"status","idle"); - - return result; -} -/*---------------------------------------------------------------------------*/ -static int MakeGenPar(pSICSOBJ self, SConnection *pCon, - char *argv[], int argc){ - char buffer[2048]; - int type, length = 1; - pHdb node = NULL , parent; - char *pPtr = NULL; - - if(argc < 5){ - snprintf(buffer,2048,"ERROR: insufficient arguments to %s makepar", - argv[0]); - SCWrite(pCon,buffer, eError); - return 0; - } - type = convertHdbType(argv[4]); - if(argc > 5){ - length = atoi(argv[5]); - } - strncpy(buffer,argv[3],2047); - pPtr = strrchr(buffer,'/'); - if(pPtr == NULL){ - node = MakeGenConPar(self, argv[3], type, length); - parent = self->objectNode; - } else { - *pPtr = '\0'; - pPtr++; - node = MakeGenConPar(self, pPtr, type, length); - parent = GetHipadabaNode(self->objectNode,buffer); - } - if(node == NULL || parent == NULL){ - SCWrite(pCon,"ERROR: failed to create node or parent not found", + if (pCon != NULL) { + SCWrite(pCon, + "ERROR: generic controller connection NOT configured", eError); - return 0; } - AddHipadabaChild(parent, node, pCon); - SCSendOK(pCon); - return 1; + return hdbAbort; + } + } + + /* + * Upper Level GetHipadabaPar will automatically return the + * node value. Which should have been updated through an update + * during the execution of enqueueNode + */ + + return hdbContinue; } + +/*---------------------------------------------------------------------------*/ +static pHdb MakeGenConPar(pSICSOBJ self, char *name, int type, int length) +{ + pHdb result = NULL; + pHdbCallback kalle = NULL; + + result = MakeHipadabaNode(name, type, length); + if (result == NULL) { + return NULL; + } + + kalle = MakeHipadabaCallback(GenConSetCallback, self, NULL); + if (kalle == NULL) { + return NULL; + } + AppendHipadabaCallback(result, kalle); + + kalle = MakeHipadabaCallback(GenConGetCallback, self, NULL); + + if (kalle == NULL) { + return NULL; + } + AppendHipadabaCallback(result, kalle); + + SetHdbProperty(result, "priv", "manager"); + SetHdbProperty(result, "readCommand", ""); + SetHdbProperty(result, "writeCommand", ""); + SetHdbProperty(result, "replyCommand", ""); + SetHdbProperty(result, "status", "idle"); + + return result; +} + +/*---------------------------------------------------------------------------*/ +static int MakeGenPar(pSICSOBJ self, SConnection * pCon, + char *argv[], int argc) +{ + char buffer[2048]; + int type, length = 1; + pHdb node = NULL, parent; + char *pPtr = NULL; + + if (argc < 5) { + snprintf(buffer, 2048, "ERROR: insufficient arguments to %s makepar", + argv[0]); + SCWrite(pCon, buffer, eError); + return 0; + } + type = convertHdbType(argv[4]); + if (argc > 5) { + length = atoi(argv[5]); + } + strncpy(buffer, argv[3], 2047); + pPtr = strrchr(buffer, '/'); + if (pPtr == NULL) { + node = MakeGenConPar(self, argv[3], type, length); + parent = self->objectNode; + } else { + *pPtr = '\0'; + pPtr++; + node = MakeGenConPar(self, pPtr, type, length); + parent = GetHipadabaNode(self->objectNode, buffer); + } + if (node == NULL || parent == NULL) { + SCWrite(pCon, "ERROR: failed to create node or parent not found", + eError); + return 0; + } + AddHipadabaChild(parent, node, pCon); + SCSendOK(pCon); + return 1; +} + /*=============================== ========================================== * This stuff is for the Tcl - AsynQueue implementation of GenericController * ==========================================================================*/ - typedef struct { - pHdb node; - pSICSOBJ obj; - SConnection *pCon; - pGenController priv; - pAsyncUnit assi; - pAsyncTxn trans; - char replyCommand[2048]; - } GenContext, *pGenContext; +typedef struct { + pHdb node; + pSICSOBJ obj; + SConnection *pCon; + pGenController priv; + pAsyncUnit assi; + pAsyncTxn trans; + char replyCommand[2048]; +} GenContext, *pGenContext; /*-------------------------------------------------------------------------- * This is called by AsyncQueue when a reply has been received. * -------------------------------------------------------------------------*/ - static int GenConTxnHandler(pAsyncTxn pTxn){ - pGenContext genCon = NULL; - char reply[10240]; - - genCon = (pGenContext)pTxn->cntx; - assert(genCon != NULL); - - memset(reply,0,10240*sizeof(char)); - switch(pTxn->txn_state){ - case ATX_NULL: - case ATX_ACTIVE: - return 1; - break; - case ATX_TIMEOUT: - strcpy(reply,"TIMEOUT"); - break; - case ATX_DISCO: - strcpy(reply,"DISCONNECTED"); - break; - case ATX_COMPLETE: - strncpy(reply,pTxn->inp_buf,10240); - break; - } - - genCon->priv->replyCallback(genCon->obj, genCon->pCon, - genCon->node, genCon->replyCommand, reply, strlen(reply)); - if(genCon->pCon != NULL){ - SCDeleteConnection(genCon->pCon); - } - free(genCon); - +static int GenConTxnHandler(pAsyncTxn pTxn) +{ + pGenContext genCon = NULL; + char reply[10240]; + + genCon = (pGenContext) pTxn->cntx; + assert(genCon != NULL); + + memset(reply, 0, 10240 * sizeof(char)); + switch (pTxn->txn_state) { + case ATX_NULL: + case ATX_ACTIVE: return 1; - } + break; + case ATX_TIMEOUT: + strcpy(reply, "TIMEOUT"); + break; + case ATX_DISCO: + strcpy(reply, "DISCONNECTED"); + break; + case ATX_COMPLETE: + strncpy(reply, pTxn->inp_buf, 10240); + break; + } + + genCon->priv->replyCallback(genCon->obj, genCon->pCon, + genCon->node, genCon->replyCommand, reply, + strlen(reply)); + if (genCon->pCon != NULL) { + SCDeleteConnection(genCon->pCon); + } + free(genCon); + + return 1; +} + /*--------------------------------------------------------------------------*/ -static char *formatCommand(pHdb node, SConnection *pCon){ - pDynString com = NULL; - char value[512]; - Tcl_Interp *pTcl = NULL; - int status; - - com = CreateDynString(256,128); - if(com == NULL){ - return NULL; - } - - memset(value,0,512); - GetHdbProperty(node,"status",value,512); - if(strstr(value,"set") != NULL){ - memset(value,0,512); - GetHdbProperty(node,"writeCommand",value,512); - DynStringConcat(com,value); - DynStringConcatChar(com,' '); - memset(value,0,512); - GetHdbProperty(node,"target",value,512); - DynStringConcat(com,value); - } else { - memset(value,0,512); - GetHdbProperty(node,"readCommand",value,512); - DynStringConcat(com,value); - } - pTcl = InterpGetTcl(pServ->pSics); - if(pCon != NULL){ - MacroPush(pCon); - } - status = Tcl_Eval(pTcl, GetCharArray(com)); - if(pCon != NULL){ - MacroPop(); - } - DeleteDynString(com); - if(status != TCL_OK){ - SetHdbProperty(node,"result", (char *)Tcl_GetStringResult(pTcl)); - return NULL; - } - return strdup(Tcl_GetStringResult(pTcl)); +static char *formatCommand(pHdb node, SConnection * pCon) +{ + pDynString com = NULL; + char value[512]; + Tcl_Interp *pTcl = NULL; + int status; + + com = CreateDynString(256, 128); + if (com == NULL) { + return NULL; + } + + memset(value, 0, 512); + GetHdbProperty(node, "status", value, 512); + if (strstr(value, "set") != NULL) { + memset(value, 0, 512); + GetHdbProperty(node, "writeCommand", value, 512); + DynStringConcat(com, value); + DynStringConcatChar(com, ' '); + memset(value, 0, 512); + GetHdbProperty(node, "target", value, 512); + DynStringConcat(com, value); + } else { + memset(value, 0, 512); + GetHdbProperty(node, "readCommand", value, 512); + DynStringConcat(com, value); + } + pTcl = InterpGetTcl(pServ->pSics); + if (pCon != NULL) { + MacroPush(pCon); + } + status = Tcl_Eval(pTcl, GetCharArray(com)); + if (pCon != NULL) { + MacroPop(); + } + DeleteDynString(com); + if (status != TCL_OK) { + SetHdbProperty(node, "result", (char *) Tcl_GetStringResult(pTcl)); + return NULL; + } + return strdup(Tcl_GetStringResult(pTcl)); } + /*--------------------------------------------------------------------------*/ -static pGenContext PrepareToEnque(pSICSOBJ self, SConnection *pCon, pHdb node){ - pGenContext result = NULL; - char *command = NULL; - pGenController priv = NULL; - - priv = (pGenController)self->pPrivate; - assert(priv != NULL); - - command = formatCommand(node, pCon); - if(command == NULL){ - return NULL; +static pGenContext PrepareToEnque(pSICSOBJ self, SConnection * pCon, + pHdb node) +{ + pGenContext result = NULL; + char *command = NULL; + pGenController priv = NULL; + + priv = (pGenController) self->pPrivate; + assert(priv != NULL); + + command = formatCommand(node, pCon); + if (command == NULL) { + return NULL; + } + + result = malloc(sizeof(GenContext)); + if (result == NULL) { + return NULL; + } + memset(result, 0, sizeof(GenContext)); + if (!GetHdbProperty(node, "replyCommand", result->replyCommand, 2048)) { + if (pCon != NULL) { + SCWrite(pCon, "ERROR: no replyCommand found", eError); } - - result = malloc(sizeof(GenContext)); - if(result == NULL){ - return NULL; - } - memset(result,0,sizeof(GenContext)); - if(!GetHdbProperty(node,"replyCommand",result->replyCommand,2048)){ - if(pCon != NULL){ - SCWrite(pCon,"ERROR: no replyCommand found",eError); - } - free(result); - return NULL; - } - - result->assi = AsyncUnitFromQueue((pAsyncQueue)priv->comContext); - if(result->assi == NULL){ - return NULL; - } - result->trans = AsyncUnitPrepareTxn(result->assi, - command,strlen(command), - GenConTxnHandler, - result, - 2048); - if(result->trans == NULL){ - return NULL; - } - result->node = node; - result->priv = priv; - result->obj = self; - result->pCon = SCCopyConnection(pCon); - priv->comError = GCOK; - free(command); - - return result; + free(result); + return NULL; + } + + result->assi = AsyncUnitFromQueue((pAsyncQueue) priv->comContext); + if (result->assi == NULL) { + return NULL; + } + result->trans = AsyncUnitPrepareTxn(result->assi, + command, strlen(command), + GenConTxnHandler, result, 2048); + if (result->trans == NULL) { + return NULL; + } + result->node = node; + result->priv = priv; + result->obj = self; + result->pCon = SCCopyConnection(pCon); + priv->comError = GCOK; + free(command); + + return result; } + /*---------------------------------------------------------------------------*/ -static int AsyncEnqueueNode(pSICSOBJ self, SConnection *pCon, pHdb node){ - pGenContext genCon = NULL; - - genCon = PrepareToEnque(self, pCon, node); - if(genCon == NULL){ - return 0; - } - return AsyncUnitEnqueueTxn(genCon->assi, genCon->trans); +static int AsyncEnqueueNode(pSICSOBJ self, SConnection * pCon, pHdb node) +{ + pGenContext genCon = NULL; + + genCon = PrepareToEnque(self, pCon, node); + if (genCon == NULL) { + return 0; + } + return AsyncUnitEnqueueTxn(genCon->assi, genCon->trans); } + /*---------------------------------------------------------------------------*/ -static int AsyncEnqueueNodeHead(pSICSOBJ self, SConnection *pCon, pHdb node){ - pGenContext genCon = NULL; - - genCon = PrepareToEnque(self, pCon, node); - if(genCon == NULL){ - return 0; - } - return AsyncUnitEnqueueHead(genCon->assi, genCon->trans); +static int AsyncEnqueueNodeHead(pSICSOBJ self, SConnection * pCon, + pHdb node) +{ + pGenContext genCon = NULL; + + genCon = PrepareToEnque(self, pCon, node); + if (genCon == NULL) { + return 0; + } + return AsyncUnitEnqueueHead(genCon->assi, genCon->trans); } + /*---------------------------------------------------------------------------*/ -static int AsyncReply(pSICSOBJ self, SConnection *pCon, pHdb node, - char *replyCommand, char *reply, int replylen){ - pDynString com = NULL; - Tcl_Interp *pTcl; - int status; - - SetHdbProperty(node,"result",reply); - - com = CreateDynString(256,128); - if(com == NULL){ - return 0; - } - DynStringConcat(com, replyCommand); - DynStringConcat(com," \""); - DynStringConcat(com, reply); - DynStringConcat(com,"\"\0"); - if(pCon != NULL){ - MacroPush(pCon); - } - pTcl = InterpGetTcl(pServ->pSics); - status = Tcl_Eval(pTcl,GetCharArray(com)); - if(pCon != NULL){ - MacroPop(); - } - DeleteDynString(com); - if(status != TCL_OK){ - SetHdbProperty(node,"lastError",(char *)Tcl_GetStringResult(pTcl)); - } - return status; +static int AsyncReply(pSICSOBJ self, SConnection * pCon, pHdb node, + char *replyCommand, char *reply, int replylen) +{ + pDynString com = NULL; + Tcl_Interp *pTcl; + int status; + + SetHdbProperty(node, "result", reply); + + com = CreateDynString(256, 128); + if (com == NULL) { + return 0; + } + DynStringConcat(com, replyCommand); + DynStringConcat(com, " \""); + DynStringConcat(com, reply); + DynStringConcat(com, "\"\0"); + if (pCon != NULL) { + MacroPush(pCon); + } + pTcl = InterpGetTcl(pServ->pSics); + status = Tcl_Eval(pTcl, GetCharArray(com)); + if (pCon != NULL) { + MacroPop(); + } + DeleteDynString(com); + if (status != TCL_OK) { + SetHdbProperty(node, "lastError", (char *) Tcl_GetStringResult(pTcl)); + } + return status; } + /*============= GenController Object Functions ==============================*/ -static int ConnectAsync(pSICSOBJ self, SConnection *pCon, - char *argv[], int argc){ - pGenController priv = NULL; - pAsyncQueue assi = NULL; - char buffer[2048]; - pAsyncUnit uni = NULL; +static int ConnectAsync(pSICSOBJ self, SConnection * pCon, + char *argv[], int argc) +{ + pGenController priv = NULL; + pAsyncQueue assi = NULL; + char buffer[2048]; + pAsyncUnit uni = NULL; - priv = (pGenController)self->pPrivate; - assert(priv != NULL); - - if(argc < 4){ - snprintf(buffer,2048,"ERROR: insufficient arguments to %s asynconnect", - argv[0]); - SCWrite(pCon,buffer, eError); - return 0; - } - - assi = (pAsyncQueue)FindCommandData(pServ->pSics, argv[3],"AsyncQueue"); - if(assi == NULL){ - snprintf(buffer,2048,"ERROR: %s not found or no AsyncQueue", argv[3]); - SCWrite(pCon,buffer,eError); - return 0; - } - - priv->comContext = assi; - priv->killComContext = NULL; /* not ours, cleaned up by AsyncQueue module */ - priv->enqueueNode = AsyncEnqueueNode; - priv->enqueueNodeHead = AsyncEnqueueNodeHead; - priv->replyCallback = AsyncReply; - priv->comError = GCOK; + priv = (pGenController) self->pPrivate; + assert(priv != NULL); - /* - * This unit is solely for the purpose of receiving event notifications - */ - uni = AsyncUnitFromQueue(assi); + if (argc < 4) { + snprintf(buffer, 2048, + "ERROR: insufficient arguments to %s asynconnect", argv[0]); + SCWrite(pCon, buffer, eError); + return 0; + } - SCSendOK(pCon); - return 1; + assi = + (pAsyncQueue) FindCommandData(pServ->pSics, argv[3], "AsyncQueue"); + if (assi == NULL) { + snprintf(buffer, 2048, "ERROR: %s not found or no AsyncQueue", + argv[3]); + SCWrite(pCon, buffer, eError); + return 0; + } + + priv->comContext = assi; + priv->killComContext = NULL; /* not ours, cleaned up by AsyncQueue module */ + priv->enqueueNode = AsyncEnqueueNode; + priv->enqueueNodeHead = AsyncEnqueueNodeHead; + priv->replyCallback = AsyncReply; + priv->comError = GCOK; + + /* + * This unit is solely for the purpose of receiving event notifications + */ + uni = AsyncUnitFromQueue(assi); + + SCSendOK(pCon); + return 1; } + /*---------------------------------------------------------------------------*/ -int GenControllerConfigure(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - pSICSOBJ controller = NULL; - pGenController self = NULL; - char buffer[2048]; - - if(argc < 3){ - snprintf(buffer,2048,"ERROR: insufficient arguments to %s", argv[0]); - SCWrite(pCon,buffer,eError); - return 0; - } - - controller = (pSICSOBJ)FindCommandData(pSics,argv[2], "GenericController"); - if(controller == NULL){ - snprintf(buffer,2048,"ERROR: controller %s not found", argv[2]); - SCWrite(pCon,buffer,eError); - return 0; - } - - strtolower(argv[1]); - if(strcmp(argv[1],"makepar") == 0){ - return MakeGenPar(controller,pCon,argv,argc); - } else if(strcmp(argv[1],"asynconnect") == 0){ - return ConnectAsync(controller, pCon, argv, argc); - } else { - SCWrite(pCon,"ERROR: argument to GenControllerConfigure not found", +int GenControllerConfigure(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pSICSOBJ controller = NULL; + pGenController self = NULL; + char buffer[2048]; + + if (argc < 3) { + snprintf(buffer, 2048, "ERROR: insufficient arguments to %s", argv[0]); + SCWrite(pCon, buffer, eError); + return 0; + } + + controller = + (pSICSOBJ) FindCommandData(pSics, argv[2], "GenericController"); + if (controller == NULL) { + snprintf(buffer, 2048, "ERROR: controller %s not found", argv[2]); + SCWrite(pCon, buffer, eError); + return 0; + } + + strtolower(argv[1]); + if (strcmp(argv[1], "makepar") == 0) { + return MakeGenPar(controller, pCon, argv, argc); + } else if (strcmp(argv[1], "asynconnect") == 0) { + return ConnectAsync(controller, pCon, argv, argc); + } else { + SCWrite(pCon, "ERROR: argument to GenControllerConfigure not found", eError); - return 0; - } - - return 1; -} -/*---------------------------------------------------------------------------*/ -static void killGeneric(void *data){ - pGenController self = (pGenController)data; - - if(self == NULL){ - return; - } - if(self->comContext != NULL && self->killComContext != NULL){ - self->killComContext(self->comContext); - } - free(self); -} -/*---------------------------------------------------------------------------*/ -static int EnqueFunc(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pGenController priv = NULL; - pHdb node = NULL; - char buffer[512]; - - priv = (pGenController)self->pPrivate; - assert(priv != NULL); - assert(nPar >= 1); - - node = GetHipadabaNode(self->objectNode,par[0]->value.v.text); - if(node == NULL){ - snprintf(buffer,511,"ERROR: node %s to enqueue not found", - par[0]->value.v.text); - SCWrite(pCon,buffer,eError); - return 0; - } - - if(priv->enqueueNode != NULL){ - priv->enqueueNode(self, pCon, node); - } else { - SCWrite(pCon,"ERROR: GenController NOT configured",eError); - return 0; - } - return 1; -} -/*---------------------------------------------------------------------------*/ -static int EnqueHeadFunc(pSICSOBJ self, SConnection *pCon, Hdb commandNode, - pHdb par[], int nPar){ - pGenController priv = NULL; - pHdb node = NULL; - char buffer[512]; - - priv = (pGenController)self->pPrivate; - assert(priv != NULL); - assert(nPar >= 1); - - node = GetHipadabaNode(self->objectNode,par[0]->value.v.text); - if(node == NULL){ - snprintf(buffer,511,"ERROR: node %s to enqueue not found", - par[0]->value.v.text); - SCWrite(pCon,buffer,eError); - return 0; - } - - if(priv->enqueueNodeHead != NULL){ - priv->enqueueNodeHead(self, pCon, node); - } else { - SCWrite(pCon,"ERROR: GenController NOT configured",eError); - return 0; - } - return 1; -} -/*---------------------------------------------------------------------------*/ -int GenControllerFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - pSICSOBJ pNew = NULL; - pGenController priv = NULL; - hdbValue funcValue, textValue; - pHdb node = NULL; - char line[132]; - int status; - - if(argc < 2){ - SCWrite(pCon, - "ERROR: insufficient number of arguments to GenControllerFactrory", - eError); - return 0; - } - priv = malloc(sizeof(GenController)); - if(priv == NULL){ - SCWrite(pCon,"ERROR: out of memory in GenControllerFactory", - eError); - return 0; - } - memset(priv,0,sizeof(GenController)); - - pNew = MakeSICSOBJ(argv[1],"GenericController"); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory in GenControllerFactory", - eError); - return 0; - } - pNew->pPrivate = priv; - pNew->KillPrivate = killGeneric; - - textValue = MakeHdbText("Undefined"); - funcValue = MakeHdbFunc((voidFunc *)EnqueFunc); - node = MakeSICSHdbPar("enqueue",usUser, funcValue); - AddSICSHdbPar(node,"node",usUser,textValue); - AppendHipadabaCallback(node,MakeSICSFuncCallback(pNew)); - AddHipadabaChild(pNew->objectNode,node,NULL); - - funcValue = MakeHdbFunc((voidFunc *)EnqueHeadFunc); - node = MakeSICSHdbPar("enqueuehead",usUser, funcValue); - AddSICSHdbPar(node,"node",usUser,textValue); - AppendHipadabaCallback(node,MakeSICSFuncCallback(pNew)); - AddHipadabaChild(pNew->objectNode,node,NULL); - - status = AddCommand(pSics, - argv[1], - InvokeSICSOBJ, - KillSICSOBJ, - pNew); - if(status != 1){ - KillSICSOBJ(pNew); - SCPrintf(pCon,eError,"ERROR: failed create duplicate command %s", argv[1]); - return 0; - } - SCSendOK(pCon); - - return 1; + return 0; + } + + return 1; } +/*---------------------------------------------------------------------------*/ +static void killGeneric(void *data) +{ + pGenController self = (pGenController) data; + + if (self == NULL) { + return; + } + if (self->comContext != NULL && self->killComContext != NULL) { + self->killComContext(self->comContext); + } + free(self); +} + +/*---------------------------------------------------------------------------*/ +static int EnqueFunc(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + pGenController priv = NULL; + pHdb node = NULL; + char buffer[512]; + + priv = (pGenController) self->pPrivate; + assert(priv != NULL); + assert(nPar >= 1); + + node = GetHipadabaNode(self->objectNode, par[0]->value.v.text); + if (node == NULL) { + snprintf(buffer, 511, "ERROR: node %s to enqueue not found", + par[0]->value.v.text); + SCWrite(pCon, buffer, eError); + return 0; + } + + if (priv->enqueueNode != NULL) { + priv->enqueueNode(self, pCon, node); + } else { + SCWrite(pCon, "ERROR: GenController NOT configured", eError); + return 0; + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int EnqueHeadFunc(pSICSOBJ self, SConnection * pCon, + Hdb commandNode, pHdb par[], int nPar) +{ + pGenController priv = NULL; + pHdb node = NULL; + char buffer[512]; + + priv = (pGenController) self->pPrivate; + assert(priv != NULL); + assert(nPar >= 1); + + node = GetHipadabaNode(self->objectNode, par[0]->value.v.text); + if (node == NULL) { + snprintf(buffer, 511, "ERROR: node %s to enqueue not found", + par[0]->value.v.text); + SCWrite(pCon, buffer, eError); + return 0; + } + + if (priv->enqueueNodeHead != NULL) { + priv->enqueueNodeHead(self, pCon, node); + } else { + SCWrite(pCon, "ERROR: GenController NOT configured", eError); + return 0; + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +int GenControllerFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pSICSOBJ pNew = NULL; + pGenController priv = NULL; + hdbValue funcValue, textValue; + pHdb node = NULL; + char line[132]; + int status; + + if (argc < 2) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to GenControllerFactrory", + eError); + return 0; + } + priv = malloc(sizeof(GenController)); + if (priv == NULL) { + SCWrite(pCon, "ERROR: out of memory in GenControllerFactory", eError); + return 0; + } + memset(priv, 0, sizeof(GenController)); + + pNew = MakeSICSOBJ(argv[1], "GenericController"); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory in GenControllerFactory", eError); + return 0; + } + pNew->pPrivate = priv; + pNew->KillPrivate = killGeneric; + + textValue = MakeHdbText("Undefined"); + funcValue = MakeHdbFunc((voidFunc *) EnqueFunc); + node = MakeSICSHdbPar("enqueue", usUser, funcValue); + AddSICSHdbPar(node, "node", usUser, textValue); + AppendHipadabaCallback(node, MakeSICSFuncCallback(pNew)); + AddHipadabaChild(pNew->objectNode, node, NULL); + + funcValue = MakeHdbFunc((voidFunc *) EnqueHeadFunc); + node = MakeSICSHdbPar("enqueuehead", usUser, funcValue); + AddSICSHdbPar(node, "node", usUser, textValue); + AppendHipadabaCallback(node, MakeSICSFuncCallback(pNew)); + AddHipadabaChild(pNew->objectNode, node, NULL); + + status = AddCommand(pSics, argv[1], InvokeSICSOBJ, KillSICSOBJ, pNew); + if (status != 1) { + KillSICSOBJ(pNew); + SCPrintf(pCon, eError, "ERROR: failed create duplicate command %s", + argv[1]); + return 0; + } + SCSendOK(pCon); + + return 1; +} diff --git a/genericcontroller.h b/genericcontroller.h index 2ba805a7..85eb849b 100644 --- a/genericcontroller.h +++ b/genericcontroller.h @@ -17,21 +17,21 @@ #define GCOK 5000 #define GCRECONNECT 5003 #define GCRETRY 5004 - -typedef struct { - int (*enqueueNode)(pSICSOBJ self, SConnection *pCon, pHdb node); - int (*enqueueNodeHead)(pSICSOBJ self, SConnection *pCon, pHdb node); - int (*replyCallback)(pSICSOBJ self, SConnection *pCon, pHdb node, - char *replyCommand, char *reply, int replylen); - void *comContext; - void (*killComContext)(void *data); - int comError; -}GenController, *pGenController; -/*---------------------------------------------------------------------------*/ -int GenControllerFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); -/*---------------------------------------------------------------------------*/ -int GenControllerConfigure(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); -#endif /*GENERICCONTROLLER_H_*/ +typedef struct { + int (*enqueueNode) (pSICSOBJ self, SConnection * pCon, pHdb node); + int (*enqueueNodeHead) (pSICSOBJ self, SConnection * pCon, pHdb node); + int (*replyCallback) (pSICSOBJ self, SConnection * pCon, pHdb node, + char *replyCommand, char *reply, int replylen); + void *comContext; + void (*killComContext) (void *data); + int comError; +} GenController, *pGenController; +/*---------------------------------------------------------------------------*/ +int GenControllerFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); +/*---------------------------------------------------------------------------*/ +int GenControllerConfigure(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + +#endif /*GENERICCONTROLLER_H_ */ diff --git a/geninter.c b/geninter.c index 0567494b..8e0037b9 100644 --- a/geninter.c +++ b/geninter.c @@ -12,8 +12,9 @@ #include /*---------------------------------------------------------------------------*/ -int GenDrivableFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - - return 1; +int GenDrivableFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + + return 1; } diff --git a/geninter.h b/geninter.h index 05a469cd..d6dc01f3 100644 --- a/geninter.h +++ b/geninter.h @@ -12,8 +12,8 @@ * make a drivable parameter: * Usage: * MakeGenDrivable name par-node control-node - */ -int GenDrivableFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); + */ +int GenDrivableFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); -#endif /*GENINTER_H_*/ +#endif /*GENINTER_H_ */ diff --git a/gpibcontroller.c b/gpibcontroller.c index cff8c1f2..769b9ad2 100644 --- a/gpibcontroller.c +++ b/gpibcontroller.c @@ -15,24 +15,33 @@ #include "gpibcontroller.h" #include "gpibcontroller.i" /*----------------------------------------------------------------------*/ -int GPIBattach(pGPIB self, int boardNo, int address, - int secondaryAddress, int tmo, int eot, int eos){ - return self->attach(boardNo,address,secondaryAddress,tmo,eot,eos); +int GPIBattach(pGPIB self, int boardNo, int address, + int secondaryAddress, int tmo, int eot, int eos) +{ + return self->attach(boardNo, address, secondaryAddress, tmo, eot, eos); } + /*---------------------------------------------------------------------*/ -int GPIBdetach(pGPIB self, int devID){ +int GPIBdetach(pGPIB self, int devID) +{ return self->detach(devID); } + /*----------------------------------------------------------------------*/ -int GPIBsend(pGPIB self, int devID, void *buffer, int bytesToWrite){ - return self->send(devID, buffer,bytesToWrite); +int GPIBsend(pGPIB self, int devID, void *buffer, int bytesToWrite) +{ + return self->send(devID, buffer, bytesToWrite); } + /*--------------------------------------------------------------------*/ -int GPIBread(pGPIB self, int devID, void *buffer, int bytesToRead){ - return self->read(devID, buffer,bytesToRead); +int GPIBread(pGPIB self, int devID, void *buffer, int bytesToRead) +{ + return self->read(devID, buffer, bytesToRead); } + /*--------------------------------------------------------------------*/ -char *GPIBreadTillTerm(pGPIB self, int devID, int terminator){ +char *GPIBreadTillTerm(pGPIB self, int devID, int terminator) +{ char buchstabe[2]; Tcl_DString buffer; char *result = NULL; @@ -40,71 +49,91 @@ char *GPIBreadTillTerm(pGPIB self, int devID, int terminator){ Tcl_DStringInit(&buffer); buchstabe[1] = '\0'; - GPIBread(self,devID,buchstabe,1); - while(buchstabe[0] != (unsigned char)terminator){ - Tcl_DStringAppend(&buffer,buchstabe,-1); - status = GPIBread(self,devID,buchstabe,1); - if(status != 1){ - Tcl_DStringAppend(&buffer,"GPIB Read Error",-1); + GPIBread(self, devID, buchstabe, 1); + while (buchstabe[0] != (unsigned char) terminator) { + Tcl_DStringAppend(&buffer, buchstabe, -1); + status = GPIBread(self, devID, buchstabe, 1); + if (status != 1) { + Tcl_DStringAppend(&buffer, "GPIB Read Error", -1); break; } - } + } result = strdup(Tcl_DStringValue(&buffer)); Tcl_DStringFree(&buffer); return result; } + /*--------------------------------------------------------------------*/ -void GPIBclear(pGPIB self, int devID){ +void GPIBclear(pGPIB self, int devID) +{ self->clear(devID); } + /*--------------------------------------------------------------------*/ -void GPIBerrorDescription(pGPIB self, int code, char *buffer, int maxBuf){ - self->getErrorDescription(code, buffer,maxBuf); +void GPIBerrorDescription(pGPIB self, int code, char *buffer, int maxBuf) +{ + self->getErrorDescription(code, buffer, maxBuf); } + /*------------------------------------------------------------------- These are void implementations of the functions for simulation purposes ----------------------------------------------------------------------*/ static int SIMattach(int boardNo, int address, int secondaryAddress, - int tmo, int eoi, int eot){ + int tmo, int eoi, int eot) +{ return 1; } + /*----------------------------------------------------------------------*/ -static int SIMdetach(int devID){ +static int SIMdetach(int devID) +{ return 1; } + /*---------------------------------------------------------------------*/ -static int SIMsend(int devID, void *buffer, int bytesToWrite){ +static int SIMsend(int devID, void *buffer, int bytesToWrite) +{ return 1; } + /*--------------------------------------------------------------------*/ -static int SIMread(int devID, void *buffer, int bytesToRead){ +static int SIMread(int devID, void *buffer, int bytesToRead) +{ return 1; } + /*--------------------------------------------------------------------*/ -static int SIMclear(int devID){ +static int SIMclear(int devID) +{ return 1; } + /*---------------------------------------------------------------------*/ -static void SIMerror(int code, char *buffer, int maxBuf){ - strncpy(buffer,"Unknown simulated error",maxBuf); +static void SIMerror(int code, char *buffer, int maxBuf) +{ + strncpy(buffer, "Unknown simulated error", maxBuf); } + /*---------------------------------------------------------------------*/ -void GPIBKill(void *pData){ +void GPIBKill(void *pData) +{ pGPIB self = NULL; - if(pData != NULL){ - self = (pGPIB)pData; - if(self->pDes){ + if (pData != NULL) { + self = (pGPIB) pData; + if (self->pDes) { DeleteDescriptor(self->pDes); } free(pData); } } + /*---------------------------------------------------------------------*/ -int GPIBAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pGPIB self = (pGPIB)pData; - int boardID, devID, tmo, count, eoi, eot, address, +int GPIBAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pGPIB self = (pGPIB) pData; + int boardID, devID, tmo, count, eoi, eot, address, secondaryAddress, status, terminator, value; char pBuffer[1024]; char *result = NULL; @@ -112,225 +141,226 @@ int GPIBAction(SConnection *pCon, SicsInterp *pSics, void *pData, assert(self != NULL); /* - Only managers will be allowed to wrestle directly with GPIB - controllers. - */ - if(!SCinMacro(pCon)){ - if(!SCMatchRights(pCon,usMugger)){ + Only managers will be allowed to wrestle directly with GPIB + controllers. + */ + if (!SCinMacro(pCon)) { + if (!SCMatchRights(pCon, usMugger)) { return 0; } } - if(argc > 1){ + if (argc > 1) { strtolower(argv[1]); - if(strcmp(argv[1],"attach") == 0){ + if (strcmp(argv[1], "attach") == 0) { /* the attach command */ - if(argc < 8){ - SCWrite(pCon,"ERROR: insufficient number of arguments to attach", - eError); - return 0; + if (argc < 8) { + SCWrite(pCon, "ERROR: insufficient number of arguments to attach", + eError); + return 0; } count = 0; - count += Tcl_GetInt(pSics->pTcl,argv[2],&boardID); - count += Tcl_GetInt(pSics->pTcl,argv[3],&address); - count += Tcl_GetInt(pSics->pTcl,argv[4],&secondaryAddress); - count += Tcl_GetInt(pSics->pTcl,argv[5],&tmo); - count += Tcl_GetInt(pSics->pTcl,argv[6],&eot); - count += Tcl_GetInt(pSics->pTcl,argv[7],&eoi); - if(count != 6*TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + count += Tcl_GetInt(pSics->pTcl, argv[2], &boardID); + count += Tcl_GetInt(pSics->pTcl, argv[3], &address); + count += Tcl_GetInt(pSics->pTcl, argv[4], &secondaryAddress); + count += Tcl_GetInt(pSics->pTcl, argv[5], &tmo); + count += Tcl_GetInt(pSics->pTcl, argv[6], &eot); + count += Tcl_GetInt(pSics->pTcl, argv[7], &eoi); + if (count != 6 * TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - status = GPIBattach(self,boardID, address, secondaryAddress, - tmo,eot,eoi); - if(status > 0){ - sprintf(pBuffer,"%d",status); - SCWrite(pCon,pBuffer,eValue); - return 1; + status = GPIBattach(self, boardID, address, secondaryAddress, + tmo, eot, eoi); + if (status > 0) { + sprintf(pBuffer, "%d", status); + SCWrite(pCon, pBuffer, eValue); + return 1; } else { - sprintf(pBuffer,"ERROR: error %d on attach", status); - SCWrite(pCon,pBuffer,eError); - return 0; + sprintf(pBuffer, "ERROR: error %d on attach", status); + SCWrite(pCon, pBuffer, eError); + return 0; } - } else if(strcmp(argv[1],"detach") == 0){ + } else if (strcmp(argv[1], "detach") == 0) { /* - detach command - */ - if(argc < 2){ - SCWrite(pCon,"ERROR: insufficient number of arguments to dettach", - eError); - return 0; + detach command + */ + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient number of arguments to dettach", + eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[2],&devID) != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[2], &devID) != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - status = GPIBdetach(self,devID); - if(status > 0){ - SCSendOK(pCon); - return 1; + status = GPIBdetach(self, devID); + if (status > 0) { + SCSendOK(pCon); + return 1; } else { - sprintf(pBuffer,"ERROR: error %d on dettach", status); - SCWrite(pCon,pBuffer,eError); - return 0; + sprintf(pBuffer, "ERROR: error %d on dettach", status); + SCWrite(pCon, pBuffer, eError); + return 0; } - } else if(strcmp(argv[1],"clear") == 0){ + } else if (strcmp(argv[1], "clear") == 0) { /* - clear command - */ - if(argc < 2){ - SCWrite(pCon,"ERROR: insufficient number of arguments to clear", - eError); - return 0; + clear command + */ + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient number of arguments to clear", + eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[2],&devID) != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[2], &devID) != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - GPIBclear(self,devID); + GPIBclear(self, devID); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"send") == 0){ + } else if (strcmp(argv[1], "send") == 0) { /* - send command - */ - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to send", - eError); - return 0; + send command + */ + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to send", + eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[2],&devID) != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[2], &devID) != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - Arg2Text(argc-3,argv+3,pBuffer,1023); - status = GPIBsend(self,devID,pBuffer, (int)strlen(pBuffer)); - if(status > 0){ - SCSendOK(pCon); - return 1; + Arg2Text(argc - 3, argv + 3, pBuffer, 1023); + status = GPIBsend(self, devID, pBuffer, (int) strlen(pBuffer)); + if (status > 0) { + SCSendOK(pCon); + return 1; } else { - sprintf(pBuffer,"ERROR: error %d on send", status); - SCWrite(pCon,pBuffer,eError); - return 0; + sprintf(pBuffer, "ERROR: error %d on send", status); + SCWrite(pCon, pBuffer, eError); + return 0; } - } else if(strcmp(argv[1],"sendwithterm") == 0){ + } else if (strcmp(argv[1], "sendwithterm") == 0) { /* - send command - */ - if(argc < 5){ - SCWrite(pCon,"ERROR: insufficient number of arguments to sendwithterm", - eError); - return 0; + send command + */ + if (argc < 5) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to sendwithterm", + eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[2],&devID) != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[2], &devID) != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[4],&terminator) != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[4], &terminator) != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - strncpy(pBuffer,argv[3], 1024); - pBuffer[strlen(pBuffer)] = (char)terminator; - status = GPIBsend(self,devID,pBuffer, (int)strlen(pBuffer)); - if(status > 0){ - SCSendOK(pCon); - return 1; + strncpy(pBuffer, argv[3], 1024); + pBuffer[strlen(pBuffer)] = (char) terminator; + status = GPIBsend(self, devID, pBuffer, (int) strlen(pBuffer)); + if (status > 0) { + SCSendOK(pCon); + return 1; } else { - sprintf(pBuffer,"ERROR: error %d on send", status); - SCWrite(pCon,pBuffer,eError); - return 0; + sprintf(pBuffer, "ERROR: error %d on send", status); + SCWrite(pCon, pBuffer, eError); + return 0; } - } else if(strcmp(argv[1],"read") == 0){ + } else if (strcmp(argv[1], "read") == 0) { /* - read command - */ - if(argc < 2){ - SCWrite(pCon,"ERROR: insufficient number of arguments to read", - eError); - return 0; + read command + */ + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient number of arguments to read", + eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[2],&devID) != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[2], &devID) != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - status = GPIBread(self,devID,pBuffer, 1023); - if(status > 0){ - SCWrite(pCon,pBuffer,eValue); - return 1; + status = GPIBread(self, devID, pBuffer, 1023); + if (status > 0) { + SCWrite(pCon, pBuffer, eValue); + return 1; } else { - sprintf(pBuffer,"ERROR: error %d on read", status); - SCWrite(pCon,pBuffer,eError); - return 0; + sprintf(pBuffer, "ERROR: error %d on read", status); + SCWrite(pCon, pBuffer, eError); + return 0; } - } else if(strcmp(argv[1],"readnum") == 0){ + } else if (strcmp(argv[1], "readnum") == 0) { /* - readnum command - */ - if(argc < 2){ - SCWrite(pCon,"ERROR: insufficient number of arguments to read", - eError); - return 0; + readnum command + */ + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient number of arguments to read", + eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[2],&devID) != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[2], &devID) != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - status = GPIBread(self,devID,&value, 4); - if(status > 0){ - sprintf(pBuffer,"gpib %d = %d",devID,value); - SCWrite(pCon,pBuffer,eValue); - return 1; + status = GPIBread(self, devID, &value, 4); + if (status > 0) { + sprintf(pBuffer, "gpib %d = %d", devID, value); + SCWrite(pCon, pBuffer, eValue); + return 1; } else { /* - sprintf(pBuffer,"ERROR: error %d on read", status); - SCWrite(pCon,pBuffer,eError); - */ - return 0; + sprintf(pBuffer,"ERROR: error %d on read", status); + SCWrite(pCon,pBuffer,eError); + */ + return 0; } - } else if(strcmp(argv[1],"readtillterm") == 0){ + } else if (strcmp(argv[1], "readtillterm") == 0) { /* - read command - */ - if(argc < 3){ - SCWrite(pCon,"ERROR: insufficient number of arguments to read", - eError); - return 0; + read command + */ + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient number of arguments to read", + eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[2],&devID) != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[2], &devID) != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[3],&terminator) != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert arguments to integer", - eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[3], &terminator) != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert arguments to integer", + eError); + return 0; } - result = GPIBreadTillTerm(self,devID,terminator); - if(result != NULL){ - SCWrite(pCon,result,eValue); - free(result); - return 1; + result = GPIBreadTillTerm(self, devID, terminator); + if (result != NULL) { + SCWrite(pCon, result, eValue); + free(result); + return 1; } else { - SCWrite(pCon,"ERROR: failed to read at GPIB",eError); - return 0; + SCWrite(pCon, "ERROR: failed to read at GPIB", eError); + return 0; } } else { - SCWrite(pCon,"ERROR: command not recognized",eError); + SCWrite(pCon, "ERROR: command not recognized", eError); return 0; } } else { - SCWrite(pCon,"ERROR: no command given to GPIB",eError); + SCWrite(pCon, "ERROR: no command given to GPIB", eError); return 0; } } @@ -340,45 +370,41 @@ int GPIBAction(SConnection *pCon, SicsInterp *pSics, void *pData, extern void NIassign(pGPIB self); #endif -int MakeGPIB(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int MakeGPIB(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pGPIB self = NULL; - if(argc < 3){ - SCWrite(pCon,"ERROR: insufficient number of arguments to MakeGPIB", - eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient number of arguments to MakeGPIB", + eError); return 0; } - self = (pGPIB)malloc(sizeof(GPIB)); - if(self == NULL){ - SCWrite(pCon,"ERROR: cannot allocate memory in MakeGPIB",eError); + self = (pGPIB) malloc(sizeof(GPIB)); + if (self == NULL) { + SCWrite(pCon, "ERROR: cannot allocate memory in MakeGPIB", eError); return 0; } - memset(self,0,sizeof(GPIB)); + memset(self, 0, sizeof(GPIB)); self->pDes = CreateDescriptor("GPIB"); strtolower(argv[2]); - if(strcmp(argv[2],"sim") == 0){ + if (strcmp(argv[2], "sim") == 0) { self->attach = SIMattach; self->detach = SIMdetach; - self->send = SIMsend; + self->send = SIMsend; self->read = SIMread; self->clear = SIMclear; self->getErrorDescription = SIMerror; #ifdef HAVENI - } else if(strcmp(argv[2],"ni") == 0){ + } else if (strcmp(argv[2], "ni") == 0) { NIassign(self); #endif } else { - SCWrite(pCon,"ERROR: GPIB driver not recognised",eError); + SCWrite(pCon, "ERROR: GPIB driver not recognised", eError); return 0; } - return AddCommand(pSics,argv[1],GPIBAction,GPIBKill,self); + return AddCommand(pSics, argv[1], GPIBAction, GPIBKill, self); } - - - - - diff --git a/gpibcontroller.h b/gpibcontroller.h index 62f19b5e..3a799eb9 100644 --- a/gpibcontroller.h +++ b/gpibcontroller.h @@ -21,28 +21,26 @@ #define GPIBENOL 2 - typedef struct __GPIB *pGPIB; +typedef struct __GPIB *pGPIB; - int GPIBattach(pGPIB self, int boardNo, - int address, int secondaryAddress, - int tmo, int eot, int eos); - int GPIBdetach(pGPIB self, int devID); - int GPIBsend(pGPIB self, int devID, void *buffer, int bytesToWrite); - int GPIBread(pGPIB self, int devID, void *buffer, int bytesToRead); - char *GPIBreadTillTerm(pGPIB self, int devID, int terminator); - void GPIBclear(pGPIB self, int devID); - void GPIBerrorDescription(pGPIB self, int code, - char *buffer, int maxBuffer); +int GPIBattach(pGPIB self, int boardNo, + int address, int secondaryAddress, + int tmo, int eot, int eos); +int GPIBdetach(pGPIB self, int devID); +int GPIBsend(pGPIB self, int devID, void *buffer, int bytesToWrite); +int GPIBread(pGPIB self, int devID, void *buffer, int bytesToRead); +char *GPIBreadTillTerm(pGPIB self, int devID, int terminator); +void GPIBclear(pGPIB self, int devID); +void GPIBerrorDescription(pGPIB self, int code, + char *buffer, int maxBuffer); - int MakeGPIB(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]); - int GPIBAction(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]); - +int MakeGPIB(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); +int GPIBAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + #endif diff --git a/hdbqueue.c b/hdbqueue.c index 88757825..3f794c88 100644 --- a/hdbqueue.c +++ b/hdbqueue.c @@ -7,7 +7,7 @@ * Mark Koennecke, July 2007 */ #include -#include +#include #include #include "sicsobj.h" #include "hdbqueue.h" @@ -17,481 +17,508 @@ #include "macro.h" /*--------------------------------------------------------------------------*/ typedef struct { - int iStop; - int isRunning; - SConnection *pCon; -}HdbQueue, *pHdbQueue; + int iStop; + int isRunning; + SConnection *pCon; +} HdbQueue, *pHdbQueue; /*--------------------------------------------------------------------------*/ -static pHdbCallback CopyCallbackChain(pHdbCallback source){ - pHdbCallback current = NULL; - pHdbCallback result = NULL; - pHdbCallback head = NULL; - pHdbCallback tail = NULL; - - current = source; - while(current != NULL){ - result = MakeHipadabaCallback(current->userCallback, - current->userData, - NULL, - current->id, - current->internalID); - if(head == NULL){ - head = result; - tail = result; - } else { - tail->next = result; - result->previous = tail; - tail = result; - } - current = current->next; +static pHdbCallback CopyCallbackChain(pHdbCallback source) +{ + pHdbCallback current = NULL; + pHdbCallback result = NULL; + pHdbCallback head = NULL; + pHdbCallback tail = NULL; + + current = source; + while (current != NULL) { + result = MakeHipadabaCallback(current->userCallback, + current->userData, + NULL, current->id, current->internalID); + if (head == NULL) { + head = result; + tail = result; + } else { + tail->next = result; + result->previous = tail; + tail = result; } - return head; + current = current->next; + } + return head; } + /*---------------------------------------------------------------------------*/ -static pHdb MakeNewEntry(char *name, pHdbCallback update){ - pHdb entry = NULL, child = NULL; - hdbValue v; +static pHdb MakeNewEntry(char *name, pHdbCallback update) +{ + pHdb entry = NULL, child = NULL; + hdbValue v; - v = MakeHdbText("Undefined"); - entry = MakeHipadabaNode(name,HIPNONE, 1); - entry->updateCallbacks = CopyCallbackChain(update); - child = MakeSICSHdbPar("description",usUser,v); - child->updateCallbacks = CopyCallbackChain(update); - AddHipadabaChild(entry,child,NULL); - child = MakeSICSHdbPar("commands",usUser,v); - child->updateCallbacks = CopyCallbackChain(update); - AddHipadabaChild(entry,child,NULL); - child = MakeSICSHdbPar("log",usUser,v); - child->updateCallbacks = CopyCallbackChain(update); - AddHipadabaChild(entry,child,NULL); - - return entry; + v = MakeHdbText("Undefined"); + entry = MakeHipadabaNode(name, HIPNONE, 1); + entry->updateCallbacks = CopyCallbackChain(update); + child = MakeSICSHdbPar("description", usUser, v); + child->updateCallbacks = CopyCallbackChain(update); + AddHipadabaChild(entry, child, NULL); + child = MakeSICSHdbPar("commands", usUser, v); + child->updateCallbacks = CopyCallbackChain(update); + AddHipadabaChild(entry, child, NULL); + child = MakeSICSHdbPar("log", usUser, v); + child->updateCallbacks = CopyCallbackChain(update); + AddHipadabaChild(entry, child, NULL); + + return entry; } + /*---------------------------------------------------------------------------*/ -static int EnqueFunc(pSICSOBJ self, SConnection *pCon, Hdb commandNode, - pHdb par[], int nPar){ - pHdb entry = NULL; - pHdb work = NULL; - char name[80]; - hdbValue v; - - if(nPar < 1){ - SCWrite(pCon,"ERROR: internal: not enough parameters to EnqueFunc",eError); - return 0; - } - - /* - * new entry - */ - memset(&v,0,sizeof(hdbValue)); - work = GetHipadabaNode(self->objectNode,"control/maxEntry"); - assert(work != NULL); - snprintf(name,80,"%3.3d", work->value.v.intValue); - entry = MakeNewEntry(name, work->updateCallbacks); - if(entry == NULL){ - SCWrite(pCon,"ERROR: out of memory in EnqueFunc",eError); - return 0; - } - /* - * Update maxEntry - */ - cloneHdbValue(&work->value,&v); - v.v.intValue++; - UpdateHipadabaPar(work,v,pCon); - - work = GetHipadabaNode(self->objectNode,"queue"); - assert(work != NULL); - AddHipadabaChild(work, entry, pCon); - - /* - * save description - */ - work = GetHipadabaNode(entry,"description"); - assert(work != NULL); - UpdateHipadabaPar(work,par[0]->value,pCon); +static int EnqueFunc(pSICSOBJ self, SConnection * pCon, Hdb commandNode, + pHdb par[], int nPar) +{ + pHdb entry = NULL; + pHdb work = NULL; + char name[80]; + hdbValue v; - - return 1; -} -/*---------------------------------------------------------------------------*/ -static int AddCmdData(pSICSOBJ self, SConnection *pCon, Hdb comNode, - pHdb par[], int nPar){ - pHdb work = NULL; - pHdb commandNode = NULL; - char name[80]; - pDynString txt = NULL; - - if(nPar < 1){ - SCWrite(pCon,"ERROR: internal: not enough parameters to AddCmdData",eError); - return 0; - } - - work = GetHipadabaNode(self->objectNode,"control/maxEntry"); - assert(work != NULL); - snprintf(name,80,"queue/%3.3d/commands", work->value.v.intValue-1); - commandNode = GetHipadabaNode(self->objectNode,name); - if(commandNode == NULL){ - SCWrite(pCon,"ERROR: Internal error in AddCommand",eError); - return 0; - } - txt = CreateDynString(80,80); - if(strstr(commandNode->value.v.text,"Undefined") == NULL){ - DynStringCopy(txt,commandNode->value.v.text); - } - DynStringConcat(txt,par[0]->value.v.text); - DynStringConcat(txt,"\n"); - free(commandNode->value.v.text); - commandNode->value.v.text = strdup(GetCharArray(txt)); - NotifyHipadabaPar(commandNode,pCon); - DeleteDynString(txt); - return 1; -} -/*--------------------------------------------------------------------------*/ -static void sequentialNames(pHdb obj,SConnection *pCon){ - pHdb work = NULL; - pHdb current = NULL; - int count = 0; - char name[80]; - - work = GetHipadabaNode(obj,"queue"); - assert(work != NULL); - current = work->child; - while(current != NULL){ - snprintf(name,80,"%3.3d",count); - if(current->name != NULL){ - free(current->name); - } - current->name = strdup(name); - count++; - current = current->next; - } - InvokeCallbackChain(work->treeChangeCallbacks,work,pCon,work->value); - - work = GetHipadabaNode(obj,"control/maxEntry"); - assert(work != NULL); - work->value.v.intValue = count; - NotifyHipadabaPar(work,pCon); -} -/*---------------------------------------------------------------------------*/ -static int Dequeue(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pHdb work = NULL; - char name[80]; - pHdbQueue priv = (pHdbQueue)self->pPrivate; - - if(priv->isRunning == 1){ - SCWrite(pCon,"ERROR: cannot dequeue while running",eError); - return 0; - } - - - if(nPar < 1){ - SCWrite(pCon,"ERROR: internal: not enough parameters to Dequeue",eError); - return 0; - } - - snprintf(name,80,"queue/%3.3d", par[0]->value.v.intValue); - work = GetHipadabaNode(self->objectNode,name); - if(work != NULL){ - DeleteHipadabaNode(work,pCon); - sequentialNames(self->objectNode, pCon); - return 1; - } - - return 0; -} -/*---------------------------------------------------------------------------*/ -static int Clean(pSICSOBJ self, SConnection *pCon,Hdb commandNode, - pHdb par[], int nPar){ - int i; - pHdb current = NULL, queue = NULL; - pHdb currentEntry = NULL, tmp = NULL; - pHdbQueue priv = (pHdbQueue)self->pPrivate; - - if(priv->isRunning == 1){ - SCWrite(pCon,"ERROR: cannot clean while running",eError); - return 0; - } - currentEntry = GetHipadabaNode(self->objectNode,"control/currentEntry"); - queue = GetHipadabaNode(self->objectNode,"queue"); - current = queue->child; - for(i = 0; i < currentEntry->value.v.intValue; i++){ - if(current != NULL){ - tmp = current->next; - DeleteNodeData(current); - current = tmp; - } - } - queue->child = tmp; - currentEntry->value.v.intValue = 0; - sequentialNames(self->objectNode, pCon); - NotifyHipadabaPar(currentEntry,pCon); - return 1; -} -/*---------------------------------------------------------------------------*/ -static int CleanAll(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - int i; - pHdb current = NULL, queue = NULL; - pHdb currentEntry = NULL, tmp; - pHdbQueue priv = (pHdbQueue)self->pPrivate; - - if(priv->isRunning == 1){ - SCWrite(pCon,"ERROR: cannot clear queue while executing",eError); - return 0; - } - currentEntry = GetHipadabaNode(self->objectNode,"control/currentEntry"); - queue = GetHipadabaNode(self->objectNode,"queue"); - current = queue->child; - while(current != NULL){ - tmp = current->next; - DeleteNodeData(current); - current = tmp; - } - queue->child = NULL; - currentEntry->value.v.intValue = 0; - sequentialNames(self->objectNode, pCon); - NotifyHipadabaPar(currentEntry,pCon); - return 1; -} -/*----------------------------------------------------------------------------*/ -static int QueueTask(void *pData){ - pSICSOBJ self = (pSICSOBJ)pData; - int status, pos; - pHdb work = NULL; - pHdb exeNode = NULL; - pHdb max = NULL; - char name[80]; - pHdbQueue priv = (pHdbQueue)self->pPrivate; - - if(priv->iStop == 1){ - priv->isRunning = 0; - return 0; - } - - work = GetHipadabaNode(self->objectNode,"control/currentEntry"); - max = GetHipadabaNode(self->objectNode,"control/maxEntry"); - assert(work != NULL && max != NULL); - pos = work->value.v.intValue; - snprintf(name,80,"queue/%3.3d", pos); - - exeNode = GetHipadabaNode(self->objectNode,name); - if(exeNode != NULL){ - MacroPush(priv->pCon); - exeHdbNode(exeNode, priv->pCon); - MacroPop(); - } - if(priv->iStop == 1 || SCGetInterrupt(priv->pCon) != eContinue){ - priv->isRunning = 0; - return 0; - } - - pos++; - work->value.v.intValue = pos; - NotifyHipadabaPar(work,priv->pCon); - if(pos >= max->value.v.intValue){ - priv->isRunning = 0; - return 0; - } - - return 1; -} -/*---------------------------------------------------------------------------*/ -static int Start(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pHdbQueue priv = (pHdbQueue)self->pPrivate; - - priv->iStop = 0; - priv->pCon = pCon; - - if(priv->isRunning == 1){ - SCWrite(pCon,"ERROR: Hdbqueue is already running",eError); - return 0; - } - priv->isRunning = 1; - - TaskRegister(pServ->pTasker, - QueueTask, - NULL, - NULL, - self, - 10); - return 1; -} -/*---------------------------------------------------------------------------*/ -static int Restart(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pHdbQueue priv = (pHdbQueue)self->pPrivate; - pHdb maxCurrent = NULL; - - maxCurrent = GetHipadabaNode(self->objectNode,"control/currentEntry"); - if(maxCurrent != NULL){ - maxCurrent->value.v.intValue = 0; - NotifyHipadabaPar(maxCurrent,pCon); - } - - return Start(self,pCon,commandNode,par,nPar); -} -/*---------------------------------------------------------------------------*/ -static int Stop(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pHdbQueue priv = (pHdbQueue)self->pPrivate; - - priv->iStop = 1; - return 1; -} -/*----------------------------------------------------------------------------*/ -static int Move(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pHdb moveNode = NULL; - pHdb insertNode = NULL; - pHdb prevNode = NULL, queueNode = NULL; - pHdb tmp; - char name[80]; - pHdbQueue priv = (pHdbQueue)self->pPrivate; - - if(priv->isRunning == 1){ - SCWrite(pCon,"ERROR: cannot move while running",eError); - return 0; - } - - if(nPar < 2){ - SCWrite(pCon,"ERROR: internal: not enough parameters to Move",eError); - return 1; - } - - if(par[1]->value.v.intValue == par[0]->value.v.intValue + 1){ - /* - * already in right sequence, nothing to do - */ - return 1; - } - - snprintf(name,80,"queue/%3.3d", par[1]->value.v.intValue); - moveNode = GetHipadabaNode(self->objectNode,name); - - snprintf(name,80,"queue/%3.3d", par[0]->value.v.intValue); - insertNode = GetHipadabaNode(self->objectNode,name); - if(moveNode == NULL || insertNode == NULL){ - SCWrite(pCon,"ERROR: move not possible, participating nodes not found", + if (nPar < 1) { + SCWrite(pCon, "ERROR: internal: not enough parameters to EnqueFunc", eError); - return 0; - } - queueNode = GetHipadabaNode(self->objectNode,"queue"); + return 0; + } - if(moveNode == queueNode->child){ - queueNode->child = queueNode->child->next; - moveNode->next = insertNode->next; - insertNode->next = moveNode; - } else { - prevNode = queueNode->child; - while(prevNode != NULL && prevNode->next != moveNode){ - prevNode = prevNode->next; - } - if(insertNode == queueNode->child ){ - /* - * insert at top - */ - tmp = queueNode->child; - queueNode->child = moveNode; - prevNode->next = moveNode->next; - moveNode->next = tmp; - } else { - tmp = insertNode->next; - insertNode->next = moveNode; - prevNode->next = moveNode->next; - moveNode->next = tmp; - } + /* + * new entry + */ + memset(&v, 0, sizeof(hdbValue)); + work = GetHipadabaNode(self->objectNode, "control/maxEntry"); + assert(work != NULL); + snprintf(name, 80, "%3.3d", work->value.v.intValue); + entry = MakeNewEntry(name, work->updateCallbacks); + if (entry == NULL) { + SCWrite(pCon, "ERROR: out of memory in EnqueFunc", eError); + return 0; + } + /* + * Update maxEntry + */ + cloneHdbValue(&work->value, &v); + v.v.intValue++; + UpdateHipadabaPar(work, v, pCon); + + work = GetHipadabaNode(self->objectNode, "queue"); + assert(work != NULL); + AddHipadabaChild(work, entry, pCon); + + /* + * save description + */ + work = GetHipadabaNode(entry, "description"); + assert(work != NULL); + UpdateHipadabaPar(work, par[0]->value, pCon); + + + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int AddCmdData(pSICSOBJ self, SConnection * pCon, Hdb comNode, + pHdb par[], int nPar) +{ + pHdb work = NULL; + pHdb commandNode = NULL; + char name[80]; + pDynString txt = NULL; + + if (nPar < 1) { + SCWrite(pCon, "ERROR: internal: not enough parameters to AddCmdData", + eError); + return 0; + } + + work = GetHipadabaNode(self->objectNode, "control/maxEntry"); + assert(work != NULL); + snprintf(name, 80, "queue/%3.3d/commands", work->value.v.intValue - 1); + commandNode = GetHipadabaNode(self->objectNode, name); + if (commandNode == NULL) { + SCWrite(pCon, "ERROR: Internal error in AddCommand", eError); + return 0; + } + txt = CreateDynString(80, 80); + if (strstr(commandNode->value.v.text, "Undefined") == NULL) { + DynStringCopy(txt, commandNode->value.v.text); + } + DynStringConcat(txt, par[0]->value.v.text); + DynStringConcat(txt, "\n"); + free(commandNode->value.v.text); + commandNode->value.v.text = strdup(GetCharArray(txt)); + NotifyHipadabaPar(commandNode, pCon); + DeleteDynString(txt); + return 1; +} + +/*--------------------------------------------------------------------------*/ +static void sequentialNames(pHdb obj, SConnection * pCon) +{ + pHdb work = NULL; + pHdb current = NULL; + int count = 0; + char name[80]; + + work = GetHipadabaNode(obj, "queue"); + assert(work != NULL); + current = work->child; + while (current != NULL) { + snprintf(name, 80, "%3.3d", count); + if (current->name != NULL) { + free(current->name); } + current->name = strdup(name); + count++; + current = current->next; + } + InvokeCallbackChain(work->treeChangeCallbacks, work, pCon, work->value); + + work = GetHipadabaNode(obj, "control/maxEntry"); + assert(work != NULL); + work->value.v.intValue = count; + NotifyHipadabaPar(work, pCon); +} + +/*---------------------------------------------------------------------------*/ +static int Dequeue(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + pHdb work = NULL; + char name[80]; + pHdbQueue priv = (pHdbQueue) self->pPrivate; + + if (priv->isRunning == 1) { + SCWrite(pCon, "ERROR: cannot dequeue while running", eError); + return 0; + } + + + if (nPar < 1) { + SCWrite(pCon, "ERROR: internal: not enough parameters to Dequeue", + eError); + return 0; + } + + snprintf(name, 80, "queue/%3.3d", par[0]->value.v.intValue); + work = GetHipadabaNode(self->objectNode, name); + if (work != NULL) { + DeleteHipadabaNode(work, pCon); sequentialNames(self->objectNode, pCon); - return 1; + } + + return 0; } + /*---------------------------------------------------------------------------*/ -static void Configure(pSICSOBJ self){ - pHdb n = NULL, par = NULL; - hdbValue intValue, textValue, funcValue; - pHdb obj = self->objectNode; - - intValue = MakeHdbInt(0); - textValue = MakeHdbText("Undefined"); - - n = MakeHipadabaNode("control",HIPNONE,1); - AddHipadabaChild(obj,n,NULL); - AddSICSHdbPar(n,"maxEntry",usInternal,intValue); - AddSICSHdbPar(n,"currentEntry",usInternal,intValue); +static int Clean(pSICSOBJ self, SConnection * pCon, Hdb commandNode, + pHdb par[], int nPar) +{ + int i; + pHdb current = NULL, queue = NULL; + pHdb currentEntry = NULL, tmp = NULL; + pHdbQueue priv = (pHdbQueue) self->pPrivate; - - n = MakeHipadabaNode("queue",HIPNONE,1); - AddHipadabaChild(obj,n, NULL); + if (priv->isRunning == 1) { + SCWrite(pCon, "ERROR: cannot clean while running", eError); + return 0; + } + currentEntry = GetHipadabaNode(self->objectNode, "control/currentEntry"); + queue = GetHipadabaNode(self->objectNode, "queue"); + current = queue->child; + for (i = 0; i < currentEntry->value.v.intValue; i++) { + if (current != NULL) { + tmp = current->next; + DeleteNodeData(current); + current = tmp; + } + } + queue->child = tmp; + currentEntry->value.v.intValue = 0; + sequentialNames(self->objectNode, pCon); + NotifyHipadabaPar(currentEntry, pCon); + return 1; +} - funcValue = MakeSICSFunc(EnqueFunc); - n = MakeSICSHdbPar("enqueue",usUser, funcValue); - AddSICSHdbPar(n,"description",usUser,textValue); - AddHipadabaChild(obj,n,NULL); - AppendHipadabaCallback(n,HCBSET,MakeSICSFuncCallback(self)); +/*---------------------------------------------------------------------------*/ +static int CleanAll(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + int i; + pHdb current = NULL, queue = NULL; + pHdb currentEntry = NULL, tmp; + pHdbQueue priv = (pHdbQueue) self->pPrivate; - funcValue = MakeSICSFunc(AddCmdData); - n = MakeSICSHdbPar("addcommand",usUser, funcValue); - AddSICSHdbPar(n,"command",usUser,textValue); - AddHipadabaChild(obj,n,NULL); - AppendHipadabaCallback(n,HCBSET,MakeSICSFuncCallback(self)); + if (priv->isRunning == 1) { + SCWrite(pCon, "ERROR: cannot clear queue while executing", eError); + return 0; + } + currentEntry = GetHipadabaNode(self->objectNode, "control/currentEntry"); + queue = GetHipadabaNode(self->objectNode, "queue"); + current = queue->child; + while (current != NULL) { + tmp = current->next; + DeleteNodeData(current); + current = tmp; + } + queue->child = NULL; + currentEntry->value.v.intValue = 0; + sequentialNames(self->objectNode, pCon); + NotifyHipadabaPar(currentEntry, pCon); + return 1; +} + +/*----------------------------------------------------------------------------*/ +static int QueueTask(void *pData) +{ + pSICSOBJ self = (pSICSOBJ) pData; + int status, pos; + pHdb work = NULL; + pHdb exeNode = NULL; + pHdb max = NULL; + char name[80]; + pHdbQueue priv = (pHdbQueue) self->pPrivate; + + if (priv->iStop == 1) { + priv->isRunning = 0; + return 0; + } + + work = GetHipadabaNode(self->objectNode, "control/currentEntry"); + max = GetHipadabaNode(self->objectNode, "control/maxEntry"); + assert(work != NULL && max != NULL); + pos = work->value.v.intValue; + snprintf(name, 80, "queue/%3.3d", pos); + + exeNode = GetHipadabaNode(self->objectNode, name); + if (exeNode != NULL) { + MacroPush(priv->pCon); + exeHdbNode(exeNode, priv->pCon); + MacroPop(); + } + if (priv->iStop == 1 || SCGetInterrupt(priv->pCon) != eContinue) { + priv->isRunning = 0; + return 0; + } + + pos++; + work->value.v.intValue = pos; + NotifyHipadabaPar(work, priv->pCon); + if (pos >= max->value.v.intValue) { + priv->isRunning = 0; + return 0; + } + + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int Start(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + pHdbQueue priv = (pHdbQueue) self->pPrivate; + + priv->iStop = 0; + priv->pCon = pCon; + + if (priv->isRunning == 1) { + SCWrite(pCon, "ERROR: Hdbqueue is already running", eError); + return 0; + } + priv->isRunning = 1; + + TaskRegister(pServ->pTasker, QueueTask, NULL, NULL, self, 10); + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int Restart(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + pHdbQueue priv = (pHdbQueue) self->pPrivate; + pHdb maxCurrent = NULL; + + maxCurrent = GetHipadabaNode(self->objectNode, "control/currentEntry"); + if (maxCurrent != NULL) { + maxCurrent->value.v.intValue = 0; + NotifyHipadabaPar(maxCurrent, pCon); + } + + return Start(self, pCon, commandNode, par, nPar); +} + +/*---------------------------------------------------------------------------*/ +static int Stop(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + pHdbQueue priv = (pHdbQueue) self->pPrivate; + + priv->iStop = 1; + return 1; +} + +/*----------------------------------------------------------------------------*/ +static int Move(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + pHdb moveNode = NULL; + pHdb insertNode = NULL; + pHdb prevNode = NULL, queueNode = NULL; + pHdb tmp; + char name[80]; + pHdbQueue priv = (pHdbQueue) self->pPrivate; + + if (priv->isRunning == 1) { + SCWrite(pCon, "ERROR: cannot move while running", eError); + return 0; + } + + if (nPar < 2) { + SCWrite(pCon, "ERROR: internal: not enough parameters to Move", + eError); + return 1; + } + + if (par[1]->value.v.intValue == par[0]->value.v.intValue + 1) { + /* + * already in right sequence, nothing to do + */ + return 1; + } + + snprintf(name, 80, "queue/%3.3d", par[1]->value.v.intValue); + moveNode = GetHipadabaNode(self->objectNode, name); + + snprintf(name, 80, "queue/%3.3d", par[0]->value.v.intValue); + insertNode = GetHipadabaNode(self->objectNode, name); + if (moveNode == NULL || insertNode == NULL) { + SCWrite(pCon, + "ERROR: move not possible, participating nodes not found", + eError); + return 0; + } + queueNode = GetHipadabaNode(self->objectNode, "queue"); + + if (moveNode == queueNode->child) { + queueNode->child = queueNode->child->next; + moveNode->next = insertNode->next; + insertNode->next = moveNode; + } else { + prevNode = queueNode->child; + while (prevNode != NULL && prevNode->next != moveNode) { + prevNode = prevNode->next; + } + if (insertNode == queueNode->child) { + /* + * insert at top + */ + tmp = queueNode->child; + queueNode->child = moveNode; + prevNode->next = moveNode->next; + moveNode->next = tmp; + } else { + tmp = insertNode->next; + insertNode->next = moveNode; + prevNode->next = moveNode->next; + moveNode->next = tmp; + } + } + sequentialNames(self->objectNode, pCon); + + return 1; +} + +/*---------------------------------------------------------------------------*/ +static void Configure(pSICSOBJ self) +{ + pHdb n = NULL, par = NULL; + hdbValue intValue, textValue, funcValue; + pHdb obj = self->objectNode; + + intValue = MakeHdbInt(0); + textValue = MakeHdbText("Undefined"); + + n = MakeHipadabaNode("control", HIPNONE, 1); + AddHipadabaChild(obj, n, NULL); + AddSICSHdbPar(n, "maxEntry", usInternal, intValue); + AddSICSHdbPar(n, "currentEntry", usInternal, intValue); - funcValue = MakeSICSFunc(Dequeue); - n = MakeSICSHdbPar("dequeue",usUser,funcValue); - AddHipadabaChild(obj,n,NULL); - AddSICSHdbPar(n,"index",usUser,intValue); - AppendHipadabaCallback(n,HCBSET,MakeSICSFuncCallback(self)); + n = MakeHipadabaNode("queue", HIPNONE, 1); + AddHipadabaChild(obj, n, NULL); + + funcValue = MakeSICSFunc(EnqueFunc); + n = MakeSICSHdbPar("enqueue", usUser, funcValue); + AddSICSHdbPar(n, "description", usUser, textValue); + AddHipadabaChild(obj, n, NULL); + AppendHipadabaCallback(n, HCBSET, MakeSICSFuncCallback(self)); + + funcValue = MakeSICSFunc(AddCmdData); + n = MakeSICSHdbPar("addcommand", usUser, funcValue); + AddSICSHdbPar(n, "command", usUser, textValue); + AddHipadabaChild(obj, n, NULL); + AppendHipadabaCallback(n, HCBSET, MakeSICSFuncCallback(self)); - funcValue = MakeSICSFunc(Clean); - n = MakeSICSHdbPar("clean",usUser, funcValue); - AddHipadabaChild(obj,n,NULL); - AppendHipadabaCallback(n,HCBSET,MakeSICSFuncCallback(self)); + funcValue = MakeSICSFunc(Dequeue); + n = MakeSICSHdbPar("dequeue", usUser, funcValue); + AddHipadabaChild(obj, n, NULL); + AddSICSHdbPar(n, "index", usUser, intValue); + AppendHipadabaCallback(n, HCBSET, MakeSICSFuncCallback(self)); - funcValue = MakeSICSFunc(CleanAll); - n = MakeSICSHdbPar("cleanall",usUser, funcValue); - AddHipadabaChild(obj,n,NULL); - AppendHipadabaCallback(n,HCBSET,MakeSICSFuncCallback(self)); - funcValue = MakeSICSFunc(Start); - n = MakeSICSHdbPar("start",usUser, funcValue); - AddHipadabaChild(obj,n,NULL); - AppendHipadabaCallback(n,HCBSET,MakeSICSFuncCallback(self)); + funcValue = MakeSICSFunc(Clean); + n = MakeSICSHdbPar("clean", usUser, funcValue); + AddHipadabaChild(obj, n, NULL); + AppendHipadabaCallback(n, HCBSET, MakeSICSFuncCallback(self)); - funcValue = MakeSICSFunc(Restart); - n = MakeSICSHdbPar("restart",usUser, funcValue); - AddHipadabaChild(obj,n,NULL); - AppendHipadabaCallback(n,HCBSET,MakeSICSFuncCallback(self)); + funcValue = MakeSICSFunc(CleanAll); + n = MakeSICSHdbPar("cleanall", usUser, funcValue); + AddHipadabaChild(obj, n, NULL); + AppendHipadabaCallback(n, HCBSET, MakeSICSFuncCallback(self)); - funcValue = MakeSICSFunc(Stop); - n = MakeSICSHdbPar("stop",usUser, funcValue); - AddHipadabaChild(obj,n,NULL); - AppendHipadabaCallback(n,HCBSET,MakeSICSFuncCallback(self)); + funcValue = MakeSICSFunc(Start); + n = MakeSICSHdbPar("start", usUser, funcValue); + AddHipadabaChild(obj, n, NULL); + AppendHipadabaCallback(n, HCBSET, MakeSICSFuncCallback(self)); - funcValue = MakeSICSFunc(Move); - n = MakeSICSHdbPar("move",usUser,funcValue); - AddHipadabaChild(obj,n,NULL); - AddSICSHdbPar(n,"moveindex",usUser,intValue); - AddSICSHdbPar(n,"insertindex",usUser,intValue); - AppendHipadabaCallback(n,HCBSET,MakeSICSFuncCallback(self)); + funcValue = MakeSICSFunc(Restart); + n = MakeSICSHdbPar("restart", usUser, funcValue); + AddHipadabaChild(obj, n, NULL); + AppendHipadabaCallback(n, HCBSET, MakeSICSFuncCallback(self)); + + funcValue = MakeSICSFunc(Stop); + n = MakeSICSHdbPar("stop", usUser, funcValue); + AddHipadabaChild(obj, n, NULL); + AppendHipadabaCallback(n, HCBSET, MakeSICSFuncCallback(self)); + + funcValue = MakeSICSFunc(Move); + n = MakeSICSHdbPar("move", usUser, funcValue); + AddHipadabaChild(obj, n, NULL); + AddSICSHdbPar(n, "moveindex", usUser, intValue); + AddSICSHdbPar(n, "insertindex", usUser, intValue); + AppendHipadabaCallback(n, HCBSET, MakeSICSFuncCallback(self)); } + /*---------------------------------------------------------------------------*/ -int MakeHDBQueue(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pSICSOBJ self = NULL; - pHdbQueue priv = NULL; - - priv = (pHdbQueue)malloc(sizeof(HdbQueue)); - self = SetupSICSOBJ(pCon,pSics, pData,argc, argv); - if(self == NULL || priv == NULL){ - return 0; - } - Configure(self); - memset(priv,0,sizeof(HdbQueue)); - self->pPrivate = priv; - self->KillPrivate = free; - return 1; -} +int MakeHDBQueue(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSICSOBJ self = NULL; + pHdbQueue priv = NULL; + + priv = (pHdbQueue) malloc(sizeof(HdbQueue)); + self = SetupSICSOBJ(pCon, pSics, pData, argc, argv); + if (self == NULL || priv == NULL) { + return 0; + } + Configure(self); + memset(priv, 0, sizeof(HdbQueue)); + self->pPrivate = priv; + self->KillPrivate = free; + return 1; +} diff --git a/hdbqueue.h b/hdbqueue.h index a1663da8..71e0f2c8 100644 --- a/hdbqueue.h +++ b/hdbqueue.h @@ -9,7 +9,7 @@ #ifndef HDBQUEUE_H_ #define HDBQUEUE_H_ -int MakeHDBQueue(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeHDBQueue(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -#endif /*HDBQUEUE_H_*/ +#endif /*HDBQUEUE_H_ */ diff --git a/help.c b/help.c index 0a16d434..bd994612 100644 --- a/help.c +++ b/help.c @@ -18,133 +18,142 @@ extern char *stptok(const char *s, char *tok, size_t toklen, char *brk); #define PATHSEP ":" #define DIRSEP "/" static char *helpDirs = NULL; -static char *defaultFile="master.txt"; +static char *defaultFile = "master.txt"; /*----------------------------------------------------------------------*/ -void KillHelp(void *pData){ +void KillHelp(void *pData) +{ KillDummy(pData); - if(helpDirs != NULL){ + if (helpDirs != NULL) { free(helpDirs); helpDirs = NULL; } } + /*-----------------------------------------------------------------------*/ -static FILE *findHelpFile(char *name){ +static FILE *findHelpFile(char *name) +{ FILE *fd = NULL; char pBueffel[256]; char dir[132]; char *pPtr; - if(helpDirs == NULL){ + if (helpDirs == NULL) { return NULL; } pPtr = helpDirs; - while( (pPtr = stptok(pPtr,dir,131,PATHSEP)) != NULL){ - strcpy(pBueffel,dir); - strcat(pBueffel,DIRSEP); - strncat(pBueffel,name,(254-strlen(pBueffel))); - fd = fopen(pBueffel,"r"); - if(fd != NULL){ + while ((pPtr = stptok(pPtr, dir, 131, PATHSEP)) != NULL) { + strcpy(pBueffel, dir); + strcat(pBueffel, DIRSEP); + strncat(pBueffel, name, (254 - strlen(pBueffel))); + fd = fopen(pBueffel, "r"); + if (fd != NULL) { return fd; } } - + /* - this means: not found! - */ + this means: not found! + */ return NULL; } + /*----------------------------------------------------------------------*/ -static void printHelpFile(SConnection *pCon, FILE *fd){ +static void printHelpFile(SConnection * pCon, FILE * fd) +{ char line[132]; - while(fgets(line,131,fd) != NULL){ - SCWrite(pCon,line,eValue); + while (fgets(line, 131, fd) != NULL) { + SCWrite(pCon, line, eValue); } } + /*----------------------------------------------------------------------*/ -static void configureHelp(SConnection *pCon, - char *option, char *parameter){ +static void configureHelp(SConnection * pCon, + char *option, char *parameter) +{ char *pPtr = NULL; int length; strtolower(option); - if(strcmp(option,"adddir") == 0){ - if(parameter == NULL){ - SCWrite(pCon,helpDirs,eValue); + if (strcmp(option, "adddir") == 0) { + if (parameter == NULL) { + SCWrite(pCon, helpDirs, eValue); return; } else { pPtr = helpDirs; - if(pPtr != NULL){ - length = strlen(pPtr) + strlen(PATHSEP) + strlen(parameter) + 2; - helpDirs = (char *)malloc(length*sizeof(char)); - memset(helpDirs,0,length*sizeof(char)); - strcpy(helpDirs,pPtr); - strcat(helpDirs,PATHSEP); - strcat(helpDirs,parameter); - free(pPtr); + if (pPtr != NULL) { + length = strlen(pPtr) + strlen(PATHSEP) + strlen(parameter) + 2; + helpDirs = (char *) malloc(length * sizeof(char)); + memset(helpDirs, 0, length * sizeof(char)); + strcpy(helpDirs, pPtr); + strcat(helpDirs, PATHSEP); + strcat(helpDirs, parameter); + free(pPtr); } else { - helpDirs=strdup(parameter); + helpDirs = strdup(parameter); } } - } else if(strcmp(option,"defaultfile") == 0){ - if(parameter == NULL){ - SCWrite(pCon,defaultFile,eValue); + } else if (strcmp(option, "defaultfile") == 0) { + if (parameter == NULL) { + SCWrite(pCon, defaultFile, eValue); return; } else { - if(defaultFile != NULL){ - free(defaultFile); + if (defaultFile != NULL) { + free(defaultFile); } defaultFile = strdup(parameter); } } else { - SCWrite(pCon,"Unknown option to configure",eWarning); - SCWrite(pCon,"Known options: defaultfile, adddir",eWarning); + SCWrite(pCon, "Unknown option to configure", eWarning); + SCWrite(pCon, "Known options: defaultfile, adddir", eWarning); } } + /*-----------------------------------------------------------------------*/ -int SicsHelp(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int SicsHelp(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ char helpFile[256]; FILE *fd = NULL; - strncpy(helpFile,defaultFile,255); + strncpy(helpFile, defaultFile, 255); - if(argc > 1){ + if (argc > 1) { strtolower(argv[1]); /* - check for configure - */ - if(strcmp(argv[1],"configure") == 0){ - if(argc < 3){ - SCWrite(pCon,"ERROR: need an option to configure",eError); - return 0; + check for configure + */ + if (strcmp(argv[1], "configure") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: need an option to configure", eError); + return 0; } - if(argc > 3){ - configureHelp(pCon,argv[2],argv[3]); + if (argc > 3) { + configureHelp(pCon, argv[2], argv[3]); } else { - configureHelp(pCon,argv[2],NULL); + configureHelp(pCon, argv[2], NULL); } SCSendOK(pCon); return 1; } /* - the parameter is a help file name - */ - strncpy(helpFile,argv[1],255); - strncat(helpFile,".txt",255); + the parameter is a help file name + */ + strncpy(helpFile, argv[1], 255); + strncat(helpFile, ".txt", 255); } /* - print the helpFile - */ + print the helpFile + */ fd = findHelpFile(helpFile); - if(fd == NULL){ - SCWrite(pCon,"ERROR: failed to locate helpFile:",eError); - SCWrite(pCon,helpFile,eError); + if (fd == NULL) { + SCWrite(pCon, "ERROR: failed to locate helpFile:", eError); + SCWrite(pCon, helpFile, eError); return 0; } - printHelpFile(pCon,fd); + printHelpFile(pCon, fd); fclose(fd); return 1; } diff --git a/help.h b/help.h index 179dd700..94c15837 100644 --- a/help.h +++ b/help.h @@ -9,9 +9,8 @@ #ifndef SICSHELP #define SICSHELP - int SicsHelp(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SicsHelp(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - void KillHelp(void *pData); +void KillHelp(void *pData); #endif - diff --git a/hipadaba.c b/hipadaba.c index 087fadc7..d213331c 100644 --- a/hipadaba.c +++ b/hipadaba.c @@ -12,945 +12,1038 @@ #include #include "hipadaba.h" -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) #define HDBMAGICK 77119900 /*================== Message Stuff ========================================*/ -static char set[] = {"set"}; -static char get[] = {"get"}; -static char update[] = {"update"}; -static char treeChange[] = {"treeChange"}; -static char dataSearch[] = {"dataSearch"}; -static char killNode[] = {"killNode"}; +static char set[] = { "set" }; +static char get[] = { "get" }; +static char update[] = { "update" }; +static char treeChange[] = { "treeChange" }; +static char dataSearch[] = { "dataSearch" }; +static char killNode[] = { "killNode" }; + /*------------------------------------------------------------------------*/ -pHdbDataMessage GetHdbSetMessage(pHdbMessage toTest){ - if(toTest->type == set){ - return (pHdbDataMessage)toTest; - } - return NULL; +pHdbDataMessage GetHdbSetMessage(pHdbMessage toTest) +{ + if (toTest->type == set) { + return (pHdbDataMessage) toTest; + } + return NULL; } + /*------------------------------------------------------------------------*/ -pHdbDataMessage GetHdbGetMessage(pHdbMessage toTest){ - if(toTest->type == get){ - return (pHdbDataMessage)toTest; - } - return NULL; +pHdbDataMessage GetHdbGetMessage(pHdbMessage toTest) +{ + if (toTest->type == get) { + return (pHdbDataMessage) toTest; + } + return NULL; } + /*------------------------------------------------------------------------*/ -pHdbDataMessage GetHdbUpdateMessage(pHdbMessage toTest){ - if(toTest->type == update){ - return (pHdbDataMessage)toTest; - } - return NULL; +pHdbDataMessage GetHdbUpdateMessage(pHdbMessage toTest) +{ + if (toTest->type == update) { + return (pHdbDataMessage) toTest; + } + return NULL; } + /*-------------------------------------------------------------------------*/ -pHdbTreeChangeMessage GetHdbTreeChangeMessage(pHdbMessage toTest){ - if(toTest->type == treeChange){ - return (pHdbTreeChangeMessage)toTest; - } - return NULL; +pHdbTreeChangeMessage GetHdbTreeChangeMessage(pHdbMessage toTest) +{ + if (toTest->type == treeChange) { + return (pHdbTreeChangeMessage) toTest; + } + return NULL; } + /*-------------------------------------------------------------------------*/ -pHdbDataSearch GetHdbDataSearchMessage(pHdbMessage toTest){ - if(toTest->type == dataSearch){ - return (pHdbDataSearch)toTest; - } - return NULL; +pHdbDataSearch GetHdbDataSearchMessage(pHdbMessage toTest) +{ + if (toTest->type == dataSearch) { + return (pHdbDataSearch) toTest; + } + return NULL; } + /*-------------------------------------------------------------------------*/ -pHdbMessage GetHdbKillNodeMessage(pHdbMessage toTest){ - if(toTest->type == killNode){ - return toTest; - } - return NULL; +pHdbMessage GetHdbKillNodeMessage(pHdbMessage toTest) +{ + if (toTest->type == killNode) { + return toTest; + } + return NULL; } + /*================== internal functions ===================================*/ -void DeleteCallbackChain(pHdb node){ - pHdbCallback current = NULL, thisEntry; - hdbMessage killNodeMsg; - - killNodeMsg.type = killNode; - InvokeCallbackChain(node, &killNodeMsg); - - current = node->callBackChain; - while(current != NULL){ - if(current->killFunc != NULL){ - current->killFunc(current->userData); - } - thisEntry = current; - current = (pHdbCallback)current->next; - free(thisEntry); +void DeleteCallbackChain(pHdb node) +{ + pHdbCallback current = NULL, thisEntry; + hdbMessage killNodeMsg; + + killNodeMsg.type = killNode; + InvokeCallbackChain(node, &killNodeMsg); + + current = node->callBackChain; + while (current != NULL) { + if (current->killFunc != NULL) { + current->killFunc(current->userData); } + thisEntry = current; + current = (pHdbCallback) current->next; + free(thisEntry); + } } + /*----------------------------------------------------------------------*/ -void RecurseCallbackChains(pHdb node, pHdbMessage message){ - pHdb current = NULL; +void RecurseCallbackChains(pHdb node, pHdbMessage message) +{ + pHdb current = NULL; - InvokeCallbackChain(node,message); - current = node->child; - while(current != NULL){ - RecurseCallbackChains(current,message); - current = current->next; - } + InvokeCallbackChain(node, message); + current = node->child; + while (current != NULL) { + RecurseCallbackChains(current, message); + current = current->next; + } } + /*-----------------------------------------------------------------------*/ -void DeleteNodeData(pHdb node){ - pHdb tmp = NULL; - - if(node == NULL){ - return; - } +void DeleteNodeData(pHdb node) +{ + pHdb tmp = NULL; - DeleteCallbackChain(node); - if(node->properties != NULL){ - DeleteStringDict(node->properties); - } - - if(node->name != NULL){ - free(node->name); - } - ReleaseHdbValue(&node->value); - node->magic = 000000; + if (node == NULL) { + return; + } - while(node->child != NULL){ - tmp = node->child; - node->child = node->child->next; - DeleteNodeData(tmp); - } - free(node); + DeleteCallbackChain(node); + if (node->properties != NULL) { + DeleteStringDict(node->properties); + } + + if (node->name != NULL) { + free(node->name); + } + ReleaseHdbValue(&node->value); + node->magic = 000000; + + while (node->child != NULL) { + tmp = node->child; + node->child = node->child->next; + DeleteNodeData(tmp); + } + free(node); } + /*------------------------------------------------------------------------*/ -static pHdbCallback CleanCallbackChain(pHdbCallback head){ - pHdbCallback current = head; - pHdbCallback next; - pHdbCallback *ptr2last = &head; - - while(current != NULL){ - if(current->killFlag == 1){ - next = current->next; - /* - * unlink - */ - *ptr2last = next; - /* - * delete - */ - if(current->killFunc != NULL){ - current->killFunc(current->userData); - } - free(current); - /* - * move on - */ - current = next; - } else { - ptr2last = ¤t->next; - current = current->next; - } - } - - return head; +static pHdbCallback CleanCallbackChain(pHdbCallback head) +{ + pHdbCallback current = head; + pHdbCallback next; + pHdbCallback *ptr2last = &head; + + while (current != NULL) { + if (current->killFlag == 1) { + next = current->next; + /* + * unlink + */ + *ptr2last = next; + /* + * delete + */ + if (current->killFunc != NULL) { + current->killFunc(current->userData); + } + free(current); + /* + * move on + */ + current = next; + } else { + ptr2last = ¤t->next; + current = current->next; + } + } + + return head; } + /*-------------------------------------------------------------------------*/ -int InvokeCallbackChain(pHdb node, pHdbMessage message){ - pHdbCallback current = node->callBackChain; - hdbCallbackReturn status; - int killFlag = 0; - - while(current != NULL){ - status = current->userCallback(node, current->userData,message); - switch(status){ - case hdbAbort: - return 0; - break; - case hdbKill: - current->killFlag = 1; - killFlag = 1; - break; - case hdbContinue: - break; - } - current = current->next; +int InvokeCallbackChain(pHdb node, pHdbMessage message) +{ + pHdbCallback current = node->callBackChain; + hdbCallbackReturn status; + int killFlag = 0; + + while (current != NULL) { + status = current->userCallback(node, current->userData, message); + switch (status) { + case hdbAbort: + return 0; + break; + case hdbKill: + current->killFlag = 1; + killFlag = 1; + break; + case hdbContinue: + break; } - if(killFlag == 1){ - node->callBackChain = CleanCallbackChain(node->callBackChain); - } - return 1; + current = current->next; + } + if (killFlag == 1) { + node->callBackChain = CleanCallbackChain(node->callBackChain); + } + return 1; } + /*-----------------------------------------------------------------------*/ -static void SendTreeChangeMessage(pHdb node, void *callData){ - hdbTreeChangeMessage treeChangeMes; - treeChangeMes.type = treeChange; - treeChangeMes.callData = callData; - InvokeCallbackChain(node, (pHdbMessage)&treeChangeMes); +static void SendTreeChangeMessage(pHdb node, void *callData) +{ + hdbTreeChangeMessage treeChangeMes; + treeChangeMes.type = treeChange; + treeChangeMes.callData = callData; + InvokeCallbackChain(node, (pHdbMessage) & treeChangeMes); } + /*------------------------------------------------------------------------*/ -void RemoveHdbNodeFromParent(pHdb node, void *callData){ - pHdb parent = NULL; - pHdb current = NULL; - hdbTreeChangeMessage treeChangeMes; - - parent = node->mama; - if(parent != NULL){ - if(parent->child == node){ - parent->child = node->next; - } else { - current = parent->child; - while(current->next != node){ - current = current->next; - } - current->next = current->next->next; - } - SendTreeChangeMessage(parent,callData); - node->mama = NULL; - } -} -/*----------------------------------------------------------------------*/ -int CountHdbChildren(pHdb node){ - int count = 0; - pHdb current = NULL; - current = node->child; - while(current != NULL){ +void RemoveHdbNodeFromParent(pHdb node, void *callData) +{ + pHdb parent = NULL; + pHdb current = NULL; + hdbTreeChangeMessage treeChangeMes; + + parent = node->mama; + if (parent != NULL) { + if (parent->child == node) { + parent->child = node->next; + } else { + current = parent->child; + while (current->next != node) { current = current->next; - count++; + } + current->next = current->next->next; } - return count; + SendTreeChangeMessage(parent, callData); + node->mama = NULL; + } } + +/*----------------------------------------------------------------------*/ +int CountHdbChildren(pHdb node) +{ + int count = 0; + pHdb current = NULL; + current = node->child; + while (current != NULL) { + current = current->next; + count++; + } + return count; +} + /*----------------------------------------------------------------------*/ char *hdbTrim(char *str) { - char *ibuf = str, *obuf = str; - int i = 0, cnt = 0; + char *ibuf = str, *obuf = str; + int i = 0, cnt = 0; - /* - ** Trap NULL - */ + /* + ** Trap NULL + */ - if (str) - { - /* - ** Remove leading spaces (from RMLEAD.C) - */ + if (str) { + /* + ** Remove leading spaces (from RMLEAD.C) + */ - for (ibuf = str; *ibuf && isspace(*ibuf); ++ibuf) - ; - if (str != ibuf) - memmove(str, ibuf, ibuf - str); - - /* - ** Collapse embedded spaces (from LV1WS.C) - */ - - while (*ibuf) - { - if (isspace(*ibuf) && cnt) - ibuf++; - else - { - if (!isspace(*ibuf)) - cnt = 0; - else - { - *ibuf = ' '; - cnt = 1; - } - obuf[i++] = *ibuf++; - } - } - obuf[i] = '\0'; - - /* - ** Remove trailing spaces (from RMTRAIL.C) - */ - - while (--i >= 0) - { - if (!isspace(obuf[i])) - break; - } - obuf[++i] = '\0'; - } - return str; -} -/*------------------------------------------------------------------------*/ -static pHdb locateChild(pHdb root, char *name){ - pHdb current = NULL; - - current = root->child; - while(current != NULL){ - if(strcmp(current->name,name) == 0){ - return current; - } - current = current->next; - } - return NULL; -} -/*================= data functions ========================================*/ -hdbValue makeHdbValue(int datatype, int length){ - hdbValue val; - - memset(&val,0,sizeof(hdbValue)); - val.dataType = datatype; - val.doNotFree = 0; - - switch(datatype){ - case HIPINTAR: - case HIPINTVARAR: - val.arrayLength = length; - val.v.intArray = malloc(length*sizeof(int)); - if(val.v.intArray != NULL){ - memset(val.v.intArray,0,length*sizeof(int)); - } - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - val.arrayLength = length; - val.v.floatArray = malloc(length*sizeof(double)); - if(val.v.floatArray != NULL){ - memset(val.v.floatArray,0,length*sizeof(double)); - } - break; - case HIPTEXT: - val.v.text = strdup("UNKNOWN"); - val.arrayLength = length; - break; - } - return val; -} -/*-------------------------------------------------------------------------*/ -hdbValue MakeHdbInt(int initValue){ - hdbValue result; - - result.dataType = HIPINT; - result.arrayLength = 1; - result.v.intValue = initValue; - return result; -} -/*-------------------------------------------------------------------------*/ -hdbValue MakeHdbFloat(double initValue){ - hdbValue result; - - result.dataType = HIPFLOAT; - result.arrayLength = 1; - result.v.doubleValue = initValue; - return result; -} -/*-------------------------------------------------------------------------*/ -hdbValue MakeHdbText(char *initText){ - hdbValue result; - - result.dataType = HIPTEXT; - result.v.text = initText; /* no strdup here ! */ - result.arrayLength = strlen(initText); - return result; -} -/*-------------------------------------------------------------------------*/ -hdbValue MakeHdbIntArray(int length, int *data){ - hdbValue result; - - result.dataType = HIPINTAR; - result.arrayLength = length; - result.v.intArray = data; - return result; -} -/*-------------------------------------------------------------------------*/ -hdbValue MakeHdbFloatArray(int length, double *data){ - hdbValue result; - - result.dataType = HIPFLOATAR; - result.arrayLength = length; - result.v.floatArray = data; - return result; -} -/*-------------------------------------------------------------------------*/ -hdbValue MakeHdbFunc(voidFunc *func){ - hdbValue result; - - result.dataType = HIPFUNC; - result.v.func = func; - return result; -} -/*-------------------------------------------------------------------------*/ -hdbValue MakeHdbObj(void *obj){ - hdbValue result; - - result.dataType = HIPOBJ; - result.v.obj = obj; - return result; -} -/*-------------------------------------------------------------------------*/ -void ReleaseHdbValue(hdbValue *v){ - - if(v->doNotFree == 1){ - return; - } - switch(v->dataType){ - case HIPTEXT: - if(v->v.text != NULL){ - free(v->v.text); - } - break; - case HIPINTAR: - case HIPINTVARAR: - if(v->v.intArray != NULL){ - free(v->v.intArray); - } - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - if(v->v.floatArray != NULL){ - free(v->v.floatArray); - } - break; - } -} -/*------------------------------------------------------------------------*/ -int compareHdbValue(hdbValue v1, hdbValue v2){ - int i; - - if(v1.dataType != v2.dataType){ - return 0; - } - switch(v1.dataType){ - case HIPNONE: - return 0; - break; - case HIPINT: - if(v1.v.intValue == v2.v.intValue){ - return 1; - } else { - return 0; - } - break; - case HIPFLOAT: - if(ABS(v1.v.doubleValue - v2.v.doubleValue) < .01){ - return 1; - } else { - return 0; - } - break; - case HIPTEXT: - if(v1.v.text == NULL || v2.v.text == NULL){ - return 0; - } - if(strcmp(v1.v.text,v2.v.text) == 0){ - return 1; - } else { - return 0; - } - break; - case HIPINTAR: - case HIPINTVARAR: - if(v1.arrayLength != v2.arrayLength){ - return 0; - } - if(v1.v.intArray == NULL || v2.v.intArray == NULL){ - return 0; - } - for(i = 0; i < v1.arrayLength; i++){ - if(v1.v.intArray[i] != v2.v.intArray[i]){ - return 0; - } - } - return 1; - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - if(v1.arrayLength != v2.arrayLength){ - return 0; - } - if(v1.v.floatArray == NULL || v2.v.floatArray == NULL){ - return 0; - } - for(i = 0; i < v1.arrayLength; i++){ - if(ABS(v1.v.floatArray[i] - v2.v.floatArray[i]) > .01){ - return 0; - } - } - return 1; - break; - case HIPOBJ: - if(v2.v.obj == v1.v.obj) { - return 1; - } else { - return 0; - } - break; - case HIPFUNC: - if(v2.v.func == v1.v.func) { - return 1; - } else { - return 0; - } - break; - default: - assert(0); - break; - } - return 0; -} -/*-------------------------------------------------------------------------*/ -int cloneHdbValue(hdbValue *source, hdbValue *clone){ - - memset(clone,0,sizeof(hdbValue)); - clone->v.text = NULL; /* this sets all pointers in the union to NULL */ - clone->dataType = source->dataType; - return copyHdbValue(source, clone); -} -/*-------------------------------------------------------------------------*/ -int getHdbValueLength(hdbValue v){ - int length = 0; - switch(v.dataType){ - case HIPNONE: - break; - case HIPINT: - length = sizeof(int); - break; - case HIPFLOAT: - length = sizeof(double); - break; - case HIPINTAR: - case HIPINTVARAR: - length = v.arrayLength * sizeof(int); - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - length = v.arrayLength * sizeof(double); - break; - case HIPTEXT: - length = strlen(v.v.text); - break; - case HIPOBJ: - length = sizeof(void *); - break; - case HIPFUNC: - length = sizeof(voidFunc *); - break; - } - return length; -} -/*================= node functions ========================================*/ -pHdb MakeHipadabaNode(char *name, int datatype, int length){ - pHdb pNew = NULL; - - pNew = malloc(sizeof(Hdb)); - if(pNew == NULL){ - return NULL; - } - memset(pNew,0,sizeof(Hdb)); - pNew->magic = HDBMAGICK; - pNew->name = strdup(name); - pNew->value.dataType = datatype; - pNew->properties = CreateStringDict(); - if(pNew->properties == NULL || pNew->name == NULL){ - return NULL; - } - switch(datatype){ - case HIPINTAR: - case HIPINTVARAR: - pNew->value.arrayLength = length; - pNew->value.v.intArray = malloc(length*sizeof(int)); - if(pNew->value.v.intArray == NULL){ - return NULL; - } - memset(pNew->value.v.intArray,0,length*sizeof(int)); - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - pNew->value.arrayLength = length; - pNew->value.v.floatArray = malloc(length*sizeof(double)); - if(pNew->value.v.floatArray == NULL){ - return NULL; - } - memset(pNew->value.v.floatArray,0,length*sizeof(double)); - break; - case HIPTEXT: - pNew->value.arrayLength = length; - pNew->value.v.text = strdup("UNKNOWN"); - break; - } - return pNew; -} -/*-------------------------------------------------------------------------*/ -void AddHipadabaChild(pHdb parent, pHdb child, void *callData){ - pHdb current = NULL, prev = NULL; - - assert(parent != NULL); - if(child == NULL){ - return; - } - - current = parent->child; - child->mama = parent; - if(current == NULL){ - parent->child = child; - child->next = NULL; - } else { - /* - * step to end of child chain - */ - while(current != NULL){ - prev = current; - current = current->next; - } - child->next = NULL; - prev->next = child; - } - SendTreeChangeMessage(parent,callData); -} -/*--------------------------------------------------------------------------*/ -void DeleteHipadabaNode(pHdb node, void *callData){ - pHdb current = NULL, tmp = NULL; - - if(node == NULL){ - return; - } - - RemoveHdbNodeFromParent(node, callData); - - DeleteNodeData(node); -} -/*--------------------------------------------------------------------------*/ -int isHdbNodeValid(pHdb node){ - if(node == NULL){ - return 0; - } - if(node->magic == HDBMAGICK){ - return 1; - } else { - return 0; - } -} -/*--------------------------------------------------------------------------*/ -pHdb GetHipadabaNode(pHdb root, char *puth){ - pHdb resultNode = NULL; - char *separator = NULL; - char *path = NULL, *pathData; + for (ibuf = str; *ibuf && isspace(*ibuf); ++ibuf); + if (str != ibuf) + memmove(str, ibuf, ibuf - str); /* - * I need to make a copy in order to get the path in writable memory. - * Otherwise we SEGFAULT in hdbTrim when this function is called with - * a string constant in puth + ** Collapse embedded spaces (from LV1WS.C) */ - pathData = strdup(puth); - path = pathData; - if(path == NULL){ - return NULL; - } - path = hdbTrim(path); - - if(strcmp(path,"/") == 0 || strlen(path) == 0){ - free(pathData); - return root; - } - - if(path[0] == '/'){ - path++; - } - - separator = strchr(path,'/'); - if(separator == NULL){ - resultNode = locateChild(root,path); - free(pathData); - return resultNode; - } else { - *separator = '\0'; - resultNode = locateChild(root, path); - if(resultNode == NULL){ - free(pathData); - return NULL; - } else { - separator++; - resultNode = GetHipadabaNode(resultNode,separator); - free(pathData); - return resultNode; + + while (*ibuf) { + if (isspace(*ibuf) && cnt) + ibuf++; + else { + if (!isspace(*ibuf)) + cnt = 0; + else { + *ibuf = ' '; + cnt = 1; } + obuf[i++] = *ibuf++; + } } + obuf[i] = '\0'; + + /* + ** Remove trailing spaces (from RMTRAIL.C) + */ + + while (--i >= 0) { + if (!isspace(obuf[i])) + break; + } + obuf[++i] = '\0'; + } + return str; } + +/*------------------------------------------------------------------------*/ +static pHdb locateChild(pHdb root, char *name) +{ + pHdb current = NULL; + + current = root->child; + while (current != NULL) { + if (strcmp(current->name, name) == 0) { + return current; + } + current = current->next; + } + return NULL; +} + +/*================= data functions ========================================*/ +hdbValue makeHdbValue(int datatype, int length) +{ + hdbValue val; + + memset(&val, 0, sizeof(hdbValue)); + val.dataType = datatype; + val.doNotFree = 0; + + switch (datatype) { + case HIPINTAR: + case HIPINTVARAR: + val.arrayLength = length; + val.v.intArray = malloc(length * sizeof(int)); + if (val.v.intArray != NULL) { + memset(val.v.intArray, 0, length * sizeof(int)); + } + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + val.arrayLength = length; + val.v.floatArray = malloc(length * sizeof(double)); + if (val.v.floatArray != NULL) { + memset(val.v.floatArray, 0, length * sizeof(double)); + } + break; + case HIPTEXT: + val.v.text = strdup("UNKNOWN"); + val.arrayLength = length; + break; + } + return val; +} + +/*-------------------------------------------------------------------------*/ +hdbValue MakeHdbInt(int initValue) +{ + hdbValue result; + + result.dataType = HIPINT; + result.arrayLength = 1; + result.v.intValue = initValue; + return result; +} + +/*-------------------------------------------------------------------------*/ +hdbValue MakeHdbFloat(double initValue) +{ + hdbValue result; + + result.dataType = HIPFLOAT; + result.arrayLength = 1; + result.v.doubleValue = initValue; + return result; +} + +/*-------------------------------------------------------------------------*/ +hdbValue MakeHdbText(char *initText) +{ + hdbValue result; + + result.dataType = HIPTEXT; + result.v.text = initText; /* no strdup here ! */ + result.arrayLength = strlen(initText); + return result; +} + +/*-------------------------------------------------------------------------*/ +hdbValue MakeHdbIntArray(int length, int *data) +{ + hdbValue result; + + result.dataType = HIPINTAR; + result.arrayLength = length; + result.v.intArray = data; + return result; +} + +/*-------------------------------------------------------------------------*/ +hdbValue MakeHdbFloatArray(int length, double *data) +{ + hdbValue result; + + result.dataType = HIPFLOATAR; + result.arrayLength = length; + result.v.floatArray = data; + return result; +} + +/*-------------------------------------------------------------------------*/ +hdbValue MakeHdbFunc(voidFunc * func) +{ + hdbValue result; + + result.dataType = HIPFUNC; + result.v.func = func; + return result; +} + +/*-------------------------------------------------------------------------*/ +hdbValue MakeHdbObj(void *obj) +{ + hdbValue result; + + result.dataType = HIPOBJ; + result.v.obj = obj; + return result; +} + +/*-------------------------------------------------------------------------*/ +void ReleaseHdbValue(hdbValue * v) +{ + + if (v->doNotFree == 1) { + return; + } + switch (v->dataType) { + case HIPTEXT: + if (v->v.text != NULL) { + free(v->v.text); + } + break; + case HIPINTAR: + case HIPINTVARAR: + if (v->v.intArray != NULL) { + free(v->v.intArray); + } + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + if (v->v.floatArray != NULL) { + free(v->v.floatArray); + } + break; + } +} + +/*------------------------------------------------------------------------*/ +int compareHdbValue(hdbValue v1, hdbValue v2) +{ + int i; + + if (v1.dataType != v2.dataType) { + return 0; + } + switch (v1.dataType) { + case HIPNONE: + return 0; + break; + case HIPINT: + if (v1.v.intValue == v2.v.intValue) { + return 1; + } else { + return 0; + } + break; + case HIPFLOAT: + if (ABS(v1.v.doubleValue - v2.v.doubleValue) < .01) { + return 1; + } else { + return 0; + } + break; + case HIPTEXT: + if (v1.v.text == NULL || v2.v.text == NULL) { + return 0; + } + if (strcmp(v1.v.text, v2.v.text) == 0) { + return 1; + } else { + return 0; + } + break; + case HIPINTAR: + case HIPINTVARAR: + if (v1.arrayLength != v2.arrayLength) { + return 0; + } + if (v1.v.intArray == NULL || v2.v.intArray == NULL) { + return 0; + } + for (i = 0; i < v1.arrayLength; i++) { + if (v1.v.intArray[i] != v2.v.intArray[i]) { + return 0; + } + } + return 1; + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + if (v1.arrayLength != v2.arrayLength) { + return 0; + } + if (v1.v.floatArray == NULL || v2.v.floatArray == NULL) { + return 0; + } + for (i = 0; i < v1.arrayLength; i++) { + if (ABS(v1.v.floatArray[i] - v2.v.floatArray[i]) > .01) { + return 0; + } + } + return 1; + break; + case HIPOBJ: + if (v2.v.obj == v1.v.obj) { + return 1; + } else { + return 0; + } + break; + case HIPFUNC: + if (v2.v.func == v1.v.func) { + return 1; + } else { + return 0; + } + break; + default: + assert(0); + break; + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +int cloneHdbValue(hdbValue * source, hdbValue * clone) +{ + + memset(clone, 0, sizeof(hdbValue)); + clone->v.text = NULL; /* this sets all pointers in the union to NULL */ + clone->dataType = source->dataType; + return copyHdbValue(source, clone); +} + +/*-------------------------------------------------------------------------*/ +int getHdbValueLength(hdbValue v) +{ + int length = 0; + switch (v.dataType) { + case HIPNONE: + break; + case HIPINT: + length = sizeof(int); + break; + case HIPFLOAT: + length = sizeof(double); + break; + case HIPINTAR: + case HIPINTVARAR: + length = v.arrayLength * sizeof(int); + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + length = v.arrayLength * sizeof(double); + break; + case HIPTEXT: + length = strlen(v.v.text); + break; + case HIPOBJ: + length = sizeof(void *); + break; + case HIPFUNC: + length = sizeof(voidFunc *); + break; + } + return length; +} + +/*================= node functions ========================================*/ +pHdb MakeHipadabaNode(char *name, int datatype, int length) +{ + pHdb pNew = NULL; + + pNew = malloc(sizeof(Hdb)); + if (pNew == NULL) { + return NULL; + } + memset(pNew, 0, sizeof(Hdb)); + pNew->magic = HDBMAGICK; + pNew->name = strdup(name); + pNew->value.dataType = datatype; + pNew->properties = CreateStringDict(); + if (pNew->properties == NULL || pNew->name == NULL) { + return NULL; + } + switch (datatype) { + case HIPINTAR: + case HIPINTVARAR: + pNew->value.arrayLength = length; + pNew->value.v.intArray = malloc(length * sizeof(int)); + if (pNew->value.v.intArray == NULL) { + return NULL; + } + memset(pNew->value.v.intArray, 0, length * sizeof(int)); + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + pNew->value.arrayLength = length; + pNew->value.v.floatArray = malloc(length * sizeof(double)); + if (pNew->value.v.floatArray == NULL) { + return NULL; + } + memset(pNew->value.v.floatArray, 0, length * sizeof(double)); + break; + case HIPTEXT: + pNew->value.arrayLength = length; + pNew->value.v.text = strdup("UNKNOWN"); + break; + } + return pNew; +} + +/*-------------------------------------------------------------------------*/ +void AddHipadabaChild(pHdb parent, pHdb child, void *callData) +{ + pHdb current = NULL, prev = NULL; + + assert(parent != NULL); + if (child == NULL) { + return; + } + + current = parent->child; + child->mama = parent; + if (current == NULL) { + parent->child = child; + child->next = NULL; + } else { + /* + * step to end of child chain + */ + while (current != NULL) { + prev = current; + current = current->next; + } + child->next = NULL; + prev->next = child; + } + SendTreeChangeMessage(parent, callData); +} + /*--------------------------------------------------------------------------*/ -char *GetHipadabaPath(pHdb node){ - pHdb nodeStack[64]; - int depth = 0, length = 0, i; - pHdb current = NULL; - char *pPtr = NULL; - +void DeleteHipadabaNode(pHdb node, void *callData) +{ + pHdb current = NULL, tmp = NULL; + + if (node == NULL) { + return; + } + + RemoveHdbNodeFromParent(node, callData); + + DeleteNodeData(node); +} + +/*--------------------------------------------------------------------------*/ +int isHdbNodeValid(pHdb node) +{ + if (node == NULL) { + return 0; + } + if (node->magic == HDBMAGICK) { + return 1; + } else { + return 0; + } +} + +/*--------------------------------------------------------------------------*/ +pHdb GetHipadabaNode(pHdb root, char *puth) +{ + pHdb resultNode = NULL; + char *separator = NULL; + char *path = NULL, *pathData; + + /* + * I need to make a copy in order to get the path in writable memory. + * Otherwise we SEGFAULT in hdbTrim when this function is called with + * a string constant in puth + */ + pathData = strdup(puth); + path = pathData; + if (path == NULL) { + return NULL; + } + path = hdbTrim(path); + + if (strcmp(path, "/") == 0 || strlen(path) == 0) { + free(pathData); + return root; + } + + if (path[0] == '/') { + path++; + } + + separator = strchr(path, '/'); + if (separator == NULL) { + resultNode = locateChild(root, path); + free(pathData); + return resultNode; + } else { + *separator = '\0'; + resultNode = locateChild(root, path); + if (resultNode == NULL) { + free(pathData); + return NULL; + } else { + separator++; + resultNode = GetHipadabaNode(resultNode, separator); + free(pathData); + return resultNode; + } + } +} + +/*--------------------------------------------------------------------------*/ +char *GetHipadabaPath(pHdb node) +{ + pHdb nodeStack[64]; + int depth = 0, length = 0, i; + pHdb current = NULL; + char *pPtr = NULL; + /** * build a nodestack and find out required string length for path */ - current = node; - while(current != NULL){ - length += strlen(current->name) + 1; - nodeStack[depth] = current; - depth++; - assert(depth < 64); - current = current->mama; - } - - pPtr = malloc(length*sizeof(char)); - if(pPtr == NULL){ - return NULL; - } - memset(pPtr,0,length*sizeof(char)); - - /* - * we wish to decremement by one because above loop - * increments one to many and we wish to ignore the - * root node - */ - for(i = depth - 2; i >= 0; i--){ - strcat(pPtr,"/"); - strcat(pPtr,nodeStack[i]->name); - } - return pPtr; -} + current = node; + while (current != NULL) { + length += strlen(current->name) + 1; + nodeStack[depth] = current; + depth++; + assert(depth < 64); + current = current->mama; + } + + pPtr = malloc(length * sizeof(char)); + if (pPtr == NULL) { + return NULL; + } + memset(pPtr, 0, length * sizeof(char)); + + /* + * we wish to decremement by one because above loop + * increments one to many and we wish to ignore the + * root node + */ + for (i = depth - 2; i >= 0; i--) { + strcat(pPtr, "/"); + strcat(pPtr, nodeStack[i]->name); + } + return pPtr; +} + /*==================== Callback Functions ==================================*/ -pHdbCallback MakeHipadabaCallback(hdbCallbackFunction func, - void *userData, killUserData killFunc){ - pHdbCallback pNew = NULL; - - assert(func != NULL); - - pNew = malloc(sizeof(hdbCallback)); - if(pNew == NULL){ - return NULL; - } - memset(pNew,0,sizeof(hdbCallback)); - - pNew->userCallback = func; - pNew->userData = userData; - pNew->killFunc = killFunc; - return pNew; +pHdbCallback MakeHipadabaCallback(hdbCallbackFunction func, + void *userData, killUserData killFunc) +{ + pHdbCallback pNew = NULL; + + assert(func != NULL); + + pNew = malloc(sizeof(hdbCallback)); + if (pNew == NULL) { + return NULL; + } + memset(pNew, 0, sizeof(hdbCallback)); + + pNew->userCallback = func; + pNew->userData = userData; + pNew->killFunc = killFunc; + return pNew; } + /*-------------------------------------------------------------------*/ -void AppendHipadabaCallback(pHdb node, pHdbCallback newCB){ - pHdbCallback current = NULL; - - assert(node); - current = node->callBackChain; - newCB->next = NULL; - if(current == NULL){ - node->callBackChain = newCB; - return; - } - while(current->next != NULL){ - current = (pHdbCallback)current->next; - } - current->next = newCB; +void AppendHipadabaCallback(pHdb node, pHdbCallback newCB) +{ + pHdbCallback current = NULL; + + assert(node); + current = node->callBackChain; + newCB->next = NULL; + if (current == NULL) { + node->callBackChain = newCB; + return; + } + while (current->next != NULL) { + current = (pHdbCallback) current->next; + } + current->next = newCB; } + /*---------------------------------------------------------------------------*/ -void PrependHipadabaCallback(pHdb node,pHdbCallback newCB){ - assert(node != NULL); - - newCB->next = node->callBackChain; - node->callBackChain = newCB; +void PrependHipadabaCallback(pHdb node, pHdbCallback newCB) +{ + assert(node != NULL); + + newCB->next = node->callBackChain; + node->callBackChain = newCB; } + /*----------------------------------------------------------------------------*/ -void *FindHdbCallbackData(pHdb node, void *userPtr){ +void *FindHdbCallbackData(pHdb node, void *userPtr) +{ hdbDataSearch dsm; - + dsm.type = dataSearch; dsm.testPtr = userPtr; dsm.result = NULL; - InvokeCallbackChain(node, (pHdbMessage)&dsm); + InvokeCallbackChain(node, (pHdbMessage) & dsm); return dsm.result; } + /*=================== parameter interface ====================================*/ -static int canCopy(hdbValue *source, hdbValue *target){ - if(target->dataType == HIPINTVARAR) { - if(source->dataType == HIPINTAR || - source->dataType == HIPINTVARAR){ - return 1; - } +static int canCopy(hdbValue * source, hdbValue * target) +{ + if (target->dataType == HIPINTVARAR) { + if (source->dataType == HIPINTAR || source->dataType == HIPINTVARAR) { + return 1; } - if(target->dataType == HIPFLOATVARAR) { - if(source->dataType == HIPFLOATAR || - source->dataType == HIPFLOATVARAR){ - return 1; - } - } - if(source->dataType != target->dataType){ - return 0; - } else { - return 1; - } -} -/*----------------------------------------------------------------------------*/ -int copyHdbValue(hdbValue *source, hdbValue *target){ - int i; - - if(!canCopy(source,target)){ - return 0; - } - - switch(source->dataType){ - case HIPNONE: - break; - case HIPINT: - target->v.intValue = source->v.intValue; - break; - case HIPFLOAT: - target->v.doubleValue = source->v.doubleValue; - break; - case HIPTEXT: - if(target->v.text != NULL){ - free(target->v.text); - } - target->v.text = strdup(source->v.text); - break; - case HIPINTAR: - case HIPINTVARAR: - if(target->arrayLength != source->arrayLength || target->v.intArray == NULL){ - if(target->v.intArray != NULL){ - free(target->v.intArray); - } - target->v.intArray = malloc(source->arrayLength * sizeof(int)); - if(target->v.intArray == NULL){ - return 0; - } - memset(target->v.intArray,0,source->arrayLength - * sizeof(int)); - target->arrayLength = source->arrayLength; - } - if(source->v.intArray != NULL){ - for(i = 0; i < source->arrayLength; i++){ - target->v.intArray[i] = source->v.intArray[i]; - } - } - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - if(target->arrayLength != source->arrayLength - || target->v.floatArray == NULL){ - if(target->v.floatArray != NULL){ - free(target->v.floatArray); - } - target->v.floatArray = - malloc(source->arrayLength * sizeof(double)); - if(target->v.floatArray == NULL){ - return 0; - } - memset(target->v.floatArray,0,source->arrayLength * - sizeof(double)); - target->arrayLength = source->arrayLength; - } - if(source->v.floatArray != NULL){ - for(i = 0; i < source->arrayLength; i++){ - target->v.floatArray[i] = source->v.floatArray[i]; - } - } - break; - case HIPOBJ: - target->v.obj = source->v.obj; - break; - case HIPFUNC: - target->v.func = source->v.func; - break; - default: - /* - * unknown data type - */ - assert(0); - break; + } + if (target->dataType == HIPFLOATVARAR) { + if (source->dataType == HIPFLOATAR || + source->dataType == HIPFLOATVARAR) { + return 1; } + } + if (source->dataType != target->dataType) { + return 0; + } else { return 1; + } } + +/*----------------------------------------------------------------------------*/ +int copyHdbValue(hdbValue * source, hdbValue * target) +{ + int i; + + if (!canCopy(source, target)) { + return 0; + } + + switch (source->dataType) { + case HIPNONE: + break; + case HIPINT: + target->v.intValue = source->v.intValue; + break; + case HIPFLOAT: + target->v.doubleValue = source->v.doubleValue; + break; + case HIPTEXT: + if (target->v.text != NULL) { + free(target->v.text); + } + target->v.text = strdup(source->v.text); + break; + case HIPINTAR: + case HIPINTVARAR: + if (target->arrayLength != source->arrayLength + || target->v.intArray == NULL) { + if (target->v.intArray != NULL) { + free(target->v.intArray); + } + target->v.intArray = malloc(source->arrayLength * sizeof(int)); + if (target->v.intArray == NULL) { + return 0; + } + memset(target->v.intArray, 0, source->arrayLength * sizeof(int)); + target->arrayLength = source->arrayLength; + } + if (source->v.intArray != NULL) { + for (i = 0; i < source->arrayLength; i++) { + target->v.intArray[i] = source->v.intArray[i]; + } + } + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + if (target->arrayLength != source->arrayLength + || target->v.floatArray == NULL) { + if (target->v.floatArray != NULL) { + free(target->v.floatArray); + } + target->v.floatArray = malloc(source->arrayLength * sizeof(double)); + if (target->v.floatArray == NULL) { + return 0; + } + memset(target->v.floatArray, 0, source->arrayLength * + sizeof(double)); + target->arrayLength = source->arrayLength; + } + if (source->v.floatArray != NULL) { + for (i = 0; i < source->arrayLength; i++) { + target->v.floatArray[i] = source->v.floatArray[i]; + } + } + break; + case HIPOBJ: + target->v.obj = source->v.obj; + break; + case HIPFUNC: + target->v.func = source->v.func; + break; + default: + /* + * unknown data type + */ + assert(0); + break; + } + return 1; +} + /*---------------------------------------------------------------------------*/ -static int SendDataMessage(pHdb node, char *type, - hdbValue v, void *callData){ - hdbDataMessage dataMes; +static int SendDataMessage(pHdb node, char *type, + hdbValue v, void *callData) +{ + hdbDataMessage dataMes; - assert(type == set || type == get || type == update); - dataMes.type = type; - dataMes.v = &v; - dataMes.callData = callData; - return InvokeCallbackChain(node, (pHdbMessage)&dataMes); + assert(type == set || type == get || type == update); + dataMes.type = type; + dataMes.v = &v; + dataMes.callData = callData; + return InvokeCallbackChain(node, (pHdbMessage) & dataMes); } + /*----------------------------------------------------------------------------*/ -int SetHipadabaPar(pHdb node, hdbValue v, void *callData){ - return SendDataMessage(node, set, v,callData); +int SetHipadabaPar(pHdb node, hdbValue v, void *callData) +{ + return SendDataMessage(node, set, v, callData); } -/*-----------------------------------------------------------------------------*/ -int UpdateHipadabaPar(pHdb node, hdbValue v, void *callData){ - int status; - status = SendDataMessage(node, update, v,callData); - if(status == 1){ - copyHdbValue(&v,&node->value); - } - return status; -} /*-----------------------------------------------------------------------------*/ -int NotifyHipadabaPar(pHdb node,void *callData){ - SendDataMessage(node, update, node->value,callData); - return 1; -} -/*-----------------------------------------------------------------------------*/ -int GetHipadabaPar(pHdb node, hdbValue *v, void *callData){ - int status; - - v->dataType = node->value.dataType; - v->doNotFree = 0; - v->v.text = NULL; /* this sets all pointers in the union to NULL */ +int UpdateHipadabaPar(pHdb node, hdbValue v, void *callData) +{ + int status; - status = SendDataMessage(node, get, *v,callData); - if(status != 1 ){ - return status; - } - copyHdbValue(&node->value,v); - return 1; + status = SendDataMessage(node, update, v, callData); + if (status == 1) { + copyHdbValue(&v, &node->value); + } + return status; } + +/*-----------------------------------------------------------------------------*/ +int NotifyHipadabaPar(pHdb node, void *callData) +{ + SendDataMessage(node, update, node->value, callData); + return 1; +} + +/*-----------------------------------------------------------------------------*/ +int GetHipadabaPar(pHdb node, hdbValue * v, void *callData) +{ + int status; + + v->dataType = node->value.dataType; + v->doNotFree = 0; + v->v.text = NULL; /* this sets all pointers in the union to NULL */ + + status = SendDataMessage(node, get, *v, callData); + copyHdbValue(&node->value, v); + if (status != 1) { + return status; + } + return 1; +} + /*----------------------------------------------------------------------------*/ -static int calcDataLength(pHdb node, int testLength){ - int length = 0; +static int calcDataLength(pHdb node, int testLength) +{ + int length = 0; + + length = getHdbValueLength(node->value); + if (node->value.dataType == HIPFLOATVARAR || + node->value.dataType == HIPINTVARAR || + node->value.dataType == HIPTEXT) { + length = testLength; + } + return length; +} - length = getHdbValueLength(node->value); - if(node->value.dataType == HIPFLOATVARAR || - node->value.dataType == HIPINTVARAR || - node->value.dataType == HIPTEXT){ - length = testLength; - } - return length; -} /*============================= Property Functions ==========================*/ - void SetHdbProperty(pHdb node, char *key, char *value){ - if(node != NULL && key != NULL && node->properties != NULL){ - if (value == NULL) { - StringDictDelete(node->properties, key); - } else if(StringDictExists(node->properties, key)){ - StringDictUpdate(node->properties,key,value); - } else { - StringDictAddPair(node->properties,key,value); - } - } - } -/*---------------------------------------------------------------------------*/ -int GetHdbProperty(pHdb node, char *key, char *value, int len){ - if(node != NULL && node->properties != NULL){ - return StringDictGet(node->properties,key,value,len); - } else { - return 0; - } +void SetHdbProperty(pHdb node, char *key, char *value) +{ + if (node != NULL && key != NULL && node->properties != NULL) { + if (value == NULL) { + StringDictDelete(node->properties, key); + } else if (StringDictExists(node->properties, key)) { + StringDictUpdate(node->properties, key, value); + } else { + StringDictAddPair(node->properties, key, value); + } + } } + /*---------------------------------------------------------------------------*/ -char *GetHdbProp(pHdb node, char *key){ - if(node != NULL && node->properties != NULL){ - return StringDictGetShort(node->properties,key); - } else { - return NULL; - } +int GetHdbProperty(pHdb node, char *key, char *value, int len) +{ + if (node != NULL && node->properties != NULL) { + return StringDictGet(node->properties, key, value, len); + } else { + return 0; + } } + /*---------------------------------------------------------------------------*/ -void InitHdbPropertySearch(pHdb node){ - if(node != NULL && node->properties != NULL){ - StringDictKillScan(node->properties); - } +char *GetHdbProp(pHdb node, char *key) +{ + if (node != NULL && node->properties != NULL) { + return StringDictGetShort(node->properties, key); + } else { + return NULL; + } } + +/*---------------------------------------------------------------------------*/ +void InitHdbPropertySearch(pHdb node) +{ + if (node != NULL && node->properties != NULL) { + StringDictKillScan(node->properties); + } +} + /*--------------------------------------------------------------------------*/ -const char *GetNextHdbProperty(pHdb node, char *value ,int len){ - if(node != NULL && node->properties != NULL) { - return StringDictGetNext(node->properties, value, len); - } else { - return NULL; - } -} +const char *GetNextHdbProperty(pHdb node, char *value, int len) +{ + if (node != NULL && node->properties != NULL) { + return StringDictGetNext(node->properties, value, len); + } else { + return NULL; + } +} diff --git a/hipadaba.h b/hipadaba.h index e94c7234..554da777 100644 --- a/hipadaba.h +++ b/hipadaba.h @@ -49,71 +49,72 @@ typedef void voidFunc(void); typedef struct __hdbValue { - int dataType; - int arrayLength; - int doNotFree; - union __value { - int intValue; - double doubleValue; - char *text; - int *intArray; - double *floatArray; - voidFunc *func; - void *obj; - }v; -}hdbValue; + int dataType; + int arrayLength; + int doNotFree; + union __value { + int intValue; + double doubleValue; + char *text; + int *intArray; + double *floatArray; + voidFunc *func; + void *obj; + } v; +} hdbValue; /*------------------------------------------------------------------------------*/ typedef struct __hipadaba { - int magic; - struct __hipadaba *mama; - struct __hipadaba *child; - struct __hipadaba *next; - struct __hdbcallback *callBackChain; - char *name; - hdbValue value; - int protected; - pStringDict properties; - }Hdb, *pHdb; + int magic; + struct __hipadaba *mama; + struct __hipadaba *child; + struct __hipadaba *next; + struct __hdbcallback *callBackChain; + char *name; + hdbValue value; + int protected; + pStringDict properties; +} Hdb, *pHdb; /*-------------- return values for callback functions -------------------------*/ -typedef enum {hdbContinue, - hdbAbort, - hdbKill } hdbCallbackReturn; +typedef enum { hdbContinue, + hdbAbort, + hdbKill +} hdbCallbackReturn; /*======================== Messages ===========================================*/ typedef struct __hdbMessage { - char *type; + char *type; } hdbMessage, *pHdbMessage; /*-----------------------------------------------------------------------------*/ typedef struct { - char *type; - hdbValue *v; - void *callData; -}hdbDataMessage, *pHdbDataMessage; + char *type; + hdbValue *v; + void *callData; +} hdbDataMessage, *pHdbDataMessage; /*-------------------------------------------------------------------------------*/ typedef struct { - char *type; - void *callData; -}hdbTreeChangeMessage, *pHdbTreeChangeMessage; + char *type; + void *callData; +} hdbTreeChangeMessage, *pHdbTreeChangeMessage; /*-------------------------------------------------------------------------------*/ typedef struct { - char *type; - void *testPtr; - void *result; -}hdbDataSearch, *pHdbDataSearch; + char *type; + void *testPtr; + void *result; +} hdbDataSearch, *pHdbDataSearch; /*-------------------------------------------------------------------------------*/ -typedef hdbCallbackReturn (*hdbCallbackFunction)(pHdb currentNode, - void *userData, - pHdbMessage message); +typedef hdbCallbackReturn(*hdbCallbackFunction) (pHdb currentNode, + void *userData, + pHdbMessage message); -typedef void (*killUserData)(void *data); +typedef void (*killUserData) (void *data); /*-------------------------------------------------------------------------------*/ typedef struct __hdbcallback { - void *userData; - killUserData killFunc; - hdbCallbackFunction userCallback; - int killFlag; - struct __hdbcallback *next; - struct __hdbcallback *previous; - }hdbCallback, *pHdbCallback; + void *userData; + killUserData killFunc; + hdbCallbackFunction userCallback; + int killFlag; + struct __hdbcallback *next; + struct __hdbcallback *previous; +} hdbCallback, *pHdbCallback; /*============= Message Test Functions ==========================================*/ /** * Test a message if it is a set message @@ -162,7 +163,7 @@ pHdbMessage GetHdbKillNodeMessage(pHdbMessage toTest); * @param datatype The datatype of the hdbValue * @param length The array length of the hdbValue * @return a suitably defined hdbValue - */ + */ hdbValue makeHdbValue(int datatype, int length); /** * wrap an integer as an hdbValue @@ -194,7 +195,7 @@ hdbValue MakeHdbText(char *initText); * data points to dynamically allocated memory. * @return: A properly initialized hdbValue structure */ -hdbValue MakeHdbIntArray(int length, int *data); +hdbValue MakeHdbIntArray(int length, int *data); /** * wrap a float array as an hdbValue * @param length The length of the int array @@ -204,13 +205,13 @@ hdbValue MakeHdbIntArray(int length, int *data); * data points to dynamically allocated memory. * @return: A properly initialized hdbValue structure */ -hdbValue MakeHdbFloatArray(int length, double *data); +hdbValue MakeHdbFloatArray(int length, double *data); /** * wrap a function as an hdbValue * @param func the function * @return: A properly initialized hdbValue structure */ -hdbValue MakeHdbFunc(voidFunc *func); +hdbValue MakeHdbFunc(voidFunc * func); /** * wrap an object as an hdbValue * @param obj the object @@ -222,14 +223,14 @@ hdbValue MakeHdbObj(void *obj); * @param v The hdbValue to check for dynamic memory allocation to be * released. */ -void ReleaseHdbValue(hdbValue *v); +void ReleaseHdbValue(hdbValue * v); /** * copy a hipadaba value field. Takes care of memory allocation * @param source The hdbValue to copy from * @param target The hdbValue to copy to. * @return 1 on success, 0 when out of memory or when type mismatch */ -int copyHdbValue(hdbValue *source, hdbValue *target); +int copyHdbValue(hdbValue * source, hdbValue * target); /** * compares two hdbValues for identity * @param v1 The first hdbValue @@ -245,7 +246,7 @@ int compareHdbValue(hdbValue v1, hdbValue v2); * @param clone the target hdbValue structure * @return 1 on success, 0 on when out of memory */ -int cloneHdbValue(hdbValue *source, hdbValue *clone); +int cloneHdbValue(hdbValue * source, hdbValue * clone); /** * get the length of the hdbValue in bytes. * @param v The hdbValue to calculate the length for @@ -259,7 +260,7 @@ int getHdbValueLength(hdbValue v); * @param datatype The datatype of the new node * @param length the array length * @return a new node or NULL when out of memory - */ + */ pHdb MakeHipadabaNode(char *name, int datatype, int length); /** * add a child to a node at the end of the child list. @@ -267,7 +268,7 @@ pHdb MakeHipadabaNode(char *name, int datatype, int length); * @param child The node to add * @param callData User data for the tree chnage callback. Can be NULL. */ -void AddHipadabaChild(pHdb parent, pHdb child, void *callData); +void AddHipadabaChild(pHdb parent, pHdb child, void *callData); /** * Delete only the node data, without invoking any callbacks * @param node The node to delete. @@ -291,14 +292,14 @@ int isHdbNodeValid(pHdb node); * @param root The node where to start the search for the node * @param path The unix path string for the node relative to parent * @return The desired node or NULL when no such node exists - */ + */ pHdb GetHipadabaNode(pHdb root, char *path); /** * given a node, return the full path name to the node * @param node The node to get the path for * @return The full path to the node. This is dynamically allocated memory; * the caller is reponsible for deleting it. Can be NULL when out of memory. - */ + */ char *GetHipadabaPath(pHdb node); /** * removes a node from the parents child list. @@ -321,21 +322,21 @@ int CountHdbChildren(pHdb node); * not be invoked * @return A new suitabaly initialised callback structure or NULL when required elements * are missing or there is nor memory. - */ -pHdbCallback MakeHipadabaCallback(hdbCallbackFunction func, - void *userData, killUserData killFunc); + */ +pHdbCallback MakeHipadabaCallback(hdbCallbackFunction func, + void *userData, killUserData killFunc); /** * add a callback at the end of the callback chain * @param node The node to which to append the callback * @param newCB The callback to append */ -void AppendHipadabaCallback(pHdb node,pHdbCallback newCB); +void AppendHipadabaCallback(pHdb node, pHdbCallback newCB); /** * add a callback at the head of the callback chain * @param node The node to which to append the callback * @param newCB The callback prepend */ -void PrependHipadabaCallback(pHdb node,pHdbCallback newCB); +void PrependHipadabaCallback(pHdb node, pHdbCallback newCB); /** * find the callback data * @param node the node from where callbacks have to be searched @@ -371,7 +372,7 @@ void RecurseCallbackChains(pHdb node, pHdbMessage message); * @param v The new value for the node * @param callData Additonal context data to be passed to the callback functions * @return 0 on failure, 1 on success - */ + */ int SetHipadabaPar(pHdb node, hdbValue v, void *callData); /** * Update a hipadaba parameter. This is an internal update of a parameter, @@ -380,7 +381,7 @@ int SetHipadabaPar(pHdb node, hdbValue v, void *callData); * @param v The new value for the node * @param callData Additonal context data to be passed to the callback functions * @return 0 on failure, 1 on success - */ + */ int UpdateHipadabaPar(pHdb node, hdbValue v, void *callData); /** * notify any update listeners that this node has been internally modifed. @@ -388,7 +389,7 @@ int UpdateHipadabaPar(pHdb node, hdbValue v, void *callData); * @param callData Addtional data for the callback * @return 1 on success, 0 on failure */ -int NotifyHipadabaPar(pHdb node,void *callData); +int NotifyHipadabaPar(pHdb node, void *callData); /** * Read a hipadaba parameter @@ -396,16 +397,17 @@ int NotifyHipadabaPar(pHdb node,void *callData); * @param v The read value for the node * @param callData Additonal context data to be passed to the callback functions * @return 0 on failure, 1 on success - */ -int GetHipadabaPar(pHdb node, hdbValue *v, void *callData); + */ +int GetHipadabaPar(pHdb node, hdbValue * v, void *callData); /*================================ Property Interface ==============================================*/ /** - * set a property + * Set or delete a property * @param node The node to set the property for * @param key The key for the property - * @param value The value of the property + * @param value The value of the property. If this is NULL, the + * property is deleted. */ - void SetHdbProperty(pHdb node, char *key, char *value); +void SetHdbProperty(pHdb node, char *key, char *value); /** * get the value of a property * @param node The node to get the property from @@ -414,7 +416,7 @@ int GetHipadabaPar(pHdb node, hdbValue *v, void *callData); * @param len The length of value * @return 0 on failure, 1 on success */ - int GetHdbProperty(pHdb node, char *key, char *value, int len); +int GetHdbProperty(pHdb node, char *key, char *value, int len); /** * get the value of a property * @param node The node to get the property from @@ -422,11 +424,11 @@ int GetHipadabaPar(pHdb node, hdbValue *v, void *callData); * @return the property or NULL on failure. Warning: the string is * only valid as long as the property has not changed */ - char *GetHdbProp(pHdb node, char *key); +char *GetHdbProp(pHdb node, char *key); /** * initialize a property scan on this node * @param node The node for which to scan properties - */ + */ void InitHdbPropertySearch(pHdb node); /** * get the next property in a search @@ -434,6 +436,6 @@ void InitHdbPropertySearch(pHdb node); * @param value An area where to copy the value of the property * @param len The length of value * @return The key of the property or NULL when the property list is exhausted - */ -const char *GetNextHdbProperty(pHdb node, char *value ,int len); + */ +const char *GetNextHdbProperty(pHdb node, char *value, int len); #endif diff --git a/histdriv.c b/histdriv.c index 14304f87..b227a742 100644 --- a/histdriv.c +++ b/histdriv.c @@ -50,73 +50,71 @@ #include "HistDriv.i" /*--------------------------------------------------------------------------*/ - pHistDriver CreateHistDriver(pStringDict pOption) - { - pHistDriver pNew = NULL; - char pDim[20]; - int i; +pHistDriver CreateHistDriver(pStringDict pOption) +{ + pHistDriver pNew = NULL; + char pDim[20]; + int i; - /* allocate some more memory */ - pNew = (pHistDriver)malloc(sizeof(HistDriver)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(HistDriver)); - - pNew->data = makeHMData(); - if(!pNew->data) - { - free(pNew); - return NULL; - } - - /* initialise defaults */ - StringDictAddPair(pOption,"rank","1"); - for(i = 0; i < MAXDIM; i++) - { - sprintf(pDim,"dim%1.1d",i); - StringDictAddPair(pOption,pDim,"-126"); - } - pNew->fCountPreset = 10.; - pNew->eCount = eTimer; - pNew->iReconfig = 1; - pNew->iUpdate = 0; - - return pNew; - } -/*-------------------------------------------------------------------------*/ - void DeleteHistDriver(pHistDriver self) - { - assert(self); - - if(self->FreePrivate) - { - self->FreePrivate(self); - } - if(self->pOption){ - DeleteStringDict(self->pOption); - } - if(self->data) - { - killHMData(self->data); - } - free(self); - } -/*------------------------------------------------------------------------*/ - int HistDriverConfig(pHistDriver self, pStringDict pOpt, SConnection *pCon) - { - int iRet; - char pBueffel[512]; - char pValue[80]; - float fVal; - TokenList *pList = NULL, *pCurrent; - char *pBuf = NULL; - int i; - - assert(self); - assert(pOpt); - assert(pCon); - - return configureHMdata(self->data,pOpt,pCon); + /* allocate some more memory */ + pNew = (pHistDriver) malloc(sizeof(HistDriver)); + if (!pNew) { + return NULL; } + memset(pNew, 0, sizeof(HistDriver)); + + pNew->data = makeHMData(); + if (!pNew->data) { + free(pNew); + return NULL; + } + + /* initialise defaults */ + StringDictAddPair(pOption, "rank", "1"); + for (i = 0; i < MAXDIM; i++) { + sprintf(pDim, "dim%1.1d", i); + StringDictAddPair(pOption, pDim, "-126"); + } + pNew->fCountPreset = 10.; + pNew->eCount = eTimer; + pNew->iReconfig = 1; + pNew->iUpdate = 0; + + return pNew; +} + +/*-------------------------------------------------------------------------*/ +void DeleteHistDriver(pHistDriver self) +{ + assert(self); + + if (self->FreePrivate) { + self->FreePrivate(self); + } + if (self->pOption) { + DeleteStringDict(self->pOption); + } + if (self->data) { + killHMData(self->data); + } + free(self); +} + +/*------------------------------------------------------------------------*/ +int HistDriverConfig(pHistDriver self, pStringDict pOpt, + SConnection * pCon) +{ + int iRet; + char pBueffel[512]; + char pValue[80]; + float fVal; + TokenList *pList = NULL, *pCurrent; + char *pBuf = NULL; + int i; + + assert(self); + assert(pOpt); + assert(pCon); + + return configureHMdata(self->data, pOpt, pCon); +} diff --git a/histmem.c b/histmem.c index 3a111160..a866a23d 100644 --- a/histmem.c +++ b/histmem.c @@ -77,1748 +77,1583 @@ extern pHistDriver CreateRegressHM(pStringDict pOpt); */ extern pHistDriver MakeHMSlaveHM(pStringDict pOpt); /*------------------------------------------------------------------------*/ - static int HistHalt(void *pData) - { - pHistMem self = NULL; +static int HistHalt(void *pData) +{ + pHistMem self = NULL; - self = (pHistMem)pData; - assert(self); + self = (pHistMem) pData; + assert(self); + + if (!self->iInit) { + return 0; + } + return self->pDriv->Halt(self->pDriv); +} - if(!self->iInit) - { - return 0; - } - return self->pDriv->Halt(self->pDriv); - } /*------------------------------------------------------------------------*/ - static int HistSave(void *pData, char *name, FILE *fd) - { - pHistMem self = NULL; - char *pMode[] = { - "timer", - "monitor", - NULL - }; - CounterMode eCount; - float fVal; - - self = (pHistMem)pData; - assert(self); +static int HistSave(void *pData, char *name, FILE * fd) +{ + pHistMem self = NULL; + char *pMode[] = { + "timer", + "monitor", + NULL + }; + CounterMode eCount; + float fVal; - if(!self->iInit) - { - return 0; - } + self = (pHistMem) pData; + assert(self); - /* counting modes */ - eCount = GetHistCountMode(self); - fprintf(fd,"%s CountMode %s\n",name,pMode[eCount]); - fVal = GetHistPreset(self); - fprintf(fd,"%s preset %f\n",name,fVal); - - /* time binning if TOF */ - if(isInTOFMode(self->pDriv->data)) - { - fprintf(fd,"%s genbin %f %f %d\n", - name, self->pDriv->data->timeBinning[0], - self->pDriv->data->timeBinning[1] - - self->pDriv->data->timeBinning[0], - self->pDriv->data->nTimeChan); - fprintf(fd,"%s init\n",name); - } + if (!self->iInit) { + return 0; + } + + /* counting modes */ + eCount = GetHistCountMode(self); + fprintf(fd, "%s CountMode %s\n", name, pMode[eCount]); + fVal = GetHistPreset(self); + fprintf(fd, "%s preset %f\n", name, fVal); + + /* time binning if TOF */ + if (isInTOFMode(self->pDriv->data)) { + fprintf(fd, "%s genbin %f %f %d\n", + name, self->pDriv->data->timeBinning[0], + self->pDriv->data->timeBinning[1] - + self->pDriv->data->timeBinning[0], + self->pDriv->data->nTimeChan); + fprintf(fd, "%s init\n", name); + } + + return 1; +} - return 1; - } /*------------------------------------------------------------------------*/ - static void *GetHistInterface(void *pData, int iID) - { - pHistMem self = NULL; - - self = (pHistMem)pData; - if(iID == COUNTID) - { - return self->pCountInt; - } - else if(iID == CALLBACKINTERFACE) - { - return self->pCall; - } - return NULL; +static void *GetHistInterface(void *pData, int iID) +{ + pHistMem self = NULL; + + self = (pHistMem) pData; + if (iID == COUNTID) { + return self->pCountInt; + } else if (iID == CALLBACKINTERFACE) { + return self->pCall; } + return NULL; +} + /*------------------------------------------------------------------------*/ - static void HistSetParameter(void *pData, float fPreset, CounterMode eMode) - { - pHistMem self = NULL; +static void HistSetParameter(void *pData, float fPreset, CounterMode eMode) +{ + pHistMem self = NULL; - self = (pHistMem)pData; - assert(self); + self = (pHistMem) pData; + assert(self); + + self->pDriv->eCount = eMode; + self->pDriv->fCountPreset = fPreset; +} - self->pDriv->eCount = eMode; - self->pDriv->fCountPreset = fPreset; - } /*-------------------------------------------------------------------------*/ - static int HistStartCount(void *pData, SConnection *pCon) - { - pHistMem self = NULL; - char pBueffel[512]; - char pError[80]; - int iErr, iRet, i; - - self = (pHistMem)pData; - assert(self); +static int HistStartCount(void *pData, SConnection * pCon) +{ + pHistMem self = NULL; + char pBueffel[512]; + char pError[80]; + int iErr, iRet, i; - if(!GetCountLock(self->pCountInt, pCon)){ - return HWFault; - } - - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - return 0; - } + self = (pHistMem) pData; + assert(self); - /* try at least three times to do it */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->Start(self->pDriv, pCon); - if(iRet == OKOK) - { - /* send a COUNTSTART event */ - InvokeCallBack(self->pCall,COUNTSTART,pCon); - updateHMData(self->pDriv->data); - return iRet; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"WARNING: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - SCWrite(pCon,"ERROR: failed to fix histogram memory problem", - eError); - SCSetInterrupt(pCon,eAbortBatch); - ReleaseCountLock(self->pCountInt); - return HWFault; - } - } - } - SCWrite(pCon,"ERROR: failed to fix histogram memory problem",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; + if (!GetCountLock(self->pCountInt, pCon)) { + return HWFault; } -/*-------------------------------------------------------------------------*/ - static int HistPause(void *pData, SConnection *pCon) - { - pHistMem self = NULL; - char pBueffel[512]; - char pError[80]; - int iErr, iRet, i; - - self = (pHistMem)pData; - assert(self); - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - return 0; - } - - /* try at least three times to do it */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->Pause(self->pDriv, pCon); - if(iRet == OKOK) - { - updateHMData(self->pDriv->data); - return iRet; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"WARNING: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - SCWrite(pCon,"ERROR: failed to fix histogram memory problem",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; - } - } - } - SCWrite(pCon,"ERROR: failed to fix histogram memory problem",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + return 0; } - -/*-------------------------------------------------------------------------*/ - static int HistContinue(void *pData, SConnection *pCon) - { - pHistMem self = NULL; - char pBueffel[512]; - char pError[80]; - int iErr, iRet, i; - - self = (pHistMem)pData; - assert(self); - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - return 0; + /* try at least three times to do it */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->Start(self->pDriv, pCon); + if (iRet == OKOK) { + /* send a COUNTSTART event */ + InvokeCallBack(self->pCall, COUNTSTART, pCon); + updateHMData(self->pDriv->data); + return iRet; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "WARNING: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + SCWrite(pCon, "ERROR: failed to fix histogram memory problem", + eError); + SCSetInterrupt(pCon, eAbortBatch); + ReleaseCountLock(self->pCountInt); + return HWFault; + } } - - /* try at least three times to do it */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->Continue(self->pDriv, pCon); - if(iRet == OKOK) - { - updateHMData(self->pDriv->data); - return iRet; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"WARNING: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - SCWrite(pCon,"ERROR: failed to fix histogram memory problem",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; - } - } - } - SCWrite(pCon,"ERROR: failed to fix histogram memory problem",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; } + SCWrite(pCon, "ERROR: failed to fix histogram memory problem", eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; +} + /*-------------------------------------------------------------------------*/ - static int HistCountStatus(void *pData, SConnection *pCon) - { - pHistMem self = NULL; - int eCt, iRet, iErr; - char pBueffel[512], pError[90]; - - self = (pHistMem)pData; - assert(self); - - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - InvokeCallBack(self->pCall,COUNTEND,NULL); - return COTERM; +static int HistPause(void *pData, SConnection * pCon) +{ + pHistMem self = NULL; + char pBueffel[512]; + char pError[80]; + int iErr, iRet, i; + + self = (pHistMem) pData; + assert(self); + + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + return 0; + } + + /* try at least three times to do it */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->Pause(self->pDriv, pCon); + if (iRet == OKOK) { + updateHMData(self->pDriv->data); + return iRet; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "WARNING: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + SCWrite(pCon, "ERROR: failed to fix histogram memory problem", + eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; } - - eCt = self->pDriv->GetCountStatus(self->pDriv,pCon); - if(eCt == HWFault) - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"WARNING: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - SCWrite(pCon,"ERROR: failed to fix histogram memory problem",eError); - SCSetInterrupt(pCon,eAbortBatch); - InvokeCallBack(self->pCall,COUNTEND,NULL); - ReleaseCountLock(self->pCountInt); - return eCt; - } - else - { - updateHMData(self->pDriv->data); - return HWBusy; - } + } + } + SCWrite(pCon, "ERROR: failed to fix histogram memory problem", eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; +} + +/*-------------------------------------------------------------------------*/ +static int HistContinue(void *pData, SConnection * pCon) +{ + pHistMem self = NULL; + char pBueffel[512]; + char pError[80]; + int iErr, iRet, i; + + self = (pHistMem) pData; + assert(self); + + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + return 0; + } + + /* try at least three times to do it */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->Continue(self->pDriv, pCon); + if (iRet == OKOK) { + updateHMData(self->pDriv->data); + return iRet; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "WARNING: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + SCWrite(pCon, "ERROR: failed to fix histogram memory problem", + eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; } - if(eCt == HWBusy) - updateHMData(self->pDriv->data); - - if(eCt == HWIdle) - { - /* force an update of local histogram data with next - GetHistogram - */ - updateHMData(self->pDriv->data); - InvokeCallBack(self->pCall,COUNTEND,NULL); - ReleaseCountLock(self->pCountInt); - } - + } + } + SCWrite(pCon, "ERROR: failed to fix histogram memory problem", eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; +} + +/*-------------------------------------------------------------------------*/ +static int HistCountStatus(void *pData, SConnection * pCon) +{ + pHistMem self = NULL; + int eCt, iRet, iErr; + char pBueffel[512], pError[90]; + + self = (pHistMem) pData; + assert(self); + + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + InvokeCallBack(self->pCall, COUNTEND, NULL); + return COTERM; + } + + eCt = self->pDriv->GetCountStatus(self->pDriv, pCon); + if (eCt == HWFault) { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "WARNING: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + SCWrite(pCon, "ERROR: failed to fix histogram memory problem", + eError); + SCSetInterrupt(pCon, eAbortBatch); + InvokeCallBack(self->pCall, COUNTEND, NULL); + ReleaseCountLock(self->pCountInt); return eCt; - } + } else { + updateHMData(self->pDriv->data); + return HWBusy; + } + } + if (eCt == HWBusy) + updateHMData(self->pDriv->data); + + if (eCt == HWIdle) { + /* force an update of local histogram data with next + GetHistogram + */ + updateHMData(self->pDriv->data); + InvokeCallBack(self->pCall, COUNTEND, NULL); + ReleaseCountLock(self->pCountInt); + } + + return eCt; +} + /*------------------------------------------------------------------------- The question arises if the histograms shall be duplicated on the host computer or not. They need to be in order to be written to file! */ - static int HistTransfer(void *pData, SConnection *pCon) - { - pHistMem self = NULL; - int i, iErr, iRet, iStatus; - char pBueffel[512], pError[80]; - - self = (pHistMem)pData; - assert(self); - - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - return COTERM; +static int HistTransfer(void *pData, SConnection * pCon) +{ + pHistMem self = NULL; + int i, iErr, iRet, iStatus; + char pBueffel[512], pError[80]; + + self = (pHistMem) pData; + assert(self); + + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + return COTERM; + } + + /* try at least three times */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->GetData(self->pDriv, pCon); + if (iRet == OKOK) { + self->pDriv->iUpdate = 0; + iStatus = iRet; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "WARNING: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + SCWrite(pCon, "ERROR: failed to fix histogram memory problem", + eError); + SCSetInterrupt(pCon, eAbortBatch); + iStatus = HWFault; + } } + } + if (iRet == OKOK) { + return iStatus; + } + SCWrite(pCon, "ERROR: failed to fix histogram memory problem", eError); + SCSetInterrupt(pCon, eAbortBatch); + return HWFault; +} - /* try at least three times */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->GetData(self->pDriv, pCon); - if(iRet == OKOK) - { - self->pDriv->iUpdate = 0; - iStatus = iRet; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"WARNING: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - SCWrite(pCon,"ERROR: failed to fix histogram memory problem", eError); - SCSetInterrupt(pCon,eAbortBatch); - iStatus = HWFault; - } - } - } - if(iRet == OKOK) - { - return iStatus; - } - SCWrite(pCon,"ERROR: failed to fix histogram memory problem",eError); - SCSetInterrupt(pCon,eAbortBatch); - return HWFault; - } /*-------------------------------------------------------------------------*/ - pHistMem CreateHistMemory(char *driver) - { - pHistMem pNew = NULL; - pSite site = NULL; - pStringDict pOption; +pHistMem CreateHistMemory(char *driver) +{ + pHistMem pNew = NULL; + pSite site = NULL; + pStringDict pOption; - /* make memory */ - pNew = (pHistMem)malloc(sizeof(HistMem)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(HistMem)); - - /* make object descriptor */ - pNew->pDes = CreateDescriptor("HistMem"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - pNew->pDes->SaveStatus = HistSave; - pNew->pDes->GetInterface = GetHistInterface; - - /* initialise countable interface */ - pNew->pCountInt = CreateCountableInterface(); - if(!pNew->pCountInt) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - } - /* initialise callback interface */ - pNew->pCall = CreateCallBackInterface(); - if(!pNew->pCall) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - } - pNew->pCountInt->SetCountParameters = HistSetParameter; - pNew->pCountInt->StartCount = HistStartCount; - pNew->pCountInt->CheckCountStatus = HistCountStatus; - pNew->pCountInt->TransferData = HistTransfer; - pNew->pCountInt->Halt = HistHalt; - pNew->pCountInt->Pause = HistPause; - pNew->pCountInt->Continue = HistContinue; - - /* initialise options dictionary */ - pOption = CreateStringDict(); - if(!pOption) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - } - StringDictAddPair(pOption,"driver",driver); - StringDictAddPair(pOption,"update","0"); + /* make memory */ + pNew = (pHistMem) malloc(sizeof(HistMem)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(HistMem)); - /* initialise driver */ - if(strcmp(driver,"sim") == 0) - { - pNew->pDriv = CreateSIMHM(pOption); - } - else if(strcmp(driver,"mcstas") == 0) - { - pNew->pDriv = NewMcStasHM(pOption); - } - else if(strcmp(driver,"regress") == 0) - { - pNew->pDriv = CreateRegressHM(pOption); - } + /* make object descriptor */ + pNew->pDes = CreateDescriptor("HistMem"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + pNew->pDes->SaveStatus = HistSave; + pNew->pDes->GetInterface = GetHistInterface; + + /* initialise countable interface */ + pNew->pCountInt = CreateCountableInterface(); + if (!pNew->pCountInt) { + DeleteDescriptor(pNew->pDes); + free(pNew); + return NULL; + } + /* initialise callback interface */ + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pCall) { + DeleteDescriptor(pNew->pDes); + free(pNew); + return NULL; + } + pNew->pCountInt->SetCountParameters = HistSetParameter; + pNew->pCountInt->StartCount = HistStartCount; + pNew->pCountInt->CheckCountStatus = HistCountStatus; + pNew->pCountInt->TransferData = HistTransfer; + pNew->pCountInt->Halt = HistHalt; + pNew->pCountInt->Pause = HistPause; + pNew->pCountInt->Continue = HistContinue; + + /* initialise options dictionary */ + pOption = CreateStringDict(); + if (!pOption) { + DeleteDescriptor(pNew->pDes); + free(pNew); + return NULL; + } + StringDictAddPair(pOption, "driver", driver); + StringDictAddPair(pOption, "update", "0"); + + /* initialise driver */ + if (strcmp(driver, "sim") == 0) { + pNew->pDriv = CreateSIMHM(pOption); + } else if (strcmp(driver, "mcstas") == 0) { + pNew->pDriv = NewMcStasHM(pOption); + } else if (strcmp(driver, "regress") == 0) { + pNew->pDriv = CreateRegressHM(pOption); + } /* else if(strcmp(driver,"slave") == 0) { pNew->pDriv = MakeHMSlaveHM(pOption); } -*/ - else - { - site = getSite(); - if(site != NULL) - { - pNew->pDriv = site->CreateHistogramMemoryDriver(driver, - pOption); - } - } - - if(pNew->pDriv == NULL) - { - DeleteDescriptor(pNew->pDes); - DeleteStringDict(pOption); - free(pNew); - return NULL; - } - pNew->iAccess = usUser; - pNew->iExponent = 0; - pNew->iInit = 0; - pNew->pDriv->pOption = pOption; - - return pNew; - } -/*-----------------------------------------------------------------------*/ - void DeleteHistMemory(void *pData) - { - pHistMem self; - - self = (pHistMem)pData; - assert(self); - - if(self->pDriv) - { - DeleteHistDriver(self->pDriv); - } - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - Fortify_CheckAllMemory(); - - if(self->pCountInt) - { - free(self->pCountInt); - } - if(self->pCall) - { - DeleteCallBackInterface(self->pCall); - } - free(self); +*/ + else { + site = getSite(); + if (site != NULL) { + pNew->pDriv = site->CreateHistogramMemoryDriver(driver, pOption); + } } + + if (pNew->pDriv == NULL) { + DeleteDescriptor(pNew->pDes); + DeleteStringDict(pOption); + free(pNew); + return NULL; + } + pNew->iAccess = usUser; + pNew->iExponent = 0; + pNew->iInit = 0; + pNew->pDriv->pOption = pOption; + + return pNew; +} + +/*-----------------------------------------------------------------------*/ +void DeleteHistMemory(void *pData) +{ + pHistMem self; + + self = (pHistMem) pData; + assert(self); + + if (self->pDriv) { + DeleteHistDriver(self->pDriv); + } + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + Fortify_CheckAllMemory(); + + if (self->pCountInt) { + free(self->pCountInt); + } + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + } + free(self); +} + /*-------------------------------------------------------------------------*/ - int MakeHistMemory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pHistMem pNew = NULL; - char pBueffel[512]; - int iRet; - - /* check no of arguments */ - if(argc < 3) - { - sprintf(pBueffel,"ERROR: insufficient no of arguments to %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* make new HM */ - strtolower(argv[2]); - pNew = CreateHistMemory(argv[2]); - if(!pNew) - { - sprintf(pBueffel,"ERROR: failed to create Histogram Memory %s, driver %s may be invalid or no memory", - argv[1], argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +int MakeHistMemory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHistMem pNew = NULL; + char pBueffel[512]; + int iRet; - StringDictAddPair(pNew->pDriv->pOption,"name",argv[1]); - - /* install HM as command */ - iRet = AddCommand(pSics,argv[1],HistAction,DeleteHistMemory,(void *)pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - DeleteHistMemory((void *)pNew); - return 0; - } - return 1; + /* check no of arguments */ + if (argc < 3) { + sprintf(pBueffel, "ERROR: insufficient no of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; } + + /* make new HM */ + strtolower(argv[2]); + pNew = CreateHistMemory(argv[2]); + if (!pNew) { + sprintf(pBueffel, + "ERROR: failed to create Histogram Memory %s, driver %s may be invalid or no memory", + argv[1], argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + StringDictAddPair(pNew->pDriv->pOption, "name", argv[1]); + + /* install HM as command */ + iRet = + AddCommand(pSics, argv[1], HistAction, DeleteHistMemory, + (void *) pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + DeleteHistMemory((void *) pNew); + return 0; + } + return 1; +} + /*------------------------------------------------------------------------*/ - int HistGetOption(pHistMem self, char *name, char *result, int iLen) - { - assert(self); - strtolower(name); - return StringDictGet(self->pDriv->pOption,name, result,iLen); - } -/*-----------------------------------------------------------------------*/ - int HistSetOption(pHistMem self, char *name, char *value) - { - int status; +int HistGetOption(pHistMem self, char *name, char *result, int iLen) +{ + assert(self); + strtolower(name); + return StringDictGet(self->pDriv->pOption, name, result, iLen); +} - assert(self); - self->iInit = 1; - strtolower(name); - status = StringDictUpdate(self->pDriv->pOption,name, value); - if(status == 0) - { - return StringDictAddPair(self->pDriv->pOption,name, value); - } - return 1; - } /*-----------------------------------------------------------------------*/ - int HistConfigure(pHistMem self, SConnection *pCon, SicsInterp *pSics) - { - int iRet, iVal; - char pValue[80]; - - assert(self); - assert(pCon); - - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot configure histogram memory while counting", eError); - return 0; - } - - iRet = HistDriverConfig(self->pDriv,self->pDriv->pOption,pCon); - if(!iRet) - { - SCWrite(pCon,"ERROR: failed to configure histogram memory",eError); - return 0; - } - iRet = self->pDriv->Configure(self->pDriv,pCon, self->pDriv->pOption,pSics); - if(!iRet) - { - SCWrite(pCon,"ERROR: failed to configure histogram memory",eError); - return 0; - } - return 1; - } -/*--------------------------------------------------------------------------*/ - float GetHistPreset(pHistMem self) - { - int i; - float fVal; - - assert(self); - - fVal = self->pDriv->fCountPreset; - if(self->pDriv->eCount == ePreset) - { - for(i = 0; i < self->iExponent; i++) - { - fVal /= 10.; - } - } - return fVal; - } -/*--------------------------------------------------------------------------*/ - int SetHistPreset(pHistMem self, float fVal) - { - int i; - - assert(self); - - if(fVal < .0) - { - return 0; - } - if(GetHistCountMode(self) == ePreset) - { - for(i = 0; i < self->iExponent;i++) - { - fVal *= 10.; - } - } - self->pDriv->fCountPreset = fVal; - return 1; - } -/*--------------------------------------------------------------------------*/ - int GetHistDim(pHistMem self, int iDim[MAXDIM], int *nDim) - { - - assert(self); +int HistSetOption(pHistMem self, char *name, char *value) +{ + int status; + + assert(self); + self->iInit = 1; + strtolower(name); + status = StringDictUpdate(self->pDriv->pOption, name, value); + if (status == 0) { + return StringDictAddPair(self->pDriv->pOption, name, value); + } + return 1; +} + +/*-----------------------------------------------------------------------*/ +int HistConfigure(pHistMem self, SConnection * pCon, SicsInterp * pSics) +{ + int iRet, iVal; + char pValue[80]; + + assert(self); + assert(pCon); + + if (isRunning(self->pCountInt)) { + SCWrite(pCon, + "ERROR: cannot configure histogram memory while counting", + eError); + return 0; + } + + iRet = HistDriverConfig(self->pDriv, self->pDriv->pOption, pCon); + if (!iRet) { + SCWrite(pCon, "ERROR: failed to configure histogram memory", eError); + return 0; + } + iRet = + self->pDriv->Configure(self->pDriv, pCon, self->pDriv->pOption, + pSics); + if (!iRet) { + SCWrite(pCon, "ERROR: failed to configure histogram memory", eError); + return 0; + } + return 1; +} - getHMDataDim(self->pDriv->data,iDim,nDim); - if(isInTOFMode(self->pDriv->data)) - { - iDim[*nDim] = getNoOfTimebins(self->pDriv->data); - *nDim = *nDim + 1; - } - return 1; - } /*--------------------------------------------------------------------------*/ - long HistSum(pHistMem self, SConnection *pCon, - int iStart[MAXDIM], int iEnd[MAXDIM]) - { - assert(self); - return sumHMDataRectangle(self,pCon,iStart,iEnd); - } +float GetHistPreset(pHistMem self) +{ + int i; + float fVal; + + assert(self); + + fVal = self->pDriv->fCountPreset; + if (self->pDriv->eCount == ePreset) { + for (i = 0; i < self->iExponent; i++) { + fVal /= 10.; + } + } + return fVal; +} + +/*--------------------------------------------------------------------------*/ +int SetHistPreset(pHistMem self, float fVal) +{ + int i; + + assert(self); + + if (fVal < .0) { + return 0; + } + if (GetHistCountMode(self) == ePreset) { + for (i = 0; i < self->iExponent; i++) { + fVal *= 10.; + } + } + self->pDriv->fCountPreset = fVal; + return 1; +} + +/*--------------------------------------------------------------------------*/ +int GetHistDim(pHistMem self, int iDim[MAXDIM], int *nDim) +{ + + assert(self); + + getHMDataDim(self->pDriv->data, iDim, nDim); + if (isInTOFMode(self->pDriv->data)) { + iDim[*nDim] = getNoOfTimebins(self->pDriv->data); + *nDim = *nDim + 1; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +long HistSum(pHistMem self, SConnection * pCon, + int iStart[MAXDIM], int iEnd[MAXDIM]) +{ + assert(self); + return sumHMDataRectangle(self, pCon, iStart, iEnd); +} + /*---------------------------------------------------------------------------*/ - CounterMode GetHistCountMode(pHistMem self) - { - assert(self); - return self->pDriv->eCount; - } -/*--------------------------------------------------------------------------*/ - int SetHistCountMode(pHistMem self, CounterMode eNew) - { - int i; - - assert(self); - if(eNew == self->pDriv->eCount) - { - return 1; - } - - if(eNew == eTimer) - { - for(i = 0; i < self->iExponent; i++) - { - self->pDriv->fCountPreset /= 10.; - } - } - if(eNew == ePreset) - { - for(i = 0; i < self->iExponent; i++) - { - self->pDriv->fCountPreset *= 10.; - } - } - self->pDriv->eCount = eNew; - return 1; +CounterMode GetHistCountMode(pHistMem self) +{ + assert(self); + return self->pDriv->eCount; +} - } /*--------------------------------------------------------------------------*/ - long GetHistMonitor(pHistMem self, int i, SConnection *pCon) - { - assert(self); - return self->pDriv->GetMonitor(self->pDriv,i,pCon); - } +int SetHistCountMode(pHistMem self, CounterMode eNew) +{ + int i; + + assert(self); + if (eNew == self->pDriv->eCount) { + return 1; + } + + if (eNew == eTimer) { + for (i = 0; i < self->iExponent; i++) { + self->pDriv->fCountPreset /= 10.; + } + } + if (eNew == ePreset) { + for (i = 0; i < self->iExponent; i++) { + self->pDriv->fCountPreset *= 10.; + } + } + self->pDriv->eCount = eNew; + return 1; + +} + +/*--------------------------------------------------------------------------*/ +long GetHistMonitor(pHistMem self, int i, SConnection * pCon) +{ + assert(self); + return self->pDriv->GetMonitor(self->pDriv, i, pCon); +} + /*-----------------------------------------------------------------------*/ void HistDirty(pHistMem self) { assert(self); updateHMData(self->pDriv->data); } + /*-------------------------------------------------------------------------*/ - const float *GetHistTimeBin(pHistMem self, int *iLength) - { - assert(self); - *iLength = getNoOfTimebins(self->pDriv->data); - return getTimeBinning(self->pDriv->data); - } +const float *GetHistTimeBin(pHistMem self, int *iLength) +{ + assert(self); + *iLength = getNoOfTimebins(self->pDriv->data); + return getTimeBinning(self->pDriv->data); +} + /*-------------------------------------------------------------------------*/ - int GetHistLength(pHistMem self) - { - assert(self); - - return getHMDataLength(self->pDriv->data); - } +int GetHistLength(pHistMem self) +{ + assert(self); + + return getHMDataLength(self->pDriv->data); +} + /*--------------------------------------------------------------------------*/ - float GetHistCountTime(pHistMem self, SConnection *pCon) - { - assert(self); - return self->pDriv->GetTime(self->pDriv,pCon); - } +float GetHistCountTime(pHistMem self, SConnection * pCon) +{ + assert(self); + return self->pDriv->GetTime(self->pDriv, pCon); +} + /*-------------------------------------------------------------------------*/ - int HistDoCount(pHistMem self, SConnection *pCon) - { - assert(self); +int HistDoCount(pHistMem self, SConnection * pCon) +{ + assert(self); - /* start */ - return StartDevice(GetExecutor(),"HistogramMemory", self->pDes, self, - pCon, self->pDriv->fCountPreset); - } + /* start */ + return StartDevice(GetExecutor(), "HistogramMemory", self->pDes, self, + pCon, self->pDriv->fCountPreset); +} + /*-----------------------------------------------------------------------*/ - int HistBlockCount(pHistMem self, SConnection *pCon) - { - int iRet; - - assert(self); - - /* start counting */ - iRet = StartDevice(GetExecutor(),"HistogramMemory", self->pDes, self, - pCon, self->pDriv->fCountPreset); - if(!iRet) - { - /* error has already been reported */ - return 0; - } - - /* wait till end */ - iRet = Wait4Success(GetExecutor()); - if(iRet == DEVINT) - { - SCWrite(pCon,"Counting aborted due to Interrupt",eError); - } - else if(iRet == DEVERROR) - { - SCWrite(pCon,"Counting finished with Problems",eValue); - iRet = 1; - } - else - { - SCWrite(pCon,"Counting finished",eValue); - iRet = 1; - } +int HistBlockCount(pHistMem self, SConnection * pCon) +{ + int iRet; - - return iRet; + assert(self); + + /* start counting */ + iRet = StartDevice(GetExecutor(), "HistogramMemory", self->pDes, self, + pCon, self->pDriv->fCountPreset); + if (!iRet) { + /* error has already been reported */ + return 0; + } + + /* wait till end */ + iRet = Wait4Success(GetExecutor()); + if (iRet == DEVINT) { + SCWrite(pCon, "Counting aborted due to Interrupt", eError); + } else if (iRet == DEVERROR) { + SCWrite(pCon, "Counting finished with Problems", eValue); + iRet = 1; + } else { + SCWrite(pCon, "Counting finished", eValue); + iRet = 1; + } + + + return iRet; + +} - } /*-------------------------------------------------------------------------*/ - int SetHistogram(pHistMem self, SConnection *pCon, - int i, int iStart, int iEnd, HistInt *lData) - { - int ii, iErr, iRet; - char pBueffel[512], pError[80]; - - assert(self); - - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - return 0; - } +int SetHistogram(pHistMem self, SConnection * pCon, + int i, int iStart, int iEnd, HistInt * lData) +{ + int ii, iErr, iRet; + char pBueffel[512], pError[80]; - /* try at least three times */ - for(ii = 0; ii < 3; ii++) - { - iRet = self->pDriv->SetHistogram(self->pDriv,pCon, - i,iStart,iEnd,lData); - if(iRet == OKOK) - { - updateHMData(self->pDriv->data); - return 1; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"ERROR: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - return 0; - } - } + assert(self); + + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + return 0; + } + + /* try at least three times */ + for (ii = 0; ii < 3; ii++) { + iRet = self->pDriv->SetHistogram(self->pDriv, pCon, + i, iStart, iEnd, lData); + if (iRet == OKOK) { + updateHMData(self->pDriv->data); + return 1; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "ERROR: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + return 0; } - return 0; - } -/*-------------------------------------------------------------------------*/ - int GetHistogram(pHistMem self, SConnection *pCon, - int i, int iStart, int iEnd, HistInt *lData, int iDataLen) - { - assert(self); - - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - return 0; - } - - if( (iEnd -iStart) > iDataLen/sizeof(HistInt)) - { - SCWrite(pCon,"WARNING: truncating request to fit data space",eWarning); - iEnd = (iDataLen/sizeof(HistInt)) - 1; - } - return getHMDataHistogram(self,pCon,i,iStart,iEnd,lData); - } -/*-------------------------------------------------------------------------*/ - int GetHistogramDirect(pHistMem self, SConnection *pCon, - int i, int iStart, int iEnd, HistInt *lData, int iDataLen) - { - int ii, iErr, iRet, iCopy; - char pBueffel[512], pError[80]; - HistInt *lHist = NULL; - - assert(self); - - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - return 0; } + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +int GetHistogram(pHistMem self, SConnection * pCon, + int i, int iStart, int iEnd, HistInt * lData, + int iDataLen) +{ + assert(self); + + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + return 0; + } + + if ((iEnd - iStart) > iDataLen / sizeof(HistInt)) { + SCWrite(pCon, "WARNING: truncating request to fit data space", + eWarning); + iEnd = (iDataLen / sizeof(HistInt)) - 1; + } + return getHMDataHistogram(self, pCon, i, iStart, iEnd, lData); +} + +/*-------------------------------------------------------------------------*/ +int GetHistogramDirect(pHistMem self, SConnection * pCon, + int i, int iStart, int iEnd, HistInt * lData, + int iDataLen) +{ + int ii, iErr, iRet, iCopy; + char pBueffel[512], pError[80]; + HistInt *lHist = NULL; + + assert(self); + + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + return 0; + } - /* try at least three times */ - for(ii = 0; ii < 3; ii++) - { - iRet = self->pDriv->GetHistogram(self->pDriv,pCon, - i,iStart,iEnd, - lData); - if(iRet == OKOK) - { - break; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"ERROR: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - return 0; - } - } + /* try at least three times */ + for (ii = 0; ii < 3; ii++) { + iRet = self->pDriv->GetHistogram(self->pDriv, pCon, + i, iStart, iEnd, lData); + if (iRet == OKOK) { + break; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "ERROR: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + return 0; + } } + } + return 1; +} + +/*-----------------------------------------------------------------------*/ +HistInt *GetHistogramPointer(pHistMem self, SConnection * pCon) +{ + assert(self); + + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + return NULL; + } + + return getHMDataBufferPointer(self, pCon); +} + +/*--------------------------------------------------------------------------*/ +int PresetHistogram(pHistMem self, SConnection * pCon, HistInt lVal) +{ + int ii, iErr, iRet; + char pBueffel[512], pError[80]; + + assert(self); + + if (!self->iInit) { + SCWrite(pCon, "ERROR: histogram memory not initialised", eError); + return 0; + } + + /* try at least three times */ + for (ii = 0; ii < 3; ii++) { + iRet = self->pDriv->Preset(self->pDriv, pCon, lVal); + if (iRet == OKOK) { + updateHMData(self->pDriv->data); + return 1; + } else { + iRet = self->pDriv->GetError(self->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "ERROR: %s ", pError); + SCWrite(pCon, pBueffel, eError); + iRet = self->pDriv->TryAndFixIt(self->pDriv, iErr); + if (iRet == COTERM) { + return 0; + } + } + } + return 0; +} + +/*----------------------------------------------------------------------*/ +static int HMCountInterest(int iEvent, void *pEvent, void *pUser) +{ + SConnection *pCon = NULL; + char pBueffel[512]; + + pCon = (SConnection *) pUser; + + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + if (iEvent == COUNTSTART && pUser != NULL) { + pCon = (SConnection *) pUser; + assert(pCon); + SCWrite(pCon, "HMCOUNTSTART", eWarning); return 1; - } -/*-----------------------------------------------------------------------*/ - HistInt *GetHistogramPointer(pHistMem self, SConnection *pCon) - { - assert(self); + } else if (iEvent == COUNTEND) { + assert(pCon); + SCWrite(pCon, "HMCOUNTEND", eWarning); + return 1; + } + return 0; +} - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - return NULL; - } - - return getHMDataBufferPointer(self,pCon); - } -/*--------------------------------------------------------------------------*/ - int PresetHistogram(pHistMem self, SConnection *pCon, HistInt lVal) - { - int ii, iErr, iRet; - char pBueffel[512], pError[80]; - - assert(self); - - if(!self->iInit) - { - SCWrite(pCon,"ERROR: histogram memory not initialised",eError); - return 0; - } - - /* try at least three times */ - for(ii = 0; ii < 3; ii++) - { - iRet = self->pDriv->Preset(self->pDriv,pCon,lVal); - if(iRet == OKOK) - { - updateHMData(self->pDriv->data); - return 1; - } - else - { - iRet = self->pDriv->GetError(self->pDriv,&iErr,pError,79); - sprintf(pBueffel,"ERROR: %s ",pError); - SCWrite(pCon,pBueffel,eError); - iRet = self->pDriv->TryAndFixIt(self->pDriv,iErr); - if(iRet == COTERM) - { - return 0; - } - } - } - return 0; - } /*----------------------------------------------------------------------*/ - static int HMCountInterest(int iEvent, void *pEvent, void *pUser) - { - SConnection *pCon = NULL; - char pBueffel[512]; - - pCon = (SConnection *)pUser; - - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } - - if(iEvent == COUNTSTART && pUser != NULL) - { - pCon = (SConnection *)pUser; - assert(pCon); - SCWrite(pCon,"HMCOUNTSTART",eWarning); - return 1; - } - else if(iEvent == COUNTEND) - { - assert(pCon); - SCWrite(pCon,"HMCOUNTEND",eWarning); - return 1; - } - return 0; - } -/*----------------------------------------------------------------------*/ -static int checkHMEnd(pHistMem self, char *text){ +static int checkHMEnd(pHistMem self, char *text) +{ int iTest, iEnd; iEnd = getHMDataLength(self->pDriv->data); - if(text == NULL){ + if (text == NULL) { return iEnd; } else { iTest = atoi(text); - if(iTest > iEnd){ + if (iTest > iEnd) { return iEnd; } else { return iTest; } } } -/*--------------------------------------------------------------------------*/ - void HMListOption(pHistMem self, SConnection *pCon) - { - char pBuffer[512]; - char name[20]; - char pValue[128]; - const char *pKey; - int i,iRet,iLen,iRank,iDiscard,tofMode; - float fVal; - char *pMode[] = {"timer","monitor",NULL}; - pDynString buf = NULL; - - memset(pBuffer, 0, sizeof(pBuffer)); - memset(pValue, 0, sizeof(pValue)); - memset(name, 0, sizeof(name)); - - SCStartBuffering(pCon); - iRet = StringDictGet(self->pDriv->pOption,"name",name,19); - if(0==iRet) { - strcpy(name,"*"); - } - iRet = StringDictGet(self->pDriv->pOption,"driver",pValue,sizeof(pValue)-1); - if(0pDriv->pOption,"update",&fVal); - if(0pDriv->pOption,"rank",&fVal); - if(0pDriv->pOption,pValue,&fVal); - if(0pDriv->pOption,pValue,sizeof(pValue)-1); - while(pKey != NULL) { - iDiscard=0; - if(0==strcmp("name",pKey)) iDiscard=1; - if(0==strcmp("driver",pKey)) iDiscard=1; - if(0==strcmp("update",pKey)) iDiscard=1; - if(0==strcmp("rank",pKey)) iDiscard=1; - if(NULL!=strstr(pKey,"dim")) iDiscard=1; - if(0==iDiscard) { - snprintf(pBuffer,511,"%s.%s = %s",name,pKey,pValue); - SCWrite(pCon,pBuffer,eValue); - } - pKey = StringDictGetNext(self->pDriv->pOption,pValue,sizeof(pValue)-1); - } - - /* Display Count Mode */ - sprintf(pBuffer,"%s.CountMode = %s",name,pMode[self->pDriv->eCount]); - SCWrite(pCon,pBuffer,eValue); - - /* Display Preset */ - sprintf(pBuffer,"%s.preset = %f",name,self->pDriv->fCountPreset); - SCWrite(pCon,pBuffer,eValue); - - if(self->pDriv->data->nTimeChan > 2) { - tofMode = 1; - } else { - tofMode = 0; - } - sprintf(pBuffer,"%s.tofMode = %d",name,tofMode); - SCWrite(pCon,pBuffer,eValue); - buf = SCEndBuffering(pCon); - if(buf != NULL){ - SCWrite(pCon,GetCharArray(buf), eValue); +/*--------------------------------------------------------------------------*/ +void HMListOption(pHistMem self, SConnection * pCon) +{ + char pBuffer[512]; + char name[20]; + char pValue[128]; + const char *pKey; + int i, iRet, iLen, iRank, iDiscard, tofMode; + float fVal; + char *pMode[] = { "timer", "monitor", NULL }; + pDynString buf = NULL; + + memset(pBuffer, 0, sizeof(pBuffer)); + memset(pValue, 0, sizeof(pValue)); + memset(name, 0, sizeof(name)); + + SCStartBuffering(pCon); + iRet = StringDictGet(self->pDriv->pOption, "name", name, 19); + if (0 == iRet) { + strcpy(name, "*"); + } + iRet = + StringDictGet(self->pDriv->pOption, "driver", pValue, + sizeof(pValue) - 1); + if (0 < iRet) { + sprintf(pBuffer, "%s.driver = %s", name, pValue); + SCWrite(pCon, pBuffer, eValue); + } + + iRet = StringDictGetAsNumber(self->pDriv->pOption, "update", &fVal); + if (0 < iRet) { + sprintf(pBuffer, "%s.update = %d", name, (int) rint(fVal)); + } else { + sprintf(pBuffer, "%s.update = 0 (no buffering)", name); + } + SCWrite(pCon, pBuffer, eValue); + + iRet = StringDictGetAsNumber(self->pDriv->pOption, "rank", &fVal); + if (0 < iRet) { + iRank = (int) rint(fVal); + sprintf(pBuffer, "%s.rank = %d", name, iRank); + SCWrite(pCon, pBuffer, eValue); + } else { + iRank = 0; + } + for (i = 0; i < iRank; i++) { + sprintf(pValue, "dim%1.1d", i); + iRet = StringDictGetAsNumber(self->pDriv->pOption, pValue, &fVal); + if (0 < iRet) { + sprintf(pBuffer, "%s.dim%1.1d = %d", name, i, (int) rint(fVal)); + SCWrite(pCon, pBuffer, eValue); } } + + pKey = + StringDictGetNext(self->pDriv->pOption, pValue, sizeof(pValue) - 1); + while (pKey != NULL) { + iDiscard = 0; + if (0 == strcmp("name", pKey)) + iDiscard = 1; + if (0 == strcmp("driver", pKey)) + iDiscard = 1; + if (0 == strcmp("update", pKey)) + iDiscard = 1; + if (0 == strcmp("rank", pKey)) + iDiscard = 1; + if (NULL != strstr(pKey, "dim")) + iDiscard = 1; + if (0 == iDiscard) { + snprintf(pBuffer, 511, "%s.%s = %s", name, pKey, pValue); + SCWrite(pCon, pBuffer, eValue); + } + pKey = + StringDictGetNext(self->pDriv->pOption, pValue, + sizeof(pValue) - 1); + } + + /* Display Count Mode */ + sprintf(pBuffer, "%s.CountMode = %s", name, pMode[self->pDriv->eCount]); + SCWrite(pCon, pBuffer, eValue); + + /* Display Preset */ + sprintf(pBuffer, "%s.preset = %f", name, self->pDriv->fCountPreset); + SCWrite(pCon, pBuffer, eValue); + + if (self->pDriv->data->nTimeChan > 2) { + tofMode = 1; + } else { + tofMode = 0; + } + sprintf(pBuffer, "%s.tofMode = %d", name, tofMode); + SCWrite(pCon, pBuffer, eValue); + buf = SCEndBuffering(pCon); + if (buf != NULL) { + SCWrite(pCon, GetCharArray(buf), eValue); + } +} + /*--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/ - int HistAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pHistMem self = NULL; - char pBueffel[512], pNumber[20]; - int iaStart[MAXDIM], iaEnd[MAXDIM]; - Tcl_DString tResult; - int iRet, iVal; - char *pBuf = NULL, *pPtr; - float fVal; - long lVal; - HistInt *lData = NULL; - int iStart, iEnd, iNum, i; - CounterMode eCount; - char *pMode[] = { - "timer", - "monitor", - NULL - }; - double dStart, dStep; - int nDim, iSwitch; - long lID; +int HistAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHistMem self = NULL; + char pBueffel[512], pNumber[20]; + int iaStart[MAXDIM], iaEnd[MAXDIM]; + Tcl_DString tResult; + int iRet, iVal; + char *pBuf = NULL, *pPtr; + float fVal; + long lVal; + HistInt *lData = NULL; + int iStart, iEnd, iNum, i; + CounterMode eCount; + char *pMode[] = { + "timer", + "monitor", + NULL + }; + double dStart, dStep; + int nDim, iSwitch; + long lID; - - assert(pCon); - assert(pSics); - assert(pData); - - self = (pHistMem)pData; - - /* check arguments */ - if(argc < 2) - { - sprintf(pBueffel,"ERROR: no arguments specified to %s", argv[0]); - SCWrite(pCon,pBueffel,eError); + + assert(pCon); + assert(pSics); + assert(pData); + + self = (pHistMem) pData; + + /* check arguments */ + if (argc < 2) { + sprintf(pBueffel, "ERROR: no arguments specified to %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* interest command */ + strtolower(argv[1]); + if (strcmp(argv[1], "interest") == 0) { + lID = RegisterCallback(self->pCall, + COUNTSTART, HMCountInterest, + SCCopyConnection(pCon), SCDeleteConnection); + lID = RegisterCallback(self->pCall, + COUNTEND, HMCountInterest, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "configure") == 0) { + /* enough arguments ? */ + if (argc < 4) { + if (argc < 3) { + sprintf(pBueffel, "ERROR: not enough arguments to %s configure", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } else { /* get value case */ + + strtolower(argv[2]); + iRet = HistGetOption(self, argv[2], NULL, 0); + if (!iRet) { + sprintf(pBueffel, "ERROR: option %s not known", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pBuf = (char *) malloc((iRet + 60) * sizeof(char)); + if (!pBuf) { + SCWrite(pCon, "ERROR: no memory in HistAction", eError); + return 0; + } + memset(pBuf, 0, iRet + 60); + HistGetOption(self, argv[2], pBuf, iRet + 60); + sprintf(pBueffel, "%s.%s = %s", argv[0], argv[2], pBuf); + SCWrite(pCon, pBueffel, eValue); + free(pBuf); + return 1; + } + } + /* do it */ + Arg2Text(argc - 3, &argv[3], pBueffel, 511); + /* authorise */ + if (!SCMatchRights(pCon, usMugger)) { + sprintf(pBueffel, + "ERROR: you need to be manager in order to configure %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + strtolower(argv[2]); + iRet = HistSetOption(self, argv[2], pBueffel); + if (!iRet) { + sprintf(pBueffel, "ERROR: option %s not known", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "preset") == 0) { /* preset */ + if (argc < 3) { /* get value */ + fVal = GetHistPreset(self); + sprintf(pBueffel, "%s.preset = %f", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { /* set case */ + + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot change preset while counting", + eError); return 0; } - - /* interest command */ - strtolower(argv[1]); - if(strcmp(argv[1],"interest") == 0) - { - lID = RegisterCallback(self->pCall, - COUNTSTART, HMCountInterest, - SCCopyConnection(pCon), SCDeleteConnection); - lID = RegisterCallback(self->pCall, - COUNTEND, HMCountInterest, - SCCopyConnection(pCon), SCDeleteConnection); - SCSendOK(pCon); - return 1; + fVal = atof(argv[2]); + if (!SCMatchRights(pCon, self->iAccess)) { + return 0; } - else if(strcmp(argv[1],"configure") == 0) - { - /* enough arguments ? */ - if(argc < 4) - { - if(argc < 3) - { - sprintf(pBueffel,"ERROR: not enough arguments to %s configure", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - else /* get value case */ - { - strtolower(argv[2]); - iRet = HistGetOption(self,argv[2],NULL,0); - if(!iRet) - { - sprintf(pBueffel,"ERROR: option %s not known", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pBuf = (char *)malloc((iRet+60)*sizeof(char)); - if(!pBuf) - { - SCWrite(pCon,"ERROR: no memory in HistAction",eError); - return 0; - } - memset(pBuf,0,iRet+60); - HistGetOption(self,argv[2],pBuf,iRet+60); - sprintf(pBueffel,"%s.%s = %s",argv[0],argv[2],pBuf); - SCWrite(pCon,pBueffel,eValue); - free(pBuf); - return 1; - } - } - /* do it */ - Arg2Text(argc - 3, &argv[3],pBueffel, 511); - /* authorise */ - if(!SCMatchRights(pCon,usMugger)) - { - sprintf(pBueffel, - "ERROR: you need to be manager in order to configure %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - strtolower(argv[2]); - iRet = HistSetOption(self,argv[2],pBueffel); - if(!iRet) - { - sprintf(pBueffel,"ERROR: option %s not known", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"preset") == 0) /* preset */ - { - if(argc < 3) /* get value */ - { - fVal = GetHistPreset(self); - sprintf(pBueffel,"%s.preset = %f",argv[0],fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else /* set case */ - { - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot change preset while counting", eError); - return 0; - } - fVal = atof(argv[2]); - if(!SCMatchRights(pCon,self->iAccess)) - { - return 0; - } - iRet = SetHistPreset(self,fVal); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - } - else if(strcmp(argv[1],"exponent") == 0) /* preset */ - { - if(argc < 3) /* get value */ - { - sprintf(pBueffel,"%s.exponent = %d",argv[0],self->iExponent); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else /* set case */ - { - if(!SCMatchRights(pCon,self->iAccess)) - { - return 0; - } - self->iExponent = atoi(argv[2]); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - } - else if(strcmp(argv[1],"countmode") == 0) /* countmode */ - { - if(argc < 3) /* get value */ - { - eCount = GetHistCountMode(self); - sprintf(pBueffel,"%s.CountMode = %s",argv[0],pMode[eCount]); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else /* set case */ - { - strtolower(argv[2]); - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot change countmode while counting", eError); - return 0; - } - if(!SCMatchRights(pCon,self->iAccess)) - { - return 0; - } - if(strcmp(argv[2],"timer") == 0) - { - eCount = eTimer; - } - else if(strcmp(argv[2],"monitor") == 0) - { - eCount = ePreset; - } - else - { - sprintf(pBueffel,"ERROR: %s invalid as CountMode",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = SetHistCountMode(self,eCount); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - - } - else if(strcmp(argv[1],"init") == 0) - { - if(GetStatus() != eEager) - { - SCWrite(pCon,"ERROR: cannot initialize HM while running", - eError); - return 0; - } - if(SCMatchRights(pCon,usMugger)) - { - iRet = HistConfigure(self,pCon,pSics); - if(iRet) - { - self->iInit = 1; - SCSendOK(pCon); - } - else - { - self->iInit = 0; - } - return iRet; - } - else - { - return 0; - } - } - else if(strcmp(argv[1],"list") == 0) - { - HMListOption(self,pCon); - return 1; - } - /* stop */ - else if(strcmp(argv[1],"stop") == 0) - { if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - self->pDriv->Halt(self->pDriv); - SCSendOK(pCon); - return 1; - } - /* pause */ - else if(strcmp(argv[1],"pause") == 0) - { if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - self->pDriv->Pause(self->pDriv,pCon); - SCSendOK(pCon); - return 1; - } - /* normal counting*/ - else if(strcmp(argv[1],"count") == 0) - { - if(SCMatchRights(pCon,self->iAccess)) - { - if(IsCounting(pServ->pExecutor)) - { - SCWrite(pCon,"WARNING: already counting!",eWarning); - return 1; - } - iRet = HistDoCount(self,pCon); - if(iRet == 1) - { - SCSendOK(pCon); - } - return iRet; - } - else - { - return 0; - } - } - /* forced count, for the case several hm need to be started */ - else if(strcmp(argv[1],"countf") == 0) - { - if(SCMatchRights(pCon,self->iAccess)) - { - iRet = HistDoCount(self,pCon); - if(iRet == 1) - { - SCSendOK(pCon); - } - return iRet; - } - else - { - return 0; - } - } -/* count in blocking mode */ - else if(strcmp(argv[1],"countblock") == 0) - { - if(SCMatchRights(pCon,self->iAccess)) - { - iRet = HistBlockCount(self,pCon); - if(iRet == 1) - { - SCSendOK(pCon); - } - return iRet; - } - else - { - return 0; - } - } - else if(strcmp(argv[1],"initval") == 0) /* initialize to a value */ - { - /* check user rights */ - if(!SCMatchRights(pCon,self->iAccess)) - { - return 0; - } - - /* enough arguments */ - if(argc < 3) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s %s", - argv[0], argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - lVal = atoi(argv[2]); - iRet = PresetHistogram(self,pCon,lVal); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - else if(strcmp(argv[1],"initfile") == 0) /* initialize from a file */ - { - /* check user rights */ - if(!SCMatchRights(pCon,self->iAccess)) - { - return 0; - } - - /* enough arguments */ - if(argc < 3) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s %s", - argv[0], argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = loadHMData(self->pDriv->data,pCon,argv[2]); - self->pDriv->SetHistogram(self->pDriv,pCon,0,0,GetHistLength(self), - self->pDriv->data->localBuffer); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - else if(strcmp(argv[1],"get") == 0) /* get a histogram */ - { - /* check parameters, first required: no of Hist */ - if(argc < 3) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s %s", - argv[0], argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iNum = atoi(argv[2]); + iRet = SetHistPreset(self, fVal); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } + } else if (strcmp(argv[1], "exponent") == 0) { /* preset */ + if (argc < 3) { /* get value */ + sprintf(pBueffel, "%s.exponent = %d", argv[0], self->iExponent); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { /* set case */ - /* optional iStart, default 0 */ - iStart = 0; - if(argc > 3 ) - { - iStart = atoi(argv[3]); - } - - /* check iStart */ - if(iStart < 0) - { - SCWrite(pCon,"WARNING: Invalid start position defaulted to 0",eWarning); - iStart = 0; - } - - if(argc > 4){ - iEnd = checkHMEnd(self,argv[4]); - } else { - iEnd = checkHMEnd(self,NULL); - } - - if(iNum != 0 && argc > 4) - { - iEnd = atoi(argv[4]); - } - - /* allocate data storage and get it */ - lData = (HistInt *)malloc(iEnd*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon,"ERROR: no memory in HistAction/get",eError); - return 0; - } - memset(lData,0,iEnd*sizeof(HistInt)); - if(iNum == 0) - { - iRet = GetHistogram(self,pCon,iNum,iStart,iEnd, - lData,iEnd*sizeof(long)); - } else { - iRet = GetHistogramDirect(self,pCon,iNum,iStart, iEnd, - lData, iEnd*sizeof(long)); - } - if(!iRet) - { - sprintf(pBueffel,"ERROR: cannot retrieve histogram %d",iNum); - SCWrite(pCon,pBueffel,eError); - free(lData); - return 0; - } - - /* OK, got it, convert to text using Tcl's Dstring for lazyness */ - Tcl_DStringInit(&tResult); - Tcl_DStringAppend(&tResult,"Histogram =",-1); - for(i = 0; i < iEnd - iStart; i++) - { - sprintf(pNumber," %d",lData[i]); - Tcl_DStringAppend(&tResult,pNumber,-1); - } - - /* Write it */ - SCWrite(pCon,Tcl_DStringValue(&tResult),eValue); - - /* clean up and go */ - free(lData); - Tcl_DStringFree(&tResult); - return 1; + if (!SCMatchRights(pCon, self->iAccess)) { + return 0; } + self->iExponent = atoi(argv[2]); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } + } else if (strcmp(argv[1], "countmode") == 0) { /* countmode */ + if (argc < 3) { /* get value */ + eCount = GetHistCountMode(self); + sprintf(pBueffel, "%s.CountMode = %s", argv[0], pMode[eCount]); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { /* set case */ + + strtolower(argv[2]); + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot change countmode while counting", + eError); + return 0; + } + if (!SCMatchRights(pCon, self->iAccess)) { + return 0; + } + if (strcmp(argv[2], "timer") == 0) { + eCount = eTimer; + } else if (strcmp(argv[2], "monitor") == 0) { + eCount = ePreset; + } else { + sprintf(pBueffel, "ERROR: %s invalid as CountMode", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = SetHistCountMode(self, eCount); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } + + } else if (strcmp(argv[1], "init") == 0) { + if (GetStatus() != eEager) { + SCWrite(pCon, "ERROR: cannot initialize HM while running", eError); + return 0; + } + if (SCMatchRights(pCon, usMugger)) { + iRet = HistConfigure(self, pCon, pSics); + if (iRet) { + self->iInit = 1; + SCSendOK(pCon); + } else { + self->iInit = 0; + } + return iRet; + } else { + return 0; + } + } else if (strcmp(argv[1], "list") == 0) { + HMListOption(self, pCon); + return 1; + } + /* stop */ + else if (strcmp(argv[1], "stop") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + self->pDriv->Halt(self->pDriv); + SCSendOK(pCon); + return 1; + } + /* pause */ + else if (strcmp(argv[1], "pause") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + self->pDriv->Pause(self->pDriv, pCon); + SCSendOK(pCon); + return 1; + } + /* normal counting */ + else if (strcmp(argv[1], "count") == 0) { + if (SCMatchRights(pCon, self->iAccess)) { + if (IsCounting(pServ->pExecutor)) { + SCWrite(pCon, "WARNING: already counting!", eWarning); + return 1; + } + iRet = HistDoCount(self, pCon); + if (iRet == 1) { + SCSendOK(pCon); + } + return iRet; + } else { + return 0; + } + } + /* forced count, for the case several hm need to be started */ + else if (strcmp(argv[1], "countf") == 0) { + if (SCMatchRights(pCon, self->iAccess)) { + iRet = HistDoCount(self, pCon); + if (iRet == 1) { + SCSendOK(pCon); + } + return iRet; + } else { + return 0; + } + } +/* count in blocking mode */ + else if (strcmp(argv[1], "countblock") == 0) { + if (SCMatchRights(pCon, self->iAccess)) { + iRet = HistBlockCount(self, pCon); + if (iRet == 1) { + SCSendOK(pCon); + } + return iRet; + } else { + return 0; + } + } else if (strcmp(argv[1], "initval") == 0) { /* initialize to a value */ + /* check user rights */ + if (!SCMatchRights(pCon, self->iAccess)) { + return 0; + } + + /* enough arguments */ + if (argc < 3) { + sprintf(pBueffel, "ERROR: insufficient number of arguments to %s %s", + argv[0], argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + lVal = atoi(argv[2]); + iRet = PresetHistogram(self, pCon, lVal); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } else if (strcmp(argv[1], "initfile") == 0) { /* initialize from a file */ + /* check user rights */ + if (!SCMatchRights(pCon, self->iAccess)) { + return 0; + } + + /* enough arguments */ + if (argc < 3) { + sprintf(pBueffel, "ERROR: insufficient number of arguments to %s %s", + argv[0], argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = loadHMData(self->pDriv->data, pCon, argv[2]); + self->pDriv->SetHistogram(self->pDriv, pCon, 0, 0, GetHistLength(self), + self->pDriv->data->localBuffer); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } else if (strcmp(argv[1], "get") == 0) { /* get a histogram */ + /* check parameters, first required: no of Hist */ + if (argc < 3) { + sprintf(pBueffel, "ERROR: insufficient number of arguments to %s %s", + argv[0], argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iNum = atoi(argv[2]); + + /* optional iStart, default 0 */ + iStart = 0; + if (argc > 3) { + iStart = atoi(argv[3]); + } + + /* check iStart */ + if (iStart < 0) { + SCWrite(pCon, "WARNING: Invalid start position defaulted to 0", + eWarning); + iStart = 0; + } + + if (argc > 4) { + iEnd = checkHMEnd(self, argv[4]); + } else { + iEnd = checkHMEnd(self, NULL); + } + + if (iNum != 0 && argc > 4) { + iEnd = atoi(argv[4]); + } + + /* allocate data storage and get it */ + lData = (HistInt *) malloc(iEnd * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, "ERROR: no memory in HistAction/get", eError); + return 0; + } + memset(lData, 0, iEnd * sizeof(HistInt)); + if (iNum == 0) { + iRet = GetHistogram(self, pCon, iNum, iStart, iEnd, + lData, iEnd * sizeof(long)); + } else { + iRet = GetHistogramDirect(self, pCon, iNum, iStart, iEnd, + lData, iEnd * sizeof(long)); + } + if (!iRet) { + sprintf(pBueffel, "ERROR: cannot retrieve histogram %d", iNum); + SCWrite(pCon, pBueffel, eError); + free(lData); + return 0; + } + + /* OK, got it, convert to text using Tcl's Dstring for lazyness */ + Tcl_DStringInit(&tResult); + Tcl_DStringAppend(&tResult, "Histogram =", -1); + for (i = 0; i < iEnd - iStart; i++) { + sprintf(pNumber, " %d", lData[i]); + Tcl_DStringAppend(&tResult, pNumber, -1); + } + + /* Write it */ + SCWrite(pCon, Tcl_DStringValue(&tResult), eValue); + + /* clean up and go */ + free(lData); + Tcl_DStringFree(&tResult); + return 1; + } /*-------- get uuencoded */ - else if(strcmp(argv[1],"uuget") == 0) /* get a histogram */ - { - /* check parameters, first required: no of Hist */ - if(argc < 3) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s %s", - argv[0], argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iNum = atoi(argv[2]); + else if (strcmp(argv[1], "uuget") == 0) { /* get a histogram */ + /* check parameters, first required: no of Hist */ + if (argc < 3) { + sprintf(pBueffel, "ERROR: insufficient number of arguments to %s %s", + argv[0], argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iNum = atoi(argv[2]); - /* optional iStart, default 0 */ - iStart = 0; - if(argc > 3 ) - { - iStart = atoi(argv[3]); - } - - /* check iStart */ - if(iStart < 0) - { - SCWrite(pCon,"WARNING: Invalid start position defaulted to 0",eWarning); - iStart = 0; - } + /* optional iStart, default 0 */ + iStart = 0; + if (argc > 3) { + iStart = atoi(argv[3]); + } - if(argc > 4){ - iEnd = checkHMEnd(self,argv[4]); - } else { - iEnd = checkHMEnd(self,NULL); - } + /* check iStart */ + if (iStart < 0) { + SCWrite(pCon, "WARNING: Invalid start position defaulted to 0", + eWarning); + iStart = 0; + } - /* allocate data storage and get it */ - lData = (HistInt *)malloc((iEnd+1)*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon,"ERROR: no memory in HistAction/get",eError); - return 0; - } - memset(lData,0,(iEnd+1)*sizeof(HistInt)); - iRet = GetHistogram(self,pCon,iNum,iStart,iEnd, - &lData[1],iEnd*sizeof(HistInt)); - if(!iRet) - { - sprintf(pBueffel,"ERROR: cannot retrieve histogram %d",iNum); - SCWrite(pCon,pBueffel,eError); - free(lData); - return 0; - } - /* lData[0] is the length of the histogram */ - lData[0] = iEnd; - - /* convert to network byte order */ - for(i = 0; i < iEnd+1; i++) - { - lData[i] = htonl(lData[i]); - } - /* Write it */ - SCWriteUUencoded(pCon,"SicsHistogram",lData,(iEnd+1)*sizeof(HistInt)); - - /* clean up and go */ - free(lData); - return 1; - } - else if(strcmp(argv[1],"zipget") == 0) /* get a histogram */ - { - /* check parameters, first required: no of Hist */ - if(argc < 3) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s %s", - argv[0], argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iNum = atoi(argv[2]); + if (argc > 4) { + iEnd = checkHMEnd(self, argv[4]); + } else { + iEnd = checkHMEnd(self, NULL); + } - /* optional iStart, default 0 */ - iStart = 0; - if(argc > 3 ) - { - iStart = atoi(argv[3]); - } - - /* check iStart */ - if(iStart < 0) - { - SCWrite(pCon,"WARNING: Invalid start position defaulted to 0", - eWarning); - iStart = 0; - } - - if(argc > 4){ - iEnd = checkHMEnd(self,argv[4]); - } else { - iEnd = checkHMEnd(self,NULL); - } + /* allocate data storage and get it */ + lData = (HistInt *) malloc((iEnd + 1) * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, "ERROR: no memory in HistAction/get", eError); + return 0; + } + memset(lData, 0, (iEnd + 1) * sizeof(HistInt)); + iRet = GetHistogram(self, pCon, iNum, iStart, iEnd, + &lData[1], iEnd * sizeof(HistInt)); + if (!iRet) { + sprintf(pBueffel, "ERROR: cannot retrieve histogram %d", iNum); + SCWrite(pCon, pBueffel, eError); + free(lData); + return 0; + } + /* lData[0] is the length of the histogram */ + lData[0] = iEnd; - /* allocate data storage and get it */ - lData = (HistInt *)malloc((iEnd+1)*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon,"ERROR: no memory in HistAction/get",eError); - return 0; - } - memset(lData,0,(iEnd+1)*sizeof(HistInt)); - iRet = GetHistogram(self,pCon,iNum,iStart,iEnd, - &lData[0],iEnd*sizeof(HistInt)); - if(!iRet) - { - sprintf(pBueffel,"ERROR: cannot retrieve histogram %d",iNum); - SCWrite(pCon,pBueffel,eError); - free(lData); - return 0; - } - - /* convert to network byte order */ - for(i = 0; i < iEnd; i++) - { - lData[i] = htonl(lData[i]); - } - /* Write it */ - SCWriteZipped(pCon,argv[0],lData,iEnd*sizeof(HistInt)); - - /* clean up and go */ - free(lData); - return 1; - } - /* retrive no of Timebins */ - else if(strcmp(argv[1],"notimebin") == 0) - { - sprintf(pBueffel, - "%s.notimebin = %d",argv[0], - getNoOfTimebins(self->pDriv->data)); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - /* retrive time binning */ - else if(strcmp(argv[1],"timebin") == 0) - { - Tcl_DStringInit(&tResult); - Tcl_DStringAppend(&tResult,"histogram.timebins =",-1); - for(i = 0; i < self->pDriv->data->nTimeChan; i++) - { - sprintf(pBueffel,"%.2f ", self->pDriv->data->timeBinning[i]); - Tcl_DStringAppend(&tResult,pBueffel,-1); - } - /* Write it */ - SCWrite(pCon,Tcl_DStringValue(&tResult),eValue); - - /* clean up and go */ - Tcl_DStringFree(&tResult); - return 1; - } - /* generate time binning */ - else if(strcmp(argv[1],"genbin") == 0) - { - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot change time binning while counting", eError); - return 0; - } - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - if(argc < 5) - { - SCWrite(pCon,"ERROR: not enough aguments to genbin",eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dStart); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: Failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[3],&dStep); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: Failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[4],&iNum); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: Failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(iNum >= MAXCHAN) - { - SCWrite(pCon, - "ERROR: number of requested time bins exceeds maximum permissible number", - eError); - return 0; - } - if(iNum <= 0){ - SCWrite(pCon,"ERROR: at least one time bin required!",eError); - return 0; - } - /* do it */ - genTimeBinning(self->pDriv->data, - (float)dStart,(float)dStep,iNum); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } - /* set a time bin */ - else if(strcmp(argv[1],"setbin") == 0) - { - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot change time binning while counting", eError); - return 0; - } - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - if(argc < 4) - { - SCWrite(pCon,"ERROR: not enough aguments to setbin",eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iNum); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: Failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[3],&dStep); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: Failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if( (iNum < 0) || (iNum > MAXCHAN) ) - { - SCWrite(pCon,"ERROR: requested time bin out or permissible range", - eError); - return 0; - } - setTimeBin(self->pDriv->data,iNum, (float)dStep); - self->iInit = 0; - SCSendOK(pCon); - return 1; - } - /* clear time bin info */ - else if(strcmp(argv[1],"clearbin") == 0) - { - if(isRunning(self->pCountInt)){ - SCWrite(pCon,"ERROR: cannot change time binning while counting", eError); - return 0; - } - clearTimeBinning(self->pDriv->data); - SCSendOK(pCon); - return 1; - } + /* convert to network byte order */ + for (i = 0; i < iEnd + 1; i++) { + lData[i] = htonl(lData[i]); + } + /* Write it */ + SCWriteUUencoded(pCon, "SicsHistogram", lData, + (iEnd + 1) * sizeof(HistInt)); + + /* clean up and go */ + free(lData); + return 1; + } else if (strcmp(argv[1], "zipget") == 0) { /* get a histogram */ + /* check parameters, first required: no of Hist */ + if (argc < 3) { + sprintf(pBueffel, "ERROR: insufficient number of arguments to %s %s", + argv[0], argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iNum = atoi(argv[2]); + + /* optional iStart, default 0 */ + iStart = 0; + if (argc > 3) { + iStart = atoi(argv[3]); + } + + /* check iStart */ + if (iStart < 0) { + SCWrite(pCon, "WARNING: Invalid start position defaulted to 0", + eWarning); + iStart = 0; + } + + if (argc > 4) { + iEnd = checkHMEnd(self, argv[4]); + } else { + iEnd = checkHMEnd(self, NULL); + } + + /* allocate data storage and get it */ + lData = (HistInt *) malloc((iEnd + 1) * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, "ERROR: no memory in HistAction/get", eError); + return 0; + } + memset(lData, 0, (iEnd + 1) * sizeof(HistInt)); + iRet = GetHistogram(self, pCon, iNum, iStart, iEnd, + &lData[0], iEnd * sizeof(HistInt)); + if (!iRet) { + sprintf(pBueffel, "ERROR: cannot retrieve histogram %d", iNum); + SCWrite(pCon, pBueffel, eError); + free(lData); + return 0; + } + + /* convert to network byte order */ + for (i = 0; i < iEnd; i++) { + lData[i] = htonl(lData[i]); + } + /* Write it */ + SCWriteZipped(pCon, argv[0], lData, iEnd * sizeof(HistInt)); + + /* clean up and go */ + free(lData); + return 1; + } + /* retrive no of Timebins */ + else if (strcmp(argv[1], "notimebin") == 0) { + sprintf(pBueffel, + "%s.notimebin = %d", argv[0], + getNoOfTimebins(self->pDriv->data)); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + /* retrive time binning */ + else if (strcmp(argv[1], "timebin") == 0) { + Tcl_DStringInit(&tResult); + Tcl_DStringAppend(&tResult, "histogram.timebins =", -1); + for (i = 0; i < self->pDriv->data->nTimeChan; i++) { + sprintf(pBueffel, "%.2f ", self->pDriv->data->timeBinning[i]); + Tcl_DStringAppend(&tResult, pBueffel, -1); + } + /* Write it */ + SCWrite(pCon, Tcl_DStringValue(&tResult), eValue); + + /* clean up and go */ + Tcl_DStringFree(&tResult); + return 1; + } + /* generate time binning */ + else if (strcmp(argv[1], "genbin") == 0) { + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot change time binning while counting", + eError); + return 0; + } + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + if (argc < 5) { + SCWrite(pCon, "ERROR: not enough aguments to genbin", eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dStart); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: Failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[3], &dStep); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: Failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[4], &iNum); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: Failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (iNum >= MAXCHAN) { + SCWrite(pCon, + "ERROR: number of requested time bins exceeds maximum permissible number", + eError); + return 0; + } + if (iNum <= 0) { + SCWrite(pCon, "ERROR: at least one time bin required!", eError); + return 0; + } + /* do it */ + genTimeBinning(self->pDriv->data, (float) dStart, (float) dStep, iNum); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } + /* set a time bin */ + else if (strcmp(argv[1], "setbin") == 0) { + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot change time binning while counting", + eError); + return 0; + } + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough aguments to setbin", eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iNum); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: Failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[3], &dStep); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: Failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if ((iNum < 0) || (iNum > MAXCHAN)) { + SCWrite(pCon, "ERROR: requested time bin out or permissible range", + eError); + return 0; + } + setTimeBin(self->pDriv->data, iNum, (float) dStep); + self->iInit = 0; + SCSendOK(pCon); + return 1; + } + /* clear time bin info */ + else if (strcmp(argv[1], "clearbin") == 0) { + if (isRunning(self->pCountInt)) { + SCWrite(pCon, "ERROR: cannot change time binning while counting", + eError); + return 0; + } + clearTimeBinning(self->pDriv->data); + SCSendOK(pCon); + return 1; + } /*-------- sum */ - else if(strcmp(argv[1],"sum") == 0) - { - /* read following arguments as ints and put them - into the iStart and iEnd array in succession. - But first check if we have an even number. - */ - if( ((argc-2) % 2) || (argc-2) == 0) - { - SCWrite(pCon, - "ERROR: need start and end for each dimension", - eError); - return 0; - } - nDim = 0; - iSwitch = 0; - for(i = 0; i < argc -2; i++) - { - iRet = Tcl_GetInt(pSics->pTcl,argv[i+2],&iVal); - if(iSwitch) - { - iaEnd[nDim] = iVal; - nDim++; - iSwitch = 0; - } - else - { - iSwitch = 1; - iaStart[nDim] = iVal; - } - } - lVal = HistSum(self,pCon,iaStart,iaEnd); - sprintf(pBueffel,"%s.sum = %ld",argv[0],lVal); - SCWrite(pCon,pBueffel,eValue); - return 1; + else if (strcmp(argv[1], "sum") == 0) { + /* read following arguments as ints and put them + into the iStart and iEnd array in succession. + But first check if we have an even number. + */ + if (((argc - 2) % 2) || (argc - 2) == 0) { + SCWrite(pCon, + "ERROR: need start and end for each dimension", eError); + return 0; + } + nDim = 0; + iSwitch = 0; + for (i = 0; i < argc - 2; i++) { + iRet = Tcl_GetInt(pSics->pTcl, argv[i + 2], &iVal); + if (iSwitch) { + iaEnd[nDim] = iVal; + nDim++; + iSwitch = 0; + } else { + iSwitch = 1; + iaStart[nDim] = iVal; } - else - { - sprintf(pBueffel,"ERROR: %s does not understand command %s", - argv[0], argv[1]); - SCWrite(pCon, pBueffel,eError); - return 0; - } - } - - - - - - - + } + lVal = HistSum(self, pCon, iaStart, iaEnd); + sprintf(pBueffel, "%s.sum = %ld", argv[0], lVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + sprintf(pBueffel, "ERROR: %s does not understand command %s", + argv[0], argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } +} diff --git a/histregress.c b/histregress.c index 8003e27f..2c01221c 100644 --- a/histregress.c +++ b/histregress.c @@ -28,246 +28,250 @@ static int iSet = 0; static HistInt iSetVal = 0; static HistMode eHistMode; /*--------------------------------------------------------------------------*/ -static int RegressConfig(pHistDriver self, SConnection *pCon, - pStringDict pOption, SicsInterp *pSics) +static int RegressConfig(pHistDriver self, SConnection * pCon, + pStringDict pOption, SicsInterp * pSics) { - int i, iLength = 1, status; - char pData[132]; - float fFail; - pCounterDriver count; + int i, iLength = 1, status; + char pData[132]; + float fFail; + pCounterDriver count; - count = (pCounterDriver)self->pPriv; - - if(eHistMode == eHTOF) - { - for(i = 0; i < self->data->rank; i++) - { - iLength *= self->data->iDim[i]; - } - iLength *= self->data->nTimeChan; + count = (pCounterDriver) self->pPriv; + + if (eHistMode == eHTOF) { + for (i = 0; i < self->data->rank; i++) { + iLength *= self->data->iDim[i]; } + iLength *= self->data->nTimeChan; + } - /* - deal with error settings - */ - status = StringDictGet(pOption,"errortype",pData,131); - if(status) - { - - fFail = atof(pData); - count->Set(count,"errortype",1,fFail); - } - status = StringDictGet(pOption,"recover",pData,131); - if(status) - { - - fFail = atof(pData); - count->Set(count,"recover",1,fFail); - } - status = StringDictGet(pOption,"finish",pData,131); - if(status) - { - - fFail = atof(pData); - count->Set(count,"finish",1,fFail); - } - - /* - configured test value - */ - status = StringDictGet(pOption,"testval",pData,131); - if(status) - { - iSet = 1; - iSetVal = atoi(pData); - } + /* + deal with error settings + */ + status = StringDictGet(pOption, "errortype", pData, 131); + if (status) { + + fFail = atof(pData); + count->Set(count, "errortype", 1, fFail); + } + status = StringDictGet(pOption, "recover", pData, 131); + if (status) { + + fFail = atof(pData); + count->Set(count, "recover", 1, fFail); + } + status = StringDictGet(pOption, "finish", pData, 131); + if (status) { + + fFail = atof(pData); + count->Set(count, "finish", 1, fFail); + } + + /* + configured test value + */ + status = StringDictGet(pOption, "testval", pData, 131); + if (status) { + iSet = 1; + iSetVal = atoi(pData); + } + + return 1; +} - return 1; - } /*-------------------------------------------------------------------------*/ - static int RegressStart(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - pDriv->fPreset = self->fCountPreset; - pDriv->eMode = self->eCount; - return pDriv->Start(pDriv); - } +static int RegressStart(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + pDriv->fPreset = self->fCountPreset; + pDriv->eMode = self->eCount; + return pDriv->Start(pDriv); +} + /*-------------------------------------------------------------------------*/ - static int RegressPause(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - pDriv->fPreset = self->fCountPreset; - pDriv->eMode = self->eCount; - return pDriv->Pause(pDriv); - } +static int RegressPause(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + pDriv->fPreset = self->fCountPreset; + pDriv->eMode = self->eCount; + return pDriv->Pause(pDriv); +} + /*------------------------------------------------------------------------*/ - static int RegressContinue(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - pDriv->fPreset = self->fCountPreset; - pDriv->eMode = self->eCount; - return pDriv->Continue(pDriv); - } +static int RegressContinue(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + pDriv->fPreset = self->fCountPreset; + pDriv->eMode = self->eCount; + return pDriv->Continue(pDriv); +} + /*-------------------------------------------------------------------------*/ - static int RegressHalt(pHistDriver self) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->Halt(pDriv); - } +static int RegressHalt(pHistDriver self) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->Halt(pDriv); +} + /*-------------------------------------------------------------------------*/ - static int RegressGetCountStatus(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - float fControl; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->GetStatus(pDriv,&fControl); - } +static int RegressGetCountStatus(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + float fControl; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->GetStatus(pDriv, &fControl); +} + /*-------------------------------------------------------------------------*/ - static int RegressGetError(pHistDriver self, int *iCode, char *pError, int iLen) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->GetError(pDriv, iCode,pError,iLen); - } +static int RegressGetError(pHistDriver self, int *iCode, char *pError, + int iLen) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->GetError(pDriv, iCode, pError, iLen); +} + /*-------------------------------------------------------------------------*/ - static int RegressTryAndFixIt(pHistDriver self, int iCode) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->TryAndFixIt(pDriv, iCode); - } +static int RegressTryAndFixIt(pHistDriver self, int iCode) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->TryAndFixIt(pDriv, iCode); +} + /*--------------------------------------------------------------------------*/ - static int RegressGetData(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; +static int RegressGetData(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + + return pDriv->ReadValues(pDriv); +} - return pDriv->ReadValues(pDriv); - } /*--------------------------------------------------------------------------*/ - static int RegressGetHistogram(pHistDriver self, SConnection *pCon, - int i, int iStart, int iEnd, HistInt *lData) - { - int ii; - - if(i < 0) - { - SCWrite(pCon,"ERROR: histogram out of range",eError); - return 0; - } +static int RegressGetHistogram(pHistDriver self, SConnection * pCon, + int i, int iStart, int iEnd, + HistInt * lData) +{ + int ii; - if(iSet == 1) - { - for(ii = iStart; ii < iEnd; ii++) - { - lData[ii-iStart] = iSetVal; - } - } - else - { - for(ii = iStart; ii < iEnd; ii++) - { - lData[ii-iStart] = random(); - } - } - return 1; - } -/*------------------------------------------------------------------------*/ - static int RegressSetHistogram(pHistDriver self, SConnection *pCon, - int i, int iStart, int iEnd, HistInt *lData) - { - iSet = 1; - iSetVal = lData[0]; - return 1; - } + if (i < 0) { + SCWrite(pCon, "ERROR: histogram out of range", eError); + return 0; + } -/*-------------------------------------------------------------------------*/ - static int RegressPreset(pHistDriver self, SConnection *pCon, HistInt iVal) - { - iSet = 1; - iSetVal = iVal; - return 1; - } -/*------------------------------------------------------------------------*/ - static int RegressFreePrivate(pHistDriver self) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - DeleteCounterDriver(pDriv); - return 1; - } -/*------------------------------------------------------------------------*/ - static long RegressGetMonitor(pHistDriver self, int i, SConnection *pCon) - { - pCounterDriver pDriv; - long lVal; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->lCounts[i]; - - } -/*------------------------------------------------------------------------*/ - static float RegressGetTime(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - long lVal; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->fTime; - - } -/*-------------------------------------------------------------------------*/ - pHistDriver CreateRegressHM(pStringDict pOpt) - { - pHistDriver pNew = NULL; - - /* create the general driver */ - pNew = CreateHistDriver(pOpt); - if(!pNew) - { - return NULL; - } - - /* put a Regresscounter in */ - pNew->pPriv = (void *)NewRegressCounter("HistoRegress"); - if(!pNew->pPriv) - { - DeleteHistDriver(pNew); - return NULL; + if (iSet == 1) { + for (ii = iStart; ii < iEnd; ii++) { + lData[ii - iStart] = iSetVal; } - - /* configure all those functions */ - pNew->Configure = RegressConfig; - pNew->Start = RegressStart; - pNew->Halt = RegressHalt; - pNew->GetCountStatus = RegressGetCountStatus; - pNew->GetError = RegressGetError; - pNew->TryAndFixIt = RegressTryAndFixIt; - pNew->GetData = RegressGetData; - pNew->GetHistogram = RegressGetHistogram; - pNew->SetHistogram = RegressSetHistogram; - pNew->GetMonitor = RegressGetMonitor; - pNew->GetTime = RegressGetTime; - pNew->Preset = RegressPreset; - pNew->FreePrivate = RegressFreePrivate; - pNew->Pause = RegressPause; - pNew->Continue = RegressContinue; - StringDictAddPair(pOpt,"errortype","0"); - StringDictAddPair(pOpt,"recover","1"); - StringDictAddPair(pOpt,"testval","0"); - - return pNew; - } + } else { + for (ii = iStart; ii < iEnd; ii++) { + lData[ii - iStart] = random(); + } + } + return 1; +} + +/*------------------------------------------------------------------------*/ +static int RegressSetHistogram(pHistDriver self, SConnection * pCon, + int i, int iStart, int iEnd, + HistInt * lData) +{ + iSet = 1; + iSetVal = lData[0]; + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int RegressPreset(pHistDriver self, SConnection * pCon, + HistInt iVal) +{ + iSet = 1; + iSetVal = iVal; + return 1; +} + +/*------------------------------------------------------------------------*/ +static int RegressFreePrivate(pHistDriver self) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + DeleteCounterDriver(pDriv); + return 1; +} + +/*------------------------------------------------------------------------*/ +static long RegressGetMonitor(pHistDriver self, int i, SConnection * pCon) +{ + pCounterDriver pDriv; + long lVal; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->lCounts[i]; + +} + +/*------------------------------------------------------------------------*/ +static float RegressGetTime(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + long lVal; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->fTime; + +} + +/*-------------------------------------------------------------------------*/ +pHistDriver CreateRegressHM(pStringDict pOpt) +{ + pHistDriver pNew = NULL; + + /* create the general driver */ + pNew = CreateHistDriver(pOpt); + if (!pNew) { + return NULL; + } + + /* put a Regresscounter in */ + pNew->pPriv = (void *) NewRegressCounter("HistoRegress"); + if (!pNew->pPriv) { + DeleteHistDriver(pNew); + return NULL; + } + + /* configure all those functions */ + pNew->Configure = RegressConfig; + pNew->Start = RegressStart; + pNew->Halt = RegressHalt; + pNew->GetCountStatus = RegressGetCountStatus; + pNew->GetError = RegressGetError; + pNew->TryAndFixIt = RegressTryAndFixIt; + pNew->GetData = RegressGetData; + pNew->GetHistogram = RegressGetHistogram; + pNew->SetHistogram = RegressSetHistogram; + pNew->GetMonitor = RegressGetMonitor; + pNew->GetTime = RegressGetTime; + pNew->Preset = RegressPreset; + pNew->FreePrivate = RegressFreePrivate; + pNew->Pause = RegressPause; + pNew->Continue = RegressContinue; + StringDictAddPair(pOpt, "errortype", "0"); + StringDictAddPair(pOpt, "recover", "1"); + StringDictAddPair(pOpt, "testval", "0"); + + return pNew; +} diff --git a/histsim.c b/histsim.c index 98eab3df..1813b584 100644 --- a/histsim.c +++ b/histsim.c @@ -49,261 +49,263 @@ #include "HistDriv.i" #include "histsim.h" - static int iSet = 0; - static HistInt iSetVal = 0; - static HistMode eHistMode; +static int iSet = 0; +static HistInt iSetVal = 0; +static HistMode eHistMode; /*--------------------------------------------------------------------------*/ - static int SimConfig(pHistDriver self, SConnection *pCon, - pStringDict pOption, SicsInterp *pSics) - { - int i, iLength = 1, status; - char pData[132]; - float fFail; +static int SimConfig(pHistDriver self, SConnection * pCon, + pStringDict pOption, SicsInterp * pSics) +{ + int i, iLength = 1, status; + char pData[132]; + float fFail; - if(eHistMode == eHTOF) - { - for(i = 0; i < self->data->rank; i++) - { - iLength *= self->data->iDim[i]; - } - iLength *= self->data->nTimeChan; + if (eHistMode == eHTOF) { + for (i = 0; i < self->data->rank; i++) { + iLength *= self->data->iDim[i]; } + iLength *= self->data->nTimeChan; + } - /* - deal with failrate - */ - status = StringDictGet(pOption,"failrate",pData,131); - if(status) - { - fFail = atof(pData); - free(self->pPriv); - self->pPriv = NewSIMCounter("HistoSim",fFail); - } - - /* - configured test value - */ - status = StringDictGet(pOption,"testval",pData,131); - if(status) - { - iSet = 1; - iSetVal = atoi(pData); - } + /* + deal with failrate + */ + status = StringDictGet(pOption, "failrate", pData, 131); + if (status) { + fFail = atof(pData); + free(self->pPriv); + self->pPriv = NewSIMCounter("HistoSim", fFail); + } - return 1; - } -/*-------------------------------------------------------------------------*/ - static int SimStart(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - pDriv->fPreset = self->fCountPreset; - pDriv->eMode = self->eCount; - return pDriv->Start(pDriv); - } -/*-------------------------------------------------------------------------*/ - static int SimPause(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - pDriv->fPreset = self->fCountPreset; - pDriv->eMode = self->eCount; - return pDriv->Pause(pDriv); - } -/*------------------------------------------------------------------------*/ - static int SimContinue(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - pDriv->fPreset = self->fCountPreset; - pDriv->eMode = self->eCount; - return pDriv->Continue(pDriv); - } -/*-------------------------------------------------------------------------*/ - static int SimHalt(pHistDriver self) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->Halt(pDriv); - } -/*-------------------------------------------------------------------------*/ - static int SimGetCountStatus(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - float fControl; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->GetStatus(pDriv,&fControl); - } -/*-------------------------------------------------------------------------*/ - static int SimGetError(pHistDriver self, int *iCode, char *pError, int iLen) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->GetError(pDriv, iCode,pError,iLen); - } -/*-------------------------------------------------------------------------*/ - static int SimTryAndFixIt(pHistDriver self, int iCode) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->TryAndFixIt(pDriv, iCode); - } -/*--------------------------------------------------------------------------*/ - static int SimGetData(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; + /* + configured test value + */ + status = StringDictGet(pOption, "testval", pData, 131); + if (status) { + iSet = 1; + iSetVal = atoi(pData); + } - return pDriv->ReadValues(pDriv); - } -/*--------------------------------------------------------------------------*/ - static int SimGetHistogram(pHistDriver self, SConnection *pCon, - int i, int iStart, int iEnd, HistInt *lData) - { - int ii; - - if(i < 0) - { - SCWrite(pCon,"ERROR: histogram out of range",eError); - return 0; - } - - if(iSet == 1) - { - for(ii = iStart; ii < iEnd; ii++) - { - lData[ii-iStart] = iSetVal; - } - } - else if(iSet == 2) - { - for(ii = iStart; ii < iEnd; ii++) - { - lData[ii-iStart] = self->data->localBuffer[ii]; - } - } - else - { - for(ii = iStart; ii < iEnd; ii++) - { - lData[ii-iStart] = random(); - } - } - return 1; - } -/*------------------------------------------------------------------------*/ - static int SimSetHistogram(pHistDriver self, SConnection *pCon, - int i, int iStart, int iEnd, HistInt *lData) - { - iSet = 2; - if(self->data->localBuffer == NULL){ - resizeBuffer(self->data); - } - iSetVal = lData[0]; - if(iEnd <= getHMDataLength(self->data)){ - memcpy(self->data->localBuffer+iStart,lData,(iEnd - iStart)*sizeof(HistInt)); - } - return 1; - } - -/*-------------------------------------------------------------------------*/ - static int SimPreset(pHistDriver self, SConnection *pCon, HistInt iVal) - { - iSet = 1; - iSetVal = iVal; - return 1; - } -/*------------------------------------------------------------------------*/ - static int SimFreePrivate(pHistDriver self) - { - pCounterDriver pDriv; - - pDriv = (pCounterDriver)self->pPriv; - DeleteCounterDriver(pDriv); - return 1; - } -/*------------------------------------------------------------------------*/ - static long SimGetMonitor(pHistDriver self, int i, SConnection *pCon) - { - pCounterDriver pDriv; - long lVal; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->lCounts[i]; - - } -/*------------------------------------------------------------------------*/ - static float SimGetTime(pHistDriver self, SConnection *pCon) - { - pCounterDriver pDriv; - long lVal; - - pDriv = (pCounterDriver)self->pPriv; - return pDriv->fTime; - - } -/*-------------------------------------------------------------------------*/ -HistInt *DefaultSubSample(pHistDriver self, SConnection *pCon, - int bank, char *command){ - HistInt *data = NULL; - char error[132]; - - assert(bank == 0); /* no bank handling yet.. */ - - memset(error,0,132*sizeof(char)); - data = subSample(self->data, command, error, 132); - if(data == NULL){ - SCWrite(pCon,error,eError); - } - return data; + return 1; } + /*-------------------------------------------------------------------------*/ - pHistDriver CreateSIMHM(pStringDict pOpt) - { - pHistDriver pNew = NULL; - - /* create the general driver */ - pNew = CreateHistDriver(pOpt); - if(!pNew) - { - return NULL; - } - - /* put a SIMcounter in */ - pNew->pPriv = (void *)NewSIMCounter("HistoSim",-1.); - if(!pNew->pPriv) - { - DeleteHistDriver(pNew); - return NULL; +static int SimStart(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + pDriv->fPreset = self->fCountPreset; + pDriv->eMode = self->eCount; + return pDriv->Start(pDriv); +} + +/*-------------------------------------------------------------------------*/ +static int SimPause(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + pDriv->fPreset = self->fCountPreset; + pDriv->eMode = self->eCount; + return pDriv->Pause(pDriv); +} + +/*------------------------------------------------------------------------*/ +static int SimContinue(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + pDriv->fPreset = self->fCountPreset; + pDriv->eMode = self->eCount; + return pDriv->Continue(pDriv); +} + +/*-------------------------------------------------------------------------*/ +static int SimHalt(pHistDriver self) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->Halt(pDriv); +} + +/*-------------------------------------------------------------------------*/ +static int SimGetCountStatus(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + float fControl; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->GetStatus(pDriv, &fControl); +} + +/*-------------------------------------------------------------------------*/ +static int SimGetError(pHistDriver self, int *iCode, char *pError, + int iLen) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->GetError(pDriv, iCode, pError, iLen); +} + +/*-------------------------------------------------------------------------*/ +static int SimTryAndFixIt(pHistDriver self, int iCode) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->TryAndFixIt(pDriv, iCode); +} + +/*--------------------------------------------------------------------------*/ +static int SimGetData(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + + return pDriv->ReadValues(pDriv); +} + +/*--------------------------------------------------------------------------*/ +static int SimGetHistogram(pHistDriver self, SConnection * pCon, + int i, int iStart, int iEnd, HistInt * lData) +{ + int ii; + + if (i < 0) { + SCWrite(pCon, "ERROR: histogram out of range", eError); + return 0; + } + + if (iSet == 1) { + for (ii = iStart; ii < iEnd; ii++) { + lData[ii - iStart] = iSetVal; } - - /* configure all those functions */ - pNew->Configure = SimConfig; - pNew->Start = SimStart; - pNew->Halt = SimHalt; - pNew->GetCountStatus = SimGetCountStatus; - pNew->GetError = SimGetError; - pNew->TryAndFixIt = SimTryAndFixIt; - pNew->GetData = SimGetData; - pNew->GetHistogram = SimGetHistogram; - pNew->SetHistogram = SimSetHistogram; - pNew->GetMonitor = SimGetMonitor; - pNew->GetTime = SimGetTime; - pNew->Preset = SimPreset; - pNew->FreePrivate = SimFreePrivate; - pNew->Pause = SimPause; - pNew->Continue = SimContinue; - pNew->SubSample = DefaultSubSample; - StringDictAddPair(pOpt,"failrate","-1"); - - return pNew; - } - + } else if (iSet == 2) { + for (ii = iStart; ii < iEnd; ii++) { + lData[ii - iStart] = self->data->localBuffer[ii]; + } + } else { + for (ii = iStart; ii < iEnd; ii++) { + lData[ii - iStart] = random(); + } + } + return 1; +} + +/*------------------------------------------------------------------------*/ +static int SimSetHistogram(pHistDriver self, SConnection * pCon, + int i, int iStart, int iEnd, HistInt * lData) +{ + iSet = 2; + if (self->data->localBuffer == NULL) { + resizeBuffer(self->data); + } + iSetVal = lData[0]; + if (iEnd <= getHMDataLength(self->data)) { + memcpy(self->data->localBuffer + iStart, lData, + (iEnd - iStart) * sizeof(HistInt)); + } + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int SimPreset(pHistDriver self, SConnection * pCon, HistInt iVal) +{ + iSet = 1; + iSetVal = iVal; + return 1; +} + +/*------------------------------------------------------------------------*/ +static int SimFreePrivate(pHistDriver self) +{ + pCounterDriver pDriv; + + pDriv = (pCounterDriver) self->pPriv; + DeleteCounterDriver(pDriv); + return 1; +} + +/*------------------------------------------------------------------------*/ +static long SimGetMonitor(pHistDriver self, int i, SConnection * pCon) +{ + pCounterDriver pDriv; + long lVal; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->lCounts[i]; + +} + +/*------------------------------------------------------------------------*/ +static float SimGetTime(pHistDriver self, SConnection * pCon) +{ + pCounterDriver pDriv; + long lVal; + + pDriv = (pCounterDriver) self->pPriv; + return pDriv->fTime; + +} + +/*-------------------------------------------------------------------------*/ +HistInt *DefaultSubSample(pHistDriver self, SConnection * pCon, + int bank, char *command) +{ + HistInt *data = NULL; + char error[132]; + + assert(bank == 0); /* no bank handling yet.. */ + + memset(error, 0, 132 * sizeof(char)); + data = subSample(self->data, command, error, 132); + if (data == NULL) { + SCWrite(pCon, error, eError); + } + return data; +} + +/*-------------------------------------------------------------------------*/ +pHistDriver CreateSIMHM(pStringDict pOpt) +{ + pHistDriver pNew = NULL; + + /* create the general driver */ + pNew = CreateHistDriver(pOpt); + if (!pNew) { + return NULL; + } + + /* put a SIMcounter in */ + pNew->pPriv = (void *) NewSIMCounter("HistoSim", -1.); + if (!pNew->pPriv) { + DeleteHistDriver(pNew); + return NULL; + } + + /* configure all those functions */ + pNew->Configure = SimConfig; + pNew->Start = SimStart; + pNew->Halt = SimHalt; + pNew->GetCountStatus = SimGetCountStatus; + pNew->GetError = SimGetError; + pNew->TryAndFixIt = SimTryAndFixIt; + pNew->GetData = SimGetData; + pNew->GetHistogram = SimGetHistogram; + pNew->SetHistogram = SimSetHistogram; + pNew->GetMonitor = SimGetMonitor; + pNew->GetTime = SimGetTime; + pNew->Preset = SimPreset; + pNew->FreePrivate = SimFreePrivate; + pNew->Pause = SimPause; + pNew->Continue = SimContinue; + pNew->SubSample = DefaultSubSample; + StringDictAddPair(pOpt, "failrate", "-1"); + + return pNew; +} diff --git a/histsim.h b/histsim.h index e347c969..6c289bad 100644 --- a/histsim.h +++ b/histsim.h @@ -15,7 +15,7 @@ #line 5 "histsim.w" - pHistDriver CreateSIMHM(pStringDict pOpt); +pHistDriver CreateSIMHM(pStringDict pOpt); #line 27 "histsim.w" diff --git a/hkl.c b/hkl.c index 5f2e32b5..594e4ead 100644 --- a/hkl.c +++ b/hkl.c @@ -47,270 +47,267 @@ the tolerance in chi we give before we allow to fix omega with phi */ #define CHITOLERANCE 3. -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*-------------------------------------------------------------------------*/ - static int HKLSave(void *pData, char *name, FILE *fd) - { - pHKL self = NULL; +static int HKLSave(void *pData, char *name, FILE * fd) +{ + pHKL self = NULL; - self = (pHKL)pData; - if( (self == NULL) || (fd == NULL) ) - { - return 1; - } - fprintf(fd,"#HKL Settings\n"); - fprintf(fd,"%s scantolerance %f\n", name,self->scanTolerance); - return 1; - } - -/*---------------------------------------------------------------------------*/ - pHKL CreateHKL() - { - pHKL pNew = NULL; - - /* allocate memory */ - pNew = (pHKL)malloc(sizeof(HKL)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(HKL)); - - /* create object descriptor */ - pNew->pDes = CreateDescriptor("4-Circle-Calculus"); - pNew->pMotDriv = makeMotListInterface(); - if(!pNew->pDes || pNew->pMotDriv == NULL) - { - free(pNew); - return NULL; - } - pNew->pDes->SaveStatus = HKLSave; - - pNew->iQuad = 1; - pNew->iHM = 0; - pNew->UBinv = NULL; - pNew->scanTolerance = 2.5; - - return pNew; + self = (pHKL) pData; + if ((self == NULL) || (fd == NULL)) { + return 1; } -/*--------------------------------------------------------------------------*/ - void DeleteHKL(void *pData) - { - pHKL self = NULL; - - self = (pHKL)pData; - if(!self) - { - return; - } - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->pMotDriv) - { - free(self->pMotDriv); - } - - free(self); - } + fprintf(fd, "#HKL Settings\n"); + fprintf(fd, "%s scantolerance %f\n", name, self->scanTolerance); + return 1; +} + /*---------------------------------------------------------------------------*/ - int HKLFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pHKL self = NULL; - int iRet; - - /* make a new structure */ - self = CreateHKL(); - if(!self) - { - SCWrite(pCon,"ERROR: cannot allocate HKL data structure",eError); - return 0; - } - - /* install a command */ - iRet = AddCommand(pSics, - "HKL", - HKLAction, - DeleteHKL, - self); - if(!iRet) - { - SCWrite(pCon,"ERROR: duplicate command HKL not created",eError); - DeleteHKL(self); - return 0; - } - return 1; - } +pHKL CreateHKL() +{ + pHKL pNew = NULL; + + /* allocate memory */ + pNew = (pHKL) malloc(sizeof(HKL)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(HKL)); + + /* create object descriptor */ + pNew->pDes = CreateDescriptor("4-Circle-Calculus"); + pNew->pMotDriv = makeMotListInterface(); + if (!pNew->pDes || pNew->pMotDriv == NULL) { + free(pNew); + return NULL; + } + pNew->pDes->SaveStatus = HKLSave; + + pNew->iQuad = 1; + pNew->iHM = 0; + pNew->UBinv = NULL; + pNew->scanTolerance = 2.5; + + return pNew; +} + +/*--------------------------------------------------------------------------*/ +void DeleteHKL(void *pData) +{ + pHKL self = NULL; + + self = (pHKL) pData; + if (!self) { + return; + } + + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->pMotDriv) { + free(self->pMotDriv); + } + + free(self); +} + +/*---------------------------------------------------------------------------*/ +int HKLFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHKL self = NULL; + int iRet; + + /* make a new structure */ + self = CreateHKL(); + if (!self) { + SCWrite(pCon, "ERROR: cannot allocate HKL data structure", eError); + return 0; + } + + /* install a command */ + iRet = AddCommand(pSics, "HKL", HKLAction, DeleteHKL, self); + if (!iRet) { + SCWrite(pCon, "ERROR: duplicate command HKL not created", eError); + DeleteHKL(self); + return 0; + } + return 1; +} + /*-------------------------------------------------------------------------*/ void SetHKLScanTolerance(pHKL self, float fVal) { assert(self); self->scanTolerance = fVal; } -/*------------------------------------------------------------------------*/ - int GetLambda(pHKL self, float *fVal) - { - assert(self); - double val; - - val = SXGetLambda(); - *fVal = (float)val; - return 1; - } -/*-------------------------------------------------------------------------*/ - int GetCurrentHKL(pHKL self, float fHKL[3]) - { - int i; - - assert(self); - - for(i = 0; i < 3; i++) - { - fHKL[i] = self->fLastHKL[i]; - } - return 1; - } -/*-------------------------------------------------------------------------*/ -static void invertMatrix(pHKL self, float fUB[9]){ - int i; - MATRIX m; - - if(self->UBinv != NULL) - { - mat_free(self->UBinv); - } - m = mat_creat(3,3,ZERO_MATRIX); - for(i = 0; i < 3; i++) - { - m[0][i] = fUB[i]; - m[1][i] = fUB[3+i]; - m[2][i] = fUB[6+i]; - } - self->UBinv = mat_inv(m); - mat_free(m); -} -/*-------------------------------------------------------------------------*/ - int SetUB(pHKL self, float fUB[9]) - { - int i; - double dUB[9]; - - assert(self); - - for(i = 0; i < 9; i++){ - dUB[i] = fUB[i]; - } - SXSetUB(dUB); - invertMatrix(self,fUB); - - return 1; - } -/*-------------------------------------------------------------------------*/ - int GetUB(pHKL self, float fUB[9]) - { - int i; - const double *dUB; - - dUB = SXGetUB(); - for(i = 0; i < 9; i++) - { - fUB[i] = (float)dUB[i]; - } - return 1; - } - -/*--------------------------------------------------------------------------*/ - int SetNOR(pHKL self, int iNOB) - { - assert(self); - - /* cannot set normal beam geometry if no nu motor */ - if( (iNOB == 1) && (SXGetMotor(Nu) == NULL)) - return 0; - switch(iNOB){ - case 0: - SXSetMode(Bisecting); - break; - case 1: - SXSetMode(NB); - break; - default: - return 0; - } - return 1; - } - /*-----------------------------------------------------------------------*/ - static int checkTheta(pHKL self, double *stt){ - char pError[132]; - int iTest; - float fHard; - pMotor pTheta; - - pTheta = SXGetMotor(TwoTheta); - if(pTheta == NULL){ - return 0; - } - - iTest = MotorCheckBoundary(pTheta,(float)*stt, &fHard,pError,131); - if(!iTest){ - return -1; - } - return iTest; +/*------------------------------------------------------------------------*/ +int GetLambda(pHKL self, float *fVal) +{ + assert(self); + double val; + + val = SXGetLambda(); + *fVal = (float) val; + return 1; +} + +/*-------------------------------------------------------------------------*/ +int GetCurrentHKL(pHKL self, float fHKL[3]) +{ + int i; + + assert(self); + + for (i = 0; i < 3; i++) { + fHKL[i] = self->fLastHKL[i]; } + return 1; +} + +/*-------------------------------------------------------------------------*/ +static void invertMatrix(pHKL self, float fUB[9]) +{ + int i; + MATRIX m; + + if (self->UBinv != NULL) { + mat_free(self->UBinv); + } + m = mat_creat(3, 3, ZERO_MATRIX); + for (i = 0; i < 3; i++) { + m[0][i] = fUB[i]; + m[1][i] = fUB[3 + i]; + m[2][i] = fUB[6 + i]; + } + self->UBinv = mat_inv(m); + mat_free(m); +} + +/*-------------------------------------------------------------------------*/ +int SetUB(pHKL self, float fUB[9]) +{ + int i; + double dUB[9]; + + assert(self); + + for (i = 0; i < 9; i++) { + dUB[i] = fUB[i]; + } + SXSetUB(dUB); + invertMatrix(self, fUB); + + return 1; +} + +/*-------------------------------------------------------------------------*/ +int GetUB(pHKL self, float fUB[9]) +{ + int i; + const double *dUB; + + dUB = SXGetUB(); + for (i = 0; i < 9; i++) { + fUB[i] = (float) dUB[i]; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int SetNOR(pHKL self, int iNOB) +{ + assert(self); + + /* cannot set normal beam geometry if no nu motor */ + if ((iNOB == 1) && (SXGetMotor(Nu) == NULL)) + return 0; + + switch (iNOB) { + case 0: + SXSetMode(Bisecting); + break; + case 1: + SXSetMode(NB); + break; + default: + return 0; + } + return 1; +} + + /*-----------------------------------------------------------------------*/ +static int checkTheta(pHKL self, double *stt) +{ + char pError[132]; + int iTest; + float fHard; + pMotor pTheta; + + pTheta = SXGetMotor(TwoTheta); + if (pTheta == NULL) { + return 0; + } + + iTest = MotorCheckBoundary(pTheta, (float) *stt, &fHard, pError, 131); + if (!iTest) { + return -1; + } + return iTest; +} + /*----------------------------------------------------------------------*/ int hklInRange(void *data, double fSet[4], int mask[4]) { - pHKL self = (pHKL)data; - float fHard, fLimit; - char pError[132]; - int i, test; - double dTheta; - pMotor pOmega, pChi, pPhi; - - pOmega = SXGetMotor(Omega); - pChi = SXGetMotor(Chi); - pPhi = SXGetMotor(Phi); - if(pOmega == NULL || pChi == NULL || pPhi == NULL){ - return 0; - } - - /* check two theta */ - dTheta = fSet[0]; - mask[0] = checkTheta(self, &dTheta); - fSet[0] = dTheta; + pHKL self = (pHKL) data; + float fHard, fLimit; + char pError[132]; + int i, test; + double dTheta; + pMotor pOmega, pChi, pPhi; - /* for omega check against the limits +- SCANBORDER in order to allow for - a omega scan. + pOmega = SXGetMotor(Omega); + pChi = SXGetMotor(Chi); + pPhi = SXGetMotor(Phi); + if (pOmega == NULL || pChi == NULL || pPhi == NULL) { + return 0; + } + + /* check two theta */ + dTheta = fSet[0]; + mask[0] = checkTheta(self, &dTheta); + fSet[0] = dTheta; + + /* for omega check against the limits +- SCANBORDER in order to allow for + a omega scan. */ - MotorGetPar(pOmega,"softlowerlim",&fLimit); - if((float)fSet[1] < fLimit + self->scanTolerance){ - mask[1] = 1; - } else { - mask[1] = 0; - MotorGetPar(pOmega,"softupperlim",&fLimit); - if((float)fSet[1] > fLimit - self->scanTolerance){ - mask[1] = 0; - } else { - mask[1] = 1; - } - } + MotorGetPar(pOmega, "softlowerlim", &fLimit); + if ((float) fSet[1] < fLimit + self->scanTolerance) { + mask[1] = 1; + } else { + mask[1] = 0; + MotorGetPar(pOmega, "softupperlim", &fLimit); + if ((float) fSet[1] > fLimit - self->scanTolerance) { + mask[1] = 0; + } else { + mask[1] = 1; + } + } - /* check chi and phi*/ - mask[2] = MotorCheckBoundary(pChi,fSet[2], &fHard,pError,131); - mask[3] = MotorCheckBoundary(pPhi,fSet[3], &fHard,pError,131); - for(i = 0, test = 0; i < 4; i++){ - test += mask[i]; - } - if(test != 4) { - return 0; - } else { - return 1; - } + /* check chi and phi */ + mask[2] = MotorCheckBoundary(pChi, fSet[2], &fHard, pError, 131); + mask[3] = MotorCheckBoundary(pPhi, fSet[3], &fHard, pError, 131); + for (i = 0, test = 0; i < 4; i++) { + test += mask[i]; + } + if (test != 4) { + return 0; + } else { + return 1; + } } + /*------------------------------------------------------------------------- calculates the four circle settings. If the position can not be reached because of a limit violation, then psi is rotated in 10 degree steps @@ -319,353 +316,334 @@ int hklInRange(void *data, double fSet[4], int mask[4]) into the right range. This is a fix because the omega movement is quite often restricted due to the cryogenic garbage around the sample. */ - int CalculateSettings(pHKL self, float fHKL[3], float fPsi, int iHamil, - float fSet[4], SConnection *pCon) - { - char pBueffel[512]; - double myPsi = fPsi; - int i,status; - pSingleDiff single = NULL; - double dHkl[4], dSet[4]; - - /* catch shitty input */ - if( (fHKL[0] == 0.) && (fHKL[1] == 0.) && (fHKL[2] == 0.)) - { - SCWrite(pCon,"ERROR: I will not calculate angles for HKL = (0,0,0) ", - eError); - return 0; - } - - /* some people are stupid.......... */ - myPsi = circlify(fPsi); +int CalculateSettings(pHKL self, float fHKL[3], float fPsi, int iHamil, + float fSet[4], SConnection * pCon) +{ + char pBueffel[512]; + double myPsi = fPsi; + int i, status; + pSingleDiff single = NULL; + double dHkl[4], dSet[4]; + + /* catch shitty input */ + if ((fHKL[0] == 0.) && (fHKL[1] == 0.) && (fHKL[2] == 0.)) { + SCWrite(pCon, "ERROR: I will not calculate angles for HKL = (0,0,0) ", + eError); + return 0; + } + + /* some people are stupid.......... */ + myPsi = circlify(fPsi); + + single = SXGetDiffractometer(); + assert(single != NULL); + + for (i = 0; i < 3; i++) { + dHkl[i] = fHKL[i]; + } + dHkl[3] = myPsi; + + status = single->calculateSettings(single, dHkl, dSet); + for (i = 0; i < 4; i++) { + fSet[i] = dSet[i]; + } + + if (!status) { + sprintf(pBueffel, + "ERROR: cannot calculate %4.1f %4.1f %4.1f, psi = %4.1f", + fHKL[0], fHKL[1], fHKL[2], dHkl[3]); + SCWrite(pCon, pBueffel, eError); + } + return status; +} - single = SXGetDiffractometer(); - assert(single != NULL); - - for(i = 0; i < 3; i++){ - dHkl[i] = fHKL[i]; - } - dHkl[3] = myPsi; - - status = single->calculateSettings(single,dHkl, dSet); - for(i = 0; i < 4; i++){ - fSet[i] = dSet[i]; - } - - if(!status){ - sprintf(pBueffel, - "ERROR: cannot calculate %4.1f %4.1f %4.1f, psi = %4.1f", - fHKL[0], fHKL[1], fHKL[2], dHkl[3]); - SCWrite(pCon,pBueffel,eError); - } - return status; - } /*------------------------------------------------------------------------*/ void stopHKLMotors(pHKL self) { - pSingleDiff single = NULL; + pSingleDiff single = NULL; - single = SXGetDiffractometer(); - assert(single != NULL); - self->pMotDriv->Halt(&single->motList); + single = SXGetDiffractometer(); + assert(single != NULL); + self->pMotDriv->Halt(&single->motList); } + /*------------------------------------------------------------------------*/ -int startHKLMotors(pHKL self, SConnection *pCon, float fSet[4]){ - char pBueffel[512]; - pSingleDiff single = NULL; - double dSet[4]; - int i, status; - - single = SXGetDiffractometer(); - assert(single != NULL); - - for(i = 0; i < 4; i++){ - dSet[i] = fSet[i]; - } - single->settingsToList(single,dSet); - - status = self->pMotDriv->SetValue(&single->motList,pCon,.1); - - return status; +int startHKLMotors(pHKL self, SConnection * pCon, float fSet[4]) +{ + char pBueffel[512]; + pSingleDiff single = NULL; + double dSet[4]; + int i, status; + + single = SXGetDiffractometer(); + assert(single != NULL); + + for (i = 0; i < 4; i++) { + dSet[i] = fSet[i]; + } + single->settingsToList(single, dSet); + + status = self->pMotDriv->SetValue(&single->motList, pCon, .1); + + return status; } + /*-------------------------------------------------------------------------*/ - int RunHKL(pHKL self, float fHKL[3], - float fPsi, int iHamil, SConnection *pCon) - { - float fSet[4]; - int iRet,i; - char pBueffel[512]; - pDummy pDum; +int RunHKL(pHKL self, float fHKL[3], + float fPsi, int iHamil, SConnection * pCon) +{ + float fSet[4]; + int iRet, i; + char pBueffel[512]; + pDummy pDum; - assert(self); - iRet = CalculateSettings(self,fHKL,fPsi,iHamil,fSet,pCon); - if(!iRet) - { - SCWrite(pCon,"ERROR: NOT started",eError); - return 0; - } + assert(self); + iRet = CalculateSettings(self, fHKL, fPsi, iHamil, fSet, pCon); + if (!iRet) { + SCWrite(pCon, "ERROR: NOT started", eError); + return 0; + } - iRet = startHKLMotors(self,pCon,fSet); - if(iRet != 1){ - return iRet; - } + iRet = startHKLMotors(self, pCon, fSet); + if (iRet != 1) { + return iRet; + } + + for (i = 0; i < 3; i++) { + self->fLastHKL[i] = fHKL[i]; + } + return 1; + +} - for(i = 0; i < 3; i++) - { - self->fLastHKL[i] = fHKL[i]; - } - return 1; - - } /*-------------------------------------------------------------------------*/ - int DriveSettings(pHKL self, float fSet[4], SConnection *pCon) - { - int iRet; - - iRet = startHKLMotors(self, pCon, fSet); - if(iRet != 1){ - stopHKLMotors(self); - } +int DriveSettings(pHKL self, float fSet[4], SConnection * pCon) +{ + int iRet; + + iRet = startHKLMotors(self, pCon, fSet); + if (iRet != 1) { + stopHKLMotors(self); + } + + /* wait for end */ + iRet = Wait4Success(pServ->pExecutor); + switch (iRet) { + case DEVINT: + if (SCGetInterrupt(pCon) == eAbortOperation) { + SCSetInterrupt(pCon, eContinue); + SCWrite(pCon, "Driving to HKL Aborted", eLogError); + } + return 0; + break; + case DEVDONE: + SCWrite(pCon, "Driving to Reflection done", eValue); + break; + default: + SCWrite(pCon, "WARNING: driving to HKL finished with problems", + eWarning); + if (SCGetInterrupt(pCon) != eContinue) { + return 0; + } + break; + } + return iRet; +} - /* wait for end */ - iRet = Wait4Success(pServ->pExecutor); - switch(iRet) - { - case DEVINT: - if(SCGetInterrupt(pCon) == eAbortOperation) - { - SCSetInterrupt(pCon,eContinue); - SCWrite(pCon,"Driving to HKL Aborted",eLogError); - } - return 0; - break; - case DEVDONE: - SCWrite(pCon,"Driving to Reflection done",eValue); - break; - default: - SCWrite(pCon,"WARNING: driving to HKL finished with problems", - eWarning); - if(SCGetInterrupt(pCon) != eContinue) - { - return 0; - } - break; - } - return iRet; - } /*--------------------------------------------------------------------------*/ - int DriveHKL(pHKL self, float fHKL[3], - float fPsi, int iHamil, SConnection *pCon) - { - int iRet, iReturn; - long lID; - char pBueffel[132]; - - assert(self); - - /* start running */ - iReturn = 1; - iRet = RunHKL(self,fHKL,fPsi,iHamil,pCon); - if(!iRet){ - StopExe(pServ->pExecutor,"all"); - iReturn = 0; - } +int DriveHKL(pHKL self, float fHKL[3], + float fPsi, int iHamil, SConnection * pCon) +{ + int iRet, iReturn; + long lID; + char pBueffel[132]; + + assert(self); + + /* start running */ + iReturn = 1; + iRet = RunHKL(self, fHKL, fPsi, iHamil, pCon); + if (!iRet) { + StopExe(pServ->pExecutor, "all"); + iReturn = 0; + } + + /* wait for end */ + iRet = Wait4Success(pServ->pExecutor); + switch (iRet) { + case DEVINT: + if (SCGetInterrupt(pCon) == eAbortOperation) { + SCSetInterrupt(pCon, eContinue); + SCWrite(pCon, "Driving to HKL Aborted", eError); + } + return 0; + break; + case DEVDONE: + if (fPsi > .01) { + snprintf(pBueffel, 131, + "Driving to %8.4f %8.4f %8.4f, psi = %8.4f done", + fHKL[0], fHKL[1], fHKL[2], fPsi); + } else { + snprintf(pBueffel, 131, "Driving to %8.4f %8.4f %8.4f done", + fHKL[0], fHKL[1], fHKL[2]); + } + SCWrite(pCon, pBueffel, eValue); + break; + default: + SCWrite(pCon, "WARNING: driving to HKL finished with problems", + eWarning); + if (SCGetInterrupt(pCon) != eContinue) { + return 0; + } + break; + } + return iReturn; +} - /* wait for end */ - iRet = Wait4Success(pServ->pExecutor); - switch(iRet) - { - case DEVINT: - if(SCGetInterrupt(pCon) == eAbortOperation) - { - SCSetInterrupt(pCon,eContinue); - SCWrite(pCon,"Driving to HKL Aborted",eError); - } - return 0; - break; - case DEVDONE: - if(fPsi > .01) - { - snprintf(pBueffel,131, - "Driving to %8.4f %8.4f %8.4f, psi = %8.4f done", - fHKL[0], fHKL[1], fHKL[2],fPsi); - } - else - { - snprintf(pBueffel,131,"Driving to %8.4f %8.4f %8.4f done", - fHKL[0], fHKL[1], fHKL[2]); - } - SCWrite(pCon,pBueffel,eValue); - break; - default: - SCWrite(pCon,"WARNING: driving to HKL finished with problems", - eWarning); - if(SCGetInterrupt(pCon) != eContinue) - { - return 0; - } - break; - } - return iReturn; - } /*----------------------------------------------------------------------- * This is only used in mesure, remove when mesure can be killed * ----------------------------------------------------------------------*/ - int GetCurrentPosition(pHKL self, SConnection *pCon, float fPos[4]) - { - float fVal; - int iRet, iResult; - pMotor pTheta, pOmega, pChi, pPhi, pNu; - - pTheta = SXGetMotor(TwoTheta); - pOmega = SXGetMotor(Omega); - pChi = SXGetMotor(Chi); - pPhi = SXGetMotor(Phi); - if(pTheta == NULL || pOmega == NULL || pChi == NULL || pPhi == NULL){ - SCWrite(pCon,"ERROR: configuration problem, stt,om,chi,phi motors not found,", - eError); - return 0; - } +int GetCurrentPosition(pHKL self, SConnection * pCon, float fPos[4]) +{ + float fVal; + int iRet, iResult; + pMotor pTheta, pOmega, pChi, pPhi, pNu; - assert(self); - assert(pCon); - - iResult = 1; - iRet = MotorGetSoftPosition(pTheta,pCon, &fVal); - if(iRet == 1) - { - fPos[0] = fVal; - } - else - { - iResult = 0; - } - iRet = MotorGetSoftPosition(pOmega,pCon, &fVal); - if(iRet == 1) - { - fPos[1] = fVal; - } - else - { - iResult = 0; - } - - /* normal beam geometry */ - if(SXGetMode() == NB) - { - pNu = SXGetMotor(Nu); - if(pNu){ - SCWrite(pCon,"ERROR: configuration problem, nu motor not found,", - eError); - return 0; - } - iRet = MotorGetSoftPosition(pNu,pCon, &fVal); - if(iRet == 1) - { - fPos[2] = fVal; - } - else - { - iResult = 0; - } - return iResult; - } - - /* bissecting geometry */ - iRet = MotorGetSoftPosition(pChi,pCon, &fVal); - if(iRet == 1) - { - fPos[2] = fVal; - } - else - { - iResult = 0; - } - iRet = MotorGetSoftPosition(pPhi,pCon, &fVal); - if(iRet == 1) - { - fPos[3] = fVal; - } - else - { - iResult = 0; - } - - return iResult; + pTheta = SXGetMotor(TwoTheta); + pOmega = SXGetMotor(Omega); + pChi = SXGetMotor(Chi); + pPhi = SXGetMotor(Phi); + if (pTheta == NULL || pOmega == NULL || pChi == NULL || pPhi == NULL) { + SCWrite(pCon, + "ERROR: configuration problem, stt,om,chi,phi motors not found,", + eError); + return 0; } + + assert(self); + assert(pCon); + + iResult = 1; + iRet = MotorGetSoftPosition(pTheta, pCon, &fVal); + if (iRet == 1) { + fPos[0] = fVal; + } else { + iResult = 0; + } + iRet = MotorGetSoftPosition(pOmega, pCon, &fVal); + if (iRet == 1) { + fPos[1] = fVal; + } else { + iResult = 0; + } + + /* normal beam geometry */ + if (SXGetMode() == NB) { + pNu = SXGetMotor(Nu); + if (pNu) { + SCWrite(pCon, "ERROR: configuration problem, nu motor not found,", + eError); + return 0; + } + iRet = MotorGetSoftPosition(pNu, pCon, &fVal); + if (iRet == 1) { + fPos[2] = fVal; + } else { + iResult = 0; + } + return iResult; + } + + /* bissecting geometry */ + iRet = MotorGetSoftPosition(pChi, pCon, &fVal); + if (iRet == 1) { + fPos[2] = fVal; + } else { + iResult = 0; + } + iRet = MotorGetSoftPosition(pPhi, pCon, &fVal); + if (iRet == 1) { + fPos[3] = fVal; + } else { + iResult = 0; + } + + return iResult; +} + /*------------------------------------------------------------------------- For the conversion from angles to HKL. -------------------------------------------------------------------------*/ - int GetHKLFromAngles(pHKL self, SConnection *pCon, float fHKL[3]){ - pSingleDiff single = NULL; - double dHkl[3]; - int i, status; - - single = SXGetDiffractometer(); - assert(single != NULL); - - status = single->hklFromAngles(single,dHkl); - for(i = 0; i < 3; i++){ - fHKL[i] = dHkl[i]; - } - return status; - } -/*--------------------------------------------------------------------------*/ - static int GetCommandData(int argc, char *argv[], float fHKL[3], - float *fPsi, int *iHamil, SConnection *pCon) - { - int iRet, i; - double d; - char pBueffel[512]; - - if(argc < 3) - { - SCWrite(pCon, - "ERROR: Insufficient reflection data specified for calculation", - eError); - return 0; - } +int GetHKLFromAngles(pHKL self, SConnection * pCon, float fHKL[3]) +{ + pSingleDiff single = NULL; + double dHkl[3]; + int i, status; - /* get the reflection */ - for(i = 0; i < 3; i++) - { - if(!isNumeric(argv[i])) - { - sprintf(pBueffel,"ERROR: %s is NOT recognized as a number",argv[i]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fHKL[i] = atof(argv[i]); - } - - *fPsi = 0.; - *iHamil = 0; - - /* has psi been specicifed ? */ - if(argc > 3) - { - if(!isNumeric(argv[3])) - { - sprintf(pBueffel,"ERROR: %s is NOT recognized as a number",argv[3]); - SCWrite(pCon,pBueffel,eError); - } - *fPsi = atof(argv[3]); - } - - /* has iHamil been specified ? */ - if(argc > 4) - { - if(!isNumeric(argv[4])) - { - sprintf(pBueffel,"ERROR: %s is NOT recognized as a number",argv[4]); - SCWrite(pCon,pBueffel,eError); - } - *iHamil = atof(argv[4]); - } - return 1; + single = SXGetDiffractometer(); + assert(single != NULL); + + status = single->hklFromAngles(single, dHkl); + for (i = 0; i < 3; i++) { + fHKL[i] = dHkl[i]; } + return status; +} + /*--------------------------------------------------------------------------*/ -static int HKLCalculateTheta(pHKL self,float fHKL[3], double *stt){ +static int GetCommandData(int argc, char *argv[], float fHKL[3], + float *fPsi, int *iHamil, SConnection * pCon) +{ + int iRet, i; + double d; + char pBueffel[512]; + + if (argc < 3) { + SCWrite(pCon, + "ERROR: Insufficient reflection data specified for calculation", + eError); + return 0; + } + + /* get the reflection */ + for (i = 0; i < 3; i++) { + if (!isNumeric(argv[i])) { + sprintf(pBueffel, "ERROR: %s is NOT recognized as a number", + argv[i]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fHKL[i] = atof(argv[i]); + } + + *fPsi = 0.; + *iHamil = 0; + + /* has psi been specicifed ? */ + if (argc > 3) { + if (!isNumeric(argv[3])) { + sprintf(pBueffel, "ERROR: %s is NOT recognized as a number", + argv[3]); + SCWrite(pCon, pBueffel, eError); + } + *fPsi = atof(argv[3]); + } + + /* has iHamil been specified ? */ + if (argc > 4) { + if (!isNumeric(argv[4])) { + sprintf(pBueffel, "ERROR: %s is NOT recognized as a number", + argv[4]); + SCWrite(pCon, pBueffel, eError); + } + *iHamil = atof(argv[4]); + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int HKLCalculateTheta(pHKL self, float fHKL[3], double *stt) +{ int status, i; MATRIX B, HC, H; double theta, d; @@ -673,10 +651,10 @@ static int HKLCalculateTheta(pHKL self,float fHKL[3], double *stt){ reflection r; lattice direct; - B = mat_creat(3,3,UNIT_MATRIX); - H = mat_creat(3,1,ZERO_MATRIX); - if(B == NULL) { - return UBNOMEMORY; + B = mat_creat(3, 3, UNIT_MATRIX); + H = mat_creat(3, 1, ZERO_MATRIX); + if (B == NULL) { + return UBNOMEMORY; } cell = SXGetCell(); direct.a = cell[0]; @@ -686,373 +664,317 @@ static int HKLCalculateTheta(pHKL self,float fHKL[3], double *stt){ direct.beta = cell[4]; direct.gamma = cell[5]; - status = calculateBMatrix(direct,B); - if(status < 0) { + status = calculateBMatrix(direct, B); + if (status < 0) { return status; } - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { H[i][0] = fHKL[i]; } - HC = mat_mul(B,H); + HC = mat_mul(B, H); status = calcTheta(SXGetLambda(), HC, &d, &theta); mat_free(HC); mat_free(B); mat_free(H); - *stt = 2.*theta; + *stt = 2. * theta; return status; } + /*--------------------------------------------------------------------------*/ - int HKLAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet,i, iHamil; - char pBueffel[512]; - float fUB[9], fPsi, fVal; - float fHKL[3], fSet[4]; - double dHKL[3], dSet[4]; - double dVal, lambda, stt; - const double *dUB; - pHKL self = NULL; - CommandList *pCom = NULL; - pDummy pDum = NULL; - pSingleDiff single = NULL; - - assert(pCon); - assert(pSics); - - self = (pHKL)pData; - assert(self); - - single = SXGetDiffractometer(); - - /* enough arguments ? */ - if(argc < 2) - { - SCWrite(pCon,"Insufficient number of arguments to HKL",eError); - return 0; - } - +int HKLAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet, i, iHamil; + char pBueffel[512]; + float fUB[9], fPsi, fVal; + float fHKL[3], fSet[4]; + double dHKL[3], dSet[4]; + double dVal, lambda, stt; + const double *dUB; + pHKL self = NULL; + CommandList *pCom = NULL; + pDummy pDum = NULL; + pSingleDiff single = NULL; + + assert(pCon); + assert(pSics); + + self = (pHKL) pData; + assert(self); + + single = SXGetDiffractometer(); + + /* enough arguments ? */ + if (argc < 2) { + SCWrite(pCon, "Insufficient number of arguments to HKL", eError); + return 0; + } + /*-------- handle list */ - strtolower(argv[1]); - if(strcmp(argv[1],"list") == 0 ) - { - sprintf(pBueffel, - "lambda = %f Normal Beam = %d Quadrant = %d HM = %d", - SXGetLambda(), self->iNOR, - self->iQuad,self->iHM); - SCWrite(pCon,pBueffel,eValue); - dUB = SXGetUB(); - sprintf(pBueffel,"UB = { %f %f %f", - dUB[0], dUB[1], dUB[2]); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel," %f %f %f", - dUB[3], dUB[4],dUB[5]); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel," %f %f %f }", - dUB[6], dUB[7],dUB[8]); - SCWrite(pCon,pBueffel,eValue); - return 1; - sprintf(pBueffel,"Last HKL: %f %f %f ", - self->fLastHKL[0], self->fLastHKL[1],self->fLastHKL[2]); - SCWrite(pCon,pBueffel,eValue); - snprintf(pBueffel,510,"%s.scantolerance = %f", argv[0], - self->scanTolerance); - SCWrite(pCon,pBueffel,eValue); - return 1; - } -/*----------- current */ - else if(strcmp(argv[1],"current") == 0) - { - GetHKLFromAngles(self,pCon,fHKL); - sprintf(pBueffel,"Current HKL: %8.4f %8.4f %8.4f ", - fHKL[0], fHKL[1],fHKL[2]); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else if(strcmp(argv[1],"fromangles") == 0) - { - if(argc < 6) - { - SCWrite(pCon, + strtolower(argv[1]); + if (strcmp(argv[1], "list") == 0) { + sprintf(pBueffel, + "lambda = %f Normal Beam = %d Quadrant = %d HM = %d", + SXGetLambda(), self->iNOR, self->iQuad, self->iHM); + SCWrite(pCon, pBueffel, eValue); + dUB = SXGetUB(); + sprintf(pBueffel, "UB = { %f %f %f", dUB[0], dUB[1], dUB[2]); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, " %f %f %f", dUB[3], dUB[4], dUB[5]); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, " %f %f %f }", dUB[6], dUB[7], dUB[8]); + SCWrite(pCon, pBueffel, eValue); + return 1; + sprintf(pBueffel, "Last HKL: %f %f %f ", + self->fLastHKL[0], self->fLastHKL[1], self->fLastHKL[2]); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 510, "%s.scantolerance = %f", argv[0], + self->scanTolerance); + SCWrite(pCon, pBueffel, eValue); + return 1; + } +/*----------- current */ + else if (strcmp(argv[1], "current") == 0) { + GetHKLFromAngles(self, pCon, fHKL); + sprintf(pBueffel, "Current HKL: %8.4f %8.4f %8.4f ", + fHKL[0], fHKL[1], fHKL[2]); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (strcmp(argv[1], "fromangles") == 0) { + if (argc < 6) { + SCWrite(pCon, "ERROR: need stt, om, chi,phi to calculate HKL from angles", - eError); - return 0; - } - for(i = 0; i < 4; i++) - { - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[i+2],&dVal); - if(iRet != TCL_OK){ - snprintf(pBueffel,511,"ERROR: failed to convert %s to number", - argv[i+2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - dSet[i] = dVal; - } - single->hklFromAnglesGiven(single,dSet,dHKL); - for(i = 0; i < 3; i++){ - fHKL[i] = dHKL[i]; - } - sprintf(pBueffel,"HKL from angles: %8.4f %8.4f %8.4f ", - fHKL[0], fHKL[1],fHKL[2]); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + eError); + return 0; + } + for (i = 0; i < 4; i++) { + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[i + 2], &dVal); + if (iRet != TCL_OK) { + snprintf(pBueffel, 511, "ERROR: failed to convert %s to number", + argv[i + 2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + dSet[i] = dVal; + } + single->hklFromAnglesGiven(single, dSet, dHKL); + for (i = 0; i < 3; i++) { + fHKL[i] = dHKL[i]; + } + sprintf(pBueffel, "HKL from angles: %8.4f %8.4f %8.4f ", + fHKL[0], fHKL[1], fHKL[2]); + SCWrite(pCon, pBueffel, eValue); + return 1; + } /*------------- lambda */ - else if(strcmp(argv[1],"lambda") == 0) - { - lambda = SXGetLambda(); - snprintf(pBueffel,132,"%s.lambda = %f", argv[0],lambda); - SCWrite(pCon,pBueffel,eValue); - } + else if (strcmp(argv[1], "lambda") == 0) { + lambda = SXGetLambda(); + snprintf(pBueffel, 132, "%s.lambda = %f", argv[0], lambda); + SCWrite(pCon, pBueffel, eValue); + } /*------------- getub*/ - else if(strcmp(argv[1],"getub") == 0) - { - dUB = SXGetUB(); - snprintf(pBueffel,510,"%s.ub = %f %f %f %f %f %f %f %f %f", - argv[0], dUB[0], dUB[1], dUB[2], - dUB[3], dUB[4], dUB[5], - dUB[6], dUB[7], dUB[8]); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + else if (strcmp(argv[1], "getub") == 0) { + dUB = SXGetUB(); + snprintf(pBueffel, 510, "%s.ub = %f %f %f %f %f %f %f %f %f", + argv[0], dUB[0], dUB[1], dUB[2], + dUB[3], dUB[4], dUB[5], dUB[6], dUB[7], dUB[8]); + SCWrite(pCon, pBueffel, eValue); + return 1; + } /*------------ UB */ - else if(strcmp(argv[1],"setub") == 0) - { - if(argc < 11) - { - SCWrite(pCon,"ERROR: Insufficient number of arguments to HKL setUB",eError); - return 0; - } - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - for(i = 2; i < 11; i++) - { - if(!isNumeric(argv[i])) - { - sprintf(pBueffel,"ERROR: %s was not recognized as a number", argv[i]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fUB[i-2] = atof(argv[i]); - } - iRet = SetUB(self,fUB); - if(!iRet) - { - SCWrite(pCon,"ERROR: cannot set UB Matrix",eError); - return 0; - } - SCSendOK(pCon); - return 1; - } + else if (strcmp(argv[1], "setub") == 0) { + if (argc < 11) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to HKL setUB", + eError); + return 0; + } + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + for (i = 2; i < 11; i++) { + if (!isNumeric(argv[i])) { + sprintf(pBueffel, "ERROR: %s was not recognized as a number", + argv[i]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fUB[i - 2] = atof(argv[i]); + } + iRet = SetUB(self, fUB); + if (!iRet) { + SCWrite(pCon, "ERROR: cannot set UB Matrix", eError); + return 0; + } + SCSendOK(pCon); + return 1; + } /*------------- HM mode */ - else if(strcmp(argv[1],"hm") == 0) - { - if(argc < 3) - { - sprintf(pBueffel,"%s.hm = %d", argv[0],self->iHM); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(!isNumeric(argv[2])) - { - sprintf(pBueffel,"ERROR: %s was not recognized as a number", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->iHM = atoi(argv[2]); - SCSendOK(pCon); - return 1; - } + else if (strcmp(argv[1], "hm") == 0) { + if (argc < 3) { + sprintf(pBueffel, "%s.hm = %d", argv[0], self->iHM); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (!isNumeric(argv[2])) { + sprintf(pBueffel, "ERROR: %s was not recognized as a number", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->iHM = atoi(argv[2]); + SCSendOK(pCon); + return 1; + } /*------------- normal beam */ - else if(strcmp(argv[1],"nb") == 0) - { - if(argc < 3) - { - snprintf(pBueffel,511,"%s.nb = %d",argv[0],self->iNOR); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(!isNumeric(argv[2])) - { - sprintf(pBueffel,"ERROR: %s was not recognized as a number", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = SetNOR(self,atoi(argv[2])); - if(!iRet) - { - SCWrite(pCon, - "ERROR: cannot set Normal Beam geometry, probably nu motor undefined", - eError); - return 0; - } - SCSendOK(pCon); - return 1; - } + else if (strcmp(argv[1], "nb") == 0) { + if (argc < 3) { + snprintf(pBueffel, 511, "%s.nb = %d", argv[0], self->iNOR); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (!isNumeric(argv[2])) { + sprintf(pBueffel, "ERROR: %s was not recognized as a number", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = SetNOR(self, atoi(argv[2])); + if (!iRet) { + SCWrite(pCon, + "ERROR: cannot set Normal Beam geometry, probably nu motor undefined", + eError); + return 0; + } + SCSendOK(pCon); + return 1; + } /*------------- quadrant */ - else if(strcmp(argv[1],"quadrant") == 0) - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: Insufficient number of arguments to HKL quadrant",eError); - return 0; - } - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(!isNumeric(argv[2])) - { - sprintf(pBueffel,"ERROR: %s was not recognized as a number", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = atoi(argv[2]); - if(!( (iRet == 1) || (iRet == 0)) ) - { - sprintf(pBueffel,"ERROR: Invalid parameter %d for quadrant, posiible: 0,1", - iRet); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->iQuad = iRet; - SCSendOK(pCon); - return 1; - } + else if (strcmp(argv[1], "quadrant") == 0) { + if (argc < 3) { + SCWrite(pCon, + "ERROR: Insufficient number of arguments to HKL quadrant", + eError); + return 0; + } + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (!isNumeric(argv[2])) { + sprintf(pBueffel, "ERROR: %s was not recognized as a number", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = atoi(argv[2]); + if (!((iRet == 1) || (iRet == 0))) { + sprintf(pBueffel, + "ERROR: Invalid parameter %d for quadrant, posiible: 0,1", + iRet); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->iQuad = iRet; + SCSendOK(pCon); + return 1; + } /*------------- scantolerance */ - else if(strcmp(argv[1],"scantolerance") == 0) - { - if(argc < 3) - { - snprintf(pBueffel,510,"%s.scantolerance = %f",argv[0], - self->scanTolerance); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(!isNumeric(argv[2])) - { - sprintf(pBueffel,"ERROR: %s was not recognized as a number", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->scanTolerance = atof(argv[2]); - SCSendOK(pCon); - return 1; - } -/*------------- calculate */ - else if(strcmp(argv[1],"calc") == 0) - { - iRet = GetCommandData(argc-2,&argv[2],fHKL, &fPsi, &iHamil,pCon); - if(!iRet) - { - return 0; - } - iRet = CalculateSettings(self,fHKL, fPsi, iHamil, fSet,pCon); - if(SXGetMode() == NB) - { - sprintf(pBueffel," gamma = %f, omega = %f, nu = %f", - fSet[0], fSet[1], fSet[2]); - SCWrite(pCon,pBueffel,eValue); - } - else - { - sprintf(pBueffel," 2-theta = %f, omega = %f, chi = %f, phi = %f", - fSet[0], fSet[1], fSet[2],fSet[3]); - SCWrite(pCon,pBueffel,eValue); - } - if(!iRet) - { - SCWrite(pCon, - "WARNING: Cannot drive to the hkl of your desire", - eWarning); - return 0; - } - return 1; - } -/*------------- calculate theta*/ - else if(strcmp(argv[1],"calctth") == 0) - { - iRet = GetCommandData(argc-2,&argv[2],fHKL, &fPsi, &iHamil,pCon); - if(!iRet) - { - return 0; - } - HKLCalculateTheta(self,fHKL, &stt); - SCPrintf(pCon,eValue,"two-theta = %lf", stt); - return 1; - } + else if (strcmp(argv[1], "scantolerance") == 0) { + if (argc < 3) { + snprintf(pBueffel, 510, "%s.scantolerance = %f", argv[0], + self->scanTolerance); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (!isNumeric(argv[2])) { + sprintf(pBueffel, "ERROR: %s was not recognized as a number", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->scanTolerance = atof(argv[2]); + SCSendOK(pCon); + return 1; + } +/*------------- calculate */ + else if (strcmp(argv[1], "calc") == 0) { + iRet = GetCommandData(argc - 2, &argv[2], fHKL, &fPsi, &iHamil, pCon); + if (!iRet) { + return 0; + } + iRet = CalculateSettings(self, fHKL, fPsi, iHamil, fSet, pCon); + if (SXGetMode() == NB) { + sprintf(pBueffel, " gamma = %f, omega = %f, nu = %f", + fSet[0], fSet[1], fSet[2]); + SCWrite(pCon, pBueffel, eValue); + } else { + sprintf(pBueffel, " 2-theta = %f, omega = %f, chi = %f, phi = %f", + fSet[0], fSet[1], fSet[2], fSet[3]); + SCWrite(pCon, pBueffel, eValue); + } + if (!iRet) { + SCWrite(pCon, + "WARNING: Cannot drive to the hkl of your desire", eWarning); + return 0; + } + return 1; + } +/*------------- calculate theta*/ + else if (strcmp(argv[1], "calctth") == 0) { + iRet = GetCommandData(argc - 2, &argv[2], fHKL, &fPsi, &iHamil, pCon); + if (!iRet) { + return 0; + } + HKLCalculateTheta(self, fHKL, &stt); + SCPrintf(pCon, eValue, "two-theta = %lf", stt); + return 1; + } /*------------------ run */ - else if(strcmp(argv[1],"run") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = GetCommandData(argc-2,&argv[2],fHKL, &fPsi, &iHamil,pCon); - if(!iRet) - { - return 0; - } - iRet = RunHKL(self,fHKL,fPsi, iHamil, pCon); - if(!iRet) - { - return 0; - } - else - { - SCSendOK(pCon); - return 1; - } - } + else if (strcmp(argv[1], "run") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + iRet = GetCommandData(argc - 2, &argv[2], fHKL, &fPsi, &iHamil, pCon); + if (!iRet) { + return 0; + } + iRet = RunHKL(self, fHKL, fPsi, iHamil, pCon); + if (!iRet) { + return 0; + } else { + SCSendOK(pCon); + return 1; + } + } /*------------------ drive */ - else if(strcmp(argv[1],"drive") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = GetCommandData(argc-2,&argv[2],fHKL, &fPsi, &iHamil,pCon); - if(!iRet) - { - return 0; - } - iRet = DriveHKL(self,fHKL,fPsi, iHamil, pCon); - if(!iRet) - { - return 0; - } - else - { - SCSendOK(pCon); - return 1; - } - } - else - { - sprintf(pBueffel,"ERROR: subcommand --> %s <-- not recognized", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 0; /* not reached */ - } - - - - - + else if (strcmp(argv[1], "drive") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + iRet = GetCommandData(argc - 2, &argv[2], fHKL, &fPsi, &iHamil, pCon); + if (!iRet) { + return 0; + } + iRet = DriveHKL(self, fHKL, fPsi, iHamil, pCon); + if (!iRet) { + return 0; + } else { + SCSendOK(pCon); + return 1; + } + } else { + sprintf(pBueffel, "ERROR: subcommand --> %s <-- not recognized", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 0; /* not reached */ +} diff --git a/hkl.h b/hkl.h index 5f8374eb..7014f0af 100644 --- a/hkl.h +++ b/hkl.h @@ -17,36 +17,36 @@ #include "selector.h" #include "selvar.h" - typedef struct __HKL *pHKL; +typedef struct __HKL *pHKL; /*-------------------------------------------------------------------------*/ - pHKL CreateHKL(); - void DeleteHKL(void *pData); - - int HKLFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +pHKL CreateHKL(); +void DeleteHKL(void *pData); + +int HKLFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*------------------------------------------------------------------------*/ - void SetHKLScanTolerance(pHKL self, float value); - int SetUB(pHKL self, float fUB[9]); - int GetUB(pHKL self, float fUB[9]); - int SetNOR(pHKL self, int iNOB); - int GetLambda(pHKL self, float *fVal); - int GetCurrentHKL(pHKL self, float fVal[3]); - int GetCurrentPosition(pHKL self, SConnection *pCon, float fPosition[4]); - int GetHKLFromAngles(pHKL self, SConnection *pCon, float fVal[3]); +void SetHKLScanTolerance(pHKL self, float value); +int SetUB(pHKL self, float fUB[9]); +int GetUB(pHKL self, float fUB[9]); +int SetNOR(pHKL self, int iNOB); +int GetLambda(pHKL self, float *fVal); +int GetCurrentHKL(pHKL self, float fVal[3]); +int GetCurrentPosition(pHKL self, SConnection * pCon, float fPosition[4]); +int GetHKLFromAngles(pHKL self, SConnection * pCon, float fVal[3]); - int CalculateSettings(pHKL self, float fHKL[3], float fPsi, int iHamil, - float fSet[4],SConnection *pCon); - int RunHKL(pHKL self, float fHKL[3], float fPsi, int iHamil, SConnection - *pCon); - int DriveHKL(pHKL self, float fHKL[3], float fPsi, int iHamil, - SConnection *pCon); +int CalculateSettings(pHKL self, float fHKL[3], float fPsi, int iHamil, + float fSet[4], SConnection * pCon); +int RunHKL(pHKL self, float fHKL[3], float fPsi, int iHamil, SConnection + * pCon); +int DriveHKL(pHKL self, float fHKL[3], float fPsi, int iHamil, + SConnection * pCon); - int DriveSettings(pHKL self, float fSet[4],SConnection *pCon); +int DriveSettings(pHKL self, float fSet[4], SConnection * pCon); - int HKLAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int hklInRange(void *data, double fSet[4], int mask[4]); - int startHKLMotors(pHKL self, SConnection *pCon, float fSet[4]); - void stopHKLMotors(pHKL self); +int HKLAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int hklInRange(void *data, double fSet[4], int mask[4]); +int startHKLMotors(pHKL self, SConnection * pCon, float fSet[4]); +void stopHKLMotors(pHKL self); -#endif +#endif diff --git a/hklmot.c b/hklmot.c index 49f88f2b..ab6f1183 100644 --- a/hklmot.c +++ b/hklmot.c @@ -17,159 +17,176 @@ #include "hklmot.h" #include "singlex.h" /*=================== Object Descriptor Interface ===================================================*/ -static void *HKLGetInterface(void *pData, int iID){ +static void *HKLGetInterface(void *pData, int iID) +{ pHKLMot self = NULL; - self = (pHKLMot)pData; - if(self == NULL){ + self = (pHKLMot) pData; + if (self == NULL) { return NULL; } - if(iID == DRIVEID){ + if (iID == DRIVEID) { return self->pDriv; } return NULL; } + /*--------------------------------------------------------------------------------------------------*/ extern void stopHKLMotors(pHKL hkl); /*=================== Drivable Interface ============================================================*/ -static int HKLHalt(void *pData){ +static int HKLHalt(void *pData) +{ pHKLMot self = NULL; - self = (pHKLMot)pData; + self = (pHKLMot) pData; assert(self != NULL); stopHKLMotors(self->pHkl); return 1; } + /*-----------------------------------------------------------------------------------------------------*/ -static int HKLCheckLimits(void *self, float fVal, char *error, int errLen){ +static int HKLCheckLimits(void *self, float fVal, char *error, int errLen) +{ /* - There is no meaningful implementation here. This gets called when starting the motor. - At that stage not all other values may be known. If the calculation fails, this will die - at status check time. - */ + There is no meaningful implementation here. This gets called when starting the motor. + At that stage not all other values may be known. If the calculation fails, this will die + at status check time. + */ return 1; } + /*----------------------------------------------------------------------------------------------------*/ -static long HKLSetValue(void *pData, SConnection *pCon, float fVal){ +static long HKLSetValue(void *pData, SConnection * pCon, float fVal) +{ pHKLMot self = NULL; - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - self = (pHKLMot)pData; + self = (pHKLMot) pData; assert(self != NULL); self->pHkl->targetHKL[self->index] = fVal; self->pHkl->targetDirty = 1; return OKOK; } + /*---------------------------------------------------------------------------------------------------*/ -static int checkMotors(pHKLMot self, SConnection *pCon){ +static int checkMotors(pHKLMot self, SConnection * pCon) +{ int status; pMotor pTheta, pOmega, pChi, pPhi, pNu; - + pTheta = SXGetMotor(TwoTheta); pOmega = SXGetMotor(Omega); pChi = SXGetMotor(Chi); pPhi = SXGetMotor(Phi); - if(pTheta == NULL || pOmega == NULL){ - SCWrite(pCon,"ERROR: configuration problem, stt,om motors not found,", - eError); - return HWFault; + if (pTheta == NULL || pOmega == NULL) { + SCWrite(pCon, "ERROR: configuration problem, stt,om motors not found,", + eError); + return HWFault; } - + status = pTheta->pDrivInt->CheckStatus(pTheta, pCon); - if(status != HWIdle && status != OKOK){ + if (status != HWIdle && status != OKOK) { return status; } status = pOmega->pDrivInt->CheckStatus(pOmega, pCon); - if(status != HWIdle && status != OKOK){ + if (status != HWIdle && status != OKOK) { return status; } - if(SXGetMode() == NB){ - pNu = SXGetMotor(Nu); - if(pNu == NULL){ - SCWrite(pCon,"ERROR: configuration problem, nu motor not found,", - eError); - return HWFault; - - } + if (SXGetMode() == NB) { + pNu = SXGetMotor(Nu); + if (pNu == NULL) { + SCWrite(pCon, "ERROR: configuration problem, nu motor not found,", + eError); + return HWFault; + + } status = pNu->pDrivInt->CheckStatus(pNu, pCon); - if(status != HWIdle && status != OKOK){ + if (status != HWIdle && status != OKOK) { return status; } } else { - pChi = SXGetMotor(Chi); - pPhi = SXGetMotor(Phi); - if(pTheta == NULL || pOmega == NULL){ - SCWrite(pCon,"ERROR: configuration problem, chi, phi motors not found,", - eError); - return HWFault; - } + pChi = SXGetMotor(Chi); + pPhi = SXGetMotor(Phi); + if (pTheta == NULL || pOmega == NULL) { + SCWrite(pCon, + "ERROR: configuration problem, chi, phi motors not found,", + eError); + return HWFault; + } status = pChi->pDrivInt->CheckStatus(pChi, pCon); - if(status != HWIdle && status != OKOK){ + if (status != HWIdle && status != OKOK) { return status; } status = pPhi->pDrivInt->CheckStatus(pPhi, pCon); - if(status != HWIdle && status != OKOK){ + if (status != HWIdle && status != OKOK) { return status; } } return HWIdle; } + /*-----------------------------------------------------------------------------------------------------*/ -static int HKLCheckStatus(void *pData, SConnection *pCon){ +static int HKLCheckStatus(void *pData, SConnection * pCon) +{ pHKLMot self = NULL; int status; - self = (pHKLMot)pData; + self = (pHKLMot) pData; assert(self != NULL); - if(self->pHkl->targetDirty == 1){ - status = RunHKL(self->pHkl,self->pHkl->targetHKL,.0,0,pCon); + if (self->pHkl->targetDirty == 1) { + status = RunHKL(self->pHkl, self->pHkl->targetHKL, .0, 0, pCon); self->pHkl->targetDirty = 0; - if(status != 1){ - SCSetInterrupt(pCon,eAbortOperation); + if (status != 1) { + SCSetInterrupt(pCon, eAbortOperation); return HWFault; } return HWBusy; } else { - return checkMotors(self,pCon); + return checkMotors(self, pCon); } } + /*-----------------------------------------------------------------------------------------------------*/ -static float HKLGetValue(void *pData, SConnection *pCon){ +static float HKLGetValue(void *pData, SConnection * pCon) +{ pHKLMot self = NULL; float fVal[3]; int status; - self = (pHKLMot)pData; + self = (pHKLMot) pData; assert(self != NULL); - status = GetHKLFromAngles(self->pHkl,pCon,fVal); - if(status != 1){ - SCWrite(pCon,"ERROR: failed to read positions or convert to HKL",eError); + status = GetHKLFromAngles(self->pHkl, pCon, fVal); + if (status != 1) { + SCWrite(pCon, "ERROR: failed to read positions or convert to HKL", + eError); return -9999.99; } return fVal[self->index]; } + /*=============================== Live and Death ====================================*/ -static pHKLMot MakeHKLMot(pHKL pHkl, int index){ +static pHKLMot MakeHKLMot(pHKL pHkl, int index) +{ pHKLMot self = NULL; assert(pHkl != NULL); assert(index >= 0 && index < 3); - self = (pHKLMot)malloc(sizeof(HKLMot)); - if(self == NULL){ + self = (pHKLMot) malloc(sizeof(HKLMot)); + if (self == NULL) { return NULL; } - memset(self,0,sizeof(HKLMot)); + memset(self, 0, sizeof(HKLMot)); self->pDes = CreateDescriptor("HKLMot"); self->pDriv = CreateDrivableInterface(); - if(self->pDes == NULL || self->pDriv == NULL){ + if (self->pDes == NULL || self->pDriv == NULL) { free(self); return NULL; } @@ -183,86 +200,95 @@ static pHKLMot MakeHKLMot(pHKL pHkl, int index){ self->index = index; return self; } + /*----------------------------------------------------------------------------------*/ -static void KillHklMot(void *pData){ +static void KillHklMot(void *pData) +{ pHKLMot self = NULL; - self = (pHKLMot)pData; - if(self == NULL){ + self = (pHKLMot) pData; + if (self == NULL) { return; } - if(self->pDes != NULL){ + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); } - if(self->pDriv){ + if (self->pDriv) { free(self->pDriv); } free(self); } + /*=============================== Interpreter Interface ============================*/ -int HKLMotAction(SConnection *pCon, SicsInterp *pSics, void *pData, int argc, char *argv[]){ +int HKLMotAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pHKLMot self = NULL; float value; char pBuffer[132]; - self = (pHKLMot)pData; + self = (pHKLMot) pData; assert(self != NULL); - value = self->pDriv->GetValue(self,pCon); - if(value < -9000.){ - snprintf(pBuffer,131,"ERROR: failed to read %s",argv[0]); - SCWrite(pCon,pBuffer,eError); + value = self->pDriv->GetValue(self, pCon); + if (value < -9000.) { + snprintf(pBuffer, 131, "ERROR: failed to read %s", argv[0]); + SCWrite(pCon, pBuffer, eError); return 0; } - snprintf(pBuffer,131,"%s = %f", argv[0], value); - SCWrite(pCon,pBuffer,eValue); + snprintf(pBuffer, 131, "%s = %f", argv[0], value); + SCWrite(pCon, pBuffer, eValue); return 1; } + /*------------------------------------------------------------------------------------------*/ -int HKLMotInstall(SConnection *pCon, SicsInterp *pSics, void *pData, int argc, char *argv[]){ +int HKLMotInstall(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pHKL pHkl; pHKLMot pMot = NULL; char pBuffer[131]; - if(argc < 2){ - pHkl = (pHKL)FindCommandData(pSics,"hkl","4-Circle-Calculus"); + if (argc < 2) { + pHkl = (pHKL) FindCommandData(pSics, "hkl", "4-Circle-Calculus"); } else { - strtolower(argv[1]); - pHkl = (pHKL)FindCommandData(pSics,argv[1],"4-Circle-Calculus"); + strtolower(argv[1]); + pHkl = (pHKL) FindCommandData(pSics, argv[1], "4-Circle-Calculus"); } - if(pHkl == NULL){ - snprintf(pBuffer,131,"ERROR: %s is not present or no HKL object",argv[1]); - SCWrite(pCon,pBuffer,eError); + if (pHkl == NULL) { + snprintf(pBuffer, 131, "ERROR: %s is not present or no HKL object", + argv[1]); + SCWrite(pCon, pBuffer, eError); return 0; } pMot = MakeHKLMot(pHkl, 0); - if(pMot == NULL){ - SCWrite(pCon,"ERROR: out of memory creating H Motor",eError); + if (pMot == NULL) { + SCWrite(pCon, "ERROR: out of memory creating H Motor", eError); return 0; } - if(!AddCommand(pSics,"H",HKLMotAction,KillHklMot,pMot)){ - SCWrite(pCon,"ERROR: duplicate command H not created",eError); + if (!AddCommand(pSics, "H", HKLMotAction, KillHklMot, pMot)) { + SCWrite(pCon, "ERROR: duplicate command H not created", eError); return 0; } pMot = MakeHKLMot(pHkl, 1); - if(pMot == NULL){ - SCWrite(pCon,"ERROR: out of memory creating K Motor",eError); + if (pMot == NULL) { + SCWrite(pCon, "ERROR: out of memory creating K Motor", eError); return 0; } - if(!AddCommand(pSics,"K",HKLMotAction,KillHklMot,pMot)){ - SCWrite(pCon,"ERROR: duplicate command K not created",eError); + if (!AddCommand(pSics, "K", HKLMotAction, KillHklMot, pMot)) { + SCWrite(pCon, "ERROR: duplicate command K not created", eError); return 0; } pMot = MakeHKLMot(pHkl, 2); - if(pMot == NULL){ - SCWrite(pCon,"ERROR: out of memory creating L Motor",eError); + if (pMot == NULL) { + SCWrite(pCon, "ERROR: out of memory creating L Motor", eError); return 0; } - if(!AddCommand(pSics,"L",HKLMotAction,KillHklMot,pMot)){ - SCWrite(pCon,"ERROR: duplicate command L not created",eError); + if (!AddCommand(pSics, "L", HKLMotAction, KillHklMot, pMot)) { + SCWrite(pCon, "ERROR: duplicate command L not created", eError); return 0; } return 1; diff --git a/hklmot.h b/hklmot.h index d3aae155..df4494ca 100644 --- a/hklmot.h +++ b/hklmot.h @@ -11,17 +11,17 @@ #define SICSHKLMOT /*====================== data structure ==============================================================*/ -typedef struct __HKLMOT { - pObjectDescriptor pDes; - pHKL pHkl; - pIDrivable pDriv; - int index; - }HKLMot, *pHKLMot; +typedef struct __HKLMOT { + pObjectDescriptor pDes; + pHKL pHkl; + pIDrivable pDriv; + int index; +} HKLMot, *pHKLMot; /*======================= interpreter interface ======================================================*/ -int HKLMotAction(SConnection *pCon, SicsInterp *pSics, void *pData, int argc, char *argv[]); -int HKLMotInstall(SConnection *pCon, SicsInterp *pSics, void *pData, int argc, char *argv[]); +int HKLMotAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int HKLMotInstall(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif - - diff --git a/hklscan.c b/hklscan.c index 6ed90cdd..a33e6f46 100644 --- a/hklscan.c +++ b/hklscan.c @@ -31,425 +31,372 @@ #include "hklscan.h" /*-----------------------------------------------------------------------*/ - static void KillHklscan(void *pData) - { - pHklscan self = NULL; +static void KillHklscan(void *pData) +{ + pHklscan self = NULL; - self = (pHklscan)pData; - if(!self) - { - return; - } - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - free(self); + self = (pHklscan) pData; + if (!self) { + return; } + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + free(self); +} + /*------------------------------------------------------------------------*/ - int HklscanFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[4]) - { - pHklscan pNew = NULL; - char pBueffel[512]; - int iRet; +int HklscanFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[4]) +{ + pHklscan pNew = NULL; + char pBueffel[512]; + int iRet; - /* check number of arguments */ - if(argc < 3) - { - SCWrite(pCon, - "ERROR: expected two arguments to MakeHklscan",eError); - return 0; - } - - /* allocate space */ - pNew = (pHklscan)malloc(sizeof(sHklscan)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory in MakeHklscan",eError); - return 0; - } - memset(pNew,0,sizeof(sHklscan)); - pNew->pDes = CreateDescriptor("Hklscan"); - - /* find scan object */ - pNew->pScan = (pScanData)FindCommandData(pSics,argv[1],"ScanObject"); - if(!pNew->pScan) - { - sprintf(pBueffel,"ERROR: %s not found or no scan object",argv[1]); - SCWrite(pCon,pBueffel,eError); - KillHklscan(pNew); - return 0; - } - - /* find HKL object */ - pNew->pCalc = (pHKL)FindCommandData(pSics,argv[2], - "4-Circle-Calculus"); - if(!pNew->pCalc) - { - sprintf(pBueffel,"ERROR: %s not found or no HKL object",argv[2]); - SCWrite(pCon,pBueffel,eError); - KillHklscan(pNew); - return 0; - } - - /* alright. Install command */ - iRet = AddCommand(pSics, "__hklscan", - HklscanAction,KillHklscan,pNew); - if(!iRet) - { - SCWrite(pCon,"ERROR: duplicate command hklscan NOT created",eError); - KillHklscan(pNew); - return 0; - } - return 1; + /* check number of arguments */ + if (argc < 3) { + SCWrite(pCon, "ERROR: expected two arguments to MakeHklscan", eError); + return 0; } + + /* allocate space */ + pNew = (pHklscan) malloc(sizeof(sHklscan)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory in MakeHklscan", eError); + return 0; + } + memset(pNew, 0, sizeof(sHklscan)); + pNew->pDes = CreateDescriptor("Hklscan"); + + /* find scan object */ + pNew->pScan = (pScanData) FindCommandData(pSics, argv[1], "ScanObject"); + if (!pNew->pScan) { + sprintf(pBueffel, "ERROR: %s not found or no scan object", argv[1]); + SCWrite(pCon, pBueffel, eError); + KillHklscan(pNew); + return 0; + } + + /* find HKL object */ + pNew->pCalc = (pHKL) FindCommandData(pSics, argv[2], + "4-Circle-Calculus"); + if (!pNew->pCalc) { + sprintf(pBueffel, "ERROR: %s not found or no HKL object", argv[2]); + SCWrite(pCon, pBueffel, eError); + KillHklscan(pNew); + return 0; + } + + /* alright. Install command */ + iRet = AddCommand(pSics, "__hklscan", HklscanAction, KillHklscan, pNew); + if (!iRet) { + SCWrite(pCon, "ERROR: duplicate command hklscan NOT created", eError); + KillHklscan(pNew); + return 0; + } + return 1; +} + /*------------------------------------------------------------------------*/ - static int HklscanDrive(pScanData pScan, int iPoint) - { - pHklscan self = NULL; - int i, iRet; +static int HklscanDrive(pScanData pScan, int iPoint) +{ + pHklscan self = NULL; + int i, iRet; - assert(pScan); - self = (pHklscan)pScan->pSpecial; - assert(self); + assert(pScan); + self = (pHklscan) pScan->pSpecial; + assert(self); - /* calculate new Positions */ - for(i = 0; i < 3; i++) - { - self->fPos[i] = self->fStart[i] + iPoint * self->fStep[i]; - } - iRet = DriveHKL(self->pCalc, self->fPos, 0.,0,pScan->pCon); - if(!iRet) - { - SCWrite(pScan->pCon,"ERROR: aborting hklscan",eError); - } - return iRet; + /* calculate new Positions */ + for (i = 0; i < 3; i++) { + self->fPos[i] = self->fStart[i] + iPoint * self->fStep[i]; } + iRet = DriveHKL(self->pCalc, self->fPos, 0., 0, pScan->pCon); + if (!iRet) { + SCWrite(pScan->pCon, "ERROR: aborting hklscan", eError); + } + return iRet; +} + /*------------------------------------------------------------------------*/ - static int WriteHklscanPoint(pScanData self, int iPoint) - { - pHklscan pHaSca = NULL; - int i, i2; - char pLine[512], pItem[30], pInfo[512]; - pVarEntry pVar = NULL; - pCountEntry pData = NULL; - void *pPtr = NULL; +static int WriteHklscanPoint(pScanData self, int iPoint) +{ + pHklscan pHaSca = NULL; + int i, i2; + char pLine[512], pItem[30], pInfo[512]; + pVarEntry pVar = NULL; + pCountEntry pData = NULL; + void *pPtr = NULL; - assert(self); - pHaSca = (pHklscan)self->pSpecial; - assert(pHaSca); + assert(self); + pHaSca = (pHklscan) self->pSpecial; + assert(pHaSca); - - assert(self->pCon); - assert(self->pSics); - if(!self->fd) - { - self->fd = fopen(self->pFile,"r+"); - if(!self->fd) - { - SCWrite(self->pCon,"ERROR: failed to reopen scan file during scan",eError); - return 0; - } - } - - /* jump to end of header */ - fseek(self->fd,self->lPos, SEEK_SET); - if(self->iChannel != 0) - { - fprintf(self->fd,"WARNING: Scanning monitor %d\n",self->iChannel); - } - - /* make the data header */ - sprintf(pLine,"%-5s","NP"); - sprintf(pInfo,"Scanning Variables: H, K, L STEP: %8.3f %8.3f %8.3f", - pHaSca->fStep[0],pHaSca->fStep[1], pHaSca->fStep[2]); - strcat(pLine,"H K L "); - for(i = 0; i < self->iScanVar;i++) - { - DynarGet(self->pScanVar,i,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - sprintf(pItem,"%-6.6s ",pVar->Name); - strcat(pLine,pItem); - } - } - strcat(pLine,"Counts "); - strcat(pLine," Monitor1 "); - sprintf(pItem,"\n%d Points,",self->iNP); - strcat(pInfo,pItem); - if(self->iMode == eTimer) - { - strcat(pInfo," Mode: Timer,"); - } - else - { - strcat(pInfo," Mode: Monitor,"); - } - sprintf(pItem," Preset %f",self->fPreset); - strcat(pInfo,pItem); - fprintf(self->fd,"%s\n",pInfo); - fprintf(self->fd,"%s\n",pLine); + assert(self->pCon); + assert(self->pSics); - /* print an addon to the status line going to the screen */ - sprintf(pLine,"NP H K L "); - SCWrite(self->pCon,pLine,eWarning); - sprintf(pLine,"%-5d%-8.4f%-8.4f%-8.4f ",iPoint,pHaSca->fPos[0], - pHaSca->fPos[1], pHaSca->fPos[2]); - SCWrite(self->pCon,pLine,eWarning); - - /* now the scan points */ - for(i = 0; i < self->iCounts; i++) - { - sprintf(pLine,"%-5d",i); - /* print HKL */ - for(i2 = 0; i2 < 3; i2++) - { - sprintf(pItem," %-8.4f",pHaSca->fStart[i2] + i * pHaSca->fStep[i2]); - strcat(pLine,pItem); - } - /* print chi, ph, om */ - for(i2 = 0; i2 < self->iScanVar; i2++) - { - DynarGet(self->pScanVar,i2,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - sprintf(pItem," %-7.2f",GetScanVarPos(pVar,i)); - strcat(pLine,pItem); - } - } - /* print Counts & Monitor */ - DynarGet(self->pCounts,i,&pPtr); - pData = (pCountEntry)pPtr; - if(pData) - { - sprintf(pItem," %-13ld",pData->lCount); - strcat(pLine,pItem); - sprintf(pItem," %-12ld",pData->Monitors[0]); - strcat(pLine,pItem); - } - fprintf(self->fd,"%s\n",pLine); - } - - /* done */ - fprintf(self->fd,"END-OF-DATA\n"); - fclose(self->fd); - self->fd = NULL; - return 1; - } -/*-------------------------------------------------------------------*/ - int Hklscan(pHklscan self, SConnection *pCon, - int iNP, int iMode, float fPreset) - { - int iRet; - float fVal; - - assert(self); - - /* configure the scan thing for our bizarre purpose */ - ClearScanVar(self->pScan); - MotorGetPar(self->pCalc->pTheta, "softlowerlim",&fVal); - fVal += .5; - AddScanVar(self->pScan,pServ->pSics,pCon,self->pCalc->pTheta->name, - fVal,0.); - MotorGetPar(self->pCalc->pOmega, "softlowerlim",&fVal); - fVal += .5; - AddScanVar(self->pScan,pServ->pSics,pCon,self->pCalc->pOmega->name, - fVal,0.); - MotorGetPar(self->pCalc->pChi, "softlowerlim",&fVal); - fVal += .5; - AddScanVar(self->pScan,pServ->pSics,pCon,self->pCalc->pChi->name, - fVal,0.); - MotorGetPar(self->pCalc->pPhi, "softlowerlim",&fVal); - fVal += .5; - AddScanVar(self->pScan,pServ->pSics,pCon,self->pCalc->pPhi->name, - fVal,0.); - self->pScan->WriteScanPoints = WriteHklscanPoint; - self->pScan->ScanDrive = HklscanDrive; - self->pScan->pSpecial = self; - self->pScan->PrepareScan = NonCheckPrepare; - - /* scan */ - iRet = DoScan(self->pScan,iNP, iMode, fPreset, pServ->pSics,pCon); - - /* unset all */ - ClearScanVar(self->pScan); - ResetScanFunctions(self->pScan); - self->pScan->pSpecial = NULL; - - return iRet; - } -/*-------------------------------------------------------------------------*/ - int HklscanAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - int iRet, iMode, iNP, iPoint; - pHklscan self = NULL; - double dVal; - float fPreset; - void *pPtr; - - assert(pCon); - assert(pSics); - assert(pData); - - self = (pHklscan)pData; - - /* check for the command word */ - if(argc < 2) - { - SCWrite(pCon,"ERROR: Insufficient number of arguments to hklscan", - eError); - return 0; - } - - /* do work according to command word */ - strtolower(argv[1]); - if(strcmp(argv[1],"start") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(argc < 5) - { - SCWrite(pCon, - "Insufficient number of arguments to hklscan", - eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->fStart[0] = (float)dVal; - iRet = Tcl_GetDouble(pSics->pTcl,argv[3],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->fStart[1] = (float)dVal; - iRet = Tcl_GetDouble(pSics->pTcl,argv[4],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[4]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->fStart[2] = (float)dVal; - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"step") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(argc < 5) - { - SCWrite(pCon, - "Insufficient number of arguments to hklscan", - eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->fStep[0] = (float)dVal; - iRet = Tcl_GetDouble(pSics->pTcl,argv[3],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->fStep[1] = (float)dVal; - iRet = Tcl_GetDouble(pSics->pTcl,argv[4],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[4]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->fStep[2] = (float)dVal; - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"run") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(argc < 5) - { - SCWrite(pCon, - "Insufficient number of arguments to hklscan run", - eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iNP); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* interpret Mode */ - if(strcmp(argv[3],"timer") == 0) - { - iMode = eTimer; - } - else if(strcmp(argv[3],"monitor") == 0) - { - iMode = ePreset; - } - else - { - sprintf(pBueffel,"ERROR: %s not recognized as valid counter mode", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* preset */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[4],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fPreset = (float)dVal; - iRet = Hklscan(self,pCon,iNP,iMode,fPreset); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - sprintf(pBueffel, - "ERROR: %s not recognized as command word to hklscan",argv[1]); - SCWrite(pCon,pBueffel,eError); + if (!self->fd) { + self->fd = fopen(self->pFile, "r+"); + if (!self->fd) { + SCWrite(self->pCon, "ERROR: failed to reopen scan file during scan", + eError); return 0; - } + } + } + + /* jump to end of header */ + fseek(self->fd, self->lPos, SEEK_SET); + if (self->iChannel != 0) { + fprintf(self->fd, "WARNING: Scanning monitor %d\n", self->iChannel); + } + + /* make the data header */ + sprintf(pLine, "%-5s", "NP"); + sprintf(pInfo, "Scanning Variables: H, K, L STEP: %8.3f %8.3f %8.3f", + pHaSca->fStep[0], pHaSca->fStep[1], pHaSca->fStep[2]); + strcat(pLine, "H K L "); + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + sprintf(pItem, "%-6.6s ", pVar->Name); + strcat(pLine, pItem); + } + } + strcat(pLine, "Counts "); + strcat(pLine, " Monitor1 "); + sprintf(pItem, "\n%d Points,", self->iNP); + strcat(pInfo, pItem); + if (self->iMode == eTimer) { + strcat(pInfo, " Mode: Timer,"); + } else { + strcat(pInfo, " Mode: Monitor,"); + } + sprintf(pItem, " Preset %f", self->fPreset); + strcat(pInfo, pItem); + fprintf(self->fd, "%s\n", pInfo); + fprintf(self->fd, "%s\n", pLine); + + /* print an addon to the status line going to the screen */ + sprintf(pLine, "NP H K L "); + SCWrite(self->pCon, pLine, eWarning); + sprintf(pLine, "%-5d%-8.4f%-8.4f%-8.4f ", iPoint, pHaSca->fPos[0], + pHaSca->fPos[1], pHaSca->fPos[2]); + SCWrite(self->pCon, pLine, eWarning); + + /* now the scan points */ + for (i = 0; i < self->iCounts; i++) { + sprintf(pLine, "%-5d", i); + /* print HKL */ + for (i2 = 0; i2 < 3; i2++) { + sprintf(pItem, " %-8.4f", + pHaSca->fStart[i2] + i * pHaSca->fStep[i2]); + strcat(pLine, pItem); + } + /* print chi, ph, om */ + for (i2 = 0; i2 < self->iScanVar; i2++) { + DynarGet(self->pScanVar, i2, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + sprintf(pItem, " %-7.2f", GetScanVarPos(pVar, i)); + strcat(pLine, pItem); + } + } + /* print Counts & Monitor */ + DynarGet(self->pCounts, i, &pPtr); + pData = (pCountEntry) pPtr; + if (pData) { + sprintf(pItem, " %-13ld", pData->lCount); + strcat(pLine, pItem); + sprintf(pItem, " %-12ld", pData->Monitors[0]); + strcat(pLine, pItem); + } + fprintf(self->fd, "%s\n", pLine); + } + + /* done */ + fprintf(self->fd, "END-OF-DATA\n"); + fclose(self->fd); + self->fd = NULL; + return 1; +} + +/*-------------------------------------------------------------------*/ +int Hklscan(pHklscan self, SConnection * pCon, + int iNP, int iMode, float fPreset) +{ + int iRet; + float fVal; + + assert(self); + + /* configure the scan thing for our bizarre purpose */ + ClearScanVar(self->pScan); + MotorGetPar(self->pCalc->pTheta, "softlowerlim", &fVal); + fVal += .5; + AddScanVar(self->pScan, pServ->pSics, pCon, self->pCalc->pTheta->name, + fVal, 0.); + MotorGetPar(self->pCalc->pOmega, "softlowerlim", &fVal); + fVal += .5; + AddScanVar(self->pScan, pServ->pSics, pCon, self->pCalc->pOmega->name, + fVal, 0.); + MotorGetPar(self->pCalc->pChi, "softlowerlim", &fVal); + fVal += .5; + AddScanVar(self->pScan, pServ->pSics, pCon, self->pCalc->pChi->name, + fVal, 0.); + MotorGetPar(self->pCalc->pPhi, "softlowerlim", &fVal); + fVal += .5; + AddScanVar(self->pScan, pServ->pSics, pCon, self->pCalc->pPhi->name, + fVal, 0.); + self->pScan->WriteScanPoints = WriteHklscanPoint; + self->pScan->ScanDrive = HklscanDrive; + self->pScan->pSpecial = self; + self->pScan->PrepareScan = NonCheckPrepare; + + /* scan */ + iRet = DoScan(self->pScan, iNP, iMode, fPreset, pServ->pSics, pCon); + + /* unset all */ + ClearScanVar(self->pScan); + ResetScanFunctions(self->pScan); + self->pScan->pSpecial = NULL; + + return iRet; +} + +/*-------------------------------------------------------------------------*/ +int HklscanAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512]; + int iRet, iMode, iNP, iPoint; + pHklscan self = NULL; + double dVal; + float fPreset; + void *pPtr; + + assert(pCon); + assert(pSics); + assert(pData); + + self = (pHklscan) pData; + + /* check for the command word */ + if (argc < 2) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to hklscan", + eError); + return 0; + } + + /* do work according to command word */ + strtolower(argv[1]); + if (strcmp(argv[1], "start") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (argc < 5) { + SCWrite(pCon, + "Insufficient number of arguments to hklscan", eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->fStart[0] = (float) dVal; + iRet = Tcl_GetDouble(pSics->pTcl, argv[3], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->fStart[1] = (float) dVal; + iRet = Tcl_GetDouble(pSics->pTcl, argv[4], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[4]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->fStart[2] = (float) dVal; + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "step") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (argc < 5) { + SCWrite(pCon, + "Insufficient number of arguments to hklscan", eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->fStep[0] = (float) dVal; + iRet = Tcl_GetDouble(pSics->pTcl, argv[3], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->fStep[1] = (float) dVal; + iRet = Tcl_GetDouble(pSics->pTcl, argv[4], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[4]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->fStep[2] = (float) dVal; + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "run") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (argc < 5) { + SCWrite(pCon, + "Insufficient number of arguments to hklscan run", eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iNP); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* interpret Mode */ + if (strcmp(argv[3], "timer") == 0) { + iMode = eTimer; + } else if (strcmp(argv[3], "monitor") == 0) { + iMode = ePreset; + } else { + sprintf(pBueffel, "ERROR: %s not recognized as valid counter mode", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* preset */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[4], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fPreset = (float) dVal; + iRet = Hklscan(self, pCon, iNP, iMode, fPreset); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } + sprintf(pBueffel, + "ERROR: %s not recognized as command word to hklscan", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; +} diff --git a/hklscan.h b/hklscan.h index d505030d..5f6457af 100644 --- a/hklscan.h +++ b/hklscan.h @@ -11,15 +11,15 @@ #ifndef HKLSCAN #define HKLSCAN - typedef struct __HKLSCAN *pHklscan; +typedef struct __HKLSCAN *pHklscan; /*--------------------------------------------------------------------------*/ - int HklScan(pHklscan self, SConnection *pCon, int iNP, int iMode, - float fPreset); +int HklScan(pHklscan self, SConnection * pCon, int iNP, int iMode, + float fPreset); /*---------------- interpreter functions -----------------------------------*/ - int HklscanFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int HklscanAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int HklscanFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int HklscanAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/hmcontrol.c b/hmcontrol.c index d3e5ddc3..f3d01c8a 100644 --- a/hmcontrol.c +++ b/hmcontrol.c @@ -25,188 +25,184 @@ static void *HMCGetInterface(void *pData, int ID) { pHMcontrol self = NULL; - self = (pHMcontrol)pData; + self = (pHMcontrol) pData; assert(self); - if(ID == COUNTID) + if (ID == COUNTID) return self->pCount; else return NULL; } + /*------------------------------------------------------------------------*/ static int HMCHalt(void *pData) { int i, retVal = OKOK, status; pHMcontrol self = NULL; - self = (pHMcontrol)pData; + self = (pHMcontrol) pData; assert(self); - for(i = 0; i < self->nSlaves; i++) - { + for (i = 0; i < self->nSlaves; i++) { status = self->slaves[i]->Halt(self->slaveData[i]); ReleaseCountLock(self->slaves[i]); - if(status != OKOK) + if (status != OKOK) retVal = status; } ReleaseCountLock(self->pCount); return retVal; } + /*-----------------------------------------------------------------------*/ -static int HMCStart(void *pData, SConnection *pCon) +static int HMCStart(void *pData, SConnection * pCon) { int i, status; pHMcontrol self = NULL; - self = (pHMcontrol)pData; + self = (pHMcontrol) pData; assert(self); - - if(!GetCountLock(self->pCount, pCon)){ - return HWFault; + + if (!GetCountLock(self->pCount, pCon)) { + return HWFault; } - - for(i = 0; i < self->nSlaves; i++) - { - ReleaseCountLock(self->slaves[i]); - status = self->slaves[i]->StartCount(self->slaveData[i],pCon); - if(status != OKOK) - { + + for (i = 0; i < self->nSlaves; i++) { + ReleaseCountLock(self->slaves[i]); + status = self->slaves[i]->StartCount(self->slaveData[i], pCon); + if (status != OKOK) { HMCHalt(self); return status; } } return OKOK; } + /*----------------------------------------------------------------------*/ -static int HMCStatus(void *pData, SConnection *pCon) +static int HMCStatus(void *pData, SConnection * pCon) { - int status,i; + int status, i; pHMcontrol self = NULL; - self = (pHMcontrol)pData; + self = (pHMcontrol) pData; assert(self); - status = self->slaves[0]->CheckCountStatus(self->slaveData[0],pCon); - if(status == HWIdle || status == HWFault) - { + status = self->slaves[0]->CheckCountStatus(self->slaveData[0], pCon); + if (status == HWIdle || status == HWFault) { /* - stop counting on slaves when finished or when an error - occurred. - */ - InvokeCallBack(self->pCall,COUNTEND,pCon); + stop counting on slaves when finished or when an error + occurred. + */ + InvokeCallBack(self->pCall, COUNTEND, pCon); HMCHalt(self); } /* - Warning: this assumes that salves 1 - MAXSLAVE are histogram memories. - If this assumption does not hold, change this code to check if this - is really a histogram memory. - */ - for(i = 1; i < MAXSLAVE; i++) - { - if(self->slaves[i] != NULL) - { - HistDirty((pHistMem)self->slaveData[i]); + Warning: this assumes that salves 1 - MAXSLAVE are histogram memories. + If this assumption does not hold, change this code to check if this + is really a histogram memory. + */ + for (i = 1; i < MAXSLAVE; i++) { + if (self->slaves[i] != NULL) { + HistDirty((pHistMem) self->slaveData[i]); } } return status; } + /*-------------------------------------------------------------------------*/ -static int HMCPause(void *pData, SConnection *pCon) +static int HMCPause(void *pData, SConnection * pCon) { int i, status; pHMcontrol self = NULL; - self = (pHMcontrol)pData; + self = (pHMcontrol) pData; assert(self); - for(i = 0; i < self->nSlaves; i++) - { - status = self->slaves[i]->Pause(self->slaveData[i],pCon); - if(status != OKOK) - { + for (i = 0; i < self->nSlaves; i++) { + status = self->slaves[i]->Pause(self->slaveData[i], pCon); + if (status != OKOK) { HMCHalt(self); return status; } } return OKOK; } + /*------------------------------------------------------------------------*/ -static int HMCContinue(void *pData, SConnection *pCon) +static int HMCContinue(void *pData, SConnection * pCon) { int i, status; pHMcontrol self = NULL; - self = (pHMcontrol)pData; + self = (pHMcontrol) pData; assert(self); - for(i = 0; i < self->nSlaves; i++) - { - status = self->slaves[i]->Continue(self->slaveData[i],pCon); - if(status != OKOK) - { + for (i = 0; i < self->nSlaves; i++) { + status = self->slaves[i]->Continue(self->slaveData[i], pCon); + if (status != OKOK) { HMCHalt(self); return status; } } return OKOK; } + /*----------------------------------------------------------------------*/ -static int HMCTransfer(void *pData, SConnection *pCon) +static int HMCTransfer(void *pData, SConnection * pCon) { int i, retVal = OKOK, status; pHMcontrol self = NULL; char pBueffel[132]; - self = (pHMcontrol)pData; + self = (pHMcontrol) pData; assert(self); - for(i = 0; i < self->nSlaves; i++) - { + for (i = 0; i < self->nSlaves; i++) { status = self->slaves[i]->TransferData(self->slaveData[i], pCon); - if(status != OKOK) - { + if (status != OKOK) { retVal = status; - sprintf(pBueffel,"WARNING: slave histogram %d failed to transfer data", - i); - SCWrite(pCon,pBueffel,eWarning); + sprintf(pBueffel, + "WARNING: slave histogram %d failed to transfer data", i); + SCWrite(pCon, pBueffel, eWarning); } } return retVal; } + /*-----------------------------------------------------------------------*/ -static void HMCParameter(void *pData, float fPreset, CounterMode eMode ) +static void HMCParameter(void *pData, float fPreset, CounterMode eMode) { int i; pHMcontrol self = NULL; - self = (pHMcontrol)pData; + self = (pHMcontrol) pData; assert(self); - for(i = 0; i < self->nSlaves; i++) - { + for (i = 0; i < self->nSlaves; i++) { self->slaves[i]->SetCountParameters(self->slaveData[i], fPreset, eMode); } } + /*----------------------------------------------------------------------*/ static void KillHMcontrol(void *pData) { pHMcontrol self; - self = (pHMcontrol)pData; - if(!self) + self = (pHMcontrol) pData; + if (!self) return; - if(self->pDes) + if (self->pDes) DeleteDescriptor(self->pDes); - if(self->pCount) + if (self->pCount) free(self->pCount); free(self); -} +} + /*-----------------------------------------------------------------------*/ -int MakeHMControl(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) +int MakeHMControl(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) { int i, status; pHMcontrol pNew = NULL; @@ -215,38 +211,36 @@ int MakeHMControl(SConnection *pCon, SicsInterp *pSics, pICountable pCount; /* - need at least two parameters - */ - if(argc < 3) - { - SCWrite(pCon,"ERROR: insufficient number of arguments to MakeHMControl", - eError); + need at least two parameters + */ + if (argc < 3) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to MakeHMControl", + eError); return 0; } /* allocate our data structure - */ - pNew = (pHMcontrol)malloc(sizeof(HMcontrol)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory in MakeHMControl",eError); + */ + pNew = (pHMcontrol) malloc(sizeof(HMcontrol)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory in MakeHMControl", eError); return 0; } - memset(pNew,0,sizeof(HMcontrol)); + memset(pNew, 0, sizeof(HMcontrol)); pNew->pDes = CreateDescriptor("HMcontrol"); pNew->pCount = CreateCountableInterface(); pNew->pCall = CreateCallBackInterface(); - if(!pNew->pDes || ! pNew->pCount) - { - SCWrite(pCon,"ERROR: out of memory in MakeHMControl",eError); + if (!pNew->pDes || !pNew->pCount) { + SCWrite(pCon, "ERROR: out of memory in MakeHMControl", eError); KillHMcontrol(pNew); return 0; } - + /* - assign interface functions - */ + assign interface functions + */ pNew->pDes->GetInterface = HMCGetInterface; pNew->pCount->Halt = HMCHalt; pNew->pCount->StartCount = HMCStart; @@ -257,25 +251,21 @@ int MakeHMControl(SConnection *pCon, SicsInterp *pSics, pNew->pCount->SetCountParameters = HMCParameter; /* - now loop through the remaining arguments, thereby entering them into - the slave list. - */ - for(i = 2; i < argc; i++) - { - pCom = FindCommand(pSics,argv[i]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: object %s not found in MakeHMcontrol", + now loop through the remaining arguments, thereby entering them into + the slave list. + */ + for (i = 2; i < argc; i++) { + pCom = FindCommand(pSics, argv[i]); + if (!pCom) { + sprintf(pBueffel, "ERROR: object %s not found in MakeHMcontrol", argv[i]); - SCWrite(pCon,pBueffel,eError); + SCWrite(pCon, pBueffel, eError); continue; } pCount = GetCountableInterface(pCom->pData); - if(!pCount) - { - sprintf(pBueffel,"ERROR: object %s is NOT countable", - argv[i]); - SCWrite(pCon,pBueffel,eError); + if (!pCount) { + sprintf(pBueffel, "ERROR: object %s is NOT countable", argv[i]); + SCWrite(pCon, pBueffel, eError); continue; } pNew->slaves[pNew->nSlaves] = pCount; @@ -284,25 +274,25 @@ int MakeHMControl(SConnection *pCon, SicsInterp *pSics, } /* - now install our action command and we are done - */ - status = AddCommand(pSics,argv[1],HMControlAction,KillHMcontrol, - pNew); - if(!status) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); + now install our action command and we are done + */ + status = AddCommand(pSics, argv[1], HMControlAction, KillHMcontrol, + pNew); + if (!status) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); KillHMcontrol(pNew); return 0; - } - + } + return 1; } + /*----------------------------------------------------------------------- Syntax: whatever start preset mode ------------------------------------------------------------------------*/ -int HMControlAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) +int HMControlAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) { pHMcontrol self; char pBueffel[132]; @@ -311,63 +301,53 @@ int HMControlAction(SConnection *pCon, SicsInterp *pSics, int status; /* - checks - */ - self = (pHMcontrol)pData; + checks + */ + self = (pHMcontrol) pData; assert(self); - if(argc < 4) - { - snprintf(pBueffel,131,"ERROR: Usage %s start preset mode", argv[0]); - SCWrite(pCon,pBueffel,eError); + if (argc < 4) { + snprintf(pBueffel, 131, "ERROR: Usage %s start preset mode", argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"start") == 0) - { - /* + if (strcmp(argv[1], "start") == 0) { + /* interpret count parameters */ - status = Tcl_GetDouble(pSics->pTcl,argv[2],&dPreset); - if(status != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - strtolower(argv[3]); - if(strcmp(argv[3],"timer") == 0) - eMode = eTimer; - else if(strcmp(argv[3],"monitor") == 0) - eMode = ePreset; - else - { - sprintf(pBueffel,"ERROR: %s is no recognized count mode",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } + status = Tcl_GetDouble(pSics->pTcl, argv[2], &dPreset); + if (status != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + strtolower(argv[3]); + if (strcmp(argv[3], "timer") == 0) + eMode = eTimer; + else if (strcmp(argv[3], "monitor") == 0) + eMode = ePreset; + else { + sprintf(pBueffel, "ERROR: %s is no recognized count mode", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } - /* + /* set count parameters and go */ - self->pCount->SetCountParameters(self,(float)dPreset,eMode); - status = StartDevice(pServ->pExecutor,"hmcontrol",self->pDes, - self,pCon,99); - if(!status) - { - SCWrite(pCon,"ERROR: failed to start counting",eError); - return 0; - } - InvokeCallBack(self->pCall,COUNTSTART,pCon); - SCSendOK(pCon); - } - else - { - SCWrite(pCon,"ERROR: subcommand not recognized",eError); - return 0; + self->pCount->SetCountParameters(self, (float) dPreset, eMode); + status = StartDevice(pServ->pExecutor, "hmcontrol", self->pDes, + self, pCon, 99); + if (!status) { + SCWrite(pCon, "ERROR: failed to start counting", eError); + return 0; + } + InvokeCallBack(self->pCall, COUNTSTART, pCon); + SCSendOK(pCon); + } else { + SCWrite(pCon, "ERROR: subcommand not recognized", eError); + return 0; } return 1; -} - - +} diff --git a/hmcontrol.h b/hmcontrol.h index e73f2a7a..2a14cf41 100644 --- a/hmcontrol.h +++ b/hmcontrol.h @@ -23,24 +23,23 @@ the maximum number of slaves #define MAXSLAVE 5 - typedef struct { - pObjectDescriptor pDes; - pICountable pCount; - pICountable slaves[MAXSLAVE]; - void *slaveData[MAXSLAVE]; - int nSlaves; - float fPreset; - CounterMode eMode; - pICallBack pCall; - } HMcontrol, *pHMcontrol; +typedef struct { + pObjectDescriptor pDes; + pICountable pCount; + pICountable slaves[MAXSLAVE]; + void *slaveData[MAXSLAVE]; + int nSlaves; + float fPreset; + CounterMode eMode; + pICallBack pCall; +} HMcontrol, *pHMcontrol; - int MakeHMControl(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - int HMControlAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int MakeHMControl(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); +int HMControlAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); #endif - diff --git a/hmdata.c b/hmdata.c index 627fae56..138c3aa4 100644 --- a/hmdata.c +++ b/hmdata.c @@ -23,217 +23,244 @@ #include "countdriv.h" #include "stptok.h" /*----------------------------------------------------------------------*/ -pHMdata makeHMData(void) { +pHMdata makeHMData(void) +{ pHMdata self = NULL; - self = (pHMdata)malloc(sizeof(HMdata)); - if(self == NULL){ + self = (pHMdata) malloc(sizeof(HMdata)); + if (self == NULL) { return NULL; } - memset(self,0,sizeof(HMdata)); + memset(self, 0, sizeof(HMdata)); self->nTimeChan = 1; self->updateFlag = 1; - + return self; } + /*---------------------------------------------------------------------*/ -void killHMData(pHMdata self){ - if(self->localBuffer != NULL){ +void killHMData(pHMdata self) +{ + if (self->localBuffer != NULL) { free(self->localBuffer); } free(self); } + /*---------------------------------------------------------------------*/ -void clearHMData(pHMdata self){ - long size; - int i; - size = 1; - for(i = 0; i < self->rank; i++){ - size *= self->iDim[i]; - } - if(self->tofMode){ - size *= getNoOfTimebins(self); - } - memset(self->localBuffer,0,size*sizeof(HistInt)); +void clearHMData(pHMdata self) +{ + long size; + int i; + size = 1; + for (i = 0; i < self->rank; i++) { + size *= self->iDim[i]; + } + if (self->tofMode) { + size *= getNoOfTimebins(self); + } + memset(self->localBuffer, 0, size * sizeof(HistInt)); } + /*----------------------------------------------------------------------*/ -int resizeBuffer(pHMdata self){ +int resizeBuffer(pHMdata self) +{ long size; int i; size = 1; - for(i = 0; i < self->rank; i++){ + for (i = 0; i < self->rank; i++) { size *= self->iDim[i]; } - if(self->tofMode){ + if (self->tofMode) { size *= getNoOfTimebins(self); } - if(self->localBuffer != NULL){ + if (self->localBuffer != NULL) { free(self->localBuffer); self->localBuffer = NULL; } - self->localBuffer = (HistInt *)malloc(size*sizeof(HistInt)); - if(!self->localBuffer){ + self->localBuffer = (HistInt *) malloc(size * sizeof(HistInt)); + if (!self->localBuffer) { return 0; } - memset(self->localBuffer,0,size*sizeof(HistInt)); + memset(self->localBuffer, 0, size * sizeof(HistInt)); self->updateFlag = 1; return 1; } + /*-----------------------------------------------------------------------*/ -int configureHMdata(pHMdata self, pStringDict pOpt, - SConnection *pCon){ +int configureHMdata(pHMdata self, pStringDict pOpt, SConnection * pCon) +{ int status, i; float fVal; char pValue[80]; pHistMem master = NULL; - if(self->nTimeChan > 2) { + if (self->nTimeChan > 2) { self->tofMode = 1; } else { self->tofMode = 0; } - status = StringDictGetAsNumber(pOpt,"rank",&fVal); - if(!status){ - SCWrite(pCon,"ERROR: critical configuration problem: no rank found", - eError); + status = StringDictGetAsNumber(pOpt, "rank", &fVal); + if (!status) { + SCWrite(pCon, "ERROR: critical configuration problem: no rank found", + eError); return 0; } - self->rank = (int)rint(fVal); + self->rank = (int) rint(fVal); - for(i = 0; i < self->rank; i++){ - sprintf(pValue,"dim%1.1d",i); - status = StringDictGetAsNumber(pOpt,pValue,&fVal); - if(!status){ - sprintf(pValue,"ERROR dimension %d not found!!", i); + for (i = 0; i < self->rank; i++) { + sprintf(pValue, "dim%1.1d", i); + status = StringDictGetAsNumber(pOpt, pValue, &fVal); + if (!status) { + sprintf(pValue, "ERROR dimension %d not found!!", i); return 0; } - self->iDim[i] = (int)rint(fVal); - } - - status = StringDictGetAsNumber(pOpt,"update",&fVal); - if(!status){ - self->updateIntervall = 0; /* no buffering */ - } else { - self->updateIntervall = (int)rint(fVal); + self->iDim[i] = (int) rint(fVal); } - status = StringDictGet(pOpt,"timeslave",pValue, 79); - if(status == 1) { - master = (pHistMem)FindCommandData(pServ->pSics,pValue,"HistMem"); - if(master == NULL){ - SCWrite(pCon,"ERROR: timeslave requested, but master HM not found", - eError); + status = StringDictGetAsNumber(pOpt, "update", &fVal); + if (!status) { + self->updateIntervall = 0; /* no buffering */ + } else { + self->updateIntervall = (int) rint(fVal); + } + + status = StringDictGet(pOpt, "timeslave", pValue, 79); + if (status == 1) { + master = (pHistMem) FindCommandData(pServ->pSics, pValue, "HistMem"); + if (master == NULL) { + SCWrite(pCon, "ERROR: timeslave requested, but master HM not found", + eError); } else { - self->timeslave = master->pDriv->data; - self->tofMode = 1; + self->timeslave = master->pDriv->data; + self->tofMode = 1; } - } + } /* - invalidate buffer - */ - if(self->localBuffer != NULL){ + invalidate buffer + */ + if (self->localBuffer != NULL) { free(self->localBuffer); self->localBuffer = NULL; } /* - note: remove update request in histmem.c - */ - if(self->updateIntervall > 0){ + note: remove update request in histmem.c + */ + if (self->updateIntervall > 0) { /* - we do buffer - */ + we do buffer + */ status = resizeBuffer(self); - if(!status){ - SCWrite(pCon,"ERROR: failed to resize buffer",eError); + if (!status) { + SCWrite(pCon, "ERROR: failed to resize buffer", eError); return 0; } } return 1; } + /*----------------------------------------------------------------------*/ -int genTimeBinning(pHMdata self, float start, float step, int noSteps){ +int genTimeBinning(pHMdata self, float start, float step, int noSteps) +{ int i; - if(noSteps >= MAXCHAN || self->timeslave != NULL){ + if (noSteps >= MAXCHAN || self->timeslave != NULL) { return 0; } - for(i = 0; i < noSteps; i++){ - self->timeBinning[i] = start + i*step; + for (i = 0; i < noSteps; i++) { + self->timeBinning[i] = start + i * step; } self->tofMode = 1; self->nTimeChan = noSteps; return resizeBuffer(self); } + /*----------------------------------------------------------------------*/ -int setTimeBin(pHMdata self, int index, float value){ - if(self->timeslave != NULL){ +int setTimeBin(pHMdata self, int index, float value) +{ + if (self->timeslave != NULL) { return 0; } - - if(index >= 0 && index < MAXCHAN){ + + if (index >= 0 && index < MAXCHAN) { self->timeBinning[index] = value; } else { return 0; } self->tofMode = 1; - if(index > self->nTimeChan){ - self->nTimeChan = index+1; + if (index > self->nTimeChan) { + self->nTimeChan = index + 1; return resizeBuffer(self); } return 1; } + /*-------------------------------------------------------------------*/ -int isInTOFMode(pHMdata self){ +int isInTOFMode(pHMdata self) +{ return self->tofMode; } + /*---------------------------------------------------------------------*/ -int getNoOfTimebins(pHMdata self){ - if(self->timeslave != NULL){ +int getNoOfTimebins(pHMdata self) +{ + if (self->timeslave != NULL) { return getNoOfTimebins(self->timeslave); - } else { - return self->nTimeChan; + } else { + return self->nTimeChan; } } + /*---------------------------------------------------------------------*/ -float *getTimeBinning(pHMdata self){ - if(self->timeslave != NULL){ +float *getTimeBinning(pHMdata self) +{ + if (self->timeslave != NULL) { return getTimeBinning(self->timeslave); - } else { - return self->timeBinning; + } else { + return self->timeBinning; } } + /*-------------------------------------------------------------------*/ -void clearTimeBinning(pHMdata self){ - if(self->timeslave == NULL){ - self->nTimeChan = 1; +void clearTimeBinning(pHMdata self) +{ + if (self->timeslave == NULL) { + self->nTimeChan = 1; self->tofMode = 0; resizeBuffer(self); } } + /*--------------------------------------------------------------------*/ -void getHMDataDim(pHMdata self, int iDim[MAXDIM], int *rank){ - memcpy(iDim,self->iDim,self->rank*sizeof(int)); +void getHMDataDim(pHMdata self, int iDim[MAXDIM], int *rank) +{ + memcpy(iDim, self->iDim, self->rank * sizeof(int)); *rank = self->rank; } + /*---------------------------------------------------------------------*/ -long getHMDataLength(pHMdata self){ +long getHMDataLength(pHMdata self) +{ long length = 1; int i; - for(i = 0; i < self->rank; i++){ + for (i = 0; i < self->rank; i++) { length *= self->iDim[i]; } - if(self->tofMode){ + if (self->tofMode) { length *= getNoOfTimebins(self); } return length; } + /*---------------------------------------------------------------------*/ -void updateHMData(pHMdata self){ +void updateHMData(pHMdata self) +{ self->updateFlag = 1; } + /*-------------------------------------------------------------------- The idea here is that upper level code sets the updateFlag through updateHMData (above) whenever the HM changes (counts). If this flag is set @@ -245,99 +272,105 @@ void updateHMData(pHMdata self){ to buffer all HM) use GetHistogramDirect (histogram.c) instead which acts on the driver level. --------------------------------------------------------------------------*/ -static int mustUpdate(pHMdata self){ - if(self->updateFlag == 1 && time(NULL) >= self->nextUpdate){ +static int mustUpdate(pHMdata self) +{ + if (self->updateFlag == 1 && time(NULL) >= self->nextUpdate) { return 1; } else { return 0; } } + /*---------------------------------------------------------------------*/ -static int updateHMbuffer(pHistMem hist, int bank, SConnection *pCon){ +static int updateHMbuffer(pHistMem hist, int bank, SConnection * pCon) +{ int status, iErr, i; char pError[80], pBueffel[256]; pHMdata self = hist->pDriv->data; assert(self); - if(self->timeslave != NULL){ + if (self->timeslave != NULL) { resizeBuffer(self); } - for(i = 0; i < 3; i++){ - status = hist->pDriv->GetHistogram(hist->pDriv,pCon, - bank,0,getHMDataLength(self), - self->localBuffer); - if(status == OKOK){ + for (i = 0; i < 3; i++) { + status = hist->pDriv->GetHistogram(hist->pDriv, pCon, + bank, 0, getHMDataLength(self), + self->localBuffer); + if (status == OKOK) { self->nextUpdate = time(NULL) + self->updateIntervall; self->updateFlag = 0; break; - } else{ - status = hist->pDriv->GetError(hist->pDriv,&iErr,pError,79); - sprintf(pBueffel,"ERROR: %s ",pError); - SCWrite(pCon,pBueffel,eError); - status = hist->pDriv->TryAndFixIt(hist->pDriv,iErr); - if(status == COTERM) { - return 0; - } + } else { + status = hist->pDriv->GetError(hist->pDriv, &iErr, pError, 79); + sprintf(pBueffel, "ERROR: %s ", pError); + SCWrite(pCon, pBueffel, eError); + status = hist->pDriv->TryAndFixIt(hist->pDriv, iErr); + if (status == COTERM) { + return 0; + } } } - if(status == OKOK){ + if (status == OKOK) { return 1; } else { return HWFault; } } + /*----------------------------------------------------------------------*/ -int getHMDataHistogram(pHistMem hist, SConnection *pCon, - int bank, int start, int length, - HistInt *lData){ +int getHMDataHistogram(pHistMem hist, SConnection * pCon, + int bank, int start, int length, HistInt * lData) +{ int status; pHMdata self = hist->pDriv->data; HistInt *lStart; assert(self); - if(self->localBuffer == NULL){ + if (self->localBuffer == NULL) { resizeBuffer(self); } /* - update buffer if necessary - */ - if(mustUpdate(self)){ - status = updateHMbuffer(hist,bank,pCon); - if(status != OKOK){ + update buffer if necessary + */ + if (mustUpdate(self)) { + status = updateHMbuffer(hist, bank, pCon); + if (status != OKOK) { return status; } } /* - copy buffered data to lData - */ + copy buffered data to lData + */ lStart = self->localBuffer + start; - if(start + length > getHMDataLength(self)){ + if (start + length > getHMDataLength(self)) { length = getHMDataLength(self) - start - 1; } - memcpy(lData,lStart,length*sizeof(HistInt)); + memcpy(lData, lStart, length * sizeof(HistInt)); return 1; } + /*-----------------------------------------------------------------------*/ -HistInt *getHMDataBufferPointer(pHistMem hist,SConnection *pCon){ +HistInt *getHMDataBufferPointer(pHistMem hist, SConnection * pCon) +{ int status; pHMdata self = hist->pDriv->data; assert(self); - if(self->localBuffer == NULL || self->timeslave != NULL){ + if (self->localBuffer == NULL || self->timeslave != NULL) { resizeBuffer(self); } /* - update buffer if necessary - */ - if(mustUpdate(self)){ - status = updateHMbuffer(hist,0,pCon); - if(status != OKOK){ + update buffer if necessary + */ + if (mustUpdate(self)) { + status = updateHMbuffer(hist, 0, pCon); + if (status != OKOK) { return NULL; } } @@ -345,23 +378,26 @@ HistInt *getHMDataBufferPointer(pHistMem hist,SConnection *pCon){ } /*------------------------------------------------------------------------*/ -static long SumRow(HistInt *iData, int iDataLength, int iStart, int iEnd){ - int i; - long lSum; +static long SumRow(HistInt * iData, int iDataLength, int iStart, int iEnd) +{ + int i; + long lSum; - if(iEnd > iDataLength){ - return -1; - } + if (iEnd > iDataLength) { + return -1; + } + + lSum = 0; + for (i = iStart; i < iEnd; i++) { + lSum += iData[i]; + } + return lSum; +} - lSum = 0; - for(i = iStart; i < iEnd; i++){ - lSum += iData[i]; - } - return lSum; - } /*--------------------------------------------------------------------------*/ -long sumHMDataRectangle(pHistMem hist, SConnection *pCon, - int iStart[MAXDIM], int iEnd[MAXDIM]) { +long sumHMDataRectangle(pHistMem hist, SConnection * pCon, + int iStart[MAXDIM], int iEnd[MAXDIM]) +{ HistInt *iData; pHMdata self = hist->pDriv->data; int i, iHistLength, status, iIndex, myrank; @@ -371,168 +407,171 @@ long sumHMDataRectangle(pHistMem hist, SConnection *pCon, assert(self); /* - error checking - */ + error checking + */ myrank = self->rank; - if(isInTOFMode(self)){ + if (isInTOFMode(self)) { self->iDim[self->rank] = getNoOfTimebins(self); myrank++; } - for(i = 0; i < myrank; i++){ - if( (iStart[i] < 0) || (iStart[i] > self->iDim[i]) ) { - sprintf(pBueffel,"ERROR: %d is out of data dimension range", - iStart[i]); - SCWrite(pCon,pBueffel,eError); - return -1; - } - if( (iEnd[i] < 0) || (iEnd[i] > self->iDim[i]) ){ - sprintf(pBueffel,"ERROR: %d is out of data dimension range", - iEnd[i]); - SCWrite(pCon,pBueffel,eError); - return -1; - } + for (i = 0; i < myrank; i++) { + if ((iStart[i] < 0) || (iStart[i] > self->iDim[i])) { + sprintf(pBueffel, "ERROR: %d is out of data dimension range", + iStart[i]); + SCWrite(pCon, pBueffel, eError); + return -1; + } + if ((iEnd[i] < 0) || (iEnd[i] > self->iDim[i])) { + sprintf(pBueffel, "ERROR: %d is out of data dimension range", + iEnd[i]); + SCWrite(pCon, pBueffel, eError); + return -1; + } } - - if(self->localBuffer == NULL){ + + if (self->localBuffer == NULL) { resizeBuffer(self); } /* - get an update of the HM if necessary - */ - if(mustUpdate(self)){ - status = updateHMbuffer(hist,0,pCon); - if(status != OKOK){ + get an update of the HM if necessary + */ + if (mustUpdate(self)) { + status = updateHMbuffer(hist, 0, pCon); + if (status != OKOK) { return -1; } } iHistLength = getHMDataLength(self); - /* actually sum */ - switch(myrank) - { - case 1: - lSum = SumRow(self->localBuffer, iHistLength, - iStart[0], iEnd[0]); - break; - case 2: - if(isInTOFMode(self)){ - lSum = 0; - for(i = iStart[0]; i < iEnd[0]; i++){ - iIndex = i*self->iDim[1]; - lRowSum = SumRow(self->localBuffer,iHistLength, - iIndex+iStart[1], iIndex+iEnd[1]); - lSum += lRowSum; - } - } else { - lSum = 0; - for(i = iStart[1]; i < iEnd[1]; i++){ - iIndex = i*self->iDim[0]; - lRowSum = SumRow(self->localBuffer,iHistLength, - iIndex+iStart[0], iIndex+iEnd[0]); - lSum += lRowSum; - } - } - break; - default: - sprintf(pBueffel, - "ERROR: summing in %d dimensions not yet implemented", - myrank); - SCWrite(pCon,pBueffel,eError); - return -1; - break; - } - if(lSum < 0){ - lSum = -lSum; + /* actually sum */ + switch (myrank) { + case 1: + lSum = SumRow(self->localBuffer, iHistLength, iStart[0], iEnd[0]); + break; + case 2: + if (isInTOFMode(self)) { + lSum = 0; + for (i = iStart[0]; i < iEnd[0]; i++) { + iIndex = i * self->iDim[1]; + lRowSum = SumRow(self->localBuffer, iHistLength, + iIndex + iStart[1], iIndex + iEnd[1]); + lSum += lRowSum; + } + } else { + lSum = 0; + for (i = iStart[1]; i < iEnd[1]; i++) { + iIndex = i * self->iDim[0]; + lRowSum = SumRow(self->localBuffer, iHistLength, + iIndex + iStart[0], iIndex + iEnd[0]); + lSum += lRowSum; + } } - return lSum; - } -/*--------------------------------------------------------------------------*/ -int loadHMData(pHMdata self, SConnection *pCon, char *filename){ - FILE *fd = NULL; - char buffer[1024], pNumber[80], *pPtr; - long i = 0, length; - HistInt *data = NULL; - - fd = fopen(filename,"r"); - if(fd == NULL){ - snprintf(buffer,1023,"ERROR: failed to open file %s", filename); - SCWrite(pCon,buffer,eError); - return 0; - } - length = getHMDataLength(self); - if(self->localBuffer == NULL || self->timeslave != NULL){ - resizeBuffer(self); - } - data = self->localBuffer; - if(data == NULL){ - SCWrite(pCon,"ERROR: failed to allocate HM", eError); - fclose(fd); - return 0; - } - while(i < length && fgets(buffer,1024,fd) != NULL){ - pPtr = buffer; - while(pPtr != NULL){ - pPtr = sicsNextNumber(pPtr,pNumber); - if(pPtr != NULL){ - data[i] = atoi(pNumber); - i++; - } - } - } - if(i < length-1){ - SCWrite(pCon,"WARNING: not enough data in file to fill HM",eWarning); - } - fclose(fd); - return 1; + break; + default: + sprintf(pBueffel, + "ERROR: summing in %d dimensions not yet implemented", myrank); + SCWrite(pCon, pBueffel, eError); + return -1; + break; + } + if (lSum < 0) { + lSum = -lSum; + } + return lSum; } + +/*--------------------------------------------------------------------------*/ +int loadHMData(pHMdata self, SConnection * pCon, char *filename) +{ + FILE *fd = NULL; + char buffer[1024], pNumber[80], *pPtr; + long i = 0, length; + HistInt *data = NULL; + + fd = fopen(filename, "r"); + if (fd == NULL) { + snprintf(buffer, 1023, "ERROR: failed to open file %s", filename); + SCWrite(pCon, buffer, eError); + return 0; + } + length = getHMDataLength(self); + if (self->localBuffer == NULL || self->timeslave != NULL) { + resizeBuffer(self); + } + data = self->localBuffer; + if (data == NULL) { + SCWrite(pCon, "ERROR: failed to allocate HM", eError); + fclose(fd); + return 0; + } + while (i < length && fgets(buffer, 1024, fd) != NULL) { + pPtr = buffer; + while (pPtr != NULL) { + pPtr = sicsNextNumber(pPtr, pNumber); + if (pPtr != NULL) { + data[i] = atoi(pNumber); + i++; + } + } + } + if (i < length - 1) { + SCWrite(pCon, "WARNING: not enough data in file to fill HM", eWarning); + } + fclose(fd); + return 1; +} + /*========================================================================== * subsampling was stolen from the SinqHTTP histogram memory code and * thus contains some additional indirections. * =========================================================================*/ -static pNXDS hmDataToNXDataset(pHMdata self){ - pNXDS result = NULL; - int i; - - result = malloc(sizeof(NXDS)); - if(result == NULL){ - return NULL; - } - memset(result,0,sizeof(NXDS)); - result->magic = MAGIC; - result->type = NX_INT32; - result->rank = self->rank; - if(isInTOFMode(self)){ - result->rank++; - } - result->dim = malloc(self->rank*sizeof(int)); - if(result->dim == NULL){ - free(result); - return NULL; - } - for(i = 0; i < self->rank; i++){ - result->dim[i] = self->iDim[i]; - } - if(isInTOFMode(self)){ - result->dim[result->rank-1] = getNoOfTimebins(self); - } - if(self->localBuffer == NULL){ - resizeBuffer(self); - } - result->u.iPtr = self->localBuffer; - return result; +static pNXDS hmDataToNXDataset(pHMdata self) +{ + pNXDS result = NULL; + int i; + + result = malloc(sizeof(NXDS)); + if (result == NULL) { + return NULL; + } + memset(result, 0, sizeof(NXDS)); + result->magic = MAGIC; + result->type = NX_INT32; + result->rank = self->rank; + if (isInTOFMode(self)) { + result->rank++; + } + result->dim = malloc(self->rank * sizeof(int)); + if (result->dim == NULL) { + free(result); + return NULL; + } + for (i = 0; i < self->rank; i++) { + result->dim[i] = self->iDim[i]; + } + if (isInTOFMode(self)) { + result->dim[result->rank - 1] = getNoOfTimebins(self); + } + if (self->localBuffer == NULL) { + resizeBuffer(self); + } + result->u.iPtr = self->localBuffer; + return result; } + /*---------------------------------------------------------------------------*/ -static pNXDS subSampleCommand(pNXDS source, char *command, - char *error, int errLen){ +static pNXDS subSampleCommand(pNXDS source, char *command, + char *error, int errLen) +{ int startDim[NX_MAXRANK], endDim[NX_MAXRANK]; int dim = 0, start = 0, i; char *pPtr = NULL, token[80]; - - pPtr = stptok(command,token,79,":\0"); - while((pPtr = stptok(pPtr,token,79,":\0")) != NULL){ - if(start == 0){ + + pPtr = stptok(command, token, 79, ":\0"); + while ((pPtr = stptok(pPtr, token, 79, ":\0")) != NULL) { + if (start == 0) { startDim[dim] = atoi(token); start = 1; } else { @@ -542,99 +581,112 @@ static pNXDS subSampleCommand(pNXDS source, char *command, } } - if(dim < source->rank - 1){ - strncpy(error,"ERROR: Not enough border values specified for subsampling",errLen); + if (dim < source->rank - 1) { + strncpy(error, + "ERROR: Not enough border values specified for subsampling", + errLen); return NULL; - } - for(i = 0; i < source->rank; i++){ - if(startDim[i] < 0 || startDim[i] >= source->dim[i]){ - snprintf(error,errLen,"ERROR: invalid start value %d for dimension %d", startDim[1], i); + } + for (i = 0; i < source->rank; i++) { + if (startDim[i] < 0 || startDim[i] >= source->dim[i]) { + snprintf(error, errLen, + "ERROR: invalid start value %d for dimension %d", + startDim[1], i); return NULL; } - if(endDim[i] < startDim[i] || endDim[i] >= source->dim[i]){ - snprintf(error,errLen,"ERROR: invalid end value %d for dimension %d", endDim[1], i); + if (endDim[i] < startDim[i] || endDim[i] >= source->dim[i]) { + snprintf(error, errLen, + "ERROR: invalid end value %d for dimension %d", endDim[1], + i); return NULL; } } - - return cutNXDataset(source,startDim,endDim); -} -/*-----------------------------------------------------------------------------*/ -static pNXDS sumCommand(pNXDS source, char *command, char *error, int errlen){ - int dimNo = -1, start = -1, end = -1; - char *pPtr = NULL; - char token[80]; - - pPtr = stptok(command,token,79,":\0"); - pPtr = stptok(pPtr,token,79,":\0"); - if(pPtr != NULL){ - dimNo = atoi(token); - } - pPtr = stptok(pPtr,token,79,":\0"); - if(pPtr != NULL){ - start = atoi(token); - } - pPtr = stptok(pPtr,token,79,":\0"); - if(pPtr != NULL){ - end = atoi(token); - } - if(dimNo < 0 || dimNo > source->rank - 1){ - snprintf(error,errlen,"ERROR: invalid dimension %d requestd to sum", dimNo); - return NULL; - } - if(end < 0 || end > source->dim[dimNo] || start < 0 || start > end){ - snprintf(error,errlen,"ERROR: invalid summing limits %d to %d requested", start,end); - return NULL; - } - - return sumNXDataset(source,dimNo, start, end); - } -/*--------------------------------------------------------------------------*/ -HistInt *subSample(pHMdata self, char *command, - char *error, int errLen){ - pNXDS source = NULL, start = NULL; - pNXDS result = NULL; - char *pPtr = NULL; - char subCommand[132]; - HistInt *data = NULL; - int length; - - start = hmDataToNXDataset(self); - if(start == NULL){ - strncpy(error,"Out-Of-Memory or no data while subsampling ", - errLen); - return NULL; - } - - source = start; - pPtr = command; - while((pPtr = stptok(pPtr,subCommand,131,";\0\r\n")) != NULL){ - if(strstr(subCommand,"sample") != NULL){ - result = subSampleCommand(source,subCommand,error, errLen); - } else if(strstr(subCommand,"sum") != NULL){ - result = sumCommand(source,subCommand,error, errLen); - } else { - strncpy(error,"ERROR: invalid subcommand to process requested",errLen); - return NULL; - } - if(result == NULL){ - return NULL; - } - if(source != start){ - dropNXDataset(source); - } - source = result; - } - length = getNXDatasetLength(result); - data = malloc((length+1)*sizeof(int)); - if(data == NULL){ - strncpy(error,"Out-Of-Mmeory in Subsample", errLen); - dropNXDataset(result); - return NULL; - } - data[0] = length; - memcpy(data+1,result->u.iPtr, length*sizeof(int)); - dropNXDataset(result); - return data; + return cutNXDataset(source, startDim, endDim); +} + +/*-----------------------------------------------------------------------------*/ +static pNXDS sumCommand(pNXDS source, char *command, char *error, + int errlen) +{ + int dimNo = -1, start = -1, end = -1; + char *pPtr = NULL; + char token[80]; + + pPtr = stptok(command, token, 79, ":\0"); + pPtr = stptok(pPtr, token, 79, ":\0"); + if (pPtr != NULL) { + dimNo = atoi(token); + } + pPtr = stptok(pPtr, token, 79, ":\0"); + if (pPtr != NULL) { + start = atoi(token); + } + pPtr = stptok(pPtr, token, 79, ":\0"); + if (pPtr != NULL) { + end = atoi(token); + } + if (dimNo < 0 || dimNo > source->rank - 1) { + snprintf(error, errlen, "ERROR: invalid dimension %d requestd to sum", + dimNo); + return NULL; + } + if (end < 0 || end > source->dim[dimNo] || start < 0 || start > end) { + snprintf(error, errlen, + "ERROR: invalid summing limits %d to %d requested", start, + end); + return NULL; + } + + return sumNXDataset(source, dimNo, start, end); +} + +/*--------------------------------------------------------------------------*/ +HistInt *subSample(pHMdata self, char *command, char *error, int errLen) +{ + pNXDS source = NULL, start = NULL; + pNXDS result = NULL; + char *pPtr = NULL; + char subCommand[132]; + HistInt *data = NULL; + int length; + + + start = hmDataToNXDataset(self); + if (start == NULL) { + strncpy(error, "Out-Of-Memory or no data while subsampling ", errLen); + return NULL; + } + + source = start; + pPtr = command; + while ((pPtr = stptok(pPtr, subCommand, 131, ";\0\r\n")) != NULL) { + if (strstr(subCommand, "sample") != NULL) { + result = subSampleCommand(source, subCommand, error, errLen); + } else if (strstr(subCommand, "sum") != NULL) { + result = sumCommand(source, subCommand, error, errLen); + } else { + strncpy(error, "ERROR: invalid subcommand to process requested", + errLen); + return NULL; + } + if (result == NULL) { + return NULL; + } + if (source != start) { + dropNXDataset(source); + } + source = result; + } + length = getNXDatasetLength(result); + data = malloc((length + 1) * sizeof(int)); + if (data == NULL) { + strncpy(error, "Out-Of-Mmeory in Subsample", errLen); + dropNXDataset(result); + return NULL; + } + data[0] = length; + memcpy(data + 1, result->u.iPtr, length * sizeof(int)); + dropNXDataset(result); + return data; } diff --git a/hmdata.h b/hmdata.h index ebacd051..108b0335 100644 --- a/hmdata.h +++ b/hmdata.h @@ -12,56 +12,51 @@ #include "sics.h" #include "HistMem.h" #include "stringdict.h" -#define MAXCHAN 16834 +#define MAXCHAN 16834 #define MAXDIM 3 - typedef struct __hmdata{ - int rank; - int iDim[MAXDIM]; - int nTimeChan; - float timeBinning[MAXCHAN]; - int tofMode; - time_t nextUpdate; - int updateIntervall; - int updateFlag; - HistInt *localBuffer; - struct __hmdata *timeslave; -} HMdata, *pHMdata; +typedef struct __hmdata { + int rank; + int iDim[MAXDIM]; + int nTimeChan; + float timeBinning[MAXCHAN]; + int tofMode; + time_t nextUpdate; + int updateIntervall; + int updateFlag; + HistInt *localBuffer; + struct __hmdata *timeslave; +} HMdata, *pHMdata; - pHMdata makeHMData(void); - void killHMData(pHMdata self); - void clearHMData(pHMdata self); - - int configureHMdata(pHMdata self, pStringDict pOpt, - SConnection *pCon); - int resizeBuffer(pHMdata self); - int genTimeBinning(pHMdata self, float start, float step, - int noSteps); - int setTimeBin(pHMdata self, int index, float value); +pHMdata makeHMData(void); +void killHMData(pHMdata self); +void clearHMData(pHMdata self); - int getNoOfTimebins(pHMdata self); - float *getTimeBinning(pHMdata self); - int isInTOFMode(pHMdata self); - void clearTimeBinning(pHMdata self); +int configureHMdata(pHMdata self, pStringDict pOpt, SConnection * pCon); +int resizeBuffer(pHMdata self); +int genTimeBinning(pHMdata self, float start, float step, int noSteps); +int setTimeBin(pHMdata self, int index, float value); - void getHMDataDim(pHMdata self, int iDIM[MAXDIM], int *rank); - long getHMDataLength(pHMdata self); +int getNoOfTimebins(pHMdata self); +float *getTimeBinning(pHMdata self); +int isInTOFMode(pHMdata self); +void clearTimeBinning(pHMdata self); - int getHMDataHistogram(pHistMem hist, SConnection *pCon, - int bank, int start, int length, - HistInt *lData); - void updateHMData(pHMdata self); - HistInt *getHMDataBufferPointer(pHistMem hist, SConnection *pCon); +void getHMDataDim(pHMdata self, int iDIM[MAXDIM], int *rank); +long getHMDataLength(pHMdata self); - long sumHMDataRectangle(pHistMem self, SConnection *pCon, - int start[MAXDIM], int end[MAXDIM]); - int loadHMData(pHMdata self, SConnection *pCon, char *filename); +int getHMDataHistogram(pHistMem hist, SConnection * pCon, + int bank, int start, int length, HistInt * lData); +void updateHMData(pHMdata self); +HistInt *getHMDataBufferPointer(pHistMem hist, SConnection * pCon); - HistInt *subSample(pHMdata self, char *command, - char *error, int errLen); +long sumHMDataRectangle(pHistMem self, SConnection * pCon, + int start[MAXDIM], int end[MAXDIM]); +int loadHMData(pHMdata self, SConnection * pCon, char *filename); + +HistInt *subSample(pHMdata self, char *command, char *error, int errLen); #endif - diff --git a/hmslave.c b/hmslave.c index 0a59538f..b728cdea 100644 --- a/hmslave.c +++ b/hmslave.c @@ -16,7 +16,7 @@ * copyright: see file COPYRIGHT * * Mark Koennecke, March 2007 - */ + */ #include #include #include @@ -27,267 +27,303 @@ #include typedef struct { - pHistMem master; - int bank; - }*HMSlave, sHMSlave; + pHistMem master; + int bank; +} *HMSlave, sHMSlave; /*------------------------------------------------------------------- Configures the HM from the options in pOpt and the HM data structure Returns 1 on success, 0 on failure ---------------------------------------------------------------------*/ -static int HMSlaveConfigure(pHistDriver self, SConnection *pCon, - pStringDict pOpt, SicsInterp *pSics){ - HMSlave pPriv = NULL; - char buffer[80], error[256]; - - pPriv =(HMSlave)self->pPriv; +static int HMSlaveConfigure(pHistDriver self, SConnection * pCon, + pStringDict pOpt, SicsInterp * pSics) +{ + HMSlave pPriv = NULL; + char buffer[80], error[256]; - if(StringDictGet(pOpt,"master",buffer, 79) == 1){ - pPriv->master = (pHistMem)FindCommandData(pServ->pSics,buffer,"HistMem"); - if(pPriv->master == NULL){ - snprintf(error,255,"ERROR: failed to find master HM %s", buffer); - SCWrite(pCon,error,eError); - return 0; - } - } else { - SCWrite(pCon,"ERROR: required configuration option master missing", - eError); - return 0; - } + pPriv = (HMSlave) self->pPriv; - if(StringDictGet(pOpt,"bank",buffer, 79) == 1){ - pPriv->bank = atoi(buffer); - } else { - SCWrite(pCon,"ERROR: required configuration option bank missing", - eError); - return 0; + if (StringDictGet(pOpt, "master", buffer, 79) == 1) { + pPriv->master = + (pHistMem) FindCommandData(pServ->pSics, buffer, "HistMem"); + if (pPriv->master == NULL) { + snprintf(error, 255, "ERROR: failed to find master HM %s", buffer); + SCWrite(pCon, error, eError); + return 0; } - - return 1; + } else { + SCWrite(pCon, "ERROR: required configuration option master missing", + eError); + return 0; + } + + if (StringDictGet(pOpt, "bank", buffer, 79) == 1) { + pPriv->bank = atoi(buffer); + } else { + SCWrite(pCon, "ERROR: required configuration option bank missing", + eError); + return 0; + } + + return 1; } + /*-------------------------------------------------------------------- Start histogramming, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int HMSlaveStart(pHistDriver self,SConnection *pCon){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - return 1; +static int HMSlaveStart(pHistDriver self, SConnection * pCon) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return 1; } + /*-------------------------------------------------------------------- Stops histogramming, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int HMSlaveHalt(pHistDriver self){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - return 1; +static int HMSlaveHalt(pHistDriver self) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return 1; } + /*-------------------------------------------------------------------- Checks histogramming status, Returns HWFault on failure, HWIdle when finished, HWBusy when counting ----------------------------------------------------------------------*/ -static int HMSlaveCountStatus(pHistDriver self,SConnection *pCon){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - return HWIdle; +static int HMSlaveCountStatus(pHistDriver self, SConnection * pCon) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return HWIdle; } + /*-------------------------------------------------------------------- Get info on error after last HWFault, returns 1 always. Puts an int error code into *code and errLen chars of error description into error ----------------------------------------------------------------------*/ -static int HMSlaveGetError(pHistDriver self,int *code, - char *error, int errLen){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - strncpy(error,"Weird status: slaves do not err..",errLen); - *code = -77; - return 1; +static int HMSlaveGetError(pHistDriver self, int *code, + char *error, int errLen) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + strncpy(error, "Weird status: slaves do not err..", errLen); + *code = -77; + return 1; } + /*-------------------------------------------------------------------- Try to fix the HM error in code. Returns COREDO when the last operation needs to be redone, COTERM when the error cannot be fixed. ----------------------------------------------------------------------*/ -static int HMSlaveFixIt(pHistDriver self,int code){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - return COTERM; +static int HMSlaveFixIt(pHistDriver self, int code) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return COTERM; } + /*-------------------------------------------------------------------- GetData reads updates the internal cache of monitor values from the hardware, Returns 1 or HWFault ----------------------------------------------------------------------*/ -static int HMSlaveGetData(pHistDriver self,SConnection *pCon){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - return 1; +static int HMSlaveGetData(pHistDriver self, SConnection * pCon) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return 1; } + /*-------------------------------------------------------------------- GetMonitor reads the monitor value i. Returns either the monitor value or -9999 if no such monitor exists or an error occurred ----------------------------------------------------------------------*/ -static long HMSlaveGetMonitor(pHistDriver self,int i, SConnection *pCon){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - return -9999; +static long HMSlaveGetMonitor(pHistDriver self, int i, SConnection * pCon) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return -9999; } + /*-------------------------------------------------------------------- GetTime reads the total counting time. Returns either the value or -9999.99 if no such value exists or an error occurred ----------------------------------------------------------------------*/ -static float HMSlaveGetTime(pHistDriver self,SConnection *pCon){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - return -9999.99; +static float HMSlaveGetTime(pHistDriver self, SConnection * pCon) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return -9999.99; } + /*-------------------------------------------------------------------- Pause histogramming, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int HMSlavePause(pHistDriver self,SConnection *pCon){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - return 1; +static int HMSlavePause(pHistDriver self, SConnection * pCon) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return 1; } + /*-------------------------------------------------------------------- Continue histogramming, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int HMSlaveContinue(pHistDriver self,SConnection *pCon){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - return 1; +static int HMSlaveContinue(pHistDriver self, SConnection * pCon) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return 1; } + /*-------------------------------------------------------------------- Free the data associated with the private data structure of the driver ----------------------------------------------------------------------*/ -static int HMSlaveFree(pHistDriver self){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - if(pPriv != NULL){ - free(pPriv); - } - self->pPriv = NULL; - return 1; +static int HMSlaveFree(pHistDriver self) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + if (pPriv != NULL) { + free(pPriv); + } + self->pPriv = NULL; + return 1; } + /*------------------------------------------------------------------- * fixTimebinning assures that our time binning dn the masters * time binning are the same. So that diemsnions are right * ------------------------------------------------------------------*/ - static int fixTimeBinning(pHistDriver self, SConnection *pCon){ - HMSlave pPriv = NULL; - - pPriv =(HMSlave)self->pPriv; - if(isInTOFMode(pPriv->master->pDriv->data) && - getNoOfTimebins(pPriv->master->pDriv->data) != - getNoOfTimebins(self->data)){ - self->data->tofMode = 1; - self->data->nTimeChan = getNoOfTimebins(pPriv->master->pDriv->data); - if(!resizeBuffer(self->data)) { - SCWrite(pCon, - "ERROR: out of memory allocating HMData for slave", - eError); - return 0; - } +static int fixTimeBinning(pHistDriver self, SConnection * pCon) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + if (isInTOFMode(pPriv->master->pDriv->data) && + getNoOfTimebins(pPriv->master->pDriv->data) != + getNoOfTimebins(self->data)) { + self->data->tofMode = 1; + self->data->nTimeChan = getNoOfTimebins(pPriv->master->pDriv->data); + if (!resizeBuffer(self->data)) { + SCWrite(pCon, + "ERROR: out of memory allocating HMData for slave", eError); + return 0; } - return 1; - } + } + return 1; +} + /*-------------------------------------------------------------------- Set The HM data or a subset of it. Returns HWFault or 1 ----------------------------------------------------------------------*/ static int HMSlaveSetHistogram(pHistDriver self, - SConnection *pCon, - int i, int iStart, int iEnd, HistInt *pData){ - HMSlave pPriv = NULL; - HistInt *start = NULL; - - pPriv =(HMSlave)self->pPriv; - if(fixTimeBinning(self,pCon) == 1){ - start = self->data->localBuffer + iStart; - memcpy(start,pData,(iEnd - iStart)*sizeof(HistInt)); - return 1; - } else { - return 0; - } + SConnection * pCon, + int i, int iStart, int iEnd, + HistInt * pData) +{ + HMSlave pPriv = NULL; + HistInt *start = NULL; + + pPriv = (HMSlave) self->pPriv; + if (fixTimeBinning(self, pCon) == 1) { + start = self->data->localBuffer + iStart; + memcpy(start, pData, (iEnd - iStart) * sizeof(HistInt)); + return 1; + } else { + return 0; + } } + /*-------------------------------------------------------------------- Set HM to a preset value, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int HMSlavePreset(pHistDriver self,SConnection *pCon, - HistInt value){ - HMSlave pPriv = NULL; - int i; - - pPriv =(HMSlave)self->pPriv; - if(fixTimeBinning(self,pCon) == 1){ - for(i = 0; i < getHMDataLength(self->data); i++){ - self->data->localBuffer[i] = value; - } - return 1; - } else { - return 0; +static int HMSlavePreset(pHistDriver self, SConnection * pCon, + HistInt value) +{ + HMSlave pPriv = NULL; + int i; + + pPriv = (HMSlave) self->pPriv; + if (fixTimeBinning(self, pCon) == 1) { + for (i = 0; i < getHMDataLength(self->data); i++) { + self->data->localBuffer[i] = value; } + return 1; + } else { + return 0; + } } + /*-------------------------------------------------------------------- get The HM data or a subset of it. Returns HWFault or 1 ----------------------------------------------------------------------*/ static int HMSlaveGetHistogram(pHistDriver self, - SConnection *pCon, - int i, int iStart, int iEnd, HistInt *pData){ - HMSlave pPriv = NULL; - - pPriv = (HMSlave)self->pPriv; - return pPriv->master->pDriv->GetHistogram(pPriv->master->pDriv, - pCon, pPriv->bank, iStart, iEnd, pData); + SConnection * pCon, + int i, int iStart, int iEnd, + HistInt * pData) +{ + HMSlave pPriv = NULL; + + pPriv = (HMSlave) self->pPriv; + return pPriv->master->pDriv->GetHistogram(pPriv->master->pDriv, + pCon, pPriv->bank, iStart, + iEnd, pData); } + /*-------------------------------------------------------------------- Make the HMDriver, returns a driver or NULL on failure ----------------------------------------------------------------------*/ -pHistDriver MakeHMSlaveHM(pStringDict pOption){ - pHistDriver pNew = NULL; - HMSlave pPriv = NULL; +pHistDriver MakeHMSlaveHM(pStringDict pOption) +{ + pHistDriver pNew = NULL; + HMSlave pPriv = NULL; - /* create the general driver */ - pNew = CreateHistDriver(pOption); - if(!pNew){ - return NULL; - } + /* create the general driver */ + pNew = CreateHistDriver(pOption); + if (!pNew) { + return NULL; + } - /*Create private data structure*/ - pPriv = (HMSlave)malloc(sizeof(sHMSlave)); - if(pPriv == NULL){ - return NULL; - } - pNew->pPriv = pPriv; - - /* add our options */ - StringDictAddPair(pOption,"master","unknown"); - StringDictAddPair(pOption,"bank","1"); + /*Create private data structure */ + pPriv = (HMSlave) malloc(sizeof(sHMSlave)); + if (pPriv == NULL) { + return NULL; + } + pNew->pPriv = pPriv; - /* configure all those functions */ - pNew->Configure = HMSlaveConfigure; - pNew->Start = HMSlaveStart; - pNew->Halt = HMSlaveHalt; - pNew->GetCountStatus = HMSlaveCountStatus; - pNew->GetError = HMSlaveGetError; - pNew->TryAndFixIt = HMSlaveFixIt; - pNew->GetData = HMSlaveGetData; - pNew->GetHistogram = HMSlaveGetHistogram; - pNew->SetHistogram = HMSlaveSetHistogram; - pNew->GetMonitor = HMSlaveGetMonitor; - pNew->GetTime = HMSlaveGetTime; - pNew->Preset = HMSlavePreset; - pNew->FreePrivate = HMSlaveFree; - pNew->Pause = HMSlavePause; - pNew->Continue = HMSlaveContinue; + /* add our options */ + StringDictAddPair(pOption, "master", "unknown"); + StringDictAddPair(pOption, "bank", "1"); - return pNew; + /* configure all those functions */ + pNew->Configure = HMSlaveConfigure; + pNew->Start = HMSlaveStart; + pNew->Halt = HMSlaveHalt; + pNew->GetCountStatus = HMSlaveCountStatus; + pNew->GetError = HMSlaveGetError; + pNew->TryAndFixIt = HMSlaveFixIt; + pNew->GetData = HMSlaveGetData; + pNew->GetHistogram = HMSlaveGetHistogram; + pNew->SetHistogram = HMSlaveSetHistogram; + pNew->GetMonitor = HMSlaveGetMonitor; + pNew->GetTime = HMSlaveGetTime; + pNew->Preset = HMSlavePreset; + pNew->FreePrivate = HMSlaveFree; + pNew->Pause = HMSlavePause; + pNew->Continue = HMSlaveContinue; + + return pNew; } diff --git a/ifile.c b/ifile.c index 04640f5e..493b33e5 100644 --- a/ifile.c +++ b/ifile.c @@ -47,204 +47,196 @@ /*====================== Locals ============================================*/ - static IPair *CreateNewEntry(char *name, char *val, IPair *pN) - { - IPair *pRes = NULL; - - pRes = (IPair *)malloc(sizeof(IPair)); - if(!pRes) - return NULL; - memset(pRes,0,sizeof(IPair)); - if(name) - pRes->name = strdup(name); - if(val) - pRes->value = strdup(val); - pRes->pNext = pN; - return pRes; - } +static IPair *CreateNewEntry(char *name, char *val, IPair * pN) +{ + IPair *pRes = NULL; + + pRes = (IPair *) malloc(sizeof(IPair)); + if (!pRes) + return NULL; + memset(pRes, 0, sizeof(IPair)); + if (name) + pRes->name = strdup(name); + if (val) + pRes->value = strdup(val); + pRes->pNext = pN; + return pRes; +} + /*--------------------------------------------------------------------------*/ - static void RemoveWhiteSpace(char *pText) - { - int i, ii, i3; - char *pPtr; - - assert(pText); - - /* find start */ - i = 0; - while(isspace(pText[i])) - { - i++; - } - - /* find end */ - ii = strlen(pText); +static void RemoveWhiteSpace(char *pText) +{ + int i, ii, i3; + char *pPtr; + + assert(pText); + + /* find start */ + i = 0; + while (isspace(pText[i])) { + i++; + } + + /* find end */ + ii = strlen(pText); + ii--; + while ((isspace(pText[ii])) || (pText[ii] == '\n')) { ii--; - while( (isspace(pText[ii])) || (pText[ii] == '\n') ) - { - ii--; - } - - /* copy it */ - pPtr = pText; - for(i3 = i; i3 < (ii+1); i3++) - { - *pPtr = pText[i3]; - pPtr++; - } - *pPtr = '\0'; - } + } + + /* copy it */ + pPtr = pText; + for (i3 = i; i3 < (ii + 1); i3++) { + *pPtr = pText[i3]; + pPtr++; + } + *pPtr = '\0'; +} + /*===========================================================================*/ - IPair *IFReadConfigFile(FILE *fd) - { - IPair *pList = NULL; - char pBueffel[256]; - char pName[132]; - char pValue[132]; - char *pPos; - int iLen; - - assert(fd); - - while(!feof(fd)) - { - fgets(pBueffel,255,fd); - if(feof(fd)) - continue; +IPair *IFReadConfigFile(FILE * fd) +{ + IPair *pList = NULL; + char pBueffel[256]; + char pName[132]; + char pValue[132]; + char *pPos; + int iLen; - pPos = strchr(pBueffel,'='); - if(!pPos) - continue; - if(pBueffel[0] == '#') - continue; - - iLen = pPos - pBueffel; - strncpy(pName,pBueffel,iLen); - pName[iLen] = '\0'; - strcpy(pValue,(pPos+1)); - RemoveWhiteSpace(pName); - RemoveWhiteSpace(pValue); - pList = CreateNewEntry(pName,pValue,pList); - if(!pList) - return NULL; - } - return pList; - } -/*--------------------------------------------------------------------------*/ - char *IFindOption(IPair *pList, char *name) - { - IPair *pCurrent; - - if(!pList) - { - return NULL; - } - - pCurrent = pList; - while(pCurrent) - { - if(strcmp(name,pCurrent->name) == 0) - return pCurrent->value; - pCurrent = pCurrent->pNext; - } - return NULL; - } -/*--------------------------------------------------------------------------*/ - IPair *IFAddOption(IPair *pList,char *name, char *value) - { - return CreateNewEntry(name,value,pList); + assert(fd); + + while (!feof(fd)) { + fgets(pBueffel, 255, fd); + if (feof(fd)) + continue; + + pPos = strchr(pBueffel, '='); + if (!pPos) + continue; + if (pBueffel[0] == '#') + continue; + + iLen = pPos - pBueffel; + strncpy(pName, pBueffel, iLen); + pName[iLen] = '\0'; + strcpy(pValue, (pPos + 1)); + RemoveWhiteSpace(pName); + RemoveWhiteSpace(pValue); + pList = CreateNewEntry(pName, pValue, pList); + if (!pList) + return NULL; } + return pList; +} /*--------------------------------------------------------------------------*/ - IPair *IFSetOption(IPair *pList,char *name, char *value) - { - IPair *pCurrent; - if(NULL!=pList) - { - pCurrent = pList; - while((NULL!=pCurrent) && (0!=strcmp(name,pCurrent->name))) - { - pCurrent = pCurrent->pNext; - } - if(NULL!=pCurrent) - { /* replace value */ - free(pCurrent->value); - pCurrent->value = strdup(value); - return pCurrent; - } +char *IFindOption(IPair * pList, char *name) +{ + IPair *pCurrent; + + if (!pList) { + return NULL; + } + + pCurrent = pList; + while (pCurrent) { + if (strcmp(name, pCurrent->name) == 0) + return pCurrent->value; + pCurrent = pCurrent->pNext; + } + return NULL; +} + +/*--------------------------------------------------------------------------*/ +IPair *IFAddOption(IPair * pList, char *name, char *value) +{ + return CreateNewEntry(name, value, pList); +} + +/*--------------------------------------------------------------------------*/ +IPair *IFSetOption(IPair * pList, char *name, char *value) +{ + IPair *pCurrent; + if (NULL != pList) { + pCurrent = pList; + while ((NULL != pCurrent) && (0 != strcmp(name, pCurrent->name))) { + pCurrent = pCurrent->pNext; + } + if (NULL != pCurrent) { /* replace value */ + free(pCurrent->value); + pCurrent->value = strdup(value); + return pCurrent; } - return CreateNewEntry(name,value,pList); } + return CreateNewEntry(name, value, pList); +} /*-------------------------------------------------------------------------*/ - int IFSaveOptions(IPair *pList,FILE *fd) - { - IPair *pCurrent; - - assert(fd); - assert(pList); - - pCurrent = pList; - while(pCurrent) - { - fprintf(fd,"%s = %s \n", pCurrent->name, pCurrent->value); - pCurrent = pCurrent->pNext; - } - return 1; - } +int IFSaveOptions(IPair * pList, FILE * fd) +{ + IPair *pCurrent; + + assert(fd); + assert(pList); + + pCurrent = pList; + while (pCurrent) { + fprintf(fd, "%s = %s \n", pCurrent->name, pCurrent->value); + pCurrent = pCurrent->pNext; + } + return 1; +} + /*--------------------------------------------------------------------------*/ - void IFDeleteOptions(IPair *pList) - { - IPair *pCurrent, *pTemp; - - pCurrent = pList; - while(pCurrent) - { - pTemp = pCurrent->pNext; - if(pCurrent->name) - { - free(pCurrent->name); - } - if(pCurrent->value) - { - free(pCurrent->value); - } - free(pCurrent); - pCurrent = pTemp; +void IFDeleteOptions(IPair * pList) +{ + IPair *pCurrent, *pTemp; + + pCurrent = pList; + while (pCurrent) { + pTemp = pCurrent->pNext; + if (pCurrent->name) { + free(pCurrent->name); } + if (pCurrent->value) { + free(pCurrent->value); + } + free(pCurrent); + pCurrent = pTemp; } +} + /*=========================================================================== Testcode: Define MAIN to activate it. Needs a file test.txt as input */ #ifdef MAIN - int main(int argc, char *argv[]) - { - FILE *fd; - IPair *pList = NULL; - char *pPos = NULL; - - fd = fopen("test.txt","r"); - if(!fd) - exit(2); - - - pList = IFReadConfigFile(fd); - if(!pList) - exit(2); - fclose(fd); - - pPos = IFindOption(pList,"Gabi"); - if(pPos) - puts(pPos); - - fd = fopen("lala.txt","w"); - IFSaveOptions(pList,fd); - IFDeleteOptions(pList); - - } -#endif +int main(int argc, char *argv[]) +{ + FILE *fd; + IPair *pList = NULL; + char *pPos = NULL; + fd = fopen("test.txt", "r"); + if (!fd) + exit(2); + + + pList = IFReadConfigFile(fd); + if (!pList) + exit(2); + fclose(fd); + + pPos = IFindOption(pList, "Gabi"); + if (pPos) + puts(pPos); + + fd = fopen("lala.txt", "w"); + IFSaveOptions(pList, fd); + IFDeleteOptions(pList); + +} +#endif diff --git a/ifile.h b/ifile.h index 69b3d819..78389086 100644 --- a/ifile.h +++ b/ifile.h @@ -13,22 +13,21 @@ #define MKIFILE #include -typedef struct __IFileE - { - char *name; - char *value; - struct __IFileE *pNext; - } IPair; - - IPair *IFReadConfigFile(FILE *fp); - char *IFindOption(IPair *pList,char *name); +typedef struct __IFileE { + char *name; + char *value; + struct __IFileE *pNext; +} IPair; + +IPair *IFReadConfigFile(FILE * fp); +char *IFindOption(IPair * pList, char *name); /* returns a value for a name - */ - IPair *IFAddOption(IPair *pList,char *name, char *value); - IPair *IFSetOption(IPair *pList,char *name, char *value); - - int IFSaveOptions(IPair *pList,FILE *fp); - void IFDeleteOptions(IPair *pList); - - extern IPair *pSICSOptions; + */ +IPair *IFAddOption(IPair * pList, char *name, char *value); +IPair *IFSetOption(IPair * pList, char *name, char *value); + +int IFSaveOptions(IPair * pList, FILE * fp); +void IFDeleteOptions(IPair * pList); + +extern IPair *pSICSOptions; #endif diff --git a/init8.c b/init8.c index 0f022f37..8c4ae857 100644 --- a/init8.c +++ b/init8.c @@ -1,293 +1,293 @@ #include -static char init_tcl[] = -"# init.tcl --\n#\n# Default system startup file for Tcl-based appli" -"cations. Defines\n# \"unknown\" procedure and auto-load facilities." -"\n#\n# SCCS: @(#) init.tcl 1.66 96/10/06 14:29:28\n#\n# Copyright (c)" -" 1991-1993 The Regents of the University of California.\n# Copyrig" -"ht (c) 1994-1996 Sun Microsystems, Inc.\n#\n# See the file \"license" -".terms\" for information on usage and redistribution\n# of this fil" -"e, and for a DISCLAIMER OF ALL WARRANTIES.\n#\n#-------------------" -"---------------------------------------------------------\n#\n# Mod" -"ified by Mark Koennecke in order to redirect unknown into the Sic" -"s\n# mechanism. Thereby disabling command shortcuts and execution " -"of shell\n# commands for security reasons.\n#\n# February 1997\n# Hac" -"ked for Tcl 8.0 September 1997, bad hack if problems start anew\n#" -"\n#---------------------------------------------------------------" -"------------\n \nif {[info commands package] == \"\"} {\n error \"ve" -"rsion mismatch: library\\nscripts expect Tcl version 7.5b1 or late" -"r but the loaded version is\\nonly [info patchlevel]\"\n}\npackage re" -"quire -exact Tcl 8.0\n#if [catch {set auto_path $env(TCLLIBPATH)}]" -" {\n# set auto_path \"\"\n#}\nif {[lsearch -exact $auto_path [info " -"library]] < 0} {\n lappend auto_path [info library]\n}\ncatch {\n " -" foreach dir $tcl_pkgPath {\n\tif {[lsearch -exact $auto_path $di" -"r] < 0} {\n\t lappend auto_path $dir\n\t}\n }\n unset dir\n}\npa" -"ckage unknown tclPkgUnknown\n\n# Some machines, such as the Macinto" -"sh, do not have exec. Also, on all\n# platforms, safe interpreters" -" do not have exec.\n# exec hereby disabled for Security reasons! M" -"K\n set auto_noexec 1\n\n\nset errorCode \"\"\nset errorInfo \"\"\n\n# un" -"known --\n# This procedure is called when a Tcl command is invoked" -" that doesn't\n# exist in the interpreter. It takes the following" -" steps to make the\n# command available:\n#\n#\t1. See if the autoloa" -"d facility can locate the command in a\n#\t Tcl script file. If " -"so, load it and execute it.\n#\t2. If the command was invoked inter" -"actively at top-level:\n#\t (a) see if the command exists as an " -"executable UNIX program.\n#\t\tIf so, \"exec\" the command.\n#\t (b) " -"see if the command requests csh-like history substitution\n#\t\tin o" -"ne of the common forms !!, !, or ^old^new. If\n#\t\tso, emu" -"late csh's history substitution.\n#\t (c) see if the command is " -"a unique abbreviation for another\n#\t\tcommand. If so, invoke the " -"command.\n#\n# Arguments:\n# args -\tA list whose elements are the wo" -"rds of the original\n#\t\tcommand, including the command name.\n\nproc" -" unknown args {\n global auto_noexec auto_noload env unknown_pe" -"nding tcl_interactive\n global errorCode errorInfo\n\n # Save " -"the values of errorCode and errorInfo variables, since they\n #" -" may get modified if caught errors occur below. The variables wi" -"ll\n # be restored just before re-executing the missing command" -".\n\n set savedErrorCode $errorCode\n set savedErrorInfo $erro" -"rInfo\n set name [lindex $args 0]\n if ![info exists auto_nol" -"oad] {\n\t#\n\t# Make sure we're not trying to load the same proc twi" -"ce.\n\t#\n\tif [info exists unknown_pending($name)] {\n\t return -co" -"de error \"self-referential recursion in \\\"unknown\\\" for command \\" -"\"$name\\\"\";\n\t}\n\tset unknown_pending($name) pending;\n\tset ret [catc" -"h {auto_load $name} msg]\n\tunset unknown_pending($name);\n\tif {$ret" -" != 0} {\n\t return -code $ret -errorcode $errorCode \\\n\t\t\"error " -"while autoloading \\\"$name\\\": $msg\"\n\t}\n\tif ![array size unknown_pe" -"nding] {\n\t unset unknown_pending\n\t}\n\tif $msg {\n\t set errorC" -"ode $savedErrorCode\n\t set errorInfo $savedErrorInfo\n\t set c" -"ode [catch {uplevel $args} msg]\n\t if {$code == 1} {\n\t\t#\n\t\t# S" -"trip the last five lines off the error stack (they're\n\t\t# from th" -"e \"uplevel\" command).\n\t\t#\n\n\t\tset new [split $errorInfo \\n]\n\t\tset " -"new [join [lrange $new 0 [expr [llength $new] - 6]] \\n]\n\t\treturn " -"-code error -errorcode $errorCode \\\n\t\t\t-errorinfo $new $msg\n\t " -"} else {\n\t\treturn -code $code $msg\n\t }\n\t}\n }\n \n # Try" -" running SICS for a change\n set ret [catch {uplevel #0 SicsUnk" -"nown $args} msg]\n if {$ret == 1} {\n return -code error " -"$msg\n } else {\n return -code ok $msg\n }\n}\n\n# auto_lo" -"ad --\n# Checks a collection of library directories to see if a pr" -"ocedure\n# is defined in one of them. If so, it sources the appro" -"priate\n# library file to create the procedure. Returns 1 if it s" -"uccessfully\n# loaded the procedure, 0 otherwise.\n#\n# Arguments: \n" -"# cmd -\t\t\tName of the command to find and load.\n\nproc auto_load c" -"md {\n global auto_index auto_oldpath auto_path env errorInfo e" -"rrorCode\n\n if [info exists auto_index($cmd)] {\n\tuplevel #0 $au" -"to_index($cmd)\n\treturn [expr {[info commands $cmd] != \"\"}]\n }\n" -" if ![info exists auto_path] {\n\treturn 0\n }\n if [info ex" -"ists auto_oldpath] {\n\tif {$auto_oldpath == $auto_path} {\n\t ret" -"urn 0\n\t}\n }\n set auto_oldpath $auto_path\n for {set i [ex" -"pr [llength $auto_path] - 1]} {$i >= 0} {incr i -1} {\n\tset dir [l" -"index $auto_path $i]\n\tset f \"\"\n\tif [catch {set f [open [file join" -" $dir tclIndex]]}] {\n\t continue\n\t}\n\tset error [catch {\n\t se" -"t id [gets $f]\n\t if {$id == \"# Tcl autoload index file, versio" -"n 2.0\"} {\n\t\teval [read $f]\n\t } elseif {$id == \"# Tcl autoload " -"index file: each line identifies a Tcl\"} {\n\t\twhile {[gets $f line" -"] >= 0} {\n\t\t if {([string index $line 0] == \"#\")\n\t\t\t || ([l" -"length $line] != 2)} {\n\t\t\tcontinue\n\t\t }\n\t\t set name [lindex" -" $line 0]\n\t\t set auto_index($name) \\\n\t\t\t\"source [file join $di" -"r [lindex $line 1]]\"\n\t\t}\n\t } else {\n\t\terror \"[file join $dir t" -"clIndex] isn't a proper Tcl index file\"\n\t }\n\t} msg]\n\tif {$f !=" -" \"\"} {\n\t close $f\n\t}\n\tif $error {\n\t error $msg $errorInfo $" -"errorCode\n\t}\n }\n if [info exists auto_index($cmd)] {\n\tuplev" -"el #0 $auto_index($cmd)\n\tif {[info commands $cmd] != \"\"} {\n\t r" -"eturn 1\n\t}\n }\n return 0\n}\n\nif {[string compare $tcl_platfor" -"m(platform) windows] == 0} {\n\n# auto_execok --\n#\n# Returns string" -" that indicates name of program to execute if \n# name corresponds" -" to a shell builtin or an executable in the\n# Windows search path" -", or \"\" otherwise. Builds an associative \n# array auto_execs tha" -"t caches information about previous checks, \n# for speed.\n#\n# Arg" -"uments: \n# name -\t\t\tName of a command.\n\n# Windows version.\n#\n# No" -"te that info executable doesn't work under Windows, so we have to" -"\n# look for files with .exe, .com, or .bat extensions. Also, the" -" path\n# may be in the Path or PATH environment variables, and pat" -"h\n# components are separated with semicolons, not colons as under" -" Unix.\n#\nproc auto_execok name {\n global auto_execs env tcl_pl" -"atform\n\n if [info exists auto_execs($name)] {\n\treturn $auto_ex" -"ecs($name)\n }\n set auto_execs($name) \"\"\n\n if {[lsearch -" -"exact {cls copy date del erase dir echo mkdir md rename \n\t ren" -" rmdir rd time type ver vol} $name] != -1} {\n\tif {[info exists en" -"v(COMSPEC)]} {\n\t set comspec $env(COMSPEC) \n\t} elseif {[info e" -"xists env(ComSpec)]} {\n\t set comspec $env(ComSpec)\n\t} elseif {" -"$tcl_platform(os) == \"Windows NT\"} {\n\t set comspec \"cmd.exe\"\n\t" -"} else {\n\t set comspec \"command.com\"\n\t}\n\treturn [set auto_exec" -"s($name) [list $comspec /c $name]]\n }\n\n if {[llength [file " -"split $name]] != 1} {\n\tforeach ext {{} .com .exe .bat} {\n\t set" -" file ${name}${ext}\n\t if {[file exists $file] && ![file isdire" -"ctory $file]} {\n\t\treturn [set auto_execs($name) $file]\n\t }\n\t}\n" -"\treturn \"\"\n }\n\n set path \"[file dirname [info nameof]];.;\"\n" -" if {[info exists env(WINDIR)]} {\n\tset windir $env(WINDIR) \n " -" } elseif {[info exists env(windir)]} {\n\tset windir $env(windir)" -"\n }\n if {[info exists windir]} {\n\tif {$tcl_platform(os) == " -"\"Windows NT\"} {\n\t append path \"$windir/system32;\"\n\t}\n\tappend p" -"ath \"$windir/system;$windir;\"\n }\n\n if {! [info exists env(P" -"ATH)]} {\n\tif [info exists env(Path)] {\n\t append path $env(Path" -")\n\t} else {\n\t return \"\"\n\t}\n } else {\n\tappend path $env(PATH" -")\n }\n\n foreach dir [split $path {;}] {\n\tif {$dir == \"\"} {\n\t" -" set dir .\n\t}\n\tforeach ext {{} .com .exe .bat} {\n\t set file" -" [file join $dir ${name}${ext}]\n\t if {[file exists $file] && !" -"[file isdirectory $file]} {\n\t\treturn [set auto_execs($name) $file" -"]\n\t }\n\t}\n }\n return \"\"\n}\n\n} else {\n\n# auto_execok --\n#\n#" -" Returns string that indicates name of program to execute if \n# n" -"ame corresponds to an executable in the path. Builds an associati" -"ve \n# array auto_execs that caches information about previous che" -"cks, \n# for speed.\n#\n# Arguments: \n# name -\t\t\tName of a command.\n" -"\n# Unix version.\n#\nproc auto_execok name {\n global auto_execs " -"env\n\n if [info exists auto_execs($name)] {\n\treturn $auto_execs" -"($name)\n }\n set auto_execs($name) \"\"\n if {[llength [file" -" split $name]] != 1} {\n\tif {[file executable $name] && ![file isd" -"irectory $name]} {\n\t set auto_execs($name) $name\n\t}\n\treturn $a" -"uto_execs($name)\n }\n foreach dir [split $env(PATH) :] {\n\tif" -" {$dir == \"\"} {\n\t set dir .\n\t}\n\tset file [file join $dir $name" -"]\n\tif {[file executable $file] && ![file isdirectory $file]} {\n\t " -" set auto_execs($name) $file\n\t return $file\n\t}\n }\n ret" -"urn \"\"\n}\n\n}\n# auto_reset --\n# Destroy all cached information for " -"auto-loading and auto-execution,\n# so that the information gets r" -"ecomputed the next time it's needed.\n# Also delete any procedures" -" that are listed in the auto-load index\n# except those defined in" -" this file.\n#\n# Arguments: \n# None.\n\nproc auto_reset {} {\n glo" -"bal auto_execs auto_index auto_oldpath\n foreach p [info procs]" -" {\n\tif {[info exists auto_index($p)] && ![string match auto_* $p]" -"\n\t\t&& ([lsearch -exact {unknown pkg_mkIndex tclPkgSetup\n\t\t\ttclPkg" -"Unknown} $p] < 0)} {\n\t rename $p {}\n\t}\n }\n catch {unset " -"auto_execs}\n catch {unset auto_index}\n catch {unset auto_ol" -"dpath}\n}\n\n# auto_mkindex --\n# Regenerate a tclIndex file from Tcl" -" source files. Takes as argument\n# the name of the directory in " -"which the tclIndex file is to be placed,\n# followed by any number" -" of glob patterns to use in that directory to\n# locate all of the" -" relevant files.\n#\n# Arguments: \n# dir -\t\t\tName of the directory " -"in which to create an index.\n# args -\t\tAny number of additional a" -"rguments giving the\n#\t\t\tnames of files within dir. If no additio" -"nal\n#\t\t\tare given auto_mkindex will look for *.tcl.\n\nproc auto_mk" -"index {dir args} {\n global errorCode errorInfo\n set oldDir " -"[pwd]\n cd $dir\n set dir [pwd]\n append index \"# Tcl autol" -"oad index file, version 2.0\\n\"\n append index \"# This file is g" -"enerated by the \\\"auto_mkindex\\\" command\\n\"\n append index \"# a" -"nd sourced to set up indexing information for one or\\n\"\n appen" -"d index \"# more commands. Typically each line is a command that\\" -"n\"\n append index \"# sets an element in the auto_index array, w" -"here the\\n\"\n append index \"# element name is the name of a com" -"mand and the value is\\n\"\n append index \"# a script that loads " -"the command.\\n\\n\"\n if {$args == \"\"} {\n\tset args *.tcl\n }\n " -" foreach file [eval glob $args] {\n\tset f \"\"\n\tset error [catch {\n" -"\t set f [open $file]\n\t while {[gets $f line] >= 0} {\n\t\tif [" -"regexp {^proc[ \t]+([^ \t]*)} $line match procName] {\n\t\t append " -"index \"set [list auto_index($procName)]\"\n\t\t append index \" \\[l" -"ist source \\[file join \\$dir [list $file]\\]\\]\\n\"\n\t\t}\n\t }\n\t " -"close $f\n\t} msg]\n\tif $error {\n\t set code $errorCode\n\t set i" -"nfo $errorInfo\n\t catch {close $f}\n\t cd $oldDir\n\t error $" -"msg $info $code\n\t}\n }\n set f \"\"\n set error [catch {\n\tset" -" f [open tclIndex w]\n\tputs $f $index nonewline\n\tclose $f\n\tcd $old" -"Dir\n } msg]\n if $error {\n\tset code $errorCode\n\tset info $er" -"rorInfo\n\tcatch {close $f}\n\tcd $oldDir\n\terror $msg $info $code\n " -" }\n}\n\n# pkg_mkIndex --\n# This procedure creates a package index i" -"n a given directory. The\n# package index consists of a \"pkgIndex" -".tcl\" file whose contents are\n# a Tcl script that sets up package" -" information with \"package require\"\n# commands. The commands des" -"cribe all of the packages defined by the\n# files given as argumen" -"ts.\n#\n# Arguments:\n# dir -\t\t\tName of the directory in which to cr" -"eate the index.\n# args -\t\tAny number of additional arguments, eac" -"h giving\n#\t\t\ta glob pattern that matches the names of one or\n#\t\t\t" -"more shared libraries or Tcl script files in\n#\t\t\tdir.\n\nproc pkg_m" -"kIndex {dir args} {\n global errorCode errorInfo\n append ind" -"ex \"# Tcl package index file, version 1.0\\n\"\n append index \"# " -"This file is generated by the \\\"pkg_mkIndex\\\" command\\n\"\n appe" -"nd index \"# and sourced either when an application starts up or\\n" -"\"\n append index \"# by a \\\"package unknown\\\" script. It invoke" -"s the\\n\"\n append index \"# \\\"package ifneeded\\\" command to set " -"up package-related\\n\"\n append index \"# information so that pac" -"kages will be loaded automatically\\n\"\n append index \"# in resp" -"onse to \\\"package require\\\" commands. When this\\n\"\n append in" -"dex \"# script is sourced, the variable \\$dir must contain the\\n\"\n" -" append index \"# full path name of this file's directory.\\n\"\n " -" set oldDir [pwd]\n cd $dir\n foreach file [eval glob $args" -"] {\n\t# For each file, figure out what commands and packages it pr" -"ovides.\n\t# To do this, create a child interpreter, load the file " -"into the\n\t# interpreter, and get a list of the new commands and p" -"ackages\n\t# that are defined. Define an empty \"package unknown\" s" -"cript so\n\t# that there are no recursive package inclusions.\n\n\tset" -" c [interp create]\n\n\t# If Tk is loaded in the parent interpreter," -" load it into the\n\t# child also, in case the extension depends on" -" it.\n\n\tforeach pkg [info loaded] {\n\t if {[lindex $pkg 1] == \"T" -"k\"} {\n\t\t$c eval {set argv {-geometry +0+0}}\n\t\tload [lindex $pkg 0" -"] Tk $c\n\t\tbreak\n\t }\n\t}\n\t$c eval [list set file $file]\n\tif [cat" -"ch {\n\t $c eval {\n\t\tproc dummy args {}\n\t\tpackage unknown dummy\n" -"\t\tset origCmds [info commands]\n\t\tset dir \"\"\t\t;# in case file is p" -"kgIndex.tcl\n\t\tset pkgs \"\"\n\n\t\t# Try to load the file if it has the" -" shared library extension,\n\t\t# otherwise source it. It's importa" -"nt not to try to load\n\t\t# files that aren't shared libraries, bec" -"ause on some systems\n\t\t# (like SunOS) the loader will abort the w" -"hole application\n\t\t# when it gets an error.\n\n\t\tif {[string compar" -"e [file extension $file] \\\n\t\t\t[info sharedlibextension]] == 0} {\n" -"\n\t\t # The \"file join .\" command below is necessary. Without\n\t" -"\t # it, if the file name has no \\'s and we're on UNIX, the\n\t\t " -" # load command will invoke the LD_LIBRARY_PATH search\n\t\t # " -"mechanism, which could cause the wrong file to be used.\n\n\t\t lo" -"ad [file join . $file]\n\t\t set type load\n\t\t} else {\n\t\t sourc" -"e $file\n\t\t set type source\n\t\t}\n\t\tforeach i [info commands] {\n\t" -"\t set cmds($i) 1\n\t\t}\n\t\tforeach i $origCmds {\n\t\t catch {unse" -"t cmds($i)}\n\t\t}\n\t\tforeach i [package names] {\n\t\t if {([string " -"compare [package provide $i] \"\"] != 0)\n\t\t\t && ([string compare" -" $i Tcl] != 0)\n\t\t\t && ([string compare $i Tk] != 0)} {\n\t\t\tlapp" -"end pkgs [list $i [package provide $i]]\n\t\t }\n\t\t}\n\t }\n\t} msg" -"] {\n\t puts \"error while loading or sourcing $file: $msg\"\n\t}\n\tf" -"oreach pkg [$c eval set pkgs] {\n\t lappend files($pkg) [list $f" -"ile [$c eval set type] \\\n\t\t [lsort [$c eval array names cmds]]" -"]\n\t}\n\tinterp delete $c\n }\n foreach pkg [lsort [array names " -"files]] {\n\tappend index \"\\npackage ifneeded $pkg\\\n\t\t\\[list tclPkg" -"Setup \\$dir [lrange $pkg 0 0] [lrange $pkg 1 1]\\\n\t\t[list $files($" -"pkg)]\\]\"\n }\n set f [open pkgIndex.tcl w]\n puts $f $index" -"\n close $f\n cd $oldDir\n}\n\n# tclPkgSetup --\n# This is a util" -"ity procedure use by pkgIndex.tcl files. It is invoked\n# as part" -" of a \"package ifneeded\" script. It calls \"package provide\"\n# to" -" indicate that a package is available, then sets entries in the\n#" -" auto_index array so that the package's files will be auto-loaded" -" when\n# the commands are used.\n#\n# Arguments:\n# dir -\t\t\tDirectory" -" containing all the files for this package.\n# pkg -\t\t\tName of the" -" package (no version number).\n# version -\t\tVersion number for the" -" package, such as 2.1.3.\n# files -\t\tList of files that constitute" -" the package. Each\n#\t\t\telement is a sub-list with three elements" -". The first\n#\t\t\tis the name of a file relative to $dir, the seco" -"nd is\n#\t\t\t\"load\" or \"source\", indicating whether the file is a\n#\t" -"\t\tloadable binary or a script to source, and the third\n#\t\t\tis a l" -"ist of commands defined by this file.\n\nproc tclPkgSetup {dir pkg " -"version files} {\n global auto_index\n\n package provide $pkg " -"$version\n foreach fileInfo $files {\n\tset f [lindex $fileInfo 0" -"]\n\tset type [lindex $fileInfo 1]\n\tforeach cmd [lindex $fileInfo 2" -"] {\n\t if {$type == \"load\"} {\n\t\tset auto_index($cmd) [list load" -" [file join $dir $f] $pkg]\n\t } else {\n\t\tset auto_index($cmd) [" -"list source [file join $dir $f]]\n\t } \n\t}\n }\n}\n\n# tclMacPkgS" -"earch --\n# The procedure is used on the Macintosh to search a giv" -"en directory for files\n# with a TEXT resource named \"pkgIndex\". " -"If it exists it is sourced in to the\n# interpreter to setup the p" -"ackage database.\n\nproc tclMacPkgSearch {dir} {\n foreach x [glo" -"b -nocomplain [file join $dir *.shlb]] {\n\tif [file isfile $x] {\n\t" -" set res [resource open $x]\n\t foreach y [resource list TEXT" -" $res] {\n\t\tif {$y == \"pkgIndex\"} {source -rsrc pkgIndex}\n\t }\n\t" -" resource close $res\n\t}\n }\n}\n\n# tclPkgUnknown --\n# This pro" -"cedure provides the default for the \"package unknown\" function.\n#" -" It is invoked when a package that's needed can't be found. It s" -"cans\n# the auto_path directories and their immediate children loo" -"king for\n# pkgIndex.tcl files and sources any such files that are" -" found to setup\n# the package database. (On the Macintosh we als" -"o search for pkgIndex\n# TEXT resources in all files.)\n#\n# Argumen" -"ts:\n# name -\t\tName of desired package. Not used.\n# version -\t\tVe" -"rsion of desired package. Not used.\n# exact -\t\tEither \"-exact\" o" -"r omitted. Not used.\n\nproc tclPkgUnknown {name version {exact {}" -"}} {\n global auto_path tcl_platform env\n\n if ![info exists " -"auto_path] {\n\treturn\n }\n for {set i [expr [llength $auto_pa" -"th] - 1]} {$i >= 0} {incr i -1} {\n\tset dir [lindex $auto_path $i]" -"\n\tset file [file join $dir pkgIndex.tcl]\n\tif [file readable $file" -"] {\n\t source $file\n\t}\n\tforeach file [glob -nocomplain [file jo" -"in $dir * pkgIndex.tcl]] {\n\t if [file readable $file] {\n\t\tset " -"dir [file dirname $file]\n\t\tsource $file\n\t }\n\t}\n\t# On the Macin" -"tosh we also look in the resource fork \n\t# of shared libraries\n\ti" -"f {$tcl_platform(platform) == \"macintosh\"} {\n\t set dir [lindex" -" $auto_path $i]\n\t tclMacPkgSearch $dir\n\t foreach x [glob -n" -"ocomplain [file join $dir *]] {\n\t\tif [file isdirectory $x] {\n\t\t " -" set dir $x\n\t\t tclMacPkgSearch $dir\n\t\t}\n\t }\n\t}\n }\n}\n" -; -int initcl_Init(Tcl_Interp* interp) +static char init_tcl[] = + "# init.tcl --\n#\n# Default system startup file for Tcl-based appli" + "cations. Defines\n# \"unknown\" procedure and auto-load facilities." + "\n#\n# SCCS: @(#) init.tcl 1.66 96/10/06 14:29:28\n#\n# Copyright (c)" + " 1991-1993 The Regents of the University of California.\n# Copyrig" + "ht (c) 1994-1996 Sun Microsystems, Inc.\n#\n# See the file \"license" + ".terms\" for information on usage and redistribution\n# of this fil" + "e, and for a DISCLAIMER OF ALL WARRANTIES.\n#\n#-------------------" + "---------------------------------------------------------\n#\n# Mod" + "ified by Mark Koennecke in order to redirect unknown into the Sic" + "s\n# mechanism. Thereby disabling command shortcuts and execution " + "of shell\n# commands for security reasons.\n#\n# February 1997\n# Hac" + "ked for Tcl 8.0 September 1997, bad hack if problems start anew\n#" + "\n#---------------------------------------------------------------" + "------------\n \nif {[info commands package] == \"\"} {\n error \"ve" + "rsion mismatch: library\\nscripts expect Tcl version 7.5b1 or late" + "r but the loaded version is\\nonly [info patchlevel]\"\n}\npackage re" + "quire -exact Tcl 8.0\n#if [catch {set auto_path $env(TCLLIBPATH)}]" + " {\n# set auto_path \"\"\n#}\nif {[lsearch -exact $auto_path [info " + "library]] < 0} {\n lappend auto_path [info library]\n}\ncatch {\n " + " foreach dir $tcl_pkgPath {\n\tif {[lsearch -exact $auto_path $di" + "r] < 0} {\n\t lappend auto_path $dir\n\t}\n }\n unset dir\n}\npa" + "ckage unknown tclPkgUnknown\n\n# Some machines, such as the Macinto" + "sh, do not have exec. Also, on all\n# platforms, safe interpreters" + " do not have exec.\n# exec hereby disabled for Security reasons! M" + "K\n set auto_noexec 1\n\n\nset errorCode \"\"\nset errorInfo \"\"\n\n# un" + "known --\n# This procedure is called when a Tcl command is invoked" + " that doesn't\n# exist in the interpreter. It takes the following" + " steps to make the\n# command available:\n#\n#\t1. See if the autoloa" + "d facility can locate the command in a\n#\t Tcl script file. If " + "so, load it and execute it.\n#\t2. If the command was invoked inter" + "actively at top-level:\n#\t (a) see if the command exists as an " + "executable UNIX program.\n#\t\tIf so, \"exec\" the command.\n#\t (b) " + "see if the command requests csh-like history substitution\n#\t\tin o" + "ne of the common forms !!, !, or ^old^new. If\n#\t\tso, emu" + "late csh's history substitution.\n#\t (c) see if the command is " + "a unique abbreviation for another\n#\t\tcommand. If so, invoke the " + "command.\n#\n# Arguments:\n# args -\tA list whose elements are the wo" + "rds of the original\n#\t\tcommand, including the command name.\n\nproc" + " unknown args {\n global auto_noexec auto_noload env unknown_pe" + "nding tcl_interactive\n global errorCode errorInfo\n\n # Save " + "the values of errorCode and errorInfo variables, since they\n #" + " may get modified if caught errors occur below. The variables wi" + "ll\n # be restored just before re-executing the missing command" + ".\n\n set savedErrorCode $errorCode\n set savedErrorInfo $erro" + "rInfo\n set name [lindex $args 0]\n if ![info exists auto_nol" + "oad] {\n\t#\n\t# Make sure we're not trying to load the same proc twi" + "ce.\n\t#\n\tif [info exists unknown_pending($name)] {\n\t return -co" + "de error \"self-referential recursion in \\\"unknown\\\" for command \\" + "\"$name\\\"\";\n\t}\n\tset unknown_pending($name) pending;\n\tset ret [catc" + "h {auto_load $name} msg]\n\tunset unknown_pending($name);\n\tif {$ret" + " != 0} {\n\t return -code $ret -errorcode $errorCode \\\n\t\t\"error " + "while autoloading \\\"$name\\\": $msg\"\n\t}\n\tif ![array size unknown_pe" + "nding] {\n\t unset unknown_pending\n\t}\n\tif $msg {\n\t set errorC" + "ode $savedErrorCode\n\t set errorInfo $savedErrorInfo\n\t set c" + "ode [catch {uplevel $args} msg]\n\t if {$code == 1} {\n\t\t#\n\t\t# S" + "trip the last five lines off the error stack (they're\n\t\t# from th" + "e \"uplevel\" command).\n\t\t#\n\n\t\tset new [split $errorInfo \\n]\n\t\tset " + "new [join [lrange $new 0 [expr [llength $new] - 6]] \\n]\n\t\treturn " + "-code error -errorcode $errorCode \\\n\t\t\t-errorinfo $new $msg\n\t " + "} else {\n\t\treturn -code $code $msg\n\t }\n\t}\n }\n \n # Try" + " running SICS for a change\n set ret [catch {uplevel #0 SicsUnk" + "nown $args} msg]\n if {$ret == 1} {\n return -code error " + "$msg\n } else {\n return -code ok $msg\n }\n}\n\n# auto_lo" + "ad --\n# Checks a collection of library directories to see if a pr" + "ocedure\n# is defined in one of them. If so, it sources the appro" + "priate\n# library file to create the procedure. Returns 1 if it s" + "uccessfully\n# loaded the procedure, 0 otherwise.\n#\n# Arguments: \n" + "# cmd -\t\t\tName of the command to find and load.\n\nproc auto_load c" + "md {\n global auto_index auto_oldpath auto_path env errorInfo e" + "rrorCode\n\n if [info exists auto_index($cmd)] {\n\tuplevel #0 $au" + "to_index($cmd)\n\treturn [expr {[info commands $cmd] != \"\"}]\n }\n" + " if ![info exists auto_path] {\n\treturn 0\n }\n if [info ex" + "ists auto_oldpath] {\n\tif {$auto_oldpath == $auto_path} {\n\t ret" + "urn 0\n\t}\n }\n set auto_oldpath $auto_path\n for {set i [ex" + "pr [llength $auto_path] - 1]} {$i >= 0} {incr i -1} {\n\tset dir [l" + "index $auto_path $i]\n\tset f \"\"\n\tif [catch {set f [open [file join" + " $dir tclIndex]]}] {\n\t continue\n\t}\n\tset error [catch {\n\t se" + "t id [gets $f]\n\t if {$id == \"# Tcl autoload index file, versio" + "n 2.0\"} {\n\t\teval [read $f]\n\t } elseif {$id == \"# Tcl autoload " + "index file: each line identifies a Tcl\"} {\n\t\twhile {[gets $f line" + "] >= 0} {\n\t\t if {([string index $line 0] == \"#\")\n\t\t\t || ([l" + "length $line] != 2)} {\n\t\t\tcontinue\n\t\t }\n\t\t set name [lindex" + " $line 0]\n\t\t set auto_index($name) \\\n\t\t\t\"source [file join $di" + "r [lindex $line 1]]\"\n\t\t}\n\t } else {\n\t\terror \"[file join $dir t" + "clIndex] isn't a proper Tcl index file\"\n\t }\n\t} msg]\n\tif {$f !=" + " \"\"} {\n\t close $f\n\t}\n\tif $error {\n\t error $msg $errorInfo $" + "errorCode\n\t}\n }\n if [info exists auto_index($cmd)] {\n\tuplev" + "el #0 $auto_index($cmd)\n\tif {[info commands $cmd] != \"\"} {\n\t r" + "eturn 1\n\t}\n }\n return 0\n}\n\nif {[string compare $tcl_platfor" + "m(platform) windows] == 0} {\n\n# auto_execok --\n#\n# Returns string" + " that indicates name of program to execute if \n# name corresponds" + " to a shell builtin or an executable in the\n# Windows search path" + ", or \"\" otherwise. Builds an associative \n# array auto_execs tha" + "t caches information about previous checks, \n# for speed.\n#\n# Arg" + "uments: \n# name -\t\t\tName of a command.\n\n# Windows version.\n#\n# No" + "te that info executable doesn't work under Windows, so we have to" + "\n# look for files with .exe, .com, or .bat extensions. Also, the" + " path\n# may be in the Path or PATH environment variables, and pat" + "h\n# components are separated with semicolons, not colons as under" + " Unix.\n#\nproc auto_execok name {\n global auto_execs env tcl_pl" + "atform\n\n if [info exists auto_execs($name)] {\n\treturn $auto_ex" + "ecs($name)\n }\n set auto_execs($name) \"\"\n\n if {[lsearch -" + "exact {cls copy date del erase dir echo mkdir md rename \n\t ren" + " rmdir rd time type ver vol} $name] != -1} {\n\tif {[info exists en" + "v(COMSPEC)]} {\n\t set comspec $env(COMSPEC) \n\t} elseif {[info e" + "xists env(ComSpec)]} {\n\t set comspec $env(ComSpec)\n\t} elseif {" + "$tcl_platform(os) == \"Windows NT\"} {\n\t set comspec \"cmd.exe\"\n\t" + "} else {\n\t set comspec \"command.com\"\n\t}\n\treturn [set auto_exec" + "s($name) [list $comspec /c $name]]\n }\n\n if {[llength [file " + "split $name]] != 1} {\n\tforeach ext {{} .com .exe .bat} {\n\t set" + " file ${name}${ext}\n\t if {[file exists $file] && ![file isdire" + "ctory $file]} {\n\t\treturn [set auto_execs($name) $file]\n\t }\n\t}\n" + "\treturn \"\"\n }\n\n set path \"[file dirname [info nameof]];.;\"\n" + " if {[info exists env(WINDIR)]} {\n\tset windir $env(WINDIR) \n " + " } elseif {[info exists env(windir)]} {\n\tset windir $env(windir)" + "\n }\n if {[info exists windir]} {\n\tif {$tcl_platform(os) == " + "\"Windows NT\"} {\n\t append path \"$windir/system32;\"\n\t}\n\tappend p" + "ath \"$windir/system;$windir;\"\n }\n\n if {! [info exists env(P" + "ATH)]} {\n\tif [info exists env(Path)] {\n\t append path $env(Path" + ")\n\t} else {\n\t return \"\"\n\t}\n } else {\n\tappend path $env(PATH" + ")\n }\n\n foreach dir [split $path {;}] {\n\tif {$dir == \"\"} {\n\t" + " set dir .\n\t}\n\tforeach ext {{} .com .exe .bat} {\n\t set file" + " [file join $dir ${name}${ext}]\n\t if {[file exists $file] && !" + "[file isdirectory $file]} {\n\t\treturn [set auto_execs($name) $file" + "]\n\t }\n\t}\n }\n return \"\"\n}\n\n} else {\n\n# auto_execok --\n#\n#" + " Returns string that indicates name of program to execute if \n# n" + "ame corresponds to an executable in the path. Builds an associati" + "ve \n# array auto_execs that caches information about previous che" + "cks, \n# for speed.\n#\n# Arguments: \n# name -\t\t\tName of a command.\n" + "\n# Unix version.\n#\nproc auto_execok name {\n global auto_execs " + "env\n\n if [info exists auto_execs($name)] {\n\treturn $auto_execs" + "($name)\n }\n set auto_execs($name) \"\"\n if {[llength [file" + " split $name]] != 1} {\n\tif {[file executable $name] && ![file isd" + "irectory $name]} {\n\t set auto_execs($name) $name\n\t}\n\treturn $a" + "uto_execs($name)\n }\n foreach dir [split $env(PATH) :] {\n\tif" + " {$dir == \"\"} {\n\t set dir .\n\t}\n\tset file [file join $dir $name" + "]\n\tif {[file executable $file] && ![file isdirectory $file]} {\n\t " + " set auto_execs($name) $file\n\t return $file\n\t}\n }\n ret" + "urn \"\"\n}\n\n}\n# auto_reset --\n# Destroy all cached information for " + "auto-loading and auto-execution,\n# so that the information gets r" + "ecomputed the next time it's needed.\n# Also delete any procedures" + " that are listed in the auto-load index\n# except those defined in" + " this file.\n#\n# Arguments: \n# None.\n\nproc auto_reset {} {\n glo" + "bal auto_execs auto_index auto_oldpath\n foreach p [info procs]" + " {\n\tif {[info exists auto_index($p)] && ![string match auto_* $p]" + "\n\t\t&& ([lsearch -exact {unknown pkg_mkIndex tclPkgSetup\n\t\t\ttclPkg" + "Unknown} $p] < 0)} {\n\t rename $p {}\n\t}\n }\n catch {unset " + "auto_execs}\n catch {unset auto_index}\n catch {unset auto_ol" + "dpath}\n}\n\n# auto_mkindex --\n# Regenerate a tclIndex file from Tcl" + " source files. Takes as argument\n# the name of the directory in " + "which the tclIndex file is to be placed,\n# followed by any number" + " of glob patterns to use in that directory to\n# locate all of the" + " relevant files.\n#\n# Arguments: \n# dir -\t\t\tName of the directory " + "in which to create an index.\n# args -\t\tAny number of additional a" + "rguments giving the\n#\t\t\tnames of files within dir. If no additio" + "nal\n#\t\t\tare given auto_mkindex will look for *.tcl.\n\nproc auto_mk" + "index {dir args} {\n global errorCode errorInfo\n set oldDir " + "[pwd]\n cd $dir\n set dir [pwd]\n append index \"# Tcl autol" + "oad index file, version 2.0\\n\"\n append index \"# This file is g" + "enerated by the \\\"auto_mkindex\\\" command\\n\"\n append index \"# a" + "nd sourced to set up indexing information for one or\\n\"\n appen" + "d index \"# more commands. Typically each line is a command that\\" + "n\"\n append index \"# sets an element in the auto_index array, w" + "here the\\n\"\n append index \"# element name is the name of a com" + "mand and the value is\\n\"\n append index \"# a script that loads " + "the command.\\n\\n\"\n if {$args == \"\"} {\n\tset args *.tcl\n }\n " + " foreach file [eval glob $args] {\n\tset f \"\"\n\tset error [catch {\n" + "\t set f [open $file]\n\t while {[gets $f line] >= 0} {\n\t\tif [" + "regexp {^proc[ \t]+([^ \t]*)} $line match procName] {\n\t\t append " + "index \"set [list auto_index($procName)]\"\n\t\t append index \" \\[l" + "ist source \\[file join \\$dir [list $file]\\]\\]\\n\"\n\t\t}\n\t }\n\t " + "close $f\n\t} msg]\n\tif $error {\n\t set code $errorCode\n\t set i" + "nfo $errorInfo\n\t catch {close $f}\n\t cd $oldDir\n\t error $" + "msg $info $code\n\t}\n }\n set f \"\"\n set error [catch {\n\tset" + " f [open tclIndex w]\n\tputs $f $index nonewline\n\tclose $f\n\tcd $old" + "Dir\n } msg]\n if $error {\n\tset code $errorCode\n\tset info $er" + "rorInfo\n\tcatch {close $f}\n\tcd $oldDir\n\terror $msg $info $code\n " + " }\n}\n\n# pkg_mkIndex --\n# This procedure creates a package index i" + "n a given directory. The\n# package index consists of a \"pkgIndex" + ".tcl\" file whose contents are\n# a Tcl script that sets up package" + " information with \"package require\"\n# commands. The commands des" + "cribe all of the packages defined by the\n# files given as argumen" + "ts.\n#\n# Arguments:\n# dir -\t\t\tName of the directory in which to cr" + "eate the index.\n# args -\t\tAny number of additional arguments, eac" + "h giving\n#\t\t\ta glob pattern that matches the names of one or\n#\t\t\t" + "more shared libraries or Tcl script files in\n#\t\t\tdir.\n\nproc pkg_m" + "kIndex {dir args} {\n global errorCode errorInfo\n append ind" + "ex \"# Tcl package index file, version 1.0\\n\"\n append index \"# " + "This file is generated by the \\\"pkg_mkIndex\\\" command\\n\"\n appe" + "nd index \"# and sourced either when an application starts up or\\n" + "\"\n append index \"# by a \\\"package unknown\\\" script. It invoke" + "s the\\n\"\n append index \"# \\\"package ifneeded\\\" command to set " + "up package-related\\n\"\n append index \"# information so that pac" + "kages will be loaded automatically\\n\"\n append index \"# in resp" + "onse to \\\"package require\\\" commands. When this\\n\"\n append in" + "dex \"# script is sourced, the variable \\$dir must contain the\\n\"\n" + " append index \"# full path name of this file's directory.\\n\"\n " + " set oldDir [pwd]\n cd $dir\n foreach file [eval glob $args" + "] {\n\t# For each file, figure out what commands and packages it pr" + "ovides.\n\t# To do this, create a child interpreter, load the file " + "into the\n\t# interpreter, and get a list of the new commands and p" + "ackages\n\t# that are defined. Define an empty \"package unknown\" s" + "cript so\n\t# that there are no recursive package inclusions.\n\n\tset" + " c [interp create]\n\n\t# If Tk is loaded in the parent interpreter," + " load it into the\n\t# child also, in case the extension depends on" + " it.\n\n\tforeach pkg [info loaded] {\n\t if {[lindex $pkg 1] == \"T" + "k\"} {\n\t\t$c eval {set argv {-geometry +0+0}}\n\t\tload [lindex $pkg 0" + "] Tk $c\n\t\tbreak\n\t }\n\t}\n\t$c eval [list set file $file]\n\tif [cat" + "ch {\n\t $c eval {\n\t\tproc dummy args {}\n\t\tpackage unknown dummy\n" + "\t\tset origCmds [info commands]\n\t\tset dir \"\"\t\t;# in case file is p" + "kgIndex.tcl\n\t\tset pkgs \"\"\n\n\t\t# Try to load the file if it has the" + " shared library extension,\n\t\t# otherwise source it. It's importa" + "nt not to try to load\n\t\t# files that aren't shared libraries, bec" + "ause on some systems\n\t\t# (like SunOS) the loader will abort the w" + "hole application\n\t\t# when it gets an error.\n\n\t\tif {[string compar" + "e [file extension $file] \\\n\t\t\t[info sharedlibextension]] == 0} {\n" + "\n\t\t # The \"file join .\" command below is necessary. Without\n\t" + "\t # it, if the file name has no \\'s and we're on UNIX, the\n\t\t " + " # load command will invoke the LD_LIBRARY_PATH search\n\t\t # " + "mechanism, which could cause the wrong file to be used.\n\n\t\t lo" + "ad [file join . $file]\n\t\t set type load\n\t\t} else {\n\t\t sourc" + "e $file\n\t\t set type source\n\t\t}\n\t\tforeach i [info commands] {\n\t" + "\t set cmds($i) 1\n\t\t}\n\t\tforeach i $origCmds {\n\t\t catch {unse" + "t cmds($i)}\n\t\t}\n\t\tforeach i [package names] {\n\t\t if {([string " + "compare [package provide $i] \"\"] != 0)\n\t\t\t && ([string compare" + " $i Tcl] != 0)\n\t\t\t && ([string compare $i Tk] != 0)} {\n\t\t\tlapp" + "end pkgs [list $i [package provide $i]]\n\t\t }\n\t\t}\n\t }\n\t} msg" + "] {\n\t puts \"error while loading or sourcing $file: $msg\"\n\t}\n\tf" + "oreach pkg [$c eval set pkgs] {\n\t lappend files($pkg) [list $f" + "ile [$c eval set type] \\\n\t\t [lsort [$c eval array names cmds]]" + "]\n\t}\n\tinterp delete $c\n }\n foreach pkg [lsort [array names " + "files]] {\n\tappend index \"\\npackage ifneeded $pkg\\\n\t\t\\[list tclPkg" + "Setup \\$dir [lrange $pkg 0 0] [lrange $pkg 1 1]\\\n\t\t[list $files($" + "pkg)]\\]\"\n }\n set f [open pkgIndex.tcl w]\n puts $f $index" + "\n close $f\n cd $oldDir\n}\n\n# tclPkgSetup --\n# This is a util" + "ity procedure use by pkgIndex.tcl files. It is invoked\n# as part" + " of a \"package ifneeded\" script. It calls \"package provide\"\n# to" + " indicate that a package is available, then sets entries in the\n#" + " auto_index array so that the package's files will be auto-loaded" + " when\n# the commands are used.\n#\n# Arguments:\n# dir -\t\t\tDirectory" + " containing all the files for this package.\n# pkg -\t\t\tName of the" + " package (no version number).\n# version -\t\tVersion number for the" + " package, such as 2.1.3.\n# files -\t\tList of files that constitute" + " the package. Each\n#\t\t\telement is a sub-list with three elements" + ". The first\n#\t\t\tis the name of a file relative to $dir, the seco" + "nd is\n#\t\t\t\"load\" or \"source\", indicating whether the file is a\n#\t" + "\t\tloadable binary or a script to source, and the third\n#\t\t\tis a l" + "ist of commands defined by this file.\n\nproc tclPkgSetup {dir pkg " + "version files} {\n global auto_index\n\n package provide $pkg " + "$version\n foreach fileInfo $files {\n\tset f [lindex $fileInfo 0" + "]\n\tset type [lindex $fileInfo 1]\n\tforeach cmd [lindex $fileInfo 2" + "] {\n\t if {$type == \"load\"} {\n\t\tset auto_index($cmd) [list load" + " [file join $dir $f] $pkg]\n\t } else {\n\t\tset auto_index($cmd) [" + "list source [file join $dir $f]]\n\t } \n\t}\n }\n}\n\n# tclMacPkgS" + "earch --\n# The procedure is used on the Macintosh to search a giv" + "en directory for files\n# with a TEXT resource named \"pkgIndex\". " + "If it exists it is sourced in to the\n# interpreter to setup the p" + "ackage database.\n\nproc tclMacPkgSearch {dir} {\n foreach x [glo" + "b -nocomplain [file join $dir *.shlb]] {\n\tif [file isfile $x] {\n\t" + " set res [resource open $x]\n\t foreach y [resource list TEXT" + " $res] {\n\t\tif {$y == \"pkgIndex\"} {source -rsrc pkgIndex}\n\t }\n\t" + " resource close $res\n\t}\n }\n}\n\n# tclPkgUnknown --\n# This pro" + "cedure provides the default for the \"package unknown\" function.\n#" + " It is invoked when a package that's needed can't be found. It s" + "cans\n# the auto_path directories and their immediate children loo" + "king for\n# pkgIndex.tcl files and sources any such files that are" + " found to setup\n# the package database. (On the Macintosh we als" + "o search for pkgIndex\n# TEXT resources in all files.)\n#\n# Argumen" + "ts:\n# name -\t\tName of desired package. Not used.\n# version -\t\tVe" + "rsion of desired package. Not used.\n# exact -\t\tEither \"-exact\" o" + "r omitted. Not used.\n\nproc tclPkgUnknown {name version {exact {}" + "}} {\n global auto_path tcl_platform env\n\n if ![info exists " + "auto_path] {\n\treturn\n }\n for {set i [expr [llength $auto_pa" + "th] - 1]} {$i >= 0} {incr i -1} {\n\tset dir [lindex $auto_path $i]" + "\n\tset file [file join $dir pkgIndex.tcl]\n\tif [file readable $file" + "] {\n\t source $file\n\t}\n\tforeach file [glob -nocomplain [file jo" + "in $dir * pkgIndex.tcl]] {\n\t if [file readable $file] {\n\t\tset " + "dir [file dirname $file]\n\t\tsource $file\n\t }\n\t}\n\t# On the Macin" + "tosh we also look in the resource fork \n\t# of shared libraries\n\ti" + "f {$tcl_platform(platform) == \"macintosh\"} {\n\t set dir [lindex" + " $auto_path $i]\n\t tclMacPkgSearch $dir\n\t foreach x [glob -n" + "ocomplain [file join $dir *]] {\n\t\tif [file isdirectory $x] {\n\t\t " + " set dir $x\n\t\t tclMacPkgSearch $dir\n\t\t}\n\t }\n\t}\n }\n}\n"; +int initcl_Init(Tcl_Interp * interp) { - Tcl_SetVar(interp, "package_name", "init", TCL_GLOBAL_ONLY); - if (Tcl_GlobalEval(interp, init_tcl) != TCL_OK) return TCL_ERROR; - Tcl_UnsetVar(interp, "package_name", TCL_GLOBAL_ONLY); - return TCL_OK; + Tcl_SetVar(interp, "package_name", "init", TCL_GLOBAL_ONLY); + if (Tcl_GlobalEval(interp, init_tcl) != TCL_OK) + return TCL_ERROR; + Tcl_UnsetVar(interp, "package_name", TCL_GLOBAL_ONLY); + return TCL_OK; } diff --git a/initcl.c b/initcl.c index 911e7ca9..df0ea132 100644 --- a/initcl.c +++ b/initcl.c @@ -1,292 +1,292 @@ #include -static char init_tcl[] = -"# init.tcl --\n#\n# Default system startup file for Tcl-based appli" -"cations. Defines\n# \"unknown\" procedure and auto-load facilities." -"\n#\n# SCCS: @(#) init.tcl 1.66 96/10/06 14:29:28\n#\n# Copyright (c)" -" 1991-1993 The Regents of the University of California.\n# Copyrig" -"ht (c) 1994-1996 Sun Microsystems, Inc.\n#\n# See the file \"license" -".terms\" for information on usage and redistribution\n# of this fil" -"e, and for a DISCLAIMER OF ALL WARRANTIES.\n#\n#-------------------" -"---------------------------------------------------------\n#\n# Mod" -"ified by Mark Koennecke in order to redirect unknown into the Sic" -"s\n# mechanism. Thereby disabling command shortcuts and execution " -"of shell\n# commands for security reasons.\n#\n# February 1997\n#\n#--" -"-----------------------------------------------------------------" -"--------\n \nif {[info commands package] == \"\"} {\n error \"versio" -"n mismatch: library\\nscripts expect Tcl version 7.5b1 or later bu" -"t the loaded version is\\nonly [info patchlevel]\"\n}\npackage requir" -"e -exact Tcl 7.6\n#if [catch {set auto_path $env(TCLLIBPATH)}] {\n#" -" set auto_path \"\"\n#}\nif {[lsearch -exact $auto_path [info libr" -"ary]] < 0} {\n lappend auto_path [info library]\n}\ncatch {\n f" -"oreach dir $tcl_pkgPath {\n\tif {[lsearch -exact $auto_path $dir] <" -" 0} {\n\t lappend auto_path $dir\n\t}\n }\n unset dir\n}\npackag" -"e unknown tclPkgUnknown\n\n# Some machines, such as the Macintosh, " -"do not have exec. Also, on all\n# platforms, safe interpreters do " -"not have exec.\n# exec hereby disabled for Security reasons! MK\n " -" set auto_noexec 1\n\n\nset errorCode \"\"\nset errorInfo \"\"\n\n# unknow" -"n --\n# This procedure is called when a Tcl command is invoked tha" -"t doesn't\n# exist in the interpreter. It takes the following ste" -"ps to make the\n# command available:\n#\n#\t1. See if the autoload fa" -"cility can locate the command in a\n#\t Tcl script file. If so, " -"load it and execute it.\n#\t2. If the command was invoked interacti" -"vely at top-level:\n#\t (a) see if the command exists as an exec" -"utable UNIX program.\n#\t\tIf so, \"exec\" the command.\n#\t (b) see " -"if the command requests csh-like history substitution\n#\t\tin one o" -"f the common forms !!, !, or ^old^new. If\n#\t\tso, emulate" -" csh's history substitution.\n#\t (c) see if the command is a un" -"ique abbreviation for another\n#\t\tcommand. If so, invoke the comm" -"and.\n#\n# Arguments:\n# args -\tA list whose elements are the words " -"of the original\n#\t\tcommand, including the command name.\n\nproc unk" -"nown args {\n global auto_noexec auto_noload env unknown_pendin" -"g tcl_interactive\n global errorCode errorInfo\n\n # Save the " -"values of errorCode and errorInfo variables, since they\n # may" -" get modified if caught errors occur below. The variables will\n " -" # be restored just before re-executing the missing command.\n\n " -" set savedErrorCode $errorCode\n set savedErrorInfo $errorInf" -"o\n set name [lindex $args 0]\n if ![info exists auto_noload]" -" {\n\t#\n\t# Make sure we're not trying to load the same proc twice.\n" -"\t#\n\tif [info exists unknown_pending($name)] {\n\t return -code e" -"rror \"self-referential recursion in \\\"unknown\\\" for command \\\"$na" -"me\\\"\";\n\t}\n\tset unknown_pending($name) pending;\n\tset ret [catch {a" -"uto_load $name} msg]\n\tunset unknown_pending($name);\n\tif {$ret != " -"0} {\n\t return -code $ret -errorcode $errorCode \\\n\t\t\"error whil" -"e autoloading \\\"$name\\\": $msg\"\n\t}\n\tif ![array size unknown_pendin" -"g] {\n\t unset unknown_pending\n\t}\n\tif $msg {\n\t set errorCode " -"$savedErrorCode\n\t set errorInfo $savedErrorInfo\n\t set code " -"[catch {uplevel $args} msg]\n\t if {$code == 1} {\n\t\t#\n\t\t# Strip" -" the last five lines off the error stack (they're\n\t\t# from the \"u" -"plevel\" command).\n\t\t#\n\n\t\tset new [split $errorInfo \\n]\n\t\tset new " -"[join [lrange $new 0 [expr [llength $new] - 6]] \\n]\n\t\treturn -cod" -"e error -errorcode $errorCode \\\n\t\t\t-errorinfo $new $msg\n\t } el" -"se {\n\t\treturn -code $code $msg\n\t }\n\t}\n }\n \n # Try run" -"ning SICS for a change\n set ret [catch {uplevel #0 SicsUnknown" -" $args} msg]\n if {$ret == 1} {\n return -code error $msg" -"\n } else {\n return -code ok $msg\n }\n}\n\n# auto_load -" -"-\n# Checks a collection of library directories to see if a proced" -"ure\n# is defined in one of them. If so, it sources the appropria" -"te\n# library file to create the procedure. Returns 1 if it succe" -"ssfully\n# loaded the procedure, 0 otherwise.\n#\n# Arguments: \n# cm" -"d -\t\t\tName of the command to find and load.\n\nproc auto_load cmd {" -"\n global auto_index auto_oldpath auto_path env errorInfo error" -"Code\n\n if [info exists auto_index($cmd)] {\n\tuplevel #0 $auto_i" -"ndex($cmd)\n\treturn [expr {[info commands $cmd] != \"\"}]\n }\n " -"if ![info exists auto_path] {\n\treturn 0\n }\n if [info exists" -" auto_oldpath] {\n\tif {$auto_oldpath == $auto_path} {\n\t return " -"0\n\t}\n }\n set auto_oldpath $auto_path\n for {set i [expr [" -"llength $auto_path] - 1]} {$i >= 0} {incr i -1} {\n\tset dir [linde" -"x $auto_path $i]\n\tset f \"\"\n\tif [catch {set f [open [file join $di" -"r tclIndex]]}] {\n\t continue\n\t}\n\tset error [catch {\n\t set id" -" [gets $f]\n\t if {$id == \"# Tcl autoload index file, version 2." -"0\"} {\n\t\teval [read $f]\n\t } elseif {$id == \"# Tcl autoload inde" -"x file: each line identifies a Tcl\"} {\n\t\twhile {[gets $f line] >=" -" 0} {\n\t\t if {([string index $line 0] == \"#\")\n\t\t\t || ([lleng" -"th $line] != 2)} {\n\t\t\tcontinue\n\t\t }\n\t\t set name [lindex $li" -"ne 0]\n\t\t set auto_index($name) \\\n\t\t\t\"source [file join $dir [l" -"index $line 1]]\"\n\t\t}\n\t } else {\n\t\terror \"[file join $dir tclIn" -"dex] isn't a proper Tcl index file\"\n\t }\n\t} msg]\n\tif {$f != \"\"}" -" {\n\t close $f\n\t}\n\tif $error {\n\t error $msg $errorInfo $erro" -"rCode\n\t}\n }\n if [info exists auto_index($cmd)] {\n\tuplevel #" -"0 $auto_index($cmd)\n\tif {[info commands $cmd] != \"\"} {\n\t retur" -"n 1\n\t}\n }\n return 0\n}\n\nif {[string compare $tcl_platform(pl" -"atform) windows] == 0} {\n\n# auto_execok --\n#\n# Returns string tha" -"t indicates name of program to execute if \n# name corresponds to " -"a shell builtin or an executable in the\n# Windows search path, or" -" \"\" otherwise. Builds an associative \n# array auto_execs that ca" -"ches information about previous checks, \n# for speed.\n#\n# Argumen" -"ts: \n# name -\t\t\tName of a command.\n\n# Windows version.\n#\n# Note t" -"hat info executable doesn't work under Windows, so we have to\n# l" -"ook for files with .exe, .com, or .bat extensions. Also, the pat" -"h\n# may be in the Path or PATH environment variables, and path\n# " -"components are separated with semicolons, not colons as under Uni" -"x.\n#\nproc auto_execok name {\n global auto_execs env tcl_platfo" -"rm\n\n if [info exists auto_execs($name)] {\n\treturn $auto_execs(" -"$name)\n }\n set auto_execs($name) \"\"\n\n if {[lsearch -exac" -"t {cls copy date del erase dir echo mkdir md rename \n\t ren rmd" -"ir rd time type ver vol} $name] != -1} {\n\tif {[info exists env(CO" -"MSPEC)]} {\n\t set comspec $env(COMSPEC) \n\t} elseif {[info exist" -"s env(ComSpec)]} {\n\t set comspec $env(ComSpec)\n\t} elseif {$tcl" -"_platform(os) == \"Windows NT\"} {\n\t set comspec \"cmd.exe\"\n\t} el" -"se {\n\t set comspec \"command.com\"\n\t}\n\treturn [set auto_execs($n" -"ame) [list $comspec /c $name]]\n }\n\n if {[llength [file spli" -"t $name]] != 1} {\n\tforeach ext {{} .com .exe .bat} {\n\t set fil" -"e ${name}${ext}\n\t if {[file exists $file] && ![file isdirector" -"y $file]} {\n\t\treturn [set auto_execs($name) $file]\n\t }\n\t}\n\tret" -"urn \"\"\n }\n\n set path \"[file dirname [info nameof]];.;\"\n " -"if {[info exists env(WINDIR)]} {\n\tset windir $env(WINDIR) \n } " -"elseif {[info exists env(windir)]} {\n\tset windir $env(windir)\n " -" }\n if {[info exists windir]} {\n\tif {$tcl_platform(os) == \"Win" -"dows NT\"} {\n\t append path \"$windir/system32;\"\n\t}\n\tappend path " -"\"$windir/system;$windir;\"\n }\n\n if {! [info exists env(PATH)" -"]} {\n\tif [info exists env(Path)] {\n\t append path $env(Path)\n\t}" -" else {\n\t return \"\"\n\t}\n } else {\n\tappend path $env(PATH)\n " -" }\n\n foreach dir [split $path {;}] {\n\tif {$dir == \"\"} {\n\t " -"set dir .\n\t}\n\tforeach ext {{} .com .exe .bat} {\n\t set file [fi" -"le join $dir ${name}${ext}]\n\t if {[file exists $file] && ![fil" -"e isdirectory $file]} {\n\t\treturn [set auto_execs($name) $file]\n\t " -" }\n\t}\n }\n return \"\"\n}\n\n} else {\n\n# auto_execok --\n#\n# Ret" -"urns string that indicates name of program to execute if \n# name " -"corresponds to an executable in the path. Builds an associative \n" -"# array auto_execs that caches information about previous checks," -" \n# for speed.\n#\n# Arguments: \n# name -\t\t\tName of a command.\n\n# U" -"nix version.\n#\nproc auto_execok name {\n global auto_execs env\n" -"\n if [info exists auto_execs($name)] {\n\treturn $auto_execs($na" -"me)\n }\n set auto_execs($name) \"\"\n if {[llength [file spl" -"it $name]] != 1} {\n\tif {[file executable $name] && ![file isdirec" -"tory $name]} {\n\t set auto_execs($name) $name\n\t}\n\treturn $auto_" -"execs($name)\n }\n foreach dir [split $env(PATH) :] {\n\tif {$d" -"ir == \"\"} {\n\t set dir .\n\t}\n\tset file [file join $dir $name]\n\ti" -"f {[file executable $file] && ![file isdirectory $file]} {\n\t s" -"et auto_execs($name) $file\n\t return $file\n\t}\n }\n return " -"\"\"\n}\n\n}\n# auto_reset --\n# Destroy all cached information for auto" -"-loading and auto-execution,\n# so that the information gets recom" -"puted the next time it's needed.\n# Also delete any procedures tha" -"t are listed in the auto-load index\n# except those defined in thi" -"s file.\n#\n# Arguments: \n# None.\n\nproc auto_reset {} {\n global " -"auto_execs auto_index auto_oldpath\n foreach p [info procs] {\n\t" -"if {[info exists auto_index($p)] && ![string match auto_* $p]\n\t\t&" -"& ([lsearch -exact {unknown pkg_mkIndex tclPkgSetup\n\t\t\ttclPkgUnkn" -"own} $p] < 0)} {\n\t rename $p {}\n\t}\n }\n catch {unset auto" -"_execs}\n catch {unset auto_index}\n catch {unset auto_oldpat" -"h}\n}\n\n# auto_mkindex --\n# Regenerate a tclIndex file from Tcl sou" -"rce files. Takes as argument\n# the name of the directory in whic" -"h the tclIndex file is to be placed,\n# followed by any number of " -"glob patterns to use in that directory to\n# locate all of the rel" -"evant files.\n#\n# Arguments: \n# dir -\t\t\tName of the directory in w" -"hich to create an index.\n# args -\t\tAny number of additional argum" -"ents giving the\n#\t\t\tnames of files within dir. If no additional\n" -"#\t\t\tare given auto_mkindex will look for *.tcl.\n\nproc auto_mkinde" -"x {dir args} {\n global errorCode errorInfo\n set oldDir [pwd" -"]\n cd $dir\n set dir [pwd]\n append index \"# Tcl autoload " -"index file, version 2.0\\n\"\n append index \"# This file is gener" -"ated by the \\\"auto_mkindex\\\" command\\n\"\n append index \"# and s" -"ourced to set up indexing information for one or\\n\"\n append in" -"dex \"# more commands. Typically each line is a command that\\n\"\n " -" append index \"# sets an element in the auto_index array, where" -" the\\n\"\n append index \"# element name is the name of a command" -" and the value is\\n\"\n append index \"# a script that loads the " -"command.\\n\\n\"\n if {$args == \"\"} {\n\tset args *.tcl\n }\n fo" -"reach file [eval glob $args] {\n\tset f \"\"\n\tset error [catch {\n\t " -" set f [open $file]\n\t while {[gets $f line] >= 0} {\n\t\tif [rege" -"xp {^proc[ \t]+([^ \t]*)} $line match procName] {\n\t\t append inde" -"x \"set [list auto_index($procName)]\"\n\t\t append index \" \\[list " -"source \\[file join \\$dir [list $file]\\]\\]\\n\"\n\t\t}\n\t }\n\t clos" -"e $f\n\t} msg]\n\tif $error {\n\t set code $errorCode\n\t set info " -"$errorInfo\n\t catch {close $f}\n\t cd $oldDir\n\t error $msg " -"$info $code\n\t}\n }\n set f \"\"\n set error [catch {\n\tset f [" -"open tclIndex w]\n\tputs $f $index nonewline\n\tclose $f\n\tcd $oldDir\n" -" } msg]\n if $error {\n\tset code $errorCode\n\tset info $errorI" -"nfo\n\tcatch {close $f}\n\tcd $oldDir\n\terror $msg $info $code\n }\n}" -"\n\n# pkg_mkIndex --\n# This procedure creates a package index in a " -"given directory. The\n# package index consists of a \"pkgIndex.tcl" -"\" file whose contents are\n# a Tcl script that sets up package inf" -"ormation with \"package require\"\n# commands. The commands describ" -"e all of the packages defined by the\n# files given as arguments.\n" -"#\n# Arguments:\n# dir -\t\t\tName of the directory in which to create" -" the index.\n# args -\t\tAny number of additional arguments, each gi" -"ving\n#\t\t\ta glob pattern that matches the names of one or\n#\t\t\tmore" -" shared libraries or Tcl script files in\n#\t\t\tdir.\n\nproc pkg_mkInd" -"ex {dir args} {\n global errorCode errorInfo\n append index \"" -"# Tcl package index file, version 1.0\\n\"\n append index \"# This" -" file is generated by the \\\"pkg_mkIndex\\\" command\\n\"\n append i" -"ndex \"# and sourced either when an application starts up or\\n\"\n " -" append index \"# by a \\\"package unknown\\\" script. It invokes th" -"e\\n\"\n append index \"# \\\"package ifneeded\\\" command to set up p" -"ackage-related\\n\"\n append index \"# information so that package" -"s will be loaded automatically\\n\"\n append index \"# in response" -" to \\\"package require\\\" commands. When this\\n\"\n append index " -"\"# script is sourced, the variable \\$dir must contain the\\n\"\n " -"append index \"# full path name of this file's directory.\\n\"\n s" -"et oldDir [pwd]\n cd $dir\n foreach file [eval glob $args] {\n" -"\t# For each file, figure out what commands and packages it provid" -"es.\n\t# To do this, create a child interpreter, load the file into" -" the\n\t# interpreter, and get a list of the new commands and packa" -"ges\n\t# that are defined. Define an empty \"package unknown\" scrip" -"t so\n\t# that there are no recursive package inclusions.\n\n\tset c [" -"interp create]\n\n\t# If Tk is loaded in the parent interpreter, loa" -"d it into the\n\t# child also, in case the extension depends on it." -"\n\n\tforeach pkg [info loaded] {\n\t if {[lindex $pkg 1] == \"Tk\"} " -"{\n\t\t$c eval {set argv {-geometry +0+0}}\n\t\tload [lindex $pkg 0] Tk" -" $c\n\t\tbreak\n\t }\n\t}\n\t$c eval [list set file $file]\n\tif [catch {" -"\n\t $c eval {\n\t\tproc dummy args {}\n\t\tpackage unknown dummy\n\t\tse" -"t origCmds [info commands]\n\t\tset dir \"\"\t\t;# in case file is pkgIn" -"dex.tcl\n\t\tset pkgs \"\"\n\n\t\t# Try to load the file if it has the sha" -"red library extension,\n\t\t# otherwise source it. It's important n" -"ot to try to load\n\t\t# files that aren't shared libraries, because" -" on some systems\n\t\t# (like SunOS) the loader will abort the whole" -" application\n\t\t# when it gets an error.\n\n\t\tif {[string compare [f" -"ile extension $file] \\\n\t\t\t[info sharedlibextension]] == 0} {\n\n\t\t " -" # The \"file join .\" command below is necessary. Without\n\t\t " -" # it, if the file name has no \\'s and we're on UNIX, the\n\t\t #" -" load command will invoke the LD_LIBRARY_PATH search\n\t\t # mech" -"anism, which could cause the wrong file to be used.\n\n\t\t load [" -"file join . $file]\n\t\t set type load\n\t\t} else {\n\t\t source $f" -"ile\n\t\t set type source\n\t\t}\n\t\tforeach i [info commands] {\n\t\t " -" set cmds($i) 1\n\t\t}\n\t\tforeach i $origCmds {\n\t\t catch {unset cm" -"ds($i)}\n\t\t}\n\t\tforeach i [package names] {\n\t\t if {([string comp" -"are [package provide $i] \"\"] != 0)\n\t\t\t && ([string compare $i " -"Tcl] != 0)\n\t\t\t && ([string compare $i Tk] != 0)} {\n\t\t\tlappend " -"pkgs [list $i [package provide $i]]\n\t\t }\n\t\t}\n\t }\n\t} msg] {\n" -"\t puts \"error while loading or sourcing $file: $msg\"\n\t}\n\tforea" -"ch pkg [$c eval set pkgs] {\n\t lappend files($pkg) [list $file " -"[$c eval set type] \\\n\t\t [lsort [$c eval array names cmds]]]\n\t}" -"\n\tinterp delete $c\n }\n foreach pkg [lsort [array names file" -"s]] {\n\tappend index \"\\npackage ifneeded $pkg\\\n\t\t\\[list tclPkgSetu" -"p \\$dir [lrange $pkg 0 0] [lrange $pkg 1 1]\\\n\t\t[list $files($pkg)" -"]\\]\"\n }\n set f [open pkgIndex.tcl w]\n puts $f $index\n " -" close $f\n cd $oldDir\n}\n\n# tclPkgSetup --\n# This is a utility " -"procedure use by pkgIndex.tcl files. It is invoked\n# as part of " -"a \"package ifneeded\" script. It calls \"package provide\"\n# to ind" -"icate that a package is available, then sets entries in the\n# aut" -"o_index array so that the package's files will be auto-loaded whe" -"n\n# the commands are used.\n#\n# Arguments:\n# dir -\t\t\tDirectory con" -"taining all the files for this package.\n# pkg -\t\t\tName of the pac" -"kage (no version number).\n# version -\t\tVersion number for the pac" -"kage, such as 2.1.3.\n# files -\t\tList of files that constitute the" -" package. Each\n#\t\t\telement is a sub-list with three elements. T" -"he first\n#\t\t\tis the name of a file relative to $dir, the second i" -"s\n#\t\t\t\"load\" or \"source\", indicating whether the file is a\n#\t\t\tlo" -"adable binary or a script to source, and the third\n#\t\t\tis a list " -"of commands defined by this file.\n\nproc tclPkgSetup {dir pkg vers" -"ion files} {\n global auto_index\n\n package provide $pkg $ver" -"sion\n foreach fileInfo $files {\n\tset f [lindex $fileInfo 0]\n\ts" -"et type [lindex $fileInfo 1]\n\tforeach cmd [lindex $fileInfo 2] {\n" -"\t if {$type == \"load\"} {\n\t\tset auto_index($cmd) [list load [fi" -"le join $dir $f] $pkg]\n\t } else {\n\t\tset auto_index($cmd) [list" -" source [file join $dir $f]]\n\t } \n\t}\n }\n}\n\n# tclMacPkgSearc" -"h --\n# The procedure is used on the Macintosh to search a given d" -"irectory for files\n# with a TEXT resource named \"pkgIndex\". If i" -"t exists it is sourced in to the\n# interpreter to setup the packa" -"ge database.\n\nproc tclMacPkgSearch {dir} {\n foreach x [glob -n" -"ocomplain [file join $dir *.shlb]] {\n\tif [file isfile $x] {\n\t " -"set res [resource open $x]\n\t foreach y [resource list TEXT $re" -"s] {\n\t\tif {$y == \"pkgIndex\"} {source -rsrc pkgIndex}\n\t }\n\t " -"resource close $res\n\t}\n }\n}\n\n# tclPkgUnknown --\n# This procedu" -"re provides the default for the \"package unknown\" function.\n# It " -"is invoked when a package that's needed can't be found. It scans" -"\n# the auto_path directories and their immediate children looking" -" for\n# pkgIndex.tcl files and sources any such files that are fou" -"nd to setup\n# the package database. (On the Macintosh we also se" -"arch for pkgIndex\n# TEXT resources in all files.)\n#\n# Arguments:\n" -"# name -\t\tName of desired package. Not used.\n# version -\t\tVersio" -"n of desired package. Not used.\n# exact -\t\tEither \"-exact\" or om" -"itted. Not used.\n\nproc tclPkgUnknown {name version {exact {}}} {" -"\n global auto_path tcl_platform env\n\n if ![info exists auto" -"_path] {\n\treturn\n }\n for {set i [expr [llength $auto_path] " -"- 1]} {$i >= 0} {incr i -1} {\n\tset dir [lindex $auto_path $i]\n\tse" -"t file [file join $dir pkgIndex.tcl]\n\tif [file readable $file] {\n" -"\t source $file\n\t}\n\tforeach file [glob -nocomplain [file join $" -"dir * pkgIndex.tcl]] {\n\t if [file readable $file] {\n\t\tset dir " -"[file dirname $file]\n\t\tsource $file\n\t }\n\t}\n\t# On the Macintosh" -" we also look in the resource fork \n\t# of shared libraries\n\tif {$" -"tcl_platform(platform) == \"macintosh\"} {\n\t set dir [lindex $au" -"to_path $i]\n\t tclMacPkgSearch $dir\n\t foreach x [glob -nocom" -"plain [file join $dir *]] {\n\t\tif [file isdirectory $x] {\n\t\t se" -"t dir $x\n\t\t tclMacPkgSearch $dir\n\t\t}\n\t }\n\t}\n }\n}\n" -; -int initcl_Init(Tcl_Interp* interp) +static char init_tcl[] = + "# init.tcl --\n#\n# Default system startup file for Tcl-based appli" + "cations. Defines\n# \"unknown\" procedure and auto-load facilities." + "\n#\n# SCCS: @(#) init.tcl 1.66 96/10/06 14:29:28\n#\n# Copyright (c)" + " 1991-1993 The Regents of the University of California.\n# Copyrig" + "ht (c) 1994-1996 Sun Microsystems, Inc.\n#\n# See the file \"license" + ".terms\" for information on usage and redistribution\n# of this fil" + "e, and for a DISCLAIMER OF ALL WARRANTIES.\n#\n#-------------------" + "---------------------------------------------------------\n#\n# Mod" + "ified by Mark Koennecke in order to redirect unknown into the Sic" + "s\n# mechanism. Thereby disabling command shortcuts and execution " + "of shell\n# commands for security reasons.\n#\n# February 1997\n#\n#--" + "-----------------------------------------------------------------" + "--------\n \nif {[info commands package] == \"\"} {\n error \"versio" + "n mismatch: library\\nscripts expect Tcl version 7.5b1 or later bu" + "t the loaded version is\\nonly [info patchlevel]\"\n}\npackage requir" + "e -exact Tcl 7.6\n#if [catch {set auto_path $env(TCLLIBPATH)}] {\n#" + " set auto_path \"\"\n#}\nif {[lsearch -exact $auto_path [info libr" + "ary]] < 0} {\n lappend auto_path [info library]\n}\ncatch {\n f" + "oreach dir $tcl_pkgPath {\n\tif {[lsearch -exact $auto_path $dir] <" + " 0} {\n\t lappend auto_path $dir\n\t}\n }\n unset dir\n}\npackag" + "e unknown tclPkgUnknown\n\n# Some machines, such as the Macintosh, " + "do not have exec. Also, on all\n# platforms, safe interpreters do " + "not have exec.\n# exec hereby disabled for Security reasons! MK\n " + " set auto_noexec 1\n\n\nset errorCode \"\"\nset errorInfo \"\"\n\n# unknow" + "n --\n# This procedure is called when a Tcl command is invoked tha" + "t doesn't\n# exist in the interpreter. It takes the following ste" + "ps to make the\n# command available:\n#\n#\t1. See if the autoload fa" + "cility can locate the command in a\n#\t Tcl script file. If so, " + "load it and execute it.\n#\t2. If the command was invoked interacti" + "vely at top-level:\n#\t (a) see if the command exists as an exec" + "utable UNIX program.\n#\t\tIf so, \"exec\" the command.\n#\t (b) see " + "if the command requests csh-like history substitution\n#\t\tin one o" + "f the common forms !!, !, or ^old^new. If\n#\t\tso, emulate" + " csh's history substitution.\n#\t (c) see if the command is a un" + "ique abbreviation for another\n#\t\tcommand. If so, invoke the comm" + "and.\n#\n# Arguments:\n# args -\tA list whose elements are the words " + "of the original\n#\t\tcommand, including the command name.\n\nproc unk" + "nown args {\n global auto_noexec auto_noload env unknown_pendin" + "g tcl_interactive\n global errorCode errorInfo\n\n # Save the " + "values of errorCode and errorInfo variables, since they\n # may" + " get modified if caught errors occur below. The variables will\n " + " # be restored just before re-executing the missing command.\n\n " + " set savedErrorCode $errorCode\n set savedErrorInfo $errorInf" + "o\n set name [lindex $args 0]\n if ![info exists auto_noload]" + " {\n\t#\n\t# Make sure we're not trying to load the same proc twice.\n" + "\t#\n\tif [info exists unknown_pending($name)] {\n\t return -code e" + "rror \"self-referential recursion in \\\"unknown\\\" for command \\\"$na" + "me\\\"\";\n\t}\n\tset unknown_pending($name) pending;\n\tset ret [catch {a" + "uto_load $name} msg]\n\tunset unknown_pending($name);\n\tif {$ret != " + "0} {\n\t return -code $ret -errorcode $errorCode \\\n\t\t\"error whil" + "e autoloading \\\"$name\\\": $msg\"\n\t}\n\tif ![array size unknown_pendin" + "g] {\n\t unset unknown_pending\n\t}\n\tif $msg {\n\t set errorCode " + "$savedErrorCode\n\t set errorInfo $savedErrorInfo\n\t set code " + "[catch {uplevel $args} msg]\n\t if {$code == 1} {\n\t\t#\n\t\t# Strip" + " the last five lines off the error stack (they're\n\t\t# from the \"u" + "plevel\" command).\n\t\t#\n\n\t\tset new [split $errorInfo \\n]\n\t\tset new " + "[join [lrange $new 0 [expr [llength $new] - 6]] \\n]\n\t\treturn -cod" + "e error -errorcode $errorCode \\\n\t\t\t-errorinfo $new $msg\n\t } el" + "se {\n\t\treturn -code $code $msg\n\t }\n\t}\n }\n \n # Try run" + "ning SICS for a change\n set ret [catch {uplevel #0 SicsUnknown" + " $args} msg]\n if {$ret == 1} {\n return -code error $msg" + "\n } else {\n return -code ok $msg\n }\n}\n\n# auto_load -" + "-\n# Checks a collection of library directories to see if a proced" + "ure\n# is defined in one of them. If so, it sources the appropria" + "te\n# library file to create the procedure. Returns 1 if it succe" + "ssfully\n# loaded the procedure, 0 otherwise.\n#\n# Arguments: \n# cm" + "d -\t\t\tName of the command to find and load.\n\nproc auto_load cmd {" + "\n global auto_index auto_oldpath auto_path env errorInfo error" + "Code\n\n if [info exists auto_index($cmd)] {\n\tuplevel #0 $auto_i" + "ndex($cmd)\n\treturn [expr {[info commands $cmd] != \"\"}]\n }\n " + "if ![info exists auto_path] {\n\treturn 0\n }\n if [info exists" + " auto_oldpath] {\n\tif {$auto_oldpath == $auto_path} {\n\t return " + "0\n\t}\n }\n set auto_oldpath $auto_path\n for {set i [expr [" + "llength $auto_path] - 1]} {$i >= 0} {incr i -1} {\n\tset dir [linde" + "x $auto_path $i]\n\tset f \"\"\n\tif [catch {set f [open [file join $di" + "r tclIndex]]}] {\n\t continue\n\t}\n\tset error [catch {\n\t set id" + " [gets $f]\n\t if {$id == \"# Tcl autoload index file, version 2." + "0\"} {\n\t\teval [read $f]\n\t } elseif {$id == \"# Tcl autoload inde" + "x file: each line identifies a Tcl\"} {\n\t\twhile {[gets $f line] >=" + " 0} {\n\t\t if {([string index $line 0] == \"#\")\n\t\t\t || ([lleng" + "th $line] != 2)} {\n\t\t\tcontinue\n\t\t }\n\t\t set name [lindex $li" + "ne 0]\n\t\t set auto_index($name) \\\n\t\t\t\"source [file join $dir [l" + "index $line 1]]\"\n\t\t}\n\t } else {\n\t\terror \"[file join $dir tclIn" + "dex] isn't a proper Tcl index file\"\n\t }\n\t} msg]\n\tif {$f != \"\"}" + " {\n\t close $f\n\t}\n\tif $error {\n\t error $msg $errorInfo $erro" + "rCode\n\t}\n }\n if [info exists auto_index($cmd)] {\n\tuplevel #" + "0 $auto_index($cmd)\n\tif {[info commands $cmd] != \"\"} {\n\t retur" + "n 1\n\t}\n }\n return 0\n}\n\nif {[string compare $tcl_platform(pl" + "atform) windows] == 0} {\n\n# auto_execok --\n#\n# Returns string tha" + "t indicates name of program to execute if \n# name corresponds to " + "a shell builtin or an executable in the\n# Windows search path, or" + " \"\" otherwise. Builds an associative \n# array auto_execs that ca" + "ches information about previous checks, \n# for speed.\n#\n# Argumen" + "ts: \n# name -\t\t\tName of a command.\n\n# Windows version.\n#\n# Note t" + "hat info executable doesn't work under Windows, so we have to\n# l" + "ook for files with .exe, .com, or .bat extensions. Also, the pat" + "h\n# may be in the Path or PATH environment variables, and path\n# " + "components are separated with semicolons, not colons as under Uni" + "x.\n#\nproc auto_execok name {\n global auto_execs env tcl_platfo" + "rm\n\n if [info exists auto_execs($name)] {\n\treturn $auto_execs(" + "$name)\n }\n set auto_execs($name) \"\"\n\n if {[lsearch -exac" + "t {cls copy date del erase dir echo mkdir md rename \n\t ren rmd" + "ir rd time type ver vol} $name] != -1} {\n\tif {[info exists env(CO" + "MSPEC)]} {\n\t set comspec $env(COMSPEC) \n\t} elseif {[info exist" + "s env(ComSpec)]} {\n\t set comspec $env(ComSpec)\n\t} elseif {$tcl" + "_platform(os) == \"Windows NT\"} {\n\t set comspec \"cmd.exe\"\n\t} el" + "se {\n\t set comspec \"command.com\"\n\t}\n\treturn [set auto_execs($n" + "ame) [list $comspec /c $name]]\n }\n\n if {[llength [file spli" + "t $name]] != 1} {\n\tforeach ext {{} .com .exe .bat} {\n\t set fil" + "e ${name}${ext}\n\t if {[file exists $file] && ![file isdirector" + "y $file]} {\n\t\treturn [set auto_execs($name) $file]\n\t }\n\t}\n\tret" + "urn \"\"\n }\n\n set path \"[file dirname [info nameof]];.;\"\n " + "if {[info exists env(WINDIR)]} {\n\tset windir $env(WINDIR) \n } " + "elseif {[info exists env(windir)]} {\n\tset windir $env(windir)\n " + " }\n if {[info exists windir]} {\n\tif {$tcl_platform(os) == \"Win" + "dows NT\"} {\n\t append path \"$windir/system32;\"\n\t}\n\tappend path " + "\"$windir/system;$windir;\"\n }\n\n if {! [info exists env(PATH)" + "]} {\n\tif [info exists env(Path)] {\n\t append path $env(Path)\n\t}" + " else {\n\t return \"\"\n\t}\n } else {\n\tappend path $env(PATH)\n " + " }\n\n foreach dir [split $path {;}] {\n\tif {$dir == \"\"} {\n\t " + "set dir .\n\t}\n\tforeach ext {{} .com .exe .bat} {\n\t set file [fi" + "le join $dir ${name}${ext}]\n\t if {[file exists $file] && ![fil" + "e isdirectory $file]} {\n\t\treturn [set auto_execs($name) $file]\n\t " + " }\n\t}\n }\n return \"\"\n}\n\n} else {\n\n# auto_execok --\n#\n# Ret" + "urns string that indicates name of program to execute if \n# name " + "corresponds to an executable in the path. Builds an associative \n" + "# array auto_execs that caches information about previous checks," + " \n# for speed.\n#\n# Arguments: \n# name -\t\t\tName of a command.\n\n# U" + "nix version.\n#\nproc auto_execok name {\n global auto_execs env\n" + "\n if [info exists auto_execs($name)] {\n\treturn $auto_execs($na" + "me)\n }\n set auto_execs($name) \"\"\n if {[llength [file spl" + "it $name]] != 1} {\n\tif {[file executable $name] && ![file isdirec" + "tory $name]} {\n\t set auto_execs($name) $name\n\t}\n\treturn $auto_" + "execs($name)\n }\n foreach dir [split $env(PATH) :] {\n\tif {$d" + "ir == \"\"} {\n\t set dir .\n\t}\n\tset file [file join $dir $name]\n\ti" + "f {[file executable $file] && ![file isdirectory $file]} {\n\t s" + "et auto_execs($name) $file\n\t return $file\n\t}\n }\n return " + "\"\"\n}\n\n}\n# auto_reset --\n# Destroy all cached information for auto" + "-loading and auto-execution,\n# so that the information gets recom" + "puted the next time it's needed.\n# Also delete any procedures tha" + "t are listed in the auto-load index\n# except those defined in thi" + "s file.\n#\n# Arguments: \n# None.\n\nproc auto_reset {} {\n global " + "auto_execs auto_index auto_oldpath\n foreach p [info procs] {\n\t" + "if {[info exists auto_index($p)] && ![string match auto_* $p]\n\t\t&" + "& ([lsearch -exact {unknown pkg_mkIndex tclPkgSetup\n\t\t\ttclPkgUnkn" + "own} $p] < 0)} {\n\t rename $p {}\n\t}\n }\n catch {unset auto" + "_execs}\n catch {unset auto_index}\n catch {unset auto_oldpat" + "h}\n}\n\n# auto_mkindex --\n# Regenerate a tclIndex file from Tcl sou" + "rce files. Takes as argument\n# the name of the directory in whic" + "h the tclIndex file is to be placed,\n# followed by any number of " + "glob patterns to use in that directory to\n# locate all of the rel" + "evant files.\n#\n# Arguments: \n# dir -\t\t\tName of the directory in w" + "hich to create an index.\n# args -\t\tAny number of additional argum" + "ents giving the\n#\t\t\tnames of files within dir. If no additional\n" + "#\t\t\tare given auto_mkindex will look for *.tcl.\n\nproc auto_mkinde" + "x {dir args} {\n global errorCode errorInfo\n set oldDir [pwd" + "]\n cd $dir\n set dir [pwd]\n append index \"# Tcl autoload " + "index file, version 2.0\\n\"\n append index \"# This file is gener" + "ated by the \\\"auto_mkindex\\\" command\\n\"\n append index \"# and s" + "ourced to set up indexing information for one or\\n\"\n append in" + "dex \"# more commands. Typically each line is a command that\\n\"\n " + " append index \"# sets an element in the auto_index array, where" + " the\\n\"\n append index \"# element name is the name of a command" + " and the value is\\n\"\n append index \"# a script that loads the " + "command.\\n\\n\"\n if {$args == \"\"} {\n\tset args *.tcl\n }\n fo" + "reach file [eval glob $args] {\n\tset f \"\"\n\tset error [catch {\n\t " + " set f [open $file]\n\t while {[gets $f line] >= 0} {\n\t\tif [rege" + "xp {^proc[ \t]+([^ \t]*)} $line match procName] {\n\t\t append inde" + "x \"set [list auto_index($procName)]\"\n\t\t append index \" \\[list " + "source \\[file join \\$dir [list $file]\\]\\]\\n\"\n\t\t}\n\t }\n\t clos" + "e $f\n\t} msg]\n\tif $error {\n\t set code $errorCode\n\t set info " + "$errorInfo\n\t catch {close $f}\n\t cd $oldDir\n\t error $msg " + "$info $code\n\t}\n }\n set f \"\"\n set error [catch {\n\tset f [" + "open tclIndex w]\n\tputs $f $index nonewline\n\tclose $f\n\tcd $oldDir\n" + " } msg]\n if $error {\n\tset code $errorCode\n\tset info $errorI" + "nfo\n\tcatch {close $f}\n\tcd $oldDir\n\terror $msg $info $code\n }\n}" + "\n\n# pkg_mkIndex --\n# This procedure creates a package index in a " + "given directory. The\n# package index consists of a \"pkgIndex.tcl" + "\" file whose contents are\n# a Tcl script that sets up package inf" + "ormation with \"package require\"\n# commands. The commands describ" + "e all of the packages defined by the\n# files given as arguments.\n" + "#\n# Arguments:\n# dir -\t\t\tName of the directory in which to create" + " the index.\n# args -\t\tAny number of additional arguments, each gi" + "ving\n#\t\t\ta glob pattern that matches the names of one or\n#\t\t\tmore" + " shared libraries or Tcl script files in\n#\t\t\tdir.\n\nproc pkg_mkInd" + "ex {dir args} {\n global errorCode errorInfo\n append index \"" + "# Tcl package index file, version 1.0\\n\"\n append index \"# This" + " file is generated by the \\\"pkg_mkIndex\\\" command\\n\"\n append i" + "ndex \"# and sourced either when an application starts up or\\n\"\n " + " append index \"# by a \\\"package unknown\\\" script. It invokes th" + "e\\n\"\n append index \"# \\\"package ifneeded\\\" command to set up p" + "ackage-related\\n\"\n append index \"# information so that package" + "s will be loaded automatically\\n\"\n append index \"# in response" + " to \\\"package require\\\" commands. When this\\n\"\n append index " + "\"# script is sourced, the variable \\$dir must contain the\\n\"\n " + "append index \"# full path name of this file's directory.\\n\"\n s" + "et oldDir [pwd]\n cd $dir\n foreach file [eval glob $args] {\n" + "\t# For each file, figure out what commands and packages it provid" + "es.\n\t# To do this, create a child interpreter, load the file into" + " the\n\t# interpreter, and get a list of the new commands and packa" + "ges\n\t# that are defined. Define an empty \"package unknown\" scrip" + "t so\n\t# that there are no recursive package inclusions.\n\n\tset c [" + "interp create]\n\n\t# If Tk is loaded in the parent interpreter, loa" + "d it into the\n\t# child also, in case the extension depends on it." + "\n\n\tforeach pkg [info loaded] {\n\t if {[lindex $pkg 1] == \"Tk\"} " + "{\n\t\t$c eval {set argv {-geometry +0+0}}\n\t\tload [lindex $pkg 0] Tk" + " $c\n\t\tbreak\n\t }\n\t}\n\t$c eval [list set file $file]\n\tif [catch {" + "\n\t $c eval {\n\t\tproc dummy args {}\n\t\tpackage unknown dummy\n\t\tse" + "t origCmds [info commands]\n\t\tset dir \"\"\t\t;# in case file is pkgIn" + "dex.tcl\n\t\tset pkgs \"\"\n\n\t\t# Try to load the file if it has the sha" + "red library extension,\n\t\t# otherwise source it. It's important n" + "ot to try to load\n\t\t# files that aren't shared libraries, because" + " on some systems\n\t\t# (like SunOS) the loader will abort the whole" + " application\n\t\t# when it gets an error.\n\n\t\tif {[string compare [f" + "ile extension $file] \\\n\t\t\t[info sharedlibextension]] == 0} {\n\n\t\t " + " # The \"file join .\" command below is necessary. Without\n\t\t " + " # it, if the file name has no \\'s and we're on UNIX, the\n\t\t #" + " load command will invoke the LD_LIBRARY_PATH search\n\t\t # mech" + "anism, which could cause the wrong file to be used.\n\n\t\t load [" + "file join . $file]\n\t\t set type load\n\t\t} else {\n\t\t source $f" + "ile\n\t\t set type source\n\t\t}\n\t\tforeach i [info commands] {\n\t\t " + " set cmds($i) 1\n\t\t}\n\t\tforeach i $origCmds {\n\t\t catch {unset cm" + "ds($i)}\n\t\t}\n\t\tforeach i [package names] {\n\t\t if {([string comp" + "are [package provide $i] \"\"] != 0)\n\t\t\t && ([string compare $i " + "Tcl] != 0)\n\t\t\t && ([string compare $i Tk] != 0)} {\n\t\t\tlappend " + "pkgs [list $i [package provide $i]]\n\t\t }\n\t\t}\n\t }\n\t} msg] {\n" + "\t puts \"error while loading or sourcing $file: $msg\"\n\t}\n\tforea" + "ch pkg [$c eval set pkgs] {\n\t lappend files($pkg) [list $file " + "[$c eval set type] \\\n\t\t [lsort [$c eval array names cmds]]]\n\t}" + "\n\tinterp delete $c\n }\n foreach pkg [lsort [array names file" + "s]] {\n\tappend index \"\\npackage ifneeded $pkg\\\n\t\t\\[list tclPkgSetu" + "p \\$dir [lrange $pkg 0 0] [lrange $pkg 1 1]\\\n\t\t[list $files($pkg)" + "]\\]\"\n }\n set f [open pkgIndex.tcl w]\n puts $f $index\n " + " close $f\n cd $oldDir\n}\n\n# tclPkgSetup --\n# This is a utility " + "procedure use by pkgIndex.tcl files. It is invoked\n# as part of " + "a \"package ifneeded\" script. It calls \"package provide\"\n# to ind" + "icate that a package is available, then sets entries in the\n# aut" + "o_index array so that the package's files will be auto-loaded whe" + "n\n# the commands are used.\n#\n# Arguments:\n# dir -\t\t\tDirectory con" + "taining all the files for this package.\n# pkg -\t\t\tName of the pac" + "kage (no version number).\n# version -\t\tVersion number for the pac" + "kage, such as 2.1.3.\n# files -\t\tList of files that constitute the" + " package. Each\n#\t\t\telement is a sub-list with three elements. T" + "he first\n#\t\t\tis the name of a file relative to $dir, the second i" + "s\n#\t\t\t\"load\" or \"source\", indicating whether the file is a\n#\t\t\tlo" + "adable binary or a script to source, and the third\n#\t\t\tis a list " + "of commands defined by this file.\n\nproc tclPkgSetup {dir pkg vers" + "ion files} {\n global auto_index\n\n package provide $pkg $ver" + "sion\n foreach fileInfo $files {\n\tset f [lindex $fileInfo 0]\n\ts" + "et type [lindex $fileInfo 1]\n\tforeach cmd [lindex $fileInfo 2] {\n" + "\t if {$type == \"load\"} {\n\t\tset auto_index($cmd) [list load [fi" + "le join $dir $f] $pkg]\n\t } else {\n\t\tset auto_index($cmd) [list" + " source [file join $dir $f]]\n\t } \n\t}\n }\n}\n\n# tclMacPkgSearc" + "h --\n# The procedure is used on the Macintosh to search a given d" + "irectory for files\n# with a TEXT resource named \"pkgIndex\". If i" + "t exists it is sourced in to the\n# interpreter to setup the packa" + "ge database.\n\nproc tclMacPkgSearch {dir} {\n foreach x [glob -n" + "ocomplain [file join $dir *.shlb]] {\n\tif [file isfile $x] {\n\t " + "set res [resource open $x]\n\t foreach y [resource list TEXT $re" + "s] {\n\t\tif {$y == \"pkgIndex\"} {source -rsrc pkgIndex}\n\t }\n\t " + "resource close $res\n\t}\n }\n}\n\n# tclPkgUnknown --\n# This procedu" + "re provides the default for the \"package unknown\" function.\n# It " + "is invoked when a package that's needed can't be found. It scans" + "\n# the auto_path directories and their immediate children looking" + " for\n# pkgIndex.tcl files and sources any such files that are fou" + "nd to setup\n# the package database. (On the Macintosh we also se" + "arch for pkgIndex\n# TEXT resources in all files.)\n#\n# Arguments:\n" + "# name -\t\tName of desired package. Not used.\n# version -\t\tVersio" + "n of desired package. Not used.\n# exact -\t\tEither \"-exact\" or om" + "itted. Not used.\n\nproc tclPkgUnknown {name version {exact {}}} {" + "\n global auto_path tcl_platform env\n\n if ![info exists auto" + "_path] {\n\treturn\n }\n for {set i [expr [llength $auto_path] " + "- 1]} {$i >= 0} {incr i -1} {\n\tset dir [lindex $auto_path $i]\n\tse" + "t file [file join $dir pkgIndex.tcl]\n\tif [file readable $file] {\n" + "\t source $file\n\t}\n\tforeach file [glob -nocomplain [file join $" + "dir * pkgIndex.tcl]] {\n\t if [file readable $file] {\n\t\tset dir " + "[file dirname $file]\n\t\tsource $file\n\t }\n\t}\n\t# On the Macintosh" + " we also look in the resource fork \n\t# of shared libraries\n\tif {$" + "tcl_platform(platform) == \"macintosh\"} {\n\t set dir [lindex $au" + "to_path $i]\n\t tclMacPkgSearch $dir\n\t foreach x [glob -nocom" + "plain [file join $dir *]] {\n\t\tif [file isdirectory $x] {\n\t\t se" + "t dir $x\n\t\t tclMacPkgSearch $dir\n\t\t}\n\t }\n\t}\n }\n}\n"; +int initcl_Init(Tcl_Interp * interp) { - Tcl_SetVar(interp, "package_name", "initcl", TCL_GLOBAL_ONLY); - if (Tcl_GlobalEval(interp, init_tcl) != TCL_OK) return TCL_ERROR; - Tcl_UnsetVar(interp, "package_name", TCL_GLOBAL_ONLY); - return TCL_OK; + Tcl_SetVar(interp, "package_name", "initcl", TCL_GLOBAL_ONLY); + if (Tcl_GlobalEval(interp, init_tcl) != TCL_OK) + return TCL_ERROR; + Tcl_UnsetVar(interp, "package_name", TCL_GLOBAL_ONLY); + return TCL_OK; } diff --git a/initializer.c b/initializer.c index ef75f394..9d47ed99 100644 --- a/initializer.c +++ b/initializer.c @@ -13,9 +13,9 @@ Markus Zolliker, March 2005 typedef struct Item { struct Item *next; - char *type; /* "Object" for all commands created by makeobject, else something more general */ - char *name; /* the name for identifying an initializer */ - char *desc; /* a description of the initializer. not the same as pObjectDescriptor->name */ + char *type; /* "Object" for all commands created by makeobject, else something more general */ + char *name; /* the name for identifying an initializer */ + char *desc; /* a description of the initializer. not the same as pObjectDescriptor->name */ Initializer maker; int startupOnly; } Item; @@ -24,9 +24,10 @@ static Item *list = NULL; static int startup = 1; void MakeInitializer(const char *type, const char *name, Initializer maker, - int startupOnly, const char *desc) { + int startupOnly, const char *desc) +{ Item *item; - + item = calloc(1, sizeof *item); assert(item); item->maker = maker; @@ -38,9 +39,10 @@ void MakeInitializer(const char *type, const char *name, Initializer maker, list = item; } -Initializer GetInitializer(const char *type, const char *name) { +Initializer GetInitializer(const char *type, const char *name) +{ Item *p, **last; - + if (startup && !ServerIsStarting(pServ)) { /* pServ->pReader exists: startup finished */ startup = 0; @@ -59,36 +61,39 @@ Initializer GetInitializer(const char *type, const char *name) { } } for (p = list; p != NULL; p = p->next) { - if (strcasecmp(p->name, name) == 0 && strcasecmp(p->type, type) == 0) { + if (strcasecmp(p->name, name) == 0 && strcasecmp(p->type, type) == 0) { return p->maker; } } return NULL; } -static int MakeObject(SConnection *con, SicsInterp *sics, - void *data, int argc, char *argv[]) { +static int MakeObject(SConnection * con, SicsInterp * sics, + void *data, int argc, char *argv[]) +{ CmdInitializer cmdin; - + if (argc < 3) { - SCPrintf(con, eError, "ERROR: should be: %s ...", argv[0]); + SCPrintf(con, eError, "ERROR: should be: %s ...", + argv[0]); return 0; } - - cmdin = (CmdInitializer)GetInitializer("Object", argv[2]); + + cmdin = (CmdInitializer) GetInitializer("Object", argv[2]); if (cmdin) { - return cmdin(con, argc, argv, strcasecmp(argv[0],"makeobject") == 0); + return cmdin(con, argc, argv, strcasecmp(argv[0], "makeobject") == 0); } else { SCPrintf(con, eError, "do not know how to make a %s object", argv[2]); return 0; } } -static int DriverList(SConnection *con, SicsInterp *sics, - void *data, int argc, char *argv[]) { +static int DriverList(SConnection * con, SicsInterp * sics, + void *data, int argc, char *argv[]) +{ Item *p; char *name, *type; - + if (argc < 2 || strcasecmp(argv[1], "list") == 0) { for (p = list; p != NULL; p = p->next) { if (argc < 3) { @@ -106,7 +111,9 @@ static int DriverList(SConnection *con, SicsInterp *sics, type = argv[1]; } p = list; - while (p != NULL && (strcasecmp(p->type, type) != 0 || strcasecmp(p->name, name) != 0)) { + while (p != NULL + && (strcasecmp(p->type, type) != 0 + || strcasecmp(p->name, name) != 0)) { p = p->next; } if (p) { @@ -118,8 +125,9 @@ static int DriverList(SConnection *con, SicsInterp *sics, return 1; } -static int RemoveObject(SConnection *con, SicsInterp *sics, - void *data, int argc, char *argv[]) { +static int RemoveObject(SConnection * con, SicsInterp * sics, + void *data, int argc, char *argv[]) +{ CmdInitializer cmdin; ObjectDescriptor *desc; char *className; @@ -127,18 +135,18 @@ static int RemoveObject(SConnection *con, SicsInterp *sics, char *p; int removeAllowed; char *creationCommand; - + if (argc != 2) { SCPrintf(con, eError, "ERROR: should be: %s ", argv[0]); return 0; } - + desc = FindCommandDescriptor(sics, argv[1]); if (!desc) { SCPrintf(con, eError, "ERROR: %s not found", argv[1]); return 0; } - + creationCommand = GetDescriptorKey(desc, "creationCommand"); if (creationCommand != NULL) { /* if there is a creationCommand, we are allowed to remove */ @@ -146,20 +154,22 @@ static int RemoveObject(SConnection *con, SicsInterp *sics, } else { /* if we have an initializer: we are also allowed to remove */ className = desc->name; - cmdin = (CmdInitializer)GetInitializer("Object", className); + cmdin = (CmdInitializer) GetInitializer("Object", className); if (cmdin == 0) { /* allow also a longer descriptor starting with the initializer name and a blank */ p = strchr(className, ' '); if (p) { - snprintf(shortClassName, sizeof shortClassName, "%.*s", p - className, className); - cmdin = (CmdInitializer)GetInitializer("Object", shortClassName); + snprintf(shortClassName, sizeof shortClassName, "%.*s", + p - className, className); + cmdin = (CmdInitializer) GetInitializer("Object", shortClassName); } } removeAllowed = (cmdin != NULL); } if (removeAllowed) { if (pServ->pExecutor && isInRunMode(pServ->pExecutor)) { - SCPrintf(con, eError, "ERROR: cannot remove %s while running", argv[1]); + SCPrintf(con, eError, "ERROR: cannot remove %s while running", + argv[1]); return 0; } SCPrintf(con, eValue, "remove %s", argv[1]); @@ -176,11 +186,13 @@ typedef struct { FILE *fil; } SaveData; -static int SaveCreationCommand(char *name, pDummy object, void *userData) { +static int SaveCreationCommand(char *name, pDummy object, void *userData) +{ SaveData *saveData = userData; char *creationCommand; - - creationCommand = GetDescriptorKey(object->pDescriptor, "creationCommand"); + + creationCommand = + GetDescriptorKey(object->pDescriptor, "creationCommand"); if (creationCommand && strcmp(creationCommand, "0") != 0) { if (saveData->printHeader == 0) { saveData->printHeader = 1; @@ -191,9 +203,10 @@ static int SaveCreationCommand(char *name, pDummy object, void *userData) { return 1; } -static int SaveCreationCommands(void *object, char *name, FILE *fil) { +static int SaveCreationCommands(void *object, char *name, FILE * fil) +{ SaveData saveData; - + saveData.fil = fil; saveData.printHeader = 0; ForEachCommand(SaveCreationCommand, &saveData); @@ -203,8 +216,9 @@ static int SaveCreationCommands(void *object, char *name, FILE *fil) { return 1; } -static int CreationCommand(SConnection *con, SicsInterp *sics, - void *data, int argc, char *argv[]) { +static int CreationCommand(SConnection * con, SicsInterp * sics, + void *data, int argc, char *argv[]) +{ CmdInitializer cmdin; char *className; char shortClassName[32]; @@ -213,12 +227,14 @@ static int CreationCommand(SConnection *con, SicsInterp *sics, ObjectDescriptor *desc; char *creationCommand; char buf[256]; - + if (argc < 2) { - SCPrintf(con, eError, "ERROR: should be: %s []", argv[0]); + SCPrintf(con, eError, + "ERROR: should be: %s []", + argv[0]); return 0; } - + desc = FindCommandDescriptor(sics, argv[1]); if (!desc) { SCPrintf(con, eError, "ERROR: %s not found", argv[1]); @@ -239,7 +255,8 @@ static int CreationCommand(SConnection *con, SicsInterp *sics, creationCommand = Arg2Tcl(argc - 2, argv + 2, buf, sizeof buf); if (creationCommand) { SetDescriptorKey(desc, "creationCommand", creationCommand); - if (creationCommand != buf) free(creationCommand); + if (creationCommand != buf) + free(creationCommand); } else { SetDescriptorKey(desc, "creationCommand", "0"); } @@ -247,34 +264,46 @@ static int CreationCommand(SConnection *con, SicsInterp *sics, return 1; } -static void KillInitializers(void *data) { +static void KillInitializers(void *data) +{ KillDummy(data); Item *item, *next; - + item = list; while (item) { next = item->next; - if (item->name) free(item->name); - if (item->type) free(item->type); - if (item->desc) free(item->desc); + if (item->name) + free(item->name); + if (item->type) + free(item->type); + if (item->desc) + free(item->desc); free(item); item = next; } list = NULL; } -void MakeDriver(const char *driver, CmdInitializer maker, int startupOnly, const char *desc) { - MakeInitializer("Object", driver, (Initializer)maker, startupOnly, desc); +void MakeDriver(const char *driver, CmdInitializer maker, int startupOnly, + const char *desc) +{ + MakeInitializer("Object", driver, (Initializer) maker, startupOnly, + desc); } -void InitializerInit(void) { +void InitializerInit(void) +{ pDummy cc = NULL; - AddCommandWithFlag(pServ->pSics, "MakeObject", MakeObject, KillInitializers, NULL, 0); - AddCommandWithFlag(pServ->pSics, "MakeStaticObject", MakeObject, NULL, NULL, 0); - AddCommandWithFlag(pServ->pSics, "RemoveObject", RemoveObject, NULL, NULL, 0); - AddCommandWithFlag(pServ->pSics, "DriverList", DriverList, NULL, NULL, 0); + AddCommandWithFlag(pServ->pSics, "MakeObject", MakeObject, + KillInitializers, NULL, 0); + AddCommandWithFlag(pServ->pSics, "MakeStaticObject", MakeObject, NULL, + NULL, 0); + AddCommandWithFlag(pServ->pSics, "RemoveObject", RemoveObject, NULL, + NULL, 0); + AddCommandWithFlag(pServ->pSics, "DriverList", DriverList, NULL, NULL, + 0); cc = CreateDummy("creation commands"); cc->pDescriptor->SaveStatus = SaveCreationCommands; AddCommandWithFlag(pServ->pSics, "CreationCommand", CreationCommand, - KillDummy, cc, 0); + KillDummy, cc, 0); } diff --git a/initializer.h b/initializer.h index 036a15a6..85d4136f 100644 --- a/initializer.h +++ b/initializer.h @@ -10,10 +10,10 @@ Markus Zolliker, March 2005 #ifndef SICSINIT_H #define SICSINIT_H -typedef void (*Initializer)(void); +typedef void (*Initializer) (void); -void MakeInitializer(const char *type, const char *name, Initializer maker, int startupOnly, - const char *desc); +void MakeInitializer(const char *type, const char *name, Initializer maker, + int startupOnly, const char *desc); /* install an initializer @@ -49,7 +49,8 @@ static int MakeObject(SConnection *con, SicsInterp *sics, */ -typedef int (*CmdInitializer) (SConnection *pCon, int argc, char *argv[], int dynamic); +typedef int (*CmdInitializer) (SConnection * pCon, int argc, char *argv[], + int dynamic); /* The initalizer prototype for the type "Object". - pCon: the sics connection calling this initializer diff --git a/intcli.c b/intcli.c index ca781e54..508eff89 100644 --- a/intcli.c +++ b/intcli.c @@ -43,41 +43,37 @@ #include "network.h" #include "interrupt.h" - static mkChannel *pChannel = NULL; - +static mkChannel *pChannel = NULL; + /*---------------------------------------------------------------------------*/ - int ClientSetupInterrupt(char *host, int iPort) - { - pChannel = UDPConnect(host,iPort); - if(pChannel == NULL) - { - return 0; - } - else - { - return 1; - } - } -/*---------------------------------------------------------------------------*/ - void ClientStopInterrupt(void) - { - if(pChannel) - { - NETClosePort(pChannel); - free(pChannel); - } +int ClientSetupInterrupt(char *host, int iPort) +{ + pChannel = UDPConnect(host, iPort); + if (pChannel == NULL) { + return 0; + } else { + return 1; } +} + /*---------------------------------------------------------------------------*/ - void SendInterrupt(int iCode) - { - char pBueffel[132]; - - if( (iCode <0) ) - { - return; - } - - sprintf(pBueffel,"SICSINT %d",iCode); - UDPWrite(pChannel,pBueffel,strlen(pBueffel)); +void ClientStopInterrupt(void) +{ + if (pChannel) { + NETClosePort(pChannel); + free(pChannel); + } +} + +/*---------------------------------------------------------------------------*/ +void SendInterrupt(int iCode) +{ + char pBueffel[132]; + + if ((iCode < 0)) { + return; } + sprintf(pBueffel, "SICSINT %d", iCode); + UDPWrite(pChannel, pBueffel, strlen(pBueffel)); +} diff --git a/integrate.c b/integrate.c index 292a1d78..c9a8751d 100644 --- a/integrate.c +++ b/integrate.c @@ -25,35 +25,34 @@ in between #define LEFT -1 #define RIGHT 1 -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*----------------- a private data structure to keep track of things ----*/ - typedef struct { - long *lCounts; - int iCounts; - int m; - int iLeft; - int iMaxCount; - int iRight; - } IntegData, *pIntegData; - +typedef struct { + long *lCounts; + int iCounts; + int m; + int iLeft; + int iMaxCount; + int iRight; +} IntegData, *pIntegData; + /*-------------------------------------------------------------------------*/ - static int FindMaxCount(long lCounts[], int iCounts) - { - int i, iPtr; - long l = -100000; - - for(i = 0, iPtr = 0; i < iCounts;i++) - { - if(lCounts[i] > l) - { - l = lCounts[i]; - iPtr = i; - } - } - return iPtr; - } +static int FindMaxCount(long lCounts[], int iCounts) +{ + int i, iPtr; + long l = -100000; + + for (i = 0, iPtr = 0; i < iCounts; i++) { + if (lCounts[i] > l) { + l = lCounts[i]; + iPtr = i; + } + } + return iPtr; +} + /*------------------------------------------------------------------------ Finds the index where the counts are less then half peak height. Assumes that iMaxCount has been set to a proper value beforehand. This helps to @@ -63,291 +62,262 @@ in between from there. Saves calculation time as well. FindHalf returns an index on success, else - 1 if it goes beyond limits! -----------------------------------------------------------------------*/ - static int FindHalf(pIntegData self, int iSign) - { - int i; - long lHalf; - - assert(self); - - lHalf = self->lCounts[self->iMaxCount]/2; - i = self->iMaxCount; - while(self->lCounts[i] > lHalf) - { - i += iSign; - if( (i < 0) || (i > self->iCounts) ) - { - return -1; - } - } - return i; - } +static int FindHalf(pIntegData self, int iSign) +{ + int i; + long lHalf; + + assert(self); + + lHalf = self->lCounts[self->iMaxCount] / 2; + i = self->iMaxCount; + while (self->lCounts[i] > lHalf) { + i += iSign; + if ((i < 0) || (i > self->iCounts)) { + return -1; + } + } + return i; +} + /*-------------------------------------------------------------------------- FindWindowHits find the number of hits in the window defined by 0.67 sigma of the value at iPos and m. Returns -1 if insufficient data is available to do the trick. iSign can be -1 for search to left or 1 for search to right. ----------------------------------------------------------------------------*/ - static int FindWindowHits(pIntegData self, int iPos, int iSign) - { - float fWinMin, fWinMax, fVar; - int i, iTest, iCount; - - assert(self); - assert( (iSign == -1) || (iSign == 1) ); - - /* check limits of the show */ - iTest = iPos + iSign * self->m; - if( (iTest < 0) || (iTest >= self->iCounts) ) - { - return -1; - } - - /* calculate limits */ - if(self->lCounts[iPos] > 0) - { - fVar = sqrt((double)self->lCounts[iPos]); - fWinMin = (float)self->lCounts[iPos] - 0.67 * fVar; - fWinMax = (float)self->lCounts[iPos] + 0.67 * fVar; - } - else - { - fWinMin = 0.; - fWinMax = 1.; - } - - /* count the window hits */ - for(i = 0, iCount = 0; i < self->m; i++) - { - iTest = iPos + iSign * i; - if( (self->lCounts[iTest] >= fWinMin) && - (self->lCounts[iTest] <= fWinMax) ) - { - iCount++; - } - } - return iCount; - } +---------------------------------------------------------------------------*/ +static int FindWindowHits(pIntegData self, int iPos, int iSign) +{ + float fWinMin, fWinMax, fVar; + int i, iTest, iCount; + + assert(self); + assert((iSign == -1) || (iSign == 1)); + + /* check limits of the show */ + iTest = iPos + iSign * self->m; + if ((iTest < 0) || (iTest >= self->iCounts)) { + return -1; + } + + /* calculate limits */ + if (self->lCounts[iPos] > 0) { + fVar = sqrt((double) self->lCounts[iPos]); + fWinMin = (float) self->lCounts[iPos] - 0.67 * fVar; + fWinMax = (float) self->lCounts[iPos] + 0.67 * fVar; + } else { + fWinMin = 0.; + fWinMax = 1.; + } + + /* count the window hits */ + for (i = 0, iCount = 0; i < self->m; i++) { + iTest = iPos + iSign * i; + if ((self->lCounts[iTest] >= fWinMin) && + (self->lCounts[iTest] <= fWinMax)) { + iCount++; + } + } + return iCount; +} + /*---------------------------------------------------------------------------- AdvanceBackground advances in the background until the predefined Probability has been reached. The probability is defined at the top of the file. iSign and errors are the same as above. -----------------------------------------------------------------------------*/ - static int AdvanceBackground(pIntegData self, int iPos, int iSign) - { - float fProb; - int iRet, iTest; - - assert(self); - assert( (iSign == 1) || (iSign == -1) ); - - /* initialize, calculate initial Probability */ - iRet = FindWindowHits(self,iPos,iSign); - if(iRet < 0) - { - return iRet; - } - fProb = (self->m - iRet)/self->m; - iTest = iPos; - - /* loop further on */ - while(fProb > PROBABILITY) - { - iTest += iSign; - iRet = FindWindowHits(self,iTest,iSign); - if(iRet < 0) - { - return iRet; - } - fProb *= (self->m - iRet)/self->m; - } - - if( (iTest < 0) || (iTest >= self->iCounts) ) - { - return -1; - } - else - { - return iTest; - } - } +----------------------------------------------------------------------------*/ +static int AdvanceBackground(pIntegData self, int iPos, int iSign) +{ + float fProb; + int iRet, iTest; + + assert(self); + assert((iSign == 1) || (iSign == -1)); + + /* initialize, calculate initial Probability */ + iRet = FindWindowHits(self, iPos, iSign); + if (iRet < 0) { + return iRet; + } + fProb = (self->m - iRet) / self->m; + iTest = iPos; + + /* loop further on */ + while (fProb > PROBABILITY) { + iTest += iSign; + iRet = FindWindowHits(self, iTest, iSign); + if (iRet < 0) { + return iRet; + } + fProb *= (self->m - iRet) / self->m; + } + + if ((iTest < 0) || (iTest >= self->iCounts)) { + return -1; + } else { + return iTest; + } +} + /*-------------------------------------------------------------------------- FindLimit assumes, that iMaxCount has been set to something sensible in advance! ---------------------------------------------------------------------------*/ - static int FindLimit(pIntegData self, int iStart, int iSign) - { - int i, iHalf, iHit, iLeft, iTest; - - assert(self); - assert( (iSign == 1) || (iSign == -1) ); - - iHit = 0; - iHalf = self->m/2; - i = iStart; - - /* loop until iHalf is reached */ - while((iHit = FindWindowHits(self,i,iSign)) < iHalf) - { - i += iSign; - if(iHit < 0) - { - if(iSign == LEFT) - { - return INTEGLEFT; - } - else - { - return INTEGRIGHT; - } - } +--------------------------------------------------------------------------*/ +static int FindLimit(pIntegData self, int iStart, int iSign) +{ + int i, iHalf, iHit, iLeft, iTest; + + assert(self); + assert((iSign == 1) || (iSign == -1)); + + iHit = 0; + iHalf = self->m / 2; + i = iStart; + + /* loop until iHalf is reached */ + while ((iHit = FindWindowHits(self, i, iSign)) < iHalf) { + i += iSign; + if (iHit < 0) { + if (iSign == LEFT) { + return INTEGLEFT; + } else { + return INTEGRIGHT; + } } - - /* step further into the backgound */ - iTest = AdvanceBackground(self,i,iSign); - if(iTest < 0) - { - if(iSign == LEFT) - { - return INTEGLEFT; - } - else - { - return INTEGRIGHT; - } - } - - /* store it away and return success */ - if(iSign == LEFT) - { - self->iLeft = iTest; - } - else - { - self->iRight = iTest; - } - return 1; } + + /* step further into the backgound */ + iTest = AdvanceBackground(self, i, iSign); + if (iTest < 0) { + if (iSign == LEFT) { + return INTEGLEFT; + } else { + return INTEGRIGHT; + } + } + + /* store it away and return success */ + if (iSign == LEFT) { + self->iLeft = iTest; + } else { + self->iRight = iTest; + } + return 1; +} + /*-------------------------------------------------------------------------- This routine does the actual integration once the limits have been determined. - --------------------------------------------------------------------------*/ - static int DoIntegrate(pIntegData self, float *fSum, float *fVariance) - { - long lLeftBack, lRightBack, lBackMean; - int i,iRes = 1; - float fScan, fBackVar,fLeft, fRight, fN, fNP, fNB, fSumm; - float fMLeft, fMRight; - - assert(self); - assert( (self->iLeft != 0) && (self->iRight != 0) ); - - - /* sum the left background */ - for(i = 0, lLeftBack = 0; i < self->iLeft; i++) - { - lLeftBack += self->lCounts[i]; - } - lLeftBack = lLeftBack; - - /* sum the right background */ - for(i = self->iRight, lRightBack = 0; i < self->iCounts; i++) - { - lRightBack += self->lCounts[i]; - } - lRightBack = lRightBack; - - - /* sum all of it */ - fScan = 0.; - for(i = 0; i < self->iCounts; i++) - { - fScan += self->lCounts[i]; - } + --------------------------------------------------------------------------*/ +static int DoIntegrate(pIntegData self, float *fSum, float *fVariance) +{ + long lLeftBack, lRightBack, lBackMean; + int i, iRes = 1; + float fScan, fBackVar, fLeft, fRight, fN, fNP, fNB, fSumm; + float fMLeft, fMRight; - /* sum the peak */ - fSumm = 0.; - for(i = self->iLeft; i < self->iRight +1; i++) - { - fSumm += (float)self->lCounts[i]; - } - - /* calculate the values */ - fLeft = (float)self->iLeft; - fRight = (float)self->iRight; - fN = (float)self->iCounts; - - fNP = fRight - fLeft + 1.; - fNB = fLeft + (fN - fRight); - - *fSum = fSumm - (fNP/fNB)*((float)lLeftBack + (float)lRightBack); - *fVariance = sqrt(fSumm + (fNP/fNB)*(fNP/fNB)*((float)lLeftBack - + (float)lRightBack)); - - /* check the background */ - fMLeft = lLeftBack/fLeft; - fMRight = lRightBack/fRight; - if(ABS(fMLeft - fMRight) > ((fMLeft + fMRight)/2) ) - { - iRes = INTEGFUNNYBACK; - } + assert(self); + assert((self->iLeft != 0) && (self->iRight != 0)); - return iRes; + + /* sum the left background */ + for (i = 0, lLeftBack = 0; i < self->iLeft; i++) { + lLeftBack += self->lCounts[i]; } + lLeftBack = lLeftBack; + + /* sum the right background */ + for (i = self->iRight, lRightBack = 0; i < self->iCounts; i++) { + lRightBack += self->lCounts[i]; + } + lRightBack = lRightBack; + + + /* sum all of it */ + fScan = 0.; + for (i = 0; i < self->iCounts; i++) { + fScan += self->lCounts[i]; + } + + /* sum the peak */ + fSumm = 0.; + for (i = self->iLeft; i < self->iRight + 1; i++) { + fSumm += (float) self->lCounts[i]; + } + + /* calculate the values */ + fLeft = (float) self->iLeft; + fRight = (float) self->iRight; + fN = (float) self->iCounts; + + fNP = fRight - fLeft + 1.; + fNB = fLeft + (fN - fRight); + + *fSum = fSumm - (fNP / fNB) * ((float) lLeftBack + (float) lRightBack); + *fVariance = sqrt(fSumm + (fNP / fNB) * (fNP / fNB) * ((float) lLeftBack + + + (float) + lRightBack)); + + /* check the background */ + fMLeft = lLeftBack / fLeft; + fMRight = lRightBack / fRight; + if (ABS(fMLeft - fMRight) > ((fMLeft + fMRight) / 2)) { + iRes = INTEGFUNNYBACK; + } + + return iRes; +} + /*---------------------------------------------------------------------------*/ - int GabePeakIntegrate(int m, int iCounts, long lCounts[], - float *fIntens, float *fVariance) - { - IntegData self; - int iTest,i, iStart; - - /* check input */ - assert(iCounts > 0); - assert(lCounts); - - - /* initialize Data Structure */ - self.iCounts = iCounts; - self.lCounts = lCounts; /* no need to duplicate data */ - self.iLeft = 0; - self.iRight = 0; - self.iMaxCount = 0; - self.m = m; - - /* find maximum */ - self.iMaxCount = FindMaxCount(self.lCounts, self.iCounts); - - /* find Left Limit */ - iStart = FindHalf(&self,LEFT); - if(iStart < 0) - { - return INTEGLEFT; - } - iTest = FindLimit(&self,iStart,LEFT); - if(iTest < 0) - { - return iTest; - } - - /* find right limit */ - iStart = FindHalf(&self,RIGHT); - if(iStart < 0) - { - return INTEGRIGHT; - } - iTest = FindLimit(&self,iStart,RIGHT); - if(iTest < 0) - { - return iTest; - } +int GabePeakIntegrate(int m, int iCounts, long lCounts[], + float *fIntens, float *fVariance) +{ + IntegData self; + int iTest, i, iStart; + + /* check input */ + assert(iCounts > 0); + assert(lCounts); + + + /* initialize Data Structure */ + self.iCounts = iCounts; + self.lCounts = lCounts; /* no need to duplicate data */ + self.iLeft = 0; + self.iRight = 0; + self.iMaxCount = 0; + self.m = m; + + /* find maximum */ + self.iMaxCount = FindMaxCount(self.lCounts, self.iCounts); + + /* find Left Limit */ + iStart = FindHalf(&self, LEFT); + if (iStart < 0) { + return INTEGLEFT; + } + iTest = FindLimit(&self, iStart, LEFT); + if (iTest < 0) { + return iTest; + } + + /* find right limit */ + iStart = FindHalf(&self, RIGHT); + if (iStart < 0) { + return INTEGRIGHT; + } + iTest = FindLimit(&self, iStart, RIGHT); + if (iTest < 0) { + return iTest; + } #ifdef PRINT - printf("Limits: %d %d\n",self.iLeft, self.iRight); - for(i = self.iLeft; i < self.iRight; i++) - { - printf(" %d\n",self.lCounts[i]); - } + printf("Limits: %d %d\n", self.iLeft, self.iRight); + for (i = self.iLeft; i < self.iRight; i++) { + printf(" %d\n", self.lCounts[i]); + } #endif - /* integrate */ - return DoIntegrate(&self,fIntens, fVariance); - - } + /* integrate */ + return DoIntegrate(&self, fIntens, fVariance); + +} diff --git a/integrate.h b/integrate.h index d03b6421..eb28f1aa 100644 --- a/integrate.h +++ b/integrate.h @@ -16,6 +16,6 @@ #define INTEGNOPEAK -3 #define INTEGFUNNYBACK -4 - int GabePeakIntegrate(int m, int iCounts, long lCounts[], - float *fIntens, float *fVariance); +int GabePeakIntegrate(int m, int iCounts, long lCounts[], + float *fIntens, float *fVariance); #endif diff --git a/interface.c b/interface.c index ea5d5631..a22cc2d3 100644 --- a/interface.c +++ b/interface.c @@ -45,156 +45,162 @@ /*========================================================================= Empty driveable interface functions ==========================================================================*/ -static int EmptyHalt(void *self){ +static int EmptyHalt(void *self) +{ return OKOK; } + /*-----------------------------------------------------------------------*/ -static int EmptyLimits(void *self, float fVal, char *error, int errLen){ +static int EmptyLimits(void *self, float fVal, char *error, int errLen) +{ return 1; } + /*-----------------------------------------------------------------------*/ -static long EmptyValue(void *self, SConnection *pCon, float fVal){ - SCWrite(pCon,"WARNING: empty SetValue",eWarning); +static long EmptyValue(void *self, SConnection * pCon, float fVal) +{ + SCWrite(pCon, "WARNING: empty SetValue", eWarning); return OKOK; } + /*-----------------------------------------------------------------------*/ -static int EmptyStatus(void *self, SConnection *pCon){ +static int EmptyStatus(void *self, SConnection * pCon) +{ return HWIdle; } + /*------------------------------------------------------------------------*/ -static float EmptyGet(void *self, SConnection *pCon){ - SCWrite(pCon,"WARNING: empty GetValue",eWarning); +static float EmptyGet(void *self, SConnection * pCon) +{ + SCWrite(pCon, "WARNING: empty GetValue", eWarning); return 555.55; } + /*-------------------------------------------------------------------------*/ - pIDrivable CreateDrivableInterface(void) - { - pIDrivable pRes = NULL; - - pRes = (pIDrivable)malloc(sizeof(IDrivable)); - if(!pRes) - { - return NULL; - } - memset(pRes,0,sizeof(IDrivable)); - pRes->ID = DRIVEID; - pRes->Halt = EmptyHalt; - pRes->CheckLimits = EmptyLimits; - pRes->SetValue = EmptyValue; - pRes->CheckStatus = EmptyStatus; - pRes->GetValue = EmptyGet; - pRes->drivableStatus=HWIdle; - return pRes; +pIDrivable CreateDrivableInterface(void) +{ + pIDrivable pRes = NULL; + + pRes = (pIDrivable) malloc(sizeof(IDrivable)); + if (!pRes) { + return NULL; } + memset(pRes, 0, sizeof(IDrivable)); + pRes->ID = DRIVEID; + pRes->Halt = EmptyHalt; + pRes->CheckLimits = EmptyLimits; + pRes->SetValue = EmptyValue; + pRes->CheckStatus = EmptyStatus; + pRes->GetValue = EmptyGet; + pRes->drivableStatus = HWIdle; + return pRes; +} + /*-------------------------------------------------------------------------*/ - pICountable CreateCountableInterface(void) - { - pICountable pRes = NULL; - - pRes = (pICountable)malloc(sizeof(ICountable)); - if(!pRes) - { - return NULL; - } - memset(pRes,0,sizeof(ICountable)); - pRes->ID = COUNTID; - return pRes; +pICountable CreateCountableInterface(void) +{ + pICountable pRes = NULL; + + pRes = (pICountable) malloc(sizeof(ICountable)); + if (!pRes) { + return NULL; } + memset(pRes, 0, sizeof(ICountable)); + pRes->ID = COUNTID; + return pRes; +} /*---------------------------------------------------------------------------*/ - pEVInterface CreateEVInterface(void) - { - pEVInterface pRes = NULL; - - pRes = (pEVInterface)malloc(sizeof(EVInterface)); - if(!pRes) - { - return NULL; - } - memset(pRes,0,sizeof(EVInterface)); - pRes->iID = ENVIRINTERFACE; - return pRes; +pEVInterface CreateEVInterface(void) +{ + pEVInterface pRes = NULL; + + pRes = (pEVInterface) malloc(sizeof(EVInterface)); + if (!pRes) { + return NULL; } + memset(pRes, 0, sizeof(EVInterface)); + pRes->iID = ENVIRINTERFACE; + return pRes; +} + /*--------------------------------------------------------------------------*/ - static void *FindInterface(void *pObject, int iID) - { - pDummy pDum = NULL; - - pDum = (pDummy)pObject; - if(!pDum) - { - return NULL; - } - if(!pDum->pDescriptor) - { - return NULL; - } - - return pDum->pDescriptor->GetInterface(pDum,iID); +static void *FindInterface(void *pObject, int iID) +{ + pDummy pDum = NULL; + + pDum = (pDummy) pObject; + if (!pDum) { + return NULL; } + if (!pDum->pDescriptor) { + return NULL; + } + + return pDum->pDescriptor->GetInterface(pDum, iID); +} + /*--------------------------------------------------------------------------*/ - pIDrivable GetDrivableInterface(void *pObject) - { - return (pIDrivable)FindInterface(pObject,DRIVEID); - } +pIDrivable GetDrivableInterface(void *pObject) +{ + return (pIDrivable) FindInterface(pObject, DRIVEID); +} + /*-------------------------------------------------------------------------*/ -int GetDrivablePosition(void *pObject, SConnection *pCon, float *fPos) +int GetDrivablePosition(void *pObject, SConnection * pCon, float *fPos) { pIDrivable pDriv = NULL; pMotor pMot = NULL; float value; pDriv = GetDrivableInterface(pObject); - if(pDriv == NULL) - { + if (pDriv == NULL) { return 0; } - if(iHasType(pObject,"Motor")) - { - pMot = (pMotor)pObject; - return MotorGetSoftPosition(pMot,pCon,fPos); + if (iHasType(pObject, "Motor")) { + pMot = (pMotor) pObject; + return MotorGetSoftPosition(pMot, pCon, fPos); } - value = pDriv->GetValue(pObject,pCon); - if(value < 9999.99) - { + value = pDriv->GetValue(pObject, pCon); + if (value < 9999.99) { return 0; } *fPos = value; return 1; } -/*--------------------------------------------------------------------------*/ - pICountable GetCountableInterface(void *pObject) - { - return (pICountable)FindInterface(pObject,COUNTID); - } -/*--------------------------------------------------------------------------*/ - int GetCountLock(pICountable self, SConnection *pCon) - { - if(self->running == 1) - { - SCWrite(pCon,"ERROR: someone else is already counting!", eError); - return 0; - } - else - { - self->running = 1; - return 1; - } - } -/*--------------------------------------------------------------------------*/ - void ReleaseCountLock(pICountable self) - { - self->running = 0; - } -/*--------------------------------------------------------------------------*/ - int isRunning(pICountable self) - { - return self->running; - } -/*--------------------------------------------------------------------------*/ - pICallBack GetCallbackInterface(void *pObject) - { - return (pICallBack)FindInterface(pObject,CALLBACKINTERFACE); - } +/*--------------------------------------------------------------------------*/ +pICountable GetCountableInterface(void *pObject) +{ + return (pICountable) FindInterface(pObject, COUNTID); +} +/*--------------------------------------------------------------------------*/ +int GetCountLock(pICountable self, SConnection * pCon) +{ + if (self->running == 1) { + SCWrite(pCon, "ERROR: someone else is already counting!", eError); + return 0; + } else { + self->running = 1; + return 1; + } +} + +/*--------------------------------------------------------------------------*/ +void ReleaseCountLock(pICountable self) +{ + self->running = 0; +} + +/*--------------------------------------------------------------------------*/ +int isRunning(pICountable self) +{ + return self->running; +} + +/*--------------------------------------------------------------------------*/ +pICallBack GetCallbackInterface(void *pObject) +{ + return (pICallBack) FindInterface(pObject, CALLBACKINTERFACE); +} diff --git a/interface.h b/interface.h index 6be57bea..b3ede689 100644 --- a/interface.h +++ b/interface.h @@ -30,88 +30,85 @@ #line 121 "interface.w" - typedef struct { - int ID; - int (*Halt)(void *self); - int (*CheckLimits)(void *self, float fVal, - char *error, int iErrLen); - long (*SetValue)(void *self, SConnection *pCon, - float fVal); - int (*CheckStatus)(void *self, SConnection *pCon); - float (*GetValue)(void *self, SConnection *pCon); - int iErrorCount; - int drivableStatus; - } IDrivable, *pIDrivable; +typedef struct { + int ID; + int (*Halt) (void *self); + int (*CheckLimits) (void *self, float fVal, char *error, int iErrLen); + long (*SetValue) (void *self, SConnection * pCon, float fVal); + int (*CheckStatus) (void *self, SConnection * pCon); + float (*GetValue) (void *self, SConnection * pCon); + int iErrorCount; + int drivableStatus; +} IDrivable, *pIDrivable; - pIDrivable GetDrivableInterface(void *pObject); - int GetDrivablePosition(void *pObject, SConnection *pCon, - float *fPos); +pIDrivable GetDrivableInterface(void *pObject); +int GetDrivablePosition(void *pObject, SConnection * pCon, float *fPos); #line 425 "interface.w" - pIDrivable CreateDrivableInterface(void); +pIDrivable CreateDrivableInterface(void); /* ------------------------ The countable interface ---------------------*/ #line 188 "interface.w" - typedef struct { - int ID; - int running; - int (*Halt)(void *self); - void (*SetCountParameters)(void *self, float fPreset, - CounterMode eMode);\ - int (*StartCount)(void *self, SConnection *pCon); - int (*CheckCountStatus)(void *self, SConnection *pCon); - int (*Pause)(void *self, SConnection *pCon); - int (*Continue)(void *self, SConnection *pCon); - int (*TransferData)(void *self, SConnection *pCon); - } ICountable, *pICountable; +typedef struct { + int ID; + int running; + int (*Halt) (void *self); + void (*SetCountParameters) (void *self, float fPreset, + CounterMode eMode); + int (*StartCount) (void *self, SConnection * pCon); + int (*CheckCountStatus) (void *self, SConnection * pCon); + int (*Pause) (void *self, SConnection * pCon); + int (*Continue) (void *self, SConnection * pCon); + int (*TransferData) (void *self, SConnection * pCon); +} ICountable, *pICountable; - pICountable GetCountableInterface(void *pObject); - int GetCountLock(pICountable self, SConnection *pCon); - void ReleaseCountLock(pICountable self); - int isRunning(pICountable self); +pICountable GetCountableInterface(void *pObject); +int GetCountLock(pICountable self, SConnection * pCon); +void ReleaseCountLock(pICountable self); +int isRunning(pICountable self); #line 430 "interface.w" - pICountable CreateCountableInterface(void); +pICountable CreateCountableInterface(void); /* ------------------------- The CallBack Interface --------------------*/ #line 253 "interface.w" - typedef void (*KillFuncIT)(void *pData); - typedef int (*SICSCallBack)(int iEvent, void *pEventData, - void *pUserData); +typedef void (*KillFuncIT) (void *pData); +typedef int (*SICSCallBack) (int iEvent, void *pEventData, + void *pUserData); #line 435 "interface.w" #line 275 "interface.w" - typedef struct __ICallBack *pICallBack; - +typedef struct __ICallBack *pICallBack; + /* event source side */ - pICallBack CreateCallBackInterface(void); - void DeleteCallBackInterface(pICallBack self); - int InvokeCallBack(pICallBack pInterface, int iEvent, void *pEventData); +pICallBack CreateCallBackInterface(void); +void DeleteCallBackInterface(pICallBack self); +int InvokeCallBack(pICallBack pInterface, int iEvent, void *pEventData); /* callback client side */ - long RegisterCallback(pICallBack pInterface, - int iEvent, SICSCallBack pFunc, - void *pUserData, KillFuncIT pKill); - int RemoveCallback(pICallBack pInterface, long iID); - int RemoveCallback2(pICallBack pInterface, void *pUserData); - int RemoveCallbackCon(pICallBack pInterface, SConnection *pCon); +long RegisterCallback(pICallBack pInterface, + int iEvent, SICSCallBack pFunc, + void *pUserData, KillFuncIT pKill); +int RemoveCallback(pICallBack pInterface, long iID); +int RemoveCallback2(pICallBack pInterface, void *pUserData); +int RemoveCallbackCon(pICallBack pInterface, SConnection * pCon); - int CallbackScript(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int CallbackScript(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - pICallBack GetCallbackInterface(void *pData); +pICallBack GetCallbackInterface(void *pData); #line 436 "interface.w" @@ -119,20 +116,20 @@ #line 353 "interface.w" - typedef enum { EVIdle, EVDrive, EVMonitor, EVError } EVMode; - typedef struct { - int iID; - EVMode (*GetMode)(void *self); - int (*IsInTolerance)(void *self); - int (*HandleError)(void *self); - } EVInterface, *pEVInterface; +typedef enum { EVIdle, EVDrive, EVMonitor, EVError } EVMode; +typedef struct { + int iID; + EVMode(*GetMode) (void *self); + int (*IsInTolerance) (void *self); + int (*HandleError) (void *self); +} EVInterface, *pEVInterface; #line 438 "interface.w" #line 379 "interface.w" - pEVInterface CreateEVInterface(void); +pEVInterface CreateEVInterface(void); #line 439 "interface.w" diff --git a/interrupt.h b/interrupt.h index 475cb8e2..ed8611c6 100644 --- a/interrupt.h +++ b/interrupt.h @@ -26,24 +26,24 @@ #define eEndServer 6 /* ---------------- server side functions ---------------------------------*/ - void ServerStopInterrupt(void); +void ServerStopInterrupt(void); /* - stops interrupt processing. - */ - - void SetInterrupt(int iCode); + stops interrupt processing. + */ + +void SetInterrupt(int iCode); /* - send an interrupt to everybody - */ + send an interrupt to everybody + */ /*------------------------------ utility ----------------------------------*/ - int Interrupt2Text(int iInterrupt, char *text, int iTextLen); - int Text2Interrupt(char *text); +int Interrupt2Text(int iInterrupt, char *text, int iTextLen); +int Text2Interrupt(char *text); /* --------------------- client side functions ----------------------------*/ - int ClientSetupInterrupt(char *host, int iPort); - void ClientStopInterrupt(void); - void SendInterrupt( int iCode); - - +int ClientSetupInterrupt(char *host, int iPort); +void ClientStopInterrupt(void); +void SendInterrupt(int iCode); + + #endif diff --git a/intserv.c b/intserv.c index 499e29a5..d8f9b0f4 100644 --- a/intserv.c +++ b/intserv.c @@ -38,82 +38,80 @@ #define MAXINTERRUPT 7 #define INTERUPTWAIT 5 - static mkChannel *IntPort = NULL; - static pTaskMan pTask = NULL; +static mkChannel *IntPort = NULL; +static pTaskMan pTask = NULL; /*----------------------------------------------------------------------------*/ - static char *pIntText[] = { - "continue", - "abortop", - "abortscan", - "abortbatch", - "halt", - "free", - "end", - NULL }; +static char *pIntText[] = { + "continue", + "abortop", + "abortscan", + "abortbatch", + "halt", + "free", + "end", + NULL +}; + /*---------------------------------------------------------------------------*/ - int ServerSetupInterrupt(int iPort, pNetRead pNet, pTaskMan pTasker) - { - int i; - - - pTask = pTasker; - /* setup interrupt port */ - IntPort = UDPOpen(iPort); - if(IntPort == NULL) - { - return 0; - } - else - { - NetReadRegister(pNet, IntPort,udp,NULL); - return 1; - } - } +int ServerSetupInterrupt(int iPort, pNetRead pNet, pTaskMan pTasker) +{ + int i; + + + pTask = pTasker; + /* setup interrupt port */ + IntPort = UDPOpen(iPort); + if (IntPort == NULL) { + return 0; + } else { + NetReadRegister(pNet, IntPort, udp, NULL); + return 1; + } +} + /*--------------------------------------------------------------------------*/ - void ServerStopInterrupt(void) - { - - /* close the port */ - if(IntPort) - { - NETClosePort(IntPort); - free(IntPort); - } - } +void ServerStopInterrupt(void) +{ + + /* close the port */ + if (IntPort) { + NETClosePort(IntPort); + free(IntPort); + } +} + /*-------------------------------------------------------------------------*/ - void SetInterrupt(int iCode) - { - int iInt; - - iInt = iCode; - - TaskSignal(pTask,SICSINT, &iInt); - } +void SetInterrupt(int iCode) +{ + int iInt; + + iInt = iCode; + + TaskSignal(pTask, SICSINT, &iInt); +} + /*--------------------------------------------------------------------------*/ - int Interrupt2Text(int iInterrupt, char *text, int iTextLen) - { - if( (iInterrupt < 0) || (iInterrupt > MAXINTERRUPT)) - { - return 0; - } - strncpy(text,pIntText[iInterrupt],iTextLen-1); - return 1; - } +int Interrupt2Text(int iInterrupt, char *text, int iTextLen) +{ + if ((iInterrupt < 0) || (iInterrupt > MAXINTERRUPT)) { + return 0; + } + strncpy(text, pIntText[iInterrupt], iTextLen - 1); + return 1; +} + /*-------------------------------------------------------------------------*/ - int Text2Interrupt(char *text) - { - int i = 0; - while(pIntText[i] != NULL) - { - if(strcmp(pIntText[i],text) == 0) - { - break; - } - i++; - } - if(i >= MAXINTERRUPT) - { - return -1; - } - return i; - } +int Text2Interrupt(char *text) +{ + int i = 0; + while (pIntText[i] != NULL) { + if (strcmp(pIntText[i], text) == 0) { + break; + } + i++; + } + if (i >= MAXINTERRUPT) { + return -1; + } + return i; +} diff --git a/lin2ang.c b/lin2ang.c index 0c6de052..07b8d7d4 100644 --- a/lin2ang.c +++ b/lin2ang.c @@ -20,303 +20,290 @@ #include "sics.h" #include "lin2ang.h" - static const float RD = 57.2957795, pi = 3.1415926; +static const float RD = 57.2957795, pi = 3.1415926; /* --------- our very own private data structure ------------------------*/ - typedef struct __LIN2ANG { - pObjectDescriptor pDes; - pIDrivable pDriv; - pMotor lin; - float length; - float zero; - }Lin2Ang, *pLin2Ang; +typedef struct __LIN2ANG { + pObjectDescriptor pDes; + pIDrivable pDriv; + pMotor lin; + float length; + float zero; +} Lin2Ang, *pLin2Ang; /*-------------------------- conversion routines -------------------------*/ - static float ang2x(pLin2Ang self, float fAngle) - { - return self->length*tan((fAngle+self->zero)/RD); - } +static float ang2x(pLin2Ang self, float fAngle) +{ + return self->length * tan((fAngle + self->zero) / RD); +} + /*-----------------------------------------------------------------------*/ - static float x2ang(pLin2Ang self, float fX) - { - double dt; +static float x2ang(pLin2Ang self, float fX) +{ + double dt; - assert(self->length > 0.); + assert(self->length > 0.); + + dt = fX / self->length; + return RD * atan(dt) - self->zero; +} - dt = fX/self->length; - return RD*atan(dt) - self->zero; - } /*============== functions in the interface ============================*/ - static void *Lin2AngGetInterface(void *pData, int iID) - { - pLin2Ang self = NULL; - - self = (pLin2Ang)pData; - assert(self); +static void *Lin2AngGetInterface(void *pData, int iID) +{ + pLin2Ang self = NULL; - if(iID == DRIVEID) - { - return self->pDriv; - } - return NULL; + self = (pLin2Ang) pData; + assert(self); + + if (iID == DRIVEID) { + return self->pDriv; } + return NULL; +} + /*----------------------------------------------------------------------*/ - static int Lin2AngSave(void *pData, char *name, FILE *fd) - { - pLin2Ang self = NULL; - - self = (pLin2Ang)pData; - if(!self) - return 0; +static int Lin2AngSave(void *pData, char *name, FILE * fd) +{ + pLin2Ang self = NULL; + + self = (pLin2Ang) pData; + if (!self) + return 0; + + fprintf(fd, "%s length %f\n", name, self->length); + fprintf(fd, "%s softzero %f\n", name, self->zero); + return 1; + +} - fprintf(fd,"%s length %f\n",name, self->length); - fprintf(fd,"%s softzero %f\n",name, self->zero); - return 1; - - } /*-----------------------------------------------------------------------*/ - static int L2AHalt(void *pData) - { - pLin2Ang self = NULL; +static int L2AHalt(void *pData) +{ + pLin2Ang self = NULL; + + self = (pLin2Ang) pData; + assert(self); + + return self->lin->pDrivInt->Halt(self->lin); +} - self = (pLin2Ang)pData; - assert(self); - - return self->lin->pDrivInt->Halt(self->lin); - } /*------------------------------------------------------------------------*/ - static int L2ALimits(void *pData, float fVal, char *error, int iErrlen) - { - float fX; - pLin2Ang self = NULL; +static int L2ALimits(void *pData, float fVal, char *error, int iErrlen) +{ + float fX; + pLin2Ang self = NULL; - self = (pLin2Ang)pData; - assert(self); + self = (pLin2Ang) pData; + assert(self); + + fX = ang2x(self, fVal); + return self->lin->pDrivInt->CheckLimits(self->lin, fX, error, iErrlen); +} - fX = ang2x(self,fVal); - return self->lin->pDrivInt->CheckLimits(self->lin,fX,error,iErrlen); - } /*-----------------------------------------------------------------------*/ - static float L2AGetValue(void *pData, SConnection *pCon) - { - float fX, zero = 0.; - pLin2Ang self = NULL; +static float L2AGetValue(void *pData, SConnection * pCon) +{ + float fX, zero = 0.; + pLin2Ang self = NULL; + + self = (pLin2Ang) pData; + assert(self); + MotorGetSoftPosition(self->lin, pCon, &fX); + return x2ang(self, fX); +} - self = (pLin2Ang)pData; - assert(self); - MotorGetSoftPosition(self->lin,pCon,&fX); - return x2ang(self,fX); - } /*------------------------------------------------------------------------*/ - static int L2AStatus(void *pData, SConnection *pCon) - { - pLin2Ang self = NULL; +static int L2AStatus(void *pData, SConnection * pCon) +{ + pLin2Ang self = NULL; + + self = (pLin2Ang) pData; + assert(self); + return self->lin->pDrivInt->CheckStatus(self->lin, pCon); +} - self = (pLin2Ang)pData; - assert(self); - return self->lin->pDrivInt->CheckStatus(self->lin,pCon); - } /*------------------------------------------------------------------------*/ - static long L2ASetValue(void *pData, SConnection *pCon, float fValue) - { - float fX; - pLin2Ang self = NULL; +static long L2ASetValue(void *pData, SConnection * pCon, float fValue) +{ + float fX; + pLin2Ang self = NULL; - self = (pLin2Ang)pData; - assert(self); + self = (pLin2Ang) pData; + assert(self); + + fX = ang2x(self, fValue); + return self->lin->pDrivInt->SetValue(self->lin, pCon, fX); +} - fX = ang2x(self,fValue); - return self->lin->pDrivInt->SetValue(self->lin,pCon,fX); - } /*--------------------------------------------------------------------*/ - static void KillL2A(void *pData) - { - pLin2Ang self = NULL; +static void KillL2A(void *pData) +{ + pLin2Ang self = NULL; - self = (pLin2Ang)pData; - if(!self) - return; + self = (pLin2Ang) pData; + if (!self) + return; - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->pDriv) - { - free(self->pDriv); - } - free(self); + if (self->pDes) { + DeleteDescriptor(self->pDes); } + if (self->pDriv) { + free(self->pDriv); + } + free(self); +} + /*------------------------------------------------------------------- Syntax: MakeLin2Ang name motor */ - int MakeLin2Ang(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pLin2Ang pNew = NULL; - char pBueffel[255]; - int iRet; +int MakeLin2Ang(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pLin2Ang pNew = NULL; + char pBueffel[255]; + int iRet; - /* check number of arguments */ - if(argc < 3) - { - SCWrite(pCon,"ERROR: Insufficient arguments to Lin2Arg",eError); - return 0; - } - - /* allocate memory */ - pNew = (pLin2Ang)malloc(sizeof(Lin2Ang)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory in MakeLin2Ang",eError); - return 0; - } - memset(pNew,0,sizeof(Lin2Ang)); - pNew->pDes = CreateDescriptor("Lin2Ang"); - if(!pNew->pDes) - { - SCWrite(pCon,"ERROR: out of memory in MakeLin2Ang",eError); - free(pNew); - return 0; - } - pNew->pDriv = CreateDrivableInterface(); - if(!pNew->pDriv) - { - SCWrite(pCon,"ERROR: out of memory in MakeLin2Ang",eError); - KillL2A(pNew); - return 0; - } - - /* check if we got a motor */ - pNew->lin = FindMotor(pSics,argv[2]); - if(!pNew->lin) - { - sprintf(pBueffel,"ERROR: %s is no motor!",argv[2]); - SCWrite(pCon,pBueffel,eError); - KillL2A(pNew); - return 0; - } - - - /* initialize the data structure */ - pNew->pDes->GetInterface = Lin2AngGetInterface; - pNew->pDes->SaveStatus = Lin2AngSave; - pNew->pDriv->Halt = L2AHalt; - pNew->pDriv->CheckLimits = L2ALimits; - pNew->pDriv->SetValue = L2ASetValue; - pNew->pDriv->CheckStatus = L2AStatus; - pNew->pDriv->GetValue = L2AGetValue; - pNew->length = 80.; - - /* install command */ - iRet = AddCommand(pSics, argv[1],Lin2AngAction,KillL2A,pNew); - if(!iRet) - { - sprintf(pBueffel, - "ERROR: duplicate Lin2Ang command %s NOT created", - argv[1]); - SCWrite(pCon,pBueffel,eError); - KillL2A(pNew); - return 0; - } - return 1; + /* check number of arguments */ + if (argc < 3) { + SCWrite(pCon, "ERROR: Insufficient arguments to Lin2Arg", eError); + return 0; } + + /* allocate memory */ + pNew = (pLin2Ang) malloc(sizeof(Lin2Ang)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory in MakeLin2Ang", eError); + return 0; + } + memset(pNew, 0, sizeof(Lin2Ang)); + pNew->pDes = CreateDescriptor("Lin2Ang"); + if (!pNew->pDes) { + SCWrite(pCon, "ERROR: out of memory in MakeLin2Ang", eError); + free(pNew); + return 0; + } + pNew->pDriv = CreateDrivableInterface(); + if (!pNew->pDriv) { + SCWrite(pCon, "ERROR: out of memory in MakeLin2Ang", eError); + KillL2A(pNew); + return 0; + } + + /* check if we got a motor */ + pNew->lin = FindMotor(pSics, argv[2]); + if (!pNew->lin) { + sprintf(pBueffel, "ERROR: %s is no motor!", argv[2]); + SCWrite(pCon, pBueffel, eError); + KillL2A(pNew); + return 0; + } + + + /* initialize the data structure */ + pNew->pDes->GetInterface = Lin2AngGetInterface; + pNew->pDes->SaveStatus = Lin2AngSave; + pNew->pDriv->Halt = L2AHalt; + pNew->pDriv->CheckLimits = L2ALimits; + pNew->pDriv->SetValue = L2ASetValue; + pNew->pDriv->CheckStatus = L2AStatus; + pNew->pDriv->GetValue = L2AGetValue; + pNew->length = 80.; + + /* install command */ + iRet = AddCommand(pSics, argv[1], Lin2AngAction, KillL2A, pNew); + if (!iRet) { + sprintf(pBueffel, + "ERROR: duplicate Lin2Ang command %s NOT created", argv[1]); + SCWrite(pCon, pBueffel, eError); + KillL2A(pNew); + return 0; + } + return 1; +} + /*--------------------------------------------------------------------*/ - int Lin2AngAction(SConnection *pCon, SicsInterp *pSics, void *pData, +int Lin2AngAction(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]) - { - pLin2Ang self = NULL; - char pBueffel[255]; - float fVal, fLow, fHigh; - double dVal; - int iRet; +{ + pLin2Ang self = NULL; + char pBueffel[255]; + float fVal, fLow, fHigh; + double dVal; + int iRet; - self = (pLin2Ang)pData; - assert(self); - assert(pCon); + self = (pLin2Ang) pData; + assert(self); + assert(pCon); - /* without parameter: give value */ - if(argc < 2) - { - fVal = L2AGetValue(self,pCon); - sprintf(pBueffel,"%s = %f",argv[0],fVal); - SCWrite(pCon,pBueffel,eError); - return 1; - } - - /* interpret commands */ - strtolower(argv[1]); - if(strcmp(argv[1],"length") == 0) - { - if(argc >= 3) - { - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK) - { - SCWrite(pCon,"ERROR: length parameter not recognised as number", - eError); - return 0; - } - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: Insufficient privilege to change length", - eError); - return 0; - } - self->length = dVal; - SCSendOK(pCon); - return 1; - } - else - { - sprintf(pBueffel,"%s.length = %f",argv[0],self->length); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } -/* zero point */ - if(strcmp(argv[1],"softzero") == 0) - { - if(argc >= 3) - { - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK) - { - SCWrite(pCon,"ERROR: softzero parameter not recognised as number", - eError); - return 0; - } - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: Insufficient privilege to change softzero point", - eError); - return 0; - } - self->zero = dVal; - SCSendOK(pCon); - return 1; - } - else - { - sprintf(pBueffel,"%s.softzero = %f",argv[0],self->zero); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } -/* limits */ - if(strstr(argv[1],"lim") != NULL) - { - MotorGetPar(self->lin,"softupperlim",&fHigh); - MotorGetPar(self->lin,"softlowerlim",&fLow); - fHigh = x2ang(self,fHigh); - fLow = x2ang(self,fLow); - sprintf(pBueffel,"%s.limits: %f %f\n change through motor limits ", - argv[0],fLow,fHigh); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - sprintf(pBueffel,"ERROR: method %s not found!",argv[1]); - SCWrite(pCon, pBueffel,eError); - return 0; + /* without parameter: give value */ + if (argc < 2) { + fVal = L2AGetValue(self, pCon); + sprintf(pBueffel, "%s = %f", argv[0], fVal); + SCWrite(pCon, pBueffel, eError); + return 1; } + /* interpret commands */ + strtolower(argv[1]); + if (strcmp(argv[1], "length") == 0) { + if (argc >= 3) { + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + SCWrite(pCon, "ERROR: length parameter not recognised as number", + eError); + return 0; + } + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: Insufficient privilege to change length", + eError); + return 0; + } + self->length = dVal; + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "%s.length = %f", argv[0], self->length); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } +/* zero point */ + if (strcmp(argv[1], "softzero") == 0) { + if (argc >= 3) { + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + SCWrite(pCon, "ERROR: softzero parameter not recognised as number", + eError); + return 0; + } + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, + "ERROR: Insufficient privilege to change softzero point", + eError); + return 0; + } + self->zero = dVal; + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "%s.softzero = %f", argv[0], self->zero); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } +/* limits */ + if (strstr(argv[1], "lim") != NULL) { + MotorGetPar(self->lin, "softupperlim", &fHigh); + MotorGetPar(self->lin, "softlowerlim", &fLow); + fHigh = x2ang(self, fHigh); + fLow = x2ang(self, fLow); + sprintf(pBueffel, "%s.limits: %f %f\n change through motor limits ", + argv[0], fLow, fHigh); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + sprintf(pBueffel, "ERROR: method %s not found!", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; +} diff --git a/lin2ang.h b/lin2ang.h index fcd2c5a3..8541d829 100644 --- a/lin2ang.h +++ b/lin2ang.h @@ -13,11 +13,10 @@ #define LIN2ANG #include "motor.h" - int MakeLin2Ang(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int Lin2AngAction(SConnection *pCon, SicsInterp *pSics, void *pData, +int MakeLin2Ang(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int Lin2AngAction(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]); #endif - diff --git a/lld.c b/lld.c index 0c6ce124..63f295ba 100644 --- a/lld.c +++ b/lld.c @@ -26,26 +26,24 @@ /_|__| A.Reitsma, Delft, The Netherlands. / | \ --------------------------------------------------------------- */ -#include /* variable arg handling */ -#include /* debugging */ -#include "defines.h" /* debugging incl MALLOC (re-) definition */ -#include "lld.h" /* also includes portable.h if necessary */ +#include /* variable arg handling */ +#include /* debugging */ +#include "defines.h" /* debugging incl MALLOC (re-) definition */ +#include "lld.h" /* also includes portable.h if necessary */ -#define NO_PROBLEMS LIST_NO_PROBLEMS /* local redefinition */ +#define NO_PROBLEMS LIST_NO_PROBLEMS /* local redefinition */ -struct Node -{ - struct Node * next; - struct Node * prev; - int data; /* also place-holder for larger items. */ -}; /* actual nodes have various sizes, */ +struct Node { + struct Node *next; + struct Node *prev; + int data; /* also place-holder for larger items. */ +}; /* actual nodes have various sizes, */ /* but a fixed size within a list. */ -struct ListHead -{ - struct Node * current; /* points to the actual current node */ - struct Node * first; /* always points to dummy head node */ - struct Node * last; /* always points to dummy tail node */ - int itemsize ; /* zero value: used as 'list not used' flag */ +struct ListHead { + struct Node *current; /* points to the actual current node */ + struct Node *first; /* always points to dummy head node */ + struct Node *last; /* always points to dummy tail node */ + int itemsize; /* zero value: used as 'list not used' flag */ }; #define ERR_MEMORY -1 @@ -59,642 +57,590 @@ struct ListHead /* ---- Local data ---------------------------------------------------- */ -static struct ListHead * ListControl = NULL; +static struct ListHead *ListControl = NULL; static unsigned int ListCount = 0; /* ---- LL system mangement ------------------------------------------- */ -static int ListInit( int List, int ItemSize ) +static int ListInit(int List, int ItemSize) { - struct Node * Tmp ; + struct Node *Tmp; - if( 0 != ItemSize ) - { - /* create dummy head node - */ - Fortify_CheckAllMemory(); - Tmp = NODE_MALLOC( List ); - if( NULL == Tmp ) - { - return ERR_MEMORY ; - } - Tmp->prev = NULL ; /* NULL identifies it as dummy head node */ - Tmp->data = 0xA709 ; /* dummy value */ - ListControl[ List ].first = Tmp ; - - /* create dummy tail node - */ - Tmp = NODE_MALLOC( List ); - if( NULL == Tmp ) - { - NODE_FREE( Tmp ); /* no need to cause memory leaks */ - ListControl[ List ].first = NULL ; /* or other errors */ - return ERR_MEMORY ; /* even if we're in trouble ... */ - } - Tmp->next = NULL ; /* NULL identifies it as dummy tail node */ - Tmp->data = 0xA725 ; /* dummy value */ - Tmp->prev = ListControl[ List ].first ; - - ListControl[ List ].current = - ListControl[ List ].last = - ListControl[ List ].first->next = Tmp ; - } - else - { - ListControl[ List ].current = - ListControl[ List ].first = - ListControl[ List ].last = NULL ; + if (0 != ItemSize) { + /* create dummy head node + */ + Fortify_CheckAllMemory(); + Tmp = NODE_MALLOC(List); + if (NULL == Tmp) { + return ERR_MEMORY; } + Tmp->prev = NULL; /* NULL identifies it as dummy head node */ + Tmp->data = 0xA709; /* dummy value */ + ListControl[List].first = Tmp; - ListControl[ List ].itemsize = ItemSize ; /* zero: list not used */ - return NO_PROBLEMS ; + /* create dummy tail node + */ + Tmp = NODE_MALLOC(List); + if (NULL == Tmp) { + NODE_FREE(Tmp); /* no need to cause memory leaks */ + ListControl[List].first = NULL; /* or other errors */ + return ERR_MEMORY; /* even if we're in trouble ... */ + } + Tmp->next = NULL; /* NULL identifies it as dummy tail node */ + Tmp->data = 0xA725; /* dummy value */ + Tmp->prev = ListControl[List].first; + + ListControl[List].current = + ListControl[List].last = ListControl[List].first->next = Tmp; + } else { + ListControl[List].current = + ListControl[List].first = ListControl[List].last = NULL; + } + + ListControl[List].itemsize = ItemSize; /* zero: list not used */ + return NO_PROBLEMS; } -int LLDsystemInit( int ListCountInit ) +int LLDsystemInit(int ListCountInit) { - assert( (unsigned) ( ListCountInit -1 ) <= 20 -1 ); - /* negative is logic error (cast => neg. is large int) */ - /* higher than 20 is ridiculous for an initial setup */ - /* zero is useless */ + assert((unsigned) (ListCountInit - 1) <= 20 - 1); + /* negative is logic error (cast => neg. is large int) */ + /* higher than 20 is ridiculous for an initial setup */ + /* zero is useless */ - if( NULL != ListControl ) - { - return NO_PROBLEMS ; /* LL system already initialized */ - } + if (NULL != ListControl) { + return NO_PROBLEMS; /* LL system already initialized */ + } - ListControl = MALLOC( ListCountInit, struct ListHead ); - if( NULL == ListControl ) - { - return ERR_MEMORY ; - } - /* MK */ - memset(ListControl,0,ListCountInit*sizeof(struct ListHead)); + ListControl = MALLOC(ListCountInit, struct ListHead); + if (NULL == ListControl) { + return ERR_MEMORY; + } + /* MK */ + memset(ListControl, 0, ListCountInit * sizeof(struct ListHead)); - for( ListCount = 0 ; ListCount < (unsigned)ListCountInit ; ListCount++ ) - ListInit( ListCount, 0 ); /* just mark it as usable ... */ + for (ListCount = 0; ListCount < (unsigned) ListCountInit; ListCount++) + ListInit(ListCount, 0); /* just mark it as usable ... */ - /* ListCount is now ListCountInit */ - assert( ListCount == (unsigned)ListCountInit ); + /* ListCount is now ListCountInit */ + assert(ListCount == (unsigned) ListCountInit); - return NO_PROBLEMS; + return NO_PROBLEMS; } int LLDsystemClose(void) { - if(ListControl) - { + if (ListControl) { free(ListControl); } ListControl = NULL; return 1; } -int LLDcreate( int ItemSize ) +int LLDcreate(int ItemSize) { - int List ; + int List; - assert( (unsigned) ( ItemSize -1 ) < 1024 -1 ) ; - /* limit to 1kB. A size of 0 is ridiculous */ + assert((unsigned) (ItemSize - 1) < 1024 - 1); + /* limit to 1kB. A size of 0 is ridiculous */ - /* trigger automatic system initialisation if neccesary - */ - if( NULL == ListControl && 0 != LLDsystemInit( 1 )) - { - return ERR_MEMORY ; + /* trigger automatic system initialisation if neccesary + */ + if (NULL == ListControl && 0 != LLDsystemInit(1)) { + return ERR_MEMORY; + } + + /* Look for empty slot + */ + for (List = 0; List < (int) ListCount; List++) { + if (0 == ListControl[List].itemsize) + break; + } + + /* What if NO EMPTY slot ??? + */ + if (List == (int) ListCount) { + struct ListHead *tmp; /* ListControl expansion needed */ + + tmp = MALLOC(ListCount + 1, struct ListHead); + if (NULL == tmp) { + return ERR_MEMORY; } + /* MK */ + memset(tmp, 0, (ListCount + 1) * sizeof(struct ListHead)); - /* Look for empty slot - */ - for( List = 0; List < (int)ListCount; List++ ) - { - if( 0 == ListControl[ List ].itemsize ) - break; - } + memcpy(tmp, ListControl, ListCount * sizeof(struct ListHead)); + /* MK */ + free(ListControl); + ListControl = tmp; + ListCount++; + } - /* What if NO EMPTY slot ??? - */ - if( List == (int)ListCount ) - { - struct ListHead * tmp ; /* ListControl expansion needed */ + /* create dummy head node and set up ListControl for the list. + */ + if (ERR_MEMORY == ListInit(List, ItemSize)) { + return ERR_MEMORY; + } - tmp = MALLOC( ListCount + 1, struct ListHead ); - if( NULL == tmp ) - { - return ERR_MEMORY ; - } - /* MK */ - memset(tmp,0,(ListCount+1)*sizeof(struct ListHead)); - - memcpy( tmp, ListControl, ListCount * sizeof( struct ListHead )); - /* MK */ - free(ListControl); - ListControl = tmp ; - ListCount++ ; - } - - /* create dummy head node and set up ListControl for the list. - */ - if( ERR_MEMORY == ListInit( List, ItemSize )) - { - return ERR_MEMORY ; - } - - return List ; + return List; } -void LLDdelete( int List ) +void LLDdelete(int List) { - struct Node * Tmp ; - struct Node * Old ; + struct Node *Tmp; + struct Node *Old; - assert( (unsigned) List < ListCount ); + assert((unsigned) List < ListCount); - if(ListControl == NULL) - { - return; - } - Tmp = ListControl[ List ].first ; /* dummies are also deleted !!! */ - while( NULL != Tmp ) /* still assuming last node has */ - { /* a NULL next pointer ... */ - Old = Tmp ; - Tmp = Old->next; - NODE_FREE( Old ); /* data already presumed to be deleted */ - } + if (ListControl == NULL) { + return; + } + Tmp = ListControl[List].first; /* dummies are also deleted !!! */ + while (NULL != Tmp) { /* still assuming last node has *//* a NULL next pointer ... */ + Old = Tmp; + Tmp = Old->next; + NODE_FREE(Old); /* data already presumed to be deleted */ + } - ListInit( List, 0 ); /* 0: mark list as not used. */ + ListInit(List, 0); /* 0: mark list as not used. */ - return ; + return; } /* ---- LL system maintenance ----------------------------------------- */ -int LLDcheck( int List ) +int LLDcheck(int List) { - if( NULL == ListControl ) - { - return LIST_SYSTEM_NULL ; + if (NULL == ListControl) { + return LIST_SYSTEM_NULL; + } + + if ((unsigned) List >= ListCount) { + return LIST_INV_NUMBER; + } + + if (0 == ListControl[List].itemsize) { + return LIST_NOT_CREATED; + } + + if (NULL == ListControl[List].first || NULL == ListControl[List].first->next /* missing tail ? */ + || NULL != ListControl[List].first->prev) { + return LIST_ERR_HEAD; + } + + /* Validate current pointer + */ + if (NULL == ListControl[List].current) { + return LIST_CORRUPT7; /* shouldn't be NULL with a good head */ + } + + if (NULL != ListControl[List].first->next->next) { /* empty list ? *//* not empty. */ + struct Node *tmp = ListControl[List].first; + + if (NULL == ListControl[List].current->next) { + return LIST_CORRUPT6; /* a NULL next pointer is only valid */ } - if( (unsigned) List >= ListCount ) - { - return LIST_INV_NUMBER ; + /* for an empty list. */ + /* look for .current in list, + checking the .prev links along the way + */ + do { + tmp = tmp->next; + + if (NULL == tmp || NULL == tmp->prev || tmp != tmp->prev->next) { + return LIST_CORRUPT5; /* current not found in list */ + } + /* or link to/from next node */ + /* invalid */ + } while (tmp != ListControl[List].current); + + /* Found .current in list. Also without link errors. + Now look for valid last node pointer in the list, + checking the .prev links along the way + Note that .current itself is never supposed to be equal + to .last (which points to the dummy tail) ! + */ + if (NULL == ListControl[List].last) { + return LIST_ERR_LAST; } - if( 0 == ListControl[ List ].itemsize ) - { - return LIST_NOT_CREATED ; + do { + tmp = tmp->next; + if (NULL == tmp || NULL == tmp->prev || tmp != tmp->prev->next) { + return LIST_CORRUPT4; /* last not found in list */ + } + /* or link to/from prev node */ + /* invalid */ + } while (tmp != ListControl[List].last); + + /* Found .last in list but is it really a valid last pointer? + Note: tmp == .last + */ + if (NULL != tmp->next) { + return LIST_CORRUPT3; } - if( NULL == ListControl[ List ].first - || NULL == ListControl[ List ].first->next /* missing tail ? */ - || NULL != ListControl[ List ].first->prev ) - { - return LIST_ERR_HEAD ; - } + return NO_PROBLEMS; + } - /* Validate current pointer - */ - if( NULL == ListControl[ List ].current ) - { - return LIST_CORRUPT7 ; /* shouldn't be NULL with a good head */ - } + /* .first->next->next == NULL => list is empty + */ + if (ListControl[List].current != ListControl[List].first->next) { + return LIST_CORRUPT2; + } - if( NULL != ListControl[ List ].first->next->next ) /* empty list ? */ - { /* not empty. */ - struct Node * tmp = ListControl[ List ].first ; + if (ListControl[List].last != ListControl[List].first->next + || ListControl[List].last != ListControl[List].current->prev->next) { + return LIST_CORRUPT1; + } - if( NULL == ListControl[ List ].current->next ) - { - return LIST_CORRUPT6 ; /* a NULL next pointer is only valid */ - } /* for an empty list. */ - - /* look for .current in list, - checking the .prev links along the way - */ - do - { - tmp = tmp->next ; - - if( NULL == tmp || NULL == tmp->prev - || tmp != tmp->prev->next ) - { - return LIST_CORRUPT5 ; /* current not found in list */ - } /* or link to/from next node */ - /* invalid */ - }while( tmp != ListControl[ List ].current ); - - /* Found .current in list. Also without link errors. - Now look for valid last node pointer in the list, - checking the .prev links along the way - Note that .current itself is never supposed to be equal - to .last (which points to the dummy tail) ! - */ - if( NULL == ListControl[ List ].last ) - { - return LIST_ERR_LAST ; - } - - do - { - tmp = tmp->next ; - if( NULL == tmp || NULL == tmp->prev - || tmp != tmp->prev->next ) - { - return LIST_CORRUPT4 ; /* last not found in list */ - } /* or link to/from prev node */ - /* invalid */ - }while( tmp != ListControl[ List ].last ); - - /* Found .last in list but is it really a valid last pointer? - Note: tmp == .last - */ - if( NULL != tmp->next ) - { - return LIST_CORRUPT3 ; - } - - return NO_PROBLEMS ; - } - - /* .first->next->next == NULL => list is empty - */ - if( ListControl[ List ].current != ListControl[ List ].first->next ) - { - return LIST_CORRUPT2 ; - } - - if( ListControl[ List ].last != ListControl[ List ].first->next - || ListControl[ List ].last - != ListControl[ List ].current->prev->next ) - { - return LIST_CORRUPT1 ; - } - - return LIST_EMPTY ; + return LIST_EMPTY; } /* ---- node management ----------------------------------------------- */ -int LLDnodeInsert( int List, ... ) /* insert _BEFORE_ current node */ +int LLDnodeInsert(int List, ...) +{ /* insert _BEFORE_ current node */ + va_list DataPtr; + int Retval; + + /* set DataPtr to the address of "..." + then action, cleanup and return. + */ + va_start(DataPtr, List); + + Retval = LLDnodeInsertFrom(List, (void *) va_arg(DataPtr, void *)); + + va_end(DataPtr); + return Retval; +} + +int LLDnodeAdd(int List, ...) +{ /* insert _AFTER_ current node */ + va_list DataPtr; + int Retval; + + /* set DataPtr to the address of "..." + then action, cleanup and return. + */ + va_start(DataPtr, List); + + Retval = LLDnodeAddFrom(List, (void *) va_arg(DataPtr, void *)); + + va_end(DataPtr); + return Retval; +} + +int LLDnodePrepend(int List, ...) +{ /* insert as first node */ + va_list DataPtr; + int Retval; + + /* set DataPtr to the address of "..." + then action, cleanup and return. + */ + va_start(DataPtr, List); + + Retval = LLDnodePrependFrom(List, (void *) va_arg(DataPtr, void *)); + + va_end(DataPtr); + return Retval; +} + +int LLDnodeAppend(int List, ...) +{ /* insert as last node */ + va_list DataPtr; + int Retval; + + /* set DataPtr to the address of "..." + then action, cleanup and return. + */ + va_start(DataPtr, List); + + Retval = LLDnodeAppendFrom(List, (void *) va_arg(DataPtr, void *)); + + va_end(DataPtr); + return Retval; +} + +int LLDnodeInsertFrom(int List, void *Source) +{ /* insert _BEFORE_ current node */ + struct Node *New; + + assert((unsigned) List < ListCount); + + /* create new node if possible + */ + New = NODE_MALLOC(List); + if (NULL == New) { + return ERR_MEMORY; + } + + /* fill node with data, link to next and previous nodes + and adjust current node pointer + */ + memcpy(&New->data, Source, ListControl[List].itemsize); + New->next = ListControl[List].current; + New->prev = ListControl[List].current->prev; + + ListControl[List].current->prev = New; + New->prev->next = New; + + ListControl[List].current = New; + + return NO_PROBLEMS; +} + +int LLDnodeAddFrom(int List, void *Source) +{ /* insert _AFTER_ current node */ + struct Node *New; + + assert((unsigned) List < ListCount); + + /* create new node if possible + */ + New = NODE_MALLOC(List); + if (NULL == New) { + return ERR_MEMORY; + } + + /* fill node with data and link to next and previous nodes + with special handling when the current node pointer points + to the dummy tail node: i.e it is an empty list. + (the same case in a non-empty list is made not to occur.) + */ + memcpy(&New->data, Source, ListControl[List].itemsize); + + if (NULL != ListControl[List].current->next) + ListControl[List].current = ListControl[List].current->next; + + New->next = ListControl[List].current; + New->prev = ListControl[List].current->prev; + + ListControl[List].current->prev = New; + New->prev->next = New; + + ListControl[List].current = New; + + return NO_PROBLEMS; +} + +int LLDnodePrependFrom(int List, void *Source) +{ /* insert as first node */ + struct Node *New; + + assert((unsigned) List < ListCount); + + /* create new node if possible + */ + New = NODE_MALLOC(List); + if (NULL == New) { + return ERR_MEMORY; + } + + /* fill node with data and link to dummy head and actual first nodes + */ + memcpy(&New->data, Source, ListControl[List].itemsize); + New->prev = ListControl[List].first; /* == .first->next->prev */ + New->next = ListControl[List].first->next; + + ListControl[List].first->next = New; + New->next->prev = New; + + /* Prevent .current from pointing at the dummy tail + (New is the only normal node...) + */ + if (NULL == ListControl[List].current->next) + ListControl[List].current = New; + + return NO_PROBLEMS; +} + +int LLDnodeAppendFrom(int List, void *Source) +{ /* insert as last node */ + struct Node *New; + + assert((unsigned) List < ListCount); + + /* create new node if possible + */ + New = NODE_MALLOC(List); + if (NULL == New) { + return ERR_MEMORY; + } + + /* fill node with data and link to dummy tail and actual last nodes + */ + memcpy(&New->data, Source, ListControl[List].itemsize); + New->next = ListControl[List].last; /* == .last->prev->next */ + New->prev = ListControl[List].last->prev; + + ListControl[List].last->prev = New; + New->prev->next = New; + + /* Prevent .current from pointing at the dummy tail + (New is the only normal node...) + */ + if (NULL == ListControl[List].current->next) + ListControl[List].current = New; + + return NO_PROBLEMS; +} + +void LLDnodeDelete(int List) { - va_list DataPtr ; - int Retval ; + struct Node *Old = ListControl[List].current; - /* set DataPtr to the address of "..." - then action, cleanup and return. - */ - va_start( DataPtr, List ); + assert((unsigned) List < ListCount); - Retval = LLDnodeInsertFrom( List, (void *)va_arg(DataPtr,void *) ); + if (NULL == ListControl[List].current->next) { + return; /* don't delete dummy tail node (list is empty) */ + } - va_end( DataPtr ); - return Retval ; + /* adjust links + */ + Old->prev->next = Old->next; + Old->next->prev = Old->prev; + + /* adjust current node pointer + prevent it from pointing to the dummy tail node + */ + if (NULL != Old->next->next) + ListControl[List].current = Old->next; + else + ListControl[List].current = Old->prev; + + NODE_FREE(Old); + + return; } -int LLDnodeAdd( int List, ... ) /* insert _AFTER_ current node */ -{ - va_list DataPtr ; - int Retval ; +int LLDnodeFind(int List, CompFunPtr Compare, void *DataPtr) +{ /* FindFirst/FindNext format may be needed ... */ + int RetVal; - /* set DataPtr to the address of "..." - then action, cleanup and return. - */ - va_start( DataPtr, List ); + assert((unsigned) List < ListCount); - Retval = LLDnodeAddFrom( List, (void *)va_arg(DataPtr,void *) ); + if (NULL == ListControl[List].first->next->next) { /* empty list ? */ + return 2; /* a compare usually returns just -1, 0 or 1 !!! */ + } - va_end( DataPtr ); - return Retval ; -} + /* note: current->next will never be NULL in a non-empty list */ -int LLDnodePrepend( int List, ... ) /* insert as first node */ -{ - va_list DataPtr ; - int Retval ; - - /* set DataPtr to the address of "..." - then action, cleanup and return. - */ - va_start( DataPtr, List ); - - Retval = LLDnodePrependFrom( List, (void *)va_arg(DataPtr,void *) ); - - va_end( DataPtr ); - return Retval ; -} - -int LLDnodeAppend( int List, ... ) /* insert as last node */ -{ - va_list DataPtr ; - int Retval ; - - /* set DataPtr to the address of "..." - then action, cleanup and return. - */ - va_start( DataPtr, List ); - - Retval = LLDnodeAppendFrom( List, (void *)va_arg(DataPtr,void *) ); - - va_end( DataPtr ); - return Retval ; -} - -int LLDnodeInsertFrom( int List, void * Source ) -{ /* insert _BEFORE_ current node */ - struct Node * New ; - - assert( (unsigned) List < ListCount ); - - /* create new node if possible - */ - New = NODE_MALLOC( List ); - if( NULL == New ) - { - return ERR_MEMORY ; + if (NULL == Compare) { /* default to memcmp with .itemsize */ + while (0 != (RetVal = memcmp(DataPtr, + &ListControl[List].current->data, + ListControl[List].itemsize)) + && NULL != ListControl[List].current->next->next) { + ListControl[List].current = ListControl[List].current->next; } - - /* fill node with data, link to next and previous nodes - and adjust current node pointer - */ - memcpy( & New->data, Source, ListControl[ List ].itemsize ); - New->next = ListControl[ List ].current; - New->prev = ListControl[ List ].current->prev; - - ListControl[ List ].current->prev = New ; - New->prev->next = New ; - - ListControl[ List ].current = New ; - - return NO_PROBLEMS; -} - -int LLDnodeAddFrom( int List, void * Source ) -{ /* insert _AFTER_ current node */ - struct Node * New ; - - assert( (unsigned) List < ListCount ); - - /* create new node if possible - */ - New = NODE_MALLOC( List ); - if( NULL == New ) - { - return ERR_MEMORY ; - } - - /* fill node with data and link to next and previous nodes - with special handling when the current node pointer points - to the dummy tail node: i.e it is an empty list. - (the same case in a non-empty list is made not to occur.) - */ - memcpy( & New->data, Source, ListControl[ List ].itemsize ); - - if( NULL != ListControl[ List ].current->next ) - ListControl[ List ].current = ListControl[ List ].current->next ; - - New->next = ListControl[ List ].current; - New->prev = ListControl[ List ].current->prev; - - ListControl[ List ].current->prev = New ; - New->prev->next = New ; - - ListControl[ List ].current = New ; - - return NO_PROBLEMS; -} - -int LLDnodePrependFrom( int List, void * Source ) -{ /* insert as first node */ - struct Node * New ; - - assert( (unsigned) List < ListCount ); - - /* create new node if possible - */ - New = NODE_MALLOC( List ); - if( NULL == New ) - { - return ERR_MEMORY ; - } - - /* fill node with data and link to dummy head and actual first nodes - */ - memcpy( & New->data, Source, ListControl[ List ].itemsize ); - New->prev = ListControl[ List ].first; /* == .first->next->prev */ - New->next = ListControl[ List ].first->next; - - ListControl[ List ].first->next = New; - New->next->prev = New ; - - /* Prevent .current from pointing at the dummy tail - (New is the only normal node...) - */ - if( NULL == ListControl[ List ].current->next ) - ListControl[ List ].current = New; - - return NO_PROBLEMS; -} - -int LLDnodeAppendFrom( int List, void * Source ) -{ /* insert as last node */ - struct Node * New ; - - assert( (unsigned) List < ListCount ); - - /* create new node if possible - */ - New = NODE_MALLOC( List ); - if( NULL == New ) - { - return ERR_MEMORY ; - } - - /* fill node with data and link to dummy tail and actual last nodes - */ - memcpy( & New->data, Source, ListControl[ List ].itemsize ); - New->next = ListControl[ List ].last ; /* == .last->prev->next */ - New->prev = ListControl[ List ].last->prev; - - ListControl[ List ].last->prev = New ; - New->prev->next = New ; - - /* Prevent .current from pointing at the dummy tail - (New is the only normal node...) - */ - if( NULL == ListControl[ List ].current->next ) - ListControl[ List ].current = New; - - return NO_PROBLEMS; -} - -void LLDnodeDelete( int List ) -{ - struct Node * Old = ListControl[ List ].current ; - - assert( (unsigned) List < ListCount ); - - if( NULL == ListControl[ List ].current->next ) - { - return ; /* don't delete dummy tail node (list is empty) */ - } - - /* adjust links - */ - Old->prev->next = Old->next ; - Old->next->prev = Old->prev ; - - /* adjust current node pointer - prevent it from pointing to the dummy tail node - */ - if( NULL != Old->next->next ) - ListControl[ List ].current = Old->next ; - else - ListControl[ List ].current = Old->prev ; - - NODE_FREE( Old ); - - return ; -} - -int LLDnodeFind( int List, CompFunPtr Compare, void * DataPtr ) -{ /* FindFirst/FindNext format may be needed ... */ - int RetVal ; - - assert( (unsigned) List < ListCount ); - - if( NULL == ListControl[ List ].first->next->next ) /* empty list ? */ - { - return 2; /* a compare usually returns just -1, 0 or 1 !!! */ - } - - /* note: current->next will never be NULL in a non-empty list */ - - if( NULL == Compare ) /* default to memcmp with .itemsize */ - { - while( 0 != (RetVal = memcmp( DataPtr, - & ListControl[ List ].current->data, - ListControl[ List ].itemsize )) - && NULL != ListControl[ List ].current->next->next ) - { - ListControl[ List ].current=ListControl[ List ].current->next; - } - return RetVal ; - } - else - { - while( 0 != (RetVal = (*Compare)( DataPtr, - & ListControl[ List ].current->data )) - && NULL != ListControl[ List ].current->next->next ) - { - ListControl[ List ].current=ListControl[ List ].current->next; - } - return RetVal ; + return RetVal; + } else { + while (0 != (RetVal = (*Compare) (DataPtr, + &ListControl[List].current->data)) + && NULL != ListControl[List].current->next->next) { + ListControl[List].current = ListControl[List].current->next; } + return RetVal; + } } /* ---- current node pointer management ------------------------------- */ -int LLDnodePtr2First( int List ) +int LLDnodePtr2First(int List) { - assert( (unsigned) List < ListCount ); + assert((unsigned) List < ListCount); - ListControl[ List ].current = ListControl[ List ].first->next ; + ListControl[List].current = ListControl[List].first->next; - if(ListControl[List].first->next == NULL) - { - return 0; - } + if (ListControl[List].first->next == NULL) { + return 0; + } - return NULL != ListControl[ List ].first->next->next ; + return NULL != ListControl[List].first->next->next; } -int LLDnodePtr2Last( int List ) +int LLDnodePtr2Last(int List) { - assert( (unsigned) List < ListCount ); + assert((unsigned) List < ListCount); - ListControl[ List ].current = ListControl[ List ].last->prev ; + ListControl[List].current = ListControl[List].last->prev; - return NULL != ListControl[ List ].last->prev->prev ; + return NULL != ListControl[List].last->prev->prev; } -int LLDnodePtr2Next( int List ) +int LLDnodePtr2Next(int List) { - assert( (unsigned) List < ListCount ); + assert((unsigned) List < ListCount); - if( NULL == ListControl[ List ].current->next /* empty list ? */ - || NULL == ListControl[ List ].current->next->next ) /* at end ?*/ - { - return 0 ; /* do not allow the current node pointer */ - } /* to point at the dummy tail node ... */ - - ListControl[ List ].current = ListControl[ List ].current->next ; - return 1 ; + if (NULL == ListControl[List].current->next /* empty list ? */ + || NULL == ListControl[List].current->next->next) { /* at end ? */ + return 0; /* do not allow the current node pointer */ + } + /* to point at the dummy tail node ... */ + ListControl[List].current = ListControl[List].current->next; + return 1; } -int LLDnodePtr2Prev( int List ) +int LLDnodePtr2Prev(int List) { - assert( (unsigned) List < ListCount ); + assert((unsigned) List < ListCount); - if( NULL == ListControl[ List ].current->prev /* empty list ? */ - || NULL == ListControl[ List ].current->prev->prev ) /* begin ? */ - { - return 0 ; /* do not allow the current node pointer */ - } /* to point at the dummy head node ... */ - - ListControl[ List ].current = ListControl[ List ].current->prev ; - return 1 ; + if (NULL == ListControl[List].current->prev /* empty list ? */ + || NULL == ListControl[List].current->prev->prev) { /* begin ? */ + return 0; /* do not allow the current node pointer */ + } + /* to point at the dummy head node ... */ + ListControl[List].current = ListControl[List].current->prev; + return 1; } /* ---- stored data management ---------------------------------------- */ -int LLDnodeInt( int List ) +int LLDnodeInt(int List) { - return ListControl[ List ].current->data; + return ListControl[List].current->data; } -long LLDnodeLong( int List ) +long LLDnodeLong(int List) { - return *((long *) &ListControl[ List ].current->data ); + return *((long *) &ListControl[List].current->data); } -float LLDnodeFloat( int List ) +float LLDnodeFloat(int List) { - return *((float *) &ListControl[ List ].current->data ); + return *((float *) &ListControl[List].current->data); } -void * LLDnodePtr( int List ) +void *LLDnodePtr(int List) { - return *((void **) &ListControl[ List ].current->data ); + return *((void **) &ListControl[List].current->data); } -void FAR * LLDnodeFptr( int List ) +void FAR *LLDnodeFptr(int List) { - return *((void FAR **) &ListControl[ List ].current->data ); + return *((void FAR **) &ListControl[List].current->data); } -int LLDnodeDataTo( int List, void * Destination ) +int LLDnodeDataTo(int List, void *Destination) { - if( NULL != Destination ) - { - memcpy( Destination, - & ListControl[ List ].current->data, - ListControl[ List ].itemsize ); - } + if (NULL != Destination) { + memcpy(Destination, + &ListControl[List].current->data, ListControl[List].itemsize); + } - return ListControl[ List ].itemsize ; /* size needed for blob */ + return ListControl[List].itemsize; /* size needed for blob */ } /* added: Mark Koennecke, 7.4.1997 */ -int LLDnodeDataFrom( int List, void *source ) +int LLDnodeDataFrom(int List, void *source) { - if( NULL != source ) - { - memcpy( - & ListControl[ List ].current->data, - source, - ListControl[ List ].itemsize ); - } + if (NULL != source) { + memcpy(&ListControl[List].current->data, + source, ListControl[List].itemsize); + } - return ListControl[ List ].itemsize ; /* size needed for blob */ + return ListControl[List].itemsize; /* size needed for blob */ } /* ==== LLD.c end ==================================================== */ diff --git a/lld.h b/lld.h index c6c6d535..645c39c4 100644 --- a/lld.h +++ b/lld.h @@ -14,54 +14,52 @@ #endif #ifndef LL__ERR_H -#define LL__ERR_H /* same values used in LLS ... */ +#define LL__ERR_H /* same values used in LLS ... */ -enum ListErrors /* return values for LLDcheck() */ -{ /* The highest value is returned */ - - LIST_NO_PROBLEMS, /* All is OK (multiple use) */ - LIST_EMPTY, /* No data available */ - LIST_ERRORS, /* Dummy to separate warnings from */ - /* ---- REAL errors --------------------------- */ - LIST_CORRUPT1, /* invalid last node pointer: != first->next */ - /* (empty list) or link error */ - LIST_CORRUPT2, /* invalid current node pointer: != first->next */ - /* (empty list) */ - LIST_CORRUPT3, /* invalid last node pointer: Not really last. */ - LIST_CORRUPT4, /* invalid last node pointer: Not in list, */ - /* or link error after current node */ - LIST_ERR_LAST, /* invalid last node pointer: NULL */ - LIST_CORRUPT5, /* invalid current node pointer: Not in list, */ - /* or link error before current node */ - LIST_CORRUPT6, /* invalid current->next node pointer: NULL */ - /* although the list is not empty */ - LIST_CORRUPT7, /* NULL current node pointer */ - LIST_ERR_HEAD, /* NULL first node pointer */ - /* or error in head node */ - LIST_NOT_CREATED, /* List deleted or not created */ - LIST_INV_NUMBER, /* List number out of range */ - LIST_SYSTEM_NULL /* List system not intialized */ +enum ListErrors { /* return values for LLDcheck() *//* The highest value is returned */ + LIST_NO_PROBLEMS, /* All is OK (multiple use) */ + LIST_EMPTY, /* No data available */ + LIST_ERRORS, /* Dummy to separate warnings from */ + /* ---- REAL errors --------------------------- */ + LIST_CORRUPT1, /* invalid last node pointer: != first->next */ + /* (empty list) or link error */ + LIST_CORRUPT2, /* invalid current node pointer: != first->next */ + /* (empty list) */ + LIST_CORRUPT3, /* invalid last node pointer: Not really last. */ + LIST_CORRUPT4, /* invalid last node pointer: Not in list, */ + /* or link error after current node */ + LIST_ERR_LAST, /* invalid last node pointer: NULL */ + LIST_CORRUPT5, /* invalid current node pointer: Not in list, */ + /* or link error before current node */ + LIST_CORRUPT6, /* invalid current->next node pointer: NULL */ + /* although the list is not empty */ + LIST_CORRUPT7, /* NULL current node pointer */ + LIST_ERR_HEAD, /* NULL first node pointer */ + /* or error in head node */ + LIST_NOT_CREATED, /* List deleted or not created */ + LIST_INV_NUMBER, /* List number out of range */ + LIST_SYSTEM_NULL /* List system not intialized */ }; -typedef int (*CompFunPtr)( const void *, const void * ); +typedef int (*CompFunPtr) (const void *, const void *); /* simplifies declarations */ #endif #ifndef LLD_H #define LLD_H /* ---- LL system management and maintenance -------------------------- */ -int LLDsystemInit( int ListCount ); +int LLDsystemInit(int ListCount); /* returns -1 on failure. It is not required to call it. */ /* A second call does nothing: ListCount is ignored. */ -int LLDcreate( int ItemSize ); +int LLDcreate(int ItemSize); /* returns list number to use or -1 on failure. */ /* MUST be called before using a list. */ /* Calls LLsystemInit if necessary. */ -void LLDdelete( int List ); /* delete entire list, data is NOT free()'d */ +void LLDdelete(int List); /* delete entire list, data is NOT free()'d */ -int LLDcheck( int List ); /* returns enum ListErrors value */ +int LLDcheck(int List); /* returns enum ListErrors value */ /* its primary purpose is debugging. */ int LLDsystemClose(void); @@ -71,30 +69,30 @@ int LLDsystemClose(void); Each created list has its own -- fixed -- datasize. See LLcreate(). An ellipsis "..." indicates the data to insert. */ -int LLDnodeInsert( int List, ... ); /* insert BEFORE current node */ -int LLDnodeAdd( int List, ... ); /* insert AFTER current node */ +int LLDnodeInsert(int List, ...); /* insert BEFORE current node */ +int LLDnodeAdd(int List, ...); /* insert AFTER current node */ /* a return value of -1 indicates a memory allocation problem. */ /* Functions NOT changing the current node pointer. Especially intended for implementation of Queue's and Stacks. */ -int LLDnodePrepend( int List, ... ); /* insert as first node */ -int LLDnodeAppend( int List, ... ); /* insert as last node */ +int LLDnodePrepend(int List, ...); /* insert as first node */ +int LLDnodeAppend(int List, ...); /* insert as last node */ /* a return value of -1 indicates a memory allocation problem. */ /* The following four functions are essentially the same as the preceeding four. The data is however not passed by value but by reference. */ -int LLDnodeInsertFrom( int List, void * Source ); -int LLDnodeAddFrom( int List, void * Source ); -int LLDnodePrependFrom( int List, void * Source ); -int LLDnodeAppendFrom( int List, void * Source ); +int LLDnodeInsertFrom(int List, void *Source); +int LLDnodeAddFrom(int List, void *Source); +int LLDnodePrependFrom(int List, void *Source); +int LLDnodeAppendFrom(int List, void *Source); -void LLDnodeDelete( int List ); /* remove current node */ +void LLDnodeDelete(int List); /* remove current node */ /* current node ptr moved to next node. UNLESS the deleted node */ /* was the last node: then current ptr moved to previous node */ -int LLDnodeFind( int List, CompFunPtr Compare, void * DataPtr ); +int LLDnodeFind(int List, CompFunPtr Compare, void *DataPtr); /* Find *DataPtr in the List using the *Compare function. */ /* Returns the return value of *Compare. 0 == equal == found. */ /* non-zero == not found. Current node is set to found node. */ @@ -110,25 +108,25 @@ int LLDnodeFind( int List, CompFunPtr Compare, void * DataPtr ); the end of the list, or an empty list. The return value is intended for iteration purposes. I.e. stopping a scan through a list. */ -int LLDnodePtr2First( int List ); -int LLDnodePtr2Last( int List ); -int LLDnodePtr2Next( int List ); -int LLDnodePtr2Prev( int List ); +int LLDnodePtr2First(int List); +int LLDnodePtr2Last(int List); +int LLDnodePtr2Next(int List); +int LLDnodePtr2Prev(int List); /* ---- stored data management ------------------------------------------- return typed data: */ -int LLDnodeInt( int List ); -long LLDnodeLong( int List ); -float LLDnodeFloat( int List ); -void * LLDnodePtr( int List ); -void FAR * LLDnodeFptr( int List ); +int LLDnodeInt(int List); +long LLDnodeLong(int List); +float LLDnodeFloat(int List); +void *LLDnodePtr(int List); +void FAR *LLDnodeFptr(int List); /* 'return' typeless data. The return value is the size of the data. The data is transferred to Destination. If 'Destination' is NULL, the only action is returning the size. */ -int LLDnodeDataTo( int List, void * Destination ); +int LLDnodeDataTo(int List, void *Destination); /* replaces typeless data with source diff --git a/lld_blob.c b/lld_blob.c index 99e560bb..12e0a410 100644 --- a/lld_blob.c +++ b/lld_blob.c @@ -9,138 +9,134 @@ /_|__| A.Reitsma, Delft, The Netherlands. / | \ --------------------------------------------------------------- */ -#include /* for malloc() */ -#include "lld.h" /* the generic LLD functions ... */ -#include "lld_blob.h" /* also includes portable.h if necessary */ +#include /* for malloc() */ +#include "lld.h" /* the generic LLD functions ... */ +#include "lld_blob.h" /* also includes portable.h if necessary */ -struct BlobDesc -{ - void * data ; /* 'data' can be obtained by LLDnodePtr() ! */ - unsigned size ; +struct BlobDesc { + void *data; /* 'data' can be obtained by LLDnodePtr() ! */ + unsigned size; }; #define ERR_MEMORY -1 /* ---- LL blob system mangement -------------------------------------- */ -int LLDblobCreate( void ) +int LLDblobCreate(void) { - return LLDcreate( sizeof( struct BlobDesc )); + return LLDcreate(sizeof(struct BlobDesc)); } /*---------------------------------------------------------------------*/ int LLDdeleteBlob(int List) { - struct BlobDesc Blob ; - int status; - - status = LLDnodePtr2First(List); - while(status == 1){ - LLDnodeDataTo( List, & Blob ); - free(Blob.data); - status = LLDnodePtr2Next(List); - } - LLDdelete(List); - return 1; + struct BlobDesc Blob; + int status; + + status = LLDnodePtr2First(List); + while (status == 1) { + LLDnodeDataTo(List, &Blob); + free(Blob.data); + status = LLDnodePtr2Next(List); + } + LLDdelete(List); + return 1; } + /* ---- LL blob node mangement ---------------------------------------- */ -int LLDblobInsert( int List, void * Source, unsigned Size ) -{ /* insert _BEFORE_ current node */ - struct BlobDesc Blob ; +int LLDblobInsert(int List, void *Source, unsigned Size) +{ /* insert _BEFORE_ current node */ + struct BlobDesc Blob; - Blob.size = Size ; - Blob.data = malloc( Size ); + Blob.size = Size; + Blob.data = malloc(Size); - if( NULL == Blob.data ) - { - return ERR_MEMORY ; - } + if (NULL == Blob.data) { + return ERR_MEMORY; + } - memcpy( Blob.data, Source, Size ); - LLDnodeInsertFrom( List, & Blob ); + memcpy(Blob.data, Source, Size); + LLDnodeInsertFrom(List, &Blob); - return LIST_NO_PROBLEMS ; + return LIST_NO_PROBLEMS; } -int LLDblobAdd( int List, void * Source, unsigned Size ) -{ /* insert _AFTER_ current node */ - struct BlobDesc Blob ; +int LLDblobAdd(int List, void *Source, unsigned Size) +{ /* insert _AFTER_ current node */ + struct BlobDesc Blob; - Blob.size = Size ; - Blob.data = malloc( Size ); + Blob.size = Size; + Blob.data = malloc(Size); - if( NULL == Blob.data ) - { - return ERR_MEMORY ; - } + if (NULL == Blob.data) { + return ERR_MEMORY; + } - memcpy( Blob.data, Source, Size ); - LLDnodeAddFrom( List, & Blob ); + memcpy(Blob.data, Source, Size); + LLDnodeAddFrom(List, &Blob); - return LIST_NO_PROBLEMS ; + return LIST_NO_PROBLEMS; } -int LLDblobPrepend( int List, void * Source, unsigned Size ) -{ /* insert as first node */ - struct BlobDesc Blob ; +int LLDblobPrepend(int List, void *Source, unsigned Size) +{ /* insert as first node */ + struct BlobDesc Blob; - Blob.size = Size ; - Blob.data = malloc( Size ); + Blob.size = Size; + Blob.data = malloc(Size); - if( NULL == Blob.data ) - { - return ERR_MEMORY ; - } + if (NULL == Blob.data) { + return ERR_MEMORY; + } - memcpy( Blob.data, Source, Size ); - LLDnodePrependFrom( List, & Blob ); + memcpy(Blob.data, Source, Size); + LLDnodePrependFrom(List, &Blob); - return LIST_NO_PROBLEMS ; + return LIST_NO_PROBLEMS; } -int LLDblobAppend( int List, void * Source, unsigned Size ) -{ /* insert as last node */ - struct BlobDesc Blob ; +int LLDblobAppend(int List, void *Source, unsigned Size) +{ /* insert as last node */ + struct BlobDesc Blob; - Blob.size = Size ; - Blob.data = malloc( Size ); + Blob.size = Size; + Blob.data = malloc(Size); - if( NULL == Blob.data ) - { - return ERR_MEMORY ; - } + if (NULL == Blob.data) { + return ERR_MEMORY; + } - memcpy( Blob.data, Source, Size ); - LLDnodeAppendFrom( List, & Blob ); + memcpy(Blob.data, Source, Size); + LLDnodeAppendFrom(List, &Blob); - return LIST_NO_PROBLEMS ; + return LIST_NO_PROBLEMS; } -void LLDblobDelete( int List ) +void LLDblobDelete(int List) { - struct BlobDesc Blob ; + struct BlobDesc Blob; - LLDnodeDataTo( List, & Blob ); - free( Blob.data ); + LLDnodeDataTo(List, &Blob); + free(Blob.data); - LLDnodeDelete( List ); + LLDnodeDelete(List); - return ; + return; } /* ---- stored data management ---------------------------------------- */ -unsigned LLDblobData( int List, void * Destination ) +unsigned LLDblobData(int List, void *Destination) { - struct BlobDesc Blob ; + struct BlobDesc Blob; - LLDnodeDataTo( List, & Blob ); + LLDnodeDataTo(List, &Blob); - if( NULL != Destination ) - memcpy( Destination, Blob.data, Blob.size ); + if (NULL != Destination) + memcpy(Destination, Blob.data, Blob.size); - return Blob.size ; /* size needed for blob */ + return Blob.size; /* size needed for blob */ } /* ==== LLD_BLOB.c end =============================================== */ diff --git a/lld_blob.h b/lld_blob.h index 56ceab06..1663e394 100644 --- a/lld_blob.h +++ b/lld_blob.h @@ -17,7 +17,7 @@ /* ---- LL blob system management and maintenance --------------------- */ -int LLDblobCreate( void ); +int LLDblobCreate(void); /* returns list number to use or -1 on failure. */ /* MUST be called before using a list of blobs. */ int LLDdeleteBlob(int List); @@ -26,20 +26,20 @@ int LLDdeleteBlob(int List); Functions changing current node pointer to the new node. A return value of -1 indicates a memory allocation problem. */ -int LLDblobInsert( int List, void * Source, unsigned Size ); +int LLDblobInsert(int List, void *Source, unsigned Size); /* insert BEFORE current node */ -int LLDblobAdd( int List, void * Source, unsigned Size ); +int LLDblobAdd(int List, void *Source, unsigned Size); /* insert AFTER current node */ /* Functions NOT changing the current node pointer. Especially intended for implementation of Queue's and Stacks. */ -int LLDblobPrepend( int List, void * Source, unsigned Size ); +int LLDblobPrepend(int List, void *Source, unsigned Size); /* insert as first node */ -int LLDblobAppend( int List, void * Source, unsigned Size ); +int LLDblobAppend(int List, void *Source, unsigned Size); /* insert as last node */ -void LLDblobDelete( int List ); +void LLDblobDelete(int List); /* remove current node and free() the data. */ /* current node ptr moved to next node. UNLESS the deleted node */ /* was the last node: then current ptr moved to previous node */ @@ -49,6 +49,6 @@ void LLDblobDelete( int List ); The data is transferred to Destination. If 'Destination' is NULL, the only action is returning the size. */ -unsigned LLDblobData( int List, void * Destination ); +unsigned LLDblobData(int List, void *Destination); /* ==== LLD_BLOB.h end =============================================== */ diff --git a/logger.c b/logger.c index 1f9eed5f..fb9c9b49 100644 --- a/logger.c +++ b/logger.c @@ -31,35 +31,42 @@ static Logger *list; static time_t lastLife = 0; static time_t lastWritten = 0; /*--------------------------------------------------------------------------*/ -char *LoggerName(Logger *log) { +char *LoggerName(Logger * log) +{ return log->name; } + /*--------------------------------------------------------------------------*/ -void LoggerSetNumeric(Logger *log, int numeric) { +void LoggerSetNumeric(Logger * log, int numeric) +{ if (log) { log->numeric = numeric; } } + /*--------------------------------------------------------------------------*/ -Logger *LoggerFind(const char *name) { +Logger *LoggerFind(const char *name) +{ Logger *p; p = list; while (p != NULL) { - if (0==strcasecmp(name, p->name)) { + if (0 == strcasecmp(name, p->name)) { return p; } p = p->next; } return NULL; } + /*--------------------------------------------------------------------------*/ #define LASTLOGTXT "#last logging entry at:\n" -time_t LoggerGetLastLife(char *dirarg) { +time_t LoggerGetLastLife(char *dirarg) +{ char path[256], line[32]; FILE *fil; time_t t = 0; - + if (dirarg == NULL) { return lastWritten; } @@ -71,7 +78,7 @@ time_t LoggerGetLastLife(char *dirarg) { fgets(line, sizeof line, fil); t = atol(line); if (t < 1000000000) { - printf("bad lastLife %ld\n", (long)t); + printf("bad lastLife %ld\n", (long) t); } } fclose(fil); @@ -82,23 +89,26 @@ time_t LoggerGetLastLife(char *dirarg) { } /*--------------------------------------------------------------------------*/ -time_t LoggerSetDir(char *dirarg) { +time_t LoggerSetDir(char *dirarg) +{ dir = dirarg; lastLife = LoggerGetLastLife(dir); return lastLife; } + /*--------------------------------------------------------------------------*/ -char *LoggerGetDir(void) { +char *LoggerGetDir(void) +{ char path[256]; FILE *fil; static time_t last; lastWritten = time(NULL); - if (lastWritten != last) { /* do not write more than once per second */ + if (lastWritten != last) { /* do not write more than once per second */ snprintf(path, sizeof path, "%s/lastlife.dat", dir); fil = fopen(path, "w"); if (fil) { - fprintf(fil, "%s%ld\n", LASTLOGTXT, (long)lastWritten); + fprintf(fil, "%s%ld\n", LASTLOGTXT, (long) lastWritten); fclose(fil); } else { printf("can not write %s\n", path); @@ -107,35 +117,42 @@ char *LoggerGetDir(void) { } return dir; } + /*--------------------------------------------------------------------------*/ -int LoggerVarPath(char *dir, char *path, int pathLen, char *name, struct tm *t) { +int LoggerVarPath(char *dir, char *path, int pathLen, char *name, + struct tm *t) +{ int l; - + l = strlen(dir); if (l + strlen(name) + 8 >= pathLen) { - path[0]='\0'; + path[0] = '\0'; return 0; } strcpy(path, dir); strftime(path + l, pathLen - l, "/%Y/", t); l += 6; - for (;*name != '\0'; name++, l++) { + for (; *name != '\0'; name++, l++) { path[l] = tolower(*name); } - path[l] = '/'; l++; + path[l] = '/'; + l++; path[l] = '\0'; return l; } + /*--------------------------------------------------------------------------*/ -int LoggerWrite0(Logger *log, time_t now, int period, char *value) { +int LoggerWrite0(Logger * log, time_t now, int period, char *value) +{ char path[256], stim[32], buf[32]; struct tm tm, lasttm; int l, ext, writeInfo; FILE *fil; time_t beforenow; - + LoggerGetDir(); - if (dir == NULL) return 0; + if (dir == NULL) + return 0; if (now == 0) { printf("now==0\n"); } @@ -146,35 +163,41 @@ int LoggerWrite0(Logger *log, time_t now, int period, char *value) { strftime(path + l, sizeof path - l, "%m-%d.log", &tm); strftime(stim, sizeof stim, "#%Y-%m-%d %H:%M:%S", &tm); - if (period <= 0) period = 1; + if (period <= 0) + period = 1; writeInfo = (tm.tm_isdst != lasttm.tm_isdst || tm.tm_yday != lasttm.tm_yday || (period != log->period && log->numeric)); if (strcmp(value, log->old) != 0 || writeInfo) { - + fil = fopen(path, "r+"); - if (fil == NULL) { /* create new file */ + if (fil == NULL) { /* create new file */ fil = fopen(path, "w+"); - if (fil == NULL) return 0; - fprintf(fil, "%s isdst %d period %d exact %d\n", stim, tm.tm_isdst, period, log->exact); - } else { /* check if file is from today */ + if (fil == NULL) + return 0; + fprintf(fil, "%s isdst %d period %d exact %d\n", stim, tm.tm_isdst, + period, log->exact); + } else { /* check if file is from today */ fgets(buf, sizeof buf, fil); if (0 != strncmp(buf, stim, 11)) { - fclose(fil); /* it was file from an earlier year */ - fil=fopen(path, "w+"); /* overwrite old logfile */ - if (fil == NULL) return 0; - fprintf(fil, "%s isdst %d period %d exact %d\n", stim, tm.tm_isdst, period, log->exact); + fclose(fil); /* it was file from an earlier year */ + fil = fopen(path, "w+"); /* overwrite old logfile */ + if (fil == NULL) + return 0; + fprintf(fil, "%s isdst %d period %d exact %d\n", stim, tm.tm_isdst, + period, log->exact); } else { - fseek(fil, 0, SEEK_END); /* set position to end */ + fseek(fil, 0, SEEK_END); /* set position to end */ if (writeInfo) { - fprintf(fil, "#isdst %d period %d exact %d\n", tm.tm_isdst, period, log->exact); + fprintf(fil, "#isdst %d period %d exact %d\n", tm.tm_isdst, + period, log->exact); } if (log->lastWrite != 0 && now >= log->lastWrite + 2 * period) { /* this is only useful for direct access of the log files */ beforenow = now - period; lasttm = *localtime(&beforenow); if (lasttm.tm_yday == tm.tm_yday) { - strftime(stim, sizeof stim,"%H:%M:%S", &lasttm); + strftime(stim, sizeof stim, "%H:%M:%S", &lasttm); } else { snprintf(stim, sizeof stim, "00:00:00"); } @@ -182,18 +205,19 @@ int LoggerWrite0(Logger *log, time_t now, int period, char *value) { } } } - strftime(stim, sizeof stim,"%H:%M:%S", &tm); + strftime(stim, sizeof stim, "%H:%M:%S", &tm); fprintf(fil, "%s\t%s\n", stim, value); log->lastWrite = now; fclose(fil); - + } log->period = period; l = strlen(value); - if (l >= log->oldsize) { /* increase log->old size, optimized for linux/i386 */ - ext = ((l - log->oldsize)/16 + 1) * 16; - if (ext < log->oldsize / 4) ext += (log->oldsize / 64) * 16; + if (l >= log->oldsize) { /* increase log->old size, optimized for linux/i386 */ + ext = ((l - log->oldsize) / 16 + 1) * 16; + if (ext < log->oldsize / 4) + ext += (log->oldsize / 64) * 16; log->oldsize += ext; free(log->old); log->old = calloc(1, log->oldsize); @@ -205,8 +229,10 @@ int LoggerWrite0(Logger *log, time_t now, int period, char *value) { log->last = now; return 1; } + /*--------------------------------------------------------------------------*/ -int LoggerWrite(Logger *log, time_t now, int period, char *value) { +int LoggerWrite(Logger * log, time_t now, int period, char *value) +{ Logger *p; time_t h0; static int yday = -1; @@ -229,7 +255,7 @@ int LoggerWrite(Logger *log, time_t now, int period, char *value) { /* -- debug logging if dir/debug exists */ l = LoggerVarPath(dir, path, sizeof path, "debug", tm); strftime(path + l, sizeof path - l, "%m-%d.log", tm); - fil=fopen(path, "a"); + fil = fopen(path, "a"); if (fil) { strftime(tim, sizeof tim, "h0 %m-%d %H:%M:%S\n", localtime(&h0)); fputs(tim, fil); @@ -238,99 +264,120 @@ int LoggerWrite(Logger *log, time_t now, int period, char *value) { /* log old values (forced midnight log) */ p = list; while (p != NULL) { - - if (fil) { /* debug logging */ - strftime(tim, sizeof tim, "last %m-%d %H:%M:%S, ", localtime(&p->last)); + + if (fil) { /* debug logging */ + strftime(tim, sizeof tim, "last %m-%d %H:%M:%S, ", + localtime(&p->last)); fputs(tim, fil); - fprintf(fil, "period %d, name %s, old %s\n", p->period, p->name, p->old); + fprintf(fil, "period %d, name %s, old %s\n", p->period, p->name, + p->old); } - + if (p->last < h0 && p->last != 0 && p->period >= 0 && p->old[0] != '\0') { LoggerWrite0(p, h0, p->period, p->old); } p = p->next; } - if (fil) fclose(fil); + if (fil) + fclose(fil); } return LoggerWrite0(log, now, period, value); } + /*--------------------------------------------------------------------------*/ -time_t LoggerLastTime(Logger *log) { +time_t LoggerLastTime(Logger * log) +{ if (log->last != 0 && log->period > 0) { return log->last; } return 0; } + /*--------------------------------------------------------------------------*/ -int LoggerPeriod(Logger *log) { +int LoggerPeriod(Logger * log) +{ return log->period; } + /*--------------------------------------------------------------------------*/ -void LoggerSetPeriod(Logger *log, int period) { +void LoggerSetPeriod(Logger * log, int period) +{ LoggerWrite0(log, time(NULL), period, log->old); } + /*--------------------------------------------------------------------------*/ -void LoggerKill(Logger *log) { +void LoggerKill(Logger * log) +{ /* we do not really free the logger, it might be reused for the same variable later. We set the value to undefined */ - - if (list != NULL) { /* LoggerFreeAll not yet called */ + + if (list != NULL) { /* LoggerFreeAll not yet called */ LoggerWrite(log, time(NULL), 0, ""); } } + /*--------------------------------------------------------------------------*/ -static int LoggerMakeDir(char *path) { +static int LoggerMakeDir(char *path) +{ static char buffer[4096]; struct stat st; int i, lpath, l; char *slash; - + i = stat(path, &st); if (i >= 0) { - if (((st.st_mode >> 12) & 15) != 4) { /* exists, but is no directory */ + if (((st.st_mode >> 12) & 15) != 4) { /* exists, but is no directory */ return 0; } return 1; } - i = mkdir(path, S_IRWXU+S_IRGRP+S_IXGRP+S_IROTH+S_IXOTH); + i = mkdir(path, S_IRWXU + S_IRGRP + S_IXGRP + S_IROTH + S_IXOTH); if (i < 0) { - if (errno != ENOENT) return 0; /* mkdir failed */ + if (errno != ENOENT) + return 0; /* mkdir failed */ snprintf(buffer, sizeof buffer, "%s", path); lpath = strlen(buffer); do { slash = strrchr(buffer, '/'); - if (!slash) return 0; - *slash='\0'; - i = mkdir(buffer, S_IRWXU+S_IRGRP+S_IXGRP+S_IROTH+S_IXOTH); + if (!slash) + return 0; + *slash = '\0'; + i = mkdir(buffer, S_IRWXU + S_IRGRP + S_IXGRP + S_IROTH + S_IXOTH); } while (i < 0 && errno == ENOENT); l = strlen(buffer); - while (lname = strdup(name); if (log->name == NULL) { free(log); @@ -338,30 +385,34 @@ Logger *LoggerMake(char *name, int period, int exact) { } log->period = -1; log->exact = exact; - log->old = calloc(1,12); + log->old = calloc(1, 12); log->oldsize = 12; log->last = 0; log->lastWrite = 0; log->numeric = 1; log->next = list; list = log; - t = time(NULL) -1; + t = time(NULL) - 1; if (lastLife != 0 && lastLife + period < t) { t = lastLife + period; - } - LoggerWrite(log, t, period, ""); /* value was undefined since last life of server */ + } + LoggerWrite(log, t, period, ""); /* value was undefined since last life of server */ } return log; } + /*--------------------------------------------------------------------------*/ -void LoggerFreeAll(void) { +void LoggerFreeAll(void) +{ Logger *p, *next; - + p = list; while (p != NULL) { next = p->next; - if (p->name) free(p->name); - if (p->old) free(p->old); + if (p->name) + free(p->name); + if (p->old) + free(p->old); free(p); p = next; } diff --git a/logger.h b/logger.h index 276a5494..9e9b4d08 100644 --- a/logger.h +++ b/logger.h @@ -13,17 +13,18 @@ Markus Zolliker, Sept 2004 typedef struct Logger Logger; Logger *LoggerMake(char *name, int period, int exact); -void LoggerKill(Logger *log); -int LoggerWrite(Logger *log, time_t now, int period, char *value); -char *LoggerName(Logger *log); -void LoggerSetNumeric(Logger *log, int numeric); +void LoggerKill(Logger * log); +int LoggerWrite(Logger * log, time_t now, int period, char *value); +char *LoggerName(Logger * log); +void LoggerSetNumeric(Logger * log, int numeric); time_t LoggerSetDir(char *dirarg); time_t LoggerGetLastLife(char *dirarg); -void LoggerWriteOld(Logger *log, time_t now); -time_t LoggerLastTime(Logger *log); -int LoggerPeriod(Logger *log); -void LoggerSetPeriod(Logger *log, int period); -int LoggerVarPath(char *dir, char *path, int pathLen, char *name, struct tm *t); +void LoggerWriteOld(Logger * log, time_t now); +time_t LoggerLastTime(Logger * log); +int LoggerPeriod(Logger * log); +void LoggerSetPeriod(Logger * log, int period); +int LoggerVarPath(char *dir, char *path, int pathLen, char *name, + struct tm *t); void LoggerFreeAll(void); #endif diff --git a/logreader.c b/logreader.c index cfa8b618..9ec3146d 100644 --- a/logreader.c +++ b/logreader.c @@ -26,10 +26,10 @@ typedef struct { int exact; CompType type; time_t step; - time_t tlim; /* 0: initial state */ - Point best; /* best point, to be written if tlim > 0 */ - Point written; /* last written point */ - Point last; /* last point */ + time_t tlim; /* 0: initial state */ + Point best; /* best point, to be written if tlim > 0 */ + Point written; /* last written point */ + Point last; /* last point */ char buf[LLEN]; int np; char *none; @@ -38,62 +38,70 @@ typedef struct { int omitEqual; } Compressor; -static char *dirs[MAX_DIRS] = {NULL}; -static int ndirs=0; +static char *dirs[MAX_DIRS] = { NULL }; +static int ndirs = 0; -static void InitCompressor(Compressor *c, SConnection *pCon, time_t step) { +static void InitCompressor(Compressor * c, SConnection * pCon, time_t step) +{ c->pCon = pCon; c->step = step; c->tlim = 0; c->last.y = LOGGER_NAN; c->last.t = 0; - c->buf[0]='\0'; + c->buf[0] = '\0'; c->written.t = 0; c->written.y = LOGGER_NAN; c->omitEqual = 1; } -static void OutFloat(Compressor *c, Point p) { +static void OutFloat(Compressor * c, Point p) +{ char *value; - + if (p.y == LOGGER_NAN) { - if (c->omitEqual && c->written.y == LOGGER_NAN) return; + if (c->omitEqual && c->written.y == LOGGER_NAN) + return; if (c->none) { value = c->none; } else { value = ""; } } else { - if (c->omitEqual && c->written.y == p.y) return; + if (c->omitEqual && c->written.y == p.y) + return; snprintf(c->buf, sizeof(c->buf), "%g", p.y); value = c->buf; } - SCPrintf(c->pCon, eWarning, "%ld %s", (long)(p.t - c->written.t), value); + SCPrintf(c->pCon, eWarning, "%ld %s", (long) (p.t - c->written.t), + value); c->written = p; c->np--; } -static void WriteHeader(Compressor *c) { +static void WriteHeader(Compressor * c) +{ if (c->header) { SCPrintf(c->pCon, eWarning, "*%s period %ld\n", c->header, c->period); c->header = NULL; } } -static void PutValue(Compressor *c, time_t t, char *value) { +static void PutValue(Compressor * c, time_t t, char *value) +{ char *p; Point new; - + WriteHeader(c); if (c->type == NUMERIC) { new.y = strtod(value, &p); if (p == value) { new.y = LOGGER_NAN; } else { - if (new.y == LOGGER_NAN) new.y *= 1.0000002; + if (new.y == LOGGER_NAN) + new.y *= 1.0000002; } new.t = t; - if (t >= c->tlim) { /* a new interval starts */ + if (t >= c->tlim) { /* a new interval starts */ if (c->tlim == 0) { c->tlim = t; } else if (c->best.y != c->written.y) { @@ -107,29 +115,31 @@ static void PutValue(Compressor *c, time_t t, char *value) { } c->tlim = t + c->step; } - } else { /* not the first point */ + } else { /* not the first point */ if (fabs(new.y - c->best.y) > fabs(c->written.y - c->best.y)) { c->best = new; } } c->last = new; } else if (c->type == TEXT) { - if (0 != strncmp(value, c->buf, sizeof(c->buf)-1)) { + if (0 != strncmp(value, c->buf, sizeof(c->buf) - 1)) { snprintf(c->buf, sizeof(c->buf), "%s", value); - SCPrintf(c->pCon, eWarning, "%ld %s\n", (long)(t - c->written.t), value); + SCPrintf(c->pCon, eWarning, "%ld %s\n", (long) (t - c->written.t), + value); c->written.t = t; c->np--; } } } -static void PutFinish(Compressor *c, time_t now) { +static void PutFinish(Compressor * c, time_t now) +{ char value[32]; - - if (c->tlim != 0) { /* there is data already */ + + if (c->tlim != 0) { /* there is data already */ c->omitEqual = 0; if (c->type == NUMERIC) { - if (now > c->last.t + c->period) { /* copy last value to the actual time */ + if (now > c->last.t + c->period) { /* copy last value to the actual time */ if (c->last.y != LOGGER_NAN) { snprintf(value, sizeof value, "%g", c->last.y); PutValue(c, now, value); @@ -138,16 +148,19 @@ static void PutFinish(Compressor *c, time_t now) { OutFloat(c, c->best); /* write last buffered value */ } } - } if (now > c->last.t) { + } + if (now > c->last.t) { PutValue(c, now, c->buf); } } } + /*--------------------------------------------------------------------------*/ -static long getOpt(char *line, int *isdst, int *exact) { +static long getOpt(char *line, int *isdst, int *exact) +{ long lxs; char *opt; - + opt = strstr(line, "isdst"); if (opt) { sscanf(opt, "isdst %d", isdst); @@ -164,67 +177,69 @@ static long getOpt(char *line, int *isdst, int *exact) { return -1; } } + /*--------------------------------------------------------------------------*/ -static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) { +static int LogReader(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ /* Usage: - graph [ none ] np [ ...] - graph text - graph [ ...] - - and are seconds since epoch (unix time) or, if the value - is below one day, a time relative to the actual time - - The is optional. if not given, unknown values are returned as empty strings - - is the maximal number of points to be returned. If more values - are present and the values are numeric, the data is reduced. If the data is not - numeric, the last values may be skipped in order to avoid overflow. - - is the name of a variable (several vaiables may be given). - Note that slashes are converted to dots, and that the first slash is ignored. - - The seconds variant is for text values, which can not be reduced. In any case, all values - are returned. - - The third variant is old style and can be replaced by the first variant, where - = ( - ) / + 2 - - + graph [ none ] np [ ...] + graph text + graph [ ...] + + and are seconds since epoch (unix time) or, if the value + is below one day, a time relative to the actual time + + The is optional. if not given, unknown values are returned as empty strings + + is the maximal number of points to be returned. If more values + are present and the values are numeric, the data is reduced. If the data is not + numeric, the last values may be skipped in order to avoid overflow. + + is the name of a variable (several vaiables may be given). + Note that slashes are converted to dots, and that the first slash is ignored. + + The seconds variant is for text values, which can not be reduced. In any case, all values + are returned. + + The third variant is old style and can be replaced by the first variant, where + = ( - ) / + 2 + + Output format: - First line: returning the actual time on the server (this time is used for relative times) - - For each variable which has data in the given interval, - the variable name is returned preceeded by a '*', followed by some infos* separated with - blanks. - After the header line for every data point a line follows with - a time relative to the last point and the value. - The first time value relative to zero, e.g. absolute. - The data value is valid until the next datapoint. Empty values are returned as an - empty string or as the . - - At the very end * is returned. - is 1, when the data had to be reduced, 0 else - is 1, when overflow occured, 0 else. Overflow may happen only - when np is given and a text variable was demanded. - - *actually only one info exists: period . This is the update rate in seconds. - As equal values are not transmitted, two points (t1,y1) and (t2,y2) with a distance - (t2 - t1) > period should not be connected directly. The plot software should generate - an intermediate point at (t2-period,y1). - - */ + First line: returning the actual time on the server (this time is used for relative times) + + For each variable which has data in the given interval, + the variable name is returned preceeded by a '*', followed by some infos* separated with + blanks. + After the header line for every data point a line follows with + a time relative to the last point and the value. + The first time value relative to zero, e.g. absolute. + The data value is valid until the next datapoint. Empty values are returned as an + empty string or as the . + + At the very end * is returned. + is 1, when the data had to be reduced, 0 else + is 1, when overflow occured, 0 else. Overflow may happen only + when np is given and a text variable was demanded. + + *actually only one info exists: period . This is the update rate in seconds. + As equal values are not transmitted, two points (t1,y1) and (t2,y2) with a distance + (t2 - t1) > period should not be connected directly. The plot software should generate + an intermediate point at (t2-period,y1). + + */ time_t from, to, step, xs, lastt; char *p, *varp; int i, j, iarg, pathLen, iret, loss, np; int inRange; - int yday=0; + int yday = 0; time_t t, startim; struct tm tm; char stim[32], path[LLEN], line[LLEN], lastval[LLEN]; char *lin, *val, *stp; FILE *fil; - Compressor c={0}; + Compressor c = { 0 }; float yy, lasty; CompType type0; DIR *dr; @@ -237,15 +252,18 @@ static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, char *dirPath; int idir; char *colon; - + /* argtolower(argc, argv); */ - if (argc < 4) goto illarg; + if (argc < 4) + goto illarg; now = time(NULL); - from = strtol(argv[1], &p, 0); /* unix time, not year 2038 safe */ - if (p == argv[1]) goto illarg; + from = strtol(argv[1], &p, 0); /* unix time, not year 2038 safe */ + if (p == argv[1]) + goto illarg; to = strtol(argv[2], &p, 0); - if (p == argv[2]) goto illarg; - if (from < ONE_YEAR) { + if (p == argv[2]) + goto illarg; + if (from < ONE_YEAR) { from += now; } if (to < ONE_YEAR) { @@ -253,24 +271,28 @@ static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, } iarg = 3; while (1) { - if (iarg>=argc) goto illarg; - if (strcasecmp(argv[iarg],"text") == 0) { /* non-numeric values */ + if (iarg >= argc) + goto illarg; + if (strcasecmp(argv[iarg], "text") == 0) { /* non-numeric values */ iarg++; step = 1; type0 = TEXT; np = to - from + 2; break; - } else if (strcasecmp(argv[iarg],"none") == 0) { /* none */ + } else if (strcasecmp(argv[iarg], "none") == 0) { /* none */ iarg++; - if (iarg >= argc) goto illarg; + if (iarg >= argc) + goto illarg; c.none = argv[iarg]; iarg++; - } else if (strcasecmp(argv[iarg],"np") == 0) { /* max. number of points */ + } else if (strcasecmp(argv[iarg], "np") == 0) { /* max. number of points */ iarg++; - if (iarg >= argc) goto illarg; + if (iarg >= argc) + goto illarg; type0 = NUMERIC; np = strtol(argv[iarg], &p, 0); - if (p == argv[iarg]) goto illarg; + if (p == argv[iarg]) + goto illarg; iarg++; if (to <= from) { step = 1; @@ -282,20 +304,23 @@ static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, break; } else { step = strtol(argv[iarg], &p, 0); - if (p == argv[iarg]) goto illarg; + if (p == argv[iarg]) + goto illarg; iarg++; - if (step <= 0) step = 1; + if (step <= 0) + step = 1; type0 = NUMERIC; np = (from - to) / step + 2; } } - if (step <= 0) step = 1; - - snprintf(line, sizeof line, "%ld\n", (long)now); + if (step <= 0) + step = 1; + + snprintf(line, sizeof line, "%ld\n", (long) now); SCWrite(pCon, line, eWarning); dirPath = IFindOption(pSICSOptions, "LogReaderPath"); - if (dirPath == NULL) { /* for compatibility, check */ + if (dirPath == NULL) { /* for compatibility, check */ dirs[0] = IFindOption(pSICSOptions, "LoggerDir"); if (dirs[0] == NULL) { SCWrite(pCon, "ERROR: LoggerPath not found", eError); @@ -327,22 +352,23 @@ static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, dirPath = colon + 1; } } - + loss = 0; overflow = 0; - for (i=iarg; i= 0) { @@ -425,10 +452,14 @@ static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, xs = step; } } - lin[0]='\0'; + lin[0] = '\0'; } else { - p = strchr(line, '\n'); if (p) *p='\0'; - p = strchr(line, '#'); if (p) *p='\0'; + p = strchr(line, '\n'); + if (p) + *p = '\0'; + p = strchr(line, '#'); + if (p) + *p = '\0'; } } while (lin[0] == '\0'); } @@ -436,15 +467,15 @@ static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, /* printf(" %s\n", line); */ p = strchr(line, '\t'); if (p) { - *p='\0'; - val = p+1; + *p = '\0'; + val = p + 1; } else { val = ""; } p = strchr(val, '\t'); if (p) { - stp = p+1; - *p='\0'; + stp = p + 1; + *p = '\0'; iret = sscanf(stp, "%ld", &c.period); if (iret == 1) { if (c.period == 0) { @@ -459,19 +490,20 @@ static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, } } } - iret = sscanf(line, "%d:%d:%d", &tm.tm_hour, &tm.tm_min, &tm.tm_sec); + iret = + sscanf(line, "%d:%d:%d", &tm.tm_hour, &tm.tm_min, &tm.tm_sec); if (iret != 3) { lin = NULL; } else { tm.tm_isdst = isdst; - t=mktime(&tm); + t = mktime(&tm); if (!inRange) { if (t < startim) { - lastval[0]='\0'; + lastval[0] = '\0'; strncat(lastval, val, sizeof lastval - 1); lastt = t; } else { - inRange=1; + inRange = 1; if (lastt != 0) { PutValue(&c, lastt, lastval); } @@ -483,11 +515,11 @@ static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, } } if (lin == NULL) { - tm.tm_hour = 24; /* try next day */ + tm.tm_hour = 24; /* try next day */ tm.tm_min = 0; tm.tm_sec = 0; tm.tm_isdst = -1; - startim=mktime(&tm); + startim = mktime(&tm); continue; } } @@ -496,13 +528,14 @@ static int LogReader(SConnection *pCon, SicsInterp *pSics, void *pData, PutValue(&c, lastt, lastval); } } - WriteHeader(&c); /* write header, if not already done */ + WriteHeader(&c); /* write header, if not already done */ PutFinish(&c, nowi); if (fil) { fclose(fil); fil = NULL; } - if (c.np < 0) overflow = 1; + if (c.np < 0) + overflow = 1; } snprintf(line, sizeof line, "*%d %d\n", loss, overflow); SCWrite(pCon, line, eWarning); @@ -511,14 +544,18 @@ illarg: SCWrite(pCon, "illegal argument(s)", eError); return 0; } + /*--------------------------------------------------------------------------*/ -static void KillLogReader(void *data) { +static void KillLogReader(void *data) +{ Logger *p, *next; - + KillDummy(data); LoggerFreeAll(); } + /*--------------------------------------------------------------------------*/ -void LogReaderInit(void) { - AddCommand(pServ->pSics,"Graph",LogReader,KillLogReader,NULL); +void LogReaderInit(void) +{ + AddCommand(pServ->pSics, "Graph", LogReader, KillLogReader, NULL); } diff --git a/logsetup.c b/logsetup.c index 46059917..3ece21a2 100644 --- a/logsetup.c +++ b/logsetup.c @@ -5,7 +5,9 @@ static char *loggerID = "loggerID"; static hdbCallbackReturn LoggerUpdateCallback(pHdb node, - void *userData, pHdbMessage message) { + void *userData, + pHdbMessage message) +{ Logger *logger = userData; pDynString str; SConnection *conn = NULL; @@ -20,32 +22,34 @@ static hdbCallbackReturn LoggerUpdateCallback(pHdb node, } return hdbContinue; } - - if((mm = GetHdbUpdateMessage(message)) == NULL){ + + if ((mm = GetHdbUpdateMessage(message)) == NULL) { return hdbContinue; } - + value = *(mm->v); - + str = formatValue(value, node); LoggerWrite(logger, time(NULL), LoggerPeriod(logger), GetCharArray(str)); DeleteDynString(str); return hdbContinue; } -static int LogSetup(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) { +static int LogSetup(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pHdb node; pHdbCallback cb; - static char basepath[1024]="/"; + static char basepath[1024] = "/"; char buf[1024]; char *p, *name; - static char *loggerDir=NULL; + static char *loggerDir = NULL; int numeric, period; Logger *logger; - + if (argc < 2) { - SCPrintf(pCon, eError, "ERROR: should be: logsetup [ []]"); + SCPrintf(pCon, eError, + "ERROR: should be: logsetup [ []]"); return 0; } if (strcasecmp(argv[1], "basepath") == 0) { @@ -57,7 +61,8 @@ static int LogSetup(SConnection *pCon, SicsInterp *pSics, void *pData, } if (loggerDir == NULL) { loggerDir = IFindOption(pSICSOptions, "LoggerDir"); - if (loggerDir == NULL) loggerDir="./"; + if (loggerDir == NULL) + loggerDir = "./"; LoggerSetDir(loggerDir); } if (strcasecmp(argv[1], "directory") == 0) { @@ -82,10 +87,11 @@ static int LogSetup(SConnection *pCon, SicsInterp *pSics, void *pData, snprintf(buf, sizeof buf, "%s", argv[1]); } for (p = buf; *p != '\0'; p++) { - if (*p =='/') *p = '.'; + if (*p == '/') + *p = '.'; } if (buf[0] == '.') { - name = buf+1; + name = buf + 1; } else { name = buf; } @@ -95,19 +101,21 @@ static int LogSetup(SConnection *pCon, SicsInterp *pSics, void *pData, numeric = 0; } logger = FindHdbCallbackData(node, loggerID); - if (logger != 0) { /* logger exists already, changed only period */ + if (logger != 0) { /* logger exists already, changed only period */ LoggerSetPeriod(logger, period); } else { logger = LoggerMake(name, period, !numeric); LoggerSetNumeric(logger, numeric); - cb = MakeHipadabaCallback(LoggerUpdateCallback, logger, (void (*)(void *))LoggerKill); + cb = MakeHipadabaCallback(LoggerUpdateCallback, logger, + (void (*)(void *)) LoggerKill); assert(cb); AppendHipadabaCallback(node, cb); } - + return 1; } -void LogSetupInit(void) { - AddCmd("LogSetup",LogSetup); +void LogSetupInit(void) +{ + AddCmd("LogSetup", LogSetup); } diff --git a/lomax.c b/lomax.c index 57721a6a..de143672 100644 --- a/lomax.c +++ b/lomax.c @@ -27,265 +27,253 @@ extern float nintf(float f); /*-------------------------------------------------------------------*/ -static int testBoundaries(int xsize, int ysize, int window, - int i, int j) +static int testBoundaries(int xsize, int ysize, int window, int i, int j) { int half; /* - if the window touches the data boundary the result is probably not - very useful. Discarding these cases early on also protects us - against data array overrun problems. - */ + if the window touches the data boundary the result is probably not + very useful. Discarding these cases early on also protects us + against data array overrun problems. + */ - half = window/2; + half = window / 2; - if( i - half < 0 || i + half > xsize) + if (i - half < 0 || i + half > xsize) return 0; - if( j - half < 0 || j + half > ysize) + if (j - half < 0 || j + half > ysize) return 0; return 1; } + /*-------------------------------------------------------------------*/ static int testSteepness(int *iData, int xsize, int ysize, - int i, int j, int window, int steepness) + int i, int j, int window, int steepness) { int testValue, x, y, half; int *iPtr; - + testValue = iData[j * xsize + i] - steepness; - half = window/2; + half = window / 2; /* - test upper row - */ + test upper row + */ iPtr = iData + (j - half) * xsize + i - half; - for(x = 0; x < window; x++) - { - if(iPtr[x] > testValue) + for (x = 0; x < window; x++) { + if (iPtr[x] > testValue) return 0; } /* - test lower row - */ + test lower row + */ iPtr = iData + (j + half) * xsize + i - half; - for(x = 0; x < window; x++) - { - if(iPtr[x] > testValue) + for (x = 0; x < window; x++) { + if (iPtr[x] > testValue) return 0; } /* - test columns - */ - for(y = j - half; y < j + half; y++) - { + test columns + */ + for (y = j - half; y < j + half; y++) { /* - left - */ - if(iData[y*xsize + i - half] > testValue) + left + */ + if (iData[y * xsize + i - half] > testValue) return 0; /* - right - */ - if(iData[y*xsize + i + half] > testValue) + right + */ + if (iData[y * xsize + i + half] > testValue) return 0; } - + return 1; } /*--------------------------------------------------------------------*/ -static int testMaximum(int *iData, int xsize, int ysize, - int i, int j, int window) +static int testMaximum(int *iData, int xsize, int ysize, + int i, int j, int window) { int testValue, x, y, half; int *iPtr; int equalCount = 0; testValue = iData[j * xsize + i]; - half = window/2; + half = window / 2; - for(y = j - half; y < j + half; y++) - { + for (y = j - half; y < j + half; y++) { iPtr = iData + y * xsize + i - half; - for(x = 0; x < window; x++) - { - if(iPtr[x] > testValue) - return 0; - if(iPtr[x] == testValue) - equalCount++; + for (x = 0; x < window; x++) { + if (iPtr[x] > testValue) + return 0; + if (iPtr[x] == testValue) + equalCount++; } } /* - if(equalCount > 3) - { - return 0; - } - */ + if(equalCount > 3) + { + return 0; + } + */ return 1; -} +} + /*--------------------------------------------------------------------*/ -int testLocalMaximum(int *iData, int xsize, int ysize, - int i, int j, - int window, int steepness, int threshold, +int testLocalMaximum(int *iData, int xsize, int ysize, + int i, int j, + int window, int steepness, int threshold, int *intensity) { - if(!testBoundaries(xsize,ysize,window,i,j)) + if (!testBoundaries(xsize, ysize, window, i, j)) return 0; - if(!testMaximum(iData,xsize,ysize,i,j,window)) + if (!testMaximum(iData, xsize, ysize, i, j, window)) return 0; - if(iData[j * xsize + i] < threshold) + if (iData[j * xsize + i] < threshold) return 0; - if(!testSteepness(iData,xsize,ysize,i,j,window, steepness)) + if (!testSteepness(iData, xsize, ysize, i, j, window, steepness)) return 0; *intensity = iData[j * xsize + i]; return 1; -} +} + /*-------------------------------------------------------------------*/ int calculateCOG(int *iData, int xsize, int ysize, - int *i, int *j, int *intensity,int *nCount, - int cogWindow, - float contour) + int *i, int *j, int *intensity, int *nCount, + int cogWindow, float contour) { int x, xLow, xMax, y, yLow, yMax; int threshold; float cogTotal, cogX, cogY; int *iPtr; - if(!testBoundaries(xsize,ysize,cogWindow,*i,*j)) + if (!testBoundaries(xsize, ysize, cogWindow, *i, *j)) return 0; /* - preparations - */ - xLow = *i - cogWindow/2; - if(xLow < 0) + preparations + */ + xLow = *i - cogWindow / 2; + if (xLow < 0) xLow = 0; - xMax = *i + cogWindow/2; - if(xLow >= xsize) - xMax = xsize-1; + xMax = *i + cogWindow / 2; + if (xLow >= xsize) + xMax = xsize - 1; - yLow = *j - cogWindow/2; - if(yLow < 0) + yLow = *j - cogWindow / 2; + if (yLow < 0) yLow = 0; - yMax = *j + cogWindow/2; - if(yLow >= ysize) - yMax = ysize-1; + yMax = *j + cogWindow / 2; + if (yLow >= ysize) + yMax = ysize - 1; - threshold = (int)(float)iData[*j * xsize + *i] * contour; + threshold = (int) (float) iData[*j * xsize + *i] * contour; /* - build the sums - */ + build the sums + */ *nCount = 0; cogTotal = cogY = cogX = .0; - for(y = yLow; y < yMax; y++) - { - iPtr = iData + y *xsize; - for(x = xLow; x < xMax; x++) - { - if(iPtr[x] > threshold) - { - *nCount++; - cogTotal += iPtr[x]; - cogY += y * iPtr[x]; + for (y = yLow; y < yMax; y++) { + iPtr = iData + y * xsize; + for (x = xLow; x < xMax; x++) { + if (iPtr[x] > threshold) { + *nCount++; + cogTotal += iPtr[x]; + cogY += y * iPtr[x]; cogX += x * iPtr[x]; } } } - if(cogTotal <= .0) - { + if (cogTotal <= .0) { return 0; } - *i = (int)nintf(cogX/cogTotal); - *j = (int)nintf(cogY/cogTotal); - *intensity = (int)cogTotal; + *i = (int) nintf(cogX / cogTotal); + *j = (int) nintf(cogY / cogTotal); + *intensity = (int) cogTotal; return 1; } + /*-------------------------------------------------------------------*/ void calculateStatistics(int *iData, int xsize, int ysize, - float *average, float *maximum) + float *average, float *maximum) { int i, iLength; int max = -999999999; long sum = 0; - iLength = xsize*ysize; - for(i = 0; i < iLength; i++) - { + iLength = xsize * ysize; + for (i = 0; i < iLength; i++) { sum += iData[i]; - if(iData[i] > max) + if (iData[i] > max) max = iData[i]; } - *average = (float)sum/(float)iLength; - *maximum = (float)max; + *average = (float) sum / (float) iLength; + *maximum = (float) max; } + /*-------------------------------------------------------------------*/ int wellFormed(int *iData, int xsize, int ysize, - int i, int j, int window, float contour, - int maxBad) + int i, int j, int window, float contour, int maxBad) { int testValue, x, y, half; int *iPtr; - int badCount = 0; + int badCount = 0; - testValue = (int)((float)iData[j * xsize + i]*contour); - half = window/2; + testValue = (int) ((float) iData[j * xsize + i] * contour); + half = window / 2; /* - test upper row - */ + test upper row + */ iPtr = iData + (j - half) * xsize + i - half; - for(x = 0; x < window; x++) - { - if(iPtr[x] > testValue) + for (x = 0; x < window; x++) { + if (iPtr[x] > testValue) badCount++; } /* - test lower row - */ + test lower row + */ iPtr = iData + (j + half) * xsize + i - half; - for(x = 0; x < window; x++) - { - if(iPtr[x] > testValue) + for (x = 0; x < window; x++) { + if (iPtr[x] > testValue) badCount++; } /* - test columns - */ - for(y = j - half; y < j + half; y++) - { + test columns + */ + for (y = j - half; y < j + half; y++) { /* - left - */ - if(iData[y*xsize + i - half] > testValue) + left + */ + if (iData[y * xsize + i - half] > testValue) badCount++; /* - right - */ - if(iData[y*xsize + i + half] > testValue) + right + */ + if (iData[y * xsize + i + half] > testValue) badCount++; } - - if(badCount > maxBad) - { + + if (badCount > maxBad) { return 0; } @@ -293,49 +281,46 @@ int wellFormed(int *iData, int xsize, int ysize, } /*-------------------------------------------------------------------*/ -static int checkHM(pHistMem *pHM, SicsInterp *pSics, SConnection *pCon, +static int checkHM(pHistMem * pHM, SicsInterp * pSics, SConnection * pCon, char *name, int *iDim) { - CommandList *pCom = NULL; - char pBueffel[256]; - int nDim; + CommandList *pCom = NULL; + char pBueffel[256]; + int nDim; - pCom = FindCommand(pSics, name); - if(!pCom) - { - sprintf(pBueffel,"ERROR: histogram memory %s not found", name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!pCom->pData) - { - sprintf(pBueffel,"ERROR: histogram memory %s not found", name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - *pHM = (pHistMem)pCom->pData; - if(!iHasType(*pHM, "HistMem")) - { - sprintf(pBueffel,"ERROR: %s is no histogram memory!", name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* - we now know that we have a histogram memory, now check Sizes - */ - GetHistDim(*pHM,iDim,&nDim); - if(nDim < 2) - { - sprintf(pBueffel,"ERROR: %s is not 2 dimensional!", name); - SCWrite(pCon,pBueffel,eError); - return 0; - } + pCom = FindCommand(pSics, name); + if (!pCom) { + sprintf(pBueffel, "ERROR: histogram memory %s not found", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!pCom->pData) { + sprintf(pBueffel, "ERROR: histogram memory %s not found", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + *pHM = (pHistMem) pCom->pData; + if (!iHasType(*pHM, "HistMem")) { + sprintf(pBueffel, "ERROR: %s is no histogram memory!", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* + we now know that we have a histogram memory, now check Sizes + */ + GetHistDim(*pHM, iDim, &nDim); + if (nDim < 2) { + sprintf(pBueffel, "ERROR: %s is not 2 dimensional!", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } - return 1; + return 1; } + /*--------------------------------------------------------------------*/ -int LoMaxAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) +int LoMaxAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) { pLoMax self = NULL; char pBueffel[256], pNum[20]; @@ -347,285 +332,250 @@ int LoMaxAction(SConnection *pCon, SicsInterp *pSics, int window; int *iData; double dVal; - ObPar *ob = NULL; + ObPar *ob = NULL; float average, maximum; - self = (pLoMax)pData; + self = (pLoMax) pData; assert(pCon); assert(pSics); assert(self); /* - we need arguments - */ - if(argc < 2) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); + we need arguments + */ + if (argc < 2) { + sprintf(pBueffel, "ERROR: insufficient number of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } /* - interpret arguments - */ + interpret arguments + */ strtolower(argv[1]); - if(strcmp(argv[1],"search") == 0) - { - if(argc < 3) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s.search", - argv[0]); - SCWrite(pCon,pBueffel,eError); + if (strcmp(argv[1], "search") == 0) { + if (argc < 3) { + sprintf(pBueffel, + "ERROR: insufficient number of arguments to %s.search", + argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } - if(!checkHM(&pHM, pSics,pCon, argv[2],iDim)) - { + if (!checkHM(&pHM, pSics, pCon, argv[2], iDim)) { return 0; } Tcl_DStringInit(&result); - iData = GetHistogramPointer(pHM,pCon); - window = (int)ObVal(self->pParam,WINDOW); + iData = GetHistogramPointer(pHM, pCon); + window = (int) ObVal(self->pParam, WINDOW); count = 0; - for(i = 0 + window/2; i < iDim[0] - window/2; i++) - { - for(j = 0 + window/2; j < iDim[1] - window/2; j++) - { - if(testLocalMaximum(iData,iDim[0], iDim[1], - i,j, - (int)ObVal(self->pParam,WINDOW), - (int)ObVal(self->pParam,STEEPNESS), - (int)ObVal(self->pParam,THRESHOLD), - &intensity)) - { - if(count != 0) - { - Tcl_DStringAppend(&result,"@",strlen("@")); + for (i = 0 + window / 2; i < iDim[0] - window / 2; i++) { + for (j = 0 + window / 2; j < iDim[1] - window / 2; j++) { + if (testLocalMaximum(iData, iDim[0], iDim[1], + i, j, + (int) ObVal(self->pParam, WINDOW), + (int) ObVal(self->pParam, STEEPNESS), + (int) ObVal(self->pParam, THRESHOLD), + &intensity)) { + if (count != 0) { + Tcl_DStringAppend(&result, "@", strlen("@")); } - sprintf(pNum,"%d ", i); - Tcl_DStringAppend(&result,pNum,strlen(pNum)); - sprintf(pNum,"%d ", j); - Tcl_DStringAppend(&result,pNum,strlen(pNum)); - sprintf(pNum,"%d", intensity); - Tcl_DStringAppend(&result,pNum,strlen(pNum)); + sprintf(pNum, "%d ", i); + Tcl_DStringAppend(&result, pNum, strlen(pNum)); + sprintf(pNum, "%d ", j); + Tcl_DStringAppend(&result, pNum, strlen(pNum)); + sprintf(pNum, "%d", intensity); + Tcl_DStringAppend(&result, pNum, strlen(pNum)); count++; } - } + } } - SCWrite(pCon,Tcl_DStringValue(&result),eValue); + SCWrite(pCon, Tcl_DStringValue(&result), eValue); Tcl_DStringFree(&result); return 1; - } - else if(strcmp(argv[1],"cog") == 0) /* COG calculation */ - { - if(argc < 5) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s.cog", - argv[0]); - SCWrite(pCon,pBueffel,eError); + } else if (strcmp(argv[1], "cog") == 0) { /* COG calculation */ + if (argc < 5) { + sprintf(pBueffel, + "ERROR: insufficient number of arguments to %s.cog", + argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } - if(!checkHM(&pHM, pSics,pCon, argv[2],iDim)) - { + if (!checkHM(&pHM, pSics, pCon, argv[2], iDim)) { return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[3],&i)!= TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[3], &i) != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[4],&j)!= TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[4], &j) != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } Tcl_DStringInit(&result); - iData = GetHistogramPointer(pHM,pCon); - window = (int)ObVal(self->pParam,COGWINDOW); - iRet = calculateCOG(iData,iDim[0], iDim[1], &i, &j, &intensity,&count, - window, ObVal(self->pParam,COGCONTOUR)); - if(!iRet) - { - SCWrite(pCon,"ERROR: no intensity in data",eError); + iData = GetHistogramPointer(pHM, pCon); + window = (int) ObVal(self->pParam, COGWINDOW); + iRet = + calculateCOG(iData, iDim[0], iDim[1], &i, &j, &intensity, &count, + window, ObVal(self->pParam, COGCONTOUR)); + if (!iRet) { + SCWrite(pCon, "ERROR: no intensity in data", eError); return 0; } - sprintf(pNum,"%d ", i); - Tcl_DStringAppend(&result,pNum,strlen(pNum)); - sprintf(pNum,"%d ", j); - Tcl_DStringAppend(&result,pNum,strlen(pNum)); - sprintf(pNum,"%d ", intensity); - Tcl_DStringAppend(&result,pNum,strlen(pNum)); - sprintf(pNum,"%d ", count); - Tcl_DStringAppend(&result,pNum,strlen(pNum)); - SCWrite(pCon,Tcl_DStringValue(&result),eValue); + sprintf(pNum, "%d ", i); + Tcl_DStringAppend(&result, pNum, strlen(pNum)); + sprintf(pNum, "%d ", j); + Tcl_DStringAppend(&result, pNum, strlen(pNum)); + sprintf(pNum, "%d ", intensity); + Tcl_DStringAppend(&result, pNum, strlen(pNum)); + sprintf(pNum, "%d ", count); + Tcl_DStringAppend(&result, pNum, strlen(pNum)); + SCWrite(pCon, Tcl_DStringValue(&result), eValue); Tcl_DStringFree(&result); return 1; - } - else if(strcmp(argv[1],"wellformed") == 0) /* test for wellformedness */ - { - if(argc < 6) - { + } else if (strcmp(argv[1], "wellformed") == 0) { /* test for wellformedness */ + if (argc < 6) { sprintf(pBueffel, - "ERROR: insufficient number of arguments to %s.wellformed", - argv[0]); - SCWrite(pCon,pBueffel,eError); + "ERROR: insufficient number of arguments to %s.wellformed", + argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } - if(!checkHM(&pHM, pSics,pCon, argv[2],iDim)) - { + if (!checkHM(&pHM, pSics, pCon, argv[2], iDim)) { return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[3],&i)!= TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[3], &i) != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[4],&j)!= TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[4], &j) != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } - if(Tcl_GetInt(pSics->pTcl,argv[5],&badMax)!= TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; + if (Tcl_GetInt(pSics->pTcl, argv[5], &badMax) != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } - iData = GetHistogramPointer(pHM,pCon); - window = (int)ObVal(self->pParam,COGWINDOW); - iRet = wellFormed(iData,iDim[0], iDim[1], i, j, - window, ObVal(self->pParam,COGCONTOUR), - badMax); - sprintf(pBueffel,"%5d", iRet); - SCWrite(pCon,pBueffel,eValue); + iData = GetHistogramPointer(pHM, pCon); + window = (int) ObVal(self->pParam, COGWINDOW); + iRet = wellFormed(iData, iDim[0], iDim[1], i, j, + window, ObVal(self->pParam, COGCONTOUR), badMax); + sprintf(pBueffel, "%5d", iRet); + SCWrite(pCon, pBueffel, eValue); return 1; - } - else if(strcmp(argv[1],"stat") == 0) - { - if(argc < 3) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s.search", - argv[0]); - SCWrite(pCon,pBueffel,eError); + } else if (strcmp(argv[1], "stat") == 0) { + if (argc < 3) { + sprintf(pBueffel, + "ERROR: insufficient number of arguments to %s.search", + argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } - if(!checkHM(&pHM, pSics,pCon, argv[2],iDim)) - { + if (!checkHM(&pHM, pSics, pCon, argv[2], iDim)) { return 0; } - iData = GetHistogramPointer(pHM,pCon); - calculateStatistics(iData,iDim[0],iDim[1],&average,&maximum); - sprintf(pBueffel," %f %f", average, maximum); - SCWrite(pCon,pBueffel,eValue); + iData = GetHistogramPointer(pHM, pCon); + calculateStatistics(iData, iDim[0], iDim[1], &average, &maximum); + sprintf(pBueffel, " %f %f", average, maximum); + SCWrite(pCon, pBueffel, eValue); return 1; - } - else - { + } else { /* we are handling one of the parameter commands */ - if(argc > 2) /* set case */ - { - if(Tcl_GetDouble(pSics->pTcl,argv[2],&dVal) != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return ObParSet(self->pParam,argv[0],argv[1],(float)dVal,pCon); - } - else /* read case */ - { - ob = ObParFind(self->pParam,argv[1]); - if(!ob) - { - sprintf(pBueffel,"ERROR: parameter %s not found or wrong command", - argv[1]); - SCWrite(pCon,pBueffel,eError); + if (argc > 2) { /* set case */ + if (Tcl_GetDouble(pSics->pTcl, argv[2], &dVal) != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } - sprintf(pBueffel,"%s.%s = %f",argv[0],argv[1],ob->fVal); - SCWrite(pCon,pBueffel,eError); + return ObParSet(self->pParam, argv[0], argv[1], (float) dVal, pCon); + } else { /* read case */ + + ob = ObParFind(self->pParam, argv[1]); + if (!ob) { + sprintf(pBueffel, "ERROR: parameter %s not found or wrong command", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + sprintf(pBueffel, "%s.%s = %f", argv[0], argv[1], ob->fVal); + SCWrite(pCon, pBueffel, eError); return 1; } } /* - not reached - */ + not reached + */ assert(0); return 0; } + /*-------------------------------------------------------------------*/ static void KillLoMax(void *pData) { - pLoMax self = (pLoMax)pData; - if(!self) + pLoMax self = (pLoMax) pData; + if (!self) return; - if(self->pDes) + if (self->pDes) DeleteDescriptor(self->pDes); - if(self->pParam) + if (self->pParam) ObParDelete(self->pParam); free(self); } + /*-------------------------------------------------------------------*/ -int LoMaxFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) +int LoMaxFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) { pLoMax pNew = NULL; - if(argc < 2) - { - SCWrite(pCon,"ERROR: Insufficient number of arguments to LoMaxfactory", - eError); - return 0; - } - - pNew = (pLoMax)malloc(sizeof(LoMax)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory creating local maximum searcher", + if (argc < 2) { + SCWrite(pCon, + "ERROR: Insufficient number of arguments to LoMaxfactory", eError); return 0; } - memset(pNew,0,sizeof(LoMax)); + + pNew = (pLoMax) malloc(sizeof(LoMax)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory creating local maximum searcher", + eError); + return 0; + } + memset(pNew, 0, sizeof(LoMax)); /* - create Descriptor - */ + create Descriptor + */ pNew->pDes = CreateDescriptor("Local Maximum Detector"); - if(!pNew->pDes) - { + if (!pNew->pDes) { KillLoMax(pNew); - SCWrite(pCon,"ERROR: out of memory creating local maximum searcher", + SCWrite(pCon, "ERROR: out of memory creating local maximum searcher", eError); return 0; } /* - create and install parameters - */ + create and install parameters + */ pNew->pParam = ObParCreate(5); - if(!pNew->pParam) - { + if (!pNew->pParam) { KillLoMax(pNew); - SCWrite(pCon,"ERROR: out of memory creating local maximum searcher", + SCWrite(pCon, "ERROR: out of memory creating local maximum searcher", eError); return 0; } - ObParInit(pNew->pParam,WINDOW,"window",10,usUser); - ObParInit(pNew->pParam,THRESHOLD,"threshold",30,usUser); - ObParInit(pNew->pParam,STEEPNESS,"steepness",5,usUser); - ObParInit(pNew->pParam,COGWINDOW,"cogwindow",50,usUser); - ObParInit(pNew->pParam,COGCONTOUR,"cogcontour",.2,usUser); + ObParInit(pNew->pParam, WINDOW, "window", 10, usUser); + ObParInit(pNew->pParam, THRESHOLD, "threshold", 30, usUser); + ObParInit(pNew->pParam, STEEPNESS, "steepness", 5, usUser); + ObParInit(pNew->pParam, COGWINDOW, "cogwindow", 50, usUser); + ObParInit(pNew->pParam, COGCONTOUR, "cogcontour", .2, usUser); - return AddCommand(pSics, - argv[1], - LoMaxAction, - KillLoMax, - pNew); + return AddCommand(pSics, argv[1], LoMaxAction, KillLoMax, pNew); } - diff --git a/lomax.h b/lomax.h index 823a1b3a..43c3eba7 100644 --- a/lomax.h +++ b/lomax.h @@ -13,28 +13,26 @@ #define LOCALMAXIMUM #include "obpar.h" - typedef struct __LOMAX *pLoMax; +typedef struct __LOMAX *pLoMax; - int LoMaxAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int LoMaxAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); - int LoMaxFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int LoMaxFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); - int testLocalMaximum(int *iData, int xsize, int ysize, - int i, int j, - int window, int threshold, int steepness, - int *intensity); - int calculateCOG(int *iData, int xsize, int ysize, - int *i, int *j, int *intensity, int *count, - int cogWindow, - float contour); - void calculateStatistics(int *iData, int xsize, int ysize, - float *average, float *maximum); - int wellFormed(int *iData, int xsize, int ysize, - int x, int y, int window, float contour, - int maxBad); +int testLocalMaximum(int *iData, int xsize, int ysize, + int i, int j, + int window, int threshold, int steepness, + int *intensity); +int calculateCOG(int *iData, int xsize, int ysize, + int *i, int *j, int *intensity, int *count, + int cogWindow, float contour); +void calculateStatistics(int *iData, int xsize, int ysize, + float *average, float *maximum); +int wellFormed(int *iData, int xsize, int ysize, + int x, int y, int window, float contour, int maxBad); diff --git a/macro.c b/macro.c index ada160fb..d71d9852 100644 --- a/macro.c +++ b/macro.c @@ -86,514 +86,479 @@ #define MAXSTACK 50 - struct __SicsUnknown { - SConnection *pCon[MAXSTACK]; - char *lastUnknown[MAXSTACK]; - int iStack; - SicsInterp *pInter; - }; - - static struct __SicsUnknown *pUnbekannt = NULL; +struct __SicsUnknown { + SConnection *pCon[MAXSTACK]; + char *lastUnknown[MAXSTACK]; + int iStack; + SicsInterp *pInter; +}; + +static struct __SicsUnknown *pUnbekannt = NULL; /*---------------------------------------------------------------------------*/ - int MacroPush(SConnection *pCon) - { - assert(pUnbekannt); - pUnbekannt->iStack++; - if(pUnbekannt->iStack >= MAXSTACK) - { - SCWrite(pCon,"ERROR: Out of Stack in macro.c",eError); - return 0; - } - pUnbekannt->pCon[pUnbekannt->iStack] = pCon; - return 1; +int MacroPush(SConnection * pCon) +{ + assert(pUnbekannt); + pUnbekannt->iStack++; + if (pUnbekannt->iStack >= MAXSTACK) { + SCWrite(pCon, "ERROR: Out of Stack in macro.c", eError); + return 0; } -/*-------------------------------------------------------------------------*/ - int MacroPop(void) - { - assert(pUnbekannt); - pUnbekannt->iStack--; - if(pUnbekannt->iStack < 1) - { - pUnbekannt->iStack = 0; + pUnbekannt->pCon[pUnbekannt->iStack] = pCon; + return 1; +} + +/*-------------------------------------------------------------------------*/ +int MacroPop(void) +{ + assert(pUnbekannt); + pUnbekannt->iStack--; + if (pUnbekannt->iStack < 1) { + pUnbekannt->iStack = 0; + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int SicsUnknownProc(ClientData pData, Tcl_Interp * pInter, + int argc, char *argv[]) +{ + struct __SicsUnknown *pSics = NULL; + char **myarg = NULL; + int margc; + SicsInterp *pSinter = NULL; + SConnection *pCon = NULL; + CommandList *pCommand = NULL; + char *lastCommand = NULL, comBuffer[132]; + int iRet = 0, i; + int iMacro; + Statistics *old; + + /* get the datastructures */ + pSics = (struct __SicsUnknown *) pData; + assert(pSics); + pSinter = pSics->pInter; + pCon = pSics->pCon[pSics->iStack]; + lastCommand = pSics->lastUnknown[pSics->iStack]; + pCon->sicsError = 0; + + assert(pSinter); + assert(pCon); + + + /* shorten the argc, argv by one and invoke */ + margc = argc - 1; + myarg = &argv[1]; + + /* find object */ + if (margc < 1) { + Tcl_SetResult(pInter, "No command found", TCL_VOLATILE); + return TCL_ERROR; + } + pCommand = FindCommand(pSinter, myarg[0]); + if (!pCommand) { + Tcl_AppendResult(pInter, "Object ", myarg[0], " not found", NULL); + return TCL_ERROR; + } + + /* check for endless loop */ + Arg2Text(margc, myarg, comBuffer, 131); + if (lastCommand != NULL) { + if (strcmp(lastCommand, comBuffer) == 0) { + Tcl_AppendResult(pInter, "ERROR: Never ending loop in unknown\n", + "Offending command: ", comBuffer, + " Probably Tcl command not found", NULL); + SCSetInterrupt(pCon, eAbortBatch); + return TCL_ERROR; } - return 1; } -/*---------------------------------------------------------------------------*/ - static int SicsUnknownProc(ClientData pData, Tcl_Interp *pInter, - int argc, char *argv[]) - { - struct __SicsUnknown *pSics = NULL; - char **myarg = NULL; - int margc; - SicsInterp *pSinter = NULL; - SConnection *pCon = NULL; - CommandList *pCommand = NULL; - char *lastCommand = NULL, comBuffer[132]; - int iRet = 0,i; - int iMacro; - Statistics *old; + if (pSics->lastUnknown[pSics->iStack]) + free(pSics->lastUnknown[pSics->iStack]); + pSics->lastUnknown[pSics->iStack] = strdup(comBuffer); - /* get the datastructures */ - pSics = (struct __SicsUnknown *)pData; - assert(pSics); - pSinter = pSics->pInter; - pCon = pSics->pCon[pSics->iStack]; - lastCommand = pSics->lastUnknown[pSics->iStack]; - pCon->sicsError = 0; - - assert(pSinter); - assert(pCon); - - - /* shorten the argc, argv by one and invoke */ - margc = argc -1; - myarg = &argv[1]; - - /* find object */ - if(margc < 1) - { - Tcl_SetResult(pInter,"No command found",TCL_VOLATILE); - return TCL_ERROR; - } - pCommand = FindCommand(pSinter,myarg[0]); - if(!pCommand) - { - Tcl_AppendResult(pInter,"Object ",myarg[0]," not found",NULL); - return TCL_ERROR; - } - - /* check for endless loop */ - Arg2Text(margc, myarg, comBuffer,131); - if(lastCommand != NULL) - { - if(strcmp(lastCommand,comBuffer) == 0) - { - Tcl_AppendResult(pInter,"ERROR: Never ending loop in unknown\n", - "Offending command: ",comBuffer, - " Probably Tcl command not found",NULL); - SCSetInterrupt(pCon,eAbortBatch); - return TCL_ERROR; - } - } - if (pSics->lastUnknown[pSics->iStack]) free(pSics->lastUnknown[pSics->iStack]); - pSics->lastUnknown[pSics->iStack] = strdup(comBuffer); - - /* invoke */ - iMacro = SCinMacro(pCon); - SCsetMacro(pCon,1); - old=StatisticsBegin(pCommand->stat); - iRet = pCommand->OFunc(pCon,pSinter,pCommand->pData,margc, myarg); - StatisticsEnd(old); - SCsetMacro(pCon,iMacro); - /* - lastUnkown gets deeply stacked with each SICS command exec'd. - This is not reflected in code. However, lastUnknown has already - done its job here, so it is safe to do it the way it is done - */ - if(pSics->lastUnknown[pSics->iStack] != NULL) - { - free(pSics->lastUnknown[pSics->iStack]); - pSics->lastUnknown[pSics->iStack] = NULL; - } - - /* finish */ - if(iRet == 1) - { - return TCL_OK; - } - else - { - Tcl_SetVar(pInter,SICSERROR,"yes",TCL_GLOBAL_ONLY); - pCon->sicsError = 1; - return TCL_ERROR; - } + /* invoke */ + iMacro = SCinMacro(pCon); + SCsetMacro(pCon, 1); + old = StatisticsBegin(pCommand->stat); + iRet = pCommand->OFunc(pCon, pSinter, pCommand->pData, margc, myarg); + StatisticsEnd(old); + SCsetMacro(pCon, iMacro); + /* + lastUnkown gets deeply stacked with each SICS command exec'd. + This is not reflected in code. However, lastUnknown has already + done its job here, so it is safe to do it the way it is done + */ + if (pSics->lastUnknown[pSics->iStack] != NULL) { + free(pSics->lastUnknown[pSics->iStack]); + pSics->lastUnknown[pSics->iStack] = NULL; } + + /* finish */ + if (iRet == 1) { + return TCL_OK; + } else { + Tcl_SetVar(pInter, SICSERROR, "yes", TCL_GLOBAL_ONLY); + pCon->sicsError = 1; + return TCL_ERROR; + } +} + /*-----------------------------------------------------------------------*/ - static void UnknownKill(ClientData pData) - { - struct __SicsUnknown *pU = NULL; - - pU = (struct __SicsUnknown *)pData; - if(pU->pCon[0]) - { - SCDeleteConnection(pU->pCon[0]); - } - free(pData); - pUnbekannt = NULL; - } - /*-----------------------------------------------------------------------*/ - void KillSicsUnknown(void) { - if (pUnbekannt) { - UnknownKill(pUnbekannt); - pUnbekannt = NULL; - } +static void UnknownKill(ClientData pData) +{ + struct __SicsUnknown *pU = NULL; + + pU = (struct __SicsUnknown *) pData; + if (pU->pCon[0]) { + SCDeleteConnection(pU->pCon[0]); } + free(pData); + pUnbekannt = NULL; +} + + /*-----------------------------------------------------------------------*/ +void KillSicsUnknown(void) +{ + if (pUnbekannt) { + UnknownKill(pUnbekannt); + pUnbekannt = NULL; + } +} + /*------------------------------------------------------------------------ Implementation of a protected exec command --------------------------------------------------------------------------*/ static pStringDict allowedCommands = NULL; /*----------------------------------------------------------------------*/ -int AllowExec(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) +int AllowExec(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) { - if(argc < 2) - { - SCWrite(pCon,"ERROR: not enough arguments to allowexec",eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to allowexec", eError); return 0; } - if(!SCMatchRights(pCon,usInternal)) - { + if (!SCMatchRights(pCon, usInternal)) { return 0; } - if(allowedCommands == NULL) - { + if (allowedCommands == NULL) { allowedCommands = CreateStringDict(); - if(allowedCommands == NULL) - { + if (allowedCommands == NULL) { SCWrite(pCon, - "ERROR: not enough memory for list of allowed system commands", - eError); + "ERROR: not enough memory for list of allowed system commands", + eError); return 0; } } - StringDictAddPair(allowedCommands,argv[1],"Allowed!"); + StringDictAddPair(allowedCommands, argv[1], "Allowed!"); return 1; } + /*--------------------------------------------------------------------*/ static void KillExec(ClientData data) { - if(allowedCommands != NULL) - { - DeleteStringDict(allowedCommands); - allowedCommands = NULL; + if (allowedCommands != NULL) { + DeleteStringDict(allowedCommands); + allowedCommands = NULL; } } + /*------------------------------------------------------------------------ This is in the Tcl sources */ -extern int Tcl_ExecObjCmd(ClientData data, Tcl_Interp *interp, - int objc, Tcl_Obj *CONST objv[]); +extern int Tcl_ExecObjCmd(ClientData data, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]); /*-----------------------------------------------------------------------*/ -static int ProtectedExec(ClientData clientData, Tcl_Interp *interp, - int objc, Tcl_Obj *CONST objv[]) +static int ProtectedExec(ClientData clientData, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) { char *test = NULL; - if(objc < 2) - { - return Tcl_ExecObjCmd(clientData,interp,objc, objv); + if (objc < 2) { + return Tcl_ExecObjCmd(clientData, interp, objc, objv); } - test = Tcl_GetStringFromObj(objv[1],NULL); - if(allowedCommands != NULL) - { - if(StringDictExists(allowedCommands,test)) - { - return Tcl_ExecObjCmd(clientData,interp,objc, objv); + test = Tcl_GetStringFromObj(objv[1], NULL); + if (allowedCommands != NULL) { + if (StringDictExists(allowedCommands, test)) { + return Tcl_ExecObjCmd(clientData, interp, objc, objv); } } - + /* - if we are here, we are not allowed to invoke this command - */ - Tcl_AppendResult(interp,"System command NOT allowed!",NULL); + if we are here, we are not allowed to invoke this command + */ + Tcl_AppendResult(interp, "System command NOT allowed!", NULL); return TCL_ERROR; } + /*-------------------------------------------------------------------------- initialises a Tcl-Interpreter, installs SICS unknown mechanism and kills a few dangerous commands from the normal Tcl command set ----------------------------------------------------------------------------*/ -extern int Nxinter_SafeInit(Tcl_Interp *pTcl); /* from Swig NeXus Tcl interface */ +extern int Nxinter_SafeInit(Tcl_Interp * pTcl); /* from Swig NeXus Tcl interface */ - Tcl_Interp *MacroInit(SicsInterp *pSics) - { - Tcl_Interp *pInter = NULL; - struct __SicsUnknown *pUnknown = NULL; - char *pPtr = NULL; - char *pPtr2 = NULL; - FILE *fp = NULL; - char pBueffel[512]; - int iRet; - - assert(pSics); - - /* create interpreter and unknown */ - pInter = Tcl_CreateInterp(); - pUnknown = (struct __SicsUnknown *)malloc(sizeof(struct __SicsUnknown)); - if( (!pInter) || (!pUnknown) ) - { - return NULL; - } - - /* install unknown command */ - memset(pUnknown,0,sizeof(struct __SicsUnknown)); - pUnknown->pCon[0] = SCCreateDummyConnection(pSics); - pUnknown->iStack = 0; - pUnknown->pInter = pSics; - pUnbekannt = pUnknown; - /* the cast before SicsUnknwonProc is to avoid a warning - Tcl_CmdProc has a const char instead of char as argument M.Z. */ - Tcl_CreateCommand(pInter,"unknown",(Tcl_CmdProc *)SicsUnknownProc, - pUnknown, UnknownKill); +Tcl_Interp *MacroInit(SicsInterp * pSics) +{ + Tcl_Interp *pInter = NULL; + struct __SicsUnknown *pUnknown = NULL; + char *pPtr = NULL; + char *pPtr2 = NULL; + FILE *fp = NULL; + char pBueffel[512]; + int iRet; - /* delete dangers */ - Tcl_DeleteCommand(pInter,"exit"); - Tcl_DeleteCommand(pInter,"socket"); - Tcl_DeleteCommand(pInter,"vwait"); - Tcl_DeleteCommand(pInter,"exec"); + assert(pSics); - /* - install protected exec command - */ - Tcl_CreateObjCommand(pInter,"exec",ProtectedExec,NULL,KillExec); - - Nxinter_SafeInit(pInter); - NXcopy_Init(pInter); - - return pInter; + /* create interpreter and unknown */ + pInter = Tcl_CreateInterp(); + pUnknown = (struct __SicsUnknown *) malloc(sizeof(struct __SicsUnknown)); + if ((!pInter) || (!pUnknown)) { + return NULL; } + + /* install unknown command */ + memset(pUnknown, 0, sizeof(struct __SicsUnknown)); + pUnknown->pCon[0] = SCCreateDummyConnection(pSics); + pUnknown->iStack = 0; + pUnknown->pInter = pSics; + pUnbekannt = pUnknown; + /* the cast before SicsUnknwonProc is to avoid a warning + Tcl_CmdProc has a const char instead of char as argument M.Z. */ + Tcl_CreateCommand(pInter, "unknown", (Tcl_CmdProc *) SicsUnknownProc, + pUnknown, UnknownKill); + + /* delete dangers */ + Tcl_DeleteCommand(pInter, "exit"); + Tcl_DeleteCommand(pInter, "socket"); + Tcl_DeleteCommand(pInter, "vwait"); + Tcl_DeleteCommand(pInter, "exec"); + + /* + install protected exec command + */ + Tcl_CreateObjCommand(pInter, "exec", ProtectedExec, NULL, KillExec); + + Nxinter_SafeInit(pInter); + NXcopy_Init(pInter); + + return pInter; +} + /*--------------------------------------------------------------------------*/ - void MacroDelete(Tcl_Interp *pInter) - { - Tcl_DeleteInterp(pInter); - } +void MacroDelete(Tcl_Interp * pInter) +{ + Tcl_DeleteInterp(pInter); +} + /*------------------------------------------------------------------------- Find the first word of a command string */ - static void FirstWord(char *pSource, char *pTarget) - { - int i, iLength, iStart, iPos; - - iLength = strlen(pSource); +static void FirstWord(char *pSource, char *pTarget) +{ + int i, iLength, iStart, iPos; - /* find start */ - for(i = 0, iStart = 0; i < iLength; i++) - { - if(pSource[i] != ' ') - { - break; - } - else - { - iStart++; - } - } + iLength = strlen(pSource); - /* do a quick check */ - if(iStart >= iLength - 2) - { - pTarget[0] = '\0'; - return; - } - - /* do the copy */ - for(i = iStart, iPos = 0; i < iLength; i++) - { - if(pSource[i] != ' ') - { - pTarget[iPos] = pSource[i]; - iPos++; - } - else - { - pTarget[iPos] = '\0'; - return; - } - } - pTarget[iPos] = '\0'; - return; + /* find start */ + for (i = 0, iStart = 0; i < iLength; i++) { + if (pSource[i] != ' ') { + break; + } else { + iStart++; } + } + + /* do a quick check */ + if (iStart >= iLength - 2) { + pTarget[0] = '\0'; + return; + } + + /* do the copy */ + for (i = iStart, iPos = 0; i < iLength; i++) { + if (pSource[i] != ' ') { + pTarget[iPos] = pSource[i]; + iPos++; + } else { + pTarget[iPos] = '\0'; + return; + } + } + pTarget[iPos] = '\0'; + return; +} + /*-------------------------------------------------------------------------*/ - static char *pWhere = NULL; - static char *pFile = NULL; +static char *pWhere = NULL; +static char *pFile = NULL; - int MacroWhere(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]) - { - assert(pCon); +int MacroWhere(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]) +{ + assert(pCon); + + if (pWhere) { + SCWrite(pCon, pWhere, eValue); + } + return 1; +} - if(pWhere) - { - SCWrite(pCon,pWhere,eValue); - } - return 1; - } /*-------------------------------------------------------------------------*/ - void WhereKill(void *pData) - { +void WhereKill(void *pData) +{ - if(pWhere) - { - free(pWhere); - pWhere = NULL; - } - if(pFile) - { - free(pFile); - pFile = NULL; - } + if (pWhere) { + free(pWhere); + pWhere = NULL; + } + if (pFile) { + free(pFile); + pFile = NULL; + } - if(pData) - KillDummy(pData); + if (pData) + KillDummy(pData); + +} - } /*--------------------------------------------------------------------------*/ - int MacroFileEvalNew(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]) - { - void *pCom = NULL; - pCom = FindCommandData(pInter,"exe","ExeManager"); - assert(pCom != NULL); - - if(argc < 2){ - SCWrite(pCon,"ERROR: no batch buffer to execute specified", - eError); - return 0; - } - return runExeBatchBuffer(pCom,pCon,pInter,argv[1]); - } -/*----------------------------------------------------------------------*/ - int MacroFileEval(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]) - { - FILE *fp = NULL; - char pBueffel[512]; - int iChar; - int i, iRun; - Tcl_DString command; - char *pCom = NULL; - int iRet; - Status eOld; - Tcl_Interp *pTcl = NULL; - int iLine = 0; +int MacroFileEvalNew(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]) +{ + void *pCom = NULL; + pCom = FindCommandData(pInter, "exe", "ExeManager"); + assert(pCom != NULL); - assert(pCon); - assert(pInter); - pTcl = InterpGetTcl(pInter); + if (argc < 2) { + SCWrite(pCon, "ERROR: no batch buffer to execute specified", eError); + return 0; + } + return runExeBatchBuffer(pCom, pCon, pInter, argv[1]); +} - /* check authorisation: only users permitted here */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: Insufficient Privilege to do FileEval",eError); - return 0; - } +/*----------------------------------------------------------------------*/ +int MacroFileEval(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]) +{ + FILE *fp = NULL; + char pBueffel[512]; + int iChar; + int i, iRun; + Tcl_DString command; + char *pCom = NULL; + int iRet; + Status eOld; + Tcl_Interp *pTcl = NULL; + int iLine = 0; - /* open filename */ - if( argc < 2) - { - SCWrite(pCon,"ERROR: No filename specified ",eError); - return 0; - } - fp = fopen(argv[1],"r"); - if(!fp) - { - sprintf(pBueffel," Failed to open file -> %s <- ",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* handle status first */ - eOld = GetStatus(); - SetStatus(eBatch); - - SICSLogWrite("Evaluating in MacroFileEval",eValue); - SICSLogWrite(argv[1],eValue); - if(pFile) - { - free(pFile); - } - pFile = strdup(argv[1]); + assert(pCon); + assert(pInter); + pTcl = InterpGetTcl(pInter); - /* cycle through file and execute complete commands */ - i = 0; - Tcl_DStringInit(&command); - iRun = 1; - while(iRun) - { - iChar = fgetc(fp); - if(iChar == EOF) - { - iChar = (int)'\n'; - iRun = 0; - } - if( iChar == (int)'\n' ) - { - pBueffel[i] = (char)iChar; - pBueffel[i+1] = '\0'; - Tcl_DStringAppend(&command,pBueffel,-1); - pCom = Tcl_DStringValue(&command); - if(Tcl_CommandComplete(pCom)) - { - SetStatus(eEager); - FirstWord(pCom,pBueffel); - if(FindCommand(pInter,pBueffel) != NULL) - { - sprintf(pBueffel,"%s:%d>> %s",pFile,iLine,pCom); - SCWrite(pCon,pBueffel,eLog); - if(pWhere != NULL) - { - free(pWhere); - } - pWhere = strdup(pBueffel); - iLine++; - } - iRet = Tcl_Eval(pTcl,pCom); - SetStatus(eBatch); - if(iRet != TCL_OK) - { - /* write TCL error and check for total interrupt */ - if(Tcl_GetVar(pTcl,SICSERROR,TCL_GLOBAL_ONLY) == NULL) - { /* Tcl error */ - if(strlen(pTcl->result) > 2) - { - /* - local copy in order to resolve a valgrind error - */ - strncpy(pBueffel,pTcl->result,511); - SCWrite(pCon,pBueffel,eError); - } - pCom = Tcl_DStringValue(&command); - SCWrite(pCon,"ERROR: in Tcl block:",eError); - SCWrite(pCon,pCom,eError); - SCWrite(pCon,"ERROR: end of Tcl error block",eError); - } - else /* SICS error */ - { - Tcl_UnsetVar(pTcl,SICSERROR,TCL_GLOBAL_ONLY); - /* SCWrite(pCon,pTcl->result,eError); */ - } - } - if(SCGetInterrupt(pCon) >= eAbortBatch) - { - fclose(fp); - Tcl_DStringFree(&command); - SCWrite(pCon,"ERROR: batch processing interrupted",eError); + /* check authorisation: only users permitted here */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: Insufficient Privilege to do FileEval", eError); + return 0; + } + + /* open filename */ + if (argc < 2) { + SCWrite(pCon, "ERROR: No filename specified ", eError); + return 0; + } + fp = fopen(argv[1], "r"); + if (!fp) { + sprintf(pBueffel, " Failed to open file -> %s <- ", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* handle status first */ + eOld = GetStatus(); + SetStatus(eBatch); + + SICSLogWrite("Evaluating in MacroFileEval", eValue); + SICSLogWrite(argv[1], eValue); + if (pFile) { + free(pFile); + } + pFile = strdup(argv[1]); + + /* cycle through file and execute complete commands */ + i = 0; + Tcl_DStringInit(&command); + iRun = 1; + while (iRun) { + iChar = fgetc(fp); + if (iChar == EOF) { + iChar = (int) '\n'; + iRun = 0; + } + if (iChar == (int) '\n') { + pBueffel[i] = (char) iChar; + pBueffel[i + 1] = '\0'; + Tcl_DStringAppend(&command, pBueffel, -1); + pCom = Tcl_DStringValue(&command); + if (Tcl_CommandComplete(pCom)) { SetStatus(eEager); - return 0; - } - else - { - SCSetInterrupt(pCon,eContinue); - } - Tcl_DStringFree(&command); - } - i = 0; - } - else - { - pBueffel[i] = (char)iChar; - i++; - } - } /* end while */ - - - /* clean up */ - fclose(fp); - Tcl_DStringFree(&command); - SetStatus(eOld); - SCSendOK(pCon); - return 1; - } + FirstWord(pCom, pBueffel); + if (FindCommand(pInter, pBueffel) != NULL) { + sprintf(pBueffel, "%s:%d>> %s", pFile, iLine, pCom); + SCWrite(pCon, pBueffel, eLog); + if (pWhere != NULL) { + free(pWhere); + } + pWhere = strdup(pBueffel); + iLine++; + } + iRet = Tcl_Eval(pTcl, pCom); + SetStatus(eBatch); + if (iRet != TCL_OK) { + /* write TCL error and check for total interrupt */ + if (Tcl_GetVar(pTcl, SICSERROR, TCL_GLOBAL_ONLY) == NULL) { /* Tcl error */ + if (strlen(pTcl->result) > 2) { + /* + local copy in order to resolve a valgrind error + */ + strncpy(pBueffel, pTcl->result, 511); + SCWrite(pCon, pBueffel, eError); + } + pCom = Tcl_DStringValue(&command); + SCWrite(pCon, "ERROR: in Tcl block:", eError); + SCWrite(pCon, pCom, eError); + SCWrite(pCon, "ERROR: end of Tcl error block", eError); + } else { /* SICS error */ + + Tcl_UnsetVar(pTcl, SICSERROR, TCL_GLOBAL_ONLY); + /* SCWrite(pCon,pTcl->result,eError); */ + } + } + if (SCGetInterrupt(pCon) >= eAbortBatch) { + fclose(fp); + Tcl_DStringFree(&command); + SCWrite(pCon, "ERROR: batch processing interrupted", eError); + SetStatus(eEager); + return 0; + } else { + SCSetInterrupt(pCon, eContinue); + } + Tcl_DStringFree(&command); + } + i = 0; + } else { + pBueffel[i] = (char) iChar; + i++; + } + } /* end while */ + + + /* clean up */ + fclose(fp); + Tcl_DStringFree(&command); + SetStatus(eOld); + SCSendOK(pCon); + return 1; +} + /*---------------------------------------------------------------------- InternalFileEval evaluates a file but on a dummy connection which only writes log files. It also configures a log file for output @@ -601,314 +566,293 @@ extern int Nxinter_SafeInit(Tcl_Interp *pTcl); /* from Swig NeXus Tcl interface This is here in order to support the evaluation of command files generated in a specific directory from the WWW-interface. If the latter does not get through, this can safely be deleted. -*/ +*/ - int InternalFileEval(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]) - { - SConnection *pIntern = NULL; - int iRet; - char *pFil = NULL, *pExt = NULL; +int InternalFileEval(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]) +{ + SConnection *pIntern = NULL; + int iRet; + char *pFil = NULL, *pExt = NULL; - /* we need a filename */ - if( argc < 2) - { - SCWrite(pCon,"ERROR: No filename specified ",eError); - return 0; - } + /* we need a filename */ + if (argc < 2) { + SCWrite(pCon, "ERROR: No filename specified ", eError); + return 0; + } - /* allocate a dummy connection for this */ - pIntern = SCCreateDummyConnection(pInter); - if(!pInter) - { - SCWrite(pCon,"ERROR: out of memory in InternalFileEval",eError); - return 0; - } - SCnoSock(pIntern); - - - /* invoke the fileeval */ - MacroPush(pIntern); - iRet = MacroFileEval(pIntern,pInter,pData,argc,argv); - MacroPop(); + /* allocate a dummy connection for this */ + pIntern = SCCreateDummyConnection(pInter); + if (!pInter) { + SCWrite(pCon, "ERROR: out of memory in InternalFileEval", eError); + return 0; + } + SCnoSock(pIntern); + + + /* invoke the fileeval */ + MacroPush(pIntern); + iRet = MacroFileEval(pIntern, pInter, pData, argc, argv); + MacroPop(); + + /* remove our internal connection */ + SCDeleteConnection(pIntern); + return iRet; +} - /* remove our internal connection */ - SCDeleteConnection(pIntern); - return iRet; - } /*-------------------------------------------------------------------------- ClientPut is installed as a command to write data to the client from a server script. Syntax: ClientPut text outputcode The output code is optional and and defaults to eStatus. ----------------------------------------------------------------------------*/ +---------------------------------------------------------------------------*/ #include "outcode.c" - int ClientPut(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]) - { - OutCode eOut = eLog; - int i = 0, iCode, iLen; - char *ppCode; - char *pMessage = NULL; - - assert(pCon); - assert(pInter); - - if(argc < 2) - { - SCWrite(pCon,"Insufficient arguments to ClientPut",eError); - return 0; - } - - /* handle optional I/O codes */ - if(argc > 2) - { - /* the last one must be the code */ - iCode = argc - 1; - ppCode = strdup(argv[iCode]); - strtolower(ppCode); - while(pCode[i] != NULL) - { - if(strcmp(pCode[i],ppCode) == 0) - { - break; - } - i++; - } - if(ppCode) - { - free(ppCode); - } - } - else - { - i = eLog; - iCode = argc; - } - - switch(i) - { - case 0: - eOut = eInternal; - break; - case 1: - eOut = eCommand; - break; - case 2: - eOut = eHWError; - break; - case 3: - eOut = eInError; - break; - case 4: - eOut = eStatus; - break; - case 5: - eOut = eValue; - break; - case 6: - eOut = eWarning; - break; - case 7: - eOut = eFinish; - break; - case 8: - eOut = eEvent; - break; - case 9: - eOut = eWarning; - break; - case 10: - eOut = eError; - break; - case 11: - eOut = eLog; - break; - case 12: - eOut = eLogError; - break; - default: - eOut = eLog; - iCode = argc; - break; - } +int ClientPut(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]) +{ + OutCode eOut = eLog; + int i = 0, iCode, iLen; + char *ppCode; + char *pMessage = NULL; - /* recombine the message */ - /* find length */ - iLen = 0; - for(i = 1; i < iCode; i++) - { - iLen += strlen(argv[i]); - } - pMessage = (char *)malloc((iLen+100)*sizeof(char)); - if(!pMessage) - { - SCWrite(pCon,"ERROR: out of memory in clientput",eLogError); - return 0; - } - memset(pMessage,0,(iLen+100)*sizeof(char)); - Arg2Text(iCode-1,&argv[1],pMessage,(iLen+100)*sizeof(char)); + assert(pCon); + assert(pInter); - SCWrite(pCon,pMessage,eOut); - if(pMessage) - { - free(pMessage); - } - return 1; + if (argc < 2) { + SCWrite(pCon, "Insufficient arguments to ClientPut", eError); + return 0; + } + + /* handle optional I/O codes */ + if (argc > 2) { + /* the last one must be the code */ + iCode = argc - 1; + ppCode = strdup(argv[iCode]); + strtolower(ppCode); + while (pCode[i] != NULL) { + if (strcmp(pCode[i], ppCode) == 0) { + break; + } + i++; } + if (ppCode) { + free(ppCode); + } + } else { + i = eLog; + iCode = argc; + } + + switch (i) { + case 0: + eOut = eInternal; + break; + case 1: + eOut = eCommand; + break; + case 2: + eOut = eHWError; + break; + case 3: + eOut = eInError; + break; + case 4: + eOut = eStatus; + break; + case 5: + eOut = eValue; + break; + case 6: + eOut = eWarning; + break; + case 7: + eOut = eFinish; + break; + case 8: + eOut = eEvent; + break; + case 9: + eOut = eWarning; + break; + case 10: + eOut = eError; + break; + case 11: + eOut = eLog; + break; + case 12: + eOut = eLogError; + break; + default: + eOut = eLog; + iCode = argc; + break; + } + + /* recombine the message */ + /* find length */ + iLen = 0; + for (i = 1; i < iCode; i++) { + iLen += strlen(argv[i]); + } + pMessage = (char *) malloc((iLen + 100) * sizeof(char)); + if (!pMessage) { + SCWrite(pCon, "ERROR: out of memory in clientput", eLogError); + return 0; + } + memset(pMessage, 0, (iLen + 100) * sizeof(char)); + Arg2Text(iCode - 1, &argv[1], pMessage, (iLen + 100) * sizeof(char)); + + SCWrite(pCon, pMessage, eOut); + if (pMessage) { + free(pMessage); + } + return 1; +} + /*-----------------------------------------------------------------------*/ - int GumPut(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]) - { - OutCode eOut = eWarning; - int i = 0, iCode, iLen; - int iMacro; - char *ppCode; - char *pMessage = NULL; - SConnection *conCon = NULL; - - assert(pCon); - assert(pInter); - - if(argc < 2) - { - SCWrite(pCon,"Insufficient arguments to ClientPut",eLogError); - return 0; - } - - /* handle optional I/O codes */ - if(argc > 2) - { - /* the last one must be the code */ - iCode = argc - 1; - ppCode = strdup(argv[iCode]); - strtolower(ppCode); - while(pCode[i] != NULL) - { - if(strcmp(pCode[i],ppCode) == 0) - { - break; - } - i++; - } - if(ppCode) - { - free(ppCode); - } - } - else - { - i = 10; - iCode = argc; - } - - switch(i) - { - case 0: - eOut = eInternal; - break; - case 1: - eOut = eCommand; - break; - case 2: - eOut = eHWError; - break; - case 3: - eOut = eInError; - break; - case 4: - eOut = eStatus; - break; - case 5: - eOut = eValue; - break; - case 6: - eOut = eWarning; - break; - case 7: - eOut = eFinish; - break; - case 8: - eOut = eEvent; - break; - case 9: - eOut = eWarning; - break; - case 10: - eOut = eError; - break; - case 11: - eOut = eLog; - break; - case 12: - eOut = eLogError; - break; - default: - eOut = eLog; - iCode = argc; - break; - } +int GumPut(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]) +{ + OutCode eOut = eWarning; + int i = 0, iCode, iLen; + int iMacro; + char *ppCode; + char *pMessage = NULL; + SConnection *conCon = NULL; - /* recombine the message */ - /* find length */ - iLen = 0; - for(i = 1; i < iCode; i++) - { - iLen += strlen(argv[i]); - } - pMessage = (char *)malloc((iLen+100)*sizeof(char)); - if(!pMessage) - { - SCWrite(pCon,"ERROR: out of memory in clientput",eError); - return 0; - } - memset(pMessage,0,(iLen+100)*sizeof(char)); - Arg2Text(iCode-1,&argv[1],pMessage,(iLen+100)*sizeof(char)); + assert(pCon); + assert(pInter); - /* now write, thereby tunneling macro flag in order to get proper - write to client and not into interpreter. We also make sure that the device - is gumput - */ - conCon = SCCopyConnection(pCon); - if(conCon == NULL){ - SCWrite(pCon,"ERROR: out of memory in gumput", eError); - } - strcpy(conCon->deviceID,"gumput"); - SCWrite(conCon,pMessage,eOut); - SCDeleteConnection(conCon); - if(pMessage) - { - free(pMessage); - } - return 1; + if (argc < 2) { + SCWrite(pCon, "Insufficient arguments to ClientPut", eLogError); + return 0; + } + + /* handle optional I/O codes */ + if (argc > 2) { + /* the last one must be the code */ + iCode = argc - 1; + ppCode = strdup(argv[iCode]); + strtolower(ppCode); + while (pCode[i] != NULL) { + if (strcmp(pCode[i], ppCode) == 0) { + break; + } + i++; } + if (ppCode) { + free(ppCode); + } + } else { + i = 10; + iCode = argc; + } + + switch (i) { + case 0: + eOut = eInternal; + break; + case 1: + eOut = eCommand; + break; + case 2: + eOut = eHWError; + break; + case 3: + eOut = eInError; + break; + case 4: + eOut = eStatus; + break; + case 5: + eOut = eValue; + break; + case 6: + eOut = eWarning; + break; + case 7: + eOut = eFinish; + break; + case 8: + eOut = eEvent; + break; + case 9: + eOut = eWarning; + break; + case 10: + eOut = eError; + break; + case 11: + eOut = eLog; + break; + case 12: + eOut = eLogError; + break; + default: + eOut = eLog; + iCode = argc; + break; + } + + /* recombine the message */ + /* find length */ + iLen = 0; + for (i = 1; i < iCode; i++) { + iLen += strlen(argv[i]); + } + pMessage = (char *) malloc((iLen + 100) * sizeof(char)); + if (!pMessage) { + SCWrite(pCon, "ERROR: out of memory in clientput", eError); + return 0; + } + memset(pMessage, 0, (iLen + 100) * sizeof(char)); + Arg2Text(iCode - 1, &argv[1], pMessage, (iLen + 100) * sizeof(char)); + + /* now write, thereby tunneling macro flag in order to get proper + write to client and not into interpreter. We also make sure that the device + is gumput + */ + conCon = SCCopyConnection(pCon); + if (conCon == NULL) { + SCWrite(pCon, "ERROR: out of memory in gumput", eError); + } + strcpy(conCon->deviceID, "gumput"); + SCWrite(conCon, pMessage, eOut); + SCDeleteConnection(conCon); + if (pMessage) { + free(pMessage); + } + return 1; +} + /*----------------------------------------------------------------------*/ - int Broadcast(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]) - { - int iMacro; - char pBueffel[256]; +int Broadcast(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]) +{ + int iMacro; + char pBueffel[256]; - assert(pCon); - assert(pInter); - - if(argc < 2) - { - SCWrite(pCon,"Insufficient arguments to Broadcast",eLog); - return 0; - } - + assert(pCon); + assert(pInter); + + if (argc < 2) { + SCWrite(pCon, "Insufficient arguments to Broadcast", eLog); + return 0; + } + + + /* now write, thereby tunneling macro flag in order to get proper + write to client and not into interpreter + */ + Arg2Text(argc - 1, &argv[1], pBueffel, 255); + ServerWriteGlobal(pBueffel, eLog); + return 1; +} - /* now write, thereby tunneling macro flag in order to get proper - write to client and not into interpreter - */ - Arg2Text(argc-1, &argv[1],pBueffel,255); - ServerWriteGlobal(pBueffel,eLog); - return 1; - } /*--------------------------------------------------------------------------- This implements a scheme to provide Tcl commands to Tcl. The Tcl commands (either procedures or objects) must be defined in a separate file. Than @@ -918,173 +862,167 @@ extern int Nxinter_SafeInit(Tcl_Interp *pTcl); /* from Swig NeXus Tcl interface the rights initialized may use it. Below the datastructure to hold for each command -----------------------------------------------------------------------------*/ - typedef struct { - pObjectDescriptor pDes; - char *command; - int iUser; - } PubTcl, *pPubTcl; -/*--------------------------------------------------------------------------*/ - static pPubTcl CreatePublish(char *name, int iUser) - { - pPubTcl pRes = NULL; - - pRes = (pPubTcl)malloc(sizeof(PubTcl)); - if(!pRes) - { - return NULL; - } - - pRes->pDes = CreateDescriptor("Macro"); - if(!pRes->pDes) - { - free(pRes); - return NULL; - } - - pRes->command = strdup(name); - pRes->iUser = iUser; - return pRes; - } +----------------------------------------------------------------------------*/ +typedef struct { + pObjectDescriptor pDes; + char *command; + int iUser; +} PubTcl, *pPubTcl; +/*--------------------------------------------------------------------------*/ +static pPubTcl CreatePublish(char *name, int iUser) +{ + pPubTcl pRes = NULL; + + pRes = (pPubTcl) malloc(sizeof(PubTcl)); + if (!pRes) { + return NULL; + } + + pRes->pDes = CreateDescriptor("Macro"); + if (!pRes->pDes) { + free(pRes); + return NULL; + } + + pRes->command = strdup(name); + pRes->iUser = iUser; + return pRes; +} + /*-------------------------------------------------------------------------*/ - static void DeletePublish(void *pData) - { - pPubTcl self = NULL; - - self = (pPubTcl)pData; - assert(self); - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->command) - { - free(self->command); - } - free(self); - } +static void DeletePublish(void *pData) +{ + pPubTcl self = NULL; + + self = (pPubTcl) pData; + assert(self); + + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->command) { + free(self->command); + } + free(self); +} + /*-------------------------------------------------------------------------- TclAction checks the user rights and than invokes the arguments as a Tcl command */ - - static int TclAction(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[1024]; - char *pCommand; - pPubTcl self = NULL; - int iRet, length; - char *pPtr; - Tcl_Interp *pTcl = NULL; - - self = (pPubTcl)pData; - assert(pCon); - assert(pSics); - assert(self); - pTcl = InterpGetTcl(pSics); - - if(!SCMatchRights(pCon,self->iUser)) - { - sprintf(pBueffel,"ERROR: you are not authorised to invoke %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 1; - } - /* make a string */ - pCommand = Arg2Tcl0(argc-1,argv+1,pBueffel,sizeof(pBueffel),self->command); - if (!pCommand) { - SCWrite(pCon, "ERROR: no more memory", eError); - return 0; - } - Tcl_ResetResult(pTcl); - iRet = Tcl_Eval(pTcl,pCommand); - if(iRet == TCL_OK) - { - if(strlen(pTcl->result) > 0){ - SCPrintf(pCon, eValue, "%s", pTcl->result); - } - if (pCommand != pBueffel) free(pCommand); - return 1; - } - else - { - if(Tcl_GetVar(pTcl,SICSERROR,TCL_GLOBAL_ONLY) != NULL) - { - Tcl_UnsetVar(pTcl,SICSERROR,TCL_GLOBAL_ONLY); - } - if(strlen(pTcl->result) > 0){ - SCPrintf(pCon,eError,"ERROR: Tcl reported %s in %s",pTcl->result, pCommand); - } - if (pCommand != pBueffel) free(pCommand); - return 0; - } - return 1; /* not reached */ - } -/*--------------------------------------------------------------------------*/ - int TclPublish(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pPubTcl pNew = NULL; - char pBueffel[132]; - int iUser, i, iRet; - - /* check no of args */ - if(argc < 3) - { - sprintf(pBueffel,"ERROR: Insufficient no of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* check user rights */ - if(!SCMatchRights(pCon,usMugger)) - { - sprintf(pBueffel,"ERROR: you are not authorised to use %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - - /* try convert last parameter to user code */ - iUser = decodeSICSPriv(argv[2]); - if(iUser < 0) - { - sprintf(pBueffel,"ERROR: cannot identify %s as a valid user code", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* check if the macro already exists */ - pNew = FindCommandData(pSics, argv[1], "Macro"); - if (pNew) - { /* yes -> overwrite access code */ - pNew->iUser = iUser; - return 1; - } - /* do a job !*/ - pNew = CreatePublish(argv[1],iUser); - if(!pNew) - { - sprintf(pBueffel,"ERROR: memory error in %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = AddCommand(pSics,argv[1],TclAction,DeletePublish,(void *)pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +static int TclAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[1024]; + char *pCommand; + pPubTcl self = NULL; + int iRet, length; + char *pPtr; + Tcl_Interp *pTcl = NULL; + + self = (pPubTcl) pData; + assert(pCon); + assert(pSics); + assert(self); + pTcl = InterpGetTcl(pSics); + + if (!SCMatchRights(pCon, self->iUser)) { + sprintf(pBueffel, "ERROR: you are not authorised to invoke %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); return 1; - - } + } + + /* make a string */ + pCommand = + Arg2Tcl0(argc - 1, argv + 1, pBueffel, sizeof(pBueffel), + self->command); + if (!pCommand) { + SCWrite(pCon, "ERROR: no more memory", eError); + return 0; + } + Tcl_ResetResult(pTcl); + iRet = Tcl_Eval(pTcl, pCommand); + if (iRet == TCL_OK) { + if (strlen(pTcl->result) > 0) { + SCPrintf(pCon, eValue, "%s", pTcl->result); + } + if (pCommand != pBueffel) + free(pCommand); + return 1; + } else { + if (Tcl_GetVar(pTcl, SICSERROR, TCL_GLOBAL_ONLY) != NULL) { + Tcl_UnsetVar(pTcl, SICSERROR, TCL_GLOBAL_ONLY); + } + if (strlen(pTcl->result) > 0) { + SCPrintf(pCon, eError, "ERROR: Tcl reported %s in %s", pTcl->result, + pCommand); + } + if (pCommand != pBueffel) + free(pCommand); + return 0; + } + return 1; /* not reached */ +} + +/*--------------------------------------------------------------------------*/ +int TclPublish(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pPubTcl pNew = NULL; + char pBueffel[132]; + int iUser, i, iRet; + + /* check no of args */ + if (argc < 3) { + sprintf(pBueffel, "ERROR: Insufficient no of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* check user rights */ + if (!SCMatchRights(pCon, usMugger)) { + sprintf(pBueffel, "ERROR: you are not authorised to use %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + + /* try convert last parameter to user code */ + iUser = decodeSICSPriv(argv[2]); + if (iUser < 0) { + sprintf(pBueffel, "ERROR: cannot identify %s as a valid user code", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* check if the macro already exists */ + pNew = FindCommandData(pSics, argv[1], "Macro"); + if (pNew) { /* yes -> overwrite access code */ + pNew->iUser = iUser; + return 1; + } + /* do a job ! */ + pNew = CreatePublish(argv[1], iUser); + if (!pNew) { + sprintf(pBueffel, "ERROR: memory error in %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = + AddCommand(pSics, argv[1], TclAction, DeletePublish, (void *) pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; + +} + /*------------------------------------------------------------------------- Transact executes a command and sends a TRANSACTIONFINISHED string at the end. This is to permit clients to search for this string in @@ -1093,34 +1031,25 @@ extern int Nxinter_SafeInit(Tcl_Interp *pTcl); /* from Swig NeXus Tcl interface - int TransactAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBuffer[1024]; - char *pCommand; - int iRet; - - pCommand = Arg2Tcl(argc-1,&argv[1],pBuffer, sizeof(pBuffer)); - if (!pCommand) { - SCWrite(pCon,"ERROR: no memory", eError); - return 0; - } - strtolower(argv[0]); - if(strcmp(argv[0],"fulltransact") == 0){ - SCPrintf(pCon,eLog, "TRANSACTIONSTART %s",pCommand); - } - iRet = InterpExecute(pSics,pCon,pCommand); - if (pCommand != pBuffer) free(pCommand); - SCWrite(pCon,"TRANSACTIONFINISHED",eLog); - return iRet; - } - - - - - - - - - +int TransactAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBuffer[1024]; + char *pCommand; + int iRet; + pCommand = Arg2Tcl(argc - 1, &argv[1], pBuffer, sizeof(pBuffer)); + if (!pCommand) { + SCWrite(pCon, "ERROR: no memory", eError); + return 0; + } + strtolower(argv[0]); + if (strcmp(argv[0], "fulltransact") == 0) { + SCPrintf(pCon, eLog, "TRANSACTIONSTART %s", pCommand); + } + iRet = InterpExecute(pSics, pCon, pCommand); + if (pCommand != pBuffer) + free(pCommand); + SCWrite(pCon, "TRANSACTIONFINISHED", eLog); + return iRet; +} diff --git a/macro.h b/macro.h index 2bd8fa78..6ddf752d 100644 --- a/macro.h +++ b/macro.h @@ -17,41 +17,38 @@ #include "sics.h" #include "SCinter.h" - Tcl_Interp *MacroInit(SicsInterp *pInter); - void MacroDelete(Tcl_Interp *pInter); - void WhereKill(void *pData); - - int MacroEval(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int MacroFileEval(SConnection *pCon, SicsInterp *pInter, void *pData, +Tcl_Interp *MacroInit(SicsInterp * pInter); +void MacroDelete(Tcl_Interp * pInter); +void WhereKill(void *pData); + +int MacroEval(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int MacroFileEval(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]); +int InternalFileEval(SConnection * pCon, SicsInterp * pInter, void *pData, int argc, char *argv[]); - int InternalFileEval(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]); - int MacroWhere(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]); - int ClientPut(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]); - int GumPut(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]); - int Broadcast(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]); - int TransactAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - - int TclPublish(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]); - int AllowExec(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]); - +int MacroWhere(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]); +int ClientPut(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]); +int GumPut(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]); +int Broadcast(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]); +int TransactAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +int TclPublish(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]); +int AllowExec(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]); + /* for maintaining the Connection stack at Unknown. Should only be used by SicsInterp module - */ - int MacroPush(SConnection *pCon); - int MacroPop(void); - - void KillSicsUnknown(void); + */ +int MacroPush(SConnection * pCon); +int MacroPop(void); + +void KillSicsUnknown(void); #endif - - - diff --git a/make_gen b/make_gen index 0f33b003..8e4cf5ed 100644 --- a/make_gen +++ b/make_gen @@ -40,7 +40,7 @@ SOBJ = network.o ifile.o conman.o SCinter.o splitter.o passwd.o \ sctdriveadapter.o sctdriveobj.o reflist.o singlex.o fourmess.o \ sgclib.o sgfind.o sgio.o sgsi.o sghkl.o singlediff.o singlebi.o \ singlenb.o simindex.o simidx.o uselect.o singletas.o motorsec.o \ - rwpuffer.o asynnet.o background.o + rwpuffer.o asynnet.o background.o countersec.o MOTOROBJ = motor.o simdriv.o COUNTEROBJ = countdriv.o simcter.o counter.o diff --git a/maximize.c b/maximize.c index f6a3c99f..67c304da 100644 --- a/maximize.c +++ b/maximize.c @@ -52,524 +52,452 @@ #define MAXPTS 100 #define DEBUG 0 - typedef struct __MAXIMIZE { - pObjectDescriptor pDes; - pCounter pCount; - int i360; - int maxpts; - }Maxxii; +typedef struct __MAXIMIZE { + pObjectDescriptor pDes; + pCounter pCount; + int i360; + int maxpts; +} Maxxii; /*----------------------------------------------------------------------- put into 360 degree range if 360 degree flag is active. */ - static float in360(pMax self, float fVal) - { - if(self->i360) - { - if(fVal < 0.) - fVal = 360. + fVal; - if(fVal > 360.) - fVal = fVal - 360.; - } - return fVal; - } +static float in360(pMax self, float fVal) +{ + if (self->i360) { + if (fVal < 0.) + fVal = 360. + fVal; + if (fVal > 360.) + fVal = fVal - 360.; + } + return fVal; +} + /*---------------------------------------------------------------------*/ - static int maxDrive(void *pObject, char *pVarName, - float fPos, SConnection *pCon) - { - pDummy pDum; - int status; - char pBueffel[132]; - long lTask; +static int maxDrive(void *pObject, char *pVarName, + float fPos, SConnection * pCon) +{ + pDummy pDum; + int status; + char pBueffel[132]; + long lTask; - /* start */ - pDum = (pDummy)pObject; - status = StartDevice(pServ->pExecutor, - pVarName, - pDum->pDescriptor, - pObject, - pCon, - fPos); - if(!status) - { - sprintf(pBueffel,"ERROR: failed to start %s",pVarName); - SCWrite(pCon,pBueffel,eError); - return 0; - } + /* start */ + pDum = (pDummy) pObject; + status = StartDevice(pServ->pExecutor, + pVarName, pDum->pDescriptor, pObject, pCon, fPos); + if (!status) { + sprintf(pBueffel, "ERROR: failed to start %s", pVarName); + SCWrite(pCon, pBueffel, eError); + return 0; + } - /* wait */ - lTask = GetDevexecID(pServ->pExecutor); - if(lTask > 0) - { - TaskWait(pServ->pTasker,lTask); - } - else - { - return 0; - } + /* wait */ + lTask = GetDevexecID(pServ->pExecutor); + if (lTask > 0) { + TaskWait(pServ->pTasker, lTask); + } else { + return 0; + } + + /* check interrupts */ + if (SCGetInterrupt(pCon) >= eAbortScan) { + SCWrite(pCon, "ERROR: Maximizing interrupted", eError); + return 0; + } + return 1; +} - /* check interrupts */ - if(SCGetInterrupt(pCon) >= eAbortScan) - { - SCWrite(pCon,"ERROR: Maximizing interrupted",eError); - return 0; - } - return 1; - } /*----------------------------------------------------------------------*/ - static int maxCount(void *pCount, CounterMode eMode, - float fPreset, long *lCts, SConnection *pCon) - { - int iRet; +static int maxCount(void *pCount, CounterMode eMode, + float fPreset, long *lCts, SConnection * pCon) +{ + int iRet; + + SetCounterMode((pCounter) pCount, eMode); + iRet = DoCount((pCounter) pCount, fPreset, pCon, 1); + if (!iRet) { + return 0; + } + *lCts = GetCounts((pCounter) pCount, pCon); + if (SCGetInterrupt(pCon) >= eAbortScan) { + SCWrite(pCon, "ERROR: maximizing aborted", eError); + return 0; + } + return 1; +} - SetCounterMode((pCounter)pCount,eMode); - iRet = DoCount((pCounter)pCount, fPreset, pCon,1); - if(!iRet) - { - return 0; - } - *lCts = GetCounts((pCounter)pCount,pCon); - if(SCGetInterrupt(pCon) >= eAbortScan) - { - SCWrite(pCon,"ERROR: maximizing aborted",eError); - return 0; - } - return 1; - } /*----------------------------------------------------------------------*/ - static float readMPDrivable(void *pVar, SConnection *pCon) - { - float value = -999.99; - pIDrivable pDriv = NULL; - pDummy pDum = (pDummy)pVar; +static float readMPDrivable(void *pVar, SConnection * pCon) +{ + float value = -999.99; + pIDrivable pDriv = NULL; + pDummy pDum = (pDummy) pVar; + + pDriv = GetDrivableInterface(pVar); + assert(pDriv != NULL); + value = pDriv->GetValue(pVar, pCon); + return value; +} - pDriv = GetDrivableInterface(pVar); - assert(pDriv != NULL); - value = pDriv->GetValue(pVar,pCon); - return value; - } /*-----------------------------------------------------------------------*/ - int MaximizePeak(pMax self, void *pVar, char *pVarName, - float fStep, CounterMode eMode, - float fPreset, SConnection *pCon) - { - float x[MAXPTS], y[MAXPTS]; - float fMax, fCent, fS, fArea, fStart, fPos, fDA, fDisc; - int iBot, iTop, iMax, i, iRet, iSkip, iTMin, iTMax; - pIDrivable pDriv = NULL; - long lCts, lMax, lMin; - char pBueffel[132]; +int MaximizePeak(pMax self, void *pVar, char *pVarName, + float fStep, CounterMode eMode, + float fPreset, SConnection * pCon) +{ + float x[MAXPTS], y[MAXPTS]; + float fMax, fCent, fS, fArea, fStart, fPos, fDA, fDisc; + int iBot, iTop, iMax, i, iRet, iSkip, iTMin, iTMax; + pIDrivable pDriv = NULL; + long lCts, lMax, lMin; + char pBueffel[132]; - /* get drivable interface */ - pDriv = GetDrivableInterface(pVar); - if(!pDriv) - { - SCWrite(pCon,"ERROR: variable is NOT drivable, cannot maximize", - eError); - return 0; + /* get drivable interface */ + pDriv = GetDrivableInterface(pVar); + if (!pDriv) { + SCWrite(pCon, "ERROR: variable is NOT drivable, cannot maximize", + eError); + return 0; + } + +start: + lMax = 0; + lMin = 0x7fffffff; + fStart = readMPDrivable(pVar, pCon); + if (fStart < -999999.) { + return 0; + } + + /* search to the left until out of space or lCts < lMax/2. */ + SCWrite(pCon, "Searching for low angle boundary..", eWarning); + for (i = self->maxpts / 2; i >= 0; i--) { + /* drive motor */ + fPos = fStart - (self->maxpts / 2 - i) * fStep; + fPos = in360(self, fPos); + if (maxDrive(pVar, pVarName, fPos, pCon) != 1) { + return 0; + } + x[i] = readMPDrivable(pVar, pCon); + /* count */ + if (maxCount(self->pCount, eMode, fPreset, &lCts, pCon) != 1) { + return 0; + } + /* print a message */ + sprintf(pBueffel, "%5d %8.2f %ld", i, x[i], lCts); + SCWrite(pCon, pBueffel, eWarning); + + /* store counts and some logic */ + if (lCts < 1) { + y[i] = 0.; + } else { + y[i] = (float) lCts; + } + if (lCts > lMax) { + lMax = lCts; + iMax = i; + } + if (lCts < lMin) { + lMin = lCts; + } + if (lCts < lMax / 2) { + break; + } + } + /* some logic: the four cases */ + iSkip = 0; + iBot = i; + /* first case: peak out of range: do again */ + if ((iMax == 0) && (lMax / 2 > lMin)) { + goto start; + } + /* no peak found or normal peak: continue at other side */ + if ((i < 1) || (y[self->maxpts / 2] > lMax / 2)) { + iSkip = 0; + } else { + /* next case: all of the peak in measured half: + find max value and skip the right half + */ + for (i = self->maxpts / 2; i > 0; i--) { + if (y[i] > lMax / 2) { + iTop = i + 1; + break; } + } + iSkip = 1; + } - start: - lMax = 0; - lMin = 0x7fffffff; - fStart = readMPDrivable(pVar,pCon); - if(fStart < -999999.) - { - return 0; - } + /* + do the same to the right hand side, but only if required + */ + if (iSkip == 0) { + lMin = 100000; + lMax = -100000; + SCWrite(pCon, "Searching for high angle boundary..", eWarning); + for (i = self->maxpts / 2; i < self->maxpts; i++) { + /* drive motor */ + fPos = fStart + (i - self->maxpts / 2) * fStep; + fPos = in360(self, fPos); + if (maxDrive(pVar, pVarName, fPos, pCon) != 1) { + return 0; + } + x[i] = readMPDrivable(pVar, pCon); + /* count */ + if (maxCount(self->pCount, eMode, fPreset, &lCts, pCon) != 1) { + return 0; + } + /* print a message */ + sprintf(pBueffel, "%5d %8.2f %ld", i, x[i], lCts); + SCWrite(pCon, pBueffel, eWarning); - /* search to the left until out of space or lCts < lMax/2. */ - SCWrite(pCon,"Searching for low angle boundary..",eWarning); - for(i = self->maxpts/2; i >= 0; i--) - { - /* drive motor */ - fPos = fStart - (self->maxpts/2 - i)*fStep; - fPos = in360(self,fPos); - if(maxDrive(pVar,pVarName,fPos,pCon) != 1) - { - return 0; - } - x[i] = readMPDrivable(pVar,pCon); - /* count */ - if(maxCount(self->pCount,eMode,fPreset, &lCts,pCon) != 1) - { - return 0; - } - /* print a message */ - sprintf(pBueffel,"%5d %8.2f %ld",i,x[i],lCts); - SCWrite(pCon,pBueffel,eWarning); - - /* store counts and some logic */ - if(lCts < 1) - { - y[i] = 0.; - } - else - { - y[i] = (float)lCts; - } - if(lCts > lMax) - { - lMax = lCts; - iMax = i; - } - if(lCts < lMin) - { - lMin = lCts; - } - if(lCts < lMax/2) - { - break; - } - } - /* some logic: the four cases */ - iSkip = 0; - iBot = i; - /* first case: peak out of range: do again */ - if( (iMax == 0) && (lMax/2 > lMin) ) - { - goto start; - } - /* no peak found or normal peak: continue at other side */ - if( (i < 1) || (y[self->maxpts/2] > lMax/2) ) - { - iSkip = 0; - } - else - { - /* next case: all of the peak in measured half: - find max value and skip the right half - */ - for(i = self->maxpts/2; i > 0; i--) - { - if(y[i] > lMax/2) - { - iTop = i + 1; - break; - } - } - iSkip = 1; - } - - /* - do the same to the right hand side, but only if required - */ - if(iSkip == 0) - { - lMin = 100000; - lMax = -100000; - SCWrite(pCon,"Searching for high angle boundary..",eWarning); - for(i = self->maxpts/2; i < self->maxpts; i++) - { - /* drive motor */ - fPos = fStart + (i - self->maxpts/2) * fStep; - fPos = in360(self,fPos); - if(maxDrive(pVar,pVarName,fPos,pCon) != 1) - { - return 0; - } - x[i] = readMPDrivable(pVar,pCon); - /* count */ - if(maxCount(self->pCount,eMode,fPreset, &lCts,pCon) != 1) - { - return 0; - } - /* print a message */ - sprintf(pBueffel,"%5d %8.2f %ld",i,x[i],lCts); - SCWrite(pCon,pBueffel,eWarning); - - /* store counts and some logic */ - if(lCts < 1) - { - y[i] = 0.; - } - else - { - y[i] = (float)lCts; - } - if(lCts > lMax) - { - lMax = lCts; - iMax = i; - } - if(lCts < lMin) - { - lMin = lCts; - } - if(lCts < lMax/2) - { - break; - } - } - /* some logic again: four cases */ - iTop = i; - iTop++; - /* first case: peak is at high angle side */ - if( (i > self->maxpts-2) && (lMax*0.5 > lMin) ) - { - goto start; - } - /* second case: no peak */ - if( (iTop > self->maxpts-2) ) - { - SCWrite(pCon,"ERROR: no peak found!",eError); - return 0; - } - /* third case: normal peak */ - if(y[self->maxpts/2] >= 0.5*lMax) - { - iTop--; - } - /* - fourth case: the peak is completely at the high angle - side - */ - else - { - for(i = self->maxpts/2; i < self->maxpts; i++) - { - if(y[i] > lMax/2) - { - iBot = i - 1; - break; - } - } - iTop--; - } - } /* end of iSkip */ - - if( (iBot < 2) || (iTop > self->maxpts-2) || (lMax < lMin*2) ) - { - SCWrite(pCon,"ERROR: no peak found!",eError); - return 0; - } + /* store counts and some logic */ + if (lCts < 1) { + y[i] = 0.; + } else { + y[i] = (float) lCts; + } + if (lCts > lMax) { + lMax = lCts; + iMax = i; + } + if (lCts < lMin) { + lMin = lCts; + } + if (lCts < lMax / 2) { + break; + } + } + /* some logic again: four cases */ + iTop = i; + iTop++; + /* first case: peak is at high angle side */ + if ((i > self->maxpts - 2) && (lMax * 0.5 > lMin)) { + goto start; + } + /* second case: no peak */ + if ((iTop > self->maxpts - 2)) { + SCWrite(pCon, "ERROR: no peak found!", eError); + return 0; + } + /* third case: normal peak */ + if (y[self->maxpts / 2] >= 0.5 * lMax) { + iTop--; + } + /* + fourth case: the peak is completely at the high angle + side + */ + else { + for (i = self->maxpts / 2; i < self->maxpts; i++) { + if (y[i] > lMax / 2) { + iBot = i - 1; + break; + } + } + iTop--; + } + } + /* end of iSkip */ + if ((iBot < 2) || (iTop > self->maxpts - 2) || (lMax < lMin * 2)) { + SCWrite(pCon, "ERROR: no peak found!", eError); + return 0; + } #ifdef DEBUG - sprintf(pBueffel,"iBot = %d, iTop = %d, lMax = %ld", - iBot, iTop, lMax); - SCWrite(pCon,pBueffel,eWarning); -#endif - - /* calculate median */ - fArea = 0.; - for(i = iBot; i < iTop; i++) - { - fArea += (x[i+1] - x[i])*(y[i+1] + y[i])*.25; - } - fS = 0.; - for(i = iBot; i < iTop; i++) - { - fS += (x[i+1] -x[i])*(y[i+1] +y[i]) *.5; - if(fS > fArea) - { - break; - } - } - fS -= .5*(x[i+1] - x[i])*(y[i+1] + y[i]); - fDA = fArea - fS; - if(y[i+1] == y[i]) - { - fCent = x[i] + fDA/y[i]; - } - else - { - fS = (y[i+1] - y[i])/(x[i+1] -x[i]); - if( (y[i]*y[i] + 2. * fS * fDA) < 0.) - { - SCWrite(pCon,"ERROR calculating median",eError); - return 0; - } - fDisc = sqrt(y[i]*y[i] + 2.* fS * fDA); - fCent = x[i] +(fDisc -y[i])/fS; - } - /* finished ! */ - for(i = 0; i < iTop-1; i++){ - if(fCent >= x[i] && fCent < x[i+1] ){ - lCts = y[i]; - break; - } - } - maxDrive(pVar,pVarName,fCent,pCon); - sprintf(pBueffel,"Found peak center at %8.2f, Count = %ld", fCent, lCts); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + sprintf(pBueffel, "iBot = %d, iTop = %d, lMax = %ld", iBot, iTop, lMax); + SCWrite(pCon, pBueffel, eWarning); +#endif + + /* calculate median */ + fArea = 0.; + for (i = iBot; i < iTop; i++) { + fArea += (x[i + 1] - x[i]) * (y[i + 1] + y[i]) * .25; + } + fS = 0.; + for (i = iBot; i < iTop; i++) { + fS += (x[i + 1] - x[i]) * (y[i + 1] + y[i]) * .5; + if (fS > fArea) { + break; + } + } + fS -= .5 * (x[i + 1] - x[i]) * (y[i + 1] + y[i]); + fDA = fArea - fS; + if (y[i + 1] == y[i]) { + fCent = x[i] + fDA / y[i]; + } else { + fS = (y[i + 1] - y[i]) / (x[i + 1] - x[i]); + if ((y[i] * y[i] + 2. * fS * fDA) < 0.) { + SCWrite(pCon, "ERROR calculating median", eError); + return 0; + } + fDisc = sqrt(y[i] * y[i] + 2. * fS * fDA); + fCent = x[i] + (fDisc - y[i]) / fS; + } + /* finished ! */ + for (i = 0; i < iTop - 1; i++) { + if (fCent >= x[i] && fCent < x[i + 1]) { + lCts = y[i]; + break; + } + } + maxDrive(pVar, pVarName, fCent, pCon); + sprintf(pBueffel, "Found peak center at %8.2f, Count = %ld", fCent, + lCts); + SCWrite(pCon, pBueffel, eValue); + return 1; +} + /*------------------------------------------------------------------*/ - static void MaxKill(void *pData) - { - pMax self = (pMax)pData; - if(self == NULL) - return; +static void MaxKill(void *pData) +{ + pMax self = (pMax) pData; + if (self == NULL) + return; + + if (self->pDes) + DeleteDescriptor(self->pDes); + free(self); +} - if(self->pDes) - DeleteDescriptor(self->pDes); - free(self); - } /*-------------------- wrap-i-wrap ----------------------------------*/ - int MaximizeFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pMax pNew = NULL; - CommandList *pCom = NULL; - pICountable pCts = NULL; +int MaximizeFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pMax pNew = NULL; + CommandList *pCom = NULL; + pICountable pCts = NULL; - if(argc < 2) - { - SCWrite(pCon, - "ERROR: insufficient number of arguments to MaximizeFactory", - eError); - return 0; - } + if (argc < 2) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to MaximizeFactory", + eError); + return 0; + } - /* find a countable */ - pCom = FindCommand(pSics,argv[1]); - if(pCom == NULL) - { - SCWrite(pCon,"ERROR: counter not found in MaximizeFactory", - eError); - return 0; - } - pCts = GetCountableInterface(pCom->pData); - if(!pCts) - { - SCWrite(pCon,"ERROR: argument to MaximizeFactory is no counter", - eError); - return 0; - } - pNew = (pMax)malloc(sizeof(Maxxii)); - pNew->pDes = CreateDescriptor("Maximizer"); - pNew->pCount = pCom->pData; - pNew->i360 = 0; - pNew->maxpts = 100; + /* find a countable */ + pCom = FindCommand(pSics, argv[1]); + if (pCom == NULL) { + SCWrite(pCon, "ERROR: counter not found in MaximizeFactory", eError); + return 0; + } + pCts = GetCountableInterface(pCom->pData); + if (!pCts) { + SCWrite(pCon, "ERROR: argument to MaximizeFactory is no counter", + eError); + return 0; + } + pNew = (pMax) malloc(sizeof(Maxxii)); + pNew->pDes = CreateDescriptor("Maximizer"); + pNew->pCount = pCom->pData; + pNew->i360 = 0; + pNew->maxpts = 100; + + AddCommand(pSics, "max", MaximizeAction, MaxKill, pNew); + return 1; +} - AddCommand(pSics,"max",MaximizeAction,MaxKill,pNew); - return 1; - } /*------------------------------------------------------------------ * max motor step preset mode * ---------------------------------------------------------------------*/ - int MaximizeAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pMax self = NULL; - CommandList *pCom = NULL; - char pBueffel[256]; - double dVal; - float fStep, fPreset; - CounterMode eCount; - int iRet, iVal; +int MaximizeAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pMax self = NULL; + CommandList *pCom = NULL; + char pBueffel[256]; + double dVal; + float fStep, fPreset; + CounterMode eCount; + int iRet, iVal; - self = (pMax)pData; - assert(self); - assert(pCon); + self = (pMax) pData; + assert(self); + assert(pCon); - /* check privilege */ - if(!SCMatchRights(pCon,usUser)) - { - return 1; - } + /* check privilege */ + if (!SCMatchRights(pCon, usUser)) { + return 1; + } - /* enough arguments ?*/ - if(argc < 5) - { - if(argc > 1) - { - strtolower(argv[1]); - if(strcmp(argv[1],"in360") == 0) - { - if(argc > 2) - { - iVal = atoi(argv[2]); - if(iVal != 0 && iVal != 1) { - SCWrite(pCon,"ERROR: only 0, 1 allowed for in360",eError); - return 0; - } - self->i360 = iVal; - SCSendOK(pCon); - return 1; - } - else - { - snprintf(pBueffel,255,"max.in360 = %d", self->i360); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - if(strcmp(argv[1],"maxpts") == 0) - { - if(argc > 2) - { - iVal = atoi(argv[2]); - if(iVal < 10 || iVal > 100) { - SCWrite(pCon,"ERROR: maxpst must be between 10 and 100", - eError); - return 0; - } - self->maxpts = iVal; - SCSendOK(pCon); - return 1; - } - else - { - snprintf(pBueffel,255,"max.maxpts = %d", self->maxpts); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - + /* enough arguments ? */ + if (argc < 5) { + if (argc > 1) { + strtolower(argv[1]); + if (strcmp(argv[1], "in360") == 0) { + if (argc > 2) { + iVal = atoi(argv[2]); + if (iVal != 0 && iVal != 1) { + SCWrite(pCon, "ERROR: only 0, 1 allowed for in360", eError); + return 0; + } + self->i360 = iVal; + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 255, "max.in360 = %d", self->i360); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + if (strcmp(argv[1], "maxpts") == 0) { + if (argc > 2) { + iVal = atoi(argv[2]); + if (iVal < 10 || iVal > 100) { + SCWrite(pCon, "ERROR: maxpst must be between 10 and 100", + eError); + return 0; + } + self->maxpts = iVal; + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 255, "max.maxpts = %d", self->maxpts); + SCWrite(pCon, pBueffel, eValue); + return 1; } - SCWrite(pCon,"ERROR: Insufficient number of arguments to max", - eError); - return 0; - } - - /* decode arguments */ - pCom = FindCommand(pSics,argv[1]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: object %s NOT found!", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!pCom->pData) - { - sprintf(pBueffel,"ERROR: object %s Invalid!!", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - iRet = Tcl_GetDouble(pSics->pTcl,argv[2], &dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; } - fStep = (float)dVal; - iRet = Tcl_GetDouble(pSics->pTcl,argv[4], &dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[4]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fPreset = (float)dVal; + } + SCWrite(pCon, "ERROR: Insufficient number of arguments to max", + eError); + return 0; + } - /* convert countmode */ - strtolower(argv[3]); - if(strcmp(argv[3],"timer") == 0) - { - eCount = eTimer; - } - else - { - eCount = ePreset; - } - return MaximizePeak(self,pCom->pData, argv[1],fStep,eCount, - fPreset, pCon); - } + /* decode arguments */ + pCom = FindCommand(pSics, argv[1]); + if (!pCom) { + sprintf(pBueffel, "ERROR: object %s NOT found!", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!pCom->pData) { + sprintf(pBueffel, "ERROR: object %s Invalid!!", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fStep = (float) dVal; + + iRet = Tcl_GetDouble(pSics->pTcl, argv[4], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", argv[4]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fPreset = (float) dVal; + + /* convert countmode */ + strtolower(argv[3]); + if (strcmp(argv[3], "timer") == 0) { + eCount = eTimer; + } else { + eCount = ePreset; + } + return MaximizePeak(self, pCom->pData, argv[1], fStep, eCount, + fPreset, pCon); +} diff --git a/maximize.h b/maximize.h index 06fd64c2..c38abd7b 100644 --- a/maximize.h +++ b/maximize.h @@ -12,11 +12,11 @@ #ifndef SICSMAXIMIZE #define SICSMAXIMIZE - typedef struct __MAXIMIZE *pMax; +typedef struct __MAXIMIZE *pMax; - int MaximizePeak(pMax self, void *pVar, char *pVarName, - float fStep, CounterMode eMode, - float fPreset, SConnection *pCon); +int MaximizePeak(pMax self, void *pVar, char *pVarName, + float fStep, CounterMode eMode, + float fPreset, SConnection * pCon); /* * Locates the maximum of a peak with respect to the motor or virtual @@ -26,10 +26,8 @@ * reported. */ /*------------------------ Wrapper functions ----------------------------*/ - int MaximizeFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int MaximizeAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MaximizeFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int MaximizeAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif - - diff --git a/mccontrol.c b/mccontrol.c index 1927259e..0361cd96 100644 --- a/mccontrol.c +++ b/mccontrol.c @@ -17,435 +17,466 @@ #include "stringdict.h" #include "mccontrol.h" /*========================= life and death ==================================*/ -static void KillMcStasController(void *pData){ - pMcStasController self = (pMcStasController)pData; - if(self == NULL){ - return; - } - if(self->pDes != NULL){ - DeleteDescriptor(self->pDes); - } - if(self->scripts != NULL){ - DeleteStringDict(self->scripts); - } - free(self); +static void KillMcStasController(void *pData) +{ + pMcStasController self = (pMcStasController) pData; + if (self == NULL) { + return; + } + if (self->pDes != NULL) { + DeleteDescriptor(self->pDes); + } + if (self->scripts != NULL) { + DeleteStringDict(self->scripts); + } + free(self); } + /*---------------------------------------------------------------------------*/ -int McStasControllerFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - pMcStasController pNew = NULL; - - pNew = (pMcStasController)malloc(sizeof(McStasController)); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating McStasController", - eError); - return 0; - } - memset(pNew,0,sizeof(McStasController)); - - pNew->pDes = CreateDescriptor("McStasController"); - pNew->scripts = CreateStringDict(); - if(pNew->pDes == NULL || pNew->scripts == NULL){ - SCWrite(pCon,"ERROR: out of memory creating McStasController", - eError); - free(pNew); - return 0; - } - StringDictAddPair(pNew->scripts,"mcstart","UNDEFINED"); - StringDictAddPair(pNew->scripts,"mcisrunning","UNDEFINED"); - StringDictAddPair(pNew->scripts,"mcdump","UNDEFINED"); - StringDictAddPair(pNew->scripts,"mckill","UNDEFINED"); - StringDictAddPair(pNew->scripts,"mccopydata","UNDEFINED"); - StringDictAddPair(pNew->scripts,"mcmonfile","UNDEFINED"); - pNew->pid = -1; - pNew->monitorScale = 1; - - return AddCommand(pSics,"mccontrol", - McStasControllerWrapper, - KillMcStasController, - pNew); -} -/*====================== interpreter interface ============================*/ -static int configureController(pMcStasController self, SConnection *pCon, - int argc, char *argv[]){ - char pBueffel[256]; - - if(argc < 4){ - SCWrite(pCon, - "ERRROR: insufficient number of arguments to mccontrol configure", - eError); - return 0; - } - strtolower(argv[2]); - if(strcmp(argv[2],"update") == 0){ - self->updateIntervall = atoi(argv[3]); - SCSendOK(pCon); - return 1; - } - if(strcmp(argv[2],"monitorscale") == 0){ - self->monitorScale = atof(argv[3]); - if(self->monitorScale <= 0){ - SCWrite(pCon,"ERROR: invalid monitor scale",eError); - self->monitorScale = 1; - return 0; - } - SCSendOK(pCon); - return 1; - } - if(!StringDictExists(self->scripts,argv[2])){ - snprintf(pBueffel,255,"ERROR: scriptkey %s does not exist",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - StringDictUpdate(self->scripts,argv[2],argv[3]); - SCSendOK(pCon); - return 1; -} -/*------------------------------------------------------------------------*/ -static void listConfiguration(pMcStasController self, SConnection *pCon){ - Tcl_DString txt; - char pLine[256]; - char pScript[131]; - - Tcl_DStringInit(&txt); - StringDictGet(self->scripts,"mcstart",pScript,131); - snprintf(pLine,255,"mccontrol.mcstart = %s\n",pScript); - Tcl_DStringAppend(&txt,pLine,-1); - StringDictGet(self->scripts,"mcisrunning",pScript,131); - snprintf(pLine,255,"mccontrol.mcisrunning = %s\n",pScript); - Tcl_DStringAppend(&txt,pLine,-1); - StringDictGet(self->scripts,"mcdump",pScript,131); - snprintf(pLine,255,"mccontrol.mcdump = %s\n",pScript); - Tcl_DStringAppend(&txt,pLine,-1); - StringDictGet(self->scripts,"mckill",pScript,131); - snprintf(pLine,255,"mccontrol.mckill = %s\n",pScript); - Tcl_DStringAppend(&txt,pLine,-1); - StringDictGet(self->scripts,"mccopydata",pScript,131); - snprintf(pLine,255,"mccontrol.mccopydata = %s\n",pScript); - Tcl_DStringAppend(&txt,pLine,-1); - StringDictGet(self->scripts,"mcmonfile",pScript,131); - snprintf(pLine,255,"mccontrol.mcmonfile = %s\n",pScript); - Tcl_DStringAppend(&txt,pLine,-1); - snprintf(pLine,255,"mccontrol.updateintervall = %d\n", - self->updateIntervall); - Tcl_DStringAppend(&txt,pLine,-1); - snprintf(pLine,255,"mccontrol.monitorscale = %f\n", - self->monitorScale); - Tcl_DStringAppend(&txt,pLine,-1); - snprintf(pLine,255,"mccontrol.pid = %d", self->pid); - Tcl_DStringAppend(&txt,pLine,-1); +int McStasControllerFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pMcStasController pNew = NULL; - SCWrite(pCon,Tcl_DStringValue(&txt),eValue); - Tcl_DStringFree(&txt); + pNew = (pMcStasController) malloc(sizeof(McStasController)); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating McStasController", + eError); + return 0; + } + memset(pNew, 0, sizeof(McStasController)); + + pNew->pDes = CreateDescriptor("McStasController"); + pNew->scripts = CreateStringDict(); + if (pNew->pDes == NULL || pNew->scripts == NULL) { + SCWrite(pCon, "ERROR: out of memory creating McStasController", + eError); + free(pNew); + return 0; + } + StringDictAddPair(pNew->scripts, "mcstart", "UNDEFINED"); + StringDictAddPair(pNew->scripts, "mcisrunning", "UNDEFINED"); + StringDictAddPair(pNew->scripts, "mcdump", "UNDEFINED"); + StringDictAddPair(pNew->scripts, "mckill", "UNDEFINED"); + StringDictAddPair(pNew->scripts, "mccopydata", "UNDEFINED"); + StringDictAddPair(pNew->scripts, "mcmonfile", "UNDEFINED"); + pNew->pid = -1; + pNew->monitorScale = 1; + + return AddCommand(pSics, "mccontrol", + McStasControllerWrapper, KillMcStasController, pNew); } + +/*====================== interpreter interface ============================*/ +static int configureController(pMcStasController self, SConnection * pCon, + int argc, char *argv[]) +{ + char pBueffel[256]; + + if (argc < 4) { + SCWrite(pCon, + "ERRROR: insufficient number of arguments to mccontrol configure", + eError); + return 0; + } + strtolower(argv[2]); + if (strcmp(argv[2], "update") == 0) { + self->updateIntervall = atoi(argv[3]); + SCSendOK(pCon); + return 1; + } + if (strcmp(argv[2], "monitorscale") == 0) { + self->monitorScale = atof(argv[3]); + if (self->monitorScale <= 0) { + SCWrite(pCon, "ERROR: invalid monitor scale", eError); + self->monitorScale = 1; + return 0; + } + SCSendOK(pCon); + return 1; + } + if (!StringDictExists(self->scripts, argv[2])) { + snprintf(pBueffel, 255, "ERROR: scriptkey %s does not exist", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + StringDictUpdate(self->scripts, argv[2], argv[3]); + SCSendOK(pCon); + return 1; +} + +/*------------------------------------------------------------------------*/ +static void listConfiguration(pMcStasController self, SConnection * pCon) +{ + Tcl_DString txt; + char pLine[256]; + char pScript[131]; + + Tcl_DStringInit(&txt); + StringDictGet(self->scripts, "mcstart", pScript, 131); + snprintf(pLine, 255, "mccontrol.mcstart = %s\n", pScript); + Tcl_DStringAppend(&txt, pLine, -1); + StringDictGet(self->scripts, "mcisrunning", pScript, 131); + snprintf(pLine, 255, "mccontrol.mcisrunning = %s\n", pScript); + Tcl_DStringAppend(&txt, pLine, -1); + StringDictGet(self->scripts, "mcdump", pScript, 131); + snprintf(pLine, 255, "mccontrol.mcdump = %s\n", pScript); + Tcl_DStringAppend(&txt, pLine, -1); + StringDictGet(self->scripts, "mckill", pScript, 131); + snprintf(pLine, 255, "mccontrol.mckill = %s\n", pScript); + Tcl_DStringAppend(&txt, pLine, -1); + StringDictGet(self->scripts, "mccopydata", pScript, 131); + snprintf(pLine, 255, "mccontrol.mccopydata = %s\n", pScript); + Tcl_DStringAppend(&txt, pLine, -1); + StringDictGet(self->scripts, "mcmonfile", pScript, 131); + snprintf(pLine, 255, "mccontrol.mcmonfile = %s\n", pScript); + Tcl_DStringAppend(&txt, pLine, -1); + snprintf(pLine, 255, "mccontrol.updateintervall = %d\n", + self->updateIntervall); + Tcl_DStringAppend(&txt, pLine, -1); + snprintf(pLine, 255, "mccontrol.monitorscale = %f\n", + self->monitorScale); + Tcl_DStringAppend(&txt, pLine, -1); + snprintf(pLine, 255, "mccontrol.pid = %d", self->pid); + Tcl_DStringAppend(&txt, pLine, -1); + + SCWrite(pCon, Tcl_DStringValue(&txt), eValue); + Tcl_DStringFree(&txt); +} + /*--------------------------------------------------------------------------*/ -static int invokeScript(pMcStasController self, char *name, SicsInterp *pSics, - char *result, int resultLen){ - char pCommand[256], pScript[132], pMode[10]; - Tcl_Interp *pTcl; - int status; - - if(!StringDictGet(self->scripts,name,pScript,131)){ - strncpy(result,"ERROR: script not found",resultLen); - return 0; - } - - if(strcmp(name,"mccopydata") == 0){ - snprintf(pCommand,255,"%s",pScript); - }else if(strcmp(name,"mcstart") == 0){ - if(self->mode == eTimer){ - strcpy(pMode,"timer"); - }else { - strcpy(pMode,"monitor"); - } - snprintf(pCommand,255,"%s %s %f", pScript,pMode,self->fPreset); - } else { - snprintf(pCommand,255,"%s %d",pScript,self->pid); - } - - pTcl = InterpGetTcl(pSics); - status = Tcl_Eval(pTcl,pCommand); - strncpy(result, pTcl->result, resultLen); - if(status == TCL_OK){ - return 1; - } else { - return 0; - } -} -/*------------------------------------------------------------------------*/ -static int runScript(pMcStasController self, SConnection *pCon, - SicsInterp *pSics, int argc, char *argv[]){ - char pResult[256]; - int status; - - if(argc < 3){ - SCWrite(pCon, - "ERRROR: insufficient number of arguments to mccontrol run", - eError); - return 0; - } - status = invokeScript(self,argv[2],pSics,pResult,255); - if(status == 1){ - SCWrite(pCon,pResult,eValue); - return 1; - } else { - SCWrite(pCon,pResult,eError); - return 0; - } -} -/*------------------------------------------------------------------------*/ -static int start(pMcStasController self, SConnection *pCon){ - int status; +static int invokeScript(pMcStasController self, char *name, + SicsInterp * pSics, char *result, int resultLen) +{ + char pCommand[256], pScript[132], pMode[10]; + Tcl_Interp *pTcl; + int status; - status = McStasStart(self,eTimer,1000.); - if(status != OKOK){ - SCWrite(pCon,self->errorText,eError); - return 0; - } - SCSendOK(pCon); - return 1; -} -/*-----------------------------------------------------------------------*/ -static void wait4Finish(pMcStasController self){ - int status; - - if(self->pid > 0){ - status = waitpid(self->pid,NULL,WNOHANG); - if(status >= 0){ - self->pid = -1; - } - } -} -/*-------------------------------------------------------------------------*/ -int McStasControllerWrapper(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - pMcStasController self = NULL; - char pBueffel[255], pFile[132]; - - self = (pMcStasController)pData; - assert(self); - if(argc < 2) { - SCWrite(pCon,"ERROR: insufficient number of arguments to mccontrol", - eError); - return 0; - } - strtolower(argv[1]); - if(strcmp(argv[1],"configure") == 0){ - return configureController(self,pCon,argc,argv); - } else if(strcmp(argv[1],"list") == 0){ - listConfiguration(self,pCon); - return 1; - } else if(strcmp(argv[1],"run") == 0){ - return runScript(self,pCon,pSics,argc,argv); - } else if(strcmp(argv[1],"start") == 0){ - return start(self,pCon); - } else if(strcmp(argv[1],"finish") == 0){ - wait4Finish(self); - SCSendOK(pCon); - return 1; + if (!StringDictGet(self->scripts, name, pScript, 131)) { + strncpy(result, "ERROR: script not found", resultLen); + return 0; + } + + if (strcmp(name, "mccopydata") == 0) { + snprintf(pCommand, 255, "%s", pScript); + } else if (strcmp(name, "mcstart") == 0) { + if (self->mode == eTimer) { + strcpy(pMode, "timer"); } else { - snprintf(pBueffel,255,"ERROR: subcommand %s to mccontrol unknown", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; + strcpy(pMode, "monitor"); } - return 0; + snprintf(pCommand, 255, "%s %s %f", pScript, pMode, self->fPreset); + } else { + snprintf(pCommand, 255, "%s %d", pScript, self->pid); + } + + pTcl = InterpGetTcl(pSics); + status = Tcl_Eval(pTcl, pCommand); + strncpy(result, pTcl->result, resultLen); + if (status == TCL_OK) { + return 1; + } else { + return 0; + } } + +/*------------------------------------------------------------------------*/ +static int runScript(pMcStasController self, SConnection * pCon, + SicsInterp * pSics, int argc, char *argv[]) +{ + char pResult[256]; + int status; + + if (argc < 3) { + SCWrite(pCon, + "ERRROR: insufficient number of arguments to mccontrol run", + eError); + return 0; + } + status = invokeScript(self, argv[2], pSics, pResult, 255); + if (status == 1) { + SCWrite(pCon, pResult, eValue); + return 1; + } else { + SCWrite(pCon, pResult, eError); + return 0; + } +} + +/*------------------------------------------------------------------------*/ +static int start(pMcStasController self, SConnection * pCon) +{ + int status; + + status = McStasStart(self, eTimer, 1000.); + if (status != OKOK) { + SCWrite(pCon, self->errorText, eError); + return 0; + } + SCSendOK(pCon); + return 1; +} + +/*-----------------------------------------------------------------------*/ +static void wait4Finish(pMcStasController self) +{ + int status; + + if (self->pid > 0) { + status = waitpid(self->pid, NULL, WNOHANG); + if (status >= 0) { + self->pid = -1; + } + } +} + +/*-------------------------------------------------------------------------*/ +int McStasControllerWrapper(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pMcStasController self = NULL; + char pBueffel[255], pFile[132]; + + self = (pMcStasController) pData; + assert(self); + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient number of arguments to mccontrol", + eError); + return 0; + } + strtolower(argv[1]); + if (strcmp(argv[1], "configure") == 0) { + return configureController(self, pCon, argc, argv); + } else if (strcmp(argv[1], "list") == 0) { + listConfiguration(self, pCon); + return 1; + } else if (strcmp(argv[1], "run") == 0) { + return runScript(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "start") == 0) { + return start(self, pCon); + } else if (strcmp(argv[1], "finish") == 0) { + wait4Finish(self); + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 255, "ERROR: subcommand %s to mccontrol unknown", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 0; +} + /*========================== the actual action functions =================*/ -int McStasStart(pMcStasController self, CounterMode mode, float fPreset){ - char pResult[256]; - int status; - FILE *fd = NULL; - - self->fPreset = fPreset; - self->mode = mode; - /** +int McStasStart(pMcStasController self, CounterMode mode, float fPreset) +{ + char pResult[256]; + int status; + FILE *fd = NULL; + + self->fPreset = fPreset; + self->mode = mode; + /** * make sure that the monitor file has only a 0 in it... */ - if(!StringDictGet(self->scripts,"mcmonfile",pResult,255)){ - strncpy(self->errorText,"Misconfiguration: no monfile",255); - return HWFault; - } - fd = fopen(pResult,"w"); - if(fd == NULL){ - strncpy(self->errorText,"Failed to access monitor file",255); - return HWFault; - } - fprintf(fd,"0\n"); - fclose(fd); - - /* - * invoke start script - */ - status = invokeScript(self,"mcstart",pServ->pSics,pResult,255); - if(status == 0){ - strncpy(self->errorText,pResult,255); - return HWFault; - } - - /* - * some general initializations .. - */ - self->pid = atoi(pResult); - self->startTime = time(NULL); - self->lastUpdate = self->startTime - self->updateIntervall; - self->lastMonitorRead = self->startTime; - return OKOK; + if (!StringDictGet(self->scripts, "mcmonfile", pResult, 255)) { + strncpy(self->errorText, "Misconfiguration: no monfile", 255); + return HWFault; + } + fd = fopen(pResult, "w"); + if (fd == NULL) { + strncpy(self->errorText, "Failed to access monitor file", 255); + return HWFault; + } + fprintf(fd, "0\n"); + fclose(fd); + + /* + * invoke start script + */ + status = invokeScript(self, "mcstart", pServ->pSics, pResult, 255); + if (status == 0) { + strncpy(self->errorText, pResult, 255); + return HWFault; + } + + /* + * some general initializations .. + */ + self->pid = atoi(pResult); + self->startTime = time(NULL); + self->lastUpdate = self->startTime - self->updateIntervall; + self->lastMonitorRead = self->startTime; + return OKOK; } + /*------------------------------------------------------------------------*/ -static long readMonFile(pMcStasController self){ - char pResult[256]; - FILE *fd = NULL; - long monValue = -1; - int i; - - if(!StringDictGet(self->scripts,"mcmonfile",pResult,255)){ - return -1; - } +static long readMonFile(pMcStasController self) +{ + char pResult[256]; + FILE *fd = NULL; + long monValue = -1; + int i; - fd = fopen(pResult,"r"); - if(fd != NULL){ - fscanf(fd,"%ld", &monValue); - fclose(fd); - } - return monValue; + if (!StringDictGet(self->scripts, "mcmonfile", pResult, 255)) { + return -1; + } + + fd = fopen(pResult, "r"); + if (fd != NULL) { + fscanf(fd, "%ld", &monValue); + fclose(fd); + } + return monValue; } + /*------------------------------------------------------------------------*/ -int McStasStatus(pMcStasController self, float *fControl){ - char pResult[256]; - float monValue; - int status, i; +int McStasStatus(pMcStasController self, float *fControl) +{ + char pResult[256]; + float monValue; + int status, i; - /* - * check at max any second, else SICS keeps the system busy and - * there is no CPU left for McStas - */ - SicsWait(1); - status = invokeScript(self,"mcisrunning",pServ->pSics,pResult, 255); - if(status == 0){ - strncpy(self->errorText,pResult,255); - return HWFault; - } - status = atoi(pResult); - /* - * handle timer mode - */ - if(status == 1 && self->mode == eTimer && - time(NULL) >= self->startTime + (int)self->fPreset){ - McStasStop(self); - return HWBusy; - } else { - *fControl = time(NULL) - self->startTime; - } - /* - * handle monitor mode - */ - if(status == 1 && self->mode == ePreset){ - /* - * check only any three seconds, else SICS uses up all the CPU time - * and the simulation has no chance. - */ - *fControl = self->lastMon; - if(time(NULL) < self->lastMonitorRead + 3) { - return HWBusy; - } - monValue = -1; - /* - * try to read the monfile up to three times. Problems reading it - * can be synchronisation problems with McStas - */ - for(i = 0, monValue = -1; i < 7; i++){ - monValue = (float)readMonFile(self); - if(monValue >= 0){ - break; - } - } - if(monValue < 0){ - return HWBusy; - } - self->lastMonitorRead = time(NULL); - monValue *= self->monitorScale; - *fControl = monValue; - self->lastMon = monValue; - if(monValue >= self->fPreset){ - McStasStop(self); - } - } - - if(status == 1){ - return HWBusy; - } else { - self->stopTime = time(NULL); - self->pid = -1; - return HWIdle; - } -} -/*-------------------------------------------------------------------------*/ -int McStasStop(pMcStasController self){ - char pResult[256]; - invokeScript(self,"mckill",pServ->pSics,pResult, 255); - self->lastUpdate = time(NULL) - 3*self->updateIntervall; - return 1; -} -/*-------------------------------------------------------------------------*/ -int McStasTransferData(pMcStasController self){ - char pResult[256]; - int status; - - /* - * prevent to frequent requests - */ - if(self->lastUpdate + self->updateIntervall > time(NULL)){ - return OKOK; - } + /* + * check at max any second, else SICS keeps the system busy and + * there is no CPU left for McStas + */ + SicsWait(1); + status = invokeScript(self, "mcisrunning", pServ->pSics, pResult, 255); + if (status == 0) { + strncpy(self->errorText, pResult, 255); + return HWFault; + } + status = atoi(pResult); + /* + * handle timer mode + */ + if (status == 1 && self->mode == eTimer && + time(NULL) >= self->startTime + (int) self->fPreset) { + McStasStop(self); + return HWBusy; + } else { + *fControl = time(NULL) - self->startTime; + } + /* + * handle monitor mode + */ + if (status == 1 && self->mode == ePreset) { + /* + * check only any three seconds, else SICS uses up all the CPU time + * and the simulation has no chance. + */ + *fControl = self->lastMon; + if (time(NULL) < self->lastMonitorRead + 3) { + return HWBusy; + } + monValue = -1; + /* + * try to read the monfile up to three times. Problems reading it + * can be synchronisation problems with McStas + */ + for (i = 0, monValue = -1; i < 7; i++) { + monValue = (float) readMonFile(self); + if (monValue >= 0) { + break; + } + } + if (monValue < 0) { + return HWBusy; + } + self->lastMonitorRead = time(NULL); + monValue *= self->monitorScale; + *fControl = monValue; + self->lastMon = monValue; + if (monValue >= self->fPreset) { + McStasStop(self); + } + } - self->lastUpdate = time(NULL); - if(self->pid >= 0){ - status = invokeScript(self,"mcdump",pServ->pSics,pResult, 255); - if(status == 0){ - strncpy(self->errorText,pResult,255); - self->lastUpdate = time(NULL) - self->updateIntervall; - return HWFault; - } - } - - status = invokeScript(self,"mccopydata",pServ->pSics,pResult, 255); - if(status == 0){ - strncpy(self->errorText,pResult,255); - self->lastUpdate = time(NULL) - self->updateIntervall; - return HWFault; - } - return OKOK; + if (status == 1) { + return HWBusy; + } else { + self->stopTime = time(NULL); + self->pid = -1; + return HWIdle; + } } + /*-------------------------------------------------------------------------*/ -int McStasGetError(pMcStasController self, char *error, int errLen){ - strncpy(error,self->errorText,errLen); - return 1; -} -/*-------------------------------------------------------------------------*/ -int McStasFix(pMcStasController self){ - /* - * if the monitor file cannot be read, this may be caused by - * a conflict of mCstas writing while we are reading. let us - * retry... - */ - if(strstr(self->errorText,"monitor") != NULL){ - return COREDO; - } - /* - * you have to edit the scripts to fix anything which is going wrong here. - * But make sure the simulation is stopped. - */ - McStasStop(self); - self->stopTime = time(NULL); - self->pid = -1; - return COTERM; +int McStasStop(pMcStasController self) +{ + char pResult[256]; + invokeScript(self, "mckill", pServ->pSics, pResult, 255); + self->lastUpdate = time(NULL) - 3 * self->updateIntervall; + return 1; } + /*-------------------------------------------------------------------------*/ -float McStasGetTime(pMcStasController self){ - if(self->pid < 0){ - return (float)(self->stopTime - self->startTime); - } else { - return (float)time(NULL) - self->startTime; - } +int McStasTransferData(pMcStasController self) +{ + char pResult[256]; + int status; + + /* + * prevent to frequent requests + */ + if (self->lastUpdate + self->updateIntervall > time(NULL)) { + return OKOK; + } + + self->lastUpdate = time(NULL); + if (self->pid >= 0) { + status = invokeScript(self, "mcdump", pServ->pSics, pResult, 255); + if (status == 0) { + strncpy(self->errorText, pResult, 255); + self->lastUpdate = time(NULL) - self->updateIntervall; + return HWFault; + } + } + + status = invokeScript(self, "mccopydata", pServ->pSics, pResult, 255); + if (status == 0) { + strncpy(self->errorText, pResult, 255); + self->lastUpdate = time(NULL) - self->updateIntervall; + return HWFault; + } + return OKOK; +} + +/*-------------------------------------------------------------------------*/ +int McStasGetError(pMcStasController self, char *error, int errLen) +{ + strncpy(error, self->errorText, errLen); + return 1; +} + +/*-------------------------------------------------------------------------*/ +int McStasFix(pMcStasController self) +{ + /* + * if the monitor file cannot be read, this may be caused by + * a conflict of mCstas writing while we are reading. let us + * retry... + */ + if (strstr(self->errorText, "monitor") != NULL) { + return COREDO; + } + /* + * you have to edit the scripts to fix anything which is going wrong here. + * But make sure the simulation is stopped. + */ + McStasStop(self); + self->stopTime = time(NULL); + self->pid = -1; + return COTERM; +} + +/*-------------------------------------------------------------------------*/ +float McStasGetTime(pMcStasController self) +{ + if (self->pid < 0) { + return (float) (self->stopTime - self->startTime); + } else { + return (float) time(NULL) - self->startTime; + } } diff --git a/mccontrol.h b/mccontrol.h index 43d611f5..d9ea74ab 100644 --- a/mccontrol.h +++ b/mccontrol.h @@ -14,37 +14,36 @@ #include "stringdict.h" /*--------------------- data structure -------------------------------------------------*/ - typedef struct{ - pObjectDescriptor pDes; - pStringDict scripts; - int updateIntervall; - int pid; - float monitorScale; - int lastError; - char errorText[256]; - CounterMode mode; - float fPreset; - time_t lastUpdate; - time_t startTime; - time_t stopTime; - time_t lastMonitorRead; - float lastMon; - }McStasController, *pMcStasController; - +typedef struct { + pObjectDescriptor pDes; + pStringDict scripts; + int updateIntervall; + int pid; + float monitorScale; + int lastError; + char errorText[256]; + CounterMode mode; + float fPreset; + time_t lastUpdate; + time_t startTime; + time_t stopTime; + time_t lastMonitorRead; + float lastMon; +} McStasController, *pMcStasController; + /*---------------------- function prototypes -------------------------------------------*/ - int McStasControllerFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - int McStasControllerWrapper(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int McStasControllerFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); +int McStasControllerWrapper(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + +int McStasStart(pMcStasController self, CounterMode mode, float fPreset); +int McStasStatus(pMcStasController self, float *fControl); +int McStasStop(pMcStasController self); +int McStasTransferData(pMcStasController self); +int McStasGetError(pMcStasController self, char *error, int errLen); +int McStasFix(pMcStasController self); +float McStasGetTime(pMcStasController self); - int McStasStart(pMcStasController self, CounterMode mode, float fPreset); - int McStasStatus(pMcStasController self,float *fControl); - int McStasStop(pMcStasController self); - int McStasTransferData(pMcStasController self); - int McStasGetError(pMcStasController self, char *error, int errLen); - int McStasFix(pMcStasController self); - float McStasGetTime(pMcStasController self); - #endif - diff --git a/mclist.c b/mclist.c index f67badf0..df354ac6 100644 --- a/mclist.c +++ b/mclist.c @@ -28,20 +28,23 @@ #define MC_NEXT next #endif -MC_TYPE MC_First_FUN(MC_List_TYPE *list) { +MC_TYPE MC_First_FUN(MC_List_TYPE * list) +{ list->ptr = &list->head; return list->head; } -MC_TYPE MC_This_FUN(MC_List_TYPE *list) { +MC_TYPE MC_This_FUN(MC_List_TYPE * list) +{ if (list->head == NULL) { list->ptr = &list->head; return NULL; } return *list->ptr; - } +} -MC_TYPE MC_Next_FUN(MC_List_TYPE *list) { +MC_TYPE MC_Next_FUN(MC_List_TYPE * list) +{ MC_TYPE node; if (list->head == NULL) { list->ptr = &list->head; @@ -54,7 +57,8 @@ MC_TYPE MC_Next_FUN(MC_List_TYPE *list) { return *list->ptr; } -void MC_End_FUN(MC_List_TYPE *list) { +void MC_End_FUN(MC_List_TYPE * list) +{ MC_TYPE node; if (list->head == NULL) { list->ptr = &list->head; @@ -68,7 +72,8 @@ void MC_End_FUN(MC_List_TYPE *list) { } } -void MC_Insert_FUN(MC_List_TYPE *list, MC_TYPE node) { +void MC_Insert_FUN(MC_List_TYPE * list, MC_TYPE node) +{ if (list->head == NULL) { list->ptr = &list->head; } @@ -76,7 +81,8 @@ void MC_Insert_FUN(MC_List_TYPE *list, MC_TYPE node) { *list->ptr = node; } -void MC_Add_FUN(MC_List_TYPE *list, MC_TYPE node) { +void MC_Add_FUN(MC_List_TYPE * list, MC_TYPE node) +{ node->MC_NEXT = NULL; if (list->head == NULL) { list->head = node; @@ -89,7 +95,8 @@ void MC_Add_FUN(MC_List_TYPE *list, MC_TYPE node) { } } -MC_TYPE MC_Take_FUN(MC_List_TYPE *list) { +MC_TYPE MC_Take_FUN(MC_List_TYPE * list) +{ MC_TYPE node; node = *list->ptr; if (node != NULL) { @@ -98,7 +105,8 @@ MC_TYPE MC_Take_FUN(MC_List_TYPE *list) { return node; } -void MC_Delete_FUN(MC_List_TYPE *list, void (*deleteFunc)(MC_TYPE n)) { +void MC_Delete_FUN(MC_List_TYPE * list, void (*deleteFunc) (MC_TYPE n)) +{ MC_TYPE node; MC_TYPE victim; node = list->head; diff --git a/mclist.h b/mclist.h index 889a6737..6dbf7553 100644 --- a/mclist.h +++ b/mclist.h @@ -110,7 +110,7 @@ typedef struct MC_List_TYPE { * * Actual position on return: at the first node */ -MC_TYPE MC_First_FUN(MC_List_TYPE *list); +MC_TYPE MC_First_FUN(MC_List_TYPE * list); /** \brief get the node at the current position * \param list the list @@ -118,7 +118,7 @@ MC_TYPE MC_First_FUN(MC_List_TYPE *list); * * Actual position on return: not changed (= at the returned node) */ -MC_TYPE MC_This_FUN(MC_List_TYPE *list); +MC_TYPE MC_This_FUN(MC_List_TYPE * list); /** \brief get the node after the current node * \param list the list @@ -126,14 +126,14 @@ MC_TYPE MC_This_FUN(MC_List_TYPE *list); * * Actual position on return: incremented (= at the returned node or at end) */ -MC_TYPE MC_Next_FUN(MC_List_TYPE *list); +MC_TYPE MC_Next_FUN(MC_List_TYPE * list); /** \brief move the position to the end * \param list the list * * Actual position on return: at end */ -void MC_End_FUN(MC_List_TYPE *list); +void MC_End_FUN(MC_List_TYPE * list); /** \brief insert at the current position, i.e. before the current node * \param list the list @@ -141,7 +141,7 @@ void MC_End_FUN(MC_List_TYPE *list); * * Actual position on return: at the inserted node */ -void MC_Insert_FUN(MC_List_TYPE *list, MC_TYPE node); +void MC_Insert_FUN(MC_List_TYPE * list, MC_TYPE node); /** \brief add at the end of the list * \param list the list @@ -149,7 +149,7 @@ void MC_Insert_FUN(MC_List_TYPE *list, MC_TYPE node); * * Actual position on return: at the inserted node (before the last node, not at end!) */ -void MC_Add_FUN(MC_List_TYPE *list, MC_TYPE node); +void MC_Add_FUN(MC_List_TYPE * list, MC_TYPE node); /** \brief remove the node at the current position * \param list the list @@ -160,7 +160,7 @@ void MC_Add_FUN(MC_List_TYPE *list, MC_TYPE node); * Note: it is the responsibility of the caller to free the node if it is not used * anymore */ -MC_TYPE MC_Take_FUN(MC_List_TYPE *list); +MC_TYPE MC_Take_FUN(MC_List_TYPE * list); /** \brief remove and delete all nodes * \param list the list @@ -169,7 +169,7 @@ MC_TYPE MC_Take_FUN(MC_List_TYPE *list); * Calls the kill function for every node. The list is * empty on return. */ -void MC_Delete_FUN(MC_List_TYPE *list, void (*deleteFunc)(MC_TYPE node)); +void MC_Delete_FUN(MC_List_TYPE * list, void (*deleteFunc) (MC_TYPE node)); #ifndef MC_DO_NOT_UNDEF #undef MC_NAME diff --git a/mcreader.c b/mcreader.c index d2d6c48d..a478db2b 100644 --- a/mcreader.c +++ b/mcreader.c @@ -13,110 +13,118 @@ #include "HistMem.h" #include "sicsdata.h" /*-------------------------------------------------------------------------*/ -static void KillMcReader(void *pData){ - pMcStasReader self = (pMcStasReader)pData; - if(self == NULL){ - return; - } - if(self->pDes){ - DeleteDescriptor(self->pDes); - } - if(self->handle != NULL){ - NXclose(&self->handle); - } - free(self); +static void KillMcReader(void *pData) +{ + pMcStasReader self = (pMcStasReader) pData; + if (self == NULL) { + return; + } + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->handle != NULL) { + NXclose(&self->handle); + } + free(self); } + /*--------------------------------------------------------------------------*/ -int McStasReaderFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - pMcStasReader pNew = NULL; - - pNew = (pMcStasReader)malloc(sizeof(McStasReader)); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating McStasReader",eError); - return 0; - } - memset(pNew,0,sizeof(McStasReader)); - - pNew->pDes = CreateDescriptor("McStasReader"); - if(pNew->pDes == NULL){ - SCWrite(pCon,"ERROR: out of memory creating McStasReader",eError); - free(pNew); - return 0; - } - return AddCommand(pSics,"mcreader", - McStasReaderWrapper, - KillMcReader, - pNew); +int McStasReaderFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pMcStasReader pNew = NULL; + + pNew = (pMcStasReader) malloc(sizeof(McStasReader)); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating McStasReader", eError); + return 0; + } + memset(pNew, 0, sizeof(McStasReader)); + + pNew->pDes = CreateDescriptor("McStasReader"); + if (pNew->pDes == NULL) { + SCWrite(pCon, "ERROR: out of memory creating McStasReader", eError); + free(pNew); + return 0; + } + return AddCommand(pSics, "mcreader", + McStasReaderWrapper, KillMcReader, pNew); } + /*==================== interpreter interface ===============================*/ -static void MCReportError(void *pData, char *txt){ - pMcStasReader self = NULL; - - self = (pMcStasReader)pData; - if(self != NULL){ - strncpy(self->nexusError,txt,1024); - } else { - printf( -"ERROR: NeXus error in McStasReader without McStasReader data structure: %s\n", - txt); - } +static void MCReportError(void *pData, char *txt) +{ + pMcStasReader self = NULL; + + self = (pMcStasReader) pData; + if (self != NULL) { + strncpy(self->nexusError, txt, 1024); + } else { + printf + ("ERROR: NeXus error in McStasReader without McStasReader data structure: %s\n", + txt); + } } + /*-------------------------------------------------------------------------*/ -static int openMcStasFile(pMcStasReader self, SConnection *pCon, - int argc, char *argv[]){ - int status; - char pBueffel[512]; - - if(argc < 3){ - SCWrite(pCon,"ERROR: need filename argument for opening file", - eError); - } - /* - * be nice to users: if file still open, close it - */ - if(self->handle != NULL){ - NXclose(&self->handle); - self->handle = NULL; - } - /** +static int openMcStasFile(pMcStasReader self, SConnection * pCon, + int argc, char *argv[]) +{ + int status; + char pBueffel[512]; + + if (argc < 3) { + SCWrite(pCon, "ERROR: need filename argument for opening file", + eError); + } + /* + * be nice to users: if file still open, close it + */ + if (self->handle != NULL) { + NXclose(&self->handle); + self->handle = NULL; + } + /** * open the file */ - NXMSetError(self,MCReportError); - status = NXopen((const char*)argv[2],NXACC_READ,&self->handle); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: NeXus reported %s", - self->nexusError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - SCSendOK(pCon); - return 1; + NXMSetError(self, MCReportError); + status = NXopen((const char *) argv[2], NXACC_READ, &self->handle); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: NeXus reported %s", self->nexusError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + SCSendOK(pCon); + return 1; } + /*--------------------------------------------------------------------------*/ -static int closeMcStasFile(pMcStasReader self, SConnection *pCon){ - if(self->handle != NULL){ - NXclose(&self->handle); - self->handle = NULL; - } - SCSendOK(pCon); - return 1; +static int closeMcStasFile(pMcStasReader self, SConnection * pCon) +{ + if (self->handle != NULL) { + NXclose(&self->handle); + self->handle = NULL; + } + SCSendOK(pCon); + return 1; } + /*-------------------------------------------------------------------*/ -static char *getNextMCNumber(char *pStart, char pNumber[80]){ +static char *getNextMCNumber(char *pStart, char pNumber[80]) +{ int charCount = 0; pNumber[0] = '\0'; /* advance to first digit */ - while(isspace(*pStart) && *pStart != '\0'){ + while (isspace(*pStart) && *pStart != '\0') { pStart++; } - if(*pStart == '\0'){ + if (*pStart == '\0') { return NULL; } /* copy */ - while(!isspace(*pStart) && *pStart != '\0' && charCount < 78){ + while (!isspace(*pStart) && *pStart != '\0' && charCount < 78) { pNumber[charCount] = *pStart; pStart++; charCount++; @@ -124,345 +132,348 @@ static char *getNextMCNumber(char *pStart, char pNumber[80]){ pNumber[charCount] = '\0'; return pStart; } + /*--------------------------------------------------------------------------*/ -static int insertMonitor(pMcStasReader self, SConnection *pCon, - SicsInterp *pSics, int argc, char *argv[]){ - char pBueffel[512], *pPtr, pNumber[80]; - pCounter pCount = NULL; - int status, mon, type, rank, iDim[NX_MAXRANK]; - float monValue, scale = 1.; - - if(argc < 5){ - SCWrite(pCon,\ - "ERROR: insufficient number of arguments to mcreader insertmon", - eError); - return 0; - } - if(self->handle == NULL){ - SCWrite(pCon,"ERROR: no file open to read data from",eError); - return 0; - } - pCount = FindCommandData(pSics,argv[3],"SingleCounter"); - if(pCount == NULL){ - snprintf(pBueffel,511, - "ERROR: %s is no counter object", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - mon = atoi(argv[4]); - - status = NXopenpath(self->handle,argv[2]); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: Nexus error %s while opening %s", - self->nexusError, argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - if(argc > 5) { - scale = atof(argv[5]); - } - - status = NXgetinfo(self->handle,&rank,iDim,&type); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: Nexus error %s while reading %s", - self->nexusError, argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(rank != 1 || type != NX_CHAR || iDim[0] > 511){ - snprintf(pBueffel,511,"ERROR: %s is no valid monitor data", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - memset(pBueffel,0,512); - status = NXgetdata(self->handle,pBueffel); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: Nexus error %s while reading %s", - self->nexusError, argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +static int insertMonitor(pMcStasReader self, SConnection * pCon, + SicsInterp * pSics, int argc, char *argv[]) +{ + char pBueffel[512], *pPtr, pNumber[80]; + pCounter pCount = NULL; + int status, mon, type, rank, iDim[NX_MAXRANK]; + float monValue, scale = 1.; + + if (argc < 5) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to mcreader insertmon", + eError); + return 0; + } + if (self->handle == NULL) { + SCWrite(pCon, "ERROR: no file open to read data from", eError); + return 0; + } + pCount = FindCommandData(pSics, argv[3], "SingleCounter"); + if (pCount == NULL) { + snprintf(pBueffel, 511, "ERROR: %s is no counter object", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + mon = atoi(argv[4]); + + status = NXopenpath(self->handle, argv[2]); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: Nexus error %s while opening %s", + self->nexusError, argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + if (argc > 5) { + scale = atof(argv[5]); + } + + status = NXgetinfo(self->handle, &rank, iDim, &type); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: Nexus error %s while reading %s", + self->nexusError, argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (rank != 1 || type != NX_CHAR || iDim[0] > 511) { + snprintf(pBueffel, 511, "ERROR: %s is no valid monitor data", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + memset(pBueffel, 0, 512); + status = NXgetdata(self->handle, pBueffel); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: Nexus error %s while reading %s", + self->nexusError, argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* + * the monitor value we want is the third value in the values field + */ + pPtr = pBueffel; + memset(pNumber, 0, 80 * sizeof(char)); + pPtr = getNextMCNumber(pPtr, pNumber); + pPtr = getNextMCNumber(pPtr, pNumber); + pPtr = getNextMCNumber(pPtr, pNumber); + monValue = atof(pNumber); + monValue *= scale; + + if (pCount != NULL) { + SetMonitorValue(pCount, mon, (long) monValue); + } + SCSendOK(pCon); + return 1; +} - /* - * the monitor value we want is the third value in the values field - */ - pPtr = pBueffel; - memset(pNumber,0,80*sizeof(char)); - pPtr = getNextMCNumber(pPtr,pNumber); - pPtr = getNextMCNumber(pPtr,pNumber); - pPtr = getNextMCNumber(pPtr,pNumber); - monValue = atof(pNumber); - monValue *= scale; - - if(pCount != NULL){ - SetMonitorValue(pCount,mon,(long)monValue); - } - SCSendOK(pCon); - return 1; -} /*--------------------------------------------------------------------------*/ -static int insertMonitorDirect(pMcStasReader self, SConnection *pCon, - SicsInterp *pSics, int argc, char *argv[]){ - char pBueffel[512], *pPtr, pNumber[80]; - pCounter pCount = NULL; - int status, mon; - float monValue; - - if(argc < 5){ - SCWrite(pCon,\ - "ERROR: insufficient number of arguments to mcreader insertmondirect", - eError); - return 0; - } +static int insertMonitorDirect(pMcStasReader self, SConnection * pCon, + SicsInterp * pSics, int argc, char *argv[]) +{ + char pBueffel[512], *pPtr, pNumber[80]; + pCounter pCount = NULL; + int status, mon; + float monValue; - pCount = FindCommandData(pSics,argv[2],"SingleCounter"); - if(pCount == NULL){ - snprintf(pBueffel,511, - "ERROR: %s is no counter object", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - mon = atoi(argv[3]); - monValue = atof(argv[4]); - - if(pCount != NULL){ - SetMonitorValue(pCount,mon,(long)monValue); - } - SCSendOK(pCon); - return 1; -} -/*--------------------------------------------------------------------------*/ -static int insertHM(pMcStasReader self, SConnection *pCon, - SicsInterp *pSics, int argc, char *argv[]){ - char pBueffel[512], *pPtr, pNumber[80], *pData = NULL; - pHistMem pHM = NULL; - int status, type, rank, iDim[NX_MAXRANK]; - int length, i; - HistInt *lData = NULL; - float scale = 1.; - double val; - - if(argc < 4){ - SCWrite(pCon,\ - "ERROR: insufficient number of arguments to mcreader inserthm", - eError); - return 0; - } - if(self->handle == NULL){ - SCWrite(pCon,"ERROR: no file open to read data from",eError); - return 0; - } - pHM = FindCommandData(pSics,argv[3],"HistMem"); - if(pHM == NULL){ - snprintf(pBueffel,511, - "ERROR: %s is no histogram memory object", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - status = NXopenpath(self->handle,argv[2]); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: Nexus error %s while opening %s", - self->nexusError, argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(argc > 4){ - scale = atof(argv[4]); - } - - status = NXgetinfo(self->handle,&rank,iDim,&type); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: Nexus error %s while reading %s", - self->nexusError, argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - pData = (char *)malloc((iDim[0]+1)*sizeof(char)); - if(pData == NULL){ - SCWrite(pCon,"ERROR: out of memory in mcreader inserthm",eError); - return 0; - } - memset(pData,0,(iDim[0]+1)*sizeof(char)); + if (argc < 5) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to mcreader insertmondirect", + eError); + return 0; + } - status = NXgetdata(self->handle,pData); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: Nexus error %s while reading %s", - self->nexusError, argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - length = GetHistLength(pHM); - lData = (HistInt *)malloc(length*sizeof(HistInt)); - if(lData== NULL){ - SCWrite(pCon,"ERROR: out of memory in mcreader inserthm",eError); - free(pData); - return 0; - } - memset(lData,0,length*sizeof(HistInt)); - - pPtr = pData; - for(i = 0; i < length && pPtr != NULL; i++){ - pPtr = getNextMCNumber(pPtr,pNumber); - val = atof(pNumber); - val *= scale; - lData[i] = (HistInt)val; - } + pCount = FindCommandData(pSics, argv[2], "SingleCounter"); + if (pCount == NULL) { + snprintf(pBueffel, 511, "ERROR: %s is no counter object", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + mon = atoi(argv[3]); + monValue = atof(argv[4]); - SetHistogram(pHM,pCon,0,0,length,lData); - free(pData); - free(lData); - SCSendOK(pCon); - return 1; + if (pCount != NULL) { + SetMonitorValue(pCount, mon, (long) monValue); + } + SCSendOK(pCon); + return 1; } -/*--------------------------------------------------------------------------*/ -static int getField(pMcStasReader self, SConnection *pCon, - SicsInterp *pSics, int argc, char *argv[]){ - char pBueffel[512], *pPtr, pNumber[80], *pData = NULL; - int status, type, rank, iDim[NX_MAXRANK]; - - if(argc < 2){ - SCWrite(pCon,\ - "ERROR: insufficient number of arguments to mcreader getfield", - eError); - return 0; - } - if(self->handle == NULL){ - SCWrite(pCon,"ERROR: no file open to read data from",eError); - return 0; - } - status = NXopenpath(self->handle,argv[2]); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: Nexus error %s while opening %s", - self->nexusError, argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - status = NXgetinfo(self->handle,&rank,iDim,&type); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: Nexus error %s while reading %s", - self->nexusError, argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - pData = (char *)malloc((iDim[0]+1)*sizeof(char)); - if(pData == NULL){ - SCWrite(pCon,"ERROR: out of memory in mcreader getfield",eError); - return 0; - } - memset(pData,0,(iDim[0]+1)*sizeof(char)); - - status = NXgetdata(self->handle,pData); - if(status != NX_OK){ - snprintf(pBueffel,511,"ERROR: Nexus error %s while reading %s", - self->nexusError, argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - SCWrite(pCon,pData,eValue); - free(pData); - return 1; -} -/*--------------------------------------------------------------------------*/ -static int insertHMFromData(pMcStasReader self, SConnection *pCon, - SicsInterp *pSics, int argc, char *argv[]){ - char pBueffel[512]; - pHistMem pHM = NULL; - int length, i; - HistInt *lData = NULL; - pSICSData data = NULL; - - if(argc < 4){ - SCWrite(pCon,\ - "ERROR: insufficient number of arguments to mcreader inserthmfromdata", - eError); - return 0; - } - pHM = FindCommandData(pSics,argv[2],"HistMem"); - if(pHM == NULL){ - snprintf(pBueffel,511, - "ERROR: %s is no histogram memory object", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - data = FindCommandData(pSics,argv[3],"SICSData"); - if(data == NULL){ - snprintf(pBueffel,511, - "ERROR: %s is no SICSData object", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - length = GetHistLength(pHM); - if(data->currentDataSize < length){ - snprintf(pBueffel,511,"WARNING: data in %s to short for HM %s", - argv[3],argv[2]); - SCWrite(pCon,pBueffel,eWarning); - } - lData = (HistInt *)malloc(length*sizeof(HistInt)); - if(lData== NULL){ - SCWrite(pCon,"ERROR: out of memory in mcreader inserthm",eError); - return 0; - } - memset(lData,0,length*sizeof(HistInt)); - if(data->currentDataSize < length){ - length = data->currentDataSize; - } - for(i = 0; i < length; i++){ - lData[i] = (HistInt)data->data[i]; - } - SetHistogram(pHM,pCon,0,0,length,lData); - free(lData); - SCSendOK(pCon); - return 1; -} /*--------------------------------------------------------------------------*/ -int McStasReaderWrapper(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - pMcStasReader self = NULL; - char pBueffel[512]; - - self = (pMcStasReader)pData; - assert(self != NULL); - - if(argc < 2){ - SCWrite(pCon,"ERROR: insufficient number of arguments to mcreader", - eError); - return 0; - } - strtolower(argv[1]); - if(strcmp(argv[1],"open") == 0){ - return openMcStasFile(self, pCon, argc, argv); - } else if(strcmp(argv[1],"close") == 0){ - return closeMcStasFile(self,pCon); - } else if(strcmp(argv[1],"insertmon") == 0){ - return insertMonitor(self,pCon, pSics,argc,argv); - } else if(strcmp(argv[1],"insertmondirect") == 0){ - return insertMonitorDirect(self,pCon, pSics,argc,argv); - } else if(strcmp(argv[1],"inserthm") == 0){ - return insertHM(self,pCon, pSics,argc,argv); - } else if(strcmp(argv[1],"inserthmfromdata") == 0){ - return insertHMFromData(self,pCon, pSics,argc,argv); - } else if(strcmp(argv[1],"getfield") == 0){ - return getField(self,pCon, pSics,argc,argv); - } else { - snprintf(pBueffel,511,"ERROR: invalid subcommand %s to %s", - argv[1],argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; +static int insertHM(pMcStasReader self, SConnection * pCon, + SicsInterp * pSics, int argc, char *argv[]) +{ + char pBueffel[512], *pPtr, pNumber[80], *pData = NULL; + pHistMem pHM = NULL; + int status, type, rank, iDim[NX_MAXRANK]; + int length, i; + HistInt *lData = NULL; + float scale = 1.; + double val; + + if (argc < 4) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to mcreader inserthm", + eError); + return 0; + } + if (self->handle == NULL) { + SCWrite(pCon, "ERROR: no file open to read data from", eError); + return 0; + } + pHM = FindCommandData(pSics, argv[3], "HistMem"); + if (pHM == NULL) { + snprintf(pBueffel, 511, + "ERROR: %s is no histogram memory object", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + status = NXopenpath(self->handle, argv[2]); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: Nexus error %s while opening %s", + self->nexusError, argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (argc > 4) { + scale = atof(argv[4]); + } + + status = NXgetinfo(self->handle, &rank, iDim, &type); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: Nexus error %s while reading %s", + self->nexusError, argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + pData = (char *) malloc((iDim[0] + 1) * sizeof(char)); + if (pData == NULL) { + SCWrite(pCon, "ERROR: out of memory in mcreader inserthm", eError); + return 0; + } + memset(pData, 0, (iDim[0] + 1) * sizeof(char)); + + status = NXgetdata(self->handle, pData); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: Nexus error %s while reading %s", + self->nexusError, argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + length = GetHistLength(pHM); + lData = (HistInt *) malloc(length * sizeof(HistInt)); + if (lData == NULL) { + SCWrite(pCon, "ERROR: out of memory in mcreader inserthm", eError); + free(pData); + return 0; + } + memset(lData, 0, length * sizeof(HistInt)); + + pPtr = pData; + for (i = 0; i < length && pPtr != NULL; i++) { + pPtr = getNextMCNumber(pPtr, pNumber); + val = atof(pNumber); + val *= scale; + lData[i] = (HistInt) val; + } + + SetHistogram(pHM, pCon, 0, 0, length, lData); + free(pData); + free(lData); + SCSendOK(pCon); + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int getField(pMcStasReader self, SConnection * pCon, + SicsInterp * pSics, int argc, char *argv[]) +{ + char pBueffel[512], *pPtr, pNumber[80], *pData = NULL; + int status, type, rank, iDim[NX_MAXRANK]; + + if (argc < 2) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to mcreader getfield", + eError); + return 0; + } + if (self->handle == NULL) { + SCWrite(pCon, "ERROR: no file open to read data from", eError); + return 0; + } + + status = NXopenpath(self->handle, argv[2]); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: Nexus error %s while opening %s", + self->nexusError, argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + status = NXgetinfo(self->handle, &rank, iDim, &type); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: Nexus error %s while reading %s", + self->nexusError, argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + pData = (char *) malloc((iDim[0] + 1) * sizeof(char)); + if (pData == NULL) { + SCWrite(pCon, "ERROR: out of memory in mcreader getfield", eError); + return 0; + } + memset(pData, 0, (iDim[0] + 1) * sizeof(char)); + + status = NXgetdata(self->handle, pData); + if (status != NX_OK) { + snprintf(pBueffel, 511, "ERROR: Nexus error %s while reading %s", + self->nexusError, argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + SCWrite(pCon, pData, eValue); + free(pData); + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int insertHMFromData(pMcStasReader self, SConnection * pCon, + SicsInterp * pSics, int argc, char *argv[]) +{ + char pBueffel[512]; + pHistMem pHM = NULL; + int length, i; + HistInt *lData = NULL; + pSICSData data = NULL; + + if (argc < 4) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to mcreader inserthmfromdata", + eError); + return 0; + } + pHM = FindCommandData(pSics, argv[2], "HistMem"); + if (pHM == NULL) { + snprintf(pBueffel, 511, + "ERROR: %s is no histogram memory object", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + data = FindCommandData(pSics, argv[3], "SICSData"); + if (data == NULL) { + snprintf(pBueffel, 511, "ERROR: %s is no SICSData object", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + length = GetHistLength(pHM); + if (data->currentDataSize < length) { + snprintf(pBueffel, 511, "WARNING: data in %s to short for HM %s", + argv[3], argv[2]); + SCWrite(pCon, pBueffel, eWarning); + } + lData = (HistInt *) malloc(length * sizeof(HistInt)); + if (lData == NULL) { + SCWrite(pCon, "ERROR: out of memory in mcreader inserthm", eError); + return 0; + } + memset(lData, 0, length * sizeof(HistInt)); + if (data->currentDataSize < length) { + length = data->currentDataSize; + } + for (i = 0; i < length; i++) { + lData[i] = (HistInt) data->data[i]; + } + SetHistogram(pHM, pCon, 0, 0, length, lData); + free(lData); + SCSendOK(pCon); + return 1; +} + +/*--------------------------------------------------------------------------*/ +int McStasReaderWrapper(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pMcStasReader self = NULL; + char pBueffel[512]; + + self = (pMcStasReader) pData; + assert(self != NULL); + + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient number of arguments to mcreader", + eError); + return 0; + } + strtolower(argv[1]); + if (strcmp(argv[1], "open") == 0) { + return openMcStasFile(self, pCon, argc, argv); + } else if (strcmp(argv[1], "close") == 0) { + return closeMcStasFile(self, pCon); + } else if (strcmp(argv[1], "insertmon") == 0) { + return insertMonitor(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "insertmondirect") == 0) { + return insertMonitorDirect(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "inserthm") == 0) { + return insertHM(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "inserthmfromdata") == 0) { + return insertHMFromData(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "getfield") == 0) { + return getField(self, pCon, pSics, argc, argv); + } else { + snprintf(pBueffel, 511, "ERROR: invalid subcommand %s to %s", + argv[1], argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; } diff --git a/mcreader.h b/mcreader.h index 6bd627b0..154e15d2 100644 --- a/mcreader.h +++ b/mcreader.h @@ -7,22 +7,20 @@ Mark Koennecke, June 2005 -------------------------------------------------------------------------------------*/ -#ifndef MCSTASREADER +#ifndef MCSTASREADER #define MCSTASREADER #include "sics.h" #include "napi.h" typedef struct { - pObjectDescriptor pDes; - NXhandle handle; - char nexusError[1024]; - }McStasReader, *pMcStasReader; + pObjectDescriptor pDes; + NXhandle handle; + char nexusError[1024]; +} McStasReader, *pMcStasReader; /*-----------------------------------------------------------------------------*/ - int McStasReaderFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - int McStasReaderWrapper(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - +int McStasReaderFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); +int McStasReaderWrapper(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + #endif - - diff --git a/mcstascounter.c b/mcstascounter.c index adbf2c02..17f372e9 100644 --- a/mcstascounter.c +++ b/mcstascounter.c @@ -16,147 +16,171 @@ #define SCRIPTERROR -110 #define NOTIMPLEMENTED -111 /*====================== interface functions ==============================*/ -static int McStatus(struct __COUNTER *self, float *fControl){ - int status; - pMcStasController pMcStas = NULL; - - pMcStas = (pMcStasController)self->pData; - - status = McStasStatus(pMcStas,fControl); - if(status == HWFault){ - self->iErrorCode = SCRIPTERROR; - return status; - } - return status; +static int McStatus(struct __COUNTER *self, float *fControl) +{ + int status; + pMcStasController pMcStas = NULL; + + pMcStas = (pMcStasController) self->pData; + + status = McStasStatus(pMcStas, fControl); + if (status == HWFault) { + self->iErrorCode = SCRIPTERROR; + return status; + } + return status; } + /*--------------------------------------------------------------------------*/ -static int McStart(struct __COUNTER *self){ - int status; - pMcStasController pMcStas = NULL; - - pMcStas = (pMcStasController)self->pData; - - memset(self->lCounts,0,MAXCOUNT*sizeof(long)); - status = McStasStart(pMcStas,self->eMode,self->fPreset); - if(status == HWFault){ - self->iErrorCode = SCRIPTERROR; - } - return status; +static int McStart(struct __COUNTER *self) +{ + int status; + pMcStasController pMcStas = NULL; + + pMcStas = (pMcStasController) self->pData; + + memset(self->lCounts, 0, MAXCOUNT * sizeof(long)); + status = McStasStart(pMcStas, self->eMode, self->fPreset); + if (status == HWFault) { + self->iErrorCode = SCRIPTERROR; + } + return status; } + /*--------------------------------------------------------------------------*/ -static int McPause(struct __COUNTER *self){ - self->iErrorCode = NOTIMPLEMENTED; - return HWFault; +static int McPause(struct __COUNTER *self) +{ + self->iErrorCode = NOTIMPLEMENTED; + return HWFault; } + /*--------------------------------------------------------------------------*/ -static int McContinue(struct __COUNTER *self){ - self->iErrorCode = NOTIMPLEMENTED; - return HWFault; +static int McContinue(struct __COUNTER *self) +{ + self->iErrorCode = NOTIMPLEMENTED; + return HWFault; } + /*--------------------------------------------------------------------------*/ -static int McHalt(struct __COUNTER *self){ - int status; - pMcStasController pMcStas = NULL; - - pMcStas = (pMcStasController)self->pData; - - status = McStasStop(pMcStas); - if(status == HWFault){ - self->iErrorCode = SCRIPTERROR; - } - return status; +static int McHalt(struct __COUNTER *self) +{ + int status; + pMcStasController pMcStas = NULL; + + pMcStas = (pMcStasController) self->pData; + + status = McStasStop(pMcStas); + if (status == HWFault) { + self->iErrorCode = SCRIPTERROR; + } + return status; } + /*--------------------------------------------------------------------------*/ -static int McReadValues(struct __COUNTER *self){ - int status; - pMcStasController pMcStas = NULL; - - pMcStas = (pMcStasController)self->pData; - - status = McStasTransferData(pMcStas); - if(status == HWFault){ - self->iErrorCode = SCRIPTERROR; - } - self->fTime = time(NULL) - pMcStas->startTime; - return status; +static int McReadValues(struct __COUNTER *self) +{ + int status; + pMcStasController pMcStas = NULL; + + pMcStas = (pMcStasController) self->pData; + + status = McStasTransferData(pMcStas); + if (status == HWFault) { + self->iErrorCode = SCRIPTERROR; + } + self->fTime = time(NULL) - pMcStas->startTime; + return status; } + /*--------------------------------------------------------------------------*/ static int McGetError(struct __COUNTER *self, int *iCode, char *error, - int iErrLen){ - pMcStasController pMcStas = NULL; - pMcStas = (pMcStasController)self->pData; + int iErrLen) +{ + pMcStasController pMcStas = NULL; + pMcStas = (pMcStasController) self->pData; - switch(self->iErrorCode){ - case SCRIPTERROR: - McStasGetError(pMcStas,error,iErrLen); - break; - case NOTIMPLEMENTED: - strncpy(error,"Feauture not implemented",iErrLen); - break; - default: - strncpy(error,"Unknown error code in McStas Driver",iErrLen); - break; - } - return 1; + switch (self->iErrorCode) { + case SCRIPTERROR: + McStasGetError(pMcStas, error, iErrLen); + break; + case NOTIMPLEMENTED: + strncpy(error, "Feauture not implemented", iErrLen); + break; + default: + strncpy(error, "Unknown error code in McStas Driver", iErrLen); + break; + } + return 1; } + /*------------------------------------------------------------------------*/ -static int McTryAndFixIt(struct __COUNTER *self, int iCode){ - int status; - pMcStasController pMcStas = NULL; - - pMcStas = (pMcStasController)self->pData; - - status = McStasFix(pMcStas); - return status; +static int McTryAndFixIt(struct __COUNTER *self, int iCode) +{ + int status; + pMcStasController pMcStas = NULL; + + pMcStas = (pMcStasController) self->pData; + + status = McStasFix(pMcStas); + return status; } + /*------------------------------------------------------------------------*/ -static int McSet(struct __COUNTER *self, char *name, int iCter, float FVal){ - return 1; +static int McSet(struct __COUNTER *self, char *name, int iCter, float FVal) +{ + return 1; } + /*------------------------------------------------------------------------*/ -static int McGet(struct __COUNTER *self, char *name, int iCter, float *fVal){ - *fVal = 25.99; - return 1; +static int McGet(struct __COUNTER *self, char *name, int iCter, + float *fVal) +{ + *fVal = 25.99; + return 1; } + /*-------------------------------------------------------------------------*/ -static int McSend(struct __COUNTER *self, char *pText, - char *pReply, int iReplyLen){ - strncpy(pReply,"WARNING: McStas simulation cannot be sent anything", - iReplyLen); - return 1; +static int McSend(struct __COUNTER *self, char *pText, + char *pReply, int iReplyLen) +{ + strncpy(pReply, "WARNING: McStas simulation cannot be sent anything", + iReplyLen); + return 1; } + /*-------------------------------------------------------------------------*/ -pCounterDriver NewMcStasCounter(char *name){ - pMcStasController pMcStas = NULL; - pCounterDriver pNew = NULL; +pCounterDriver NewMcStasCounter(char *name) +{ + pMcStasController pMcStas = NULL; + pCounterDriver pNew = NULL; - /* - * cannot do it without a McStas Controller - */ - pMcStas = FindCommandData(pServ->pSics,"mccontrol","McStasController"); - if(pMcStas == NULL){ - return NULL; - } - - pNew = CreateCounterDriver(name,"McStas"); - if(pNew == NULL){ - return NULL; - } - pNew->iNoOfMonitors = 10; - pNew->pData = pMcStas; - - pNew->GetStatus = McStatus; - pNew->Start = McStart; - pNew->Halt = McHalt; - pNew->ReadValues = McReadValues; - pNew->GetError = McGetError; - pNew->TryAndFixIt = McTryAndFixIt; - pNew->Pause = McPause; - pNew->Continue = McContinue; - pNew->Set = McSet; - pNew->Get = McGet; - pNew->Send = McSend; - pNew->KillPrivate = NULL; + /* + * cannot do it without a McStas Controller + */ + pMcStas = FindCommandData(pServ->pSics, "mccontrol", "McStasController"); + if (pMcStas == NULL) { + return NULL; + } - return pNew; -} + pNew = CreateCounterDriver(name, "McStas"); + if (pNew == NULL) { + return NULL; + } + pNew->iNoOfMonitors = 10; + pNew->pData = pMcStas; + + pNew->GetStatus = McStatus; + pNew->Start = McStart; + pNew->Halt = McHalt; + pNew->ReadValues = McReadValues; + pNew->GetError = McGetError; + pNew->TryAndFixIt = McTryAndFixIt; + pNew->Pause = McPause; + pNew->Continue = McContinue; + pNew->Set = McSet; + pNew->Get = McGet; + pNew->Send = McSend; + pNew->KillPrivate = NULL; + + return pNew; +} diff --git a/mcstashm.c b/mcstashm.c index 9e2b10e3..3c5ab849 100644 --- a/mcstashm.c +++ b/mcstashm.c @@ -17,193 +17,221 @@ #include "stringdict.h" #include "HistDriv.i" /*================= operator functions ====================================*/ -static int McHMConfigure(pHistDriver self, SConnection *pCon, - pStringDict pOpt, SicsInterp *pSics){ - char counterName[80]; - char pError[256]; - - if(StringDictGet(pOpt,"counter",counterName,79) == 1){ - self->pPriv = FindCommandData(pSics,counterName,"SingleCounter"); - if(self->pPriv == NULL){ - snprintf(pError,255, - "ERROR: tried to configure counter but %s not found", - counterName); - SCWrite(pCon,pError,eError); - return 0; - } - } - self->iReconfig = 0; - return configureHMdata(self->data,pOpt,pCon); +static int McHMConfigure(pHistDriver self, SConnection * pCon, + pStringDict pOpt, SicsInterp * pSics) +{ + char counterName[80]; + char pError[256]; + + if (StringDictGet(pOpt, "counter", counterName, 79) == 1) { + self->pPriv = FindCommandData(pSics, counterName, "SingleCounter"); + if (self->pPriv == NULL) { + snprintf(pError, 255, + "ERROR: tried to configure counter but %s not found", + counterName); + SCWrite(pCon, pError, eError); + return 0; + } + } + self->iReconfig = 0; + return configureHMdata(self->data, pOpt, pCon); } + /*-------------------------------------------------------------------------*/ -static int McHMStart(pHistDriver self, SConnection *pCon){ - pCounter pCount = NULL; - - /* - * clear data - */ - clearHMData(self->data); - /* - * if there is a counter, make him start - */ - pCount = (pCounter)self->pPriv; - if(pCount != NULL){ - pCount->pDriv->eMode = self->eCount; - pCount->pDriv->fPreset = self->fCountPreset; - return pCount->pCountInt->StartCount(pCount,pCon); - } else { - return 1; - } +static int McHMStart(pHistDriver self, SConnection * pCon) +{ + pCounter pCount = NULL; + + /* + * clear data + */ + clearHMData(self->data); + /* + * if there is a counter, make him start + */ + pCount = (pCounter) self->pPriv; + if (pCount != NULL) { + pCount->pDriv->eMode = self->eCount; + pCount->pDriv->fPreset = self->fCountPreset; + return pCount->pCountInt->StartCount(pCount, pCon); + } else { + return 1; + } } + /*------------------------------------------------------------------------*/ -static int McHMHalt(pHistDriver self){ - pCounter pCount = NULL; +static int McHMHalt(pHistDriver self) +{ + pCounter pCount = NULL; - pCount = (pCounter)self->pPriv; - if(pCount != NULL){ - return pCount->pCountInt->Halt(pCount); - } else { - return 1; - } + pCount = (pCounter) self->pPriv; + if (pCount != NULL) { + return pCount->pCountInt->Halt(pCount); + } else { + return 1; + } } + /*-------------------------------------------------------------------------*/ -static int McHMCountStatus(pHistDriver self, SConnection *pCon){ - pCounter pCount = NULL; +static int McHMCountStatus(pHistDriver self, SConnection * pCon) +{ + pCounter pCount = NULL; - pCount = (pCounter)self->pPriv; - if(pCount != NULL){ - return pCount->pCountInt->CheckCountStatus(pCount,pCon); - } else { - return HWIdle; - } + pCount = (pCounter) self->pPriv; + if (pCount != NULL) { + return pCount->pCountInt->CheckCountStatus(pCount, pCon); + } else { + return HWIdle; + } } + /*------------------------------------------------------------------------*/ -static int McHMGetError(pHistDriver self, int *iCode, char *error, int errLen){ - pCounter pCount = NULL; +static int McHMGetError(pHistDriver self, int *iCode, char *error, + int errLen) +{ + pCounter pCount = NULL; - pCount = (pCounter)self->pPriv; - if(pCount != NULL){ - return pCount->pDriv->GetError(pCount->pDriv,iCode, error, errLen); - } else { - *iCode = -1000; - strncpy(error,"Feature not implemented in McStasHM",errLen); - return 1; - } + pCount = (pCounter) self->pPriv; + if (pCount != NULL) { + return pCount->pDriv->GetError(pCount->pDriv, iCode, error, errLen); + } else { + *iCode = -1000; + strncpy(error, "Feature not implemented in McStasHM", errLen); + return 1; + } } + /*-------------------------------------------------------------------------*/ -static int McHMFixIt(pHistDriver self, int iCode){ - pCounter pCount = NULL; +static int McHMFixIt(pHistDriver self, int iCode) +{ + pCounter pCount = NULL; - pCount = (pCounter)self->pPriv; - if(pCount != NULL){ - return pCount->pDriv->TryAndFixIt(pCount->pDriv,iCode); - } else { - return COTERM; - } + pCount = (pCounter) self->pPriv; + if (pCount != NULL) { + return pCount->pDriv->TryAndFixIt(pCount->pDriv, iCode); + } else { + return COTERM; + } } -/*-----------------------------------------------------------------------*/ -static int McHMGetData(pHistDriver self, SConnection *pCon){ - pCounter pCount = NULL; - pCount = (pCounter)self->pPriv; - if(pCount != NULL){ - return pCount->pCountInt->TransferData(pCount,pCon); - } else { - return 1; - } -} /*-----------------------------------------------------------------------*/ -static int McHMGetHistogram(pHistDriver self, SConnection *pCon, - int bank, int start, int end, HistInt *pData){ +static int McHMGetData(pHistDriver self, SConnection * pCon) +{ + pCounter pCount = NULL; + + pCount = (pCounter) self->pPriv; + if (pCount != NULL) { + return pCount->pCountInt->TransferData(pCount, pCon); + } else { + return 1; + } +} + +/*-----------------------------------------------------------------------*/ +static int McHMGetHistogram(pHistDriver self, SConnection * pCon, + int bank, int start, int end, HistInt * pData) +{ /* * make sure data gets transferred */ - return McHMGetData(self,pCon); + return McHMGetData(self, pCon); } -/*-------------------------------------------------------------------------*/ -static int McHMSetHistogram(pHistDriver self, SConnection *pCon, - int bank, int start, int end, - HistInt *pData){ - int i, count = 0; - HistInt *hmData; - - assert(bank == 0); - hmData = self->data->localBuffer; - for(i = start; i < end; i++, count++){ - hmData[i] = pData[count]; - } - return 1; -} /*-------------------------------------------------------------------------*/ -static long McHMMonitor(pHistDriver self, int i, SConnection *pCon){ - pCounter pCount = NULL; +static int McHMSetHistogram(pHistDriver self, SConnection * pCon, + int bank, int start, int end, HistInt * pData) +{ + int i, count = 0; + HistInt *hmData; - pCount = (pCounter)self->pPriv; - if(pCount != NULL){ - return GetMonitor(pCount,i,pCon); - } else { - return 0L; - } + assert(bank == 0); + + hmData = self->data->localBuffer; + for (i = start; i < end; i++, count++) { + hmData[i] = pData[count]; + } + return 1; } -/*-------------------------------------------------------------------------*/ -static float McHMGetTime(pHistDriver self, SConnection *pCon){ - pCounter pCount = NULL; - pCount = (pCounter)self->pPriv; - if(pCount != NULL){ - return GetCountTime(pCount,pCon);; - } else { - return -999.99; - } +/*-------------------------------------------------------------------------*/ +static long McHMMonitor(pHistDriver self, int i, SConnection * pCon) +{ + pCounter pCount = NULL; + + pCount = (pCounter) self->pPriv; + if (pCount != NULL) { + return GetMonitor(pCount, i, pCon); + } else { + return 0L; + } } + +/*-------------------------------------------------------------------------*/ +static float McHMGetTime(pHistDriver self, SConnection * pCon) +{ + pCounter pCount = NULL; + + pCount = (pCounter) self->pPriv; + if (pCount != NULL) { + return GetCountTime(pCount, pCon);; + } else { + return -999.99; + } +} + /*--------------------------------------------------------------------------*/ -static int McHMPreset(pHistDriver self, SConnection *pCon, HistInt val){ - int i; - long length; - HistInt *data; - - length = getHMDataLength(self->data); - data = self->data->localBuffer; - for(i = 0; i < length; i++){ - data[i] = val; - } - return 1; -} -/*------------------------------------------------------------------------*/ -static int McHMPause(pHistDriver self, SConnection *pCon){ - return HWFault; -} -/*-----------------------------------------------------------------------*/ -static int McHMContinue(pHistDriver self, SConnection *pCon){ - return HWFault; -} -/*========================== the actual creation function ================*/ -pHistDriver NewMcStasHM(pStringDict pOpt){ - pHistDriver pNew = NULL; - - pNew = CreateHistDriver(pOpt); - if(pNew == NULL){ - return NULL; - } - pNew->Configure = McHMConfigure; - pNew->Start = McHMStart; - pNew->Halt = McHMHalt; - pNew->GetCountStatus = McHMCountStatus; - pNew->GetError = McHMGetError; - pNew->TryAndFixIt = McHMFixIt; - pNew->GetData = McHMGetData; - pNew->GetHistogram = McHMGetHistogram; - pNew->SetHistogram = McHMSetHistogram; - pNew->GetMonitor = McHMMonitor; - pNew->GetTime = McHMGetTime; - pNew->Preset = McHMPreset; - pNew->FreePrivate = NULL; - pNew->Pause = McHMPause; - pNew->Continue = McHMContinue; - StringDictAddPair(pOpt,"counter","UNKNOWN"); - StringDictUpdate(pOpt,"update","10"); - - return pNew; +static int McHMPreset(pHistDriver self, SConnection * pCon, HistInt val) +{ + int i; + long length; + HistInt *data; + + length = getHMDataLength(self->data); + data = self->data->localBuffer; + for (i = 0; i < length; i++) { + data[i] = val; + } + return 1; } +/*------------------------------------------------------------------------*/ +static int McHMPause(pHistDriver self, SConnection * pCon) +{ + return HWFault; +} + +/*-----------------------------------------------------------------------*/ +static int McHMContinue(pHistDriver self, SConnection * pCon) +{ + return HWFault; +} + +/*========================== the actual creation function ================*/ +pHistDriver NewMcStasHM(pStringDict pOpt) +{ + pHistDriver pNew = NULL; + + pNew = CreateHistDriver(pOpt); + if (pNew == NULL) { + return NULL; + } + pNew->Configure = McHMConfigure; + pNew->Start = McHMStart; + pNew->Halt = McHMHalt; + pNew->GetCountStatus = McHMCountStatus; + pNew->GetError = McHMGetError; + pNew->TryAndFixIt = McHMFixIt; + pNew->GetData = McHMGetData; + pNew->GetHistogram = McHMGetHistogram; + pNew->SetHistogram = McHMSetHistogram; + pNew->GetMonitor = McHMMonitor; + pNew->GetTime = McHMGetTime; + pNew->Preset = McHMPreset; + pNew->FreePrivate = NULL; + pNew->Pause = McHMPause; + pNew->Continue = McHMContinue; + StringDictAddPair(pOpt, "counter", "UNKNOWN"); + StringDictUpdate(pOpt, "update", "10"); + + return pNew; +} diff --git a/mcstashm.h b/mcstashm.h index 4596448e..e17b5944 100644 --- a/mcstashm.h +++ b/mcstashm.h @@ -12,5 +12,5 @@ -------------------------------------------------------------------------*/ #ifndef _MCSTASHM_H_ #define _MCSTASHM_H_ - pHistDriver NewMcStasHM(pStringDict pOpt); -#endif //_MCSTASHM_H_ +pHistDriver NewMcStasHM(pStringDict pOpt); +#endif //_MCSTASHM_H_ diff --git a/mesure.c b/mesure.c index 5a1c8514..3cf5e44d 100644 --- a/mesure.c +++ b/mesure.c @@ -35,8 +35,8 @@ #include "stdscan.h" #include "exeman.h" - extern void SNXFormatTime(char *pBueffel, int iLen); - extern float nintf(float f); +extern void SNXFormatTime(char *pBueffel, int iLen); +extern float nintf(float f); #define ANGERR 0.2 /* @@ -44,396 +44,370 @@ define MESSDEBUG for simulated peaks. This helps in debugging this code and the initial data correction code -*/ +*/ - extern void SNXFormatTime(char *pBueffel, int iLen); /* nxutil.c */ +extern void SNXFormatTime(char *pBueffel, int iLen); /* nxutil.c */ /*------------------- the data structure -----------------------------------*/ - typedef struct __Mesure - { - pObjectDescriptor pDes; /* standard object descriptor */ - pICallBack pCall; /* callback interface for automatic notification */ - pScanData pScanner; /* scan object to use for scans */ - pHKL pCryst; /* hkl object for crystallographic calc - and reflection driving */ - pMotor pOmega; /* motor for omega scans */ - pMotor p2Theta; /* motor for 2 theta scans*/ - char *pCOmega; /* name of omega motor */ - char *pC2Theta; /* name of 2 theta motor */ - char *pFileRoot; /* where to write files */ - pDataNumber pDanu; /* where to get data file number */ - FILE *fRefl; /* reflection profile file */ - FILE *fHKL; /* integrated intensity file */ - int iLogFile; /* log file num at connection */ - SConnection *pCon; /* log file owning connection */ - char *pCurrentFile; /* current file root */ - char headerTemplate[512]; - int iCount; /* count of reflection */ - int CountMode; /* timer or preset */ - int np; /* number of scan points */ - float fPreset; /* counting preset */ - float fStep; /* omega step widths */ - long *lCounts; /* array to store counting values */ - float fPosition[4]; /* the real positions after driving */ - int iCompact; /* true if compact scan ouput. */ - int weak; /* weak flag: remeasure weak reflections */ - long weakThreshold; /* threshold when a peak is so weak that is has to - remeasured */ - int fastScan; /* flag for using fastscans for scanning reflections */ - int psiMode; /* 1 for psi scan mode, 0 else */ - int psd; /* a flag for making 2D detector scans */ - int stepTable; /* mapping of two theta ranges to step width and - variable to scan */ - } Mesure; +typedef struct __Mesure { + pObjectDescriptor pDes; /* standard object descriptor */ + pICallBack pCall; /* callback interface for automatic notification */ + pScanData pScanner; /* scan object to use for scans */ + pHKL pCryst; /* hkl object for crystallographic calc + and reflection driving */ + pMotor pOmega; /* motor for omega scans */ + pMotor p2Theta; /* motor for 2 theta scans */ + char *pCOmega; /* name of omega motor */ + char *pC2Theta; /* name of 2 theta motor */ + char *pFileRoot; /* where to write files */ + pDataNumber pDanu; /* where to get data file number */ + FILE *fRefl; /* reflection profile file */ + FILE *fHKL; /* integrated intensity file */ + int iLogFile; /* log file num at connection */ + SConnection *pCon; /* log file owning connection */ + char *pCurrentFile; /* current file root */ + char headerTemplate[512]; + int iCount; /* count of reflection */ + int CountMode; /* timer or preset */ + int np; /* number of scan points */ + float fPreset; /* counting preset */ + float fStep; /* omega step widths */ + long *lCounts; /* array to store counting values */ + float fPosition[4]; /* the real positions after driving */ + int iCompact; /* true if compact scan ouput. */ + int weak; /* weak flag: remeasure weak reflections */ + long weakThreshold; /* threshold when a peak is so weak that is has to + remeasured */ + int fastScan; /* flag for using fastscans for scanning reflections */ + int psiMode; /* 1 for psi scan mode, 0 else */ + int psd; /* a flag for making 2D detector scans */ + int stepTable; /* mapping of two theta ranges to step width and + variable to scan */ +} Mesure; /*-------------------------------------------------------------------------*/ -static int SaveMesure(void *pData, char *name, FILE *fd) +static int SaveMesure(void *pData, char *name, FILE * fd) { - pMesure self = (pMesure)pData; - - fprintf(fd,"#Four Circle Dataset Module %s\n",name); - if(self->CountMode == eTimer) - { - fprintf(fd,"%s countmode timer\n",name); - } - else - { - fprintf(fd,"%s countmode monitor\n",name); + pMesure self = (pMesure) pData; + + fprintf(fd, "#Four Circle Dataset Module %s\n", name); + if (self->CountMode == eTimer) { + fprintf(fd, "%s countmode timer\n", name); + } else { + fprintf(fd, "%s countmode monitor\n", name); } - fprintf(fd,"%s np %d\n", name, self->np); - fprintf(fd,"%s preset %f\n", name, self->fPreset); - fprintf(fd,"%s step %f\n", name, self->fStep); - fprintf(fd,"%s weakthreshold %ld\n", name, self->weakThreshold); - fprintf(fd,"%s compact %d\n", name, self->iCompact); - fprintf(fd,"%s psd %d\n", name, self->psd); - fprintf(fd,"%s weak %d\n", name, self->weak); - fprintf(fd,"%s fastscan %d\n", name, self->fastScan); - SaveFourCircleTable(self->stepTable,name,fd); + fprintf(fd, "%s np %d\n", name, self->np); + fprintf(fd, "%s preset %f\n", name, self->fPreset); + fprintf(fd, "%s step %f\n", name, self->fStep); + fprintf(fd, "%s weakthreshold %ld\n", name, self->weakThreshold); + fprintf(fd, "%s compact %d\n", name, self->iCompact); + fprintf(fd, "%s psd %d\n", name, self->psd); + fprintf(fd, "%s weak %d\n", name, self->weak); + fprintf(fd, "%s fastscan %d\n", name, self->fastScan); + SaveFourCircleTable(self->stepTable, name, fd); return 1; } + /*-------------------------------------------------------------------------*/ -static void ListMesure(pMesure self, char *name, SConnection *pCon) +static void ListMesure(pMesure self, char *name, SConnection * pCon) { Tcl_DString list; char pBuffer[132]; - + Tcl_DStringInit(&list); - if(self->CountMode == eTimer) - { - snprintf(pBuffer,131,"%s.countmode timer\n",name); - } - else - { - snprintf(pBuffer,131,"%s.countmode monitor\n",name); + if (self->CountMode == eTimer) { + snprintf(pBuffer, 131, "%s.countmode timer\n", name); + } else { + snprintf(pBuffer, 131, "%s.countmode monitor\n", name); } - Tcl_DStringAppend(&list,pBuffer,-1); - snprintf(pBuffer,131,"%s.np %d\n", name, self->np); - Tcl_DStringAppend(&list,pBuffer,-1); - snprintf(pBuffer,131,"%s.preset %f\n", name, self->fPreset); - Tcl_DStringAppend(&list,pBuffer,-1); - snprintf(pBuffer,131,"%s.step %f\n", name, self->fStep); - Tcl_DStringAppend(&list,pBuffer,-1); - snprintf(pBuffer,131,"%s.weakthreshold %ld\n", name, self->weakThreshold); - Tcl_DStringAppend(&list,pBuffer,-1); - snprintf(pBuffer,131,"%s.compact %d\n", name, self->iCompact); - Tcl_DStringAppend(&list,pBuffer,-1); - snprintf(pBuffer,131,"%s.psd %d\n", name, self->psd); - Tcl_DStringAppend(&list,pBuffer,-1); - snprintf(pBuffer,131,"%s.weak %d\n", name, self->weak); - Tcl_DStringAppend(&list,pBuffer,-1); - snprintf(pBuffer,131,"%s.fastscan %d\n", name, self->fastScan); - Tcl_DStringAppend(&list,pBuffer,-1); - SCWrite(pCon,Tcl_DStringValue(&list),eValue); + Tcl_DStringAppend(&list, pBuffer, -1); + snprintf(pBuffer, 131, "%s.np %d\n", name, self->np); + Tcl_DStringAppend(&list, pBuffer, -1); + snprintf(pBuffer, 131, "%s.preset %f\n", name, self->fPreset); + Tcl_DStringAppend(&list, pBuffer, -1); + snprintf(pBuffer, 131, "%s.step %f\n", name, self->fStep); + Tcl_DStringAppend(&list, pBuffer, -1); + snprintf(pBuffer, 131, "%s.weakthreshold %ld\n", name, + self->weakThreshold); + Tcl_DStringAppend(&list, pBuffer, -1); + snprintf(pBuffer, 131, "%s.compact %d\n", name, self->iCompact); + Tcl_DStringAppend(&list, pBuffer, -1); + snprintf(pBuffer, 131, "%s.psd %d\n", name, self->psd); + Tcl_DStringAppend(&list, pBuffer, -1); + snprintf(pBuffer, 131, "%s.weak %d\n", name, self->weak); + Tcl_DStringAppend(&list, pBuffer, -1); + snprintf(pBuffer, 131, "%s.fastscan %d\n", name, self->fastScan); + Tcl_DStringAppend(&list, pBuffer, -1); + SCWrite(pCon, Tcl_DStringValue(&list), eValue); Tcl_DStringFree(&list); } -/*--------------------------------------------------------------------------*/ - pMesure CreateMesure(pHKL pCryst, pScanData pScanner, pMotor pOmega, - char *pOm, pMotor p2Theta, char *p2t, - char *pFileRoot, - pDataNumber pDanu, char *hdTemplate) - { - pMesure pNew = NULL; - - assert(pCryst); - assert(pScanner); - assert(pOmega); - assert(pFileRoot); - assert(pDanu); - - /* allocate space............. */ - pNew = (pMesure)malloc(sizeof(Mesure)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(Mesure)); - - pNew->pDes = CreateDescriptor("Mesure"); - pNew->pDes->SaveStatus = SaveMesure; - pNew->pCall = CreateCallBackInterface(); - if( !pNew->pDes || !pNew->pCall) - { - free(pNew); - return NULL; - } - - /* asssign defaults */ - pNew->pScanner = pScanner; - pNew->pCryst = pCryst; - pNew->pOmega = pOmega; - pNew->p2Theta = p2Theta; - pNew->pCOmega = strdup(pOm); - pNew->pC2Theta = strdup(p2t); - pNew->pFileRoot = strdup(pFileRoot); - pNew->pDanu = pDanu; - pNew->iCount = 0; - pNew->CountMode = 0; - pNew->np = 50; - pNew->fStep = 0.05; - pNew->fPreset = 2; - pNew->iCompact = 1; - pNew->psd = 0; - pNew->weak = 0; - pNew->weakThreshold = 99999; - pNew->fastScan = 0; - pNew->psiMode = 0; -#ifdef MESSDEBUG - pNew->lCounts = (long *)malloc(90*sizeof(long)); -#endif - pNew->lCounts = (long *)malloc(50*sizeof(long)); - pNew->stepTable = MakeFourCircleTable(); - strncpy(pNew->headerTemplate,hdTemplate,511); - return pNew; - } -/*------------------------------------------------------------------------*/ - void DeleteMesure(void *pData) - { - pMesure self = NULL; - - self = (pMesure)pData; - - if(!pData) - { - return; - } - - if(self->pDes) - DeleteDescriptor(self->pDes); - - if(self->pCall) - DeleteCallBackInterface(self->pCall); - if(self->pFileRoot) - free(self->pFileRoot); - if(self->pCOmega) - free(self->pCOmega); - if(self->fRefl) - MesureClose(self); - if(self->lCounts) - free(self->lCounts); - DeleteFourCircleTable(self->stepTable); - free(self); - } -/*------------------------------------------------------------------------*/ - int MesureFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pMesure pNew = NULL; - pHKL pCryst = NULL; - pScanData pScan = NULL; - CommandList *pCom = NULL; - pMotor pMot = NULL, pMot2 = NULL; - pDataNumber pDanu = NULL; - pSicsO2T pO2T = NULL; - char pBueffel[512]; - pDummy pDum = NULL; - int iRet; - - assert(pCon); - assert(pSics); - - /* check no of parameters - inicom name hkl scan omega root danu - */ - if(argc < 9) - { - SCWrite(pCon, - "ERROR: Insufficient number of parameters to MesureFactory",eError); - return 0; - } - - /* work parameters one by one, first hkl */ - pCom = FindCommand(pSics,argv[2]); - if(pCom) - { - pDum = (pDummy)pCom->pData; - if(pDum) - { - if(strcmp(pDum->pDescriptor->name,"4-Circle-Calculus") == 0) - { - pCryst = (pHKL)pCom->pData; - } - } - } - if(!pCryst) - { - sprintf(pBueffel,"ERROR: %s is no four circle calculus object",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* scanner */ - pCom = FindCommand(pSics,argv[3]); - if(pCom) - { - pDum = (pDummy)pCom->pData; - if(pDum) - { - if(strcmp(pDum->pDescriptor->name,"ScanObject") == 0) - { - pScan = (pScanData)pCom->pData; - } - } - } - if(!pScan) - { - sprintf(pBueffel,"ERROR: %s is no scan object",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* omega */ - pMot = FindMotor(pSics,argv[4]); - if(!pMot) - { - sprintf(pBueffel,"ERROR: %s is no motor object ",argv[4]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* 2 theta */ - pMot2 = FindMotor(pSics,argv[5]); - if(!pMot2) - { - sprintf(pBueffel,"ERROR: %s is no motor object ",argv[5]); - SCWrite(pCon,pBueffel,eError); - return 0; +/*--------------------------------------------------------------------------*/ +pMesure CreateMesure(pHKL pCryst, pScanData pScanner, pMotor pOmega, + char *pOm, pMotor p2Theta, char *p2t, + char *pFileRoot, pDataNumber pDanu, char *hdTemplate) +{ + pMesure pNew = NULL; + + assert(pCryst); + assert(pScanner); + assert(pOmega); + assert(pFileRoot); + assert(pDanu); + + /* allocate space............. */ + pNew = (pMesure) malloc(sizeof(Mesure)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(Mesure)); + + pNew->pDes = CreateDescriptor("Mesure"); + pNew->pDes->SaveStatus = SaveMesure; + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pDes || !pNew->pCall) { + free(pNew); + return NULL; + } + + /* asssign defaults */ + pNew->pScanner = pScanner; + pNew->pCryst = pCryst; + pNew->pOmega = pOmega; + pNew->p2Theta = p2Theta; + pNew->pCOmega = strdup(pOm); + pNew->pC2Theta = strdup(p2t); + pNew->pFileRoot = strdup(pFileRoot); + pNew->pDanu = pDanu; + pNew->iCount = 0; + pNew->CountMode = 0; + pNew->np = 50; + pNew->fStep = 0.05; + pNew->fPreset = 2; + pNew->iCompact = 1; + pNew->psd = 0; + pNew->weak = 0; + pNew->weakThreshold = 99999; + pNew->fastScan = 0; + pNew->psiMode = 0; +#ifdef MESSDEBUG + pNew->lCounts = (long *) malloc(90 * sizeof(long)); +#endif + pNew->lCounts = (long *) malloc(50 * sizeof(long)); + pNew->stepTable = MakeFourCircleTable(); + strncpy(pNew->headerTemplate, hdTemplate, 511); + return pNew; +} + +/*------------------------------------------------------------------------*/ +void DeleteMesure(void *pData) +{ + pMesure self = NULL; + + self = (pMesure) pData; + + if (!pData) { + return; + } + + if (self->pDes) + DeleteDescriptor(self->pDes); + + if (self->pCall) + DeleteCallBackInterface(self->pCall); + if (self->pFileRoot) + free(self->pFileRoot); + if (self->pCOmega) + free(self->pCOmega); + if (self->fRefl) + MesureClose(self); + if (self->lCounts) + free(self->lCounts); + DeleteFourCircleTable(self->stepTable); + free(self); +} + +/*------------------------------------------------------------------------*/ +int MesureFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pMesure pNew = NULL; + pHKL pCryst = NULL; + pScanData pScan = NULL; + CommandList *pCom = NULL; + pMotor pMot = NULL, pMot2 = NULL; + pDataNumber pDanu = NULL; + pSicsO2T pO2T = NULL; + char pBueffel[512]; + pDummy pDum = NULL; + int iRet; + + assert(pCon); + assert(pSics); + + /* check no of parameters + inicom name hkl scan omega root danu + */ + if (argc < 9) { + SCWrite(pCon, + "ERROR: Insufficient number of parameters to MesureFactory", + eError); + return 0; + } + + /* work parameters one by one, first hkl */ + pCom = FindCommand(pSics, argv[2]); + if (pCom) { + pDum = (pDummy) pCom->pData; + if (pDum) { + if (strcmp(pDum->pDescriptor->name, "4-Circle-Calculus") == 0) { + pCryst = (pHKL) pCom->pData; } - - /* Data Number */ - pCom = FindCommand(pSics,argv[7]); - if(pCom) - { - pDum = (pDummy)pCom->pData; - if(pDum) - { - if(strcmp(pDum->pDescriptor->name,"DataNumber") == 0) - { - pDanu = (pDataNumber)pCom->pData; - } - } + } + } + if (!pCryst) { + sprintf(pBueffel, "ERROR: %s is no four circle calculus object", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* scanner */ + pCom = FindCommand(pSics, argv[3]); + if (pCom) { + pDum = (pDummy) pCom->pData; + if (pDum) { + if (strcmp(pDum->pDescriptor->name, "ScanObject") == 0) { + pScan = (pScanData) pCom->pData; } - if(!pDanu) - { - sprintf(pBueffel,"ERROR: %s is no DataNumber object",argv[7]); - SCWrite(pCon,pBueffel,eError); - return 0; + } + } + if (!pScan) { + sprintf(pBueffel, "ERROR: %s is no scan object", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* omega */ + pMot = FindMotor(pSics, argv[4]); + if (!pMot) { + sprintf(pBueffel, "ERROR: %s is no motor object ", argv[4]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* 2 theta */ + pMot2 = FindMotor(pSics, argv[5]); + if (!pMot2) { + sprintf(pBueffel, "ERROR: %s is no motor object ", argv[5]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* Data Number */ + pCom = FindCommand(pSics, argv[7]); + if (pCom) { + pDum = (pDummy) pCom->pData; + if (pDum) { + if (strcmp(pDum->pDescriptor->name, "DataNumber") == 0) { + pDanu = (pDataNumber) pCom->pData; } - - /* finally create the thing */ - pNew = CreateMesure(pCryst,pScan,pMot,argv[4], pMot2, argv[5], - argv[6],pDanu,argv[8]); - if(!pNew) - { - SCWrite(pCon,"ERROR: no memory in MesureFactory",eError); - return 0; - } - - /* add the new command */ - iRet = AddCommand(pSics,argv[1],MesureAction,DeleteMesure,pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } + } + } + if (!pDanu) { + sprintf(pBueffel, "ERROR: %s is no DataNumber object", argv[7]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* finally create the thing */ + pNew = CreateMesure(pCryst, pScan, pMot, argv[4], pMot2, argv[5], + argv[6], pDanu, argv[8]); + if (!pNew) { + SCWrite(pCon, "ERROR: no memory in MesureFactory", eError); + return 0; + } + + /* add the new command */ + iRet = AddCommand(pSics, argv[1], MesureAction, DeleteMesure, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} + /*------------------------------------------------------------------------ This implements the compact scan output for TRICS scans */ - static int CompactScanData(pScanData self, int iPoint) - { - pVarEntry pVar = NULL; - void *pDings; - int i, iRet, status; - float fVal; - char pStatus[512], pItem[20]; - char pHead[512]; - CountEntry sCount; - char *pAns = NULL, *pPtr = NULL ; - Tcl_Interp *pTcl; +static int CompactScanData(pScanData self, int iPoint) +{ + pVarEntry pVar = NULL; + void *pDings; + int i, iRet, status; + float fVal; + char pStatus[512], pItem[20]; + char pHead[512]; + CountEntry sCount; + char *pAns = NULL, *pPtr = NULL; + Tcl_Interp *pTcl; - assert(self); - assert(self->pCon); - - /* loop over all scan variables */ - status = 1; - memset(pHead,0,512*sizeof(char)); - memset(pStatus,0,512*sizeof(char)); - memset(pItem,0,20*sizeof(char)); - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pDings); - pVar = (pVarEntry)pDings; - if(pVar) - { - fVal = pVar->pInter->GetValue(pVar->pObject,self->pCon); - AppendScanVar(pVar,fVal); - sprintf(pItem,"%-10.10s",pVar->Name); - strcat(pHead,pItem); - sprintf(pItem,"%-10.3f",fVal); - strcat(pStatus,pItem); - } - } - - /* store counter data */ - /* monitors */ - for(i = 1; i < 10; i++) - { - sCount.Monitors[i-1] = GetMonitor((pCounter)self->pCounterData,i, - self->pCon); - } - if( self->iChannel != 0 && self->iChannel != -10 ) - { - sCount.Monitors[self->iChannel - 1] = - GetCounts((pCounter)self->pCounterData, - self->pCon); - } - if(self->iChannel == 0) - { - sCount.lCount = GetCounts((pCounter)self->pCounterData,self->pCon); - } - else - { - sCount.lCount = GetMonitor((pCounter)self->pCounterData, - self->iChannel, self->pCon); - } - - /* stow away */ - DynarReplace(self->pCounts,self->iCounts,&sCount,sizeof(CountEntry)); - self->iCounts++; + assert(self); + assert(self->pCon); - return 1; + /* loop over all scan variables */ + status = 1; + memset(pHead, 0, 512 * sizeof(char)); + memset(pStatus, 0, 512 * sizeof(char)); + memset(pItem, 0, 20 * sizeof(char)); + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pDings); + pVar = (pVarEntry) pDings; + if (pVar) { + fVal = pVar->pInter->GetValue(pVar->pObject, self->pCon); + AppendScanVar(pVar, fVal); + sprintf(pItem, "%-10.10s", pVar->Name); + strcat(pHead, pItem); + sprintf(pItem, "%-10.3f", fVal); + strcat(pStatus, pItem); + } } + + /* store counter data */ + /* monitors */ + for (i = 1; i < 10; i++) { + sCount.Monitors[i - 1] = GetMonitor((pCounter) self->pCounterData, i, + self->pCon); + } + if (self->iChannel != 0 && self->iChannel != -10) { + sCount.Monitors[self->iChannel - 1] = + GetCounts((pCounter) self->pCounterData, self->pCon); + } + if (self->iChannel == 0) { + sCount.lCount = GetCounts((pCounter) self->pCounterData, self->pCon); + } else { + sCount.lCount = GetMonitor((pCounter) self->pCounterData, + self->iChannel, self->pCon); + } + + /* stow away */ + DynarReplace(self->pCounts, self->iCounts, &sCount, sizeof(CountEntry)); + self->iCounts++; + + return 1; +} + /*------------------------------------------------------------------------*/ static int getMesureNP(pMesure self, double twoTheta) { int np; - np = GetFourCircleScanNP(self->stepTable,twoTheta); - if(np < -800){ + np = GetFourCircleScanNP(self->stepTable, twoTheta); + if (np < -800) { np = self->np; } return np; } + /*------------------------------------------------------------------------- This is slightly tricky: the crystallography module has a scan tolerance. This is supposed to be automatically set. In order to do so, I need @@ -442,103 +416,101 @@ static int getMesureNP(pMesure self, double twoTheta) second time with the scan tolerance ste to a decent value to get the real thing. ---------------------------------------------------------------------------*/ -static int MesureCalculateSettings(pMesure self, float fHKL[3], float fSet[4], - float fPsi, SConnection *pCon) +static int MesureCalculateSettings(pMesure self, float fHKL[3], + float fSet[4], float fPsi, + SConnection * pCon) { int status, np; float step, tolerance, fHard; char *scanvar = NULL; char buffer[256]; - - SetHKLScanTolerance(self->pCryst,.0); - status = CalculateSettings(self->pCryst,fHKL,fPsi,0,fSet,pCon); - if(!status) - { + + SetHKLScanTolerance(self->pCryst, .0); + status = CalculateSettings(self->pCryst, fHKL, fPsi, 0, fSet, pCon); + if (!status) { return status; } step = GetFourCircleStep(self->stepTable, fSet[0]); - if(step < -900.){ + if (step < -900.) { step = self->fStep; } - np = getMesureNP(self,(double)fSet[0]); - tolerance = (step * (float)np)/2. + .2; - SetHKLScanTolerance(self->pCryst,tolerance); - status = CalculateSettings(self->pCryst,fHKL,fPsi,0,fSet,pCon); - if(status != 1){ + np = getMesureNP(self, (double) fSet[0]); + tolerance = (step * (float) np) / 2. + .2; + SetHKLScanTolerance(self->pCryst, tolerance); + status = CalculateSettings(self->pCryst, fHKL, fPsi, 0, fSet, pCon); + if (status != 1) { return status; } - scanvar = GetFourCircleScanVar(self->stepTable,fSet[0]); - if(scanvar != NULL && strcmp(scanvar,"om") != 0){ - tolerance *= 2.; - strcpy(buffer,"ERROR: 2theta limit problem:"); - if(!MotorCheckBoundary(self->p2Theta,fSet[0]-tolerance,&fHard, - buffer,256-strlen(buffer))){ - SCWrite(pCon,buffer,eWarning); - return 0; - } - if(!MotorCheckBoundary(self->p2Theta,fSet[0]+tolerance,&fHard, - buffer,256-strlen(buffer))){ - SCWrite(pCon,buffer,eWarning); - return 0; - } + scanvar = GetFourCircleScanVar(self->stepTable, fSet[0]); + if (scanvar != NULL && strcmp(scanvar, "om") != 0) { + tolerance *= 2.; + strcpy(buffer, "ERROR: 2theta limit problem:"); + if (!MotorCheckBoundary(self->p2Theta, fSet[0] - tolerance, &fHard, + buffer, 256 - strlen(buffer))) { + SCWrite(pCon, buffer, eWarning); + return 0; + } + if (!MotorCheckBoundary(self->p2Theta, fSet[0] + tolerance, &fHard, + buffer, 256 - strlen(buffer))) { + SCWrite(pCon, buffer, eWarning); + return 0; + } } return status; } + /*--------------------------------------------------------------------------*/ - int MesureReflection(pMesure self, float fHKL[3], float fPsi, - SConnection *pCon) - { - int iRet; - float fSet[4]; +int MesureReflection(pMesure self, float fHKL[3], float fPsi, + SConnection * pCon) +{ + int iRet; + float fSet[4]; - assert(self); + assert(self); + + iRet = MesureCalculateSettings(self, fHKL, fSet, fPsi, pCon); + if (!iRet) { + return iRet; + } + return MesureGenReflection(self, fHKL, fSet, pCon); +} - iRet = MesureCalculateSettings(self,fHKL,fSet,fPsi,pCon); - if(!iRet) - { - return iRet; - } - return MesureGenReflection(self,fHKL,fSet,pCon); - } /*-----------------------------------------------------------------------*/ -static int DriveToReflection(pMesure self, float fSet[4], SConnection *pCon) +static int DriveToReflection(pMesure self, float fSet[4], + SConnection * pCon) { int iRet, i; float fDelta; char pBueffel[132]; - iRet = DriveSettings(self->pCryst,fSet,pCon); - if(!iRet) - { + iRet = DriveSettings(self->pCryst, fSet, pCon); + if (!iRet) { return iRet; } /* store achieved position for reporting */ - iRet = GetCurrentPosition(self->pCryst,pCon,self->fPosition); - if(iRet != 1) - { + iRet = GetCurrentPosition(self->pCryst, pCon, self->fPosition); + if (iRet != 1) { return iRet; } /* check if we are really there. - */ - for(i = 0; i < 4; i++) - { + */ + for (i = 0; i < 4; i++) { fDelta = fSet[i] - self->fPosition[i]; - if(fDelta < 0.) + if (fDelta < 0.) fDelta = -fDelta; - if(fDelta > ANGERR) - { - snprintf(pBueffel,131, - "ERROR: angle %d positioned badly, aborting Reflection", - i); - SCWrite(pCon,pBueffel,eError); - return 0; + if (fDelta > ANGERR) { + snprintf(pBueffel, 131, + "ERROR: angle %d positioned badly, aborting Reflection", i); + SCWrite(pCon, pBueffel, eError); + return 0; } } return 1; } + /*----------------------------------------------------------------------- test if this scan has to be remeasured because it is weak ------------------------------------------------------------------------*/ @@ -548,41 +520,36 @@ int weakScan(pMesure self, double twoTheta) long low = 99999, high = -99999; /* - the scan is always OK if we do not test for weak conditions or we are in psd mode - */ - if(self->weak == 0 || self->psd == 1){ + the scan is always OK if we do not test for weak conditions or we are in psd mode + */ + if (self->weak == 0 || self->psd == 1) { return 0; } - - np = getMesureNP(self,twoTheta); - GetScanCounts(self->pScanner,self->lCounts,np); - for(i = 0; i < np; i++) - { - if(self->lCounts[i] < low) - { + + np = getMesureNP(self, twoTheta); + GetScanCounts(self->pScanner, self->lCounts, np); + for (i = 0; i < np; i++) { + if (self->lCounts[i] < low) { low = self->lCounts[i]; } - if(self->lCounts[i] > high) - { + if (self->lCounts[i] > high) { high = self->lCounts[i]; } } /* - I am using the weakest point here as a rough estimate of - the background - */ - if(high - 2 * low > self->weakThreshold) - { + I am using the weakest point here as a rough estimate of + the background + */ + if (high - 2 * low > self->weakThreshold) { return 0; - } - else - { + } else { return 1; } } + /*-----------------------------------------------------------------------*/ -static int PerformPSDScan(pMesure self, char *scanVar, float fStart, - float step, int np, float two_theta) +static int PerformPSDScan(pMesure self, char *scanVar, float fStart, + float step, int np, float two_theta) { int status; char pCommand[1024]; @@ -591,36 +558,31 @@ static int PerformPSDScan(pMesure self, char *scanVar, float fStart, float fPreset; /* - PSD scans are done by calling the routine Tcl procedure tricsscan with the - appropriate parameters. tricsscan does only omega scans! - */ - if(self->CountMode == eTimer) - { - strcpy(countMode,"timer"); + PSD scans are done by calling the routine Tcl procedure tricsscan with the + appropriate parameters. tricsscan does only omega scans! + */ + if (self->CountMode == eTimer) { + strcpy(countMode, "timer"); + } else { + strcpy(countMode, "monitor"); } - else - { - strcpy(countMode,"monitor"); + fPreset = GetFourCirclePreset(self->stepTable, (double) two_theta); + if (fPreset < .0) { + fPreset = self->fPreset; } - fPreset = GetFourCirclePreset(self->stepTable,(double)two_theta); - if(fPreset < .0){ - fPreset = self->fPreset; - } - snprintf(pCommand,1023,"tricsscan %f %f %d %s %f", fStart, step, np, - countMode,fPreset); + snprintf(pCommand, 1023, "tricsscan %f %f %d %s %f", fStart, step, np, + countMode, fPreset); pTcl = InterpGetTcl(pServ->pSics); - status = Tcl_Eval(pTcl,pCommand); - if(status != TCL_OK) - { + status = Tcl_Eval(pTcl, pCommand); + if (status != TCL_OK) { return 0; - } - else - { + } else { return 1; } } + /*------------------------------------------------------------------------*/ -static int ScanReflection(pMesure self, float twoTheta, SConnection *pCon) +static int ScanReflection(pMesure self, float twoTheta, SConnection * pCon) { float fStart, stepWidth, fPreset; int iRet, np; @@ -628,35 +590,32 @@ static int ScanReflection(pMesure self, float twoTheta, SConnection *pCon) char *scanVar = NULL; /* calculate scan start */ - iRet = MotorGetSoftPosition(self->pOmega,pCon,&fStart); - if(!iRet) - { - return iRet; + iRet = MotorGetSoftPosition(self->pOmega, pCon, &fStart); + if (!iRet) { + return iRet; } - scanVar = GetFourCircleScanVar(self->stepTable,(double)twoTheta); - if(strcmp(scanVar,"NOT FOUND") == 0) - { + scanVar = GetFourCircleScanVar(self->stepTable, (double) twoTheta); + if (strcmp(scanVar, "NOT FOUND") == 0) { free(scanVar); scanVar = strdup(self->pCOmega); stepWidth = self->fStep; } else { - stepWidth = GetFourCircleStep(self->stepTable,(double)twoTheta); + stepWidth = GetFourCircleStep(self->stepTable, (double) twoTheta); } - np = getMesureNP(self,(double)twoTheta); + np = getMesureNP(self, (double) twoTheta); - if(stepWidth != self->fStep) - { - snprintf(pBueffel,130,"Using stepwidth %f, %d points",stepWidth,np); - SCWrite(pCon,pBueffel,eWarning); + if (stepWidth != self->fStep) { + snprintf(pBueffel, 130, "Using stepwidth %f, %d points", stepWidth, + np); + SCWrite(pCon, pBueffel, eWarning); } - fStart -= (np/2)*stepWidth; + fStart -= (np / 2) * stepWidth; /* - special case: psd mode - */ - if(self->psd == 1) - { - iRet = PerformPSDScan(self,scanVar,fStart, stepWidth, np,twoTheta); + special case: psd mode + */ + if (self->psd == 1) { + iRet = PerformPSDScan(self, scanVar, fStart, stepWidth, np, twoTheta); free(scanVar); return iRet; } @@ -666,1220 +625,1068 @@ static int ScanReflection(pMesure self, float twoTheta, SConnection *pCon) TODO: (maybe) make this clearer and separate this into another subroutine Set the scan up - */ + */ ClearScanVar(self->pScanner); - AddScanVar(self->pScanner, pServ->pSics,pCon,self->pCOmega, - fStart, stepWidth); - snprintf(pBueffel,131,"Scanning om from %f with step %f", fStart, stepWidth); - SCWrite(pCon,pBueffel,eLog); + AddScanVar(self->pScanner, pServ->pSics, pCon, self->pCOmega, + fStart, stepWidth); + snprintf(pBueffel, 131, "Scanning om from %f with step %f", fStart, + stepWidth); + SCWrite(pCon, pBueffel, eLog); /* - Oksana does not want o2t scans to be tightly coupled, this is why we - cannot use the normal o2t scan variable. Instead we calculate new limits and - steps for 2 theta and use it as a second scan variable - */ - if(strstr(scanVar,"o2t") != NULL){ - iRet = MotorGetSoftPosition(self->p2Theta,pCon,&fStart); - if(!iRet) - { - return iRet; + Oksana does not want o2t scans to be tightly coupled, this is why we + cannot use the normal o2t scan variable. Instead we calculate new limits and + steps for 2 theta and use it as a second scan variable + */ + if (strstr(scanVar, "o2t") != NULL) { + iRet = MotorGetSoftPosition(self->p2Theta, pCon, &fStart); + if (!iRet) { + return iRet; } stepWidth *= 2.; - fStart -= (np/2.)*stepWidth; - AddScanVar(self->pScanner, pServ->pSics,pCon,self->pC2Theta, - fStart, stepWidth); - snprintf(pBueffel,131,"Scanning 2theta from %f with step %f", fStart, stepWidth); - SCWrite(pCon,pBueffel,eLog); + fStart -= (np / 2.) * stepWidth; + AddScanVar(self->pScanner, pServ->pSics, pCon, self->pC2Theta, + fStart, stepWidth); + snprintf(pBueffel, 131, "Scanning 2theta from %f with step %f", fStart, + stepWidth); + SCWrite(pCon, pBueffel, eLog); } /* - as np can change, we have to reallocate enough space - */ - if(self->lCounts != NULL){ + as np can change, we have to reallocate enough space + */ + if (self->lCounts != NULL) { free(self->lCounts); - self->lCounts = (long *)malloc(np*sizeof(long)); - if(self->lCounts == NULL){ - SCWrite(pCon,"ERROR: out of memory for scan scan data",eError); - SCSetInterrupt(pCon,eAbortScan); + self->lCounts = (long *) malloc(np * sizeof(long)); + if (self->lCounts == NULL) { + SCWrite(pCon, "ERROR: out of memory for scan scan data", eError); + SCSetInterrupt(pCon, eAbortScan); return 0; } - memset(self->lCounts,0,np*sizeof(long)); + memset(self->lCounts, 0, np * sizeof(long)); } - /* - * determine preset - */ - fPreset = GetFourCirclePreset(self->stepTable,(double)twoTheta); - if(fPreset < .0){ - fPreset = self->fPreset; + /* + * determine preset + */ + fPreset = GetFourCirclePreset(self->stepTable, (double) twoTheta); + if (fPreset < .0) { + fPreset = self->fPreset; } /* do the scan */ free(scanVar); - if(self->iCompact) - { + if (self->iCompact) { self->pScanner->CollectScanData = CompactScanData; } - if(self->fastScan >= 1) - { + if (self->fastScan >= 1) { self->pScanner->ScanDrive = ScanFastDrive; } - iRet = SilentScan(self->pScanner,np,self->CountMode, - fPreset,pServ->pSics,pCon); - if(weakScan(self,twoTheta)) - { + iRet = SilentScan(self->pScanner, np, self->CountMode, + fPreset, pServ->pSics, pCon); + if (weakScan(self, twoTheta)) { /* - look for interrupts before restarting scan - */ - if(iRet == 0) - { - if(SCGetInterrupt(pCon) >= eAbortBatch) - { - return 0; - } - else - { - SCSetInterrupt(pCon,eContinue); + look for interrupts before restarting scan + */ + if (iRet == 0) { + if (SCGetInterrupt(pCon) >= eAbortBatch) { + return 0; + } else { + SCSetInterrupt(pCon, eContinue); } } /* - redo scan with preset * 5 - */ - SCWrite(pCon,"Remeasuring weak reflection",eLog); - iRet = SilentScan(self->pScanner,np,self->CountMode, - fPreset*5.,pServ->pSics,pCon); + redo scan with preset * 5 + */ + SCWrite(pCon, "Remeasuring weak reflection", eLog); + iRet = SilentScan(self->pScanner, np, self->CountMode, + fPreset * 5., pServ->pSics, pCon); } ResetScanFunctions(self->pScanner); return iRet; } + /*------------------------------------------------------------------------*/ - int MesureGenReflection(pMesure self, float fHKL[3], float fSet[4], - SConnection *pCon) - { - - int iRet, i; - char pBueffel[132]; - - assert(self); - - iRet = DriveToReflection(self,fSet,pCon); - if(!iRet) - { - return iRet; - } +int MesureGenReflection(pMesure self, float fHKL[3], float fSet[4], + SConnection * pCon) +{ - iRet = ScanReflection(self,fSet[0],pCon); + int iRet, i; + char pBueffel[132]; - return iRet; - } -/*--------------------------------------------------------------------------*/ - int MesureStart(pMesure self, SConnection *pCon) - { - char pFilename[512], pRoot[512]; - char pBueffel[1024]; - char pBuff[132]; - int iYear, iNum, iTaus; - float fVal, fUB[9]; - pSicsVariable pVar = NULL; - char *pFile = NULL, *pPtr; - float zero, pos; - pMotor pMot = NULL; - FILE *temp = NULL; - - assert(self); - assert(pCon); - - /* close open files if so */ - if(self->fRefl != NULL) - { - MesureClose(self); - } - - /* create filename root */ - pFile = makeFilename(pServ->pSics,pCon); - if(!pFile) - { - return 0; - } - pPtr = strrchr(pFile,(int)'.'); - pPtr++; - *pPtr = '\0'; - self->pCurrentFile = strdup(pFile); - free(pFile); - strncpy(pRoot,self->pCurrentFile,511); - - /* do the logfile */ - strcpy(pFilename,pRoot); - strcat(pFilename,"log"); - /* TODO - self->iLogFile = SCAddLogFile(pCon,pFilename); - */ - self->pCon = pCon; + assert(self); - /* - we do not need reflection files when doing a PSD scan - */ - if(self->psd == 1) - { - sprintf(pBueffel,"Logging to %s.log", pRoot); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - - /* open the reflection file */ - sprintf(pBueffel,"Writing to %s.log, .ccl, .rfl",pRoot); - SCWrite(pCon,pBueffel,eValue); - strcpy(pFilename,pRoot); - strcat(pFilename,"ccl"); - self->fRefl = fopen(pFilename,"w"); - if(!self->fRefl) - { - sprintf(pBueffel,"ERROR: SERIOUS TROUBLE: cannot open %s!", - pFilename); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,eAbortBatch); - return 0; - } - temp = fopen(self->headerTemplate,"r"); - if(temp == NULL) - { - SCWrite(pCon,"ERROR: failed to open header template",eError); - } - if(temp != NULL && self->fRefl != NULL) - { - WriteTemplate(self->fRefl, temp, pFilename, NULL, - pCon, pServ->pSics); - fclose(temp); - } - - - - /* open hkl-data file */ - strcpy(pFilename,pRoot); - strcat(pFilename,"rfl"); - self->fHKL = fopen(pFilename,"w"); - if(!self->fHKL) - { - sprintf(pBueffel,"ERROR: SERIOUS TROUBLE: cannot open %s!", - pFilename); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,eAbortBatch); - return 0; - } - fputs(pFilename,self->fHKL); - fputs("\n",self->fHKL); - - /* write some header data */ - SNXFormatTime(pBueffel,1024); - fprintf(self->fHKL,"filetime = %s\n",pBueffel); - GetLambda(self->pCryst,&fVal); - fprintf(self->fHKL,"lambda = %f Angstroem\n",fVal); - GetUB(self->pCryst,fUB); - fprintf(self->fHKL, - "UB = %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f\n", - fUB[0], fUB[1],fUB[2],fUB[3],fUB[4],fUB[5],fUB[6],fUB[7],fUB[8]); - - /* write sample & user info */ - strcpy(pBueffel,"CCL, Instr=TRICS, "); - pVar = FindVariable(pServ->pSics,"sample"); - if(pVar) - { - fprintf(self->fHKL,"sample = %s\n",pVar->text); - sprintf(pBuff,"sample = %s, ",pVar->text); - strcat(pBueffel,pBuff); - } - pVar = FindVariable(pServ->pSics,"user"); - if(pVar) - { - fprintf(self->fHKL,"user = %s \n",pVar->text); - sprintf(pBuff,"user = %s",pVar->text); - strcat(pBueffel,pBuff); - } - return 1; + iRet = DriveToReflection(self, fSet, pCon); + if (!iRet) { + return iRet; } + + iRet = ScanReflection(self, fSet[0], pCon); + + return iRet; +} + +/*--------------------------------------------------------------------------*/ +int MesureStart(pMesure self, SConnection * pCon) +{ + char pFilename[512], pRoot[512]; + char pBueffel[1024]; + char pBuff[132]; + int iYear, iNum, iTaus; + float fVal, fUB[9]; + pSicsVariable pVar = NULL; + char *pFile = NULL, *pPtr; + float zero, pos; + pMotor pMot = NULL; + FILE *temp = NULL; + + assert(self); + assert(pCon); + + /* close open files if so */ + if (self->fRefl != NULL) { + MesureClose(self); + } + + /* create filename root */ + pFile = makeFilename(pServ->pSics, pCon); + if (!pFile) { + return 0; + } + pPtr = strrchr(pFile, (int) '.'); + pPtr++; + *pPtr = '\0'; + self->pCurrentFile = strdup(pFile); + free(pFile); + strncpy(pRoot, self->pCurrentFile, 511); + + /* do the logfile */ + strcpy(pFilename, pRoot); + strcat(pFilename, "log"); + /* TODO + self->iLogFile = SCAddLogFile(pCon,pFilename); + */ + self->pCon = pCon; + + /* + we do not need reflection files when doing a PSD scan + */ + if (self->psd == 1) { + sprintf(pBueffel, "Logging to %s.log", pRoot); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + + /* open the reflection file */ + sprintf(pBueffel, "Writing to %s.log, .ccl, .rfl", pRoot); + SCWrite(pCon, pBueffel, eValue); + strcpy(pFilename, pRoot); + strcat(pFilename, "ccl"); + self->fRefl = fopen(pFilename, "w"); + if (!self->fRefl) { + sprintf(pBueffel, "ERROR: SERIOUS TROUBLE: cannot open %s!", + pFilename); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, eAbortBatch); + return 0; + } + temp = fopen(self->headerTemplate, "r"); + if (temp == NULL) { + SCWrite(pCon, "ERROR: failed to open header template", eError); + } + if (temp != NULL && self->fRefl != NULL) { + WriteTemplate(self->fRefl, temp, pFilename, NULL, pCon, pServ->pSics); + fclose(temp); + } + + + + /* open hkl-data file */ + strcpy(pFilename, pRoot); + strcat(pFilename, "rfl"); + self->fHKL = fopen(pFilename, "w"); + if (!self->fHKL) { + sprintf(pBueffel, "ERROR: SERIOUS TROUBLE: cannot open %s!", + pFilename); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, eAbortBatch); + return 0; + } + fputs(pFilename, self->fHKL); + fputs("\n", self->fHKL); + + /* write some header data */ + SNXFormatTime(pBueffel, 1024); + fprintf(self->fHKL, "filetime = %s\n", pBueffel); + GetLambda(self->pCryst, &fVal); + fprintf(self->fHKL, "lambda = %f Angstroem\n", fVal); + GetUB(self->pCryst, fUB); + fprintf(self->fHKL, + "UB = %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f %7.6f\n", + fUB[0], fUB[1], fUB[2], fUB[3], fUB[4], fUB[5], fUB[6], fUB[7], + fUB[8]); + + /* write sample & user info */ + strcpy(pBueffel, "CCL, Instr=TRICS, "); + pVar = FindVariable(pServ->pSics, "sample"); + if (pVar) { + fprintf(self->fHKL, "sample = %s\n", pVar->text); + sprintf(pBuff, "sample = %s, ", pVar->text); + strcat(pBueffel, pBuff); + } + pVar = FindVariable(pServ->pSics, "user"); + if (pVar) { + fprintf(self->fHKL, "user = %s \n", pVar->text); + sprintf(pBuff, "user = %s", pVar->text); + strcat(pBueffel, pBuff); + } + return 1; +} + /*---------------------------------------------------------------------------*/ - int MesureReopen(pMesure self, char *fileroot, SConnection *pCon) - { - char pBueffel[1024]; - char pFile[512]; - - assert(self); - assert(fileroot); - assert(pCon); +int MesureReopen(pMesure self, char *fileroot, SConnection * pCon) +{ + char pBueffel[1024]; + char pFile[512]; - /* close pending files */ - if(self->fRefl != NULL) - { - MesureClose(self); + assert(self); + assert(fileroot); + assert(pCon); + + /* close pending files */ + if (self->fRefl != NULL) { + MesureClose(self); + } + + /* log file */ + strcpy(pFile, self->pFileRoot); + strcat(pFile, "/"); + strcat(pFile, fileroot); + strcat(pFile, ".log"); + /* TODO: + self->iLogFile = SCAddLogFile(pCon,pFile); + */ + self->pCon = pCon; + + /* + No reopening of reflection files in psd mode + */ + if (self->psd == 1) { + return 1; + } + + /* check if this is possible */ + strcpy(pFile, self->pFileRoot); + strcat(pFile, "/"); + strcat(pFile, fileroot); + strcat(pFile, ".col"); + self->fRefl = fopen(pFile, "r"); + if (!self->fRefl) { + sprintf(pBueffel, "ERROR: there is no such measurement at %s", + fileroot); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fclose(self->fRefl); + + /* well seems to exist, open for append */ + self->fRefl = fopen(pFile, "a"); + + /* rfl file */ + strcpy(pFile, self->pFileRoot); + strcat(pFile, "/"); + strcat(pFile, fileroot); + self->pCurrentFile = strdup(pFile); + strcat(pFile, ".rfl"); + self->fHKL = fopen(pFile, "a"); + + + return 1; +} + +/*------------------------------------------------------------------------*/ +int MesureClose(pMesure self) +{ + assert(self); + + /* TODO + * SCDelLogFile(self->pCon,self->iLogFile); + */ + if (self->psd == 1) { + self->pCon = NULL; + self->iLogFile = -1; + if (self->pCurrentFile) + free(self->pCurrentFile); + return 1; + } + + if (self->fRefl) { + fclose(self->fRefl); + self->fRefl = NULL; + } + if (self->fHKL) { + fclose(self->fHKL); + self->fHKL = NULL; + } + self->pCon = NULL; + self->iLogFile = -1; + if (self->pCurrentFile) + free(self->pCurrentFile); + + return 1; +} + +/*---------------------------------------------------------------------------*/ +static double getProtonAverage(pMesure self) +{ + int np, i; + long *lData = NULL, lSum = 0; + + np = GetScanNP(self->pScanner); + lData = (long *) malloc((np + 1) * sizeof(long)); + if (lData == NULL || np == 0) { + return 0.; + } + memset(lData, 0, (np + 1) * sizeof(long)); + GetScanMonitor(self->pScanner, 2, lData, np); + for (i = 0; i < np; i++) { + lSum += lData[i]; + } + return (double) lSum / (double) np; +} + +/*---------------------------------------------------------------------------*/ +static int WriteReflection(pMesure self, float fHKL[3], SConnection * pCon) +{ + float fSum, fSigma, fSet[4], fTemp, fPreset, fStep; + double prot; + static float fMax = 10.; + int iRet, i, ii, iLF, iNP; + char pBueffel[512], pNum[10], pTime[132]; + pEVControl pEva = NULL; + pDummy pPtr = NULL; + pIDrivable pDriv = NULL; + + assert(self); + assert(pCon); + memset(pTime, 0, 132 * sizeof(char)); + +#ifdef MESSDEBUG + self->np = 90; + fMax += 10; + SimScan(self->pScanner, 14., 0.5, fMax); + if (fMax > 1000) { + fMax = 10.; + } +#endif + + /* + no writing in PSD mode + */ + if (self->psd == 1) { + return 1; + } + + /* get necessary data */ + fSum = 0.; + fSigma = 0.; + iRet = ScanIntegrate(self->pScanner, &fSum, &fSigma); + if (iRet != 1) { + switch (iRet) { + case INTEGLEFT: + sprintf(pBueffel, + "WARNING: integration failed --> no left side to: %f %f %f", + fHKL[0], fHKL[1], fHKL[2]); + break; + case INTEGRIGHT: + sprintf(pBueffel, + "WARNING: integration failed -->no right side to: %f %f %f", + fHKL[0], fHKL[1], fHKL[2]); + break; + case INTEGNOPEAK: + sprintf(pBueffel, + "WARNING: integration failed -->no peak found: %f %f %f", + fHKL[0], fHKL[1], fHKL[2]); + break; + case INTEGFUNNYBACK: + sprintf(pBueffel, + "WARNING: integration problem, asymmetric background: %f %f %f", + fHKL[0], fHKL[1], fHKL[2]); + break; } + SCWrite(pCon, pBueffel, eWarning); + } + iNP = GetScanNP(self->pScanner); + GetScanCounts(self->pScanner, self->lCounts, iNP); - /* log file */ - strcpy(pFile,self->pFileRoot); - strcat(pFile,"/"); - strcat(pFile,fileroot); - strcat(pFile,".log"); - /* TODO: - self->iLogFile = SCAddLogFile(pCon,pFile); - */ - self->pCon = pCon; + /* write it */ + if (self->fRefl) { + fprintf(self->fRefl, + "%4d %7.3f %7.3f %7.3f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", + self->iCount, fHKL[0], fHKL[1], fHKL[2], self->fPosition[0], + self->fPosition[1], self->fPosition[2], self->fPosition[3], + fSum, fSigma); + } + if (self->fHKL) { + fprintf(self->fHKL, + "%5d %6.2f %6.2f %6.2f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", + self->iCount, fHKL[0], fHKL[1], fHKL[2], self->fPosition[0], + self->fPosition[1], self->fPosition[2], self->fPosition[3], + fSum, fSigma); + } + sprintf(pBueffel, + "%5d %6.2f %6.2f %6.2f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", + self->iCount, fHKL[0], fHKL[1], fHKL[2], self->fPosition[0], + self->fPosition[1], self->fPosition[2], self->fPosition[3], fSum, + fSigma); + SCWrite(pCon, pBueffel, eLog); - /* - No reopening of reflection files in psd mode - */ - if(self->psd == 1) - { - return 1; + /* get temperature */ + fTemp = -777.77; + pEva = (pEVControl) FindCommandData(pServ->pSics, "temperature", + "Environment Controller"); + if (pEva == NULL) { + pPtr = (pDummy) FindCommandData(pServ->pSics, "temperature", + "RemObject"); + if (pPtr != NULL) { + pDriv = pPtr->pDescriptor->GetInterface(pPtr, DRIVEID); + if (pDriv != NULL) { + fTemp = pDriv->GetValue(pPtr, pCon); + } } - - /* check if this is possible */ - strcpy(pFile,self->pFileRoot); - strcat(pFile,"/"); - strcat(pFile,fileroot); - strcat(pFile,".col"); - self->fRefl = fopen(pFile,"r"); - if(!self->fRefl) - { - sprintf(pBueffel,"ERROR: there is no such measurement at %s",fileroot); - SCWrite(pCon,pBueffel,eError); + } else { + iRet = EVCGetPos(pEva, pCon, &fTemp); + } + + /* write profile */ + if (self->fRefl) { + /* collect data */ + SNXFormatTime(pBueffel, 512); + GetScanVarStep(self->pScanner, 0, &fStep); + fPreset = GetScanPreset(self->pScanner); + prot = getProtonAverage(self); + fprintf(self->fRefl, "%3d %7.4f %9.0f %7.3f %12f %s\n", iNP, fStep, + fPreset, fTemp, prot, pBueffel); + for (i = 0; i < iNP; i++) { + for (ii = 0; ii < 10 && i < iNP; ii++) { + fprintf(self->fRefl, " %7ld", self->lCounts[i]); + iLF = 1; + i++; + } + fprintf(self->fRefl, "\n"); + i--; + iLF = 0; + } + if (iLF) { + fprintf(self->fRefl, "\n"); + } + fflush(self->fRefl); + } + + /* write data if compact output */ + if (self->iCompact == 1) { + strcpy(pTime, pBueffel); + sprintf(pBueffel, "%3d%8.4f%10.0f%8.3f %s\n", iNP, fStep, + fPreset, fTemp, pTime); + SCWrite(pCon, pBueffel, eValue); + pBueffel[0] = '\0'; + for (i = 0; i < iNP; i++) { + for (ii = 0; ii < 10 && i < iNP; ii++) { + sprintf(pNum, " %6ld", self->lCounts[i]); + strcat(pBueffel, pNum); + iLF = 1; + i++; + } + SCWrite(pCon, pBueffel, eValue); + pBueffel[0] = '\0'; + i--; + iLF = 0; + } + if (iLF) { + SCWrite(pCon, pBueffel, eValue); + } + } + return 1; +} + + /*---------------------------------------------------------------------*/ +static FILE *openListFile(char *pName) +{ + FILE *fd = NULL; + pDynString filename = NULL; + filename = findBatchFile(pServ->pSics, pName); + if (filename != NULL) { + fd = fopen(GetCharArray(filename), "r"); + DeleteDynString(filename); + } else { + fd = fopen(pName, "r"); + } + return fd; +} + +/*------------------------------------------------------------------------*/ +int MesureFile(pMesure self, char *pFile, int iSkip, SConnection * pCon) +{ + FILE *fd = NULL; + char pBueffel[512], pTime[132], pError[256]; + int i, iRet; + float fHKL[3], fPsi = .0; + + assert(self); + assert(pCon); + + /* well before doing a thing, open the list file */ + fd = openListFile(pFile); + if (!fd) { + sprintf(pBueffel, "ERROR: reflection file %s NOT found!", pFile); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* check that files are open, if not open */ + if (self->fRefl == NULL) { + MesureStart(self, pCon); + } + + /* make a mark */ + SNXFormatTime(pTime, 131); + sprintf(pBueffel, "Starting at list %s at %s", pFile, pTime); + SCWrite(pCon, pBueffel, eLog); + + /* skippy! */ + for (i = 0; i < iSkip; i++) { + fgets(pBueffel, 510, fd); + } + self->iCount = iSkip; + + if (self->psiMode > 0) { + SCWrite(pCon, "WARNING: measuring in psi mode", eWarning); + } + + /* loop through space and measure! */ + while (fgets(pBueffel, 510, fd) != NULL) { + for (i = 0; i < 3; i++) + fHKL[i] = 0.; + if (self->psiMode > 0) { + iRet = sscanf(pBueffel, "%f%f%f%f", + &fHKL[0], &fHKL[1], &fHKL[2], &fPsi); + if (iRet != 4) { + snprintf(pError, 255, "WARNING: skipping bad line %s", pBueffel); + SCWrite(pCon, pError, eWarning); + continue; + } + } else { + iRet = sscanf(pBueffel, "%f%f%f", &fHKL[0], &fHKL[1], &fHKL[2]); + if (iRet != 3) { + snprintf(pError, 255, "WARNING: skipping bad line %s", pBueffel); + SCWrite(pCon, pError, eWarning); + continue; + } + } + self->iCount++; + iRet = MesureReflection(self, fHKL, fPsi, pCon); + if (iRet == 0) { + if (SCGetInterrupt(pCon) >= eAbortBatch) { + return 0; + } else { + SCSetInterrupt(pCon, eContinue); + continue; + } + } + WriteReflection(self, fHKL, pCon); + } + + /* we are done */ + SNXFormatTime(pTime, 131); + sprintf(pBueffel, "Finishing list %s at %s", pFile, pTime); + SCWrite(pCon, pBueffel, eLog); + + fclose(fd); + return 1; +} + +/*------------------------------------------------------------------------*/ +int TestFile(pMesure self, char *pFile, SConnection * pCon) +{ + FILE *fd = NULL; + char pBueffel[512], pError[256]; + int i, iRet; + float fHKL[3], fSet[4], fPsi = .0; + int count = 0, good = 0; + + assert(self); + assert(pCon); + + /* well before doing a thing, open the list file */ + fd = openListFile(pFile); + if (!fd) { + sprintf(pBueffel, "ERROR: reflection file %s NOT found!", pFile); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + if (self->psiMode > 0) { + SCWrite(pCon, "WARNING: measuring in psi mode", eWarning); + } + + /* loop through space and test! */ + while (fgets(pBueffel, 510, fd) != NULL) { + for (i = 0; i < 3; i++) + fHKL[i] = 0.; + if (self->psiMode > 0) { + iRet = sscanf(pBueffel, "%f%f%f%f", + &fHKL[0], &fHKL[1], &fHKL[2], &fPsi); + if (iRet != 4) { + snprintf(pError, 255, "WARNING: skipping bad line %s", pBueffel); + SCWrite(pCon, pError, eWarning); + continue; + } + } else { + iRet = sscanf(pBueffel, "%f%f%f", &fHKL[0], &fHKL[1], &fHKL[2]); + if (iRet != 3) { + snprintf(pError, 255, "WARNING: skipping bad line %s", pBueffel); + SCWrite(pCon, pError, eWarning); + continue; + } + } + count++; + iRet = MesureCalculateSettings(self, fHKL, fSet, fPsi, pCon); + if (iRet == 1) { + good++; + } + } + fclose(fd); + snprintf(pBueffel, 511, + "Of %d reflections on file, %d are good and %d are rotten", + count, good, count - good); + SCWrite(pCon, pBueffel, eValue); + return 1; +} + +/*------------------------------------------------------------------------*/ +int MesureGenFile(pMesure self, char *pFile, int iSkip, SConnection * pCon) +{ + FILE *fd = NULL; + char pBueffel[512], pTime[132]; + int i, iRet, iH, iK, iL; + float fHKL[3], fSet[4]; + char pDum[4]; + + assert(self); + assert(pCon); + + /* well before doing a thing, open the list file */ + fd = openListFile(pFile); + if (!fd) { + sprintf(pBueffel, "ERROR: reflection file %s NOT found!", pFile); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* check that files are open, if not open */ + if (self->fRefl == NULL) { + MesureStart(self, pCon); + } + + /* make a mark */ + SNXFormatTime(pTime, 131); + sprintf(pBueffel, "Starting at list %s at %s", pFile, pTime); + SCWrite(pCon, pBueffel, eLog); + + /* skippy! */ + for (i = 0; i < iSkip; i++) { + fgets(pBueffel, 510, fd); + } + self->iCount = iSkip; + + + /* loop through space and measure! */ + while (fgets(pBueffel, 510, fd) != NULL) { + for (i = 0; i < 3; i++) + fHKL[i] = 0.; + for (i = 0; i < 4; i++) + fSet[i] = 0.; + iRet = sscanf(pBueffel, "%4d%4d%4d%s%f%f%f%f", + &iH, &iK, &iL, pDum, + &fSet[0], &fSet[1], &fSet[2], &fSet[3]); + fHKL[0] = (float) iH; + fHKL[1] = (float) iK; + fHKL[2] = (float) iL; + self->iCount++; + iRet = MesureGenReflection(self, fHKL, fSet, pCon); + if (iRet == 0) { + if (SCGetInterrupt(pCon) >= eAbortBatch) { + return 0; + } else { + SCSetInterrupt(pCon, eContinue); + continue; + } + } + WriteReflection(self, fHKL, pCon); + } + + /* we are done */ + SNXFormatTime(pTime, 131); + sprintf(pBueffel, "Finishing list %s at %s", pFile, pTime); + SCWrite(pCon, pBueffel, eLog); + + fclose(fd); + return 1; +} + +/*--------------------------------------------------------------------------*/ +int MesureSetPar(pMesure self, char *name, float fVal) +{ + if (strcmp(name, "np") == 0) { +#ifndef MESSDEBUG + self->np = (int) fVal; + if (self->lCounts) + free(self->lCounts); + self->lCounts = (long *) malloc(self->np * sizeof(long)); + if (!self->lCounts) { return 0; } - fclose(self->fRefl); - - /* well seems to exist, open for append */ - self->fRefl = fopen(pFile,"a"); - - /* rfl file */ - strcpy(pFile,self->pFileRoot); - strcat(pFile,"/"); - strcat(pFile,fileroot); - self->pCurrentFile = strdup(pFile); - strcat(pFile,".rfl"); - self->fHKL = fopen(pFile,"a"); - - - return 1; - } -/*------------------------------------------------------------------------*/ - int MesureClose(pMesure self) - { - assert(self); - - /* TODO - * SCDelLogFile(self->pCon,self->iLogFile); - */ - if(self->psd == 1) - { - self->pCon = NULL; - self->iLogFile = -1; - if(self->pCurrentFile) - free(self->pCurrentFile); - return 1; - } +#else - if(self->fRefl) - { - fclose(self->fRefl); - self->fRefl = NULL; - } - if(self->fHKL) - { - fclose(self->fHKL); - self->fHKL = NULL; - } - self->pCon = NULL; - self->iLogFile = -1; - if(self->pCurrentFile) - free(self->pCurrentFile); - - return 1; - } -/*---------------------------------------------------------------------------*/ -static double getProtonAverage(pMesure self){ - int np, i; - long *lData = NULL, lSum = 0; - - np = GetScanNP(self->pScanner); - lData = (long *)malloc((np+1)*sizeof(long)); - if(lData == NULL || np == 0){ - return 0.; - } - memset(lData,0,(np+1)*sizeof(long)); - GetScanMonitor(self->pScanner,2,lData, np); - for(i = 0; i < np; i++){ - lSum += lData[i]; - } - return (double)lSum/(double)np; -} -/*---------------------------------------------------------------------------*/ - static int WriteReflection(pMesure self, float fHKL[3],SConnection *pCon) - { - float fSum, fSigma, fSet[4], fTemp, fPreset, fStep; - double prot; - static float fMax = 10.; - int iRet, i,ii, iLF, iNP; - char pBueffel[512], pNum[10], pTime[132]; - pEVControl pEva = NULL; - pDummy pPtr = NULL; - pIDrivable pDriv = NULL; - - assert(self); - assert(pCon); - memset(pTime,0,132*sizeof(char)); - -#ifdef MESSDEBUG - self->np = 90; - fMax += 10; - SimScan(self->pScanner,14.,0.5,fMax); - if(fMax > 1000) - { - fMax = 10.; - } #endif - - /* - no writing in PSD mode - */ - if(self->psd == 1) - { - return 1; - } - - /* get necessary data */ - fSum = 0.; - fSigma = 0.; - iRet = ScanIntegrate(self->pScanner,&fSum, &fSigma); - if(iRet != 1) - { - switch(iRet) - { - case INTEGLEFT: - sprintf(pBueffel, - "WARNING: integration failed --> no left side to: %f %f %f", - fHKL[0], fHKL[1],fHKL[2]); - break; - case INTEGRIGHT: - sprintf(pBueffel, - "WARNING: integration failed -->no right side to: %f %f %f", - fHKL[0], fHKL[1],fHKL[2]); - break; - case INTEGNOPEAK: - sprintf(pBueffel, - "WARNING: integration failed -->no peak found: %f %f %f", - fHKL[0], fHKL[1],fHKL[2]); - break; - case INTEGFUNNYBACK: - sprintf(pBueffel, - "WARNING: integration problem, asymmetric background: %f %f %f", - fHKL[0], fHKL[1],fHKL[2]); - break; - } - SCWrite(pCon,pBueffel,eWarning); - } - iNP = GetScanNP(self->pScanner); - GetScanCounts(self->pScanner,self->lCounts,iNP); - - /* write it */ - if(self->fRefl) - { - fprintf(self->fRefl,"%4d %7.3f %7.3f %7.3f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", - self->iCount, fHKL[0],fHKL[1],fHKL[2], - self->fPosition[0], self->fPosition[1], - self->fPosition[2],self->fPosition[3], - fSum,fSigma); - } - if(self->fHKL) - { - fprintf(self->fHKL,"%5d %6.2f %6.2f %6.2f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", - self->iCount, fHKL[0],fHKL[1],fHKL[2], - self->fPosition[0], self->fPosition[1], - self->fPosition[2],self->fPosition[3], - fSum,fSigma); - } - sprintf(pBueffel,"%5d %6.2f %6.2f %6.2f %7.2f %7.2f %7.2f %7.2f %7.0f %7.2f\n", - self->iCount, fHKL[0],fHKL[1],fHKL[2], - self->fPosition[0], self->fPosition[1], - self->fPosition[2],self->fPosition[3], - fSum,fSigma); - SCWrite(pCon,pBueffel,eLog); - - /* get temperature */ - fTemp = -777.77; - pEva = (pEVControl)FindCommandData(pServ->pSics,"temperature", - "Environment Controller"); - if(pEva == NULL) - { - pPtr = (pDummy)FindCommandData(pServ->pSics,"temperature", - "RemObject"); - if(pPtr != NULL) - { - pDriv = pPtr->pDescriptor->GetInterface(pPtr,DRIVEID); - if(pDriv != NULL) - { - fTemp = pDriv->GetValue(pPtr,pCon); - } - } - } - else - { - iRet = EVCGetPos(pEva, pCon,&fTemp); - } - - /* write profile */ - if(self->fRefl) - { - /* collect data */ - SNXFormatTime(pBueffel,512); - GetScanVarStep(self->pScanner,0,&fStep); - fPreset = GetScanPreset(self->pScanner); - prot = getProtonAverage(self); - fprintf(self->fRefl,"%3d %7.4f %9.0f %7.3f %12f %s\n",iNP,fStep, - fPreset,fTemp,prot, pBueffel); - for(i = 0; i < iNP; i++) - { - for(ii = 0; ii < 10 && i < iNP; ii++) - { - fprintf(self->fRefl," %7ld",self->lCounts[i]); - iLF = 1; - i++; - } - fprintf(self->fRefl,"\n"); - i--; - iLF = 0; - } - if(iLF) - { - fprintf(self->fRefl,"\n"); - } - fflush(self->fRefl); - } - - /* write data if compact output */ - if(self->iCompact == 1) - { - strcpy(pTime,pBueffel); - sprintf(pBueffel,"%3d%8.4f%10.0f%8.3f %s\n",iNP,fStep, - fPreset,fTemp,pTime); - SCWrite(pCon,pBueffel,eValue); - pBueffel[0] = '\0'; - for(i = 0; i < iNP; i++) - { - for(ii = 0; ii < 10 && i < iNP; ii++) - { - sprintf(pNum," %6ld",self->lCounts[i]); - strcat(pBueffel,pNum); - iLF = 1; - i++; - } - SCWrite(pCon,pBueffel,eValue); - pBueffel[0] = '\0'; - i--; - iLF = 0; - } - if(iLF) - { - SCWrite(pCon,pBueffel,eValue); - } + return 1; + } else if (strcmp(name, "step") == 0) { + self->fStep = fVal; + return 1; + } else if (strcmp(name, "weakthreshold") == 0) { + self->weakThreshold = (long) nintf(fVal); + return 1; + } else if (strcmp(name, "preset") == 0) { + self->fPreset = fVal; + return 1; + } else if (strcmp(name, "countmode") == 0) { + if (fVal < 0.05) { + self->CountMode = eTimer; + } else { + self->CountMode = ePreset; } return 1; - } - /*---------------------------------------------------------------------*/ - static FILE *openListFile(char *pName){ - FILE *fd = NULL; - pDynString filename = NULL; - filename = findBatchFile(pServ->pSics,pName); - if(filename != NULL){ - fd = fopen(GetCharArray(filename),"r"); - DeleteDynString(filename); - } else { - fd = fopen(pName,"r"); - } - return fd; - } -/*------------------------------------------------------------------------*/ - int MesureFile(pMesure self, char *pFile, int iSkip, SConnection *pCon) - { - FILE *fd = NULL; - char pBueffel[512], pTime[132], pError[256]; - int i, iRet; - float fHKL[3], fPsi = .0; - - assert(self); - assert(pCon); - - /* well before doing a thing, open the list file */ - fd = openListFile(pFile); - if(!fd) - { - sprintf(pBueffel,"ERROR: reflection file %s NOT found!",pFile); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* check that files are open, if not open */ - if(self->fRefl == NULL) - { - MesureStart(self,pCon); - } - - /* make a mark */ - SNXFormatTime(pTime,131); - sprintf(pBueffel,"Starting at list %s at %s",pFile,pTime); - SCWrite(pCon,pBueffel,eLog); - - /* skippy! */ - for(i = 0; i < iSkip; i++) - { - fgets(pBueffel,510,fd); - } - self->iCount = iSkip; - - if(self->psiMode > 0){ - SCWrite(pCon,"WARNING: measuring in psi mode",eWarning); - } + } else if (strcmp(name, "compact") == 0) { + if (fVal >= 1.) { + self->iCompact = 1; + } else { + self->iCompact = 0; + } + return 1; + } else if (strcmp(name, "psd") == 0) { + if (fVal >= 1.) { + self->psd = 1; + } else { + self->psd = 0; + } + return 1; + } else if (strcmp(name, "weak") == 0) { + if (fVal >= 1.) { + self->weak = 1; + } else { + self->weak = 0; + } + return 1; + } else if (strcmp(name, "fastscan") == 0) { + if (fVal >= 1.) { + self->fastScan = 1; + } else { + self->fastScan = 0; + } + return 1; + } else if (strcmp(name, "psimode") == 0) { + if (fVal >= 1.) { + self->psiMode = 1; + } else { + self->psiMode = 0; + } + return 1; + } else { + return 0; + } +} - /* loop through space and measure! */ - while(fgets(pBueffel,510,fd) != NULL) - { - for(i = 0; i < 3;i++) - fHKL[i] = 0.; - if(self->psiMode > 0){ - iRet = sscanf(pBueffel,"%f%f%f%f", - &fHKL[0],&fHKL[1],&fHKL[2],&fPsi); - if(iRet != 4){ - snprintf(pError,255,"WARNING: skipping bad line %s",pBueffel); - SCWrite(pCon,pError,eWarning); - continue; - } - } else { - iRet = sscanf(pBueffel,"%f%f%f",&fHKL[0],&fHKL[1],&fHKL[2]); - if(iRet != 3){ - snprintf(pError,255,"WARNING: skipping bad line %s",pBueffel); - SCWrite(pCon,pError,eWarning); - continue; - } - } - self->iCount++; - iRet = MesureReflection(self,fHKL,fPsi,pCon); - if(iRet == 0) - { - if(SCGetInterrupt(pCon) >= eAbortBatch) - { - return 0; - } - else - { - SCSetInterrupt(pCon,eContinue); - continue; - } - } - WriteReflection(self,fHKL,pCon); - } - - /* we are done */ - SNXFormatTime(pTime,131); - sprintf(pBueffel,"Finishing list %s at %s",pFile,pTime); - SCWrite(pCon,pBueffel,eLog); - - fclose(fd); - return 1; - } -/*------------------------------------------------------------------------*/ - int TestFile(pMesure self, char *pFile, SConnection *pCon) - { - FILE *fd = NULL; - char pBueffel[512], pError[256]; - int i, iRet; - float fHKL[3], fSet[4], fPsi = .0; - int count = 0, good = 0; - - assert(self); - assert(pCon); - - /* well before doing a thing, open the list file */ - fd = openListFile(pFile); - if(!fd) - { - sprintf(pBueffel,"ERROR: reflection file %s NOT found!",pFile); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - if(self->psiMode > 0){ - SCWrite(pCon,"WARNING: measuring in psi mode",eWarning); - } - - /* loop through space and test! */ - while(fgets(pBueffel,510,fd) != NULL) - { - for(i = 0; i < 3;i++) - fHKL[i] = 0.; - if(self->psiMode > 0){ - iRet = sscanf(pBueffel,"%f%f%f%f", - &fHKL[0],&fHKL[1],&fHKL[2],&fPsi); - if(iRet != 4){ - snprintf(pError,255,"WARNING: skipping bad line %s",pBueffel); - SCWrite(pCon,pError,eWarning); - continue; - } - } else { - iRet = sscanf(pBueffel,"%f%f%f",&fHKL[0],&fHKL[1],&fHKL[2]); - if(iRet != 3){ - snprintf(pError,255,"WARNING: skipping bad line %s",pBueffel); - SCWrite(pCon,pError,eWarning); - continue; - } - } - count++; - iRet = MesureCalculateSettings(self,fHKL,fSet,fPsi,pCon); - if(iRet == 1) - { - good++; - } - } - fclose(fd); - snprintf(pBueffel,511,"Of %d reflections on file, %d are good and %d are rotten", - count,good,count-good); - SCWrite(pCon,pBueffel,eValue); - return 1; - } -/*------------------------------------------------------------------------*/ - int MesureGenFile(pMesure self, char *pFile, int iSkip, SConnection *pCon) - { - FILE *fd = NULL; - char pBueffel[512], pTime[132]; - int i, iRet, iH, iK, iL; - float fHKL[3], fSet[4]; - char pDum[4]; - - assert(self); - assert(pCon); - - /* well before doing a thing, open the list file */ - fd = openListFile(pFile); - if(!fd) - { - sprintf(pBueffel,"ERROR: reflection file %s NOT found!",pFile); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* check that files are open, if not open */ - if(self->fRefl == NULL) - { - MesureStart(self,pCon); - } - - /* make a mark */ - SNXFormatTime(pTime,131); - sprintf(pBueffel,"Starting at list %s at %s",pFile,pTime); - SCWrite(pCon,pBueffel,eLog); - - /* skippy! */ - for(i = 0; i < iSkip; i++) - { - fgets(pBueffel,510,fd); - } - self->iCount = iSkip; - - - /* loop through space and measure! */ - while(fgets(pBueffel,510,fd) != NULL) - { - for(i = 0; i < 3;i++) - fHKL[i] = 0.; - for(i = 0; i < 4;i++) - fSet[i] = 0.; - iRet = sscanf(pBueffel,"%4d%4d%4d%s%f%f%f%f", - &iH,&iK,&iL,pDum, - &fSet[0], &fSet[1],&fSet[2],&fSet[3]); - fHKL[0] = (float)iH; - fHKL[1] = (float)iK; - fHKL[2] = (float)iL; - self->iCount++; - iRet = MesureGenReflection(self,fHKL,fSet,pCon); - if(iRet == 0) - { - if(SCGetInterrupt(pCon) >= eAbortBatch) - { - return 0; - } - else - { - SCSetInterrupt(pCon,eContinue); - continue; - } - } - WriteReflection(self,fHKL,pCon); - } - - /* we are done */ - SNXFormatTime(pTime,131); - sprintf(pBueffel,"Finishing list %s at %s",pFile,pTime); - SCWrite(pCon,pBueffel,eLog); - - fclose(fd); - return 1; - } -/*--------------------------------------------------------------------------*/ - int MesureSetPar(pMesure self, char *name, float fVal) - { - if(strcmp(name,"np") == 0) - { -#ifndef MESSDEBUG - self->np = (int)fVal; - if(self->lCounts) - free(self->lCounts); - self->lCounts = (long *)malloc(self->np*sizeof(long)); - if(!self->lCounts) - { - return 0; - } -#else - -#endif - return 1; - } - else if(strcmp(name,"step") == 0) - { - self->fStep = fVal; - return 1; - } - else if(strcmp(name,"weakthreshold") == 0) - { - self->weakThreshold = (long)nintf(fVal); - return 1; - } - else if(strcmp(name,"preset") == 0) - { - self->fPreset = fVal; - return 1; - } - else if(strcmp(name,"countmode") == 0) - { - if(fVal < 0.05) - { - self->CountMode = eTimer; - } - else - { - self->CountMode = ePreset; - } - return 1; - } - else if(strcmp(name,"compact") == 0) - { - if(fVal >= 1.) - { - self->iCompact = 1; - } - else - { - self->iCompact = 0; - } - return 1; - } - else if(strcmp(name,"psd") == 0) - { - if(fVal >= 1.) - { - self->psd = 1; - } - else - { - self->psd = 0; - } - return 1; - } - else if(strcmp(name,"weak") == 0) - { - if(fVal >= 1.) - { - self->weak = 1; - } - else - { - self->weak = 0; - } - return 1; - } - else if(strcmp(name,"fastscan") == 0) - { - if(fVal >= 1.) - { - self->fastScan = 1; - } - else - { - self->fastScan = 0; - } - return 1; - } - else if(strcmp(name,"psimode") == 0) - { - if(fVal >= 1.) - { - self->psiMode = 1; - } - else - { - self->psiMode = 0; - } - return 1; - } - else - { - return 0; - } - } /*-------------------------------------------------------------------------*/ - int MesureGetPar(pMesure self, char *name, float *fVal) - { - if(strcmp(name,"np") == 0) - { - *fVal = self->np; - return 1; - } - else if(strcmp(name,"step") == 0) - { - *fVal = self->fStep; - return 1; - } - else if(strcmp(name,"weakthreshold") == 0) - { - *fVal = (float)self->weakThreshold; - return 1; - } - else if(strcmp(name,"preset") == 0) - { - *fVal = self->fPreset; - return 1; - } - else if(strcmp(name,"countmode") == 0) - { - if(self->CountMode == eTimer) - { - *fVal = 0.; - } - else - { - *fVal = 1.0; - } - return 1; - } - else if(strcmp(name,"compact") == 0) - { - *fVal = self->iCompact; - return 1; - } - else if(strcmp(name,"psd") == 0) - { - *fVal = self->psd; - return 1; - } - else if(strcmp(name,"fastscan") == 0) - { - *fVal = (float)self->fastScan; - return 1; - } - else if(strcmp(name,"weak") == 0) - { - *fVal = (float)self->weak; - return 1; - } - else if(strcmp(name,"psimode") == 0) - { - *fVal = self->psiMode; - return 1; - } - else - { - return 0; - } +int MesureGetPar(pMesure self, char *name, float *fVal) +{ + if (strcmp(name, "np") == 0) { + *fVal = self->np; + return 1; + } else if (strcmp(name, "step") == 0) { + *fVal = self->fStep; + return 1; + } else if (strcmp(name, "weakthreshold") == 0) { + *fVal = (float) self->weakThreshold; + return 1; + } else if (strcmp(name, "preset") == 0) { + *fVal = self->fPreset; + return 1; + } else if (strcmp(name, "countmode") == 0) { + if (self->CountMode == eTimer) { + *fVal = 0.; + } else { + *fVal = 1.0; + } + return 1; + } else if (strcmp(name, "compact") == 0) { + *fVal = self->iCompact; + return 1; + } else if (strcmp(name, "psd") == 0) { + *fVal = self->psd; + return 1; + } else if (strcmp(name, "fastscan") == 0) { + *fVal = (float) self->fastScan; + return 1; + } else if (strcmp(name, "weak") == 0) { + *fVal = (float) self->weak; + return 1; + } else if (strcmp(name, "psimode") == 0) { + *fVal = self->psiMode; + return 1; + } else { + return 0; } -/*---------------------------------------------------------------------------*/ - int MesureAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet, iSkip, err; - char pBueffel[1024]; - pMesure self = NULL; - double d; - float fVal, fHKL[3], start, end, step; - - self = (pMesure)pData; - assert(self); - assert(pCon); - - if(argc < 2) - { - sprintf(pBueffel,"ERROR: Insufficient arguments to %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +} - /* - catch table processing commands - */ - iRet = HandleFourCircleCommands(&self->stepTable,pCon,argc,argv,&err); - if(iRet == 1) - { - return err; - } - - strtolower(argv[1]); -/*------ start */ - if(strcmp(argv[1],"open") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = MesureStart(self,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } -/*----------- list*/ - else if(strcmp(argv[1],"list") == 0) - { - ListMesure(self,argv[0],pCon); - return 1; - } -/*------ file */ - else if(strcmp(argv[1],"file") == 0) - { - sprintf(pBueffel,"Currently writing to: %s",self->pCurrentFile); - SCWrite(pCon,pBueffel,eValue); - return 1; - } -/*------ nb */ - else if(strcmp(argv[1],"nb") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = SetNOR(self->pCryst,1); - if(!iRet) - { - SCWrite(pCon, - "ERROR: nu motor not configured at hkl, cannot do normal beam", - eError); - return 0; - } - SCSendOK(pCon); - return 1; - } -/*------ bi */ - else if(strcmp(argv[1],"bi") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = SetNOR(self->pCryst,0); - SCSendOK(pCon); - return 1; - } -/*--------- close */ - else if(strcmp(argv[1],"close") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - MesureClose(self); - return 1; - } -/*-------- reopen */ - else if(strcmp(argv[1],"reopen") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(argc < 3) - { - SCWrite(pCon,"ERROR: expected filename as parameter for reopen",eError); - return 0; - } - iRet = MesureReopen(self,argv[2],pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } -/*------- measure */ - else if(strcmp(argv[1],"measure") == 0) - { - iSkip = 0; - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(argc < 3) - { - SCWrite(pCon,"ERROR: expected list file name as parameter for measure ",eError); - return 0; - } - if(argc >= 4) - { - iRet = Tcl_GetInt(pSics->pTcl,argv[3],&iSkip); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected integer, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - iRet = MesureFile(self,argv[2],iSkip,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } -/*------- calc */ - else if(strcmp(argv[1],"calc") == 0) - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: expected list file name as parameter for measure ",eError); - return 0; - } - iRet = TestFile(self,argv[2],pCon); - return iRet; - } -/*------- genlist */ - else if(strcmp(argv[1],"genlist") == 0) - { - iSkip = 0; - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(argc < 3) - { - SCWrite(pCon,"ERROR: expected list file name as parameter for measure ",eError); - return 0; - } - if(argc >= 4) - { - iRet = Tcl_GetInt(pSics->pTcl,argv[3],&iSkip); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected integer, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - iRet = MesureGenFile(self,argv[2],iSkip,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } -/* ------ writereflection*/ - else if(strcmp(argv[1],"writereflection") == 0) - { - GetCurrentHKL(self->pCryst,fHKL); - WriteReflection(self,fHKL,pCon); - SCSendOK(pCon); - return 1; - } -/* ------ count mode */ - else if(strcmp(argv[1],"countmode") == 0) - { - if(argc > 2) /* set case */ - { - /* check rights */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: You are not aurhorised to do this!",eError); - return 0; - } - if(strcmp(argv[2],"timer") == 0) - { - fVal = 0.; - } - else if(strcmp(argv[2],"monitor") == 0) - { - fVal = 1.; - } - else - { - SCWrite(pCon,"ERROR: Invalid parameter for countmode",eError); - return 0; - } - MesureSetPar(self,"countmode",fVal); - SCSendOK(pCon); - return 1; - } - else /* get case */ - { - MesureGetPar(self,"countmode",&fVal); - if(fVal < 0.05) - { - sprintf(pBueffel,"%s.countmode = timer",argv[0]); - } - else - { - sprintf(pBueffel,"%s.countmode = monitor", argv[0]); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } -/*------ can be other pars */ - else - { - if(argc > 2) /* set case */ - { - /* check rights */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: You are not aurhorised to do this!",eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&d); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected numeric value for %s but got %s", - argv[1],argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fVal = (float)d; - - iRet = MesureSetPar(self,argv[1],fVal); - if(iRet) - { - SCSendOK(pCon); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: parameter %s not known",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - else /* get case */ - { - iRet = MesureGetPar(self,argv[1],&fVal); - if(!iRet) - { - sprintf(pBueffel,"ERROR: parameter %s not known",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - sprintf(pBueffel,"%s.%s = %f",argv[0],argv[1],fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } +/*---------------------------------------------------------------------------*/ +int MesureAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet, iSkip, err; + char pBueffel[1024]; + pMesure self = NULL; + double d; + float fVal, fHKL[3], start, end, step; + + self = (pMesure) pData; + assert(self); + assert(pCon); + + if (argc < 2) { + sprintf(pBueffel, "ERROR: Insufficient arguments to %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; } + + /* + catch table processing commands + */ + iRet = + HandleFourCircleCommands(&self->stepTable, pCon, argc, argv, &err); + if (iRet == 1) { + return err; + } + + strtolower(argv[1]); +/*------ start */ + if (strcmp(argv[1], "open") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + iRet = MesureStart(self, pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } +/*----------- list*/ + else if (strcmp(argv[1], "list") == 0) { + ListMesure(self, argv[0], pCon); + return 1; + } +/*------ file */ + else if (strcmp(argv[1], "file") == 0) { + sprintf(pBueffel, "Currently writing to: %s", self->pCurrentFile); + SCWrite(pCon, pBueffel, eValue); + return 1; + } +/*------ nb */ + else if (strcmp(argv[1], "nb") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + iRet = SetNOR(self->pCryst, 1); + if (!iRet) { + SCWrite(pCon, + "ERROR: nu motor not configured at hkl, cannot do normal beam", + eError); + return 0; + } + SCSendOK(pCon); + return 1; + } +/*------ bi */ + else if (strcmp(argv[1], "bi") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + iRet = SetNOR(self->pCryst, 0); + SCSendOK(pCon); + return 1; + } +/*--------- close */ + else if (strcmp(argv[1], "close") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + MesureClose(self); + return 1; + } +/*-------- reopen */ + else if (strcmp(argv[1], "reopen") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (argc < 3) { + SCWrite(pCon, "ERROR: expected filename as parameter for reopen", + eError); + return 0; + } + iRet = MesureReopen(self, argv[2], pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } +/*------- measure */ + else if (strcmp(argv[1], "measure") == 0) { + iSkip = 0; + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (argc < 3) { + SCWrite(pCon, + "ERROR: expected list file name as parameter for measure ", + eError); + return 0; + } + if (argc >= 4) { + iRet = Tcl_GetInt(pSics->pTcl, argv[3], &iSkip); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected integer, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + iRet = MesureFile(self, argv[2], iSkip, pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } +/*------- calc */ + else if (strcmp(argv[1], "calc") == 0) { + if (argc < 3) { + SCWrite(pCon, + "ERROR: expected list file name as parameter for measure ", + eError); + return 0; + } + iRet = TestFile(self, argv[2], pCon); + return iRet; + } +/*------- genlist */ + else if (strcmp(argv[1], "genlist") == 0) { + iSkip = 0; + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (argc < 3) { + SCWrite(pCon, + "ERROR: expected list file name as parameter for measure ", + eError); + return 0; + } + if (argc >= 4) { + iRet = Tcl_GetInt(pSics->pTcl, argv[3], &iSkip); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected integer, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + iRet = MesureGenFile(self, argv[2], iSkip, pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } +/* ------ writereflection*/ + else if (strcmp(argv[1], "writereflection") == 0) { + GetCurrentHKL(self->pCryst, fHKL); + WriteReflection(self, fHKL, pCon); + SCSendOK(pCon); + return 1; + } +/* ------ count mode */ + else if (strcmp(argv[1], "countmode") == 0) { + if (argc > 2) { /* set case */ + /* check rights */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: You are not aurhorised to do this!", eError); + return 0; + } + if (strcmp(argv[2], "timer") == 0) { + fVal = 0.; + } else if (strcmp(argv[2], "monitor") == 0) { + fVal = 1.; + } else { + SCWrite(pCon, "ERROR: Invalid parameter for countmode", eError); + return 0; + } + MesureSetPar(self, "countmode", fVal); + SCSendOK(pCon); + return 1; + } else { /* get case */ + + MesureGetPar(self, "countmode", &fVal); + if (fVal < 0.05) { + sprintf(pBueffel, "%s.countmode = timer", argv[0]); + } else { + sprintf(pBueffel, "%s.countmode = monitor", argv[0]); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } +/*------ can be other pars */ + else { + if (argc > 2) { /* set case */ + /* check rights */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: You are not aurhorised to do this!", eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &d); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: expected numeric value for %s but got %s", argv[1], + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fVal = (float) d; + + iRet = MesureSetPar(self, argv[1], fVal); + if (iRet) { + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "ERROR: parameter %s not known", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } else { /* get case */ + + iRet = MesureGetPar(self, argv[1], &fVal); + if (!iRet) { + sprintf(pBueffel, "ERROR: parameter %s not known", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + sprintf(pBueffel, "%s.%s = %f", argv[0], argv[1], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } +} diff --git a/mesure.h b/mesure.h index 295e3dca..cec6670f 100644 --- a/mesure.h +++ b/mesure.h @@ -13,30 +13,33 @@ #ifndef SICSMESURE #define SICSMESURE - typedef struct __Mesure *pMesure; +typedef struct __Mesure *pMesure; /*--------------------- live & death --------------------------------------*/ - pMesure CreateMesure(pHKL pCryst, pScanData pScanner, - pMotor pOmega, char *pom, - pMotor p2Theta, char *p2t, - char *pFileRoot,pDataNumber pDanu, char *headerTemplate); - void DeleteMesure(void *pData); +pMesure CreateMesure(pHKL pCryst, pScanData pScanner, + pMotor pOmega, char *pom, + pMotor p2Theta, char *p2t, + char *pFileRoot, pDataNumber pDanu, + char *headerTemplate); +void DeleteMesure(void *pData); - int MesureFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MesureFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*------------------- object functions -----------------------------------*/ - int MesureReflection(pMesure self, float fHKL[3], float fPsi, - SConnection *pCon); - int MesureGenReflection(pMesure self, float fHKL[3],float fSet[4], SConnection *pCon); - int MesureStart(pMesure self, SConnection *pCon); - int MesureReopen(pMesure self, char *filename, SConnection *pCon); - int MesureClose(pMesure self); - int MesureFile(pMesure self, char *pFile, int iSkip, SConnection *pCon); - int MesureGenFile(pMesure self, char *pFile, int iSkip, SConnection *pCon); - int MesureSetPar(pMesure self, char *name, float fVal); - int MesureGetPar(pMesure self, char *name, float *fVal); +int MesureReflection(pMesure self, float fHKL[3], float fPsi, + SConnection * pCon); +int MesureGenReflection(pMesure self, float fHKL[3], float fSet[4], + SConnection * pCon); +int MesureStart(pMesure self, SConnection * pCon); +int MesureReopen(pMesure self, char *filename, SConnection * pCon); +int MesureClose(pMesure self); +int MesureFile(pMesure self, char *pFile, int iSkip, SConnection * pCon); +int MesureGenFile(pMesure self, char *pFile, int iSkip, + SConnection * pCon); +int MesureSetPar(pMesure self, char *name, float fVal); +int MesureGetPar(pMesure self, char *name, float *fVal); + +int MesureAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - int MesureAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - #endif diff --git a/modriv.h b/modriv.h index 2b7cd1b9..f84d0df8 100644 --- a/modriv.h +++ b/modriv.h @@ -15,64 +15,59 @@ #define MOTFAIL 0 #define MOTOK 1 - typedef struct __AbstractMoDriv { - /* general motor driver interface - fields. REQUIRED! - */ - float fUpper; /* upper limit */ - float fLower; /* lower limit */ - char *name; - int (*GetPosition)(void *self, float *fPos); - int (*RunTo)(void *self,float fNewVal); - int (*GetStatus)(void *self); - void (*GetError)(void *self, int *iCode, char *buffer, int iBufLen); - int (*TryAndFixIt)(void *self, int iError,float fNew); - int (*Halt)(void *self); - int (*GetDriverPar)(void *self, char *name, - float *value); - int (*SetDriverPar)(void *self,SConnection *pCon, - char *name, float newValue); - void (*ListDriverPar)(void *self, char *motorName, - SConnection *pCon); - void (*KillPrivate)(void *self); - } MotorDriver; - - /* the first fields above HAVE to be IDENTICAL to those below */ +typedef struct __AbstractMoDriv { + /* general motor driver interface + fields. REQUIRED! + */ + float fUpper; /* upper limit */ + float fLower; /* lower limit */ + char *name; + int (*GetPosition) (void *self, float *fPos); + int (*RunTo) (void *self, float fNewVal); + int (*GetStatus) (void *self); + void (*GetError) (void *self, int *iCode, char *buffer, int iBufLen); + int (*TryAndFixIt) (void *self, int iError, float fNew); + int (*Halt) (void *self); + int (*GetDriverPar) (void *self, char *name, float *value); + int (*SetDriverPar) (void *self, SConnection * pCon, + char *name, float newValue); + void (*ListDriverPar) (void *self, char *motorName, SConnection * pCon); + void (*KillPrivate) (void *self); +} MotorDriver; + + /* the first fields above HAVE to be IDENTICAL to those below */ - typedef struct ___MoSDriv { - /* general motor driver interface - fields. REQUIRED! - */ - float fUpper; /* upper limit */ - float fLower; /* lower limit */ - char *name; - int (*GetPosition)(void *self,float *fPos); - int (*RunTo)(void *self, float fNewVal); - int (*GetStatus)(void *self); - void (*GetError)(void *self, int *iCode, char *buffer, int iBufLen); - int (*TryAndFixIt)(void *self,int iError, float fNew); - int (*Halt)(void *self); - int (*GetDriverPar)(void *self, char *name, - float *value); - int (*SetDriverPar)(void *self,SConnection *pCon, - char *name, float newValue); - void (*ListDriverPar)(void *self, char *motorName, - SConnection *pCon); - void (*KillPrivate)(void *self); - - /* Simulation specific fields */ - float fFailure; /* percent random failures*/ - float fSpeed; - time_t iTime; - float fPos; /* position */ - float fTarget; /* target position */ - } SIMDriv; +typedef struct ___MoSDriv { + /* general motor driver interface + fields. REQUIRED! + */ + float fUpper; /* upper limit */ + float fLower; /* lower limit */ + char *name; + int (*GetPosition) (void *self, float *fPos); + int (*RunTo) (void *self, float fNewVal); + int (*GetStatus) (void *self); + void (*GetError) (void *self, int *iCode, char *buffer, int iBufLen); + int (*TryAndFixIt) (void *self, int iError, float fNew); + int (*Halt) (void *self); + int (*GetDriverPar) (void *self, char *name, float *value); + int (*SetDriverPar) (void *self, SConnection * pCon, + char *name, float newValue); + void (*ListDriverPar) (void *self, char *motorName, SConnection * pCon); + void (*KillPrivate) (void *self); + + /* Simulation specific fields */ + float fFailure; /* percent random failures */ + float fSpeed; + time_t iTime; + float fPos; /* position */ + float fTarget; /* target position */ +} SIMDriv; + - /* ----------------------- Simulation -----------------------------------*/ - MotorDriver *CreateSIM(SConnection *pCon, int argc, char *argv[]); - void KillSIM(void *pData); - MotorDriver *RGMakeMotorDriver(void); +MotorDriver *CreateSIM(SConnection * pCon, int argc, char *argv[]); +void KillSIM(void *pData); +MotorDriver *RGMakeMotorDriver(void); #endif - diff --git a/moregress.c b/moregress.c index e8f48045..1f58d124 100644 --- a/moregress.c +++ b/moregress.c @@ -7,7 +7,7 @@ * copyright: see file COPYRIGHT * * Mark Koennecke, July 2007 - */ + */ #include #include #include @@ -15,70 +15,72 @@ /*===================== supported errors ======================*/ #define NONE 0 #define STARTFAIL 1 -#define BADPOS 2 /* positioning problem */ -#define FAIL 3 /* failure */ -#define OFFPOS 4 /* off pos by .2 */ -#define READFAIL 5 -#define RUN 6 /* keep running; for interrupt testing */ +#define BADPOS 2 /* positioning problem */ +#define FAIL 3 /* failure */ +#define OFFPOS 4 /* off pos by .2 */ +#define READFAIL 5 +#define RUN 6 /* keep running; for interrupt testing */ /*=============================================================*/ -typedef struct __RGMoDriv{ - /* general motor driver interface - fields. REQUIRED! - */ - float fUpper; /* upper limit */ - float fLower; /* lower limit */ - char *name; - int (*GetPosition)(void *self, float *fPos); - int (*RunTo)(void *self,float fNewVal); - int (*GetStatus)(void *self); - void (*GetError)(void *self, int *iCode, char *buffer, int iBufLen); - int (*TryAndFixIt)(void *self, int iError,float fNew); - int (*Halt)(void *self); - int (*GetDriverPar)(void *self, char *name, - float *value); - int (*SetDriverPar)(void *self,SConnection *pCon, - char *name, float newValue); - void (*ListDriverPar)(void *self, char *motorName, - SConnection *pCon); - void (*KillPrivate)(void *self); - /* your drivers private fields follow below */ - float target; - int errorType; - int recover; - int counter; - } RGMotorDriver; - +typedef struct __RGMoDriv { + /* general motor driver interface + fields. REQUIRED! + */ + float fUpper; /* upper limit */ + float fLower; /* lower limit */ + char *name; + int (*GetPosition) (void *self, float *fPos); + int (*RunTo) (void *self, float fNewVal); + int (*GetStatus) (void *self); + void (*GetError) (void *self, int *iCode, char *buffer, int iBufLen); + int (*TryAndFixIt) (void *self, int iError, float fNew); + int (*Halt) (void *self); + int (*GetDriverPar) (void *self, char *name, float *value); + int (*SetDriverPar) (void *self, SConnection * pCon, + char *name, float newValue); + void (*ListDriverPar) (void *self, char *motorName, SConnection * pCon); + void (*KillPrivate) (void *self); + /* your drivers private fields follow below */ + float target; + int errorType; + int recover; + int counter; +} RGMotorDriver; + /*================================================================ GetPos returns OKOK on success, HWFault on failure ------------------------------------------------------------------*/ -static int RGGetPos(void *data, float *fPos){ +static int RGGetPos(void *data, float *fPos) +{ RGMotorDriver *self = NULL; - - self = (RGMotorDriver *)data; - if(self->errorType == READFAIL){ + + self = (RGMotorDriver *) data; + if (self->errorType == READFAIL) { return HWFault; } - if(self->errorType > 1 && self->errorType < 6){ + if (self->errorType > 1 && self->errorType < 6) { *fPos = self->target - .2; } else { - *fPos = self->target; + *fPos = self->target; } return OKOK; } + /*---------------------------------------------------------------- RunTo starts the motor running. Returns OKOK on success, HWfault on Errors ------------------------------------------------------------------*/ -static int RGRunTo(void *data, float newValue){ +static int RGRunTo(void *data, float newValue) +{ RGMotorDriver *self = NULL; - - self = (RGMotorDriver *)data; + + self = (RGMotorDriver *) data; self->target = newValue; - if(self->errorType == STARTFAIL){ + if (self->errorType == STARTFAIL) { return HWFault; } return OKOK; } + /*----------------------------------------------------------------- CheckStatus queries the sattus of a running motor. Possible return values can be: @@ -88,54 +90,57 @@ static int RGRunTo(void *data, float newValue){ HWIdle : motor finished OK HWWarn : motor issued warning --------------------------------------------------------------------*/ -static int RGCheckStatus(void *data){ +static int RGCheckStatus(void *data) +{ RGMotorDriver *self = NULL; - - self = (RGMotorDriver *)data; - switch(self->errorType){ - case BADPOS: - return HWPosFault; - break; - case FAIL: - return HWFault; - break; - case RUN: - return HWBusy; - break; + + self = (RGMotorDriver *) data; + switch (self->errorType) { + case BADPOS: + return HWPosFault; + break; + case FAIL: + return HWFault; + break; + case RUN: + return HWBusy; + break; } return HWIdle; } + /*------------------------------------------------------------------ GetError gets more information about error which occurred *iCode is an integer error code to be used in TryFixIt as indicator buffer is a buffer for a text description of the problem iBufLen is the length of buffer --------------------------------------------------------------------*/ -static void RGGetError(void *data, int *iCode, char *buffer, - int iBufLen){ +static void RGGetError(void *data, int *iCode, char *buffer, int iBufLen) +{ RGMotorDriver *self = NULL; - - self = (RGMotorDriver *)data; - *iCode = self->errorType; - switch(self->errorType){ - case NONE: - strncpy(buffer,"No error found",iBufLen); - break; - case BADPOS: - strncpy(buffer,"Position not reached",iBufLen); - break; - case FAIL: - strncpy(buffer,"Hardware is mad",iBufLen); - break; - case STARTFAIL: - strncpy(buffer,"Failed to start motor",iBufLen); - break; - case READFAIL: - strncpy(buffer,"Failed to read motor",iBufLen); - break; - + + self = (RGMotorDriver *) data; + *iCode = self->errorType; + switch (self->errorType) { + case NONE: + strncpy(buffer, "No error found", iBufLen); + break; + case BADPOS: + strncpy(buffer, "Position not reached", iBufLen); + break; + case FAIL: + strncpy(buffer, "Hardware is mad", iBufLen); + break; + case STARTFAIL: + strncpy(buffer, "Failed to start motor", iBufLen); + break; + case READFAIL: + strncpy(buffer, "Failed to read motor", iBufLen); + break; + } } + /*------------------------------------------------------------------ TryAndFixIt tries everything which is possible in software to fix a problem. iError is the error code from GetError, newValue is @@ -145,120 +150,130 @@ static void RGGetError(void *data, int *iCode, char *buffer, MOTREDO : try again MOTFAIL : cannot fix this --------------------------------------------------------------------*/ -static int RGFixIt(void *data, int iError, float newValue){ +static int RGFixIt(void *data, int iError, float newValue) +{ RGMotorDriver *self = NULL; - - self = (RGMotorDriver *)data; - if(self->recover == 1){ + + self = (RGMotorDriver *) data; + if (self->recover == 1) { self->errorType = NONE; return MOTREDO; } return MOTFAIL; } + /*------------------------------------------------------------------- Halt tries to stop the motor. Halt errors are ignored ---------------------------------------------------------------------*/ -static int RGHalt(void *data){ +static int RGHalt(void *data) +{ RGMotorDriver *self = NULL; - - self = (RGMotorDriver *)data; + + self = (RGMotorDriver *) data; self->errorType = NONE; return 1; } + /*-------------------------------------------------------------------- GetDriverPar retrieves the value of a driver parameter. Name is the name of the parameter, fValue the value when found. Returns 0 on success, 0 else -----------------------------------------------------------------------*/ -static int RGGetDriverPar(void *data, char *name, float *value){ +static int RGGetDriverPar(void *data, char *name, float *value) +{ RGMotorDriver *self = NULL; - - self = (RGMotorDriver *)data; - if(strcmp(name,"errortype") == 0){ - *value = (float)self->errorType; + + self = (RGMotorDriver *) data; + if (strcmp(name, "errortype") == 0) { + *value = (float) self->errorType; return 1; - } else if (strcmp(name,"recover") == 0){ + } else if (strcmp(name, "recover") == 0) { *value = self->recover; return 1; } - + return 0; } + /*---------------------------------------------------------------------- SetDriverPar sets a driver parameter. Returns 0 on failure, 1 on success. Name is the parameter name, pCon the connection to report errors too, value the new value ------------------------------------------------------------------------*/ -static int RGSetDriverPar(void *data, SConnection *pCon, - char *name, float value){ +static int RGSetDriverPar(void *data, SConnection * pCon, + char *name, float value) +{ RGMotorDriver *self = NULL; - - self = (RGMotorDriver *)data; - if(strcmp(name,"errortype") == 0){ - self->errorType = (int)value; + + self = (RGMotorDriver *) data; + if (strcmp(name, "errortype") == 0) { + self->errorType = (int) value; return 1; - } else if (strcmp(name,"recover") == 0){ - self->recover = (int)value; + } else if (strcmp(name, "recover") == 0) { + self->recover = (int) value; + return 1; + } else if (strcmp(name, "hardupperlim") == 0) { + self->fUpper = value; + return 1; + } else if (strcmp(name, "hardlowerlim") == 0) { + self->fLower = value; return 1; - } else if(strcmp(name,"hardupperlim") == 0) { - self->fUpper = value; - return 1; - } else if(strcmp(name,"hardlowerlim") == 0){ - self->fLower = value; - return 1; } - return 0; + return 0; } + /*----------------------------------------------------------------------- ListDriverPar lists the names and values of driver parameters to pCon. Motorname is the name of the motor ro prefix to the listing. -------------------------------------------------------------------------*/ -static void RGListDriverPar(void *data, char *motorname, - SConnection *pCon){ +static void RGListDriverPar(void *data, char *motorname, + SConnection * pCon) +{ RGMotorDriver *self = NULL; char buffer[256]; - self = (RGMotorDriver *)data; - snprintf(buffer,255,"%s errortype = %d", motorname, - self->errorType); - SCWrite(pCon,buffer,eValue); + self = (RGMotorDriver *) data; + snprintf(buffer, 255, "%s errortype = %d", motorname, self->errorType); + SCWrite(pCon, buffer, eValue); - snprintf(buffer,255,"%s recover = %d", motorname, - self->recover); - SCWrite(pCon,buffer,eValue); + snprintf(buffer, 255, "%s recover = %d", motorname, self->recover); + SCWrite(pCon, buffer, eValue); } + /*----------------------------------------------------------------------- KillPrivate has the task to delete possibly dynamically allocated memory in the private part of the driver structure ------------------------------------------------------------------------*/ -static void RGKillPrivate(void *data){ +static void RGKillPrivate(void *data) +{ RGMotorDriver *self = NULL; - - self = (RGMotorDriver *)data; + + self = (RGMotorDriver *) data; } + /*=======================================================================*/ -MotorDriver *RGMakeMotorDriver(void) { - RGMotorDriver *pNew = NULL; +MotorDriver *RGMakeMotorDriver(void) +{ + RGMotorDriver *pNew = NULL; - pNew = malloc(sizeof(RGMotorDriver)); - if(pNew == NULL){ - return NULL; - } - memset(pNew,0,sizeof(RGMotorDriver)); - - pNew->GetPosition = RGGetPos; - pNew->RunTo = RGRunTo; - pNew->GetStatus = RGCheckStatus; - pNew->GetError = RGGetError; - pNew->TryAndFixIt = RGFixIt; - pNew->Halt = RGHalt; - pNew->GetDriverPar = RGGetDriverPar; - pNew->SetDriverPar = RGSetDriverPar; - pNew->ListDriverPar = RGListDriverPar; - pNew->KillPrivate = RGKillPrivate; - pNew->fLower = -180.; - pNew->fUpper = 180.; - - return (MotorDriver *)pNew; + pNew = malloc(sizeof(RGMotorDriver)); + if (pNew == NULL) { + return NULL; + } + memset(pNew, 0, sizeof(RGMotorDriver)); + + pNew->GetPosition = RGGetPos; + pNew->RunTo = RGRunTo; + pNew->GetStatus = RGCheckStatus; + pNew->GetError = RGGetError; + pNew->TryAndFixIt = RGFixIt; + pNew->Halt = RGHalt; + pNew->GetDriverPar = RGGetDriverPar; + pNew->SetDriverPar = RGSetDriverPar; + pNew->ListDriverPar = RGListDriverPar; + pNew->KillPrivate = RGKillPrivate; + pNew->fLower = -180.; + pNew->fUpper = 180.; + + return (MotorDriver *) pNew; } - diff --git a/motor.c b/motor.c index 0a2802d1..9aec5433 100644 --- a/motor.c +++ b/motor.c @@ -82,327 +82,328 @@ /*-------------------------------------------------------------------------*/ - static void *MotorGetInterface(void *pData, int iID) - { - pMotor self = NULL; - - self = (pMotor)pData; - assert(self); - if(iID == DRIVEID) - { - return self->pDrivInt; - } - else if(iID == CALLBACKINTERFACE) - { - return self->pCall; - } - return NULL; - } -/*------------------------------------------------------------------------*/ - static int MotorHalt(void *sulf) - { - pMotor self; - - assert(sulf); - self = (pMotor)sulf; - - /* reduce the error count by 1. This is because the driver is - expected to return an error when the motor had been stopped. - However, a stop is usually a consequence of a user intervention - or program logic. This prevents to a false motor alarm when the - motor was repeatedly stopped for other reasons. - */ - self->pDrivInt->iErrorCount--; - if(self->pDrivInt->iErrorCount < 0) - self->pDrivInt->iErrorCount = 0; +static void *MotorGetInterface(void *pData, int iID) +{ + pMotor self = NULL; - self->stopped = 1; - return self->pDriver->Halt((void *)self->pDriver); + self = (pMotor) pData; + assert(self); + if (iID == DRIVEID) { + return self->pDrivInt; + } else if (iID == CALLBACKINTERFACE) { + return self->pCall; } + return NULL; +} + +/*------------------------------------------------------------------------*/ +static int MotorHalt(void *sulf) +{ + pMotor self; + + assert(sulf); + self = (pMotor) sulf; + + /* reduce the error count by 1. This is because the driver is + expected to return an error when the motor had been stopped. + However, a stop is usually a consequence of a user intervention + or program logic. This prevents to a false motor alarm when the + motor was repeatedly stopped for other reasons. + */ + self->pDrivInt->iErrorCount--; + if (self->pDrivInt->iErrorCount < 0) + self->pDrivInt->iErrorCount = 0; + + self->stopped = 1; + return self->pDriver->Halt((void *) self->pDriver); +} + /*--------------------------------------------------------------------------- MotorCheckBoundary checks for violation of boundary conditions and transforms from SoftCoordinates to hard coordinates. */ - + static int MotorCheckBoundaryImpl(pMotor self, float fVal, float *fNew, - char *pError, int iErrLen) - { - float fHard; - float fZero; - char pBueffel[512]; - - assert(self); - - /* check for fixed */ - if(ObVal(self->ParArray,FIX) >= 0) - { - sprintf(pBueffel,"Motor %s is Fixed",self->name); - strncpy(pError,pBueffel,iErrLen); - return 0; /* is this an error? */ - } - - /* check against software boundaries */ - if(fVal > ObVal(self->ParArray,SUPP)) - { - sprintf(pBueffel,"%f violates upper software limit %f on %s", - fVal, ObVal(self->ParArray,SUPP),self->name); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - if(fVal < ObVal(self->ParArray,SLOW)) - { - sprintf(pBueffel,"%f violates lower software limit %f on %s", - fVal,ObVal(self->ParArray,SLOW),self->name ); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - - /* correct for zero point */ - fZero = ObVal(self->ParArray,SZERO); - fZero = -fZero; - fHard = fVal - fZero; - - /* apply sign */ - fHard = fHard*ObVal(self->ParArray,SIGN); - - /* check for hardware limits */ - if(fHard > self->pDriver->fUpper) - { - sprintf(pBueffel,"%f violates upper hardware limit %f on %s", - fVal,self->pDriver->fUpper,self->name); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - if(fHard < self->pDriver->fLower) - { - sprintf(pBueffel,"%f violates lower hardware limit %f on %s", - fVal,self->pDriver->fLower,self->name); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - - *fNew = fHard; - return 1; - } -/*--------------------------------------------------------------------------*/ - static int MotorLimits(void *sulf, float fVal, char *error, int iErrLen) - { - float fHard; - pMotor self; - - assert(sulf); - - self = (pMotor)sulf; - - return MotorCheckBoundaryImpl(self,fVal,&fHard,error,iErrLen); - } - /* ------------------------------------------------------------------------*/ -static int MotorGetSoftPositionImpl(pMotor self, SConnection *pCon, float *fVal) + char *pError, int iErrLen) { - int iRet; - float fValue; - - assert(self); - assert(pCon); - - /* get the hard position */ - iRet = MotorGetHardPosition(self,pCon,&fValue); - if(!iRet) - { - *fVal = fValue; - return 0; - } - /* apply zeropoint */ - if(ObVal(self->ParArray,SIGN) < 0.) - { - fValue += ObVal(self->ParArray,SZERO); - } - else - { - fValue -= ObVal(self->ParArray,SZERO); - } - *fVal = fValue; + float fHard; + float fZero; + char pBueffel[512]; - /* apply sign */ - /* *fVal = MotorHardToSoftPosition(self,fValue); */ + assert(self); + + /* check for fixed */ + if (ObVal(self->ParArray, FIX) >= 0) { + sprintf(pBueffel, "Motor %s is Fixed", self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; /* is this an error? */ + } + + /* check against software boundaries */ + if (fVal > ObVal(self->ParArray, SUPP)) { + sprintf(pBueffel, "%f violates upper software limit %f on %s", + fVal, ObVal(self->ParArray, SUPP), self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + if (fVal < ObVal(self->ParArray, SLOW)) { + sprintf(pBueffel, "%f violates lower software limit %f on %s", + fVal, ObVal(self->ParArray, SLOW), self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + + /* correct for zero point */ + fZero = ObVal(self->ParArray, SZERO); + fZero = -fZero; + fHard = fVal - fZero; + + /* apply sign */ + fHard = fHard * ObVal(self->ParArray, SIGN); + + /* check for hardware limits */ + if (fHard > self->pDriver->fUpper) { + sprintf(pBueffel, "%f violates upper hardware limit %f on %s", + fVal, self->pDriver->fUpper, self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + if (fHard < self->pDriver->fLower) { + sprintf(pBueffel, "%f violates lower hardware limit %f on %s", + fVal, self->pDriver->fLower, self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + + *fNew = fHard; + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int MotorLimits(void *sulf, float fVal, char *error, int iErrLen) +{ + float fHard; + pMotor self; + + assert(sulf); + + self = (pMotor) sulf; + + return MotorCheckBoundaryImpl(self, fVal, &fHard, error, iErrLen); +} + + /* ------------------------------------------------------------------------ */ +static int MotorGetSoftPositionImpl(pMotor self, SConnection * pCon, + float *fVal) +{ + int iRet; + float fValue; + + assert(self); + assert(pCon); + + /* get the hard position */ + iRet = MotorGetHardPosition(self, pCon, &fValue); + if (!iRet) { + *fVal = fValue; + return 0; + } + /* apply zeropoint */ + if (ObVal(self->ParArray, SIGN) < 0.) { + fValue += ObVal(self->ParArray, SZERO); + } else { + fValue -= ObVal(self->ParArray, SZERO); + } + *fVal = fValue; + + /* apply sign */ + /* *fVal = MotorHardToSoftPosition(self,fValue); */ + + *fVal = fValue * ObVal(self->ParArray, SIGN); + + return 1; +} - *fVal = fValue*ObVal(self->ParArray,SIGN); - - return 1; - } /*---------------------------------------------------------------------------*/ - static float MotorGetValue(void *pData, SConnection *pCon) - { - int iRet; - float fVal = 0.; - - assert(pData); - iRet = MotorGetSoftPositionImpl((pMotor)pData,pCon,&fVal); - if(iRet != OKOK) - { - fVal = -9999999.99; - } - return fVal; - } +static float MotorGetValue(void *pData, SConnection * pCon) +{ + int iRet; + float fVal = 0.; + + assert(pData); + iRet = MotorGetSoftPositionImpl((pMotor) pData, pCon, &fVal); + if (iRet != OKOK) { + fVal = -9999999.99; + } + return fVal; +} + /*------------------------------------------------------------------------*/ - static int MotorSaveStatus(void *pData, char *name, FILE *fd) - { - pMotor self = NULL; - char pBueffel[512]; - - assert(pData); - assert(fd); - - self= (pMotor)pData; - fprintf(fd,"# Motor %s\n",name); - sprintf(pBueffel,"%s sign %f\n",name,ObVal(self->ParArray,SIGN)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s SoftZero %f\n",name,ObVal(self->ParArray,SZERO)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s SoftLowerLim %f\n",name,ObVal(self->ParArray,SLOW)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s SoftUpperLim %f\n",name,ObVal(self->ParArray,SUPP)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s Fixed %f\n",name,ObVal(self->ParArray,FIX)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s InterruptMode %f\n",name,ObVal(self->ParArray,INT)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s precision %f\n",name,ObVal(self->ParArray,PREC)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s ignorefault %f\n",name,ObVal(self->ParArray,IGNOREFAULT)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s AccessCode %f\n",name,ObVal(self->ParArray,USRIGHTS)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s failafter %f\n",name,ObVal(self->ParArray,ECOUNT)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s maxretry %f\n",name,ObVal(self->ParArray,POSCOUNT)); - fputs(pBueffel,fd); - sprintf(pBueffel,"%s movecount %f\n",name, - ObVal(self->ParArray,MOVECOUNT)); - fputs(pBueffel,fd); - return 1; - } +static int MotorSaveStatus(void *pData, char *name, FILE * fd) +{ + pMotor self = NULL; + char pBueffel[512]; + + assert(pData); + assert(fd); + + self = (pMotor) pData; + fprintf(fd, "# Motor %s\n", name); + sprintf(pBueffel, "%s sign %f\n", name, ObVal(self->ParArray, SIGN)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s SoftZero %f\n", name, + ObVal(self->ParArray, SZERO)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s SoftLowerLim %f\n", name, + ObVal(self->ParArray, SLOW)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s SoftUpperLim %f\n", name, + ObVal(self->ParArray, SUPP)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s Fixed %f\n", name, ObVal(self->ParArray, FIX)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s InterruptMode %f\n", name, + ObVal(self->ParArray, INT)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s precision %f\n", name, + ObVal(self->ParArray, PREC)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s ignorefault %f\n", name, + ObVal(self->ParArray, IGNOREFAULT)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s AccessCode %f\n", name, + ObVal(self->ParArray, USRIGHTS)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s failafter %f\n", name, + ObVal(self->ParArray, ECOUNT)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s maxretry %f\n", name, + ObVal(self->ParArray, POSCOUNT)); + fputs(pBueffel, fd); + sprintf(pBueffel, "%s movecount %f\n", name, + ObVal(self->ParArray, MOVECOUNT)); + fputs(pBueffel, fd); + return 1; +} + /*-------------------------------------------------------------------------*/ - static float absf(float f) - { - if(f < 0.) - { - return -f; - } - else - { - return f; - } - } -/*-------------------------------------------------------------------------*/ - static void MotorInterrupt(SConnection *pCon, int iVal) - { - if(SCGetInterrupt(pCon) < iVal) - { - SCSetInterrupt(pCon,iVal); - } +static float absf(float f) +{ + if (f < 0.) { + return -f; + } else { + return f; } +} + +/*-------------------------------------------------------------------------*/ +static void MotorInterrupt(SConnection * pCon, int iVal) +{ + if (SCGetInterrupt(pCon) < iVal) { + SCSetInterrupt(pCon, iVal); + } +} + /*---------------------------------------------------------------------*/ -static int statusRunTo(pMotor self, SConnection *pCon) +static int statusRunTo(pMotor self, SConnection * pCon) { char pBueffel[256]; - if(self->retryCount >= ObVal(self->ParArray,POSCOUNT)) - { - snprintf(pBueffel,255,"ERROR: aborting motor %s after %d retries", - self->name, self->retryCount); - SCWrite(pCon,pBueffel,eError); + if (self->retryCount >= ObVal(self->ParArray, POSCOUNT)) { + snprintf(pBueffel, 255, "ERROR: aborting motor %s after %d retries", + self->name, self->retryCount); + SCWrite(pCon, pBueffel, eError); return HWFault; } - if(SCGetInterrupt(pCon) != eContinue){ - return HWFault; + if (SCGetInterrupt(pCon) != eContinue) { + return HWFault; } self->retryCount++; - snprintf(pBueffel,255,"WARNING: restarting %s, %d time", - self->name,self->retryCount); - SCWrite(pCon,pBueffel,eWarning); - self->pDriver->RunTo(self->pDriver,self->fTarget); + snprintf(pBueffel, 255, "WARNING: restarting %s, %d time", + self->name, self->retryCount); + SCWrite(pCon, pBueffel, eWarning); + self->pDriver->RunTo(self->pDriver, self->fTarget); return HWBusy; } + /*--------------------------------------------------------------------*/ -static int checkPosition(pMotor self, SConnection *pCon) +static int checkPosition(pMotor self, SConnection * pCon) { float fHard; char pBueffel[132]; int status; - MotorGetHardPosition(self,pCon,&fHard); + MotorGetHardPosition(self, pCon, &fHard); self->fPosition = fHard; - if(absf(fHard - self->fTarget) > ObVal(self->ParArray,PREC)) - { - if (SCGetInterrupt(pCon) != eContinue) - { - return HWFault; - } - if(self->stopped) - { - snprintf(pBueffel,131,"WARNING: %s stopped", self->name); - SCWrite(pCon,pBueffel, eWarning); - return HWFault; - } - snprintf(pBueffel,131,"WARNING: %s off position by %f", - self->name, absf(fHard - self->fTarget)); - SCWrite(pCon,pBueffel, eWarning); - status = statusRunTo(self,pCon); - return status; + if (absf(fHard - self->fTarget) > ObVal(self->ParArray, PREC)) { + if (SCGetInterrupt(pCon) != eContinue) { + return HWFault; + } + if (self->stopped) { + snprintf(pBueffel, 131, "WARNING: %s stopped", self->name); + SCWrite(pCon, pBueffel, eWarning); + return HWFault; + } + snprintf(pBueffel, 131, "WARNING: %s off position by %f", + self->name, absf(fHard - self->fTarget)); + SCWrite(pCon, pBueffel, eWarning); + status = statusRunTo(self, pCon); + return status; } - return HWIdle; + return HWIdle; } + /*--------------------------------------------------------------------*/ -static void finishDriving(pMotor self, SConnection *pCon) +static void finishDriving(pMotor self, SConnection * pCon) { MotCallback sCall; - MotorGetSoftPosition(self,pCon,&sCall.fVal); + MotorGetSoftPosition(self, pCon, &sCall.fVal); sCall.pName = self->name; self->fPosition = sCall.fVal; self->fPosition = sCall.fVal; - InvokeCallBack(self->pCall, MOTDRIVE, &sCall); /* send also very last position */ + InvokeCallBack(self->pCall, MOTDRIVE, &sCall); /* send also very last position */ InvokeCallBack(self->pCall, MOTEND, &sCall); } + /*--------------------------------------------------------------------*/ -static int reportAndFixError(pMotor self, SConnection *pCon) +static int reportAndFixError(pMotor self, SConnection * pCon) { char pBueffel[256], pError[131]; int iCode, iRet, newStatus; - self->pDriver->GetError(self->pDriver,&iCode, pError,131); - iRet = self->pDriver->TryAndFixIt(self->pDriver,iCode, self->fTarget); - switch(iRet) - { + self->pDriver->GetError(self->pDriver, &iCode, pError, 131); + iRet = self->pDriver->TryAndFixIt(self->pDriver, iCode, self->fTarget); + switch (iRet) { case MOTFAIL: - snprintf(pBueffel,255,"ERROR: %s on %s",pError,self->name); - SCWrite(pCon,pBueffel,eError); + snprintf(pBueffel, 255, "ERROR: %s on %s", pError, self->name); + SCWrite(pCon, pBueffel, eError); newStatus = HWFault; break; case MOTREDO: - snprintf(pBueffel,255,"WARNING: %s on %s",pError,self->name); - SCWrite(pCon,pBueffel,eWarning); - newStatus = statusRunTo(self,pCon); + snprintf(pBueffel, 255, "WARNING: %s on %s", pError, self->name); + SCWrite(pCon, pBueffel, eWarning); + newStatus = statusRunTo(self, pCon); break; case MOTOK: - snprintf(pBueffel,255,"WARNING: %s on %s",pError,self->name); - SCWrite(pCon,pBueffel,eWarning); + snprintf(pBueffel, 255, "WARNING: %s on %s", pError, self->name); + SCWrite(pCon, pBueffel, eWarning); newStatus = HWIdle; break; default: - SCWrite(pCon,"WARNING: bad status code in motor.c:reportAndFixError", - eWarning); - SCWrite(pCon,"You may continue, but show this to a SICS programmer", - eWarning); + SCWrite(pCon, "WARNING: bad status code in motor.c:reportAndFixError", + eWarning); + SCWrite(pCon, "You may continue, but show this to a SICS programmer", + eWarning); newStatus = HWIdle; break; } return newStatus; } + /*--------------------------------------------------------------------- New version, refactored October 2003 -----------------------------------------------------------------------*/ -static int evaluateStatus(pMotor self, SConnection *pCon) +static int evaluateStatus(pMotor self, SConnection * pCon) { int iRet, iCode, newStatus; MotCallback sCall; @@ -411,31 +412,26 @@ static int evaluateStatus(pMotor self, SConnection *pCon) iRet = self->pDriver->GetStatus(self->pDriver); newStatus = iRet; - switch(iRet) - { + switch (iRet) { case OKOK: case HWIdle: - newStatus = checkPosition(self,pCon); - if(newStatus != HWBusy) - { - finishDriving(self,pCon); + newStatus = checkPosition(self, pCon); + if (newStatus != HWBusy) { + finishDriving(self, pCon); } break; case HWFault: - newStatus = reportAndFixError(self,pCon); + newStatus = reportAndFixError(self, pCon); break; case HWPosFault: - newStatus = reportAndFixError(self,pCon); - if(newStatus == HWFault && ObVal(self->ParArray,IGNOREFAULT) < 1) - { + newStatus = reportAndFixError(self, pCon); + if (newStatus == HWFault && ObVal(self->ParArray, IGNOREFAULT) < 1) { newStatus = HWPosFault; - } - if(newStatus == HWIdle || newStatus == OKOK) - { - newStatus = checkPosition(self,pCon); - if(newStatus != HWBusy) - { - finishDriving(self,pCon); + } + if (newStatus == HWIdle || newStatus == OKOK) { + newStatus = checkPosition(self, pCon); + if (newStatus != HWBusy) { + finishDriving(self, pCon); } } break; @@ -443,570 +439,532 @@ static int evaluateStatus(pMotor self, SConnection *pCon) newStatus = HWBusy; break; case HWWarn: - self->pDriver->GetError(self->pDriver,&iCode, pError,131); - snprintf(pBueffel,255,"WARNING: motor reported: %s", pError); - SCWrite(pCon,pBueffel,eWarning); + self->pDriver->GetError(self->pDriver, &iCode, pError, 131); + snprintf(pBueffel, 255, "WARNING: motor reported: %s", pError); + SCWrite(pCon, pBueffel, eWarning); newStatus = HWIdle; break; default: - SCWrite(pCon,"WARNING: Bad status in motor.c:evaluatStatus",eWarning); - SCWrite(pCon,"You may continue, but show this to a SICS programmer", - eWarning); + SCWrite(pCon, "WARNING: Bad status in motor.c:evaluatStatus", + eWarning); + SCWrite(pCon, "You may continue, but show this to a SICS programmer", + eWarning); break; } - if(newStatus == HWFault) - { - finishDriving(self,pCon); - MotorInterrupt(pCon,ObVal(self->ParArray,INT)); + if (newStatus == HWFault) { + finishDriving(self, pCon); + MotorInterrupt(pCon, ObVal(self->ParArray, INT)); self->retryCount = 0; } return newStatus; } + /*---------------------------------------------------------------------*/ -static void handleMoveCallback(pMotor self, SConnection *pCon) +static void handleMoveCallback(pMotor self, SConnection * pCon) { - MotCallback sCall; - - self->posCount++; - if(self->posCount >= ObVal(self->ParArray,MOVECOUNT)) - { - MotorGetSoftPosition(self,pCon,&sCall.fVal); - sCall.pName = self->name; - InvokeCallBack(self->pCall, MOTDRIVE, &sCall); - self->posCount = 0; - } -} -/*-----------------------------------------------------------------------*/ - static int MotorStatus(void *sulf, SConnection *pCon) - { - pMotor self = NULL; - int status; + MotCallback sCall; - assert(sulf); - self = (pMotor)sulf; - - status = evaluateStatus(self,pCon); - if (self->pDrivInt->drivableStatus!=status) { - ((SConnection *)pCon)->conEventType=STATUS; - ((SConnection *)pCon)->conStatus=status; - SCWrite(pCon, "", eEvent); - self->pDrivInt->drivableStatus=status; - } - if(status == HWBusy) - { - handleMoveCallback(self,pCon); - } - return status; + self->posCount++; + if (self->posCount >= ObVal(self->ParArray, MOVECOUNT)) { + MotorGetSoftPosition(self, pCon, &sCall.fVal); + sCall.pName = self->name; + InvokeCallBack(self->pCall, MOTDRIVE, &sCall); + self->posCount = 0; } +} + +/*-----------------------------------------------------------------------*/ +static int MotorStatus(void *sulf, SConnection * pCon) +{ + pMotor self = NULL; + int status; + + assert(sulf); + self = (pMotor) sulf; + + status = evaluateStatus(self, pCon); + if (self->pDrivInt->drivableStatus != status) { + ((SConnection *) pCon)->conEventType = STATUS; + ((SConnection *) pCon)->conStatus = status; + SCWrite(pCon, "", eEvent); + self->pDrivInt->drivableStatus = status; + } + if (status == HWBusy) { + handleMoveCallback(self, pCon); + } + return status; +} + /*---------------------------------------------------------------------------*/ int MotorGetPar(pMotor self, char *name, float *fVal) { - return self->MotorGetPar(self,name,fVal); + return self->MotorGetPar(self, name, fVal); } + /*---------------------------------------------------------------------------*/ -int MotorSetPar(pMotor self, SConnection *pCon, char *name, float fVal) +int MotorSetPar(pMotor self, SConnection * pCon, char *name, float fVal) { - return self->MotorSetPar(self,pCon,name,fVal); + return self->MotorSetPar(self, pCon, name, fVal); } + /*---------------------------------------------------------------------------*/ -int MotorGetHardPosition(pMotor self,SConnection *pCon, float *fVal) +int MotorGetHardPosition(pMotor self, SConnection * pCon, float *fVal) { - return self->MotorGetHardPosition(self, pCon, fVal); + return self->MotorGetHardPosition(self, pCon, fVal); } + /*--------------------------------------------------------------------------*/ static int MotorGetParImpl(pMotor self, char *name, float *fVal) - { - ObPar *pPar = NULL; - assert(self); +{ + ObPar *pPar = NULL; + assert(self); - if(strcmp(name,"hardupperlim") == 0) - { - *fVal = self->pDriver->fUpper; - return 1; - } - if(strcmp(name,"hardlowerlim") == 0) - { - *fVal = self->pDriver->fLower; - return 1; - } - - pPar = ObParFind(self->ParArray,name); - if(pPar) - { - *fVal = pPar->fVal; - return 1; - } - else - { - /* can still be position */ - if(strcmp(name,"position") == 0) - { - *fVal = self->fPosition; - return 1; - } - else if(strcmp(name,"target") == 0) - { - *fVal = self->fTarget; - return 1; - } - else - { - /* - check for a driver parameter - */ - if(self->pDriver->GetDriverPar != NULL) - { - return self->pDriver->GetDriverPar(self->pDriver,name,fVal); - } - else - { - return 0; - } - } - } + if (strcmp(name, "hardupperlim") == 0) { + *fVal = self->pDriver->fUpper; + return 1; + } + if (strcmp(name, "hardlowerlim") == 0) { + *fVal = self->pDriver->fLower; + return 1; } -/*---------------------------------------------------------------------------*/ -static int MotorSetParImpl(pMotor self, SConnection *pCon, char *name, float fVal) - { - ObPar *pPar = NULL; - char pBueffel[512]; - int iRet; - float fLimit, fOld, fChange; - - assert(self); - assert(pCon); - /* - try set driver parameters - */ - if(self->pDriver->SetDriverPar != NULL) - { - iRet = self->pDriver->SetDriverPar(self->pDriver,pCon,name,fVal); - if(iRet == 1) - { - SCparChange(pCon); - InvokeCallBack(self->pCall,HDBVAL,self); - return iRet; - } - } - - - if(strcmp(name,"softzero") == 0) - { - /* set it first, this also tests the necessary privileges */ - fOld = ObVal(self->ParArray,SZERO); - iRet = ObParSet(self->ParArray,self->name,name,fVal,pCon); - if(!iRet) - { - return iRet; - } - /* shift the limits by the difference between old and new */ - fChange = fVal - fOld; - /* upper limit */ - fLimit = ObVal(self->ParArray,SUPP); - fLimit -= fChange; - ObParSet(self->ParArray,self->name,"softupperlim",fLimit,pCon); - /* lower limit */ - fLimit = ObVal(self->ParArray,SLOW); - fLimit -= fChange; - ObParSet(self->ParArray,self->name,"softlowerlim",fLimit,pCon); - SCparChange(pCon); - InvokeCallBack(self->pCall,HDBVAL,self); - - return 1; - } - - iRet = ObParSet(self->ParArray,self->name,name,fVal,pCon); - if(strcmp(name,"sign") == 0) - { - if((absf(fVal)-1.0) > 0.01) - { - SCWrite(pCon,"ERROR: Invalid Sign Value",eError); - return 0; - } - if(fVal < 0.0) - { - ObParInit(self->ParArray,SLOW,"softlowerlim", - self->pDriver->fUpper*fVal,usUser); - ObParInit(self->ParArray,SUPP,"softupperlim", - self->pDriver->fLower*fVal,usUser); - ObParInit(self->ParArray,SZERO,"softzero",ZEROINACTIVE,usUser); - } - } - InvokeCallBack(self->pCall,HDBVAL,self); - SCparChange(pCon); - - return iRet; - } -/*------------------------------------------------------------------------*/ -static int MotorGetHardPositionImpl(pMotor self,SConnection *pCon, float *fHard) - { - int iRet, iCode; - float fVal; - char pBueffel[512],pError[256]; - - assert(self); - assert(pCon); - - iRet = self->pDriver->GetPosition(self->pDriver,&fVal); - if(iRet == OKOK) /* all went well, the exception */ - { - *fHard = fVal; + pPar = ObParFind(self->ParArray, name); + if (pPar) { + *fVal = pPar->fVal; + return 1; + } else { + /* can still be position */ + if (strcmp(name, "position") == 0) { + *fVal = self->fPosition; return 1; + } else if (strcmp(name, "target") == 0) { + *fVal = self->fTarget; + return 1; + } else { + /* + check for a driver parameter + */ + if (self->pDriver->GetDriverPar != NULL) { + return self->pDriver->GetDriverPar(self->pDriver, name, fVal); + } else { + return 0; + } } - else /* a problem, the usual case: try fix the problem */ - { /* no point in trying this three times */ - self->pDriver->GetError(self->pDriver,&iCode, pError,255); - iRet = self->pDriver->TryAndFixIt(self->pDriver,iCode, fVal); - sprintf(pBueffel,"WARNING: Trying to fix %s",pError); - SCWrite(pCon,pBueffel,eWarning); - switch(iRet) - { - case MOTFAIL: - sprintf(pBueffel,"ERROR: cannot fix motor %s", - self->name); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,(int)ObVal(self->ParArray,INT)); - *fHard = fVal; - return 0; - case MOTOK: - case MOTREDO: - iRet = self->pDriver->GetPosition(self->pDriver,&fVal); - if(iRet) - { - *fHard = fVal*ObVal(self->ParArray,SIGN); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: cannot fix motor %s", - self->name); - SCSetInterrupt(pCon,(int)ObVal(self->ParArray,INT)); - SCWrite(pCon,pBueffel,eError); - *fHard = fVal; - return 0; - } - } - } - *fHard = fVal*ObVal(self->ParArray,SIGN); - return 0; - } -/*---------------------------------------------------------------------------*/ -static long MotorRunImpl(void *sulf, SConnection *pCon, float fNew) - { - float fHard; - int i, iRet, iCode; - char pBueffel[512]; - char pError[132]; - pMotor self; - long lTime; - float fDelta; - - self = (pMotor)(sulf); - assert(self); - assert(pCon); - - /* check if I'am allowed to move this motor */ - if(!SCMatchRights(pCon,(int)ObVal(self->ParArray,USRIGHTS))) - { - sprintf(pBueffel,"ERROR: You are not authorised to move motor %s", - self->name); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,eAbortBatch); - return 0; - } - - /* check boundaries first */ - iRet = MotorCheckBoundaryImpl(self,fNew,&fHard,pError,131); - if(!iRet) - { - snprintf(pBueffel,511,"ERROR: %s",pError); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,eAbortOperation); - return 0; - } - - /* check if the bad motor flag is set */ - if((int)ObVal(self->ParArray,IGNOREFAULT) > 0) - { - snprintf(pBueffel,511,"WARNING: motor %s is unreliable", - self->name); - SCWrite(pCon,pBueffel,eWarning); - self->pDrivInt->iErrorCount = 0; - } + } +} - /* check our error count and interrupt if to much */ - iCode = (int)ObVal(self->ParArray,ECOUNT); - if(self->pDrivInt->iErrorCount > iCode) - { - /* big alarm */ - ServerWriteGlobal("ERROR: !!! MOTOR ALARM !!! MOTOR ALARM !!!",eError); - sprintf(pBueffel, - "ERROR: too many position errors counted at motor %s", - self->name); - ServerWriteGlobal(pBueffel,eError); - SCSetInterrupt(pCon,eAbortBatch); - self->pDrivInt->iErrorCount = 0; +/*---------------------------------------------------------------------------*/ +static int MotorSetParImpl(pMotor self, SConnection * pCon, char *name, + float fVal) +{ + ObPar *pPar = NULL; + char pBueffel[512]; + int iRet; + float fLimit, fOld, fChange; + + assert(self); + assert(pCon); + + /* + try set driver parameters + */ + if (self->pDriver->SetDriverPar != NULL) { + iRet = self->pDriver->SetDriverPar(self->pDriver, pCon, name, fVal); + if (iRet == 1) { + SCparChange(pCon); + InvokeCallBack(self->pCall, HDBVAL, self); + return iRet; + } + } + + + if (strcmp(name, "softzero") == 0) { + /* set it first, this also tests the necessary privileges */ + fOld = ObVal(self->ParArray, SZERO); + iRet = ObParSet(self->ParArray, self->name, name, fVal, pCon); + if (!iRet) { + return iRet; + } + /* shift the limits by the difference between old and new */ + fChange = fVal - fOld; + /* upper limit */ + fLimit = ObVal(self->ParArray, SUPP); + fLimit -= fChange; + ObParSet(self->ParArray, self->name, "softupperlim", fLimit, pCon); + /* lower limit */ + fLimit = ObVal(self->ParArray, SLOW); + fLimit -= fChange; + ObParSet(self->ParArray, self->name, "softlowerlim", fLimit, pCon); + SCparChange(pCon); + InvokeCallBack(self->pCall, HDBVAL, self); + + return 1; + } + + iRet = ObParSet(self->ParArray, self->name, name, fVal, pCon); + if (strcmp(name, "sign") == 0) { + if ((absf(fVal) - 1.0) > 0.01) { + SCWrite(pCon, "ERROR: Invalid Sign Value", eError); return 0; } - - /* Boundaries OK, send command */ - self->posFaultCount = 0; - self->retryCount = 0; - self->stopped = 0; - self->fTarget = fHard; - InvokeCallBack(self->pCall,HDBVAL,self); - self->posCount = 0; - iRet = self->pDriver->RunTo(self->pDriver,fHard); - if(iRet != OKOK) - { /* try three times to fix it */ - for(i = 0; (i < 3) && (iRet != OKOK); i++) - { - self->pDriver->GetError(self->pDriver,&iCode, pError,131); - sprintf(pBueffel,"WARNING: Trying to fix: %s",pError); - SCWrite(pCon,pBueffel,eWarning); - iRet = self->pDriver->TryAndFixIt(self->pDriver,iCode, fHard); - switch(iRet) - { - case MOTFAIL: - SCWrite(pCon,pError,eError); - SCWrite(pCon,"\n",eError); - SCSetInterrupt(pCon,(int)ObVal(self->ParArray,INT)); - return HWFault; - case MOTREDO: - iRet = self->pDriver->RunTo(self->pDriver,fHard); - if(iRet == OKOK) - { - return OKOK; - } - break; - case MOTOK: - return OKOK; - break; - } - } - /* tried three times, refuses to work */ - SCWrite(pCon,pError,eError); - SCWrite(pCon,"\n",eError); - SCSetInterrupt(pCon,(int)ObVal(self->ParArray,INT)); - return HWFault; + if (fVal < 0.0) { + ObParInit(self->ParArray, SLOW, "softlowerlim", + self->pDriver->fUpper * fVal, usUser); + ObParInit(self->ParArray, SUPP, "softupperlim", + self->pDriver->fLower * fVal, usUser); + ObParInit(self->ParArray, SZERO, "softzero", ZEROINACTIVE, usUser); } - return OKOK; } -/*---------------------------------------------------------------------------*/ - pMotor MotorInit(char *drivername, char *name, MotorDriver *pDriv) - { - pMotor pM = NULL; - - assert(drivername); - assert(pDriv); - assert(name); - - /* get memory */ - pM = (pMotor)malloc(sizeof(Motor)); - if(!pM) - { - return NULL; - } - - - /* create and initialize parameters */ - pM->ParArray = ObParCreate(MOTOBPARLENGTH); - if(!pM->ParArray) - { - free(pM); - return NULL; - } - ObParInit(pM->ParArray,SLOW,"softlowerlim",pDriv->fLower,usUser); - ObParInit(pM->ParArray,SUPP,"softupperlim",pDriv->fUpper,usUser); - ObParInit(pM->ParArray,SZERO,"softzero",ZEROINACTIVE,usUser); - ObParInit(pM->ParArray,FIX,"fixed",-1,usUser); - ObParInit(pM->ParArray,INT,"interruptmode",INTCONT,usMugger); - ObParInit(pM->ParArray,PREC,"precision",0.01,usMugger); - ObParInit(pM->ParArray,USRIGHTS,"accesscode",(float)usUser,usMugger); - ObParInit(pM->ParArray,SIGN,"sign",1.0,usMugger); - ObParInit(pM->ParArray,ECOUNT,"failafter",3.0,usMugger); - ObParInit(pM->ParArray,POSCOUNT,"maxretry",3.0,usMugger); - ObParInit(pM->ParArray,IGNOREFAULT,"ignorefault",0.0,usMugger); - ObParInit(pM->ParArray,MOVECOUNT,"movecount",10.0,usMugger); - pDriv->GetPosition(pDriv,&(pM->fPosition)); - pM->fTarget = pM->fPosition; - pM->endScriptID = 0; + InvokeCallBack(self->pCall, HDBVAL, self); + SCparChange(pCon); - /* copy arguments */ - pM->pDriver = pDriv; - pM->drivername = strdup(drivername); - pM->name = strdup(name); - - - /* initialise object descriptor */ - pM->pDescriptor = CreateDescriptor("Motor"); - if(!pM->pDescriptor) - { - ObParDelete(pM->ParArray); - free(pM); - return NULL; - } - pM->pDescriptor->GetInterface = MotorGetInterface; - pM->pDescriptor->SaveStatus = MotorSaveStatus; - - /* initialise Drivable interface */ - pM->pDrivInt = CreateDrivableInterface(); - if(!pM->pDrivInt) - { - DeleteDescriptor(pM->pDescriptor); - ObParDelete(pM->ParArray); - free(pM); - return NULL; - } - pM->pDrivInt->SetValue = MotorRunImpl; - pM->pDrivInt->CheckLimits = MotorLimits; - pM->pDrivInt->CheckStatus = MotorStatus; - pM->pDrivInt->GetValue = MotorGetValue; - pM->pDrivInt->Halt = MotorHalt; - - /* initialize function pointers */ - pM->MotorGetPar = MotorGetParImpl; - pM->MotorSetPar = MotorSetParImpl; - pM->MotorGetHardPosition = MotorGetHardPositionImpl; - - /* initialise callback interface */ - pM->pCall = CreateCallBackInterface(); - if(!pM->pCall) - { - MotorKill(pM); - return NULL; - } - - /* done */ - return pM; - } -/*--------------------------------------------------------------------------*/ -long MotorRun(void *data, SConnection *pCon, float fNew) -{ - pMotor self = (pMotor)data; - - return self->pDrivInt->SetValue(data,pCon,fNew); + return iRet; } + +/*------------------------------------------------------------------------*/ +static int MotorGetHardPositionImpl(pMotor self, SConnection * pCon, + float *fHard) +{ + int iRet, iCode; + float fVal; + char pBueffel[512], pError[256]; + + assert(self); + assert(pCon); + + iRet = self->pDriver->GetPosition(self->pDriver, &fVal); + if (iRet == OKOK) { /* all went well, the exception */ + *fHard = fVal; + return 1; + } else { /* a problem, the usual case: try fix the problem */ + /* no point in trying this three times */ + self->pDriver->GetError(self->pDriver, &iCode, pError, 255); + iRet = self->pDriver->TryAndFixIt(self->pDriver, iCode, fVal); + sprintf(pBueffel, "WARNING: Trying to fix %s", pError); + SCWrite(pCon, pBueffel, eWarning); + switch (iRet) { + case MOTFAIL: + sprintf(pBueffel, "ERROR: cannot fix motor %s", self->name); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, (int) ObVal(self->ParArray, INT)); + *fHard = fVal; + return 0; + case MOTOK: + case MOTREDO: + iRet = self->pDriver->GetPosition(self->pDriver, &fVal); + if (iRet) { + *fHard = fVal * ObVal(self->ParArray, SIGN); + return 1; + } else { + sprintf(pBueffel, "ERROR: cannot fix motor %s", self->name); + SCSetInterrupt(pCon, (int) ObVal(self->ParArray, INT)); + SCWrite(pCon, pBueffel, eError); + *fHard = fVal; + return 0; + } + } + } + *fHard = fVal * ObVal(self->ParArray, SIGN); + return 0; +} + +/*---------------------------------------------------------------------------*/ +static long MotorRunImpl(void *sulf, SConnection * pCon, float fNew) +{ + float fHard; + int i, iRet, iCode; + char pBueffel[512]; + char pError[132]; + pMotor self; + long lTime; + float fDelta; + + self = (pMotor) (sulf); + assert(self); + assert(pCon); + + /* check if I'am allowed to move this motor */ + if (!SCMatchRights(pCon, (int) ObVal(self->ParArray, USRIGHTS))) { + sprintf(pBueffel, "ERROR: You are not authorised to move motor %s", + self->name); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, eAbortBatch); + return 0; + } + + /* check boundaries first */ + iRet = MotorCheckBoundaryImpl(self, fNew, &fHard, pError, 131); + if (!iRet) { + snprintf(pBueffel, 511, "ERROR: %s", pError); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, eAbortOperation); + return 0; + } + + /* check if the bad motor flag is set */ + if ((int) ObVal(self->ParArray, IGNOREFAULT) > 0) { + snprintf(pBueffel, 511, "WARNING: motor %s is unreliable", self->name); + SCWrite(pCon, pBueffel, eWarning); + self->pDrivInt->iErrorCount = 0; + } + + /* check our error count and interrupt if to much */ + iCode = (int) ObVal(self->ParArray, ECOUNT); + if (self->pDrivInt->iErrorCount > iCode) { + /* big alarm */ + ServerWriteGlobal("ERROR: !!! MOTOR ALARM !!! MOTOR ALARM !!!", + eError); + sprintf(pBueffel, + "ERROR: too many position errors counted at motor %s", + self->name); + ServerWriteGlobal(pBueffel, eError); + SCSetInterrupt(pCon, eAbortBatch); + self->pDrivInt->iErrorCount = 0; + return 0; + } + + /* Boundaries OK, send command */ + self->posFaultCount = 0; + self->retryCount = 0; + self->stopped = 0; + self->fTarget = fHard; + InvokeCallBack(self->pCall, HDBVAL, self); + self->posCount = 0; + iRet = self->pDriver->RunTo(self->pDriver, fHard); + if (iRet != OKOK) { /* try three times to fix it */ + for (i = 0; (i < 3) && (iRet != OKOK); i++) { + self->pDriver->GetError(self->pDriver, &iCode, pError, 131); + sprintf(pBueffel, "WARNING: Trying to fix: %s", pError); + SCWrite(pCon, pBueffel, eWarning); + iRet = self->pDriver->TryAndFixIt(self->pDriver, iCode, fHard); + switch (iRet) { + case MOTFAIL: + SCWrite(pCon, pError, eError); + SCWrite(pCon, "\n", eError); + SCSetInterrupt(pCon, (int) ObVal(self->ParArray, INT)); + return HWFault; + case MOTREDO: + iRet = self->pDriver->RunTo(self->pDriver, fHard); + if (iRet == OKOK) { + return OKOK; + } + break; + case MOTOK: + return OKOK; + break; + } + } + /* tried three times, refuses to work */ + SCWrite(pCon, pError, eError); + SCWrite(pCon, "\n", eError); + SCSetInterrupt(pCon, (int) ObVal(self->ParArray, INT)); + return HWFault; + } + return OKOK; +} + +/*---------------------------------------------------------------------------*/ +pMotor MotorInit(char *drivername, char *name, MotorDriver * pDriv) +{ + pMotor pM = NULL; + + assert(drivername); + assert(pDriv); + assert(name); + + /* get memory */ + pM = (pMotor) malloc(sizeof(Motor)); + if (!pM) { + return NULL; + } + + + /* create and initialize parameters */ + pM->ParArray = ObParCreate(MOTOBPARLENGTH); + if (!pM->ParArray) { + free(pM); + return NULL; + } + ObParInit(pM->ParArray, SLOW, "softlowerlim", pDriv->fLower, usUser); + ObParInit(pM->ParArray, SUPP, "softupperlim", pDriv->fUpper, usUser); + ObParInit(pM->ParArray, SZERO, "softzero", ZEROINACTIVE, usUser); + ObParInit(pM->ParArray, FIX, "fixed", -1, usUser); + ObParInit(pM->ParArray, INT, "interruptmode", INTCONT, usMugger); + ObParInit(pM->ParArray, PREC, "precision", 0.01, usMugger); + ObParInit(pM->ParArray, USRIGHTS, "accesscode", (float) usUser, + usMugger); + ObParInit(pM->ParArray, SIGN, "sign", 1.0, usMugger); + ObParInit(pM->ParArray, ECOUNT, "failafter", 3.0, usMugger); + ObParInit(pM->ParArray, POSCOUNT, "maxretry", 3.0, usMugger); + ObParInit(pM->ParArray, IGNOREFAULT, "ignorefault", 0.0, usMugger); + ObParInit(pM->ParArray, MOVECOUNT, "movecount", 10.0, usMugger); + pDriv->GetPosition(pDriv, &(pM->fPosition)); + pM->fTarget = pM->fPosition; + pM->endScriptID = 0; + + /* copy arguments */ + pM->pDriver = pDriv; + pM->drivername = strdup(drivername); + pM->name = strdup(name); + + + /* initialise object descriptor */ + pM->pDescriptor = CreateDescriptor("Motor"); + if (!pM->pDescriptor) { + ObParDelete(pM->ParArray); + free(pM); + return NULL; + } + pM->pDescriptor->GetInterface = MotorGetInterface; + pM->pDescriptor->SaveStatus = MotorSaveStatus; + + /* initialise Drivable interface */ + pM->pDrivInt = CreateDrivableInterface(); + if (!pM->pDrivInt) { + DeleteDescriptor(pM->pDescriptor); + ObParDelete(pM->ParArray); + free(pM); + return NULL; + } + pM->pDrivInt->SetValue = MotorRunImpl; + pM->pDrivInt->CheckLimits = MotorLimits; + pM->pDrivInt->CheckStatus = MotorStatus; + pM->pDrivInt->GetValue = MotorGetValue; + pM->pDrivInt->Halt = MotorHalt; + + /* initialize function pointers */ + pM->MotorGetPar = MotorGetParImpl; + pM->MotorSetPar = MotorSetParImpl; + pM->MotorGetHardPosition = MotorGetHardPositionImpl; + + /* initialise callback interface */ + pM->pCall = CreateCallBackInterface(); + if (!pM->pCall) { + MotorKill(pM); + return NULL; + } + + /* done */ + return pM; +} + +/*--------------------------------------------------------------------------*/ +long MotorRun(void *data, SConnection * pCon, float fNew) +{ + pMotor self = (pMotor) data; + + return self->pDrivInt->SetValue(data, pCon, fNew); +} + /*--------------------------------------------------------------------------*/ int MotorCheckBoundary(pMotor self, float fVal, float *fHard, char *error, int iErrLen) { - return self->pDrivInt->CheckLimits(self,fVal,error,iErrLen); + return self->pDrivInt->CheckLimits(self, fVal, error, iErrLen); } + /*--------------------------------------------------------------------------*/ -int MotorGetSoftPosition(pMotor self,SConnection *pCon, float *fVal) +int MotorGetSoftPosition(pMotor self, SConnection * pCon, float *fVal) { - float myVal; - myVal = self->pDrivInt->GetValue(self,pCon); - *fVal = myVal; - if(myVal <= -9999999.99){ - return 0; - } else { - return 1; - } + float myVal; + myVal = self->pDrivInt->GetValue(self, pCon); + *fVal = myVal; + if (myVal <= -9999999.99) { + return 0; + } else { + return 1; + } } + /*--------------------------------------------------------------------------*/ extern void KillPiPiezo(void *pData); - - void MotorKill(void *self) - { - pMotor pM; - assert(self); - - pM = (pMotor)self; - - /* MotorHalt(pM); */ - - if(pM->name) - free(pM->name); - - if(pM->pDrivInt) - { - free(pM->pDrivInt); - } - - if(pM->pCall) - { - DeleteCallBackInterface(pM->pCall); - } - - /* kill driver */ - if(pM->drivername) - { - if(pM->pDriver->KillPrivate != NULL) - { - pM->pDriver->KillPrivate(pM->pDriver); - if(pM->pDriver->name != NULL) - { - free(pM->pDriver->name); - } - free(pM->pDriver); - } - free(pM->drivername); - } - - /* get rid of parameter space */ - if(pM->ParArray) - { - ObParDelete(pM->ParArray); - } - - /* kill Descriptor */ - DeleteDescriptor(pM->pDescriptor); - - free(pM); - - } + +void MotorKill(void *self) +{ + pMotor pM; + assert(self); + + pM = (pMotor) self; + + /* MotorHalt(pM); */ + + if (pM->name) + free(pM->name); + + if (pM->pDrivInt) { + free(pM->pDrivInt); + } + + if (pM->pCall) { + DeleteCallBackInterface(pM->pCall); + } + + /* kill driver */ + if (pM->drivername) { + if (pM->pDriver->KillPrivate != NULL) { + pM->pDriver->KillPrivate(pM->pDriver); + if (pM->pDriver->name != NULL) { + free(pM->pDriver->name); + } + free(pM->pDriver); + } + free(pM->drivername); + } + + /* get rid of parameter space */ + if (pM->ParArray) { + ObParDelete(pM->ParArray); + } + + /* kill Descriptor */ + DeleteDescriptor(pM->pDescriptor); + + free(pM); + +} + /*------------------------------------------------------------------------*/ - float MotorHardToSoftPosition(pMotor self, float fValue) - { - /* apply zeropoint */ - if(ObVal(self->ParArray,SIGN) < 0.) - { - fValue += ObVal(self->ParArray,SZERO); - } - else - { - fValue -= ObVal(self->ParArray,SZERO); - } - /* apply sign */ - return fValue*ObVal(self->ParArray,SIGN); +float MotorHardToSoftPosition(pMotor self, float fValue) +{ + /* apply zeropoint */ + if (ObVal(self->ParArray, SIGN) < 0.) { + fValue += ObVal(self->ParArray, SZERO); + } else { + fValue -= ObVal(self->ParArray, SZERO); } + /* apply sign */ + return fValue * ObVal(self->ParArray, SIGN); +} + /*---------------------------------------------------------------------------*/ - int MotorCheckPosition(void *sulf, SConnection *pCon) - { - float fHard; - int i, iRet, iCode; - char pBueffel[512]; - pMotor self; - - self = (pMotor)sulf; - assert(self); - assert(pCon); - - /* try to find current position */ - iRet = MotorGetHardPosition(self,pCon,&fHard); - if(iRet) - { - if(absf(fHard - self->fTarget) < ObVal(self->ParArray,PREC)) - { - self->fPosition = fHard; - return 1; - } - else - { - /* Oooopppsss error */ - return 0; - } - } - else /* error getting hold of position, MotorGetHard already tried to - solve the problem and FAILED, the fucking bastard - even messaged the connection accordingly */ - { - return -1; +int MotorCheckPosition(void *sulf, SConnection * pCon) +{ + float fHard; + int i, iRet, iCode; + char pBueffel[512]; + pMotor self; + + self = (pMotor) sulf; + assert(self); + assert(pCon); + + /* try to find current position */ + iRet = MotorGetHardPosition(self, pCon, &fHard); + if (iRet) { + if (absf(fHard - self->fTarget) < ObVal(self->ParArray, PREC)) { + self->fPosition = fHard; + return 1; + } else { + /* Oooopppsss error */ + return 0; } + } else { /* error getting hold of position, MotorGetHard already tried to + solve the problem and FAILED, the fucking bastard + even messaged the connection accordingly */ + return -1; } +} + /* -------------------------------------------------------------------------- The Factory function for creating a motor. Usage: MotorCreate name DriverName. @@ -1017,222 +975,211 @@ extern void KillPiPiezo(void *pData); PiPiezo Physik-Instrumente E-255 Piezo Controller SIM simulated motor */ - -extern MotorDriver *MakePiPiezo(Tcl_Interp *pTcl, char *pArray); - int MotorCreate(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pMotor pNew = NULL; - MotorDriver *pDriver = NULL; - char pBueffel[512]; - int iD, iRet; - Tcl_Interp *pTcl = (Tcl_Interp *)pSics->pTcl; - pSite site = NULL; +extern MotorDriver *MakePiPiezo(Tcl_Interp * pTcl, char *pArray); + +int MotorCreate(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pMotor pNew = NULL; + MotorDriver *pDriver = NULL; + char pBueffel[512]; + int iD, iRet; + Tcl_Interp *pTcl = (Tcl_Interp *) pSics->pTcl; + pSite site = NULL; + + assert(pCon); + assert(pSics); + + /* a first check */ + if (argc < 3) { + SCWrite(pCon, "Insufficient arguments for motor creation", eError); + return 0; + } + + /* create the driver */ + strtolower(argv[2]); + strtolower(argv[1]); + if (strcmp(argv[2], "sim") == 0) { + iD = argc - 3; + pDriver = CreateSIM(pCon, iD, &argv[3]); + if (!pDriver) { + return 0; + } + /* create the motor */ + pNew = MotorInit("SIM", argv[1], pDriver); + if (!pNew) { + sprintf(pBueffel, "Failure to create motor %s", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } else if (strcmp(argv[2], "tclmot") == 0) { + pDriver = CreateTclMotDriv(pCon, argc, argv); + if (!pDriver) { + return 0; + } + /* create the motor */ + pNew = MotorInit("TCLMOT", argv[1], pDriver); + if (!pNew) { + sprintf(pBueffel, "Failure to create motor %s", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } else if (strcmp(argv[2], "regress") == 0) { + pDriver = RGMakeMotorDriver(); + if (!pDriver) { + return 0; + } + /* create the motor */ + pNew = MotorInit("regress", argv[1], pDriver); + if (!pNew) { + sprintf(pBueffel, "Failure to create motor %s", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } else { + site = getSite(); + if (site != NULL) { + pNew = site->CreateMotor(pCon, argc - 1, &argv[1]); + } + if (pNew == NULL) { + sprintf(pBueffel, "Motor Type %s not recognized for motor %s", + argv[2], argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + + /* create the interpreter command */ + iRet = AddCommand(pSics, argv[1], MotorAction, MotorKill, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} - assert(pCon); - assert(pSics); - - /* a first check */ - if(argc < 3) - { - SCWrite(pCon,"Insufficient arguments for motor creation",eError); - return 0; - } - - /* create the driver */ - strtolower(argv[2]); - strtolower(argv[1]); - if (strcmp(argv[2],"sim") == 0) - { - iD = argc - 3; - pDriver = CreateSIM(pCon,iD,&argv[3]); - if(!pDriver) - { - return 0; - } - /* create the motor */ - pNew = MotorInit("SIM",argv[1],pDriver); - if(!pNew) - { - sprintf(pBueffel,"Failure to create motor %s",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - }else if (strcmp(argv[2],"tclmot") == 0) - { - pDriver = CreateTclMotDriv(pCon,argc,argv); - if(!pDriver) - { - return 0; - } - /* create the motor */ - pNew = MotorInit("TCLMOT",argv[1],pDriver); - if(!pNew) - { - sprintf(pBueffel,"Failure to create motor %s",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } else if(strcmp(argv[2],"regress") == 0) - { - pDriver = RGMakeMotorDriver(); - if(!pDriver) - { - return 0; - } - /* create the motor */ - pNew = MotorInit("regress",argv[1],pDriver); - if(!pNew) - { - sprintf(pBueffel,"Failure to create motor %s",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - else - { - site = getSite(); - if(site != NULL) - { - pNew = site->CreateMotor(pCon,argc-1,&argv[1]); - } - if(pNew == NULL) - { - sprintf(pBueffel,"Motor Type %s not recognized for motor %s", - argv[2],argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - - /* create the interpreter command */ - iRet = AddCommand(pSics,argv[1],MotorAction,MotorKill,pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } /* ----------------- some private functions used in MotorAction -------------*/ - void MotorListLL(pMotor self, SConnection *pCon) - { - char pBueffel[512]; - int i, iLen; - - iLen = ObParLength(self->ParArray); - sprintf(pBueffel,"Parameter Listing for motor %s",self->name); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%s.Position = %f\n", self->name,self->fPosition); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%s.TargetPosition = %f\n", self->name,self->fTarget); - SCWrite(pCon,pBueffel,eValue); +void MotorListLL(pMotor self, SConnection * pCon) +{ + char pBueffel[512]; + int i, iLen; - snprintf(pBueffel,511,"%s.hardlowerlim = %f",self->name, - self->pDriver->fLower); - SCWrite(pCon,pBueffel,eValue); - snprintf(pBueffel,511,"%s.hardupperlim = %f",self->name, - self->pDriver->fUpper); - SCWrite(pCon,pBueffel,eValue); - for(i = 0; i < iLen; i++) - { - sprintf(pBueffel,"%s.%s = %f\n",self->name, - self->ParArray[i].name,self->ParArray[i].fVal); - SCWrite(pCon,pBueffel,eValue); - } - - /* - list driver parameters when appropriate - */ - if(self->pDriver->ListDriverPar != NULL) - { - self->pDriver->ListDriverPar(self->pDriver,self->name, pCon); - } + iLen = ObParLength(self->ParArray); + sprintf(pBueffel, "Parameter Listing for motor %s", self->name); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%s.Position = %f\n", self->name, self->fPosition); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%s.TargetPosition = %f\n", self->name, self->fTarget); + SCWrite(pCon, pBueffel, eValue); + + snprintf(pBueffel, 511, "%s.hardlowerlim = %f", self->name, + self->pDriver->fLower); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 511, "%s.hardupperlim = %f", self->name, + self->pDriver->fUpper); + SCWrite(pCon, pBueffel, eValue); + for (i = 0; i < iLen; i++) { + sprintf(pBueffel, "%s.%s = %f\n", self->name, + self->ParArray[i].name, self->ParArray[i].fVal); + SCWrite(pCon, pBueffel, eValue); } + + /* + list driver parameters when appropriate + */ + if (self->pDriver->ListDriverPar != NULL) { + self->pDriver->ListDriverPar(self->pDriver, self->name, pCon); + } +} + /*--------------------------------------------------------------------------*/ - void MotorReset(pMotor pM) - { - ObParInit(pM->ParArray,SLOW,"softlowerlim",pM->pDriver->fLower,usUser); - ObParInit(pM->ParArray,SUPP,"softupperlim",pM->pDriver->fUpper,usUser); - ObParInit(pM->ParArray,SZERO,"softzero",ZEROINACTIVE,usUser); - ObParInit(pM->ParArray,FIX,"fixed",-1,usUser); - } +void MotorReset(pMotor pM) +{ + ObParInit(pM->ParArray, SLOW, "softlowerlim", pM->pDriver->fLower, + usUser); + ObParInit(pM->ParArray, SUPP, "softupperlim", pM->pDriver->fUpper, + usUser); + ObParInit(pM->ParArray, SZERO, "softzero", ZEROINACTIVE, usUser); + ObParInit(pM->ParArray, FIX, "fixed", -1, usUser); +} + /*------------------------------------------------------------------------*/ - typedef struct { - char *pName; - SConnection *pCon; - float lastValue; - } MotInfo, *pMotInfo; +typedef struct { + char *pName; + SConnection *pCon; + float lastValue; +} MotInfo, *pMotInfo; /*-----------------------------------------------------------------------*/ - static void KillInfo(void *pData) - { - pMotInfo self = NULL; - - assert(pData); - self = (pMotInfo)pData; - if(self->pName) - { - free(self->pName); - } - if(self->pCon != NULL) - { - SCDeleteConnection(self->pCon); - } - free(self); - } -/*------------------- The CallBack function for interest ------------------*/ - static int InterestCallback(int iEvent, void *pEvent, void *pUser) - { - pMotInfo pInfo = NULL; - char pBueffel[80]; - MotCallback *psCall; - - assert(pEvent); - assert(pUser); - - psCall = (MotCallback *)pEvent; - pInfo = (MotInfo *)pUser; +static void KillInfo(void *pData) +{ + pMotInfo self = NULL; - if(!SCisConnected(pInfo->pCon)){ - return -1; - } - - if (pInfo->lastValue != psCall->fVal) { - pInfo->lastValue = psCall->fVal; - (pInfo->pCon)->conEventType=POSITION; - sprintf(pBueffel,"%s.position = %f ", pInfo->pName, pInfo->lastValue); - SCWrite(pInfo->pCon,pBueffel,eEvent); - } - return 1; - } -/*------------------------------------------------------------------------*/ - static void KillScript(void *pData) - { - if(pData != NULL) - { - free(pData); - } + assert(pData); + self = (pMotInfo) pData; + if (self->pName) { + free(self->pName); } + if (self->pCon != NULL) { + SCDeleteConnection(self->pCon); + } + free(self); +} + +/*------------------- The CallBack function for interest ------------------*/ +static int InterestCallback(int iEvent, void *pEvent, void *pUser) +{ + pMotInfo pInfo = NULL; + char pBueffel[80]; + MotCallback *psCall; + + assert(pEvent); + assert(pUser); + + psCall = (MotCallback *) pEvent; + pInfo = (MotInfo *) pUser; + + if (!SCisConnected(pInfo->pCon)) { + return -1; + } + + if (pInfo->lastValue != psCall->fVal) { + pInfo->lastValue = psCall->fVal; + (pInfo->pCon)->conEventType = POSITION; + sprintf(pBueffel, "%s.position = %f ", pInfo->pName, pInfo->lastValue); + SCWrite(pInfo->pCon, pBueffel, eEvent); + } + return 1; +} + +/*------------------------------------------------------------------------*/ +static void KillScript(void *pData) +{ + if (pData != NULL) { + free(pData); + } +} + /*------------------------ The endscript callback function ----------------*/ - static int EndScriptCallback(int iEvent, void *pEvent, void *pUser) - { - char *pScript = NULL; - MotCallback *psCall; - char pCommand[1024]; - int iRet; +static int EndScriptCallback(int iEvent, void *pEvent, void *pUser) +{ + char *pScript = NULL; + MotCallback *psCall; + char pCommand[1024]; + int iRet; - assert(pEvent); - assert(pUser); - - psCall = (MotCallback *)pEvent; - pScript = (char *)pUser; + assert(pEvent); + assert(pUser); + + psCall = (MotCallback *) pEvent; + pScript = (char *) pUser; + + sprintf(pCommand, "%s %f", pScript, psCall->fVal); + iRet = Tcl_Eval(pServ->pSics->pTcl, pCommand); + return iRet; +} - sprintf(pCommand,"%s %f",pScript,psCall->fVal); - iRet = Tcl_Eval(pServ->pSics->pTcl,pCommand); - return iRet; - } /*---------------------------------------------------------------------------- The wrapper function for a motor. Commands currently supported are: @@ -1245,214 +1192,177 @@ extern MotorDriver *MakePiPiezo(Tcl_Interp *pTcl, char *pArray); motorname endscript : script to call when motor finishes driving -----------------------------------------------------------------------------*/ - int MotorAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - TokenList *pList = NULL; - TokenList *pCurrent; - TokenList *pName; - int iRet; - pMotor self; - float fValue; - long lID; - pMotInfo pMoti = NULL; - - assert(pCon); - assert(pSics); - assert(pData); - - self = (pMotor)pData; - - /* create Tokenlist */ - argtolower(argc,argv); - pList = SplitArguments(argc,argv); - if(!pList) - { - SCWrite(pCon,"Error parsing argument list in MotorAction",eError); - return 0; - } - - /* first argument can be one of list, reset or parameter name */ - pCurrent = pList->pNext; - if(!pCurrent) /* no argument, print value */ - { - iRet = MotorGetSoftPosition(self,pCon,&fValue); - if(!iRet) - { - sprintf(pBueffel,"Error obtaining position for %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return 0; - } - sprintf(pBueffel,"%s = %f",argv[0],fValue); - SCWrite(pCon,pBueffel,eValue); - DeleteTokenList(pList); - return 1; - } - - /* check for list */ - if(strcmp(pCurrent->text,"list") == 0) - { - MotorListLL(self,pCon); - DeleteTokenList(pList); - return 1; - } /* check for reset */ - else if(strcmp(pCurrent->text,"reset") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - sprintf(pBueffel,"Insufficient privilege to reset %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return 0; - } - MotorReset(self); - DeleteTokenList(pList); - SCSendOK(pCon); - return 1; - } - else if(strcmp(pCurrent->text,"interest") == 0) /* interest */ - { - pMoti = (pMotInfo)malloc(sizeof(MotInfo)); - if(!pMoti) - { - SCWrite(pCon,"ERROR: out of memory in motor.c",eError); - return 0; - } - pMoti->pName = strdup(argv[0]); - pMoti->pCon = SCCopyConnection(pCon); - iRet = MotorGetSoftPosition(self,pCon,&fValue); - if(!iRet) - { - sprintf(pBueffel,"Failed to register interest, Reason:Error obtaining current position for %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return 0; - } - pMoti->lastValue = fValue; +int MotorAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512]; + TokenList *pList = NULL; + TokenList *pCurrent; + TokenList *pName; + int iRet; + pMotor self; + float fValue; + long lID; + pMotInfo pMoti = NULL; - lID = RegisterCallback(self->pCall, MOTDRIVE, InterestCallback, - pMoti, KillInfo); - DeleteTokenList(pList); - SCSendOK(pCon); - return 1; - } - else if(strcmp(pCurrent->text,"uninterest") == 0) - { - RemoveCallbackCon(self->pCall,pCon); - SCSendOK(pCon); - DeleteTokenList(pList); - return 1; - } - else if(strcmp(pCurrent->text,"endscript") == 0) /* endscript */ - { - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - if(self->endScriptID != 0) - { - RemoveCallback(self->pCall, self->endScriptID); - self->endScriptID = 0; - } - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - SCWrite(pCon,"ERROR: scriptname argument missing",eError); - return 0; - } - self->endScriptID = - RegisterCallback(self->pCall, MOTEND, EndScriptCallback, - strdup(pCurrent->text), KillScript); - DeleteTokenList(pList); - SCSendOK(pCon); - return 1; - } - else /* one of the parameter commands or error left now */ - { - pName = pCurrent; - pCurrent = pCurrent->pNext; - if(!pCurrent) /* no third par: print val */ - { - /* deal with position first */ - if(strcmp(pName->text,"position") == 0) - { - iRet = MotorGetSoftPosition(self,pCon,&fValue); - if(!iRet) - { - sprintf(pBueffel,"Error obtaining position for %s",argv[0]); - SCWrite(pCon,pBueffel,eValue); - DeleteTokenList(pList); - return 0; - } - sprintf(pBueffel,"%s.SoftPosition = %f",argv[0],fValue); - SCWrite(pCon,pBueffel,eValue); - DeleteTokenList(pList); - return 1; - } - else if(strcmp(pName->text,"hardposition") == 0) - { - iRet = MotorGetHardPosition(self,pCon,&fValue); - if(!iRet) { - sprintf(pBueffel,"Error obtaining position for %s",argv[0]); - SCWrite(pCon,pBueffel,eValue); - DeleteTokenList(pList); - return 0; - } - sprintf(pBueffel,"%s.HardPosition = %f",argv[0],fValue); - SCWrite(pCon,pBueffel,eValue); - DeleteTokenList(pList); - return 1; - } - iRet = MotorGetPar(self,pName->text,&fValue); - if(!iRet) - { - sprintf(pBueffel,"Parameter %s not found ",pName->text); - SCWrite(pCon,pBueffel,eValue); - DeleteTokenList(pList); - return 0; - } - else - { - sprintf(pBueffel, "%s.%s = %f",self->name,pName->text,fValue); - SCWrite(pCon,pBueffel,eValue); - DeleteTokenList(pList); - return 1; - } - } - else /* set */ - { /* set command */ - /* parameter must be numerical value */ - if(pCurrent->Type == eInt) - { - fValue = (float)pCurrent->iVal; - } - else if(pCurrent->Type == eFloat) - { - fValue = pCurrent->fVal; - } - else - { - sprintf(pBueffel,"Wrong argument type for %s %s set", - argv[0],pName->text); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return 0; - } - iRet = MotorSetPar(self,pCon,pName->text,fValue); - DeleteTokenList(pList); - if(iRet) - SCSendOK(pCon); - return iRet; - } - } - return 0; + assert(pCon); + assert(pSics); + assert(pData); + + self = (pMotor) pData; + + /* create Tokenlist */ + argtolower(argc, argv); + pList = SplitArguments(argc, argv); + if (!pList) { + SCWrite(pCon, "Error parsing argument list in MotorAction", eError); + return 0; } + /* first argument can be one of list, reset or parameter name */ + pCurrent = pList->pNext; + if (!pCurrent) { /* no argument, print value */ + iRet = MotorGetSoftPosition(self, pCon, &fValue); + if (!iRet) { + sprintf(pBueffel, "Error obtaining position for %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return 0; + } + sprintf(pBueffel, "%s = %f", argv[0], fValue); + SCWrite(pCon, pBueffel, eValue); + DeleteTokenList(pList); + return 1; + } + /* check for list */ + if (strcmp(pCurrent->text, "list") == 0) { + MotorListLL(self, pCon); + DeleteTokenList(pList); + return 1; + } /* check for reset */ + else if (strcmp(pCurrent->text, "reset") == 0) { + if (!SCMatchRights(pCon, usUser)) { + sprintf(pBueffel, "Insufficient privilege to reset %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return 0; + } + MotorReset(self); + DeleteTokenList(pList); + SCSendOK(pCon); + return 1; + } else if (strcmp(pCurrent->text, "interest") == 0) { /* interest */ + pMoti = (pMotInfo) malloc(sizeof(MotInfo)); + if (!pMoti) { + SCWrite(pCon, "ERROR: out of memory in motor.c", eError); + return 0; + } + pMoti->pName = strdup(argv[0]); + pMoti->pCon = SCCopyConnection(pCon); + iRet = MotorGetSoftPosition(self, pCon, &fValue); + if (!iRet) { + sprintf(pBueffel, + "Failed to register interest, Reason:Error obtaining current position for %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return 0; + } + pMoti->lastValue = fValue; + lID = RegisterCallback(self->pCall, MOTDRIVE, InterestCallback, + pMoti, KillInfo); + DeleteTokenList(pList); + SCSendOK(pCon); + return 1; + } else if (strcmp(pCurrent->text, "uninterest") == 0) { + RemoveCallbackCon(self->pCall, pCon); + SCSendOK(pCon); + DeleteTokenList(pList); + return 1; + } else if (strcmp(pCurrent->text, "endscript") == 0) { /* endscript */ + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + if (self->endScriptID != 0) { + RemoveCallback(self->pCall, self->endScriptID); + self->endScriptID = 0; + } + pCurrent = pCurrent->pNext; + if (!pCurrent) { + SCWrite(pCon, "ERROR: scriptname argument missing", eError); + return 0; + } + self->endScriptID = + RegisterCallback(self->pCall, MOTEND, EndScriptCallback, + strdup(pCurrent->text), KillScript); + DeleteTokenList(pList); + SCSendOK(pCon); + return 1; + } else { /* one of the parameter commands or error left now */ - - + pName = pCurrent; + pCurrent = pCurrent->pNext; + if (!pCurrent) { /* no third par: print val */ + /* deal with position first */ + if (strcmp(pName->text, "position") == 0) { + iRet = MotorGetSoftPosition(self, pCon, &fValue); + if (!iRet) { + sprintf(pBueffel, "Error obtaining position for %s", argv[0]); + SCWrite(pCon, pBueffel, eValue); + DeleteTokenList(pList); + return 0; + } + sprintf(pBueffel, "%s.SoftPosition = %f", argv[0], fValue); + SCWrite(pCon, pBueffel, eValue); + DeleteTokenList(pList); + return 1; + } else if (strcmp(pName->text, "hardposition") == 0) { + iRet = MotorGetHardPosition(self, pCon, &fValue); + if (!iRet) { + sprintf(pBueffel, "Error obtaining position for %s", argv[0]); + SCWrite(pCon, pBueffel, eValue); + DeleteTokenList(pList); + return 0; + } + sprintf(pBueffel, "%s.HardPosition = %f", argv[0], fValue); + SCWrite(pCon, pBueffel, eValue); + DeleteTokenList(pList); + return 1; + } + iRet = MotorGetPar(self, pName->text, &fValue); + if (!iRet) { + sprintf(pBueffel, "Parameter %s not found ", pName->text); + SCWrite(pCon, pBueffel, eValue); + DeleteTokenList(pList); + return 0; + } else { + sprintf(pBueffel, "%s.%s = %f", self->name, pName->text, fValue); + SCWrite(pCon, pBueffel, eValue); + DeleteTokenList(pList); + return 1; + } + } else { /* set */ + /* set command */ + /* parameter must be numerical value */ + if (pCurrent->Type == eInt) { + fValue = (float) pCurrent->iVal; + } else if (pCurrent->Type == eFloat) { + fValue = pCurrent->fVal; + } else { + sprintf(pBueffel, "Wrong argument type for %s %s set", + argv[0], pName->text); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return 0; + } + iRet = MotorSetPar(self, pCon, pName->text, fValue); + DeleteTokenList(pList); + if (iRet) + SCSendOK(pCon); + return iRet; + } + } + return 0; +} diff --git a/motor.h b/motor.h index e5f11599..145e33ac 100644 --- a/motor.h +++ b/motor.h @@ -16,63 +16,64 @@ #include "hipadaba.h" #define MOTOBPARLENGTH 12 - typedef struct __Motor { - pObjectDescriptor pDescriptor; - pHdb objectNode; - pIDrivable pDrivInt; - pICallBack pCall; - int (*MotorSetPar)(struct __Motor *self, SConnection *pCon, char *name, float fVal); - int (*MotorGetPar)(struct __Motor *self, char *name, float *fVal); - int (*MotorGetHardPosition)(struct __Motor *self, SConnection *pCon, float *fVal); - char *drivername; - char *name; - MotorDriver *pDriver; - float fTarget; - float fPosition; - long endScriptID; - int posCount; /* counter for calling the - motor callback */ - int retryCount; /* for retries in status */ - int posFaultCount; - int stopped; - int errorCount; - ObPar *ParArray; - void *pPrivate; - void (*KillPrivate)(void *); - } Motor; - typedef Motor *pMotor; +typedef struct __Motor { + pObjectDescriptor pDescriptor; + pHdb objectNode; + pIDrivable pDrivInt; + pICallBack pCall; + int (*MotorSetPar) (struct __Motor * self, SConnection * pCon, + char *name, float fVal); + int (*MotorGetPar) (struct __Motor * self, char *name, float *fVal); + int (*MotorGetHardPosition) (struct __Motor * self, SConnection * pCon, + float *fVal); + char *drivername; + char *name; + MotorDriver *pDriver; + float fTarget; + float fPosition; + long endScriptID; + int posCount; /* counter for calling the + motor callback */ + int retryCount; /* for retries in status */ + int posFaultCount; + int stopped; + int errorCount; + ObPar *ParArray; + void *pPrivate; + void (*KillPrivate) (void *); +} Motor; +typedef Motor *pMotor; /*------------------------------------------------------------------------ a tiny structure used in CallBack work --------------------------------------------------------------------------*/ typedef struct { - float fVal; - char *pName; - } MotCallback; -/*-------------------------------------------------------------------------*/ + float fVal; + char *pName; +} MotCallback; +/*-------------------------------------------------------------------------*/ /* parameter management */ - int MotorGetPar(pMotor self, char *name, float *fVal); - int MotorSetPar(pMotor self, SConnection *pCon, char *name, float fVal); +int MotorGetPar(pMotor self, char *name, float *fVal); +int MotorSetPar(pMotor self, SConnection * pCon, char *name, float fVal); /* driving */ - long MotorRun(void *self, SConnection *pCon, float fNew); - int MotorCheckBoundary(pMotor self, float fVal, float *fHard, - char *error, int iErrLen); - +long MotorRun(void *self, SConnection * pCon, float fNew); +int MotorCheckBoundary(pMotor self, float fVal, float *fHard, + char *error, int iErrLen); + /* Where are we ? */ - int MotorGetSoftPosition(pMotor self,SConnection *pCon, float *fVal); - int MotorGetHardPosition(pMotor self,SConnection *pCon, float *fVal); - +int MotorGetSoftPosition(pMotor self, SConnection * pCon, float *fVal); +int MotorGetHardPosition(pMotor self, SConnection * pCon, float *fVal); + /* creation */ - int MotorCreate(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - pMotor MotorInit(char *drivername,char *name, MotorDriver *pDriv); - void MotorKill(void *self); +int MotorCreate(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +pMotor MotorInit(char *drivername, char *name, MotorDriver * pDriv); +void MotorKill(void *self); /* interface to interpreter */ - int MotorAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - pMotor FindMotor(SicsInterp *pSics, char *name); - -#endif +int MotorAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +pMotor FindMotor(SicsInterp * pSics, char *name); +#endif diff --git a/motorlist.c b/motorlist.c index 60c3ff77..2f740597 100644 --- a/motorlist.c +++ b/motorlist.c @@ -11,54 +11,57 @@ #include "lld.h" #include "motor.h" /*---------------------------------------------------------------*/ -static void *MOLIGetInterface(void *data, int iD){ - return NULL; +static void *MOLIGetInterface(void *data, int iD) +{ + return NULL; } + /*---------------------------------------------------------------- This routine can return either OKOK or HWFault when thing go wrong. However, the return value of Halt is usually ignored! ------------------------------------------------------------------*/ -static int MOLIHalt(void *data) { - int self = 0, iRet; - MotControl tuktuk; - - self = *(int *)data; +static int MOLIHalt(void *data) +{ + int self = 0, iRet; + MotControl tuktuk; - iRet = LLDnodePtr2First(self); - while(iRet != 0) - { - LLDnodeDataTo(self,&tuktuk); - tuktuk.pDriv->Halt(tuktuk.data); - iRet = LLDnodePtr2Next(self); - } - return OKOK; + self = *(int *) data; + + iRet = LLDnodePtr2First(self); + while (iRet != 0) { + LLDnodeDataTo(self, &tuktuk); + tuktuk.pDriv->Halt(tuktuk.data); + iRet = LLDnodePtr2Next(self); + } + return OKOK; } + /*---------------------------------------------------------------- This routine can return either 1 or 0. 1 means the position can be reached, 0 NOT If 0, error shall contain up to errlen characters of information about which limit was violated ------------------------------------------------------------------*/ -static int MOLICheckLimits(void *data, float val, - char *error, int errlen){ - int self = 0, iRet, test, retVal = 1; - MotControl tuktuk; - - self = *(int *)data; +static int MOLICheckLimits(void *data, float val, char *error, int errlen) +{ + int self = 0, iRet, test, retVal = 1; + MotControl tuktuk; - iRet = LLDnodePtr2First(self); - while(iRet != 0) - { - LLDnodeDataTo(self,&tuktuk); - test = tuktuk.pDriv->CheckLimits(tuktuk.data,val, error, errlen); - if(test == 0){ - retVal = 0; - } - iRet = LLDnodePtr2Next(self); + self = *(int *) data; + + iRet = LLDnodePtr2First(self); + while (iRet != 0) { + LLDnodeDataTo(self, &tuktuk); + test = tuktuk.pDriv->CheckLimits(tuktuk.data, val, error, errlen); + if (test == 0) { + retVal = 0; } + iRet = LLDnodePtr2Next(self); + } - return retVal; + return retVal; } + /*---------------------------------------------------------------- This routine can return 0 when a limit problem occurred OKOK when the motor was successfully started @@ -68,27 +71,28 @@ static int MOLICheckLimits(void *data, float val, to start the motor in question val is the value to drive the motor too ------------------------------------------------------------------*/ -static long MOLISetValue(void *data, SConnection *pCon, float val){ - int self = 0, iRet, test; - MotControl tuktuk; - - self = *(int *)data; +static long MOLISetValue(void *data, SConnection * pCon, float val) +{ + int self = 0, iRet, test; + MotControl tuktuk; - iRet = LLDnodePtr2First(self); - while(iRet != 0) - { - LLDnodeDataTo(self,&tuktuk); - test = tuktuk.pDriv->SetValue(tuktuk.data,pCon,tuktuk.target); - if(test != 1) { - return test; - } else { - tuktuk.running = 1; - LLDnodeDataFrom(self,&tuktuk); - } - iRet = LLDnodePtr2Next(self); + self = *(int *) data; + + iRet = LLDnodePtr2First(self); + while (iRet != 0) { + LLDnodeDataTo(self, &tuktuk); + test = tuktuk.pDriv->SetValue(tuktuk.data, pCon, tuktuk.target); + if (test != 1) { + return test; + } else { + tuktuk.running = 1; + LLDnodeDataFrom(self, &tuktuk); } - return OKOK; + iRet = LLDnodePtr2Next(self); + } + return OKOK; } + /*---------------------------------------------------------------- Checks the status of a running motor. Possible return values HWBusy The motor is still running @@ -99,167 +103,176 @@ static long MOLISetValue(void *data, SConnection *pCon, float val){ For real motors CheckStatus again shall try hard to fix any issues with the motor ------------------------------------------------------------------*/ -static int MOLICheckStatus(void *data, SConnection *pCon){ - int self = 0, iRet, status, result = HWIdle; - MotControl tuktuk; - - self = *(int *)data; +static int MOLICheckStatus(void *data, SConnection * pCon) +{ + int self = 0, iRet, status, result = HWIdle; + MotControl tuktuk; - iRet = LLDnodePtr2First(self); - while(iRet != 0) - { - LLDnodeDataTo(self,&tuktuk); - if(tuktuk.running == 1){ - status = tuktuk.pDriv->CheckStatus(tuktuk.data, pCon); - switch(status){ - case HWIdle: - tuktuk.running = 0; - LLDnodeDataFrom(self,&tuktuk); - break; - case HWBusy: - result = HWBusy; - break; - case HWFault: - case HWPosFault: - return status; - break; - default: - /* - this is a programming error and has to be fixed - */ - assert(0); - } + self = *(int *) data; + + iRet = LLDnodePtr2First(self); + while (iRet != 0) { + LLDnodeDataTo(self, &tuktuk); + if (tuktuk.running == 1) { + status = tuktuk.pDriv->CheckStatus(tuktuk.data, pCon); + switch (status) { + case HWIdle: + tuktuk.running = 0; + LLDnodeDataFrom(self, &tuktuk); + break; + case HWBusy: + result = HWBusy; + break; + case HWFault: + case HWPosFault: + return status; + break; + default: + /* + this is a programming error and has to be fixed + */ + assert(0); } - iRet = LLDnodePtr2Next(self); } - return result; + iRet = LLDnodePtr2Next(self); + } + return result; } + /*---------------------------------------------------------------- GetValue is supposed to read a motor position On errors, -99999999.99 is returned and messages printed to pCon ------------------------------------------------------------------*/ -static float MOLIGetValue(void *data, SConnection *pCon){ - int self = 0, iRet; - MotControl tuktuk; - float value, result = 1; - - self = *(int *)data; +static float MOLIGetValue(void *data, SConnection * pCon) +{ + int self = 0, iRet; + MotControl tuktuk; + float value, result = 1; - iRet = LLDnodePtr2First(self); - while(iRet != 0) - { - LLDnodeDataTo(self,&tuktuk); - if(MotorGetSoftPosition(tuktuk.data,pCon,&value) == 1){ - tuktuk.position = value; - } else { - tuktuk.position = -9999999.99; - } - LLDnodeDataFrom(self,&tuktuk); - iRet = LLDnodePtr2Next(self); + self = *(int *) data; + + iRet = LLDnodePtr2First(self); + while (iRet != 0) { + LLDnodeDataTo(self, &tuktuk); + if (MotorGetSoftPosition(tuktuk.data, pCon, &value) == 1) { + tuktuk.position = value; + } else { + tuktuk.position = -9999999.99; } - return OKOK; + LLDnodeDataFrom(self, &tuktuk); + iRet = LLDnodePtr2Next(self); + } + return OKOK; } + /*======================== interface functions ========================*/ -pIDrivable makeMotListInterface(){ - pIDrivable pDriv = NULL; +pIDrivable makeMotListInterface() +{ + pIDrivable pDriv = NULL; - pDriv = CreateDrivableInterface(); - if(pDriv == NULL){ - return NULL; - } - pDriv->Halt = MOLIHalt; - pDriv->CheckLimits = MOLICheckLimits; - pDriv->SetValue = MOLISetValue; - pDriv->CheckStatus = MOLICheckStatus; - pDriv->GetValue = MOLIGetValue; + pDriv = CreateDrivableInterface(); + if (pDriv == NULL) { + return NULL; + } + pDriv->Halt = MOLIHalt; + pDriv->CheckLimits = MOLICheckLimits; + pDriv->SetValue = MOLISetValue; + pDriv->CheckStatus = MOLICheckStatus; + pDriv->GetValue = MOLIGetValue; - return pDriv; + return pDriv; } + /*----------------------------------------------------------------------*/ -int addMotorToList(int listHandle, char *name, float targetValue){ - pMotor pMot = NULL; - MotControl tuktuk; - - pMot = FindMotor(pServ->pSics,name); - if(pMot == NULL){ - return 0; - } - tuktuk.data = pMot; - strncpy(tuktuk.name,name,79); - tuktuk.pDriv = pMot->pDrivInt; - tuktuk.target = targetValue; - tuktuk.running = 0; - tuktuk.position = -9999999.999; - LLDnodeAppendFrom(listHandle,&tuktuk); - return 1; +int addMotorToList(int listHandle, char *name, float targetValue) +{ + pMotor pMot = NULL; + MotControl tuktuk; + + pMot = FindMotor(pServ->pSics, name); + if (pMot == NULL) { + return 0; + } + tuktuk.data = pMot; + strncpy(tuktuk.name, name, 79); + tuktuk.pDriv = pMot->pDrivInt; + tuktuk.target = targetValue; + tuktuk.running = 0; + tuktuk.position = -9999999.999; + LLDnodeAppendFrom(listHandle, &tuktuk); + return 1; } + /*---------------------------------------------------------------------*/ -int setNewMotorTarget(int listHandle, char *name, float value){ - int iRet; - MotControl tuktuk; - - iRet = LLDnodePtr2First(listHandle); - while(iRet != 0) - { - LLDnodeDataTo(listHandle,&tuktuk); - if(strcmp(tuktuk.name,name) == 0){ - tuktuk.target = value; - tuktuk.running = 0; - LLDnodeDataFrom(listHandle, &tuktuk); - return 1; - } - iRet = LLDnodePtr2Next(listHandle); +int setNewMotorTarget(int listHandle, char *name, float value) +{ + int iRet; + MotControl tuktuk; + + iRet = LLDnodePtr2First(listHandle); + while (iRet != 0) { + LLDnodeDataTo(listHandle, &tuktuk); + if (strcmp(tuktuk.name, name) == 0) { + tuktuk.target = value; + tuktuk.running = 0; + LLDnodeDataFrom(listHandle, &tuktuk); + return 1; } - return 0; + iRet = LLDnodePtr2Next(listHandle); + } + return 0; } + /*-----------------------------------------------------------------*/ -int getMotorFromList(int listHandle, char *name,pMotControl tuk){ - int iRet; - MotControl tuktuk; - - iRet = LLDnodePtr2First(listHandle); - while(iRet != 0) - { - LLDnodeDataTo(listHandle,&tuktuk); - if(strcmp(tuktuk.name,name) == 0){ - memcpy(tuk,&tuktuk,sizeof(MotControl)); - return 1; - } - iRet = LLDnodePtr2Next(listHandle); +int getMotorFromList(int listHandle, char *name, pMotControl tuk) +{ + int iRet; + MotControl tuktuk; + + iRet = LLDnodePtr2First(listHandle); + while (iRet != 0) { + LLDnodeDataTo(listHandle, &tuktuk); + if (strcmp(tuktuk.name, name) == 0) { + memcpy(tuk, &tuktuk, sizeof(MotControl)); + return 1; } - return 0; + iRet = LLDnodePtr2Next(listHandle); + } + return 0; } + /*-----------------------------------------------------------------*/ -float getListMotorPosition(int listHandle, char *name){ - int iRet; - MotControl tuktuk; - - iRet = LLDnodePtr2First(listHandle); - while(iRet != 0) - { - LLDnodeDataTo(listHandle,&tuktuk); - if(strcmp(tuktuk.name,name) == 0){ - return tuktuk.position; - } - iRet = LLDnodePtr2Next(listHandle); +float getListMotorPosition(int listHandle, char *name) +{ + int iRet; + MotControl tuktuk; + + iRet = LLDnodePtr2First(listHandle); + while (iRet != 0) { + LLDnodeDataTo(listHandle, &tuktuk); + if (strcmp(tuktuk.name, name) == 0) { + return tuktuk.position; } - return -999999.99; + iRet = LLDnodePtr2Next(listHandle); + } + return -999999.99; } + /*--------------------------------------------------------------------*/ -void printMotorList(int listHandle, SConnection *pCon){ - int iRet; - MotControl tuktuk; - char pBueffel[132]; - - MOLIGetValue(&listHandle,pCon); - - iRet = LLDnodePtr2First(listHandle); - while(iRet != 0) - { - LLDnodeDataTo(listHandle,&tuktuk); - snprintf(pBueffel,131,"Driving %20s from %8.3f to %8.3f", - tuktuk.name, tuktuk.position, tuktuk.target); - SCWrite(pCon,pBueffel,eValue); - iRet = LLDnodePtr2Next(listHandle); - } +void printMotorList(int listHandle, SConnection * pCon) +{ + int iRet; + MotControl tuktuk; + char pBueffel[132]; + + MOLIGetValue(&listHandle, pCon); + + iRet = LLDnodePtr2First(listHandle); + while (iRet != 0) { + LLDnodeDataTo(listHandle, &tuktuk); + snprintf(pBueffel, 131, "Driving %20s from %8.3f to %8.3f", + tuktuk.name, tuktuk.position, tuktuk.target); + SCWrite(pCon, pBueffel, eValue); + iRet = LLDnodePtr2Next(listHandle); + } } diff --git a/motorlist.h b/motorlist.h index 963d0e3b..4821dbd2 100644 --- a/motorlist.h +++ b/motorlist.h @@ -12,14 +12,14 @@ #define SICSMOTLIST #include "sics.h" -typedef struct{ - char name[80]; - float target; - float position; - pIDrivable pDriv; - void *data; - int running; -}MotControl, *pMotControl; +typedef struct { + char name[80]; + float target; + float position; + pIDrivable pDriv; + void *data; + int running; +} MotControl, *pMotControl; /*======================================================================*/ @@ -27,8 +27,7 @@ pIDrivable makeMotListInterface(); int addMotorToList(int listHandle, char *name, float targetValue); int setNewMotorTarget(int listHandle, char *name, float value); int getMotorFromList(int listHandle, char *name, pMotControl tuk); -float getListMotorPosition(int listHandle, char *name); -void printMotorList(int listHandle, SConnection *pCon); +float getListMotorPosition(int listHandle, char *name); +void printMotorList(int listHandle, SConnection * pCon); #endif - diff --git a/motorsec.c b/motorsec.c index 49dc6aa4..3064480c 100644 --- a/motorsec.c +++ b/motorsec.c @@ -45,705 +45,740 @@ #include "motor.h" #include "splitter.h" -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*--------------------------------------------------------------------------*/ -static int SecMotorGetPar(pMotor self, char *name, float *fVal){ - char pBueffel[512]; - hdbValue value;; - int status; - - snprintf(pBueffel,511,"%s ", name); - status = SICSHdbGetPar(self,NULL,pBueffel, &value); - *fVal = (float)value.v.doubleValue; - return status; +static int SecMotorGetPar(pMotor self, char *name, float *fVal) +{ + char pBueffel[512]; + hdbValue value;; + int status; + + snprintf(pBueffel, 511, "%s ", name); + status = SICSHdbGetPar(self, NULL, pBueffel, &value); + *fVal = (float) value.v.doubleValue; + return status; } + /*---------------------------------------------------------------------------*/ -static int SecMotorSetPar(pMotor self, SConnection *pCon, char *name, float fVal){ - int status; - hdbValue value; - value = MakeHdbFloat(fVal); - status = SICSHdbSetPar(self, - pCon,name,value); - if(status == 1){ - SCparChange(pCon); - return 1; - } else { - return 0; - } -} +static int SecMotorSetPar(pMotor self, SConnection * pCon, char *name, + float fVal) +{ + int status; + hdbValue value; + value = MakeHdbFloat(fVal); + status = SICSHdbSetPar(self, pCon, name, value); + if (status == 1) { + SCparChange(pCon); + return 1; + } else { + return 0; + } +} + /*-------------------------------------------------------------------------*/ -static void *MotorGetInterfaceSec(void *pData, int iID){ - pMotor self = NULL; - - self = (pMotor)pData; - assert(self); - if(iID == DRIVEID){ - return self->pDrivInt; - } else if(iID == CALLBACKINTERFACE) { - return self->pCall; - } - return NULL; +static void *MotorGetInterfaceSec(void *pData, int iID) +{ + pMotor self = NULL; + + self = (pMotor) pData; + assert(self); + if (iID == DRIVEID) { + return self->pDrivInt; + } else if (iID == CALLBACKINTERFACE) { + return self->pCall; + } + return NULL; } + /*---------------------------------------------------------------------------*/ -static long SecMotorRun(void *sulf, SConnection *pCon, float fNew){ - pMotor self = (pMotor)sulf; - hdbValue v; - - v = MakeHdbFloat(fNew); - return SetHipadabaPar(self->pDescriptor->parNode,v,pCon); +static long SecMotorRun(void *sulf, SConnection * pCon, float fNew) +{ + pMotor self = (pMotor) sulf; + hdbValue v; + + v = MakeHdbFloat(fNew); + return SetHipadabaPar(self->pDescriptor->parNode, v, pCon); } + /*--------------------------------------------------------------------------*/ -static int SecMotorCheckBoundary(pMotor self, float fVal, float *fTarget, - char *pError, int iErrLen){ - double fZero, fixed, lowerlim, upperlim, sign; - float fHard, hupper, hlower; - char pBueffel[512]; - hdbValue v; +static int SecMotorCheckBoundary(pMotor self, float fVal, float *fTarget, + char *pError, int iErrLen) +{ + double fZero, fixed, lowerlim, upperlim, sign; + float fHard, hupper, hlower; + char pBueffel[512]; + hdbValue v; - assert(self); + assert(self); - assert(SICSHdbGetPar(self,NULL, - "fixed",&v) == 1); - fixed = v.v.doubleValue; - assert(SICSHdbGetPar(self,NULL, - "softzero",&v) == 1); - fZero = v.v.doubleValue; - assert(SICSHdbGetPar(self,NULL, - "softlowerlim",&v) == 1); - lowerlim = v.v.doubleValue; - assert(SICSHdbGetPar(self,NULL, - "softupperlim",&v) == 1); - upperlim = v.v.doubleValue; - assert(SICSHdbGetPar(self,NULL, - "sign",&v) == 1); - sign = v.v.doubleValue; - - *fTarget = fVal; - - /* check for fixed */ - if(fixed >= 0){ - sprintf(pBueffel,"Motor %s is Fixed",self->name); - strncpy(pError,pBueffel,iErrLen); - return 0; /* is this an error? */ - } - - /* check against software boundaries */ - if(fVal > upperlim){ - sprintf(pBueffel,"%f violates upper software limit %f on %s", - fVal, upperlim,self->name); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - if(fVal < lowerlim){ - sprintf(pBueffel,"%f violates lower software limit %f on %s", - fVal,lowerlim,self->name ); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - - /* correct for zero point */ - fZero = -fZero; - fHard = fVal - fZero; + assert(SICSHdbGetPar(self, NULL, "fixed", &v) == 1); + fixed = v.v.doubleValue; + assert(SICSHdbGetPar(self, NULL, "softzero", &v) == 1); + fZero = v.v.doubleValue; + assert(SICSHdbGetPar(self, NULL, "softlowerlim", &v) == 1); + lowerlim = v.v.doubleValue; + assert(SICSHdbGetPar(self, NULL, "softupperlim", &v) == 1); + upperlim = v.v.doubleValue; + assert(SICSHdbGetPar(self, NULL, "sign", &v) == 1); + sign = v.v.doubleValue; - /* apply sign */ - fHard = fHard*sign; - - - /* check for hardware limits */ - SecMotorGetPar(self,"hardlowerlim",&hlower); - SecMotorGetPar(self,"hardupperlim",&hupper); - if(fHard > hupper){ - sprintf(pBueffel,"%f violates upper hardware limit %f on %s", - fVal,hupper,self->name); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - if(fHard < hlower){ - sprintf(pBueffel,"%f violates lower hardware limit %f on %s", - fVal,hlower,self->name); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - - *fTarget = fHard; - return 1; + *fTarget = fVal; + + /* check for fixed */ + if (fixed >= 0) { + sprintf(pBueffel, "Motor %s is Fixed", self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; /* is this an error? */ + } + + /* check against software boundaries */ + if (fVal > upperlim) { + sprintf(pBueffel, "%f violates upper software limit %f on %s", + fVal, upperlim, self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + if (fVal < lowerlim) { + sprintf(pBueffel, "%f violates lower software limit %f on %s", + fVal, lowerlim, self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + + /* correct for zero point */ + fZero = -fZero; + fHard = fVal - fZero; + + /* apply sign */ + fHard = fHard * sign; + + + /* check for hardware limits */ + SecMotorGetPar(self, "hardlowerlim", &hlower); + SecMotorGetPar(self, "hardupperlim", &hupper); + if (fHard > hupper) { + sprintf(pBueffel, "%f violates upper hardware limit %f on %s", + fVal, hupper, self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + if (fHard < hlower) { + sprintf(pBueffel, "%f violates lower hardware limit %f on %s", + fVal, hlower, self->name); + strncpy(pError, pBueffel, iErrLen); + return 0; + } + + *fTarget = fHard; + return 1; } + /*--------------------------------------------------------------------------*/ -static int SecMotorLimits(void *sulf, float fVal, char *error, int iErrLen){ - float fHard; - pMotor self; - - assert(sulf); - - self = (pMotor)sulf; - - return SecMotorCheckBoundary(self,fVal,&fHard,error,iErrLen); +static int SecMotorLimits(void *sulf, float fVal, char *error, int iErrLen) +{ + float fHard; + pMotor self; + + assert(sulf); + + self = (pMotor) sulf; + + return SecMotorCheckBoundary(self, fVal, &fHard, error, iErrLen); } + /*-----------------------------------------------------------------------*/ -static int checkPosition(pMotor self, SConnection *pCon){ - float precision, hard, target, maxretry; - pHdb node = NULL; - - if(SCGetInterrupt(pCon) != eContinue){ - return HWFault; - } - if(self->stopped){ - SCPrintf(pCon,eWarning,"WARNING: %s stopped", self->name); - return HWFault; - } - SecMotorGetPar(self,"hardposition",&hard); - SecMotorGetPar(self,"targetposition",&target); - SecMotorGetPar(self,"precision",&precision); - SecMotorGetPar(self,"maxretry",&maxretry); - if(ABS(target-hard) > precision){ - if(self->retryCount >= (int)maxretry){ - SCPrintf(pCon,eError, - "ERROR: Aborting %s after %d retries, off position by %f", - self->name, (int)maxretry, target - hard); - return HWFault; - } - self->retryCount++; - SCPrintf(pCon,eWarning,"WARNING: %s off position by %f, restarting", - self->name, target-hard); - node = GetHipadabaNode(self->pDescriptor->parNode,"status"); - assert(node != NULL); - UpdateHipadabaPar(node,MakeHdbText("run"), pCon); - node = GetHipadabaNode(self->pDescriptor->parNode,"hardposition"); - assert(node != NULL); - SetHipadabaPar(node,MakeHdbFloat(target), pCon); - return HWBusy; - } - return HWIdle; -} -/*-----------------------------------------------------------------------*/ -static void handleMoveCallback(pMotor self, SConnection *pCon){ - float movecount; - pHdb node = NULL; - hdbValue v; - - SecMotorGetPar(self,"movecount",&movecount); - self->posCount++; - if(self->posCount > (int)movecount){ - node = GetHipadabaNode(self->pDescriptor->parNode,"hardposition"); - GetHipadabaPar(node,&v,pCon); - UpdateHipadabaPar(node,v,pCon); - self->posCount = 0; - } -} -/*-----------------------------------------------------------------------*/ -static int SecMotorStatus(void *sulf, SConnection *pCon){ - pMotor self = NULL; - int status; - pHdb node = NULL; - hdbValue v; - float interrupt; - - assert(sulf); - self = (pMotor)sulf; - - node = GetHipadabaNode(self->pDescriptor->parNode,"status"); - assert(node != NULL); - status = GetHipadabaPar(node,&v,pCon); - - if(status != 1){ - return HWFault; - } - - if(v.v.text == NULL){ - return HWBusy; - } - if(strstr(v.v.text,"idle") != NULL){ - status = checkPosition(self,pCon); - } else if(strstr(v.v.text,"run") != NULL){ - handleMoveCallback(self,pCon); - status = HWBusy; - } else if(strstr(v.v.text,"poserror") != NULL){ - status = checkPosition(self,pCon); - } else if(strstr(v.v.text,"error") != NULL){ - status = HWFault; - } else { - SCPrintf(pCon,eError,"ERROR: unknown motor status %s found", v.v.text); - status = HWFault; - } - /* - * when terminating: force an update of the position. - */ - switch(status){ - case HWFault: - self->posCount = 10000; - handleMoveCallback(self,pCon); - SecMotorGetPar(self,"interrupt",&interrupt); - if(SCGetInterrupt(pCon) < (int)interrupt){ - SCSetInterrupt(pCon,(int)interrupt); - } - self->errorCount++; - break; - case HWIdle: - self->posCount = 10000; - handleMoveCallback(self,pCon); - self->errorCount = 0; - break; +static int checkPosition(pMotor self, SConnection * pCon) +{ + float precision, hard, target, maxretry; + pHdb node = NULL; + + if (SCGetInterrupt(pCon) != eContinue) { + return HWFault; + } + if (self->stopped) { + SCPrintf(pCon, eWarning, "WARNING: %s stopped", self->name); + return HWFault; + } + SecMotorGetPar(self, "hardposition", &hard); + SecMotorGetPar(self, "targetposition", &target); + SecMotorGetPar(self, "precision", &precision); + SecMotorGetPar(self, "maxretry", &maxretry); + if (ABS(target - hard) > precision) { + if (self->retryCount >= (int) maxretry) { + SCPrintf(pCon, eError, + "ERROR: Aborting %s after %d retries, off position by %f", + self->name, (int) maxretry, target - hard); + return HWFault; } - return status; -} -/*---------------------------------------------------------------------------*/ -static float SecMotorGetValue(void *pData, SConnection *pCon){ - int status; - pMotor self = (pMotor)pData; - hdbValue v; - - assert(pData); - status = GetHipadabaPar(self->pDescriptor->parNode, &v,pCon); - if(status != 1){ - return -9999999.99; - } else { - return (float)v.v.doubleValue; - } -} -/*------------------------------------------------------------------------*/ -static int SecMotorHalt(void *sulf){ - pMotor self; - pHdb node = NULL, par[0]; - SICSOBJFunc haltFunc = NULL; - int status; - - assert(sulf); - self = (pMotor)sulf; - - node = GetHipadabaNode(self->pDescriptor->parNode,"halt"); + self->retryCount++; + SCPrintf(pCon, eWarning, "WARNING: %s off position by %f, restarting", + self->name, target - hard); + node = GetHipadabaNode(self->pDescriptor->parNode, "status"); assert(node != NULL); - - haltFunc = (SICSOBJFunc)node->value.v.func; - assert(haltFunc != NULL); - self->stopped = 1; - return haltFunc((pSICSOBJ)self,pServ->dummyCon,node,par,0); + UpdateHipadabaPar(node, MakeHdbText("run"), pCon); + node = GetHipadabaNode(self->pDescriptor->parNode, "hardposition"); + assert(node != NULL); + SetHipadabaPar(node, MakeHdbFloat(target), pCon); + return HWBusy; + } + return HWIdle; } -/*--------------------------------------------------------------------------*/ -static int SecMotorGetHardPosition(struct __Motor *self, - SConnection *pCon, float *fVal){ - hdbValue v; - int status; - pHdb node = NULL; - - node = GetHipadabaNode(self->pDescriptor->parNode,"hardposition"); - assert(node != NULL); - status = GetHipadabaPar(node,&v,pCon); - *fVal = (float)v.v.doubleValue; - return status; -} -/*---------------------------------------------------------------------------*/ -static void AddMotorPar(pHdb node, int priv, char *name){ - pHdb child = NULL; - - child = MakeSICSHdbPar(name,priv,MakeHdbFloat(.0)); - if(child != NULL){ - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - } -} -/*---------------------------------------------------------------------------*/ -static float hardToSoftPosition(pMotor self, float hard){ - float sign, zero, fVal; - - SecMotorGetPar(self,"sign", &sign); - SecMotorGetPar(self,"softzero", &zero); - fVal = hard; - if(sign < 0){ - fVal += zero; - } else { - fVal -= zero; - } - fVal *= sign; - return fVal; -} -/*---------------------------------------------------------------------------*/ -static hdbCallbackReturn SecMotorCallback(pHdb node, void *userData, - pHdbMessage message){ - SConnection *pCon = NULL; - pHdbDataMessage mm = NULL; - hdbValue v; - pHdb child = NULL; - pMotor self = NULL; - float fHard, fVal, sign, zero; - char pBueffel[512], pError[132]; - int status; - - self = (pMotor)userData; - assert(self != NULL); - - mm = GetHdbSetMessage(message); - if(mm != NULL){ - pCon = (SConnection *)mm->callData; - v = *(mm->v); - - /* - * check permission - */ - SecMotorGetPar(self,"accesscode",&fVal); - if(!SCMatchRights(pCon,(int)fVal)){ - sprintf(pBueffel,"ERROR: You are not authorised to move motor %s", - self->name); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,eAbortBatch); - return hdbAbort; - } - - /* - * check limits - */ - status = SecMotorCheckBoundary(self,(float)v.v.doubleValue, - &fHard,pError,131); - if(status != 1){ - snprintf(pBueffel,511,"ERROR: %s",pError); - SCWrite(pCon,pBueffel,eWarning); - SCSetInterrupt(pCon,eAbortOperation); - return hdbAbort; - } - - /* - * check the motor bad flag - */ - SecMotorGetPar(self,"ignorefault",&fVal); - if((int)fVal > 0){ - snprintf(pBueffel,511,"WARNING: motor %s is unreliable", - self->name); - SCWrite(pCon,pBueffel,eWarning); - self->errorCount = 0; - } - /* - * check for alarm condition - */ - SecMotorGetPar(self,"failafter",&fVal); - if(self->errorCount > (int)fVal){ - /* big alarm */ - ServerWriteGlobal("ERROR: !!! MOTOR ALARM !!! MOTOR ALARM !!!",eError); - sprintf(pBueffel, +/*-----------------------------------------------------------------------*/ +static void handleMoveCallback(pMotor self, SConnection * pCon) +{ + float movecount; + pHdb node = NULL; + hdbValue v; + + SecMotorGetPar(self, "movecount", &movecount); + self->posCount++; + if (self->posCount > (int) movecount) { + node = GetHipadabaNode(self->pDescriptor->parNode, "hardposition"); + GetHipadabaPar(node, &v, pCon); + UpdateHipadabaPar(node, v, pCon); + self->posCount = 0; + } +} + +/*-----------------------------------------------------------------------*/ +static int SecMotorStatus(void *sulf, SConnection * pCon) +{ + pMotor self = NULL; + int status; + pHdb node = NULL; + hdbValue v; + float interrupt; + + assert(sulf); + self = (pMotor) sulf; + + node = GetHipadabaNode(self->pDescriptor->parNode, "status"); + assert(node != NULL); + status = GetHipadabaPar(node, &v, pCon); + + if (status != 1) { + return HWFault; + } + + if (v.v.text == NULL) { + return HWBusy; + } + if (strstr(v.v.text, "idle") != NULL) { + status = checkPosition(self, pCon); + } else if (strstr(v.v.text, "run") != NULL) { + handleMoveCallback(self, pCon); + status = HWBusy; + } else if (strstr(v.v.text, "poserror") != NULL) { + status = checkPosition(self, pCon); + } else if (strstr(v.v.text, "error") != NULL) { + status = HWFault; + } else { + SCPrintf(pCon, eError, "ERROR: unknown motor status %s found", + v.v.text); + status = HWFault; + } + /* + * when terminating: force an update of the position. + */ + switch (status) { + case HWFault: + self->posCount = 10000; + handleMoveCallback(self, pCon); + SecMotorGetPar(self, "interrupt", &interrupt); + if (SCGetInterrupt(pCon) < (int) interrupt) { + SCSetInterrupt(pCon, (int) interrupt); + } + self->errorCount++; + break; + case HWIdle: + self->posCount = 10000; + handleMoveCallback(self, pCon); + self->errorCount = 0; + break; + } + return status; +} + +/*---------------------------------------------------------------------------*/ +static float SecMotorGetValue(void *pData, SConnection * pCon) +{ + int status; + pMotor self = (pMotor) pData; + hdbValue v; + + assert(pData); + status = GetHipadabaPar(self->pDescriptor->parNode, &v, pCon); + if (status != 1) { + return -9999999.99; + } else { + return (float) v.v.doubleValue; + } +} + +/*------------------------------------------------------------------------*/ +static int SecMotorHalt(void *sulf) +{ + pMotor self; + pHdb node = NULL, par[0]; + SICSOBJFunc haltFunc = NULL; + int status; + + assert(sulf); + self = (pMotor) sulf; + + node = GetHipadabaNode(self->pDescriptor->parNode, "halt"); + assert(node != NULL); + + haltFunc = (SICSOBJFunc) node->value.v.func; + assert(haltFunc != NULL); + self->stopped = 1; + return haltFunc((pSICSOBJ) self, pServ->dummyCon, node, par, 0); +} + +/*--------------------------------------------------------------------------*/ +static int SecMotorGetHardPosition(struct __Motor *self, + SConnection * pCon, float *fVal) +{ + hdbValue v; + int status; + pHdb node = NULL; + + node = GetHipadabaNode(self->pDescriptor->parNode, "hardposition"); + assert(node != NULL); + status = GetHipadabaPar(node, &v, pCon); + *fVal = (float) v.v.doubleValue; + return status; +} + +/*---------------------------------------------------------------------------*/ +static void AddMotorPar(pHdb node, int priv, char *name) +{ + pHdb child = NULL; + + child = MakeSICSHdbPar(name, priv, MakeHdbFloat(.0)); + if (child != NULL) { + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + } +} + +/*---------------------------------------------------------------------------*/ +static float hardToSoftPosition(pMotor self, float hard) +{ + float sign, zero, fVal; + + SecMotorGetPar(self, "sign", &sign); + SecMotorGetPar(self, "softzero", &zero); + fVal = hard; + if (sign < 0) { + fVal += zero; + } else { + fVal -= zero; + } + fVal *= sign; + return fVal; +} + +/*---------------------------------------------------------------------------*/ +static hdbCallbackReturn SecMotorCallback(pHdb node, void *userData, + pHdbMessage message) +{ + SConnection *pCon = NULL; + pHdbDataMessage mm = NULL; + hdbValue v; + pHdb child = NULL; + pMotor self = NULL; + float fHard, fVal, sign, zero; + char pBueffel[512], pError[132]; + int status; + + self = (pMotor) userData; + assert(self != NULL); + + mm = GetHdbSetMessage(message); + if (mm != NULL) { + pCon = (SConnection *) mm->callData; + v = *(mm->v); + + /* + * check permission + */ + SecMotorGetPar(self, "accesscode", &fVal); + if (!SCMatchRights(pCon, (int) fVal)) { + sprintf(pBueffel, "ERROR: You are not authorised to move motor %s", + self->name); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, eAbortBatch); + return hdbAbort; + } + + /* + * check limits + */ + status = SecMotorCheckBoundary(self, (float) v.v.doubleValue, + &fHard, pError, 131); + if (status != 1) { + snprintf(pBueffel, 511, "ERROR: %s", pError); + SCWrite(pCon, pBueffel, eWarning); + SCSetInterrupt(pCon, eAbortOperation); + return hdbAbort; + } + + /* + * check the motor bad flag + */ + SecMotorGetPar(self, "ignorefault", &fVal); + if ((int) fVal > 0) { + snprintf(pBueffel, 511, "WARNING: motor %s is unreliable", + self->name); + SCWrite(pCon, pBueffel, eWarning); + self->errorCount = 0; + } + + /* + * check for alarm condition + */ + SecMotorGetPar(self, "failafter", &fVal); + if (self->errorCount > (int) fVal) { + /* big alarm */ + ServerWriteGlobal("ERROR: !!! MOTOR ALARM !!! MOTOR ALARM !!!", + eError); + sprintf(pBueffel, "ERROR: too many position errors counted at motor %s", self->name); - ServerWriteGlobal(pBueffel,eError); - SCSetInterrupt(pCon,eAbortBatch); - self->errorCount = 0; - return hdbAbort; - } - - self->posFaultCount = 0; - self->retryCount = 0; - self->stopped = 0; - self->posCount = 0; - child = GetHipadabaNode(self->pDescriptor->parNode,"targetposition"); - UpdateHipadabaPar(child,MakeHdbFloat(fHard),pCon); - child = GetHipadabaNode(self->pDescriptor->parNode,"status"); - UpdateHipadabaPar(child,MakeHdbText("run"), pCon); - child = GetHipadabaNode(self->pDescriptor->parNode,"hardposition"); - SetHipadabaPar(child,MakeHdbFloat(fHard), pCon); - - return hdbContinue; - } - - mm = GetHdbGetMessage(message); - if(mm != NULL){ - pCon = (SConnection *)mm->callData; - SecMotorGetPar(self,"hardposition", &fVal); - fVal = hardToSoftPosition(self,fVal); - node->value.v.doubleValue = fVal; - mm->v->v.doubleValue = fVal; - return hdbContinue; + ServerWriteGlobal(pBueffel, eError); + SCSetInterrupt(pCon, eAbortBatch); + self->errorCount = 0; + return hdbAbort; } - + + self->posFaultCount = 0; + self->retryCount = 0; + self->stopped = 0; + self->posCount = 0; + child = GetHipadabaNode(self->pDescriptor->parNode, "targetposition"); + UpdateHipadabaPar(child, MakeHdbFloat(fHard), pCon); + child = GetHipadabaNode(self->pDescriptor->parNode, "status"); + UpdateHipadabaPar(child, MakeHdbText("run"), pCon); + child = GetHipadabaNode(self->pDescriptor->parNode, "hardposition"); + SetHipadabaPar(child, MakeHdbFloat(fHard), pCon); + return hdbContinue; + } + + mm = GetHdbGetMessage(message); + if (mm != NULL) { + pCon = (SConnection *) mm->callData; + SecMotorGetPar(self, "hardposition", &fVal); + fVal = hardToSoftPosition(self, fVal); + node->value.v.doubleValue = fVal; + mm->v->v.doubleValue = fVal; + return hdbContinue; + } + + return hdbContinue; } + /*--------------------------------------------------------------------------*/ -static hdbCallbackReturn HardUpdateCallback(pHdb node, void *userData, - pHdbMessage message){ - pHdbDataMessage mm = NULL; - pMotor self = (pMotor)userData; - float fVal; - hdbValue v; - - assert(self != NULL); - - mm = GetHdbUpdateMessage(message); - if(mm != NULL){ - v = *mm->v; - fVal = hardToSoftPosition(self,(float)v.v.doubleValue); - v.v.doubleValue = fVal; - UpdateHipadabaPar(self->pDescriptor->parNode, v, mm->callData); - return hdbContinue; - } - return hdbContinue; +static hdbCallbackReturn HardUpdateCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdbDataMessage mm = NULL; + pMotor self = (pMotor) userData; + float fVal; + hdbValue v; + + assert(self != NULL); + + mm = GetHdbUpdateMessage(message); + if (mm != NULL) { + v = *mm->v; + fVal = hardToSoftPosition(self, (float) v.v.doubleValue); + v.v.doubleValue = fVal; + UpdateHipadabaPar(self->pDescriptor->parNode, v, mm->callData); + return hdbContinue; + } + return hdbContinue; } + /*--------------------------------------------------------------------------*/ -static hdbCallbackReturn SecMotorSignCallback(pHdb node, void *userData, - pHdbMessage message){ - pMotor self = NULL; - SConnection *pCon = NULL; - pHdb zero = NULL; - double value; - pHdbDataMessage mm = NULL; - float limit; - hdbValue v; - - self = (pMotor)userData; - - mm = GetHdbSetMessage(message); - if(mm != NULL){ - pCon = (SConnection *)mm->callData; - if(!SCMatchRights(pCon,usMugger)){ - return hdbAbort; - } - v = *mm->v; - if(ABS(v.v.doubleValue) - 1. > .01){ - if(pCon!= NULL){ - SCWrite(pCon,"ERROR: invalid sign value",eError); - return hdbAbort; - } - } - SecMotorGetPar(self,"softlowerlim",&limit); - limit *= v.v.doubleValue; - SecMotorSetPar(self,pCon,"softlowerlim",limit); - SecMotorGetPar(self,"softupperlim",&limit); - limit *= v.v.doubleValue; - SecMotorSetPar(self,pCon,"softupperlim",limit); - SecMotorSetPar(self,pCon,"softzero",.0); - UpdateHipadabaPar(node,v,pCon); - return hdbContinue; +static hdbCallbackReturn SecMotorSignCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pMotor self = NULL; + SConnection *pCon = NULL; + pHdb zero = NULL; + double value; + pHdbDataMessage mm = NULL; + float limit; + hdbValue v; + + self = (pMotor) userData; + + mm = GetHdbSetMessage(message); + if (mm != NULL) { + pCon = (SConnection *) mm->callData; + if (!SCMatchRights(pCon, usMugger)) { + return hdbAbort; } + v = *mm->v; + if (ABS(v.v.doubleValue) - 1. > .01) { + if (pCon != NULL) { + SCWrite(pCon, "ERROR: invalid sign value", eError); + return hdbAbort; + } + } + SecMotorGetPar(self, "softlowerlim", &limit); + limit *= v.v.doubleValue; + SecMotorSetPar(self, pCon, "softlowerlim", limit); + SecMotorGetPar(self, "softupperlim", &limit); + limit *= v.v.doubleValue; + SecMotorSetPar(self, pCon, "softupperlim", limit); + SecMotorSetPar(self, pCon, "softzero", .0); + UpdateHipadabaPar(node, v, pCon); return hdbContinue; + } + return hdbContinue; } + /*---------------------------------------------------------------------------*/ static hdbCallbackReturn SecMotorZeroCallback(pHdb node, void *userData, - pHdbMessage message){ - pMotor self = NULL; - float limit, oldZero, diff; - SConnection *pCon = NULL; - pHdbDataMessage mm = NULL; - hdbValue v; - - self = (pMotor)userData; - assert(self != NULL); - - mm = GetHdbSetMessage(message); - if(mm != NULL){ - pCon = (SConnection *)mm->callData; - if(!SCMatchRights(pCon,usUser)){ - return hdbAbort; - } - v = *mm->v; - SecMotorGetPar(self,"softzero", &oldZero); - diff = v.v.doubleValue - oldZero; + pHdbMessage message) +{ + pMotor self = NULL; + float limit, oldZero, diff; + SConnection *pCon = NULL; + pHdbDataMessage mm = NULL; + hdbValue v; - SecMotorGetPar(self,"softupperlim",&limit); - limit -= diff; - SecMotorSetPar(self,pCon,"softupperlim",limit); - - SecMotorGetPar(self,"softlowerlim",&limit); - limit -= diff; - SecMotorSetPar(self,pCon,"softlowerlim",limit); - UpdateHipadabaPar(node,v,pCon); - return hdbContinue; - } + self = (pMotor) userData; + assert(self != NULL); + + mm = GetHdbSetMessage(message); + if (mm != NULL) { + pCon = (SConnection *) mm->callData; + if (!SCMatchRights(pCon, usUser)) { + return hdbAbort; + } + v = *mm->v; + SecMotorGetPar(self, "softzero", &oldZero); + diff = v.v.doubleValue - oldZero; + + SecMotorGetPar(self, "softupperlim", &limit); + limit -= diff; + SecMotorSetPar(self, pCon, "softupperlim", limit); + + SecMotorGetPar(self, "softlowerlim", &limit); + limit -= diff; + SecMotorSetPar(self, pCon, "softlowerlim", limit); + UpdateHipadabaPar(node, v, pCon); return hdbContinue; -} -/*---------------------------------------------------------------------------*/ -pMotor SecMotorInit(char *name){ - pMotor pM = NULL; - pHdb node = NULL, child = NULL; - hdbValue v; - - assert(name); - - /* get memory */ - pM = (pMotor)malloc(sizeof(Motor)); - if(!pM){ - return NULL; - } - memset(pM,0,sizeof(Motor)); - - /* initialise object descriptor */ - pM->pDescriptor = CreateDescriptor("Motor"); - if(!pM->pDescriptor){ - free(pM); - return NULL; - } - pM->pDescriptor->GetInterface = MotorGetInterfaceSec; - pM->pDescriptor->SaveStatus = SaveSICSOBJ; - pM->pDescriptor->parNode = MakeSICSHdbPar(name,usSpy,MakeHdbFloat(.0)); - if(pM->pDescriptor->parNode == NULL){ - free(pM); - return NULL; - } - node = pM->pDescriptor->parNode; - pM->objectNode = node; - AppendHipadabaCallback(pM->pDescriptor->parNode, - MakeHipadabaCallback(SecMotorCallback,pM,NULL)); - - /* copy arguments */ - pM->name = strdup(name); - - /* - * install parameters - */ - child = MakeSICSHdbPar("targetposition",usInternal,MakeHdbFloat(.0)); - if(child == NULL){ - return(NULL); - } - SetHdbProperty(child,"__save", "true"); - - AddHipadabaChild(node,child,NULL); - child = MakeHipadabaNode("hardposition",HIPFLOAT,1); - if(child == NULL){ - return(NULL); - } - AddHipadabaChild(node,child,NULL); - SetHdbProperty(child,"motname", name); - AppendHipadabaCallback(child, - MakeHipadabaCallback(HardUpdateCallback,pM,NULL)); - - child = MakeHipadabaNode("sign",HIPFLOAT, 1); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - AppendHipadabaCallback(child, - MakeHipadabaCallback(SecMotorSignCallback,pM,NULL)); - UpdateHipadabaPar(child,MakeHdbFloat(1.),NULL); - - child = MakeHipadabaNode("softzero",HIPFLOAT, 1); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - AppendHipadabaCallback(child, - MakeHipadabaCallback(SecMotorZeroCallback,pM,NULL)); - - child = MakeHipadabaNode("hardlowerlim",HIPFLOAT, 1); - AddHipadabaChild(node,child,NULL); - - child = MakeHipadabaNode("hardupperlim",HIPFLOAT, 1); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("softlowerlim",usUser, - MakeHdbFloat(.0)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("softupperlim",usUser, - MakeHdbFloat(.0)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("fixed",usUser, - MakeHdbFloat(-1.)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("interruptmode",usMugger, - MakeHdbFloat(.0)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("precision",usMugger, - MakeHdbFloat(.1)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("accesscode",usMugger, - MakeHdbFloat((double)usUser)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("failafter",usMugger, - MakeHdbFloat((double)3.0)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("maxretry",usMugger, - MakeHdbFloat((double)3.0)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("ignorefault",usMugger, - MakeHdbFloat((double).0)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeSICSHdbPar("movecount",usMugger, - MakeHdbFloat((double)10.0)); - SetHdbProperty(child,"__save", "true"); - AddHipadabaChild(node,child,NULL); - - child = MakeHipadabaNode("status",HIPTEXT,1); - SetHdbProperty(child,"motname", name); - AddHipadabaChild(node,child,NULL); - - pM->endScriptID = 0; - - /* initialise Drivable interface */ - pM->pDrivInt = CreateDrivableInterface(); - if(!pM->pDrivInt){ - DeleteDescriptor(pM->pDescriptor); - free(pM); - return NULL; - } - pM->pDrivInt->SetValue = SecMotorRun; - pM->pDrivInt->CheckLimits = SecMotorLimits; - pM->pDrivInt->CheckStatus = SecMotorStatus; - pM->pDrivInt->GetValue = SecMotorGetValue; - pM->pDrivInt->Halt = SecMotorHalt; - - /* - * initialize motor function pointers - */ - pM->MotorGetPar = SecMotorGetPar; - pM->MotorSetPar = SecMotorSetPar; - pM->MotorGetHardPosition = SecMotorGetHardPosition; - - /* initialise callback interface */ - pM->pCall = CreateCallBackInterface(); - if(!pM->pCall){ - MotorKill(pM); - return NULL; - } - - /* done */ - return pM; } -/*--------------------------------------------------------------------------*/ -static void SecMotorKill(void *data){ - pMotor self = (pMotor)data; - if(self == NULL){ - return; - } - if(self->name) - free(self->name); - - if(self->pDrivInt){ - free(self->pDrivInt); - } - - if(self->pCall){ - DeleteCallBackInterface(self->pCall); - } - - /* kill Descriptor */ - DeleteDescriptor(self->pDescriptor); - - free(self); + return hdbContinue; } -/*--------------------------------------------------------------------------*/ -int SecMotorFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pMotor pNew = NULL; - if(argc < 2){ - SCWrite(pCon,"ERROR: need name for new motor", eError); - return 0; - } - - pNew = SecMotorInit(argv[1]); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating motor", eError); - return 0; - } - return AddCommand(pSics,argv[1],InterInvokeSICSOBJ, - SecMotorKill,pNew); - +/*---------------------------------------------------------------------------*/ +pMotor SecMotorInit(char *name) +{ + pMotor pM = NULL; + pHdb node = NULL, child = NULL; + hdbValue v; + + assert(name); + + /* get memory */ + pM = (pMotor) malloc(sizeof(Motor)); + if (!pM) { + return NULL; + } + memset(pM, 0, sizeof(Motor)); + + /* initialise object descriptor */ + pM->pDescriptor = CreateDescriptor("Motor"); + if (!pM->pDescriptor) { + free(pM); + return NULL; + } + pM->pDescriptor->GetInterface = MotorGetInterfaceSec; + pM->pDescriptor->SaveStatus = SaveSICSOBJ; + pM->pDescriptor->parNode = MakeSICSHdbPar(name, usSpy, MakeHdbFloat(.0)); + if (pM->pDescriptor->parNode == NULL) { + free(pM); + return NULL; + } + node = pM->pDescriptor->parNode; + pM->objectNode = node; + AppendHipadabaCallback(pM->pDescriptor->parNode, + MakeHipadabaCallback(SecMotorCallback, pM, NULL)); + + /* copy arguments */ + pM->name = strdup(name); + + /* + * install parameters + */ + child = MakeSICSHdbPar("targetposition", usInternal, MakeHdbFloat(.0)); + if (child == NULL) { + return (NULL); + } + SetHdbProperty(child, "__save", "true"); + + AddHipadabaChild(node, child, NULL); + child = MakeHipadabaNode("hardposition", HIPFLOAT, 1); + if (child == NULL) { + return (NULL); + } + AddHipadabaChild(node, child, NULL); + SetHdbProperty(child, "motname", name); + AppendHipadabaCallback(child, + MakeHipadabaCallback(HardUpdateCallback, pM, + NULL)); + + child = MakeHipadabaNode("sign", HIPFLOAT, 1); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + AppendHipadabaCallback(child, + MakeHipadabaCallback(SecMotorSignCallback, pM, + NULL)); + UpdateHipadabaPar(child, MakeHdbFloat(1.), NULL); + + child = MakeHipadabaNode("softzero", HIPFLOAT, 1); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + AppendHipadabaCallback(child, + MakeHipadabaCallback(SecMotorZeroCallback, pM, + NULL)); + + child = MakeHipadabaNode("hardlowerlim", HIPFLOAT, 1); + AddHipadabaChild(node, child, NULL); + + child = MakeHipadabaNode("hardupperlim", HIPFLOAT, 1); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("softlowerlim", usUser, MakeHdbFloat(.0)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("softupperlim", usUser, MakeHdbFloat(.0)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("fixed", usUser, MakeHdbFloat(-1.)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("interruptmode", usMugger, MakeHdbFloat(.0)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("precision", usMugger, MakeHdbFloat(.1)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("accesscode", usMugger, + MakeHdbFloat((double) usUser)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("failafter", usMugger, + MakeHdbFloat((double) 3.0)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("maxretry", usMugger, MakeHdbFloat((double) 3.0)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("ignorefault", usMugger, + MakeHdbFloat((double) .0)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeSICSHdbPar("movecount", usMugger, + MakeHdbFloat((double) 10.0)); + SetHdbProperty(child, "__save", "true"); + AddHipadabaChild(node, child, NULL); + + child = MakeHipadabaNode("status", HIPTEXT, 1); + SetHdbProperty(child, "motname", name); + AddHipadabaChild(node, child, NULL); + + pM->endScriptID = 0; + + /* initialise Drivable interface */ + pM->pDrivInt = CreateDrivableInterface(); + if (!pM->pDrivInt) { + DeleteDescriptor(pM->pDescriptor); + free(pM); + return NULL; + } + pM->pDrivInt->SetValue = SecMotorRun; + pM->pDrivInt->CheckLimits = SecMotorLimits; + pM->pDrivInt->CheckStatus = SecMotorStatus; + pM->pDrivInt->GetValue = SecMotorGetValue; + pM->pDrivInt->Halt = SecMotorHalt; + + /* + * initialize motor function pointers + */ + pM->MotorGetPar = SecMotorGetPar; + pM->MotorSetPar = SecMotorSetPar; + pM->MotorGetHardPosition = SecMotorGetHardPosition; + + /* initialise callback interface */ + pM->pCall = CreateCallBackInterface(); + if (!pM->pCall) { + MotorKill(pM); + return NULL; + } + + /* done */ + return pM; +} + +/*--------------------------------------------------------------------------*/ +static void SecMotorKill(void *data) +{ + pMotor self = (pMotor) data; + if (self == NULL) { + return; + } + if (self->name) + free(self->name); + + if (self->pDrivInt) { + free(self->pDrivInt); + } + + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + } + + /* kill Descriptor */ + DeleteDescriptor(self->pDescriptor); + + free(self); +} + +/*--------------------------------------------------------------------------*/ +int SecMotorFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pMotor pNew = NULL; + + if (argc < 2) { + SCWrite(pCon, "ERROR: need name for new motor", eError); + return 0; + } + + pNew = SecMotorInit(argv[1]); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating motor", eError); + return 0; + } + return AddCommand(pSics, argv[1], InterInvokeSICSOBJ, + SecMotorKill, pNew); + } diff --git a/motorsec.h b/motorsec.h index 68da0be3..b2ff76b9 100644 --- a/motorsec.h +++ b/motorsec.h @@ -5,10 +5,10 @@ * copyright: see file COPYRIGHT * * Mark Koennecke, December 2008 - */ + */ #ifndef MOTORSEC_H_ #define MOTORSEC_H_ -int SecMotorFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SecMotorFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -#endif /*MOTORSEC_H_*/ +#endif /*MOTORSEC_H_ */ diff --git a/motreg.c b/motreg.c index 92e024a1..0e5a4c57 100644 --- a/motreg.c +++ b/motreg.c @@ -10,39 +10,41 @@ Mark Koennecke, August 2002 -----------------------------------------------------------------------*/ #include -#include +#include #include "fortify.h" #include "motreg.h" /*--------------------------------------------------------------------*/ -pMotReg RegisterMotor(char *name, SicsInterp *pSics, - long (*NewSetValue)(void *pData, SConnection *pCon, - float farget), - int (*NewCheckStatus)(void *pData,SConnection *pCon) ){ +pMotReg RegisterMotor(char *name, SicsInterp * pSics, + long (*NewSetValue) (void *pData, SConnection * pCon, + float farget), + int (*NewCheckStatus) (void *pData, + SConnection * pCon)) +{ CommandList *pCom = NULL; pIDrivable pDriv = NULL; pMotReg pNew = NULL; /* - find motor data structures - */ - pCom = FindCommand(pSics,name); - if(pCom == NULL){ + find motor data structures + */ + pCom = FindCommand(pSics, name); + if (pCom == NULL) { return NULL; } pDriv = GetDrivableInterface(pCom->pData); - if(pDriv == NULL){ + if (pDriv == NULL) { return NULL; } /* - everything seems OK. Allocate data structure and initialize - */ - pNew = (pMotReg)malloc(sizeof(MotReg)); - if(pNew == NULL){ + everything seems OK. Allocate data structure and initialize + */ + pNew = (pMotReg) malloc(sizeof(MotReg)); + if (pNew == NULL) { return NULL; } - memset(pNew,0,sizeof(MotReg)); + memset(pNew, 0, sizeof(MotReg)); pNew->motorData = pCom->pData; pNew->motorName = strdup(name); @@ -55,45 +57,56 @@ pMotReg RegisterMotor(char *name, SicsInterp *pSics, return pNew; } -/*---------------------------------------------------------------------*/ -void KillRegMot(void *pData){ - pMotReg self = (pMotReg)pData; - if(self == NULL){ +/*---------------------------------------------------------------------*/ +void KillRegMot(void *pData) +{ + pMotReg self = (pMotReg) pData; + + if (self == NULL) { return; } - if(self->motorName != NULL){ + if (self->motorName != NULL) { free(self->motorName); } free(self); } + /*------------------------------------------------------------------------*/ -void SetRegMotTarget(pMotReg self, float fValue){ +void SetRegMotTarget(pMotReg self, float fValue) +{ assert(self); self->targetPosition = fValue; self->iActive = 1; } + /*------------------------------------------------------------------------*/ -void CreateTargetString(pMotReg self, char pBueffel[80]) { +void CreateTargetString(pMotReg self, char pBueffel[80]) +{ assert(self); - if(strlen(self->motorName) + 20 < 80) { - sprintf(pBueffel," %s %12.4f ", self->motorName, self->targetPosition); + if (strlen(self->motorName) + 20 < 80) { + sprintf(pBueffel, " %s %12.4f ", self->motorName, + self->targetPosition); } } + /*-----------------------------------------------------------------------*/ -int RegMotMatch(pMotReg self, char *name){ +int RegMotMatch(pMotReg self, char *name) +{ assert(self); - if(strcmp(self->motorName, name) == 0) { + if (strcmp(self->motorName, name) == 0) { return 1; } return 0; } + /*----------------------------------------------------------------------*/ -int StartRegMot(pMotReg self, SConnection *pCon, float fValue){ +int StartRegMot(pMotReg self, SConnection * pCon, float fValue) +{ int ret; - long (*oldSet)(void *pmotorData, SConnection *pCon, float fValue); + long (*oldSet) (void *pmotorData, SConnection * pCon, float fValue); pIDrivable pDriv = NULL; char pBueffel[132]; @@ -104,35 +117,35 @@ int StartRegMot(pMotReg self, SConnection *pCon, float fValue){ oldSet = pDriv->SetValue; pDriv->SetValue = self->originalSetValue; ret = StartDevice(pServ->pExecutor, self->motorName, - FindDescriptor(self->motorData), - self->motorData, - pCon, - fValue); + FindDescriptor(self->motorData), + self->motorData, pCon, fValue); /* - sprintf(pBueffel,"anticollision started %s to %f",self->motorName, - fValue); - SCWrite(pCon,pBueffel,eValue); - */ + sprintf(pBueffel,"anticollision started %s to %f",self->motorName, + fValue); + SCWrite(pCon,pBueffel,eValue); + */ pDriv->SetValue = oldSet; - if(ret == 1){ - self->iActive = 1; + if (ret == 1) { + self->iActive = 1; } else { - snprintf(pBueffel,131,"ERROR: failed to start motor %s", - self->motorName); - SCWrite(pCon,pBueffel,eError); - self->iActive = 0; + snprintf(pBueffel, 131, "ERROR: failed to start motor %s", + self->motorName); + SCWrite(pCon, pBueffel, eError); + self->iActive = 0; } return ret; } + /*----------------------------------------------------------------------*/ -int CheckRegMot(pMotReg self, SConnection *pCon){ +int CheckRegMot(pMotReg self, SConnection * pCon) +{ int stat; assert(self); - if(self->iActive){ - stat = self->originalCheckStatus(self->motorData,pCon); - if(stat != HWBusy){ + if (self->iActive) { + stat = self->originalCheckStatus(self->motorData, pCon); + if (stat != HWBusy) { self->iActive = 0; } return stat; @@ -140,4 +153,3 @@ int CheckRegMot(pMotReg self, SConnection *pCon){ return HWIdle; } } - diff --git a/motreg.h b/motreg.h index 457abb97..7b61e21a 100644 --- a/motreg.h +++ b/motreg.h @@ -17,36 +17,34 @@ typedef struct __MOTREG { - void *motorData; - char *motorName; - float targetPosition; - long (*originalSetValue)(void *motorData, - SConnection *pCon, - float fTarget); - int (*originalCheckStatus)(void *motorData, - SConnection *pCon); - int iActive; - } MotReg, *pMotReg; + void *motorData; + char *motorName; + float targetPosition; + long (*originalSetValue) (void *motorData, + SConnection * pCon, float fTarget); + int (*originalCheckStatus) (void *motorData, SConnection * pCon); + int iActive; +} MotReg, *pMotReg; /*----------------------------------------------------------------------*/ - pMotReg RegisterMotor(char *name, SicsInterp *pSics, - long (*SetValue)(void *pData, SConnection *pCon, float - fTarget), - int (*CheckStatus)(void *pData, SConnection *pCon)); - void KillRegMot(void *self); +pMotReg RegisterMotor(char *name, SicsInterp * pSics, + long (*SetValue) (void *pData, SConnection * pCon, + float fTarget), + int (*CheckStatus) (void *pData, + SConnection * pCon)); +void KillRegMot(void *self); - void SetRegMotTarget(pMotReg self, float target); - void CreateTargetString(pMotReg self, char pBueffel[80]); +void SetRegMotTarget(pMotReg self, float target); +void CreateTargetString(pMotReg self, char pBueffel[80]); - int RegMotMatch(pMotReg self, char *name); +int RegMotMatch(pMotReg self, char *name); - int StartRegMot(pMotReg self, SConnection *pCon, float fValue); +int StartRegMot(pMotReg self, SConnection * pCon, float fValue); + +int CheckRegMot(pMotReg self, SConnection * pCon); - int CheckRegMot(pMotReg self, SConnection *pCon); - #endif - diff --git a/motreglist.c b/motreglist.c index ff7ba7cb..6badef39 100644 --- a/motreglist.c +++ b/motreglist.c @@ -14,106 +14,119 @@ #include "motreglist.h" /*-----------------------------------------------------------------------*/ -int MakeMotList(){ +int MakeMotList() +{ return LLDcreate(sizeof(pMotReg)); } + /*----------------------------------------------------------------------*/ -pMotReg FindMotEntry(int iList, char *name){ +pMotReg FindMotEntry(int iList, char *name) +{ int iRet; pMotReg pMot = NULL; iRet = LLDnodePtr2First(iList); - while(iRet != 0){ - LLDnodeDataTo(iList,&pMot); - if(pMot != NULL){ - if(RegMotMatch(pMot,name)){ - return pMot; + while (iRet != 0) { + LLDnodeDataTo(iList, &pMot); + if (pMot != NULL) { + if (RegMotMatch(pMot, name)) { + return pMot; } } iRet = LLDnodePtr2Next(iList); } return NULL; } + /*-----------------------------------------------------------------------*/ -pMotReg FindMotFromDataStructure(int iList, void *pData){ +pMotReg FindMotFromDataStructure(int iList, void *pData) +{ int iRet; pMotReg pMot = NULL; iRet = LLDnodePtr2First(iList); - while(iRet != 0){ - LLDnodeDataTo(iList,&pMot); - if(pMot != NULL){ - if(pMot->motorData == pData){ - return pMot; + while (iRet != 0) { + LLDnodeDataTo(iList, &pMot); + if (pMot != NULL) { + if (pMot->motorData == pData) { + return pMot; } } iRet = LLDnodePtr2Next(iList); } return NULL; } + /*----------------------------------------------------------------------*/ -int CheckAllMotors(int iList, SConnection *pCon){ +int CheckAllMotors(int iList, SConnection * pCon) +{ int iRet, count = 0; pMotReg pMot = NULL; iRet = LLDnodePtr2First(iList); - while(iRet != 0){ - LLDnodeDataTo(iList,&pMot); - if(pMot != NULL){ - CheckRegMot(pMot,pCon); - if(pMot->iActive){ - count++; + while (iRet != 0) { + LLDnodeDataTo(iList, &pMot); + if (pMot != NULL) { + CheckRegMot(pMot, pCon); + if (pMot->iActive) { + count++; } } iRet = LLDnodePtr2Next(iList); } return count; } + /*----------------------------------------------------------------------*/ -void StopAllMotors(int iList){ +void StopAllMotors(int iList) +{ int iRet, count = 0; pMotReg pMot = NULL; pIDrivable pDriv; iRet = LLDnodePtr2First(iList); - while(iRet != 0){ - LLDnodeDataTo(iList,&pMot); - if(pMot != NULL){ - if(pMot->iActive){ - pDriv = (pIDrivable)GetDrivableInterface(pMot->motorData); - if(pDriv){ - pDriv->Halt(pMot->motorData); - } - pMot->iActive = 0; + while (iRet != 0) { + LLDnodeDataTo(iList, &pMot); + if (pMot != NULL) { + if (pMot->iActive) { + pDriv = (pIDrivable) GetDrivableInterface(pMot->motorData); + if (pDriv) { + pDriv->Halt(pMot->motorData); + } + pMot->iActive = 0; } } iRet = LLDnodePtr2Next(iList); } } + /*----------------------------------------------------------------------*/ -void DeactivateAllMotors(int iList){ +void DeactivateAllMotors(int iList) +{ int iRet, count = 0; pMotReg pMot = NULL; pIDrivable pDriv; iRet = LLDnodePtr2First(iList); - while(iRet != 0){ - LLDnodeDataTo(iList,&pMot); - if(pMot != NULL){ + while (iRet != 0) { + LLDnodeDataTo(iList, &pMot); + if (pMot != NULL) { pMot->iActive = 0; } iRet = LLDnodePtr2Next(iList); } } + /*----------------------------------------------------------------------*/ -void KillMotList(int iList){ +void KillMotList(int iList) +{ int iRet; pMotReg pMot = NULL; iRet = LLDnodePtr2First(iList); - while(iRet != 0){ - LLDnodeDataTo(iList,&pMot); - if(pMot != NULL){ + while (iRet != 0) { + LLDnodeDataTo(iList, &pMot); + if (pMot != NULL) { KillRegMot(pMot); } iRet = LLDnodePtr2Next(iList); diff --git a/motreglist.h b/motreglist.h index dd887a53..5aaca947 100644 --- a/motreglist.h +++ b/motreglist.h @@ -14,17 +14,15 @@ #include "motreg.h" - int MakeMotList(); - pMotReg FindMotEntry(int iList,char *name); - pMotReg FindMotFromDataStructure(int iList, void *pData); - int CheckAllMotors(int iList, SConnection *pCon); - void KillMotList(int iList); - void StopAllMotors(int iList); - void DeactivateAllMotors(int iList); - +int MakeMotList(); +pMotReg FindMotEntry(int iList, char *name); +pMotReg FindMotFromDataStructure(int iList, void *pData); +int CheckAllMotors(int iList, SConnection * pCon); +void KillMotList(int iList); +void StopAllMotors(int iList); +void DeactivateAllMotors(int iList); + #endif - - diff --git a/multicounter.c b/multicounter.c index 7b1a9367..ac71b29b 100644 --- a/multicounter.c +++ b/multicounter.c @@ -28,170 +28,183 @@ #define MAXSLAVE 16 #define NOCOUNTERS -2727 /*=============== code for the driver ======================================*/ -typedef struct { - void *slaveData[MAXSLAVE]; - pICountable slaves[MAXSLAVE]; - char *transferScript; - int nSlaves; -}MultiCounter, *pMultiCounter; +typedef struct { + void *slaveData[MAXSLAVE]; + pICountable slaves[MAXSLAVE]; + char *transferScript; + int nSlaves; +} MultiCounter, *pMultiCounter; /*--------------------------------------------------------------------------*/ -static void KillMultiDriver(struct __COUNTER *data){ - pMultiCounter self = (pMultiCounter)data->pData; - if(self == NULL){ - return; - } - if(self->transferScript != NULL){ - free(self->transferScript); - } - free(self); +static void KillMultiDriver(struct __COUNTER *data) +{ + pMultiCounter self = (pMultiCounter) data->pData; + if (self == NULL) { + return; + } + if (self->transferScript != NULL) { + free(self->transferScript); + } + free(self); } + /*============== countable interface functions ============================*/ -static int MMCCHalt(void *pData){ +static int MMCCHalt(void *pData) +{ int i, retVal = OKOK, status; pCounter pCount = NULL; pMultiCounter self = NULL; - pCount = (pCounter)pData; - if(pCount != NULL){ - self = (pMultiCounter)pCount->pDriv->pData; + pCount = (pCounter) pData; + if (pCount != NULL) { + self = (pMultiCounter) pCount->pDriv->pData; } assert(self); - for(i = 0; i < self->nSlaves; i++){ + for (i = 0; i < self->nSlaves; i++) { status = self->slaves[i]->Halt(self->slaveData[i]); ReleaseCountLock(self->slaves[i]); - if(status != OKOK) + if (status != OKOK) retVal = status; } ReleaseCountLock(pCount->pCountInt); return retVal; } + /*-------------------------------------------------------------------------*/ -static int MMCCStart(void *pData, SConnection *pCon) +static int MMCCStart(void *pData, SConnection * pCon) { int i, status; pCounter pCount = NULL; pMultiCounter self = NULL; - pCount = (pCounter)pData; - if(pCount != NULL){ - self = (pMultiCounter)pCount->pDriv->pData; + pCount = (pCounter) pData; + if (pCount != NULL) { + self = (pMultiCounter) pCount->pDriv->pData; } assert(self); - - if(!GetCountLock(pCount->pCountInt, pCon)){ - return HWFault; + + if (!GetCountLock(pCount->pCountInt, pCon)) { + return HWFault; } - - for(i = 0; i < self->nSlaves; i++){ + + for (i = 0; i < self->nSlaves; i++) { self->slaves[i]->SetCountParameters(self->slaveData[i], - pCount->pDriv->fPreset, pCount->pDriv->eMode); + pCount->pDriv->fPreset, + pCount->pDriv->eMode); ReleaseCountLock(self->slaves[i]); - status = self->slaves[i]->StartCount(self->slaveData[i],pCon); - if(status != OKOK){ + status = self->slaves[i]->StartCount(self->slaveData[i], pCon); + if (status != OKOK) { MMCCHalt(pData); return status; } } pCount->isUpToDate = 0; pCount->tStart = time(NULL); - InvokeCallBack(pCount->pCall,COUNTSTART,pCon); + InvokeCallBack(pCount->pCall, COUNTSTART, pCon); return OKOK; } + /*-------------------------------------------------------------------------*/ -static int MMCCStatus(void *pData, SConnection *pCon){ - int status,i; +static int MMCCStatus(void *pData, SConnection * pCon) +{ + int status, i; pCounter pCount = NULL; pMultiCounter self = NULL; pDummy pDum = NULL; - pCount = (pCounter)pData; - if(pCount != NULL){ - self = (pMultiCounter)pCount->pDriv->pData; + pCount = (pCounter) pData; + if (pCount != NULL) { + self = (pMultiCounter) pCount->pDriv->pData; } assert(self); - if(self->nSlaves == 0) { + if (self->nSlaves == 0) { pCount->pDriv->iErrorCode = NOCOUNTERS; return HWFault; } - status = self->slaves[0]->CheckCountStatus(self->slaveData[0],pCon); - if(status == HWIdle || status == HWFault){ + status = self->slaves[0]->CheckCountStatus(self->slaveData[0], pCon); + if (status == HWIdle || status == HWFault) { /* - stop counting on slaves when finished or when an error - occurred. - */ - InvokeCallBack(pCount->pCall,COUNTEND,pCon); + stop counting on slaves when finished or when an error + occurred. + */ + InvokeCallBack(pCount->pCall, COUNTEND, pCon); MMCCHalt(pCount); } - for(i = 1; i < MAXSLAVE; i++){ - if(self->slaves[i] != NULL){ - pDum = (pDummy)self->slaveData[i]; - if(strcmp(pDum->pDescriptor->name,"HistMem") == 0){ - HistDirty((pHistMem)self->slaveData[i]); + for (i = 1; i < MAXSLAVE; i++) { + if (self->slaves[i] != NULL) { + pDum = (pDummy) self->slaveData[i]; + if (strcmp(pDum->pDescriptor->name, "HistMem") == 0) { + HistDirty((pHistMem) self->slaveData[i]); } } } return status; } + /*-------------------------------------------------------------------------*/ -static int MMCCPause(void *pData, SConnection *pCon){ +static int MMCCPause(void *pData, SConnection * pCon) +{ int i, status; pCounter pCount = NULL; pMultiCounter self = NULL; - pCount = (pCounter)pData; - if(pCount != NULL){ - self = (pMultiCounter)pCount->pDriv->pData; + pCount = (pCounter) pData; + if (pCount != NULL) { + self = (pMultiCounter) pCount->pDriv->pData; } assert(self); - for(i = 0; i < self->nSlaves; i++){ - status = self->slaves[i]->Pause(self->slaveData[i],pCon); - if(status != OKOK){ + for (i = 0; i < self->nSlaves; i++) { + status = self->slaves[i]->Pause(self->slaveData[i], pCon); + if (status != OKOK) { MMCCHalt(pCount); return status; } } return OKOK; } + /*--------------------------------------------------------------------------*/ -static int MMCCContinue(void *pData, SConnection *pCon){ +static int MMCCContinue(void *pData, SConnection * pCon) +{ int i, status; pCounter pCount = NULL; pMultiCounter self = NULL; - pCount = (pCounter)pData; - if(pCount != NULL){ - self = (pMultiCounter)pCount->pDriv->pData; + pCount = (pCounter) pData; + if (pCount != NULL) { + self = (pMultiCounter) pCount->pDriv->pData; } assert(self); - for(i = 0; i < self->nSlaves; i++){ - status = self->slaves[i]->Continue(self->slaveData[i],pCon); - if(status != OKOK){ + for (i = 0; i < self->nSlaves; i++) { + status = self->slaves[i]->Continue(self->slaveData[i], pCon); + if (status != OKOK) { MMCCHalt(pCount); return status; } } return OKOK; } + /*------------------------------------------------------------------------*/ -static char *getNextMMCCNumber(char *pStart, char pNumber[80]){ +static char *getNextMMCCNumber(char *pStart, char pNumber[80]) +{ int charCount = 0; pNumber[0] = '\0'; /* advance to first digit */ - while(isspace(*pStart) && *pStart != '\0'){ + while (isspace(*pStart) && *pStart != '\0') { pStart++; } - if(*pStart == '\0'){ + if (*pStart == '\0') { return NULL; } /* copy */ - while(!isspace(*pStart) && *pStart != '\0' && charCount < 78){ + while (!isspace(*pStart) && *pStart != '\0' && charCount < 78) { pNumber[charCount] = *pStart; pStart++; charCount++; @@ -199,146 +212,166 @@ static char *getNextMMCCNumber(char *pStart, char pNumber[80]){ pNumber[charCount] = '\0'; return pStart; } + /*-------------------------------------------------------------------------*/ -static void loadCountData(pCounter pCount, const char *data){ - char *pPtr = NULL; - char pNumber[80]; - int i = 0; - - pPtr = (char *)data; - pPtr = getNextMMCCNumber(pPtr,pNumber); - pCount->pDriv->fTime = atof(pNumber); - while(pPtr != NULL && i < MAXCOUNT){ - pPtr = getNextMMCCNumber(pPtr,pNumber); - pCount->pDriv->lCounts[i] = atoi(pNumber); - i++; - } +static void loadCountData(pCounter pCount, const char *data) +{ + char *pPtr = NULL; + char pNumber[80]; + int i = 0; + + pPtr = (char *) data; + pPtr = getNextMMCCNumber(pPtr, pNumber); + pCount->pDriv->fTime = atof(pNumber); + while (pPtr != NULL && i < MAXCOUNT) { + pPtr = getNextMMCCNumber(pPtr, pNumber); + pCount->pDriv->lCounts[i] = atoi(pNumber); + i++; + } } + /*--------------------------------------------------------------------------*/ -static int MMCCTransfer(void *pData, SConnection *pCon){ +static int MMCCTransfer(void *pData, SConnection * pCon) +{ int i, retVal = OKOK, status; char pBueffel[132]; pCounter pCount = NULL; pMultiCounter self = NULL; int tclStatus; - pCount = (pCounter)pData; - if(pCount != NULL){ - self = (pMultiCounter)pCount->pDriv->pData; + pCount = (pCounter) pData; + if (pCount != NULL) { + self = (pMultiCounter) pCount->pDriv->pData; } assert(self); - for(i = 0; i < self->nSlaves; i++){ + for (i = 0; i < self->nSlaves; i++) { status = self->slaves[i]->TransferData(self->slaveData[i], pCon); - if(status != OKOK){ + if (status != OKOK) { retVal = status; - sprintf(pBueffel,"WARNING: slave histogram %d failed to transfer data", - i); - SCWrite(pCon,pBueffel,eWarning); + sprintf(pBueffel, + "WARNING: slave histogram %d failed to transfer data", i); + SCWrite(pCon, pBueffel, eWarning); } } - if(self->transferScript != NULL){ + if (self->transferScript != NULL) { MacroPush(pCon); tclStatus = Tcl_Eval(InterpGetTcl(pServ->pSics), self->transferScript); - if(tclStatus != TCL_OK){ - snprintf(pBueffel,131,"ERROR: TransferScript returned: %s", - Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); - SCWrite(pCon,pBueffel,eError); - MacroPop(); - return HWFault; + if (tclStatus != TCL_OK) { + snprintf(pBueffel, 131, "ERROR: TransferScript returned: %s", + Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); + SCWrite(pCon, pBueffel, eError); + MacroPop(); + return HWFault; } MacroPop(); - loadCountData(pCount,Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); + loadCountData(pCount, Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); } return retVal; } + /*-------------------------------------------------------------------------*/ -static void MMCCParameter(void *pData, float fPreset, CounterMode eMode ){ +static void MMCCParameter(void *pData, float fPreset, CounterMode eMode) +{ int i; pCounter pCount = NULL; pMultiCounter self = NULL; - pCount = (pCounter)pData; - if(pCount != NULL){ - self = (pMultiCounter)pCount->pDriv->pData; + pCount = (pCounter) pData; + if (pCount != NULL) { + self = (pMultiCounter) pCount->pDriv->pData; } assert(self); - for(i = 0; i < self->nSlaves; i++){ + for (i = 0; i < self->nSlaves; i++) { self->slaves[i]->SetCountParameters(self->slaveData[i], fPreset, eMode); } } + /*======================= Driver Interface ==============================*/ -static int MultiCounterSet(struct __COUNTER *self, char *name, - int iCter, float fVal){ - - return 0; +static int MultiCounterSet(struct __COUNTER *self, char *name, + int iCter, float fVal) +{ + + return 0; } + /*-----------------------------------------------------------------------*/ -static int MultiCounterGet(struct __COUNTER *self, char *name, - int iCter, float *fVal){ - - return 0; +static int MultiCounterGet(struct __COUNTER *self, char *name, + int iCter, float *fVal) +{ + + return 0; } + /*-----------------------------------------------------------------------*/ -static int MultiCounterSend(struct __COUNTER *self, char *pText, - char *reply, int replylen){ - - strncpy(reply,"NOT Implemented",replylen); - return 0; +static int MultiCounterSend(struct __COUNTER *self, char *pText, + char *reply, int replylen) +{ + + strncpy(reply, "NOT Implemented", replylen); + return 0; } + /*---------------------------------------------------------------------*/ static int MultiCounterError(struct __COUNTER *pDriv, int *iCode, - char *error, int errlen){ - + char *error, int errlen) +{ - if(pDriv->iErrorCode == NOCOUNTERS){ - strncpy(error,"NO counters configured!",errlen); - } else { - strncpy(error,"Not Implemented", errlen); - } - return COTERM; -} -/*----------------------------------------------------------------------*/ -static int MultiCounterFix(struct __COUNTER *self, int iCode){ + + if (pDriv->iErrorCode == NOCOUNTERS) { + strncpy(error, "NO counters configured!", errlen); + } else { + strncpy(error, "Not Implemented", errlen); + } return COTERM; } -/*=============== Interpreter Interface ================================ */ -int MultiCounterAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ - pMultiCounter self = NULL; - pCounter pCount = NULL; - char buffer[256]; - - if(argc > 1){ - strtolower(argv[1]); - if(strcmp(argv[1],"transferscript") == 0){ - pCount = (pCounter)pData; - self = (pMultiCounter)pCount->pDriv->pData; - if(argc < 3){ - SCPrintf(pCon,eValue,"%s.transferscript = %s", - argv[0],self->transferScript); - return 1; - } else { - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - if(self->transferScript != NULL){ - free(self->transferScript); - } - Arg2Text(argc-2,&argv[2],buffer,255); - self->transferScript = strdup(buffer); - SCSendOK(pCon); - return 1; - } - } - } - return CountAction(pCon,pSics,pData,argc,argv); + +/*----------------------------------------------------------------------*/ +static int MultiCounterFix(struct __COUNTER *self, int iCode) +{ + return COTERM; } + +/*=============== Interpreter Interface ================================ */ +int MultiCounterAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pMultiCounter self = NULL; + pCounter pCount = NULL; + char buffer[256]; + + if (argc > 1) { + strtolower(argv[1]); + if (strcmp(argv[1], "transferscript") == 0) { + pCount = (pCounter) pData; + self = (pMultiCounter) pCount->pDriv->pData; + if (argc < 3) { + SCPrintf(pCon, eValue, "%s.transferscript = %s", + argv[0], self->transferScript); + return 1; + } else { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (self->transferScript != NULL) { + free(self->transferScript); + } + Arg2Text(argc - 2, &argv[2], buffer, 255); + self->transferScript = strdup(buffer); + SCSendOK(pCon); + return 1; + } + } + } + return CountAction(pCon, pSics, pData, argc, argv); +} + /*------------------------------------------------------------------------*/ -int MakeMultiCounter(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ +int MakeMultiCounter(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ int i, status; pCounter pNew = NULL; char pBueffel[132]; @@ -348,42 +381,43 @@ int MakeMultiCounter(SConnection *pCon, SicsInterp *pSics, pCounterDriver pDriv = NULL; /* - need at least two parameters - */ - if(argc < 3){ - SCWrite(pCon,"ERROR: insufficient number of arguments to MakeMultiCounter", - eError); + need at least two parameters + */ + if (argc < 3) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to MakeMultiCounter", + eError); return 0; } /* allocate our data structure - */ + */ self = malloc(sizeof(MultiCounter)); pDriv = malloc(sizeof(CounterDriver)); - if(self == NULL || pDriv == NULL){ - SCWrite(pCon,"ERROR: out of memory in MakeMultiCounter",eError); + if (self == NULL || pDriv == NULL) { + SCWrite(pCon, "ERROR: out of memory in MakeMultiCounter", eError); return 0; } - memset(self,0,sizeof(MultiCounter)); - memset(pDriv,0,sizeof(CounterDriver)); + memset(self, 0, sizeof(MultiCounter)); + memset(pDriv, 0, sizeof(CounterDriver)); pDriv->pData = self; pDriv->KillPrivate = KillMultiDriver; pDriv->iNoOfMonitors = MAXCOUNT; - pNew = CreateCounter(argv[1],pDriv); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory in MakeMultiCounter",eError); + pNew = CreateCounter(argv[1], pDriv); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory in MakeMultiCounter", eError); return 0; } - pDriv->Get = MultiCounterGet; - pDriv->GetError = MultiCounterError; + pDriv->Get = MultiCounterGet; + pDriv->GetError = MultiCounterError; pDriv->TryAndFixIt = MultiCounterFix; - pDriv->Set = MultiCounterSet; - pDriv->Send = MultiCounterSend; - + pDriv->Set = MultiCounterSet; + pDriv->Send = MultiCounterSend; + /* - assign interface functions - */ + assign interface functions + */ pNew->pCountInt->Halt = MMCCHalt; pNew->pCountInt->StartCount = MMCCStart; pNew->pCountInt->CheckCountStatus = MMCCStatus; @@ -393,22 +427,21 @@ int MakeMultiCounter(SConnection *pCon, SicsInterp *pSics, pNew->pCountInt->SetCountParameters = MMCCParameter; /* - now loop through the remaining arguments, thereby entering them into - the slave list. - */ - for(i = 2; i < argc; i++){ - pCom = FindCommand(pSics,argv[i]); - if(!pCom){ - sprintf(pBueffel,"ERROR: object %s not found in MakeMultiCounter", + now loop through the remaining arguments, thereby entering them into + the slave list. + */ + for (i = 2; i < argc; i++) { + pCom = FindCommand(pSics, argv[i]); + if (!pCom) { + sprintf(pBueffel, "ERROR: object %s not found in MakeMultiCounter", argv[i]); - SCWrite(pCon,pBueffel,eError); + SCWrite(pCon, pBueffel, eError); continue; } pCount = GetCountableInterface(pCom->pData); - if(!pCount){ - sprintf(pBueffel,"ERROR: object %s is NOT countable", - argv[i]); - SCWrite(pCon,pBueffel,eError); + if (!pCount) { + sprintf(pBueffel, "ERROR: object %s is NOT countable", argv[i]); + SCWrite(pCon, pBueffel, eError); continue; } self->slaves[self->nSlaves] = pCount; @@ -417,17 +450,16 @@ int MakeMultiCounter(SConnection *pCon, SicsInterp *pSics, } /* - now install our action command and we are done - */ - status = AddCommand(pSics,argv[1],MultiCounterAction,DeleteCounter, - pNew); - if(!status){ - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); + now install our action command and we are done + */ + status = AddCommand(pSics, argv[1], MultiCounterAction, DeleteCounter, + pNew); + if (!status) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); DeleteCounter(pNew); return 0; - } - + } + return 1; } - diff --git a/multicounter.h b/multicounter.h index 400e36f6..ba3434b3 100644 --- a/multicounter.h +++ b/multicounter.h @@ -14,6 +14,6 @@ #define MULTICOUNTER_H_ #include -int MakeMultiCounter(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); -#endif /*MULTICOUNTER_H_*/ +int MakeMultiCounter(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); +#endif /*MULTICOUNTER_H_ */ diff --git a/mumo.c b/mumo.c index d3b8c406..3191e810 100644 --- a/mumo.c +++ b/mumo.c @@ -64,115 +64,108 @@ #include "mumo.h" #include "mumo.i" /*-------------------------------------------------------------------------*/ -static int SaveMumo(void *pData, char *name, FILE *fd) +static int SaveMumo(void *pData, char *name, FILE * fd) { pMulMot self = NULL; char pCommand[512]; const char *pName = NULL; - self = (pMulMot)pData; - if(self == NULL) - { + self = (pMulMot) pData; + if (self == NULL) { return 0; } - fprintf(fd,"#----- MultiMotor %s\n", name); - while((pName = StringDictGetNext(self->pNamPos,pCommand, 511)) != NULL) - { - if(strcmp(pName,"back") != 0) - { - fprintf(fd,"%s recovernampos %s %s\n",name,pName,pCommand); + fprintf(fd, "#----- MultiMotor %s\n", name); + while ((pName = StringDictGetNext(self->pNamPos, pCommand, 511)) != NULL) { + if (strcmp(pName, "back") != 0) { + fprintf(fd, "%s recovernampos %s %s\n", name, pName, pCommand); } } return 1; } + /*--------------------------------------------------------------------------*/ - pMulMot MakeMultiMotor(void) - { - pMulMot pNew = NULL; - - pNew = (pMulMot)malloc(sizeof(MulMot)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(MulMot)); +pMulMot MakeMultiMotor(void) +{ + pMulMot pNew = NULL; - /* the string Dictionaries */ - pNew->pAlias = CreateStringDict(); - pNew->pNamPos = CreateStringDict(); - if( (!pNew->pAlias) || (!pNew->pNamPos)) - { - free(pNew); - return NULL; - } - - pNew->pDes = CreateDescriptor("MulMot"); - if(!pNew->pDes) - { - DeleteStringDict(pNew->pAlias); - DeleteStringDict(pNew->pNamPos); - free(pNew); - return NULL; - } - pNew->pDes->SaveStatus = SaveMumo; - - /* the parameter array */ - pNew->pParam = ObParCreate(1); - ObParInit(pNew->pParam,ACCESS,"accesscode",usUser,usMugger); - - - pNew->name = NULL; - return pNew; + pNew = (pMulMot) malloc(sizeof(MulMot)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(MulMot)); + + /* the string Dictionaries */ + pNew->pAlias = CreateStringDict(); + pNew->pNamPos = CreateStringDict(); + if ((!pNew->pAlias) || (!pNew->pNamPos)) { + free(pNew); + return NULL; + } + + pNew->pDes = CreateDescriptor("MulMot"); + if (!pNew->pDes) { + DeleteStringDict(pNew->pAlias); + DeleteStringDict(pNew->pNamPos); + free(pNew); + return NULL; + } + pNew->pDes->SaveStatus = SaveMumo; + + /* the parameter array */ + pNew->pParam = ObParCreate(1); + ObParInit(pNew->pParam, ACCESS, "accesscode", usUser, usMugger); + + + pNew->name = NULL; + return pNew; +} + +/*-------------------------------------------------------------------------*/ +void KillMultiMotor(void *pData) +{ + pMulMot self; + int i; + + assert(pData); + + self = (pMulMot) pData; + assert(strcmp(self->pDes->name, "MulMot") == 0); + + /* remove string dictionaries */ + if (self->pAlias) { + DeleteStringDict(self->pAlias); + } + if (self->pNamPos) { + DeleteStringDict(self->pNamPos); + } + + /* free descriptor */ + if (self->pDes) { + DeleteDescriptor(self->pDes); } -/*-------------------------------------------------------------------------*/ - void KillMultiMotor(void *pData) - { - pMulMot self; - int i; - - assert(pData); - - self = (pMulMot)pData; - assert(strcmp(self->pDes->name,"MulMot") == 0); - /* remove string dictionaries */ - if(self->pAlias) - { - DeleteStringDict(self->pAlias); - } - if(self->pNamPos) - { - DeleteStringDict(self->pNamPos); - } - - /* free descriptor */ - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - /* kill parameter array */ - ObParDelete(self->pParam); + ObParDelete(self->pParam); /* free name and myself */ - if(self->name) - { - free(self->name); - } - free(self); + if (self->name) { + free(self->name); } + free(self); +} + /*--------------------------------------------------------------------------- Multiple Motors have a funny and flexible syntax. Analysing the argc, argv[] set will not do. Therefore this is done by some recursive descent parsing. */ - - typedef struct __MYTOKEN { - char *pCommand; - char *pPtr; - int iCurrentToken; - char Token[80]; - } sParser, *psParser; + +typedef struct __MYTOKEN { + char *pCommand; + char *pPtr; + int iCurrentToken; + char Token[80]; +} sParser, *psParser; /* define some TokenTypes */ #define END 0 #define INCREMENT 1 @@ -181,7 +174,7 @@ static int SaveMumo(void *pData, char *name, FILE *fd) #define ALIAS 4 #define SYMBOL 5 #define NUMBER 6 -#define EQUALITY 7 +#define EQUALITY 7 #define PLUS 8 #define MINUS 9 #define UNKNOWN 10 @@ -191,314 +184,270 @@ static int SaveMumo(void *pData, char *name, FILE *fd) #define DEFPOS 14 #define RECOVERNAMPOS 15 #define GETPOS 16 -/*-------------------------------------------------------------------------*/ - static int GetNextToken(psParser self, pMulMot pDings) - { - char *pPtr; - int i; - - pPtr = self->pPtr; - - /* skip whitespace */ - while( (*pPtr == ' ') || (*pPtr == '\t') ) - { - pPtr++; - } - - /* check for end */ - if( (*pPtr == '\n') || (*pPtr == '\0') || (*pPtr == '\r') ) - { - self->pPtr = pPtr; - self->Token[0] = *pPtr; - self->Token[1] = '\0'; - self->iCurrentToken = END; - return END; - } - - /* check equaL SIGN */ - if(*pPtr == '=') - { - strcpy(self->Token,"="); - self->iCurrentToken = EQUALITY; - self->pPtr = pPtr +1; - return EQUALITY; - } - - /* check + */ - if(*pPtr == '+') - { - if(*(pPtr+1) == '+') /* increment */ - { - strcpy(self->Token,"++"); - self->iCurrentToken = INCREMENT; - self->pPtr = pPtr+2; - return INCREMENT; - } - else /* silly plus */ - { - strcpy(self->Token,"+"); - self->iCurrentToken = PLUS; - self->pPtr = pPtr + 1; - return PLUS; - } - } - - /* check - */ - if(*pPtr == '-') - { - if(*(pPtr+1) == '-') /* Decrement */ - { - strcpy(self->Token,"--"); - self->iCurrentToken = DECREMENT; - self->pPtr = pPtr+2; - return DECREMENT; - } - else /* silly minus */ - { - strcpy(self->Token,"-"); - self->iCurrentToken = MINUS; - self->pPtr = pPtr + 1; - return MINUS; - } - } - - /* number */ - if( (isdigit((int)*pPtr)) || (*pPtr == '.') ) - { - i = 0; - while (isdigit((int)*pPtr) || (*pPtr == '.') ) - { - self->Token[i] = *pPtr; - i++; - pPtr++; - } - self->Token[i] = '\0'; - self->iCurrentToken = NUMBER; - self->pPtr = pPtr; - return NUMBER; - } - - /* a Symbol ? */ - if(isalnum((int)*pPtr)) - { - i = 0; - while( (!isspace((int)*pPtr)) && (*pPtr != '=') - && (*pPtr != '+') && (*pPtr != '-') &&(*pPtr != '\0') - && (*pPtr != '\n') ) - { - self->Token[i] = *pPtr; - i++; - pPtr++; - } - self->Token[i] = '\0'; - self->pPtr = pPtr; - /* now it can be a named position, a motor alias or a keyword */ - if(StringDictExists(pDings->pNamPos,self->Token)) - { - self->iCurrentToken = NAMPOS; - return NAMPOS; - } - else if(StringDictExists(pDings->pAlias,self->Token)) - { - self->iCurrentToken = ALIAS; - return ALIAS; - } - else if(strcmp(self->Token,"all") == 0) - { - self->iCurrentToken = NAMALL; - return NAMALL; - } - else if(strcmp(self->Token,"list") == 0) - { - self->iCurrentToken = LIST; - return LIST; - } - else if(strcmp(self->Token,"defpos") ==0) - { - self->iCurrentToken = DEFPOS; - return DEFPOS; - } - else if(strcmp(self->Token,"getpos") ==0) - { - self->iCurrentToken = GETPOS; - return GETPOS; - } - else if(strcmp(self->Token,"recovernampos") ==0) - { - self->iCurrentToken = RECOVERNAMPOS; - return RECOVERNAMPOS; - } - else - { - self->iCurrentToken = SYMBOL; - return SYMBOL; - } - } - return UNKNOWN; - } /*-------------------------------------------------------------------------*/ - static void ListMulMot(char *name, SConnection *pCon, pMulMot self) - { - int i, iRet; - char pBueffel[512]; - float fVal; - OutCode eOut = eValue; - const char *pNam = NULL; - char pMotName[132]; - pMotor pMot = NULL; - - sprintf(pBueffel,"Status listing for %s",name); - SCWrite(pCon,pBueffel,eValue); +static int GetNextToken(psParser self, pMulMot pDings) +{ + char *pPtr; + int i; - /* scan through all aliases */ - pNam = StringDictGetNext(self->pAlias,pMotName, 131); - while(pNam != NULL) - { - pMot = FindMotor(GetInterpreter(), pMotName); - assert(pMot); /* has been tested on definition */ - iRet = MotorGetSoftPosition(pMot,pCon,&fVal); - if(!iRet) - { - sprintf(pBueffel,"ERROR: Cannot read motor %s\n", - pMotName); - eOut = eError; - } - else - { - eOut = eValue; - sprintf(pBueffel,"%s.%s = %f\n",name,pNam, fVal); - } - SCWrite(pCon,pBueffel,eValue); - pNam = StringDictGetNext(self->pAlias, pMotName, 131); + pPtr = self->pPtr; + + /* skip whitespace */ + while ((*pPtr == ' ') || (*pPtr == '\t')) { + pPtr++; + } + + /* check for end */ + if ((*pPtr == '\n') || (*pPtr == '\0') || (*pPtr == '\r')) { + self->pPtr = pPtr; + self->Token[0] = *pPtr; + self->Token[1] = '\0'; + self->iCurrentToken = END; + return END; + } + + /* check equaL SIGN */ + if (*pPtr == '=') { + strcpy(self->Token, "="); + self->iCurrentToken = EQUALITY; + self->pPtr = pPtr + 1; + return EQUALITY; + } + + /* check + */ + if (*pPtr == '+') { + if (*(pPtr + 1) == '+') { /* increment */ + strcpy(self->Token, "++"); + self->iCurrentToken = INCREMENT; + self->pPtr = pPtr + 2; + return INCREMENT; + } else { /* silly plus */ + + strcpy(self->Token, "+"); + self->iCurrentToken = PLUS; + self->pPtr = pPtr + 1; + return PLUS; } } + + /* check - */ + if (*pPtr == '-') { + if (*(pPtr + 1) == '-') { /* Decrement */ + strcpy(self->Token, "--"); + self->iCurrentToken = DECREMENT; + self->pPtr = pPtr + 2; + return DECREMENT; + } else { /* silly minus */ + + strcpy(self->Token, "-"); + self->iCurrentToken = MINUS; + self->pPtr = pPtr + 1; + return MINUS; + } + } + + /* number */ + if ((isdigit((int) *pPtr)) || (*pPtr == '.')) { + i = 0; + while (isdigit((int) *pPtr) || (*pPtr == '.')) { + self->Token[i] = *pPtr; + i++; + pPtr++; + } + self->Token[i] = '\0'; + self->iCurrentToken = NUMBER; + self->pPtr = pPtr; + return NUMBER; + } + + /* a Symbol ? */ + if (isalnum((int) *pPtr)) { + i = 0; + while ((!isspace((int) *pPtr)) && (*pPtr != '=') + && (*pPtr != '+') && (*pPtr != '-') && (*pPtr != '\0') + && (*pPtr != '\n')) { + self->Token[i] = *pPtr; + i++; + pPtr++; + } + self->Token[i] = '\0'; + self->pPtr = pPtr; + /* now it can be a named position, a motor alias or a keyword */ + if (StringDictExists(pDings->pNamPos, self->Token)) { + self->iCurrentToken = NAMPOS; + return NAMPOS; + } else if (StringDictExists(pDings->pAlias, self->Token)) { + self->iCurrentToken = ALIAS; + return ALIAS; + } else if (strcmp(self->Token, "all") == 0) { + self->iCurrentToken = NAMALL; + return NAMALL; + } else if (strcmp(self->Token, "list") == 0) { + self->iCurrentToken = LIST; + return LIST; + } else if (strcmp(self->Token, "defpos") == 0) { + self->iCurrentToken = DEFPOS; + return DEFPOS; + } else if (strcmp(self->Token, "getpos") == 0) { + self->iCurrentToken = GETPOS; + return GETPOS; + } else if (strcmp(self->Token, "recovernampos") == 0) { + self->iCurrentToken = RECOVERNAMPOS; + return RECOVERNAMPOS; + } else { + self->iCurrentToken = SYMBOL; + return SYMBOL; + } + } + return UNKNOWN; +} + +/*-------------------------------------------------------------------------*/ +static void ListMulMot(char *name, SConnection * pCon, pMulMot self) +{ + int i, iRet; + char pBueffel[512]; + float fVal; + OutCode eOut = eValue; + const char *pNam = NULL; + char pMotName[132]; + pMotor pMot = NULL; + + sprintf(pBueffel, "Status listing for %s", name); + SCWrite(pCon, pBueffel, eValue); + + /* scan through all aliases */ + pNam = StringDictGetNext(self->pAlias, pMotName, 131); + while (pNam != NULL) { + pMot = FindMotor(GetInterpreter(), pMotName); + assert(pMot); /* has been tested on definition */ + iRet = MotorGetSoftPosition(pMot, pCon, &fVal); + if (!iRet) { + sprintf(pBueffel, "ERROR: Cannot read motor %s\n", pMotName); + eOut = eError; + } else { + eOut = eValue; + sprintf(pBueffel, "%s.%s = %f\n", name, pNam, fVal); + } + SCWrite(pCon, pBueffel, eValue); + pNam = StringDictGetNext(self->pAlias, pMotName, 131); + } +} + /*--------------------------------------------------------------------------*/ - static int ParseAlias(psParser pParse, SConnection *pCon, - pMulMot self) - { - int i, iToken, iRet; - int iSign = 1; - int iInc = 0; - char pBueffel[132]; - char pCommand[1064]; - float fVal = 0, fIn = 0; - int iComplete; - pMotor pMot = NULL; - - /* Okay first find the alias, the current token must still be - its name - */ - strcpy(pCommand,"run "); - iRet = StringDictGet(self->pAlias,pParse->Token,pBueffel,131); - /* that it is alias has been tested earlier */ - assert(iRet == 1); - strcat(pCommand, pBueffel); +static int ParseAlias(psParser pParse, SConnection * pCon, pMulMot self) +{ + int i, iToken, iRet; + int iSign = 1; + int iInc = 0; + char pBueffel[132]; + char pCommand[1064]; + float fVal = 0, fIn = 0; + int iComplete; + pMotor pMot = NULL; + + /* Okay first find the alias, the current token must still be + its name + */ + strcpy(pCommand, "run "); + iRet = StringDictGet(self->pAlias, pParse->Token, pBueffel, 131); + /* that it is alias has been tested earlier */ + assert(iRet == 1); + strcat(pCommand, pBueffel); /* now find the value to handle */ - iToken = GetNextToken(pParse,self); - iComplete = 0; - while(iToken != END) - { - switch(iToken) - { - case PLUS: - iSign = 1; - break; - case MINUS: - iSign = -1; - break; - case EQUALITY: - break; - case INCREMENT: - iInc = 1; - break; - case DECREMENT: - iSign = -1; - iInc = 1; - break; - case NUMBER:/* ey! Do some real work */ - fIn = (float)atof(pParse->Token); - iComplete = 0; - if(iInc) - { - pMot = FindMotor(GetInterpreter(), pBueffel); - assert(pMot); /* existence shoul have been verified earlier */ - MotorGetSoftPosition(pMot,pCon,&fVal); - fVal += iSign * fIn; - sprintf(pBueffel," %f ",fVal); - strcat(pCommand, pBueffel); - InterpExecute(GetInterpreter(),pCon,pCommand); - return 1; - } - else - { - sprintf(pBueffel," %f ",iSign*fIn); - strcat(pCommand, pBueffel); - InterpExecute(GetInterpreter(),pCon,pCommand); - return 1; - } - return 1; - break; - default: - sprintf(pBueffel,"ERROR: Unexpected symbol %s", - pParse->Token); - SCWrite(pCon,pBueffel,eError); - return 0; + iToken = GetNextToken(pParse, self); + iComplete = 0; + while (iToken != END) { + switch (iToken) { + case PLUS: + iSign = 1; + break; + case MINUS: + iSign = -1; + break; + case EQUALITY: + break; + case INCREMENT: + iInc = 1; + break; + case DECREMENT: + iSign = -1; + iInc = 1; + break; + case NUMBER: /* ey! Do some real work */ + fIn = (float) atof(pParse->Token); + iComplete = 0; + if (iInc) { + pMot = FindMotor(GetInterpreter(), pBueffel); + assert(pMot); /* existence shoul have been verified earlier */ + MotorGetSoftPosition(pMot, pCon, &fVal); + fVal += iSign * fIn; + sprintf(pBueffel, " %f ", fVal); + strcat(pCommand, pBueffel); + InterpExecute(GetInterpreter(), pCon, pCommand); + return 1; + } else { + sprintf(pBueffel, " %f ", iSign * fIn); + strcat(pCommand, pBueffel); + InterpExecute(GetInterpreter(), pCon, pCommand); + return 1; } - iToken = GetNextToken(pParse,self); - } - if(!iComplete) - { - SCWrite(pCon,"ERROR: Incomplete command",eError); + return 1; + break; + default: + sprintf(pBueffel, "ERROR: Unexpected symbol %s", pParse->Token); + SCWrite(pCon, pBueffel, eError); return 0; } - return 1; - } - + iToken = GetNextToken(pParse, self); + } + if (!iComplete) { + SCWrite(pCon, "ERROR: Incomplete command", eError); + return 0; + } + return 1; +} + /*-------------------------------------------------------------------------- */ - static int MakeCurrentNamPos(char *name, SConnection *pCon, - pMulMot self) - { - const char *pAlias = NULL; - char pMotort[132]; - char pCommand[1064]; - pMotor pMot = NULL; - float fVal; - int iRet; +static int MakeCurrentNamPos(char *name, SConnection * pCon, pMulMot self) +{ + const char *pAlias = NULL; + char pMotort[132]; + char pCommand[1064]; + pMotor pMot = NULL; + float fVal; + int iRet; + + assert(self); + assert(pCon); + + pCommand[0] = '\0'; + pAlias = StringDictGetNext(self->pAlias, pMotort, 131); + while (pAlias != NULL) { + strcat(pCommand, pMotort); + pMot = FindMotor(GetInterpreter(), pMotort); + assert(pMot); /* validity of alias has already been checked */ + iRet = MotorGetSoftPosition(pMot, pCon, &fVal); + if (!iRet) { + sprintf(pCommand, "ERROR: failure to read motor %s, %s", + pMotort, " named position not created"); + SCWrite(pCon, pCommand, eError); + return 0; + } + sprintf(pMotort, " %f ", fVal); + strcat(pCommand, pMotort); + pAlias = StringDictGetNext(self->pAlias, pMotort, 131); + } + if (StringDictExists(self->pNamPos, name)) { + StringDictUpdate(self->pNamPos, name, pCommand); + } else { + StringDictAddPair(self->pNamPos, name, pCommand); + } + return 1; +} - assert(self); - assert(pCon); - - pCommand[0] = '\0'; - pAlias = StringDictGetNext(self->pAlias, pMotort, 131); - while(pAlias != NULL) - { - strcat(pCommand, pMotort); - pMot = FindMotor(GetInterpreter(),pMotort); - assert(pMot); /* validity of alias has already been checked */ - iRet = MotorGetSoftPosition(pMot,pCon,&fVal); - if(!iRet) - { - sprintf(pCommand,"ERROR: failure to read motor %s, %s", - pMotort," named position not created"); - SCWrite(pCon,pCommand,eError); - return 0; - } - sprintf(pMotort," %f ", fVal); - strcat(pCommand,pMotort); - pAlias = StringDictGetNext(self->pAlias, pMotort, 131); - } - if(StringDictExists(self->pNamPos,name)) - { - StringDictUpdate(self->pNamPos,name,pCommand); - } - else - { - StringDictAddPair(self->pNamPos,name,pCommand); - } - return 1; - } /*-------------------------------------------------------------------------- FindNamPos: checks if the current position is identical to a named position. The comparison is done by getting the motors @@ -506,245 +455,224 @@ static int SaveMumo(void *pData, char *name, FILE *fd) all currently stored named positions. -------------------------------------------------------------------------*/ - const char *FindNamPos(pMulMot self, SConnection *pCon) - { - int iRet, iTest; - char pCurrCommand[1064], pTestCommand[1064]; - const char *pAlias; - char *pName, *pVal; - float f1, f2; - pMotor pMot = NULL; - pStringDict motCache = NULL; - - /* - * create cache of motor positions - */ - motCache = CreateStringDict(); - if(motCache == NULL){ - SCWrite(pCon,"ERROR: out of memory in FindNamPos",eError); - return NULL; - } - StringDictKillScan(self->pAlias); - pAlias = StringDictGetNext(self->pAlias,pCurrCommand,1023); - while(pAlias != NULL){ - pMot = FindMotor(pServ->pSics,pCurrCommand); - if(pMot != NULL){ - iRet = MotorGetSoftPosition(pMot,pCon,&f1); - if(!iRet){ - sprintf(pTestCommand, - "ERROR: failed to get motor position for %s", pName); - SCWrite(pCon,pTestCommand,eError); - return NULL; - } - snprintf(pTestCommand,1023,"%f",f1); - StringDictAddPair(motCache,pCurrCommand,pTestCommand); - } - pAlias = StringDictGetNext(self->pAlias,pCurrCommand,1023); - } - - /* scan named position list */ - StringDictKillScan(self->pNamPos); - pAlias = StringDictGetNext(self->pNamPos,pTestCommand,1063); - while(pAlias != NULL) - { - strcpy(pCurrCommand,pTestCommand); - pName = strtok(pCurrCommand," "); - iTest = 1; - while(pName != NULL) - { - pVal = strtok(NULL," "); - StringDictGetAsNumber(motCache,pName,&f1); - sscanf(pVal,"%f",&f2); - f1 = f1 - f2; - if(f1 < 0.) - f1 = - f1; - if(f1 > 0.03) - { - iTest--; - break; - } - pName = strtok(NULL," "); - } - if(iTest == 1 && (strcmp(pAlias,"back") != 0) ) { - DeleteStringDict(motCache); - return pAlias; - } - pAlias = StringDictGetNext(self->pNamPos,pTestCommand,1063); - } - DeleteStringDict(motCache); - /* not found */ - return NULL; - } -/*--------------------------------------------------------------------------*/ - static int ParseDropPos(psParser pParse, SConnection *pCon, - pMulMot self) - { - int i, iToken, iRet; - char pBueffel[256]; - float fVal = 0; - char pName[80]; - char *pPtr = NULL; - - iToken = GetNextToken(pParse,self); - while(iToken != END) - { - switch(iToken) - { - case EQUALITY: - break; - case NAMPOS: - /* we never want back to be killed ..... */ - if(strcmp(pParse->Token,"back") == 0) - { - SCWrite(pCon, - "ERROR: You are NOT allowed to deleted system position BACK", - eError); - return 0; - } - /* find NamPos and kill it */ - iRet = StringDictDelete(self->pNamPos,pParse->Token); - return 1; - break; - case NAMALL: - /* kill all named positions except back */ - iRet = StringDictGet(self->pNamPos,"back",pBueffel,256); - DeleteStringDict(self->pNamPos); - self->pNamPos = CreateStringDict(); - if(!self->pNamPos) - { - SCWrite(pCon, - "ERROR: severe! out of memory in mumo drop", - eError); - return 0; - } - if(iRet) - { - StringDictAddPair(self->pNamPos,"back",pBueffel); - } - return 1; - break; - default: - sprintf(pBueffel,"ERROR: Unexpected symbol %s", - pParse->Token); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - return 1; - } -/*-------------------------------------------------------------------------*/ - static int CheckPermission(SConnection *pCon, pMulMot self) - { - int iAccess; - char pBueffel[132]; - - iAccess = (int)ObVal(self->pParam,ACCESS); - if(SCMatchRights(pCon, iAccess)) - { - return 1; - } - else - { - sprintf(pBueffel,"ERROR: NO permission to drive %s", - self->name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } -/* ------------------------------------------------------------------------*/ - static int ParseNamPos(psParser pParse, SConnection *pCon, - SicsInterp *pSics, pMulMot self) - { - int iToken, iRet; - char pBueffel[256]; - char pCommand[1064]; - char *pPtr; +const char *FindNamPos(pMulMot self, SConnection * pCon) +{ + int iRet, iTest; + char pCurrCommand[1064], pTestCommand[1064]; + const char *pAlias; + char *pName, *pVal; + float f1, f2; + pMotor pMot = NULL; + pStringDict motCache = NULL; - /* is the user allowed to do ANYTHING ? */ - iRet = CheckPermission(pCon,self); - if(!iRet) - { - return 0; + /* + * create cache of motor positions + */ + motCache = CreateStringDict(); + if (motCache == NULL) { + SCWrite(pCon, "ERROR: out of memory in FindNamPos", eError); + return NULL; + } + StringDictKillScan(self->pAlias); + pAlias = StringDictGetNext(self->pAlias, pCurrCommand, 1023); + while (pAlias != NULL) { + pMot = FindMotor(pServ->pSics, pCurrCommand); + if (pMot != NULL) { + iRet = MotorGetSoftPosition(pMot, pCon, &f1); + if (!iRet) { + sprintf(pTestCommand, + "ERROR: failed to get motor position for %s", pName); + SCWrite(pCon, pTestCommand, eError); + return NULL; } - - strcpy(pCommand,"run "); - pPtr = pCommand + strlen("run "); - iRet = StringDictGet(self->pNamPos,pParse->Token,pPtr, 1050); - if(iRet) - { - InterpExecute(GetInterpreter(),pCon,pCommand); - return 1; + snprintf(pTestCommand, 1023, "%f", f1); + StringDictAddPair(motCache, pCurrCommand, pTestCommand); + } + pAlias = StringDictGetNext(self->pAlias, pCurrCommand, 1023); + } + + /* scan named position list */ + StringDictKillScan(self->pNamPos); + pAlias = StringDictGetNext(self->pNamPos, pTestCommand, 1063); + while (pAlias != NULL) { + strcpy(pCurrCommand, pTestCommand); + pName = strtok(pCurrCommand, " "); + iTest = 1; + while (pName != NULL) { + pVal = strtok(NULL, " "); + StringDictGetAsNumber(motCache, pName, &f1); + sscanf(pVal, "%f", &f2); + f1 = f1 - f2; + if (f1 < 0.) + f1 = -f1; + if (f1 > 0.03) { + iTest--; + break; } - else - { - sprintf(pCommand,"ERROR: named position %s NOT found",pParse->Token); - SCWrite(pCon,pCommand,eError); + pName = strtok(NULL, " "); + } + if (iTest == 1 && (strcmp(pAlias, "back") != 0)) { + DeleteStringDict(motCache); + return pAlias; + } + pAlias = StringDictGetNext(self->pNamPos, pTestCommand, 1063); + } + DeleteStringDict(motCache); + /* not found */ + return NULL; +} + +/*--------------------------------------------------------------------------*/ +static int ParseDropPos(psParser pParse, SConnection * pCon, pMulMot self) +{ + int i, iToken, iRet; + char pBueffel[256]; + float fVal = 0; + char pName[80]; + char *pPtr = NULL; + + iToken = GetNextToken(pParse, self); + while (iToken != END) { + switch (iToken) { + case EQUALITY: + break; + case NAMPOS: + /* we never want back to be killed ..... */ + if (strcmp(pParse->Token, "back") == 0) { + SCWrite(pCon, + "ERROR: You are NOT allowed to deleted system position BACK", + eError); return 0; } - return 0; /* not reached */ + /* find NamPos and kill it */ + iRet = StringDictDelete(self->pNamPos, pParse->Token); + return 1; + break; + case NAMALL: + /* kill all named positions except back */ + iRet = StringDictGet(self->pNamPos, "back", pBueffel, 256); + DeleteStringDict(self->pNamPos); + self->pNamPos = CreateStringDict(); + if (!self->pNamPos) { + SCWrite(pCon, "ERROR: severe! out of memory in mumo drop", eError); + return 0; + } + if (iRet) { + StringDictAddPair(self->pNamPos, "back", pBueffel); + } + return 1; + break; + default: + sprintf(pBueffel, "ERROR: Unexpected symbol %s", pParse->Token); + SCWrite(pCon, pBueffel, eError); + return 0; + } } -/*-------------------------------------------------------------------------*/ - static int ParseDefPos(SicsInterp *pSics,psParser pPP, - pMulMot self, SConnection *pCon) - { - pMotor pMot = NULL; - char pError[132], motorName[80], command[1024], namPos[80]; - int iToken, status; - float fVal; - - - iToken = GetNextToken(pPP,self); - if(iToken != SYMBOL) /* we want a name here */ - { - sprintf(pError,"ERROR: Invalid Token %s in ParsePos",pPP->Token); - SCWrite(pCon,pError,eError); - return 0; - } - - strncpy(namPos,pPP->Token,79); - iToken = GetNextToken(pPP,self); - command[0] = '\0'; - while(iToken != END) - { - if(iToken != ALIAS) - { - sprintf(command,"ERROR: expected motor alias, got: %s", pPP->Token); - SCWrite(pCon,command,eError); - return 0; - } - StringDictGet(self->pAlias,pPP->Token,motorName,79); - strcat(command, motorName); - strcat(command," "); - iToken = GetNextToken(pPP,self); - if(iToken != NUMBER) - { - sprintf(command,"ERROR: expected number, got: %s", pPP->Token); - SCWrite(pCon,command,eError); - return 0; - } - strcat(command,pPP->Token); - strcat(command," "); - iToken = GetNextToken(pPP,self); - } + return 1; +} - StringDictAddPair(self->pNamPos,namPos,command); +/*-------------------------------------------------------------------------*/ +static int CheckPermission(SConnection * pCon, pMulMot self) +{ + int iAccess; + char pBueffel[132]; + + iAccess = (int) ObVal(self->pParam, ACCESS); + if (SCMatchRights(pCon, iAccess)) { return 1; - } + } else { + sprintf(pBueffel, "ERROR: NO permission to drive %s", self->name); + SCWrite(pCon, pBueffel, eError); + return 0; + } +} + +/* ------------------------------------------------------------------------*/ +static int ParseNamPos(psParser pParse, SConnection * pCon, + SicsInterp * pSics, pMulMot self) +{ + int iToken, iRet; + char pBueffel[256]; + char pCommand[1064]; + char *pPtr; + + /* is the user allowed to do ANYTHING ? */ + iRet = CheckPermission(pCon, self); + if (!iRet) { + return 0; + } + + strcpy(pCommand, "run "); + pPtr = pCommand + strlen("run "); + iRet = StringDictGet(self->pNamPos, pParse->Token, pPtr, 1050); + if (iRet) { + InterpExecute(GetInterpreter(), pCon, pCommand); + return 1; + } else { + sprintf(pCommand, "ERROR: named position %s NOT found", pParse->Token); + SCWrite(pCon, pCommand, eError); + return 0; + } + return 0; /* not reached */ +} + +/*-------------------------------------------------------------------------*/ +static int ParseDefPos(SicsInterp * pSics, psParser pPP, + pMulMot self, SConnection * pCon) +{ + pMotor pMot = NULL; + char pError[132], motorName[80], command[1024], namPos[80]; + int iToken, status; + float fVal; + + + iToken = GetNextToken(pPP, self); + if (iToken != SYMBOL) { /* we want a name here */ + sprintf(pError, "ERROR: Invalid Token %s in ParsePos", pPP->Token); + SCWrite(pCon, pError, eError); + return 0; + } + + strncpy(namPos, pPP->Token, 79); + iToken = GetNextToken(pPP, self); + command[0] = '\0'; + while (iToken != END) { + if (iToken != ALIAS) { + sprintf(command, "ERROR: expected motor alias, got: %s", pPP->Token); + SCWrite(pCon, command, eError); + return 0; + } + StringDictGet(self->pAlias, pPP->Token, motorName, 79); + strcat(command, motorName); + strcat(command, " "); + iToken = GetNextToken(pPP, self); + if (iToken != NUMBER) { + sprintf(command, "ERROR: expected number, got: %s", pPP->Token); + SCWrite(pCon, command, eError); + return 0; + } + strcat(command, pPP->Token); + strcat(command, " "); + iToken = GetNextToken(pPP, self); + } + + StringDictAddPair(self->pNamPos, namPos, command); + return 1; +} + /*-----------------------------------------------------------------------*/ static void RecoverNamPos(pMulMot self, int argc, char *argv[]) { char pCommand[512]; - Arg2Text(argc-1,&argv[1],pCommand, 511); - if(StringDictExists(self->pNamPos,argv[0])) - { - StringDictUpdate(self->pNamPos,argv[0],pCommand); + Arg2Text(argc - 1, &argv[1], pCommand, 511); + if (StringDictExists(self->pNamPos, argv[0])) { + StringDictUpdate(self->pNamPos, argv[0], pCommand); + } else { + StringDictAddPair(self->pNamPos, argv[0], pCommand); } - else - { - StringDictAddPair(self->pNamPos,argv[0],pCommand); - } -} +} + /*--------------------------------------------------------------------------- MultiWrapper is the user interface to a multi motor unit. It supports the following syntax, where DingsBums is the name of the unit: @@ -764,198 +692,165 @@ static void RecoverNamPos(pMulMot self, int argc, char *argv[]) saved named positions -*/ - - - int MultiWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - char pError[132]; - sParser MyParser; - int iToken; - int iRet; - pMulMot self; - int iAlias = 0; - const char *pPtr; - Tcl_DString tString; - - assert(pCon); - assert(pSics); - assert(pData); - - self = (pMulMot)pData; - assert(strcmp(self->pDes->name,"MulMot")== 0); - - /* setup */ - argtolower(argc,argv); - iRet = Arg2Text(argc,argv,pBueffel,511); - if(!iRet) - { - SCWrite(pCon,"Command line to long",eError); +*/ + + +int MultiWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512]; + char pError[132]; + sParser MyParser; + int iToken; + int iRet; + pMulMot self; + int iAlias = 0; + const char *pPtr; + Tcl_DString tString; + + assert(pCon); + assert(pSics); + assert(pData); + + self = (pMulMot) pData; + assert(strcmp(self->pDes->name, "MulMot") == 0); + + /* setup */ + argtolower(argc, argv); + iRet = Arg2Text(argc, argv, pBueffel, 511); + if (!iRet) { + SCWrite(pCon, "Command line to long", eError); + return 0; + } + MyParser.pPtr = &pBueffel[0]; + MyParser.pCommand = pBueffel; + + /* ignore first Token: that is my name ! */ + iToken = GetNextToken(&MyParser, self); + + /* now loop through my Tokens */ + iToken = GetNextToken(&MyParser, self); + if (iToken == END) { + ListMulMot(argv[0], pCon, self); + return 1; + } + while (iToken != END) { + switch (iToken) { + case END: + SCSendOK(pCon); + return 1; + case NAMPOS: + /* do a named position, current token is it */ + if (strcmp(MyParser.Token, "back") != 0) { + MakeCurrentNamPos("back", pCon, self); + } + iRet = ParseNamPos(&MyParser, pCon, pSics, self); + if (iRet) { + SCSendOK(pCon); + SCparChange(pCon); + return 1; + } else { + return 0; + } + break; + case ALIAS: + iRet = CheckPermission(pCon, self); + if (iAlias == 0) { + MakeCurrentNamPos("back", pCon, self); + iAlias = 1; + } + if (!iRet) { + return 0; + } + iRet = ParseAlias(&MyParser, pCon, self); + if (!iRet) { + return 0; + } + break; + case GETPOS: + pPtr = FindNamPos(self, pCon); + if (pPtr != NULL) { + sprintf(pBueffel, "%s.nampos = %s", argv[0], pPtr); + } else { + sprintf(pBueffel, "%s.nampos = undefined", argv[0]); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + case DEFPOS: + SCparChange(pCon); + return ParseDefPos(pSics, &MyParser, self, pCon); + break; + case LIST: + pPtr = NULL; + Tcl_DStringInit(&tString); + sprintf(pBueffel, "%s list of known named positions \n", argv[0]); + Tcl_DStringAppend(&tString, pBueffel, strlen(pBueffel)); + StringDictKillScan(self->pNamPos); + pPtr = StringDictGetNext(self->pNamPos, pError, 131); + while (pPtr != NULL) { + Tcl_DStringAppend(&tString, (char *) pPtr, -1); + Tcl_DStringAppend(&tString, " \n", -1); + pPtr = StringDictGetNext(self->pNamPos, pError, 131); + } + SCWrite(pCon, Tcl_DStringValue(&tString), eValue); + Tcl_DStringFree(&tString); + return 1; + break; + case SYMBOL: + if (strcmp(MyParser.Token, "pos") == 0) { + iRet = CheckPermission(pCon, self); + if (!iRet) { + return 0; + } else { + iToken = GetNextToken(&MyParser, self); + if ((iToken == SYMBOL) || (iToken == NAMPOS)) { + MakeCurrentNamPos(MyParser.Token, pCon, self); + SCparChange(pCon); + return 1; + } else { + sprintf(pError, "ERROR: %s no valid named position name", + MyParser.Token); + SCWrite(pCon, pError, eError); + return 0; + } + } + } + if (strcmp(MyParser.Token, "drop") == 0) { + iRet = CheckPermission(pCon, self); + if (!iRet) { + return 0; + } else { + SCparChange(pCon); + return ParseDropPos(&MyParser, pCon, self); + } + } + if (strcmp(MyParser.Token, "find") == 0) { + pPtr = NULL; + pPtr = FindNamPos(self, pCon); + if (pPtr) { + sprintf(pBueffel, "%s.namedposition = %s", argv[0], pPtr); + } else { + sprintf(pBueffel, "%s.namedposition = UNKNOWN", argv[0]); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + } + sprintf(pError, "ERROR: Unknown Token %s", MyParser.Token); + SCWrite(pCon, pError, eError); + return 0; + case RECOVERNAMPOS: + /* + This is not meant to be user command but a facility to read + back data from sattus file. This is why the error checking + is not happening + */ + RecoverNamPos(self, argc - 2, &argv[2]); + return 1; + default: + SCWrite(pCon, "ERROR: Parse Error", eError); return 0; } - MyParser.pPtr = &pBueffel[0]; - MyParser.pCommand = pBueffel; - - /* ignore first Token: that is my name ! */ - iToken = GetNextToken(&MyParser,self); - - /* now loop through my Tokens */ - iToken = GetNextToken(&MyParser,self); - if(iToken == END) - { - ListMulMot(argv[0],pCon,self); - return 1; - } - while( iToken != END) - { - switch(iToken) - { - case END: - SCSendOK(pCon); - return 1; - case NAMPOS: - /* do a named position, current token is it */ - if(strcmp(MyParser.Token,"back")!= 0) - { - MakeCurrentNamPos("back",pCon,self); - } - iRet = ParseNamPos(&MyParser,pCon,pSics,self); - if(iRet) - { - SCSendOK(pCon); - SCparChange(pCon); - return 1; - } - else - { - return 0; - } - break; - case ALIAS: - iRet = CheckPermission(pCon, self); - if(iAlias == 0) - { - MakeCurrentNamPos("back",pCon,self); - iAlias = 1; - } - if(!iRet) - { - return 0; - } - iRet = ParseAlias(&MyParser,pCon,self); - if(!iRet) - { - return 0; - } - break; - case GETPOS: - pPtr = FindNamPos(self,pCon); - if(pPtr != NULL) - { - sprintf(pBueffel,"%s.nampos = %s",argv[0], pPtr); - } - else - { - sprintf(pBueffel,"%s.nampos = undefined",argv[0]); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - case DEFPOS: - SCparChange(pCon); - return ParseDefPos(pSics,&MyParser,self,pCon); - break; - case LIST: - pPtr = NULL; - Tcl_DStringInit(&tString); - sprintf(pBueffel,"%s list of known named positions \n", - argv[0]); - Tcl_DStringAppend(&tString,pBueffel,strlen(pBueffel)); - StringDictKillScan(self->pNamPos); - pPtr = StringDictGetNext(self->pNamPos,pError,131); - while(pPtr != NULL) - { - Tcl_DStringAppend(&tString,(char *)pPtr,-1); - Tcl_DStringAppend (&tString," \n",-1); - pPtr = StringDictGetNext(self->pNamPos, - pError,131); - } - SCWrite(pCon,Tcl_DStringValue(&tString),eValue); - Tcl_DStringFree(&tString); - return 1; - break; - case SYMBOL: - if(strcmp(MyParser.Token,"pos") == 0) - { - iRet = CheckPermission(pCon,self); - if(!iRet) - { - return 0; - } - else - { - iToken = GetNextToken(&MyParser, self); - if((iToken == SYMBOL) || (iToken == NAMPOS)) - { - MakeCurrentNamPos(MyParser.Token,pCon,self); - SCparChange(pCon); - return 1; - } - else - { - sprintf(pError,"ERROR: %s no valid named position name", - MyParser.Token); - SCWrite(pCon,pError,eError); - return 0; - } - } - } - if(strcmp(MyParser.Token,"drop") == 0) - { - iRet = CheckPermission(pCon,self); - if(!iRet) - { - return 0; - } - else - { - SCparChange(pCon); - return ParseDropPos(&MyParser, pCon, self); - } - } - if(strcmp(MyParser.Token,"find") == 0) - { - pPtr = NULL; - pPtr = FindNamPos(self,pCon); - if(pPtr) - { - sprintf(pBueffel,"%s.namedposition = %s",argv[0],pPtr); - } - else - { - sprintf(pBueffel,"%s.namedposition = UNKNOWN",argv[0]); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - } - sprintf(pError,"ERROR: Unknown Token %s",MyParser.Token); - SCWrite(pCon,pError,eError); - return 0; - case RECOVERNAMPOS: - /* - This is not meant to be user command but a facility to read - back data from sattus file. This is why the error checking - is not happening - */ - RecoverNamPos(self,argc-2,&argv[2]); - return 1; - default: - SCWrite(pCon,"ERROR: Parse Error",eError); - return 0; - } - iToken = GetNextToken(&MyParser,self); - } - return 1; - } - + iToken = GetNextToken(&MyParser, self); + } + return 1; +} diff --git a/mumo.h b/mumo.h index 84983a76..d1f9d999 100644 --- a/mumo.h +++ b/mumo.h @@ -15,22 +15,21 @@ #ifndef SICSMUMO #define SICSMUMO /*-------------------------------------------------------------------------*/ - typedef struct __MULMOT *pMulMot; +typedef struct __MULMOT *pMulMot; - pMulMot MakeMultiMotor(void); - void KillMultiMotor(void *pData); - - const char *FindNamPos(pMulMot self, SConnection *pCon); - - int MultiWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +pMulMot MakeMultiMotor(void); +void KillMultiMotor(void *pData); - int MakeMulti(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - - int ConfigMulti(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - - -#endif +const char *FindNamPos(pMulMot self, SConnection * pCon); +int MultiWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +int MakeMulti(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +int ConfigMulti(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + + +#endif diff --git a/mumoconf.c b/mumoconf.c index 305a7417..2b53d5fc 100644 --- a/mumoconf.c +++ b/mumoconf.c @@ -62,13 +62,13 @@ Once again, the demands for command evaluation are high. Therefore a recursice descent parser. */ - - typedef struct __MYTOKEN { - char *pCommand; - char *pPtr; - int iCurrentToken; - char Token[80]; - } sParser, *psParser; + +typedef struct __MYTOKEN { + char *pCommand; + char *pPtr; + int iCurrentToken; + char Token[80]; +} sParser, *psParser; /* define Token Types */ #define UNKNOWN 0 @@ -80,295 +80,271 @@ #define NUMBER 6 #define ENDCONFIG 7 -/*-------------------------------------------------------------------------*/ - static int GetNextToken(psParser self) - { - char *pPtr; - int i; - - pPtr = self->pPtr; - - /* skip whitespace */ - while( (*pPtr == ' ') || (*pPtr == '\t') ) - { - pPtr++; - } +/*-------------------------------------------------------------------------*/ +static int GetNextToken(psParser self) +{ + char *pPtr; + int i; - /* check for end */ - if( (*pPtr == '\n') || (*pPtr == '\0') || (*pPtr == '\r') ) - { - self->pPtr = pPtr; - self->Token[0] = *pPtr; - self->Token[1] = '\0'; - self->iCurrentToken = END; - return END; - } + pPtr = self->pPtr; + + /* skip whitespace */ + while ((*pPtr == ' ') || (*pPtr == '\t')) { + pPtr++; + } + + /* check for end */ + if ((*pPtr == '\n') || (*pPtr == '\0') || (*pPtr == '\r')) { + self->pPtr = pPtr; + self->Token[0] = *pPtr; + self->Token[1] = '\0'; + self->iCurrentToken = END; + return END; + } - - /* check equaL SIGN */ - if(*pPtr == '=') - { - strcpy(self->Token,"="); - self->iCurrentToken = EQUALITY; - self->pPtr = pPtr +1; - return EQUALITY; - } - - /* number */ - if( (isdigit((int)*pPtr)) || (*pPtr == '.') - ||(*pPtr == '+') || (*pPtr == '-') ) - { - i = 0; - while (isdigit((int)*pPtr) || (*pPtr == '.') - ||(*pPtr == '+') || (*pPtr == '-') ) - { - self->Token[i] = *pPtr; - i++; - pPtr++; - } - self->Token[i] = '\0'; - self->iCurrentToken = NUMBER; - self->pPtr = pPtr; - return NUMBER; - } - - /* a Symbol ? */ - if(isalnum((int)*pPtr)) - { - i = 0; - while( (!isspace((int)*pPtr)) && (*pPtr != '=') - && (*pPtr != '+') && (*pPtr != '-') - && (*pPtr != '\0') && (*pPtr != '\n') ) - { - self->Token[i] = *pPtr; - i++; - pPtr++; - } - self->Token[i] = '\0'; - self->pPtr = pPtr; - /* now it can be one of the keywords, a motor or a symbol */ - if(strcmp(self->Token,"alias") == 0) - { - self->iCurrentToken = ALIAS; - return ALIAS; - } - else if(strcmp(self->Token,"pos") == 0) - { - self->iCurrentToken = POS; - return POS; - } - else if(strcmp(self->Token,"endconfig") == 0) - { - self->iCurrentToken = ENDCONFIG; - return ENDCONFIG; - } - else - { - self->iCurrentToken = SYMBOL; - return SYMBOL; - } - } - return UNKNOWN; - } + + /* check equaL SIGN */ + if (*pPtr == '=') { + strcpy(self->Token, "="); + self->iCurrentToken = EQUALITY; + self->pPtr = pPtr + 1; + return EQUALITY; + } + + /* number */ + if ((isdigit((int) *pPtr)) || (*pPtr == '.') + || (*pPtr == '+') || (*pPtr == '-')) { + i = 0; + while (isdigit((int) *pPtr) || (*pPtr == '.') + || (*pPtr == '+') || (*pPtr == '-')) { + self->Token[i] = *pPtr; + i++; + pPtr++; + } + self->Token[i] = '\0'; + self->iCurrentToken = NUMBER; + self->pPtr = pPtr; + return NUMBER; + } + + /* a Symbol ? */ + if (isalnum((int) *pPtr)) { + i = 0; + while ((!isspace((int) *pPtr)) && (*pPtr != '=') + && (*pPtr != '+') && (*pPtr != '-') + && (*pPtr != '\0') && (*pPtr != '\n')) { + self->Token[i] = *pPtr; + i++; + pPtr++; + } + self->Token[i] = '\0'; + self->pPtr = pPtr; + /* now it can be one of the keywords, a motor or a symbol */ + if (strcmp(self->Token, "alias") == 0) { + self->iCurrentToken = ALIAS; + return ALIAS; + } else if (strcmp(self->Token, "pos") == 0) { + self->iCurrentToken = POS; + return POS; + } else if (strcmp(self->Token, "endconfig") == 0) { + self->iCurrentToken = ENDCONFIG; + return ENDCONFIG; + } else { + self->iCurrentToken = SYMBOL; + return SYMBOL; + } + } + return UNKNOWN; +} + /*-------------------------------------------------------------------------- in this code we need to find a motor for a name quite frequently....... */ - pMotor FindMotor(SicsInterp *pSics, char *name) - { - CommandList *pC; - pMotor pMot; - - pC = FindCommand(pSics,name); - if(!pC) - { - return NULL; - } - pMot = (pMotor)pC->pData; - if(!pMot) - { - return NULL; - } - if(strcmp(pMot->pDescriptor->name,"Motor") != 0) - { - return NULL; - } - return pMot; +pMotor FindMotor(SicsInterp * pSics, char *name) +{ + CommandList *pC; + pMotor pMot; + + pC = FindCommand(pSics, name); + if (!pC) { + return NULL; } + pMot = (pMotor) pC->pData; + if (!pMot) { + return NULL; + } + if (strcmp(pMot->pDescriptor->name, "Motor") != 0) { + return NULL; + } + return pMot; +} + /*--------------------------------------------------------------------------*/ - int MakeMulti(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - /* this does not do much, just installs the configuration command */ - pMulMot pNew = NULL; - int iRet; - char pBueffel[512]; - - if(argc < 2) - { - SCWrite(pCon,"You need to specify a name for a MultiMotor",eError); - return 0; - } +int MakeMulti(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + /* this does not do much, just installs the configuration command */ + pMulMot pNew = NULL; + int iRet; + char pBueffel[512]; - /* check rights */ - if(!SCMatchRights(pCon,usMugger)) - { - SCWrite(pCon,"ERROR: you are not permitted to do this",eError); - return 0; - } - - pNew = MakeMultiMotor(); - if(!pNew) - { - SCWrite(pCon,"No Memory for creating MultiMot",eError); - return 0; - } - pNew->name = strdup(argv[1]); - iRet = AddCommand(pSics,argv[1],ConfigMulti,NULL,pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } -/*-------------------------------------------------------------------------*/ - static int ParseAlias(SicsInterp *pSics,psParser pPP, pMulMot self, SConnection *pCon) - { - int iToken; - char pError[132]; - pMotor pMot; - - /* next token should be a motor name */ - iToken = GetNextToken(pPP); - if(iToken != SYMBOL) - { - sprintf(pError,"ERROR: Token %s not recognized in MulMot alias", - pPP->Token); - SCWrite(pCon,pError,eError); - return 0; - } - /* try find the motor and verify that it is a motor */ - pMot = FindMotor(pSics,pPP->Token); - if(!pMot) - { - sprintf(pError,"ERROR: Motor %s not found, no alias created", - pPP->Token); - SCWrite(pCon,pError,eError); - return 0; - } - - /* now pMot holds all info ever needed about the motor */ - /* the next Token should be a symbol giving the alias */ - iToken = GetNextToken(pPP); - if(iToken == EQUALITY) /* tolerate Equality */ - { - iToken = GetNextToken(pPP); - } - if(iToken != SYMBOL) - { - sprintf(pError,"ERROR: Token %s not recognized in MulMot alias", - pPP->Token); - SCWrite(pCon,pError,eError); - return 0; - } - - /* now we have all that is ever needed to create an alias. We have done - so much work in order to get here, that it will be done, here and - now! - */ - StringDictAddPair(self->pAlias,pPP->Token,pMot->name); - return 1; - } - -/*-------------------------------------------------------------------------*/ - static int ParsePos(SicsInterp *pSics,psParser pPP, - pMulMot self, SConnection *pCon) - { - pMotor pMot = NULL; - char pError[132]; - int iToken; - float fVal; - - iToken = GetNextToken(pPP); - if(iToken != SYMBOL) /* we want a name here */ - { - sprintf(pError,"ERROR: Invalid Token %s in ParsePos",pPP->Token); - SCWrite(pCon,pError,eError); - return 0; - } - - /* The rest of the stuff should be the motors to drive until - we are there - */ - StringDictAddPair(self->pNamPos,pPP->Token,pPP->pPtr); - return 1; - } -/*--------------------------------------------------------------------------*/ - int ConfigMulti(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pMulMot self; - char pBueffel[512]; - char pError[132]; - int i, iToken, iRet; - sParser PP; - CommandList *pCom = NULL; - - assert(pCon); - assert(pSics); - assert(pData); - - self = (pMulMot)pData; - - iRet = Arg2Text(argc,argv,pBueffel,511); - if(!iRet) - { - sprintf(pBueffel,"Argument string to long for %s configuration",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - strtolower(pBueffel); - - /* first token is name, ignore */ - PP.pCommand = pBueffel; - PP.pPtr = pBueffel; - iToken = GetNextToken(&PP); - iToken = GetNextToken(&PP); - while(iToken != END) - { - switch(iToken) - { - case END: - return 1; /* ignored */ - break; - case ENDCONFIG: - /* reconfigure command to final state */ - pCom = FindCommand(pSics,argv[0]); - assert(pCom != NULL); - pCom->OFunc = MultiWrapper; - pCom->KFunc = KillMultiMotor; - return 1; - break; - case ALIAS: - return ParseAlias(pSics,&PP,self,pCon); - break; - case POS: - return ParsePos(pSics,&PP,self,pCon); - break; - default: - sprintf(pError,"ERROR: Invalid Token %s found in %s", - PP.Token, argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iToken = GetNextToken(&PP); - } - /* should never end here */ - sprintf(pError,"ERROR: %s was NOT understood in mumoconf",pBueffel); - SCWrite(pCon,pError,eError); + if (argc < 2) { + SCWrite(pCon, "You need to specify a name for a MultiMotor", eError); return 0; - } + } + /* check rights */ + if (!SCMatchRights(pCon, usMugger)) { + SCWrite(pCon, "ERROR: you are not permitted to do this", eError); + return 0; + } + + pNew = MakeMultiMotor(); + if (!pNew) { + SCWrite(pCon, "No Memory for creating MultiMot", eError); + return 0; + } + pNew->name = strdup(argv[1]); + iRet = AddCommand(pSics, argv[1], ConfigMulti, NULL, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int ParseAlias(SicsInterp * pSics, psParser pPP, pMulMot self, + SConnection * pCon) +{ + int iToken; + char pError[132]; + pMotor pMot; + + /* next token should be a motor name */ + iToken = GetNextToken(pPP); + if (iToken != SYMBOL) { + sprintf(pError, "ERROR: Token %s not recognized in MulMot alias", + pPP->Token); + SCWrite(pCon, pError, eError); + return 0; + } + /* try find the motor and verify that it is a motor */ + pMot = FindMotor(pSics, pPP->Token); + if (!pMot) { + sprintf(pError, "ERROR: Motor %s not found, no alias created", + pPP->Token); + SCWrite(pCon, pError, eError); + return 0; + } + + /* now pMot holds all info ever needed about the motor */ + /* the next Token should be a symbol giving the alias */ + iToken = GetNextToken(pPP); + if (iToken == EQUALITY) { /* tolerate Equality */ + iToken = GetNextToken(pPP); + } + if (iToken != SYMBOL) { + sprintf(pError, "ERROR: Token %s not recognized in MulMot alias", + pPP->Token); + SCWrite(pCon, pError, eError); + return 0; + } + + /* now we have all that is ever needed to create an alias. We have done + so much work in order to get here, that it will be done, here and + now! + */ + StringDictAddPair(self->pAlias, pPP->Token, pMot->name); + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int ParsePos(SicsInterp * pSics, psParser pPP, + pMulMot self, SConnection * pCon) +{ + pMotor pMot = NULL; + char pError[132]; + int iToken; + float fVal; + + iToken = GetNextToken(pPP); + if (iToken != SYMBOL) { /* we want a name here */ + sprintf(pError, "ERROR: Invalid Token %s in ParsePos", pPP->Token); + SCWrite(pCon, pError, eError); + return 0; + } + + /* The rest of the stuff should be the motors to drive until + we are there + */ + StringDictAddPair(self->pNamPos, pPP->Token, pPP->pPtr); + return 1; +} + +/*--------------------------------------------------------------------------*/ +int ConfigMulti(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pMulMot self; + char pBueffel[512]; + char pError[132]; + int i, iToken, iRet; + sParser PP; + CommandList *pCom = NULL; + + assert(pCon); + assert(pSics); + assert(pData); + + self = (pMulMot) pData; + + iRet = Arg2Text(argc, argv, pBueffel, 511); + if (!iRet) { + sprintf(pBueffel, "Argument string to long for %s configuration", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + strtolower(pBueffel); + + /* first token is name, ignore */ + PP.pCommand = pBueffel; + PP.pPtr = pBueffel; + iToken = GetNextToken(&PP); + iToken = GetNextToken(&PP); + while (iToken != END) { + switch (iToken) { + case END: + return 1; /* ignored */ + break; + case ENDCONFIG: + /* reconfigure command to final state */ + pCom = FindCommand(pSics, argv[0]); + assert(pCom != NULL); + pCom->OFunc = MultiWrapper; + pCom->KFunc = KillMultiMotor; + return 1; + break; + case ALIAS: + return ParseAlias(pSics, &PP, self, pCon); + break; + case POS: + return ParsePos(pSics, &PP, self, pCon); + break; + default: + sprintf(pError, "ERROR: Invalid Token %s found in %s", + PP.Token, argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iToken = GetNextToken(&PP); + } + /* should never end here */ + sprintf(pError, "ERROR: %s was NOT understood in mumoconf", pBueffel); + SCWrite(pCon, pError, eError); + return 0; +} diff --git a/napi.c b/napi.c index a821750b..d229d0b6 100644 --- a/napi.c +++ b/napi.c @@ -23,7 +23,7 @@ ----------------------------------------------------------------------------*/ -static const char* rscid = "$Id: napi.c,v 1.14 2008/01/03 09:56:56 koennecke Exp $"; /* Revision inserted by CVS */ +static const char *rscid = "$Id: napi.c,v 1.15 2009/02/13 09:00:20 koennecke Exp $"; /* Revision inserted by CVS */ #include #include @@ -57,83 +57,88 @@ extern char *stptok(char *s, char *tok, size_t toklen, char *brk); /*--------------------------------------------------------------------- wrapper for getenv. This is a future proofing thing for porting to OS which have different ways of accessing environment variables - --------------------------------------------------------------------*/ -static char *nxgetenv(const char *name){ + --------------------------------------------------------------------*/ +static char *nxgetenv(const char *name) +{ return getenv(name); } + /*----------------------------------------------------------------------*/ -static int canOpen(char *filename){ +static int canOpen(char *filename) +{ FILE *fd = NULL; - fd = fopen(filename,"r"); - if(fd != NULL){ + fd = fopen(filename, "r"); + if (fd != NULL) { fclose(fd); return 1; } else { return 0; } -} +} + /*--------------------------------------------------------------------*/ -static char *locateNexusFileInPath(char *startName){ +static char *locateNexusFileInPath(char *startName) +{ char *loadPath = NULL, *testPath = NULL, *pPtr = NULL; char pathPrefix[256]; int length; - if(canOpen(startName)){ + if (canOpen(startName)) { return strdup(startName); } loadPath = nxgetenv("NX_LOAD_PATH"); - if(loadPath == NULL){ + if (loadPath == NULL) { /* file not found will be issued by upper level code */ return strdup(startName); } - pPtr = stptok(loadPath,pathPrefix,255,LIBSEP); - while(pPtr != NULL){ + pPtr = stptok(loadPath, pathPrefix, 255, LIBSEP); + while (pPtr != NULL) { length = strlen(pathPrefix) + strlen(startName) + strlen(PATHSEP) + 2; - testPath = malloc(length*sizeof(char)); - if(testPath == NULL){ + testPath = malloc(length * sizeof(char)); + if (testPath == NULL) { return strdup(startName); } - memset(testPath,0,length*sizeof(char)); + memset(testPath, 0, length * sizeof(char)); strcpy(testPath, pathPrefix); - strcat(testPath,PATHSEP); - strcat(testPath,startName); - if(canOpen(testPath)){ - return(testPath); + strcat(testPath, PATHSEP); + strcat(testPath, startName); + if (canOpen(testPath)) { + return (testPath); } free(testPath); - pPtr = stptok(pPtr,pathPrefix,255,LIBSEP); + pPtr = stptok(pPtr, pathPrefix, 255, LIBSEP); } - return strdup(startName); + return strdup(startName); } + /*------------------------------------------------------------------------ HDF-5 cache size special stuff -------------------------------------------------------------------------*/ -long nx_cacheSize = 1024000; /* 1MB, HDF-5 default */ +long nx_cacheSize = 1024000; /* 1MB, HDF-5 default */ NXstatus NXsetcache(long newVal) { - if(newVal > 0) - { + if (newVal > 0) { nx_cacheSize = newVal; return NX_OK; } return NX_ERROR; } - + /*-----------------------------------------------------------------------*/ -static NXstatus NXisXML(CONSTCHAR *filename) +static NXstatus NXisXML(CONSTCHAR * filename) { FILE *fd = NULL; char line[132]; - fd = fopen(filename,"r"); - if(fd) { - fgets(line,131,fd); + fd = fopen(filename, "r"); + if (fd) { + fgets(line, 131, fd); fclose(fd); - if(strstr(line,"?xml") != NULL){ + if (strstr(line, "?xml") != NULL) { return NX_OK; } } @@ -141,42 +146,47 @@ static NXstatus NXisXML(CONSTCHAR *filename) } /*-------------------------------------------------------------------------*/ - static void NXNXNXReportError(void *pData, char *string) - { - printf("%s \n",string); - } +static void NXNXNXReportError(void *pData, char *string) +{ + printf("%s \n", string); +} + /*---------------------------------------------------------------------*/ - void *NXpData = NULL; - void (*NXIReportError)(void *pData, char *string) = NXNXNXReportError; +void *NXpData = NULL; +void (*NXIReportError) (void *pData, char *string) = NXNXNXReportError; /*---------------------------------------------------------------------*/ - extern void NXMSetError(void *pData, - void (*NewError)(void *pD, char *text)) - { - NXpData = pData; - NXIReportError = NewError; - } +extern void NXMSetError(void *pData, + void (*NewError) (void *pD, char *text)) +{ + NXpData = pData; + NXIReportError = NewError; +} + /*----------------------------------------------------------------------*/ -extern ErrFunc NXMGetError(){ +extern ErrFunc NXMGetError() +{ return NXIReportError; } /*----------------------------------------------------------------------*/ -void NXNXNoReport(void *pData, char *string){ +void NXNXNoReport(void *pData, char *string) +{ /* do nothing */ -} +} + /*----------------------------------------------------------------------*/ static ErrFunc last_errfunc = NXNXNXReportError; extern void NXMDisableErrorReporting() { - last_errfunc = NXMGetError(); - NXMSetError(NXpData, NXNXNoReport); + last_errfunc = NXMGetError(); + NXMSetError(NXpData, NXNXNoReport); } extern void NXMEnableErrorReporting() { - NXMSetError(NXpData, last_errfunc); + NXMSetError(NXpData, last_errfunc); } /*----------------------------------------------------------------------*/ @@ -188,559 +198,573 @@ extern void NXMEnableErrorReporting() #endif #ifdef NXXML #include "nxxml.h" -#endif +#endif /* ---------------------------------------------------------------------- - - Definition of NeXus API - ---------------------------------------------------------------------*/ -static int determineFileType(CONSTCHAR *filename) + Definition of NeXus API + + --------------------------------------------------------------------- */ +static int determineFileType(CONSTCHAR * filename) { FILE *fd = NULL; int iRet, fapl; NXhandle handle; - + /* - this is for reading, check for existence first - */ - fd = fopen(filename,"r"); - if(fd == NULL){ + this is for reading, check for existence first + */ + fd = fopen(filename, "r"); + if (fd == NULL) { return -1; } fclose(fd); #ifdef HDF5 - iRet=H5Fis_hdf5((const char*)filename); - if( iRet > 0){ + iRet = H5Fis_hdf5((const char *) filename); + if (iRet > 0) { return 2; } -#endif +#endif #ifdef HDF4 - iRet=Hishdf((const char*)filename); - if( iRet > 0){ + iRet = Hishdf((const char *) filename); + if (iRet > 0) { return 1; } #endif #ifdef NXXML iRet = NXisXML(filename); - if(iRet == NX_OK){ + if (iRet == NX_OK) { return 3; } #endif /* - file type not recognized - */ + file type not recognized + */ return 0; } + /*---------------------------------------------------------------------*/ -static pNexusFunction handleToNexusFunc(NXhandle fid){ +static pNexusFunction handleToNexusFunc(NXhandle fid) +{ pFileStack fileStack = NULL; - fileStack = (pFileStack)fid; - if(fileStack != NULL){ + fileStack = (pFileStack) fid; + if (fileStack != NULL) { return peekFileOnStack(fileStack); } else { return NULL; } } + /*--------------------------------------------------------------------*/ -static NXstatus NXinternalopen(CONSTCHAR *userfilename, NXaccess am, - pFileStack fileStack); +static NXstatus NXinternalopen(CONSTCHAR * userfilename, NXaccess am, + pFileStack fileStack); /*----------------------------------------------------------------------*/ -NXstatus NXopen(CONSTCHAR *userfilename, NXaccess am, NXhandle *gHandle){ +NXstatus NXopen(CONSTCHAR * userfilename, NXaccess am, NXhandle * gHandle) +{ int status; pFileStack fileStack = NULL; NXhandle hfile; fileStack = makeFileStack(); - if(fileStack == NULL){ - NXIReportError (NXpData,"ERROR: no memory to create filestack"); - return NX_ERROR; + if (fileStack == NULL) { + NXIReportError(NXpData, "ERROR: no memory to create filestack"); + return NX_ERROR; } - status = NXinternalopen(userfilename,am,fileStack); - if(status == NX_OK){ + status = NXinternalopen(userfilename, am, fileStack); + if (status == NX_OK) { *gHandle = fileStack; } return status; } + /*-----------------------------------------------------------------------*/ -static NXstatus NXinternalopen(CONSTCHAR *userfilename, NXaccess am, pFileStack fileStack) - { - int hdf_type=0; - int iRet=0; - NXhandle hdf5_handle = NULL; - NXhandle hdf4_handle = NULL; - NXhandle xmlHandle = NULL; - pNexusFunction fHandle = NULL; - NXstatus retstat = NX_ERROR; - char error[1024]; - char *filename = NULL; - - /* configure fortify - iFortifyScope = Fortify_EnterScope(); - Fortify_CheckAllMemory(); - */ - - /* - allocate data - */ - fHandle = (pNexusFunction)malloc(sizeof(NexusFunction)); - if (fHandle == NULL) { - NXIReportError (NXpData,"ERROR: no memory to create Function structure"); +static NXstatus NXinternalopen(CONSTCHAR * userfilename, NXaccess am, + pFileStack fileStack) +{ + int hdf_type = 0; + int iRet = 0; + NXhandle hdf5_handle = NULL; + NXhandle hdf4_handle = NULL; + NXhandle xmlHandle = NULL; + pNexusFunction fHandle = NULL; + NXstatus retstat = NX_ERROR; + char error[1024]; + char *filename = NULL; + + /* configure fortify + iFortifyScope = Fortify_EnterScope(); + Fortify_CheckAllMemory(); + */ + + /* + allocate data + */ + fHandle = (pNexusFunction) malloc(sizeof(NexusFunction)); + if (fHandle == NULL) { + NXIReportError(NXpData, + "ERROR: no memory to create Function structure"); + return NX_ERROR; + } + memset(fHandle, 0, sizeof(NexusFunction)); /* so any functions we miss are NULL */ + + /* + test the strip flag. Elimnate it for the rest of the tests to work + */ + fHandle->stripFlag = 1; + if (am & NXACC_NOSTRIP) { + fHandle->stripFlag = 0; + am -= NXACC_NOSTRIP; + } + + if (am == NXACC_CREATE) { + /* HDF4 will be used ! */ + hdf_type = 1; + filename = strdup(userfilename); + } else if (am == NXACC_CREATE4) { + /* HDF4 will be used ! */ + hdf_type = 1; + filename = strdup(userfilename); + } else if (am == NXACC_CREATE5) { + /* HDF5 will be used ! */ + hdf_type = 2; + filename = strdup(userfilename); + } else if (am == NXACC_CREATEXML) { + /* XML will be used ! */ + hdf_type = 3; + filename = strdup(userfilename); + } else { + filename = locateNexusFileInPath((char *) userfilename); + if (filename == NULL) { + NXIReportError(NXpData, "Out of memory in NeXus-API"); + free(fHandle); return NX_ERROR; } - memset(fHandle, 0, sizeof(NexusFunction)); /* so any functions we miss are NULL */ - - /* - test the strip flag. Elimnate it for the rest of the tests to work - */ - fHandle->stripFlag = 1; - if(am & NXACC_NOSTRIP){ - fHandle->stripFlag = 0; - am -= NXACC_NOSTRIP; - } - - if (am==NXACC_CREATE) { - /* HDF4 will be used ! */ - hdf_type=1; - filename = strdup(userfilename); - } else if (am==NXACC_CREATE4) { - /* HDF4 will be used ! */ - hdf_type=1; - filename = strdup(userfilename); - } else if (am==NXACC_CREATE5) { - /* HDF5 will be used ! */ - hdf_type=2; - filename = strdup(userfilename); - } else if (am==NXACC_CREATEXML) { - /* XML will be used ! */ - hdf_type=3; - filename = strdup(userfilename); - } else { - filename = locateNexusFileInPath((char *)userfilename); - if(filename == NULL){ - NXIReportError(NXpData,"Out of memory in NeXus-API"); - free(fHandle); - return NX_ERROR; - } - /* check file type hdf4/hdf5/XML for reading */ - iRet = determineFileType(filename); - if(iRet < 0) { - snprintf(error,1023,"failed to open %s for reading", - filename); - NXIReportError(NXpData,error); - free(filename); - return NX_ERROR; - } - if(iRet == 0){ - snprintf(error,1023,"failed to determine filetype for %s ", - filename); - NXIReportError(NXpData,error); - free(filename); - free(fHandle); - return NX_ERROR; - } - hdf_type = iRet; - } - if(filename == NULL){ - NXIReportError(NXpData,"Out of memory in NeXus-API"); - return NX_ERROR; - } - - if (hdf_type==1) { - /* HDF4 type */ -#ifdef HDF4 - retstat = NX4open((const char *)filename,am,&hdf4_handle); - if(retstat != NX_OK){ - free(fHandle); - free(filename); - return retstat; - } - fHandle->pNexusData=hdf4_handle; - NX4assignFunctions(fHandle); - pushFileStack(fileStack,fHandle,filename); -#else - NXIReportError (NXpData, - "ERROR: Attempt to create HDF4 file when not linked with HDF4"); - retstat = NX_ERROR; -#endif /* HDF4 */ + /* check file type hdf4/hdf5/XML for reading */ + iRet = determineFileType(filename); + if (iRet < 0) { + snprintf(error, 1023, "failed to open %s for reading", filename); + NXIReportError(NXpData, error); free(filename); - return retstat; - } else if (hdf_type==2) { - /* HDF5 type */ -#ifdef HDF5 - retstat = NX5open(filename,am,&hdf5_handle); - if(retstat != NX_OK){ - free(fHandle); - free(filename); - return retstat; - } - fHandle->pNexusData=hdf5_handle; - NX5assignFunctions(fHandle); - pushFileStack(fileStack,fHandle, filename); -#else - NXIReportError (NXpData, - "ERROR: Attempt to create HDF5 file when not linked with HDF5"); - retstat = NX_ERROR; -#endif /* HDF5 */ + return NX_ERROR; + } + if (iRet == 0) { + snprintf(error, 1023, "failed to determine filetype for %s ", + filename); + NXIReportError(NXpData, error); + free(filename); + free(fHandle); + return NX_ERROR; + } + hdf_type = iRet; + } + if (filename == NULL) { + NXIReportError(NXpData, "Out of memory in NeXus-API"); + return NX_ERROR; + } + + if (hdf_type == 1) { + /* HDF4 type */ +#ifdef HDF4 + retstat = NX4open((const char *) filename, am, &hdf4_handle); + if (retstat != NX_OK) { + free(fHandle); free(filename); return retstat; - } else if(hdf_type == 3){ - /* - XML type - */ -#ifdef NXXML - retstat = NXXopen(filename,am,&xmlHandle); - if(retstat != NX_OK){ - free(fHandle); - free(filename); - return retstat; - } - fHandle->pNexusData=xmlHandle; - NXXassignFunctions(fHandle); - pushFileStack(fileStack,fHandle, filename); + } + fHandle->pNexusData = hdf4_handle; + NX4assignFunctions(fHandle); + pushFileStack(fileStack, fHandle, filename); #else - NXIReportError (NXpData, - "ERROR: Attempt to create XML file when not linked with XML"); - retstat = NX_ERROR; -#endif - } else { - NXIReportError (NXpData, - "ERROR: Format not readable by this NeXus library"); - retstat = NX_ERROR; - } - if (filename != NULL) { - free(filename); - } + NXIReportError(NXpData, + "ERROR: Attempt to create HDF4 file when not linked with HDF4"); + retstat = NX_ERROR; +#endif /* HDF4 */ + free(filename); return retstat; + } else if (hdf_type == 2) { + /* HDF5 type */ +#ifdef HDF5 + retstat = NX5open(filename, am, &hdf5_handle); + if (retstat != NX_OK) { + free(fHandle); + free(filename); + return retstat; + } + fHandle->pNexusData = hdf5_handle; + NX5assignFunctions(fHandle); + pushFileStack(fileStack, fHandle, filename); +#else + NXIReportError(NXpData, + "ERROR: Attempt to create HDF5 file when not linked with HDF5"); + retstat = NX_ERROR; +#endif /* HDF5 */ + free(filename); + return retstat; + } else if (hdf_type == 3) { + /* + XML type + */ +#ifdef NXXML + retstat = NXXopen(filename, am, &xmlHandle); + if (retstat != NX_OK) { + free(fHandle); + free(filename); + return retstat; + } + fHandle->pNexusData = xmlHandle; + NXXassignFunctions(fHandle); + pushFileStack(fileStack, fHandle, filename); +#else + NXIReportError(NXpData, + "ERROR: Attempt to create XML file when not linked with XML"); + retstat = NX_ERROR; +#endif + } else { + NXIReportError(NXpData, + "ERROR: Format not readable by this NeXus library"); + retstat = NX_ERROR; } + if (filename != NULL) { + free(filename); + } + return retstat; +} /* ------------------------------------------------------------------------- */ - NXstatus NXclose (NXhandle *fid) - { - NXhandle hfil; - int status; - pFileStack fileStack = NULL; - - pNexusFunction pFunc=NULL; - fileStack = (pFileStack)*fid; - pFunc = peekFileOnStack(fileStack); - hfil = pFunc->pNexusData; - status = pFunc->nxclose(&hfil); - pFunc->pNexusData = hfil; - free(pFunc); - popFileStack(fileStack); - if(fileStackDepth(fileStack) < 0){ - killFileStack(fileStack); - } - /* - Fortify_CheckAllMemory(); - */ - return status; - } +NXstatus NXclose(NXhandle * fid) +{ + NXhandle hfil; + int status; + pFileStack fileStack = NULL; - /*-----------------------------------------------------------------------*/ - - NXstatus NXmakegroup (NXhandle fid, CONSTCHAR *name, CONSTCHAR *nxclass) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxmakegroup(pFunc->pNexusData, name, nxclass); + pNexusFunction pFunc = NULL; + fileStack = (pFileStack) * fid; + pFunc = peekFileOnStack(fileStack); + hfil = pFunc->pNexusData; + status = pFunc->nxclose(&hfil); + pFunc->pNexusData = hfil; + free(pFunc); + popFileStack(fileStack); + if (fileStackDepth(fileStack) < 0) { + killFileStack(fileStack); } + /* + Fortify_CheckAllMemory(); + */ + return status; +} + + /*-----------------------------------------------------------------------*/ + +NXstatus NXmakegroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxmakegroup(pFunc->pNexusData, name, nxclass); +} + /*------------------------------------------------------------------------*/ -static int analyzeNapimount(char *napiMount, char *extFile, int extFileLen, - char *extPath, int extPathLen){ +static int analyzeNapimount(char *napiMount, char *extFile, int extFileLen, + char *extPath, int extPathLen) +{ char *pPtr = NULL, *path = NULL; int length; - memset(extFile,0,extFileLen); - memset(extPath,0,extPathLen); - pPtr = strstr(napiMount,"nxfile://"); - if(pPtr == NULL){ + memset(extFile, 0, extFileLen); + memset(extPath, 0, extPathLen); + pPtr = strstr(napiMount, "nxfile://"); + if (pPtr == NULL) { return NXBADURL; } - path = strrchr(napiMount,'#'); - if(path == NULL){ + path = strrchr(napiMount, '#'); + if (path == NULL) { length = strlen(napiMount) - 9; - if(length > extFileLen){ - NXIReportError(NXpData,"ERROR: internal errro with external linking"); + if (length > extFileLen) { + NXIReportError(NXpData, + "ERROR: internal errro with external linking"); return NXBADURL; } - memcpy(extFile,pPtr+9,length); - strcpy(extPath,"/"); + memcpy(extFile, pPtr + 9, length); + strcpy(extPath, "/"); return NXFILE; } else { pPtr += 9; length = path - pPtr; - if(length > extFileLen){ - NXIReportError(NXpData,"ERROR: internal errro with external linking"); + if (length > extFileLen) { + NXIReportError(NXpData, + "ERROR: internal errro with external linking"); return NXBADURL; } - memcpy(extFile,pPtr,length); - length = strlen(path-1); - if(length > extPathLen){ - NXIReportError(NXpData,"ERROR: internal error with external linking"); + memcpy(extFile, pPtr, length); + length = strlen(path - 1); + if (length > extPathLen) { + NXIReportError(NXpData, + "ERROR: internal error with external linking"); return NXBADURL; } - strcpy(extPath,path+1); + strcpy(extPath, path + 1); return NXFILE; } return NXBADURL; } + /*------------------------------------------------------------------------*/ - NXstatus NXopengroup (NXhandle fid, CONSTCHAR *name, CONSTCHAR *nxclass) - { - int status, attStatus, type = NX_CHAR, length = 1023; - NXaccess access = NXACC_RDWR; - NXlink breakID; - pFileStack fileStack; - char nxurl[1024], exfile[512], expath[512]; - ErrFunc oldError; - pNexusFunction pFunc = NULL; +NXstatus NXopengroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass) +{ + int status, attStatus, type = NX_CHAR, length = 1023; + NXaccess access = NXACC_RDWR; + NXlink breakID; + pFileStack fileStack; + char nxurl[1024], exfile[512], expath[512]; + ErrFunc oldError; + pNexusFunction pFunc = NULL; - fileStack = (pFileStack)fid; - pFunc = handleToNexusFunc(fid); + fileStack = (pFileStack) fid; + pFunc = handleToNexusFunc(fid); - status = pFunc->nxopengroup(pFunc->pNexusData, name, nxclass); - oldError = NXMGetError(); - NXIReportError = NXNXNoReport; - attStatus = NXgetattr(fid,"napimount",nxurl,&length, &type); - NXIReportError = oldError; - if(attStatus == NX_OK){ - /* - this is an external linking group - */ - status = analyzeNapimount(nxurl,exfile,511,expath,511); - if(status == NXBADURL){ - return NX_ERROR; - } - status = NXinternalopen(exfile,access, fileStack); - if(status == NX_ERROR){ - return status; - } - status = NXopenpath(fid,expath); - NXgetgroupID(fid,&breakID); - setCloseID(fileStack,breakID); + status = pFunc->nxopengroup(pFunc->pNexusData, name, nxclass); + oldError = NXMGetError(); + NXIReportError = NXNXNoReport; + attStatus = NXgetattr(fid, "napimount", nxurl, &length, &type); + NXIReportError = oldError; + if (attStatus == NX_OK) { + /* + this is an external linking group + */ + status = analyzeNapimount(nxurl, exfile, 511, expath, 511); + if (status == NXBADURL) { + return NX_ERROR; } - - return status; - } + status = NXinternalopen(exfile, access, fileStack); + if (status == NX_ERROR) { + return status; + } + status = NXopenpath(fid, expath); + NXgetgroupID(fid, &breakID); + setCloseID(fileStack, breakID); + } + + return status; +} /* ------------------------------------------------------------------- */ - NXstatus NXclosegroup (NXhandle fid) - { - int status; - pFileStack fileStack = NULL; - NXlink closeID, currentID; +NXstatus NXclosegroup(NXhandle fid) +{ + int status; + pFileStack fileStack = NULL; + NXlink closeID, currentID; - pNexusFunction pFunc = handleToNexusFunc(fid); - fileStack = (pFileStack)fid; - if(fileStackDepth(fileStack) == 0){ - return pFunc->nxclosegroup(pFunc->pNexusData); + pNexusFunction pFunc = handleToNexusFunc(fid); + fileStack = (pFileStack) fid; + if (fileStackDepth(fileStack) == 0) { + return pFunc->nxclosegroup(pFunc->pNexusData); + } else { + /* we have to check for leaving an external file */ + NXgetgroupID(fid, ¤tID); + peekIDOnStack(fileStack, &closeID); + if (NXsameID(fid, &closeID, ¤tID) == NX_OK) { + NXclose(&fid); + status = NXclosegroup(fid); } else { - /* we have to check for leaving an external file */ - NXgetgroupID(fid,¤tID); - peekIDOnStack(fileStack,&closeID); - if(NXsameID(fid,&closeID,¤tID) == NX_OK){ - NXclose(&fid); - status = NXclosegroup(fid); - } else { - status = pFunc->nxclosegroup(pFunc->pNexusData); - } - return status; + status = pFunc->nxclosegroup(pFunc->pNexusData); } - } + return status; + } +} /* --------------------------------------------------------------------- */ - - NXstatus NXmakedata (NXhandle fid, CONSTCHAR *name, int datatype, - int rank, int dimensions[]) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxmakedata(pFunc->pNexusData, name, datatype, rank, dimensions); - } + +NXstatus NXmakedata(NXhandle fid, CONSTCHAR * name, int datatype, + int rank, int dimensions[]) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxmakedata(pFunc->pNexusData, name, datatype, rank, + dimensions); +} /* --------------------------------------------------------------------- */ - - NXstatus NXcompmakedata (NXhandle fid, CONSTCHAR *name, int datatype, - int rank, int dimensions[],int compress_type, int chunk_size[]) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxcompmakedata (pFunc->pNexusData, name, datatype, rank, dimensions, compress_type, chunk_size); - } - - + +NXstatus NXcompmakedata(NXhandle fid, CONSTCHAR * name, int datatype, + int rank, int dimensions[], int compress_type, + int chunk_size[]) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxcompmakedata(pFunc->pNexusData, name, datatype, rank, + dimensions, compress_type, chunk_size); +} + + /* --------------------------------------------------------------------- */ - NXstatus NXcompress (NXhandle fid, int compress_type) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxcompress (pFunc->pNexusData, compress_type); - } - - +NXstatus NXcompress(NXhandle fid, int compress_type) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxcompress(pFunc->pNexusData, compress_type); +} + + /* --------------------------------------------------------------------- */ - - NXstatus NXopendata (NXhandle fid, CONSTCHAR *name) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxopendata(pFunc->pNexusData, name); - } + +NXstatus NXopendata(NXhandle fid, CONSTCHAR * name) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxopendata(pFunc->pNexusData, name); +} /* ----------------------------------------------------------------- */ - - NXstatus NXclosedata (NXhandle fid) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxclosedata(pFunc->pNexusData); - } + +NXstatus NXclosedata(NXhandle fid) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxclosedata(pFunc->pNexusData); +} /* ------------------------------------------------------------------- */ - NXstatus NXputdata (NXhandle fid, void *data) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxputdata(pFunc->pNexusData, data); - } +NXstatus NXputdata(NXhandle fid, void *data) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxputdata(pFunc->pNexusData, data); +} /* ------------------------------------------------------------------- */ - NXstatus NXputattr (NXhandle fid, CONSTCHAR *name, void *data, - int datalen, int iType) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxputattr(pFunc->pNexusData, name, data, datalen, iType); - } +NXstatus NXputattr(NXhandle fid, CONSTCHAR * name, void *data, + int datalen, int iType) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxputattr(pFunc->pNexusData, name, data, datalen, iType); +} /* ------------------------------------------------------------------- */ - NXstatus NXputslab (NXhandle fid, void *data, int iStart[], int iSize[]) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxputslab(pFunc->pNexusData, data, iStart, iSize); - } +NXstatus NXputslab(NXhandle fid, void *data, int iStart[], int iSize[]) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxputslab(pFunc->pNexusData, data, iStart, iSize); +} /* ------------------------------------------------------------------- */ - NXstatus NXgetdataID (NXhandle fid, NXlink* sRes) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxgetdataID(pFunc->pNexusData, sRes); - } +NXstatus NXgetdataID(NXhandle fid, NXlink * sRes) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxgetdataID(pFunc->pNexusData, sRes); +} /* ------------------------------------------------------------------- */ - NXstatus NXmakelink (NXhandle fid, NXlink* sLink) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxmakelink(pFunc->pNexusData, sLink); - } +NXstatus NXmakelink(NXhandle fid, NXlink * sLink) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxmakelink(pFunc->pNexusData, sLink); +} + /* ------------------------------------------------------------------- */ - NXstatus NXmakenamedlink (NXhandle fid, CONSTCHAR *newname, NXlink* sLink) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxmakenamedlink(pFunc->pNexusData, newname, sLink); - } - /* --------------------------------------------------------------------*/ - NXstatus NXopensourcegroup(NXhandle fid) - { - char target_path[512]; - int status, type = NX_CHAR, length = 511; +NXstatus NXmakenamedlink(NXhandle fid, CONSTCHAR * newname, NXlink * sLink) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxmakenamedlink(pFunc->pNexusData, newname, sLink); +} - status = NXgetattr(fid,"target",target_path,&length,&type); - if(status != NX_OK) - { - NXIReportError(NXpData,"ERROR: item not linked"); - return NX_ERROR; - } - return NXopengrouppath(fid,target_path); + /* -------------------------------------------------------------------- */ +NXstatus NXopensourcegroup(NXhandle fid) +{ + char target_path[512]; + int status, type = NX_CHAR, length = 511; + + status = NXgetattr(fid, "target", target_path, &length, &type); + if (status != NX_OK) { + NXIReportError(NXpData, "ERROR: item not linked"); + return NX_ERROR; } + return NXopengrouppath(fid, target_path); +} + /*----------------------------------------------------------------------*/ - NXstatus NXflush(NXhandle *pHandle) - { - NXhandle hfil; - pFileStack fileStack = NULL; - int status; - - pNexusFunction pFunc=NULL; - fileStack = (pFileStack)*pHandle; - pFunc = peekFileOnStack(fileStack); - hfil = pFunc->pNexusData; - status = pFunc->nxflush(&hfil); - pFunc->pNexusData = hfil; - return status; - } +NXstatus NXflush(NXhandle * pHandle) +{ + NXhandle hfil; + pFileStack fileStack = NULL; + int status; + + pNexusFunction pFunc = NULL; + fileStack = (pFileStack) * pHandle; + pFunc = peekFileOnStack(fileStack); + hfil = pFunc->pNexusData; + status = pFunc->nxflush(&hfil); + pFunc->pNexusData = hfil; + return status; +} /*-------------------------------------------------------------------------*/ - - NXstatus NXmalloc (void** data, int rank, - int dimensions[], int datatype) - { - int i; - size_t size = 1; - *data = NULL; - for(i=0; inxgetnextentry(pFunc->pNexusData, name, nxclass, datatype); - } + + +NXstatus NXgetnextentry(NXhandle fid, NXname name, NXname nxclass, + int *datatype) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxgetnextentry(pFunc->pNexusData, name, nxclass, datatype); +} + /*----------------------------------------------------------------------*/ /* ** TRIM.C - Remove leading, trailing, & excess embedded spaces @@ -751,293 +775,287 @@ static int analyzeNapimount(char *napiMount, char *extFile, int extFileLen, char *nxitrim(char *str) { - char *ibuf = str, *obuf = str; - int i = 0, cnt = 0; + char *ibuf = str, *obuf = str; + int i = 0, cnt = 0; - /* - ** Trap NULL - */ + /* + ** Trap NULL + */ - if (str) - { - /* - ** Remove leading spaces (from RMLEAD.C) - */ - - for (ibuf = str; *ibuf && isspace(*ibuf); ++ibuf) - ; - str = ibuf; - - /* - ** Remove trailing spaces (from RMTRAIL.C) - */ - i = strlen(str); - while (--i >= 0) - { - if (!isspace(str[i])) - break; - } - str[++i] = NUL; - } - return str; -} - /*-------------------------------------------------------------------------*/ - - NXstatus NXgetdata (NXhandle fid, void *data) - { - int status, type, rank, iDim[NX_MAXRANK]; - char *pPtr, *pPtr2; - - pNexusFunction pFunc = handleToNexusFunc(fid); - status = pFunc->nxgetinfo(pFunc->pNexusData, &rank, iDim, &type); /* unstripped size if string */ - /* only strip one dimensional strings */ - if ( (type == NX_CHAR) && (pFunc->stripFlag == 1) && (rank == 1) ) - { - pPtr = (char*)malloc(iDim[0]+5); - memset(pPtr, 0, iDim[0]+5); - status = pFunc->nxgetdata(pFunc->pNexusData, pPtr); - pPtr2 = nxitrim(pPtr); - strncpy((char*)data, pPtr2, strlen(pPtr2)); /* not NULL terminated by default */ - free(pPtr); - } - else - { - status = pFunc->nxgetdata(pFunc->pNexusData, data); - } - return status; - } - - /*-------------------------------------------------------------------------*/ - - NXstatus NXgetinfo (NXhandle fid, int *rank, - int dimension[], int *iType) - { - int status; - char *pPtr = NULL; - - pNexusFunction pFunc = handleToNexusFunc(fid); - status = pFunc->nxgetinfo(pFunc->pNexusData, rank, dimension, iType); + if (str) { /* - the length of a string may be trimmed.... - */ - /* only strip one dimensional strings */ - if((*iType == NX_CHAR) && (pFunc->stripFlag == 1) && (*rank == 1)){ - pPtr = (char *)malloc((dimension[0]+1)*sizeof(char)); - if(pPtr != NULL){ - memset(pPtr,0,(dimension[0]+1)*sizeof(char)); - pFunc->nxgetdata(pFunc->pNexusData, pPtr); - dimension[0] = strlen(nxitrim(pPtr)); - free(pPtr); - } - } - return status; - } - - /*-------------------------------------------------------------------------*/ + ** Remove leading spaces (from RMLEAD.C) + */ - NXstatus NXgetslab (NXhandle fid, void *data, - int iStart[], int iSize[]) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxgetslab(pFunc->pNexusData, data, iStart, iSize); - } - - - /*-------------------------------------------------------------------------*/ + for (ibuf = str; *ibuf && isspace(*ibuf); ++ibuf); + str = ibuf; - NXstatus NXgetnextattr (NXhandle fileid, NXname pName, - int *iLength, int *iType) - { - pNexusFunction pFunc = handleToNexusFunc(fileid); - return pFunc->nxgetnextattr(pFunc->pNexusData, pName, iLength, iType); - } - - - /*-------------------------------------------------------------------------*/ - - NXstatus NXgetattr (NXhandle fid, char *name, void *data, int* datalen, int* iType) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxgetattr(pFunc->pNexusData, name, data, datalen, iType); - } - - - /*-------------------------------------------------------------------------*/ - - NXstatus NXgetattrinfo (NXhandle fid, int *iN) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxgetattrinfo(pFunc->pNexusData, iN); - } - - - /*-------------------------------------------------------------------------*/ - - NXstatus NXgetgroupID (NXhandle fileid, NXlink* sRes) - { - pNexusFunction pFunc = handleToNexusFunc(fileid); - return pFunc->nxgetgroupID(pFunc->pNexusData, sRes); - } - - /*-------------------------------------------------------------------------*/ - - NXstatus NXgetgroupinfo (NXhandle fid, int *iN, NXname pName, NXname pClass) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxgetgroupinfo(pFunc->pNexusData, iN, pName, pClass); - } - - - /*-------------------------------------------------------------------------*/ - - NXstatus NXsameID (NXhandle fileid, NXlink* pFirstID, NXlink* pSecondID) - { - pNexusFunction pFunc = handleToNexusFunc(fileid); - return pFunc->nxsameID(pFunc->pNexusData, pFirstID, pSecondID); - } - - /*-------------------------------------------------------------------------*/ - - NXstatus NXinitattrdir (NXhandle fid) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxinitattrdir(pFunc->pNexusData); - } - /*-------------------------------------------------------------------------*/ - - NXstatus NXsetnumberformat (NXhandle fid, - int type, char *format) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - if(pFunc->nxsetnumberformat != NULL) - { - return pFunc->nxsetnumberformat(pFunc->pNexusData,type,format); + /* + ** Remove trailing spaces (from RMTRAIL.C) + */ + i = strlen(str); + while (--i >= 0) { + if (!isspace(str[i])) + break; } - else - { - /* - silently ignore this. Most NeXus file formats do not require - this - */ - return NX_OK; + str[++i] = NUL; + } + return str; +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NXgetdata(NXhandle fid, void *data) +{ + int status, type, rank, iDim[NX_MAXRANK]; + char *pPtr, *pPtr2; + + pNexusFunction pFunc = handleToNexusFunc(fid); + status = pFunc->nxgetinfo(pFunc->pNexusData, &rank, iDim, &type); /* unstripped size if string */ + /* only strip one dimensional strings */ + if ((type == NX_CHAR) && (pFunc->stripFlag == 1) && (rank == 1)) { + pPtr = (char *) malloc(iDim[0] + 5); + memset(pPtr, 0, iDim[0] + 5); + status = pFunc->nxgetdata(pFunc->pNexusData, pPtr); + pPtr2 = nxitrim(pPtr); + strncpy((char *) data, pPtr2, strlen(pPtr2)); /* not NULL terminated by default */ + free(pPtr); + } else { + status = pFunc->nxgetdata(pFunc->pNexusData, data); + } + return status; +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NXgetinfo(NXhandle fid, int *rank, int dimension[], int *iType) +{ + int status; + char *pPtr = NULL; + + pNexusFunction pFunc = handleToNexusFunc(fid); + status = pFunc->nxgetinfo(pFunc->pNexusData, rank, dimension, iType); + /* + the length of a string may be trimmed.... + */ + /* only strip one dimensional strings */ + if ((*iType == NX_CHAR) && (pFunc->stripFlag == 1) && (*rank == 1)) { + pPtr = (char *) malloc((dimension[0] + 1) * sizeof(char)); + if (pPtr != NULL) { + memset(pPtr, 0, (dimension[0] + 1) * sizeof(char)); + pFunc->nxgetdata(pFunc->pNexusData, pPtr); + dimension[0] = strlen(nxitrim(pPtr)); + free(pPtr); } } - - + return status; +} + /*-------------------------------------------------------------------------*/ - - NXstatus NXinitgroupdir (NXhandle fid) - { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxinitgroupdir(pFunc->pNexusData); + +NXstatus NXgetslab(NXhandle fid, void *data, int iStart[], int iSize[]) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxgetslab(pFunc->pNexusData, data, iStart, iSize); +} + + + /*-------------------------------------------------------------------------*/ + +NXstatus NXgetnextattr(NXhandle fileid, NXname pName, + int *iLength, int *iType) +{ + pNexusFunction pFunc = handleToNexusFunc(fileid); + return pFunc->nxgetnextattr(pFunc->pNexusData, pName, iLength, iType); +} + + + /*-------------------------------------------------------------------------*/ + +NXstatus NXgetattr(NXhandle fid, char *name, void *data, int *datalen, + int *iType) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxgetattr(pFunc->pNexusData, name, data, datalen, iType); +} + + + /*-------------------------------------------------------------------------*/ + +NXstatus NXgetattrinfo(NXhandle fid, int *iN) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxgetattrinfo(pFunc->pNexusData, iN); +} + + + /*-------------------------------------------------------------------------*/ + +NXstatus NXgetgroupID(NXhandle fileid, NXlink * sRes) +{ + pNexusFunction pFunc = handleToNexusFunc(fileid); + return pFunc->nxgetgroupID(pFunc->pNexusData, sRes); +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NXgetgroupinfo(NXhandle fid, int *iN, NXname pName, NXname pClass) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxgetgroupinfo(pFunc->pNexusData, iN, pName, pClass); +} + + + /*-------------------------------------------------------------------------*/ + +NXstatus NXsameID(NXhandle fileid, NXlink * pFirstID, NXlink * pSecondID) +{ + pNexusFunction pFunc = handleToNexusFunc(fileid); + return pFunc->nxsameID(pFunc->pNexusData, pFirstID, pSecondID); +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NXinitattrdir(NXhandle fid) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxinitattrdir(pFunc->pNexusData); +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NXsetnumberformat(NXhandle fid, int type, char *format) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + if (pFunc->nxsetnumberformat != NULL) { + return pFunc->nxsetnumberformat(pFunc->pNexusData, type, format); + } else { + /* + silently ignore this. Most NeXus file formats do not require + this + */ + return NX_OK; } +} + + + /*-------------------------------------------------------------------------*/ + +NXstatus NXinitgroupdir(NXhandle fid) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxinitgroupdir(pFunc->pNexusData); +} + /*----------------------------------------------------------------------*/ - NXstatus NXinquirefile(NXhandle handle, char *filename, - int filenameBufferLength){ +NXstatus NXinquirefile(NXhandle handle, char *filename, + int filenameBufferLength) +{ pFileStack fileStack; char *pPtr = NULL; int length; - fileStack = (pFileStack)handle; + fileStack = (pFileStack) handle; pPtr = peekFilenameOnStack(fileStack); - if(pPtr != NULL){ + if (pPtr != NULL) { length = strlen(pPtr); - if(length > filenameBufferLength){ - length = filenameBufferLength -1; + if (length > filenameBufferLength) { + length = filenameBufferLength - 1; } - memset(filename,0,filenameBufferLength); - memcpy(filename,pPtr, length); + memset(filename, 0, filenameBufferLength); + memcpy(filename, pPtr, length); return NX_OK; } else { return NX_ERROR; } } + /*------------------------------------------------------------------------*/ -NXstatus NXisexternalgroup(NXhandle fid, CONSTCHAR *name, CONSTCHAR *class, - char *url, int urlLen){ +NXstatus NXisexternalgroup(NXhandle fid, CONSTCHAR * name, + CONSTCHAR * class, char *url, int urlLen) +{ int status, attStatus, length = 1023, type = NX_CHAR; ErrFunc oldError; char nxurl[1024]; pNexusFunction pFunc = handleToNexusFunc(fid); - status = pFunc->nxopengroup(pFunc->pNexusData, name,class); - if(status != NX_OK){ + status = pFunc->nxopengroup(pFunc->pNexusData, name, class); + if (status != NX_OK) { return status; } oldError = NXMGetError(); NXIReportError = NXNXNoReport; - attStatus = NXgetattr(fid,"napimount",nxurl,&length, &type); + attStatus = NXgetattr(fid, "napimount", nxurl, &length, &type); NXIReportError = oldError; pFunc->nxclosegroup(pFunc->pNexusData); - if(attStatus == NX_OK){ + if (attStatus == NX_OK) { length = strlen(nxurl); - if(length > urlLen){ + if (length > urlLen) { length = urlLen - 1; } - memset(url,0,urlLen); - memcpy(url,nxurl,length); + memset(url, 0, urlLen); + memcpy(url, nxurl, length); return attStatus; } else { return NX_ERROR; } } + /*------------------------------------------------------------------------*/ -NXstatus NXlinkexternal(NXhandle fid, CONSTCHAR *name, CONSTCHAR *class, - CONSTCHAR *url){ +NXstatus NXlinkexternal(NXhandle fid, CONSTCHAR * name, CONSTCHAR * class, + CONSTCHAR * url) +{ int status, type = NX_CHAR, length; pNexusFunction pFunc = handleToNexusFunc(fid); - status = pFunc->nxopengroup(pFunc->pNexusData,name,class); - if(status != NX_OK){ + status = pFunc->nxopengroup(pFunc->pNexusData, name, class); + if (status != NX_OK) { return status; } length = strlen(url); - status = NXputattr(fid, "napimount",(void *)url,length, type); - if(status != NX_OK){ + status = NXputattr(fid, "napimount", (void *) url, length, type); + if (status != NX_OK) { return status; } pFunc->nxclosegroup(pFunc->pNexusData); return NX_OK; } + /*------------------------------------------------------------------------ Implementation of NXopenpath. --------------------------------------------------------------------------*/ static int isDataSetOpen(NXhandle hfil) { NXlink id; - + /* - This uses the (sensible) feauture that NXgetdataID returns NX_ERROR - when no dataset is open - */ - if(NXgetdataID(hfil,&id) == NX_ERROR) - { + This uses the (sensible) feauture that NXgetdataID returns NX_ERROR + when no dataset is open + */ + if (NXgetdataID(hfil, &id) == NX_ERROR) { return 0; - } - else - { + } else { return 1; } } + /*----------------------------------------------------------------------*/ static int isRoot(NXhandle hfil) { NXlink id; - + /* - This uses the feauture that NXgetgroupID returns NX_ERROR - when we are at root level - */ - if(NXgetgroupID(hfil,&id) == NX_ERROR) - { + This uses the feauture that NXgetgroupID returns NX_ERROR + when we are at root level + */ + if (NXgetgroupID(hfil, &id) == NX_ERROR) { return 1; - } - else - { + } else { return 0; } } + /*-------------------------------------------------------------------- copies the next path element into element. returns a pointer into path beyond the extracted path @@ -1049,75 +1067,70 @@ static char *extractNextPath(char *path, NXname element) pPtr = path; /* - skip over leading / - */ - if(*pPtr == '/') - { + skip over leading / + */ + if (*pPtr == '/') { pPtr++; } pStart = pPtr; - + /* - find next / - */ - pPtr = strchr(pStart,'/'); - if(pPtr == NULL) - { + find next / + */ + pPtr = strchr(pStart, '/'); + if (pPtr == NULL) { /* - this is the last path element - */ - strcpy(element,pStart); + this is the last path element + */ + strcpy(element, pStart); return NULL; } else { length = pPtr - pStart; - strncpy(element,pStart,length); + strncpy(element, pStart, length); element[length] = '\0'; } return pPtr + 1; } + /*-------------------------------------------------------------------*/ static NXstatus gotoRoot(NXhandle hfil) { - int status; + int status; - if(isDataSetOpen(hfil)) - { - status = NXclosedata(hfil); - if(status == NX_ERROR) - { - return status; - } + if (isDataSetOpen(hfil)) { + status = NXclosedata(hfil); + if (status == NX_ERROR) { + return status; } - while(!isRoot(hfil)) - { - status = NXclosegroup(hfil); - if(status == NX_ERROR) - { - return status; - } + } + while (!isRoot(hfil)) { + status = NXclosegroup(hfil); + if (status == NX_ERROR) { + return status; } - return NX_OK; + } + return NX_OK; } + /*--------------------------------------------------------------------*/ static int isRelative(char *path) { - if(path[0] == '.' && path[1] == '.') + if (path[0] == '.' && path[1] == '.') return 1; else return 0; } + /*------------------------------------------------------------------*/ static NXstatus moveOneDown(NXhandle hfil) { - if(isDataSetOpen(hfil)) - { + if (isDataSetOpen(hfil)) { return NXclosedata(hfil); - } - else - { + } else { return NXclosegroup(hfil); } } + /*------------------------------------------------------------------- returns a pointer to the remaining path string to move up --------------------------------------------------------------------*/ @@ -1129,252 +1142,219 @@ static char *moveDown(NXhandle hfil, char *path, int *code) *code = NX_OK; - if(path[0] == '/') - { + if (path[0] == '/') { *code = gotoRoot(hfil); return path; - } - else - { + } else { pPtr = path; - while(isRelative(pPtr)) - { + while (isRelative(pPtr)) { status = moveOneDown(hfil); - if(status == NX_ERROR) - { - *code = status; - return pPtr; + if (status == NX_ERROR) { + *code = status; + return pPtr; } pPtr += 3; } return pPtr; } -} +} + /*--------------------------------------------------------------------*/ static NXstatus stepOneUp(NXhandle hfil, char *name) { int status, datatype; NXname name2, xclass; - char pBueffel[256]; + char pBueffel[256]; /* - catch the case when we are there: i.e. no further stepping - necessary. This can happen with paths like ../ - */ - if(strlen(name) < 1) - { - return NX_OK; + catch the case when we are there: i.e. no further stepping + necessary. This can happen with paths like ../ + */ + if (strlen(name) < 1) { + return NX_OK; } - + NXinitgroupdir(hfil); - while(NXgetnextentry(hfil,name2,xclass,&datatype) != NX_EOD) - { - - if(strcmp(name2,name) == 0) - { - if(strcmp(xclass,"SDS") == 0) - { - return NXopendata(hfil,name); - } - else - { - return NXopengroup(hfil,name,xclass); + while (NXgetnextentry(hfil, name2, xclass, &datatype) != NX_EOD) { + + if (strcmp(name2, name) == 0) { + if (strcmp(xclass, "SDS") == 0) { + return NXopendata(hfil, name); + } else { + return NXopengroup(hfil, name, xclass); } } } - snprintf(pBueffel,255,"ERROR: NXopenpath cannot step into %s",name); - NXIReportError (NXpData, pBueffel); - return NX_ERROR; + snprintf(pBueffel, 255, "ERROR: NXopenpath cannot step into %s", name); + NXIReportError(NXpData, pBueffel); + return NX_ERROR; } + /*--------------------------------------------------------------------*/ static NXstatus stepOneGroupUp(NXhandle hfil, char *name) { int status, datatype; NXname name2, xclass; - char pBueffel[256]; + char pBueffel[256]; /* - catch the case when we are there: i.e. no further stepping - necessary. This can happen with paths like ../ - */ - if(strlen(name) < 1) - { - return NX_OK; + catch the case when we are there: i.e. no further stepping + necessary. This can happen with paths like ../ + */ + if (strlen(name) < 1) { + return NX_OK; } - + NXinitgroupdir(hfil); - while(NXgetnextentry(hfil,name2,xclass,&datatype) != NX_EOD) - { - - if(strcmp(name2,name) == 0) - { - if(strcmp(xclass,"SDS") == 0) - { - return NX_EOD; - } - else - { - return NXopengroup(hfil,name,xclass); + while (NXgetnextentry(hfil, name2, xclass, &datatype) != NX_EOD) { + + if (strcmp(name2, name) == 0) { + if (strcmp(xclass, "SDS") == 0) { + return NX_EOD; + } else { + return NXopengroup(hfil, name, xclass); } } } - snprintf(pBueffel,255,"ERROR: NXopenpath cannot step into %s",name); - NXIReportError (NXpData, pBueffel); - return NX_ERROR; + snprintf(pBueffel, 255, "ERROR: NXopenpath cannot step into %s", name); + NXIReportError(NXpData, pBueffel); + return NX_ERROR; } + /*---------------------------------------------------------------------*/ -NXstatus NXopenpath(NXhandle hfil, CONSTCHAR *path) +NXstatus NXopenpath(NXhandle hfil, CONSTCHAR * path) { int status, run = 1; NXname pathElement; char *pPtr; - if(hfil == NULL || path == NULL) - { + if (hfil == NULL || path == NULL) { NXIReportError(NXpData, - "ERROR: NXopendata needs both a file handle and a path string"); + "ERROR: NXopendata needs both a file handle and a path string"); return NX_ERROR; } - pPtr = moveDown(hfil,(char *)path,&status); - if(status != NX_OK) - { - NXIReportError (NXpData, - "ERROR: NXopendata failed to move down in hierarchy"); - return status; - } - - while(run == 1) - { - pPtr = extractNextPath(pPtr, pathElement); - status = stepOneUp(hfil,pathElement); - if(status != NX_OK) - { - return status; - } - if(pPtr == NULL) - { - run = 0; - } - } - return NX_OK; -} -/*---------------------------------------------------------------------*/ -NXstatus NXopengrouppath(NXhandle hfil, CONSTCHAR *path) -{ - int status, run = 1; - NXname pathElement; - char *pPtr; - - if(hfil == NULL || path == NULL) - { + pPtr = moveDown(hfil, (char *) path, &status); + if (status != NX_OK) { NXIReportError(NXpData, - "ERROR: NXopendata needs both a file handle and a path string"); - return NX_ERROR; - } - - pPtr = moveDown(hfil,(char *)path,&status); - if(status != NX_OK) - { - NXIReportError (NXpData, - "ERROR: NXopendata failed to move down in hierarchy"); + "ERROR: NXopendata failed to move down in hierarchy"); return status; } - while(run == 1) - { + while (run == 1) { pPtr = extractNextPath(pPtr, pathElement); - status = stepOneGroupUp(hfil,pathElement); - if(status == NX_ERROR) - { + status = stepOneUp(hfil, pathElement); + if (status != NX_OK) { return status; } - if(pPtr == NULL || status == NX_EOD) - { + if (pPtr == NULL) { run = 0; } } return NX_OK; } -NXstatus NXIprintlink(NXhandle fid, NXlink* link) +/*---------------------------------------------------------------------*/ +NXstatus NXopengrouppath(NXhandle hfil, CONSTCHAR * path) { - pNexusFunction pFunc = handleToNexusFunc(fid); - return pFunc->nxprintlink(pFunc->pNexusData, link); + int status, run = 1; + NXname pathElement; + char *pPtr; + + if (hfil == NULL || path == NULL) { + NXIReportError(NXpData, + "ERROR: NXopendata needs both a file handle and a path string"); + return NX_ERROR; + } + + pPtr = moveDown(hfil, (char *) path, &status); + if (status != NX_OK) { + NXIReportError(NXpData, + "ERROR: NXopendata failed to move down in hierarchy"); + return status; + } + + while (run == 1) { + pPtr = extractNextPath(pPtr, pathElement); + status = stepOneGroupUp(hfil, pathElement); + if (status == NX_ERROR) { + return status; + } + if (pPtr == NULL || status == NX_EOD) { + run = 0; + } + } + return NX_OK; +} + +NXstatus NXIprintlink(NXhandle fid, NXlink * link) +{ + pNexusFunction pFunc = handleToNexusFunc(fid); + return pFunc->nxprintlink(pFunc->pNexusData, link); } /*-------------------------------------------------------------------- format NeXus time. Code needed in every NeXus file driver ---------------------------------------------------------------------*/ -char *NXIformatNeXusTime(){ - char *timeData; - time_t timer; - char* time_buffer = NULL; - struct tm *time_info; - const char* time_format; - long gmt_offset; +char *NXIformatNeXusTime() +{ + char *timeData; + time_t timer; + char *time_buffer = NULL; + struct tm *time_info; + const char *time_format; + long gmt_offset; #ifdef USE_FTIME - struct timeb timeb_struct; -#endif - - time_buffer = (char *)malloc(64*sizeof(char)); - if(!time_buffer){ - NXIReportError(NXpData,"Failed to allocate buffer for time data"); - return NULL; - } + struct timeb timeb_struct; +#endif + time_buffer = (char *) malloc(64 * sizeof(char)); + if (!time_buffer) { + NXIReportError(NXpData, "Failed to allocate buffer for time data"); + return NULL; + } #ifdef NEED_TZSET - tzset(); -#endif - time(&timer); + tzset(); +#endif + time(&timer); #ifdef USE_FTIME - ftime(&timeb_struct); - gmt_offset = -timeb_struct.timezone * 60; - if (timeb_struct.dstflag != 0) - { - gmt_offset += 3600; - } + ftime(&timeb_struct); + gmt_offset = -timeb_struct.timezone * 60; + if (timeb_struct.dstflag != 0) { + gmt_offset += 3600; + } #else - time_info = gmtime(&timer); - if (time_info != NULL) - { - gmt_offset = (long)difftime(timer, mktime(time_info)); + time_info = gmtime(&timer); + if (time_info != NULL) { + gmt_offset = (long) difftime(timer, mktime(time_info)); + } else { + NXIReportError(NXpData, + "Your gmtime() function does not work ... timezone information will be incorrect\n"); + gmt_offset = 0; + } +#endif + time_info = localtime(&timer); + if (time_info != NULL) { + if (gmt_offset < 0) { + time_format = "%04d-%02d-%02d %02d:%02d:%02d-%02d%02d"; + } else { + time_format = "%04d-%02d-%02d %02d:%02d:%02d+%02d%02d"; } - else - { - NXIReportError (NXpData, - "Your gmtime() function does not work ... timezone information will be incorrect\n"); - gmt_offset = 0; - } -#endif - time_info = localtime(&timer); - if (time_info != NULL) - { - if (gmt_offset < 0) - { - time_format = "%04d-%02d-%02d %02d:%02d:%02d-%02d%02d"; - } - else - { - time_format = "%04d-%02d-%02d %02d:%02d:%02d+%02d%02d"; - } - sprintf(time_buffer, time_format, + sprintf(time_buffer, time_format, 1900 + time_info->tm_year, 1 + time_info->tm_mon, time_info->tm_mday, time_info->tm_hour, time_info->tm_min, time_info->tm_sec, - abs(gmt_offset / 3600), - abs((gmt_offset % 3600) / 60) + abs(gmt_offset / 3600), abs((gmt_offset % 3600) / 60) ); - } - else - { - strcpy(time_buffer, "1970-01-01 00:00:00+0000"); - } - return time_buffer; + } else { + strcpy(time_buffer, "1970-01-01 00:00:00+0000"); + } + return time_buffer; } + /*---------------------------------------------------------------------- F77 - API - Support - Routines ----------------------------------------------------------------------*/ @@ -1384,137 +1364,132 @@ char *NXIformatNeXusTime(){ * NXhandle. We could store the NXhandle value in the FORTRAN array * instead, but that would mean writing far more wrappers */ - NXstatus NXfopen(char * filename, NXaccess* am, - NexusFunction* pHandle) - { - NXstatus ret; - NXhandle fileid = NULL; - ret = NXopen(filename, *am, &fileid); - if (ret == NX_OK) - { - memcpy(pHandle, fileid, sizeof(NexusFunction)); - } - else - { - memset(pHandle, 0, sizeof(NexusFunction)); - } - if (fileid != NULL) - { - free(fileid); - } - return ret; +NXstatus NXfopen(char *filename, NXaccess * am, NexusFunction * pHandle) +{ + NXstatus ret; + NXhandle fileid = NULL; + ret = NXopen(filename, *am, &fileid); + if (ret == NX_OK) { + memcpy(pHandle, fileid, sizeof(NexusFunction)); + } else { + memset(pHandle, 0, sizeof(NexusFunction)); } + if (fileid != NULL) { + free(fileid); + } + return ret; +} + /* * The pHandle from FORTRAN is a pointer to a static FORTRAN * array holding the NexusFunction structure. We need to malloc() * a temporary copy as NXclose will try to free() this */ - NXstatus NXfclose (NexusFunction* pHandle) - { - NXhandle h; - NXstatus ret; - h = (NXhandle)malloc(sizeof(NexusFunction)); - memcpy(h, pHandle, sizeof(NexusFunction)); - ret = NXclose(&h); /* does free(h) */ - memset(pHandle, 0, sizeof(NexusFunction)); - return ret; - } - -/*---------------------------------------------------------------------*/ - NXstatus NXfflush(NexusFunction* pHandle) - { - NXhandle h; - NXstatus ret; - h = (NXhandle)malloc(sizeof(NexusFunction)); - memcpy(h, pHandle, sizeof(NexusFunction)); - ret = NXflush(&h); /* modifies and reallocates h */ - memcpy(pHandle, h, sizeof(NexusFunction)); - return ret; - } +NXstatus NXfclose(NexusFunction * pHandle) +{ + NXhandle h; + NXstatus ret; + h = (NXhandle) malloc(sizeof(NexusFunction)); + memcpy(h, pHandle, sizeof(NexusFunction)); + ret = NXclose(&h); /* does free(h) */ + memset(pHandle, 0, sizeof(NexusFunction)); + return ret; +} + +/*---------------------------------------------------------------------*/ +NXstatus NXfflush(NexusFunction * pHandle) +{ + NXhandle h; + NXstatus ret; + h = (NXhandle) malloc(sizeof(NexusFunction)); + memcpy(h, pHandle, sizeof(NexusFunction)); + ret = NXflush(&h); /* modifies and reallocates h */ + memcpy(pHandle, h, sizeof(NexusFunction)); + return ret; +} + /*----------------------------------------------------------------------*/ - NXstatus NXfmakedata(NXhandle fid, char *name, int *pDatatype, - int *pRank, int dimensions[]) - { - NXstatus ret; - static char buffer[256]; - int i, *reversed_dimensions; - reversed_dimensions = (int*)malloc(*pRank * sizeof(int)); - if (reversed_dimensions == NULL) - { - sprintf (buffer, - "ERROR: Cannot allocate space for array rank of %d in NXfmakedata", - *pRank); - NXIReportError (NXpData, buffer); - return NX_ERROR; - } +NXstatus NXfmakedata(NXhandle fid, char *name, int *pDatatype, + int *pRank, int dimensions[]) +{ + NXstatus ret; + static char buffer[256]; + int i, *reversed_dimensions; + reversed_dimensions = (int *) malloc(*pRank * sizeof(int)); + if (reversed_dimensions == NULL) { + sprintf(buffer, + "ERROR: Cannot allocate space for array rank of %d in NXfmakedata", + *pRank); + NXIReportError(NXpData, buffer); + return NX_ERROR; + } /* * Reverse dimensions array as FORTRAN is column major, C row major */ - for(i=0; i < *pRank; i++) - { - reversed_dimensions[i] = dimensions[*pRank - i - 1]; - } - ret = NXmakedata(fid, name, *pDatatype, *pRank, reversed_dimensions); - free(reversed_dimensions); - return ret; + for (i = 0; i < *pRank; i++) { + reversed_dimensions[i] = dimensions[*pRank - i - 1]; } + ret = NXmakedata(fid, name, *pDatatype, *pRank, reversed_dimensions); + free(reversed_dimensions); + return ret; +} - NXstatus NXfcompmakedata(NXhandle fid, char *name, - int *pDatatype, - int *pRank, int dimensions[], - int *compression_type, int chunk[]) - { - NXstatus ret; - static char buffer[256]; - int i, *reversed_dimensions, *reversed_chunk; - reversed_dimensions = (int*)malloc(*pRank * sizeof(int)); - reversed_chunk = (int*)malloc(*pRank * sizeof(int)); - if (reversed_dimensions == NULL || reversed_chunk == NULL) - { - sprintf (buffer, - "ERROR: Cannot allocate space for array rank of %d in NXfcompmakedata", - *pRank); - NXIReportError (NXpData, buffer); - return NX_ERROR; - } +NXstatus NXfcompmakedata(NXhandle fid, char *name, + int *pDatatype, + int *pRank, int dimensions[], + int *compression_type, int chunk[]) +{ + NXstatus ret; + static char buffer[256]; + int i, *reversed_dimensions, *reversed_chunk; + reversed_dimensions = (int *) malloc(*pRank * sizeof(int)); + reversed_chunk = (int *) malloc(*pRank * sizeof(int)); + if (reversed_dimensions == NULL || reversed_chunk == NULL) { + sprintf(buffer, + "ERROR: Cannot allocate space for array rank of %d in NXfcompmakedata", + *pRank); + NXIReportError(NXpData, buffer); + return NX_ERROR; + } /* * Reverse dimensions array as FORTRAN is column major, C row major */ - for(i=0; i < *pRank; i++) - { - reversed_dimensions[i] = dimensions[*pRank - i - 1]; - reversed_chunk[i] = chunk[*pRank - i - 1]; - } - ret = NXcompmakedata(fid, name, *pDatatype, *pRank, - reversed_dimensions,*compression_type, reversed_chunk); - free(reversed_dimensions); - free(reversed_chunk); - return ret; + for (i = 0; i < *pRank; i++) { + reversed_dimensions[i] = dimensions[*pRank - i - 1]; + reversed_chunk[i] = chunk[*pRank - i - 1]; } + ret = NXcompmakedata(fid, name, *pDatatype, *pRank, + reversed_dimensions, *compression_type, + reversed_chunk); + free(reversed_dimensions); + free(reversed_chunk); + return ret; +} + /*-----------------------------------------------------------------------*/ - NXstatus NXfcompress(NXhandle fid, int *compr_type) - { - return NXcompress(fid,*compr_type); - } +NXstatus NXfcompress(NXhandle fid, int *compr_type) +{ + return NXcompress(fid, *compr_type); +} + /*-----------------------------------------------------------------------*/ - NXstatus NXfputattr(NXhandle fid, char *name, void *data, - int *pDatalen, int *pIType) - { - return NXputattr(fid, name, data, *pDatalen, *pIType); - } +NXstatus NXfputattr(NXhandle fid, char *name, void *data, + int *pDatalen, int *pIType) +{ + return NXputattr(fid, name, data, *pDatalen, *pIType); +} /* * implement snprintf when it is not available */ - int nxisnprintf(char* buffer, int len, const char* format, ... ) - { - int ret; - va_list valist; - va_start(valist,format); - ret = vsprintf(buffer, format, valist); - va_end(valist); - return ret; - } - +int nxisnprintf(char *buffer, int len, const char *format, ...) +{ + int ret; + va_list valist; + va_start(valist, format); + ret = vsprintf(buffer, format, valist); + va_end(valist); + return ret; +} diff --git a/napi.h b/napi.h index 92307eb7..d3db9ddc 100644 --- a/napi.h +++ b/napi.h @@ -21,24 +21,24 @@ For further information, see - $Id: napi.h,v 1.12 2008/01/03 09:56:56 koennecke Exp $ + $Id: napi.h,v 1.13 2009/02/13 09:00:20 koennecke Exp $ ----------------------------------------------------------------------------*/ - + #ifndef NEXUSAPI #define NEXUSAPI /* NeXus HDF45 */ -#define NEXUS_VERSION "4.1.0" /* major.minor.patch */ +#define NEXUS_VERSION "4.1.0" /* major.minor.patch */ #define CONSTCHAR const char #ifdef _MSC_VER #define snprintf nxisnprintf -extern int nxisnprintf(char* buffer, int len, const char* format, ... ); -#endif /* _MSC_VER */ +extern int nxisnprintf(char *buffer, int len, const char *format, ...); +#endif /* _MSC_VER */ -typedef void* NXhandle; /* really a pointer to a NexusFile structure */ +typedef void *NXhandle; /* really a pointer to a NexusFile structure */ typedef int NXstatus; typedef char NXname[128]; @@ -55,16 +55,18 @@ typedef char NXname[128]; * if ( mode & NXACC_NOSTRIP ) * */ -#define NXACCMASK_REMOVEFLAGS (0x7) /* bit mask to remove higher flag options */ +#define NXACCMASK_REMOVEFLAGS (0x7) /* bit mask to remove higher flag options */ -typedef enum {NXACC_READ=1, NXACC_RDWR=2, NXACC_CREATE=3, NXACC_CREATE4=4, - NXACC_CREATE5=5, NXACC_CREATEXML=6, NXACC_NOSTRIP=128} NXaccess; +typedef enum { NXACC_READ = 1, NXACC_RDWR = 2, NXACC_CREATE = + 3, NXACC_CREATE4 = 4, + NXACC_CREATE5 = 5, NXACC_CREATEXML = 6, NXACC_NOSTRIP = 128 +} NXaccess; typedef struct { - char *iname; - int type; - }info_type, *pinfo; - + char *iname; + int type; +} info_type, *pinfo; + #define NX_OK 1 #define NX_ERROR 0 #define NX_EOD -1 @@ -89,15 +91,15 @@ typedef struct { NX_CHAR 8 bit character NX_BINARY lump of binary data == NX_UINT8 ---------------------------------------------------------------------------*/ +--------------------------------------------------------------------------*/ /* Map NeXus to HDF types */ #define NX_FLOAT32 5 #define NX_FLOAT64 6 -#define NX_INT8 20 +#define NX_INT8 20 #define NX_UINT8 21 #define NX_BOOLEAN NX_UINT -#define NX_INT16 22 +#define NX_INT16 22 #define NX_UINT16 23 #define NX_INT32 24 #define NX_UINT32 25 @@ -110,21 +112,21 @@ typedef struct { #define NX_COMP_NONE 100 #define NX_COMP_LZW 200 #define NX_COMP_RLE 300 -#define NX_COMP_HUF 400 +#define NX_COMP_HUF 400 typedef struct { - long iTag; /* HDF4 variable */ - long iRef; /* HDF4 variable */ - char targetPath[1024]; /* path to item to link */ - int linkType; /* HDF5: 0 for group link, 1 for SDS link */ - } NXlink; + long iTag; /* HDF4 variable */ + long iRef; /* HDF4 variable */ + char targetPath[1024]; /* path to item to link */ + int linkType; /* HDF5: 0 for group link, 1 for SDS link */ +} NXlink; #define NXMAXSTACK 50 #define CONCAT(__a,__b) __a##__b /* token concatenation */ # ifdef __VMS -# define MANGLE(__arg) __arg +# define MANGLE(__arg) __arg # else # define MANGLE(__arg) CONCAT(__arg,_) # endif @@ -194,132 +196,167 @@ typedef struct { #ifdef __cplusplus extern "C" { -#endif /* __cplusplus */ -extern NXstatus NXopen(CONSTCHAR * filename, NXaccess access_method, NXhandle* pHandle); -extern NXstatus NXclose(NXhandle* pHandle); -extern NXstatus NXflush(NXhandle* pHandle); - -extern NXstatus NXmakegroup (NXhandle handle, CONSTCHAR *name, CONSTCHAR* NXclass); -extern NXstatus NXopengroup (NXhandle handle, CONSTCHAR *name, CONSTCHAR* NXclass); -extern NXstatus NXopenpath (NXhandle handle, CONSTCHAR *path); -extern NXstatus NXopengrouppath (NXhandle handle, CONSTCHAR *path); +#endif /* __cplusplus */ + extern NXstatus NXopen(CONSTCHAR * filename, NXaccess access_method, + NXhandle * pHandle); + extern NXstatus NXclose(NXhandle * pHandle); + extern NXstatus NXflush(NXhandle * pHandle); -extern NXstatus NXclosegroup(NXhandle handle); - -extern NXstatus NXmakedata (NXhandle handle, CONSTCHAR* label, int datatype, int rank, int dim[]); -extern NXstatus NXcompmakedata (NXhandle handle, CONSTCHAR* label, int datatype, int rank, int dim[], int comp_typ, int bufsize[]); -extern NXstatus NXcompress (NXhandle handle, int compr_type); -extern NXstatus NXopendata (NXhandle handle, CONSTCHAR* label); -extern NXstatus NXclosedata(NXhandle handle); -extern NXstatus NXputdata(NXhandle handle, void* data); + extern NXstatus NXmakegroup(NXhandle handle, CONSTCHAR * name, + CONSTCHAR * NXclass); + extern NXstatus NXopengroup(NXhandle handle, CONSTCHAR * name, + CONSTCHAR * NXclass); + extern NXstatus NXopenpath(NXhandle handle, CONSTCHAR * path); + extern NXstatus NXopengrouppath(NXhandle handle, CONSTCHAR * path); -extern NXstatus NXputattr(NXhandle handle, CONSTCHAR* name, void* data, int iDataLen, int iType); -extern NXstatus NXputslab(NXhandle handle, void* data, int start[], int size[]); + extern NXstatus NXclosegroup(NXhandle handle); -extern NXstatus NXgetdataID(NXhandle handle, NXlink* pLink); -extern NXstatus NXmakelink(NXhandle handle, NXlink* pLink); -extern NXstatus NXmakenamedlink(NXhandle handle, CONSTCHAR* newname, NXlink* pLink); -extern NXstatus NXopensourcegroup(NXhandle handle); + extern NXstatus NXmakedata(NXhandle handle, CONSTCHAR * label, + int datatype, int rank, int dim[]); + extern NXstatus NXcompmakedata(NXhandle handle, CONSTCHAR * label, + int datatype, int rank, int dim[], + int comp_typ, int bufsize[]); + extern NXstatus NXcompress(NXhandle handle, int compr_type); + extern NXstatus NXopendata(NXhandle handle, CONSTCHAR * label); + extern NXstatus NXclosedata(NXhandle handle); + extern NXstatus NXputdata(NXhandle handle, void *data); -extern NXstatus NXgetdata(NXhandle handle, void* data); -extern NXstatus NXgetinfo(NXhandle handle, int* rank, int dimension[], int* datatype); -extern NXstatus NXgetnextentry(NXhandle handle, NXname name, NXname nxclass, int* datatype); + extern NXstatus NXputattr(NXhandle handle, CONSTCHAR * name, void *data, + int iDataLen, int iType); + extern NXstatus NXputslab(NXhandle handle, void *data, int start[], + int size[]); -extern NXstatus NXgetslab(NXhandle handle, void* data, int start[], int size[]); -extern NXstatus NXgetnextattr(NXhandle handle, NXname pName, int *iLength, int *iType); -extern NXstatus NXgetattr(NXhandle handle, char* name, void* data, int* iDataLen, int* iType); -extern NXstatus NXgetattrinfo(NXhandle handle, int* no_items); -extern NXstatus NXgetgroupID(NXhandle handle, NXlink* pLink); -extern NXstatus NXgetgroupinfo(NXhandle handle, int* no_items, NXname name, NXname nxclass); -extern NXstatus NXsameID(NXhandle handle, NXlink* pFirstID, NXlink* pSecondID); + extern NXstatus NXgetdataID(NXhandle handle, NXlink * pLink); + extern NXstatus NXmakelink(NXhandle handle, NXlink * pLink); + extern NXstatus NXmakenamedlink(NXhandle handle, CONSTCHAR * newname, + NXlink * pLink); + extern NXstatus NXopensourcegroup(NXhandle handle); -extern NXstatus NXinitgroupdir(NXhandle handle); -extern NXstatus NXinitattrdir(NXhandle handle); -extern NXstatus NXsetnumberformat(NXhandle handle, - int type, char *format); + extern NXstatus NXgetdata(NXhandle handle, void *data); + extern NXstatus NXgetinfo(NXhandle handle, int *rank, int dimension[], + int *datatype); + extern NXstatus NXgetnextentry(NXhandle handle, NXname name, + NXname nxclass, int *datatype); -extern NXstatus NXinquirefile(NXhandle handle, char *filename, int filenameBufferLength); -extern NXstatus NXisexternalgroup(NXhandle fid, CONSTCHAR *name, CONSTCHAR *nxclass, char *url, int urlLen); -extern NXstatus NXlinkexternal(NXhandle fid, CONSTCHAR *name, CONSTCHAR *nxclass, CONSTCHAR *url); + extern NXstatus NXgetslab(NXhandle handle, void *data, int start[], + int size[]); + extern NXstatus NXgetnextattr(NXhandle handle, NXname pName, + int *iLength, int *iType); + extern NXstatus NXgetattr(NXhandle handle, char *name, void *data, + int *iDataLen, int *iType); + extern NXstatus NXgetattrinfo(NXhandle handle, int *no_items); + extern NXstatus NXgetgroupID(NXhandle handle, NXlink * pLink); + extern NXstatus NXgetgroupinfo(NXhandle handle, int *no_items, + NXname name, NXname nxclass); + extern NXstatus NXsameID(NXhandle handle, NXlink * pFirstID, + NXlink * pSecondID); -extern NXstatus NXmalloc(void** data, int rank, int dimensions[], int datatype); -extern NXstatus NXfree(void** data); + extern NXstatus NXinitgroupdir(NXhandle handle); + extern NXstatus NXinitattrdir(NXhandle handle); + extern NXstatus NXsetnumberformat(NXhandle handle, + int type, char *format); + + extern NXstatus NXinquirefile(NXhandle handle, char *filename, + int filenameBufferLength); + extern NXstatus NXisexternalgroup(NXhandle fid, CONSTCHAR * name, + CONSTCHAR * nxclass, char *url, + int urlLen); + extern NXstatus NXlinkexternal(NXhandle fid, CONSTCHAR * name, + CONSTCHAR * nxclass, CONSTCHAR * url); + + extern NXstatus NXmalloc(void **data, int rank, int dimensions[], + int datatype); + extern NXstatus NXfree(void **data); /*----------------------------------------------------------------------- NAPI internals ------------------------------------------------------------------------*/ -typedef void (*ErrFunc)(void *data, char *text); -extern void NXMSetError(void *pData, ErrFunc); -extern ErrFunc NXMGetError(); -extern void NXMDisableErrorReporting(); -extern void NXMEnableErrorReporting(); -extern void (*NXIReportError)(void *pData,char *text); -extern void *NXpData; -extern char *NXIformatNeXusTime(); -extern NXstatus NXIprintlink(NXhandle fid, NXlink* link); + typedef void (*ErrFunc) (void *data, char *text); + extern void NXMSetError(void *pData, ErrFunc); + extern ErrFunc NXMGetError(); + extern void NXMDisableErrorReporting(); + extern void NXMEnableErrorReporting(); + extern void (*NXIReportError) (void *pData, char *text); + extern void *NXpData; + extern char *NXIformatNeXusTime(); + extern NXstatus NXIprintlink(NXhandle fid, NXlink * link); /* another special function for setting the default cache size for HDF-5 */ -extern NXstatus NXsetcache(long newVal); + extern NXstatus NXsetcache(long newVal); typedef struct { - NXhandle *pNexusData; - int stripFlag; - NXstatus ( *nxclose)(NXhandle* pHandle); - NXstatus ( *nxflush)(NXhandle* pHandle); - NXstatus ( *nxmakegroup) (NXhandle handle, CONSTCHAR *name, CONSTCHAR* NXclass); - NXstatus ( *nxopengroup) (NXhandle handle, CONSTCHAR *name, CONSTCHAR* NXclass); - NXstatus ( *nxclosegroup)(NXhandle handle); - NXstatus ( *nxmakedata) (NXhandle handle, CONSTCHAR* label, int datatype, int rank, int dim[]); - NXstatus ( *nxcompmakedata) (NXhandle handle, CONSTCHAR* label, int datatype, int rank, int dim[], int comp_typ, int bufsize[]); - NXstatus ( *nxcompress) (NXhandle handle, int compr_type); - NXstatus ( *nxopendata) (NXhandle handle, CONSTCHAR* label); - NXstatus ( *nxclosedata)(NXhandle handle); - NXstatus ( *nxputdata)(NXhandle handle, void* data); - NXstatus ( *nxputattr)(NXhandle handle, CONSTCHAR* name, void* data, int iDataLen, int iType); - NXstatus ( *nxputslab)(NXhandle handle, void* data, int start[], int size[]); - NXstatus ( *nxgetdataID)(NXhandle handle, NXlink* pLink); - NXstatus ( *nxmakelink)(NXhandle handle, NXlink* pLink); - NXstatus ( *nxmakenamedlink)(NXhandle handle, CONSTCHAR *newname, NXlink* pLink); - NXstatus ( *nxgetdata)(NXhandle handle, void* data); - NXstatus ( *nxgetinfo)(NXhandle handle, int* rank, int dimension[], int* datatype); - NXstatus ( *nxgetnextentry)(NXhandle handle, NXname name, NXname nxclass, int* datatype); - NXstatus ( *nxgetslab)(NXhandle handle, void* data, int start[], int size[]); - NXstatus ( *nxgetnextattr)(NXhandle handle, NXname pName, int *iLength, int *iType); - NXstatus ( *nxgetattr)(NXhandle handle, char* name, void* data, int* iDataLen, int* iType); - NXstatus ( *nxgetattrinfo)(NXhandle handle, int* no_items); - NXstatus ( *nxgetgroupID)(NXhandle handle, NXlink* pLink); - NXstatus ( *nxgetgroupinfo)(NXhandle handle, int* no_items, NXname name, NXname nxclass); - NXstatus ( *nxsameID)(NXhandle handle, NXlink* pFirstID, NXlink* pSecondID); - NXstatus ( *nxinitgroupdir)(NXhandle handle); - NXstatus ( *nxinitattrdir)(NXhandle handle); - NXstatus ( *nxsetnumberformat)(NXhandle handle, int type, char *format); - NXstatus ( *nxprintlink)(NXhandle handle, NXlink* link); + NXhandle *pNexusData; + int stripFlag; + NXstatus(*nxclose) (NXhandle * pHandle); + NXstatus(*nxflush) (NXhandle * pHandle); + NXstatus(*nxmakegroup) (NXhandle handle, CONSTCHAR * name, + CONSTCHAR * NXclass); + NXstatus(*nxopengroup) (NXhandle handle, CONSTCHAR * name, + CONSTCHAR * NXclass); + NXstatus(*nxclosegroup) (NXhandle handle); + NXstatus(*nxmakedata) (NXhandle handle, CONSTCHAR * label, + int datatype, int rank, int dim[]); + NXstatus(*nxcompmakedata) (NXhandle handle, CONSTCHAR * label, + int datatype, int rank, int dim[], + int comp_typ, int bufsize[]); + NXstatus(*nxcompress) (NXhandle handle, int compr_type); + NXstatus(*nxopendata) (NXhandle handle, CONSTCHAR * label); + NXstatus(*nxclosedata) (NXhandle handle); + NXstatus(*nxputdata) (NXhandle handle, void *data); + NXstatus(*nxputattr) (NXhandle handle, CONSTCHAR * name, void *data, + int iDataLen, int iType); + NXstatus(*nxputslab) (NXhandle handle, void *data, int start[], + int size[]); + NXstatus(*nxgetdataID) (NXhandle handle, NXlink * pLink); + NXstatus(*nxmakelink) (NXhandle handle, NXlink * pLink); + NXstatus(*nxmakenamedlink) (NXhandle handle, CONSTCHAR * newname, + NXlink * pLink); + NXstatus(*nxgetdata) (NXhandle handle, void *data); + NXstatus(*nxgetinfo) (NXhandle handle, int *rank, int dimension[], + int *datatype); + NXstatus(*nxgetnextentry) (NXhandle handle, NXname name, + NXname nxclass, int *datatype); + NXstatus(*nxgetslab) (NXhandle handle, void *data, int start[], + int size[]); + NXstatus(*nxgetnextattr) (NXhandle handle, NXname pName, int *iLength, + int *iType); + NXstatus(*nxgetattr) (NXhandle handle, char *name, void *data, + int *iDataLen, int *iType); + NXstatus(*nxgetattrinfo) (NXhandle handle, int *no_items); + NXstatus(*nxgetgroupID) (NXhandle handle, NXlink * pLink); + NXstatus(*nxgetgroupinfo) (NXhandle handle, int *no_items, + NXname name, NXname nxclass); + NXstatus(*nxsameID) (NXhandle handle, NXlink * pFirstID, + NXlink * pSecondID); + NXstatus(*nxinitgroupdir) (NXhandle handle); + NXstatus(*nxinitattrdir) (NXhandle handle); + NXstatus(*nxsetnumberformat) (NXhandle handle, int type, + char *format); + NXstatus(*nxprintlink) (NXhandle handle, NXlink * link); } NexusFunction, *pNexusFunction; /*---------------------*/ extern long nx_cacheSize; /* FORTRAN internals */ - extern NXstatus NXfopen(char * filename, NXaccess* am, - NexusFunction* pHandle); - extern NXstatus NXfclose (NexusFunction* pHandle); - extern NXstatus NXfputattr(NXhandle fid, char *name, void *data, - int *pDatalen, int *pIType); - extern NXstatus NXfcompress(NXhandle fid, int *compr_type); - extern NXstatus NXfcompmakedata(NXhandle fid, char *name, - int *pDatatype, - int *pRank, int dimensions[], - int *compression_type, int chunk[]); - extern NXstatus NXfmakedata(NXhandle fid, char *name, int *pDatatype, - int *pRank, int dimensions[]); - extern NXstatus NXfflush(NexusFunction* pHandle); + extern NXstatus NXfopen(char *filename, NXaccess * am, + NexusFunction * pHandle); + extern NXstatus NXfclose(NexusFunction * pHandle); + extern NXstatus NXfputattr(NXhandle fid, char *name, void *data, + int *pDatalen, int *pIType); + extern NXstatus NXfcompress(NXhandle fid, int *compr_type); + extern NXstatus NXfcompmakedata(NXhandle fid, char *name, + int *pDatatype, + int *pRank, int dimensions[], + int *compression_type, int chunk[]); + extern NXstatus NXfmakedata(NXhandle fid, char *name, int *pDatatype, + int *pRank, int dimensions[]); + extern NXstatus NXfflush(NexusFunction * pHandle); #ifdef __cplusplus } -#endif /* __cplusplus */ - +#endif /* __cplusplus */ #endif /*NEXUSAPI*/ - diff --git a/napi4.c b/napi4.c index e0f3bb9a..289b8f3e 100644 --- a/napi4.c +++ b/napi4.c @@ -21,7 +21,7 @@ For further information, see - $Id: napi4.c,v 1.9 2008/01/03 09:56:56 koennecke Exp $ + $Id: napi4.c,v 1.10 2009/02/13 09:00:20 koennecke Exp $ ----------------------------------------------------------------------------*/ #include @@ -32,1933 +32,1834 @@ #include "napi.h" #include "napi4.h" -extern void *NXpData; +extern void *NXpData; - typedef struct __NexusFile { - struct iStack { - int32 *iRefDir; - int32 *iTagDir; - int32 iVref; - int32 __iStack_pad; - int iNDir; - int iCurDir; - } iStack[NXMAXSTACK]; - struct iStack iAtt; - int32 iVID; - int32 iSID; - int32 iCurrentVG; - int32 iCurrentSDS; - int iNXID; - int iStackPtr; - char iAccess[2]; - } NexusFile, *pNexusFile; +typedef struct __NexusFile { + struct iStack { + int32 *iRefDir; + int32 *iTagDir; + int32 iVref; + int32 __iStack_pad; + int iNDir; + int iCurDir; + } iStack[NXMAXSTACK]; + struct iStack iAtt; + int32 iVID; + int32 iSID; + int32 iCurrentVG; + int32 iCurrentSDS; + int iNXID; + int iStackPtr; + char iAccess[2]; +} NexusFile, *pNexusFile; /*--------------------------------------------------------------------*/ - static pNexusFile NXIassert(NXhandle fid) - { - pNexusFile pRes; - - assert(fid != NULL); - pRes = (pNexusFile)fid; - assert(pRes->iNXID == NXSIGNATURE); - return pRes; - } +static pNexusFile NXIassert(NXhandle fid) +{ + pNexusFile pRes; + + assert(fid != NULL); + pRes = (pNexusFile) fid; + assert(pRes->iNXID == NXSIGNATURE); + return pRes; +} + /*----------------------------------------------------------------------*/ static int findNapiClass(pNexusFile pFile, int groupRef, NXname nxclass) { NXname classText, linkClass; int32 tags[2], attID, linkID, groupID; - groupID = Vattach(pFile->iVID,groupRef,"r"); + groupID = Vattach(pFile->iVID, groupRef, "r"); Vgetclass(groupID, classText); - if(strcmp(classText,"NAPIlink") != 0) - { + if (strcmp(classText, "NAPIlink") != 0) { /* normal group */ - strcpy(nxclass,classText); + strcpy(nxclass, classText); Vdetach(groupID); return groupRef; - } - else - { + } else { /* code for linked renamed groups */ - attID = Vfindattr(groupID,"NAPIlink"); - if(attID >= 0) - { - Vgetattr(groupID,attID, tags); - linkID = Vattach(pFile->iVID,tags[1],"r"); + attID = Vfindattr(groupID, "NAPIlink"); + if (attID >= 0) { + Vgetattr(groupID, attID, tags); + linkID = Vattach(pFile->iVID, tags[1], "r"); Vgetclass(linkID, linkClass); Vdetach(groupID); Vdetach(linkID); - strcpy(nxclass,linkClass); + strcpy(nxclass, linkClass); return tags[1]; - } - else - { + } else { /* this allows for finding the NAPIlink group in NXmakenamedlink */ - strcpy(nxclass,classText); + strcpy(nxclass, classText); Vdetach(groupID); return groupRef; } - } + } } + /* --------------------------------------------------------------------- */ - static int32 NXIFindVgroup (pNexusFile pFile, CONSTCHAR *name, CONSTCHAR *nxclass) - { - int32 iNew, iRef, iTag; - int iN, i, status; - int32 *pArray = NULL; - NXname pText; - - assert (pFile != NULL); - - if (pFile->iCurrentVG == 0) { /* root level */ - /* get the number and ID's of all lone Vgroups in the file */ - iN = Vlone (pFile->iVID, NULL, 0); - if(iN == 0) { - return NX_EOD; - } - pArray = (int32 *) malloc (iN * sizeof (int32)); - if (!pArray) { - NXIReportError (NXpData, "ERROR: out of memory in NXIFindVgroup"); - return NX_EOD; - } - Vlone (pFile->iVID, pArray, iN); - - /* loop and check */ - for (i = 0; i < iN; i++) { - iNew = Vattach (pFile->iVID, pArray[i], "r"); - Vgetname (iNew, pText); - Vdetach(iNew); - if (strcmp (pText, name) == 0) { - pArray[i] = findNapiClass(pFile,pArray[i],pText); - if (strcmp (pText, nxclass) == 0) { - /* found ! */ - iNew = pArray[i]; - free (pArray); - return iNew; - } - } - } - /* nothing found */ - free (pArray); +static int32 NXIFindVgroup(pNexusFile pFile, CONSTCHAR * name, + CONSTCHAR * nxclass) +{ + int32 iNew, iRef, iTag; + int iN, i, status; + int32 *pArray = NULL; + NXname pText; + + assert(pFile != NULL); + + if (pFile->iCurrentVG == 0) { /* root level */ + /* get the number and ID's of all lone Vgroups in the file */ + iN = Vlone(pFile->iVID, NULL, 0); + if (iN == 0) { return NX_EOD; - } else { /* case in Vgroup */ - iN = Vntagrefs (pFile->iCurrentVG); - for (i = 0; i < iN; i++) { - Vgettagref (pFile->iCurrentVG, i, &iTag, &iRef); - if (iTag == DFTAG_VG) { - iNew = Vattach (pFile->iVID, iRef, "r"); - Vgetname (iNew, pText); - Vdetach(iNew); - if (strcmp (pText, name) == 0) { - iRef = findNapiClass(pFile,iRef, pText); - if (strcmp (pText, nxclass) == 0) { - return iRef; - } + } + pArray = (int32 *) malloc(iN * sizeof(int32)); + if (!pArray) { + NXIReportError(NXpData, "ERROR: out of memory in NXIFindVgroup"); + return NX_EOD; + } + Vlone(pFile->iVID, pArray, iN); + + /* loop and check */ + for (i = 0; i < iN; i++) { + iNew = Vattach(pFile->iVID, pArray[i], "r"); + Vgetname(iNew, pText); + Vdetach(iNew); + if (strcmp(pText, name) == 0) { + pArray[i] = findNapiClass(pFile, pArray[i], pText); + if (strcmp(pText, nxclass) == 0) { + /* found ! */ + iNew = pArray[i]; + free(pArray); + return iNew; + } + } + } + /* nothing found */ + free(pArray); + return NX_EOD; + } else { /* case in Vgroup */ + iN = Vntagrefs(pFile->iCurrentVG); + for (i = 0; i < iN; i++) { + Vgettagref(pFile->iCurrentVG, i, &iTag, &iRef); + if (iTag == DFTAG_VG) { + iNew = Vattach(pFile->iVID, iRef, "r"); + Vgetname(iNew, pText); + Vdetach(iNew); + if (strcmp(pText, name) == 0) { + iRef = findNapiClass(pFile, iRef, pText); + if (strcmp(pText, nxclass) == 0) { + return iRef; } } - } /* end for */ - } /* end else */ + } + } /* end for */ + } /* end else */ + /* not found */ + return NX_EOD; +} + + /*----------------------------------------------------------------------*/ + +static int32 NXIFindSDS(NXhandle fid, CONSTCHAR * name) +{ + pNexusFile self; + int32 iNew, iRet, iTag, iRef; + int32 i, iN, iA, iD1, iD2; + NXname pNam; + int32 iDim[MAX_VAR_DIMS]; + + self = NXIassert(fid); + + /* root level search */ + if (self->iCurrentVG == 0) { + i = SDfileinfo(self->iSID, &iN, &iA); + if (i < 0) { + NXIReportError(NXpData, "ERROR: failure to read file information"); + return NX_EOD; + } + for (i = 0; i < iN; i++) { + iNew = SDselect(self->iSID, i); + SDgetinfo(iNew, pNam, &iA, iDim, &iD1, &iD2); + if (strcmp(pNam, name) == 0) { + iRet = SDidtoref(iNew); + SDendaccess(iNew); + return iRet; + } else { + SDendaccess(iNew); + } + } /* not found */ return NX_EOD; } - - /*----------------------------------------------------------------------*/ + /* end root level */ + else { /* search in a Vgroup */ + iN = Vntagrefs(self->iCurrentVG); + for (i = 0; i < iN; i++) { + Vgettagref(self->iCurrentVG, i, &iTag, &iRef); + /* we are now writing using DFTAG_NDG, but need others for backward compatability */ + if ((iTag == DFTAG_SDG) || (iTag == DFTAG_NDG) + || (iTag == DFTAG_SDS)) { + iNew = SDreftoindex(self->iSID, iRef); + iNew = SDselect(self->iSID, iNew); + SDgetinfo(iNew, pNam, &iA, iDim, &iD1, &iD2); + if (strcmp(pNam, name) == 0) { + SDendaccess(iNew); + return iRef; + } + SDendaccess(iNew); + } + } /* end for */ + } /* end Vgroup */ + /* we get here, only if nothing found */ + return NX_EOD; +} - static int32 NXIFindSDS (NXhandle fid, CONSTCHAR *name) - { - pNexusFile self; - int32 iNew, iRet, iTag, iRef; - int32 i, iN, iA, iD1, iD2; - NXname pNam; - int32 iDim[MAX_VAR_DIMS]; - - self = NXIassert (fid); - - /* root level search */ - if (self->iCurrentVG == 0) { - i = SDfileinfo (self->iSID, &iN, &iA); - if (i < 0) { - NXIReportError (NXpData, "ERROR: failure to read file information"); - return NX_EOD; - } - for (i = 0; i < iN; i++) { - iNew = SDselect (self->iSID, i); - SDgetinfo (iNew, pNam, &iA, iDim, &iD1, &iD2); - if (strcmp (pNam, name) == 0) { - iRet = SDidtoref (iNew); - SDendaccess (iNew); - return iRet; - } else { - SDendaccess (iNew); - } - } - /* not found */ - return NX_EOD; - } - /* end root level */ - else { /* search in a Vgroup */ - iN = Vntagrefs (self->iCurrentVG); - for (i = 0; i < iN; i++) { - Vgettagref (self->iCurrentVG, i, &iTag, &iRef); - /* we are now writing using DFTAG_NDG, but need others for backward compatability */ - if ((iTag == DFTAG_SDG) || (iTag == DFTAG_NDG) || (iTag == DFTAG_SDS)) { - iNew = SDreftoindex (self->iSID, iRef); - iNew = SDselect (self->iSID, iNew); - SDgetinfo (iNew, pNam, &iA, iDim, &iD1, &iD2); - if (strcmp (pNam, name) == 0) { - SDendaccess (iNew); - return iRef; - } - SDendaccess (iNew); - } - } /* end for */ - } /* end Vgroup */ - /* we get here, only if nothing found */ - return NX_EOD; - } - /*----------------------------------------------------------------------*/ - static int NXIInitDir (pNexusFile self) - { - int i; - int32 iTag, iRef; - int iStackPtr; - +static int NXIInitDir(pNexusFile self) +{ + int i; + int32 iTag, iRef; + int iStackPtr; + /* * Note: the +1 to various malloc() operations is to avoid a * malloc(0), which is an error on some operating systems */ - iStackPtr = self->iStackPtr; - if (self->iCurrentVG == 0 && - self->iStack[iStackPtr].iRefDir == NULL) { /* root level */ - /* get the number and ID's of all lone Vgroups in the file */ - self->iStack[iStackPtr].iNDir = Vlone (self->iVID, NULL, 0); - self->iStack[iStackPtr].iRefDir = - (int32 *) malloc (self->iStack[iStackPtr].iNDir * sizeof (int32) + 1); - if (!self->iStack[iStackPtr].iRefDir) { - NXIReportError (NXpData, "ERROR: out of memory in NXIInitDir"); - return NX_EOD; - } - Vlone (self->iVID, - self->iStack[self->iStackPtr].iRefDir, - self->iStack[self->iStackPtr].iNDir); - } else { - /* Vgroup level */ - self->iStack[iStackPtr].iNDir = Vntagrefs (self->iCurrentVG); - self->iStack[iStackPtr].iRefDir = - (int32 *) malloc (self->iStack[iStackPtr].iNDir * sizeof (int32) + 1); - self->iStack[iStackPtr].iTagDir = - (int32 *) malloc (self->iStack[iStackPtr].iNDir * sizeof (int32) + 1); - if ((!self->iStack[iStackPtr].iRefDir) || - (!self->iStack[iStackPtr].iTagDir)) { - NXIReportError (NXpData, "ERROR: out of memory in NXIInitDir"); - return NX_EOD; - } - for (i = 0; i < self->iStack[self->iStackPtr].iNDir; i++) { - Vgettagref (self->iCurrentVG, i, &iTag, &iRef); - self->iStack[iStackPtr].iRefDir[i] = iRef; - self->iStack[iStackPtr].iTagDir[i] = iTag; - } + iStackPtr = self->iStackPtr; + if (self->iCurrentVG == 0 && self->iStack[iStackPtr].iRefDir == NULL) { /* root level */ + /* get the number and ID's of all lone Vgroups in the file */ + self->iStack[iStackPtr].iNDir = Vlone(self->iVID, NULL, 0); + self->iStack[iStackPtr].iRefDir = + (int32 *) malloc(self->iStack[iStackPtr].iNDir * sizeof(int32) + + 1); + if (!self->iStack[iStackPtr].iRefDir) { + NXIReportError(NXpData, "ERROR: out of memory in NXIInitDir"); + return NX_EOD; + } + Vlone(self->iVID, + self->iStack[self->iStackPtr].iRefDir, + self->iStack[self->iStackPtr].iNDir); + } else { + /* Vgroup level */ + self->iStack[iStackPtr].iNDir = Vntagrefs(self->iCurrentVG); + self->iStack[iStackPtr].iRefDir = + (int32 *) malloc(self->iStack[iStackPtr].iNDir * sizeof(int32) + + 1); + self->iStack[iStackPtr].iTagDir = + (int32 *) malloc(self->iStack[iStackPtr].iNDir * sizeof(int32) + + 1); + if ((!self->iStack[iStackPtr].iRefDir) + || (!self->iStack[iStackPtr].iTagDir)) { + NXIReportError(NXpData, "ERROR: out of memory in NXIInitDir"); + return NX_EOD; + } + for (i = 0; i < self->iStack[self->iStackPtr].iNDir; i++) { + Vgettagref(self->iCurrentVG, i, &iTag, &iRef); + self->iStack[iStackPtr].iRefDir[i] = iRef; + self->iStack[iStackPtr].iTagDir[i] = iTag; } - self->iStack[iStackPtr].iCurDir = 0; - return 1; } + self->iStack[iStackPtr].iCurDir = 0; + return 1; +} /*----------------------------------------------------------------------*/ - - static void NXIKillDir (pNexusFile self) - { - if (self->iStack[self->iStackPtr].iRefDir) { - free (self->iStack[self->iStackPtr].iRefDir); - self->iStack[self->iStackPtr].iRefDir = NULL; - } - if (self->iStack[self->iStackPtr].iTagDir) { - free (self->iStack[self->iStackPtr].iTagDir); - self->iStack[self->iStackPtr].iTagDir = NULL; - } - self->iStack[self->iStackPtr].iCurDir = 0; - self->iStack[self->iStackPtr].iNDir = 0; - } - +static void NXIKillDir(pNexusFile self) +{ + if (self->iStack[self->iStackPtr].iRefDir) { + free(self->iStack[self->iStackPtr].iRefDir); + self->iStack[self->iStackPtr].iRefDir = NULL; + } + if (self->iStack[self->iStackPtr].iTagDir) { + free(self->iStack[self->iStackPtr].iTagDir); + self->iStack[self->iStackPtr].iTagDir = NULL; + } + self->iStack[self->iStackPtr].iCurDir = 0; + self->iStack[self->iStackPtr].iNDir = 0; +} + + /*-------------------------------------------------------------------------*/ - static int NXIInitAttDir (pNexusFile pFile) - { - int iRet; - int32 iData, iAtt, iRank, iType; - int32 iDim[MAX_VAR_DIMS]; - NXname pNam; - - pFile->iAtt.iCurDir = 0; - if (pFile->iCurrentSDS != 0) { /* SDS level */ - iRet = SDgetinfo (pFile->iCurrentSDS, pNam, &iRank, iDim, &iType, - &iAtt); +static int NXIInitAttDir(pNexusFile pFile) +{ + int iRet; + int32 iData, iAtt, iRank, iType; + int32 iDim[MAX_VAR_DIMS]; + NXname pNam; + + pFile->iAtt.iCurDir = 0; + if (pFile->iCurrentSDS != 0) { /* SDS level */ + iRet = SDgetinfo(pFile->iCurrentSDS, pNam, &iRank, iDim, &iType, + &iAtt); + } else { + if (pFile->iCurrentVG == 0) { + /* global level */ + iRet = SDfileinfo(pFile->iSID, &iData, &iAtt); } else { - if(pFile->iCurrentVG == 0){ - /* global level */ - iRet = SDfileinfo (pFile->iSID, &iData, &iAtt); - } else { - /* group attribute */ - iRet = Vnattrs(pFile->iCurrentVG); - iAtt = iRet; - } + /* group attribute */ + iRet = Vnattrs(pFile->iCurrentVG); + iAtt = iRet; } - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot read attribute numbers"); - pFile->iAtt.iNDir = 0; - return NX_ERROR; - } - pFile->iAtt.iNDir = iAtt; - return NX_OK; } + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot read attribute numbers"); + pFile->iAtt.iNDir = 0; + return NX_ERROR; + } + pFile->iAtt.iNDir = iAtt; + return NX_OK; +} /* --------------------------------------------------------------------- */ - static void NXIKillAttDir (pNexusFile self) - { - if (self->iAtt.iRefDir) { - free (self->iAtt.iRefDir); - self->iAtt.iRefDir = NULL; - } - if (self->iAtt.iTagDir) { - free (self->iAtt.iTagDir); - self->iAtt.iTagDir = NULL; - } - self->iAtt.iCurDir = 0; - self->iAtt.iNDir = 0; +static void NXIKillAttDir(pNexusFile self) +{ + if (self->iAtt.iRefDir) { + free(self->iAtt.iRefDir); + self->iAtt.iRefDir = NULL; } + if (self->iAtt.iTagDir) { + free(self->iAtt.iTagDir); + self->iAtt.iTagDir = NULL; + } + self->iAtt.iCurDir = 0; + self->iAtt.iNDir = 0; +} + /*------------------------------------------------------------------*/ - static void NXIbuildPath(pNexusFile pFile, char *buffer, int bufLen) - { - int i; - int32 groupID, iA, iD1, iD2, iDim[MAX_VAR_DIMS]; - NXname pText; +static void NXIbuildPath(pNexusFile pFile, char *buffer, int bufLen) +{ + int i; + int32 groupID, iA, iD1, iD2, iDim[MAX_VAR_DIMS]; + NXname pText; + + buffer[0] = '\0'; + for (i = 0; i < pFile->iStackPtr; i++) { + strncat(buffer, "/", bufLen - strlen(buffer)); + groupID = Vattach(pFile->iVID, pFile->iStack[pFile->iStackPtr].iVref, + "r"); + Vgetname(groupID, pText); + strncat(buffer, pText, bufLen - strlen(buffer)); + Vdetach(groupID); + } + if (pFile->iCurrentSDS != 0) { + strncat(buffer, "/", bufLen - strlen(buffer)); + SDgetinfo(pFile->iCurrentSDS, pText, &iA, iDim, &iD1, &iD2); + strncat(buffer, pText, bufLen - strlen(buffer)); + } +} - buffer[0] = '\0'; - for(i = 0; i < pFile->iStackPtr; i++){ - strncat(buffer,"/",bufLen-strlen(buffer)); - groupID = Vattach(pFile->iVID,pFile->iStack[pFile->iStackPtr].iVref, - "r"); - Vgetname(groupID, pText); - strncat(buffer,pText,bufLen-strlen(buffer)); - Vdetach(groupID); - } - if(pFile->iCurrentSDS != 0){ - strncat(buffer,"/",bufLen-strlen(buffer)); - SDgetinfo(pFile->iCurrentSDS,pText,&iA,iDim,&iD1,&iD2); - strncat(buffer,pText,bufLen-strlen(buffer)); - } - } /* ---------------------------------------------------------------------- - - Definition of NeXus API - ---------------------------------------------------------------------*/ + Definition of NeXus API + + --------------------------------------------------------------------- */ - NXstatus NX4open(CONSTCHAR *filename, NXaccess am, - NXhandle* pHandle) - { - pNexusFile pNew = NULL; - char pBuffer[512]; - char *time_puffer = NULL; - char HDF_VERSION[64]; - uint32 lmajor, lminor, lrelease; - int32 am1=0; - int32 file_id=0, an_id=0, ann_id=0; - - *pHandle = NULL; - /* map Nexus NXaccess types to HDF4 types */ - if (am == NXACC_CREATE) { - am1 = DFACC_CREATE; - } else if (am == NXACC_CREATE4) { - am1 = DFACC_CREATE; - } else if (am == NXACC_READ) { - am1 = DFACC_READ; - } else if (am == NXACC_RDWR) { - am1 = DFACC_RDWR; - } - /* get memory */ - pNew = (pNexusFile) malloc (sizeof (NexusFile)); - if (!pNew) { - NXIReportError (NXpData, "ERROR: no memory to create File datastructure"); - return NX_ERROR; - } - memset (pNew, 0, sizeof (NexusFile)); +NXstatus NX4open(CONSTCHAR * filename, NXaccess am, NXhandle * pHandle) +{ + pNexusFile pNew = NULL; + char pBuffer[512]; + char *time_puffer = NULL; + char HDF_VERSION[64]; + uint32 lmajor, lminor, lrelease; + int32 am1 = 0; + int32 file_id = 0, an_id = 0, ann_id = 0; -#if WRITE_OLD_IDENT /* not used at moment */ + *pHandle = NULL; + /* map Nexus NXaccess types to HDF4 types */ + if (am == NXACC_CREATE) { + am1 = DFACC_CREATE; + } else if (am == NXACC_CREATE4) { + am1 = DFACC_CREATE; + } else if (am == NXACC_READ) { + am1 = DFACC_READ; + } else if (am == NXACC_RDWR) { + am1 = DFACC_RDWR; + } + /* get memory */ + pNew = (pNexusFile) malloc(sizeof(NexusFile)); + if (!pNew) { + NXIReportError(NXpData, + "ERROR: no memory to create File datastructure"); + return NX_ERROR; + } + memset(pNew, 0, sizeof(NexusFile)); + +#if WRITE_OLD_IDENT /* not used at moment */ /* * write something that can be used by OLE */ - - if (am == NXACC_CREATE || am == NXACC_CREATE4) { - if ( (file_id = Hopen(filename, am1, 0)) == -1 ) { - sprintf (pBuffer, "ERROR: cannot open file_a: %s", filename); - NXIReportError (NXpData, pBuffer); - free (pNew); - return NX_ERROR; - } - an_id = ANstart(file_id); - ann_id = ANcreatef(an_id, AN_FILE_LABEL); /* AN_FILE_DESC */ - ANwriteann(ann_id, "NeXus", 5); - ANendaccess(ann_id); - ANend(an_id); - if (Hclose(file_id) == -1) { - sprintf (pBuffer, "ERROR: cannot close file: %s", filename); - NXIReportError (NXpData, pBuffer); - free (pNew); - return NX_ERROR; - } - am = NXACC_RDWR; - } -#endif /* WRITE_OLD_IDENT */ - /* start SDS interface */ - pNew->iSID = SDstart (filename, am1); - if (pNew->iSID <= 0) { - sprintf (pBuffer, "ERROR: cannot open file_b: %s", filename); - NXIReportError (NXpData, pBuffer); - free (pNew); + if (am == NXACC_CREATE || am == NXACC_CREATE4) { + if ((file_id = Hopen(filename, am1, 0)) == -1) { + sprintf(pBuffer, "ERROR: cannot open file_a: %s", filename); + NXIReportError(NXpData, pBuffer); + free(pNew); return NX_ERROR; } + an_id = ANstart(file_id); + ann_id = ANcreatef(an_id, AN_FILE_LABEL); /* AN_FILE_DESC */ + ANwriteann(ann_id, "NeXus", 5); + ANendaccess(ann_id); + ANend(an_id); + if (Hclose(file_id) == -1) { + sprintf(pBuffer, "ERROR: cannot close file: %s", filename); + NXIReportError(NXpData, pBuffer); + free(pNew); + return NX_ERROR; + } + am = NXACC_RDWR; + } +#endif /* WRITE_OLD_IDENT */ + + /* start SDS interface */ + pNew->iSID = SDstart(filename, am1); + if (pNew->iSID <= 0) { + sprintf(pBuffer, "ERROR: cannot open file_b: %s", filename); + NXIReportError(NXpData, pBuffer); + free(pNew); + return NX_ERROR; + } /* * need to create global attributes file_name file_time NeXus_version * at some point for new files */ - if (am != NXACC_READ) { - if (SDsetattr(pNew->iSID, "NeXus_version", DFNT_CHAR8, strlen(NEXUS_VERSION), NEXUS_VERSION) < 0) { - NXIReportError (NXpData, "ERROR: HDF failed to store NeXus_version attribute "); - return NX_ERROR; - } - Hgetlibversion(&lmajor, &lminor, &lrelease, HDF_VERSION); - if (SDsetattr(pNew->iSID, "HDF_version", DFNT_CHAR8, strlen(HDF_VERSION), HDF_VERSION) < 0) { - NXIReportError (NXpData, "ERROR: HDF failed to store HDF_version attribute "); - return NX_ERROR; - } + if (am != NXACC_READ) { + if (SDsetattr + (pNew->iSID, "NeXus_version", DFNT_CHAR8, strlen(NEXUS_VERSION), + NEXUS_VERSION) < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store NeXus_version attribute "); + return NX_ERROR; } + Hgetlibversion(&lmajor, &lminor, &lrelease, HDF_VERSION); + if (SDsetattr + (pNew->iSID, "HDF_version", DFNT_CHAR8, strlen(HDF_VERSION), + HDF_VERSION) < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store HDF_version attribute "); + return NX_ERROR; + } + } - time_puffer = NXIformatNeXusTime(); - if (am == NXACC_CREATE || am == NXACC_CREATE4) { - if (SDsetattr(pNew->iSID, "file_name", DFNT_CHAR8, strlen(filename), (char*)filename) < 0) { - NXIReportError (NXpData, "ERROR: HDF failed to store file_name attribute "); - return NX_ERROR; - } - if(time_puffer != NULL){ - if (SDsetattr(pNew->iSID, "file_time", DFNT_CHAR8, - strlen(time_puffer), time_puffer) < 0) { - NXIReportError (NXpData, - "ERROR: HDF failed to store file_time attribute "); - free(time_puffer); - return NX_ERROR; - } - } + time_puffer = NXIformatNeXusTime(); + if (am == NXACC_CREATE || am == NXACC_CREATE4) { + if (SDsetattr + (pNew->iSID, "file_name", DFNT_CHAR8, strlen(filename), + (char *) filename) < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store file_name attribute "); + return NX_ERROR; } if (time_puffer != NULL) { - free(time_puffer); + if (SDsetattr(pNew->iSID, "file_time", DFNT_CHAR8, + strlen(time_puffer), time_puffer) < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store file_time attribute "); + free(time_puffer); + return NX_ERROR; + } } - - /* - * Otherwise we try to create the file two times which makes HDF - * Throw up on us. - */ - if (am == NXACC_CREATE || am == NXACC_CREATE4) { - am = NXACC_RDWR; - am1 = DFACC_RDWR; - } - - /* Set Vgroup access mode */ - if (am == NXACC_READ) { - strcpy(pNew->iAccess,"r"); - } else { - strcpy(pNew->iAccess,"w"); - } - - /* start Vgroup API */ - - pNew->iVID = Hopen(filename, am1, 100); - if (pNew->iVID <= 0) { - sprintf (pBuffer, "ERROR: cannot open file_c: %s", filename); - NXIReportError (NXpData, pBuffer); - free (pNew); - return NX_ERROR; - } - Vstart (pNew->iVID); - pNew->iNXID = NXSIGNATURE; - pNew->iStack[0].iVref = 0; /* root! */ - - *pHandle = (NXhandle)pNew; - return NX_OK; } + if (time_puffer != NULL) { + free(time_puffer); + } + + /* + * Otherwise we try to create the file two times which makes HDF + * Throw up on us. + */ + if (am == NXACC_CREATE || am == NXACC_CREATE4) { + am = NXACC_RDWR; + am1 = DFACC_RDWR; + } + + /* Set Vgroup access mode */ + if (am == NXACC_READ) { + strcpy(pNew->iAccess, "r"); + } else { + strcpy(pNew->iAccess, "w"); + } + + /* start Vgroup API */ + + pNew->iVID = Hopen(filename, am1, 100); + if (pNew->iVID <= 0) { + sprintf(pBuffer, "ERROR: cannot open file_c: %s", filename); + NXIReportError(NXpData, pBuffer); + free(pNew); + return NX_ERROR; + } + Vstart(pNew->iVID); + pNew->iNXID = NXSIGNATURE; + pNew->iStack[0].iVref = 0; /* root! */ + + *pHandle = (NXhandle) pNew; + return NX_OK; +} /*-----------------------------------------------------------------------*/ - - NXstatus NX4close (NXhandle* fid) - { - pNexusFile pFile = NULL; - int iRet; - - pFile = NXIassert(*fid); - iRet = 0; - /* close links into vGroups or SDS */ - if (pFile->iCurrentVG != 0) { - Vdetach (pFile->iCurrentVG); - } - if (pFile->iCurrentSDS != 0) { - iRet = SDendaccess (pFile->iCurrentSDS); - } - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: ending access to SDS"); - } - /* close the SDS and Vgroup API's */ - Vend (pFile->iVID); - iRet = SDend (pFile->iSID); - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot close SDS interface"); - } - iRet = Hclose (pFile->iVID); - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot close HDF file"); - } - /* release memory */ - NXIKillDir (pFile); - free (pFile); - *fid = NULL; - return NX_OK; - } +NXstatus NX4close(NXhandle * fid) +{ + pNexusFile pFile = NULL; + int iRet; -/*-----------------------------------------------------------------------*/ - - - NXstatus NX4makegroup (NXhandle fid, CONSTCHAR *name, CONSTCHAR *nxclass) - { - pNexusFile pFile; - int32 iNew, iRet; - char pBuffer[256]; - - pFile = NXIassert (fid); - /* - * Make sure that a group with the same name and nxclass does not - * already exist. - */ - if ((iRet = NXIFindVgroup (pFile, (char*)name, nxclass)) >= 0) { - sprintf (pBuffer, "ERROR: Vgroup %s, class %s already exists", - name, nxclass); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - - /* create and configure the group */ - iNew = Vattach (pFile->iVID, -1, "w"); - if (iNew < 0) { - NXIReportError (NXpData, "ERROR: HDF could not create Vgroup"); - return NX_ERROR; - } - Vsetname (iNew, name); - Vsetclass (iNew, nxclass); - - /* Insert it into the hierarchy, when appropriate */ - iRet = 0; - if (pFile->iCurrentVG != 0) { - iRet = Vinsert (pFile->iCurrentVG, iNew); - } - Vdetach (iNew); - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF failed to insert Vgroup"); - return NX_ERROR; - } - return NX_OK; + pFile = NXIassert(*fid); + iRet = 0; + /* close links into vGroups or SDS */ + if (pFile->iCurrentVG != 0) { + Vdetach(pFile->iCurrentVG); } + if (pFile->iCurrentSDS != 0) { + iRet = SDendaccess(pFile->iCurrentSDS); + } + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: ending access to SDS"); + } + /* close the SDS and Vgroup API's */ + Vend(pFile->iVID); + iRet = SDend(pFile->iSID); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot close SDS interface"); + } + iRet = Hclose(pFile->iVID); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot close HDF file"); + } + /* release memory */ + NXIKillDir(pFile); + free(pFile); + *fid = NULL; + return NX_OK; +} + + +/*-----------------------------------------------------------------------*/ + + +NXstatus NX4makegroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass) +{ + pNexusFile pFile; + int32 iNew, iRet; + char pBuffer[256]; + + pFile = NXIassert(fid); + /* + * Make sure that a group with the same name and nxclass does not + * already exist. + */ + if ((iRet = NXIFindVgroup(pFile, (char *) name, nxclass)) >= 0) { + sprintf(pBuffer, "ERROR: Vgroup %s, class %s already exists", + name, nxclass); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + + /* create and configure the group */ + iNew = Vattach(pFile->iVID, -1, "w"); + if (iNew < 0) { + NXIReportError(NXpData, "ERROR: HDF could not create Vgroup"); + return NX_ERROR; + } + Vsetname(iNew, name); + Vsetclass(iNew, nxclass); + + /* Insert it into the hierarchy, when appropriate */ + iRet = 0; + if (pFile->iCurrentVG != 0) { + iRet = Vinsert(pFile->iCurrentVG, iNew); + } + Vdetach(iNew); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF failed to insert Vgroup"); + return NX_ERROR; + } + return NX_OK; +} /*------------------------------------------------------------------------*/ - NXstatus NX4opengroup (NXhandle fid, CONSTCHAR *name, CONSTCHAR *nxclass) - { - pNexusFile pFile; - int32 iRef; - char pBuffer[256]; - - pFile = NXIassert (fid); - - iRef = NXIFindVgroup (pFile, (char*)name, nxclass); - if (iRef < 0) { - sprintf (pBuffer, "ERROR: Vgroup %s, class %s NOT found", name, nxclass); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - /* are we at root level ? */ - if (pFile->iCurrentVG == 0) { - pFile->iCurrentVG = Vattach (pFile->iVID, iRef,pFile->iAccess); - pFile->iStackPtr++; - pFile->iStack[pFile->iStackPtr].iVref = iRef; - } else { - Vdetach (pFile->iCurrentVG); - pFile->iStackPtr++; - pFile->iStack[pFile->iStackPtr].iVref = iRef; - pFile->iCurrentVG = Vattach (pFile->iVID, - pFile->iStack[pFile->iStackPtr].iVref, - pFile->iAccess); - } - NXIKillDir (pFile); - return NX_OK; +NXstatus NX4opengroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass) +{ + pNexusFile pFile; + int32 iRef; + char pBuffer[256]; + + pFile = NXIassert(fid); + + iRef = NXIFindVgroup(pFile, (char *) name, nxclass); + if (iRef < 0) { + sprintf(pBuffer, "ERROR: Vgroup %s, class %s NOT found", name, + nxclass); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; } - /* ------------------------------------------------------------------- */ - - - NXstatus NX4closegroup (NXhandle fid) - { - pNexusFile pFile; - - pFile = NXIassert (fid); - - /* first catch the trivial case: we are at root and cannot get - deeper into a negative directory hierarchy (anti-directory) - */ - if (pFile->iCurrentVG == 0) { - NXIKillDir (pFile); - return NX_OK; - } else { /* Sighhh. Some work to do */ - /* close the current VG and decrement stack */ - Vdetach (pFile->iCurrentVG); - NXIKillDir (pFile); - pFile->iStackPtr--; - if (pFile->iStackPtr <= 0) { /* we hit root */ - pFile->iStackPtr = 0; - pFile->iCurrentVG = 0; - } else { - /* attach to the lower Vgroup */ - pFile->iCurrentVG = Vattach (pFile->iVID, - pFile->iStack[pFile->iStackPtr].iVref, - pFile->iAccess); - } - } - return NX_OK; + /* are we at root level ? */ + if (pFile->iCurrentVG == 0) { + pFile->iCurrentVG = Vattach(pFile->iVID, iRef, pFile->iAccess); + pFile->iStackPtr++; + pFile->iStack[pFile->iStackPtr].iVref = iRef; + } else { + Vdetach(pFile->iCurrentVG); + pFile->iStackPtr++; + pFile->iStack[pFile->iStackPtr].iVref = iRef; + pFile->iCurrentVG = Vattach(pFile->iVID, + pFile->iStack[pFile->iStackPtr].iVref, + pFile->iAccess); } - - - /* --------------------------------------------------------------------- */ - - NXstatus NX4makedata (NXhandle fid, CONSTCHAR *name, int datatype, int rank, - int dimensions[]) - { - pNexusFile pFile; - int32 iNew; - char pBuffer[256]; - int i, iRet, type; - int32 myDim[MAX_VAR_DIMS]; - - pFile = NXIassert (fid); - - if (dimensions[0] == NX_UNLIMITED) - { - dimensions[0] = SD_UNLIMITED; - } - - if ((iNew = NXIFindSDS (fid, name))>=0) { - sprintf (pBuffer, "ERROR: SDS %s already exists at this level", name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - - if (datatype == NX_CHAR) - { - type=DFNT_CHAR8; - } - else if (datatype == NX_INT8) - { - type=DFNT_INT8; - } - else if (datatype == NX_UINT8) - { - type=DFNT_UINT8; - } - else if (datatype == NX_INT16) - { - type=DFNT_INT16; - } - else if (datatype == NX_UINT16) - { - type=DFNT_UINT16; - } - else if (datatype == NX_INT32) - { - type=DFNT_INT32; - } - else if (datatype == NX_UINT32) - { - type=DFNT_UINT32; - } - else if (datatype == NX_FLOAT32) - { - type=DFNT_FLOAT32; - } - else if (datatype == NX_FLOAT64) - { - type=DFNT_FLOAT64; - } - else - { - NXIReportError (NXpData, "ERROR: invalid type in NX4makedata"); - return NX_ERROR; - } - - if (rank <= 0) { - sprintf (pBuffer, "ERROR: invalid rank specified for SDS %s", - name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - - /* - Check dimensions for consistency. The first dimension may be 0 - thus denoting an unlimited dimension. - */ - for (i = 1; i < rank; i++) { - if (dimensions[i] <= 0) { - sprintf (pBuffer, - "ERROR: invalid dimension %d, value %d given for SDS %s", - i, dimensions[i], name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - } - - /* cast the dimensions array properly for non 32-bit ints */ - for(i = 0; i < rank; i++) - { - myDim[i] = (int32)dimensions[i]; - } - - - /* behave nicely, if there is still an SDS open */ - if (pFile->iCurrentSDS != 0) { - SDendaccess (pFile->iCurrentSDS); - pFile->iCurrentSDS = 0; - } - - /* Do not allow creation of SDS's at the root level */ - if (pFile->iCurrentVG == 0) { - sprintf(pBuffer, "ERROR: SDS creation at root level is not permitted"); - NXIReportError(NXpData, pBuffer); - return NX_ERROR; - } - - /* dataset creation */ - iNew = SDcreate (pFile->iSID, (char*)name, (int32)type, - (int32)rank, myDim); - if (iNew < 0) { - sprintf (pBuffer, "ERROR: cannot create SDS %s, check arguments", - name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - /* link into Vgroup, if in one */ - if (pFile->iCurrentVG != 0) { - iRet = Vaddtagref (pFile->iCurrentVG, DFTAG_NDG, SDidtoref (iNew)); - } - iRet = SDendaccess (iNew); - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot end access to SDS"); - return NX_ERROR; - } - return NX_OK; - } - - - /* --------------------------------------------------------------------- */ - - - NXstatus NX4compmakedata (NXhandle fid, CONSTCHAR *name, int datatype, int rank, - int dimensions[],int compress_type, int chunk_size[]) - { - pNexusFile pFile; - int32 iNew, iRet, type; - char pBuffer[256]; - int i; - int32 myDim[MAX_VAR_DIMS]; - comp_info compstruct; - - pFile = NXIassert (fid); - - if (dimensions[0] == NX_UNLIMITED) - { - dimensions[0] = SD_UNLIMITED; - } - - if ((iNew = NXIFindSDS (fid, name))>=0) { - sprintf (pBuffer, "ERROR: SDS %s already exists at this level", name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - - if (datatype == NX_CHAR) - { - type=DFNT_CHAR8; - } - else if (datatype == NX_INT8) - { - type=DFNT_INT8; - } - else if (datatype == NX_UINT8) - { - type=DFNT_UINT8; - } - else if (datatype == NX_INT16) - { - type=DFNT_INT16; - } - else if (datatype == NX_UINT16) - { - type=DFNT_UINT16; - } - else if (datatype == NX_INT32) - { - type=DFNT_INT32; - } - else if (datatype == NX_UINT32) - { - type=DFNT_UINT32; - } - else if (datatype == NX_FLOAT32) - { - type=DFNT_FLOAT32; - } - else if (datatype == NX_FLOAT64) - { - type=DFNT_FLOAT64; - } - else - { - NXIReportError (NXpData, "ERROR: invalid datatype in NX4compmakedata"); - return NX_ERROR; - } - - if (rank <= 0) { - sprintf (pBuffer, "ERROR: invalid rank specified for SDS %s", - name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - - /* - Check dimensions for consistency. The first dimension may be 0 - thus denoting an unlimited dimension. - */ - for (i = 1; i < rank; i++) { - if (dimensions[i] <= 0) { - sprintf (pBuffer, - "ERROR: invalid dimension %d, value %d given for SDS %s", - i, dimensions[i], name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - } - - /* cast the dimensions array properly for non 32-bit ints */ - for(i = 0; i < rank; i++) - { - myDim[i] = (int32)dimensions[i]; - } - - - /* behave nicely, if there is still an SDS open */ - if (pFile->iCurrentSDS != 0) { - SDendaccess (pFile->iCurrentSDS); - pFile->iCurrentSDS = 0; - } - - /* Do not allow creation of SDS's at the root level */ - if (pFile->iCurrentVG == 0) { - sprintf(pBuffer, "ERROR: SDS creation at root level is not permitted"); - NXIReportError(NXpData, pBuffer); - return NX_ERROR; - } - - /* dataset creation */ - iNew = SDcreate (pFile->iSID, (char*)name, (int32)type, - (int32)rank, myDim); - if (iNew < 0) { - sprintf (pBuffer, "ERROR: cannot create SDS %s, check arguments", - name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - - /* compress SD data set */ - - if(compress_type == NX_COMP_LZW) - { - compstruct.deflate.level = 6; - iRet = SDsetcompress(iNew, COMP_CODE_DEFLATE, &compstruct); - if (iRet < 0) - { - NXIReportError (NXpData, "LZW-Compression failure!"); - return NX_ERROR; - } - } - else if (compress_type == NX_COMP_RLE) - { - iRet = SDsetcompress(iNew, COMP_CODE_RLE, &compstruct); - if (iRet < 0) - { - NXIReportError (NXpData, "RLE-Compression failure!"); - return NX_ERROR; - } - } - else if (compress_type == NX_COMP_HUF) - { - compstruct.skphuff.skp_size = DFKNTsize(type); - iRet = SDsetcompress(iNew, COMP_CODE_SKPHUFF, &compstruct); - if (iRet < 0) - { - NXIReportError (NXpData, "HUF-Compression failure!"); - return NX_ERROR; - } - } - else if (compress_type == NX_COMP_NONE) - { - /* */ - } - else - { - NXIReportError (NXpData, "Unknown compression method!"); - return NX_ERROR; - } - /* link into Vgroup, if in one */ - if (pFile->iCurrentVG != 0) { - iRet = Vaddtagref (pFile->iCurrentVG, DFTAG_NDG, SDidtoref (iNew)); - } - iRet = SDendaccess (iNew); - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot end access to SDS"); - return NX_ERROR; - } - - return NX_OK; - } - - /* --------------------------------------------------------------------- */ - - - NXstatus NX4compress (NXhandle fid, int compress_type) - { - pNexusFile pFile; - int32 iRank, iAtt, iType, iRet; - int32 iSize[MAX_VAR_DIMS]; - int compress_typei = COMP_CODE_NONE; - NXname pBuffer; - char pError[512]; - comp_info compstruct; - - pFile = NXIassert (fid); - - /* check if there is an SDS open */ - if (pFile->iCurrentSDS == 0) { - NXIReportError (NXpData, "ERROR: no SDS open"); - return NX_ERROR; - } - - if (compress_type == NX_COMP_NONE) - { - compress_typei = COMP_CODE_NONE; - } - else if (compress_type == NX_COMP_LZW) - { - compress_typei = COMP_CODE_DEFLATE; - } - else if (compress_type == NX_COMP_RLE) - { - compress_typei = COMP_CODE_RLE; - } - else if - (compress_type == NX_COMP_HUF) - { - compress_typei = COMP_CODE_SKPHUFF; - } - - /* first read dimension information */ - SDgetinfo (pFile->iCurrentSDS, pBuffer, &iRank, iSize, &iType, &iAtt); - - /* - according to compression type initialize compression - information - */ - if(compress_type == NX_COMP_LZW) - { - compstruct.deflate.level = 6; - } - else if(compress_type == NX_COMP_HUF) - { - compstruct.skphuff.skp_size = DFKNTsize(iType); - } - - iRet = SDsetcompress(pFile->iCurrentSDS, compress_typei, &compstruct); - if (iRet < 0) { - sprintf (pError, "ERROR: failure to compress data to %s", pBuffer); - NXIReportError (NXpData, pError); - return NX_ERROR; - } - return NX_OK; - } - - /* --------------------------------------------------------------------- */ - - - NXstatus NX4opendata (NXhandle fid, CONSTCHAR *name) - { - pNexusFile pFile; - int32 iNew, attID, tags[2]; - char pBuffer[256]; - int iRet; - - pFile = NXIassert (fid); - - /* First find the reference number of the SDS */ - iNew = NXIFindSDS (fid, name); - if (iNew < 0) { - sprintf (pBuffer, "ERROR: SDS %s not found at this level", name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - /* Be nice: properly close the old open SDS silently if there is - * still an SDS open. - */ - if (pFile->iCurrentSDS) { - iRet = SDendaccess (pFile->iCurrentSDS); - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot end access to SDS"); - } - } - /* clear pending attribute directories first */ - NXIKillAttDir (pFile); - - /* open the SDS, thereby watching for linked SDS under a different name */ - iNew = SDreftoindex (pFile->iSID, iNew); - pFile->iCurrentSDS = SDselect (pFile->iSID, iNew); - attID = SDfindattr(pFile->iCurrentSDS,"NAPIlink"); - if(attID >= 0) - { - SDreadattr(pFile->iCurrentSDS,attID, tags); - SDendaccess(pFile->iCurrentSDS); - iNew = SDreftoindex (pFile->iSID, tags[1]); - pFile->iCurrentSDS = SDselect (pFile->iSID, iNew); - } - - if (pFile->iCurrentSDS < 0) { - NXIReportError (NXpData, "ERROR: HDF error opening SDS"); - pFile->iCurrentSDS = 0; - return NX_ERROR; - } - return NX_OK; - } - - /* ----------------------------------------------------------------- */ - - - NXstatus NX4closedata (NXhandle fid) - { - pNexusFile pFile; - int iRet; - - pFile = NXIassert (fid); - - if (pFile->iCurrentSDS != 0) { - iRet = SDendaccess (pFile->iCurrentSDS); - pFile->iCurrentSDS = 0; - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot end access to SDS"); - return NX_ERROR; - } - } else { - NXIReportError (NXpData, "ERROR: no SDS open --> nothing to do"); - return NX_ERROR; - } - NXIKillAttDir (pFile); /* for attribute data */ - return NX_OK; - } - - - /* ------------------------------------------------------------------- */ - - NXstatus NX4putdata (NXhandle fid, void *data) - { - pNexusFile pFile; - int32 iStart[MAX_VAR_DIMS], iSize[MAX_VAR_DIMS], iStride[MAX_VAR_DIMS]; - NXname pBuffer; - int32 iRank, iAtt, iType, iRet, i; - char pError[512]; - - pFile = NXIassert (fid); - - /* check if there is an SDS open */ - if (pFile->iCurrentSDS == 0) { - NXIReportError (NXpData, "ERROR: no SDS open"); - return NX_ERROR; - } - /* first read dimension information */ - memset (iStart, 0, MAX_VAR_DIMS * sizeof (int32)); - SDgetinfo (pFile->iCurrentSDS, pBuffer, &iRank, iSize, &iType, &iAtt); - - /* initialise stride to 1 */ - for (i = 0; i < iRank; i++) { - iStride[i] = 1; - } - - /* actually write */ - iRet = SDwritedata (pFile->iCurrentSDS, iStart, iStride, iSize, data); - if (iRet < 0) { - sprintf (pError, "ERROR: failure to write data to %s", pBuffer); - NXIReportError (NXpData, pError); - return NX_ERROR; - } - return NX_OK; - } - - /* ------------------------------------------------------------------- */ - - NXstatus - NX4putattr (NXhandle fid, CONSTCHAR *name, void *data, int datalen, int iType) - { - pNexusFile pFile; - int iRet, type; - - pFile = NXIassert (fid); - if (iType == NX_CHAR) - { - type=DFNT_CHAR8; - } - else if (iType == NX_INT8) - { - type=DFNT_INT8; - } - else if (iType == NX_UINT8) - { - type=DFNT_UINT8; - } - else if (iType == NX_INT16) - { - type=DFNT_INT16; - } - else if (iType == NX_UINT16) - { - type=DFNT_UINT16; - } - else if (iType == NX_INT32) - { - type=DFNT_INT32; - } - else if (iType == NX_UINT32) - { - type=DFNT_UINT32; - } - else if (iType == NX_FLOAT32) - { - type=DFNT_FLOAT32; - } - else if (iType == NX_FLOAT64) - { - type=DFNT_FLOAT64; - } - else - { - NXIReportError (NXpData, "ERROR: Invalid data type for HDF attribute"); - return NX_ERROR; - } - if (pFile->iCurrentSDS != 0) { - /* SDS attribute */ - iRet = SDsetattr (pFile->iCurrentSDS, (char*)name, (int32)type, - (int32)datalen, data); - } else { - if(pFile->iCurrentVG == 0){ - /* global attribute */ - iRet = SDsetattr (pFile->iSID, (char*)name, (int32)type, - (int32)datalen, data); - } else { - /* group attribute */ - iRet = Vsetattr(pFile->iCurrentVG, (char *)name, (int32) type, - (int32)datalen,data); - } - } - iType = type; - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF failed to store attribute "); - return NX_ERROR; - } - return NX_OK; - } - - /* ------------------------------------------------------------------- */ - - - NXstatus NX4putslab (NXhandle fid, void *data, int iStart[], int iSize[]) - { - pNexusFile pFile; - int iRet; - int32 iStride[MAX_VAR_DIMS]; - int32 myStart[MAX_VAR_DIMS], mySize[MAX_VAR_DIMS]; - int32 i, iRank, iType, iAtt; - NXname pBuffer; - - - pFile = NXIassert (fid); - - /* check if there is an SDS open */ - if (pFile->iCurrentSDS == 0) { - NXIReportError (NXpData, "ERROR: no SDS open"); - return NX_ERROR; - } - /* initialise stride to 1 */ - for (i = 0; i < MAX_VAR_DIMS; i++) { - iStride[i] = 1; - } - - /* if an int is not 32-bit we have to cast them properly in order - to kill a bug. - */ - if(sizeof(int) != 4) - { - SDgetinfo (pFile->iCurrentSDS, pBuffer, - &iRank, myStart, &iType, &iAtt); - for(i = 0; i < iRank; i++) - { - myStart[i] = (int32)iStart[i]; - mySize[i] = (int32)iSize[i]; - } - /* finally write */ - iRet = SDwritedata (pFile->iCurrentSDS, myStart, - iStride, mySize, data); - - } - else - { - /* write directly */ - - iRet = SDwritedata (pFile->iCurrentSDS,(int32*)iStart, iStride, (int32*)iSize, data); - } - - /* deal with HDF errors */ - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: writing slab failed"); - return NX_ERROR; - } - return NX_OK; - } - - - /* ------------------------------------------------------------------- */ - - NXstatus NX4getdataID (NXhandle fid, NXlink* sRes) - { - pNexusFile pFile; - - pFile = NXIassert (fid); - - if (pFile->iCurrentSDS == 0) { - sRes->iTag = NX_ERROR; - return NX_ERROR; - } else { - sRes->iTag = DFTAG_NDG; - sRes->iRef = SDidtoref (pFile->iCurrentSDS); - NXIbuildPath(pFile,sRes->targetPath,1024); - return NX_OK; - } - sRes->iTag = NX_ERROR; - return NX_ERROR; /* not reached */ - } - + NXIKillDir(pFile); + return NX_OK; +} /* ------------------------------------------------------------------- */ - - NXstatus NX4makelink (NXhandle fid, NXlink* sLink) - { - pNexusFile pFile; - int32 iVG, iRet, dataID, type = DFNT_CHAR8, length; - char name[] = "target"; - - pFile = NXIassert (fid); - - if (pFile->iCurrentVG == 0) { /* root level, can not link here */ - return NX_ERROR; - } - Vaddtagref(pFile->iCurrentVG, sLink->iTag, sLink->iRef); - length = strlen(sLink->targetPath); - if(sLink->iTag == DFTAG_SDG || sLink->iTag == DFTAG_NDG || - sLink->iTag == DFTAG_SDS) - { - dataID = SDreftoindex(pFile->iSID,sLink->iRef); - dataID = SDselect(pFile->iSID,dataID); - SDsetattr(dataID,name,type,length,sLink->targetPath); - SDendaccess(dataID); - } - else - { - dataID = Vattach(pFile->iVID,sLink->iRef,"w"); - Vsetattr(dataID, (char *)name, type, (int32) length, sLink->targetPath); - Vdetach(dataID); - } + +NXstatus NX4closegroup(NXhandle fid) +{ + pNexusFile pFile; + + pFile = NXIassert(fid); + + /* first catch the trivial case: we are at root and cannot get + deeper into a negative directory hierarchy (anti-directory) + */ + if (pFile->iCurrentVG == 0) { + NXIKillDir(pFile); return NX_OK; - } - /* ------------------------------------------------------------------- */ - - - NXstatus NX4makenamedlink (NXhandle fid, CONSTCHAR* newname, NXlink* sLink) - { - pNexusFile pFile; - int32 iVG, iRet, dataID, type = DFNT_CHAR8, length, dataType = NX_CHAR, - rank = 1, attType = NX_INT32; - int iDim[1]; - char name[] = "target"; - int tags[2]; - - pFile = NXIassert (fid); - - if (pFile->iCurrentVG == 0) { /* root level, can not link here */ - return NX_ERROR; - } - - tags[0] = sLink->iTag; - tags[1] = sLink->iRef; - - length = strlen(sLink->targetPath); - if(sLink->iTag == DFTAG_SDG || sLink->iTag == DFTAG_NDG || - sLink->iTag == DFTAG_SDS) - { - iDim[0] = 1; - NX4makedata(fid,newname, dataType,rank,iDim); - NX4opendata(fid,newname); - NX4putattr(fid,"NAPIlink",tags, 2, attType); - NX4closedata(fid); - dataID = SDreftoindex(pFile->iSID,sLink->iRef); - dataID = SDselect(pFile->iSID,dataID); - SDsetattr(dataID,name,type,length,sLink->targetPath); - SDendaccess(dataID); + } else { /* Sighhh. Some work to do */ + /* close the current VG and decrement stack */ + Vdetach(pFile->iCurrentVG); + NXIKillDir(pFile); + pFile->iStackPtr--; + if (pFile->iStackPtr <= 0) { /* we hit root */ + pFile->iStackPtr = 0; + pFile->iCurrentVG = 0; } else { - NX4makegroup(fid,newname,"NAPIlink"); - NX4opengroup(fid,newname,"NAPIlink"); - NX4putattr(fid,"NAPIlink",tags, 2, attType); - NX4closegroup(fid); - dataID = Vattach(pFile->iVID,sLink->iRef,"w"); - Vsetattr(dataID, (char *)name, type, (int32) length, sLink->targetPath); - Vdetach(dataID); - } - return NX_OK; - } - - /*----------------------------------------------------------------------*/ - - NXstatus NX4printlink (NXhandle fid, NXlink* sLink) - { - pNexusFile pFile; - pFile = NXIassert (fid); - printf("HDF4 link: iTag = %ld, iRef = %ld, target=\"%s\"\n", sLink->iTag, sLink->iRef, sLink->targetPath); - return NX_OK; - } - - /*----------------------------------------------------------------------*/ - - NXstatus NX4flush(NXhandle *pHandle) - { - char *pFileName, *pCopy = NULL; - int access, dummy, iRet, i, iStack; - pNexusFile pFile = NULL; - NXaccess ac; - int *iRefs = NULL; - - pFile = NXIassert(*pHandle); - - /* - The HDF4-API does not support a flush. We help ourselves with - inquiring the name and access type of the file, closing it and - opening it again. This is also the reason why this needs a pointer - to the handle structure as the handle changes. The other thing we - do is to store the refs of all open vGroups in a temporary array - in order to recover the position in the vGroup hierarchy before the - flush. - */ - iRet = Hfidinquire(pFile->iVID,&pFileName,&access,&dummy); - if (iRet < 0) { - NXIReportError (NXpData, - "ERROR: Failed to inquire file name for HDF file"); - return NX_ERROR; - } - if(pFile->iAccess[0] == 'r') { - ac = NXACC_READ; - }else if(pFile->iAccess[0] == 'w') { - ac = NXACC_RDWR; - } else { - NXIReportError (NXpData, - "ERROR: NX4flush failed to determine file access mode"); - return NX_ERROR; - } - pCopy = (char *)malloc((strlen(pFileName)+10)*sizeof(char)); - if(!pCopy) { - NXIReportError (NXpData, - "ERROR: Failed to allocate data for filename copy"); - return NX_ERROR; - } - memset(pCopy,0,strlen(pFileName)+10); - strcpy(pCopy,pFileName); - - /* get refs for recovering vGroup position */ - iStack = 0; - if(pFile->iStackPtr > 0) { - iStack = pFile->iStackPtr + 1; - iRefs = (int *)malloc(iStack*sizeof(int)); - if(!iRefs){ - NXIReportError (NXpData, - "ERROR: Failed to allocate data for hierarchy copy"); - return NX_ERROR; - } - for(i = 0; i < iStack; i++){ - iRefs[i] = pFile->iStack[i].iVref; - } - } - - iRet = NX4close(pHandle); - if(iRet != NX_OK) { - return iRet; - } - - iRet = NX4open(pCopy, ac, pHandle); - free(pCopy); - - /* return to position in vGroup hierarchy */ - pFile = NXIassert(*pHandle); - if(iStack > 0){ - pFile->iStackPtr = iStack - 1; - for(i = 0; i < iStack; i++){ - pFile->iStack[i].iVref = iRefs[i]; - } - free(iRefs); + /* attach to the lower Vgroup */ pFile->iCurrentVG = Vattach(pFile->iVID, pFile->iStack[pFile->iStackPtr].iVref, pFile->iAccess); } - - return iRet; - } + } + return NX_OK; +} - /*-------------------------------------------------------------------------*/ - - NXstatus NX4getnextentry (NXhandle fid, NXname name, NXname nxclass, int *datatype) - { - pNexusFile pFile; - int iRet, iStackPtr, iCurDir; - int32 iTemp, iD1, iD2, iA; - int32 iDim[MAX_VAR_DIMS]; - - pFile = NXIassert (fid); - - iStackPtr = pFile->iStackPtr; - iCurDir = pFile->iStack[pFile->iStackPtr].iCurDir; - - /* first case to check for: no directory entry */ - if (pFile->iStack[pFile->iStackPtr].iRefDir == NULL) { - iRet = NXIInitDir (pFile); - if (iRet < 0) { - NXIReportError (NXpData, - "ERROR: no memory to store directory info"); - return NX_EOD; - } - } + /* --------------------------------------------------------------------- */ - /* Next case: end of directory */ - if (iCurDir >= pFile->iStack[pFile->iStackPtr].iNDir) { - NXIKillDir (pFile); - return NX_EOD; - } +NXstatus NX4makedata(NXhandle fid, CONSTCHAR * name, int datatype, + int rank, int dimensions[]) +{ + pNexusFile pFile; + int32 iNew; + char pBuffer[256]; + int i, iRet, type; + int32 myDim[MAX_VAR_DIMS]; - /* Next case: we have data! supply it and increment counter */ - if (pFile->iCurrentVG == 0) { /* root level */ - iTemp = Vattach (pFile->iVID, - pFile->iStack[iStackPtr].iRefDir[iCurDir], "r"); - if (iTemp < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot attach to Vgroup"); - return NX_ERROR; - } - Vgetname (iTemp, name); - Vdetach (iTemp); - findNapiClass(pFile, pFile->iStack[pFile->iStackPtr].iRefDir[iCurDir], nxclass); - *datatype = DFTAG_VG; - pFile->iStack[pFile->iStackPtr].iCurDir++; - return NX_OK; - } else { /* in Vgroup */ - if (pFile->iStack[iStackPtr].iTagDir[iCurDir] == DFTAG_VG) {/* Vgroup */ - iTemp = Vattach (pFile->iVID, - pFile->iStack[iStackPtr].iRefDir[iCurDir], "r"); - if (iTemp < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot attach to Vgroup"); - return NX_ERROR; - } - Vgetname (iTemp, name); - Vdetach(iTemp); - findNapiClass(pFile, pFile->iStack[pFile->iStackPtr].iRefDir[iCurDir], nxclass); - *datatype = DFTAG_VG; - pFile->iStack[pFile->iStackPtr].iCurDir++; - Vdetach (iTemp); - return NX_OK; - /* we are now writing using DFTAG_NDG, but need others for backward compatability */ - } else if ((pFile->iStack[iStackPtr].iTagDir[iCurDir] == DFTAG_SDG) || - (pFile->iStack[iStackPtr].iTagDir[iCurDir] == DFTAG_NDG) || - (pFile->iStack[iStackPtr].iTagDir[iCurDir] == DFTAG_SDS)) { - iTemp = SDreftoindex (pFile->iSID, - pFile->iStack[iStackPtr].iRefDir[iCurDir]); - iTemp = SDselect (pFile->iSID, iTemp); - SDgetinfo (iTemp, name, &iA, iDim, &iD1, &iD2); - strcpy (nxclass, "SDS"); - *datatype = iD1; - SDendaccess (iTemp); - pFile->iStack[pFile->iStackPtr].iCurDir++; - return NX_OK; - } else { /* unidentified */ - strcpy (name, "UNKNOWN"); - strcpy (nxclass, "UNKNOWN"); - *datatype = pFile->iStack[iStackPtr].iTagDir[iCurDir]; - pFile->iStack[pFile->iStackPtr].iCurDir++; - return NX_OK; - } - } - return NX_ERROR; /* not reached */ + pFile = NXIassert(fid); + + if (dimensions[0] == NX_UNLIMITED) { + dimensions[0] = SD_UNLIMITED; } - - /*-------------------------------------------------------------------------*/ - - - NXstatus NX4getdata (NXhandle fid, void *data) - { - pNexusFile pFile; - int32 iStart[MAX_VAR_DIMS], iSize[MAX_VAR_DIMS]; - NXname pBuffer; - int32 iRank, iAtt, iType; - - pFile = NXIassert (fid); - - /* check if there is an SDS open */ - if (pFile->iCurrentSDS == 0) { - NXIReportError (NXpData, "ERROR: no SDS open"); - return NX_ERROR; - } - /* first read dimension information */ - memset (iStart, 0, MAX_VAR_DIMS * sizeof (int32)); - SDgetinfo (pFile->iCurrentSDS, pBuffer, &iRank, iSize, &iType, &iAtt); - /* actually read */ - SDreaddata (pFile->iCurrentSDS, iStart, NULL, iSize, data); - return NX_OK; - } - - /*-------------------------------------------------------------------------*/ - - NXstatus - NX4getinfo (NXhandle fid, int *rank, int dimension[], - int *iType) - { - pNexusFile pFile; - NXname pBuffer; - int32 iAtt, myDim[MAX_VAR_DIMS], i, iRank, mType; - - pFile = NXIassert (fid); - - /* check if there is an SDS open */ - if (pFile->iCurrentSDS == 0) { - NXIReportError (NXpData, "ERROR: no SDS open"); - return NX_ERROR; - } - /* read information */ - SDgetinfo (pFile->iCurrentSDS, pBuffer, &iRank, myDim, - &mType, &iAtt); - - /* conversion to proper ints for the platform */ - *iType = (int)mType; - *rank = (int)iRank; - for(i = 0; i < iRank; i++) - { - dimension[i] = (int)myDim[i]; - } - return NX_OK; - } - - - /*-------------------------------------------------------------------------*/ - - - NXstatus NX4getslab (NXhandle fid, void *data, int iStart[], int iSize[]) - { - pNexusFile pFile; - int32 myStart[MAX_VAR_DIMS], mySize[MAX_VAR_DIMS]; - int32 i, iRank, iType, iAtt; - NXname pBuffer; - - pFile = NXIassert (fid); - - /* check if there is an SDS open */ - if (pFile->iCurrentSDS == 0) { - NXIReportError (NXpData, "ERROR: no SDS open"); - return NX_ERROR; - } - - /* if an int is not 32-bit we have to cast them properly in order - to kill a bug. - */ - if(sizeof(int) != 4) - { - SDgetinfo (pFile->iCurrentSDS, pBuffer, - &iRank, myStart, &iType, &iAtt); - for(i = 0; i < iRank; i++) - { - myStart[i] = (int32)iStart[i]; - mySize[i] = (int32)iSize[i]; - } - /* finally read */ - SDreaddata (pFile->iCurrentSDS, myStart, NULL, - mySize, data); - return NX_OK; - } - else - { - /* read directly */ - SDreaddata (pFile->iCurrentSDS, (int32*)iStart, NULL, - (int32*)iSize, data); - return NX_OK; - } - } - - /*-------------------------------------------------------------------------*/ - - NXstatus NX4getnextattr (NXhandle fileid, NXname pName, - int *iLength, int *iType) - { - pNexusFile pFile; - int iRet; - int32 iPType, iCount, count; - - pFile = NXIassert (fileid); - - /* first check if we have to start a new attribute search */ - if (pFile->iAtt.iNDir == 0) { - iRet = NXIInitAttDir (pFile); - if (iRet == NX_ERROR) { - return NX_ERROR; - } - } - /* are we done ? */ - if (pFile->iAtt.iCurDir >= pFile->iAtt.iNDir) { - NXIKillAttDir (pFile); - return NX_EOD; - } - /* well, there must be data to copy */ - if (pFile->iCurrentSDS == 0) { - if(pFile->iCurrentVG == 0) { - /* global attribute */ - iRet = SDattrinfo (pFile->iSID, pFile->iAtt.iCurDir, - pName, &iPType, &iCount); - }else { - /* group attribute */ - iRet = Vattrinfo(pFile->iCurrentVG, pFile->iAtt.iCurDir, - pName, &iPType, &iCount, &count); - } - } else { - iRet = SDattrinfo (pFile->iCurrentSDS, pFile->iAtt.iCurDir, - pName, &iPType, &iCount); - } - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot read attribute info"); - return NX_ERROR; - } - *iLength = iCount; - *iType = iPType; - pFile->iAtt.iCurDir++; - return NX_OK; - } - - - /*-------------------------------------------------------------------------*/ - - - NXstatus NX4getattr (NXhandle fid, char *name, void *data, int* datalen, int* iType) - { - pNexusFile pFile; - int32 iNew, iType32, count; - void *pData = NULL; - int32 iLen, iRet; - int type; - char pBuffer[256]; - NXname pNam; - - type = *iType; - if (type == NX_CHAR) - { - type=DFNT_CHAR8; - } - else if (type == NX_INT8) - { - type=DFNT_INT8; - } - else if (type == NX_UINT8) - { - type=DFNT_UINT8; - } - else if (type == NX_INT16) - { - type=DFNT_INT16; - } - else if (type == NX_UINT16) - { - type=DFNT_UINT16; - } - else if (type == NX_INT32) - { - type=DFNT_INT32; - } - else if (type == NX_UINT32) - { - type=DFNT_UINT32; - } - else if (type == NX_FLOAT32) - { - type=DFNT_FLOAT32; - } - else if (type == NX_FLOAT64) - { - type=DFNT_FLOAT64; - } - *datalen = (*datalen) * DFKNTsize(type); - pFile = NXIassert (fid); - - /* find attribute */ - if (pFile->iCurrentSDS != 0) { - /* SDS attribute */ - iNew = SDfindattr (pFile->iCurrentSDS, name); - } else { - if(pFile->iCurrentVG == 0){ - /* global attribute */ - iNew = SDfindattr (pFile->iSID, name); - } else { - /* group attribute */ - iNew = Vfindattr(pFile->iCurrentVG, name); - } - } - if (iNew < 0) { - sprintf (pBuffer, "ERROR: attribute %s not found", name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - /* get more info, allocate temporary data space */ - iType32 = (int32)type; - if (pFile->iCurrentSDS != 0) { - iRet = SDattrinfo (pFile->iCurrentSDS, iNew, pNam, &iType32, &iLen); - } else { - if(pFile->iCurrentVG == 0){ - iRet = SDattrinfo (pFile->iSID, iNew, pNam, &iType32, &iLen); - } else { - iRet = Vattrinfo(pFile->iCurrentVG,iNew,pNam,&iType32,&count, - &iLen); - } - } - if (iRet < 0) { - sprintf (pBuffer, "ERROR: HDF could not read attribute info"); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - *iType = (int)iType32; - iLen = iLen * DFKNTsize (*iType); - pData = (void *) malloc (iLen); - if (!pData) { - NXIReportError (NXpData, "ERROR: allocating memory in NXgetattr"); - return NX_ERROR; - } - memset (pData, 0, iLen); - - /* finally read the data */ - if (pFile->iCurrentSDS != 0) { - iRet = SDreadattr (pFile->iCurrentSDS, iNew, pData); - } else { - if(pFile->iCurrentVG == 0){ - iRet = SDreadattr (pFile->iSID, iNew, pData); - } else { - iRet = Vgetattr(pFile->iCurrentVG, iNew, pData); - } - } - if (iRet < 0) { - sprintf (pBuffer, "ERROR: HDF could not read attribute data"); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - /* copy data to caller */ - memset (data, 0, *datalen); - if ((*datalen <= iLen) && - (*iType == DFNT_UINT8 || *iType == DFNT_CHAR8 || *iType == DFNT_UCHAR8)) { - iLen = *datalen - 1; - } - memcpy (data, pData, iLen); - *datalen = iLen / DFKNTsize(*iType); - free (pData); - return NX_OK; - } - - /*-------------------------------------------------------------------------*/ - - - NXstatus NX4getattrinfo (NXhandle fid, int *iN) - { - pNexusFile pFile; - int iRet; - int32 iData, iAtt, iRank, iType; - int32 iDim[MAX_VAR_DIMS]; - NXname pNam; - - pFile = NXIassert (fid); - if (pFile->iCurrentSDS != 0) { /* SDS level */ - iRet = SDgetinfo (pFile->iCurrentSDS, pNam, &iRank, iDim, &iType, - &iAtt); - } else { - if(pFile->iCurrentVG == 0){ - /* global level */ - iRet = SDfileinfo (pFile->iSID, &iData, &iAtt); - } else { - iRet = Vnattrs(pFile->iCurrentVG); - iAtt = iRet; - } - } - if (iRet < 0) { - NXIReportError (NXpData, "NX_ERROR: HDF cannot read attribute numbers"); - *iN = 0; - return NX_ERROR; - } - *iN = iAtt; - return NX_OK; - } - - /*-------------------------------------------------------------------------*/ - - NXstatus NX4getgroupID (NXhandle fileid, NXlink* sRes) - { - pNexusFile pFile; - - pFile = NXIassert (fileid); - - if (pFile->iCurrentVG == 0) { - sRes->iTag = NX_ERROR; - return NX_ERROR; - } else { - sRes->iTag = DFTAG_VG; - sRes->iRef = VQueryref(pFile->iCurrentVG); - NXIbuildPath(pFile,sRes->targetPath,1024); - return NX_OK; - } - /* not reached */ - sRes->iTag = NX_ERROR; + if ((iNew = NXIFindSDS(fid, name)) >= 0) { + sprintf(pBuffer, "ERROR: SDS %s already exists at this level", name); + NXIReportError(NXpData, pBuffer); return NX_ERROR; } - /*-------------------------------------------------------------------------*/ - - NXstatus - NX4getgroupinfo (NXhandle fid, int *iN, NXname pName, NXname pClass) - { - pNexusFile pFile; - - pFile = NXIassert (fid); - /* check if there is a group open */ - if (pFile->iCurrentVG == 0) { - *iN = Vlone (pFile->iVID, NULL, 0); - strcpy (pName, "root"); - strcpy (pClass, "NXroot"); - } - else { - *iN = Vntagrefs (pFile->iCurrentVG); - Vgetname (pFile->iCurrentVG, pName); - Vgetclass (pFile->iCurrentVG, pClass); - } - return NX_OK; + if (datatype == NX_CHAR) { + type = DFNT_CHAR8; + } else if (datatype == NX_INT8) { + type = DFNT_INT8; + } else if (datatype == NX_UINT8) { + type = DFNT_UINT8; + } else if (datatype == NX_INT16) { + type = DFNT_INT16; + } else if (datatype == NX_UINT16) { + type = DFNT_UINT16; + } else if (datatype == NX_INT32) { + type = DFNT_INT32; + } else if (datatype == NX_UINT32) { + type = DFNT_UINT32; + } else if (datatype == NX_FLOAT32) { + type = DFNT_FLOAT32; + } else if (datatype == NX_FLOAT64) { + type = DFNT_FLOAT64; + } else { + NXIReportError(NXpData, "ERROR: invalid type in NX4makedata"); + return NX_ERROR; } - + + if (rank <= 0) { + sprintf(pBuffer, "ERROR: invalid rank specified for SDS %s", name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + + /* + Check dimensions for consistency. The first dimension may be 0 + thus denoting an unlimited dimension. + */ + for (i = 1; i < rank; i++) { + if (dimensions[i] <= 0) { + sprintf(pBuffer, + "ERROR: invalid dimension %d, value %d given for SDS %s", + i, dimensions[i], name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + } + + /* cast the dimensions array properly for non 32-bit ints */ + for (i = 0; i < rank; i++) { + myDim[i] = (int32) dimensions[i]; + } + + + /* behave nicely, if there is still an SDS open */ + if (pFile->iCurrentSDS != 0) { + SDendaccess(pFile->iCurrentSDS); + pFile->iCurrentSDS = 0; + } + + /* Do not allow creation of SDS's at the root level */ + if (pFile->iCurrentVG == 0) { + sprintf(pBuffer, "ERROR: SDS creation at root level is not permitted"); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + + /* dataset creation */ + iNew = SDcreate(pFile->iSID, (char *) name, (int32) type, + (int32) rank, myDim); + if (iNew < 0) { + sprintf(pBuffer, "ERROR: cannot create SDS %s, check arguments", name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + /* link into Vgroup, if in one */ + if (pFile->iCurrentVG != 0) { + iRet = Vaddtagref(pFile->iCurrentVG, DFTAG_NDG, SDidtoref(iNew)); + } + iRet = SDendaccess(iNew); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot end access to SDS"); + return NX_ERROR; + } + return NX_OK; +} + + + /* --------------------------------------------------------------------- */ + + +NXstatus NX4compmakedata(NXhandle fid, CONSTCHAR * name, int datatype, + int rank, int dimensions[], int compress_type, + int chunk_size[]) +{ + pNexusFile pFile; + int32 iNew, iRet, type; + char pBuffer[256]; + int i; + int32 myDim[MAX_VAR_DIMS]; + comp_info compstruct; + + pFile = NXIassert(fid); + + if (dimensions[0] == NX_UNLIMITED) { + dimensions[0] = SD_UNLIMITED; + } + + if ((iNew = NXIFindSDS(fid, name)) >= 0) { + sprintf(pBuffer, "ERROR: SDS %s already exists at this level", name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + + if (datatype == NX_CHAR) { + type = DFNT_CHAR8; + } else if (datatype == NX_INT8) { + type = DFNT_INT8; + } else if (datatype == NX_UINT8) { + type = DFNT_UINT8; + } else if (datatype == NX_INT16) { + type = DFNT_INT16; + } else if (datatype == NX_UINT16) { + type = DFNT_UINT16; + } else if (datatype == NX_INT32) { + type = DFNT_INT32; + } else if (datatype == NX_UINT32) { + type = DFNT_UINT32; + } else if (datatype == NX_FLOAT32) { + type = DFNT_FLOAT32; + } else if (datatype == NX_FLOAT64) { + type = DFNT_FLOAT64; + } else { + NXIReportError(NXpData, "ERROR: invalid datatype in NX4compmakedata"); + return NX_ERROR; + } + + if (rank <= 0) { + sprintf(pBuffer, "ERROR: invalid rank specified for SDS %s", name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + + /* + Check dimensions for consistency. The first dimension may be 0 + thus denoting an unlimited dimension. + */ + for (i = 1; i < rank; i++) { + if (dimensions[i] <= 0) { + sprintf(pBuffer, + "ERROR: invalid dimension %d, value %d given for SDS %s", + i, dimensions[i], name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + } + + /* cast the dimensions array properly for non 32-bit ints */ + for (i = 0; i < rank; i++) { + myDim[i] = (int32) dimensions[i]; + } + + + /* behave nicely, if there is still an SDS open */ + if (pFile->iCurrentSDS != 0) { + SDendaccess(pFile->iCurrentSDS); + pFile->iCurrentSDS = 0; + } + + /* Do not allow creation of SDS's at the root level */ + if (pFile->iCurrentVG == 0) { + sprintf(pBuffer, "ERROR: SDS creation at root level is not permitted"); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + + /* dataset creation */ + iNew = SDcreate(pFile->iSID, (char *) name, (int32) type, + (int32) rank, myDim); + if (iNew < 0) { + sprintf(pBuffer, "ERROR: cannot create SDS %s, check arguments", name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + + /* compress SD data set */ + + if (compress_type == NX_COMP_LZW) { + compstruct.deflate.level = 6; + iRet = SDsetcompress(iNew, COMP_CODE_DEFLATE, &compstruct); + if (iRet < 0) { + NXIReportError(NXpData, "LZW-Compression failure!"); + return NX_ERROR; + } + } else if (compress_type == NX_COMP_RLE) { + iRet = SDsetcompress(iNew, COMP_CODE_RLE, &compstruct); + if (iRet < 0) { + NXIReportError(NXpData, "RLE-Compression failure!"); + return NX_ERROR; + } + } else if (compress_type == NX_COMP_HUF) { + compstruct.skphuff.skp_size = DFKNTsize(type); + iRet = SDsetcompress(iNew, COMP_CODE_SKPHUFF, &compstruct); + if (iRet < 0) { + NXIReportError(NXpData, "HUF-Compression failure!"); + return NX_ERROR; + } + } else if (compress_type == NX_COMP_NONE) { + /* */ + } else { + NXIReportError(NXpData, "Unknown compression method!"); + return NX_ERROR; + } + /* link into Vgroup, if in one */ + if (pFile->iCurrentVG != 0) { + iRet = Vaddtagref(pFile->iCurrentVG, DFTAG_NDG, SDidtoref(iNew)); + } + iRet = SDendaccess(iNew); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot end access to SDS"); + return NX_ERROR; + } + + return NX_OK; +} + + /* --------------------------------------------------------------------- */ + + +NXstatus NX4compress(NXhandle fid, int compress_type) +{ + pNexusFile pFile; + int32 iRank, iAtt, iType, iRet; + int32 iSize[MAX_VAR_DIMS]; + int compress_typei = COMP_CODE_NONE; + NXname pBuffer; + char pError[512]; + comp_info compstruct; + + pFile = NXIassert(fid); + + /* check if there is an SDS open */ + if (pFile->iCurrentSDS == 0) { + NXIReportError(NXpData, "ERROR: no SDS open"); + return NX_ERROR; + } + + if (compress_type == NX_COMP_NONE) { + compress_typei = COMP_CODE_NONE; + } else if (compress_type == NX_COMP_LZW) { + compress_typei = COMP_CODE_DEFLATE; + } else if (compress_type == NX_COMP_RLE) { + compress_typei = COMP_CODE_RLE; + } else if (compress_type == NX_COMP_HUF) { + compress_typei = COMP_CODE_SKPHUFF; + } + + /* first read dimension information */ + SDgetinfo(pFile->iCurrentSDS, pBuffer, &iRank, iSize, &iType, &iAtt); + + /* + according to compression type initialize compression + information + */ + if (compress_type == NX_COMP_LZW) { + compstruct.deflate.level = 6; + } else if (compress_type == NX_COMP_HUF) { + compstruct.skphuff.skp_size = DFKNTsize(iType); + } + + iRet = SDsetcompress(pFile->iCurrentSDS, compress_typei, &compstruct); + if (iRet < 0) { + sprintf(pError, "ERROR: failure to compress data to %s", pBuffer); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + return NX_OK; +} + + /* --------------------------------------------------------------------- */ + + +NXstatus NX4opendata(NXhandle fid, CONSTCHAR * name) +{ + pNexusFile pFile; + int32 iNew, attID, tags[2]; + char pBuffer[256]; + int iRet; + + pFile = NXIassert(fid); + + /* First find the reference number of the SDS */ + iNew = NXIFindSDS(fid, name); + if (iNew < 0) { + sprintf(pBuffer, "ERROR: SDS %s not found at this level", name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + /* Be nice: properly close the old open SDS silently if there is + * still an SDS open. + */ + if (pFile->iCurrentSDS) { + iRet = SDendaccess(pFile->iCurrentSDS); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot end access to SDS"); + } + } + /* clear pending attribute directories first */ + NXIKillAttDir(pFile); + + /* open the SDS, thereby watching for linked SDS under a different name */ + iNew = SDreftoindex(pFile->iSID, iNew); + pFile->iCurrentSDS = SDselect(pFile->iSID, iNew); + attID = SDfindattr(pFile->iCurrentSDS, "NAPIlink"); + if (attID >= 0) { + SDreadattr(pFile->iCurrentSDS, attID, tags); + SDendaccess(pFile->iCurrentSDS); + iNew = SDreftoindex(pFile->iSID, tags[1]); + pFile->iCurrentSDS = SDselect(pFile->iSID, iNew); + } + + if (pFile->iCurrentSDS < 0) { + NXIReportError(NXpData, "ERROR: HDF error opening SDS"); + pFile->iCurrentSDS = 0; + return NX_ERROR; + } + return NX_OK; +} + + /* ----------------------------------------------------------------- */ + + +NXstatus NX4closedata(NXhandle fid) +{ + pNexusFile pFile; + int iRet; + + pFile = NXIassert(fid); + + if (pFile->iCurrentSDS != 0) { + iRet = SDendaccess(pFile->iCurrentSDS); + pFile->iCurrentSDS = 0; + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot end access to SDS"); + return NX_ERROR; + } + } else { + NXIReportError(NXpData, "ERROR: no SDS open --> nothing to do"); + return NX_ERROR; + } + NXIKillAttDir(pFile); /* for attribute data */ + return NX_OK; +} + + /* ------------------------------------------------------------------- */ - NXstatus NX4sameID (NXhandle fileid, NXlink* pFirstID, NXlink* pSecondID) - { - pNexusFile pFile; +NXstatus NX4putdata(NXhandle fid, void *data) +{ + pNexusFile pFile; + int32 iStart[MAX_VAR_DIMS], iSize[MAX_VAR_DIMS], iStride[MAX_VAR_DIMS]; + NXname pBuffer; + int32 iRank, iAtt, iType, iRet, i; + char pError[512]; - pFile = NXIassert (fileid); - if ((pFirstID->iTag == pSecondID->iTag) & (pFirstID->iRef == pSecondID->iRef)) { - return NX_OK; + pFile = NXIassert(fid); + + /* check if there is an SDS open */ + if (pFile->iCurrentSDS == 0) { + NXIReportError(NXpData, "ERROR: no SDS open"); + return NX_ERROR; + } + /* first read dimension information */ + memset(iStart, 0, MAX_VAR_DIMS * sizeof(int32)); + SDgetinfo(pFile->iCurrentSDS, pBuffer, &iRank, iSize, &iType, &iAtt); + + /* initialise stride to 1 */ + for (i = 0; i < iRank; i++) { + iStride[i] = 1; + } + + /* actually write */ + iRet = SDwritedata(pFile->iCurrentSDS, iStart, iStride, iSize, data); + if (iRet < 0) { + sprintf(pError, "ERROR: failure to write data to %s", pBuffer); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + return NX_OK; +} + + /* ------------------------------------------------------------------- */ + +NXstatus +NX4putattr(NXhandle fid, CONSTCHAR * name, void *data, int datalen, + int iType) +{ + pNexusFile pFile; + int iRet, type; + + pFile = NXIassert(fid); + if (iType == NX_CHAR) { + type = DFNT_CHAR8; + } else if (iType == NX_INT8) { + type = DFNT_INT8; + } else if (iType == NX_UINT8) { + type = DFNT_UINT8; + } else if (iType == NX_INT16) { + type = DFNT_INT16; + } else if (iType == NX_UINT16) { + type = DFNT_UINT16; + } else if (iType == NX_INT32) { + type = DFNT_INT32; + } else if (iType == NX_UINT32) { + type = DFNT_UINT32; + } else if (iType == NX_FLOAT32) { + type = DFNT_FLOAT32; + } else if (iType == NX_FLOAT64) { + type = DFNT_FLOAT64; + } else { + NXIReportError(NXpData, "ERROR: Invalid data type for HDF attribute"); + return NX_ERROR; + } + if (pFile->iCurrentSDS != 0) { + /* SDS attribute */ + iRet = SDsetattr(pFile->iCurrentSDS, (char *) name, (int32) type, + (int32) datalen, data); + } else { + if (pFile->iCurrentVG == 0) { + /* global attribute */ + iRet = SDsetattr(pFile->iSID, (char *) name, (int32) type, + (int32) datalen, data); } else { - return NX_ERROR; + /* group attribute */ + iRet = Vsetattr(pFile->iCurrentVG, (char *) name, (int32) type, + (int32) datalen, data); + } + } + iType = type; + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF failed to store attribute "); + return NX_ERROR; + } + return NX_OK; +} + + /* ------------------------------------------------------------------- */ + + +NXstatus NX4putslab(NXhandle fid, void *data, int iStart[], int iSize[]) +{ + pNexusFile pFile; + int iRet; + int32 iStride[MAX_VAR_DIMS]; + int32 myStart[MAX_VAR_DIMS], mySize[MAX_VAR_DIMS]; + int32 i, iRank, iType, iAtt; + NXname pBuffer; + + + pFile = NXIassert(fid); + + /* check if there is an SDS open */ + if (pFile->iCurrentSDS == 0) { + NXIReportError(NXpData, "ERROR: no SDS open"); + return NX_ERROR; + } + /* initialise stride to 1 */ + for (i = 0; i < MAX_VAR_DIMS; i++) { + iStride[i] = 1; + } + + /* if an int is not 32-bit we have to cast them properly in order + to kill a bug. + */ + if (sizeof(int) != 4) { + SDgetinfo(pFile->iCurrentSDS, pBuffer, &iRank, myStart, &iType, &iAtt); + for (i = 0; i < iRank; i++) { + myStart[i] = (int32) iStart[i]; + mySize[i] = (int32) iSize[i]; + } + /* finally write */ + iRet = SDwritedata(pFile->iCurrentSDS, myStart, iStride, mySize, data); + + } else { + /* write directly */ + + iRet = + SDwritedata(pFile->iCurrentSDS, (int32 *) iStart, iStride, + (int32 *) iSize, data); + } + + /* deal with HDF errors */ + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: writing slab failed"); + return NX_ERROR; + } + return NX_OK; +} + + + /* ------------------------------------------------------------------- */ + +NXstatus NX4getdataID(NXhandle fid, NXlink * sRes) +{ + pNexusFile pFile; + + pFile = NXIassert(fid); + + if (pFile->iCurrentSDS == 0) { + sRes->iTag = NX_ERROR; + return NX_ERROR; + } else { + sRes->iTag = DFTAG_NDG; + sRes->iRef = SDidtoref(pFile->iCurrentSDS); + NXIbuildPath(pFile, sRes->targetPath, 1024); + return NX_OK; + } + sRes->iTag = NX_ERROR; + return NX_ERROR; /* not reached */ +} + + + /* ------------------------------------------------------------------- */ + + +NXstatus NX4makelink(NXhandle fid, NXlink * sLink) +{ + pNexusFile pFile; + int32 iVG, iRet, dataID, type = DFNT_CHAR8, length; + char name[] = "target"; + + pFile = NXIassert(fid); + + if (pFile->iCurrentVG == 0) { /* root level, can not link here */ + return NX_ERROR; + } + Vaddtagref(pFile->iCurrentVG, sLink->iTag, sLink->iRef); + length = strlen(sLink->targetPath); + if (sLink->iTag == DFTAG_SDG || sLink->iTag == DFTAG_NDG || + sLink->iTag == DFTAG_SDS) { + dataID = SDreftoindex(pFile->iSID, sLink->iRef); + dataID = SDselect(pFile->iSID, dataID); + SDsetattr(dataID, name, type, length, sLink->targetPath); + SDendaccess(dataID); + } else { + dataID = Vattach(pFile->iVID, sLink->iRef, "w"); + Vsetattr(dataID, (char *) name, type, (int32) length, + sLink->targetPath); + Vdetach(dataID); + } + return NX_OK; +} + + /* ------------------------------------------------------------------- */ + + +NXstatus NX4makenamedlink(NXhandle fid, CONSTCHAR * newname, + NXlink * sLink) +{ + pNexusFile pFile; + int32 iVG, iRet, dataID, type = DFNT_CHAR8, length, dataType = NX_CHAR, + rank = 1, attType = NX_INT32; + int iDim[1]; + char name[] = "target"; + int tags[2]; + + pFile = NXIassert(fid); + + if (pFile->iCurrentVG == 0) { /* root level, can not link here */ + return NX_ERROR; + } + + tags[0] = sLink->iTag; + tags[1] = sLink->iRef; + + length = strlen(sLink->targetPath); + if (sLink->iTag == DFTAG_SDG || sLink->iTag == DFTAG_NDG || + sLink->iTag == DFTAG_SDS) { + iDim[0] = 1; + NX4makedata(fid, newname, dataType, rank, iDim); + NX4opendata(fid, newname); + NX4putattr(fid, "NAPIlink", tags, 2, attType); + NX4closedata(fid); + dataID = SDreftoindex(pFile->iSID, sLink->iRef); + dataID = SDselect(pFile->iSID, dataID); + SDsetattr(dataID, name, type, length, sLink->targetPath); + SDendaccess(dataID); + } else { + NX4makegroup(fid, newname, "NAPIlink"); + NX4opengroup(fid, newname, "NAPIlink"); + NX4putattr(fid, "NAPIlink", tags, 2, attType); + NX4closegroup(fid); + dataID = Vattach(pFile->iVID, sLink->iRef, "w"); + Vsetattr(dataID, (char *) name, type, (int32) length, + sLink->targetPath); + Vdetach(dataID); + } + return NX_OK; +} + + /*----------------------------------------------------------------------*/ + +NXstatus NX4printlink(NXhandle fid, NXlink * sLink) +{ + pNexusFile pFile; + pFile = NXIassert(fid); + printf("HDF4 link: iTag = %ld, iRef = %ld, target=\"%s\"\n", sLink->iTag, + sLink->iRef, sLink->targetPath); + return NX_OK; +} + + /*----------------------------------------------------------------------*/ + +NXstatus NX4flush(NXhandle * pHandle) +{ + char *pFileName, *pCopy = NULL; + int access, dummy, iRet, i, iStack; + pNexusFile pFile = NULL; + NXaccess ac; + int *iRefs = NULL; + + pFile = NXIassert(*pHandle); + + /* + The HDF4-API does not support a flush. We help ourselves with + inquiring the name and access type of the file, closing it and + opening it again. This is also the reason why this needs a pointer + to the handle structure as the handle changes. The other thing we + do is to store the refs of all open vGroups in a temporary array + in order to recover the position in the vGroup hierarchy before the + flush. + */ + iRet = Hfidinquire(pFile->iVID, &pFileName, &access, &dummy); + if (iRet < 0) { + NXIReportError(NXpData, + "ERROR: Failed to inquire file name for HDF file"); + return NX_ERROR; + } + if (pFile->iAccess[0] == 'r') { + ac = NXACC_READ; + } else if (pFile->iAccess[0] == 'w') { + ac = NXACC_RDWR; + } else { + NXIReportError(NXpData, + "ERROR: NX4flush failed to determine file access mode"); + return NX_ERROR; + } + pCopy = (char *) malloc((strlen(pFileName) + 10) * sizeof(char)); + if (!pCopy) { + NXIReportError(NXpData, + "ERROR: Failed to allocate data for filename copy"); + return NX_ERROR; + } + memset(pCopy, 0, strlen(pFileName) + 10); + strcpy(pCopy, pFileName); + + /* get refs for recovering vGroup position */ + iStack = 0; + if (pFile->iStackPtr > 0) { + iStack = pFile->iStackPtr + 1; + iRefs = (int *) malloc(iStack * sizeof(int)); + if (!iRefs) { + NXIReportError(NXpData, + "ERROR: Failed to allocate data for hierarchy copy"); + return NX_ERROR; + } + for (i = 0; i < iStack; i++) { + iRefs[i] = pFile->iStack[i].iVref; } } + iRet = NX4close(pHandle); + if (iRet != NX_OK) { + return iRet; + } + + iRet = NX4open(pCopy, ac, pHandle); + free(pCopy); + + /* return to position in vGroup hierarchy */ + pFile = NXIassert(*pHandle); + if (iStack > 0) { + pFile->iStackPtr = iStack - 1; + for (i = 0; i < iStack; i++) { + pFile->iStack[i].iVref = iRefs[i]; + } + free(iRefs); + pFile->iCurrentVG = Vattach(pFile->iVID, + pFile->iStack[pFile->iStackPtr].iVref, + pFile->iAccess); + } + + return iRet; +} + /*-------------------------------------------------------------------------*/ - - NXstatus NX4initattrdir (NXhandle fid) - { - pNexusFile pFile; - int iRet; - - pFile = NXIassert (fid); - NXIKillAttDir (fid); - iRet = NXIInitAttDir (pFile); - if (iRet == NX_ERROR) - return NX_ERROR; - return NX_OK; - } - - - /*-------------------------------------------------------------------------*/ - - - NXstatus NX4initgroupdir (NXhandle fid) - { - pNexusFile pFile; - int iRet; - - pFile = NXIassert (fid); - NXIKillDir (fid); - iRet = NXIInitDir (pFile); + +NXstatus NX4getnextentry(NXhandle fid, NXname name, NXname nxclass, + int *datatype) +{ + pNexusFile pFile; + int iRet, iStackPtr, iCurDir; + int32 iTemp, iD1, iD2, iA; + int32 iDim[MAX_VAR_DIMS]; + + pFile = NXIassert(fid); + + iStackPtr = pFile->iStackPtr; + iCurDir = pFile->iStack[pFile->iStackPtr].iCurDir; + + /* first case to check for: no directory entry */ + if (pFile->iStack[pFile->iStackPtr].iRefDir == NULL) { + iRet = NXIInitDir(pFile); if (iRet < 0) { - NXIReportError (NXpData,"NX_ERROR: no memory to store directory info"); + NXIReportError(NXpData, "ERROR: no memory to store directory info"); return NX_EOD; } + } + + /* Next case: end of directory */ + if (iCurDir >= pFile->iStack[pFile->iStackPtr].iNDir) { + NXIKillDir(pFile); + return NX_EOD; + } + + /* Next case: we have data! supply it and increment counter */ + if (pFile->iCurrentVG == 0) { /* root level */ + iTemp = Vattach(pFile->iVID, + pFile->iStack[iStackPtr].iRefDir[iCurDir], "r"); + if (iTemp < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot attach to Vgroup"); + return NX_ERROR; + } + Vgetname(iTemp, name); + Vdetach(iTemp); + findNapiClass(pFile, pFile->iStack[pFile->iStackPtr].iRefDir[iCurDir], + nxclass); + *datatype = DFTAG_VG; + pFile->iStack[pFile->iStackPtr].iCurDir++; + return NX_OK; + } else { /* in Vgroup */ + if (pFile->iStack[iStackPtr].iTagDir[iCurDir] == DFTAG_VG) { /* Vgroup */ + iTemp = Vattach(pFile->iVID, + pFile->iStack[iStackPtr].iRefDir[iCurDir], "r"); + if (iTemp < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot attach to Vgroup"); + return NX_ERROR; + } + Vgetname(iTemp, name); + Vdetach(iTemp); + findNapiClass(pFile, + pFile->iStack[pFile->iStackPtr].iRefDir[iCurDir], + nxclass); + *datatype = DFTAG_VG; + pFile->iStack[pFile->iStackPtr].iCurDir++; + Vdetach(iTemp); + return NX_OK; + /* we are now writing using DFTAG_NDG, but need others for backward compatability */ + } else if ((pFile->iStack[iStackPtr].iTagDir[iCurDir] == DFTAG_SDG) || + (pFile->iStack[iStackPtr].iTagDir[iCurDir] == DFTAG_NDG) || + (pFile->iStack[iStackPtr].iTagDir[iCurDir] == DFTAG_SDS)) { + iTemp = SDreftoindex(pFile->iSID, + pFile->iStack[iStackPtr].iRefDir[iCurDir]); + iTemp = SDselect(pFile->iSID, iTemp); + SDgetinfo(iTemp, name, &iA, iDim, &iD1, &iD2); + strcpy(nxclass, "SDS"); + *datatype = iD1; + SDendaccess(iTemp); + pFile->iStack[pFile->iStackPtr].iCurDir++; + return NX_OK; + } else { /* unidentified */ + strcpy(name, "UNKNOWN"); + strcpy(nxclass, "UNKNOWN"); + *datatype = pFile->iStack[iStackPtr].iTagDir[iCurDir]; + pFile->iStack[pFile->iStackPtr].iCurDir++; + return NX_OK; + } + } + return NX_ERROR; /* not reached */ +} + + + /*-------------------------------------------------------------------------*/ + + +NXstatus NX4getdata(NXhandle fid, void *data) +{ + pNexusFile pFile; + int32 iStart[MAX_VAR_DIMS], iSize[MAX_VAR_DIMS]; + NXname pBuffer; + int32 iRank, iAtt, iType; + + pFile = NXIassert(fid); + + /* check if there is an SDS open */ + if (pFile->iCurrentSDS == 0) { + NXIReportError(NXpData, "ERROR: no SDS open"); + return NX_ERROR; + } + /* first read dimension information */ + memset(iStart, 0, MAX_VAR_DIMS * sizeof(int32)); + SDgetinfo(pFile->iCurrentSDS, pBuffer, &iRank, iSize, &iType, &iAtt); + /* actually read */ + SDreaddata(pFile->iCurrentSDS, iStart, NULL, iSize, data); + return NX_OK; +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NX4getinfo(NXhandle fid, int *rank, int dimension[], int *iType) +{ + pNexusFile pFile; + NXname pBuffer; + int32 iAtt, myDim[MAX_VAR_DIMS], i, iRank, mType; + + pFile = NXIassert(fid); + + /* check if there is an SDS open */ + if (pFile->iCurrentSDS == 0) { + NXIReportError(NXpData, "ERROR: no SDS open"); + return NX_ERROR; + } + /* read information */ + SDgetinfo(pFile->iCurrentSDS, pBuffer, &iRank, myDim, &mType, &iAtt); + + /* conversion to proper ints for the platform */ + *iType = (int) mType; + *rank = (int) iRank; + for (i = 0; i < iRank; i++) { + dimension[i] = (int) myDim[i]; + } + return NX_OK; +} + + + /*-------------------------------------------------------------------------*/ + + +NXstatus NX4getslab(NXhandle fid, void *data, int iStart[], int iSize[]) +{ + pNexusFile pFile; + int32 myStart[MAX_VAR_DIMS], mySize[MAX_VAR_DIMS]; + int32 i, iRank, iType, iAtt; + NXname pBuffer; + + pFile = NXIassert(fid); + + /* check if there is an SDS open */ + if (pFile->iCurrentSDS == 0) { + NXIReportError(NXpData, "ERROR: no SDS open"); + return NX_ERROR; + } + + /* if an int is not 32-bit we have to cast them properly in order + to kill a bug. + */ + if (sizeof(int) != 4) { + SDgetinfo(pFile->iCurrentSDS, pBuffer, &iRank, myStart, &iType, &iAtt); + for (i = 0; i < iRank; i++) { + myStart[i] = (int32) iStart[i]; + mySize[i] = (int32) iSize[i]; + } + /* finally read */ + SDreaddata(pFile->iCurrentSDS, myStart, NULL, mySize, data); + return NX_OK; + } else { + /* read directly */ + SDreaddata(pFile->iCurrentSDS, (int32 *) iStart, NULL, + (int32 *) iSize, data); return NX_OK; } - +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NX4getnextattr(NXhandle fileid, NXname pName, + int *iLength, int *iType) +{ + pNexusFile pFile; + int iRet; + int32 iPType, iCount, count; + + pFile = NXIassert(fileid); + + /* first check if we have to start a new attribute search */ + if (pFile->iAtt.iNDir == 0) { + iRet = NXIInitAttDir(pFile); + if (iRet == NX_ERROR) { + return NX_ERROR; + } + } + /* are we done ? */ + if (pFile->iAtt.iCurDir >= pFile->iAtt.iNDir) { + NXIKillAttDir(pFile); + return NX_EOD; + } + /* well, there must be data to copy */ + if (pFile->iCurrentSDS == 0) { + if (pFile->iCurrentVG == 0) { + /* global attribute */ + iRet = SDattrinfo(pFile->iSID, pFile->iAtt.iCurDir, + pName, &iPType, &iCount); + } else { + /* group attribute */ + iRet = Vattrinfo(pFile->iCurrentVG, pFile->iAtt.iCurDir, + pName, &iPType, &iCount, &count); + } + } else { + iRet = SDattrinfo(pFile->iCurrentSDS, pFile->iAtt.iCurDir, + pName, &iPType, &iCount); + } + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot read attribute info"); + return NX_ERROR; + } + *iLength = iCount; + *iType = iPType; + pFile->iAtt.iCurDir++; + return NX_OK; +} + + + /*-------------------------------------------------------------------------*/ + + +NXstatus NX4getattr(NXhandle fid, char *name, void *data, int *datalen, + int *iType) +{ + pNexusFile pFile; + int32 iNew, iType32, count; + void *pData = NULL; + int32 iLen, iRet; + int type; + char pBuffer[256]; + NXname pNam; + + type = *iType; + if (type == NX_CHAR) { + type = DFNT_CHAR8; + } else if (type == NX_INT8) { + type = DFNT_INT8; + } else if (type == NX_UINT8) { + type = DFNT_UINT8; + } else if (type == NX_INT16) { + type = DFNT_INT16; + } else if (type == NX_UINT16) { + type = DFNT_UINT16; + } else if (type == NX_INT32) { + type = DFNT_INT32; + } else if (type == NX_UINT32) { + type = DFNT_UINT32; + } else if (type == NX_FLOAT32) { + type = DFNT_FLOAT32; + } else if (type == NX_FLOAT64) { + type = DFNT_FLOAT64; + } + *datalen = (*datalen) * DFKNTsize(type); + pFile = NXIassert(fid); + + /* find attribute */ + if (pFile->iCurrentSDS != 0) { + /* SDS attribute */ + iNew = SDfindattr(pFile->iCurrentSDS, name); + } else { + if (pFile->iCurrentVG == 0) { + /* global attribute */ + iNew = SDfindattr(pFile->iSID, name); + } else { + /* group attribute */ + iNew = Vfindattr(pFile->iCurrentVG, name); + } + } + if (iNew < 0) { + sprintf(pBuffer, "ERROR: attribute %s not found", name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + /* get more info, allocate temporary data space */ + iType32 = (int32) type; + if (pFile->iCurrentSDS != 0) { + iRet = SDattrinfo(pFile->iCurrentSDS, iNew, pNam, &iType32, &iLen); + } else { + if (pFile->iCurrentVG == 0) { + iRet = SDattrinfo(pFile->iSID, iNew, pNam, &iType32, &iLen); + } else { + iRet = Vattrinfo(pFile->iCurrentVG, iNew, pNam, &iType32, &count, + &iLen); + } + } + if (iRet < 0) { + sprintf(pBuffer, "ERROR: HDF could not read attribute info"); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + *iType = (int) iType32; + iLen = iLen * DFKNTsize(*iType); + pData = (void *) malloc(iLen); + if (!pData) { + NXIReportError(NXpData, "ERROR: allocating memory in NXgetattr"); + return NX_ERROR; + } + memset(pData, 0, iLen); + + /* finally read the data */ + if (pFile->iCurrentSDS != 0) { + iRet = SDreadattr(pFile->iCurrentSDS, iNew, pData); + } else { + if (pFile->iCurrentVG == 0) { + iRet = SDreadattr(pFile->iSID, iNew, pData); + } else { + iRet = Vgetattr(pFile->iCurrentVG, iNew, pData); + } + } + if (iRet < 0) { + sprintf(pBuffer, "ERROR: HDF could not read attribute data"); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + /* copy data to caller */ + memset(data, 0, *datalen); + if ((*datalen <= iLen) && + (*iType == DFNT_UINT8 || *iType == DFNT_CHAR8 + || *iType == DFNT_UCHAR8)) { + iLen = *datalen - 1; + } + memcpy(data, pData, iLen); + *datalen = iLen / DFKNTsize(*iType); + free(pData); + return NX_OK; +} + + /*-------------------------------------------------------------------------*/ + + +NXstatus NX4getattrinfo(NXhandle fid, int *iN) +{ + pNexusFile pFile; + int iRet; + int32 iData, iAtt, iRank, iType; + int32 iDim[MAX_VAR_DIMS]; + NXname pNam; + + pFile = NXIassert(fid); + if (pFile->iCurrentSDS != 0) { /* SDS level */ + iRet = SDgetinfo(pFile->iCurrentSDS, pNam, &iRank, iDim, &iType, + &iAtt); + } else { + if (pFile->iCurrentVG == 0) { + /* global level */ + iRet = SDfileinfo(pFile->iSID, &iData, &iAtt); + } else { + iRet = Vnattrs(pFile->iCurrentVG); + iAtt = iRet; + } + } + if (iRet < 0) { + NXIReportError(NXpData, "NX_ERROR: HDF cannot read attribute numbers"); + *iN = 0; + return NX_ERROR; + } + *iN = iAtt; + return NX_OK; +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NX4getgroupID(NXhandle fileid, NXlink * sRes) +{ + pNexusFile pFile; + + pFile = NXIassert(fileid); + + if (pFile->iCurrentVG == 0) { + sRes->iTag = NX_ERROR; + return NX_ERROR; + } else { + sRes->iTag = DFTAG_VG; + sRes->iRef = VQueryref(pFile->iCurrentVG); + NXIbuildPath(pFile, sRes->targetPath, 1024); + return NX_OK; + } + /* not reached */ + sRes->iTag = NX_ERROR; + return NX_ERROR; +} + + /*-------------------------------------------------------------------------*/ + +NXstatus +NX4getgroupinfo(NXhandle fid, int *iN, NXname pName, NXname pClass) +{ + pNexusFile pFile; + + pFile = NXIassert(fid); + /* check if there is a group open */ + if (pFile->iCurrentVG == 0) { + *iN = Vlone(pFile->iVID, NULL, 0); + strcpy(pName, "root"); + strcpy(pClass, "NXroot"); + } else { + *iN = Vntagrefs(pFile->iCurrentVG); + Vgetname(pFile->iCurrentVG, pName); + Vgetclass(pFile->iCurrentVG, pClass); + } + return NX_OK; +} + + /* ------------------------------------------------------------------- */ + +NXstatus NX4sameID(NXhandle fileid, NXlink * pFirstID, NXlink * pSecondID) +{ + pNexusFile pFile; + + pFile = NXIassert(fileid); + if ((pFirstID->iTag == pSecondID->iTag) & (pFirstID->iRef == + pSecondID->iRef)) { + return NX_OK; + } else { + return NX_ERROR; + } +} + + /*-------------------------------------------------------------------------*/ + + +NXstatus NX4initattrdir(NXhandle fid) +{ + pNexusFile pFile; + int iRet; + + pFile = NXIassert(fid); + NXIKillAttDir(fid); + iRet = NXIInitAttDir(pFile); + if (iRet == NX_ERROR) + return NX_ERROR; + return NX_OK; +} + + + /*-------------------------------------------------------------------------*/ + + +NXstatus NX4initgroupdir(NXhandle fid) +{ + pNexusFile pFile; + int iRet; + + pFile = NXIassert(fid); + NXIKillDir(fid); + iRet = NXIInitDir(pFile); + if (iRet < 0) { + NXIReportError(NXpData, "NX_ERROR: no memory to store directory info"); + return NX_EOD; + } + return NX_OK; +} + /*--------------------------------------------------------------------*/ void NX4assignFunctions(pNexusFunction fHandle) { - fHandle->nxclose=NX4close; - fHandle->nxflush=NX4flush; - fHandle->nxmakegroup=NX4makegroup; - fHandle->nxopengroup=NX4opengroup; - fHandle->nxclosegroup=NX4closegroup; - fHandle->nxmakedata=NX4makedata; - fHandle->nxcompmakedata=NX4compmakedata; - fHandle->nxcompress=NX4compress; - fHandle->nxopendata=NX4opendata; - fHandle->nxclosedata=NX4closedata; - fHandle->nxputdata=NX4putdata; - fHandle->nxputattr=NX4putattr; - fHandle->nxputslab=NX4putslab; - fHandle->nxgetdataID=NX4getdataID; - fHandle->nxmakelink=NX4makelink; - fHandle->nxmakenamedlink=NX4makenamedlink; - fHandle->nxgetdata=NX4getdata; - fHandle->nxgetinfo=NX4getinfo; - fHandle->nxgetnextentry=NX4getnextentry; - fHandle->nxgetslab=NX4getslab; - fHandle->nxgetnextattr=NX4getnextattr; - fHandle->nxgetattr=NX4getattr; - fHandle->nxgetattrinfo=NX4getattrinfo; - fHandle->nxgetgroupID=NX4getgroupID; - fHandle->nxgetgroupinfo=NX4getgroupinfo; - fHandle->nxsameID=NX4sameID; - fHandle->nxinitgroupdir=NX4initgroupdir; - fHandle->nxinitattrdir=NX4initattrdir; - fHandle->nxprintlink=NX4printlink; + fHandle->nxclose = NX4close; + fHandle->nxflush = NX4flush; + fHandle->nxmakegroup = NX4makegroup; + fHandle->nxopengroup = NX4opengroup; + fHandle->nxclosegroup = NX4closegroup; + fHandle->nxmakedata = NX4makedata; + fHandle->nxcompmakedata = NX4compmakedata; + fHandle->nxcompress = NX4compress; + fHandle->nxopendata = NX4opendata; + fHandle->nxclosedata = NX4closedata; + fHandle->nxputdata = NX4putdata; + fHandle->nxputattr = NX4putattr; + fHandle->nxputslab = NX4putslab; + fHandle->nxgetdataID = NX4getdataID; + fHandle->nxmakelink = NX4makelink; + fHandle->nxmakenamedlink = NX4makenamedlink; + fHandle->nxgetdata = NX4getdata; + fHandle->nxgetinfo = NX4getinfo; + fHandle->nxgetnextentry = NX4getnextentry; + fHandle->nxgetslab = NX4getslab; + fHandle->nxgetnextattr = NX4getnextattr; + fHandle->nxgetattr = NX4getattr; + fHandle->nxgetattrinfo = NX4getattrinfo; + fHandle->nxgetgroupID = NX4getgroupID; + fHandle->nxgetgroupinfo = NX4getgroupinfo; + fHandle->nxsameID = NX4sameID; + fHandle->nxinitgroupdir = NX4initgroupdir; + fHandle->nxinitattrdir = NX4initattrdir; + fHandle->nxprintlink = NX4printlink; } diff --git a/napi4.h b/napi4.h index f07cce9a..3be8aac4 100644 --- a/napi4.h +++ b/napi4.h @@ -7,42 +7,54 @@ * HDF4 interface */ -extern NXstatus NX4open(CONSTCHAR *filename, NXaccess access_method, NXhandle* pHandle); -extern NXstatus NX4close(NXhandle* pHandle); -extern NXstatus NX4flush(NXhandle* pHandle); - -extern NXstatus NX4makegroup (NXhandle handle, CONSTCHAR* Vgroup, CONSTCHAR* NXclass); -extern NXstatus NX4opengroup (NXhandle handle, CONSTCHAR* Vgroup, CONSTCHAR* NXclass); -extern NXstatus NX4closegroup(NXhandle handle); - -extern NXstatus NX4makedata (NXhandle handle, CONSTCHAR* label, int datatype, int rank, int dim[]); -extern NXstatus NX4compmakedata (NXhandle handle, CONSTCHAR* label, int datatype, int rank, int dim[], int comp_typ, int bufsize[]); -extern NXstatus NX4compress (NXhandle handle, int compr_type); -extern NXstatus NX4opendata (NXhandle handle, CONSTCHAR* label); +extern NXstatus NX4open(CONSTCHAR * filename, NXaccess access_method, + NXhandle * pHandle); +extern NXstatus NX4close(NXhandle * pHandle); +extern NXstatus NX4flush(NXhandle * pHandle); -extern NXstatus NX4closedata(NXhandle handle); - -extern NXstatus NX4getdata(NXhandle handle, void* data); -extern NXstatus NX4getslab(NXhandle handle, void* data, int start[], int size[]); -extern NXstatus NX4getattr(NXhandle handle, char* name, void* data, int* iDataLen, int* iType); - -extern NXstatus NX4putdata(NXhandle handle, void* data); -extern NXstatus NX4putslab(NXhandle handle, void* data, int start[], int size[]); -extern NXstatus NX4putattr(NXhandle handle, CONSTCHAR* name, void* data, int iDataLen, int iType); - -extern NXstatus NX4getinfo(NXhandle handle, int* rank, int dimension[], int* datatype); -extern NXstatus NX4getgroupinfo(NXhandle handle, int* no_items, NXname name, NXname nxclass); -extern NXstatus NX4initgroupdir(NXhandle handle); -extern NXstatus NX4getnextentry(NXhandle handle, NXname name, NXname nxclass, int* datatype); -extern NXstatus NX4getattrinfo(NXhandle handle, int* no_items); -extern NXstatus NX4initattrdir(NXhandle handle); -extern NXstatus NX4getnextattr(NXhandle handle, NXname pName, int *iLength, int *iType); - -extern NXstatus NX4getgroupID(NXhandle handle, NXlink* pLink); -extern NXstatus NX4getdataID(NXhandle handle, NXlink* pLink); -extern NXstatus NX4makelink(NXhandle handle, NXlink* pLink); -extern NXstatus NX4printlink(NXhandle handle, NXlink* pLink); +extern NXstatus NX4makegroup(NXhandle handle, CONSTCHAR * Vgroup, + CONSTCHAR * NXclass); +extern NXstatus NX4opengroup(NXhandle handle, CONSTCHAR * Vgroup, + CONSTCHAR * NXclass); +extern NXstatus NX4closegroup(NXhandle handle); + +extern NXstatus NX4makedata(NXhandle handle, CONSTCHAR * label, + int datatype, int rank, int dim[]); +extern NXstatus NX4compmakedata(NXhandle handle, CONSTCHAR * label, + int datatype, int rank, int dim[], + int comp_typ, int bufsize[]); +extern NXstatus NX4compress(NXhandle handle, int compr_type); +extern NXstatus NX4opendata(NXhandle handle, CONSTCHAR * label); + +extern NXstatus NX4closedata(NXhandle handle); + +extern NXstatus NX4getdata(NXhandle handle, void *data); +extern NXstatus NX4getslab(NXhandle handle, void *data, int start[], + int size[]); +extern NXstatus NX4getattr(NXhandle handle, char *name, void *data, + int *iDataLen, int *iType); + +extern NXstatus NX4putdata(NXhandle handle, void *data); +extern NXstatus NX4putslab(NXhandle handle, void *data, int start[], + int size[]); +extern NXstatus NX4putattr(NXhandle handle, CONSTCHAR * name, void *data, + int iDataLen, int iType); + +extern NXstatus NX4getinfo(NXhandle handle, int *rank, int dimension[], + int *datatype); +extern NXstatus NX4getgroupinfo(NXhandle handle, int *no_items, + NXname name, NXname nxclass); +extern NXstatus NX4initgroupdir(NXhandle handle); +extern NXstatus NX4getnextentry(NXhandle handle, NXname name, + NXname nxclass, int *datatype); +extern NXstatus NX4getattrinfo(NXhandle handle, int *no_items); +extern NXstatus NX4initattrdir(NXhandle handle); +extern NXstatus NX4getnextattr(NXhandle handle, NXname pName, int *iLength, + int *iType); + +extern NXstatus NX4getgroupID(NXhandle handle, NXlink * pLink); +extern NXstatus NX4getdataID(NXhandle handle, NXlink * pLink); +extern NXstatus NX4makelink(NXhandle handle, NXlink * pLink); +extern NXstatus NX4printlink(NXhandle handle, NXlink * pLink); void NX4assignFunctions(pNexusFunction fHandle); - - diff --git a/napi5.c b/napi5.c index 939b9972..ad745414 100644 --- a/napi5.c +++ b/napi5.c @@ -30,102 +30,106 @@ #include "napi.h" #include "napi5.h" -#define NX_UNKNOWN_GROUP "" /* for when no NX_class attr */ +#define NX_UNKNOWN_GROUP "" /* for when no NX_class attr */ -extern void *NXpData; +extern void *NXpData; - typedef struct __NexusFile5 { - struct iStack5 { - char irefn[1024]; - int iVref; - int iCurrentIDX; - } iStack5[NXMAXSTACK]; - struct iStack5 iAtt5; - int iFID; - int iCurrentG; - int iCurrentD; - int iCurrentS; - int iCurrentT; - int iCurrentA; - int iNX; - int iNXID; - int iStackPtr; - char *iCurrentLGG; - char *iCurrentLD; - char name_ref[1024]; - char name_tmp[1024]; - char iAccess[2]; - } NexusFile5, *pNexusFile5; +typedef struct __NexusFile5 { + struct iStack5 { + char irefn[1024]; + int iVref; + int iCurrentIDX; + } iStack5[NXMAXSTACK]; + struct iStack5 iAtt5; + int iFID; + int iCurrentG; + int iCurrentD; + int iCurrentS; + int iCurrentT; + int iCurrentA; + int iNX; + int iNXID; + int iStackPtr; + char *iCurrentLGG; + char *iCurrentLD; + char name_ref[1024]; + char name_tmp[1024]; + char iAccess[2]; +} NexusFile5, *pNexusFile5; /* forward declaration of NX5closegroup in order to get rid of a nasty warning */ -NXstatus NX5closegroup (NXhandle fid); +NXstatus NX5closegroup(NXhandle fid); /*-------------------------------------------------------------------*/ -static void ignoreError(void *data, char *text){ +static void ignoreError(void *data, char *text) +{ } + /*--------------------------------------------------------------------*/ - static pNexusFile5 NXI5assert(NXhandle fid) - { - pNexusFile5 pRes; - - assert(fid != NULL); - pRes = (pNexusFile5)fid; - assert(pRes->iNXID == NX5SIGNATURE); - return pRes; - } - +static pNexusFile5 NXI5assert(NXhandle fid) +{ + pNexusFile5 pRes; + + assert(fid != NULL); + pRes = (pNexusFile5) fid; + assert(pRes->iNXID == NX5SIGNATURE); + return pRes; +} + /*--------------------------------------------------------------------*/ - static void NXI5KillDir (pNexusFile5 self) - { - self->iStack5[self->iStackPtr].iCurrentIDX = 0; - } - +static void NXI5KillDir(pNexusFile5 self) +{ + self->iStack5[self->iStackPtr].iCurrentIDX = 0; +} + /*--------------------------------------------------------------------*/ - static void NXI5KillAttDir (pNexusFile5 self) - { - self->iAtt5.iCurrentIDX = 0; - } +static void NXI5KillAttDir(pNexusFile5 self) +{ + self->iAtt5.iCurrentIDX = 0; +} + /*---------------------------------------------------------------------*/ -static void buildCurrentPath(pNexusFile5 self, char *pathBuffer, - int pathBufferLen){ +static void buildCurrentPath(pNexusFile5 self, char *pathBuffer, + int pathBufferLen) +{ int length; - memset(pathBuffer,0,pathBufferLen); - if(self->iCurrentG != 0) { - strcpy(pathBuffer,"/"); - if(strlen(self->name_ref) + 1 < pathBufferLen){ + memset(pathBuffer, 0, pathBufferLen); + if (self->iCurrentG != 0) { + strcpy(pathBuffer, "/"); + if (strlen(self->name_ref) + 1 < pathBufferLen) { strcat(pathBuffer, self->name_ref); } } - if(self->iCurrentD != 0){ - strcat(pathBuffer,"/"); - if(strlen(self->iCurrentLD) + strlen(pathBuffer) < pathBufferLen){ - strcat(pathBuffer,self->iCurrentLD); + if (self->iCurrentD != 0) { + strcat(pathBuffer, "/"); + if (strlen(self->iCurrentLD) + strlen(pathBuffer) < pathBufferLen) { + strcat(pathBuffer, self->iCurrentLD); } } } + /* ---------------------------------------------------------------------- - - Definition of NeXus API - ---------------------------------------------------------------------*/ + Definition of NeXus API - NXstatus NX5open(CONSTCHAR *filename, NXaccess am, - NXhandle* pHandle) - { - hid_t attr1,aid1, aid2, iVID; + --------------------------------------------------------------------- */ + +NXstatus NX5open(CONSTCHAR * filename, NXaccess am, NXhandle * pHandle) +{ + hid_t attr1, aid1, aid2, iVID; pNexusFile5 pNew = NULL; char pBuffer[512]; char *time_buffer = NULL; char version_nr[10]; int iRet; - unsigned int vers_major, vers_minor, vers_release, am1 ; - hid_t fapl = -1; + unsigned int vers_major, vers_minor, vers_release, am1; + hid_t fapl = -1; int mdc_nelmts; #ifdef H5_WANT_H5_V1_4_COMPAT int rdcc_nelmts; @@ -135,1198 +139,1138 @@ static void buildCurrentPath(pNexusFile5 self, char *pathBuffer, size_t rdcc_nbytes; double rdcc_w0; - /* turn off the automatic HDF error handling */ - H5Eset_auto(NULL,NULL); + /* turn off the automatic HDF error handling */ + H5Eset_auto(NULL, NULL); #ifdef USE_FTIME - struct timeb timeb_struct; -#endif + struct timeb timeb_struct; +#endif - *pHandle = NULL; + *pHandle = NULL; - pNew = (pNexusFile5) malloc (sizeof (NexusFile5)); - if (!pNew) { - NXIReportError (NXpData,"ERROR: no memory to create File datastructure"); - return NX_ERROR; - } - memset (pNew, 0, sizeof (NexusFile5)); + pNew = (pNexusFile5) malloc(sizeof(NexusFile5)); + if (!pNew) { + NXIReportError(NXpData, + "ERROR: no memory to create File datastructure"); + return NX_ERROR; + } + memset(pNew, 0, sizeof(NexusFile5)); - /* start HDF5 interface */ - if (am == NXACC_CREATE5) { - fapl = H5Pcreate(H5P_FILE_ACCESS); - iRet=H5Pget_cache(fapl,&mdc_nelmts,&rdcc_nelmts,&rdcc_nbytes,&rdcc_w0); - rdcc_nbytes=(size_t)nx_cacheSize; - iRet = H5Pset_cache(fapl,mdc_nelmts,rdcc_nelmts,rdcc_nbytes,rdcc_w0); - /* - setting the close degree is absolutely necessary in HDF5 - versions > 1.6. If you use a lessere version and the compiler - complains, comment it out but keep this in mind. - */ - H5Pset_fclose_degree(fapl,H5F_CLOSE_STRONG); - am1 = H5F_ACC_TRUNC; - pNew->iFID = H5Fcreate (filename, am1, H5P_DEFAULT, fapl); + /* start HDF5 interface */ + if (am == NXACC_CREATE5) { + fapl = H5Pcreate(H5P_FILE_ACCESS); + iRet = + H5Pget_cache(fapl, &mdc_nelmts, &rdcc_nelmts, &rdcc_nbytes, + &rdcc_w0); + rdcc_nbytes = (size_t) nx_cacheSize; + iRet = + H5Pset_cache(fapl, mdc_nelmts, rdcc_nelmts, rdcc_nbytes, rdcc_w0); + /* + setting the close degree is absolutely necessary in HDF5 + versions > 1.6. If you use a lessere version and the compiler + complains, comment it out but keep this in mind. + */ + H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG); + am1 = H5F_ACC_TRUNC; + pNew->iFID = H5Fcreate(filename, am1, H5P_DEFAULT, fapl); + } else { + if (am == NXACC_READ) { + am1 = H5F_ACC_RDONLY; } else { - if (am == NXACC_READ) { - am1 = H5F_ACC_RDONLY; - } else { - am1 = H5F_ACC_RDWR; - } - fapl = H5Pcreate(H5P_FILE_ACCESS); - H5Pset_fclose_degree(fapl,H5F_CLOSE_STRONG); - pNew->iFID = H5Fopen (filename, am1, fapl); - } - if (pNew->iFID <= 0) { - sprintf (pBuffer, "ERROR: cannot open file: %s", filename); - NXIReportError (NXpData, pBuffer); - free (pNew); - return NX_ERROR; - } - if(fapl != -1) { - H5Pclose(fapl); + am1 = H5F_ACC_RDWR; } + fapl = H5Pcreate(H5P_FILE_ACCESS); + H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG); + pNew->iFID = H5Fopen(filename, am1, fapl); + } + if (pNew->iFID <= 0) { + sprintf(pBuffer, "ERROR: cannot open file: %s", filename); + NXIReportError(NXpData, pBuffer); + free(pNew); + return NX_ERROR; + } + if (fapl != -1) { + H5Pclose(fapl); + } /* * need to create global attributes file_name file_time NeXus_version * at some point for new files */ - if (am1 != H5F_ACC_RDONLY) - { - iVID=H5Gopen(pNew->iFID,"/"); - aid2 = H5Screate(H5S_SCALAR); - aid1 = H5Tcopy(H5T_C_S1); - H5Tset_size(aid1, strlen(NEXUS_VERSION)); - if (am1 == H5F_ACC_RDWR) - { - H5Adelete(iVID, "NeXus_version"); - } - attr1= H5Acreate(iVID, "NeXus_version", aid1, aid2, H5P_DEFAULT); - if (attr1<0) - { - NXIReportError (NXpData, - "ERROR: HDF failed to store NeXus_version attribute "); - return NX_ERROR; - } - if (H5Awrite(attr1, aid1,NEXUS_VERSION)<0) - { - NXIReportError (NXpData, - "ERROR: HDF failed to store NeXus_version attribute "); - return NX_ERROR; - } - /* Close attribute dataspace */ - iRet = H5Tclose(aid1); - iRet = H5Sclose(aid2); - /* Close attribute */ - iRet = H5Aclose(attr1); - H5Gclose(iVID); - } - if (am1 == H5F_ACC_TRUNC) - { - iVID=H5Gopen(pNew->iFID,"/"); - aid2=H5Screate(H5S_SCALAR); - aid1 = H5Tcopy(H5T_C_S1); - H5Tset_size(aid1, strlen(filename)); - attr1= H5Acreate(iVID, "file_name", aid1, aid2, H5P_DEFAULT); - if (attr1 < 0) - { - NXIReportError (NXpData, - "ERROR: HDF failed to store file_name attribute "); - return NX_ERROR; - } - if (H5Awrite(attr1, aid1, (char*)filename) < 0) - { - NXIReportError (NXpData, - "ERROR: HDF failed to store file_name attribute "); - return NX_ERROR; - } - iRet = H5Tclose(aid1); - iRet = H5Sclose(aid2); - iRet = H5Aclose(attr1); - /* ------- library version ------*/ - H5get_libversion(&vers_major, &vers_minor, &vers_release); - sprintf (version_nr, "%d.%d.%d", vers_major,vers_minor,vers_release); - aid2=H5Screate(H5S_SCALAR); - aid1 = H5Tcopy(H5T_C_S1); - H5Tset_size(aid1, strlen(version_nr)); - attr1= H5Acreate(iVID, "HDF5_Version", aid1, aid2, H5P_DEFAULT); - if (attr1 < 0) - { - NXIReportError (NXpData, - "ERROR: HDF failed to store file_name attribute "); - return NX_ERROR; - } - if (H5Awrite(attr1, aid1, (char*)version_nr) < 0) - { - NXIReportError (NXpData, - "ERROR: HDF failed to store file_name attribute "); - return NX_ERROR; - } - iRet = H5Tclose(aid1); - iRet = H5Sclose(aid2); - iRet = H5Aclose(attr1); - /*----------- file time */ - time_buffer = NXIformatNeXusTime(); - if(time_buffer != NULL){ - aid2=H5Screate(H5S_SCALAR); - aid1 = H5Tcopy(H5T_C_S1); - H5Tset_size(aid1, strlen(time_buffer)); - attr1=H5Acreate(iVID, "file_time", aid1, aid2, H5P_DEFAULT); - if (attr1 < 0) - { - NXIReportError (NXpData, - "ERROR: HDF failed to store file_time attribute "); - free(time_buffer); - return NX_ERROR; - } - if (H5Awrite(attr1, aid1, time_buffer) < 0) - { - NXIReportError (NXpData, - "ERROR: HDF failed to store file_time attribute "); - free(time_buffer); - return NX_ERROR; - } - /* Close attribute dataspace */ - iRet = H5Tclose(aid1); - iRet = H5Sclose(aid2); - /* Close attribute */ - iRet = H5Aclose(attr1); - free(time_buffer); - } - H5Gclose(iVID); - } - /* Set HDFgroup access mode */ - if (am1 == H5F_ACC_RDONLY) { - strcpy(pNew->iAccess,"r"); - } else { - strcpy(pNew->iAccess,"w"); - } - pNew->iNXID = NX5SIGNATURE; - pNew->iStack5[0].iVref = 0; /* root! */ - *pHandle = (NXhandle)pNew; - return NX_OK; - } - - /* ------------------------------------------------------------------------- */ - - NXstatus NX5close (NXhandle* fid) - { - pNexusFile5 pFile = NULL; - int iRet; - - pFile=NXI5assert(*fid); - - iRet=0; - /* - printf("HDF5 object count before close: %d\n", - H5Fget_obj_count(pFile->iFID,H5F_OBJ_ALL)); - */ - iRet = H5Fclose(pFile->iFID); - - /* - leave this here: it helps in debugging leakage problems - printf("HDF5 object count after close: %d\n", - H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_ALL)); - printf("HDF5 dataset count after close: %d\n", - H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_DATASET)); - printf("HDF5 group count after close: %d\n", - H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_GROUP)); - printf("HDF5 datatype count after close: %d\n", - H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_DATATYPE)); - printf("HDF5 attribute count after close: %d\n", - H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_ATTR)); - */ - - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot close HDF file"); - } - /* release memory */ - NXI5KillDir (pFile); - if(pFile->iCurrentLGG != NULL){ - free(pFile->iCurrentLGG); - } - if(pFile->iCurrentLD != NULL){ - free(pFile->iCurrentLD); - } - free (pFile); - *fid = NULL; - H5garbage_collect(); - return NX_OK; - } - - /*-----------------------------------------------------------------------*/ - - NXstatus NX5makegroup (NXhandle fid, CONSTCHAR *name, CONSTCHAR *nxclass) - { - pNexusFile5 pFile; - hid_t iRet, iVID; - hid_t attr1,aid1, aid2; - char pBuffer[1024] = ""; - - pFile = NXI5assert (fid); - /* create and configure the group */ - if (pFile->iCurrentG==0) - { - iRet = H5Gcreate(pFile->iFID,(const char*)name, 0); - snprintf(pBuffer,1023,"/%s",name); - } else - { - snprintf(pBuffer,1023,"/%s/%s",pFile->name_ref,name); - iRet = H5Gcreate(pFile->iFID,(const char*)pBuffer, 0); - } - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF could not create Group"); - return NX_ERROR; - } - iVID = iRet; - strncpy(pFile->name_ref,pBuffer,1023); + if (am1 != H5F_ACC_RDONLY) { + iVID = H5Gopen(pNew->iFID, "/"); aid2 = H5Screate(H5S_SCALAR); aid1 = H5Tcopy(H5T_C_S1); - H5Tset_size(aid1, strlen(nxclass)); - attr1= H5Acreate(iVID, "NX_class", aid1, aid2, H5P_DEFAULT); - if (attr1 < 0) - { - NXIReportError (NXpData, "ERROR: HDF failed to store class name!"); - return NX_ERROR; - } - if (H5Awrite(attr1, aid1, (char*)nxclass) < 0) - { - NXIReportError (NXpData, "ERROR: HDF failed to store class name!"); + H5Tset_size(aid1, strlen(NEXUS_VERSION)); + if (am1 == H5F_ACC_RDWR) { + H5Adelete(iVID, "NeXus_version"); + } + attr1 = H5Acreate(iVID, "NeXus_version", aid1, aid2, H5P_DEFAULT); + if (attr1 < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store NeXus_version attribute "); return NX_ERROR; + } + if (H5Awrite(attr1, aid1, NEXUS_VERSION) < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store NeXus_version attribute "); + return NX_ERROR; + } + /* Close attribute dataspace */ + iRet = H5Tclose(aid1); + iRet = H5Sclose(aid2); + /* Close attribute */ + iRet = H5Aclose(attr1); + H5Gclose(iVID); + } + if (am1 == H5F_ACC_TRUNC) { + iVID = H5Gopen(pNew->iFID, "/"); + aid2 = H5Screate(H5S_SCALAR); + aid1 = H5Tcopy(H5T_C_S1); + H5Tset_size(aid1, strlen(filename)); + attr1 = H5Acreate(iVID, "file_name", aid1, aid2, H5P_DEFAULT); + if (attr1 < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store file_name attribute "); + return NX_ERROR; + } + if (H5Awrite(attr1, aid1, (char *) filename) < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store file_name attribute "); + return NX_ERROR; + } + iRet = H5Tclose(aid1); + iRet = H5Sclose(aid2); + iRet = H5Aclose(attr1); + /* ------- library version ------ */ + H5get_libversion(&vers_major, &vers_minor, &vers_release); + sprintf(version_nr, "%d.%d.%d", vers_major, vers_minor, vers_release); + aid2 = H5Screate(H5S_SCALAR); + aid1 = H5Tcopy(H5T_C_S1); + H5Tset_size(aid1, strlen(version_nr)); + attr1 = H5Acreate(iVID, "HDF5_Version", aid1, aid2, H5P_DEFAULT); + if (attr1 < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store file_name attribute "); + return NX_ERROR; + } + if (H5Awrite(attr1, aid1, (char *) version_nr) < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store file_name attribute "); + return NX_ERROR; + } + iRet = H5Tclose(aid1); + iRet = H5Sclose(aid2); + iRet = H5Aclose(attr1); + /*----------- file time */ + time_buffer = NXIformatNeXusTime(); + if (time_buffer != NULL) { + aid2 = H5Screate(H5S_SCALAR); + aid1 = H5Tcopy(H5T_C_S1); + H5Tset_size(aid1, strlen(time_buffer)); + attr1 = H5Acreate(iVID, "file_time", aid1, aid2, H5P_DEFAULT); + if (attr1 < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store file_time attribute "); + free(time_buffer); + return NX_ERROR; } - /* close group */ - iRet=H5Sclose(aid2); - iRet=H5Tclose(aid1); - iRet=H5Aclose(attr1); - iRet=H5Gclose(iVID); - return NX_OK; - } - - /*------------------------------------------------------------------------*/ - - herr_t attr_check (hid_t loc_id, const char *member_name, void *opdata) - { - char attr_name[8+1]; /* need to leave space for \0 as well */ - - strcpy(attr_name,"NX_class"); - return strstr(member_name, attr_name) ? 1 : 0; - } - /*------------------------------------------------------------------------*/ - NXstatus NX5opengroup (NXhandle fid, CONSTCHAR *name, CONSTCHAR *nxclass) - { - - pNexusFile5 pFile; - hid_t iRet, attr1, atype; - char pBuffer[1024]; - char data[128]; - - pFile = NXI5assert (fid); - if (pFile->iCurrentG == 0) - { - strcpy(pBuffer,name); - } - else - { - sprintf(pBuffer,"%s/%s",pFile->name_tmp,name); + if (H5Awrite(attr1, aid1, time_buffer) < 0) { + NXIReportError(NXpData, + "ERROR: HDF failed to store file_time attribute "); + free(time_buffer); + return NX_ERROR; + } + /* Close attribute dataspace */ + iRet = H5Tclose(aid1); + iRet = H5Sclose(aid2); + /* Close attribute */ + iRet = H5Aclose(attr1); + free(time_buffer); } - iRet = H5Gopen (pFile->iFID,(const char *)pBuffer); + H5Gclose(iVID); + } + /* Set HDFgroup access mode */ + if (am1 == H5F_ACC_RDONLY) { + strcpy(pNew->iAccess, "r"); + } else { + strcpy(pNew->iAccess, "w"); + } + pNew->iNXID = NX5SIGNATURE; + pNew->iStack5[0].iVref = 0; /* root! */ + *pHandle = (NXhandle) pNew; + return NX_OK; +} + + /* ------------------------------------------------------------------------- */ + +NXstatus NX5close(NXhandle * fid) +{ + pNexusFile5 pFile = NULL; + int iRet; + + pFile = NXI5assert(*fid); + + iRet = 0; + /* + printf("HDF5 object count before close: %d\n", + H5Fget_obj_count(pFile->iFID,H5F_OBJ_ALL)); + */ + iRet = H5Fclose(pFile->iFID); + + /* + leave this here: it helps in debugging leakage problems + printf("HDF5 object count after close: %d\n", + H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_ALL)); + printf("HDF5 dataset count after close: %d\n", + H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_DATASET)); + printf("HDF5 group count after close: %d\n", + H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_GROUP)); + printf("HDF5 datatype count after close: %d\n", + H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_DATATYPE)); + printf("HDF5 attribute count after close: %d\n", + H5Fget_obj_count(H5F_OBJ_ALL,H5F_OBJ_ATTR)); + */ + + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot close HDF file"); + } + /* release memory */ + NXI5KillDir(pFile); + if (pFile->iCurrentLGG != NULL) { + free(pFile->iCurrentLGG); + } + if (pFile->iCurrentLD != NULL) { + free(pFile->iCurrentLD); + } + free(pFile); + *fid = NULL; + H5garbage_collect(); + return NX_OK; +} + + /*-----------------------------------------------------------------------*/ + +NXstatus NX5makegroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass) +{ + pNexusFile5 pFile; + hid_t iRet, iVID; + hid_t attr1, aid1, aid2; + char pBuffer[1024] = ""; + + pFile = NXI5assert(fid); + /* create and configure the group */ + if (pFile->iCurrentG == 0) { + iRet = H5Gcreate(pFile->iFID, (const char *) name, 0); + snprintf(pBuffer, 1023, "/%s", name); + } else { + snprintf(pBuffer, 1023, "/%s/%s", pFile->name_ref, name); + iRet = H5Gcreate(pFile->iFID, (const char *) pBuffer, 0); + } + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF could not create Group"); + return NX_ERROR; + } + iVID = iRet; + strncpy(pFile->name_ref, pBuffer, 1023); + aid2 = H5Screate(H5S_SCALAR); + aid1 = H5Tcopy(H5T_C_S1); + H5Tset_size(aid1, strlen(nxclass)); + attr1 = H5Acreate(iVID, "NX_class", aid1, aid2, H5P_DEFAULT); + if (attr1 < 0) { + NXIReportError(NXpData, "ERROR: HDF failed to store class name!"); + return NX_ERROR; + } + if (H5Awrite(attr1, aid1, (char *) nxclass) < 0) { + NXIReportError(NXpData, "ERROR: HDF failed to store class name!"); + return NX_ERROR; + } + /* close group */ + iRet = H5Sclose(aid2); + iRet = H5Tclose(aid1); + iRet = H5Aclose(attr1); + iRet = H5Gclose(iVID); + return NX_OK; +} + + /*------------------------------------------------------------------------*/ + +herr_t attr_check(hid_t loc_id, const char *member_name, void *opdata) +{ + char attr_name[8 + 1]; /* need to leave space for \0 as well */ + + strcpy(attr_name, "NX_class"); + return strstr(member_name, attr_name) ? 1 : 0; +} + + /*------------------------------------------------------------------------*/ +NXstatus NX5opengroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass) +{ + + pNexusFile5 pFile; + hid_t iRet, attr1, atype; + char pBuffer[1024]; + char data[128]; + + pFile = NXI5assert(fid); + if (pFile->iCurrentG == 0) { + strcpy(pBuffer, name); + } else { + sprintf(pBuffer, "%s/%s", pFile->name_tmp, name); + } + iRet = H5Gopen(pFile->iFID, (const char *) pBuffer); + if (iRet < 0) { + sprintf(pBuffer, "ERROR: Group %s does not exist!", pFile->name_tmp); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + pFile->iCurrentG = iRet; + strcpy(pFile->name_tmp, pBuffer); + strcpy(pFile->name_ref, pBuffer); + + if ((nxclass != NULL) && (strcmp(nxclass, NX_UNKNOWN_GROUP) != 0)) { + /* check group attribute */ + iRet = H5Aiterate(pFile->iCurrentG, NULL, attr_check, NULL); if (iRet < 0) { - sprintf (pBuffer, "ERROR: Group %s does not exist!", pFile->name_tmp); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; + NXIReportError(NXpData, "ERROR iterating through group!"); + return NX_ERROR; + } else if (iRet == 1) { + /* group attribute was found */ + } else { + /* no group attribute available */ + NXIReportError(NXpData, "No group attribute available"); + return NX_ERROR; } - pFile->iCurrentG = iRet; - strcpy(pFile->name_tmp,pBuffer); - strcpy(pFile->name_ref,pBuffer); - - if ((nxclass != NULL) && (strcmp(nxclass, NX_UNKNOWN_GROUP) != 0)) - { - /* check group attribute */ - iRet=H5Aiterate(pFile->iCurrentG,NULL,attr_check,NULL); - if (iRet < 0) { - NXIReportError (NXpData, "ERROR iterating through group!"); - return NX_ERROR; - } else if (iRet == 1) { - /* group attribute was found */ - } else { - /* no group attribute available */ - NXIReportError (NXpData, "No group attribute available"); - return NX_ERROR; - } - /* check contents of group attribute */ - attr1 = H5Aopen_name(pFile->iCurrentG, "NX_class"); - if (attr1 < 0) - { - NXIReportError (NXpData, "Error opening NX_class group attribute!"); - return NX_ERROR; - } - atype=H5Tcopy(H5T_C_S1); - H5Tset_size(atype,128); - iRet = H5Aread(attr1, atype, data); - if (strcmp(data, nxclass) == 0) { - /* test OK */ - } else { - NXIReportError (NXpData, "Group class is not identical!"); - iRet = H5Tclose(atype); - iRet = H5Aclose(attr1); - return NX_ERROR; - } - iRet = H5Tclose(atype); - iRet = H5Aclose(attr1); + /* check contents of group attribute */ + attr1 = H5Aopen_name(pFile->iCurrentG, "NX_class"); + if (attr1 < 0) { + NXIReportError(NXpData, "Error opening NX_class group attribute!"); + return NX_ERROR; } - - /* maintain stack */ - pFile->iStackPtr++; - pFile->iStack5[pFile->iStackPtr].iVref=pFile->iCurrentG; - strcpy(pFile->iStack5[pFile->iStackPtr].irefn,name); - pFile->iAtt5.iCurrentIDX=0; - pFile->iCurrentD = 0; - if(pFile->iCurrentLGG != NULL){ - free(pFile->iCurrentLGG); + atype = H5Tcopy(H5T_C_S1); + H5Tset_size(atype, 128); + iRet = H5Aread(attr1, atype, data); + if (strcmp(data, nxclass) == 0) { + /* test OK */ + } else { + NXIReportError(NXpData, "Group class is not identical!"); + iRet = H5Tclose(atype); + iRet = H5Aclose(attr1); + return NX_ERROR; } - pFile->iCurrentLGG = strdup(name); - NXI5KillDir (pFile); - return NX_OK; + iRet = H5Tclose(atype); + iRet = H5Aclose(attr1); } + /* maintain stack */ + pFile->iStackPtr++; + pFile->iStack5[pFile->iStackPtr].iVref = pFile->iCurrentG; + strcpy(pFile->iStack5[pFile->iStackPtr].irefn, name); + pFile->iAtt5.iCurrentIDX = 0; + pFile->iCurrentD = 0; + if (pFile->iCurrentLGG != NULL) { + free(pFile->iCurrentLGG); + } + pFile->iCurrentLGG = strdup(name); + NXI5KillDir(pFile); + return NX_OK; +} + /* ------------------------------------------------------------------- */ - NXstatus NX5closegroup (NXhandle fid) - { - pNexusFile5 pFile; - int i,ii; - char *uname = NULL; - char *u1name = NULL; - - pFile = NXI5assert (fid); - /* first catch the trivial case: we are at root and cannot get - deeper into a negative directory hierarchy (anti-directory) - */ - if (pFile->iCurrentG == 0) { - NXI5KillDir (pFile); - return NX_OK; - } else { - /* close the current group and decrement name_ref */ - H5Gclose (pFile->iCurrentG); - i = 0; - i = strlen(pFile->iStack5[pFile->iStackPtr].irefn); - ii = strlen(pFile->name_ref); - if (pFile->iStackPtr>1) { - ii=ii-i-1; - } else { - ii=ii-i; - } - if (ii>0) { - uname = strdup(pFile->name_ref); - u1name = (char*) malloc((ii+1)*sizeof(char)); - memset(u1name,0,ii); - for (i=0; iname_ref,u1name); - strcpy(pFile->name_tmp,u1name); - free(uname); - free(u1name); - } else { - strcpy(pFile->name_ref,""); - strcpy(pFile->name_tmp,""); - } - NXI5KillDir (pFile); - pFile->iStackPtr--; - if (pFile->iStackPtr>0) { - pFile->iCurrentG=pFile->iStack5[pFile->iStackPtr].iVref; - } else { - pFile->iCurrentG=0; - } - } +NXstatus NX5closegroup(NXhandle fid) +{ + pNexusFile5 pFile; + int i, ii; + char *uname = NULL; + char *u1name = NULL; + + pFile = NXI5assert(fid); + /* first catch the trivial case: we are at root and cannot get + deeper into a negative directory hierarchy (anti-directory) + */ + if (pFile->iCurrentG == 0) { + NXI5KillDir(pFile); return NX_OK; + } else { + /* close the current group and decrement name_ref */ + H5Gclose(pFile->iCurrentG); + i = 0; + i = strlen(pFile->iStack5[pFile->iStackPtr].irefn); + ii = strlen(pFile->name_ref); + if (pFile->iStackPtr > 1) { + ii = ii - i - 1; + } else { + ii = ii - i; + } + if (ii > 0) { + uname = strdup(pFile->name_ref); + u1name = (char *) malloc((ii + 1) * sizeof(char)); + memset(u1name, 0, ii); + for (i = 0; i < ii; i++) { + *(u1name + i) = *(uname + i); + } + *(u1name + i) = '\0'; + /* + strncpy(u1name, uname, ii); + */ + strcpy(pFile->name_ref, u1name); + strcpy(pFile->name_tmp, u1name); + free(uname); + free(u1name); + } else { + strcpy(pFile->name_ref, ""); + strcpy(pFile->name_tmp, ""); + } + NXI5KillDir(pFile); + pFile->iStackPtr--; + if (pFile->iStackPtr > 0) { + pFile->iCurrentG = pFile->iStack5[pFile->iStackPtr].iVref; + } else { + pFile->iCurrentG = 0; + } } + return NX_OK; +} + /*-----------------------------------------------------------------------*/ static int nxToHDF5Type(int datatype) { int type; - if (datatype == NX_CHAR) - { - type=H5T_C_S1; - } - else if (datatype == NX_INT8) - { - type=H5T_NATIVE_CHAR; - } - else if (datatype == NX_UINT8) - { - type=H5T_NATIVE_UCHAR; - } - else if (datatype == NX_INT16) - { - type=H5T_NATIVE_SHORT; - } - else if (datatype == NX_UINT16) - { - type=H5T_NATIVE_USHORT; - } - else if (datatype == NX_INT32) - { - type=H5T_NATIVE_INT; - } - else if (datatype == NX_UINT32) - { - type=H5T_NATIVE_UINT; - } - else if (datatype == NX_INT64) - { - type = H5T_NATIVE_INT64; - } - else if (datatype == NX_UINT64) - { - type = H5T_NATIVE_UINT64; - } - else if (datatype == NX_FLOAT32) - { - type=H5T_NATIVE_FLOAT; - } - else if (datatype == NX_FLOAT64) - { - type=H5T_NATIVE_DOUBLE; - } - else - { - NXIReportError (NXpData, "ERROR: nxToHDF5Type: unknown type"); - type = -1; - } - return type; + if (datatype == NX_CHAR) { + type = H5T_C_S1; + } else if (datatype == NX_INT8) { + type = H5T_NATIVE_CHAR; + } else if (datatype == NX_UINT8) { + type = H5T_NATIVE_UCHAR; + } else if (datatype == NX_INT16) { + type = H5T_NATIVE_SHORT; + } else if (datatype == NX_UINT16) { + type = H5T_NATIVE_USHORT; + } else if (datatype == NX_INT32) { + type = H5T_NATIVE_INT; + } else if (datatype == NX_UINT32) { + type = H5T_NATIVE_UINT; + } else if (datatype == NX_INT64) { + type = H5T_NATIVE_INT64; + } else if (datatype == NX_UINT64) { + type = H5T_NATIVE_UINT64; + } else if (datatype == NX_FLOAT32) { + type = H5T_NATIVE_FLOAT; + } else if (datatype == NX_FLOAT64) { + type = H5T_NATIVE_DOUBLE; + } else { + NXIReportError(NXpData, "ERROR: nxToHDF5Type: unknown type"); + type = -1; + } + return type; } - + /* --------------------------------------------------------------------- */ - NXstatus NX5compmakedata (NXhandle fid, CONSTCHAR *name, - int datatype, - int rank, int dimensions[], - int compress_type, int chunk_size[]) - { - hid_t datatype1, dataspace, iNew, iRet; - hid_t type, cparms = -1; - pNexusFile5 pFile; - char pBuffer[256]; - int i, byte_zahl = 0; - hsize_t chunkdims[H5S_MAX_RANK]; - hsize_t mydim[H5S_MAX_RANK], mydim1[H5S_MAX_RANK]; - hsize_t size[H5S_MAX_RANK]; - hsize_t maxdims[H5S_MAX_RANK]; +NXstatus NX5compmakedata(NXhandle fid, CONSTCHAR * name, + int datatype, + int rank, int dimensions[], + int compress_type, int chunk_size[]) +{ + hid_t datatype1, dataspace, iNew, iRet; + hid_t type, cparms = -1; + pNexusFile5 pFile; + char pBuffer[256]; + int i, byte_zahl = 0; + hsize_t chunkdims[H5S_MAX_RANK]; + hsize_t mydim[H5S_MAX_RANK], mydim1[H5S_MAX_RANK]; + hsize_t size[H5S_MAX_RANK]; + hsize_t maxdims[H5S_MAX_RANK]; - pFile = NXI5assert (fid); - - for (i = 0; i < rank; i++) - { - chunkdims[i]=chunk_size[i]; - mydim[i] = dimensions[i]; - maxdims[i] = dimensions[i]; - size[i] = dimensions[i]; - } + pFile = NXI5assert(fid); - type = nxToHDF5Type(datatype); + for (i = 0; i < rank; i++) { + chunkdims[i] = chunk_size[i]; + mydim[i] = dimensions[i]; + maxdims[i] = dimensions[i]; + size[i] = dimensions[i]; + } - if (rank <= 0) { - sprintf (pBuffer, "ERROR: invalid rank specified %s", - name); - NXIReportError (NXpData, pBuffer); + type = nxToHDF5Type(datatype); + + if (rank <= 0) { + sprintf(pBuffer, "ERROR: invalid rank specified %s", name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + /* + Check dimensions for consistency. The first dimension may be -1 + thus denoting an unlimited dimension. + */ + for (i = 1; i < rank; i++) { + if (dimensions[i] <= 0) { + sprintf(pBuffer, + "ERROR: invalid dimension %d, value %d given for Dataset %s", + i, dimensions[i], name); + NXIReportError(NXpData, pBuffer); return NX_ERROR; } - /* - Check dimensions for consistency. The first dimension may be -1 - thus denoting an unlimited dimension. - */ - for (i = 1; i < rank; i++) { - if (dimensions[i] <= 0) { - sprintf (pBuffer, - "ERROR: invalid dimension %d, value %d given for Dataset %s", - i, dimensions[i], name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - } - if (datatype == NX_CHAR) - { + } + if (datatype == NX_CHAR) { /* * This assumes string lenght is in the last dimensions and * the logic must be the same as used in NX5getslab and NX5getinfo * * search for tests on H5T_STRING */ - byte_zahl=dimensions[rank-1]; - for(i = 0; i < rank; i++) - { - mydim1[i] = dimensions[i]; - } - mydim1[rank-1] = 1; - if (dimensions[rank-1] > 1) - { - mydim[rank-1] = maxdims[rank-1] = size[rank-1] = 1; - } - if (chunkdims[rank-1] > 1) - { - chunkdims[rank-1] = 1; - } - if (dimensions[0] == NX_UNLIMITED) - { - mydim1[0] = 1; - maxdims[0] = H5S_UNLIMITED; - } - dataspace=H5Screate_simple(rank,mydim1,maxdims); + byte_zahl = dimensions[rank - 1]; + for (i = 0; i < rank; i++) { + mydim1[i] = dimensions[i]; + } + mydim1[rank - 1] = 1; + if (dimensions[rank - 1] > 1) { + mydim[rank - 1] = maxdims[rank - 1] = size[rank - 1] = 1; + } + if (chunkdims[rank - 1] > 1) { + chunkdims[rank - 1] = 1; + } + if (dimensions[0] == NX_UNLIMITED) { + mydim1[0] = 1; + maxdims[0] = H5S_UNLIMITED; + } + dataspace = H5Screate_simple(rank, mydim1, maxdims); + } else { + if (dimensions[0] == NX_UNLIMITED) { + mydim[0] = 1; + maxdims[0] = H5S_UNLIMITED; + dataspace = H5Screate_simple(rank, mydim, maxdims); } else { - if (dimensions[0] == NX_UNLIMITED) - { - mydim[0] = 1; - maxdims[0] = H5S_UNLIMITED; - dataspace=H5Screate_simple(rank, mydim, maxdims); - } else { - /* dataset creation */ - dataspace=H5Screate_simple(rank, mydim, NULL); - } - } - datatype1=H5Tcopy(type); - if (datatype == NX_CHAR) - { - H5Tset_size(datatype1, byte_zahl); -/* H5Tset_strpad(H5T_STR_SPACEPAD); */ + /* dataset creation */ + dataspace = H5Screate_simple(rank, mydim, NULL); } - if(compress_type == NX_COMP_LZW) - { - cparms = H5Pcreate(H5P_DATASET_CREATE); - iNew = H5Pset_chunk(cparms,rank,chunkdims); - if (iNew < 0) { - NXIReportError (NXpData, "ERROR: Size of chunks could not be set!"); - return NX_ERROR; - } - H5Pset_deflate(cparms,6); - iRet = H5Dcreate (pFile->iCurrentG, (char*)name, datatype1, - dataspace, cparms); - } else if (compress_type == NX_COMP_NONE) { - if (dimensions[0] == NX_UNLIMITED) { - cparms = H5Pcreate(H5P_DATASET_CREATE); - iNew = H5Pset_chunk(cparms,rank,chunkdims); - if (iNew < 0) { - NXIReportError (NXpData, - "ERROR: Size of chunks could not be set!"); - return NX_ERROR; - } - iRet = H5Dcreate (pFile->iCurrentG, (char*)name, datatype1, - dataspace, cparms); - } else { - iRet = H5Dcreate (pFile->iCurrentG, (char*)name, datatype1, - dataspace, H5P_DEFAULT); - } - } else { - NXIReportError (NXpData, - "HDF5 doesn't support selected compression method! Dataset was saved without compression"); - iRet = H5Dcreate (pFile->iCurrentG, (char*)name, datatype1, - dataspace, H5P_DEFAULT); - } - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: Creating chunked dataset failed!"); - return NX_ERROR; - } else { - pFile->iCurrentD = iRet; - } - if (dimensions[0] == NX_UNLIMITED) - { - size[0] = 1; - iNew = H5Dextend (pFile->iCurrentD, size); - if (iNew < 0) { - sprintf (pBuffer, "ERROR: cannot create Dataset %s, check arguments", - name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - } - if (cparms != -1) { - iRet = H5Pclose(cparms); - } - iRet = H5Sclose(dataspace); - iRet = H5Tclose(datatype1); - iRet = H5Dclose(pFile->iCurrentD); - pFile->iCurrentD = 0; - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot close Dataset"); - return NX_ERROR; - } - return NX_OK; } + datatype1 = H5Tcopy(type); + if (datatype == NX_CHAR) { + H5Tset_size(datatype1, byte_zahl); +/* H5Tset_strpad(H5T_STR_SPACEPAD); */ + } + if (compress_type == NX_COMP_LZW) { + cparms = H5Pcreate(H5P_DATASET_CREATE); + iNew = H5Pset_chunk(cparms, rank, chunkdims); + if (iNew < 0) { + NXIReportError(NXpData, "ERROR: Size of chunks could not be set!"); + return NX_ERROR; + } + H5Pset_deflate(cparms, 6); + iRet = H5Dcreate(pFile->iCurrentG, (char *) name, datatype1, + dataspace, cparms); + } else if (compress_type == NX_COMP_NONE) { + if (dimensions[0] == NX_UNLIMITED) { + cparms = H5Pcreate(H5P_DATASET_CREATE); + iNew = H5Pset_chunk(cparms, rank, chunkdims); + if (iNew < 0) { + NXIReportError(NXpData, "ERROR: Size of chunks could not be set!"); + return NX_ERROR; + } + iRet = H5Dcreate(pFile->iCurrentG, (char *) name, datatype1, + dataspace, cparms); + } else { + iRet = H5Dcreate(pFile->iCurrentG, (char *) name, datatype1, + dataspace, H5P_DEFAULT); + } + } else { + NXIReportError(NXpData, + "HDF5 doesn't support selected compression method! Dataset was saved without compression"); + iRet = H5Dcreate(pFile->iCurrentG, (char *) name, datatype1, + dataspace, H5P_DEFAULT); + } + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: Creating chunked dataset failed!"); + return NX_ERROR; + } else { + pFile->iCurrentD = iRet; + } + if (dimensions[0] == NX_UNLIMITED) { + size[0] = 1; + iNew = H5Dextend(pFile->iCurrentD, size); + if (iNew < 0) { + sprintf(pBuffer, "ERROR: cannot create Dataset %s, check arguments", + name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + } + if (cparms != -1) { + iRet = H5Pclose(cparms); + } + iRet = H5Sclose(dataspace); + iRet = H5Tclose(datatype1); + iRet = H5Dclose(pFile->iCurrentD); + pFile->iCurrentD = 0; + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot close Dataset"); + return NX_ERROR; + } + return NX_OK; +} /* --------------------------------------------------------------------- */ - NXstatus NX5makedata (NXhandle fid, CONSTCHAR *name, int datatype, - int rank, int dimensions[]) - { +NXstatus NX5makedata(NXhandle fid, CONSTCHAR * name, int datatype, + int rank, int dimensions[]) +{ pNexusFile5 pFile; int chunk_size[H5S_MAX_RANK]; int i; - - pFile = NXI5assert (fid); - memset(chunk_size,0,H5S_MAX_RANK*sizeof(int)); - if (dimensions[0] == NX_UNLIMITED) - { - for (i = 0; i < H5S_MAX_RANK; i++) - { - chunk_size[i]= 1; - } - } - return NX5compmakedata (fid, name, datatype, rank, dimensions, NX_COMP_NONE, chunk_size); - + + pFile = NXI5assert(fid); + memset(chunk_size, 0, H5S_MAX_RANK * sizeof(int)); + if (dimensions[0] == NX_UNLIMITED) { + for (i = 0; i < H5S_MAX_RANK; i++) { + chunk_size[i] = 1; + } + } + return NX5compmakedata(fid, name, datatype, rank, dimensions, + NX_COMP_NONE, chunk_size); + return NX_OK; - } +} + - /* --------------------------------------------------------------------- */ - NXstatus NX5compress (NXhandle fid, int compress_type) - { - printf(" NXcompress ERROR: NeXus API based on HDF5 doesn't support\n"); - printf(" NXcompress function! Using HDF5 library,\n"); - printf(" the NXcompmakedata function can be applied\n"); - printf(" for compression of data!\n"); +NXstatus NX5compress(NXhandle fid, int compress_type) +{ + printf + (" NXcompress ERROR: NeXus API based on HDF5 doesn't support\n"); + printf + (" NXcompress function! Using HDF5 library,\n"); + printf + (" the NXcompmakedata function can be applied\n"); + printf(" for compression of data!\n"); + return NX_ERROR; +} + + /* --------------------------------------------------------------------- */ + +NXstatus NX5opendata(NXhandle fid, CONSTCHAR * name) +{ + pNexusFile5 pFile; + char pBuffer[256]; + + pFile = NXI5assert(fid); + /* clear pending attribute directories first */ + NXI5KillAttDir(pFile); + + + /* find the ID number and open the dataset */ + pFile->iCurrentD = H5Dopen(pFile->iCurrentG, name); + if (pFile->iCurrentD < 0) { + sprintf(pBuffer, "ERROR: Dataset %s not found at this level", name); + NXIReportError(NXpData, pBuffer); return NX_ERROR; - } - - /* --------------------------------------------------------------------- */ - - NXstatus NX5opendata (NXhandle fid, CONSTCHAR *name) - { - pNexusFile5 pFile; - char pBuffer[256]; - - pFile = NXI5assert (fid); - /* clear pending attribute directories first */ - NXI5KillAttDir (pFile); - - - /* find the ID number and open the dataset */ - pFile->iCurrentD = H5Dopen(pFile->iCurrentG, name); - if (pFile->iCurrentD < 0) { - sprintf (pBuffer, "ERROR: Dataset %s not found at this level", name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - /* find the ID number of datatype */ - pFile->iCurrentT = H5Dget_type(pFile->iCurrentD); - if (pFile->iCurrentT < 0) { - NXIReportError (NXpData, "ERROR:HDF error opening Dataset"); - pFile->iCurrentT=0; - return NX_ERROR; - } - /* find the ID number of dataspace */ - pFile->iCurrentS = H5Dget_space(pFile->iCurrentD); - if (pFile->iCurrentS < 0) { - NXIReportError (NXpData, "ERROR:HDF error opening Dataset"); - pFile->iCurrentS=0; - return NX_ERROR; - } - if(pFile->iCurrentLD != NULL){ - free(pFile->iCurrentLD); - } - pFile->iCurrentLD = strdup(name); - return NX_OK; } - + /* find the ID number of datatype */ + pFile->iCurrentT = H5Dget_type(pFile->iCurrentD); + if (pFile->iCurrentT < 0) { + NXIReportError(NXpData, "ERROR:HDF error opening Dataset"); + pFile->iCurrentT = 0; + return NX_ERROR; + } + /* find the ID number of dataspace */ + pFile->iCurrentS = H5Dget_space(pFile->iCurrentD); + if (pFile->iCurrentS < 0) { + NXIReportError(NXpData, "ERROR:HDF error opening Dataset"); + pFile->iCurrentS = 0; + return NX_ERROR; + } + if (pFile->iCurrentLD != NULL) { + free(pFile->iCurrentLD); + } + pFile->iCurrentLD = strdup(name); + return NX_OK; +} + /* ----------------------------------------------------------------- */ - NXstatus NX5closedata (NXhandle fid) - { - pNexusFile5 pFile; - int iRet; - - pFile = NXI5assert (fid); - iRet = H5Sclose(pFile->iCurrentS); - iRet = H5Tclose(pFile->iCurrentT); - iRet = H5Dclose(pFile->iCurrentD); - if (iRet < 0) { - NXIReportError (NXpData, "ERROR: HDF cannot end access to Dataset"); - return NX_ERROR; - } - pFile->iCurrentD=0; - return NX_OK; - } - - /* ------------------------------------------------------------------- */ - +NXstatus NX5closedata(NXhandle fid) +{ + pNexusFile5 pFile; + int iRet; - - NXstatus NX5putdata (NXhandle fid, void *data) - { - pNexusFile5 pFile; - hid_t iRet; - - char pError[512] = ""; - - pFile = NXI5assert (fid); - - /* actually write */ - iRet = H5Dwrite (pFile->iCurrentD, pFile->iCurrentT, H5S_ALL, H5S_ALL, - H5P_DEFAULT, data); - if (iRet < 0) { - snprintf (pError,511, "ERROR: failure to write data"); - NXIReportError (NXpData, pError); - return NX_ERROR; - } - return NX_OK; + pFile = NXI5assert(fid); + iRet = H5Sclose(pFile->iCurrentS); + iRet = H5Tclose(pFile->iCurrentT); + iRet = H5Dclose(pFile->iCurrentD); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: HDF cannot end access to Dataset"); + return NX_ERROR; } -/*------------------------------------------------------------------*/ -static int getAttVID(pNexusFile5 pFile){ - int vid; - if(pFile->iCurrentG == 0 && pFile->iCurrentD == 0){ - /* global attribute */ - vid = H5Gopen(pFile->iFID,"/"); - } else if(pFile->iCurrentD != 0) { - /* dataset attribute */ - vid = pFile->iCurrentD; - } else { - /* group attribute */; - vid = pFile->iCurrentG; - } - return vid; + pFile->iCurrentD = 0; + return NX_OK; } + + /* ------------------------------------------------------------------- */ + + + +NXstatus NX5putdata(NXhandle fid, void *data) +{ + pNexusFile5 pFile; + hid_t iRet; + + char pError[512] = ""; + + pFile = NXI5assert(fid); + + /* actually write */ + iRet = H5Dwrite(pFile->iCurrentD, pFile->iCurrentT, H5S_ALL, H5S_ALL, + H5P_DEFAULT, data); + if (iRet < 0) { + snprintf(pError, 511, "ERROR: failure to write data"); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + return NX_OK; +} + +/*------------------------------------------------------------------*/ +static int getAttVID(pNexusFile5 pFile) +{ + int vid; + if (pFile->iCurrentG == 0 && pFile->iCurrentD == 0) { + /* global attribute */ + vid = H5Gopen(pFile->iFID, "/"); + } else if (pFile->iCurrentD != 0) { + /* dataset attribute */ + vid = pFile->iCurrentD; + } else { + /* group attribute */ ; + vid = pFile->iCurrentG; + } + return vid; +} + /*---------------------------------------------------------------*/ -static void killAttVID(pNexusFile5 pFile, int vid){ - if(pFile->iCurrentG == 0 && pFile->iCurrentD == 0){ +static void killAttVID(pNexusFile5 pFile, int vid) +{ + if (pFile->iCurrentG == 0 && pFile->iCurrentD == 0) { H5Gclose(vid); } } + /* ------------------------------------------------------------------- */ - NXstatus NX5putattr (NXhandle fid, CONSTCHAR *name, void *data, - int datalen, int iType) - { - pNexusFile5 pFile; - hid_t attr1, aid1, aid2; - hid_t type; - int iRet; - int vid; +NXstatus NX5putattr(NXhandle fid, CONSTCHAR * name, void *data, + int datalen, int iType) +{ + pNexusFile5 pFile; + hid_t attr1, aid1, aid2; + hid_t type; + int iRet; + int vid; - pFile = NXI5assert (fid); + pFile = NXI5assert(fid); - type = nxToHDF5Type(iType); - - /* determine vid */ - vid = getAttVID(pFile); - aid2=H5Screate(H5S_SCALAR); - aid1=H5Tcopy(type); - if (iType == NX_CHAR){ - H5Tset_size(aid1,datalen); - } - iRet = H5Aopen_name(vid, name); - if (iRet>0) { - H5Aclose(iRet); - iRet=H5Adelete(vid,name); - if (iRet<0) { - NXIReportError (NXpData, "ERROR: Old attribute cannot removed! "); - killAttVID(pFile,vid); - return NX_ERROR; - } - } - attr1 = H5Acreate(vid, name, aid1, aid2, H5P_DEFAULT); - if (attr1 < 0) { - NXIReportError (NXpData, "ERROR: Attribute cannot created! "); - killAttVID(pFile,vid); - return NX_ERROR; - } - if (H5Awrite(attr1,aid1,data) < 0) { - NXIReportError (NXpData, "ERROR: HDF failed to store attribute "); - killAttVID(pFile,vid); - return NX_ERROR; - } - /* Close attribute dataspace */ - iRet=H5Tclose(aid1); - iRet=H5Sclose(aid2); - /* Close attribute */ - iRet=H5Aclose(attr1); - killAttVID(pFile,vid); - return NX_OK; + type = nxToHDF5Type(iType); + + /* determine vid */ + vid = getAttVID(pFile); + aid2 = H5Screate(H5S_SCALAR); + aid1 = H5Tcopy(type); + if (iType == NX_CHAR) { + H5Tset_size(aid1, datalen); } - - /* ------------------------------------------------------------------- */ - - NXstatus NX5putslab (NXhandle fid, void *data, int iStart[], int iSize[]) - { - pNexusFile5 pFile; - int iRet, i; - int rank; - hsize_t myStart[H5S_MAX_RANK]; - hsize_t mySize[H5S_MAX_RANK]; - hsize_t size[H5S_MAX_RANK],maxdims[H5S_MAX_RANK]; - hid_t filespace,dataspace; - - pFile = NXI5assert (fid); - /* check if there is an Dataset open */ - if (pFile->iCurrentD == 0) { - NXIReportError (NXpData, "ERROR: no dataset open"); + iRet = H5Aopen_name(vid, name); + if (iRet > 0) { + H5Aclose(iRet); + iRet = H5Adelete(vid, name); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: Old attribute cannot removed! "); + killAttVID(pFile, vid); return NX_ERROR; } - rank = H5Sget_simple_extent_ndims(pFile->iCurrentS); - iRet = H5Sget_simple_extent_dims(pFile->iCurrentS, NULL, maxdims); - for(i = 0; i < rank; i++) - { - myStart[i] = iStart[i]; - mySize[i] = iSize[i]; - size[i] = iSize[i]; - } - if (H5Tget_class(pFile->iCurrentT) == H5T_STRING) - { - mySize[rank - 1] = 1; - myStart[rank - 1] = 0; - } - dataspace = H5Screate_simple (rank, mySize, NULL); - if (maxdims[0] == NX_UNLIMITED) - { - size[0]=iStart[0] + iSize[0]; - iRet = H5Dextend(pFile->iCurrentD, size); - if (iRet < 0) - { - NXIReportError (NXpData, "ERROR: extend slab failed"); - return NX_ERROR; - } + } + attr1 = H5Acreate(vid, name, aid1, aid2, H5P_DEFAULT); + if (attr1 < 0) { + NXIReportError(NXpData, "ERROR: Attribute cannot created! "); + killAttVID(pFile, vid); + return NX_ERROR; + } + if (H5Awrite(attr1, aid1, data) < 0) { + NXIReportError(NXpData, "ERROR: HDF failed to store attribute "); + killAttVID(pFile, vid); + return NX_ERROR; + } + /* Close attribute dataspace */ + iRet = H5Tclose(aid1); + iRet = H5Sclose(aid2); + /* Close attribute */ + iRet = H5Aclose(attr1); + killAttVID(pFile, vid); + return NX_OK; +} - filespace = H5Dget_space(pFile->iCurrentD); - - /* define slab */ - iRet = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, myStart, + /* ------------------------------------------------------------------- */ + +NXstatus NX5putslab(NXhandle fid, void *data, int iStart[], int iSize[]) +{ + pNexusFile5 pFile; + int iRet, i; + int rank; + hsize_t myStart[H5S_MAX_RANK]; + hsize_t mySize[H5S_MAX_RANK]; + hsize_t size[H5S_MAX_RANK], maxdims[H5S_MAX_RANK]; + hid_t filespace, dataspace; + + pFile = NXI5assert(fid); + /* check if there is an Dataset open */ + if (pFile->iCurrentD == 0) { + NXIReportError(NXpData, "ERROR: no dataset open"); + return NX_ERROR; + } + rank = H5Sget_simple_extent_ndims(pFile->iCurrentS); + iRet = H5Sget_simple_extent_dims(pFile->iCurrentS, NULL, maxdims); + for (i = 0; i < rank; i++) { + myStart[i] = iStart[i]; + mySize[i] = iSize[i]; + size[i] = iSize[i]; + } + if (H5Tget_class(pFile->iCurrentT) == H5T_STRING) { + mySize[rank - 1] = 1; + myStart[rank - 1] = 0; + } + dataspace = H5Screate_simple(rank, mySize, NULL); + if (maxdims[0] == NX_UNLIMITED) { + size[0] = iStart[0] + iSize[0]; + iRet = H5Dextend(pFile->iCurrentD, size); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: extend slab failed"); + return NX_ERROR; + } + + filespace = H5Dget_space(pFile->iCurrentD); + + /* define slab */ + iRet = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, myStart, NULL, mySize, NULL); - /* deal with HDF errors */ - if (iRet < 0) - { - NXIReportError (NXpData, "ERROR: selecting slab failed"); - return NX_ERROR; - } - /* write slab */ - iRet = H5Dwrite(pFile->iCurrentD, pFile->iCurrentT, dataspace, - filespace, H5P_DEFAULT,data); - if (iRet < 0) - { - NXIReportError (NXpData, "ERROR: writing slab failed"); - } - iRet = H5Sclose(filespace); - } else { - /* define slab */ - iRet = H5Sselect_hyperslab(pFile->iCurrentS, H5S_SELECT_SET, myStart, - NULL, mySize, NULL); - /* deal with HDF errors */ - if (iRet < 0) - { - NXIReportError (NXpData, "ERROR: selecting slab failed"); - return NX_ERROR; - } - /* write slab */ - iRet = H5Dwrite(pFile->iCurrentD, pFile->iCurrentT, dataspace, - pFile->iCurrentS, H5P_DEFAULT,data); - if (iRet < 0) - { - NXIReportError (NXpData, "ERROR: writing slab failed"); - } - } - /* deal with HDF errors */ - iRet = H5Sclose(dataspace); - if (iRet < 0) - { - NXIReportError (NXpData, "ERROR: closing slab failed"); + /* deal with HDF errors */ + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: selecting slab failed"); return NX_ERROR; - } - return NX_OK; + } + /* write slab */ + iRet = H5Dwrite(pFile->iCurrentD, pFile->iCurrentT, dataspace, + filespace, H5P_DEFAULT, data); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: writing slab failed"); + } + iRet = H5Sclose(filespace); + } else { + /* define slab */ + iRet = H5Sselect_hyperslab(pFile->iCurrentS, H5S_SELECT_SET, myStart, + NULL, mySize, NULL); + /* deal with HDF errors */ + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: selecting slab failed"); + return NX_ERROR; + } + /* write slab */ + iRet = H5Dwrite(pFile->iCurrentD, pFile->iCurrentT, dataspace, + pFile->iCurrentS, H5P_DEFAULT, data); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: writing slab failed"); + } } - + /* deal with HDF errors */ + iRet = H5Sclose(dataspace); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: closing slab failed"); + return NX_ERROR; + } + return NX_OK; +} + /* ------------------------------------------------------------------- */ - NXstatus NX5getdataID (NXhandle fid, NXlink* sRes) - { - pNexusFile5 pFile; - ErrFunc oldErr; - int datalen, type = NX_CHAR; - - pFile = NXI5assert (fid); +NXstatus NX5getdataID(NXhandle fid, NXlink * sRes) +{ + pNexusFile5 pFile; + ErrFunc oldErr; + int datalen, type = NX_CHAR; - /* - we cannot return ID's when no datset is open - */ - if(pFile->iCurrentD <= 0){ - return NX_ERROR; - } + pFile = NXI5assert(fid); - /* - this means: if the item is already linked: use the target attribute else, - the path to the current node - */ - oldErr = NXMGetError(); - NXMSetError(NXpData, ignoreError); - datalen = 1024; - memset(&sRes->targetPath,0,datalen*sizeof(char)); - if(NX5getattr(fid,"target",&sRes->targetPath,&datalen,&type) != NX_OK) - { - buildCurrentPath(pFile, sRes->targetPath, 1024); - } - NXMSetError(NXpData,oldErr); - sRes->linkType = 1; - return NX_OK; + /* + we cannot return ID's when no datset is open + */ + if (pFile->iCurrentD <= 0) { + return NX_ERROR; } + /* + this means: if the item is already linked: use the target attribute else, + the path to the current node + */ + oldErr = NXMGetError(); + NXMSetError(NXpData, ignoreError); + datalen = 1024; + memset(&sRes->targetPath, 0, datalen * sizeof(char)); + if (NX5getattr(fid, "target", &sRes->targetPath, &datalen, &type) != + NX_OK) { + buildCurrentPath(pFile, sRes->targetPath, 1024); + } + NXMSetError(NXpData, oldErr); + sRes->linkType = 1; + return NX_OK; +} + /* ------------------------------------------------------------------- */ - - NXstatus NX5printlink (NXhandle fid, NXlink* sLink) - { - pNexusFile5 pFile; - pFile = NXI5assert (fid); - printf("HDF5 link: targetPath = \"%s\", linkType = \"%d\"\n", sLink->targetPath, sLink->linkType); - return NX_OK; - } + +NXstatus NX5printlink(NXhandle fid, NXlink * sLink) +{ + pNexusFile5 pFile; + pFile = NXI5assert(fid); + printf("HDF5 link: targetPath = \"%s\", linkType = \"%d\"\n", + sLink->targetPath, sLink->linkType); + return NX_OK; +} + /*--------------------------------------------------------------------*/ -static NXstatus NX5settargetattribute(pNexusFile5 pFile, NXlink *sLink) +static NXstatus NX5settargetattribute(pNexusFile5 pFile, NXlink * sLink) { herr_t length, dataID, status, aid2, aid1, attID; int type = NX_CHAR; char name[] = "target"; - length = strlen(sLink->targetPath); - /* - set the target attribute - */ - if(sLink->linkType > 0) - { - dataID = H5Dopen(pFile->iFID,sLink->targetPath); - } else { - dataID = H5Gopen(pFile->iFID,sLink->targetPath); - } - if(dataID < 0) - { - NXIReportError(NXpData,"Internal error, path to link does not exist"); - return NX_ERROR; - } - status = H5Aopen_name(dataID,name); - if(status > 0) - { - H5Aclose(status); - status = H5Adelete(dataID,name); - if(status < 0) - { - return NX_OK; - } - } - aid2 = H5Screate(H5S_SCALAR); - aid1 = H5Tcopy(H5T_C_S1); - H5Tset_size(aid1,strlen(sLink->targetPath)); - attID = H5Acreate(dataID,name,aid1,aid2,H5P_DEFAULT); - if(attID < 0) - { - return NX_OK; - } - status = H5Awrite(attID,aid1,sLink->targetPath); - H5Tclose(aid1); - H5Sclose(aid2); - H5Aclose(attID); - if(sLink->linkType > 0){ - H5Dclose(dataID); - } else { - H5Gclose(dataID); + length = strlen(sLink->targetPath); + /* + set the target attribute + */ + if (sLink->linkType > 0) { + dataID = H5Dopen(pFile->iFID, sLink->targetPath); + } else { + dataID = H5Gopen(pFile->iFID, sLink->targetPath); + } + if (dataID < 0) { + NXIReportError(NXpData, "Internal error, path to link does not exist"); + return NX_ERROR; + } + status = H5Aopen_name(dataID, name); + if (status > 0) { + H5Aclose(status); + status = H5Adelete(dataID, name); + if (status < 0) { + return NX_OK; } + } + aid2 = H5Screate(H5S_SCALAR); + aid1 = H5Tcopy(H5T_C_S1); + H5Tset_size(aid1, strlen(sLink->targetPath)); + attID = H5Acreate(dataID, name, aid1, aid2, H5P_DEFAULT); + if (attID < 0) { return NX_OK; + } + status = H5Awrite(attID, aid1, sLink->targetPath); + H5Tclose(aid1); + H5Sclose(aid2); + H5Aclose(attID); + if (sLink->linkType > 0) { + H5Dclose(dataID); + } else { + H5Gclose(dataID); + } + return NX_OK; } + /*---------------------------------------------------------------------*/ -NXstatus NX5makenamedlink(NXhandle fid, CONSTCHAR *name, NXlink *sLink) +NXstatus NX5makenamedlink(NXhandle fid, CONSTCHAR * name, NXlink * sLink) { - pNexusFile5 pFile; - char linkTarget[1024]; - int type = NX_CHAR, length; - int status; + pNexusFile5 pFile; + char linkTarget[1024]; + int type = NX_CHAR, length; + int status; - pFile = NXI5assert (fid); - if (pFile->iCurrentG == 0) { /* root level, can not link here */ - return NX_ERROR; - } - - /* - build pathname to link from our current group and the name - of the thing to link - */ - if(strlen(pFile->name_ref) + strlen(name) + 2 < 1024) - { - strcpy(linkTarget,"/"); - strcat(linkTarget,pFile->name_ref); - strcat(linkTarget,"/"); - strcat(linkTarget,name); - } - else - { - NXIReportError(NXpData,"Path string to long"); - return NX_ERROR; - } + pFile = NXI5assert(fid); + if (pFile->iCurrentG == 0) { /* root level, can not link here */ + return NX_ERROR; + } - status = H5Glink(pFile->iFID, H5G_LINK_HARD, sLink->targetPath, linkTarget); + /* + build pathname to link from our current group and the name + of the thing to link + */ + if (strlen(pFile->name_ref) + strlen(name) + 2 < 1024) { + strcpy(linkTarget, "/"); + strcat(linkTarget, pFile->name_ref); + strcat(linkTarget, "/"); + strcat(linkTarget, name); + } else { + NXIReportError(NXpData, "Path string to long"); + return NX_ERROR; + } - return NX5settargetattribute(pFile,sLink); + status = + H5Glink(pFile->iFID, H5G_LINK_HARD, sLink->targetPath, linkTarget); + + return NX5settargetattribute(pFile, sLink); } + /* ------------------------------------------------------------------- */ - - NXstatus NX5makelink (NXhandle fid, NXlink* sLink) - { - pNexusFile5 pFile; - char linkTarget[1024]; - int type = NX_CHAR, length; - char *itemName = NULL; - int status; - pFile = NXI5assert (fid); - if (pFile->iCurrentG == 0) { /* root level, can not link here */ - return NX_ERROR; - } - - /* - locate name of the element to link - */ - itemName = strrchr(sLink->targetPath,'/'); - if(itemName == NULL){ - NXIReportError(NXpData,"Bad link structure"); - return NX_ERROR; - } - itemName++; +NXstatus NX5makelink(NXhandle fid, NXlink * sLink) +{ + pNexusFile5 pFile; + char linkTarget[1024]; + int type = NX_CHAR, length; + char *itemName = NULL; + int status; - /* - build pathname to link from our current group and the name - of the thing to link - */ - if(strlen(pFile->name_ref) + strlen(itemName) + 2 < 1024) - { - strcpy(linkTarget,"/"); - strcat(linkTarget,pFile->name_ref); - strcat(linkTarget,"/"); - strcat(linkTarget,itemName); - } - else - { - NXIReportError(NXpData,"Path string to long"); - return NX_ERROR; - } + pFile = NXI5assert(fid); + if (pFile->iCurrentG == 0) { /* root level, can not link here */ + return NX_ERROR; + } - status = H5Glink(pFile->iFID, H5G_LINK_HARD, sLink->targetPath, linkTarget); + /* + locate name of the element to link + */ + itemName = strrchr(sLink->targetPath, '/'); + if (itemName == NULL) { + NXIReportError(NXpData, "Bad link structure"); + return NX_ERROR; + } + itemName++; + + /* + build pathname to link from our current group and the name + of the thing to link + */ + if (strlen(pFile->name_ref) + strlen(itemName) + 2 < 1024) { + strcpy(linkTarget, "/"); + strcat(linkTarget, pFile->name_ref); + strcat(linkTarget, "/"); + strcat(linkTarget, itemName); + } else { + NXIReportError(NXpData, "Path string to long"); + return NX_ERROR; + } + + status = + H5Glink(pFile->iFID, H5G_LINK_HARD, sLink->targetPath, linkTarget); + + return NX5settargetattribute(pFile, sLink); +} - return NX5settargetattribute(pFile,sLink); - } - /*----------------------------------------------------------------------*/ - NXstatus NX5flush(NXhandle *pHandle) - { - pNexusFile5 pFile = NULL; - int iRet; - - pFile = NXI5assert (*pHandle); - if (pFile->iCurrentD != 0) - { - iRet=H5Fflush(pFile->iCurrentD,H5F_SCOPE_LOCAL); - } - else if (pFile->iCurrentG != 0) - { - iRet=H5Fflush(pFile->iCurrentG,H5F_SCOPE_LOCAL); - } - else - { - iRet=H5Fflush(pFile->iFID,H5F_SCOPE_LOCAL); - } - if (iRet < 0){ - NXIReportError (NXpData, "ERROR: The object cannot be flushed"); - return NX_ERROR; - } - return NX_OK; - } - - /*-------------------------------------------------------------------------*/ - - /* Operator function. */ - - herr_t nxgroup_info(hid_t loc_id, const char *name, void *op_data) - { - H5G_stat_t statbuf; - pinfo self; - - self = (pinfo)op_data; - H5Gget_objinfo(loc_id, name, 0, &statbuf); - switch (statbuf.type) - { - case H5G_GROUP: - self->iname = strdup(name); - self->type = H5G_GROUP; - break; - case H5G_DATASET: - self->iname = strdup(name); - self->type = H5G_DATASET; - break; - default: - self->type=0; - break; - } - return 1; +NXstatus NX5flush(NXhandle * pHandle) +{ + pNexusFile5 pFile = NULL; + int iRet; + + pFile = NXI5assert(*pHandle); + if (pFile->iCurrentD != 0) { + iRet = H5Fflush(pFile->iCurrentD, H5F_SCOPE_LOCAL); + } else if (pFile->iCurrentG != 0) { + iRet = H5Fflush(pFile->iCurrentG, H5F_SCOPE_LOCAL); + } else { + iRet = H5Fflush(pFile->iFID, H5F_SCOPE_LOCAL); } + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: The object cannot be flushed"); + return NX_ERROR; + } + return NX_OK; +} + + /*-------------------------------------------------------------------------*/ + + /* Operator function. */ + +herr_t nxgroup_info(hid_t loc_id, const char *name, void *op_data) +{ + H5G_stat_t statbuf; + pinfo self; + + self = (pinfo) op_data; + H5Gget_objinfo(loc_id, name, 0, &statbuf); + switch (statbuf.type) { + case H5G_GROUP: + self->iname = strdup(name); + self->type = H5G_GROUP; + break; + case H5G_DATASET: + self->iname = strdup(name); + self->type = H5G_DATASET; + break; + default: + self->type = 0; + break; + } + return 1; +} + /* --------------------------------------------------------------------- */ /* Operator function. */ - herr_t group_info1(hid_t loc_id, const char *name, void *opdata) - { - NexusFile5 self; - H5G_stat_t statbuf; - self.iNX = *((int*)opdata); - H5Gget_objinfo(loc_id, name, 0, &statbuf); - - switch (statbuf.type) - { - case H5G_GROUP: - self.iNX++; - *((int*)opdata)=self.iNX; - break; - case H5G_DATASET: - self.iNX++; - *((int*)opdata)=self.iNX; - break; - default: - break; - } - return 0; +herr_t group_info1(hid_t loc_id, const char *name, void *opdata) +{ + NexusFile5 self; + H5G_stat_t statbuf; + self.iNX = *((int *) opdata); + H5Gget_objinfo(loc_id, name, 0, &statbuf); + + switch (statbuf.type) { + case H5G_GROUP: + self.iNX++; + *((int *) opdata) = self.iNX; + break; + case H5G_DATASET: + self.iNX++; + *((int *) opdata) = self.iNX; + break; + default: + break; } - + return 0; +} + /*-------------------------------------------------------------------------*/ - NXstatus NX5getgroupinfo (NXhandle fid, int *iN, NXname pName, NXname pClass) - { - pNexusFile5 pFile; - hid_t atype,attr_id; - char data[64]; - int iRet; - - pFile = NXI5assert (fid); - /* check if there is a group open */ - if (pFile->iCurrentG == 0) { - strcpy (pName, "root"); - strcpy (pClass, "NXroot"); - pFile->iNX=0; - iRet=H5Giterate(pFile->iFID,"/",0,group_info1,&pFile->iNX); - *iN=pFile->iNX; +NXstatus NX5getgroupinfo(NXhandle fid, int *iN, NXname pName, + NXname pClass) +{ + pNexusFile5 pFile; + hid_t atype, attr_id; + char data[64]; + int iRet; + + pFile = NXI5assert(fid); + /* check if there is a group open */ + if (pFile->iCurrentG == 0) { + strcpy(pName, "root"); + strcpy(pClass, "NXroot"); + pFile->iNX = 0; + iRet = H5Giterate(pFile->iFID, "/", 0, group_info1, &pFile->iNX); + *iN = pFile->iNX; + } else { + strcpy(pName, pFile->name_ref); + attr_id = H5Aopen_name(pFile->iCurrentG, "NX_class"); + if (attr_id < 0) { + strcpy(pClass, NX_UNKNOWN_GROUP); + } else { + atype = H5Tcopy(H5T_C_S1); + H5Tset_size(atype, 64); + H5Aread(attr_id, atype, data); + strcpy(pClass, data); + pFile->iNX = 0; + iRet = + H5Giterate(pFile->iFID, pFile->name_ref, 0, group_info1, + &pFile->iNX); + *iN = pFile->iNX; + H5Aclose(attr_id); } - else { - strcpy (pName,pFile->name_ref); - attr_id = H5Aopen_name(pFile->iCurrentG,"NX_class"); - if (attr_id<0) { - strcpy(pClass, NX_UNKNOWN_GROUP); - } else { - atype=H5Tcopy(H5T_C_S1); - H5Tset_size(atype,64); - H5Aread(attr_id, atype, data); - strcpy(pClass,data); - pFile->iNX=0; - iRet=H5Giterate(pFile->iFID,pFile->name_ref,0,group_info1, &pFile->iNX); - *iN=pFile->iNX; - H5Aclose(attr_id); - } - } - return NX_OK; } + return NX_OK; +} /*------------------------------------------------------------------------*/ static int hdf5ToNXType(int data_id, hid_t atype) @@ -1334,699 +1278,652 @@ static int hdf5ToNXType(int data_id, hid_t atype) int iPtype = -1; hid_t sign_id, size_id; - if (data_id==H5T_STRING) - { - iPtype=NX_CHAR; - } - if (data_id==H5T_INTEGER) - { - size_id=H5Tget_size(atype); - sign_id=H5Tget_sign(atype); - if (size_id==1) - { - if (sign_id==H5T_SGN_2) - { - iPtype=NX_INT8; - } else { - iPtype=NX_UINT8; - } - } - else if (size_id==2) - { - if (sign_id==H5T_SGN_2) - { - iPtype=NX_INT16; - } else { - iPtype=NX_UINT16; - } - } - else if (size_id==4) - { - if (sign_id==H5T_SGN_2) - { - iPtype=NX_INT32; - } else { - iPtype=NX_UINT32; - } - } - else if(size_id == 8) - { - if (sign_id==H5T_SGN_2) - { - iPtype=NX_INT64; - } else { - iPtype=NX_UINT64; - } - } - } else if (data_id==H5T_FLOAT) - { - size_id=H5Tget_size(atype); - if (size_id==4) - { - iPtype=NX_FLOAT32; - } - else if (size_id==8) - { - iPtype=NX_FLOAT64; - } - } - if (iPtype == -1) - { - NXIReportError (NXpData, "ERROR: hdf5ToNXtype: invalid type"); - } + if (data_id == H5T_STRING) { + iPtype = NX_CHAR; + } + if (data_id == H5T_INTEGER) { + size_id = H5Tget_size(atype); + sign_id = H5Tget_sign(atype); + if (size_id == 1) { + if (sign_id == H5T_SGN_2) { + iPtype = NX_INT8; + } else { + iPtype = NX_UINT8; + } + } else if (size_id == 2) { + if (sign_id == H5T_SGN_2) { + iPtype = NX_INT16; + } else { + iPtype = NX_UINT16; + } + } else if (size_id == 4) { + if (sign_id == H5T_SGN_2) { + iPtype = NX_INT32; + } else { + iPtype = NX_UINT32; + } + } else if (size_id == 8) { + if (sign_id == H5T_SGN_2) { + iPtype = NX_INT64; + } else { + iPtype = NX_UINT64; + } + } + } else if (data_id == H5T_FLOAT) { + size_id = H5Tget_size(atype); + if (size_id == 4) { + iPtype = NX_FLOAT32; + } else if (size_id == 8) { + iPtype = NX_FLOAT64; + } + } + if (iPtype == -1) { + NXIReportError(NXpData, "ERROR: hdf5ToNXtype: invalid type"); + } - return iPtype; + return iPtype; } + /*--------------------------------------------------------------------------*/ static int h5MemType(hid_t atype) { hid_t data_id, size_id, sign_id, memtype_id = -1; - + data_id = H5Tget_class(atype); - if (data_id==H5T_INTEGER) - { - size_id=H5Tget_size(atype); - sign_id=H5Tget_sign(atype); - if (size_id==1) - { - if (sign_id==H5T_SGN_2) - { - memtype_id = H5T_NATIVE_INT8; - } else { - memtype_id = H5T_NATIVE_UINT8; - } - } - else if (size_id==2) - { - if (sign_id==H5T_SGN_2) - { - memtype_id = H5T_NATIVE_INT16; - } else { - memtype_id = H5T_NATIVE_UINT16; - } - } - else if (size_id==4) - { - if (sign_id==H5T_SGN_2) - { - memtype_id = H5T_NATIVE_INT32; - } else { - memtype_id = H5T_NATIVE_UINT32; - } - } - else if (size_id==8) - { - if (sign_id==H5T_SGN_2) - { - memtype_id = H5T_NATIVE_INT64; - } else { - memtype_id = H5T_NATIVE_UINT64; - } - } - } else if (data_id==H5T_FLOAT) - { - size_id=H5Tget_size(atype); - if (size_id==4) - { - memtype_id = H5T_NATIVE_FLOAT; - } else if (size_id==8) { - memtype_id = H5T_NATIVE_DOUBLE; - } - } - if (memtype_id == -1) - { - NXIReportError (NXpData, "ERROR: h5MemType: invalid type"); + if (data_id == H5T_INTEGER) { + size_id = H5Tget_size(atype); + sign_id = H5Tget_sign(atype); + if (size_id == 1) { + if (sign_id == H5T_SGN_2) { + memtype_id = H5T_NATIVE_INT8; + } else { + memtype_id = H5T_NATIVE_UINT8; } - return memtype_id; + } else if (size_id == 2) { + if (sign_id == H5T_SGN_2) { + memtype_id = H5T_NATIVE_INT16; + } else { + memtype_id = H5T_NATIVE_UINT16; + } + } else if (size_id == 4) { + if (sign_id == H5T_SGN_2) { + memtype_id = H5T_NATIVE_INT32; + } else { + memtype_id = H5T_NATIVE_UINT32; + } + } else if (size_id == 8) { + if (sign_id == H5T_SGN_2) { + memtype_id = H5T_NATIVE_INT64; + } else { + memtype_id = H5T_NATIVE_UINT64; + } + } + } else if (data_id == H5T_FLOAT) { + size_id = H5Tget_size(atype); + if (size_id == 4) { + memtype_id = H5T_NATIVE_FLOAT; + } else if (size_id == 8) { + memtype_id = H5T_NATIVE_DOUBLE; + } + } + if (memtype_id == -1) { + NXIReportError(NXpData, "ERROR: h5MemType: invalid type"); + } + return memtype_id; } + /*-------------------------------------------------------------------------*/ - NXstatus NX5getnextentry (NXhandle fid,NXname name, NXname nxclass, int *datatype) - { - pNexusFile5 pFile; - hid_t grp, attr1,type,atype; - int iRet,iPtype, i; - int idx,data_id,size_id, sign_id; - char data[128]; - char ph_name[1024]; - info_type op_data; - int iRet_iNX=-1; - char pBuffer[256]; - - pFile = NXI5assert (fid); - op_data.iname = NULL; +NXstatus NX5getnextentry(NXhandle fid, NXname name, NXname nxclass, + int *datatype) +{ + pNexusFile5 pFile; + hid_t grp, attr1, type, atype; + int iRet, iPtype, i; + int idx, data_id, size_id, sign_id; + char data[128]; + char ph_name[1024]; + info_type op_data; + int iRet_iNX = -1; + char pBuffer[256]; - /* - iterate to next entry in group list - */ - idx=pFile->iStack5[pFile->iStackPtr].iCurrentIDX; - if (strlen(pFile->name_ref) == 0) { - /* root group */ - strcpy(pFile->name_ref,"/"); - } - iRet=H5Giterate(pFile->iFID,pFile->name_ref,&idx,nxgroup_info,&op_data); - strcpy(nxclass, NX_UNKNOWN_GROUP); - - /* - figure out the number of items in the current group. We need this in order to - find out if we are at the end of the search. - */ - if (pFile->iCurrentG == 0) { - pFile->iNX=0; - iRet_iNX = H5Giterate(pFile->iFID,"/",0,group_info1,&pFile->iNX); + pFile = NXI5assert(fid); + op_data.iname = NULL; + + /* + iterate to next entry in group list + */ + idx = pFile->iStack5[pFile->iStackPtr].iCurrentIDX; + if (strlen(pFile->name_ref) == 0) { + /* root group */ + strcpy(pFile->name_ref, "/"); + } + iRet = + H5Giterate(pFile->iFID, pFile->name_ref, &idx, nxgroup_info, + &op_data); + strcpy(nxclass, NX_UNKNOWN_GROUP); + + /* + figure out the number of items in the current group. We need this in order to + find out if we are at the end of the search. + */ + if (pFile->iCurrentG == 0) { + pFile->iNX = 0; + iRet_iNX = H5Giterate(pFile->iFID, "/", 0, group_info1, &pFile->iNX); + } else { + pFile->iNX = 0; + iRet_iNX = + H5Giterate(pFile->iFID, pFile->name_ref, 0, group_info1, + &pFile->iNX); + } + if (idx == pFile->iNX) { + iRet_iNX = 2; + } + + if (iRet > 0) { + pFile->iStack5[pFile->iStackPtr].iCurrentIDX++; + if (op_data.iname != NULL) { + strcpy(name, op_data.iname); + free(op_data.iname); } else { - pFile->iNX=0; - iRet_iNX = H5Giterate(pFile->iFID,pFile->name_ref,0,group_info1, &pFile->iNX); + pFile->iStack5[pFile->iStackPtr].iCurrentIDX = 0; + return NX_EOD; } - if (idx == pFile->iNX) { - iRet_iNX = 2; - } - - if (iRet > 0) - { - pFile->iStack5[pFile->iStackPtr].iCurrentIDX++; - if (op_data.iname != NULL) { - strcpy(name,op_data.iname); - free(op_data.iname); - } else { - pFile->iStack5[pFile->iStackPtr].iCurrentIDX = 0; - return NX_EOD; - } - if (op_data.type == H5G_GROUP) - { - /* - open group and find class name attribute - */ - strcpy(ph_name,""); - for(i = 1; i < (pFile->iStackPtr + 1); i++) - { - strcat(ph_name,pFile->iStack5[i].irefn); - strcat(ph_name,"/"); - } - strcat(ph_name,name); - grp=H5Gopen(pFile->iFID,ph_name); - if (grp < 0) { - sprintf (pBuffer, "ERROR: Group %s does not exist!", ph_name); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - attr1 = H5Aopen_name(grp, "NX_class"); - if (attr1 < 0) { - strcpy(nxclass, NX_UNKNOWN_GROUP); - } else { - type=H5T_C_S1; - atype=H5Tcopy(type); - H5Tset_size(atype,128); - iRet = H5Aread(attr1, atype, data); - strcpy(nxclass,data); - H5Tclose(atype); - H5Aclose(attr1); - } - H5Gclose(grp); - } else if (op_data.type==H5G_DATASET) - { - /* - open dataset and find type - */ - grp=H5Dopen(pFile->iCurrentG,name); - type=H5Dget_type(grp); - atype=H5Tcopy(type); - data_id = H5Tget_class(atype); - iPtype = hdf5ToNXType(data_id, atype); - *datatype=iPtype; - strcpy(nxclass, "SDS"); - H5Tclose(atype); - H5Tclose(type); - H5Dclose(grp); - } - return NX_OK; - } - else - { - /* - we are at the end of the search: clear the data structure and reset - iCurrentIDX to 0 - */ - if (iRet_iNX == 2) { - if (op_data.iname != NULL) { - free(op_data.iname); - } - pFile->iStack5[pFile->iStackPtr].iCurrentIDX = 0; - return NX_EOD; - } - if (op_data.iname != NULL) { - free(op_data.iname); - } - NXIReportError (NXpData, - "ERROR: Iteration (directory) was not successful"); - return NX_ERROR; - } - } + if (op_data.type == H5G_GROUP) { + /* + open group and find class name attribute + */ + strcpy(ph_name, ""); + for (i = 1; i < (pFile->iStackPtr + 1); i++) { + strcat(ph_name, pFile->iStack5[i].irefn); + strcat(ph_name, "/"); + } + strcat(ph_name, name); + grp = H5Gopen(pFile->iFID, ph_name); + if (grp < 0) { + sprintf(pBuffer, "ERROR: Group %s does not exist!", ph_name); + NXIReportError(NXpData, pBuffer); + return NX_ERROR; + } + attr1 = H5Aopen_name(grp, "NX_class"); + if (attr1 < 0) { + strcpy(nxclass, NX_UNKNOWN_GROUP); + } else { + type = H5T_C_S1; + atype = H5Tcopy(type); + H5Tset_size(atype, 128); + iRet = H5Aread(attr1, atype, data); + strcpy(nxclass, data); + H5Tclose(atype); + H5Aclose(attr1); + } + H5Gclose(grp); + } else if (op_data.type == H5G_DATASET) { + /* + open dataset and find type + */ + grp = H5Dopen(pFile->iCurrentG, name); + type = H5Dget_type(grp); + atype = H5Tcopy(type); + data_id = H5Tget_class(atype); + iPtype = hdf5ToNXType(data_id, atype); + *datatype = iPtype; + strcpy(nxclass, "SDS"); + H5Tclose(atype); + H5Tclose(type); + H5Dclose(grp); + } + return NX_OK; + } else { + /* + we are at the end of the search: clear the data structure and reset + iCurrentIDX to 0 + */ + if (iRet_iNX == 2) { + if (op_data.iname != NULL) { + free(op_data.iname); + } + pFile->iStack5[pFile->iStackPtr].iCurrentIDX = 0; + return NX_EOD; + } + if (op_data.iname != NULL) { + free(op_data.iname); + } + NXIReportError(NXpData, + "ERROR: Iteration (directory) was not successful"); + return NX_ERROR; + } +} /*-------------------------------------------------------------------------*/ - NXstatus NX5getdata (NXhandle fid, void *data) - { - pNexusFile5 pFile; - int iStart[H5S_MAX_RANK], status; - hid_t data_id, memtype_id, size_id, sign_id; - int dims; +NXstatus NX5getdata(NXhandle fid, void *data) +{ + pNexusFile5 pFile; + int iStart[H5S_MAX_RANK], status; + hid_t data_id, memtype_id, size_id, sign_id; + int dims; - pFile = NXI5assert (fid); - /* check if there is an Dataset open */ - if (pFile->iCurrentD == 0) - { - NXIReportError (NXpData, "ERROR: no Dataset open"); - return NX_ERROR; - } - memset (iStart, 0, H5S_MAX_RANK * sizeof(int)); - /* map datatypes of other plateforms */ - data_id = H5Tget_class(pFile->iCurrentT); - if (data_id==H5T_STRING) - { - dims = H5Tget_size(pFile->iCurrentT); - memtype_id = H5Tcopy(H5T_C_S1); - H5Tset_size(memtype_id, dims); - } - else - { - memtype_id = h5MemType(pFile->iCurrentT); - } + pFile = NXI5assert(fid); + /* check if there is an Dataset open */ + if (pFile->iCurrentD == 0) { + NXIReportError(NXpData, "ERROR: no Dataset open"); + return NX_ERROR; + } + memset(iStart, 0, H5S_MAX_RANK * sizeof(int)); + /* map datatypes of other plateforms */ + data_id = H5Tget_class(pFile->iCurrentT); + if (data_id == H5T_STRING) { + dims = H5Tget_size(pFile->iCurrentT); + memtype_id = H5Tcopy(H5T_C_S1); + H5Tset_size(memtype_id, dims); + } else { + memtype_id = h5MemType(pFile->iCurrentT); + } - /* actually read */ - status = H5Dread (pFile->iCurrentD, memtype_id, - H5S_ALL, H5S_ALL,H5P_DEFAULT, data); - if(data_id == H5T_STRING) - { - H5Tclose(memtype_id); - } - if(status < 0) - { - NXIReportError (NXpData, "ERROR: failed to transfer dataset"); - return NX_ERROR; + /* actually read */ + status = H5Dread(pFile->iCurrentD, memtype_id, + H5S_ALL, H5S_ALL, H5P_DEFAULT, data); + if (data_id == H5T_STRING) { + H5Tclose(memtype_id); + } + if (status < 0) { + NXIReportError(NXpData, "ERROR: failed to transfer dataset"); + return NX_ERROR; - } - return NX_OK; - } + } + return NX_OK; +} /*-------------------------------------------------------------------------*/ - NXstatus NX5getinfo (NXhandle fid, int *rank, int dimension[], int *iType) - { - pNexusFile5 pFile; - int i, iRank, mType, iRet; - hsize_t myDim[H5S_MAX_RANK]; - hid_t data_id,size_id,sign_id; +NXstatus NX5getinfo(NXhandle fid, int *rank, int dimension[], int *iType) +{ + pNexusFile5 pFile; + int i, iRank, mType, iRet; + hsize_t myDim[H5S_MAX_RANK]; + hid_t data_id, size_id, sign_id; - pFile = NXI5assert (fid); - /* check if there is an Dataset open */ - if (pFile->iCurrentD == 0) { - NXIReportError (NXpData, "ERROR: no Dataset open"); - return NX_ERROR; - } + pFile = NXI5assert(fid); + /* check if there is an Dataset open */ + if (pFile->iCurrentD == 0) { + NXIReportError(NXpData, "ERROR: no Dataset open"); + return NX_ERROR; + } - /* read information */ - data_id = H5Tget_class(pFile->iCurrentT); - mType = hdf5ToNXType(data_id,pFile->iCurrentT); - iRank = H5Sget_simple_extent_ndims(pFile->iCurrentS); - iRet = H5Sget_simple_extent_dims(pFile->iCurrentS, myDim, NULL); - /* conversion to proper ints for the platform */ - *iType = (int)mType; - if (data_id==H5T_STRING && myDim[iRank-1] == 1) { - myDim[iRank-1] = H5Tget_size(pFile->iCurrentT); - } - *rank = (int)iRank; - for (i = 0; i < iRank; i++) - { - dimension[i] = (int)myDim[i]; - } - return NX_OK; - } + /* read information */ + data_id = H5Tget_class(pFile->iCurrentT); + mType = hdf5ToNXType(data_id, pFile->iCurrentT); + iRank = H5Sget_simple_extent_ndims(pFile->iCurrentS); + iRet = H5Sget_simple_extent_dims(pFile->iCurrentS, myDim, NULL); + /* conversion to proper ints for the platform */ + *iType = (int) mType; + if (data_id == H5T_STRING && myDim[iRank - 1] == 1) { + myDim[iRank - 1] = H5Tget_size(pFile->iCurrentT); + } + *rank = (int) iRank; + for (i = 0; i < iRank; i++) { + dimension[i] = (int) myDim[i]; + } + return NX_OK; +} /*-------------------------------------------------------------------------*/ - NXstatus NX5getslab (NXhandle fid, void *data, int iStart[], int iSize[]) - { - pNexusFile5 pFile; - hsize_t myStart[H5S_MAX_RANK]; - hsize_t mySize[H5S_MAX_RANK]; - hsize_t mStart[H5S_MAX_RANK]; - hid_t memspace, iRet, data_id; - hid_t memtype_id, size_id, sign_id; - char *tmp_data = NULL; - char *data1; - int i, dims, iRank, mtype = 0; +NXstatus NX5getslab(NXhandle fid, void *data, int iStart[], int iSize[]) +{ + pNexusFile5 pFile; + hsize_t myStart[H5S_MAX_RANK]; + hsize_t mySize[H5S_MAX_RANK]; + hsize_t mStart[H5S_MAX_RANK]; + hid_t memspace, iRet, data_id; + hid_t memtype_id, size_id, sign_id; + char *tmp_data = NULL; + char *data1; + int i, dims, iRank, mtype = 0; - pFile = NXI5assert (fid); - /* check if there is an Dataset open */ - if (pFile->iCurrentD == 0) - { - NXIReportError (NXpData, "ERROR: no Dataset open"); - return NX_ERROR; - } - iRank = H5Sget_simple_extent_ndims(pFile->iCurrentS); - for (i = 0; i < iRank; i++) - { - myStart[i] = (hssize_t)iStart[i]; - mySize[i] = (hsize_t)iSize[i]; - mStart[i] = (hsize_t)0; - } - data_id = H5Tget_class(pFile->iCurrentT); - if (data_id == H5T_STRING) { + pFile = NXI5assert(fid); + /* check if there is an Dataset open */ + if (pFile->iCurrentD == 0) { + NXIReportError(NXpData, "ERROR: no Dataset open"); + return NX_ERROR; + } + iRank = H5Sget_simple_extent_ndims(pFile->iCurrentS); + for (i = 0; i < iRank; i++) { + myStart[i] = (hssize_t) iStart[i]; + mySize[i] = (hsize_t) iSize[i]; + mStart[i] = (hsize_t) 0; + } + data_id = H5Tget_class(pFile->iCurrentT); + if (data_id == H5T_STRING) { /* * FAA 24/1/2007: I don't think this will work for multidimensional * string arrays. * MK 23/7/2007: You are right Freddie. */ - mtype = NX_CHAR; - if (mySize[0] == 1) { - mySize[0] = H5Tget_size(pFile->iCurrentT); - } - tmp_data = (char*) malloc(mySize[0]); - memset(tmp_data,0,sizeof(mySize[0])); - iRet = H5Sselect_hyperslab(pFile->iCurrentS, H5S_SELECT_SET, mStart, - NULL, mySize, NULL); - } else { - iRet = H5Sselect_hyperslab(pFile->iCurrentS, H5S_SELECT_SET, myStart, - NULL, mySize, NULL); - } - /* define slab */ - /* deal with HDF errors */ - if (iRet < 0) - { - NXIReportError (NXpData, "ERROR: selecting slab failed"); - return NX_ERROR; - } + mtype = NX_CHAR; + if (mySize[0] == 1) { + mySize[0] = H5Tget_size(pFile->iCurrentT); + } + tmp_data = (char *) malloc(mySize[0]); + memset(tmp_data, 0, sizeof(mySize[0])); + iRet = H5Sselect_hyperslab(pFile->iCurrentS, H5S_SELECT_SET, mStart, + NULL, mySize, NULL); + } else { + iRet = H5Sselect_hyperslab(pFile->iCurrentS, H5S_SELECT_SET, myStart, + NULL, mySize, NULL); + } + /* define slab */ + /* deal with HDF errors */ + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: selecting slab failed"); + return NX_ERROR; + } - memspace=H5Screate_simple(iRank, mySize, NULL); - iRet = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, mStart, - NULL, mySize, NULL); - if (iRet < 0) - { - NXIReportError (NXpData, "ERROR: Select memspace failed"); - return NX_ERROR; - } - /* map datatypes of other plateforms */ - if (data_id==H5T_STRING) - { - dims = H5Tget_size(pFile->iCurrentT); - memtype_id = H5Tcopy(H5T_C_S1); - H5Tset_size(memtype_id, dims); - } - else - { - memtype_id = h5MemType(pFile->iCurrentT); - } + memspace = H5Screate_simple(iRank, mySize, NULL); + iRet = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, mStart, + NULL, mySize, NULL); + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: Select memspace failed"); + return NX_ERROR; + } + /* map datatypes of other plateforms */ + if (data_id == H5T_STRING) { + dims = H5Tget_size(pFile->iCurrentT); + memtype_id = H5Tcopy(H5T_C_S1); + H5Tset_size(memtype_id, dims); + } else { + memtype_id = h5MemType(pFile->iCurrentT); + } - /* read slab */ - if (mtype == NX_CHAR) { - iRet = H5Dread(pFile->iCurrentD, memtype_id, H5S_ALL, - H5S_ALL, H5P_DEFAULT,tmp_data); - data1 = tmp_data + myStart[0]; - strncpy(data,data1,(hsize_t)iSize[0]); - free(tmp_data); - } else { - iRet = H5Dread(pFile->iCurrentD, memtype_id, memspace, - pFile->iCurrentS, H5P_DEFAULT,data); - } + /* read slab */ + if (mtype == NX_CHAR) { + iRet = H5Dread(pFile->iCurrentD, memtype_id, H5S_ALL, + H5S_ALL, H5P_DEFAULT, tmp_data); + data1 = tmp_data + myStart[0]; + strncpy(data, data1, (hsize_t) iSize[0]); + free(tmp_data); + } else { + iRet = H5Dread(pFile->iCurrentD, memtype_id, memspace, + pFile->iCurrentS, H5P_DEFAULT, data); + } - if (iRet < 0) - { - NXIReportError (NXpData, "ERROR: Reading slab failed"); - return NX_ERROR; - } - return NX_OK; - } + if (iRet < 0) { + NXIReportError(NXpData, "ERROR: Reading slab failed"); + return NX_ERROR; + } + return NX_OK; +} /*-------------------------------------------------------------------------*/ /* Operator function. */ - herr_t attr_info(hid_t loc_id, const char *name, void *opdata) - { - *((char**)opdata)=strdup(name); - return 1; - } +herr_t attr_info(hid_t loc_id, const char *name, void *opdata) +{ + *((char **) opdata) = strdup(name); + return 1; +} - NXstatus NX5getnextattr (NXhandle fileid, NXname pName, - int *iLength, int *iType) - { - pNexusFile5 pFile; - hid_t attr_id,size_id,sign_id; - hid_t iRet, atype, aspace; - int iPType,rank; - char *iname = NULL; - unsigned int idx; - int intern_idx=-1; - int vid; +NXstatus NX5getnextattr(NXhandle fileid, NXname pName, + int *iLength, int *iType) +{ + pNexusFile5 pFile; + hid_t attr_id, size_id, sign_id; + hid_t iRet, atype, aspace; + int iPType, rank; + char *iname = NULL; + unsigned int idx; + int intern_idx = -1; + int vid; - pFile = NXI5assert (fileid); + pFile = NXI5assert(fileid); - vid = getAttVID(pFile); + vid = getAttVID(pFile); - idx=pFile->iAtt5.iCurrentIDX; - iRet=0; - intern_idx=H5Aget_num_attrs(vid); - if(intern_idx == idx) { - killAttVID(pFile,vid); - return NX_EOD; - } + idx = pFile->iAtt5.iCurrentIDX; + iRet = 0; + intern_idx = H5Aget_num_attrs(vid); + if (intern_idx == idx) { + killAttVID(pFile, vid); + return NX_EOD; + } - if (intern_idx > idx) { - iRet=H5Aiterate(vid,&idx,attr_info,&iname); - } else { - iRet=0; - } - intern_idx=-1; - if (iRet < 0) { - NXIReportError (NXpData, "ERROR iterating through attribute list!"); - killAttVID(pFile,vid); - return NX_ERROR; - } - pFile->iAtt5.iCurrentIDX++; - if (iname != NULL) { - if(strcmp(iname, "NX_class") == 0 && pFile->iCurrentG != 0) { - /* - skip NXclass attribute which is internal - */ - killAttVID(pFile, vid); - return NX5getnextattr(fileid, pName, iLength, iType); - } - strcpy(pName, iname); - free(iname); - iname = NULL; - } else { - strcpy(pName,"What is this?"); - } - pFile->iCurrentA = H5Aopen_name(vid, pName); - atype = H5Aget_type(pFile->iCurrentA); - aspace = H5Aget_space(pFile->iCurrentA); - rank = H5Sget_simple_extent_ndims(aspace); - attr_id = H5Tget_class(atype); - if (attr_id==H5T_STRING) { - iPType=NX_CHAR; - rank = H5Tget_size(atype); - } - if (rank == 0) { - rank++; - } - iPType = hdf5ToNXType(attr_id,atype); - *iType=iPType; - *iLength=rank; - H5Tclose(atype); - H5Sclose(aspace); - H5Aclose(pFile->iCurrentA); - - intern_idx=H5Aget_num_attrs(vid); + if (intern_idx > idx) { + iRet = H5Aiterate(vid, &idx, attr_info, &iname); + } else { + iRet = 0; + } + intern_idx = -1; + if (iRet < 0) { + NXIReportError(NXpData, "ERROR iterating through attribute list!"); + killAttVID(pFile, vid); + return NX_ERROR; + } + pFile->iAtt5.iCurrentIDX++; + if (iname != NULL) { + if (strcmp(iname, "NX_class") == 0 && pFile->iCurrentG != 0) { + /* + skip NXclass attribute which is internal + */ + killAttVID(pFile, vid); + return NX5getnextattr(fileid, pName, iLength, iType); + } + strcpy(pName, iname); + free(iname); + iname = NULL; + } else { + strcpy(pName, "What is this?"); + } + pFile->iCurrentA = H5Aopen_name(vid, pName); + atype = H5Aget_type(pFile->iCurrentA); + aspace = H5Aget_space(pFile->iCurrentA); + rank = H5Sget_simple_extent_ndims(aspace); + attr_id = H5Tget_class(atype); + if (attr_id == H5T_STRING) { + iPType = NX_CHAR; + rank = H5Tget_size(atype); + } + if (rank == 0) { + rank++; + } + iPType = hdf5ToNXType(attr_id, atype); + *iType = iPType; + *iLength = rank; + H5Tclose(atype); + H5Sclose(aspace); + H5Aclose(pFile->iCurrentA); + + intern_idx = H5Aget_num_attrs(vid); + + killAttVID(pFile, vid); + return NX_OK; +} - killAttVID(pFile,vid); - return NX_OK; - } /*-------------------------------------------------------------------------*/ - NXstatus NX5getattr (NXhandle fid, char *name, - void *data, int* datalen, int* iType) - { - pNexusFile5 pFile; - int iNew, iRet, vid; - hid_t type, atype = -1, glob; - char pBuffer[256]; +NXstatus NX5getattr(NXhandle fid, char *name, + void *data, int *datalen, int *iType) +{ + pNexusFile5 pFile; + int iNew, iRet, vid; + hid_t type, atype = -1, glob; + char pBuffer[256]; - pFile = NXI5assert (fid); - type = *iType; - glob = 0; + pFile = NXI5assert(fid); + type = *iType; + glob = 0; - type = nxToHDF5Type(type); + type = nxToHDF5Type(type); - vid = getAttVID(pFile); - iNew = H5Aopen_name(vid, name); - if (iNew < 0) { - sprintf (pBuffer, "ERROR: attribute %s not found", name); - killAttVID(pFile,vid); - NXIReportError (NXpData, pBuffer); - return NX_ERROR; - } - pFile->iCurrentA = iNew; - /* finally read the data */ - if (type==H5T_C_S1) - { - atype=H5Tcopy(type); - H5Tset_size(atype,*datalen); - iRet = H5Aread(pFile->iCurrentA, atype, data); - *datalen=strlen(data); - } else { - iRet = H5Aread(pFile->iCurrentA, type, data); - *datalen=1; - } - - if (iRet < 0) { - sprintf (pBuffer, "ERROR: HDF could not read attribute data"); - NXIReportError (NXpData, pBuffer); - killAttVID(pFile,vid); - return NX_ERROR; - } - - iRet = H5Aclose(pFile->iCurrentA); - - killAttVID(pFile,vid); - if (type==H5T_C_S1) - { - H5Tclose(atype); - } - return NX_OK; - } - - /*-------------------------------------------------------------------------*/ - - NXstatus NX5getattrinfo (NXhandle fid, int *iN) - { - pNexusFile5 pFile; - char *iname = NULL; - unsigned int idx; - int vid; - herr_t iRet; - - pFile = NXI5assert (fid); - idx=0; - *iN = idx; - - vid = getAttVID(pFile); - - idx=H5Aget_num_attrs(vid); - if (idx > 0) { - if(pFile->iCurrentG > 0 && pFile->iCurrentD == 0){ - *iN = idx -1; - } else { - *iN = idx; - } - } else { - *iN = 0; - } - killAttVID(pFile,vid); - return NX_OK; - } - - - /*-------------------------------------------------------------------------*/ - NXstatus NX5getgroupID (NXhandle fileid, NXlink* sRes) - { - pNexusFile5 pFile; - int u, datalen, type = NX_CHAR; - char group_name[64], class_name[64]; - ErrFunc oldErr; - - pFile = NXI5assert (fileid); - if (pFile->iCurrentG == 0) { - return NX_ERROR; - } - else { - /* - this means: if the item is already linked: use the target attribute, else - the path to the current node - */ - oldErr = NXMGetError(); - NXMSetError(NXpData, ignoreError); - datalen = 1024; - memset(sRes->targetPath,0,datalen*sizeof(char)); - if(NX5getattr(fileid,"target",sRes->targetPath,&datalen,&type) != NX_OK){ - buildCurrentPath(pFile,sRes->targetPath,1024); - } - NXMSetError(NXpData,oldErr); - sRes->linkType = 0; - return NX_OK; - } - /* not reached */ + vid = getAttVID(pFile); + iNew = H5Aopen_name(vid, name); + if (iNew < 0) { + sprintf(pBuffer, "ERROR: attribute %s not found", name); + killAttVID(pFile, vid); + NXIReportError(NXpData, pBuffer); return NX_ERROR; - } - + } + pFile->iCurrentA = iNew; + /* finally read the data */ + if (type == H5T_C_S1) { + atype = H5Tcopy(type); + H5Tset_size(atype, *datalen); + iRet = H5Aread(pFile->iCurrentA, atype, data); + *datalen = strlen(data); + } else { + iRet = H5Aread(pFile->iCurrentA, type, data); + *datalen = 1; + } + + if (iRet < 0) { + sprintf(pBuffer, "ERROR: HDF could not read attribute data"); + NXIReportError(NXpData, pBuffer); + killAttVID(pFile, vid); + return NX_ERROR; + } + + iRet = H5Aclose(pFile->iCurrentA); + + killAttVID(pFile, vid); + if (type == H5T_C_S1) { + H5Tclose(atype); + } + return NX_OK; +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NX5getattrinfo(NXhandle fid, int *iN) +{ + pNexusFile5 pFile; + char *iname = NULL; + unsigned int idx; + int vid; + herr_t iRet; + + pFile = NXI5assert(fid); + idx = 0; + *iN = idx; + + vid = getAttVID(pFile); + + idx = H5Aget_num_attrs(vid); + if (idx > 0) { + if (pFile->iCurrentG > 0 && pFile->iCurrentD == 0) { + *iN = idx - 1; + } else { + *iN = idx; + } + } else { + *iN = 0; + } + killAttVID(pFile, vid); + return NX_OK; +} + + + /*-------------------------------------------------------------------------*/ +NXstatus NX5getgroupID(NXhandle fileid, NXlink * sRes) +{ + pNexusFile5 pFile; + int u, datalen, type = NX_CHAR; + char group_name[64], class_name[64]; + ErrFunc oldErr; + + pFile = NXI5assert(fileid); + if (pFile->iCurrentG == 0) { + return NX_ERROR; + } else { + /* + this means: if the item is already linked: use the target attribute, else + the path to the current node + */ + oldErr = NXMGetError(); + NXMSetError(NXpData, ignoreError); + datalen = 1024; + memset(sRes->targetPath, 0, datalen * sizeof(char)); + if (NX5getattr(fileid, "target", sRes->targetPath, &datalen, &type) != + NX_OK) { + buildCurrentPath(pFile, sRes->targetPath, 1024); + } + NXMSetError(NXpData, oldErr); + sRes->linkType = 0; + return NX_OK; + } + /* not reached */ + return NX_ERROR; +} + /* ------------------------------------------------------------------- */ - NXstatus NX5sameID (NXhandle fileid, NXlink* pFirstID, NXlink* pSecondID) - { - pNexusFile5 pFile; +NXstatus NX5sameID(NXhandle fileid, NXlink * pFirstID, NXlink * pSecondID) +{ + pNexusFile5 pFile; - pFile = NXI5assert (fileid); - if ((strcmp(pFirstID->targetPath,pSecondID->targetPath) == 0)){ - return NX_OK; - } else { - return NX_ERROR; - } - } - - /*-------------------------------------------------------------------------*/ - - NXstatus NX5initattrdir (NXhandle fid) - { - pNexusFile5 pFile; - - pFile = NXI5assert (fid); - NXI5KillAttDir (fid); + pFile = NXI5assert(fileid); + if ((strcmp(pFirstID->targetPath, pSecondID->targetPath) == 0)) { return NX_OK; + } else { + return NX_ERROR; } +} + + /*-------------------------------------------------------------------------*/ + +NXstatus NX5initattrdir(NXhandle fid) +{ + pNexusFile5 pFile; + + pFile = NXI5assert(fid); + NXI5KillAttDir(fid); + return NX_OK; +} /*-------------------------------------------------------------------------*/ - - NXstatus NX5initgroupdir (NXhandle fid) - { - pNexusFile5 pFile; - - pFile = NXI5assert (fid); - NXI5KillDir (fid); - return NX_OK; - } + +NXstatus NX5initgroupdir(NXhandle fid) +{ + pNexusFile5 pFile; + + pFile = NXI5assert(fid); + NXI5KillDir(fid); + return NX_OK; +} + /*------------------------------------------------------------------------*/ void NX5assignFunctions(pNexusFunction fHandle) { - fHandle->nxclose=NX5close; - fHandle->nxflush=NX5flush; - fHandle->nxmakegroup=NX5makegroup; - fHandle->nxopengroup=NX5opengroup; - fHandle->nxclosegroup=NX5closegroup; - fHandle->nxmakedata=NX5makedata; - fHandle->nxcompmakedata=NX5compmakedata; - fHandle->nxcompress=NX5compress; - fHandle->nxopendata=NX5opendata; - fHandle->nxclosedata=NX5closedata; - fHandle->nxputdata=NX5putdata; - fHandle->nxputattr=NX5putattr; - fHandle->nxputslab=NX5putslab; - fHandle->nxgetdataID=NX5getdataID; - fHandle->nxmakelink=NX5makelink; - fHandle->nxmakenamedlink=NX5makenamedlink; - fHandle->nxgetdata=NX5getdata; - fHandle->nxgetinfo=NX5getinfo; - fHandle->nxgetnextentry=NX5getnextentry; - fHandle->nxgetslab=NX5getslab; - fHandle->nxgetnextattr=NX5getnextattr; - fHandle->nxgetattr=NX5getattr; - fHandle->nxgetattrinfo=NX5getattrinfo; - fHandle->nxgetgroupID=NX5getgroupID; - fHandle->nxgetgroupinfo=NX5getgroupinfo; - fHandle->nxsameID=NX5sameID; - fHandle->nxinitgroupdir=NX5initgroupdir; - fHandle->nxinitattrdir=NX5initattrdir; - fHandle->nxprintlink=NX5printlink; + fHandle->nxclose = NX5close; + fHandle->nxflush = NX5flush; + fHandle->nxmakegroup = NX5makegroup; + fHandle->nxopengroup = NX5opengroup; + fHandle->nxclosegroup = NX5closegroup; + fHandle->nxmakedata = NX5makedata; + fHandle->nxcompmakedata = NX5compmakedata; + fHandle->nxcompress = NX5compress; + fHandle->nxopendata = NX5opendata; + fHandle->nxclosedata = NX5closedata; + fHandle->nxputdata = NX5putdata; + fHandle->nxputattr = NX5putattr; + fHandle->nxputslab = NX5putslab; + fHandle->nxgetdataID = NX5getdataID; + fHandle->nxmakelink = NX5makelink; + fHandle->nxmakenamedlink = NX5makenamedlink; + fHandle->nxgetdata = NX5getdata; + fHandle->nxgetinfo = NX5getinfo; + fHandle->nxgetnextentry = NX5getnextentry; + fHandle->nxgetslab = NX5getslab; + fHandle->nxgetnextattr = NX5getnextattr; + fHandle->nxgetattr = NX5getattr; + fHandle->nxgetattrinfo = NX5getattrinfo; + fHandle->nxgetgroupID = NX5getgroupID; + fHandle->nxgetgroupinfo = NX5getgroupinfo; + fHandle->nxsameID = NX5sameID; + fHandle->nxinitgroupdir = NX5initgroupdir; + fHandle->nxinitattrdir = NX5initattrdir; + fHandle->nxprintlink = NX5printlink; } diff --git a/napi5.h b/napi5.h index 61d67315..2ee47d98 100644 --- a/napi5.h +++ b/napi5.h @@ -4,45 +4,58 @@ /* HDF5 interface */ -extern NXstatus NX5open(CONSTCHAR *filename, NXaccess access_method, NXhandle* pHandle); -extern NXstatus NX5close(NXhandle* pHandle); -extern NXstatus NX5flush(NXhandle* pHandle); - -extern NXstatus NX5makegroup (NXhandle handle, CONSTCHAR *name, CONSTCHAR* NXclass); -extern NXstatus NX5opengroup (NXhandle handle, CONSTCHAR *name, CONSTCHAR* NXclass); -extern NXstatus NX5closegroup(NXhandle handle); - -extern NXstatus NX5makedata (NXhandle handle, CONSTCHAR* label, int datatype, int rank, int dim[]); -extern NXstatus NX5compmakedata (NXhandle handle, CONSTCHAR* label, int datatype, int rank, int dim[], int comp_typ, int bufsize[]); -extern NXstatus NX5compress (NXhandle handle, int compr_type); -extern NXstatus NX5opendata (NXhandle handle, CONSTCHAR* label); -extern NXstatus NX5closedata(NXhandle handle); -extern NXstatus NX5putdata(NXhandle handle, void* data); +extern NXstatus NX5open(CONSTCHAR * filename, NXaccess access_method, + NXhandle * pHandle); +extern NXstatus NX5close(NXhandle * pHandle); +extern NXstatus NX5flush(NXhandle * pHandle); -extern NXstatus NX5putattr(NXhandle handle, CONSTCHAR* name, void* data, int iDataLen, int iType); -extern NXstatus NX5putslab(NXhandle handle, void* data, int start[], int size[]); +extern NXstatus NX5makegroup(NXhandle handle, CONSTCHAR * name, + CONSTCHAR * NXclass); +extern NXstatus NX5opengroup(NXhandle handle, CONSTCHAR * name, + CONSTCHAR * NXclass); +extern NXstatus NX5closegroup(NXhandle handle); -extern NXstatus NX5getdataID(NXhandle handle, NXlink* pLink); -extern NXstatus NX5makelink(NXhandle handle, NXlink* pLink); -extern NXstatus NX5printlink(NXhandle handle, NXlink* pLink); +extern NXstatus NX5makedata(NXhandle handle, CONSTCHAR * label, + int datatype, int rank, int dim[]); +extern NXstatus NX5compmakedata(NXhandle handle, CONSTCHAR * label, + int datatype, int rank, int dim[], + int comp_typ, int bufsize[]); +extern NXstatus NX5compress(NXhandle handle, int compr_type); +extern NXstatus NX5opendata(NXhandle handle, CONSTCHAR * label); +extern NXstatus NX5closedata(NXhandle handle); +extern NXstatus NX5putdata(NXhandle handle, void *data); -extern NXstatus NX5getdata(NXhandle handle, void* data); -extern NXstatus NX5getinfo(NXhandle handle, int* rank, int dimension[], int* datatype); -extern NXstatus NX5getnextentry(NXhandle handle, NXname name, NXname nxclass, int* datatype); +extern NXstatus NX5putattr(NXhandle handle, CONSTCHAR * name, void *data, + int iDataLen, int iType); +extern NXstatus NX5putslab(NXhandle handle, void *data, int start[], + int size[]); -extern NXstatus NX5getslab(NXhandle handle, void* data, int start[], int size[]); -extern NXstatus NX5getnextattr(NXhandle handle, NXname pName, int *iLength, int *iType); -extern NXstatus NX5getattr(NXhandle handle, char* name, void* data, int* iDataLen, int* iType); -extern NXstatus NX5getattrinfo(NXhandle handle, int* no_items); -extern NXstatus NX5getgroupID(NXhandle handle, NXlink* pLink); -extern NXstatus NX5getgroupinfo(NXhandle handle, int* no_items, NXname name, NXname nxclass); +extern NXstatus NX5getdataID(NXhandle handle, NXlink * pLink); +extern NXstatus NX5makelink(NXhandle handle, NXlink * pLink); +extern NXstatus NX5printlink(NXhandle handle, NXlink * pLink); -extern NXstatus NX5initgroupdir(NXhandle handle); -extern NXstatus NX5initattrdir(NXhandle handle); +extern NXstatus NX5getdata(NXhandle handle, void *data); +extern NXstatus NX5getinfo(NXhandle handle, int *rank, int dimension[], + int *datatype); +extern NXstatus NX5getnextentry(NXhandle handle, NXname name, + NXname nxclass, int *datatype); + +extern NXstatus NX5getslab(NXhandle handle, void *data, int start[], + int size[]); +extern NXstatus NX5getnextattr(NXhandle handle, NXname pName, int *iLength, + int *iType); +extern NXstatus NX5getattr(NXhandle handle, char *name, void *data, + int *iDataLen, int *iType); +extern NXstatus NX5getattrinfo(NXhandle handle, int *no_items); +extern NXstatus NX5getgroupID(NXhandle handle, NXlink * pLink); +extern NXstatus NX5getgroupinfo(NXhandle handle, int *no_items, + NXname name, NXname nxclass); + +extern NXstatus NX5initgroupdir(NXhandle handle); +extern NXstatus NX5initattrdir(NXhandle handle); void NX5assignFunctions(pNexusFunction fHandle); herr_t nxgroup_info(hid_t loc_id, const char *name, void *op_data); herr_t attr_info(hid_t loc_id, const char *name, void *opdata); herr_t group_info(hid_t loc_id, const char *name, void *opdata); - diff --git a/napiconfig.h b/napiconfig.h index 5b238331..e2608f3b 100755 --- a/napiconfig.h +++ b/napiconfig.h @@ -9,14 +9,14 @@ #ifdef HAVE_STDINT_H #include #else -typedef signed char int8_t; -typedef short int int16_t; -typedef int int32_t; -typedef long int64_t; -typedef unsigned char uint8_t; -typedef unsigned short int uint16_t; -typedef unsigned int uint32_t; -typedef unsigned long uint64_t; +typedef signed char int8_t; +typedef short int int16_t; +typedef int int32_t; +typedef long int64_t; +typedef unsigned char uint8_t; +typedef unsigned short int uint16_t; +typedef unsigned int uint32_t; +typedef unsigned long uint64_t; -#endif /* HAVE_STDINT_H */ -#endif /* NAPICONFIG_H */ +#endif /* HAVE_STDINT_H */ +#endif /* NAPICONFIG_H */ diff --git a/napiu.c b/napiu.c index 18f68e6c..2f40cab3 100644 --- a/napiu.c +++ b/napiu.c @@ -21,10 +21,10 @@ For further information, see - $Id: napiu.c,v 1.2 2008/01/03 09:56:56 koennecke Exp $ + $Id: napiu.c,v 1.3 2009/02/13 09:00:20 koennecke Exp $ ----------------------------------------------------------------------------*/ -static const char* rscid = "$Id: napiu.c,v 1.2 2008/01/03 09:56:56 koennecke Exp $"; /* Revision interted by CVS */ +static const char *rscid = "$Id: napiu.c,v 1.3 2009/02/13 09:00:20 koennecke Exp $"; /* Revision interted by CVS */ #include #include @@ -41,120 +41,130 @@ static const char* rscid = "$Id: napiu.c,v 1.2 2008/01/03 09:56:56 koennecke Exp } \ } - NXstatus NXUwriteglobals(NXhandle file_id, const char* user, const char* affiliation, const char* address, const char* telephone_number, const char* fax_number, const char* email) - { - DO_GLOBAL(user); - DO_GLOBAL(affiliation); - DO_GLOBAL(address); - DO_GLOBAL(telephone_number); - DO_GLOBAL(fax_number); - DO_GLOBAL(email); - return NX_OK; - } +NXstatus NXUwriteglobals(NXhandle file_id, const char *user, + const char *affiliation, const char *address, + const char *telephone_number, + const char *fax_number, const char *email) +{ + DO_GLOBAL(user); + DO_GLOBAL(affiliation); + DO_GLOBAL(address); + DO_GLOBAL(telephone_number); + DO_GLOBAL(fax_number); + DO_GLOBAL(email); + return NX_OK; +} /* NXUwritegroup creates and leaves open a group */ - NXstatus NXUwritegroup(NXhandle file_id, const char* group_name, const char* group_class) - { - int status; - status = NXmakegroup(file_id, group_name, group_class); - if (status == NX_OK) - { - status = NXopengroup(file_id, group_name, group_class); - } - return status; - } +NXstatus NXUwritegroup(NXhandle file_id, const char *group_name, + const char *group_class) +{ + int status; + status = NXmakegroup(file_id, group_name, group_class); + if (status == NX_OK) { + status = NXopengroup(file_id, group_name, group_class); + } + return status; +} - NXstatus NXUwritedata(NXhandle file_id, const char* data_name, const void* data, int data_type, int rank, const int dim[], const char* units, const int start[], const int size[]) - { - return NX_OK; - } +NXstatus NXUwritedata(NXhandle file_id, const char *data_name, + const void *data, int data_type, int rank, + const int dim[], const char *units, + const int start[], const int size[]) +{ + return NX_OK; +} - NXstatus NXUreaddata(NXhandle file_id, const char* data_name, void* data, char* units, const int start[], const int size[]) - { - return NX_OK; - } +NXstatus NXUreaddata(NXhandle file_id, const char *data_name, void *data, + char *units, const int start[], const int size[]) +{ + return NX_OK; +} - NXstatus NXUwritehistogram(NXhandle file_id, const char* data_name, const void* data, const char* units) - { - return NX_OK; - } +NXstatus NXUwritehistogram(NXhandle file_id, const char *data_name, + const void *data, const char *units) +{ + return NX_OK; +} - NXstatus NXUreadhistogram(NXhandle file_id, const char* data_name, void* data, char* units) - { - return NX_OK; - } +NXstatus NXUreadhistogram(NXhandle file_id, const char *data_name, + void *data, char *units) +{ + return NX_OK; +} static int NXcompress_type = 0; static int NXcompress_size = 0; /* NXUsetcompress sets the default compression type and minimum size */ - NXstatus NXUsetcompress(NXhandle file_id, int comp_type, int comp_size) - { - int status; - if (comp_type == NX_COMP_LZW || comp_type == NX_COMP_HUF || - comp_type == NX_COMP_RLE || comp_type == NX_COMP_NONE) - { - NXcompress_type = comp_type; - if (comp_size != 0) - { - NXcompress_size = comp_size; - } - status = NX_OK; - } - else - { - NXIReportError(NXpData, "Invalid compression option"); - status = NX_ERROR; - } - return status; - } +NXstatus NXUsetcompress(NXhandle file_id, int comp_type, int comp_size) +{ + int status; + if (comp_type == NX_COMP_LZW || comp_type == NX_COMP_HUF || + comp_type == NX_COMP_RLE || comp_type == NX_COMP_NONE) { + NXcompress_type = comp_type; + if (comp_size != 0) { + NXcompress_size = comp_size; + } + status = NX_OK; + } else { + NXIReportError(NXpData, "Invalid compression option"); + status = NX_ERROR; + } + return status; +} - /* !NXUfindgroup finds if a NeXus group of the specified name exists */ - NXstatus NXUfindgroup(NXhandle file_id, const char* group_name, char* group_class) - { - int status, n; - NXname vname, vclass; - status = NXgetgroupinfo(file_id, &n, vname, vclass); - if (status != NX_OK) - { - return status; - } - return NX_OK; - } + /* !NXUfindgroup finds if a NeXus group of the specified name exists */ +NXstatus NXUfindgroup(NXhandle file_id, const char *group_name, + char *group_class) +{ + int status, n; + NXname vname, vclass; + status = NXgetgroupinfo(file_id, &n, vname, vclass); + if (status != NX_OK) { + return status; + } + return NX_OK; +} - NXstatus NXUfindclass(NXhandle file_id, const char* group_class, char* group_name, int find_index) - { - return NX_OK; - } +NXstatus NXUfindclass(NXhandle file_id, const char *group_class, + char *group_name, int find_index) +{ + return NX_OK; +} /* NXUfinddata finds if a NeXus data item is in the current group */ - NXstatus NXUfinddata(NXhandle file_id, const char* data_name) - { - return NX_OK; - } +NXstatus NXUfinddata(NXhandle file_id, const char *data_name) +{ + return NX_OK; +} - NXstatus NXUfindattr(NXhandle file_id, const char* attr_name) - { - return NX_OK; - } +NXstatus NXUfindattr(NXhandle file_id, const char *attr_name) +{ + return NX_OK; +} - NXstatus NXUfindsignal(NXhandle file_id, int signal, char* data_name, int* data_rank, int* data_type, int data_dimensions[]) - { - return NX_OK; - } +NXstatus NXUfindsignal(NXhandle file_id, int signal, char *data_name, + int *data_rank, int *data_type, + int data_dimensions[]) +{ + return NX_OK; +} - NXstatus NXUfindaxis(NXhandle file_id, int axis, int primary, char* data_name, int* data_rank, int* data_type, int data_dimensions[]) - { - return NX_OK; - } +NXstatus NXUfindaxis(NXhandle file_id, int axis, int primary, + char *data_name, int *data_rank, int *data_type, + int data_dimensions[]) +{ + return NX_OK; +} - NXstatus NXUfindlink(NXhandle file_id, NXlink* group_id, const char* group_class) - { - return NX_OK; - } - - NXstatus NXUresumelink(NXhandle file_id, NXlink group_id) - { - return NX_OK; - } +NXstatus NXUfindlink(NXhandle file_id, NXlink * group_id, + const char *group_class) +{ + return NX_OK; +} +NXstatus NXUresumelink(NXhandle file_id, NXlink group_id) +{ + return NX_OK; +} diff --git a/napiu.h b/napiu.h index 75efcefd..1d67b66f 100644 --- a/napiu.h +++ b/napiu.h @@ -21,10 +21,10 @@ For further information, see - $Id: napiu.h,v 1.2 2008/01/03 09:56:56 koennecke Exp $ + $Id: napiu.h,v 1.3 2009/02/13 09:00:20 koennecke Exp $ ----------------------------------------------------------------------------*/ - + #ifndef NEXUSAPIU #define NEXUSAPIU @@ -32,41 +32,59 @@ #ifdef __cplusplus extern "C" { -#endif /* __cplusplus */ +#endif /* __cplusplus */ -extern NXstatus NXUwriteglobals(NXhandle file_id, const char* user, const char* affiliation, const char* address, const char* phone, const char* fax, const char* email); + extern NXstatus NXUwriteglobals(NXhandle file_id, const char *user, + const char *affiliation, + const char *address, const char *phone, + const char *fax, const char *email); -extern NXstatus NXUwritegroup(NXhandle file_id, const char* group_name, const char* group_class); + extern NXstatus NXUwritegroup(NXhandle file_id, const char *group_name, + const char *group_class); -extern NXstatus NXUwritedata(NXhandle file_id, const char* data_name, const void* data, int data_type, int rank, const int dim[], const char* units, const int start[], const int size[]); + extern NXstatus NXUwritedata(NXhandle file_id, const char *data_name, + const void *data, int data_type, int rank, + const int dim[], const char *units, + const int start[], const int size[]); -extern NXstatus NXUreaddata(NXhandle file_id, const char* data_name, void* data, char* units, const int start[], const int size[]); + extern NXstatus NXUreaddata(NXhandle file_id, const char *data_name, + void *data, char *units, const int start[], + const int size[]); -extern NXstatus NXUwritehistogram(NXhandle file_id, const char* data_name, const void* data, const char* units); + extern NXstatus NXUwritehistogram(NXhandle file_id, + const char *data_name, + const void *data, const char *units); -extern NXstatus NXUreadhistogram(NXhandle file_id, const char* data_name, void* data, char* units); + extern NXstatus NXUreadhistogram(NXhandle file_id, const char *data_name, + void *data, char *units); -extern NXstatus NXUsetcompress(NXhandle file_id, int comp_type, int comp_size); + extern NXstatus NXUsetcompress(NXhandle file_id, int comp_type, + int comp_size); -extern NXstatus NXUfindgroup(NXhandle file_id, const char* group_name, char* group_class); + extern NXstatus NXUfindgroup(NXhandle file_id, const char *group_name, + char *group_class); -extern NXstatus NXUfindclass(NXhandle file_id, const char* group_class, char* group_name, int find_index); + extern NXstatus NXUfindclass(NXhandle file_id, const char *group_class, + char *group_name, int find_index); -extern NXstatus NXUfinddata(NXhandle file_id, const char* data_name); + extern NXstatus NXUfinddata(NXhandle file_id, const char *data_name); -extern NXstatus NXUfindattr(NXhandle file_id, const char* attr_name); + extern NXstatus NXUfindattr(NXhandle file_id, const char *attr_name); -extern NXstatus NXUfindsignal(NXhandle file_id, int signal, char* data_name, int* data_rank, int* data_type, int data_dimensions[]); + extern NXstatus NXUfindsignal(NXhandle file_id, int signal, + char *data_name, int *data_rank, + int *data_type, int data_dimensions[]); -extern NXstatus NXUfindaxis(NXhandle file_id, int axis, int primary, char* data_name, int* data_rank, int* data_type, int data_dimensions[]); + extern NXstatus NXUfindaxis(NXhandle file_id, int axis, int primary, + char *data_name, int *data_rank, + int *data_type, int data_dimensions[]); -extern NXstatus NXUfindlink(NXhandle file_id, NXlink* group_id, const char* group_class); + extern NXstatus NXUfindlink(NXhandle file_id, NXlink * group_id, + const char *group_class); -extern NXstatus NXUresumelink(NXhandle file_id, NXlink group_id); + extern NXstatus NXUresumelink(NXhandle file_id, NXlink group_id); #ifdef __cplusplus } -#endif /* __cplusplus */ - +#endif /* __cplusplus */ #endif /*NEXUSAPIU*/ - diff --git a/network.c b/network.c index add22e11..4cbe4f6a 100644 --- a/network.c +++ b/network.c @@ -58,598 +58,580 @@ #define UDP 3 /* wait time [ms] between a close and the next open */ -#define WAIT_CLOSE_OPEN 500 +#define WAIT_CLOSE_OPEN 500 + +struct timeval lastclose = { -1, 0 }; -struct timeval lastclose={-1,0}; /*----------------------------------------------------------------------- Redefine this function if another means of error reporting is necessary. */ #include "Scommon.h" - extern void SICSLogWrite(char *pText, OutCode eCode); /* servlog.c */ +extern void SICSLogWrite(char *pText, OutCode eCode); /* servlog.c */ - void WriteToCommandLog(char *p, char *t); - - static void NetError(char *pText) - { +void WriteToCommandLog(char *p, char *t); + +static void NetError(char *pText) +{ /* SICSLogWrite(pText,eError); */ - WriteToCommandLog("NET>", pText); - } + WriteToCommandLog("NET>", pText); +} /* ---------------------------- Local ------------------------------------ CreateSocketAdress stolen from Tcl. Thanks to John Ousterhout */ -static int -CreateSocketAdress( - struct sockaddr_in *sockaddrPtr, /* Socket address */ - char *host, /* Host. NULL implies INADDR_ANY */ - int port) /* Port number */ -{ - struct hostent *hostent; /* Host database entry */ - struct in_addr addr; /* For 64/32 bit madness */ +static int CreateSocketAdress(struct sockaddr_in *sockaddrPtr, /* Socket address */ + char *host, /* Host. NULL implies INADDR_ANY */ + int port) +{ /* Port number */ + struct hostent *hostent; /* Host database entry */ + struct in_addr addr; /* For 64/32 bit madness */ - (void) memset((char *) sockaddrPtr, '\0', sizeof(struct sockaddr_in)); - sockaddrPtr->sin_family = AF_INET; - sockaddrPtr->sin_port = htons((unsigned short) (port & 0xFFFF)); - if (host == NULL) { - addr.s_addr = INADDR_ANY; + (void) memset((char *) sockaddrPtr, '\0', sizeof(struct sockaddr_in)); + sockaddrPtr->sin_family = AF_INET; + sockaddrPtr->sin_port = htons((unsigned short) (port & 0xFFFF)); + if (host == NULL) { + addr.s_addr = INADDR_ANY; + } else { + hostent = gethostbyname(host); + if (hostent != NULL) { + memcpy((char *) &addr, + (char *) hostent->h_addr_list[0], (size_t) hostent->h_length); } else { - hostent = gethostbyname(host); - if (hostent != NULL) { - memcpy((char *) &addr, - (char *) hostent->h_addr_list[0], (size_t) hostent->h_length); - } else { - addr.s_addr = inet_addr(host); - if (addr.s_addr == (unsigned long)-1) { - return 0; /* error */ - } - } + addr.s_addr = inet_addr(host); + if (addr.s_addr == (unsigned long) -1) { + return 0; /* error */ + } } - /* - * There is a rumor that this assignment may require care on - * some 64 bit machines. - */ + } + /* + * There is a rumor that this assignment may require care on + * some 64 bit machines. + */ - sockaddrPtr->sin_addr.s_addr = addr.s_addr; - return 1; + sockaddrPtr->sin_addr.s_addr = addr.s_addr; + return 1; } + /*-------------------------------------------------------------------------*/ - mkChannel *NETOpenPort(int iPort) - { - mkChannel *pRes = NULL; - int iRet,i; - struct linger lili; - - pRes = (mkChannel *)malloc(sizeof(mkChannel)); - if(!pRes) - return NULL; - - /* open a socket */ - pRes->sockid = socket(AF_INET,SOCK_STREAM,0); - if(pRes->sockid < 0) - { - free(pRes); - return NULL; - } - - /* REUSEADDR, for restarts */ - i = 1; - setsockopt(pRes->sockid,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(int)); - - /* bind */ - memset(&(pRes->adresse),0,sizeof(struct sockaddr_in)); - pRes->adresse.sin_family = AF_INET; - pRes->adresse.sin_addr.s_addr = htonl(INADDR_ANY); - pRes->adresse.sin_port = htons(iPort); - iRet = bind(pRes->sockid,(struct sockaddr *)&(pRes->adresse), - sizeof(struct sockaddr_in)); - if(iRet < 0) - { - free(pRes); - return NULL; - } - - /* listen */ - iRet = listen(pRes->sockid,8); - if(iRet < 0) - { - free(pRes); - return NULL; - } - i = sizeof(struct linger); - lili.l_onoff = 1; - lili.l_linger = 1; - /* - setsockopt(pRes->sockid,SOL_SOCKET,SO_LINGER,&lili,i); - */ - pRes->iType = PORT; - pRes->lMagic = NETMAGIC; - return pRes; - } +mkChannel *NETOpenPort(int iPort) +{ + mkChannel *pRes = NULL; + int iRet, i; + struct linger lili; + + pRes = (mkChannel *) malloc(sizeof(mkChannel)); + if (!pRes) + return NULL; + + /* open a socket */ + pRes->sockid = socket(AF_INET, SOCK_STREAM, 0); + if (pRes->sockid < 0) { + free(pRes); + return NULL; + } + + /* REUSEADDR, for restarts */ + i = 1; + setsockopt(pRes->sockid, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(int)); + + /* bind */ + memset(&(pRes->adresse), 0, sizeof(struct sockaddr_in)); + pRes->adresse.sin_family = AF_INET; + pRes->adresse.sin_addr.s_addr = htonl(INADDR_ANY); + pRes->adresse.sin_port = htons(iPort); + iRet = bind(pRes->sockid, (struct sockaddr *) &(pRes->adresse), + sizeof(struct sockaddr_in)); + if (iRet < 0) { + free(pRes); + return NULL; + } + + /* listen */ + iRet = listen(pRes->sockid, 8); + if (iRet < 0) { + free(pRes); + return NULL; + } + i = sizeof(struct linger); + lili.l_onoff = 1; + lili.l_linger = 1; + /* + setsockopt(pRes->sockid,SOL_SOCKET,SO_LINGER,&lili,i); + */ + pRes->iType = PORT; + pRes->lMagic = NETMAGIC; + return pRes; +} + /*---------------------------------------------------------------------------*/ - mkChannel *NETAccept(mkChannel *self, long timeout) - { - mkChannel *pRes = NULL; - int iRet; - fd_set lMask; - struct timeval tmo = {1,0}; - int i; - socklen_t iLen; - struct linger lili; - - assert(self != NULL); - - if(timeout >= 0) - { - /* select first */ - tmo.tv_usec = (timeout % 1000) * 1000; - tmo.tv_sec = timeout / 1000; - FD_ZERO(&lMask); - FD_SET(self->sockid,&lMask); - if((self->sockid >= FD_SETSIZE) || (self->sockid < 0) ) /* invalid descriptor */ - { - return NULL; /* eof */ - } - iRet = uselect( (self->sockid + 1),(fd_set *)&lMask, NULL, NULL,&tmo); - if( iRet <= 0) - { - /* failure, or no request */ - return NULL; - } - } - - /* positive: accept */ - iLen = sizeof(struct sockaddr); - pRes = (mkChannel *)malloc(sizeof(mkChannel)); - if(!pRes) return NULL; - - pRes->sockid = accept(self->sockid, - (struct sockaddr *)&(pRes->adresse), - &iLen); - if(pRes->sockid < 0) - { - free(pRes); - return NULL; - } - /* - i = sizeof(struct linger); - lili.l_onoff = 1; - lili.l_linger = 1; - setsockopt(pRes->sockid,SOL_SOCKET,SO_LINGER,&lili,i); - i = 1; - setsockopt(pRes->sockid,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(int)); - */ - pRes->iType = SOCKET; - pRes->lMagic = NETMAGIC; - return pRes; - - } -/*--------------------------------------------------------------------------*/ - mkChannel *NETConnectWithFlags(char *name, int port, int flags) - { - mkChannel *pRes = NULL; - int iRet, i, cnt; - char pBueffel[80]; - struct hostent *pServer = NULL; - struct linger lili; - struct timeval now; - long dif; - int oldopts; - - assert(port > 0); - - /* default name to localhost */ - if(name == NULL) - { - strcpy(pBueffel,"localhost"); - name = pBueffel; - } - - /* new channel */ - pRes = (mkChannel *)malloc(sizeof(mkChannel)); - if(!pRes) - return NULL; +mkChannel *NETAccept(mkChannel * self, long timeout) +{ + mkChannel *pRes = NULL; + int iRet; + fd_set lMask; + struct timeval tmo = { 1, 0 }; + int i; + socklen_t iLen; + struct linger lili; + + assert(self != NULL); + + if (timeout >= 0) { + /* select first */ + tmo.tv_usec = (timeout % 1000) * 1000; + tmo.tv_sec = timeout / 1000; + FD_ZERO(&lMask); + FD_SET(self->sockid, &lMask); + if ((self->sockid >= FD_SETSIZE) || (self->sockid < 0)) { /* invalid descriptor */ + return NULL; /* eof */ + } + iRet = + uselect((self->sockid + 1), (fd_set *) & lMask, NULL, NULL, &tmo); + if (iRet <= 0) { + /* failure, or no request */ + return NULL; + } + } + + /* positive: accept */ + iLen = sizeof(struct sockaddr); + pRes = (mkChannel *) malloc(sizeof(mkChannel)); + if (!pRes) + return NULL; + + pRes->sockid = accept(self->sockid, + (struct sockaddr *) &(pRes->adresse), &iLen); + if (pRes->sockid < 0) { + free(pRes); + return NULL; + } + /* + i = sizeof(struct linger); + lili.l_onoff = 1; + lili.l_linger = 1; + setsockopt(pRes->sockid,SOL_SOCKET,SO_LINGER,&lili,i); + i = 1; + setsockopt(pRes->sockid,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(int)); + */ + pRes->iType = SOCKET; + pRes->lMagic = NETMAGIC; + return pRes; + +} - /* connect */ - iRet = CreateSocketAdress(&(pRes->adresse),name,port); - if(!iRet) - { - free(pRes); - return NULL; - } - pRes->sockid = socket(AF_INET,SOCK_STREAM,0); - if(pRes->sockid < 0) - { - free(pRes); - return NULL; - } - - if (flags & 2) { /* wait if closed recently */ - /* workaround for a bug in Lantronix terminal server: - if a channel is closed and reopened within short time - the connect will be succesful, but a message will be - sent on the channel! */ - - if (lastclose.tv_sec >= 0) { - gettimeofday(&now, NULL); - dif = (now.tv_sec-lastclose.tv_sec)*1000+(now.tv_usec-lastclose.tv_usec)/1000; - if (dif < 0) dif += 24*3600*1000; - } else { - dif = 0; - } - if (dif < WAIT_CLOSE_OPEN) { - usleep((WAIT_CLOSE_OPEN-dif)*1000); - } - } - - if (flags & 1) { /* open in non blocking mode */ - oldopts = fcntl(pRes->sockid, F_GETFL, 0); - fcntl(pRes->sockid, F_SETFL, oldopts | O_NONBLOCK); - } - - iRet = connect(pRes->sockid,(struct sockaddr *)&(pRes->adresse), - sizeof(struct sockaddr_in)); - if(iRet < 0) - { - if (errno != EINPROGRESS) { - free(pRes); - return NULL; - } - } - /* - i = sizeof(struct linger); - lili.l_onoff = 1; - lili.l_linger = 1; - setsockopt(pRes->sockid,SOL_SOCKET,SO_LINGER,&lili,i); - i = 1; - setsockopt(pRes->sockid,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(int)); - */ - pRes->iType = SOCKET; - pRes->lMagic = NETMAGIC; - return pRes; - } /*--------------------------------------------------------------------------*/ - mkChannel *NETConnect(char *name, int port) { - return NETConnectWithFlags(name, port, 0); - } +mkChannel *NETConnectWithFlags(char *name, int port, int flags) +{ + mkChannel *pRes = NULL; + int iRet, i, cnt; + char pBueffel[80]; + struct hostent *pServer = NULL; + struct linger lili; + struct timeval now; + long dif; + int oldopts; + + assert(port > 0); + + /* default name to localhost */ + if (name == NULL) { + strcpy(pBueffel, "localhost"); + name = pBueffel; + } + + /* new channel */ + pRes = (mkChannel *) malloc(sizeof(mkChannel)); + if (!pRes) + return NULL; + + /* connect */ + iRet = CreateSocketAdress(&(pRes->adresse), name, port); + if (!iRet) { + free(pRes); + return NULL; + } + pRes->sockid = socket(AF_INET, SOCK_STREAM, 0); + if (pRes->sockid < 0) { + free(pRes); + return NULL; + } + + if (flags & 2) { /* wait if closed recently */ + /* workaround for a bug in Lantronix terminal server: + if a channel is closed and reopened within short time + the connect will be succesful, but a message will be + sent on the channel! */ + + if (lastclose.tv_sec >= 0) { + gettimeofday(&now, NULL); + dif = + (now.tv_sec - lastclose.tv_sec) * 1000 + (now.tv_usec - + lastclose.tv_usec) / + 1000; + if (dif < 0) + dif += 24 * 3600 * 1000; + } else { + dif = 0; + } + if (dif < WAIT_CLOSE_OPEN) { + usleep((WAIT_CLOSE_OPEN - dif) * 1000); + } + } + + if (flags & 1) { /* open in non blocking mode */ + oldopts = fcntl(pRes->sockid, F_GETFL, 0); + fcntl(pRes->sockid, F_SETFL, oldopts | O_NONBLOCK); + } + + iRet = connect(pRes->sockid, (struct sockaddr *) &(pRes->adresse), + sizeof(struct sockaddr_in)); + if (iRet < 0) { + if (errno != EINPROGRESS) { + free(pRes); + return NULL; + } + } + /* + i = sizeof(struct linger); + lili.l_onoff = 1; + lili.l_linger = 1; + setsockopt(pRes->sockid,SOL_SOCKET,SO_LINGER,&lili,i); + i = 1; + setsockopt(pRes->sockid,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(int)); + */ + pRes->iType = SOCKET; + pRes->lMagic = NETMAGIC; + return pRes; +} + /*--------------------------------------------------------------------------*/ - int NETConnectFinished(mkChannel *self) { - fd_set wmask, rmask; - struct timeval tmo = {0,0}; - int iret; - int oldopts; - - if (self->sockid == 0) { - errno = ENOTCONN; - return -1; - } - oldopts = fcntl(self->sockid, F_GETFL, 0); - if (! (oldopts | O_NONBLOCK)) { - /* assume success when in blocking mode */ - return 1; - } - FD_ZERO(&wmask); - FD_ZERO(&rmask); - FD_SET(self->sockid, &wmask); - FD_SET(self->sockid, &rmask); - iret = uselect(self->sockid+1, &rmask, &wmask, NULL, &tmo); - if (iret == 0) return 0; /* in progress */ - if (iret > 0) { - /* the connection has either succeded or failed - - the write flag indicates success - - the read flag indicates, if there is already data pending - the read flag should not appear without the write flag - */ - if (FD_ISSET(self->sockid, &wmask)) { /* should always be true */ - if (FD_ISSET(self->sockid, &rmask)) { /* there may already be data for read */ - iret = recv(self->sockid, NULL, 0, 0); /* zero length, check only return value */ - if (iret >= 0) { - iret = 1; /* success */ - } /* else failure */ - } else { - iret = send(self->sockid, NULL, 0, 0); /* zero length, check only return value */ - if (iret >= 0) { - iret = 1; /* success */ - } /* else failure */ - } - } - } - /* reset to blocking mode */ - fcntl(self->sockid, F_SETFL, oldopts | ~ O_NONBLOCK); - return iret; - } -/*------------------------------------------------------------------------*/ - int VerifyChannel(mkChannel *self) - { - if(!self) - { - return 0; - } - if(self->lMagic != NETMAGIC) - { - NetError("CORRUPTED MAGIC: network channel data corrupted"); - return 0; - } - if( (self->sockid < 0) || (self->sockid > 65000) ) - { - NetError("MAGIC DEAD: Invalid socket number, data corrupted"); - return 0; - } +mkChannel *NETConnect(char *name, int port) +{ + return NETConnectWithFlags(name, port, 0); +} + +/*--------------------------------------------------------------------------*/ +int NETConnectFinished(mkChannel * self) +{ + fd_set wmask, rmask; + struct timeval tmo = { 0, 0 }; + int iret; + int oldopts; + + if (self->sockid == 0) { + errno = ENOTCONN; + return -1; + } + oldopts = fcntl(self->sockid, F_GETFL, 0); + if (!(oldopts | O_NONBLOCK)) { + /* assume success when in blocking mode */ return 1; - } -/*------------------------------------------------------------------------*/ - int NETInfo(mkChannel *self, char *pCompost, int iBufLen) - { + } + FD_ZERO(&wmask); + FD_ZERO(&rmask); + FD_SET(self->sockid, &wmask); + FD_SET(self->sockid, &rmask); + iret = uselect(self->sockid + 1, &rmask, &wmask, NULL, &tmo); + if (iret == 0) + return 0; /* in progress */ + if (iret > 0) { + /* the connection has either succeded or failed + - the write flag indicates success + - the read flag indicates, if there is already data pending + the read flag should not appear without the write flag + */ + if (FD_ISSET(self->sockid, &wmask)) { /* should always be true */ + if (FD_ISSET(self->sockid, &rmask)) { /* there may already be data for read */ + iret = recv(self->sockid, NULL, 0, 0); /* zero length, check only return value */ + if (iret >= 0) { + iret = 1; /* success */ + } /* else failure */ + } else { + iret = send(self->sockid, NULL, 0, 0); /* zero length, check only return value */ + if (iret >= 0) { + iret = 1; /* success */ + } /* else failure */ + } + } + } + /* reset to blocking mode */ + fcntl(self->sockid, F_SETFL, oldopts | ~O_NONBLOCK); + return iret; +} - int t; - socklen_t len; - struct sockaddr_in sin; - struct hostent *host; - - if(!VerifyChannel(self)) - { +/*------------------------------------------------------------------------*/ +int VerifyChannel(mkChannel * self) +{ + if (!self) { + return 0; + } + if (self->lMagic != NETMAGIC) { + NetError("CORRUPTED MAGIC: network channel data corrupted"); + return 0; + } + if ((self->sockid < 0) || (self->sockid > 65000)) { + NetError("MAGIC DEAD: Invalid socket number, data corrupted"); + return 0; + } + return 1; +} + +/*------------------------------------------------------------------------*/ +int NETInfo(mkChannel * self, char *pCompost, int iBufLen) +{ + + int t; + socklen_t len; + struct sockaddr_in sin; + struct hostent *host; + + if (!VerifyChannel(self)) { + return 0; + } + + len = sizeof sin; + if (getpeername(self->sockid, (struct sockaddr *) &sin, &len) < 0) { + return 0; + } else { + if ((host = gethostbyaddr((char *) &sin.sin_addr, + sizeof sin.sin_addr, AF_INET)) == NULL) { + return 0; + } else { + strncpy(pCompost, host->h_name, iBufLen); + pCompost[iBufLen - 1] = '\0'; + } + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int NETWrite(mkChannel * self, char *buffer, long lLen) +{ + long iRet; + fd_set lMask; + struct timeval tmo; + char buf[256]; + time_t expire, delta; + char *pos; + long l; + int disconnected; + + if (!VerifyChannel(self)) { + return 0; + } + if (!(self->iType == SOCKET)) { + return 0; + } + + /* + * Check if the we can write to the socket first.... + * Well, this how it should be. However, on linux I observe that + * there is a problem with Java clients not reliably receiving data when + * this is active. + */ + if ((self->sockid >= FD_SETSIZE) || (self->sockid < 0)) { + /* invalid descriptor */ + return 0; + } +#ifdef DO_NOT_SELECT_BEFORE_SEND + iRet = send(self->sockid, buffer, lLen, 0); + if (iRet != lLen) { + self->iType = 0; + if (iRet < 0) { + if (errno == EPIPE) { /* do not write "broken pipe" error */ return 0; } - - len = sizeof sin; - if (getpeername(self->sockid, (struct sockaddr *) &sin, &len) < 0) - { - return 0; - } - else - { - if ((host = gethostbyaddr((char *) &sin.sin_addr, - sizeof sin.sin_addr, - AF_INET)) == NULL) - { - return 0; - } - else - { - strncpy(pCompost,host->h_name,iBufLen); - pCompost[iBufLen-1]='\0'; - } - } - return 1; - } -/*--------------------------------------------------------------------------*/ - int NETWrite(mkChannel *self, char *buffer, long lLen) - { - long iRet; - fd_set lMask; - struct timeval tmo; - char buf[256]; - time_t expire, delta; - char *pos; - long l; - int disconnected; - - if(!VerifyChannel(self)) - { - return 0; - } - if(!(self->iType == SOCKET)) - { - return 0; - } - - /* - * Check if the we can write to the socket first.... - * Well, this how it should be. However, on linux I observe that - * there is a problem with Java clients not reliably receiving data when - * this is active. - */ - if((self->sockid >= FD_SETSIZE) || (self->sockid < 0) ) - { - /* invalid descriptor */ - return 0; - } -#ifdef DO_NOT_SELECT_BEFORE_SEND - iRet = send(self->sockid,buffer,lLen,0); - if (iRet != lLen) { - self->iType = 0; - if (iRet < 0) { - if (errno == EPIPE) { /* do not write "broken pipe" error */ - return 0; - } - snprintf(buf, sizeof buf, "NETWrite: send system error: %s (socket %d)", - strerror(errno), self->sockid); - } else { - snprintf(buf, sizeof buf, "NETWrite: only %ld of %ld bytes sent (socket %d)", - iRet, lLen, self->sockid); - } - NetError(buf); - return 0; - } else { - return 1; - } -#endif - pos = buffer; - l = lLen; - FD_ZERO(&lMask); - disconnected = 0; + snprintf(buf, sizeof buf, + "NETWrite: send system error: %s (socket %d)", + strerror(errno), self->sockid); + } else { + snprintf(buf, sizeof buf, + "NETWrite: only %ld of %ld bytes sent (socket %d)", iRet, + lLen, self->sockid); + } + NetError(buf); + return 0; + } else { + return 1; + } +#endif + pos = buffer; + l = lLen; + FD_ZERO(&lMask); + disconnected = 0; #define TIMEOUT 10 - expire = time(NULL) + TIMEOUT; - while (l > 0) { - delta = expire - time(NULL); - if (delta <= 0) break; - FD_SET(self->sockid,&lMask); - tmo.tv_usec = 0; - tmo.tv_sec = delta; - iRet = uselect( (self->sockid + 1),NULL, &lMask, NULL,&tmo); - if (iRet < 0) { - /* failure, or no data */ - self->iType = 0; - snprintf(buf, sizeof buf, - "NETWrite: failure on select before send: %s (socket %d)", - strerror(errno), self->sockid); - NetError(buf); - return 0; - } - if (!FD_ISSET(self->sockid,&lMask)) break; - - iRet = send(self->sockid,pos,l,0); - disconnected = (iRet == 0); - if (iRet < 0) { - self->iType = 0; - if (errno == EPIPE || errno == ECONNRESET) { /* do not write these errors */ - return 0; - } - snprintf(buf, sizeof buf, "NETWrite: send system error: %s (socket %d)", - strerror(errno), self->sockid); - NetError(buf); - return 0; - } - l -= iRet; - pos += iRet; - } - if (l > 0) { - self->iType = 0; - if (!disconnected) { /* do not write an error message on disconnect */ - snprintf(buf, sizeof buf, "NETWrite: timeout, only %ld of %ld bytes sent (socket %d) %ld.%6.6ld", - lLen - l, lLen, self->sockid, (long)tmo.tv_sec, (long)tmo.tv_usec); - NetError(buf); - } - return 0; - } - return 1; - } + expire = time(NULL) + TIMEOUT; + while (l > 0) { + delta = expire - time(NULL); + if (delta <= 0) + break; + FD_SET(self->sockid, &lMask); + tmo.tv_usec = 0; + tmo.tv_sec = delta; + iRet = uselect((self->sockid + 1), NULL, &lMask, NULL, &tmo); + if (iRet < 0) { + /* failure, or no data */ + self->iType = 0; + snprintf(buf, sizeof buf, + "NETWrite: failure on select before send: %s (socket %d)", + strerror(errno), self->sockid); + NetError(buf); + return 0; + } + if (!FD_ISSET(self->sockid, &lMask)) + break; + + iRet = send(self->sockid, pos, l, 0); + disconnected = (iRet == 0); + if (iRet < 0) { + self->iType = 0; + if (errno == EPIPE || errno == ECONNRESET) { /* do not write these errors */ + return 0; + } + snprintf(buf, sizeof buf, + "NETWrite: send system error: %s (socket %d)", + strerror(errno), self->sockid); + NetError(buf); + return 0; + } + l -= iRet; + pos += iRet; + } + if (l > 0) { + self->iType = 0; + if (!disconnected) { /* do not write an error message on disconnect */ + snprintf(buf, sizeof buf, + "NETWrite: timeout, only %ld of %ld bytes sent (socket %d) %ld.%6.6ld", + lLen - l, lLen, self->sockid, (long) tmo.tv_sec, + (long) tmo.tv_usec); + NetError(buf); + } + return 0; + } + return 1; +} + /* -------------------------------------------------------------------------*/ - long NETRead(mkChannel *self, char *buffer, long lLen, long timeout) - { - fd_set lMask; - struct timeval tmo ={0,1}; - long iRet; - - if(!VerifyChannel(self)) - { - return 0; - } - - if(timeout >= 0) - { - /* setup for select first */ - tmo.tv_usec = (timeout % 1000) *1000; - tmo.tv_sec = timeout / 1000; - FD_ZERO(&lMask); - FD_SET(self->sockid,&lMask); - if((self->sockid >= FD_SETSIZE) || (self->sockid < 0) ) /* invalid descriptor */ - { - return -1; /* eof */ - } - iRet = uselect( (self->sockid + 1),&lMask, NULL, NULL,&tmo); - if( iRet <= 0) - { - /* failure, or no data - printf(" %d %d\n", iRet, errno); - */ - return 0; - } - } - - /* data or block for read, read */ - memset(buffer,0,lLen); - iRet = recv(self->sockid,buffer,lLen,0); - if(iRet == 0) - {/* eof */ - return -1; - } - if(iRet < 0) - { - return 0; - } - else - { - return iRet; - } - } +long NETRead(mkChannel * self, char *buffer, long lLen, long timeout) +{ + fd_set lMask; + struct timeval tmo = { 0, 1 }; + long iRet; + + if (!VerifyChannel(self)) { + return 0; + } + + if (timeout >= 0) { + /* setup for select first */ + tmo.tv_usec = (timeout % 1000) * 1000; + tmo.tv_sec = timeout / 1000; + FD_ZERO(&lMask); + FD_SET(self->sockid, &lMask); + if ((self->sockid >= FD_SETSIZE) || (self->sockid < 0)) { /* invalid descriptor */ + return -1; /* eof */ + } + iRet = uselect((self->sockid + 1), &lMask, NULL, NULL, &tmo); + if (iRet <= 0) { + /* failure, or no data + printf(" %d %d\n", iRet, errno); + */ + return 0; + } + } + + /* data or block for read, read */ + memset(buffer, 0, lLen); + iRet = recv(self->sockid, buffer, lLen, 0); + if (iRet == 0) { /* eof */ + return -1; + } + if (iRet < 0) { + return 0; + } else { + return iRet; + } +} + /*---------------------------------------------------------------------*/ - int NETAvailable(mkChannel *self, long timeout) - { - fd_set lMask; - struct timeval tmo ={0,1}; - int iRet; - - if(!VerifyChannel(self)) - { - return 0; - } - - /* setup for select */ - tmo.tv_usec = (timeout % 1000) * 1000; - tmo.tv_sec = timeout / 1000; - FD_ZERO(&lMask); - FD_SET(self->sockid,&lMask); - if((self->sockid >= FD_SETSIZE) || (self->sockid < 0) ) - /* invalid descriptor */ - { - return -1; /* eof */ - } - iRet = uselect( (self->sockid + 1),&lMask, NULL, NULL,&tmo); - if( iRet < 0) - { - return -1; - } - if(FD_ISSET(self->sockid,&lMask)) - { - return 1; - } - else - { - return 0; - } - } +int NETAvailable(mkChannel * self, long timeout) +{ + fd_set lMask; + struct timeval tmo = { 0, 1 }; + int iRet; + + if (!VerifyChannel(self)) { + return 0; + } + + /* setup for select */ + tmo.tv_usec = (timeout % 1000) * 1000; + tmo.tv_sec = timeout / 1000; + FD_ZERO(&lMask); + FD_SET(self->sockid, &lMask); + if ((self->sockid >= FD_SETSIZE) || (self->sockid < 0)) + /* invalid descriptor */ + { + return -1; /* eof */ + } + iRet = uselect((self->sockid + 1), &lMask, NULL, NULL, &tmo); + if (iRet < 0) { + return -1; + } + if (FD_ISSET(self->sockid, &lMask)) { + return 1; + } else { + return 0; + } +} + /*-------------------------------------------------------------------------*/ -int NETReadTillTerm(mkChannel *self, long timeout, +int NETReadTillTerm(mkChannel * self, long timeout, char *pTerm, char *pBuffer, int iBufLen) { struct timeval start, now; - int bufPtr = 0, status, i, length, matchIndex=1; + int bufPtr = 0, status, i, length, matchIndex = 1; char c; long dif; - if(!VerifyChannel(self)) - { + if (!VerifyChannel(self)) { return -1; } - + gettimeofday(&start, NULL); - if (pTerm == NULL) pTerm=""; - + if (pTerm == NULL) + pTerm = ""; + length = strlen(pTerm); - memset(pBuffer,0,iBufLen); - - status = NETAvailable(self,timeout); /* first time: full timeout */ - if(status <= 0) /* return on error or on timeout */ - { + memset(pBuffer, 0, iBufLen); + + status = NETAvailable(self, timeout); /* first time: full timeout */ + if (status <= 0) { /* return on error or on timeout */ return status; } - while (status > 0) - { - status = recv(self->sockid,&c,1,0); - if(status <= 0) - { + while (status > 0) { + status = recv(self->sockid, &c, 1, 0); + if (status <= 0) { return status; } if ('&' != pTerm[0]) { - for(i = 0; i < length; i++) - { - if(c == pTerm[i]) - { - return bufPtr+1; + for (i = 0; i < length; i++) { + if (c == pTerm[i]) { + return bufPtr + 1; } } } else { if (matchIndex == 1 && c == pTerm[1]) { matchIndex++; } else { - if (c== pTerm[matchIndex] && matchIndex < length -1) { + if (c == pTerm[matchIndex] && matchIndex < length - 1) { matchIndex++; } else { if (c == pTerm[matchIndex] && matchIndex == length - 1) { @@ -662,62 +644,62 @@ int NETReadTillTerm(mkChannel *self, long timeout, } } } - if (c == 0 && *pTerm != 0) - { + if (c == 0 && *pTerm != 0) { /* a null character is an error, except when no terminator is defined (binary data) */ return -1; } - if(bufPtr >= iBufLen-1) - { - if (*pTerm != 0) { /* terminator expected */ - return -1; /* overflow */ + if (bufPtr >= iBufLen - 1) { + if (*pTerm != 0) { /* terminator expected */ + return -1; /* overflow */ } pBuffer[bufPtr] = c; - return bufPtr+1; + return bufPtr + 1; } pBuffer[bufPtr] = c; bufPtr++; /* - wait for more data - */ - status = NETAvailable(self,0); /* timeout 0 (just poll) */ - if (status == 0 && timeout > 0) - { + wait for more data + */ + status = NETAvailable(self, 0); /* timeout 0 (just poll) */ + if (status == 0 && timeout > 0) { gettimeofday(&now, NULL); - dif = (now.tv_sec-start.tv_sec)*1000+(now.tv_usec-start.tv_usec)/1000; - if (dif < 0) dif += 24*3600*1000; /* treat midnight correctly */ - if(dif > timeout) - { - return 0; /* timeout */ + dif = + (now.tv_sec - start.tv_sec) * 1000 + (now.tv_usec - + start.tv_usec) / 1000; + if (dif < 0) + dif += 24 * 3600 * 1000; /* treat midnight correctly */ + if (dif > timeout) { + return 0; /* timeout */ } - status = NETAvailable(self,timeout-dif); + status = NETAvailable(self, timeout - dif); }; }; assert(bufPtr > 0); return bufPtr; } -/*---------------------------------------------------------------------------*/ - int NETClosePort(mkChannel *self) - { - int iRet; - if(!VerifyChannel(self)) - { - return 0; - } - - iRet = close(self->sockid); - gettimeofday(&lastclose, NULL); - self->iType = 0; - self->sockid = 0; - if(iRet < 0) - return 0; - else - return 1; - - } /*---------------------------------------------------------------------------*/ -int NETReconnectWithFlags(mkChannel* self, int flags) +int NETClosePort(mkChannel * self) +{ + int iRet; + + if (!VerifyChannel(self)) { + return 0; + } + + iRet = close(self->sockid); + gettimeofday(&lastclose, NULL); + self->iType = 0; + self->sockid = 0; + if (iRet < 0) + return 0; + else + return 1; + +} + +/*---------------------------------------------------------------------------*/ +int NETReconnectWithFlags(mkChannel * self, int flags) { int iRet; int sock; @@ -729,7 +711,7 @@ int NETReconnectWithFlags(mkChannel* self, int flags) oldopts = fcntl(self->sockid, F_GETFL, 0); close(self->sockid); /* Reopen and try to get it on the olf fd */ - sock = socket(AF_INET,SOCK_STREAM,0); + sock = socket(AF_INET, SOCK_STREAM, 0); if (self->sockid != sock) { iRet = fcntl(sock, F_DUPFD, self->sockid); if (iRet != sock) @@ -742,233 +724,218 @@ int NETReconnectWithFlags(mkChannel* self, int flags) fcntl(self->sockid, F_SETFL, oldopts); /* set socket non-blocking */ oldopts = fcntl(self->sockid, F_GETFL, 0); - if (/*(flags & 1) &&*/ !(oldopts & O_NONBLOCK)) + if ( /*(flags & 1) && */ !(oldopts & O_NONBLOCK)) fcntl(self->sockid, F_SETFL, oldopts | O_NONBLOCK); /* try to reconnect */ iRet = connect(self->sockid, - (struct sockaddr *)&(self->adresse), - sizeof(struct sockaddr_in)); + (struct sockaddr *) &(self->adresse), + sizeof(struct sockaddr_in)); if (iRet < 0) { if (errno == EINPROGRESS) { if ((flags & 1)) { - iRet = 0; /* in progress */ + iRet = 0; /* in progress */ } else { fd_set rmask; fd_set wmask; - struct timeval tmo = {1,0}; + struct timeval tmo = { 1, 0 }; FD_ZERO(&rmask); FD_ZERO(&wmask); FD_SET(self->sockid, &rmask); FD_SET(self->sockid, &wmask); - iRet = uselect(self->sockid+1, &rmask, &wmask, NULL, &tmo); - if (iRet < 0) /* error */ + iRet = uselect(self->sockid + 1, &rmask, &wmask, NULL, &tmo); + if (iRet < 0) /* error */ iRet = -1; - else if (iRet == 0) /* timeout */ - iRet = 0; /* in progress */ + else if (iRet == 0) /* timeout */ + iRet = 0; /* in progress */ else { char reply[1]; if (FD_ISSET(self->sockid, &rmask)) { iRet = recv(self->sockid, reply, 1, MSG_PEEK); if (iRet <= 0) - iRet = -1; /* failure */ + iRet = -1; /* failure */ } if (FD_ISSET(self->sockid, &wmask)) { iRet = send(self->sockid, NULL, 0, 0); if (iRet < 0) - iRet = -1; /* failure */ + iRet = -1; /* failure */ else - iRet = 1; /* success */ + iRet = 1; /* success */ } } } - } - else /* other error */ - iRet = -1; /* error */ - } - else - iRet = 1; /* success */ - + } else /* other error */ + iRet = -1; /* error */ + } else + iRet = 1; /* success */ + if (iRet != 0 && !(oldopts & O_NONBLOCK)) fcntl(self->sockid, F_SETFL, oldopts); return iRet; } -int NETReconnect(mkChannel* self) +int NETReconnect(mkChannel * self) { return NETReconnectWithFlags(self, 0); } /* ################### UDP -functions ######################################*/ - mkChannel *UDPOpen(int iPort) - { - mkChannel *pRes = NULL; - int iRet, i; - - pRes = (mkChannel *)malloc(sizeof(mkChannel)); - if(!pRes) - return NULL; - - /* open a socket */ - pRes->sockid = socket(AF_INET,SOCK_DGRAM,0); - if(pRes->sockid < 0) - { - free(pRes); - return NULL; - } - - /* REUSEADDR for restarting ability */ - i = 1; - setsockopt(pRes->sockid,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(int)); - - assert(pRes->sockid < (sizeof(long)*8)); - /* if this fails the masks for select will be to - short. - */ - - - /* bind */ - memset(&(pRes->adresse),0,sizeof(struct sockaddr_in)); - pRes->adresse.sin_family = AF_INET; - pRes->adresse.sin_addr.s_addr = htonl(INADDR_ANY); - pRes->adresse.sin_port = htons(iPort); - iRet = bind(pRes->sockid,(struct sockaddr *)&(pRes->adresse), - sizeof(struct sockaddr_in)); - if(iRet < 0) - { - free(pRes); - return NULL; - } +mkChannel *UDPOpen(int iPort) +{ + mkChannel *pRes = NULL; + int iRet, i; - pRes->iType = UDP; - pRes->lMagic = NETMAGIC; - return pRes; - } -/*--------------------------------------------------------------------------*/ - mkChannel *UDPConnect(char *name, int port) - { - mkChannel *pRes = NULL; - int iRet, i; - char pBueffel[80]; - struct hostent *pServer = NULL; - - assert(port > 0); - - /* default name to localhost */ - if(name == NULL) - { - strcpy(pBueffel,"localhost"); - name = pBueffel; - } - - /* new channel */ - pRes = (mkChannel *)malloc(sizeof(mkChannel)); - if(!pRes) - return NULL; + pRes = (mkChannel *) malloc(sizeof(mkChannel)); + if (!pRes) + return NULL; - /* connect */ - iRet = CreateSocketAdress(&(pRes->adresse),name,port); - if(!iRet) - { - free(pRes); - return NULL; - } - pRes->sockid = socket(AF_INET,SOCK_DGRAM,0); - if(pRes->sockid < 0) - { - free(pRes); - return NULL; - } - /* + /* open a socket */ + pRes->sockid = socket(AF_INET, SOCK_DGRAM, 0); + if (pRes->sockid < 0) { + free(pRes); + return NULL; + } + + /* REUSEADDR for restarting ability */ + i = 1; + setsockopt(pRes->sockid, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(int)); + + assert(pRes->sockid < (sizeof(long) * 8)); + /* if this fails the masks for select will be to + short. + */ + + + /* bind */ + memset(&(pRes->adresse), 0, sizeof(struct sockaddr_in)); + pRes->adresse.sin_family = AF_INET; + pRes->adresse.sin_addr.s_addr = htonl(INADDR_ANY); + pRes->adresse.sin_port = htons(iPort); + iRet = bind(pRes->sockid, (struct sockaddr *) &(pRes->adresse), + sizeof(struct sockaddr_in)); + if (iRet < 0) { + free(pRes); + return NULL; + } + + pRes->iType = UDP; + pRes->lMagic = NETMAGIC; + return pRes; +} + +/*--------------------------------------------------------------------------*/ +mkChannel *UDPConnect(char *name, int port) +{ + mkChannel *pRes = NULL; + int iRet, i; + char pBueffel[80]; + struct hostent *pServer = NULL; + + assert(port > 0); + + /* default name to localhost */ + if (name == NULL) { + strcpy(pBueffel, "localhost"); + name = pBueffel; + } + + /* new channel */ + pRes = (mkChannel *) malloc(sizeof(mkChannel)); + if (!pRes) + return NULL; + + /* connect */ + iRet = CreateSocketAdress(&(pRes->adresse), name, port); + if (!iRet) { + free(pRes); + return NULL; + } + pRes->sockid = socket(AF_INET, SOCK_DGRAM, 0); + if (pRes->sockid < 0) { + free(pRes); + return NULL; + } + /* iRet = connect(pRes->sockid,(struct sockaddr *)&(pRes->adresse), - sizeof(struct sockaddr_in)); - */ - iRet = 1; - if(iRet < 0) - { - free(pRes); - return NULL; - } + sizeof(struct sockaddr_in)); + */ + iRet = 1; + if (iRet < 0) { + free(pRes); + return NULL; + } /* i = 1; setsockopt(pRes->sockid,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(int)); */ - pRes->iType = UDP; - pRes->lMagic = NETMAGIC; - return pRes; - } -/*--------------------------------------------------------------------------*/ - long UDPRead(mkChannel *self, char *buffer, long lLen, int timeout) - { - long lMask = 0L; - struct timeval tmo ={0,1}; - long iRet; - socklen_t iLang; - - if(!VerifyChannel(self)) - { - return 0; - } - assert(self->iType == UDP); - - if(timeout >= 0) - { - /* setup for select first */ - tmo.tv_usec = (timeout % 1000) *1000; - tmo.tv_sec = timeout / 1000; - lMask = (1 << self->sockid); - iRet = uselect( (self->sockid + 1),(fd_set *)&lMask, NULL, NULL,&tmo); - if( iRet <= 0) - { - /* failure, or no data */ - return 0; - } - } - - /* data, read */ - buffer[0] = '\0'; - iLang = sizeof(struct sockaddr_in); - iRet = recvfrom(self->sockid,buffer,lLen,0, - (struct sockaddr *)&(self->adresse), - &iLang); - if(iRet == 0) - {/* eof */ - return -1; - } - if(iRet < 0) - { - return 0; - } - else - { - buffer[iRet] = '\0'; - return iRet; - } - } + pRes->iType = UDP; + pRes->lMagic = NETMAGIC; + return pRes; +} + /*--------------------------------------------------------------------------*/ - int UDPWrite(mkChannel *self, char *buffer, long lLen) - { - int iRet; - - if(!VerifyChannel(self)) - { - return 0; - } - assert(self->iType == UDP); - - iRet = sendto(self->sockid,buffer,lLen,0, - (struct sockaddr *)&(self->adresse),sizeof(struct sockaddr_in)); - fsync(self->sockid); - if(iRet < 0) - { - return 0; - } - else - { - return 1; - } - } - +long UDPRead(mkChannel * self, char *buffer, long lLen, int timeout) +{ + long lMask = 0L; + struct timeval tmo = { 0, 1 }; + long iRet; + socklen_t iLang; + + if (!VerifyChannel(self)) { + return 0; + } + assert(self->iType == UDP); + + if (timeout >= 0) { + /* setup for select first */ + tmo.tv_usec = (timeout % 1000) * 1000; + tmo.tv_sec = timeout / 1000; + lMask = (1 << self->sockid); + iRet = + uselect((self->sockid + 1), (fd_set *) & lMask, NULL, NULL, &tmo); + if (iRet <= 0) { + /* failure, or no data */ + return 0; + } + } + + /* data, read */ + buffer[0] = '\0'; + iLang = sizeof(struct sockaddr_in); + iRet = recvfrom(self->sockid, buffer, lLen, 0, + (struct sockaddr *) &(self->adresse), &iLang); + if (iRet == 0) { /* eof */ + return -1; + } + if (iRet < 0) { + return 0; + } else { + buffer[iRet] = '\0'; + return iRet; + } +} + +/*--------------------------------------------------------------------------*/ +int UDPWrite(mkChannel * self, char *buffer, long lLen) +{ + int iRet; + + if (!VerifyChannel(self)) { + return 0; + } + assert(self->iType == UDP); + + iRet = sendto(self->sockid, buffer, lLen, 0, + (struct sockaddr *) &(self->adresse), + sizeof(struct sockaddr_in)); + fsync(self->sockid); + if (iRet < 0) { + return 0; + } else { + return 1; + } +} + /* ========================================================================== TestCode. Compile with DBCLIENT defined to get a test client, @@ -978,94 +945,81 @@ int NETReconnect(mkChannel* self) #ifdef DBCLIENT - int main(int argc, char *argv[]) - { - char pBueffel[80]; - mkChannel *pChan = NULL; - int iRet; - - pChan = NETConnect("localhost",4711); - if(!pChan) - { - puts("No connection to server"); - exit(2); - } - - for( ; ; ) - { - printf("Client> "); - gets(pBueffel); - if(strcmp(pBueffel,"exit") == 0) - break; - iRet = NETWrite(pChan,pBueffel,strlen(pBueffel)); - if(!iRet) - puts("Write error"); - - iRet = NETRead(pChan,pBueffel,79,2000); - if(iRet < -1) - { - puts("Read error"); - } - else if(iRet > 0) - { - pBueffel[iRet] = '\0'; - puts(pBueffel); - } - } - NETClosePort(pChan); - return 0; +int main(int argc, char *argv[]) +{ + char pBueffel[80]; + mkChannel *pChan = NULL; + int iRet; + + pChan = NETConnect("localhost", 4711); + if (!pChan) { + puts("No connection to server"); + exit(2); } + + for (;;) { + printf("Client> "); + gets(pBueffel); + if (strcmp(pBueffel, "exit") == 0) + break; + iRet = NETWrite(pChan, pBueffel, strlen(pBueffel)); + if (!iRet) + puts("Write error"); + + iRet = NETRead(pChan, pBueffel, 79, 2000); + if (iRet < -1) { + puts("Read error"); + } else if (iRet > 0) { + pBueffel[iRet] = '\0'; + puts(pBueffel); + } + } + NETClosePort(pChan); + return 0; +} #endif #ifdef DBSERVER - int main(int argc, char *argv[]) - { - mkChannel *pPort = NULL; - mkChannel *pCon[20]; - int i,iRet, iPtr = 0; - char pBueffel[132]; - - pPort = NETOpenPort(4711); - if(!pPort) - { - puts("Cannot start server"); - exit(1); - } - - while(1) - { - /* accept new connections */ - pCon[iPtr] = NETAccept(pPort,200); - if(pCon[iPtr]) - { - printf("Connection accepted on socket %d\n",pCon[iPtr]->sockid); - iPtr++; - } - - /* look for messages */ - for(i = 0; i < iPtr; i++) - { - if(pCon[i]) - { - iRet = NETRead(pCon[i],pBueffel,131,200); - if(iRet < 0) - { - printf("closing socket %d\n",pCon[i]->sockid); - NETClosePort(pCon[i]); - free(pCon[i]); - pCon[i] = NULL; - } - else if(iRet > 0) - { - pBueffel[iRet] = '\0'; - printf("Received - %s - from %d\n",pBueffel,pCon[i]->sockid); - NETWrite(pCon[i],"Acknowledge",strlen("Acknowledge")); - } - } - } - - } - +int main(int argc, char *argv[]) +{ + mkChannel *pPort = NULL; + mkChannel *pCon[20]; + int i, iRet, iPtr = 0; + char pBueffel[132]; + pPort = NETOpenPort(4711); + if (!pPort) { + puts("Cannot start server"); + exit(1); + } + + while (1) { + /* accept new connections */ + pCon[iPtr] = NETAccept(pPort, 200); + if (pCon[iPtr]) { + printf("Connection accepted on socket %d\n", pCon[iPtr]->sockid); + iPtr++; } + + /* look for messages */ + for (i = 0; i < iPtr; i++) { + if (pCon[i]) { + iRet = NETRead(pCon[i], pBueffel, 131, 200); + if (iRet < 0) { + printf("closing socket %d\n", pCon[i]->sockid); + NETClosePort(pCon[i]); + free(pCon[i]); + pCon[i] = NULL; + } else if (iRet > 0) { + pBueffel[iRet] = '\0'; + printf("Received - %s - from %d\n", pBueffel, pCon[i]->sockid); + NETWrite(pCon[i], "Acknowledge", strlen("Acknowledge")); + } + } + } + + } + + +} #endif diff --git a/network.h b/network.h index 900d035a..9d8452b5 100644 --- a/network.h +++ b/network.h @@ -26,13 +26,13 @@ #include #include - typedef struct __MKCHANNEL{ - int sockid; - int iType; - struct sockaddr_in adresse; - long lMagic; - } mkChannel; - +typedef struct __MKCHANNEL { + int sockid; + int iType; + struct sockaddr_in adresse; + long lMagic; +} mkChannel; + #define NETMAGIC 29121993 /*========================= exported functions ============================*/ @@ -41,48 +41,48 @@ /********************** OPENING ************************************** */ - mkChannel *NETOpenPort(int iPort); - /* opens a ServerPort for listening, returns NULL if failure, - else a valid mkChannel structure for the port - */ - - mkChannel *NETAccept(mkChannel *self, long timeout); - /* tries to accept a new connection on the Channel self - until timeout. If a connection can be built a new mkChannel - structure is returned, else NULL. With a negative value or 0 for - timeout this function blocks for an accept. - */ - - mkChannel *NETConnect(char *name, int port); - /* tries to open a client connection to the server specified by name - and port. Returns NULL on failure, a struct else - */ +mkChannel *NETOpenPort(int iPort); + /* opens a ServerPort for listening, returns NULL if failure, + else a valid mkChannel structure for the port + */ - mkChannel *NETConnectWithFlags(char *name, int port, int flags); +mkChannel *NETAccept(mkChannel * self, long timeout); + /* tries to accept a new connection on the Channel self + until timeout. If a connection can be built a new mkChannel + structure is returned, else NULL. With a negative value or 0 for + timeout this function blocks for an accept. + */ + +mkChannel *NETConnect(char *name, int port); + /* tries to open a client connection to the server specified by name + and port. Returns NULL on failure, a struct else + */ + +mkChannel *NETConnectWithFlags(char *name, int port, int flags); /* the same as NETConnect, but with flags: if (flags & 1): do not block on connect (use NETConnectFinished - to check success) + to check success) if (flags & 2): wait 1000 ms after last close (workaround for - a bug in Lantronix terminal server - */ - - int NETConnectFinished(mkChannel *self); + a bug in Lantronix terminal server + */ + +int NETConnectFinished(mkChannel * self); /* returns 0 if in progress, 1 on success, a negative value on error - */ - - int NETInfo(mkChannel *self, char *pComposter, int iBufLen); + */ + +int NETInfo(mkChannel * self, char *pComposter, int iBufLen); /* Once a socket is connected it is possible to figure out which host the connection came from. Maximum iBufLen characters of hostname are copied to pComposter - */ + */ - int NETReconnect(mkChannel* self); +int NETReconnect(mkChannel * self); /* If a connection has been lost, try to reconnect using the same * socket id if possible. Blocks for up to one second. * returns 0 if in progress, 1 on success, a negative value on error */ - int NETReconnectWithFlags(mkChannel* self, int flags); +int NETReconnectWithFlags(mkChannel * self, int flags); /* If a connection has been lost, try to reconnect using the same * socket id if possible. If (flags & 1) do not block, use * NETConnectFinished to check success. @@ -90,55 +90,55 @@ */ /* *********************** DATA TRANSFER ******************************** */ - int NETWrite(mkChannel *self, char *buffer, long lLen); - /* writes data to socket self, returns True if success, - false otherwise. - */ - - long NETRead(mkChannel *self, char *buffer, long lLen, long timeout); - /* reads data from socket self into buffer with max length lLen - waits maximum timeout for data. Returns -1 on error, 0 on no - data, and else the length of the data read. With a negative value - or 0 for timeout this function blocks for the read. - */ - int NETAvailable(mkChannel *self, long timeout); +int NETWrite(mkChannel * self, char *buffer, long lLen); + /* writes data to socket self, returns True if success, + false otherwise. + */ + +long NETRead(mkChannel * self, char *buffer, long lLen, long timeout); + /* reads data from socket self into buffer with max length lLen + waits maximum timeout for data. Returns -1 on error, 0 on no + data, and else the length of the data read. With a negative value + or 0 for timeout this function blocks for the read. + */ +int NETAvailable(mkChannel * self, long timeout); /* returns 1 if data is pending on the port, 0 if none is pending. - */ - int NETReadTillTerm(mkChannel *self, long timeout, + */ +int NETReadTillTerm(mkChannel * self, long timeout, char *pTerm, char *pBuffer, int iBufLen); /* - reads data until one of the terminators defined in pTerm has - been found. The data is copied into the buffer pBuffer. A - maximum length of iBufLen characters is observed. The timeout - parameter defines a maximum time to wait for a terminator to - appear. NETReadTillTerm returns the number of characters read - (including terminator) on success, 0 on a timeout, - and a negative value if a network error occurred. Beware that - this may not work correctly if the wrong terminator is given. - The last one is really needed. - In the new version, timeout is in MILLIseconds (10 -3 sec). - However, the accuracy is machine dependent (for Linux 10 ms, for Tru64 1 ms) - If no terminator is given, the routine waits for iBufLen characters - or timeout. - */ + reads data until one of the terminators defined in pTerm has + been found. The data is copied into the buffer pBuffer. A + maximum length of iBufLen characters is observed. The timeout + parameter defines a maximum time to wait for a terminator to + appear. NETReadTillTerm returns the number of characters read + (including terminator) on success, 0 on a timeout, + and a negative value if a network error occurred. Beware that + this may not work correctly if the wrong terminator is given. + The last one is really needed. + In the new version, timeout is in MILLIseconds (10 -3 sec). + However, the accuracy is machine dependent (for Linux 10 ms, for Tru64 1 ms) + If no terminator is given, the routine waits for iBufLen characters + or timeout. + */ /* ********************* KILLING FIELD ******************************** */ - int NETClosePort(mkChannel *self); - /* closes a port, do not forget to free the channel data- - structure afterwards, returns True on success, False else - */ - +int NETClosePort(mkChannel * self); + /* closes a port, do not forget to free the channel data- + structure afterwards, returns True on success, False else + */ + /*################## ConnectionLess functions ##########################*/ - mkChannel *UDPOpen(int iPort); +mkChannel *UDPOpen(int iPort); /* opens a port connectionless communications. - */ - mkChannel *UDPConnect(char *name, int iPort); + */ +mkChannel *UDPConnect(char *name, int iPort); /* connects a client for connectionless communication - */ - + */ + /* can use NETClosePort */ - - long UDPRead(mkChannel *self, char *buffer, long lLen, int timeout); - int UDPWrite(mkChannel *self, char *buffer, long lLen); + +long UDPRead(mkChannel * self, char *buffer, long lLen, int timeout); +int UDPWrite(mkChannel * self, char *buffer, long lLen); #endif diff --git a/nigpib.c b/nigpib.c index 32384f13..e9708cc4 100644 --- a/nigpib.c +++ b/nigpib.c @@ -15,90 +15,102 @@ #include #include "fortify.h" #include "sics.h" -#include +#include #include "gpibcontroller.i" typedef struct __GPIB *pGPIB; /*--------------------------------------------------------------------------*/ static int NIattach(int boardNo, int address, int secondaryAddress, - int tmo, int eot, int eos){ + int tmo, int eot, int eos) +{ int devID; devID = ibdev(boardNo, address, secondaryAddress, tmo, eot, eos); - if(devID < 0){ + if (devID < 0) { return -iberr; } else { return devID; } } + /*---------------------------------------------------------------------*/ -static int NIdetach(int devID){ +static int NIdetach(int devID) +{ int status; status = ibonl(devID, 0); - if(status & ERR){ + if (status & ERR) { return -iberr; } else { return 1; } } + /*-------------------------------------------------------------------*/ -static int NIwrite(int devID, void *buffer, int bytesToWrite){ +static int NIwrite(int devID, void *buffer, int bytesToWrite) +{ int status; - - status = ibwrt(devID,buffer,bytesToWrite); - if(status & ERR){ - return - iberr; - } else { + + status = ibwrt(devID, buffer, bytesToWrite); + if (status & ERR) { + return -iberr; + } else { return 1; } } + /*-------------------------------------------------------------------*/ -static int NIread(int devID, void *buffer, int bytesToRead){ +static int NIread(int devID, void *buffer, int bytesToRead) +{ int status; - - status = ibrd(devID,buffer,bytesToRead); - if(status & ERR){ - return - iberr; - } else { + + status = ibrd(devID, buffer, bytesToRead); + if (status & ERR) { + return -iberr; + } else { return 1; } } + /*--------------------------------------------------------------------*/ -static int NIclear(int devID){ +static int NIclear(int devID) +{ ibclr(devID); return 1; } -/*-----------------------------------------------------------------*/ -static void NIerror(int code, char *buffer, int maxBuffer){ - int flag = - code; - switch(flag){ +/*-----------------------------------------------------------------*/ +static void NIerror(int code, char *buffer, int maxBuffer) +{ + int flag = -code; + + switch (flag) { case EDVR: case ENEB: case ECIC: - strncpy(buffer,"NI-GPIB not correctly installed or bad address", - maxBuffer); + strncpy(buffer, "NI-GPIB not correctly installed or bad address", + maxBuffer); return; case EABO: - strncpy(buffer,"Timeout on data transfer",maxBuffer); + strncpy(buffer, "Timeout on data transfer", maxBuffer); return; case EBUS: - strncpy(buffer,"No device connected to GPIB or address errror", - maxBuffer); + strncpy(buffer, "No device connected to GPIB or address errror", + maxBuffer); return; case ENOL: - strncpy(buffer,"No listeners on bus. Perhaps address error?", - maxBuffer); + strncpy(buffer, "No listeners on bus. Perhaps address error?", + maxBuffer); return; default: - strncpy(buffer,"Unrecognised error code, fix nigpib.c", - maxBuffer); + strncpy(buffer, "Unrecognised error code, fix nigpib.c", maxBuffer); break; } } + /*------------------------------------------------------------------*/ -void NIassign(pGPIB self){ +void NIassign(pGPIB self) +{ self->attach = NIattach; self->detach = NIdetach; self->send = NIwrite; diff --git a/nintf.c b/nintf.c index acfe1055..1c8a326e 100644 --- a/nintf.c +++ b/nintf.c @@ -8,40 +8,41 @@ ---------------------------------------------------------------------------*/ #include - float nintf(float f) - { - double ip, rm, dVal; - float fRes; +float nintf(float f) +{ + double ip, rm, dVal; + float fRes; - dVal = (double)f; - rm = modf(dVal,&ip); - if(rm < .0)rm = -rm; - if(rm > .5) - { - if(ip < .0) - ip -= 1.; - else - ip += 1.; + dVal = (double) f; + rm = modf(dVal, &ip); + if (rm < .0) + rm = -rm; + if (rm > .5) { + if (ip < .0) + ip -= 1.; + else + ip += 1.; - } - return (float) ip; } -/*-------------------------------------------------------------------*/ - double nintd(double f) - { - double ip, rm, dVal; - double fRes; + return (float) ip; +} - dVal = (double)f; - rm = modf(dVal,&ip); - if(rm < .0)rm = -rm; - if(rm > .5) - { - if(ip < .0) - ip -= 1.; - else - ip += 1.; +/*-------------------------------------------------------------------*/ +double nintd(double f) +{ + double ip, rm, dVal; + double fRes; + + dVal = (double) f; + rm = modf(dVal, &ip); + if (rm < .0) + rm = -rm; + if (rm > .5) { + if (ip < .0) + ip -= 1.; + else + ip += 1.; - } - return (double) ip; } + return (double) ip; +} diff --git a/nread.c b/nread.c index 49002932..56679cc1 100644 --- a/nread.c +++ b/nread.c @@ -41,381 +41,336 @@ #include "uselect.h" extern pServer pServ; -extern int VerifyChannel(mkChannel *self); /* defined in network.c */ +extern int VerifyChannel(mkChannel * self); /* defined in network.c */ #define NRMAGIC 1061996 /* #define TELNETDEBUG 1 */ - typedef enum { - tData, - tIAC, - tWill, - tWont, - tDo, - tDont, - tCR, - tSB, - tSBIN, - tSE } TelnetStatus; +typedef enum { + tData, + tIAC, + tWill, + tWont, + tDo, + tDont, + tCR, + tSB, + tSBIN, + tSE +} TelnetStatus; /*--------------------------------------------------------------------------*/ - typedef struct __netreader { - pServer pMain; /* The server ds */ - int iList; /* the list of sockets to check */ - int iPasswdTimeout; - int iReadTimeout; - int iEnd; - long lMagic; - pDynString conList; - } NetReader; +typedef struct __netreader { + pServer pMain; /* The server ds */ + int iList; /* the list of sockets to check */ + int iPasswdTimeout; + int iReadTimeout; + int iEnd; + long lMagic; + pDynString conList; +} NetReader; /*--------------------------------------------------------------------------- The structure used for an item in the Net Reader list of connections */ - typedef struct { - mkChannel *pSock; - SConnection *pCon; - eNRType eType; - char pHold[512]; - int iEOD; - TelnetStatus tStatus; - int iReadable; - } NetItem, *pNetItem; +typedef struct { + mkChannel *pSock; + SConnection *pCon; + eNRType eType; + char pHold[512]; + int iEOD; + TelnetStatus tStatus; + int iReadable; +} NetItem, *pNetItem; /*----------------------------------------------------------------------------*/ - pNetRead CreateNetReader(pServer pTask, int iPasswdTimeout, int iReadTimeout) - { - pNetRead pNew = NULL; - - assert(pTask); - assert(iPasswdTimeout > 0); - assert(iReadTimeout >= 0); - - pNew = (pNetRead)malloc(sizeof(NetReader)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(NetReader)); - - pNew->iList = LLDcreate(sizeof(NetItem)); - pNew->conList = CreateDynString(1024,1024); - if(pNew->iList < 0 || pNew->conList == NULL) - { - free(pNew); - return NULL; - } - pNew->pMain = pTask; - pNew->iPasswdTimeout = iPasswdTimeout; - pNew->iReadTimeout = iReadTimeout; - pNew->lMagic = NRMAGIC; - return pNew; - } -/*--------------------------------------------------------------------------*/ - void DeleteNetReader(void *pData) - { - pNetRead self = NULL; - - self = (pNetRead)pData; - assert(self); - if(self->lMagic != NRMAGIC) - { - return; - } - - LLDdelete(self->iList); - if(self->conList != NULL) - { - DeleteDynString(self->conList); - } - free(self); - } -/*--------------------------------------------------------------------------*/ - int NetReadRegister(pNetRead self, mkChannel *pSock, eNRType eType, - SConnection *pCon) - { - NetItem sItem, sEntry; - char buffer[80]; - int iRet; - - assert(self); - if(!VerifyChannel(pSock)) - { - return 0; - } - - sItem.pSock = pSock; - sItem.eType = eType; - sItem.pCon = pCon; - sItem.iEOD = 0; - sItem.tStatus = tData; - sItem.iReadable = 0; - memset(sItem.pHold,0,511); - - /* check if the entry is already there */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sEntry); - if(sEntry.pSock->sockid == pSock->sockid) - { - snprintf(buffer, sizeof buffer, "NetReadRegister twice %d type %d", pSock->sockid, eType); - WriteToCommandLog("SYS>",buffer); - return 1; - } - iRet = LLDnodePtr2Next(self->iList); - } +pNetRead CreateNetReader(pServer pTask, int iPasswdTimeout, + int iReadTimeout) +{ + pNetRead pNew = NULL; - LLDnodeAppendFrom(self->iList, &sItem); - return 1; + assert(pTask); + assert(iPasswdTimeout > 0); + assert(iReadTimeout >= 0); + + pNew = (pNetRead) malloc(sizeof(NetReader)); + if (!pNew) { + return NULL; } + memset(pNew, 0, sizeof(NetReader)); + + pNew->iList = LLDcreate(sizeof(NetItem)); + pNew->conList = CreateDynString(1024, 1024); + if (pNew->iList < 0 || pNew->conList == NULL) { + free(pNew); + return NULL; + } + pNew->pMain = pTask; + pNew->iPasswdTimeout = iPasswdTimeout; + pNew->iReadTimeout = iReadTimeout; + pNew->lMagic = NRMAGIC; + return pNew; +} + /*--------------------------------------------------------------------------*/ - int NetReadRemove(pNetRead self, mkChannel *pSock) - { - NetItem sItem; - int iRet; - - assert(self); - if(self->lMagic != NRMAGIC) - { - return 0; - } - - /* find the entry to remove */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sItem); - if(sItem.pSock == pSock) - { - LLDnodeDelete(self->iList); - return 1; - } - iRet = LLDnodePtr2Next(self->iList); - } +void DeleteNetReader(void *pData) +{ + pNetRead self = NULL; + + self = (pNetRead) pData; + assert(self); + if (self->lMagic != NRMAGIC) { + return; + } + + LLDdelete(self->iList); + if (self->conList != NULL) { + DeleteDynString(self->conList); + } + free(self); +} + +/*--------------------------------------------------------------------------*/ +int NetReadRegister(pNetRead self, mkChannel * pSock, eNRType eType, + SConnection * pCon) +{ + NetItem sItem, sEntry; + char buffer[80]; + int iRet; + + assert(self); + if (!VerifyChannel(pSock)) { return 0; } -/*-------------------------------------------------------------------------*/ - static int NetReadAccept(pNetRead self, mkChannel *pSock) - { - mkChannel *pNew = NULL; - char pBuffer[1064]; - int iRet; - SConnection *pRes = NULL; - char *pUser = NULL, *pPasswd = NULL; - time_t target; - - if(!VerifyChannel(pSock)) - { - return 0; - } - - /* check for new connection */ - pNew = NETAccept(pSock,0); - if(pNew) - { - /* create connection object */ - /* TODO - pRes = SCreateConnection(self->pMain->pSics,pNew,3); - */ - if(!pRes) - { - SICSLogWrite("Failure to allocate new Connection",eInternal); - NETClosePort(pNew); - free(pNew); - return 0; - } - else - { - /* register the connection and create a task for it here */ - NetReadRegister(self,pNew,command, pRes); - TaskRegister(self->pMain->pTasker, - SCTaskFunction, - SCSignalFunction, - SCDeleteConnection, - pRes, - 1); - SCSendOK(pRes); - return 1; - } - } - else - { - return 0; - } + + sItem.pSock = pSock; + sItem.eType = eType; + sItem.pCon = pCon; + sItem.iEOD = 0; + sItem.tStatus = tData; + sItem.iReadable = 0; + memset(sItem.pHold, 0, 511); + + /* check if the entry is already there */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sEntry); + if (sEntry.pSock->sockid == pSock->sockid) { + snprintf(buffer, sizeof buffer, "NetReadRegister twice %d type %d", + pSock->sockid, eType); + WriteToCommandLog("SYS>", buffer); + return 1; + } + iRet = LLDnodePtr2Next(self->iList); } + + LLDnodeAppendFrom(self->iList, &sItem); + return 1; +} + +/*--------------------------------------------------------------------------*/ +int NetReadRemove(pNetRead self, mkChannel * pSock) +{ + NetItem sItem; + int iRet; + + assert(self); + if (self->lMagic != NRMAGIC) { + return 0; + } + + /* find the entry to remove */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sItem); + if (sItem.pSock == pSock) { + LLDnodeDelete(self->iList); + return 1; + } + iRet = LLDnodePtr2Next(self->iList); + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +static int NetReadAccept(pNetRead self, mkChannel * pSock) +{ + mkChannel *pNew = NULL; + char pBuffer[1064]; + int iRet; + SConnection *pRes = NULL; + char *pUser = NULL, *pPasswd = NULL; + time_t target; + + if (!VerifyChannel(pSock)) { + return 0; + } + + /* check for new connection */ + pNew = NETAccept(pSock, 0); + if (pNew) { + /* create connection object */ + /* TODO + pRes = SCreateConnection(self->pMain->pSics,pNew,3); + */ + if (!pRes) { + SICSLogWrite("Failure to allocate new Connection", eInternal); + NETClosePort(pNew); + free(pNew); + return 0; + } else { + /* register the connection and create a task for it here */ + NetReadRegister(self, pNew, command, pRes); + TaskRegister(self->pMain->pTasker, + SCTaskFunction, + SCSignalFunction, SCDeleteConnection, pRes, 1); + SCSendOK(pRes); + return 1; + } + } else { + return 0; + } +} + /*--------------------------------------------------------------------------*/ #define COLLECT 0 #define SKIPTERM 1 /*------------------------------------------------------------------------*/ - static int NetReadRead(pNetRead self, pNetItem pItem) - { - char *pPtr, *pEnd, *pBufEnd; - char pBuffer[1024], pMuell[20]; - char pBueffel[80]; - int i, iInt, iRet, iStat, state; +static int NetReadRead(pNetRead self, pNetItem pItem) +{ + char *pPtr, *pEnd, *pBufEnd; + char pBuffer[1024], pMuell[20]; + char pBueffel[80]; + int i, iInt, iRet, iStat, state; - /* read first */ - memset(pBuffer,0,1024); - iRet = NETRead(pItem->pCon->pSock,pBuffer, 1022,0); - if(iRet < 0) /* EOF */ - { - pItem->pCon->iEnd = 1; - NetReadRemove(self,pItem->pCon->pSock); - return 0; - } - else if(iRet == 0) /* should not happen */ - { - return 1; - } - /* iRet is now the number of bytes read. Now we check for command - interrupts */ - pPtr = strstr(pBuffer,"INT1712"); - if(pPtr) - { - sscanf(pPtr, "%s %d",pMuell, &iInt); - if(SCMatchRights(pItem->pCon,usUser)) - { - TaskSignal(self->pMain->pTasker, SICSINT, &iInt); - sprintf(pBueffel,"INTERRUPT %d issued on sock %d", - iInt,pItem->pCon->pSock->sockid); - WriteToCommandLog("SYS>",pBueffel); - if(iInt == eEndServer) - { - TaskStop(self->pMain->pTasker); - } - } - else - { - SCWrite(pItem->pCon, - "ERROR: insufficient privilege to invoke Interrupt", - eError); - } - return 0; - } - - /* split into command lines - and put into fifo - */ - pBufEnd = pBuffer + iRet; - pPtr = pBuffer; - pEnd = pBuffer; - state = COLLECT; - while(pEnd < pBufEnd) - { - switch(state) - { - case COLLECT: - if( (*pEnd != '\r') && (*pEnd != '\n')) - { - pEnd++; - } - else - { - /* there is a string between pPtr and pEnd */ - *pEnd = '\0'; - /* do we have something in hold ? */ - if(strlen(pItem->pHold) > 0) - { - strcat(pItem->pHold,pPtr); - iStat = CostaTop(pItem->pCon->pStack,pItem->pHold); - if(!iStat) - { - SCWrite(pItem->pCon,"ERROR: Busy",eError); - } - pItem->pHold[0] = '\0'; - } - else - { - /* no, normal command */ - iStat = CostaTop(pItem->pCon->pStack,pPtr); - if(!iStat) - { - SCWrite(pItem->pCon,"ERROR: Busy",eError); - } - } - pPtr = pEnd +1; - pEnd = pPtr; - state = SKIPTERM; - } - break; - case SKIPTERM: - if( (*pEnd != '\r') && (*pEnd != '\n')) - { - state = COLLECT; - pPtr = pEnd; - } - else - { - pEnd++; - pPtr = pEnd; - } - break; - } - } - /* when we are here we may still have an incomplete command pending */ - if(pEnd != pPtr && strlen(pPtr) > 0) - { - strcpy(pItem->pHold,pPtr); - } - return 1; - } -/*-------------------------- telnet protocoll code -------------------------*/ - static int TelnetAccept(pNetRead self, mkChannel *pSock) - { - mkChannel *pNew = NULL; - char pBuffer[1064]; - int iRet; - SConnection *pRes = NULL; - pTelTask pTel = NULL; - - if(!VerifyChannel(pSock)) - { - return 0; - } - - /* check for new connection */ - pNew = NETAccept(pSock,0); - if(pNew) - { - /* create connection object */ - /* TODO - pRes = SCreateConnection(self->pMain->pSics,pNew,usSpy); - */ - if(!pRes) - { - SICSLogWrite("Failure to allocate new Connection",eInternal); - NETClosePort(pNew); - free(pNew); - return 0; - } - else - { - /* Create a task object for the telnet connection */ - pTel = CreateTelnet(pRes); - if(!pTel) - { - SICSLogWrite("Failure to allocate new Telnet Task Object", - eInternal); - SCDeleteConnection(pRes); - return 0; - } - /* register connection and task */ - pRes->iTelnet = 1; - NetReadRegister(self,pNew,tcommand, pRes); - TaskRegister(self->pMain->pTasker, - TelnetTask, - TelnetSignal, - DeleteTelnet, - pTel, - 1); - return 1; - } - } - else - { - return 0; - } + /* read first */ + memset(pBuffer, 0, 1024); + iRet = NETRead(pItem->pCon->pSock, pBuffer, 1022, 0); + if (iRet < 0) { /* EOF */ + pItem->pCon->iEnd = 1; + NetReadRemove(self, pItem->pCon->pSock); + return 0; + } else if (iRet == 0) { /* should not happen */ + return 1; } + /* iRet is now the number of bytes read. Now we check for command + interrupts */ + pPtr = strstr(pBuffer, "INT1712"); + if (pPtr) { + sscanf(pPtr, "%s %d", pMuell, &iInt); + if (SCMatchRights(pItem->pCon, usUser)) { + TaskSignal(self->pMain->pTasker, SICSINT, &iInt); + sprintf(pBueffel, "INTERRUPT %d issued on sock %d", + iInt, pItem->pCon->pSock->sockid); + WriteToCommandLog("SYS>", pBueffel); + if (iInt == eEndServer) { + TaskStop(self->pMain->pTasker); + } + } else { + SCWrite(pItem->pCon, + "ERROR: insufficient privilege to invoke Interrupt", eError); + } + return 0; + } + + /* split into command lines + and put into fifo + */ + pBufEnd = pBuffer + iRet; + pPtr = pBuffer; + pEnd = pBuffer; + state = COLLECT; + while (pEnd < pBufEnd) { + switch (state) { + case COLLECT: + if ((*pEnd != '\r') && (*pEnd != '\n')) { + pEnd++; + } else { + /* there is a string between pPtr and pEnd */ + *pEnd = '\0'; + /* do we have something in hold ? */ + if (strlen(pItem->pHold) > 0) { + strcat(pItem->pHold, pPtr); + iStat = CostaTop(pItem->pCon->pStack, pItem->pHold); + if (!iStat) { + SCWrite(pItem->pCon, "ERROR: Busy", eError); + } + pItem->pHold[0] = '\0'; + } else { + /* no, normal command */ + iStat = CostaTop(pItem->pCon->pStack, pPtr); + if (!iStat) { + SCWrite(pItem->pCon, "ERROR: Busy", eError); + } + } + pPtr = pEnd + 1; + pEnd = pPtr; + state = SKIPTERM; + } + break; + case SKIPTERM: + if ((*pEnd != '\r') && (*pEnd != '\n')) { + state = COLLECT; + pPtr = pEnd; + } else { + pEnd++; + pPtr = pEnd; + } + break; + } + } + /* when we are here we may still have an incomplete command pending */ + if (pEnd != pPtr && strlen(pPtr) > 0) { + strcpy(pItem->pHold, pPtr); + } + return 1; +} + +/*-------------------------- telnet protocoll code -------------------------*/ +static int TelnetAccept(pNetRead self, mkChannel * pSock) +{ + mkChannel *pNew = NULL; + char pBuffer[1064]; + int iRet; + SConnection *pRes = NULL; + pTelTask pTel = NULL; + + if (!VerifyChannel(pSock)) { + return 0; + } + + /* check for new connection */ + pNew = NETAccept(pSock, 0); + if (pNew) { + /* create connection object */ + /* TODO + pRes = SCreateConnection(self->pMain->pSics,pNew,usSpy); + */ + if (!pRes) { + SICSLogWrite("Failure to allocate new Connection", eInternal); + NETClosePort(pNew); + free(pNew); + return 0; + } else { + /* Create a task object for the telnet connection */ + pTel = CreateTelnet(pRes); + if (!pTel) { + SICSLogWrite("Failure to allocate new Telnet Task Object", + eInternal); + SCDeleteConnection(pRes); + return 0; + } + /* register connection and task */ + pRes->iTelnet = 1; + NetReadRegister(self, pNew, tcommand, pRes); + TaskRegister(self->pMain->pTasker, + TelnetTask, TelnetSignal, DeleteTelnet, pTel, 1); + return 1; + } + } else { + return 0; + } +} + /*------------------------------------------------------------------------ Telnet is fully described in RFC-854. This implementation is very simple. It just supports the NVT and no options. Implementation is via a state @@ -425,7 +380,7 @@ extern int VerifyChannel(mkChannel *self); /* defined in network.c */ /* Telnet codes */ #define SE 240 #define NOP 241 -#define DM 242 /* data mark */ +#define DM 242 /* data mark */ #define BRK 243 #define IP 244 #define AO 245 @@ -441,986 +396,938 @@ extern int VerifyChannel(mkChannel *self); /* defined in network.c */ #define IAC 255 #define EOR 239 /*-----------------------------------------------------------------------*/ - static int TelnetReply(pNetItem pItem, char code, char cChar) - { - char pReply[3]; - - pReply[0] = IAC; - pReply[1] = code; - pReply[2] = cChar; - - NETWrite(pItem->pCon->pSock,pReply,3); - return 1; - } -/*------------------------------------------------------------------------*/ - static int TelnetRead(pNetRead self, pNetItem pItem) - { - char pBuffer[1024], pMuell[20], pError[256]; - int i, iStat, iInt, iRet; - int cChar; - char *pPtr = NULL; - SConnection *pOwner = NULL; - - /* read first */ - memset(pBuffer,0,1023); - iRet = NETRead(pItem->pCon->pSock,pBuffer, 1022,0); - if(iRet < 0) /* EOF */ - { - pItem->pCon->iEnd = 1; - NetReadRemove(self,pItem->pCon->pSock); - return 0; - } - else if(iRet == 0) /* should not happen */ - { - return 1; - } - - /* iRet is now the number of bytes read. Now we check for command - interrupts */ - pPtr = strstr(pBuffer,"INT1712"); - if(pPtr) - { - sscanf(pPtr, "%s %d",pMuell, &iInt); - if(SCMatchRights(pItem->pCon,usUser)) - { - /* owners may kill own tasks, otherwise manager - privilege is required. - */ - pOwner = GetExeOwner(pServ->pExecutor); - if(pOwner) - { - if(pOwner != pItem->pCon) - { - if(!SCMatchRights(pItem->pCon,usMugger)) - { - SCWrite(pItem->pCon, - "ERROR: Insufficient privilege to stop other people's experiments", - eError); - return 1; - } - } - } - TaskSignal(self->pMain->pTasker, SICSINT, &iInt); - sprintf(pError,"INTERRUPT %d issued on sock %d",iInt, - pItem->pCon->pSock->sockid); - WriteToCommandLog("SYS>",pError); - if(iInt == eEndServer) - { - TaskStop(self->pMain->pTasker); - } - } - else - { - SCWrite(pItem->pCon,"ERROR: insufficient privilege to invoke Interrupt", - eError); - } - return 1; - } - - /* do telnet analysis of the data buffer */ - for(i = 0; i < iRet; i++) - { - cChar = (int)pBuffer[i]; -#ifdef TELNETDEBUG - if( (cChar > 48) && (cChar < 128) ) - { - printf("char: %c\n",cChar); - } - else - { - printf("Control: %d\n",cChar); - } -#endif - /* Telnet status switching */ - switch(pItem->tStatus) - { - case tData: - switch(cChar) - { - case IAC: - pItem->tStatus = tIAC; - break; - case '\r': - case '\n': - iStat = CostaTop(pItem->pCon->pStack,pItem->pHold); - /* printf("%s\n",pItem->pHold); */ - if(!iStat) - { - SCWrite(pItem->pCon,"ERROR: Busy",eError); - } - memset(pItem->pHold,0,511); - pItem->iEOD = 0; - pItem->tStatus = tCR; - break; - case (char)8: /* backspace */ - pItem->iEOD--; - if(pItem->iEOD < 0) - { - pItem->iEOD = 0; - } - break; - case (char)0:/* ignore 0 character sent as end of text */ - break; - default: - pItem->pHold[pItem->iEOD] = cChar; - pItem->iEOD++; - break; - - } /* end of tData case */ - break; - case tCR: /* ignore the second character after a newline. - Telnet gives you two characters for newline - */ - pItem->tStatus = tData; - break; - case tIAC: - switch(cChar) - { - case IAC: - pItem->tStatus = tData; - break; - case WILL: - pItem->tStatus = tWill; - break; - case WONT: - pItem->tStatus = tWont; - break; - case DONT: - pItem->tStatus = tDont; - break; - case DO: - pItem->tStatus = tDo; - break; - case EOR: - pItem->tStatus = tData; - break; - case SB: - pItem->tStatus = tSB; - break; - case EC: - pItem->iEOD--; - if(pItem->iEOD < 0) - { - pItem->iEOD = 0; - } - pItem->tStatus = tData; - break; - case EL: - memset(pItem->pHold,0,511); - pItem->iEOD = 0; - pItem->tStatus = tData; - break; - case IP: - SCSetInterrupt(pItem->pCon,eAbortBatch); - pItem->tStatus = tData; - break; - default: - pItem->tStatus = tData; - break; - } /* end of tIAC */ - break; - case tWill: /* we do not do options! */ - TelnetReply(pItem,DONT,cChar); - pItem->tStatus = tData; - break; - case tWont: /* we do not do options! A Wont is sent by the client - if it cannot do a option we requested it to have. As - we do not try to force options, this should not happen - */ - pItem->tStatus = tData; - break; - case tDo: /* we do not do options! */ - TelnetReply(pItem,WONT,cChar); - pItem->tStatus = tData; - break; - case tDont: /* we do not do options! A Dont is sent by the client - if it cannot do a option we requested it to have. As - we do not try to force options, this should not happen - */ - pItem->tStatus = tData; - break; - case tSB: /* as we do not have options, we cannot have suboption - negotaitions. Something is seriously wrong when - we are here. It is a protocoll error. However, we - ignore it silently. tSB marks the start of the - subnegotiation. The current character must be the - option code we are dealing with. - */ - pItem->tStatus = tSE; - break; - case tSE: - /* now we are in the suboption parameter. Normally data - should be copied to a suboption string buffer here - until SE. - */ - switch(cChar) - { - case IAC: - break; - case SE: - pItem->tStatus = tData; - /* suboption interpretation would go here */ - break; - default: - /* copy data to suboption buffer */ - break; - } - break; - - default: - /* There is something wrong here! */ - sprintf(pError,"ERROR: bad telnet code %d", cChar); - SICSLogWrite(pError,eInternal); - pItem->tStatus = tData; - break; - - } - } - return 1; - } - -/*---------------------------------------------------------------------------*/ - static int NetReadUDP(pNetRead self, pNetItem pItem) - { - char pBueffel[512], pMuell[20]; - int iRet, iInt; - char *pPtr = NULL; - - /* read */ - iRet = UDPRead(pItem->pSock,pBueffel,510,0); - if(iRet > 10) /* something has beeen sent, verfify */ - { - pPtr = strstr(pBueffel,"SICSINT"); - if(pPtr) - { - sscanf(pPtr,"%s %d", pMuell, &iInt); - TaskSignal(self->pMain->pTasker, SICSINT, &iInt); - if(iInt == eEndServer) - { - TaskStop(self->pMain->pTasker); - } - return 1; - } - } - return 0; - } -/*-------------------------------------------------------------------------*/ - int NetReaderTask(void *pData) - { - pNetRead self = NULL; - fd_set lMask; - struct timeval tmo = {0,1}; - int iRet, iStatus; - int iCount; - NetItem NItem; - int conCount = 0; - char num[50]; - IPair *options = NULL; - - self = (pNetRead)pData; - assert(self); - if(self->lMagic != NRMAGIC) - { - return 0; - } - - /* check for end */ - if(self->iEnd) - { - return 0; - } - - ANETprocess(); +static int TelnetReply(pNetItem pItem, char code, char cChar) +{ + char pReply[3]; - /* build the select mask */ - FD_ZERO(&lMask); - iRet = LLDnodePtr2First(self->iList); - iCount = 0; - DynStringClear(self->conList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&NItem); - if(!VerifyChannel(NItem.pSock)) - { + pReply[0] = IAC; + pReply[1] = code; + pReply[2] = cChar; + + NETWrite(pItem->pCon->pSock, pReply, 3); + return 1; +} + +/*------------------------------------------------------------------------*/ +static int TelnetRead(pNetRead self, pNetItem pItem) +{ + char pBuffer[1024], pMuell[20], pError[256]; + int i, iStat, iInt, iRet; + int cChar; + char *pPtr = NULL; + SConnection *pOwner = NULL; + + /* read first */ + memset(pBuffer, 0, 1023); + iRet = NETRead(pItem->pCon->pSock, pBuffer, 1022, 0); + if (iRet < 0) { /* EOF */ + pItem->pCon->iEnd = 1; + NetReadRemove(self, pItem->pCon->pSock); + return 0; + } else if (iRet == 0) { /* should not happen */ + return 1; + } + + /* iRet is now the number of bytes read. Now we check for command + interrupts */ + pPtr = strstr(pBuffer, "INT1712"); + if (pPtr) { + sscanf(pPtr, "%s %d", pMuell, &iInt); + if (SCMatchRights(pItem->pCon, usUser)) { + /* owners may kill own tasks, otherwise manager + privilege is required. + */ + pOwner = GetExeOwner(pServ->pExecutor); + if (pOwner) { + if (pOwner != pItem->pCon) { + if (!SCMatchRights(pItem->pCon, usMugger)) { + SCWrite(pItem->pCon, + "ERROR: Insufficient privilege to stop other people's experiments", + eError); + return 1; + } + } + } + TaskSignal(self->pMain->pTasker, SICSINT, &iInt); + sprintf(pError, "INTERRUPT %d issued on sock %d", iInt, + pItem->pCon->pSock->sockid); + WriteToCommandLog("SYS>", pError); + if (iInt == eEndServer) { + TaskStop(self->pMain->pTasker); + } + } else { + SCWrite(pItem->pCon, + "ERROR: insufficient privilege to invoke Interrupt", eError); + } + return 1; + } + + /* do telnet analysis of the data buffer */ + for (i = 0; i < iRet; i++) { + cChar = (int) pBuffer[i]; +#ifdef TELNETDEBUG + if ((cChar > 48) && (cChar < 128)) { + printf("char: %c\n", cChar); + } else { + printf("Control: %d\n", cChar); + } +#endif + /* Telnet status switching */ + switch (pItem->tStatus) { + case tData: + switch (cChar) { + case IAC: + pItem->tStatus = tIAC; + break; + case '\r': + case '\n': + iStat = CostaTop(pItem->pCon->pStack, pItem->pHold); + /* printf("%s\n",pItem->pHold); */ + if (!iStat) { + SCWrite(pItem->pCon, "ERROR: Busy", eError); + } + memset(pItem->pHold, 0, 511); + pItem->iEOD = 0; + pItem->tStatus = tCR; + break; + case (char) 8: /* backspace */ + pItem->iEOD--; + if (pItem->iEOD < 0) { + pItem->iEOD = 0; + } + break; + case (char) 0: /* ignore 0 character sent as end of text */ + break; + default: + pItem->pHold[pItem->iEOD] = cChar; + pItem->iEOD++; + break; + + } /* end of tData case */ + break; + case tCR: /* ignore the second character after a newline. + Telnet gives you two characters for newline + */ + pItem->tStatus = tData; + break; + case tIAC: + switch (cChar) { + case IAC: + pItem->tStatus = tData; + break; + case WILL: + pItem->tStatus = tWill; + break; + case WONT: + pItem->tStatus = tWont; + break; + case DONT: + pItem->tStatus = tDont; + break; + case DO: + pItem->tStatus = tDo; + break; + case EOR: + pItem->tStatus = tData; + break; + case SB: + pItem->tStatus = tSB; + break; + case EC: + pItem->iEOD--; + if (pItem->iEOD < 0) { + pItem->iEOD = 0; + } + pItem->tStatus = tData; + break; + case EL: + memset(pItem->pHold, 0, 511); + pItem->iEOD = 0; + pItem->tStatus = tData; + break; + case IP: + SCSetInterrupt(pItem->pCon, eAbortBatch); + pItem->tStatus = tData; + break; + default: + pItem->tStatus = tData; + break; + } /* end of tIAC */ + break; + case tWill: /* we do not do options! */ + TelnetReply(pItem, DONT, cChar); + pItem->tStatus = tData; + break; + case tWont: /* we do not do options! A Wont is sent by the client + if it cannot do a option we requested it to have. As + we do not try to force options, this should not happen + */ + pItem->tStatus = tData; + break; + case tDo: /* we do not do options! */ + TelnetReply(pItem, WONT, cChar); + pItem->tStatus = tData; + break; + case tDont: /* we do not do options! A Dont is sent by the client + if it cannot do a option we requested it to have. As + we do not try to force options, this should not happen + */ + pItem->tStatus = tData; + break; + case tSB: /* as we do not have options, we cannot have suboption + negotaitions. Something is seriously wrong when + we are here. It is a protocoll error. However, we + ignore it silently. tSB marks the start of the + subnegotiation. The current character must be the + option code we are dealing with. + */ + pItem->tStatus = tSE; + break; + case tSE: + /* now we are in the suboption parameter. Normally data + should be copied to a suboption string buffer here + until SE. + */ + switch (cChar) { + case IAC: + break; + case SE: + pItem->tStatus = tData; + /* suboption interpretation would go here */ + break; + default: + /* copy data to suboption buffer */ break; } + break; - sprintf(num,"%d, type %d:", NItem.pSock->sockid, NItem.eType); - if(conCount < 100){ - DynStringConcat(self->conList,num); - } - FD_SET(NItem.pSock->sockid,&lMask); - if(NItem.pSock->sockid > iCount) - { - iCount = NItem.pSock->sockid; - } - conCount++; - if(conCount > 100){ - WriteToCommandLog("WAYTOMANYCONNECTIONS> ", GetCharArray(self->conList)); - } - iRet = LLDnodePtr2Next(self->iList); - } + default: + /* There is something wrong here! */ + sprintf(pError, "ERROR: bad telnet code %d", cChar); + SICSLogWrite(pError, eInternal); + pItem->tStatus = tData; + break; - if(conCount > 100){ - WriteToCommandLog("WAYTOMANYCONNECTIONS> ", GetCharArray(self->conList)); } - - snprintf(num,sizeof num,"%d", conCount); - IFSetOption(pSICSOptions,"ConnectionCount",num); - IFSetOption(pSICSOptions,"ConMask",GetCharArray(self->conList)); - - - /* the select itself */ - tmo.tv_usec = self->iReadTimeout; - iCount++; - iRet = uselect(iCount, &lMask,NULL,NULL,&tmo); - if(iRet <= 0) /* no pending request */ - { + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int NetReadUDP(pNetRead self, pNetItem pItem) +{ + char pBueffel[512], pMuell[20]; + int iRet, iInt; + char *pPtr = NULL; + + /* read */ + iRet = UDPRead(pItem->pSock, pBueffel, 510, 0); + if (iRet > 10) { /* something has beeen sent, verfify */ + pPtr = strstr(pBueffel, "SICSINT"); + if (pPtr) { + sscanf(pPtr, "%s %d", pMuell, &iInt); + TaskSignal(self->pMain->pTasker, SICSINT, &iInt); + if (iInt == eEndServer) { + TaskStop(self->pMain->pTasker); + } return 1; } - - - /* now go through all registered things and handle the message */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&NItem); - if(FD_ISSET(NItem.pSock->sockid,&lMask)) /* data */ - { - switch(NItem.eType) - { - /* lists have been changed after accept, return */ - case naccept: - NetReadAccept(self,NItem.pSock); - return 1; - break; - case taccept: - TelnetAccept(self,NItem.pSock); - return 1; - break; - case command: - iStatus = NetReadRead(self,&NItem); - if(iStatus == 0) /* there was an eof */ - { - /* do not continue, list is messy */ - return 1; - } - break; - case tcommand: - iStatus = TelnetRead(self,&NItem); - if(iStatus == 0) /* there was an eof */ - { - /* do not continue, list is messy */ - return 1; - } - break; - case udp: - NetReadUDP(self,&NItem); - break; - case user: - NItem.iReadable = 1; - LLDnodeDataFrom(self->iList, &NItem); - break; - } - LLDnodeDataFrom(self->iList,&NItem); - } - iRet = LLDnodePtr2Next(self->iList); - } - - /* done, finally */ - return 1; - } -/*--------------------------------------------------------------------------*/ - void NetReaderSignal(void *pUser, int iSignal, void *pEventData) - { - pNetRead self = NULL; - int *iInt; - - self = (pNetRead)pUser; - assert(self); - iInt = (int *)pEventData; - - if(iSignal == SICSINT) - { - iInt = (int *)pEventData; - if(*iInt == eEndServer) - { - self->iEnd = 1; - } - } - } -/*--------------------------------------------------------------------------*/ - typedef struct { - pNetRead pRead; - mkChannel *pChan; - int iEnd; - } ReadWait, *pReadWait; -/*--------------------------------------------------------------------------*/ - static void ReadWaitFree(void *pData) - { - pReadWait pWait = NULL; - - pWait = (pReadWait)pData; - if(!pWait) - { - return; - } - - if(pWait->pChan) - { - free(pWait->pChan); - } - free(pWait); - } -/*--------------------------------------------------------------------------*/ - static void ReadWaitSignal(void *pUser, int iSignal, void *pSigData) - { - pReadWait pWait = NULL; - int *iInt; - - pWait = (pReadWait)pUser; - assert(pWait); - - if(iSignal == SICSINT) - { - iInt = (int *)pSigData; - if(*iInt != eContinue) - { - pWait->iEnd = 1; - } - } - } -/*---------------------------------------------------------------------------*/ - static int Wait4ReadTask(void *pData) - { - pReadWait pWait = NULL; - NetItem sItem; - int iRet; - - pWait = (pReadWait)pData; - assert(pWait); - - if(pWait->iEnd) - { - return 0; /* an interrupt occurred */ - } - - iRet = LLDnodePtr2First(pWait->pRead->iList); - while(iRet != 0) - { - LLDnodeDataTo(pWait->pRead->iList, &sItem); - if(sItem.pSock == pWait->pChan) - { - if(sItem.iReadable) - { - NetReadRemove(pWait->pRead,pWait->pChan); - return 0; - } - } - iRet = LLDnodePtr2Next(pWait->pRead->iList); - } - return 1; - } -/*---------------------------------------------------------------------------*/ - int NetReadWait4Data(pNetRead self, int iSocket) - { - pReadWait pNew = NULL; - mkChannel *pChan = NULL; - long lID; - int iRet; - - /* make a new ReadWait */ - pNew = (pReadWait)malloc(sizeof(ReadWait)); - if(!pNew) - { - return 0; - } - - /* make a new channel */ - pChan = (mkChannel *)malloc(sizeof(mkChannel)); - if(!pChan) - { - free(pNew); - return 0; - } - pChan->sockid = iSocket; - pChan->lMagic = NETMAGIC; - - /* put it into the NetReader */ - iRet = NetReadRegister(self,pChan,user,NULL); - if(!iRet) - { - return 0; - } - - /* start the wait task */ - pNew->pChan = pChan; - pNew->iEnd = 0; - pNew->pRead = self; - lID = TaskRegister(self->pMain->pTasker, - Wait4ReadTask, - ReadWaitSignal, - ReadWaitFree, - pNew,0); - - /* wait for finish */ - TaskWait(self->pMain->pTasker,lID); - - return 1; - } -/*--------------------------------------------------------------------------*/ - int NetReadRegisterUserSocket(pNetRead self, int iSocket) - { - mkChannel *pChan = NULL; - int iRet; - - - /* make a new channel */ - pChan = (mkChannel *)malloc(sizeof(mkChannel)); - if(!pChan) - { - return 0; - } - pChan->sockid = iSocket; - pChan->lMagic = NETMAGIC; - - /* put it into the NetReader */ - iRet = NetReadRegister(self,pChan,user,NULL); - if(!iRet) - { - return 0; - } - return 1; - } -/*--------------------------------------------------------------------------*/ - int NetReadRemoveUserSocket(pNetRead self, int iSocket) - { - NetItem sItem; - int iRet; - - assert(self); - if(self->lMagic != NRMAGIC) - { - return 0; - } - - /* find the entry to remove */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sItem); - if(sItem.eType == user) - { - if(sItem.pSock->sockid == iSocket) - { - free(sItem.pSock); - LLDnodeDelete(self->iList); - return 1; - } - } - iRet = LLDnodePtr2Next(self->iList); - } - return 0; - } -/*--------------------------------------------------------------------------*/ - int NetReadReadable(pNetRead self, int iSocket) - { - NetItem sItem; - int iRet; - - assert(self); - - /* find the entry to read */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sItem); - if(sItem.eType == user) - { - if(sItem.pSock->sockid == iSocket) - { - if(sItem.iReadable) - { - return 1; - } - else - { - return 0; - } - } - } - iRet = LLDnodePtr2Next(self->iList); - } - return 0; - } -/*--------------------------------------------------------------------------*/ - int NetReadResetUser(pNetRead self, int iSocket) - { - NetItem sItem; - int iRet; - - assert(self); - - /* find the entry to remove */ - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sItem); - if(sItem.eType == user) - { - if(sItem.pSock->sockid == iSocket) - { - sItem.iReadable = 0; - LLDnodeDataFrom(self->iList,&sItem); - return 1; - } - } - iRet = LLDnodePtr2Next(self->iList); - } - return 0; - } -/*=================================================================================== - * new code to support the ANET network stuff - * =================================================================================*/ -typedef struct { - pDynString command; - int state; - SConnection *pCon; -}CommandCBData, *pCommandCBData; -/*----------------------------------------------------------------------------------*/ -static void killCommandCBData(void *data){ - pCommandCBData self = (pCommandCBData)data; - if(self == NULL){ - return; - } - if(self->command != NULL){ - DeleteDynString(self->command); - } - free(self); -} -/*----------------------------------------------------------------------------------*/ -static int testAndInvokeInterrupt(pCommandCBData self, int handle){ - char *pPtr; - char buffer[512]; - int iInt; - - pPtr = GetCharArray(self->command); - if(strstr(pPtr,"INT1712") != NULL){ - sscanf(pPtr, "%s %d",buffer, &iInt); - if(SCMatchRights(self->pCon,usUser)) { - TaskSignal(pServ->pTasker, SICSINT, &iInt); - snprintf(buffer,512, "INTERRUPT %d issued on sock %d", - iInt,handle); - WriteToCommandLog("SYS>", buffer); - if(iInt == eEndServer){ - TaskStop(pServ->pTasker); - } - } else { - SCWrite(self->pCon, - "ERROR: insufficient privilege to invoke Interrupt", - eError); - } - return 1; - } - return 0; -} -/*----------------------------------------------------------------------------------*/ -static int CommandDataCB(int handle, void *userData){ - pCommandCBData self = (pCommandCBData)userData; - int i, length, status; - char *pPtr = NULL; - - assert(self != NULL); - pPtr = ANETreadPtr(handle,&length); - if(pPtr == NULL){ - return 1; - } - for(i = 0; i < length; i++){ - switch(self->state){ - case COLLECT: - if(pPtr[i] == '\r' || pPtr[i] == '\n'){ - self->state = SKIPTERM; - if(!testAndInvokeInterrupt(self,handle)){ - status = CostaTop(self->pCon->pStack, GetCharArray(self->command)); - if(!status){ - SCWrite(self->pCon,"ERROR: Busy", eError); - } - } - DynStringClear(self->command); - } else { - if(pPtr[i] != '\0'){ - DynStringConcatChar(self->command, pPtr[i]); - } - } - break; - case SKIPTERM: - if(pPtr[i] != '\r' && pPtr[i] != '\n' && pPtr[i] != '\0'){ - DynStringConcatChar(self->command, pPtr[i]); - self->state = COLLECT; - } - break; - } - } - ANETreadConsume(handle, length); - return 1; -} -/*----------------------------------------------------------------------------------*/ -static int CommandAcceptCB(int handle, void *userData){ - SConnection *pCon = NULL; - pCommandCBData usData = NULL; - - pCon = SCreateConnection(pServ->pSics, handle, 3); - usData = malloc(sizeof(CommandCBData)); - if(pCon == NULL || usData == NULL){ - SICSLogWrite("Failure to allocate new Connection",eInternal); - return 0; - } - usData->command = CreateDynString(256,256); - if(usData->command == NULL){ - SICSLogWrite("Failure to allocate new Connection",eInternal); - return 0; - } - usData->pCon = pCon; - usData->state = COLLECT; - TaskRegister(pServ->pTasker, - SCTaskFunction, - SCSignalFunction, - SCDeleteConnection, - pCon, - 1); - ANETsetReadCallback(handle, CommandDataCB, - usData, killCommandCBData); - SCSendOK(pCon); - return 1; -} -/*-----------------------------------------------------------------------*/ - static int ANETTelnetReply(int sockHandle, char code, char cChar) - { - char pReply[3]; - - pReply[0] = IAC; - pReply[1] = code; - pReply[2] = cChar; - - ANETwrite(sockHandle,pReply,3); - return 1; - } -/*-----------------------------------------------------------------------*/ -static int ANETTelnetProcess(int handle, void *usData){ - pCommandCBData self = NULL; - int length, status, i; - int cChar; - char *pPtr = NULL; - char pError[256]; - - self = (pCommandCBData)usData; - assert(self != NULL); - - pPtr = ANETreadPtr(handle,&length); - - /* do telnet analysis of the data buffer */ - for(i = 0; i < length; i++){ - cChar = (int)pPtr[i]; -#ifdef TELNETDEBUG - if( (cChar > 48) && (cChar < 128) ){ - printf("char: %c\n",cChar); - } else { - printf("Control: %d\n",cChar); - } -#endif - /* Telnet status switching */ - switch(self->state){ - case tData: - switch(cChar){ - case IAC: - self->state = tIAC; - break; - case '\r': - case '\n': - if(!testAndInvokeInterrupt(self,handle)){ - status = CostaTop(self->pCon->pStack, GetCharArray(self->command)); - if(!status){ - SCWrite(self->pCon,"ERROR: Busy", eError); - } - } - self->state = tCR; - DynStringClear(self->command); - break; - case (char)8: /* backspace */ - DynStringBackspace(self->command); - break; - case (char)0:/* ignore 0 character sent as end of text */ - break; - default: - DynStringConcatChar(self->command,(char)cChar); - break; - - } /* end of tData case */ - break; - case tCR: - if(cChar == '\r' || cChar == '\n' || cChar == '\0'){ - continue; - } else { - self->state = tData; - DynStringConcatChar(self->command,(char)cChar); - } - break; - case tIAC: - switch(cChar) - { - case IAC: - self->state = tData; - break; - case WILL: - self->state = tWill; - break; - case WONT: - self->state = tWont; - break; - case DONT: - self->state = tDont; - break; - case DO: - self->state = tDo; - break; - case EOR: - self->state = tData; - break; - case SB: - self->state = tSB; - break; - case EC: - DynStringBackspace(self->command); - self->state = tData; - break; - case EL: - DynStringClear(self->command); - self->state = tData; - break; - case IP: - SCSetInterrupt(self->pCon,eAbortBatch); - self->state = tData; - break; - default: - self->state = tData; - break; - } /* end of tIAC */ - break; - case tWill: /* we do not do options! */ - ANETTelnetReply(handle,DONT,cChar); - self->state = tData; - break; - case tWont: /* we do not do options! A Wont is sent by the client - if it cannot do a option we requested it to have. As - we do not try to force options, this should not happen - */ - self->state = tData; - break; - case tDo: /* we do not do options! */ - ANETTelnetReply(handle,WONT,cChar); - self->state = tData; - break; - case tDont: /* we do not do options! A Dont is sent by the client - if it cannot do a option we requested it to have. As - we do not try to force options, this should not happen - */ - self->state = tData; - break; - case tSB: /* as we do not have options, we cannot have suboption - negotaitions. Something is seriously wrong when - we are here. It is a protocoll error. However, we - ignore it silently. tSB marks the start of the - subnegotiation. The current character must be the - option code we are dealing with. - */ - self->state = tSE; - break; - case tSE: - /* now we are in the suboption parameter. Normally data - should be copied to a suboption string buffer here - until SE. - */ - switch(cChar) - { - case IAC: - break; - case SE: - self->state = tData; - /* suboption interpretation would go here */ - break; - default: - /* copy data to suboption buffer */ - break; - } - break; - - default: - /* There is something wrong here! */ - sprintf(pError,"ERROR: bad telnet code %d", cChar); - SICSLogWrite(pError,eInternal); - self->state = tData; - break; - - } /* end master swicth */ - } /* end for loop */ - ANETreadConsume(handle,length); - return 1; -} -/*----------------------------------------------------------------------------------*/ -static int TelnetAcceptCB(int handle, void *userData){ - SConnection *pCon = NULL; - pCommandCBData usData = NULL; - pTelTask pTel = NULL; - - pCon = SCreateConnection(pServ->pSics, handle, 3); - usData = malloc(sizeof(CommandCBData)); - if(pCon == NULL || usData == NULL){ - SICSLogWrite("Failure to allocate new Connection",eInternal); - return 0; - } - usData->command = CreateDynString(256,256); - if(usData->command == NULL){ - SICSLogWrite("Failure to allocate new Connection",eInternal); - return 0; - } - usData->pCon = pCon; - usData->state = tData; - /* Create a task object for the telnet connection */ - pTel = CreateTelnet(pCon); - if(!pTel){ - SICSLogWrite("Failure to allocate new Telnet Task Object", - eInternal); - SCDeleteConnection(pCon); - return 0; - } - /* register connection and task */ - pCon->iTelnet = 1; - TaskRegister(pServ->pTasker, - TelnetTask, - TelnetSignal, - DeleteTelnet, - pTel, - 1); - ANETsetReadCallback(handle, ANETTelnetProcess, - usData, killCommandCBData); - SCSendOK(pCon); - return 1; -} -/*------------------------------------------------------------------------------------*/ -static void NREADlog(int level, char *txt, void *userData){ - puts(txt); -} -/*------------------------------------------------------------------------------------*/ -int NetReadInstallANETPort(pNetRead self, eNRType eType, int iPort){ - ANETsetLog(NREADlog,NULL); - switch(eType){ - case naccept: - return ANETopenServerPort(iPort,CommandAcceptCB,NULL); - break; - case taccept: - return ANETopenServerPort(iPort,TelnetAcceptCB,NULL); - break; } return 0; } +/*-------------------------------------------------------------------------*/ +int NetReaderTask(void *pData) +{ + pNetRead self = NULL; + fd_set lMask; + struct timeval tmo = { 0, 1 }; + int iRet, iStatus; + int iCount; + NetItem NItem; + int conCount = 0; + char num[50]; + IPair *options = NULL; + + self = (pNetRead) pData; + assert(self); + if (self->lMagic != NRMAGIC) { + return 0; + } + + /* check for end */ + if (self->iEnd) { + return 0; + } + + ANETprocess(); + + /* build the select mask */ + FD_ZERO(&lMask); + iRet = LLDnodePtr2First(self->iList); + iCount = 0; + DynStringClear(self->conList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &NItem); + if (!VerifyChannel(NItem.pSock)) { + break; + } + + sprintf(num, "%d, type %d:", NItem.pSock->sockid, NItem.eType); + if (conCount < 100) { + DynStringConcat(self->conList, num); + } + FD_SET(NItem.pSock->sockid, &lMask); + if (NItem.pSock->sockid > iCount) { + iCount = NItem.pSock->sockid; + } + conCount++; + if (conCount > 100) { + WriteToCommandLog("WAYTOMANYCONNECTIONS> ", + GetCharArray(self->conList)); + } + iRet = LLDnodePtr2Next(self->iList); + } + + if (conCount > 100) { + WriteToCommandLog("WAYTOMANYCONNECTIONS> ", + GetCharArray(self->conList)); + } + + snprintf(num, sizeof num, "%d", conCount); + IFSetOption(pSICSOptions, "ConnectionCount", num); + IFSetOption(pSICSOptions, "ConMask", GetCharArray(self->conList)); + + + /* the select itself */ + tmo.tv_usec = self->iReadTimeout; + iCount++; + iRet = uselect(iCount, &lMask, NULL, NULL, &tmo); + if (iRet <= 0) { /* no pending request */ + return 1; + } + + + /* now go through all registered things and handle the message */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &NItem); + if (FD_ISSET(NItem.pSock->sockid, &lMask)) { /* data */ + switch (NItem.eType) { + /* lists have been changed after accept, return */ + case naccept: + NetReadAccept(self, NItem.pSock); + return 1; + break; + case taccept: + TelnetAccept(self, NItem.pSock); + return 1; + break; + case command: + iStatus = NetReadRead(self, &NItem); + if (iStatus == 0) { /* there was an eof */ + /* do not continue, list is messy */ + return 1; + } + break; + case tcommand: + iStatus = TelnetRead(self, &NItem); + if (iStatus == 0) { /* there was an eof */ + /* do not continue, list is messy */ + return 1; + } + break; + case udp: + NetReadUDP(self, &NItem); + break; + case user: + NItem.iReadable = 1; + LLDnodeDataFrom(self->iList, &NItem); + break; + } + LLDnodeDataFrom(self->iList, &NItem); + } + iRet = LLDnodePtr2Next(self->iList); + } + + /* done, finally */ + return 1; +} + +/*--------------------------------------------------------------------------*/ +void NetReaderSignal(void *pUser, int iSignal, void *pEventData) +{ + pNetRead self = NULL; + int *iInt; + + self = (pNetRead) pUser; + assert(self); + iInt = (int *) pEventData; + + if (iSignal == SICSINT) { + iInt = (int *) pEventData; + if (*iInt == eEndServer) { + self->iEnd = 1; + } + } +} + +/*--------------------------------------------------------------------------*/ +typedef struct { + pNetRead pRead; + mkChannel *pChan; + int iEnd; +} ReadWait, *pReadWait; +/*--------------------------------------------------------------------------*/ +static void ReadWaitFree(void *pData) +{ + pReadWait pWait = NULL; + + pWait = (pReadWait) pData; + if (!pWait) { + return; + } + + if (pWait->pChan) { + free(pWait->pChan); + } + free(pWait); +} + +/*--------------------------------------------------------------------------*/ +static void ReadWaitSignal(void *pUser, int iSignal, void *pSigData) +{ + pReadWait pWait = NULL; + int *iInt; + + pWait = (pReadWait) pUser; + assert(pWait); + + if (iSignal == SICSINT) { + iInt = (int *) pSigData; + if (*iInt != eContinue) { + pWait->iEnd = 1; + } + } +} + +/*---------------------------------------------------------------------------*/ +static int Wait4ReadTask(void *pData) +{ + pReadWait pWait = NULL; + NetItem sItem; + int iRet; + + pWait = (pReadWait) pData; + assert(pWait); + + if (pWait->iEnd) { + return 0; /* an interrupt occurred */ + } + + iRet = LLDnodePtr2First(pWait->pRead->iList); + while (iRet != 0) { + LLDnodeDataTo(pWait->pRead->iList, &sItem); + if (sItem.pSock == pWait->pChan) { + if (sItem.iReadable) { + NetReadRemove(pWait->pRead, pWait->pChan); + return 0; + } + } + iRet = LLDnodePtr2Next(pWait->pRead->iList); + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +int NetReadWait4Data(pNetRead self, int iSocket) +{ + pReadWait pNew = NULL; + mkChannel *pChan = NULL; + long lID; + int iRet; + + /* make a new ReadWait */ + pNew = (pReadWait) malloc(sizeof(ReadWait)); + if (!pNew) { + return 0; + } + + /* make a new channel */ + pChan = (mkChannel *) malloc(sizeof(mkChannel)); + if (!pChan) { + free(pNew); + return 0; + } + pChan->sockid = iSocket; + pChan->lMagic = NETMAGIC; + + /* put it into the NetReader */ + iRet = NetReadRegister(self, pChan, user, NULL); + if (!iRet) { + return 0; + } + + /* start the wait task */ + pNew->pChan = pChan; + pNew->iEnd = 0; + pNew->pRead = self; + lID = TaskRegister(self->pMain->pTasker, + Wait4ReadTask, ReadWaitSignal, ReadWaitFree, pNew, 0); + + /* wait for finish */ + TaskWait(self->pMain->pTasker, lID); + + return 1; +} + +/*--------------------------------------------------------------------------*/ +int NetReadRegisterUserSocket(pNetRead self, int iSocket) +{ + mkChannel *pChan = NULL; + int iRet; + + + /* make a new channel */ + pChan = (mkChannel *) malloc(sizeof(mkChannel)); + if (!pChan) { + return 0; + } + pChan->sockid = iSocket; + pChan->lMagic = NETMAGIC; + + /* put it into the NetReader */ + iRet = NetReadRegister(self, pChan, user, NULL); + if (!iRet) { + return 0; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int NetReadRemoveUserSocket(pNetRead self, int iSocket) +{ + NetItem sItem; + int iRet; + + assert(self); + if (self->lMagic != NRMAGIC) { + return 0; + } + + /* find the entry to remove */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sItem); + if (sItem.eType == user) { + if (sItem.pSock->sockid == iSocket) { + free(sItem.pSock); + LLDnodeDelete(self->iList); + return 1; + } + } + iRet = LLDnodePtr2Next(self->iList); + } + return 0; +} + +/*--------------------------------------------------------------------------*/ +int NetReadReadable(pNetRead self, int iSocket) +{ + NetItem sItem; + int iRet; + + assert(self); + + /* find the entry to read */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sItem); + if (sItem.eType == user) { + if (sItem.pSock->sockid == iSocket) { + if (sItem.iReadable) { + return 1; + } else { + return 0; + } + } + } + iRet = LLDnodePtr2Next(self->iList); + } + return 0; +} + +/*--------------------------------------------------------------------------*/ +int NetReadResetUser(pNetRead self, int iSocket) +{ + NetItem sItem; + int iRet; + + assert(self); + + /* find the entry to remove */ + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sItem); + if (sItem.eType == user) { + if (sItem.pSock->sockid == iSocket) { + sItem.iReadable = 0; + LLDnodeDataFrom(self->iList, &sItem); + return 1; + } + } + iRet = LLDnodePtr2Next(self->iList); + } + return 0; +} + +/*=================================================================================== + * new code to support the ANET network stuff + * =================================================================================*/ +typedef struct { + pDynString command; + int state; + SConnection *pCon; +} CommandCBData, *pCommandCBData; +/*----------------------------------------------------------------------------------*/ +static void killCommandCBData(void *data) +{ + pCommandCBData self = (pCommandCBData) data; + if (self == NULL) { + return; + } + if (self->command != NULL) { + DeleteDynString(self->command); + } + free(self); +} + +/*----------------------------------------------------------------------------------*/ +static int testAndInvokeInterrupt(pCommandCBData self, int handle) +{ + char *pPtr; + char buffer[512]; + int iInt; + + pPtr = GetCharArray(self->command); + if (strstr(pPtr, "INT1712") != NULL) { + sscanf(pPtr, "%s %d", buffer, &iInt); + if (SCMatchRights(self->pCon, usUser)) { + TaskSignal(pServ->pTasker, SICSINT, &iInt); + snprintf(buffer, 512, "INTERRUPT %d issued on sock %d", + iInt, handle); + WriteToCommandLog("SYS>", buffer); + if (iInt == eEndServer) { + TaskStop(pServ->pTasker); + } + } else { + SCWrite(self->pCon, + "ERROR: insufficient privilege to invoke Interrupt", eError); + } + return 1; + } + return 0; +} + +/*----------------------------------------------------------------------------------*/ +static int CommandDataCB(int handle, void *userData) +{ + pCommandCBData self = (pCommandCBData) userData; + int i, length, status; + char *pPtr = NULL; + + assert(self != NULL); + pPtr = ANETreadPtr(handle, &length); + if (pPtr == NULL) { + return 1; + } + for (i = 0; i < length; i++) { + switch (self->state) { + case COLLECT: + if (pPtr[i] == '\r' || pPtr[i] == '\n') { + self->state = SKIPTERM; + if (!testAndInvokeInterrupt(self, handle)) { + status = + CostaTop(self->pCon->pStack, GetCharArray(self->command)); + if (!status) { + SCWrite(self->pCon, "ERROR: Busy", eError); + } + } + DynStringClear(self->command); + } else { + if (pPtr[i] != '\0') { + DynStringConcatChar(self->command, pPtr[i]); + } + } + break; + case SKIPTERM: + if (pPtr[i] != '\r' && pPtr[i] != '\n' && pPtr[i] != '\0') { + DynStringConcatChar(self->command, pPtr[i]); + self->state = COLLECT; + } + break; + } + } + ANETreadConsume(handle, length); + return 1; +} + +/*----------------------------------------------------------------------------------*/ +static int CommandAcceptCB(int handle, void *userData) +{ + SConnection *pCon = NULL; + pCommandCBData usData = NULL; + + pCon = SCreateConnection(pServ->pSics, handle, 3); + usData = malloc(sizeof(CommandCBData)); + if (pCon == NULL || usData == NULL) { + SICSLogWrite("Failure to allocate new Connection", eInternal); + return 0; + } + usData->command = CreateDynString(256, 256); + if (usData->command == NULL) { + SICSLogWrite("Failure to allocate new Connection", eInternal); + return 0; + } + usData->pCon = pCon; + usData->state = COLLECT; + TaskRegister(pServ->pTasker, + SCTaskFunction, + SCSignalFunction, SCDeleteConnection, pCon, 1); + ANETsetReadCallback(handle, CommandDataCB, usData, killCommandCBData); + SCSendOK(pCon); + return 1; +} + +/*-----------------------------------------------------------------------*/ +static int ANETTelnetReply(int sockHandle, char code, char cChar) +{ + char pReply[3]; + + pReply[0] = IAC; + pReply[1] = code; + pReply[2] = cChar; + + ANETwrite(sockHandle, pReply, 3); + return 1; +} + +/*-----------------------------------------------------------------------*/ +static int ANETTelnetProcess(int handle, void *usData) +{ + pCommandCBData self = NULL; + int length, status, i; + int cChar; + char *pPtr = NULL; + char pError[256]; + + self = (pCommandCBData) usData; + assert(self != NULL); + + pPtr = ANETreadPtr(handle, &length); + + /* do telnet analysis of the data buffer */ + for (i = 0; i < length; i++) { + cChar = (int) pPtr[i]; +#ifdef TELNETDEBUG + if ((cChar > 48) && (cChar < 128)) { + printf("char: %c\n", cChar); + } else { + printf("Control: %d\n", cChar); + } +#endif + /* Telnet status switching */ + switch (self->state) { + case tData: + switch (cChar) { + case IAC: + self->state = tIAC; + break; + case '\r': + case '\n': + if (!testAndInvokeInterrupt(self, handle)) { + status = + CostaTop(self->pCon->pStack, GetCharArray(self->command)); + if (!status) { + SCWrite(self->pCon, "ERROR: Busy", eError); + } + } + self->state = tCR; + DynStringClear(self->command); + break; + case (char) 8: /* backspace */ + DynStringBackspace(self->command); + break; + case (char) 0: /* ignore 0 character sent as end of text */ + break; + default: + DynStringConcatChar(self->command, (char) cChar); + break; + + } /* end of tData case */ + break; + case tCR: + if (cChar == '\r' || cChar == '\n' || cChar == '\0') { + continue; + } else { + self->state = tData; + DynStringConcatChar(self->command, (char) cChar); + } + break; + case tIAC: + switch (cChar) { + case IAC: + self->state = tData; + break; + case WILL: + self->state = tWill; + break; + case WONT: + self->state = tWont; + break; + case DONT: + self->state = tDont; + break; + case DO: + self->state = tDo; + break; + case EOR: + self->state = tData; + break; + case SB: + self->state = tSB; + break; + case EC: + DynStringBackspace(self->command); + self->state = tData; + break; + case EL: + DynStringClear(self->command); + self->state = tData; + break; + case IP: + SCSetInterrupt(self->pCon, eAbortBatch); + self->state = tData; + break; + default: + self->state = tData; + break; + } /* end of tIAC */ + break; + case tWill: /* we do not do options! */ + ANETTelnetReply(handle, DONT, cChar); + self->state = tData; + break; + case tWont: /* we do not do options! A Wont is sent by the client + if it cannot do a option we requested it to have. As + we do not try to force options, this should not happen + */ + self->state = tData; + break; + case tDo: /* we do not do options! */ + ANETTelnetReply(handle, WONT, cChar); + self->state = tData; + break; + case tDont: /* we do not do options! A Dont is sent by the client + if it cannot do a option we requested it to have. As + we do not try to force options, this should not happen + */ + self->state = tData; + break; + case tSB: /* as we do not have options, we cannot have suboption + negotaitions. Something is seriously wrong when + we are here. It is a protocoll error. However, we + ignore it silently. tSB marks the start of the + subnegotiation. The current character must be the + option code we are dealing with. + */ + self->state = tSE; + break; + case tSE: + /* now we are in the suboption parameter. Normally data + should be copied to a suboption string buffer here + until SE. + */ + switch (cChar) { + case IAC: + break; + case SE: + self->state = tData; + /* suboption interpretation would go here */ + break; + default: + /* copy data to suboption buffer */ + break; + } + break; + + default: + /* There is something wrong here! */ + sprintf(pError, "ERROR: bad telnet code %d", cChar); + SICSLogWrite(pError, eInternal); + self->state = tData; + break; + + } /* end master swicth */ + } /* end for loop */ + ANETreadConsume(handle, length); + return 1; +} + +/*----------------------------------------------------------------------------------*/ +static int TelnetAcceptCB(int handle, void *userData) +{ + SConnection *pCon = NULL; + pCommandCBData usData = NULL; + pTelTask pTel = NULL; + + pCon = SCreateConnection(pServ->pSics, handle, 3); + usData = malloc(sizeof(CommandCBData)); + if (pCon == NULL || usData == NULL) { + SICSLogWrite("Failure to allocate new Connection", eInternal); + return 0; + } + usData->command = CreateDynString(256, 256); + if (usData->command == NULL) { + SICSLogWrite("Failure to allocate new Connection", eInternal); + return 0; + } + usData->pCon = pCon; + usData->state = tData; + /* Create a task object for the telnet connection */ + pTel = CreateTelnet(pCon); + if (!pTel) { + SICSLogWrite("Failure to allocate new Telnet Task Object", eInternal); + SCDeleteConnection(pCon); + return 0; + } + /* register connection and task */ + pCon->iTelnet = 1; + TaskRegister(pServ->pTasker, + TelnetTask, TelnetSignal, DeleteTelnet, pTel, 1); + ANETsetReadCallback(handle, ANETTelnetProcess, + usData, killCommandCBData); + SCSendOK(pCon); + return 1; +} + +/*------------------------------------------------------------------------------------*/ +static void NREADlog(int level, char *txt, void *userData) +{ + puts(txt); +} + +/*------------------------------------------------------------------------------------*/ +int NetReadInstallANETPort(pNetRead self, eNRType eType, int iPort) +{ + ANETsetLog(NREADlog, NULL); + switch (eType) { + case naccept: + return ANETopenServerPort(iPort, CommandAcceptCB, NULL); + break; + case taccept: + return ANETopenServerPort(iPort, TelnetAcceptCB, NULL); + break; + } + return 0; +} diff --git a/nread.h b/nread.h index 084d178c..15436177 100644 --- a/nread.h +++ b/nread.h @@ -14,25 +14,25 @@ #define SICSNETREADER /*--------------------------------------------------------------------------*/ - typedef struct __netreader *pNetRead; - typedef enum {naccept, command, udp, user, taccept, tcommand} eNRType; +typedef struct __netreader *pNetRead; +typedef enum { naccept, command, udp, user, taccept, tcommand } eNRType; /*--------------------------------------------------------------------------*/ - pNetRead CreateNetReader(pServer pServ, int iPasswdTimeout, - int iReadTimeout); - void DeleteNetReader(void *pData); +pNetRead CreateNetReader(pServer pServ, int iPasswdTimeout, + int iReadTimeout); +void DeleteNetReader(void *pData); /*--------------------------------------------------------------------------*/ - int NetReadRegister(pNetRead self, mkChannel *pSock, eNRType eType, - SConnection *pCon); - int NetReadRegisterUserSocket(pNetRead self, int iSocket); - int NetReadRemove(pNetRead self, mkChannel *pSock); - int NetReadRemoveUserSocket(pNetRead self, int iSocket); +int NetReadRegister(pNetRead self, mkChannel * pSock, eNRType eType, + SConnection * pCon); +int NetReadRegisterUserSocket(pNetRead self, int iSocket); +int NetReadRemove(pNetRead self, mkChannel * pSock); +int NetReadRemoveUserSocket(pNetRead self, int iSocket); /*-------------------------------------------------------------------------*/ - int NetReaderTask(void *pReader); - void NetReaderSignal(void *pUser, int iSignal, void *pSigData); - int NetReadWait4Data(pNetRead self, int iSocket); - int NetReadReadable(pNetRead self, int iSocket); - int NetReadResetUser(pNetRead self, int iSocket); +int NetReaderTask(void *pReader); +void NetReaderSignal(void *pUser, int iSignal, void *pSigData); +int NetReadWait4Data(pNetRead self, int iSocket); +int NetReadReadable(pNetRead self, int iSocket); +int NetReadResetUser(pNetRead self, int iSocket); /*--------------------------------------------------------------------------*/ - int NetReadInstallANETPort(pNetRead self, eNRType eType, int iPort); +int NetReadInstallANETPort(pNetRead self, eNRType eType, int iPort); #endif diff --git a/nserver.c b/nserver.c index de87b13a..b9192fba 100644 --- a/nserver.c +++ b/nserver.c @@ -28,7 +28,7 @@ #include "devexec.h" #include "passwd.h" #include "lld.h" -#include "macro.h" +#include "macro.h" #include "perfmon.h" #include "nread.h" #include "ofac.h" @@ -38,538 +38,493 @@ #include "nserver.h" #include "sicshipadaba.h" - int ServerSetupInterrupt(int iPort, pNetRead pNet, pTaskMan pTasker); +int ServerSetupInterrupt(int iPort, pNetRead pNet, pTaskMan pTasker); /* configures a port for listening for interrupts - */ + */ - extern void StopExit(void); /* in SICSmain.c */ - - extern int openDevexecLog(); /* in devexec.c */ - - extern void NetWatchInit(void); /* in nwatch.c */ +extern void StopExit(void); /* in SICSmain.c */ + +extern int openDevexecLog(); /* in devexec.c */ + +extern void NetWatchInit(void); /* in nwatch.c */ /* ========================= Less dreadful file statics =================== */ #define DEFAULTINIFILE "servo.tcl" #define DEFAULTSTATUSFILE "sicsstat.tcl" - - static int iFortifyScope; - + +static int iFortifyScope; + #include "obdes.h" -#include "interface.h" +#include "interface.h" #include "sicsvar.h" #include "emon.h" /*----------------------------------------------------------------------*/ - pEnvMon GetEnvMon(SicsInterp *pSics) - { - CommandList *pCom; - - assert(pSics); - - pCom = FindCommand(pSics,"emon"); - assert(pCom); - assert(pCom->pData); - return (pEnvMon)pCom->pData; - } +pEnvMon GetEnvMon(SicsInterp * pSics) +{ + CommandList *pCom; + + assert(pSics); + + pCom = FindCommand(pSics, "emon"); + assert(pCom); + assert(pCom->pData); + return (pEnvMon) pCom->pData; +} + /*-------------------------------------------------------------------------*/ - int InitServer(char *file, pServer *pServ) - { - char *pText = NULL; - int iPort, iRet; - FILE *fp; - pSicsVariable pVar; - char pBueffel[512]; - SConnection *pCon = NULL; - pServer self = NULL; - char *pPtr; - int iCommandTimeOut, iPasswordTimeOut, i; - pNetRead pReader = NULL; - pPerfMon pMon = NULL; - CommandList *pCom; - pid_t myPid; +int InitServer(char *file, pServer * pServ) +{ + char *pText = NULL; + int iPort, iRet; + FILE *fp; + pSicsVariable pVar; + char pBueffel[512]; + SConnection *pCon = NULL; + pServer self = NULL; + char *pPtr; + int iCommandTimeOut, iPasswordTimeOut, i; + pNetRead pReader = NULL; + pPerfMon pMon = NULL; + CommandList *pCom; + pid_t myPid; - /* allocate a new server structure */ - self = (pServer)malloc(sizeof(SicsServer)); - if(!self) - { - puts("DEADLY ERROR: Cannot allocate server data structure!"); - return 0; - } - memset(self,0,sizeof(SicsServer)); - *pServ = self; + /* allocate a new server structure */ + self = (pServer) malloc(sizeof(SicsServer)); + if (!self) { + puts("DEADLY ERROR: Cannot allocate server data structure!"); + return 0; + } + memset(self, 0, sizeof(SicsServer)); + *pServ = self; - /* define any signal handlers */ - signal(SIGPIPE,SIG_IGN); + /* define any signal handlers */ + signal(SIGPIPE, SIG_IGN); - /* configure fortify */ - iFortifyScope = Fortify_EnterScope(); - Fortify_CheckAllMemory(); - - /* interpreter */ - self->pSics = InitInterp(); - assert(self->pSics); + /* configure fortify */ + iFortifyScope = Fortify_EnterScope(); + Fortify_CheckAllMemory(); - /* initialise tasker */ - assert(TaskerInit(&self->pTasker)); - - pSICSOptions = IFAddOption(pSICSOptions, "ConnectionCount","0"); - pSICSOptions = IFAddOption(pSICSOptions, "ConMask","0"); - - /* initialize the network watcher */ - NetWatchInit(); - - /* initialise the server from script */ - if(file == NULL) - { - iRet = InitObjectCommands(self,DEFAULTINIFILE); - } - else - { - iRet = InitObjectCommands(self,file); - } - if(!iRet) - { - if(file) - { - printf("Error on initialization file --> %s <-- \n",file); - } - else - { - printf("Error on initialization file --> %s <-- \n",DEFAULTINIFILE); - } - return 0; - } - self->dummyCon = SCCreateDummyConnection(self->pSics); - - /* - check for option RedirectFile and redirect stout/sterr to it - if present. - */ - pPtr = NULL; - pPtr = IFindOption(pSICSOptions,"RedirectFile"); - if(pPtr != NULL) - { - myPid = getpid(); - sprintf(pBueffel,"%s%5.5d.log",pPtr,(int)myPid); - fp = freopen(pBueffel,"w",stdout); - if(!fp) - { - printf("Failed to redirect stdout/stderr to %s\n",pBueffel); - } - fp = freopen(pBueffel,"w",stderr); - if(!fp) - { - printf("Failed to redirect stdout/stderr to %s\n",pBueffel); - } - } + /* interpreter */ + self->pSics = InitInterp(); + assert(self->pSics); - - /* initialise net reader */ - pPtr = NULL; - pPtr = IFindOption(pSICSOptions,"ReadTimeOut"); - if(pPtr != NULL) - { - i = atoi(pPtr); - iCommandTimeOut = i; + /* initialise tasker */ + assert(TaskerInit(&self->pTasker)); + + pSICSOptions = IFAddOption(pSICSOptions, "ConnectionCount", "0"); + pSICSOptions = IFAddOption(pSICSOptions, "ConMask", "0"); + + /* initialize the network watcher */ + NetWatchInit(); + + /* initialise the server from script */ + if (file == NULL) { + iRet = InitObjectCommands(self, DEFAULTINIFILE); + } else { + iRet = InitObjectCommands(self, file); + } + if (!iRet) { + if (file) { + printf("Error on initialization file --> %s <-- \n", file); + } else { + printf("Error on initialization file --> %s <-- \n", DEFAULTINIFILE); } - else - { - iCommandTimeOut = 100; /* this is in microseconds and anyway o.k. */ + return 0; + } + self->dummyCon = SCCreateDummyConnection(self->pSics); + + /* + check for option RedirectFile and redirect stout/sterr to it + if present. + */ + pPtr = NULL; + pPtr = IFindOption(pSICSOptions, "RedirectFile"); + if (pPtr != NULL) { + myPid = getpid(); + sprintf(pBueffel, "%s%5.5d.log", pPtr, (int) myPid); + fp = freopen(pBueffel, "w", stdout); + if (!fp) { + printf("Failed to redirect stdout/stderr to %s\n", pBueffel); } - pPtr = NULL; - pPtr = IFindOption(pSICSOptions,"ReadUserPasswdTimeout"); - if(pPtr != NULL) - { - i = atoi(pPtr); - iPasswordTimeOut = i; + fp = freopen(pBueffel, "w", stderr); + if (!fp) { + printf("Failed to redirect stdout/stderr to %s\n", pBueffel); } - else - { - iPasswordTimeOut = 1; /* never used, but checked ! */ - } - assert((pReader = CreateNetReader(self,iPasswordTimeOut,iCommandTimeOut)) != NULL); - TaskRegister(self->pTasker, - NetReaderTask, - NetReaderSignal, - NULL, /* call DeleteNetReader later than TaskerDelete */ - pReader,1); - self->pReader = pReader; - - /* the socket */ - pText = IFindOption(pSICSOptions,"ServerPort"); - if(!pText) - { - printf("Cannot find ServerPort number in options file %s\n", - "This value is required!"); - DeleteInterp(self->pSics); - IFDeleteOptions(pSICSOptions); - return 0; - } - iRet = sscanf(pText,"%d",&iPort); - if( (iRet != 1) || (iPort < 1024) ) - { - printf("Invalid port number specified in Server initialisation file\n"); - DeleteInterp(self->pSics); - IFDeleteOptions(pSICSOptions); - return 0; - } - /* + } + + + /* initialise net reader */ + pPtr = NULL; + pPtr = IFindOption(pSICSOptions, "ReadTimeOut"); + if (pPtr != NULL) { + i = atoi(pPtr); + iCommandTimeOut = i; + } else { + iCommandTimeOut = 100; /* this is in microseconds and anyway o.k. */ + } + pPtr = NULL; + pPtr = IFindOption(pSICSOptions, "ReadUserPasswdTimeout"); + if (pPtr != NULL) { + i = atoi(pPtr); + iPasswordTimeOut = i; + } else { + iPasswordTimeOut = 1; /* never used, but checked ! */ + } + assert((pReader = + CreateNetReader(self, iPasswordTimeOut, + iCommandTimeOut)) != NULL); + TaskRegister(self->pTasker, NetReaderTask, NetReaderSignal, NULL, /* call DeleteNetReader later than TaskerDelete */ + pReader, 1); + self->pReader = pReader; + + /* the socket */ + pText = IFindOption(pSICSOptions, "ServerPort"); + if (!pText) { + printf("Cannot find ServerPort number in options file %s\n", + "This value is required!"); + DeleteInterp(self->pSics); + IFDeleteOptions(pSICSOptions); + return 0; + } + iRet = sscanf(pText, "%d", &iPort); + if ((iRet != 1) || (iPort < 1024)) { + printf + ("Invalid port number specified in Server initialisation file\n"); + DeleteInterp(self->pSics); + IFDeleteOptions(pSICSOptions); + return 0; + } + /* self->pServerPort = NETOpenPort(iPort); if(!self->pServerPort) { - printf("Cannot open Server Socket\n"); - DeleteInterp(self->pSics); - IFDeleteOptions(pSICSOptions); - return 0; + printf("Cannot open Server Socket\n"); + DeleteInterp(self->pSics); + IFDeleteOptions(pSICSOptions); + return 0; } NetReadRegister(pReader, self->pServerPort, naccept, NULL); - */ - NetReadInstallANETPort(pReader,naccept, iPort); + */ + NetReadInstallANETPort(pReader, naccept, iPort); - /* the device executor */ - openDevexecLog(); - DevexecLog("START","SICS"); + /* the device executor */ + openDevexecLog(); + DevexecLog("START", "SICS"); - - /* initialize Interrupt Port */ - pText = IFindOption(pSICSOptions,"InterruptPort"); - if(!pText) - { - printf("Cannot find InterruptPort number in options file %s\n", - "This value is required!"); - DeleteInterp(self->pSics); - IFDeleteOptions(pSICSOptions); - return 0; - } - iRet = sscanf(pText,"%d",&iPort); - if( (iRet != 1) || (iPort < 1024) ) - { - printf("Invalid port number specified in Server initialisation file\n"); - DeleteInterp(self->pSics); - IFDeleteOptions(pSICSOptions); - return 0; - } - iRet = ServerSetupInterrupt(iPort,pReader,self->pTasker); - if(!iRet) - { - SCWrite(pCon,"WARNING: UDP interrupt port not initialized",eWarning); - } - /* install a secret fully priviledged entry point for ME */ - AddUser("Achterbahn","Kiel",usInternal); - /* install environment monitor */ - self->pMonitor = GetEnvMon(self->pSics); - TaskRegister(self->pTasker, - EnvMonTask, - EnvMonSignal, - NULL, - self->pMonitor,1); - - /* install performance monitor */ - pMon = CreatePerfMon(20); - AddCommand(self->pSics,"Performance",PerfMonWrapper,DeletePerfMon,pMon); - TaskRegister(self->pTasker, - PerfMonTask, - PerfMonSignal, - NULL, - pMon,1); - - /* install telnet port */ - InstallTelnet(); - - /* If the restore file has not been loaded, do so now */ - if(!hasRestored()) - { - strcpy(pBueffel,"restore"); - SCInvoke(self->dummyCon,self->pSics,pBueffel); - } - - /* exit handlers need to be installed here */ - atexit(StopExit); - Fortify_CheckAllMemory(); - return 1; - + /* initialize Interrupt Port */ + pText = IFindOption(pSICSOptions, "InterruptPort"); + if (!pText) { + printf("Cannot find InterruptPort number in options file %s\n", + "This value is required!"); + DeleteInterp(self->pSics); + IFDeleteOptions(pSICSOptions); + return 0; } + iRet = sscanf(pText, "%d", &iPort); + if ((iRet != 1) || (iPort < 1024)) { + printf + ("Invalid port number specified in Server initialisation file\n"); + DeleteInterp(self->pSics); + IFDeleteOptions(pSICSOptions); + return 0; + } + iRet = ServerSetupInterrupt(iPort, pReader, self->pTasker); + if (!iRet) { + SCWrite(pCon, "WARNING: UDP interrupt port not initialized", eWarning); + } + /* install a secret fully priviledged entry point for ME */ + AddUser("Achterbahn", "Kiel", usInternal); + + /* install environment monitor */ + self->pMonitor = GetEnvMon(self->pSics); + TaskRegister(self->pTasker, + EnvMonTask, EnvMonSignal, NULL, self->pMonitor, 1); + + /* install performance monitor */ + pMon = CreatePerfMon(20); + AddCommand(self->pSics, "Performance", PerfMonWrapper, DeletePerfMon, + pMon); + TaskRegister(self->pTasker, PerfMonTask, PerfMonSignal, NULL, pMon, 1); + + /* install telnet port */ + InstallTelnet(); + + /* If the restore file has not been loaded, do so now */ + if (!hasRestored()) { + strcpy(pBueffel, "restore"); + SCInvoke(self->dummyCon, self->pSics, pBueffel); + } + + /* exit handlers need to be installed here */ + atexit(StopExit); + Fortify_CheckAllMemory(); + return 1; + +} + /*---------------------------------------------------------------------------*/ - void StopServer(pServer self) - { - SConnection *pCurrent, *pTemp; - char pBueffel[512]; - char *pText = NULL; - SConnection *pCon = NULL; - pSite site = NULL; +void StopServer(pServer self) +{ + SConnection *pCurrent, *pTemp; + char pBueffel[512]; + char *pText = NULL; + SConnection *pCon = NULL; + pSite site = NULL; - /* clear all pending bullshit */ - ClearExecutor(self->pExecutor); - DevexecLog("STOP","SICS"); + /* clear all pending bullshit */ + ClearExecutor(self->pExecutor); + DevexecLog("STOP", "SICS"); - /* shut telnet down */ - KillTelnet(); + /* shut telnet down */ + KillTelnet(); - /* shut tasker down */ - TaskerDelete(&self->pTasker); - self->pTasker = NULL; + /* shut tasker down */ + TaskerDelete(&self->pTasker); + self->pTasker = NULL; - /* save status */ - if(!self->simMode) - { - strcpy(pBueffel,"Backup "); - pText = IFindOption(pSICSOptions,"statusfile"); - if(pText) - { - strcat(pBueffel,pText); - } - else - { - strcat(pBueffel,DEFAULTSTATUSFILE); - } - if(self->dummyCon) - { - InterpExecute(self->pSics,self->dummyCon,pBueffel); - SCDeleteConnection(self->dummyCon); - } - else - { - printf("ERROR: Cannot allocate dummy connection, status NOT saved"); - } + /* save status */ + if (!self->simMode) { + strcpy(pBueffel, "Backup "); + pText = IFindOption(pSICSOptions, "statusfile"); + if (pText) { + strcat(pBueffel, pText); + } else { + strcat(pBueffel, DEFAULTSTATUSFILE); } - - /* close redirection file if present */ - pText = NULL; - pText = IFindOption(pSICSOptions,"RedirectFile"); - if(pText) - { - fclose(stderr); + if (self->dummyCon) { + InterpExecute(self->pSics, self->dummyCon, pBueffel); + SCDeleteConnection(self->dummyCon); + } else { + printf("ERROR: Cannot allocate dummy connection, status NOT saved"); } - - /* clean out */ - if(self->pSics) - { - DeleteInterp(self->pSics); - self->pSics = NULL; - } - /* remove options after interpreter as some object kill functions - may use options */ - if(pSICSOptions) - IFDeleteOptions(pSICSOptions); - - /* delete net reader */ - DeleteNetReader(self->pReader); - self->pReader = NULL; - - /* close the server port */ - if(self->pServerPort) - { - NETClosePort(self->pServerPort); - free(self->pServerPort); - } - - - /* remove the in memory password database */ - KillPasswd(); - - - /* close Interrupt system */ - ServerStopInterrupt(); - - /* Remove Status Callback */ - KillStatus(NULL); - - /* - kill the site data structure - */ - site = getSite(); - if(site != NULL) - { - site->KillSite(site); - } - - /* - kill overloaded interfaces data - */ - killTclDrivable(); - - KillFreeConnections(); - - killSICSHipadaba(); - - /* close the List system */ - LLDsystemClose(); - - /* make fortify print his findings */ - Fortify_DumpAllMemory(iFortifyScope); - Fortify_LeaveScope(); - - free(self); - } -/*------------------------------------------------------------------------*/ - void RunServer(pServer self) - { - TaskSchedule(self->pTasker); + + /* close redirection file if present */ + pText = NULL; + pText = IFindOption(pSICSOptions, "RedirectFile"); + if (pText) { + fclose(stderr); } + + /* clean out */ + if (self->pSics) { + DeleteInterp(self->pSics); + self->pSics = NULL; + } + /* remove options after interpreter as some object kill functions + may use options */ + if (pSICSOptions) + IFDeleteOptions(pSICSOptions); + + /* delete net reader */ + DeleteNetReader(self->pReader); + self->pReader = NULL; + + /* close the server port */ + if (self->pServerPort) { + NETClosePort(self->pServerPort); + free(self->pServerPort); + } + + + /* remove the in memory password database */ + KillPasswd(); + + + /* close Interrupt system */ + ServerStopInterrupt(); + + /* Remove Status Callback */ + KillStatus(NULL); + + /* + kill the site data structure + */ + site = getSite(); + if (site != NULL) { + site->KillSite(site); + } + + /* + kill overloaded interfaces data + */ + killTclDrivable(); + + KillFreeConnections(); + + killSICSHipadaba(); + + /* close the List system */ + LLDsystemClose(); + + /* make fortify print his findings */ + Fortify_DumpAllMemory(iFortifyScope); + Fortify_LeaveScope(); + + free(self); + +} + /*------------------------------------------------------------------------*/ - typedef struct { - time_t tFinish; - int iEnd; - } WaitStruct, *pWaitStruct; +void RunServer(pServer self) +{ + TaskSchedule(self->pTasker); +} + +/*------------------------------------------------------------------------*/ +typedef struct { + time_t tFinish; + int iEnd; +} WaitStruct, *pWaitStruct; /*-------------------------------------------------------------------------*/ - static int WaitTask(void *pData) - { - time_t tNow; - pWaitStruct self = NULL; - - self = (pWaitStruct)pData; - if(self->iEnd) - { - return 0; - } - - tNow = time(NULL); - if(tNow >= self->tFinish) - { - return 0; /* done */ - } - else - { - return 1; - } +static int WaitTask(void *pData) +{ + time_t tNow; + pWaitStruct self = NULL; + + self = (pWaitStruct) pData; + if (self->iEnd) { + return 0; } + + tNow = time(NULL); + if (tNow >= self->tFinish) { + return 0; /* done */ + } else { + return 1; + } +} + /*-----------------------------------------------------------------------*/ - static void WaitSignal(void *pUser, int iSignal, void *pEventData) - { - pWaitStruct self = NULL; - int *iInt; - - self = (pWaitStruct)pUser; - assert(self); - iInt = (int *)pEventData; - - if(iSignal == SICSINT) - { - iInt = (int *)pEventData; - if(*iInt > eContinue) - { - self->iEnd = 1; - } - } +static void WaitSignal(void *pUser, int iSignal, void *pEventData) +{ + pWaitStruct self = NULL; + int *iInt; + + self = (pWaitStruct) pUser; + assert(self); + iInt = (int *) pEventData; + + if (iSignal == SICSINT) { + iInt = (int *) pEventData; + if (*iInt > eContinue) { + self->iEnd = 1; + } } - +} + /*-------------------------------------------------------------------------- UserWait: the user command for waiting, expects one arg: time to wait in seconds ---------------------------------------------------------------------------*/ - int UserWait(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int i; - char pBueffel[80]; - float fVal; - Status eOld; - time_t tNow; - WaitStruct sWait; - pTaskMan pTask; - long lID; - - assert(pCon); - assert(pSics); - assert(pData); - - pTask = GetTasker(); - - if(argc < 2) - { - sprintf(pBueffel,"Insufficient number of args to %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* try convert to a number */ - i = sscanf(argv[1],"%f",&fVal); - if(i < 1) - { - sprintf(pBueffel,"Expected numeric argument to %s, got %s", - argv[0], argv[1]); - SCWrite(pCon,pBueffel,eInError); - return 0; - } - - if(pServ->simMode) - { - return 1; - } +int UserWait(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int i; + char pBueffel[80]; + float fVal; + Status eOld; + time_t tNow; + WaitStruct sWait; + pTaskMan pTask; + long lID; - eOld = GetStatus(); - SetStatus(eUserWait); - tNow = time(NULL); - sWait.tFinish = tNow + (time_t)fVal; - sWait.iEnd = 0; - lID = TaskRegister(pTask,WaitTask,WaitSignal,NULL,&sWait,1); - TaskWait(pTask,lID); - SetStatus(eOld); - if(SCGetInterrupt(pCon) != eContinue) - { - return 0; - } - else - { - return 1; - } - } -/*------------------------------------------------------------------------*/ - int SicsWaitOld(long lTime) - { - WaitStruct sWait; - pTaskMan pTasker = NULL; - time_t tNow; - long lID; + assert(pCon); + assert(pSics); + assert(pData); - if(pServ->simMode) - { - return 1; - } + pTask = GetTasker(); - pTasker = GetTasker(); - tNow = time(NULL); - sWait.tFinish = tNow + lTime; - sWait.iEnd = 0; - lID = TaskRegister(pTasker,WaitTask,WaitSignal,NULL,&sWait,1); - TaskWait(pTasker,lID); + if (argc < 2) { + sprintf(pBueffel, "Insufficient number of args to %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* try convert to a number */ + i = sscanf(argv[1], "%f", &fVal); + if (i < 1) { + sprintf(pBueffel, "Expected numeric argument to %s, got %s", + argv[0], argv[1]); + SCWrite(pCon, pBueffel, eInError); + return 0; + } + + if (pServ->simMode) { return 1; } + + eOld = GetStatus(); + SetStatus(eUserWait); + tNow = time(NULL); + sWait.tFinish = tNow + (time_t) fVal; + sWait.iEnd = 0; + lID = TaskRegister(pTask, WaitTask, WaitSignal, NULL, &sWait, 1); + TaskWait(pTask, lID); + SetStatus(eOld); + if (SCGetInterrupt(pCon) != eContinue) { + return 0; + } else { + return 1; + } +} + +/*------------------------------------------------------------------------*/ +int SicsWaitOld(long lTime) +{ + WaitStruct sWait; + pTaskMan pTasker = NULL; + time_t tNow; + long lID; + + if (pServ->simMode) { + return 1; + } + + pTasker = GetTasker(); + tNow = time(NULL); + sWait.tFinish = tNow + lTime; + sWait.iEnd = 0; + lID = TaskRegister(pTasker, WaitTask, WaitSignal, NULL, &sWait, 1); + TaskWait(pTasker, lID); + return 1; +} + /*------------------------------------------------------------------------ The new SicsWait is still on probation. It prevents commands to be executed on the same task on which the Sicswait is acting. M.K. December 2005 - -------------------------------------------------------------------------*/ - int SicsWait(long lTime) - { - pTaskMan pTasker = NULL; - time_t endTime; + -------------------------------------------------------------------------*/ +int SicsWait(long lTime) +{ + pTaskMan pTasker = NULL; + time_t endTime; - if(pServ->simMode) - { - return 1; - } - pTasker = GetTasker(); - endTime = time(NULL) + lTime; - while(time(NULL) < endTime) - { - TaskYield(pTasker); - } - return 1; + if (pServ->simMode) { + return 1; } + pTasker = GetTasker(); + endTime = time(NULL) + lTime; + while (time(NULL) < endTime) { + TaskYield(pTasker); + } + return 1; +} + /*-------------------------------------------------------------------------*/ - void ServerWriteGlobal(char *pMessage,int iOut) - { - pTaskMan pTasker = NULL; - - pTasker = GetTasker(); - - TaskSignal(pTasker,SICSBROADCAST,pMessage); - } +void ServerWriteGlobal(char *pMessage, int iOut) +{ + pTaskMan pTasker = NULL; + + pTasker = GetTasker(); + + TaskSignal(pTasker, SICSBROADCAST, pMessage); +} + /*-------------------------------------------------------------------------*/ - int ServerIsStarting(pServer self) - { - return self->pReader == NULL; - } +int ServerIsStarting(pServer self) +{ + return self->pReader == NULL; +} diff --git a/nserver.h b/nserver.h index 3c644041..8a9619b1 100644 --- a/nserver.h +++ b/nserver.h @@ -19,36 +19,36 @@ #include "task.h" #include "network.h" - typedef struct __SicsServer *pServer; +typedef struct __SicsServer *pServer; #include "nread.h" - typedef struct __SicsServer { - SicsInterp *pSics; - pTaskMan pTasker; - pExeList pExecutor; - pEnvMon pMonitor; - mkChannel *pServerPort; - pNetRead pReader; - int simMode; - SConnection *dummyCon; - } SicsServer; +typedef struct __SicsServer { + SicsInterp *pSics; + pTaskMan pTasker; + pExeList pExecutor; + pEnvMon pMonitor; + mkChannel *pServerPort; + pNetRead pReader; + int simMode; + SConnection *dummyCon; +} SicsServer; /*----------------------------------------------------------------------*/ - int InitServer(char *file, pServer *pServ); - void RunServer(pServer self); - void StopServer(pServer self); +int InitServer(char *file, pServer * pServ); +void RunServer(pServer self); +void StopServer(pServer self); /*----------------------------------------------------------------------*/ - SicsInterp *GetInterpreter(void); - pExeList GetExecutor(void); - pTaskMan GetTasker(void); - void ServerWriteGlobal(char *pMessage, int iCode); +SicsInterp *GetInterpreter(void); +pExeList GetExecutor(void); +pTaskMan GetTasker(void); +void ServerWriteGlobal(char *pMessage, int iCode); - int UserWait(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int UserWait(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - int SicsWait(long lTime); - int ServerIsStarting(pServer self); +int SicsWait(long lTime); +int ServerIsStarting(pServer self); #endif diff --git a/nwatch.c b/nwatch.c index 80627318..32f8d674 100644 --- a/nwatch.c +++ b/nwatch.c @@ -25,25 +25,26 @@ /* Net Watcher control structure */ typedef struct __netwatcher_s { - pNWContext cq_head; /* head of socket context queue */ - pNWContext cq_tail; /* tail of socket context queue */ - int nInvalid; /* number of invalidated entries */ - pNWTimer tq_head; /* head of timer context queue */ - pNWTimer tq_tail; /* tail of timer context queue */ - long lMagic; /* integrity check */ + pNWContext cq_head; /* head of socket context queue */ + pNWContext cq_tail; /* tail of socket context queue */ + int nInvalid; /* number of invalidated entries */ + pNWTimer tq_head; /* head of timer context queue */ + pNWTimer tq_tail; /* tail of timer context queue */ + long lMagic; /* integrity check */ } NetWatch, *pNetWatch; /* Singleton pattern */ static pNetWatch instance = NULL; -static int NetWatchTask(void* pData); +static int NetWatchTask(void *pData); /** * \brief Initialises the Net Watcher singleton and starts the task * * \return 1=success, 0=failure */ -int NetWatchInit(void) { +int NetWatchInit(void) +{ /* * If the singleton has not yet been created, do so now */ @@ -62,12 +63,12 @@ int NetWatchInit(void) { * The timer context object private definition */ typedef struct __netwatchtimer { - pNWTimer next; /* chain to next event */ - struct timeval tv; /* time when event is due */ - pNWCallback func; /* function to call */ - void* cntx; /* abstract context to pass to callback */ - long int tick; /* millisecond repeat rate */ - long int vrfy; /* integrity check */ + pNWTimer next; /* chain to next event */ + struct timeval tv; /* time when event is due */ + pNWCallback func; /* function to call */ + void *cntx; /* abstract context to pass to callback */ + long int tick; /* millisecond repeat rate */ + long int vrfy; /* integrity check */ } NWTimer; /* @@ -100,20 +101,18 @@ static int NetWatchTimerInsQue(pNetWatch self, pNWTimer handle) handle->next = self->tq_head; self->tq_head = handle; return 1; - } - else - { + } else { /* must be in between two so start at the first entry */ pNWTimer pNxt = self->tq_head; /* follow chain until the one after this one is greater than new one */ while (pNxt->next && - (handle->tv.tv_sec > pNxt->next->tv.tv_sec || - (handle->tv.tv_sec == pNxt->next->tv.tv_sec && - handle->tv.tv_usec > pNxt->next->tv.tv_usec))) + (handle->tv.tv_sec > pNxt->next->tv.tv_sec || + (handle->tv.tv_sec == pNxt->next->tv.tv_sec && + handle->tv.tv_usec > pNxt->next->tv.tv_usec))) pNxt = pNxt->next; /* slip new one in between this one and the next one */ handle->next = pNxt->next; - pNxt->next = handle ; + pNxt->next = handle; } return 1; } @@ -128,7 +127,7 @@ static int NetWatchTimerRemQue(pNetWatch self, pNWTimer handle) { /* handle the case of first and possibly only */ if (handle == self->tq_head) { - self->tq_head = self->tq_head->next; /* may be NULL */ + self->tq_head = self->tq_head->next; /* may be NULL */ if (handle == self->tq_tail) self->tq_tail = NULL; } @@ -149,11 +148,11 @@ static int NetWatchTimerRemQue(pNetWatch self, pNWTimer handle) return 1; } -int NetWatchRegisterTimer(pNWTimer* handle, int mSec, - pNWCallback callback, void* context) +int NetWatchRegisterTimer(pNWTimer * handle, int mSec, + pNWCallback callback, void *context) { pNetWatch self = instance; - if(!self || self->lMagic != NWMAGIC) + if (!self || self->lMagic != NWMAGIC) return 0; pNWTimer pNew = (pNWTimer) malloc(sizeof(NWTimer)); if (pNew == NULL) @@ -163,7 +162,7 @@ int NetWatchRegisterTimer(pNWTimer* handle, int mSec, pNew->tv.tv_sec += mSec / 1000; pNew->tv.tv_usec += 1000 * (mSec % 1000); if (pNew->tv.tv_usec > 1000000) { - pNew->tv.tv_sec ++; + pNew->tv.tv_sec++; pNew->tv.tv_usec -= 1000000; } pNew->tick = 0; @@ -175,8 +174,9 @@ int NetWatchRegisterTimer(pNWTimer* handle, int mSec, return 1; } -int NetWatchRegisterTimerPeriodic(pNWTimer* handle, int mSecInitial, int mSecPeriod, - pNWCallback callback, void* context) +int NetWatchRegisterTimerPeriodic(pNWTimer * handle, int mSecInitial, + int mSecPeriod, pNWCallback callback, + void *context) { if (NetWatchRegisterTimer(handle, mSecInitial, callback, context)) { pNWTimer pNew = *handle; @@ -207,7 +207,7 @@ int NetWatchSetTimerPeriod(pNWTimer handle, int mSecPeriod) int NetWatchRemoveTimer(pNWTimer handle) { pNetWatch self = instance; - if (!self || self->lMagic != NWMAGIC)\ + if (!self || self->lMagic != NWMAGIC) return 0; NetWatchTimerRemQue(self, handle); handle->vrfy = 0; @@ -217,12 +217,12 @@ int NetWatchRemoveTimer(pNWTimer handle) /* private data */ typedef struct __netwatchcontext { - pNWContext next; /* chain pointer */ - int sock; /* socket to watch */ - int mode; /* read or write */ - pNWCallback func; /* user supplied callback function */ - void* cntx; /* user supplied callback context */ - long vrfy; /* integrity check */ + pNWContext next; /* chain pointer */ + int sock; /* socket to watch */ + int mode; /* read or write */ + pNWCallback func; /* user supplied callback function */ + void *cntx; /* user supplied callback context */ + long vrfy; /* integrity check */ } NWContext; /** @@ -233,7 +233,7 @@ typedef struct __netwatchcontext { */ static int NetWatchContextInsQue(pNetWatch self, pNWContext handle) { - if (self->cq_head == NULL) /* empty */ + if (self->cq_head == NULL) /* empty */ self->cq_head = self->cq_tail = handle; else { self->cq_tail->next = handle; @@ -250,12 +250,11 @@ static int NetWatchContextInsQue(pNetWatch self, pNWContext handle) */ static void NetWatchContextRemQue(pNetWatch self, pNWContext handle) { - if (handle == self->cq_head) { /* if first */ + if (handle == self->cq_head) { /* if first */ self->cq_head = self->cq_head->next; - if (handle == self->cq_tail) /* if also last */ + if (handle == self->cq_tail) /* if also last */ self->cq_tail = NULL; - } - else { + } else { pNWContext pNxt = self->cq_head; while (pNxt) { if (handle == pNxt->next) { @@ -264,7 +263,7 @@ static void NetWatchContextRemQue(pNetWatch self, pNWContext handle) } pNxt = pNxt->next; } - if (handle == self->cq_tail) /* if last */ + if (handle == self->cq_tail) /* if last */ self->cq_tail = pNxt; } return; @@ -304,12 +303,12 @@ static void NetWatchContextPrgQue(pNetWatch self) return; } -int NetWatchRegisterCallback(pNWContext* handle, int iSocket, - pNWCallback callback, void* context) +int NetWatchRegisterCallback(pNWContext * handle, int iSocket, + pNWCallback callback, void *context) { pNWContext pNew = NULL; pNetWatch self = instance; - if(!self || self->lMagic != NWMAGIC) + if (!self || self->lMagic != NWMAGIC) return 0; if (iSocket < 0 || iSocket > 65535) return 0; @@ -332,7 +331,7 @@ int NetWatchRemoveCallback(pNWContext handle) pNetWatch self = instance; if (handle == NULL || handle->vrfy != NWMAGIC) return 0; - if(!self || self->lMagic != NWMAGIC) + if (!self || self->lMagic != NWMAGIC) return 0; handle->sock = -1; self->nInvalid++; @@ -357,19 +356,19 @@ int NetWatchSetMode(pNWContext handle, int mode) /** * \brief the registered SICS Task to drive all this */ -int NetWatchTask (void* pData) +int NetWatchTask(void *pData) { pNetWatch self = NULL; pNWContext pNWC = NULL; fd_set rMask; fd_set wMask; - struct timeval tmo = {0,0}; + struct timeval tmo = { 0, 0 }; int iRet; int iCount; /* Check the singleton */ self = (pNetWatch) instance; - if(!self || self->lMagic != NWMAGIC) + if (!self || self->lMagic != NWMAGIC) return 0; /* Purge the invalidated */ @@ -381,13 +380,13 @@ int NetWatchTask (void* pData) FD_ZERO(&wMask); pNWC = self->cq_head; iCount = -1; - while(pNWC) { + while (pNWC) { if (pNWC->sock >= 0 && pNWC->sock <= 65535) { if (pNWC->mode & nwatch_read) - FD_SET(pNWC->sock,&rMask); + FD_SET(pNWC->sock, &rMask); if (pNWC->mode & nwatch_write) - FD_SET(pNWC->sock,&wMask); - if(pNWC->sock > iCount) { + FD_SET(pNWC->sock, &wMask); + if (pNWC->sock > iCount) { iCount = pNWC->sock; } } @@ -396,14 +395,13 @@ int NetWatchTask (void* pData) iRet = 0; if (iCount >= 0) - iRet = uselect(iCount+1, &rMask, &wMask, NULL, &tmo); + iRet = uselect(iCount + 1, &rMask, &wMask, NULL, &tmo); - if(iRet > 0) { + if (iRet > 0) { /* invoke the active callbacks */ iCount = 0; pNWC = self->cq_head; - while(pNWC) - { + while (pNWC) { if (pNWC->sock >= 0 && pNWC->sock <= 65535) { int action_mode = 0; if ((pNWC->mode & nwatch_read) && FD_ISSET(pNWC->sock, &rMask)) @@ -412,7 +410,7 @@ int NetWatchTask (void* pData) action_mode |= nwatch_write; if (action_mode != 0) { int iStatus; - iStatus = (*pNWC->func)(pNWC->cntx, action_mode); + iStatus = (*pNWC->func) (pNWC->cntx, action_mode); } } pNWC = pNWC->next; @@ -427,7 +425,7 @@ int NetWatchTask (void* pData) while (self->tq_head) { pNWTimer pNew = self->tq_head; if (tv.tv_sec < pNew->tv.tv_sec || - (tv.tv_sec == pNew->tv.tv_sec && + (tv.tv_sec == pNew->tv.tv_sec && tv.tv_usec < pNew->tv.tv_usec)) { break; } @@ -443,8 +441,8 @@ int NetWatchTask (void* pData) */ gettimeofday(&tv, NULL); while (tv.tv_sec > pNew->tv.tv_sec || - (tv.tv_sec == pNew->tv.tv_sec && - tv.tv_usec > pNew->tv.tv_usec)) { + (tv.tv_sec == pNew->tv.tv_sec && + tv.tv_usec > pNew->tv.tv_usec)) { pNew->tv.tv_usec += 1000 * pNew->tick; if (pNew->tv.tv_usec > 1000000) { pNew->tv.tv_sec += pNew->tv.tv_usec / 1000000; @@ -452,8 +450,7 @@ int NetWatchTask (void* pData) } } NetWatchTimerInsQue(self, pNew); - } - else { + } else { pNew->vrfy = 0; free(pNew); } diff --git a/nwatch.h b/nwatch.h index fbaeda14..03f41fb4 100644 --- a/nwatch.h +++ b/nwatch.h @@ -22,7 +22,7 @@ * * \return normally zero, for future use */ -typedef int (*pNWCallback)(void* context, int mode); +typedef int (*pNWCallback) (void *context, int mode); /* the abstract timer object handle */ typedef struct __netwatchtimer *pNWTimer; @@ -36,8 +36,8 @@ typedef struct __netwatchtimer *pNWTimer; * \param context abstract context passed to callback function * \return success=1, failure=0 */ -int NetWatchRegisterTimer(pNWTimer* handle, int mSec, - pNWCallback callback, void* context); +int NetWatchRegisterTimer(pNWTimer * handle, int mSec, + pNWCallback callback, void *context); /** * \brief register a periodic timer @@ -49,8 +49,9 @@ int NetWatchRegisterTimer(pNWTimer* handle, int mSec, * \param context abstract context passed to callback function * \return success=1, failure=0 */ -int NetWatchRegisterTimerPeriodic(pNWTimer* handle, int mSecInitial, int mSecPeriod, - pNWCallback callback, void* context); +int NetWatchRegisterTimerPeriodic(pNWTimer * handle, int mSecInitial, + int mSecPeriod, pNWCallback callback, + void *context); int NetWatchGetTimerPeriod(pNWTimer handle); int NetWatchSetTimerPeriod(pNWTimer handle, int mSecPeriod); @@ -74,8 +75,8 @@ typedef struct __netwatchcontext *pNWContext; * \param context abstract context passed to callback function * \return success=1, failure=0 */ -int NetWatchRegisterCallback(pNWContext* handle, int iSocket, - pNWCallback callback, void* context); +int NetWatchRegisterCallback(pNWContext * handle, int iSocket, + pNWCallback callback, void *context); /** * \brief remove a socket callback registration @@ -102,4 +103,4 @@ int NetWatchGetMode(pNWContext handle); */ int NetWatchSetMode(pNWContext handle, int mode); -#endif /* SICSNETWATCHER */ +#endif /* SICSNETWATCHER */ diff --git a/nxcopy.c b/nxcopy.c index 116b00b1..6a12b592 100644 --- a/nxcopy.c +++ b/nxcopy.c @@ -17,7 +17,8 @@ * decode a SWIG style pointer into the real pointer value. * Stolen from SWIG generated code. --------------------------------------------------------------------------------*/ -static const char *SWIG_UnpackData(const char *c, void *ptr, size_t sz) { +static const char *SWIG_UnpackData(const char *c, void *ptr, size_t sz) +{ register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { @@ -26,269 +27,284 @@ static const char *SWIG_UnpackData(const char *c, void *ptr, size_t sz) { if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) - uu = ((d - ('a'-10)) << 4); - else + uu = ((d - ('a' - 10)) << 4); + else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) - uu |= (d - ('a'-10)); - else + uu |= (d - ('a' - 10)); + else return (char *) 0; *u = uu; } return c; } + /*-------------------------------------------------------------------------------*/ -int isTypeAllowed(int type){ - switch(type){ - case NX_INT32: - case NX_UINT32: - case NX_FLOAT32: - return 1; - break; - default: - return 0; - break; - } -} +int isTypeAllowed(int type) +{ + switch (type) { + case NX_INT32: + case NX_UINT32: + case NX_FLOAT32: + return 1; + break; + default: + return 0; + break; + } +} + /*-------------------------------------------------------------------------------- * copy an nxdataset to a sicsdata object --------------------------------------------------------------------------------*/ -static int NXDataToSicsdata(ClientData clientData, Tcl_Interp *interp, - int objc, Tcl_Obj *CONST objv[]){ - Tcl_Obj *resultPtr; - const char *text; - pNXDS data = NULL; - pSICSData sicsData; - int length, i; - - if(objc < 3) { - Tcl_WrongNumArgs(interp,objc,objv,"Usage: nxdatatosicsdata nxdata sicsdata"); - return TCL_ERROR; - } - resultPtr = Tcl_GetObjResult(interp); - - /* - * get nxdataset pointer - */ - text = Tcl_GetStringFromObj(objv[1],NULL); - if(strstr(text,"NULL") != NULL){ - Tcl_SetStringObj(resultPtr,"nxdata argument is NULL pointer",38); - return TCL_ERROR; - } - text++; - SWIG_UnpackData(text,&data,sizeof(void *)); +static int NXDataToSicsdata(ClientData clientData, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) +{ + Tcl_Obj *resultPtr; + const char *text; + pNXDS data = NULL; + pSICSData sicsData; + int length, i; - if(data->magic != MAGIC){ - Tcl_SetStringObj(resultPtr,"nxdata argument is no valid nxdataset", - strlen("nxdata argument is no valid nxdataset")); - return TCL_ERROR; - } - length = getNXDatasetLength(data); - if(!isTypeAllowed(data->type)){ - Tcl_SetStringObj(resultPtr,"can only copy int and float types", - strlen("can only copy int and float types")); - return TCL_ERROR; - } + if (objc < 3) { + Tcl_WrongNumArgs(interp, objc, objv, + "Usage: nxdatatosicsdata nxdata sicsdata"); + return TCL_ERROR; + } + resultPtr = Tcl_GetObjResult(interp); - /* - * locate sicsdata - */ - text = Tcl_GetStringFromObj(objv[2],NULL); - sicsData = (pSICSData)FindCommandData(pServ->pSics,(char *)text,"SICSData"); - if(sicsData == NULL){ - Tcl_SetStringObj(resultPtr,"sicsdata argument is no valid SICSData", - strlen("sicsdata argument is no valid SICSData")); - return TCL_ERROR; - } - - /* - * copy the data - */ - if(data->type == NX_FLOAT32){ - for(i = 0; i < length; i++){ - setSICSDataFloat(sicsData,i,data->u.fPtr[i]); - } - } else { - for(i = 0; i < length; i++){ - setSICSDataInt(sicsData,i,data->u.iPtr[i]); - } - } - - return TCL_OK; -} -/*--------------------------------------------------------------------------*/ -static hdbValue NXDatasetToHdbValue(pNXDS data){ - hdbValue val; - int length, i; - - length = getNXDatasetLength(data); - switch(getNXDatasetType(data)){ - case NX_INT32: - case NX_UINT32: - if(length == 1){ - val = MakeHdbInt(data->u.iPtr[0]); - } else { - val = MakeHdbIntArray(length,data->u.iPtr); - val.dataType = HIPINTVARAR; - } - break; - case NX_FLOAT32: - if(length == 1){ - val = MakeHdbFloat((double)data->u.fPtr[0]); - } else { - val = makeHdbValue(HIPFLOATAR,length); - for(i = 0; i < length; i++){ - val.v.floatArray[i] = (double)data->u.fPtr[i]; - } - val.dataType = HIPFLOATVARAR; - } - break; - case NX_FLOAT64: - if(length == 1){ - val = MakeHdbFloat(data->u.dPtr[0]); - } else { - val = MakeHdbFloatArray(length,data->u.dPtr); - } - break; - case NX_CHAR: - case NX_INT8: - case NX_UINT8: - val = MakeHdbText(data->u.cPtr); - break; - case NX_INT16: - case NX_UINT16: - if(length == 1){ - val = MakeHdbInt((int)data->u.sPtr[0]); - } else { - val = makeHdbValue(HIPINTAR,length); - for(i = 0; i < length; i++){ - val.v.intArray[i] = (int)data->u.sPtr[i]; - } - } - break; + /* + * get nxdataset pointer + */ + text = Tcl_GetStringFromObj(objv[1], NULL); + if (strstr(text, "NULL") != NULL) { + Tcl_SetStringObj(resultPtr, "nxdata argument is NULL pointer", 38); + return TCL_ERROR; + } + text++; + SWIG_UnpackData(text, &data, sizeof(void *)); + + if (data->magic != MAGIC) { + Tcl_SetStringObj(resultPtr, "nxdata argument is no valid nxdataset", + strlen("nxdata argument is no valid nxdataset")); + return TCL_ERROR; + } + length = getNXDatasetLength(data); + if (!isTypeAllowed(data->type)) { + Tcl_SetStringObj(resultPtr, "can only copy int and float types", + strlen("can only copy int and float types")); + return TCL_ERROR; + } + + /* + * locate sicsdata + */ + text = Tcl_GetStringFromObj(objv[2], NULL); + sicsData = + (pSICSData) FindCommandData(pServ->pSics, (char *) text, "SICSData"); + if (sicsData == NULL) { + Tcl_SetStringObj(resultPtr, "sicsdata argument is no valid SICSData", + strlen("sicsdata argument is no valid SICSData")); + return TCL_ERROR; + } + + /* + * copy the data + */ + if (data->type == NX_FLOAT32) { + for (i = 0; i < length; i++) { + setSICSDataFloat(sicsData, i, data->u.fPtr[i]); } - return val; + } else { + for (i = 0; i < length; i++) { + setSICSDataInt(sicsData, i, data->u.iPtr[i]); + } + } + + return TCL_OK; } + +/*--------------------------------------------------------------------------*/ +static hdbValue NXDatasetToHdbValue(pNXDS data) +{ + hdbValue val; + int length, i; + + length = getNXDatasetLength(data); + switch (getNXDatasetType(data)) { + case NX_INT32: + case NX_UINT32: + if (length == 1) { + val = MakeHdbInt(data->u.iPtr[0]); + } else { + val = MakeHdbIntArray(length, data->u.iPtr); + val.dataType = HIPINTVARAR; + } + break; + case NX_FLOAT32: + if (length == 1) { + val = MakeHdbFloat((double) data->u.fPtr[0]); + } else { + val = makeHdbValue(HIPFLOATAR, length); + for (i = 0; i < length; i++) { + val.v.floatArray[i] = (double) data->u.fPtr[i]; + } + val.dataType = HIPFLOATVARAR; + } + break; + case NX_FLOAT64: + if (length == 1) { + val = MakeHdbFloat(data->u.dPtr[0]); + } else { + val = MakeHdbFloatArray(length, data->u.dPtr); + } + break; + case NX_CHAR: + case NX_INT8: + case NX_UINT8: + val = MakeHdbText(data->u.cPtr); + break; + case NX_INT16: + case NX_UINT16: + if (length == 1) { + val = MakeHdbInt((int) data->u.sPtr[0]); + } else { + val = makeHdbValue(HIPINTAR, length); + for (i = 0; i < length; i++) { + val.v.intArray[i] = (int) data->u.sPtr[i]; + } + } + break; + } + return val; +} + /*--------------------------------------------------------------------------- * copy the content of an nxdataset onto a Hipadaba node *---------------------------------------------------------------------------*/ -static int NXDataToHdbNode(ClientData clientData, Tcl_Interp *interp, - int objc, Tcl_Obj *CONST objv[]){ - pNXDS data = NULL; - Tcl_Obj *resultPtr; - int length, status; - const char *text; - pHdb node = NULL; - hdbValue val; +static int NXDataToHdbNode(ClientData clientData, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) +{ + pNXDS data = NULL; + Tcl_Obj *resultPtr; + int length, status; + const char *text; + pHdb node = NULL; + hdbValue val; - if(objc < 3) { - Tcl_WrongNumArgs(interp,objc,objv,"Usage: nxdatatohdb nxdata path"); - return TCL_ERROR; - } - resultPtr = Tcl_GetObjResult(interp); - - /* - * get nxdataset pointer - */ - text = Tcl_GetStringFromObj(objv[1],NULL); - if(strstr(text,"NULL") != NULL){ - Tcl_SetStringObj(resultPtr,"nxdata argument is NULL pointer",38); - return TCL_ERROR; - } - text++; - SWIG_UnpackData(text,&data,sizeof(void *)); + if (objc < 3) { + Tcl_WrongNumArgs(interp, objc, objv, "Usage: nxdatatohdb nxdata path"); + return TCL_ERROR; + } + resultPtr = Tcl_GetObjResult(interp); - if(data->magic != MAGIC){ - Tcl_SetStringObj(resultPtr,"nxdata argument is no valid nxdataset", - strlen("nxdata argument is no valid nxdataset")); - return TCL_ERROR; - } - length = getNXDatasetLength(data); + /* + * get nxdataset pointer + */ + text = Tcl_GetStringFromObj(objv[1], NULL); + if (strstr(text, "NULL") != NULL) { + Tcl_SetStringObj(resultPtr, "nxdata argument is NULL pointer", 38); + return TCL_ERROR; + } + text++; + SWIG_UnpackData(text, &data, sizeof(void *)); - /* - * locate node - */ - text = Tcl_GetStringFromObj(objv[2],NULL); - node = GetHipadabaNode(GetHipadabaRoot(),(char *)text); - if(node == NULL){ - Tcl_SetStringObj(resultPtr,"path does not point to a valid node", - strlen("path does not point to a valid node")); - return TCL_ERROR; - } - - val = NXDatasetToHdbValue(data); - status = UpdateHipadabaPar(node,val,NULL); - if(status != 1){ - Tcl_SetStringObj(resultPtr,"data type mismatch", - strlen("data type mismatch")); - return TCL_ERROR; - } - return TCL_OK; + if (data->magic != MAGIC) { + Tcl_SetStringObj(resultPtr, "nxdata argument is no valid nxdataset", + strlen("nxdata argument is no valid nxdataset")); + return TCL_ERROR; + } + length = getNXDatasetLength(data); + + /* + * locate node + */ + text = Tcl_GetStringFromObj(objv[2], NULL); + node = GetHipadabaNode(GetHipadabaRoot(), (char *) text); + if (node == NULL) { + Tcl_SetStringObj(resultPtr, "path does not point to a valid node", + strlen("path does not point to a valid node")); + return TCL_ERROR; + } + + val = NXDatasetToHdbValue(data); + status = UpdateHipadabaPar(node, val, NULL); + if (status != 1) { + Tcl_SetStringObj(resultPtr, "data type mismatch", + strlen("data type mismatch")); + return TCL_ERROR; + } + return TCL_OK; } + /*---------------------------------------------------------------------------*/ -static int NXDataToHM(ClientData clientData, Tcl_Interp *interp, - int objc, Tcl_Obj *CONST objv[]){ - pNXDS data = NULL; - Tcl_Obj *resultPtr; - int length, status; - const char *text; - pHistMem pHM = NULL; - SConnection *pCon = NULL; +static int NXDataToHM(ClientData clientData, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) +{ + pNXDS data = NULL; + Tcl_Obj *resultPtr; + int length, status; + const char *text; + pHistMem pHM = NULL; + SConnection *pCon = NULL; - if(objc < 3) { - Tcl_WrongNumArgs(interp,objc,objv,"Usage: nxdatatohdb nxdata path"); - return TCL_ERROR; - } - resultPtr = Tcl_GetObjResult(interp); - - /* - * get nxdataset pointer - */ - text = Tcl_GetStringFromObj(objv[1],NULL); - if(strstr(text,"NULL") != NULL){ - Tcl_SetStringObj(resultPtr,"nxdata argument is NULL pointer",38); - return TCL_ERROR; - } - text++; - SWIG_UnpackData(text,&data,sizeof(void *)); + if (objc < 3) { + Tcl_WrongNumArgs(interp, objc, objv, "Usage: nxdatatohdb nxdata path"); + return TCL_ERROR; + } + resultPtr = Tcl_GetObjResult(interp); - if(data->magic != MAGIC){ - Tcl_SetStringObj(resultPtr,"nxdata argument is no valid nxdataset", - strlen("nxdata argument is no valid nxdataset")); - return TCL_ERROR; - } - length = getNXDatasetLength(data); - - /* - * get HM - */ - text = Tcl_GetStringFromObj(objv[2],NULL); - pHM = (pHistMem)FindCommandData(pServ->pSics,(char *)text,"HistMem"); - if(pHM == NULL){ - Tcl_SetStringObj(resultPtr,"hm argument is not histogram memory", - strlen("hm argument is not histogram memory")); - return TCL_ERROR; - } - - if(getNXDatasetType(data) != NX_INT32 || GetHistLength(pHM) < length){ - Tcl_SetStringObj(resultPtr,"data to hm type or length mismatch", - strlen("data to hm type or length mismatch")); - return TCL_ERROR; - } - - pCon = SCCreateDummyConnection(pServ->pSics); - SetHistogram(pHM, pCon, 0,0,length, data->u.iPtr); - SCDeleteConnection(pCon); - - return TCL_OK; + /* + * get nxdataset pointer + */ + text = Tcl_GetStringFromObj(objv[1], NULL); + if (strstr(text, "NULL") != NULL) { + Tcl_SetStringObj(resultPtr, "nxdata argument is NULL pointer", 38); + return TCL_ERROR; + } + text++; + SWIG_UnpackData(text, &data, sizeof(void *)); + + if (data->magic != MAGIC) { + Tcl_SetStringObj(resultPtr, "nxdata argument is no valid nxdataset", + strlen("nxdata argument is no valid nxdataset")); + return TCL_ERROR; + } + length = getNXDatasetLength(data); + + /* + * get HM + */ + text = Tcl_GetStringFromObj(objv[2], NULL); + pHM = (pHistMem) FindCommandData(pServ->pSics, (char *) text, "HistMem"); + if (pHM == NULL) { + Tcl_SetStringObj(resultPtr, "hm argument is not histogram memory", + strlen("hm argument is not histogram memory")); + return TCL_ERROR; + } + + if (getNXDatasetType(data) != NX_INT32 || GetHistLength(pHM) < length) { + Tcl_SetStringObj(resultPtr, "data to hm type or length mismatch", + strlen("data to hm type or length mismatch")); + return TCL_ERROR; + } + + pCon = SCCreateDummyConnection(pServ->pSics); + SetHistogram(pHM, pCon, 0, 0, length, data->u.iPtr); + SCDeleteConnection(pCon); + + return TCL_OK; } + /*---------------------------------------------------------------------------*/ -int NXcopy_Init(Tcl_Interp *pInter){ - Tcl_CreateObjCommand(pInter,"nxToSicsData",NXDataToSicsdata,NULL,NULL); - Tcl_CreateObjCommand(pInter,"nxToHdb",NXDataToHdbNode,NULL,NULL); - Tcl_CreateObjCommand(pInter,"nxToHM",NXDataToHM,NULL,NULL); - return 1; +int NXcopy_Init(Tcl_Interp * pInter) +{ + Tcl_CreateObjCommand(pInter, "nxToSicsData", NXDataToSicsdata, NULL, + NULL); + Tcl_CreateObjCommand(pInter, "nxToHdb", NXDataToHdbNode, NULL, NULL); + Tcl_CreateObjCommand(pInter, "nxToHM", NXDataToHM, NULL, NULL); + return 1; } diff --git a/nxcopy.h b/nxcopy.h index 539fae36..cc49852d 100644 --- a/nxcopy.h +++ b/nxcopy.h @@ -11,6 +11,6 @@ #define NXCOPY_H_ #include -int NXcopy_Init(Tcl_Interp *pTcl); +int NXcopy_Init(Tcl_Interp * pTcl); -#endif /*NXCOPY_H_*/ +#endif /*NXCOPY_H_ */ diff --git a/nxdata.c b/nxdata.c index ff060a11..105b6e7d 100644 --- a/nxdata.c +++ b/nxdata.c @@ -49,7 +49,7 @@ #include "nxdict.h" #include "modriv.h" #include "motor.h" -#include "nxdata.h" +#include "nxdata.h" #include "nxutil.h" #include "selector.h" #include "selvar.h" @@ -67,834 +67,748 @@ #define HRPTDETNAM "Cerca-Detector" /*-----------------------------------------------------------------------*/ - static void SNError(void *pData, char *text) - { - SConnection *pCon; - - assert(pData); - pCon = (SConnection *)pData; - SCWrite(pCon,text,eError); - } +static void SNError(void *pData, char *text) +{ + SConnection *pCon; + + assert(pData); + pCon = (SConnection *) pData; + SCWrite(pCon, text, eError); +} + /*-----------------------------------------------------------------------*/ -char *SNXMakeFileName(SicsInterp *pSics, SConnection *pCon) +char *SNXMakeFileName(SicsInterp * pSics, SConnection * pCon) { char *pPtr = NULL; - pPtr = makeFilename(pSics,pCon); - if(pPtr == NULL) - { + pPtr = makeFilename(pSics, pCon); + if (pPtr == NULL) { pPtr = strdup("emergency.hdf"); } return pPtr; } + /*------------------------------------------------------------------------*/ - char *SNXMakeFileNameOld(SicsInterp *pSics, SConnection *pCon) - { - pSicsVariable pPath = NULL, pPref = NULL, pEnd = NULL; - char *pRes = NULL; - int iLen, iNum, iYear; - char pNumText[10]; - CommandList *pCom = NULL; - - /* Try, get all the Variables */ - pPath = FindVariable(pSics,"sicsdatapath"); - pPref = FindVariable(pSics,"sicsdataprefix"); - pCom = FindCommand(pSics,"sicsdatanumber"); - pEnd = FindVariable(pSics,"sicsdatapostfix"); - - if( (!pPath) || (!pPref) || (!pCom) || (!pEnd) ) - { - SCWrite(pCon, - "ERROR: cannot read variables for automatic data file name creation", +char *SNXMakeFileNameOld(SicsInterp * pSics, SConnection * pCon) +{ + pSicsVariable pPath = NULL, pPref = NULL, pEnd = NULL; + char *pRes = NULL; + int iLen, iNum, iYear; + char pNumText[10]; + CommandList *pCom = NULL; + + /* Try, get all the Variables */ + pPath = FindVariable(pSics, "sicsdatapath"); + pPref = FindVariable(pSics, "sicsdataprefix"); + pCom = FindCommand(pSics, "sicsdatanumber"); + pEnd = FindVariable(pSics, "sicsdatapostfix"); + + if ((!pPath) || (!pPref) || (!pCom) || (!pEnd)) { + SCWrite(pCon, + "ERROR: cannot read variables for automatic data file name creation", eError); - SCWrite(pCon,"ERROR: This is a VERY, VERY, VERY serious installation problem", - eError); - SCWrite(pCon,"ERROR: your data will be dumped into emergency.hdf",eError); - return strdup("emergency.hdf"); - } - - /* find length */ - iLen = strlen(pPath->text); - iLen += strlen(pPref->text); - iLen += 8; /* for number + year */ - iLen += strlen(pEnd->text); - iLen += 10; /* safety margin */ - - /* allocate memory */ - pRes = (char *)malloc(iLen*sizeof(char)); - if(!pRes) - { - SCWrite(pCon,"ERROR: no memory in SNXMakeFileName",eError); - return NULL; - } - memset(pRes,0,iLen); - - /* build the filename */ - strcpy(pRes,pPath->text); - strcat(pRes,pPref->text); - iNum = IncrementDataNumber(pCom->pData,&iYear); - if(iNum < 0) - { - SCWrite(pCon,"ERROR: cannot increment data number!",eError); - SCWrite(pCon,"ERROR: your data will be dumped to emergency.hdf",eError); - free(pRes); - return strdup("emergency.hdf"); - } - sprintf(pNumText,"%5.5d",iNum); - strcat(pRes,pNumText); - sprintf(pNumText,"%4.4d",iYear); - strcat(pRes,pNumText); - strcat(pRes,pEnd->text); - - - /* install an error handler */ - NXMSetError((void *)pCon,SNError); - - return pRes; + SCWrite(pCon, + "ERROR: This is a VERY, VERY, VERY serious installation problem", + eError); + SCWrite(pCon, "ERROR: your data will be dumped into emergency.hdf", + eError); + return strdup("emergency.hdf"); } + + /* find length */ + iLen = strlen(pPath->text); + iLen += strlen(pPref->text); + iLen += 8; /* for number + year */ + iLen += strlen(pEnd->text); + iLen += 10; /* safety margin */ + + /* allocate memory */ + pRes = (char *) malloc(iLen * sizeof(char)); + if (!pRes) { + SCWrite(pCon, "ERROR: no memory in SNXMakeFileName", eError); + return NULL; + } + memset(pRes, 0, iLen); + + /* build the filename */ + strcpy(pRes, pPath->text); + strcat(pRes, pPref->text); + iNum = IncrementDataNumber(pCom->pData, &iYear); + if (iNum < 0) { + SCWrite(pCon, "ERROR: cannot increment data number!", eError); + SCWrite(pCon, "ERROR: your data will be dumped to emergency.hdf", + eError); + free(pRes); + return strdup("emergency.hdf"); + } + sprintf(pNumText, "%5.5d", iNum); + strcat(pRes, pNumText); + sprintf(pNumText, "%4.4d", iYear); + strcat(pRes, pNumText); + strcat(pRes, pEnd->text); + + + /* install an error handler */ + NXMSetError((void *) pCon, SNError); + + return pRes; +} + /*-------------------------------------------------------------------------*/ - NXhandle SNXStartFile(SConnection *pCon, SicsInterp *pSics) - { - NXhandle pFile = NULL; - char *filename = NULL; - pSicsVariable pVar = NULL; - int iStat; - char pBueffel[512], pTime[132]; - - /* get a filename */ - filename = SNXMakeFileName(pSics,pCon); - if(!filename) - { - return NULL; - } - - /* create a Nexus file */ - NXopen(filename,NXACC_CREATE,&pFile); - if(!pFile) - { - SCWrite(pCon,"ERROR: cannot create data file ",eError); - free(filename); - return NULL; - } - - /* tell Uwe User what we are doing */ - sprintf(pBueffel,"Writing %s ......",filename); - SCWrite(pCon,pBueffel,eWarning); - - /* store global attributes */ - iStat = NXputattr(pFile,"file_name",filename, - strlen(filename)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing file_name attribute to Nexus file",eError); - } +NXhandle SNXStartFile(SConnection * pCon, SicsInterp * pSics) +{ + NXhandle pFile = NULL; + char *filename = NULL; + pSicsVariable pVar = NULL; + int iStat; + char pBueffel[512], pTime[132]; - /* filename no longer needed*/ - free(filename); + /* get a filename */ + filename = SNXMakeFileName(pSics, pCon); + if (!filename) { + return NULL; + } - /* write creation time */ - SNXFormatTime(pTime,132); - iStat = NXputattr(pFile,"file_time",pTime, - strlen(pTime)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing date attribute to Nexus file",eError); - } - sprintf(pBueffel,"File created at StarDate: %s",pTime); - SCWrite(pCon,pBueffel,eWarning); + /* create a Nexus file */ + NXopen(filename, NXACC_CREATE, &pFile); + if (!pFile) { + SCWrite(pCon, "ERROR: cannot create data file ", eError); + free(filename); + return NULL; + } - pVar = FindVariable(pSics,"instrument"); - if(pVar) - { - iStat = NXputattr(pFile,"instrument",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing instrument attribute to Nexus file",eError); - } - } - pVar = NULL; - pVar = FindVariable(pSics,"user"); - if(pVar) - { - iStat = NXputattr(pFile,"owner",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner attribute to Nexus file",eError); - } - } + /* tell Uwe User what we are doing */ + sprintf(pBueffel, "Writing %s ......", filename); + SCWrite(pCon, pBueffel, eWarning); + + /* store global attributes */ + iStat = NXputattr(pFile, "file_name", filename, + strlen(filename) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing file_name attribute to Nexus file", + eError); + } + + /* filename no longer needed */ + free(filename); + + /* write creation time */ + SNXFormatTime(pTime, 132); + iStat = NXputattr(pFile, "file_time", pTime, strlen(pTime) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing date attribute to Nexus file", eError); + } + sprintf(pBueffel, "File created at StarDate: %s", pTime); + SCWrite(pCon, pBueffel, eWarning); + + pVar = FindVariable(pSics, "instrument"); + if (pVar) { + iStat = NXputattr(pFile, "instrument", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing instrument attribute to Nexus file", + eError); + } + } + pVar = NULL; + pVar = FindVariable(pSics, "user"); + if (pVar) { + iStat = NXputattr(pFile, "owner", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing owner attribute to Nexus file", + eError); + } + } + + pVar = NULL; + pVar = FindVariable(pSics, "address"); + if (pVar) { + iStat = NXputattr(pFile, "owner_adress", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing owner_adress attribute to Nexus file", + eError); + } + } + pVar = NULL; + pVar = FindVariable(pSics, "phone"); + if (pVar) { + iStat = NXputattr(pFile, "owner_telephone_number", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, + "ERROR: writing owner_telephone_number attribute to Nexus file", + eError); + } + } + pVar = NULL; + pVar = FindVariable(pSics, "fax"); + if (pVar) { + iStat = NXputattr(pFile, "owner_fax_number", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, + "ERROR: writing owner_fax_number attribute to Nexus file", + eError); + } + } + pVar = NULL; + pVar = FindVariable(pSics, "email"); + if (pVar) { + iStat = NXputattr(pFile, "owner_email", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing owner_email attribute to Nexus file", + eError); + } + } + pVar = NULL; + return pFile; +} - pVar = NULL; - pVar = FindVariable(pSics,"address"); - if(pVar) - { - iStat = NXputattr(pFile,"owner_adress",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner_adress attribute to Nexus file",eError); - } - } - pVar = NULL; - pVar = FindVariable(pSics,"phone"); - if(pVar) - { - iStat = NXputattr(pFile,"owner_telephone_number",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner_telephone_number attribute to Nexus file",eError); - } - } - pVar = NULL; - pVar = FindVariable(pSics,"fax"); - if(pVar) - { - iStat = NXputattr(pFile,"owner_fax_number",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner_fax_number attribute to Nexus file",eError); - } - } - pVar = NULL; - pVar = FindVariable(pSics,"email"); - if(pVar) - { - iStat = NXputattr(pFile,"owner_email",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner_email attribute to Nexus file",eError); - } - } - pVar = NULL; - return pFile; - } /*--------------------------------------------------------------------------*/ - int SNXStartEntry(NXhandle Nfil, int iNew, SicsInterp *pSics) - { - int iStat; - char pName[80]; - pSicsVariable pVar = NULL; - int iDim[2]; - - /* format an entry name */ - if(iNew < 10) - { - sprintf(pName,"entry%1.1d", iNew); - } - else if( (iNew > 9) && (iNew < 100) ) - { - sprintf(pName,"entry%2.2d",iNew); - } - else if( (iNew > 99) && (iNew < 1000) ) - { - sprintf(pName,"entry%3.3d",iNew); - } - else if( (iNew > 9999) && (iNew < 10000) ) - { - sprintf(pName,"entry%4.4d",iNew); - } - else - { - return 0; - } - - /* create entry and step into it */ - iStat = NXmakegroup(Nfil,pName,"NXentry"); - if(iStat == NX_ERROR) - { - return 0; - } - iStat = NXopengroup(Nfil,pName,"NXentry"); - if(iStat == NX_ERROR) - { - return 0; - } - - /* write entry level attributes here */ - pVar = FindVariable(pSics,"title"); - if(pVar) - { - iDim[0] = strlen(pVar->text) + 1; - NXmakedata(Nfil,"title",NX_CHAR,1,iDim); - NXopendata(Nfil,"title"); - NXputdata(Nfil,pVar->text); - NXclosedata(Nfil); - } - /* write time */ - SNXFormatTime(pName,79); - iDim[0] = strlen(pName) + 1; - NXmakedata(Nfil,"start_time",NX_CHAR,1,iDim); - NXopendata(Nfil,"start_time"); - NXputdata(Nfil,pName); - NXclosedata(Nfil); - - return 1; - } -/*-------------------------------------------------------------------------*/ - int SNenter(NXhandle Nfil, char *name, char *class) - { - int iStat; - - iStat = NXmakegroup(Nfil,name,class); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - iStat = NXopengroup(Nfil,name,class); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } +int SNXStartEntry(NXhandle Nfil, int iNew, SicsInterp * pSics) +{ + int iStat; + char pName[80]; + pSicsVariable pVar = NULL; + int iDim[2]; - return 1; - } -/*-------------------------------------------------------------------------*/ - int SNputdata1(NXhandle Nfil, char *name, int datatype, int iLong, - void *pData) - { - int iStat; - int iDim[2]; - - iDim[0] = iLong; - iStat = NXmakedata (Nfil, name, datatype, 1, (int *) iDim); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - iStat = NXopendata(Nfil,name); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - iStat = NXputdata(Nfil,pData); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - iStat = NXclosedata(Nfil); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - return 1; + /* format an entry name */ + if (iNew < 10) { + sprintf(pName, "entry%1.1d", iNew); + } else if ((iNew > 9) && (iNew < 100)) { + sprintf(pName, "entry%2.2d", iNew); + } else if ((iNew > 99) && (iNew < 1000)) { + sprintf(pName, "entry%3.3d", iNew); + } else if ((iNew > 9999) && (iNew < 10000)) { + sprintf(pName, "entry%4.4d", iNew); + } else { + return 0; + } - } - -/*-------------------------------------------------------------------------*/ - int SNputdata1att(NXhandle Nfil, char *name, int datatype, int iLong, - void *pData, char *attname, char *val) - { - int iStat; - int iDim[2]; - - iDim[0] = iLong; - iStat = NXmakedata (Nfil, name, datatype, 1, (int *) iDim); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - iStat = NXopendata(Nfil,name); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - iStat = NXputdata(Nfil,pData); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - iStat = NXputattr(Nfil,attname,val, - strlen(val) + 1,NX_CHAR); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - iStat = NXclosedata(Nfil); - if(iStat == NX_ERROR) - { - NXclose(&Nfil); - return 0; - } - return 1; + /* create entry and step into it */ + iStat = NXmakegroup(Nfil, pName, "NXentry"); + if (iStat == NX_ERROR) { + return 0; + } + iStat = NXopengroup(Nfil, pName, "NXentry"); + if (iStat == NX_ERROR) { + return 0; + } + + /* write entry level attributes here */ + pVar = FindVariable(pSics, "title"); + if (pVar) { + iDim[0] = strlen(pVar->text) + 1; + NXmakedata(Nfil, "title", NX_CHAR, 1, iDim); + NXopendata(Nfil, "title"); + NXputdata(Nfil, pVar->text); + NXclosedata(Nfil); + } + /* write time */ + SNXFormatTime(pName, 79); + iDim[0] = strlen(pName) + 1; + NXmakedata(Nfil, "start_time", NX_CHAR, 1, iDim); + NXopendata(Nfil, "start_time"); + NXputdata(Nfil, pName); + NXclosedata(Nfil); + + return 1; +} + +/*-------------------------------------------------------------------------*/ +int SNenter(NXhandle Nfil, char *name, char *class) +{ + int iStat; + + iStat = NXmakegroup(Nfil, name, class); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + iStat = NXopengroup(Nfil, name, class); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + + return 1; +} + +/*-------------------------------------------------------------------------*/ +int SNputdata1(NXhandle Nfil, char *name, int datatype, int iLong, + void *pData) +{ + int iStat; + int iDim[2]; + + iDim[0] = iLong; + iStat = NXmakedata(Nfil, name, datatype, 1, (int *) iDim); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + iStat = NXopendata(Nfil, name); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + iStat = NXputdata(Nfil, pData); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + iStat = NXclosedata(Nfil); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + return 1; + +} + +/*-------------------------------------------------------------------------*/ +int SNputdata1att(NXhandle Nfil, char *name, int datatype, int iLong, + void *pData, char *attname, char *val) +{ + int iStat; + int iDim[2]; + + iDim[0] = iLong; + iStat = NXmakedata(Nfil, name, datatype, 1, (int *) iDim); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + iStat = NXopendata(Nfil, name); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + iStat = NXputdata(Nfil, pData); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + iStat = NXputattr(Nfil, attname, val, strlen(val) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + iStat = NXclosedata(Nfil); + if (iStat == NX_ERROR) { + NXclose(&Nfil); + return 0; + } + return 1; + +} - } /*-----------------------------------------------------------------------*/ - static int SNPutMotor(NXhandle hfil, SicsInterp *pSics, - SConnection *pCon,char *sicsname, - char *dataname, char *units) - { - float fVal; - char pBueffel[512]; - int iRet; - pMotor pMot; +static int SNPutMotor(NXhandle hfil, SicsInterp * pSics, + SConnection * pCon, char *sicsname, + char *dataname, char *units) +{ + float fVal; + char pBueffel[512]; + int iRet; + pMotor pMot; - pMot = FindMotor(pSics,sicsname); - if(!pMot) - { - sprintf(pBueffel,"ERROR: motor %s not found ", sicsname); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = MotorGetSoftPosition(pMot,pCon,&fVal); - if(iRet != 1) - { - sprintf(pBueffel,"ERROR: cannot read motor %s", sicsname); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return SNputdata1att(hfil,dataname, NX_FLOAT32,1,&fVal,"Units",units); + pMot = FindMotor(pSics, sicsname); + if (!pMot) { + sprintf(pBueffel, "ERROR: motor %s not found ", sicsname); + SCWrite(pCon, pBueffel, eError); + return 0; } + iRet = MotorGetSoftPosition(pMot, pCon, &fVal); + if (iRet != 1) { + sprintf(pBueffel, "ERROR: cannot read motor %s", sicsname); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return SNputdata1att(hfil, dataname, NX_FLOAT32, 1, &fVal, "Units", + units); +} + #ifdef NONINTF - extern float nintf(float f); -#endif +extern float nintf(float f); +#endif /*--------------------------------------------------------------------------*/ - int SNMakeDMC(SConnection *pCon, SicsInterp *pSics) +int SNMakeDMC(SConnection * pCon, SicsInterp * pSics) +{ + NXhandle Nfil; + NXlink lWave, lDetData, lStart, lTemp, lMoni, lStep, lNumber, + lTheta, lSetData; + int iDim[2]; + float fEnd, fStart, fStep; + int iStat; + pSicsVariable pVar; + pSicsSelector pSel = NULL; + pICountable pCountInt; + pIDrivable pDrive = NULL; + pSelVar pPell; + char *pP; + float fVal; + float *fTheta; + float fTh, f2Th, fB1, fB2; + pMotor pMot = NULL; + CommandList *pCom = NULL; + int iVal, i; + char pBuffer[132]; + pHistMem pHist = NULL; + HistInt *lData = NULL; + CounterMode eCount; + int *iTVal = NULL; + pDummy pDum; + int bHRPT = 0; + float fMean, fStdDev; + pVarLog pLog = NULL; + + /* open the file & entry */ + Nfil = SNXStartFile(pCon, pSics); + if (!Nfil) { + return 0; + } + + iStat = SNXStartEntry(Nfil, 1, pSics); + if (!iStat) { + NXclose(&Nfil); + return 0; + } + + /* create the instrument Vgroup */ + pVar = FindVariable(pSics, "instrument"); + if (strcmp(pVar->text, "HRPT") == 0) { + bHRPT = 1; + } + assert(pVar); + iStat = SNenter(Nfil, pVar->text, "NXpsdpowder"); + if (!iStat) { + return 0; + } + /* write the Kollimator for HRPT */ + if (bHRPT) { + iStat = SNenter(Nfil, "kollimator", "NXkollimator"); + if (!iStat) { + return 0; + } + pMot = FindMotor(pSics, "CEX1"); + if (pMot) { + iStat = MotorGetSoftPosition(pMot, pCon, &fStart); + iStat = SNputdata1att(Nfil, "kollimator1", NX_FLOAT32, 1, + &fStart, "Units", "degrees"); + } + pMot = FindMotor(pSics, "CEX2"); + if (pMot) { + iStat = MotorGetSoftPosition(pMot, pCon, &fStart); + iStat = SNputdata1att(Nfil, "kollimator2", NX_FLOAT32, 1, + &fStart, "Units", "degrees"); + } + NXclosegroup(Nfil); /* leave kollimator */ + } + + /* write the Monochromator data */ + iStat = SNenter(Nfil, "Monochromator", "NXcrystal"); + if (!iStat) { + return 0; + } + if (bHRPT) { + pVar = FindVariable(pSics, "lambda"); + if (pVar) { + VarGetFloat(pVar, &fVal); + SNputdata1att(Nfil, "lambda", NX_FLOAT32, 1, &fVal, + "Units", "Angstroem"); + NXopendata(Nfil, "lambda"); + NXgetdataID(Nfil, &lWave); + NXclosedata(Nfil); + } + pVar = FindVariable(pSics, "monotype"); + if (pVar) { + iStat = SNputdata1(Nfil, "type", NX_CHAR, strlen(pVar->text), + pVar->text); + } + /* write tons of motors for the monochromator */ + SNPutMotor(Nfil, pSics, pCon, "momu", "omega_upper", "degree"); + SNPutMotor(Nfil, pSics, pCon, "mtvu", + "vertical_translation_upper", "mm"); + SNPutMotor(Nfil, pSics, pCon, "mtpu", + "paralell_translation_upper", "mm"); + SNPutMotor(Nfil, pSics, pCon, "mgvu", "vertical_tilt_upper", "degree"); + SNPutMotor(Nfil, pSics, pCon, "mgpu", "parallel_tilt_upper", "degree"); + SNPutMotor(Nfil, pSics, pCon, "mcvu", "curvature_upper", ""); + SNPutMotor(Nfil, pSics, pCon, "moml", "omega_lower", "degree"); + SNPutMotor(Nfil, pSics, pCon, "mtvl", + "vertical_translation_lower", "mm"); + SNPutMotor(Nfil, pSics, pCon, "mtpl", + "parallel_translation_lower", "degree"); + SNPutMotor(Nfil, pSics, pCon, "mgvl", "vertical_tilt_lower", "degree"); + SNPutMotor(Nfil, pSics, pCon, "mgpl", "parallel_tilt_lower", "degree"); + SNPutMotor(Nfil, pSics, pCon, "mcvl", "curvature_lower", "degree"); + SNPutMotor(Nfil, pSics, pCon, "mexz", "lift", "mm"); + } else { + pCom = FindCommand(pSics, "mono"); + assert(pCom); + pSel = (pSicsSelector) pCom->pData; + pP = MonoGetType(pSel); + iStat = SNputdata1(Nfil, "type", NX_CHAR, strlen(pP), pP); + if (!iStat) { + return 0; + } + pCom = NULL; + pCom = FindCommand(pSics, "lambda"); + assert(pCom); + pPell = (pSelVar) pCom->pData; + assert(iHasType(pPell, "SicsSelVar")); + fVal = GetSelValue(pPell, pCon); + iStat = SNputdata1(Nfil, "lambda", NX_FLOAT32, 1, &fVal); + if (!iStat) { + return 0; + } + NXopendata(Nfil, "lambda"); + NXputattr(Nfil, "Units", "Angstroem", 10, NX_CHAR); + NXgetdataID(Nfil, &lWave); + NXclosedata(Nfil); + iStat = GetMonoPositions(pSel, pCon, &fTh, &f2Th, &fB1, &fB2); + if (iStat) + /* skip if not readable, error has been reported lower down */ + { + SNputdata1att(Nfil, "theta", NX_FLOAT32, 1, &fTh, + "Units", "degrees"); + SNputdata1att(Nfil, "two_theta", NX_FLOAT32, 1, &f2Th, + "Units", "degrees"); + SNputdata1att(Nfil, "curvature", NX_FLOAT32, 1, &fB1, "Units", "mm"); + } + /* more monochromatic motors */ + SNPutMotor(Nfil, pSics, pCon, "monox", "x_translation", "mm"); + SNPutMotor(Nfil, pSics, pCon, "monoy", "y_translation", "mm"); + SNPutMotor(Nfil, pSics, pCon, "monophi", "phi", "degree"); + SNPutMotor(Nfil, pSics, pCon, "monochi", "chi", "degree"); + } + NXclosegroup(Nfil); /* leave monochromator */ + + /* start Detector vGroup */ + if (bHRPT) { + iStat = SNenter(Nfil, HRPTDETNAM, "NXpsd"); + } else { + iStat = SNenter(Nfil, DMCDETNAM, "NXpsd"); + } + /* get the histogram memory object */ + pCom = FindCommand(pSics, "banana"); + assert(pCom); + pHist = pCom->pData; + assert(pHist); + + /* counter mode */ + eCount = GetHistCountMode(pHist); + if (eCount == eTimer) { + strcpy(pBuffer, "Timer"); + } else { + strcpy(pBuffer, "Monitor"); + } + iStat = + SNputdata1(Nfil, "CounterMode", NX_CHAR, strlen(pBuffer), pBuffer); + if (!iStat) { + return 0; + } + + /* count preset */ + fVal = GetHistPreset(pHist); + if (eCount == eTimer) { + iStat = SNputdata1(Nfil, "Preset", NX_FLOAT32, 1, &fVal); + } else { + fVal = nintf(fVal); + iStat = SNputdata1(Nfil, "Preset", NX_FLOAT32, 1, &fVal); + } + if (!iStat) { + return 0; + } + + /* monitor value */ + pDum = (pDummy) pHist; + pCountInt = pDum->pDescriptor->GetInterface(pDum, COUNTID); { - NXhandle Nfil; - NXlink lWave, lDetData, lStart, lTemp, lMoni, lStep, lNumber, - lTheta, lSetData; - int iDim[2]; - float fEnd,fStart, fStep; - int iStat; - pSicsVariable pVar; - pSicsSelector pSel = NULL; - pICountable pCountInt; - pIDrivable pDrive = NULL; - pSelVar pPell; - char *pP; - float fVal; - float *fTheta; - float fTh, f2Th, fB1, fB2; - pMotor pMot = NULL; - CommandList *pCom = NULL; - int iVal, i; - char pBuffer[132]; - pHistMem pHist = NULL; - HistInt *lData = NULL; - CounterMode eCount; - int *iTVal = NULL; - pDummy pDum; - int bHRPT = 0; - float fMean, fStdDev; - pVarLog pLog = NULL; + pCountInt->TransferData(pHist, pCon); + } + iVal = GetHistMonitor(pHist, 1, pCon); + if (iVal < 0) { + return 0; + } + iStat = SNputdata1(Nfil, "Monitor", NX_INT32, 1, &iVal); + /* + count time + */ + fVal = GetHistCountTime(pHist, pCon); + SNputdata1att(Nfil, "time", NX_FLOAT32, 1, &fVal, "Units", "seconds"); - /* open the file & entry */ - Nfil = SNXStartFile(pCon,pSics); - if(!Nfil) - { - return 0; - } - - iStat = SNXStartEntry(Nfil,1,pSics); - if(!iStat) - { - NXclose(&Nfil); - return 0; - } - - /* create the instrument Vgroup */ - pVar = FindVariable(pSics,"instrument"); - if(strcmp(pVar->text,"HRPT") == 0) - { - bHRPT = 1; - } - assert(pVar); - iStat = SNenter(Nfil,pVar->text,"NXpsdpowder"); - if(!iStat) - { - return 0; - } - /* write the Kollimator for HRPT */ - if(bHRPT) - { - iStat = SNenter(Nfil,"kollimator","NXkollimator"); - if(!iStat) - { - return 0; - } - pMot = FindMotor(pSics,"CEX1"); - if(pMot) - { - iStat = MotorGetSoftPosition(pMot,pCon,&fStart); - iStat = SNputdata1att(Nfil,"kollimator1",NX_FLOAT32,1, - &fStart,"Units","degrees"); - } - pMot = FindMotor(pSics,"CEX2"); - if(pMot) - { - iStat = MotorGetSoftPosition(pMot,pCon,&fStart); - iStat = SNputdata1att(Nfil,"kollimator2",NX_FLOAT32,1, - &fStart,"Units","degrees"); - } - NXclosegroup(Nfil); /* leave kollimator */ - } + /* + more monitors + */ + iVal = GetHistMonitor(pHist, 0, pCon); + SNputdata1(Nfil, "beam_monitor", NX_INT32, 1, &iVal); + iVal = GetHistMonitor(pHist, 4, pCon); + SNputdata1(Nfil, "proton_monitor", NX_INT32, 1, &iVal); + NXopendata(Nfil, "Monitor"); + NXgetdataID(Nfil, &lMoni); + NXclosedata(Nfil); - /* write the Monochromator data */ - iStat = SNenter(Nfil,"Monochromator","NXcrystal"); - if(!iStat) - { - return 0; - } - if(bHRPT) - { - pVar = FindVariable(pSics,"lambda"); - if(pVar) - { - VarGetFloat(pVar,&fVal); - SNputdata1att(Nfil,"lambda",NX_FLOAT32,1,&fVal, - "Units","Angstroem"); - NXopendata(Nfil,"lambda"); - NXgetdataID(Nfil,&lWave); - NXclosedata(Nfil); - } - pVar = FindVariable(pSics,"monotype"); - if(pVar) - { - iStat = SNputdata1(Nfil,"type",NX_CHAR,strlen(pVar->text), - pVar->text); - } - /* write tons of motors for the monochromator */ - SNPutMotor(Nfil,pSics,pCon,"momu", - "omega_upper","degree"); - SNPutMotor(Nfil,pSics,pCon,"mtvu", - "vertical_translation_upper","mm"); - SNPutMotor(Nfil,pSics,pCon,"mtpu", - "paralell_translation_upper","mm"); - SNPutMotor(Nfil,pSics,pCon,"mgvu", - "vertical_tilt_upper","degree"); - SNPutMotor(Nfil,pSics,pCon,"mgpu", - "parallel_tilt_upper","degree"); - SNPutMotor(Nfil,pSics,pCon,"mcvu", - "curvature_upper",""); - SNPutMotor(Nfil,pSics,pCon,"moml", - "omega_lower","degree"); - SNPutMotor(Nfil,pSics,pCon,"mtvl", - "vertical_translation_lower","mm"); - SNPutMotor(Nfil,pSics,pCon,"mtpl", - "parallel_translation_lower","degree"); - SNPutMotor(Nfil,pSics,pCon,"mgvl", - "vertical_tilt_lower","degree"); - SNPutMotor(Nfil,pSics,pCon,"mgpl", - "parallel_tilt_lower","degree"); - SNPutMotor(Nfil,pSics,pCon,"mcvl", - "curvature_lower","degree"); - SNPutMotor(Nfil,pSics,pCon,"mexz", - "lift","mm"); - } - else - { - pCom = FindCommand(pSics,"mono"); - assert(pCom); - pSel = (pSicsSelector)pCom->pData; - pP = MonoGetType(pSel); - iStat = SNputdata1(Nfil,"type",NX_CHAR,strlen(pP), pP); - if(!iStat) - { - return 0; - } - pCom = NULL; - pCom = FindCommand(pSics,"lambda"); - assert(pCom); - pPell = (pSelVar)pCom->pData; - assert(iHasType(pPell,"SicsSelVar")); - fVal = GetSelValue(pPell,pCon); - iStat = SNputdata1(Nfil,"lambda",NX_FLOAT32,1,&fVal); - if(!iStat) - { - return 0; - } - NXopendata(Nfil,"lambda"); - NXputattr(Nfil,"Units","Angstroem",10,NX_CHAR); - NXgetdataID(Nfil,&lWave); - NXclosedata(Nfil); - iStat = GetMonoPositions(pSel,pCon,&fTh,&f2Th, &fB1, &fB2); - if(iStat) - /* skip if not readable, error has been reported lower down */ - { - SNputdata1att(Nfil,"theta",NX_FLOAT32,1,&fTh, - "Units","degrees"); - SNputdata1att(Nfil,"two_theta",NX_FLOAT32, 1,&f2Th, - "Units","degrees"); - SNputdata1att(Nfil,"curvature",NX_FLOAT32, 1,&fB1, - "Units","mm"); - } - /* more monochromatic motors */ - SNPutMotor(Nfil,pSics,pCon,"monox", - "x_translation","mm"); - SNPutMotor(Nfil,pSics,pCon,"monoy", - "y_translation","mm"); - SNPutMotor(Nfil,pSics,pCon,"monophi", - "phi","degree"); - SNPutMotor(Nfil,pSics,pCon,"monochi", - "chi","degree"); - } - NXclosegroup(Nfil); /* leave monochromator */ - - /* start Detector vGroup */ - if(bHRPT) - { - iStat = SNenter(Nfil,HRPTDETNAM,"NXpsd"); - } - else - { - iStat = SNenter(Nfil,DMCDETNAM,"NXpsd"); - } - /* get the histogram memory object */ - pCom = FindCommand(pSics,"banana"); - assert(pCom); - pHist = pCom->pData; - assert(pHist); - - /* counter mode */ - eCount = GetHistCountMode(pHist); - if(eCount == eTimer) - { - strcpy(pBuffer,"Timer"); - } - else - { - strcpy(pBuffer,"Monitor"); - } - iStat = SNputdata1(Nfil,"CounterMode",NX_CHAR,strlen(pBuffer), pBuffer); - if(!iStat) - { - return 0; - } - - /* count preset */ - fVal = GetHistPreset(pHist); - if(eCount == eTimer) - { - iStat = SNputdata1(Nfil,"Preset",NX_FLOAT32,1, &fVal); - } - else - { - fVal = nintf(fVal); - iStat = SNputdata1(Nfil,"Preset",NX_FLOAT32,1, &fVal); - } - if(!iStat) - { - return 0; - } - /* monitor value */ - pDum = (pDummy)pHist; - pCountInt = pDum->pDescriptor->GetInterface(pDum,COUNTID); - { - pCountInt->TransferData(pHist,pCon); - } - iVal = GetHistMonitor(pHist, 1, pCon); - if(iVal < 0) - { - return 0; - } - iStat = SNputdata1(Nfil,"Monitor",NX_INT32,1, &iVal); - /* - count time - */ - fVal = GetHistCountTime(pHist,pCon); - SNputdata1att(Nfil,"time",NX_FLOAT32,1,&fVal,"Units","seconds"); + /* stepwidth */ + pVar = FindVariable(pSics, "detstepwidth"); + if (!pVar) { + return 0; + } + fVal = pVar->fVal; + iStat = SNputdata1(Nfil, "Step", NX_FLOAT32, 1, &fVal); + if (!iStat) { + return 0; + } + NXopendata(Nfil, "Step"); + NXgetdataID(Nfil, &lStep); + NXclosedata(Nfil); - /* - more monitors - */ - iVal = GetHistMonitor(pHist, 0, pCon); - SNputdata1(Nfil,"beam_monitor",NX_INT32,1, &iVal); - iVal = GetHistMonitor(pHist, 4, pCon); - SNputdata1(Nfil,"proton_monitor",NX_INT32,1, &iVal); - NXopendata(Nfil,"Monitor"); - NXgetdataID(Nfil,&lMoni); - NXclosedata(Nfil); - - - /* stepwidth */ - pVar = FindVariable(pSics,"detstepwidth"); - if(!pVar) - { - return 0; - } - fVal = pVar->fVal; - iStat = SNputdata1(Nfil,"Step",NX_FLOAT32,1, &fVal); - if(!iStat) - { - return 0; - } - NXopendata(Nfil,"Step"); - NXgetdataID(Nfil,&lStep); - NXclosedata(Nfil); - - /* histogram Length */ - GetHistDim(pHist,iDim,&iVal); - iVal = iDim[0]; - if(iVal < 1) - { - return 0; - } - iStat = SNputdata1(Nfil,"no_of_steps",NX_INT32,1, &iVal); - if(iStat < 1) - { - return 0; - } - NXopendata(Nfil,"no_of_steps"); - NXgetdataID(Nfil,&lNumber); - NXclosedata(Nfil); + /* histogram Length */ + GetHistDim(pHist, iDim, &iVal); + iVal = iDim[0]; + if (iVal < 1) { + return 0; + } + iStat = SNputdata1(Nfil, "no_of_steps", NX_INT32, 1, &iVal); + if (iStat < 1) { + return 0; + } + NXopendata(Nfil, "no_of_steps"); + NXgetdataID(Nfil, &lNumber); + NXclosedata(Nfil); - /* actual data */ - lData = (HistInt *)malloc(iVal*sizeof(HistInt)); - if(!lData) - { - return 0; - } - iStat = GetHistogram(pHist,pCon,0,0,iVal,lData,iVal*sizeof(HistInt)); - if(!iStat) - { - return 0; - } - iStat = SNputdata1(Nfil,"Counts",NX_INT32,iVal, lData); - if(!iStat) - { - return 0; - } - free(lData); - NXopendata(Nfil,"Counts"); - NXgetdataID(Nfil,&lSetData); - strcpy(pBuffer,"1"); - NXputattr(Nfil,"signal",pBuffer,strlen(pBuffer)+1,NX_CHAR); - NXclosedata(Nfil); - - /* motor position */ - pMot = FindMotor(pSics,"a4"); - assert(pMot); - iStat = MotorGetSoftPosition(pMot,pCon,&fStart); - iStat = SNputdata1att(Nfil,"two_theta_start",NX_FLOAT32,1, - &fStart,"Units","degrees"); - if(!iStat) - { - return 0; - } - - /* create 2Theta array and store it */ - fTheta = NULL; - fTheta = (float *)malloc(iVal*sizeof(NX_FLOAT32)); - if(!fTheta) - { - return 0; - } - for(i = 0; i < iVal; i++) - { - fTheta[i] = fStart + i*fVal; - } - iStat = SNputdata1att(Nfil,"two_theta",NX_FLOAT32,iVal, - fTheta,"Units","degrees"); - if(!iStat) - { - return 0; - } - /* get link, put axis attribute */ - NXopendata(Nfil,"two_theta"); - NXputattr(Nfil,"axis","1",strlen("1")+1,NX_CHAR); - NXgetdataID(Nfil,&lTheta); - NXclosedata(Nfil); - free(fTheta); - - - NXopendata(Nfil,"two_theta_start"); - NXgetdataID(Nfil,&lStart); - NXclosedata(Nfil); - NXclosegroup(Nfil); /* detector Vgroup */ - NXclosegroup(Nfil); /* instrument Vgroup */ + /* actual data */ + lData = (HistInt *) malloc(iVal * sizeof(HistInt)); + if (!lData) { + return 0; + } + iStat = + GetHistogram(pHist, pCon, 0, 0, iVal, lData, iVal * sizeof(HistInt)); + if (!iStat) { + return 0; + } + iStat = SNputdata1(Nfil, "Counts", NX_INT32, iVal, lData); + if (!iStat) { + return 0; + } + free(lData); + NXopendata(Nfil, "Counts"); + NXgetdataID(Nfil, &lSetData); + strcpy(pBuffer, "1"); + NXputattr(Nfil, "signal", pBuffer, strlen(pBuffer) + 1, NX_CHAR); + NXclosedata(Nfil); - /* do the sample Vgroup */ - iStat = SNenter(Nfil,"Sample","NXpowder"); - if(!iStat) - { - return 0; - } - pVar = FindVariable(pSics,"sample"); - if(pVar) - { - iDim[0] = strlen(pVar->text) + 1; - NXmakedata(Nfil,"sample_name",NX_CHAR,1,iDim); - NXopendata(Nfil,"sample_name"); - NXputdata(Nfil,pVar->text); - NXclosedata(Nfil); - } - pVar = FindVariable(pSics,"sample_mur"); - if(pVar) - { - SNputdata1att(Nfil,"sample_mur",NX_FLOAT32, 1,&pVar->fVal, - "Units","???"); - } - /* do a3 */ - SNPutMotor(Nfil,pSics,pCon,"a3", - "sample_table_rotation","degree"); - - /* write sample environment here */ - pCom = FindCommand(pSics,"temperature"); - if(pCom) - { - pDum = (pDummy)pCom->pData; - pDrive = pDum->pDescriptor->GetInterface(pDum,DRIVEID); - if(pDrive) /* a proper environment device */ - { - pLog = EVCGetVarLog( (pEVControl)pCom->pData); - if(pLog) - { - VarlogGetMean(pLog,&fMean,&fStdDev); - SNputdata1att(Nfil,"temperature_mean",NX_FLOAT32, 1,&fMean, - "Units","K"); - SNputdata1att(Nfil,"temperature_stddev",NX_FLOAT32, 1, - &fStdDev,"Units","K"); - } - fVal = pDrive->GetValue(pCom->pData,pCon); - } - else /* a simple variable */ - { - VarGetFloat((pSicsVariable)pDum,&fVal); - } - SNputdata1att(Nfil,"sample_temperature",NX_FLOAT32, 1,&fVal, - "Units","K"); - } - NXclosegroup(Nfil); /* sample Vgroup */ - - /* write the data Vgroup */ - SNenter(Nfil,"data1","NXdata"); - NXmakelink(Nfil,&lWave); - NXmakelink(Nfil,&lTheta); - NXmakelink(Nfil,&lStart); - NXmakelink(Nfil,&lSetData); - NXmakelink(Nfil,&lMoni); - NXmakelink(Nfil,&lStep); - NXmakelink(Nfil,&lNumber); - - /* send quieck message */ - i = 131; - iVal = NX_CHAR; - NXgetattr(Nfil,"file_name",pBuffer,&i,&iVal); - SendQuieck(QUIECK,pBuffer); - - /* done */ - NXclose(&Nfil); - return 1; - } + /* motor position */ + pMot = FindMotor(pSics, "a4"); + assert(pMot); + iStat = MotorGetSoftPosition(pMot, pCon, &fStart); + iStat = SNputdata1att(Nfil, "two_theta_start", NX_FLOAT32, 1, + &fStart, "Units", "degrees"); + if (!iStat) { + return 0; + } + + /* create 2Theta array and store it */ + fTheta = NULL; + fTheta = (float *) malloc(iVal * sizeof(NX_FLOAT32)); + if (!fTheta) { + return 0; + } + for (i = 0; i < iVal; i++) { + fTheta[i] = fStart + i * fVal; + } + iStat = SNputdata1att(Nfil, "two_theta", NX_FLOAT32, iVal, + fTheta, "Units", "degrees"); + if (!iStat) { + return 0; + } + /* get link, put axis attribute */ + NXopendata(Nfil, "two_theta"); + NXputattr(Nfil, "axis", "1", strlen("1") + 1, NX_CHAR); + NXgetdataID(Nfil, &lTheta); + NXclosedata(Nfil); + free(fTheta); + + + NXopendata(Nfil, "two_theta_start"); + NXgetdataID(Nfil, &lStart); + NXclosedata(Nfil); + NXclosegroup(Nfil); /* detector Vgroup */ + NXclosegroup(Nfil); /* instrument Vgroup */ + + /* do the sample Vgroup */ + iStat = SNenter(Nfil, "Sample", "NXpowder"); + if (!iStat) { + return 0; + } + pVar = FindVariable(pSics, "sample"); + if (pVar) { + iDim[0] = strlen(pVar->text) + 1; + NXmakedata(Nfil, "sample_name", NX_CHAR, 1, iDim); + NXopendata(Nfil, "sample_name"); + NXputdata(Nfil, pVar->text); + NXclosedata(Nfil); + } + pVar = FindVariable(pSics, "sample_mur"); + if (pVar) { + SNputdata1att(Nfil, "sample_mur", NX_FLOAT32, 1, &pVar->fVal, + "Units", "???"); + } + /* do a3 */ + SNPutMotor(Nfil, pSics, pCon, "a3", "sample_table_rotation", "degree"); + + /* write sample environment here */ + pCom = FindCommand(pSics, "temperature"); + if (pCom) { + pDum = (pDummy) pCom->pData; + pDrive = pDum->pDescriptor->GetInterface(pDum, DRIVEID); + if (pDrive) { /* a proper environment device */ + pLog = EVCGetVarLog((pEVControl) pCom->pData); + if (pLog) { + VarlogGetMean(pLog, &fMean, &fStdDev); + SNputdata1att(Nfil, "temperature_mean", NX_FLOAT32, 1, &fMean, + "Units", "K"); + SNputdata1att(Nfil, "temperature_stddev", NX_FLOAT32, 1, + &fStdDev, "Units", "K"); + } + fVal = pDrive->GetValue(pCom->pData, pCon); + } else { /* a simple variable */ + + VarGetFloat((pSicsVariable) pDum, &fVal); + } + SNputdata1att(Nfil, "sample_temperature", NX_FLOAT32, 1, &fVal, + "Units", "K"); + } + NXclosegroup(Nfil); /* sample Vgroup */ + + /* write the data Vgroup */ + SNenter(Nfil, "data1", "NXdata"); + NXmakelink(Nfil, &lWave); + NXmakelink(Nfil, &lTheta); + NXmakelink(Nfil, &lStart); + NXmakelink(Nfil, &lSetData); + NXmakelink(Nfil, &lMoni); + NXmakelink(Nfil, &lStep); + NXmakelink(Nfil, &lNumber); + + /* send quieck message */ + i = 131; + iVal = NX_CHAR; + NXgetattr(Nfil, "file_name", pBuffer, &i, &iVal); + SendQuieck(QUIECK, pBuffer); + + /* done */ + NXclose(&Nfil); + return 1; +} /*--------------------------------------------------------------------------*/ - int SNStoreDMC(SConnection *pCon, SicsInterp *pSics, void *pData, int argc, - char *argv[]) - - { - return SNMakeDMC(pCon,pSics); - } +int SNStoreDMC(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + return SNMakeDMC(pCon, pSics); +} diff --git a/nxdata.h b/nxdata.h index c3ecae95..2f34f1bf 100644 --- a/nxdata.h +++ b/nxdata.h @@ -11,20 +11,19 @@ #ifndef SICSNXDATA #define SICSNXDATA - char *SNXMakeFileName(SicsInterp *pSics, SConnection *pCon); +char *SNXMakeFileName(SicsInterp * pSics, SConnection * pCon); - NXhandle SNXStartFile(SConnection *pCon, SicsInterp *pSics); +NXhandle SNXStartFile(SConnection * pCon, SicsInterp * pSics); - int SNXStartEntry(NXhandle Nfil, int iNew, SicsInterp *pSics); +int SNXStartEntry(NXhandle Nfil, int iNew, SicsInterp * pSics); - void SNXFormatTime(char *pBuffer, int iBufLen); +void SNXFormatTime(char *pBuffer, int iBufLen); - int SNFinishFile(NXhandle Nfil); +int SNFinishFile(NXhandle Nfil); - int SNMakeDMC(SConnection *pCon, SicsInterp *pSics); +int SNMakeDMC(SConnection * pCon, SicsInterp * pSics); -int SNStoreDMC(SConnection *pCon, SicsInterp *pSics, void *pData, int argc, - char *argv[]); - -#endif +int SNStoreDMC(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +#endif diff --git a/nxdataset.c b/nxdataset.c index 6d419196..25034bc6 100644 --- a/nxdataset.c +++ b/nxdataset.c @@ -12,8 +12,9 @@ #include "nxdataset.h" /*-----------------------------------------------------------------------*/ -static int getTypeSize(int typecode){ - switch(typecode){ +static int getTypeSize(int typecode) +{ + switch (typecode) { case NX_FLOAT32: case NX_INT32: case NX_UINT32: @@ -33,47 +34,51 @@ static int getTypeSize(int typecode){ break; } } + /*-----------------------------------------------------------------------*/ -pNXDS createNXDataset(int rank, int typecode, int dim[]){ +pNXDS createNXDataset(int rank, int typecode, int dim[]) +{ pNXDS pNew = NULL; int i, length; - pNew = (pNXDS)malloc(sizeof(NXDS)); - if(pNew == NULL){ + pNew = (pNXDS) malloc(sizeof(NXDS)); + if (pNew == NULL) { return NULL; } - pNew->dim = (int *)malloc(rank*sizeof(int)); - for(i = 0, length = 1; i < rank; i++){ + pNew->dim = (int *) malloc(rank * sizeof(int)); + for (i = 0, length = 1; i < rank; i++) { length *= dim[i]; } - pNew->u.ptr = malloc(length*getTypeSize(typecode)); + pNew->u.ptr = malloc(length * getTypeSize(typecode)); - if(pNew->dim == NULL || pNew->u.ptr == NULL){ + if (pNew->dim == NULL || pNew->u.ptr == NULL) { free(pNew); return NULL; } pNew->rank = rank; pNew->type = typecode; pNew->format = NULL; - for(i = 0; i < rank; i++){ + for (i = 0; i < rank; i++) { pNew->dim[i] = dim[i]; } pNew->magic = MAGIC; - memset(pNew->u.ptr,0,length*getTypeSize(typecode)); + memset(pNew->u.ptr, 0, length * getTypeSize(typecode)); return pNew; } + /*---------------------------------------------------------------------*/ -pNXDS createTextNXDataset(char *name){ +pNXDS createTextNXDataset(char *name) +{ pNXDS pNew = NULL; - pNew = (pNXDS)malloc(sizeof(NXDS)); - if(pNew == NULL){ + pNew = (pNXDS) malloc(sizeof(NXDS)); + if (pNew == NULL) { return NULL; } - pNew->dim = (int *)malloc(sizeof(int)); + pNew->dim = (int *) malloc(sizeof(int)); pNew->u.cPtr = strdup(name); - if(pNew->dim == NULL || pNew->u.ptr == NULL){ + if (pNew->dim == NULL || pNew->u.ptr == NULL) { free(pNew); return NULL; } @@ -83,364 +88,395 @@ pNXDS createTextNXDataset(char *name){ pNew->dim[0] = strlen(name); return pNew; } + /*-----------------------------------------------------------------------*/ -void dropNXDataset(pNXDS dataset){ - if(dataset == NULL){ +void dropNXDataset(pNXDS dataset) +{ + if (dataset == NULL) { return; } - if(dataset->magic != MAGIC){ + if (dataset->magic != MAGIC) { return; } - if(dataset->dim != NULL){ + if (dataset->dim != NULL) { free(dataset->dim); } - if(dataset->u.ptr != NULL){ + if (dataset->u.ptr != NULL) { free(dataset->u.ptr); } - if(dataset->format != NULL){ + if (dataset->format != NULL) { free(dataset->format); } free(dataset); } + /*-----------------------------------------------------------------------*/ -int getNXDatasetRank(pNXDS dataset){ - if(dataset == NULL){ +int getNXDatasetRank(pNXDS dataset) +{ + if (dataset == NULL) { return 0; } - if(dataset->magic != MAGIC){ + if (dataset->magic != MAGIC) { return 0; } return dataset->rank; } + /*-----------------------------------------------------------------------*/ -int getNXDatasetDim(pNXDS dataset, int which){ - if(dataset == NULL){ +int getNXDatasetDim(pNXDS dataset, int which) +{ + if (dataset == NULL) { return 0; } - if(dataset->magic != MAGIC){ + if (dataset->magic != MAGIC) { return 0; } - if(which < 0 || which >= dataset->rank){ + if (which < 0 || which >= dataset->rank) { return 0; } return dataset->dim[which]; } + /*------------------------------------------------------------------------*/ -int getNXDatasetType(pNXDS dataset){ - if(dataset == NULL){ +int getNXDatasetType(pNXDS dataset) +{ + if (dataset == NULL) { return 0; } - if(dataset->magic != MAGIC){ + if (dataset->magic != MAGIC) { return 0; } return dataset->type; } + /*--------------------------------------------------------------------*/ -int getNXDatasetLength(pNXDS dataset){ +int getNXDatasetLength(pNXDS dataset) +{ int length, i; - if(dataset == NULL){ + if (dataset == NULL) { return 0; } - if(dataset->magic != MAGIC){ + if (dataset->magic != MAGIC) { return 0; } length = dataset->dim[0]; - for(i = 1; i < dataset->rank; i++){ + for (i = 1; i < dataset->rank; i++) { length *= dataset->dim[i]; } return length; } + /*---------------------------------------------------------------------*/ -int getNXDatasetByteLength(pNXDS dataset){ - return getNXDatasetLength(dataset)*getTypeSize(dataset->type); +int getNXDatasetByteLength(pNXDS dataset) +{ + return getNXDatasetLength(dataset) * getTypeSize(dataset->type); } + /*---------------------------------------------------------------------- This calculates an arbitray address in C storage order -----------------------------------------------------------------------*/ -static int calculateAddress(pNXDS dataset, int pos[]){ +static int calculateAddress(pNXDS dataset, int pos[]) +{ int result, mult; int i, j; result = pos[dataset->rank - 1]; - for(i = 0; i < dataset->rank -1; i++){ + for (i = 0; i < dataset->rank - 1; i++) { mult = 1; - for(j = dataset->rank -1; j > i; j--){ + for (j = dataset->rank - 1; j > i; j--) { mult *= dataset->dim[j]; } - if(pos[i] < dataset->dim[i] && pos[i] > 0){ - result += mult*pos[i]; + if (pos[i] < dataset->dim[i] && pos[i] > 0) { + result += mult * pos[i]; } } return result; } + /*-----------------------------------------------------------------------*/ -double getNXDatasetValue(pNXDS dataset, int pos[]){ +double getNXDatasetValue(pNXDS dataset, int pos[]) +{ int address; double value; - if(dataset == NULL){ + if (dataset == NULL) { return 0; } - if(dataset->magic != MAGIC){ + if (dataset->magic != MAGIC) { return 0; } - address = calculateAddress(dataset,pos); + address = calculateAddress(dataset, pos); return getNXDatasetValueAt(dataset, address); } + /*----------------------------------------------------------------------*/ -double getNXDatasetValueAt(pNXDS dataset, int address){ +double getNXDatasetValueAt(pNXDS dataset, int address) +{ double value; - if(dataset == NULL){ + if (dataset == NULL) { return 0; } - if(dataset->magic != MAGIC){ + if (dataset->magic != MAGIC) { return 0; } - switch(dataset->type){ + switch (dataset->type) { case NX_FLOAT64: value = dataset->u.dPtr[address]; break; case NX_FLOAT32: - value = (double)dataset->u.fPtr[address]; + value = (double) dataset->u.fPtr[address]; break; case NX_INT32: case NX_UINT32: - value = (double)dataset->u.iPtr[address]; + value = (double) dataset->u.iPtr[address]; break; case NX_INT64: case NX_UINT64: - value = (double)dataset->u.lPtr[address]; + value = (double) dataset->u.lPtr[address]; break; case NX_INT16: case NX_UINT16: - value = (double)dataset->u.sPtr[address]; + value = (double) dataset->u.sPtr[address]; break; default: - value = (double)dataset->u.cPtr[address]; + value = (double) dataset->u.cPtr[address]; break; } return value; } + /*-----------------------------------------------------------------------*/ -char *getNXDatasetText(pNXDS dataset){ +char *getNXDatasetText(pNXDS dataset) +{ char *resultBuffer = NULL; int length, status = 1; - if(dataset == NULL){ + if (dataset == NULL) { return strdup("NULL"); } - if(dataset->magic != MAGIC){ + if (dataset->magic != MAGIC) { return strdup("NULL"); } - if(dataset->rank > 1){ + if (dataset->rank > 1) { status = 0; - } - if(dataset->type == NX_FLOAT32 || - dataset->type == NX_FLOAT64 || - dataset->type == NX_INT32 || - dataset->type == NX_UINT32 || - dataset->type == NX_INT64 || - dataset->type == NX_UINT64 || - dataset->type == NX_INT16 || - dataset->type == NX_UINT16 ) { + } + if (dataset->type == NX_FLOAT32 || + dataset->type == NX_FLOAT64 || + dataset->type == NX_INT32 || + dataset->type == NX_UINT32 || + dataset->type == NX_INT64 || + dataset->type == NX_UINT64 || + dataset->type == NX_INT16 || dataset->type == NX_UINT16) { status = 0; } - if(status == 0){ + if (status == 0) { return strdup("NO type problem"); - }else{ - resultBuffer = (char *)malloc((dataset->dim[0]+10)*sizeof(char)); - if(resultBuffer == NULL){ + } else { + resultBuffer = (char *) malloc((dataset->dim[0] + 10) * sizeof(char)); + if (resultBuffer == NULL) { return strdup("NO Memory"); } - memset(resultBuffer,0,(dataset->dim[0]+10)*sizeof(char)); - strncpy(resultBuffer,dataset->u.cPtr,dataset->dim[0]); + memset(resultBuffer, 0, (dataset->dim[0] + 10) * sizeof(char)); + strncpy(resultBuffer, dataset->u.cPtr, dataset->dim[0]); } return resultBuffer; } + /*----------------------------------------------------------------------*/ -int putNXDatasetValue(pNXDS dataset, int pos[], double value){ +int putNXDatasetValue(pNXDS dataset, int pos[], double value) +{ int address; - if(dataset == NULL){ + if (dataset == NULL) { return 0; } - if(dataset->magic != MAGIC){ + if (dataset->magic != MAGIC) { return 0; } - address = calculateAddress(dataset,pos); - return putNXDatasetValueAt(dataset,address,value); + address = calculateAddress(dataset, pos); + return putNXDatasetValueAt(dataset, address, value); } + /*---------------------------------------------------------------------*/ -int putNXDatasetValueAt(pNXDS dataset, int address, double value){ +int putNXDatasetValueAt(pNXDS dataset, int address, double value) +{ /* - this code is dangerous, it casts without checking the data range. - This may cause trouble in some cases - */ - switch(dataset->type){ + this code is dangerous, it casts without checking the data range. + This may cause trouble in some cases + */ + switch (dataset->type) { case NX_FLOAT64: dataset->u.dPtr[address] = value; break; case NX_FLOAT32: - dataset->u.fPtr[address] = (float)value; + dataset->u.fPtr[address] = (float) value; break; case NX_INT32: case NX_UINT32: - dataset->u.iPtr[address] = (int)value; + dataset->u.iPtr[address] = (int) value; break; case NX_INT64: case NX_UINT64: - dataset->u.lPtr[address] = (int64_t)value; + dataset->u.lPtr[address] = (int64_t) value; break; case NX_INT16: case NX_UINT16: - dataset->u.sPtr[address] = (short int)value; + dataset->u.sPtr[address] = (short int) value; break; default: - dataset->u.cPtr[address] = (char)value; + dataset->u.cPtr[address] = (char) value; break; } return 1; } + /*---------------------------------------------------------------------- This is working recursively through the dimensions. When at the last: actual copying takes place. -----------------------------------------------------------------------*/ -static void copyCutData(pNXDS source, pNXDS target, int sourceDim[], - int targetDim[], int start[], int end[], - int dim){ +static void copyCutData(pNXDS source, pNXDS target, int sourceDim[], + int targetDim[], int start[], int end[], int dim) +{ int i, length; double val; targetDim[dim] = 0; length = end[dim] - start[dim]; - if(dim == source->rank -1){ - for(i = 0; i < length; i++){ + if (dim == source->rank - 1) { + for (i = 0; i < length; i++) { sourceDim[dim] = start[dim] + i; - val = getNXDatasetValue(source,sourceDim); + val = getNXDatasetValue(source, sourceDim); targetDim[dim] = i; putNXDatasetValue(target, targetDim, val); } } else { - for(i = 0; i < length; i++){ + for (i = 0; i < length; i++) { sourceDim[dim] = start[dim] + i; targetDim[dim] = i; - copyCutData(source,target, sourceDim, targetDim, start, end, dim+1); + copyCutData(source, target, sourceDim, targetDim, start, end, + dim + 1); } } } + /*-----------------------------------------------------------------------*/ -pNXDS cutNXDataset(pNXDS source, int start[], int end[]){ +pNXDS cutNXDataset(pNXDS source, int start[], int end[]) +{ pNXDS result = NULL; int newDim[NX_MAXRANK], i; int sourceDim[NX_MAXRANK], targetDim[NX_MAXRANK]; - for(i = 0; i < source->rank; i++){ - if(start[i] < 0 || end[i] > source->dim[i]){ - fprintf(stderr,"ERROR: invalid boundaries specified for cutting"); + for (i = 0; i < source->rank; i++) { + if (start[i] < 0 || end[i] > source->dim[i]) { + fprintf(stderr, "ERROR: invalid boundaries specified for cutting"); return NULL; } newDim[i] = end[i] - start[i]; - if(newDim[i] <= 0){ - fprintf(stderr,"ERROR: invalid cut limits specified for cutting dataset"); + if (newDim[i] <= 0) { + fprintf(stderr, + "ERROR: invalid cut limits specified for cutting dataset"); return NULL; } } result = createNXDataset(source->rank, source->type, newDim); - if(result == NULL){ - fprintf(stderr,"ERROR: out of memory creating result dataset"); + if (result == NULL) { + fprintf(stderr, "ERROR: out of memory creating result dataset"); return NULL; } - + copyCutData(source, result, sourceDim, targetDim, start, end, 0); return result; } + /*---------------------------------------------------------------------- This recurses through all dimesnions, thereby skipping the summed one. At the end of the rescusion the actual summing is performed. ----------------------------------------------------------------------*/ -static void sumData(pNXDS source, pNXDS target, int sourceDim[], - int targetDim[], int targetDimCount, int dimNo, - int start, int end, int currentDim){ +static void sumData(pNXDS source, pNXDS target, int sourceDim[], + int targetDim[], int targetDimCount, int dimNo, + int start, int end, int currentDim) +{ int i, length; double val, sumVal; /* - when we have recursed through all dimensions - we actually do the sums... - */ - if(currentDim == source->rank){ + when we have recursed through all dimensions + we actually do the sums... + */ + if (currentDim == source->rank) { length = end - start; sumVal = getNXDatasetValue(target, targetDim); - for(i = 0; i < length; i++){ + for (i = 0; i < length; i++) { sourceDim[dimNo] = start + i; - val = getNXDatasetValue(source,sourceDim); + val = getNXDatasetValue(source, sourceDim); sumVal += val; } putNXDatasetValue(target, targetDim, sumVal); } else { /* - jump over the summed dimension while recursing - through the dimensions - */ - if(currentDim == dimNo){ - sumData(source,target,sourceDim, - targetDim,targetDimCount, - dimNo,start,end,currentDim+1); + jump over the summed dimension while recursing + through the dimensions + */ + if (currentDim == dimNo) { + sumData(source, target, sourceDim, + targetDim, targetDimCount, + dimNo, start, end, currentDim + 1); } else { /* - loop over all values of the non summed dimension - */ - for(i = 0; i < source->dim[currentDim]; i++){ - /* - the problem here is that we have to jump over the summed - dimension here. This why we have to maintain a separate - dimension count for the target array. Jumping is done - above. - */ - targetDim[targetDimCount] = i; - targetDimCount++; + loop over all values of the non summed dimension + */ + for (i = 0; i < source->dim[currentDim]; i++) { + /* + the problem here is that we have to jump over the summed + dimension here. This why we have to maintain a separate + dimension count for the target array. Jumping is done + above. + */ + targetDim[targetDimCount] = i; + targetDimCount++; - sourceDim[currentDim] = i; - sumData(source,target,sourceDim,targetDim,targetDimCount, - dimNo,start,end,currentDim+1); - targetDimCount--; + sourceDim[currentDim] = i; + sumData(source, target, sourceDim, targetDim, targetDimCount, + dimNo, start, end, currentDim + 1); + targetDimCount--; } } } } + /*-----------------------------------------------------------------------*/ -pNXDS sumNXDataset(pNXDS source, int dimNo, int start, int end){ +pNXDS sumNXDataset(pNXDS source, int dimNo, int start, int end) +{ int newDim[NX_MAXRANK], targetDim[NX_MAXRANK], sourceDim[NX_MAXRANK]; pNXDS result = NULL; int i, count; - if(dimNo < 0 || dimNo > source->rank-1) { - fprintf(stderr,"ERROR: invalid dimension for summing requested"); + if (dimNo < 0 || dimNo > source->rank - 1) { + fprintf(stderr, "ERROR: invalid dimension for summing requested"); return NULL; } /* - make result dataset with missing summed dimension - */ - for(i = 0, count = 0; i < source->rank; i++){ - if(i != dimNo){ + make result dataset with missing summed dimension + */ + for (i = 0, count = 0; i < source->rank; i++) { + if (i != dimNo) { newDim[count] = source->dim[i]; count++; } } - result = createNXDataset(source->rank-1, source->type, newDim); - if(result == NULL){ - fprintf(stderr,"ERROR: out of memory creating result dataset"); + result = createNXDataset(source->rank - 1, source->type, newDim); + if (result == NULL) { + fprintf(stderr, "ERROR: out of memory creating result dataset"); return NULL; } - sumData(source,result,sourceDim,targetDim,0, - dimNo, start, end, 0); + sumData(source, result, sourceDim, targetDim, 0, dimNo, start, end, 0); return result; } diff --git a/nxdataset.h b/nxdataset.h index ab5d33a9..129a5350 100644 --- a/nxdataset.h +++ b/nxdataset.h @@ -10,26 +10,26 @@ #define NXDATASET -#define MAGIC 7776622 +#define MAGIC 7776622 #include "napiconfig.h" typedef struct { - int magic; - int rank; - int type; - int *dim; - char *format; - union { - void *ptr; - float *fPtr; - double *dPtr; - int *iPtr; - short int *sPtr; - char *cPtr; - int64_t *lPtr; - } u; -}*pNXDS, NXDS; + int magic; + int rank; + int type; + int *dim; + char *format; + union { + void *ptr; + float *fPtr; + double *dPtr; + int *iPtr; + short int *sPtr; + char *cPtr; + int64_t *lPtr; + } u; +} *pNXDS, NXDS; /* include NeXus type codes if not already defined @@ -38,9 +38,9 @@ typedef struct { #define NX_FLOAT32 5 #define NX_FLOAT64 6 -#define NX_INT8 20 +#define NX_INT8 20 #define NX_UINT8 21 -#define NX_INT16 22 +#define NX_INT16 22 #define NX_UINT16 23 #define NX_INT32 24 #define NX_UINT32 25 @@ -56,20 +56,20 @@ typedef struct { pNXDS createNXDataset(int rank, int typecode, int dim[]); pNXDS createTextNXDataset(char *name); -void dropNXDataset(pNXDS dataset); +void dropNXDataset(pNXDS dataset); -int getNXDatasetRank(pNXDS dataset); -int getNXDatasetDim(pNXDS dataset, int which); -int getNXDatasetType(pNXDS dataset); -int getNXDatasetLength(pNXDS dataset); -int getNXDatasetByteLength(pNXDS dataset); +int getNXDatasetRank(pNXDS dataset); +int getNXDatasetDim(pNXDS dataset, int which); +int getNXDatasetType(pNXDS dataset); +int getNXDatasetLength(pNXDS dataset); +int getNXDatasetByteLength(pNXDS dataset); double getNXDatasetValue(pNXDS dataset, int pos[]); double getNXDatasetValueAt(pNXDS dataset, int address); -char *getNXDatasetText(pNXDS dataset); +char *getNXDatasetText(pNXDS dataset); -int putNXDatasetValue(pNXDS dataset, int pos[], double value); -int putNXDatasetValueAt(pNXDS dataset, int address, double value); +int putNXDatasetValue(pNXDS dataset, int pos[], double value); +int putNXDatasetValueAt(pNXDS dataset, int address, double value); pNXDS cutNXDataset(pNXDS source, int start[], int end[]); pNXDS sumNXDataset(pNXDS source, int dimNo, int start, int end); diff --git a/nxdict.c b/nxdict.c index 25737a7e..a5c07801 100644 --- a/nxdict.c +++ b/nxdict.c @@ -47,8 +47,8 @@ /*-------------------------------------------------------------------------- Things defined in napi.c for error reporting ---------------------------------------------------------------------------*/ - extern void *NXpData; - extern void (*NXIReportError)(void *pData, char *pBuffer); +extern void *NXpData; +extern void (*NXIReportError) (void *pData, char *pBuffer); /*--------------------------------------------------------------------------*/ /* #define DEFDEBUG 1 */ /* define DEFDEBUG when you wish to print your definition strings before @@ -58,53 +58,50 @@ /*-------------------------------------------------------------------------*/ - typedef struct __NXdict - { - int iID; - pStringDict pDictionary; - } sNXdict; +typedef struct __NXdict { + int iID; + pStringDict pDictionary; +} sNXdict; /*------------------ verbosity level -------------------------------------*/ - static int iVerbosity = 0 ; +static int iVerbosity = 0; /*-------------------------------------------------------------------------*/ - static char *NXDIReadFile(FILE *fd) - { - char *pNew = NULL; - long lLength = 0; - - assert(fd); +static char *NXDIReadFile(FILE * fd) +{ + char *pNew = NULL; + long lLength = 0; - /* determine length of file */ - fseek(fd,0L,SEEK_END); - lLength = ftell(fd); - if(lLength <= 0) - { - return NULL; - } - fseek(fd,0L,SEEK_SET); + assert(fd); - /* allocate buffer */ - lLength += 3; - pNew = (char *)malloc(lLength*sizeof(char)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,lLength); /* this ensures a 0 at the end */ - - /* read file */ - fread(pNew,sizeof(char),lLength-3,fd); - - /* check for existence of the NXDICT string in the file */ - if(strncmp(pNew,"##NXDICT-1.0",12) != 0 ) - { - NXIReportError(NXpData,"ERROR: This is NO NXdict file"); - free(pNew); - return NULL; - } - return pNew; + /* determine length of file */ + fseek(fd, 0L, SEEK_END); + lLength = ftell(fd); + if (lLength <= 0) { + return NULL; } + fseek(fd, 0L, SEEK_SET); + + /* allocate buffer */ + lLength += 3; + pNew = (char *) malloc(lLength * sizeof(char)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, lLength); /* this ensures a 0 at the end */ + + /* read file */ + fread(pNew, sizeof(char), lLength - 3, fd); + + /* check for existence of the NXDICT string in the file */ + if (strncmp(pNew, "##NXDICT-1.0", 12) != 0) { + NXIReportError(NXpData, "ERROR: This is NO NXdict file"); + free(pNew); + return NULL; + } + return pNew; +} + /*--------------------------------------------------------------------------*/ @@ -115,69 +112,56 @@ #define FEQUAL 5 #define FSLASH 6 - static char *NXDIfNextToken(char *pPtr, char *pToken, int *iToken) - { - pToken[0] = '\0'; - /* skip whitespace */ - while( (*pPtr == ' ') || (*pPtr == '\t') ) - { - pPtr++; - } +static char *NXDIfNextToken(char *pPtr, char *pToken, int *iToken) +{ + pToken[0] = '\0'; + /* skip whitespace */ + while ((*pPtr == ' ') || (*pPtr == '\t')) { + pPtr++; + } + + /* check for special characters */ + if (*pPtr == '#') { + *iToken = FHASH; + pToken[0] = *pPtr; + pPtr++; + return pPtr; + } else if (*pPtr == '\n') { + *iToken = FEOL; + pToken[0] = *pPtr; + pPtr++; + return pPtr; + } else if (*pPtr == '\0') { + *iToken = FEOB; + pToken[0] = *pPtr; + pPtr++; + return pPtr; + } else if (*pPtr == '=') { + *iToken = FEQUAL; + pToken[0] = *pPtr; + pPtr++; + return pPtr; + } else if (*pPtr == '\\') { + *iToken = FSLASH; + pToken[0] = *pPtr; + pPtr++; + return pPtr; + } else { + *iToken = FWORD; + /* copy word to pToken */ + while ((*pPtr != ' ') && (*pPtr != '\t') && + (*pPtr != '\n') && (*pPtr != '\0') && (*pPtr != '=')) { + *pToken = *pPtr; + pPtr++; + pToken++; + } + *pToken = '\0'; + return pPtr; + } + /* not reached */ + return pPtr; +} - /* check for special characters */ - if(*pPtr == '#') - { - *iToken = FHASH; - pToken[0] = *pPtr; - pPtr++; - return pPtr; - } - else if(*pPtr == '\n') - { - *iToken = FEOL; - pToken[0] = *pPtr; - pPtr++; - return pPtr; - } - else if(*pPtr == '\0') - { - *iToken = FEOB; - pToken[0] = *pPtr; - pPtr++; - return pPtr; - } - else if(*pPtr == '=') - { - *iToken = FEQUAL; - pToken[0] = *pPtr; - pPtr++; - return pPtr; - } - else if(*pPtr == '\\') - { - *iToken = FSLASH; - pToken[0] = *pPtr; - pPtr++; - return pPtr; - } - else - { - *iToken = FWORD; - /* copy word to pToken */ - while( (*pPtr != ' ') && (*pPtr != '\t') && - (*pPtr != '\n') && (*pPtr != '\0') && (*pPtr != '=') ) - { - *pToken = *pPtr; - pPtr++; - pToken++; - } - *pToken = '\0'; - return pPtr; - } - /* not reached */ - return pPtr; - } - /*------------------------------------------------------------------------*/ @@ -186,438 +170,399 @@ #define AMODE 0 #define DMODE 1 - static void NXDIParse(char *pBuffer, pStringDict pDict) - { - char *pPtr; - int iToken; - int iMode; - char pAlias[132]; - char pDefinition[1024]; /* this is > 10 lines of definition */ - char pWord[132]; +static void NXDIParse(char *pBuffer, pStringDict pDict) +{ + char *pPtr; + int iToken; + int iMode; + char pAlias[132]; + char pDefinition[1024]; /* this is > 10 lines of definition */ + char pWord[132]; - assert(pBuffer); - assert(pDict); + assert(pBuffer); + assert(pDict); - iMode = AMODE; - pPtr = pBuffer; - iToken = -1; - pDefinition[0] = '\0'; - pAlias[0] = '\0'; - pWord[0] = '\0'; + iMode = AMODE; + pPtr = pBuffer; + iToken = -1; + pDefinition[0] = '\0'; + pAlias[0] = '\0'; + pWord[0] = '\0'; - while(iToken != FEOB) - { - pPtr = NXDIfNextToken(pPtr,pWord,&iToken); - switch(iToken) - { - case FHASH: - case FSLASH: /* skip over \n to next non blank */ - while(*pPtr != '\n') - { - pPtr++; - /* check for end of file */ - if(*pPtr == '\0') - { - return; - } - } - pPtr++; - break; - case FEQUAL: /* do a mode change */ - iMode = DMODE; - pDefinition[0] = '\0'; - break; + while (iToken != FEOB) { + pPtr = NXDIfNextToken(pPtr, pWord, &iToken); + switch (iToken) { + case FHASH: + case FSLASH: /* skip over \n to next non blank */ + while (*pPtr != '\n') { + pPtr++; + /* check for end of file */ + if (*pPtr == '\0') { + return; + } + } + pPtr++; + break; + case FEQUAL: /* do a mode change */ + iMode = DMODE; + pDefinition[0] = '\0'; + break; - case FWORD: - if(iMode == AMODE) - { - strcpy(pAlias,pWord); - } - else - { - strcat(pDefinition,pWord); - strcat(pDefinition," "); - } - break; - case FEOL: - if(iMode == DMODE) - { - /* enter in dictionary */ - StringDictAddPair(pDict,pAlias,pDefinition); - iMode = AMODE; - pAlias[0] = '\0'; - } - break; - case FEOB: - if(iMode == AMODE) - { - /* empty line or a problem */ - } - else - { - /* enter in dictionary */ - StringDictAddPair(pDict,pAlias,pDefinition); - iMode = AMODE; - pAlias[0] = '\0'; - } - return; - default: - assert(0); /* unrecognized token is a programming - error - */ - break; - } - } + case FWORD: + if (iMode == AMODE) { + strcpy(pAlias, pWord); + } else { + strcat(pDefinition, pWord); + strcat(pDefinition, " "); + } + break; + case FEOL: + if (iMode == DMODE) { + /* enter in dictionary */ + StringDictAddPair(pDict, pAlias, pDefinition); + iMode = AMODE; + pAlias[0] = '\0'; + } + break; + case FEOB: + if (iMode == AMODE) { + /* empty line or a problem */ + } else { + /* enter in dictionary */ + StringDictAddPair(pDict, pAlias, pDefinition); + iMode = AMODE; + pAlias[0] = '\0'; + } + return; + default: + assert(0); /* unrecognized token is a programming + error + */ + break; + } + } +} + + +/*--------------------------------------------------------------------------*/ +NXstatus NXDinitfromfile(char *filename, NXdict * pData) +{ + NXdict pNew = NULL; + FILE *fd = NULL; + char *pBuffer = NULL; + char pError[512]; + + + + /* allocate a new NXdict structure */ + if (iVerbosity == NXalot) { + NXIReportError(NXpData, "Allocating new NXdict structure "); + } + pNew = (NXdict) malloc(sizeof(sNXdict)); + if (!pNew) { + NXIReportError(NXpData, "Insufficient memory for creation of NXdict"); + return NX_ERROR; + } + + /* initialise it */ + pNew->iID = NXDMAGIC; + pNew->pDictionary = CreateStringDict(); + if (!pNew->pDictionary) { + NXIReportError(NXpData, "Insufficient memory for creation of NXdict"); + free(pNew); + return NX_ERROR; } -/*--------------------------------------------------------------------------*/ - NXstatus NXDinitfromfile(char *filename, NXdict *pData) - { - NXdict pNew = NULL; - FILE *fd = NULL; - char *pBuffer = NULL; - char pError[512]; + + /* is there a file name argument */ + if (filename == NULL) { + if (iVerbosity == NXalot) { + NXIReportError(NXpData, "NXDinitfrom file finished without data"); + } + *pData = pNew; + return NX_OK; + } - - /* allocate a new NXdict structure */ - if(iVerbosity == NXalot) - { - NXIReportError(NXpData, "Allocating new NXdict structure "); - } - pNew = (NXdict)malloc(sizeof(sNXdict)); - if(!pNew) - { - NXIReportError(NXpData, "Insufficient memory for creation of NXdict"); - return NX_ERROR; - } - - /* initialise it */ - pNew->iID = NXDMAGIC; - pNew->pDictionary = CreateStringDict(); - if(!pNew->pDictionary) - { - NXIReportError(NXpData, "Insufficient memory for creation of NXdict"); - free(pNew); - return NX_ERROR; - } + fd = fopen(filename, "rb"); + if (!fd) { + sprintf(pError, "ERROR: file %s NOT found ", filename); + NXIReportError(NXpData, pError); + NXIReportError(NXpData, "NXDinitfrom file finished without data"); + *pData = pNew; + return NX_ERROR; + } + /* read the file contents */ + if (iVerbosity == NXalot) { + NXIReportError(NXpData, "NXDinitfrom: reading file"); + } + pBuffer = NXDIReadFile(fd); + fclose(fd); /* we are done with it then */ + if (!pBuffer) { + sprintf(pError, "ERROR: reading file %s or no memory", filename); + NXIReportError(NXpData, pError); + NXIReportError(NXpData, "NXDinitfrom file finished without data"); + *pData = pNew; + return NX_ERROR; + } - /* is there a file name argument */ - if(filename == NULL) - { - if(iVerbosity == NXalot) - { - NXIReportError(NXpData, "NXDinitfrom file finished without data"); - } - *pData = pNew; - return NX_OK; - } + /* parse it */ + if (iVerbosity == NXalot) { + NXIReportError(NXpData, "NXDinitfrom: parsing dictionary definitions"); + } + NXDIParse(pBuffer, pNew->pDictionary); - fd = fopen(filename,"rb"); - if(!fd) - { - sprintf(pError,"ERROR: file %s NOT found ",filename); - NXIReportError(NXpData, pError); - NXIReportError(NXpData, "NXDinitfrom file finished without data"); - *pData = pNew; - return NX_ERROR; - } + if (iVerbosity == NXalot) { + NXIReportError(NXpData, "NXDinitfrom: performed successfully"); + } + free(pBuffer); + *pData = pNew; + return NX_OK; +} - - /* read the file contents */ - if(iVerbosity == NXalot) - { - NXIReportError(NXpData, "NXDinitfrom: reading file"); - } - pBuffer = NXDIReadFile(fd); - fclose(fd); /* we are done with it then */ - if(!pBuffer) - { - sprintf(pError,"ERROR: reading file %s or no memory",filename); - NXIReportError(NXpData, pError); - NXIReportError(NXpData, "NXDinitfrom file finished without data"); - *pData = pNew; - return NX_ERROR; - } - - /* parse it */ - if(iVerbosity == NXalot) - { - NXIReportError(NXpData, "NXDinitfrom: parsing dictionary definitions"); - } - NXDIParse(pBuffer, pNew->pDictionary); - - - if(iVerbosity == NXalot) - { - NXIReportError(NXpData, "NXDinitfrom: performed successfully"); - } - free(pBuffer); - *pData = pNew; - return NX_OK; - } /*--------------------------------------------------------------------------*/ - NXdict NXDIAssert(NXdict handle) - { - NXdict self = NULL; - assert(handle); - self = (NXdict)handle; - assert(self->iID == NXDMAGIC); - return self; - } +NXdict NXDIAssert(NXdict handle) +{ + NXdict self = NULL; + assert(handle); + self = (NXdict) handle; + assert(self->iID == NXDMAGIC); + return self; +} /*-------------------------------------------------------------------------*/ - NXstatus NXDclose(NXdict handle, char *filename) - { - NXdict self; - const char *pKey = NULL; - char pValue[1024]; - FILE *fd = NULL; +NXstatus NXDclose(NXdict handle, char *filename) +{ + NXdict self; + const char *pKey = NULL; + char pValue[1024]; + FILE *fd = NULL; - self = NXDIAssert(handle); + self = NXDIAssert(handle); - if(filename) /* we must write a file */ - { - if(iVerbosity == NXalot) - { - sprintf(pValue,"Writing file %s",filename); - NXIReportError(NXpData, pValue); - } - fd = fopen(filename,"w"); - if(!fd) - { - sprintf(pValue,"ERROR: opening file %s for write",filename); - NXIReportError(NXpData, pValue); - return NX_ERROR; - } - - /* write our magic recognition header */ - fprintf(fd,"##NXDICT-1.0\n"); + if (filename) { /* we must write a file */ + if (iVerbosity == NXalot) { + sprintf(pValue, "Writing file %s", filename); + NXIReportError(NXpData, pValue); + } + fd = fopen(filename, "w"); + if (!fd) { + sprintf(pValue, "ERROR: opening file %s for write", filename); + NXIReportError(NXpData, pValue); + return NX_ERROR; + } - /* write all our keys */ - pKey = StringDictGetNext(self->pDictionary, pValue,1023); - while(pKey != NULL) - { - fprintf(fd,"%s = %s\n",pKey,pValue); - pKey = StringDictGetNext(self->pDictionary,pValue,1023); - } - fclose(fd); - if(iVerbosity == NXalot) - { - sprintf(pValue,"File %s written",filename); - NXIReportError(NXpData, pValue); - } - } + /* write our magic recognition header */ + fprintf(fd, "##NXDICT-1.0\n"); - /* now we send the cleaners in */ - DeleteStringDict(self->pDictionary); - free(self); - return NX_OK; - } + /* write all our keys */ + pKey = StringDictGetNext(self->pDictionary, pValue, 1023); + while (pKey != NULL) { + fprintf(fd, "%s = %s\n", pKey, pValue); + pKey = StringDictGetNext(self->pDictionary, pValue, 1023); + } + fclose(fd); + if (iVerbosity == NXalot) { + sprintf(pValue, "File %s written", filename); + NXIReportError(NXpData, pValue); + } + } + + /* now we send the cleaners in */ + DeleteStringDict(self->pDictionary); + free(self); + return NX_OK; +} /*------------------------------------------------------------------------*/ - NXstatus NXDadd(NXdict handle, char *alias, char *pDef) - { - NXdict self; - int iRet; +NXstatus NXDadd(NXdict handle, char *alias, char *pDef) +{ + NXdict self; + int iRet; + + self = NXDIAssert(handle); + iRet = StringDictAddPair(self->pDictionary, alias, pDef); + if (!iRet) { + return NX_ERROR; + } + return NX_OK; +} - self = NXDIAssert(handle); - iRet = StringDictAddPair(self->pDictionary,alias,pDef); - if(!iRet) - { - return NX_ERROR; - } - return NX_OK; - } /*---------------------------------------------------------------------------*/ - NXstatus NXDget(NXdict handle, char *pKey, char *pBuffer, int iBufLen) - { - NXdict self; - int iRet; +NXstatus NXDget(NXdict handle, char *pKey, char *pBuffer, int iBufLen) +{ + NXdict self; + int iRet; - self = NXDIAssert(handle); - iRet = StringDictGet(self->pDictionary,pKey,pBuffer,iBufLen); - if(!iRet) - { - return NX_ERROR; - } + self = NXDIAssert(handle); + iRet = StringDictGet(self->pDictionary, pKey, pBuffer, iBufLen); + if (!iRet) { + return NX_ERROR; + } #ifdef DEFDEBUG - printf("Resolved: %s to %s\n",pKey,pBuffer); + printf("Resolved: %s to %s\n", pKey, pBuffer); #endif - return NX_OK; - } -/*-------------------------------------------------------------------------*/ - NXstatus NXDupdate(NXdict handle, char *pKey, char *pNewVal) - { - NXdict self; - int iRet; + return NX_OK; +} + +/*-------------------------------------------------------------------------*/ +NXstatus NXDupdate(NXdict handle, char *pKey, char *pNewVal) +{ + NXdict self; + int iRet; + + self = NXDIAssert(handle); + iRet = StringDictUpdate(self->pDictionary, pKey, pNewVal); + if (!iRet) { + return NX_ERROR; + } + return NX_OK; +} - self = NXDIAssert(handle); - iRet = StringDictUpdate(self->pDictionary,pKey,pNewVal); - if(!iRet) - { - return NX_ERROR; - } - return NX_OK; - } /*-----------------------------------------------------------------------*/ #define NORMAL 1 #define ALIAS 2 - pDynString NXDItextreplace(NXdict handle, char *pDefString) - { - NXdict self; - int iRet, iPos, i; - pDynString pReplaced = NULL; - char pBueffel[1024]; - char pBuffer2[1024]; - char *pPtr; - int iState; +pDynString NXDItextreplace(NXdict handle, char *pDefString) +{ + NXdict self; + int iRet, iPos, i; + pDynString pReplaced = NULL; + char pBueffel[1024]; + char pBuffer2[1024]; + char *pPtr; + int iState; - self = NXDIAssert(handle); - - /* create a dynamic string */ - pReplaced = CreateDynString(strlen(pDefString),512); - if(!pReplaced) - { - NXIReportError(NXpData,"ERROR: out of memory in NXDtextreplace"); - return NULL; - } + self = NXDIAssert(handle); - /* the loop */ - iState = NORMAL; - for(i = 0, pPtr = pDefString; i < strlen(pDefString); i++,pPtr++) - { - if(iState == NORMAL) - { - if(*pPtr == '$') - { - iState = ALIAS; - memset(pBueffel,0,1024); - iPos = 0; - } - else - { - DynStringConcatChar(pReplaced,*pPtr); - } + /* create a dynamic string */ + pReplaced = CreateDynString(strlen(pDefString), 512); + if (!pReplaced) { + NXIReportError(NXpData, "ERROR: out of memory in NXDtextreplace"); + return NULL; + } + + /* the loop */ + iState = NORMAL; + for (i = 0, pPtr = pDefString; i < strlen(pDefString); i++, pPtr++) { + if (iState == NORMAL) { + if (*pPtr == '$') { + iState = ALIAS; + memset(pBueffel, 0, 1024); + iPos = 0; + } else { + DynStringConcatChar(pReplaced, *pPtr); + } + } else if (iState == ALIAS) { + switch (*pPtr) { + case '(': /* ignore */ + break; + case ')': + /* do the replacement */ + memset(pBuffer2, 0, 1023); + iRet = NXDget(handle, pBueffel, pBuffer2, 1023); + if (iRet != NX_OK) { + DeleteDynString(pReplaced); + return NULL; } - else if(iState == ALIAS) - { - switch(*pPtr) - { - case '(': /* ignore */ - break; - case ')': - /* do the replacement */ - memset(pBuffer2,0,1023); - iRet = NXDget(handle, pBueffel,pBuffer2,1023); - if(iRet != NX_OK) - { - DeleteDynString(pReplaced); - return NULL; - } - DynStringConcat(pReplaced,pBuffer2); - iState = NORMAL; - break; - default: - pBueffel[iPos] = *pPtr; - iPos++; - if(iPos >= 1024) - { - NXIReportError(NXpData, - "ERROR: buffer overrun in NXDItextreplace"); - DeleteDynString(pReplaced); - return NULL; - } - break; - } + DynStringConcat(pReplaced, pBuffer2); + iState = NORMAL; + break; + default: + pBueffel[iPos] = *pPtr; + iPos++; + if (iPos >= 1024) { + NXIReportError(NXpData, + "ERROR: buffer overrun in NXDItextreplace"); + DeleteDynString(pReplaced); + return NULL; } - } + break; + } + } + } #ifdef DEFDEBUG - printf("Replacement result: %s\n",GetCharArray(pReplaced)); + printf("Replacement result: %s\n", GetCharArray(pReplaced)); #endif - return pReplaced; - } + return pReplaced; +} + /*------------------------------------------------------------------------*/ - NXstatus NXDdefget(NXdict handle, char *pKey, char *pBuffer, int iBufLen) - { - int status; - pDynString pRep = NULL; +NXstatus NXDdefget(NXdict handle, char *pKey, char *pBuffer, int iBufLen) +{ + int status; + pDynString pRep = NULL; + + status = NXDget(handle, pKey, pBuffer, iBufLen); + if (status != NX_OK) { + return status; + } + + pRep = NXDItextreplace(handle, pBuffer); + if (pRep) { + strncpy(pBuffer, GetCharArray(pRep), iBufLen); + status = NX_OK; + DeleteDynString(pRep); + } else { + status = NX_ERROR; + } + return status; +} - status = NXDget(handle,pKey,pBuffer,iBufLen); - if(status != NX_OK) - { - return status; - } - - pRep = NXDItextreplace(handle,pBuffer); - if(pRep) - { - strncpy(pBuffer,GetCharArray(pRep),iBufLen); - status = NX_OK; - DeleteDynString(pRep); - } - else - { - status = NX_ERROR; - } - return status; - } /*--------------------------------------------------------------------------*/ - NXstatus NXDtextreplace(NXdict handle, char *pDefString, - char *pBuffer, int iBufLen) - { - pDynString pResult = NULL; - char *pPtr = NULL; +NXstatus NXDtextreplace(NXdict handle, char *pDefString, + char *pBuffer, int iBufLen) +{ + pDynString pResult = NULL; + char *pPtr = NULL; - pResult = NXDItextreplace(handle,pDefString); - if(!pResult) - { - return NX_ERROR; - } + pResult = NXDItextreplace(handle, pDefString); + if (!pResult) { + return NX_ERROR; + } - /* copy results home */ - pPtr = GetCharArray(pResult); - strncpy(pBuffer,pPtr,iBufLen); - DeleteDynString(pResult); - return NX_OK; - } + /* copy results home */ + pPtr = GetCharArray(pResult); + strncpy(pBuffer, pPtr, iBufLen); + DeleteDynString(pResult); + return NX_OK; +} /*------------------- The Defintion String Parser -----------------------*/ /*------- Data structures */ - typedef struct { - char *pText; - int iCode; - } TokDat; +typedef struct { + char *pText; + int iCode; +} TokDat; #define TERMSDS 100 #define TERMVG 200 #define TERMLINK 300 - typedef struct { - char *pPtr; - char pToken[256]; - int iToken; - int iDepth; - int iMayCreate; - int iTerminal; - } ParDat; +typedef struct { + char *pPtr; + char pToken[256]; + int iToken; + int iDepth; + int iMayCreate; + int iTerminal; +} ParDat; - static void DummyError(void *pData, char *pError) - { - return; - } - typedef struct { - char name[256]; - char value[256]; - }AttItem; +static void DummyError(void *pData, char *pError) +{ + return; +} +typedef struct { + char name[256]; + char value[256]; +} AttItem; /*---------------- Token name defines ---------------------------*/ #define DSLASH 0 @@ -640,1367 +585,1241 @@ /*----------------- Keywords ----------------------------------------*/ - static TokDat TokenList[12] = { - {"SDS",DSDS}, - {"NXLINK",DLINK}, - {"NXVGROUP",DGROUP}, - {"-dim",DDIM}, - {"-type",DTYPE}, - {"-rank",DRANK}, - {"-attr",DATTR}, - {"-chunk",CHUNK}, - {"-LZW",DLZW}, - {"-HUF",DHUF}, - {"-RLE",DRLE}, - {NULL,0} }; +static TokDat TokenList[12] = { + {"SDS", DSDS}, + {"NXLINK", DLINK}, + {"NXVGROUP", DGROUP}, + {"-dim", DDIM}, + {"-type", DTYPE}, + {"-rank", DRANK}, + {"-attr", DATTR}, + {"-chunk", CHUNK}, + {"-LZW", DLZW}, + {"-HUF", DHUF}, + {"-RLE", DRLE}, + {NULL, 0} +}; /*-----------------------------------------------------------------------*/ - static void NXDIDefToken(ParDat *sStat) - { - int i; - +static void NXDIDefToken(ParDat * sStat) +{ + int i; - sStat->pToken[0] = '\0'; - /* skip whitespace */ - while( (*(sStat->pPtr) == ' ') || (*(sStat->pPtr) == '\t') ) - { - sStat->pPtr++; - } + sStat->pToken[0] = '\0'; - /* check for special characters */ - if(*(sStat->pPtr) == '/') - { - sStat->iToken = DSLASH; - sStat->pToken[0] = *(sStat->pPtr); - sStat->pPtr++; - return; - } - else if(*(sStat->pPtr) == ',') - { - sStat->iToken = DKOMMA; - sStat->pToken[0] = *(sStat->pPtr); - sStat->pPtr++; - return; - } - else if(*(sStat->pPtr) == '\0') - { - sStat->iToken = DEND; - sStat->pToken[0] = *(sStat->pPtr); - sStat->pPtr++; - return; - } - else if(*(sStat->pPtr) == '{') - { - sStat->iToken = DOPEN; - sStat->pToken[0] = *(sStat->pPtr); - sStat->pPtr++; - return; - } - else if(*(sStat->pPtr) == '}') - { - sStat->iToken = DCLOSE; - sStat->pToken[0] = *(sStat->pPtr); - sStat->pPtr++; - return; - } - else - { - sStat->iToken = DWORD; - /* copy word to pToken */ - i = 0; - while( (*(sStat->pPtr) != ' ') && (*(sStat->pPtr) != '\t') && - (*(sStat->pPtr) != '/') && (*(sStat->pPtr) != '\0') && - (*(sStat->pPtr) != ',') && (*(sStat->pPtr) != '}') ) - { - sStat->pToken[i] = *(sStat->pPtr); - sStat->pPtr++; - i++; - } - sStat->pToken[i] = '\0'; + /* skip whitespace */ + while ((*(sStat->pPtr) == ' ') || (*(sStat->pPtr) == '\t')) { + sStat->pPtr++; + } + + /* check for special characters */ + if (*(sStat->pPtr) == '/') { + sStat->iToken = DSLASH; + sStat->pToken[0] = *(sStat->pPtr); + sStat->pPtr++; + return; + } else if (*(sStat->pPtr) == ',') { + sStat->iToken = DKOMMA; + sStat->pToken[0] = *(sStat->pPtr); + sStat->pPtr++; + return; + } else if (*(sStat->pPtr) == '\0') { + sStat->iToken = DEND; + sStat->pToken[0] = *(sStat->pPtr); + sStat->pPtr++; + return; + } else if (*(sStat->pPtr) == '{') { + sStat->iToken = DOPEN; + sStat->pToken[0] = *(sStat->pPtr); + sStat->pPtr++; + return; + } else if (*(sStat->pPtr) == '}') { + sStat->iToken = DCLOSE; + sStat->pToken[0] = *(sStat->pPtr); + sStat->pPtr++; + return; + } else { + sStat->iToken = DWORD; + /* copy word to pToken */ + i = 0; + while ((*(sStat->pPtr) != ' ') && (*(sStat->pPtr) != '\t') && + (*(sStat->pPtr) != '/') && (*(sStat->pPtr) != '\0') && + (*(sStat->pPtr) != ',') && (*(sStat->pPtr) != '}')) { + sStat->pToken[i] = *(sStat->pPtr); + sStat->pPtr++; + i++; + } + sStat->pToken[i] = '\0'; /*--------- try to find word in Tokenlist */ - for(i = 0; i < 11; i++) - { - if(strcmp(sStat->pToken,TokenList[i].pText) == 0) - { - sStat->iToken = TokenList[i].iCode; - break; - } - } - return; - } - /* not reached */ - return; - } -/*-----------------------------------------------------------------------*/ - static void NXDIAttValue(ParDat *sStat) - { - int i; - - - sStat->pToken[0] = '\0'; - - /* skip whitespace */ - while( (*(sStat->pPtr) == ' ') || (*(sStat->pPtr) == '\t') ) - { - sStat->pPtr++; - } - - if(*(sStat->pPtr) == ',') - { - sStat->iToken = DKOMMA; - sStat->pToken[0] = *(sStat->pPtr); - sStat->pPtr++; - return; - } - else if(*(sStat->pPtr) == '\0') - { - sStat->iToken = DEND; - sStat->pToken[0] = *(sStat->pPtr); - sStat->pPtr++; - return; - } - else if(*(sStat->pPtr) == '{') - { - sStat->iToken = DOPEN; - sStat->pToken[0] = *(sStat->pPtr); - sStat->pPtr++; - return; - } - else if(*(sStat->pPtr) == '}') - { - sStat->iToken = DCLOSE; - sStat->pToken[0] = *(sStat->pPtr); - sStat->pPtr++; - return; - } - else - { - sStat->iToken = DWORD; - /* copy word to pToken */ - i = 0; - while( (*(sStat->pPtr) != ' ') && (*(sStat->pPtr) != '\t') && - (*(sStat->pPtr) != '\0') && - (*(sStat->pPtr) != ',') && (*(sStat->pPtr) != '}') ) - { - sStat->pToken[i] = *(sStat->pPtr); - sStat->pPtr++; - i++; - } - sStat->pToken[i] = '\0'; - return; - } - /* not reached */ - return; - } - - -/*------------------------------------------------------------------------*/ - - int NXDIParsePath(NXhandle hfil, ParDat *pParse) - { - int iRet, iToken; - void (*ErrFunc)(void *pData, char *pErr); - char pName[132], pClass[132]; - char pError[256]; - - /* get the name */ - NXDIDefToken(pParse); /* next token */ - if( (pParse->iToken == DSDS) || (pParse->iToken == DGROUP) - || (pParse->iToken == DLINK) ) - { - /* put back & OK */ - pParse->pPtr -= strlen(pParse->pToken); - return NX_OK; - } - if(pParse->iToken != DWORD) - { - sprintf(pError,"ERROR: parse error at %s, expected vGroup name", - pParse->pToken); - NXIReportError(NXpData, pError); - return NX_ERROR; - } - strcpy(pName,pParse->pToken); - - /* now we expect a komma */ - NXDIDefToken(pParse); /* next token */ - if(pParse->iToken != DKOMMA) - { - sprintf(pError,"ERROR: parse error at %s, expected komma", - pParse->pToken); - NXIReportError(NXpData, pError); - return NX_ERROR; - } - - /* next must be the class */ - NXDIDefToken(pParse); /* next token */ - if(pParse->iToken != DWORD) - { - sprintf(pError,"ERROR: parse error at %s, expected vGroup class", - pParse->pToken); - NXIReportError(NXpData, pError); - return NX_ERROR; - } - strcpy(pClass,pParse->pToken); - - /* done reading, ACTION, first install dummy error handler */ - ErrFunc = NXIReportError; - NXMSetError(NXpData, DummyError); - - /* try opening vGroup */ - iRet = NXopengroup(hfil, pName, pClass); - NXMSetError(NXpData,ErrFunc); - if(iRet == NX_OK) - { - pParse->iDepth++; - return NX_OK; - } - else - { - /* we need to create it, if we may */ - if(pParse->iMayCreate) - { - iRet = NXmakegroup(hfil,pName,pClass); - if(iRet != NX_OK) - { - /* a comment on this one has already been written! */ - return iRet; - } - iRet = NXopengroup(hfil,pName,pClass); - if(iRet != NX_OK) - { - /* a comment on this one has already been written! */ - return iRet; - } - pParse->iDepth++; - return NX_OK; - } - else - { - /* this is an error */ - sprintf(pError,"ERROR: vGroup %s, %s NOT found",pName, pClass); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - } - /* not reached */ - return NX_ERROR; - } - -/*------------------------------------------------------------------------*/ - - static int NXDIParseAttr(ParDat *pParse, int iList) - { - char pError[256]; - int iRet; - AttItem sAtt; - - /* a { is expected */ - NXDIDefToken(pParse); - if(pParse->iToken != DOPEN) - { - sprintf(pError,"ERROR: expected {, got %s",pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - - /* a word is expected */ - NXDIDefToken(pParse); - if(pParse->iToken != DWORD) - { - sprintf(pError,"ERROR: expected attribute name, got %s",pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - strcpy(sAtt.name,pParse->pToken); - - /* a , is expected */ - NXDIDefToken(pParse); - if(pParse->iToken != DKOMMA) - { - sprintf(pError,"ERROR: expected , , got %s",pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - - /* a word is expected */ - NXDIAttValue(pParse); - if(pParse->iToken != DWORD) - { - sprintf(pError,"ERROR: expected attribute value, got %s",pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - strcpy(sAtt.value,pParse->pToken); - - /* a } is expected */ - NXDIDefToken(pParse); - if(pParse->iToken != DCLOSE) - { - sprintf(pError,"ERROR: expected }, got %s",pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - - /* enter into list */ - LLDnodeAppendFrom(iList,&sAtt); - return NX_OK; - } - -/*------------------------------------------------------------------------*/ - static int NXDIParseDim(ParDat *pParse, int *iDim) - { - char pError[256]; - int iRet, i; - - /* initialise dimensions to 0 */ - for(i = 0; i < NX_MAXRANK; i++) - { - iDim[i] = 0; - } - - NXDIDefToken(pParse); - if(pParse->iToken != DOPEN) - { - sprintf(pError,"ERROR: expected {, got %s",pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - - i = 0; - while(pParse->iToken != DCLOSE) - { - /* get a number */ - NXDIDefToken(pParse); - if(pParse->iToken != DWORD) - { - sprintf(pError,"ERROR: expected number, got %s",pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - iDim[i] = atoi(pParse->pToken); - i++; - /* next must be close of komma */ - NXDIDefToken(pParse); - if( (pParse->iToken != DKOMMA) && (pParse->iToken != DCLOSE) ) - { - sprintf(pError,"ERROR: expected , or }, got %s",pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - if(pParse->iToken == DCLOSE) - { - break; - } - } - return NX_OK; - } -/*------------------------------------------------------------------------*/ - static TokDat tDatType[] = { - {"DFNT_FLOAT32",NX_FLOAT32}, - {"DFNT_FLOAT64",NX_FLOAT64}, - {"DFNT_INT8",NX_INT8}, - {"DFNT_UINT8",NX_UINT8}, - {"DFNT_INT16",NX_INT16}, - {"DFNT_UINT16",NX_UINT16}, - {"DFNT_INT32",NX_INT32}, - {"DFNT_UINT32",NX_UINT32}, - {"DFNT_CHAR",NX_CHAR}, - {"NX_FLOAT32",NX_FLOAT32}, - {"NX_FLOAT64",NX_FLOAT64}, - {"NX_INT8",NX_INT8}, - {"NX_UINT8",NX_UINT8}, - {"NX_INT16",NX_INT16}, - {"NX_UINT16",NX_UINT16}, - {"NX_INT32",NX_INT32}, - {"NX_UINT32",NX_UINT32}, - {"NX_CHAR",NX_CHAR}, - {NULL,-122} }; - - - - static int NXDIParseType(ParDat *pParse, int *iType) - { - char pError[256]; - int i = 0; - - NXDIDefToken(pParse); - if(pParse->iToken != DWORD) - { - sprintf(pError,"ERROR: expected data type, got %s", pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; + for (i = 0; i < 11; i++) { + if (strcmp(sStat->pToken, TokenList[i].pText) == 0) { + sStat->iToken = TokenList[i].iCode; + break; } - - /* try to interpret data type */ - while(tDatType[i].iCode > 0) { - if(strcmp(tDatType[i].pText,pParse->pToken) == 0) - { - *iType = tDatType[i].iCode; - return NX_OK; - } - i++; - } - /* if we are here, the data type has not been recognized. Reason for - some boring error reporting code - */ - sprintf(pError,"ERROR: %s not recognized as valid data type", - pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - -/*-------------------------------------------------------------------------*/ - static int NXDIParseSDS(NXhandle hfil, ParDat *pParse) - { - int iType = NX_FLOAT32; - int iRank = 1; - int iCompress = NX_COMP_NONE; - int iDim[NX_MAXRANK], iChunk[NX_MAXRANK]; - int iList, iChunkDefined = 0 ; - int iRet, iStat, i; - char pError[256]; - char pName[NX_MAXNAMELEN]; - void (*ErrFunc)(void *pData, char *pErr); - AttItem sAtt; - - - iDim[0] = 1; - /* first find the name */ - NXDIDefToken(pParse); - if(pParse->iToken != DWORD) - { - sprintf(pError,"ERROR: parsing, expected name, got %s", - pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - strcpy(pName,pParse->pToken); - - /* create the attribute list */ - iList = LLDcreate(sizeof(AttItem)); - if(iList < 0) - { - NXIReportError(NXpData, "ERROR: cannot create list in NXDIParseSDS"); - return NX_ERROR; - } - - NXDIDefToken(pParse); - while(pParse->iToken != DEND) - { - switch(pParse->iToken) - { - case DRANK: /* rank */ - NXDIDefToken(pParse); /* advance */ - if(pParse->iToken != DWORD) - { - sprintf(pError, - "ERROR: expected int, got %s", pParse->pToken); - NXIReportError(NXpData,pError); - LLDdelete(iList); - return NX_ERROR; - } - iRank = atoi(pParse->pToken); - break; - case CHUNK: /* chunk size for compression */ - iRet = NXDIParseDim(pParse, iChunk); - if(iRet == NX_ERROR) - { - LLDdelete(iList); - return iRet; - } - iChunkDefined = 1; - break; - case DDIM: - iRet = NXDIParseDim(pParse, iDim); - if(iRet == NX_ERROR) - { - LLDdelete(iList); - return iRet; - } - break; - case DTYPE: - iRet = NXDIParseType(pParse, &iType); - if(iRet == NX_ERROR) - { - LLDdelete(iList); - return iRet; - } - break; - case DATTR: - iRet = NXDIParseAttr(pParse, iList); - if(iRet == NX_ERROR) - { - LLDdelete(iList); - return iRet; - } - break; - case DLZW: - iCompress = NX_COMP_LZW; - break; - case DRLE: - iCompress = NX_COMP_RLE; - break; - case DHUF: - iCompress = NX_COMP_HUF; - break; - case DEND: - break; - default: - sprintf(pError,"ERROR: cannot identify token %s", - pParse->pToken); - NXIReportError(NXpData, pError); - LLDdelete(iList); - return NX_ERROR; - - } - NXDIDefToken(pParse); - } - - /* whew! got all information for doing the SDS - However, if the chunk sizes for compression have not - been set, default them to the dimensions of the data set - */ - if(iChunkDefined == 0) - { - for(i = 0; i < iRank; i++) - { - iChunk[i] = iDim[i]; - } - } - if(iChunk[0] < 0) { - iChunk[0] = 1; - } - - /* first install dummy error handler, try open it, then - deinstall again and create if allowed - */ - ErrFunc = NXIReportError; - NXMSetError(NXpData, DummyError); - - /* try opening SDS */ - iRet = NXopendata(hfil, pName); - NXMSetError(NXpData,ErrFunc); - if(iRet == NX_OK) - { - LLDdelete(iList); - return NX_OK; - } - else - { - /* we need to create it, if we may */ - if(pParse->iMayCreate) - { - iRet = NXcompmakedata(hfil,pName,iType, iRank,iDim, - iCompress,iChunk); - if(iRet != NX_OK) - { - /* a comment on this one has already been written! */ - LLDdelete(iList); - return iRet; - } - iRet = NXopendata(hfil,pName); - if(iRet != NX_OK) - { - /* a comment on this one has already been written! */ - LLDdelete(iList); - return iRet; - } - - /* put attributes in */ - iRet = LLDnodePtr2First(iList); - while(iRet != 0) - { - LLDnodeDataTo(iList,&sAtt); - iStat = NXputattr(hfil,sAtt.name, - sAtt.value,strlen(sAtt.value),NX_CHAR); - if(iStat != NX_OK) - { - /* NeXus already complained bitterly */ - LLDdelete(iList); - return iStat; - } - iRet = LLDnodePtr2Next(iList); - } - LLDdelete(iList); - return NX_OK; - } - else - { - /* this is an error */ - sprintf(pError,"ERROR: SDS %s NOT found",pName); - NXIReportError(NXpData,pError); - LLDdelete(iList); - return NX_ERROR; - } - } - return NX_OK; - } -/*------------------------------------------------------------------------*/ - static int NXDIParseLink(NXhandle hfil, NXdict pDict,ParDat *pParse) - { - char pError[256]; - int i, iRet; - - /* need one word of alias */ - NXDIDefToken(pParse); - if(pParse->iToken != DCLOSE) - { - sprintf(pError,"ERROR: expected alias , got %s",pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - } - - /* move back in hierarchy */ - for(i = 0; i < pParse->iDepth; i++) - { - iRet = NXclosegroup(hfil); - if(iRet == NX_ERROR) - { - return NX_ERROR; - } - } - - /* open the link instead */ - return NXDopenalias(hfil, pDict, pParse->pToken); - - } -/*------------------------------------------------------------------------*/ - int NXDIDefParse(NXhandle hFil, NXdict pDict, ParDat *pParse) - { - int iRet; - char pError[256]; - - pParse->iToken = -1; - while(pParse->iToken != DEND) - { - NXDIDefToken(pParse); /* next token */ - switch(pParse->iToken) - { - case DEND: - break; - case DSLASH: - iRet = NXDIParsePath(hFil, pParse); - if(iRet == NX_ERROR) - { - return NX_ERROR; - } - break; - case DSDS: - iRet = NXDIParseSDS(hFil, pParse); - if(iRet == NX_ERROR) - { - return NX_ERROR; - } - pParse->iTerminal = TERMSDS; - break; - case DLINK: - iRet = NXDIParseLink(hFil,pDict, pParse); - if(iRet == NX_ERROR) - { - return NX_ERROR; - } - pParse->iTerminal = TERMLINK; - break; - case DGROUP: - pParse->iTerminal = TERMVG; - return NX_OK; - default: - sprintf(pError, - "ERROR: Definition String parse error: %s not permitted here", - pParse->pToken); - NXIReportError(NXpData,pError); - return NX_ERROR; - break; - } - } - return NX_OK; } -/*----------------------------------------------------------------------*/ - NXstatus NXDIUnwind(NXhandle hFil, int iDepth) - { - int i, iRet; - - for(i = 0; i < iDepth; i++) - { - iRet = NXclosegroup(hFil); - if(iRet != NX_OK) - { - return NX_ERROR; - } - } - return NX_OK; + return; } -/*-------------------- The Data Transfer Functions ----------------------*/ - NXstatus NXDopendef(NXhandle hfil, NXdict dict, char *pDef) - { - NXdict pDict; - ParDat pParse; - int iRet, i, iStat; + /* not reached */ + return; +} - pDict = NXDIAssert(dict); - - /* parse and act on definition string */ - pParse.iMayCreate = 1; - pParse.pPtr = pDef; - pParse.iDepth = 0; - iRet = NXDIDefParse(hfil,pDict,&pParse); - if(iRet == NX_ERROR) - { - /* unwind and throw up */ - iRet = NXDIUnwind(hfil,pParse.iDepth); - return NX_ERROR; - } - - return iRet; - } -/*------------------------------------------------------------------------*/ - NXstatus NXDopenalias(NXhandle hfil, NXdict dict, char *pAlias) - { - NXdict pDict; - int iRet; - char pDefinition[2048]; - pDynString pReplaced = NULL; - - pDict = NXDIAssert(dict); - - /* get Definition String */ - iRet = NXDget(pDict,pAlias,pDefinition,2047); - if(iRet != NX_OK) - { - sprintf(pDefinition,"ERROR: alias %s not recognized",pAlias); - NXIReportError(NXpData,pDefinition); - return NX_ERROR; - } - - /* do the text replacement */ - pReplaced = NXDItextreplace(dict,pDefinition); - if(!pReplaced) - { - return NX_ERROR; - } - - /* call NXDopendef */ - iRet = NXDopendef(hfil,dict,GetCharArray(pReplaced)); - DeleteDynString(pReplaced); - return iRet; - } -/*------------------------------------------------------------------------*/ - NXstatus NXDputdef(NXhandle hFil, NXdict dict, char *pDef, void *pData) - { - NXdict pDict; - ParDat pParse; - int iRet, i, iStat; - - pDict = NXDIAssert(dict); - - /* parse and act on definition string */ - pParse.iMayCreate = 1; - pParse.pPtr = pDef; - pParse.iDepth = 0; -#ifdef DEFDEBUG - printf("Putting: %s\n",pDef); -#endif - iRet = NXDIDefParse(hFil,pDict,&pParse); - if(iRet == NX_ERROR) - { - NXDIUnwind(hFil,pParse.iDepth); - return NX_ERROR; - } - - - /* only SDS can be written */ - if(pParse.iTerminal != TERMSDS) - { - NXIReportError(NXpData, - "ERROR: can only write to an SDS!"); - iStat = NX_ERROR; - } - else - { - /* the SDS should be open by now, write it */ - iStat = NXputdata(hFil, pData); - iRet = NXclosedata(hFil); - } +/*-----------------------------------------------------------------------*/ +static void NXDIAttValue(ParDat * sStat) +{ + int i; - /* rewind the hierarchy */ - iRet = NXDIUnwind(hFil,pParse.iDepth); - if(iRet != NX_OK) - { - return NX_ERROR; - } - return iStat; - } -/*------------------------------------------------------------------------*/ - NXstatus NXDputalias(NXhandle hFil, NXdict dict, char *pAlias, void *pData) - { - NXdict pDict; - int iRet; - char pDefinition[2048]; - pDynString pReplaced = NULL; + sStat->pToken[0] = '\0'; - pDict = NXDIAssert(dict); - - /* get Definition String */ - iRet = NXDget(pDict,pAlias,pDefinition,2047); - if(iRet != NX_OK) - { - sprintf(pDefinition,"ERROR: alias %s not recognized",pAlias); - NXIReportError(NXpData,pDefinition); - return NX_ERROR; - } - - /* do text replacement */ - pReplaced = NXDItextreplace(dict,pDefinition); - if(!pReplaced) - { - return NX_ERROR; - } - - /* call NXDputdef */ - iRet = NXDputdef(hFil,dict,GetCharArray(pReplaced),pData); - DeleteDynString(pReplaced); - return iRet; - } -/*------------------------------------------------------------------------*/ - NXstatus NXDgetdef(NXhandle hFil, NXdict dict, char *pDef, void *pData) - { - NXdict pDict; - ParDat pParse; - int iRet, i, iStat; - - pDict = NXDIAssert(dict); - - /* parse and act on definition string */ - pParse.iMayCreate = 0; - pParse.pPtr = pDef; - pParse.iDepth = 0; -#ifdef DEFDEBUG - printf("Getting: %s\n",pDef); -#endif - iRet = NXDIDefParse(hFil,pDict,&pParse); - if(iRet == NX_ERROR) - { - /* unwind and throw up */ - NXDIUnwind(hFil,pParse.iDepth); - return NX_ERROR; - } - - - /* only SDS can be written */ - if(pParse.iTerminal != TERMSDS) - { - NXIReportError(NXpData, - "ERROR: can only write to an SDS!"); - iStat = NX_ERROR; - } - else - { - /* the SDS should be open by now, read it */ - iStat = NXgetdata(hFil, pData); - iRet = NXclosedata(hFil); - } - - - /* rewind the hierarchy */ - iRet = NXDIUnwind(hFil,pParse.iDepth); - if(iRet != NX_OK) - { - return NX_ERROR; - } - return iStat; - } - -/*------------------------------------------------------------------------*/ - NXstatus NXDgetalias(NXhandle hFil, NXdict dict, char *pAlias, void *pData) - { - NXdict pDict; - int iRet; - char pDefinition[2048]; - pDynString pReplaced = NULL; - - pDict = NXDIAssert(dict); - - /* get Definition String */ - iRet = NXDget(pDict,pAlias,pDefinition,2047); - if(iRet != NX_OK) - { - sprintf(pDefinition,"ERROR: alias %s not recognized",pAlias); - NXIReportError(NXpData,pDefinition); - return NX_ERROR; - } - - /* do text replacement */ - pReplaced = NXDItextreplace(dict,pDefinition); - if(!pReplaced) - { - return NX_ERROR; - } - - /* call NXDgetdef */ - iRet = NXDgetdef(hFil,dict,GetCharArray(pReplaced),pData); - DeleteDynString(pReplaced); - return iRet; - } -/*------------------------------------------------------------------------*/ - - NXstatus NXDinfodef(NXhandle hFil, NXdict dict, char *pDef, int *rank, - int dimension[], int *iType) - { - NXdict pDict; - ParDat pParse; - int iRet, i, iStat; - - pDict = NXDIAssert(dict); - - /* parse and act on definition string */ - pParse.iMayCreate = 0; - pParse.pPtr = pDef; - pParse.iDepth = 0; -#ifdef DEFDEBUG - printf("Getting: %s\n",pDef); -#endif - iRet = NXDIDefParse(hFil,pDict,&pParse); - if(iRet == NX_ERROR) - { - /* unwind and throw up */ - NXDIUnwind(hFil,pParse.iDepth); - return NX_ERROR; - } - - - /* only SDS can be written */ - if(pParse.iTerminal != TERMSDS) - { - NXIReportError(NXpData, - "ERROR: can only write to an SDS!"); - iStat = NX_ERROR; - } - else - { - /* the SDS should be open by now, read it */ - iStat = NXgetinfo(hFil, rank,dimension, iType); - iRet = NXclosedata(hFil); - } - - - /* rewind the hierarchy */ - iRet = NXDIUnwind(hFil,pParse.iDepth); - if(iRet != NX_OK) - { - return NX_ERROR; - } - return iStat; - } - -/*------------------------------------------------------------------------*/ - - NXstatus NXDinfoalias(NXhandle hFil, NXdict dict, char *pAlias, int *rank, - int dimension[], int *iType) - { - NXdict pDict; - int iRet; - char pDefinition[2048]; - pDynString pReplaced = NULL; - - pDict = NXDIAssert(dict); - - /* get Definition String */ - iRet = NXDget(pDict,pAlias,pDefinition,2047); - if(iRet != NX_OK) - { - sprintf(pDefinition,"ERROR: alias %s not recognized",pAlias); - NXIReportError(NXpData,pDefinition); - return NX_ERROR; - } - - /* do text replacement */ - pReplaced = NXDItextreplace(dict,pDefinition); - if(!pReplaced) - { - return NX_ERROR; - } - - /* call NXDgetdef */ - iRet = NXDinfodef(hFil,dict,GetCharArray(pReplaced),rank,dimension,iType); - DeleteDynString(pReplaced); - return iRet; + /* skip whitespace */ + while ((*(sStat->pPtr) == ' ') || (*(sStat->pPtr) == '\t')) { + sStat->pPtr++; } + if (*(sStat->pPtr) == ',') { + sStat->iToken = DKOMMA; + sStat->pToken[0] = *(sStat->pPtr); + sStat->pPtr++; + return; + } else if (*(sStat->pPtr) == '\0') { + sStat->iToken = DEND; + sStat->pToken[0] = *(sStat->pPtr); + sStat->pPtr++; + return; + } else if (*(sStat->pPtr) == '{') { + sStat->iToken = DOPEN; + sStat->pToken[0] = *(sStat->pPtr); + sStat->pPtr++; + return; + } else if (*(sStat->pPtr) == '}') { + sStat->iToken = DCLOSE; + sStat->pToken[0] = *(sStat->pPtr); + sStat->pPtr++; + return; + } else { + sStat->iToken = DWORD; + /* copy word to pToken */ + i = 0; + while ((*(sStat->pPtr) != ' ') && (*(sStat->pPtr) != '\t') && + (*(sStat->pPtr) != '\0') && + (*(sStat->pPtr) != ',') && (*(sStat->pPtr) != '}')) { + sStat->pToken[i] = *(sStat->pPtr); + sStat->pPtr++; + i++; + } + sStat->pToken[i] = '\0'; + return; + } + /* not reached */ + return; +} + + /*------------------------------------------------------------------------*/ - NXstatus NXDdeflink(NXhandle hFil, NXdict dict, - char *pTarget, char *pVictim) - { - NXdict pDict; - ParDat pParseT, pParseV; - int iRet, i, iStat; - NXlink sLink; - pDict = NXDIAssert(dict); +int NXDIParsePath(NXhandle hfil, ParDat * pParse) +{ + int iRet, iToken; + void (*ErrFunc) (void *pData, char *pErr); + char pName[132], pClass[132]; + char pError[256]; - -#ifdef DEFDEBUG - printf("Linking: %s\n",pVictim); - printf("To: %s\n", pTarget); -#endif - - - /* parse Victim */ - pParseV.iMayCreate = 0; - pParseV.pPtr = pVictim; - pParseV.iDepth = 0; - iRet = NXDIDefParse(hFil,pDict,&pParseV); - if(iRet == NX_ERROR) - { - /* unwind and throw up */ - NXDIUnwind(hFil,pParseV.iDepth); - return NX_ERROR; - } - /* get link data */ - if(pParseV.iTerminal == TERMSDS) - { - NXgetdataID(hFil,&sLink); - iRet = NXclosedata(hFil); - if(iRet != NX_OK) - { - /* unwind and throw up */ - NXDIUnwind(hFil,pParseV.iDepth); - return NX_ERROR; - } - } - else if(pParseV.iTerminal == TERMVG) - { - NXgetgroupID(hFil,&sLink); - } - else - { - assert(0); /* serious programming error */ - } - /* Unwind */ - iRet = NXDIUnwind(hFil,pParseV.iDepth); - if(iRet != NX_OK) - { - return NX_ERROR; - } - - /* parse Target */ - pParseT.iMayCreate = 1; - pParseT.pPtr = pTarget; - pParseT.iDepth = 0; - iRet = NXDIDefParse(hFil,pDict,&pParseT); - if(iRet == NX_ERROR) - { - /* unwind and throw up */ - NXDIUnwind(hFil,pParseT.iDepth); - return NX_ERROR; - } - /* check it being a vGroup! */ - if(pParseT.iTerminal != TERMVG) - { - NXIReportError(NXpData,"ERROR: can link only into a vGroup"); - NXDIUnwind(hFil,pParseT.iDepth); - return NX_ERROR; - } - - /* link, finally */ - iRet = NXmakelink(hFil,&sLink); - /* Unwind anyway */ - iStat = NXDIUnwind(hFil,pParseT.iDepth); - if(iStat != NX_OK) - { - return NX_ERROR; - } - return iStat; + /* get the name */ + NXDIDefToken(pParse); /* next token */ + if ((pParse->iToken == DSDS) || (pParse->iToken == DGROUP) + || (pParse->iToken == DLINK)) { + /* put back & OK */ + pParse->pPtr -= strlen(pParse->pToken); + return NX_OK; } -/*--------------------------------------------------------------------------*/ - NXstatus NXDaliaslink(NXhandle hFil, NXdict dict, - char *pTarget, char *pVictim) - { - char pTargetDef[2048], pVictimDef[2048]; - int iRet; - NXdict pDict; - pDynString pRep1 = NULL, pRep2 = NULL; - - pDict = NXDIAssert(dict); - - /* get Target Definition String */ - iRet = NXDget(pDict,pTarget,pTargetDef,2047); - if(iRet != NX_OK) - { - sprintf(pTargetDef,"ERROR: alias %s not recognized",pTarget); - NXIReportError(NXpData,pTargetDef); - return NX_ERROR; - } - - /* get Victim definition string */ - iRet = NXDget(pDict,pVictim,pVictimDef,2047); - if(iRet != NX_OK) - { - sprintf(pTargetDef,"ERROR: alias %s not recognized",pTarget); - NXIReportError(NXpData,pTargetDef); - return NX_ERROR; - } - - /* do replacements */ - pRep1 = NXDItextreplace(dict,pTargetDef); - pRep2 = NXDItextreplace(dict,pVictimDef); - if( (!pRep1) || (!pRep2) ) - { - if(pRep1) - DeleteDynString(pRep1); - if(pRep2) - DeleteDynString(pRep2); - return NX_ERROR; - } - - /* call NXdeflin */ - iRet = NXDdeflink(hFil,pDict,GetCharArray(pRep1),GetCharArray(pRep2)); - DeleteDynString(pRep1); - DeleteDynString(pRep2); - return iRet; + if (pParse->iToken != DWORD) { + sprintf(pError, "ERROR: parse error at %s, expected vGroup name", + pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; } + strcpy(pName, pParse->pToken); + + /* now we expect a komma */ + NXDIDefToken(pParse); /* next token */ + if (pParse->iToken != DKOMMA) { + sprintf(pError, "ERROR: parse error at %s, expected komma", + pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + + /* next must be the class */ + NXDIDefToken(pParse); /* next token */ + if (pParse->iToken != DWORD) { + sprintf(pError, "ERROR: parse error at %s, expected vGroup class", + pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + strcpy(pClass, pParse->pToken); + + /* done reading, ACTION, first install dummy error handler */ + ErrFunc = NXIReportError; + NXMSetError(NXpData, DummyError); + + /* try opening vGroup */ + iRet = NXopengroup(hfil, pName, pClass); + NXMSetError(NXpData, ErrFunc); + if (iRet == NX_OK) { + pParse->iDepth++; + return NX_OK; + } else { + /* we need to create it, if we may */ + if (pParse->iMayCreate) { + iRet = NXmakegroup(hfil, pName, pClass); + if (iRet != NX_OK) { + /* a comment on this one has already been written! */ + return iRet; + } + iRet = NXopengroup(hfil, pName, pClass); + if (iRet != NX_OK) { + /* a comment on this one has already been written! */ + return iRet; + } + pParse->iDepth++; + return NX_OK; + } else { + /* this is an error */ + sprintf(pError, "ERROR: vGroup %s, %s NOT found", pName, pClass); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + } + /* not reached */ + return NX_ERROR; +} + +/*------------------------------------------------------------------------*/ + +static int NXDIParseAttr(ParDat * pParse, int iList) +{ + char pError[256]; + int iRet; + AttItem sAtt; + + /* a { is expected */ + NXDIDefToken(pParse); + if (pParse->iToken != DOPEN) { + sprintf(pError, "ERROR: expected {, got %s", pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + + /* a word is expected */ + NXDIDefToken(pParse); + if (pParse->iToken != DWORD) { + sprintf(pError, "ERROR: expected attribute name, got %s", + pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + strcpy(sAtt.name, pParse->pToken); + + /* a , is expected */ + NXDIDefToken(pParse); + if (pParse->iToken != DKOMMA) { + sprintf(pError, "ERROR: expected , , got %s", pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + + /* a word is expected */ + NXDIAttValue(pParse); + if (pParse->iToken != DWORD) { + sprintf(pError, "ERROR: expected attribute value, got %s", + pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + strcpy(sAtt.value, pParse->pToken); + + /* a } is expected */ + NXDIDefToken(pParse); + if (pParse->iToken != DCLOSE) { + sprintf(pError, "ERROR: expected }, got %s", pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + + /* enter into list */ + LLDnodeAppendFrom(iList, &sAtt); + return NX_OK; +} + +/*------------------------------------------------------------------------*/ +static int NXDIParseDim(ParDat * pParse, int *iDim) +{ + char pError[256]; + int iRet, i; + + /* initialise dimensions to 0 */ + for (i = 0; i < NX_MAXRANK; i++) { + iDim[i] = 0; + } + + NXDIDefToken(pParse); + if (pParse->iToken != DOPEN) { + sprintf(pError, "ERROR: expected {, got %s", pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + + i = 0; + while (pParse->iToken != DCLOSE) { + /* get a number */ + NXDIDefToken(pParse); + if (pParse->iToken != DWORD) { + sprintf(pError, "ERROR: expected number, got %s", pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + iDim[i] = atoi(pParse->pToken); + i++; + /* next must be close of komma */ + NXDIDefToken(pParse); + if ((pParse->iToken != DKOMMA) && (pParse->iToken != DCLOSE)) { + sprintf(pError, "ERROR: expected , or }, got %s", pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + if (pParse->iToken == DCLOSE) { + break; + } + } + return NX_OK; +} + +/*------------------------------------------------------------------------*/ +static TokDat tDatType[] = { + {"DFNT_FLOAT32", NX_FLOAT32}, + {"DFNT_FLOAT64", NX_FLOAT64}, + {"DFNT_INT8", NX_INT8}, + {"DFNT_UINT8", NX_UINT8}, + {"DFNT_INT16", NX_INT16}, + {"DFNT_UINT16", NX_UINT16}, + {"DFNT_INT32", NX_INT32}, + {"DFNT_UINT32", NX_UINT32}, + {"DFNT_CHAR", NX_CHAR}, + {"NX_FLOAT32", NX_FLOAT32}, + {"NX_FLOAT64", NX_FLOAT64}, + {"NX_INT8", NX_INT8}, + {"NX_UINT8", NX_UINT8}, + {"NX_INT16", NX_INT16}, + {"NX_UINT16", NX_UINT16}, + {"NX_INT32", NX_INT32}, + {"NX_UINT32", NX_UINT32}, + {"NX_CHAR", NX_CHAR}, + {NULL, -122} +}; + + + +static int NXDIParseType(ParDat * pParse, int *iType) +{ + char pError[256]; + int i = 0; + + NXDIDefToken(pParse); + if (pParse->iToken != DWORD) { + sprintf(pError, "ERROR: expected data type, got %s", pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + + /* try to interpret data type */ + while (tDatType[i].iCode > 0) { + if (strcmp(tDatType[i].pText, pParse->pToken) == 0) { + *iType = tDatType[i].iCode; + return NX_OK; + } + i++; + } + /* if we are here, the data type has not been recognized. Reason for + some boring error reporting code + */ + sprintf(pError, "ERROR: %s not recognized as valid data type", + pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; +} + /*-------------------------------------------------------------------------*/ - static void SNXFormatTime(char *pBuffer, int iBufLen) - { - time_t iDate; - struct tm *psTime; +static int NXDIParseSDS(NXhandle hfil, ParDat * pParse) +{ + int iType = NX_FLOAT32; + int iRank = 1; + int iCompress = NX_COMP_NONE; + int iDim[NX_MAXRANK], iChunk[NX_MAXRANK]; + int iList, iChunkDefined = 0; + int iRet, iStat, i; + char pError[256]; + char pName[NX_MAXNAMELEN]; + void (*ErrFunc) (void *pData, char *pErr); + AttItem sAtt; + + + iDim[0] = 1; + /* first find the name */ + NXDIDefToken(pParse); + if (pParse->iToken != DWORD) { + sprintf(pError, "ERROR: parsing, expected name, got %s", + pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + strcpy(pName, pParse->pToken); + + /* create the attribute list */ + iList = LLDcreate(sizeof(AttItem)); + if (iList < 0) { + NXIReportError(NXpData, "ERROR: cannot create list in NXDIParseSDS"); + return NX_ERROR; + } + + NXDIDefToken(pParse); + while (pParse->iToken != DEND) { + switch (pParse->iToken) { + case DRANK: /* rank */ + NXDIDefToken(pParse); /* advance */ + if (pParse->iToken != DWORD) { + sprintf(pError, "ERROR: expected int, got %s", pParse->pToken); + NXIReportError(NXpData, pError); + LLDdelete(iList); + return NX_ERROR; + } + iRank = atoi(pParse->pToken); + break; + case CHUNK: /* chunk size for compression */ + iRet = NXDIParseDim(pParse, iChunk); + if (iRet == NX_ERROR) { + LLDdelete(iList); + return iRet; + } + iChunkDefined = 1; + break; + case DDIM: + iRet = NXDIParseDim(pParse, iDim); + if (iRet == NX_ERROR) { + LLDdelete(iList); + return iRet; + } + break; + case DTYPE: + iRet = NXDIParseType(pParse, &iType); + if (iRet == NX_ERROR) { + LLDdelete(iList); + return iRet; + } + break; + case DATTR: + iRet = NXDIParseAttr(pParse, iList); + if (iRet == NX_ERROR) { + LLDdelete(iList); + return iRet; + } + break; + case DLZW: + iCompress = NX_COMP_LZW; + break; + case DRLE: + iCompress = NX_COMP_RLE; + break; + case DHUF: + iCompress = NX_COMP_HUF; + break; + case DEND: + break; + default: + sprintf(pError, "ERROR: cannot identify token %s", pParse->pToken); + NXIReportError(NXpData, pError); + LLDdelete(iList); + return NX_ERROR; + + } + NXDIDefToken(pParse); + } + + /* whew! got all information for doing the SDS + However, if the chunk sizes for compression have not + been set, default them to the dimensions of the data set + */ + if (iChunkDefined == 0) { + for (i = 0; i < iRank; i++) { + iChunk[i] = iDim[i]; + } + } + if (iChunk[0] < 0) { + iChunk[0] = 1; + } + + /* first install dummy error handler, try open it, then + deinstall again and create if allowed + */ + ErrFunc = NXIReportError; + NXMSetError(NXpData, DummyError); + + /* try opening SDS */ + iRet = NXopendata(hfil, pName); + NXMSetError(NXpData, ErrFunc); + if (iRet == NX_OK) { + LLDdelete(iList); + return NX_OK; + } else { + /* we need to create it, if we may */ + if (pParse->iMayCreate) { + iRet = NXcompmakedata(hfil, pName, iType, iRank, iDim, + iCompress, iChunk); + if (iRet != NX_OK) { + /* a comment on this one has already been written! */ + LLDdelete(iList); + return iRet; + } + iRet = NXopendata(hfil, pName); + if (iRet != NX_OK) { + /* a comment on this one has already been written! */ + LLDdelete(iList); + return iRet; + } + + /* put attributes in */ + iRet = LLDnodePtr2First(iList); + while (iRet != 0) { + LLDnodeDataTo(iList, &sAtt); + iStat = NXputattr(hfil, sAtt.name, + sAtt.value, strlen(sAtt.value), NX_CHAR); + if (iStat != NX_OK) { + /* NeXus already complained bitterly */ + LLDdelete(iList); + return iStat; + } + iRet = LLDnodePtr2Next(iList); + } + LLDdelete(iList); + return NX_OK; + } else { + /* this is an error */ + sprintf(pError, "ERROR: SDS %s NOT found", pName); + NXIReportError(NXpData, pError); + LLDdelete(iList); + return NX_ERROR; + } + } + return NX_OK; +} + +/*------------------------------------------------------------------------*/ +static int NXDIParseLink(NXhandle hfil, NXdict pDict, ParDat * pParse) +{ + char pError[256]; + int i, iRet; + + /* need one word of alias */ + NXDIDefToken(pParse); + if (pParse->iToken != DCLOSE) { + sprintf(pError, "ERROR: expected alias , got %s", pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + } + + /* move back in hierarchy */ + for (i = 0; i < pParse->iDepth; i++) { + iRet = NXclosegroup(hfil); + if (iRet == NX_ERROR) { + return NX_ERROR; + } + } + + /* open the link instead */ + return NXDopenalias(hfil, pDict, pParse->pToken); + +} + +/*------------------------------------------------------------------------*/ +int NXDIDefParse(NXhandle hFil, NXdict pDict, ParDat * pParse) +{ + int iRet; + char pError[256]; + + pParse->iToken = -1; + while (pParse->iToken != DEND) { + NXDIDefToken(pParse); /* next token */ + switch (pParse->iToken) { + case DEND: + break; + case DSLASH: + iRet = NXDIParsePath(hFil, pParse); + if (iRet == NX_ERROR) { + return NX_ERROR; + } + break; + case DSDS: + iRet = NXDIParseSDS(hFil, pParse); + if (iRet == NX_ERROR) { + return NX_ERROR; + } + pParse->iTerminal = TERMSDS; + break; + case DLINK: + iRet = NXDIParseLink(hFil, pDict, pParse); + if (iRet == NX_ERROR) { + return NX_ERROR; + } + pParse->iTerminal = TERMLINK; + break; + case DGROUP: + pParse->iTerminal = TERMVG; + return NX_OK; + default: + sprintf(pError, + "ERROR: Definition String parse error: %s not permitted here", + pParse->pToken); + NXIReportError(NXpData, pError); + return NX_ERROR; + break; + } + } + return NX_OK; +} + +/*----------------------------------------------------------------------*/ +NXstatus NXDIUnwind(NXhandle hFil, int iDepth) +{ + int i, iRet; + + for (i = 0; i < iDepth; i++) { + iRet = NXclosegroup(hFil); + if (iRet != NX_OK) { + return NX_ERROR; + } + } + return NX_OK; +} + +/*-------------------- The Data Transfer Functions ----------------------*/ +NXstatus NXDopendef(NXhandle hfil, NXdict dict, char *pDef) +{ + NXdict pDict; + ParDat pParse; + int iRet, i, iStat; + + pDict = NXDIAssert(dict); + + /* parse and act on definition string */ + pParse.iMayCreate = 1; + pParse.pPtr = pDef; + pParse.iDepth = 0; + iRet = NXDIDefParse(hfil, pDict, &pParse); + if (iRet == NX_ERROR) { + /* unwind and throw up */ + iRet = NXDIUnwind(hfil, pParse.iDepth); + return NX_ERROR; + } + + return iRet; +} + +/*------------------------------------------------------------------------*/ +NXstatus NXDopenalias(NXhandle hfil, NXdict dict, char *pAlias) +{ + NXdict pDict; + int iRet; + char pDefinition[2048]; + pDynString pReplaced = NULL; + + pDict = NXDIAssert(dict); + + /* get Definition String */ + iRet = NXDget(pDict, pAlias, pDefinition, 2047); + if (iRet != NX_OK) { + sprintf(pDefinition, "ERROR: alias %s not recognized", pAlias); + NXIReportError(NXpData, pDefinition); + return NX_ERROR; + } + + /* do the text replacement */ + pReplaced = NXDItextreplace(dict, pDefinition); + if (!pReplaced) { + return NX_ERROR; + } + + /* call NXDopendef */ + iRet = NXDopendef(hfil, dict, GetCharArray(pReplaced)); + DeleteDynString(pReplaced); + return iRet; +} + +/*------------------------------------------------------------------------*/ +NXstatus NXDputdef(NXhandle hFil, NXdict dict, char *pDef, void *pData) +{ + NXdict pDict; + ParDat pParse; + int iRet, i, iStat; + + pDict = NXDIAssert(dict); + + /* parse and act on definition string */ + pParse.iMayCreate = 1; + pParse.pPtr = pDef; + pParse.iDepth = 0; +#ifdef DEFDEBUG + printf("Putting: %s\n", pDef); +#endif + iRet = NXDIDefParse(hFil, pDict, &pParse); + if (iRet == NX_ERROR) { + NXDIUnwind(hFil, pParse.iDepth); + return NX_ERROR; + } + + + /* only SDS can be written */ + if (pParse.iTerminal != TERMSDS) { + NXIReportError(NXpData, "ERROR: can only write to an SDS!"); + iStat = NX_ERROR; + } else { + /* the SDS should be open by now, write it */ + iStat = NXputdata(hFil, pData); + iRet = NXclosedata(hFil); + } + + + /* rewind the hierarchy */ + iRet = NXDIUnwind(hFil, pParse.iDepth); + if (iRet != NX_OK) { + return NX_ERROR; + } + return iStat; +} + +/*------------------------------------------------------------------------*/ +NXstatus NXDputalias(NXhandle hFil, NXdict dict, char *pAlias, void *pData) +{ + NXdict pDict; + int iRet; + char pDefinition[2048]; + pDynString pReplaced = NULL; + + pDict = NXDIAssert(dict); + + /* get Definition String */ + iRet = NXDget(pDict, pAlias, pDefinition, 2047); + if (iRet != NX_OK) { + sprintf(pDefinition, "ERROR: alias %s not recognized", pAlias); + NXIReportError(NXpData, pDefinition); + return NX_ERROR; + } + + /* do text replacement */ + pReplaced = NXDItextreplace(dict, pDefinition); + if (!pReplaced) { + return NX_ERROR; + } + + /* call NXDputdef */ + iRet = NXDputdef(hFil, dict, GetCharArray(pReplaced), pData); + DeleteDynString(pReplaced); + return iRet; +} + +/*------------------------------------------------------------------------*/ +NXstatus NXDgetdef(NXhandle hFil, NXdict dict, char *pDef, void *pData) +{ + NXdict pDict; + ParDat pParse; + int iRet, i, iStat; + + pDict = NXDIAssert(dict); + + /* parse and act on definition string */ + pParse.iMayCreate = 0; + pParse.pPtr = pDef; + pParse.iDepth = 0; +#ifdef DEFDEBUG + printf("Getting: %s\n", pDef); +#endif + iRet = NXDIDefParse(hFil, pDict, &pParse); + if (iRet == NX_ERROR) { + /* unwind and throw up */ + NXDIUnwind(hFil, pParse.iDepth); + return NX_ERROR; + } + + + /* only SDS can be written */ + if (pParse.iTerminal != TERMSDS) { + NXIReportError(NXpData, "ERROR: can only write to an SDS!"); + iStat = NX_ERROR; + } else { + /* the SDS should be open by now, read it */ + iStat = NXgetdata(hFil, pData); + iRet = NXclosedata(hFil); + } + + + /* rewind the hierarchy */ + iRet = NXDIUnwind(hFil, pParse.iDepth); + if (iRet != NX_OK) { + return NX_ERROR; + } + return iStat; +} + +/*------------------------------------------------------------------------*/ +NXstatus NXDgetalias(NXhandle hFil, NXdict dict, char *pAlias, void *pData) +{ + NXdict pDict; + int iRet; + char pDefinition[2048]; + pDynString pReplaced = NULL; + + pDict = NXDIAssert(dict); + + /* get Definition String */ + iRet = NXDget(pDict, pAlias, pDefinition, 2047); + if (iRet != NX_OK) { + sprintf(pDefinition, "ERROR: alias %s not recognized", pAlias); + NXIReportError(NXpData, pDefinition); + return NX_ERROR; + } + + /* do text replacement */ + pReplaced = NXDItextreplace(dict, pDefinition); + if (!pReplaced) { + return NX_ERROR; + } + + /* call NXDgetdef */ + iRet = NXDgetdef(hFil, dict, GetCharArray(pReplaced), pData); + DeleteDynString(pReplaced); + return iRet; +} + +/*------------------------------------------------------------------------*/ + +NXstatus NXDinfodef(NXhandle hFil, NXdict dict, char *pDef, int *rank, + int dimension[], int *iType) +{ + NXdict pDict; + ParDat pParse; + int iRet, i, iStat; + + pDict = NXDIAssert(dict); + + /* parse and act on definition string */ + pParse.iMayCreate = 0; + pParse.pPtr = pDef; + pParse.iDepth = 0; +#ifdef DEFDEBUG + printf("Getting: %s\n", pDef); +#endif + iRet = NXDIDefParse(hFil, pDict, &pParse); + if (iRet == NX_ERROR) { + /* unwind and throw up */ + NXDIUnwind(hFil, pParse.iDepth); + return NX_ERROR; + } + + + /* only SDS can be written */ + if (pParse.iTerminal != TERMSDS) { + NXIReportError(NXpData, "ERROR: can only write to an SDS!"); + iStat = NX_ERROR; + } else { + /* the SDS should be open by now, read it */ + iStat = NXgetinfo(hFil, rank, dimension, iType); + iRet = NXclosedata(hFil); + } + + + /* rewind the hierarchy */ + iRet = NXDIUnwind(hFil, pParse.iDepth); + if (iRet != NX_OK) { + return NX_ERROR; + } + return iStat; +} + +/*------------------------------------------------------------------------*/ + +NXstatus NXDinfoalias(NXhandle hFil, NXdict dict, char *pAlias, int *rank, + int dimension[], int *iType) +{ + NXdict pDict; + int iRet; + char pDefinition[2048]; + pDynString pReplaced = NULL; + + pDict = NXDIAssert(dict); + + /* get Definition String */ + iRet = NXDget(pDict, pAlias, pDefinition, 2047); + if (iRet != NX_OK) { + sprintf(pDefinition, "ERROR: alias %s not recognized", pAlias); + NXIReportError(NXpData, pDefinition); + return NX_ERROR; + } + + /* do text replacement */ + pReplaced = NXDItextreplace(dict, pDefinition); + if (!pReplaced) { + return NX_ERROR; + } + + /* call NXDgetdef */ + iRet = + NXDinfodef(hFil, dict, GetCharArray(pReplaced), rank, dimension, + iType); + DeleteDynString(pReplaced); + return iRet; +} + +/*------------------------------------------------------------------------*/ +NXstatus NXDdeflink(NXhandle hFil, NXdict dict, + char *pTarget, char *pVictim) +{ + NXdict pDict; + ParDat pParseT, pParseV; + int iRet, i, iStat; + NXlink sLink; + + pDict = NXDIAssert(dict); + + +#ifdef DEFDEBUG + printf("Linking: %s\n", pVictim); + printf("To: %s\n", pTarget); +#endif + + + /* parse Victim */ + pParseV.iMayCreate = 0; + pParseV.pPtr = pVictim; + pParseV.iDepth = 0; + iRet = NXDIDefParse(hFil, pDict, &pParseV); + if (iRet == NX_ERROR) { + /* unwind and throw up */ + NXDIUnwind(hFil, pParseV.iDepth); + return NX_ERROR; + } + /* get link data */ + if (pParseV.iTerminal == TERMSDS) { + NXgetdataID(hFil, &sLink); + iRet = NXclosedata(hFil); + if (iRet != NX_OK) { + /* unwind and throw up */ + NXDIUnwind(hFil, pParseV.iDepth); + return NX_ERROR; + } + } else if (pParseV.iTerminal == TERMVG) { + NXgetgroupID(hFil, &sLink); + } else { + assert(0); /* serious programming error */ + } + /* Unwind */ + iRet = NXDIUnwind(hFil, pParseV.iDepth); + if (iRet != NX_OK) { + return NX_ERROR; + } + + /* parse Target */ + pParseT.iMayCreate = 1; + pParseT.pPtr = pTarget; + pParseT.iDepth = 0; + iRet = NXDIDefParse(hFil, pDict, &pParseT); + if (iRet == NX_ERROR) { + /* unwind and throw up */ + NXDIUnwind(hFil, pParseT.iDepth); + return NX_ERROR; + } + /* check it being a vGroup! */ + if (pParseT.iTerminal != TERMVG) { + NXIReportError(NXpData, "ERROR: can link only into a vGroup"); + NXDIUnwind(hFil, pParseT.iDepth); + return NX_ERROR; + } + + /* link, finally */ + iRet = NXmakelink(hFil, &sLink); + /* Unwind anyway */ + iStat = NXDIUnwind(hFil, pParseT.iDepth); + if (iStat != NX_OK) { + return NX_ERROR; + } + return iStat; +} - /* make time string */ - iDate = time(NULL); - psTime = localtime(&iDate); - memset(pBuffer,0,iBufLen); - strftime(pBuffer,iBufLen,"%Y-%m-%d %H:%M:%S",psTime); - } /*--------------------------------------------------------------------------*/ - NXstatus NXUwriteglobals(NXhandle pFile, - char *filename, - char *owner, - char *adress, - char *phone, - char *email, - char *fax, - char *instrument) - { - char pBueffel[512]; - int iStat; - - /* store global attributes, now done by NXopen +NXstatus NXDaliaslink(NXhandle hFil, NXdict dict, + char *pTarget, char *pVictim) +{ + char pTargetDef[2048], pVictimDef[2048]; + int iRet; + NXdict pDict; + pDynString pRep1 = NULL, pRep2 = NULL; + + pDict = NXDIAssert(dict); + + /* get Target Definition String */ + iRet = NXDget(pDict, pTarget, pTargetDef, 2047); + if (iRet != NX_OK) { + sprintf(pTargetDef, "ERROR: alias %s not recognized", pTarget); + NXIReportError(NXpData, pTargetDef); + return NX_ERROR; + } + + /* get Victim definition string */ + iRet = NXDget(pDict, pVictim, pVictimDef, 2047); + if (iRet != NX_OK) { + sprintf(pTargetDef, "ERROR: alias %s not recognized", pTarget); + NXIReportError(NXpData, pTargetDef); + return NX_ERROR; + } + + /* do replacements */ + pRep1 = NXDItextreplace(dict, pTargetDef); + pRep2 = NXDItextreplace(dict, pVictimDef); + if ((!pRep1) || (!pRep2)) { + if (pRep1) + DeleteDynString(pRep1); + if (pRep2) + DeleteDynString(pRep2); + return NX_ERROR; + } + + /* call NXdeflin */ + iRet = NXDdeflink(hFil, pDict, GetCharArray(pRep1), GetCharArray(pRep2)); + DeleteDynString(pRep1); + DeleteDynString(pRep2); + return iRet; +} + +/*-------------------------------------------------------------------------*/ +static void SNXFormatTime(char *pBuffer, int iBufLen) +{ + time_t iDate; + struct tm *psTime; + + /* make time string */ + iDate = time(NULL); + psTime = localtime(&iDate); + memset(pBuffer, 0, iBufLen); + strftime(pBuffer, iBufLen, "%Y-%m-%d %H:%M:%S", psTime); +} + +/*--------------------------------------------------------------------------*/ +NXstatus NXUwriteglobals(NXhandle pFile, + char *filename, + char *owner, + char *adress, + char *phone, + char *email, char *fax, char *instrument) +{ + char pBueffel[512]; + int iStat; + + /* store global attributes, now done by NXopen iStat = NXputattr(pFile,"file_name",filename, - strlen(filename)+1,NX_CHAR); + strlen(filename)+1,NX_CHAR); if(iStat == NX_ERROR) { - return NX_ERROR; + return NX_ERROR; } - */ - - /* write creation time, now done by NXopen + */ + + /* write creation time, now done by NXopen SNXFormatTime(pBueffel,512); iStat = NXputattr(pFile,"file_time",pBueffel, - strlen(pBueffel)+1,NX_CHAR); + strlen(pBueffel)+1,NX_CHAR); if(iStat == NX_ERROR) { - return NX_ERROR; + return NX_ERROR; } - */ + */ - /* instrument name */ - iStat = NXputattr(pFile,"instrument",instrument, - strlen(instrument)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - return iStat; - } + /* instrument name */ + iStat = NXputattr(pFile, "instrument", instrument, + strlen(instrument) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + return iStat; + } - /* owner */ - iStat = NXputattr(pFile,"owner",owner, - strlen(owner)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - return iStat; - } + /* owner */ + iStat = NXputattr(pFile, "owner", owner, strlen(owner) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + return iStat; + } - /* Adress */ - iStat = NXputattr(pFile,"owner_adress",adress, - strlen(adress)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - return iStat; - } + /* Adress */ + iStat = NXputattr(pFile, "owner_adress", adress, + strlen(adress) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + return iStat; + } - /* phone */ - iStat = NXputattr(pFile,"owner_telephone_number",phone, - strlen(phone)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - return iStat; - } + /* phone */ + iStat = NXputattr(pFile, "owner_telephone_number", phone, + strlen(phone) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + return iStat; + } - /* fax */ - iStat = NXputattr(pFile,"owner_fax_number",fax, - strlen(fax)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - return iStat; - } + /* fax */ + iStat = NXputattr(pFile, "owner_fax_number", fax, + strlen(fax) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + return iStat; + } + + /* email */ + iStat = NXputattr(pFile, "owner_email", email, + strlen(email) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + return iStat; + } + return NX_OK; +} - /* email */ - iStat = NXputattr(pFile,"owner_email",email, - strlen(email)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - return iStat; - } - return NX_OK; - } /*-----------------------------------------------------------------------*/ - NXstatus NXUentergroup(NXhandle hFil, char *name, char *class) - { - void (*ErrFunc)(void *pData, char *pErr); - int iRet; +NXstatus NXUentergroup(NXhandle hFil, char *name, char *class) +{ + void (*ErrFunc) (void *pData, char *pErr); + int iRet; + + /* ACTION, first install dummy error handler */ + ErrFunc = NXIReportError; + NXMSetError(NXpData, DummyError); + + /* try opening vGroup */ + iRet = NXopengroup(hFil, name, class); + NXMSetError(NXpData, ErrFunc); + if (iRet == NX_OK) { + return NX_OK; + } else { + /* we need to create it */ + iRet = NXmakegroup(hFil, name, class); + if (iRet != NX_OK) { + /* a comment on this one has already been written! */ + return iRet; + } + iRet = NXopengroup(hFil, name, class); + if (iRet != NX_OK) { + /* a comment on this one has already been written! */ + return iRet; + } + } + return NX_OK; +} - /* ACTION, first install dummy error handler */ - ErrFunc = NXIReportError; - NXMSetError(NXpData, DummyError); - - /* try opening vGroup */ - iRet = NXopengroup(hFil, name, class); - NXMSetError(NXpData,ErrFunc); - if(iRet == NX_OK) - { - return NX_OK; - } - else - { - /* we need to create it */ - iRet = NXmakegroup(hFil,name,class); - if(iRet != NX_OK) - { - /* a comment on this one has already been written! */ - return iRet; - } - iRet = NXopengroup(hFil,name,class); - if(iRet != NX_OK) - { - /* a comment on this one has already been written! */ - return iRet; - } - } - return NX_OK; - } /*-----------------------------------------------------------------------*/ - NXstatus NXUenterdata(NXhandle hFil, char *label, int datatype, - int rank, int dim[], char *pUnits) - { - void (*ErrFunc)(void *pData, char *pErr); - int iRet; +NXstatus NXUenterdata(NXhandle hFil, char *label, int datatype, + int rank, int dim[], char *pUnits) +{ + void (*ErrFunc) (void *pData, char *pErr); + int iRet; + + /* ACTION, first install dummy error handler */ + ErrFunc = NXIReportError; + NXMSetError(NXpData, DummyError); + + /* try opening SDS */ + iRet = NXopendata(hFil, label); + NXMSetError(NXpData, ErrFunc); + if (iRet == NX_OK) { + return NX_OK; + } else { + /* we need to create it */ + iRet = NXmakedata(hFil, label, datatype, rank, dim); + if (iRet != NX_OK) { + /* a comment on this one has already been written! */ + return iRet; + } + iRet = NXopendata(hFil, label); + if (iRet != NX_OK) { + /* a comment on this one has already been written! */ + return iRet; + } + iRet = NXputattr(hFil, "Units", pUnits, strlen(pUnits) + 1, NX_INT8); + if (iRet != NX_OK) { + /* a comment on this one has already been written! */ + return iRet; + } + } + return NX_OK; +} - /* ACTION, first install dummy error handler */ - ErrFunc = NXIReportError; - NXMSetError(NXpData, DummyError); - - /* try opening SDS */ - iRet = NXopendata(hFil, label); - NXMSetError(NXpData,ErrFunc); - if(iRet == NX_OK) - { - return NX_OK; - } - else - { - /* we need to create it */ - iRet = NXmakedata(hFil,label, datatype, rank,dim); - if(iRet != NX_OK) - { - /* a comment on this one has already been written! */ - return iRet; - } - iRet = NXopendata(hFil,label); - if(iRet != NX_OK) - { - /* a comment on this one has already been written! */ - return iRet; - } - iRet = NXputattr(hFil, "Units",pUnits, - strlen(pUnits) + 1,NX_INT8); - if(iRet != NX_OK) - { - /* a comment on this one has already been written! */ - return iRet; - } - } - return NX_OK; - } /*-----------------------------------------------------------------------*/ - NXstatus NXUallocSDS(NXhandle hFil, void **pData) - { - int iDIM[NX_MAXRANK]; - int iRank,iType; - int iRet, i; - long lLength; +NXstatus NXUallocSDS(NXhandle hFil, void **pData) +{ + int iDIM[NX_MAXRANK]; + int iRank, iType; + int iRet, i; + long lLength; - /* get info */ - iRet = NXgetinfo(hFil,&iRank, iDIM, &iType); - if(iRet != NX_OK) - { - return iRet; - } + /* get info */ + iRet = NXgetinfo(hFil, &iRank, iDIM, &iType); + if (iRet != NX_OK) { + return iRet; + } - /* calculate Size */ - lLength = iDIM[0]; - for(i = 1; i < iRank; i++) - { - lLength *= iDIM[i]; - } - switch(iType) - { - case NX_FLOAT32: - lLength *= sizeof(float); - break; - case NX_FLOAT64: - lLength *= sizeof(double); - break; - case NX_INT8: - case NX_CHAR: - lLength *= sizeof(char); - break; - case NX_UINT8: - lLength *= sizeof(unsigned char); - break; - case NX_INT16: - lLength *= sizeof(short); - break; - case NX_UINT16: - lLength *= sizeof(unsigned short); - break; - case NX_INT32: - lLength *= sizeof(int); - break; - case NX_UINT32: - lLength *= sizeof(int); - break; - default: - NXIReportError(NXpData,"ERROR: Internal: number type not recoginized"); - return NX_ERROR; - } + /* calculate Size */ + lLength = iDIM[0]; + for (i = 1; i < iRank; i++) { + lLength *= iDIM[i]; + } + switch (iType) { + case NX_FLOAT32: + lLength *= sizeof(float); + break; + case NX_FLOAT64: + lLength *= sizeof(double); + break; + case NX_INT8: + case NX_CHAR: + lLength *= sizeof(char); + break; + case NX_UINT8: + lLength *= sizeof(unsigned char); + break; + case NX_INT16: + lLength *= sizeof(short); + break; + case NX_UINT16: + lLength *= sizeof(unsigned short); + break; + case NX_INT32: + lLength *= sizeof(int); + break; + case NX_UINT32: + lLength *= sizeof(int); + break; + default: + NXIReportError(NXpData, + "ERROR: Internal: number type not recoginized"); + return NX_ERROR; + } + + /* time to malloc */ + *pData = NULL; + *pData = malloc(lLength); + if (*pData == NULL) { + NXIReportError(NXpData, "ERROR: memory exhausted in NXUallocSDS"); + return NX_ERROR; + } + memset(*pData, 0, lLength); + return NX_OK; +} - /* time to malloc */ - *pData = NULL; - *pData = malloc(lLength); - if(*pData == NULL) - { - NXIReportError(NXpData,"ERROR: memory exhausted in NXUallocSDS"); - return NX_ERROR; - } - memset(*pData,0,lLength); - return NX_OK; - } /*----------------------------------------------------------------------*/ - NXstatus NXUfreeSDS(void **pData) - { - free(*pData); - *pData = NULL; - return NX_OK; - } - +NXstatus NXUfreeSDS(void **pData) +{ + free(*pData); + *pData = NULL; + return NX_OK; +} diff --git a/nxdict.h b/nxdict.h index 197a26a7..a7ee0623 100644 --- a/nxdict.h +++ b/nxdict.h @@ -10,13 +10,13 @@ ----------------------------------------------------------------------------*/ #ifndef NXDICTAPI #define NXDICTAPI -#include "napi.h" /* make sure, napi is included */ +#include "napi.h" /* make sure, napi is included */ /*-------------------- NXDict data types & defines ----------------------*/ #line 195 "nxdict.w" - typedef struct __NXdict *NXdict; +typedef struct __NXdict *NXdict; #line 2252 "nxdict.w" @@ -26,38 +26,36 @@ #line 201 "nxdict.w" - NXstatus NXDinitfromfile(char *filename, NXdict *pDict); - NXstatus NXDclose(NXdict handle, char *filename); +NXstatus NXDinitfromfile(char *filename, NXdict * pDict); +NXstatus NXDclose(NXdict handle, char *filename); - NXstatus NXDadd(NXdict handle, char *alias, char *DefString); - NXstatus NXDget(NXdict handle, char *alias, char *pBuffer, int iBufLen); - NXstatus NXDupdate(NXdict handle, char *alias, char *pNewVal); - NXstatus NXDtextreplace(NXdict handle, char *pDefString, char *pBuffer, - int iBuflen); +NXstatus NXDadd(NXdict handle, char *alias, char *DefString); +NXstatus NXDget(NXdict handle, char *alias, char *pBuffer, int iBufLen); +NXstatus NXDupdate(NXdict handle, char *alias, char *pNewVal); +NXstatus NXDtextreplace(NXdict handle, char *pDefString, char *pBuffer, + int iBuflen); #line 2256 "nxdict.w" -/*----------------- Dictionary added data transfer -----------------------*/ +/*----------------- Dictionary added data transfer -----------------------*/ #line 240 "nxdict.w" - NXstatus NXDputalias(NXhandle file, NXdict dict, - char *alias, void *pData); - NXstatus NXDputdef(NXhandle file, NXdict dict, char *pDefString, void *pData); +NXstatus NXDputalias(NXhandle file, NXdict dict, char *alias, void *pData); +NXstatus NXDputdef(NXhandle file, NXdict dict, char *pDefString, + void *pData); - NXstatus NXDgetalias(NXhandle file, NXdict dict, - char *alias, void *pData); - NXstatus NXDgetdef(NXhandle file, NXdict dict, char *pDefString, void *pData); - NXstatus NXDdefget(NXdict handle, char *pKey, char *pBuffer, int iBufLen); +NXstatus NXDgetalias(NXhandle file, NXdict dict, char *alias, void *pData); +NXstatus NXDgetdef(NXhandle file, NXdict dict, char *pDefString, + void *pData); +NXstatus NXDdefget(NXdict handle, char *pKey, char *pBuffer, int iBufLen); - NXstatus NXDaliaslink(NXhandle file, NXdict dict, - char *pAlias1, char *pAlias2); - NXstatus NXDdeflink(NXhandle file, NXdict dict, - char *pDef1, char *pDef2); +NXstatus NXDaliaslink(NXhandle file, NXdict dict, + char *pAlias1, char *pAlias2); +NXstatus NXDdeflink(NXhandle file, NXdict dict, char *pDef1, char *pDef2); - NXstatus NXDopenalias(NXhandle file, NXdict dict, - char *alias); - NXstatus NXDopendef(NXhandle file, NXdict dict, char *pDefString); +NXstatus NXDopenalias(NXhandle file, NXdict dict, char *alias); +NXstatus NXDopendef(NXhandle file, NXdict dict, char *pDefString); #line 2258 "nxdict.w" @@ -66,22 +64,19 @@ #line 310 "nxdict.w" - NXstatus NXUwriteglobals(NXhandle file, - char *filename, - char *owner, - char *adress, - char *phone, - char *email, - char *fax, - char *thing); +NXstatus NXUwriteglobals(NXhandle file, + char *filename, + char *owner, + char *adress, + char *phone, char *email, char *fax, char *thing); - NXstatus NXUentergroup(NXhandle hFil, char *name, char *class); - NXstatus NXUenterdata (NXhandle fileid, char* label, int datatype, - int rank, int dim[], char *pUnits); - - NXstatus NXUallocSDS(NXhandle hFil, void **pData); - NXstatus NXUfreeSDS(void **pData); +NXstatus NXUentergroup(NXhandle hFil, char *name, char *class); +NXstatus NXUenterdata(NXhandle fileid, char *label, int datatype, + int rank, int dim[], char *pUnits); + +NXstatus NXUallocSDS(NXhandle hFil, void **pData); +NXstatus NXUfreeSDS(void **pData); #line 2260 "nxdict.w" diff --git a/nxdump.c b/nxdump.c index afcfd30c..224847e7 100644 --- a/nxdump.c +++ b/nxdump.c @@ -16,95 +16,113 @@ #define INDENT_AMOUNT " " -char * -type2s(uint type){ +char *type2s(uint type) +{ static char unknownType[40]; - switch (type){ - case DFNT_NONE: return "DFNT_NONE"; - case DFNT_FLOAT32: return "DFNT_FLOAT32"; - case DFNT_FLOAT64: return "DFNT_FLOAT64"; - case DFNT_INT8: return "DFNT_INT8"; - case DFNT_UINT8: return "DFNT_UINT8"; - case DFNT_INT16: return "DFNT_INT16"; - case DFNT_UINT16: return "DFNT_UINT16"; - case DFNT_INT32: return "DFNT_INT32"; - case DFNT_UINT32: return "DFNT_UINT32"; + switch (type) { + case DFNT_NONE: + return "DFNT_NONE"; + case DFNT_FLOAT32: + return "DFNT_FLOAT32"; + case DFNT_FLOAT64: + return "DFNT_FLOAT64"; + case DFNT_INT8: + return "DFNT_INT8"; + case DFNT_UINT8: + return "DFNT_UINT8"; + case DFNT_INT16: + return "DFNT_INT16"; + case DFNT_UINT16: + return "DFNT_UINT16"; + case DFNT_INT32: + return "DFNT_INT32"; + case DFNT_UINT32: + return "DFNT_UINT32"; } return "Unsupported!"; } -int dumpAttr(NXhandle NXdat, char * parent, char * indent) { +int dumpAttr(NXhandle NXdat, char *parent, char *indent) +{ int length, itype; char name[VGNAMELENMAX], *data; NXstatus NXstat; - while((NXstat = NXgetnextattr(NXdat, name, &length, &itype)) != NX_EOD) { + while ((NXstat = NXgetnextattr(NXdat, name, &length, &itype)) != NX_EOD) { data = (char *) malloc(length + 1); NXstat = NXgetattr(NXdat, name, data, length); data[length] = 0; - printf("%s%s:%s=%s\n",indent,parent,name,data); + printf("%s%s:%s=%s\n", indent, parent, name, data); } return 0; } -int dumpSDS(NXhandle NXdat, char * name, char * indent) { +int dumpSDS(NXhandle NXdat, char *name, char *indent) +{ char new_indent[80]; - int rank, dims[MAX_VAR_DIMS], datatype,i; + int rank, dims[MAX_VAR_DIMS], datatype, i; NXstatus NXstat; - strcpy(new_indent,indent); strcat(new_indent,INDENT_AMOUNT); + strcpy(new_indent, indent); + strcat(new_indent, INDENT_AMOUNT); NXstat = NXopendata(NXdat, name); NXstat = NXgetinfo(NXdat, &rank, dims, &datatype); - printf("%sSD %s (datatype=%s, rank=%d, dimensions=%d",new_indent, + printf("%sSD %s (datatype=%s, rank=%d, dimensions=%d", new_indent, name, type2s(datatype), rank, dims[0]); if (rank > 1) { - for (i=1;i%s\n",indent,class,name); - if ((NXstat = NXopengroup(NXdat,name,class)) == NX_ERROR) { - fprintf(stderr,"Error opening V group %s!",name); - return -1; - } - dumpVG(NXdat,new_indent); - NXstat = NXclosegroup(NXdat); - printf("%sv %s->%s\n",indent,class,name); + if (! + ((strcmp(class, "Dim0.0") == 0) + || (strcmp(class, "CDF0.0") == 0))) { + printf("%sV %s->%s\n", indent, class, name); + if ((NXstat = NXopengroup(NXdat, name, class)) == NX_ERROR) { + fprintf(stderr, "Error opening V group %s!", name); + return -1; + } + dumpVG(NXdat, new_indent); + NXstat = NXclosegroup(NXdat); + printf("%sv %s->%s\n", indent, class, name); } - break; + break; default: - dumpSDS(NXdat,name,new_indent); + dumpSDS(NXdat, name, new_indent); } } return 0; } -void -main(int argc, char ** argv) { +void main(int argc, char **argv) +{ char name[VGNAMELENMAX], class[VGNAMELENMAX], indent[80] = ""; int datatype; char filename[80]; @@ -112,13 +130,13 @@ main(int argc, char ** argv) { NXstatus NXstat; if (argc < 2) { - fprintf(stderr,"Usage: nxdump \n"); + fprintf(stderr, "Usage: nxdump \n"); exit(1); } - strcpy(filename,argv[1]); + strcpy(filename, argv[1]); - if ((NXdat = NXopen(filename,DFACC_RDWR)) == NULL) { - fprintf(stderr,"Unable to access file %s! Exiting...\n",filename); + if ((NXdat = NXopen(filename, DFACC_RDWR)) == NULL) { + fprintf(stderr, "Unable to access file %s! Exiting...\n", filename); exit(1); } @@ -130,4 +148,3 @@ main(int argc, char ** argv) { NXclose(NXdat); } - diff --git a/nxinter_wrap.c b/nxinter_wrap.c index a2dda998..4d2c4e90 100644 --- a/nxinter_wrap.c +++ b/nxinter_wrap.c @@ -19,10 +19,10 @@ # if (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # else -# define SWIGTEMPLATEDISAMBIGUATOR +# define SWIGTEMPLATEDISAMBIGUATOR # endif # else -# define SWIGTEMPLATEDISAMBIGUATOR +# define SWIGTEMPLATEDISAMBIGUATOR # endif #endif @@ -39,14 +39,14 @@ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define SWIGUNUSED __attribute__ ((__unused__)) +# define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) -# define SWIGUNUSED __attribute__ ((__unused__)) +# define SWIGUNUSED __attribute__ ((__unused__)) # else -# define SWIGUNUSED +# define SWIGUNUSED # endif #endif @@ -54,7 +54,7 @@ # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else -# define SWIGUNUSEDPARM(p) p SWIGUNUSED +# define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif @@ -97,7 +97,7 @@ # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL -# endif +# endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ @@ -242,10 +242,10 @@ */ -#define SWIG_OK (0) +#define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) -#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) +#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) @@ -272,18 +272,21 @@ # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif -# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ +# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) -SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; +SWIGINTERNINLINE int SWIG_AddCast(int r) +{ + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : + SWIG_ERROR) : r; } -SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; +SWIGINTERNINLINE int SWIG_CheckState(int r) +{ + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } -#else /* no cast-rank mode */ +#else /* no cast-rank mode */ # define SWIG_AddCast # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif @@ -297,38 +300,38 @@ SWIGINTERNINLINE int SWIG_CheckState(int r) { extern "C" { #endif -typedef void *(*swig_converter_func)(void *); -typedef struct swig_type_info *(*swig_dycast_func)(void **); + typedef void *(*swig_converter_func) (void *); + typedef struct swig_type_info *(*swig_dycast_func) (void **); /* Structure to store inforomation on one type */ -typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ -} swig_type_info; + typedef struct swig_type_info { + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ + } swig_type_info; /* Structure to store a type and conversion function used for casting */ -typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ -} swig_cast_info; + typedef struct swig_cast_info { + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ + } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ -typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ -} swig_module_info; + typedef struct swig_module_info { + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ + } swig_module_info; /* Compare two type names skipping the space characters, therefore @@ -337,54 +340,60 @@ typedef struct swig_module_info { Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ -SWIGRUNTIME int -SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + SWIGRUNTIME int + SWIG_TypeNameComp(const char *f1, const char *l1, + const char *f2, const char *l2) { + for (; (f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) + ++f1; + while ((*f2 == ' ') && (f2 != l2)) + ++f2; + if (*f1 != *f2) + return (*f1 > *f2) ? 1 : -1; + } return (l1 - f1) - (l2 - f2); } - return (l1 - f1) - (l2 - f2); -} /* Check type equivalence in a name list like ||... Return 0 if not equal, 1 if equal */ -SWIGRUNTIME int -SWIG_TypeEquiv(const char *nb, const char *tb) { - int equiv = 0; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (!equiv && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; + SWIGRUNTIME int + SWIG_TypeEquiv(const char *nb, const char *tb) { + int equiv = 0; + const char *te = tb + strlen(tb); + const char *ne = nb; + while (!equiv && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') + break; + } + equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; + if (*ne) + ++ne; } - equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; - if (*ne) ++ne; + return equiv; } - return equiv; -} /* Check type equivalence in a name list like ||... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ -SWIGRUNTIME int -SWIG_TypeCompare(const char *nb, const char *tb) { - int equiv = 0; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (!equiv && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; + SWIGRUNTIME int + SWIG_TypeCompare(const char *nb, const char *tb) { + int equiv = 0; + const char *te = tb + strlen(tb); + const char *ne = nb; + while (!equiv && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') + break; + } + equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; + if (*ne) + ++ne; } - equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; - if (*ne) ++ne; + return equiv; } - return equiv; -} /* think of this as a c++ template<> or a scheme macro */ @@ -412,94 +421,94 @@ SWIG_TypeCompare(const char *nb, const char *tb) { /* Check the typename */ -SWIGRUNTIME swig_cast_info * -SWIG_TypeCheck(const char *c, swig_type_info *ty) { - SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty); -} + SWIGRUNTIME swig_cast_info *SWIG_TypeCheck(const char *c, + swig_type_info * ty) { + SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty); + } /* Same as previous function, except strcmp is replaced with a pointer comparison */ -SWIGRUNTIME swig_cast_info * -SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) { - SWIG_TypeCheck_Template(iter->type == from, into); -} + SWIGRUNTIME swig_cast_info *SWIG_TypeCheckStruct(swig_type_info * from, + swig_type_info * into) { + SWIG_TypeCheck_Template(iter->type == from, into); + } /* Cast a pointer up an inheritance hierarchy */ -SWIGRUNTIMEINLINE void * -SWIG_TypeCast(swig_cast_info *ty, void *ptr) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr); -} + SWIGRUNTIMEINLINE void *SWIG_TypeCast(swig_cast_info * ty, void *ptr) { + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter) (ptr); + } /* Dynamic pointer casting. Down an inheritance hierarchy */ -SWIGRUNTIME swig_type_info * -SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; + SWIGRUNTIME swig_type_info *SWIG_TypeDynamicCast(swig_type_info * ty, + void **ptr) { + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) + return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast) (ptr); + if (ty) + lastty = ty; + } + return lastty; } - return lastty; -} /* Return the name associated with this type */ -SWIGRUNTIMEINLINE const char * -SWIG_TypeName(const swig_type_info *ty) { - return ty->name; -} + SWIGRUNTIMEINLINE const char *SWIG_TypeName(const swig_type_info * ty) { + return ty->name; + } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ -SWIGRUNTIME const char * -SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. We choose - to print the last name, as it is often (?) the most - specific. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s+1; - return last_name; + SWIGRUNTIME const char *SWIG_TypePrettyName(const swig_type_info * type) { + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. We choose + to print the last name, as it is often (?) the most + specific. */ + if (!type) + return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') + last_name = s + 1; + return last_name; + } else + return type->name; } - else - return type->name; -} /* Set the clientdata field for a type */ -SWIGRUNTIME void -SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; - - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); + SWIGRUNTIME void + SWIG_TypeClientData(swig_type_info * ti, void *clientdata) { + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; + + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } } - } - cast = cast->next; + cast = cast->next; + } } -} -SWIGRUNTIME void -SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; -} - + SWIGRUNTIME void + SWIG_TypeNewClientData(swig_type_info * ti, void *clientdata) { + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; + } + /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) @@ -508,41 +517,43 @@ SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { Note: if start == end at the beginning of the function, we go all the way around the circular list. */ -SWIGRUNTIME swig_type_info * -SWIG_MangledTypeQueryModule(swig_module_info *start, - swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - register size_t l = 0; - register size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - register size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - register int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; -} + SWIGRUNTIME swig_type_info *SWIG_MangledTypeQueryModule(swig_module_info + * start, + swig_module_info + * end, + const char *name) + { + swig_module_info *iter = start; + do { + if (iter->size) { + register size_t l = 0; + register size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + register size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + register int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; + } /* Search for a swig_type_info structure for either a mangled name or a human readable name. @@ -553,148 +564,152 @@ SWIG_MangledTypeQueryModule(swig_module_info *start, Note: if start == end at the beginning of the function, we go all the way around the circular list. */ -SWIGRUNTIME swig_type_info * -SWIG_TypeQueryModule(swig_module_info *start, - swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - register size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); + SWIGRUNTIME swig_type_info *SWIG_TypeQueryModule(swig_module_info * + start, + swig_module_info * end, + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + register size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str + && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } + + /* neither found a match */ + return 0; } - - /* neither found a match */ - return 0; -} /* Pack binary data into a string */ -SWIGRUNTIME char * -SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - register const unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; + SWIGRUNTIME char *SWIG_PackData(char *c, void *ptr, size_t sz) { + static const char hex[17] = "0123456789abcdef"; + register const unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; } - return c; -} /* Unpack binary data from a string */ -SWIGRUNTIME const char * -SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - register unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register char d = *(c++); - register unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = ((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = ((d - ('a'-10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (d - ('a'-10)); - else - return (char *) 0; - *u = uu; + SWIGRUNTIME const char *SWIG_UnpackData(const char *c, void *ptr, + size_t sz) { + register unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register char d = *(c++); + register unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = ((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = ((d - ('a' - 10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (d - ('a' - 10)); + else + return (char *) 0; + *u = uu; + } + return c; } - return c; -} /* Pack 'void *' into a string buffer. */ -SWIGRUNTIME char * -SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2*sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,&ptr,sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r,name); - return buff; -} - -SWIGRUNTIME const char * -SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { + SWIGRUNTIME char *SWIG_PackVoidPtr(char *buff, void *ptr, + const char *name, size_t bsz) { + char *r = buff; + if ((2 * sizeof(void *) + 2) > bsz) return 0; - } - } - return SWIG_UnpackData(++c,ptr,sizeof(void *)); -} - -SWIGRUNTIME char * -SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2*sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,ptr,sz); - if (lname) { - strncpy(r,name,lname+1); - } else { - *r = 0; - } - return buff; -} - -SWIGRUNTIME const char * -SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - memset(ptr,0,sz); - return name; - } else { + *(r++) = '_'; + r = SWIG_PackData(r, &ptr, sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - } + strcpy(r, name); + return buff; + } + + SWIGRUNTIME const char *SWIG_UnpackVoidPtr(const char *c, void **ptr, + const char *name) { + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c, ptr, sizeof(void *)); + } + + SWIGRUNTIME char *SWIG_PackDataName(char *buff, void *ptr, size_t sz, + const char *name, size_t bsz) { + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2 * sz + 2 + lname) > bsz) + return 0; + *(r++) = '_'; + r = SWIG_PackData(r, ptr, sz); + if (lname) { + strncpy(r, name, lname + 1); + } else { + *r = 0; + } + return buff; + } + + SWIGRUNTIME const char *SWIG_UnpackDataName(const char *c, void *ptr, + size_t sz, + const char *name) { + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + memset(ptr, 0, sz); + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c, ptr, sz); } - return SWIG_UnpackData(++c,ptr,sz); -} #ifdef __cplusplus } #endif /* Errors in SWIG */ -#define SWIG_UnknownError -1 -#define SWIG_IOError -2 -#define SWIG_RuntimeError -3 -#define SWIG_IndexError -4 -#define SWIG_TypeError -5 -#define SWIG_DivisionByZero -6 -#define SWIG_OverflowError -7 -#define SWIG_SyntaxError -8 -#define SWIG_ValueError -9 +#define SWIG_UnknownError -1 +#define SWIG_IOError -2 +#define SWIG_RuntimeError -3 +#define SWIG_IndexError -4 +#define SWIG_TypeError -5 +#define SWIG_DivisionByZero -6 +#define SWIG_OverflowError -7 +#define SWIG_SyntaxError -8 +#define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 -#define SWIG_MemoryError -12 +#define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 @@ -703,10 +718,10 @@ SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { * error manipulation * ----------------------------------------------------------------------------- */ -SWIGINTERN const char* -SWIG_Tcl_ErrorType(int code) { - const char* type = 0; - switch(code) { +SWIGINTERN const char *SWIG_Tcl_ErrorType(int code) +{ + const char *type = 0; + switch (code) { case SWIG_MemoryError: type = "MemoryError"; break; @@ -748,7 +763,7 @@ SWIG_Tcl_ErrorType(int code) { SWIGINTERN void -SWIG_Tcl_SetErrorObj(Tcl_Interp *interp, const char *ctype, Tcl_Obj *obj) +SWIG_Tcl_SetErrorObj(Tcl_Interp * interp, const char *ctype, Tcl_Obj * obj) { Tcl_ResetResult(interp); Tcl_SetObjResult(interp, obj); @@ -756,20 +771,21 @@ SWIG_Tcl_SetErrorObj(Tcl_Interp *interp, const char *ctype, Tcl_Obj *obj) } SWIGINTERN void -SWIG_Tcl_SetErrorMsg(Tcl_Interp *interp, const char *ctype, const char *mesg) +SWIG_Tcl_SetErrorMsg(Tcl_Interp * interp, const char *ctype, + const char *mesg) { Tcl_ResetResult(interp); Tcl_SetErrorCode(interp, "SWIG", ctype, NULL); Tcl_AppendResult(interp, ctype, " ", mesg, NULL); /* - Tcl_AddErrorInfo(interp, ctype); - Tcl_AddErrorInfo(interp, " "); - Tcl_AddErrorInfo(interp, mesg); - */ + Tcl_AddErrorInfo(interp, ctype); + Tcl_AddErrorInfo(interp, " "); + Tcl_AddErrorInfo(interp, mesg); + */ } SWIGINTERNINLINE void -SWIG_Tcl_AddErrorMsg(Tcl_Interp *interp, const char* mesg) +SWIG_Tcl_AddErrorMsg(Tcl_Interp * interp, const char *mesg) { Tcl_AddErrorInfo(interp, mesg); } @@ -792,91 +808,95 @@ extern "C" { #define SWIG_TCL_BINARY 5 /* Constant information structure */ -typedef struct swig_const_info { + typedef struct swig_const_info { int type; char *name; long lvalue; double dvalue; - void *pvalue; + void *pvalue; swig_type_info **ptype; -} swig_const_info; + } swig_const_info; -typedef int (*swig_wrapper)(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []); -typedef int (*swig_wrapper_func)(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []); -typedef char *(*swig_variable_func)(ClientData, Tcl_Interp *, char *, char *, int); -typedef void (*swig_delete_func)(ClientData); + typedef int (*swig_wrapper) (ClientData, Tcl_Interp *, int, + Tcl_Obj * CONST[]); + typedef int (*swig_wrapper_func) (ClientData, Tcl_Interp *, int, + Tcl_Obj * CONST[]); + typedef char *(*swig_variable_func) (ClientData, Tcl_Interp *, char *, + char *, int); + typedef void (*swig_delete_func) (ClientData); -typedef struct swig_method { - const char *name; - swig_wrapper method; -} swig_method; + typedef struct swig_method { + const char *name; + swig_wrapper method; + } swig_method; -typedef struct swig_attribute { - const char *name; - swig_wrapper getmethod; - swig_wrapper setmethod; -} swig_attribute; + typedef struct swig_attribute { + const char *name; + swig_wrapper getmethod; + swig_wrapper setmethod; + } swig_attribute; -typedef struct swig_class { - const char *name; - swig_type_info **type; - swig_wrapper constructor; - void (*destructor)(void *); - swig_method *methods; - swig_attribute *attributes; - struct swig_class **bases; - char **base_names; - swig_module_info *module; -} swig_class; + typedef struct swig_class { + const char *name; + swig_type_info **type; + swig_wrapper constructor; + void (*destructor) (void *); + swig_method *methods; + swig_attribute *attributes; + struct swig_class **bases; + char **base_names; + swig_module_info *module; + } swig_class; -typedef struct swig_instance { - Tcl_Obj *thisptr; - void *thisvalue; - swig_class *classptr; - int destroy; - Tcl_Command cmdtok; -} swig_instance; + typedef struct swig_instance { + Tcl_Obj *thisptr; + void *thisvalue; + swig_class *classptr; + int destroy; + Tcl_Command cmdtok; + } swig_instance; /* Structure for command table */ -typedef struct { - const char *name; - int (*wrapper)(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []); - ClientData clientdata; -} swig_command_info; + typedef struct { + const char *name; + int (*wrapper) (ClientData, Tcl_Interp *, int, Tcl_Obj * CONST[]); + ClientData clientdata; + } swig_command_info; /* Structure for variable linking table */ -typedef struct { - const char *name; - void *addr; - char * (*get)(ClientData, Tcl_Interp *, char *, char *, int); - char * (*set)(ClientData, Tcl_Interp *, char *, char *, int); -} swig_var_info; + typedef struct { + const char *name; + void *addr; + char *(*get) (ClientData, Tcl_Interp *, char *, char *, int); + char *(*set) (ClientData, Tcl_Interp *, char *, char *, int); + } swig_var_info; /* -----------------------------------------------------------------------------* * Install a constant object * -----------------------------------------------------------------------------*/ -static Tcl_HashTable swigconstTable; -static int swigconstTableinit = 0; + static Tcl_HashTable swigconstTable; + static int swigconstTableinit = 0; -SWIGINTERN void -SWIG_Tcl_SetConstantObj(Tcl_Interp *interp, const char* name, Tcl_Obj *obj) { - int newobj; - Tcl_ObjSetVar2(interp,Tcl_NewStringObj(name,-1), NULL, obj, TCL_GLOBAL_ONLY); - Tcl_SetHashValue(Tcl_CreateHashEntry(&swigconstTable, name, &newobj), (ClientData) obj); -} - -SWIGINTERN Tcl_Obj * -SWIG_Tcl_GetConstantObj(const char *key) { - Tcl_HashEntry *entryPtr; - if (!swigconstTableinit) return 0; - entryPtr = Tcl_FindHashEntry(&swigconstTable, key); - if (entryPtr) { - return (Tcl_Obj *) Tcl_GetHashValue(entryPtr); + SWIGINTERN void + SWIG_Tcl_SetConstantObj(Tcl_Interp * interp, const char *name, + Tcl_Obj * obj) { + int newobj; + Tcl_ObjSetVar2(interp, Tcl_NewStringObj(name, -1), NULL, obj, + TCL_GLOBAL_ONLY); + Tcl_SetHashValue(Tcl_CreateHashEntry(&swigconstTable, name, &newobj), + (ClientData) obj); + } SWIGINTERN Tcl_Obj *SWIG_Tcl_GetConstantObj(const char *key) { + Tcl_HashEntry *entryPtr; + if (!swigconstTableinit) + return 0; + entryPtr = Tcl_FindHashEntry(&swigconstTable, key); + if (entryPtr) { + return (Tcl_Obj *) Tcl_GetHashValue(entryPtr); + } + return 0; } - return 0; -} #ifdef __cplusplus } @@ -919,30 +939,30 @@ SWIG_Tcl_GetConstantObj(const char *key) { /* Runtime API */ -#define SWIG_GetModule(clientdata) SWIG_Tcl_GetModule((Tcl_Interp *) (clientdata)) +#define SWIG_GetModule(clientdata) SWIG_Tcl_GetModule((Tcl_Interp *) (clientdata)) #define SWIG_SetModule(clientdata, pointer) SWIG_Tcl_SetModule((Tcl_Interp *) (clientdata), pointer) /* Error manipulation */ -#define SWIG_ErrorType(code) SWIG_Tcl_ErrorType(code) +#define SWIG_ErrorType(code) SWIG_Tcl_ErrorType(code) #define SWIG_Error(code, msg) SWIG_Tcl_SetErrorMsg(interp, SWIG_Tcl_ErrorType(code), msg) -#define SWIG_fail goto fail +#define SWIG_fail goto fail /* Tcl-specific SWIG API */ -#define SWIG_Acquire(ptr) SWIG_Tcl_Acquire(ptr) -#define SWIG_MethodCommand SWIG_Tcl_MethodCommand -#define SWIG_Disown(ptr) SWIG_Tcl_Disown(ptr) -#define SWIG_ConvertPtrFromString(c, ptr, ty, flags) SWIG_Tcl_ConvertPtrFromString(interp, c, ptr, ty, flags) -#define SWIG_MakePtr(c, ptr, ty, flags) SWIG_Tcl_MakePtr(c, ptr, ty, flags) -#define SWIG_PointerTypeFromString(c) SWIG_Tcl_PointerTypeFromString(c) -#define SWIG_GetArgs SWIG_Tcl_GetArgs -#define SWIG_GetConstantObj(key) SWIG_Tcl_GetConstantObj(key) -#define SWIG_ObjectConstructor SWIG_Tcl_ObjectConstructor -#define SWIG_Thisown(ptr) SWIG_Tcl_Thisown(ptr) -#define SWIG_ObjectDelete SWIG_Tcl_ObjectDelete +#define SWIG_Acquire(ptr) SWIG_Tcl_Acquire(ptr) +#define SWIG_MethodCommand SWIG_Tcl_MethodCommand +#define SWIG_Disown(ptr) SWIG_Tcl_Disown(ptr) +#define SWIG_ConvertPtrFromString(c, ptr, ty, flags) SWIG_Tcl_ConvertPtrFromString(interp, c, ptr, ty, flags) +#define SWIG_MakePtr(c, ptr, ty, flags) SWIG_Tcl_MakePtr(c, ptr, ty, flags) +#define SWIG_PointerTypeFromString(c) SWIG_Tcl_PointerTypeFromString(c) +#define SWIG_GetArgs SWIG_Tcl_GetArgs +#define SWIG_GetConstantObj(key) SWIG_Tcl_GetConstantObj(key) +#define SWIG_ObjectConstructor SWIG_Tcl_ObjectConstructor +#define SWIG_Thisown(ptr) SWIG_Tcl_Thisown(ptr) +#define SWIG_ObjectDelete SWIG_Tcl_ObjectDelete #define SWIG_TCL_DECL_ARGS_2(arg1, arg2) (Tcl_Interp *interp SWIGUNUSED, arg1, arg2) @@ -960,16 +980,14 @@ SWIG_Tcl_GetConstantObj(const char *key) { #ifdef __cplusplus extern "C" { #if 0 -} /* cc-mode */ +} /* cc-mode */ #endif #endif - -/* Object support */ - -SWIGRUNTIME Tcl_HashTable* -SWIG_Tcl_ObjectTable(void) { - static Tcl_HashTable swigobjectTable; - static int swigobjectTableinit = 0; +/* Object support */ SWIGRUNTIME Tcl_HashTable * +SWIG_Tcl_ObjectTable(void) +{ + static Tcl_HashTable swigobjectTable; + static int swigobjectTableinit = 0; if (!swigobjectTableinit) { Tcl_InitHashTable(&swigobjectTable, TCL_ONE_WORD_KEYS); swigobjectTableinit = 1; @@ -978,14 +996,14 @@ SWIG_Tcl_ObjectTable(void) { } /* Acquire ownership of a pointer */ -SWIGRUNTIME void -SWIG_Tcl_Acquire(void *ptr) { +SWIGRUNTIME void SWIG_Tcl_Acquire(void *ptr) +{ int newobj; Tcl_CreateHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr, &newobj); } -SWIGRUNTIME int -SWIG_Tcl_Thisown(void *ptr) { +SWIGRUNTIME int SWIG_Tcl_Thisown(void *ptr) +{ if (Tcl_FindHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr)) { return 1; } @@ -993,9 +1011,10 @@ SWIG_Tcl_Thisown(void *ptr) { } /* Disown a pointer. Returns 1 if we owned it to begin with */ -SWIGRUNTIME int -SWIG_Tcl_Disown(void *ptr) { - Tcl_HashEntry *entryPtr = Tcl_FindHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr); +SWIGRUNTIME int SWIG_Tcl_Disown(void *ptr) +{ + Tcl_HashEntry *entryPtr = + Tcl_FindHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr); if (entryPtr) { Tcl_DeleteHashEntry(entryPtr); return 1; @@ -1005,14 +1024,17 @@ SWIG_Tcl_Disown(void *ptr) { /* Convert a pointer value */ SWIGRUNTIME int -SWIG_Tcl_ConvertPtrFromString(Tcl_Interp *interp, const char *c, void **ptr, swig_type_info *ty, int flags) { +SWIG_Tcl_ConvertPtrFromString(Tcl_Interp * interp, const char *c, + void **ptr, swig_type_info * ty, int flags) +{ swig_cast_info *tc; /* Pointer values must start with leading underscore */ while (*c != '_') { *ptr = (void *) 0; - if (strcmp(c,"NULL") == 0) return SWIG_OK; + if (strcmp(c, "NULL") == 0) + return SWIG_OK; /* Hmmm. It could be an object name. */ - if (Tcl_VarEval(interp,c," cget -this", (char *) NULL) == TCL_OK) { + if (Tcl_VarEval(interp, c, " cget -this", (char *) NULL) == TCL_OK) { Tcl_Obj *result = Tcl_GetObjResult(interp); c = Tcl_GetStringFromObj(result, NULL); continue; @@ -1021,29 +1043,33 @@ SWIG_Tcl_ConvertPtrFromString(Tcl_Interp *interp, const char *c, void **ptr, swi return SWIG_ERROR; } c++; - c = SWIG_UnpackData(c,ptr,sizeof(void *)); + c = SWIG_UnpackData(c, ptr, sizeof(void *)); if (ty) { - tc = c ? SWIG_TypeCheck(c,ty) : 0; + tc = c ? SWIG_TypeCheck(c, ty) : 0; if (!tc) { return SWIG_ERROR; } if (flags & SWIG_POINTER_DISOWN) { SWIG_Disown((void *) *ptr); } - *ptr = SWIG_TypeCast(tc,(void *) *ptr); + *ptr = SWIG_TypeCast(tc, (void *) *ptr); } return SWIG_OK; } /* Convert a pointer value */ SWIGRUNTIMEINLINE int -SWIG_Tcl_ConvertPtr(Tcl_Interp *interp, Tcl_Obj *oc, void **ptr, swig_type_info *ty, int flags) { - return SWIG_Tcl_ConvertPtrFromString(interp, Tcl_GetStringFromObj(oc,NULL), ptr, ty, flags); +SWIG_Tcl_ConvertPtr(Tcl_Interp * interp, Tcl_Obj * oc, void **ptr, + swig_type_info * ty, int flags) +{ + return SWIG_Tcl_ConvertPtrFromString(interp, + Tcl_GetStringFromObj(oc, NULL), ptr, + ty, flags); } /* Convert a pointer value */ -SWIGRUNTIME char * -SWIG_Tcl_PointerTypeFromString(char *c) { +SWIGRUNTIME char *SWIG_Tcl_PointerTypeFromString(char *c) +{ char d; /* Pointer values must start with leading underscore. NULL has no type */ if (*c != '_') { @@ -1052,7 +1078,8 @@ SWIG_Tcl_PointerTypeFromString(char *c) { c++; /* Extract hex value from pointer */ while ((d = *c)) { - if (!(((d >= '0') && (d <= '9')) || ((d >= 'a') && (d <= 'f')))) break; + if (!(((d >= '0') && (d <= '9')) || ((d >= 'a') && (d <= 'f')))) + break; c++; } return c; @@ -1060,23 +1087,28 @@ SWIG_Tcl_PointerTypeFromString(char *c) { /* Convert a packed value value */ SWIGRUNTIME int -SWIG_Tcl_ConvertPacked(Tcl_Interp *SWIGUNUSEDPARM(interp) , Tcl_Obj *obj, void *ptr, int sz, swig_type_info *ty) { +SWIG_Tcl_ConvertPacked(Tcl_Interp * SWIGUNUSEDPARM(interp), Tcl_Obj * obj, + void *ptr, int sz, swig_type_info * ty) +{ swig_cast_info *tc; - const char *c; + const char *c; - if (!obj) goto type_error; - c = Tcl_GetStringFromObj(obj,NULL); + if (!obj) + goto type_error; + c = Tcl_GetStringFromObj(obj, NULL); /* Pointer values must start with leading underscore */ - if (*c != '_') goto type_error; + if (*c != '_') + goto type_error; c++; - c = SWIG_UnpackData(c,ptr,sz); + c = SWIG_UnpackData(c, ptr, sz); if (ty) { - tc = SWIG_TypeCheck(c,ty); - if (!tc) goto type_error; + tc = SWIG_TypeCheck(c, ty); + if (!tc) + goto type_error; } return SWIG_OK; - type_error: +type_error: return SWIG_ERROR; } @@ -1084,49 +1116,58 @@ SWIG_Tcl_ConvertPacked(Tcl_Interp *SWIGUNUSEDPARM(interp) , Tcl_Obj *obj, void * /* Take a pointer and convert it to a string */ SWIGRUNTIME void -SWIG_Tcl_MakePtr(char *c, void *ptr, swig_type_info *ty, int flags) { +SWIG_Tcl_MakePtr(char *c, void *ptr, swig_type_info * ty, int flags) +{ if (ptr) { *(c++) = '_'; - c = SWIG_PackData(c,&ptr,sizeof(void *)); - strcpy(c,ty->name); + c = SWIG_PackData(c, &ptr, sizeof(void *)); + strcpy(c, ty->name); } else { - strcpy(c,(char *)"NULL"); + strcpy(c, (char *) "NULL"); } flags = 0; } /* Create a new pointer object */ -SWIGRUNTIMEINLINE Tcl_Obj * -SWIG_Tcl_NewPointerObj(void *ptr, swig_type_info *type, int flags) { +SWIGRUNTIMEINLINE Tcl_Obj *SWIG_Tcl_NewPointerObj(void *ptr, + swig_type_info * type, + int flags) +{ Tcl_Obj *robj; char result[SWIG_BUFFER_SIZE]; - SWIG_MakePtr(result,ptr,type,flags); - robj = Tcl_NewStringObj(result,-1); + SWIG_MakePtr(result, ptr, type, flags); + robj = Tcl_NewStringObj(result, -1); return robj; } -SWIGRUNTIME Tcl_Obj * -SWIG_Tcl_NewPackedObj(void *ptr, int sz, swig_type_info *type) { +SWIGRUNTIME Tcl_Obj *SWIG_Tcl_NewPackedObj(void *ptr, int sz, + swig_type_info * type) +{ char result[1024]; char *r = result; - if ((2*sz + 1 + strlen(type->name)) > 1000) return 0; + if ((2 * sz + 1 + strlen(type->name)) > 1000) + return 0; *(r++) = '_'; - r = SWIG_PackData(r,ptr,sz); - strcpy(r,type->name); - return Tcl_NewStringObj(result,-1); + r = SWIG_PackData(r, ptr, sz); + strcpy(r, type->name); + return Tcl_NewStringObj(result, -1); } /* -----------------------------------------------------------------------------* * Get type list * -----------------------------------------------------------------------------*/ -SWIGRUNTIME swig_module_info * -SWIG_Tcl_GetModule(Tcl_Interp *interp) { +SWIGRUNTIME swig_module_info *SWIG_Tcl_GetModule(Tcl_Interp * interp) +{ const char *data; swig_module_info *ret = 0; - + /* first check if pointer already created */ - data = Tcl_GetVar(interp, (char *)"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, TCL_GLOBAL_ONLY); + data = + Tcl_GetVar(interp, + (char *) "swig_runtime_data_type_pointer" + SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, + TCL_GLOBAL_ONLY); if (data) { SWIG_UnpackData(data, &ret, sizeof(swig_type_info **)); } @@ -1135,14 +1176,17 @@ SWIG_Tcl_GetModule(Tcl_Interp *interp) { } SWIGRUNTIME void -SWIG_Tcl_SetModule(Tcl_Interp *interp, swig_module_info *module) { +SWIG_Tcl_SetModule(Tcl_Interp * interp, swig_module_info * module) +{ char buf[SWIG_BUFFER_SIZE]; char *data; /* create a new pointer */ data = SWIG_PackData(buf, &module, sizeof(swig_type_info **)); *data = 0; - Tcl_SetVar(interp, (char *)"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, buf, 0); + Tcl_SetVar(interp, + (char *) "swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION + SWIG_TYPE_TABLE_NAME, buf, 0); } /* -----------------------------------------------------------------------------* @@ -1150,12 +1194,12 @@ SWIG_Tcl_SetModule(Tcl_Interp *interp, swig_module_info *module) { * -----------------------------------------------------------------------------*/ -SWIGRUNTIME void -SWIG_Tcl_ObjectDelete(ClientData clientData) { +SWIGRUNTIME void SWIG_Tcl_ObjectDelete(ClientData clientData) +{ swig_instance *si = (swig_instance *) clientData; if ((si) && (si->destroy) && (SWIG_Disown(si->thisvalue))) { if (si->classptr->destructor) { - (si->classptr->destructor)(si->thisvalue); + (si->classptr->destructor) (si->thisvalue); } } Tcl_DecrRefCount(si->thisptr); @@ -1164,41 +1208,43 @@ SWIG_Tcl_ObjectDelete(ClientData clientData) { /* Function to invoke object methods given an instance */ SWIGRUNTIME int -SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST _objv[]) { - char *method, *attrname; - swig_instance *inst = (swig_instance *) clientData; - swig_method *meth; - swig_attribute *attr; - Tcl_Obj *oldarg; - Tcl_Obj **objv; - int rcode; - swig_class *cls; - swig_class *cls_stack[64]; - int cls_stack_bi[64]; - int cls_stack_top = 0; - int numconf = 2; - int bi; +SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST _objv[]) +{ + char *method, *attrname; + swig_instance *inst = (swig_instance *) clientData; + swig_method *meth; + swig_attribute *attr; + Tcl_Obj *oldarg; + Tcl_Obj **objv; + int rcode; + swig_class *cls; + swig_class *cls_stack[64]; + int cls_stack_bi[64]; + int cls_stack_top = 0; + int numconf = 2; + int bi; objv = (Tcl_Obj **) _objv; if (objc < 2) { Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC); return TCL_ERROR; } - method = Tcl_GetStringFromObj(objv[1],NULL); - if (strcmp(method,"-acquire") == 0) { + method = Tcl_GetStringFromObj(objv[1], NULL); + if (strcmp(method, "-acquire") == 0) { inst->destroy = 1; SWIG_Acquire(inst->thisvalue); return TCL_OK; } - if (strcmp(method,"-disown") == 0) { + if (strcmp(method, "-disown") == 0) { if (inst->destroy) { SWIG_Disown(inst->thisvalue); } inst->destroy = 0; return TCL_OK; } - if (strcmp(method,"-delete") == 0) { - Tcl_DeleteCommandFromToken(interp,inst->cmdtok); + if (strcmp(method, "-delete") == 0) { + Tcl_DeleteCommandFromToken(interp, inst->cmdtok); return TCL_OK; } cls_stack[cls_stack_top] = inst->classptr; @@ -1210,8 +1256,11 @@ SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_ if (bi != -1) { if (!cls->bases[bi] && cls->base_names[bi]) { /* lookup and cache the base class */ - swig_type_info *info = SWIG_TypeQueryModule(cls->module, cls->module, cls->base_names[bi]); - if (info) cls->bases[bi] = (swig_class *) info->clientdata; + swig_type_info *info = + SWIG_TypeQueryModule(cls->module, cls->module, + cls->base_names[bi]); + if (info) + cls->bases[bi] = (swig_class *) info->clientdata; } cls = cls->bases[bi]; if (cls) { @@ -1224,19 +1273,21 @@ SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_ } if (!cls) { cls_stack_top--; - if (cls_stack_top < 0) break; - else continue; + if (cls_stack_top < 0) + break; + else + continue; } cls_stack_bi[cls_stack_top]++; meth = cls->methods; /* Check for methods */ while (meth && meth->name) { - if (strcmp(meth->name,method) == 0) { + if (strcmp(meth->name, method) == 0) { oldarg = objv[1]; objv[1] = inst->thisptr; Tcl_IncrRefCount(inst->thisptr); - rcode = (*meth->method)(clientData,interp,objc,objv); + rcode = (*meth->method) (clientData, interp, objc, objv); objv[1] = oldarg; Tcl_DecrRefCount(inst->thisptr); return rcode; @@ -1244,19 +1295,19 @@ SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_ meth++; } /* Check class methods for a match */ - if (strcmp(method,"cget") == 0) { + if (strcmp(method, "cget") == 0) { if (objc < 3) { Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC); return TCL_ERROR; } - attrname = Tcl_GetStringFromObj(objv[2],NULL); + attrname = Tcl_GetStringFromObj(objv[2], NULL); attr = cls->attributes; while (attr && attr->name) { if ((strcmp(attr->name, attrname) == 0) && (attr->getmethod)) { oldarg = objv[1]; objv[1] = inst->thisptr; Tcl_IncrRefCount(inst->thisptr); - rcode = (*attr->getmethod)(clientData,interp,2, objv); + rcode = (*attr->getmethod) (clientData, interp, 2, objv); objv[1] = oldarg; Tcl_DecrRefCount(inst->thisptr); return rcode; @@ -1269,9 +1320,9 @@ SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_ } if (strcmp(attrname, "-thisown") == 0) { if (SWIG_Thisown(inst->thisvalue)) { - Tcl_SetResult(interp,(char*)"1",TCL_STATIC); + Tcl_SetResult(interp, (char *) "1", TCL_STATIC); } else { - Tcl_SetResult(interp,(char*)"0",TCL_STATIC); + Tcl_SetResult(interp, (char *) "0", TCL_STATIC); } return TCL_OK; } @@ -1283,38 +1334,44 @@ SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_ } i = 2; while (i < objc) { - attrname = Tcl_GetStringFromObj(objv[i],NULL); + attrname = Tcl_GetStringFromObj(objv[i], NULL); attr = cls->attributes; while (attr && attr->name) { if ((strcmp(attr->name, attrname) == 0) && (attr->setmethod)) { oldarg = objv[i]; objv[i] = inst->thisptr; Tcl_IncrRefCount(inst->thisptr); - rcode = (*attr->setmethod)(clientData,interp,3, &objv[i-1]); + rcode = + (*attr->setmethod) (clientData, interp, 3, &objv[i - 1]); objv[i] = oldarg; Tcl_DecrRefCount(inst->thisptr); - if (rcode != TCL_OK) return rcode; + if (rcode != TCL_OK) + return rcode; numconf += 2; } attr++; } - i+=2; + i += 2; } } } - if (strcmp(method,"configure") == 0) { + if (strcmp(method, "configure") == 0) { if (numconf >= objc) { return TCL_OK; } else { - Tcl_SetResult(interp,(char *) "Invalid attribute name.", TCL_STATIC); + Tcl_SetResult(interp, (char *) "Invalid attribute name.", + TCL_STATIC); return TCL_ERROR; } } - if (strcmp(method,"cget") == 0) { - Tcl_SetResult(interp,(char *) "Invalid attribute name.", TCL_STATIC); + if (strcmp(method, "cget") == 0) { + Tcl_SetResult(interp, (char *) "Invalid attribute name.", TCL_STATIC); return TCL_ERROR; } - Tcl_SetResult(interp, (char *) "Invalid method. Must be one of: configure cget -acquire -disown -delete", TCL_STATIC); + Tcl_SetResult(interp, + (char *) + "Invalid method. Must be one of: configure cget -acquire -disown -delete", + TCL_STATIC); cls = inst->classptr; bi = 0; while (cls) { @@ -1322,11 +1379,12 @@ SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_ while (meth && meth->name) { char *cr = (char *) Tcl_GetStringResult(interp); int meth_len = strlen(meth->name); - char* where = strchr(cr,':'); - while(where) { + char *where = strchr(cr, ':'); + while (where) { where = strstr(where, meth->name); - if(where) { - if(where[-1] == ' ' && (where[meth_len] == ' ' || where[meth_len]==0)) { + if (where) { + if (where[-1] == ' ' + && (where[meth_len] == ' ' || where[meth_len] == 0)) { break; } else { where++; @@ -1344,22 +1402,30 @@ SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_ } /* This function takes the current result and turns it into an object command */ -SWIGRUNTIME Tcl_Obj * -SWIG_Tcl_NewInstanceObj(Tcl_Interp *interp, void *thisvalue, swig_type_info *type, int flags) { - Tcl_Obj *robj = SWIG_NewPointerObj(thisvalue, type,0); +SWIGRUNTIME Tcl_Obj *SWIG_Tcl_NewInstanceObj(Tcl_Interp * interp, + void *thisvalue, + swig_type_info * type, + int flags) +{ + Tcl_Obj *robj = SWIG_NewPointerObj(thisvalue, type, 0); /* Check to see if this pointer belongs to a class or not */ if ((type->clientdata) && (interp)) { - Tcl_CmdInfo ci; - char *name; - name = Tcl_GetStringFromObj(robj,NULL); - if (!Tcl_GetCommandInfo(interp,name, &ci) || (flags)) { - swig_instance *newinst = (swig_instance *) malloc(sizeof(swig_instance)); + Tcl_CmdInfo ci; + char *name; + name = Tcl_GetStringFromObj(robj, NULL); + if (!Tcl_GetCommandInfo(interp, name, &ci) || (flags)) { + swig_instance *newinst = + (swig_instance *) malloc(sizeof(swig_instance)); newinst->thisptr = Tcl_DuplicateObj(robj); Tcl_IncrRefCount(newinst->thisptr); newinst->thisvalue = thisvalue; newinst->classptr = (swig_class *) type->clientdata; newinst->destroy = flags; - newinst->cmdtok = Tcl_CreateObjCommand(interp, Tcl_GetStringFromObj(robj,NULL), (swig_wrapper_func) SWIG_MethodCommand, (ClientData) newinst, (swig_delete_func) SWIG_ObjectDelete); + newinst->cmdtok = + Tcl_CreateObjCommand(interp, Tcl_GetStringFromObj(robj, NULL), + (swig_wrapper_func) SWIG_MethodCommand, + (ClientData) newinst, + (swig_delete_func) SWIG_ObjectDelete); if (flags) { SWIG_Acquire(thisvalue); } @@ -1370,28 +1436,33 @@ SWIG_Tcl_NewInstanceObj(Tcl_Interp *interp, void *thisvalue, swig_type_info *typ /* Function to create objects */ SWIGRUNTIME int -SWIG_Tcl_ObjectConstructor(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - Tcl_Obj *newObj = 0; - void *thisvalue = 0; - swig_instance *newinst = 0; - swig_class *classptr = (swig_class *) clientData; - swig_wrapper cons = 0; - char *name = 0; - int firstarg = 0; - int thisarg = 0; - int destroy = 1; +SWIG_Tcl_ObjectConstructor(ClientData clientData, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) +{ + Tcl_Obj *newObj = 0; + void *thisvalue = 0; + swig_instance *newinst = 0; + swig_class *classptr = (swig_class *) clientData; + swig_wrapper cons = 0; + char *name = 0; + int firstarg = 0; + int thisarg = 0; + int destroy = 1; if (!classptr) { - Tcl_SetResult(interp, (char *) "swig: internal runtime error. No class object defined.", TCL_STATIC); + Tcl_SetResult(interp, + (char *) + "swig: internal runtime error. No class object defined.", + TCL_STATIC); return TCL_ERROR; } cons = classptr->constructor; if (objc > 1) { - char *s = Tcl_GetStringFromObj(objv[1],NULL); - if (strcmp(s,"-this") == 0) { + char *s = Tcl_GetStringFromObj(objv[1], NULL); + if (strcmp(s, "-this") == 0) { thisarg = 2; cons = 0; - } else if (strcmp(s,"-args") == 0) { + } else if (strcmp(s, "-args") == 0) { firstarg = 1; } else if (objc == 2) { firstarg = 1; @@ -1399,37 +1470,42 @@ SWIG_Tcl_ObjectConstructor(ClientData clientData, Tcl_Interp *interp, int objc, } else if (objc >= 3) { char *s1; name = s; - s1 = Tcl_GetStringFromObj(objv[2],NULL); - if (strcmp(s1,"-this") == 0) { - thisarg = 3; - cons = 0; + s1 = Tcl_GetStringFromObj(objv[2], NULL); + if (strcmp(s1, "-this") == 0) { + thisarg = 3; + cons = 0; } else { - firstarg = 1; + firstarg = 1; } } } if (cons) { int result; - result = (*cons)(0, interp, objc-firstarg, &objv[firstarg]); + result = (*cons) (0, interp, objc - firstarg, &objv[firstarg]); if (result != TCL_OK) { return result; } newObj = Tcl_DuplicateObj(Tcl_GetObjResult(interp)); - if (!name) name = Tcl_GetStringFromObj(newObj,NULL); + if (!name) + name = Tcl_GetStringFromObj(newObj, NULL); } else if (thisarg > 0) { if (thisarg < objc) { destroy = 0; newObj = Tcl_DuplicateObj(objv[thisarg]); - if (!name) name = Tcl_GetStringFromObj(newObj,NULL); + if (!name) + name = Tcl_GetStringFromObj(newObj, NULL); } else { Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC); return TCL_ERROR; } } else { - Tcl_SetResult(interp, (char *) "No constructor available.", TCL_STATIC); + Tcl_SetResult(interp, (char *) "No constructor available.", + TCL_STATIC); return TCL_ERROR; } - if (SWIG_Tcl_ConvertPtr(interp,newObj, (void **) &thisvalue, *(classptr->type), 0) != SWIG_OK) { + if (SWIG_Tcl_ConvertPtr + (interp, newObj, (void **) &thisvalue, *(classptr->type), + 0) != SWIG_OK) { Tcl_DecrRefCount(newObj); return TCL_ERROR; } @@ -1442,7 +1518,10 @@ SWIG_Tcl_ObjectConstructor(ClientData clientData, Tcl_Interp *interp, int objc, if (destroy) { SWIG_Acquire(thisvalue); } - newinst->cmdtok = Tcl_CreateObjCommand(interp,name, (swig_wrapper) SWIG_MethodCommand, (ClientData) newinst, (swig_delete_func) SWIG_ObjectDelete); + newinst->cmdtok = + Tcl_CreateObjCommand(interp, name, (swig_wrapper) SWIG_MethodCommand, + (ClientData) newinst, + (swig_delete_func) SWIG_ObjectDelete); return TCL_OK; } @@ -1450,25 +1529,28 @@ SWIG_Tcl_ObjectConstructor(ClientData clientData, Tcl_Interp *interp, int objc, * Get arguments * -----------------------------------------------------------------------------*/ SWIGRUNTIME int -SWIG_Tcl_GetArgs(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], const char *fmt, ...) { - int argno = 0, opt = 0; - long tempi; - double tempd; +SWIG_Tcl_GetArgs(Tcl_Interp * interp, int objc, Tcl_Obj * CONST objv[], + const char *fmt, ...) +{ + int argno = 0, opt = 0; + long tempi; + double tempd; const char *c; - va_list ap; - void *vptr; - Tcl_Obj *obj = 0; + va_list ap; + void *vptr; + Tcl_Obj *obj = 0; swig_type_info *ty; - va_start(ap,fmt); - for (c = fmt; (*c && (*c != ':') && (*c != ';')); c++,argno++) { + va_start(ap, fmt); + for (c = fmt; (*c && (*c != ':') && (*c != ';')); c++, argno++) { if (*c == '|') { opt = 1; c++; } - if (argno >= (objc-1)) { + if (argno >= (objc - 1)) { if (!opt) { - Tcl_SetResult(interp, (char *) "Wrong number of arguments ", TCL_STATIC); + Tcl_SetResult(interp, (char *) "Wrong number of arguments ", + TCL_STATIC); goto argerror; } else { va_end(ap); @@ -1476,49 +1558,72 @@ SWIG_Tcl_GetArgs(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], const char } } - vptr = va_arg(ap,void *); + vptr = va_arg(ap, void *); if (vptr) { if (isupper(*c)) { - obj = SWIG_Tcl_GetConstantObj(Tcl_GetStringFromObj(objv[argno+1],0)); - if (!obj) obj = objv[argno+1]; + obj = + SWIG_Tcl_GetConstantObj(Tcl_GetStringFromObj + (objv[argno + 1], 0)); + if (!obj) + obj = objv[argno + 1]; } else { - obj = objv[argno+1]; + obj = objv[argno + 1]; } - switch(*c) { - case 'i': case 'I': - case 'l': case 'L': - case 'h': case 'H': - case 'b': case 'B': - if (Tcl_GetLongFromObj(interp,obj,&tempi) != TCL_OK) goto argerror; - if ((*c == 'i') || (*c == 'I')) *((int *)vptr) = (int)tempi; - else if ((*c == 'l') || (*c == 'L')) *((long *)vptr) = (long)tempi; - else if ((*c == 'h') || (*c == 'H')) *((short*)vptr) = (short)tempi; - else if ((*c == 'b') || (*c == 'B')) *((unsigned char *)vptr) = (unsigned char)tempi; + switch (*c) { + case 'i': + case 'I': + case 'l': + case 'L': + case 'h': + case 'H': + case 'b': + case 'B': + if (Tcl_GetLongFromObj(interp, obj, &tempi) != TCL_OK) + goto argerror; + if ((*c == 'i') || (*c == 'I')) + *((int *) vptr) = (int) tempi; + else if ((*c == 'l') || (*c == 'L')) + *((long *) vptr) = (long) tempi; + else if ((*c == 'h') || (*c == 'H')) + *((short *) vptr) = (short) tempi; + else if ((*c == 'b') || (*c == 'B')) + *((unsigned char *) vptr) = (unsigned char) tempi; break; - case 'f': case 'F': - case 'd': case 'D': - if (Tcl_GetDoubleFromObj(interp,obj,&tempd) != TCL_OK) goto argerror; - if ((*c == 'f') || (*c == 'F')) *((float *) vptr) = (float)tempd; - else if ((*c == 'd') || (*c == 'D')) *((double*) vptr) = tempd; + case 'f': + case 'F': + case 'd': + case 'D': + if (Tcl_GetDoubleFromObj(interp, obj, &tempd) != TCL_OK) + goto argerror; + if ((*c == 'f') || (*c == 'F')) + *((float *) vptr) = (float) tempd; + else if ((*c == 'd') || (*c == 'D')) + *((double *) vptr) = tempd; break; - case 's': case 'S': - if (*(c+1) == '#') { + case 's': + case 'S': + if (*(c + 1) == '#') { int *vlptr = (int *) va_arg(ap, void *); *((char **) vptr) = Tcl_GetStringFromObj(obj, vlptr); c++; } else { - *((char **)vptr) = Tcl_GetStringFromObj(obj,NULL); + *((char **) vptr) = Tcl_GetStringFromObj(obj, NULL); } break; - case 'c': case 'C': - *((char *)vptr) = *(Tcl_GetStringFromObj(obj,NULL)); + case 'c': + case 'C': + *((char *) vptr) = *(Tcl_GetStringFromObj(obj, NULL)); break; - case 'p': case 'P': + case 'p': + case 'P': ty = (swig_type_info *) va_arg(ap, void *); - if (SWIG_Tcl_ConvertPtr(interp, obj, (void **) vptr, ty, 0) != SWIG_OK) goto argerror; + if (SWIG_Tcl_ConvertPtr(interp, obj, (void **) vptr, ty, 0) != + SWIG_OK) + goto argerror; break; - case 'o': case 'O': - *((Tcl_Obj **)vptr) = objv[argno+1]; + case 'o': + case 'O': + *((Tcl_Obj **) vptr) = objv[argno + 1]; break; default: break; @@ -1526,21 +1631,23 @@ SWIG_Tcl_GetArgs(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], const char } } - if ((*c != ';') && ((objc-1) > argno)) { + if ((*c != ';') && ((objc - 1) > argno)) { Tcl_SetResult(interp, (char *) "Wrong # args.", TCL_STATIC); goto argerror; } va_end(ap); return TCL_OK; - argerror: +argerror: { char temp[32]; - sprintf(temp,"%d", argno+1); - c = strchr(fmt,':'); - if (!c) c = strchr(fmt,';'); - if (!c) c = (char *)""; - Tcl_AppendResult(interp,c," argument ", temp, NULL); + sprintf(temp, "%d", argno + 1); + c = strchr(fmt, ':'); + if (!c) + c = strchr(fmt, ';'); + if (!c) + c = (char *) ""; + Tcl_AppendResult(interp, c, " argument ", temp, NULL); va_end(ap); return TCL_ERROR; } @@ -1548,16 +1655,16 @@ SWIG_Tcl_GetArgs(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], const char #ifdef __cplusplus #if 0 -{ /* cc-mode */ +{ /* cc-mode */ #endif } #endif -#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) +#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) -#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else +#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else @@ -1566,7 +1673,8 @@ SWIG_Tcl_GetArgs(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], const char #define SWIGTYPE_p_char swig_types[0] #define SWIGTYPE_p_void swig_types[1] static swig_type_info *swig_types[3]; -static swig_module_info swig_module = {swig_types, 2, 0, 0, 0, 0}; +static swig_module_info swig_module = { swig_types, 2, 0, 0, 0, 0 }; + #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) @@ -1577,12 +1685,12 @@ static swig_module_info swig_module = {swig_types, 2, 0, 0, 0, 0}; #define SWIG_prefix "" #define SWIG_version "0.0" -#define SWIGVERSION 0x010331 +#define SWIGVERSION 0x010331 #define SWIG_VERSION SWIGVERSION -#define SWIG_as_voidptr(a) (void *)((const void *)(a)) -#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) +#define SWIG_as_voidptr(a) (void *)((const void *)(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) @@ -1592,20 +1700,14 @@ extern "C" { #ifdef MAC_TCL #pragma export on #endif -SWIGEXPORT int SWIG_init(Tcl_Interp *); + SWIGEXPORT int SWIG_init(Tcl_Interp *); #ifdef MAC_TCL #pragma export off #endif #ifdef __cplusplus } #endif - - - #include "nxinterhelper.h" - - - #include #ifndef LLONG_MIN # define LLONG_MIN LONG_LONG_MIN @@ -1616,23 +1718,19 @@ SWIGEXPORT int SWIG_init(Tcl_Interp *); #ifndef ULLONG_MAX # define ULLONG_MAX ULONG_LONG_MAX #endif - - -SWIGINTERNINLINE Tcl_Obj* -SWIG_From_long (long value) +SWIGINTERNINLINE Tcl_Obj *SWIG_From_long(long value) { if (((long) INT_MIN <= value) && (value <= (long) INT_MAX)) { - return Tcl_NewIntObj((int)(value)); + return Tcl_NewIntObj((int) (value)); } else { return Tcl_NewLongObj(value); } } -SWIGINTERNINLINE Tcl_Obj * -SWIG_From_int (int value) -{ - return SWIG_From_long (value); +SWIGINTERNINLINE Tcl_Obj *SWIG_From_int(int value) +{ + return SWIG_From_long(value); } @@ -1640,83 +1738,93 @@ SWIG_From_int (int value) #define MAXDIM 7 -void *create_nxds(int rank, int type, int dim0, int dim1, int dim2, - int dim3, int dim4, int dim5,int dim6){ - int dim[MAXDIM],i; +void *create_nxds(int rank, int type, int dim0, int dim1, int dim2, + int dim3, int dim4, int dim5, int dim6) +{ + int dim[MAXDIM], i; - dim[0] = dim0; - dim[1] = dim1; - dim[2] = dim2; - dim[3] = dim3; - dim[4] = dim4; - dim[5] = dim5; - dim[6] = dim6; + dim[0] = dim0; + dim[1] = dim1; + dim[2] = dim2; + dim[3] = dim3; + dim[4] = dim4; + dim[5] = dim5; + dim[6] = dim6; - return createNXDataset(rank,type,dim); + return createNXDataset(rank, type, dim); } -void *create_text_nxds(char *name){ - return (void *)createTextNXDataset(name); +void *create_text_nxds(char *name) +{ + return (void *) createTextNXDataset(name); } -void drop_nxds(void *ptr){ - dropNXDataset( (pNXDS) ptr); +void drop_nxds(void *ptr) +{ + dropNXDataset((pNXDS) ptr); } -int get_nxds_rank(void *ptr){ - return getNXDatasetRank((pNXDS) ptr); +int get_nxds_rank(void *ptr) +{ + return getNXDatasetRank((pNXDS) ptr); } -int get_nxds_type(void *ptr){ - return getNXDatasetType((pNXDS) ptr); +int get_nxds_type(void *ptr) +{ + return getNXDatasetType((pNXDS) ptr); } -int get_nxds_dim(void *ptr, int which){ - return getNXDatasetDim((pNXDS) ptr, which); +int get_nxds_dim(void *ptr, int which) +{ + return getNXDatasetDim((pNXDS) ptr, which); } -double get_nxds_value(void *ptr,int dim0, int dim1, int dim2, - int dim3, int dim4, int dim5,int dim6){ - int dim[MAXDIM]; +double get_nxds_value(void *ptr, int dim0, int dim1, int dim2, + int dim3, int dim4, int dim5, int dim6) +{ + int dim[MAXDIM]; - dim[0] = dim0; - dim[1] = dim1; - dim[2] = dim2; - dim[3] = dim3; - dim[4] = dim4; - dim[5] = dim5; - dim[6] = dim6; + dim[0] = dim0; + dim[1] = dim1; + dim[2] = dim2; + dim[3] = dim3; + dim[4] = dim4; + dim[5] = dim5; + dim[6] = dim6; - return getNXDatasetValue((pNXDS)ptr,dim); + return getNXDatasetValue((pNXDS) ptr, dim); } -char *get_nxds_text(void *ptr){ - return getNXDatasetText((pNXDS) ptr); +char *get_nxds_text(void *ptr) +{ + return getNXDatasetText((pNXDS) ptr); } -int put_nxds_value(void *ptr, double value, int dim0, int dim1, int dim2, - int dim3, int dim4, int dim5,int dim6){ - int dim[MAXDIM]; +int put_nxds_value(void *ptr, double value, int dim0, int dim1, int dim2, + int dim3, int dim4, int dim5, int dim6) +{ + int dim[MAXDIM]; - dim[0] = dim0; - dim[1] = dim1; - dim[2] = dim2; - dim[3] = dim3; - dim[4] = dim4; - dim[5] = dim5; - dim[6] = dim6; + dim[0] = dim0; + dim[1] = dim1; + dim[2] = dim2; + dim[3] = dim3; + dim[4] = dim4; + dim[5] = dim5; + dim[6] = dim6; - return putNXDatasetValue((pNXDS)ptr,dim,value); + return putNXDatasetValue((pNXDS) ptr, dim, value); } SWIGINTERN int -SWIG_AsVal_long SWIG_TCL_DECL_ARGS_2(Tcl_Obj *obj, long* val) +SWIG_AsVal_long SWIG_TCL_DECL_ARGS_2(Tcl_Obj * obj, long *val) { long v; - if (Tcl_GetLongFromObj(0,obj, &v) == TCL_OK) { - if (val) *val = (long) v; + if (Tcl_GetLongFromObj(0, obj, &v) == TCL_OK) { + if (val) + *val = (long) v; return SWIG_OK; } return SWIG_TypeError; @@ -1732,22 +1840,27 @@ SWIG_AsVal_int SWIG_TCL_DECL_ARGS_2(Tcl_Obj * obj, int *val) if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { - if (val) *val = (int)(v); + if (val) + *val = (int) (v); } - } + } return res; } SWIGINTERN int -SWIG_AsCharPtrAndSize(Tcl_Obj *obj, char** cptr, size_t* psize, int *alloc) -{ +SWIG_AsCharPtrAndSize(Tcl_Obj * obj, char **cptr, size_t * psize, + int *alloc) +{ int len = 0; char *cstr = Tcl_GetStringFromObj(obj, &len); if (cstr) { - if (cptr) *cptr = cstr; - if (psize) *psize = len + 1; - if (alloc) *alloc = SWIG_OLDOBJ; + if (cptr) + *cptr = cstr; + if (psize) + *psize = len + 1; + if (alloc) + *alloc = SWIG_OLDOBJ; return SWIG_OK; } return SWIG_TypeError; @@ -1757,54 +1870,59 @@ SWIG_AsCharPtrAndSize(Tcl_Obj *obj, char** cptr, size_t* psize, int *alloc) - #define SWIG_From_double Tcl_NewDoubleObj +#define SWIG_From_double Tcl_NewDoubleObj -SWIGINTERNINLINE Tcl_Obj * -SWIG_FromCharPtrAndSize(const char* carray, size_t size) +SWIGINTERNINLINE Tcl_Obj *SWIG_FromCharPtrAndSize(const char *carray, + size_t size) { - return (size < INT_MAX) ? Tcl_NewStringObj(carray, (int)(size)) : NULL; + return (size < INT_MAX) ? Tcl_NewStringObj(carray, (int) (size)) : NULL; } -SWIGINTERNINLINE Tcl_Obj * -SWIG_FromCharPtr(const char *cptr) -{ +SWIGINTERNINLINE Tcl_Obj *SWIG_FromCharPtr(const char *cptr) +{ return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); } SWIGINTERN int -SWIG_AsVal_double SWIG_TCL_DECL_ARGS_2(Tcl_Obj *obj, double *val) +SWIG_AsVal_double SWIG_TCL_DECL_ARGS_2(Tcl_Obj * obj, double *val) { double v; if (Tcl_GetDoubleFromObj(0, obj, &v) == TCL_OK) { - if (val) *val = v; + if (val) + *val = v; return SWIG_OK; } return SWIG_TypeError; } -SWIGINTERN int -SWIG_AsCharArray(Tcl_Obj * obj, char *val, size_t size) -{ - char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ; +SWIGINTERN int SWIG_AsCharArray(Tcl_Obj * obj, char *val, size_t size) +{ + char *cptr = 0; + size_t csize = 0; + int alloc = SWIG_OLDOBJ; int res = SWIG_AsCharPtrAndSize(obj, &cptr, &csize, &alloc); if (SWIG_IsOK(res)) { - if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize; + if ((csize == size + 1) && cptr && !(cptr[csize - 1])) + --csize; if (csize <= size) { if (val) { - if (csize) memcpy(val, cptr, csize*sizeof(char)); - if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char)); + if (csize) + memcpy(val, cptr, csize * sizeof(char)); + if (csize < size) + memset(val + csize, 0, (size - csize) * sizeof(char)); } if (alloc == SWIG_NEWOBJ) { - free((char*)cptr); - res = SWIG_DelNewMask(res); - } + free((char *) cptr); + res = SWIG_DelNewMask(res); + } return res; } - if (alloc == SWIG_NEWOBJ) free((char*)cptr); + if (alloc == SWIG_NEWOBJ) + free((char *) cptr); } return SWIG_TypeError; } @@ -1812,16 +1930,17 @@ SWIG_AsCharArray(Tcl_Obj * obj, char *val, size_t size) SWIGINTERN int SWIG_AsVal_char SWIG_TCL_DECL_ARGS_2(Tcl_Obj * obj, char *val) -{ +{ int res = SWIG_AsCharArray(obj, val, 1); if (!SWIG_IsOK(res)) { long v; res = SWIG_AddCast(SWIG_AsVal_long SWIG_TCL_CALL_ARGS_2(obj, &v)); if (SWIG_IsOK(res)) { if ((CHAR_MIN <= v) && (v <= CHAR_MAX)) { - if (val) *val = (char)(v); + if (val) + *val = (char) (v); } else { - res = SWIG_OverflowError; + res = SWIG_OverflowError; } } } @@ -1843,12 +1962,13 @@ char *SWIG_RcFileName = "~/.myapprc"; #ifdef MAC_TCL -extern int MacintoshInit _ANSI_ARGS_((void)); +extern int MacintoshInit _ANSI_ARGS_((void)); #endif -int Tcl_AppInit(Tcl_Interp *interp){ +int Tcl_AppInit(Tcl_Interp * interp) +{ - if (Tcl_Init(interp) == TCL_ERROR) + if (Tcl_Init(interp) == TCL_ERROR) return TCL_ERROR; /* Now initialize our functions */ @@ -1856,14 +1976,16 @@ int Tcl_AppInit(Tcl_Interp *interp){ if (SWIG_init(interp) == TCL_ERROR) return TCL_ERROR; #if TCL_MAJOR_VERSION > 7 || TCL_MAJOR_VERSION == 7 && TCL_MINOR_VERSION >= 5 - Tcl_SetVar(interp, (char *) "tcl_rcFileName",SWIG_RcFileName,TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, (char *) "tcl_rcFileName", SWIG_RcFileName, + TCL_GLOBAL_ONLY); #else - tcl_RcFileName = SWIG_RcFileName; + tcl_RcFileName = SWIG_RcFileName; #endif #ifdef SWIG_RcRsrcName - Tcl_SetVar(interp, (char *) "tcl_rcRsrcName",SWIG_RcRsrcName,TCL_GLOBAL); + Tcl_SetVar(interp, (char *) "tcl_rcRsrcName", SWIG_RcRsrcName, + TCL_GLOBAL); #endif - + return TCL_OK; } @@ -1871,1315 +1993,1779 @@ int Tcl_AppInit(Tcl_Interp *interp){ #ifdef __cplusplus extern "C" { #endif -SWIGINTERN int -_wrap_create_nxds(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - int arg1 ; - int arg2 ; - int arg3 = (int) 0 ; - int arg4 = (int) 0 ; - int arg5 = (int) 0 ; - int arg6 = (int) 0 ; - int arg7 = (int) 0 ; - int arg8 = (int) 0 ; - int arg9 = (int) 0 ; - void *result = 0 ; - int val1 ; - int ecode1 = 0 ; - int val2 ; - int ecode2 = 0 ; - int val3 ; - int ecode3 = 0 ; - int val4 ; - int ecode4 = 0 ; - int val5 ; - int ecode5 = 0 ; - int val6 ; - int ecode6 = 0 ; - int val7 ; - int ecode7 = 0 ; - int val8 ; - int ecode8 = 0 ; - int val9 ; - int ecode9 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo|ooooooo:create_nxds rank type ?dim0? ?dim1? ?dim2? ?dim3? ?dim4? ?dim5? ?dim6? ",(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - ecode1 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[1], &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "create_nxds" "', argument " "1"" of type '" "int""'"); - } - arg1 = (int)(val1); - ecode2 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[2], &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "create_nxds" "', argument " "2"" of type '" "int""'"); - } - arg2 = (int)(val2); - if (objc > 3) { - ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); - if (!SWIG_IsOK(ecode3)) { - SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "create_nxds" "', argument " "3"" of type '" "int""'"); - } - arg3 = (int)(val3); - } - if (objc > 4) { - ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); - if (!SWIG_IsOK(ecode4)) { - SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "create_nxds" "', argument " "4"" of type '" "int""'"); - } - arg4 = (int)(val4); - } - if (objc > 5) { - ecode5 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[5], &val5); - if (!SWIG_IsOK(ecode5)) { - SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "create_nxds" "', argument " "5"" of type '" "int""'"); - } - arg5 = (int)(val5); - } - if (objc > 6) { - ecode6 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[6], &val6); - if (!SWIG_IsOK(ecode6)) { - SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "create_nxds" "', argument " "6"" of type '" "int""'"); - } - arg6 = (int)(val6); - } - if (objc > 7) { - ecode7 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[7], &val7); - if (!SWIG_IsOK(ecode7)) { - SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "create_nxds" "', argument " "7"" of type '" "int""'"); - } - arg7 = (int)(val7); - } - if (objc > 8) { - ecode8 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[8], &val8); - if (!SWIG_IsOK(ecode8)) { - SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "create_nxds" "', argument " "8"" of type '" "int""'"); - } - arg8 = (int)(val8); - } - if (objc > 9) { - ecode9 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[9], &val9); - if (!SWIG_IsOK(ecode9)) { - SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "create_nxds" "', argument " "9"" of type '" "int""'"); - } - arg9 = (int)(val9); - } - result = (void *)create_nxds(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - return TCL_OK; -fail: - return TCL_ERROR; -} + SWIGINTERN int + _wrap_create_nxds(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + int arg1; + int arg2; + int arg3 = (int) 0; + int arg4 = (int) 0; + int arg5 = (int) 0; + int arg6 = (int) 0; + int arg7 = (int) 0; + int arg8 = (int) 0; + int arg9 = (int) 0; + void *result = 0; + int val1; + int ecode1 = 0; + int val2; + int ecode2 = 0; + int val3; + int ecode3 = 0; + int val4; + int ecode4 = 0; + int val5; + int ecode5 = 0; + int val6; + int ecode6 = 0; + int val7; + int ecode7 = 0; + int val8; + int ecode8 = 0; + int val9; + int ecode9 = 0; - -SWIGINTERN int -_wrap_create_text_nxds(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - char *arg1 = (char *) 0 ; - void *result = 0 ; - int res1 ; - char *buf1 = 0 ; - int alloc1 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:create_text_nxds name ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_AsCharPtrAndSize(objv[1], &buf1, NULL, &alloc1); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "create_text_nxds" "', argument " "1"" of type '" "char *""'"); - } - arg1 = (char *)(buf1); - result = (void *)create_text_nxds(arg1); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); - return TCL_OK; -fail: - if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_drop_nxds(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:drop_nxds ptr ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "drop_nxds" "', argument " "1"" of type '" "void *""'"); - } - drop_nxds(arg1); - - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_get_nxds_rank(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int result; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:get_nxds_rank ptr ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_nxds_rank" "', argument " "1"" of type '" "void *""'"); - } - result = (int)get_nxds_rank(arg1); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_get_nxds_type(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int result; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:get_nxds_type ptr ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_nxds_type" "', argument " "1"" of type '" "void *""'"); - } - result = (int)get_nxds_type(arg1); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_get_nxds_dim(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int arg2 ; - int result; - int res1 ; - int val2 ; - int ecode2 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:get_nxds_dim ptr which ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_nxds_dim" "', argument " "1"" of type '" "void *""'"); - } - ecode2 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[2], &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "get_nxds_dim" "', argument " "2"" of type '" "int""'"); - } - arg2 = (int)(val2); - result = (int)get_nxds_dim(arg1,arg2); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_get_nxds_value(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int arg2 = (int) 0 ; - int arg3 = (int) 0 ; - int arg4 = (int) 0 ; - int arg5 = (int) 0 ; - int arg6 = (int) 0 ; - int arg7 = (int) 0 ; - int arg8 = (int) 0 ; - double result; - int res1 ; - int val2 ; - int ecode2 = 0 ; - int val3 ; - int ecode3 = 0 ; - int val4 ; - int ecode4 = 0 ; - int val5 ; - int ecode5 = 0 ; - int val6 ; - int ecode6 = 0 ; - int val7 ; - int ecode7 = 0 ; - int val8 ; - int ecode8 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"o|ooooooo:get_nxds_value ptr ?dim0? ?dim1? ?dim2? ?dim3? ?dim4? ?dim5? ?dim6? ",(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_nxds_value" "', argument " "1"" of type '" "void *""'"); - } - if (objc > 2) { + if (SWIG_GetArgs + (interp, objc, objv, + "oo|ooooooo:create_nxds rank type ?dim0? ?dim1? ?dim2? ?dim3? ?dim4? ?dim5? ?dim6? ", + (void *) 0, (void *) 0, (void *) 0, (void *) 0, (void *) 0, + (void *) 0, (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + ecode1 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[1], &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), + "in method '" "create_nxds" "', argument " "1" + " of type '" "int" "'"); + } + arg1 = (int) (val1); ecode2 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[2], &val2); if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "get_nxds_value" "', argument " "2"" of type '" "int""'"); - } - arg2 = (int)(val2); + SWIG_exception_fail(SWIG_ArgError(ecode2), + "in method '" "create_nxds" "', argument " "2" + " of type '" "int" "'"); + } + arg2 = (int) (val2); + if (objc > 3) { + ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), + "in method '" "create_nxds" "', argument " "3" + " of type '" "int" "'"); + } + arg3 = (int) (val3); + } + if (objc > 4) { + ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), + "in method '" "create_nxds" "', argument " "4" + " of type '" "int" "'"); + } + arg4 = (int) (val4); + } + if (objc > 5) { + ecode5 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[5], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), + "in method '" "create_nxds" "', argument " "5" + " of type '" "int" "'"); + } + arg5 = (int) (val5); + } + if (objc > 6) { + ecode6 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[6], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), + "in method '" "create_nxds" "', argument " "6" + " of type '" "int" "'"); + } + arg6 = (int) (val6); + } + if (objc > 7) { + ecode7 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[7], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), + "in method '" "create_nxds" "', argument " "7" + " of type '" "int" "'"); + } + arg7 = (int) (val7); + } + if (objc > 8) { + ecode8 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[8], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), + "in method '" "create_nxds" "', argument " "8" + " of type '" "int" "'"); + } + arg8 = (int) (val8); + } + if (objc > 9) { + ecode9 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[9], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), + "in method '" "create_nxds" "', argument " "9" + " of type '" "int" "'"); + } + arg9 = (int) (val9); + } + result = + (void *) create_nxds(arg1, arg2, arg3, arg4, arg5, arg6, arg7, + arg8, arg9); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + return TCL_OK; + fail: + return TCL_ERROR; } - if (objc > 3) { + + + SWIGINTERN int + _wrap_create_text_nxds(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + char *arg1 = (char *) 0; + void *result = 0; + int res1; + char *buf1 = 0; + int alloc1 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "o:create_text_nxds name ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(objv[1], &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "create_text_nxds" "', argument " + "1" " of type '" "char *" "'"); + } + arg1 = (char *) (buf1); + result = (void *) create_text_nxds(arg1); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + if (alloc1 == SWIG_NEWOBJ) + free((char *) buf1); + return TCL_OK; + fail: + if (alloc1 == SWIG_NEWOBJ) + free((char *) buf1); + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_drop_nxds(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int res1; + + if (SWIG_GetArgs(interp, objc, objv, "o:drop_nxds ptr ", (void *) 0) == + TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "drop_nxds" "', argument " "1" + " of type '" "void *" "'"); + } + drop_nxds(arg1); + + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_get_nxds_rank(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int result; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:get_nxds_rank ptr ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "get_nxds_rank" "', argument " "1" + " of type '" "void *" "'"); + } + result = (int) get_nxds_rank(arg1); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_get_nxds_type(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int result; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:get_nxds_type ptr ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "get_nxds_type" "', argument " "1" + " of type '" "void *" "'"); + } + result = (int) get_nxds_type(arg1); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_get_nxds_dim(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int arg2; + int result; + int res1; + int val2; + int ecode2 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:get_nxds_dim ptr which ", (void *) 0, + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "get_nxds_dim" "', argument " "1" + " of type '" "void *" "'"); + } + ecode2 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[2], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), + "in method '" "get_nxds_dim" "', argument " "2" + " of type '" "int" "'"); + } + arg2 = (int) (val2); + result = (int) get_nxds_dim(arg1, arg2); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_get_nxds_value(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int arg2 = (int) 0; + int arg3 = (int) 0; + int arg4 = (int) 0; + int arg5 = (int) 0; + int arg6 = (int) 0; + int arg7 = (int) 0; + int arg8 = (int) 0; + double result; + int res1; + int val2; + int ecode2 = 0; + int val3; + int ecode3 = 0; + int val4; + int ecode4 = 0; + int val5; + int ecode5 = 0; + int val6; + int ecode6 = 0; + int val7; + int ecode7 = 0; + int val8; + int ecode8 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, + "o|ooooooo:get_nxds_value ptr ?dim0? ?dim1? ?dim2? ?dim3? ?dim4? ?dim5? ?dim6? ", + (void *) 0, (void *) 0, (void *) 0, (void *) 0, (void *) 0, + (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "get_nxds_value" "', argument " "1" + " of type '" "void *" "'"); + } + if (objc > 2) { + ecode2 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[2], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), + "in method '" "get_nxds_value" "', argument " + "2" " of type '" "int" "'"); + } + arg2 = (int) (val2); + } + if (objc > 3) { + ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), + "in method '" "get_nxds_value" "', argument " + "3" " of type '" "int" "'"); + } + arg3 = (int) (val3); + } + if (objc > 4) { + ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), + "in method '" "get_nxds_value" "', argument " + "4" " of type '" "int" "'"); + } + arg4 = (int) (val4); + } + if (objc > 5) { + ecode5 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[5], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), + "in method '" "get_nxds_value" "', argument " + "5" " of type '" "int" "'"); + } + arg5 = (int) (val5); + } + if (objc > 6) { + ecode6 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[6], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), + "in method '" "get_nxds_value" "', argument " + "6" " of type '" "int" "'"); + } + arg6 = (int) (val6); + } + if (objc > 7) { + ecode7 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[7], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), + "in method '" "get_nxds_value" "', argument " + "7" " of type '" "int" "'"); + } + arg7 = (int) (val7); + } + if (objc > 8) { + ecode8 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[8], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), + "in method '" "get_nxds_value" "', argument " + "8" " of type '" "int" "'"); + } + arg8 = (int) (val8); + } + result = + (double) get_nxds_value(arg1, arg2, arg3, arg4, arg5, arg6, arg7, + arg8); + Tcl_SetObjResult(interp, SWIG_From_double((double) (result))); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_get_nxds_text(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *result = 0; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:get_nxds_text ptr ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "get_nxds_text" "', argument " "1" + " of type '" "void *" "'"); + } + result = (char *) get_nxds_text(arg1); + Tcl_SetObjResult(interp, SWIG_FromCharPtr((const char *) result)); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_put_nxds_value(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + double arg2; + int arg3 = (int) 0; + int arg4 = (int) 0; + int arg5 = (int) 0; + int arg6 = (int) 0; + int arg7 = (int) 0; + int arg8 = (int) 0; + int arg9 = (int) 0; + int result; + int res1; + double val2; + int ecode2 = 0; + int val3; + int ecode3 = 0; + int val4; + int ecode4 = 0; + int val5; + int ecode5 = 0; + int val6; + int ecode6 = 0; + int val7; + int ecode7 = 0; + int val8; + int ecode8 = 0; + int val9; + int ecode9 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, + "oo|ooooooo:put_nxds_value ptr value ?dim0? ?dim1? ?dim2? ?dim3? ?dim4? ?dim5? ?dim6? ", + (void *) 0, (void *) 0, (void *) 0, (void *) 0, (void *) 0, + (void *) 0, (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "put_nxds_value" "', argument " "1" + " of type '" "void *" "'"); + } + ecode2 = SWIG_AsVal_double SWIG_TCL_CALL_ARGS_2(objv[2], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), + "in method '" "put_nxds_value" "', argument " "2" + " of type '" "double" "'"); + } + arg2 = (double) (val2); + if (objc > 3) { + ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), + "in method '" "put_nxds_value" "', argument " + "3" " of type '" "int" "'"); + } + arg3 = (int) (val3); + } + if (objc > 4) { + ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), + "in method '" "put_nxds_value" "', argument " + "4" " of type '" "int" "'"); + } + arg4 = (int) (val4); + } + if (objc > 5) { + ecode5 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[5], &val5); + if (!SWIG_IsOK(ecode5)) { + SWIG_exception_fail(SWIG_ArgError(ecode5), + "in method '" "put_nxds_value" "', argument " + "5" " of type '" "int" "'"); + } + arg5 = (int) (val5); + } + if (objc > 6) { + ecode6 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[6], &val6); + if (!SWIG_IsOK(ecode6)) { + SWIG_exception_fail(SWIG_ArgError(ecode6), + "in method '" "put_nxds_value" "', argument " + "6" " of type '" "int" "'"); + } + arg6 = (int) (val6); + } + if (objc > 7) { + ecode7 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[7], &val7); + if (!SWIG_IsOK(ecode7)) { + SWIG_exception_fail(SWIG_ArgError(ecode7), + "in method '" "put_nxds_value" "', argument " + "7" " of type '" "int" "'"); + } + arg7 = (int) (val7); + } + if (objc > 8) { + ecode8 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[8], &val8); + if (!SWIG_IsOK(ecode8)) { + SWIG_exception_fail(SWIG_ArgError(ecode8), + "in method '" "put_nxds_value" "', argument " + "8" " of type '" "int" "'"); + } + arg8 = (int) (val8); + } + if (objc > 9) { + ecode9 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[9], &val9); + if (!SWIG_IsOK(ecode9)) { + SWIG_exception_fail(SWIG_ArgError(ecode9), + "in method '" "put_nxds_value" "', argument " + "9" " of type '" "int" "'"); + } + arg9 = (int) (val9); + } + result = + (int) put_nxds_value(arg1, arg2, arg3, arg4, arg5, arg6, arg7, + arg8, arg9); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_getlasterror(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + char *result = 0; + + if (SWIG_GetArgs(interp, objc, objv, ":nx_getlasterror ") == TCL_ERROR) + SWIG_fail; + result = (char *) nx_getlasterror(); + Tcl_SetObjResult(interp, SWIG_FromCharPtr((const char *) result)); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_open(ClientData clientData SWIGUNUSED, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) { + char *arg1 = (char *) 0; + int arg2; + void *result = 0; + int res1; + char *buf1 = 0; + int alloc1 = 0; + int val2; + int ecode2 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:nx_open filename accessCode ", (void *) 0, + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(objv[1], &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_open" "', argument " "1" + " of type '" "char *" "'"); + } + arg1 = (char *) (buf1); + ecode2 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[2], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), + "in method '" "nx_open" "', argument " "2" + " of type '" "int" "'"); + } + arg2 = (int) (val2); + result = (void *) nx_open(arg1, arg2); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + if (alloc1 == SWIG_NEWOBJ) + free((char *) buf1); + return TCL_OK; + fail: + if (alloc1 == SWIG_NEWOBJ) + free((char *) buf1); + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_flush(ClientData clientData SWIGUNUSED, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + void *result = 0; + int res1; + + if (SWIG_GetArgs(interp, objc, objv, "o:nx_flush handle ", (void *) 0) + == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_flush" "', argument " "1" + " of type '" "void *" "'"); + } + result = (void *) nx_flush(arg1); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_close(ClientData clientData SWIGUNUSED, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int res1; + + if (SWIG_GetArgs(interp, objc, objv, "o:nx_close handle ", (void *) 0) + == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_close" "', argument " "1" + " of type '" "void *" "'"); + } + nx_close(arg1); + + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_makegroup(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + char *arg3 = (char *) 0; + int result; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + int res3; + char *buf3 = 0; + int alloc3 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "ooo:nx_makegroup handle name nxclass ", + (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_makegroup" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_makegroup" "', argument " "2" + " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); + res3 = SWIG_AsCharPtrAndSize(objv[3], &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), + "in method '" "nx_makegroup" "', argument " "3" + " of type '" "char *" "'"); + } + arg3 = (char *) (buf3); + result = (int) nx_makegroup(arg1, arg2, arg3); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + if (alloc3 == SWIG_NEWOBJ) + free((char *) buf3); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + if (alloc3 == SWIG_NEWOBJ) + free((char *) buf3); + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_opengroup(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + char *arg3 = (char *) 0; + int result; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + int res3; + char *buf3 = 0; + int alloc3 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "ooo:nx_opengroup handle name nxclass ", + (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_opengroup" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_opengroup" "', argument " "2" + " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); + res3 = SWIG_AsCharPtrAndSize(objv[3], &buf3, NULL, &alloc3); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), + "in method '" "nx_opengroup" "', argument " "3" + " of type '" "char *" "'"); + } + arg3 = (char *) (buf3); + result = (int) nx_opengroup(arg1, arg2, arg3); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + if (alloc3 == SWIG_NEWOBJ) + free((char *) buf3); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + if (alloc3 == SWIG_NEWOBJ) + free((char *) buf3); + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_openpath(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + int result; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:nx_openpath handle path ", (void *) 0, + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_openpath" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_openpath" "', argument " "2" + " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); + result = (int) nx_openpath(arg1, arg2); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_opengrouppath(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + int result; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:nx_opengrouppath handle path ", + (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_opengrouppath" "', argument " + "1" " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_opengrouppath" "', argument " + "2" " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); + result = (int) nx_opengrouppath(arg1, arg2); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_closegroup(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int result; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:nx_closegroup handle ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_closegroup" "', argument " "1" + " of type '" "void *" "'"); + } + result = (int) nx_closegroup(arg1); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_getnextentry(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char arg2; + char *result = 0; + int res1; + char val2; + int ecode2 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:nx_getnextentry handle separator ", + (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_getnextentry" "', argument " + "1" " of type '" "void *" "'"); + } + ecode2 = SWIG_AsVal_char SWIG_TCL_CALL_ARGS_2(objv[2], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), + "in method '" "nx_getnextentry" "', argument " + "2" " of type '" "char" "'"); + } + arg2 = (char) (val2); + result = (char *) nx_getnextentry(arg1, arg2); + Tcl_SetObjResult(interp, SWIG_FromCharPtr((const char *) result)); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_getgroupID(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + void *result = 0; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:nx_getgroupID handle ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_getgroupID" "', argument " "1" + " of type '" "void *" "'"); + } + result = (void *) nx_getgroupID(arg1); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_initgroupdir(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int result; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:nx_initgroupdir handle ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_initgroupdir" "', argument " + "1" " of type '" "void *" "'"); + } + result = (int) nx_initgroupdir(arg1); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; + } + + + SWIGINTERN int + _wrap_nx_makedata(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + int arg3; + int arg4; + void *arg5 = (void *) 0; + int result; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + int val3; + int ecode3 = 0; + int val4; + int ecode4 = 0; + int res5; + + if (SWIG_GetArgs + (interp, objc, objv, + "ooooo:nx_makedata handle name rank type dimPtr ", (void *) 0, + (void *) 0, (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_makedata" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_makedata" "', argument " "2" + " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); if (!SWIG_IsOK(ecode3)) { - SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "get_nxds_value" "', argument " "3"" of type '" "int""'"); - } - arg3 = (int)(val3); - } - if (objc > 4) { + SWIG_exception_fail(SWIG_ArgError(ecode3), + "in method '" "nx_makedata" "', argument " "3" + " of type '" "int" "'"); + } + arg3 = (int) (val3); ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); if (!SWIG_IsOK(ecode4)) { - SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "get_nxds_value" "', argument " "4"" of type '" "int""'"); - } - arg4 = (int)(val4); + SWIG_exception_fail(SWIG_ArgError(ecode4), + "in method '" "nx_makedata" "', argument " "4" + " of type '" "int" "'"); + } + arg4 = (int) (val4); + res5 = SWIG_ConvertPtr(objv[5], SWIG_as_voidptrptr(&arg5), 0, 0); + if (!SWIG_IsOK(res5)) { + SWIG_exception_fail(SWIG_ArgError(res5), + "in method '" "nx_makedata" "', argument " "5" + " of type '" "void *" "'"); + } + result = (int) nx_makedata(arg1, arg2, arg3, arg4, arg5); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_ERROR; } - if (objc > 5) { - ecode5 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[5], &val5); - if (!SWIG_IsOK(ecode5)) { - SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "get_nxds_value" "', argument " "5"" of type '" "int""'"); - } - arg5 = (int)(val5); - } - if (objc > 6) { - ecode6 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[6], &val6); - if (!SWIG_IsOK(ecode6)) { - SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "get_nxds_value" "', argument " "6"" of type '" "int""'"); - } - arg6 = (int)(val6); - } - if (objc > 7) { - ecode7 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[7], &val7); - if (!SWIG_IsOK(ecode7)) { - SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "get_nxds_value" "', argument " "7"" of type '" "int""'"); - } - arg7 = (int)(val7); - } - if (objc > 8) { - ecode8 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[8], &val8); - if (!SWIG_IsOK(ecode8)) { - SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "get_nxds_value" "', argument " "8"" of type '" "int""'"); - } - arg8 = (int)(val8); - } - result = (double)get_nxds_value(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); - Tcl_SetObjResult(interp,SWIG_From_double((double)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} -SWIGINTERN int -_wrap_get_nxds_text(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *result = 0 ; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:get_nxds_text ptr ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_nxds_text" "', argument " "1"" of type '" "void *""'"); - } - result = (char *)get_nxds_text(arg1); - Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); - return TCL_OK; -fail: - return TCL_ERROR; -} + SWIGINTERN int + _wrap_nx_compmakedata(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + int arg3; + int arg4; + void *arg5 = (void *) 0; + void *arg6 = (void *) 0; + int result; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + int val3; + int ecode3 = 0; + int val4; + int ecode4 = 0; + int res5; + int res6; - -SWIGINTERN int -_wrap_put_nxds_value(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - double arg2 ; - int arg3 = (int) 0 ; - int arg4 = (int) 0 ; - int arg5 = (int) 0 ; - int arg6 = (int) 0 ; - int arg7 = (int) 0 ; - int arg8 = (int) 0 ; - int arg9 = (int) 0 ; - int result; - int res1 ; - double val2 ; - int ecode2 = 0 ; - int val3 ; - int ecode3 = 0 ; - int val4 ; - int ecode4 = 0 ; - int val5 ; - int ecode5 = 0 ; - int val6 ; - int ecode6 = 0 ; - int val7 ; - int ecode7 = 0 ; - int val8 ; - int ecode8 = 0 ; - int val9 ; - int ecode9 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo|ooooooo:put_nxds_value ptr value ?dim0? ?dim1? ?dim2? ?dim3? ?dim4? ?dim5? ?dim6? ",(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "put_nxds_value" "', argument " "1"" of type '" "void *""'"); - } - ecode2 = SWIG_AsVal_double SWIG_TCL_CALL_ARGS_2(objv[2], &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "put_nxds_value" "', argument " "2"" of type '" "double""'"); - } - arg2 = (double)(val2); - if (objc > 3) { + if (SWIG_GetArgs + (interp, objc, objv, + "oooooo:nx_compmakedata handle name rank type dimPtr bufPtr ", + (void *) 0, (void *) 0, (void *) 0, (void *) 0, (void *) 0, + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_compmakedata" "', argument " + "1" " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_compmakedata" "', argument " + "2" " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); if (!SWIG_IsOK(ecode3)) { - SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "put_nxds_value" "', argument " "3"" of type '" "int""'"); - } - arg3 = (int)(val3); - } - if (objc > 4) { + SWIG_exception_fail(SWIG_ArgError(ecode3), + "in method '" "nx_compmakedata" "', argument " + "3" " of type '" "int" "'"); + } + arg3 = (int) (val3); ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); if (!SWIG_IsOK(ecode4)) { - SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "put_nxds_value" "', argument " "4"" of type '" "int""'"); - } - arg4 = (int)(val4); + SWIG_exception_fail(SWIG_ArgError(ecode4), + "in method '" "nx_compmakedata" "', argument " + "4" " of type '" "int" "'"); + } + arg4 = (int) (val4); + res5 = SWIG_ConvertPtr(objv[5], SWIG_as_voidptrptr(&arg5), 0, 0); + if (!SWIG_IsOK(res5)) { + SWIG_exception_fail(SWIG_ArgError(res5), + "in method '" "nx_compmakedata" "', argument " + "5" " of type '" "void *" "'"); + } + res6 = SWIG_ConvertPtr(objv[6], SWIG_as_voidptrptr(&arg6), 0, 0); + if (!SWIG_IsOK(res6)) { + SWIG_exception_fail(SWIG_ArgError(res6), + "in method '" "nx_compmakedata" "', argument " + "6" " of type '" "void *" "'"); + } + result = (int) nx_compmakedata(arg1, arg2, arg3, arg4, arg5, arg6); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_ERROR; } - if (objc > 5) { - ecode5 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[5], &val5); - if (!SWIG_IsOK(ecode5)) { - SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "put_nxds_value" "', argument " "5"" of type '" "int""'"); - } - arg5 = (int)(val5); + + + SWIGINTERN int + _wrap_nx_opendata(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + int result; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:nx_opendata handle name ", (void *) 0, + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_opendata" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_opendata" "', argument " "2" + " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); + result = (int) nx_opendata(arg1, arg2); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_ERROR; } - if (objc > 6) { - ecode6 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[6], &val6); - if (!SWIG_IsOK(ecode6)) { - SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "put_nxds_value" "', argument " "6"" of type '" "int""'"); - } - arg6 = (int)(val6); + + + SWIGINTERN int + _wrap_nx_closedata(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int result; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:nx_closedata handle ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_closedata" "', argument " "1" + " of type '" "void *" "'"); + } + result = (int) nx_closedata(arg1); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; } - if (objc > 7) { - ecode7 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[7], &val7); - if (!SWIG_IsOK(ecode7)) { - SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "put_nxds_value" "', argument " "7"" of type '" "int""'"); - } - arg7 = (int)(val7); + + + SWIGINTERN int + _wrap_nx_putslab(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + void *arg2 = (void *) 0; + void *arg3 = (void *) 0; + int result; + int res1; + int res2; + int res3; + + if (SWIG_GetArgs + (interp, objc, objv, "ooo:nx_putslab handle dataset startDim ", + (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_putslab" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_ConvertPtr(objv[2], SWIG_as_voidptrptr(&arg2), 0, 0); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_putslab" "', argument " "2" + " of type '" "void *" "'"); + } + res3 = SWIG_ConvertPtr(objv[3], SWIG_as_voidptrptr(&arg3), 0, 0); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), + "in method '" "nx_putslab" "', argument " "3" + " of type '" "void *" "'"); + } + result = (int) nx_putslab(arg1, arg2, arg3); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; } - if (objc > 8) { - ecode8 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[8], &val8); - if (!SWIG_IsOK(ecode8)) { - SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "put_nxds_value" "', argument " "8"" of type '" "int""'"); - } - arg8 = (int)(val8); + + + SWIGINTERN int + _wrap_nx_getslab(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + void *arg2 = (void *) 0; + void *arg3 = (void *) 0; + void *result = 0; + int res1; + int res2; + int res3; + + if (SWIG_GetArgs + (interp, objc, objv, "ooo:nx_getslab handle startdim size ", + (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_getslab" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_ConvertPtr(objv[2], SWIG_as_voidptrptr(&arg2), 0, 0); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_getslab" "', argument " "2" + " of type '" "void *" "'"); + } + res3 = SWIG_ConvertPtr(objv[3], SWIG_as_voidptrptr(&arg3), 0, 0); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), + "in method '" "nx_getslab" "', argument " "3" + " of type '" "void *" "'"); + } + result = (void *) nx_getslab(arg1, arg2, arg3); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + return TCL_OK; + fail: + return TCL_ERROR; } - if (objc > 9) { - ecode9 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[9], &val9); - if (!SWIG_IsOK(ecode9)) { - SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "put_nxds_value" "', argument " "9"" of type '" "int""'"); - } - arg9 = (int)(val9); + + + SWIGINTERN int + _wrap_nx_getds(ClientData clientData SWIGUNUSED, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + void *result = 0; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:nx_getds handle name ", (void *) 0, + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_getds" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_getds" "', argument " "2" + " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); + result = (void *) nx_getds(arg1, arg2); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_ERROR; } - result = (int)put_nxds_value(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} -SWIGINTERN int -_wrap_nx_getlasterror(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - char *result = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,":nx_getlasterror ") == TCL_ERROR) SWIG_fail; - result = (char *)nx_getlasterror(); - Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); - return TCL_OK; -fail: - return TCL_ERROR; -} + SWIGINTERN int + _wrap_nx_putds(ClientData clientData SWIGUNUSED, Tcl_Interp * interp, + int objc, Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + void *arg3 = (void *) 0; + int result; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + int res3; - -SWIGINTERN int -_wrap_nx_open(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - char *arg1 = (char *) 0 ; - int arg2 ; - void *result = 0 ; - int res1 ; - char *buf1 = 0 ; - int alloc1 = 0 ; - int val2 ; - int ecode2 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:nx_open filename accessCode ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_AsCharPtrAndSize(objv[1], &buf1, NULL, &alloc1); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_open" "', argument " "1"" of type '" "char *""'"); + if (SWIG_GetArgs + (interp, objc, objv, "ooo:nx_putds handle name dataset ", + (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_putds" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_putds" "', argument " "2" + " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); + res3 = SWIG_ConvertPtr(objv[3], SWIG_as_voidptrptr(&arg3), 0, 0); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), + "in method '" "nx_putds" "', argument " "3" + " of type '" "void *" "'"); + } + result = (int) nx_putds(arg1, arg2, arg3); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_ERROR; } - arg1 = (char *)(buf1); - ecode2 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[2], &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "nx_open" "', argument " "2"" of type '" "int""'"); - } - arg2 = (int)(val2); - result = (void *)nx_open(arg1,arg2); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); - return TCL_OK; -fail: - if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); - return TCL_ERROR; -} -SWIGINTERN int -_wrap_nx_flush(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - void *result = 0 ; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_flush handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_flush" "', argument " "1"" of type '" "void *""'"); + SWIGINTERN int + _wrap_nx_getdata(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + void *result = 0; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:nx_getdata handle ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_getdata" "', argument " "1" + " of type '" "void *" "'"); + } + result = (void *) nx_getdata(arg1); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + return TCL_OK; + fail: + return TCL_ERROR; } - result = (void *)nx_flush(arg1); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - return TCL_OK; -fail: - return TCL_ERROR; -} -SWIGINTERN int -_wrap_nx_close(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_close handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_close" "', argument " "1"" of type '" "void *""'"); + SWIGINTERN int + _wrap_nx_putdata(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + void *arg2 = (void *) 0; + int result; + int res1; + int res2; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:nx_putdata handle dataset ", (void *) 0, + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_putdata" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_ConvertPtr(objv[2], SWIG_as_voidptrptr(&arg2), 0, 0); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_putdata" "', argument " "2" + " of type '" "void *" "'"); + } + result = (int) nx_putdata(arg1, arg2); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; } - nx_close(arg1); - - return TCL_OK; -fail: - return TCL_ERROR; -} -SWIGINTERN int -_wrap_nx_makegroup(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - char *arg3 = (char *) 0 ; - int result; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - int res3 ; - char *buf3 = 0 ; - int alloc3 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"ooo:nx_makegroup handle name nxclass ",(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_makegroup" "', argument " "1"" of type '" "void *""'"); + SWIGINTERN int + _wrap_nx_getinfo(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + void *result = 0; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:nx_getinfo handle ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_getinfo" "', argument " "1" + " of type '" "void *" "'"); + } + result = (void *) nx_getinfo(arg1); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + return TCL_OK; + fail: + return TCL_ERROR; } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_makegroup" "', argument " "2"" of type '" "char *""'"); + + + SWIGINTERN int + _wrap_nx_getdataID(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + void *result = 0; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:nx_getdataID handle ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_getdataID" "', argument " "1" + " of type '" "void *" "'"); + } + result = (void *) nx_getdataID(arg1); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + return TCL_OK; + fail: + return TCL_ERROR; } - arg2 = (char *)(buf2); - res3 = SWIG_AsCharPtrAndSize(objv[3], &buf3, NULL, &alloc3); - if (!SWIG_IsOK(res3)) { - SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "nx_makegroup" "', argument " "3"" of type '" "char *""'"); + + + SWIGINTERN int + _wrap_nx_getnextattr(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char arg2; + char *result = 0; + int res1; + char val2; + int ecode2 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:nx_getnextattr handle separator ", + (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_getnextattr" "', argument " "1" + " of type '" "void *" "'"); + } + ecode2 = SWIG_AsVal_char SWIG_TCL_CALL_ARGS_2(objv[2], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), + "in method '" "nx_getnextattr" "', argument " "2" + " of type '" "char" "'"); + } + arg2 = (char) (val2); + result = (char *) nx_getnextattr(arg1, arg2); + Tcl_SetObjResult(interp, SWIG_FromCharPtr((const char *) result)); + return TCL_OK; + fail: + return TCL_ERROR; } - arg3 = (char *)(buf3); - result = (int)nx_makegroup(arg1,arg2,arg3); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); - return TCL_ERROR; -} -SWIGINTERN int -_wrap_nx_opengroup(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - char *arg3 = (char *) 0 ; - int result; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - int res3 ; - char *buf3 = 0 ; - int alloc3 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"ooo:nx_opengroup handle name nxclass ",(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_opengroup" "', argument " "1"" of type '" "void *""'"); + SWIGINTERN int + _wrap_nx_putattr(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + void *arg3 = (void *) 0; + int result; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + int res3; + + if (SWIG_GetArgs + (interp, objc, objv, "ooo:nx_putattr handle name ds ", (void *) 0, + (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_putattr" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_putattr" "', argument " "2" + " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); + res3 = SWIG_ConvertPtr(objv[3], SWIG_as_voidptrptr(&arg3), 0, 0); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), + "in method '" "nx_putattr" "', argument " "3" + " of type '" "void *" "'"); + } + result = (int) nx_putattr(arg1, arg2, arg3); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_ERROR; } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_opengroup" "', argument " "2"" of type '" "char *""'"); + + + SWIGINTERN int + _wrap_nx_getattr(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + char *arg2 = (char *) 0; + int arg3; + int arg4; + void *result = 0; + int res1; + int res2; + char *buf2 = 0; + int alloc2 = 0; + int val3; + int ecode3 = 0; + int val4; + int ecode4 = 0; + + if (SWIG_GetArgs + (interp, objc, objv, "oooo:nx_getattr handle name type length ", + (void *) 0, (void *) 0, (void *) 0, (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_getattr" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_getattr" "', argument " "2" + " of type '" "char *" "'"); + } + arg2 = (char *) (buf2); + ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), + "in method '" "nx_getattr" "', argument " "3" + " of type '" "int" "'"); + } + arg3 = (int) (val3); + ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), + "in method '" "nx_getattr" "', argument " "4" + " of type '" "int" "'"); + } + arg4 = (int) (val4); + result = (void *) nx_getattr(arg1, arg2, arg3, arg4); + Tcl_SetObjResult(interp, + SWIG_NewInstanceObj(SWIG_as_voidptr(result), + SWIGTYPE_p_void, 0)); + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_OK; + fail: + if (alloc2 == SWIG_NEWOBJ) + free((char *) buf2); + return TCL_ERROR; } - arg2 = (char *)(buf2); - res3 = SWIG_AsCharPtrAndSize(objv[3], &buf3, NULL, &alloc3); - if (!SWIG_IsOK(res3)) { - SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "nx_opengroup" "', argument " "3"" of type '" "char *""'"); + + + SWIGINTERN int + _wrap_nx_makelink(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + void *arg2 = (void *) 0; + int result; + int res1; + int res2; + + if (SWIG_GetArgs + (interp, objc, objv, "oo:nx_makelink handle link ", (void *) 0, + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_makelink" "', argument " "1" + " of type '" "void *" "'"); + } + res2 = SWIG_ConvertPtr(objv[2], SWIG_as_voidptrptr(&arg2), 0, 0); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), + "in method '" "nx_makelink" "', argument " "2" + " of type '" "void *" "'"); + } + result = (int) nx_makelink(arg1, arg2); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; } - arg3 = (char *)(buf3); - result = (int)nx_opengroup(arg1,arg2,arg3); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); - return TCL_ERROR; -} -SWIGINTERN int -_wrap_nx_openpath(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - int result; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:nx_openpath handle path ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_openpath" "', argument " "1"" of type '" "void *""'"); + SWIGINTERN int + _wrap_nx_opensourcegroup(ClientData clientData SWIGUNUSED, + Tcl_Interp * interp, int objc, + Tcl_Obj * CONST objv[]) { + void *arg1 = (void *) 0; + int result; + int res1; + + if (SWIG_GetArgs + (interp, objc, objv, "o:nx_opensourcegroup handle ", + (void *) 0) == TCL_ERROR) + SWIG_fail; + res1 = SWIG_ConvertPtr(objv[1], SWIG_as_voidptrptr(&arg1), 0, 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), + "in method '" "nx_opensourcegroup" "', argument " + "1" " of type '" "void *" "'"); + } + result = (int) nx_opensourcegroup(arg1); + Tcl_SetObjResult(interp, SWIG_From_int((int) (result))); + return TCL_OK; + fail: + return TCL_ERROR; } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_openpath" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - result = (int)nx_openpath(arg1,arg2); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_opengrouppath(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - int result; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:nx_opengrouppath handle path ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_opengrouppath" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_opengrouppath" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - result = (int)nx_opengrouppath(arg1,arg2); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_closegroup(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int result; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_closegroup handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_closegroup" "', argument " "1"" of type '" "void *""'"); - } - result = (int)nx_closegroup(arg1); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_getnextentry(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char arg2 ; - char *result = 0 ; - int res1 ; - char val2 ; - int ecode2 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:nx_getnextentry handle separator ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_getnextentry" "', argument " "1"" of type '" "void *""'"); - } - ecode2 = SWIG_AsVal_char SWIG_TCL_CALL_ARGS_2(objv[2], &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "nx_getnextentry" "', argument " "2"" of type '" "char""'"); - } - arg2 = (char)(val2); - result = (char *)nx_getnextentry(arg1,arg2); - Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_getgroupID(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - void *result = 0 ; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_getgroupID handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_getgroupID" "', argument " "1"" of type '" "void *""'"); - } - result = (void *)nx_getgroupID(arg1); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_initgroupdir(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int result; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_initgroupdir handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_initgroupdir" "', argument " "1"" of type '" "void *""'"); - } - result = (int)nx_initgroupdir(arg1); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_makedata(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - int arg3 ; - int arg4 ; - void *arg5 = (void *) 0 ; - int result; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - int val3 ; - int ecode3 = 0 ; - int val4 ; - int ecode4 = 0 ; - int res5 ; - - if (SWIG_GetArgs(interp, objc, objv,"ooooo:nx_makedata handle name rank type dimPtr ",(void *)0,(void *)0,(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_makedata" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_makedata" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); - if (!SWIG_IsOK(ecode3)) { - SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "nx_makedata" "', argument " "3"" of type '" "int""'"); - } - arg3 = (int)(val3); - ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); - if (!SWIG_IsOK(ecode4)) { - SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "nx_makedata" "', argument " "4"" of type '" "int""'"); - } - arg4 = (int)(val4); - res5 = SWIG_ConvertPtr(objv[5],SWIG_as_voidptrptr(&arg5), 0, 0); - if (!SWIG_IsOK(res5)) { - SWIG_exception_fail(SWIG_ArgError(res5), "in method '" "nx_makedata" "', argument " "5"" of type '" "void *""'"); - } - result = (int)nx_makedata(arg1,arg2,arg3,arg4,arg5); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_compmakedata(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - int arg3 ; - int arg4 ; - void *arg5 = (void *) 0 ; - void *arg6 = (void *) 0 ; - int result; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - int val3 ; - int ecode3 = 0 ; - int val4 ; - int ecode4 = 0 ; - int res5 ; - int res6 ; - - if (SWIG_GetArgs(interp, objc, objv,"oooooo:nx_compmakedata handle name rank type dimPtr bufPtr ",(void *)0,(void *)0,(void *)0,(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_compmakedata" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_compmakedata" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); - if (!SWIG_IsOK(ecode3)) { - SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "nx_compmakedata" "', argument " "3"" of type '" "int""'"); - } - arg3 = (int)(val3); - ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); - if (!SWIG_IsOK(ecode4)) { - SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "nx_compmakedata" "', argument " "4"" of type '" "int""'"); - } - arg4 = (int)(val4); - res5 = SWIG_ConvertPtr(objv[5],SWIG_as_voidptrptr(&arg5), 0, 0); - if (!SWIG_IsOK(res5)) { - SWIG_exception_fail(SWIG_ArgError(res5), "in method '" "nx_compmakedata" "', argument " "5"" of type '" "void *""'"); - } - res6 = SWIG_ConvertPtr(objv[6],SWIG_as_voidptrptr(&arg6), 0, 0); - if (!SWIG_IsOK(res6)) { - SWIG_exception_fail(SWIG_ArgError(res6), "in method '" "nx_compmakedata" "', argument " "6"" of type '" "void *""'"); - } - result = (int)nx_compmakedata(arg1,arg2,arg3,arg4,arg5,arg6); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_opendata(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - int result; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:nx_opendata handle name ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_opendata" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_opendata" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - result = (int)nx_opendata(arg1,arg2); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_closedata(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int result; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_closedata handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_closedata" "', argument " "1"" of type '" "void *""'"); - } - result = (int)nx_closedata(arg1); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_putslab(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - void *arg2 = (void *) 0 ; - void *arg3 = (void *) 0 ; - int result; - int res1 ; - int res2 ; - int res3 ; - - if (SWIG_GetArgs(interp, objc, objv,"ooo:nx_putslab handle dataset startDim ",(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_putslab" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_ConvertPtr(objv[2],SWIG_as_voidptrptr(&arg2), 0, 0); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_putslab" "', argument " "2"" of type '" "void *""'"); - } - res3 = SWIG_ConvertPtr(objv[3],SWIG_as_voidptrptr(&arg3), 0, 0); - if (!SWIG_IsOK(res3)) { - SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "nx_putslab" "', argument " "3"" of type '" "void *""'"); - } - result = (int)nx_putslab(arg1,arg2,arg3); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_getslab(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - void *arg2 = (void *) 0 ; - void *arg3 = (void *) 0 ; - void *result = 0 ; - int res1 ; - int res2 ; - int res3 ; - - if (SWIG_GetArgs(interp, objc, objv,"ooo:nx_getslab handle startdim size ",(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_getslab" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_ConvertPtr(objv[2],SWIG_as_voidptrptr(&arg2), 0, 0); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_getslab" "', argument " "2"" of type '" "void *""'"); - } - res3 = SWIG_ConvertPtr(objv[3],SWIG_as_voidptrptr(&arg3), 0, 0); - if (!SWIG_IsOK(res3)) { - SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "nx_getslab" "', argument " "3"" of type '" "void *""'"); - } - result = (void *)nx_getslab(arg1,arg2,arg3); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_getds(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - void *result = 0 ; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:nx_getds handle name ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_getds" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_getds" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - result = (void *)nx_getds(arg1,arg2); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_putds(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - void *arg3 = (void *) 0 ; - int result; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - int res3 ; - - if (SWIG_GetArgs(interp, objc, objv,"ooo:nx_putds handle name dataset ",(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_putds" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_putds" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - res3 = SWIG_ConvertPtr(objv[3],SWIG_as_voidptrptr(&arg3), 0, 0); - if (!SWIG_IsOK(res3)) { - SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "nx_putds" "', argument " "3"" of type '" "void *""'"); - } - result = (int)nx_putds(arg1,arg2,arg3); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_getdata(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - void *result = 0 ; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_getdata handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_getdata" "', argument " "1"" of type '" "void *""'"); - } - result = (void *)nx_getdata(arg1); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_putdata(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - void *arg2 = (void *) 0 ; - int result; - int res1 ; - int res2 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:nx_putdata handle dataset ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_putdata" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_ConvertPtr(objv[2],SWIG_as_voidptrptr(&arg2), 0, 0); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_putdata" "', argument " "2"" of type '" "void *""'"); - } - result = (int)nx_putdata(arg1,arg2); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_getinfo(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - void *result = 0 ; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_getinfo handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_getinfo" "', argument " "1"" of type '" "void *""'"); - } - result = (void *)nx_getinfo(arg1); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_getdataID(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - void *result = 0 ; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_getdataID handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_getdataID" "', argument " "1"" of type '" "void *""'"); - } - result = (void *)nx_getdataID(arg1); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_getnextattr(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char arg2 ; - char *result = 0 ; - int res1 ; - char val2 ; - int ecode2 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:nx_getnextattr handle separator ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_getnextattr" "', argument " "1"" of type '" "void *""'"); - } - ecode2 = SWIG_AsVal_char SWIG_TCL_CALL_ARGS_2(objv[2], &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "nx_getnextattr" "', argument " "2"" of type '" "char""'"); - } - arg2 = (char)(val2); - result = (char *)nx_getnextattr(arg1,arg2); - Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_putattr(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - void *arg3 = (void *) 0 ; - int result; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - int res3 ; - - if (SWIG_GetArgs(interp, objc, objv,"ooo:nx_putattr handle name ds ",(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_putattr" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_putattr" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - res3 = SWIG_ConvertPtr(objv[3],SWIG_as_voidptrptr(&arg3), 0, 0); - if (!SWIG_IsOK(res3)) { - SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "nx_putattr" "', argument " "3"" of type '" "void *""'"); - } - result = (int)nx_putattr(arg1,arg2,arg3); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_getattr(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - char *arg2 = (char *) 0 ; - int arg3 ; - int arg4 ; - void *result = 0 ; - int res1 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - int val3 ; - int ecode3 = 0 ; - int val4 ; - int ecode4 = 0 ; - - if (SWIG_GetArgs(interp, objc, objv,"oooo:nx_getattr handle name type length ",(void *)0,(void *)0,(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_getattr" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_getattr" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - ecode3 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[3], &val3); - if (!SWIG_IsOK(ecode3)) { - SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "nx_getattr" "', argument " "3"" of type '" "int""'"); - } - arg3 = (int)(val3); - ecode4 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[4], &val4); - if (!SWIG_IsOK(ecode4)) { - SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "nx_getattr" "', argument " "4"" of type '" "int""'"); - } - arg4 = (int)(val4); - result = (void *)nx_getattr(arg1,arg2,arg3,arg4); - Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_void,0)); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_OK; -fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_makelink(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - void *arg2 = (void *) 0 ; - int result; - int res1 ; - int res2 ; - - if (SWIG_GetArgs(interp, objc, objv,"oo:nx_makelink handle link ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_makelink" "', argument " "1"" of type '" "void *""'"); - } - res2 = SWIG_ConvertPtr(objv[2],SWIG_as_voidptrptr(&arg2), 0, 0); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nx_makelink" "', argument " "2"" of type '" "void *""'"); - } - result = (int)nx_makelink(arg1,arg2); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} - - -SWIGINTERN int -_wrap_nx_opensourcegroup(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { - void *arg1 = (void *) 0 ; - int result; - int res1 ; - - if (SWIG_GetArgs(interp, objc, objv,"o:nx_opensourcegroup handle ",(void *)0) == TCL_ERROR) SWIG_fail; - res1 = SWIG_ConvertPtr(objv[1],SWIG_as_voidptrptr(&arg1), 0, 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nx_opensourcegroup" "', argument " "1"" of type '" "void *""'"); - } - result = (int)nx_opensourcegroup(arg1); - Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); - return TCL_OK; -fail: - return TCL_ERROR; -} -static swig_command_info swig_commands[] = { - { SWIG_prefix "create_nxds", (swig_wrapper_func) _wrap_create_nxds, NULL}, - { SWIG_prefix "create_text_nxds", (swig_wrapper_func) _wrap_create_text_nxds, NULL}, - { SWIG_prefix "drop_nxds", (swig_wrapper_func) _wrap_drop_nxds, NULL}, - { SWIG_prefix "get_nxds_rank", (swig_wrapper_func) _wrap_get_nxds_rank, NULL}, - { SWIG_prefix "get_nxds_type", (swig_wrapper_func) _wrap_get_nxds_type, NULL}, - { SWIG_prefix "get_nxds_dim", (swig_wrapper_func) _wrap_get_nxds_dim, NULL}, - { SWIG_prefix "get_nxds_value", (swig_wrapper_func) _wrap_get_nxds_value, NULL}, - { SWIG_prefix "get_nxds_text", (swig_wrapper_func) _wrap_get_nxds_text, NULL}, - { SWIG_prefix "put_nxds_value", (swig_wrapper_func) _wrap_put_nxds_value, NULL}, - { SWIG_prefix "nx_getlasterror", (swig_wrapper_func) _wrap_nx_getlasterror, NULL}, - { SWIG_prefix "nx_open", (swig_wrapper_func) _wrap_nx_open, NULL}, - { SWIG_prefix "nx_flush", (swig_wrapper_func) _wrap_nx_flush, NULL}, - { SWIG_prefix "nx_close", (swig_wrapper_func) _wrap_nx_close, NULL}, - { SWIG_prefix "nx_makegroup", (swig_wrapper_func) _wrap_nx_makegroup, NULL}, - { SWIG_prefix "nx_opengroup", (swig_wrapper_func) _wrap_nx_opengroup, NULL}, - { SWIG_prefix "nx_openpath", (swig_wrapper_func) _wrap_nx_openpath, NULL}, - { SWIG_prefix "nx_opengrouppath", (swig_wrapper_func) _wrap_nx_opengrouppath, NULL}, - { SWIG_prefix "nx_closegroup", (swig_wrapper_func) _wrap_nx_closegroup, NULL}, - { SWIG_prefix "nx_getnextentry", (swig_wrapper_func) _wrap_nx_getnextentry, NULL}, - { SWIG_prefix "nx_getgroupID", (swig_wrapper_func) _wrap_nx_getgroupID, NULL}, - { SWIG_prefix "nx_initgroupdir", (swig_wrapper_func) _wrap_nx_initgroupdir, NULL}, - { SWIG_prefix "nx_makedata", (swig_wrapper_func) _wrap_nx_makedata, NULL}, - { SWIG_prefix "nx_compmakedata", (swig_wrapper_func) _wrap_nx_compmakedata, NULL}, - { SWIG_prefix "nx_opendata", (swig_wrapper_func) _wrap_nx_opendata, NULL}, - { SWIG_prefix "nx_closedata", (swig_wrapper_func) _wrap_nx_closedata, NULL}, - { SWIG_prefix "nx_putslab", (swig_wrapper_func) _wrap_nx_putslab, NULL}, - { SWIG_prefix "nx_getslab", (swig_wrapper_func) _wrap_nx_getslab, NULL}, - { SWIG_prefix "nx_getds", (swig_wrapper_func) _wrap_nx_getds, NULL}, - { SWIG_prefix "nx_putds", (swig_wrapper_func) _wrap_nx_putds, NULL}, - { SWIG_prefix "nx_getdata", (swig_wrapper_func) _wrap_nx_getdata, NULL}, - { SWIG_prefix "nx_putdata", (swig_wrapper_func) _wrap_nx_putdata, NULL}, - { SWIG_prefix "nx_getinfo", (swig_wrapper_func) _wrap_nx_getinfo, NULL}, - { SWIG_prefix "nx_getdataID", (swig_wrapper_func) _wrap_nx_getdataID, NULL}, - { SWIG_prefix "nx_getnextattr", (swig_wrapper_func) _wrap_nx_getnextattr, NULL}, - { SWIG_prefix "nx_putattr", (swig_wrapper_func) _wrap_nx_putattr, NULL}, - { SWIG_prefix "nx_getattr", (swig_wrapper_func) _wrap_nx_getattr, NULL}, - { SWIG_prefix "nx_makelink", (swig_wrapper_func) _wrap_nx_makelink, NULL}, - { SWIG_prefix "nx_opensourcegroup", (swig_wrapper_func) _wrap_nx_opensourcegroup, NULL}, + static swig_command_info swig_commands[] = { + {SWIG_prefix "create_nxds", (swig_wrapper_func) _wrap_create_nxds, + NULL}, + {SWIG_prefix "create_text_nxds", + (swig_wrapper_func) _wrap_create_text_nxds, NULL}, + {SWIG_prefix "drop_nxds", (swig_wrapper_func) _wrap_drop_nxds, NULL}, + {SWIG_prefix "get_nxds_rank", (swig_wrapper_func) _wrap_get_nxds_rank, + NULL}, + {SWIG_prefix "get_nxds_type", (swig_wrapper_func) _wrap_get_nxds_type, + NULL}, + {SWIG_prefix "get_nxds_dim", (swig_wrapper_func) _wrap_get_nxds_dim, + NULL}, + {SWIG_prefix "get_nxds_value", + (swig_wrapper_func) _wrap_get_nxds_value, NULL}, + {SWIG_prefix "get_nxds_text", (swig_wrapper_func) _wrap_get_nxds_text, + NULL}, + {SWIG_prefix "put_nxds_value", + (swig_wrapper_func) _wrap_put_nxds_value, NULL}, + {SWIG_prefix "nx_getlasterror", + (swig_wrapper_func) _wrap_nx_getlasterror, NULL}, + {SWIG_prefix "nx_open", (swig_wrapper_func) _wrap_nx_open, NULL}, + {SWIG_prefix "nx_flush", (swig_wrapper_func) _wrap_nx_flush, NULL}, + {SWIG_prefix "nx_close", (swig_wrapper_func) _wrap_nx_close, NULL}, + {SWIG_prefix "nx_makegroup", (swig_wrapper_func) _wrap_nx_makegroup, + NULL}, + {SWIG_prefix "nx_opengroup", (swig_wrapper_func) _wrap_nx_opengroup, + NULL}, + {SWIG_prefix "nx_openpath", (swig_wrapper_func) _wrap_nx_openpath, + NULL}, + {SWIG_prefix "nx_opengrouppath", + (swig_wrapper_func) _wrap_nx_opengrouppath, NULL}, + {SWIG_prefix "nx_closegroup", (swig_wrapper_func) _wrap_nx_closegroup, + NULL}, + {SWIG_prefix "nx_getnextentry", + (swig_wrapper_func) _wrap_nx_getnextentry, NULL}, + {SWIG_prefix "nx_getgroupID", (swig_wrapper_func) _wrap_nx_getgroupID, + NULL}, + {SWIG_prefix "nx_initgroupdir", + (swig_wrapper_func) _wrap_nx_initgroupdir, NULL}, + {SWIG_prefix "nx_makedata", (swig_wrapper_func) _wrap_nx_makedata, + NULL}, + {SWIG_prefix "nx_compmakedata", + (swig_wrapper_func) _wrap_nx_compmakedata, NULL}, + {SWIG_prefix "nx_opendata", (swig_wrapper_func) _wrap_nx_opendata, + NULL}, + {SWIG_prefix "nx_closedata", (swig_wrapper_func) _wrap_nx_closedata, + NULL}, + {SWIG_prefix "nx_putslab", (swig_wrapper_func) _wrap_nx_putslab, NULL}, + {SWIG_prefix "nx_getslab", (swig_wrapper_func) _wrap_nx_getslab, NULL}, + {SWIG_prefix "nx_getds", (swig_wrapper_func) _wrap_nx_getds, NULL}, + {SWIG_prefix "nx_putds", (swig_wrapper_func) _wrap_nx_putds, NULL}, + {SWIG_prefix "nx_getdata", (swig_wrapper_func) _wrap_nx_getdata, NULL}, + {SWIG_prefix "nx_putdata", (swig_wrapper_func) _wrap_nx_putdata, NULL}, + {SWIG_prefix "nx_getinfo", (swig_wrapper_func) _wrap_nx_getinfo, NULL}, + {SWIG_prefix "nx_getdataID", (swig_wrapper_func) _wrap_nx_getdataID, + NULL}, + {SWIG_prefix "nx_getnextattr", + (swig_wrapper_func) _wrap_nx_getnextattr, NULL}, + {SWIG_prefix "nx_putattr", (swig_wrapper_func) _wrap_nx_putattr, NULL}, + {SWIG_prefix "nx_getattr", (swig_wrapper_func) _wrap_nx_getattr, NULL}, + {SWIG_prefix "nx_makelink", (swig_wrapper_func) _wrap_nx_makelink, + NULL}, + {SWIG_prefix "nx_opensourcegroup", + (swig_wrapper_func) _wrap_nx_opensourcegroup, NULL}, {0, 0, 0} -}; + }; -static swig_var_info swig_variables[] = { - {0,0,0,0} -}; + static swig_var_info swig_variables[] = { + {0, 0, 0, 0} + }; -static swig_const_info swig_constants[] = { - {0,0,0,0,0,0} -}; + static swig_const_info swig_constants[] = { + {0, 0, 0, 0, 0, 0} + }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ -static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_void = {"_p_void", "void *", 0, 0, (void*)0, 0}; + static swig_type_info _swigt__p_char = + { "_p_char", "char *", 0, 0, (void *) 0, 0 }; + static swig_type_info _swigt__p_void = + { "_p_void", "void *", 0, 0, (void *) 0, 0 }; -static swig_type_info *swig_type_initial[] = { - &_swigt__p_char, - &_swigt__p_void, -}; + static swig_type_info *swig_type_initial[] = { + &_swigt__p_char, + &_swigt__p_void, + }; -static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; -static swig_cast_info _swigc__p_void[] = { {&_swigt__p_void, 0, 0, 0},{0, 0, 0, 0}}; + static swig_cast_info _swigc__p_char[] = + { {&_swigt__p_char, 0, 0, 0}, {0, 0, 0, 0} }; + static swig_cast_info _swigc__p_void[] = + { {&_swigt__p_void, 0, 0, 0}, {0, 0, 0, 0} }; -static swig_cast_info *swig_cast_initial[] = { - _swigc__p_char, - _swigc__p_void, -}; + static swig_cast_info *swig_cast_initial[] = { + _swigc__p_char, + _swigc__p_void, + }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ @@ -3231,31 +3817,28 @@ static swig_cast_info *swig_cast_initial[] = { #ifdef __cplusplus extern "C" { #if 0 -} /* c-mode */ +} /* c-mode */ #endif #endif - #if 0 #define SWIGRUNTIME_DEBUG #endif - - -SWIGRUNTIME void -SWIG_InitializeModule(void *clientdata) { +SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) +{ size_t i; swig_module_info *module_head, *iter; int found; - + clientdata = clientdata; - + /* check to see if the circular list has been setup, if not, set it up */ - if (swig_module.next==0) { + if (swig_module.next == 0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; } - + /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { @@ -3265,23 +3848,24 @@ SWIG_InitializeModule(void *clientdata) { module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ - found=0; - iter=module_head; + found = 0; + iter = module_head; do { - if (iter==&swig_module) { - found=1; + if (iter == &swig_module) { + found = 1; break; } - iter=iter->next; - } while (iter!= module_head); - + iter = iter->next; + } while (iter != module_head); + /* if the is found in the list, then all is done and we may leave */ - if (found) return; + if (found) + return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } - + /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); @@ -3290,14 +3874,17 @@ SWIG_InitializeModule(void *clientdata) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; - + #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); + printf("SWIG_InitializeModule: type %d %s\n", i, + swig_module.type_initial[i]->name); #endif - + /* if there is another module already loaded */ if (swig_module.next != &swig_module) { - type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); + type = + SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, + swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ @@ -3307,13 +3894,14 @@ SWIG_InitializeModule(void *clientdata) { if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); + printf("SWIG_InitializeModule: found and overwrite type %s \n", + type->name); #endif } } else { type = swig_module.type_initial[i]; } - + /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { @@ -3323,9 +3911,12 @@ SWIG_InitializeModule(void *clientdata) { printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { - ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); + ret = + SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, + cast->type->name); #ifdef SWIGRUNTIME_DEBUG - if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); + if (ret) + printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { @@ -3339,15 +3930,18 @@ SWIG_InitializeModule(void *clientdata) { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG - if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); + if (ocast) + printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif - if (!ocast) ret = 0; + if (!ocast) + ret = 0; } } - + if (!ret) { #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); + printf("SWIG_InitializeModule: adding cast %s\n", + cast->type->name); #endif if (type->cast) { type->cast->prev = cast; @@ -3361,19 +3955,20 @@ SWIG_InitializeModule(void *clientdata) { swig_module.types[i] = type; } swig_module.types[i] = 0; - + #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; - printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); + printf("SWIG_InitializeModule: type %d %s\n", i, + swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } - printf("---- Total casts: %d\n",j); + printf("---- Total casts: %d\n", j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif @@ -3384,22 +3979,24 @@ SWIG_InitializeModule(void *clientdata) { * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ -SWIGRUNTIME void -SWIG_PropagateClientData(void) { +SWIGRUNTIME void SWIG_PropagateClientData(void) +{ size_t i; swig_cast_info *equiv; static int init_run = 0; - - if (init_run) return; + + if (init_run) + return; init_run = 1; - + for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) - SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + SWIG_TypeClientData(equiv->type, + swig_module.types[i]->clientdata); } equiv = equiv->next; } @@ -3419,29 +4016,34 @@ SWIG_PropagateClientData(void) { #ifdef __cplusplus extern "C" { #endif - + /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ - + /* Install Constants */ - + SWIGINTERN void - SWIG_Tcl_InstallConstants(Tcl_Interp *interp, swig_const_info constants[]) { + SWIG_Tcl_InstallConstants(Tcl_Interp * interp, + swig_const_info constants[]) { int i; Tcl_Obj *obj; - + if (!swigconstTableinit) { Tcl_InitHashTable(&swigconstTable, TCL_STRING_KEYS); swigconstTableinit = 1; } for (i = 0; constants[i].type; i++) { - switch(constants[i].type) { + switch (constants[i].type) { case SWIG_TCL_POINTER: - obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); + obj = + SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype, + 0); break; case SWIG_TCL_BINARY: - obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); + obj = + SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, + *(constants[i].ptype)); break; default: obj = 0; @@ -3452,7 +4054,7 @@ extern "C" { } } } - + #ifdef __cplusplus } #endif @@ -3461,56 +4063,67 @@ extern "C" { * Partial Init method * -----------------------------------------------------------------------------*/ -SWIGEXPORT int SWIG_init(Tcl_Interp *interp) { +SWIGEXPORT int SWIG_init(Tcl_Interp * interp) +{ int i; - if (interp == 0) return TCL_ERROR; + if (interp == 0) + return TCL_ERROR; #ifdef USE_TCL_STUBS - if (Tcl_InitStubs(interp, (char*)"8.1", 0) == NULL) { + if (Tcl_InitStubs(interp, (char *) "8.1", 0) == NULL) { return TCL_ERROR; } -#endif - Tcl_PkgProvide(interp, (char*)SWIG_name, (char*)SWIG_version); - +#endif + Tcl_PkgProvide(interp, (char *) SWIG_name, (char *) SWIG_version); + #ifdef SWIG_namespace Tcl_Eval(interp, "namespace eval " SWIG_namespace " { }"); #endif - + SWIG_InitializeModule((void *) interp); SWIG_PropagateClientData(); - + for (i = 0; swig_commands[i].name; i++) { - Tcl_CreateObjCommand(interp, (char *) swig_commands[i].name, (swig_wrapper_func) swig_commands[i].wrapper, - swig_commands[i].clientdata, NULL); + Tcl_CreateObjCommand(interp, (char *) swig_commands[i].name, + (swig_wrapper_func) swig_commands[i].wrapper, + swig_commands[i].clientdata, NULL); } for (i = 0; swig_variables[i].name; i++) { - Tcl_SetVar(interp, (char *) swig_variables[i].name, (char *) "", TCL_GLOBAL_ONLY); - Tcl_TraceVar(interp, (char *) swig_variables[i].name, TCL_TRACE_READS | TCL_GLOBAL_ONLY, - (Tcl_VarTraceProc *) swig_variables[i].get, (ClientData) swig_variables[i].addr); - Tcl_TraceVar(interp, (char *) swig_variables[i].name, TCL_TRACE_WRITES | TCL_GLOBAL_ONLY, - (Tcl_VarTraceProc *) swig_variables[i].set, (ClientData) swig_variables[i].addr); + Tcl_SetVar(interp, (char *) swig_variables[i].name, (char *) "", + TCL_GLOBAL_ONLY); + Tcl_TraceVar(interp, (char *) swig_variables[i].name, + TCL_TRACE_READS | TCL_GLOBAL_ONLY, + (Tcl_VarTraceProc *) swig_variables[i].get, + (ClientData) swig_variables[i].addr); + Tcl_TraceVar(interp, (char *) swig_variables[i].name, + TCL_TRACE_WRITES | TCL_GLOBAL_ONLY, + (Tcl_VarTraceProc *) swig_variables[i].set, + (ClientData) swig_variables[i].addr); } - + SWIG_Tcl_InstallConstants(interp, swig_constants); - - - SWIG_Tcl_SetConstantObj(interp, "NXACC_READ", SWIG_From_int((int)(1))); - SWIG_Tcl_SetConstantObj(interp, "NXACC_RDWR", SWIG_From_int((int)(2))); - SWIG_Tcl_SetConstantObj(interp, "NXACC_CREATE", SWIG_From_int((int)(3))); - SWIG_Tcl_SetConstantObj(interp, "NXACC_CREATE4", SWIG_From_int((int)(4))); - SWIG_Tcl_SetConstantObj(interp, "NXACC_CREATE5", SWIG_From_int((int)(5))); - SWIG_Tcl_SetConstantObj(interp, "NX_FLOAT32", SWIG_From_int((int)(5))); - SWIG_Tcl_SetConstantObj(interp, "NX_FLOAT64", SWIG_From_int((int)(6))); - SWIG_Tcl_SetConstantObj(interp, "NX_INT8", SWIG_From_int((int)(20))); - SWIG_Tcl_SetConstantObj(interp, "NX_UINT8", SWIG_From_int((int)(21))); - SWIG_Tcl_SetConstantObj(interp, "NX_BOOLEAN", SWIG_From_int((int)(21))); - SWIG_Tcl_SetConstantObj(interp, "NX_INT16", SWIG_From_int((int)(22))); - SWIG_Tcl_SetConstantObj(interp, "NX_UINT16", SWIG_From_int((int)(23))); - SWIG_Tcl_SetConstantObj(interp, "NX_INT32", SWIG_From_int((int)(24))); - SWIG_Tcl_SetConstantObj(interp, "NX_UINT32", SWIG_From_int((int)(25))); - SWIG_Tcl_SetConstantObj(interp, "NX_CHAR", SWIG_From_int((int)(4))); + + + SWIG_Tcl_SetConstantObj(interp, "NXACC_READ", SWIG_From_int((int) (1))); + SWIG_Tcl_SetConstantObj(interp, "NXACC_RDWR", SWIG_From_int((int) (2))); + SWIG_Tcl_SetConstantObj(interp, "NXACC_CREATE", + SWIG_From_int((int) (3))); + SWIG_Tcl_SetConstantObj(interp, "NXACC_CREATE4", + SWIG_From_int((int) (4))); + SWIG_Tcl_SetConstantObj(interp, "NXACC_CREATE5", + SWIG_From_int((int) (5))); + SWIG_Tcl_SetConstantObj(interp, "NX_FLOAT32", SWIG_From_int((int) (5))); + SWIG_Tcl_SetConstantObj(interp, "NX_FLOAT64", SWIG_From_int((int) (6))); + SWIG_Tcl_SetConstantObj(interp, "NX_INT8", SWIG_From_int((int) (20))); + SWIG_Tcl_SetConstantObj(interp, "NX_UINT8", SWIG_From_int((int) (21))); + SWIG_Tcl_SetConstantObj(interp, "NX_BOOLEAN", SWIG_From_int((int) (21))); + SWIG_Tcl_SetConstantObj(interp, "NX_INT16", SWIG_From_int((int) (22))); + SWIG_Tcl_SetConstantObj(interp, "NX_UINT16", SWIG_From_int((int) (23))); + SWIG_Tcl_SetConstantObj(interp, "NX_INT32", SWIG_From_int((int) (24))); + SWIG_Tcl_SetConstantObj(interp, "NX_UINT32", SWIG_From_int((int) (25))); + SWIG_Tcl_SetConstantObj(interp, "NX_CHAR", SWIG_From_int((int) (4))); return TCL_OK; } -SWIGEXPORT int Nxinter_SafeInit(Tcl_Interp *interp) { +SWIGEXPORT int Nxinter_SafeInit(Tcl_Interp * interp) +{ return SWIG_init(interp); } - diff --git a/nxinterhelper.c b/nxinterhelper.c index 723e0adf..297b3144 100644 --- a/nxinterhelper.c +++ b/nxinterhelper.c @@ -18,320 +18,356 @@ An own error handler. nx_getlasterror will return the test of the last NeXus error. --------------------------------------------------------------------*/ -static char errorText[256]= ""; +static char errorText[256] = ""; -static void nxinterError(void *pData, char *error){ - strncpy(errorText,error,255); +static void nxinterError(void *pData, char *error) +{ + strncpy(errorText, error, 255); } + /*-----------------------------------------------------------------------*/ -char *nx_getlasterror(void){ +char *nx_getlasterror(void) +{ return strdup(errorText); } + /*-------------------- opening and closing -------------------------------*/ -void *nx_open(char *filename, int accessMethod){ +void *nx_open(char *filename, int accessMethod) +{ NXhandle handle = NULL; int status; - NXMSetError(NULL,nxinterError); - status = NXopen(filename,(NXaccess)accessMethod, &handle); - if(status == NX_OK){ - return handle; - }else{ - return NULL; - } -} -/*------------------------------------------------------------------------*/ -void *nx_flush(void *hundle){ - NXhandle handle; - int status; - - handle = (NXhandle)hundle; - status = NXflush(&handle); - if(status == NX_OK){ + NXMSetError(NULL, nxinterError); + status = NXopen(filename, (NXaccess) accessMethod, &handle); + if (status == NX_OK) { return handle; } else { return NULL; } } + +/*------------------------------------------------------------------------*/ +void *nx_flush(void *hundle) +{ + NXhandle handle; + int status; + + handle = (NXhandle) hundle; + status = NXflush(&handle); + if (status == NX_OK) { + return handle; + } else { + return NULL; + } +} + /*-----------------------------------------------------------------------*/ -void nx_close(void *hundle){ +void nx_close(void *hundle) +{ NXhandle handle; - handle = (NXhandle)hundle; + handle = (NXhandle) hundle; NXclose(&handle); } + /*=================== group handling functions ========================*/ -int nx_makegroup(void *handle, char *name, char *nxclass){ +int nx_makegroup(void *handle, char *name, char *nxclass) +{ int status; NXhandle hfil; - hfil = (NXhandle)handle; - status = NXmakegroup(hfil,name, nxclass); - if(status == NX_OK){ + hfil = (NXhandle) handle; + status = NXmakegroup(hfil, name, nxclass); + if (status == NX_OK) { return 1; } else { return 0; } } + /*---------------------------------------------------------------------*/ -int nx_opengroup(void *handle, char *name, char *nxclass){ +int nx_opengroup(void *handle, char *name, char *nxclass) +{ int status; NXhandle hfil; - hfil = (NXhandle)handle; - status = NXopengroup(hfil,name, nxclass); - if(status == NX_OK){ + hfil = (NXhandle) handle; + status = NXopengroup(hfil, name, nxclass); + if (status == NX_OK) { return 1; } else { return 0; } } + /*---------------------------------------------------------------------*/ -int nx_openpath(void *handle, char *path){ +int nx_openpath(void *handle, char *path) +{ int status; NXhandle hfil; - hfil = (NXhandle)handle; - status = NXopenpath(hfil,path); - if(status == NX_OK){ + hfil = (NXhandle) handle; + status = NXopenpath(hfil, path); + if (status == NX_OK) { return 1; } else { return 0; } } + /*---------------------------------------------------------------------*/ -int nx_opengrouppath(void *handle, char *path){ +int nx_opengrouppath(void *handle, char *path) +{ int status; NXhandle hfil; - hfil = (NXhandle)handle; - status = NXopengrouppath(hfil,path); - if(status == NX_OK){ + hfil = (NXhandle) handle; + status = NXopengrouppath(hfil, path); + if (status == NX_OK) { return 1; } else { return 0; } } + /*--------------------------------------------------------------------*/ -int nx_closegroup(void *handle){ +int nx_closegroup(void *handle) +{ int status; NXhandle hfil; - hfil = (NXhandle)handle; + hfil = (NXhandle) handle; status = NXclosegroup(hfil); - if(status == NX_OK){ + if (status == NX_OK) { return 1; } else { return 0; } } + /*-------------------------------------------------------------------*/ -char *nx_getnextentry(void *handle, char separator){ +char *nx_getnextentry(void *handle, char separator) +{ int status, length, type; NXhandle hfil; char *resultBuffer = NULL; - NXname group,nxclass; + NXname group, nxclass; - hfil = (NXhandle)handle; - status = NXgetnextentry(hfil,group, nxclass,&type); - if(status == NX_OK){ + hfil = (NXhandle) handle; + status = NXgetnextentry(hfil, group, nxclass, &type); + if (status == NX_OK) { length = 30 + strlen(group) + strlen(nxclass); /* - This introduces a memory leak. I had hoped, that swig would - kill it for me after use, but I'am afraid, this is not the - case. Unfortately I do not know how to fix the issue. - */ - resultBuffer = (char *)malloc(length*sizeof(char)); - if(resultBuffer == NULL){ + This introduces a memory leak. I had hoped, that swig would + kill it for me after use, but I'am afraid, this is not the + case. Unfortately I do not know how to fix the issue. + */ + resultBuffer = (char *) malloc(length * sizeof(char)); + if (resultBuffer == NULL) { return NULL; } - sprintf(resultBuffer,"%s%c%s%c%d",group,separator,nxclass, - separator,type); + sprintf(resultBuffer, "%s%c%s%c%d", group, separator, nxclass, + separator, type); return resultBuffer; } else { return NULL; } } + /*-------------------------------------------------------------------*/ -void *nx_getgroupID(void *handle){ +void *nx_getgroupID(void *handle) +{ int status; NXhandle hfil; NXlink *linki; - linki = (NXlink *)malloc(sizeof(NXlink)); - if(linki == NULL){ + linki = (NXlink *) malloc(sizeof(NXlink)); + if (linki == NULL) { return NULL; } - hfil = (NXhandle)handle; - status = NXgetgroupID(hfil,linki); - if(status == NX_OK){ + hfil = (NXhandle) handle; + status = NXgetgroupID(hfil, linki); + if (status == NX_OK) { return linki; } else { return NULL; } } + /*------------------------------------------------------------------*/ -int nx_initgroupdir(void *handle){ +int nx_initgroupdir(void *handle) +{ int status; NXhandle hfil; - hfil = (NXhandle)handle; + hfil = (NXhandle) handle; status = NXinitgroupdir(hfil); - if(status == NX_OK){ + if (status == NX_OK) { return 1; } else { return 0; } } + /*========================== dataset handling =======================*/ -int nx_makedata(void *ptr, char *name, int rank, int type, - void *dimPtr){ +int nx_makedata(void *ptr, char *name, int rank, int type, void *dimPtr) +{ int status; NXhandle hfil; pNXDS dimData; - hfil = (NXhandle)ptr; - dimData = (pNXDS)dimPtr; - if(dimData->type != NX_INT32){ - NXIReportError(NULL,"ERROR: dimension data not integer"); + hfil = (NXhandle) ptr; + dimData = (pNXDS) dimPtr; + if (dimData->type != NX_INT32) { + NXIReportError(NULL, "ERROR: dimension data not integer"); return 0; } - status = NXmakedata(hfil, name, type, rank, - dimData->u.iPtr); - if(status == NX_OK){ + status = NXmakedata(hfil, name, type, rank, dimData->u.iPtr); + if (status == NX_OK) { return 1; } else { return 0; } } + /*--------------------------------------------------------------------*/ -int nx_compmakedata(void *ptr, char *name, int rank, int type, - void *dimPtr, void *bufPtr){ +int nx_compmakedata(void *ptr, char *name, int rank, int type, + void *dimPtr, void *bufPtr) +{ int status; NXhandle hfil; pNXDS dimData, bufData; - hfil = (NXhandle)ptr; - dimData = (pNXDS)dimPtr; - if(dimData->type != NX_INT32){ - NXIReportError(NULL,"ERROR: dimension data not integer"); + hfil = (NXhandle) ptr; + dimData = (pNXDS) dimPtr; + if (dimData->type != NX_INT32) { + NXIReportError(NULL, "ERROR: dimension data not integer"); return 0; } - bufData = (pNXDS)bufPtr; - status = NXcompmakedata(hfil, name, type, rank, - dimData->u.iPtr, NX_COMP_LZW,bufData->u.iPtr); - if(status == NX_OK){ + bufData = (pNXDS) bufPtr; + status = NXcompmakedata(hfil, name, type, rank, + dimData->u.iPtr, NX_COMP_LZW, bufData->u.iPtr); + if (status == NX_OK) { return 1; } else { return 0; } } + /*----------------------------------------------------------------------*/ -int nx_opendata(void *handle, char *name){ +int nx_opendata(void *handle, char *name) +{ int status; NXhandle hfil; - hfil = (NXhandle)handle; - status = NXopendata(hfil,name); - if(status == NX_OK){ + hfil = (NXhandle) handle; + status = NXopendata(hfil, name); + if (status == NX_OK) { return 1; } else { return 0; } } + /*----------------------------------------------------------------------*/ -int nx_closedata(void *handle){ +int nx_closedata(void *handle) +{ int status; NXhandle hfil; - hfil = (NXhandle)handle; + hfil = (NXhandle) handle; status = NXclosedata(hfil); - if(status == NX_OK){ + if (status == NX_OK) { return 1; } else { return 0; } } + /*------------------------------------------------------------------------*/ -int nx_putslab(void *handle, void *dataset, void *startDim){ +int nx_putslab(void *handle, void *dataset, void *startDim) +{ int status; NXhandle hfil; pNXDS data; pNXDS start; - int end[NX_MAXRANK], i; + int end[NX_MAXRANK], i; - hfil = (NXhandle)handle; - data = (pNXDS)dataset; - start = (pNXDS)startDim; - for(i = 0; i < data->rank;i++){ + hfil = (NXhandle) handle; + data = (pNXDS) dataset; + start = (pNXDS) startDim; + for (i = 0; i < data->rank; i++) { end[i] = data->dim[i]; } - status = NXputslab(hfil,data->u.ptr,start->u.iPtr,end); - if(status == NX_OK){ + status = NXputslab(hfil, data->u.ptr, start->u.iPtr, end); + if (status == NX_OK) { return 1; } else { return 0; } } + /*-----------------------------------------------------------------------*/ -void *nx_getslab(void *handle, void *startdim, void *sizedim){ +void *nx_getslab(void *handle, void *startdim, void *sizedim) +{ pNXDS resultdata; pNXDS start, size; int status, rank, type, dim[NX_MAXRANK]; NXhandle hfil; - hfil = (NXhandle)handle; - start = (pNXDS)startdim; - size = (pNXDS)sizedim; + hfil = (NXhandle) handle; + start = (pNXDS) startdim; + size = (pNXDS) sizedim; /* - get info first, then allocate data - */ - status = NXgetinfo(hfil, &rank,dim,&type); - if(status != NX_OK){ - return NULL; - } - - resultdata = createNXDataset(rank,type,size->u.iPtr); - if(resultdata == NULL){ + get info first, then allocate data + */ + status = NXgetinfo(hfil, &rank, dim, &type); + if (status != NX_OK) { return NULL; } - status = NXgetslab(hfil,resultdata->u.ptr,start->u.iPtr, - size->u.iPtr); - if(status == NX_OK){ + resultdata = createNXDataset(rank, type, size->u.iPtr); + if (resultdata == NULL) { + return NULL; + } + + status = NXgetslab(hfil, resultdata->u.ptr, start->u.iPtr, size->u.iPtr); + if (status == NX_OK) { return resultdata; - }else{ + } else { dropNXDataset(resultdata); return NULL; } } + /*------------------------------------------------------------------------*/ -void *nx_getds(void *handle, char *name){ +void *nx_getds(void *handle, char *name) +{ pNXDS result = NULL; - int rank, type,dim[NX_MAXRANK],status; + int rank, type, dim[NX_MAXRANK], status; NXhandle hfil; - hfil = (NXhandle)handle; - status = NXopendata(hfil,name); - if(status != NX_OK){ + hfil = (NXhandle) handle; + status = NXopendata(hfil, name); + if (status != NX_OK) { return NULL; } - status = NXgetinfo(hfil,&rank,dim,&type); - if(status != NX_OK){ + status = NXgetinfo(hfil, &rank, dim, &type); + if (status != NX_OK) { return NULL; } - result = createNXDataset(rank,type,dim); - if(result == NULL){ + result = createNXDataset(rank, type, dim); + if (result == NULL) { NXclosedata(hfil); return NULL; } - status = NXgetdata(hfil,result->u.ptr); - if(result == NULL){ + status = NXgetdata(hfil, result->u.ptr); + if (result == NULL) { NXclosedata(hfil); dropNXDataset(result); return NULL; @@ -339,223 +375,240 @@ void *nx_getds(void *handle, char *name){ NXclosedata(hfil); return result; } + /*----------------------------------------------------------------------*/ -int nx_putds(void *handle, char *name, void *dataset){ +int nx_putds(void *handle, char *name, void *dataset) +{ NXhandle hfil; int status; pNXDS data; - hfil = (NXhandle)handle; - data = (pNXDS)dataset; + hfil = (NXhandle) handle; + data = (pNXDS) dataset; - status = NXopendata(hfil,name); - if(status != NX_OK){ - status = NXmakedata(hfil,name,data->type,data->rank,data->dim); - if(status != NX_OK){ + status = NXopendata(hfil, name); + if (status != NX_OK) { + status = NXmakedata(hfil, name, data->type, data->rank, data->dim); + if (status != NX_OK) { return 0; } - NXopendata(hfil,name); + NXopendata(hfil, name); } - status = NXputdata(hfil,data->u.ptr); + status = NXputdata(hfil, data->u.ptr); NXclosedata(hfil); - if(status != NX_OK){ + if (status != NX_OK) { return 0; - }else{ + } else { return 1; } } + /*------------------------------------------------------------------------*/ -void *nx_getdata(void *handle){ +void *nx_getdata(void *handle) +{ pNXDS result = NULL; - int rank, type,dim[NX_MAXRANK],status; + int rank, type, dim[NX_MAXRANK], status; NXhandle hfil; - hfil = (NXhandle)handle; - status = NXgetinfo(hfil,&rank,dim,&type); - if(status != NX_OK){ + hfil = (NXhandle) handle; + status = NXgetinfo(hfil, &rank, dim, &type); + if (status != NX_OK) { return NULL; } - result = createNXDataset(rank,type,dim); - if(result == NULL){ + result = createNXDataset(rank, type, dim); + if (result == NULL) { NXclosedata(hfil); return NULL; } - status = NXgetdata(hfil,result->u.ptr); - if(result == NULL){ + status = NXgetdata(hfil, result->u.ptr); + if (result == NULL) { dropNXDataset(result); return NULL; } return result; } + /*----------------------------------------------------------------------*/ -int nx_putdata(void *handle, void *dataset){ +int nx_putdata(void *handle, void *dataset) +{ NXhandle hfil; int status; pNXDS data; - hfil = (NXhandle)handle; - data = (pNXDS)dataset; + hfil = (NXhandle) handle; + data = (pNXDS) dataset; - if(data == NULL){ - NXIReportError(NULL,"ERROR: NULL data pointer in nx_putdata"); + if (data == NULL) { + NXIReportError(NULL, "ERROR: NULL data pointer in nx_putdata"); return 0; } - status = NXputdata(hfil,data->u.ptr); - if(status != NX_OK){ + status = NXputdata(hfil, data->u.ptr); + if (status != NX_OK) { return 0; - }else{ + } else { return 1; } } + /*----------------------------------------------------------------------*/ -void *nx_getinfo(void *handle){ +void *nx_getinfo(void *handle) +{ NXhandle hfil; int status, type, rank, dim[NX_MAXRANK], rdim[1], i; pNXDS data = NULL; - hfil = (NXhandle)handle; + hfil = (NXhandle) handle; - status = NXgetinfo(handle,&rank,dim,&type); - if(status != NX_OK){ + status = NXgetinfo(handle, &rank, dim, &type); + if (status != NX_OK) { return NULL; } rdim[0] = 2 + rank; - data = createNXDataset(1,NX_INT32,rdim); + data = createNXDataset(1, NX_INT32, rdim); data->u.iPtr[0] = type; data->u.iPtr[1] = rank; - for(i = 0; i < rank; i++){ - data->u.iPtr[2+i] = dim[i]; + for (i = 0; i < rank; i++) { + data->u.iPtr[2 + i] = dim[i]; } return data; } + /*----------------------------------------------------------------------*/ -void *nx_getdataID(void *handle){ +void *nx_getdataID(void *handle) +{ NXhandle hfil; int status; NXlink *linki; - linki = (NXlink *)malloc(sizeof(NXlink)); - if(linki == NULL){ + linki = (NXlink *) malloc(sizeof(NXlink)); + if (linki == NULL) { return NULL; } - hfil = (NXhandle)handle; - status = NXgetdataID(hfil,linki); - if(status == NX_OK){ + hfil = (NXhandle) handle; + status = NXgetdataID(hfil, linki); + if (status == NX_OK) { return linki; } else { free(linki); return NULL; } } + /*-------------------------------------------------------------------*/ -char *nx_getnextattr(void *handle, char separator){ +char *nx_getnextattr(void *handle, char separator) +{ int status, length, type; char *result; NXhandle hfil; NXname aName; - hfil = (NXhandle)handle; - status = NXgetnextattr(hfil,aName, &length, &type); - if(status == NX_OK){ + hfil = (NXhandle) handle; + status = NXgetnextattr(hfil, aName, &length, &type); + if (status == NX_OK) { /* - This introduces a memory leak. I had hoped, that swig would - kill it for me after use, but I'am afraid, this is not the - case. Unfortately I do not know how to fix the issue. - */ - result = (char *)malloc((20+strlen(aName))*sizeof(char)); - if(result == NULL){ + This introduces a memory leak. I had hoped, that swig would + kill it for me after use, but I'am afraid, this is not the + case. Unfortately I do not know how to fix the issue. + */ + result = (char *) malloc((20 + strlen(aName)) * sizeof(char)); + if (result == NULL) { return NULL; } - memset(result,0,(20+strlen(aName))*sizeof(char)); - sprintf(result,"%s%c%d%c%d", aName,separator, - length,separator,type); + memset(result, 0, (20 + strlen(aName)) * sizeof(char)); + sprintf(result, "%s%c%d%c%d", aName, separator, + length, separator, type); return result; } else { return NULL; } } + /*-------------------------------------------------------------------*/ -int nx_putattr(void *handle, char *name, void *ds){ +int nx_putattr(void *handle, char *name, void *ds) +{ int status; NXhandle hfil; pNXDS data; - hfil = (NXhandle)handle; - data = (pNXDS)ds; - status = NXputattr(hfil,name,data->u.ptr,data->dim[0],data->type); - if(status == NX_OK){ + hfil = (NXhandle) handle; + data = (pNXDS) ds; + status = NXputattr(hfil, name, data->u.ptr, data->dim[0], data->type); + if (status == NX_OK) { return 1; - }else{ + } else { return 0; } } + /*-------------------------------------------------------------------*/ -void *nx_getattr(void *handle, char *name, int type, int length){ +void *nx_getattr(void *handle, char *name, int type, int length) +{ NXhandle hfil; int status, tp, ll, dim[1]; pNXDS data = NULL; - hfil = (NXhandle)handle; + hfil = (NXhandle) handle; /* - prepare dataset - */ - dim[0] = length+1; - data = createNXDataset(1,type,dim); - if(data == NULL){ + prepare dataset + */ + dim[0] = length + 1; + data = createNXDataset(1, type, dim); + if (data == NULL) { return NULL; } - + /* - finally read the real data - */ + finally read the real data + */ ll = length; tp = type; - status = NXgetattr(hfil,name,data->u.ptr,&ll,&tp); - if(status != NX_OK){ + status = NXgetattr(hfil, name, data->u.ptr, &ll, &tp); + if (status != NX_OK) { dropNXDataset(data); return NULL; } return data; } + /*-----------------------------------------------------------------------*/ -int nx_makelink(void *handle, void *link){ +int nx_makelink(void *handle, void *link) +{ NXhandle hfil; - NXlink* lk; + NXlink *lk; int status; - hfil = (NXhandle)handle; - lk = (NXlink *)link; + hfil = (NXhandle) handle; + lk = (NXlink *) link; - status = NXmakelink(hfil,lk); - if(status == NX_OK){ + status = NXmakelink(hfil, lk); + if (status == NX_OK) { return 1; - }else{ + } else { return 0; } } + /*-----------------------------------------------------------------------*/ -int nx_opensourcegroup(void *handle){ +int nx_opensourcegroup(void *handle) +{ NXhandle hfil; int status; - hfil = (NXhandle)handle; + hfil = (NXhandle) handle; status = NXopensourcegroup(hfil); - if(status == NX_OK){ + if (status == NX_OK) { return 1; - }else{ + } else { return 0; } } - - - diff --git a/nxinterhelper.h b/nxinterhelper.h index 7c2e280c..2b0d0b12 100644 --- a/nxinterhelper.h +++ b/nxinterhelper.h @@ -16,7 +16,7 @@ /*------------- opening and closing section ---------------------*/ void *nx_open(char *filename, int accessMethod); void *nx_flush(void *handle); -void nx_close(void *handle); +void nx_close(void *handle); /*--------------- group handling section ------------------------*/ int nx_makegroup(void *handle, char *name, char *nxclass); int nx_opengroup(void *handle, char *name, char *nxclass); @@ -29,8 +29,8 @@ int nx_initgroupdir(void *handle); /*---------------- dataset handling -----------------------------*/ int nx_makedata(void *ptr, char *name, int rank, int type, void *dimPtr); -int nx_compmakedata(void *ptr, char *name, int rank, int type, - void *dimPtr, void *bufPtr); +int nx_compmakedata(void *ptr, char *name, int rank, int type, + void *dimPtr, void *bufPtr); int nx_opendata(void *handle, char *name); int nx_closedata(void *handle); @@ -39,18 +39,18 @@ int nx_putslab(void *handle, void *dataset, void *startDim); void *nx_getslab(void *handle, void *startdim, void *size); void *nx_getds(void *handle, char *name); -int nx_putds(void *handle, char *name, void *dataset); +int nx_putds(void *handle, char *name, void *dataset); void *nx_getdata(void *handle); -int nx_putdata(void *handle,void *dataset); +int nx_putdata(void *handle, void *dataset); void *nx_getinfo(void *handle); void *nx_getdataID(void *handle); /*-------------------- attributes --------------------------------*/ char *nx_getnextattr(void *handle, char separator); -int nx_putattr(void *handle, char *name, void *ds); -void *nx_getattr(void *handle, char *name, int type, int length); +int nx_putattr(void *handle, char *name, void *ds); +void *nx_getattr(void *handle, char *name, int type, int length); /*---------------------- link -----------------------------------*/ @@ -60,9 +60,3 @@ int nx_opensourcegroup(void *handle); char *nx_getlasterror(void); #endif - - - - - - diff --git a/nxio.c b/nxio.c index a74145e9..d5e040aa 100644 --- a/nxio.c +++ b/nxio.c @@ -40,179 +40,176 @@ typedef struct { char name[30]; char format[30]; - int nx_type; -}type_code; + int nx_type; +} type_code; #define NTYPECODE 11 static type_code typecode[NTYPECODE]; /*-----------------------------------------------------------------------*/ -void initializeNumberFormats(){ +void initializeNumberFormats() +{ type_code myCode; - strcpy(myCode.name,"NX_FLOAT32"); - strcpy(myCode.format,"%12.4f"); + strcpy(myCode.name, "NX_FLOAT32"); + strcpy(myCode.format, "%12.4f"); myCode.nx_type = NX_FLOAT32; typecode[0] = myCode; - strcpy(myCode.name,"NX_FLOAT64"); - strcpy(myCode.format,"%16.5f"); + strcpy(myCode.name, "NX_FLOAT64"); + strcpy(myCode.format, "%16.5f"); myCode.nx_type = NX_FLOAT64; typecode[1] = myCode; - strcpy(myCode.name,"NX_INT8"); - strcpy(myCode.format,"%5d"); + strcpy(myCode.name, "NX_INT8"); + strcpy(myCode.format, "%5d"); myCode.nx_type = NX_INT8; typecode[2] = myCode; - strcpy(myCode.name,"NX_UINT8"); - strcpy(myCode.format,"%5d"); + strcpy(myCode.name, "NX_UINT8"); + strcpy(myCode.format, "%5d"); myCode.nx_type = NX_UINT8; typecode[3] = myCode; - strcpy(myCode.name,"NX_INT16"); - strcpy(myCode.format,"%8d"); + strcpy(myCode.name, "NX_INT16"); + strcpy(myCode.format, "%8d"); myCode.nx_type = NX_INT16; typecode[4] = myCode; - strcpy(myCode.name,"NX_UINT16"); - strcpy(myCode.format,"%8d"); + strcpy(myCode.name, "NX_UINT16"); + strcpy(myCode.format, "%8d"); myCode.nx_type = NX_UINT16; typecode[5] = myCode; - strcpy(myCode.name,"NX_INT32"); - strcpy(myCode.format,"%12d"); + strcpy(myCode.name, "NX_INT32"); + strcpy(myCode.format, "%12d"); myCode.nx_type = NX_INT32; typecode[6] = myCode; - strcpy(myCode.name,"NX_UINT32"); - strcpy(myCode.format,"%12d"); + strcpy(myCode.name, "NX_UINT32"); + strcpy(myCode.format, "%12d"); myCode.nx_type = NX_UINT32; typecode[7] = myCode; - strcpy(myCode.name,"NX_INT64"); - strcpy(myCode.format,"%24" PRINTF_INT64 ); + strcpy(myCode.name, "NX_INT64"); + strcpy(myCode.format, "%24" PRINTF_INT64); myCode.nx_type = NX_INT64; typecode[8] = myCode; - strcpy(myCode.name,"NX_UINT64"); - strcpy(myCode.format,"%24" PRINTF_UINT64); + strcpy(myCode.name, "NX_UINT64"); + strcpy(myCode.format, "%24" PRINTF_UINT64); myCode.nx_type = NX_UINT64; typecode[9] = myCode; - strcpy(myCode.name,"NX_CHAR"); - strcpy(myCode.format,"%c"); + strcpy(myCode.name, "NX_CHAR"); + strcpy(myCode.format, "%c"); myCode.nx_type = NX_CHAR; typecode[10] = myCode; } + /*----------------------------------------------------------------------*/ -void setNumberFormat(int nx_type, char *format){ +void setNumberFormat(int nx_type, char *format) +{ int i; - for(i = 0; i < NTYPECODE; i++){ - if(typecode[i].nx_type == nx_type){ - strncpy(typecode[i].format,format,29); + for (i = 0; i < NTYPECODE; i++) { + if (typecode[i].nx_type == nx_type) { + strncpy(typecode[i].format, format, 29); } } } + /*------------------------------------------------------------------*/ -static void getNumberFormat(int nx_type, char format[30]){ +static void getNumberFormat(int nx_type, char format[30]) +{ int i; - for(i = 0; i < NTYPECODE; i++){ - if(typecode[i].nx_type == nx_type){ - strncpy(format,typecode[i].format,29); + for (i = 0; i < NTYPECODE; i++) { + if (typecode[i].nx_type == nx_type) { + strncpy(format, typecode[i].format, 29); } } } + /*----------------------------------------------------------------*/ -void getNumberText(int nx_type, char *typestring, int typeLen){ +void getNumberText(int nx_type, char *typestring, int typeLen) +{ int i; - for(i = 0; i < NTYPECODE; i++){ - if(typecode[i].nx_type == nx_type){ - strncpy(typestring,typecode[i].name,typeLen); + for (i = 0; i < NTYPECODE; i++) { + if (typecode[i].nx_type == nx_type) { + strncpy(typestring, typecode[i].name, typeLen); } } } + /* * 'mxml_add_char()' - Add a character to a buffer, expanding as needed. * copied here from mxml-file.c to achieve compatibility with mxml-2.1 * standard */ -static int /* O - 0 on success, -1 on error */ -myxml_add_char(int ch, /* I - Character to add */ - char **bufptr, /* IO - Current position in buffer */ - char **buffer, /* IO - Current buffer */ - int *bufsize) /* IO - Current buffer size */ -{ - char *newbuffer; /* New buffer value */ +static int /* O - 0 on success, -1 on error */ myxml_add_char(int ch, /* I - Character to add */ + char **bufptr, /* IO - Current position in buffer */ + char **buffer, /* IO - Current buffer */ + int + *bufsize) +{ /* IO - Current buffer size */ + char *newbuffer; /* New buffer value */ - if (*bufptr >= (*buffer + *bufsize - 4)) - { - /* - * Increase the size of the buffer... - */ + if (*bufptr >= (*buffer + *bufsize - 4)) { + /* + * Increase the size of the buffer... + */ - if (*bufsize < 1024) - { + if (*bufsize < 1024) { (*bufsize) *= 2; - } - else - { + } else { (*bufsize) *= 3; (*bufsize) /= 2; } - newbuffer = (char *)malloc(*bufsize*sizeof(char)); - if(!newbuffer){ + newbuffer = (char *) malloc(*bufsize * sizeof(char)); + if (!newbuffer) { free(*buffer); mxml_error("Unable to expand string buffer to %d bytes!", *bufsize); return (-1); } - memset(newbuffer,0,*bufsize*sizeof(char)); - memcpy(newbuffer,*buffer,*bufptr - *buffer); + memset(newbuffer, 0, *bufsize * sizeof(char)); + memcpy(newbuffer, *buffer, *bufptr - *buffer); free(*buffer); *bufptr = newbuffer + (*bufptr - *buffer); *buffer = newbuffer; } - if (ch < 128) - { - /* - * Single byte ASCII... - */ + if (ch < 128) { + /* + * Single byte ASCII... + */ *(*bufptr)++ = ch; - } - else if (ch < 2048) - { - /* - * Two-byte UTF-8... - */ + } else if (ch < 2048) { + /* + * Two-byte UTF-8... + */ *(*bufptr)++ = 0xc0 | (ch >> 6); *(*bufptr)++ = 0x80 | (ch & 0x3f); - } - else if (ch < 65536) - { - /* - * Three-byte UTF-8... - */ + } else if (ch < 65536) { + /* + * Three-byte UTF-8... + */ *(*bufptr)++ = 0xe0 | (ch >> 12); *(*bufptr)++ = 0x80 | ((ch >> 6) & 0x3f); *(*bufptr)++ = 0x80 | (ch & 0x3f); - } - else - { - /* - * Four-byte UTF-8... - */ + } else { + /* + * Four-byte UTF-8... + */ *(*bufptr)++ = 0xf0 | (ch >> 18); *(*bufptr)++ = 0x80 | ((ch >> 12) & 0x3f); @@ -222,20 +219,21 @@ myxml_add_char(int ch, /* I - Character to add */ return (0); } + /*------------------------------------------------------------------*/ extern char *stptok(char *s, char *tok, size_t toklen, char *brk); /*===================================================================== actual stuff for implementing the callback functions =====================================================================*/ -void analyzeDim(const char *typeString, int *rank, - int *iDim, int *type){ +void analyzeDim(const char *typeString, int *rank, int *iDim, int *type) +{ char dimString[132]; char dim[20]; char *dimStart, *dimEnd; int myRank; - if(strchr(typeString,(int)'[') == NULL){ - switch(*type){ + if (strchr(typeString, (int) '[') == NULL) { + switch (*type) { case NX_INT8: case NX_UINT8: case NX_INT16: @@ -254,46 +252,50 @@ void analyzeDim(const char *typeString, int *rank, } } else { /* - we have to determine rank and the dims. - Start by extracting the dimension string. - */ - dimStart = strchr(typeString,(int)'[') + 1; - dimEnd = strchr(typeString,(int)']'); - if(!dimStart || !dimEnd) { - mxml_error("ERROR: malformed dimension string in %s",typeString); + we have to determine rank and the dims. + Start by extracting the dimension string. + */ + dimStart = strchr(typeString, (int) '[') + 1; + dimEnd = strchr(typeString, (int) ']'); + if (!dimStart || !dimEnd) { + mxml_error("ERROR: malformed dimension string in %s", typeString); return; } - if((dimEnd - dimStart) > 131){ - mxml_error("ERROR: run away dimension definition in %s",typeString); + if ((dimEnd - dimStart) > 131) { + mxml_error("ERROR: run away dimension definition in %s", typeString); return; } - memset(dimString,0,132); - memcpy(dimString,dimStart,(dimEnd-dimStart)*sizeof(char)); - dimStart = stptok(dimString,dim,19,","); + memset(dimString, 0, 132); + memcpy(dimString, dimStart, (dimEnd - dimStart) * sizeof(char)); + dimStart = stptok(dimString, dim, 19, ","); myRank = 0; - while(dimStart != NULL){ + while (dimStart != NULL) { iDim[myRank] = atoi(dim); - dimStart = stptok(dimStart,dim,19,","); + dimStart = stptok(dimStart, dim, 19, ","); myRank++; } *rank = myRank; } } + /*--------------------------------------------------------------------*/ -int translateTypeCode(char *code){ +int translateTypeCode(char *code) +{ int i, result = -1; - - for(i = 0; i < NTYPECODE; i++){ - if(strstr(code,typecode[i].name) != NULL){ + + for (i = 0; i < NTYPECODE; i++) { + if (strstr(code, typecode[i].name) != NULL) { result = typecode[i].nx_type; break; } } return result; } + /*---------------------------------------------------------------------*/ -static void analyzeDataType(mxml_node_t *parent, int *rank, int *type, - int *iDim){ +static void analyzeDataType(mxml_node_t * parent, int *rank, int *type, + int *iDim) +{ const char *typeString; mxml_type_t myType; int i, nx_type = -1; @@ -303,51 +305,55 @@ static void analyzeDataType(mxml_node_t *parent, int *rank, int *type, iDim[0] = -1; /* - get the type attribute. No attribute means: plain text - */ - typeString = mxmlElementGetAttr(parent,TYPENAME); - if(typeString == NULL){ + get the type attribute. No attribute means: plain text + */ + typeString = mxmlElementGetAttr(parent, TYPENAME); + if (typeString == NULL) { return; } - nx_type = translateTypeCode((char *)typeString); + nx_type = translateTypeCode((char *) typeString); /* - assign type - */ - if(nx_type == -1){ - mxml_error( - "ERROR: %s is an invalid NeXus type, I try to continue but may fail", - typeString); - *type =NX_CHAR; + assign type + */ + if (nx_type == -1) { + mxml_error + ("ERROR: %s is an invalid NeXus type, I try to continue but may fail", + typeString); + *type = NX_CHAR; return; } *type = nx_type; - + analyzeDim(typeString, rank, iDim, type); } + /*-------------------------------------------------------------------*/ -void destroyDataset(void *data){ - if(data != NULL){ - dropNXDataset((pNXDS)data); +void destroyDataset(void *data) +{ + if (data != NULL) { + dropNXDataset((pNXDS) data); } } + /*-------------------------------------------------------------------*/ -static char *getNextNumber(char *pStart, char pNumber[80]){ +static char *getNextNumber(char *pStart, char pNumber[80]) +{ int charCount = 0; pNumber[0] = '\0'; /* advance to first digit */ - while(isspace(*pStart) && *pStart != '\0'){ + while (isspace(*pStart) && *pStart != '\0') { pStart++; } - if(*pStart == '\0'){ + if (*pStart == '\0') { return NULL; } /* copy */ - while(!isspace(*pStart) && *pStart != '\0' && charCount < 78){ + while (!isspace(*pStart) && *pStart != '\0' && charCount < 78) { pNumber[charCount] = *pStart; pStart++; charCount++; @@ -355,32 +361,36 @@ static char *getNextNumber(char *pStart, char pNumber[80]){ pNumber[charCount] = '\0'; return pStart; } + /*--------------------------------------------------------------------*/ -mxml_type_t nexusTypeCallback(mxml_node_t *parent){ +mxml_type_t nexusTypeCallback(mxml_node_t * parent) +{ const char *typeString; - if(strstr(parent->value.element.name,"?xml") != NULL || - strstr(parent->value.element.name,"NX") != NULL){ + if (strstr(parent->value.element.name, "?xml") != NULL || + strstr(parent->value.element.name, "NX") != NULL) { return MXML_ELEMENT; } else { - typeString = mxmlElementGetAttr(parent,TYPENAME); - if(typeString == NULL){ + typeString = mxmlElementGetAttr(parent, TYPENAME); + if (typeString == NULL) { /* - MXML_TEXT seems more appropriate here. But mxml hacks text into - single words which is not what NeXus wants. - */ + MXML_TEXT seems more appropriate here. But mxml hacks text into + single words which is not what NeXus wants. + */ return MXML_OPAQUE; - } else{ - if(strstr(typeString,"NX_CHAR") != NULL){ - return MXML_OPAQUE; + } else { + if (strstr(typeString, "NX_CHAR") != NULL) { + return MXML_OPAQUE; } else { - return MXML_CUSTOM; + return MXML_CUSTOM; } } } } + /*----------------------------------------------------------------------*/ -int nexusLoadCallback(mxml_node_t *node, const char *buffer){ +int nexusLoadCallback(mxml_node_t * node, const char *buffer) +{ mxml_node_t *parent = NULL; int rank, type, iDim[NX_MAXRANK]; char pNumber[80], *pStart; @@ -389,66 +399,70 @@ int nexusLoadCallback(mxml_node_t *node, const char *buffer){ int i; parent = node->parent; - analyzeDataType(parent,&rank,&type,iDim); - if(iDim[0] == -1){ + analyzeDataType(parent, &rank, &type, iDim); + if (iDim[0] == -1) { iDim[0] = strlen(buffer); node->value.custom.data = strdup(buffer); node->value.custom.destroy = free; return 0; } else { - node->value.custom.data = createNXDataset(rank,type,iDim); - dataset = (pNXDS)node->value.custom.data; - if(dataset == NULL){ + node->value.custom.data = createNXDataset(rank, type, iDim); + dataset = (pNXDS) node->value.custom.data; + if (dataset == NULL) { mxml_error("Failed to allocate custom dataset"); return 1; } - node->value.custom.destroy = destroyDataset; + node->value.custom.destroy = destroyDataset; } /* - load data - */ - pStart = (char *)buffer; + load data + */ + pStart = (char *) buffer; maxAddress = getNXDatasetLength(dataset); address = 0; - while( (pStart = getNextNumber(pStart,pNumber)) != NULL && - address < maxAddress){ - putNXDatasetValueAt(dataset,address,atof(pNumber)); + while ((pStart = getNextNumber(pStart, pNumber)) != NULL && + address < maxAddress) { + putNXDatasetValueAt(dataset, address, atof(pNumber)); address++; } return 0; } + /*---------------------------------------------------------------------*/ -static void stringIntoBuffer(char **buffer, char **bufPtr, int *bufSize, - char *string){ +static void stringIntoBuffer(char **buffer, char **bufPtr, int *bufSize, + char *string) +{ int i; - for(i = 0; i < strlen(string); i++){ - myxml_add_char(string[i],bufPtr,buffer,bufSize); + for (i = 0; i < strlen(string); i++) { + myxml_add_char(string[i], bufPtr, buffer, bufSize); } } + /*--------------------------------------------------------------------*/ static void formatNumber(double value, char *txt, int txtLen, - char *format, int type){ - switch(type){ + char *format, int type) +{ + switch (type) { case NX_INT8: case NX_UINT8: case NX_INT16: case NX_UINT16: case NX_INT32: case NX_UINT32: - snprintf(txt,txtLen,format,(int)value); + snprintf(txt, txtLen, format, (int) value); break; case NX_INT64: - snprintf(txt,txtLen,format,(int64_t)value); + snprintf(txt, txtLen, format, (int64_t) value); break; case NX_UINT64: - snprintf(txt,txtLen,format,(uint64_t)value); + snprintf(txt, txtLen, format, (uint64_t) value); break; case NX_FLOAT32: case NX_FLOAT64: - snprintf(txt,txtLen,format,value); + snprintf(txt, txtLen, format, value); break; default: /*assert(0); something is very wrong here */ @@ -456,194 +470,205 @@ static void formatNumber(double value, char *txt, int txtLen, break; } } + /*--------------------------------------------------------------------*/ -static int countDepth(mxml_node_t *node){ +static int countDepth(mxml_node_t * node) +{ int count = 0; mxml_node_t *cur; cur = node; - while(cur != NULL){ + while (cur != NULL) { count++; cur = cur->parent; } count--; return count; } + /*---------------------------------------------------------------------*/ -char *nexusWriteCallback(mxml_node_t *node){ +char *nexusWriteCallback(mxml_node_t * node) +{ int type, col; char pNumber[80], indent[80], format[30]; char *buffer, *bufPtr; pNXDS dataset; - int bufsize, i, length, currentLen; + int bufsize, i, length, currentLen; /* - allocate output buffer - */ - buffer = (char *)malloc(1024*sizeof(char)); - if(buffer == NULL){ + allocate output buffer + */ + buffer = (char *) malloc(1024 * sizeof(char)); + if (buffer == NULL) { mxml_error("Unable to allocate buffer"); return NULL; } - memset(buffer,0,1024); + memset(buffer, 0, 1024); bufPtr = buffer; bufsize = 1024; - dataset = (pNXDS)node->value.custom.data; + dataset = (pNXDS) node->value.custom.data; /* - prepare indentation level - */ - col = countDepth(node)*2; - memset(indent,0,80); - for(i = 0; i < col; i++){ + prepare indentation level + */ + col = countDepth(node) * 2; + memset(indent, 0, 80); + for (i = 0; i < col; i++) { indent[i] = ' '; } /* - get dataset info - */ + get dataset info + */ type = getNXDatasetType(dataset); length = getNXDatasetLength(dataset); - if(dataset->format != NULL){ - strcpy(format,dataset->format); + if (dataset->format != NULL) { + strcpy(format, dataset->format); } else { - getNumberFormat(type,format); + getNumberFormat(type, format); } /* - actually get the data out - */ + actually get the data out + */ currentLen = col; - myxml_add_char('\n',&bufPtr,&buffer,&bufsize); - stringIntoBuffer(&buffer,&bufPtr,&bufsize,indent); - for(i = 0; i < length; i++){ - formatNumber(getNXDatasetValueAt(dataset,i),pNumber,79,format,type); - if(currentLen + strlen(pNumber) > MXML_WRAP){ + myxml_add_char('\n', &bufPtr, &buffer, &bufsize); + stringIntoBuffer(&buffer, &bufPtr, &bufsize, indent); + for (i = 0; i < length; i++) { + formatNumber(getNXDatasetValueAt(dataset, i), pNumber, 79, format, + type); + if (currentLen + strlen(pNumber) > MXML_WRAP) { /* - wrap line - */ - myxml_add_char('\n',&bufPtr,&buffer,&bufsize); - stringIntoBuffer(&buffer,&bufPtr,&bufsize,indent); + wrap line + */ + myxml_add_char('\n', &bufPtr, &buffer, &bufsize); + stringIntoBuffer(&buffer, &bufPtr, &bufsize, indent); currentLen = col; } - stringIntoBuffer(&buffer,&bufPtr,&bufsize,pNumber); - myxml_add_char(' ',&bufPtr,&buffer,&bufsize); + stringIntoBuffer(&buffer, &bufPtr, &bufsize, pNumber); + myxml_add_char(' ', &bufPtr, &buffer, &bufsize); currentLen += strlen(pNumber) + 1; } - myxml_add_char('\0',&bufPtr,&buffer,&bufsize); - return (char *)buffer; + myxml_add_char('\0', &bufPtr, &buffer, &bufsize); + return (char *) buffer; } + /*------------------------------------------------------------------*/ -int isDataNode(mxml_node_t *node){ - if(mxmlElementGetAttr(node,"name") != NULL){ +int isDataNode(mxml_node_t * node) +{ + if (mxmlElementGetAttr(node, "name") != NULL) { return 0; } - if(strcmp(node->value.element.name,"NXroot") == 0){ + if (strcmp(node->value.element.name, "NXroot") == 0) { return 0; } - if(strcmp(node->value.element.name,"NAPIlink") == 0){ + if (strcmp(node->value.element.name, "NAPIlink") == 0) { return 0; } return 1; } + /*--------------------------------------------------------------------*/ -static int isTextData(mxml_node_t *node){ +static int isTextData(mxml_node_t * node) +{ const char *attr = NULL; int rank, type = 0, iDim[NX_MAXRANK]; - if(!isDataNode(node)){ + if (!isDataNode(node)) { return 0; } /* - test datasets - */ - attr = mxmlElementGetAttr(node,TYPENAME); - if(attr == NULL){ + test datasets + */ + attr = mxmlElementGetAttr(node, TYPENAME); + if (attr == NULL) { return 1; } - analyzeDim(attr,&rank,iDim,&type); - if(type == NX_CHAR){ + analyzeDim(attr, &rank, iDim, &type); + if (type == NX_CHAR) { return 1; } else { return 0; } } + /*---------------------------------------------------------------------*/ /* * note: not reentrant or thead safe; returns pointer to static storage */ -const char *NXwhitespaceCallback(mxml_node_t *node, int where){ +const char *NXwhitespaceCallback(mxml_node_t * node, int where) +{ static char *indent = NULL; - int len; + int len; - if(strstr(node->value.element.name,"?xml") != NULL){ + if (strstr(node->value.element.name, "?xml") != NULL) { return NULL; } - if(isTextData(node)){ - if(where == MXML_WS_BEFORE_OPEN){ - len = countDepth(node)*2 + 2; - if (indent != NULL) - { - free(indent); - indent = NULL; + if (isTextData(node)) { + if (where == MXML_WS_BEFORE_OPEN) { + len = countDepth(node) * 2 + 2; + if (indent != NULL) { + free(indent); + indent = NULL; } - indent = (char *)malloc(len*sizeof(char)); - if(indent != NULL){ - memset(indent,' ',len); - indent[0]= '\n'; - indent[len-1] = '\0'; - return (const char*)indent; + indent = (char *) malloc(len * sizeof(char)); + if (indent != NULL) { + memset(indent, ' ', len); + indent[0] = '\n'; + indent[len - 1] = '\0'; + return (const char *) indent; } } return NULL; } - if(where == MXML_WS_BEFORE_OPEN || where == MXML_WS_BEFORE_CLOSE){ - len = countDepth(node)*2 + 2; - if (indent != NULL) - { - free(indent); - indent = NULL; + if (where == MXML_WS_BEFORE_OPEN || where == MXML_WS_BEFORE_CLOSE) { + len = countDepth(node) * 2 + 2; + if (indent != NULL) { + free(indent); + indent = NULL; } - indent = (char *)malloc(len*sizeof(char)); - if(indent != NULL){ - memset(indent,' ',len); - indent[0]= '\n'; - indent[len-1] = '\0'; - return (const char*)indent; + indent = (char *) malloc(len * sizeof(char)); + if (indent != NULL) { + memset(indent, ' ', len); + indent[0] = '\n'; + indent[len - 1] = '\0'; + return (const char *) indent; } } return NULL; } + /*-----------------------------------------------------------------------*/ #ifdef TESTMAIN #include -int main(int argc, char *argv[]){ - mxml_node_t *root = NULL; - FILE *f; +int main(int argc, char *argv[]) +{ + mxml_node_t *root = NULL; + FILE *f; - mxmlSetCustomHandlers(nexusLoadCallback, nexusWriteCallback); - initializeNumberFormats(); + mxmlSetCustomHandlers(nexusLoadCallback, nexusWriteCallback); + initializeNumberFormats(); - /* + /* read test */ - f = fopen("dmc.xml","r"); - root = mxmlLoadFile(NULL,f,nexusTypeCallback); - fclose(f); + f = fopen("dmc.xml", "r"); + root = mxmlLoadFile(NULL, f, nexusTypeCallback); + fclose(f); - /* + /* write test */ - setNumberFormat(NX_INT32,"%8d"); - setNumberFormat(NX_FLOAT32,"%8.2f"); - f = fopen("dmc2.xml","w"); - mxmlSaveFile(root,f,NXwhitespaceCallback); - fclose(f); + setNumberFormat(NX_INT32, "%8d"); + setNumberFormat(NX_FLOAT32, "%8.2f"); + f = fopen("dmc2.xml", "w"); + mxmlSaveFile(root, f, NXwhitespaceCallback); + fclose(f); } #endif diff --git a/nxio.h b/nxio.h index 0de80474..b2d44cae 100644 --- a/nxio.h +++ b/nxio.h @@ -29,19 +29,18 @@ #define TYPENAME "NAPItype" -mxml_type_t nexusTypeCallback(mxml_node_t *parent); -const char *NXwhitespaceCallback(mxml_node_t *node, int where); -int nexusLoadCallback(mxml_node_t *node, const char *buffer); -char *nexusWriteCallback(mxml_node_t *node); +mxml_type_t nexusTypeCallback(mxml_node_t * parent); +const char *NXwhitespaceCallback(mxml_node_t * node, int where); +int nexusLoadCallback(mxml_node_t * node, const char *buffer); +char *nexusWriteCallback(mxml_node_t * node); void setNumberFormat(int dataType, char *formatString); void initializeNumberFormats(); void getNumberText(int nx_type, char *typestring, int typeLen); void destroyDataset(void *data); int translateTypeCode(char *code); -int isDataNode(mxml_node_t *node); -void analyzeDim(const char *typeString, int *rank, - int *iDim, int *type); +int isDataNode(mxml_node_t * node); +void analyzeDim(const char *typeString, int *rank, int *iDim, int *type); #endif diff --git a/nxscript.c b/nxscript.c index dd02c6d6..ec37a2d7 100644 --- a/nxscript.c +++ b/nxscript.c @@ -38,251 +38,266 @@ extern char *trim(char *str); /* missing in nxdict.h: */ NXstatus NXDdefget(NXdict handle, char *pKey, char *pBuffer, int iBufLen); /*------------------------------------------------------------------------*/ -char *makeFilename(SicsInterp *pSics, SConnection *pCon) { +char *makeFilename(SicsInterp * pSics, SConnection * pCon) +{ pSicsVariable pPath = NULL, pPref = NULL, pEnd = NULL; char *pRes = NULL; int iLen, iNum, iYear, thousand; char pNumText[10], pBueffel[256]; CommandList *pCom = NULL; DIR *dir = NULL; - + /* Try, get all the Variables */ - pPath = FindVariable(pSics,"sicsdatapath"); - pPref = FindVariable(pSics,"sicsdataprefix"); - pCom = FindCommand(pSics,"sicsdatanumber"); - pEnd = FindVariable(pSics,"sicsdatapostfix"); - - if( (!pPath) || (!pPref) || (!pCom) || (!pEnd) ){ + pPath = FindVariable(pSics, "sicsdatapath"); + pPref = FindVariable(pSics, "sicsdataprefix"); + pCom = FindCommand(pSics, "sicsdatanumber"); + pEnd = FindVariable(pSics, "sicsdatapostfix"); + + if ((!pPath) || (!pPref) || (!pCom) || (!pEnd)) { SCWrite(pCon, - "ERROR: cannot read variables for automatic data file name creation", + "ERROR: cannot read variables for automatic data file name creation", eError); SCWrite(pCon, - "ERROR: This is a VERY, VERY, VERY serious installation problem", - eError); - SCWrite(pCon,"ERROR: your data will be dumped into emergency.hdf",eError); - return NULL; + "ERROR: This is a VERY, VERY, VERY serious installation problem", + eError); + SCWrite(pCon, "ERROR: your data will be dumped into emergency.hdf", + eError); + return NULL; } /* find length */ - iLen = strlen(pPath->text) + 4; /* extra 4 for dir number */ + iLen = strlen(pPath->text) + 4; /* extra 4 for dir number */ iLen += strlen(pPref->text); - iLen += 10; /* for number + year */ + iLen += 10; /* for number + year */ iLen += strlen(pEnd->text); - iLen += 10; /* safety margin */ - + iLen += 10; /* safety margin */ + /* allocate memory */ - pRes = (char *)malloc(iLen*sizeof(char)); - if(!pRes){ - SCWrite(pCon,"ERROR: no memory in makeFilename",eError); + pRes = (char *) malloc(iLen * sizeof(char)); + if (!pRes) { + SCWrite(pCon, "ERROR: no memory in makeFilename", eError); return NULL; - } - memset(pRes,0,iLen); - + } + memset(pRes, 0, iLen); + /* increment the data file number */ - iNum = IncrementDataNumber(pCom->pData,&iYear); - if(iNum < 0){ - SCWrite(pCon,"ERROR: cannot increment data number!",eError); - SCWrite(pCon,"ERROR: your data will be dumped to emergency.hdf",eError); + iNum = IncrementDataNumber(pCom->pData, &iYear); + if (iNum < 0) { + SCWrite(pCon, "ERROR: cannot increment data number!", eError); + SCWrite(pCon, "ERROR: your data will be dumped to emergency.hdf", + eError); free(pRes); return NULL; } - strcpy(pRes,pPath->text); - thousand = (int)floor(iNum/1000.); - snprintf(pNumText,9,"%3.3d",thousand); - strcat(pRes,pNumText); + strcpy(pRes, pPath->text); + thousand = (int) floor(iNum / 1000.); + snprintf(pNumText, 9, "%3.3d", thousand); + strcat(pRes, pNumText); /* - check for existence of directory and create if neccessary - */ + check for existence of directory and create if neccessary + */ dir = opendir(pRes); - if(dir == NULL){ - mkdir(pRes,S_IRWXU | S_IRGRP | S_IXGRP); - snprintf(pBueffel,255,"Creating dir: %s", pRes); - SCWrite(pCon,pBueffel,eLog); + if (dir == NULL) { + mkdir(pRes, S_IRWXU | S_IRGRP | S_IXGRP); + snprintf(pBueffel, 255, "Creating dir: %s", pRes); + SCWrite(pCon, pBueffel, eLog); } else { closedir(dir); } /* - build the rest of the filename - */ - strcat(pRes,"/"); - strcat(pRes,pPref->text); - sprintf(pNumText,"%4.4d",iYear); - strcat(pRes,pNumText); - strcat(pRes,"n"); - sprintf(pNumText,"%6.6d",iNum); - strcat(pRes,pNumText); - strcat(pRes,pEnd->text); - + build the rest of the filename + */ + strcat(pRes, "/"); + strcat(pRes, pPref->text); + sprintf(pNumText, "%4.4d", iYear); + strcat(pRes, pNumText); + strcat(pRes, "n"); + sprintf(pNumText, "%6.6d", iNum); + strcat(pRes, pNumText); + strcat(pRes, pEnd->text); + return pRes; } + /*---------------------------------------------------------------------*/ -void changeExtension(char *filename, char *newExtension){ +void changeExtension(char *filename, char *newExtension) +{ char *pPtr = NULL; - pPtr = strrchr(filename,(int)'.'); + pPtr = strrchr(filename, (int) '.'); assert(pPtr != NULL); - + pPtr++; assert(strlen(pPtr) >= strlen(newExtension)); - strcpy(pPtr,newExtension); + strcpy(pPtr, newExtension); } + /*----------------------------------------------------------------------*/ -static int listToArray(SicsInterp *pSics, char *list, - int intar[NX_MAXRANK]){ - int argc, status, i, val; - CONST char **argv; - Tcl_Interp *pTcl = InterpGetTcl(pSics); - - status = Tcl_SplitList(pTcl, list, &argc, &argv); - if(status != TCL_OK){ - return status; +static int listToArray(SicsInterp * pSics, char *list, + int intar[NX_MAXRANK]) +{ + int argc, status, i, val; + CONST char **argv; + Tcl_Interp *pTcl = InterpGetTcl(pSics); + + status = Tcl_SplitList(pTcl, list, &argc, &argv); + if (status != TCL_OK) { + return status; + } + + for (i = 0; i < argc; i++) { + status = Tcl_GetInt(pTcl, argv[i], &val); + if (status != TCL_OK) { + return status; } - - for(i = 0; i < argc; i++){ - status = Tcl_GetInt(pTcl,argv[i],&val); - if(status != TCL_OK){ - return status; - } - intar[i] = val; - } - Tcl_Free((char *)argv); - return TCL_OK; + intar[i] = val; + } + Tcl_Free((char *) argv); + return TCL_OK; } + /*======================== Action =======================================*/ -static int handleFileOperations(SConnection *pCon, pNXScript self, - int argc, char *argv[]){ - int status,i, iVal; +static int handleFileOperations(SConnection * pCon, pNXScript self, + int argc, char *argv[]) +{ + int status, i, iVal; NXaccess access; char buffer[512]; - if(strcmp(argv[1],"close") == 0){ + if (strcmp(argv[1], "close") == 0) { /* - close everything! and send a message to trigger file synchronisation - to the central server - */ - if(self->fileHandle == NULL){ + close everything! and send a message to trigger file synchronisation + to the central server + */ + if (self->fileHandle == NULL) { SCSendOK(pCon); return 1; } i = 511; iVal = NX_CHAR; - NXgetattr(self->fileHandle,"file_name",buffer,&i,&iVal); + NXgetattr(self->fileHandle, "file_name", buffer, &i, &iVal); NXclose(&self->fileHandle); - NXDclose(self->dictHandle,NULL); + NXDclose(self->dictHandle, NULL); self->fileHandle = NULL; self->dictHandle = NULL; - SendQuieck(QUIECK,buffer); + SendQuieck(QUIECK, buffer); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"reopen") == 0){ + } else if (strcmp(argv[1], "reopen") == 0) { access = NXACC_RDWR; - } else if(strcmp(argv[1],"create4") == 0){ + } else if (strcmp(argv[1], "create4") == 0) { access = NXACC_CREATE4; - unlink(argv[2]); /* kill file for overwrite */ - } else if(strcmp(argv[1],"create5") == 0){ + unlink(argv[2]); /* kill file for overwrite */ + } else if (strcmp(argv[1], "create5") == 0) { access = NXACC_CREATE5; - unlink(argv[2]); /* kill file for overwrite */ - } else if(strcmp(argv[1],"createxml") == 0){ + unlink(argv[2]); /* kill file for overwrite */ + } else if (strcmp(argv[1], "createxml") == 0) { access = NXACC_CREATEXML; } else { return 0; } - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments for file operation", - eError); + if (argc < 4) { + SCWrite(pCon, + "ERROR: insufficient number of arguments for file operation", + eError); return -1; } /* - be considerate: close files left open - */ - if(self->fileHandle != NULL){ + be considerate: close files left open + */ + if (self->fileHandle != NULL) { NXclose(&self->fileHandle); self->fileHandle = NULL; } - if(self->dictHandle != NULL){ + if (self->dictHandle != NULL) { NXDclose(self->dictHandle, NULL); self->dictHandle = NULL; } /* - now initialize ourselves - */ - status = NXopen(argv[2],access,&self->fileHandle); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to open %s",argv[2]); - SCWrite(pCon,buffer,eError); + now initialize ourselves + */ + status = NXopen(argv[2], access, &self->fileHandle); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to open %s", argv[2]); + SCWrite(pCon, buffer, eError); return -1; } - status = NXDinitfromfile(argv[3],&self->dictHandle); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to open dictionary %s",argv[3]); - SCWrite(pCon,buffer,eError); + status = NXDinitfromfile(argv[3], &self->dictHandle); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to open dictionary %s", argv[3]); + SCWrite(pCon, buffer, eError); return -1; } SCSendOK(pCon); return 1; } + /*----------------------------------------------------------------------*/ -static void putMotor(SConnection *pCon, SicsInterp *pSics, pNXScript self, - int argc, char *argv[]){ +static void putMotor(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ int status; pMotor brumm = NULL; float fVal; char buffer[132], dummy[256]; - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to putmotor", - eLogError); - return; - } - - /* - find motor - */ - brumm = (pMotor)FindCommandData(pSics,argv[3],"Motor"); - if(!brumm){ - sprintf(buffer,"ERROR: motor %s not found!", argv[3]); - SCWrite(pCon,buffer,eLogError); + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to putmotor", + eLogError); return; } /* - do position - */ - status = MotorGetSoftPosition(brumm, pCon,&fVal); - if(!status){ - sprintf(buffer,"ERROR: failed to read position of %s", argv[3]); - SCWrite(pCon,buffer,eLogError); - return; - } - status = NXDputalias(self->fileHandle,self->dictHandle,argv[2],&fVal); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write %s with alias %s", - argv[3],argv[2]); - SCWrite(pCon,buffer,eLogError); + find motor + */ + brumm = (pMotor) FindCommandData(pSics, argv[3], "Motor"); + if (!brumm) { + sprintf(buffer, "ERROR: motor %s not found!", argv[3]); + SCWrite(pCon, buffer, eLogError); return; } /* - if alias_null is available: write zero point - */ - strcpy(buffer,argv[2]); - strcat(buffer,"_null"); - if(NXDdefget(self->dictHandle,buffer,dummy,255)){ - MotorGetPar(brumm,"softzero",&fVal); - status = NXDputalias(self->fileHandle,self->dictHandle,buffer, &fVal); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write %s zero with alias %s", - argv[3],argv[2]); - SCWrite(pCon,buffer,eLogError); + do position + */ + status = MotorGetSoftPosition(brumm, pCon, &fVal); + if (!status) { + sprintf(buffer, "ERROR: failed to read position of %s", argv[3]); + SCWrite(pCon, buffer, eLogError); + return; + } + status = NXDputalias(self->fileHandle, self->dictHandle, argv[2], &fVal); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write %s with alias %s", + argv[3], argv[2]); + SCWrite(pCon, buffer, eLogError); + return; + } + + /* + if alias_null is available: write zero point + */ + strcpy(buffer, argv[2]); + strcat(buffer, "_null"); + if (NXDdefget(self->dictHandle, buffer, dummy, 255)) { + MotorGetPar(brumm, "softzero", &fVal); + status = + NXDputalias(self->fileHandle, self->dictHandle, buffer, &fVal); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write %s zero with alias %s", + argv[3], argv[2]); + SCWrite(pCon, buffer, eLogError); return; } } } + /*---------------------------------------------------------------------*/ -static void putCounter(SConnection *pCon, SicsInterp *pSics, pNXScript self, - int argc, char *argv[]){ +static void putCounter(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ pCounter cter = NULL; float fVal; long counts; @@ -290,675 +305,695 @@ static void putCounter(SConnection *pCon, SicsInterp *pSics, pNXScript self, int status, i, icounts; CounterMode eMode; - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to putcounter", - eLogError); + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to putcounter", + eLogError); return; } - memset(dummy,0,80*sizeof(char)); - + memset(dummy, 0, 80 * sizeof(char)); + /* - find counter - */ - cter = (pCounter)FindCommandData(pSics,argv[3],"SingleCounter"); - if(!cter){ - sprintf(buffer,"ERROR: counter %s not found!", argv[3]); - SCWrite(pCon,buffer,eLogError); + find counter + */ + cter = (pCounter) FindCommandData(pSics, argv[3], "SingleCounter"); + if (!cter) { + sprintf(buffer, "ERROR: counter %s not found!", argv[3]); + SCWrite(pCon, buffer, eLogError); return; } /* - do preset - */ + do preset + */ fVal = GetCounterPreset(cter); - strcpy(newAlias,argv[2]); - strcat(newAlias,"_preset"); - status = NXDputalias(self->fileHandle,self->dictHandle,newAlias,&fVal); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write preset to %s", newAlias); - SCWrite(pCon,buffer,eLogError); + strcpy(newAlias, argv[2]); + strcat(newAlias, "_preset"); + status = + NXDputalias(self->fileHandle, self->dictHandle, newAlias, &fVal); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write preset to %s", newAlias); + SCWrite(pCon, buffer, eLogError); } /* - do countmode - */ + do countmode + */ eMode = GetCounterMode(cter); - strcpy(newAlias,argv[2]); - strcat(newAlias,"_mode"); - if(eMode == eTimer){ - strcpy(dummy,"timer"); + strcpy(newAlias, argv[2]); + strcat(newAlias, "_mode"); + if (eMode == eTimer) { + strcpy(dummy, "timer"); } else { - strcpy(dummy,"monitor"); + strcpy(dummy, "monitor"); } - status = NXDputalias(self->fileHandle,self->dictHandle,newAlias,dummy); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write counter mode to %s", newAlias); - SCWrite(pCon,buffer,eLogError); + status = + NXDputalias(self->fileHandle, self->dictHandle, newAlias, dummy); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write counter mode to %s", newAlias); + SCWrite(pCon, buffer, eLogError); } /* - do time - */ - fVal = GetCountTime(cter,pCon); - strcpy(newAlias,argv[2]); - strcat(newAlias,"_time"); - if(NXDdefget(self->dictHandle,newAlias,dummy,79)){ - status = NXDputalias(self->fileHandle,self->dictHandle,newAlias,&fVal); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write count time to %s", newAlias); - SCWrite(pCon,buffer,eLogError); + do time + */ + fVal = GetCountTime(cter, pCon); + strcpy(newAlias, argv[2]); + strcat(newAlias, "_time"); + if (NXDdefget(self->dictHandle, newAlias, dummy, 79)) { + status = + NXDputalias(self->fileHandle, self->dictHandle, newAlias, &fVal); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write count time to %s", newAlias); + SCWrite(pCon, buffer, eLogError); } } /* - do counter and monitors - */ - for(i = 0; i < 10; i++){ - sprintf(newAlias,"%s_%2.2d",argv[2],i); - if(NXDdefget(self->dictHandle,newAlias,dummy,79)){ - counts = GetMonitor(cter,i,pCon); - icounts = (int)counts; - status = NXDputalias(self->fileHandle,self->dictHandle,newAlias, - &icounts); + do counter and monitors + */ + for (i = 0; i < 10; i++) { + sprintf(newAlias, "%s_%2.2d", argv[2], i); + if (NXDdefget(self->dictHandle, newAlias, dummy, 79)) { + counts = GetMonitor(cter, i, pCon); + icounts = (int) counts; + status = NXDputalias(self->fileHandle, self->dictHandle, newAlias, + &icounts); } } return; } -/*----------------------------------------------------------------------*/ -static void putSicsData(SConnection *pCon, SicsInterp *pSics, - pNXScript self, int argc, char *argv[]){ - - pSICSData data = NULL; - int status; - char buffer[256]; - - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to putSicsData", - eLogError); - return; - } - /* - find data - */ - data = (pSICSData)FindCommandData(pSics,argv[3],"SICSData"); - if(data == NULL){ - snprintf(buffer,255,"ERROR: sicsdata %s not found!", argv[3]); - SCWrite(pCon,buffer,eLogError); - return; - } - - status = NXDputalias(self->fileHandle,self->dictHandle,argv[2],data->data); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write sicsdata to %s", argv[2]); - SCWrite(pCon,buffer,eLogError); - } -} /*----------------------------------------------------------------------*/ -static void putAttribute(SConnection *pCon, SicsInterp *pSics, - pNXScript self, int argc, char *argv[]){ - int status, type = NX_CHAR; - char buffer[256]; - - if(argc < 5){ - SCWrite(pCon,"ERROR: insufficient number of arguments to putAttribute", - eLogError); - return; - } +static void putSicsData(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ - status = NXDopenalias(self->fileHandle,self->dictHandle,argv[2]); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to open alias %s", argv[2]); - SCWrite(pCon,buffer,eLogError); + pSICSData data = NULL; + int status; + char buffer[256]; + + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to putSicsData", + eLogError); + return; + } + + /* + find data + */ + data = (pSICSData) FindCommandData(pSics, argv[3], "SICSData"); + if (data == NULL) { + snprintf(buffer, 255, "ERROR: sicsdata %s not found!", argv[3]); + SCWrite(pCon, buffer, eLogError); + return; + } + + status = + NXDputalias(self->fileHandle, self->dictHandle, argv[2], data->data); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write sicsdata to %s", argv[2]); + SCWrite(pCon, buffer, eLogError); + } +} + +/*----------------------------------------------------------------------*/ +static void putAttribute(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ + int status, type = NX_CHAR; + char buffer[256]; + + if (argc < 5) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to putAttribute", + eLogError); + return; + } + + status = NXDopenalias(self->fileHandle, self->dictHandle, argv[2]); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to open alias %s", argv[2]); + SCWrite(pCon, buffer, eLogError); + return; + } + status = NXputattr(self->fileHandle, argv[3], (void *) argv[4], + strlen(argv[4]) + 1, type); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write attribute %s", argv[3]); + SCWrite(pCon, buffer, eLogError); + } + NXopenpath(self->fileHandle, "/"); +} + +/*----------------------------------------------------------------------*/ +static void putHdb(SConnection * pCon, SicsInterp * pSics, pNXScript self, + int argc, char *argv[]) +{ + pHdb node = NULL; + char alias[512]; + hdbValue v; + float fVal, *floatAr = NULL; + int i; + + if (argc < 3) { + SCWrite(pCon, "ERROR: putHdb needs at least node name", eLogError); + return; + } + node = FindHdbNode(NULL, argv[2], pCon); + if (node == NULL) { + SCPrintf(pCon, eLogError, "ERROR: node %s not found", argv[2]); + return; + } + memset(alias, 0, 512 * sizeof(char)); + if (!GetHdbProperty(node, "nxalias", alias, 512)) { + if (argc < 4) { + SCPrintf(pCon, eLogError, + "ERROR: neither nxalias property nor alias on command line found for %s", + argv[2]); + return; + } else { + strncpy(alias, argv[3], 512); + } + } + GetHipadabaPar(node, &v, pCon); + switch (v.dataType) { + case HIPNONE: + return; + break; + case HIPINT: + NXDputalias(self->fileHandle, self->dictHandle, alias, &v.v.intValue); + break; + case HIPFLOAT: + fVal = v.v.doubleValue; + NXDputalias(self->fileHandle, self->dictHandle, alias, &fVal); + break; + case HIPTEXT: + NXDputalias(self->fileHandle, self->dictHandle, alias, v.v.text); + break; + case HIPINTAR: + case HIPINTVARAR: + NXDputalias(self->fileHandle, self->dictHandle, alias, v.v.intArray); + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + floatAr = malloc(v.arrayLength * sizeof(float)); + if (floatAr == NULL) { + SCPrintf(pCon, eLogError, "ERROR: out of memory writing %s", + node->name); return; } - status = NXputattr(self->fileHandle,argv[3],(void *)argv[4], - strlen(argv[4])+1, type); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write attribute %s", argv[3]); - SCWrite(pCon,buffer,eLogError); + for (i = 0; i < v.arrayLength; i++) { + floatAr[i] = v.v.floatArray[i]; } - NXopenpath(self->fileHandle,"/"); -} -/*----------------------------------------------------------------------*/ -static void putHdb(SConnection *pCon, SicsInterp *pSics, pNXScript self, - int argc, char *argv[]){ - pHdb node = NULL; - char alias[512]; - hdbValue v; - float fVal, *floatAr = NULL; - int i; - - if(argc < 3){ - SCWrite(pCon,"ERROR: putHdb needs at least node name", - eLogError); - return; - } - node = FindHdbNode(NULL,argv[2], pCon); - if(node == NULL){ - SCPrintf(pCon,eLogError,"ERROR: node %s not found", argv[2]); - return; - } - memset(alias,0,512*sizeof(char)); - if(!GetHdbProperty(node,"nxalias", alias, 512)){ - if(argc < 4) { - SCPrintf(pCon,eLogError,"ERROR: neither nxalias property nor alias on command line found for %s", - argv[2]); - return; - } else { - strncpy(alias, argv[3],512); - } - } - GetHipadabaPar(node,&v,pCon); - switch(v.dataType){ - case HIPNONE: - return; - break; - case HIPINT: - NXDputalias(self->fileHandle, self->dictHandle, alias, - &v.v.intValue); - break; - case HIPFLOAT: - fVal = v.v.doubleValue; - NXDputalias(self->fileHandle, self->dictHandle, alias, - &fVal); - break; - case HIPTEXT: - NXDputalias(self->fileHandle, self->dictHandle, alias, - v.v.text); - break; - case HIPINTAR: - case HIPINTVARAR: - NXDputalias(self->fileHandle, self->dictHandle, alias, - v.v.intArray); - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - floatAr = malloc(v.arrayLength*sizeof(float)); - if(floatAr == NULL){ - SCPrintf(pCon,eLogError,"ERROR: out of memory writing %s", node->name); - return; - } - for(i = 0; i < v.arrayLength; i++){ - floatAr[i] = v.v.floatArray[i]; - } - NXDputalias(self->fileHandle, self->dictHandle, alias, - floatAr); - free(floatAr); - break; - } - ReleaseHdbValue(&v); + NXDputalias(self->fileHandle, self->dictHandle, alias, floatAr); + free(floatAr); + break; + } + ReleaseHdbValue(&v); } + /*----------------------------------------------------------------------*/ -static void putHdbSlab(SConnection *pCon, SicsInterp *pSics, pNXScript self, - int argc, char *argv[]){ - pHdb node = NULL; - char alias[512]; - hdbValue v; - float fVal, *floatAr = NULL; - int start[NX_MAXRANK], size[NX_MAXRANK]; - int i, status; - - if(argc < 5){ - SCWrite(pCon,"ERROR: putHdbSlab needs at least node name start, size", +static void putHdbSlab(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ + pHdb node = NULL; + char alias[512]; + hdbValue v; + float fVal, *floatAr = NULL; + int start[NX_MAXRANK], size[NX_MAXRANK]; + int i, status; + + if (argc < 5) { + SCWrite(pCon, + "ERROR: putHdbSlab needs at least node name start, size", eLogError); - return; - } - node = FindHdbNode(NULL,argv[2], pCon); - if(node == NULL){ - SCPrintf(pCon,eLogError,"ERROR: node %s not found", argv[2]); - return; - } - memset(alias,0,512*sizeof(char)); - if(!GetHdbProperty(node,"nxalias", alias, 512)){ - SCPrintf(pCon,eLogError, - "ERROR: nxalias property not found for %s", - argv[2]); - return; - } - status = NXDopenalias(self->fileHandle, self->dictHandle,alias); - if(status != NX_OK){ - SCPrintf(pCon,eLogError,"ERROR: failed to open alias for %s", argv[2]); - return; - } + return; + } + node = FindHdbNode(NULL, argv[2], pCon); + if (node == NULL) { + SCPrintf(pCon, eLogError, "ERROR: node %s not found", argv[2]); + return; + } + memset(alias, 0, 512 * sizeof(char)); + if (!GetHdbProperty(node, "nxalias", alias, 512)) { + SCPrintf(pCon, eLogError, + "ERROR: nxalias property not found for %s", argv[2]); + return; + } + status = NXDopenalias(self->fileHandle, self->dictHandle, alias); + if (status != NX_OK) { + SCPrintf(pCon, eLogError, "ERROR: failed to open alias for %s", + argv[2]); + return; + } - status = listToArray(pSics,argv[3],start); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert start value list", eLogError); - return; - } + status = listToArray(pSics, argv[3], start); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert start value list", eLogError); + return; + } - status = listToArray(pSics,argv[4],size); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert size value list", eLogError); - return; - } + status = listToArray(pSics, argv[4], size); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert size value list", eLogError); + return; + } - GetHipadabaPar(node,&v,pCon); - switch(v.dataType){ - case HIPNONE: - return; - break; - case HIPINT: - status = NXputslab(self->fileHandle, &v.v.intValue, start,size); - break; - case HIPFLOAT: - fVal = v.v.doubleValue; - status = NXputslab(self->fileHandle, &fVal, start,size); - break; - case HIPTEXT: - status = NXputslab(self->fileHandle, v.v.text, start,size); - break; - case HIPINTAR: - case HIPINTVARAR: - status = NXputslab(self->fileHandle, v.v.intArray, start,size); - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - floatAr = malloc(v.arrayLength*sizeof(float)); - if(floatAr == NULL){ - SCPrintf(pCon,eLogError,"ERROR: out of memory writing %s", node->name); - return; - } - for(i = 0; i < v.arrayLength; i++){ - floatAr[i] = v.v.floatArray[i]; - } - status = NXputslab(self->fileHandle, floatAr, start,size); - free(floatAr); - break; - } - if(status != NX_OK){ - SCPrintf(pCon,eLogError,"ERROR: failed to write slab for node %s", argv[2]); - } - ReleaseHdbValue(&v); + GetHipadabaPar(node, &v, pCon); + switch (v.dataType) { + case HIPNONE: + return; + break; + case HIPINT: + status = NXputslab(self->fileHandle, &v.v.intValue, start, size); + break; + case HIPFLOAT: + fVal = v.v.doubleValue; + status = NXputslab(self->fileHandle, &fVal, start, size); + break; + case HIPTEXT: + status = NXputslab(self->fileHandle, v.v.text, start, size); + break; + case HIPINTAR: + case HIPINTVARAR: + status = NXputslab(self->fileHandle, v.v.intArray, start, size); + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + floatAr = malloc(v.arrayLength * sizeof(float)); + if (floatAr == NULL) { + SCPrintf(pCon, eLogError, "ERROR: out of memory writing %s", + node->name); + return; + } + for (i = 0; i < v.arrayLength; i++) { + floatAr[i] = v.v.floatArray[i]; + } + status = NXputslab(self->fileHandle, floatAr, start, size); + free(floatAr); + break; + } + if (status != NX_OK) { + SCPrintf(pCon, eLogError, "ERROR: failed to write slab for node %s", + argv[2]); + } + ReleaseHdbValue(&v); } + /*----------------------------------------------------------------------*/ -static void updateHMDim(NXScript *self, pHistMem mem){ +static void updateHMDim(NXScript * self, pHistMem mem) +{ int iDim[MAXDIM]; int i, rank, timeLength, status; - char dummy[40], value[20]; + char dummy[40], value[20]; const float *timeBin; /* - update the dimension variables in the dictionary - */ - GetHistDim(mem,iDim,&rank); - for(i = 0; i < rank; i++){ - sprintf(dummy,"dim%1.1d", i); - sprintf(value,"%d",iDim[i]); - status = NXDupdate(self->dictHandle,dummy,value); - if(status == 0) { - NXDadd(self->dictHandle,dummy,value); + update the dimension variables in the dictionary + */ + GetHistDim(mem, iDim, &rank); + for (i = 0; i < rank; i++) { + sprintf(dummy, "dim%1.1d", i); + sprintf(value, "%d", iDim[i]); + status = NXDupdate(self->dictHandle, dummy, value); + if (status == 0) { + NXDadd(self->dictHandle, dummy, value); } } - timeBin = GetHistTimeBin(mem,&timeLength); - if(timeLength > 2){ - sprintf(dummy,"%d",timeLength); + timeBin = GetHistTimeBin(mem, &timeLength); + if (timeLength > 2) { + sprintf(dummy, "%d", timeLength); } else { - sprintf(dummy,"%d",1); + sprintf(dummy, "%d", 1); } - status = NXDupdate(self->dictHandle,"timedim",dummy); - if(status == 0) { - NXDadd(self->dictHandle,"timedim",dummy); + status = NXDupdate(self->dictHandle, "timedim", dummy); + if (status == 0) { + NXDadd(self->dictHandle, "timedim", dummy); } } + /*---------------------------------------------------------------------- The sequence of things is important in here: The code for updating the dimensions variables also applies the time binning to the length. Thus subsets can only be checked for after that. And then we can allocate memory. -------------------------------------------------------------------------*/ -static void putHistogramMemory(SConnection *pCon, SicsInterp *pSics, - pNXScript self, - int argc, char *argv[]){ +static void putHistogramMemory(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ pHistMem mem = NULL; int status, start, length, i, subset = 0, bank = 0; HistInt *iData = NULL; char buffer[256]; - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to puthm", - eLogError); - return; - } - - /* - find Histogram Memory - */ - mem = (pHistMem)FindCommandData(pSics,argv[3],"HistMem"); - if(!mem){ - sprintf(buffer,"ERROR: HistMem %s not found!", argv[3]); - SCWrite(pCon,buffer,eLogError); + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to puthm", + eLogError); return; } /* - default: everything - */ + find Histogram Memory + */ + mem = (pHistMem) FindCommandData(pSics, argv[3], "HistMem"); + if (!mem) { + sprintf(buffer, "ERROR: HistMem %s not found!", argv[3]); + SCWrite(pCon, buffer, eLogError); + return; + } + + /* + default: everything + */ start = 0; length = GetHistLength(mem); - updateHMDim(self,mem); + updateHMDim(self, mem); /* check for further arguments specifying a subset */ - if(argc > 5){ + if (argc > 5) { subset = 1; - status = Tcl_GetInt(InterpGetTcl(pSics),argv[4],&start); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to integer", - argv[4]); - SCWrite(pCon,buffer,eLogError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[4], &start); + if (status != TCL_OK) { + sprintf(buffer, "ERROR: failed to convert %s to integer", argv[4]); + SCWrite(pCon, buffer, eLogError); return; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[5],&length); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to integer", - argv[5]); - SCWrite(pCon,buffer,eLogError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[5], &length); + if (status != TCL_OK) { + sprintf(buffer, "ERROR: failed to convert %s to integer", argv[5]); + SCWrite(pCon, buffer, eLogError); return; } } - + /* * check for additional bank number */ - if(argc > 6){ - status = Tcl_GetInt(InterpGetTcl(pSics),argv[6],&bank); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to integer", - argv[6]); - SCWrite(pCon,buffer,eLogError); + if (argc > 6) { + status = Tcl_GetInt(InterpGetTcl(pSics), argv[6], &bank); + if (status != TCL_OK) { + sprintf(buffer, "ERROR: failed to convert %s to integer", argv[6]); + SCWrite(pCon, buffer, eLogError); return; } - } + } /* - read HM - */ - if(subset){ - iData = (HistInt *)malloc(length*sizeof(HistInt)); - if(!iData){ - SCWrite(pCon,"ERROR: out of memory for reading histogram memory", - eLogError); + read HM + */ + if (subset) { + iData = (HistInt *) malloc(length * sizeof(HistInt)); + if (!iData) { + SCWrite(pCon, "ERROR: out of memory for reading histogram memory", + eLogError); return; } - memset(iData,0,length*sizeof(HistInt)); - status = GetHistogramDirect(mem,pCon,bank,start,start+length,iData, - length*sizeof(HistInt)); - }else{ + memset(iData, 0, length * sizeof(HistInt)); + status = + GetHistogramDirect(mem, pCon, bank, start, start + length, iData, + length * sizeof(HistInt)); + } else { /* - status = GetHistogram(mem,pCon,0,start,length,iData, - length*sizeof(HistInt)); - */ - iData = GetHistogramPointer(mem,pCon); - if(iData == NULL){ + status = GetHistogram(mem,pCon,0,start,length,iData, + length*sizeof(HistInt)); + */ + iData = GetHistogramPointer(mem, pCon); + if (iData == NULL) { status = 0; } else { status = 1; } } - if(!status){ - SCWrite(pCon,"ERROR: failed to read histogram memory",eLogError); - if(subset){ + if (!status) { + SCWrite(pCon, "ERROR: failed to read histogram memory", eLogError); + if (subset) { free(iData); - } + } return; } /* - finally: write - */ - status = NXDputalias(self->fileHandle, self->dictHandle,argv[2],iData); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write histogram memory data"); - SCWrite(pCon,buffer,eLogError); + finally: write + */ + status = NXDputalias(self->fileHandle, self->dictHandle, argv[2], iData); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write histogram memory data"); + SCWrite(pCon, buffer, eLogError); } - - if(subset){ + + if (subset) { free(iData); } SCSendOK(pCon); return; } + /*--------------------------------------------------------------------- defunct as of december 2003 */ -static void putHistogramMemoryChunked(SConnection *pCon, SicsInterp *pSics, - pNXScript self, - int argc, char *argv[]){ +static void putHistogramMemoryChunked(SConnection * pCon, + SicsInterp * pSics, pNXScript self, + int argc, char *argv[]) +{ pHistMem mem = NULL; int status, start, length, i, noChunks, chunkDim[MAXDIM], rank; HistInt *iData = NULL; char buffer[256]; int subset; - if(argc < 5){ - SCWrite(pCon,"ERROR: insufficient number of arguments to puthmchunked", - eLogError); - return; - } - - /* - find Histogram Memory - */ - mem = (pHistMem)FindCommandData(pSics,argv[3],"HistMem"); - if(!mem){ - sprintf(buffer,"ERROR: HistMem %s not found!", argv[3]); - SCWrite(pCon,buffer,eLogError); + if (argc < 5) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to puthmchunked", + eLogError); return; } /* - default: everything - */ + find Histogram Memory + */ + mem = (pHistMem) FindCommandData(pSics, argv[3], "HistMem"); + if (!mem) { + sprintf(buffer, "ERROR: HistMem %s not found!", argv[3]); + SCWrite(pCon, buffer, eLogError); + return; + } + + /* + default: everything + */ start = 0; length = GetHistLength(mem); - updateHMDim(self,mem); + updateHMDim(self, mem); /* - check for an argument defining the number of chunks - */ - status = Tcl_GetInt(InterpGetTcl(pSics),argv[4],&noChunks); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to integer", - argv[4]); - SCWrite(pCon,buffer,eLogError); + check for an argument defining the number of chunks + */ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[4], &noChunks); + if (status != TCL_OK) { + sprintf(buffer, "ERROR: failed to convert %s to integer", argv[4]); + SCWrite(pCon, buffer, eLogError); return; } - + /* - read HM - */ - if(subset){ - iData = (HistInt *)malloc(length*sizeof(HistInt)); - if(!iData){ - SCWrite(pCon,"ERROR: out of memory for reading histogram memory", - eLogError); + read HM + */ + if (subset) { + iData = (HistInt *) malloc(length * sizeof(HistInt)); + if (!iData) { + SCWrite(pCon, "ERROR: out of memory for reading histogram memory", + eLogError); return; } - memset(iData,0,length*sizeof(HistInt)); - status = GetHistogramDirect(mem,pCon,0,start,start+length,iData, - length*sizeof(HistInt)); - }else{ + memset(iData, 0, length * sizeof(HistInt)); + status = GetHistogramDirect(mem, pCon, 0, start, start + length, iData, + length * sizeof(HistInt)); + } else { /* - status = GetHistogram(mem,pCon,0,start,length,iData, - length*sizeof(HistInt)); - */ - iData = GetHistogramPointer(mem,pCon); - if(iData == NULL){ + status = GetHistogram(mem,pCon,0,start,length,iData, + length*sizeof(HistInt)); + */ + iData = GetHistogramPointer(mem, pCon); + if (iData == NULL) { status = 0; } else { status = 1; } } - if(!status){ - SCWrite(pCon,"ERROR: failed to read histogram memory",eLogError); - if(subset){ + if (!status) { + SCWrite(pCon, "ERROR: failed to read histogram memory", eLogError); + if (subset) { free(iData); - } + } return; } /* - finally: write - */ - status = NXDputalias(self->fileHandle, self->dictHandle,argv[2],iData); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write histogram memory data"); - SCWrite(pCon,buffer,eLogError); + finally: write + */ + status = NXDputalias(self->fileHandle, self->dictHandle, argv[2], iData); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write histogram memory data"); + SCWrite(pCon, buffer, eLogError); } - - if(subset){ + + if (subset) { free(iData); } SCSendOK(pCon); return; } + /*----------------------------------------------------------------------*/ -static void putSlab(SConnection *pCon, SicsInterp *pSics, pNXScript self, - int argc, char *argv[]){ - int start[NX_MAXRANK], size[NX_MAXRANK]; - int status, written = 0; - pHistMem mem = NULL; - HistInt *histData = NULL; - pSICSData data = NULL; - - if(argc < 6){ - SCWrite(pCon,"ERROR: insufficient number of arguments to putslab", - eLogError); - return; - } +static void putSlab(SConnection * pCon, SicsInterp * pSics, pNXScript self, + int argc, char *argv[]) +{ + int start[NX_MAXRANK], size[NX_MAXRANK]; + int status, written = 0; + pHistMem mem = NULL; + HistInt *histData = NULL; + pSICSData data = NULL; - status = NXDopenalias(self->fileHandle, self->dictHandle,argv[2]); - if(status != NX_OK){ - SCPrintf(pCon,eLogError,"ERROR: failed to open alias %s", argv[2]); - return; - } - - status = listToArray(pSics,argv[3],start); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert start value list", eLogError); - return; - } - - status = listToArray(pSics,argv[4],size); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert size value list", eLogError); - return; - } - - /* - * try to write HM data - */ - mem = (pHistMem)FindCommandData(pSics,argv[5],"HistMem"); - if(mem != NULL){ - histData = GetHistogramPointer(mem,pCon); - if(histData){ - status = NXputslab(self->fileHandle, histData, start, size); - if(status == NX_OK){ - written = 1; - } - } - } - - /* - * try to look for sicsdata - */ - data = (pSICSData)FindCommandData(pSics,argv[5],"SICSData"); - if(data != NULL){ - status = NXputslab(self->fileHandle,data->data,start,size); - if(status == NX_OK){ - written = 1; - } - } - /* - * drop out of hierarchy - */ - NXopenpath(self->fileHandle,"/"); - - if(written == 0){ - SCWrite(pCon,"ERROR: failed to write data, data not recognised", + if (argc < 6) { + SCWrite(pCon, "ERROR: insufficient number of arguments to putslab", eLogError); - } + return; + } + + status = NXDopenalias(self->fileHandle, self->dictHandle, argv[2]); + if (status != NX_OK) { + SCPrintf(pCon, eLogError, "ERROR: failed to open alias %s", argv[2]); + return; + } + + status = listToArray(pSics, argv[3], start); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert start value list", eLogError); + return; + } + + status = listToArray(pSics, argv[4], size); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert size value list", eLogError); + return; + } + + /* + * try to write HM data + */ + mem = (pHistMem) FindCommandData(pSics, argv[5], "HistMem"); + if (mem != NULL) { + histData = GetHistogramPointer(mem, pCon); + if (histData) { + status = NXputslab(self->fileHandle, histData, start, size); + if (status == NX_OK) { + written = 1; + } + } + } + + /* + * try to look for sicsdata + */ + data = (pSICSData) FindCommandData(pSics, argv[5], "SICSData"); + if (data != NULL) { + status = NXputslab(self->fileHandle, data->data, start, size); + if (status == NX_OK) { + written = 1; + } + } + /* + * drop out of hierarchy + */ + NXopenpath(self->fileHandle, "/"); + + if (written == 0) { + SCWrite(pCon, "ERROR: failed to write data, data not recognised", + eLogError); + } } + /*-------------------------------------------------------------------*/ -static void putTimeBinning(SConnection *pCon, SicsInterp *pSics, - pNXScript self, - int argc, char *argv[]){ +static void putTimeBinning(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ pHistMem mem = NULL; int i, status, timeLength; char buffer[256], defString[512], dummy[40]; const float *timeBin; float *timeCopy = NULL; - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to puttimebinning", - eLogError); - return; - } - - /* - find Histogram Memory - */ - mem = (pHistMem)FindCommandData(pSics,argv[3],"HistMem"); - if(!mem){ - sprintf(buffer,"ERROR: HistMem %s not found!", argv[3]); - SCWrite(pCon,buffer,eLogError); + if (argc < 4) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to puttimebinning", + eLogError); return; } - /* - build definition string - */ - status = NXDdefget(self->dictHandle,argv[2],buffer,254); - if(!status){ - sprintf(buffer,"ERROR: alias %s for time binning not found", - argv[2]); - SCWrite(pCon,buffer,eLogError); - return; - } - timeBin = GetHistTimeBin(mem,&timeLength); - sprintf(defString,"%s -dim {%d} ",buffer,timeLength); - - /* - Divide the time binning when appropriate and write + find Histogram Memory */ - if(self->timeDivisor != 1){ - timeCopy = (float *)malloc(timeLength*sizeof(float)); - if(timeCopy == NULL){ - SCWrite(pCon,"ERROR: out of memory writing time binning",eLogError); + mem = (pHistMem) FindCommandData(pSics, argv[3], "HistMem"); + if (!mem) { + sprintf(buffer, "ERROR: HistMem %s not found!", argv[3]); + SCWrite(pCon, buffer, eLogError); + return; + } + + + /* + build definition string + */ + status = NXDdefget(self->dictHandle, argv[2], buffer, 254); + if (!status) { + sprintf(buffer, "ERROR: alias %s for time binning not found", argv[2]); + SCWrite(pCon, buffer, eLogError); + return; + } + timeBin = GetHistTimeBin(mem, &timeLength); + sprintf(defString, "%s -dim {%d} ", buffer, timeLength); + + /* + Divide the time binning when appropriate and write + */ + if (self->timeDivisor != 1) { + timeCopy = (float *) malloc(timeLength * sizeof(float)); + if (timeCopy == NULL) { + SCWrite(pCon, "ERROR: out of memory writing time binning", + eLogError); return; } - for(i = 0; i < timeLength; i++){ - timeCopy[i] = timeBin[i]/self->timeDivisor; + for (i = 0; i < timeLength; i++) { + timeCopy[i] = timeBin[i] / self->timeDivisor; } status = NXDputdef(self->fileHandle, self->dictHandle, - defString,(void *)timeCopy); + defString, (void *) timeCopy); free(timeCopy); } else { status = NXDputdef(self->fileHandle, self->dictHandle, - defString,(void *)timeBin); + defString, (void *) timeBin); } - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write time binning"); - SCWrite(pCon,buffer,eLogError); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write time binning"); + SCWrite(pCon, buffer, eLogError); } SCSendOK(pCon); return; } + /*----------------------------------------------------------------------*/ -static void putArray(SConnection *pCon, SicsInterp *pSics, - pNXScript self, - int argc, char *argv[]){ +static void putArray(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ float *data = NULL; int length, i, status; char num[20]; @@ -966,87 +1001,91 @@ static void putArray(SConnection *pCon, SicsInterp *pSics, Tcl_Interp *tcl = NULL; double dVal; - if(argc < 5){ - SCWrite(pCon,"ERROR: insufficient number of arguments to array", - eLogError); + if (argc < 5) { + SCWrite(pCon, "ERROR: insufficient number of arguments to array", + eLogError); return; } tcl = InterpGetTcl(pSics); assert(tcl != NULL); /* - get array length - */ - status = Tcl_GetInt(tcl,argv[4],&length); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to integer in putarray",argv[4]); - SCWrite(pCon,buffer,eLogError); + get array length + */ + status = Tcl_GetInt(tcl, argv[4], &length); + if (status != TCL_OK) { + sprintf(buffer, "ERROR: failed to convert %s to integer in putarray", + argv[4]); + SCWrite(pCon, buffer, eLogError); return; } /* - allocate - */ - if(length > 0){ - data = (float *)malloc(length*sizeof(float)); + allocate + */ + if (length > 0) { + data = (float *) malloc(length * sizeof(float)); } - if(data == NULL){ - snprintf(buffer,255, - "ERROR: out of memory or invalid length in putarray at %s, length = %s", - argv[2],argv[4]); - SCWrite(pCon,buffer,eLogError); + if (data == NULL) { + snprintf(buffer, 255, + "ERROR: out of memory or invalid length in putarray at %s, length = %s", + argv[2], argv[4]); + SCWrite(pCon, buffer, eLogError); return; } - memset(data,0,length*sizeof(float)); + memset(data, 0, length * sizeof(float)); /* - try getting data - */ - for(i = 0; i < length; i++){ - sprintf(num,"%d",i); - varData = (char *)Tcl_GetVar2(tcl,argv[3],num,0); - if(varData != NULL){ - status = Tcl_GetDouble(tcl,varData,&dVal); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to double in putarray", - varData); - SCWrite(pCon,buffer,eLogError); + try getting data + */ + for (i = 0; i < length; i++) { + sprintf(num, "%d", i); + varData = (char *) Tcl_GetVar2(tcl, argv[3], num, 0); + if (varData != NULL) { + status = Tcl_GetDouble(tcl, varData, &dVal); + if (status != TCL_OK) { + sprintf(buffer, + "ERROR: failed to convert %s to double in putarray", + varData); + SCWrite(pCon, buffer, eLogError); } - data[i] = (float)dVal; + data[i] = (float) dVal; } else { - snprintf(buffer,254,"WARNING: failed to find array element %d in putarray", i); - SCWrite(pCon,buffer,eLogError); + snprintf(buffer, 254, + "WARNING: failed to find array element %d in putarray", i); + SCWrite(pCon, buffer, eLogError); } } /* - build definition string - */ - status = NXDdefget(self->dictHandle,argv[2],buffer,254); - if(!status){ - sprintf(buffer,"ERROR: alias %s for array not found in putarray", - argv[2]); - SCWrite(pCon,buffer,eLogError); + build definition string + */ + status = NXDdefget(self->dictHandle, argv[2], buffer, 254); + if (!status) { + sprintf(buffer, "ERROR: alias %s for array not found in putarray", + argv[2]); + SCWrite(pCon, buffer, eLogError); free(data); return; } - snprintf(defString,511,"%s -dim {%d} ",buffer,length); + snprintf(defString, 511, "%s -dim {%d} ", buffer, length); /* - write it! - */ - status = NXDputdef(self->fileHandle,self->dictHandle,defString,data); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write array in putarray"); - SCWrite(pCon,buffer,eLogError); + write it! + */ + status = NXDputdef(self->fileHandle, self->dictHandle, defString, data); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write array in putarray"); + SCWrite(pCon, buffer, eLogError); } free(data); SCSendOK(pCon); } + /*----------------------------------------------------------------------*/ -static void putIntArray(SConnection *pCon, SicsInterp *pSics, - pNXScript self, - int argc, char *argv[]){ +static void putIntArray(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ int *data = NULL; int length, i, status; char num[20]; @@ -1054,414 +1093,422 @@ static void putIntArray(SConnection *pCon, SicsInterp *pSics, Tcl_Interp *tcl = NULL; int iVal; - if(argc < 5){ - SCWrite(pCon,"ERROR: insufficient number of arguments to array", - eLogError); + if (argc < 5) { + SCWrite(pCon, "ERROR: insufficient number of arguments to array", + eLogError); return; } tcl = InterpGetTcl(pSics); assert(tcl != NULL); /* - get array length - */ - status = Tcl_GetInt(tcl,argv[4],&length); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to integer",argv[4]); - SCWrite(pCon,buffer,eLogError); + get array length + */ + status = Tcl_GetInt(tcl, argv[4], &length); + if (status != TCL_OK) { + sprintf(buffer, "ERROR: failed to convert %s to integer", argv[4]); + SCWrite(pCon, buffer, eLogError); return; } /* - allocate - */ - if(length > 0){ - data = (int *)malloc(length*sizeof(int)); + allocate + */ + if (length > 0) { + data = (int *) malloc(length * sizeof(int)); } - if(data == NULL){ - SCWrite(pCon,"ERROR: out of memory or invalid length",eLogError); + if (data == NULL) { + SCWrite(pCon, "ERROR: out of memory or invalid length", eLogError); return; } - memset(data,0,length*sizeof(int)); + memset(data, 0, length * sizeof(int)); /* - try getting data - */ - for(i = 0; i < length; i++){ - sprintf(num,"%d",i); - varData = (char *)Tcl_GetVar2(tcl,argv[3],num,0); - if(varData != NULL){ - status = Tcl_GetInt(tcl,varData,&iVal); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to int", - varData); - SCWrite(pCon,buffer,eLogError); + try getting data + */ + for (i = 0; i < length; i++) { + sprintf(num, "%d", i); + varData = (char *) Tcl_GetVar2(tcl, argv[3], num, 0); + if (varData != NULL) { + status = Tcl_GetInt(tcl, varData, &iVal); + if (status != TCL_OK) { + sprintf(buffer, "ERROR: failed to convert %s to int", varData); + SCWrite(pCon, buffer, eLogError); } data[i] = iVal; } else { - snprintf(buffer,254,"WARNING: failed to find array element %d", i); - SCWrite(pCon,buffer,eLogError); + snprintf(buffer, 254, "WARNING: failed to find array element %d", i); + SCWrite(pCon, buffer, eLogError); } } /* - build definition string - */ - status = NXDdefget(self->dictHandle,argv[2],buffer,254); - if(!status){ - sprintf(buffer,"ERROR: alias %s for array not found", - argv[2]); - SCWrite(pCon,buffer,eLogError); + build definition string + */ + status = NXDdefget(self->dictHandle, argv[2], buffer, 254); + if (!status) { + sprintf(buffer, "ERROR: alias %s for array not found", argv[2]); + SCWrite(pCon, buffer, eLogError); free(data); return; } - snprintf(defString,511,"%s -dim {%d} ",buffer,length); + snprintf(defString, 511, "%s -dim {%d} ", buffer, length); /* - write it! - */ - status = NXDputdef(self->fileHandle,self->dictHandle,defString,data); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write array"); - SCWrite(pCon,buffer,eLogError); + write it! + */ + status = NXDputdef(self->fileHandle, self->dictHandle, defString, data); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write array"); + SCWrite(pCon, buffer, eLogError); } free(data); SCSendOK(pCon); } + /*----------------------------------------------------------------------*/ -static void putGlobal(SConnection *pCon, SicsInterp *pSics, - pNXScript self, - int argc, char *argv[]){ +static void putGlobal(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ char value[1024]; int status; - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to putglobal", - eLogError); + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to putglobal", + eLogError); return; } - Arg2Text(argc-3,&argv[3],value,1023); - status = NXputattr(self->fileHandle,argv[2],value,strlen(value), - NX_CHAR); - if(status != NX_OK){ - SCWrite(pCon,"ERROR: failed to write attribute",eLogError); + Arg2Text(argc - 3, &argv[3], value, 1023); + status = NXputattr(self->fileHandle, argv[2], value, strlen(value), + NX_CHAR); + if (status != NX_OK) { + SCWrite(pCon, "ERROR: failed to write attribute", eLogError); } SCSendOK(pCon); } + /*-----------------------------------------------------------------------*/ -static int handlePut(SConnection *pCon, SicsInterp *pSics, pNXScript self, - int argc, char *argv[]){ +static int handlePut(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ int status, iVal; char buffer[1024], defString[1024], numBuf[25]; double dVal; float fVal; /*============ */ - if(strcmp(argv[1],"putfloat") == 0){ - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to putfloat", - eLogError); + if (strcmp(argv[1], "putfloat") == 0) { + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to putfloat", + eLogError); return 1; } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&dVal); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to float", - argv[3]); - SCWrite(pCon,buffer,eLogError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &dVal); + if (status != TCL_OK) { + sprintf(buffer, "ERROR: failed to convert %s to float", argv[3]); + SCWrite(pCon, buffer, eLogError); return 1; } - fVal = (float)dVal; + fVal = (float) dVal; status = NXDputalias(self->fileHandle, self->dictHandle, - argv[2],&fVal); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write %f to alias %s", - fVal, argv[2]); - SCWrite(pCon,buffer,eLogError); + argv[2], &fVal); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write %f to alias %s", + fVal, argv[2]); + SCWrite(pCon, buffer, eLogError); } return 1; - } else if(strcmp(argv[1],"putint") == 0){ - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to putint", - eLogError); + } else if (strcmp(argv[1], "putint") == 0) { + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to putint", + eLogError); return 1; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[3],&iVal); - if(status != TCL_OK){ - sprintf(buffer,"ERROR: failed to convert %s to int", - argv[3]); - SCWrite(pCon,buffer,eLogError); - return 1; + status = Tcl_GetInt(InterpGetTcl(pSics), argv[3], &iVal); + if (status != TCL_OK) { + sprintf(buffer, "ERROR: failed to convert %s to int", argv[3]); + SCWrite(pCon, buffer, eLogError); + return 1; } status = NXDputalias(self->fileHandle, self->dictHandle, - argv[2],&iVal); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write %d to alias %s", - iVal, argv[2]); - SCWrite(pCon,buffer,eLogError); + argv[2], &iVal); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write %d to alias %s", + iVal, argv[2]); + SCWrite(pCon, buffer, eLogError); } return 1; - } else if (strcmp(argv[1],"puttext") == 0){ + } else if (strcmp(argv[1], "puttext") == 0) { /*====================*/ - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to puttext", - eLogError); + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to puttext", + eLogError); return 1; } - Arg2Text(argc-3,&argv[3],buffer,1023); + Arg2Text(argc - 3, &argv[3], buffer, 1023); trim(buffer); - status = NXDdefget(self->dictHandle,argv[2],defString,1023); - if(status != NX_OK){ - sprintf(buffer,"ERROR: alias %s not found in puttext", - argv[2]); - SCWrite(pCon,buffer,eLogError); + status = NXDdefget(self->dictHandle, argv[2], defString, 1023); + if (status != NX_OK) { + sprintf(buffer, "ERROR: alias %s not found in puttext", argv[2]); + SCWrite(pCon, buffer, eLogError); return 1; } - if(strlen(defString) < 900){ - strcat(defString," -dim {"); - sprintf(numBuf,"%d",(int)strlen(buffer)+1); - strcat(defString,numBuf); - strcat(defString," }"); + if (strlen(defString) < 900) { + strcat(defString, " -dim {"); + sprintf(numBuf, "%d", (int) strlen(buffer) + 1); + strcat(defString, numBuf); + strcat(defString, " }"); } else { - SCWrite(pCon,"ERROR: out of definition string space in puttext", - eLogError); + SCWrite(pCon, "ERROR: out of definition string space in puttext", + eLogError); return 1; } - status = NXDputdef(self->fileHandle,self->dictHandle, - defString,buffer); - if(status != NX_OK){ - sprintf(buffer,"ERROR: failed to write alias %s", - argv[2]); - SCWrite(pCon,buffer,eLogError); + status = NXDputdef(self->fileHandle, self->dictHandle, + defString, buffer); + if (status != NX_OK) { + sprintf(buffer, "ERROR: failed to write alias %s", argv[2]); + SCWrite(pCon, buffer, eLogError); } return 1; - } else if(strcmp(argv[1],"putmot") == 0){ + } else if (strcmp(argv[1], "putmot") == 0) { /*=========== */ - putMotor(pCon,pSics,self,argc,argv); + putMotor(pCon, pSics, self, argc, argv); return 1; - } else if(strcmp(argv[1],"putcounter") == 0){ - /* ================*/ - putCounter(pCon,pSics,self, argc,argv); + } else if (strcmp(argv[1], "putcounter") == 0) { + /* ================ */ + putCounter(pCon, pSics, self, argc, argv); return 1; - } else if(strcmp(argv[1],"puthdb") == 0){ - /* ================*/ - putHdb(pCon,pSics,self, argc,argv); + } else if (strcmp(argv[1], "puthdb") == 0) { + /* ================ */ + putHdb(pCon, pSics, self, argc, argv); return 1; - } else if(strcmp(argv[1],"puthdbslab") == 0){ - /* ================*/ - putHdbSlab(pCon,pSics,self, argc,argv); + } else if (strcmp(argv[1], "puthdbslab") == 0) { + /* ================ */ + putHdbSlab(pCon, pSics, self, argc, argv); return 1; - }else if(strcmp(argv[1],"puthm") == 0){ + } else if (strcmp(argv[1], "puthm") == 0) { /*=================*/ - putHistogramMemory(pCon,pSics,self,argc, argv); + putHistogramMemory(pCon, pSics, self, argc, argv); return 1; - }else if(strcmp(argv[1],"puttimebinning") == 0){ + } else if (strcmp(argv[1], "puttimebinning") == 0) { /*=================*/ - putTimeBinning(pCon,pSics,self,argc,argv); - }else if(strcmp(argv[1],"putarray") == 0){ + putTimeBinning(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "putarray") == 0) { /*================*/ - putArray(pCon,pSics,self,argc,argv); - }else if(strcmp(argv[1],"putintarray") == 0){ + putArray(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "putintarray") == 0) { /*================*/ - putIntArray(pCon,pSics,self,argc,argv); - }else if(strcmp(argv[1],"putglobal") == 0){ + putIntArray(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "putglobal") == 0) { /*===============*/ - putGlobal(pCon,pSics,self,argc,argv); - }else if(strcmp(argv[1],"putsicsdata") == 0){ + putGlobal(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "putsicsdata") == 0) { /*===============*/ - putSicsData(pCon,pSics,self,argc,argv); - }else if(strcmp(argv[1],"putattribute") == 0){ + putSicsData(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "putattribute") == 0) { /*===============*/ - putAttribute(pCon,pSics,self,argc,argv); - }else if(strcmp(argv[1],"putslab") == 0){ + putAttribute(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "putslab") == 0) { /*===============*/ - putSlab(pCon,pSics,self,argc,argv); + putSlab(pCon, pSics, self, argc, argv); } else { - SCWrite(pCon,"ERROR: put command not recognised",eLogError); + SCWrite(pCon, "ERROR: put command not recognised", eLogError); } return 1; -} +} + /*----------------------------------------------------------------------*/ -static void makeLink(SConnection *pCon, SicsInterp *pSics, - pNXScript self, - int argc, char *argv[]){ +static void makeLink(SConnection * pCon, SicsInterp * pSics, + pNXScript self, int argc, char *argv[]) +{ int status; char pBueffel[256]; - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to makelink", - eLogError); + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to makelink", + eLogError); return; } status = NXDaliaslink(self->fileHandle, self->dictHandle, - argv[2],argv[3]); - if(status != NX_OK){ - snprintf(pBueffel,255,"ERROR: linking %s against %s failed", - argv[2], argv[3]); - SCWrite(pCon,pBueffel,eLogError); + argv[2], argv[3]); + if (status != NX_OK) { + snprintf(pBueffel, 255, "ERROR: linking %s against %s failed", + argv[2], argv[3]); + SCWrite(pCon, pBueffel, eLogError); return; } SCSendOK(pCon); } + /*----------------------------------------------------------------------*/ -static void updateDictVar(SConnection *pCon, pNXScript self, int argc, - char *argv[]){ +static void updateDictVar(SConnection * pCon, pNXScript self, int argc, + char *argv[]) +{ int status; - if(self->dictHandle == NULL){ - SCWrite(pCon,"ERROR: cannot update variable, dictionary not open", - eLogError); + if (self->dictHandle == NULL) { + SCWrite(pCon, "ERROR: cannot update variable, dictionary not open", + eLogError); return; } - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to updateDictVar", - eLogError); + if (argc < 4) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to updateDictVar", + eLogError); return; } - NXDupdate(self->dictHandle,argv[2],argv[3]); + NXDupdate(self->dictHandle, argv[2], argv[3]); } + /*-----------------------------------------------------------------------*/ -int NXScriptAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pNXScript self = (pNXScript)pData; +int NXScriptAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pNXScript self = (pNXScript) pData; char *pFile = NULL; int status; char buffer[132]; /* - preliminary checks - */ + preliminary checks + */ assert(self); - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 1; } - if(argc < 2){ - SCWrite(pCon,"ERROR: no keyword found",eLogError); + if (argc < 2) { + SCWrite(pCon, "ERROR: no keyword found", eLogError); return 1; } strtolower(argv[1]); - if(strcmp(argv[1],"makefilename") == 0){ - pFile = makeFilename(pSics,pCon); - if(pFile != NULL){ - SCWrite(pCon,pFile,eValue); + if (strcmp(argv[1], "makefilename") == 0) { + pFile = makeFilename(pSics, pCon); + if (pFile != NULL) { + SCWrite(pCon, pFile, eValue); free(pFile); return 1; } else { - SCWrite(pCon,"ERROR: failed to create filename",eError); + SCWrite(pCon, "ERROR: failed to create filename", eError); return 0; } - } else if(strcmp(argv[1],"divisor") == 0){ - if(argc < 3) { - SCWrite(pCon,"ERROR: no divisor found",eLogError); + } else if (strcmp(argv[1], "divisor") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: no divisor found", eLogError); return 1; } - if(!SCMatchRights(pCon,usMugger)){ + if (!SCMatchRights(pCon, usMugger)) { return 1; } self->timeDivisor = atoi(argv[2]); return 1; } - - status = handleFileOperations(pCon,self,argc,argv); - if(status < 0){ + + status = handleFileOperations(pCon, self, argc, argv); + if (status < 0) { return 0; - } else if(status == 1){ + } else if (status == 1) { return 1; } /* - if we are here, we can only continue if files are open - */ - if(self->fileHandle == NULL || self->dictHandle == NULL){ - SCWrite(pCon,"ERROR: cannot write, files not open",eLogError); + if we are here, we can only continue if files are open + */ + if (self->fileHandle == NULL || self->dictHandle == NULL) { + SCWrite(pCon, "ERROR: cannot write, files not open", eLogError); return 1; } - if(strcmp(argv[1],"updatedictvar") == 0){ - updateDictVar(pCon,self,argc,argv); + if (strcmp(argv[1], "updatedictvar") == 0) { + updateDictVar(pCon, self, argc, argv); return 1; } - if(strstr(argv[1],"put") != NULL){ - handlePut(pCon,pSics,self,argc,argv); + if (strstr(argv[1], "put") != NULL) { + handlePut(pCon, pSics, self, argc, argv); return 1; } - if(strcmp(argv[1],"isalias") == 0) { - if(argc < 3) { - SCWrite(pCon,"ERROR: need alias to test",eLogError); - return 1; + if (strcmp(argv[1], "isalias") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: need alias to test", eLogError); + return 1; } - if(NXDget(self->dictHandle,argv[2],buffer,131) == NX_OK){ - snprintf(buffer,131,"%s = 1", argv[2]); + if (NXDget(self->dictHandle, argv[2], buffer, 131) == NX_OK) { + snprintf(buffer, 131, "%s = 1", argv[2]); } else { - snprintf(buffer,131,"%s = 0", argv[2]); + snprintf(buffer, 131, "%s = 0", argv[2]); } - SCWrite(pCon,buffer,eValue); + SCWrite(pCon, buffer, eValue); return 1; } - if(strcmp(argv[1],"makelink") == 0){ - makeLink(pCon,pSics,self,argc,argv); + if (strcmp(argv[1], "makelink") == 0) { + makeLink(pCon, pSics, self, argc, argv); return 1; } return 1; } + /*=============== make it ==============================================*/ -static void KillNXScript(void *pData){ - pNXScript self = (pNXScript)pData; - if(self == NULL){ +static void KillNXScript(void *pData) +{ + pNXScript self = (pNXScript) pData; + if (self == NULL) { return; } - if(self->pDes){ + if (self->pDes) { DeleteDescriptor(self->pDes); } - if(self->fileHandle){ + if (self->fileHandle) { NXclose(&self->fileHandle); } - if(self->dictHandle){ + if (self->dictHandle) { NXDclose(self->dictHandle, NULL); } free(self); } + /*----------------------------------------------------------------------*/ -int MakeNXScript(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int MakeNXScript(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pNXScript self = NULL; int status; - self = (pNXScript)malloc(sizeof(NXScript)); - if(self == NULL){ - SCWrite(pCon,"ERROR: no memory for NXscript creation",eError); + self = (pNXScript) malloc(sizeof(NXScript)); + if (self == NULL) { + SCWrite(pCon, "ERROR: no memory for NXscript creation", eError); return 0; } - memset(self,0,sizeof(NXScript)); + memset(self, 0, sizeof(NXScript)); self->pDes = CreateDescriptor("NXScript"); - if(self->pDes == NULL){ - SCWrite(pCon,"ERROR: no memory for NXscript creation",eError); + if (self->pDes == NULL) { + SCWrite(pCon, "ERROR: no memory for NXscript creation", eError); free(self); return 0; } self->timeDivisor = 1; - + /* - create with with a default name if none specified - */ - if(argc > 1){ - status = AddCommand(pSics,argv[1],NXScriptAction,KillNXScript,self); + create with with a default name if none specified + */ + if (argc > 1) { + status = + AddCommand(pSics, argv[1], NXScriptAction, KillNXScript, self); } else { - status = AddCommand(pSics,"nxscript",NXScriptAction,KillNXScript,self); + status = + AddCommand(pSics, "nxscript", NXScriptAction, KillNXScript, self); } - if(!status){ - SCWrite(pCon,"ERROR: duplicate NXScript object not created",eError); + if (!status) { + SCWrite(pCon, "ERROR: duplicate NXScript object not created", eError); KillNXScript(self); return 0; } return 1; } - diff --git a/nxscript.h b/nxscript.h index 5acf16b0..08b8290a 100644 --- a/nxscript.h +++ b/nxscript.h @@ -14,12 +14,12 @@ #include "napi.h" #include "nxdict.h" -int MakeNXScript(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int NXScriptAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeNXScript(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int NXScriptAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -char *makeFilename(SicsInterp *pSics, SConnection *pCon); +char *makeFilename(SicsInterp * pSics, SConnection * pCon); void changeExtension(char *filename, char *newExtension); /*============== a personal data structure ============================*/ typedef struct { diff --git a/nxstack.c b/nxstack.c index bd2f492c..3199f8e2 100644 --- a/nxstack.c +++ b/nxstack.c @@ -33,68 +33,88 @@ typedef struct { pNexusFunction pDriver; NXlink closeID; char filename[1024]; -}fileStackEntry; +} fileStackEntry; typedef struct __fileStack { int fileStackPointer; fileStackEntry fileStack[MAXEXTERNALDEPTH]; -}fileStack; +} fileStack; /*---------------------------------------------------------------------*/ -pFileStack makeFileStack(){ +pFileStack makeFileStack() +{ pFileStack pNew = NULL; - + pNew = malloc(sizeof(fileStack)); - if(pNew == NULL){ + if (pNew == NULL) { return NULL; } - memset(pNew,0,sizeof(fileStack)); + memset(pNew, 0, sizeof(fileStack)); pNew->fileStackPointer = -1; return pNew; } + /*---------------------------------------------------------------------*/ -void killFileStack(pFileStack self){ - if(self != NULL){ +void killFileStack(pFileStack self) +{ + if (self != NULL) { free(self); } } + /*----------------------------------------------------------------------*/ -void pushFileStack(pFileStack self, pNexusFunction pDriv, char *file){ +void pushFileStack(pFileStack self, pNexusFunction pDriv, char *file) +{ int length; self->fileStackPointer++; self->fileStack[self->fileStackPointer].pDriver = pDriv; - memset(&self->fileStack[self->fileStackPointer].closeID,0,sizeof(NXlink)); + memset(&self->fileStack[self->fileStackPointer].closeID, 0, + sizeof(NXlink)); length = strlen(file); - if(length >= 1024){ + if (length >= 1024) { length = 1023; } - memcpy(&self->fileStack[self->fileStackPointer].filename,file,length); + memcpy(&self->fileStack[self->fileStackPointer].filename, file, length); } + /*----------------------------------------------------------------------*/ -void popFileStack(pFileStack self){ +void popFileStack(pFileStack self) +{ self->fileStackPointer--; - if(self->fileStackPointer < -1){ + if (self->fileStackPointer < -1) { self->fileStackPointer = -1; } } + /*----------------------------------------------------------------------*/ -pNexusFunction peekFileOnStack(pFileStack self){ +pNexusFunction peekFileOnStack(pFileStack self) +{ return self->fileStack[self->fileStackPointer].pDriver; } + /*---------------------------------------------------------------------*/ -char *peekFilenameOnStack(pFileStack self){ +char *peekFilenameOnStack(pFileStack self) +{ return self->fileStack[self->fileStackPointer].filename; } + /*----------------------------------------------------------------------*/ -void peekIDOnStack(pFileStack self, NXlink *id){ - memcpy(id, &self->fileStack[self->fileStackPointer].closeID, sizeof(NXlink)); +void peekIDOnStack(pFileStack self, NXlink * id) +{ + memcpy(id, &self->fileStack[self->fileStackPointer].closeID, + sizeof(NXlink)); } + /*---------------------------------------------------------------------*/ -void setCloseID(pFileStack self, NXlink id){ - memcpy(&self->fileStack[self->fileStackPointer].closeID, &id, sizeof(NXlink)); +void setCloseID(pFileStack self, NXlink id) +{ + memcpy(&self->fileStack[self->fileStackPointer].closeID, &id, + sizeof(NXlink)); } + /*----------------------------------------------------------------------*/ -int fileStackDepth(pFileStack self){ +int fileStackDepth(pFileStack self) +{ return self->fileStackPointer; } diff --git a/nxstack.h b/nxstack.h index e7a9568b..578129fe 100755 --- a/nxstack.h +++ b/nxstack.h @@ -34,10 +34,9 @@ void popFileStack(pFileStack self); pNexusFunction peekFileOnStack(pFileStack self); char *peekFilenameOnStack(pFileStack self); -void peekIDOnStack(pFileStack self, NXlink *id); +void peekIDOnStack(pFileStack self, NXlink * id); void setCloseID(pFileStack self, NXlink id); - + int fileStackDepth(pFileStack self); #endif - diff --git a/nxupdate.c b/nxupdate.c index f72b998a..67ec0773 100644 --- a/nxupdate.c +++ b/nxupdate.c @@ -16,197 +16,211 @@ #include "nxupdate.h" #include "nxupdate.i" /*-------------------------------------------------------------------*/ -static int UpdateTask(void *pData){ +static int UpdateTask(void *pData) +{ pNXupdate self = NULL; - self = (pNXupdate)pData; - if(self == NULL){ + self = (pNXupdate) pData; + if (self == NULL) { return 0; } - if(self->onOff == 0){ + if (self->onOff == 0) { return 0; } /* - update when intervall reached or when end - */ - if(time(NULL) >= self->nextUpdate || self->iEnd == 1){ - if(self->updateScript != NULL && self->pCon != NULL){ - InterpExecute(pServ->pSics,self->pCon,self->updateScript); + update when intervall reached or when end + */ + if (time(NULL) >= self->nextUpdate || self->iEnd == 1) { + if (self->updateScript != NULL && self->pCon != NULL) { + InterpExecute(pServ->pSics, self->pCon, self->updateScript); } self->nextUpdate = time(NULL) + self->updateIntervall; } - if(self->iEnd == 1){ + if (self->iEnd == 1) { self->pCon = NULL; return 0; } else { return 1; } } + /*--------------------------------------------------------------------*/ -static int CountCallback(int iEvent, void *pEventData, void *pUser){ +static int CountCallback(int iEvent, void *pEventData, void *pUser) +{ pNXupdate self = NULL; SConnection *pCon = NULL; - self = (pNXupdate)pUser; - pCon = (SConnection *)pEventData; + self = (pNXupdate) pUser; + pCon = (SConnection *) pEventData; - if(self->onOff == 0){ + if (self->onOff == 0) { return 1; } - if(iEvent == COUNTSTART){ + if (iEvent == COUNTSTART) { assert(pCon); assert(self); /* - start file - */ - if(self->startScript != NULL){ - InterpExecute(pServ->pSics,pCon,self->startScript); + start file + */ + if (self->startScript != NULL) { + InterpExecute(pServ->pSics, pCon, self->startScript); } - if(self->updateScript != NULL){ - InterpExecute(pServ->pSics,pCon,self->updateScript); + if (self->updateScript != NULL) { + InterpExecute(pServ->pSics, pCon, self->updateScript); } - if(self->linkScript != NULL){ - InterpExecute(pServ->pSics,pCon,self->linkScript); + if (self->linkScript != NULL) { + InterpExecute(pServ->pSics, pCon, self->linkScript); } /* - register update function - */ + register update function + */ self->nextUpdate = time(NULL) + self->updateIntervall; self->iEnd = 0; self->pCon = pCon; - TaskRegister(pServ->pTasker,UpdateTask,NULL,NULL,self,1); + TaskRegister(pServ->pTasker, UpdateTask, NULL, NULL, self, 1); return 1; - } else if(iEvent == COUNTEND){ + } else if (iEvent == COUNTEND) { self->iEnd = 1; assert(self); return 1; } return 1; } + /*----------------------------------------------------------------------*/ -void KillUpdate(void *pData){ +void KillUpdate(void *pData) +{ pNXupdate self = NULL; - self = (pNXupdate)pData; - if(self == NULL){ + self = (pNXupdate) pData; + if (self == NULL) { return; } - if(self->startScript != NULL){ + if (self->startScript != NULL) { free(self->startScript); self->startScript = NULL; } - if(self->updateScript != NULL){ + if (self->updateScript != NULL) { free(self->updateScript); self->updateScript = NULL; } - if(self->linkScript != NULL){ + if (self->linkScript != NULL) { free(self->linkScript); self->linkScript = NULL; } free(self); } + /*-------------------------------------------------------------------*/ -static void printUpdateList(SConnection *pCon, pNXupdate self, char *name){ +static void printUpdateList(SConnection * pCon, pNXupdate self, char *name) +{ char pBueffel[256]; - snprintf(pBueffel,255,"%s.startScript = %s",name, self->startScript); - SCWrite(pCon,pBueffel,eValue); - snprintf(pBueffel,255,"%s.updateScript = %s",name, self->updateScript); - SCWrite(pCon,pBueffel,eValue); - snprintf(pBueffel,255,"%s.linkScript = %s",name, self->linkScript); - SCWrite(pCon,pBueffel,eValue); - snprintf(pBueffel,255,"%s.updateIntervall = %d",name, - self->updateIntervall); - SCWrite(pCon,pBueffel,eValue); - snprintf(pBueffel,255,"%s.onOff = %d",name, - self->onOff); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "%s.startScript = %s", name, self->startScript); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.updateScript = %s", name, + self->updateScript); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.linkScript = %s", name, self->linkScript); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.updateIntervall = %d", name, + self->updateIntervall); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.onOff = %d", name, self->onOff); + SCWrite(pCon, pBueffel, eValue); } + /*--------------------------------------------------------------------*/ -static int printUpdateParameters(SConnection *pCon, pNXupdate self, - char *name, char *param){ +static int printUpdateParameters(SConnection * pCon, pNXupdate self, + char *name, char *param) +{ char pBueffel[256]; - if(strcmp(param,"list") == 0){ - printUpdateList(pCon,self, name); + if (strcmp(param, "list") == 0) { + printUpdateList(pCon, self, name); return 1; - } else if(strcmp(param,"startscript") == 0){ - snprintf(pBueffel,255,"%s.startScript = %s",name, self->startScript); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(param, "startscript") == 0) { + snprintf(pBueffel, 255, "%s.startScript = %s", name, + self->startScript); + SCWrite(pCon, pBueffel, eValue); return 1; - } else if(strcmp(param,"updatescript")== 0){ - snprintf(pBueffel,255,"%s.updateScript = %s",name, self->updateScript); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(param, "updatescript") == 0) { + snprintf(pBueffel, 255, "%s.updateScript = %s", name, + self->updateScript); + SCWrite(pCon, pBueffel, eValue); return 1; - } else if(strcmp(param,"linkscript") == 0){ - snprintf(pBueffel,255,"%s.linkScript = %s",name, self->linkScript); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(param, "linkscript") == 0) { + snprintf(pBueffel, 255, "%s.linkScript = %s", name, self->linkScript); + SCWrite(pCon, pBueffel, eValue); return 1; - } else if(strcmp(param,"updateintervall") == 0){ - snprintf(pBueffel,255,"%s.updateIntervall = %d",name, - self->updateIntervall); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(param, "updateintervall") == 0) { + snprintf(pBueffel, 255, "%s.updateIntervall = %d", name, + self->updateIntervall); + SCWrite(pCon, pBueffel, eValue); return 1; - } else if(strcmp(param,"onoff") == 0){ - snprintf(pBueffel,255,"%s.onoff = %d",name, - self->onOff); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(param, "onoff") == 0) { + snprintf(pBueffel, 255, "%s.onoff = %d", name, self->onOff); + SCWrite(pCon, pBueffel, eValue); return 1; } else { - snprintf(pBueffel,255,"ERROR: parameter %s not known", param); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "ERROR: parameter %s not known", param); + SCWrite(pCon, pBueffel, eValue); return 0; } } + /*---------------------------------------------------------------------*/ -static int configureUpdate(SConnection *pCon, pNXupdate self, - char *param, char *value){ +static int configureUpdate(SConnection * pCon, pNXupdate self, + char *param, char *value) +{ char pBueffel[256]; int newUpdate; - if(strcmp(param,"startscript") == 0){ - if(self->startScript != NULL){ + if (strcmp(param, "startscript") == 0) { + if (self->startScript != NULL) { free(self->startScript); } self->startScript = strdup(value); SCSendOK(pCon); return 1; - } else if(strcmp(param,"updatescript")== 0){ - if(self->updateScript != NULL){ + } else if (strcmp(param, "updatescript") == 0) { + if (self->updateScript != NULL) { free(self->updateScript); } self->updateScript = strdup(value); SCSendOK(pCon); return 1; - } else if(strcmp(param,"linkscript") == 0){ - if(self->linkScript != NULL){ + } else if (strcmp(param, "linkscript") == 0) { + if (self->linkScript != NULL) { free(self->linkScript); } self->linkScript = strdup(value); SCSendOK(pCon); return 1; - } else if(strcmp(param,"updateintervall") == 0){ - if(Tcl_GetInt(InterpGetTcl(pServ->pSics),value,&newUpdate) != TCL_OK){ - snprintf(pBueffel,255, - "ERROR: %s not an int, cannot set updateIntervall", value); - SCWrite(pCon,pBueffel,eError); + } else if (strcmp(param, "updateintervall") == 0) { + if (Tcl_GetInt(InterpGetTcl(pServ->pSics), value, &newUpdate) != + TCL_OK) { + snprintf(pBueffel, 255, + "ERROR: %s not an int, cannot set updateIntervall", value); + SCWrite(pCon, pBueffel, eError); return 0; } self->updateIntervall = newUpdate; SCSendOK(pCon); return 1; - } else if(strcmp(param,"onoff") == 0){ - if(Tcl_GetInt(InterpGetTcl(pServ->pSics),value,&newUpdate) != TCL_OK){ - snprintf(pBueffel,255, - "ERROR: %s not an int, cannot set onoff", value); - SCWrite(pCon,pBueffel,eError); + } else if (strcmp(param, "onoff") == 0) { + if (Tcl_GetInt(InterpGetTcl(pServ->pSics), value, &newUpdate) != + TCL_OK) { + snprintf(pBueffel, 255, "ERROR: %s not an int, cannot set onoff", + value); + SCWrite(pCon, pBueffel, eError); return 0; } - if(newUpdate >= 1){ + if (newUpdate >= 1) { self->onOff = 1; } else { self->onOff = 0; @@ -214,43 +228,47 @@ static int configureUpdate(SConnection *pCon, pNXupdate self, SCSendOK(pCon); return 1; } else { - snprintf(pBueffel,255,"ERROR: parameter %s not known", param); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "ERROR: parameter %s not known", param); + SCWrite(pCon, pBueffel, eValue); return 0; } } + /*----------------------------------------------------------------------*/ -int UpdateAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int UpdateAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pNXupdate self = NULL; char pBueffel[132]; - self = (pNXupdate)pData; + self = (pNXupdate) pData; assert(self); - if(argc < 2){ - snprintf(pBueffel,131,"ERROR: need argument to %s", argv[0]); - SCWrite(pCon,pBueffel,eError); + if (argc < 2) { + snprintf(pBueffel, 131, "ERROR: need argument to %s", argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } - - if(argc < 3){ + + if (argc < 3) { strtolower(argv[1]); - return printUpdateParameters(pCon,self,argv[0], argv[1]); + return printUpdateParameters(pCon, self, argv[0], argv[1]); } else { - Arg2Text(argc-2,&argv[2],pBueffel,131); - return configureUpdate(pCon,self,argv[1],pBueffel); + Arg2Text(argc - 2, &argv[2], pBueffel, 131); + return configureUpdate(pCon, self, argv[1], pBueffel); } /* - not reached - */ + not reached + */ assert(0); return 0; } + /*----------------------------------------------------------------------*/ -int UpdateFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int UpdateFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pICountable pCount = NULL; pICallBack pCall = NULL; void *pPtr = NULL; @@ -258,45 +276,46 @@ int UpdateFactory(SConnection *pCon, SicsInterp *pSics, void *pData, pNXupdate self = NULL; CommandList *pCom = NULL; - if(argc < 3){ - SCWrite(pCon,"ERROR: insuffcient number of argument to UpdateFactory", - eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: insuffcient number of argument to UpdateFactory", + eError); return 0; } - + /* - argv[1] = name - argv[2] = counter with which to register for automatic notifications - */ - pCom = FindCommand(pSics,argv[2]); - if(pCom){ + argv[1] = name + argv[2] = counter with which to register for automatic notifications + */ + pCom = FindCommand(pSics, argv[2]); + if (pCom) { pPtr = pCom->pData; } - if(!pPtr){ - snprintf(pBueffel,255,"ERROR: cannot find %s to register to", argv[2]); - SCWrite(pCon,pBueffel,eError); + if (!pPtr) { + snprintf(pBueffel, 255, "ERROR: cannot find %s to register to", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } pCount = GetCountableInterface(pPtr); - pCall = GetCallbackInterface(pPtr); - if(!pCount || !pCall){ - snprintf(pBueffel,255,"ERROR: %s is not a usable counter",argv[2]); - SCWrite(pCon,pBueffel,eError); + pCall = GetCallbackInterface(pPtr); + if (!pCount || !pCall) { + snprintf(pBueffel, 255, "ERROR: %s is not a usable counter", argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } - + /* - allocate memory and initialize - */ - self = (pNXupdate)malloc(sizeof(NXupdate)); - if(self == NULL){ - SCWrite(pCon,"ERROR: out of memory in UpdateFactory",eError); + allocate memory and initialize + */ + self = (pNXupdate) malloc(sizeof(NXupdate)); + if (self == NULL) { + SCWrite(pCon, "ERROR: out of memory in UpdateFactory", eError); return 0; } - memset(self,0,sizeof(NXupdate)); + memset(self, 0, sizeof(NXupdate)); self->pDes = CreateDescriptor("AutoUpdate"); - if(self->pDes == NULL){ - SCWrite(pCon,"ERROR: out of memory in UpdateFactory",eError); + if (self->pDes == NULL) { + SCWrite(pCon, "ERROR: out of memory in UpdateFactory", eError); return 0; } self->startScript = strdup("UNDEFINED"); @@ -307,16 +326,11 @@ int UpdateFactory(SConnection *pCon, SicsInterp *pSics, void *pData, /* - register callbacks - */ - RegisterCallback(pCall,COUNTSTART,CountCallback, - self,NULL); - RegisterCallback(pCall,COUNTEND,CountCallback, - self,NULL); + register callbacks + */ + RegisterCallback(pCall, COUNTSTART, CountCallback, self, NULL); + RegisterCallback(pCall, COUNTEND, CountCallback, self, NULL); - AddCommand(pSics,argv[1],UpdateAction,KillUpdate,self); + AddCommand(pSics, argv[1], UpdateAction, KillUpdate, self); return 1; } - - - diff --git a/nxupdate.h b/nxupdate.h index fc584d73..b1639df6 100644 --- a/nxupdate.h +++ b/nxupdate.h @@ -10,11 +10,10 @@ #ifndef NXUPDATE #define NXUPDATE - int UpdateAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int UpdateFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int UpdateAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int UpdateFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - void KillUpdate(void *pData); +void KillUpdate(void *pData); #endif - diff --git a/nxutil.c b/nxutil.c index 07c74429..00dea0f3 100644 --- a/nxutil.c +++ b/nxutil.c @@ -18,316 +18,275 @@ #include "nxdict.h" #include "nxutil.h" /*-----------------------------------------------------------------------*/ - int SNXSPutMotor(SicsInterp *pSics, SConnection *pCon, - NXhandle hFil, NXdict pDict, - char *pAlias, char *pName) - { - pMotor pMot = NULL; - float fVal; - char pBueffel[512]; - int iRet; - - /* Find the motor */ - strncpy(pBueffel,pName,511); - strtolower(pBueffel); - pMot = FindMotor(pSics,pBueffel); - if(!pMot) - { - sprintf(pBueffel,"WARNING: cannot find motor %s",pName); - SCWrite(pCon,pBueffel,eWarning); - return 0; - } - - /* get the position */ - iRet = MotorGetSoftPosition(pMot,pCon,&fVal); - if(!iRet) /* should have been reported */ - { - return 0; - } - - /* write it */ - return NXDputalias(hFil,pDict,pAlias,&fVal); - } +int SNXSPutMotor(SicsInterp * pSics, SConnection * pCon, + NXhandle hFil, NXdict pDict, char *pAlias, char *pName) +{ + pMotor pMot = NULL; + float fVal; + char pBueffel[512]; + int iRet; + + /* Find the motor */ + strncpy(pBueffel, pName, 511); + strtolower(pBueffel); + pMot = FindMotor(pSics, pBueffel); + if (!pMot) { + sprintf(pBueffel, "WARNING: cannot find motor %s", pName); + SCWrite(pCon, pBueffel, eWarning); + return 0; + } + + /* get the position */ + iRet = MotorGetSoftPosition(pMot, pCon, &fVal); + if (!iRet) { /* should have been reported */ + return 0; + } + + /* write it */ + return NXDputalias(hFil, pDict, pAlias, &fVal); +} + /*-----------------------------------------------------------------------*/ - int SNXSPutMotorNull(SicsInterp *pSics, SConnection *pCon, - NXhandle hFil, NXdict pDict, - char *pAlias, char *pName) - { - pMotor pMot = NULL; - float fVal; - char pBueffel[512]; - int iRet; - - /* Find the motor */ - strncpy(pBueffel,pName,511); - strtolower(pBueffel); - pMot = FindMotor(pSics,pBueffel); - if(!pMot) - { - sprintf(pBueffel,"WARNING: cannot find motor %s",pName); - SCWrite(pCon,pBueffel,eWarning); - return 0; - } - - /* get the null point */ - iRet = MotorGetPar(pMot,"softzero",&fVal); - if(!iRet) /* should have been reported */ - { - sprintf(pBueffel, - "WARNING: failed to find zero point for motor %s", - pName); - SCWrite(pCon,pBueffel,eWarning); - return 0; - } - - /* write it */ - return NXDputalias(hFil,pDict,pAlias,&fVal); - } +int SNXSPutMotorNull(SicsInterp * pSics, SConnection * pCon, + NXhandle hFil, NXdict pDict, + char *pAlias, char *pName) +{ + pMotor pMot = NULL; + float fVal; + char pBueffel[512]; + int iRet; + + /* Find the motor */ + strncpy(pBueffel, pName, 511); + strtolower(pBueffel); + pMot = FindMotor(pSics, pBueffel); + if (!pMot) { + sprintf(pBueffel, "WARNING: cannot find motor %s", pName); + SCWrite(pCon, pBueffel, eWarning); + return 0; + } + + /* get the null point */ + iRet = MotorGetPar(pMot, "softzero", &fVal); + if (!iRet) { /* should have been reported */ + sprintf(pBueffel, + "WARNING: failed to find zero point for motor %s", pName); + SCWrite(pCon, pBueffel, eWarning); + return 0; + } + + /* write it */ + return NXDputalias(hFil, pDict, pAlias, &fVal); +} + /*-------------------------------------------------------------------------*/ - int SNXSPutVariable(SicsInterp *pSics,SConnection *pCon, - NXhandle hFil, NXdict pDict, - char *pAlias, char *pName) - { - pSicsVariable pVar = NULL; - int iRet; - float fVal; - int iVal; - char pBueffel[512]; - VarType eType; - char *pText = NULL; - - /* find it */ - strncpy(pBueffel,pName,511); - strtolower(pBueffel); - pVar = FindVariable(pSics,pBueffel); - if(!pVar) - { - sprintf(pBueffel,"WARNING: cannot find variable %s",pName); - SCWrite(pCon,pBueffel,eWarning); - return 0; - } +int SNXSPutVariable(SicsInterp * pSics, SConnection * pCon, + NXhandle hFil, NXdict pDict, char *pAlias, char *pName) +{ + pSicsVariable pVar = NULL; + int iRet; + float fVal; + int iVal; + char pBueffel[512]; + VarType eType; + char *pText = NULL; + + /* find it */ + strncpy(pBueffel, pName, 511); + strtolower(pBueffel); + pVar = FindVariable(pSics, pBueffel); + if (!pVar) { + sprintf(pBueffel, "WARNING: cannot find variable %s", pName); + SCWrite(pCon, pBueffel, eWarning); + return 0; + } + + /* write it, depending on type */ + eType = GetVarType(pVar); + switch (eType) { + case veText: + VarGetText(pVar, &pText); + if (pText != NULL) { + memset(pBueffel, 0, 511); + strncpy(pBueffel, pText, 511); + iRet = NXDputalias(hFil, pDict, pAlias, pBueffel); + free(pText); + return iRet; + } + break; + case veInt: + VarGetInt(pVar, &iVal); + return NXDputalias(hFil, pDict, pAlias, &iVal); + break; + case veFloat: + VarGetFloat(pVar, &fVal); + return NXDputalias(hFil, pDict, pAlias, &fVal); + break; + default: + assert(0); /* should not happen */ + + } + return 1; +} - /* write it, depending on type */ - eType = GetVarType(pVar); - switch(eType) - { - case veText: - VarGetText(pVar,&pText); - if(pText != NULL) - { - memset(pBueffel,0,511); - strncpy(pBueffel,pText,511); - iRet = NXDputalias(hFil,pDict,pAlias,pBueffel); - free(pText); - return iRet; - } - break; - case veInt: - VarGetInt(pVar,&iVal); - return NXDputalias(hFil,pDict,pAlias,&iVal); - break; - case veFloat: - VarGetFloat(pVar,&fVal); - return NXDputalias(hFil,pDict,pAlias,&fVal); - break; - default: - assert(0); /* should not happen */ - - } - return 1; - } /*------------------------------------------------------------------------*/ - void SNXFormatTime(char *pBuffer, int iBufLen) - { - time_t iDate; - struct tm *psTime; +void SNXFormatTime(char *pBuffer, int iBufLen) +{ + time_t iDate; + struct tm *psTime; + + /* make time string */ + iDate = time(NULL); + psTime = localtime(&iDate); + memset(pBuffer, 0, iBufLen); + strftime(pBuffer, iBufLen, "%Y-%m-%d %H:%M:%S", psTime); +} - /* make time string */ - iDate = time(NULL); - psTime = localtime(&iDate); - memset(pBuffer,0,iBufLen); - strftime(pBuffer,iBufLen,"%Y-%m-%d %H:%M:%S",psTime); - } /*--------------------------------------------------------------------------*/ - int SNXSPutGlobals(NXhandle hfil,char *pFilename, - char *pInst, SConnection *pCon) - { - pSicsVariable pVar = NULL; - char pBueffel[1024]; - char *pUser,*pemail,*pPhone,*pFax, *pAddress; - int iRet; - - /* write global attributes */ - strcpy(pBueffel,"UNKNOWN"); - pVar = FindVariable(pServ->pSics,"user"); - if(pVar) - { - pUser = pVar->text; - } - else - { - SCWrite(pCon,"WARNING: Variable user not found ",eWarning); - pUser = pBueffel; - } - pVar = FindVariable(pServ->pSics,"phone"); - if(pVar) - { - pPhone = pVar->text; - } - else - { - SCWrite(pCon,"WARNING: Variable phone not found ",eWarning); - pPhone = pBueffel; - } - pVar = FindVariable(pServ->pSics,"email"); - if(pVar) - { - pemail = pVar->text; - } - else - { - SCWrite(pCon,"WARNING: Variable email not found ",eWarning); - pemail = pBueffel; - } - pVar = FindVariable(pServ->pSics,"adress"); - if(pVar) - { - pAddress = pVar->text; - } - else - { - SCWrite(pCon,"WARNING: Variable adress not found ",eWarning); - pAddress = pBueffel; - } - pVar = FindVariable(pServ->pSics,"fax"); - if(pVar) - { - pFax = pVar->text; - } - else - { - SCWrite(pCon,"WARNING: Variable phone not found ",eWarning); - pFax = pBueffel; - } - iRet = NXUwriteglobals(hfil, - pFilename, - pUser, - pAddress, - pPhone, - pemail, - pFax, - pInst); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: failed writing global attributes to file",eWarning); - } +int SNXSPutGlobals(NXhandle hfil, char *pFilename, + char *pInst, SConnection * pCon) +{ + pSicsVariable pVar = NULL; + char pBueffel[1024]; + char *pUser, *pemail, *pPhone, *pFax, *pAddress; + int iRet; + + /* write global attributes */ + strcpy(pBueffel, "UNKNOWN"); + pVar = FindVariable(pServ->pSics, "user"); + if (pVar) { + pUser = pVar->text; + } else { + SCWrite(pCon, "WARNING: Variable user not found ", eWarning); + pUser = pBueffel; + } + pVar = FindVariable(pServ->pSics, "phone"); + if (pVar) { + pPhone = pVar->text; + } else { + SCWrite(pCon, "WARNING: Variable phone not found ", eWarning); + pPhone = pBueffel; + } + pVar = FindVariable(pServ->pSics, "email"); + if (pVar) { + pemail = pVar->text; + } else { + SCWrite(pCon, "WARNING: Variable email not found ", eWarning); + pemail = pBueffel; + } + pVar = FindVariable(pServ->pSics, "adress"); + if (pVar) { + pAddress = pVar->text; + } else { + SCWrite(pCon, "WARNING: Variable adress not found ", eWarning); + pAddress = pBueffel; + } + pVar = FindVariable(pServ->pSics, "fax"); + if (pVar) { + pFax = pVar->text; + } else { + SCWrite(pCon, "WARNING: Variable phone not found ", eWarning); + pFax = pBueffel; + } + iRet = NXUwriteglobals(hfil, + pFilename, + pUser, pAddress, pPhone, pemail, pFax, pInst); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: failed writing global attributes to file", + eWarning); + } + + return 1; +} - return 1; - } /*---------------------------------------------------------------------------*/ - int SNXSPutEVVar(NXhandle hfil, NXdict pDict, - char *pName, SConnection *pCon, - char *pValAlias, char *pStdDevAlias) - { - CommandList *pCom = NULL; - pIDrivable pDriv = NULL; - float fMean, fStdDev; - pVarLog pLog = NULL; - int iRet; - char pBueffel[512]; - pSicsVariable pVar = NULL; +int SNXSPutEVVar(NXhandle hfil, NXdict pDict, + char *pName, SConnection * pCon, + char *pValAlias, char *pStdDevAlias) +{ + CommandList *pCom = NULL; + pIDrivable pDriv = NULL; + float fMean, fStdDev; + pVarLog pLog = NULL; + int iRet; + char pBueffel[512]; + pSicsVariable pVar = NULL; + + pCom = NULL; + fMean = -111.; + fStdDev = -111.; + pCom = FindCommand(pServ->pSics, pName); + if (pCom) { + pDriv = GetDrivableInterface(pCom->pData); + if (pDriv) { /* it is a controller */ + pLog = EVCGetVarLog((pEVControl) pCom->pData); + iRet = VarlogGetMean(pLog, &fMean, &fStdDev); + if (!iRet) { /* the data was not logged, get the value */ + iRet = EVCGetPos((pEVControl) pCom->pData, pCon, &fMean); + } + } else { + /* it can still be a simple variable */ + pVar = (pSicsVariable) pCom->pData; + fMean = pVar->fVal; + } + } + + if (fMean < -110) { + sprintf(pBueffel, "WARNING: %s invalid", pName); + SCWrite(pCon, pBueffel, eWarning); + } + if (pStdDevAlias) { + if (fStdDev < -110) { + sprintf(pBueffel, "WARNING: %s standard deviation invalid", pName); + SCWrite(pCon, pBueffel, eWarning); + } + } + /* whatever it was, write it, even if it is shit */ + iRet = NXDputalias(hfil, pDict, pValAlias, &fMean); + if (iRet != NX_OK) { + sprintf(pBueffel, "WARNING: failed to write %s", pName); + SCWrite(pCon, pBueffel, eWarning); + } + if (pStdDevAlias) { + iRet = NXDputalias(hfil, pDict, pStdDevAlias, &fStdDev); + if (iRet != NX_OK) { + sprintf(pBueffel, "WARNING: failed to write %s standard deviation", + pName); + SCWrite(pCon, pBueffel, eWarning); + } + } + return 1; +} - pCom = NULL; - fMean = -111.; - fStdDev = -111.; - pCom = FindCommand(pServ->pSics,pName); - if(pCom) - { - pDriv = GetDrivableInterface(pCom->pData); - if(pDriv) /* it is a controller */ - { - pLog = EVCGetVarLog((pEVControl)pCom->pData); - iRet = VarlogGetMean(pLog,&fMean, &fStdDev); - if(!iRet) - { /* the data was not logged, get the value */ - iRet = EVCGetPos((pEVControl)pCom->pData,pCon,&fMean); - } - } - else - { - /* it can still be a simple variable */ - pVar = (pSicsVariable)pCom->pData; - fMean = pVar->fVal; - } - } - - if(fMean < -110) - { - sprintf(pBueffel,"WARNING: %s invalid",pName); - SCWrite(pCon,pBueffel,eWarning); - } - if(pStdDevAlias) - { - if(fStdDev < -110) - { - sprintf(pBueffel,"WARNING: %s standard deviation invalid",pName); - SCWrite(pCon,pBueffel,eWarning); - } - } - /* whatever it was, write it, even if it is shit */ - iRet = NXDputalias(hfil,pDict,pValAlias,&fMean); - if(iRet != NX_OK) - { - sprintf(pBueffel,"WARNING: failed to write %s",pName); - SCWrite(pCon,pBueffel,eWarning); - } - if(pStdDevAlias) - { - iRet = NXDputalias(hfil,pDict,pStdDevAlias,&fStdDev); - if(iRet != NX_OK) - { - sprintf(pBueffel,"WARNING: failed to write %s standard deviation",pName); - SCWrite(pCon,pBueffel,eWarning); - } - } - return 1; - } /*---------------------------------------------------------------------------*/ - int SNXSPutDrivable(SicsInterp *pSics, SConnection *pCon, - NXhandle hfil, NXdict pDict, - char *pName, - char *pAlias) - { - CommandList *pCom = NULL; - pIDrivable pDriv = NULL; - float fVal =- -777.77; - int iRet; - char pBueffel[512]; +int SNXSPutDrivable(SicsInterp * pSics, SConnection * pCon, + NXhandle hfil, NXdict pDict, char *pName, char *pAlias) +{ + CommandList *pCom = NULL; + pIDrivable pDriv = NULL; + float fVal = -777.77; + int iRet; + char pBueffel[512]; - pCom = NULL; - pCom = FindCommand(pSics,pName); - if(pCom) - { - pDriv = GetDrivableInterface(pCom->pData); - if(pDriv) /* it is drivable */ - { - fVal = pDriv->GetValue(pCom->pData,pCon); - } - else - { - sprintf(pBueffel,"ERROR: %s is not driveable, not written",pName); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - - /* whatever it was, write it, even if it is shit */ - iRet = NXDputalias(hfil,pDict,pAlias,&fVal); - if(iRet != NX_OK) - { - sprintf(pBueffel,"WARNING: failed to write %s",pName); - SCWrite(pCon,pBueffel,eWarning); - return 0; - } - return 1; - } + pCom = NULL; + pCom = FindCommand(pSics, pName); + if (pCom) { + pDriv = GetDrivableInterface(pCom->pData); + if (pDriv) { /* it is drivable */ + fVal = pDriv->GetValue(pCom->pData, pCon); + } else { + sprintf(pBueffel, "ERROR: %s is not driveable, not written", pName); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + + /* whatever it was, write it, even if it is shit */ + iRet = NXDputalias(hfil, pDict, pAlias, &fVal); + if (iRet != NX_OK) { + sprintf(pBueffel, "WARNING: failed to write %s", pName); + SCWrite(pCon, pBueffel, eWarning); + return 0; + } + return 1; +} diff --git a/nxutil.h b/nxutil.h index 87cab7f5..0c665d32 100644 --- a/nxutil.h +++ b/nxutil.h @@ -9,26 +9,26 @@ ---------------------------------------------------------------------------*/ #ifndef NXUTIL #define NXUTIL - int SNXSPutMotor(SicsInterp *pSics, SConnection *pCon, NXhandle hFil, - NXdict pDict, char *pAlias, char *pName); - int SNXSPutMotorNull(SicsInterp *pSics, SConnection *pCon, NXhandle hFil, - NXdict pDict, char *pAlias, char *pName); - int SNXSPutVariable(SicsInterp *pSics, SConnection *pCon, - NXhandle hFil, NXdict pDict, char *pAlias, - char *pName); - int SNXSPutEVVar(NXhandle hfil, NXdict pDict, - char *pName, SConnection *pCon, - char *pValAlias, char *pStdDevAlias); - int SNXSPutGlobals(NXhandle hfil, char *pFile, char *pInst, - SConnection *pCon); - void SNXFormatTime(char *pBuffer, int iLen); - - char *SNXMakeFileName(SicsInterp *pSics, SConnection *pCon); - /* - coded in nxdata.c - */ - int SNXSPutDrivable(SicsInterp *pSics, SConnection *pCon, NXhandle hFil, - NXdict pDict, char *pAlias, char *pName); +int SNXSPutMotor(SicsInterp * pSics, SConnection * pCon, NXhandle hFil, + NXdict pDict, char *pAlias, char *pName); +int SNXSPutMotorNull(SicsInterp * pSics, SConnection * pCon, NXhandle hFil, + NXdict pDict, char *pAlias, char *pName); +int SNXSPutVariable(SicsInterp * pSics, SConnection * pCon, + NXhandle hFil, NXdict pDict, char *pAlias, + char *pName); +int SNXSPutEVVar(NXhandle hfil, NXdict pDict, + char *pName, SConnection * pCon, + char *pValAlias, char *pStdDevAlias); +int SNXSPutGlobals(NXhandle hfil, char *pFile, char *pInst, + SConnection * pCon); +void SNXFormatTime(char *pBuffer, int iLen); - -#endif +char *SNXMakeFileName(SicsInterp * pSics, SConnection * pCon); + /* + coded in nxdata.c + */ +int SNXSPutDrivable(SicsInterp * pSics, SConnection * pCon, NXhandle hFil, + NXdict pDict, char *pAlias, char *pName); + + +#endif diff --git a/nxxml.c b/nxxml.c index e1ab96aa..559682b1 100644 --- a/nxxml.c +++ b/nxxml.c @@ -29,9 +29,9 @@ #include "nxdataset.h" -extern void *NXpData; +extern void *NXpData; -char *nxitrim(char *str); /* from napi.c */ +char *nxitrim(char *str); /* from napi.c */ /*----------------------- our data structures -------------------------- One might wonder why a node stack is still needed even if this API @@ -46,41 +46,46 @@ char *nxitrim(char *str); /* from napi.c */ the tree. -----------------------------------------------------------------------*/ typedef struct { - mxml_node_t *current; - mxml_node_t *currentChild; - int currentAttribute; -}xmlStack; + mxml_node_t *current; + mxml_node_t *currentChild; + int currentAttribute; +} xmlStack; /*---------------------------------------------------------------------*/ typedef struct { - mxml_node_t *root; /* root node */ - int readOnly; /* read only flag */ - int stackPointer; /* stack pointer */ - char filename[1024]; /* file name, for NXflush, NXclose */ - xmlStack stack[NXMAXSTACK]; /* stack */ -}XMLNexus, *pXMLNexus; + mxml_node_t *root; /* root node */ + int readOnly; /* read only flag */ + int stackPointer; /* stack pointer */ + char filename[1024]; /* file name, for NXflush, NXclose */ + xmlStack stack[NXMAXSTACK]; /* stack */ +} XMLNexus, *pXMLNexus; /*===================== support functions ===============================*/ extern char *stptok(char *s, char *tok, size_t toklen, char *brk); /*----------------------------------------------------------------------*/ -static mxml_node_t *getLinkTarget(pXMLNexus xmlHandle, const char *target){ +static mxml_node_t *getLinkTarget(pXMLNexus xmlHandle, const char *target) +{ mxml_node_t *node = NULL; mxml_node_t *testNode = NULL; char path[132], *pPtr; - pPtr = (char *)target + 1; + pPtr = (char *) target + 1; node = xmlHandle->stack[0].current; - while((pPtr = stptok(pPtr,path,131,"/")) != NULL){ + while ((pPtr = stptok(pPtr, path, 131, "/")) != NULL) { /* - search for group node - */ - testNode = mxmlFindElement(node,node,NULL,"name",path,MXML_DESCEND_FIRST); - if(testNode == NULL){ + search for group node + */ + testNode = + mxmlFindElement(node, node, NULL, "name", path, + MXML_DESCEND_FIRST); + if (testNode == NULL) { /* - it can still be a data node - */ - testNode = mxmlFindElement(node,node,path,NULL,NULL,MXML_DESCEND_FIRST); + it can still be a data node + */ + testNode = + mxmlFindElement(node, node, path, NULL, NULL, + MXML_DESCEND_FIRST); } - if(testNode == NULL){ - NXIReportError(NXpData,"Cannot follow broken link"); + if (testNode == NULL) { + NXIReportError(NXpData, "Cannot follow broken link"); return NULL; } else { node = testNode; @@ -88,104 +93,109 @@ static mxml_node_t *getLinkTarget(pXMLNexus xmlHandle, const char *target){ } return node; } + /*==================== file functions ===================================*/ -static void errorCallbackForMxml(const char *txt){ - NXIReportError(NXpData,(char *)txt); +static void errorCallbackForMxml(const char *txt) +{ + NXIReportError(NXpData, (char *) txt); } + /*-----------------------------------------------------------------------*/ -NXstatus NXXopen(CONSTCHAR *filename, NXaccess am, - NXhandle* pHandle) { +NXstatus NXXopen(CONSTCHAR * filename, NXaccess am, NXhandle * pHandle) +{ pXMLNexus xmlHandle = NULL; FILE *fp = NULL; char *time_buffer = NULL; mxml_node_t *current; /* - allocate data - */ - xmlHandle = (pXMLNexus)malloc(sizeof(XMLNexus)); - if(!xmlHandle){ + allocate data + */ + xmlHandle = (pXMLNexus) malloc(sizeof(XMLNexus)); + if (!xmlHandle) { NXIReportError(NXpData, "Out of memory allocating XML file handle"); return NX_ERROR; } - memset(xmlHandle,0,sizeof(XMLNexus)); + memset(xmlHandle, 0, sizeof(XMLNexus)); /* - initialize mxml XML parser - */ + initialize mxml XML parser + */ mxmlSetCustomHandlers(nexusLoadCallback, nexusWriteCallback); initializeNumberFormats(); mxmlSetErrorCallback(errorCallbackForMxml); /* - open file - */ - strncpy(xmlHandle->filename,filename,1023); - switch(am){ + open file + */ + strncpy(xmlHandle->filename, filename, 1023); + switch (am) { case NXACC_READ: xmlHandle->readOnly = 1; case NXACC_RDWR: - fp = fopen(filename,"r"); - if(fp == NULL){ - NXIReportError(NXpData,"Failed to open file:"); - NXIReportError(NXpData,(char *)filename); + fp = fopen(filename, "r"); + if (fp == NULL) { + NXIReportError(NXpData, "Failed to open file:"); + NXIReportError(NXpData, (char *) filename); free(xmlHandle); return NX_ERROR; } - xmlHandle->root = mxmlLoadFile(NULL,fp,nexusTypeCallback); + xmlHandle->root = mxmlLoadFile(NULL, fp, nexusTypeCallback); xmlHandle->stack[0].current = mxmlFindElement(xmlHandle->root, - xmlHandle->root, - "NXroot", - NULL,NULL, - MXML_DESCEND); + xmlHandle->root, + "NXroot", + NULL, NULL, + MXML_DESCEND); xmlHandle->stack[0].currentChild = NULL; xmlHandle->stack[0].currentAttribute = 0; fclose(fp); break; case NXACC_CREATEXML: xmlHandle->root = mxmlNewElement(NULL, - "?xml version=\"1.0\" encoding=\"UTF-8\"?"); - current = mxmlNewElement(xmlHandle->root,"NXroot"); - mxmlElementSetAttr(current,"NeXus_version",NEXUS_VERSION); - mxmlElementSetAttr(current,"XML_version","mxml"); - mxmlElementSetAttr(current,"file_name",filename); + "?xml version=\"1.0\" encoding=\"UTF-8\"?"); + current = mxmlNewElement(xmlHandle->root, "NXroot"); + mxmlElementSetAttr(current, "NeXus_version", NEXUS_VERSION); + mxmlElementSetAttr(current, "XML_version", "mxml"); + mxmlElementSetAttr(current, "file_name", filename); time_buffer = NXIformatNeXusTime(); - if(time_buffer != NULL){ - mxmlElementSetAttr(current,"file_time",time_buffer); + if (time_buffer != NULL) { + mxmlElementSetAttr(current, "file_time", time_buffer); free(time_buffer); - } + } xmlHandle->stack[0].current = current; xmlHandle->stack[0].currentChild = NULL; xmlHandle->stack[0].currentAttribute = 0; break; default: - NXIReportError(NXpData,"Bad access parameter specified in NXXopen"); + NXIReportError(NXpData, "Bad access parameter specified in NXXopen"); return NX_ERROR; } - if(xmlHandle->stack[0].current == NULL){ - NXIReportError(NXpData, - "No NXroot element in XML-file, no NeXus-XML file"); - return NX_ERROR; + if (xmlHandle->stack[0].current == NULL) { + NXIReportError(NXpData, + "No NXroot element in XML-file, no NeXus-XML file"); + return NX_ERROR; } *pHandle = xmlHandle; return NX_OK; } + /*----------------------------------------------------------------------*/ -NXstatus NXXclose (NXhandle* fid){ +NXstatus NXXclose(NXhandle * fid) +{ pXMLNexus xmlHandle = NULL; FILE *fp = NULL; - xmlHandle = (pXMLNexus)*fid; + xmlHandle = (pXMLNexus) * fid; assert(xmlHandle); - - if(xmlHandle->readOnly == 0) { - fp = fopen(xmlHandle->filename,"w"); - if(fp == NULL){ - NXIReportError(NXpData,"Failed to open NeXus XML file for writing"); + + if (xmlHandle->readOnly == 0) { + fp = fopen(xmlHandle->filename, "w"); + if (fp == NULL) { + NXIReportError(NXpData, "Failed to open NeXus XML file for writing"); return NX_ERROR; } - mxmlSaveFile(xmlHandle->root,fp,NXwhitespaceCallback); + mxmlSaveFile(xmlHandle->root, fp, NXwhitespaceCallback); fclose(fp); } mxmlDelete(xmlHandle->root); @@ -193,53 +203,60 @@ NXstatus NXXclose (NXhandle* fid){ *fid = NULL; return NX_OK; } + /*----------------------------------------------------------------------*/ -NXstatus NXXflush(NXhandle *fid){ +NXstatus NXXflush(NXhandle * fid) +{ pXMLNexus xmlHandle = NULL; FILE *fp = NULL; - xmlHandle = (pXMLNexus)*fid; + xmlHandle = (pXMLNexus) * fid; assert(xmlHandle); - - if(xmlHandle->readOnly == 0) { - fp = fopen(xmlHandle->filename,"w"); - if(fp == NULL){ - NXIReportError(NXpData,"Failed to open NeXus XML file for writing"); + + if (xmlHandle->readOnly == 0) { + fp = fopen(xmlHandle->filename, "w"); + if (fp == NULL) { + NXIReportError(NXpData, "Failed to open NeXus XML file for writing"); return NX_ERROR; } - mxmlSaveFile(xmlHandle->root,fp,NXwhitespaceCallback); + mxmlSaveFile(xmlHandle->root, fp, NXwhitespaceCallback); fclose(fp); } return NX_OK; } + /*======================================================================= Group functions =========================================================================*/ -NXstatus NXXmakegroup (NXhandle fid, CONSTCHAR *name, - CONSTCHAR *nxclass){ +NXstatus NXXmakegroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *newGroup = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"Close dataset before trying to create a group"); + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, + "Close dataset before trying to create a group"); return NX_ERROR; } - newGroup = mxmlNewElement(xmlHandle->stack[xmlHandle->stackPointer].current, - nxclass); - if(!newGroup){ - NXIReportError(NXpData,"failed to allocate new group"); + newGroup = + mxmlNewElement(xmlHandle->stack[xmlHandle->stackPointer].current, + nxclass); + if (!newGroup) { + NXIReportError(NXpData, "failed to allocate new group"); return NX_ERROR; } - mxmlElementSetAttr(newGroup,"name",name); + mxmlElementSetAttr(newGroup, "name", name); return NX_OK; -} +} + /*----------------------------------------------------------------------*/ -static mxml_node_t *searchGroupLinks(pXMLNexus xmlHandle, CONSTCHAR *name, - CONSTCHAR *nxclass){ +static mxml_node_t *searchGroupLinks(pXMLNexus xmlHandle, CONSTCHAR * name, + CONSTCHAR * nxclass) +{ mxml_node_t *linkNode = NULL; mxml_node_t *current; mxml_node_t *test = NULL; @@ -248,57 +265,57 @@ static mxml_node_t *searchGroupLinks(pXMLNexus xmlHandle, CONSTCHAR *name, current = xmlHandle->stack[xmlHandle->stackPointer].current; linkNode = current; - while((linkNode = mxmlFindElement(linkNode,current,"NAPIlink",NULL,NULL, - MXML_DESCEND_FIRST)) != NULL){ - linkTarget = mxmlElementGetAttr(linkNode,"target"); - test = getLinkTarget(xmlHandle,linkTarget); - if(test != NULL){ - if(strcmp(test->value.element.name,nxclass) == 0){ - if(strcmp(mxmlElementGetAttr(test,"name"),name) == 0){ - return test; - } + while ((linkNode = + mxmlFindElement(linkNode, current, "NAPIlink", NULL, NULL, + MXML_DESCEND_FIRST)) != NULL) { + linkTarget = mxmlElementGetAttr(linkNode, "target"); + test = getLinkTarget(xmlHandle, linkTarget); + if (test != NULL) { + if (strcmp(test->value.element.name, nxclass) == 0) { + if (strcmp(mxmlElementGetAttr(test, "name"), name) == 0) { + return test; + } } } /* - test for named links - */ - linkName = mxmlElementGetAttr(linkNode,"name"); - if(test != NULL && linkName != NULL){ - if(strcmp(test->value.element.name,nxclass) == 0){ - if(strcmp(linkName, name) == 0){ - return test; - } + test for named links + */ + linkName = mxmlElementGetAttr(linkNode, "name"); + if (test != NULL && linkName != NULL) { + if (strcmp(test->value.element.name, nxclass) == 0) { + if (strcmp(linkName, name) == 0) { + return test; + } } } } return NULL; } + /*------------------------------------------------------------------------*/ -NXstatus NXXopengroup (NXhandle fid, CONSTCHAR *name, - CONSTCHAR *nxclass){ +NXstatus NXXopengroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *newGroup = NULL; char error[1024]; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"Close dataset before trying to open a group"); + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "Close dataset before trying to open a group"); return NX_ERROR; } - newGroup = mxmlFindElement(xmlHandle->stack[xmlHandle->stackPointer].current, - xmlHandle->stack[xmlHandle->stackPointer].current, - nxclass, - "name", - name, - MXML_DESCEND_FIRST); - if(newGroup == NULL){ - newGroup = searchGroupLinks(xmlHandle,name,nxclass); + newGroup = + mxmlFindElement(xmlHandle->stack[xmlHandle->stackPointer].current, + xmlHandle->stack[xmlHandle->stackPointer].current, + nxclass, "name", name, MXML_DESCEND_FIRST); + if (newGroup == NULL) { + newGroup = searchGroupLinks(xmlHandle, name, nxclass); } - if(!newGroup){ - snprintf(error,1023,"Failed to open %s, %s",name,nxclass); - NXIReportError(NXpData,error); + if (!newGroup) { + snprintf(error, 1023, "Failed to open %s, %s", name, nxclass); + NXIReportError(NXpData, error); return NX_ERROR; } xmlHandle->stackPointer++; @@ -307,125 +324,137 @@ NXstatus NXXopengroup (NXhandle fid, CONSTCHAR *name, xmlHandle->stack[xmlHandle->stackPointer].currentAttribute = 0; return NX_OK; } + /*----------------------------------------------------------------------*/ -NXstatus NXXclosegroup (NXhandle fid){ +NXstatus NXXclosegroup(NXhandle fid) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *newGroup = NULL; char error[1024]; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { /* - silently fix this - */ + silently fix this + */ NXXclosedata(fid); } - if(xmlHandle->stackPointer > 0){ + if (xmlHandle->stackPointer > 0) { xmlHandle->stackPointer--; } return NX_OK; } + /*========================================================================= dataset functions =========================================================================*/ -NXstatus NXXcompmakedata (NXhandle fid, CONSTCHAR *name, - int datatype, - int rank, - int dimensions[], - int compress_type, int chunk_size[]){ +NXstatus NXXcompmakedata(NXhandle fid, CONSTCHAR * name, + int datatype, + int rank, + int dimensions[], + int compress_type, int chunk_size[]) +{ /* - compression does not relly make sense with XML - */ - return NXXmakedata(fid,name,datatype,rank,dimensions); + compression does not relly make sense with XML + */ + return NXXmakedata(fid, name, datatype, rank, dimensions); } + /*-----------------------------------------------------------------------*/ -static char *buildTypeString(int datatype, int rank, int dimensions[]){ +static char *buildTypeString(int datatype, int rank, int dimensions[]) +{ char *typestring = NULL; char pNumber[20]; int i; /* - allocate data - */ - typestring = (char *)malloc(132*sizeof(char)); - if(!typestring){ - NXIReportError(NXpData,"Failed to allocate typestring"); + allocate data + */ + typestring = (char *) malloc(132 * sizeof(char)); + if (!typestring) { + NXIReportError(NXpData, "Failed to allocate typestring"); return NULL; } - memset(typestring,0,132*sizeof(char)); + memset(typestring, 0, 132 * sizeof(char)); - getNumberText(datatype,typestring,130); - if(rank > 1 || dimensions[0] > 1) { - strcat(typestring,"["); - snprintf(pNumber,19,"%d",dimensions[0]); - strncat(typestring,pNumber,130-strlen(typestring)); - for(i = 1; i < rank; i++){ - snprintf(pNumber,19,",%d",dimensions[i]); - strncat(typestring,pNumber,130-strlen(typestring)); + getNumberText(datatype, typestring, 130); + if (rank > 1 || dimensions[0] > 1) { + strcat(typestring, "["); + snprintf(pNumber, 19, "%d", dimensions[0]); + strncat(typestring, pNumber, 130 - strlen(typestring)); + for (i = 1; i < rank; i++) { + snprintf(pNumber, 19, ",%d", dimensions[i]); + strncat(typestring, pNumber, 130 - strlen(typestring)); } - strcat(typestring,"]"); + strcat(typestring, "]"); } return typestring; } + /*------------------------------------------------------------------------*/ -NXstatus NXXmakedata (NXhandle fid, - CONSTCHAR *name, int datatype, - int rank, int dimensions[]){ +NXstatus NXXmakedata(NXhandle fid, + CONSTCHAR * name, int datatype, + int rank, int dimensions[]) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *dataNode = NULL; mxml_node_t *newData = NULL; mxml_node_t *current; char *typestring; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"Close dataset before trying to create a dataset"); + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, + "Close dataset before trying to create a dataset"); return NX_ERROR; } - if(dimensions[0] < 0){ + if (dimensions[0] < 0) { dimensions[0] = 1; } current = xmlHandle->stack[xmlHandle->stackPointer].current; - dataNode = mxmlNewElement(current,name); - typestring = buildTypeString(datatype,rank,dimensions); - if(typestring != NULL){ - mxmlElementSetAttr(dataNode,TYPENAME,typestring); + dataNode = mxmlNewElement(current, name); + typestring = buildTypeString(datatype, rank, dimensions); + if (typestring != NULL) { + mxmlElementSetAttr(dataNode, TYPENAME, typestring); free(typestring); } else { - NXIReportError(NXpData,"Failed to allocate typestring"); + NXIReportError(NXpData, "Failed to allocate typestring"); return NX_ERROR; } /* - NX_CHAR maps to MXML_OPAQUE datasets - */ - if(datatype == NX_CHAR){ - newData = mxmlNewOpaque(dataNode,""); + NX_CHAR maps to MXML_OPAQUE datasets + */ + if (datatype == NX_CHAR) { + newData = mxmlNewOpaque(dataNode, ""); return NX_OK; } else { - newData = (mxml_node_t *)malloc(sizeof(mxml_node_t)); - if(!newData){ - NXIReportError(NXpData,"Failed to allocate space for dataset"); + newData = (mxml_node_t *) malloc(sizeof(mxml_node_t)); + if (!newData) { + NXIReportError(NXpData, "Failed to allocate space for dataset"); return NX_ERROR; } - memset(newData,0,sizeof(mxml_node_t)); + memset(newData, 0, sizeof(mxml_node_t)); mxmlAdd(dataNode, MXML_ADD_AFTER, MXML_ADD_TO_PARENT, newData); newData->type = MXML_CUSTOM; - newData->value.custom.data = createNXDataset(rank,datatype,dimensions); - if(!newData->value.custom.data){ - NXIReportError(NXpData,"Failed to allocate space for dataset"); + newData->value.custom.data = + createNXDataset(rank, datatype, dimensions); + if (!newData->value.custom.data) { + NXIReportError(NXpData, "Failed to allocate space for dataset"); return NX_ERROR; } newData->value.custom.destroy = destroyDataset; } return NX_OK; } + /*----------------------------------------------------------------------*/ -static mxml_node_t *searchSDSLinks(pXMLNexus xmlHandle, CONSTCHAR *name){ +static mxml_node_t *searchSDSLinks(pXMLNexus xmlHandle, CONSTCHAR * name) +{ mxml_node_t *linkNode = NULL; mxml_node_t *current; mxml_node_t *test = NULL; @@ -434,58 +463,59 @@ static mxml_node_t *searchSDSLinks(pXMLNexus xmlHandle, CONSTCHAR *name){ current = xmlHandle->stack[xmlHandle->stackPointer].current; linkNode = current; - while((linkNode = mxmlFindElement(linkNode,current,"NAPIlink",NULL,NULL, - MXML_DESCEND_FIRST)) != NULL){ - linkTarget = mxmlElementGetAttr(linkNode,"target"); - test = getLinkTarget(xmlHandle,linkTarget); - if(test != NULL){ - if(strcmp(test->value.element.name,name) == 0){ - return test; + while ((linkNode = + mxmlFindElement(linkNode, current, "NAPIlink", NULL, NULL, + MXML_DESCEND_FIRST)) != NULL) { + linkTarget = mxmlElementGetAttr(linkNode, "target"); + test = getLinkTarget(xmlHandle, linkTarget); + if (test != NULL) { + if (strcmp(test->value.element.name, name) == 0) { + return test; } } /* - test for named links - */ - linkName = mxmlElementGetAttr(linkNode,"name"); - if(test != NULL && linkName != NULL){ - if(strcmp(linkName,name) == 0){ - return test; + test for named links + */ + linkName = mxmlElementGetAttr(linkNode, "name"); + if (test != NULL && linkName != NULL) { + if (strcmp(linkName, name) == 0) { + return test; } } } return NULL; } + /*-----------------------------------------------------------------------*/ -NXstatus NXXopendata (NXhandle fid, CONSTCHAR *name){ +NXstatus NXXopendata(NXhandle fid, CONSTCHAR * name) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *dataNode = NULL; char error[1024]; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { /* - silently fix this - */ + silently fix this + */ xmlHandle->stackPointer--; - if(xmlHandle->stackPointer < 0){ + if (xmlHandle->stackPointer < 0) { xmlHandle->stackPointer = 0; } } - - dataNode = mxmlFindElement(xmlHandle->stack[xmlHandle->stackPointer].current, - xmlHandle->stack[xmlHandle->stackPointer].current, - name, - NULL, - NULL, - MXML_DESCEND_FIRST); - if(dataNode == NULL){ - dataNode = searchSDSLinks(xmlHandle,name); + + dataNode = + mxmlFindElement(xmlHandle->stack[xmlHandle->stackPointer].current, + xmlHandle->stack[xmlHandle->stackPointer].current, + name, NULL, NULL, MXML_DESCEND_FIRST); + if (dataNode == NULL) { + dataNode = searchSDSLinks(xmlHandle, name); } - if(!dataNode){ - snprintf(error,1023,"Failed to open dataset %s",name); - NXIReportError(NXpData,error); + if (!dataNode) { + snprintf(error, 1023, "Failed to open dataset %s", name); + NXIReportError(NXpData, error); return NX_ERROR; } xmlHandle->stackPointer++; @@ -494,34 +524,40 @@ NXstatus NXXopendata (NXhandle fid, CONSTCHAR *name){ xmlHandle->stack[xmlHandle->stackPointer].currentAttribute = 0; return NX_OK; } + /*----------------------------------------------------------------------*/ -NXstatus NXXclosedata (NXhandle fid){ +NXstatus NXXclosedata(NXhandle fid) +{ pXMLNexus xmlHandle = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - if(xmlHandle->stackPointer > 0){ + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + if (xmlHandle->stackPointer > 0) { xmlHandle->stackPointer--; } return NX_OK; } return NX_OK; } + /*----------------------------------------------------------------------*/ -static mxml_node_t *findData(mxml_node_t *node){ +static mxml_node_t *findData(mxml_node_t * node) +{ mxml_node_t *baby = node; - - while( (baby = mxmlWalkNext(baby,node,MXML_DESCEND_FIRST)) != NULL){ - if(baby->type == MXML_OPAQUE || baby->type == MXML_CUSTOM){ + + while ((baby = mxmlWalkNext(baby, node, MXML_DESCEND_FIRST)) != NULL) { + if (baby->type == MXML_OPAQUE || baby->type == MXML_CUSTOM) { return baby; } } return NULL; } + /*------------------------------------------------------------------------*/ -NXstatus NXXputdata (NXhandle fid, void *data){ +NXstatus NXXputdata(NXhandle fid, void *data) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *userData = NULL; mxml_node_t *current = NULL; @@ -529,94 +565,94 @@ NXstatus NXXputdata (NXhandle fid, void *data){ int i, length, type, rank, dim[NX_MAXRANK]; char *pPtr = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"No dataset open"); + if (!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "No dataset open"); return NX_ERROR; } - + current = xmlHandle->stack[xmlHandle->stackPointer].current; userData = findData(current); assert(userData != NULL); - if(userData->type == MXML_OPAQUE){ + if (userData->type == MXML_OPAQUE) { /* - Text data. We have to make sure that the text is \0 terminated. - Some language bindings do not ensure that this is the case. - */ - if(NXXgetinfo(fid,&rank, dim, &type) == NX_OK){ + Text data. We have to make sure that the text is \0 terminated. + Some language bindings do not ensure that this is the case. + */ + if (NXXgetinfo(fid, &rank, dim, &type) == NX_OK) { length = 1; - for(i=0; ivalue.custom.data; + dataset = (pNXDS) userData->value.custom.data; assert(dataset); length = getNXDatasetByteLength(dataset); - memcpy(dataset->u.ptr,data,length); + memcpy(dataset->u.ptr, data, length); } return NX_OK; } + /*------------------------------------------------------------------------*/ -NXstatus NXXgetdata (NXhandle fid, void *data){ +NXstatus NXXgetdata(NXhandle fid, void *data) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *userData = NULL; mxml_node_t *current = NULL; pNXDS dataset; int i, length, type, rank, dim[NX_MAXRANK]; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"No dataset open"); + if (!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "No dataset open"); return NX_ERROR; } - + current = xmlHandle->stack[xmlHandle->stackPointer].current; userData = findData(current); assert(userData != NULL); - if(userData->type == MXML_OPAQUE){ + if (userData->type == MXML_OPAQUE) { /* - text data - */ - if(NXXgetinfo(fid,&rank, dim, &type) == NX_OK){ + text data + */ + if (NXXgetinfo(fid, &rank, dim, &type) == NX_OK) { length = 1; - for(i=0; ivalue.opaque,length); + strncpy((char *) data, userData->value.opaque, length); } else { - strcpy((char *)data,nxitrim(userData->value.opaque)); + strcpy((char *) data, nxitrim(userData->value.opaque)); } } else { - dataset = (pNXDS)userData->value.custom.data; + dataset = (pNXDS) userData->value.custom.data; assert(dataset); length = getNXDatasetByteLength(dataset); - memcpy(data,dataset->u.ptr,length); + memcpy(data, dataset->u.ptr, length); } return NX_OK; } + /*------------------------------------------------------------------------*/ -NXstatus NXXgetinfo (NXhandle fid, int *rank, - int dimension[], int *iType){ +NXstatus NXXgetinfo(NXhandle fid, int *rank, int dimension[], int *iType) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *userData = NULL; mxml_node_t *current = NULL; @@ -624,255 +660,265 @@ NXstatus NXXgetinfo (NXhandle fid, int *rank, int myRank, i; const char *attr = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"No dataset open"); + if (!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "No dataset open"); return NX_ERROR; } - + current = xmlHandle->stack[xmlHandle->stackPointer].current; userData = findData(current); assert(userData != NULL); - if(userData->type == MXML_OPAQUE){ + if (userData->type == MXML_OPAQUE) { /* - text data - */ + text data + */ attr = mxmlElementGetAttr(current, TYPENAME); - if(attr == NULL){ + if (attr == NULL) { *rank = 1; *iType = NX_CHAR; - dimension[0]= strlen(userData->value.opaque); + dimension[0] = strlen(userData->value.opaque); } else { - analyzeDim(attr,rank,dimension,iType); + analyzeDim(attr, rank, dimension, iType); *iType = NX_CHAR; } - } else { - dataset = (pNXDS)userData->value.custom.data; + } else { + dataset = (pNXDS) userData->value.custom.data; assert(dataset); myRank = getNXDatasetRank(dataset); *rank = myRank; *iType = getNXDatasetType(dataset); - for(i = 0; i < myRank; i++){ - dimension[i] = getNXDatasetDim(dataset,i); + for (i = 0; i < myRank; i++) { + dimension[i] = getNXDatasetDim(dataset, i); } } return NX_OK; } + /*--------------------------------------------------------------------- clone the dataset and set the data pointer. This in order to use the addressing and type conversion implemented in nxdataset ----------------------------------------------------------------------*/ -static pNXDS makeSlabData(pNXDS dataset, void *data, int size[]){ +---------------------------------------------------------------------*/ +static pNXDS makeSlabData(pNXDS dataset, void *data, int size[]) +{ pNXDS slabData = NULL; int rank, i; - - slabData = (pNXDS)malloc(sizeof(NXDS)); - if(slabData == NULL){ + + slabData = (pNXDS) malloc(sizeof(NXDS)); + if (slabData == NULL) { return NULL; } rank = getNXDatasetRank(dataset); slabData->rank = rank; - slabData->dim = (int *)malloc(rank*sizeof(int)); - for(i = 0; i < rank; i++){ + slabData->dim = (int *) malloc(rank * sizeof(int)); + for (i = 0; i < rank; i++) { slabData->dim[i] = size[i]; } slabData->type = getNXDatasetType(dataset); slabData->u.ptr = data; slabData->magic = dataset->magic; return slabData; -} +} + /*-------------------------------------------------------------------- This goes by recursion ----------------------------------------------------------------------*/ static void putSlabData(pNXDS dataset, pNXDS slabData, int dim, - int start[], - int sourcePos[],int targetPos[]){ + int start[], int sourcePos[], int targetPos[]) +{ int i, rank, length; rank = getNXDatasetRank(slabData); - length = getNXDatasetDim(slabData,dim); - if(dim != rank-1){ - for(i = 0; i < length; i++){ - targetPos[dim] = start[dim] +i; + length = getNXDatasetDim(slabData, dim); + if (dim != rank - 1) { + for (i = 0; i < length; i++) { + targetPos[dim] = start[dim] + i; sourcePos[dim] = i; - putSlabData(dataset,slabData, dim+1,start, - sourcePos,targetPos); + putSlabData(dataset, slabData, dim + 1, start, sourcePos, targetPos); } } else { - for(i = 0; i < length; i++){ - targetPos[dim] = start[dim] +i; + for (i = 0; i < length; i++) { + targetPos[dim] = start[dim] + i; sourcePos[dim] = i; - putNXDatasetValue(dataset,targetPos, - getNXDatasetValue(slabData,sourcePos)); + putNXDatasetValue(dataset, targetPos, + getNXDatasetValue(slabData, sourcePos)); } } } + /*---------------------------------------------------------------------- This is in order to support unlimited dimensions along the first axis -----------------------------------------------------------------------*/ -static int checkAndExtendDataset(mxml_node_t *node, pNXDS dataset, - int start[], int size[]){ +static int checkAndExtendDataset(mxml_node_t * node, pNXDS dataset, + int start[], int size[]) +{ int dim0, byteLength; void *oldData = NULL; char *typestring = NULL; dim0 = start[0] + size[0]; - if(dim0 > dataset->dim[0]){ + if (dim0 > dataset->dim[0]) { byteLength = getNXDatasetByteLength(dataset); oldData = dataset->u.ptr; dataset->dim[0] = dim0; dataset->u.ptr = malloc(getNXDatasetByteLength(dataset)); - if(dataset->u.ptr == NULL){ + if (dataset->u.ptr == NULL) { return 0; } - memset(dataset->u.ptr,0,getNXDatasetByteLength(dataset)); - memcpy(dataset->u.ptr,oldData,byteLength); + memset(dataset->u.ptr, 0, getNXDatasetByteLength(dataset)); + memcpy(dataset->u.ptr, oldData, byteLength); free(oldData); - typestring = buildTypeString(dataset->type,dataset->rank,dataset->dim); - if(typestring != NULL){ - mxmlElementSetAttr(node,TYPENAME,typestring); + typestring = + buildTypeString(dataset->type, dataset->rank, dataset->dim); + if (typestring != NULL) { + mxmlElementSetAttr(node, TYPENAME, typestring); free(typestring); } else { - NXIReportError(NXpData,"Failed to allocate typestring"); + NXIReportError(NXpData, "Failed to allocate typestring"); return 0; } } return 1; } + /*----------------------------------------------------------------------*/ -NXstatus NXXputslab (NXhandle fid, void *data, - int iStart[], int iSize[]){ - +NXstatus NXXputslab(NXhandle fid, void *data, int iStart[], int iSize[]) +{ + pXMLNexus xmlHandle = NULL; mxml_node_t *userData = NULL; mxml_node_t *current = NULL; pNXDS dataset, slabData; int sourcePos[NX_MAXRANK], targetPos[NX_MAXRANK], status; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"No dataset open"); + if (!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "No dataset open"); return NX_ERROR; } - + current = xmlHandle->stack[xmlHandle->stackPointer].current; userData = findData(current); assert(userData != NULL); - if(userData->type == MXML_OPAQUE){ - NXIReportError(NXpData,"This API does not support slabs on text data"); + if (userData->type == MXML_OPAQUE) { + NXIReportError(NXpData, + "This API does not support slabs on text data"); return NX_ERROR; } - dataset = (pNXDS)userData->value.custom.data; + dataset = (pNXDS) userData->value.custom.data; assert(dataset); - status = checkAndExtendDataset(current,dataset,iStart,iSize); - if(status == 0){ - NXIReportError(NXpData,"Out of memory extending dataset"); + status = checkAndExtendDataset(current, dataset, iStart, iSize); + if (status == 0) { + NXIReportError(NXpData, "Out of memory extending dataset"); return NX_ERROR; } slabData = makeSlabData(dataset, data, iSize); - if(slabData == NULL){ - NXIReportError(NXpData,"Failed to allocate slab data"); + if (slabData == NULL) { + NXIReportError(NXpData, "Failed to allocate slab data"); return NX_ERROR; } - - putSlabData(dataset,slabData,0,iStart,sourcePos,targetPos); + + putSlabData(dataset, slabData, 0, iStart, sourcePos, targetPos); free(slabData->dim); free(slabData); - + return NX_OK; } + /*-------------------------------------------------------------------- This goes by recursion ----------------------------------------------------------------------*/ static void getSlabData(pNXDS dataset, pNXDS slabData, int dim, - int start[], - int sourcePos[],int targetPos[]){ + int start[], int sourcePos[], int targetPos[]) +{ int i, rank, length; rank = getNXDatasetRank(slabData); - length = getNXDatasetDim(slabData,dim); - if(dim != rank-1){ - for(i = 0; i < length; i++){ - sourcePos[dim] = start[dim] +i; + length = getNXDatasetDim(slabData, dim); + if (dim != rank - 1) { + for (i = 0; i < length; i++) { + sourcePos[dim] = start[dim] + i; targetPos[dim] = i; - getSlabData(dataset,slabData, dim+1,start, - sourcePos,targetPos); + getSlabData(dataset, slabData, dim + 1, start, sourcePos, targetPos); } } else { - for(i = 0; i < length; i++){ - sourcePos[dim] = start[dim] +i; + for (i = 0; i < length; i++) { + sourcePos[dim] = start[dim] + i; targetPos[dim] = i; - putNXDatasetValue(slabData,targetPos, - getNXDatasetValue(dataset,sourcePos)); + putNXDatasetValue(slabData, targetPos, + getNXDatasetValue(dataset, sourcePos)); } } } + /*----------------------------------------------------------------------*/ -NXstatus NXXgetslab (NXhandle fid, void *data, - int iStart[], int iSize[]){ +NXstatus NXXgetslab(NXhandle fid, void *data, int iStart[], int iSize[]) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *userData = NULL; mxml_node_t *current = NULL; pNXDS dataset, slabData; int sourcePos[NX_MAXRANK], targetPos[NX_MAXRANK]; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"No dataset open"); + if (!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "No dataset open"); return NX_ERROR; } - + current = xmlHandle->stack[xmlHandle->stackPointer].current; userData = findData(current); assert(userData != NULL); - if(userData->type == MXML_OPAQUE){ - NXIReportError(NXpData,"This API does not support slabs on text data"); + if (userData->type == MXML_OPAQUE) { + NXIReportError(NXpData, + "This API does not support slabs on text data"); return NX_ERROR; } - dataset = (pNXDS)userData->value.custom.data; + dataset = (pNXDS) userData->value.custom.data; assert(dataset); slabData = makeSlabData(dataset, data, iSize); - if(slabData == NULL){ - NXIReportError(NXpData,"Failed to allocate slab data"); + if (slabData == NULL) { + NXIReportError(NXpData, "Failed to allocate slab data"); return NX_ERROR; } - getSlabData(dataset,slabData,0,iStart,sourcePos,targetPos); + getSlabData(dataset, slabData, 0, iStart, sourcePos, targetPos); free(slabData->dim); free(slabData); - + return NX_OK; } + /*----------------------------------------------------------------------*/ -static NXstatus NXXsetnumberformat(NXhandle fid, - int type, char *format){ +static NXstatus NXXsetnumberformat(NXhandle fid, int type, char *format) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *current = NULL; mxml_node_t *userData = NULL; pNXDS dataset; - - xmlHandle = (pXMLNexus)fid; + + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { current = xmlHandle->stack[xmlHandle->stackPointer].current; userData = findData(current); assert(userData != NULL); - if(userData->type == MXML_OPAQUE){ + if (userData->type == MXML_OPAQUE) { return NX_OK; } - dataset = (pNXDS)userData->value.custom.data; + dataset = (pNXDS) userData->value.custom.data; assert(dataset); - if(dataset->format != NULL){ + if (dataset->format != NULL) { free(dataset->format); } dataset->format = strdup(format); @@ -881,8 +927,10 @@ static NXstatus NXXsetnumberformat(NXhandle fid, } return NX_OK; } + /*============================ Attributes ============================*/ -static char *formatAttributeData(void *data, int datalen, int iType){ +static char *formatAttributeData(void *data, int datalen, int iType) +{ int intData = 0; long iValue = -99999; double dValue = -1e38; @@ -890,104 +938,109 @@ static char *formatAttributeData(void *data, int datalen, int iType){ char *number; - if(iType == NX_CHAR){ + if (iType == NX_CHAR) { /* data may not be NULL terminated */ - number = (char*)malloc((datalen+1) * sizeof(char)); + number = (char *) malloc((datalen + 1) * sizeof(char)); memcpy(number, data, datalen * sizeof(char)); number[datalen] = '\0'; return number; } - number = (char *)malloc(132*sizeof(char)); - if(!number){ - NXIReportError(NXpData,"Failed to allocate attribute number buffer"); + number = (char *) malloc(132 * sizeof(char)); + if (!number) { + NXIReportError(NXpData, "Failed to allocate attribute number buffer"); return NULL; } - - if(datalen > 1){ + + if (datalen > 1) { return NULL; } type[0] = '\0'; - switch(iType){ + switch (iType) { case NX_INT32: - iValue = ((int *)data)[0]; + iValue = ((int *) data)[0]; intData = 1; - strcpy(type,"NX_INT32:"); + strcpy(type, "NX_INT32:"); break; case NX_UINT32: - iValue = ((unsigned int *)data)[0]; + iValue = ((unsigned int *) data)[0]; intData = 1; - strcpy(type,"NX_UINT32:"); + strcpy(type, "NX_UINT32:"); break; case NX_INT16: - iValue = ((short *)data)[0]; + iValue = ((short *) data)[0]; intData = 1; - strcpy(type,"NX_INT16:"); + strcpy(type, "NX_INT16:"); break; case NX_UINT16: - iValue = ((unsigned short *)data)[0]; + iValue = ((unsigned short *) data)[0]; intData = 1; - strcpy(type,"NX_UINT16:"); + strcpy(type, "NX_UINT16:"); break; case NX_INT8: - iValue = (int)((char *)data)[0]; + iValue = (int) ((char *) data)[0]; intData = 1; - strcpy(type,"NX_INT8:"); + strcpy(type, "NX_INT8:"); break; case NX_UINT8: intData = 1; - iValue = (int)((unsigned char *)data)[0]; - strcpy(type,"NX_UINT8:"); + iValue = (int) ((unsigned char *) data)[0]; + strcpy(type, "NX_UINT8:"); break; case NX_FLOAT32: - dValue = ((float *)data)[0]; - strcpy(type,"NX_FLOAT32:"); + dValue = ((float *) data)[0]; + strcpy(type, "NX_FLOAT32:"); intData = 0; break; case NX_FLOAT64: - dValue = ((double *)data)[0]; - strcpy(type,"NX_FLOAT64:"); + dValue = ((double *) data)[0]; + strcpy(type, "NX_FLOAT64:"); intData = 0; break; } - if(intData){ - snprintf(number,79,"%s%ld",type,iValue); + if (intData) { + snprintf(number, 79, "%s%ld", type, iValue); } else { - snprintf(number,79,"%s%f",type,dValue); + snprintf(number, 79, "%s%f", type, dValue); } return number; } + /*---------------------------------------------------------------------*/ -NXstatus NXXputattr (NXhandle fid, CONSTCHAR *name, void *data, - int datalen, int iType){ +NXstatus NXXputattr(NXhandle fid, CONSTCHAR * name, void *data, + int datalen, int iType) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *current = NULL; char *numberData = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); current = xmlHandle->stack[xmlHandle->stackPointer].current; - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - if(strcmp(name,TYPENAME) == 0){ - NXIReportError(NXpData,"type is a reserved attribute name, rejected"); - return NX_ERROR; + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + if (strcmp(name, TYPENAME) == 0) { + NXIReportError(NXpData, + "type is a reserved attribute name, rejected"); + return NX_ERROR; } } - numberData = formatAttributeData(data,datalen,iType); - if(numberData == NULL){ - NXIReportError(NXpData,"This API does not support non number arrays"); + numberData = formatAttributeData(data, datalen, iType); + if (numberData == NULL) { + NXIReportError(NXpData, "This API does not support non number arrays"); return NX_ERROR; } else { - mxmlElementSetAttr(current,name,numberData); + mxmlElementSetAttr(current, name, numberData); free(numberData); } return NX_OK; } + /*--------------------------------------------------------------------------*/ -NXstatus NXXgetattr (NXhandle fid, char *name, - void *data, int* datalen, int* iType){ +NXstatus NXXgetattr(NXhandle fid, char *name, + void *data, int *datalen, int *iType) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *current = NULL; const char *attribute = NULL; @@ -996,85 +1049,87 @@ NXstatus NXXgetattr (NXhandle fid, char *name, int iValue, nx_type; float fValue; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); current = xmlHandle->stack[xmlHandle->stackPointer].current; - attribute = mxmlElementGetAttr(current,name); - if(!attribute){ - snprintf(error,1023,"Attribute %s not found", name); - NXIReportError(NXpData,error); + attribute = mxmlElementGetAttr(current, name); + if (!attribute) { + snprintf(error, 1023, "Attribute %s not found", name); + NXIReportError(NXpData, error); return NX_ERROR; } - nx_type = translateTypeCode((char *)attribute); - if(nx_type < 0) { + nx_type = translateTypeCode((char *) attribute); + if (nx_type < 0) { /* - no type code == text attribute - */ + no type code == text attribute + */ nx_type = NX_CHAR; } else { /* - We need to find the number after the type code. However, there is - the complication of the datatype type attribute ... - */ - if(strcmp(name,TYPENAME) == 0){ + We need to find the number after the type code. However, there is + the complication of the datatype type attribute ... + */ + if (strcmp(name, TYPENAME) == 0) { nx_type = NX_CHAR; } else { - attData = strchr(attribute,(int)':'); - if(attData == NULL){ - NXIReportError(NXpData,"ERROR: bad attribute string, : missing"); - return NX_ERROR; + attData = strchr(attribute, (int) ':'); + if (attData == NULL) { + NXIReportError(NXpData, "ERROR: bad attribute string, : missing"); + return NX_ERROR; } attData++; } } *iType = nx_type; - switch(nx_type){ + switch (nx_type) { case NX_CHAR: - strncpy((char *)data, attribute, *datalen); + strncpy((char *) data, attribute, *datalen); *datalen = strlen(attribute); *iType = NX_CHAR; break; case NX_INT32: - ((int *)data)[0] = atoi(attData); + ((int *) data)[0] = atoi(attData); *datalen = 1; break; case NX_UINT32: - ((unsigned int *)data)[0] = atoi(attData); + ((unsigned int *) data)[0] = atoi(attData); *datalen = 1; break; case NX_INT16: - ((short *)data)[0] = atoi(attData); + ((short *) data)[0] = atoi(attData); *datalen = 1; break; case NX_UINT16: - ((unsigned short *)data)[0] = atoi(attData); + ((unsigned short *) data)[0] = atoi(attData); *datalen = 1; break; case NX_INT8: - ((char *)data)[0] = atoi(attData); + ((char *) data)[0] = atoi(attData); *datalen = 1; break; case NX_UINT8: - ((unsigned char *)data)[0] = atoi(attData); + ((unsigned char *) data)[0] = atoi(attData); *datalen = 1; break; case NX_FLOAT32: - ((float *)data)[0] = atof(attData); + ((float *) data)[0] = atof(attData); *datalen = 1; break; case NX_FLOAT64: - ((double *)data)[0] = atof(attData); + ((double *) data)[0] = atof(attData); *datalen = 1; break; } return NX_OK; } + /*====================== search functions =================================*/ -NXstatus NXXgetnextentry (NXhandle fid,NXname name, - NXname nxclass, int *datatype){ +NXstatus NXXgetnextentry(NXhandle fid, NXname name, + NXname nxclass, int *datatype) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *next = NULL, *userData; int stackPtr; @@ -1083,88 +1138,90 @@ NXstatus NXXgetnextentry (NXhandle fid,NXname name, char pBueffel[256]; const char *linkName = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { /* - be nice to user: silently fix this problem - */ + be nice to user: silently fix this problem + */ NXXclosedata(fid); } stackPtr = xmlHandle->stackPointer; - if(xmlHandle->stack[stackPtr].currentChild == NULL){ + if (xmlHandle->stack[stackPtr].currentChild == NULL) { /* - initialization of search - */ - xmlHandle->stack[stackPtr].currentChild = - xmlHandle->stack[stackPtr].current->child; + initialization of search + */ + xmlHandle->stack[stackPtr].currentChild = + xmlHandle->stack[stackPtr].current->child; } else { /* - proceed - */ - xmlHandle->stack[stackPtr].currentChild = - xmlHandle->stack[stackPtr].currentChild->next; + proceed + */ + xmlHandle->stack[stackPtr].currentChild = + xmlHandle->stack[stackPtr].currentChild->next; } next = xmlHandle->stack[stackPtr].currentChild; - if(next == NULL){ + if (next == NULL) { return NX_EOD; } - if(strcmp(next->value.element.name,"NAPIlink") == 0){ - target = mxmlElementGetAttr(next,"target"); - linkName = mxmlElementGetAttr(next,"name"); - if(target == NULL){ - NXIReportError(NXpData,"Corrupted file, NAPIlink without target"); + if (strcmp(next->value.element.name, "NAPIlink") == 0) { + target = mxmlElementGetAttr(next, "target"); + linkName = mxmlElementGetAttr(next, "name"); + if (target == NULL) { + NXIReportError(NXpData, "Corrupted file, NAPIlink without target"); return NX_ERROR; } - next = getLinkTarget(xmlHandle,target); - if(next == NULL){ - NXIReportError(NXpData,"Corrupted file, broken link"); + next = getLinkTarget(xmlHandle, target); + if (next == NULL) { + NXIReportError(NXpData, "Corrupted file, broken link"); return NX_ERROR; } } - if(isDataNode(next)){ - strcpy(name,next->value.element.name); - strcpy(nxclass,"SDS"); + if (isDataNode(next)) { + strcpy(name, next->value.element.name); + strcpy(nxclass, "SDS"); userData = findData(next); - if(userData == NULL){ - snprintf(pBueffel,255,"Corrupted file, userData for %s not found", - name); - NXIReportError(NXpData,pBueffel); + if (userData == NULL) { + snprintf(pBueffel, 255, "Corrupted file, userData for %s not found", + name); + NXIReportError(NXpData, pBueffel); return NX_ERROR; } - if(userData->type == MXML_OPAQUE){ + if (userData->type == MXML_OPAQUE) { *datatype = NX_CHAR; } else { - dataset = (pNXDS)userData->value.custom.data; + dataset = (pNXDS) userData->value.custom.data; assert(dataset); *datatype = getNXDatasetType(dataset); } } else { - strcpy(nxclass,next->value.element.name); - attname = mxmlElementGetAttr(next,"name"); - strcpy(name,attname); + strcpy(nxclass, next->value.element.name); + attname = mxmlElementGetAttr(next, "name"); + strcpy(name, attname); } /* - this is for named links - */ - if(linkName != NULL){ - strcpy(name,linkName); + this is for named links + */ + if (linkName != NULL) { + strcpy(name, linkName); } return NX_OK; } + /*----------------------------------------------------------------------*/ -extern NXstatus NXXinitgroupdir(NXhandle fid){ +extern NXstatus NXXinitgroupdir(NXhandle fid) +{ pXMLNexus xmlHandle = NULL; int stackPtr; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"Cannot search datasets"); + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "Cannot search datasets"); return NX_ERROR; } @@ -1172,52 +1229,53 @@ extern NXstatus NXXinitgroupdir(NXhandle fid){ xmlHandle->stack[stackPtr].currentChild = NULL; return NX_OK; } + /*-------------------------------------------------------------------------*/ -NXstatus NXXgetnextattr (NXhandle fid, NXname pName, - int *iLength, int *iType){ +NXstatus NXXgetnextattr(NXhandle fid, NXname pName, + int *iLength, int *iType) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *current = NULL; int stackPtr, currentAtt, nx_type; - char *attVal; + char *attVal; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); stackPtr = xmlHandle->stackPointer; current = xmlHandle->stack[stackPtr].current; currentAtt = xmlHandle->stack[stackPtr].currentAttribute; - if(currentAtt >= - current->value.element.num_attrs ){ + if (currentAtt >= current->value.element.num_attrs) { xmlHandle->stack[stackPtr].currentAttribute = 0; return NX_EOD; } /* - hide group name attribute - */ - if(strcmp(current->value.element.attrs[currentAtt].name,"name") == 0 - && !isDataNode(current) ){ + hide group name attribute + */ + if (strcmp(current->value.element.attrs[currentAtt].name, "name") == 0 + && !isDataNode(current)) { xmlHandle->stack[stackPtr].currentAttribute++; - return NXXgetnextattr(fid,pName,iLength,iType); + return NXXgetnextattr(fid, pName, iLength, iType); } /* - hide type attribute - */ - if(strcmp(current->value.element.attrs[currentAtt].name,TYPENAME) == 0 - && isDataNode(current)){ + hide type attribute + */ + if (strcmp(current->value.element.attrs[currentAtt].name, TYPENAME) == 0 + && isDataNode(current)) { xmlHandle->stack[stackPtr].currentAttribute++; - return NXXgetnextattr(fid,pName,iLength,iType); + return NXXgetnextattr(fid, pName, iLength, iType); } - strcpy(pName,current->value.element.attrs[currentAtt].name); + strcpy(pName, current->value.element.attrs[currentAtt].name); attVal = current->value.element.attrs[currentAtt].value; - nx_type = translateTypeCode((char *)attVal); - if(nx_type < 0 || strcmp(pName,TYPENAME) == 0){ + nx_type = translateTypeCode((char *) attVal); + if (nx_type < 0 || strcmp(pName, TYPENAME) == 0) { /* - no type == NX_CHAR - */ + no type == NX_CHAR + */ *iLength = strlen(attVal); *iType = NX_CHAR; } else { @@ -1228,58 +1286,64 @@ NXstatus NXXgetnextattr (NXhandle fid, NXname pName, xmlHandle->stack[stackPtr].currentAttribute++; return NX_OK; } + /*-------------------------------------------------------------------------*/ -extern NXstatus NXXinitattrdir(NXhandle fid){ +extern NXstatus NXXinitattrdir(NXhandle fid) +{ pXMLNexus xmlHandle = NULL; int stackPtr; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); stackPtr = xmlHandle->stackPointer; xmlHandle->stack[stackPtr].currentAttribute = 0; return NX_OK; } + /*-------------------------------------------------------------------------*/ -NXstatus NXXgetgroupinfo (NXhandle fid, int *iN, - NXname pName, NXname pClass){ +NXstatus NXXgetgroupinfo(NXhandle fid, int *iN, + NXname pName, NXname pClass) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *child = NULL; mxml_node_t *current = NULL; const char *nameAtt = NULL; int childCount; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"No group open"); + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "No group open"); return NX_ERROR; - } + } current = xmlHandle->stack[xmlHandle->stackPointer].current; - nameAtt = mxmlElementGetAttr(current,"name"); - if(nameAtt != NULL){ - strcpy(pName,nameAtt); + nameAtt = mxmlElementGetAttr(current, "name"); + if (nameAtt != NULL) { + strcpy(pName, nameAtt); } - strcpy(pClass,current->value.element.name); + strcpy(pClass, current->value.element.name); childCount = 0; child = current->child; - while(child != NULL){ + while (child != NULL) { childCount++; child = child->next; } *iN = childCount; return NX_OK; } + /*----------------------------------------------------------------------*/ -NXstatus NXXgetattrinfo (NXhandle fid, int *iN){ +NXstatus NXXgetattrinfo(NXhandle fid, int *iN) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *current = NULL; int stackPtr, currentAtt; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); stackPtr = xmlHandle->stackPointer; @@ -1287,31 +1351,33 @@ NXstatus NXXgetattrinfo (NXhandle fid, int *iN){ current = xmlHandle->stack[stackPtr].current; /* - hide type and group name attributes - */ - if(!isDataNode(current)) { - *iN = current->value.element.num_attrs -1; + hide type and group name attributes + */ + if (!isDataNode(current)) { + *iN = current->value.element.num_attrs - 1; return NX_OK; } - if(mxmlElementGetAttr(current,TYPENAME) != NULL){ - *iN = current->value.element.num_attrs -1; + if (mxmlElementGetAttr(current, TYPENAME) != NULL) { + *iN = current->value.element.num_attrs - 1; } else { *iN = current->value.element.num_attrs; } return NX_OK; } + /*================= Linking functions =================================*/ -static int countPathChars(mxml_node_t *path[], int stackPtr){ +static int countPathChars(mxml_node_t * path[], int stackPtr) +{ int count = 1; const char *name = NULL; - while(stackPtr >= 0) { - if(isDataNode(path[stackPtr])){ + while (stackPtr >= 0) { + if (isDataNode(path[stackPtr])) { count += strlen(path[stackPtr]->value.element.name); } else { - name = mxmlElementGetAttr(path[stackPtr],"name"); - if(name != NULL){ - count += strlen(name); + name = mxmlElementGetAttr(path[stackPtr], "name"); + if (name != NULL) { + count += strlen(name); } } stackPtr--; @@ -1319,56 +1385,60 @@ static int countPathChars(mxml_node_t *path[], int stackPtr){ } return count; } + /*-------------------------------------------------------------------*/ -static char *buildPathString(mxml_node_t *path[], int stackPtr){ +static char *buildPathString(mxml_node_t * path[], int stackPtr) +{ int count = 0; const char *name = NULL; char *pathString = NULL; - count = countPathChars(path,stackPtr); - pathString = (char *)malloc((count+10)*sizeof(char)); - if(pathString == NULL){ + count = countPathChars(path, stackPtr); + pathString = (char *) malloc((count + 10) * sizeof(char)); + if (pathString == NULL) { return NULL; } - memset(pathString,0,(count+10)*sizeof(char)); + memset(pathString, 0, (count + 10) * sizeof(char)); - while(stackPtr >= 0) { - if(isDataNode(path[stackPtr])){ - strcat(pathString,"/"); - strcat(pathString,path[stackPtr]->value.element.name); + while (stackPtr >= 0) { + if (isDataNode(path[stackPtr])) { + strcat(pathString, "/"); + strcat(pathString, path[stackPtr]->value.element.name); } else { - name = mxmlElementGetAttr(path[stackPtr],"name"); - if(name != NULL){ - strcat(pathString,"/"); - strcat(pathString,name); + name = mxmlElementGetAttr(path[stackPtr], "name"); + if (name != NULL) { + strcat(pathString, "/"); + strcat(pathString, name); } } stackPtr--; } return pathString; } + /*--------------------------------------------------------------------*/ -static char *findLinkPath(mxml_node_t *node){ +static char *findLinkPath(mxml_node_t * node) +{ mxml_node_t **path = NULL; int stackPtr; mxml_node_t *current = NULL; char *pathString = NULL, *result = NULL; int count; - path = (mxml_node_t **)malloc(NXMAXSTACK*sizeof(mxml_node_t *)); - if(path == NULL){ - NXIReportError(NXpData,"ERROR: out of memory follwoing link path"); + path = (mxml_node_t **) malloc(NXMAXSTACK * sizeof(mxml_node_t *)); + if (path == NULL) { + NXIReportError(NXpData, "ERROR: out of memory follwoing link path"); return NULL; } - memset(path,0,NXMAXSTACK*sizeof(mxml_node_t *)); + memset(path, 0, NXMAXSTACK * sizeof(mxml_node_t *)); /* - first path: walk up the tree untill NXroot is found - */ + first path: walk up the tree untill NXroot is found + */ current = node; stackPtr = 0; - while(current != NULL && - strcmp(current->value.element.name,"NXroot") != 0){ + while (current != NULL && + strcmp(current->value.element.name, "NXroot") != 0) { path[stackPtr] = current; stackPtr++; current = current->parent; @@ -1376,175 +1446,185 @@ static char *findLinkPath(mxml_node_t *node){ stackPtr--; /* - path now contains the nodes to the root node in reverse order. - From this build the path string - */ - result = buildPathString(path,stackPtr); + path now contains the nodes to the root node in reverse order. + From this build the path string + */ + result = buildPathString(path, stackPtr); free(path); return result; } + /*--------------------------------------------------------------------*/ -NXstatus NXXgetdataID (NXhandle fid, NXlink* sRes){ +NXstatus NXXgetdataID(NXhandle fid, NXlink * sRes) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *current = NULL; char *linkPath = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - return NX_ERROR; - } - current = xmlHandle->stack[xmlHandle->stackPointer].current; - - linkPath = findLinkPath(current); - if(!linkPath){ - NXIReportError(NXpData,"Failed to allocate link path string"); + if (!isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { return NX_ERROR; } - strncpy(sRes->targetPath,linkPath,1023); + current = xmlHandle->stack[xmlHandle->stackPointer].current; + + linkPath = findLinkPath(current); + if (!linkPath) { + NXIReportError(NXpData, "Failed to allocate link path string"); + return NX_ERROR; + } + strncpy(sRes->targetPath, linkPath, 1023); free(linkPath); return NX_OK; } + /*--------------------------------------------------------------------*/ -NXstatus NXXgetgroupID (NXhandle fid, NXlink* sRes){ +NXstatus NXXgetgroupID(NXhandle fid, NXlink * sRes) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *current = NULL; char *linkPath = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"No group open"); + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "No group open"); return NX_ERROR; - } + } current = xmlHandle->stack[xmlHandle->stackPointer].current; - if(xmlHandle->stackPointer == 0){ + if (xmlHandle->stackPointer == 0) { return NX_ERROR; } linkPath = findLinkPath(current); - if(!linkPath){ - NXIReportError(NXpData,"Failed to allocate link path string"); + if (!linkPath) { + NXIReportError(NXpData, "Failed to allocate link path string"); return NX_ERROR; } - strncpy(sRes->targetPath,linkPath,1023); + strncpy(sRes->targetPath, linkPath, 1023); free(linkPath); return NX_OK; } /*-----------------------------------------------------------------------*/ - NXstatus NXXprintlink (NXhandle fid, NXlink* sLink) - { - pXMLNexus xmlHandle = NULL; - xmlHandle = (pXMLNexus)fid; - assert(xmlHandle); +NXstatus NXXprintlink(NXhandle fid, NXlink * sLink) +{ + pXMLNexus xmlHandle = NULL; + xmlHandle = (pXMLNexus) fid; + assert(xmlHandle); + + printf("XML link: target=\"%s\"\n", sLink->targetPath); + return NX_OK; +} - printf("XML link: target=\"%s\"\n", sLink->targetPath); - return NX_OK; - } - /*-----------------------------------------------------------------------*/ -NXstatus NXXmakelink (NXhandle fid, NXlink* sLink){ +NXstatus NXXmakelink(NXhandle fid, NXlink * sLink) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *current = NULL, *linkNode = NULL; mxml_node_t *linkedNode = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"No group to link to open"); - return NX_ERROR; - } - current = xmlHandle->stack[xmlHandle->stackPointer].current; - linkNode = mxmlNewElement(current,"NAPIlink"); - if(!linkNode){ - NXIReportError(NXpData,"Failed to allocate new link element"); + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "No group to link to open"); return NX_ERROR; } - mxmlElementSetAttr(linkNode,"target",sLink->targetPath); - linkedNode = getLinkTarget(xmlHandle,sLink->targetPath); - if(linkedNode != NULL){ - mxmlElementSetAttr(linkedNode,"target",sLink->targetPath); + current = xmlHandle->stack[xmlHandle->stackPointer].current; + linkNode = mxmlNewElement(current, "NAPIlink"); + if (!linkNode) { + NXIReportError(NXpData, "Failed to allocate new link element"); + return NX_ERROR; + } + mxmlElementSetAttr(linkNode, "target", sLink->targetPath); + linkedNode = getLinkTarget(xmlHandle, sLink->targetPath); + if (linkedNode != NULL) { + mxmlElementSetAttr(linkedNode, "target", sLink->targetPath); } return NX_OK; } - + /*-----------------------------------------------------------------------*/ -NXstatus NXXmakenamedlink (NXhandle fid, CONSTCHAR *name, NXlink* sLink){ +NXstatus NXXmakenamedlink(NXhandle fid, CONSTCHAR * name, NXlink * sLink) +{ pXMLNexus xmlHandle = NULL; mxml_node_t *current = NULL, *linkNode = NULL; mxml_node_t *linkedNode = NULL; - xmlHandle = (pXMLNexus)fid; + xmlHandle = (pXMLNexus) fid; assert(xmlHandle); - if(isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)){ - NXIReportError(NXpData,"No group to link to open"); - return NX_ERROR; - } - current = xmlHandle->stack[xmlHandle->stackPointer].current; - linkNode = mxmlNewElement(current,"NAPIlink"); - if(!linkNode){ - NXIReportError(NXpData,"Failed to allocate new link element"); + if (isDataNode(xmlHandle->stack[xmlHandle->stackPointer].current)) { + NXIReportError(NXpData, "No group to link to open"); return NX_ERROR; } - mxmlElementSetAttr(linkNode,"target",sLink->targetPath); - mxmlElementSetAttr(linkNode,"name",name); - linkedNode = getLinkTarget(xmlHandle,sLink->targetPath); - if(linkedNode != NULL){ - mxmlElementSetAttr(linkedNode,"target",sLink->targetPath); + current = xmlHandle->stack[xmlHandle->stackPointer].current; + linkNode = mxmlNewElement(current, "NAPIlink"); + if (!linkNode) { + NXIReportError(NXpData, "Failed to allocate new link element"); + return NX_ERROR; + } + mxmlElementSetAttr(linkNode, "target", sLink->targetPath); + mxmlElementSetAttr(linkNode, "name", name); + linkedNode = getLinkTarget(xmlHandle, sLink->targetPath); + if (linkedNode != NULL) { + mxmlElementSetAttr(linkedNode, "target", sLink->targetPath); } return NX_OK; } + /*----------------------------------------------------------------------*/ -NXstatus NXXsameID (NXhandle fileid, NXlink* pFirstID, - NXlink* pSecondID){ - if(strcmp(pFirstID->targetPath,pSecondID->targetPath) == 0) { +NXstatus NXXsameID(NXhandle fileid, NXlink * pFirstID, NXlink * pSecondID) +{ + if (strcmp(pFirstID->targetPath, pSecondID->targetPath) == 0) { return NX_OK; } else { return NX_ERROR; } } + /*--------------------------------------------------------------------*/ -int NXXcompress(NXhandle fid, int comp){ - NXIReportError(NXpData,"NXcompress is deprecated, IGNORED"); +int NXXcompress(NXhandle fid, int comp) +{ + NXIReportError(NXpData, "NXcompress is deprecated, IGNORED"); return NX_OK; } -/*----------------------------------------------------------------------*/ -void NXXassignFunctions(pNexusFunction fHandle){ - fHandle->nxclose=NXXclose; - fHandle->nxflush=NXXflush; - fHandle->nxmakegroup=NXXmakegroup; - fHandle->nxopengroup=NXXopengroup; - fHandle->nxclosegroup=NXXclosegroup; - fHandle->nxmakedata=NXXmakedata; - fHandle->nxcompmakedata=NXXcompmakedata; - fHandle->nxcompress=NXXcompress; - fHandle->nxopendata=NXXopendata; - fHandle->nxclosedata=NXXclosedata; - fHandle->nxputdata=NXXputdata; - fHandle->nxputattr=NXXputattr; - fHandle->nxputslab=NXXputslab; - fHandle->nxgetdataID=NXXgetdataID; - fHandle->nxmakelink=NXXmakelink; - fHandle->nxmakenamedlink=NXXmakenamedlink; - fHandle->nxgetdata=NXXgetdata; - fHandle->nxgetinfo=NXXgetinfo; - fHandle->nxgetnextentry=NXXgetnextentry; - fHandle->nxgetslab=NXXgetslab; - fHandle->nxgetnextattr=NXXgetnextattr; - fHandle->nxgetattr=NXXgetattr; - fHandle->nxgetattrinfo=NXXgetattrinfo; - fHandle->nxgetgroupID=NXXgetgroupID; - fHandle->nxgetgroupinfo=NXXgetgroupinfo; - fHandle->nxsameID=NXXsameID; - fHandle->nxinitgroupdir=NXXinitgroupdir; - fHandle->nxinitattrdir=NXXinitattrdir; - fHandle->nxsetnumberformat=NXXsetnumberformat; - fHandle->nxprintlink=NXXprintlink; -} +/*----------------------------------------------------------------------*/ +void NXXassignFunctions(pNexusFunction fHandle) +{ + fHandle->nxclose = NXXclose; + fHandle->nxflush = NXXflush; + fHandle->nxmakegroup = NXXmakegroup; + fHandle->nxopengroup = NXXopengroup; + fHandle->nxclosegroup = NXXclosegroup; + fHandle->nxmakedata = NXXmakedata; + fHandle->nxcompmakedata = NXXcompmakedata; + fHandle->nxcompress = NXXcompress; + fHandle->nxopendata = NXXopendata; + fHandle->nxclosedata = NXXclosedata; + fHandle->nxputdata = NXXputdata; + fHandle->nxputattr = NXXputattr; + fHandle->nxputslab = NXXputslab; + fHandle->nxgetdataID = NXXgetdataID; + fHandle->nxmakelink = NXXmakelink; + fHandle->nxmakenamedlink = NXXmakenamedlink; + fHandle->nxgetdata = NXXgetdata; + fHandle->nxgetinfo = NXXgetinfo; + fHandle->nxgetnextentry = NXXgetnextentry; + fHandle->nxgetslab = NXXgetslab; + fHandle->nxgetnextattr = NXXgetnextattr; + fHandle->nxgetattr = NXXgetattr; + fHandle->nxgetattrinfo = NXXgetattrinfo; + fHandle->nxgetgroupID = NXXgetgroupID; + fHandle->nxgetgroupinfo = NXXgetgroupinfo; + fHandle->nxsameID = NXXsameID; + fHandle->nxinitgroupdir = NXXinitgroupdir; + fHandle->nxinitattrdir = NXXinitattrdir; + fHandle->nxsetnumberformat = NXXsetnumberformat; + fHandle->nxprintlink = NXXprintlink; +} diff --git a/nxxml.h b/nxxml.h index fc27345d..c7b8c1b7 100644 --- a/nxxml.h +++ b/nxxml.h @@ -22,57 +22,51 @@ #ifndef NEXUSXML #define NEXUSXML -extern NXstatus NXXopen(CONSTCHAR *filename, - NXaccess access_method, - NXhandle* pHandle); -extern NXstatus NXXclose(NXhandle* pHandle); -extern NXstatus NXXflush(NXhandle* pHandle); +extern NXstatus NXXopen(CONSTCHAR * filename, + NXaccess access_method, NXhandle * pHandle); +extern NXstatus NXXclose(NXhandle * pHandle); +extern NXstatus NXXflush(NXhandle * pHandle); -NXstatus NXXmakegroup (NXhandle fid, CONSTCHAR *name, - CONSTCHAR *nxclass); -NXstatus NXXopengroup (NXhandle fid, CONSTCHAR *name, - CONSTCHAR *nxclass); -NXstatus NXXclosegroup (NXhandle fid); +NXstatus NXXmakegroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass); +NXstatus NXXopengroup(NXhandle fid, CONSTCHAR * name, CONSTCHAR * nxclass); +NXstatus NXXclosegroup(NXhandle fid); -NXstatus NXXcompmakedata (NXhandle fid, CONSTCHAR *name, - int datatype, - int rank, - int dimensions[], - int compress_type, int chunk_size[]); -NXstatus NXXmakedata (NXhandle fid, - CONSTCHAR *name, int datatype, - int rank, int dimensions[]); -NXstatus NXXopendata (NXhandle fid, CONSTCHAR *name); -NXstatus NXXclosedata (NXhandle fid); -NXstatus NXXputdata (NXhandle fid, void *data); -NXstatus NXXgetdata (NXhandle fid, void *data); -NXstatus NXXgetinfo (NXhandle fid, int *rank, - int dimension[], int *iType); -NXstatus NXXputslab (NXhandle fid, void *data, - int iStart[], int iSize[]); -NXstatus NXXgetslab (NXhandle fid, void *data, - int iStart[], int iSize[]); -NXstatus NXXputattr (NXhandle fid, CONSTCHAR *name, void *data, - int datalen, int iType); -NXstatus NXXgetattr (NXhandle fid, char *name, - void *data, int* datalen, int* iType); +NXstatus NXXcompmakedata(NXhandle fid, CONSTCHAR * name, + int datatype, + int rank, + int dimensions[], + int compress_type, int chunk_size[]); +NXstatus NXXmakedata(NXhandle fid, + CONSTCHAR * name, int datatype, + int rank, int dimensions[]); +NXstatus NXXopendata(NXhandle fid, CONSTCHAR * name); +NXstatus NXXclosedata(NXhandle fid); +NXstatus NXXputdata(NXhandle fid, void *data); +NXstatus NXXgetdata(NXhandle fid, void *data); +NXstatus NXXgetinfo(NXhandle fid, int *rank, int dimension[], int *iType); +NXstatus NXXputslab(NXhandle fid, void *data, int iStart[], int iSize[]); +NXstatus NXXgetslab(NXhandle fid, void *data, int iStart[], int iSize[]); +NXstatus NXXputattr(NXhandle fid, CONSTCHAR * name, void *data, + int datalen, int iType); +NXstatus NXXgetattr(NXhandle fid, char *name, + void *data, int *datalen, int *iType); -NXstatus NXXgetnextentry (NXhandle fid,NXname name, - NXname nxclass, int *datatype); -extern NXstatus NXXgetnextattr(NXhandle handle, - NXname pName, int *iLength, int *iType); -extern NXstatus NXXinitgroupdir(NXhandle handle); -extern NXstatus NXXinitattrdir(NXhandle handle); -extern NXstatus NXXgetattrinfo (NXhandle fid, int *iN); -extern NXstatus NXXgetgroupinfo (NXhandle fid, int *iN, - NXname pName, NXname pClass); +NXstatus NXXgetnextentry(NXhandle fid, NXname name, + NXname nxclass, int *datatype); +extern NXstatus NXXgetnextattr(NXhandle handle, + NXname pName, int *iLength, int *iType); +extern NXstatus NXXinitgroupdir(NXhandle handle); +extern NXstatus NXXinitattrdir(NXhandle handle); +extern NXstatus NXXgetattrinfo(NXhandle fid, int *iN); +extern NXstatus NXXgetgroupinfo(NXhandle fid, int *iN, + NXname pName, NXname pClass); -extern NXstatus NXXgetdataID (NXhandle fid, NXlink* sRes); -extern NXstatus NXXgetgroupID (NXhandle fid, NXlink* sRes); -extern NXstatus NXXmakelink (NXhandle fid, NXlink* sLink); -extern NXstatus NXXprintlink (NXhandle fid, NXlink* sLink); -extern NXstatus NXXsameID (NXhandle fileid, - NXlink* pFirstID, NXlink* pSecondID); +extern NXstatus NXXgetdataID(NXhandle fid, NXlink * sRes); +extern NXstatus NXXgetgroupID(NXhandle fid, NXlink * sRes); +extern NXstatus NXXmakelink(NXhandle fid, NXlink * sLink); +extern NXstatus NXXprintlink(NXhandle fid, NXlink * sLink); +extern NXstatus NXXsameID(NXhandle fileid, + NXlink * pFirstID, NXlink * pSecondID); void NXXassignFunctions(pNexusFunction fHandle); #endif diff --git a/o2t.c b/o2t.c index 6359936c..0ed68801 100644 --- a/o2t.c +++ b/o2t.c @@ -49,282 +49,270 @@ #include "fupa.h" #include "o2t.h" - typedef struct __SicsO2T { - pObjectDescriptor pDes; - pIDrivable pDrivInt; - pDummy pOmega; - pDummy pTheta; - } SicsO2T; - -/*---------------------------------------------------------------------------*/ - static void *GetO2TInterface(void *pData, int iID) - { - SicsO2T *self = NULL; - - self = (SicsO2T *)pData; - assert(self); - if(iID == DRIVEID) - { - return self->pDrivInt; - } - return NULL; - } -/*---------------------------------------------------------------------------*/ - static int O2THalt(void *pData) - { - pSicsO2T self = NULL; - pIDrivable pDrivInt = NULL; - - self = (pSicsO2T)pData; - assert(self); - - pDrivInt = self->pOmega->pDescriptor->GetInterface(self->pOmega,DRIVEID); - if(pDrivInt) - { - pDrivInt->Halt(self->pOmega); - } - pDrivInt = self->pTheta->pDescriptor->GetInterface(self->pTheta,DRIVEID); - if(pDrivInt) - { - pDrivInt->Halt(self->pTheta); - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int O2TCheckLimits(void *pData, float fVal, char *pError, - int iErrLen) - { - pSicsO2T self = NULL; - int iRet; - pIDrivable pDrivInt = NULL; - - self = (pSicsO2T)pData; - assert(self); - - pDrivInt = self->pOmega->pDescriptor->GetInterface(self->pOmega,DRIVEID); - if(pDrivInt) - { - iRet = pDrivInt->CheckLimits(self->pOmega, fVal/2., - pError, iErrLen); - if(!iRet) - { - return iRet; - } - } - pDrivInt = self->pTheta->pDescriptor->GetInterface(self->pTheta,DRIVEID); - if(pDrivInt) - { - return pDrivInt->CheckLimits(self->pTheta, fVal, - pError, iErrLen); - } - return 0; - } -/*-------------------------------------------------------------------------*/ - static long O2TSetValue(void *pData, SConnection *pCon, float fVal) - { - pSicsO2T self = NULL; - pIDrivable pDrivInt = NULL; - int iRet; - - self = (pSicsO2T)pData; - assert(self); - - pDrivInt = self->pOmega->pDescriptor->GetInterface(self->pOmega,DRIVEID); - if(pDrivInt) - { - iRet = pDrivInt->SetValue(self->pOmega,pCon, fVal/2.); - if(iRet != OKOK) - { - return iRet; - } - } - pDrivInt = self->pTheta->pDescriptor->GetInterface(self->pTheta,DRIVEID); - if(pDrivInt) - { - iRet = pDrivInt->SetValue(self->pTheta,pCon, fVal); - return iRet; - } - return 0; - } -/*-------------------------------------------------------------------------*/ - static int O2TCheckStatus(void *pData, SConnection *pCon) - { - pSicsO2T self = NULL; - pIDrivable pDrivInt = NULL; - int iRet; - - self = (pSicsO2T)pData; - assert(self); - - pDrivInt = self->pOmega->pDescriptor->GetInterface(self->pOmega,DRIVEID); - if(pDrivInt) - { - iRet = pDrivInt->CheckStatus(self->pOmega,pCon); - if((iRet != OKOK) && (iRet != HWIdle) ) - { - return iRet; - } - } - pDrivInt = self->pTheta->pDescriptor->GetInterface(self->pTheta,DRIVEID); - if(pDrivInt) - { - iRet = pDrivInt->CheckStatus(self->pTheta,pCon); - return iRet; - } - return 0; - } -/*-------------------------------------------------------------------------*/ - static float O2TGetValue(void *pData, SConnection *pCon) - { - pSicsO2T self = NULL; - pIDrivable pDrivInt = NULL; - - self = (pSicsO2T)pData; - assert(self); - - pDrivInt = self->pTheta->pDescriptor->GetInterface(self->pTheta,DRIVEID); - if(pDrivInt) - { - return pDrivInt->GetValue(self->pTheta,pCon); - } - return -9999.; - } -/*-------------------------------------------------------------------------*/ - pSicsO2T MakeO2T(char *omega, char *theta, SicsInterp *pSics) - { - pSicsO2T self = NULL; - CommandList *pCom = NULL; - pIDrivable pDriv = NULL; - pDummy pDum = NULL; - - /* allocate memory */ - self = (pSicsO2T)malloc(sizeof(SicsO2T)); - if(!self) - { - return NULL; - } - self->pDes = CreateDescriptor("Omega2Theta"); - if(!self->pDes) - { - free(self); - return NULL; - } - - /* get and check drivabels */ - pCom = FindCommand(pSics,omega); - if(pCom != NULL) - { - pDum = pCom->pData; - } else - { - pDum = NULL; - } - if(GetDrivableInterface(pDum) != NULL){ - self->pOmega = pDum; - } - pCom = FindCommand(pSics,theta); - if(pCom != NULL) - { - pDum = pCom->pData; - } - else - { - pDum = NULL; - } - if(GetDrivableInterface(pDum) != NULL){ - self->pTheta = pDum; - } - if( (self->pOmega == NULL) || (self->pTheta == NULL) ) - { - DeleteDescriptor(self->pDes); - free(self); - return NULL; - } - - /* initialize Descriptor */ - self->pDes->GetInterface = GetO2TInterface; - - - /* initialise drivable interface */ - self->pDrivInt = CreateDrivableInterface(); - if(!self->pDrivInt) - { - DeleteDescriptor(self->pDes); - free(self); - return NULL; - } - self->pDrivInt->Halt = O2THalt; - self->pDrivInt->CheckLimits = O2TCheckLimits; - self->pDrivInt->SetValue = O2TSetValue; - self->pDrivInt->CheckStatus = O2TCheckStatus; - self->pDrivInt->GetValue = O2TGetValue; - - return self; - } -/*---------------------------------------------------------------------------*/ - void DeleteO2T(void *pData) - { - pSicsO2T self = NULL; - - self = (pSicsO2T)pData; - assert(self); +typedef struct __SicsO2T { + pObjectDescriptor pDes; + pIDrivable pDrivInt; + pDummy pOmega; + pDummy pTheta; +} SicsO2T; - if(self->pDrivInt) - { - free(self->pDrivInt); - } - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - free(self); - } -/*-------------------------------------------------------------------------*/ - static int DummyO2T(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - SCWrite(pCon,"WARNING: O2T does not understand any commnds",eWarning); - return 1; +/*---------------------------------------------------------------------------*/ +static void *GetO2TInterface(void *pData, int iID) +{ + SicsO2T *self = NULL; + + self = (SicsO2T *) pData; + assert(self); + if (iID == DRIVEID) { + return self->pDrivInt; } + return NULL; +} + +/*---------------------------------------------------------------------------*/ +static int O2THalt(void *pData) +{ + pSicsO2T self = NULL; + pIDrivable pDrivInt = NULL; + + self = (pSicsO2T) pData; + assert(self); + + pDrivInt = + self->pOmega->pDescriptor->GetInterface(self->pOmega, DRIVEID); + if (pDrivInt) { + pDrivInt->Halt(self->pOmega); + } + pDrivInt = + self->pTheta->pDescriptor->GetInterface(self->pTheta, DRIVEID); + if (pDrivInt) { + pDrivInt->Halt(self->pTheta); + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int O2TCheckLimits(void *pData, float fVal, char *pError, + int iErrLen) +{ + pSicsO2T self = NULL; + int iRet; + pIDrivable pDrivInt = NULL; + + self = (pSicsO2T) pData; + assert(self); + + pDrivInt = + self->pOmega->pDescriptor->GetInterface(self->pOmega, DRIVEID); + if (pDrivInt) { + iRet = pDrivInt->CheckLimits(self->pOmega, fVal / 2., pError, iErrLen); + if (!iRet) { + return iRet; + } + } + pDrivInt = + self->pTheta->pDescriptor->GetInterface(self->pTheta, DRIVEID); + if (pDrivInt) { + return pDrivInt->CheckLimits(self->pTheta, fVal, pError, iErrLen); + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +static long O2TSetValue(void *pData, SConnection * pCon, float fVal) +{ + pSicsO2T self = NULL; + pIDrivable pDrivInt = NULL; + int iRet; + + self = (pSicsO2T) pData; + assert(self); + + pDrivInt = + self->pOmega->pDescriptor->GetInterface(self->pOmega, DRIVEID); + if (pDrivInt) { + iRet = pDrivInt->SetValue(self->pOmega, pCon, fVal / 2.); + if (iRet != OKOK) { + return iRet; + } + } + pDrivInt = + self->pTheta->pDescriptor->GetInterface(self->pTheta, DRIVEID); + if (pDrivInt) { + iRet = pDrivInt->SetValue(self->pTheta, pCon, fVal); + return iRet; + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +static int O2TCheckStatus(void *pData, SConnection * pCon) +{ + pSicsO2T self = NULL; + pIDrivable pDrivInt = NULL; + int iRet; + + self = (pSicsO2T) pData; + assert(self); + + pDrivInt = + self->pOmega->pDescriptor->GetInterface(self->pOmega, DRIVEID); + if (pDrivInt) { + iRet = pDrivInt->CheckStatus(self->pOmega, pCon); + if ((iRet != OKOK) && (iRet != HWIdle)) { + return iRet; + } + } + pDrivInt = + self->pTheta->pDescriptor->GetInterface(self->pTheta, DRIVEID); + if (pDrivInt) { + iRet = pDrivInt->CheckStatus(self->pTheta, pCon); + return iRet; + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +static float O2TGetValue(void *pData, SConnection * pCon) +{ + pSicsO2T self = NULL; + pIDrivable pDrivInt = NULL; + + self = (pSicsO2T) pData; + assert(self); + + pDrivInt = + self->pTheta->pDescriptor->GetInterface(self->pTheta, DRIVEID); + if (pDrivInt) { + return pDrivInt->GetValue(self->pTheta, pCon); + } + return -9999.; +} + +/*-------------------------------------------------------------------------*/ +pSicsO2T MakeO2T(char *omega, char *theta, SicsInterp * pSics) +{ + pSicsO2T self = NULL; + CommandList *pCom = NULL; + pIDrivable pDriv = NULL; + pDummy pDum = NULL; + + /* allocate memory */ + self = (pSicsO2T) malloc(sizeof(SicsO2T)); + if (!self) { + return NULL; + } + self->pDes = CreateDescriptor("Omega2Theta"); + if (!self->pDes) { + free(self); + return NULL; + } + + /* get and check drivabels */ + pCom = FindCommand(pSics, omega); + if (pCom != NULL) { + pDum = pCom->pData; + } else { + pDum = NULL; + } + if (GetDrivableInterface(pDum) != NULL) { + self->pOmega = pDum; + } + pCom = FindCommand(pSics, theta); + if (pCom != NULL) { + pDum = pCom->pData; + } else { + pDum = NULL; + } + if (GetDrivableInterface(pDum) != NULL) { + self->pTheta = pDum; + } + if ((self->pOmega == NULL) || (self->pTheta == NULL)) { + DeleteDescriptor(self->pDes); + free(self); + return NULL; + } + + /* initialize Descriptor */ + self->pDes->GetInterface = GetO2TInterface; + + + /* initialise drivable interface */ + self->pDrivInt = CreateDrivableInterface(); + if (!self->pDrivInt) { + DeleteDescriptor(self->pDes); + free(self); + return NULL; + } + self->pDrivInt->Halt = O2THalt; + self->pDrivInt->CheckLimits = O2TCheckLimits; + self->pDrivInt->SetValue = O2TSetValue; + self->pDrivInt->CheckStatus = O2TCheckStatus; + self->pDrivInt->GetValue = O2TGetValue; + + return self; +} + +/*---------------------------------------------------------------------------*/ +void DeleteO2T(void *pData) +{ + pSicsO2T self = NULL; + + self = (pSicsO2T) pData; + assert(self); + + if (self->pDrivInt) { + free(self->pDrivInt); + } + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + free(self); +} + +/*-------------------------------------------------------------------------*/ +static int DummyO2T(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + SCWrite(pCon, "WARNING: O2T does not understand any commnds", eWarning); + return 1; +} + /*--------------------------------------------------------------------------- initialisation command. Syntax: CreateO2T name omegamotor thetamotor -*/ - int CreateO2T(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pSicsO2T self = NULL; - char pBueffel[256]; - int iRet; - - assert(pCon); - assert(pSics); - - if(argc < 4) - { - SCWrite(pCon,"ERROR: Insufficienet number of argumnets to CreateO2T", - eError); - return 0; - } - - /* make O2T */ - self = MakeO2T(argv[2],argv[3],pSics); - if(!self) - { - sprintf(pBueffel,"ERROR: no Memory or %s %s are no valid motor names", - argv[2], argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* install command */ - iRet = AddCommand(pSics,argv[1],DummyO2T,DeleteO2T,self); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } +*/ +int CreateO2T(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSicsO2T self = NULL; + char pBueffel[256]; + int iRet; + assert(pCon); + assert(pSics); + + if (argc < 4) { + SCWrite(pCon, "ERROR: Insufficienet number of argumnets to CreateO2T", + eError); + return 0; + } + + /* make O2T */ + self = MakeO2T(argv[2], argv[3], pSics); + if (!self) { + sprintf(pBueffel, "ERROR: no Memory or %s %s are no valid motor names", + argv[2], argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* install command */ + iRet = AddCommand(pSics, argv[1], DummyO2T, DeleteO2T, self); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} diff --git a/o2t.h b/o2t.h index 9d695939..1c8b834f 100644 --- a/o2t.h +++ b/o2t.h @@ -10,12 +10,12 @@ #ifndef SICSO2T #define SICSO2T - typedef struct __SicsO2T *pSicsO2T; - - pSicsO2T MakeO2T(char *omega, char *theta, SicsInterp *pSics); - void DeleteO2T(void *pData); - - int CreateO2T(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +typedef struct __SicsO2T *pSicsO2T; + +pSicsO2T MakeO2T(char *omega, char *theta, SicsInterp * pSics); +void DeleteO2T(void *pData); + +int CreateO2T(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + #endif diff --git a/obdes.c b/obdes.c index 127e56bc..63f48e06 100644 --- a/obdes.c +++ b/obdes.c @@ -47,160 +47,165 @@ #include "hipadaba.h" /*-------------------------------------------------------------------------*/ - static void *DefaultGetInterface(void *pData,int iID) - { +static void *DefaultGetInterface(void *pData, int iID) +{ + return NULL; +} + +/*-------------------------------------------------------------------------*/ +static int DefaultSave(void *self, char *name, FILE * fd) +{ + return 1; +} + +/*--------------------------------------------------------------------------*/ +pObjectDescriptor CreateDescriptor(char *name) +{ + pObjectDescriptor pRes = NULL; + + pRes = (pObjectDescriptor) malloc(sizeof(ObjectDescriptor)); + if (!pRes) { return NULL; } -/*-------------------------------------------------------------------------*/ - static int DefaultSave(void *self, char *name,FILE *fd) - { - return 1; - } -/*--------------------------------------------------------------------------*/ - pObjectDescriptor CreateDescriptor(char *name) - { - pObjectDescriptor pRes = NULL; - - pRes = (pObjectDescriptor)malloc(sizeof(ObjectDescriptor)); - if(!pRes) - { - return NULL; - } - pRes->name = strdup(name); - pRes->pKeys = NULL; - pRes->parNode = NULL; - pRes->SaveStatus = DefaultSave; - pRes->GetInterface = DefaultGetInterface; - return pRes; - } + pRes->name = strdup(name); + pRes->pKeys = NULL; + pRes->parNode = NULL; + pRes->SaveStatus = DefaultSave; + pRes->GetInterface = DefaultGetInterface; + return pRes; +} + /*---------------------------------------------------------------------------*/ - void DeleteDescriptor(pObjectDescriptor self) - { - assert(self); - if(self->name) free(self->name); - if(self->pKeys) IFDeleteOptions(self->pKeys); - /* - * delate a parameter node only when not linked elsewhere - */ - if(self->parNode != NULL){ - if(self->parNode->mama == NULL){ - DeleteHipadabaNode(self->parNode,NULL); - } +void DeleteDescriptor(pObjectDescriptor self) +{ + assert(self); + if (self->name) + free(self->name); + if (self->pKeys) + IFDeleteOptions(self->pKeys); + /* + * delate a parameter node only when not linked elsewhere + */ + if (self->parNode != NULL) { + if (self->parNode->mama == NULL) { + DeleteHipadabaNode(self->parNode, NULL); } - free(self); - } + free(self); + +} + /*-------------------------------------------------------------------------*/ - pDummy CreateDummy(char *name) - { - pDummy pRes = NULL; - - pRes = (pDummy)malloc(sizeof(Dummy)); - if(!pRes) - { - SICSLogWrite("Out of Memory in CreateDummy",eInternal); - return NULL; - } - - pRes->pDescriptor = CreateDescriptor(name); - if(!pRes->pDescriptor) - { - free(pRes); - SICSLogWrite("Out of Memory in CreateDummy",eInternal); - return NULL; - } - return pRes; +pDummy CreateDummy(char *name) +{ + pDummy pRes = NULL; + + pRes = (pDummy) malloc(sizeof(Dummy)); + if (!pRes) { + SICSLogWrite("Out of Memory in CreateDummy", eInternal); + return NULL; } + + pRes->pDescriptor = CreateDescriptor(name); + if (!pRes->pDescriptor) { + free(pRes); + SICSLogWrite("Out of Memory in CreateDummy", eInternal); + return NULL; + } + return pRes; +} + /*--------------------------------------------------------------------------*/ - void KillDummy(void *pData) - { - pDummy pVictim; - - if(!pData)return; - - pVictim = (pDummy)pData; - if(pVictim->pDescriptor) - { - DeleteDescriptor(pVictim->pDescriptor); - } - free(pData); +void KillDummy(void *pData) +{ + pDummy pVictim; + + if (!pData) + return; + + pVictim = (pDummy) pData; + if (pVictim->pDescriptor) { + DeleteDescriptor(pVictim->pDescriptor); } + free(pData); +} + /*-------------------------------------------------------------------------*/ - int iHasType(void *pData, char *Type) - { - pDummy pTest; - - assert(pData); - pTest = (pDummy)pData; - if(!pTest->pDescriptor) - { - return 0; - } - if(strcmp(pTest->pDescriptor->name,Type) == 0) - { - return 1; - } - return 0; +int iHasType(void *pData, char *Type) +{ + pDummy pTest; + + assert(pData); + pTest = (pDummy) pData; + if (!pTest->pDescriptor) { + return 0; } + if (strcmp(pTest->pDescriptor->name, Type) == 0) { + return 1; + } + return 0; +} + /*------------------------------------------------------------------------*/ - pObjectDescriptor FindDescriptor(void *pData) - { - pDummy pDum = NULL; - - assert(pData); - pDum = (pDummy)pData; - return pDum->pDescriptor; - } +pObjectDescriptor FindDescriptor(void *pData) +{ + pDummy pDum = NULL; + + assert(pData); + pDum = (pDummy) pData; + return pDum->pDescriptor; +} + /*--------------------------------------------------------------------------*/ - void SetDescriptorKey(pObjectDescriptor self, char *keyName, char *eltValue) - { - if(NULL!=self) - { - self->pKeys = IFSetOption(self->pKeys,keyName,eltValue); - } +void SetDescriptorKey(pObjectDescriptor self, char *keyName, + char *eltValue) +{ + if (NULL != self) { + self->pKeys = IFSetOption(self->pKeys, keyName, eltValue); } +} + /*--------------------------------------------------------------------------*/ - void SetDescriptorGroup(pObjectDescriptor self, char *group) - { - if(NULL==self) - { - return; - } - self->pKeys = IFSetOption(self->pKeys,"group",group); +void SetDescriptorGroup(pObjectDescriptor self, char *group) +{ + if (NULL == self) { + return; } + self->pKeys = IFSetOption(self->pKeys, "group", group); +} + /*--------------------------------------------------------------------------*/ - void SetDescriptorDescription(pObjectDescriptor self, char *description) - { - if(NULL==self) - { - return; - } - self->pKeys = IFSetOption(self->pKeys,"description", description); +void SetDescriptorDescription(pObjectDescriptor self, char *description) +{ + if (NULL == self) { + return; } + self->pKeys = IFSetOption(self->pKeys, "description", description); +} + /*--------------------------------------------------------------------------*/ - char * GetDescriptorKey(pObjectDescriptor self, char *keyName) - { - if(NULL==self) - { - return NULL; - } - return IFindOption(self->pKeys,keyName); +char *GetDescriptorKey(pObjectDescriptor self, char *keyName) +{ + if (NULL == self) { + return NULL; } + return IFindOption(self->pKeys, keyName); +} + /*--------------------------------------------------------------------------*/ - char * GetDescriptorGroup(pObjectDescriptor self) - { - if(NULL==self) - { - return NULL; - } - return IFindOption(self->pKeys,"group"); +char *GetDescriptorGroup(pObjectDescriptor self) +{ + if (NULL == self) { + return NULL; } + return IFindOption(self->pKeys, "group"); +} + /*--------------------------------------------------------------------------*/ - char *GetDescriptorDescription(pObjectDescriptor self) - { - if(NULL==self) - { - return NULL; - } - return IFindOption(self->pKeys,"description"); +char *GetDescriptorDescription(pObjectDescriptor self) +{ + if (NULL == self) { + return NULL; } + return IFindOption(self->pKeys, "description"); +} diff --git a/obdes.h b/obdes.h index 2fb9f1e8..d1477dc0 100644 --- a/obdes.h +++ b/obdes.h @@ -25,19 +25,19 @@ #include #include - typedef struct { - char *name; - int (*SaveStatus)(void *self, char *name,FILE *fd); - void *(*GetInterface)(void *self, int iInterfaceID); - IPair *pKeys; - pHdb parNode; - } ObjectDescriptor, *pObjectDescriptor; +typedef struct { + char *name; + int (*SaveStatus) (void *self, char *name, FILE * fd); + void *(*GetInterface) (void *self, int iInterfaceID); + IPair *pKeys; + pHdb parNode; +} ObjectDescriptor, *pObjectDescriptor; /*---------------------------------------------------------------------------*/ - pObjectDescriptor CreateDescriptor(char *name); - void DeleteDescriptor(pObjectDescriptor self); - pObjectDescriptor FindDescriptor(void *pData); - +pObjectDescriptor CreateDescriptor(char *name); +void DeleteDescriptor(pObjectDescriptor self); +pObjectDescriptor FindDescriptor(void *pData); + /*============================================================================ Objects which do not carry data need a dummy descriptor. Otherwise drive or scan will protection fault when trying to drive something @@ -45,16 +45,16 @@ */ typedef struct { - pObjectDescriptor pDescriptor; - }Dummy, *pDummy; - + pObjectDescriptor pDescriptor; +} Dummy, *pDummy; - pDummy CreateDummy(char *name); - void KillDummy(void *pData); - int iHasType(void *pData, char *Type); - -#endif +pDummy CreateDummy(char *name); +void KillDummy(void *pData); + +int iHasType(void *pData, char *Type); + +#endif #line 386 "interface.w" @@ -62,9 +62,9 @@ typedef struct { /* Additional properties used by the ANSTO site to provide more information * about each object instance, especially devices. */ - void SetDescriptorKey(pObjectDescriptor self, char *keyName, char *value); - void SetDescriptorGroup(pObjectDescriptor self, char *group); - void SetDescriptorDescription(pObjectDescriptor self, char *description); - char * GetDescriptorKey(pObjectDescriptor self, char *keyName); - char * GetDescriptorGroup(pObjectDescriptor self); - char * GetDescriptorDescription(pObjectDescriptor self); +void SetDescriptorKey(pObjectDescriptor self, char *keyName, char *value); +void SetDescriptorGroup(pObjectDescriptor self, char *group); +void SetDescriptorDescription(pObjectDescriptor self, char *description); +char *GetDescriptorKey(pObjectDescriptor self, char *keyName); +char *GetDescriptorGroup(pObjectDescriptor self); +char *GetDescriptorDescription(pObjectDescriptor self); diff --git a/obpar.c b/obpar.c index ee1564fd..20ece3e1 100644 --- a/obpar.c +++ b/obpar.c @@ -47,169 +47,162 @@ /*------------------------------------------------------------------------*/ - int ObParLength(ObPar *self) - { - int i = 0; +int ObParLength(ObPar * self) +{ + int i = 0; - assert(self); - - while(self[i].iCode != -100) - { - i++; - } - return i; + assert(self); + + while (self[i].iCode != -100) { + i++; } + return i; +} + /*-------------------------------------------------------------------------*/ - ObPar *ObParCreate(int iArrayLong) - { - ObPar *pRes = NULL; - int i; - - assert(iArrayLong > 0); - - /* allocate memory */ - pRes = (ObPar *)malloc((iArrayLong + 1)*sizeof(ObPar)); - if(!pRes) - { - return NULL; - } - - /* initialise all to 0 */ - for(i = 0; i < iArrayLong; i++) - { - pRes[i].name = NULL; - pRes[i].fVal = .0; - pRes[i].iCode = usSpy; - } - - /* have a sentinel at the end */ - pRes[iArrayLong].iCode = -100; - - return pRes; +ObPar *ObParCreate(int iArrayLong) +{ + ObPar *pRes = NULL; + int i; + + assert(iArrayLong > 0); + + /* allocate memory */ + pRes = (ObPar *) malloc((iArrayLong + 1) * sizeof(ObPar)); + if (!pRes) { + return NULL; } + + /* initialise all to 0 */ + for (i = 0; i < iArrayLong; i++) { + pRes[i].name = NULL; + pRes[i].fVal = .0; + pRes[i].iCode = usSpy; + } + + /* have a sentinel at the end */ + pRes[iArrayLong].iCode = -100; + + return pRes; +} + /*--------------------------------------------------------------------------*/ - void ObParDelete(ObPar *self) - { - int i; - int iLong; - - assert(self); - - /* free the names */ - iLong = ObParLength(self); - for(i = 0; i < iLong; i++) - { - if(self[i].name) - free(self[i].name); +void ObParDelete(ObPar * self) +{ + int i; + int iLong; + + assert(self); + + /* free the names */ + iLong = ObParLength(self); + for (i = 0; i < iLong; i++) { + if (self[i].name) + free(self[i].name); + } + + free(self); +} + +/*---------------------------------------------------------------------------*/ +ObPar *ObParFind(ObPar * self, char *name) +{ + int i; + + assert(self); + + for (i = 0; self[i].iCode != -100; i++) { + if (strcmp(name, self[i].name) == 0) { + return &self[i]; } - - free(self); } + + return NULL; +} + /*---------------------------------------------------------------------------*/ - ObPar *ObParFind(ObPar *self, char *name) - { - int i; - - assert(self); - - for(i = 0; self[i].iCode != -100; i++) - { - if(strcmp(name,self[i].name) == 0) - { - return &self[i]; - } - } - - return NULL; - } -/*---------------------------------------------------------------------------*/ - int ObParIndex(ObPar *self, char *name) - { - int i; - - assert(self); - - for(i = 0; self[i].iCode != -100; i++) - { - if(strcmp(name,self[i].name) == 0) - { - return i; - } - } - - return -1; - } -/*---------------------------------------------------------------------------*/ - int ObParInit(ObPar *self, int i, char *name, float fVal, int iCode) - { - - assert(self); - - /* check i */ - if( (i < 0) && ( i >= ObParLength(self) )) - { - return 0; - } - - if(self[i].name) - { - free(self[i].name); - } - self[i].name = strdup(name); - self[i].fVal = fVal; - self[i].iCode = iCode; - return 1; +int ObParIndex(ObPar * self, char *name) +{ + int i; + + assert(self); + + for (i = 0; self[i].iCode != -100; i++) { + if (strcmp(name, self[i].name) == 0) { + return i; + } } -/*------------------------------------------------------------------------*/ - int ObParSet(ObPar *self, char *obname, char *name, float fVal, - SConnection *pCon) - { - char pBueffel[512]; - ObPar *pPar = NULL; - Status eStat; - - assert(self); - - /* find the parameter */ - pPar = ObParFind(self,name); - if(pPar == NULL) - { - sprintf(pBueffel,"ERROR: %s.%s parameter not found", - obname,name); - SCWrite(pCon, pBueffel,eError); - return 0; - } - - /* are we running? */ - eStat = GetStatus(); - if(!((eStat == eEager) || (eStat == eBatch)) ) - { - sprintf(pBueffel,"ERROR: Cannot change parameter while running"); - SCWrite(pCon, pBueffel,eError); - return 0; - } - - /* check permission */ - if(!SCMatchRights(pCon,pPar->iCode)) - { - sprintf(pBueffel,"ERROR: Insufficient privilege to change %s.%s", - obname, name); - SCWrite(pCon, pBueffel,eError); - return 0; - } - - /* passed all tests: do It! */ - pPar->fVal = fVal; - return 1; - } + + return -1; +} + +/*---------------------------------------------------------------------------*/ +int ObParInit(ObPar * self, int i, char *name, float fVal, int iCode) +{ + + assert(self); + + /* check i */ + if ((i < 0) && (i >= ObParLength(self))) { + return 0; + } + + if (self[i].name) { + free(self[i].name); + } + self[i].name = strdup(name); + self[i].fVal = fVal; + self[i].iCode = iCode; + return 1; +} + +/*------------------------------------------------------------------------*/ +int ObParSet(ObPar * self, char *obname, char *name, float fVal, + SConnection * pCon) +{ + char pBueffel[512]; + ObPar *pPar = NULL; + Status eStat; + + assert(self); + + /* find the parameter */ + pPar = ObParFind(self, name); + if (pPar == NULL) { + sprintf(pBueffel, "ERROR: %s.%s parameter not found", obname, name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* are we running? */ + eStat = GetStatus(); + if (!((eStat == eEager) || (eStat == eBatch))) { + sprintf(pBueffel, "ERROR: Cannot change parameter while running"); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* check permission */ + if (!SCMatchRights(pCon, pPar->iCode)) { + sprintf(pBueffel, "ERROR: Insufficient privilege to change %s.%s", + obname, name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* passed all tests: do It! */ + pPar->fVal = fVal; + return 1; +} + /*------------------------------------------------------------------------*/ - float ObVal(ObPar *self, int i) - { - assert(self); - assert(i > -1); - assert( i < ObParLength(self)); - - return self[i].fVal; - } +float ObVal(ObPar * self, int i) +{ + assert(self); + assert(i > -1); + assert(i < ObParLength(self)); + + return self[i].fVal; +} diff --git a/obpar.h b/obpar.h index f0a7be55..e8b56950 100644 --- a/obpar.h +++ b/obpar.h @@ -21,53 +21,53 @@ ----------------------------------------------------------------------------*/ #ifndef SICSARPAR #define SICSARPAR - - typedef struct { - char *name; - float fVal; - int iCode; - } ObPar; + +typedef struct { + char *name; + float fVal; + int iCode; +} ObPar; /* quick access internally, self is the ObPar array, i is the parameter number, nice to have defines for some, better than handling ints - */ - float ObVal(ObPar *self, int i); + */ +float ObVal(ObPar * self, int i); - int ObParLength(ObPar *self); +int ObParLength(ObPar * self); /* - finds the length of an ObPar array - */ - - ObPar *ObParFind(ObPar *self, char *name); + finds the length of an ObPar array + */ + +ObPar *ObParFind(ObPar * self, char *name); /* finds a ObPar struct for a name, return NULL if none */ - int ObParIndex(ObPar *self, char *name); +int ObParIndex(ObPar * self, char *name); /* - finds an index for name in self. Returns -1 on failure - */ + finds an index for name in self. Returns -1 on failure + */ - int ObParInit(ObPar *self,int i, char *name, float fVal, int iCode); +int ObParInit(ObPar * self, int i, char *name, float fVal, int iCode); /* - sets a ObPar entry. self is a pointer to the array - */ - int ObParSet(ObPar *self, char *obname,char *name, float fVal, SConnection *pCon); + sets a ObPar entry. self is a pointer to the array + */ +int ObParSet(ObPar * self, char *obname, char *name, float fVal, + SConnection * pCon); /* checks if the connections permissions are alright and changes value if so. Returns 1 on success, 0 on failure. Prints errors directly to pCon. The parameter obmane is the name of the object the parameters belong to. Needed for error printing. name is the parameter name, fVal the new value. - */ - - void ObParDelete(ObPar *self); + */ + +void ObParDelete(ObPar * self); /* Deletes an ObPar array - */ - - ObPar *ObParCreate(int iArrayLong); - /* - creates an array with iArrayLong entries - */ -#endif + */ +ObPar *ObParCreate(int iArrayLong); + /* + creates an array with iArrayLong entries + */ +#endif diff --git a/ofac.c b/ofac.c index 53aedb63..c2227d82 100644 --- a/ofac.c +++ b/ofac.c @@ -133,366 +133,351 @@ #include "motorsec.h" #include "background.h" /*----------------------- Server options creation -------------------------*/ - static int IFServerOption(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - - assert(pSics); - assert(pCon); +static int IFServerOption(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + char pBueffel[512]; + + assert(pSics); + assert(pCon); + + /* check authorisation */ + if (!SCMatchRights(pCon, usMugger)) { + SCWrite(pCon, "Insufficient privilege to set options", eError); + return 0; + } + + /* test if sufficient arguments */ + if (argc < 3) { + sprintf(pBueffel, "Syntax: %s name value ", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* just do it */ + pSICSOptions = IFAddOption(pSICSOptions, argv[1], argv[2]); + return 1; +} - /* check authorisation */ - if(!SCMatchRights(pCon,usMugger)) - { - SCWrite(pCon,"Insufficient privilege to set options",eError); - return 0; - } - - /* test if sufficient arguments */ - if(argc < 3) - { - sprintf(pBueffel,"Syntax: %s name value ", argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* just do it */ - pSICSOptions = IFAddOption(pSICSOptions,argv[1],argv[2]); - return 1; - } /*----------------------- Password database update -------------------------*/ - static int PWSicsUser(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - TokenList *pList = NULL; - - assert(pSics); - assert(pCon); +static int PWSicsUser(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512]; + TokenList *pList = NULL; - /* check authorisation */ - if(SCGetRights(pCon) > usMugger) - { - SCWrite(pCon,"Insufficient privilege to set users",eError); - return 0; - } - - /* analyse commandlist */ - pList = SplitArguments(argc-1, &argv[1]); - if( (!pList) || (!pList->pNext) || (!pList->pNext->pNext) ) - { - sprintf(pBueffel,"Invalid Passwd Entry ::\n %s %s %s\n", argv[1], - argv[2], argv[3]); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return 0; - } - else - { - if(pList->pNext->pNext->Type != eInt) - { - SCWrite(pCon,"Need integer rights code",eError); - DeleteTokenList(pList); - return 0; - } - else - { - AddUser(pList->text, pList->pNext->text, - pList->pNext->pNext->iVal); - } - } - DeleteTokenList(pList); - return 1; - } -/*--------------------------------------------------------------------------*/ - static void InitIniCommands(SicsInterp *pInter,pTaskMan pTask) - { - pExeList pExe; - pEnvMon pEnv = NULL; - pSite site = NULL; - assert(pInter); - - pExe = CreateExeList(pTask); - pServ->pExecutor = pExe; - pEnv = CreateEnvMon(); - - assert(pExe); - assert(pEnv); - - /* permanent commands */ - AddCommand(pInter,"Sics_Exitus",SicsExit,NULL,NULL); - AddCommand(pInter,"FileEval",MacroFileEval,NULL,NULL); + assert(pSics); + assert(pCon); - AddCommand(pInter,"InternEval",InternalFileEval,NULL,NULL); - AddCommand(pInter,"ClientPut",ClientPut,NULL,NULL); - AddCommand(pInter,"GumPut",GumPut,NULL,NULL); - AddCommand(pInter,"broadcast",Broadcast,NULL,NULL); - AddCommand(pInter,"transact",TransactAction,NULL,NULL); - AddCommand(pInter,"fulltransact",TransactAction,NULL,NULL); - AddCommand(pInter,"sicsprompt", SicsPrompt,NULL,NULL); - AddCommand(pInter,"Publish",TclPublish,NULL,NULL); - AddCommand(pInter,"GetLog", LogCapture,NULL,NULL); - AddCommand(pInter,"config", ConfigCon,NULL,NULL); - AddCommand(pInter,"wait", UserWait,NULL,NULL); - AddCommand(pInter,"status", UserStatus,NULL,NULL); - AddCommand(pInter,"ResetServer",ResetStatus,NULL,NULL); - AddCommand(pInter,"Dir",ListObjects,NULL,NULL); - AddCommand(pInter,"SetInt", SetSICSInterrupt,NULL,NULL); - AddCommand(pInter,"GetInt",GetSICSInterrupt,NULL,NULL); - AddCommand(pInter,"SICSType",SICSType,NULL,NULL); - AddCommand(pInter,"SICSBounds",SICSBounds,NULL,NULL); - AddCommand(pInter,"SICSStatus",SICSStatus,NULL,NULL); - AddCommand(pInter,"sicstime",SICSTime,NULL,NULL); - AddCommand(pInter,"sicsdescriptor",SICSDescriptor,NULL,NULL); - AddCommand(pInter,"SetStatus",SetSICSStatus,NULL,NULL); - AddCommand(pInter,"db",SICSDebug,NULL,NULL); - AddCommand(pInter,"EVFactory",EVControlFactory,NULL,NULL); - AddCommand(pInter,"emon",EVWrapper,DeleteEnvMon,pEnv); - AddCommand(pInter,"commandlog",CommandLog,CommandLogClose,NULL); - AddCommand(pInter,"udpquieck",QuieckAction,KillQuieck,NULL); - AddCommand(pInter,"alias",MakeAlias,NULL,NULL); - AddCommand(pInter,"findalias",LocateAliasAction,NULL,NULL); - AddCommand(pInter,"sicscron",MakeCron,NULL,NULL); - AddCommand(pInter,"dolater",MakeCron,NULL,NULL); - AddCommand(pInter,"sicsdatafactory",SICSDataFactory,NULL,NULL); - AddCommand(pInter,"scriptcallback",CallbackScript,NULL,NULL); - AddCommand(pInter,"help",SicsHelp,KillHelp,NULL); - AddCommand(pInter,"list",SicsList,NULL,NULL); - AddCommand(pInter,"InstallHdb",InstallSICSHipadaba,NULL,NULL); - MakeProtocol(pInter); - InstallBackground(pInter); - - /* commands to do with the executor. Only StopExe carries the - DeleteFunction in order to avoid double deletion. All the - other commands operate on the same datastructure. - */ - AddCommand(pInter,"StopExe",StopCommand,DeleteExeList, pExe); - AddCommand(pInter,"ListExe",ListExe,NULL,pExe); - AddCommand(pInter,"sicsidle",SicsIdle,NULL,pExe); - AddCommand(pInter,"Success",Success,NULL,pExe); - AddCommand(pInter,"pause",PauseAction,NULL,pExe); - AddCommand(pInter,"continue",ContinueAction,NULL,pExe); - AddCommand(pInter,"devexec",DevexecAction,NULL,pExe); - - /* add additional object creation commands here */ - AddCommand(pInter,"TokenInit",TokenInit,NULL,NULL); - AddCommand(pInter,"ServerOption",IFServerOption,NULL,NULL); - AddCommand(pInter,"SicsUser", PWSicsUser,NULL,NULL); - AddCommand(pInter,"VarMake",VarFactory,NULL,NULL); - AddCommand(pInter,"MakeDrive",MakeDrive,NULL,NULL); - AddCommand(pInter,"Motor",MotorCreate,NULL,NULL); - AddCommand(pInter,"MakeMulti",MakeMulti,NULL,NULL); - AddCommand(pInter,"MakeMono",MonoInit,NULL,NULL); - AddCommand(pInter,"MakeWaveLength",MakeWaveLengthVar,NULL,NULL); - AddCommand(pInter,"MakeEnergy",MakeEnergyVar,NULL,NULL); - AddCommand(pInter,"MakeCounter",MakeCounter,NULL,NULL); - AddCommand(pInter,"MakeO2T",CreateO2T,NULL,NULL); - AddCommand(pInter,"SicsAlias",SicsAlias,NULL,NULL); - AddCommand(pInter,"DefineAlias",DefineAlias,NULL,NULL); /* M.Z. */ - AddCommand(pInter,"MakeHM",MakeHistMemory,NULL,NULL); - AddCommand(pInter,"VelocitySelector",VelSelFactory,NULL,NULL); - AddCommand(pInter,"MakeDataNumber",DNFactory,NULL,NULL); - AddCommand(pInter,"MakeScanCommand",ScanFactory,NULL,NULL); - AddCommand(pInter,"MakePeakCenter",FitFactory,NULL,NULL); - AddCommand(pInter,"MakeHKL",HKLFactory,NULL,NULL); - AddCommand(pInter,"MakeOptimise",MakeOptimiser,NULL,NULL); - AddCommand(pInter,"MakeMesure",MesureFactory,NULL,NULL); - AddCommand(pInter,"kill_command",SICSKill,NULL,NULL); - AddCommand(pInter,"MakeChopper",ChocoFactory,NULL,NULL); - AddCommand(pInter,"ChopperAdapter",CHAdapterFactory,NULL,NULL); - AddCommand(pInter,"MakeXYTable",XYFactory,NULL,NULL); - AddCommand(pInter,"MakeMaximize",MaximizeFactory,NULL,NULL); - AddCommand(pInter,"MakeLin2Ang",MakeLin2Ang,NULL,NULL); - AddCommand(pInter,"MakeSync",MakeSync,NULL,NULL); - AddCommand(pInter,"MakeHMControl",MakeHMControl,NULL,NULL); - AddCommand(pInter,"MakeRS232Controller",RS232Factory,NULL,NULL); - AddCommand(pInter,"MakeMaxDetector",LoMaxFactory,NULL,NULL); - AddCommand(pInter,"AntiCollisionInstall",AntiColliderFactory,NULL,NULL); - AddCommand(pInter,"MakeGPIB",MakeGPIB,NULL,NULL); - AddCommand(pInter,"MakeNXScript",MakeNXScript,NULL,NULL); - AddCommand(pInter,"MakeTclInt",MakeTclInt,NULL,NULL); - AddCommand(pInter,"TclReplaceDrivable",TclReplaceDrivable,NULL,NULL); - AddCommand(pInter,"DrivableInvoke", TclDrivableInvoke,NULL,NULL); - AddCommand(pInter,"UpdateFactory",UpdateFactory,NULL,NULL); - AddCommand(pInter,"allowexec",AllowExec,NULL,NULL); - AddCommand(pInter,"MakeConfigurableMotor", - MakeConfigurableVirtualMotor,NULL,NULL); - AddCommand(pInter,"MakeBatchManager", - MakeExeManager,NULL,NULL); - AddCommand(pInter,"MakeOscillator", - MakeOscillator,NULL,NULL); - AddCommand(pInter,"MakeDiffScan", - MakeDiffScan,NULL,NULL); - AddCommand(pInter,"MakeHKLMot", - HKLMotInstall,NULL,NULL); - AddCommand(pInter,"MakeUBCalc", - MakeUBCalc,NULL,NULL); - AddCommand(pInter,"MakeTasUB", - TasUBFactory,NULL,NULL); - AddCommand(pInter,"MakeTasScan", - TASUBScanFactory,NULL,NULL); - AddCommand(pInter,"MakeMcStasReader", - McStasReaderFactory,NULL,NULL); - AddCommand(pInter,"MakeMcStasController", - McStasControllerFactory,NULL,NULL); - AddCommand(pInter,"InstallSinfox", - InstallSinfox,NULL,NULL); - AddCommand(pInter,"MakeCone", - MakeCone,NULL,NULL); - AddCommand(pInter,"MakeMultiCounter", - MakeMultiCounter,NULL,NULL); - AddCommand(pInter,"MakeSicsPoll", - InstallSICSPoll,NULL,NULL); - AddCommand(pInter,"MakeStateMon", - StateMonFactory,NULL,NULL); - AddCommand(pInter,"MakeAsyncProtocol",AsyncProtocolFactory,NULL,NULL); - AddCommand(pInter,"MakeAsyncQueue",AsyncQueueFactory,NULL,NULL); - AddCommand(pInter,"MakeSicsObj",InstallSICSOBJ,NULL,NULL); - AddCommand(pInter,"DynSicsObj",InstallSICSOBJ,NULL,NULL); -/* AddCommand(pInter,"MakeHdbQueue",MakeHDBQueue,NULL,NULL); */ - AddCommand(pInter,"MakeGenController",GenControllerFactory,NULL,NULL); - AddCommand(pInter,"genconfigure",GenControllerConfigure,NULL,NULL); - AddCommand(pInter,"MakeProxy",ProxyFactory,NULL,NULL); - AddCommand(pInter,"MakeRefList",MakeReflectionList,NULL,NULL); - AddCommand(pInter,"MakeSingleX",MakeSingleX,NULL,NULL); - AddCommand(pInter,"MakeSecMotor",SecMotorFactory,NULL,NULL); + /* check authorisation */ + if (SCGetRights(pCon) > usMugger) { + SCWrite(pCon, "Insufficient privilege to set users", eError); + return 0; + } - /* - install site specific commands - */ - site = getSite(); - if(site != NULL){ - site->AddSiteCommands(pInter); - } - } -/*---------------------------------------------------------------------------*/ - static void KillIniCommands(SicsInterp *pSics) - { - pSite site = NULL; - - /* specify superfluous initialization commands here */ - RemoveCommand(pSics,"TokenInit"); - RemoveCommand(pSics,"ServerOption"); - RemoveCommand(pSics,"SicsUser"); - RemoveCommand(pSics,"VarMake"); - RemoveCommand(pSics,"MakeDrive"); - RemoveCommand(pSics,"Motor"); -/* - RemoveCommand(pSics,"MakeMulti"); -*/ - RemoveCommand(pSics,"MakeMono"); - RemoveCommand(pSics,"MakeWaveLength"); - RemoveCommand(pSics,"MakeEnergy"); - RemoveCommand(pSics,"MakeCounter"); - RemoveCommand(pSics,"MakeRuenBuffer"); - RemoveCommand(pSics,"MakeScan"); - RemoveCommand(pSics,"MakeO2T"); - RemoveCommand(pSics,"SicsAlias"); - RemoveCommand(pSics,"MakeHM"); - RemoveCommand(pSics,"VelocitySelector"); - RemoveCommand(pSics,"MakeDataNumber"); - RemoveCommand(pSics,"MakeScanCommand"); - RemoveCommand(pSics,"MakePeakCenter"); - RemoveCommand(pSics,"MakeHKL"); - RemoveCommand(pSics,"MakeOptimiser"); - RemoveCommand(pSics,"MakeMesure"); - RemoveCommand(pSics,"MakeChopper"); - RemoveCommand(pSics,"ChopperAdapter"); - RemoveCommand(pSics,"MakeHklscan"); - RemoveCommand(pSics,"MakeXYTable"); - RemoveCommand(pSics,"MakeMaximize"); - RemoveCommand(pSics,"MakeLin2Ang"); - RemoveCommand(pSics,"MakeSync"); - RemoveCommand(pSics,"MakeHMControl"); - RemoveCommand(pSics,"MakeRS232Controller"); - RemoveCommand(pSics,"MakeMaxDetector"); - RemoveCommand(pSics,"AntiColliderInstall"); - RemoveCommand(pSics,"MakeGPIB"); - RemoveCommand(pSics,"MakeNXScript"); - RemoveCommand(pSics,"MakeTclInt"); - RemoveCommand(pSics,"UpdateFactory"); - RemoveCommand(pSics,"allowexec"); - RemoveCommand(pSics,"MakeConfigurableMotor"); - RemoveCommand(pSics,"MakeBatchManager"); - RemoveCommand(pSics,"MakeOscillator"); - RemoveCommand(pSics,"MakeDiffScan"); - RemoveCommand(pSics,"MakeHKLMot"); - RemoveCommand(pSics,"MakeUBCalc"); - RemoveCommand(pSics,"MakeTasUB"); - RemoveCommand(pSics,"MakeTasScan"); - RemoveCommand(pSics,"MakemcStasReader"); - RemoveCommand(pSics,"InstallSinfox"); - RemoveCommand(pSics,"MakeCone"); - RemoveCommand(pSics,"MakeMultiCounter"); - RemoveCommand(pSics,"MakeStateMon"); - RemoveCommand(pSics,"MakeAsyncQueue"); - RemoveCommand(pSics,"MakeAsyncProtocol"); - RemoveCommand(pSics,"MakeSicsObject"); - RemoveCommand(pSics,"MakeGenController"); - RemoveCommand(pSics,"genconfigure"); - RemoveCommand(pSics,"MakeProxy"); - RemoveCommand(pSics,"MakeRefList"); - RemoveCommand(pSics,"MakeSingleX"); - RemoveCommand(pSics,"MakeSecMotor"); - /* - remove site specific installation commands - */ - site = getSite(); - if(site != NULL){ - site->RemoveSiteCommands(pSics); + /* analyse commandlist */ + pList = SplitArguments(argc - 1, &argv[1]); + if ((!pList) || (!pList->pNext) || (!pList->pNext->pNext)) { + sprintf(pBueffel, "Invalid Passwd Entry ::\n %s %s %s\n", argv[1], + argv[2], argv[3]); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return 0; + } else { + if (pList->pNext->pNext->Type != eInt) { + SCWrite(pCon, "Need integer rights code", eError); + DeleteTokenList(pList); + return 0; + } else { + AddUser(pList->text, pList->pNext->text, pList->pNext->pNext->iVal); } } + DeleteTokenList(pList); + return 1; +} + /*--------------------------------------------------------------------------*/ - void InitGeneral(void) - { +static void InitIniCommands(SicsInterp * pInter, pTaskMan pTask) +{ + pExeList pExe; + pEnvMon pEnv = NULL; + pSite site = NULL; + assert(pInter); + + pExe = CreateExeList(pTask); + pServ->pExecutor = pExe; + pEnv = CreateEnvMon(); + + assert(pExe); + assert(pEnv); + + /* permanent commands */ + AddCommand(pInter, "Sics_Exitus", SicsExit, NULL, NULL); + AddCommand(pInter, "FileEval", MacroFileEval, NULL, NULL); + + AddCommand(pInter, "InternEval", InternalFileEval, NULL, NULL); + AddCommand(pInter, "ClientPut", ClientPut, NULL, NULL); + AddCommand(pInter, "GumPut", GumPut, NULL, NULL); + AddCommand(pInter, "broadcast", Broadcast, NULL, NULL); + AddCommand(pInter, "transact", TransactAction, NULL, NULL); + AddCommand(pInter, "fulltransact", TransactAction, NULL, NULL); + AddCommand(pInter, "sicsprompt", SicsPrompt, NULL, NULL); + AddCommand(pInter, "Publish", TclPublish, NULL, NULL); + AddCommand(pInter, "GetLog", LogCapture, NULL, NULL); + AddCommand(pInter, "config", ConfigCon, NULL, NULL); + AddCommand(pInter, "wait", UserWait, NULL, NULL); + AddCommand(pInter, "status", UserStatus, NULL, NULL); + AddCommand(pInter, "ResetServer", ResetStatus, NULL, NULL); + AddCommand(pInter, "Dir", ListObjects, NULL, NULL); + AddCommand(pInter, "SetInt", SetSICSInterrupt, NULL, NULL); + AddCommand(pInter, "GetInt", GetSICSInterrupt, NULL, NULL); + AddCommand(pInter, "SICSType", SICSType, NULL, NULL); + AddCommand(pInter, "SICSBounds", SICSBounds, NULL, NULL); + AddCommand(pInter, "SICSStatus", SICSStatus, NULL, NULL); + AddCommand(pInter, "sicstime", SICSTime, NULL, NULL); + AddCommand(pInter, "sicsdescriptor", SICSDescriptor, NULL, NULL); + AddCommand(pInter, "SetStatus", SetSICSStatus, NULL, NULL); + AddCommand(pInter, "db", SICSDebug, NULL, NULL); + AddCommand(pInter, "EVFactory", EVControlFactory, NULL, NULL); + AddCommand(pInter, "emon", EVWrapper, DeleteEnvMon, pEnv); + AddCommand(pInter, "commandlog", CommandLog, CommandLogClose, NULL); + AddCommand(pInter, "udpquieck", QuieckAction, KillQuieck, NULL); + AddCommand(pInter, "alias", MakeAlias, NULL, NULL); + AddCommand(pInter, "findalias", LocateAliasAction, NULL, NULL); + AddCommand(pInter, "sicscron", MakeCron, NULL, NULL); + AddCommand(pInter, "dolater", MakeCron, NULL, NULL); + AddCommand(pInter, "sicsdatafactory", SICSDataFactory, NULL, NULL); + AddCommand(pInter, "scriptcallback", CallbackScript, NULL, NULL); + AddCommand(pInter, "help", SicsHelp, KillHelp, NULL); + AddCommand(pInter, "list", SicsList, NULL, NULL); + AddCommand(pInter, "InstallHdb", InstallSICSHipadaba, NULL, NULL); + MakeProtocol(pInter); + InstallBackground(pInter); + + /* commands to do with the executor. Only StopExe carries the + DeleteFunction in order to avoid double deletion. All the + other commands operate on the same datastructure. + */ + AddCommand(pInter, "StopExe", StopCommand, DeleteExeList, pExe); + AddCommand(pInter, "ListExe", ListExe, NULL, pExe); + AddCommand(pInter, "sicsidle", SicsIdle, NULL, pExe); + AddCommand(pInter, "Success", Success, NULL, pExe); + AddCommand(pInter, "pause", PauseAction, NULL, pExe); + AddCommand(pInter, "continue", ContinueAction, NULL, pExe); + AddCommand(pInter, "devexec", DevexecAction, NULL, pExe); + + /* add additional object creation commands here */ + AddCommand(pInter, "TokenInit", TokenInit, NULL, NULL); + AddCommand(pInter, "ServerOption", IFServerOption, NULL, NULL); + AddCommand(pInter, "SicsUser", PWSicsUser, NULL, NULL); + AddCommand(pInter, "VarMake", VarFactory, NULL, NULL); + AddCommand(pInter, "MakeDrive", MakeDrive, NULL, NULL); + AddCommand(pInter, "Motor", MotorCreate, NULL, NULL); + AddCommand(pInter, "MakeMulti", MakeMulti, NULL, NULL); + AddCommand(pInter, "MakeMono", MonoInit, NULL, NULL); + AddCommand(pInter, "MakeWaveLength", MakeWaveLengthVar, NULL, NULL); + AddCommand(pInter, "MakeEnergy", MakeEnergyVar, NULL, NULL); + AddCommand(pInter, "MakeCounter", MakeCounter, NULL, NULL); + AddCommand(pInter, "MakeSecCounter", MakeSecCter, NULL, NULL); + AddCommand(pInter, "MakeO2T", CreateO2T, NULL, NULL); + AddCommand(pInter, "SicsAlias", SicsAlias, NULL, NULL); + AddCommand(pInter, "DefineAlias", DefineAlias, NULL, NULL); /* M.Z. */ + AddCommand(pInter, "MakeHM", MakeHistMemory, NULL, NULL); + AddCommand(pInter, "VelocitySelector", VelSelFactory, NULL, NULL); + AddCommand(pInter, "MakeDataNumber", DNFactory, NULL, NULL); + AddCommand(pInter, "MakeScanCommand", ScanFactory, NULL, NULL); + AddCommand(pInter, "MakePeakCenter", FitFactory, NULL, NULL); + AddCommand(pInter, "MakeHKL", HKLFactory, NULL, NULL); + AddCommand(pInter, "MakeOptimise", MakeOptimiser, NULL, NULL); + AddCommand(pInter, "MakeMesure", MesureFactory, NULL, NULL); + AddCommand(pInter, "kill_command", SICSKill, NULL, NULL); + AddCommand(pInter, "MakeChopper", ChocoFactory, NULL, NULL); + AddCommand(pInter, "ChopperAdapter", CHAdapterFactory, NULL, NULL); + AddCommand(pInter, "MakeXYTable", XYFactory, NULL, NULL); + AddCommand(pInter, "MakeMaximize", MaximizeFactory, NULL, NULL); + AddCommand(pInter, "MakeLin2Ang", MakeLin2Ang, NULL, NULL); + AddCommand(pInter, "MakeSync", MakeSync, NULL, NULL); + AddCommand(pInter, "MakeHMControl", MakeHMControl, NULL, NULL); + AddCommand(pInter, "MakeRS232Controller", RS232Factory, NULL, NULL); + AddCommand(pInter, "MakeMaxDetector", LoMaxFactory, NULL, NULL); + AddCommand(pInter, "AntiCollisionInstall", AntiColliderFactory, NULL, + NULL); + AddCommand(pInter, "MakeGPIB", MakeGPIB, NULL, NULL); + AddCommand(pInter, "MakeNXScript", MakeNXScript, NULL, NULL); + AddCommand(pInter, "MakeTclInt", MakeTclInt, NULL, NULL); + AddCommand(pInter, "TclReplaceDrivable", TclReplaceDrivable, NULL, NULL); + AddCommand(pInter, "DrivableInvoke", TclDrivableInvoke, NULL, NULL); + AddCommand(pInter, "UpdateFactory", UpdateFactory, NULL, NULL); + AddCommand(pInter, "allowexec", AllowExec, NULL, NULL); + AddCommand(pInter, "MakeConfigurableMotor", + MakeConfigurableVirtualMotor, NULL, NULL); + AddCommand(pInter, "MakeBatchManager", MakeExeManager, NULL, NULL); + AddCommand(pInter, "MakeOscillator", MakeOscillator, NULL, NULL); + AddCommand(pInter, "MakeDiffScan", MakeDiffScan, NULL, NULL); + AddCommand(pInter, "MakeHKLMot", HKLMotInstall, NULL, NULL); + AddCommand(pInter, "MakeUBCalc", MakeUBCalc, NULL, NULL); + AddCommand(pInter, "MakeTasUB", TasUBFactory, NULL, NULL); + AddCommand(pInter, "MakeTasScan", TASUBScanFactory, NULL, NULL); + AddCommand(pInter, "MakeMcStasReader", McStasReaderFactory, NULL, NULL); + AddCommand(pInter, "MakeMcStasController", + McStasControllerFactory, NULL, NULL); + AddCommand(pInter, "InstallSinfox", InstallSinfox, NULL, NULL); + AddCommand(pInter, "MakeCone", MakeCone, NULL, NULL); + AddCommand(pInter, "MakeMultiCounter", MakeMultiCounter, NULL, NULL); + AddCommand(pInter, "MakeSicsPoll", InstallSICSPoll, NULL, NULL); + AddCommand(pInter, "MakeStateMon", StateMonFactory, NULL, NULL); + AddCommand(pInter, "MakeAsyncProtocol", AsyncProtocolFactory, NULL, + NULL); + AddCommand(pInter, "MakeAsyncQueue", AsyncQueueFactory, NULL, NULL); + AddCommand(pInter, "MakeSicsObj", InstallSICSOBJ, NULL, NULL); + AddCommand(pInter, "DynSicsObj", InstallSICSOBJ, NULL, NULL); +/* AddCommand(pInter,"MakeHdbQueue",MakeHDBQueue,NULL,NULL); */ + AddCommand(pInter, "MakeGenController", GenControllerFactory, NULL, + NULL); + AddCommand(pInter, "genconfigure", GenControllerConfigure, NULL, NULL); + AddCommand(pInter, "MakeProxy", ProxyFactory, NULL, NULL); + AddCommand(pInter, "MakeRefList", MakeReflectionList, NULL, NULL); + AddCommand(pInter, "MakeSingleX", MakeSingleX, NULL, NULL); + AddCommand(pInter, "MakeSecMotor", SecMotorFactory, NULL, NULL); + + /* + install site specific commands + */ + site = getSite(); + if (site != NULL) { + site->AddSiteCommands(pInter); + } +} + +/*---------------------------------------------------------------------------*/ +static void KillIniCommands(SicsInterp * pSics) +{ + pSite site = NULL; + + /* specify superfluous initialization commands here */ + RemoveCommand(pSics, "TokenInit"); + RemoveCommand(pSics, "ServerOption"); + RemoveCommand(pSics, "SicsUser"); + RemoveCommand(pSics, "VarMake"); + RemoveCommand(pSics, "MakeDrive"); + RemoveCommand(pSics, "Motor"); +/* + RemoveCommand(pSics,"MakeMulti"); +*/ + RemoveCommand(pSics, "MakeMono"); + RemoveCommand(pSics, "MakeWaveLength"); + RemoveCommand(pSics, "MakeEnergy"); + RemoveCommand(pSics, "MakeCounter"); + RemoveCommand(pSics, "MakeSecCounter"); + RemoveCommand(pSics, "MakeRuenBuffer"); + RemoveCommand(pSics, "MakeScan"); + RemoveCommand(pSics, "MakeO2T"); + RemoveCommand(pSics, "SicsAlias"); + RemoveCommand(pSics, "MakeHM"); + RemoveCommand(pSics, "VelocitySelector"); + RemoveCommand(pSics, "MakeDataNumber"); + RemoveCommand(pSics, "MakeScanCommand"); + RemoveCommand(pSics, "MakePeakCenter"); + RemoveCommand(pSics, "MakeHKL"); + RemoveCommand(pSics, "MakeOptimiser"); + RemoveCommand(pSics, "MakeMesure"); + RemoveCommand(pSics, "MakeChopper"); + RemoveCommand(pSics, "ChopperAdapter"); + RemoveCommand(pSics, "MakeHklscan"); + RemoveCommand(pSics, "MakeXYTable"); + RemoveCommand(pSics, "MakeMaximize"); + RemoveCommand(pSics, "MakeLin2Ang"); + RemoveCommand(pSics, "MakeSync"); + RemoveCommand(pSics, "MakeHMControl"); + RemoveCommand(pSics, "MakeRS232Controller"); + RemoveCommand(pSics, "MakeMaxDetector"); + RemoveCommand(pSics, "AntiColliderInstall"); + RemoveCommand(pSics, "MakeGPIB"); + RemoveCommand(pSics, "MakeNXScript"); + RemoveCommand(pSics, "MakeTclInt"); + RemoveCommand(pSics, "UpdateFactory"); + RemoveCommand(pSics, "allowexec"); + RemoveCommand(pSics, "MakeConfigurableMotor"); + RemoveCommand(pSics, "MakeBatchManager"); + RemoveCommand(pSics, "MakeOscillator"); + RemoveCommand(pSics, "MakeDiffScan"); + RemoveCommand(pSics, "MakeHKLMot"); + RemoveCommand(pSics, "MakeUBCalc"); + RemoveCommand(pSics, "MakeTasUB"); + RemoveCommand(pSics, "MakeTasScan"); + RemoveCommand(pSics, "MakemcStasReader"); + RemoveCommand(pSics, "InstallSinfox"); + RemoveCommand(pSics, "MakeCone"); + RemoveCommand(pSics, "MakeMultiCounter"); + RemoveCommand(pSics, "MakeStateMon"); + RemoveCommand(pSics, "MakeAsyncQueue"); + RemoveCommand(pSics, "MakeAsyncProtocol"); + RemoveCommand(pSics, "MakeSicsObject"); + RemoveCommand(pSics, "MakeGenController"); + RemoveCommand(pSics, "genconfigure"); + RemoveCommand(pSics, "MakeProxy"); + RemoveCommand(pSics, "MakeRefList"); + RemoveCommand(pSics, "MakeSingleX"); + RemoveCommand(pSics, "MakeSecMotor"); + /* + remove site specific installation commands + */ + site = getSite(); + if (site != NULL) { + site->RemoveSiteCommands(pSics); + } +} + +/*--------------------------------------------------------------------------*/ +void InitGeneral(void) +{ #define INIT(F) { void F(void); F(); } /* insert here initialization routines ... */ - INIT(StatisticsInit); - INIT(InitializerInit); - INIT(SaveHdbInit); /* must be after InitializerInit */ - INIT(SctInit); - INIT(SctDriveInit); - INIT(LogReaderInit); - INIT(LogSetupInit); - INIT(StatusFileInit); + INIT(StatisticsInit); + INIT(InitializerInit); + INIT(SaveHdbInit); /* must be after InitializerInit */ + INIT(SctInit); + INIT(SctDriveInit); + INIT(LogReaderInit); + INIT(LogSetupInit); + INIT(StatusFileInit); + + INIT(SiteInit); /* site specific initializations */ +} - INIT(SiteInit); /* site specific initializations */ - } /*--------------------------------------------------------------------------*/ - int InitObjectCommands(pServer pServ, char *file) - { - SConnection *pCon = NULL; - char pBueffel[1024]; - int iRet; - SicsInterp *pSics; - - pSics = pServ->pSics; - assert(pSics); - - InitGeneral(); - - /* general initialization */ - /* create a connection */ - pCon = SCCreateDummyConnection(pSics); - if(!pCon) - { - return 0; - } - MakeExeManager(pCon,pSics,NULL,1, NULL); - InitIniCommands(pSics,pServ->pTasker); - InstallBckRestore(pCon,pSics); - - - /* evaluate the file */ - sprintf(pBueffel,"fileeval %s",file); - iRet = InterpExecute(pSics,pCon,pBueffel); - - /* done */ - SCDeleteConnection(pCon); - KillIniCommands(pSics); - RemoveStartupCommands(); - return 1; - } +int InitObjectCommands(pServer pServ, char *file) +{ + SConnection *pCon = NULL; + char pBueffel[1024]; + int iRet; + SicsInterp *pSics; + pSics = pServ->pSics; + assert(pSics); + + InitGeneral(); + + /* general initialization */ + /* create a connection */ + pCon = SCCreateDummyConnection(pSics); + if (!pCon) { + return 0; + } + MakeExeManager(pCon, pSics, NULL, 1, NULL); + InitIniCommands(pSics, pServ->pTasker); + InstallBckRestore(pCon, pSics); + + + /* evaluate the file */ + sprintf(pBueffel, "fileeval %s", file); + iRet = InterpExecute(pSics, pCon, pBueffel); + + /* done */ + SCDeleteConnection(pCon); + KillIniCommands(pSics); + RemoveStartupCommands(); + return 1; +} diff --git a/ofac.h b/ofac.h index abd49042..e8eabdab 100644 --- a/ofac.h +++ b/ofac.h @@ -20,7 +20,6 @@ #ifndef OBJECTFACTORY #define OBJECTFACTORY - int InitObjectCommands(pServer pServ, char *file); - -#endif +int InitObjectCommands(pServer pServ, char *file); +#endif diff --git a/optimise.c b/optimise.c index 066dc53c..6666543a 100644 --- a/optimise.c +++ b/optimise.c @@ -28,1057 +28,955 @@ #define MAXFLOAT 9999999.99 #endif -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*----------------- local variable structure -----------------------------*/ - typedef struct { - char *pName; - float fStep; - int iStep; - float fPrecision; - float fCenter; - float fShift; - pIDrivable pDriv; - void *pData; - int iLost; - } OVarEntry, *pOVarEntry; +typedef struct { + char *pName; + float fStep; + int iStep; + float fPrecision; + float fCenter; + float fShift; + pIDrivable pDriv; + void *pData; + int iLost; +} OVarEntry, *pOVarEntry; /*-------------------------------------------------------------------------*/ - static void FreeOVar(void *pData) - { - pOVarEntry self = NULL; - - self = (pOVarEntry)pData; - if(!self) - return; - - if(self->pName) - { - free(self->pName); - } - free(self); - } - +static void FreeOVar(void *pData) +{ + pOVarEntry self = NULL; + + self = (pOVarEntry) pData; + if (!self) + return; + + if (self->pName) { + free(self->pName); + } + free(self); +} + /*-------------------- the optimise structure -----------------------------*/ - typedef struct __OptimiseStruct { - pObjectDescriptor pDes; - int iMaxCycles; - CounterMode eCount; - float fPreset; - int iChannel; - float fThreshold; - int iVar; - pDynar pVariables; - pScanData pScanner; - pFit pPeakFitter; - } Optimiser; - -/*--- dummy functions to stop scan from writing scan files --------------*/ +typedef struct __OptimiseStruct { + pObjectDescriptor pDes; + int iMaxCycles; + CounterMode eCount; + float fPreset; + int iChannel; + float fThreshold; + int iVar; + pDynar pVariables; + pScanData pScanner; + pFit pPeakFitter; +} Optimiser; + +/*--- dummy functions to stop scan from writing scan files --------------*/ + +static int DummyHeader(pScanData self) +{ + return 1; +} +static int DummyHeader2(pScanData self, int iPoint) +{ + return 1; +} - static int DummyHeader(pScanData self) - { - return 1; - } - static int DummyHeader2(pScanData self,int iPoint) - { - return 1; - } /*------------------------------------------------------------------------*/ - pOptimise CreateOptimiser(pCounter pCount) - { - pOptimise pNew = NULL; - - assert(pCount); - - /* get some memory */ - pNew = (pOptimise)malloc(sizeof(Optimiser)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(Optimiser)); - - /* initialise a few defaults */ - pNew->fThreshold = 100; - pNew->iMaxCycles = 7; - pNew->iChannel = 0; - pNew->eCount = eTimer; - pNew->iVar = 0; - pNew->fPreset = 10000.; - - pNew->pDes = CreateDescriptor("PeakOptimiser"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - - pNew->pScanner = CreateScanObject(NULL,NULL,pCount,"optiscan"); - if(!pNew->pScanner) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - - } - pNew->pScanner->WriteHeader = DummyHeader; - pNew->pScanner->WriteScanPoints = DummyHeader2; - - pNew->pPeakFitter = CreateFitCenter(pNew->pScanner); - if(!pNew->pPeakFitter) - { - DeleteDescriptor(pNew->pDes); - DeleteScanObject(pNew->pScanner); - free(pNew); - return NULL; - } - - pNew->iVar = 0; - pNew->pVariables = CreateDynar(0,10,10,FreeOVar); - if(!pNew->pVariables) - { - DeleteFitCenter(pNew->pPeakFitter); - DeleteDescriptor(pNew->pDes); - DeleteScanObject(pNew->pScanner); - free(pNew); - return NULL; - } - - return pNew; - } -/*--------------------------------------------------------------------------*/ - void DeleteOptimiser(void *pData) - { - pOptimise self = NULL; - - self = (pOptimise)pData; - if(!self) - return; - - if(self->pVariables) - { - DeleteDynar(self->pVariables); - } - - if(self->pPeakFitter) - { - DeleteFitCenter(self->pPeakFitter); - } - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->pScanner) - { - DeleteScanObject(self->pScanner); - } - - free(self); +pOptimise CreateOptimiser(pCounter pCount) +{ + pOptimise pNew = NULL; + + assert(pCount); + + /* get some memory */ + pNew = (pOptimise) malloc(sizeof(Optimiser)); + if (!pNew) { + return NULL; } + memset(pNew, 0, sizeof(Optimiser)); + + /* initialise a few defaults */ + pNew->fThreshold = 100; + pNew->iMaxCycles = 7; + pNew->iChannel = 0; + pNew->eCount = eTimer; + pNew->iVar = 0; + pNew->fPreset = 10000.; + + pNew->pDes = CreateDescriptor("PeakOptimiser"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + + pNew->pScanner = CreateScanObject(NULL, NULL, pCount, "optiscan"); + if (!pNew->pScanner) { + DeleteDescriptor(pNew->pDes); + free(pNew); + return NULL; + + } + pNew->pScanner->WriteHeader = DummyHeader; + pNew->pScanner->WriteScanPoints = DummyHeader2; + + pNew->pPeakFitter = CreateFitCenter(pNew->pScanner); + if (!pNew->pPeakFitter) { + DeleteDescriptor(pNew->pDes); + DeleteScanObject(pNew->pScanner); + free(pNew); + return NULL; + } + + pNew->iVar = 0; + pNew->pVariables = CreateDynar(0, 10, 10, FreeOVar); + if (!pNew->pVariables) { + DeleteFitCenter(pNew->pPeakFitter); + DeleteDescriptor(pNew->pDes); + DeleteScanObject(pNew->pScanner); + free(pNew); + return NULL; + } + + return pNew; +} + /*--------------------------------------------------------------------------*/ - void OptimiserClear(pOptimise self) - { - assert(self); - self->iVar = 0; - } +void DeleteOptimiser(void *pData) +{ + pOptimise self = NULL; + + self = (pOptimise) pData; + if (!self) + return; + + if (self->pVariables) { + DeleteDynar(self->pVariables); + } + + if (self->pPeakFitter) { + DeleteFitCenter(self->pPeakFitter); + } + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->pScanner) { + DeleteScanObject(self->pScanner); + } + + free(self); +} + /*--------------------------------------------------------------------------*/ - int OptimiserAdd(pOptimise self, - char *pName, float fStep, int nStep, float fPrecision) - { - OVarEntry sNeu; - CommandList *pCom = NULL; - - /* find and check our object */ - pCom = FindCommand(pServ->pSics,pName); - if(!pCom) - { - return 0; - } - sNeu.pData = pCom->pData; - sNeu.pDriv = GetDrivableInterface(sNeu.pData); - if(!sNeu.pDriv) - { - return 0; - } - sNeu.fStep = fStep; - sNeu.iStep = nStep; - sNeu.fPrecision = fPrecision; - sNeu.pName = strdup(pName); - sNeu.iLost = 0; - - DynarPutCopy(self->pVariables,self->iVar,&sNeu,sizeof(OVarEntry)); - self->iVar++; - - return 1; - } +void OptimiserClear(pOptimise self) +{ + assert(self); + self->iVar = 0; +} + /*--------------------------------------------------------------------------*/ - int OptimiserSetPar(pOptimise self, char *name, float fVal) - { - if(strcmp(name,"maxcycles") == 0) - { - self->iMaxCycles = (int)fVal; - return 1; - } - else if(strcmp(name,"threshold") == 0) - { - self->fThreshold = fVal; - return 1; - } - else if(strcmp(name,"channel") == 0) - { - self->iChannel = (int)fVal; - return 1; - } - else if(strcmp(name,"preset") == 0) - { - self->fPreset = fVal; - return 1; - } - else if(strcmp(name,"countmode") == 0) - { - if(fVal < 0.05) - { - self->eCount = eTimer; - } - else - { - self->eCount = ePreset; - } - return 1; - } - else - { - return 0; - } - } +int OptimiserAdd(pOptimise self, + char *pName, float fStep, int nStep, float fPrecision) +{ + OVarEntry sNeu; + CommandList *pCom = NULL; + + /* find and check our object */ + pCom = FindCommand(pServ->pSics, pName); + if (!pCom) { + return 0; + } + sNeu.pData = pCom->pData; + sNeu.pDriv = GetDrivableInterface(sNeu.pData); + if (!sNeu.pDriv) { + return 0; + } + sNeu.fStep = fStep; + sNeu.iStep = nStep; + sNeu.fPrecision = fPrecision; + sNeu.pName = strdup(pName); + sNeu.iLost = 0; + + DynarPutCopy(self->pVariables, self->iVar, &sNeu, sizeof(OVarEntry)); + self->iVar++; + + return 1; +} + /*--------------------------------------------------------------------------*/ - int OptimiserGetPar(pOptimise self, char *name, float *fVal) - { - if(strcmp(name,"maxcycles") == 0) - { - *fVal = self->iMaxCycles; - return 1; - } - else if(strcmp(name,"threshold") == 0) - { - *fVal = self->fThreshold; - return 1; - } - else if(strcmp(name,"channel") == 0) - { - *fVal = self->iChannel; - return 1; - } - else if(strcmp(name,"preset") == 0) - { - *fVal = self->fPreset; - return 1; - } - else if(strcmp(name,"countmode") == 0) - { - if(self->eCount == eTimer) - { - *fVal = 0.; - } - else - { - *fVal = 1.0; - } - return 1; - } - else - { - return 0; - } - } +int OptimiserSetPar(pOptimise self, char *name, float fVal) +{ + if (strcmp(name, "maxcycles") == 0) { + self->iMaxCycles = (int) fVal; + return 1; + } else if (strcmp(name, "threshold") == 0) { + self->fThreshold = fVal; + return 1; + } else if (strcmp(name, "channel") == 0) { + self->iChannel = (int) fVal; + return 1; + } else if (strcmp(name, "preset") == 0) { + self->fPreset = fVal; + return 1; + } else if (strcmp(name, "countmode") == 0) { + if (fVal < 0.05) { + self->eCount = eTimer; + } else { + self->eCount = ePreset; + } + return 1; + } else { + return 0; + } +} + +/*--------------------------------------------------------------------------*/ +int OptimiserGetPar(pOptimise self, char *name, float *fVal) +{ + if (strcmp(name, "maxcycles") == 0) { + *fVal = self->iMaxCycles; + return 1; + } else if (strcmp(name, "threshold") == 0) { + *fVal = self->fThreshold; + return 1; + } else if (strcmp(name, "channel") == 0) { + *fVal = self->iChannel; + return 1; + } else if (strcmp(name, "preset") == 0) { + *fVal = self->fPreset; + return 1; + } else if (strcmp(name, "countmode") == 0) { + if (self->eCount == eTimer) { + *fVal = 0.; + } else { + *fVal = 1.0; + } + return 1; + } else { + return 0; + } +} + /*---------------------------------------------------------------------------*/ - static int OptimiserInit(pOptimise self,SConnection *pCon) - { - int i, iRet; - void *pData; - pOVarEntry pOVar; - float fVal; - - /* initialise each variable entry with the current position and - set the shift to something senseless. - */ - for(i = 0; i < self->iVar; i++) - { - DynarGet(self->pVariables,i,&pData); - pOVar = (pOVarEntry)pData; - pOVar->fCenter = pOVar->pDriv->GetValue(pOVar->pData,pCon); - if(pOVar->fCenter < -900.) - { - return SCANERROR; - } - pOVar->fShift = MAXFLOAT; - pOVar->iLost = 0; - } - self->pScanner->iChannel = self->iChannel; - return 1; - } -/*-------------------------------------------------------------------------*/ - static int CenterVariable(pOptimise self, SConnection *pCon, int i) - { - pOVarEntry pOvar; - void *pData; - int iRet, iReturn; - float fStart; - float fNewCenter, fStdDev, FWHM, fMax; - char pBueffel[512], cData[80]; - - assert(self); - assert( (i >= 0) && (i < self->iVar)); - assert(pCon); - - /* get variable data */ - DynarGet(self->pVariables,i,&pData); - pOvar = (pOVarEntry)pData; - - /* do a scan first */ - fStart = pOvar->fCenter - (pOvar->iStep/2)*pOvar->fStep; - ClearScanVar(self->pScanner); - iRet = AddScanVar(self->pScanner, pServ->pSics,pCon, - pOvar->pName, fStart, pOvar->fStep); - if(!iRet) - { - return 0; - } - sprintf(pBueffel,"Trying hard to optimise variable %s",pOvar->pName); - SCWrite(pCon,pBueffel,eLog); - iRet = SilentScan(self->pScanner,pOvar->iStep,self->eCount, - self->fPreset,pServ->pSics,pCon); - if(!iRet) - { - return SCANABORT; - } - - /* try to find a fit for this one */ - iRet = CalculateFit(self->pPeakFitter); - if(iRet == 0) - { - return SYSERROR; - } - GetFitResults(self->pPeakFitter, &fNewCenter,&fStdDev, &FWHM, &fMax); +static int OptimiserInit(pOptimise self, SConnection * pCon) +{ + int i, iRet; + void *pData; + pOVarEntry pOVar; + float fVal; - /* write some diagnostic messages */ - strcpy(pBueffel,"Peak Diagnosis: \n"); - sprintf(cData,"New %s position: %f \n",pOvar->pName,fNewCenter); - switch(iRet) - { - case 1: - strcat(pBueffel,"Peak found in scan range \n"); - strcat(pBueffel,cData); - iReturn = 1; - break; - case -1: - strcat(pBueffel,"Left half of peak missing \n"); - strcat(pBueffel, - "Extending scan range and setting position to maximum \n"); - strcat(pBueffel,cData); - iReturn = VARREDO; - break; - case -2: - strcat(pBueffel,"Right half of peak missing \n"); - strcat(pBueffel, - "Extending scan range and setting position to maximum \n"); - strcat(pBueffel,cData); - iReturn = 2; - break; - case -3: - case -4: - strcat(pBueffel,"No data in scan \n"); - break; - default: - strcat(pBueffel,cData); - sprintf(pData,"Fitting ended with error code %d \n",iRet); - strcat(pBueffel,cData); - break; - } - SCWrite(pCon,pBueffel,eLog); - - if(fMax < self->fThreshold) - { - SCWrite(pCon,"Peak may be lost, increasing scan range",eLog); - pOvar->iLost++; - if(pOvar->iLost > 2) - { - return PEAKLOST; - } - } - else - { - pOvar->iLost = 0; - } - - - /* act upon the fits results */ - if(iRet != 1) { - /* not enough scan data for a proper evaluation of the - peak. But the peak fitter has given us the maximum of - the counts. What we do is, we set the center to the - maximum, increase the scan width and mark the variable - for a redo in the next cycle by leaving the fShift - high. But we do this only if the maximum is above a threshold, - otherwise we just increase the scan range and leave the thing - where it is. - */ - if(fMax > self->fThreshold) - { - pOvar->fCenter = fNewCenter; - } - pOvar->iStep += pOvar->iStep; - } - else /* the success case */ - { - pOvar->fShift = ABS(pOvar->fCenter - fNewCenter); - sprintf(pBueffel,"%s shifted by %8.2f ",pOvar->pName,pOvar->fShift); - SCWrite(pCon,pBueffel,eLog); - pOvar->fPrecision = 3*fStdDev; - sprintf(pBueffel,"%s precision set to 3*StdDev = %8.3f", - pOvar->pName, 3*fStdDev); - SCWrite(pCon,pBueffel,eLog); - pOvar->fCenter = fNewCenter; - } - /* drive to the new center */ - iRet = Drive(pCon,pServ->pSics,pOvar->pName,pOvar->fCenter); - if(!iRet) - { - return DRIVEERROR; - } - - return iReturn; + /* initialise each variable entry with the current position and + set the shift to something senseless. + */ + for (i = 0; i < self->iVar; i++) { + DynarGet(self->pVariables, i, &pData); + pOVar = (pOVarEntry) pData; + pOVar->fCenter = pOVar->pDriv->GetValue(pOVar->pData, pCon); + if (pOVar->fCenter < -900.) { + return SCANERROR; + } + pOVar->fShift = MAXFLOAT; + pOVar->iLost = 0; } + self->pScanner->iChannel = self->iChannel; + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int CenterVariable(pOptimise self, SConnection * pCon, int i) +{ + pOVarEntry pOvar; + void *pData; + int iRet, iReturn; + float fStart; + float fNewCenter, fStdDev, FWHM, fMax; + char pBueffel[512], cData[80]; + + assert(self); + assert((i >= 0) && (i < self->iVar)); + assert(pCon); + + /* get variable data */ + DynarGet(self->pVariables, i, &pData); + pOvar = (pOVarEntry) pData; + + /* do a scan first */ + fStart = pOvar->fCenter - (pOvar->iStep / 2) * pOvar->fStep; + ClearScanVar(self->pScanner); + iRet = AddScanVar(self->pScanner, pServ->pSics, pCon, + pOvar->pName, fStart, pOvar->fStep); + if (!iRet) { + return 0; + } + sprintf(pBueffel, "Trying hard to optimise variable %s", pOvar->pName); + SCWrite(pCon, pBueffel, eLog); + iRet = SilentScan(self->pScanner, pOvar->iStep, self->eCount, + self->fPreset, pServ->pSics, pCon); + if (!iRet) { + return SCANABORT; + } + + /* try to find a fit for this one */ + iRet = CalculateFit(self->pPeakFitter); + if (iRet == 0) { + return SYSERROR; + } + GetFitResults(self->pPeakFitter, &fNewCenter, &fStdDev, &FWHM, &fMax); + + /* write some diagnostic messages */ + strcpy(pBueffel, "Peak Diagnosis: \n"); + sprintf(cData, "New %s position: %f \n", pOvar->pName, fNewCenter); + switch (iRet) { + case 1: + strcat(pBueffel, "Peak found in scan range \n"); + strcat(pBueffel, cData); + iReturn = 1; + break; + case -1: + strcat(pBueffel, "Left half of peak missing \n"); + strcat(pBueffel, + "Extending scan range and setting position to maximum \n"); + strcat(pBueffel, cData); + iReturn = VARREDO; + break; + case -2: + strcat(pBueffel, "Right half of peak missing \n"); + strcat(pBueffel, + "Extending scan range and setting position to maximum \n"); + strcat(pBueffel, cData); + iReturn = 2; + break; + case -3: + case -4: + strcat(pBueffel, "No data in scan \n"); + break; + default: + strcat(pBueffel, cData); + sprintf(pData, "Fitting ended with error code %d \n", iRet); + strcat(pBueffel, cData); + break; + } + SCWrite(pCon, pBueffel, eLog); + + if (fMax < self->fThreshold) { + SCWrite(pCon, "Peak may be lost, increasing scan range", eLog); + pOvar->iLost++; + if (pOvar->iLost > 2) { + return PEAKLOST; + } + } else { + pOvar->iLost = 0; + } + + + /* act upon the fits results */ + if (iRet != 1) { + /* not enough scan data for a proper evaluation of the + peak. But the peak fitter has given us the maximum of + the counts. What we do is, we set the center to the + maximum, increase the scan width and mark the variable + for a redo in the next cycle by leaving the fShift + high. But we do this only if the maximum is above a threshold, + otherwise we just increase the scan range and leave the thing + where it is. + */ + if (fMax > self->fThreshold) { + pOvar->fCenter = fNewCenter; + } + pOvar->iStep += pOvar->iStep; + } else { /* the success case */ + + pOvar->fShift = ABS(pOvar->fCenter - fNewCenter); + sprintf(pBueffel, "%s shifted by %8.2f ", pOvar->pName, pOvar->fShift); + SCWrite(pCon, pBueffel, eLog); + pOvar->fPrecision = 3 * fStdDev; + sprintf(pBueffel, "%s precision set to 3*StdDev = %8.3f", + pOvar->pName, 3 * fStdDev); + SCWrite(pCon, pBueffel, eLog); + pOvar->fCenter = fNewCenter; + } + /* drive to the new center */ + iRet = Drive(pCon, pServ->pSics, pOvar->pName, pOvar->fCenter); + if (!iRet) { + return DRIVEERROR; + } + + return iReturn; +} + /*------------------------------------------------------------------------ * We use the scan object here for counting. The reason is that this * handles well in the common case of a single counter but also has * provisions for other counting methods through the scan modules * scripting mechanism * ------------------------------------------------------------------------*/ -static long ClimbCount(pOptimise self, SConnection *pCon) +static long ClimbCount(pOptimise self, SConnection * pCon) { - int status; - long data[1]; - int (*CollectFunc)(pScanData self, int iPoint) = NULL; - - SilentPrepare(self->pScanner); + int status; + long data[1]; + int (*CollectFunc) (pScanData self, int iPoint) = NULL; - status = self->pScanner->ScanCount(self->pScanner,0); - if(status != 1) - { - return status; - } - if(self->pScanner->CollectScanData == CollectScanData) - { - CollectFunc = self->pScanner->CollectScanData; - self->pScanner->CollectScanData = CollectSilent; - } - status = self->pScanner->CollectScanData(self->pScanner,0); - if(CollectFunc != NULL) - { - self->pScanner->CollectScanData = CollectFunc; - } - if(status != 1) - { - return status; - } - GetScanCounts(self->pScanner,data,1); - return data[0]; -} -/*------------------------------------------------------------------------*/ -static int ClimbDrive(SConnection *pCon,char *name, float value) -{ - int status; - - status = Start2Run(pCon,pServ->pSics,name,value); - if(status != 1) - { - return DRIVEERROR; - } - status = Wait4Success(GetExecutor()); - if(status != DEVDONE) - { - return DRIVEERROR; - } - return 1; + SilentPrepare(self->pScanner); + + status = self->pScanner->ScanCount(self->pScanner, 0); + if (status != 1) { + return status; + } + if (self->pScanner->CollectScanData == CollectScanData) { + CollectFunc = self->pScanner->CollectScanData; + self->pScanner->CollectScanData = CollectSilent; + } + status = self->pScanner->CollectScanData(self->pScanner, 0); + if (CollectFunc != NULL) { + self->pScanner->CollectScanData = CollectFunc; + } + if (status != 1) { + return status; + } + GetScanCounts(self->pScanner, data, 1); + return data[0]; } + /*------------------------------------------------------------------------*/ -static int findDirection(pOptimise self, pOVarEntry pOvar, SConnection *pCon) +static int ClimbDrive(SConnection * pCon, char *name, float value) { - int status, direction; - float varValue; - long oneCount, twoCount; - - varValue = pOvar->fCenter + pOvar->fStep; - status = ClimbDrive(pCon,pOvar->pName,varValue); - if(!status) - { - return DRIVEERROR; - } - oneCount = ClimbCount(self,pCon); - if(oneCount < 0) - { - return SCANERROR; - } - if(SCGetInterrupt(pCon) != eContinue) - { - return SCANABORT; - } - varValue = pOvar->fCenter - pOvar->fStep; - status = ClimbDrive(pCon,pOvar->pName,varValue); - if(!status) - { - return DRIVEERROR; - } - twoCount = ClimbCount(self,pCon); - if(SCGetInterrupt(pCon) != eContinue) - { - return SCANABORT; - } - if(twoCount < 0) - { - return SCANERROR; - } - if(oneCount > twoCount) - { - direction = 1; - } - else - { - direction = -1; - } - return direction; + int status; + + status = Start2Run(pCon, pServ->pSics, name, value); + if (status != 1) { + return DRIVEERROR; + } + status = Wait4Success(GetExecutor()); + if (status != DEVDONE) { + return DRIVEERROR; + } + return 1; } + +/*------------------------------------------------------------------------*/ +static int findDirection(pOptimise self, pOVarEntry pOvar, + SConnection * pCon) +{ + int status, direction; + float varValue; + long oneCount, twoCount; + + varValue = pOvar->fCenter + pOvar->fStep; + status = ClimbDrive(pCon, pOvar->pName, varValue); + if (!status) { + return DRIVEERROR; + } + oneCount = ClimbCount(self, pCon); + if (oneCount < 0) { + return SCANERROR; + } + if (SCGetInterrupt(pCon) != eContinue) { + return SCANABORT; + } + varValue = pOvar->fCenter - pOvar->fStep; + status = ClimbDrive(pCon, pOvar->pName, varValue); + if (!status) { + return DRIVEERROR; + } + twoCount = ClimbCount(self, pCon); + if (SCGetInterrupt(pCon) != eContinue) { + return SCANABORT; + } + if (twoCount < 0) { + return SCANERROR; + } + if (oneCount > twoCount) { + direction = 1; + } else { + direction = -1; + } + return direction; +} + /*-------------------------------------------------------------------------*/ - static int ClimbVariable(pOptimise self, SConnection *pCon, int i) - { - pOVarEntry pOvar; - void *pData; - int status, direction = 1; - long oneCount, twoCount, lastCount, currentCount; - float varValue, startValue; - char buffer[256]; - int (*CollectFunc)(pScanData self, int iPoint) = NULL; - - assert(self); - assert( (i >= 0) && (i < self->iVar)); - assert(pCon); - - /* get variable data */ - DynarGet(self->pVariables,i,&pData); - pOvar = (pOVarEntry)pData; - startValue = pOvar->fCenter; +static int ClimbVariable(pOptimise self, SConnection * pCon, int i) +{ + pOVarEntry pOvar; + void *pData; + int status, direction = 1; + long oneCount, twoCount, lastCount, currentCount; + float varValue, startValue; + char buffer[256]; + int (*CollectFunc) (pScanData self, int iPoint) = NULL; - /* - * prepare scan object - */ - self->pScanner->pCon = pCon; - self->pScanner->pSics = pServ->pSics; - self->pScanner->iNP = 1; - self->pScanner->iMode = self->eCount; - self->pScanner->fPreset = self->fPreset; + assert(self); + assert((i >= 0) && (i < self->iVar)); + assert(pCon); - direction = findDirection(self,pOvar, pCon); - if(direction < -1){ - return direction; - } - /* - * drive to the last best position - */ - varValue = pOvar->fCenter + direction*pOvar->fStep; - status = ClimbDrive(pCon,pOvar->pName,varValue); - if(!status) - { - return DRIVEERROR; - } - lastCount = ClimbCount(self,pCon); - if(lastCount < 0) - { - return SCANERROR; - } - currentCount = lastCount; - - /* - * climb upwards as long as possible - */ - while(1) - { - pOvar->fCenter = varValue; - varValue = pOvar->fCenter + direction * pOvar->fStep; - status = ClimbDrive(pCon,pOvar->pName,varValue); - if(!status) - { - return DRIVEERROR; - } - if(SCGetInterrupt(pCon) != eContinue) - { - return SCANABORT; + /* get variable data */ + DynarGet(self->pVariables, i, &pData); + pOvar = (pOVarEntry) pData; + startValue = pOvar->fCenter; + + /* + * prepare scan object + */ + self->pScanner->pCon = pCon; + self->pScanner->pSics = pServ->pSics; + self->pScanner->iNP = 1; + self->pScanner->iMode = self->eCount; + self->pScanner->fPreset = self->fPreset; + + direction = findDirection(self, pOvar, pCon); + if (direction < -1) { + return direction; + } + /* + * drive to the last best position + */ + varValue = pOvar->fCenter + direction * pOvar->fStep; + status = ClimbDrive(pCon, pOvar->pName, varValue); + if (!status) { + return DRIVEERROR; + } + lastCount = ClimbCount(self, pCon); + if (lastCount < 0) { + return SCANERROR; + } + currentCount = lastCount; + + /* + * climb upwards as long as possible + */ + while (1) { + pOvar->fCenter = varValue; + varValue = pOvar->fCenter + direction * pOvar->fStep; + status = ClimbDrive(pCon, pOvar->pName, varValue); + if (!status) { + return DRIVEERROR; + } + if (SCGetInterrupt(pCon) != eContinue) { + return SCANABORT; + } + currentCount = ClimbCount(self, pCon); + if (currentCount < 0) { + return SCANERROR; + } + if (SCGetInterrupt(pCon) != eContinue) { + return SCANABORT; + } + snprintf(buffer, 255, "Climbing %s, value = %f, count = %ld", + pOvar->pName, varValue, currentCount); + SCWrite(pCon, buffer, eLog); + + if (currentCount <= lastCount) { + /* + * we are finished. Drive to previous position and + * break + */ + status = ClimbDrive(pCon, pOvar->pName, pOvar->fCenter); + if (!status) { + return DRIVEERROR; } - currentCount = ClimbCount(self,pCon); - if(currentCount < 0) - { - return SCANERROR; - } - if(SCGetInterrupt(pCon) != eContinue) - { - return SCANABORT; + break; + } else { + /* + * go on, we are not over the top yet + */ + lastCount = currentCount; + } + } + pOvar->fShift = ABS(startValue - pOvar->fCenter); + + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int CheckSuccess(pOptimise self) +{ + int i, iTest; + pOVarEntry pOvar; + void *pData; + + assert(self); + for (i = 0; i < self->iVar; i++) { + DynarGet(self->pVariables, i, &pData); + pOvar = (pOVarEntry) pData; + if (pOvar->fShift > pOvar->fPrecision) { + return 0; + } + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +int OptimiserRun(pOptimise self, SConnection * pCon) +{ + int i, iRet, iCycle, iRedoVar = 0; + char pBueffel[256]; + + assert(self); + + if (self->iVar < 1) { + SCWrite(pCon, "ERROR: Nothing to optimise", eError); + return 0; + } + + iRet = OptimiserInit(self, pCon); + if (!iRet) { + return iRet; + } + for (iCycle = 0; iCycle < self->iMaxCycles; iCycle++) { + sprintf(pBueffel, "Optimiser cycle %d of %d started", iCycle, + self->iMaxCycles); + SCWrite(pCon, pBueffel, eLog); + for (i = iRedoVar; i < self->iVar; i++) { + iRet = CenterVariable(self, pCon, i); + if (iRet <= 0) { + return iRet; } - snprintf(buffer,255,"Climbing %s, value = %f, count = %ld", - pOvar->pName, varValue, currentCount); - SCWrite(pCon,buffer,eLog); - - if(currentCount <= lastCount) - { - /* - * we are finished. Drive to previous position and - * break - */ - status = ClimbDrive(pCon,pOvar->pName,pOvar->fCenter); - if(!status) - { - return DRIVEERROR; - } + if (iRet == VARREDO) { + iRedoVar = i; break; } - else - { - /* - * go on, we are not over the top yet - */ - lastCount = currentCount; - } + iRedoVar = 0; + } + iRet = CheckSuccess(self); + if (iRet) { + return 1; } - pOvar->fShift = ABS(startValue - pOvar->fCenter); - - return 1; } + return MAXCYCLE; +} + /*---------------------------------------------------------------------------*/ - static int CheckSuccess(pOptimise self) - { - int i, iTest; - pOVarEntry pOvar; - void *pData; - - assert(self); - for(i = 0; i < self->iVar; i++) - { - DynarGet(self->pVariables,i,&pData); - pOvar = (pOVarEntry)pData; - if(pOvar->fShift > pOvar->fPrecision) - { - return 0; +int OptimiserClimb(pOptimise self, SConnection * pCon) +{ + int i, iRet, iCycle, iRedoVar = 0; + char pBueffel[256]; + + assert(self); + + if (self->iVar < 1) { + SCWrite(pCon, "ERROR: Nothing to optimise", eError); + return 0; + } + + iRet = OptimiserInit(self, pCon); + if (!iRet) { + return iRet; + } + for (iCycle = 0; iCycle < self->iMaxCycles; iCycle++) { + sprintf(pBueffel, "Optimiser cycle %d of %d started", iCycle, + self->iMaxCycles); + SCWrite(pCon, pBueffel, eLog); + for (i = iRedoVar; i < self->iVar; i++) { + iRet = ClimbVariable(self, pCon, i); + if (iRet <= 0) { + return iRet; } } - return 1; - } -/*---------------------------------------------------------------------------*/ - int OptimiserRun(pOptimise self, SConnection *pCon) - { - int i, iRet, iCycle, iRedoVar = 0; - char pBueffel[256]; + iRet = CheckSuccess(self); + if (iRet) { + return 1; + } + } + return MAXCYCLE; +} - assert(self); - - if(self->iVar < 1) - { - SCWrite(pCon,"ERROR: Nothing to optimise",eError); - return 0; - } - - iRet = OptimiserInit(self,pCon); - if(!iRet) - { - return iRet; - } - for(iCycle = 0; iCycle < self->iMaxCycles; iCycle++) - { - sprintf(pBueffel,"Optimiser cycle %d of %d started",iCycle, self->iMaxCycles); - SCWrite(pCon,pBueffel,eLog); - for(i = iRedoVar; i < self->iVar; i++) - { - iRet = CenterVariable(self,pCon,i); - if(iRet <= 0) - { - return iRet; - } - if(iRet == VARREDO) - { - iRedoVar = i; - break; - } - iRedoVar = 0; - } - iRet = CheckSuccess(self); - if(iRet) - { - return 1; - } - } - return MAXCYCLE; - } -/*---------------------------------------------------------------------------*/ - int OptimiserClimb(pOptimise self, SConnection *pCon) - { - int i, iRet, iCycle, iRedoVar = 0; - char pBueffel[256]; - - assert(self); - - if(self->iVar < 1) - { - SCWrite(pCon,"ERROR: Nothing to optimise",eError); - return 0; - } - - iRet = OptimiserInit(self,pCon); - if(!iRet) - { - return iRet; - } - for(iCycle = 0; iCycle < self->iMaxCycles; iCycle++) - { - sprintf(pBueffel,"Optimiser cycle %d of %d started",iCycle, self->iMaxCycles); - SCWrite(pCon,pBueffel,eLog); - for(i = iRedoVar; i < self->iVar; i++) - { - iRet = ClimbVariable(self,pCon,i); - if(iRet <= 0) - { - return iRet; - } - } - iRet = CheckSuccess(self); - if(iRet) - { - return 1; - } - } - return MAXCYCLE; - } /*--------------------------------------------------------------------------*/ - int MakeOptimiser(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - CommandList *pCom; - pICountable pCt = NULL; - pCounter pCount; - pOptimise pNew = NULL; - char pBueffel[256]; - int iRet; - - /* check no of args */ - if(argc < 3) - { - SCWrite(pCon,"EEROR: Not enough arguments to create optimiser",eError); - return 0; - } - - /* 2 argument must be counter name */ - pCom = FindCommand(pSics,argv[2]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: Expected counter name, cannot find %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pCt = GetCountableInterface(pCom->pData); - if(!pCt) - { - sprintf(pBueffel,"ERROR: Expected counter name, BUT %s is NO counter",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pCount = (pCounter)pCom->pData; - - pNew = CreateOptimiser(pCount); - if(!pNew) - { - SCWrite(pCon,"ERROR: cannot create Optimiser",eError); - return 0; - } - - iRet = AddCommand(pSics,argv[1],OptimiserAction, - DeleteOptimiser,pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: Duplicate Command %s NOT created", argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } +int MakeOptimiser(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom; + pICountable pCt = NULL; + pCounter pCount; + pOptimise pNew = NULL; + char pBueffel[256]; + int iRet; + + /* check no of args */ + if (argc < 3) { + SCWrite(pCon, "EEROR: Not enough arguments to create optimiser", + eError); + return 0; + } + + /* 2 argument must be counter name */ + pCom = FindCommand(pSics, argv[2]); + if (!pCom) { + sprintf(pBueffel, "ERROR: Expected counter name, cannot find %s", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pCt = GetCountableInterface(pCom->pData); + if (!pCt) { + sprintf(pBueffel, "ERROR: Expected counter name, BUT %s is NO counter", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pCount = (pCounter) pCom->pData; + + pNew = CreateOptimiser(pCount); + if (!pNew) { + SCWrite(pCon, "ERROR: cannot create Optimiser", eError); + return 0; + } + + iRet = AddCommand(pSics, argv[1], OptimiserAction, + DeleteOptimiser, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: Duplicate Command %s NOT created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} + /*-------------------------------------------------------------------------*/ - int OptimiserAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pOptimise self = NULL; - char pBueffel[1024]; - int iRet; - double d; - float fStep, fPrec, fVal; - int iStep; - - self = (pOptimise)pData; - assert(self); - assert(pCon); - - - if(argc < 2) - { - sprintf(pBueffel,"ERROR: Insufficient arguments to %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - strtolower(argv[1]); - if(strcmp(argv[1],"addvar") == 0) +int OptimiserAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pOptimise self = NULL; + char pBueffel[1024]; + int iRet; + double d; + float fStep, fPrec, fVal; + int iStep; + + self = (pOptimise) pData; + assert(self); + assert(pCon); + + + if (argc < 2) { + sprintf(pBueffel, "ERROR: Insufficient arguments to %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + strtolower(argv[1]); + if (strcmp(argv[1], "addvar") == 0) /*--------- addvar */ - { - /* check rights */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: You are not authorised to do this!",eError); - return 0; - } - /* check no of args */ - if(argc < 6) - { - sprintf(pBueffel,"ERROR: Insufficient arguments to %s addvar",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* convert arguments to types */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[3],&d); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected float value for step but got %s", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fStep = (float)d; - iRet = Tcl_GetInt(pSics->pTcl,argv[4],&iStep); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected integer value for iStep but got %s", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[5],&d); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected float value for precision but got %s", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fPrec = (float)d; - iRet = OptimiserAdd(self,argv[2],fStep,iStep,fPrec); - if(!iRet) - { - sprintf(pBueffel, - "ERROR: cannot optimise variable %s, mistyped?",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - SCSendOK(pCon); - return 1; - } + { + /* check rights */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: You are not authorised to do this!", eError); + return 0; + } + /* check no of args */ + if (argc < 6) { + sprintf(pBueffel, "ERROR: Insufficient arguments to %s addvar", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* convert arguments to types */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[3], &d); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected float value for step but got %s", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fStep = (float) d; + iRet = Tcl_GetInt(pSics->pTcl, argv[4], &iStep); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: expected integer value for iStep but got %s", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[5], &d); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: expected float value for precision but got %s", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fPrec = (float) d; + iRet = OptimiserAdd(self, argv[2], fStep, iStep, fPrec); + if (!iRet) { + sprintf(pBueffel, + "ERROR: cannot optimise variable %s, mistyped?", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + SCSendOK(pCon); + return 1; + } /*----- clear */ - else if(strcmp(argv[1],"clear") == 0) - { - /* check rights */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: You are not aurhorised to do this!",eError); - return 0; - } - OptimiserClear(self); - SCSendOK(pCon); - return 1; - } + else if (strcmp(argv[1], "clear") == 0) { + /* check rights */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: You are not aurhorised to do this!", eError); + return 0; + } + OptimiserClear(self); + SCSendOK(pCon); + return 1; + } /*-------- run */ - else if(strcmp(argv[1],"run") == 0) - { - /* check rights */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: You are not aurhorised to do this!",eError); - return 0; - } - iRet = OptimiserRun(self,pCon); - switch(iRet) - { - case PEAKLOST: - SCWrite(pCon,"ERROR: lost the peak, sorry!",eError); - return 0; - break; - case MAXCYCLE: - sprintf(pBueffel,"ERROR: could not optimise peak in %d cycles", - self->iMaxCycles); - SCWrite(pCon,pBueffel,eError); - return 0; - break; - case SCANERROR: - SCWrite(pCon,"ERROR: failed to scan the peak",eError); - return 0; - break; - case SCANABORT: - SCWrite(pCon,"ERROR: Scan was aborted, Optimiser follows",eError); - return 0; - break; - case DRIVEERROR: - SCWrite(pCon,"ERROR: Failure to drive variable to new position",eError); - return 0; - break; - case 1: - SCWrite(pCon,"At long last, I finished optimising the peak",eValue); - return 1; - break; - default: - SCWrite(pCon,"ERROR: Unidentified error krept into Optimiser",eError); - return 0; - break; - } - } + else if (strcmp(argv[1], "run") == 0) { + /* check rights */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: You are not aurhorised to do this!", eError); + return 0; + } + iRet = OptimiserRun(self, pCon); + switch (iRet) { + case PEAKLOST: + SCWrite(pCon, "ERROR: lost the peak, sorry!", eError); + return 0; + break; + case MAXCYCLE: + sprintf(pBueffel, "ERROR: could not optimise peak in %d cycles", + self->iMaxCycles); + SCWrite(pCon, pBueffel, eError); + return 0; + break; + case SCANERROR: + SCWrite(pCon, "ERROR: failed to scan the peak", eError); + return 0; + break; + case SCANABORT: + SCWrite(pCon, "ERROR: Scan was aborted, Optimiser follows", eError); + return 0; + break; + case DRIVEERROR: + SCWrite(pCon, "ERROR: Failure to drive variable to new position", + eError); + return 0; + break; + case 1: + SCWrite(pCon, "At long last, I finished optimising the peak", + eValue); + return 1; + break; + default: + SCWrite(pCon, "ERROR: Unidentified error krept into Optimiser", + eError); + return 0; + break; + } + } /*-------- climb */ - else if(strcmp(argv[1],"climb") == 0) - { - /* check rights */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: You are not aurhorised to do this!",eError); - return 0; - } - iRet = OptimiserClimb(self,pCon); - switch(iRet) - { - case PEAKLOST: - SCWrite(pCon,"ERROR: lost the peak, sorry!",eError); - return 0; - break; - case MAXCYCLE: - sprintf(pBueffel,"ERROR: could not optimise peak in %d cycles", - self->iMaxCycles); - SCWrite(pCon,pBueffel,eError); - return 0; - break; - case SCANERROR: - SCWrite(pCon,"ERROR: failed to scan the peak",eError); - return 0; - break; - case SCANABORT: - SCWrite(pCon,"ERROR: Scan was aborted, Optimiser follows",eError); - return 0; - break; - case DRIVEERROR: - SCWrite(pCon,"ERROR: Failure to drive variable to new position",eError); - return 0; - break; - case 1: - SCWrite(pCon,"At long last, I finished optimising the peak",eValue); - return 1; - break; - default: - SCWrite(pCon,"ERROR: Unidentified error krept into Optimiser",eError); - return 0; - break; - } - SCWrite(pCon,"Optimiser climbed successfully",eValue); - return 1; - } + else if (strcmp(argv[1], "climb") == 0) { + /* check rights */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: You are not aurhorised to do this!", eError); + return 0; + } + iRet = OptimiserClimb(self, pCon); + switch (iRet) { + case PEAKLOST: + SCWrite(pCon, "ERROR: lost the peak, sorry!", eError); + return 0; + break; + case MAXCYCLE: + sprintf(pBueffel, "ERROR: could not optimise peak in %d cycles", + self->iMaxCycles); + SCWrite(pCon, pBueffel, eError); + return 0; + break; + case SCANERROR: + SCWrite(pCon, "ERROR: failed to scan the peak", eError); + return 0; + break; + case SCANABORT: + SCWrite(pCon, "ERROR: Scan was aborted, Optimiser follows", eError); + return 0; + break; + case DRIVEERROR: + SCWrite(pCon, "ERROR: Failure to drive variable to new position", + eError); + return 0; + break; + case 1: + SCWrite(pCon, "At long last, I finished optimising the peak", + eValue); + return 1; + break; + default: + SCWrite(pCon, "ERROR: Unidentified error krept into Optimiser", + eError); + return 0; + break; + } + SCWrite(pCon, "Optimiser climbed successfully", eValue); + return 1; + } /* ------ count mode */ - if(strcmp(argv[1],"countmode") == 0) - { - if(argc > 2) /* set case */ - { - /* check rights */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: You are not aurhorised to do this!",eError); - return 0; - } - if(strcmp(argv[2],"timer") == 0) - { - fVal = 0.; - } - else if(strcmp(argv[2],"monitor") == 0) - { - fVal = 1.; - } - else - { - SCWrite(pCon,"ERROR: Invalid parameter for countmode",eError); - return 0; - } - OptimiserSetPar(self,"countmode",fVal); - SCSendOK(pCon); - return 1; - } - else /* get case */ - { - OptimiserGetPar(self,"countmode",&fVal); - if(fVal < 0.05) - { - sprintf(pBueffel,"%s.countmode = timer",argv[0]); - } - else - { - sprintf(pBueffel,"%s.countmode = monitor", argv[0]); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } + if (strcmp(argv[1], "countmode") == 0) { + if (argc > 2) { /* set case */ + /* check rights */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: You are not aurhorised to do this!", eError); + return 0; + } + if (strcmp(argv[2], "timer") == 0) { + fVal = 0.; + } else if (strcmp(argv[2], "monitor") == 0) { + fVal = 1.; + } else { + SCWrite(pCon, "ERROR: Invalid parameter for countmode", eError); + return 0; + } + OptimiserSetPar(self, "countmode", fVal); + SCSendOK(pCon); + return 1; + } else { /* get case */ + + OptimiserGetPar(self, "countmode", &fVal); + if (fVal < 0.05) { + sprintf(pBueffel, "%s.countmode = timer", argv[0]); + } else { + sprintf(pBueffel, "%s.countmode = monitor", argv[0]); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } /*------ can be other pars */ - else - { - if(argc > 2) /* set case */ - { - /* check rights */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: You are not aurhorised to do this!",eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&d); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected numeric value for %s but got %s", - argv[1],argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fVal = (float)d; - - iRet = OptimiserSetPar(self,argv[1],fVal); - if(iRet) - { - SCSendOK(pCon); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: parameter %s not known",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - else /* get case */ - { - iRet = OptimiserGetPar(self,argv[1],&fVal); - if(!iRet) - { - sprintf(pBueffel,"ERROR: parameter %s not known",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - sprintf(pBueffel,"%s.%s = %f",argv[0],argv[1],fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - } + else { + if (argc > 2) { /* set case */ + /* check rights */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: You are not aurhorised to do this!", eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &d); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: expected numeric value for %s but got %s", argv[1], + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fVal = (float) d; + + iRet = OptimiserSetPar(self, argv[1], fVal); + if (iRet) { + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "ERROR: parameter %s not known", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } else { /* get case */ + + iRet = OptimiserGetPar(self, argv[1], &fVal); + if (!iRet) { + sprintf(pBueffel, "ERROR: parameter %s not known", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + sprintf(pBueffel, "%s.%s = %f", argv[0], argv[1], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } +} diff --git a/optimise.h b/optimise.h index 9d73e5ea..40d292e3 100644 --- a/optimise.h +++ b/optimise.h @@ -11,13 +11,13 @@ #ifndef SICSOPTIMISE #define SICSOPTIMISE - typedef struct __OptimiseStruct *pOptimise; +typedef struct __OptimiseStruct *pOptimise; /*------------------- live & death -----------------------------------------*/ - pOptimise CreateOptimiser(pCounter pCount); - void DeleteOptimiser(void *pData); - int MakeOptimiser(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +pOptimise CreateOptimiser(pCounter pCount); +void DeleteOptimiser(void *pData); +int MakeOptimiser(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); /*------------------- operation -------------------------------------------*/ #define PEAKLOST -1 #define MAXCYCLE -2 @@ -28,17 +28,14 @@ #define VARREDO -7 - void OptimiserClear(pOptimise self); - int OptimiserAdd(pOptimise self, - char *pVarName, - float fStep, - int nStep, - float fPrecision); - int OptimiserSetPar(pOptimise self, char *name, float fVal); - int OptimiserGetPar(pOptimise self, char *name, float *fVal); +void OptimiserClear(pOptimise self); +int OptimiserAdd(pOptimise self, + char *pVarName, float fStep, int nStep, float fPrecision); +int OptimiserSetPar(pOptimise self, char *name, float fVal); +int OptimiserGetPar(pOptimise self, char *name, float *fVal); - int OptimiserRun(pOptimise self, SConnection *pCon); +int OptimiserRun(pOptimise self, SConnection * pCon); - int OptimiserAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int OptimiserAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/oscillate.c b/oscillate.c index 09be9e24..b65ba11e 100644 --- a/oscillate.c +++ b/oscillate.c @@ -14,25 +14,28 @@ #include "commandlog.h" #include "oscillate.h" -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*================== real work =========================================*/ -static void StopOscillation(pOscillator self){ +static void StopOscillation(pOscillator self) +{ assert(self != NULL); - if(self->taskID > 0){ + if (self->taskID > 0) { self->pMot->pDriver->Halt(self->pMot->pDriver); self->stopFlag = 1; self->taskID = -1; } - MotorSetPar(self->pMot,self->pCon,"accesscode",usUser); - if(self->debug > 0){ - WriteToCommandLog("oscillator>> ","Stopping"); + MotorSetPar(self->pMot, self->pCon, "accesscode", usUser); + if (self->debug > 0) { + WriteToCommandLog("oscillator>> ", "Stopping"); } } + /*-------------------------------------------------------------------*/ -static float getNextPos(pOscillator self){ +static float getNextPos(pOscillator self) +{ float pos; - if(self->nextTargetFlag == 1){ + if (self->nextTargetFlag == 1) { pos = self->upperLimit; self->nextTargetFlag = 0; } else { @@ -41,242 +44,251 @@ static float getNextPos(pOscillator self){ } return pos; } + /*-------------------------------------------------------------------*/ -static float getCurrentTarget(pOscillator self){ +static float getCurrentTarget(pOscillator self) +{ float pos; - if(self->nextTargetFlag == 1){ + if (self->nextTargetFlag == 1) { pos = self->lowerLimit; } else { pos = self->upperLimit; } return pos; } + /*---------------------------------------------------------------------*/ -static int OscillationTask(void *data){ - pOscillator self = (pOscillator)data; +static int OscillationTask(void *data) +{ + pOscillator self = (pOscillator) data; int status, code, errStatus; char error[256], message[132]; float pos, curPos; assert(self); - if(self->stopFlag == 1){ + if (self->stopFlag == 1) { return 0; } status = self->pMot->pDriver->GetStatus(self->pMot->pDriver); - switch(status){ + switch (status) { case HWFault: case HWPosFault: - self->pMot->pDriver->GetError(self->pMot->pDriver,&code,error,255); - WriteToCommandLog("oscillator>> ",error); + self->pMot->pDriver->GetError(self->pMot->pDriver, &code, error, 255); + WriteToCommandLog("oscillator>> ", error); pos = getCurrentTarget(self); - errStatus = self->pMot->pDriver->TryAndFixIt(self->pMot->pDriver,code,pos); + errStatus = + self->pMot->pDriver->TryAndFixIt(self->pMot->pDriver, code, pos); self->errorCount++; - if(errStatus == MOTFAIL){ + if (errStatus == MOTFAIL) { /* - try driving the other way on a serious error - */ + try driving the other way on a serious error + */ pos = getNextPos(self); - status = MotorRun(self->pMot,self->pCon,pos); - if(self->debug > 0){ - snprintf(message,131,"Started oscillation to %f, ret code = %d", - pos,status); - WriteToCommandLog("oscillator>>",message); + status = MotorRun(self->pMot, self->pCon, pos); + if (self->debug > 0) { + snprintf(message, 131, "Started oscillation to %f, ret code = %d", + pos, status); + WriteToCommandLog("oscillator>>", message); } } break; case HWWarn: - MotorGetSoftPosition(self->pMot,self->pCon,&curPos); + MotorGetSoftPosition(self->pMot, self->pCon, &curPos); pos = getCurrentTarget(self); - if(ABS(curPos - pos) < .5){ - status = MotorRun(self->pMot,self->pCon,getNextPos(self)); - } + if (ABS(curPos - pos) < .5) { + status = MotorRun(self->pMot, self->pCon, getNextPos(self)); + } break; case HWBusy: break; case HWIdle: pos = getNextPos(self); - status = MotorRun(self->pMot,self->pCon,pos); - if(status == OKOK){ + status = MotorRun(self->pMot, self->pCon, pos); + if (status == OKOK) { self->pMot->pDrivInt->iErrorCount = 0; } - if(self->debug > 0){ - snprintf(message,131,"Started oscillation to %f, ret code = %d", - pos,status); - WriteToCommandLog("oscillator>>",message); + if (self->debug > 0) { + snprintf(message, 131, "Started oscillation to %f, ret code = %d", + pos, status); + WriteToCommandLog("oscillator>>", message); } } return 1; } + /*--------------------------------------------------------------------*/ -static int StartOscillation(pOscillator self, SConnection *pCon){ +static int StartOscillation(pOscillator self, SConnection * pCon) +{ float fval; int status; - char error[80], pBueffel[255]; + char error[80], pBueffel[255]; assert(self); - if(self->taskID > 0){ - SCWrite(pCon,"WARNING: oscillation already running",eWarning); - SCWrite(pCon,"WARNING: restarting .. ",eWarning); + if (self->taskID > 0) { + SCWrite(pCon, "WARNING: oscillation already running", eWarning); + SCWrite(pCon, "WARNING: restarting .. ", eWarning); StopOscillation(self); SicsWait(2); - } + } - MotorGetPar(self->pMot,"softlowerlim",&self->lowerLimit); + MotorGetPar(self->pMot, "softlowerlim", &self->lowerLimit); self->lowerLimit += .5; - MotorGetPar(self->pMot,"softupperlim",&self->upperLimit); + MotorGetPar(self->pMot, "softupperlim", &self->upperLimit); self->upperLimit -= .5; - MotorSetPar(self->pMot,self->pCon,"accesscode",(float)usInternal); + MotorSetPar(self->pMot, self->pCon, "accesscode", (float) usInternal); self->nextTargetFlag = 0; self->errorCount = 0; self->stopFlag = 0; /* - check reachability of limits - */ - status = MotorCheckBoundary(self->pMot,self->lowerLimit,&fval,error,79); - if(!status){ - snprintf(pBueffel,255,"ERROR: cannot reach %f: %s reported", - self->lowerLimit,error); - SCWrite(pCon,pBueffel,eError); + check reachability of limits + */ + status = + MotorCheckBoundary(self->pMot, self->lowerLimit, &fval, error, 79); + if (!status) { + snprintf(pBueffel, 255, "ERROR: cannot reach %f: %s reported", + self->lowerLimit, error); + SCWrite(pCon, pBueffel, eError); return 0; } - status = MotorCheckBoundary(self->pMot,self->upperLimit,&fval,error,79); - if(!status){ - snprintf(pBueffel,255,"ERROR: cannot reach %f: %s reported", - self->upperLimit,error); - SCWrite(pCon,pBueffel,eError); + status = + MotorCheckBoundary(self->pMot, self->upperLimit, &fval, error, 79); + if (!status) { + snprintf(pBueffel, 255, "ERROR: cannot reach %f: %s reported", + self->upperLimit, error); + SCWrite(pCon, pBueffel, eError); return 0; } /* - start task - */ + start task + */ self->taskID = TaskRegister(pServ->pTasker, - OscillationTask, - NULL, - NULL, - self, - 10); - if(self->taskID < 0){ - SCWrite(pCon,"ERROR: failed to start oscillation task",eError); + OscillationTask, NULL, NULL, self, 10); + if (self->taskID < 0) { + SCWrite(pCon, "ERROR: failed to start oscillation task", eError); return 0; } return 1; } + /*===================== life and death =================================*/ -static void KillOscillator(void *data){ - pOscillator self = (pOscillator)data; - if(self != NULL){ - if(self->pDes != NULL){ +static void KillOscillator(void *data) +{ + pOscillator self = (pOscillator) data; + if (self != NULL) { + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); } - if(self->pCon != NULL){ + if (self->pCon != NULL) { SCDeleteConnection(self->pCon); } free(self); } } + /*========================================================================*/ -int MakeOscillator(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int MakeOscillator(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pOscillator pNew = NULL; pMotor pMot = NULL; char pBueffel[132]; int status; - if(argc < 3){ - SCWrite(pCon,"ERROR: insufficient number of arguments to MakeOscilator", - eError); + if (argc < 3) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to MakeOscilator", + eError); return 0; } - pMot = FindMotor(pSics,argv[2]); - if(pMot == NULL){ - snprintf(pBueffel,131,"ERROR: %s is no motor",argv[2]); - SCWrite(pCon,pBueffel,eError); + pMot = FindMotor(pSics, argv[2]); + if (pMot == NULL) { + snprintf(pBueffel, 131, "ERROR: %s is no motor", argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } - pNew = (pOscillator)malloc(sizeof(Oscillator)); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating oscillator",eError); + pNew = (pOscillator) malloc(sizeof(Oscillator)); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating oscillator", eError); return 0; } - memset(pNew,0,sizeof(Oscillator)); + memset(pNew, 0, sizeof(Oscillator)); pNew->pDes = CreateDescriptor("Oscillator"); pNew->pMot = pMot; pNew->pCon = SCCreateDummyConnection(pSics); - if(!pNew->pDes || !pNew->pCon){ - SCWrite(pCon,"ERROR: out of memory creating oscillator",eError); + if (!pNew->pDes || !pNew->pCon) { + SCWrite(pCon, "ERROR: out of memory creating oscillator", eError); return 0; } - SCSetWriteFunc(pNew->pCon,SCFileWrite); - SCSetRights(pNew->pCon,usInternal); - - status = AddCommand(pSics,argv[1], - OscillatorWrapper, - KillOscillator, - pNew); - if(!status){ - snprintf(pBueffel,131,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); + SCSetWriteFunc(pNew->pCon, SCFileWrite); + SCSetRights(pNew->pCon, usInternal); + + status = AddCommand(pSics, argv[1], + OscillatorWrapper, KillOscillator, pNew); + if (!status) { + snprintf(pBueffel, 131, "ERROR: duplicate command %s not created", + argv[1]); + SCWrite(pCon, pBueffel, eError); return 0; } return 1; } + /*========================================================================*/ -int OscillatorWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pOscillator self = (pOscillator)pData; +int OscillatorWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pOscillator self = (pOscillator) pData; char pBueffel[256]; assert(self); - if(argc < 2){ - SCWrite(pCon,"ERROR: need start/stop argument for oscillator",eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: need start/stop argument for oscillator", + eError); return 0; } - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - + strtolower(argv[1]); - if(strcmp(argv[1],"start") == 0){ - return StartOscillation(self,pCon); - } else if(strcmp(argv[1],"stop") == 0) { + if (strcmp(argv[1], "start") == 0) { + return StartOscillation(self, pCon); + } else if (strcmp(argv[1], "stop") == 0) { StopOscillation(self); - snprintf(pBueffel,255,"Oscillation stopped with %d errors, %s", - self->errorCount, - "see commandlog for details"); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "Oscillation stopped with %d errors, %s", + self->errorCount, "see commandlog for details"); + SCWrite(pCon, pBueffel, eValue); return 1; - } else if(strcmp(argv[1],"debug") == 0) { - if(argc >= 3){ + } else if (strcmp(argv[1], "debug") == 0) { + if (argc >= 3) { self->debug = atoi(argv[2]); SCSendOK(pCon); return 1; } - snprintf(pBueffel,255,"%s.debug = %d", argv[0],self->debug); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "%s.debug = %d", argv[0], self->debug); + SCWrite(pCon, pBueffel, eValue); return 1; - } else if(strcmp(argv[1],"status") == 0) { - if(self->taskID > 0){ - snprintf(pBueffel,255,"Oscillation running, %d errors so far, %s", - self->errorCount, - " error details in commandlog"); + } else if (strcmp(argv[1], "status") == 0) { + if (self->taskID > 0) { + snprintf(pBueffel, 255, "Oscillation running, %d errors so far, %s", + self->errorCount, " error details in commandlog"); } else { - snprintf(pBueffel,255,"Oscillation stopped"); + snprintf(pBueffel, 255, "Oscillation stopped"); } - SCWrite(pCon,pBueffel,eValue); + SCWrite(pCon, pBueffel, eValue); return 1; } else { - SCWrite(pCon,"ERROR: invalid sub command for oscillator requested", - eError); + SCWrite(pCon, "ERROR: invalid sub command for oscillator requested", + eError); return 0; } return 1; } - diff --git a/oscillate.h b/oscillate.h index ddb67b5a..6ec7eae8 100644 --- a/oscillate.h +++ b/oscillate.h @@ -12,24 +12,23 @@ typedef struct { - pObjectDescriptor pDes; - pMotor pMot; - int oldRights; - float upperLimit; - float lowerLimit; - int nextTargetFlag; - long taskID; - int stopFlag; - SConnection *pCon; - int errorCount; - int debug; - } Oscillator, *pOscillator; + pObjectDescriptor pDes; + pMotor pMot; + int oldRights; + float upperLimit; + float lowerLimit; + int nextTargetFlag; + long taskID; + int stopFlag; + SConnection *pCon; + int errorCount; + int debug; +} Oscillator, *pOscillator; /*---------------------------------------------------------------------*/ -int MakeOscillator(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int OscillatorWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeOscillator(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int OscillatorWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif - diff --git a/outcode.c b/outcode.c index 42183aa9..a55ee959 100644 --- a/outcode.c +++ b/outcode.c @@ -8,22 +8,23 @@ #ifndef POUTCODE #define POUTCODE - static char *pCode[] = { - "internal", - "command", - "hwerror", - "inerror", - "status", - "value", - "start", - "finish", - "event", - "warning", - "error", - "hdbvalue", - "hdbevent", - "log", - "logerror", - NULL }; - static int iNoCodes = 13; +static char *pCode[] = { + "internal", + "command", + "hwerror", + "inerror", + "status", + "value", + "start", + "finish", + "event", + "warning", + "error", + "hdbvalue", + "hdbevent", + "log", + "logerror", + NULL +}; +static int iNoCodes = 13; #endif diff --git a/passwd.c b/passwd.c index 46e2f7ea..99c3c3ee 100644 --- a/passwd.c +++ b/passwd.c @@ -45,120 +45,110 @@ #include "passwd.h" #include "splitter.h" -typedef struct __PENTRY - { - char *name; - char *passwd; - int iCode; - struct __PENTRY *pNext; - } Pentry; - +typedef struct __PENTRY { + char *name; + char *passwd; + int iCode; + struct __PENTRY *pNext; +} Pentry; + /* -------------------------- THE DATABASE --------------------------------*/ - static Pentry *pPasswords = NULL; - +static Pentry *pPasswords = NULL; + /*=========================================================================*/ - void AddUser(char *name, char *passwd, int iCode) - { - Pentry *pNew = NULL; +void AddUser(char *name, char *passwd, int iCode) +{ + Pentry *pNew = NULL; - assert(name); - assert(passwd); - - pNew = (Pentry *)malloc(sizeof(Pentry)); - assert(pNew); + assert(name); + assert(passwd); + + pNew = (Pentry *) malloc(sizeof(Pentry)); + assert(pNew); + + pNew->name = NULL; + pNew->passwd = NULL; + pNew->name = strdup(name); + pNew->passwd = strdup(passwd); + pNew->iCode = iCode; + pNew->pNext = pPasswords; + pPasswords = pNew; +} - pNew->name = NULL; - pNew->passwd = NULL; - pNew->name = strdup(name); - pNew->passwd = strdup(passwd); - pNew->iCode = iCode; - pNew->pNext = pPasswords; - pPasswords = pNew; - } /*--------------------------------------------------------------------------*/ - int IsValidUser(char *name, char *password) - { - int iRes = -10; - Pentry *pCurrent = NULL; - - assert(pPasswords); +int IsValidUser(char *name, char *password) +{ + int iRes = -10; + Pentry *pCurrent = NULL; - if( (name == NULL) || (password == NULL) ) - { - return iRes; - } - pCurrent = pPasswords; - while(pCurrent) - { - if(strcmp(pCurrent->name,name) == 0) - { - if(strcmp(pCurrent->passwd,password) == 0) - { - return pCurrent->iCode; - } - } - pCurrent = pCurrent->pNext; - } - return iRes; - } -/* --------------------------------------------------------------------------*/ - void KillPasswd(void) - { - Pentry *pCurrent, *pTemp; - - pCurrent = pPasswords; - while(pCurrent) - { - pTemp = pCurrent->pNext; - if(pCurrent->name) - free(pCurrent->name); - if(pCurrent->passwd) - free(pCurrent->passwd); - free(pCurrent); - pCurrent = pTemp; - } - pPasswords = NULL; - } -/*-------------------------------------------------------------------------*/ - int InitPasswd(char *filename) - { - FILE *fp = NULL; - char pLine[256]; - TokenList *pList = NULL; - int iRes = 0; - - assert(filename); - fp = fopen(filename,"r"); - if(!fp) - return 0; - - while((int)fgets(pLine,255,fp) != EOF) - { - if(feof(fp)) - break; - - pList = SplitText(pLine); - if( (!pList) || (!pList->pNext) || (!pList->pNext->pNext) ) - { - printf("Invalid Passwd Entry ::\n %s \n",pLine); - continue; - } - else - { - if(pList->pNext->pNext->Type != eInt) - { - continue; - } - else - { - AddUser(pList->text, pList->pNext->text, - pList->pNext->pNext->iVal); - iRes = 1; - } - } - DeleteTokenList(pList); - pList = NULL; - } - fclose(fp); + assert(pPasswords); + + if ((name == NULL) || (password == NULL)) { return iRes; - } + } + pCurrent = pPasswords; + while (pCurrent) { + if (strcmp(pCurrent->name, name) == 0) { + if (strcmp(pCurrent->passwd, password) == 0) { + return pCurrent->iCode; + } + } + pCurrent = pCurrent->pNext; + } + return iRes; +} + +/* --------------------------------------------------------------------------*/ +void KillPasswd(void) +{ + Pentry *pCurrent, *pTemp; + + pCurrent = pPasswords; + while (pCurrent) { + pTemp = pCurrent->pNext; + if (pCurrent->name) + free(pCurrent->name); + if (pCurrent->passwd) + free(pCurrent->passwd); + free(pCurrent); + pCurrent = pTemp; + } + pPasswords = NULL; +} + +/*-------------------------------------------------------------------------*/ +int InitPasswd(char *filename) +{ + FILE *fp = NULL; + char pLine[256]; + TokenList *pList = NULL; + int iRes = 0; + + assert(filename); + fp = fopen(filename, "r"); + if (!fp) + return 0; + + while ((int) fgets(pLine, 255, fp) != EOF) { + if (feof(fp)) + break; + + pList = SplitText(pLine); + if ((!pList) || (!pList->pNext) || (!pList->pNext->pNext)) { + printf("Invalid Passwd Entry ::\n %s \n", pLine); + continue; + } else { + if (pList->pNext->pNext->Type != eInt) { + continue; + } else { + AddUser(pList->text, pList->pNext->text, + pList->pNext->pNext->iVal); + iRes = 1; + } + } + DeleteTokenList(pList); + pList = NULL; + } + fclose(fp); + return iRes; +} diff --git a/passwd.h b/passwd.h index afc59041..9aad8296 100644 --- a/passwd.h +++ b/passwd.h @@ -10,13 +10,13 @@ #ifndef MKPASSWD #define MKPASSWD - int InitPasswd(char *filename); - void AddUser(char *name, char *passwd, int iCode); - int IsValidUser(char *name, char *passwd); - /* - returns negative number if not found, iCode else - iCode is the integer rights code the user is configured - with. - */ - void KillPasswd(void); +int InitPasswd(char *filename); +void AddUser(char *name, char *passwd, int iCode); +int IsValidUser(char *name, char *passwd); + /* + returns negative number if not found, iCode else + iCode is the integer rights code the user is configured + with. + */ +void KillPasswd(void); #endif diff --git a/perfmon.c b/perfmon.c index da06ddd8..82bddcd1 100644 --- a/perfmon.c +++ b/perfmon.c @@ -45,129 +45,124 @@ #include "perfmon.h" #include "perfmon.i" /*-------------------------------------------------------------------------*/ - static void *PerfMonInter(void *pData, int iInterface) - { - pPerfMon self = NULL; - - self = (pPerfMon)pData; - assert(self); - - if(iInterface == CALLBACKINTERFACE) - { - return self->pCall; - } +static void *PerfMonInter(void *pData, int iInterface) +{ + pPerfMon self = NULL; + + self = (pPerfMon) pData; + assert(self); + + if (iInterface == CALLBACKINTERFACE) { + return self->pCall; + } + return NULL; +} + +/*--------------------------------------------------------------------------*/ +pPerfMon CreatePerfMon(int iInteg) +{ + + pPerfMon pNew = NULL; + time_t tCurrent; + + pNew = (pPerfMon) malloc(sizeof(PerfMon)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(PerfMon)); + + /* initialise Descriptor */ + pNew->pDes = CreateDescriptor("PerfMon"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + pNew->pDes->GetInterface = PerfMonInter; + + /* initalise callback */ + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pCall) { + DeleteDescriptor(pNew->pDes); + free(pNew); return NULL; } + pNew->tLast = time(&tCurrent); + pNew->tTarget = pNew->tLast + iInteg; + pNew->iInteg = iInteg; + + return pNew; +} + /*--------------------------------------------------------------------------*/ - pPerfMon CreatePerfMon(int iInteg) - { - - pPerfMon pNew = NULL; - time_t tCurrent; - - pNew = (pPerfMon)malloc(sizeof(PerfMon)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(PerfMon)); - - /* initialise Descriptor */ - pNew->pDes = CreateDescriptor("PerfMon"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - pNew->pDes->GetInterface = PerfMonInter; - - /* initalise callback */ - pNew->pCall = CreateCallBackInterface(); - if(!pNew->pCall) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - } - - pNew->tLast = time(&tCurrent); - pNew->tTarget = pNew->tLast + iInteg; - pNew->iInteg = iInteg; - - return pNew; - } +void DeletePerfMon(void *pData) +{ + pPerfMon self = NULL; + + self = (pPerfMon) pData; + assert(self); + + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + } + free(self); +} + /*--------------------------------------------------------------------------*/ - void DeletePerfMon(void *pData) - { - pPerfMon self = NULL; - - self = (pPerfMon)pData; - assert(self); - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->pCall) - { - DeleteCallBackInterface(self->pCall); - } - free(self); - } -/*--------------------------------------------------------------------------*/ - int IncrementPerfMon(pPerfMon self) - { - time_t tCurrent; - char pBueffel[80]; - - self->iCount++; - - time(&tCurrent); - if(tCurrent > self->tTarget) /* recalculation necessary */ - { - self->fCPS = (float)self->iCount / - (float)(tCurrent - self->tLast); - self->iCount = 0; - self->tLast = tCurrent; - self->tTarget = tCurrent + self->iInteg; - if(self->iLog) - { - sprintf(pBueffel,"PerfMon = %f",self->fCPS); - SICSLogWrite(pBueffel,eValue); - } - InvokeCallBack(self->pCall, VALUECHANGE, &self->fCPS); - } - return 1; - } +int IncrementPerfMon(pPerfMon self) +{ + time_t tCurrent; + char pBueffel[80]; + + self->iCount++; + + time(&tCurrent); + if (tCurrent > self->tTarget) { /* recalculation necessary */ + self->fCPS = (float) self->iCount / (float) (tCurrent - self->tLast); + self->iCount = 0; + self->tLast = tCurrent; + self->tTarget = tCurrent + self->iInteg; + if (self->iLog) { + sprintf(pBueffel, "PerfMon = %f", self->fCPS); + SICSLogWrite(pBueffel, eValue); + } + InvokeCallBack(self->pCall, VALUECHANGE, &self->fCPS); + } + return 1; +} + /*---------------------------------------------------------------------------*/ - float GetPerformance(pPerfMon self) - { - assert(self); - return self->fCPS; - } +float GetPerformance(pPerfMon self) +{ + assert(self); + return self->fCPS; +} + /*------------------- The CallBack function for interest ------------------*/ - static int InterestCallback(int iEvent, void *pEvent, void *pUser) - { - float *fPos; - SConnection *pCon; - char pBueffel[80]; - - assert(pEvent); - assert(pUser); - - fPos = (float *)pEvent; - pCon = (SConnection *)pUser; - - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } - - sprintf(pBueffel,"Performance = %f", *fPos); - SCWrite(pCon,pBueffel,eValue); - return 1; - } +static int InterestCallback(int iEvent, void *pEvent, void *pUser) +{ + float *fPos; + SConnection *pCon; + char pBueffel[80]; + + assert(pEvent); + assert(pUser); + + fPos = (float *) pEvent; + pCon = (SConnection *) pUser; + + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + sprintf(pBueffel, "Performance = %f", *fPos); + SCWrite(pCon, pBueffel, eValue); + return 1; +} + /*---------------------------------------------------------------------------- PerfMon understands this syntax: PerfMon : prints current CPS value @@ -175,84 +170,78 @@ PerfMon off : stops writing performance to ServLog PerfMon interest : makes perfmon writes any change of its value to the connection regsitering this. ------------------------------------------------------------------------------*/ - int PerfMonWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pPerfMon self = NULL; - char pBueffel[132]; - long lID; - - self = (pPerfMon)pData; - assert(self); - assert(pCon); - - argtolower(argc,argv); - if(argc < 2) /* print value */ - { - sprintf(pBueffel,"Performance = %f",self->fCPS); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - - if(strcmp(argv[1],"on") == 0) - { - self->iLog = 1; - SCSendOK(pCon); - return 1; - } - - if(strcmp(argv[1],"off") == 0) - { - self->iLog = 0; - SCSendOK(pCon); - return 1; - } - - if(strcmp(argv[1],"interest") == 0) - { - lID = RegisterCallback(self->pCall, - VALUECHANGE, InterestCallback, - SCCopyConnection(pCon), SCDeleteConnection); - SCSendOK(pCon); - return 1; - } - printf(pBueffel,"ERROR: unknown command %s",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } -/*---------------------------------------------------------------------------*/ - int PerfMonTask(void *pData) - { - pPerfMon self = NULL; - - self = (pPerfMon)pData; - assert(self); - - if(self->iEnd) - { - return 0; - } - IncrementPerfMon(self); +-----------------------------------------------------------------------------*/ +int PerfMonWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pPerfMon self = NULL; + char pBueffel[132]; + long lID; + + self = (pPerfMon) pData; + assert(self); + assert(pCon); + + argtolower(argc, argv); + if (argc < 2) { /* print value */ + sprintf(pBueffel, "Performance = %f", self->fCPS); + SCWrite(pCon, pBueffel, eValue); return 1; } -/*------------------------------------------------------------------------*/ - void PerfMonSignal(void *pUser, int iSignal, void *pEventData) - { - pPerfMon self = NULL; - int *iInt; - - self = (pPerfMon)pUser; - assert(self); - iInt = (int *)pEventData; - - if(iSignal == SICSINT) - { - iInt = (int *)pEventData; - if(*iInt == eEndServer) - { - self->iEnd = 1; - } - } + + if (strcmp(argv[1], "on") == 0) { + self->iLog = 1; + SCSendOK(pCon); + return 1; } - + + if (strcmp(argv[1], "off") == 0) { + self->iLog = 0; + SCSendOK(pCon); + return 1; + } + + if (strcmp(argv[1], "interest") == 0) { + lID = RegisterCallback(self->pCall, + VALUECHANGE, InterestCallback, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + } + printf(pBueffel, "ERROR: unknown command %s", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; +} + +/*---------------------------------------------------------------------------*/ +int PerfMonTask(void *pData) +{ + pPerfMon self = NULL; + + self = (pPerfMon) pData; + assert(self); + + if (self->iEnd) { + return 0; + } + IncrementPerfMon(self); + return 1; +} + +/*------------------------------------------------------------------------*/ +void PerfMonSignal(void *pUser, int iSignal, void *pEventData) +{ + pPerfMon self = NULL; + int *iInt; + + self = (pPerfMon) pUser; + assert(self); + iInt = (int *) pEventData; + + if (iSignal == SICSINT) { + iInt = (int *) pEventData; + if (*iInt == eEndServer) { + self->iEnd = 1; + } + } +} diff --git a/perfmon.h b/perfmon.h index 42cfae52..c4a2f2db 100644 --- a/perfmon.h +++ b/perfmon.h @@ -16,20 +16,20 @@ #line 35 "perfmon.w" - typedef struct __PerfMon *pPerfMon; +typedef struct __PerfMon *pPerfMon; /*---------------------- live and death ----------------------------------*/ - pPerfMon CreatePerfMon(int iInteg); - void DeletePerfMon(void *pData); +pPerfMon CreatePerfMon(int iInteg); +void DeletePerfMon(void *pData); /*---------------------- increment ---------------------------------------*/ - int IncrementPerfMon(pPerfMon self); +int IncrementPerfMon(pPerfMon self); /*------------------------------------------------------------------------*/ - float GetPerformance(pPerfMon self); +float GetPerformance(pPerfMon self); /*------------------------------------------------------------------------*/ - int PerfMonWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int PerfMonWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*-----------------------------------------------------------------------*/ - int PerfMonTask(void *pPerf); - void PerfMonSignal(void *pPerf, int iSignal, void *pSigData); +int PerfMonTask(void *pPerf); +void PerfMonSignal(void *pPerf, int iSignal, void *pSigData); #line 67 "perfmon.w" diff --git a/polldriv.c b/polldriv.c index da2f5119..0c800eab 100644 --- a/polldriv.c +++ b/polldriv.c @@ -16,138 +16,155 @@ #include "macro.h" #include "sicshipadaba.h" /*================ actual driver implementation =========================*/ -static int timeDue(struct __POLLDRIV *self, time_t now, SConnection *pCon){ - if(now > self->nextPoll){ - return 1; - } else { - return 0; - } +static int timeDue(struct __POLLDRIV *self, time_t now, SConnection * pCon) +{ + if (now > self->nextPoll) { + return 1; + } else { + return 0; + } } + /*------------------ HDB Driver -----------------------------------------*/ -static int pollHdb(struct __POLLDRIV *self, SConnection *pCon){ - hdbValue old, newVal; - pHdb node = NULL; - - memset(&old,0,sizeof(hdbValue)); - memset(&newVal,0,sizeof(hdbValue)); - node = (pHdb)self->objPointer; - assert(node != NULL); - old = node->value; - self->nextPoll = time(NULL) + self->pollIntervall; - if(GetHipadabaPar(node, &newVal, pCon) == 1){ - if(!compareHdbValue(old,newVal)){ - UpdateHipadabaPar(node,newVal,pCon); - } - ReleaseHdbValue(&newVal); - return 1; - } else { - return 0; +static int pollHdb(struct __POLLDRIV *self, SConnection * pCon) +{ + hdbValue old, newVal; + pHdb node = NULL; + + memset(&old, 0, sizeof(hdbValue)); + memset(&newVal, 0, sizeof(hdbValue)); + node = (pHdb) self->objPointer; + assert(node != NULL); + old = node->value; + self->nextPoll = time(NULL) + self->pollIntervall; + if (GetHipadabaPar(node, &newVal, pCon) == 1) { + if (!compareHdbValue(old, newVal)) { + UpdateHipadabaPar(node, newVal, pCon); } + ReleaseHdbValue(&newVal); + return 1; + } else { + return 0; + } } + /*-----------------------------------------------------------------------*/ -static pPollDriv makeHdbDriver(SConnection *pCon, char *objectIdentifier, - int argc, char *argv[]){ - pHdb node = NULL; - pPollDriv pNew = NULL; - - node = FindHdbNode(NULL,objectIdentifier,pCon); - if(node == NULL){ - SCWrite(pCon,"ERROR: object to poll not found",eError); - return 0; - } - pNew = malloc(sizeof(PollDriv)); - if(pNew == NULL){ - return NULL; - } - memset(pNew,0,sizeof(PollDriv)); +static pPollDriv makeHdbDriver(SConnection * pCon, char *objectIdentifier, + int argc, char *argv[]) +{ + pHdb node = NULL; + pPollDriv pNew = NULL; - - pNew->objectIdentifier = strdup(objectIdentifier); - pNew->objPointer = node; - pNew->isDue = timeDue; - pNew->poll = pollHdb; + node = FindHdbNode(NULL, objectIdentifier, pCon); + if (node == NULL) { + SCWrite(pCon, "ERROR: object to poll not found", eError); + return 0; + } + pNew = malloc(sizeof(PollDriv)); + if (pNew == NULL) { + return NULL; + } + memset(pNew, 0, sizeof(PollDriv)); - if(argc > 0){ - pNew->pollIntervall = atoi(argv[0]); - } else { - pNew->pollIntervall = 10; - } - - return pNew; -} -/*==================== script poll driver ========================*/ -static int pollScript(struct __POLLDRIV *self, SConnection *pCon){ - int status; - Tcl_Interp *pTcl = InterpGetTcl(pServ->pSics); - self->nextPoll = time(NULL) + self->pollIntervall; - - MacroPush(pCon); - status = Tcl_Eval(pTcl,(char *)self->objPointer); - MacroPop(); - if(status == 0){ - return 1; - } else { - return 0; - } -} -/*-----------------------------------------------------------------------*/ -static void killScriptObj(void *data){ - if(data != NULL){ - free(data); - } -} -/*-----------------------------------------------------------------------*/ -static pPollDriv makeScriptDriver(SConnection *pCon, char *objectIdentifier, - int argc, char *argv[]){ - pPollDriv pNew = NULL; - char scriptBuffer[512]; - - if(argc < 2){ - SCWrite(pCon, - "ERROR: need intervall and script parameter for script polling driver", eError); - return NULL; - } - - pNew = malloc(sizeof(PollDriv)); - if(pNew == NULL){ - return NULL; - } - memset(pNew,0,sizeof(PollDriv)); + pNew->objectIdentifier = strdup(objectIdentifier); + pNew->objPointer = node; + pNew->isDue = timeDue; + pNew->poll = pollHdb; + if (argc > 0) { pNew->pollIntervall = atoi(argv[0]); - memset(scriptBuffer,0,512); - Arg2Text(argc-1, &argv[1],scriptBuffer,511); - - pNew->objectIdentifier = strdup(objectIdentifier); - pNew->objPointer = strdup(scriptBuffer); - pNew->isDue = timeDue; - pNew->poll = pollScript; - pNew->killObjPointer = killScriptObj; + } else { + pNew->pollIntervall = 10; + } + + return pNew; +} + +/*==================== script poll driver ========================*/ +static int pollScript(struct __POLLDRIV *self, SConnection * pCon) +{ + int status; + Tcl_Interp *pTcl = InterpGetTcl(pServ->pSics); + + self->nextPoll = time(NULL) + self->pollIntervall; + + MacroPush(pCon); + status = Tcl_Eval(pTcl, (char *) self->objPointer); + MacroPop(); + if (status == 0) { + return 1; + } else { + return 0; + } +} + +/*-----------------------------------------------------------------------*/ +static void killScriptObj(void *data) +{ + if (data != NULL) { + free(data); + } +} + +/*-----------------------------------------------------------------------*/ +static pPollDriv makeScriptDriver(SConnection * pCon, + char *objectIdentifier, int argc, + char *argv[]) +{ + pPollDriv pNew = NULL; + char scriptBuffer[512]; + + if (argc < 2) { + SCWrite(pCon, + "ERROR: need intervall and script parameter for script polling driver", + eError); + return NULL; + } + + pNew = malloc(sizeof(PollDriv)); + if (pNew == NULL) { + return NULL; + } + memset(pNew, 0, sizeof(PollDriv)); + + pNew->pollIntervall = atoi(argv[0]); + memset(scriptBuffer, 0, 512); + Arg2Text(argc - 1, &argv[1], scriptBuffer, 511); + + pNew->objectIdentifier = strdup(objectIdentifier); + pNew->objPointer = strdup(scriptBuffer); + pNew->isDue = timeDue; + pNew->poll = pollScript; + pNew->killObjPointer = killScriptObj; + + return pNew; +} - return pNew; -} /*================ external interface ====================================*/ -pPollDriv makePollDriver(SConnection *pCon, char *driver, - char *objectIdentifier, int argc, char *argv[]){ - - strtolower(driver); - if(strcmp(driver,"hdb") == 0) { - return makeHdbDriver(pCon,objectIdentifier, argc, argv); - } else if(strcmp(driver,"script") == 0){ - return makeScriptDriver(pCon,objectIdentifier, argc, argv); - } else { - SCWrite(pCon,"ERROR: polling driver type unknown",eError); - return NULL; - } +pPollDriv makePollDriver(SConnection * pCon, char *driver, + char *objectIdentifier, int argc, char *argv[]) +{ + + strtolower(driver); + if (strcmp(driver, "hdb") == 0) { + return makeHdbDriver(pCon, objectIdentifier, argc, argv); + } else if (strcmp(driver, "script") == 0) { + return makeScriptDriver(pCon, objectIdentifier, argc, argv); + } else { + SCWrite(pCon, "ERROR: polling driver type unknown", eError); + return NULL; + } } + /*------------------------------------------------------------------------*/ -void deletePollDriv(pPollDriv self){ - if(self->objectIdentifier != NULL){ - free(self->objectIdentifier); - } - if(self->objPointer != NULL && self->killObjPointer != NULL){ - self->killObjPointer(self->objPointer); - } - free(self); +void deletePollDriv(pPollDriv self) +{ + if (self->objectIdentifier != NULL) { + free(self->objectIdentifier); + } + if (self->objPointer != NULL && self->killObjPointer != NULL) { + self->killObjPointer(self->objPointer); + } + free(self); } diff --git a/polldriv.h b/polldriv.h index 409afb2d..3100dba0 100644 --- a/polldriv.h +++ b/polldriv.h @@ -11,18 +11,18 @@ #include #include /*==================== a data structure ===================================*/ -typedef struct __POLLDRIV{ - char *objectIdentifier; /* the object identifier */ - void *objPointer; /* a pointer to the object */ - time_t nextPoll; /* next polling time */ - int pollIntervall; /* poll intervall */ - int (*isDue)(struct __POLLDRIV *self, time_t now, SConnection *pCon); - /* function called to determine if this object must be polled */ - int (*poll)(struct __POLLDRIV *self, SConnection *pCon); - /* the actual polling function */ - void (*killObjPointer)(void *data); - /* a function to possibly kill the objPointer. Can be NULL */ -}PollDriv, *pPollDriv; +typedef struct __POLLDRIV { + char *objectIdentifier; /* the object identifier */ + void *objPointer; /* a pointer to the object */ + time_t nextPoll; /* next polling time */ + int pollIntervall; /* poll intervall */ + int (*isDue) (struct __POLLDRIV * self, time_t now, SConnection * pCon); + /* function called to determine if this object must be polled */ + int (*poll) (struct __POLLDRIV * self, SConnection * pCon); + /* the actual polling function */ + void (*killObjPointer) (void *data); + /* a function to possibly kill the objPointer. Can be NULL */ +} PollDriv, *pPollDriv; /*==================== the interface =====================================*/ /* * make a poll driver @@ -33,12 +33,12 @@ typedef struct __POLLDRIV{ * @param *argv[] Additional parameters. * @return NULL on failure or a PollDriv strucure else. */ -pPollDriv makePollDriver(SConnection *pCon, char *driver, - char *objectIdentifier, int argc, char *argv[]); +pPollDriv makePollDriver(SConnection * pCon, char *driver, + char *objectIdentifier, int argc, char *argv[]); /** * free all memory associated with this poll driver * @param self The structure to delete */ -void deletePollDriv(pPollDriv self); - -#endif /*POLLDRIV_H_*/ +void deletePollDriv(pPollDriv self); + +#endif /*POLLDRIV_H_ */ diff --git a/protocol.c b/protocol.c index eb429c6c..2a80b99a 100644 --- a/protocol.c +++ b/protocol.c @@ -24,51 +24,51 @@ #define NUMPROS 6 #define PROLISTLEN 7 typedef struct __Protocol { - pObjectDescriptor pDes; /* required as first field */ - char *name; /* protocol handler name */ - char *version; /* protocol version string */ - int iNumPros; /* number of valid protocols? */ - writeFunc defaultWriter; /* default write function */ - int isDefaultSet; - char *pProList[PROLISTLEN]; /* list of valid protocols? */ + pObjectDescriptor pDes; /* required as first field */ + char *name; /* protocol handler name */ + char *version; /* protocol version string */ + int iNumPros; /* number of valid protocols? */ + writeFunc defaultWriter; /* default write function */ + int isDefaultSet; + char *pProList[PROLISTLEN]; /* list of valid protocols? */ } Protocol; -char *pEventType[]={ -"VALUECHANGE", /* 0 */ -"MOTDRIVE", /* 1 */ -"MONITOR", /* 2 */ -"ROTSTART", /* 3 */ -"ROTMOVE", /* 4 */ -"SCANEND", /* 5 */ -"SCANSTART", /* 6 */ -"SCANPOINT", /* 7 */ -"WLCHANGE", /* 8 */ -"REFLECTIONDONE", /* 9 */ -"COUNTSTART", /* 10 */ -"COUNTEND", /* 11 */ -"FILELOADED", /* 12 */ -"MOTEND", /* 13 */ -"BATCHSTART", /* 14 */ -"BATCHAREA", /* 15 */ -"BATCHEND", /* 16 */ -"DRIVSTAT", /* 17 */ -"STATUS", /* 18 */ -"POSITION" /* 19 Motor position events, ffr */ +char *pEventType[] = { + "VALUECHANGE", /* 0 */ + "MOTDRIVE", /* 1 */ + "MONITOR", /* 2 */ + "ROTSTART", /* 3 */ + "ROTMOVE", /* 4 */ + "SCANEND", /* 5 */ + "SCANSTART", /* 6 */ + "SCANPOINT", /* 7 */ + "WLCHANGE", /* 8 */ + "REFLECTIONDONE", /* 9 */ + "COUNTSTART", /* 10 */ + "COUNTEND", /* 11 */ + "FILELOADED", /* 12 */ + "MOTEND", /* 13 */ + "BATCHSTART", /* 14 */ + "BATCHAREA", /* 15 */ + "BATCHEND", /* 16 */ + "DRIVSTAT", /* 17 */ + "STATUS", /* 18 */ + "POSITION" /* 19 Motor position events, ffr */ }; -char *pStatus[]={ -"UNSET", -"OKOK", /* 1 */ -"HWIdle", /* 2 */ -"HWBusy", /* 3 */ -"HWFault", /* 4 */ -"HWPosFault", /* 5 */ -"HWCrash", /* 6 */ -"NOMEMORY", /* 7 */ -"HWNoBeam", /* 8 */ -"HWPause", /* 9 */ -"HWWarn", /* 10 */ -"HWRedo", /* 11 */ +char *pStatus[] = { + "UNSET", + "OKOK", /* 1 */ + "HWIdle", /* 2 */ + "HWBusy", /* 3 */ + "HWFault", /* 4 */ + "HWPosFault", /* 5 */ + "HWCrash", /* 6 */ + "NOMEMORY", /* 7 */ + "HWNoBeam", /* 8 */ + "HWPause", /* 9 */ + "HWWarn", /* 10 */ + "HWRedo", /* 11 */ }; typedef struct __Protocol *pProtocol; @@ -84,751 +84,737 @@ typedef struct __Protocol *pProtocol; */ pProtocol CreateProtocol(void); -static int ProtocolOptions(SConnection* pCon, pProtocol pPro); -static int ProtocolHelp(SConnection* pCon, Protocol* pPro); -static int ProtocolSet(SConnection* pCon, Protocol* pPro, char *pProName); -static int ProtocolList(SConnection* pCon, Protocol* pPro); -int ProtocolAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +static int ProtocolOptions(SConnection * pCon, pProtocol pPro); +static int ProtocolHelp(SConnection * pCon, Protocol * pPro); +static int ProtocolSet(SConnection * pCon, Protocol * pPro, + char *pProName); +static int ProtocolList(SConnection * pCon, Protocol * pPro); +int ProtocolAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); static int EnumChoice(char *pList[], int iLength, char *pInput); -static int InitDefaultProtocol(SConnection* pCon, Protocol *pPro); +static int InitDefaultProtocol(SConnection * pCon, Protocol * pPro); /* Signatures for protocol writers implemented in this file */ -int SCWriteSycamore(SConnection *pCon, char *pBuffer, int iOut); -int SCWriteJSON_String(SConnection *pCon, char *pBuffer, int iOut); +int SCWriteSycamore(SConnection * pCon, char *pBuffer, int iOut); +int SCWriteJSON_String(SConnection * pCon, char *pBuffer, int iOut); /*--------------------------------------------------------------------------*/ pProtocol CreateProtocol(void) { - int i, iNumPros = NUMPROS; - char *pPros[] = {"default", - "normal", - "withcode", - "sycamore", - "json", - "act", - NULL - }; - pProtocol pNew = NULL; + int i, iNumPros = NUMPROS; + char *pPros[] = { "default", + "normal", + "withcode", + "sycamore", + "json", + "act", + NULL + }; + pProtocol pNew = NULL; - pNew = (pProtocol)malloc(sizeof(Protocol)); - if(!pNew) - { - return NULL; - } - pNew->pDes = CreateDescriptor("Protocol"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - - pNew->name = strdup("protocol"); - pNew->version = strdup("1.0"); - pNew->iNumPros = iNumPros; + pNew = (pProtocol) malloc(sizeof(Protocol)); + if (!pNew) { + return NULL; + } + pNew->pDes = CreateDescriptor("Protocol"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + + pNew->name = strdup("protocol"); + pNew->version = strdup("1.0"); + pNew->iNumPros = iNumPros; // pNew->pProList = (char *)malloc(sizeof(pPros)); - for(i=0;ipProList[i] = strdup(pPros[i]); - } - pNew->pProList[i] = NULL; - pNew->isDefaultSet = 0; - - return pNew; + for (i = 0; i < iNumPros; i++) { + pNew->pProList[i] = strdup(pPros[i]); + } + pNew->pProList[i] = NULL; + pNew->isDefaultSet = 0; + + return pNew; } -/*-------------------------------------------------------------------------*/ +/*-------------------------------------------------------------------------*/ void DeleteProtocol(void *self) { - int i; - pProtocol pOld = (pProtocol)self; - - if(NULL==pOld) - { - return; + int i; + pProtocol pOld = (pProtocol) self; + + if (NULL == pOld) { + return; + } + if (pOld->name) { + free(pOld->name); + } + if (pOld->pDes) { + DeleteDescriptor(pOld->pDes); + } + if (pOld->version) { + free(pOld->version); + } + if (pOld->pProList) { + i = 0; + while (NULL != pOld->pProList[i]) { + free(pOld->pProList[i]); + i++; } - if(pOld->name) - { - free(pOld->name); - } - if(pOld->pDes) - { - DeleteDescriptor(pOld->pDes); - } - if(pOld->version) - { - free(pOld->version); - } - if(pOld->pProList) - { - i = 0; - while(NULL!=pOld->pProList[i]) - { - free(pOld->pProList[i]); - i++; - } - } - free(pOld); + } + free(pOld); } + /*------------------------------------------------------------------*/ -static int ContextDo(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - SConnection *comCon = NULL; - char buffer[1024]; - char *command; - int status; +static int ContextDo(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + SConnection *comCon = NULL; + char buffer[1024]; + char *command; + int status; - if(argc < 3){ - SCWrite(pCon,"ERROR: insufficient arguments to contextdo",eError); - return 0; - } - - comCon = SCCopyConnection(pCon); - if(comCon == NULL){ - SCWrite(pCon,"EROOR: out of memory in contextdo", eError); - return 0; - } - status = Tcl_GetInt(pSics->pTcl,argv[1],&comCon->transID); - if(status != TCL_OK){ - snprintf(buffer,1023,"ERROR: failed to convert %s to transaction ID", argv[1]); - SCWrite(pCon,buffer,eError); - return 0; - } - strncpy(comCon->deviceID,argv[2],SCDEVIDLEN); - memset(buffer,0,sizeof(buffer)); - command = Arg2Tcl(argc-2,&argv[2],buffer,sizeof buffer); - if (!command) { - SCWrite(pCon,"ERROR: no more memory",eError); - return 0; - } - status = InterpExecute(pSics,comCon,command); - if (command != buffer) free(command); - SCDeleteConnection(comCon); - return status; + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient arguments to contextdo", eError); + return 0; + } + + comCon = SCCopyConnection(pCon); + if (comCon == NULL) { + SCWrite(pCon, "EROOR: out of memory in contextdo", eError); + return 0; + } + status = Tcl_GetInt(pSics->pTcl, argv[1], &comCon->transID); + if (status != TCL_OK) { + snprintf(buffer, 1023, "ERROR: failed to convert %s to transaction ID", + argv[1]); + SCWrite(pCon, buffer, eError); + return 0; + } + strncpy(comCon->deviceID, argv[2], SCDEVIDLEN); + memset(buffer, 0, sizeof(buffer)); + command = Arg2Tcl(argc - 2, &argv[2], buffer, sizeof buffer); + if (!command) { + SCWrite(pCon, "ERROR: no more memory", eError); + return 0; + } + status = InterpExecute(pSics, comCon, command); + if (command != buffer) + free(command); + SCDeleteConnection(comCon); + return status; } + /*--------------------------------------------------------------------------*/ -int InstallProtocol(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) +int InstallProtocol(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) { - pProtocol pNew = NULL; - pNew = CreateProtocol(); - if(NULL==pNew) - { - SCWrite(pCon,"No memory to create Protocol",eError); - return 0; - } - AddCommand(pSics,"Protocol",ProtocolAction,DeleteProtocol,pNew); - AddCommand(pSics,"contextdo",ContextDo,NULL,NULL); - SCSendOK(pCon); - return 1; -} -/*------------------------------------------------------------------------*/ -void MakeProtocol(SicsInterp *pSics){ - pProtocol pNew = NULL; - pNew = CreateProtocol(); - if(NULL!= pNew) - { - AddCommand(pSics,"Protocol",ProtocolAction,DeleteProtocol,pNew); - AddCommand(pSics,"contextdo",ContextDo,NULL,NULL); - } -} -/*------------------------------------------------------------------------*/ -static int ProtocolOptions(SConnection* pCon, pProtocol pPro) -{ - int i; - char pBuffer[80]; - for(i=0;iiNumPros;i++) - { - sprintf(pBuffer,"Protocol[%d] = %s",i,pPro->pProList[i]); - SCWrite(pCon,pBuffer,eValue); - } - return 1; + pProtocol pNew = NULL; + pNew = CreateProtocol(); + if (NULL == pNew) { + SCWrite(pCon, "No memory to create Protocol", eError); + return 0; + } + AddCommand(pSics, "Protocol", ProtocolAction, DeleteProtocol, pNew); + AddCommand(pSics, "contextdo", ContextDo, NULL, NULL); + SCSendOK(pCon); + return 1; } /*------------------------------------------------------------------------*/ -static int ProtocolHelp(SConnection* pCon, Protocol* pPro) +void MakeProtocol(SicsInterp * pSics) { - SCWrite(pCon, - "Usage: protocol {help|list|options|reset} | set protocolName", - eValue); - return 1; + pProtocol pNew = NULL; + pNew = CreateProtocol(); + if (NULL != pNew) { + AddCommand(pSics, "Protocol", ProtocolAction, DeleteProtocol, pNew); + AddCommand(pSics, "contextdo", ContextDo, NULL, NULL); + } } /*------------------------------------------------------------------------*/ -static int ProtocolSet(SConnection* pCon, Protocol* pPro, char *pProName) +static int ProtocolOptions(SConnection * pCon, pProtocol pPro) { - SConnection *pMaster = NULL; - - int proID; - if(!SCVerifyConnection(pCon)) - { - return 0; - } - pMaster = SCfindMaster(pCon); - assert(pMaster != NULL); - - /* lazy initialisation of defaultWriter since connection is verified */ - InitDefaultProtocol(pCon,pPro); - - /* Do not die if no data */ - if(NULL == pProName) - { - return 0; - } - - /* check list of protocols for valid name and assign functions based */ - /* on match of pProName */ - proID = EnumChoice(pPro->pProList,pPro->iNumPros,pProName); - switch(proID) - { - case -1: /* invalid */ - return 0; - break; - - case 1: /* normal (connection start default) */ - SCSetWriteFunc(pMaster,SCNormalWrite); - SCSetWriteFunc(pCon,SCNormalWrite); - break; - - case 2: /* outcodes */ - SCSetWriteFunc(pMaster,SCWriteWithOutcode); - SCSetWriteFunc(pCon,SCWriteWithOutcode); - break; - - case 3: /* sycamore */ - SCSetWriteFunc(pMaster,SCWriteSycamore); - SCSetWriteFunc(pCon,SCWriteSycamore); - break; - case 4: /* json */ - SCSetWriteFunc(pCon,SCWriteJSON_String); - SCSetWriteFunc(pMaster,SCWriteJSON_String); - break; - case 5: - SCSetWriteFunc(pMaster,SCACTWrite); - SCSetWriteFunc(pCon,SCACTWrite); - break; - case 0: /* default = psi_sics */ - default: - SCSetWriteFunc(pMaster,pPro->defaultWriter); - SCSetWriteFunc(pCon,pPro->defaultWriter); - break; - } - pCon->iProtocolID = proID; - pMaster->iProtocolID = proID; - SCSendOK(pCon); - return 1; + int i; + char pBuffer[80]; + for (i = 0; i < pPro->iNumPros; i++) { + sprintf(pBuffer, "Protocol[%d] = %s", i, pPro->pProList[i]); + SCWrite(pCon, pBuffer, eValue); + } + return 1; } /*------------------------------------------------------------------------*/ -int ProtocolGet(SConnection* pCon, void* pData, char *pProName, int len) +static int ProtocolHelp(SConnection * pCon, Protocol * pPro) +{ + SCWrite(pCon, + "Usage: protocol {help|list|options|reset} | set protocolName", + eValue); + return 1; +} + +/*------------------------------------------------------------------------*/ +static int ProtocolSet(SConnection * pCon, Protocol * pPro, char *pProName) +{ + SConnection *pMaster = NULL; + + int proID; + if (!SCVerifyConnection(pCon)) { + return 0; + } + pMaster = SCfindMaster(pCon); + assert(pMaster != NULL); + + /* lazy initialisation of defaultWriter since connection is verified */ + InitDefaultProtocol(pCon, pPro); + + /* Do not die if no data */ + if (NULL == pProName) { + return 0; + } + + /* check list of protocols for valid name and assign functions based */ + /* on match of pProName */ + proID = EnumChoice(pPro->pProList, pPro->iNumPros, pProName); + switch (proID) { + case -1: /* invalid */ + return 0; + break; + + case 1: /* normal (connection start default) */ + SCSetWriteFunc(pMaster, SCNormalWrite); + SCSetWriteFunc(pCon, SCNormalWrite); + break; + + case 2: /* outcodes */ + SCSetWriteFunc(pMaster, SCWriteWithOutcode); + SCSetWriteFunc(pCon, SCWriteWithOutcode); + break; + + case 3: /* sycamore */ + SCSetWriteFunc(pMaster, SCWriteSycamore); + SCSetWriteFunc(pCon, SCWriteSycamore); + break; + case 4: /* json */ + SCSetWriteFunc(pCon, SCWriteJSON_String); + SCSetWriteFunc(pMaster, SCWriteJSON_String); + break; + case 5: + SCSetWriteFunc(pMaster, SCACTWrite); + SCSetWriteFunc(pCon, SCACTWrite); + break; + case 0: /* default = psi_sics */ + default: + SCSetWriteFunc(pMaster, pPro->defaultWriter); + SCSetWriteFunc(pCon, pPro->defaultWriter); + break; + } + pCon->iProtocolID = proID; + pMaster->iProtocolID = proID; + SCSendOK(pCon); + return 1; +} + +/*------------------------------------------------------------------------*/ +int ProtocolGet(SConnection * pCon, void *pData, char *pProName, int len) { int Index; - Protocol *pPro = (Protocol *)pData; - if(!SCVerifyConnection(pCon)) - { - return 0; - } - - if(pData == NULL) - { - pCon->iProtocolID = 0; - return 1; - } - - /* lazy initialisation of defaultWriter since connection is verified */ - if(0==pPro->isDefaultSet) - { - pPro->defaultWriter = SCGetWriteFunc(pCon); - pPro->isDefaultSet = 1; - pCon->iProtocolID = 0; - } - strncpy(pProName, pPro->pProList[pCon->iProtocolID], len); - return 1; -#if 0 - Index = pCon->iProtocolID; + Protocol *pPro = (Protocol *) pData; + if (!SCVerifyConnection(pCon)) { + return 0; + } - /* check list of protocols for valid name */ - switch(Index) - { - case 0: /* default = psi_sics */ - case 1: /* normal (connection start default) */ - case 2: /* outcodes */ - case 3: /* sycamore */ - case 4: /* json */ - case 5: /* act */ - pProName = pPro->pProList[Index]; - return 1; - break; - default: - return 0; - break; - } + if (pData == NULL) { + pCon->iProtocolID = 0; + return 1; + } + + /* lazy initialisation of defaultWriter since connection is verified */ + if (0 == pPro->isDefaultSet) { + pPro->defaultWriter = SCGetWriteFunc(pCon); + pPro->isDefaultSet = 1; + pCon->iProtocolID = 0; + } + strncpy(pProName, pPro->pProList[pCon->iProtocolID], len); + return 1; +#if 0 + Index = pCon->iProtocolID; + + /* check list of protocols for valid name */ + switch (Index) { + case 0: /* default = psi_sics */ + case 1: /* normal (connection start default) */ + case 2: /* outcodes */ + case 3: /* sycamore */ + case 4: /* json */ + case 5: /* act */ + pProName = pPro->pProList[Index]; + return 1; + break; + default: + return 0; + break; + } #endif } /*------------------------------------------------------------------------*/ -static int ProtocolList(SConnection* pCon, Protocol* pPro) +static int ProtocolList(SConnection * pCon, Protocol * pPro) { - SCWrite(pCon, - "Usage: protocol {help|list|options|reset} | set protocolName", - eValue); - return 1; + SCWrite(pCon, + "Usage: protocol {help|list|options|reset} | set protocolName", + eValue); + return 1; } /*-------------------------------------------------------------------------*/ -int ProtocolAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) +int ProtocolAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) { - int iRet; - char **argx; - FuPaResult PaRes; - pProtocol pPro = NULL; - - const int iNumCmds = 5; - FuncTemplate CommandTemplate[] = { - {"help",0,{0,0}}, - {"list",0,{0,0}}, - {"options",0,{0,0}}, - {"set",1,{FUPATEXT}}, - {"reset",0,{0,0}}, - {NULL} - }; + int iRet; + char **argx; + FuPaResult PaRes; + pProtocol pPro = NULL; - assert(pCon != NULL); - assert(pSics != NULL); - pPro = (pProtocol)pData; - assert(pPro != NULL); - - /* You need to have User level access rights to use this facility */ - if(!SCMatchRights(pCon,usSpy)) - { - return 0; - } - - /* parse function args */ - argtolower(argc,argv); - argx = &argv[1]; - iRet = EvaluateFuPa((pFuncTemplate)&CommandTemplate,iNumCmds,argc-1,argx,&PaRes); + const int iNumCmds = 5; + FuncTemplate CommandTemplate[] = { + {"help", 0, {0, 0}}, + {"list", 0, {0, 0}}, + {"options", 0, {0, 0}}, + {"set", 1, {FUPATEXT}}, + {"reset", 0, {0, 0}}, + {NULL} + }; - /* if invalid (iRet < 0) then default to "help" command */ - - switch(iRet) - { - case 1: /* list */ - iRet = ProtocolList(pCon,pPro); - break; - case 2: /* options */ - iRet = ProtocolOptions(pCon,pPro); - break; - case 3: /* set */ - iRet = ProtocolSet(pCon,pPro,PaRes.Arg[0].text); - break; - case 4: /* reset */ - iRet = ProtocolSet(pCon,pPro,"default"); - break; - case 0: /* help */ - default: - iRet = ProtocolHelp(pCon,pPro); - break; - } - return iRet; + assert(pCon != NULL); + assert(pSics != NULL); + pPro = (pProtocol) pData; + assert(pPro != NULL); + + /* You need to have User level access rights to use this facility */ + if (!SCMatchRights(pCon, usSpy)) { + return 0; + } + + /* parse function args */ + argtolower(argc, argv); + argx = &argv[1]; + iRet = + EvaluateFuPa((pFuncTemplate) & CommandTemplate, iNumCmds, argc - 1, + argx, &PaRes); + + /* if invalid (iRet < 0) then default to "help" command */ + + switch (iRet) { + case 1: /* list */ + iRet = ProtocolList(pCon, pPro); + break; + case 2: /* options */ + iRet = ProtocolOptions(pCon, pPro); + break; + case 3: /* set */ + iRet = ProtocolSet(pCon, pPro, PaRes.Arg[0].text); + break; + case 4: /* reset */ + iRet = ProtocolSet(pCon, pPro, "default"); + break; + case 0: /* help */ + default: + iRet = ProtocolHelp(pCon, pPro); + break; + } + return iRet; } /*-------------------------------------------------------------------------*/ static int EnumChoice(char *pList[], int iLength, char *pInput) { - int i; - int iRet = -1; - - for(i=0;iisDefaultSet) - { - pPro->defaultWriter = SCGetWriteFunc(pCon); - pPro->isDefaultSet = 1; - pCon->iProtocolID = 0; - } - return pPro->isDefaultSet; -} + if (NULL == pCon) { + return 0; + } + + /* lazy initialisation of defaultWriter since connection is verified */ + if (0 == pPro->isDefaultSet) { + pPro->defaultWriter = SCGetWriteFunc(pCon); + pPro->isDefaultSet = 1; + pCon->iProtocolID = 0; + } + return pPro->isDefaultSet; +} + /*---------------------------------------------------------------------*/ -void sycformat(char *tag, OutCode msgFlag, pDynString msgString, pDynString msgOut) { - DynStringConcat(msgOut," "); +void sycformat(char *tag, OutCode msgFlag, pDynString msgString, + pDynString msgOut) +{ + DynStringConcat(msgOut, " "); switch (msgFlag) { - eEvent: + eEvent: break; - eFinish: + eFinish: + break; + default: + DynStringConcat(msgOut, tag); + DynStringConcat(msgOut, "={"); + DynStringConcat(msgOut, GetCharArray(msgString)); + DynStringConcat(msgOut, "}"); break; - default: - DynStringConcat(msgOut,tag); - DynStringConcat(msgOut,"={"); - DynStringConcat(msgOut,GetCharArray(msgString)); - DynStringConcat(msgOut,"}"); - break; } } -int SCWriteSycamore(SConnection *pCon, char *pBuffer, int iOut) +int SCWriteSycamore(SConnection * pCon, char *pBuffer, int iOut) { - int iRet; - char pBueffel[MAXMSG], *pBufferFrom, *pBufferTo; - long taskID = 0; + int iRet; + char pBueffel[MAXMSG], *pBufferFrom, *pBufferTo; + long taskID = 0; /* char pPrefix[40];*/ - pDynString pMsg = NULL; - pDynString pMsgString = NULL; - commandContext comCon; + pDynString pMsg = NULL; + pDynString pMsgString = NULL; + commandContext comCon; - if (strlen(pBuffer) == 0) { - return 0; - } - /* Strip \r and \n */ - for (pBufferFrom=pBufferTo=pBuffer; ; pBufferFrom++) { - if (*pBufferFrom == '\r' || *pBufferFrom == '\n') - continue; - *pBufferTo = *pBufferFrom; - if (*pBufferTo == '\0') - break; - pBufferTo++; - } + if (strlen(pBuffer) == 0) { + return 0; + } + /* Strip \r and \n */ + for (pBufferFrom = pBufferTo = pBuffer;; pBufferFrom++) { + if (*pBufferFrom == '\r' || *pBufferFrom == '\n') + continue; + *pBufferTo = *pBufferFrom; + if (*pBufferTo == '\0') + break; + pBufferTo++; + } - if(!SCVerifyConnection(pCon)) - { - return 0; - } + if (!SCVerifyConnection(pCon)) { + return 0; + } - /* log it for any case */ - if(pCon->pSock) - { - iRet = pCon->pSock->sockid; - } - else - { - iRet = 0; - } - sprintf(pBueffel,"Next line intended for socket: %d",iRet); - SICSLogWrite(pBueffel,eInternal); - SICSLogWrite(pBuffer,iOut); - - /* write to commandlog if user or manager privilege */ - if(SCGetRights(pCon) <= usUser) - { - WriteToCommandLogId(NULL,iRet,pBuffer); - } - - /* put it into the interpreter if present */ - if(SCinMacro(pCon)) - { - InterpWrite(pServ->pSics,pBuffer); - /* print it to client if error message */ - /* FIXME should report errors via sycamore + /* log it for any case */ + if (pCon->pSock) { + iRet = pCon->pSock->sockid; + } else { + iRet = 0; + } + sprintf(pBueffel, "Next line intended for socket: %d", iRet); + SICSLogWrite(pBueffel, eInternal); + SICSLogWrite(pBuffer, iOut); + + /* write to commandlog if user or manager privilege */ + if (SCGetRights(pCon) <= usUser) { + WriteToCommandLogId(NULL, iRet, pBuffer); + } + + /* put it into the interpreter if present */ + if (SCinMacro(pCon)) { + InterpWrite(pServ->pSics, pBuffer); + /* print it to client if error message */ + /* FIXME should report errors via sycamore if((iOut== eError) || (iOut == eWarning) ) - iRet = SCDoSockWrite(pCon,GetCharArray(pMsgOut));*/ - } - else /* not in interpreter, normal logic */ - { - comCon = SCGetContext(pCon); + iRet = SCDoSockWrite(pCon,GetCharArray(pMsgOut)); */ + } else { /* not in interpreter, normal logic */ + + comCon = SCGetContext(pCon); /* Return 0 without dying if no message data */ - if(pBuffer == NULL) - { - return 0; + if (pBuffer == NULL) { + return 0; } taskID = comCon.transID; - + pMsg = CreateDynString(INIT_STR_SIZE, STR_RESIZE_LENGTH); pMsgString = CreateDynString(INIT_STR_SIZE, STR_RESIZE_LENGTH); pBueffel[0] = '\0'; - sprintf(pBueffel,"[con%4.4d:",(int)pCon->ident); /* field 1: connID */ - DynStringConcat(pMsg,pBueffel); - sprintf(pBueffel,"t%6.6d:",(int)taskID); /* field 2: taskID */ - DynStringConcat(pMsg,pBueffel); + sprintf(pBueffel, "[con%4.4d:", (int) pCon->ident); /* field 1: connID */ + DynStringConcat(pMsg, pBueffel); + sprintf(pBueffel, "t%6.6d:", (int) taskID); /* field 2: taskID */ + DynStringConcat(pMsg, pBueffel); /* deviceID */ - DynStringConcat(pMsg,comCon.deviceID); - DynStringConcatChar(pMsg,':'); + DynStringConcat(pMsg, comCon.deviceID); + DynStringConcatChar(pMsg, ':'); - /* msgFlag */ - switch(iOut) { - case 5: /* eValue */ - DynStringConcat(pMsg,"out"); - break; - default: - DynStringConcat(pMsg,pCode[iOut]); - break; + /* msgFlag */ + switch (iOut) { + case 5: /* eValue */ + DynStringConcat(pMsg, "out"); + break; + default: + DynStringConcat(pMsg, pCode[iOut]); + break; } - DynStringConcatChar(pMsg,']'); - if (iOut == eStart){ + DynStringConcatChar(pMsg, ']'); + if (iOut == eStart) { DynStringConcat(pMsgString, comCon.deviceID); } if (iOut == eEvent) { DynStringConcat(pMsgString, " type="); /* Default type to VALUECHANGE if conEventType not set */ - if (-1 == pCon->conEventType) + if (-1 == pCon->conEventType) DynStringConcat(pMsgString, pEventType[0]); else DynStringConcat(pMsgString, pEventType[pCon->conEventType]); /* DynStringConcat(pMsgString, " status="); DynStringConcat(pMsgString, pStatus[pCon->conStatus]);*/ - DynStringConcat(pMsgString,","); + DynStringConcat(pMsgString, ","); } - DynStringConcat(pMsgString," "); - DynStringConcat(pMsgString,pBuffer); + DynStringConcat(pMsgString, " "); + DynStringConcat(pMsgString, pBuffer); sycformat(comCon.deviceID, iOut, pMsgString, pMsg); - /* is this really to be printed ? */ - if(iOut < pCon->iOutput) - { - if (pMsg != NULL) + /* is this really to be printed ? */ + if (iOut < pCon->iOutput) { + if (pMsg != NULL) DeleteDynString(pMsg); return 0; } - /* first the socket */ - /*strcat(pMsg, pBueffel);*/ - iRet = SCDoSockWrite(pCon,GetCharArray(pMsg)); - } - if (pMsg != NULL) - DeleteDynString(pMsg); - return 1; + /* first the socket */ + /*strcat(pMsg, pBueffel); */ + iRet = SCDoSockWrite(pCon, GetCharArray(pMsg)); + } + if (pMsg != NULL) + DeleteDynString(pMsg); + return 1; } /* Only work for hipadaba commands, hlist, hset, hget, hnotify * A multiline string (ie have crnl) will be converted to an array. * Strings with '=' will be converted to name value pairs */ -struct json_object *mkJSON_Object(SConnection *pCon, char *pBuffer, int iOut) +struct json_object *mkJSON_Object(SConnection * pCon, char *pBuffer, + int iOut) { - int linenum = __LINE__; - char pBueffel[MAXMSG], *pBufferFrom, *pBufferTo; - long taskID = 0; - struct json_object *msg_json=NULL, *tmp_json=NULL; + int linenum = __LINE__; + char pBueffel[MAXMSG], *pBufferFrom, *pBufferTo; + long taskID = 0; + struct json_object *msg_json = NULL, *tmp_json = NULL; - commandContext comCon; - char pError[256]; - pError[0]='\0'; + commandContext comCon; + char pError[256]; + pError[0] = '\0'; - if (strlen(pBuffer) == 0) { - return 0; - } - - if(!SCVerifyConnection(pCon)) - { - return 0; - } - comCon = SCGetContext(pCon); + if (strlen(pBuffer) == 0) { + return 0; + } - /* Return 0 without dying if no message data */ - if(pBuffer == NULL) - { - return 0; - } + if (!SCVerifyConnection(pCon)) { + return 0; + } + comCon = SCGetContext(pCon); - /* - build the Tcl-command to execute for formatting the - data into a sycamore string - */ - taskID = comCon.transID; - - pBueffel[0] = '\0'; - msg_json = json_object_new_object(); - if (is_error(msg_json)) { linenum = __LINE__; goto reporterr; } + /* Return 0 without dying if no message data */ + if (pBuffer == NULL) { + return 0; + } + + /* + build the Tcl-command to execute for formatting the + data into a sycamore string + */ + taskID = comCon.transID; + + pBueffel[0] = '\0'; + msg_json = json_object_new_object(); + if (is_error(msg_json)) { + linenum = __LINE__; + goto reporterr; + } /* field 1: connID */ - json_object_object_add(msg_json, "con", json_object_new_int(pCon->ident)); + json_object_object_add(msg_json, "con", + json_object_new_int(pCon->ident)); /* field 2: taskID */ - json_object_object_add(msg_json, "trans", json_object_new_int(taskID)); - /* deviceID */ - json_object_object_add(msg_json, "object", json_object_new_string(comCon.deviceID)); + json_object_object_add(msg_json, "trans", json_object_new_int(taskID)); + /* deviceID */ + json_object_object_add(msg_json, "object", + json_object_new_string(comCon.deviceID)); /* msgFlag */ - switch(iOut) { - case 5: /* eValue */ - json_object_object_add(msg_json, "flag", json_object_new_string("out")); - break; - default: - json_object_object_add(msg_json, "flag", json_object_new_string(pCode[iOut])); - break; + switch (iOut) { + case 5: /* eValue */ + json_object_object_add(msg_json, "flag", + json_object_new_string("out")); + break; + default: + json_object_object_add(msg_json, "flag", + json_object_new_string(pCode[iOut])); + break; + } + if (iOut == eHdbValue || iOut == eHdbEvent) { + tmp_json = json_tokener_parse(pBuffer); + if (is_error(tmp_json)) { + linenum = __LINE__; + goto reporterr; } - if (iOut == eHdbValue || iOut == eHdbEvent) { - tmp_json = json_tokener_parse(pBuffer); - if (is_error(tmp_json)) { linenum = __LINE__; goto reporterr; } - } else { - /* Strip \r and \n */ - for (pBufferFrom=pBufferTo=pBuffer; ; pBufferFrom++) { - if (*pBufferFrom == '\r' || *pBufferFrom == '\n') - continue; - pBufferTo = pBufferFrom; - if (*pBufferTo == '\0') - break; - pBufferTo++; - } - tmp_json = json_object_new_string(pBuffer); - if (is_error(tmp_json)) { linenum = __LINE__; goto reporterr; } + } else { + /* Strip \r and \n */ + for (pBufferFrom = pBufferTo = pBuffer;; pBufferFrom++) { + if (*pBufferFrom == '\r' || *pBufferFrom == '\n') + continue; + pBufferTo = pBufferFrom; + if (*pBufferTo == '\0') + break; + pBufferTo++; } - json_object_object_add(msg_json, "data", tmp_json); - return msg_json; + tmp_json = json_object_new_string(pBuffer); + if (is_error(tmp_json)) { + linenum = __LINE__; + goto reporterr; + } + } + json_object_object_add(msg_json, "data", tmp_json); + return msg_json; reporterr: - SCSetWriteFunc(pCon,SCNormalWrite); - snprintf(pError, 256,"{\"ERROR\": \"%s:%d Error making json object\"}", __FILE__, linenum); - SCWrite(pCon,pError,eError); - SCSetWriteFunc(pCon,SCWriteJSON_String); + SCSetWriteFunc(pCon, SCNormalWrite); + snprintf(pError, 256, "{\"ERROR\": \"%s:%d Error making json object\"}", + __FILE__, linenum); + SCWrite(pCon, pError, eError); + SCSetWriteFunc(pCon, SCWriteJSON_String); cleanup: - if (tmp_json != NULL && !is_error(tmp_json)) - json_object_put(tmp_json); - if (msg_json != NULL && !is_error(msg_json)) - json_object_put(msg_json); - return NULL; + if (tmp_json != NULL && !is_error(tmp_json)) + json_object_put(tmp_json); + if (msg_json != NULL && !is_error(msg_json)) + json_object_put(msg_json); + return NULL; } -int SCWriteJSON_String(SConnection *pCon, char *pBuffer, int iOut) +int SCWriteJSON_String(SConnection * pCon, char *pBuffer, int iOut) { - struct json_object *my_object=NULL, *tmp_json=NULL; - char pBueffel[MAXMSG], errBuff[MAXMSG]; + struct json_object *my_object = NULL, *tmp_json = NULL; + char pBueffel[MAXMSG], errBuff[MAXMSG]; int iRet, errLen = MAXMSG; if (strlen(pBuffer) == 0) return 1; - /* log it for any case */ - if(pCon->pSock) - { - iRet = pCon->pSock->sockid; - } - else - { - iRet = 0; - } - sprintf(pBueffel,"Next line intended for socket: %d",iRet); - SICSLogWrite(pBueffel,eInternal); - SICSLogWrite(pBuffer,iOut); - - /* write to commandlog if user or manager privilege */ - if(SCGetRights(pCon) <= usUser) - { - if(pCon->iMacro != 1) - { - WriteToCommandLogId(NULL,iRet,pBuffer); - } - else - { - if(iOut == eError || iOut == eWarning) - { - WriteToCommandLogId(NULL,iRet,pBuffer); - } - } - } - - if(SCinMacro(pCon)) - { - InterpWrite(pServ->pSics,pBuffer); - /* print it to client if error message */ - if((iOut== eError) || (iOut == eWarning) ) - { - tmp_json = json_object_new_string(pBuffer); - iRet = SCDoSockWrite(pCon,json_object_to_json_string(tmp_json)); - } + /* log it for any case */ + if (pCon->pSock) { + iRet = pCon->pSock->sockid; + } else { + iRet = 0; + } + sprintf(pBueffel, "Next line intended for socket: %d", iRet); + SICSLogWrite(pBueffel, eInternal); + SICSLogWrite(pBuffer, iOut); + + /* write to commandlog if user or manager privilege */ + if (SCGetRights(pCon) <= usUser) { + if (pCon->iMacro != 1) { + WriteToCommandLogId(NULL, iRet, pBuffer); } else { - if ((my_object = mkJSON_Object(pCon, pBuffer, iOut)) == NULL) { - snprintf(errBuff, errLen, "failed to make JSON object from, %s", pBuffer); - tmp_json = json_object_new_string(errBuff); - my_object = json_object_new_object(); - json_object_object_add(my_object, "ERROR", tmp_json); - SCDoSockWrite(pCon,json_object_to_json_string(my_object)); - iRet = 0; - } else { - iRet = SCDoSockWrite(pCon,json_object_to_json_string(my_object)); + if (iOut == eError || iOut == eWarning) { + WriteToCommandLogId(NULL, iRet, pBuffer); } } - if (tmp_json != NULL && !is_error(tmp_json)) - json_object_put(tmp_json); - if (my_object != NULL && !is_error(my_object)) - json_object_put(my_object); + } + + if (SCinMacro(pCon)) { + InterpWrite(pServ->pSics, pBuffer); + /* print it to client if error message */ + if ((iOut == eError) || (iOut == eWarning)) { + tmp_json = json_object_new_string(pBuffer); + iRet = SCDoSockWrite(pCon, json_object_to_json_string(tmp_json)); + } + } else { + if ((my_object = mkJSON_Object(pCon, pBuffer, iOut)) == NULL) { + snprintf(errBuff, errLen, "failed to make JSON object from, %s", + pBuffer); + tmp_json = json_object_new_string(errBuff); + my_object = json_object_new_object(); + json_object_object_add(my_object, "ERROR", tmp_json); + SCDoSockWrite(pCon, json_object_to_json_string(my_object)); + iRet = 0; + } else { + iRet = SCDoSockWrite(pCon, json_object_to_json_string(my_object)); + } + } + if (tmp_json != NULL && !is_error(tmp_json)) + json_object_put(tmp_json); + if (my_object != NULL && !is_error(my_object)) + json_object_put(my_object); return iRet; } + /*------------------------------------------------------------------------*/ /* Protocol API */ -char * GetProtocolName(SConnection* pCon) +char *GetProtocolName(SConnection * pCon) { - pProtocol pPro; - pSicsInterp pSics; - - if(!SCVerifyConnection(pCon)) - { - return NULL; - } - - pSics = GetInterpreter(); - if(!pSics) return NULL; - - pPro = FindCommandData(pSics,"protocol","Protocol"); - if(!pPro) return NULL; - - InitDefaultProtocol(pCon,pPro); + pProtocol pPro; + pSicsInterp pSics; - /* check list of protocols for valid name */ - switch(pCon->iProtocolID) - { - case 0: /* default = psi_sics */ - case 1: /* normal (connection start default) */ - case 2: /* outcodes */ - case 3: /* sycamore */ - case 4: /* json */ - return strdup(pPro->pProList[pCon->iProtocolID]); - break; - default: - return strdup("invalid"); - break; - } + if (!SCVerifyConnection(pCon)) { + return NULL; + } + + pSics = GetInterpreter(); + if (!pSics) + return NULL; + + pPro = FindCommandData(pSics, "protocol", "Protocol"); + if (!pPro) + return NULL; + + InitDefaultProtocol(pCon, pPro); + + /* check list of protocols for valid name */ + switch (pCon->iProtocolID) { + case 0: /* default = psi_sics */ + case 1: /* normal (connection start default) */ + case 2: /* outcodes */ + case 3: /* sycamore */ + case 4: /* json */ + return strdup(pPro->pProList[pCon->iProtocolID]); + break; + default: + return strdup("invalid"); + break; + } } /*----------------------------------*/ -int GetProtocolID(SConnection* pCon) +int GetProtocolID(SConnection * pCon) { - if(NULL!=pCon) - { - return pCon->iProtocolID; - } - return -1; + if (NULL != pCon) { + return pCon->iProtocolID; + } + return -1; } + /*---------------------------------------------------------------------------*/ -writeFunc GetProtocolWriteFunc(SConnection *pCon){ - if(pCon != NULL){ - switch(pCon->iProtocolID){ - case 2: /* outcodes */ - return SCWriteWithOutcode; - break; - case 3: /* sycamore */ - return SCWriteSycamore; - break; - case 4: /* json */ - return SCWriteJSON_String; - break; - case 5: - return SCACTWrite; - break; - default: - return SCNormalWrite; - break; - } +writeFunc GetProtocolWriteFunc(SConnection * pCon) +{ + if (pCon != NULL) { + switch (pCon->iProtocolID) { + case 2: /* outcodes */ + return SCWriteWithOutcode; + break; + case 3: /* sycamore */ + return SCWriteSycamore; + break; + case 4: /* json */ + return SCWriteJSON_String; + break; + case 5: + return SCACTWrite; + break; + default: + return SCNormalWrite; + break; } - return SCNormalWrite; + } + return SCNormalWrite; } diff --git a/protocol.h b/protocol.h index 24d51d72..22e204b2 100644 --- a/protocol.h +++ b/protocol.h @@ -7,30 +7,30 @@ static const int iNumProTags = 2; static char *pProTags[3] = { - "start", - "finish", - NULL + "start", + "finish", + NULL }; #define esStart -1 #define esFinish -2 - + /*--------------------- lifecycle -------------------------------------- */ -int InstallProtocol(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int InstallProtocol(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); void DeleteProtocol(void *pSelf); -void MakeProtocol(SicsInterp *pSics); - +void MakeProtocol(SicsInterp * pSics); + /*--------------------- operations --------------------------------------*/ -int ProtocolAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int ProtocolAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*--------------------- implement protocol sycamore ---------------------*/ -int SCWriteSycamore(SConnection *pCon, char *pBuffer, int iOut); +int SCWriteSycamore(SConnection * pCon, char *pBuffer, int iOut); /*--------------------- implement protocol API -----------------------*/ -char * GetProtocolName(SConnection *pCon); -int GetProtocolID(SConnection *pCon); -int ProtocolGet(SConnection* pCon, void* pData, char *pProName, int len); -writeFunc GetProtocolWriteFunc(SConnection *pCon); +char *GetProtocolName(SConnection * pCon); +int GetProtocolID(SConnection * pCon); +int ProtocolGet(SConnection * pCon, void *pData, char *pProName, int len); +writeFunc GetProtocolWriteFunc(SConnection * pCon); /*-----------------------------------------------------------------------*/ -#endif +#endif diff --git a/proxy.c b/proxy.c index a30a5dd8..b7065485 100644 --- a/proxy.c +++ b/proxy.c @@ -14,463 +14,488 @@ #include /*-----------------------------------------------------------------------*/ typedef struct { - pIDrivable pDriv; - pEVInterface pEnv; - pIDrivable pSlaveDriv; - void *slaveData; - pEVInterface pEnvSlave; + pIDrivable pDriv; + pEVInterface pEnv; + pIDrivable pSlaveDriv; + void *slaveData; + pEVInterface pEnvSlave; } ProxyInt, *pProxyInt; /*------------------------------------------------------------------------*/ -static void KillProxyInt(void *data){ - pProxyInt proxy = (pProxyInt)data; - - if(proxy == NULL){ - return; - } - if(proxy->pDriv != NULL){ - free(proxy->pDriv); - } - if(proxy->pEnv != NULL){ - free(proxy->pEnv); - } - free(proxy); +static void KillProxyInt(void *data) +{ + pProxyInt proxy = (pProxyInt) data; + + if (proxy == NULL) { + return; + } + if (proxy->pDriv != NULL) { + free(proxy->pDriv); + } + if (proxy->pEnv != NULL) { + free(proxy->pEnv); + } + free(proxy); } + /*===================== Drivable Interfaces ================================*/ -static int testDrivProxy(pSICSOBJ self){ - pProxyInt proxy = self->pPrivate; +static int testDrivProxy(pSICSOBJ self) +{ + pProxyInt proxy = self->pPrivate; - if(proxy->pSlaveDriv != NULL && proxy->slaveData != NULL){ - return 1; - } + if (proxy->pSlaveDriv != NULL && proxy->slaveData != NULL) { + return 1; + } + return 0; +} + +/*-----------------------------------------------------------------------*/ +static int ProxyHalt(void *data) +{ + pSICSOBJ self = (pSICSOBJ) data; + pProxyInt proxy = NULL; + + assert(self != NULL); + proxy = self->pPrivate; + assert(self != NULL); + + if (testDrivProxy(self)) { + return proxy->pSlaveDriv->Halt(proxy->slaveData); + } else { return 0; + } } -/*-----------------------------------------------------------------------*/ -static int ProxyHalt(void *data){ - pSICSOBJ self = (pSICSOBJ)data; - pProxyInt proxy = NULL; - - assert(self != NULL); - proxy = self->pPrivate; - assert(self != NULL); - - if(testDrivProxy(self)){ - return proxy->pSlaveDriv->Halt(proxy->slaveData); - } else { - return 0; - } -} + /*------------------------------------------------------------------------*/ -static int ProxyLimits(void *data, float fval, - char *error, int iErrLen){ - pSICSOBJ self = (pSICSOBJ)data; - pProxyInt proxy = NULL; - - assert(self != NULL); - proxy = self->pPrivate; - assert(self != NULL); - - if(testDrivProxy(self)){ - return proxy->pSlaveDriv->CheckLimits(proxy->slaveData, fval, - error, iErrLen); - } else { - strncpy(error,"ERROR: device not configured",iErrLen); - return 0; - } +static int ProxyLimits(void *data, float fval, char *error, int iErrLen) +{ + pSICSOBJ self = (pSICSOBJ) data; + pProxyInt proxy = NULL; + + assert(self != NULL); + proxy = self->pPrivate; + assert(self != NULL); + + if (testDrivProxy(self)) { + return proxy->pSlaveDriv->CheckLimits(proxy->slaveData, fval, + error, iErrLen); + } else { + strncpy(error, "ERROR: device not configured", iErrLen); + return 0; + } } + /*-----------------------------------------------------------------------*/ -static long ProxySet(void *data, SConnection *pCon, float fVal){ - pSICSOBJ self = (pSICSOBJ)data; - pProxyInt proxy = NULL; - - assert(self != NULL); - proxy = self->pPrivate; - assert(self != NULL); - - if(testDrivProxy(self)){ - return proxy->pSlaveDriv->SetValue(proxy->slaveData, - pCon, fVal); - } else { - SCWrite(pCon,"ERROR: device not configured", eError); - return 0; - } +static long ProxySet(void *data, SConnection * pCon, float fVal) +{ + pSICSOBJ self = (pSICSOBJ) data; + pProxyInt proxy = NULL; + + assert(self != NULL); + proxy = self->pPrivate; + assert(self != NULL); + + if (testDrivProxy(self)) { + return proxy->pSlaveDriv->SetValue(proxy->slaveData, pCon, fVal); + } else { + SCWrite(pCon, "ERROR: device not configured", eError); + return 0; + } } + /*-----------------------------------------------------------------------*/ -static int ProxyStatus(void *data, SConnection *pCon){ - pSICSOBJ self = (pSICSOBJ)data; - pProxyInt proxy = NULL; - - assert(self != NULL); - proxy = self->pPrivate; - assert(self != NULL); - - if(testDrivProxy(self)){ - return proxy->pSlaveDriv->CheckStatus(proxy->slaveData, - pCon); - } else { - SCWrite(pCon,"ERROR: device not configured", eError); - return HWFault; - } +static int ProxyStatus(void *data, SConnection * pCon) +{ + pSICSOBJ self = (pSICSOBJ) data; + pProxyInt proxy = NULL; + + assert(self != NULL); + proxy = self->pPrivate; + assert(self != NULL); + + if (testDrivProxy(self)) { + return proxy->pSlaveDriv->CheckStatus(proxy->slaveData, pCon); + } else { + SCWrite(pCon, "ERROR: device not configured", eError); + return HWFault; + } } + /*-----------------------------------------------------------------------*/ -static float ProxyGet(void *data, SConnection *pCon){ - pSICSOBJ self = (pSICSOBJ)data; - pProxyInt proxy = NULL; - - assert(self != NULL); - proxy = self->pPrivate; - assert(self != NULL); - - if(testDrivProxy(self)){ - return proxy->pSlaveDriv->GetValue(proxy->slaveData, pCon); - } else { - SCWrite(pCon,"ERROR: device not configured", eError); - return HWFault; - } +static float ProxyGet(void *data, SConnection * pCon) +{ + pSICSOBJ self = (pSICSOBJ) data; + pProxyInt proxy = NULL; + + assert(self != NULL); + proxy = self->pPrivate; + assert(self != NULL); + + if (testDrivProxy(self)) { + return proxy->pSlaveDriv->GetValue(proxy->slaveData, pCon); + } else { + SCWrite(pCon, "ERROR: device not configured", eError); + return HWFault; + } } + /*===================== environment interface ==========================*/ -static int testEnvProxy(pSICSOBJ self){ - pProxyInt proxy = self->pPrivate; +static int testEnvProxy(pSICSOBJ self) +{ + pProxyInt proxy = self->pPrivate; - if(proxy->pEnvSlave != NULL && proxy->slaveData != NULL){ - return 1; - } + if (proxy->pEnvSlave != NULL && proxy->slaveData != NULL) { + return 1; + } + return 0; +} + +/*-----------------------------------------------------------------------*/ +static EVMode ProxyMode(void *data) +{ + pSICSOBJ self = (pSICSOBJ) data; + pProxyInt proxy = NULL; + + assert(self != NULL); + proxy = self->pPrivate; + assert(self != NULL); + + if (testEnvProxy(self)) { + return proxy->pEnvSlave->GetMode(proxy->slaveData); + } else { + return EVError; + } +} + +/*------------------------------------------------------------------------*/ +static int ProxyTolerance(void *data) +{ + pSICSOBJ self = (pSICSOBJ) data; + pProxyInt proxy = NULL; + + assert(self != NULL); + proxy = self->pPrivate; + assert(self != NULL); + + if (testEnvProxy(self)) { + return proxy->pEnvSlave->IsInTolerance(proxy->slaveData); + } else { return 0; + } } -/*-----------------------------------------------------------------------*/ -static EVMode ProxyMode(void *data){ - pSICSOBJ self = (pSICSOBJ)data; - pProxyInt proxy = NULL; - - assert(self != NULL); - proxy = self->pPrivate; - assert(self != NULL); - - if(testEnvProxy(self)){ - return proxy->pEnvSlave->GetMode(proxy->slaveData); - } else { - return EVError; - } -} -/*------------------------------------------------------------------------*/ -static int ProxyTolerance(void *data){ - pSICSOBJ self = (pSICSOBJ)data; - pProxyInt proxy = NULL; - - assert(self != NULL); - proxy = self->pPrivate; - assert(self != NULL); - - if(testEnvProxy(self)){ - return proxy->pEnvSlave->IsInTolerance(proxy->slaveData); - } else { - return 0; - } -} -/*-------------------------------------------------------------------------*/ -static int ProxyError(void *data){ - pSICSOBJ self = (pSICSOBJ)data; - pProxyInt proxy = NULL; - - assert(self != NULL); - proxy = self->pPrivate; - assert(self != NULL); - - if(testEnvProxy(self)){ - return proxy->pEnvSlave->HandleError(proxy->slaveData); - } else { - return 0; - } -} -/*-----------------------------------------------------------------------*/ -static void *findRealDev(pHdb node){ - char realDevice[80]; - CommandList *pCom = NULL; - - GetHdbProperty(node,"proxy",realDevice,80); - pCom = FindCommand(pServ->pSics,realDevice); - if(pCom != NULL){ - return pCom->pData; - } else { - return NULL; - } -} -/*-----------------------------------------------------------------------*/ -static void *ProxyGetInterface(void *pData, int iID){ - pSICSOBJ self = (pSICSOBJ)pData; - pDummy other = NULL; - void *inter = NULL; - pProxyInt proxy = NULL; - assert(self != NULL); - proxy = self->pPrivate; - - if(self != NULL){ - other = (pDummy)findRealDev(self->objectNode); - if(other != NULL){ - inter = other->pDescriptor->GetInterface(other, iID); - if(inter == NULL && - (iID == DRIVEID || iID == ENVIRINTERFACE) ){ - proxy->pEnvSlave = NULL; - proxy->pSlaveDriv = NULL; - proxy->slaveData = NULL; - return NULL; - } else { - if(iID == DRIVEID){ - proxy->pSlaveDriv = inter; - proxy->slaveData = other; - return proxy->pDriv; - } else if(iID == ENVIRINTERFACE){ - proxy->pEnvSlave = inter; - proxy->slaveData = other; - return proxy->pEnv; - } - } - return inter; - } - } +/*-------------------------------------------------------------------------*/ +static int ProxyError(void *data) +{ + pSICSOBJ self = (pSICSOBJ) data; + pProxyInt proxy = NULL; + + assert(self != NULL); + proxy = self->pPrivate; + assert(self != NULL); + + if (testEnvProxy(self)) { + return proxy->pEnvSlave->HandleError(proxy->slaveData); + } else { + return 0; + } +} + +/*-----------------------------------------------------------------------*/ +static void *findRealDev(pHdb node) +{ + char realDevice[80]; + CommandList *pCom = NULL; + + GetHdbProperty(node, "proxy", realDevice, 80); + pCom = FindCommand(pServ->pSics, realDevice); + if (pCom != NULL) { + return pCom->pData; + } else { return NULL; + } } + +/*-----------------------------------------------------------------------*/ +static void *ProxyGetInterface(void *pData, int iID) +{ + pSICSOBJ self = (pSICSOBJ) pData; + pDummy other = NULL; + void *inter = NULL; + pProxyInt proxy = NULL; + + assert(self != NULL); + proxy = self->pPrivate; + + if (self != NULL) { + other = (pDummy) findRealDev(self->objectNode); + if (other != NULL) { + inter = other->pDescriptor->GetInterface(other, iID); + if (inter == NULL && (iID == DRIVEID || iID == ENVIRINTERFACE)) { + proxy->pEnvSlave = NULL; + proxy->pSlaveDriv = NULL; + proxy->slaveData = NULL; + return NULL; + } else { + if (iID == DRIVEID) { + proxy->pSlaveDriv = inter; + proxy->slaveData = other; + return proxy->pDriv; + } else if (iID == ENVIRINTERFACE) { + proxy->pEnvSlave = inter; + proxy->slaveData = other; + return proxy->pEnv; + } + } + return inter; + } + } + return NULL; +} + /*------------------------------------------------------------------------*/ -static hdbCallbackReturn ProxyCallback(pHdb node, void *userData, - pHdbMessage message){ - pHdbDataMessage get = NULL, set = NULL; - pDummy other = NULL; - pIDrivable pDriv = NULL; - float fval; - int status; - SConnection *pCon = NULL; - pSICSOBJ self = (pSICSOBJ)userData; - char proxyDev[80]; - - get = GetHdbGetMessage(message); - if(get != NULL){ - pCon = (SConnection *)get->callData; - other = (pDummy)findRealDev(node); - if(other != NULL){ - pDriv = other->pDescriptor->GetInterface(other,DRIVEID); - if(pDriv != NULL && pCon != NULL){ - fval = pDriv->GetValue(other, pCon); - get->v->v.doubleValue = (double)fval; - node->value.v.doubleValue = (double)fval; - return hdbContinue; - } - } - get->v->v.doubleValue = .0; - } +static hdbCallbackReturn ProxyCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdbDataMessage get = NULL, set = NULL; + pDummy other = NULL; + pIDrivable pDriv = NULL; + float fval; + int status; + SConnection *pCon = NULL; + pSICSOBJ self = (pSICSOBJ) userData; + char proxyDev[80]; - set = GetHdbSetMessage(message); - if(set != NULL){ - pCon = (SConnection *)set->callData; - other = (pDummy)findRealDev(node); - if(other == NULL){ - if(pCon != NULL){ - SCWrite(pCon,"ERROR: device not configured", eError); - return hdbAbort; - } - } - GetHdbProperty(node,"proxy", proxyDev,80); - status = StartDevice(pServ->pExecutor, proxyDev, - self->pDes, self, pCon, (float)set->v->v.doubleValue); - if(status == 1){ - return hdbContinue; - } else { - return hdbAbort; - } - } - - return hdbContinue; + get = GetHdbGetMessage(message); + if (get != NULL) { + pCon = (SConnection *) get->callData; + other = (pDummy) findRealDev(node); + if (other != NULL) { + pDriv = other->pDescriptor->GetInterface(other, DRIVEID); + if (pDriv != NULL && pCon != NULL) { + fval = pDriv->GetValue(other, pCon); + get->v->v.doubleValue = (double) fval; + node->value.v.doubleValue = (double) fval; + return hdbContinue; + } + } + get->v->v.doubleValue = .0; + } + + set = GetHdbSetMessage(message); + if (set != NULL) { + pCon = (SConnection *) set->callData; + other = (pDummy) findRealDev(node); + if (other == NULL) { + if (pCon != NULL) { + SCWrite(pCon, "ERROR: device not configured", eError); + return hdbAbort; + } + } + GetHdbProperty(node, "proxy", proxyDev, 80); + status = StartDevice(pServ->pExecutor, proxyDev, + self->pDes, self, pCon, + (float) set->v->v.doubleValue); + if (status == 1) { + return hdbContinue; + } else { + return hdbAbort; + } + } + + return hdbContinue; } + /*----------------------------------------------------------------------------*/ -static hdbCallbackReturn MapParCallback(pHdb node, void *userData, - pHdbMessage message){ - pHdbDataMessage get = NULL, set = NULL; - CommandList *pCom = NULL; - SConnection *pCon = NULL; - char mapPar[80], proxyDev[80], *pData = NULL; - char command[1024]; - pDynString data = NULL; - - if(GetHdbKillNodeMessage(message) != NULL ){ - return hdbContinue; - } - - GetHdbProperty(node->mama, "proxy", proxyDev,80); - pCom = FindCommand(pServ->pSics, proxyDev); - if(pCom == NULL){ - if(pCon != NULL){ - SCWrite(pCon,"ERROR: device not configured", eError); - } - return hdbContinue; - } - GetHdbProperty(node,"mappar", mapPar, 80); - - get = GetHdbGetMessage(message); - if(get != NULL){ - pCon = (SConnection *)get->callData; snprintf(command,1024,"%s %s", proxyDev, mapPar); - if(pCon != NULL){ - SCStartBuffering(pCon); - InterpExecute(pServ->pSics, pCon,command); - data = SCEndBuffering(pCon); - if(data != NULL){ - pData = GetCharArray(data); - if(strstr(pData,"ERROR") != NULL){ - SCWrite(pCon,pData,eError); - } else { - pData = strchr(pData,(int)'='); - if(pData != NULL){ - pData++; - if(!readHdbValue(get->v, pData, command, 1024)){ - SCWrite(pCon, command, eError); - } - copyHdbValue(get->v, &node->value); - return hdbContinue; - } - } - } - } - } +static hdbCallbackReturn MapParCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdbDataMessage get = NULL, set = NULL; + CommandList *pCom = NULL; + SConnection *pCon = NULL; + char mapPar[80], proxyDev[80], *pData = NULL; + char command[1024]; + pDynString data = NULL; - set = GetHdbSetMessage(message); - if(set != NULL){ - pCon = (SConnection *)set->callData; - data = formatValue(*(set->v), node); - if(data != NULL){ - snprintf(command,1024,"%s %s %s", proxyDev, mapPar, - GetCharArray(data)); - DeleteDynString(data); - InterpExecute(pServ->pSics, pCon, command); - } - } - - return hdbContinue; + if (GetHdbKillNodeMessage(message) != NULL) { + return hdbContinue; + } + + GetHdbProperty(node->mama, "proxy", proxyDev, 80); + pCom = FindCommand(pServ->pSics, proxyDev); + if (pCom == NULL) { + if (pCon != NULL) { + SCWrite(pCon, "ERROR: device not configured", eError); + } + return hdbContinue; + } + GetHdbProperty(node, "mappar", mapPar, 80); + + get = GetHdbGetMessage(message); + if (get != NULL) { + pCon = (SConnection *) get->callData; + snprintf(command, 1024, "%s %s", proxyDev, mapPar); + if (pCon != NULL) { + SCStartBuffering(pCon); + InterpExecute(pServ->pSics, pCon, command); + data = SCEndBuffering(pCon); + if (data != NULL) { + pData = GetCharArray(data); + if (strstr(pData, "ERROR") != NULL) { + SCWrite(pCon, pData, eError); + } else { + pData = strchr(pData, (int) '='); + if (pData != NULL) { + pData++; + if (!readHdbValue(get->v, pData, command, 1024)) { + SCWrite(pCon, command, eError); + } + copyHdbValue(get->v, &node->value); + return hdbContinue; + } + } + } + } + } + + set = GetHdbSetMessage(message); + if (set != NULL) { + pCon = (SConnection *) set->callData; + data = formatValue(*(set->v), node); + if (data != NULL) { + snprintf(command, 1024, "%s %s %s", proxyDev, mapPar, + GetCharArray(data)); + DeleteDynString(data); + InterpExecute(pServ->pSics, pCon, command); + } + } + + return hdbContinue; } + /*-------------------------------------------------------------------------*/ -static int MapFunc(pSICSOBJ self, SConnection *pCon, pHdb commandNode, - pHdb par[], int nPar){ - pHdb node = NULL; - int type; - - if(nPar < 4){ - SCWrite(pCon,"ERROR: not enough arguments to MapFunc", eError); - return 0; - } - - type = convertHdbType(par[2]->value.v.text); - node = MakeHipadabaNode(par[0]->value.v.text, type, 1); - if(node == NULL){ - SCWrite(pCon,"ERROR: out of memory in MapFunc", eError); - return 0; - } - SetHdbProperty(node,"mappar", par[1]->value.v.text); - SetHdbProperty(node,"priv", par[3]->value.v.text); - AppendHipadabaCallback(node, - MakeHipadabaCallback(MapParCallback, NULL, NULL)); - AddHipadabaChild(self->objectNode, node, pCon); - - return 1; +static int MapFunc(pSICSOBJ self, SConnection * pCon, pHdb commandNode, + pHdb par[], int nPar) +{ + pHdb node = NULL; + int type; + + if (nPar < 4) { + SCWrite(pCon, "ERROR: not enough arguments to MapFunc", eError); + return 0; + } + + type = convertHdbType(par[2]->value.v.text); + node = MakeHipadabaNode(par[0]->value.v.text, type, 1); + if (node == NULL) { + SCWrite(pCon, "ERROR: out of memory in MapFunc", eError); + return 0; + } + SetHdbProperty(node, "mappar", par[1]->value.v.text); + SetHdbProperty(node, "priv", par[3]->value.v.text); + AppendHipadabaCallback(node, + MakeHipadabaCallback(MapParCallback, NULL, NULL)); + AddHipadabaChild(self->objectNode, node, pCon); + + return 1; } + /*--------------------------------------------------------------------------*/ -static int ProxyAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - int status; - pSICSOBJ self = (pSICSOBJ)pData; - CommandList *pCom = NULL; - char proxyObj[80]; - - assert(self != NULL); - - /* - * do parameters and object functions - */ - if(argc > 1){ - status = InvokeSICSOBJ(pCon, pSics, pData, argc, argv); - if(status != -1 ){ - return status; - } - } - - /* - * try the interpreter function of the proxy object - */ - GetHdbProperty(self->objectNode,"proxy", proxyObj, 80); - pCom = FindCommand(pSics, proxyObj); - if(pCom != NULL){ - return pCom->OFunc(pCon,pSics,pCom->pData, argc, argv); - } else { - SCWrite(pCon,"ERROR: device not configured", eError); - return 0; - } +static int ProxyAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int status; + pSICSOBJ self = (pSICSOBJ) pData; + CommandList *pCom = NULL; + char proxyObj[80]; + + assert(self != NULL); + + /* + * do parameters and object functions + */ + if (argc > 1) { + status = InvokeSICSOBJ(pCon, pSics, pData, argc, argv); + if (status != -1) { + return status; + } + } + + /* + * try the interpreter function of the proxy object + */ + GetHdbProperty(self->objectNode, "proxy", proxyObj, 80); + pCom = FindCommand(pSics, proxyObj); + if (pCom != NULL) { + return pCom->OFunc(pCon, pSics, pCom->pData, argc, argv); + } else { + SCWrite(pCon, "ERROR: device not configured", eError); + return 0; + } } + /*--------------------------------------------------------------------------*/ -int ProxyFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - int type; - pSICSOBJ pNew = NULL; - pHdb mapFunc = NULL; - hdbValue v; - pProxyInt proxy = NULL; - - if(argc < 4){ - SCWrite(pCon,"ERROR: not enough arguments for ProxyFactory", - eError); - return 0; - } - - type = convertHdbType(argv[3]); - pNew = MakeSICSOBJv(argv[1], "ProxyObject", type, usSpy); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory in ProxyFactory", - eError); - return 0; - } +int ProxyFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int type; + pSICSOBJ pNew = NULL; + pHdb mapFunc = NULL; + hdbValue v; + pProxyInt proxy = NULL; - proxy = malloc(sizeof(ProxyInt)); - if(proxy == NULL){ - SCWrite(pCon,"ERROR: out of memory in ProxyFactory", - eError); - return 0; - } - memset(proxy,0,sizeof(ProxyInt)); - proxy->pDriv = CreateDrivableInterface(); - proxy->pEnv = CreateEVInterface(); - if(proxy->pDriv == NULL && proxy->pEnv == NULL){ - SCWrite(pCon,"ERROR: out of memory in ProxyFactory", - eError); - return 0; - } - proxy->pDriv->CheckLimits = ProxyLimits; - proxy->pDriv->CheckStatus = ProxyStatus; - proxy->pDriv->GetValue = ProxyGet; - proxy->pDriv->Halt = ProxyHalt; - proxy->pDriv->SetValue = ProxySet; + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough arguments for ProxyFactory", eError); + return 0; + } - proxy->pEnv->GetMode = ProxyMode; - proxy->pEnv->HandleError = ProxyError; - proxy->pEnv->IsInTolerance = ProxyTolerance; - - pNew->KillPrivate = KillProxyInt; - pNew->pPrivate = proxy; - - pNew->pDes->GetInterface = ProxyGetInterface; - SetHdbProperty(pNew->objectNode, "proxy", argv[2]); - AppendHipadabaCallback(pNew->objectNode, - MakeHipadabaCallback(ProxyCallback, pNew,NULL)); - - v = MakeSICSFunc(MapFunc); - mapFunc = MakeSICSHdbPar("map", usMugger, v); - SetHdbProperty(mapFunc,"visible","false"); - v = MakeHdbText("Undefined"); - AddSICSHdbPar(mapFunc,"name",usMugger,v); - AddSICSHdbPar(mapFunc,"target",usMugger,v); - AddSICSHdbPar(mapFunc,"type",usMugger,v); - AddSICSHdbPar(mapFunc,"priv",usMugger,v); - AddHipadabaChild(pNew->objectNode, mapFunc, pCon); - - AddCommand(pSics,argv[1], - ProxyAction, - KillSICSOBJ, - pNew); - - return 1; + type = convertHdbType(argv[3]); + pNew = MakeSICSOBJv(argv[1], "ProxyObject", type, usSpy); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory in ProxyFactory", eError); + return 0; + } + + proxy = malloc(sizeof(ProxyInt)); + if (proxy == NULL) { + SCWrite(pCon, "ERROR: out of memory in ProxyFactory", eError); + return 0; + } + memset(proxy, 0, sizeof(ProxyInt)); + proxy->pDriv = CreateDrivableInterface(); + proxy->pEnv = CreateEVInterface(); + if (proxy->pDriv == NULL && proxy->pEnv == NULL) { + SCWrite(pCon, "ERROR: out of memory in ProxyFactory", eError); + return 0; + } + proxy->pDriv->CheckLimits = ProxyLimits; + proxy->pDriv->CheckStatus = ProxyStatus; + proxy->pDriv->GetValue = ProxyGet; + proxy->pDriv->Halt = ProxyHalt; + proxy->pDriv->SetValue = ProxySet; + + proxy->pEnv->GetMode = ProxyMode; + proxy->pEnv->HandleError = ProxyError; + proxy->pEnv->IsInTolerance = ProxyTolerance; + + pNew->KillPrivate = KillProxyInt; + pNew->pPrivate = proxy; + + pNew->pDes->GetInterface = ProxyGetInterface; + SetHdbProperty(pNew->objectNode, "proxy", argv[2]); + AppendHipadabaCallback(pNew->objectNode, + MakeHipadabaCallback(ProxyCallback, pNew, NULL)); + + v = MakeSICSFunc(MapFunc); + mapFunc = MakeSICSHdbPar("map", usMugger, v); + SetHdbProperty(mapFunc, "visible", "false"); + v = MakeHdbText("Undefined"); + AddSICSHdbPar(mapFunc, "name", usMugger, v); + AddSICSHdbPar(mapFunc, "target", usMugger, v); + AddSICSHdbPar(mapFunc, "type", usMugger, v); + AddSICSHdbPar(mapFunc, "priv", usMugger, v); + AddHipadabaChild(pNew->objectNode, mapFunc, pCon); + + AddCommand(pSics, argv[1], ProxyAction, KillSICSOBJ, pNew); + + return 1; } - diff --git a/proxy.h b/proxy.h index 4afc22cc..70df5bd4 100644 --- a/proxy.h +++ b/proxy.h @@ -11,7 +11,7 @@ */ #ifndef PROXY_H_ #define PROXY_H_ -int ProxyFactory(SConnection *pCon, SicsInterp *pSics, void *pData, +int ProxyFactory(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]); -#endif /*PROXY_H_*/ +#endif /*PROXY_H_ */ diff --git a/regresscter.c b/regresscter.c index a0701b50..11cad75e 100644 --- a/regresscter.c +++ b/regresscter.c @@ -26,237 +26,260 @@ #define STATEPAU 2 /*--------------------------------------------------------------------------*/ typedef struct { - int errType; - int recover; - int state; - time_t endTime; + int errType; + int recover; + int state; + time_t endTime; } RegressSt; /*---------------------------------------------------------------------------*/ -static int RegressGetStatus(struct __COUNTER *self, float *fControl){ - RegressSt *pSim = NULL; - time_t tD, tDe; - int iRun; +static int RegressGetStatus(struct __COUNTER *self, float *fControl) +{ + RegressSt *pSim = NULL; + time_t tD, tDe; + int iRun; - assert(self); - pSim = (RegressSt *) self->pData; - assert(pSim); + assert(self); + pSim = (RegressSt *) self->pData; + assert(pSim); - if(pSim->errType == STATUSFAIL){ - return HWFault; - } - if(time(NULL) > pSim->endTime){ - pSim->state = STATEIDLE; - } - switch(pSim->state){ - case STATEIDLE: - return HWIdle; - break; - case STATERUN: - return HWBusy; - break; - case STATEPAU: - return HWPause; - break; - } - assert(0); + if (pSim->errType == STATUSFAIL) { return HWFault; -} -/*---------------------------------------------------------------------------*/ -static int RegressStart(struct __COUNTER *self){ - RegressSt *pSim = NULL; - time_t tD; - int iRun; - - assert(self); - pSim = (RegressSt *) self->pData; - assert(pSim); - - if(pSim->errType == STARTFAIL){ - return HWFault; - } - pSim->state = STATERUN; - if(self->eMode == eTimer){ - pSim->endTime = time(NULL) + (int)self->fPreset; - } else { - pSim->endTime = time(NULL) + 7; - } - - return OKOK; -} -/*---------------------------------------------------------------------------*/ -static int RegressPause(struct __COUNTER *self){ - RegressSt *pSim = NULL; - time_t tD; - int iRun; - - assert(self); - pSim = (RegressSt *) self->pData; - assert(pSim); - - if(pSim->errType == PAUSEFAIL){ - return HWFault; - } - - pSim->state = STATEPAU; - - return OKOK; -} -/*---------------------------------------------------------------------------*/ -static int RegressContinue(struct __COUNTER *self){ - RegressSt *pSim = NULL; - - assert(self); - pSim = (RegressSt *) self->pData; - assert(pSim); - - if(pSim->errType == CONTFAIL){ - return HWFault; - } - - pSim->state = STATERUN; - - return OKOK; -} -/*--------------------------------------------------------------------------*/ -static int RegressHalt(struct __COUNTER *self){ - RegressSt *pSim = NULL; - - assert(self); - pSim = (RegressSt *) self->pData; - assert(pSim); - + } + if (time(NULL) > pSim->endTime) { pSim->state = STATEIDLE; + } + switch (pSim->state) { + case STATEIDLE: + return HWIdle; + break; + case STATERUN: + return HWBusy; + break; + case STATEPAU: + return HWPause; + break; + } + assert(0); + return HWFault; +} - return OKOK; +/*---------------------------------------------------------------------------*/ +static int RegressStart(struct __COUNTER *self) +{ + RegressSt *pSim = NULL; + time_t tD; + int iRun; + + assert(self); + pSim = (RegressSt *) self->pData; + assert(pSim); + + if (pSim->errType == STARTFAIL) { + return HWFault; + } + pSim->state = STATERUN; + if (self->eMode == eTimer) { + pSim->endTime = time(NULL) + (int) self->fPreset; + } else { + pSim->endTime = time(NULL) + 7; + } + + return OKOK; +} + +/*---------------------------------------------------------------------------*/ +static int RegressPause(struct __COUNTER *self) +{ + RegressSt *pSim = NULL; + time_t tD; + int iRun; + + assert(self); + pSim = (RegressSt *) self->pData; + assert(pSim); + + if (pSim->errType == PAUSEFAIL) { + return HWFault; + } + + pSim->state = STATEPAU; + + return OKOK; +} + +/*---------------------------------------------------------------------------*/ +static int RegressContinue(struct __COUNTER *self) +{ + RegressSt *pSim = NULL; + + assert(self); + pSim = (RegressSt *) self->pData; + assert(pSim); + + if (pSim->errType == CONTFAIL) { + return HWFault; + } + + pSim->state = STATERUN; + + return OKOK; +} + +/*--------------------------------------------------------------------------*/ +static int RegressHalt(struct __COUNTER *self) +{ + RegressSt *pSim = NULL; + + assert(self); + pSim = (RegressSt *) self->pData; + assert(pSim); + + pSim->state = STATEIDLE; + + return OKOK; } /*-------------------------------------------------------------------------*/ -static int RegressReadValues(struct __COUNTER *self){ - RegressSt *pSim = NULL; - int i; +static int RegressReadValues(struct __COUNTER *self) +{ + RegressSt *pSim = NULL; + int i; - assert(self); - pSim = (RegressSt *) self->pData; - assert(pSim); + assert(self); + pSim = (RegressSt *) self->pData; + assert(pSim); - if(pSim->errType == READFAIL){ - return HWFault; - } - - for (i = 0; i < MAXCOUNT; i++) { - self->lCounts[i] = i*10+5; - } - self->lCounts[1] = self->fPreset; - self->fTime = self->fPreset; - return OKOK; + if (pSim->errType == READFAIL) { + return HWFault; + } + + for (i = 0; i < MAXCOUNT; i++) { + self->lCounts[i] = i * 10 + 5; + } + self->lCounts[1] = self->fPreset; + self->fTime = self->fPreset; + return OKOK; } + /*-------------------------------------------------------------------------*/ static int RegressGetError(struct __COUNTER *self, int *iCode, char *error, - int iErrLen){ - strncpy(error, "Regression counter error", iErrLen); - *iCode = 1; + int iErrLen) +{ + strncpy(error, "Regression counter error", iErrLen); + *iCode = 1; + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int RegressTryAndFixIt(struct __COUNTER *self, int iCode) +{ + RegressSt *pSim = NULL; + + assert(self); + pSim = (RegressSt *) self->pData; + assert(pSim); + + if (pSim->recover == 1) { + pSim->errType = NONE; + return COREDO; + } else { + return COTERM; + } +} + +/*--------------------------------------------------------------------------*/ +static int RegressSet(struct __COUNTER *self, char *name, int iCter, + float FVal) +{ + RegressSt *pSim = NULL; + + assert(self); + pSim = (RegressSt *) self->pData; + assert(pSim); + + if (strcmp(name, "errortype") == 0) { + pSim->errType = (int) FVal; return 1; + } + if (strcmp(name, "recover") == 0) { + pSim->recover = (int) FVal; + return 1; + } + if (strcmp(name, "finish") == 0) { + pSim->state = STATEIDLE; + return 1; + } + return 0; } + /*--------------------------------------------------------------------------*/ -static int RegressTryAndFixIt(struct __COUNTER *self, int iCode){ - RegressSt *pSim = NULL; +static int RegressGet(struct __COUNTER *self, char *name, + int iCter, float *fVal) +{ + RegressSt *pSim = NULL; - assert(self); - pSim = (RegressSt *) self->pData; - assert(pSim); - - if(pSim->recover == 1){ - pSim->errType = NONE; - return COREDO; - } else { - return COTERM; - } + assert(self); + pSim = (RegressSt *) self->pData; + assert(pSim); + + if (strcmp(name, "errortype") == 0) { + *fVal = pSim->errType; + return 1; + } + if (strcmp(name, "recover") == 0) { + *fVal = pSim->recover; + return 1; + } + return 0; } -/*--------------------------------------------------------------------------*/ -static int RegressSet(struct __COUNTER *self, char *name, int iCter, float FVal){ - RegressSt *pSim = NULL; - assert(self); - pSim = (RegressSt *) self->pData; - assert(pSim); - - if(strcmp(name,"errortype") == 0){ - pSim->errType = (int)FVal; - return 1; - } - if(strcmp(name,"recover") == 0){ - pSim->recover = (int)FVal; - return 1; - } - if(strcmp(name,"finish") == 0){ - pSim->state = STATEIDLE; - return 1; - } - return 0; -} -/*--------------------------------------------------------------------------*/ -static int RegressGet(struct __COUNTER *self, char *name, - int iCter, float *fVal){ - RegressSt *pSim = NULL; - - assert(self); - pSim = (RegressSt *) self->pData; - assert(pSim); - - if(strcmp(name,"errortype") == 0){ - *fVal = pSim->errType; - return 1; - } - if(strcmp(name,"recover") == 0){ - *fVal = pSim->recover; - return 1; - } - return 0; -} /*---------------------------------------------------------------------------*/ static int RegressSend(struct __COUNTER *self, char *pText, - char *pReply, int iReplyLen){ - strncpy(pReply, "Simulated response", iReplyLen); - return 1; + char *pReply, int iReplyLen) +{ + strncpy(pReply, "Simulated response", iReplyLen); + return 1; } + /*---------------------------------------------------------------------------*/ -pCounterDriver NewRegressCounter(char *name){ - pCounterDriver pRes = NULL; - RegressSt *pData = NULL; - int iRet; - int iC1, iC2, iC3; - char *pErr; - char pBueffel[132]; +pCounterDriver NewRegressCounter(char *name) +{ + pCounterDriver pRes = NULL; + RegressSt *pData = NULL; + int iRet; + int iC1, iC2, iC3; + char *pErr; + char pBueffel[132]; - pRes = CreateCounterDriver(name, "Regress"); - if (!pRes) { - return NULL; - } + pRes = CreateCounterDriver(name, "Regress"); + if (!pRes) { + return NULL; + } - pData = (RegressSt *) malloc(sizeof(RegressSt)); - if (!pData) { - DeleteCounterDriver(pRes); - return NULL; - } - memset(pData,0,sizeof(RegressSt)); - pRes->pData = pData; + pData = (RegressSt *) malloc(sizeof(RegressSt)); + if (!pData) { + DeleteCounterDriver(pRes); + return NULL; + } + memset(pData, 0, sizeof(RegressSt)); + pRes->pData = pData; - /* - * assign functions - */ - pRes->GetStatus = RegressGetStatus; - pRes->Start = RegressStart; - pRes->Halt = RegressHalt; - pRes->ReadValues = RegressReadValues; - pRes->GetError = RegressGetError; - pRes->TryAndFixIt = RegressTryAndFixIt; - pRes->Pause = RegressPause; - pRes->Continue = RegressContinue; - pRes->Set = RegressSet; - pRes->Get = RegressGet; - pRes->Send = RegressSend; - pRes->KillPrivate = NULL; - pRes->iNoOfMonitors = 8; + /* + * assign functions + */ + pRes->GetStatus = RegressGetStatus; + pRes->Start = RegressStart; + pRes->Halt = RegressHalt; + pRes->ReadValues = RegressReadValues; + pRes->GetError = RegressGetError; + pRes->TryAndFixIt = RegressTryAndFixIt; + pRes->Pause = RegressPause; + pRes->Continue = RegressContinue; + pRes->Set = RegressSet; + pRes->Get = RegressGet; + pRes->Send = RegressSend; + pRes->KillPrivate = NULL; + pRes->iNoOfMonitors = 8; - return pRes; + return pRes; } diff --git a/remob.c b/remob.c index ad168088..f3b7d782 100644 --- a/remob.c +++ b/remob.c @@ -35,7 +35,7 @@ typedef struct RemChannel { } RemChannel; typedef struct RemServer { - pObjectDescriptor desc; + pObjectDescriptor desc; char *name; char *host; int port; @@ -49,7 +49,7 @@ typedef struct RemServer { } RemServer; struct Remob { - pObjectDescriptor desc; + pObjectDescriptor desc; char *name; pIDrivable pDrivInt; pICallBack pCall; @@ -70,70 +70,81 @@ typedef struct { } RemobInfo; /*-------------------------------------------------------------------------*/ -static char *StartsWith(char *line, char *name) { +static char *StartsWith(char *line, char *name) +{ /* if line does not start with name, return NULL else return a pointer to the next non-white space character - */ + */ char *str; int l; - + l = strlen(name); - if (0 != strncmp(line, name, l)) return NULL; + if (0 != strncmp(line, name, l)) + return NULL; str = line + l; while (*str == ' ') { str++; } return str; } + /*-------------------------------------------------------------------------*/ -static int RemWrite(RemChannel *rc, char *line) { +static int RemWrite(RemChannel * rc, char *line) +{ int iret; - + if (rc->chan) { /* printf("> %s\n", line); */ iret = NETWrite(rc->chan, line, strlen(line)); - if (iret == 0) iret = -1; + if (iret == 0) + iret = -1; return iret; } else { return -1; - } + } } + /*-------------------------------------------------------------------------*/ -static int RemRead(RemChannel *rc, long tmo) { +static int RemRead(RemChannel * rc, long tmo) +{ int iRet; - - if (rc->chan == NULL) return 0; /* no data */ + + if (rc->chan == NULL) + return 0; /* no data */ iRet = NETReadTillTerm(rc->chan, tmo, "\n", rc->line + rc->incomplete, - sizeof(rc->line) - rc->incomplete); + sizeof(rc->line) - rc->incomplete); if (iRet == 0) { - rc->incomplete = strlen(rc->line); /* number of chars already received */ - return 0; /* timeout */ + rc->incomplete = strlen(rc->line); /* number of chars already received */ + return 0; /* timeout */ } else { - rc->incomplete=0; + rc->incomplete = 0; } return iRet; } + /*-------------------------------------------------------------------------*/ -static int RemHandle(RemServer *remserver) { +static int RemHandle(RemServer * remserver) +{ char *line, *par, *str; Remob *remob; RemChannel *rc; - - rc = &remserver->rc[0]; /* drivstat messages appear only on the spy channel */ - + + rc = &remserver->rc[0]; /* drivstat messages appear only on the spy channel */ + /* skip whitespace at the beginning */ - line=rc->line; - if (line[0] == '\0') return 0; /* return when line is empty */ + line = rc->line; + if (line[0] == '\0') + return 0; /* return when line is empty */ while (*line < ' ' && *line != '\0') { line++; } memmove(rc->line, line, strlen(line)); - + /* handle drivstat messages */ line = rc->line; - + for (remob = remserver->objList; remob != NULL; remob = remob->next) { - par=StartsWith(line, remob->name); + par = StartsWith(line, remob->name); if (par != NULL) { if ((str = StartsWith(par, "finished"))) { if (*str == '\0') { @@ -141,30 +152,34 @@ static int RemHandle(RemServer *remserver) { } else { remob->status = HWFault; } - line[0]='\0'; + line[0] = '\0'; return 1; } if ((str = StartsWith(par, "started"))) { remob->status = HWBusy; - line[0]='\0'; + line[0] = '\0'; return 1; } } } return 0; } + /*-------------------------------------------------------------------------*/ -static void RemCopy(RemChannel *rc, SConnection *pCon) { +static void RemCopy(RemChannel * rc, SConnection * pCon) +{ if (pCon != NULL && rc->line[0] != '\0') { SCPrintf(pCon, eLog, " %s", rc->line); } } + /*-------------------------------------------------------------------------*/ -static void RemDisconnect(RemServer *remserver) { +static void RemDisconnect(RemServer * remserver) +{ int isUser; RemChannel *rc; - - for (isUser=0; isUser<=1; isUser++) { + + for (isUser = 0; isUser <= 1; isUser++) { rc = &remserver->rc[isUser]; if (rc->chan != NULL) { NETClosePort(rc->chan); @@ -174,15 +189,17 @@ static void RemDisconnect(RemServer *remserver) { } } } + /*-------------------------------------------------------------------------*/ -static int RemSetInterest(RemChannel *rc) { +static int RemSetInterest(RemChannel * rc) +{ int iRet; - - if (rc->chan != NULL) { /* already connected */ + + if (rc->chan != NULL) { /* already connected */ iRet = RemWrite(rc, "transact listexe interest\n"); if (iRet >= 0) { iRet = RemRead(rc, 1000); - while (iRet > 0) { /* eat response */ + while (iRet > 0) { /* eat response */ if (StartsWith(rc->line, "TRANSACTIONFINISHED")) { return 1; } @@ -192,14 +209,16 @@ static int RemSetInterest(RemChannel *rc) { } return 0; } + /*-------------------------------------------------------------------------*/ -static void RemConnect(RemServer *remserver, int both) { +static void RemConnect(RemServer * remserver, int both) +{ /* open channel 0 or both channels, if not yet opened */ int iRet; mkChannel *chan; int i; RemChannel *rc; - + for (i = 0; i <= both; i++) { rc = &remserver->rc[i]; if (!rc->chan) { @@ -209,24 +228,27 @@ static void RemConnect(RemServer *remserver, int both) { return; } rc->chan = chan; - if (i != 0) { /* open the user channel */ + if (i != 0) { /* open the user channel */ iRet = RemWrite(rc, "remuser sesam\n"); - } else { /* open spy channel */ + } else { /* open spy channel */ iRet = RemWrite(rc, "Spy 007\n"); } - if (iRet < 0) goto close; + if (iRet < 0) + goto close; iRet = RemRead(rc, 1000); - while (iRet > 0) { /* eat login response */ + while (iRet > 0) { /* eat login response */ if (StartsWith(rc->line, "Login OK")) { /* printf("connected\n"); */ - if (remserver->interestActive && rc == &remserver->rc[0]) { /* open the user channel */ - if (!RemSetInterest(rc)) goto close; + if (remserver->interestActive && rc == &remserver->rc[0]) { /* open the user channel */ + if (!RemSetInterest(rc)) + goto close; } break; } iRet = RemRead(rc, 1000); } - if (iRet <= 0) goto close; + if (iRet <= 0) + goto close; } } return; @@ -234,26 +256,30 @@ close: RemDisconnect(remserver); return; } + /*-------------------------------------------------------------------------*/ -static int RemServerTask(void *data) { - RemServer *remserver=data; +static int RemServerTask(void *data) +{ + RemServer *remserver = data; int iRet; SConnection *pCon; int isUser; RemChannel *rc; - - if (!remserver->taskActive) return 0; /* remove task */ - + + if (!remserver->taskActive) + return 0; /* remove task */ + for (isUser = 0; isUser <= 1; isUser++) { rc = &remserver->rc[isUser]; - if (RemRead(rc, 0) <= 0) continue; + if (RemRead(rc, 0) <= 0) + continue; if (strstr(rc->line, " ") == rc->line) { WriteToCommandLog("REMOB>", "infinite echo loop detected"); continue; } if (isUser == 0) { - if (RemHandle(remserver)) { /* handle drivstat messages */ + if (RemHandle(remserver)) { /* handle drivstat messages */ continue; } } @@ -267,15 +293,17 @@ static int RemServerTask(void *data) { } return 1; } + /*-------------------------------------------------------------------------*/ -static int RemTransact(RemServer *remserver, int nChan, SConnection *pCon, - char *cmd, ...) { +static int RemTransact(RemServer * remserver, int nChan, + SConnection * pCon, char *cmd, ...) +{ /* the variable arguments are for filtering: - + "" write untreated lines to pCon - */ + */ char *buffer; int bufferLen; int iRet; @@ -286,50 +314,53 @@ static int RemTransact(RemServer *remserver, int nChan, SConnection *pCon, int argMask; RemChannel *rc = &remserver->rc[nChan]; - try=3; - if (rc->timeout) { /* eat old responses */ + try = 3; + if (rc->timeout) { /* eat old responses */ while (RemRead(rc, 0) > 0) { RemHandle(remserver); } } tryagain: - bufferLen = strlen(cmd)+16; - buffer=malloc(bufferLen); + bufferLen = strlen(cmd) + 16; + buffer = malloc(bufferLen); if (buffer == NULL) { - SCPrintf(pCon, eError, "ERROR: can not get another %d bytes", bufferLen); + SCPrintf(pCon, eError, "ERROR: can not get another %d bytes", + bufferLen); return 0; } snprintf(buffer, bufferLen, "transact %s\n", cmd); RemConnect(remserver, nChan); iRet = RemWrite(rc, buffer); free(buffer); - if (iRet < 0) goto close; - + if (iRet < 0) + goto close; + iRet = RemRead(rc, 2000); - if (iRet <= 0) goto close; + if (iRet <= 0) + goto close; while (!StartsWith(rc->line, "TRANSACTIONFINISHED")) { RemHandle(remserver); va_start(ap, cmd); arg = va_arg(ap, char *); - argMask=1; + argMask = 1; remserver->matchMap = 0; while (arg != NULL) { if (*arg == '>') { RemCopy(rc, pCon); } else if (*arg == '<') { f = va_arg(ap, float *); - val = StartsWith(rc->line, arg+1); + val = StartsWith(rc->line, arg + 1); if (val != NULL) { val = StartsWith(val, "="); if (val != NULL) { *f = strtod(val, &endp); break; - } + } } } else if (*arg == '!') { - if (StartsWith(rc->line, arg+1)) { + if (StartsWith(rc->line, arg + 1)) { remserver->matchMap |= argMask; - argMask = argMask*2; + argMask = argMask * 2; break; } } else { @@ -340,7 +371,8 @@ tryagain: } va_end(ap); iRet = RemRead(rc, 2000); - if (iRet <= 0) goto close; + if (iRet <= 0) + goto close; } return 1; close: @@ -355,29 +387,34 @@ close: } RemDisconnect(remserver); try--; - if (try>0) goto tryagain; + if (try > 0) + goto tryagain; SCPrintf(pCon, eError, "ERROR: no connection to %s", remserver->name); return iRet; } + /*-------------------------------------------------------------------------*/ -static void *RemobGetInterface(void *pData, int iID) { +static void *RemobGetInterface(void *pData, int iID) +{ Remob *self = pData; - + assert(self); - if(iID == DRIVEID) { + if (iID == DRIVEID) { return self->pDrivInt; - } else if(iID == CALLBACKINTERFACE) { + } else if (iID == CALLBACKINTERFACE) { return self->pCall; } return NULL; } + /*------------------------------------------------------------------------*/ -static int RemobHalt(void *self) { - Remob *remob=self; +static int RemobHalt(void *self) +{ + Remob *remob = self; RemServer *remserver = remob->server; - RemChannel *rc = &remserver->rc[1]; /* Halt is only called with at least user priv. */ + RemChannel *rc = &remserver->rc[1]; /* Halt is only called with at least user priv. */ char buf[64]; - + assert(remob); RemConnect(remserver, 1); snprintf(buf, sizeof(buf), "stopexe %s\n", remob->name); @@ -386,33 +423,37 @@ static int RemobHalt(void *self) { } /*--------------------------------------------------------------------------*/ -static int RemobLimits(void *self, float fVal, char *error, int iErrLen) { +static int RemobLimits(void *self, float fVal, char *error, int iErrLen) +{ float fHard; - Remob *remob=self; - + Remob *remob = self; + assert(remob); /* check is done on remote server */ return 1; } + /*---------------------------------------------------------------------------*/ -static float RemobGetValue(void *pData, SConnection *pCon) { - Remob *remob=pData; +static float RemobGetValue(void *pData, SConnection * pCon) +{ + Remob *remob = pData; RemServer *remserver = remob->server; char buf[80]; float none, value; int iRet; - + assert(remob); - - if(remserver->conn != NULL){ - SCDeleteConnection(remserver->conn); + + if (remserver->conn != NULL) { + SCDeleteConnection(remserver->conn); } remserver->conn = SCCopyConnection(pCon); none = -1.25e6; - value= none; + value = none; snprintf(buf, sizeof(buf), "<%s", remob->name); /* get value needs only spy priviledge */ - iRet = RemTransact(remserver, 0, pCon, remob->name, buf, &value, ">", NULL); + iRet = + RemTransact(remserver, 0, pCon, remob->name, buf, &value, ">", NULL); if (iRet <= 0) { return 0.0; } @@ -422,51 +463,61 @@ static float RemobGetValue(void *pData, SConnection *pCon) { snprintf(buf, sizeof(buf), "can not get %s", remob->name); SCWrite(pCon, buf, eWarning); return 0.0; -} +} + /*------------------------------------------------------------------------*/ -static int RemobSaveStatus(void *pData, char *name, FILE *fil) { +static int RemobSaveStatus(void *pData, char *name, FILE * fil) +{ Remob *self = pData; - + assert(self); assert(fil); - + /* - data is stored on remote server - */ + data is stored on remote server + */ return 1; } + /*------------------------------------------------------------------------*/ -static int RemServerSaveStatus(void *pData, char *name, FILE *fil) { +static int RemServerSaveStatus(void *pData, char *name, FILE * fil) +{ RemServer *remserver = pData; Remob *remob; - + assert(remserver); assert(fil); for (remob = remserver->objList; remob != NULL; remob = remob->next) { if (remob->pDrivInt) { - fprintf(fil, "catch { remob drv %s %s }\n", remob->name, remserver->name); + fprintf(fil, "catch { remob drv %s %s }\n", remob->name, + remserver->name); } else { - fprintf(fil, "catch { remob obj %s %s }\n", remob->name, remserver->name); + fprintf(fil, "catch { remob obj %s %s }\n", remob->name, + remserver->name); } } return 1; } + /*------------------------------------------------------------------------*/ -static int RemobStatus(void *pData, SConnection *pCon) { - Remob *remob=pData; - +static int RemobStatus(void *pData, SConnection * pCon) +{ + Remob *remob = pData; + assert(remob); - - if(remob->server->conn != NULL){ - SCDeleteConnection(remob->server->conn); + + if (remob->server->conn != NULL) { + SCDeleteConnection(remob->server->conn); } remob->server->conn = SCCopyConnection(pCon); return remob->status; } + /*---------------------------------------------------------------------------*/ -static long RemobRun(void *self, SConnection *pCon, float fNew) { - Remob *remob=self; +static long RemobRun(void *self, SConnection * pCon, float fNew) +{ + Remob *remob = self; float fHard; int i, iRet, iCode; char buf[512], sBuf[64]; @@ -483,41 +534,48 @@ static long RemobRun(void *self, SConnection *pCon, float fNew) { assert(pCon); remserver = remob->server; - if(remserver->conn != NULL){ - SCDeleteConnection(remserver->conn); + if (remserver->conn != NULL) { + SCDeleteConnection(remserver->conn); } remserver->conn = SCCopyConnection(pCon); - + rights = SCGetRights(pCon); nChan = rights <= usUser; rc = &remserver->rc[nChan]; - RemConnect(remserver, 0); /* connect spy for listexe interest */ + RemConnect(remserver, 0); /* connect spy for listexe interest */ remob->status = HWIdle; snprintf(buf, sizeof(buf), "run %s %f", remob->name, fNew); - iRet = RemTransact(remserver, nChan, pCon, buf, "!ERROR: somebody else", "!ERROR: cannot", ">", NULL); - if (iRet <= 0) return 0; + iRet = + RemTransact(remserver, nChan, pCon, buf, "!ERROR: somebody else", + "!ERROR: cannot", ">", NULL); + if (iRet <= 0) + return 0; - if (remserver->matchMap & 1) { /* already running, stop first */ + if (remserver->matchMap & 1) { /* already running, stop first */ remob->status = HWBusy; snprintf(sBuf, sizeof(sBuf), "stopexe %s", remob->name); iRet = RemTransact(remserver, nChan, pCon, sBuf, ">", NULL); - if (iRet <= 0) return 0; + if (iRet <= 0) + return 0; while (remob->status == HWBusy) { iRet = RemRead(rc, 1000); - if (iRet <= 0) break; - if (! RemHandle(remserver)) { + if (iRet <= 0) + break; + if (!RemHandle(remserver)) { RemCopy(rc, pCon); } } iRet = RemTransact(remserver, nChan, pCon, buf, ">", NULL); - if (iRet <= 0) return 0; + if (iRet <= 0) + return 0; } /* wait for "started" message */ while (remob->status != HWBusy) { iRet = RemRead(&remserver->rc[0], 1000); - if (iRet <= 0) break; - if (! RemHandle(remserver)) { + if (iRet <= 0) + break; + if (!RemHandle(remserver)) { RemCopy(&remserver->rc[0], pCon); } } @@ -526,41 +584,48 @@ static long RemobRun(void *self, SConnection *pCon, float fNew) { } return OKOK; } + /*-----------------------------------------------------------------------*/ -static void KillInfo(void *pData) { +static void KillInfo(void *pData) +{ RemobInfo *self = pData; - + assert(self); if (self->pName) { free(self->pName); } - if(self->pCon){ - SCDeleteConnection(self->pCon); + if (self->pCon) { + SCDeleteConnection(self->pCon); } free(self); } + /*------------------- The CallBack function for interest ------------------*/ -static int InterestCallback(int iEvent, void *pEvent, void *pUser) { +static int InterestCallback(int iEvent, void *pEvent, void *pUser) +{ RemobCallback *psCall = pEvent; RemobInfo *pInfo = pUser; char buf[80]; - + assert(psCall); assert(pInfo); - - snprintf(buf, sizeof(buf),"%s.position = %f ", pInfo->pName, psCall->fVal); - SCWrite(pInfo->pCon,buf,eValue); + + snprintf(buf, sizeof(buf), "%s.position = %f ", pInfo->pName, + psCall->fVal); + SCWrite(pInfo->pCon, buf, eValue); return 1; -} +} + /*---------------------------------------------------------------------------*/ -int RemobAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) { +int RemobAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ Remob *remob = pData; RemServer *remserver = remob->server; char buf[512]; TokenList *pList = NULL; TokenList *pCurrent; - TokenList *pName; + TokenList *pName; int iRet; int i; int pos; @@ -569,63 +634,66 @@ int RemobAction(SConnection *pCon, SicsInterp *pSics, void *pData, char *endp; char *cmd; /* - char acce[128], inte[128]; - */ + char acce[128], inte[128]; + */ int rights; int nChan; RemChannel *rc; - + assert(pCon); assert(pSics); assert(remob); - + rights = SCGetRights(pCon); nChan = (rights <= usUser); rc = &remserver->rc[nChan]; if (rights >= usUser) { - if(remserver->conn != NULL){ - SCDeleteConnection(remserver->conn); - } + if (remserver->conn != NULL) { + SCDeleteConnection(remserver->conn); + } remserver->conn = SCCopyConnection(pCon); } if (argc == 1) { iRet = RemTransact(remserver, nChan, pCon, remob->name, ">", NULL); - } else if (strcasecmp(argv[1],"interest") == 0) { + } else if (strcasecmp(argv[1], "interest") == 0) { /* ignore interest commands, as they would not work properly */ - iRet=1; - } else if (strcasecmp(argv[1],"list") == 0) { + iRet = 1; + } else if (strcasecmp(argv[1], "list") == 0) { /* - snprintf(acce, sizeof(acce), "!%s.accesscode", remob->name); - snprintf(inte, sizeof(inte), "!%s.interruptmode", remob->name); - */ - - cmd = Arg2Tcl0(argc-1, argv+1, buf, sizeof buf, remob->name); + snprintf(acce, sizeof(acce), "!%s.accesscode", remob->name); + snprintf(inte, sizeof(inte), "!%s.interruptmode", remob->name); + */ + + cmd = Arg2Tcl0(argc - 1, argv + 1, buf, sizeof buf, remob->name); if (cmd) { RemTransact(remserver, nChan, pCon, cmd, ">", NULL); - if (cmd != buf) free(cmd); + if (cmd != buf) + free(cmd); } - iRet=1; + iRet = 1; } else { - pos=snprintf(buf, sizeof(buf), "%s ", remob->name); - for (i=1; iname); + for (i = 1; i < argc; i++) { + pos += snprintf(buf + pos, sizeof(buf) - pos, "%s ", argv[i]); } iRet = RemTransact(remserver, nChan, pCon, buf, ">", NULL); } return iRet; } + /*--------------------------------------------------------------------------*/ -static void RemobKill(void *self) { +static void RemobKill(void *self) +{ Remob *remob = self; Remob *p, **last; - + assert(remob); - + /* remove from object list */ if (remob->server) { last = &remob->server->objList; p = *last; - while (p != remob && p !=NULL) { + while (p != remob && p != NULL) { last = &p->next; p = p->next; } @@ -636,27 +704,29 @@ static void RemobKill(void *self) { } if (remob->name) { free(remob->name); - } + } if (remob->pDrivInt) { free(remob->pDrivInt); - } + } if (remob->pCall) { DeleteCallBackInterface(remob->pCall); } - + /* kill Descriptor */ if (remob->desc) { DeleteDescriptor(remob->desc); } free(remob); -} +} + /*---------------------------------------------------------------------------*/ -int RemServerAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) { +int RemServerAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ RemServer *remserver = pData; TokenList *pList = NULL; TokenList *pCurrent; - TokenList *pName; + TokenList *pName; int iRet; socklen_t i; int pos; @@ -669,55 +739,58 @@ int RemServerAction(SConnection *pCon, SicsInterp *pSics, void *pData, int rights, nChan; RemChannel *rc; char *args; - + assert(pCon); assert(pSics); assert(remserver); - + rights = SCGetRights(pCon); nChan = (rights <= usUser); rc = &remserver->rc[nChan]; if (nChan) { - if(remserver->conn != NULL){ - SCDeleteConnection(remserver->conn); - } + if (remserver->conn != NULL) { + SCDeleteConnection(remserver->conn); + } remserver->conn = SCCopyConnection(pCon); } if (argc == 1) { - serverport = IFindOption(pSICSOptions,"ServerPort"); + serverport = IFindOption(pSICSOptions, "ServerPort"); i = sizeof adr; thishostname = NULL; if (rc->chan) { - if (getsockname(rc->chan->sockid, (void *)&adr, &i) >= 0) { - thishost = gethostbyaddr((char *)&adr.sin_addr, - sizeof adr.sin_addr, AF_INET); + if (getsockname(rc->chan->sockid, (void *) &adr, &i) >= 0) { + thishost = gethostbyaddr((char *) &adr.sin_addr, + sizeof adr.sin_addr, AF_INET); if (thishost) { thishostname = thishost->h_name; } } } - if (thishostname == NULL) thishostname = "undef"; + if (thishostname == NULL) + thishostname = "undef"; SCPrintf(pCon, eValue, "%s = %s:%d %s:%s", - argv[0], remserver->host, remserver->port, thishostname, serverport); - } else if (argc>2 && strcasecmp(argv[1],"nowait") == 0) { + argv[0], remserver->host, remserver->port, thishostname, + serverport); + } else if (argc > 2 && strcasecmp(argv[1], "nowait") == 0) { RemConnect(remserver, nChan); - args = Arg2Tcl(argc-2, argv+2, NULL, 0); + args = Arg2Tcl(argc - 2, argv + 2, NULL, 0); RemWrite(rc, args); RemWrite(rc, "\n"); free(args); - } else if (argc==2 && strcasecmp(argv[1],"markForDel") == 0) { + } else if (argc == 2 && strcasecmp(argv[1], "markForDel") == 0) { p = remserver->objList; while (p) { p->markForDel = 1; p = p->next; } - } else if (argc==2 && strcasecmp(argv[1],"delMarked") == 0) { + } else if (argc == 2 && strcasecmp(argv[1], "delMarked") == 0) { p = remserver->objList; while (p) { next = p->next; if (p->markForDel) { - if (p->pDrivInt && pServ->pExecutor && isInRunMode(pServ->pExecutor)) { - SCWrite(pCon,"ERROR: cannot delete while running",eError); + if (p->pDrivInt && pServ->pExecutor + && isInRunMode(pServ->pExecutor)) { + SCWrite(pCon, "ERROR: cannot delete while running", eError); return 0; } RemoveCommand(pSics, p->name); @@ -725,22 +798,24 @@ int RemServerAction(SConnection *pCon, SicsInterp *pSics, void *pData, p = next; } } else { - args = Arg2Tcl(argc-1, argv+1, NULL, 0); + args = Arg2Tcl(argc - 1, argv + 1, NULL, 0); iRet = RemTransact(remserver, nChan, pCon, args, ">", NULL); free(args); return iRet; } return 1; } + /*--------------------------------------------------------------------------*/ -static void RemServerKill(void *self) { +static void RemServerKill(void *self) +{ RemServer *remserver = self; Remob *remob, *next; - + assert(remserver); - + if (remserver->taskActive) { - remserver->taskActive=0; + remserver->taskActive = 0; /* let the tasker kill me */ return; } @@ -752,21 +827,26 @@ static void RemServerKill(void *self) { } RemDisconnect(remserver); DeleteDescriptor(remserver->desc); - if (remserver->name) free(remserver->name); - if (remserver->host) free(remserver->host); - if(remserver->conn != NULL){ - SCDeleteConnection(remserver->conn); + if (remserver->name) + free(remserver->name); + if (remserver->host) + free(remserver->host); + if (remserver->conn != NULL) { + SCDeleteConnection(remserver->conn); } free(remserver); } + /*-----------------------------------------------------------------------*/ -static int RemobSetDriveable(Remob *remob, int driveable) { +static int RemobSetDriveable(Remob * remob, int driveable) +{ RemChannel *rc; - + if (driveable) { /* initialise Drivable interface */ remob->pDrivInt = CreateDrivableInterface(); - if (!remob->pDrivInt) return 0; + if (!remob->pDrivInt) + return 0; remob->pDrivInt->SetValue = RemobRun; remob->pDrivInt->CheckLimits = RemobLimits; remob->pDrivInt->CheckStatus = RemobStatus; @@ -775,8 +855,8 @@ static int RemobSetDriveable(Remob *remob, int driveable) { if (remob->server->interestActive == 0) { rc = &remob->server->rc[0]; remob->server->interestActive = 1; - if (! RemSetInterest(rc)) { - RemDisconnect(remob->server); /* disconnect on error, RemSetInterest will be called again on connect */ + if (!RemSetInterest(rc)) { + RemDisconnect(remob->server); /* disconnect on error, RemSetInterest will be called again on connect */ } } } else if (remob->pDrivInt) { @@ -785,35 +865,40 @@ static int RemobSetDriveable(Remob *remob, int driveable) { } return 1; } + /*-----------------------------------------------------------------------*/ -static Remob *RemobInit(char *name, RemServer *remserver) { +static Remob *RemobInit(char *name, RemServer * remserver) +{ Remob *remob, *p; assert(name); - + /* get memory */ - remob = (Remob *)calloc(1,sizeof(Remob)); - if(!remob) { + remob = (Remob *) calloc(1, sizeof(Remob)); + if (!remob) { return NULL; } - + /* copy arguments */ remob->server = remserver; remob->name = strdup(name); - - /* initialise object descriptor */ + + /* initialise object descriptor */ remob->desc = CreateDescriptor("RemObject"); - if (!remob->desc) goto killit; + if (!remob->desc) + goto killit; remob->desc->GetInterface = RemobGetInterface; remob->desc->SaveStatus = RemobSaveStatus; - + /* initialise callback interface */ remob->pCall = CreateCallBackInterface(); - if(!remob->pCall) goto killit; - + if (!remob->pCall) + goto killit; + /* check if not yet in object list */ - for (p = remserver->objList; p != NULL; p=p->next) { - if (p == remob) break; + for (p = remserver->objList; p != NULL; p = p->next) { + if (p == remob) + break; } if (p == NULL) { remob->next = remserver->objList; @@ -827,20 +912,22 @@ killit: RemobKill(remob); return NULL; } + /*-----------------------------------------------------------------------*/ -static RemServer *RemServerInit(char *name, char *host, int port) { +static RemServer *RemServerInit(char *name, char *host, int port) +{ RemServer *remserver = NULL; RemChannel *rc; int isUser; - + assert(name); - + remserver = calloc(1, sizeof(RemServer)); if (!remserver) { return 0; } - - /* initialise object descriptor */ + + /* initialise object descriptor */ remserver->desc = CreateDescriptor("RemServer"); if (!remserver->desc) { free(remserver); @@ -850,7 +937,7 @@ static RemServer *RemServerInit(char *name, char *host, int port) { remserver->name = strdup(name); remserver->host = strdup(host); remserver->port = port; - for (isUser=0; isUser <= 1; isUser++) { + for (isUser = 0; isUser <= 1; isUser++) { rc = &remserver->rc[isUser]; rc->incomplete = 0; rc->chan = NULL; @@ -858,9 +945,7 @@ static RemServer *RemServerInit(char *name, char *host, int port) { } remserver->objList = NULL; remserver->conn = NULL; - if (!remserver->name || - !remserver->host || - !remserver->port) { + if (!remserver->name || !remserver->host || !remserver->port) { /* no success, clean up */ RemServerKill(remserver); return NULL; @@ -868,9 +953,11 @@ static RemServer *RemServerInit(char *name, char *host, int port) { remserver->taskActive = 1; remserver->interestActive = 0; remserver->forwardMessages = 1; - TaskRegister(pServ->pTasker, RemServerTask, NULL, RemServerKill, remserver, 1); + TaskRegister(pServ->pTasker, RemServerTask, NULL, RemServerKill, + remserver, 1); return remserver; } + /*-------------------------------------------------------------------------- The Factory function for creating a remote driveable object. @@ -882,19 +969,20 @@ static RemServer *RemServerInit(char *name, char *host, int port) { Remob del serverName */ -int RemobCreate(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) { +int RemobCreate(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ RemServer *remserver = NULL; Remob *remob = NULL; char host[128]; char *p; int iD, iRet; char *obj; - + assert(pCon); assert(pSics); - - argtolower(argc,argv); + + argtolower(argc, argv); if (argc >= 4 && strcmp(argv[1], "server") == 0) { if (argc >= 5) { remserver = RemServerInit(argv[2], argv[3], atoi(argv[4])); @@ -907,23 +995,30 @@ int RemobCreate(SConnection *pCon, SicsInterp *pSics, void *pData, SCPrintf(pCon, eError, "ERROR: illegal host:port"); return 0; } - snprintf(host, sizeof host, "%.*s", p-argv[3], argv[3]); - remserver = RemServerInit(argv[2], host, atoi(p+1)); + snprintf(host, sizeof host, "%.*s", p - argv[3], argv[3]); + remserver = RemServerInit(argv[2], host, atoi(p + 1)); } if (!remserver) { - SCPrintf(pCon, eError, "ERROR: Failure to create remote server connection %s", argv[2]); + SCPrintf(pCon, eError, + "ERROR: Failure to create remote server connection %s", + argv[2]); return 0; } /* create the interpreter command */ - iRet = AddCommand(pSics,argv[2],RemServerAction,RemServerKill,remserver); + iRet = + AddCommand(pSics, argv[2], RemServerAction, RemServerKill, + remserver); if (!iRet) { - SCPrintf(pCon, eError, "ERROR: duplicate command %s not created",argv[2]); + SCPrintf(pCon, eError, "ERROR: duplicate command %s not created", + argv[2]); RemServerKill(remserver); return 0; } - + return 1; - } else if (argc == 4 && (strcmp(argv[1], "obj") == 0 || strcmp(argv[1], "drv") == 0)) { + } else if (argc == 4 + && (strcmp(argv[1], "obj") == 0 + || strcmp(argv[1], "drv") == 0)) { remserver = FindCommandData(pServ->pSics, argv[3], "RemServer"); if (!remserver) { SCPrintf(pCon, eError, "ERROR: remote server %s not found", argv[3]); @@ -934,47 +1029,49 @@ int RemobCreate(SConnection *pCon, SicsInterp *pSics, void *pData, if (remob->server == remserver) { RemobSetDriveable(remob, strcmp(argv[1], "drv") == 0); remob->markForDel = 0; - return 1; /* object exists already, silent return */ + return 1; /* object exists already, silent return */ } } remob = RemobInit(argv[2], remserver); if (!remob) { - SCPrintf(pCon, eError, "ERROR: Failure to create remote object %s", argv[1]); + SCPrintf(pCon, eError, "ERROR: Failure to create remote object %s", + argv[1]); return 0; } RemobSetDriveable(remob, strcmp(argv[1], "drv") == 0); /* create the interpreter command */ - iRet = AddCommand(pSics,argv[2],RemobAction,RemobKill,remob); + iRet = AddCommand(pSics, argv[2], RemobAction, RemobKill, remob); SCparChange(pCon); if (!iRet) { - SCPrintf(pCon, eError, "ERROR: duplicate command %s not created",argv[2]); + SCPrintf(pCon, eError, "ERROR: duplicate command %s not created", + argv[2]); RemobKill(remob); return 0; } return 1; } else if (argc == 3 && strcmp(argv[1], "del") == 0) { remob = FindCommandData(pSics, argv[2], "RemObject"); - if (remob) { /* its a remob */ - if (remob->pDrivInt && pServ->pExecutor && isInRunMode(pServ->pExecutor)) { - SCPrintf(pCon,eError,"ERROR: cannot delete %s while running", argv[2]); + if (remob) { /* its a remob */ + if (remob->pDrivInt && pServ->pExecutor + && isInRunMode(pServ->pExecutor)) { + SCPrintf(pCon, eError, "ERROR: cannot delete %s while running", + argv[2]); return 0; } return RemoveCommand(pSics, argv[2]); } if (pServ->pExecutor && isInRunMode(pServ->pExecutor)) { - SCPrintf(pCon,eError,"ERROR: cannot delete %s while running", argv[2]); + SCPrintf(pCon, eError, "ERROR: cannot delete %s while running", + argv[2]); return 0; } remserver = FindCommandData(pSics, argv[2], "RemServer"); - if (remserver) { /* its a remserver */ + if (remserver) { /* its a remserver */ return RemoveCommand(pSics, argv[2]); } - SCWrite(pCon,"ERROR: remob object not found",eError); + SCWrite(pCon, "ERROR: remob object not found", eError); return 0; } SCPrintf(pCon, eError, "ERROR: illegal arguments for command remob"); return 0; } - - - diff --git a/remob.h b/remob.h index fed42c5f..4e6087f0 100644 --- a/remob.h +++ b/remob.h @@ -10,10 +10,9 @@ copyright: see implementation file #define SICSREM #include "Scommon.h" -/*-------------------------------------------------------------------------*/ +/*-------------------------------------------------------------------------*/ -int RemobCreate(SConnection *pCon, SicsInterp *pSics, void *pData, +int RemobCreate(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]); - -#endif +#endif diff --git a/rmlead.c b/rmlead.c index 53558274..75bceb11 100644 --- a/rmlead.c +++ b/rmlead.c @@ -1,26 +1,26 @@ -/* -** Originally published as part of the MicroFirm Function Library -** -** Copyright 1986, S.E. Margison -** Copyright 1989, Robert B.Stout -** -** Subset version released to the public domain, 1991 -** -** remove leading whitespace from a string -*/ - -#include -#include - -#define NUL '\0' - -char *rmlead(char *str) +/* +** Originally published as part of the MicroFirm Function Library +** +** Copyright 1986, S.E. Margison +** Copyright 1989, Robert B.Stout +** +** Subset version released to the public domain, 1991 +** +** remove leading whitespace from a string +*/ + +#include +#include + +#define NUL '\0' + char *rmlead(char *str) { - char *obuf; + char *obuf; + for (obuf = str; obuf && *obuf && isspace(*obuf); ++obuf) + ; + if (str != obuf) + strcpy(str, obuf); + return str; + } - for (obuf = str; obuf && *obuf && isspace(*obuf); ++obuf) - ; - if (str != obuf) - strcpy(str, obuf); - return str; -} + diff --git a/rmtrail.c b/rmtrail.c index 154168c3..e16b9898 100644 --- a/rmtrail.c +++ b/rmtrail.c @@ -16,16 +16,14 @@ char *rmtrail(char *str) { - int i; + int i; - if (0 != (i = strlen(str))) - { - while (--i >= 0) - { - if (!isspace(str[i])) - break; - } - str[++i] = NUL; - } - return str; + if (0 != (i = strlen(str))) { + while (--i >= 0) { + if (!isspace(str[i])) + break; + } + str[++i] = NUL; + } + return str; } diff --git a/rs232controller.c b/rs232controller.c index 9d0f9d09..7568d705 100644 --- a/rs232controller.c +++ b/rs232controller.c @@ -25,52 +25,48 @@ void setRS232SendTerminator(prs232 self, char *term) { assert(self); - - if(self->sendTerminator != NULL) - { + + if (self->sendTerminator != NULL) { free(self->sendTerminator); } - if(term != NULL) - { + if (term != NULL) { self->sendTerminator = strdup(term); - } - else - { + } else { self->sendTerminator = NULL; } } + /*--------------------------------------------------------------------*/ void setRS232ReplyTerminator(prs232 self, char *term) { assert(self); - if(self->replyTerminator != NULL) - { + if (self->replyTerminator != NULL) { free(self->replyTerminator); } - if(term != NULL) - { + if (term != NULL) { self->replyTerminator = strdup(term); - } - else - { + } else { self->replyTerminator = NULL; } - + } + /*---------------------------------------------------------------------*/ void setRS232Timeout(prs232 self, int timeout) { assert(self); self->timeout = timeout; } + /*---------------------------------------------------------------------*/ void setRS232Debug(prs232 self, int deb) { assert(self); self->debug = deb; } + /*--------------------------------------------------------------------*/ int writeRS232(prs232 self, void *data, int dataLen) { @@ -81,217 +77,194 @@ int writeRS232(prs232 self, void *data, int dataLen) assert(self); /* - catch an unconnected socket - */ - if(!self->pSock) - { + catch an unconnected socket + */ + if (!self->pSock) { return NOTCONNECTED; } - + /* do the terminator processing, if required. If new data had to be allocated in order to add the terminator, pPtr is not NULL. I any other case it is. - */ - if(self->sendTerminator != NULL) - { - pPtr = (char *)data; - if(strstr(pPtr,self->sendTerminator) == NULL) - { + */ + if (self->sendTerminator != NULL) { + pPtr = (char *) data; + if (strstr(pPtr, self->sendTerminator) == NULL) { /* - the terminator is missing. add it. - */ - pPtr = (char *)malloc((dataLen + strlen(self->sendTerminator) +2) - *sizeof(char)); - if(!pPtr) - { - return BADMEMORY; + the terminator is missing. add it. + */ + pPtr = (char *) malloc((dataLen + strlen(self->sendTerminator) + 2) + * sizeof(char)); + if (!pPtr) { + return BADMEMORY; } - strcpy(pPtr,(char *) data); - strcat(pPtr,self->sendTerminator); + strcpy(pPtr, (char *) data); + strcat(pPtr, self->sendTerminator); dataLen += strlen(self->sendTerminator); data = pPtr; - } - else - { + } else { pPtr = NULL; } } /* - send - */ - iRet = NETWrite(self->pSock,data,dataLen); - if(self->debug > 0) - { - printf("RS232 OUT : %s",(char *)data); - if(strchr((char *)data,'\n') == NULL) - { + send + */ + iRet = NETWrite(self->pSock, data, dataLen); + if (self->debug > 0) { + printf("RS232 OUT : %s", (char *) data); + if (strchr((char *) data, '\n') == NULL) { puts(""); } fflush(stdout); } - if(pPtr != NULL) + if (pPtr != NULL) free(pPtr); - if(iRet != 1){ + if (iRet != 1) { return BADSEND; } return iRet; } + /*----------------------------------------------------------------------*/ int readRS232(prs232 self, void *data, int *dataLen) { long lRead; int iRet; size_t rLength; - + assert(self); /* - catch an unconnected socket - */ - if(!self->pSock) - { + catch an unconnected socket + */ + if (!self->pSock) { return NOTCONNECTED; } /* - clean our space in order to prevent corrupted stuff - */ - memset(data,0,*dataLen); + clean our space in order to prevent corrupted stuff + */ + memset(data, 0, *dataLen); - iRet = NETAvailable(self->pSock,self->timeout); - if(iRet < 0) - { + iRet = NETAvailable(self->pSock, self->timeout); + if (iRet < 0) { return iRet; - } - else if(iRet == 0) - { + } else if (iRet == 0) { *dataLen = 0; return TIMEOUT; - } - else - { - rLength = *dataLen; - lRead = recv(self->pSock->sockid, data,rLength,0); - if(lRead >= 0) - { - if(self->debug > 0) - { - printf("RS232 IN : %s",(char *)data); - if(strchr((char *)data,'\n') == NULL) - { - puts(""); - } - fflush(stdout); + } else { + rLength = *dataLen; + lRead = recv(self->pSock->sockid, data, rLength, 0); + if (lRead >= 0) { + if (self->debug > 0) { + printf("RS232 IN : %s", (char *) data); + if (strchr((char *) data, '\n') == NULL) { + puts(""); + } + fflush(stdout); } *dataLen = lRead; return 1; - } - else - { - return (int)lRead; + } else { + return (int) lRead; } } /* - not reached - */ + not reached + */ return 0; } + /*--------------------------------------------------------------------*/ -int readRS232TillTerm(prs232 self, void *data, int *datalen){ +int readRS232TillTerm(prs232 self, void *data, int *datalen) +{ int iRet, replylen; assert(self); /* - catch an unconnected socket - */ - if(!self->pSock) - { + catch an unconnected socket + */ + if (!self->pSock) { return NOTCONNECTED; } - memset(data,0,*datalen); + memset(data, 0, *datalen); replylen = *datalen; - iRet = NETReadTillTerm(self->pSock,self->timeout,self->replyTerminator, - (char *)data, replylen); - if(self->debug > 0 && iRet > 0) - { - printf("RS232 IN/TERM : %s",(char *)data); - if(strchr((char *)data,'\n') == NULL) - { - puts(""); + iRet = NETReadTillTerm(self->pSock, self->timeout, self->replyTerminator, + (char *) data, replylen); + if (self->debug > 0 && iRet > 0) { + printf("RS232 IN/TERM : %s", (char *) data); + if (strchr((char *) data, '\n') == NULL) { + puts(""); } fflush(stdout); } - if(iRet == 0) - { - if(self->debug > 0) - { - printf("RS232 IN/TERM : TIMEOUT:%s\n",(char *)data); + if (iRet == 0) { + if (self->debug > 0) { + printf("RS232 IN/TERM : TIMEOUT:%s\n", (char *) data); } return TIMEOUT; - } - else if(iRet == -1) - { - printf("Incomplete read: %s, errno = %d\n", (char *)data, errno); + } else if (iRet == -1) { + printf("Incomplete read: %s, errno = %d\n", (char *) data, errno); return INCOMPLETE; - } - else if (iRet < 0) - { + } else if (iRet < 0) { return iRet; } if (*self->replyTerminator != 0) { - *datalen = strlen((char *)data); + *datalen = strlen((char *) data); } else { *datalen = iRet; } return 1; } + /*----------------------------------------------------------------------*/ -int readRS232UntilWord(prs232 self, - char *buffer, int buflen, char *word){ - time_t endTime; - int status; - int bytesRead = 0; +int readRS232UntilWord(prs232 self, char *buffer, int buflen, char *word) +{ + time_t endTime; + int status; + int bytesRead = 0; - endTime = time(NULL) + self->timeout; - memset(buffer,0,buflen); - while(time(NULL) < endTime){ - if(availableRS232(self)){ - bytesRead = recv(self->pSock->sockid,buffer + bytesRead, - buflen - bytesRead - 1,0); - if(bytesRead < 0){ - return BADREAD; - } - if(strstr(buffer,word) != NULL) { - return 1; - } - } else { - SicsWait(1); - } + endTime = time(NULL) + self->timeout; + memset(buffer, 0, buflen); + while (time(NULL) < endTime) { + if (availableRS232(self)) { + bytesRead = recv(self->pSock->sockid, buffer + bytesRead, + buflen - bytesRead - 1, 0); + if (bytesRead < 0) { + return BADREAD; + } + if (strstr(buffer, word) != NULL) { + return 1; + } + } else { + SicsWait(1); } + } - return 0; + return 0; } + /*-----------------------------------------------------------------------*/ int availableRS232(prs232 self) { assert(self); /* - catch an unconnected socket - */ - if(!self->pSock) - { + catch an unconnected socket + */ + if (!self->pSock) { return NOTCONNECTED; } - return NETAvailable(self->pSock,0); + return NETAvailable(self->pSock, 0); } + /*-----------------------------------------------------------------------*/ int availableNetRS232(prs232 self) { @@ -299,180 +272,166 @@ int availableNetRS232(prs232 self) assert(self); /* - catch an unconnected socket - */ - if(!self->pSock) - { + catch an unconnected socket + */ + if (!self->pSock) { return NOTCONNECTED; } - if(!self->registered){ - if(pServ->pReader != NULL){ - NetReadRegisterUserSocket(pServ->pReader,self->pSock->sockid); + if (!self->registered) { + if (pServ->pReader != NULL) { + NetReadRegisterUserSocket(pServ->pReader, self->pSock->sockid); self->registered = 1; return 0; } } - status = NetReadReadable(pServ->pReader,self->pSock->sockid); + status = NetReadReadable(pServ->pReader, self->pSock->sockid); NetReadResetUser(pServ->pReader, self->pSock->sockid); return status; } + /*------------------------------------------------------------------------*/ int transactRS232(prs232 self, void *send, int sendLen, - void *reply, int replyLen) + void *reply, int replyLen) { int iRet, len; assert(self); /* - catch an unconnected socket - */ - if(!self->pSock) - { + catch an unconnected socket + */ + if (!self->pSock) { return NOTCONNECTED; } /* - if there is still data on the socket: clear it - while(availableRS232(self)){ + if there is still data on the socket: clear it + while(availableRS232(self)){ len = replyLen; readRS232(self,reply,&len); - } + } */ - - + + /* - write data - */ - iRet = writeRS232(self,send,sendLen); - if(iRet <= 0) - { + write data + */ + iRet = writeRS232(self, send, sendLen); + if (iRet <= 0) { return BADSEND; } /* - read - */ - memset(reply,0,replyLen); - iRet = NETReadTillTerm(self->pSock,self->timeout,self->replyTerminator, - reply, replyLen); - if(self->debug > 0) - { - if(iRet > 0) - { - printf("RS232 IN/TRANS: %s",(char *)reply); - if(strchr((char *)reply,'\n') == NULL) - { - puts(""); + read + */ + memset(reply, 0, replyLen); + iRet = NETReadTillTerm(self->pSock, self->timeout, self->replyTerminator, + reply, replyLen); + if (self->debug > 0) { + if (iRet > 0) { + printf("RS232 IN/TRANS: %s", (char *) reply); + if (strchr((char *) reply, '\n') == NULL) { + puts(""); } fflush(stdout); - } - else if(iRet == 0) - { + } else if (iRet == 0) { printf("RS232 IN/TRANS: TIMEOUT\n"); - } - else - { - printf("RS232 IN/TRANS/INCOMPLETE: %s, errno = %d",(char *)reply, errno); + } else { + printf("RS232 IN/TRANS/INCOMPLETE: %s, errno = %d", (char *) reply, + errno); } } - if(iRet == 0) - { + if (iRet == 0) { return TIMEOUT; - } - else if(iRet == -1) - { + } else if (iRet == -1) { return INCOMPLETE; - } - else - { + } else { return iRet; } } + /*------------------------------------------------------------------------*/ -void getRS232Error(int iCode, char *errorBuffer, - int errorBufferLen) +void getRS232Error(int iCode, char *errorBuffer, int errorBufferLen) { /* - the error code is either one of our errors, or an errno code from - the system - */ - switch(iCode) - { - case BADMEMORY: - strncpy(errorBuffer, - "Out of memory for appending terminators", - errorBufferLen); - break; - case NOTCONNECTED: - strncpy(errorBuffer, - "Not connected!", - errorBufferLen); - break; - case TIMEOUT: - strncpy(errorBuffer, - "Timeout or network error when reading data", - errorBufferLen); - break; - case FAILEDCONNECT: - strncpy(errorBuffer, - "Failed to connect to terminal server", - errorBufferLen); - break; + the error code is either one of our errors, or an errno code from + the system + */ + switch (iCode) { + case BADMEMORY: + strncpy(errorBuffer, + "Out of memory for appending terminators", errorBufferLen); + break; + case NOTCONNECTED: + strncpy(errorBuffer, "Not connected!", errorBufferLen); + break; + case TIMEOUT: + strncpy(errorBuffer, + "Timeout or network error when reading data", errorBufferLen); + break; + case FAILEDCONNECT: + strncpy(errorBuffer, + "Failed to connect to terminal server", errorBufferLen); + break; case INCOMPLETE: - strncpy(errorBuffer,"Did not find terminator in read buffer", - errorBufferLen); - break; + strncpy(errorBuffer, "Did not find terminator in read buffer", + errorBufferLen); + break; case BADSEND: - strncpy(errorBuffer,"Network problem: failed to send",errorBufferLen); - break; - default: - strncpy(errorBuffer,strerror(errno), - errorBufferLen); - break; + strncpy(errorBuffer, "Network problem: failed to send", + errorBufferLen); + break; + default: + strncpy(errorBuffer, strerror(errno), errorBufferLen); + break; } } + /*--------------------------------------------------------------------*/ -int fixRS232Error(prs232 self, int iCode){ - int i, status, read; - char buffer[8192]; - - switch(iCode){ - case BADMEMORY: - case FAILEDCONNECT: - return 0; - break; - case INCOMPLETE: - case TIMEOUT: - /* - * try to clear possibly pending stuff - */ - for(i = 0; i < 3; i++){ - if(availableRS232(self)){ - read = 8192; - readRS232(self,buffer,&read); - } - } - return 1; - break; - case NOTCONNECTED: - case BADSEND: - closeRS232(self); - status = initRS232(self); - if(status > 0){ - return 1; - } else { - return 0; - } - break; - } +int fixRS232Error(prs232 self, int iCode) +{ + int i, status, read; + char buffer[8192]; + + switch (iCode) { + case BADMEMORY: + case FAILEDCONNECT: return 0; + break; + case INCOMPLETE: + case TIMEOUT: + /* + * try to clear possibly pending stuff + */ + for (i = 0; i < 3; i++) { + if (availableRS232(self)) { + read = 8192; + readRS232(self, buffer, &read); + } + } + return 1; + break; + case NOTCONNECTED: + case BADSEND: + closeRS232(self); + status = initRS232(self); + if (status > 0) { + return 1; + } else { + return 0; + } + break; + } + return 0; } + /*--------------------------------------------------------------------*/ -int getRS232Timeout(prs232 self){ +int getRS232Timeout(prs232 self) +{ return self->timeout; } + /*--------------------------------------------------------------------*/ int initRS232WithFlags(prs232 self, int flags) { @@ -480,71 +439,72 @@ int initRS232WithFlags(prs232 self, int flags) assert(self); - if(self->pSock != NULL) - { - if(pServ->pReader != NULL){ - NetReadRemoveUserSocket(pServ->pReader,self->pSock->sockid); + if (self->pSock != NULL) { + if (pServ->pReader != NULL) { + NetReadRemoveUserSocket(pServ->pReader, self->pSock->sockid); } NETClosePort(self->pSock); free(self->pSock); self->pSock = NULL; } self->pSock = NETConnectWithFlags(self->pHost, self->iPort, flags); - if(!self->pSock){ + if (!self->pSock) { return FAILEDCONNECT; - } else{ - if(pServ->pReader != NULL){ - NetReadRegisterUserSocket(pServ->pReader,self->pSock->sockid); + } else { + if (pServ->pReader != NULL) { + NetReadRegisterUserSocket(pServ->pReader, self->pSock->sockid); self->registered = 1; } return 1; } } + /*--------------------------------------------------------------------*/ int initRS232(prs232 self) { return initRS232WithFlags(self, 0); } + /*--------------------------------------------------------------------*/ int initRS232Finished(prs232 self) { - int iret; - - iret = NETConnectFinished(self->pSock); - if (iret < 0) { - return FAILEDCONNECT; - } else { - return iret; - } + int iret; + + iret = NETConnectFinished(self->pSock); + if (iret < 0) { + return FAILEDCONNECT; + } else { + return iret; + } } + /*--------------------------------------------------------------------*/ void closeRS232(prs232 self) { assert(self); - if(self->pSock != NULL) - { - if(pServ->pReader != NULL){ - NetReadRemoveUserSocket(pServ->pReader,self->pSock->sockid); + if (self->pSock != NULL) { + if (pServ->pReader != NULL) { + NetReadRemoveUserSocket(pServ->pReader, self->pSock->sockid); } NETClosePort(self->pSock); free(self->pSock); self->pSock = NULL; } } + /*------------------------------------------------------------------*/ prs232 createRS232(char *host, int iPort) { prs232 pNew = NULL; assert(iPort > 0); - + /* - create data structure - */ - pNew = (prs232)malloc(sizeof(rs232)); - if(!pNew) - { + create data structure + */ + pNew = (prs232) malloc(sizeof(rs232)); + if (!pNew) { return NULL; } memset(pNew, 0, sizeof(rs232)); @@ -556,92 +516,82 @@ prs232 createRS232(char *host, int iPort) pNew->timeout = 1000; pNew->debug = 0; pNew->pDes = CreateDescriptor("RS232 Controller"); - if(!pNew->pDes || !pNew->pHost || - !pNew->replyTerminator || !pNew->sendTerminator) - { + if (!pNew->pDes || !pNew->pHost || + !pNew->replyTerminator || !pNew->sendTerminator) { return NULL; } return pNew; } + /*-------------------------------------------------------------------*/ - void KillRS232(void *pData) +void KillRS232(void *pData) { - prs232 self = (prs232)pData; - if(!self) - { - return; + prs232 self = (prs232) pData; + if (!self) { + return; } - if(self->pDes) - { + if (self->pDes) { DeleteDescriptor(self->pDes); } - if(self->sendTerminator != NULL) - { + if (self->sendTerminator != NULL) { free(self->sendTerminator); } - if(self->replyTerminator != NULL) - { + if (self->replyTerminator != NULL) { free(self->replyTerminator); } - if(self->pSock) - { - if(pServ->pReader != NULL){ - NetReadRemoveUserSocket(pServ->pReader,self->pSock->sockid); + if (self->pSock) { + if (pServ->pReader != NULL) { + NetReadRemoveUserSocket(pServ->pReader, self->pSock->sockid); } NETClosePort(self->pSock); free(self->pSock); } - if(self->pHost) - { + if (self->pHost) { free(self->pHost); } } + /*-------------------------------------------------------------------*/ -static void KillAndFreeRS232(void *pData) { +static void KillAndFreeRS232(void *pData) +{ KillRS232(pData); free(pData); } + /*-------------------------------------------------------------------*/ -static int checkSet(SConnection *pCon, int argc, int rights) +static int checkSet(SConnection * pCon, int argc, int rights) { - if(argc < 3) - { - return 0; - } - else - { - if(SCMatchRights(pCon,rights)) - { + if (argc < 3) { + return 0; + } else { + if (SCMatchRights(pCon, rights)) { return 1; - } - else - { + } else { return 0; } - } + } /* - not reached - */ + not reached + */ return 0; } + /*--------------------------------------------------------------------*/ static void encodeTerminator(char *result, char *terminator) { int i, len; char pBuffer[10]; - - if(terminator == NULL) - { + + if (terminator == NULL) { result[0] = '\0'; } len = strlen(terminator); - sprintf(pBuffer,"0x%x",(int)terminator[0]); - strcpy(result,pBuffer); - for(i = 1; i < len; i++) - { - sprintf(pBuffer,"0x%x",(int)terminator[i]); - strcat(result,pBuffer); + sprintf(pBuffer, "0x%x", (int) terminator[0]); + strcpy(result, pBuffer); + for (i = 1; i < len; i++) { + sprintf(pBuffer, "0x%x", (int) terminator[i]); + strcat(result, pBuffer); } } extern char *stptok(char *pPtr, char *pToken, int tokenLen, char *term); @@ -653,34 +603,33 @@ char *decodeTerminator(char *code) char *pPtr, pToken[10]; /* - max 10 terminators! - */ - pResult = (char *)malloc(10*sizeof(char)); - if(!pResult) - { + max 10 terminators! + */ + pResult = (char *) malloc(10 * sizeof(char)); + if (!pResult) { return NULL; } - memset(pResult,0,10); + memset(pResult, 0, 10); pToken[0] = '0'; /* - I seem to get an empty token on the first call to stptok, this is why - I do 2 stptoks. Strange and wonderful. - */ - pPtr = stptok(code,pToken+1,9,"0"); - pPtr = stptok(pPtr,pToken+1,9,"0"); - while(pPtr != NULL) - { - sscanf(pToken,"%x",&icode); - pResult[count] = (char)icode; + I seem to get an empty token on the first call to stptok, this is why + I do 2 stptoks. Strange and wonderful. + */ + pPtr = stptok(code, pToken + 1, 9, "0"); + pPtr = stptok(pPtr, pToken + 1, 9, "0"); + while (pPtr != NULL) { + sscanf(pToken, "%x", &icode); + pResult[count] = (char) icode; count++; - pPtr = stptok(pPtr,pToken+1,9,"0"); + pPtr = stptok(pPtr, pToken + 1, 9, "0"); } return pResult; } + /*--------------------------------------------------------------------*/ -int RS232Action(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) +int RS232Action(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) { prs232 self = NULL; char pError[256]; @@ -689,270 +638,212 @@ int RS232Action(SConnection *pCon, SicsInterp *pSics, char *pPtr = NULL; int iRet, iRead = 8191, count, i; - self = (prs232)pData; + self = (prs232) pData; assert(self); assert(pCon); /* - check for arguments - */ - if(argc < 2) - { - sprintf(pError,"ERROR: insufficient no of arguments to %s",argv[0]); - SCWrite(pCon,pError,eError); + check for arguments + */ + if (argc < 2) { + sprintf(pError, "ERROR: insufficient no of arguments to %s", argv[0]); + SCWrite(pCon, pError, eError); return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"sendterminator") == 0) - { - if(checkSet(pCon,argc,usMugger)) - { + if (strcmp(argv[1], "sendterminator") == 0) { + if (checkSet(pCon, argc, usMugger)) { pPtr = decodeTerminator(argv[2]); - setRS232SendTerminator(self,pPtr); - if(pPtr) - free(pPtr); + setRS232SendTerminator(self, pPtr); + if (pPtr) + free(pPtr); SCSendOK(pCon); return 1; + } else { + encodeTerminator(pBuffer, self->sendTerminator); + sprintf(pError, "%s.sendTerminator = \"%s\"", argv[0], pBuffer); + SCWrite(pCon, pError, eValue); + return 1; } - else - { - encodeTerminator(pBuffer,self->sendTerminator); - sprintf(pError,"%s.sendTerminator = \"%s\"",argv[0], - pBuffer); - SCWrite(pCon,pError,eValue); - return 1; - } - } - else if(strcmp(argv[1],"debug") == 0) - { + } else if (strcmp(argv[1], "debug") == 0) { self->debug = atoi(argv[2]); SCSendOK(pCon); return 1; - } - else if(strcmp(argv[1],"timeout") == 0) - { - if(checkSet(pCon,argc,usUser)) - { - setRS232Timeout(self,atoi(argv[2])); + } else if (strcmp(argv[1], "timeout") == 0) { + if (checkSet(pCon, argc, usUser)) { + setRS232Timeout(self, atoi(argv[2])); SCSendOK(pCon); return 1; + } else { + sprintf(pError, "%s.Timeout = %d", argv[0], self->timeout); + SCWrite(pCon, pError, eValue); + return 1; } - else - { - sprintf(pError,"%s.Timeout = %d",argv[0],self->timeout); - SCWrite(pCon,pError,eValue); - return 1; - } - } - else if(strcmp(argv[1],"replyterminator") == 0) - { - if(checkSet(pCon,argc,usMugger)) - { - memset(pTerm,0,10); - for(i = 2; i < argc;i++){ + } else if (strcmp(argv[1], "replyterminator") == 0) { + if (checkSet(pCon, argc, usMugger)) { + memset(pTerm, 0, 10); + for (i = 2; i < argc; i++) { pPtr = decodeTerminator(argv[i]); - pTerm[i-2] = pPtr[0]; - if(pPtr) - free(pPtr); + pTerm[i - 2] = pPtr[0]; + if (pPtr) + free(pPtr); } - setRS232ReplyTerminator(self,pTerm); + setRS232ReplyTerminator(self, pTerm); SCSendOK(pCon); return 1; + } else { + encodeTerminator(pBuffer, self->replyTerminator); + sprintf(pError, "%s.replyTerminator = \"%s\"", argv[0], pBuffer); + SCWrite(pCon, pError, eValue); + return 1; } - else - { - encodeTerminator(pBuffer,self->replyTerminator); - sprintf(pError,"%s.replyTerminator = \"%s\"",argv[0], - pBuffer); - SCWrite(pCon,pError,eValue); - return 1; - } - } - else if(strcmp(argv[1],"write") == 0) - { - Arg2Text(argc-2,argv+2,pBuffer,8191); - iRet = writeRS232(self,pBuffer,strlen(pBuffer)); - if(iRet < 0) - { - getRS232Error(iRet,pError,255); - SCWrite(pCon,pError,eError); + } else if (strcmp(argv[1], "write") == 0) { + Arg2Text(argc - 2, argv + 2, pBuffer, 8191); + iRet = writeRS232(self, pBuffer, strlen(pBuffer)); + if (iRet < 0) { + getRS232Error(iRet, pError, 255); + SCWrite(pCon, pError, eError); return 0; } SCSendOK(pCon); return 1; - } - else if(strcmp(argv[1],"read") == 0) - { - if(!availableRS232(self)) - { - SCWrite(pCon,"Nothing to read!",eError); + } else if (strcmp(argv[1], "read") == 0) { + if (!availableRS232(self)) { + SCWrite(pCon, "Nothing to read!", eError); return 1; } - iRet = readRS232(self,pBuffer,&iRead); - if(iRet < 0) - { - getRS232Error(iRet,pError,255); - SCWrite(pCon,pError,eError); + iRet = readRS232(self, pBuffer, &iRead); + if (iRet < 0) { + getRS232Error(iRet, pError, 255); + SCWrite(pCon, pError, eError); return 0; } - SCWrite(pCon,pBuffer,eValue); + SCWrite(pCon, pBuffer, eValue); return 1; - } - else if(strcmp(argv[1],"readchar") == 0){ - if(argc < 3){ - SCWrite(pCon,"ERROR: need number of chars to read",eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iRead); - if(iRet != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert argument to number",eError); - return 0; - } - if(!availableRS232(self)) - { - SCWrite(pCon,"Nothing to read!",eError); + } else if (strcmp(argv[1], "readchar") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: need number of chars to read", eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iRead); + if (iRet != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert argument to number", eError); + return 0; + } + if (!availableRS232(self)) { + SCWrite(pCon, "Nothing to read!", eError); return 1; } - iRet = readRS232(self,pBuffer,&iRead); - if(iRet < 0) - { - getRS232Error(iRet,pError,255); - SCWrite(pCon,pError,eError); + iRet = readRS232(self, pBuffer, &iRead); + if (iRet < 0) { + getRS232Error(iRet, pError, 255); + SCWrite(pCon, pError, eError); return 0; } - SCWrite(pCon,pBuffer,eValue); + SCWrite(pCon, pBuffer, eValue); return 1; - } - else if(strcmp(argv[1],"available") == 0) - { + } else if (strcmp(argv[1], "available") == 0) { iRet = availableRS232(self); - if(iRet < 0) - { - getRS232Error(iRet,pError,255); - SCWrite(pCon,pError,eError); + if (iRet < 0) { + getRS232Error(iRet, pError, 255); + SCWrite(pCon, pError, eError); return 0; - } - else if(iRet == 0) - { - SCWrite(pCon,"No data pending",eValue); + } else if (iRet == 0) { + SCWrite(pCon, "No data pending", eValue); + return 1; + } else { + SCWrite(pCon, "Data available", eValue); return 1; } - else - { - SCWrite(pCon,"Data available",eValue); - return 1; - } - } - else if(strcmp(argv[1],"send") == 0) - { - Arg2Text(argc-2,argv+2,pBuffer,8191); - iRet = transactRS232(self,pBuffer,strlen(pBuffer), - pReply,iRead); - if(iRet < 0) - { - getRS232Error(iRet,pError,255); - SCWrite(pCon,pError,eError); + } else if (strcmp(argv[1], "send") == 0) { + Arg2Text(argc - 2, argv + 2, pBuffer, 8191); + iRet = transactRS232(self, pBuffer, strlen(pBuffer), pReply, iRead); + if (iRet < 0) { + getRS232Error(iRet, pError, 255); + SCWrite(pCon, pError, eError); return 0; } - SCWrite(pCon,pReply,eValue); + SCWrite(pCon, pReply, eValue); return 1; - } - else if(strcmp(argv[1],"binwrite") == 0) - { + } else if (strcmp(argv[1], "binwrite") == 0) { count = argc - 2; - for(i = 0; i < count; i++) - { - pBuffer[i] = (char)atoi(argv[i+2]); + for (i = 0; i < count; i++) { + pBuffer[i] = (char) atoi(argv[i + 2]); } - if(self->pSock) - { - iRet = NETWrite(self->pSock,pBuffer,count); - } - else - { + if (self->pSock) { + iRet = NETWrite(self->pSock, pBuffer, count); + } else { iRet = NOTCONNECTED; } - if(iRet < 0) - { - getRS232Error(iRet,pError,255); - SCWrite(pCon,pError,eError); + if (iRet < 0) { + getRS232Error(iRet, pError, 255); + SCWrite(pCon, pError, eError); return 0; } SCSendOK(pCon); return 1; - } - else if(strcmp(argv[1],"init") == 0) - { + } else if (strcmp(argv[1], "init") == 0) { iRet = initRS232(self); - if(iRet != 1) - { - sprintf(pError,"ERROR: reinitializing connection to %s at %d failed", - self->pHost, self->iPort); - SCWrite(pCon,pError,eError); + if (iRet != 1) { + sprintf(pError, + "ERROR: reinitializing connection to %s at %d failed", + self->pHost, self->iPort); + SCWrite(pCon, pError, eError); return 0; - } - else - { + } else { SCSendOK(pCon); return 1; } - } - else - { - sprintf(pError,"ERROR: %s does not understand %s",argv[0], argv[1]); - SCWrite(pCon,pError,eError); + } else { + sprintf(pError, "ERROR: %s does not understand %s", argv[0], argv[1]); + SCWrite(pCon, pError, eError); return 0; } return 1; } + /*-------------------------------------------------------------------*/ -int RS232Factory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) +int RS232Factory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) { prs232 pNew = NULL; int iRet, status; char pError[256]; - if(argc < 4) - { - SCWrite(pCon,"ERROR: insufficient no of arguments to RS232Factory", + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient no of arguments to RS232Factory", eError); return 0; } /* - create data structure and open port - */ + create data structure and open port + */ pNew = createRS232(argv[2], atoi(argv[3])); - - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory in RS232Factory",eError); + + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory in RS232Factory", eError); return 0; } status = initRS232(pNew); - if(status != 1) - { - sprintf(pError,"ERROR: failed to connect to %s at port %d", - pNew->pHost, pNew->iPort); - SCWrite(pCon,pError,eError); + if (status != 1) { + sprintf(pError, "ERROR: failed to connect to %s at port %d", + pNew->pHost, pNew->iPort); + SCWrite(pCon, pError, eError); } - + /* - create the command - */ - iRet = AddCommand(pSics,argv[1],RS232Action, KillAndFreeRS232, pNew); - if(!iRet) - { - sprintf(pError,"ERROR: duplicate command %s not created", argv[1]); - SCWrite(pCon,pError,eError); - KillAndFreeRS232(pNew); - return 0; - } - return 1; + create the command + */ + iRet = AddCommand(pSics, argv[1], RS232Action, KillAndFreeRS232, pNew); + if (!iRet) { + sprintf(pError, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pError, eError); + KillAndFreeRS232(pNew); + return 0; + } + return 1; } - - diff --git a/rs232controller.h b/rs232controller.h index 1628930c..833b27aa 100644 --- a/rs232controller.h +++ b/rs232controller.h @@ -27,52 +27,50 @@ /*----------------------- a data structure ----------------------------*/ - typedef struct{ - pObjectDescriptor pDes; - char *sendTerminator; - char *replyTerminator; - int timeout; - mkChannel *pSock; - char *pHost; - int iPort; - int debug; - int registered; - } rs232, *prs232; +typedef struct { + pObjectDescriptor pDes; + char *sendTerminator; + char *replyTerminator; + int timeout; + mkChannel *pSock; + char *pHost; + int iPort; + int debug; + int registered; +} rs232, *prs232; /*----------------------- the interface functions --------------------*/ - int RS232Action(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - int RS232Factory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int RS232Action(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); +int RS232Factory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); - void setRS232SendTerminator(prs232 self, char *term); - void setRS232ReplyTerminator(prs232 self, char *term); - void setRS232Timeout(prs232 self, int timeout); - void setRS232Debug(prs232 self, int deb); +void setRS232SendTerminator(prs232 self, char *term); +void setRS232ReplyTerminator(prs232 self, char *term); +void setRS232Timeout(prs232 self, int timeout); +void setRS232Debug(prs232 self, int deb); - int writeRS232(prs232 self, void *data, int dataLen); - int readRS232(prs232 self, void *data, int *dataLen); - int readRS232TillTerm(prs232 self, void *data, int *datalen); - int readRS232UntilWord(prs232 self, - char *buffer, int buflen, char *word); - int availableRS232(prs232 self); - int availableNetRS232(prs232 self); - int transactRS232(prs232 self, void *send, int sendLen, - void *reply, int replylen); +int writeRS232(prs232 self, void *data, int dataLen); +int readRS232(prs232 self, void *data, int *dataLen); +int readRS232TillTerm(prs232 self, void *data, int *datalen); +int readRS232UntilWord(prs232 self, char *buffer, int buflen, char *word); +int availableRS232(prs232 self); +int availableNetRS232(prs232 self); +int transactRS232(prs232 self, void *send, int sendLen, + void *reply, int replylen); - void getRS232Error(int iCode, char *errorBuffer, - int errorBufferLen); - int fixRS232Error(prs232 self, int iCode); - int getRS232Timeout(prs232 self); - int initRS232(prs232 self); - int initRS232WithFlags(prs232 self, int flags); - int initRS232Finished(prs232 self); - void closeRS232(prs232 self); - prs232 createRS232(char *host, int iPort); - void KillRS232(void *pData); +void getRS232Error(int iCode, char *errorBuffer, int errorBufferLen); +int fixRS232Error(prs232 self, int iCode); +int getRS232Timeout(prs232 self); +int initRS232(prs232 self); +int initRS232WithFlags(prs232 self, int flags); +int initRS232Finished(prs232 self); +void closeRS232(prs232 self); +prs232 createRS232(char *host, int iPort); +void KillRS232(void *pData); #endif diff --git a/s_rnge.c b/s_rnge.c index 5c12b949..88b1566c 100644 --- a/s_rnge.c +++ b/s_rnge.c @@ -7,26 +7,28 @@ extern "C" { /* called when a subscript is out of range */ #ifdef KR_headers -extern VOID sig_die(); -integer s_rnge(varn, offset, procn, line) char *varn, *procn; ftnint offset, line; + extern VOID sig_die(); + integer s_rnge(varn, offset, procn, line) char *varn, *procn; + ftnint offset, line; #else -extern VOID sig_die(char*,int); -integer s_rnge(char *varn, ftnint offset, char *procn, ftnint line) + extern VOID sig_die(char *, int); + integer s_rnge(char *varn, ftnint offset, char *procn, ftnint line) #endif -{ -register int i; + { + register int i; -fprintf(stderr, "Subscript out of range on file line %ld, procedure ", - (long)line); -while((i = *procn) && i != '_' && i != ' ') - putc(*procn++, stderr); -fprintf(stderr, ".\nAttempt to access the %ld-th element of variable ", - (long)offset+1); -while((i = *varn) && i != ' ') - putc(*varn++, stderr); -sig_die(".", 1); -return 0; /* not reached */ -} + fprintf(stderr, "Subscript out of range on file line %ld, procedure ", + (long) line); + while ((i = *procn) && i != '_' && i != ' ') + putc(*procn++, stderr); + fprintf(stderr, + ".\nAttempt to access the %ld-th element of variable ", + (long) offset + 1); + while ((i = *varn) && i != ' ') + putc(*varn++, stderr); + sig_die(".", 1); + return 0; /* not reached */ + } #ifdef __cplusplus } #endif diff --git a/savehdb.c b/savehdb.c index b4b29523..86912117 100644 --- a/savehdb.c +++ b/savehdb.c @@ -3,12 +3,13 @@ #include "statusfile.h" #include "sicshipadaba.h" -static void SaveHdbBranch(pHdb node, FILE *fil) { +static void SaveHdbBranch(pHdb node, FILE * fil) +{ pHdb child; char prop[16]; pDynString dyn; char path[1024]; - + if (GetHdbProperty(node, "save", prop, sizeof prop)) { if (strcmp(prop, "me") == 0) { dyn = formatValue(node->value, node); @@ -22,36 +23,39 @@ static void SaveHdbBranch(pHdb node, FILE *fil) { } } -static int SaveHdbTree(void *object, char *name, FILE *fil) { +static int SaveHdbTree(void *object, char *name, FILE * fil) +{ pHdb node; - + SaveHdbBranch(GetHipadabaRoot(), fil); return 1; } -static hdbCallbackReturn SaveHdbCallback(pHdb node, void *userData, - pHdbMessage message) { - pHdbDataMessage mm = NULL; - - if((mm = GetHdbUpdateMessage(message)) == NULL){ - return hdbContinue; +static hdbCallbackReturn SaveHdbCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbUpdateMessage(message)) == NULL) { + return hdbContinue; } - + StatusFileDirty(); return hdbContinue;; } -static int SaveHdbEnable(SConnection *con, SicsInterp *sics, - void *data, int argc, char *argv[]) { +static int SaveHdbEnable(SConnection * con, SicsInterp * sics, + void *data, int argc, char *argv[]) +{ pHdb node; char prop[16]; pHdbCallback cb; - + if (argc < 2) { SCPrintf(con, eError, "ERROR: should be: %s ", argv[0]); return 0; } - + node = FindHdbNode(NULL, argv[1], con); if (!node) { SCPrintf(con, eError, "ERROR: %s not found", argv[1]); @@ -59,7 +63,7 @@ static int SaveHdbEnable(SConnection *con, SicsInterp *sics, } cb = MakeHipadabaCallback(SaveHdbCallback, NULL, NULL); assert(cb); - AppendHipadabaCallback(node,cb); + AppendHipadabaCallback(node, cb); SetHdbProperty(node, "save", "me"); for (node = node->mama; node != NULL; node = node->mama) { @@ -71,10 +75,12 @@ static int SaveHdbEnable(SConnection *con, SicsInterp *sics, return 1; } -void SaveHdbInit(void) { +void SaveHdbInit(void) +{ pDummy hs = NULL; hs = CreateDummy("hdb saver"); hs->pDescriptor->SaveStatus = SaveHdbTree; - AddCommandWithFlag(pServ->pSics, "hsave", SaveHdbEnable, KillDummy, hs, 0); + AddCommandWithFlag(pServ->pSics, "hsave", SaveHdbEnable, KillDummy, hs, + 0); } diff --git a/scaldate.c b/scaldate.c index e0baf5ae..dbae0d42 100644 --- a/scaldate.c +++ b/scaldate.c @@ -11,45 +11,46 @@ #include "scaldate.h" -int isleap (unsigned yr) +int isleap(unsigned yr) { - return yr % 400 == 0 || (yr % 4 == 0 && yr % 100 != 0); + return yr % 400 == 0 || (yr % 4 == 0 && yr % 100 != 0); } -static unsigned months_to_days (unsigned month) +static unsigned months_to_days(unsigned month) { - return (month * 3057 - 3007) / 100; + return (month * 3057 - 3007) / 100; } -static long years_to_days (unsigned yr) +static long years_to_days(unsigned yr) { - return yr * 365L + yr / 4 - yr / 100 + yr / 400; + return yr * 365L + yr / 4 - yr / 100 + yr / 400; } -long ymd_to_scalar (unsigned yr, unsigned mo, unsigned day) +long ymd_to_scalar(unsigned yr, unsigned mo, unsigned day) { - long scalar; - scalar = day + months_to_days(mo); - if ( mo > 2 ) /* adjust if past February */ - scalar -= isleap(yr) ? 1 : 2; - yr--; - scalar += years_to_days(yr); - return scalar; + long scalar; + scalar = day + months_to_days(mo); + if (mo > 2) /* adjust if past February */ + scalar -= isleap(yr) ? 1 : 2; + yr--; + scalar += years_to_days(yr); + return scalar; } -void scalar_to_ymd (long scalar, unsigned *yr, unsigned *mo, unsigned *day) +void scalar_to_ymd(long scalar, unsigned *yr, unsigned *mo, unsigned *day) { - unsigned n; /* compute inverse of years_to_days() */ + unsigned n; /* compute inverse of years_to_days() */ - for ( n = (unsigned)((scalar * 400L) / 146097L); years_to_days(n) < scalar;) - n++; /* 146097 == years_to_days(400) */ - *yr = n; - n = (unsigned)(scalar - years_to_days(n-1)); - if ( n > 59 ) { /* adjust if past February */ - n += 2; - if ( isleap(*yr) ) - n -= n > 62 ? 1 : 2; - } - *mo = (n * 100 + 3007) / 3057; /* inverse of months_to_days() */ - *day = n - months_to_days(*mo); + for (n = (unsigned) ((scalar * 400L) / 146097L); + years_to_days(n) < scalar;) + n++; /* 146097 == years_to_days(400) */ + *yr = n; + n = (unsigned) (scalar - years_to_days(n - 1)); + if (n > 59) { /* adjust if past February */ + n += 2; + if (isleap(*yr)) + n -= n > 62 ? 1 : 2; + } + *mo = (n * 100 + 3007) / 3057; /* inverse of months_to_days() */ + *day = n - months_to_days(*mo); } diff --git a/scaldate.h b/scaldate.h index 7fb3030f..fb7cd029 100644 --- a/scaldate.h +++ b/scaldate.h @@ -21,19 +21,21 @@ */ #ifndef ISO_CAL - #define ISO_CAL 0 +#define ISO_CAL 0 #endif #if (ISO_CAL != 0 && ISO_CAL != 1) - #error ISO_CAL must be set to either 0 or 1 +#error ISO_CAL must be set to either 0 or 1 #endif #if ISO_CAL - enum DOW_T {DOW_IGNORE = -1, - MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}; +enum DOW_T { DOW_IGNORE = -1, + MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY +}; #else - enum DOW_T {DOW_IGNORE = -1, - SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}; +enum DOW_T { DOW_IGNORE = -1, + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY +}; #endif /* @@ -51,19 +53,19 @@ ** October 31. */ -extern unsigned DST_start_mo; -extern unsigned DST_start_dt; +extern unsigned DST_start_mo; +extern unsigned DST_start_dt; extern enum DOW_T DST_start_dy; -extern unsigned DST_stop_mo; -extern unsigned DST_stop_dt; +extern unsigned DST_stop_mo; +extern unsigned DST_stop_dt; extern enum DOW_T DST_stop_dy; -int isleap (unsigned yr); -long ymd_to_scalar (unsigned yr, unsigned mo, unsigned day); -void scalar_to_ymd (long scalar, unsigned *yr, unsigned *mo, unsigned *day); -int daynum(int year, int month, int day); -int weeknum(int year, int month, int day); +int isleap(unsigned yr); +long ymd_to_scalar(unsigned yr, unsigned mo, unsigned day); +void scalar_to_ymd(long scalar, unsigned *yr, unsigned *mo, unsigned *day); +int daynum(int year, int month, int day); +int weeknum(int year, int month, int day); int valiDate(unsigned yr, unsigned mo, unsigned day); @@ -76,8 +78,8 @@ extern char *MoonPhaseText[8]; unsigned moonphase(unsigned yr, unsigned mo, unsigned dy); -int getfdate (int handle, long *date); -int getdatef (char *fname, long *date); +int getfdate(int handle, long *date); +int getdatef(char *fname, long *date); -#endif /* SCALDATE__H */ +#endif /* SCALDATE__H */ diff --git a/scan.c b/scan.c index bdfb8cd9..b754912f 100644 --- a/scan.c +++ b/scan.c @@ -43,10 +43,11 @@ #include "stdscan.h" /*---------------------------------------------------------------------------*/ - static void DeleteCountEntry(void *pData) - { - free(pData); - } +static void DeleteCountEntry(void *pData) +{ + free(pData); +} + /*---------------------------------------------------------------------------*/ void InitCountEntry(pCountEntry pCount) { @@ -55,332 +56,307 @@ void InitCountEntry(pCountEntry pCount) pCount->lCount = -1L; pCount->i = -1; pCount->fTime = -1.0; - for(i = 0; i < 10; i++) - { + for (i = 0; i < 10; i++) { pCount->Monitors[i] = -1L; } } + /*--------------------------------------------------------------------------*/ - static int DummyWrite(pScanData self) - { - return 1; - } +static int DummyWrite(pScanData self) +{ + return 1; +} + /*--------------------------------------------------------------------------*/ - static int DummyWrite2(pScanData self, int iPoint) - { - return 1; - } +static int DummyWrite2(pScanData self, int iPoint) +{ + return 1; +} + /*---------------------------------------------------------------------------*/ - static void *ScanInterface(void *pData, int iInter) - { - pScanData self = NULL; - - self = (pScanData)pData; - assert(self); - - if(iInter == CALLBACKINTERFACE) - { - return self->pCall; - } - return NULL; - } +static void *ScanInterface(void *pData, int iInter) +{ + pScanData self = NULL; + + self = (pScanData) pData; + assert(self); + + if (iInter == CALLBACKINTERFACE) { + return self->pCall; + } + return NULL; +} + /*------------------------------------------------------------------------*/ static void ConfigureScanDict(pStringDict dict) { - StringDictAddPair(dict,"writeheader","stdscan writeheader"); - StringDictAddPair(dict,"prepare","stdscan prepare"); - StringDictAddPair(dict,"drive","stdscan drive"); - StringDictAddPair(dict,"count","stdscan count"); - StringDictAddPair(dict,"collect","stdscan collect"); - StringDictAddPair(dict,"writepoint","stdscan writepoint"); - StringDictAddPair(dict,"userdata","unknown"); - StringDictAddPair(dict,"finish","stdscan finish"); + StringDictAddPair(dict, "writeheader", "stdscan writeheader"); + StringDictAddPair(dict, "prepare", "stdscan prepare"); + StringDictAddPair(dict, "drive", "stdscan drive"); + StringDictAddPair(dict, "count", "stdscan count"); + StringDictAddPair(dict, "collect", "stdscan collect"); + StringDictAddPair(dict, "writepoint", "stdscan writepoint"); + StringDictAddPair(dict, "userdata", "unknown"); + StringDictAddPair(dict, "finish", "stdscan finish"); } -/*--------------------------------------------------------------------------*/ - pScanData CreateScanObject(char *pRecover, char *pHeader,pCounter pCount, - char *objName) - { - pScanData pNew = NULL; - - pNew = (pScanData)malloc(sizeof(ScanData)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(ScanData)); - - /* create an ObjectDescriptor */ - pNew->pDes = CreateDescriptor("ScanObject"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - pNew->pDes->GetInterface = ScanInterface; - - /* allocate the dynamic arrays */ - pNew->pScanVar = CreateDynar(0,10,10,DeleteVarEntry); - pNew->pCounts = CreateDynar(0,10,10,DeleteCountEntry); - pNew->scanFunctions = CreateStringDict(); - if( (!pNew->pScanVar) || (!pNew->pCounts) || (!pNew->scanFunctions) ) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - } - - /* make a callback interface */ - pNew->pCall = CreateCallBackInterface(); - if(!pNew->pCall) - { - DeleteScanObject(pNew); - return NULL; - } - - /* assign various things */ - if(pRecover) - { - strcpy(pNew->pRecover,pRecover); - } - if(pHeader) - { - strcpy(pNew->pHeaderFile,pHeader); - } - pNew->iMode = eTimer; - pNew->fPreset = 10.; - strcpy(pNew->pCounterName,pCount->name); - pNew->pCounterData = pCount; - pNew->PrepareScan = PrepareScan; - pNew->WriteHeader = WriteHeader; - pNew->WriteScanPoints = WriteScanPoints; - pNew->ScanDrive = ScanDrive; - pNew->ScanCount = ScanCount; - pNew->CollectScanData = CollectScanData; - pNew->iWindow = 6; - strncpy(pNew->objectName,objName, 131); - ConfigureScanDict(pNew->scanFunctions); - return pNew; +/*--------------------------------------------------------------------------*/ +pScanData CreateScanObject(char *pRecover, char *pHeader, pCounter pCount, + char *objName) +{ + pScanData pNew = NULL; + + pNew = (pScanData) malloc(sizeof(ScanData)); + if (!pNew) { + return NULL; } + memset(pNew, 0, sizeof(ScanData)); + + /* create an ObjectDescriptor */ + pNew->pDes = CreateDescriptor("ScanObject"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + pNew->pDes->GetInterface = ScanInterface; + + /* allocate the dynamic arrays */ + pNew->pScanVar = CreateDynar(0, 10, 10, DeleteVarEntry); + pNew->pCounts = CreateDynar(0, 10, 10, DeleteCountEntry); + pNew->scanFunctions = CreateStringDict(); + if ((!pNew->pScanVar) || (!pNew->pCounts) || (!pNew->scanFunctions)) { + DeleteDescriptor(pNew->pDes); + free(pNew); + return NULL; + } + + /* make a callback interface */ + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pCall) { + DeleteScanObject(pNew); + return NULL; + } + + /* assign various things */ + if (pRecover) { + strcpy(pNew->pRecover, pRecover); + } + if (pHeader) { + strcpy(pNew->pHeaderFile, pHeader); + } + pNew->iMode = eTimer; + pNew->fPreset = 10.; + strcpy(pNew->pCounterName, pCount->name); + pNew->pCounterData = pCount; + pNew->PrepareScan = PrepareScan; + pNew->WriteHeader = WriteHeader; + pNew->WriteScanPoints = WriteScanPoints; + pNew->ScanDrive = ScanDrive; + pNew->ScanCount = ScanCount; + pNew->CollectScanData = CollectScanData; + pNew->iWindow = 6; + strncpy(pNew->objectName, objName, 131); + ConfigureScanDict(pNew->scanFunctions); + + return pNew; +} + /*---------------------------------------------------------------------------*/ - void DeleteScanObject(void *pData) - { - pScanData self = NULL; - - self = (pScanData)pData; - if(!self) - { - return; - } - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->pCall) - { - DeleteCallBackInterface(self->pCall); - } - if(self->pScanVar) - { - DeleteDynar(self->pScanVar); - } - if(self->pCounts) - { - DeleteDynar(self->pCounts); - } - if(self->pCommand) - { - free(self->pCommand); - } - if(self->scanFunctions) - { - DeleteStringDict(self->scanFunctions); - } - free(self); - } +void DeleteScanObject(void *pData) +{ + pScanData self = NULL; + + self = (pScanData) pData; + if (!self) { + return; + } + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + } + if (self->pScanVar) { + DeleteDynar(self->pScanVar); + } + if (self->pCounts) { + DeleteDynar(self->pCounts); + } + if (self->pCommand) { + free(self->pCommand); + } + if (self->scanFunctions) { + DeleteStringDict(self->scanFunctions); + } + free(self); +} + /*------------------------------------------------------------------------*/ - int ResetScanFunctions(pScanData self) - { - assert(self); +int ResetScanFunctions(pScanData self) +{ + assert(self); + + self->PrepareScan = PrepareScan; + self->WriteHeader = WriteHeader; + self->WriteScanPoints = WriteScanPoints; + self->ScanDrive = ScanDrive; + self->ScanCount = ScanCount; + self->CollectScanData = CollectScanData; + return 1; +} - self->PrepareScan = PrepareScan; - self->WriteHeader = WriteHeader; - self->WriteScanPoints = WriteScanPoints; - self->ScanDrive = ScanDrive; - self->ScanCount = ScanCount; - self->CollectScanData = CollectScanData; - return 1; - } /*-------------------------------------------------------------------------*/ - int AddScanVar(pScanData self, SicsInterp *pSics, SConnection *pCon, - char *name, float fStart, float fStep) - { - pVarEntry pVar = NULL; - - if(self->iActive) - { - SCWrite(pCon,"ERROR: cannot change parameters while scan is running", - eError); - return 0; - } - - pVar = MakeScanVar(pSics,pCon,name,fStart,fStep); - if(pVar == NULL) - { - return 0; - } - - /* put it away */ - DynarPut(self->pScanVar,self->iScanVar,pVar); - self->iScanVar++; - - return 1; - } -/*-------------------------------------------------------------------------*/ - int AddLogVar(pScanData self, SicsInterp *pSics, SConnection *pCon, - char *name) - { - pVarEntry pVar = NULL; - - if(self->iActive) - { - SCWrite(pCon,"ERROR: cannot change parameters while scan is running", - eError); - return 0; - } - - pVar = MakeLogVar(pSics,pCon,name); - if(pVar == NULL) - { - return 0; - } - - /* put it away */ - DynarPut(self->pScanVar,self->iScanVar,pVar); - self->iScanVar++; - - return 1; - } -/*--------------------------------------------------------------------------*/ - int ClearScanVar(pScanData self) - { - if(self->iActive) - { - return 0; - } +int AddScanVar(pScanData self, SicsInterp * pSics, SConnection * pCon, + char *name, float fStart, float fStep) +{ + pVarEntry pVar = NULL; - self->iScanVar = 0; - return 1; + if (self->iActive) { + SCWrite(pCon, "ERROR: cannot change parameters while scan is running", + eError); + return 0; } + + pVar = MakeScanVar(pSics, pCon, name, fStart, fStep); + if (pVar == NULL) { + return 0; + } + + /* put it away */ + DynarPut(self->pScanVar, self->iScanVar, pVar); + self->iScanVar++; + + return 1; +} + +/*-------------------------------------------------------------------------*/ +int AddLogVar(pScanData self, SicsInterp * pSics, SConnection * pCon, + char *name) +{ + pVarEntry pVar = NULL; + + if (self->iActive) { + SCWrite(pCon, "ERROR: cannot change parameters while scan is running", + eError); + return 0; + } + + pVar = MakeLogVar(pSics, pCon, name); + if (pVar == NULL) { + return 0; + } + + /* put it away */ + DynarPut(self->pScanVar, self->iScanVar, pVar); + self->iScanVar++; + + return 1; +} + /*--------------------------------------------------------------------------*/ - static int WriteRecover(pScanData self) - { - FILE *fd; - pVarEntry pVar = NULL; - void *pData = NULL; - pCountEntry pCount = NULL; - int i, j, status; +int ClearScanVar(pScanData self) +{ + if (self->iActive) { + return 0; + } - fd = fopen(self->pRecover,"w"); - if(!fd) - { - return 0; - } - - fprintf(fd,"%s clear\n",self->objectName); + self->iScanVar = 0; + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int WriteRecover(pScanData self) +{ + FILE *fd; + pVarEntry pVar = NULL; + void *pData = NULL; + pCountEntry pCount = NULL; + int i, j, status; + + fd = fopen(self->pRecover, "w"); + if (!fd) { + return 0; + } + + fprintf(fd, "%s clear\n", self->objectName); + + /* write scan vars */ + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pData); + pVar = (pVarEntry) pData; + if (pVar) { + if (isLogVar(pVar)) { + fprintf(fd, "%s log %s\n", self->objectName, ScanVarName(pVar)); + } else { + fprintf(fd, "%s add %s %f %f\n", self->objectName, + ScanVarName(pVar), ScanVarStart(pVar), ScanVarStep(pVar)); + } + } + pData = NULL; + } + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pData); + pVar = (pVarEntry) pData; + if (pVar) { + status = LLDnodePtr2First(pVar->dataList); + while (status != 0) { + fprintf(fd, "%s appendvarpos %d %f\n", self->objectName, + i, LLDnodeFloat(pVar->dataList)); + status = LLDnodePtr2Next(pVar->dataList); + } + } + pData = NULL; + } + + /* write counts */ + for (i = 0; i < self->iCounts; i++) { + DynarGet(self->pCounts, i, &pData); + pCount = (pCountEntry) pData; + if (pCount != NULL) { + fprintf(fd, + "%s storecounts %ld %f %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld\n", + self->objectName, pCount->lCount, pCount->fTime, + pCount->Monitors[0], pCount->Monitors[1], + pCount->Monitors[2], pCount->Monitors[3], + pCount->Monitors[4], pCount->Monitors[5], + pCount->Monitors[6], pCount->Monitors[7], + pCount->Monitors[8], pCount->Monitors[9]); + } + } + if (self->iMode == eTimer) { + fprintf(fd, "%s continue %d timer %f\n", self->objectName, + self->iNP, self->fPreset); + } else { + fprintf(fd, "%s continue %d monitor %f\n", self->objectName, + self->iNP, self->fPreset); + } + fclose(fd); + return 1; +} - /* write scan vars */ - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pData); - pVar = (pVarEntry)pData; - if(pVar) - { - if(isLogVar(pVar)) - { - fprintf(fd,"%s log %s\n", self->objectName, ScanVarName(pVar)); - } - else - { - fprintf(fd,"%s add %s %f %f\n", self->objectName, ScanVarName(pVar), - ScanVarStart(pVar), ScanVarStep(pVar)); - } - } - pData = NULL; - } - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pData); - pVar = (pVarEntry)pData; - if(pVar) - { - status = LLDnodePtr2First(pVar->dataList); - while(status != 0) { - fprintf(fd,"%s appendvarpos %d %f\n",self->objectName, - i, LLDnodeFloat(pVar->dataList)); - status = LLDnodePtr2Next(pVar->dataList); - } - } - pData = NULL; - } - - /* write counts */ - for(i = 0; i < self->iCounts; i++) - { - DynarGet(self->pCounts,i,&pData); - pCount = (pCountEntry)pData; - if(pCount != NULL) - { - fprintf(fd,"%s storecounts %ld %f %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld\n", - self->objectName, - pCount->lCount, - pCount->fTime, - pCount->Monitors[0], - pCount->Monitors[1], - pCount->Monitors[2], - pCount->Monitors[3], - pCount->Monitors[4], - pCount->Monitors[5], - pCount->Monitors[6], - pCount->Monitors[7], - pCount->Monitors[8], - pCount->Monitors[9]); - } - } - if(self->iMode == eTimer){ - fprintf(fd,"%s continue %d timer %f\n",self->objectName, - self->iNP,self->fPreset); - }else { - fprintf(fd,"%s continue %d monitor %f\n",self->objectName, - self->iNP,self->fPreset); - } - fclose(fd); - return 1; - } /*-------------------------------------------------------------------------*/ int AppendScanLine(pScanData self, char *line) { - /* reopen file */ - self->fd = fopen(self->pFile,"r+"); - if(!self->fd) - { - SCWrite(self->pCon, - "ERROR: Failed to reopen scan file, aborting scan", - eError); - return 0; - } - - /* jump to end of file */ - fseek(self->fd,0,SEEK_END); + /* reopen file */ + self->fd = fopen(self->pFile, "r+"); + if (!self->fd) { + SCWrite(self->pCon, + "ERROR: Failed to reopen scan file, aborting scan", eError); + return 0; + } - /* print */ - fprintf(self->fd,"%s\n",line); + /* jump to end of file */ + fseek(self->fd, 0, SEEK_END); - /* done */ - fclose(self->fd); - self->fd = NULL; - return 1; + /* print */ + fprintf(self->fd, "%s\n", line); + + /* done */ + fclose(self->fd); + self->fd = NULL; + return 1; } + /*-------------------------------------------------------------------------*/ extern char *stptok(const char *s, char *t, int len, char *brk); extern char *trim(char *txt); @@ -392,737 +368,669 @@ int StoreScanCounts(pScanData self, char *data) int iCount = 0; char pBueffel[256]; - if(data == NULL) - { - SCWrite(self->pCon,"WARNING: StoreScanCounts called without data", - eLog); - return 1; + if (data == NULL) { + SCWrite(self->pCon, "WARNING: StoreScanCounts called without data", + eLog); + return 1; } InitCountEntry(&sCount); /* parse the data */ pPtr = trim(data); - pPtr = stptok(pPtr,pNumber,29," \t"); - if(pPtr != NULL) - { + pPtr = stptok(pPtr, pNumber, 29, " \t"); + if (pPtr != NULL) { sCount.lCount = atoi(pNumber); - } - else - { - SCWrite(self->pCon,"WARNING: No data in StoreScanCounts",eLog); - snprintf(pBueffel,255,"Received: %s", data); - SCWrite(self->pCon,pBueffel,eLog); + } else { + SCWrite(self->pCon, "WARNING: No data in StoreScanCounts", eLog); + snprintf(pBueffel, 255, "Received: %s", data); + SCWrite(self->pCon, pBueffel, eLog); return 1; } - pPtr = stptok(pPtr,pNumber,29," \t"); - if(pPtr != NULL) - { + pPtr = stptok(pPtr, pNumber, 29, " \t"); + if (pPtr != NULL) { sCount.fTime = atof(pNumber); - } - if(pPtr == NULL){ + } + if (pPtr == NULL) { return 1; } - while((pPtr = stptok(pPtr,pNumber,29," \t")) != NULL) - { + while ((pPtr = stptok(pPtr, pNumber, 29, " \t")) != NULL) { sCount.Monitors[iCount] = atoi(pNumber); iCount++; - if(iCount >= 10) - { + if (iCount >= 10) { SCWrite(self->pCon, - "ERROR: I have only space for 10 Monitors in count structure", + "ERROR: I have only space for 10 Monitors in count structure", eLogError); return 0; } - } + } sCount.i = self->iCounts; - DynarReplace(self->pCounts,self->iCounts,&sCount,sizeof(CountEntry)); + DynarReplace(self->pCounts, self->iCounts, &sCount, sizeof(CountEntry)); self->iCounts++; - if(self->iCounts > self->iNP){ + if (self->iCounts > self->iNP) { self->iNP++; } return 1; } + /*-----------------------------------------------------------------------*/ CountEntry CollectCounterData(pScanData self) { int i, iRet; CountEntry sCount; - char *pAns = NULL, *pPtr = NULL ; + char *pAns = NULL, *pPtr = NULL; Tcl_Interp *pTcl; float fVal; InitCountEntry(&sCount); /* monitors */ - for(i = 1; i < 10; i++) - { - sCount.Monitors[i-1] = GetMonitor((pCounter)self->pCounterData,i, + for (i = 1; i < 10; i++) { + sCount.Monitors[i - 1] = GetMonitor((pCounter) self->pCounterData, i, self->pCon); } - if( self->iChannel != 0 && self->iChannel != -10 ) - { - sCount.Monitors[self->iChannel - 1] = - GetCounts((pCounter)self->pCounterData, - self->pCon); + if (self->iChannel != 0 && self->iChannel != -10) { + sCount.Monitors[self->iChannel - 1] = + GetCounts((pCounter) self->pCounterData, self->pCon); } /* counts, depending on iChannel */ - if(self->iChannel == -10) - { + if (self->iChannel == -10) { /* execute the Tcl-script for getting the data */ pTcl = InterpGetTcl(self->pSics); - if(!self->pCommand) - { + if (!self->pCommand) { SCWrite(self->pCon, - "ERROR: command must be configured for user defined scans", - eError); - SCSetInterrupt(self->pCon,eAbortBatch); + "ERROR: command must be configured for user defined scans", + eError); + SCSetInterrupt(self->pCon, eAbortBatch); return sCount; } - iRet = Tcl_Eval(pTcl,self->pCommand); - if(iRet != TCL_OK) - { - SCWrite(self->pCon,pTcl->result,eLogError); + iRet = Tcl_Eval(pTcl, self->pCommand); + if (iRet != TCL_OK) { + SCWrite(self->pCon, pTcl->result, eLogError); return sCount; - } + } /* interprete the Tcl result as a list of counts WARNING: this may need to be changed when switching to future versions of Tcl - */ + */ pAns = strdup(pTcl->result); - pPtr = strtok(pAns," "); - if(!pPtr) - { - SCWrite(self->pCon,"ERROR: no counts found in Tcl-result",eLogError); - } - sscanf(pPtr,"%f",&fVal); - sCount.lCount = (long)fVal; + pPtr = strtok(pAns, " "); + if (!pPtr) { + SCWrite(self->pCon, "ERROR: no counts found in Tcl-result", + eLogError); + } + sscanf(pPtr, "%f", &fVal); + sCount.lCount = (long) fVal; i = 0; - while( (pPtr != NULL) && (i < 10)) - { - pPtr = strtok(NULL," "); - if(pPtr) - { - sscanf(pPtr,"%f",&fVal); - sCount.Monitors[i] = (long)fVal; - i++; + while ((pPtr != NULL) && (i < 10)) { + pPtr = strtok(NULL, " "); + if (pPtr) { + sscanf(pPtr, "%f", &fVal); + sCount.Monitors[i] = (long) fVal; + i++; } - } + } free(pAns); + } else if (self->iChannel == 0) { + sCount.lCount = GetCounts((pCounter) self->pCounterData, self->pCon); + } else { + sCount.lCount = GetMonitor((pCounter) self->pCounterData, + self->iChannel, self->pCon); } - else if(self->iChannel == 0) - { - sCount.lCount = GetCounts((pCounter)self->pCounterData,self->pCon); - } - else - { - sCount.lCount = GetMonitor((pCounter)self->pCounterData, - self->iChannel, self->pCon); - } - + /* get time */ - sCount.fTime = GetCountTime((pCounter)self->pCounterData, - self->pCon); + sCount.fTime = GetCountTime((pCounter) self->pCounterData, self->pCon); /* stow away */ - DynarReplace(self->pCounts,self->iCounts,&sCount,sizeof(CountEntry)); + DynarReplace(self->pCounts, self->iCounts, &sCount, sizeof(CountEntry)); self->iCounts++; - if(self->iCounts > self->iNP){ + if (self->iCounts > self->iNP) { self->iNP++; } return sCount; } + /*---------------------------------------------------------------------------*/ - static int ScanLoop(pScanData self) - { - int i,iInt,iRet,iStatus; - - assert(self); - assert(self->pCon); - - InvokeCallBack(self->pCall,SCANSTART,self); - for(i = self->iCounts; i < self->iNP; i++) - { +static int ScanLoop(pScanData self) +{ + int i, iInt, iRet, iStatus; + + assert(self); + assert(self->pCon); + + InvokeCallBack(self->pCall, SCANSTART, self); + for (i = self->iCounts; i < self->iNP; i++) { /*--------- drive */ - iRet = self->ScanDrive(self,i); - /* finished, check for interrupts. Whatever happened, user - interrupt or HW interrupt, it will be on our connection - */ - iInt = SCGetInterrupt(self->pCon); - switch(iInt) - { - case eContinue: - break; - case eAbortOperation: - SCSetInterrupt(self->pCon,eContinue); - SCWrite(self->pCon, - "WARNING: skipped scan point due to motor failure", - eLog); - continue; - break; - case eAbortScan: - SCWrite(self->pCon,"ERROR: Scan aborted",eLogError); - /* eat the interrupt, the requested op has been - done - */ - SCSetInterrupt(self->pCon,eContinue); - return 0; - break; - default: /* all others */ - SCWrite(self->pCon,"ERROR: Scan aborted",eLogError); - return 0; - break; - } - if(!iRet) - { - SCWrite(self->pCon,"WARNING: skipped scan point after drive failure", - eLog); - continue; - } + iRet = self->ScanDrive(self, i); + /* finished, check for interrupts. Whatever happened, user + interrupt or HW interrupt, it will be on our connection + */ + iInt = SCGetInterrupt(self->pCon); + switch (iInt) { + case eContinue: + break; + case eAbortOperation: + SCSetInterrupt(self->pCon, eContinue); + SCWrite(self->pCon, + "WARNING: skipped scan point due to motor failure", eLog); + continue; + break; + case eAbortScan: + SCWrite(self->pCon, "ERROR: Scan aborted", eLogError); + /* eat the interrupt, the requested op has been + done + */ + SCSetInterrupt(self->pCon, eContinue); + return 0; + break; + default: /* all others */ + SCWrite(self->pCon, "ERROR: Scan aborted", eLogError); + return 0; + break; + } + if (!iRet) { + SCWrite(self->pCon, + "WARNING: skipped scan point after drive failure", eLog); + continue; + } /*-------------- count */ - iRet = self->ScanCount(self, i); - /* finished, check for interrupts. Whatever happened, user - interrupt or HW interrupt, it will be on our connection - */ - iInt = SCGetInterrupt(self->pCon); - switch(iInt) - { - case eContinue: - break; - case eAbortOperation: - continue; - break; - case eAbortScan: - SCWrite(self->pCon,"ERROR: Scan aborted",eLogError); - /* eat the interrupt, the requested op has been - done - */ - SCSetInterrupt(self->pCon,eContinue); - return 0; - break; - default: /* all others */ - SCWrite(self->pCon,"ERROR: Scan aborted",eLogError); - return 0; - break; - } - if(!iRet) - { - SCWrite(self->pCon,"WARNING: skipped scan point after count failure", - eLog); - continue; - } - + iRet = self->ScanCount(self, i); + /* finished, check for interrupts. Whatever happened, user + interrupt or HW interrupt, it will be on our connection + */ + iInt = SCGetInterrupt(self->pCon); + switch (iInt) { + case eContinue: + break; + case eAbortOperation: + continue; + break; + case eAbortScan: + SCWrite(self->pCon, "ERROR: Scan aborted", eLogError); + /* eat the interrupt, the requested op has been + done + */ + SCSetInterrupt(self->pCon, eContinue); + return 0; + break; + default: /* all others */ + SCWrite(self->pCon, "ERROR: Scan aborted", eLogError); + return 0; + break; + } + if (!iRet) { + SCWrite(self->pCon, + "WARNING: skipped scan point after count failure", eLog); + continue; + } + /*-------- scan post processing */ - self->CollectScanData(self,i); - InvokeCallBack(self->pCall,SCANPOINT,self); + self->CollectScanData(self, i); + InvokeCallBack(self->pCall, SCANPOINT, self); - self->WriteScanPoints(self,i); - if(self->pRecover) - { - WriteRecover(self); - } - } - return 1; + self->WriteScanPoints(self, i); + if (self->pRecover) { + WriteRecover(self); + } } + return 1; +} + /*--------------------------------------------------------------------------*/ - int DoScan(pScanData self, int iNP, int iMode, float fPreset, - SicsInterp *pSics, SConnection *pCon) - { - int iRet; - char *pPtr = NULL; - char pBueffel[1024]; - - assert(self); - assert(pCon); - assert(pSics); - - self->pCon = pCon; - self->pSics = pSics; - - /* check arguments */ - if(iNP <= 0) - { - SCWrite(self->pCon,"ERROR: iNP < 0, nothing to do, Scan aborted",eError); - self->pCon = NULL; - self->pSics = NULL; - return 0; - } - if(self->iScanVar <= 0) - { - SCWrite(self->pCon,"WARNING: no scan variables given",eWarning); - } - - if( (iMode != eTimer) && (iMode != ePreset)) - { - SCWrite(self->pCon,"ERROR: Invalid counter mode given",eError); - self->pCon = NULL; - self->pSics = NULL; - return 0; - } - if(self->iActive != 0) - { - SCWrite(pCon,"ERROR: another scan is still running",eError); - self->pCon = NULL; - self->pSics = NULL; - return 0; - } +int DoScan(pScanData self, int iNP, int iMode, float fPreset, + SicsInterp * pSics, SConnection * pCon) +{ + int iRet; + char *pPtr = NULL; + char pBueffel[1024]; - self->iNP = iNP; - self->iMode = iMode; - self->fPreset = fPreset; - - /* do some preprocessing */ - if(self->PrepareScan != NULL) - { - iRet = self->PrepareScan(self); - } - else - { - iRet = 1; - } - if(!iRet) - { - self->pCon = NULL; - self->pSics = NULL; - return 0; - } - + assert(self); + assert(pCon); + assert(pSics); - iRet = self->WriteHeader(self); - if(!iRet) - { - SCWrite(self->pCon,"ERROR: cannot open data file, Scan aborted", - eError); - self->pCon = NULL; - self->pSics = NULL; - return 0; - } + self->pCon = pCon; + self->pSics = pSics; + + /* check arguments */ + if (iNP <= 0) { + SCWrite(self->pCon, "ERROR: iNP < 0, nothing to do, Scan aborted", + eError); + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + if (self->iScanVar <= 0) { + SCWrite(self->pCon, "WARNING: no scan variables given", eWarning); + } + + if ((iMode != eTimer) && (iMode != ePreset)) { + SCWrite(self->pCon, "ERROR: Invalid counter mode given", eError); + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + if (self->iActive != 0) { + SCWrite(pCon, "ERROR: another scan is still running", eError); + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + + self->iNP = iNP; + self->iMode = iMode; + self->fPreset = fPreset; + + /* do some preprocessing */ + if (self->PrepareScan != NULL) { + iRet = self->PrepareScan(self); + } else { + iRet = 1; + } + if (!iRet) { + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + + + iRet = self->WriteHeader(self); + if (!iRet) { + SCWrite(self->pCon, "ERROR: cannot open data file, Scan aborted", + eError); + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + + self->iActive = 1; + iRet = ScanLoop(self); + ScriptScanFinish(self); + InvokeCallBack(self->pCall, SCANEND, self); + SendQuieck(QUIECK, self->pFile); + self->iActive = 0; + self->pCon = NULL; + self->pSics = NULL; + return iRet; +} - self->iActive = 1; - iRet = ScanLoop(self); - ScriptScanFinish(self); - InvokeCallBack(self->pCall,SCANEND,self); - SendQuieck(QUIECK,self->pFile); - self->iActive = 0; - self->pCon = NULL; - self->pSics = NULL; - return iRet; - } /*---------------------------------------------------------------------------- SilentScan does a scan which does not produce a data file. It is intended for internal use. Only status messages appear on screen. ----------------------------------------------------------------------------*/ - int SilentScan(pScanData self, int iNP, int iMode, float fPreset, - SicsInterp *pSics, SConnection *pCon) - { - int iRet; - char *pPtr = NULL; - char pBueffel[1024]; - int (*HeaderFunc)(pScanData self), (*ScanFunc)(pScanData self, - int iPoint); - - assert(self); - assert(pCon); - assert(pSics); - - /* check arguments */ - if(iNP <= 0) - { - SCWrite(self->pCon,"ERROR: iNP < 0, nothing to do, Scan aborted",eError); - return 0; - } - if(self->iScanVar <= 0) - { - SCWrite(self->pCon,"WARNING: no scan variables given",eWarning); - } - - if( (iMode != eTimer) && (iMode != ePreset)) - { - SCWrite(self->pCon,"ERROR: Invalid counter mode given",eError); - return 0; - } - if(self->iActive != 0) - { - SCWrite(pCon,"ERROR: another scan is still running",eError); - self->pCon = NULL; - self->pSics = NULL; - return 0; - } +---------------------------------------------------------------------------*/ +int SilentScan(pScanData self, int iNP, int iMode, float fPreset, + SicsInterp * pSics, SConnection * pCon) +{ + int iRet; + char *pPtr = NULL; + char pBueffel[1024]; + int (*HeaderFunc) (pScanData self), (*ScanFunc) (pScanData self, + int iPoint); + + assert(self); + assert(pCon); + assert(pSics); + + /* check arguments */ + if (iNP <= 0) { + SCWrite(self->pCon, "ERROR: iNP < 0, nothing to do, Scan aborted", + eError); + return 0; + } + if (self->iScanVar <= 0) { + SCWrite(self->pCon, "WARNING: no scan variables given", eWarning); + } + + if ((iMode != eTimer) && (iMode != ePreset)) { + SCWrite(self->pCon, "ERROR: Invalid counter mode given", eError); + return 0; + } + if (self->iActive != 0) { + SCWrite(pCon, "ERROR: another scan is still running", eError); + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + + HeaderFunc = self->WriteHeader; + self->WriteHeader = DummyWrite; + ScanFunc = self->WriteScanPoints; + self->WriteScanPoints = DummyWrite2; + self->pCon = pCon; + self->pSics = pSics; + self->iNP = iNP; + self->iMode = iMode; + self->fPreset = fPreset; + + /* do some preprocessing */ + iRet = SilentPrepare(self); + if (!iRet) { + self->WriteHeader = HeaderFunc; + self->WriteScanPoints = ScanFunc; + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + + self->iActive = 1; + iRet = ScanLoop(self); + self->iActive = 0; + self->pCon = NULL; + self->pSics = NULL; + self->WriteHeader = HeaderFunc; + self->WriteScanPoints = ScanFunc; + + return iRet; +} - HeaderFunc = self->WriteHeader; - self->WriteHeader = DummyWrite; - ScanFunc = self->WriteScanPoints; - self->WriteScanPoints = DummyWrite2; - self->pCon = pCon; - self->pSics = pSics; - self->iNP = iNP; - self->iMode = iMode; - self->fPreset = fPreset; - - /* do some preprocessing */ - iRet = SilentPrepare(self); - if(!iRet) - { - self->WriteHeader = HeaderFunc; - self->WriteScanPoints = ScanFunc; - self->pCon = NULL; - self->pSics = NULL; - return 0; - } - - self->iActive = 1; - iRet = ScanLoop(self); - self->iActive = 0; - self->pCon = NULL; - self->pSics = NULL; - self->WriteHeader = HeaderFunc; - self->WriteScanPoints = ScanFunc; - - return iRet; - } /*--------------------------------------------------------------------------*/ - int ContinueScan(pScanData self, SicsInterp *pSics, SConnection *pCon, - int argc, char *argv[]) - { - int iRet; - char *pPtr = NULL, pBueffel[512]; - double dVal; - - assert(pSics); - assert(pCon); - - self->pCon = pCon; - self->pSics = pSics; - - if(argc < 5) - { - SCWrite(pCon,"ERROR: not enough arguments to scan continue",eError); - return 0; - } +int ContinueScan(pScanData self, SicsInterp * pSics, SConnection * pCon, + int argc, char *argv[]) +{ + int iRet; + char *pPtr = NULL, pBueffel[512]; + double dVal; - /* get NP */ - iRet = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&self->iNP); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* interpret Mode */ - if(strcmp(argv[3],"timer") == 0) - { - self->iMode = eTimer; - } - else if(strcmp(argv[3],"monitor") == 0) - { - self->iMode = ePreset; - } - else - { - sprintf(pBueffel,"ERROR: %s not recognized as valid counter mode", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* preset */ - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->fPreset = dVal; - - /* configure counter */ - SetCounterMode((pCounter)self->pCounterData,self->iMode); - SetCounterPreset((pCounter)self->pCounterData, self->fPreset); - + assert(pSics); + assert(pCon); - /* new scan data file */ - pPtr = ScanMakeFileName(self->pSics,self->pCon); - if(!pPtr) - { - SCWrite(self->pCon,"ERROR: cannot allocate new data filename, Scan aborted", - eError); - self->pCon = NULL; - self->pSics = NULL; - return 0; - } - sprintf(pBueffel,"Writing data file: %s ...",pPtr); - SCWrite(self->pCon,pBueffel,eWarning); - strcpy(self->pFile,pPtr); - free(pPtr); - iRet = self->WriteHeader(self); - if(!iRet) - { - SCWrite(self->pCon,"ERROR: cannot open data file, Scan aborted", - eError); - self->pCon = NULL; - self->pSics = NULL; - return 0; - } + self->pCon = pCon; + self->pSics = pSics; + + if (argc < 5) { + SCWrite(pCon, "ERROR: not enough arguments to scan continue", eError); + return 0; + } + + /* get NP */ + iRet = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &self->iNP); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* interpret Mode */ + if (strcmp(argv[3], "timer") == 0) { + self->iMode = eTimer; + } else if (strcmp(argv[3], "monitor") == 0) { + self->iMode = ePreset; + } else { + sprintf(pBueffel, "ERROR: %s not recognized as valid counter mode", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* preset */ + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->fPreset = dVal; + + /* configure counter */ + SetCounterMode((pCounter) self->pCounterData, self->iMode); + SetCounterPreset((pCounter) self->pCounterData, self->fPreset); + + + /* new scan data file */ + pPtr = ScanMakeFileName(self->pSics, self->pCon); + if (!pPtr) { + SCWrite(self->pCon, + "ERROR: cannot allocate new data filename, Scan aborted", + eError); + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + sprintf(pBueffel, "Writing data file: %s ...", pPtr); + SCWrite(self->pCon, pBueffel, eWarning); + strcpy(self->pFile, pPtr); + free(pPtr); + iRet = self->WriteHeader(self); + if (!iRet) { + SCWrite(self->pCon, "ERROR: cannot open data file, Scan aborted", + eError); + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + + self->iActive = 1; + iRet = ScanLoop(self); + ScriptScanFinish(self); + InvokeCallBack(self->pCall, SCANEND, self); + SendQuieck(QUIECK, self->pFile); + self->iActive = 0; + self->pCon = NULL; + self->pSics = NULL; + return iRet; + +} - self->iActive = 1; - iRet = ScanLoop(self); - ScriptScanFinish(self); - InvokeCallBack(self->pCall,SCANEND,self); - SendQuieck(QUIECK,self->pFile); - self->iActive = 0; - self->pCon = NULL; - self->pSics = NULL; - return iRet; - - } /*--------------------------------------------------------------------------*/ - int GetScanNP(pScanData self) - { - assert(self); - return self->iNP; - } -/*--------------------------------------------------------------------------*/ - float GetScanPreset(pScanData self) - { - assert(self); - return self->fPreset; - } -/*--------------------------------------------------------------------------*/ - int GetScanCounts(pScanData self,long *lData, int iDataLen) - { - int i, iEnd; - pCountEntry pData = NULL; - void *pPtr = NULL; - - assert(self); - /* hanlde iEnd */ - if(self->iCounts < iDataLen) - { - iEnd = self->iCounts; - } - else - { - iEnd = iDataLen; - } - - /* initialise to 0 */ - memset(lData,0,iDataLen*sizeof(long)); - - /* the loop */ - for(i = 0; i < iEnd; i++) - { - DynarGet(self->pCounts,i,&pPtr); - pData = (pCountEntry)pPtr; - if(pData) - { - lData[i] = pData->lCount; - } - pData = NULL; - } - - return 1; - } -/*--------------------------------------------------------------------------*/ - int GetScanMonitor(pScanData self,int iWhich,long *lData, int iDataLen) - { - int i, iEnd; - pCountEntry pData = NULL; - void *pPtr = NULL; - - assert(self); +int GetScanNP(pScanData self) +{ + assert(self); + return self->iNP; +} - /* hanlde iEnd */ - if(self->iCounts < iDataLen) - { - iEnd = self->iCounts; - } - else - { - iEnd = iDataLen; - } - - /* initialise to 0 */ - memset(lData,0,iDataLen*sizeof(long)); - - /* the loop */ - for(i = 0; i < iEnd; i++) - { - DynarGet(self->pCounts,i,&pPtr); - pData = (pCountEntry)pPtr; - if(pData) - { - lData[i] = pData->Monitors[iWhich]; - } - pData = NULL; - } - - return 1; - } /*--------------------------------------------------------------------------*/ - int GetScanVar(pScanData self, int iWhich, float *fData, int iDataLen) - { - int iEnd, i; - pVarEntry pVar = NULL; - void *pPtr = NULL; - - /* does it exist ?*/ - if( (iWhich < 0) || (iWhich >= self->iScanVar) ) - { - return 0; +float GetScanPreset(pScanData self) +{ + assert(self); + return self->fPreset; +} + +/*--------------------------------------------------------------------------*/ +int GetScanCounts(pScanData self, long *lData, int iDataLen) +{ + int i, iEnd; + pCountEntry pData = NULL; + void *pPtr = NULL; + + assert(self); + /* hanlde iEnd */ + if (self->iCounts < iDataLen) { + iEnd = self->iCounts; + } else { + iEnd = iDataLen; + } + + /* initialise to 0 */ + memset(lData, 0, iDataLen * sizeof(long)); + + /* the loop */ + for (i = 0; i < iEnd; i++) { + DynarGet(self->pCounts, i, &pPtr); + pData = (pCountEntry) pPtr; + if (pData) { + lData[i] = pData->lCount; } + pData = NULL; + } - /* handle iEnd */ - if(self->iCounts < iDataLen) - { - iEnd = self->iCounts; - } - else - { - iEnd = iDataLen; - } + return 1; +} - DynarGet(self->pScanVar,iWhich,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - /* initialise to theoretical values */ - for(i = 0; i < self->iNP; i++) - { - fData[i] = pVar->fStart + i * pVar->fStep; - } - CopyScanVar(pVar,fData, self->iNP); - return 1; - } - else - { - return 0; - } - - /* not reached */ - assert(0); - } /*--------------------------------------------------------------------------*/ - int GetSoftScanVar(pScanData self, int iWhich, float *fData, int iDataLen) - { - int iEnd, i; - pVarEntry pVar = NULL; - void *pPtr = NULL; - - /* does it exist ?*/ - if( (iWhich < 0) || (iWhich >= self->iScanVar) ) - { - return 0; +int GetScanMonitor(pScanData self, int iWhich, long *lData, int iDataLen) +{ + int i, iEnd; + pCountEntry pData = NULL; + void *pPtr = NULL; + + assert(self); + + /* hanlde iEnd */ + if (self->iCounts < iDataLen) { + iEnd = self->iCounts; + } else { + iEnd = iDataLen; + } + + /* initialise to 0 */ + memset(lData, 0, iDataLen * sizeof(long)); + + /* the loop */ + for (i = 0; i < iEnd; i++) { + DynarGet(self->pCounts, i, &pPtr); + pData = (pCountEntry) pPtr; + if (pData) { + lData[i] = pData->Monitors[iWhich]; } + pData = NULL; + } - /* handle iEnd */ - if(self->iCounts < iDataLen) - { - iEnd = self->iCounts; - } - else - { - iEnd = iDataLen; - } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int GetScanVar(pScanData self, int iWhich, float *fData, int iDataLen) +{ + int iEnd, i; + pVarEntry pVar = NULL; + void *pPtr = NULL; + + /* does it exist ? */ + if ((iWhich < 0) || (iWhich >= self->iScanVar)) { + return 0; + } + + /* handle iEnd */ + if (self->iCounts < iDataLen) { + iEnd = self->iCounts; + } else { + iEnd = iDataLen; + } + + DynarGet(self->pScanVar, iWhich, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + /* initialise to theoretical values */ + for (i = 0; i < self->iNP; i++) { + fData[i] = pVar->fStart + i * pVar->fStep; + } + CopyScanVar(pVar, fData, self->iNP); + return 1; + } else { + return 0; + } + + /* not reached */ + assert(0); +} + +/*--------------------------------------------------------------------------*/ +int GetSoftScanVar(pScanData self, int iWhich, float *fData, int iDataLen) +{ + int iEnd, i; + pVarEntry pVar = NULL; + void *pPtr = NULL; + + /* does it exist ? */ + if ((iWhich < 0) || (iWhich >= self->iScanVar)) { + return 0; + } + + /* handle iEnd */ + if (self->iCounts < iDataLen) { + iEnd = self->iCounts; + } else { + iEnd = iDataLen; + } + + DynarGet(self->pScanVar, iWhich, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + /* initialise to theoretical values */ + for (i = 0; i < self->iNP; i++) { + fData[i] = pVar->fStart + i * pVar->fStep; + } + return 1; + } else { + return 0; + } + + /* not reached */ + assert(0); +} - DynarGet(self->pScanVar,iWhich,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - /* initialise to theoretical values */ - for(i = 0; i < self->iNP; i++) - { - fData[i] = pVar->fStart + i * pVar->fStep; - } - return 1; - } - else - { - return 0; - } - - /* not reached */ - assert(0); - } /*-------------------------------------------------------------------------*/ - int GetScanVarName(pScanData self, int iWhich, char *pName, int iLength) - { - pVarEntry pVar = NULL; - void *pPtr = NULL; - - /* does it exist ?*/ - if( (iWhich < 0) || (iWhich >= self->iScanVar) ) - { - return 0; - } +int GetScanVarName(pScanData self, int iWhich, char *pName, int iLength) +{ + pVarEntry pVar = NULL; + void *pPtr = NULL; + + /* does it exist ? */ + if ((iWhich < 0) || (iWhich >= self->iScanVar)) { + return 0; + } + + /* get the scan var */ + DynarGet(self->pScanVar, iWhich, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + strncpy(pName, ScanVarName(pVar), iLength); + return 1; + } else { + return 0; + } +} - /* get the scan var */ - DynarGet(self->pScanVar,iWhich,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - strncpy(pName,ScanVarName(pVar),iLength); - return 1; - } - else - { - return 0; - } - } /*---------------------------------------------------------------------*/ - int GetScanVarStep(pScanData self, int iWhich, float *fStep) - { - pVarEntry pVar = NULL; - void *pPtr = NULL; - - /* does it exist ?*/ - if( (iWhich < 0) || (iWhich >= self->iScanVar) ) - { - return 0; - } +int GetScanVarStep(pScanData self, int iWhich, float *fStep) +{ + pVarEntry pVar = NULL; + void *pPtr = NULL; + + /* does it exist ? */ + if ((iWhich < 0) || (iWhich >= self->iScanVar)) { + return 0; + } + + /* get the scan var */ + DynarGet(self->pScanVar, iWhich, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + *fStep = ScanVarStep(pVar); + return 1; + } else { + return 0; + } +} - /* get the scan var */ - DynarGet(self->pScanVar,iWhich,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - *fStep = ScanVarStep(pVar); - return 1; - } - else - { - return 0; - } - } /*-------------------------------------------------------------------------- ScanIntegrate does an integration of the current scan data. It returns 1 on success or one of the integrate error codes defined in integrate.h -----------------------------------------------------------------------------*/ - int ScanIntegrate(pScanData self, float *fSum, float *fVar) - { - long *lData = NULL; - int iRet; - - assert(self); - - /* no integration if no peak measured */ - if(self->iCounts <= self->iWindow*2) - return INTEGNOPEAK; - - /* get some memory */ - lData = (long *)malloc(self->iNP*sizeof(long)); - if(!lData) - { - return INTEGNOPEAK; - } - /* get counts */ - GetScanCounts(self,lData,self->iNP); - /* Do it */ - iRet = GabePeakIntegrate(self->iWindow,self->iNP,lData, fSum, fVar); - free(lData); - return iRet; - } +int ScanIntegrate(pScanData self, float *fSum, float *fVar) +{ + long *lData = NULL; + int iRet; + + assert(self); + + /* no integration if no peak measured */ + if (self->iCounts <= self->iWindow * 2) + return INTEGNOPEAK; + + /* get some memory */ + lData = (long *) malloc(self->iNP * sizeof(long)); + if (!lData) { + return INTEGNOPEAK; + } + /* get counts */ + GetScanCounts(self, lData, self->iNP); + /* Do it */ + iRet = GabePeakIntegrate(self->iWindow, self->iNP, lData, fSum, fVar); + free(lData); + return iRet; +} + /*-------------------------------------------------------------------------- SimScan is a debugging aid for other modules. It simulates a scan on a variable in the range from 10 -20 degrees in angle and 100 points. Data @@ -1131,1313 +1039,1169 @@ CountEntry CollectCounterData(pScanData self) of 5 counts. The peak will sit on a background of 20 counts. This requires a motor a4 to exist as it will be used for x-axis simulation. This routine will not stop you from simulating shit if you throw shit at it! -----------------------------------------------------------------------------*/ - int SimScan(pScanData self, float fPos, float FWHM, float fHeight) - { - int i, iRet; - SConnection *pCon = NULL; - CountEntry sCount; - pVarEntry pVar = NULL; - void *pDings = NULL; - float x, y, fTmp, fStdDev; - - - assert(self); - - InitCountEntry(&sCount); +----------------------------------------------------------------------------*/ +int SimScan(pScanData self, float fPos, float FWHM, float fHeight) +{ + int i, iRet; + SConnection *pCon = NULL; + CountEntry sCount; + pVarEntry pVar = NULL; + void *pDings = NULL; + float x, y, fTmp, fStdDev; + + + assert(self); + + InitCountEntry(&sCount); + + /* go to a clean state */ + ClearScanVar(self); + + /* put in the scan variable */ + pCon = SCCreateDummyConnection(pServ->pSics); + if (!pCon) { + return 0; + } + iRet = AddScanVar(self, pServ->pSics, pCon, "a4", 10., 0.1); + SCDeleteConnection(pCon); + if (!iRet) { + return 0; + } + + /* do the x-axis of the scan */ + DynarGet(self->pScanVar, 0, &pDings); + pVar = (pVarEntry) pDings; + if (!pVar) { + return 0; + } + + + /* create scan data in loop */ + fStdDev = FWHM / 2.354; + for (i = 0; i < 90; i++) { + x = 10. + 0.1 * i; + AppendScanVar(pVar, x); + sCount.i = i; + /* gaussian */ + fTmp = (x - fPos) / fStdDev; + y = fHeight * 0.4 * exp(-0.5 * fTmp * fTmp); + /* randomize a little */ + y += 7. * (float) rand() / (float) RAND_MAX; + /* add a little background */ + sCount.lCount = (long) (10 + y); + /* stow away */ + DynarReplace(self->pCounts, i, &sCount, sizeof(CountEntry)); + } + self->iCounts = 90; + self->iNP = 90; + return 1; +} - /* go to a clean state */ - ClearScanVar(self); - - /* put in the scan variable */ - pCon = SCCreateDummyConnection(pServ->pSics); - if(!pCon) - { - return 0; - } - iRet = AddScanVar(self,pServ->pSics,pCon,"a4",10., 0.1); - SCDeleteConnection(pCon); - if(!iRet) - { - return 0; - } - - /* do the x-axis of the scan */ - DynarGet(self->pScanVar,0,&pDings); - pVar = (pVarEntry)pDings; - if(!pVar) - { - return 0; - } - - - /* create scan data in loop */ - fStdDev = FWHM/2.354; - for(i = 0; i < 90; i++) - { - x = 10. + 0.1 * i; - AppendScanVar(pVar,x); - sCount.i = i; - /* gaussian */ - fTmp = (x - fPos)/fStdDev; - y = fHeight*0.4* exp(-0.5*fTmp*fTmp); - /* randomize a little */ - y += 7. * (float)rand()/(float)RAND_MAX; - /* add a little background */ - sCount.lCount = (long)(10 + y); - /* stow away */ - DynarReplace(self->pCounts,i,&sCount,sizeof(CountEntry)); - } - self->iCounts = 90; - self->iNP = 90; - return 1; - } /*---------------------------------------------------------------------------*/ - int ScanFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pScanData pNew = NULL; - pCounter pCount = NULL; - pDummy pDum = NULL; - CommandList *pCom = NULL; - char pBueffel[512]; - int iRet; - - if(argc < 5) - { - SCWrite(pCon,"ERROR: Insufficient number of arguments to ScanFactory", - eError); - return 0; - } - - strtolower(argv[1]); - strtolower(argv[2]); - pCom = FindCommand(pSics,argv[2]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: cannot find counter %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pDum = (pDummy)pCom->pData; - if(!pDum) - { - sprintf(pBueffel,"ERROR: counter %s has no data",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!(pDum->pDescriptor->GetInterface(pDum,COUNTID))) - { - sprintf(pBueffel,"ERROR: object %s is NO counter",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pNew = CreateScanObject(argv[4],argv[3],(pCounter)pCom->pData, - argv[1]); - if(!pNew) - { - SCWrite(pCon,"ERROR: failure to allocate scan data structure", - eError); - return 0; - } - - iRet = AddCommand(pSics, - argv[1], - ScanWrapper, - DeleteScanObject, - pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* - ignore this one, this is cheaper then checking for the existence - of another scan object - */ - AddCommand(pSics, - "stdscan", - StandardScanWrapper, - NULL, - NULL); - return 1; - } -/*--------------------------------------------------------------------------*/ - static int ScanInterest(int iEvent, void *pEventData, void *pUser) - { - pScanData self = NULL; - SConnection *pCon = NULL; - char *pPtr = NULL, pItem[20]; - long *lData = NULL; - int i; - writeFunc oldWrite; - - self = (pScanData)pEventData; - pCon = (SConnection *)pUser; - - assert(self); - assert(pCon); - - if(!SCisConnected(pCon)){ - return -1; - } +int ScanFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pScanData pNew = NULL; + pCounter pCount = NULL; + pDummy pDum = NULL; + CommandList *pCom = NULL; + char pBueffel[512]; + int iRet; - if(iEvent == SCANSTART) - { - SCWrite(pCon,"NewScan",eLog); - return 1; - } - else if(iEvent == SCANEND) - { - SCWrite(pCon,"ScanEnd",eLog); - return 1; - } - else if(iEvent == SCANPOINT) - { - /* allocate space */ - pPtr = (char *)malloc((self->iNP*20+20)*sizeof(char)); - if(!pPtr) - { - return 0; - } - memset(pPtr,0,(self->iNP*20+20)*sizeof(char)); - lData = (long *)malloc(self->iNP*sizeof(long)); - if(!lData) - { - return 0; - } - memset(lData,0,self->iNP*sizeof(long)); - - /* get counts */ - GetScanCounts(self,lData,self->iNP); - /* format a message */ - - strcpy(pPtr,"scan.Counts= {"); - for(i = 0; i < self->iNP; i++) - { - sprintf(pItem,"%ld ",lData[i]); - strcat(pPtr,pItem); - } - strcat(pPtr,"}"); - oldWrite = SCGetWriteFunc(pCon); - SCSetWriteFunc(pCon,SCOnlySockWrite); - SCWrite(pCon,pPtr,eLog); - SCSetWriteFunc(pCon,oldWrite); - free(lData); - free(pPtr); - return 1; - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int ScanDynInterest(int iEvent, void *pEventData, void *pUser) - { - pScanData self = NULL; - SConnection *pCon = NULL; - void *pPtr; - pVarEntry pVar; - pCountEntry pCount = NULL; - float fVal; - long lVal; - int i; - char pBueffel[256]; + if (argc < 5) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to ScanFactory", + eError); + return 0; + } - self = (pScanData)pEventData; - pCon = (SConnection *)pUser; - - assert(self); - assert(pCon); - - if(!SCisConnected(pCon)) - { - return -1; - } + strtolower(argv[1]); + strtolower(argv[2]); + pCom = FindCommand(pSics, argv[2]); + if (!pCom) { + sprintf(pBueffel, "ERROR: cannot find counter %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pDum = (pDummy) pCom->pData; + if (!pDum) { + sprintf(pBueffel, "ERROR: counter %s has no data", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!(pDum->pDescriptor->GetInterface(pDum, COUNTID))) { + sprintf(pBueffel, "ERROR: object %s is NO counter", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pNew = CreateScanObject(argv[4], argv[3], (pCounter) pCom->pData, + argv[1]); + if (!pNew) { + SCWrite(pCon, "ERROR: failure to allocate scan data structure", + eError); + return 0; + } - if(iEvent == SCANSTART) - { - SCWrite(pCon,"NewScan",eLog); - return 1; - } - else if(iEvent == SCANEND) - { - SCWrite(pCon,"ScanEnd",eLog); - return 1; - } - else if(iEvent == SCANPOINT) - { - i = self->iCounts -1; - DynarGet(self->pScanVar,0,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar != NULL){ - fVal = GetScanVarPos(pVar,i); - } else { - fVal = -9999.99; - } - DynarGet(self->pCounts,i,&pPtr); - pCount =(pCountEntry)pPtr; - if(pCount != NULL){ - lVal = pCount->lCount; - } else { - lVal = -9999.99; - } - snprintf(pBueffel,255,"%s.scanpoint = {%d %f %ld}", - self->objectName,i,fVal,lVal); - SCWrite(pCon,pBueffel,eLog); - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int ScanUUInterest(int iEvent, void *pEventData, void *pUser) - { - pScanData self = NULL; - SConnection *pCon = NULL, *comCon = NULL; - char pItem[20]; - long *lData = NULL; - int *iData = NULL; - int i; - - self = (pScanData)pEventData; - pCon = (SConnection *)pUser; - - assert(self); - assert(pCon); - /* - printf("ScanUUInterest called for pCon = %p handle %d\n", pCon, pCon->sockHandle); - */ - if(!SCisConnected(pCon)){ - return -1; - } + iRet = AddCommand(pSics, argv[1], ScanWrapper, DeleteScanObject, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* + ignore this one, this is cheaper then checking for the existence + of another scan object + */ + AddCommand(pSics, "stdscan", StandardScanWrapper, NULL, NULL); + return 1; +} - if(iEvent == SCANSTART) - { - SCWrite(pCon,"NewScan",eLog); - return 1; - } - else if(iEvent == SCANEND) - { - SCWrite(pCon,"ScanEnd",eLog); - return 1; - } - else if(iEvent == SCANPOINT) - { - /* allocate space */ - lData = (long *)malloc(self->iNP*sizeof(long)); - iData = (int *)malloc(self->iNP*sizeof(int)); - if(!lData || !iData) - { - return 0; - } - memset(lData,0,self->iNP*sizeof(long)); - memset(iData,0,self->iNP*sizeof(int)); - - /* get counts */ - GetScanCounts(self,lData,self->iNP); - /* put into network byte order */ - for(i = 0; i < self->iNP; i++) - { - iData[i] = htonl((int)lData[i]); - } - SCWriteUUencoded(pCon,"ScanData",iData,self->iNP*sizeof(int)); - free(lData); - free(iData); - return 1; - } - return 1; - } /*--------------------------------------------------------------------------*/ -static int GetVarPar(SConnection *pCon, pScanData self, char *scanname, int i) +static int ScanInterest(int iEvent, void *pEventData, void *pUser) +{ + pScanData self = NULL; + SConnection *pCon = NULL; + char *pPtr = NULL, pItem[20]; + long *lData = NULL; + int i; + writeFunc oldWrite; + + self = (pScanData) pEventData; + pCon = (SConnection *) pUser; + + assert(self); + assert(pCon); + + if (!SCisConnected(pCon)) { + return -1; + } + + if (iEvent == SCANSTART) { + SCWrite(pCon, "NewScan", eLog); + return 1; + } else if (iEvent == SCANEND) { + SCWrite(pCon, "ScanEnd", eLog); + return 1; + } else if (iEvent == SCANPOINT) { + /* allocate space */ + pPtr = (char *) malloc((self->iNP * 20 + 20) * sizeof(char)); + if (!pPtr) { + return 0; + } + memset(pPtr, 0, (self->iNP * 20 + 20) * sizeof(char)); + lData = (long *) malloc(self->iNP * sizeof(long)); + if (!lData) { + return 0; + } + memset(lData, 0, self->iNP * sizeof(long)); + + /* get counts */ + GetScanCounts(self, lData, self->iNP); + /* format a message */ + + strcpy(pPtr, "scan.Counts= {"); + for (i = 0; i < self->iNP; i++) { + sprintf(pItem, "%ld ", lData[i]); + strcat(pPtr, pItem); + } + strcat(pPtr, "}"); + oldWrite = SCGetWriteFunc(pCon); + SCSetWriteFunc(pCon, SCOnlySockWrite); + SCWrite(pCon, pPtr, eLog); + SCSetWriteFunc(pCon, oldWrite); + free(lData); + free(pPtr); + return 1; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int ScanDynInterest(int iEvent, void *pEventData, void *pUser) +{ + pScanData self = NULL; + SConnection *pCon = NULL; + void *pPtr; + pVarEntry pVar; + pCountEntry pCount = NULL; + float fVal; + long lVal; + int i; + char pBueffel[256]; + + self = (pScanData) pEventData; + pCon = (SConnection *) pUser; + + assert(self); + assert(pCon); + + if (!SCisConnected(pCon)) { + return -1; + } + + if (iEvent == SCANSTART) { + SCWrite(pCon, "NewScan", eLog); + return 1; + } else if (iEvent == SCANEND) { + SCWrite(pCon, "ScanEnd", eLog); + return 1; + } else if (iEvent == SCANPOINT) { + i = self->iCounts - 1; + DynarGet(self->pScanVar, 0, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar != NULL) { + fVal = GetScanVarPos(pVar, i); + } else { + fVal = -9999.99; + } + DynarGet(self->pCounts, i, &pPtr); + pCount = (pCountEntry) pPtr; + if (pCount != NULL) { + lVal = pCount->lCount; + } else { + lVal = -9999.99; + } + snprintf(pBueffel, 255, "%s.scanpoint = {%d %f %ld}", + self->objectName, i, fVal, lVal); + SCWrite(pCon, pBueffel, eLog); + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int ScanUUInterest(int iEvent, void *pEventData, void *pUser) +{ + pScanData self = NULL; + SConnection *pCon = NULL, *comCon = NULL; + char pItem[20]; + long *lData = NULL; + int *iData = NULL; + int i; + + self = (pScanData) pEventData; + pCon = (SConnection *) pUser; + + assert(self); + assert(pCon); + /* + printf("ScanUUInterest called for pCon = %p handle %d\n", pCon, pCon->sockHandle); + */ + if (!SCisConnected(pCon)) { + return -1; + } + + if (iEvent == SCANSTART) { + SCWrite(pCon, "NewScan", eLog); + return 1; + } else if (iEvent == SCANEND) { + SCWrite(pCon, "ScanEnd", eLog); + return 1; + } else if (iEvent == SCANPOINT) { + /* allocate space */ + lData = (long *) malloc(self->iNP * sizeof(long)); + iData = (int *) malloc(self->iNP * sizeof(int)); + if (!lData || !iData) { + return 0; + } + memset(lData, 0, self->iNP * sizeof(long)); + memset(iData, 0, self->iNP * sizeof(int)); + + /* get counts */ + GetScanCounts(self, lData, self->iNP); + /* put into network byte order */ + for (i = 0; i < self->iNP; i++) { + iData[i] = htonl((int) lData[i]); + } + SCWriteUUencoded(pCon, "ScanData", iData, self->iNP * sizeof(int)); + free(lData); + free(iData); + return 1; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int GetVarPar(SConnection * pCon, pScanData self, char *scanname, + int i) { char pBueffel[512]; void *pPtr = NULL; - pVarEntry pVar = NULL; + pVarEntry pVar = NULL; assert(pCon); assert(self); - if(i < 0 || i >= self->iScanVar) - { - SCWrite(pCon,"ERROR: scan variable number out of range",eError); + if (i < 0 || i >= self->iScanVar) { + SCWrite(pCon, "ERROR: scan variable number out of range", eError); return 0; } - DynarGet(self->pScanVar,i,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar != NULL) - { - snprintf(pBueffel, 511,"%s.%s = %f = %f", - scanname, - ScanVarName(pVar), - ScanVarStart(pVar), - ScanVarStep(pVar)); - SCWrite(pCon,pBueffel,eValue); + DynarGet(self->pScanVar, i, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar != NULL) { + snprintf(pBueffel, 511, "%s.%s = %f = %f", + scanname, + ScanVarName(pVar), ScanVarStart(pVar), ScanVarStep(pVar)); + SCWrite(pCon, pBueffel, eValue); return 1; } return 0; } + /*--------------------------------------------------------------------------*/ -static int AppendVarPos(SConnection *pCon, pScanData self, - int scanVar, float fPos) +static int AppendVarPos(SConnection * pCon, pScanData self, + int scanVar, float fPos) { char pBueffel[512]; void *pPtr = NULL; - pVarEntry pVar = NULL; + pVarEntry pVar = NULL; assert(pCon); assert(self); - if(scanVar < 0 || scanVar >= self->iScanVar) - { - SCWrite(pCon,"ERROR: scan variable number out of range",eError); + if (scanVar < 0 || scanVar >= self->iScanVar) { + SCWrite(pCon, "ERROR: scan variable number out of range", eError); return 0; } - DynarGet(self->pScanVar,scanVar,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar != NULL) - { - AppendScanVar(pVar,fPos); + DynarGet(self->pScanVar, scanVar, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar != NULL) { + AppendScanVar(pVar, fPos); return 1; } return 0; -} +} + /*--------------------------------------------------------------------------*/ -static void PrintScanVars(pScanData self, char *scanname, SConnection *pCon){ +static void PrintScanVars(pScanData self, char *scanname, + SConnection * pCon) +{ char pBueffel[1024]; pVarEntry pVar = NULL; - void *pPtr = NULL; + void *pPtr = NULL; int i; assert(pCon); assert(self); - snprintf(pBueffel,1023,"%s.scanvars = { ", scanname); - for(i = 0; i < self->iScanVar; i++){ - DynarGet(self->pScanVar,i,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar != NULL){ - strncat(pBueffel,ScanVarName(pVar),1023-strlen(pBueffel)); - strcat(pBueffel," "); + snprintf(pBueffel, 1023, "%s.scanvars = { ", scanname); + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar != NULL) { + strncat(pBueffel, ScanVarName(pVar), 1023 - strlen(pBueffel)); + strcat(pBueffel, " "); } } - strcat(pBueffel,"}"); - SCWrite(pCon,pBueffel,eValue); + strcat(pBueffel, "}"); + SCWrite(pCon, pBueffel, eValue); } + /*--------------------------------------------------------------------------*/ -static int PrintCountsOrMonitors(pScanData self, SConnection *pCon, - char *name, int iWhich) +static int PrintCountsOrMonitors(pScanData self, SConnection * pCon, + char *name, int iWhich) { pDynString data = NULL; long *lData = NULL; char pBueffel[60]; int i; - - if(self->iNP < 1) - { - SCWrite(pCon,"ERROR: no scan data available",eError); + + if (self->iNP < 1) { + SCWrite(pCon, "ERROR: no scan data available", eError); return 0; } - data = CreateDynString(80,80); - lData = (long *)malloc(self->iNP*sizeof(long)); - if(data == NULL || lData == NULL) - { - SCWrite(pCon,"ERROR: out of memory printing counts",eError); + data = CreateDynString(80, 80); + lData = (long *) malloc(self->iNP * sizeof(long)); + if (data == NULL || lData == NULL) { + SCWrite(pCon, "ERROR: out of memory printing counts", eError); return 0; } - memset(lData,0,self->iNP*sizeof(long)); - - if(iWhich < 0) - { - GetScanCounts(self,lData,self->iNP); - snprintf(pBueffel,59,"%s.Counts = {", name); - } - else - { - GetScanMonitor(self,iWhich,lData,self->iNP); - snprintf(pBueffel,59,"%s.mon%2.2d = {", name, iWhich); + memset(lData, 0, self->iNP * sizeof(long)); + + if (iWhich < 0) { + GetScanCounts(self, lData, self->iNP); + snprintf(pBueffel, 59, "%s.Counts = {", name); + } else { + GetScanMonitor(self, iWhich, lData, self->iNP); + snprintf(pBueffel, 59, "%s.mon%2.2d = {", name, iWhich); } - DynStringCopy(data,pBueffel); - for(i = 0; i < self->iNP; i++) - { - snprintf(pBueffel,59," %ld", lData[i]); - DynStringConcat(data,pBueffel); + DynStringCopy(data, pBueffel); + for (i = 0; i < self->iNP; i++) { + snprintf(pBueffel, 59, " %ld", lData[i]); + DynStringConcat(data, pBueffel); } - DynStringConcatChar(data,'}'); - SCWrite(pCon,GetCharArray(data),eValue); + DynStringConcatChar(data, '}'); + SCWrite(pCon, GetCharArray(data), eValue); DeleteDynString(data); free(lData); return 1; } + /*--------------------------------------------------------------------------*/ -static int PrintTimes(pScanData self, SConnection *pCon, - char *name) +static int PrintTimes(pScanData self, SConnection * pCon, char *name) { pDynString data = NULL; char pBueffel[60]; int i, iEnd; pCountEntry pData = NULL; void *pPtr = NULL; - - if(self->iNP < 1) - { - SCWrite(pCon,"ERROR: no scan data available",eError); + + if (self->iNP < 1) { + SCWrite(pCon, "ERROR: no scan data available", eError); return 0; } - data = CreateDynString(80,80); - if(data == NULL) - { - SCWrite(pCon,"ERROR: out of memory printing counts",eError); + data = CreateDynString(80, 80); + if (data == NULL) { + SCWrite(pCon, "ERROR: out of memory printing counts", eError); return 0; } - snprintf(pBueffel,59,"%s.scantimes = { ",name); - DynStringCopy(data,pBueffel); - for(i = 0; i < self->iCounts; i++) - { - DynarGet(self->pCounts,i,&pPtr); - pData = (pCountEntry)pPtr; - if(pData) - { - snprintf(pBueffel,59," %f", pData->fTime); - DynStringConcat(data,pBueffel); - } + snprintf(pBueffel, 59, "%s.scantimes = { ", name); + DynStringCopy(data, pBueffel); + for (i = 0; i < self->iCounts; i++) { + DynarGet(self->pCounts, i, &pPtr); + pData = (pCountEntry) pPtr; + if (pData) { + snprintf(pBueffel, 59, " %f", pData->fTime); + DynStringConcat(data, pBueffel); + } } - DynStringConcatChar(data,'}'); - SCWrite(pCon,GetCharArray(data),eValue); + DynStringConcatChar(data, '}'); + SCWrite(pCon, GetCharArray(data), eValue); DeleteDynString(data); return 1; } + /*------------------------------------------------------------------------*/ -static int ScanInvokeCallback(pScanData self, SConnection *pCon, char *name) +static int ScanInvokeCallback(pScanData self, SConnection * pCon, + char *name) { int eventID; - if(strcmp(name,"scanstart") == 0){ + if (strcmp(name, "scanstart") == 0) { eventID = SCANSTART; - }else if(strcmp(name,"scanpoint") == 0){ + } else if (strcmp(name, "scanpoint") == 0) { eventID = SCANPOINT; - }else if(strcmp(name,"scanend") == 0){ + } else if (strcmp(name, "scanend") == 0) { eventID = SCANEND; } else { - SCWrite(pCon,"ERROR: callback ID not recognised",eError); + SCWrite(pCon, "ERROR: callback ID not recognised", eError); return 0; } - InvokeCallBack(self->pCall,eventID, self); + InvokeCallBack(self->pCall, eventID, self); SCSendOK(pCon); return 1; } + /*-----------------------------------------------------------------------*/ -static void ListScanFunctions(pScanData self, SConnection *pCon){ +static void ListScanFunctions(pScanData self, SConnection * pCon) +{ pDynString result = NULL; char pValue[256], *pPtr = NULL; - result = CreateDynString(80,80); - if(result == NULL){ - SCWrite(pCon,"ERROR: failed to allocate memory in function list",eError); + result = CreateDynString(80, 80); + if (result == NULL) { + SCWrite(pCon, "ERROR: failed to allocate memory in function list", + eError); return; } - while( (pPtr = (char *)StringDictGetNext(self->scanFunctions, - pValue,255)) != NULL){ + while ((pPtr = (char *) StringDictGetNext(self->scanFunctions, + pValue, 255)) != NULL) { DynStringConcat(result, pPtr); - DynStringConcat(result," = "); + DynStringConcat(result, " = "); DynStringConcat(result, pValue); DynStringConcatChar(result, '\n'); } - SCWrite(pCon,GetCharArray(result), eValue); + SCWrite(pCon, GetCharArray(result), eValue); DeleteDynString(result); } + /*-------------------------------------------------------------------------*/ -static int InterpretScanFunctions(pScanData self, SConnection *pCon, - int argc, char *argv[]){ +static int InterpretScanFunctions(pScanData self, SConnection * pCon, + int argc, char *argv[]) +{ char pValue[256]; char response[512]; - if(argc < 3){ - SCWrite(pCon,"ERROR: need subcommand to scan function",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: need subcommand to scan function", eError); return 0; } strtolower(argv[2]); - if(strcmp(argv[2],"list") == 0){ - ListScanFunctions(self,pCon); + if (strcmp(argv[2], "list") == 0) { + ListScanFunctions(self, pCon); return 1; } - if(argc > 3){ + if (argc > 3) { /* - set case - */ - Arg2Text(argc-3,&argv[3],pValue,255); - if(!StringDictUpdate(self->scanFunctions,argv[2],pValue)){ - snprintf(pValue,255,"ERROR: scan function %s not found",argv[2]); - SCWrite(pCon,pValue,eError); + set case + */ + Arg2Text(argc - 3, &argv[3], pValue, 255); + if (!StringDictUpdate(self->scanFunctions, argv[2], pValue)) { + snprintf(pValue, 255, "ERROR: scan function %s not found", argv[2]); + SCWrite(pCon, pValue, eError); return 0; } } /* - request case - */ - if(StringDictGet(self->scanFunctions,argv[2],pValue,255)){ - snprintf(response,511,"%s function %s = %s",argv[0],argv[2], - pValue); - SCWrite(pCon,response,eValue); + request case + */ + if (StringDictGet(self->scanFunctions, argv[2], pValue, 255)) { + snprintf(response, 511, "%s function %s = %s", argv[0], argv[2], + pValue); + SCWrite(pCon, response, eValue); return 1; } else { - snprintf(pValue,255,"ERROR: scan function %s not found",argv[2]); - SCWrite(pCon,pValue,eError); + snprintf(pValue, 255, "ERROR: scan function %s not found", argv[2]); + SCWrite(pCon, pValue, eError); return 0; } return 0; } + /*--------------------------------------------------------------------------*/ -static int DumpScan(pScanData self, SConnection *pCon) +static int DumpScan(pScanData self, SConnection * pCon) { - int i; - SConnection *oldCon; - char pFile[1024]; - - if(self->iActive) - { - SCWrite(pCon,"ERROR: cannot dump scan while running",eError); - return 0; - } - if(!self->pSics) - { - self->pSics = pServ->pSics; - } - /* - * save old file etc status - */ - oldCon = self->pCon; - pFile[0] = '\0'; - strncpy(pFile,self->pFile,1023); - prepareDataFile(self); - self->pCon = pCon; - self->WriteHeader(self); - for(i = 0; i < self->iNP; i++) - { - self->WriteScanPoints(self,i); - } - SCWrite(pCon,"Scan dumped", eValue); - self->pCon = oldCon; - strncpy(self->pFile,pFile,1023); - return 1; -} + int i; + SConnection *oldCon; + char pFile[1024]; + + if (self->iActive) { + SCWrite(pCon, "ERROR: cannot dump scan while running", eError); + return 0; + } + if (!self->pSics) { + self->pSics = pServ->pSics; + } + /* + * save old file etc status + */ + oldCon = self->pCon; + pFile[0] = '\0'; + strncpy(pFile, self->pFile, 1023); + prepareDataFile(self); + self->pCon = pCon; + self->WriteHeader(self); + for (i = 0; i < self->iNP; i++) { + self->WriteScanPoints(self, i); + } + SCWrite(pCon, "Scan dumped", eValue); + self->pCon = oldCon; + strncpy(self->pFile, pFile, 1023); + return 1; +} + /*---------------------------------------------------------------------------*/ - int ScanWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pScanData self = NULL; - char pBueffel[512]; - double fStep, fStart, fPreset; - float *fData = NULL; - int lNP; - int iChannel; - int iRet, iMode,i; - char *pPtr = NULL, pItem[20]; - long *lData = NULL, lID; - int *iData; - void *pVarData = NULL; - pVarEntry pVar = NULL; - float fSum, fVar; - double x; - float fPos, FWHM, fHeight; - pSite site = NULL; - SConnection *conSave; - - self = (pScanData)pData; - assert(self); - - argtolower(argc,argv); - if(argc < 2) - { - sprintf(pBueffel,"ERROR: not enough arguments for %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* - first interpret commands which do not require user rights - */ +int ScanWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pScanData self = NULL; + char pBueffel[512]; + double fStep, fStart, fPreset; + float *fData = NULL; + int lNP; + int iChannel; + int iRet, iMode, i; + char *pPtr = NULL, pItem[20]; + long *lData = NULL, lID; + int *iData; + void *pVarData = NULL; + pVarEntry pVar = NULL; + float fSum, fVar; + double x; + float fPos, FWHM, fHeight; + pSite site = NULL; + SConnection *conSave; + + self = (pScanData) pData; + assert(self); + + argtolower(argc, argv); + if (argc < 2) { + sprintf(pBueffel, "ERROR: not enough arguments for %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* + first interpret commands which do not require user rights + */ /*---------- getfile */ - if(strcmp(argv[1],"getfile") == 0) - { - sprintf(pBueffel,"scan.File = %s",self->pFile); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - if(strcmp(argv[1],"getscanvars") == 0) - { - PrintScanVars(self,argv[0],pCon); - return 1; - } + if (strcmp(argv[1], "getfile") == 0) { + sprintf(pBueffel, "scan.File = %s", self->pFile); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + if (strcmp(argv[1], "getscanvars") == 0) { + PrintScanVars(self, argv[0], pCon); + return 1; + } /*--------- getcounts */ - else if(strcmp(argv[1],"getcounts") == 0) - { - return PrintCountsOrMonitors(self,pCon,argv[0],-77); - } + else if (strcmp(argv[1], "getcounts") == 0) { + return PrintCountsOrMonitors(self, pCon, argv[0], -77); + } /*------------ getmonitor */ - else if(strcmp(argv[1],"getmonitor") == 0) - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: need monitor number to print",eError); - return 0; - } - iRet = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&i); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected integer, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return PrintCountsOrMonitors(self,pCon,argv[0],i); - } + else if (strcmp(argv[1], "getmonitor") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: need monitor number to print", eError); + return 0; + } + iRet = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &i); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected integer, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return PrintCountsOrMonitors(self, pCon, argv[0], i); + } /*--------- gettimes */ - else if(strcmp(argv[1],"gettimes") == 0) - { - return PrintTimes(self,pCon,argv[0]); - } + else if (strcmp(argv[1], "gettimes") == 0) { + return PrintTimes(self, pCon, argv[0]); + } /*---------- uucounts */ - else if(strcmp(argv[1],"uucounts") == 0) - { - /* get some memory */ - if(self->iNP < 1) - { - SCWrite(pCon,"ERROR: no counts available",eError); - return 0; - } - lData = (long *)malloc(self->iNP*sizeof(long)); - iData = (int *)malloc((self->iNP + 1)*sizeof(int)); - if(!lData || !iData ) - { - SCWrite(pCon,"ERROR: out of memory in scan",eError); - return 0; - } - - /* get counts */ - GetScanCounts(self,lData,self->iNP); - /* copy them */ - memset(iData,0,self->iNP+1); - iData[0] = htonl(self->iNP); - for(i = 0; i < self->iNP; i++) - { - iData[i+1] = htonl(lData[i]); - } - SCWriteUUencoded(pCon,"ScanCounts",iData, - (self->iNP + 1)*sizeof(int)); - return 1; - } -/*--------- noscanvar */ - else if(strcmp(argv[1],"noscanvar") == 0) - { - sprintf(pBueffel,"%s.noscanvar = %d",argv[0], - self->iScanVar); - SCWrite(pCon,pBueffel,eValue); - return 1; - } -/*-------- NP */ - else if(strcmp(argv[1],"np") == 0) - { - sprintf(pBueffel,"%s.nP = %d",argv[0], - self->iNP); - SCWrite(pCon,pBueffel,eValue); - return 1; - } -/*--------- getvardata */ - else if(strcmp(argv[1],"getvardata") == 0) - { - /* we need an integer parameter saying which */ - if(argc >= 3) - { - iRet = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&i); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected integer, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - else - { - SCWrite(pCon,"ERROR: expected number of variable to retrieve data for ", - eError); - return 0; - } - /* check the int for validity */ - if( (i < 0) || (i >= self->iScanVar)) - { - SCWrite(pCon,"ERROR: non existent scan variable requested!",eError); - return 0; - } - - /* get some memory */ - fData = (float *)malloc(self->iNP*sizeof(float)); - if(!fData) - { - SCWrite(pCon,"ERROR: out of memory in scan",eError); - return 0; - } - pPtr = (char *)malloc((self->iNP*20+20)*sizeof(char)); - if(!pPtr) - { - SCWrite(pCon,"ERROR: out of memory in scan",eError); - return 0; - } - memset(pPtr,0,(self->iNP*20+20)*sizeof(char)); - - /* get data */ - GetScanVar(self,i,fData,self->iNP); - - /* get name of ScanVar */ - DynarGet(self->pScanVar,i,&pVarData); - pVar = (pVarEntry)pVarData; - if(!pVar) - { - SCWrite(pCon,"ERROR: Corrupted data structures, inform Programmer", - eError); - return 0; - } - - /* format them */ - sprintf(pPtr,"scan.%s = ", ScanVarName(pVar)); - for(i = 0; i < self->iNP; i++) - { - sprintf(pItem,"{%12.3f} ",fData[i]); - strcat(pPtr,pItem); - } - SCWrite(pCon,pPtr,eValue); - free(fData); - free(pPtr); - return 1; - } -/*---------getvarpar */ - else if(strcmp(argv[1],"getvarpar") == 0) - { - /* we need an integer parameter saying which */ - if(argc >= 3) - { - iRet = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&i); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected integer, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - else - { - SCWrite(pCon,"ERROR: expected number of variable to retrieve data for ", - eError); - return 0; - } - return GetVarPar(pCon,self,argv[0],i); - } -/*-------- interest */ - else if(strcmp(argv[1],"interest") == 0) - { - /* - printf("Registering scan callbacks on handle %d\n", pCon->sockHandle); - */ - lID = RegisterCallback(self->pCall, SCANSTART, ScanInterest, - SCCopyConnection(pCon), SCDeleteConnection); - lID = RegisterCallback(self->pCall, SCANEND, ScanInterest, - SCCopyConnection(pCon),SCDeleteConnection); - lID = RegisterCallback(self->pCall, SCANPOINT, ScanInterest, - SCCopyConnection(pCon), SCDeleteConnection); - SCSendOK(pCon); - return 1; - } -/*-------- interest */ - else if(strcmp(argv[1],"dyninterest") == 0) - { - /* - printf("Registering scanDyn callbacks on handle %d\n", pCon->sockHandle); - */ - lID = RegisterCallback(self->pCall, SCANSTART, ScanDynInterest, - SCCopyConnection(pCon), SCDeleteConnection); - lID = RegisterCallback(self->pCall,SCANEND, ScanDynInterest, - SCCopyConnection(pCon), SCDeleteConnection); - lID = RegisterCallback(self->pCall, SCANPOINT, ScanDynInterest, - SCCopyConnection(pCon), SCDeleteConnection); - SCSendOK(pCon); - return 1; - } -/*-------- uuinterest */ - else if(strcmp(argv[1],"uuinterest") == 0) - { - /* - printf("Registering scanUU callbacks on handle %d, con = %p\n", - conSave->sockHandle, conSave); - */ - lID = RegisterCallback(self->pCall, SCANSTART, ScanUUInterest, - SCCopyConnection(pCon), SCDeleteConnection); - lID = RegisterCallback(self->pCall, SCANEND, ScanUUInterest, - SCCopyConnection(pCon),SCDeleteConnection); - lID = RegisterCallback(self->pCall, SCANPOINT, ScanUUInterest, - SCCopyConnection(pCon), SCDeleteConnection); - SCSendOK(pCon); - return 1; - } -/* ------- uninterest */ - else if(strcmp(argv[1],"uninterest") == 0) - { - RemoveCallbackCon(self->pCall,pCon); - SCSendOK(pCon); - return 1; - } + else if (strcmp(argv[1], "uucounts") == 0) { + /* get some memory */ + if (self->iNP < 1) { + SCWrite(pCon, "ERROR: no counts available", eError); + return 0; + } + lData = (long *) malloc(self->iNP * sizeof(long)); + iData = (int *) malloc((self->iNP + 1) * sizeof(int)); + if (!lData || !iData) { + SCWrite(pCon, "ERROR: out of memory in scan", eError); + return 0; + } -/*------- deal with command needing user rights in all cases */ - - /* check User Rights */ - if(!(SCMatchRights(pCon,usUser))) - { - SCWrite(pCon,"ERROR: You are NOT authorised to use scan",eError); - return 0; - } -/*---------- add command */ - if(strcmp(argv[1],"add") == 0) - { - if(argc < 5) - { - sprintf(pBueffel, - "ERROR: Insufficient number of arguments given for %s add", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* get numbers */ - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&fStart); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&fStep); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = AddScanVar(self,pSics,pCon,argv[2], - (float)fStart,(float)fStep); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - else if(strcmp(argv[1],"log") == 0) - { - if(argc < 3) - { - sprintf(pBueffel, - "ERROR: Insufficient number of arguments given for %s log", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = AddLogVar(self,pSics,pCon,argv[2]); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } -/* --------clear */ - else if(strcmp(argv[1],"clear") == 0) - { - iRet = ClearScanVar(self); - if(iRet) - { - SCSendOK(pCon); - } - else - { - SCWrite(pCon,"ERROR: cannot change parameters while scanning", - eError); - return 0; - } - return 1; - } -/*------------ dump */ - else if(strcmp(argv[1],"dump") == 0) - { - return DumpScan(self,pCon); - } -/* --------callback */ - else if(strcmp(argv[1],"callback") == 0) - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: need callback ID for invocation",eError); - return 0; - } - return ScanInvokeCallback(self,pCon,argv[2]); - } -/*------------ configure */ - else if(strcmp(argv[1],"configure") == 0) - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: missing configure option",eError); - return 0; - } - /* this is for users only */ - if(!SCMatchRights(pCon,usUser)) - return 0; - strtolower(argv[2]); - if(strcmp(argv[2],"standard") == 0) - { - ResetScanFunctions(self); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[2],"user") == 0) - { - ConfigureUserScan(self); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[2],"script") == 0) - { - ConfigureScript(self); - SCSendOK(pCon); - return 1; - } - else - { - site = getSite(); - if(site != NULL){ - iRet = site->ConfigureScan(self,argv[2]); - } - if(!iRet){ - sprintf(pBueffel,"ERROR: option %s not recognized by configure", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } else { - SCSendOK(pCon); - return 1; - } - } - } -/*------------ functions */ - else if(strcmp(argv[1],"function") == 0) - { - return InterpretScanFunctions(self, pCon, argc, argv); - } -/*---------- scan */ - else if(strcmp(argv[1],"run") == 0) - { - if (argc < 5) { - sprintf(pBueffel,"ERROR: not enough arguments for %s run",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* get NP */ - iRet = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&lNP); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* interpret Mode */ - if(strcmp(argv[3],"timer") == 0) - { - iMode = eTimer; - } - else if(strcmp(argv[3],"monitor") == 0) - { - iMode = ePreset; - } - else - { - sprintf(pBueffel,"ERROR: %s not recognized as valid counter mode", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* preset */ - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&fPreset); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = DoScan(self,(int)lNP,iMode,(float)fPreset, - pSics,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } -/*------------ continue */ - else if(strcmp(argv[1],"continue") == 0) - { - return ContinueScan(self,pSics,pCon,argc,argv); - } -/*---------- silent */ - else if(strcmp(argv[1],"silent") == 0) - { - if (argc < 5) { - sprintf(pBueffel,"ERROR: not enough arguments for %s silent",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* get NP */ - iRet = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&lNP); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* interpret Mode */ - if(strcmp(argv[3],"timer") == 0) - { - iMode = eTimer; - } - else if(strcmp(argv[3],"monitor") == 0) - { - iMode = ePreset; - } - else - { - sprintf(pBueffel,"ERROR: %s not recognized as valid counter mode", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* preset */ - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&fPreset); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = SilentScan(self,(int)lNP,iMode,(float)fPreset, - pSics,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } -/*----------- getnumchan */ - else if(strcmp(argv[1],"getnumchan") == 0) { - snprintf(pBueffel,511,"%s.getnumchan = %d", argv[0], GetNMonitor((pCounter)self->pCounterData)); - SCWrite(pCon,pBueffel,eValue); - } -/*----------- setchannel */ - else if(strcmp(argv[1],"setchannel") == 0) - { - if(argc < 3) - { - SCWrite(pCon,"ERROR: setchannel expects an integer argument",eError); - return 0; - } - /* convert to int */ - iRet = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&iChannel); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected integer, got %s", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if( ((iChannel < 0) && (iChannel != -10)) || - (iChannel >= GetNMonitor((pCounter)self->pCounterData)) ) - { - SCWrite(pCon,"ERROR: requested counter channel out of range ", - eError); - return 0; - } - self->iChannel = iChannel; - SCSendOK(pCon); - return 1; - } -/*--------- command */ - else if(strcmp(argv[1],"command") == 0) - { - /* inquire */ - if(argc < 3) - { - sprintf(pBueffel,"%s.command = %s",argv[0], - self->pCommand); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - /* set case */ - Arg2Text(argc-2,&argv[2],pBueffel,511); - if(self->pCommand) - free(self->pCommand); - self->pCommand = strdup(pBueffel); - SCSendOK(pCon); - return 1; - } -/*--------- integration window */ - else if(strcmp(argv[1],"window") == 0) - { - if(argc > 2) - { - /* set value */ - iRet = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&iChannel); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(iChannel < 0) - { - SCWrite(pCon,"ERROR: new integration window size out of range", - eError); - return 0; - } - self->iWindow = iChannel; - SCSendOK(pCon); - return 1; - } - else - { - /* request the value */ - sprintf(pBueffel,"Integration Window = %d",self->iWindow); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } -/*------------- integrate */ - else if(strcmp(argv[1],"integrate") == 0) - { - iRet = ScanIntegrate(self,&fSum,&fVar); - switch(iRet) - { - case INTEGLEFT: - SCWrite(pCon,"ERROR: no left limit found for peak",eError); - return 0; - break; - case INTEGRIGHT: - SCWrite(pCon,"ERROR: no right limit found for peak",eError); - return 0; - break; - case INTEGNOPEAK: - SCWrite(pCon,"ERROR: no data found for peak",eError); - return 0; - break; - case INTEGFUNNYBACK: - SCWrite(pCon,"WARNING: background asymmetric or worse",eWarning); - default: - sprintf(pBueffel,"Intensity = %f, Variance = %f",fSum,fVar); - SCWrite(pCon,pBueffel,eValue); - return 1; - break; - } - } -/*---------- simscan */ - else if(strcmp(argv[1],"simscan") == 0) - { - if(argc < 5) - { - SCWrite(pCon,"ERROR expected fPos FWHM Height parameters",eError); - return 0; - } - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[2],&x); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fPos = x; - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&x); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - FWHM = x; - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&x); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fHeight = x; - iRet = SimScan(self,fPos,FWHM,fHeight); - if(!iRet) - { - SCWrite(pCon,"ERROR: cannot create simulated scan data",eError); - return 0; - } - SCSendOK(pCon); - return 1; - } -/*----------------- line */ - else if(strcmp(argv[1],"line") == 0) - { - Arg2Text(argc-2,&argv[2],pBueffel,511); - return AppendScanLine(self,pBueffel); - } -/*----------------- storecounts */ - else if(strcmp(argv[1],"storecounts") == 0) - { - Arg2Text(argc-2,&argv[2],pBueffel,511); - return StoreScanCounts(self,pBueffel); - } -/*----------------- appendvarpos */ - else if(strcmp(argv[1],"appendvarpos") == 0) - { - if(argc < 4) - { - SCWrite(pCon, - "ERROR: insufficient number of arguments to appendvarpos", - eError); - return 0; - } - iRet = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&i); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&fStep); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return AppendVarPos(pCon,self,i,(float)fStep); - } -/*------- savecounter */ - else if(strcmp(argv[1],"savecounter") == 0) - { - conSave = self->pCon; - self->pCon = pCon; - CollectCounterData(self); - self->pCon = conSave; - if(SCGetInterrupt(pCon) >= eAbortScan){ - return 0; - } - } - else - { - sprintf(pBueffel,"ERROR: %s not recognized as subcommand to %s", - argv[1], argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } + /* get counts */ + GetScanCounts(self, lData, self->iNP); + /* copy them */ + memset(iData, 0, self->iNP + 1); + iData[0] = htonl(self->iNP); + for (i = 0; i < self->iNP; i++) { + iData[i + 1] = htonl(lData[i]); + } + SCWriteUUencoded(pCon, "ScanCounts", iData, + (self->iNP + 1) * sizeof(int)); + return 1; + } +/*--------- noscanvar */ + else if (strcmp(argv[1], "noscanvar") == 0) { + sprintf(pBueffel, "%s.noscanvar = %d", argv[0], self->iScanVar); + SCWrite(pCon, pBueffel, eValue); + return 1; + } +/*-------- NP */ + else if (strcmp(argv[1], "np") == 0) { + sprintf(pBueffel, "%s.nP = %d", argv[0], self->iNP); + SCWrite(pCon, pBueffel, eValue); + return 1; + } +/*--------- getvardata */ + else if (strcmp(argv[1], "getvardata") == 0) { + /* we need an integer parameter saying which */ + if (argc >= 3) { + iRet = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &i); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected integer, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } else { + SCWrite(pCon, + "ERROR: expected number of variable to retrieve data for ", + eError); + return 0; + } + /* check the int for validity */ + if ((i < 0) || (i >= self->iScanVar)) { + SCWrite(pCon, "ERROR: non existent scan variable requested!", + eError); + return 0; + } + + /* get some memory */ + fData = (float *) malloc(self->iNP * sizeof(float)); + if (!fData) { + SCWrite(pCon, "ERROR: out of memory in scan", eError); + return 0; + } + pPtr = (char *) malloc((self->iNP * 20 + 20) * sizeof(char)); + if (!pPtr) { + SCWrite(pCon, "ERROR: out of memory in scan", eError); + return 0; + } + memset(pPtr, 0, (self->iNP * 20 + 20) * sizeof(char)); + + /* get data */ + GetScanVar(self, i, fData, self->iNP); + + /* get name of ScanVar */ + DynarGet(self->pScanVar, i, &pVarData); + pVar = (pVarEntry) pVarData; + if (!pVar) { + SCWrite(pCon, "ERROR: Corrupted data structures, inform Programmer", + eError); + return 0; + } + + /* format them */ + sprintf(pPtr, "scan.%s = ", ScanVarName(pVar)); + for (i = 0; i < self->iNP; i++) { + sprintf(pItem, "{%12.3f} ", fData[i]); + strcat(pPtr, pItem); + } + SCWrite(pCon, pPtr, eValue); + free(fData); + free(pPtr); + return 1; + } +/*---------getvarpar */ + else if (strcmp(argv[1], "getvarpar") == 0) { + /* we need an integer parameter saying which */ + if (argc >= 3) { + iRet = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &i); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected integer, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } else { + SCWrite(pCon, + "ERROR: expected number of variable to retrieve data for ", + eError); + return 0; + } + return GetVarPar(pCon, self, argv[0], i); + } +/*-------- interest */ + else if (strcmp(argv[1], "interest") == 0) { + /* + printf("Registering scan callbacks on handle %d\n", pCon->sockHandle); + */ + lID = RegisterCallback(self->pCall, SCANSTART, ScanInterest, + SCCopyConnection(pCon), SCDeleteConnection); + lID = RegisterCallback(self->pCall, SCANEND, ScanInterest, + SCCopyConnection(pCon), SCDeleteConnection); + lID = RegisterCallback(self->pCall, SCANPOINT, ScanInterest, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + } +/*-------- interest */ + else if (strcmp(argv[1], "dyninterest") == 0) { + /* + printf("Registering scanDyn callbacks on handle %d\n", pCon->sockHandle); + */ + lID = RegisterCallback(self->pCall, SCANSTART, ScanDynInterest, + SCCopyConnection(pCon), SCDeleteConnection); + lID = RegisterCallback(self->pCall, SCANEND, ScanDynInterest, + SCCopyConnection(pCon), SCDeleteConnection); + lID = RegisterCallback(self->pCall, SCANPOINT, ScanDynInterest, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + } +/*-------- uuinterest */ + else if (strcmp(argv[1], "uuinterest") == 0) { + /* + printf("Registering scanUU callbacks on handle %d, con = %p\n", + conSave->sockHandle, conSave); + */ + lID = RegisterCallback(self->pCall, SCANSTART, ScanUUInterest, + SCCopyConnection(pCon), SCDeleteConnection); + lID = RegisterCallback(self->pCall, SCANEND, ScanUUInterest, + SCCopyConnection(pCon), SCDeleteConnection); + lID = RegisterCallback(self->pCall, SCANPOINT, ScanUUInterest, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + } +/* ------- uninterest */ + else if (strcmp(argv[1], "uninterest") == 0) { + RemoveCallbackCon(self->pCall, pCon); + SCSendOK(pCon); + return 1; + } + +/*------- deal with command needing user rights in all cases */ + + /* check User Rights */ + if (!(SCMatchRights(pCon, usUser))) { + SCWrite(pCon, "ERROR: You are NOT authorised to use scan", eError); return 0; - } + } +/*---------- add command */ + if (strcmp(argv[1], "add") == 0) { + if (argc < 5) { + sprintf(pBueffel, + "ERROR: Insufficient number of arguments given for %s add", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* get numbers */ + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &fStart); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &fStep); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = AddScanVar(self, pSics, pCon, argv[2], + (float) fStart, (float) fStep); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } else if (strcmp(argv[1], "log") == 0) { + if (argc < 3) { + sprintf(pBueffel, + "ERROR: Insufficient number of arguments given for %s log", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = AddLogVar(self, pSics, pCon, argv[2]); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } +/* --------clear */ + else if (strcmp(argv[1], "clear") == 0) { + iRet = ClearScanVar(self); + if (iRet) { + SCSendOK(pCon); + } else { + SCWrite(pCon, "ERROR: cannot change parameters while scanning", + eError); + return 0; + } + return 1; + } +/*------------ dump */ + else if (strcmp(argv[1], "dump") == 0) { + return DumpScan(self, pCon); + } +/* --------callback */ + else if (strcmp(argv[1], "callback") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: need callback ID for invocation", eError); + return 0; + } + return ScanInvokeCallback(self, pCon, argv[2]); + } +/*------------ configure */ + else if (strcmp(argv[1], "configure") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: missing configure option", eError); + return 0; + } + /* this is for users only */ + if (!SCMatchRights(pCon, usUser)) + return 0; + strtolower(argv[2]); + if (strcmp(argv[2], "standard") == 0) { + ResetScanFunctions(self); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[2], "user") == 0) { + ConfigureUserScan(self); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[2], "script") == 0) { + ConfigureScript(self); + SCSendOK(pCon); + return 1; + } else { + site = getSite(); + if (site != NULL) { + iRet = site->ConfigureScan(self, argv[2]); + } + if (!iRet) { + sprintf(pBueffel, "ERROR: option %s not recognized by configure", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } else { + SCSendOK(pCon); + return 1; + } + } + } +/*------------ functions */ + else if (strcmp(argv[1], "function") == 0) { + return InterpretScanFunctions(self, pCon, argc, argv); + } +/*---------- scan */ + else if (strcmp(argv[1], "run") == 0) { + if (argc < 5) { + sprintf(pBueffel, "ERROR: not enough arguments for %s run", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* get NP */ + iRet = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &lNP); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* interpret Mode */ + if (strcmp(argv[3], "timer") == 0) { + iMode = eTimer; + } else if (strcmp(argv[3], "monitor") == 0) { + iMode = ePreset; + } else { + sprintf(pBueffel, "ERROR: %s not recognized as valid counter mode", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* preset */ + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &fPreset); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = DoScan(self, (int) lNP, iMode, (float) fPreset, pSics, pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } +/*------------ continue */ + else if (strcmp(argv[1], "continue") == 0) { + return ContinueScan(self, pSics, pCon, argc, argv); + } +/*---------- silent */ + else if (strcmp(argv[1], "silent") == 0) { + if (argc < 5) { + sprintf(pBueffel, "ERROR: not enough arguments for %s silent", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* get NP */ + iRet = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &lNP); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* interpret Mode */ + if (strcmp(argv[3], "timer") == 0) { + iMode = eTimer; + } else if (strcmp(argv[3], "monitor") == 0) { + iMode = ePreset; + } else { + sprintf(pBueffel, "ERROR: %s not recognized as valid counter mode", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* preset */ + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &fPreset); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = SilentScan(self, (int) lNP, iMode, (float) fPreset, + pSics, pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } +/*----------- getnumchan */ + else if (strcmp(argv[1], "getnumchan") == 0) { + snprintf(pBueffel, 511, "%s.getnumchan = %d", argv[0], + GetNMonitor((pCounter) self->pCounterData)); + SCWrite(pCon, pBueffel, eValue); + } +/*----------- setchannel */ + else if (strcmp(argv[1], "setchannel") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: setchannel expects an integer argument", + eError); + return 0; + } + /* convert to int */ + iRet = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &iChannel); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected integer, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (((iChannel < 0) && (iChannel != -10)) || + (iChannel >= GetNMonitor((pCounter) self->pCounterData))) { + SCWrite(pCon, "ERROR: requested counter channel out of range ", + eError); + return 0; + } + self->iChannel = iChannel; + SCSendOK(pCon); + return 1; + } +/*--------- command */ + else if (strcmp(argv[1], "command") == 0) { + /* inquire */ + if (argc < 3) { + sprintf(pBueffel, "%s.command = %s", argv[0], self->pCommand); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + /* set case */ + Arg2Text(argc - 2, &argv[2], pBueffel, 511); + if (self->pCommand) + free(self->pCommand); + self->pCommand = strdup(pBueffel); + SCSendOK(pCon); + return 1; + } +/*--------- integration window */ + else if (strcmp(argv[1], "window") == 0) { + if (argc > 2) { + /* set value */ + iRet = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &iChannel); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (iChannel < 0) { + SCWrite(pCon, "ERROR: new integration window size out of range", + eError); + return 0; + } + self->iWindow = iChannel; + SCSendOK(pCon); + return 1; + } else { + /* request the value */ + sprintf(pBueffel, "Integration Window = %d", self->iWindow); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } +/*------------- integrate */ + else if (strcmp(argv[1], "integrate") == 0) { + iRet = ScanIntegrate(self, &fSum, &fVar); + switch (iRet) { + case INTEGLEFT: + SCWrite(pCon, "ERROR: no left limit found for peak", eError); + return 0; + break; + case INTEGRIGHT: + SCWrite(pCon, "ERROR: no right limit found for peak", eError); + return 0; + break; + case INTEGNOPEAK: + SCWrite(pCon, "ERROR: no data found for peak", eError); + return 0; + break; + case INTEGFUNNYBACK: + SCWrite(pCon, "WARNING: background asymmetric or worse", eWarning); + default: + sprintf(pBueffel, "Intensity = %f, Variance = %f", fSum, fVar); + SCWrite(pCon, pBueffel, eValue); + return 1; + break; + } + } +/*---------- simscan */ + else if (strcmp(argv[1], "simscan") == 0) { + if (argc < 5) { + SCWrite(pCon, "ERROR expected fPos FWHM Height parameters", eError); + return 0; + } + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], &x); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fPos = x; + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &x); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + FWHM = x; + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &x); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fHeight = x; + iRet = SimScan(self, fPos, FWHM, fHeight); + if (!iRet) { + SCWrite(pCon, "ERROR: cannot create simulated scan data", eError); + return 0; + } + SCSendOK(pCon); + return 1; + } +/*----------------- line */ + else if (strcmp(argv[1], "line") == 0) { + Arg2Text(argc - 2, &argv[2], pBueffel, 511); + return AppendScanLine(self, pBueffel); + } +/*----------------- storecounts */ + else if (strcmp(argv[1], "storecounts") == 0) { + Arg2Text(argc - 2, &argv[2], pBueffel, 511); + return StoreScanCounts(self, pBueffel); + } +/*----------------- appendvarpos */ + else if (strcmp(argv[1], "appendvarpos") == 0) { + if (argc < 4) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to appendvarpos", + eError); + return 0; + } + iRet = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &i); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &fStep); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return AppendVarPos(pCon, self, i, (float) fStep); + } +/*------- savecounter */ + else if (strcmp(argv[1], "savecounter") == 0) { + conSave = self->pCon; + self->pCon = pCon; + CollectCounterData(self); + self->pCon = conSave; + if (SCGetInterrupt(pCon) >= eAbortScan) { + return 0; + } + } else { + sprintf(pBueffel, "ERROR: %s not recognized as subcommand to %s", + argv[1], argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 0; +} diff --git a/scan.h b/scan.h index 09ad15b7..f9e2ca2e 100644 --- a/scan.h +++ b/scan.h @@ -12,71 +12,68 @@ -----------------------------------------------------------------------------*/ #ifndef SICSSCAN1 #define SICSSCAN1 - typedef struct __ScanData *pScanData; +typedef struct __ScanData *pScanData; /*--------------------------------------------------------------------------*/ #include "counter.h" /*------------------------- live & death ----------------------------------*/ - pScanData CreateScanObject(char *pRecover, char *pHeader, - pCounter pCount, char *objName); - void DeleteScanObject(void *self); +pScanData CreateScanObject(char *pRecover, char *pHeader, + pCounter pCount, char *objName); +void DeleteScanObject(void *self); /*-------------------------------------------------------------------------*/ - int AddScanVar(pScanData self, SicsInterp *pSics, SConnection *pCon, - char *name, float fStart, float fStep); - int ClearScanVar(pScanData self); - - int DoScan(pScanData self, int iNP, int iMode, float fPreset, - SicsInterp *pSics, SConnection *pCon); - int SilentScan(pScanData self, int iNP, int iMode, float fPreset, - SicsInterp *pSics, SConnection *pCon); - int RecoverScan(pScanData self, SicsInterp *pSics, SConnection *pCon); - - int GetScanCounts(pScanData self, long *lData, int iDataLen); - int GetScanVar(pScanData self, int iWhich, float *fData, int iDataLen); - int GetSoftScanVar(pScanData self, int iWhich, float *fData, int iDataLen); +int AddScanVar(pScanData self, SicsInterp * pSics, SConnection * pCon, + char *name, float fStart, float fStep); +int ClearScanVar(pScanData self); - int GetScanVarName(pScanData self, int iWhich, - char *pName, int iLength); - int GetScanVarStep(pScanData self, int iWhich, - float *fStep); - int GetScanMonitor(pScanData self, int iWhich, - long *lData, int iDataLen); - int GetScanNP(pScanData self); - float GetScanPreset(pScanData self); - - int ScanIntegrate(pScanData self, float *fSum, float *fVariance); - - int SimScan(pScanData self, float fPos, float FHWM, float fHeight); +int DoScan(pScanData self, int iNP, int iMode, float fPreset, + SicsInterp * pSics, SConnection * pCon); +int SilentScan(pScanData self, int iNP, int iMode, float fPreset, + SicsInterp * pSics, SConnection * pCon); +int RecoverScan(pScanData self, SicsInterp * pSics, SConnection * pCon); + +int GetScanCounts(pScanData self, long *lData, int iDataLen); +int GetScanVar(pScanData self, int iWhich, float *fData, int iDataLen); +int GetSoftScanVar(pScanData self, int iWhich, float *fData, int iDataLen); + +int GetScanVarName(pScanData self, int iWhich, char *pName, int iLength); +int GetScanVarStep(pScanData self, int iWhich, float *fStep); +int GetScanMonitor(pScanData self, int iWhich, long *lData, int iDataLen); +int GetScanNP(pScanData self); +float GetScanPreset(pScanData self); + +int ScanIntegrate(pScanData self, float *fSum, float *fVariance); + +int SimScan(pScanData self, float fPos, float FHWM, float fHeight); /* creates a simulated gaussian shaped peak with the parameters given. - */ - int ResetScanFunctions(pScanData self); + */ +int ResetScanFunctions(pScanData self); /* resets the configurable scan functions to their default values. - */ - int NonCheckPrepare(pScanData self); + */ +int NonCheckPrepare(pScanData self); /* - a function for the PrepareScan field in the scan data structure - which does not check the boundaries of the scan as the default - PrepareScan does. - */ - int AppendScanLine(pScanData self, char *line); + a function for the PrepareScan field in the scan data structure + which does not check the boundaries of the scan as the default + PrepareScan does. + */ +int AppendScanLine(pScanData self, char *line); /* - AppendScanLine appends a line to the scan data file. When finished - it updates the position pointer in the file to point behind the - added line. - */ - int StoreScanCounts(pScanData self, char *data); + AppendScanLine appends a line to the scan data file. When finished + it updates the position pointer in the file to point behind the + added line. + */ +int StoreScanCounts(pScanData self, char *data); /* - parses the numbers in data and stores them as the count and - monitor data for the current scan point. - */ + parses the numbers in data and stores them as the count and + monitor data for the current scan point. + */ /*------------------------ Interpreter Interface --------------------------*/ - int ScanFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int ScanFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - int ScanWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int ScanWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/scanvar.c b/scanvar.c index 800c2a6a..5bc0720c 100644 --- a/scanvar.c +++ b/scanvar.c @@ -16,96 +16,104 @@ #include "lld.h" #include "devexec.h" /*----------------------------------------------------------------------*/ -pVarEntry MakeScanVar(SicsInterp *pSics, SConnection *pCon, char - *name, float start, float step){ +pVarEntry MakeScanVar(SicsInterp * pSics, SConnection * pCon, char + *name, float start, float step) +{ CommandList *pCom = NULL; - pIDrivable pDriv = NULL; - pDummy pData = NULL; - pVarEntry pVar = NULL; + pIDrivable pDriv = NULL; + pDummy pData = NULL; + pVarEntry pVar = NULL; char pBueffel[512]; /* - allocate space - */ - pVar = (pVarEntry)malloc(sizeof(VarEntry)); - if(pVar == NULL){ - SCWrite(pCon,"ERROR: out of memory allocating scan variable",eError); + allocate space + */ + pVar = (pVarEntry) malloc(sizeof(VarEntry)); + if (pVar == NULL) { + SCWrite(pCon, "ERROR: out of memory allocating scan variable", eError); return NULL; } - memset(pVar,0,sizeof(VarEntry)); + memset(pVar, 0, sizeof(VarEntry)); /* find the thing */ - pCom = FindCommand(pSics,name); - if(!pCom){ - snprintf(pBueffel,511,"ERROR: Cannot find variable %s to scan",name); - SCWrite(pCon,pBueffel,eError); + pCom = FindCommand(pSics, name); + if (!pCom) { + snprintf(pBueffel, 511, "ERROR: Cannot find variable %s to scan", + name); + SCWrite(pCon, pBueffel, eError); return NULL; } - pData = (pDummy)pCom->pData; - if(!pData){ - snprintf(pBueffel,511,"ERROR: Cannot find data for variable %s",name); - SCWrite(pCon,pBueffel,eError); + pData = (pDummy) pCom->pData; + if (!pData) { + snprintf(pBueffel, 511, "ERROR: Cannot find data for variable %s", + name); + SCWrite(pCon, pBueffel, eError); return NULL; } - pDriv = pData->pDescriptor->GetInterface(pData,DRIVEID); - if(!pDriv){ - snprintf(pBueffel,511, - "ERROR: variable %s is NOT driveable and cannot be scanned",name); - SCWrite(pCon,pBueffel,eError); - return NULL; + pDriv = pData->pDescriptor->GetInterface(pData, DRIVEID); + if (!pDriv) { + snprintf(pBueffel, 511, + "ERROR: variable %s is NOT driveable and cannot be scanned", + name); + SCWrite(pCon, pBueffel, eError); + return NULL; } /* got everything, fill in the VarEntry structure */ - strcpy(pVar->Name,name); + strcpy(pVar->Name, name); pVar->pInter = pDriv; pVar->pObject = pData; pVar->fStart = start; - pVar->fStep = step; + pVar->fStep = step; pVar->dataList = LLDcreate(sizeof(float)); return pVar; } + /*----------------------------------------------------------------------*/ -pVarEntry MakeLogVar(SicsInterp *pSics, SConnection *pCon, char *name){ +pVarEntry MakeLogVar(SicsInterp * pSics, SConnection * pCon, char *name) +{ CommandList *pCom = NULL; - pIDrivable pDriv = NULL; - pDummy pData = NULL; - pVarEntry pVar = NULL; + pIDrivable pDriv = NULL; + pDummy pData = NULL; + pVarEntry pVar = NULL; char pBueffel[512]; /* - allocate space - */ - pVar = (pVarEntry)malloc(sizeof(VarEntry)); - if(pVar == NULL){ - SCWrite(pCon,"ERROR: out of memory allocating scan variable",eError); + allocate space + */ + pVar = (pVarEntry) malloc(sizeof(VarEntry)); + if (pVar == NULL) { + SCWrite(pCon, "ERROR: out of memory allocating scan variable", eError); return NULL; } - memset(pVar,0,sizeof(VarEntry)); + memset(pVar, 0, sizeof(VarEntry)); /* find the thing */ - pCom = FindCommand(pSics,name); - if(!pCom){ - snprintf(pBueffel,511,"ERROR: Cannot find variable %s to log",name); - SCWrite(pCon,pBueffel,eError); + pCom = FindCommand(pSics, name); + if (!pCom) { + snprintf(pBueffel, 511, "ERROR: Cannot find variable %s to log", name); + SCWrite(pCon, pBueffel, eError); return NULL; } - pData = (pDummy)pCom->pData; - if(!pData){ - snprintf(pBueffel,511,"ERROR: Cannot find data for variable %s",name); - SCWrite(pCon,pBueffel,eError); + pData = (pDummy) pCom->pData; + if (!pData) { + snprintf(pBueffel, 511, "ERROR: Cannot find data for variable %s", + name); + SCWrite(pCon, pBueffel, eError); return NULL; } - pDriv = pData->pDescriptor->GetInterface(pData,DRIVEID); - if(!pDriv){ - snprintf(pBueffel,511, - "ERROR: variable %s is NOT driveable and cannot be logged",name); - SCWrite(pCon,pBueffel,eError); - return NULL; + pDriv = pData->pDescriptor->GetInterface(pData, DRIVEID); + if (!pDriv) { + snprintf(pBueffel, 511, + "ERROR: variable %s is NOT driveable and cannot be logged", + name); + SCWrite(pCon, pBueffel, eError); + return NULL; } /* got everything, fill in the VarEntry structure */ - strcpy(pVar->Name,name); + strcpy(pVar->Name, name); pVar->pInter = pDriv; pVar->pObject = pData; pVar->logVar = 1; @@ -115,40 +123,51 @@ pVarEntry MakeLogVar(SicsInterp *pSics, SConnection *pCon, char *name){ } /*------------------------------------------------------------------*/ -void InitScanVar(pVarEntry pVar){ +void InitScanVar(pVarEntry pVar) +{ LLDdelete(pVar->dataList); pVar->dataList = LLDcreate(sizeof(float)); } + /*--------------------------------------------------------------------*/ -void DeleteVarEntry(void *pData){ +void DeleteVarEntry(void *pData) +{ pVarEntry pVar = NULL; - - pVar = (pVarEntry)pData; - - if(pVar == NULL){ + + pVar = (pVarEntry) pData; + + if (pVar == NULL) { return; } - - if(pVar->fData){ + + if (pVar->fData) { free(pVar->fData); } LLDdelete(pVar->dataList); free(pVar); } + /*------------------------------------------------------------------------*/ -char *ScanVarName(pVarEntry pVar){ +char *ScanVarName(pVarEntry pVar) +{ return pVar->Name; } + /*------------------------------------------------------------------------*/ -float ScanVarStart(pVarEntry pVar){ +float ScanVarStart(pVarEntry pVar) +{ return pVar->fStart; } + /*-------------------------------------------------------------------------*/ -float ScanVarStep(pVarEntry pVar){ +float ScanVarStep(pVarEntry pVar) +{ return pVar->fStep; } + /*------------------------------------------------------------------------*/ -int StartScanVar(pVarEntry pVar, SConnection *pCon, int i){ +int StartScanVar(pVarEntry pVar, SConnection * pCon, int i) +{ float fVal; pDummy pDum; char pBueffel[512]; @@ -157,84 +176,90 @@ int StartScanVar(pVarEntry pVar, SConnection *pCon, int i){ /** * logged variables are not started */ - if(pVar->logVar == 1){ + if (pVar->logVar == 1) { return 1; } - pDum = (pDummy)pVar->pObject; - fVal = pVar->fStart + i * pVar->fStep; - status = StartDevice(pServ->pExecutor, - pVar->Name, - pDum->pDescriptor, - pVar->pObject, - pCon, - fVal); - if(!status){ - snprintf(pBueffel,511,"ERROR: Failed to start %s",pVar->Name); - SCWrite(pCon,pBueffel,eError); + pDum = (pDummy) pVar->pObject; + fVal = pVar->fStart + i * pVar->fStep; + status = StartDevice(pServ->pExecutor, + pVar->Name, + pDum->pDescriptor, pVar->pObject, pCon, fVal); + if (!status) { + snprintf(pBueffel, 511, "ERROR: Failed to start %s", pVar->Name); + SCWrite(pCon, pBueffel, eError); return 0; - } + } return 1; } -/*-------------------------------------------------------------------------*/ -int CheckScanVar(pVarEntry pVar, SConnection *pCon, int np){ - int status; - char pError[132], pBueffel[512]; - if(pVar->logVar == 1){ - return 1; - } - - status = pVar->pInter->CheckLimits(pVar->pObject, - pVar->fStart,pError,131); - if(status != 1){ - snprintf(pBueffel,511,"ERROR: %s, scan aborted",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - status = pVar->pInter->CheckLimits(pVar->pObject, - pVar->fStart + np * pVar->fStep, - pError,131); - if(status != 1){ - snprintf(pBueffel,511,"ERROR: %s, scan aborted",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; -} /*-------------------------------------------------------------------------*/ -void AppendScanVar(pVarEntry pVar, float pos){ - float fVal = pos; - LLDnodeAppendFrom(pVar->dataList,&fVal); +int CheckScanVar(pVarEntry pVar, SConnection * pCon, int np) +{ + int status; + char pError[132], pBueffel[512]; + + if (pVar->logVar == 1) { + return 1; + } + + status = pVar->pInter->CheckLimits(pVar->pObject, + pVar->fStart, pError, 131); + if (status != 1) { + snprintf(pBueffel, 511, "ERROR: %s, scan aborted", pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + status = pVar->pInter->CheckLimits(pVar->pObject, + pVar->fStart + np * pVar->fStep, + pError, 131); + if (status != 1) { + snprintf(pBueffel, 511, "ERROR: %s, scan aborted", pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; } + +/*-------------------------------------------------------------------------*/ +void AppendScanVar(pVarEntry pVar, float pos) +{ + float fVal = pos; + LLDnodeAppendFrom(pVar->dataList, &fVal); +} + /*------------------------------------------------------------------------*/ -float GetScanVarPos(pVarEntry pVar, int i){ +float GetScanVarPos(pVarEntry pVar, int i) +{ int count = 0, status; status = LLDnodePtr2First(pVar->dataList); - while(count < i && (status = LLDnodePtr2Next(pVar->dataList)) != 0){ + while (count < i && (status = LLDnodePtr2Next(pVar->dataList)) != 0) { count++; } - if(count == i){ + if (count == i) { return LLDnodeFloat(pVar->dataList); } else { return -99999.99; } } + /*------------------------------------------------------------------------*/ -void CopyScanVar(pVarEntry pVar, float *fData, int np){ +void CopyScanVar(pVarEntry pVar, float *fData, int np) +{ int i, count = 0, status; status = LLDnodePtr2First(pVar->dataList); - while(status > 0 && count < np){ + while (status > 0 && count < np) { fData[count] = LLDnodeFloat(pVar->dataList); count++; status = LLDnodePtr2Next(pVar->dataList); } } -/*-------------------------------------------------------------------------*/ -int isLogVar(pVarEntry pVar){ - return pVar->logVar; -} +/*-------------------------------------------------------------------------*/ +int isLogVar(pVarEntry pVar) +{ + return pVar->logVar; +} diff --git a/scanvar.h b/scanvar.h index e73c5080..99f6e40c 100644 --- a/scanvar.h +++ b/scanvar.h @@ -13,16 +13,16 @@ #define SICSSCANVAR #include "sics.h" - typedef struct { - char Name[132]; - pIDrivable pInter; - pDummy pObject; - float fStart; - float fStep; - float *fData; - int dataList; - int logVar; - }VarEntry, *pVarEntry; +typedef struct { + char Name[132]; + pIDrivable pInter; + pDummy pObject; + float fStart; + float fStep; + float *fData; + int dataList; + int logVar; +} VarEntry, *pVarEntry; /*---------------------------------------------------------------------*/ @@ -37,44 +37,43 @@ * @return A pointer to a new scan variable object on success, NULL * else */ - pVarEntry MakeScanVar(SicsInterp *pSics, SConnection *pCon, char - *name, float start, float step); +pVarEntry MakeScanVar(SicsInterp * pSics, SConnection * pCon, char + *name, float start, float step); /** * make a variable which is logged during the scan but not driven. * @param pSics The interpreter in order to locate the variable. * @param pCon A connection object for error reporting * @param name The name of the variable to log */ - pVarEntry MakeLogVar(SicsInterp *pSics, - SConnection *pCon, char *name); +pVarEntry MakeLogVar(SicsInterp * pSics, SConnection * pCon, char *name); /** * InitScanVar clears the list of scan points * @param pvar The scna variable to clear */ - void InitScanVar(pVarEntry pVar); +void InitScanVar(pVarEntry pVar); /** * DeleteVarEntry deletes a scan variable. * @param pData The scan variable entry to delete. */ - void DeleteVarEntry(void *pData); +void DeleteVarEntry(void *pData); /** * ScanVarName returns the name of the scan variable * @param pVar The scan variable to query. * @return The name of the scan variable. Do not delete pointer. */ - char *ScanVarName(pVarEntry pVar); +char *ScanVarName(pVarEntry pVar); /** * ScanVarStart returns the start value for the scan * @param pVar The scan variable to query. * @return The start point for the scan. */ - float ScanVarStart(pVarEntry pVar); +float ScanVarStart(pVarEntry pVar); /** * ScanVarStep returns the start value for the scan * @param pVar The scan variable to query. * @return The step width for the scan. */ - float ScanVarStep(pVarEntry pVar); +float ScanVarStep(pVarEntry pVar); /** * StartScanVar starts the scan variable to drive to the next * position. @@ -83,28 +82,28 @@ * @param i The position number to drive to * @return 1 on success, 0 on failure */ - int StartScanVar(pVarEntry pVar, SConnection *pCon, int i); +int StartScanVar(pVarEntry pVar, SConnection * pCon, int i); /** * AppendScanVar appends a position to the list of positions * reached while scanning this variable. * @param pVar The scan variable to append to. * @param pos The position to append. */ - void AppendScanVar(pVarEntry pVar, float pos); +void AppendScanVar(pVarEntry pVar, float pos); /** * GetScanVarPos returns a position for an index. * @param pVar The scan variable to append to. * @param i The position number to retrieve * @return The positiopn or -99999.99 for an error */ - float GetScanVarPos(pVarEntry pVar, int i); +float GetScanVarPos(pVarEntry pVar, int i); /** * CopyScanVar copies the scan positions to the array given. * @param pVar The scan variable to copy from * @param fData The array to copy to. * @param np The number of slots in fData. */ - void CopyScanVar(pVarEntry pVar, float *fData, int np); +void CopyScanVar(pVarEntry pVar, float *fData, int np); /** * CheckScanVar checks if the scan variable can be driven through the * whole range. @@ -113,12 +112,12 @@ * @param np The number of points to check for. * @return 0 on failuyre, 1 on success */ - int CheckScanVar(pVarEntry pVar, SConnection *pCon, int np); +int CheckScanVar(pVarEntry pVar, SConnection * pCon, int np); /** * queries if the variable is alogged variable or a drive one. * @param pVar The variable to query. * @return 1 if log var, 0 else */ - int isLogVar(pVarEntry pVar); +int isLogVar(pVarEntry pVar); #endif diff --git a/script.c b/script.c index 5622af40..f60d9f7f 100644 --- a/script.c +++ b/script.c @@ -55,515 +55,465 @@ #include "status.h" #include "script.h" #include "devexec.h" - - extern Tcl_Interp *InterpGetTcl(SicsInterp *pSics); - extern void SNXFormatTime(char *pBueffel, int iLen); /* in nxdata.c */ - + +extern Tcl_Interp *InterpGetTcl(SicsInterp * pSics); +extern void SNXFormatTime(char *pBueffel, int iLen); /* in nxdata.c */ + /* -------------------------- Interrupts -----------------------------------*/ - int GetSICSInterrupt(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[132]; - SConnection *pOwner = NULL; - pExeList pDev = NULL; - - assert(pCon); - assert(pSics); +int GetSICSInterrupt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[132]; + SConnection *pOwner = NULL; + pExeList pDev = NULL; - /* we are interested in the interrupt pending in the executor. If - not specified, use our very own - */ - pDev = GetExecutor(); - assert(pDev); - pOwner = GetExeOwner(pDev); - if(pOwner) - { - Interrupt2Text(SCGetInterrupt(pOwner),pBueffel,131); - SCWrite(pCon,pBueffel,eValue); - } - else - { - Interrupt2Text(SCGetInterrupt(pCon),pBueffel,131); - SCWrite(pCon,pBueffel,eValue); - } - return 1; - } -/*-------------------------------------------------------------------------*/ - int SetSICSInterrupt(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iInt; - char pBueffel[132]; - SConnection *pOwner = NULL; - pExeList pDev = NULL; - - assert(pCon); - assert(pSics); - - /* minimum user privelege */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: you are not priviledged to set interrupts",eError); - return 0; - } - - /* only in script processing */ - if(!SCinMacro(pCon)) - { - SCWrite(pCon,"ERROR: Interrupt manipulation only permitted in Macros", - eError); - return 0; - } - - /* is there a value ? */ - if(argc < 2) - { - SCWrite(pCon,"ERROR: missing parameter for SetInterrupt",eError); - return 0; - } - - /* actually do a job */ - strtolower(argv[1]); - iInt = Text2Interrupt(argv[1]); - if(iInt < 0) - { - sprintf(pBueffel,"ERROR: %s not recognized as Interrupt code", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } + assert(pCon); + assert(pSics); + + /* we are interested in the interrupt pending in the executor. If + not specified, use our very own + */ + pDev = GetExecutor(); + assert(pDev); + pOwner = GetExeOwner(pDev); + if (pOwner) { + Interrupt2Text(SCGetInterrupt(pOwner), pBueffel, 131); + SCWrite(pCon, pBueffel, eValue); + } else { + Interrupt2Text(SCGetInterrupt(pCon), pBueffel, 131); + SCWrite(pCon, pBueffel, eValue); + } + return 1; +} + +/*-------------------------------------------------------------------------*/ +int SetSICSInterrupt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iInt; + char pBueffel[132]; + SConnection *pOwner = NULL; + pExeList pDev = NULL; + + assert(pCon); + assert(pSics); + + /* minimum user privelege */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: you are not priviledged to set interrupts", + eError); + return 0; + } + + /* only in script processing */ + if (!SCinMacro(pCon)) { + SCWrite(pCon, "ERROR: Interrupt manipulation only permitted in Macros", + eError); + return 0; + } + + /* is there a value ? */ + if (argc < 2) { + SCWrite(pCon, "ERROR: missing parameter for SetInterrupt", eError); + return 0; + } + + /* actually do a job */ + strtolower(argv[1]); + iInt = Text2Interrupt(argv[1]); + if (iInt < 0) { + sprintf(pBueffel, "ERROR: %s not recognized as Interrupt code", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* we want to change the interrupt pending in the executor. If none + there, charnge our own. + */ + pDev = GetExecutor(); + assert(pDev); + pOwner = GetExeOwner(pDev); + if (pOwner) { + SCSetInterrupt(pOwner, iInt); + } else { + SCSetInterrupt(pCon, iInt); + } + SCSendOK(pCon); + return 1; +} + +/*-------------------------------------------------------------------------*/ +int SetSICSStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iInt; + char pBueffel[132]; + + assert(pCon); + assert(pSics); + + /* minimum user privelege */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: you are not priviledged to set status", eError); + return 0; + } + + /* only in script processing */ + if (!SCinMacro(pCon)) { + SCWrite(pCon, "ERROR: status manipulation only permitted in Macros", + eError); + return 0; + } + + /* is there a value ? */ + if (argc < 2) { + SCWrite(pCon, "ERROR: missing parameter for SetStatus", eError); + return 0; + } + + /* actually do a job */ + strtolower(argv[1]); + iInt = SetStatusFromText(argv[1]); + if (iInt) { + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "ERROR: %s not recognized as status code", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } +} - /* we want to change the interrupt pending in the executor. If none - there, charnge our own. - */ - pDev = GetExecutor(); - assert(pDev); - pOwner = GetExeOwner(pDev); - if(pOwner) - { - SCSetInterrupt(pOwner,iInt); - } - else - { - SCSetInterrupt(pCon,iInt); - } - SCSendOK(pCon); - return 1; - } -/*-------------------------------------------------------------------------*/ - int SetSICSStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iInt; - char pBueffel[132]; - - assert(pCon); - assert(pSics); - - /* minimum user privelege */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: you are not priviledged to set status",eError); - return 0; - } - - /* only in script processing */ - if(!SCinMacro(pCon)) - { - SCWrite(pCon,"ERROR: status manipulation only permitted in Macros", - eError); - return 0; - } - - /* is there a value ? */ - if(argc < 2) - { - SCWrite(pCon,"ERROR: missing parameter for SetStatus",eError); - return 0; - } - - /* actually do a job */ - strtolower(argv[1]); - iInt = SetStatusFromText(argv[1]); - if(iInt) - { - SCSendOK(pCon); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: %s not recognized as status code",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } /*-----------------------------------------------------------------------*/ - static int isNum(char *pText) - { - int i; - int iRet = 1; - - for(i = 0; i < strlen(pText); i++) - { - if(!isdigit(pText[i])) - { - if(!((pText[i] == '+') || (pText[i] == '-') || (pText[i] == '.'))) - { - iRet = 0; - break; - } - } +static int isNum(char *pText) +{ + int i; + int iRet = 1; + + for (i = 0; i < strlen(pText); i++) { + if (!isdigit(pText[i])) { + if (!((pText[i] == '+') || (pText[i] == '-') || (pText[i] == '.'))) { + iRet = 0; + break; } - return iRet; - } - + } + } + return iRet; +} + /*--------------------------- Type Checking ------------------------------- classifies a given string: numeric, countable, drivable, sicsobject, text */ - - int SICSType(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - CommandList *pCom = NULL; - Dummy *pDum = NULL; - char pBueffel[132]; - - - assert(pCon); - assert(pSics); - - /* is there a parameter anyway */ - if(argc < 2) - { - SCWrite(pCon,"ERROR: no object to test specified!",eError); - return 0; - } - - /* test, one by one */ - strtolower(argv[1]); - if(isNum(argv[1])) - { - SCWrite(pCon,"NUM",eValue); + +int SICSType(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL; + Dummy *pDum = NULL; + char pBueffel[132]; + + + assert(pCon); + assert(pSics); + + /* is there a parameter anyway */ + if (argc < 2) { + SCWrite(pCon, "ERROR: no object to test specified!", eError); + return 0; + } + + /* test, one by one */ + strtolower(argv[1]); + if (isNum(argv[1])) { + SCWrite(pCon, "NUM", eValue); + return 1; + } + + pCom = FindCommand(pSics, argv[1]); + if (pCom) { + pDum = (Dummy *) pCom->pData; + if (pDum) { + if (pDum->pDescriptor->GetInterface(pDum, DRIVEID)) { + SCWrite(pCon, "DRIV", eValue); return 1; - } - - pCom = FindCommand(pSics,argv[1]); - if(pCom) - { - pDum = (Dummy *)pCom->pData; - if(pDum) - { - if(pDum->pDescriptor->GetInterface(pDum,DRIVEID)) - { - SCWrite(pCon,"DRIV",eValue); - return 1; - } - if(pDum->pDescriptor->GetInterface(pDum,COUNTID)) - { - SCWrite(pCon,"COUNT",eValue); - return 1; - } - } - SCWrite(pCon,"COM",eValue); - return 1; - } - - SCWrite(pCon,"TEXT",eValue); - return 1; - } - + } + if (pDum->pDescriptor->GetInterface(pDum, COUNTID)) { + SCWrite(pCon, "COUNT", eValue); + return 1; + } + } + SCWrite(pCon, "COM", eValue); + return 1; + } + + SCWrite(pCon, "TEXT", eValue); + return 1; +} + /*----------------- Bounds checking for all driveables ---------------------*/ - int SICSBounds(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - CommandList *pCom = NULL; - pIDrivable pInt = NULL; - Dummy *pDum = NULL; - char pBueffel[132]; - float fVal; - int iRet; - - assert(pCon); - assert(pSics); - - if(argc < 3) - { - SCWrite(pCon,"ERROR: not enough parameters specified",eError); - return 0; - } - - /* argv[1] should be drivable */ - pCom = FindCommand(pSics,argv[1]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: %s is no Sics Object",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - pDum = (Dummy *)pCom->pData; - if(!pDum) - { - sprintf(pBueffel,"ERROR: %s is no valid Sics Object",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - pInt = pDum->pDescriptor->GetInterface(pDum,DRIVEID); - if(!pInt) - { - sprintf(pBueffel,"ERROR: %s is not drivable!",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* argv[2] should be a numeric */ - if(!isNum(argv[2])) - { - sprintf(pBueffel,"ERROR: %s is not a number!",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* do a job */ - fVal = atof(argv[2]); - iRet = pInt->CheckLimits(pCom->pData,fVal,pBueffel,131); - if(iRet) - { - SCWrite(pCon,"OK",eValue); - return 1; - } - else - { - SCWrite(pCon,pBueffel,eWarning); - return 0; - } - return 0; /* not reached */ - } +int SICSBounds(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL; + pIDrivable pInt = NULL; + Dummy *pDum = NULL; + char pBueffel[132]; + float fVal; + int iRet; + + assert(pCon); + assert(pSics); + + if (argc < 3) { + SCWrite(pCon, "ERROR: not enough parameters specified", eError); + return 0; + } + + /* argv[1] should be drivable */ + pCom = FindCommand(pSics, argv[1]); + if (!pCom) { + sprintf(pBueffel, "ERROR: %s is no Sics Object", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + pDum = (Dummy *) pCom->pData; + if (!pDum) { + sprintf(pBueffel, "ERROR: %s is no valid Sics Object", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + pInt = pDum->pDescriptor->GetInterface(pDum, DRIVEID); + if (!pInt) { + sprintf(pBueffel, "ERROR: %s is not drivable!", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* argv[2] should be a numeric */ + if (!isNum(argv[2])) { + sprintf(pBueffel, "ERROR: %s is not a number!", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* do a job */ + fVal = atof(argv[2]); + iRet = pInt->CheckLimits(pCom->pData, fVal, pBueffel, 131); + if (iRet) { + SCWrite(pCon, "OK", eValue); + return 1; + } else { + SCWrite(pCon, pBueffel, eWarning); + return 0; + } + return 0; /* not reached */ +} + /*----------------- Status checking for Sics Objects ---------------------*/ - int SICSStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - CommandList *pCom = NULL; - Dummy *pDum = NULL; - pIDrivable pDInt = NULL; - pICountable pCInt = NULL; - char pBueffel[132]; - float fVal; - int iRet; - - assert(pCon); - assert(pSics); - - if(argc < 2) - { - SCWrite(pCon,"ERROR: not enough parameters specified",eError); - return 0; - } - - /* argv[1] should be drivable */ - pCom = FindCommand(pSics,argv[1]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: %s is no Sics Object",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - pDum = (Dummy *)pCom->pData; - if(!pDum) - { - sprintf(pBueffel,"ERROR: %s is no valid Sics Object",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - pDInt = pDum->pDescriptor->GetInterface(pDum,DRIVEID); - pCInt = pDum->pDescriptor->GetInterface(pDum,COUNTID); - if(pDInt) - { - iRet = pDInt->CheckStatus(pDum,pCon); - sprintf(pBueffel,"%d",iRet); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else if(pCInt) - { - iRet = pCInt->CheckCountStatus(pDum,pCon); - sprintf(pBueffel,"%d",iRet); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: %s is neither drivable nor countable",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* not reached */ - return 0; +int SICSStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL; + Dummy *pDum = NULL; + pIDrivable pDInt = NULL; + pICountable pCInt = NULL; + char pBueffel[132]; + float fVal; + int iRet; - } -/*--------------------------------------------------------------------------*/ - int SICSDebug(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[256]; - Tcl_Interp *pTcl = NULL; - int iRet; - char *cmd; - - assert(pCon); - assert(pSics); - - if(!SCMatchRights(pCon,usInternal)) - { - SCWrite(pCon,"ERROR: no privilege to interact with Tcl for you", - eError); - return 0; - } - - pTcl = InterpGetTcl(pSics); - assert(pTcl); - - cmd = Arg2Tcl(argc-1,&argv[1],pBueffel,sizeof pBueffel); - if (!cmd) { - SCWrite(pCon,"ERROR: no more memory",eError); - return 0; - } - iRet = Tcl_Eval(pTcl,cmd); - if (cmd != pBueffel) free(cmd); - if(strlen(pTcl->result) > 1) - { - SCWrite(pCon,pTcl->result,eValue); - } - return iRet; - } -/*--------------------------------------------------------------------------*/ - int SICSTime(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[256]; + assert(pCon); + assert(pSics); + + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough parameters specified", eError); + return 0; + } + + /* argv[1] should be drivable */ + pCom = FindCommand(pSics, argv[1]); + if (!pCom) { + sprintf(pBueffel, "ERROR: %s is no Sics Object", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + pDum = (Dummy *) pCom->pData; + if (!pDum) { + sprintf(pBueffel, "ERROR: %s is no valid Sics Object", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + pDInt = pDum->pDescriptor->GetInterface(pDum, DRIVEID); + pCInt = pDum->pDescriptor->GetInterface(pDum, COUNTID); + if (pDInt) { + iRet = pDInt->CheckStatus(pDum, pCon); + sprintf(pBueffel, "%d", iRet); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (pCInt) { + iRet = pCInt->CheckCountStatus(pDum, pCon); + sprintf(pBueffel, "%d", iRet); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + sprintf(pBueffel, "ERROR: %s is neither drivable nor countable", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* not reached */ + return 0; + +} + +/*--------------------------------------------------------------------------*/ +int SICSDebug(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[256]; + Tcl_Interp *pTcl = NULL; + int iRet; + char *cmd; + + assert(pCon); + assert(pSics); + + if (!SCMatchRights(pCon, usInternal)) { + SCWrite(pCon, "ERROR: no privilege to interact with Tcl for you", + eError); + return 0; + } + + pTcl = InterpGetTcl(pSics); + assert(pTcl); + + cmd = Arg2Tcl(argc - 1, &argv[1], pBueffel, sizeof pBueffel); + if (!cmd) { + SCWrite(pCon, "ERROR: no more memory", eError); + return 0; + } + iRet = Tcl_Eval(pTcl, cmd); + if (cmd != pBueffel) + free(cmd); + if (strlen(pTcl->result) > 1) { + SCWrite(pCon, pTcl->result, eValue); + } + return iRet; +} + +/*--------------------------------------------------------------------------*/ +int SICSTime(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[256]; + + SNXFormatTime(pBueffel, 255); + SCWrite(pCon, pBueffel, eValue); + return 1; +} - SNXFormatTime(pBueffel,255); - SCWrite(pCon,pBueffel,eValue); - return 1; - } /*-------------------------------------------------------------------------- Kill a command from SICS -*/ - int SICSKill(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - CommandList *pCom = NULL, *pCurrent = NULL; - void *pDat = NULL; - char *pPtr = NULL; - - if(!SCMatchRights(pCon,usMugger)) - { - SCWrite(pCon,"ERROR: you may not kill commands here, no privilege", - eError); - return 0; - } - - if(argc < 2) - { - SCWrite(pCon,"ERROR: need name of command to kill",eError); - return 0; - } +*/ +int SICSKill(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL, *pCurrent = NULL; + void *pDat = NULL; + char *pPtr = NULL; + + if (!SCMatchRights(pCon, usMugger)) { + SCWrite(pCon, "ERROR: you may not kill commands here, no privilege", + eError); + return 0; + } + + if (argc < 2) { + SCWrite(pCon, "ERROR: need name of command to kill", eError); + return 0; + } + + /* memorise data for alias search */ + pCom = FindCommand(pSics, argv[1]); + if (pCom) { + pDat = pCom->pData; + } else { + pDat = NULL; + } + RemoveCommand(pSics, argv[1]); + if (!pDat) { /* no data, no alias */ + SCSendOK(pCon); + return 0; + } + + /* kill aliases */ + pPtr = FindAlias(pSics, pDat); + while (pPtr) { + RemoveCommand(pSics, pPtr); + pPtr = FindAlias(pSics, pDat); + } + SCSendOK(pCon); + return 1; +} - /* memorise data for alias search */ - pCom = FindCommand(pSics,argv[1]); - if(pCom) - { - pDat = pCom->pData; - } - else - { - pDat = NULL; - } - RemoveCommand(pSics,argv[1]); - if(!pDat) /* no data, no alias */ - { - SCSendOK(pCon); - return 0; - } - - /* kill aliases */ - pPtr = FindAlias(pSics,pDat); - while(pPtr) - { - RemoveCommand(pSics,pPtr); - pPtr = FindAlias(pSics,pDat); - } - SCSendOK(pCon); - return 1; - } /*------------------------------------------------------------------------*/ - int SicsPrompt(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - int iRet; +int SicsPrompt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512]; + int iRet; + + /* all arguments are optional */ + if (argc < 1) { + iRet = SCPrompt(pCon, "SICS> ", pBueffel, 511); + } else { + iRet = SCPrompt(pCon, argv[1], pBueffel, 511); + } + if (iRet == 1) { + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + SCWrite(pCon, "ERROR: Interrupted while waiting for data", eError); + return 0; + } +} - /* all arguments are optional */ - if(argc < 1) - { - iRet = SCPrompt(pCon, "SICS> ", - pBueffel, 511); - } - else - { - iRet = SCPrompt(pCon, argv[1], - pBueffel, 511); - } - if(iRet == 1) - { - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { - SCWrite(pCon,"ERROR: Interrupted while waiting for data",eError); - return 0; - } - } /*----------------------- get object descriptor name ------------------------------- get the name of the object descriptor */ - - int SICSDescriptor(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - CommandList *pCom = NULL; - Dummy *pDum = NULL; - char pBueffel[132]; - - - assert(pCon); - assert(pSics); - - /* is there a parameter anyway */ - if(argc < 2) - { - SCWrite(pCon,"ERROR: no object specified!",eError); - return 0; - } - - pCom = FindCommand(pSics,argv[1]); - if(pCom) - { - pDum = (Dummy *)pCom->pData; - if(pDum) - { - SCWrite(pCon,pDum->pDescriptor->name,eValue); - return 1; - } - SCWrite(pCon,"empty",eValue); - return 1; - } - - SCWrite(pCon,"notfound",eValue); - return 1; - } - + +int SICSDescriptor(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL; + Dummy *pDum = NULL; + char pBueffel[132]; + + + assert(pCon); + assert(pSics); + + /* is there a parameter anyway */ + if (argc < 2) { + SCWrite(pCon, "ERROR: no object specified!", eError); + return 0; + } + + pCom = FindCommand(pSics, argv[1]); + if (pCom) { + pDum = (Dummy *) pCom->pData; + if (pDum) { + SCWrite(pCon, pDum->pDescriptor->name, eValue); + return 1; + } + SCWrite(pCon, "empty", eValue); + return 1; + } + + SCWrite(pCon, "notfound", eValue); + return 1; +} diff --git a/script.h b/script.h index 29cbafad..b2adbec6 100644 --- a/script.h +++ b/script.h @@ -11,43 +11,41 @@ #define SICSSCRIPT /* -------------------------- Interrupts -----------------------------------*/ - int GetSICSInterrupt(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - - int SetSICSInterrupt(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +int GetSICSInterrupt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +int SetSICSInterrupt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + /*---------------------------- Status -------------------------------------*/ - int SetSICSStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +int SetSICSStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + /*--------------------------- Type Checking -------------------------------*/ - int SICSType(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +int SICSType(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + /*----------------- Bounds checking for all driveables ---------------------*/ - int SICSBounds(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SICSBounds(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*------------------ Status checking for SicsObjects ----------------------- */ - int SICSStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SICSStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*------------------ Type directly to Tcl ----------------------- */ - int SICSDebug(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SICSDebug(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*-----------------------------------------------------------------------*/ - int SICSTime(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SICSTime(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*----------------------------------------------------------------------*/ - int SICSKill(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SICSKill(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*----------------------------------------------------------------------*/ - int SicsPrompt(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SicsPrompt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*----------------------------------------------------------------------*/ - int SICSDescriptor(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SICSDescriptor(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif - - diff --git a/scriptcontext.c b/scriptcontext.c index 6c6b221e..d02fad14 100644 --- a/scriptcontext.c +++ b/scriptcontext.c @@ -32,8 +32,8 @@ typedef struct ScriptContext { struct SctController { DevSer *devser; - Hdb *node; /* the controller node */ - SConnection*conn; + Hdb *node; /* the controller node */ + SConnection *conn; int verbose; }; @@ -41,7 +41,7 @@ struct SctController { typedef struct SctData { char *name; SctController *controller; - SConnection*conCtx; + SConnection *conCtx; int answered; Hdb *node; } SctData; @@ -55,9 +55,10 @@ static struct { static char *mainCallback = "main callback"; -void PushContext(Hdb *node, Hdb *controllerNode) { +void PushContext(Hdb * node, Hdb * controllerNode) +{ ContextItem *new; - + if (sct->trash == NULL) { new = calloc(1, sizeof(*new)); } else { @@ -70,9 +71,10 @@ void PushContext(Hdb *node, Hdb *controllerNode) { new->controllerNode = controllerNode; } -void PopContext(void) { +void PopContext(void) +{ ContextItem *c; - + c = sct->nodes; assert(c); sct->nodes = c->next; @@ -80,9 +82,10 @@ void PopContext(void) { sct->trash = c; } -void CleanStack(Hdb *node) { +void CleanStack(Hdb * node) +{ ContextItem *s; - + /* clean context from killed nodes */ for (s = sct->nodes; s != NULL; s = s->next) { if (s->node == node) { @@ -94,11 +97,13 @@ void CleanStack(Hdb *node) { } } -static void SetProp(Hdb *node, Hdb *cNode, char *key, char *value) { +static void SetProp(Hdb * node, Hdb * cNode, char *key, char *value) +{ char *val; - + if (node == NULL) { - if (cNode == NULL) return; + if (cNode == NULL) + return; node = cNode; } else { val = GetHdbProp(node, key); @@ -118,12 +123,14 @@ static void SetProp(Hdb *node, Hdb *cNode, char *key, char *value) { } } -static char *GetProp(Hdb *node, Hdb *cNode, char *key) { +static char *GetProp(Hdb * node, Hdb * cNode, char *key) +{ char *val; if (node != NULL) { val = GetHdbProp(node, key); - if (val != NULL) return val; + if (val != NULL) + return val; } if (cNode != NULL) { val = GetHdbProp(cNode, key); @@ -134,8 +141,9 @@ static char *GetProp(Hdb *node, Hdb *cNode, char *key) { /* * This is the actual sct command available in scripts. */ -int SctCommand(SConnection *con, SicsInterp *sics, void *object, - int argc, char *argv[]) { +int SctCommand(SConnection * con, SicsInterp * sics, void *object, + int argc, char *argv[]) +{ static char value[1024]; char *val; char error[512]; @@ -143,7 +151,7 @@ int SctCommand(SConnection *con, SicsInterp *sics, void *object, Hdb *cNode = NULL; hdbValue v; double dtime; - + assert(sct == object); if (sct->nodes != NULL) { node = sct->nodes->node; @@ -151,7 +159,7 @@ int SctCommand(SConnection *con, SicsInterp *sics, void *object, } if (node == NULL && cNode == NULL) { SCPrintf(con, eError, "ERROR: %s may be called only in proper context", - argv[0]); + argv[0]); return 0; } if (argc <= 1) { @@ -159,96 +167,97 @@ int SctCommand(SConnection *con, SicsInterp *sics, void *object, SCWrite(con, value, eValue); return 1; } - + /* * update command */ - if(strcmp(argv[1],"update") == 0){ - cloneHdbValue(&node->value, &v); - Arg2Text(argc-2, argv+2, value, sizeof value); - if(!readHdbValue(&v, value, error, 512)){ - SCWrite(con, error, eError); - return 0; - } - UpdateHipadabaPar(node,v,con); - SetHdbProperty(node,"geterror", NULL); - return 1; + if (strcmp(argv[1], "update") == 0) { + cloneHdbValue(&node->value, &v); + Arg2Text(argc - 2, argv + 2, value, sizeof value); + if (!readHdbValue(&v, value, error, 512)) { + SCWrite(con, error, eError); + return 0; + } + UpdateHipadabaPar(node, v, con); + SetHdbProperty(node, "geterror", NULL); + return 1; } /* * print */ - if(strcmp(argv[1],"print") == 0){ - Arg2Text(argc-2, argv+2, value, sizeof value); - SCWrite(con,value,eWarning); - return 1; + if (strcmp(argv[1], "print") == 0) { + Arg2Text(argc - 2, argv + 2, value, sizeof value); + SCWrite(con, value, eLog); + return 1; } - + /** * controller */ - if(strcmp(argv[1],"controller") == 0){ - SCWrite(con,cNode->name, eValue); - return 1; + if (strcmp(argv[1], "controller") == 0) { + SCWrite(con, cNode->name, eValue); + return 1; } - + /* * time stamping - */ - if(strcmp(argv[1],"utime") == 0){ - if(argc < 3){ - SCWrite(con,"ERROR: need property to write time stamp too", - eError); - return 0; - } - dtime = DoubleTime(); - snprintf(value,1024,"%.3f",dtime); - SetHdbProperty(node,argv[2], value); - return 1; + */ + if (strcmp(argv[1], "utime") == 0) { + if (argc < 3) { + SCWrite(con, "ERROR: need property to write time stamp too", eError); + return 0; + } + dtime = DoubleTime(); + snprintf(value, 1024, "%.3f", dtime); + SetHdbProperty(node, argv[2], value); + return 1; } - + /* * property handling */ - if (argc == 2) { /* get case */ + if (argc == 2) { /* get case */ val = GetProp(node, cNode, argv[1]); if (val == NULL) { SCPrintf(con, eError, "ERROR: %s %s not found", argv[0], argv[1]); return 0; } SCWrite(con, val, eValue); - } else { /* set case */ + } else { /* set case */ if (argc == 3) { SetProp(node, cNode, argv[1], argv[2]); } else { - val = Arg2Tcl(argc-2, argv+2, value, sizeof value); + val = Arg2Tcl(argc - 2, argv + 2, value, sizeof value); SetProp(node, cNode, argv[1], val); - if (val != NULL && val != value) free(val); + if (val != NULL && val != value) + free(val); } } return 1; } -int SctCallInContext(SConnection *con, char *script, Hdb *node, - SctController *controller, char **resPtr) { +int SctCallInContext(SConnection * con, char *script, Hdb * node, + SctController * controller, char **resPtr) +{ Tcl_Interp *pTcl = InterpGetTcl(pServ->pSics); int ret, l; char *result = NULL; int iRet = 1; int verbose = controller->verbose; - + PushContext(node, controller->node); if (verbose) { - SCPrintf(con, eInError, "\nscript: %s\n", script); + SCPrintf(con, eLog, "\nscript: %s\n", script); } - + MacroPush(con); l = strlen(script); ret = Tcl_EvalEx(pTcl, script, l, 0); - result = (char *)Tcl_GetStringResult(pTcl); - if (ret != TCL_OK && result[0]!='\0') { + result = (char *) Tcl_GetStringResult(pTcl); + if (ret != TCL_OK && result[0] != '\0') { if (verbose) { - SCPrintf(con, eInError, "\nerror: %s\n", result); + SCPrintf(con, eLog, "\nerror: %s\n", result); } iRet = 0; } @@ -259,14 +268,16 @@ int SctCallInContext(SConnection *con, char *script, Hdb *node, return iRet; } -static int SctMatch(void *data1, void *data2) { +static int SctMatch(void *data1, void *data2) +{ SctData *a = data1; SctData *b = data2; - + return a->node == b->node && strcasecmp(a->name, b->name) == 0; } -static char *SctActionHandler(void *actionData, char *lastReply) { +static char *SctActionHandler(void *actionData, char *lastReply) +{ SctData *data = actionData; Hdb *node = data->node; SctController *controller = data->controller; @@ -277,7 +288,7 @@ static char *SctActionHandler(void *actionData, char *lastReply) { int i; SConnection *con; char timeKey[50], timeVal[50]; - + if (currentCon) { con = currentCon; } else { @@ -285,7 +296,7 @@ static char *SctActionHandler(void *actionData, char *lastReply) { } SetProp(node, controller->node, "result", lastReply); if (controller->verbose && lastReply != NULL && *lastReply != '\0') { - SCPrintf(con, eWarning, "reply : %s", lastReply); + SCPrintf(con, eLog, "reply : %s", lastReply); } state = GetProp(node, controller->node, "state"); if (state == NULL || strcasecmp(state, "idle") == 0) { @@ -295,23 +306,24 @@ static char *SctActionHandler(void *actionData, char *lastReply) { for (i = 0; i < 10; i++) { SetProp(node, controller->node, "send", NULL); script = GetProp(node, controller->node, state); - if (script == NULL) script = state; + if (script == NULL) + script = state; - if (! SctCallInContext(con, script, node, data->controller, &result)) { + if (!SctCallInContext(con, script, node, data->controller, &result)) { SCPrintf(con, eError, "ERROR: %s", result); goto finish; } state = result; if (strcasecmp(state, "idle") == 0) { - if (currentCon && ! data->answered) { + if (currentCon && !data->answered) { SCWrite(con, "o.k.", eValue); } - if(strcmp(data->name,"write") == 0){ - SetHdbProperty(data->node,"writestatus","commandsent"); + if (strcmp(data->name, "write") == 0) { + SetHdbProperty(data->node, "writestatus", "commandsent"); } - snprintf(timeKey,50,"%s_time",data->name); - snprintf(timeVal,50,"%.3f", DoubleTime()); - SetHdbProperty(data->node,timeKey,timeVal); + snprintf(timeKey, 50, "%s_time", data->name); + snprintf(timeVal, 50, "%.3f", DoubleTime()); + SetHdbProperty(data->node, timeKey, timeVal); goto finish; } SetProp(node, controller->node, "state", state); @@ -333,11 +345,12 @@ finish: return send; } -static char *SctWriteHandler(void *actionData, char *lastReply) { +static char *SctWriteHandler(void *actionData, char *lastReply) +{ SctData *data = actionData; - SConnection*old; + SConnection *old; char *result; - + old = currentCon; currentCon = data->conCtx; result = SctActionHandler(data, lastReply); @@ -345,15 +358,17 @@ static char *SctWriteHandler(void *actionData, char *lastReply) { return result; } -static int SctMatchNode(void *vNode, void *vData) { +static int SctMatchNode(void *vNode, void *vData) +{ Hdb *node = vNode; SctData *d = vData; - + return node == d->node; } -static hdbCallbackReturn SctMainCallback(Hdb *node, void *userData, - hdbMessage *msg) { +static hdbCallbackReturn SctMainCallback(Hdb * node, void *userData, + hdbMessage * msg) +{ SctController *controller = userData; hdbDataSearch *dsm; hdbDataMessage *mm; @@ -362,6 +377,7 @@ static hdbCallbackReturn SctMainCallback(Hdb *node, void *userData, ContextItem *s; SConnection *con; char *geterror; + char error[256]; pm = GetKillPtrMessage(msg); if (pm != NULL) { @@ -381,7 +397,8 @@ static hdbCallbackReturn SctMainCallback(Hdb *node, void *userData, km = GetHdbKillNodeMessage(msg); if (km != NULL) { /* unschedule all actions related to this node */ - DevUnschedule(controller->devser, node, SctActionHandler, SctMatchNode); + DevUnschedule(controller->devser, node, SctActionHandler, + SctMatchNode); CleanStack(node); return hdbContinue; } @@ -390,17 +407,25 @@ static hdbCallbackReturn SctMainCallback(Hdb *node, void *userData, con = mm->callData; geterror = GetHdbProp(node, "geterror"); if (geterror != NULL) { - SCPrintf(con, eError, "ERROR: %s", geterror); + snprintf(error,255,"ERROR: %s", geterror); + SCWrite(con, error, eError); + if(mm->v->dataType == HIPTEXT){ + if(mm->v->v.text != NULL){ + free(mm->v->v.text); + } + mm->v->v.text = strdup(error); + } return hdbAbort; } return hdbContinue; } - + return hdbContinue; } -static hdbCallbackReturn SctActionCallback(Hdb *node, void *userData, - hdbMessage *msg) { +static hdbCallbackReturn SctActionCallback(Hdb * node, void *userData, + hdbMessage * msg) +{ hdbDataSearch *dsm; hdbDataMessage *mm; hdbPtrMessage *pm; @@ -417,7 +442,7 @@ static hdbCallbackReturn SctActionCallback(Hdb *node, void *userData, SConnection *con; SConnection *con2; char path[MAX_HDB_PATH]; - + pm = GetKillPtrMessage(msg); if (pm != NULL) { if (data->controller == pm->pPtr) { @@ -435,7 +460,7 @@ static hdbCallbackReturn SctActionCallback(Hdb *node, void *userData, } return hdbContinue; } - + mm = GetHdbSetMessage(msg); if (mm != NULL) { con = mm->callData; @@ -443,18 +468,19 @@ static hdbCallbackReturn SctActionCallback(Hdb *node, void *userData, /* set target value */ text = formatValue(*(mm->v), node); SetHdbProperty(node, "target", GetCharArray(text)); - + /* call check script, if available */ script = GetProp(node, data->controller->node, "check"); if (script != NULL) { - if (SctCallInContext(con, script, node, data->controller, &error) == 0) { + if (SctCallInContext(con, script, node, data->controller, &error) == + 0) { SCPrintf(con, eError, "ERROR: %s", error); - SetHdbProperty(node,"target", NULL); + SetHdbProperty(node, "target", NULL); return hdbAbort; } } - - + + /* enqueue write action */ writeprio = GetProp(node, data->controller->node, "writeprio"); if (writeprio != NULL) { @@ -466,11 +492,12 @@ static hdbCallbackReturn SctActionCallback(Hdb *node, void *userData, } else { prio = WritePRIO; } - + if (data->conCtx != NULL) { GetHdbPath(node, path, sizeof path); - SCPrintf(data->conCtx, eLog, "%s target changed to %s before completion", - path, GetCharArray(text)); + SCPrintf(data->conCtx, eLog, + "%s target changed to %s before completion", path, + GetCharArray(text)); } DeleteDynString(text); data->conCtx = SCCopyConnection(con); @@ -483,14 +510,16 @@ static hdbCallbackReturn SctActionCallback(Hdb *node, void *userData, mm = GetHdbUpdateMessage(msg); if (mm != NULL) { - if (currentCon) { /* update called from a write action */ + if (currentCon) { /* update called from a write action */ data->answered = 1; GetHdbPath(node, path, sizeof path); con = currentCon; text = formatValue(*(mm->v), node); - /* Markus: who is receiving this message? */ - SCPrintf(con, eLog, "%s = %s", path, - GetCharArray(text)); + /* Markus: who is receiving this message? + It gave unwanted output to me. MK + SCPrintf(con, eLog, "%s = %s", path, GetCharArray(text)); + */ + DeleteDynString(text); } return hdbContinue; @@ -498,10 +527,11 @@ static hdbCallbackReturn SctActionCallback(Hdb *node, void *userData, return hdbContinue; } -static char *ParText(Hdb *cmdNode, char *name, - int nPar, char *defaultValue) { +static char *ParText(Hdb * cmdNode, char *name, + int nPar, char *defaultValue) +{ Hdb *par; - + for (par = cmdNode->child; nPar > 0 && par != NULL; par = par->next, nPar--) { if (strcasecmp(par->name, name) == 0) { @@ -513,63 +543,72 @@ static char *ParText(Hdb *cmdNode, char *name, return defaultValue; } -static double ParValue(Hdb *cmdNode, char *name, - int nPar, double defaultValue) { +static double ParValue(Hdb * cmdNode, char *name, + int nPar, double defaultValue) +{ Hdb *par; - + for (par = cmdNode->child; nPar > 0 && par != NULL; par = par->next, nPar--) { if (strcasecmp(par->name, name) == 0) { switch (par->value.dataType) { - case HIPINT: return par->value.v.intValue; - case HIPFLOAT: return par->value.v.doubleValue; + case HIPINT: + return par->value.v.intValue; + case HIPFLOAT: + return par->value.v.doubleValue; } } } return defaultValue; } -static void SctKillData(void *d) { +static void SctKillData(void *d) +{ SctData *data = d; - - if (data->name) free(data->name); - if (data->conCtx) SCDeleteConnection(data->conCtx); + + if (data->name) + free(data->name); + if (data->conCtx) + SCDeleteConnection(data->conCtx); free(data); } -static void SctKillCBData(void *d) { +static void SctKillCBData(void *d) +{ SctData *data = d; - + DevRemoveAction(data->controller->devser, data); SctKillData(d); } -int SctAddPollNode(SctController *controller, Hdb *node, double interval, - DevPrio prio, char *action) { +int SctAddPollNode(SctController * controller, Hdb * node, double interval, + DevPrio prio, char *action) +{ SctData *data; hdbCallback *cb; - - if (! FindHdbCallbackData(node, controller)) { + + if (!FindHdbCallbackData(node, controller)) { cb = MakeHipadabaCallback(SctMainCallback, controller, NULL); assert(cb); AppendHipadabaCallback(node, cb); - SetHdbProperty(node,"geterror","Not read yet"); + SetHdbProperty(node, "geterror", "Not read yet"); } data = calloc(1, sizeof(*data)); assert(data); data->controller = controller; data->node = node; - data->conCtx = NULL; /* we might need a dummy connection here */ + data->conCtx = NULL; /* we might need a dummy connection here */ data->name = strdup(action); return DevSchedule(controller->devser, data, prio, interval, - SctActionHandler, SctMatch, SctKillData); + SctActionHandler, SctMatch, SctKillData); } -static int SctPollCmd(pSICSOBJ ccmd, SConnection *con, - Hdb *cmdNode, Hdb *par[], int nPar) { +static int SctPollCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ Hdb *node; SctController *controller; double interval; @@ -577,11 +616,11 @@ static int SctPollCmd(pSICSOBJ ccmd, SConnection *con, DevPrio prio; char *action; char *prioText; - - if(nPar < 1){ - SCPrintf(con,eError, - "ERROR: should be: %s poll ( )", - ccmd->objectNode->name); + + if (nPar < 1) { + SCPrintf(con, eError, + "ERROR: should be: %s poll ( )", + ccmd->objectNode->name); return 0; } controller = ccmd->pPrivate; @@ -595,36 +634,37 @@ static int SctPollCmd(pSICSOBJ ccmd, SConnection *con, prioText = ParText(cmdNode, "prio", nPar, "read"); prio = DevText2Prio(prioText); if (prio == NullPRIO) { - SCPrintf(con,eError, "ERROR: unknown priority: %s", prioText); + SCPrintf(con, eError, "ERROR: unknown priority: %s", prioText); return 0; } action = ParText(cmdNode, "action", nPar, "read"); if (SctAddPollNode(controller, node, interval, prio, action) > 0) { SCPrintf(con, eValue, - "%s poll on %s changed to %g sec, %s prio", - action, path, interval, prioText); + "%s poll on %s changed to %g sec, %s prio", + action, path, interval, prioText); } else { SCPrintf(con, eValue, - "%s poll registered on %s (%g sec, %s prio)", - action, path, interval, prioText); + "%s poll registered on %s (%g sec, %s prio)", + action, path, interval, prioText); } return 1; } -static int SctUnpollCmd(pSICSOBJ ccmd, SConnection *con, - Hdb *cmdNode, Hdb *par[], int nPar) { +static int SctUnpollCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ SctController *controller; double interval; char *path; DevPrio prio; char *prioText; SctData data; - - if(nPar < 1){ - SCPrintf(con,eError, - "ERROR: should be: %s poll ()", - ccmd->objectNode->name); + + if (nPar < 1) { + SCPrintf(con, eError, + "ERROR: should be: %s poll ()", + ccmd->objectNode->name); return 0; } controller = ccmd->pPrivate; @@ -635,26 +675,27 @@ static int SctUnpollCmd(pSICSOBJ ccmd, SConnection *con, return 0; } data.name = ParText(cmdNode, "action", nPar, "read"); - if (DevUnschedule(controller->devser, &data, SctActionHandler, SctMatch) == 0) { - SCPrintf(con, eValue, - "%s poll not found on %s", data.name, path); + if (DevUnschedule(controller->devser, &data, SctActionHandler, SctMatch) + == 0) { + SCPrintf(con, eValue, "%s poll not found on %s", data.name, path); } else { SCSendOK(con); } return 1; } -static int SctConnectCmd(pSICSOBJ ccmd, SConnection *con, - Hdb *cmdNode, Hdb *par[], int nPar) { +static int SctConnectCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ Hdb *node; SctController *controller; char *path; hdbCallback *cb; - - if(nPar < 1){ - SCPrintf(con,eError, - "ERROR: should be: %s connect ", - ccmd->objectNode->name); + + if (nPar < 1) { + SCPrintf(con, eError, + "ERROR: should be: %s connect ", + ccmd->objectNode->name); return 0; } controller = ccmd->pPrivate; @@ -665,7 +706,7 @@ static int SctConnectCmd(pSICSOBJ ccmd, SConnection *con, return 0; } - if (! FindHdbCallbackData(node, controller)) { + if (!FindHdbCallbackData(node, controller)) { cb = MakeHipadabaCallback(SctMainCallback, controller, NULL); assert(cb); AppendHipadabaCallback(node, cb); @@ -674,17 +715,18 @@ static int SctConnectCmd(pSICSOBJ ccmd, SConnection *con, return 1; } -int SctAddWriteNode(SctController *controller, Hdb *node) { +int SctAddWriteNode(SctController * controller, Hdb * node) +{ hdbCallback *cb; SctData *data; - if (! FindHdbCallbackData(node, controller)) { + if (!FindHdbCallbackData(node, controller)) { cb = MakeHipadabaCallback(SctMainCallback, controller, NULL); assert(cb); AppendHipadabaCallback(node, cb); } - actionCallback.name = "write"; /* local, so no strdup here */ + actionCallback.name = "write"; /* local, so no strdup here */ data = FindHdbCallbackData(node, &actionCallback); if (data != NULL) { return 0; @@ -704,16 +746,17 @@ int SctAddWriteNode(SctController *controller, Hdb *node) { return 1; } -static int SctWriteCmd(pSICSOBJ ccmd, SConnection *con, - Hdb *cmdNode, Hdb *par[], int nPar) { +static int SctWriteCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ Hdb *node; SctController *controller; double interval; char *path; - - if(nPar < 1){ + + if (nPar < 1) { SCPrintf(con, eError, "ERROR: should be: %s write ", - ccmd->objectNode->name); + ccmd->objectNode->name); return 0; } controller = ccmd->pPrivate; @@ -724,21 +767,21 @@ static int SctWriteCmd(pSICSOBJ ccmd, SConnection *con, return 0; } if (SctAddWriteNode(controller, node) == 0) { - SCPrintf(con, eError, - "ERROR: %s has already a write action", path); + SCPrintf(con, eError, "ERROR: %s has already a write action", path); return 0; } - + SCSendOK(con); return 1; } -void SctQueueNode(SctController *controller, Hdb *node, - DevPrio prio, char *action, SConnection *con) { +void SctQueueNode(SctController * controller, Hdb * node, + DevPrio prio, char *action, SConnection * con) +{ SctData *data; hdbCallback *cb; - if (! FindHdbCallbackData(node, controller)) { + if (!FindHdbCallbackData(node, controller)) { cb = MakeHipadabaCallback(SctMainCallback, controller, NULL); assert(cb); AppendHipadabaCallback(node, cb); @@ -751,22 +794,23 @@ void SctQueueNode(SctController *controller, Hdb *node, data->name = strdup(action); data->conCtx = NULL; - if(!DevQueue(data->controller->devser, data, prio, - SctWriteHandler, SctMatch, SctKillData)){ - if(data->name != NULL){ - free(data->name); - } - free(data); + if (!DevQueue(data->controller->devser, data, prio, + SctWriteHandler, SctMatch, SctKillData)) { + if (data->name != NULL) { + free(data->name); + } + free(data); } else { - if (con != NULL) { - data->conCtx = SCCopyConnection(con); - } + if (con != NULL) { + data->conCtx = SCCopyConnection(con); + } } return; } -static int SctQueueCmd(pSICSOBJ ccmd, SConnection *con, - Hdb *cmdNode, Hdb *par[], int nPar) { +static int SctQueueCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ Hdb *node; SctController *controller; double interval; @@ -775,11 +819,11 @@ static int SctQueueCmd(pSICSOBJ ccmd, SConnection *con, DevPrio prio; SctData *data; char *prioText; - - if(nPar < 2){ - SCPrintf(con,eError, - "ERROR: should be: %s queue ", - ccmd->objectNode->name); + + if (nPar < 2) { + SCPrintf(con, eError, + "ERROR: should be: %s queue ", + ccmd->objectNode->name); return 0; } controller = ccmd->pPrivate; @@ -792,7 +836,7 @@ static int SctQueueCmd(pSICSOBJ ccmd, SConnection *con, prioText = ParText(cmdNode, "prio", nPar, "write"); prio = DevText2Prio(prioText); if (prio == NullPRIO) { - SCPrintf(con,eError, "ERROR: unknown priority: %s", prioText); + SCPrintf(con, eError, "ERROR: unknown priority: %s", prioText); return 0; } action = ParText(cmdNode, "action", nPar, "write"); @@ -802,112 +846,119 @@ static int SctQueueCmd(pSICSOBJ ccmd, SConnection *con, } typedef struct SctTransact { - char *command; - int sent; - SConnection *con; -}SctTransact, *pSctTransact; + char *command; + int sent; + SConnection *con; +} SctTransact, *pSctTransact; -static void KillSctTransact(void *data){ - pSctTransact self = (pSctTransact)data; - if(self == NULL){ - return; - } - if(self->command){ - free(self->command); - } - if(self->con){ - SCDeleteConnection(self->con); - } - free(self); +static void KillSctTransact(void *data) +{ + pSctTransact self = (pSctTransact) data; + if (self == NULL) { + return; + } + if (self->command) { + free(self->command); + } + if (self->con) { + SCDeleteConnection(self->con); + } + free(self); } -static char *TransactionHandler(void *actionData, char *lastReply){ - pSctTransact st = (pSctTransact)actionData; - - if(st->sent == 0){ - st->sent = 1; - return st->command; - } else { - st->sent = 2; - SCWrite(st->con,lastReply, eValue); - return NULL; - } +static char *TransactionHandler(void *actionData, char *lastReply) +{ + pSctTransact st = (pSctTransact) actionData; + + if (st->sent == 0) { + st->sent = 1; + return st->command; + } else { + st->sent = 2; + SCWrite(st->con, lastReply, eValue); + return NULL; + } } -static int SctTransactMatch(void *d1, void *d2){ - return d1 == d2; +static int SctTransactMatch(void *d1, void *d2) +{ + return d1 == d2; } -static int SctTransactCmd(pSICSOBJ ccmd, SConnection *con, - Hdb *cmdNode, Hdb *par[], int nPar) { - pSctTransact st = NULL; - SctController *c; - - c = (SctController *)ccmd->pPrivate; - - st = calloc(sizeof(SctTransact),1); - if(st == NULL){ - SCWrite(con,"ERROR: out of memory in SctTransactCommand", eError); - return 0; - } - st->con = SCCopyConnection(con); - st->command = strdup(par[0]->value.v.text); - - DevQueue(c->devser, st, WritePRIO, - TransactionHandler, SctTransactMatch, NULL); - while(st->sent != 2){ - TaskYield(pServ->pTasker); - if(SCGetInterrupt(con) != eContinue){ - break; - } - } - KillSctTransact(st); - return 1; +static int SctTransactCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ + pSctTransact st = NULL; + SctController *c; + + c = (SctController *) ccmd->pPrivate; + + st = calloc(sizeof(SctTransact), 1); + if (st == NULL) { + SCWrite(con, "ERROR: out of memory in SctTransactCommand", eError); + return 0; + } + st->con = SCCopyConnection(con); + st->command = strdup(par[0]->value.v.text); + + DevQueue(c->devser, st, WritePRIO, + TransactionHandler, SctTransactMatch, NULL); + while (st->sent != 2) { + TaskYield(pServ->pTasker); + if (SCGetInterrupt(con) != eContinue) { + break; + } + } + KillSctTransact(st); + return 1; } -static int SctSendCmd(pSICSOBJ ccmd, SConnection *con, - Hdb *cmdNode, Hdb *par[], int nPar) { - pSctTransact st = NULL; - SctController *c; - char *prioText = NULL; - int prio; - - c = (SctController *)ccmd->pPrivate; - - st = calloc(sizeof(SctTransact),1); - if(st == NULL){ - SCWrite(con,"ERROR: out of memory in SctSendCmd", eError); - return 0; - } - st->con = SCCopyConnection(con); - st->command = strdup(par[0]->value.v.text); - - prioText = ParText(cmdNode, "prio", nPar, "write"); - prio = DevText2Prio(prioText); - if(prio == NullPRIO){ - prio = WritePRIO; - } - - DevQueue(c->devser, st, prio, - TransactionHandler, SctTransactMatch, KillSctTransact); - return 1; +static int SctSendCmd(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ + pSctTransact st = NULL; + SctController *c; + char *prioText = NULL; + int prio; + + c = (SctController *) ccmd->pPrivate; + + st = calloc(sizeof(SctTransact), 1); + if (st == NULL) { + SCWrite(con, "ERROR: out of memory in SctSendCmd", eError); + return 0; + } + st->con = SCCopyConnection(con); + st->command = strdup(par[0]->value.v.text); + + prioText = ParText(cmdNode, "prio", nPar, "write"); + prio = DevText2Prio(prioText); + if (prio == NullPRIO) { + prio = WritePRIO; + } + + DevQueue(c->devser, st, prio, + TransactionHandler, SctTransactMatch, KillSctTransact); + return 1; } -static int SctDisconnect(pSICSOBJ ccmd, SConnection *con, - Hdb *cmdNode, Hdb *par[], int nPar) { - SctController *c; - - c = (SctController *)ccmd->pPrivate; - DevDisconnect(c->devser); - return 1; +static int SctDisconnect(pSICSOBJ ccmd, SConnection * con, + Hdb * cmdNode, Hdb * par[], int nPar) +{ + SctController *c; + + c = (SctController *) ccmd->pPrivate; + DevDisconnect(c->devser); + return 1; } -static hdbCallbackReturn SctDebugCallback(Hdb *node, void *userData, - hdbMessage *msg) { +static hdbCallbackReturn SctDebugCallback(Hdb * node, void *userData, + hdbMessage * msg) +{ hdbDataMessage *mm; SctController *controller = userData; SConnection *con; int i; - + mm = GetHdbSetMessage(msg); if (mm != NULL) { i = mm->v->v.intValue; @@ -925,41 +976,43 @@ static hdbCallbackReturn SctDebugCallback(Hdb *node, void *userData, return hdbContinue; } -static void SctKillController(void *c) { +static void SctKillController(void *c) +{ SctController *controller = c; SConnection *con; - + CleanStack(controller->node); RemoveSICSInternalCallback(controller); if (controller->conn) { - SCDeleteConnection(controller->conn); + SCDeleteConnection(controller->conn); } DevKill(controller->devser); free(controller); } -static int SctMakeController(SConnection *con, SicsInterp *sics, - void *object, int argc, char *argv[]) { +static int SctMakeController(SConnection * con, SicsInterp * sics, + void *object, int argc, char *argv[]) +{ SICSOBJ *ccmd; Hdb *parent, *par, *cmd; char *nodeName; hdbCallback *cb; SctController *controller; - + if (argc < 2) { SCPrintf(con, eError, - "ERROR: should be %s ...", - argv[0]); + "ERROR: should be %s ...", argv[0]); return 0; } - + parent = FindHdbParent(NULL, argv[1], &nodeName, con); - if (parent == NULL) return 0; /* error message already written */ - + if (parent == NULL) + return 0; /* error message already written */ + controller = calloc(1, sizeof(*controller)); assert(controller); controller->verbose = 0; - + ccmd = MakeSICSOBJv(nodeName, "SctController", HIPNONE, usSpy); controller->node = ccmd->objectNode; controller->conn = SCCreateDummyConnection(pServ->pSics); @@ -972,62 +1025,65 @@ static int SctMakeController(SConnection *con, SicsInterp *sics, AddHipadabaChild(parent, controller->node, con); controller->devser = DevMake(con, argc - 2, argv + 2); - if (!controller->devser) return 0; - + if (!controller->devser) + return 0; + AddCommand(pServ->pSics, nodeName, InvokeSICSOBJ, KillSICSOBJ, ccmd); SetDescriptorKey(ccmd->pDes, "creationCommand", "0"); cmd = AddSICSHdbPar(controller->node, - "poll", usMugger, MakeSICSFunc(SctPollCmd)); - AddSICSHdbPar(cmd, "node", usMugger, MakeHdbText("")); - AddSICSHdbPar(cmd, "interval", usMugger, MakeHdbFloat(5.0)); - AddSICSHdbPar(cmd, "prio", usMugger, MakeHdbText("read")); - AddSICSHdbPar(cmd, "action", usMugger, MakeHdbText("read")); - - cmd = AddSICSHdbPar(controller->node, - "unpoll", usMugger, MakeSICSFunc(SctUnpollCmd)); - AddSICSHdbPar(cmd, "node", usMugger, MakeHdbText("")); - AddSICSHdbPar(cmd, "action", usMugger, MakeHdbText("read")); - - cmd = AddSICSHdbPar(controller->node, - "connect", usMugger, MakeSICSFunc(SctConnectCmd)); - AddSICSHdbPar(cmd, "node", usMugger, MakeHdbText("")); - - cmd = AddSICSHdbPar(controller->node, - "write", usMugger, MakeSICSFunc(SctWriteCmd)); + "poll", usMugger, MakeSICSFunc(SctPollCmd)); AddSICSHdbPar(cmd, "node", usMugger, MakeHdbText("")); - + AddSICSHdbPar(cmd, "interval", usMugger, MakeHdbFloat(5.0)); + AddSICSHdbPar(cmd, "prio", usMugger, MakeHdbText("read")); + AddSICSHdbPar(cmd, "action", usMugger, MakeHdbText("read")); cmd = AddSICSHdbPar(controller->node, - "queue", usMugger, MakeSICSFunc(SctQueueCmd)); + "unpoll", usMugger, MakeSICSFunc(SctUnpollCmd)); + AddSICSHdbPar(cmd, "node", usMugger, MakeHdbText("")); + AddSICSHdbPar(cmd, "action", usMugger, MakeHdbText("read")); + + cmd = AddSICSHdbPar(controller->node, + "connect", usMugger, MakeSICSFunc(SctConnectCmd)); + AddSICSHdbPar(cmd, "node", usMugger, MakeHdbText("")); + + cmd = AddSICSHdbPar(controller->node, + "write", usMugger, MakeSICSFunc(SctWriteCmd)); + AddSICSHdbPar(cmd, "node", usMugger, MakeHdbText("")); + + + cmd = AddSICSHdbPar(controller->node, + "queue", usMugger, MakeSICSFunc(SctQueueCmd)); AddSICSHdbPar(cmd, "node", usMugger, MakeHdbText("")); AddSICSHdbPar(cmd, "prio", usMugger, MakeHdbText("write")); AddSICSHdbPar(cmd, "action", usMugger, MakeHdbText("write")); cmd = AddSICSHdbPar(controller->node, - "transact", usMugger, MakeSICSFunc(SctTransactCmd)); + "transact", usMugger, MakeSICSFunc(SctTransactCmd)); AddSICSHdbPar(cmd, "data", usMugger, MakeHdbText("")); cmd = AddSICSHdbPar(controller->node, - "send", usMugger, MakeSICSFunc(SctSendCmd)); + "send", usMugger, MakeSICSFunc(SctSendCmd)); AddSICSHdbPar(cmd, "data", usMugger, MakeHdbText("")); AddSICSHdbPar(cmd, "prio", usMugger, MakeHdbText("")); - + cmd = AddSICSHdbPar(controller->node, - "disconnect", usMugger, MakeSICSFunc(SctDisconnect)); - + "disconnect", usMugger, MakeSICSFunc(SctDisconnect)); + par = AddSICSHdbPar(controller->node, "debug", usUser, MakeHdbInt(-1)); cb = MakeHipadabaCallback(SctDebugCallback, controller, NULL); - if (cb) AppendHipadabaCallback(par, cb); - + if (cb) + AppendHipadabaCallback(par, cb); + return 1; } -void SctKill(void *object) { +void SctKill(void *object) +{ assert(sct == object); ContextItem *p, *q; - + for (p = sct->nodes; p != NULL; p = q) { q = p->next; free(p); @@ -1043,8 +1099,10 @@ void SctKill(void *object) { sct = NULL; } -void SctInit(void) { - if (sct) return; +void SctInit(void) +{ + if (sct) + return; sct = calloc(1, sizeof(*sct)); assert(sct); sct->desc = CreateDescriptor("ScriptContext"); @@ -1052,6 +1110,7 @@ void SctInit(void) { AddCmd("makesctcontroller", SctMakeController); } -int SctVerbose(SctController *c){ - return c->verbose; +int SctVerbose(SctController * c) +{ + return c->verbose; } diff --git a/scriptcontext.h b/scriptcontext.h index 30c5bc87..660f4b68 100644 --- a/scriptcontext.h +++ b/scriptcontext.h @@ -6,7 +6,7 @@ /* \brief an sct controller */ -typedef struct SctController SctController; +typedef struct SctController SctController; /** \brief queue node action to a controller * @@ -16,9 +16,9 @@ typedef struct SctController SctController; * \param action the initial state * \param con an optional connection to be used by the action scripts */ -void SctQueueNode(SctController *controller, Hdb *node, - DevPrio prio, char *action, SConnection *con); - +void SctQueueNode(SctController * controller, Hdb * node, + DevPrio prio, char *action, SConnection * con); + /** \brief call a script and configure the sct command to be used * in connection with the given node and controller * @@ -27,12 +27,12 @@ void SctQueueNode(SctController *controller, Hdb *node, * \param the node to which the sct command * \return 0 when this was a new action, > 0 when an action was overwritten */ -int SctCallInContext(SConnection *con, char *script, Hdb *node, - SctController *controller, char **resPtr); +int SctCallInContext(SConnection * con, char *script, Hdb * node, + SctController * controller, char **resPtr); /** * test the controller verbose flag * \param c The SctController to test * \return 1 for verbose, 0 for silent */ -int SctVerbose(SctController *c); +int SctVerbose(SctController * c); #endif diff --git a/sctdriveadapter.c b/sctdriveadapter.c index 6b496fee..cdc60fe3 100644 --- a/sctdriveadapter.c +++ b/sctdriveadapter.c @@ -24,40 +24,45 @@ #include "scriptcontext.h" /*---------------------------------------------------------------*/ typedef struct { - pObjectDescriptor pDes; - pIDrivable pDriv; - pHdb node; - SctController *c; -}SctDrive, *pSctDrive; + pObjectDescriptor pDes; + pIDrivable pDriv; + pHdb node; + SctController *c; +} SctDrive, *pSctDrive; /*---------------------------------------------------------------*/ -static void *SCTDRIVGetInterface(void *data, int iD){ - pSctDrive self = NULL; - - self = (pSctDrive)data; - if(self != NULL && iD == DRIVEID){ - if (self->node == NULL) return NULL; - return self->pDriv; - } else { - return NULL; - } - return NULL; +static void *SCTDRIVGetInterface(void *data, int iD) +{ + pSctDrive self = NULL; + + self = (pSctDrive) data; + if (self != NULL && iD == DRIVEID) { + if (self->node == NULL) + return NULL; + return self->pDriv; + } else { + return NULL; + } + return NULL; } + /*---------------------------------------------------------------- This routine can return either OKOK or HWFault when thing go wrong. However, the return value of Halt is usually ignored! ------------------------------------------------------------------*/ -static int SCTDRIVHalt(void *data) { - pSctDrive self = NULL; - char dummy[16]; - - self = (pSctDrive)data; - if (GetHdbProperty(self->node,"halt", dummy, sizeof dummy)) { - SctQueueNode(self->c, self->node, HaltPRIO, "halt", NULL); - } else if (GetHdbProperty(self->node, "status", dummy, sizeof dummy)) { - SetHdbProperty(self->node, "status", "idle"); - } - return OKOK; +static int SCTDRIVHalt(void *data) +{ + pSctDrive self = NULL; + char dummy[16]; + + self = (pSctDrive) data; + if (GetHdbProperty(self->node, "halt", dummy, sizeof dummy)) { + SctQueueNode(self->c, self->node, HaltPRIO, "halt", NULL); + } else if (GetHdbProperty(self->node, "status", dummy, sizeof dummy)) { + SetHdbProperty(self->node, "status", "idle"); + } + return OKOK; } + /*---------------------------------------------------------------- This routine can return either 1 or 0. 1 means the position can be reached, 0 NOT @@ -65,30 +70,32 @@ static int SCTDRIVHalt(void *data) { about which limit was violated ------------------------------------------------------------------*/ static int SCTDRIVCheckLimits(void *data, float val, - char *error, int errlen){ - pSctDrive self = NULL; - char script[1024]; - int status; - Tcl_Interp *pTcl = NULL; - char *result; - - self = (pSctDrive)data; - snprintf(script,1024,"%f", val); - SetHdbProperty(self->node,"target", script); - if(GetHdbProperty(self->node,"checklimits",script,1024)){ - status = SctCallInContext(pServ->dummyCon, script, - self->node, self->c, &result); - if(SctVerbose(self->c)){ - SCPrintf(pServ->dummyCon, eWarning, "script %s called with result %s\n ", - script, result); - } - if(status == 0){ - strncpy(error,result,errlen); - return 0; - } + char *error, int errlen) +{ + pSctDrive self = NULL; + char script[1024]; + int status; + Tcl_Interp *pTcl = NULL; + char *result; + + self = (pSctDrive) data; + snprintf(script, 1024, "%f", val); + SetHdbProperty(self->node, "target", script); + if (GetHdbProperty(self->node, "checklimits", script, 1024)) { + status = SctCallInContext(pServ->dummyCon, script, + self->node, self->c, &result); + if (SctVerbose(self->c)) { + SCPrintf(pServ->dummyCon, eWarning, + "script %s called with result %s\n ", script, result); } - return 1; + if (status == 0) { + strncpy(error, result, errlen); + return 0; + } + } + return 1; } + /*---------------------------------------------------------------- This routine can return 0 when a limit problem occurred OKOK when the motor was successfully started @@ -98,22 +105,24 @@ static int SCTDRIVCheckLimits(void *data, float val, to start the motor in question val is the value to drive the motor too ------------------------------------------------------------------*/ -static long SCTDRIVSetValue(void *data, SConnection *pCon, float val){ - pSctDrive self = NULL; - int status; - hdbValue v; - - self = (pSctDrive)data; - v.dataType = HIPFLOAT; - v.v.doubleValue = (double)val; - SetHdbProperty(self->node,"writestatus", "start"); - status = SetHipadabaPar(self->node, v, pCon); - if(status == 1){ - return OKOK; - } else { - return HWFault; - } +static long SCTDRIVSetValue(void *data, SConnection * pCon, float val) +{ + pSctDrive self = NULL; + int status; + hdbValue v; + + self = (pSctDrive) data; + v.dataType = HIPFLOAT; + v.v.doubleValue = (double) val; + SetHdbProperty(self->node, "writestatus", "start"); + status = SetHipadabaPar(self->node, v, pCon); + if (status == 1) { + return OKOK; + } else { + return HWFault; + } } + /*---------------------------------------------------------------- Checks the status of a running motor. Possible return values HWBusy The motor is still running @@ -124,199 +133,214 @@ static long SCTDRIVSetValue(void *data, SConnection *pCon, float val){ For real motors CheckStatus again shall try hard to fix any issues with the motor ------------------------------------------------------------------*/ -static int SCTDRIVCheckStatus(void *data, SConnection *pCon){ - pSctDrive self = NULL; - char script[1024]; - int status; - Tcl_Interp *pTcl = NULL; - char *result; - SConnection *con; - - self = (pSctDrive)data; - - /* - * check if the write command has gone through - */ - if(GetHdbProperty(self->node,"writestatus", script,1024)){ - if(strcmp(script,"start") == 0){ - return HWBusy; - } - } - - /* - * run the checkstatus script - */ - if(!GetHdbProperty(self->node,"checkstatus",script,1024)){ - if (!GetHdbProperty(self->node,"status",script,1024)){ - SCWrite(pCon, - "ERROR: configuration problem: no checkstatus script!", eError); - return HWFault; - } - result = script; - } else { - status = SctCallInContext(pCon,script, self->node, - self->c, &result); - if (status == 0) { - SCPrintf(pCon,eError," script %s returned %s", - script, result); - return HWFault; - } - if(SctVerbose(self->c)){ - SCPrintf(pCon,eError," script %s returned %s", - script, result); - } - } - if(strstr(result,"busy") != NULL){ +static int SCTDRIVCheckStatus(void *data, SConnection * pCon) +{ + pSctDrive self = NULL; + char script[1024]; + int status; + Tcl_Interp *pTcl = NULL; + char *result; + SConnection *con; + + self = (pSctDrive) data; + + /* + * check if the write command has gone through + */ + if (GetHdbProperty(self->node, "writestatus", script, 1024)) { + if (strcmp(script, "start") == 0) { return HWBusy; - } else if(strstr(result,"posfault") != NULL){ - return HWPosFault; - } else if(strstr(result,"fault") != NULL){ - return HWFault; - } else if(strstr(result,"idle") != NULL){ - return HWIdle; - } else { - SCPrintf(pCon,eError, - "ERROR: invalid status code %s returned from checkstatus script", - result); + } + } + + /* + * run the checkstatus script + */ + if (!GetHdbProperty(self->node, "checkstatus", script, 1024)) { + if (!GetHdbProperty(self->node, "status", script, 1024)) { + SCWrite(pCon, + "ERROR: configuration problem: no checkstatus script!", + eError); return HWFault; } + result = script; + } else { + status = SctCallInContext(pCon, script, self->node, self->c, &result); + if (status == 0) { + SCPrintf(pCon, eError, " script %s returned %s", script, result); + return HWFault; + } + if (SctVerbose(self->c)) { + SCPrintf(pCon, eError, " script %s returned %s", script, result); + } + } + if (strstr(result, "busy") != NULL) { + return HWBusy; + } else if (strstr(result, "posfault") != NULL) { + return HWPosFault; + } else if (strstr(result, "fault") != NULL) { return HWFault; + } else if (strstr(result, "idle") != NULL) { + return HWIdle; + } else { + SCPrintf(pCon, eError, + "ERROR: invalid status code %s returned from checkstatus script", + result); + return HWFault; + } + return HWFault; } + /*---------------------------------------------------------------- GetValue is supposed to read a motor position On errors, -99999999.99 is returned and messages printed to pCon ------------------------------------------------------------------*/ -static float SCTDRIVGetValue(void *data, SConnection *pCon){ - pSctDrive self = NULL; - float val = -99999999.99; - int status; - char error[256]; - hdbValue v; - - self = (pSctDrive)data; - if(GetHdbProperty(self->node,"geterror", error, 256)){ - SCWrite(pCon,error, eError); - return val; - } - return (float)self->node->value.v.doubleValue; +static float SCTDRIVGetValue(void *data, SConnection * pCon) +{ + pSctDrive self = NULL; + float val = -99999999.99; + int status; + char error[256]; + hdbValue v; + + self = (pSctDrive) data; + if (GetHdbProperty(self->node, "geterror", error, 256)) { + SCWrite(pCon, error, eError); + return val; + } + return (float) self->node->value.v.doubleValue; } + /*---------------------------------------------------------------- returns NULL on failure, a new datastructure else ------------------------------------------------------------------*/ -static pSctDrive SCTDRIVMakeObject(){ - pSctDrive self = NULL; +static pSctDrive SCTDRIVMakeObject() +{ + pSctDrive self = NULL; - self = calloc(sizeof(SctDrive),1); - if(self == NULL){ - return NULL; - } - self->pDes = CreateDescriptor("SctDriveAdapter"); - self->pDriv = CreateDrivableInterface(); - if(self->pDes == NULL || self->pDriv == NULL){ - free(self); - return NULL; - } - - self->pDes->GetInterface = SCTDRIVGetInterface; - self->pDriv->Halt = SCTDRIVHalt; - self->pDriv->CheckLimits = SCTDRIVCheckLimits; - self->pDriv->SetValue = SCTDRIVSetValue; - self->pDriv->CheckStatus = SCTDRIVCheckStatus; - self->pDriv->GetValue = SCTDRIVGetValue; + self = calloc(sizeof(SctDrive), 1); + if (self == NULL) { + return NULL; + } + self->pDes = CreateDescriptor("SctDriveAdapter"); + self->pDriv = CreateDrivableInterface(); + if (self->pDes == NULL || self->pDriv == NULL) { + free(self); + return NULL; + } - return self; + self->pDes->GetInterface = SCTDRIVGetInterface; + self->pDriv->Halt = SCTDRIVHalt; + self->pDriv->CheckLimits = SCTDRIVCheckLimits; + self->pDriv->SetValue = SCTDRIVSetValue; + self->pDriv->CheckStatus = SCTDRIVCheckStatus; + self->pDriv->GetValue = SCTDRIVGetValue; + + return self; } + /*-----------------------------------------------------------------*/ -static int SctDriveCommand(SConnection *pCon, SicsInterp *sics, void *object, - int argc, char *argv[]) { - pSctDrive self = (pSctDrive)object; - float val; - - assert(self != NULL); - - if (self->node == NULL) { - SCWrite(pCon, "ERROR: defunct object", eError); - return 0; - } - /* - * only action: print value - */ - val = self->pDriv->GetValue(self,pCon); - SCPrintf(pCon,eValue,"%s = %f", argv[0], val); - return 1; +static int SctDriveCommand(SConnection * pCon, SicsInterp * sics, + void *object, int argc, char *argv[]) +{ + pSctDrive self = (pSctDrive) object; + float val; + + assert(self != NULL); + + if (self->node == NULL) { + SCWrite(pCon, "ERROR: defunct object", eError); + return 0; + } + /* + * only action: print value + */ + val = self->pDriv->GetValue(self, pCon); + SCPrintf(pCon, eValue, "%s = %f", argv[0], val); + return 1; } + /*----------------------------------------------------------------*/ -static void SctDriveKill(void *data){ - pSctDrive self = (pSctDrive)data; - - if(self == NULL){ - return; - } - if(self->pDriv != NULL){ - free(self->pDriv); - } - if(self->pDes != NULL){ - DeleteDescriptor(self->pDes); - } - free(self); +static void SctDriveKill(void *data) +{ + pSctDrive self = (pSctDrive) data; + + if (self == NULL) { + return; + } + if (self->pDriv != NULL) { + free(self->pDriv); + } + if (self->pDes != NULL) { + DeleteDescriptor(self->pDes); + } + free(self); } + /*----------------------------------------------------------------*/ -static hdbCallbackReturn SctDummyCallback(Hdb *node, void *userData, - hdbMessage *msg) { +static hdbCallbackReturn SctDummyCallback(Hdb * node, void *userData, + hdbMessage * msg) +{ return hdbContinue; } + /*----------------------------------------------------------------*/ -static void SctDriveDeleteNode(void *data) { - pSctDrive self = (pSctDrive)data; +static void SctDriveDeleteNode(void *data) +{ + pSctDrive self = (pSctDrive) data; self->node = NULL; } + /*---------------------------------------------------------------*/ -int SctMakeDriveAdapter(SConnection *pCon, SicsInterp *pSics, void *object, - int argc, char *argv[]) { - pSctDrive pNew = NULL; - pSICSOBJ obj = NULL; +int SctMakeDriveAdapter(SConnection * pCon, SicsInterp * pSics, + void *object, int argc, char *argv[]) +{ + pSctDrive pNew = NULL; + pSICSOBJ obj = NULL; hdbCallback *cb; - - pNew = SCTDRIVMakeObject(); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory in SctMakeDriveAdapter", - eError); - return 0; - } - - if(argc < 4){ - SCWrite(pCon,"ERROR: not enough arguments for SctMakeDriveAdapter", eError); - return 0; - } - - pNew->node = FindHdbNode(NULL,argv[2], pCon); - obj = FindCommandData(pSics,argv[3], "SctController"); - if(pNew->node == NULL || obj == NULL){ - SCWrite(pCon,"ERROR: node or controller not found", eError); - SctDriveKill(pNew); - return 0; - } - pNew->c =(SctController *)obj->pPrivate; - - if (strcasecmp(argv[0],"dynsctdrive") == 0) { + + pNew = SCTDRIVMakeObject(); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory in SctMakeDriveAdapter", eError); + return 0; + } + + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough arguments for SctMakeDriveAdapter", + eError); + return 0; + } + + pNew->node = FindHdbNode(NULL, argv[2], pCon); + obj = FindCommandData(pSics, argv[3], "SctController"); + if (pNew->node == NULL || obj == NULL) { + SCWrite(pCon, "ERROR: node or controller not found", eError); + SctDriveKill(pNew); + return 0; + } + pNew->c = (SctController *) obj->pPrivate; + + if (strcasecmp(argv[0], "dynsctdrive") == 0) { /* make object dynamic by defining a descriptor command */ SetDescriptorKey(pNew->pDes, "creationCommand", "0"); } - AddCommand(pSics, argv[1], SctDriveCommand, SctDriveKill, pNew); - SetHdbProperty(pNew->node,"sicsdev",argv[1]); - + AddCommand(pSics, argv[1], SctDriveCommand, SctDriveKill, pNew); + SetHdbProperty(pNew->node, "sicsdev", argv[1]); + cb = MakeHipadabaCallback(SctDummyCallback, pNew, SctDriveDeleteNode); assert(cb); AppendHipadabaCallback(pNew->node, cb); - - return 1; -} -/*---------------------------------------------------------------*/ -int SctMakeDriveObject(SConnection *pCon, SicsInterp *pSics, void *object, - int argc, char *argv[]); -void SctDriveInit(void) { + return 1; +} + +/*---------------------------------------------------------------*/ +int SctMakeDriveObject(SConnection * pCon, SicsInterp * pSics, + void *object, int argc, char *argv[]); + +void SctDriveInit(void) +{ AddCmd("makesctdrive", SctMakeDriveAdapter); AddCmd("dynsctdrive", SctMakeDriveAdapter); - AddCmd("makesctdriveobj",SctMakeDriveObject); + AddCmd("makesctdriveobj", SctMakeDriveObject); } diff --git a/sctdriveobj.c b/sctdriveobj.c index e747a863..a9d20e94 100644 --- a/sctdriveobj.c +++ b/sctdriveobj.c @@ -14,43 +14,67 @@ #include typedef struct { - pIDrivable pDriv; - SctController *c; - int doNotKillNode; + pIDrivable pDriv; + SctController *c; + int doNotKillNode; + SConnection *pCon; } DrivObjPriv, *pDrivObjPriv; -/*---------------------------------------------------------------*/ -static void *SCTDRIVGetInterface(void *data, int iD){ - pSICSOBJ self = NULL; - pDrivObjPriv pPriv; - - self = (pSICSOBJ)data; - pPriv = (pDrivObjPriv)self->pPrivate; - if(self != NULL && pPriv != NULL && iD == DRIVEID){ - if (self->objectNode == NULL) return NULL; - return pPriv->pDriv; - } else { - return NULL; - } - return NULL; +/*--------------------------------------------------------------*/ +static void KillDrivePriv(void *data) +{ + pDrivObjPriv priv = (pDrivObjPriv)data; + if(priv == NULL){ + return; + } + if(priv->pDriv != NULL){ + free(priv->pDriv); + } + if(priv->pCon != NULL){ + SCDeleteConnection(priv->pCon); + } + free(priv); } +/*---------------------------------------------------------------*/ +static void *SCTDRIVGetInterface(void *data, int iD) +{ + pSICSOBJ self = NULL; + pDrivObjPriv pPriv; + + self = (pSICSOBJ) data; + pPriv = (pDrivObjPriv) self->pPrivate; + if (self != NULL && pPriv != NULL && iD == DRIVEID) { + if (self->objectNode == NULL) + return NULL; + return pPriv->pDriv; + } else { + return NULL; + } + return NULL; +} + /*---------------------------------------------------------------- This routine can return either OKOK or HWFault when thing go wrong. However, the return value of Halt is usually ignored! ------------------------------------------------------------------*/ -static int SCTDRIVHalt(void *data) { - pSICSOBJ self = NULL; - pDrivObjPriv pPriv; - char dummy[16]; - - self = (pSICSOBJ)data; - pPriv = (pDrivObjPriv)self->pPrivate; - if (GetHdbProperty(self->objectNode,"halt", dummy, sizeof dummy)) { - SctQueueNode(pPriv->c, self->objectNode, HaltPRIO, "halt", NULL); - } else if (GetHdbProperty(self->objectNode, "status", dummy, sizeof dummy)) { - SetHdbProperty(self->objectNode, "status", "idle"); - } - return OKOK; +static int SCTDRIVHalt(void *data) +{ + pSICSOBJ self = NULL; + pDrivObjPriv pPriv; + char dummy[16]; + + self = (pSICSOBJ) data; + pPriv = (pDrivObjPriv) self->pPrivate; + if (GetHdbProperty(self->objectNode, "halt", dummy, sizeof dummy)) { + SctQueueNode(pPriv->c, self->objectNode, HaltPRIO, "halt", + pPriv->pCon); + } else + if (GetHdbProperty(self->objectNode, "status", dummy, sizeof dummy)) + { + SetHdbProperty(self->objectNode, "status", "idle"); + } + return OKOK; } + /*---------------------------------------------------------------- This routine can return either 1 or 0. 1 means the position can be reached, 0 NOT @@ -58,32 +82,34 @@ static int SCTDRIVHalt(void *data) { about which limit was violated ------------------------------------------------------------------*/ static int SCTDRIVCheckLimits(void *data, float val, - char *error, int errlen){ - pSICSOBJ self = NULL; - pDrivObjPriv pPriv; - char script[1024]; - int status; - Tcl_Interp *pTcl = NULL; - char *result; - - self = (pSICSOBJ)data; - pPriv = (pDrivObjPriv)self->pPrivate; - snprintf(script,1024,"%f", val); - SetHdbProperty(self->objectNode,"target", script); - if(GetHdbProperty(self->objectNode,"checklimits",script,1024)){ - status = SctCallInContext(pServ->dummyCon, script, - self->objectNode, pPriv->c, &result); - if(SctVerbose(pPriv->c)){ - SCPrintf(pServ->dummyCon, eWarning, "script %s called with result %s\n ", - script, result); - } - if(status == 0){ - strncpy(error,result,errlen); - return 0; - } + char *error, int errlen) +{ + pSICSOBJ self = NULL; + pDrivObjPriv pPriv; + char script[1024]; + int status; + Tcl_Interp *pTcl = NULL; + char *result; + + self = (pSICSOBJ) data; + pPriv = (pDrivObjPriv) self->pPrivate; + snprintf(script, 1024, "%f", val); + SetHdbProperty(self->objectNode, "target", script); + if (GetHdbProperty(self->objectNode, "checklimits", script, 1024)) { + status = SctCallInContext(pServ->dummyCon, script, + self->objectNode, pPriv->c, &result); + if (SctVerbose(pPriv->c)) { + SCPrintf(pServ->dummyCon, eWarning, + "script %s called with result %s\n ", script, result); } - return 1; + if (status == 0) { + strncpy(error, result, errlen); + return 0; + } + } + return 1; } + /*---------------------------------------------------------------- This routine can return 0 when a limit problem occurred OKOK when the motor was successfully started @@ -93,25 +119,31 @@ static int SCTDRIVCheckLimits(void *data, float val, to start the motor in question val is the value to drive the motor too ------------------------------------------------------------------*/ -static long SCTDRIVSetValue(void *data, SConnection *pCon, float val){ - pSICSOBJ self = NULL; - pDrivObjPriv pPriv; - int status; - hdbValue v; - - self = (pSICSOBJ)data; - pPriv = (pDrivObjPriv)self->pPrivate; +static long SCTDRIVSetValue(void *data, SConnection * pCon, float val) +{ + pSICSOBJ self = NULL; + pDrivObjPriv pPriv; + int status; + hdbValue v; - v.dataType = HIPFLOAT; - v.v.doubleValue = (double)val; - SetHdbProperty(self->objectNode,"writestatus", "start"); - status = SetHipadabaPar(self->objectNode, v, pCon); - if(status == 1){ - return OKOK; - } else { - return HWFault; - } + self = (pSICSOBJ) data; + pPriv = (pDrivObjPriv) self->pPrivate; + if(pPriv->pCon != NULL){ + SCDeleteConnection(pPriv->pCon); + } + pPriv->pCon = SCCopyConnection(pCon); + + v.dataType = HIPFLOAT; + v.v.doubleValue = (double) val; + SetHdbProperty(self->objectNode, "writestatus", "start"); + status = SetHipadabaPar(self->objectNode, v, pCon); + if (status == 1) { + return OKOK; + } else { + return HWFault; + } } + /*---------------------------------------------------------------- Checks the status of a running motor. Possible return values HWBusy The motor is still running @@ -122,216 +154,226 @@ static long SCTDRIVSetValue(void *data, SConnection *pCon, float val){ For real motors CheckStatus again shall try hard to fix any issues with the motor ------------------------------------------------------------------*/ -static int SCTDRIVCheckStatus(void *data, SConnection *pCon){ - pSICSOBJ self = NULL; - pDrivObjPriv pPriv; - char script[1024]; - int status; - Tcl_Interp *pTcl = NULL; - char *result; - SConnection *con; - - self = (pSICSOBJ)data; - pPriv = (pDrivObjPriv)self->pPrivate; - - /* - * check if the write command has gone through - */ - if(GetHdbProperty(self->objectNode,"writestatus", script,1024)){ - if(strcmp(script,"start") == 0){ - return HWBusy; - } - } - - /* - * run the checkstatus script - */ - if(!GetHdbProperty(self->objectNode,"checkstatus",script,1024)){ - if (!GetHdbProperty(self->objectNode,"status",script,1024)){ - SCWrite(pCon, - "ERROR: configuration problem: no checkstatus script!", eError); - return HWFault; - } - result = script; - } else { - status = SctCallInContext(pCon,script, self->objectNode, - pPriv->c, &result); - if (status == 0) { - SCPrintf(pCon,eError," script %s returned %s", - script, result); - return HWFault; - } - if(SctVerbose(pPriv->c)){ - SCPrintf(pCon,eError," script %s returned %s", - script, result); - } - } - if(strstr(result,"busy") != NULL){ +static int SCTDRIVCheckStatus(void *data, SConnection * pCon) +{ + pSICSOBJ self = NULL; + pDrivObjPriv pPriv; + char script[1024]; + int status; + Tcl_Interp *pTcl = NULL; + char *result; + SConnection *con; + + self = (pSICSOBJ) data; + pPriv = (pDrivObjPriv) self->pPrivate; + + /* + * check if the write command has gone through + */ + if (GetHdbProperty(self->objectNode, "writestatus", script, 1024)) { + if (strcmp(script, "start") == 0) { return HWBusy; - } else if(strstr(result,"posfault") != NULL){ - return HWPosFault; - } else if(strstr(result,"fault") != NULL){ - return HWFault; - } else if(strstr(result,"idle") != NULL){ - return HWIdle; - } else { - SCPrintf(pCon,eError, - "ERROR: invalid status code %s returned from checkstatus script", - result); + } + } + + /* + * run the checkstatus script + */ + if (!GetHdbProperty(self->objectNode, "checkstatus", script, 1024)) { + if (!GetHdbProperty(self->objectNode, "status", script, 1024)) { + SCWrite(pCon, + "ERROR: configuration problem: no checkstatus script!", + eError); return HWFault; } + result = script; + } else { + status = SctCallInContext(pCon, script, self->objectNode, + pPriv->c, &result); + if (status == 0) { + SCPrintf(pCon, eError, " script %s returned %s", script, result); + return HWFault; + } + if (SctVerbose(pPriv->c)) { + SCPrintf(pCon, eError, " script %s returned %s", script, result); + } + } + if (strstr(result, "busy") != NULL) { + return HWBusy; + } else if (strstr(result, "posfault") != NULL) { + return HWPosFault; + } else if (strstr(result, "fault") != NULL) { return HWFault; + } else if (strstr(result, "idle") != NULL) { + return HWIdle; + } else { + SCPrintf(pCon, eError, + "ERROR: invalid status code %s returned from checkstatus script", + result); + return HWFault; + } + return HWFault; } + /*---------------------------------------------------------------- GetValue is supposed to read a motor position On errors, -99999999.99 is returned and messages printed to pCon ------------------------------------------------------------------*/ -static float SCTDRIVGetValue(void *data, SConnection *pCon){ - pSICSOBJ self = NULL; - pDrivObjPriv pPriv; - float val = -99999999.99; - int status; - char error[256]; - hdbValue v; - - self = (pSICSOBJ)data; - pPriv = (pDrivObjPriv)self->pPrivate; - if(GetHdbProperty(self->objectNode,"geterror", error, 256)){ - SCWrite(pCon,error, eError); - return val; - } - return (float)self->objectNode->value.v.doubleValue; +static float SCTDRIVGetValue(void *data, SConnection * pCon) +{ + pSICSOBJ self = NULL; + pDrivObjPriv pPriv; + float val = -99999999.99; + int status; + char error[256]; + hdbValue v; + + self = (pSICSOBJ) data; + pPriv = (pDrivObjPriv) self->pPrivate; + if (GetHdbProperty(self->objectNode, "geterror", error, 256)) { + SCWrite(pCon, error, eError); + return val; + } + return (float) self->objectNode->value.v.doubleValue; } + /*-----------------------------------------------------------------*/ -void AssignSctDrive(pIDrivable pDriv){ - pDriv->Halt = SCTDRIVHalt; - pDriv->CheckLimits = SCTDRIVCheckLimits; - pDriv->SetValue = SCTDRIVSetValue; - pDriv->CheckStatus = SCTDRIVCheckStatus; - pDriv->GetValue = SCTDRIVGetValue; +void AssignSctDrive(pIDrivable pDriv) +{ + pDriv->Halt = SCTDRIVHalt; + pDriv->CheckLimits = SCTDRIVCheckLimits; + pDriv->SetValue = SCTDRIVSetValue; + pDriv->CheckStatus = SCTDRIVCheckStatus; + pDriv->GetValue = SCTDRIVGetValue; } + /*---------------------------------------------------------------------------*/ -static void KillDriveOBJ(void *data){ - pSICSOBJ self = (pSICSOBJ)data; - pDrivObjPriv pPriv; +static void KillDriveOBJ(void *data) +{ + pSICSOBJ self = (pSICSOBJ) data; + pDrivObjPriv pPriv; - if(self == NULL){ - return; - } + if (self == NULL) { + return; + } - pPriv = (pDrivObjPriv)self->pPrivate; - if(pPriv->doNotKillNode && self->pDes != NULL){ - if(self->pDes->name) free(self->pDes->name); - if(self->pDes->pKeys) IFDeleteOptions(self->pDes->pKeys); - free(self->pDes); - } else { - DeleteDescriptor(self->pDes); /* kill descriptor including node */ - } - if(self->KillPrivate != NULL && self->pPrivate != NULL){ - self->KillPrivate(self->pPrivate); - } - RemoveHdbNodeFromParent(self->objectNode, pServ->dummyCon); - free(self); + pPriv = (pDrivObjPriv) self->pPrivate; + if (pPriv->doNotKillNode && self->pDes != NULL) { + if (self->pDes->name) + free(self->pDes->name); + if (self->pDes->pKeys) + IFDeleteOptions(self->pDes->pKeys); + free(self->pDes); + } else { + DeleteDescriptor(self->pDes); /* kill descriptor including node */ + } + if (self->KillPrivate != NULL && self->pPrivate != NULL) { + self->KillPrivate(self->pPrivate); + } + RemoveHdbNodeFromParent(self->objectNode, pServ->dummyCon); + free(self); } + /*-----------------------------------------------------------------------------*/ -pSICSOBJ MakeSctDriveObj(pHdb node, char *class, SctController *c){ - pSICSOBJ pNew = NULL; - pDrivObjPriv pPriv = NULL; - hdbValue val; - - pNew = (pSICSOBJ)malloc(sizeof(SICSOBJ)); - pPriv = (pDrivObjPriv)malloc(sizeof(DrivObjPriv)); - if(pNew == NULL || pPriv == NULL){ - return NULL; - } - memset(pNew,0,sizeof(SICSOBJ)); - memset(pPriv,0,sizeof(DrivObjPriv)); - - pNew->pDes = CreateDescriptor(class); - pPriv->pDriv = CreateDrivableInterface(); - if(pNew->pDes == NULL || pPriv->pDriv == NULL){ - free(pNew); - free(pPriv); - return(NULL); - } - pNew->objectNode = node; - AssignSctDrive(pPriv->pDriv); - pPriv->c = c; - pNew->pDes->parNode = pNew->objectNode; - pNew->pDes->GetInterface = SCTDRIVGetInterface; - pNew->pPrivate = pPriv; - pNew->KillPrivate = DefaultKill; - return pNew; +pSICSOBJ MakeSctDriveObj(pHdb node, char *class, SctController * c) +{ + pSICSOBJ pNew = NULL; + pDrivObjPriv pPriv = NULL; + hdbValue val; + + pNew = (pSICSOBJ) malloc(sizeof(SICSOBJ)); + pPriv = (pDrivObjPriv) malloc(sizeof(DrivObjPriv)); + if (pNew == NULL || pPriv == NULL) { + return NULL; + } + memset(pNew, 0, sizeof(SICSOBJ)); + memset(pPriv, 0, sizeof(DrivObjPriv)); + + pNew->pDes = CreateDescriptor(class); + pPriv->pDriv = CreateDrivableInterface(); + if (pNew->pDes == NULL || pPriv->pDriv == NULL) { + free(pNew); + free(pPriv); + return (NULL); + } + pNew->objectNode = node; + AssignSctDrive(pPriv->pDriv); + pPriv->c = c; + pNew->pDes->parNode = pNew->objectNode; + pNew->pDes->GetInterface = SCTDRIVGetInterface; + pNew->pPrivate = pPriv; + pNew->KillPrivate = KillDrivePriv; + return pNew; } + /*-------------------------------------------------------------------------- * This actually has two syntaxes: * makesctdrive name path-to-existing-node class SctController * makesctdrive name type priv class SctController *--------------------------------------------------------------------------*/ -int SctMakeDriveObject(SConnection *pCon, SicsInterp *pSics, void *object, - int argc, char *argv[]) { - pHdb node = NULL; - pDrivObjPriv pPriv = NULL; - pSICSOBJ pNew = NULL; - pSICSOBJ pSct = NULL; - SctController *c = NULL; - int priv, type, status; - hdbValue val; - - if(argc < 5){ - SCWrite(pCon,"ERROR: not enough arguments to SctMakeDriveObject", eError); - return 0; - } - - node = FindHdbNode(NULL,argv[2], pCon); - if(node != NULL){ - pSct = FindCommandData(pSics,argv[4], "SctController"); - if(pSct == NULL){ - SCPrintf(pCon,eError, "ERROR: SctController %s not found", argv[4]); - return 0; - } - c = (SctController *)pSct->pPrivate; - pNew = MakeSctDriveObj(node,argv[3],c); - pPriv = (pDrivObjPriv)pNew->pPrivate; - pPriv->doNotKillNode = 1; /* the node is owned by someone else*/ - } else { - /* convert privilege */ - priv = decodeSICSPriv(argv[3]); - /* convert datatype */ - strtolower(argv[4]); - type = convertHdbType(argv[2]); - if (type == HIPNONE) { - node = MakeHipadabaNode(argv[1], HIPNONE, 1); - } else { - val = makeHdbValue(type,0); - node = MakeSICSHdbPar(argv[1], priv, val); - ReleaseHdbValue(&val); - } - if(node == NULL){ - SCWrite(pCon,"ERROR: node creation failed", eError); - return 0; - } - c = FindCommandData(pSics,argv[5], "SctController"); - if(c == NULL){ - SCPrintf(pCon,eError, "ERROR: SctController %s not found", argv[4]); - return 0; - } - pNew = MakeSctDriveObj(node,argv[3],c); - } - if(pNew == NULL){ - SCWrite(pCon,"ERROR: failed to create drive object", eError); - return 0; - } - status = AddCommand(pSics, - argv[1], - InterInvokeSICSOBJ, - KillDriveOBJ, - pNew); - if(status != 1){ - KillSICSOBJ(pNew); - SCPrintf(pCon,eError,"ERROR: failed create duplicate command %s", argv[1]); - return 0; - } - return 1; -} +int SctMakeDriveObject(SConnection * pCon, SicsInterp * pSics, + void *object, int argc, char *argv[]) +{ + pHdb node = NULL; + pDrivObjPriv pPriv = NULL; + pSICSOBJ pNew = NULL; + pSICSOBJ pSct = NULL; + SctController *c = NULL; + int priv, type, status; + hdbValue val; + if (argc < 5) { + SCWrite(pCon, "ERROR: not enough arguments to SctMakeDriveObject", + eError); + return 0; + } + + node = FindHdbNode(NULL, argv[2], pCon); + if (node != NULL) { + pSct = FindCommandData(pSics, argv[4], "SctController"); + if (pSct == NULL) { + SCPrintf(pCon, eError, "ERROR: SctController %s not found", argv[4]); + return 0; + } + c = (SctController *) pSct->pPrivate; + pNew = MakeSctDriveObj(node, argv[3], c); + pPriv = (pDrivObjPriv) pNew->pPrivate; + pPriv->doNotKillNode = 1; /* the node is owned by someone else */ + } else { + /* convert privilege */ + priv = decodeSICSPriv(argv[3]); + /* convert datatype */ + strtolower(argv[4]); + type = convertHdbType(argv[2]); + if (type == HIPNONE) { + node = MakeHipadabaNode(argv[1], HIPNONE, 1); + } else { + val = makeHdbValue(type, 0); + node = MakeSICSHdbPar(argv[1], priv, val); + ReleaseHdbValue(&val); + } + if (node == NULL) { + SCWrite(pCon, "ERROR: node creation failed", eError); + return 0; + } + c = FindCommandData(pSics, argv[5], "SctController"); + if (c == NULL) { + SCPrintf(pCon, eError, "ERROR: SctController %s not found", argv[4]); + return 0; + } + pNew = MakeSctDriveObj(node, argv[3], c); + } + if (pNew == NULL) { + SCWrite(pCon, "ERROR: failed to create drive object", eError); + return 0; + } + status = AddCommand(pSics, + argv[1], InterInvokeSICSOBJ, KillDriveOBJ, pNew); + if (status != 1) { + KillSICSOBJ(pNew); + SCPrintf(pCon, eError, "ERROR: failed create duplicate command %s", + argv[1]); + return 0; + } + return 1; +} diff --git a/sdynar.c b/sdynar.c index 313a0b50..843b7298 100644 --- a/sdynar.c +++ b/sdynar.c @@ -15,184 +15,171 @@ #include "sdynar.i" /*---------------------------------------------------------------------------*/ - pDynar CreateDynar(int iStart, int iEnd, int iGrain, - void (*DataFree)(void *pData)) - { - pDynar pNew = NULL; - int iSize; - - pNew = (pDynar)malloc(sizeof(Dynar)); - if(!pNew) - { - return NULL; - } - memset(pNew, 0, sizeof(Dynar)); - - pNew->iStart = iStart; - pNew->iEnd = iEnd; - pNew->iGrain = iGrain; - pNew->DataFree = DataFree; - iSize = iEnd - iStart; - assert(iSize > 0); - pNew->pArray = (void **)malloc(iSize * sizeof(void *)); - if(!pNew->pArray) - { - free(pNew); - return NULL; - } - memset(pNew->pArray,0,iSize * sizeof(void *)); - return pNew; - } -/*----------------------------------------------------------------------------*/ - void DeleteDynar(pDynar self) - { - int i, iSize; - - assert(self); - - iSize = self->iEnd - self->iStart; - for(i = 0; i < iSize; i++) - { - if(self->pArray[i]) - { - if(self->DataFree) - { - self->DataFree(self->pArray[i]); - } - } - } - free(self->pArray); - free(self); - } -/*---------------------------------------------------------------------------*/ - static int DynarResize(pDynar self, int iRequest) - { - void **pNew = NULL; - int i, iNewStart, iNewEnd, iOldSize, iNewSize, iOffset; +pDynar CreateDynar(int iStart, int iEnd, int iGrain, + void (*DataFree) (void *pData)) +{ + pDynar pNew = NULL; + int iSize; - assert(self); - iOldSize = self->iEnd - self->iStart; - - iNewStart = self->iStart; - iNewEnd = self->iEnd; - if(iRequest <= self->iStart) - { - iNewStart -= self->iGrain; - } - if(iRequest >= (self->iEnd - 1)) - { - iNewEnd += self->iGrain; - } - iNewSize = iNewEnd - iNewStart; - - pNew = (void **)malloc(iNewSize * sizeof(void *)); - if(!pNew) - { - return 0; - } - memset(pNew,0,iNewSize*sizeof(void *)); - - iOffset = self->iStart - iNewStart; - if(iOffset < 0) - { - iOffset = - iOffset; - } - for(i = 0; i < iOldSize; i++) - { - pNew[i+iOffset] = self->pArray[i]; - } - self->iStart = iNewStart; - self->iEnd = iNewEnd; - free(self->pArray); - self->pArray = pNew; - return 1; - } -/*----------------------------------------------------------------------------*/ - int DynarPut(pDynar self, int iIndex, void *pData) - { - int iReal, iRet; - - assert(self); - - if( (iIndex < self->iStart) || (iIndex > self->iEnd -1) ) - { - iRet = DynarResize(self,iIndex); - if(!iRet) - { - return 0; - } - } - - iReal = iIndex - self->iStart; - if(self->pArray[iReal]) - { - if(self->DataFree) - { - self->DataFree(self->pArray[iReal]); - } - } - self->pArray[iReal] = pData; - return 1; + pNew = (pDynar) malloc(sizeof(Dynar)); + if (!pNew) { + return NULL; } -/*-------------------------------------------------------------------------*/ - int DynarPutCopy(pDynar self, int iIndex, void *pBuffer, int iDataLen) - { - char *pPtr = NULL; - - pPtr = (char *)malloc(iDataLen); - if(!pPtr) - { + memset(pNew, 0, sizeof(Dynar)); + + pNew->iStart = iStart; + pNew->iEnd = iEnd; + pNew->iGrain = iGrain; + pNew->DataFree = DataFree; + iSize = iEnd - iStart; + assert(iSize > 0); + pNew->pArray = (void **) malloc(iSize * sizeof(void *)); + if (!pNew->pArray) { + free(pNew); + return NULL; + } + memset(pNew->pArray, 0, iSize * sizeof(void *)); + return pNew; +} + +/*----------------------------------------------------------------------------*/ +void DeleteDynar(pDynar self) +{ + int i, iSize; + + assert(self); + + iSize = self->iEnd - self->iStart; + for (i = 0; i < iSize; i++) { + if (self->pArray[i]) { + if (self->DataFree) { + self->DataFree(self->pArray[i]); + } + } + } + free(self->pArray); + free(self); +} + +/*---------------------------------------------------------------------------*/ +static int DynarResize(pDynar self, int iRequest) +{ + void **pNew = NULL; + int i, iNewStart, iNewEnd, iOldSize, iNewSize, iOffset; + + assert(self); + iOldSize = self->iEnd - self->iStart; + + iNewStart = self->iStart; + iNewEnd = self->iEnd; + if (iRequest <= self->iStart) { + iNewStart -= self->iGrain; + } + if (iRequest >= (self->iEnd - 1)) { + iNewEnd += self->iGrain; + } + iNewSize = iNewEnd - iNewStart; + + pNew = (void **) malloc(iNewSize * sizeof(void *)); + if (!pNew) { + return 0; + } + memset(pNew, 0, iNewSize * sizeof(void *)); + + iOffset = self->iStart - iNewStart; + if (iOffset < 0) { + iOffset = -iOffset; + } + for (i = 0; i < iOldSize; i++) { + pNew[i + iOffset] = self->pArray[i]; + } + self->iStart = iNewStart; + self->iEnd = iNewEnd; + free(self->pArray); + self->pArray = pNew; + return 1; +} + +/*----------------------------------------------------------------------------*/ +int DynarPut(pDynar self, int iIndex, void *pData) +{ + int iReal, iRet; + + assert(self); + + if ((iIndex < self->iStart) || (iIndex > self->iEnd - 1)) { + iRet = DynarResize(self, iIndex); + if (!iRet) { return 0; } - memcpy(pPtr,pBuffer,iDataLen); - return DynarPut(self,iIndex,pPtr); - } -/*--------------------------------------------------------------------------*/ - int DynarReplace(pDynar self, int iIndex, void *pData, int iDataLen) - { - int iReal, iRet; - - assert(self); - - if( (iIndex < self->iStart) || (iIndex >= self->iEnd -1) ) - { - iRet = DynarResize(self,iIndex); - if(!iRet) - { - return 0; - } - } - - iReal = iIndex - self->iStart; - if(self->pArray[iReal]) - { - memcpy(self->pArray[iReal],pData,iDataLen); - return 1; - } - else - { - return DynarPutCopy(self,iIndex,pData,iDataLen); - } } -/*---------------------------------------------------------------------------*/ - int DynarGet(pDynar self, int iIndex, void **pData) - { - int iReal; - - assert(self); - - iReal = iIndex - self->iStart; - *pData = self->pArray[iReal]; - return 1; + + iReal = iIndex - self->iStart; + if (self->pArray[iReal]) { + if (self->DataFree) { + self->DataFree(self->pArray[iReal]); + } } + self->pArray[iReal] = pData; + return 1; +} + /*-------------------------------------------------------------------------*/ - int DynarGetCopy(pDynar self, int iIndex, void *pData, int iDataLen) - { - int iReal; - - assert(self); - - iReal = iIndex - self->iStart; - memcpy(pData,self->pArray[iReal],iDataLen); - return 1; +int DynarPutCopy(pDynar self, int iIndex, void *pBuffer, int iDataLen) +{ + char *pPtr = NULL; + + pPtr = (char *) malloc(iDataLen); + if (!pPtr) { + return 0; } + memcpy(pPtr, pBuffer, iDataLen); + return DynarPut(self, iIndex, pPtr); +} + +/*--------------------------------------------------------------------------*/ +int DynarReplace(pDynar self, int iIndex, void *pData, int iDataLen) +{ + int iReal, iRet; + + assert(self); + + if ((iIndex < self->iStart) || (iIndex >= self->iEnd - 1)) { + iRet = DynarResize(self, iIndex); + if (!iRet) { + return 0; + } + } + + iReal = iIndex - self->iStart; + if (self->pArray[iReal]) { + memcpy(self->pArray[iReal], pData, iDataLen); + return 1; + } else { + return DynarPutCopy(self, iIndex, pData, iDataLen); + } +} + +/*---------------------------------------------------------------------------*/ +int DynarGet(pDynar self, int iIndex, void **pData) +{ + int iReal; + + assert(self); + + iReal = iIndex - self->iStart; + *pData = self->pArray[iReal]; + return 1; +} + +/*-------------------------------------------------------------------------*/ +int DynarGetCopy(pDynar self, int iIndex, void *pData, int iDataLen) +{ + int iReal; + + assert(self); + + iReal = iIndex - self->iStart; + memcpy(pData, self->pArray[iReal], iDataLen); + return 1; +} diff --git a/sdynar.h b/sdynar.h index 04d61d3b..b14542a9 100644 --- a/sdynar.h +++ b/sdynar.h @@ -13,19 +13,18 @@ #ifndef SICSDYNAR #define SICSDYNAR - typedef struct __SDynar *pDynar; +typedef struct __SDynar *pDynar; /*-------------------------------------------------------------------------*/ - pDynar CreateDynar(int iStart, int iEnd, int iGrain, - void (*DataFree)(void *pData)); - void DeleteDynar(pDynar self); +pDynar CreateDynar(int iStart, int iEnd, int iGrain, + void (*DataFree) (void *pData)); +void DeleteDynar(pDynar self); /*------------------------------------------------------------------------*/ - int DynarPut(pDynar self, int iIndex, void *pData); - int DynarPutCopy(pDynar self, int iIndex, void *pData, int iDataLen); - int DynarReplace(pDynar self, int iIndex, void *pData, int iDatLen); - - int DynarGet(pDynar self, int iIndex, void **pData); - int DynarGetCopy(pDynar self, int iIndex, void *pData, int iDataLen); +int DynarPut(pDynar self, int iIndex, void *pData); +int DynarPutCopy(pDynar self, int iIndex, void *pData, int iDataLen); +int DynarReplace(pDynar self, int iIndex, void *pData, int iDatLen); + +int DynarGet(pDynar self, int iIndex, void **pData); +int DynarGetCopy(pDynar self, int iIndex, void *pData, int iDataLen); #endif - diff --git a/sel2.c b/sel2.c index 9501c84e..01652c04 100644 --- a/sel2.c +++ b/sel2.c @@ -88,7 +88,7 @@ BRE Beginne eine Verlustleistungsmessung - ist bei Statusabruf HAL Bremse Selektor bis zum Stillstand ab (unterhalb 3000 U/min.) -*/ +*/ #include stdio.h #include descrip.h #include iodef.h @@ -101,7 +101,7 @@ HAL Bremse Selektor bis zum Stillstand ab (unterhalb 3000 U/min.) #define OK 0L #define NOT_OK !OK -#define LIMIT_U 3100 /* niedrigste Drehzahl */ +#define LIMIT_U 3100 /* niedrigste Drehzahl */ #define LIMIT_O 28300 /* Verbotene Drehzahlbereiche (Resonanzgefahr) */ @@ -119,33 +119,38 @@ HAL Bremse Selektor bis zum Stillstand ab (unterhalb 3000 U/min.) extern FILE *fs; -static short chan_s=6; +static short chan_s = 6; /* *********************************************************************** */ /* ------------------------------------------------------------------------ */ long select_setup() { -register rc; -$DESCRIPTOR(dev_descr, "TXA1:"); -chan_s=SELE_LUN; -if ((rc=sys$assign(&dev_descr, &chan_s, NULL,NULL)) != 1) - {printf("Error in Selector_SETUP: Ret = %d\n",rc); return(NOT_OK);} -return(OK); + register rc; + $DESCRIPTOR(dev_descr, "TXA1:"); + chan_s = SELE_LUN; + if ((rc = sys$assign(&dev_descr, &chan_s, NULL, NULL)) != 1) { + printf("Error in Selector_SETUP: Ret = %d\n", rc); + return (NOT_OK); + } + return (OK); } /* ------------------------------------------------------------------------ */ -/* Function liest ueberprueft das Befehlsecho */ +/* Function liest ueberprueft das Befehlsecho */ long sele_test_echo(cmd, lng) -char *cmd[]; +char *cmd[]; int lng; { -char echo[80]; -if (sele_read(&echo)!= OK) return(NOT_OK); -if (strncmp(&echo, cmd, lng) != 0) - {printf("Selector:protocol error%s\n",echo); return(NOT_OK);} - else - return(OK); -} + char echo[80]; + if (sele_read(&echo) != OK) + return (NOT_OK); + if (strncmp(&echo, cmd, lng) != 0) { + printf("Selector:protocol error%s\n", echo); + return (NOT_OK); + } else + return (OK); +} + /* ------------------------------------------------------------------------ */ /* Function prueft die Anzahl der sich im Typeahead-Buffer befindenden Bytes und liefert das naechste dort anstehende Zeichen, jedoch ohne es @@ -154,86 +159,102 @@ if (strncmp(&echo, cmd, lng) != 0) long tst_buf_s(bt) int *bt; { -int bytes; -register rc; -struct {unsigned short status, bytes; - int pid; } iosb; -if ((rc=sys$qiow(NULL,chan_s,IO$_SENSEMODE | IO$M_TYPEAHDCNT,&iosb, - NULL, NULL, &bytes, NULL, NULL, NULL, NULL, NULL)) != 1) - {print_error(fs,"Error in QIOW"); return(NOT_OK);} + int bytes; + register rc; + struct { + unsigned short status, bytes; + int pid; + } iosb; + if ((rc = sys$qiow(NULL, chan_s, IO$_SENSEMODE | IO$M_TYPEAHDCNT, &iosb, + NULL, NULL, &bytes, NULL, NULL, NULL, NULL, + NULL)) != 1) { + print_error(fs, "Error in QIOW"); + return (NOT_OK); + } /**ch = (bytes >> 16) & 0xff;*/ -*bt = bytes & 0xffff; -return(OK); + *bt = bytes & 0xffff; + return (OK); } /* ------------------------------------------------------------------------ */ long sele_read(message) -char *message; +char *message; { -char char_l[8], *ptr; -register rc; - struct {unsigned short status, bytes; - int pid; } iosb; -ptr = message; -for (;;) - { - if ((rc=sys$qiow(NULL,chan_s,IO$_READVBLK | IO$M_NOECHO, - &iosb,NULL, - NULL, char_l, 1, NULL, NULL, NULL, NULL)) != 1) - {printf("Error in QIOW, READ_MESS: %d\n", rc);return(NOT_OK);} - *ptr = char_l[0]; - /* Terminator (linefeed) ? */ - ptr++; - if (char_l[0] == '\n') break; - } -return(OK); + char char_l[8], *ptr; + register rc; + struct { + unsigned short status, bytes; + int pid; + } iosb; + ptr = message; + for (;;) { + if ((rc = sys$qiow(NULL, chan_s, IO$_READVBLK | IO$M_NOECHO, + &iosb, NULL, + NULL, char_l, 1, NULL, NULL, NULL, NULL)) != 1) { + printf("Error in QIOW, READ_MESS: %d\n", rc); + return (NOT_OK); + } + *ptr = char_l[0]; + /* Terminator (linefeed) ? */ + ptr++; + if (char_l[0] == '\n') + break; + } + return (OK); } + /* ------------------------------------------------------------------------ */ /* Pruefe ob der Selektor eine Fehlermeldung erzeugt hat und gib sie aus */ long select_error_msg(err) long *err; { -char chr[10], msg[80]; -float waiti=3.0; /* Selektor PC hat 3 Sekunden Reaktionszeit !! */ + char chr[10], msg[80]; + float waiti = 3.0; /* Selektor PC hat 3 Sekunden Reaktionszeit !! */ /* Warte ein wenig - es koennte auf den Befehl hin eine Fehlermeldung erscheinen */ -lib$wait(&waiti); + lib$wait(&waiti); /* Es koennen auch mehrere Zeilen sein */ -*err = FALSE; -for (;;) - {if (tst_buf_s(&chr) != OK) return(NOT_OK); - if (chr[0] != NULL) - { - if (sele_read(&msg) != OK) return(NOT_OK); - printf("Selektor failure:"); - printf("%s\n\7",msg); - *err = TRUE; - } - else - return(OK); - } + *err = FALSE; + for (;;) { + if (tst_buf_s(&chr) != OK) + return (NOT_OK); + if (chr[0] != NULL) { + if (sele_read(&msg) != OK) + return (NOT_OK); + printf("Selektor failure:"); + printf("%s\n\7", msg); + *err = TRUE; + } else + return (OK); + } } + /* ------------------------------------------------------------------------ */ long sele_write(message) char message[]; { -char msg[80]; -long err; -register rc; -struct - { - unsigned short status, bytes; - int pid; } iosb; + char msg[80]; + long err; + register rc; + struct { + unsigned short status, bytes; + int pid; + } iosb; -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); -if ((rc=sys$qiow(NULL,chan_s,IO$_WRITEVBLK,&iosb,NULL, NULL, - message, strlen(message), NULL, NULL, NULL, NULL)) != 1) - {printf("Error in QIOW: %d\n",rc); return(NOT_OK);} -return(OK); + if ((rc = sys$qiow(NULL, chan_s, IO$_WRITEVBLK, &iosb, NULL, NULL, + message, strlen(message), NULL, NULL, NULL, + NULL)) != 1) { + printf("Error in QIOW: %d\n", rc); + return (NOT_OK); + } + return (OK); } /* -------------------------------------------------------------------------- */ @@ -244,30 +265,38 @@ return(OK); long select_msg(tim) long tim; { -int sts; -long err; -char cmd[20] = "TIM "; -sprintf(&cmd+4,"%5u\0",tim); -sts = sele_write(cmd); -if (sele_test_echo(&cmd,3)!= OK) lib$stop(-1); -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); -return(OK); + int sts; + long err; + char cmd[20] = "TIM "; + sprintf(&cmd + 4, "%5u\0", tim); + sts = sele_write(cmd); + if (sele_test_echo(&cmd, 3) != OK) + lib$stop(-1); + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); + return (OK); } + /* -------------------------------------------------------------------------- */ /* Einschaltung der Fremdsteuerung des Selektors Diese Funktion ist z.Z. nur vom Selektor-PC aktivierbar */ long select_remote() { -int sts; -long err; -char cmd[] = "REM"; -sts = sele_write(cmd); -if (sele_test_echo(&cmd,3)!= OK) lib$stop(-1); -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); + int sts; + long err; + char cmd[] = "REM"; + sts = sele_write(cmd); + if (sele_test_echo(&cmd, 3) != OK) + lib$stop(-1); + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); } + /* -------------------------------------------------------------------------- */ /* Ausschaltung der Fremdsteuerung des Selektors - ein Steuerung kann dann nur noch ueber den PC des Geraetes @@ -276,41 +305,53 @@ if (err == TRUE) return(NOT_OK); */ long select_local() { -int sts; -long err; -char cmd[] = "TTY"; -sts = sele_write(cmd); -if (sele_test_echo(&cmd,3)!= OK) lib$stop(-1); -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); + int sts; + long err; + char cmd[] = "TTY"; + sts = sele_write(cmd); + if (sele_test_echo(&cmd, 3) != OK) + lib$stop(-1); + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); } + /* -------------------------------------------------------------------------- */ /* Starten des Selektors nach Stillstand auf die Minimaldrehzahl */ long select_start() { -int sts; -long err; -char cmd[] = "SST"; -sts = sele_write(cmd); -if (sele_test_echo(&cmd,3)!= OK) lib$stop(-1); -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); + int sts; + long err; + char cmd[] = "SST"; + sts = sele_write(cmd); + if (sele_test_echo(&cmd, 3) != OK) + lib$stop(-1); + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); } + /* -------------------------------------------------------------------------- */ /* Bremsen des Selektors bis zum Stillstand; eine Drehzahlanzeige unterhalb 3000 U/min ist nicht moeglich. */ long select_stop() { -int sts; -long err; -char cmd[] = "HAL"; -sts = sele_write(cmd); -if (sele_test_echo(&cmd,3)!= OK) lib$stop(-1); -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); + int sts; + long err; + char cmd[] = "HAL"; + sts = sele_write(cmd); + if (sele_test_echo(&cmd, 3) != OK) + lib$stop(-1); + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); } + /* -------------------------------------------------------------------------- */ /* Einschalten des geregelten Betriebes mit dem Setzen eines Sollwertes der Drehzahl. @@ -321,29 +362,30 @@ if (err == TRUE) return(NOT_OK); long select_set_rpm(rpm) int rpm; { -int sts; -long err; -char cmd[] = "SDR", s_dat[10] = "SDR 00000"; -if ((rpm < LIMIT_U) || (rpm > LIMIT_O)) - { - print_error(fs,"nominal value out of allowed range"); - return; - } + int sts; + long err; + char cmd[] = "SDR", s_dat[10] = "SDR 00000"; + if ((rpm < LIMIT_U) || (rpm > LIMIT_O)) { + print_error(fs, "nominal value out of allowed range"); + return; + } /* Resonanzbereiche sind auch verboten */ -if ( -((rpm >= RESONANZ_1U) && (rpm <= RESONANZ_1O)) || -((rpm >= RESONANZ_2U) && (rpm <= RESONANZ_2O)) || -((rpm >= RESONANZ_3U) && (rpm <= RESONANZ_3O))) - { - print_error(fs,"nominal value within inhibited range"); - return; - } -sprintf(&s_dat+4,"%5u",rpm); -sts = sele_write(s_dat); -if (sele_test_echo(&cmd,3)!= OK) lib$stop(-1); -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); + if (((rpm >= RESONANZ_1U) && (rpm <= RESONANZ_1O)) || + ((rpm >= RESONANZ_2U) && (rpm <= RESONANZ_2O)) || + ((rpm >= RESONANZ_3U) && (rpm <= RESONANZ_3O))) { + print_error(fs, "nominal value within inhibited range"); + return; + } + sprintf(&s_dat + 4, "%5u", rpm); + sts = sele_write(s_dat); + if (sele_test_echo(&cmd, 3) != OK) + lib$stop(-1); + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); } + /* -------------------------------------------------------------------------- */ /* Leerlauf des Selektors einschalten; weder Antrieb noch Verzoegerung erfolgen - eine anschliessende Abbremsung oder @@ -351,14 +393,18 @@ if (err == TRUE) return(NOT_OK); */ long select_set_idle() { -int sts; -long err; -char cmd[] = "STB"; -sts = sele_write(cmd); -if (sele_test_echo(&cmd,3)!= OK) lib$stop(-1); -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); + int sts; + long err; + char cmd[] = "STB"; + sts = sele_write(cmd); + if (sele_test_echo(&cmd, 3) != OK) + lib$stop(-1); + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); } + /* -------------------------------------------------------------------------- */ /* Starten der Messung der elektrischen Verlustleistung des Selektors. Anscheinend wird waehrend der Zeit die @@ -369,30 +415,37 @@ if (err == TRUE) return(NOT_OK); */ long select_read_power() { -int sts; -long err; -char cmd[] = "BRE"; -sts = sele_write(cmd); -if (sele_test_echo(&cmd,3)!= OK) lib$stop(-1); -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); + int sts; + long err; + char cmd[] = "BRE"; + sts = sele_write(cmd); + if (sele_test_echo(&cmd, 3) != OK) + lib$stop(-1); + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); } + /* -------------------------------------------------------------------------- */ /* Lesen der aktuellen Drehzahl des Selektors */ long select_read_rpm(rpm) int *rpm; { -int sts, tmp; -long err; -char status[80], cmd[] = "FDR"; -sts = sele_write(cmd); -if (sele_test_echo(&cmd,3)!= OK) lib$stop(-1); + int sts, tmp; + long err; + char status[80], cmd[] = "FDR"; + sts = sele_write(cmd); + if (sele_test_echo(&cmd, 3) != OK) + lib$stop(-1); -sts = sele_read(&status); -sscanf(&status+4,"%d",&tmp); -*rpm = tmp; -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); + sts = sele_read(&status); + sscanf(&status + 4, "%d", &tmp); + *rpm = tmp; + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); } /* -------------------------------------------------------------------------- */ @@ -421,108 +474,148 @@ dat = Tagesdatum dd.m.yyyy tim = Tageszeit hh.mm.s */ -long select_read_status(rm,nom_rpm, cur_rpm, pwr, curr, rot_temp, cont_temp, - inl_temp, outl_temp, cool_wat, vacuum, accel, komm, dat, tim) +long select_read_status(rm, nom_rpm, cur_rpm, pwr, curr, rot_temp, + cont_temp, inl_temp, outl_temp, cool_wat, vacuum, + accel, komm, dat, tim) char *rm[]; int *nom_rpm, *cur_rpm, *pwr, *rot_temp, *cont_temp, *inl_temp, *outl_temp; float *cool_wat, *vacuum, *accel, *curr; char *dat[], *tim[]; short *komm; { -int cnt, key_id, sl, sts; -long err; -char ena_str[] = "ENABLED"; -char dis_str[] = "DISABLED"; -char keys[15][9] = - { - "Status:\0 ", - "S_DREH:\0 ", - "I_DREH:\0 ", - "P_VERL:\0 ", - "STROM:\0 ", - "T_ROT:\0 ", - "T_GEH:\0 ", - "T_VOR:\0 ", - "T_RUECK:\0", - "DURCHFL:\0", - "VAKUUM:\0 ", - "BESCHL:\0 ", - "KOM: \0 ", - "DATE: \0 ", - "TIME: \0 "}; + int cnt, key_id, sl, sts; + long err; + char ena_str[] = "ENABLED"; + char dis_str[] = "DISABLED"; + char keys[15][9] = { + "Status:\0 ", + "S_DREH:\0 ", + "I_DREH:\0 ", + "P_VERL:\0 ", + "STROM:\0 ", + "T_ROT:\0 ", + "T_GEH:\0 ", + "T_VOR:\0 ", + "T_RUECK:\0", + "DURCHFL:\0", + "VAKUUM:\0 ", + "BESCHL:\0 ", + "KOM: \0 ", + "DATE: \0 ", + "TIME: \0 " + }; -char tok_buf[TOK_BUF_L], *ptr_token, *ptr_src, *ptr, tok_c[] = "/\0"; + char tok_buf[TOK_BUF_L], *ptr_token, *ptr_src, *ptr, tok_c[] = "/\0"; -char status[255], cmd[] = "???"; + char status[255], cmd[] = "???"; -if (sele_write(cmd) != OK) return(NOT_OK); + if (sele_write(cmd) != OK) + return (NOT_OK); -if (sele_test_echo(&cmd, 3) == NOT_OK) lib$stop(-1); + if (sele_test_echo(&cmd, 3) == NOT_OK) + lib$stop(-1); -if (sele_read(&status) != OK) return(NOT_OK); /* Und nun der Status */ -ptr_src = &status; -for (;;) - { - /* Lies Zeichenfolge bis zum naechsten Trennzeichen '/' */ - ptr_token = strtok(ptr_src, &tok_c); - ptr_src = NULL; /* fuer die weitere Suche notwendig */ - if (ptr_token == NULL) break; - strcpy(&tok_buf,ptr_token); + if (sele_read(&status) != OK) + return (NOT_OK); /* Und nun der Status */ + ptr_src = &status; + for (;;) { + /* Lies Zeichenfolge bis zum naechsten Trennzeichen '/' */ + ptr_token = strtok(ptr_src, &tok_c); + ptr_src = NULL; /* fuer die weitere Suche notwendig */ + if (ptr_token == NULL) + break; + strcpy(&tok_buf, ptr_token); - for (key_id = 0; key_id<=14; key_id++) - { - /* Ist das Schluesselwort enthalten ? */ - sl = strlen(keys[key_id]); - if (strncmp(&keys[key_id][0], &tok_buf, sl) == NULL) - { - /* Schiebe das Schluesselwort raus */ - for (cnt=0;cnt+sl < TOK_BUF_L; cnt++) - tok_buf[cnt] = tok_buf[cnt+sl]; - switch (key_id) - { - case 0: - { - ptr = rm; - strcpy(ptr, &tok_buf); - break; - } - case 1: {sscanf(&tok_buf,"%d",nom_rpm); break;} - case 2: {sscanf(&tok_buf,"%d",cur_rpm); break;} - case 3: {sscanf(&tok_buf,"%d",pwr); break;} - case 4: {sscanf(&tok_buf,"%f",curr); break;} - case 5: {sscanf(&tok_buf,"%d",rot_temp); break;} - case 6: {sscanf(&tok_buf,"%d",cont_temp); break;} - case 7: {sscanf(&tok_buf,"%d",inl_temp); break;} - case 8: {sscanf(&tok_buf,"%d",outl_temp); break;} - case 9: {sscanf(&tok_buf,"%f",cool_wat); break;} - case 10: {sscanf(&tok_buf,"%f",vacuum); break;} - case 11: {sscanf(&tok_buf,"%f",accel); break;} - case 12: - { - if (strcmp(&tok_buf, &ena_str) == NULL) - {*komm = TRUE; break;} - if (strcmp(&tok_buf, &dis_str) == NULL) - {*komm = FALSE;break;} - printf("Invalid Communication value"); - break; - } - case 13: - { - ptr = dat; - strcpy(ptr, &tok_buf); - break; - } - case 14: - { - ptr = tim; - strcpy(ptr, &tok_buf); - break; - } - } - } - } - } -if (select_error_msg(&err) != OK) return(NOT_OK); -if (err == TRUE) return(NOT_OK); -return(OK); + for (key_id = 0; key_id <= 14; key_id++) { + /* Ist das Schluesselwort enthalten ? */ + sl = strlen(keys[key_id]); + if (strncmp(&keys[key_id][0], &tok_buf, sl) == NULL) { + /* Schiebe das Schluesselwort raus */ + for (cnt = 0; cnt + sl < TOK_BUF_L; cnt++) + tok_buf[cnt] = tok_buf[cnt + sl]; + switch (key_id) { + case 0: + { + ptr = rm; + strcpy(ptr, &tok_buf); + break; + } + case 1:{ + sscanf(&tok_buf, "%d", nom_rpm); + break; + } + case 2:{ + sscanf(&tok_buf, "%d", cur_rpm); + break; + } + case 3:{ + sscanf(&tok_buf, "%d", pwr); + break; + } + case 4:{ + sscanf(&tok_buf, "%f", curr); + break; + } + case 5:{ + sscanf(&tok_buf, "%d", rot_temp); + break; + } + case 6:{ + sscanf(&tok_buf, "%d", cont_temp); + break; + } + case 7:{ + sscanf(&tok_buf, "%d", inl_temp); + break; + } + case 8:{ + sscanf(&tok_buf, "%d", outl_temp); + break; + } + case 9:{ + sscanf(&tok_buf, "%f", cool_wat); + break; + } + case 10:{ + sscanf(&tok_buf, "%f", vacuum); + break; + } + case 11:{ + sscanf(&tok_buf, "%f", accel); + break; + } + case 12: + { + if (strcmp(&tok_buf, &ena_str) == NULL) { + *komm = TRUE; + break; + } + if (strcmp(&tok_buf, &dis_str) == NULL) { + *komm = FALSE; + break; + } + printf("Invalid Communication value"); + break; + } + case 13: + { + ptr = dat; + strcpy(ptr, &tok_buf); + break; + } + case 14: + { + ptr = tim; + strcpy(ptr, &tok_buf); + break; + } + } + } + } + } + if (select_error_msg(&err) != OK) + return (NOT_OK); + if (err == TRUE) + return (NOT_OK); + return (OK); } diff --git a/selector.c b/selector.c index 1438dd6f..45b4294b 100644 --- a/selector.c +++ b/selector.c @@ -62,324 +62,307 @@ #define LATD 9 #define RIGHTS 10 /*------------------------------------------------------------------------*/ - typedef struct __SicsSelector { - ObjectDescriptor *pDes; - ObPar *pParams; - char *name; - pMotor pTheta; - pMotor pTwoTheta; - pMotor pBend1; - pMotor pBend2; - char *pType; - } SicsSelector; +typedef struct __SicsSelector { + ObjectDescriptor *pDes; + ObPar *pParams; + char *name; + pMotor pTheta; + pMotor pTwoTheta; + pMotor pBend1; + pMotor pBend2; + char *pType; +} SicsSelector; /*-------------------------------------------------------------------------*/ - char *MonoGetType(pSicsSelector self) - { - assert(self); - return self->pType; - } -/*---------------------------------------------------------------------------*/ - pSicsSelector CreateSelector(char *name, pMotor pTheta, pMotor pTwoTheta, - pMotor pBend1, pMotor pBend2) - { - pSicsSelector pRes = NULL; - int iRet; - float fVal; +char *MonoGetType(pSicsSelector self) +{ + assert(self); + return self->pType; +} - assert(pTheta); - assert(pTwoTheta); - - /* allocate memory */ - pRes = (pSicsSelector)malloc(sizeof(SicsSelector)); - if(!pRes) - { - return NULL; - } - - /* create ObjectDescriptor */ - pRes->pDes = CreateDescriptor("CrystalSelector"); - if(!pRes->pDes) - { - free(pRes); - return NULL; - } - - /* create Parameter Array */ - pRes->pParams = ObParCreate(11); - if(!pRes->pParams) - { - free(pRes->pDes); - free(pRes); - return NULL; - } - - /* create all the parameters */ - ObParInit(pRes->pParams,SS, "ss",1.,usUser); - ObParInit(pRes->pParams,B1C1, "vk1",1.,usInternal); - ObParInit(pRes->pParams,B1C2, "vk2",1.,usInternal); - ObParInit(pRes->pParams,B2C1, "hk1",1.,usInternal); - ObParInit(pRes->pParams,B2C2, "hk2",1.,usInternal); - ObParInit(pRes->pParams,LATD, "dd",2.087,usMugger); - ObParInit(pRes->pParams,RIGHTS, "access",usUser,usMugger); - - /* assign motors */ - pRes->pTheta = pTheta; - pRes->pTwoTheta = pTwoTheta; - - /* provide default values for Bender Parameters in order to make - things look nice - */ - fVal = 0.; - ObParInit(pRes->pParams,B1MIN, "vmin",fVal,usInternal); - ObParInit(pRes->pParams,B1MAX, "vmax",fVal,usInternal); - ObParInit(pRes->pParams,B2MIN, "hmin",fVal,usInternal); - ObParInit(pRes->pParams,B2MAX, "hmax",fVal,usInternal); - - - /* handle benders, if present */ - pRes->pBend1 = pBend1; - if(pBend1) - { - iRet = MotorGetPar(pBend1,"hardlowerlim",&fVal); - assert(iRet); - ObParInit(pRes->pParams,B1MIN, "vmin",fVal,usInternal); - iRet = MotorGetPar(pBend1,"hardupperlim",&fVal); - assert(iRet); - ObParInit(pRes->pParams,B1MAX, "vmax",fVal,usInternal); - } - pRes->pBend2 = pBend2; - if(pBend2) - { - iRet = MotorGetPar(pBend2,"hardlowerlim",&fVal); - assert(iRet); - ObParInit(pRes->pParams,B2MIN, "hmin",fVal,usInternal); - iRet = MotorGetPar(pBend2,"hardupperlim",&fVal); - assert(iRet); - ObParInit(pRes->pParams,B2MAX, "hmax",fVal,usInternal); - } - pRes->name = strdup(name); - pRes->pType = strdup("Unknown"); - return pRes; - } /*---------------------------------------------------------------------------*/ - void DeleteSelector(void *self) - { - pSicsSelector pSelf; - - assert(self); - - pSelf = (pSicsSelector)self; - - if(pSelf->pDes) - { - DeleteDescriptor(pSelf->pDes); - } - if(pSelf->pParams) - { - ObParDelete(pSelf->pParams); - } - if(pSelf->name) - { - free(pSelf->name); - } - if(pSelf->pType) - { - free(pSelf->pType); - } - free(pSelf); +pSicsSelector CreateSelector(char *name, pMotor pTheta, pMotor pTwoTheta, + pMotor pBend1, pMotor pBend2) +{ + pSicsSelector pRes = NULL; + int iRet; + float fVal; + + assert(pTheta); + assert(pTwoTheta); + + /* allocate memory */ + pRes = (pSicsSelector) malloc(sizeof(SicsSelector)); + if (!pRes) { + return NULL; } + + /* create ObjectDescriptor */ + pRes->pDes = CreateDescriptor("CrystalSelector"); + if (!pRes->pDes) { + free(pRes); + return NULL; + } + + /* create Parameter Array */ + pRes->pParams = ObParCreate(11); + if (!pRes->pParams) { + free(pRes->pDes); + free(pRes); + return NULL; + } + + /* create all the parameters */ + ObParInit(pRes->pParams, SS, "ss", 1., usUser); + ObParInit(pRes->pParams, B1C1, "vk1", 1., usInternal); + ObParInit(pRes->pParams, B1C2, "vk2", 1., usInternal); + ObParInit(pRes->pParams, B2C1, "hk1", 1., usInternal); + ObParInit(pRes->pParams, B2C2, "hk2", 1., usInternal); + ObParInit(pRes->pParams, LATD, "dd", 2.087, usMugger); + ObParInit(pRes->pParams, RIGHTS, "access", usUser, usMugger); + + /* assign motors */ + pRes->pTheta = pTheta; + pRes->pTwoTheta = pTwoTheta; + + /* provide default values for Bender Parameters in order to make + things look nice + */ + fVal = 0.; + ObParInit(pRes->pParams, B1MIN, "vmin", fVal, usInternal); + ObParInit(pRes->pParams, B1MAX, "vmax", fVal, usInternal); + ObParInit(pRes->pParams, B2MIN, "hmin", fVal, usInternal); + ObParInit(pRes->pParams, B2MAX, "hmax", fVal, usInternal); + + + /* handle benders, if present */ + pRes->pBend1 = pBend1; + if (pBend1) { + iRet = MotorGetPar(pBend1, "hardlowerlim", &fVal); + assert(iRet); + ObParInit(pRes->pParams, B1MIN, "vmin", fVal, usInternal); + iRet = MotorGetPar(pBend1, "hardupperlim", &fVal); + assert(iRet); + ObParInit(pRes->pParams, B1MAX, "vmax", fVal, usInternal); + } + pRes->pBend2 = pBend2; + if (pBend2) { + iRet = MotorGetPar(pBend2, "hardlowerlim", &fVal); + assert(iRet); + ObParInit(pRes->pParams, B2MIN, "hmin", fVal, usInternal); + iRet = MotorGetPar(pBend2, "hardupperlim", &fVal); + assert(iRet); + ObParInit(pRes->pParams, B2MAX, "hmax", fVal, usInternal); + } + pRes->name = strdup(name); + pRes->pType = strdup("Unknown"); + return pRes; +} + +/*---------------------------------------------------------------------------*/ +void DeleteSelector(void *self) +{ + pSicsSelector pSelf; + + assert(self); + + pSelf = (pSicsSelector) self; + + if (pSelf->pDes) { + DeleteDescriptor(pSelf->pDes); + } + if (pSelf->pParams) { + ObParDelete(pSelf->pParams); + } + if (pSelf->name) { + free(pSelf->name); + } + if (pSelf->pType) { + free(pSelf->pType); + } + free(pSelf); +} + /*-------------------------------------------------------------------------- Syntax: MonoInit name Type ThetaMotor TwoThetaMotor Bend1Motor Bend2Motor with Bend1Motor, Bend2Motor beeing optional. -*/ +*/ - int MonoInit(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pSicsSelector pRes = NULL; - pMotor pTheta = NULL; - pMotor pTwoTheta = NULL; - pMotor pBend1 = NULL; - pMotor pBend2 = NULL; - TokenList *pList = NULL; - int iRet = 0; - TokenList *pCurrent; - char pBueffel[132]; - char pName[132]; - char *pType = NULL; +int MonoInit(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSicsSelector pRes = NULL; + pMotor pTheta = NULL; + pMotor pTwoTheta = NULL; + pMotor pBend1 = NULL; + pMotor pBend2 = NULL; + TokenList *pList = NULL; + int iRet = 0; + TokenList *pCurrent; + char pBueffel[132]; + char pName[132]; + char *pType = NULL; - assert(pCon); - assert(pSics); - - /* split arguments */ - argtolower(argc,argv); - pList = SplitArguments(argc,argv); - if(!pList) - { - sprintf(pBueffel,"ERROR: parsing arguments in %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* advance and search name */ - pCurrent = pList->pNext; - if(!pCurrent) - { - sprintf(pBueffel,"ERRROR: Insufficient number of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - goto end; - } - strcpy(pName,pCurrent->text); - - /* advance and find Type string */ - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - sprintf(pBueffel,"ERRROR: Insufficient number of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - goto end; - } - pType = pCurrent->text; - - /* advance and find Theta motor */ - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - sprintf(pBueffel,"ERRROR: Insufficient number of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - goto end; - } - pTheta = FindMotor(pSics,pCurrent->text); - if(!pTheta) - { - sprintf(pBueffel,"ERROR: Cannot find motor %s for driving Theta", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - goto end; - } + assert(pCon); + assert(pSics); - /* advance and find Two Theta motor */ - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - sprintf(pBueffel,"ERRROR: Insufficient number of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - goto end; - } - pTwoTheta = FindMotor(pSics,pCurrent->text); - if(!pTwoTheta) - { - sprintf(pBueffel,"ERROR: Cannot find motor %s for driving Two Theta", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - goto end; - } - iRet = 1; /* we are now able to install a monochromator */ - - /* try find first bending motor */ - pCurrent = pCurrent->pNext; - if(pCurrent) - { - pBend1 = FindMotor(pSics,pCurrent->text); - if(!pBend1) - { - sprintf(pBueffel,"ERROR: Cannot find motor %s for driving vertical bender", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - goto end; - } - } - else - { - goto end; - } - - /* find second bender */ - pCurrent = pCurrent->pNext; - if(pCurrent) - { - pBend2 = FindMotor(pSics,pCurrent->text); - if(!pBend2) - { - sprintf(pBueffel,"ERROR: Cannot find motor %s for driving horizontal bender", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - goto end; - } - } + /* split arguments */ + argtolower(argc, argv); + pList = SplitArguments(argc, argv); + if (!pList) { + sprintf(pBueffel, "ERROR: parsing arguments in %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* advance and search name */ + pCurrent = pList->pNext; + if (!pCurrent) { + sprintf(pBueffel, "ERRROR: Insufficient number of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + goto end; + } + strcpy(pName, pCurrent->text); + + /* advance and find Type string */ + pCurrent = pCurrent->pNext; + if (!pCurrent) { + sprintf(pBueffel, "ERRROR: Insufficient number of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + goto end; + } + pType = pCurrent->text; + + /* advance and find Theta motor */ + pCurrent = pCurrent->pNext; + if (!pCurrent) { + sprintf(pBueffel, "ERRROR: Insufficient number of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + goto end; + } + pTheta = FindMotor(pSics, pCurrent->text); + if (!pTheta) { + sprintf(pBueffel, "ERROR: Cannot find motor %s for driving Theta", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + goto end; + } + + /* advance and find Two Theta motor */ + pCurrent = pCurrent->pNext; + if (!pCurrent) { + sprintf(pBueffel, "ERRROR: Insufficient number of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + goto end; + } + pTwoTheta = FindMotor(pSics, pCurrent->text); + if (!pTwoTheta) { + sprintf(pBueffel, "ERROR: Cannot find motor %s for driving Two Theta", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + goto end; + } + iRet = 1; /* we are now able to install a monochromator */ + + /* try find first bending motor */ + pCurrent = pCurrent->pNext; + if (pCurrent) { + pBend1 = FindMotor(pSics, pCurrent->text); + if (!pBend1) { + sprintf(pBueffel, + "ERROR: Cannot find motor %s for driving vertical bender", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + goto end; + } + } else { + goto end; + } + + /* find second bender */ + pCurrent = pCurrent->pNext; + if (pCurrent) { + pBend2 = FindMotor(pSics, pCurrent->text); + if (!pBend2) { + sprintf(pBueffel, + "ERROR: Cannot find motor %s for driving horizontal bender", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + goto end; + } + } end: - if(iRet) - { - pRes = CreateSelector(pName, pTheta, pTwoTheta,pBend1,pBend2); - if(!pRes) - { - iRet = 0; - } - else - { - if(pRes->pType) - { - free(pRes->pType); - } - pRes->pType = strdup(pType); - iRet = AddCommand(pSics, pName,MonoAction,DeleteSelector,(void *)pRes); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[2]); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - DeleteSelector((void *)pRes); - return 0; - } - } + if (iRet) { + pRes = CreateSelector(pName, pTheta, pTwoTheta, pBend1, pBend2); + if (!pRes) { + iRet = 0; + } else { + if (pRes->pType) { + free(pRes->pType); + } + pRes->pType = strdup(pType); + iRet = + AddCommand(pSics, pName, MonoAction, DeleteSelector, + (void *) pRes); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", + argv[2]); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + DeleteSelector((void *) pRes); + return 0; + } } - - DeleteTokenList(pList); - return iRet; - } + + DeleteTokenList(pList); + return iRet; + +} + /*--------------------------------------------------------------------------- a private function used in MonoAction to print all relevant features of the monochromator */ - static void MonoList(pSicsSelector self, SConnection *pCon) - { - char pBueffel[512]; - int i, iLen; - - /* print known parameters */ - iLen = ObParLength(self->pParams); - sprintf(pBueffel,"Parameter Listing for %s\n",self->name); - SCWrite(pCon,pBueffel,eValue); - for(i = 0; i < iLen; i++) - { - sprintf(pBueffel,"%s.%s = %f\n",self->name, - self->pParams[i].name,self->pParams[i].fVal); - SCWrite(pCon,pBueffel,eValue); - } - - /* print motornames as well */ - sprintf(pBueffel,"%s.ThetaMotor = %s\n",self->name,self->pTheta->name); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%s.TwoThetaMotor = %s\n",self->name,self->pTwoTheta->name); - SCWrite(pCon,pBueffel,eValue); - if(self->pBend1) - { - sprintf(pBueffel,"%s.VerticalBenderMotor = %s\n",self->name,self->pBend1->name); - SCWrite(pCon,pBueffel,eValue); - } - if(self->pBend2) - { - sprintf(pBueffel,"%s.HorizontalBenderMotor = %s\n",self->name,self->pBend2->name); - SCWrite(pCon,pBueffel,eValue); - } +static void MonoList(pSicsSelector self, SConnection * pCon) +{ + char pBueffel[512]; + int i, iLen; + + /* print known parameters */ + iLen = ObParLength(self->pParams); + sprintf(pBueffel, "Parameter Listing for %s\n", self->name); + SCWrite(pCon, pBueffel, eValue); + for (i = 0; i < iLen; i++) { + sprintf(pBueffel, "%s.%s = %f\n", self->name, + self->pParams[i].name, self->pParams[i].fVal); + SCWrite(pCon, pBueffel, eValue); } + + /* print motornames as well */ + sprintf(pBueffel, "%s.ThetaMotor = %s\n", self->name, + self->pTheta->name); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%s.TwoThetaMotor = %s\n", self->name, + self->pTwoTheta->name); + SCWrite(pCon, pBueffel, eValue); + if (self->pBend1) { + sprintf(pBueffel, "%s.VerticalBenderMotor = %s\n", self->name, + self->pBend1->name); + SCWrite(pCon, pBueffel, eValue); + } + if (self->pBend2) { + sprintf(pBueffel, "%s.HorizontalBenderMotor = %s\n", self->name, + self->pBend2->name); + SCWrite(pCon, pBueffel, eValue); + } +} + /*----------------------------------------------------------------------------- The Action function. Syntax: mononame list -- list all pars @@ -387,468 +370,423 @@ end: mononame parname value -- tries changing the parameter */ - int MonoAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pSicsSelector pSelf = NULL; - TokenList *pList = NULL; - TokenList *pCurrent; - int iRet; - char pBueffel[132]; - char pName[132]; - float fVal; - ObPar *pPar = NULL; - - assert(pCon); - assert(pSics); - assert(pData); - - pSelf = (pSicsSelector)pData; - - /* split arguments */ - argtolower(argc,argv); - pList = SplitArguments(argc,argv); - if(!pList) - { - sprintf(pBueffel,"ERROR: parsing arguments in %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +int MonoAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSicsSelector pSelf = NULL; + TokenList *pList = NULL; + TokenList *pCurrent; + int iRet; + char pBueffel[132]; + char pName[132]; + float fVal; + ObPar *pPar = NULL; - pCurrent = pList->pNext; - /* now we can have "list" or a parametername */ - /* check for list first */ - if(!pCurrent) - { - sprintf(pBueffel,"ERROR: Insufficient number of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - goto end; - } - if(strcmp(pCurrent->text,"list") == 0) - { - MonoList(pSelf,pCon); - iRet = 1; - goto end; - } - - /* must be parametername now */ - strcpy(pName,pCurrent->text); - - /* find out if it is a set or a get. On set there is another paremeter, - else none - */ - pCurrent = pCurrent->pNext; - if(pCurrent) /* set */ - { - /* check if input is proper */ - if(pCurrent->Type == eFloat) - { - fVal = pCurrent->fVal; - } - else if(pCurrent->Type == eInt) - { - fVal = (float)pCurrent->iVal; - } - else - { - sprintf(pBueffel,"ERROR: Illegal parameter %s given to %s", - pCurrent->text, argv[0]); - SCWrite(pCon,pBueffel,eError); - goto end; - } - iRet = ObParSet(pSelf->pParams,argv[0],pName,fVal,pCon); - goto end; - } - else /* get */ - { - pPar = ObParFind(pSelf->pParams,pName); - if(!pPar) - { - sprintf(pBueffel,"ERROR: Parameter %s not found in %s",pName, argv[0]); - SCWrite(pCon,pBueffel,eError); - goto end; - } - else - { - sprintf(pBueffel,"%s.%s = %f",argv[0],pName,pPar->fVal); - SCWrite(pCon,pBueffel,eValue); - iRet = 1; - DeleteTokenList(pList); - return 1; - } - } + assert(pCon); + assert(pSics); + assert(pData); + + pSelf = (pSicsSelector) pData; + + /* split arguments */ + argtolower(argc, argv); + pList = SplitArguments(argc, argv); + if (!pList) { + sprintf(pBueffel, "ERROR: parsing arguments in %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + pCurrent = pList->pNext; + /* now we can have "list" or a parametername */ + /* check for list first */ + if (!pCurrent) { + sprintf(pBueffel, "ERROR: Insufficient number of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + goto end; + } + if (strcmp(pCurrent->text, "list") == 0) { + MonoList(pSelf, pCon); + iRet = 1; + goto end; + } + + /* must be parametername now */ + strcpy(pName, pCurrent->text); + + /* find out if it is a set or a get. On set there is another paremeter, + else none + */ + pCurrent = pCurrent->pNext; + if (pCurrent) { /* set */ + /* check if input is proper */ + if (pCurrent->Type == eFloat) { + fVal = pCurrent->fVal; + } else if (pCurrent->Type == eInt) { + fVal = (float) pCurrent->iVal; + } else { + sprintf(pBueffel, "ERROR: Illegal parameter %s given to %s", + pCurrent->text, argv[0]); + SCWrite(pCon, pBueffel, eError); + goto end; + } + iRet = ObParSet(pSelf->pParams, argv[0], pName, fVal, pCon); + goto end; + } else { /* get */ + + pPar = ObParFind(pSelf->pParams, pName); + if (!pPar) { + sprintf(pBueffel, "ERROR: Parameter %s not found in %s", pName, + argv[0]); + SCWrite(pCon, pBueffel, eError); + goto end; + } else { + sprintf(pBueffel, "%s.%s = %f", argv[0], pName, pPar->fVal); + SCWrite(pCon, pBueffel, eValue); + iRet = 1; + DeleteTokenList(pList); + return 1; + } + } end: - DeleteTokenList(pList); - if(iRet) - SCSendOK(pCon); - return iRet; - } + DeleteTokenList(pList); + if (iRet) + SCSendOK(pCon); + return iRet; +} + /*--------------------------------------------------------------------------*/ - struct SelPos { - float fTheta, fTwoTheta, fVert, fHor; - }; +struct SelPos { + float fTheta, fTwoTheta, fVert, fHor; +}; #define PI 3.14159265358979323846264338327950 #define RD 57.29577951308232087679815481410517 /* ------------------- C has no proper abs -------------------------------*/ - static double absd(double f) - { - if(f < .0) - { - f = -f; - } - return f; +static double absd(double f) +{ + if (f < .0) { + f = -f; } -/*-------------------------------------------------------------------------*/ - static struct SelPos CalculatePosition(pSicsSelector self, float fWaveLength) - { - struct SelPos pRes; - double fD; - - /* Theta, TwoTheta first */ - fD = fWaveLength/(2.0* ObVal(self->pParams,LATD)); - if(fD > 1.0) - { - pRes.fTheta = 1000.; /* error indication: energy to big */ - return pRes; - } - fD = asin(fD); - pRes.fTheta = fD*ObVal(self->pParams,SS)*RD; - pRes.fTwoTheta = 2 * pRes.fTheta; - - /* now first bender */ - if(self->pBend1) - { - pRes.fVert = ObVal(self->pParams,B1C1)+(ObVal(self->pParams,B1C2)/ - sin(fD)); - } + return f; +} +/*-------------------------------------------------------------------------*/ +static struct SelPos CalculatePosition(pSicsSelector self, + float fWaveLength) +{ + struct SelPos pRes; + double fD; - /* now second bender */ - if(self->pBend2) - { - pRes.fHor = ObVal(self->pParams,B2C1)+ (ObVal(self->pParams,B2C2)/ - sin(fD)); - } + /* Theta, TwoTheta first */ + fD = fWaveLength / (2.0 * ObVal(self->pParams, LATD)); + if (fD > 1.0) { + pRes.fTheta = 1000.; /* error indication: energy to big */ return pRes; - } -/*--------------------------------------------------------------------------*/ - int MonoLimits(pSicsSelector self, float fWaveLength, - char *error, int iErrLen) - { - struct SelPos sNeu; - char pBueffel[132]; - pIDrivable pDrivInt = NULL; - - /* get Position */ - sNeu = CalculatePosition(self,fWaveLength); - if(sNeu.fTheta > 900.) /* invalid wavelength or energy */ - { - sprintf(pBueffel,"ERROR: Invalid wavelength or energy to high: %f", - fWaveLength); - strncpy(error,pBueffel,iErrLen-1); - return 0; - } - - /* check each motor in turn */ - pDrivInt = self->pTheta->pDescriptor->GetInterface(self->pTheta,DRIVEID); - if(!pDrivInt->CheckLimits(self->pTheta,sNeu.fTheta,error,iErrLen)) - { - return 0; - } - pDrivInt = self->pTwoTheta->pDescriptor->GetInterface(self->pTwoTheta, - DRIVEID); - if(!pDrivInt->CheckLimits(self->pTwoTheta,sNeu.fTwoTheta, - error,iErrLen)) - { - return 0; - } - - if(self->pBend1) - { - pDrivInt = self->pBend1->pDescriptor->GetInterface(self->pBend1,DRIVEID); - if(!pDrivInt->CheckLimits(self->pBend1,sNeu.fVert, - error,iErrLen)) - { - return 0; - } - } - if(self->pBend2) - { - pDrivInt = self->pBend2->pDescriptor->GetInterface(self->pBend2,DRIVEID); - if(!pDrivInt->CheckLimits(self->pBend2,sNeu.fHor, - error,iErrLen)) - { - return 0; - } - } - return 1; - } -/*--------------------------------------------------------------------------*/ - int MonoHalt(pSicsSelector self) - { - pIDrivable pDrivInt = NULL; - - /* halt each motor in turn */ - pDrivInt = self->pTheta->pDescriptor->GetInterface(self->pTheta,DRIVEID); - if(pDrivInt) - { - pDrivInt->Halt(self->pTheta); - } - - pDrivInt = self->pTwoTheta->pDescriptor->GetInterface(self->pTwoTheta, - DRIVEID); - if(pDrivInt) - { - pDrivInt->Halt(self->pTwoTheta); - } - - if(self->pBend1) - { - pDrivInt = self->pBend1->pDescriptor->GetInterface(self->pBend1, - DRIVEID); - if(pDrivInt) - { - pDrivInt->Halt(self->pBend1); - } - } - if(self->pBend2) - { - pDrivInt = self->pBend2->pDescriptor->GetInterface(self->pBend2, - DRIVEID); - if(pDrivInt) - { - pDrivInt->Halt(self->pBend2); - } - } - - - return 1; - } -/*-------------------------------------------------------------------------*/ - int MonoRun(pSicsSelector self, SConnection *pCon, float fWaveLength) - { - struct SelPos sNeu; - char pBueffel[132]; - int iRet; - - /* Check authorisation */ - if(!SCMatchRights(pCon,(int)ObVal(self->pParams,RIGHTS))) - { - sprintf(pBueffel, - "ERROR: You are not authorised to move the monochromator %s",self->name); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* get Position */ - sNeu = CalculatePosition(self,fWaveLength); - if(sNeu.fTheta > 900.) /* invalid wavelength or energy */ - { - sprintf(pBueffel,"ERROR: Invalid wavelength or energy to high: %f", - fWaveLength); - return 0; - } - - /* start each motor in turn */ - iRet = StartDevice(GetExecutor(),self->pTheta->name, - self->pTheta->pDescriptor, - self->pTheta, - pCon,sNeu.fTheta); - if(!iRet) - { - return 0; - } - iRet = StartDevice(GetExecutor(),self->pTwoTheta->name, - self->pTwoTheta->pDescriptor, - self->pTwoTheta, - pCon,sNeu.fTwoTheta); - if(!iRet) - { - return 0; - } - - - /* bending motors */ - if(self->pBend1) - { - iRet = StartDevice(GetExecutor(),self->pBend1->name, - self->pBend1->pDescriptor, - self->pBend1, - pCon,sNeu.fVert); - if(!iRet) - { - return 0; - } - - } - if(self->pBend2) - { - iRet = StartDevice(GetExecutor(),self->pBend2->name, - self->pBend2->pDescriptor, - self->pBend2, - pCon,sNeu.fHor); - if(!iRet) - { - return 0; - } - } - return OKOK; } -/*--------------------------------------------------------------------------*/ - int MonoCheck(pSicsSelector self, SConnection *pCon) - { - int iRet; - pIDrivable pDrivInt = NULL; + fD = asin(fD); + pRes.fTheta = fD * ObVal(self->pParams, SS) * RD; + pRes.fTwoTheta = 2 * pRes.fTheta; - /* cheack each motor in turn */ - pDrivInt = self->pTheta->pDescriptor->GetInterface(self->pTheta,DRIVEID); - if(pDrivInt) - { - iRet = pDrivInt->CheckStatus(self->pTheta,pCon); - if( (iRet != OKOK) && (iRet != HWIdle)) - { - return iRet; - } - } - - pDrivInt = self->pTwoTheta->pDescriptor->GetInterface(self->pTwoTheta, - DRIVEID); - if(pDrivInt) - { - iRet = pDrivInt->CheckStatus(self->pTwoTheta,pCon); - if( (iRet != OKOK) && (iRet != HWIdle)) - { - return iRet; - } - } - - if(self->pBend1) - { - pDrivInt = self->pBend1->pDescriptor->GetInterface(self->pBend1, - DRIVEID); - if(pDrivInt) - { - iRet = pDrivInt->CheckStatus(self->pBend1,pCon); - if( (iRet != OKOK) && (iRet != HWIdle)) - { - return iRet; - } - } - } - - if(self->pBend2) - { - pDrivInt = self->pBend2->pDescriptor->GetInterface(self->pBend2, - DRIVEID); - if(pDrivInt) - { - iRet = pDrivInt->CheckStatus(self->pBend2,pCon); - if( (iRet != OKOK) && (iRet != HWIdle)) - { - return iRet; - } - } - } - - - return HWIdle; + /* now first bender */ + if (self->pBend1) { + pRes.fVert = ObVal(self->pParams, B1C1) + (ObVal(self->pParams, B1C2) / + sin(fD)); } + + + /* now second bender */ + if (self->pBend2) { + pRes.fHor = ObVal(self->pParams, B2C1) + (ObVal(self->pParams, B2C2) / + sin(fD)); + } + return pRes; +} + +/*--------------------------------------------------------------------------*/ +int MonoLimits(pSicsSelector self, float fWaveLength, + char *error, int iErrLen) +{ + struct SelPos sNeu; + char pBueffel[132]; + pIDrivable pDrivInt = NULL; + + /* get Position */ + sNeu = CalculatePosition(self, fWaveLength); + if (sNeu.fTheta > 900.) { /* invalid wavelength or energy */ + sprintf(pBueffel, "ERROR: Invalid wavelength or energy to high: %f", + fWaveLength); + strncpy(error, pBueffel, iErrLen - 1); + return 0; + } + + /* check each motor in turn */ + pDrivInt = + self->pTheta->pDescriptor->GetInterface(self->pTheta, DRIVEID); + if (!pDrivInt->CheckLimits(self->pTheta, sNeu.fTheta, error, iErrLen)) { + return 0; + } + pDrivInt = self->pTwoTheta->pDescriptor->GetInterface(self->pTwoTheta, + DRIVEID); + if (!pDrivInt->CheckLimits(self->pTwoTheta, sNeu.fTwoTheta, + error, iErrLen)) { + return 0; + } + + if (self->pBend1) { + pDrivInt = + self->pBend1->pDescriptor->GetInterface(self->pBend1, DRIVEID); + if (!pDrivInt->CheckLimits(self->pBend1, sNeu.fVert, error, iErrLen)) { + return 0; + } + } + if (self->pBend2) { + pDrivInt = + self->pBend2->pDescriptor->GetInterface(self->pBend2, DRIVEID); + if (!pDrivInt->CheckLimits(self->pBend2, sNeu.fHor, error, iErrLen)) { + return 0; + } + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int MonoHalt(pSicsSelector self) +{ + pIDrivable pDrivInt = NULL; + + /* halt each motor in turn */ + pDrivInt = + self->pTheta->pDescriptor->GetInterface(self->pTheta, DRIVEID); + if (pDrivInt) { + pDrivInt->Halt(self->pTheta); + } + + pDrivInt = self->pTwoTheta->pDescriptor->GetInterface(self->pTwoTheta, + DRIVEID); + if (pDrivInt) { + pDrivInt->Halt(self->pTwoTheta); + } + + if (self->pBend1) { + pDrivInt = self->pBend1->pDescriptor->GetInterface(self->pBend1, + DRIVEID); + if (pDrivInt) { + pDrivInt->Halt(self->pBend1); + } + } + if (self->pBend2) { + pDrivInt = self->pBend2->pDescriptor->GetInterface(self->pBend2, + DRIVEID); + if (pDrivInt) { + pDrivInt->Halt(self->pBend2); + } + } + + + return 1; +} + +/*-------------------------------------------------------------------------*/ +int MonoRun(pSicsSelector self, SConnection * pCon, float fWaveLength) +{ + struct SelPos sNeu; + char pBueffel[132]; + int iRet; + + /* Check authorisation */ + if (!SCMatchRights(pCon, (int) ObVal(self->pParams, RIGHTS))) { + sprintf(pBueffel, + "ERROR: You are not authorised to move the monochromator %s", + self->name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* get Position */ + sNeu = CalculatePosition(self, fWaveLength); + if (sNeu.fTheta > 900.) { /* invalid wavelength or energy */ + sprintf(pBueffel, "ERROR: Invalid wavelength or energy to high: %f", + fWaveLength); + return 0; + } + + /* start each motor in turn */ + iRet = StartDevice(GetExecutor(), self->pTheta->name, + self->pTheta->pDescriptor, + self->pTheta, pCon, sNeu.fTheta); + if (!iRet) { + return 0; + } + iRet = StartDevice(GetExecutor(), self->pTwoTheta->name, + self->pTwoTheta->pDescriptor, + self->pTwoTheta, pCon, sNeu.fTwoTheta); + if (!iRet) { + return 0; + } + + + /* bending motors */ + if (self->pBend1) { + iRet = StartDevice(GetExecutor(), self->pBend1->name, + self->pBend1->pDescriptor, + self->pBend1, pCon, sNeu.fVert); + if (!iRet) { + return 0; + } + + } + if (self->pBend2) { + iRet = StartDevice(GetExecutor(), self->pBend2->name, + self->pBend2->pDescriptor, + self->pBend2, pCon, sNeu.fHor); + if (!iRet) { + return 0; + } + } + return OKOK; +} + +/*--------------------------------------------------------------------------*/ +int MonoCheck(pSicsSelector self, SConnection * pCon) +{ + int iRet; + pIDrivable pDrivInt = NULL; + + /* cheack each motor in turn */ + pDrivInt = + self->pTheta->pDescriptor->GetInterface(self->pTheta, DRIVEID); + if (pDrivInt) { + iRet = pDrivInt->CheckStatus(self->pTheta, pCon); + if ((iRet != OKOK) && (iRet != HWIdle)) { + return iRet; + } + } + + pDrivInt = self->pTwoTheta->pDescriptor->GetInterface(self->pTwoTheta, + DRIVEID); + if (pDrivInt) { + iRet = pDrivInt->CheckStatus(self->pTwoTheta, pCon); + if ((iRet != OKOK) && (iRet != HWIdle)) { + return iRet; + } + } + + if (self->pBend1) { + pDrivInt = self->pBend1->pDescriptor->GetInterface(self->pBend1, + DRIVEID); + if (pDrivInt) { + iRet = pDrivInt->CheckStatus(self->pBend1, pCon); + if ((iRet != OKOK) && (iRet != HWIdle)) { + return iRet; + } + } + } + + if (self->pBend2) { + pDrivInt = self->pBend2->pDescriptor->GetInterface(self->pBend2, + DRIVEID); + if (pDrivInt) { + iRet = pDrivInt->CheckStatus(self->pBend2, pCon); + if ((iRet != OKOK) && (iRet != HWIdle)) { + return iRet; + } + } + } + + + return HWIdle; +} + /*-------------------------------------------------------------------------- returns the current Wavelength the monochromator is adjusted to */ - float GetMonoPosition(pSicsSelector self, SConnection *pCon) - { - double fVal, dTheta; - float fTheta, fTwoTheta; - char pBueffel[132]; - int iRet; - - /* get the two positions */ - iRet = MotorGetSoftPosition(self->pTheta,pCon,&fTheta); - if(!iRet) - { - sprintf(pBueffel,"ERROR: cannot read Theta motor for monochromator %s\n", - self->name); - SCWrite(pCon,pBueffel,eError); - return 0.; - } - iRet = MotorGetSoftPosition(self->pTwoTheta,pCon,&fTwoTheta); - if(!iRet) - { - sprintf(pBueffel, - "ERROR: cannot read TwoTheta motor for monochromator %s\n", - self->name); - SCWrite(pCon,pBueffel,eError); - return 0.; - } - - /* check for sync */ - fVal = fTwoTheta - 2* fTheta; - if(fVal < 0.)fVal = -fVal; - if(fVal > 0.01) - { - sprintf(pBueffel,"WARNING: monochromator %s out of sync by %f\n", - self->name,fVal); - SCWrite(pCon,pBueffel,eWarning); - } - - /* calculate wavelength from angles */ - dTheta =(double)fTheta; - dTheta = dTheta *(1.0/RD); - fVal = 2.0 * (double)ObVal(self->pParams,LATD); - fVal = fVal * sin(dTheta) * ObVal(self->pParams,SS); - return fVal; +float GetMonoPosition(pSicsSelector self, SConnection * pCon) +{ + double fVal, dTheta; + float fTheta, fTwoTheta; + char pBueffel[132]; + int iRet; + + /* get the two positions */ + iRet = MotorGetSoftPosition(self->pTheta, pCon, &fTheta); + if (!iRet) { + sprintf(pBueffel, + "ERROR: cannot read Theta motor for monochromator %s\n", + self->name); + SCWrite(pCon, pBueffel, eError); + return 0.; } + iRet = MotorGetSoftPosition(self->pTwoTheta, pCon, &fTwoTheta); + if (!iRet) { + sprintf(pBueffel, + "ERROR: cannot read TwoTheta motor for monochromator %s\n", + self->name); + SCWrite(pCon, pBueffel, eError); + return 0.; + } + + /* check for sync */ + fVal = fTwoTheta - 2 * fTheta; + if (fVal < 0.) + fVal = -fVal; + if (fVal > 0.01) { + sprintf(pBueffel, "WARNING: monochromator %s out of sync by %f\n", + self->name, fVal); + SCWrite(pCon, pBueffel, eWarning); + } + + /* calculate wavelength from angles */ + dTheta = (double) fTheta; + dTheta = dTheta * (1.0 / RD); + fVal = 2.0 * (double) ObVal(self->pParams, LATD); + fVal = fVal * sin(dTheta) * ObVal(self->pParams, SS); + return fVal; +} + /*--------------------------------------------------------------------------*/ - int GetMonoPositions(pSicsSelector self, SConnection *pCon, - float *fTh, float *f2TH, float *fB1, float *fB2) - { - int iRet; - char pBueffel[512]; +int GetMonoPositions(pSicsSelector self, SConnection * pCon, + float *fTh, float *f2TH, float *fB1, float *fB2) +{ + int iRet; + char pBueffel[512]; - iRet = MotorGetSoftPosition(self->pTheta,pCon,fTh); - if(!iRet) - { - sprintf(pBueffel,"ERROR: cannot read Theta motor for monochromator %s\n", - self->name); - SCWrite(pCon,pBueffel,eError); - return 0.; - } - iRet = MotorGetSoftPosition(self->pTwoTheta,pCon,f2TH); - if(!iRet) - { + iRet = MotorGetSoftPosition(self->pTheta, pCon, fTh); + if (!iRet) { + sprintf(pBueffel, + "ERROR: cannot read Theta motor for monochromator %s\n", + self->name); + SCWrite(pCon, pBueffel, eError); + return 0.; + } + iRet = MotorGetSoftPosition(self->pTwoTheta, pCon, f2TH); + if (!iRet) { + sprintf(pBueffel, + "ERROR: cannot read TwoTheta motor for monochromator %s\n", + self->name); + SCWrite(pCon, pBueffel, eError); + return 0.; + } + + if (self->pBend1) { + iRet = MotorGetSoftPosition(self->pBend1, pCon, fB1); + if (!iRet) { sprintf(pBueffel, - "ERROR: cannot read TwoTheta motor for monochromator %s\n", + "ERROR: cannot read vertical bender motor for monochromator %s\n", self->name); - SCWrite(pCon,pBueffel,eError); + SCWrite(pCon, pBueffel, eError); return 0.; } - - if(self->pBend1) - { - iRet = MotorGetSoftPosition(self->pBend1,pCon,fB1); - if(!iRet) - { - sprintf(pBueffel, - "ERROR: cannot read vertical bender motor for monochromator %s\n", + } + if (self->pBend2) { + iRet = MotorGetSoftPosition(self->pBend2, pCon, fB2); + if (!iRet) { + sprintf(pBueffel, + "ERROR: cannot read horizontal bender motor for monochromator %s\n", self->name); - SCWrite(pCon,pBueffel,eError); - return 0.; - } + SCWrite(pCon, pBueffel, eError); + return 0.; } - if(self->pBend2) - { - iRet = MotorGetSoftPosition(self->pBend2,pCon,fB2); - if(!iRet) - { - sprintf(pBueffel, - "ERROR: cannot read horizontal bender motor for monochromator %s\n", - self->name); - SCWrite(pCon,pBueffel,eError); - return 0.; - } - } - return 1; - } - + } + return 1; +} diff --git a/selector.h b/selector.h index ddeb0421..9380cb09 100644 --- a/selector.h +++ b/selector.h @@ -26,35 +26,34 @@ #define SICSMONO #include "motor.h" - typedef struct __SicsSelector *pSicsSelector; - - - /* birth and death: The Selector himself */ - pSicsSelector CreateSelector(char *name, pMotor pTheta, pMotor pTwoTheta, - pMotor pBend1, pMotor pBend2); - - int MonoInit(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); +typedef struct __SicsSelector *pSicsSelector; + + + /* birth and death: The Selector himself */ +pSicsSelector CreateSelector(char *name, pMotor pTheta, pMotor pTwoTheta, + pMotor pBend1, pMotor pBend2); + +int MonoInit(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +void DeleteSelector(void *self); - void DeleteSelector(void *self); - /* Action! */ - - int MonoAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int MonoRun(pSicsSelector self, SConnection *pCon, float fWaveLength); - struct __ComEntry *GetSelectorMotors(pSicsSelector self, SConnection *pCon, - float fNew); - int MonoLimits(pSicsSelector self, float fWaveLength, char *error, - int iErrLen); - int MonoCheck(pSicsSelector self, SConnection *pCon); - int MonoHalt(pSicsSelector self); - float GetMonoPosition(pSicsSelector self, SConnection *pCon); - char *MonoGetType(pSicsSelector self); - int GetMonoPositions(pSicsSelector self, SConnection *pCon, - float *fTheta, float *fTwtTh, float *fB1, float *fB2); - -#endif +int MonoAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int MonoRun(pSicsSelector self, SConnection * pCon, float fWaveLength); +struct __ComEntry *GetSelectorMotors(pSicsSelector self, + SConnection * pCon, float fNew); +int MonoLimits(pSicsSelector self, float fWaveLength, char *error, + int iErrLen); +int MonoCheck(pSicsSelector self, SConnection * pCon); +int MonoHalt(pSicsSelector self); +float GetMonoPosition(pSicsSelector self, SConnection * pCon); +char *MonoGetType(pSicsSelector self); +int GetMonoPositions(pSicsSelector self, SConnection * pCon, + float *fTheta, float *fTwtTh, float *fB1, float *fB2); + +#endif diff --git a/selvar.c b/selvar.c index 02683d8d..883ac172 100644 --- a/selvar.c +++ b/selvar.c @@ -58,450 +58,432 @@ lots of static functions necessary to initialize the ObjectDescriptor structures of our variables. ----------------------------------------------------------------------------*/ - static void *SelVarGetInterface(void *pData, int iID) - { - pSelVar self = NULL; - - self = (pSelVar)pData; - assert(self); - - if(iID == DRIVEID) - { - return self->pDrivInt; - } - else if(iID == CALLBACKINTERFACE) - { - return self->pCall; - } - return NULL; +static void *SelVarGetInterface(void *pData, int iID) +{ + pSelVar self = NULL; + + self = (pSelVar) pData; + assert(self); + + if (iID == DRIVEID) { + return self->pDrivInt; + } else if (iID == CALLBACKINTERFACE) { + return self->pCall; } + return NULL; +} /*--------------------------------------------------------------------------*/ - static float Energy2Wave(float fVal, SConnection *pCon) - { - float fWave; - char pBueffel[132]; - - if(fVal < .0) - { - sprintf(pBueffel,"ERROR: Invalid energy %f specified, defaulted to 20.", - fVal); - SCWrite(pCon,pBueffel,eError); - fWave = 20./2.07; - } - fWave = fVal/1000.; - fWave = sqrt(fWave); - fWave = 0.286/fWave; - return fWave; - } -/*--------------------------------------------------------------------------*/ - static int CheckWLLimits(void *pSelf, float fNew, char *error, int iErrLen) - { - pSelVar self = NULL; - - self = (pSelVar)pSelf; - assert(self); - assert(self->pDes); - assert(strcmp(self->pDes->name,"SicsSelVar") == 0); - assert(self->pSel); - - return MonoLimits(self->pSel,fNew,error,iErrLen); - } -/*--------------------------------------------------------------------------*/ - static int CheckELimits(void *pSelf, float fNew, char *error, int iErrLen) - { - pSelVar self = NULL; - float fWave; - char pBueffel[132]; - - self = (pSelVar)pSelf; - assert(self); - assert(self->pDes); - assert(strcmp(self->pDes->name,"SicsSelVar") == 0); - assert(self->pSel); +static float Energy2Wave(float fVal, SConnection * pCon) +{ + float fWave; + char pBueffel[132]; + + if (fVal < .0) { + sprintf(pBueffel, + "ERROR: Invalid energy %f specified, defaulted to 20.", fVal); + SCWrite(pCon, pBueffel, eError); + fWave = 20. / 2.07; + } + fWave = fVal / 1000.; + fWave = sqrt(fWave); + fWave = 0.286 / fWave; + return fWave; +} + +/*--------------------------------------------------------------------------*/ +static int CheckWLLimits(void *pSelf, float fNew, char *error, int iErrLen) +{ + pSelVar self = NULL; + + self = (pSelVar) pSelf; + assert(self); + assert(self->pDes); + assert(strcmp(self->pDes->name, "SicsSelVar") == 0); + assert(self->pSel); + + return MonoLimits(self->pSel, fNew, error, iErrLen); +} + +/*--------------------------------------------------------------------------*/ +static int CheckELimits(void *pSelf, float fNew, char *error, int iErrLen) +{ + pSelVar self = NULL; + float fWave; + char pBueffel[132]; + + self = (pSelVar) pSelf; + assert(self); + assert(self->pDes); + assert(strcmp(self->pDes->name, "SicsSelVar") == 0); + assert(self->pSel); + + fWave = fNew / 2.07; + if (fWave < .0) { + sprintf(pBueffel, "ERROR: Invalid energy %f specified", fNew); + strncpy(error, pBueffel, iErrLen); + return 0; + } + fWave = sqrt(fWave); + + return MonoLimits(self->pSel, fWave, error, iErrLen); +} - fWave = fNew/2.07; - if(fWave < .0) - { - sprintf(pBueffel,"ERROR: Invalid energy %f specified", - fNew); - strncpy(error,pBueffel,iErrLen); - return 0; - } - fWave = sqrt(fWave); - - return MonoLimits(self->pSel,fWave,error,iErrLen); - } /*-------------------------------------------------------------------------*/ - static long SetWL(void *pSelf, SConnection *pCon, float fNew ) - { - pSelVar self = NULL; - - self = (pSelVar)pSelf; - assert(self); - assert(self->pDes); - assert(strcmp(self->pDes->name,"SicsSelVar") == 0); - assert(self->pSel); - - return MonoRun(self->pSel,pCon,fNew); - } - +static long SetWL(void *pSelf, SConnection * pCon, float fNew) +{ + pSelVar self = NULL; + + self = (pSelVar) pSelf; + assert(self); + assert(self->pDes); + assert(strcmp(self->pDes->name, "SicsSelVar") == 0); + assert(self->pSel); + + return MonoRun(self->pSel, pCon, fNew); +} + /*-------------------------------------------------------------------------*/ - static long SetEnergy(void *pSelf, SConnection *pCon, float fNew) - { - pSelVar self = NULL; - - self = (pSelVar)pSelf; - assert(self); - assert(self->pDes); - assert(strcmp(self->pDes->name,"SicsSelVar") == 0); - assert(self->pSel); - - return MonoRun(self->pSel,pCon,Energy2Wave(fNew,pCon)); - } +static long SetEnergy(void *pSelf, SConnection * pCon, float fNew) +{ + pSelVar self = NULL; + + self = (pSelVar) pSelf; + assert(self); + assert(self->pDes); + assert(strcmp(self->pDes->name, "SicsSelVar") == 0); + assert(self->pSel); + + return MonoRun(self->pSel, pCon, Energy2Wave(fNew, pCon)); +} + /*------------------------------------------------------------------------*/ - static int CheckVal(void *pSelf, SConnection *pCon ) - { - pSelVar self = NULL; - int status; - - self = (pSelVar)pSelf; - assert(self); - assert(self->pDes); - assert(strcmp(self->pDes->name,"SicsSelVar") == 0); - assert(self->pSel); - assert(pCon); - - self->pCon = pCon; +static int CheckVal(void *pSelf, SConnection * pCon) +{ + pSelVar self = NULL; + int status; + + self = (pSelVar) pSelf; + assert(self); + assert(self->pDes); + assert(strcmp(self->pDes->name, "SicsSelVar") == 0); + assert(self->pSel); + assert(pCon); + + self->pCon = pCon; + InvokeCallBack(self->pCall, WLCHANGE, self); + status = MonoCheck(self->pSel, pCon); + if (status != HWBusy) { InvokeCallBack(self->pCall, WLCHANGE, self); - status = MonoCheck(self->pSel,pCon); - if(status != HWBusy) - { - InvokeCallBack(self->pCall, WLCHANGE, self); - } - return status; - } -/*------------------------------------------------------------------------*/ - static int HaltSelVar(void *pSelf) - { - pSelVar self = NULL; - - self = (pSelVar)pSelf; - assert(self); - assert(self->pDes); - assert(strcmp(self->pDes->name,"SicsSelVar") == 0); - assert(self->pSel); - - return MonoHalt(self->pSel); - } -/*-------------------------------------------------------------------------*/ - static float GetWL(void *pData, SConnection *pCon) - { - pSelVar pVar; - - pVar = (pSelVar)pData; - assert(pVar); - return GetMonoPosition(pVar->pSel,pCon); - } -/*-------------------------------------------------------------------------*/ - static float GetEE(void *pData, SConnection *pCon) - { - float fWave = 0; - pSelVar pVar; - - pVar = (pSelVar)pData; - assert(pVar); - - fWave = GetMonoPosition(pVar->pSel,pCon); - fWave = 0.286/fWave; - fWave = fWave*fWave*1000.; - return fWave; - } -/*------------------------------------------------------------------------*/ - pSelVar CreateWLVar(char *name, pSicsSelector pSel) - { - pSelVar pNew = NULL; - - assert(pSel); - assert(name); - - /* allocate memory */ - pNew = (pSelVar)malloc(sizeof(SelVar)); - if(!pNew) - { - return NULL; - } - pNew->pDes = CreateDescriptor("SicsSelVar"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - - pNew->pCall = CreateCallBackInterface(); - if(!pNew->pCall) - { - free(pNew); - return NULL; - } - /* initialize Descriptor */ - pNew->pDes->GetInterface = SelVarGetInterface; - - - /* initialise Drivable interface */ - pNew->pDrivInt = CreateDrivableInterface(); - if(!pNew->pDrivInt) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - } - pNew->pDrivInt->SetValue = SetWL; - pNew->pDrivInt->CheckStatus = CheckVal; - pNew->pDrivInt->GetValue = GetWL; - pNew->pDrivInt->CheckLimits = CheckWLLimits; - pNew->pDrivInt->Halt = HaltSelVar; - - /* intialize Rest */ - pNew->pSel = pSel; - pNew->name = strdup(name); - - return pNew; - } -/*------------------------------------------------------------------------*/ - pSelVar CreateEnergy(char *name, pSicsSelector pSel) - { - pSelVar pNew = NULL; - - assert(pSel); - assert(name); - - /* allocate memory */ - pNew = (pSelVar)malloc(sizeof(SelVar)); - if(!pNew) - { - return NULL; - } - pNew->pDes = CreateDescriptor("SicsSelVar"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - - /* create call back interface */ - pNew->pCall = CreateCallBackInterface(); - if(!pNew->pCall) - { - free(pNew); - return NULL; - } - - /* initialize Descriptor */ - pNew->pDes->GetInterface = SelVarGetInterface; - - /* initialise Drivable interface */ - pNew->pDrivInt = CreateDrivableInterface(); - if(!pNew->pDrivInt) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - } - pNew->pDrivInt->Halt = HaltSelVar; - pNew->pDrivInt->CheckLimits = CheckELimits; - pNew->pDrivInt->SetValue = SetEnergy; - pNew->pDrivInt->CheckStatus = CheckVal; - pNew->pDrivInt->GetValue = GetEE; - /* intialize Rest */ - pNew->pSel = pSel; - pNew->name = strdup(name); - - return pNew; - } -/*------------------------------------------------------------------------*/ - void DeleteSelVar(void *pSelf) - { - pSelVar self = NULL; - - assert(pSelf); - self = (pSelVar)pSelf; - assert(self->pDes); - assert(strcmp(self->pDes->name, "SicsSelVar") == 0); - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->pDrivInt) - { - free(self->pDrivInt); - } - if(self->pCall) - { - DeleteCallBackInterface(self->pCall); - } - if(self->name) - { - free(self->name); - } - free(self); - } -/*------------------------------------------------------------------------*/ - float GetSelValue(pSelVar self, SConnection *pCon) - { - assert(self); - return self->pDrivInt->GetValue(self,pCon); } - + return status; +} + +/*------------------------------------------------------------------------*/ +static int HaltSelVar(void *pSelf) +{ + pSelVar self = NULL; + + self = (pSelVar) pSelf; + assert(self); + assert(self->pDes); + assert(strcmp(self->pDes->name, "SicsSelVar") == 0); + assert(self->pSel); + + return MonoHalt(self->pSel); +} + +/*-------------------------------------------------------------------------*/ +static float GetWL(void *pData, SConnection * pCon) +{ + pSelVar pVar; + + pVar = (pSelVar) pData; + assert(pVar); + return GetMonoPosition(pVar->pSel, pCon); +} + +/*-------------------------------------------------------------------------*/ +static float GetEE(void *pData, SConnection * pCon) +{ + float fWave = 0; + pSelVar pVar; + + pVar = (pSelVar) pData; + assert(pVar); + + fWave = GetMonoPosition(pVar->pSel, pCon); + fWave = 0.286 / fWave; + fWave = fWave * fWave * 1000.; + return fWave; +} + +/*------------------------------------------------------------------------*/ +pSelVar CreateWLVar(char *name, pSicsSelector pSel) +{ + pSelVar pNew = NULL; + + assert(pSel); + assert(name); + + /* allocate memory */ + pNew = (pSelVar) malloc(sizeof(SelVar)); + if (!pNew) { + return NULL; + } + pNew->pDes = CreateDescriptor("SicsSelVar"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pCall) { + free(pNew); + return NULL; + } + /* initialize Descriptor */ + pNew->pDes->GetInterface = SelVarGetInterface; + + + /* initialise Drivable interface */ + pNew->pDrivInt = CreateDrivableInterface(); + if (!pNew->pDrivInt) { + DeleteDescriptor(pNew->pDes); + free(pNew); + return NULL; + } + pNew->pDrivInt->SetValue = SetWL; + pNew->pDrivInt->CheckStatus = CheckVal; + pNew->pDrivInt->GetValue = GetWL; + pNew->pDrivInt->CheckLimits = CheckWLLimits; + pNew->pDrivInt->Halt = HaltSelVar; + + /* intialize Rest */ + pNew->pSel = pSel; + pNew->name = strdup(name); + + return pNew; +} + +/*------------------------------------------------------------------------*/ +pSelVar CreateEnergy(char *name, pSicsSelector pSel) +{ + pSelVar pNew = NULL; + + assert(pSel); + assert(name); + + /* allocate memory */ + pNew = (pSelVar) malloc(sizeof(SelVar)); + if (!pNew) { + return NULL; + } + pNew->pDes = CreateDescriptor("SicsSelVar"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + + /* create call back interface */ + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pCall) { + free(pNew); + return NULL; + } + + /* initialize Descriptor */ + pNew->pDes->GetInterface = SelVarGetInterface; + + /* initialise Drivable interface */ + pNew->pDrivInt = CreateDrivableInterface(); + if (!pNew->pDrivInt) { + DeleteDescriptor(pNew->pDes); + free(pNew); + return NULL; + } + pNew->pDrivInt->Halt = HaltSelVar; + pNew->pDrivInt->CheckLimits = CheckELimits; + pNew->pDrivInt->SetValue = SetEnergy; + pNew->pDrivInt->CheckStatus = CheckVal; + pNew->pDrivInt->GetValue = GetEE; + /* intialize Rest */ + pNew->pSel = pSel; + pNew->name = strdup(name); + + return pNew; +} + +/*------------------------------------------------------------------------*/ +void DeleteSelVar(void *pSelf) +{ + pSelVar self = NULL; + + assert(pSelf); + self = (pSelVar) pSelf; + assert(self->pDes); + assert(strcmp(self->pDes->name, "SicsSelVar") == 0); + + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->pDrivInt) { + free(self->pDrivInt); + } + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + } + if (self->name) { + free(self->name); + } + free(self); +} + +/*------------------------------------------------------------------------*/ +float GetSelValue(pSelVar self, SConnection * pCon) +{ + assert(self); + return self->pDrivInt->GetValue(self, pCon); +} + /*------------------------------------------------------------------------- Syntax: MakeWL name monochromatorname AccesCode */ - int MakeWaveLengthVar(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet; - char pBueffel[132]; - pSicsSelector pMono = NULL; - pSelVar pNeu = NULL; - CommandList *pCom = NULL; +int MakeWaveLengthVar(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet; + char pBueffel[132]; + pSicsSelector pMono = NULL; + pSelVar pNeu = NULL; + CommandList *pCom = NULL; + + /* 99.99999999999 % of all code is argument checking! */ + argtolower(argc, argv); + if (argc < 3) { + sprintf(pBueffel, "ERROR: Insufficient number of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* argv[1] == name, argv[2] should be a monochromator, find it */ + pCom = FindCommand(pSics, argv[2]); + if (!pCom) { + sprintf(pBueffel, "ERROR: %s not found", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pMono = (pSicsSelector) pCom->pData; + if (!pMono) { + sprintf(pBueffel, "ERROR: %s is no monochromator", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!iHasType(pMono, "CrystalSelector")) { + sprintf(pBueffel, "ERROR: %s is no monochromator", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* got everything we need to set things up */ + pNeu = CreateWLVar(argv[1], pMono); + if (!pNeu) { + sprintf(pBueffel, "ERROR: Out of memory creating %s found", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = AddCommand(pSics, argv[1], WaveLengthAction, DeleteSelVar, pNeu); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + DeleteSelVar((void *) pNeu); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} - /* 99.99999999999 % of all code is argument checking! */ - argtolower(argc,argv); - if(argc < 3) - { - sprintf(pBueffel,"ERROR: Insufficient number of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* argv[1] == name, argv[2] should be a monochromator, find it */ - pCom = FindCommand(pSics,argv[2]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: %s not found",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pMono = (pSicsSelector)pCom->pData; - if(!pMono) - { - sprintf(pBueffel,"ERROR: %s is no monochromator",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!iHasType(pMono, "CrystalSelector")) - { - sprintf(pBueffel,"ERROR: %s is no monochromator",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* got everything we need to set things up */ - pNeu = CreateWLVar(argv[1],pMono); - if(!pNeu) - { - sprintf(pBueffel,"ERROR: Out of memory creating %s found",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = AddCommand(pSics,argv[1],WaveLengthAction,DeleteSelVar,pNeu); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - DeleteSelVar((void *)pNeu); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } /*--------------------------------------------------------------------------*/ - int MakeEnergyVar(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet; - char pBueffel[132]; - pSicsSelector pMono = NULL; - pSelVar pNeu = NULL; - CommandList *pCom = NULL; +int MakeEnergyVar(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet; + char pBueffel[132]; + pSicsSelector pMono = NULL; + pSelVar pNeu = NULL; + CommandList *pCom = NULL; + + /* 99.99999999999 % of all code is argument checking! */ + argtolower(argc, argv); + if (argc < 3) { + sprintf(pBueffel, "ERROR: Insufficient number of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* argv[1] == name, argv[2] should be a monochromator, find it */ + pCom = FindCommand(pSics, argv[2]); + if (!pCom) { + sprintf(pBueffel, "ERROR: %s not found", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pMono = (pSicsSelector) pCom->pData; + if (!pMono) { + sprintf(pBueffel, "ERROR: %s is no monochromator", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!iHasType(pMono, "CrystalSelector")) { + sprintf(pBueffel, "ERROR: %s is no monochromator", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* got everything we need to set things up */ + pNeu = CreateEnergy(argv[1], pMono); + if (!pNeu) { + sprintf(pBueffel, "ERROR: Out of memory creating %s found", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = AddCommand(pSics, argv[1], EnergyAction, DeleteSelVar, pNeu); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + DeleteSelVar((void *) pNeu); + return 0; + } + return 1; +} - /* 99.99999999999 % of all code is argument checking! */ - argtolower(argc,argv); - if(argc < 3) - { - sprintf(pBueffel,"ERROR: Insufficient number of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* argv[1] == name, argv[2] should be a monochromator, find it */ - pCom = FindCommand(pSics,argv[2]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: %s not found",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pMono = (pSicsSelector)pCom->pData; - if(!pMono) - { - sprintf(pBueffel,"ERROR: %s is no monochromator",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!iHasType(pMono,"CrystalSelector")) - { - sprintf(pBueffel,"ERROR: %s is no monochromator",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* got everything we need to set things up */ - pNeu = CreateEnergy(argv[1],pMono); - if(!pNeu) - { - sprintf(pBueffel,"ERROR: Out of memory creating %s found",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = AddCommand(pSics,argv[1],EnergyAction,DeleteSelVar,pNeu); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - DeleteSelVar((void *)pNeu); - return 0; - } - return 1; - } /*------------------------------------------------------------------------*/ - static int WaveLengthCallBack(int iEvent, void *pEvent, void *pUser) - { - SConnection *pCon = NULL; - pSelVar self = NULL; - float fVal; - char pBueffel[512]; - - pCon = (SConnection *)pUser; - self = (pSelVar)pEvent; - assert(pCon); - assert(self); - - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } +static int WaveLengthCallBack(int iEvent, void *pEvent, void *pUser) +{ + SConnection *pCon = NULL; + pSelVar self = NULL; + float fVal; + char pBueffel[512]; + + pCon = (SConnection *) pUser; + self = (pSelVar) pEvent; + assert(pCon); + assert(self); + + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + fVal = GetSelValue(self, pCon); + sprintf(pBueffel, "%s.value = %f", self->name, fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; +} - fVal = GetSelValue(self,pCon); - sprintf(pBueffel,"%s.value = %f", self->name, fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } /*-------------------------------------------------------------------------- very simple syntax: name - return current value @@ -509,145 +491,129 @@ no new code is needed to do that interest - enables automatic printing when changes. uninterest - disables printing of value changes -*/ - int WaveLengthAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[132]; - float fWave; - pSelVar self; - int iRet; - double dVal; - long lID; - - assert(pCon); - assert(pSics); - assert(pData); - self = (pSelVar)pData; - assert(self->pSel); - - if(argc > 1) /* set case or interest handling*/ - { - strtolower(argv[1]); - if(strcmp(argv[1],"interest") == 0) - { - lID = RegisterCallback(self->pCall, - WLCHANGE, WaveLengthCallBack, - SCCopyConnection(pCon), SCDeleteConnection); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"uninterest") == 0) - { - RemoveCallback2(self->pCall,pCon); - SCSendOK(pCon); - return 1; - } - - /* verify that argv[1] is a valid number */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[1],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: %s is NO valid number ",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(dVal < 0) - { - sprintf(pBueffel,"ERROR: %s cannnot be a valid wavelength",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +*/ +int WaveLengthAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[132]; + float fWave; + pSelVar self; + int iRet; + double dVal; + long lID; - /* - Removed, on demand of Lukas Keller, DMC + assert(pCon); + assert(pSics); + assert(pData); + self = (pSelVar) pData; + assert(self->pSel); + + if (argc > 1) { /* set case or interest handling */ + strtolower(argv[1]); + if (strcmp(argv[1], "interest") == 0) { + lID = RegisterCallback(self->pCall, + WLCHANGE, WaveLengthCallBack, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "uninterest") == 0) { + RemoveCallback2(self->pCall, pCon); + SCSendOK(pCon); + return 1; + } + + /* verify that argv[1] is a valid number */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[1], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: %s is NO valid number ", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (dVal < 0) { + sprintf(pBueffel, "ERROR: %s cannnot be a valid wavelength", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* + Removed, on demand of Lukas Keller, DMC sprintf(pBueffel,"%s %s %s",DRIVE,argv[0],argv[1]); return InterpExecute(pSics,pCon,pBueffel); - */ - snprintf(pBueffel,131,"ERROR: subcommand %s to %s not understood", - argv[1], argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - else /* get case */ - { - fWave = GetMonoPosition(self->pSel,pCon); - sprintf(pBueffel,"%s = %f",argv[0],fWave); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - return 0; - } -/*------------------------------------------------------------------------*/ - int EnergyAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[132]; - float fWave; - pSelVar self; - int iRet; - double dVal; - long lID; + */ + snprintf(pBueffel, 131, "ERROR: subcommand %s to %s not understood", + argv[1], argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } else { /* get case */ - assert(pCon); - assert(pSics); - assert(pData); - self = (pSelVar)pData; - assert(self->pSel); - - if(argc > 1) /* set case or interest/uninterest*/ - { - strtolower(argv[1]); - if(strcmp(argv[1],"interest") == 0) - { - lID = RegisterCallback(self->pCall, - WLCHANGE, WaveLengthCallBack, - pCon, NULL); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"uninterest") == 0) - { - RemoveCallback2(self->pCall,pCon); - SCSendOK(pCon); - return 1; - } - - /* verify that argv[1] is a valid number */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[1],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: %s is NO valid number ",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(dVal < 0) - { - sprintf(pBueffel,"ERROR: %s cannnot be a valid energy",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - - sprintf(pBueffel,"%s %s %s",DRIVE,argv[0],argv[1]); - return InterpExecute(pSics,pCon,pBueffel); - } - else /* get case */ - { - fWave = GetMonoPosition(self->pSel,pCon); - /* convert to energy */ - if(fWave >0.001) - { - fWave = 0.286/fWave; - fWave = fWave*fWave*1000.; - } - else - { - fWave = 777.77; - } - sprintf(pBueffel,"%s = %f",argv[0],fWave); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - return 0; + fWave = GetMonoPosition(self->pSel, pCon); + sprintf(pBueffel, "%s = %f", argv[0], fWave); + SCWrite(pCon, pBueffel, eValue); + return 1; } + return 0; +} + +/*------------------------------------------------------------------------*/ +int EnergyAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[132]; + float fWave; + pSelVar self; + int iRet; + double dVal; + long lID; + + assert(pCon); + assert(pSics); + assert(pData); + self = (pSelVar) pData; + assert(self->pSel); + + if (argc > 1) { /* set case or interest/uninterest */ + strtolower(argv[1]); + if (strcmp(argv[1], "interest") == 0) { + lID = RegisterCallback(self->pCall, + WLCHANGE, WaveLengthCallBack, pCon, NULL); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "uninterest") == 0) { + RemoveCallback2(self->pCall, pCon); + SCSendOK(pCon); + return 1; + } + + /* verify that argv[1] is a valid number */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[1], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: %s is NO valid number ", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (dVal < 0) { + sprintf(pBueffel, "ERROR: %s cannnot be a valid energy", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + + sprintf(pBueffel, "%s %s %s", DRIVE, argv[0], argv[1]); + return InterpExecute(pSics, pCon, pBueffel); + } else { /* get case */ + + fWave = GetMonoPosition(self->pSel, pCon); + /* convert to energy */ + if (fWave > 0.001) { + fWave = 0.286 / fWave; + fWave = fWave * fWave * 1000.; + } else { + fWave = 777.77; + } + sprintf(pBueffel, "%s = %f", argv[0], fWave); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + return 0; +} diff --git a/selvar.h b/selvar.h index 3386b69b..47ddb78f 100644 --- a/selvar.h +++ b/selvar.h @@ -16,23 +16,22 @@ #ifndef SICSSELVAR #define SICSSELVAR - typedef struct __SelVar *pSelVar; - -/*------------------------ birth and death --------------------------------*/ - pSelVar CreateWLVar(char *name, pSicsSelector pSel); - pSelVar CreateEnergy(char *name, pSicsSelector pSel); - void DeleteSelVar(void *pSelf); -/* ----------------------- Factory functions for initialization -----------*/ - int MakeWaveLengthVar(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int MakeEnergyVar(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -/*-------------------------------------------------------------------------*/ - float GetSelValue(pSelVar self, SConnection *pCon); -/*------------------------ Action functions -------------------------------*/ - int WaveLengthAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int EnergyAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -#endif +typedef struct __SelVar *pSelVar; +/*------------------------ birth and death --------------------------------*/ +pSelVar CreateWLVar(char *name, pSicsSelector pSel); +pSelVar CreateEnergy(char *name, pSicsSelector pSel); +void DeleteSelVar(void *pSelf); +/* ----------------------- Factory functions for initialization -----------*/ +int MakeWaveLengthVar(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int MakeEnergyVar(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +/*-------------------------------------------------------------------------*/ +float GetSelValue(pSelVar self, SConnection * pCon); +/*------------------------ Action functions -------------------------------*/ +int WaveLengthAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int EnergyAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +#endif diff --git a/serialsinq.h b/serialsinq.h index 4261d88f..bd7ba68f 100644 --- a/serialsinq.h +++ b/serialsinq.h @@ -22,20 +22,20 @@ #line 10 "serialsinq.w" - int SerialOpen(void **pData, char *pHost, int iPort, int iChannel); - int SerialForceOpen(void **pData, char *pHost, int iPort, int iChannel); - int SerialConfig(void **pData, int iTmo); - int SerialGetTmo(void **pData); - int SerialATerm(void **pData, char *pTerm); - int SerialAGetTerm(void **pData, char *pTerm, int iTermLen); - int SerialSendTerm(void **pData, char *pTerm); - int SerialGetSocket(void **pData); - int SerialClose(void **pData); - int SerialSend(void **pData, char *pCommand); - int SerialReceive(void **pData, char *pBuffer, int iBufLen); - int SerialError(int iError, char *pError, int iErrLen); - int SerialWriteRead(void **pData, char *pCommand, - char *pBuffer, int iBufLen); +int SerialOpen(void **pData, char *pHost, int iPort, int iChannel); +int SerialForceOpen(void **pData, char *pHost, int iPort, int iChannel); +int SerialConfig(void **pData, int iTmo); +int SerialGetTmo(void **pData); +int SerialATerm(void **pData, char *pTerm); +int SerialAGetTerm(void **pData, char *pTerm, int iTermLen); +int SerialSendTerm(void **pData, char *pTerm); +int SerialGetSocket(void **pData); +int SerialClose(void **pData); +int SerialSend(void **pData, char *pCommand); +int SerialReceive(void **pData, char *pBuffer, int iBufLen); +int SerialError(int iError, char *pError, int iErrLen); +int SerialWriteRead(void **pData, char *pCommand, + char *pBuffer, int iBufLen); #line 131 "serialsinq.w" @@ -43,8 +43,8 @@ #line 96 "serialsinq.w" - typedef int (*SerialSleep)(void *pData, int iTime); - void SetSerialSleep(void **pData, SerialSleep pFunc, void *pUserData); +typedef int (*SerialSleep) (void *pData, int iTime); +void SetSerialSleep(void **pData, SerialSleep pFunc, void *pUserData); #line 133 "serialsinq.w" diff --git a/serialwait.c b/serialwait.c index 8eb3aed9..f762584d 100644 --- a/serialwait.c +++ b/serialwait.c @@ -23,221 +23,196 @@ #define SDEBUG 1 */ /*--------------- The wait data structure --------------------------------*/ - typedef struct { - int iEnd; /* end signal flag */ - int iError; /* error returns */ - int iFirst; /* first call, receive only */ - time_t tEnd; /* not more then a minute! */ - pDynString data; /* reply data read */ - void **pData; /* the serial IO data structure */ - } SW, *pSW; - +typedef struct { + int iEnd; /* end signal flag */ + int iError; /* error returns */ + int iFirst; /* first call, receive only */ + time_t tEnd; /* not more then a minute! */ + pDynString data; /* reply data read */ + void **pData; /* the serial IO data structure */ +} SW, *pSW; + /*---------------- The signal function --------------------------------*/ - static void SWSignal(void *pUser, int iSignal, void *pSigData) - { - pSW self = NULL; - int *iInt; - - self = (pSW)pUser; - iInt = (int *)pSigData; - - if(iSignal == SICSINT) - { - if(*iInt > eContinue) - { - self->iEnd = 2; - } - } +static void SWSignal(void *pUser, int iSignal, void *pSigData) +{ + pSW self = NULL; + int *iInt; + + self = (pSW) pUser; + iInt = (int *) pSigData; + + if (iSignal == SICSINT) { + if (*iInt > eContinue) { + self->iEnd = 2; + } } +} + /*---------------------- The task function ------------------------------*/ - static int SWTask(void *pData) - { - pSW self = NULL; - char pReply[1024]; - int iRet, iCount; - char *pPtr; - - self = (pSW)pData; - assert(self); +static int SWTask(void *pData) +{ + pSW self = NULL; + char pReply[1024]; + int iRet, iCount; + char *pPtr; - - /* check for interrupt end */ - if(self->iEnd > 0) - { - return 0; - } - - /* check for timeout */ - if(time(NULL) >= self->tEnd) - { - self->iError = TIMEOUT; - self->iEnd = 3; - return 0; - } + self = (pSW) pData; + assert(self); - /* wait for a second */ - SicsWait(1); - - /* send a null command and read reply */ - if(!self->iFirst) - { - iRet = SerialSend(self->pData,""); - } - else - { - self->iFirst = 0; - } + /* check for interrupt end */ + if (self->iEnd > 0) { + return 0; + } + /* check for timeout */ + if (time(NULL) >= self->tEnd) { + self->iError = TIMEOUT; + self->iEnd = 3; + return 0; + } + + + /* wait for a second */ + SicsWait(1); + + /* send a null command and read reply */ + if (!self->iFirst) { + iRet = SerialSend(self->pData, ""); + } else { + self->iFirst = 0; + } + + pReply[0] = '\0'; + iRet = SerialReceive(self->pData, pReply, 1023); +#ifdef SDEBUG + printf("Primary answer: %s\n", pReply); +#endif + if ((iRet == TIMEOUT) || (iRet == SELECTFAIL)) { +#ifdef SDEBUG + printf("Return 1 on timeout\n"); +#endif + return 1; + } else if (iRet < 0) { + self->iError = iRet; + self->iEnd = 3; +#ifdef SDEBUG + printf("Error %d return Receive 0\n", iRet); +#endif + return 0; + } + + /* is there data ? */ + iCount = strlen(pReply); + if (iCount <= 0) { +#ifdef SDEBUG + printf("No data in Reply, return 1\n"); +#endif + return 1; + } + + /* do we have a tmo message ? */ + if (strncmp("?TMO", pReply, 4) == 0) { + /* is there additional data appended ? */ + if (iCount > 4) { + /* store what we have */ + pPtr = pReply + 4; + DynStringConcat(self->data, pPtr); + + /* set tmo high, read rest of reply */ + SerialConfig(self->pData, 90000); pReply[0] = '\0'; - iRet = SerialReceive(self->pData,pReply,1023); + iRet = SerialWriteRead(self->pData, "", pReply, 1023); #ifdef SDEBUG - printf("Primary answer: %s\n",pReply); -#endif - if((iRet == TIMEOUT) || (iRet == SELECTFAIL) ) - { -#ifdef SDEBUG - printf("Return 1 on timeout\n"); -#endif - return 1; - } - else if(iRet < 0) - { - self->iError = iRet; - self->iEnd = 3; -#ifdef SDEBUG - printf("Error %d return Receive 0\n", iRet); -#endif - return 0; - } - - /* is there data ? */ - iCount = strlen(pReply); - if(iCount <= 0) - { + printf(" sec rep: %s\n", pReply); +#endif + if (iRet != 1) { + self->iError = iRet; + self->iEnd = 3; #ifdef SDEBUG - printf("No data in Reply, return 1\n"); -#endif - return 1; + printf("return 0, on secondary read error\n"); +#endif + return 0; } - - /* do we have a tmo message ? */ - if(strncmp("?TMO",pReply,4) == 0) - { - /* is there additional data appended ? */ - if(iCount > 4) - { - /* store what we have */ - pPtr = pReply + 4; - DynStringConcat(self->data, pPtr); - - /* set tmo high, read rest of reply */ - SerialConfig(self->pData, 90000); - pReply[0] = '\0'; - iRet = SerialWriteRead(self->pData,"",pReply,1023); -#ifdef SDEBUG - printf(" sec rep: %s\n",pReply); -#endif - if(iRet != 1) - { - self->iError = iRet; - self->iEnd = 3; -#ifdef SDEBUG - printf("return 0, on secondary read error\n"); -#endif - return 0; - } - DynStringConcat(self->data,pReply); - self->iEnd = 1; -#ifdef SDEBUG - printf("Complete read on second try, return 0\n"); -#endif - return 0; - } - else /* schnuuuueeeeeffffff! no data, poll again */ - { + DynStringConcat(self->data, pReply); + self->iEnd = 1; #ifdef SDEBUG - printf("Do agaian, got a TMO \n"); + printf("Complete read on second try, return 0\n"); +#endif + return 0; + } else { /* schnuuuueeeeeffffff! no data, poll again */ + +#ifdef SDEBUG + printf("Do agaian, got a TMO \n"); #endif - return 1; - } - } - else /* we obtained all the data right away */ - { - DynStringConcat(self->data,pReply); - self->iEnd = 1; -#ifdef SDEBUG - printf("Return 0, received all data in one go \n"); -#endif - return 0; - } - /* should not get here */ -#ifdef SDEBUG - printf("Should not get here return 1\n"); -#endif return 1; + } + } else { /* we obtained all the data right away */ + + DynStringConcat(self->data, pReply); + self->iEnd = 1; +#ifdef SDEBUG + printf("Return 0, received all data in one go \n"); +#endif + return 0; + } + /* should not get here */ +#ifdef SDEBUG + printf("Should not get here return 1\n"); +#endif + return 1; +} + +/*-------------------------- The actual working function ------------------*/ +int SerialSicsExecute(void **pData, char *pCommand, + char *pReply, int iBufLen) +{ + int iOldTmo, iRet, iResult; + long lTask; + SW control; + char *pPtr; + + /* set timeout to 0 */ + iOldTmo = SerialGetTmo(pData); + SerialConfig(pData, 200); + + /* send the command to execute */ + iRet = SerialSend(pData, pCommand); + if (iRet != 1) { + SerialConfig(pData, iOldTmo); + return iRet; } -/*-------------------------- The actual working function ------------------*/ - int SerialSicsExecute(void **pData, char *pCommand, - char *pReply, int iBufLen) - { - int iOldTmo, iRet, iResult; - long lTask; - SW control; - char *pPtr; - - /* set timeout to 0 */ - iOldTmo = SerialGetTmo(pData); - SerialConfig(pData,200); - - /* send the command to execute */ - iRet = SerialSend(pData,pCommand); - if(iRet != 1) - { - SerialConfig(pData,iOldTmo); - return iRet; - } - - /* initialize task data structure */ - control.iEnd = 0; - control.iError = 0; - control.iFirst = 1; - control.pData = pData; - /* do a timeout after a minute without a reply */ - control.tEnd = time(NULL) + 60; - control.data = CreateDynString(1024,1024); - - /* start task */ - lTask = TaskRegister(pServ->pTasker, - SWTask, - SWSignal, - NULL, - &control, - 1); - /* wait for it to end */ - TaskWait(pServ->pTasker,lTask); - - /* analyse what we have got, success first */ - if(control.iEnd == 1) - { - iResult = 1; - pPtr = GetCharArray(control.data); - strncpy(pReply,pPtr,iBufLen); - } - else if(control.iEnd == 2) /* interrupted */ - { - iResult = INTERRUPTED; - } - else - { - iResult = control.iError; - } - control.iEnd = 10; - - /* clear up and go */ - DeleteDynString(control.data); - SerialConfig(pData,iOldTmo); - return iResult; + /* initialize task data structure */ + control.iEnd = 0; + control.iError = 0; + control.iFirst = 1; + control.pData = pData; + /* do a timeout after a minute without a reply */ + control.tEnd = time(NULL) + 60; + control.data = CreateDynString(1024, 1024); + + /* start task */ + lTask = TaskRegister(pServ->pTasker, + SWTask, SWSignal, NULL, &control, 1); + /* wait for it to end */ + TaskWait(pServ->pTasker, lTask); + + /* analyse what we have got, success first */ + if (control.iEnd == 1) { + iResult = 1; + pPtr = GetCharArray(control.data); + strncpy(pReply, pPtr, iBufLen); + } else if (control.iEnd == 2) { /* interrupted */ + iResult = INTERRUPTED; + } else { + iResult = control.iError; } + control.iEnd = 10; + + /* clear up and go */ + DeleteDynString(control.data); + SerialConfig(pData, iOldTmo); + return iResult; +} diff --git a/serialwait.h b/serialwait.h index d7193f9a..d750a61c 100644 --- a/serialwait.h +++ b/serialwait.h @@ -13,7 +13,7 @@ #define SERIALSICSWAIT #include "sics.h" #include "psi/hardsup/serialsinq.h" - int SerialSicsExecute(void **pData, char *pCommand, char *pReply, - int iBufLen); +int SerialSicsExecute(void **pData, char *pCommand, char *pReply, + int iBufLen); #endif diff --git a/servlog.c b/servlog.c index d5e4e133..0fddac65 100644 --- a/servlog.c +++ b/servlog.c @@ -66,54 +66,46 @@ The server log output can be captured by a client. In order to implement this the following code is necessary. */ - typedef struct __LogLog{ - SConnection *pCon; - OutCode iOut; - int iAllFlag; - struct __LogLog *pNext; - struct __LogLog *pPrevious; - } CaptureEntry, *pCaptureEntry; +typedef struct __LogLog { + SConnection *pCon; + OutCode iOut; + int iAllFlag; + struct __LogLog *pNext; + struct __LogLog *pPrevious; +} CaptureEntry, *pCaptureEntry; - static pCaptureEntry pCapture = NULL; +static pCaptureEntry pCapture = NULL; /*------------------------------------------------------------------------*/ - int KillCapture(SConnection *pCon) - { - pCaptureEntry pCurrent, pTemp; - - /* find first */ - pCurrent = pCapture; - while(pCurrent != NULL) - { - if(pCon == pCurrent->pCon) - { - /* relink */ - if(pCurrent->pPrevious) - { - pCurrent->pPrevious->pNext = pCurrent->pNext; - } - else - { - pCapture = pCurrent->pNext; - } - if(pCurrent->pNext) - { - pCurrent->pNext->pPrevious = pCurrent->pPrevious; - } - pTemp = pCurrent->pNext; - /* get rid of pCurrent */ - free(pCurrent); - pCurrent = pTemp; - } - else - { - pCurrent = pCurrent->pNext; - } - } - return 1; - } - - +int KillCapture(SConnection * pCon) +{ + pCaptureEntry pCurrent, pTemp; + + /* find first */ + pCurrent = pCapture; + while (pCurrent != NULL) { + if (pCon == pCurrent->pCon) { + /* relink */ + if (pCurrent->pPrevious) { + pCurrent->pPrevious->pNext = pCurrent->pNext; + } else { + pCapture = pCurrent->pNext; + } + if (pCurrent->pNext) { + pCurrent->pNext->pPrevious = pCurrent->pPrevious; + } + pTemp = pCurrent->pNext; + /* get rid of pCurrent */ + free(pCurrent); + pCurrent = pTemp; + } else { + pCurrent = pCurrent->pNext; + } + } + return 1; +} + + /* ------------------------------------------------------------------------ the command function: Syntax: @@ -121,206 +113,181 @@ Log OutCode starts loggin OutCode events All starts logging all events -------------------------------------------------------------------------- */ -#include "outcode.c" /* for pCode */ - - int LogCapture(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pCaptureEntry pNew = NULL; - char pBueffel[512]; - int i; - - /* check no af args */ - if(argc < 2) - { - sprintf(pBueffel,"Insufficient number of argumenst to %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - argtolower(argc,argv); - - /* Branch according to argv[1] */ - if(strcmp(argv[1],"kill") == 0 ) - { - KillCapture(pCon); - return 1; - } - else if(strcmp(argv[1],"all") == 0) - { - pNew = (pCaptureEntry)malloc(sizeof(CaptureEntry)); - if(!pNew) - { - SICSLogWrite("Out of memory in LogCapture",eInternal); - return 0; - } - if(pCapture) - { - pCapture->pPrevious = pNew; - } - pNew->pPrevious = NULL; - pNew->pNext = pCapture; - pCapture = pNew; - pNew->iAllFlag = 1; - pNew->pCon = pCon; - return 1; - } - else - { - /* must be outcode, try find it */ - i = 0; - while(pCode[i] != NULL) - { - if(strcmp(argv[1],pCode[i]) == 0) - { - break; - } - i++; - } - if(i > iNoCodes) - { - sprintf(pBueffel,"OutPutCode %s not recognized in %s",argv[1], - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* create a new one */ - pNew = (pCaptureEntry)malloc(sizeof(CaptureEntry)); - if(!pNew) - { - SICSLogWrite("Out of memory in LogCapture",eInternal); - return 0; - } - if(pCapture) - { - pCapture->pPrevious = pNew; - } - pNew->pPrevious = NULL; - pNew->pNext = pCapture; - pCapture = pNew; - pNew->iAllFlag = 0; - pNew->pCon = pCon; - pNew->iOut = i; - return 1; - } +#include "outcode.c" /* for pCode */ + +int LogCapture(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pCaptureEntry pNew = NULL; + char pBueffel[512]; + int i; + + /* check no af args */ + if (argc < 2) { + sprintf(pBueffel, "Insufficient number of argumenst to %s", argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } + argtolower(argc, argv); + + /* Branch according to argv[1] */ + if (strcmp(argv[1], "kill") == 0) { + KillCapture(pCon); + return 1; + } else if (strcmp(argv[1], "all") == 0) { + pNew = (pCaptureEntry) malloc(sizeof(CaptureEntry)); + if (!pNew) { + SICSLogWrite("Out of memory in LogCapture", eInternal); + return 0; + } + if (pCapture) { + pCapture->pPrevious = pNew; + } + pNew->pPrevious = NULL; + pNew->pNext = pCapture; + pCapture = pNew; + pNew->iAllFlag = 1; + pNew->pCon = pCon; + return 1; + } else { + /* must be outcode, try find it */ + i = 0; + while (pCode[i] != NULL) { + if (strcmp(argv[1], pCode[i]) == 0) { + break; + } + i++; + } + if (i > iNoCodes) { + sprintf(pBueffel, "OutPutCode %s not recognized in %s", argv[1], + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* create a new one */ + pNew = (pCaptureEntry) malloc(sizeof(CaptureEntry)); + if (!pNew) { + SICSLogWrite("Out of memory in LogCapture", eInternal); + return 0; + } + if (pCapture) { + pCapture->pPrevious = pNew; + } + pNew->pPrevious = NULL; + pNew->pNext = pCapture; + pCapture = pNew; + pNew->iAllFlag = 0; + pNew->pCon = pCon; + pNew->iOut = i; + return 1; + } + return 0; +} + /*--------------------------------------------------------------------------*/ - static int HasLineFeed(char *pText) - { - int i; - - for(i = strlen(pText); i > 0; i--) - { - if(pText[i] == '\n') - { - return 1; - } - if(isalpha(pText[i])) - { - return 0; - } - } - return 1; - } +static int HasLineFeed(char *pText) +{ + int i; + + for (i = strlen(pText); i > 0; i--) { + if (pText[i] == '\n') { + return 1; + } + if (isalpha(pText[i])) { + return 0; + } + } + return 1; +} /*---------------------------------------------------------------------------*/ #define MAXLOG 10000 #define MAXFILES 20 - static FILE *fLogFile = NULL; - static int iFile = 0; - static int iLineCount = 0; - static int iLogUsable = 1; +static FILE *fLogFile = NULL; +static int iFile = 0; +static int iLineCount = 0; +static int iLogUsable = 1; /*---------------------------------------------------------------------------*/ - int OpenVerifyLogFile() - { - char pFile[256]; - char filnam[512]; - char *pChar = NULL; +int OpenVerifyLogFile() +{ + char pFile[256]; + char filnam[512]; + char *pChar = NULL; - pChar = IFindOption(pSICSOptions,"LogFileBaseName"); - if(!pChar) - { /* Try to write to file "server" in*/ - strcpy(pFile,"server"); - } - else - { - strncpy(pFile,pChar,255); - } - snprintf(filnam,511,"%s%2.2d.log",pFile, iFile); - fLogFile = fopen(filnam,"w"); - if(!fLogFile) - { - fprintf(stderr,"ERROR: Cannot open logfile %s for writing\n",pFile); - fLogFile = NULL; - return 0; - } - else - { - return 1; - } + pChar = IFindOption(pSICSOptions, "LogFileBaseName"); + if (!pChar) { /* Try to write to file "server" in */ + strcpy(pFile, "server"); + } else { + strncpy(pFile, pChar, 255); } - -/*---------------------------------------------------------------------------*/ - void SICSLogEnable(int flag) { - iLogUsable=flag; + snprintf(filnam, 511, "%s%2.2d.log", pFile, iFile); + fLogFile = fopen(filnam, "w"); + if (!fLogFile) { + fprintf(stderr, "ERROR: Cannot open logfile %s for writing\n", pFile); + fLogFile = NULL; + return 0; + } else { + return 1; } +} + /*---------------------------------------------------------------------------*/ - void SICSLogWrite(char *pText, OutCode eOut) - { - char pFile[256]; - char *pChar = NULL; - pCaptureEntry pCurrent; - char pBueffel[256]; +void SICSLogEnable(int flag) +{ + iLogUsable = flag; +} + +/*---------------------------------------------------------------------------*/ +void SICSLogWrite(char *pText, OutCode eOut) +{ + char pFile[256]; + char *pChar = NULL; + pCaptureEntry pCurrent; + char pBueffel[256]; #ifdef NOLOG - return ; -#endif + return; +#endif - /* do all captured */ - pCurrent = pCapture; - while(pCurrent) - { - if( (pCurrent->iOut == eOut) || (pCurrent->iAllFlag == 1) ) - { - ANETwrite(pCurrent->pCon->sockHandle,pText,strlen(pText)); - ANETwrite(pCurrent->pCon->sockHandle,"\n",1); - } - pCurrent = pCurrent->pNext; - } - - if(0 == iLogUsable) return; - - if(fLogFile == NULL) /* first time of use*/ - { - /* no options: startup or serious trouble, print to stdout*/ - if(!pSICSOptions) - { - printf("WARNING: Cannot log(%s)\n",pText); - return; - } - iLogUsable = OpenVerifyLogFile(); - } - - /* switch file if too many lines */ - if(iLineCount >= MAXLOG) - { - fclose(fLogFile); - fLogFile = NULL; - iFile++; - iLineCount = 0; - if(iFile >= MAXFILES) - { - iFile = 0; - } - iLogUsable = OpenVerifyLogFile(); - } - - if(1 == iLogUsable) - { - fprintf(fLogFile,"%s\n",pText); - fflush(fLogFile); - iLineCount++; + /* do all captured */ + pCurrent = pCapture; + while (pCurrent) { + if ((pCurrent->iOut == eOut) || (pCurrent->iAllFlag == 1)) { + ANETwrite(pCurrent->pCon->sockHandle, pText, strlen(pText)); + ANETwrite(pCurrent->pCon->sockHandle, "\n", 1); } + pCurrent = pCurrent->pNext; } + + if (0 == iLogUsable) + return; + + if (fLogFile == NULL) { /* first time of use */ + /* no options: startup or serious trouble, print to stdout */ + if (!pSICSOptions) { + printf("WARNING: Cannot log(%s)\n", pText); + return; + } + iLogUsable = OpenVerifyLogFile(); + } + + /* switch file if too many lines */ + if (iLineCount >= MAXLOG) { + fclose(fLogFile); + fLogFile = NULL; + iFile++; + iLineCount = 0; + if (iFile >= MAXFILES) { + iFile = 0; + } + iLogUsable = OpenVerifyLogFile(); + } + + if (1 == iLogUsable) { + fprintf(fLogFile, "%s\n", pText); + fflush(fLogFile); + iLineCount++; + } +} diff --git a/servlog.h b/servlog.h index 6d88bbbf..c61615f5 100644 --- a/servlog.h +++ b/servlog.h @@ -15,10 +15,10 @@ #ifndef SICSLOG #define SICSLOG #include "Scommon.h" - void SICSLogWrite(char *ptext, OutCode eOut ); - void SICSLogEnable(int flag); - int KillCapture(SConnection *pCon); - - int LogCapture(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]); +void SICSLogWrite(char *ptext, OutCode eOut); +void SICSLogEnable(int flag); +int KillCapture(SConnection * pCon); + +int LogCapture(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]); #endif diff --git a/sgclib.c b/sgclib.c index 76ec59f2..7be51869 100644 --- a/sgclib.c +++ b/sgclib.c @@ -11,53 +11,56 @@ #include "sginfo.h" -static const char *Err_Ill_SMx_in_List = - "Error: Illegal SeitzMx in list"; +static const char *Err_Ill_SMx_in_List = "Error: Illegal SeitzMx in list"; void SetSgError(const char *msg) { - if (SgError == NULL) SgError = msg; + if (SgError == NULL) + SgError = msg; } int iModPositive(int ix, int iy) { - if (iy > 0) - { + if (iy > 0) { ix %= iy; - if (ix < 0) ix += iy; + if (ix < 0) + ix += iy; } return ix; } -static void SwapRTMx(T_RTMx *Mx_a, T_RTMx *Mx_b) +static void SwapRTMx(T_RTMx * Mx_a, T_RTMx * Mx_b) { - int i; - T_RTMx BufMx; + int i; + T_RTMx BufMx; - for (i = 0; i < 12; i++) BufMx.a[i] = Mx_a->a[i]; - for (i = 0; i < 12; i++) Mx_a->a[i] = Mx_b->a[i]; - for (i = 0; i < 12; i++) Mx_b->a[i] = BufMx.a[i]; + for (i = 0; i < 12; i++) + BufMx.a[i] = Mx_a->a[i]; + for (i = 0; i < 12; i++) + Mx_a->a[i] = Mx_b->a[i]; + for (i = 0; i < 12; i++) + Mx_b->a[i] = BufMx.a[i]; } -static void CopyRotMxInfo(T_RotMxInfo *target, const T_RotMxInfo *source) +static void CopyRotMxInfo(T_RotMxInfo * target, const T_RotMxInfo * source) { - memcpy(target, source, sizeof (*target)); + memcpy(target, source, sizeof(*target)); } -static void SwapRotMxInfo(T_RotMxInfo *RMx_a, T_RotMxInfo *RMx_b) +static void SwapRotMxInfo(T_RotMxInfo * RMx_a, T_RotMxInfo * RMx_b) { - T_RotMxInfo Buffer; + T_RotMxInfo Buffer; - memcpy(&Buffer, RMx_a, sizeof (Buffer)); - memcpy(RMx_a, RMx_b, sizeof (Buffer)); - memcpy(RMx_b, &Buffer, sizeof (Buffer)); + memcpy(&Buffer, RMx_a, sizeof(Buffer)); + memcpy(RMx_a, RMx_b, sizeof(Buffer)); + memcpy(RMx_b, &Buffer, sizeof(Buffer)); } @@ -69,9 +72,9 @@ int traceRotMx(const int *RotMx) int deterRotMx(const int *RotMx) { - int det; + int det; - det = RotMx[0] * (RotMx[4] * RotMx[8] - RotMx[5] * RotMx[7]); + det = RotMx[0] * (RotMx[4] * RotMx[8] - RotMx[5] * RotMx[7]); det -= RotMx[1] * (RotMx[3] * RotMx[8] - RotMx[5] * RotMx[6]); det += RotMx[2] * (RotMx[3] * RotMx[7] - RotMx[4] * RotMx[6]); @@ -79,339 +82,439 @@ int deterRotMx(const int *RotMx) } -void RotMx_t_Vector(int *R_t_V, const int *RotMx, const int *Vector, int FacTr) +void RotMx_t_Vector(int *R_t_V, const int *RotMx, const int *Vector, + int FacTr) { - const int *vec; + const int *vec; - if (FacTr > 0) - { - vec = Vector; - *R_t_V = *RotMx++ * *vec++; - *R_t_V += *RotMx++ * *vec++; - *R_t_V += *RotMx++ * *vec; - *R_t_V %= FacTr; if (*R_t_V < 0) *R_t_V += FacTr; - R_t_V++; - vec = Vector; - *R_t_V = *RotMx++ * *vec++; - *R_t_V += *RotMx++ * *vec++; - *R_t_V += *RotMx++ * *vec; - *R_t_V %= FacTr; if (*R_t_V < 0) *R_t_V += FacTr; - R_t_V++; - vec = Vector; - *R_t_V = *RotMx++ * *vec++; - *R_t_V += *RotMx++ * *vec++; - *R_t_V += *RotMx * *vec; - *R_t_V %= FacTr; if (*R_t_V < 0) *R_t_V += FacTr; - } - else - { - vec = Vector; - *R_t_V = *RotMx++ * *vec++; - *R_t_V += *RotMx++ * *vec++; + if (FacTr > 0) { + vec = Vector; + *R_t_V = *RotMx++ * *vec++; + *R_t_V += *RotMx++ * *vec++; + *R_t_V += *RotMx++ * *vec; + *R_t_V %= FacTr; + if (*R_t_V < 0) + *R_t_V += FacTr; + R_t_V++; + vec = Vector; + *R_t_V = *RotMx++ * *vec++; + *R_t_V += *RotMx++ * *vec++; + *R_t_V += *RotMx++ * *vec; + *R_t_V %= FacTr; + if (*R_t_V < 0) + *R_t_V += FacTr; + R_t_V++; + vec = Vector; + *R_t_V = *RotMx++ * *vec++; + *R_t_V += *RotMx++ * *vec++; + *R_t_V += *RotMx * *vec; + *R_t_V %= FacTr; + if (*R_t_V < 0) + *R_t_V += FacTr; + } else { + vec = Vector; + *R_t_V = *RotMx++ * *vec++; + *R_t_V += *RotMx++ * *vec++; *R_t_V++ += *RotMx++ * *vec; - vec = Vector; - *R_t_V = *RotMx++ * *vec++; - *R_t_V += *RotMx++ * *vec++; + vec = Vector; + *R_t_V = *RotMx++ * *vec++; + *R_t_V += *RotMx++ * *vec++; *R_t_V++ += *RotMx++ * *vec; - vec = Vector; - *R_t_V = *RotMx++ * *vec++; - *R_t_V += *RotMx++ * *vec++; - *R_t_V += *RotMx * *vec; + vec = Vector; + *R_t_V = *RotMx++ * *vec++; + *R_t_V += *RotMx++ * *vec++; + *R_t_V += *RotMx * *vec; } } void RotMxMultiply(int *rmxab, const int *rmxa, const int *rmxb) { - const int *a, *b; + const int *a, *b; /* no loops to be as fast as posslible */ a = rmxa; b = rmxb; - *rmxab = *a++ * *b; b += 3; /* r11 */ - *rmxab += *a++ * *b; b += 3; - *rmxab += *a * *b; b -= 5; - rmxab++; + *rmxab = *a++ * *b; + b += 3; /* r11 */ + *rmxab += *a++ * *b; + b += 3; + *rmxab += *a * *b; + b -= 5; + rmxab++; a = rmxa; - *rmxab = *a++ * *b; b += 3; /* r12 */ - *rmxab += *a++ * *b; b += 3; - *rmxab += *a * *b; b -= 5; - rmxab++; + *rmxab = *a++ * *b; + b += 3; /* r12 */ + *rmxab += *a++ * *b; + b += 3; + *rmxab += *a * *b; + b -= 5; + rmxab++; a = rmxa; - *rmxab = *a++ * *b; b += 3; /* r13 */ - *rmxab += *a++ * *b; b += 3; - *rmxab += *a++ * *b; b = rmxb; - rmxab++; + *rmxab = *a++ * *b; + b += 3; /* r13 */ + *rmxab += *a++ * *b; + b += 3; + *rmxab += *a++ * *b; + b = rmxb; + rmxab++; rmxa = a; - *rmxab = *a++ * *b; b += 3; /* r21 */ - *rmxab += *a++ * *b; b += 3; - *rmxab += *a * *b; b -= 5; - rmxab++; + *rmxab = *a++ * *b; + b += 3; /* r21 */ + *rmxab += *a++ * *b; + b += 3; + *rmxab += *a * *b; + b -= 5; + rmxab++; a = rmxa; - *rmxab = *a++ * *b; b += 3; /* r22 */ - *rmxab += *a++ * *b; b += 3; - *rmxab += *a * *b; b -= 5; - rmxab++; + *rmxab = *a++ * *b; + b += 3; /* r22 */ + *rmxab += *a++ * *b; + b += 3; + *rmxab += *a * *b; + b -= 5; + rmxab++; a = rmxa; - *rmxab = *a++ * *b; b += 3; /* r23 */ - *rmxab += *a++ * *b; b += 3; - *rmxab += *a++ * *b; b = rmxb; - rmxab++; + *rmxab = *a++ * *b; + b += 3; /* r23 */ + *rmxab += *a++ * *b; + b += 3; + *rmxab += *a++ * *b; + b = rmxb; + rmxab++; rmxa = a; - *rmxab = *a++ * *b; b += 3; /* r31 */ - *rmxab += *a++ * *b; b += 3; - *rmxab += *a * *b; b -= 5; - rmxab++; + *rmxab = *a++ * *b; + b += 3; /* r31 */ + *rmxab += *a++ * *b; + b += 3; + *rmxab += *a * *b; + b -= 5; + rmxab++; a = rmxa; - *rmxab = *a++ * *b; b += 3; /* r32 */ - *rmxab += *a++ * *b; b += 3; - *rmxab += *a * *b; b -= 5; - rmxab++; + *rmxab = *a++ * *b; + b += 3; /* r32 */ + *rmxab += *a++ * *b; + b += 3; + *rmxab += *a * *b; + b -= 5; + rmxab++; a = rmxa; - *rmxab = *a++ * *b; b += 3; /* r33 */ - *rmxab += *a++ * *b; b += 3; - *rmxab += *a * *b; + *rmxab = *a++ * *b; + b += 3; /* r33 */ + *rmxab += *a++ * *b; + b += 3; + *rmxab += *a * *b; } void RotateRotMx(int *RotMx, const int *RMx, const int *InvRMx) { - int BufMx[9]; + int BufMx[9]; RotMxMultiply(BufMx, RotMx, InvRMx); - RotMxMultiply(RotMx, RMx, BufMx); + RotMxMultiply(RotMx, RMx, BufMx); } -void SeitzMxMultiply(T_RTMx *smxab, const T_RTMx *smxa, const T_RTMx *smxb) +void SeitzMxMultiply(T_RTMx * smxab, const T_RTMx * smxa, + const T_RTMx * smxb) { - const int *ar, *a, *b, *bt; - int *ab; + const int *ar, *a, *b, *bt; + int *ab; /* no loops to be as fast as posslible */ ar = smxa->a; - a = smxa->a; - b = smxb->a; + a = smxa->a; + b = smxb->a; ab = smxab->a; - *ab = *a++ * *b; b += 3; /* r11 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r11 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r12 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r12 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r13 */ - *ab += *a++ * *b; b += 3; - *ab += *a++ * *b; b = smxb->a; - ab++; + *ab = *a++ * *b; + b += 3; /* r13 */ + *ab += *a++ * *b; + b += 3; + *ab += *a++ * *b; + b = smxb->a; + ab++; ar = a; - *ab = *a++ * *b; b += 3; /* r21 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r21 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r22 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r22 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r23 */ - *ab += *a++ * *b; b += 3; - *ab += *a++ * *b; b = smxb->a; - ab++; + *ab = *a++ * *b; + b += 3; /* r23 */ + *ab += *a++ * *b; + b += 3; + *ab += *a++ * *b; + b = smxb->a; + ab++; ar = a; - *ab = *a++ * *b; b += 3; /* r31 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r31 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r32 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r32 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r33 */ - *ab += *a++ * *b; b += 3; - *ab += *a++ * *b++; bt = b; - ab++; + *ab = *a++ * *b; + b += 3; /* r33 */ + *ab += *a++ * *b; + b += 3; + *ab += *a++ * *b++; + bt = b; + ab++; ar = smxa->a; - *ab = *ar++ * *b++; /* t1 */ + *ab = *ar++ * *b++; /* t1 */ *ab += *ar++ * *b++; - *ab += *ar++ * *b; b = bt; + *ab += *ar++ * *b; + b = bt; *ab += *a++; - *ab %= STBF; if (*ab < 0) *ab += STBF; - ab++; + *ab %= STBF; + if (*ab < 0) + *ab += STBF; + ab++; - *ab = *ar++ * *b++; /* t2 */ + *ab = *ar++ * *b++; /* t2 */ *ab += *ar++ * *b++; - *ab += *ar++ * *b; b = bt; + *ab += *ar++ * *b; + b = bt; *ab += *a++; - *ab %= STBF; if (*ab < 0) *ab += STBF; - ab++; + *ab %= STBF; + if (*ab < 0) + *ab += STBF; + ab++; - *ab = *ar++ * *b++; /* t3 */ + *ab = *ar++ * *b++; /* t3 */ *ab += *ar++ * *b++; - *ab += *ar * *b; + *ab += *ar * *b; *ab += *a; - *ab %= STBF; if (*ab < 0) *ab += STBF; + *ab %= STBF; + if (*ab < 0) + *ab += STBF; } -void RTMxMultiply(T_RTMx *rtmxab, const T_RTMx *rtmxa, const T_RTMx *rtmxb, - int FacAug, int FacTr) +void RTMxMultiply(T_RTMx * rtmxab, const T_RTMx * rtmxa, + const T_RTMx * rtmxb, int FacAug, int FacTr) { - const int *ar, *a, *b, *bt; - int *ab; + const int *ar, *a, *b, *bt; + int *ab; /* no loops to be as fast as posslible */ ar = rtmxa->a; - a = rtmxa->a; - b = rtmxb->a; + a = rtmxa->a; + b = rtmxb->a; ab = rtmxab->a; - *ab = *a++ * *b; b += 3; /* r11 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r11 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r12 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r12 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r13 */ - *ab += *a++ * *b; b += 3; - *ab += *a++ * *b; b = rtmxb->a; - ab++; + *ab = *a++ * *b; + b += 3; /* r13 */ + *ab += *a++ * *b; + b += 3; + *ab += *a++ * *b; + b = rtmxb->a; + ab++; ar = a; - *ab = *a++ * *b; b += 3; /* r21 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r21 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r22 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r22 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r23 */ - *ab += *a++ * *b; b += 3; - *ab += *a++ * *b; b = rtmxb->a; - ab++; + *ab = *a++ * *b; + b += 3; /* r23 */ + *ab += *a++ * *b; + b += 3; + *ab += *a++ * *b; + b = rtmxb->a; + ab++; ar = a; - *ab = *a++ * *b; b += 3; /* r31 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r31 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r32 */ - *ab += *a++ * *b; b += 3; - *ab += *a * *b; b -= 5; - ab++; + *ab = *a++ * *b; + b += 3; /* r32 */ + *ab += *a++ * *b; + b += 3; + *ab += *a * *b; + b -= 5; + ab++; a = ar; - *ab = *a++ * *b; b += 3; /* r33 */ - *ab += *a++ * *b; b += 3; - *ab += *a++ * *b++; bt = b; - ab++; + *ab = *a++ * *b; + b += 3; /* r33 */ + *ab += *a++ * *b; + b += 3; + *ab += *a++ * *b++; + bt = b; + ab++; - if (FacTr > 0) - { + if (FacTr > 0) { ar = rtmxa->a; - *ab = *ar++ * *b++; /* t1 */ + *ab = *ar++ * *b++; /* t1 */ *ab += *ar++ * *b++; - *ab += *ar++ * *b; b = bt; + *ab += *ar++ * *b; + b = bt; *ab += *a++ * FacAug; - *ab %= FacTr; if (*ab < 0) *ab += FacTr; - ab++; + *ab %= FacTr; + if (*ab < 0) + *ab += FacTr; + ab++; - *ab = *ar++ * *b++; /* t2 */ + *ab = *ar++ * *b++; /* t2 */ *ab += *ar++ * *b++; - *ab += *ar++ * *b; b = bt; + *ab += *ar++ * *b; + b = bt; *ab += *a++ * FacAug; - *ab %= FacTr; if (*ab < 0) *ab += FacTr; - ab++; + *ab %= FacTr; + if (*ab < 0) + *ab += FacTr; + ab++; - *ab = *ar++ * *b++; /* t3 */ + *ab = *ar++ * *b++; /* t3 */ *ab += *ar++ * *b++; - *ab += *ar * *b; - *ab += *a * FacAug; - *ab %= FacTr; if (*ab < 0) *ab += FacTr; - } - else - { + *ab += *ar * *b; + *ab += *a * FacAug; + *ab %= FacTr; + if (*ab < 0) + *ab += FacTr; + } else { ar = rtmxa->a; - *ab = *ar++ * *b++; /* t1 */ + *ab = *ar++ * *b++; /* t1 */ *ab += *ar++ * *b++; - *ab += *ar++ * *b; b = bt; + *ab += *ar++ * *b; + b = bt; *ab += *a++ * FacAug; - ab++; + ab++; - *ab = *ar++ * *b++; /* t2 */ + *ab = *ar++ * *b++; /* t2 */ *ab += *ar++ * *b++; - *ab += *ar++ * *b; b = bt; + *ab += *ar++ * *b; + b = bt; *ab += *a++ * FacAug; - ab++; + ab++; - *ab = *ar++ * *b++; /* t3 */ + *ab = *ar++ * *b++; /* t3 */ *ab += *ar++ * *b++; - *ab += *ar * *b; - *ab += *a * FacAug; + *ab += *ar * *b; + *ab += *a * FacAug; } } void InverseRotMx(const int *RotMx, int *InvRotMx) { - InvRotMx[0] = RotMx[4] * RotMx[8] - RotMx[5] * RotMx[7]; - InvRotMx[1] = - RotMx[1] * RotMx[8] + RotMx[2] * RotMx[7]; - InvRotMx[2] = RotMx[1] * RotMx[5] - RotMx[2] * RotMx[4]; - InvRotMx[3] = - RotMx[3] * RotMx[8] + RotMx[5] * RotMx[6]; - InvRotMx[4] = RotMx[0] * RotMx[8] - RotMx[2] * RotMx[6]; - InvRotMx[5] = - RotMx[0] * RotMx[5] + RotMx[2] * RotMx[3]; - InvRotMx[6] = RotMx[3] * RotMx[7] - RotMx[4] * RotMx[6]; - InvRotMx[7] = - RotMx[0] * RotMx[7] + RotMx[1] * RotMx[6]; - InvRotMx[8] = RotMx[0] * RotMx[4] - RotMx[1] * RotMx[3]; + InvRotMx[0] = RotMx[4] * RotMx[8] - RotMx[5] * RotMx[7]; + InvRotMx[1] = -RotMx[1] * RotMx[8] + RotMx[2] * RotMx[7]; + InvRotMx[2] = RotMx[1] * RotMx[5] - RotMx[2] * RotMx[4]; + InvRotMx[3] = -RotMx[3] * RotMx[8] + RotMx[5] * RotMx[6]; + InvRotMx[4] = RotMx[0] * RotMx[8] - RotMx[2] * RotMx[6]; + InvRotMx[5] = -RotMx[0] * RotMx[5] + RotMx[2] * RotMx[3]; + InvRotMx[6] = RotMx[3] * RotMx[7] - RotMx[4] * RotMx[6]; + InvRotMx[7] = -RotMx[0] * RotMx[7] + RotMx[1] * RotMx[6]; + InvRotMx[8] = RotMx[0] * RotMx[4] - RotMx[1] * RotMx[3]; } -void InverseRTMx(const T_RTMx *RTMx, T_RTMx *InvRTMx) +void InverseRTMx(const T_RTMx * RTMx, T_RTMx * InvRTMx) { - int *iR; - const int *T; + int *iR; + const int *T; iR = InvRTMx->s.R; @@ -420,31 +523,31 @@ void InverseRTMx(const T_RTMx *RTMx, T_RTMx *InvRTMx) T = RTMx->s.T; - InvRTMx->s.T[0] = - iR[0] * T[0] - iR[1] * T[1] - iR[2] * T[2]; - InvRTMx->s.T[1] = - iR[3] * T[0] - iR[4] * T[1] - iR[5] * T[2]; - InvRTMx->s.T[2] = - iR[6] * T[0] - iR[7] * T[1] - iR[8] * T[2]; + InvRTMx->s.T[0] = -iR[0] * T[0] - iR[1] * T[1] - iR[2] * T[2]; + InvRTMx->s.T[1] = -iR[3] * T[0] - iR[4] * T[1] - iR[5] * T[2]; + InvRTMx->s.T[2] = -iR[6] * T[0] - iR[7] * T[1] - iR[8] * T[2]; } -int IsSMxTransl0(const T_LatticeInfo *LatticeInfo, const int *SeitzMxT) +int IsSMxTransl0(const T_LatticeInfo * LatticeInfo, const int *SeitzMxT) { - int iTrV, nTrV, t; - const int *TrV; + int iTrV, nTrV, t; + const int *TrV; nTrV = LatticeInfo->nTrVector; - TrV = LatticeInfo->TrVector; + TrV = LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++) - { - t = (SeitzMxT[0] + TrV[0]) % STBF; + for (iTrV = 0; iTrV < nTrV; iTrV++) { + t = (SeitzMxT[0] + TrV[0]) % STBF; if (t == 0) { - t = (SeitzMxT[1] + TrV[1]) % STBF; + t = (SeitzMxT[1] + TrV[1]) % STBF; if (t == 0) { - t = (SeitzMxT[2] + TrV[2]) % STBF; + t = (SeitzMxT[2] + TrV[2]) % STBF; if (t == 0) return 1; - }} + } + } TrV += 3; } @@ -453,28 +556,33 @@ int IsSMxTransl0(const T_LatticeInfo *LatticeInfo, const int *SeitzMxT) } -static int IsSpecialSeitzMx(T_SgInfo *SgInfo, const T_RTMx *SMx, int ExpandLT) +static int IsSpecialSeitzMx(T_SgInfo * SgInfo, const T_RTMx * SMx, + int ExpandLT) { - int i, special, smx11; - const T_LatticeInfo *ExpLT; + int i, special, smx11; + const T_LatticeInfo *ExpLT; /* check rotation part for identity or inversion operation */ - smx11 = SMx->s.R[0]; - if ( smx11 != 1 - && smx11 != -1) return 0; + smx11 = SMx->s.R[0]; + if (smx11 != 1 && smx11 != -1) + return 0; - for (i = 1; i < 9; i++) - { + for (i = 1; i < 9; i++) { if (i % 4) { - if (SMx->s.R[i] != 0) return 0; } - else { - if (SMx->s.R[i] != smx11) return 0; } + if (SMx->s.R[i] != 0) + return 0; + } else { + if (SMx->s.R[i] != smx11) + return 0; + } } - if (smx11 == 1) special = SpecialSMx_Identity; - else special = SpecialSMx_Inversion; + if (smx11 == 1) + special = SpecialSMx_Identity; + else + special = SpecialSMx_Inversion; /* rotation part is identity or inversion check translation part now @@ -483,38 +591,49 @@ static int IsSpecialSeitzMx(T_SgInfo *SgInfo, const T_RTMx *SMx, int ExpandLT) if (IsSMxTransl0(SgInfo->LatticeInfo, SMx->s.T) == 1) return (special | SpecialSMx_Transl0); - if (ExpandLT && (smx11 == 1 || SgInfo->Centric)) - { + if (ExpandLT && (smx11 == 1 || SgInfo->Centric)) { /* try to expand lattice type */ ExpLT = NULL; - switch (SgInfo->LatticeInfo->Code) - { - case 'P': - if (IsSMxTransl0(LI_A, SMx->s.T) == 1) - { ExpLT = LI_A; break; } - if (IsSMxTransl0(LI_B, SMx->s.T) == 1) - { ExpLT = LI_B; break; } - if (IsSMxTransl0(LI_C, SMx->s.T) == 1) - { ExpLT = LI_C; break; } - if (IsSMxTransl0(LI_I, SMx->s.T) == 1) - { ExpLT = LI_I; break; } - if (IsSMxTransl0(LI_R, SMx->s.T) == 1) - { ExpLT = LI_R; break; } - if (IsSMxTransl0(LI_S, SMx->s.T) == 1) - { ExpLT = LI_S; break; } - if (IsSMxTransl0(LI_T, SMx->s.T) == 1) - { ExpLT = LI_T; break; } - case 'A': - case 'B': - case 'C': - if (IsSMxTransl0(LI_F, SMx->s.T) == 1) - ExpLT = LI_F; + switch (SgInfo->LatticeInfo->Code) { + case 'P': + if (IsSMxTransl0(LI_A, SMx->s.T) == 1) { + ExpLT = LI_A; + break; + } + if (IsSMxTransl0(LI_B, SMx->s.T) == 1) { + ExpLT = LI_B; + break; + } + if (IsSMxTransl0(LI_C, SMx->s.T) == 1) { + ExpLT = LI_C; + break; + } + if (IsSMxTransl0(LI_I, SMx->s.T) == 1) { + ExpLT = LI_I; + break; + } + if (IsSMxTransl0(LI_R, SMx->s.T) == 1) { + ExpLT = LI_R; + break; + } + if (IsSMxTransl0(LI_S, SMx->s.T) == 1) { + ExpLT = LI_S; + break; + } + if (IsSMxTransl0(LI_T, SMx->s.T) == 1) { + ExpLT = LI_T; + break; + } + case 'A': + case 'B': + case 'C': + if (IsSMxTransl0(LI_F, SMx->s.T) == 1) + ExpLT = LI_F; } - if (ExpLT != NULL) - { + if (ExpLT != NULL) { SgInfo->LatticeInfo = ExpLT; SgInfo->StatusLatticeTr = -1; return (special | SpecialSMx_Transl0); @@ -525,35 +644,36 @@ static int IsSpecialSeitzMx(T_SgInfo *SgInfo, const T_RTMx *SMx, int ExpandLT) } -int CompareSeitzMx(const T_LatticeInfo *LatticeInfo, - const T_RTMx *SeitzMxA, const T_RTMx *SeitzMxB) +int CompareSeitzMx(const T_LatticeInfo * LatticeInfo, + const T_RTMx * SeitzMxA, const T_RTMx * SeitzMxB) { - int i, iTrV, nTrV, t; - const int *TrV; + int i, iTrV, nTrV, t; + const int *TrV; /* compare rotation part */ for (i = 0; i < 9; i++) - if (SeitzMxA->s.R[i] != SeitzMxB->s.R[i]) return 1; + if (SeitzMxA->s.R[i] != SeitzMxB->s.R[i]) + return 1; /* rotation part is same check translation */ nTrV = LatticeInfo->nTrVector; - TrV = LatticeInfo->TrVector; + TrV = LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) - { - t = (SeitzMxA->s.T[0] + TrV[0]) % STBF; - if (t == SeitzMxB->s.T[0]) { - t = (SeitzMxA->s.T[1] + TrV[1]) % STBF; - if (t == SeitzMxB->s.T[1]) { - t = (SeitzMxA->s.T[2] + TrV[2]) % STBF; + for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) { + t = (SeitzMxA->s.T[0] + TrV[0]) % STBF; + if (t == SeitzMxB->s.T[0]) { + t = (SeitzMxA->s.T[1] + TrV[1]) % STBF; + if (t == SeitzMxB->s.T[1]) { + t = (SeitzMxA->s.T[2] + TrV[2]) % STBF; if (t == SeitzMxB->s.T[2]) return 0; - }} + } + } } return -1; @@ -564,20 +684,31 @@ int GetRotMxOrder(const int *RotMx) { int deter = deterRotMx(RotMx); - if (deter == -1 || deter == 1) - { - switch (traceRotMx(RotMx)) - { - case -3: return -1; - case -2: return -6; - case -1: if (deter == -1) return -4; - else return 2; - case 0: if (deter == -1) return -3; - else return 3; - case 1: if (deter == -1) return -2; - else return 4; - case 2: return 6; - case 3: return 1; + if (deter == -1 || deter == 1) { + switch (traceRotMx(RotMx)) { + case -3: + return -1; + case -2: + return -6; + case -1: + if (deter == -1) + return -4; + else + return 2; + case 0: + if (deter == -1) + return -3; + else + return 3; + case 1: + if (deter == -1) + return -2; + else + return 4; + case 2: + return 6; + case 3: + return 1; } } @@ -588,17 +719,24 @@ int GetRotMxOrder(const int *RotMx) static int nNextBasis_of_DirCode(const int DirCode, const int **RMx, const int **InvRMx) { - switch (DirCode) - { - case '.': *RMx = *InvRMx = NULL; return 1; - case '=': - case '"': - case '\'': - case '|': - case '\\': *RMx = RMx_3_111; *InvRMx = RMx_3i111; return 3; - case '*': *RMx = RMx_4_001; *InvRMx = RMx_4i001; return 4; - default: - break; + switch (DirCode) { + case '.': + *RMx = *InvRMx = NULL; + return 1; + case '=': + case '"': + case '\'': + case '|': + case '\\': + *RMx = RMx_3_111; + *InvRMx = RMx_3i111; + return 3; + case '*': + *RMx = RMx_4_001; + *InvRMx = RMx_4i001; + return 4; + default: + break; } SetSgError("Internal Error: Corrupt DirCode"); @@ -606,82 +744,86 @@ static int nNextBasis_of_DirCode(const int DirCode, } -int GetRotMxInfo(const int *RotMx, T_RotMxInfo *RotMxInfo) +int GetRotMxInfo(const int *RotMx, T_RotMxInfo * RotMxInfo) { - int i; - int nNextBasis, iNextBasis; - int nLoopInv, iLoopInv; - int Order, AbsOrder; - int RMxCopy[9], MatchMx[9], InvMatchMx[9], REV[3]; - int *mmx; - const int *NBRMx, *InvNBRMx; + int i; + int nNextBasis, iNextBasis; + int nLoopInv, iLoopInv; + int Order, AbsOrder; + int RMxCopy[9], MatchMx[9], InvMatchMx[9], REV[3]; + int *mmx; + const int *NBRMx, *InvNBRMx; - const T_TabXtalRotMx *txrmx; + const T_TabXtalRotMx *txrmx; Order = GetRotMxOrder(RotMx); if (RotMxInfo) - RotMxInfo->Order = Order; + RotMxInfo->Order = Order; - if (Order) - { + if (Order) { AbsOrder = abs(Order); if (Order > 0) - for (i = 0; i < 9; i++) RMxCopy[i] = RotMx[i]; + for (i = 0; i < 9; i++) + RMxCopy[i] = RotMx[i]; else - for (i = 0; i < 9; i++) RMxCopy[i] = -RotMx[i]; + for (i = 0; i < 9; i++) + RMxCopy[i] = -RotMx[i]; for (txrmx = TabXtalRotMx; txrmx->Order; txrmx++) - if (txrmx->Order == AbsOrder) break; + if (txrmx->Order == AbsOrder) + break; - while (txrmx->Order == AbsOrder) - { - nNextBasis = nNextBasis_of_DirCode(txrmx->DirCode, &NBRMx, &InvNBRMx); + while (txrmx->Order == AbsOrder) { + nNextBasis = + nNextBasis_of_DirCode(txrmx->DirCode, &NBRMx, &InvNBRMx); if (nNextBasis < 0) return 0; - if (AbsOrder > 2) nLoopInv = 2; - else nLoopInv = 1; + if (AbsOrder > 2) + nLoopInv = 2; + else + nLoopInv = 1; - for (i = 0; i < 9; i++) MatchMx[i] = txrmx->RMx[i]; + for (i = 0; i < 9; i++) + MatchMx[i] = txrmx->RMx[i]; - for (iNextBasis = 0; iNextBasis < nNextBasis; iNextBasis++) - { + for (iNextBasis = 0; iNextBasis < nNextBasis; iNextBasis++) { if (iNextBasis) RotateRotMx(MatchMx, NBRMx, InvNBRMx); mmx = MatchMx; - for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) - { - if (iLoopInv) - { + for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) { + if (iLoopInv) { InverseRotMx(MatchMx, InvMatchMx); mmx = InvMatchMx; } for (i = 0; i < 9; i++) - if (mmx[i] != RMxCopy[i]) break; + if (mmx[i] != RMxCopy[i]) + break; - if (i == 9) /* matrix has been found */ - { - if (RotMxInfo) - { + if (i == 9) { /* matrix has been found */ + if (RotMxInfo) { RotMxInfo->Inverse = iLoopInv; - if (nNextBasis == 3) - { - switch(iNextBasis) - { - case 0: RotMxInfo->RefAxis = 'z'; break; - case 1: RotMxInfo->RefAxis = 'x'; break; - case 2: RotMxInfo->RefAxis = 'y'; break; + if (nNextBasis == 3) { + switch (iNextBasis) { + case 0: + RotMxInfo->RefAxis = 'z'; + break; + case 1: + RotMxInfo->RefAxis = 'x'; + break; + case 2: + RotMxInfo->RefAxis = 'y'; + break; } - } - else + } else RotMxInfo->RefAxis = 'o'; RotMxInfo->DirCode = txrmx->DirCode; @@ -689,12 +831,10 @@ int GetRotMxInfo(const int *RotMx, T_RotMxInfo *RotMxInfo) for (i = 0; i < 3; i++) RotMxInfo->EigenVector[i] = txrmx->EigenVector[i]; - for (; iNextBasis--;) - { + for (; iNextBasis--;) { RotMx_t_Vector(REV, NBRMx, RotMxInfo->EigenVector, 0); - if (iNextBasis-- == 0) - { + if (iNextBasis-- == 0) { for (i = 0; i < 3; i++) RotMxInfo->EigenVector[i] = REV[i]; @@ -718,17 +858,16 @@ int GetRotMxInfo(const int *RotMx, T_RotMxInfo *RotMxInfo) } -const T_RotMxInfo *ListOrBufRotMxInfo(const T_SgInfo *SgInfo, int iList, - T_RotMxInfo *BufRotMxInfo) +const T_RotMxInfo *ListOrBufRotMxInfo(const T_SgInfo * SgInfo, int iList, + T_RotMxInfo * BufRotMxInfo) { - T_RotMxInfo *RMxI; + T_RotMxInfo *RMxI; - RMxI = SgInfo->ListRotMxInfo; + RMxI = SgInfo->ListRotMxInfo; if (RMxI) - RMxI += iList; - else - { + RMxI += iList; + else { RMxI = BufRotMxInfo; if (GetRotMxInfo(SgInfo->ListSeitzMx[iList].s.R, RMxI) == 0) { @@ -741,42 +880,45 @@ const T_RotMxInfo *ListOrBufRotMxInfo(const T_SgInfo *SgInfo, int iList, } -static int CoreAdd2ListSeitzMx(T_SgInfo *SgInfo, const T_RTMx *NewSMx) +static int CoreAdd2ListSeitzMx(T_SgInfo * SgInfo, const T_RTMx * NewSMx) { - int i, iList; - T_RTMx *lsmx; - T_RotMxInfo RotMxInfo; - const T_LatticeInfo *LI; + int i, iList; + T_RTMx *lsmx; + T_RotMxInfo RotMxInfo; + const T_LatticeInfo *LI; static const char *Err_NonXtalOp = - "Error: Generators produce non-crystallographic operation"; + "Error: Generators produce non-crystallographic operation"; - if (SgInfo->GenOption) LI = SgInfo->LatticeInfo; - else LI = LI_P; + if (SgInfo->GenOption) + LI = SgInfo->LatticeInfo; + else + LI = LI_P; lsmx = SgInfo->ListSeitzMx; for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) if (CompareSeitzMx(LI, NewSMx, lsmx) == 0) - return 0; /* matrix is not unique */ + return 0; /* matrix is not unique */ if (GetRotMxInfo(NewSMx->s.R, &RotMxInfo) == 0) { SetSgError(Err_NonXtalOp); return -1; } - if (SgInfo->nList >= SgInfo->MaxList) - { + if (SgInfo->nList >= SgInfo->MaxList) { if (SgInfo->nList >= 192) SetSgError(Err_NonXtalOp); else - SetSgError("Internal Error: Allocated space for ListSeitzMx too small"); + SetSgError + ("Internal Error: Allocated space for ListSeitzMx too small"); return -1; } - for (i = 0; i < 12; i++) lsmx->a[i] = NewSMx->a[i]; + for (i = 0; i < 12; i++) + lsmx->a[i] = NewSMx->a[i]; if (SgInfo->ListRotMxInfo != NULL) CopyRotMxInfo(&SgInfo->ListRotMxInfo[SgInfo->nList], &RotMxInfo); @@ -787,18 +929,17 @@ static int CoreAdd2ListSeitzMx(T_SgInfo *SgInfo, const T_RTMx *NewSMx) } -int Add2ListSeitzMx(T_SgInfo *SgInfo, const T_RTMx *NewSMx) +int Add2ListSeitzMx(T_SgInfo * SgInfo, const T_RTMx * NewSMx) { - int i, special, Enter; - int iMult, jMult; - T_RTMx TrialSMx, *iMultSMx, *jMultSMx; + int i, special, Enter; + int iMult, jMult; + T_RTMx TrialSMx, *iMultSMx, *jMultSMx; static const char *Err_Ill_lattice_translation = - "Error: Illegal lattice translation"; + "Error: Illegal lattice translation"; - if (SgInfo->nList == 0) - { + if (SgInfo->nList == 0) { /* make sure identity matrix is first in list */ InitSeitzMx(&TrialSMx, 1); @@ -808,62 +949,53 @@ int Add2ListSeitzMx(T_SgInfo *SgInfo, const T_RTMx *NewSMx) } for (i = 0; i < 9; i++) - TrialSMx.s.R[i] = NewSMx->s.R[i]; + TrialSMx.s.R[i] = NewSMx->s.R[i]; for (i = 0; i < 3; i++) { - TrialSMx.s.T[i] = NewSMx->s.T[i] % STBF; + TrialSMx.s.T[i] = NewSMx->s.T[i] % STBF; if (TrialSMx.s.T[i] < 0) - TrialSMx.s.T[i] += STBF; + TrialSMx.s.T[i] += STBF; } iMult = SgInfo->nList; iMultSMx = &SgInfo->ListSeitzMx[iMult]; jMult = 1; - jMultSMx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ + jMultSMx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ - for (;;) - { + for (;;) { Enter = 1; special = IsSpecialSeitzMx(SgInfo, &TrialSMx, 1); - if (special & SpecialSMx_Identity) - { - if (! (special & SpecialSMx_Transl0)) { + if (special & SpecialSMx_Identity) { + if (!(special & SpecialSMx_Transl0)) { SetSgError(Err_Ill_lattice_translation); return -1; } if (SgInfo->GenOption) Enter = 0; - } - else if (special & SpecialSMx_Inversion) - { - if (! (special & SpecialSMx_Transl0)) - { + } else if (special & SpecialSMx_Inversion) { + if (!(special & SpecialSMx_Transl0)) { if (SgInfo->Centric) { SetSgError(Err_Ill_lattice_translation); return -1; } SgInfo->InversionOffOrigin = 1; - } - else - { + } else { if (SgInfo->InversionOffOrigin) SgInfo->Centric = 1; SgInfo->InversionOffOrigin = 0; - if (SgInfo->GenOption) - { + if (SgInfo->GenOption) { if (SgInfo->Centric == 0) - SgInfo->Centric = -1; + SgInfo->Centric = -1; Enter = 0; - } - else + } else SgInfo->Centric = 1; } } @@ -874,13 +1006,12 @@ int Add2ListSeitzMx(T_SgInfo *SgInfo, const T_RTMx *NewSMx) if (SgInfo->GenOption < 0) break; - if (jMult > iMult) - { + if (jMult > iMult) { iMult++; iMultSMx++; jMult = 1; - jMultSMx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ + jMultSMx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ } if (iMult == SgInfo->nList) @@ -896,30 +1027,29 @@ int Add2ListSeitzMx(T_SgInfo *SgInfo, const T_RTMx *NewSMx) } -int AddInversion2ListSeitzMx(T_SgInfo *SgInfo) +int AddInversion2ListSeitzMx(T_SgInfo * SgInfo) { - T_RTMx SeitzMx; + T_RTMx SeitzMx; InitSeitzMx(&SeitzMx, -1); return Add2ListSeitzMx(SgInfo, &SeitzMx); } -int AddLatticeTr2ListSeitzMx(T_SgInfo *SgInfo, - const T_LatticeInfo *LatticeInfo) +int AddLatticeTr2ListSeitzMx(T_SgInfo * SgInfo, + const T_LatticeInfo * LatticeInfo) { - int iTrV, nTrV; - const int *TrV; - T_RTMx SeitzMx; + int iTrV, nTrV; + const int *TrV; + T_RTMx SeitzMx; InitRotMx(SeitzMx.s.R, 1); nTrV = LatticeInfo->nTrVector; - TrV = &LatticeInfo->TrVector[3]; /* skip first vector which is always 000 */ + TrV = &LatticeInfo->TrVector[3]; /* skip first vector which is always 000 */ - for (iTrV = 1; iTrV < nTrV; iTrV++) - { + for (iTrV = 1; iTrV < nTrV; iTrV++) { SeitzMx.s.T[0] = *TrV++; SeitzMx.s.T[1] = *TrV++; SeitzMx.s.T[2] = *TrV++; @@ -937,49 +1067,44 @@ int AddLatticeTr2ListSeitzMx(T_SgInfo *SgInfo, } -static int RemoveLatticeTr(T_SgInfo *SgInfo) +static int RemoveLatticeTr(T_SgInfo * SgInfo) { - int iList, jList, i; - T_RTMx *smxi, *smxj, *lastsmx; - T_RotMxInfo *lrmxi, *lastrmxi; + int iList, jList, i; + T_RTMx *smxi, *smxj, *lastsmx; + T_RotMxInfo *lrmxi, *lastrmxi; if (SgInfo->LatticeInfo->Code == 'P') return 0; - if (SgInfo->StatusLatticeTr == -1) - { + if (SgInfo->StatusLatticeTr == -1) { if (AddLatticeTr2ListSeitzMx(SgInfo, SgInfo->LatticeInfo) < 0) return -1; } iList = 0; - while (iList < SgInfo->nList) - { + while (iList < SgInfo->nList) { smxi = &SgInfo->ListSeitzMx[iList]; jList = iList + 1; - while (jList < SgInfo->nList) - { + while (jList < SgInfo->nList) { smxj = &SgInfo->ListSeitzMx[jList]; - if (CompareSeitzMx(SgInfo->LatticeInfo, smxi, smxj) == 0) - { + if (CompareSeitzMx(SgInfo->LatticeInfo, smxi, smxj) == 0) { /* copy last element to this place */ SgInfo->nList--; lastsmx = &SgInfo->ListSeitzMx[SgInfo->nList]; - for (i = 0; i < 12; i++) smxj->a[i] = lastsmx->a[i]; + for (i = 0; i < 12; i++) + smxj->a[i] = lastsmx->a[i]; - if (SgInfo->ListRotMxInfo != NULL) - { - lrmxi = &SgInfo->ListRotMxInfo[jList]; + if (SgInfo->ListRotMxInfo != NULL) { + lrmxi = &SgInfo->ListRotMxInfo[jList]; lastrmxi = &SgInfo->ListRotMxInfo[SgInfo->nList]; CopyRotMxInfo(lrmxi, lastrmxi); } - } - else + } else jList++; } @@ -992,11 +1117,11 @@ static int RemoveLatticeTr(T_SgInfo *SgInfo) } -static int RemoveInversion(T_SgInfo *SgInfo) +static int RemoveInversion(T_SgInfo * SgInfo) { - int i, iList, special, deter, Centric, InversionOffOrigin; - T_RTMx *lsmx, *smx, ProperSMx; - T_RotMxInfo *lrmxi, *rmxi; + int i, iList, special, deter, Centric, InversionOffOrigin; + T_RTMx *lsmx, *smx, ProperSMx; + T_RotMxInfo *lrmxi, *rmxi; Centric = 0; @@ -1004,12 +1129,10 @@ static int RemoveInversion(T_SgInfo *SgInfo) lsmx = SgInfo->ListSeitzMx; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { special = IsSpecialSeitzMx(SgInfo, lsmx, 0); - if (special & SpecialSMx_Inversion) - { + if (special & SpecialSMx_Inversion) { if (special & SpecialSMx_Transl0) Centric = 1; else @@ -1024,49 +1147,44 @@ static int RemoveInversion(T_SgInfo *SgInfo) return -1; } - if (Centric == 0) - { + if (Centric == 0) { if (InversionOffOrigin) { SgInfo->Centric = 0; SgInfo->InversionOffOrigin = 1; - } - else - { - if (SgInfo->Centric) SgInfo->Centric = -1; + } else { + if (SgInfo->Centric) + SgInfo->Centric = -1; SgInfo->InversionOffOrigin = 0; } - } - else - { + } else { SgInfo->InversionOffOrigin = 0; - lsmx = SgInfo->ListSeitzMx; + lsmx = SgInfo->ListSeitzMx; lrmxi = SgInfo->ListRotMxInfo; iList = 0; - while (iList < SgInfo->nList) - { + while (iList < SgInfo->nList) { deter = deterRotMx(lsmx->s.R); - if (deter == -1 && SgInfo->Centric == -1) - { + if (deter == -1 && SgInfo->Centric == -1) { for (i = 0; i < 9; i++) - ProperSMx.s.R[i] = -lsmx->s.R[i]; + ProperSMx.s.R[i] = -lsmx->s.R[i]; for (i = 0; i < 3; i++) { - ProperSMx.s.T[i] = -lsmx->s.T[i] % STBF; + ProperSMx.s.T[i] = -lsmx->s.T[i] % STBF; if (ProperSMx.s.T[i] < 0) - ProperSMx.s.T[i] += STBF; + ProperSMx.s.T[i] += STBF; } smx = SgInfo->ListSeitzMx; for (i = 0; i < SgInfo->nList; i++, smx++) - if (CompareSeitzMx(LI_P, &ProperSMx, smx) == 0) break; + if (CompareSeitzMx(LI_P, &ProperSMx, smx) == 0) + break; - if (i == SgInfo->nList) - { - for (i = 0; i < 12; i++) lsmx->a[i] = ProperSMx.a[i]; + if (i == SgInfo->nList) { + for (i = 0; i < 12; i++) + lsmx->a[i] = ProperSMx.a[i]; deter = deterRotMx(lsmx->s.R); @@ -1077,30 +1195,26 @@ static int RemoveInversion(T_SgInfo *SgInfo) } } - if (deter == -1) - { + if (deter == -1) { /* copy last element to this place */ - SgInfo->nList--; - if (SgInfo->nList != iList) - { + SgInfo->nList--; + if (SgInfo->nList != iList) { smx = &SgInfo->ListSeitzMx[SgInfo->nList]; - for (i = 0; i < 12; i++) lsmx->a[i] = smx->a[i]; + for (i = 0; i < 12; i++) + lsmx->a[i] = smx->a[i]; - if (lrmxi) - { + if (lrmxi) { rmxi = &SgInfo->ListRotMxInfo[SgInfo->nList]; CopyRotMxInfo(lrmxi, rmxi); } } - } - else if (deter == 1) - { + } else if (deter == 1) { lsmx++; - if (lrmxi != NULL) lrmxi++; + if (lrmxi != NULL) + lrmxi++; iList++; - } - else { + } else { SetSgError(Err_Ill_SMx_in_List); return -1; } @@ -1113,18 +1227,19 @@ static int RemoveInversion(T_SgInfo *SgInfo) } -int ApplyOriginShift(T_SgInfo *SgInfo) +int ApplyOriginShift(T_SgInfo * SgInfo) { - int HaveOrSh, iList, i; - T_RTMx *lsmx, SMx; - int OrSh[3], lo[3]; + int HaveOrSh, iList, i; + T_RTMx *lsmx, SMx; + int OrSh[3], lo[3]; HaveOrSh = 0; for (i = 0; i < 3; i++) { - OrSh[i] = SgInfo->OriginShift[i] * (STBF / 12); - if (OrSh[i]) HaveOrSh = 1; + OrSh[i] = SgInfo->OriginShift[i] * (STBF / 12); + if (OrSh[i]) + HaveOrSh = 1; } if (HaveOrSh == 0) @@ -1132,16 +1247,14 @@ int ApplyOriginShift(T_SgInfo *SgInfo) lsmx = SgInfo->ListSeitzMx; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { RotMx_t_Vector(lo, lsmx->s.R, OrSh, STBF); for (i = 0; i < 3; i++) lsmx->s.T[i] = iModPositive(lsmx->s.T[i] - lo[i] + OrSh[i], STBF); } - if (SgInfo->Centric == -1) - { + if (SgInfo->Centric == -1) { lsmx = &SMx; InitSeitzMx(lsmx, -1); @@ -1162,30 +1275,28 @@ int ApplyOriginShift(T_SgInfo *SgInfo) } -static void TidyTranslation(T_SgInfo *SgInfo) +static void TidyTranslation(T_SgInfo * SgInfo) { - int iList; - int iTrV, nTrV; - const int *TrV; - T_RTMx *lsmx; - int t1, t2, t3, *lt1, *lt2, *lt3, mint1, mint2, mint3; - int n0t, n0mint; + int iList; + int iTrV, nTrV; + const int *TrV; + T_RTMx *lsmx; + int t1, t2, t3, *lt1, *lt2, *lt3, mint1, mint2, mint3; + int n0t, n0mint; nTrV = SgInfo->LatticeInfo->nTrVector; - lsmx = SgInfo->ListSeitzMx; + lsmx = SgInfo->ListSeitzMx; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { mint1 = *(lt1 = &lsmx->s.T[0]); mint2 = *(lt2 = &lsmx->s.T[1]); mint3 = *(lt3 = &lsmx->s.T[2]); TrV = SgInfo->LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++) - { + for (iTrV = 0; iTrV < nTrV; iTrV++) { t1 = ((*lt1) + *TrV++) % STBF; t2 = ((*lt2) + *TrV++) % STBF; t3 = ((*lt3) + *TrV++) % STBF; @@ -1193,12 +1304,14 @@ static void TidyTranslation(T_SgInfo *SgInfo) n0t = (t1 == 0) + (t2 == 0) + (t3 == 0); n0mint = (mint1 == 0) + (mint2 == 0) + (mint3 == 0); - if ( n0t > n0mint - || ( n0t == n0mint - && ( t1 + t2 + t3 < mint1 + mint2 + mint3 - || ( t1 + t2 + t3 == mint1 + mint2 + mint3 + if (n0t > n0mint + || (n0t == n0mint + && (t1 + t2 + t3 < mint1 + mint2 + mint3 + || (t1 + t2 + t3 == mint1 + mint2 + mint3 && (t1 < mint1 || (t1 == mint1 && t2 < mint2)))))) { - mint1 = t1; mint2 = t2; mint3 = t3; + mint1 = t1; + mint2 = t2; + mint3 = t3; } } @@ -1213,31 +1326,28 @@ static T_SgInfo *Pt_SgInfo_ListSortFunction = NULL; static int SgInfoListSortFunction(const int *iList_a, const int *iList_b) { - int val_a, val_b, n0_a, n0_b, i; - T_RTMx *smx_a, *smx_b; - T_RotMxInfo RotMxInfo_a, RotMxInfo_b, *rmxi_a, *rmxi_b; - T_SgInfo *SgInfo = Pt_SgInfo_ListSortFunction; + int val_a, val_b, n0_a, n0_b, i; + T_RTMx *smx_a, *smx_b; + T_RotMxInfo RotMxInfo_a, RotMxInfo_b, *rmxi_a, *rmxi_b; + T_SgInfo *SgInfo = Pt_SgInfo_ListSortFunction; - if (SgError != NULL) return 0; + if (SgError != NULL) + return 0; - if (SgInfo->ListRotMxInfo == NULL) - { + if (SgInfo->ListRotMxInfo == NULL) { rmxi_a = &RotMxInfo_a; rmxi_b = &RotMxInfo_b; smx_a = &SgInfo->ListSeitzMx[*iList_a]; smx_b = &SgInfo->ListSeitzMx[*iList_b]; - if ( GetRotMxInfo(smx_a->s.R, rmxi_a) == 0 - || GetRotMxInfo(smx_b->s.R, rmxi_b) == 0) - { + if (GetRotMxInfo(smx_a->s.R, rmxi_a) == 0 + || GetRotMxInfo(smx_b->s.R, rmxi_b) == 0) { SetSgError(Err_Ill_SMx_in_List); return 0; } - } - else - { + } else { rmxi_a = &SgInfo->ListRotMxInfo[*iList_a]; rmxi_b = &SgInfo->ListRotMxInfo[*iList_b]; } @@ -1245,126 +1355,139 @@ static int SgInfoListSortFunction(const int *iList_a, const int *iList_b) val_a = abs(rmxi_a->Order); val_b = abs(rmxi_b->Order); - if (val_a == 1 && val_b != 1) return -1; - if (val_a != 1 && val_b == 1) return 1; - if (rmxi_a->Order == 1 && rmxi_b->Order != 1) return -1; - if (rmxi_a->Order != 1 && rmxi_b->Order == 1) return 1; + if (val_a == 1 && val_b != 1) + return -1; + if (val_a != 1 && val_b == 1) + return 1; + if (rmxi_a->Order == 1 && rmxi_b->Order != 1) + return -1; + if (rmxi_a->Order != 1 && rmxi_b->Order == 1) + return 1; - if (val_a != 1) - { - if (val_a > val_b) return -1; - if (val_a < val_b) return 1; - if (rmxi_a->Order > rmxi_b->Order) return -1; - if (rmxi_a->Order < rmxi_b->Order) return 1; + if (val_a != 1) { + if (val_a > val_b) + return -1; + if (val_a < val_b) + return 1; + if (rmxi_a->Order > rmxi_b->Order) + return -1; + if (rmxi_a->Order < rmxi_b->Order) + return 1; } n0_a = n0_b = 0; - for (i = 0; i < 3; i++) - { - if (rmxi_a->EigenVector[i] == 0) n0_a++; - if (rmxi_b->EigenVector[i] == 0) n0_b++; + for (i = 0; i < 3; i++) { + if (rmxi_a->EigenVector[i] == 0) + n0_a++; + if (rmxi_b->EigenVector[i] == 0) + n0_b++; } - if (n0_a > n0_b) return -1; - if (n0_a < n0_b) return 1; + if (n0_a > n0_b) + return -1; + if (n0_a < n0_b) + return 1; val_a = val_b = 0; - for (i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { if (val_a < abs(rmxi_a->EigenVector[i])) - val_a = abs(rmxi_a->EigenVector[i]); + val_a = abs(rmxi_a->EigenVector[i]); if (val_b < abs(rmxi_b->EigenVector[i])) - val_b = abs(rmxi_b->EigenVector[i]); + val_b = abs(rmxi_b->EigenVector[i]); } - if (val_a < val_b) return -1; - if (val_a > val_b) return 1; + if (val_a < val_b) + return -1; + if (val_a > val_b) + return 1; - val_a = 100 * abs(rmxi_a->EigenVector[2]); - val_a += 10 * abs(rmxi_a->EigenVector[0]); - val_a += abs(rmxi_a->EigenVector[1]); - val_b = 100 * abs(rmxi_b->EigenVector[2]); - val_b += 10 * abs(rmxi_b->EigenVector[0]); - val_b += abs(rmxi_b->EigenVector[1]); + val_a = 100 * abs(rmxi_a->EigenVector[2]); + val_a += 10 * abs(rmxi_a->EigenVector[0]); + val_a += abs(rmxi_a->EigenVector[1]); + val_b = 100 * abs(rmxi_b->EigenVector[2]); + val_b += 10 * abs(rmxi_b->EigenVector[0]); + val_b += abs(rmxi_b->EigenVector[1]); - if (n0_a < 2) - { - if (val_a < val_b) return -1; - if (val_a > val_b) return 1; - } - else - { - if (val_a > val_b) return -1; - if (val_a < val_b) return 1; + if (n0_a < 2) { + if (val_a < val_b) + return -1; + if (val_a > val_b) + return 1; + } else { + if (val_a > val_b) + return -1; + if (val_a < val_b) + return 1; } - for (i = 0; i < 3; i++) - { - if (rmxi_a->EigenVector[i] > rmxi_b->EigenVector[i]) return -1; - if (rmxi_a->EigenVector[i] < rmxi_b->EigenVector[i]) return 1; + for (i = 0; i < 3; i++) { + if (rmxi_a->EigenVector[i] > rmxi_b->EigenVector[i]) + return -1; + if (rmxi_a->EigenVector[i] < rmxi_b->EigenVector[i]) + return 1; } - if (rmxi_a->Inverse < rmxi_b->Inverse) return -1; - if (rmxi_a->Inverse > rmxi_b->Inverse) return 1; + if (rmxi_a->Inverse < rmxi_b->Inverse) + return -1; + if (rmxi_a->Inverse > rmxi_b->Inverse) + return 1; smx_a = &SgInfo->ListSeitzMx[*iList_a]; smx_b = &SgInfo->ListSeitzMx[*iList_b]; - for (i = 0; i < 3; i++) - { - if (smx_a->s.T[i] < smx_b->s.T[i]) return -1; - if (smx_a->s.T[i] > smx_b->s.T[i]) return 1; + for (i = 0; i < 3; i++) { + if (smx_a->s.T[i] < smx_b->s.T[i]) + return -1; + if (smx_a->s.T[i] > smx_b->s.T[i]) + return 1; } return 0; } -static int PostSortSgInfoList(const T_SgInfo *SgInfo, int *List_iList) +static int PostSortSgInfoList(const T_SgInfo * SgInfo, int *List_iList) { - int nList, iL_iL, jL_iL; - T_RTMx BufMx1, BufMx2, *smxab; - const T_RTMx *lsmx, *smxb; - T_RotMxInfo RotMxInfo; - const T_RotMxInfo *rmxi; - int nO_1, iO, save, i, i_; + int nList, iL_iL, jL_iL; + T_RTMx BufMx1, BufMx2, *smxab; + const T_RTMx *lsmx, *smxb; + T_RotMxInfo RotMxInfo; + const T_RotMxInfo *rmxi; + int nO_1, iO, save, i, i_; nList = SgInfo->nList; iL_iL = 0; - while (iL_iL < nList) - { + while (iL_iL < nList) { lsmx = &SgInfo->ListSeitzMx[List_iList[iL_iL]]; - rmxi = ListOrBufRotMxInfo(SgInfo, List_iList[iL_iL], &RotMxInfo); + rmxi = ListOrBufRotMxInfo(SgInfo, List_iList[iL_iL], &RotMxInfo); if (rmxi == NULL) return -1; iL_iL++; iO = rmxi->Order; - if (iO < 0 && iO % 2) iO *= 2; + if (iO < 0 && iO % 2) + iO *= 2; nO_1 = abs(iO) - 1; smxab = &BufMx2; smxb = lsmx; - for (iO = 1; iO < nO_1; iO++) - { + for (iO = 1; iO < nO_1; iO++) { SeitzMxMultiply(smxab, lsmx, smxb); - for (jL_iL = iL_iL; jL_iL < nList; jL_iL++) - { + for (jL_iL = iL_iL; jL_iL < nList; jL_iL++) { smxb = &SgInfo->ListSeitzMx[List_iList[jL_iL]]; if (CompareSeitzMx(SgInfo->LatticeInfo, smxab, smxb) == 0) break; } - if (jL_iL < nList) - { - save = List_iList[jL_iL]; + if (jL_iL < nList) { + save = List_iList[jL_iL]; for (i = i_ = jL_iL; i > iL_iL; i = i_) List_iList[i] = List_iList[--i_]; @@ -1373,8 +1496,10 @@ static int PostSortSgInfoList(const T_SgInfo *SgInfo, int *List_iList) } smxb = smxab; - if (iO % 2) smxab = &BufMx1; - else smxab = &BufMx2; + if (iO % 2) + smxab = &BufMx1; + else + smxab = &BufMx2; } } @@ -1382,40 +1507,42 @@ static int PostSortSgInfoList(const T_SgInfo *SgInfo, int *List_iList) } -static void SortSgInfoList(T_SgInfo *SgInfo, int *List_iList) +static void SortSgInfoList(T_SgInfo * SgInfo, int *List_iList) { - int i, j, refi; - int nList; - T_RTMx *lsmx; - T_RotMxInfo *lrmxi; + int i, j, refi; + int nList; + T_RTMx *lsmx; + T_RotMxInfo *lrmxi; - if (SgError != NULL) return; + if (SgError != NULL) + return; nList = SgInfo->nList; - lsmx = SgInfo->ListSeitzMx; + lsmx = SgInfo->ListSeitzMx; lrmxi = SgInfo->ListRotMxInfo; Pt_SgInfo_ListSortFunction = SgInfo; - for (i = 0; i < nList; i++) List_iList[i] = i; + for (i = 0; i < nList; i++) + List_iList[i] = i; - qsort((void *) List_iList, nList, sizeof (*List_iList), + qsort((void *) List_iList, nList, sizeof(*List_iList), (int (*)(const void *, const void *)) SgInfoListSortFunction); Pt_SgInfo_ListSortFunction = NULL; - if (SgError != NULL) return; + if (SgError != NULL) + return; if (PostSortSgInfoList(SgInfo, List_iList) != 0) return; - for (i = 0; i < nList; i++) - { + for (i = 0; i < nList; i++) { j = List_iList[i]; - if (j != i) - { + if (j != i) { for (refi = i + 1; refi < nList; refi++) - if (List_iList[refi] == i) break; + if (List_iList[refi] == i) + break; if (refi >= nList) { SetSgError("Internal Error: SortSgInfoList(): Corrupt List_iList"); @@ -1432,24 +1559,23 @@ static void SortSgInfoList(T_SgInfo *SgInfo, int *List_iList) } -int FindSeitzMx(const T_SgInfo *SgInfo, +int FindSeitzMx(const T_SgInfo * SgInfo, int Order, int HonorSign, int RefAxis, int DirCode) { - int iList; - int MatchingOrder; - T_RTMx *lsmx; - T_RotMxInfo *lrmxi, RotMxInfo; + int iList; + int MatchingOrder; + T_RTMx *lsmx; + T_RotMxInfo *lrmxi, RotMxInfo; - lsmx = SgInfo->ListSeitzMx; + lsmx = SgInfo->ListSeitzMx; lrmxi = SgInfo->ListRotMxInfo; - if (lrmxi == NULL) lrmxi = &RotMxInfo; + if (lrmxi == NULL) + lrmxi = &RotMxInfo; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { - if (lrmxi == &RotMxInfo) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { + if (lrmxi == &RotMxInfo) { if (GetRotMxInfo(lsmx->s.R, lrmxi) == 0) { SetSgError(Err_Ill_SMx_in_List); return -1; @@ -1461,198 +1587,225 @@ int FindSeitzMx(const T_SgInfo *SgInfo, else MatchingOrder = (Order == lrmxi->Order); - if ( MatchingOrder + if (MatchingOrder && lrmxi->Inverse == 0 && (RefAxis == 0 || RefAxis == lrmxi->RefAxis) - && (DirCode == 0 || DirCode == lrmxi->DirCode)) - { - if (DirCode != '*') return iList; + && (DirCode == 0 || DirCode == lrmxi->DirCode)) { + if (DirCode != '*') + return iList; - if ( lrmxi->EigenVector[0] == 1 - && lrmxi->EigenVector[1] == 1 - && lrmxi->EigenVector[2] == 1) return iList; + if (lrmxi->EigenVector[0] == 1 + && lrmxi->EigenVector[1] == 1 && lrmxi->EigenVector[2] == 1) + return iList; } - if (lrmxi != &RotMxInfo) lrmxi++; + if (lrmxi != &RotMxInfo) + lrmxi++; } return -1; } -static int FindXtalSystem(T_SgInfo *SgInfo) +static int FindXtalSystem(T_SgInfo * SgInfo) { - int iList, i; - int HonorSign = 0, CheckEnantiomorph; - const T_RTMx *lsmx; - T_RotMxInfo RotMxInfo; - const T_RotMxInfo *lrmxi; + int iList, i; + int HonorSign = 0, CheckEnantiomorph; + const T_RTMx *lsmx; + T_RotMxInfo RotMxInfo; + const T_RotMxInfo *lrmxi; enum Axis { N1 = 0, N2, N3, N4, N6, EndOfAxis }; - int N_count[EndOfAxis]; + int N_count[EndOfAxis]; - SgInfo->XtalSystem = XS_Unknown; + SgInfo->XtalSystem = XS_Unknown; SgInfo->UniqueRefAxis = 0; SgInfo->UniqueDirCode = 0; - SgInfo->ExtraInfo = EI_Unknown; + SgInfo->ExtraInfo = EI_Unknown; CheckEnantiomorph = 0; - for (i = 0; i < EndOfAxis; i++) N_count[i] = 0; + for (i = 0; i < EndOfAxis; i++) + N_count[i] = 0; - lsmx = SgInfo->ListSeitzMx; + lsmx = SgInfo->ListSeitzMx; lrmxi = SgInfo->ListRotMxInfo; - if (lrmxi == NULL) lrmxi = &RotMxInfo; + if (lrmxi == NULL) + lrmxi = &RotMxInfo; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { - if (lrmxi == &RotMxInfo) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { + if (lrmxi == &RotMxInfo) { if (GetRotMxInfo(lsmx->s.R, &RotMxInfo) == 0) { SetSgError(Err_Ill_SMx_in_List); return XS_Unknown; } } - switch(abs(lrmxi->Order)) - { - case 1: i = N1; break; - case 2: i = N2; break; - case 3: i = N3; break; - case 4: i = N4; break; - case 6: i = N6; break; - default: - SetSgError("Internal Error: FindXtalSystem(): Corrupt ListRotMxInfo"); - return XS_Unknown; + switch (abs(lrmxi->Order)) { + case 1: + i = N1; + break; + case 2: + i = N2; + break; + case 3: + i = N3; + break; + case 4: + i = N4; + break; + case 6: + i = N6; + break; + default: + SetSgError + ("Internal Error: FindXtalSystem(): Corrupt ListRotMxInfo"); + return XS_Unknown; } - if (lrmxi->Inverse == 0) /* skip N^-1 */ + if (lrmxi->Inverse == 0) /* skip N^-1 */ N_count[i]++; - if (lrmxi != &RotMxInfo) lrmxi++; + if (lrmxi != &RotMxInfo) + lrmxi++; } i = EndOfAxis; - if (SgInfo->InversionOffOrigin == 1) - { - for (i = 0; i < EndOfAxis; i++) - { - if (N_count[i] % 2) break; + if (SgInfo->InversionOffOrigin == 1) { + for (i = 0; i < EndOfAxis; i++) { + if (N_count[i] % 2) + break; N_count[i] /= 2; } } - if (i == EndOfAxis) - { - if (N_count[N3] == 4) SgInfo->XtalSystem = XS_Cubic; - else if (N_count[N3] > 1) SgInfo->XtalSystem = XS_Unknown; - else if (N_count[N6] == 1) SgInfo->XtalSystem = XS_Hexagonal; - else if (N_count[N6] > 0) SgInfo->XtalSystem = XS_Unknown; - else if (N_count[N3] == 1) SgInfo->XtalSystem = XS_Trigonal; - else if (N_count[N4] == 1) SgInfo->XtalSystem = XS_Tetragonal; - else if (N_count[N4] > 0) SgInfo->XtalSystem = XS_Unknown; - else if (N_count[N2] > 2) SgInfo->XtalSystem = XS_Orthorhombic; - else if (N_count[N2] > 0) SgInfo->XtalSystem = XS_Monoclinic; - else if (N_count[N1] > 0) SgInfo->XtalSystem = XS_Triclinic; + if (i == EndOfAxis) { + if (N_count[N3] == 4) + SgInfo->XtalSystem = XS_Cubic; + else if (N_count[N3] > 1) + SgInfo->XtalSystem = XS_Unknown; + else if (N_count[N6] == 1) + SgInfo->XtalSystem = XS_Hexagonal; + else if (N_count[N6] > 0) + SgInfo->XtalSystem = XS_Unknown; + else if (N_count[N3] == 1) + SgInfo->XtalSystem = XS_Trigonal; + else if (N_count[N4] == 1) + SgInfo->XtalSystem = XS_Tetragonal; + else if (N_count[N4] > 0) + SgInfo->XtalSystem = XS_Unknown; + else if (N_count[N2] > 2) + SgInfo->XtalSystem = XS_Orthorhombic; + else if (N_count[N2] > 0) + SgInfo->XtalSystem = XS_Monoclinic; + else if (N_count[N1] > 0) + SgInfo->XtalSystem = XS_Triclinic; HonorSign = 1; iList = FindSeitzMx(SgInfo, -1, HonorSign, 'o', '.'); - if (iList < 0) HonorSign = 0; + if (iList < 0) + HonorSign = 0; - switch(SgInfo->XtalSystem) - { - case XS_Monoclinic: - iList = FindSeitzMx(SgInfo, 2, HonorSign, 0, '='); - if (iList < 0) SgInfo->XtalSystem = XS_Unknown; - break; - case XS_Tetragonal: + switch (SgInfo->XtalSystem) { + case XS_Monoclinic: + iList = FindSeitzMx(SgInfo, 2, HonorSign, 0, '='); + if (iList < 0) + SgInfo->XtalSystem = XS_Unknown; + break; + case XS_Tetragonal: + CheckEnantiomorph = 1; + iList = FindSeitzMx(SgInfo, 4, HonorSign, 0, '='); + if (iList < 0) + SgInfo->XtalSystem = XS_Unknown; + break; + case XS_Trigonal: + CheckEnantiomorph = 1; + iList = FindSeitzMx(SgInfo, 3, HonorSign, 0, '='); + if (iList < 0) + iList = FindSeitzMx(SgInfo, 3, HonorSign, 0, '*'); + if (iList < 0) + SgInfo->XtalSystem = XS_Unknown; + break; + case XS_Hexagonal: + CheckEnantiomorph = 1; + iList = FindSeitzMx(SgInfo, 6, HonorSign, 0, '='); + if (iList < 0) + SgInfo->XtalSystem = XS_Unknown; + break; + case XS_Cubic: + iList = FindSeitzMx(SgInfo, 4, HonorSign, 0, '='); + if (iList >= 0) CheckEnantiomorph = 1; - iList = FindSeitzMx(SgInfo, 4, HonorSign, 0, '='); - if (iList < 0) SgInfo->XtalSystem = XS_Unknown; - break; - case XS_Trigonal: - CheckEnantiomorph = 1; - iList = FindSeitzMx(SgInfo, 3, HonorSign, 0, '='); - if (iList < 0) - iList = FindSeitzMx(SgInfo, 3, HonorSign, 0, '*'); - if (iList < 0) SgInfo->XtalSystem = XS_Unknown; - break; - case XS_Hexagonal: - CheckEnantiomorph = 1; - iList = FindSeitzMx(SgInfo, 6, HonorSign, 0, '='); - if (iList < 0) SgInfo->XtalSystem = XS_Unknown; - break; - case XS_Cubic: - iList = FindSeitzMx(SgInfo, 4, HonorSign, 0, '='); - if (iList >= 0) CheckEnantiomorph = 1; - break; - default: - iList = -1; - break; + break; + default: + iList = -1; + break; } } if (SgInfo->XtalSystem == XS_Unknown) { SetSgError("Error: Can't determine crystal system"); - } - else if (iList >= 0) - { - lrmxi = ListOrBufRotMxInfo(SgInfo, iList, &RotMxInfo); + } else if (iList >= 0) { + lrmxi = ListOrBufRotMxInfo(SgInfo, iList, &RotMxInfo); if (lrmxi == NULL) { SgInfo->XtalSystem = XS_Unknown; return XS_Unknown; } - if (SgInfo->XtalSystem != XS_Cubic) - { + if (SgInfo->XtalSystem != XS_Cubic) { SgInfo->UniqueRefAxis = lrmxi->RefAxis; SgInfo->UniqueDirCode = lrmxi->DirCode; - if (SgInfo->XtalSystem == XS_Trigonal && lrmxi->DirCode == '=') - { - switch (lrmxi->RefAxis) - { - case 'z': - switch (SgInfo->LatticeInfo->Code) - { - case 'R': SgInfo->ExtraInfo = EI_Obverse; break; - case 'T': SgInfo->ExtraInfo = EI_Reverse; break; - } + if (SgInfo->XtalSystem == XS_Trigonal && lrmxi->DirCode == '=') { + switch (lrmxi->RefAxis) { + case 'z': + switch (SgInfo->LatticeInfo->Code) { + case 'R': + SgInfo->ExtraInfo = EI_Obverse; break; - case 'y': - switch (SgInfo->LatticeInfo->Code) - { - case 'S': SgInfo->ExtraInfo = EI_Obverse; break; - case 'R': SgInfo->ExtraInfo = EI_Reverse; break; - } + case 'T': + SgInfo->ExtraInfo = EI_Reverse; break; - case 'x': - switch (SgInfo->LatticeInfo->Code) - { - case 'T': SgInfo->ExtraInfo = EI_Obverse; break; - case 'S': SgInfo->ExtraInfo = EI_Reverse; break; - } + } + break; + case 'y': + switch (SgInfo->LatticeInfo->Code) { + case 'S': + SgInfo->ExtraInfo = EI_Obverse; break; + case 'R': + SgInfo->ExtraInfo = EI_Reverse; + break; + } + break; + case 'x': + switch (SgInfo->LatticeInfo->Code) { + case 'T': + SgInfo->ExtraInfo = EI_Obverse; + break; + case 'S': + SgInfo->ExtraInfo = EI_Reverse; + break; + } + break; } } } - if ( HonorSign == 0 /* no inversion matrix */ - && SgInfo->LatticeInfo->Code == 'P' - && CheckEnantiomorph == 1) - { + if (HonorSign == 0 /* no inversion matrix */ + && SgInfo->LatticeInfo->Code == 'P' && CheckEnantiomorph == 1) { lsmx = &SgInfo->ListSeitzMx[iList]; - if (GetRotMxOrder(lsmx->s.R) > 1) - { - i = lsmx->s.T[0] * lrmxi->EigenVector[0]; + if (GetRotMxOrder(lsmx->s.R) > 1) { + i = lsmx->s.T[0] * lrmxi->EigenVector[0]; i += lsmx->s.T[1] * lrmxi->EigenVector[1]; i += lsmx->s.T[2] * lrmxi->EigenVector[2]; - if (i % (STBF / 2)) SgInfo->ExtraInfo = EI_Enantiomorphic; + if (i % (STBF / 2)) + SgInfo->ExtraInfo = EI_Enantiomorphic; } } } @@ -1661,288 +1814,286 @@ static int FindXtalSystem(T_SgInfo *SgInfo) } -static int BuildGenerator_iList(T_SgInfo *SgInfo) +static int BuildGenerator_iList(T_SgInfo * SgInfo) { - int iList, iList_1, nG; - int SgInfo_CI, HonorSign, Flag3asterisk, FlagPG; + int iList, iList_1, nG; + int SgInfo_CI, HonorSign, Flag3asterisk, FlagPG; SgInfo_CI = (SgInfo->Centric || SgInfo->InversionOffOrigin); SgInfo->PointGroup = PG_Unknown; - nG = SgInfo->nGenerator = 0; + nG = SgInfo->nGenerator = 0; #define G_iL SgInfo->Generator_iList HonorSign = 1; iList_1 = FindSeitzMx(SgInfo, -1, HonorSign, 'o', '.'); - if (iList_1 < 0) HonorSign = 0; + if (iList_1 < 0) + HonorSign = 0; if (SgInfo->XtalSystem == XS_Unknown) FindXtalSystem(SgInfo); - switch(SgInfo->XtalSystem) - { - case XS_Triclinic: - if (iList_1 < 0) - iList_1 = FindSeitzMx(SgInfo, 1, HonorSign, 'o', '.'); - if (iList_1 >= 0) G_iL[nG++] = iList_1; + switch (SgInfo->XtalSystem) { + case XS_Triclinic: + if (iList_1 < 0) + iList_1 = FindSeitzMx(SgInfo, 1, HonorSign, 'o', '.'); + if (iList_1 >= 0) + G_iL[nG++] = iList_1; - if (SgInfo_CI) - SgInfo->PointGroup = PG_1b; - else - SgInfo->PointGroup = PG_1; + if (SgInfo_CI) + SgInfo->PointGroup = PG_1b; + else + SgInfo->PointGroup = PG_1; - SgInfo->nGenerator = nG; - return 0; + SgInfo->nGenerator = nG; + return 0; - case XS_Monoclinic: - iList = FindSeitzMx(SgInfo, 2, HonorSign, 0, '='); - if (iList < 0) break; - G_iL[nG++] = iList; - - if (SgInfo_CI) - SgInfo->PointGroup = PG_2_m; - else if (deterRotMx(SgInfo->ListSeitzMx[iList].s.R) == -1) - SgInfo->PointGroup = PG_m; - else - SgInfo->PointGroup = PG_2; - - if (iList_1 >= 0) G_iL[nG++] = iList_1; - - SgInfo->nGenerator = nG; - return 0; - - case XS_Orthorhombic: - iList = FindSeitzMx(SgInfo, 2, HonorSign, 'z', '='); - if (iList >= 0) G_iL[nG++] = iList; - - iList = FindSeitzMx(SgInfo, 2, HonorSign, 'x', '='); - if (iList >= 0) G_iL[nG++] = iList; - - if (nG < 2) - { - iList = FindSeitzMx(SgInfo, 2, HonorSign, 'y', '='); - if (iList >= 0) G_iL[nG++] = iList; - } - - if (nG != 2) break; - - if (SgInfo_CI) - SgInfo->PointGroup = PG_mmm; - else if ( deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1 - || deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == -1) - SgInfo->PointGroup = PG_mm2; - else - SgInfo->PointGroup = PG_222; - - if (iList_1 >= 0) G_iL[nG++] = iList_1; - - SgInfo->nGenerator = nG; - return 0; - - case XS_Tetragonal: - iList = FindSeitzMx(SgInfo, 4, HonorSign, 0, '='); - if (iList < 0) break; - G_iL[nG++] = iList; - - if ( SgInfo->UniqueRefAxis != 'x') - { - iList = FindSeitzMx(SgInfo, 2, HonorSign, 'x', '='); - if (iList >= 0) G_iL[nG++] = iList; - } - if (nG < 2 && SgInfo->UniqueRefAxis != 'z') - { - iList = FindSeitzMx(SgInfo, 2, HonorSign, 'z', '='); - if (iList >= 0) G_iL[nG++] = iList; - } - if (nG < 2 && SgInfo->UniqueRefAxis != 'y') - { - iList = FindSeitzMx(SgInfo, 2, HonorSign, 'y', '='); - if (iList >= 0) G_iL[nG++] = iList; - } - - if (nG < 2) - { - if (SgInfo_CI) - SgInfo->PointGroup = PG_4_m; - else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) - SgInfo->PointGroup = PG_4b; - else - SgInfo->PointGroup = PG_4; - } - else - { - if (SgInfo_CI) - SgInfo->PointGroup = PG_4_mmm; - else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) - { - if (deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == -1) - SgInfo->PointGroup = PG_4bm2; - else - SgInfo->PointGroup = PG_4b2m; - } - else - { - if (deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == -1) - SgInfo->PointGroup = PG_4mm; - else - SgInfo->PointGroup = PG_422; - } - } - - if (iList_1 >= 0) G_iL[nG++] = iList_1; - - SgInfo->nGenerator = nG; - return 0; - - case XS_Trigonal: - case XS_Hexagonal: - Flag3asterisk = 0; - - if (SgInfo->XtalSystem == XS_Trigonal) - { - iList = FindSeitzMx(SgInfo, 3, HonorSign, 0, '='); - if (iList < 0) - { - iList = FindSeitzMx(SgInfo, 3, HonorSign, 0, '*'); - Flag3asterisk = 1; - } - } - else - iList = FindSeitzMx(SgInfo, 6, HonorSign, 0, '='); - - if (iList < 0) break; - G_iL[nG++] = iList; - - iList = FindSeitzMx(SgInfo, 2, HonorSign, 0, '\''); - if (iList >= 0) G_iL[nG++] = iList; - - FlagPG = -1; - - if (nG < 2) - { - iList = FindSeitzMx(SgInfo, 2, HonorSign, 0, '"'); - if (iList >= 0) G_iL[nG++] = iList; - FlagPG = 1; - } - - if (SgInfo->XtalSystem == XS_Trigonal) - { - if (nG < 2) - { - if (SgInfo_CI) SgInfo->PointGroup = PG_3b; - else SgInfo->PointGroup = PG_3; - } - else - { - if (Flag3asterisk == 1) - { - if (SgInfo_CI) - SgInfo->PointGroup = PG_3bm; - else - { FlagPG = deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R); - if (FlagPG == -1) SgInfo->PointGroup = PG_3m; - else SgInfo->PointGroup = PG_32; - } - } - else if (FlagPG == -1) - { - if (SgInfo_CI) - SgInfo->PointGroup = PG_3b1m; - else - { FlagPG = deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R); - if (FlagPG == -1) SgInfo->PointGroup = PG_31m; - else SgInfo->PointGroup = PG_312; - } - } - else - { - if (SgInfo_CI) - SgInfo->PointGroup = PG_3bm1; - else - { FlagPG = deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R); - if (FlagPG == -1) SgInfo->PointGroup = PG_3m1; - else SgInfo->PointGroup = PG_321; - } - } - } - } - else - { - if (nG < 2) - { - if (SgInfo_CI) - SgInfo->PointGroup = PG_6_m; - else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) - SgInfo->PointGroup = PG_6b; - else - SgInfo->PointGroup = PG_6; - } - else - { - if (SgInfo_CI) - SgInfo->PointGroup = PG_6_mmm; - else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) - { - if (deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == FlagPG) - SgInfo->PointGroup = PG_6b2m; - else - SgInfo->PointGroup = PG_6bm2; - } - else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == -1) - SgInfo->PointGroup = PG_6mm; - else - SgInfo->PointGroup = PG_622; - } - } - - if (iList_1 >= 0) G_iL[nG++] = iList_1; - - SgInfo->nGenerator = nG; - return 0; - - case XS_Cubic: - FlagPG = 0; - - iList = FindSeitzMx(SgInfo, 4, HonorSign, 'z', '='); - if (iList < 0) { - iList = FindSeitzMx(SgInfo, 2, HonorSign, 'z', '='); - FlagPG = 1; - } - if (iList < 0) break; - G_iL[nG++] = iList; - - iList = FindSeitzMx(SgInfo, 2, HonorSign, 'x', '='); - if (iList < 0) break; - G_iL[nG++] = iList; - - iList = FindSeitzMx(SgInfo, 3, HonorSign, 'o', '*'); - if (iList < 0) break; - G_iL[nG++] = iList; - - if (FlagPG) - { - if (SgInfo_CI) SgInfo->PointGroup = PG_m3b; - else SgInfo->PointGroup = PG_23; - } - else - { - if (SgInfo_CI) - SgInfo->PointGroup = PG_m3bm; - else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) - SgInfo->PointGroup = PG_4b3m; - else - SgInfo->PointGroup = PG_432; - } - - if (iList_1 >= 0) G_iL[nG++] = iList_1; - - SgInfo->nGenerator = nG; - return 0; - - default: + case XS_Monoclinic: + iList = FindSeitzMx(SgInfo, 2, HonorSign, 0, '='); + if (iList < 0) break; + G_iL[nG++] = iList; + + if (SgInfo_CI) + SgInfo->PointGroup = PG_2_m; + else if (deterRotMx(SgInfo->ListSeitzMx[iList].s.R) == -1) + SgInfo->PointGroup = PG_m; + else + SgInfo->PointGroup = PG_2; + + if (iList_1 >= 0) + G_iL[nG++] = iList_1; + + SgInfo->nGenerator = nG; + return 0; + + case XS_Orthorhombic: + iList = FindSeitzMx(SgInfo, 2, HonorSign, 'z', '='); + if (iList >= 0) + G_iL[nG++] = iList; + + iList = FindSeitzMx(SgInfo, 2, HonorSign, 'x', '='); + if (iList >= 0) + G_iL[nG++] = iList; + + if (nG < 2) { + iList = FindSeitzMx(SgInfo, 2, HonorSign, 'y', '='); + if (iList >= 0) + G_iL[nG++] = iList; + } + + if (nG != 2) + break; + + if (SgInfo_CI) + SgInfo->PointGroup = PG_mmm; + else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1 + || deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == -1) + SgInfo->PointGroup = PG_mm2; + else + SgInfo->PointGroup = PG_222; + + if (iList_1 >= 0) + G_iL[nG++] = iList_1; + + SgInfo->nGenerator = nG; + return 0; + + case XS_Tetragonal: + iList = FindSeitzMx(SgInfo, 4, HonorSign, 0, '='); + if (iList < 0) + break; + G_iL[nG++] = iList; + + if (SgInfo->UniqueRefAxis != 'x') { + iList = FindSeitzMx(SgInfo, 2, HonorSign, 'x', '='); + if (iList >= 0) + G_iL[nG++] = iList; + } + if (nG < 2 && SgInfo->UniqueRefAxis != 'z') { + iList = FindSeitzMx(SgInfo, 2, HonorSign, 'z', '='); + if (iList >= 0) + G_iL[nG++] = iList; + } + if (nG < 2 && SgInfo->UniqueRefAxis != 'y') { + iList = FindSeitzMx(SgInfo, 2, HonorSign, 'y', '='); + if (iList >= 0) + G_iL[nG++] = iList; + } + + if (nG < 2) { + if (SgInfo_CI) + SgInfo->PointGroup = PG_4_m; + else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) + SgInfo->PointGroup = PG_4b; + else + SgInfo->PointGroup = PG_4; + } else { + if (SgInfo_CI) + SgInfo->PointGroup = PG_4_mmm; + else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) { + if (deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == -1) + SgInfo->PointGroup = PG_4bm2; + else + SgInfo->PointGroup = PG_4b2m; + } else { + if (deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == -1) + SgInfo->PointGroup = PG_4mm; + else + SgInfo->PointGroup = PG_422; + } + } + + if (iList_1 >= 0) + G_iL[nG++] = iList_1; + + SgInfo->nGenerator = nG; + return 0; + + case XS_Trigonal: + case XS_Hexagonal: + Flag3asterisk = 0; + + if (SgInfo->XtalSystem == XS_Trigonal) { + iList = FindSeitzMx(SgInfo, 3, HonorSign, 0, '='); + if (iList < 0) { + iList = FindSeitzMx(SgInfo, 3, HonorSign, 0, '*'); + Flag3asterisk = 1; + } + } else + iList = FindSeitzMx(SgInfo, 6, HonorSign, 0, '='); + + if (iList < 0) + break; + G_iL[nG++] = iList; + + iList = FindSeitzMx(SgInfo, 2, HonorSign, 0, '\''); + if (iList >= 0) + G_iL[nG++] = iList; + + FlagPG = -1; + + if (nG < 2) { + iList = FindSeitzMx(SgInfo, 2, HonorSign, 0, '"'); + if (iList >= 0) + G_iL[nG++] = iList; + FlagPG = 1; + } + + if (SgInfo->XtalSystem == XS_Trigonal) { + if (nG < 2) { + if (SgInfo_CI) + SgInfo->PointGroup = PG_3b; + else + SgInfo->PointGroup = PG_3; + } else { + if (Flag3asterisk == 1) { + if (SgInfo_CI) + SgInfo->PointGroup = PG_3bm; + else { + FlagPG = deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R); + if (FlagPG == -1) + SgInfo->PointGroup = PG_3m; + else + SgInfo->PointGroup = PG_32; + } + } else if (FlagPG == -1) { + if (SgInfo_CI) + SgInfo->PointGroup = PG_3b1m; + else { + FlagPG = deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R); + if (FlagPG == -1) + SgInfo->PointGroup = PG_31m; + else + SgInfo->PointGroup = PG_312; + } + } else { + if (SgInfo_CI) + SgInfo->PointGroup = PG_3bm1; + else { + FlagPG = deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R); + if (FlagPG == -1) + SgInfo->PointGroup = PG_3m1; + else + SgInfo->PointGroup = PG_321; + } + } + } + } else { + if (nG < 2) { + if (SgInfo_CI) + SgInfo->PointGroup = PG_6_m; + else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) + SgInfo->PointGroup = PG_6b; + else + SgInfo->PointGroup = PG_6; + } else { + if (SgInfo_CI) + SgInfo->PointGroup = PG_6_mmm; + else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) { + if (deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == FlagPG) + SgInfo->PointGroup = PG_6b2m; + else + SgInfo->PointGroup = PG_6bm2; + } else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[1]].s.R) == -1) + SgInfo->PointGroup = PG_6mm; + else + SgInfo->PointGroup = PG_622; + } + } + + if (iList_1 >= 0) + G_iL[nG++] = iList_1; + + SgInfo->nGenerator = nG; + return 0; + + case XS_Cubic: + FlagPG = 0; + + iList = FindSeitzMx(SgInfo, 4, HonorSign, 'z', '='); + if (iList < 0) { + iList = FindSeitzMx(SgInfo, 2, HonorSign, 'z', '='); + FlagPG = 1; + } + if (iList < 0) + break; + G_iL[nG++] = iList; + + iList = FindSeitzMx(SgInfo, 2, HonorSign, 'x', '='); + if (iList < 0) + break; + G_iL[nG++] = iList; + + iList = FindSeitzMx(SgInfo, 3, HonorSign, 'o', '*'); + if (iList < 0) + break; + G_iL[nG++] = iList; + + if (FlagPG) { + if (SgInfo_CI) + SgInfo->PointGroup = PG_m3b; + else + SgInfo->PointGroup = PG_23; + } else { + if (SgInfo_CI) + SgInfo->PointGroup = PG_m3bm; + else if (deterRotMx(SgInfo->ListSeitzMx[G_iL[0]].s.R) == -1) + SgInfo->PointGroup = PG_4b3m; + else + SgInfo->PointGroup = PG_432; + } + + if (iList_1 >= 0) + G_iL[nG++] = iList_1; + + SgInfo->nGenerator = nG; + return 0; + + default: + break; } #undef G_iL @@ -1951,25 +2102,24 @@ static int BuildGenerator_iList(T_SgInfo *SgInfo) } -static int BuildHSym(T_SgInfo *SgInfo) +static int BuildHSym(T_SgInfo * SgInfo) { - int NeedDash, HaveOrSh, nGRT, iList, iG, ip, os, i; - int AbsOrder, RefAxis, DirCode, ScrewPrimitive, Screw; - int PreviousRotation, PreviousRefAxis, PreviousDirCode; - int nTrV, iTrV, OrSh[3], RO[3], Transl[3]; - const int *TrV, *ht; - T_RTMx SMx_1; - const T_RTMx *SMx; - const T_RotMxInfo *rmxi; - char *hsym, *hsym_mark; + int NeedDash, HaveOrSh, nGRT, iList, iG, ip, os, i; + int AbsOrder, RefAxis, DirCode, ScrewPrimitive, Screw; + int PreviousRotation, PreviousRefAxis, PreviousDirCode; + int nTrV, iTrV, OrSh[3], RO[3], Transl[3]; + const int *TrV, *ht; + T_RTMx SMx_1; + const T_RTMx *SMx; + const T_RotMxInfo *rmxi; + char *hsym, *hsym_mark; - struct - { - T_RotMxInfo RMxI_Buf; - const T_RotMxInfo *RMxI; - int Transl[3]; - } - GRT[sizeof SgInfo->Generator_iList / sizeof (*SgInfo->Generator_iList) + 1]; + struct { + T_RotMxInfo RMxI_Buf; + const T_RotMxInfo *RMxI; + int Transl[3]; + } GRT[sizeof SgInfo->Generator_iList / sizeof(*SgInfo->Generator_iList) + + 1]; const char *Digits = "0123456"; @@ -1982,18 +2132,19 @@ static int BuildHSym(T_SgInfo *SgInfo) HaveOrSh = 0; for (i = 0; i < 3; i++) { - OrSh[i] = SgInfo->OriginShift[i] * (STBF / 12); - if (OrSh[i]) HaveOrSh = 1; + OrSh[i] = SgInfo->OriginShift[i] * (STBF / 12); + if (OrSh[i]) + HaveOrSh = 1; } NeedDash = 0; nGRT = 0; - for (iG = 0; iG < SgInfo->nGenerator; iG++) - { + for (iG = 0; iG < SgInfo->nGenerator; iG++) { iList = SgInfo->Generator_iList[iG]; - GRT[nGRT].RMxI = ListOrBufRotMxInfo(SgInfo, iList, &GRT[nGRT].RMxI_Buf); + GRT[nGRT].RMxI = + ListOrBufRotMxInfo(SgInfo, iList, &GRT[nGRT].RMxI_Buf); if (GRT[nGRT].RMxI == NULL) return -1; @@ -2002,28 +2153,29 @@ static int BuildHSym(T_SgInfo *SgInfo) RotMx_t_Vector(RO, SMx->s.R, OrSh, STBF); for (i = 0; i < 3; i++) - GRT[nGRT].Transl[i] = iModPositive(SMx->s.T[i] + RO[i] - OrSh[i], STBF); + GRT[nGRT].Transl[i] = + iModPositive(SMx->s.T[i] + RO[i] - OrSh[i], STBF); - if (GRT[nGRT].RMxI->Order == -1) - { + if (GRT[nGRT].RMxI->Order == -1) { for (i = 0; i < 3; i++) - if (GRT[nGRT].Transl[i] != 0) break; + if (GRT[nGRT].Transl[i] != 0) + break; - if (i == 3) NeedDash = 1; - else nGRT++; - } - else + if (i == 3) + NeedDash = 1; + else + nGRT++; + } else nGRT++; } - if (SgInfo->Centric) - { + if (SgInfo->Centric) { if (HaveOrSh == 0) NeedDash = 1; - else - { + else { for (iG = 0; iG < nGRT; iG++) - if (GRT[iG].RMxI->Order == 1) break; + if (GRT[iG].RMxI->Order == 1) + break; InitSeitzMx(&SMx_1, -1); @@ -2062,38 +2214,34 @@ static int BuildHSym(T_SgInfo *SgInfo) nTrV = SgInfo->LatticeInfo->nTrVector; - for (iG = 0; iG < nGRT; iG++) - { + for (iG = 0; iG < nGRT; iG++) { rmxi = GRT[iG].RMxI; AbsOrder = abs(rmxi->Order); RefAxis = rmxi->RefAxis; DirCode = rmxi->DirCode; - if (RefAxis == 'o') RefAxis = 0; - if (DirCode == '=' || DirCode == '.') DirCode = 0; + if (RefAxis == 'o') + RefAxis = 0; + if (DirCode == '=' || DirCode == '.') + DirCode = 0; - if (iG == 0) - { - if (RefAxis == 'z') RefAxis = 0; - } - else - { - if (AbsOrder == 2) - { - if (PreviousRotation == 2 || PreviousRotation == 4) - { - if (RefAxis == 'x') RefAxis = 0; + if (iG == 0) { + if (RefAxis == 'z') + RefAxis = 0; + } else { + if (AbsOrder == 2) { + if (PreviousRotation == 2 || PreviousRotation == 4) { + if (RefAxis == 'x') + RefAxis = 0; + } else if (PreviousRotation == 3 || PreviousRotation == 6) { + if (PreviousDirCode == '*' || RefAxis == PreviousRefAxis) + RefAxis = 0; + if (DirCode == '\'') + DirCode = 0; } - else if (PreviousRotation == 3 || PreviousRotation == 6) - { - if ( PreviousDirCode == '*' - || RefAxis == PreviousRefAxis) RefAxis = 0; - if (DirCode == '\'') DirCode = 0; - } - } - else if (AbsOrder == 3) - { - if (DirCode == '*') DirCode = 0; + } else if (AbsOrder == 3) { + if (DirCode == '*') + DirCode = 0; } } @@ -2102,15 +2250,17 @@ static int BuildHSym(T_SgInfo *SgInfo) PreviousDirCode = rmxi->DirCode; *hsym++ = ' '; - if (rmxi->Order < 0) *hsym++ = '-'; + if (rmxi->Order < 0) + *hsym++ = '-'; *hsym++ = Digits[AbsOrder]; - if (RefAxis) *hsym++ = RefAxis; - if (DirCode) *hsym++ = DirCode; + if (RefAxis) + *hsym++ = RefAxis; + if (DirCode) + *hsym++ = DirCode; TrV = SgInfo->LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) - { + for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) { for (i = 0; i < 3; i++) if ((GRT[iG].Transl[i] + TrV[i]) % STBF != 0) break; @@ -2120,34 +2270,32 @@ static int BuildHSym(T_SgInfo *SgInfo) } if (iTrV < nTrV) - continue; /* next iG */ + continue; /* next iG */ hsym_mark = hsym; TrV = SgInfo->LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3, hsym = hsym_mark) - { + for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3, hsym = hsym_mark) { for (i = 0; i < 3; i++) Transl[i] = iModPositive(GRT[iG].Transl[i] + TrV[i], STBF); Screw = 0; for (ip = 0; ip < 3; ip++) - if (rmxi->EigenVector[ip] != 0) break; + if (rmxi->EigenVector[ip] != 0) + break; - if (ip < 3 && rmxi->EigenVector[ip] == 1) - { + if (ip < 3 && rmxi->EigenVector[ip] == 1) { for (i = ip + 1; i < 3; i++) - if (rmxi->EigenVector[i] != 0) break; + if (rmxi->EigenVector[i] != 0) + break; - if (i == 3) - { + if (i == 3) { ScrewPrimitive = STBF / AbsOrder; Screw = Transl[ip] / ScrewPrimitive; - i = Screw * ScrewPrimitive; - if (i % 3) - { + i = Screw * ScrewPrimitive; + if (i % 3) { *hsym++ = Digits[Screw]; Transl[ip] -= i; } @@ -2156,13 +2304,12 @@ static int BuildHSym(T_SgInfo *SgInfo) ht = HallTranslations; - while (*ht) - { + while (*ht) { for (i = 0; i < 3; i++) - if (Transl[i] < ht[i + 1]) break; + if (Transl[i] < ht[i + 1]) + break; - if (i == 3) - { + if (i == 3) { for (i = 0; i < 3; i++) Transl[i] -= ht[i + 1]; @@ -2184,24 +2331,21 @@ static int BuildHSym(T_SgInfo *SgInfo) return 0; } - if (nGRT == 0) - { + if (nGRT == 0) { *hsym++ = ' '; *hsym++ = '1'; } - if (HaveOrSh) - { + if (HaveOrSh) { *hsym++ = ' '; *hsym++ = '('; - for (i = 0; i < 3; i++) - { - if (i) *hsym++ = ' '; + for (i = 0; i < 3; i++) { + if (i) + *hsym++ = ' '; - os = iModPositive(SgInfo->OriginShift[i], 12); - if (os > 6) - { + os = iModPositive(SgInfo->OriginShift[i], 12); + if (os > 6) { *hsym++ = '-'; os = 12 - os; } @@ -2223,46 +2367,39 @@ static int BuildHSym(T_SgInfo *SgInfo) } -static int BuildHallSymbol(T_SgInfo *SgInfo, int FixedOriginShift) +static int BuildHallSymbol(T_SgInfo * SgInfo, int FixedOriginShift) { - int ix, iy, iz; - int status; + int ix, iy, iz; + int status; static const int ShiftTable[] = { 0, 1, -1, 2, -2, 3 }; - if (SgError != NULL) return -1; + if (SgError != NULL) + return -1; - if (SgInfo->nGenerator == 0) - { - if (BuildGenerator_iList(SgInfo) != 0) - { + if (SgInfo->nGenerator == 0) { + if (BuildGenerator_iList(SgInfo) != 0) { SetSgError("Error: Can't build generator list"); return -1; } } - if (FixedOriginShift) - { - status = BuildHSym(SgInfo); + if (FixedOriginShift) { + status = BuildHSym(SgInfo); if (status == 1) return 0; - } - else - { - for (ix = 0; ix < 6; ix++) - { + } else { + for (ix = 0; ix < 6; ix++) { SgInfo->OriginShift[0] = ShiftTable[ix]; - for (iy = 0; iy < 6; iy++) - { + for (iy = 0; iy < 6; iy++) { SgInfo->OriginShift[1] = ShiftTable[iy]; - for (iz = 0; iz < 6; iz++) - { + for (iz = 0; iz < 6; iz++) { SgInfo->OriginShift[2] = ShiftTable[iz]; - status = BuildHSym(SgInfo); + status = BuildHSym(SgInfo); if (status < 0) return -1; @@ -2278,9 +2415,9 @@ static int BuildHallSymbol(T_SgInfo *SgInfo, int FixedOriginShift) } -void InitSgInfo(T_SgInfo *SgInfo) +void InitSgInfo(T_SgInfo * SgInfo) { - int i; + int i; SgInfo->GenOption = 0; @@ -2307,14 +2444,13 @@ void InitSgInfo(T_SgInfo *SgInfo) } -int CompleteSgInfo(T_SgInfo *SgInfo) +int CompleteSgInfo(T_SgInfo * SgInfo) { - int List_iList[192]; - const T_TabSgName *tsgn; + int List_iList[192]; + const T_TabSgName *tsgn; - if (SgInfo->StatusLatticeTr == -1) - { + if (SgInfo->StatusLatticeTr == -1) { if (AddLatticeTr2ListSeitzMx(SgInfo, SgInfo->LatticeInfo) < 0) return -1; } @@ -2322,15 +2458,15 @@ int CompleteSgInfo(T_SgInfo *SgInfo) if (ApplyOriginShift(SgInfo) < 0) return -1; - if (SgInfo->nList > sizeof List_iList / sizeof (*List_iList)) { + if (SgInfo->nList > sizeof List_iList / sizeof(*List_iList)) { SetSgError("Internal Error: CompleteSgInfo()"); return -1; } - if (SgInfo->nList > 1) - { + if (SgInfo->nList > 1) { SortSgInfoList(SgInfo, List_iList); - if (SgError != NULL) return -1; + if (SgError != NULL) + return -1; } if (RemoveLatticeTr(SgInfo) != 0) @@ -2341,13 +2477,14 @@ int CompleteSgInfo(T_SgInfo *SgInfo) TidyTranslation(SgInfo); - if (SgInfo->nList > 1) - { + if (SgInfo->nList > 1) { SortSgInfoList(SgInfo, List_iList); - if (SgError != NULL) return -1; + if (SgError != NULL) + return -1; } - SgInfo->OrderP = SgInfo->nList; - if (SgInfo->Centric == -1) SgInfo->OrderP *= 2; + SgInfo->OrderP = SgInfo->nList; + if (SgInfo->Centric == -1) + SgInfo->OrderP *= 2; SgInfo->OrderL = SgInfo->OrderP * SgInfo->LatticeInfo->nTrVector; @@ -2355,18 +2492,17 @@ int CompleteSgInfo(T_SgInfo *SgInfo) return -1; for (tsgn = TabSgName; tsgn->HallSymbol; tsgn++) - if ( strcmp(tsgn->HallSymbol, SgInfo->HallSymbol) == 0 - && ( SgInfo->TabSgName == NULL - || SgInfo->TabSgName == tsgn)) + if (strcmp(tsgn->HallSymbol, SgInfo->HallSymbol) == 0 + && (SgInfo->TabSgName == NULL || SgInfo->TabSgName == tsgn)) break; - if (SgInfo->TabSgName != NULL && tsgn->HallSymbol == NULL) - { - if (SgError) return -1; + if (SgInfo->TabSgName != NULL && tsgn->HallSymbol == NULL) { + if (SgError) + return -1; sprintf(SgErrorBuffer, - "Internal Error: Input/Output HallSymbol mismatch: %s <> %s", - SgInfo->TabSgName->HallSymbol, SgInfo->HallSymbol); + "Internal Error: Input/Output HallSymbol mismatch: %s <> %s", + SgInfo->TabSgName->HallSymbol, SgInfo->HallSymbol); SetSgError(SgErrorBuffer); return -1; @@ -2377,40 +2513,66 @@ int CompleteSgInfo(T_SgInfo *SgInfo) SgInfo->CCMx_LP = NULL; - switch (SgInfo->LatticeInfo->Code) - { - case 'P': SgInfo->CCMx_LP = CCMx_PP; break; - case 'A': SgInfo->CCMx_LP = CCMx_AP; break; - case 'B': SgInfo->CCMx_LP = CCMx_BP; break; - case 'C': SgInfo->CCMx_LP = CCMx_CP; break; - case 'I': SgInfo->CCMx_LP = CCMx_IP; break; - case 'R': - switch (SgInfo->UniqueRefAxis) { - case 0: - case 'z': SgInfo->CCMx_LP = CCMx_RP_z; break; - case 'y': SgInfo->CCMx_LP = CCMx_RP_y; break; - default: break; - } + switch (SgInfo->LatticeInfo->Code) { + case 'P': + SgInfo->CCMx_LP = CCMx_PP; + break; + case 'A': + SgInfo->CCMx_LP = CCMx_AP; + break; + case 'B': + SgInfo->CCMx_LP = CCMx_BP; + break; + case 'C': + SgInfo->CCMx_LP = CCMx_CP; + break; + case 'I': + SgInfo->CCMx_LP = CCMx_IP; + break; + case 'R': + switch (SgInfo->UniqueRefAxis) { + case 0: + case 'z': + SgInfo->CCMx_LP = CCMx_RP_z; break; - case 'S': - switch (SgInfo->UniqueRefAxis) { - case 0: - case 'y': SgInfo->CCMx_LP = CCMx_SP_y; break; - case 'x': SgInfo->CCMx_LP = CCMx_SP_x; break; - default: break; - } + case 'y': + SgInfo->CCMx_LP = CCMx_RP_y; break; - case 'T': - switch (SgInfo->UniqueRefAxis) { - case 0: - case 'x': SgInfo->CCMx_LP = CCMx_TP_x; break; - case 'z': SgInfo->CCMx_LP = CCMx_TP_z; break; - default: break; - } - break; - case 'F': SgInfo->CCMx_LP = CCMx_FP; break; default: break; + } + break; + case 'S': + switch (SgInfo->UniqueRefAxis) { + case 0: + case 'y': + SgInfo->CCMx_LP = CCMx_SP_y; + break; + case 'x': + SgInfo->CCMx_LP = CCMx_SP_x; + break; + default: + break; + } + break; + case 'T': + switch (SgInfo->UniqueRefAxis) { + case 0: + case 'x': + SgInfo->CCMx_LP = CCMx_TP_x; + break; + case 'z': + SgInfo->CCMx_LP = CCMx_TP_z; + break; + default: + break; + } + break; + case 'F': + SgInfo->CCMx_LP = CCMx_FP; + break; + default: + break; } if (SgInfo->CCMx_LP == NULL) { @@ -2422,18 +2584,17 @@ int CompleteSgInfo(T_SgInfo *SgInfo) } -int CB_SMx(T_RTMx *CSiC, - const T_RTMx *CBMx, const T_RTMx *SMx, const T_RTMx *InvCBMx) +int CB_SMx(T_RTMx * CSiC, + const T_RTMx * CBMx, const T_RTMx * SMx, const T_RTMx * InvCBMx) { - int i; - T_RTMx BufMx; + int i; + T_RTMx BufMx; - RTMxMultiply(&BufMx, SMx, InvCBMx, CTBF / STBF, CTBF); - RTMxMultiply(CSiC, CBMx, &BufMx, CRBF, CRBF * CTBF); + RTMxMultiply(&BufMx, SMx, InvCBMx, CTBF / STBF, CTBF); + RTMxMultiply(CSiC, CBMx, &BufMx, CRBF, CRBF * CTBF); - for (i = 0; i < 9; i++) - { + for (i = 0; i < 9; i++) { if (CSiC->s.R[i] % (CRBF * CRBF)) { SetSgError("Internal Error: Corrupt CBMx/SMx/InvCBMx"); return -1; @@ -2442,8 +2603,7 @@ int CB_SMx(T_RTMx *CSiC, CSiC->s.R[i] /= (CRBF * CRBF); } - for (i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { if (CSiC->s.T[i] % (CRBF * (CTBF / STBF))) { SetSgError("Internal Error: Out of STBF range"); return -1; @@ -2456,33 +2616,32 @@ int CB_SMx(T_RTMx *CSiC, } -int TransformSgInfo(const T_SgInfo *SgInfo, - const T_RTMx *CBMx, const T_RTMx *InvCBMx, - T_SgInfo *BC_SgInfo) +int TransformSgInfo(const T_SgInfo * SgInfo, + const T_RTMx * CBMx, const T_RTMx * InvCBMx, + T_SgInfo * BC_SgInfo) { - int iList, f, i; - int nTrV, iTrV, nLoopInv, iLoopInv; - const int *TrV; - T_RTMx SMx, BC_SMx; - const T_RTMx *lsmx; + int iList, f, i; + int nTrV, iTrV, nLoopInv, iLoopInv; + const int *TrV; + T_RTMx SMx, BC_SMx; + const T_RTMx *lsmx; nLoopInv = Sg_nLoopInv(SgInfo); nTrV = SgInfo->LatticeInfo->nTrVector; - TrV = SgInfo->LatticeInfo->TrVector; + TrV = SgInfo->LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) - { - for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) - { - if (iLoopInv == 0) f = 1; - else f = -1; + for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) { + for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) { + if (iLoopInv == 0) + f = 1; + else + f = -1; lsmx = SgInfo->ListSeitzMx; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { for (i = 0; i < 9; i++) SMx.s.R[i] = f * lsmx->s.R[i]; diff --git a/sgfind.c b/sgfind.c index ea58fe5a..0cc9fdfa 100644 --- a/sgfind.c +++ b/sgfind.c @@ -10,87 +10,100 @@ #include "sginfo.h" -static int InitialCBMxR(T_SgInfo *SgInfo, - const T_LatticeInfo **NewLatticeInfo, +static int InitialCBMxR(T_SgInfo * SgInfo, + const T_LatticeInfo ** NewLatticeInfo, int *NewPointGroup, int *IniCBMxR, int *IniInvCBMxR) { - int Code, NewPG, deterCCMx, fac, i; - const T_LatticeInfo *NewLI; - const int *CCMx; + int Code, NewPG, deterCCMx, fac, i; + const T_LatticeInfo *NewLI; + const int *CCMx; - Code = SgInfo->LatticeInfo->Code; + Code = SgInfo->LatticeInfo->Code; NewLI = SgInfo->LatticeInfo; NewPG = SgInfo->PointGroup; - CCMx = CCMx_PP; + CCMx = CCMx_PP; - switch(SgInfo->XtalSystem) - { - case XS_Triclinic: - NewLI = LI_P; - CCMx = SgInfo->CCMx_LP; - break; + switch (SgInfo->XtalSystem) { + case XS_Triclinic: + NewLI = LI_P; + CCMx = SgInfo->CCMx_LP; + break; - case XS_Monoclinic: - case XS_Tetragonal: - switch (SgInfo->UniqueRefAxis) - { - case 'z': if (Code == 'C') { - NewLI = LI_P; CCMx = SgInfo->CCMx_LP; } - else if (Code == 'F') { - NewLI = LI_I; CCMx = CCMx_FI_z; } - break; - case 'y': if (Code == 'B') { - NewLI = LI_P; CCMx = SgInfo->CCMx_LP; } - else if (Code == 'F') { - NewLI = LI_I; CCMx = CCMx_FI_y; } - break; - case 'x': if (Code == 'A') { - NewLI = LI_P; CCMx = SgInfo->CCMx_LP; } - else if (Code == 'F') { - NewLI = LI_I; CCMx = CCMx_FI_x; } - break; - default: - goto ReturnError; + case XS_Monoclinic: + case XS_Tetragonal: + switch (SgInfo->UniqueRefAxis) { + case 'z': + if (Code == 'C') { + NewLI = LI_P; + CCMx = SgInfo->CCMx_LP; + } else if (Code == 'F') { + NewLI = LI_I; + CCMx = CCMx_FI_z; } - - if ( SgInfo->XtalSystem == XS_Tetragonal - && SgInfo->LatticeInfo != NewLI) - { - if (NewPG == PG_4b2m) NewPG = PG_4bm2; - else if (NewPG == PG_4bm2) NewPG = PG_4b2m; + break; + case 'y': + if (Code == 'B') { + NewLI = LI_P; + CCMx = SgInfo->CCMx_LP; + } else if (Code == 'F') { + NewLI = LI_I; + CCMx = CCMx_FI_y; } - break; - - case XS_Orthorhombic: - break; - - case XS_Trigonal: - NewLI = LI_P; - CCMx = SgInfo->CCMx_LP; - - if (Code == 'R' || Code == 'S' || Code == 'T') - { - if (NewPG == PG_321) NewPG = PG_32; - else if (NewPG == PG_3m1) NewPG = PG_3m; - else if (NewPG == PG_3bm1) NewPG = PG_3bm; + case 'x': + if (Code == 'A') { + NewLI = LI_P; + CCMx = SgInfo->CCMx_LP; + } else if (Code == 'F') { + NewLI = LI_I; + CCMx = CCMx_FI_x; } - break; - - case XS_Hexagonal: - break; - - case XS_Cubic: - break; - default: goto ReturnError; + } + + if (SgInfo->XtalSystem == XS_Tetragonal + && SgInfo->LatticeInfo != NewLI) { + if (NewPG == PG_4b2m) + NewPG = PG_4bm2; + else if (NewPG == PG_4bm2) + NewPG = PG_4b2m; + } + + break; + + case XS_Orthorhombic: + break; + + case XS_Trigonal: + NewLI = LI_P; + CCMx = SgInfo->CCMx_LP; + + if (Code == 'R' || Code == 'S' || Code == 'T') { + if (NewPG == PG_321) + NewPG = PG_32; + else if (NewPG == PG_3m1) + NewPG = PG_3m; + else if (NewPG == PG_3bm1) + NewPG = PG_3bm; + } + + break; + + case XS_Hexagonal: + break; + + case XS_Cubic: + break; + + default: + goto ReturnError; } - deterCCMx = deterRotMx(CCMx); + deterCCMx = deterRotMx(CCMx); if (deterCCMx < 1 || CRBF % deterCCMx) goto ReturnError; @@ -99,16 +112,16 @@ static int InitialCBMxR(T_SgInfo *SgInfo, InverseRotMx(CCMx, IniInvCBMxR); for (i = 0; i < 9; i++) { - IniCBMxR[i] = CRBF * CCMx[i]; + IniCBMxR[i] = CRBF * CCMx[i]; IniInvCBMxR[i] *= fac; } *NewLatticeInfo = NewLI; - *NewPointGroup = NewPG; + *NewPointGroup = NewPG; return deterCCMx; - ReturnError: +ReturnError: SetSgError("Internal Error: InitialCBMxR()"); return -1; @@ -118,14 +131,13 @@ static int InitialCBMxR(T_SgInfo *SgInfo, static int CBR_RMx(int *RRMx, const int *CBMxR, const int *RMx, const int *InvCBMxR) { - int i, BufMx[9]; + int i, BufMx[9]; - RotMxMultiply(BufMx, RMx, InvCBMxR); - RotMxMultiply(RRMx, CBMxR, BufMx); + RotMxMultiply(BufMx, RMx, InvCBMxR); + RotMxMultiply(RRMx, CBMxR, BufMx); - for (i = 0; i < 9; i++) - { + for (i = 0; i < 9; i++) { if (RRMx[i] % (CRBF * CRBF)) { SetSgError("Internal Error: CBR_SMx()"); return -1; @@ -141,28 +153,29 @@ static int CBR_RMx(int *RRMx, static void RotateCBMxR(const int *RMx, const int *InvRMx, int *CBMxR, int *InvCBMxR) { - int i, BufMx[9]; + int i, BufMx[9]; RotMxMultiply(BufMx, RMx, CBMxR); - for (i = 0; i < 9; i++) CBMxR[i] = BufMx[i]; + for (i = 0; i < 9; i++) + CBMxR[i] = BufMx[i]; /* matrix algebra: (A * B)^-1 = B^-1 * A^-1 */ RotMxMultiply(BufMx, InvCBMxR, InvRMx); - for (i = 0; i < 9; i++) InvCBMxR[i] = BufMx[i]; + for (i = 0; i < 9; i++) + InvCBMxR[i] = BufMx[i]; } -static int AlignUniqueAxis(const T_SgInfo *SgInfo, - const T_SgInfo *GenSgI, - int *CBMxR, int *InvCBMxR, - const int **AlignRMx) +static int AlignUniqueAxis(const T_SgInfo * SgInfo, + const T_SgInfo * GenSgI, + int *CBMxR, int *InvCBMxR, const int **AlignRMx) { - int i, iListS, DirCode; - int UAMx[9], RotEV[3]; - const int *RMx, *InvRMx, *lsmxR; - T_RotMxInfo RMxI_S, *RMxI_G; + int i, iListS, DirCode; + int UAMx[9], RotEV[3]; + const int *RMx, *InvRMx, *lsmxR; + T_RotMxInfo RMxI_S, *RMxI_G; if (GenSgI->nList < 2) @@ -170,16 +183,17 @@ static int AlignUniqueAxis(const T_SgInfo *SgInfo, RMxI_G = &GenSgI->ListRotMxInfo[1]; - if (abs(RMxI_G->Order) == 3) DirCode = 0; - else DirCode = '='; + if (abs(RMxI_G->Order) == 3) + DirCode = 0; + else + DirCode = '='; - iListS = FindSeitzMx(SgInfo, RMxI_G->Order, 1, 0, DirCode); - if (iListS < 0) - { + iListS = FindSeitzMx(SgInfo, RMxI_G->Order, 1, 0, DirCode); + if (iListS < 0) { if (SgInfo->Centric == 0) return 0; - iListS = FindSeitzMx(SgInfo, -RMxI_G->Order, 1, 0, DirCode); + iListS = FindSeitzMx(SgInfo, -RMxI_G->Order, 1, 0, DirCode); if (iListS < 0) goto ReturnError; @@ -187,8 +201,7 @@ static int AlignUniqueAxis(const T_SgInfo *SgInfo, UAMx[i] = -SgInfo->ListSeitzMx[iListS].s.R[i]; lsmxR = UAMx; - } - else + } else lsmxR = SgInfo->ListSeitzMx[iListS].s.R; if (CBR_RMx(UAMx, CBMxR, lsmxR, InvCBMxR) != 0) @@ -202,37 +215,38 @@ static int AlignUniqueAxis(const T_SgInfo *SgInfo, RMx = InvRMx = RMx_1_000; - for (;;) - { + for (;;) { RotMx_t_Vector(RotEV, RMx, RMxI_S.EigenVector, 0); for (i = 0; i < 3; i++) - if (RotEV[i] != RMxI_G->EigenVector[i]) break; + if (RotEV[i] != RMxI_G->EigenVector[i]) + break; if (i == 3) break; - if (RMxI_S.DirCode == '=') - { - if (RMx == RMx_1_000) { - RMx = RMx_3_111; InvRMx = RMx_3i111; } - else if (RMx == RMx_3_111) { - RMx = RMx_3i111; InvRMx = RMx_3_111; } - else + if (RMxI_S.DirCode == '=') { + if (RMx == RMx_1_000) { + RMx = RMx_3_111; + InvRMx = RMx_3i111; + } else if (RMx == RMx_3_111) { + RMx = RMx_3i111; + InvRMx = RMx_3_111; + } else goto ReturnError; - } - else if (RMxI_S.DirCode == '*') - { - if (RMx == RMx_1_000) { - RMx = RMx_4_001; InvRMx = RMx_4i001; } - else if (RMx == RMx_4_001) { - RMx = RMx_2_001; InvRMx = RMx_2_001; } - else if (RMx == RMx_2_001) { - RMx = RMx_4i001; InvRMx = RMx_4_001; } - else + } else if (RMxI_S.DirCode == '*') { + if (RMx == RMx_1_000) { + RMx = RMx_4_001; + InvRMx = RMx_4i001; + } else if (RMx == RMx_4_001) { + RMx = RMx_2_001; + InvRMx = RMx_2_001; + } else if (RMx == RMx_2_001) { + RMx = RMx_4i001; + InvRMx = RMx_4_001; + } else goto ReturnError; - } - else + } else goto ReturnError; } @@ -240,11 +254,11 @@ static int AlignUniqueAxis(const T_SgInfo *SgInfo, RotateCBMxR(RMx, InvRMx, CBMxR, InvCBMxR); if (AlignRMx) - *AlignRMx = RMx; + *AlignRMx = RMx; return 1; - ReturnError: +ReturnError: SetSgError("Internal Error: AlignUniqueAxis()"); return -1; @@ -252,18 +266,18 @@ static int AlignUniqueAxis(const T_SgInfo *SgInfo, static const T_RTMx *GetSMxWithSameRot(const int *WtdRotMx, - const T_SgInfo *SgInfo, T_RTMx *BufMx) + const T_SgInfo * SgInfo, + T_RTMx * BufMx) { - int iList, i; - const T_RTMx *lsmx; + int iList, i; + const T_RTMx *lsmx; lsmx = SgInfo->ListSeitzMx; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { for (i = 0; i < 9; i++) - if (WtdRotMx[i] != lsmx->s.R[i]) + if (WtdRotMx[i] != lsmx->s.R[i]) break; if (i == 9) @@ -276,15 +290,14 @@ static const T_RTMx *GetSMxWithSameRot(const int *WtdRotMx, if (WtdRotMx[i] != -lsmx->s.R[i]) break; - if (i == 9) - { + if (i == 9) { for (i = 0; i < 9; i++) - BufMx->s.R[i] = -lsmx->s.R[i]; + BufMx->s.R[i] = -lsmx->s.R[i]; for (i = 0; i < 3; i++) { - BufMx->s.T[i] = -lsmx->s.T[i] % STBF; + BufMx->s.T[i] = -lsmx->s.T[i] % STBF; if (BufMx->s.T[i] < 0) - BufMx->s.T[i] += STBF; + BufMx->s.T[i] += STBF; } return BufMx; @@ -297,19 +310,18 @@ static const T_RTMx *GetSMxWithSameRot(const int *WtdRotMx, static int BuildFreeMx(const int *EigenVector, int Order, int *FreeMx) { - static const int GeneratorEigenVectors[] = - { - 001, 0, 0, 1, - 010, 0, 1, 0, - 100, 1, 0, 0, - 110, 1, 1, 0, - -110, 1, -1, 0, - 111, 1, 1, 1, - 0 - }; + static const int GeneratorEigenVectors[] = { + 001, 0, 0, 1, + 010, 0, 1, 0, + 100, 1, 0, 0, + 110, 1, 1, 0, + -110, 1, -1, 0, + 111, 1, 1, 1, + 0 + }; - int i; - const int *gev; + int i; + const int *gev; for (i = 0; i < 9; i++) @@ -318,8 +330,7 @@ static int BuildFreeMx(const int *EigenVector, int Order, int *FreeMx) if (Order == -1 || Order == -3 || Order == -4 || Order == -6) return 0; - for (gev = GeneratorEigenVectors; *gev++ != 0; gev += 3) - { + for (gev = GeneratorEigenVectors; *gev++ != 0; gev += 3) { for (i = 0; i < 3; i++) if (EigenVector[i] != gev[i]) break; @@ -330,31 +341,59 @@ static int BuildFreeMx(const int *EigenVector, int Order, int *FreeMx) gev--; - if (Order == -2) - { - switch (*gev) - { - case 001: FreeMx[0] = 1; FreeMx[4] = 1; return 0; - case 010: FreeMx[8] = 1; FreeMx[0] = 1; return 0; - case 100: FreeMx[4] = 1; FreeMx[8] = 1; return 0; - case 110: FreeMx[1] = 1; FreeMx[4] = -1; FreeMx[8] = 1; return 1; - case -110: FreeMx[1] = 1; FreeMx[4] = 1; FreeMx[8] = 1; return 1; - default: - break; + if (Order == -2) { + switch (*gev) { + case 001: + FreeMx[0] = 1; + FreeMx[4] = 1; + return 0; + case 010: + FreeMx[8] = 1; + FreeMx[0] = 1; + return 0; + case 100: + FreeMx[4] = 1; + FreeMx[8] = 1; + return 0; + case 110: + FreeMx[1] = 1; + FreeMx[4] = -1; + FreeMx[8] = 1; + return 1; + case -110: + FreeMx[1] = 1; + FreeMx[4] = 1; + FreeMx[8] = 1; + return 1; + default: + break; } - } - else if (Order > 1) - { - switch (*gev) - { - case 001: FreeMx[8] = 1; return 0; - case 010: FreeMx[4] = 1; return 0; - case 100: FreeMx[0] = 1; return 0; - case 110: FreeMx[0] = 1; FreeMx[3] = 1; return 1; - case -110: FreeMx[0] = 1; FreeMx[3] = -1; return 1; - case 111: FreeMx[0] = 1; FreeMx[3] = 1; FreeMx[6] = 1; return 1; - default: - break; + } else if (Order > 1) { + switch (*gev) { + case 001: + FreeMx[8] = 1; + return 0; + case 010: + FreeMx[4] = 1; + return 0; + case 100: + FreeMx[0] = 1; + return 0; + case 110: + FreeMx[0] = 1; + FreeMx[3] = 1; + return 1; + case -110: + FreeMx[0] = 1; + FreeMx[3] = -1; + return 1; + case 111: + FreeMx[0] = 1; + FreeMx[3] = 1; + FreeMx[6] = 1; + return 1; + default: + break; } } @@ -363,17 +402,17 @@ static int BuildFreeMx(const int *EigenVector, int Order, int *FreeMx) } -static int StartFixAxes(const T_SgInfo *SgInfo, - const T_SgInfo *GenSgI, const int *iGen, - T_RTMx *CBMx, T_RTMx *InvCBMx, - T_RTMx *SMxG, T_RTMx *SMxS_G, +static int StartFixAxes(const T_SgInfo * SgInfo, + const T_SgInfo * GenSgI, const int *iGen, + T_RTMx * CBMx, T_RTMx * InvCBMx, + T_RTMx * SMxG, T_RTMx * SMxS_G, int *FreeMx, int *TryAgain) { - int iG, Order, i; - const int *EV; - T_RTMx SMxG_S, BufMx; - const T_RTMx *SMx; - const T_RotMxInfo *RMxI_G; + int iG, Order, i; + const int *EV; + T_RTMx SMxG_S, BufMx; + const T_RTMx *SMx; + const T_RotMxInfo *RMxI_G; if (*iGen == -3) @@ -381,35 +420,28 @@ static int StartFixAxes(const T_SgInfo *SgInfo, else iG = *iGen; - if (iG == -1) - { + if (iG == -1) { Order = -1; - EV = NULL; - } - else - { + EV = NULL; + } else { if (iG < 1 || iG >= GenSgI->nList) goto ReturnError; - RMxI_G = &GenSgI->ListRotMxInfo[iG]; + RMxI_G = &GenSgI->ListRotMxInfo[iG]; Order = RMxI_G->Order; - EV = RMxI_G->EigenVector; + EV = RMxI_G->EigenVector; - if (iG != *iGen) - { - Order *= -1; + if (iG != *iGen) { + Order *= -1; if (Order != *iGen) goto ReturnError; } } - if (Order == -1) - { + if (Order == -1) { if (GenSgI->Centric == -1) { InitSeitzMx(SMxG, -1); - } - else - { + } else { for (iG = 1; iG < GenSgI->nList; iG++) if (GenSgI->ListRotMxInfo[iG].Order == -1) break; @@ -419,24 +451,23 @@ static int StartFixAxes(const T_SgInfo *SgInfo, SMx = &GenSgI->ListSeitzMx[iG]; - for (i = 0; i < 12; i++) SMxG->a[i] = SMx->a[i]; + for (i = 0; i < 12; i++) + SMxG->a[i] = SMx->a[i]; } - } - else - { + } else { SMx = &GenSgI->ListSeitzMx[iG]; if (iG == *iGen) - for (i = 0; i < 12; i++) SMxG->a[i] = SMx->a[i]; - else - { + for (i = 0; i < 12; i++) + SMxG->a[i] = SMx->a[i]; + else { for (i = 0; i < 9; i++) - SMxG->s.R[i] = -SMx->s.R[i]; + SMxG->s.R[i] = -SMx->s.R[i]; for (i = 0; i < 3; i++) { - SMxG->s.T[i] = -SMx->s.T[i] % STBF; + SMxG->s.T[i] = -SMx->s.T[i] % STBF; if (SMxG->s.T[i] < 0) - SMxG->s.T[i] += STBF; + SMxG->s.T[i] += STBF; } } } @@ -444,7 +475,7 @@ static int StartFixAxes(const T_SgInfo *SgInfo, if (CB_SMx(&SMxG_S, InvCBMx, SMxG, CBMx) != 0) return -1; - SMx = GetSMxWithSameRot(SMxG_S.s.R, SgInfo, &BufMx); + SMx = GetSMxWithSameRot(SMxG_S.s.R, SgInfo, &BufMx); if (SMx == NULL) return 0; @@ -455,13 +486,13 @@ static int StartFixAxes(const T_SgInfo *SgInfo, if (SMxS_G->s.R[i] != SMxG->s.R[i]) goto ReturnError; - *TryAgain = BuildFreeMx(EV, Order, FreeMx); + *TryAgain = BuildFreeMx(EV, Order, FreeMx); if (*TryAgain < 0) return -1; return 1; - ReturnError: +ReturnError: SetSgError("Internal Error: StartFixAxes()"); return -1; @@ -471,72 +502,61 @@ static int StartFixAxes(const T_SgInfo *SgInfo, static int FindInvertableMx(const int *Mx, int *InvMx, int *nActive, int *irActive, int *icActive) { - int Init, deterMx, i; + int Init, deterMx, i; if (*nActive == 0 || *nActive == 3) return 0; - if (*nActive == -1) - { + if (*nActive == -1) { Init = 1; - deterMx = deterRotMx(Mx); - if (deterMx) - { + deterMx = deterRotMx(Mx); + if (deterMx) { InverseRotMx(Mx, InvMx); *nActive = 3; return deterMx; } - } - else + } else Init = 0; - if (Init || *nActive == 2) - { - for (;;) - { - if (Init) - { + if (Init || *nActive == 2) { + for (;;) { + if (Init) { irActive[0] = 0; irActive[1] = 1; icActive[0] = 0; icActive[1] = 1; Init = 0; - } - else - { + } else { if (++icActive[1] == 3) { if (++icActive[0] == 2) { if (++irActive[1] == 3) { if (++irActive[0] == 2) { Init = 1; break; - } - else { + } else { irActive[1] = irActive[0] + 1; icActive[0] = 0; icActive[1] = 1; } - } - else { + } else { icActive[0] = 0; icActive[1] = 1; } - } - else { + } else { icActive[1] = icActive[0] + 1; } } } - InvMx[0] = Mx[irActive[1] * 3 + icActive[1]]; - InvMx[1] = - Mx[irActive[0] * 3 + icActive[1]]; - InvMx[2] = - Mx[irActive[1] * 3 + icActive[0]]; - InvMx[3] = Mx[irActive[0] * 3 + icActive[0]]; + InvMx[0] = Mx[irActive[1] * 3 + icActive[1]]; + InvMx[1] = -Mx[irActive[0] * 3 + icActive[1]]; + InvMx[2] = -Mx[irActive[1] * 3 + icActive[0]]; + InvMx[3] = Mx[irActive[0] * 3 + icActive[0]]; - deterMx = InvMx[3] * InvMx[0] - InvMx[1] * InvMx[2]; + deterMx = InvMx[3] * InvMx[0] - InvMx[1] * InvMx[2]; if (deterMx) { *nActive = 2; return deterMx; @@ -547,11 +567,12 @@ static int FindInvertableMx(const int *Mx, int *InvMx, if (*nActive == 2) return 0; - if (Init) i = 0; - else i = irActive[0] * 3 + icActive[0] + 1; + if (Init) + i = 0; + else + i = irActive[0] * 3 + icActive[0] + 1; - for ( ; i < 9; i++) - { + for (; i < 9; i++) { if (Mx[i]) { irActive[0] = i / 3; icActive[0] = i % 3; @@ -568,47 +589,47 @@ static int FindInvertableMx(const int *Mx, int *InvMx, } -static int SetInvCBMxT(const int *CBMxT, const int *InvCBMxR, int *InvCBMxT) +static int SetInvCBMxT(const int *CBMxT, const int *InvCBMxR, + int *InvCBMxT) { - int i; + int i; RotMx_t_Vector(InvCBMxT, InvCBMxR, CBMxT, CRBF * CTBF); - for (i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { if (InvCBMxT[i] % CRBF) { SetSgError("Internal Error: SetInvCBMxT()"); return -1; } if (InvCBMxT[i]) - InvCBMxT[i] = CTBF - InvCBMxT[i] / CRBF; + InvCBMxT[i] = CTBF - InvCBMxT[i] / CRBF; } return 0; } -static int FixAxes(const T_SgInfo *SgInfo, - const T_SgInfo *GenSgI, const int *iGen, - T_RTMx *CBMx, T_RTMx *InvCBMx, +static int FixAxes(const T_SgInfo * SgInfo, + const T_SgInfo * GenSgI, const int *iGen, + T_RTMx * CBMx, T_RTMx * InvCBMx, int *FreeMx, int TryAgain) { - int i, NextTryAgain; - int IniCBMxT[3], SingleFreeMx[9]; - T_RTMx SMxG, SMxS_G; - int NextFreeMxBuf[9], R_I_FMxBuf[9]; - int R_I[9], *R_I_FMx, InvR_I_FMx[9], deterR_I_FMx; - int S_G[3], CmpS_G[3], RedSh[3], Sh[3], *NextFreeMx; - int nActive, irActive[3], icActive[3]; - int nTrV, iTrV; - const int *TrV; + int i, NextTryAgain; + int IniCBMxT[3], SingleFreeMx[9]; + T_RTMx SMxG, SMxS_G; + int NextFreeMxBuf[9], R_I_FMxBuf[9]; + int R_I[9], *R_I_FMx, InvR_I_FMx[9], deterR_I_FMx; + int S_G[3], CmpS_G[3], RedSh[3], Sh[3], *NextFreeMx; + int nActive, irActive[3], icActive[3]; + int nTrV, iTrV; + const int *TrV; if (FreeMx == NULL) { for (i = 0; i < 3; i++) { - CBMx->s.T[i] = 0; + CBMx->s.T[i] = 0; InvCBMx->s.T[i] = 0; } } @@ -620,9 +641,8 @@ static int FixAxes(const T_SgInfo *SgInfo, if (FreeMx) { RotMxMultiply(NextFreeMxBuf, SingleFreeMx, FreeMx); - NextFreeMx = NextFreeMxBuf; - } - else + NextFreeMx = NextFreeMxBuf; + } else NextFreeMx = SingleFreeMx; for (i = 0; i < 9; i++) @@ -633,9 +653,8 @@ static int FixAxes(const T_SgInfo *SgInfo, if (FreeMx) { RotMxMultiply(R_I_FMxBuf, R_I, FreeMx); - R_I_FMx = R_I_FMxBuf; - } - else + R_I_FMx = R_I_FMxBuf; + } else R_I_FMx = R_I; for (i = 0; i < 3; i++) @@ -643,51 +662,45 @@ static int FixAxes(const T_SgInfo *SgInfo, nActive = -1; - for (;;) - { + for (;;) { deterR_I_FMx = FindInvertableMx(R_I_FMx, InvR_I_FMx, &nActive, irActive, icActive); if (deterR_I_FMx == 0) break; nTrV = GenSgI->LatticeInfo->nTrVector; - TrV = GenSgI->LatticeInfo->TrVector; + TrV = GenSgI->LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) - { + for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) { for (i = 0; i < 3; i++) { - S_G[i] = (CTBF / STBF) - * ((SMxS_G.s.T[i] - SMxG.s.T[i] - TrV[i]) % STBF); + S_G[i] = (CTBF / STBF) + * ((SMxS_G.s.T[i] - SMxG.s.T[i] - TrV[i]) % STBF); RedSh[i] = 0; } - switch(nActive) - { - case 1: - RedSh[icActive[0]] = S_G[irActive[0]]; - break; - case 2: - RedSh[icActive[0]] = InvR_I_FMx[0] * S_G[irActive[0]] - + InvR_I_FMx[1] * S_G[irActive[1]]; - RedSh[icActive[1]] = InvR_I_FMx[2] * S_G[irActive[0]] - + InvR_I_FMx[3] * S_G[irActive[1]]; - break; - case 3: - RotMx_t_Vector(RedSh, InvR_I_FMx, S_G, 0); - break; - default: - break; + switch (nActive) { + case 1: + RedSh[icActive[0]] = S_G[irActive[0]]; + break; + case 2: + RedSh[icActive[0]] = InvR_I_FMx[0] * S_G[irActive[0]] + + InvR_I_FMx[1] * S_G[irActive[1]]; + RedSh[icActive[1]] = InvR_I_FMx[2] * S_G[irActive[0]] + + InvR_I_FMx[3] * S_G[irActive[1]]; + break; + case 3: + RotMx_t_Vector(RedSh, InvR_I_FMx, S_G, 0); + break; + default: + break; } - if (FreeMx) - { + if (FreeMx) { RotMx_t_Vector(Sh, FreeMx, RedSh, 0); for (i = 0; i < 3; i++) Sh[i] %= (CTBF * abs(deterR_I_FMx)); - } - else - { + } else { for (i = 0; i < 3; i++) Sh[i] = RedSh[i] % (CTBF * abs(deterR_I_FMx)); } @@ -695,16 +708,15 @@ static int FixAxes(const T_SgInfo *SgInfo, RotMx_t_Vector(CmpS_G, R_I, Sh, 0); for (i = 0; i < 3; i++) - if ((CmpS_G[i] - S_G[i] * deterR_I_FMx) % (CTBF * abs(deterR_I_FMx))) + if ((CmpS_G[i] - + S_G[i] * deterR_I_FMx) % (CTBF * abs(deterR_I_FMx))) break; if (i < 3) continue; - if (deterR_I_FMx != 1) - { - for (i = 0; i < 3; i++) - { + if (deterR_I_FMx != 1) { + for (i = 0; i < 3; i++) { if (Sh[i] % abs(deterR_I_FMx)) goto ReturnError; @@ -713,9 +725,9 @@ static int FixAxes(const T_SgInfo *SgInfo, } for (i = 0; i < 3; i++) { - CBMx->s.T[i] = IniCBMxT[i] + Sh[i] % CTBF; + CBMx->s.T[i] = IniCBMxT[i] + Sh[i] % CTBF; if (CBMx->s.T[i] < 0) - CBMx->s.T[i] += CTBF; + CBMx->s.T[i] += CTBF; } if (SetInvCBMxT(CBMx->s.T, InvCBMx->s.R, InvCBMx->s.T) != 0) @@ -724,8 +736,8 @@ static int FixAxes(const T_SgInfo *SgInfo, if (iGen[1] == 0) return 1; - i = FixAxes(SgInfo, GenSgI, &iGen[1], CBMx, InvCBMx, - NextFreeMx, NextTryAgain); + i = FixAxes(SgInfo, GenSgI, &iGen[1], CBMx, InvCBMx, + NextFreeMx, NextTryAgain); if (i != 0) return i; } @@ -736,61 +748,59 @@ static int FixAxes(const T_SgInfo *SgInfo, return 0; - ReturnError: +ReturnError: SetSgError("Internal Error: FixAxes()"); return -1; } -static int CompleteCBMx(const T_SgInfo *SgInfo, const T_LatticeInfo *NewLI, - const T_SgInfo *GenSgI, - const int *IniCBMxR, const int *IniInvCBMxR, - T_RTMx *CBMx, T_RTMx *InvCBMx) +static int CompleteCBMx(const T_SgInfo * SgInfo, + const T_LatticeInfo * NewLI, + const T_SgInfo * GenSgI, const int *IniCBMxR, + const int *IniInvCBMxR, T_RTMx * CBMx, + T_RTMx * InvCBMx) { - int iGen[5], i; + int iGen[5], i; - if (SgInfo->XtalSystem == XS_Triclinic) - { + if (SgInfo->XtalSystem == XS_Triclinic) { for (i = 0; i < 9; i++) { - CBMx->s.R[i] = IniCBMxR[i]; + CBMx->s.R[i] = IniCBMxR[i]; InvCBMx->s.R[i] = IniInvCBMxR[i]; } - if (GenSgI->PointGroup == PG_1) - { + if (GenSgI->PointGroup == PG_1) { for (i = 0; i < 3; i++) { - CBMx->s.T[i] = 0; + CBMx->s.T[i] = 0; InvCBMx->s.T[i] = 0; } return 1; } iGen[0] = -1; - iGen[1] = 0; + iGen[1] = 0; return FixAxes(SgInfo, GenSgI, iGen, CBMx, InvCBMx, NULL, 0); } - if (SgInfo->XtalSystem == XS_Monoclinic) - { - int iCCs, BufRMx[9]; - int RMxCCs_Buf[9], RMxCCn_Buf[9], InvRMxCCn_Buf[9], RotLTrV[3]; - const int *RMxAA, *RMxCCs, *RMxCCn, *InvRMxCCn, *TrV; - T_RTMx BufCBMx, BufInvCBMx; + if (SgInfo->XtalSystem == XS_Monoclinic) { + int iCCs, BufRMx[9]; + int RMxCCs_Buf[9], RMxCCn_Buf[9], InvRMxCCn_Buf[9], RotLTrV[3]; + const int *RMxAA, *RMxCCs, *RMxCCn, *InvRMxCCn, *TrV; + T_RTMx BufCBMx, BufInvCBMx; if (NewLI->nTrVector != 1 && NewLI->nTrVector != 2) goto ReturnError; for (i = 0; i < 9; i++) { - BufCBMx.s.R[i] = IniCBMxR[i]; + BufCBMx.s.R[i] = IniCBMxR[i]; BufInvCBMx.s.R[i] = IniInvCBMxR[i]; } - i = AlignUniqueAxis(SgInfo, GenSgI, - BufCBMx.s.R, BufInvCBMx.s.R, &RMxAA); + i = AlignUniqueAxis(SgInfo, GenSgI, + BufCBMx.s.R, BufInvCBMx.s.R, &RMxAA); if (i != 1) return i; @@ -802,39 +812,39 @@ static int CompleteCBMx(const T_SgInfo *SgInfo, const T_LatticeInfo *NewLI, RMxCCn_Buf[i] = RMx_3_001[i]; } - switch (GenSgI->ListRotMxInfo[1].RefAxis) - { - case 'z': break; - case 'x': RotateRotMx(RMxCCs_Buf, RMx_3_111, RMx_3i111); - RotateRotMx(RMxCCn_Buf, RMx_3_111, RMx_3i111); - break; - case 'y': RotateRotMx(RMxCCs_Buf, RMx_3i111, RMx_3_111); - RotateRotMx(RMxCCn_Buf, RMx_3i111, RMx_3_111); - break; - default: - goto ReturnError; + switch (GenSgI->ListRotMxInfo[1].RefAxis) { + case 'z': + break; + case 'x': + RotateRotMx(RMxCCs_Buf, RMx_3_111, RMx_3i111); + RotateRotMx(RMxCCn_Buf, RMx_3_111, RMx_3i111); + break; + case 'y': + RotateRotMx(RMxCCs_Buf, RMx_3i111, RMx_3_111); + RotateRotMx(RMxCCn_Buf, RMx_3i111, RMx_3_111); + break; + default: + goto ReturnError; } InverseRotMx(RMxCCn_Buf, InvRMxCCn_Buf); - i = 0; - iGen[i++] = 1; - if (GenSgI->PointGroup == PG_2_m) iGen[i++] = -1; - iGen[i ] = 0; + i = 0; + iGen[i++] = 1; + if (GenSgI->PointGroup == PG_2_m) + iGen[i++] = -1; + iGen[i] = 0; RMxCCs = RMx_1_000; - for (iCCs = 0; iCCs < 2; iCCs++, RMxCCs = RMxCCs_Buf) - { + for (iCCs = 0; iCCs < 2; iCCs++, RMxCCs = RMxCCs_Buf) { RMxCCn = InvRMxCCn = RMx_1_000; - for (;;) - { - if (NewLI->nTrVector == 2) - { - RotMx_t_Vector(RotLTrV, RMxAA, &NewLI->TrVector[3], STBF); - RotMx_t_Vector(BufRMx, RMxCCn, RotLTrV, STBF); - RotMx_t_Vector(RotLTrV, RMxCCs, BufRMx, STBF); + for (;;) { + if (NewLI->nTrVector == 2) { + RotMx_t_Vector(RotLTrV, RMxAA, &NewLI->TrVector[3], STBF); + RotMx_t_Vector(BufRMx, RMxCCn, RotLTrV, STBF); + RotMx_t_Vector(RotLTrV, RMxCCs, BufRMx, STBF); TrV = &GenSgI->LatticeInfo->TrVector[3]; @@ -843,26 +853,27 @@ static int CompleteCBMx(const T_SgInfo *SgInfo, const T_LatticeInfo *NewLI, break; } - if (NewLI->nTrVector == 1 || i == 3) - { - RotMxMultiply(BufRMx, RMxCCn, BufCBMx.s.R); + if (NewLI->nTrVector == 1 || i == 3) { + RotMxMultiply(BufRMx, RMxCCn, BufCBMx.s.R); RotMxMultiply(CBMx->s.R, RMxCCs, BufRMx); - RotMxMultiply(BufRMx, BufInvCBMx.s.R, InvRMxCCn); - RotMxMultiply(InvCBMx->s.R, BufRMx, RMxCCs); + RotMxMultiply(BufRMx, BufInvCBMx.s.R, InvRMxCCn); + RotMxMultiply(InvCBMx->s.R, BufRMx, RMxCCs); - i = FixAxes(SgInfo, GenSgI, iGen, CBMx, InvCBMx, NULL, 0); + i = FixAxes(SgInfo, GenSgI, iGen, CBMx, InvCBMx, NULL, 0); if (i != 0) return i; } - if (RMxCCn == RMx_1_000) { - RMxCCn = RMxCCn_Buf; InvRMxCCn = InvRMxCCn_Buf; } - else if (RMxCCn == RMxCCn_Buf) { - RMxCCn = InvRMxCCn_Buf; InvRMxCCn = RMxCCn_Buf; } - else { - RMxCCn = NULL; - break; + if (RMxCCn == RMx_1_000) { + RMxCCn = RMxCCn_Buf; + InvRMxCCn = InvRMxCCn_Buf; + } else if (RMxCCn == RMxCCn_Buf) { + RMxCCn = InvRMxCCn_Buf; + InvRMxCCn = RMxCCn_Buf; + } else { + RMxCCn = NULL; + break; } } } @@ -871,67 +882,59 @@ static int CompleteCBMx(const T_SgInfo *SgInfo, const T_LatticeInfo *NewLI, } for (i = 0; i < 9; i++) { - CBMx->s.R[i] = IniCBMxR[i]; + CBMx->s.R[i] = IniCBMxR[i]; InvCBMx->s.R[i] = IniInvCBMxR[i]; } - if (SgInfo->XtalSystem == XS_Orthorhombic) - { - int iNextBasis; - int BufCBMxR[9], BufInvCBMxR[9]; - int NLTrV_Buf1[3], NLTrV_Buf2[3]; - const int *NLTrV, *GLTrV; + if (SgInfo->XtalSystem == XS_Orthorhombic) { + int iNextBasis; + int BufCBMxR[9], BufInvCBMxR[9]; + int NLTrV_Buf1[3], NLTrV_Buf2[3]; + const int *NLTrV, *GLTrV; if ((GenSgI->LatticeInfo->Code == 'I') != (NewLI->Code == 'I')) return 0; - if ( NewLI->Code == 'A' - || NewLI->Code == 'B' - || NewLI->Code == 'C') { - NLTrV = &NewLI->TrVector[3]; - GLTrV = &GenSgI->LatticeInfo->TrVector[3]; } - else { + if (NewLI->Code == 'A' || NewLI->Code == 'B' || NewLI->Code == 'C') { + NLTrV = &NewLI->TrVector[3]; + GLTrV = &GenSgI->LatticeInfo->TrVector[3]; + } else { NLTrV = NULL; - GLTrV = NULL; } - i = 0; - iGen[i++] = 1; - iGen[i++] = 2; - if (GenSgI->PointGroup == PG_mmm) iGen[i++] = -1; - iGen[i ] = 0; + GLTrV = NULL; + } + i = 0; + iGen[i++] = 1; + iGen[i++] = 2; + if (GenSgI->PointGroup == PG_mmm) + iGen[i++] = -1; + iGen[i] = 0; - for (iNextBasis = 0; iNextBasis < 6; iNextBasis++) - { - if (iNextBasis % 2) - { - RotMxMultiply( BufCBMxR, RMx_2_110, CBMx->s.R); + for (iNextBasis = 0; iNextBasis < 6; iNextBasis++) { + if (iNextBasis % 2) { + RotMxMultiply(BufCBMxR, RMx_2_110, CBMx->s.R); RotMxMultiply(BufInvCBMxR, InvCBMx->s.R, RMx_2_110); for (i = 0; i < 9; i++) { - CBMx->s.R[i] = BufCBMxR[i]; + CBMx->s.R[i] = BufCBMxR[i]; InvCBMx->s.R[i] = BufInvCBMxR[i]; } - } - else if (iNextBasis == 2) { - RotMxMultiply( CBMx->s.R, RMx_3_111, IniCBMxR); + } else if (iNextBasis == 2) { + RotMxMultiply(CBMx->s.R, RMx_3_111, IniCBMxR); RotMxMultiply(InvCBMx->s.R, IniInvCBMxR, RMx_3i111); - } - else if (iNextBasis) { - RotMxMultiply( CBMx->s.R, RMx_3i111, IniCBMxR); + } else if (iNextBasis) { + RotMxMultiply(CBMx->s.R, RMx_3i111, IniCBMxR); RotMxMultiply(InvCBMx->s.R, IniInvCBMxR, RMx_3_111); } - if (NLTrV) - { - if (iNextBasis % 2) { + if (NLTrV) { + if (iNextBasis % 2) { RotMx_t_Vector(NLTrV_Buf1, RMx_2_110, NLTrV, STBF); NLTrV = NLTrV_Buf1; - } - else if (iNextBasis == 2) { + } else if (iNextBasis == 2) { RotMx_t_Vector(NLTrV_Buf2, RMx_3_111, &NewLI->TrVector[3], STBF); NLTrV = NLTrV_Buf2; - } - else if (iNextBasis) { + } else if (iNextBasis) { RotMx_t_Vector(NLTrV_Buf2, RMx_3i111, &NewLI->TrVector[3], STBF); NLTrV = NLTrV_Buf2; } @@ -944,151 +947,158 @@ static int CompleteCBMx(const T_SgInfo *SgInfo, const T_LatticeInfo *NewLI, continue; } - i = FixAxes(SgInfo, GenSgI, iGen, CBMx, InvCBMx, NULL, 0); + i = FixAxes(SgInfo, GenSgI, iGen, CBMx, InvCBMx, NULL, 0); if (i != 0) return i; } } - if (SgInfo->XtalSystem == XS_Tetragonal) - { - i = AlignUniqueAxis(SgInfo, GenSgI, CBMx->s.R, InvCBMx->s.R, NULL); + if (SgInfo->XtalSystem == XS_Tetragonal) { + i = AlignUniqueAxis(SgInfo, GenSgI, CBMx->s.R, InvCBMx->s.R, NULL); if (i != 1) return -1; - i = 0; - iGen[i++] = 1; + i = 0; + iGen[i++] = 1; switch (GenSgI->PointGroup) { - case PG_422: - case PG_4mm: - case PG_4b2m: - case PG_4bm2: - case PG_4_mmm: iGen[i++] = 2; + case PG_422: + case PG_4mm: + case PG_4b2m: + case PG_4bm2: + case PG_4_mmm: + iGen[i++] = 2; } switch (GenSgI->PointGroup) { - case PG_4_m: - case PG_4_mmm: iGen[i++] = -1; + case PG_4_m: + case PG_4_mmm: + iGen[i++] = -1; } - iGen[i ] = 0; + iGen[i] = 0; return FixAxes(SgInfo, GenSgI, iGen, CBMx, InvCBMx, NULL, 0); } - if (SgInfo->XtalSystem == XS_Trigonal) - { - i = AlignUniqueAxis(SgInfo, GenSgI, CBMx->s.R, InvCBMx->s.R, NULL); + if (SgInfo->XtalSystem == XS_Trigonal) { + i = AlignUniqueAxis(SgInfo, GenSgI, CBMx->s.R, InvCBMx->s.R, NULL); if (i != 1) return i; - i = 0; + i = 0; switch (GenSgI->PointGroup) { - case PG_3: - case PG_312: - case PG_32: - case PG_3m1: - case PG_3m: iGen[i++] = 1; - break; - case PG_3b: - case PG_3bm1: - case PG_3b1m: - case PG_3bm: iGen[i++] = -3; + case PG_3: + case PG_312: + case PG_32: + case PG_3m1: + case PG_3m: + iGen[i++] = 1; + break; + case PG_3b: + case PG_3bm1: + case PG_3b1m: + case PG_3bm: + iGen[i++] = -3; } switch (GenSgI->PointGroup) { - case PG_321: - case PG_312: - case PG_32: - case PG_3m1: - case PG_31m: - case PG_3m: - case PG_3bm1: - case PG_3b1m: - case PG_3bm: iGen[i++] = 2; + case PG_321: + case PG_312: + case PG_32: + case PG_3m1: + case PG_31m: + case PG_3m: + case PG_3bm1: + case PG_3b1m: + case PG_3bm: + iGen[i++] = 2; } switch (GenSgI->PointGroup) { - case PG_321: - case PG_31m: iGen[i++] = 1; + case PG_321: + case PG_31m: + iGen[i++] = 1; } - iGen[i ] = 0; + iGen[i] = 0; return FixAxes(SgInfo, GenSgI, iGen, CBMx, InvCBMx, NULL, 0); } - if (SgInfo->XtalSystem == XS_Hexagonal) - { - i = AlignUniqueAxis(SgInfo, GenSgI, CBMx->s.R, InvCBMx->s.R, NULL); + if (SgInfo->XtalSystem == XS_Hexagonal) { + i = AlignUniqueAxis(SgInfo, GenSgI, CBMx->s.R, InvCBMx->s.R, NULL); if (i != 1) return -1; - i = 0; + i = 0; switch (GenSgI->PointGroup) { - case PG_6bm2: - case PG_6b2m: iGen[i++] = 2; + case PG_6bm2: + case PG_6b2m: + iGen[i++] = 2; } - iGen[i++] = 1; + iGen[i++] = 1; switch (GenSgI->PointGroup) { - case PG_622: - case PG_6mm: - case PG_6_mmm: iGen[i++] = 2; + case PG_622: + case PG_6mm: + case PG_6_mmm: + iGen[i++] = 2; } switch (GenSgI->PointGroup) { - case PG_6_m: - case PG_6_mmm: iGen[i++] = -1; + case PG_6_m: + case PG_6_mmm: + iGen[i++] = -1; } - iGen[i ] = 0; + iGen[i] = 0; return FixAxes(SgInfo, GenSgI, iGen, CBMx, InvCBMx, NULL, 0); } - if (SgInfo->XtalSystem == XS_Cubic) - { i = 0; - iGen[i++] = 3; - iGen[i++] = 1; - iGen[i++] = 2; - if ( GenSgI->PointGroup == PG_m3b - || GenSgI->PointGroup == PG_m3bm) iGen[i++] = -1; - iGen[i ] = 0; + if (SgInfo->XtalSystem == XS_Cubic) { + i = 0; + iGen[i++] = 3; + iGen[i++] = 1; + iGen[i++] = 2; + if (GenSgI->PointGroup == PG_m3b || GenSgI->PointGroup == PG_m3bm) + iGen[i++] = -1; + iGen[i] = 0; return FixAxes(SgInfo, GenSgI, iGen, CBMx, InvCBMx, NULL, 0); } return 0; - ReturnError: +ReturnError: SetSgError("Internal Error: CompleteCBMx()"); return -1; } -const T_TabSgName *FindReferenceSpaceGroup(T_SgInfo *SgInfo, - T_RTMx *CBMx, T_RTMx *InvCBMx) +const T_TabSgName *FindReferenceSpaceGroup(T_SgInfo * SgInfo, + T_RTMx * CBMx, T_RTMx * InvCBMx) { - int stat, NewPG, SgInfo_CI, OL_SgInfo, OL_GenSgI; - const T_TabSgName *tsgn; - T_SgInfo GenSgI; - T_RTMx GenSgI_ListSeitzMx[5]; - T_RotMxInfo GenSgI_ListRotMxInfo[5]; - int iList, PrevSgNumber; - int FacIniCBMxR; - T_RotMxInfo *lrmxi; - const T_LatticeInfo *NewLI; - int IniCBMxR[9], IniInvCBMxR[9]; + int stat, NewPG, SgInfo_CI, OL_SgInfo, OL_GenSgI; + const T_TabSgName *tsgn; + T_SgInfo GenSgI; + T_RTMx GenSgI_ListSeitzMx[5]; + T_RotMxInfo GenSgI_ListRotMxInfo[5]; + int iList, PrevSgNumber; + int FacIniCBMxR; + T_RotMxInfo *lrmxi; + const T_LatticeInfo *NewLI; + int IniCBMxR[9], IniInvCBMxR[9]; - GenSgI.MaxList = 5; - GenSgI.ListSeitzMx = GenSgI_ListSeitzMx; + GenSgI.MaxList = 5; + GenSgI.ListSeitzMx = GenSgI_ListSeitzMx; GenSgI.ListRotMxInfo = GenSgI_ListRotMxInfo; - FacIniCBMxR = InitialCBMxR(SgInfo, &NewLI, &NewPG, IniCBMxR, IniInvCBMxR); + FacIniCBMxR = + InitialCBMxR(SgInfo, &NewLI, &NewPG, IniCBMxR, IniInvCBMxR); if (FacIniCBMxR < 0) return NULL; - OL_SgInfo = SgInfo->OrderL; + OL_SgInfo = SgInfo->OrderL; if (OL_SgInfo % FacIniCBMxR) goto ReturnError; @@ -1098,8 +1108,7 @@ const T_TabSgName *FindReferenceSpaceGroup(T_SgInfo *SgInfo, PrevSgNumber = 0; - for (tsgn = TabSgName; tsgn->HallSymbol; tsgn++) - { + for (tsgn = TabSgName; tsgn->HallSymbol; tsgn++) { if (tsgn->HallSymbol[1] == 'R') continue; @@ -1132,17 +1141,15 @@ const T_TabSgName *FindReferenceSpaceGroup(T_SgInfo *SgInfo, lrmxi = &GenSgI.ListRotMxInfo[1]; - for (iList = 1; iList < GenSgI.nList; iList++, lrmxi++) - { + for (iList = 1; iList < GenSgI.nList; iList++, lrmxi++) { OL_GenSgI *= abs(lrmxi->Order); - if ( (lrmxi->Order == -1 || lrmxi->Order == -3) + if ((lrmxi->Order == -1 || lrmxi->Order == -3) && GenSgI.Centric == 0 && GenSgI.InversionOffOrigin == 0) goto ReturnError; } - if (OL_GenSgI == OL_SgInfo) - { + if (OL_GenSgI == OL_SgInfo) { if (NewLI->nTrVector != GenSgI.LatticeInfo->nTrVector) goto ReturnError; @@ -1150,12 +1157,11 @@ const T_TabSgName *FindReferenceSpaceGroup(T_SgInfo *SgInfo, #if DEBUG_FindConventionalSetting fprintf(stdout, "%s ?= %s (%d)\n", - SgInfo->HallSymbol, tsgn->HallSymbol, tsgn->SgNumber); + SgInfo->HallSymbol, tsgn->HallSymbol, tsgn->SgNumber); #endif stat = CompleteCBMx(SgInfo, NewLI, &GenSgI, - IniCBMxR, IniInvCBMxR, - CBMx, InvCBMx); + IniCBMxR, IniInvCBMxR, CBMx, InvCBMx); if (stat < 0) return NULL; @@ -1167,7 +1173,7 @@ const T_TabSgName *FindReferenceSpaceGroup(T_SgInfo *SgInfo, SetSgError("Internal Error: Space Group not found"); return NULL; - ReturnError: +ReturnError: SetSgError("Internal Error: FindReferenceSpaceGroup()"); return NULL; diff --git a/sghkl.c b/sghkl.c index db3f2e06..ba04b74e 100644 --- a/sghkl.c +++ b/sghkl.c @@ -10,17 +10,17 @@ static const char *IErr_Inc_SymMx = - "Internal Error: Inconsistent symmetry matrices"; + "Internal Error: Inconsistent symmetry matrices"; -int IsSysAbsent_hkl(const T_SgInfo *SgInfo, +int IsSysAbsent_hkl(const T_SgInfo * SgInfo, int h, int k, int l, int *TH_Restriction) { - int iTrV, nTrV; - const int *TrV; - int iList, mh, mk, ml, hm, km, lm; - int TH, THr, FlagMismatch; - const T_RTMx *lsmx; + int iTrV, nTrV; + const int *TrV; + int iList, mh, mk, ml, hm, km, lm; + int TH, THr, FlagMismatch; + const T_RTMx *lsmx; mh = -h; @@ -31,44 +31,41 @@ int IsSysAbsent_hkl(const T_SgInfo *SgInfo, take care of lattice type and "centric" flag */ THr = -1; - if (TH_Restriction != NULL) *TH_Restriction = THr; + if (TH_Restriction != NULL) + *TH_Restriction = THr; FlagMismatch = 0; nTrV = SgInfo->LatticeInfo->nTrVector; lsmx = SgInfo->ListSeitzMx; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { hm = lsmx->s.R[0] * h + lsmx->s.R[3] * k + lsmx->s.R[6] * l; km = lsmx->s.R[1] * h + lsmx->s.R[4] * k + lsmx->s.R[7] * l; lm = lsmx->s.R[2] * h + lsmx->s.R[5] * k + lsmx->s.R[8] * l; TrV = SgInfo->LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++) - { - TH = (lsmx->s.T[0] + *TrV++) * h; + for (iTrV = 0; iTrV < nTrV; iTrV++) { + TH = (lsmx->s.T[0] + *TrV++) * h; TH += (lsmx->s.T[1] + *TrV++) * k; TH += (lsmx->s.T[2] + *TrV++) * l; - TH %= STBF; if (TH < 0) TH += STBF; + TH %= STBF; + if (TH < 0) + TH += STBF; - if (mh == hm && mk == km && ml == lm) - { + if (mh == hm && mk == km && ml == lm) { if (TH != 0 && SgInfo->Centric == -1) return -(iList + 1 + iTrV * SgInfo->nList); if (THr < 0) THr = TH; else if (THr != TH) - FlagMismatch = 1; /* must be systematic absent */ - /* will check later ... */ - } - else if ( h == hm && k == km && l == lm) - { + FlagMismatch = 1; /* must be systematic absent */ + /* will check later ... */ + } else if (h == hm && k == km && l == lm) { if (TH != 0) - return (iList + 1 + iTrV * SgInfo->nList); - } - else + return (iList + 1 + iTrV * SgInfo->nList); + } else break; } } @@ -76,21 +73,23 @@ int IsSysAbsent_hkl(const T_SgInfo *SgInfo, if (THr >= 0 && FlagMismatch) /* ... consistency check */ SetSgError(IErr_Inc_SymMx); - if (TH_Restriction != NULL) - { - if (SgInfo->Centric == -1) *TH_Restriction = 0; - else *TH_Restriction = THr; + if (TH_Restriction != NULL) { + if (SgInfo->Centric == -1) + *TH_Restriction = 0; + else + *TH_Restriction = THr; } return 0; } -int BuildEq_hkl(const T_SgInfo *SgInfo, T_Eq_hkl *Eq_hkl, int h, int k, int l) +int BuildEq_hkl(const T_SgInfo * SgInfo, T_Eq_hkl * Eq_hkl, int h, int k, + int l) { - int iList, hm, km, lm, i; - T_RTMx *lsmx; - T_Eq_hkl BufEq_hkl; + int iList, hm, km, lm, i; + T_RTMx *lsmx; + T_Eq_hkl BufEq_hkl; if (Eq_hkl == NULL) @@ -103,30 +102,28 @@ int BuildEq_hkl(const T_SgInfo *SgInfo, T_Eq_hkl *Eq_hkl, int h, int k, int l) Eq_hkl->l[0] = l; Eq_hkl->TH[0] = 0; - if (! (h || k || l)) - return Eq_hkl->M; /* this is 000 */ + if (!(h || k || l)) + return Eq_hkl->M; /* this is 000 */ Eq_hkl->M++; /* check list of symmetry operations */ - lsmx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ + lsmx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ - for (iList = 1; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 1; iList < SgInfo->nList; iList++, lsmx++) { hm = lsmx->s.R[0] * h + lsmx->s.R[3] * k + lsmx->s.R[6] * l; km = lsmx->s.R[1] * h + lsmx->s.R[4] * k + lsmx->s.R[7] * l; lm = lsmx->s.R[2] * h + lsmx->s.R[5] * k + lsmx->s.R[8] * l; - for (i = 0; i < Eq_hkl->N; i++) - { - if ( ( hm == Eq_hkl->h[i] && km == Eq_hkl->k[i] && lm == Eq_hkl->l[i]) - || (-hm == Eq_hkl->h[i] && -km == Eq_hkl->k[i] && -lm == Eq_hkl->l[i])) + for (i = 0; i < Eq_hkl->N; i++) { + if ((hm == Eq_hkl->h[i] && km == Eq_hkl->k[i] && lm == Eq_hkl->l[i]) + || (-hm == Eq_hkl->h[i] && -km == Eq_hkl->k[i] + && -lm == Eq_hkl->l[i])) break; } - if (i == Eq_hkl->N) - { + if (i == Eq_hkl->N) { if (Eq_hkl->N >= 24) { SetSgError(IErr_Inc_SymMx); return 0; @@ -136,18 +133,17 @@ int BuildEq_hkl(const T_SgInfo *SgInfo, T_Eq_hkl *Eq_hkl, int h, int k, int l) Eq_hkl->k[i] = km; Eq_hkl->l[i] = lm; - Eq_hkl->TH[i] = ( lsmx->s.T[0] * h - + lsmx->s.T[1] * k - + lsmx->s.T[2] * l) % STBF; + Eq_hkl->TH[i] = (lsmx->s.T[0] * h + + lsmx->s.T[1] * k + lsmx->s.T[2] * l) % STBF; if (Eq_hkl->TH[i] < 0) - Eq_hkl->TH[i] += STBF; + Eq_hkl->TH[i] += STBF; Eq_hkl->M += 2; Eq_hkl->N++; } } - if (SgInfo->nList % Eq_hkl->N) /* another error trap */ { + if (SgInfo->nList % Eq_hkl->N) { /* another error trap */ SetSgError(IErr_Inc_SymMx); return 0; } @@ -156,11 +152,11 @@ int BuildEq_hkl(const T_SgInfo *SgInfo, T_Eq_hkl *Eq_hkl, int h, int k, int l) } -int AreSymEquivalent_hkl(const T_SgInfo *SgInfo, int h1, int k1, int l1, - int h2, int k2, int l2) +int AreSymEquivalent_hkl(const T_SgInfo * SgInfo, int h1, int k1, int l1, + int h2, int k2, int l2) { - int iList, mh2, mk2, ml2, hm, km, lm; - T_RTMx *lsmx; + int iList, mh2, mk2, ml2, hm, km, lm; + T_RTMx *lsmx; mh2 = -h2; @@ -171,14 +167,13 @@ int AreSymEquivalent_hkl(const T_SgInfo *SgInfo, int h1, int k1, int l1, lsmx = SgInfo->ListSeitzMx; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { hm = lsmx->s.R[0] * h1 + lsmx->s.R[3] * k1 + lsmx->s.R[6] * l1; km = lsmx->s.R[1] * h1 + lsmx->s.R[4] * k1 + lsmx->s.R[7] * l1; lm = lsmx->s.R[2] * h1 + lsmx->s.R[5] * k1 + lsmx->s.R[8] * l1; - if ( h2 == hm && k2 == km && l2 == lm) - return (iList + 1); + if (h2 == hm && k2 == km && l2 == lm) + return (iList + 1); else if (mh2 == hm && mk2 == km && ml2 == lm) return -(iList + 1); @@ -188,90 +183,83 @@ int AreSymEquivalent_hkl(const T_SgInfo *SgInfo, int h1, int k1, int l1, } -void SetListMin_hkl(const T_SgInfo *SgInfo, int Maxk, int Maxl, - int *Minh, int *Mink, int *Minl) +void SetListMin_hkl(const T_SgInfo * SgInfo, int Maxk, int Maxl, + int *Minh, int *Mink, int *Minl) { *Minh = 0; - switch(SgInfo->XtalSystem) - { - case XS_Triclinic: + switch (SgInfo->XtalSystem) { + case XS_Triclinic: + *Mink = -Maxk; + *Minl = -Maxl; + break; + case XS_Monoclinic: + if (SgInfo->UniqueRefAxis == 'z') { *Mink = -Maxk; - *Minl = -Maxl; - break; - case XS_Monoclinic: - if (SgInfo->UniqueRefAxis == 'z') - { - *Mink = -Maxk; - *Minl = 0; - } - else - { - *Mink = 0; - *Minl = -Maxl; - } - break; - default: - if (SgInfo->XtalSystem == XS_Trigonal && SgInfo->UniqueDirCode == '*') - *Mink = -Maxk; - else - *Mink = 0; *Minl = 0; - break; + } else { + *Mink = 0; + *Minl = -Maxl; + } + break; + default: + if (SgInfo->XtalSystem == XS_Trigonal && SgInfo->UniqueDirCode == '*') + *Mink = -Maxk; + else + *Mink = 0; + *Minl = 0; + break; } } -int IsSuppressed_hkl(const T_SgInfo *SgInfo, int Minh, int Mink, int Minl, - int Maxk, int Maxl, - int h, int k, int l) +int IsSuppressed_hkl(const T_SgInfo * SgInfo, int Minh, int Mink, int Minl, + int Maxk, int Maxl, int h, int k, int l) { - int iList, mate, hm, km, lm; - T_RTMx *lsmx; + int iList, mate, hm, km, lm; + T_RTMx *lsmx; /* check for Friedel mate first */ hm = -h, km = -k, lm = -l; - if ( (Minh <= hm && hm <= h) + if ((Minh <= hm && hm <= h) && (Mink <= km && km <= Maxk) - && (Minl <= lm && lm <= Maxl)){ - if (hm < h) return -1; - else /* if (h == 0) */ - if (km < k) return -1; - else if (k == 0) - if (lm < l) return -1; + && (Minl <= lm && lm <= Maxl)) { + if (hm < h) + return -1; + else /* if (h == 0) */ if (km < k) + return -1; + else if (k == 0) + if (lm < l) + return -1; } - lsmx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ + lsmx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ - for (iList = 1; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 1; iList < SgInfo->nList; iList++, lsmx++) { /* check if equivalent hm, km, lm are inside loop range ... */ hm = lsmx->s.R[0] * h + lsmx->s.R[3] * k + lsmx->s.R[6] * l; km = lsmx->s.R[1] * h + lsmx->s.R[4] * k + lsmx->s.R[7] * l; lm = lsmx->s.R[2] * h + lsmx->s.R[5] * k + lsmx->s.R[8] * l; - for (mate = 0; mate < 2; mate++) - { - if (mate) hm = -hm, km = -km, lm = -lm; /* ... or friedel mate */ + for (mate = 0; mate < 2; mate++) { + if (mate) + hm = -hm, km = -km, lm = -lm; /* ... or friedel mate */ - if ( Minh <= hm && hm <= h - && Mink <= km && km <= Maxk - && Minl <= lm && lm <= Maxl) - { + if (Minh <= hm && hm <= h + && Mink <= km && km <= Maxk && Minl <= lm && lm <= Maxl) { /* ... and were processed before */ if (hm < h) return (mate ? -(iList + 1) : iList + 1); - else /* if (hm == h) */ - if (km < k) + else /* if (hm == h) */ if (km < k) + return (mate ? -(iList + 1) : iList + 1); + else if (km == k) + if (lm < l) return (mate ? -(iList + 1) : iList + 1); - else if (km == k) - if (lm < l) - return (mate ? -(iList + 1) : iList + 1); } } } diff --git a/sginfo.c b/sginfo.c index 1c6f02e4..3e638576 100644 --- a/sginfo.c +++ b/sginfo.c @@ -13,8 +13,8 @@ */ #if defined(__THINK__) || defined(__MWERKS__) #include -#define CONSOLE_LINES 36 /* number of lines to use for console */ -#define CONSOLE_COLUMNS 90 /* number of columns to use for console */ +#define CONSOLE_LINES 36 /* number of lines to use for console */ +#define CONSOLE_COLUMNS 90 /* number of columns to use for console */ #ifdef __MWERKS__ #include #endif @@ -31,11 +31,11 @@ #if USE_GS_SI -static int PrimitiveRotMx(const int *CCMx_LP, int *RotMx, const int *CCMx_PL, - int deterCCMx_LP) +static int PrimitiveRotMx(const int *CCMx_LP, int *RotMx, + const int *CCMx_PL, int deterCCMx_LP) { - int i; - int BufMx[9]; + int i; + int BufMx[9]; /* Mp = Tlp . Mz . Tpl */ @@ -43,8 +43,7 @@ static int PrimitiveRotMx(const int *CCMx_LP, int *RotMx, const int *CCMx_PL, RotMxMultiply(BufMx, RotMx, CCMx_PL); RotMxMultiply(RotMx, CCMx_LP, BufMx); - for (i = 0; i < 9; i++) - { + for (i = 0; i < 9; i++) { if (RotMx[i] % deterCCMx_LP) { SetSgError("Internal Error: PrimitiveRotMx()"); return -1; @@ -58,50 +57,48 @@ static int PrimitiveRotMx(const int *CCMx_LP, int *RotMx, const int *CCMx_PL, } -static int Find_si(T_SgInfo *SgInfo) +static int Find_si(T_SgInfo * SgInfo) { - static const int Tab_si_Vector[] = - { - 1, 0, 0, 0, /* h */ - 0, 1, 0, 1, /* k */ - 0, 0, 1, 2, /* l */ - 1, 1, 0, 0, /* h+k */ - 1, -1, 0, 0, /* h-k */ - 0, 1, 1, 1, /* k+l */ - 0, 1, -1, 1, /* k-l */ - 1, 0, 1, 1, /* h+l */ - 1, 0, -1, 1, /* h-l */ - 1, 1, 1, 0, /* h+k+l */ - 1, 1, -1, 0, /* h+k-l */ - 1, -1, 1, 0, /* h-k+l */ - -1, 1, 1, 0, /* -h+k+l */ - 2, 1, -1, 0, /* 2h+k-l */ - 2, -1, 1, 0, /* 2h-k+l */ - -1, 2, 1, 0, /* -h+2k+l */ - 1, 2, -1, 0, /* h+2k-l */ - -1, 1, 2, 0, /* -h+k+2l */ - 1, -1, 2, 0 /* h-k+2l */ - }; + static const int Tab_si_Vector[] = { + 1, 0, 0, 0, /* h */ + 0, 1, 0, 1, /* k */ + 0, 0, 1, 2, /* l */ + 1, 1, 0, 0, /* h+k */ + 1, -1, 0, 0, /* h-k */ + 0, 1, 1, 1, /* k+l */ + 0, 1, -1, 1, /* k-l */ + 1, 0, 1, 1, /* h+l */ + 1, 0, -1, 1, /* h-l */ + 1, 1, 1, 0, /* h+k+l */ + 1, 1, -1, 0, /* h+k-l */ + 1, -1, 1, 0, /* h-k+l */ + -1, 1, 1, 0, /* -h+k+l */ + 2, 1, -1, 0, /* 2h+k-l */ + 2, -1, 1, 0, /* 2h-k+l */ + -1, 2, 1, 0, /* -h+2k+l */ + 1, 2, -1, 0, /* h+2k-l */ + -1, 1, 2, 0, /* -h+k+2l */ + 1, -1, 2, 0 /* h-k+2l */ + }; static int nTab_si_Vector - = sizeof Tab_si_Vector / sizeof (*Tab_si_Vector) / 4; + = sizeof Tab_si_Vector / sizeof(*Tab_si_Vector) / 4; - int deterCCMx_LP, CCMx_PL[9]; - int i, itabsiv; - int nLoopInv, iLoopInv, n_si_v, i_si_v; - int n, m, l; - int IsFine; - int item[3]; - int R_I[9], si_Buf[9]; - int iList; - T_RTMx *lsmx; - const int *tabsiv; + int deterCCMx_LP, CCMx_PL[9]; + int i, itabsiv; + int nLoopInv, iLoopInv, n_si_v, i_si_v; + int n, m, l; + int IsFine; + int item[3]; + int R_I[9], si_Buf[9]; + int iList; + T_RTMx *lsmx; + const int *tabsiv; - if (SgInfo->LatticeInfo->Code != 'P') - { + if (SgInfo->LatticeInfo->Code != 'P') { deterCCMx_LP = deterRotMx(SgInfo->CCMx_LP); - InverseRotMx(SgInfo->CCMx_LP, CCMx_PL); + InverseRotMx(SgInfo->CCMx_LP, CCMx_PL); if (deterCCMx_LP < 1) goto ReturnError; @@ -114,48 +111,43 @@ static int Find_si(T_SgInfo *SgInfo) for (i = 0; i < 9; i++) SgInfo->si_Vector[i] = 0; - for (i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { SgInfo->si_Modulus[i] = 1; item[i] = 1; } tabsiv = Tab_si_Vector; - for (itabsiv = 0; itabsiv < nTab_si_Vector; itabsiv++, tabsiv += 4) - { + for (itabsiv = 0; itabsiv < nTab_si_Vector; itabsiv++, tabsiv += 4) { IsFine = 1; m = -1; - for (iList = 0; IsFine && iList < SgInfo->nList; iList++) - { + for (iList = 0; IsFine && iList < SgInfo->nList; iList++) { lsmx = &SgInfo->ListSeitzMx[iList]; - for (iLoopInv = 0; IsFine && iLoopInv < nLoopInv; iLoopInv++) - { + for (iLoopInv = 0; IsFine && iLoopInv < nLoopInv; iLoopInv++) { if (iLoopInv == 0) - for (i = 0; i < 9; i++) - { - if (i % 4) R_I[i] = lsmx->s.R[i]; - else R_I[i] = lsmx->s.R[i] - 1; - } - else - for (i = 0; i < 9; i++) - { - if (i % 4) R_I[i] = -lsmx->s.R[i]; - else R_I[i] = -lsmx->s.R[i] - 1; + for (i = 0; i < 9; i++) { + if (i % 4) + R_I[i] = lsmx->s.R[i]; + else + R_I[i] = lsmx->s.R[i] - 1; + } else + for (i = 0; i < 9; i++) { + if (i % 4) + R_I[i] = -lsmx->s.R[i]; + else + R_I[i] = -lsmx->s.R[i] - 1; } - if (SgInfo->LatticeInfo->Code != 'P') - { + if (SgInfo->LatticeInfo->Code != 'P') { if (PrimitiveRotMx(SgInfo->CCMx_LP, R_I, CCMx_PL, - deterCCMx_LP) < 0) + deterCCMx_LP) < 0) return -1; } - for (i = 0; IsFine && i < 3; i++) - { - n = tabsiv[0] * R_I[i * 3 + 0]; + for (i = 0; IsFine && i < 3; i++) { + n = tabsiv[0] * R_I[i * 3 + 0]; n += tabsiv[1] * R_I[i * 3 + 1]; n += tabsiv[2] * R_I[i * 3 + 2]; n = abs(n); @@ -170,26 +162,28 @@ static int Find_si(T_SgInfo *SgInfo) } } - if (IsFine) - { + if (IsFine) { #if DEBUG_Find_si fprintf(stdout, "H-Kt %2d %2d %2d %d\n", - tabsiv[0], tabsiv[1], tabsiv[2], m); + tabsiv[0], tabsiv[1], tabsiv[2], m); #endif l = tabsiv[3]; - while (item[l] > 1) /* just "if", see break's */ - { - if (m == item[l]) break; + while (item[l] > 1) { /* just "if", see break's */ + if (m == item[l]) + break; - if (m == 3 && ( SgInfo->XtalSystem != XS_Trigonal - || SgInfo->UniqueDirCode != '=')) break; + if (m == 3 && (SgInfo->XtalSystem != XS_Trigonal + || SgInfo->UniqueDirCode != '=')) + break; - if (m == 4 && ( SgInfo->XtalSystem == XS_Triclinic - || SgInfo->XtalSystem == XS_Monoclinic)) break; + if (m == 4 && (SgInfo->XtalSystem == XS_Triclinic + || SgInfo->XtalSystem == XS_Monoclinic)) + break; - if (m == 2) break; + if (m == 2) + break; /* if (m > 1 || m != 4) break; */ @@ -198,8 +192,7 @@ static int Find_si(T_SgInfo *SgInfo) break; } - if (item[l] == 1) - { + if (item[l] == 1) { if (itabsiv > 12) n_si_v = 0; @@ -219,36 +212,31 @@ static int Find_si(T_SgInfo *SgInfo) fprintf(stdout, "H-Kt\n"); #endif - if (SgInfo->LatticeInfo->Code != 'P') - { + if (SgInfo->LatticeInfo->Code != 'P') { #if DEBUG_Find_si for (i = 0; i < n_si_v; i++) fprintf(stdout, "H-Kp %2d %2d %2d %d\n", - SgInfo->si_Vector[i * 3 + 0], - SgInfo->si_Vector[i * 3 + 1], - SgInfo->si_Vector[i * 3 + 2], - SgInfo->si_Modulus[i]); + SgInfo->si_Vector[i * 3 + 0], + SgInfo->si_Vector[i * 3 + 1], + SgInfo->si_Vector[i * 3 + 2], SgInfo->si_Modulus[i]); fprintf(stdout, "H-Kp\n"); #endif - for (i_si_v = 0; i_si_v < n_si_v; i_si_v++) - { - for (i = 0; i < 3; i++) - { + for (i_si_v = 0; i_si_v < n_si_v; i_si_v++) { + for (i = 0; i < 3; i++) { si_Buf[i_si_v * 3 + i] - = SgInfo->si_Vector[i_si_v * 3 + 0] * CCMx_PL[i * 3 + 0] + = SgInfo->si_Vector[i_si_v * 3 + 0] * CCMx_PL[i * 3 + 0] + SgInfo->si_Vector[i_si_v * 3 + 1] * CCMx_PL[i * 3 + 1] + SgInfo->si_Vector[i_si_v * 3 + 2] * CCMx_PL[i * 3 + 2]; } } - for (i = 0; i < i_si_v * 3; i++) - { - if (si_Buf[i] % deterCCMx_LP) - { - n = i / 3; n *= 3; + for (i = 0; i < i_si_v * 3; i++) { + if (si_Buf[i] % deterCCMx_LP) { + n = i / 3; + n *= 3; fprintf(stdout, " %3d %3d %3d\n", - si_Buf[n + 0], si_Buf[n + 1], si_Buf[n + 2]); + si_Buf[n + 0], si_Buf[n + 1], si_Buf[n + 2]); goto ReturnError; } @@ -259,26 +247,26 @@ static int Find_si(T_SgInfo *SgInfo) SgInfo->n_si_Vector = n_si_v; return n_si_v; - ReturnError: +ReturnError: SetSgError("Internal Error: Find_si()"); return -1; } -static int Try_GS_si(T_SgInfo *SgInfo) +static int Try_GS_si(T_SgInfo * SgInfo) { - int h, k, l, iList; - int Maxh, Maxk, Maxl; - int Minh, Mink, Minl; - int nTestField, *TestField; - int nProperty, *Property, *pp; - int IsFine, would_be, is; + int h, k, l, iList; + int Maxh, Maxk, Maxl; + int Minh, Mink, Minl; + int nTestField, *TestField; + int nProperty, *Property, *pp; + int IsFine, would_be, is; SgInfo->n_si_Vector = -1; - nTestField = 12 * 12 * 12; + nTestField = 12 * 12 * 12; AppMalloc(TestField, nTestField); if (TestField == NULL) { SetSgError("Not enough core"); @@ -290,9 +278,9 @@ static int Try_GS_si(T_SgInfo *SgInfo) Maxh = Maxk = Maxl = 7; SetListMin_hkl(SgInfo, Maxk, Maxl, &Minh, &Mink, &Minl); - nProperty = (Maxh - Minh + 1) - * (Maxk - Mink + 1) - * (Maxl - Minl + 1); + nProperty = (Maxh - Minh + 1) + * (Maxk - Mink + 1) + * (Maxl - Minl + 1); AppMalloc(Property, nProperty); if (Property == NULL) { @@ -303,44 +291,38 @@ static int Try_GS_si(T_SgInfo *SgInfo) pp = Property; for (h = Minh; h <= Maxh; h++) - for (k = Mink; k <= Maxk; k++) - for (l = Minl; l <= Maxl; l++) - { - iList = IsSysAbsent_hkl(SgInfo, h, k, l, NULL); - if (SgError != NULL) - { - AppFree(Property, nProperty); - AppFree(TestField, nTestField); - return -1; - } + for (k = Mink; k <= Maxk; k++) + for (l = Minl; l <= Maxl; l++) { + iList = IsSysAbsent_hkl(SgInfo, h, k, l, NULL); + if (SgError != NULL) { + AppFree(Property, nProperty); + AppFree(TestField, nTestField); + return -1; + } - if (iList == 0) - *pp++ = Verify_si(h, k, l, TestField); - else - *pp++ = -1; - } + if (iList == 0) + *pp++ = Verify_si(h, k, l, TestField); + else + *pp++ = -1; + } - if (Find_si(SgInfo) >= 0) - { + if (Find_si(SgInfo) >= 0) { IsFine = 1; pp = Property; for (h = Minh; IsFine && h <= Maxh; h++) - for (k = Mink; IsFine && k <= Maxk; k++) - for (l = Minl; IsFine && l <= Maxl; l++) - { - is = *pp++; + for (k = Mink; IsFine && k <= Maxk; k++) + for (l = Minl; IsFine && l <= Maxl; l++) { + is = *pp++; - if (is >= 0) - { - would_be = Is_si(SgInfo, h, k, l); - if (is != would_be) - IsFine = 0; - } - } + if (is >= 0) { + would_be = Is_si(SgInfo, h, k, l); + if (is != would_be) + IsFine = 0; + } + } - if (IsFine) - { + if (IsFine) { AppFree(Property, nProperty); AppFree(TestField, nTestField); return 0; @@ -355,7 +337,7 @@ static int Try_GS_si(T_SgInfo *SgInfo) return -1; } -#endif /* USE_GS_SI */ +#endif /* USE_GS_SI */ static const char *progn = "sginfo"; @@ -380,10 +362,10 @@ static void PrintClearSgError(int ClearError, int CertainSgError) if (CertainSgError && SgError == NULL) SetSgError("Internal Error: SgError not set but should be"); - if (SgError) - { + if (SgError) { fprintf(stdout, "%s: %s\n", progn, SgError); - if (ClearError == 0) exit(1); + if (ClearError == 0) + exit(1); SgError = NULL; } } @@ -391,72 +373,75 @@ static void PrintClearSgError(int ClearError, int CertainSgError) static int str_icmp(const char *s, const char *t) { - char cs, ct; + char cs, ct; - while (*s || *t) - { cs = toupper(*s++); + while (*s || *t) { + cs = toupper(*s++); ct = toupper(*t++); - if (cs < ct) return -1; - if (cs > ct) return 1; + if (cs < ct) + return -1; + if (cs > ct) + return 1; } return 0; } -static int str_ibegin(const char *s1, const char *s2) /* string ignore-case */ -{ /* begin */ - char u1, u2; +static int str_ibegin(const char *s1, const char *s2) +{ /* string ignore-case *//* begin */ + char u1, u2; - while (*s1 && *s2) - { + while (*s1 && *s2) { u1 = toupper(*s1++); u2 = toupper(*s2++); - if (u1 < u2) return -1; - else if (u1 > u2) return 1; + if (u1 < u2) + return -1; + else if (u1 > u2) + return 1; } - if (*s2) return -1; + if (*s2) + return -1; return 0; } -static const char *LegendTabSgName[] = - { - "", - " Extensions", - " ----------", - " Monoclinic unique axis b unique axis c unique axis a", - " abc c-ba abc ba-c abc -acb", - " ------------ ------------ ------------", - " cell choice 1 :b1 :-b1 :c1 :-c1 :a1 :-a1", - " 2 :b2 :-b2 :c2 :-c2 :a2 :-a2", - " 3 :b3 :-b3 :c3 :-c3 :a3 :-a3", - "", - " Orthorhombic :ba-c change of basis abc -> ba-c", - " :1 origin choice 1", - " :2ba-c origin choice 2, change of basis abc -> ba-c", - "", - " Tetragonal :1 origin choice 1", - " Cubic :2 origin choice 2", - "", - " Trigonal :H hexagonal axes", - " :R rhombohedral axes", - "", - " Number Schoenflies Hermann-Mauguin Hall", - " ------ ----------- --------------- ----", - NULL, - }; +static const char *LegendTabSgName[] = { + "", + " Extensions", + " ----------", + " Monoclinic unique axis b unique axis c unique axis a", + " abc c-ba abc ba-c abc -acb", + " ------------ ------------ ------------", + " cell choice 1 :b1 :-b1 :c1 :-c1 :a1 :-a1", + " 2 :b2 :-b2 :c2 :-c2 :a2 :-a2", + " 3 :b3 :-b3 :c3 :-c3 :a3 :-a3", + "", + " Orthorhombic :ba-c change of basis abc -> ba-c", + " :1 origin choice 1", + " :2ba-c origin choice 2, change of basis abc -> ba-c", + "", + " Tetragonal :1 origin choice 1", + " Cubic :2 origin choice 2", + "", + " Trigonal :H hexagonal axes", + " :R rhombohedral axes", + "", + " Number Schoenflies Hermann-Mauguin Hall", + " ------ ----------- --------------- ----", + NULL, +}; -static void ListTabSgName(int WantedSgNumber, int VolLetter, FILE *fpout) +static void ListTabSgName(int WantedSgNumber, int VolLetter, FILE * fpout) { - int i; - const char *sgl, *ext, **ltsgn; - const T_TabSgName *tsgn, *show, *show_later; + int i; + const char *sgl, *ext, **ltsgn; + const T_TabSgName *tsgn, *show, *show_later; if (WantedSgNumber == -1) for (ltsgn = LegendTabSgName; *ltsgn; ltsgn++) - fprintf(fpout, "%s\n", *ltsgn); + fprintf(fpout, "%s\n", *ltsgn); if (VolLetter == '1') VolLetter = 'I'; @@ -465,69 +450,50 @@ static void ListTabSgName(int WantedSgNumber, int VolLetter, FILE *fpout) show = show_later = NULL; - for (tsgn = TabSgName; tsgn->HallSymbol; tsgn++) - { - if ( WantedSgNumber == -1 - || WantedSgNumber == tsgn->SgNumber) - { - if (tsgn->SgNumber >= 3 && tsgn->SgNumber < 16) - { - if (VolLetter == 'I') - { - ext = tsgn->Extension; + for (tsgn = TabSgName; tsgn->HallSymbol; tsgn++) { + if (WantedSgNumber == -1 || WantedSgNumber == tsgn->SgNumber) { + if (tsgn->SgNumber >= 3 && tsgn->SgNumber < 16) { + if (VolLetter == 'I') { + ext = tsgn->Extension; if (*ext == '-') - ext++; + ext++; - if ( tsgn->Extension[0] == 'b' - && ( tsgn->Extension[1] == '\0' - || tsgn->Extension[1] == '1')) + if (tsgn->Extension[0] == 'b' + && (tsgn->Extension[1] == '\0' || tsgn->Extension[1] == '1')) show_later = tsgn; - else if ( ext[0] == 'c') - { + else if (ext[0] == 'c') { if (ext[1] == '\0') show = tsgn; - else - { + else { i = 0; for (sgl = tsgn->SgLabels; *sgl; sgl++) - if (*sgl == '=') i++; + if (*sgl == '=') + i++; if (i == 2) show = tsgn; } } - } - else if (VolLetter == 'A') - { - if ( tsgn->Extension[0] != '-' - && tsgn->Extension[0] != 'a') + } else if (VolLetter == 'A') { + if (tsgn->Extension[0] != '-' && tsgn->Extension[0] != 'a') show = tsgn; - } - else + } else show = tsgn; - } - else if ( tsgn->Extension[0] == 'H' - && VolLetter == 'I') + } else if (tsgn->Extension[0] == 'H' && VolLetter == 'I') show_later = tsgn; - else if ( VolLetter == 'A' - || VolLetter == 'I') - { - if ( tsgn->Extension[0] == '\0' - || tsgn->Extension[1] == '\0') + else if (VolLetter == 'A' || VolLetter == 'I') { + if (tsgn->Extension[0] == '\0' || tsgn->Extension[1] == '\0') show = tsgn; - } - else + } else show = tsgn; - if (show) - { + if (show) { putc(' ', fpout); PrintTabSgNameEntry(show, 1, 0, fpout); putc('\n', fpout); show = NULL; - if (show_later) - { + if (show_later) { putc(' ', fpout); PrintTabSgNameEntry(show_later, 1, 0, fpout); putc('\n', fpout); @@ -539,54 +505,52 @@ static void ListTabSgName(int WantedSgNumber, int VolLetter, FILE *fpout) } -static void ListCIF(FILE *fpout) +static void ListCIF(FILE * fpout) { - int n; - const char **loop, *lbl; - const T_TabSgName *tsgn; + int n; + const char **loop, *lbl; + const T_TabSgName *tsgn; - static const char *loop_monoclinic_extensions[] = - { - "_monoclinic_extension # cf. _symmetry_space_group_id", - "_monoclinic_axis # cf. IT Vol. A 1983 sec. 2.16.", - "_monoclinic_setting # cf. IT Vol. A 1983 tab. 2.16.1.", - "_monoclinic_cellchoice # cf. IT Vol. A 1983 sec. 2.16.(i) & fig. 2.6.4.", - "", - " b b abc 1", - " b1 b abc 1", - " b2 b abc 2", - " b3 b abc 3", - "-b b c-ba 1", - "-b1 b c-ba 1", - "-b2 b c-ba 2", - "-b3 b c-ba 3", - " c c abc 1", - " c1 c abc 1", - " c2 c abc 2", - " c3 c abc 3", - "-c c ba-c 1", - "-c1 c ba-c 1", - "-c2 c ba-c 2", - "-c3 c ba-c 3", - " a a abc 1", - " a1 a abc 1", - " a2 a abc 2", - " a3 a abc 3", - "-a a -acb 1", - "-a1 a -acb 1", - "-a2 a -acb 2", - "-a3 a -acb 3", - NULL - }; + static const char *loop_monoclinic_extensions[] = { + "_monoclinic_extension # cf. _symmetry_space_group_id", + "_monoclinic_axis # cf. IT Vol. A 1983 sec. 2.16.", + "_monoclinic_setting # cf. IT Vol. A 1983 tab. 2.16.1.", + "_monoclinic_cellchoice # cf. IT Vol. A 1983 sec. 2.16.(i) & fig. 2.6.4.", + "", + " b b abc 1", + " b1 b abc 1", + " b2 b abc 2", + " b3 b abc 3", + "-b b c-ba 1", + "-b1 b c-ba 1", + "-b2 b c-ba 2", + "-b3 b c-ba 3", + " c c abc 1", + " c1 c abc 1", + " c2 c abc 2", + " c3 c abc 3", + "-c c ba-c 1", + "-c1 c ba-c 1", + "-c2 c ba-c 2", + "-c3 c ba-c 3", + " a a abc 1", + " a1 a abc 1", + " a2 a abc 2", + " a3 a abc 3", + "-a a -acb 1", + "-a1 a -acb 1", + "-a2 a -acb 2", + "-a3 a -acb 3", + NULL + }; - static const char *loop_symmetry_space_group[] = - { - "_symmetry_space_group_id", - "_symmetry_space_group_name_sch", - "_symmetry_space_group_name_h-m # recognised IUCr CIF data names", - "_symmetry_space_group_name_hall # recognised IUCr CIF data names", - NULL - }; + static const char *loop_symmetry_space_group[] = { + "_symmetry_space_group_id", + "_symmetry_space_group_name_sch", + "_symmetry_space_group_name_h-m # recognised IUCr CIF data names", + "_symmetry_space_group_name_hall # recognised IUCr CIF data names", + NULL + }; fprintf(fpout, "data_ notation\n\n"); @@ -594,7 +558,8 @@ static void ListCIF(FILE *fpout) fprintf(fpout, "loop_\n"); for (loop = loop_monoclinic_extensions; *loop; loop++) { - if ((*loop)[0]) fprintf(fpout, " %s", *loop); + if ((*loop)[0]) + fprintf(fpout, " %s", *loop); putc('\n', fpout); } @@ -604,14 +569,14 @@ static void ListCIF(FILE *fpout) fprintf(fpout, "loop_\n"); for (loop = loop_symmetry_space_group; *loop; loop++) { - if ((*loop)[0]) fprintf(fpout, " %s", *loop); + if ((*loop)[0]) + fprintf(fpout, " %s", *loop); putc('\n', fpout); } putc('\n', fpout); - for (tsgn = TabSgName; tsgn->HallSymbol; tsgn++) - { + for (tsgn = TabSgName; tsgn->HallSymbol; tsgn++) { n = fprintf(fpout, " %3d", tsgn->SgNumber); if (tsgn->Extension[0]) @@ -622,21 +587,31 @@ static void ListCIF(FILE *fpout) return; } - while (n < 14) { putc(' ', fpout); n++; } - putc(' ', fpout); n++; + while (n < 14) { + putc(' ', fpout); + n++; + } + putc(' ', fpout); + n++; n += fprintf(fpout, "%s", SchoenfliesSymbols[tsgn->SgNumber]); - while (n < 22) { putc(' ', fpout); n++; } - putc(' ', fpout); n++; + while (n < 22) { + putc(' ', fpout); + n++; + } + putc(' ', fpout); + n++; n += PrintFullHM_SgName(tsgn, '_', fpout); - while (n < 36) { putc(' ', fpout); n++; } + while (n < 36) { + putc(' ', fpout); + n++; + } putc(' ', fpout); - for (lbl = tsgn->HallSymbol; *lbl; lbl++) - { + for (lbl = tsgn->HallSymbol; *lbl; lbl++) { if (*lbl == ' ' && lbl != tsgn->HallSymbol) putc('_', fpout); else @@ -648,28 +623,28 @@ static void ListCIF(FILE *fpout) } -static void PutAllXYZ(const T_SgInfo *SgInfo, FILE *fpout) +static void PutAllXYZ(const T_SgInfo * SgInfo, FILE * fpout) { - int iList, f, i; - int nTrV, iTrV, nLoopInv, iLoopInv; - const int *TrV; - T_RTMx SMx; - const T_RTMx *lsmx; - const char *xyz; - char buf0[8], buf1[8], buf2[8]; + int iList, f, i; + int nTrV, iTrV, nLoopInv, iLoopInv; + const int *TrV; + T_RTMx SMx; + const T_RTMx *lsmx; + const char *xyz; + char buf0[8], buf1[8], buf2[8]; nLoopInv = Sg_nLoopInv(SgInfo); nTrV = SgInfo->LatticeInfo->nTrVector; - TrV = SgInfo->LatticeInfo->TrVector; + TrV = SgInfo->LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) - { - for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) - { - if (iLoopInv == 0) f = 1; - else f = -1; + for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) { + for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) { + if (iLoopInv == 0) + f = 1; + else + f = -1; lsmx = SgInfo->ListSeitzMx; @@ -678,9 +653,12 @@ static void PutAllXYZ(const T_SgInfo *SgInfo, FILE *fpout) if (nTrV > 1) fprintf(fpout, " +(%s %s %s)", - FormatFraction(TrV[0], STBF, 0, buf0, sizeof buf0 / sizeof (*buf0)), - FormatFraction(TrV[1], STBF, 0, buf1, sizeof buf1 / sizeof (*buf1)), - FormatFraction(TrV[2], STBF, 0, buf2, sizeof buf2 / sizeof (*buf2))); + FormatFraction(TrV[0], STBF, 0, buf0, + sizeof buf0 / sizeof(*buf0)), + FormatFraction(TrV[1], STBF, 0, buf1, + sizeof buf1 / sizeof(*buf1)), + FormatFraction(TrV[2], STBF, 0, buf2, + sizeof buf2 / sizeof(*buf2))); if (nLoopInv > 1) fprintf(fpout, " Inversion-Flag = %d", iLoopInv); @@ -688,19 +666,17 @@ static void PutAllXYZ(const T_SgInfo *SgInfo, FILE *fpout) if (nLoopInv > 1 || nTrV > 1) putc('\n', fpout); - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { for (i = 0; i < 9; i++) - SMx.s.R[i] = f * lsmx->s.R[i]; + SMx.s.R[i] = f * lsmx->s.R[i]; for (i = 0; i < 3; i++) SMx.s.T[i] = iModPositive(f * lsmx->s.T[i] + TrV[i], STBF); - xyz = RTMx2XYZ(&SMx, 1, STBF, 0, 0, 1, ", ", NULL, 0); + xyz = RTMx2XYZ(&SMx, 1, STBF, 0, 0, 1, ", ", NULL, 0); if (xyz) fprintf(fpout, "%s\n", xyz); - else - { + else { SetSgError("Internal Error: PutAllXYZ()"); return; } @@ -712,15 +688,15 @@ static void PutAllXYZ(const T_SgInfo *SgInfo, FILE *fpout) } -static void PutMaple(const T_SgInfo *SgInfo, FILE *fpout) +static void PutMaple(const T_SgInfo * SgInfo, FILE * fpout) { - int iList, f, i; - int nTrV, iTrV, nLoopInv, iLoopInv; - const int *TrV; - T_RTMx SMx; - const T_RTMx *lsmx; - int iMatrix; - char buf0[8], buf1[8], buf2[8]; + int iList, f, i; + int nTrV, iTrV, nLoopInv, iLoopInv; + const int *TrV; + T_RTMx SMx; + const T_RTMx *lsmx; + int iMatrix; + char buf0[8], buf1[8], buf2[8]; iMatrix = 0; @@ -728,14 +704,14 @@ static void PutMaple(const T_SgInfo *SgInfo, FILE *fpout) nLoopInv = Sg_nLoopInv(SgInfo); nTrV = SgInfo->LatticeInfo->nTrVector; - TrV = SgInfo->LatticeInfo->TrVector; + TrV = SgInfo->LatticeInfo->TrVector; - for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) - { - for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) - { - if (iLoopInv == 0) f = 1; - else f = -1; + for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) { + for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) { + if (iLoopInv == 0) + f = 1; + else + f = -1; lsmx = SgInfo->ListSeitzMx; @@ -744,9 +720,12 @@ static void PutMaple(const T_SgInfo *SgInfo, FILE *fpout) if (nTrV > 1) fprintf(fpout, " +(%s %s %s)", - FormatFraction(TrV[0], STBF, 0, buf0, sizeof buf0 / sizeof (*buf0)), - FormatFraction(TrV[1], STBF, 0, buf1, sizeof buf1 / sizeof (*buf1)), - FormatFraction(TrV[2], STBF, 0, buf2, sizeof buf2 / sizeof (*buf2))); + FormatFraction(TrV[0], STBF, 0, buf0, + sizeof buf0 / sizeof(*buf0)), + FormatFraction(TrV[1], STBF, 0, buf1, + sizeof buf1 / sizeof(*buf1)), + FormatFraction(TrV[2], STBF, 0, buf2, + sizeof buf2 / sizeof(*buf2))); if (nLoopInv > 1) fprintf(fpout, " Inversion-Flag = %d", iLoopInv); @@ -754,10 +733,9 @@ static void PutMaple(const T_SgInfo *SgInfo, FILE *fpout) if (nLoopInv > 1 || nTrV > 1) putc('\n', fpout); - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { for (i = 0; i < 9; i++) - SMx.s.R[i] = f * lsmx->s.R[i]; + SMx.s.R[i] = f * lsmx->s.R[i]; for (i = 0; i < 3; i++) SMx.s.T[i] = iModPositive(f * lsmx->s.T[i] + TrV[i], STBF); @@ -772,18 +750,19 @@ static void PutMaple(const T_SgInfo *SgInfo, FILE *fpout) } -static void PutSpaceSymFile(const T_SgInfo *SgInfo, FILE *fpout) +static void PutSpaceSymFile(const T_SgInfo * SgInfo, FILE * fpout) { - unsigned int SgID; - int iList, SuppressMx, f, i; - int nTrV, iTrV, nLoopInv, iLoopInv; - const int *TrV; - const T_RTMx *lsmx; - const T_TabSgName *tsgn; + unsigned int SgID; + int iList, SuppressMx, f, i; + int nTrV, iTrV, nLoopInv, iLoopInv; + const int *TrV; + const T_RTMx *lsmx; + const T_TabSgName *tsgn; - tsgn = SgInfo->TabSgName; - if (tsgn && tsgn->SgLabels == NULL) tsgn = NULL; + tsgn = SgInfo->TabSgName; + if (tsgn && tsgn->SgLabels == NULL) + tsgn = NULL; SgID = 0; @@ -805,40 +784,37 @@ static void PutSpaceSymFile(const T_SgInfo *SgInfo, FILE *fpout) nLoopInv = Sg_nLoopInv(SgInfo); nTrV = SgInfo->LatticeInfo->nTrVector; - TrV = SgInfo->LatticeInfo->TrVector; + TrV = SgInfo->LatticeInfo->TrVector; - iList = SgInfo->OrderL; - if (iList > 1) - { + iList = SgInfo->OrderL; + if (iList > 1) { iList--; SuppressMx = 1; - } - else + } else SuppressMx = 0; fprintf(fpout, "%d\n", iList); - for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) - { - for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) - { - if (iLoopInv == 0) f = 1; - else f = -1; + for (iTrV = 0; iTrV < nTrV; iTrV++, TrV += 3) { + for (iLoopInv = 0; iLoopInv < nLoopInv; iLoopInv++) { + if (iLoopInv == 0) + f = 1; + else + f = -1; lsmx = SgInfo->ListSeitzMx; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { - if (SuppressMx == 0) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { + if (SuppressMx == 0) { for (i = 0; i < 3; i++) fprintf(fpout, " %12.8f %12.8f %12.8f %12.8f\n", - (double) f * lsmx->s.R[3 * i + 0], - (double) f * lsmx->s.R[3 * i + 1], - (double) f * lsmx->s.R[3 * i + 2], - (double) iModPositive(f * lsmx->s.T[i] + TrV[i], STBF) / STBF); + (double) f * lsmx->s.R[3 * i + 0], + (double) f * lsmx->s.R[3 * i + 1], + (double) f * lsmx->s.R[3 * i + 2], + (double) iModPositive(f * lsmx->s.T[i] + TrV[i], + STBF) / STBF); - putc(':', fpout); + putc(':', fpout); putc('\n', fpout); } @@ -849,34 +825,46 @@ static void PutSpaceSymFile(const T_SgInfo *SgInfo, FILE *fpout) } -static void PutShelx(const T_SgInfo *SgInfo, FILE *fpout) +static void PutShelx(const T_SgInfo * SgInfo, FILE * fpout) { - int Latt_N = 0, iList; - const T_RTMx *lsmx; - const char *xyz; + int Latt_N = 0, iList; + const T_RTMx *lsmx; + const char *xyz; if (SgInfo->InversionOffOrigin != 0) fprintf(fpout, "***WARNING***: %s\n", - "Shelx manual: the origin MUST lie on a center of symmetry"); + "Shelx manual: the origin MUST lie on a center of symmetry"); - switch (SgInfo->LatticeInfo->Code) - { - case 'P': Latt_N = 1; break; - case 'A': Latt_N = 5; break; - case 'B': Latt_N = 6; break; - case 'C': Latt_N = 7; break; - case 'I': Latt_N = 2; break; - case 'R': - if (SgInfo->ExtraInfo == EI_Obverse) - Latt_N = 3; break; - case 'S': - case 'T': - SetSgError("Shelx supports R-obverse only"); - return; - case 'F': Latt_N = 4; break; - default: - goto ReturnError; + switch (SgInfo->LatticeInfo->Code) { + case 'P': + Latt_N = 1; + break; + case 'A': + Latt_N = 5; + break; + case 'B': + Latt_N = 6; + break; + case 'C': + Latt_N = 7; + break; + case 'I': + Latt_N = 2; + break; + case 'R': + if (SgInfo->ExtraInfo == EI_Obverse) + Latt_N = 3; + break; + case 'S': + case 'T': + SetSgError("Shelx supports R-obverse only"); + return; + case 'F': + Latt_N = 4; + break; + default: + goto ReturnError; } /* N must be made negative if the structure is non-centrosymmetric @@ -886,11 +874,10 @@ static void PutShelx(const T_SgInfo *SgInfo, FILE *fpout) fprintf(fpout, "LATT %2d\n", Latt_N); - lsmx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ + lsmx = &SgInfo->ListSeitzMx[1]; /* skip first = identity matrix */ - for (iList = 1; iList < SgInfo->nList; iList++, lsmx++) - { - xyz = RTMx2XYZ(lsmx, 1, STBF, 1, 1, 0, ", ", NULL, 0); + for (iList = 1; iList < SgInfo->nList; iList++, lsmx++) { + xyz = RTMx2XYZ(lsmx, 1, STBF, 1, 1, 0, ", ", NULL, 0); if (xyz) fprintf(fpout, "SYMM %s\n", xyz); else @@ -901,52 +888,47 @@ static void PutShelx(const T_SgInfo *SgInfo, FILE *fpout) return; - ReturnError: +ReturnError: SetSgError("Internal Error: PutShelx()"); return; } -static void PutSchakal(const T_SgInfo *SgInfo, FILE *fpout) +static void PutSchakal(const T_SgInfo * SgInfo, FILE * fpout) { - int iList, nMx, i; - int nTrV, iTrV; - const int *TrV; - T_RTMx SMx; - const T_RTMx *lsmx; - const char *xyz; + int iList, nMx, i; + int nTrV, iTrV; + const int *TrV; + T_RTMx SMx; + const T_RTMx *lsmx; + const char *xyz; if (Sg_nLoopInv(SgInfo) == 2) fprintf(fpout, "DU -x,-y,-z\n"); nTrV = SgInfo->LatticeInfo->nTrVector; - TrV = SgInfo->LatticeInfo->TrVector; + TrV = SgInfo->LatticeInfo->TrVector; - if (nTrV > 1) - { + if (nTrV > 1) { fprintf(fpout, "DU"); InitRotMx(SMx.s.R, 1); TrV += 3; - for (iTrV = 1; iTrV < nTrV; iTrV++, TrV += 3) - { + for (iTrV = 1; iTrV < nTrV; iTrV++, TrV += 3) { for (i = 0; i < 3; i++) SMx.s.T[i] = TrV[i]; - xyz = RTMx2XYZ(&SMx, 1, STBF, 0, 0, 1, ",", NULL, 0); - if (xyz) - { + xyz = RTMx2XYZ(&SMx, 1, STBF, 0, 0, 1, ",", NULL, 0); + if (xyz) { if (iTrV > 1) fprintf(fpout, " ;"); fprintf(fpout, " %s", xyz); - } - else - { + } else { putc('\n', fpout); goto ReturnError; } @@ -959,21 +941,16 @@ static void PutSchakal(const T_SgInfo *SgInfo, FILE *fpout) lsmx = &SgInfo->ListSeitzMx[1]; - for (iList = 1; iList < SgInfo->nList; iList++, lsmx++) - { - xyz = RTMx2XYZ(lsmx, 1, STBF, 0, 0, 1, ",", NULL, 0); - if (xyz) - { - if (nMx % 4 == 0) - { - if (nMx) putc('\n', fpout); + for (iList = 1; iList < SgInfo->nList; iList++, lsmx++) { + xyz = RTMx2XYZ(lsmx, 1, STBF, 0, 0, 1, ",", NULL, 0); + if (xyz) { + if (nMx % 4 == 0) { + if (nMx) + putc('\n', fpout); fprintf(fpout, "SY %s", xyz); - } - else + } else fprintf(fpout, " ; %s", xyz); - } - else - { + } else { putc('\n', fpout); goto ReturnError; } @@ -988,26 +965,25 @@ static void PutSchakal(const T_SgInfo *SgInfo, FILE *fpout) return; - ReturnError: +ReturnError: SetSgError("Internal Error: PutSchakal()"); return; } -static void Simple_hklList(T_SgInfo *SgInfo, int Maxh, int Maxk, int Maxl, +static void Simple_hklList(T_SgInfo * SgInfo, int Maxh, int Maxk, int Maxl, int ListSysAbsent) { - int h, k, l, iList, restriction, M, n, i; - int Minh, Mink, Minl; - int uvw[3]; - int CCMx_PL[9], deterCCMx_LP = 0, hP, kP, lP; + int h, k, l, iList, restriction, M, n, i; + int Minh, Mink, Minl; + int uvw[3]; + int CCMx_PL[9], deterCCMx_LP = 0, hP, kP, lP; - if (SgInfo->LatticeInfo->Code != 'P') - { + if (SgInfo->LatticeInfo->Code != 'P') { deterCCMx_LP = deterRotMx(SgInfo->CCMx_LP); - InverseRotMx(SgInfo->CCMx_LP, CCMx_PL); + InverseRotMx(SgInfo->CCMx_LP, CCMx_PL); if (deterCCMx_LP < 1) goto ReturnError; @@ -1018,73 +994,77 @@ static void Simple_hklList(T_SgInfo *SgInfo, int Maxh, int Maxk, int Maxl, fprintf(stdout, ">Begin hklList\n"); for (h = Minh; h <= Maxh; h++) - for (k = Mink; k <= Maxk; k++) - for (l = Minl; l <= Maxl; l++) - { - iList = IsSysAbsent_hkl(SgInfo, h, k, l, &restriction); - if (SgError != NULL) - return; + for (k = Mink; k <= Maxk; k++) + for (l = Minl; l <= Maxl; l++) { + iList = IsSysAbsent_hkl(SgInfo, h, k, l, &restriction); + if (SgError != NULL) + return; - M = BuildEq_hkl(SgInfo, NULL, h, k, l); - if (SgError != NULL) - return; + M = BuildEq_hkl(SgInfo, NULL, h, k, l); + if (SgError != NULL) + return; - if (iList == 0) - { - if ((iList = IsSuppressed_hkl(SgInfo, Minh, Mink, Minl, - Maxk, Maxl, - h, k, l)) != 0) - n = fprintf(stdout, "# %3d %3d %3d %3d [%d]", - h, k, l, M, iList); - else - n = fprintf(stdout, " %3d %3d %3d %3d", - h, k, l, M); + if (iList == 0) { + if ((iList = IsSuppressed_hkl(SgInfo, Minh, Mink, Minl, + Maxk, Maxl, h, k, l)) != 0) + n = fprintf(stdout, "# %3d %3d %3d %3d [%d]", + h, k, l, M, iList); + else + n = fprintf(stdout, " %3d %3d %3d %3d", h, k, l, M); - if (restriction >= 0) - { - while (n < 27) { n++; putc(' ', stdout); } - n += fprintf(stdout, " %2d/%d", restriction, STBF); + if (restriction >= 0) { + while (n < 27) { + n++; + putc(' ', stdout); + } + n += fprintf(stdout, " %2d/%d", restriction, STBF); + } + + while (n < 34) { + n++; + putc(' ', stdout); + } + if (Is_si(SgInfo, h, k, l) == 1) + n += fprintf(stdout, " s.i."); + + while (n < 41) { + n++; + putc(' ', stdout); + } + Set_uvw(SgInfo, h, k, l, uvw); + for (i = 0; i < SgInfo->n_si_Vector; i++) + n += fprintf(stdout, " %3d", uvw[i]); + + if (SgInfo->LatticeInfo->Code != 'P') { + hP = h * CCMx_PL[0] + k * CCMx_PL[3] + l * CCMx_PL[6]; + kP = h * CCMx_PL[1] + k * CCMx_PL[4] + l * CCMx_PL[7]; + lP = h * CCMx_PL[2] + k * CCMx_PL[5] + l * CCMx_PL[8]; + + if (hP % deterCCMx_LP || kP % deterCCMx_LP + || lP % deterCCMx_LP) + goto ReturnError; + + hP /= deterCCMx_LP; + kP /= deterCCMx_LP; + lP /= deterCCMx_LP; + + while (n < 55) { + n++; + putc(' ', stdout); + } + n += fprintf(stdout, " P %3d %3d %3d", hP, kP, lP); + } + + putc('\n', stdout); + } else if (ListSysAbsent) + fprintf(stdout, "# %3d %3d %3d %3d (%d)\n", h, k, l, M, iList); } - while (n < 34) { n++; putc(' ', stdout); } - if (Is_si(SgInfo, h, k, l) == 1) - n += fprintf(stdout, " s.i."); - - while (n < 41) { n++; putc(' ', stdout); } - Set_uvw(SgInfo, h, k, l, uvw); - for (i = 0; i < SgInfo->n_si_Vector; i++) - n += fprintf(stdout, " %3d", uvw[i]); - - if (SgInfo->LatticeInfo->Code != 'P') - { - hP = h * CCMx_PL[0] + k * CCMx_PL[3] + l * CCMx_PL[6]; - kP = h * CCMx_PL[1] + k * CCMx_PL[4] + l * CCMx_PL[7]; - lP = h * CCMx_PL[2] + k * CCMx_PL[5] + l * CCMx_PL[8]; - - if (hP % deterCCMx_LP || kP % deterCCMx_LP || lP % deterCCMx_LP) - goto ReturnError; - - hP /= deterCCMx_LP; - kP /= deterCCMx_LP; - lP /= deterCCMx_LP; - - while (n < 55) { n++; putc(' ', stdout); } - n += fprintf(stdout, " P %3d %3d %3d", - hP, kP, lP); - } - - putc('\n', stdout); - } - else if (ListSysAbsent) - fprintf(stdout, "# %3d %3d %3d %3d (%d)\n", - h, k, l, M, iList); - } - fprintf(stdout, ">End hklList\n"); return; - ReturnError: +ReturnError: SetSgError("Internal Error: Simple_hklList()"); return; @@ -1100,14 +1080,13 @@ static void Simple_hklList(T_SgInfo *SgInfo, int Maxh, int Maxk, int Maxl, typedef struct { - double a, b, c; - double alpha, beta, gamma; - double sa, sb, sg; - double ca, cb, cg; - double v; - char calcs, calcc; - } - T_LatticeConstants; + double a, b, c; + double alpha, beta, gamma; + double sa, sb, sg; + double ca, cb, cg; + double v; + char calcs, calcc; +} T_LatticeConstants; #ifndef M_PI @@ -1119,7 +1098,7 @@ typedef struct { #define PIover180 (M_PI / 180.) -#define EpsPI (1.e-6) /* ARBITRARY */ +#define EpsPI (1.e-6) /* ARBITRARY */ static double sinC(double arg) @@ -1140,36 +1119,42 @@ static double cosC(double arg) } -static int Lc2RLc(T_LatticeConstants *lc, T_LatticeConstants *rlc) +static int Lc2RLc(T_LatticeConstants * lc, T_LatticeConstants * rlc) { /* Transformation Lattice Constants -> Reciprocal Lattice Constants after Kleber, W., 17. Aufl., Verlag Technik GmbH Berlin 1990, P.352 */ - double D; + double D; - if (lc->calcs) - { lc->sa = sinC(lc->alpha); lc->sb = sinC(lc->beta); lc->sg = sinC(lc->gamma); + if (lc->calcs) { + lc->sa = sinC(lc->alpha); + lc->sb = sinC(lc->beta); + lc->sg = sinC(lc->gamma); lc->calcs = 0; } - if (lc->calcc) - { lc->ca = cosC(lc->alpha); lc->cb = cosC(lc->beta); lc->cg = cosC(lc->gamma); + if (lc->calcc) { + lc->ca = cosC(lc->alpha); + lc->cb = cosC(lc->beta); + lc->cg = cosC(lc->gamma); lc->calcc = 0; } D = 1. - lc->ca * lc->ca - lc->cb * lc->cb - lc->cg * lc->cg - + 2. * lc->ca * lc->cb * lc->cg; - if (D < 0.) return -1; + + 2. * lc->ca * lc->cb * lc->cg; + if (D < 0.) + return -1; lc->v = lc->a * lc->b * lc->c * sqrt(D); - if (lc->v == 0.) return -1; + if (lc->v == 0.) + return -1; - if (lc->sa == 0. || lc->sb == 0. || lc->sg == 0.) return -1; + if (lc->sa == 0. || lc->sb == 0. || lc->sg == 0.) + return -1; - if (rlc != NULL) - { + if (rlc != NULL) { rlc->a = lc->b * lc->c * lc->sa / lc->v; rlc->b = lc->c * lc->a * lc->sb / lc->v; rlc->c = lc->a * lc->b * lc->sg / lc->v; @@ -1177,7 +1162,7 @@ static int Lc2RLc(T_LatticeConstants *lc, T_LatticeConstants *rlc) rlc->cb = (lc->cg * lc->ca - lc->cb) / (lc->sg * lc->sa); rlc->cg = (lc->ca * lc->cb - lc->cg) / (lc->sa * lc->sb); rlc->alpha = acos(rlc->ca); - rlc->beta = acos(rlc->cb); + rlc->beta = acos(rlc->cb); rlc->gamma = acos(rlc->cg); rlc->sa = sinC(rlc->alpha); rlc->sb = sinC(rlc->beta); @@ -1191,122 +1176,146 @@ static int Lc2RLc(T_LatticeConstants *lc, T_LatticeConstants *rlc) } -static void Lc2MetricalMx(T_LatticeConstants *lc, double *G) +static void Lc2MetricalMx(T_LatticeConstants * lc, double *G) { - G[0] = lc->a * lc->a; + G[0] = lc->a * lc->a; G[1] = G[3] = lc->a * lc->b * lc->cg; G[2] = G[6] = lc->a * lc->c * lc->cb; - G[4] = lc->b * lc->b; + G[4] = lc->b * lc->b; G[5] = G[7] = lc->b * lc->c * lc->ca; - G[8] = lc->c * lc->c; + G[8] = lc->c * lc->c; } -static int HarmonizeSgLatCon(T_SgInfo *SgInfo, T_LatticeConstants *lc, int np) +static int HarmonizeSgLatCon(T_SgInfo * SgInfo, T_LatticeConstants * lc, + int np) { - switch(SgInfo->XtalSystem) - { - case XS_Triclinic: - if (np != 6) goto IllUnitCell; + switch (SgInfo->XtalSystem) { + case XS_Triclinic: + if (np != 6) + goto IllUnitCell; + break; + case XS_Monoclinic: + if (np != 4 && np != 6) + goto IllUnitCell; + switch (SgInfo->UniqueRefAxis) { + case 'x': + lc->beta = lc->gamma = 90. * PIover180; break; - case XS_Monoclinic: - if (np != 4 && np != 6) goto IllUnitCell; - switch (SgInfo->UniqueRefAxis) - { - case 'x': lc->beta = lc->gamma = 90. * PIover180; break; - case 'y': if (np != 6) lc->beta = lc->alpha; - lc->alpha = lc->gamma = 90. * PIover180; break; - case 'z': if (np != 6) lc->gamma = lc->alpha; - lc->alpha = lc->beta = 90. * PIover180; break; - default: - goto IntErr; - } + case 'y': + if (np != 6) + lc->beta = lc->alpha; + lc->alpha = lc->gamma = 90. * PIover180; break; - case XS_Orthorhombic: - if (np != 3 && np != 6) goto IllUnitCell; - lc->alpha = lc->beta = lc->gamma = 90. * PIover180; - break; - case XS_Tetragonal: - if (np != 2 && np != 6) goto IllUnitCell; - switch (SgInfo->UniqueRefAxis) - { - case 'x': lc->c = lc->b; break; - case 'y': lc->c = lc->a; break; - case 'z': if (np != 6) lc->c = lc->b; - lc->b = lc->a; break; - default: - goto IntErr; - } - lc->alpha = lc->beta = lc->gamma = 90. * PIover180; - break; - case XS_Trigonal: - if (np != 2 && np != 6) goto IllUnitCell; - if (SgInfo->UniqueDirCode == '*') - { - if (np != 6) lc->alpha = lc->b * PIover180; - lc->c = lc->b = lc->a; - lc->gamma = lc->beta = lc->alpha; - break; - } - case XS_Hexagonal: - if (np != 2 && np != 6) goto IllUnitCell; - switch (SgInfo->UniqueRefAxis) - { - case 'x': lc->c = lc->b; - lc->alpha = 120. * PIover180; - lc->beta = lc->gamma = 90. * PIover180; break; - case 'y': lc->c = lc->a; - lc->beta = 120. * PIover180; - lc->alpha = lc->gamma = 90. * PIover180; break; - case 'z': if (np != 6) lc->c = lc->b; - lc->b = lc->a; - lc->gamma = 120. * PIover180; - lc->alpha = lc->beta = 90. * PIover180; break; - default: - goto IntErr; - } - break; - case XS_Cubic: - if (np != 1 && np != 6) goto IllUnitCell; - lc->c = lc->b = lc->a; - lc->alpha = lc->beta = lc->gamma = 90. * PIover180; + case 'z': + if (np != 6) + lc->gamma = lc->alpha; + lc->alpha = lc->beta = 90. * PIover180; break; default: goto IntErr; + } + break; + case XS_Orthorhombic: + if (np != 3 && np != 6) + goto IllUnitCell; + lc->alpha = lc->beta = lc->gamma = 90. * PIover180; + break; + case XS_Tetragonal: + if (np != 2 && np != 6) + goto IllUnitCell; + switch (SgInfo->UniqueRefAxis) { + case 'x': + lc->c = lc->b; + break; + case 'y': + lc->c = lc->a; + break; + case 'z': + if (np != 6) + lc->c = lc->b; + lc->b = lc->a; + break; + default: + goto IntErr; + } + lc->alpha = lc->beta = lc->gamma = 90. * PIover180; + break; + case XS_Trigonal: + if (np != 2 && np != 6) + goto IllUnitCell; + if (SgInfo->UniqueDirCode == '*') { + if (np != 6) + lc->alpha = lc->b * PIover180; + lc->c = lc->b = lc->a; + lc->gamma = lc->beta = lc->alpha; + break; + } + case XS_Hexagonal: + if (np != 2 && np != 6) + goto IllUnitCell; + switch (SgInfo->UniqueRefAxis) { + case 'x': + lc->c = lc->b; + lc->alpha = 120. * PIover180; + lc->beta = lc->gamma = 90. * PIover180; + break; + case 'y': + lc->c = lc->a; + lc->beta = 120. * PIover180; + lc->alpha = lc->gamma = 90. * PIover180; + break; + case 'z': + if (np != 6) + lc->c = lc->b; + lc->b = lc->a; + lc->gamma = 120. * PIover180; + lc->alpha = lc->beta = 90. * PIover180; + break; + default: + goto IntErr; + } + break; + case XS_Cubic: + if (np != 1 && np != 6) + goto IllUnitCell; + lc->c = lc->b = lc->a; + lc->alpha = lc->beta = lc->gamma = 90. * PIover180; + break; + default: + goto IntErr; } - return 0; + return 0; - IntErr: SetSgError("Internal Error: HarmonizeSgLatCon()"); +IntErr:SetSgError("Internal Error: HarmonizeSgLatCon()"); return -1; - IllUnitCell: SetSgError("Error: Illegal UnitCell or SpaceGroup"); +IllUnitCell:SetSgError("Error: Illegal UnitCell or SpaceGroup"); return -1; } -static void MxMultiply(double *ab, double *a, double *b, int ma, int na, int nb) +static void MxMultiply(double *ab, double *a, double *b, int ma, int na, + int nb) { - int i, j, k; - double *ai, *aij, *bk, *bkj; + int i, j, k; + double *ai, *aij, *bk, *bkj; ai = a; - for (i = 0; i < ma; i++) - { + for (i = 0; i < ma; i++) { bk = b; - for (k = 0; k < nb; k++) - { + for (k = 0; k < nb; k++) { aij = ai; bkj = bk; *ab = 0.; - for (j = 0; j < na; j++) - { + for (j = 0; j < na; j++) { *ab += (*aij) * (*bkj); aij++; @@ -1322,14 +1331,13 @@ static void MxMultiply(double *ab, double *a, double *b, int ma, int na, int nb) } -static int TransformLatticeConstants(T_LatticeConstants *LatConA, +static int TransformLatticeConstants(T_LatticeConstants * LatConA, int np, - T_LatticeConstants *LatConB, - T_SgInfo *SgInfo, - int *InvCBMxR) + T_LatticeConstants * LatConB, + T_SgInfo * SgInfo, int *InvCBMxR) { - int i, j; - double GA[9], GB[9], GAR[9], R[9], Rt[9]; + int i, j; + double GA[9], GB[9], GAR[9], R[9], Rt[9]; if (HarmonizeSgLatCon(SgInfo, LatConA, np) != 0) @@ -1349,7 +1357,7 @@ static int TransformLatticeConstants(T_LatticeConstants *LatConA, for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { - R[i * 3 + j] = InvCBMxR[i * 3 + j] / (double) CRBF; + R[i * 3 + j] = InvCBMxR[i * 3 + j] / (double) CRBF; Rt[i * 3 + j] = InvCBMxR[j * 3 + i] / (double) CRBF; } @@ -1364,16 +1372,16 @@ static int TransformLatticeConstants(T_LatticeConstants *LatConA, LatConB->c = sqrt(GB[8]); LatConB->alpha = GB[5] / LatConB->b / LatConB->c; - LatConB->beta = GB[2] / LatConB->c / LatConB->a; + LatConB->beta = GB[2] / LatConB->c / LatConB->a; LatConB->gamma = GB[1] / LatConB->a / LatConB->b; - if ( LatConB->alpha < -1. || LatConB->alpha > 1. - || LatConB->beta < -1. || LatConB->beta > 1. + if (LatConB->alpha < -1. || LatConB->alpha > 1. + || LatConB->beta < -1. || LatConB->beta > 1. || LatConB->gamma < -1. || LatConB->gamma > 1.) goto ReturnError; LatConB->alpha = acos(LatConB->alpha); - LatConB->beta = acos(LatConB->beta ); + LatConB->beta = acos(LatConB->beta); LatConB->gamma = acos(LatConB->gamma); LatConB->calcs = 1; @@ -1381,7 +1389,7 @@ static int TransformLatticeConstants(T_LatticeConstants *LatConA, return 0; - ReturnError: +ReturnError: SetSgError("InternalError: Corrupt InvCBMxR"); return -1; @@ -1394,94 +1402,90 @@ static int TransformLatticeConstants(T_LatticeConstants *LatConA, static void usage(void) { - static const char *quick_help[] = - { - "-Hall|VolA|VolI select conventions", - "-ListTable[=#] print [parts of] internal table", - "-CIF print internal table in CIF format", - "-XYZ print something like \"-x, y+1/2, z\"", - "-AllXYZ print all symmetry operations", - "-Maple print symmetry matrices in Maple format", - "-Space print symmetry file for AVS SpaceModule", - "-Shelx print Shelx LATT & SYMM cards", - "-Schakal print Schakal DU & SY cards", - "-hklList print simple hkl listing", - "-Standard compute transformation to \"standard\" setting", + static const char *quick_help[] = { + "-Hall|VolA|VolI select conventions", + "-ListTable[=#] print [parts of] internal table", + "-CIF print internal table in CIF format", + "-XYZ print something like \"-x, y+1/2, z\"", + "-AllXYZ print all symmetry operations", + "-Maple print symmetry matrices in Maple format", + "-Space print symmetry file for AVS SpaceModule", + "-Shelx print Shelx LATT & SYMM cards", + "-Schakal print Schakal DU & SY cards", + "-hklList print simple hkl listing", + "-Standard compute transformation to \"standard\" setting", "-UnitCell=\"a..g\" unit cell constants a, b, c, alpha, beta, gamma", - "-v be more verbose", - "-Verify debug option: verify transformations", - "-ClearError debug option: clear errors and continue", - NULL - }; + "-v be more verbose", + "-Verify debug option: verify transformations", + "-ClearError debug option: clear errors and continue", + NULL + }; - const char **qh; + const char **qh; fprintf(stderr, - "usage: %s [options] [SpaceGroupName_or_# [SpaceGroupName_or_#]]\n", - progn); + "usage: %s [options] [SpaceGroupName_or_# [SpaceGroupName_or_#]]\n", + progn); for (qh = quick_help; *qh; qh++) fprintf(stderr, " %s\n", *qh); putc('\n', stderr); - fprintf(stderr, "examples: %s 68\n", progn); - fprintf(stderr, " %s C2/m:c2 -XYZ\n", progn); - fprintf(stderr, " %s \"Oh^3\" -Shelx\n", progn); + fprintf(stderr, "examples: %s 68\n", progn); + fprintf(stderr, " %s C2/m:c2 -XYZ\n", progn); + fprintf(stderr, " %s \"Oh^3\" -Shelx\n", progn); fprintf(stderr, " %s -Hall \"-F 4y 2\" -Standard\n", progn); - fprintf(stderr, " %s -VolI 15 -VolA 15\n", progn); - fprintf(stderr, " %s -ListTable=68\n", progn); + fprintf(stderr, " %s -VolI 15 -VolA 15\n", progn); + fprintf(stderr, " %s -ListTable=68\n", progn); exit(1); } -static void ShowCBMx(T_RTMx *CBMx, T_RTMx *InvCBMx, int F_Maple) +static void ShowCBMx(T_RTMx * CBMx, T_RTMx * InvCBMx, int F_Maple) { if (F_Maple) { - PrintMapleRTMx( CBMx, CRBF, CTBF, " CBMx", stdout); + PrintMapleRTMx(CBMx, CRBF, CTBF, " CBMx", stdout); PrintMapleRTMx(InvCBMx, CRBF, CTBF, "InvCBMx", stdout); - } - else { + } else { fprintf(stdout, " CBMx = %s\n", - RTMx2XYZ( CBMx, CRBF, CTBF, 0, 0, 1, ", ", NULL, 0)); + RTMx2XYZ(CBMx, CRBF, CTBF, 0, 0, 1, ", ", NULL, 0)); fprintf(stdout, "InvCBMx = %s\n", - RTMx2XYZ(InvCBMx, CRBF, CTBF, 0, 0, 1, ", ", NULL, 0)); + RTMx2XYZ(InvCBMx, CRBF, CTBF, 0, 0, 1, ", ", NULL, 0)); } } -typedef struct - { - int Convention; - const char *SgName; - const T_TabSgName *InpTSgN; - const T_TabSgName *RefTSgN; - T_RTMx CBMx, InvCBMx; - } - T_SgList; +typedef struct { + int Convention; + const char *SgName; + const T_TabSgName *InpTSgN; + const T_TabSgName *RefTSgN; + T_RTMx CBMx, InvCBMx; +} T_SgList; int main(int argc, char *argv[]) { - int i, n, HaveSpace, pos_hsym; - int F_Convention, Last_F_Convention; - int F_ListTable, F_CIF; - int F_XYZ, F_AllXYZ, F_Maple; - int F_Space, F_Shelx, F_Schakal; - int F_hklList; - int F_Standard, F_UnitCell; - int F_Verbose, F_Verify, F_ClearError; - T_LatticeConstants LatConA, LatConB; - char *cp, xtrac; - const char *SgName; - const T_TabSgName *tsgn; - T_SgInfo SpgrInfo[2], BC_SgInfo, *SgInfo; - int nSgList, iSgList; - T_SgList SgList[2]; - T_RTMx *CBMx, *InvCBMx; - T_RTMx CCBMx, CInvCBMx; + int i, n, HaveSpace, pos_hsym; + int F_Convention, Last_F_Convention; + int F_ListTable, F_CIF; + int F_XYZ, F_AllXYZ, F_Maple; + int F_Space, F_Shelx, F_Schakal; + int F_hklList; + int F_Standard, F_UnitCell; + int F_Verbose, F_Verify, F_ClearError; + T_LatticeConstants LatConA, LatConB; + char *cp, xtrac; + const char *SgName; + const T_TabSgName *tsgn; + T_SgInfo SpgrInfo[2], BC_SgInfo, *SgInfo; + int nSgList, iSgList; + T_SgList SgList[2]; + T_RTMx *CBMx, *InvCBMx; + T_RTMx CCBMx, CInvCBMx; /* @@ -1505,7 +1509,8 @@ int main(int argc, char *argv[]) nSgList = 0; - F_Convention = 'A'; Last_F_Convention = 0; + F_Convention = 'A'; + Last_F_Convention = 0; F_ListTable = 0; F_CIF = 0; F_XYZ = 0; @@ -1521,36 +1526,28 @@ int main(int argc, char *argv[]) F_Verify = 0; F_ClearError = 0; - for (i = 1; i < argc; i++) - { - if (str_icmp(argv[i], "-Hall") == 0) { + for (i = 1; i < argc; i++) { + if (str_icmp(argv[i], "-Hall") == 0) { F_Convention = 'H'; Last_F_Convention = 0; - } - else if (str_icmp(argv[i], "-VolA") == 0) { + } else if (str_icmp(argv[i], "-VolA") == 0) { F_Convention = 'A'; Last_F_Convention = 'A'; - } - else if ( str_icmp(argv[i], "-VolI") == 0 - || str_icmp(argv[i], "-Vol1") == 0) { + } else if (str_icmp(argv[i], "-VolI") == 0 + || str_icmp(argv[i], "-Vol1") == 0) { F_Convention = 'I'; Last_F_Convention = 'I'; - } - else if (str_ibegin(argv[i], "-ListTable") == 0) - { - cp = argv[i] + 10; - if (*cp == '\0') + } else if (str_ibegin(argv[i], "-ListTable") == 0) { + cp = argv[i] + 10; + if (*cp == '\0') F_ListTable = -1; - else if (*cp++ == '=') - { + else if (*cp++ == '=') { n = sscanf(cp, "%d%c", &F_ListTable, &xtrac); - if (n != 1 || F_ListTable < 1 - || F_ListTable > 230) usage(); - } - else + if (n != 1 || F_ListTable < 1 || F_ListTable > 230) + usage(); + } else usage(); - } - else if (str_icmp(argv[i], "-CIF") == 0) + } else if (str_icmp(argv[i], "-CIF") == 0) F_CIF = 1; else if (str_icmp(argv[i], "-XYZ") == 0) @@ -1577,20 +1574,21 @@ int main(int argc, char *argv[]) else if (str_icmp(argv[i], "-Standard") == 0) F_Standard = 1; - else if (str_ibegin(argv[i], "-UnitCell=") == 0) - { + else if (str_ibegin(argv[i], "-UnitCell=") == 0) { F_UnitCell = sscanf(&argv[i][10], "%lf%lf%lf%lf%lf%lf", - &LatConA.a, &LatConA.b, &LatConA.c, - &LatConA.alpha, &LatConA.beta, &LatConA.gamma); + &LatConA.a, &LatConA.b, &LatConA.c, + &LatConA.alpha, &LatConA.beta, &LatConA.gamma); if (F_UnitCell < 1) usage(); - if (F_UnitCell > 3) LatConA.alpha *= PIover180; - if (F_UnitCell > 4) LatConA.beta *= PIover180; - if (F_UnitCell > 5) LatConA.gamma *= PIover180; - } - else if (str_icmp(argv[i], "-v") == 0) + if (F_UnitCell > 3) + LatConA.alpha *= PIover180; + if (F_UnitCell > 4) + LatConA.beta *= PIover180; + if (F_UnitCell > 5) + LatConA.gamma *= PIover180; + } else if (str_icmp(argv[i], "-v") == 0) F_Verbose = 1; else if (str_icmp(argv[i], "-Verify") == 0) @@ -1599,55 +1597,49 @@ int main(int argc, char *argv[]) else if (str_icmp(argv[i], "-ClearError") == 0) F_ClearError = 1; - else if (nSgList < 2) - { + else if (nSgList < 2) { SgName = argv[i]; - while (*SgName == ' ' || *SgName == '\t') SgName++; + while (*SgName == ' ' || *SgName == '\t') + SgName++; if (F_Convention == 'H' && isdigit(*SgName)) SgList[nSgList].Convention = 'A'; else SgList[nSgList].Convention = F_Convention; - SgList[nSgList].SgName = SgName; + SgList[nSgList].SgName = SgName; SgList[nSgList].InpTSgN = NULL; SgList[nSgList].RefTSgN = NULL; nSgList++; - } - else + } else usage(); } - if (F_ListTable) - { + if (F_ListTable) { ListTabSgName(F_ListTable, Last_F_Convention, stdout); PrintClearSgError(1, 0); putc('\n', stdout); } - if (F_CIF) - { + if (F_CIF) { ListCIF(stdout); PrintClearSgError(1, 0); putc('\n', stdout); } - if (nSgList == 0) - { + if (nSgList == 0) { if (F_ListTable == 0 && F_CIF == 0) usage(); else exit(0); } - if (F_Space == 0) - { + if (F_Space == 0) { putc('#', stdout); - for (i = 0; i < argc; i++) - { + for (i = 0; i < argc; i++) { putc(' ', stdout); HaveSpace = 0; @@ -1663,13 +1655,14 @@ int main(int argc, char *argv[]) if (HaveSpace == 0) fprintf(stdout, "%s", argv[i]); - else - { + else { putc('"', stdout); for (n = 0; argv[i][n]; n++) - if (argv[i][n] == '"') putc('+', stdout); - else putc(argv[i][n], stdout); + if (argv[i][n] == '"') + putc('+', stdout); + else + putc(argv[i][n], stdout); putc('"', stdout); } @@ -1682,9 +1675,9 @@ int main(int argc, char *argv[]) BC_SgInfo.ListSeitzMx = NULL; BC_SgInfo.ListRotMxInfo = NULL; - for (iSgList = 0; iSgList < nSgList; iSgList++) - { - if (iSgList) putc('\n', stdout); + for (iSgList = 0; iSgList < nSgList; iSgList++) { + if (iSgList) + putc('\n', stdout); if (nSgList > 1 || F_Standard) fprintf(stdout, "Setting %c:\n\n", "AB"[iSgList]); @@ -1694,33 +1687,32 @@ int main(int argc, char *argv[]) SgInfo->MaxList = 192; SgInfo->ListSeitzMx - = malloc(SgInfo->MaxList * sizeof (*SgInfo->ListSeitzMx)); - if (SgInfo->ListSeitzMx == NULL) NotEnoughCore(); + = malloc(SgInfo->MaxList * sizeof(*SgInfo->ListSeitzMx)); + if (SgInfo->ListSeitzMx == NULL) + NotEnoughCore(); #ifndef No_ListRotMxInfo SgInfo->ListRotMxInfo - = malloc(SgInfo->MaxList * sizeof (*SgInfo->ListRotMxInfo)); - if (SgInfo->ListRotMxInfo == NULL) NotEnoughCore(); + = malloc(SgInfo->MaxList * sizeof(*SgInfo->ListRotMxInfo)); + if (SgInfo->ListRotMxInfo == NULL) + NotEnoughCore(); #else SgInfo->ListRotMxInfo = NULL; #endif F_Convention = SgList[iSgList].Convention; - SgName = SgList[iSgList].SgName; + SgName = SgList[iSgList].SgName; tsgn = NULL; - if (F_Convention == 'A' || F_Convention == 'I') - { - tsgn = FindTabSgNameEntry(SgName, F_Convention); - if (tsgn == NULL) - { + if (F_Convention == 'A' || F_Convention == 'I') { + tsgn = FindTabSgNameEntry(SgName, F_Convention); + if (tsgn == NULL) { PrintClearSgError(1, 0); progerror("Error: Unknown Space Group Symbol"); } - if (F_Space == 0) - { + if (F_Space == 0) { fprintf(stdout, "Space Group "); PrintTabSgNameEntry(tsgn, 0, 0, stdout); putc('\n', stdout); @@ -1734,14 +1726,15 @@ int main(int argc, char *argv[]) InitSgInfo(SgInfo); SgInfo->TabSgName = tsgn; - if (tsgn) SgInfo->GenOption = 1; + if (tsgn) + SgInfo->GenOption = 1; pos_hsym = ParseHallSymbol(SgName, SgInfo); - if (SgError != NULL) - { + if (SgError != NULL) { fprintf(stdout, " %s\n", SgName); - for (i = 0; i < pos_hsym; i++) putc('-', stdout); + for (i = 0; i < pos_hsym; i++) + putc('-', stdout); fprintf(stdout, "---^\n"); fprintf(stdout, "%s\n", SgError); exit(1); @@ -1750,15 +1743,12 @@ int main(int argc, char *argv[]) if (CompleteSgInfo(SgInfo) != 0) PrintClearSgError(F_ClearError, 1); - if (tsgn == NULL && F_Space == 0) - { - if (SgInfo->TabSgName) - { + if (tsgn == NULL && F_Space == 0) { + if (SgInfo->TabSgName) { fprintf(stdout, "Space Group "); PrintTabSgNameEntry(SgInfo->TabSgName, 0, 0, stdout); putc('\n', stdout); - } - else + } else fprintf(stdout, "Hall Symbol %s\n", SgInfo->HallSymbol); } @@ -1806,19 +1796,16 @@ int main(int argc, char *argv[]) PrintClearSgError(F_ClearError, 0); } - if (nSgList > 1 || F_Standard) - { - CBMx = &SgList[iSgList].CBMx; + if (nSgList > 1 || F_Standard) { + CBMx = &SgList[iSgList].CBMx; InvCBMx = &SgList[iSgList].InvCBMx; SgList[iSgList].RefTSgN = FindReferenceSpaceGroup(SgInfo, CBMx, InvCBMx); PrintClearSgError(F_ClearError, 0); - if (SgList[iSgList].RefTSgN) - { - if (F_Verbose || F_Verify) - { + if (SgList[iSgList].RefTSgN) { + if (F_Verbose || F_Verify) { fprintf(stdout, "Change of Basis => Reference Setting "); PrintTabSgNameEntry(SgList[iSgList].RefTSgN, 0, 0, stdout); putc('\n', stdout); @@ -1827,19 +1814,22 @@ int main(int argc, char *argv[]) PrintClearSgError(F_ClearError, 0); } - if (F_Verify) - { - if (BC_SgInfo.MaxList == 0) - { + if (F_Verify) { + if (BC_SgInfo.MaxList == 0) { BC_SgInfo.MaxList = 192; BC_SgInfo.ListSeitzMx - = malloc(BC_SgInfo.MaxList * sizeof (*BC_SgInfo.ListSeitzMx)); - if (BC_SgInfo.ListSeitzMx == NULL) NotEnoughCore(); + = + malloc(BC_SgInfo.MaxList * sizeof(*BC_SgInfo.ListSeitzMx)); + if (BC_SgInfo.ListSeitzMx == NULL) + NotEnoughCore(); BC_SgInfo.ListRotMxInfo - = malloc(BC_SgInfo.MaxList * sizeof (*BC_SgInfo.ListRotMxInfo)); - if (BC_SgInfo.ListRotMxInfo == NULL) NotEnoughCore(); + = + malloc(BC_SgInfo.MaxList * + sizeof(*BC_SgInfo.ListRotMxInfo)); + if (BC_SgInfo.ListRotMxInfo == NULL) + NotEnoughCore(); } InitSgInfo(&BC_SgInfo); @@ -1847,32 +1837,27 @@ int main(int argc, char *argv[]) if (TransformSgInfo(SgInfo, CBMx, InvCBMx, &BC_SgInfo) == 0) CompleteSgInfo(&BC_SgInfo); - if (SgError) - { + if (SgError) { PrintClearSgError(F_ClearError, 0); SgList[iSgList].RefTSgN = NULL; - } - else if (BC_SgInfo.TabSgName != SgList[iSgList].RefTSgN) - { + } else if (BC_SgInfo.TabSgName != SgList[iSgList].RefTSgN) { fprintf(stdout, "Hall Symbol %s\n", BC_SgInfo.HallSymbol); SetSgError("Verify Error: Wrong CBMx/InvCBMx"); PrintClearSgError(F_ClearError, 0); SgList[iSgList].RefTSgN = NULL; - } - else + } else fprintf(stdout, "Verify O.K.\n\n"); } } - tsgn = SgList[iSgList].RefTSgN; - if (tsgn && F_Standard && nSgList == 1) - { + tsgn = SgList[iSgList].RefTSgN; + if (tsgn && F_Standard && nSgList == 1) { if (Last_F_Convention == 'A' || Last_F_Convention == 'I') SgList[nSgList].Convention = Last_F_Convention; else SgList[nSgList].Convention = 'A'; - SgList[nSgList].SgName = SchoenfliesSymbols[tsgn->SgNumber]; + SgList[nSgList].SgName = SchoenfliesSymbols[tsgn->SgNumber]; SgList[nSgList].InpTSgN = NULL; SgList[nSgList].RefTSgN = NULL; @@ -1881,60 +1866,54 @@ int main(int argc, char *argv[]) } } - if ( nSgList == 2 - && SgList[0].RefTSgN && SgList[1].RefTSgN - && SgList[0].RefTSgN->SgNumber == SgList[1].RefTSgN->SgNumber) - { + if (nSgList == 2 + && SgList[0].RefTSgN && SgList[1].RefTSgN + && SgList[0].RefTSgN->SgNumber == SgList[1].RefTSgN->SgNumber) { putc('\n', stdout); fprintf(stdout, "Change of Basis Setting A -> Setting B:\n"); - RTMxMultiply( &CCBMx, &SgList[1].InvCBMx, &SgList[0].CBMx, + RTMxMultiply(&CCBMx, &SgList[1].InvCBMx, &SgList[0].CBMx, CRBF, CRBF * CTBF); RTMxMultiply(&CInvCBMx, &SgList[0].InvCBMx, &SgList[1].CBMx, CRBF, CRBF * CTBF); - for (i = 0; i < 12; i++) - { - if ( CCBMx.a[i] % CRBF) break; - if (CInvCBMx.a[i] % CRBF) break; + for (i = 0; i < 12; i++) { + if (CCBMx.a[i] % CRBF) + break; + if (CInvCBMx.a[i] % CRBF) + break; - CCBMx.a[i] /= CRBF; + CCBMx.a[i] /= CRBF; CInvCBMx.a[i] /= CRBF; } - if (i < 12) - { + if (i < 12) { SetSgError("Internal Error: Can't combine CBMx's"); PrintClearSgError(1, 1); - } - else - { + } else { ShowCBMx(&CCBMx, &CInvCBMx, F_Maple); PrintClearSgError(F_ClearError, 0); - if (F_Verify) - { + if (F_Verify) { InitSgInfo(&BC_SgInfo); - if (TransformSgInfo(&SpgrInfo[0], &CCBMx, &CInvCBMx, &BC_SgInfo) == 0) + if (TransformSgInfo(&SpgrInfo[0], &CCBMx, &CInvCBMx, &BC_SgInfo) == + 0) CompleteSgInfo(&BC_SgInfo); if (SgError) PrintClearSgError(F_ClearError, 1); - else if (strcmp(SpgrInfo[1].HallSymbol, BC_SgInfo.HallSymbol) != 0) - { + else if (strcmp(SpgrInfo[1].HallSymbol, BC_SgInfo.HallSymbol) != 0) { fprintf(stdout, "Hall Symbol %s\n", SpgrInfo[1].HallSymbol); fprintf(stdout, "Hall Symbol %s\n", BC_SgInfo.HallSymbol); SetSgError("Verify Error: Wrong CBMx/InvCBMx"); PrintClearSgError(F_ClearError, 1); - } - else + } else fprintf(stdout, "Verify O.K.\n"); } - if (F_UnitCell) - { + if (F_UnitCell) { putc('\n', stdout); if (TransformLatticeConstants(&LatConA, F_UnitCell, @@ -1943,24 +1922,22 @@ int main(int argc, char *argv[]) PrintClearSgError(0, 1); fprintf(stdout, - "Setting A UnitCell %.6g %.6g %.6g %.6g %.6g %.6g\n", - LatConA.a, LatConA.b, LatConA.c, - LatConA.alpha / PIover180, - LatConA.beta / PIover180, - LatConA.gamma / PIover180); + "Setting A UnitCell %.6g %.6g %.6g %.6g %.6g %.6g\n", + LatConA.a, LatConA.b, LatConA.c, + LatConA.alpha / PIover180, + LatConA.beta / PIover180, LatConA.gamma / PIover180); fprintf(stdout, - "Setting B UnitCell %.6g %.6g %.6g %.6g %.6g %.6g\n", - LatConB.a, LatConB.b, LatConB.c, - LatConB.alpha / PIover180, - LatConB.beta / PIover180, - LatConB.gamma / PIover180); + "Setting B UnitCell %.6g %.6g %.6g %.6g %.6g %.6g\n", + LatConB.a, LatConB.b, LatConB.c, + LatConB.alpha / PIover180, + LatConB.beta / PIover180, LatConB.gamma / PIover180); } } putc('\n', stdout); } - exit(0); /* old VAX didn't like "return 0;" */ + exit(0); /* old VAX didn't like "return 0;" */ return 0; } diff --git a/sginfo.h b/sginfo.h index 7266458c..adb23c1f 100644 --- a/sginfo.h +++ b/sginfo.h @@ -11,92 +11,84 @@ extern const char *SgError; #ifdef SGCOREDEF__ extern -char SgErrorBuffer[128]; +char SgErrorBuffer[128]; #endif #else const char *SgError = NULL; -char SgErrorBuffer[128]; +char SgErrorBuffer[128]; #endif -#define STBF 12 /* Seitz Matrix Translation Base Factor */ +#define STBF 12 /* Seitz Matrix Translation Base Factor */ -#define CRBF 12 /* Change of Basis Matrix Rotation Base Factor */ -#define CTBF 72 /* Change of Basis Matrix Translation Base Factor */ +#define CRBF 12 /* Change of Basis Matrix Rotation Base Factor */ +#define CTBF 72 /* Change of Basis Matrix Translation Base Factor */ /* CAUTION: (CTBF / STBF) has to be an INTEGER */ -typedef struct - { - int Code; - int nTrVector; - int *TrVector; - } - T_LatticeInfo; +typedef struct { + int Code; + int nTrVector; + int *TrVector; +} T_LatticeInfo; -typedef union - { - struct { int R[9], T[3]; } s; - int a[12]; - } - T_RTMx; +typedef union { + struct { + int R[9], T[3]; + } s; + int a[12]; +} T_RTMx; -typedef struct - { - int EigenVector[3]; - int Order; - int Inverse; - int RefAxis; - int DirCode; - } - T_RotMxInfo; +typedef struct { + int EigenVector[3]; + int Order; + int Inverse; + int RefAxis; + int DirCode; +} T_RotMxInfo; -typedef struct - { - const char *HallSymbol; - int SgNumber; - const char *Extension; - const char *SgLabels; - } - T_TabSgName; +typedef struct { + const char *HallSymbol; + int SgNumber; + const char *Extension; + const char *SgLabels; +} T_TabSgName; #define MaxLenHallSymbol 39 -typedef struct - { - int GenOption; - int Centric; - int InversionOffOrigin; - const T_LatticeInfo *LatticeInfo; - int StatusLatticeTr; - int OriginShift[3]; - int nList; - int MaxList; - T_RTMx *ListSeitzMx; - T_RotMxInfo *ListRotMxInfo; - int OrderL; - int OrderP; - int XtalSystem; - int UniqueRefAxis; - int UniqueDirCode; - int ExtraInfo; - int PointGroup; - int nGenerator; - int Generator_iList[4]; - char HallSymbol[MaxLenHallSymbol + 1]; - const T_TabSgName *TabSgName; - const int *CCMx_LP; - int n_si_Vector; - int si_Vector[9]; - int si_Modulus[3]; - } - T_SgInfo; +typedef struct { + int GenOption; + int Centric; + int InversionOffOrigin; + const T_LatticeInfo *LatticeInfo; + int StatusLatticeTr; + int OriginShift[3]; + int nList; + int MaxList; + T_RTMx *ListSeitzMx; + T_RotMxInfo *ListRotMxInfo; + int OrderL; + int OrderP; + int XtalSystem; + int UniqueRefAxis; + int UniqueDirCode; + int ExtraInfo; + int PointGroup; + int nGenerator; + int Generator_iList[4]; + char HallSymbol[MaxLenHallSymbol + 1]; + const T_TabSgName *TabSgName; + const int *CCMx_LP; + int n_si_Vector; + int si_Vector[9]; + int si_Modulus[3]; +} T_SgInfo; /* T_Sginfo.GenOption: 0 = full group generation 1 = trusted: @@ -114,16 +106,14 @@ typedef struct */ -typedef struct - { - int M; /* Multiplicity */ - int N; /* Number of equivalent hkl to follow */ - int h[24]; /* If hkl == 000 M = N = 1 */ - int k[24]; /* If hkl != 000 M = 2 * N */ - int l[24]; /* List of hkl does not contain friedel mates */ - int TH[24]; /* Phase shift relative to h[0], k[0], l[0] */ - } - T_Eq_hkl; +typedef struct { + int M; /* Multiplicity */ + int N; /* Number of equivalent hkl to follow */ + int h[24]; /* If hkl == 000 M = N = 1 */ + int k[24]; /* If hkl != 000 M = 2 * N */ + int l[24]; /* List of hkl does not contain friedel mates */ + int TH[24]; /* Phase shift relative to h[0], k[0], l[0] */ +} T_Eq_hkl; #define EI_Unknown 0 @@ -135,13 +125,12 @@ typedef struct extern const char *EI_Name[]; #else -const char *EI_Name[] = - { - "Unknown", - "Enantiomorphic", - "Obverse", - "Reverse" - }; +const char *EI_Name[] = { + "Unknown", + "Enantiomorphic", + "Obverse", + "Reverse" +}; #endif @@ -158,17 +147,16 @@ const char *EI_Name[] = extern const char *XS_Name[]; #else -const char *XS_Name[] = - { - "Unknown", - "Triclinic", - "Monoclinic", - "Orthorhombic", - "Tetragonal", - "Trigonal", - "Hexagonal", - "Cubic" - }; +const char *XS_Name[] = { + "Unknown", + "Triclinic", + "Monoclinic", + "Orthorhombic", + "Tetragonal", + "Trigonal", + "Hexagonal", + "Cubic" +}; #endif @@ -223,101 +211,99 @@ const char *XS_Name[] = extern const int LG_Code_of_PG_Index[]; #else -const int LG_Code_of_PG_Index[] = - { - PG_Unknown, - PG_1b, - PG_1b, - PG_2_m, - PG_2_m, - PG_2_m, - PG_mmm, - PG_mmm, - PG_mmm, - PG_4_m, - PG_4_m, - PG_4_m, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_3b, - PG_3b, - PG_3bm1, - PG_3b1m, - PG_3bm, - PG_3bm1, - PG_3b1m, - PG_3bm, - PG_3bm1, - PG_3b1m, - PG_3bm, - PG_6_m, - PG_6_m, - PG_6_m, - PG_6_mmm, - PG_6_mmm, - PG_6_mmm, - PG_6_mmm, - PG_6_mmm, - PG_m3b, - PG_m3b, - PG_m3bm, - PG_m3bm, - PG_m3bm - }; -#endif /* SGCLIB_C__ */ +const int LG_Code_of_PG_Index[] = { + PG_Unknown, + PG_1b, + PG_1b, + PG_2_m, + PG_2_m, + PG_2_m, + PG_mmm, + PG_mmm, + PG_mmm, + PG_4_m, + PG_4_m, + PG_4_m, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_3b, + PG_3b, + PG_3bm1, + PG_3b1m, + PG_3bm, + PG_3bm1, + PG_3b1m, + PG_3bm, + PG_3bm1, + PG_3b1m, + PG_3bm, + PG_6_m, + PG_6_m, + PG_6_m, + PG_6_mmm, + PG_6_mmm, + PG_6_mmm, + PG_6_mmm, + PG_6_mmm, + PG_m3b, + PG_m3b, + PG_m3bm, + PG_m3bm, + PG_m3bm +}; +#endif /* SGCLIB_C__ */ #ifndef SGCLIB_C__ extern const char *PG_Names[]; #else -const char *PG_Names[] = - { - "Unknown", - "1", - "-1", - "2", - "m", - "2/m", - "222", - "mm2", - "mmm", - "4", - "-4", - "4/m", - "422", - "4mm", - "-42m", - "-4m2", - "4/mmm", - "3", - "-3", - "321", - "312", - "32", - "3m1", - "31m", - "3m", - "-3m1", - "-31m", - "-3m", - "6", - "-6", - "6/m", - "622", - "6mm", - "-6m2", - "-62m", - "6/mmm", - "23", - "m-3", - "432", - "-43m", - "m-3m" - }; -#endif /* SGCLIB_C__ */ +const char *PG_Names[] = { + "Unknown", + "1", + "-1", + "2", + "m", + "2/m", + "222", + "mm2", + "mmm", + "4", + "-4", + "4/m", + "422", + "4mm", + "-42m", + "-4m2", + "4/mmm", + "3", + "-3", + "321", + "312", + "32", + "3m1", + "31m", + "3m", + "-3m1", + "-31m", + "-3m", + "6", + "-6", + "6/m", + "622", + "6mm", + "-6m2", + "-62m", + "6/mmm", + "23", + "m-3", + "432", + "-43m", + "m-3m" +}; +#endif /* SGCLIB_C__ */ #ifndef SGCLIB_C__ @@ -334,57 +320,58 @@ extern const T_LatticeInfo LI_F[]; #endif #else #define T(i) ((i) * (STBF / 12)) -static int LTr_P[] = { T(0), T(0), T(0) - }; -const T_LatticeInfo LI_P[] = {{ 'P', 1, LTr_P - }}; -static int LTr_A[] = { T(0), T(0), T(0), - T(0), T(6), T(6) - }; -const T_LatticeInfo LI_A[] = {{ 'A', 2, LTr_A - }}; -static int LTr_B[] = { T(0), T(0), T(0), - T(6), T(0), T(6) - }; -const T_LatticeInfo LI_B[] = {{ 'B', 2, LTr_B - }}; -static int LTr_C[] = { T(0), T(0), T(0), - T(6), T(6), T(0) - }; -const T_LatticeInfo LI_C[] = {{ 'C', 2, LTr_C - }}; -static int LTr_I[] = { T(0), T(0), T(0), - T(6), T(6), T(6) - }; -const T_LatticeInfo LI_I[] = {{ 'I', 2, LTr_I - }}; -static int LTr_R[] = { T(0), T(0), T(0), - T(8), T(4), T(4), - T(4), T(8), T(8) - }; -const T_LatticeInfo LI_R[] = {{ 'R', 3, LTr_R - }}; -static int LTr_S[] = { T(0), T(0), T(0), - T(4), T(4), T(8), - T(8), T(8), T(4) - }; -const T_LatticeInfo LI_S[] = {{ 'S', 3, LTr_S - }}; -static int LTr_T[] = { T(0), T(0), T(0), - T(4), T(8), T(4), - T(8), T(4), T(8) - }; -const T_LatticeInfo LI_T[] = {{ 'T', 3, LTr_T - }}; -static int LTr_F[] = { T(0), T(0), T(0), - T(0), T(6), T(6), - T(6), T(0), T(6), - T(6), T(6), T(0) - }; -const T_LatticeInfo LI_F[] = {{ 'F', 4, LTr_F - }}; +static int LTr_P[] = { T(0), T(0), T(0) +}; +const T_LatticeInfo LI_P[] = { {'P', 1, LTr_P} +}; +static int LTr_A[] = { T(0), T(0), T(0), + T(0), T(6), T(6) +}; +const T_LatticeInfo LI_A[] = { {'A', 2, LTr_A} +}; +static int LTr_B[] = { T(0), T(0), T(0), + T(6), T(0), T(6) +}; +const T_LatticeInfo LI_B[] = { {'B', 2, LTr_B} +}; +static int LTr_C[] = { T(0), T(0), T(0), + T(6), T(6), T(0) +}; +const T_LatticeInfo LI_C[] = { {'C', 2, LTr_C} +}; +static int LTr_I[] = { T(0), T(0), T(0), + T(6), T(6), T(6) +}; +const T_LatticeInfo LI_I[] = { {'I', 2, LTr_I} +}; +static int LTr_R[] = { T(0), T(0), T(0), + T(8), T(4), T(4), + T(4), T(8), T(8) +}; +const T_LatticeInfo LI_R[] = { {'R', 3, LTr_R} +}; +static int LTr_S[] = { T(0), T(0), T(0), + T(4), T(4), T(8), + T(8), T(8), T(4) +}; +const T_LatticeInfo LI_S[] = { {'S', 3, LTr_S} +}; +static int LTr_T[] = { T(0), T(0), T(0), + T(4), T(8), T(4), + T(8), T(4), T(8) +}; +const T_LatticeInfo LI_T[] = { {'T', 3, LTr_T} +}; +static int LTr_F[] = { T(0), T(0), T(0), + T(0), T(6), T(6), + T(6), T(0), T(6), + T(6), T(6), T(0) +}; +const T_LatticeInfo LI_F[] = { {'F', 4, LTr_F} +}; + #undef T -#endif /* SGCLIB_C__ */ +#endif /* SGCLIB_C__ */ /* lattice code @@ -430,78 +417,76 @@ extern const int CCMx_FP[]; #endif #else -const int CCMx_PP[] = { 1, 0, 0, /* Change of Basis Matrices */ - 0, 1, 0, /* (coordinate transformations) */ - 0, 0, 1 - }; -const int CCMx_AP[] = { -1, 0, 0, - 0, -1, 1, - 0, 1, 1 - }; -const int CCMx_BP[] = { -1, 0, 1, - 0, -1, 0, - 1, 0, 1 - }; -const int CCMx_CP[] = { 1, 1, 0, - 1, -1, 0, - 0, 0, -1 - }; -const int CCMx_IP[] = { 0, 1, 1, - 1, 0, 1, - 1, 1, 0 - }; -const int CCMx_RP_z[] = { 1, 0, 1, - -1, 1, 1, - 0, -1, 1 - }; -const int CCMx_SP_y[] = { 1, 1, -1, - -1, 1, 0, - 0, 1, 1 - }; -const int CCMx_TP_x[] = { 1, 0, -1, - 1, 1, 0, - 1, -1, 1 - }; -const int CCMx_TP_z[] = { -1, 0, 1, - 1, -1, 1, - 0, 1, 1 - }; -const int CCMx_RP_y[] = { -1, 1, 1, - 1, 1, 0, - 0, 1, -1 - }; -const int CCMx_SP_x[] = { 1, 0, 1, - 1, -1, 0, - 1, 1, -1 - }; -const int CCMx_FI_z[] = { 1, 1, 0, - -1, 1, 0, - 0, 0, 1 - }; -const int CCMx_FI_y[] = { 1, 0, -1, - 0, 1, 0, - 1, 0, 1 - }; -const int CCMx_FI_x[] = { 1, 0, 0, - 0, 1, 1, - 0, -1, 1 - }; -const int CCMx_FP[] = { -1, 1, 1, - 1, -1, 1, - 1, 1, -1 - }; -#endif /* SGCLIB_C__ */ +const int CCMx_PP[] = { 1, 0, 0, /* Change of Basis Matrices */ + 0, 1, 0, /* (coordinate transformations) */ + 0, 0, 1 +}; +const int CCMx_AP[] = { -1, 0, 0, + 0, -1, 1, + 0, 1, 1 +}; +const int CCMx_BP[] = { -1, 0, 1, + 0, -1, 0, + 1, 0, 1 +}; +const int CCMx_CP[] = { 1, 1, 0, + 1, -1, 0, + 0, 0, -1 +}; +const int CCMx_IP[] = { 0, 1, 1, + 1, 0, 1, + 1, 1, 0 +}; +const int CCMx_RP_z[] = { 1, 0, 1, + -1, 1, 1, + 0, -1, 1 +}; +const int CCMx_SP_y[] = { 1, 1, -1, + -1, 1, 0, + 0, 1, 1 +}; +const int CCMx_TP_x[] = { 1, 0, -1, + 1, 1, 0, + 1, -1, 1 +}; +const int CCMx_TP_z[] = { -1, 0, 1, + 1, -1, 1, + 0, 1, 1 +}; +const int CCMx_RP_y[] = { -1, 1, 1, + 1, 1, 0, + 0, 1, -1 +}; +const int CCMx_SP_x[] = { 1, 0, 1, + 1, -1, 0, + 1, 1, -1 +}; +const int CCMx_FI_z[] = { 1, 1, 0, + -1, 1, 0, + 0, 0, 1 +}; +const int CCMx_FI_y[] = { 1, 0, -1, + 0, 1, 0, + 1, 0, 1 +}; +const int CCMx_FI_x[] = { 1, 0, 0, + 0, 1, 1, + 0, -1, 1 +}; +const int CCMx_FP[] = { -1, 1, 1, + 1, -1, 1, + 1, 1, -1 +}; +#endif /* SGCLIB_C__ */ #if defined(SGCLIB_C__) || defined(SGCOREDEF__) -typedef struct - { - int Order; - int EigenVector[3]; - int DirCode; - int RMx[9]; - } - T_TabXtalRotMx; +typedef struct { + int Order; + int EigenVector[3]; + int DirCode; + int RMx[9]; +} T_TabXtalRotMx; #endif @@ -511,77 +496,76 @@ extern const T_TabXtalRotMx TabXtalRotMx[]; #endif #else -const T_TabXtalRotMx TabXtalRotMx[] = - { - /* # EigenVector DirCode */ +const T_TabXtalRotMx TabXtalRotMx[] = { + /* # EigenVector DirCode */ - { /* [ 0] */ 1, { 0, 0, 0 }, '.', /* CAUTION: */ - { 1, 0, 0, /* Reorganizing this table */ - 0, 1, 0, /* affects RMx_????? below. */ - 0, 0, 1 } - }, - { /* [ 1] */ 2, { 0, 0, 1 }, '=', - {-1, 0, 0, - 0, -1, 0, - 0, 0, 1 } - }, - { /* [ 2] */ 2, { 1, 0, 0 }, '=', /* hexagonal */ - { 1, -1, 0, - 0, -1, 0, - 0, 0, -1 } - }, - { /* [ 3] */ 2, { 0, 1, 0 }, '=', /* hexagonal */ - {-1, 0, 0, - -1, 1, 0, - 0, 0, -1 } - }, - { /* [ 4] */ 2, { 1, 1, 0 }, '"', - { 0, 1, 0, - 1, 0, 0, - 0, 0, -1 } - }, - { /* [ 5] */ 2, { 1, -1, 0 }, '\'', - { 0, -1, 0, - -1, 0, 0, - 0, 0, -1 } - }, - { /* [ 6] */ 2, { 2, 1, 0 }, '|', /* hexagonal */ - { 1, 0, 0, - 1, -1, 0, - 0, 0, -1 } - }, - { /* [ 7] */ 2, { 1, 2, 0 }, '\\', /* hexagonal */ - {-1, 1, 0, - 0, 1, 0, - 0, 0, -1 } - }, - { /* [ 8] */ 3, { 0, 0, 1 }, '=', - { 0, -1, 0, - 1, -1, 0, - 0, 0, 1 } - }, - { /* [ 9] */ 3, { 1, 1, 1 }, '*', - { 0, 0, 1, - 1, 0, 0, - 0, 1, 0 } - }, - { /* [10] */ 4, { 0, 0, 1 }, '=', - { 0, -1, 0, - 1, 0, 0, - 0, 0, 1 } - }, - { /* [11] */ 6, { 0, 0, 1 }, '=', - { 1, -1, 0, - 1, 0, 0, - 0, 0, 1 } - }, - { 0, { 0, 0, 0 }, 0, - { 0, 0, 0, - 0, 0, 0, - 0, 0, 0 } - } - }; -#endif /* SGCLIB_C__ */ + { /* [ 0] */ 1, {0, 0, 0}, '.', /* CAUTION: */ + {1, 0, 0, /* Reorganizing this table */ + 0, 1, 0, /* affects RMx_????? below. */ + 0, 0, 1} + }, + { /* [ 1] */ 2, {0, 0, 1}, '=', + {-1, 0, 0, + 0, -1, 0, + 0, 0, 1} + }, + { /* [ 2] */ 2, {1, 0, 0}, '=', /* hexagonal */ + {1, -1, 0, + 0, -1, 0, + 0, 0, -1} + }, + { /* [ 3] */ 2, {0, 1, 0}, '=', /* hexagonal */ + {-1, 0, 0, + -1, 1, 0, + 0, 0, -1} + }, + { /* [ 4] */ 2, {1, 1, 0}, '"', + {0, 1, 0, + 1, 0, 0, + 0, 0, -1} + }, + { /* [ 5] */ 2, {1, -1, 0}, '\'', + {0, -1, 0, + -1, 0, 0, + 0, 0, -1} + }, + { /* [ 6] */ 2, {2, 1, 0}, '|', /* hexagonal */ + {1, 0, 0, + 1, -1, 0, + 0, 0, -1} + }, + { /* [ 7] */ 2, {1, 2, 0}, '\\', /* hexagonal */ + {-1, 1, 0, + 0, 1, 0, + 0, 0, -1} + }, + { /* [ 8] */ 3, {0, 0, 1}, '=', + {0, -1, 0, + 1, -1, 0, + 0, 0, 1} + }, + { /* [ 9] */ 3, {1, 1, 1}, '*', + {0, 0, 1, + 1, 0, 0, + 0, 1, 0} + }, + { /* [10] */ 4, {0, 0, 1}, '=', + {0, -1, 0, + 1, 0, 0, + 0, 0, 1} + }, + { /* [11] */ 6, {0, 0, 1}, '=', + {1, -1, 0, + 1, 0, 0, + 0, 0, 1} + }, + {0, {0, 0, 0}, 0, + {0, 0, 0, + 0, 0, 0, + 0, 0, 0} + } +}; +#endif /* SGCLIB_C__ */ #ifndef SGCLIB_C__ @@ -597,32 +581,30 @@ const int *RMx_3_001; extern const int *RMx_3_111; extern -const int RMx_3i111[]; +const int RMx_3i111[]; extern const int *RMx_4_001; extern -const int RMx_4i001[]; +const int RMx_4i001[]; #endif #else -const int *RMx_1_000 = TabXtalRotMx[ 0].RMx; -const int *RMx_2_001 = TabXtalRotMx[ 1].RMx; -const int *RMx_2_110 = TabXtalRotMx[ 4].RMx; -const int *RMx_3_001 = TabXtalRotMx[ 8].RMx; -const int *RMx_3_111 = TabXtalRotMx[ 9].RMx; -const int RMx_3i111[] = - { - 0, 1, 0, - 0, 0, 1, - 1, 0, 0 - }; -const int *RMx_4_001 = TabXtalRotMx[10].RMx; -const int RMx_4i001[] = - { - 0, 1, 0, - -1, 0, 0, - 0, 0, 1 - }; -#endif /* SGCLIB_C__ */ +const int *RMx_1_000 = TabXtalRotMx[0].RMx; +const int *RMx_2_001 = TabXtalRotMx[1].RMx; +const int *RMx_2_110 = TabXtalRotMx[4].RMx; +const int *RMx_3_001 = TabXtalRotMx[8].RMx; +const int *RMx_3_111 = TabXtalRotMx[9].RMx; +const int RMx_3i111[] = { + 0, 1, 0, + 0, 0, 1, + 1, 0, 0 +}; +const int *RMx_4_001 = TabXtalRotMx[10].RMx; +const int RMx_4i001[] = { + 0, 1, 0, + -1, 0, 0, + 0, 0, 1 +}; +#endif /* SGCLIB_C__ */ #ifndef SGCLIB_C__ @@ -632,18 +614,18 @@ const int HallTranslations[]; #endif #else #define T(i) ((i) * (STBF / 12)) -const int HallTranslations[] = - { - 'n', T(6), T(6), T(6), - 'a', T(6), T(0), T(0), - 'b', T(0), T(6), T(0), - 'c', T(0), T(0), T(6), - 'd', T(3), T(3), T(3), - 'u', T(3), T(0), T(0), - 'v', T(0), T(3), T(0), - 'w', T(0), T(0), T(3), - 0 - }; +const int HallTranslations[] = { + 'n', T(6), T(6), T(6), + 'a', T(6), T(0), T(0), + 'b', T(0), T(6), T(0), + 'c', T(0), T(0), T(6), + 'd', T(3), T(3), T(3), + 'u', T(3), T(0), T(0), + 'v', T(0), T(3), T(0), + 'w', T(0), T(0), T(3), + 0 +}; + #undef T #endif @@ -654,241 +636,240 @@ extern const int VolAPointGroups[]; #endif #else -const int VolAPointGroups[] = - { - PG_Unknown, - PG_1, - PG_1b, - PG_2, - PG_2, - PG_2, - PG_m, - PG_m, - PG_m, - PG_m, - PG_2_m, - PG_2_m, - PG_2_m, - PG_2_m, - PG_2_m, - PG_2_m, - PG_222, - PG_222, - PG_222, - PG_222, - PG_222, - PG_222, - PG_222, - PG_222, - PG_222, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mm2, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_mmm, - PG_4, - PG_4, - PG_4, - PG_4, - PG_4, - PG_4, - PG_4b, - PG_4b, - PG_4_m, - PG_4_m, - PG_4_m, - PG_4_m, - PG_4_m, - PG_4_m, - PG_422, - PG_422, - PG_422, - PG_422, - PG_422, - PG_422, - PG_422, - PG_422, - PG_422, - PG_422, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4mm, - PG_4b2m, - PG_4b2m, - PG_4b2m, - PG_4b2m, - PG_4bm2, - PG_4bm2, - PG_4bm2, - PG_4bm2, - PG_4bm2, - PG_4bm2, - PG_4b2m, - PG_4b2m, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_4_mmm, - PG_3, - PG_3, - PG_3, - PG_3, - PG_3b, - PG_3b, - PG_312, - PG_321, - PG_312, - PG_321, - PG_312, - PG_321, - PG_32, - PG_3m1, - PG_31m, - PG_3m1, - PG_31m, - PG_3m, - PG_3m, - PG_3b1m, - PG_3b1m, - PG_3bm1, - PG_3bm1, - PG_3bm, - PG_3bm, - PG_6, - PG_6, - PG_6, - PG_6, - PG_6, - PG_6, - PG_6b, - PG_6_m, - PG_6_m, - PG_622, - PG_622, - PG_622, - PG_622, - PG_622, - PG_622, - PG_6mm, - PG_6mm, - PG_6mm, - PG_6mm, - PG_6bm2, - PG_6bm2, - PG_6b2m, - PG_6b2m, - PG_6_mmm, - PG_6_mmm, - PG_6_mmm, - PG_6_mmm, - PG_23, - PG_23, - PG_23, - PG_23, - PG_23, - PG_m3b, - PG_m3b, - PG_m3b, - PG_m3b, - PG_m3b, - PG_m3b, - PG_m3b, - PG_432, - PG_432, - PG_432, - PG_432, - PG_432, - PG_432, - PG_432, - PG_432, - PG_4b3m, - PG_4b3m, - PG_4b3m, - PG_4b3m, - PG_4b3m, - PG_4b3m, - PG_m3bm, - PG_m3bm, - PG_m3bm, - PG_m3bm, - PG_m3bm, - PG_m3bm, - PG_m3bm, - PG_m3bm, - PG_m3bm, - PG_m3bm - }; -#endif /* SGCLIB_C__ */ +const int VolAPointGroups[] = { + PG_Unknown, + PG_1, + PG_1b, + PG_2, + PG_2, + PG_2, + PG_m, + PG_m, + PG_m, + PG_m, + PG_2_m, + PG_2_m, + PG_2_m, + PG_2_m, + PG_2_m, + PG_2_m, + PG_222, + PG_222, + PG_222, + PG_222, + PG_222, + PG_222, + PG_222, + PG_222, + PG_222, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mm2, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_mmm, + PG_4, + PG_4, + PG_4, + PG_4, + PG_4, + PG_4, + PG_4b, + PG_4b, + PG_4_m, + PG_4_m, + PG_4_m, + PG_4_m, + PG_4_m, + PG_4_m, + PG_422, + PG_422, + PG_422, + PG_422, + PG_422, + PG_422, + PG_422, + PG_422, + PG_422, + PG_422, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4mm, + PG_4b2m, + PG_4b2m, + PG_4b2m, + PG_4b2m, + PG_4bm2, + PG_4bm2, + PG_4bm2, + PG_4bm2, + PG_4bm2, + PG_4bm2, + PG_4b2m, + PG_4b2m, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_4_mmm, + PG_3, + PG_3, + PG_3, + PG_3, + PG_3b, + PG_3b, + PG_312, + PG_321, + PG_312, + PG_321, + PG_312, + PG_321, + PG_32, + PG_3m1, + PG_31m, + PG_3m1, + PG_31m, + PG_3m, + PG_3m, + PG_3b1m, + PG_3b1m, + PG_3bm1, + PG_3bm1, + PG_3bm, + PG_3bm, + PG_6, + PG_6, + PG_6, + PG_6, + PG_6, + PG_6, + PG_6b, + PG_6_m, + PG_6_m, + PG_622, + PG_622, + PG_622, + PG_622, + PG_622, + PG_622, + PG_6mm, + PG_6mm, + PG_6mm, + PG_6mm, + PG_6bm2, + PG_6bm2, + PG_6b2m, + PG_6b2m, + PG_6_mmm, + PG_6_mmm, + PG_6_mmm, + PG_6_mmm, + PG_23, + PG_23, + PG_23, + PG_23, + PG_23, + PG_m3b, + PG_m3b, + PG_m3b, + PG_m3b, + PG_m3b, + PG_m3b, + PG_m3b, + PG_432, + PG_432, + PG_432, + PG_432, + PG_432, + PG_432, + PG_432, + PG_432, + PG_4b3m, + PG_4b3m, + PG_4b3m, + PG_4b3m, + PG_4b3m, + PG_4b3m, + PG_m3bm, + PG_m3bm, + PG_m3bm, + PG_m3bm, + PG_m3bm, + PG_m3bm, + PG_m3bm, + PG_m3bm, + PG_m3bm, + PG_m3bm +}; +#endif /* SGCLIB_C__ */ #ifndef SGCLIB_C__ @@ -897,241 +878,240 @@ extern const char *SchoenfliesSymbols[]; #endif #else -const char *SchoenfliesSymbols[] = - { - NULL, - "C1^1", - "Ci^1", - "C2^1", - "C2^2", - "C2^3", - "Cs^1", - "Cs^2", - "Cs^3", - "Cs^4", - "C2h^1", - "C2h^2", - "C2h^3", - "C2h^4", - "C2h^5", - "C2h^6", - "D2^1", - "D2^2", - "D2^3", - "D2^4", - "D2^5", - "D2^6", - "D2^7", - "D2^8", - "D2^9", - "C2v^1", - "C2v^2", - "C2v^3", - "C2v^4", - "C2v^5", - "C2v^6", - "C2v^7", - "C2v^8", - "C2v^9", - "C2v^10", - "C2v^11", - "C2v^12", - "C2v^13", - "C2v^14", - "C2v^15", - "C2v^16", - "C2v^17", - "C2v^18", - "C2v^19", - "C2v^20", - "C2v^21", - "C2v^22", - "D2h^1", - "D2h^2", - "D2h^3", - "D2h^4", - "D2h^5", - "D2h^6", - "D2h^7", - "D2h^8", - "D2h^9", - "D2h^10", - "D2h^11", - "D2h^12", - "D2h^13", - "D2h^14", - "D2h^15", - "D2h^16", - "D2h^17", - "D2h^18", - "D2h^19", - "D2h^20", - "D2h^21", - "D2h^22", - "D2h^23", - "D2h^24", - "D2h^25", - "D2h^26", - "D2h^27", - "D2h^28", - "C4^1", - "C4^2", - "C4^3", - "C4^4", - "C4^5", - "C4^6", - "S4^1", - "S4^2", - "C4h^1", - "C4h^2", - "C4h^3", - "C4h^4", - "C4h^5", - "C4h^6", - "D4^1", - "D4^2", - "D4^3", - "D4^4", - "D4^5", - "D4^6", - "D4^7", - "D4^8", - "D4^9", - "D4^10", - "C4v^1", - "C4v^2", - "C4v^3", - "C4v^4", - "C4v^5", - "C4v^6", - "C4v^7", - "C4v^8", - "C4v^9", - "C4v^10", - "C4v^11", - "C4v^12", - "D2d^1", - "D2d^2", - "D2d^3", - "D2d^4", - "D2d^5", - "D2d^6", - "D2d^7", - "D2d^8", - "D2d^9", - "D2d^10", - "D2d^11", - "D2d^12", - "D4h^1", - "D4h^2", - "D4h^3", - "D4h^4", - "D4h^5", - "D4h^6", - "D4h^7", - "D4h^8", - "D4h^9", - "D4h^10", - "D4h^11", - "D4h^12", - "D4h^13", - "D4h^14", - "D4h^15", - "D4h^16", - "D4h^17", - "D4h^18", - "D4h^19", - "D4h^20", - "C3^1", - "C3^2", - "C3^3", - "C3^4", - "C3i^1", - "C3i^2", - "D3^1", - "D3^2", - "D3^3", - "D3^4", - "D3^5", - "D3^6", - "D3^7", - "C3v^1", - "C3v^2", - "C3v^3", - "C3v^4", - "C3v^5", - "C3v^6", - "D3d^1", - "D3d^2", - "D3d^3", - "D3d^4", - "D3d^5", - "D3d^6", - "C6^1", - "C6^2", - "C6^3", - "C6^4", - "C6^5", - "C6^6", - "C3h^1", - "C6h^1", - "C6h^2", - "D6^1", - "D6^2", - "D6^3", - "D6^4", - "D6^5", - "D6^6", - "C6v^1", - "C6v^2", - "C6v^3", - "C6v^4", - "D3h^1", - "D3h^2", - "D3h^3", - "D3h^4", - "D6h^1", - "D6h^2", - "D6h^3", - "D6h^4", - "T^1", - "T^2", - "T^3", - "T^4", - "T^5", - "Th^1", - "Th^2", - "Th^3", - "Th^4", - "Th^5", - "Th^6", - "Th^7", - "O^1", - "O^2", - "O^3", - "O^4", - "O^5", - "O^6", - "O^7", - "O^8", - "Td^1", - "Td^2", - "Td^3", - "Td^4", - "Td^5", - "Td^6", - "Oh^1", - "Oh^2", - "Oh^3", - "Oh^4", - "Oh^5", - "Oh^6", - "Oh^7", - "Oh^8", - "Oh^9", - "Oh^10" - }; -#endif /* SGCLIB_C__ */ +const char *SchoenfliesSymbols[] = { + NULL, + "C1^1", + "Ci^1", + "C2^1", + "C2^2", + "C2^3", + "Cs^1", + "Cs^2", + "Cs^3", + "Cs^4", + "C2h^1", + "C2h^2", + "C2h^3", + "C2h^4", + "C2h^5", + "C2h^6", + "D2^1", + "D2^2", + "D2^3", + "D2^4", + "D2^5", + "D2^6", + "D2^7", + "D2^8", + "D2^9", + "C2v^1", + "C2v^2", + "C2v^3", + "C2v^4", + "C2v^5", + "C2v^6", + "C2v^7", + "C2v^8", + "C2v^9", + "C2v^10", + "C2v^11", + "C2v^12", + "C2v^13", + "C2v^14", + "C2v^15", + "C2v^16", + "C2v^17", + "C2v^18", + "C2v^19", + "C2v^20", + "C2v^21", + "C2v^22", + "D2h^1", + "D2h^2", + "D2h^3", + "D2h^4", + "D2h^5", + "D2h^6", + "D2h^7", + "D2h^8", + "D2h^9", + "D2h^10", + "D2h^11", + "D2h^12", + "D2h^13", + "D2h^14", + "D2h^15", + "D2h^16", + "D2h^17", + "D2h^18", + "D2h^19", + "D2h^20", + "D2h^21", + "D2h^22", + "D2h^23", + "D2h^24", + "D2h^25", + "D2h^26", + "D2h^27", + "D2h^28", + "C4^1", + "C4^2", + "C4^3", + "C4^4", + "C4^5", + "C4^6", + "S4^1", + "S4^2", + "C4h^1", + "C4h^2", + "C4h^3", + "C4h^4", + "C4h^5", + "C4h^6", + "D4^1", + "D4^2", + "D4^3", + "D4^4", + "D4^5", + "D4^6", + "D4^7", + "D4^8", + "D4^9", + "D4^10", + "C4v^1", + "C4v^2", + "C4v^3", + "C4v^4", + "C4v^5", + "C4v^6", + "C4v^7", + "C4v^8", + "C4v^9", + "C4v^10", + "C4v^11", + "C4v^12", + "D2d^1", + "D2d^2", + "D2d^3", + "D2d^4", + "D2d^5", + "D2d^6", + "D2d^7", + "D2d^8", + "D2d^9", + "D2d^10", + "D2d^11", + "D2d^12", + "D4h^1", + "D4h^2", + "D4h^3", + "D4h^4", + "D4h^5", + "D4h^6", + "D4h^7", + "D4h^8", + "D4h^9", + "D4h^10", + "D4h^11", + "D4h^12", + "D4h^13", + "D4h^14", + "D4h^15", + "D4h^16", + "D4h^17", + "D4h^18", + "D4h^19", + "D4h^20", + "C3^1", + "C3^2", + "C3^3", + "C3^4", + "C3i^1", + "C3i^2", + "D3^1", + "D3^2", + "D3^3", + "D3^4", + "D3^5", + "D3^6", + "D3^7", + "C3v^1", + "C3v^2", + "C3v^3", + "C3v^4", + "C3v^5", + "C3v^6", + "D3d^1", + "D3d^2", + "D3d^3", + "D3d^4", + "D3d^5", + "D3d^6", + "C6^1", + "C6^2", + "C6^3", + "C6^4", + "C6^5", + "C6^6", + "C3h^1", + "C6h^1", + "C6h^2", + "D6^1", + "D6^2", + "D6^3", + "D6^4", + "D6^5", + "D6^6", + "C6v^1", + "C6v^2", + "C6v^3", + "C6v^4", + "D3h^1", + "D3h^2", + "D3h^3", + "D3h^4", + "D6h^1", + "D6h^2", + "D6h^3", + "D6h^4", + "T^1", + "T^2", + "T^3", + "T^4", + "T^5", + "Th^1", + "Th^2", + "Th^3", + "Th^4", + "Th^5", + "Th^6", + "Th^7", + "O^1", + "O^2", + "O^3", + "O^4", + "O^5", + "O^6", + "O^7", + "O^8", + "Td^1", + "Td^2", + "Td^3", + "Td^4", + "Td^5", + "Td^6", + "Oh^1", + "Oh^2", + "Oh^3", + "Oh^4", + "Oh^5", + "Oh^6", + "Oh^7", + "Oh^8", + "Oh^9", + "Oh^10" +}; +#endif /* SGCLIB_C__ */ #ifndef SGCLIB_C__ @@ -1140,541 +1120,540 @@ extern const T_TabSgName TabSgName[]; #endif #else -const T_TabSgName TabSgName[] = - { - { " P 1", 1, "", "P_1" }, - { "-P 1", 2, "", "P_-1" }, - { " P 2y", 3, "b", "P_2 = P_1_2_1" }, - { " P 2", 3, "c", "P_2 = P_1_1_2" }, - { " P 2x", 3, "a", "P_2 = P_2_1_1" }, - { " P 2yb", 4, "b", "P_21 = P_1_21_1" }, - { " P 2c", 4, "c", "P_21 = P_1_1_21" }, - { " P 2xa", 4, "a", "P_21 = P_21_1_1" }, - { " C 2y", 5, "b1", "C_2 = C_1_2_1" }, - { " A 2y", 5, "b2", "C_2 = A_1_2_1" }, - { " I 2y", 5, "b3", "C_2 = I_1_2_1" }, - { " A 2", 5, "c1", "C_2 = A_1_1_2" }, - { " B 2", 5, "c2", "C_2 = B_1_1_2 = B_2" }, - { " I 2", 5, "c3", "C_2 = I_1_1_2" }, - { " B 2x", 5, "a1", "C_2 = B_2_1_1" }, - { " C 2x", 5, "a2", "C_2 = C_2_1_1" }, - { " I 2x", 5, "a3", "C_2 = I_2_1_1" }, - { " P -2y", 6, "b", "P_m = P_1_m_1" }, - { " P -2", 6, "c", "P_m = P_1_1_m" }, - { " P -2x", 6, "a", "P_m = P_m_1_1" }, - { " P -2yc", 7, "b1", "P_c = P_1_c_1" }, - { " P -2yac", 7, "b2", "P_c = P_1_n_1" }, - { " P -2ya", 7, "b3", "P_c = P_1_a_1" }, - { " P -2a", 7, "c1", "P_c = P_1_1_a" }, - { " P -2ab", 7, "c2", "P_c = P_1_1_n" }, - { " P -2b", 7, "c3", "P_c = P_1_1_b = P_b" }, - { " P -2xb", 7, "a1", "P_c = P_b_1_1" }, - { " P -2xbc", 7, "a2", "P_c = P_n_1_1" }, - { " P -2xc", 7, "a3", "P_c = P_c_1_1" }, - { " C -2y", 8, "b1", "C_m = C_1_m_1" }, - { " A -2y", 8, "b2", "C_m = A_1_m_1" }, - { " I -2y", 8, "b3", "C_m = I_1_m_1" }, - { " A -2", 8, "c1", "C_m = A_1_1_m" }, - { " B -2", 8, "c2", "C_m = B_1_1_m = B_m" }, - { " I -2", 8, "c3", "C_m = I_1_1_m" }, - { " B -2x", 8, "a1", "C_m = B_m_1_1" }, - { " C -2x", 8, "a2", "C_m = C_m_1_1" }, - { " I -2x", 8, "a3", "C_m = I_m_1_1" }, - { " C -2yc", 9, "b1", "C_c = C_1_c_1" }, - { " A -2yac", 9, "b2", "C_c = A_1_n_1" }, - { " I -2ya", 9, "b3", "C_c = I_1_a_1" }, - { " A -2ya", 9, "-b1", "C_c = A_1_a_1" }, - { " C -2ybc", 9, "-b2", "C_c = C_1_n_1" }, - { " I -2yc", 9, "-b3", "C_c = I_1_c_1" }, - { " A -2a", 9, "c1", "C_c = A_1_1_a" }, - { " B -2bc", 9, "c2", "C_c = B_1_1_n" }, - { " I -2b", 9, "c3", "C_c = I_1_1_b" }, - { " B -2b", 9, "-c1", "C_c = B_1_1_b = B_b" }, - { " A -2ac", 9, "-c2", "C_c = A_1_1_n" }, - { " I -2a", 9, "-c3", "C_c = I_1_1_a" }, - { " B -2xb", 9, "a1", "C_c = B_b_1_1" }, - { " C -2xbc", 9, "a2", "C_c = C_n_1_1" }, - { " I -2xc", 9, "a3", "C_c = I_c_1_1" }, - { " C -2xc", 9, "-a1", "C_c = C_c_1_1" }, - { " B -2xbc", 9, "-a2", "C_c = B_n_1_1" }, - { " I -2xb", 9, "-a3", "C_c = I_b_1_1" }, - { "-P 2y", 10, "b", "P_2/m = P_1_2/m_1" }, - { "-P 2", 10, "c", "P_2/m = P_1_1_2/m" }, - { "-P 2x", 10, "a", "P_2/m = P_2/m_1_1" }, - { "-P 2yb", 11, "b", "P_21/m = P_1_21/m_1" }, - { "-P 2c", 11, "c", "P_21/m = P_1_1_21/m" }, - { "-P 2xa", 11, "a", "P_21/m = P_21/m_1_1" }, - { "-C 2y", 12, "b1", "C_2/m = C_1_2/m_1" }, - { "-A 2y", 12, "b2", "C_2/m = A_1_2/m_1" }, - { "-I 2y", 12, "b3", "C_2/m = I_1_2/m_1" }, - { "-A 2", 12, "c1", "C_2/m = A_1_1_2/m" }, - { "-B 2", 12, "c2", "C_2/m = B_1_1_2/m = B_2/m" }, - { "-I 2", 12, "c3", "C_2/m = I_1_1_2/m" }, - { "-B 2x", 12, "a1", "C_2/m = B_2/m_1_1" }, - { "-C 2x", 12, "a2", "C_2/m = C_2/m_1_1" }, - { "-I 2x", 12, "a3", "C_2/m = I_2/m_1_1" }, - { "-P 2yc", 13, "b1", "P_2/c = P_1_2/c_1" }, - { "-P 2yac", 13, "b2", "P_2/c = P_1_2/n_1" }, - { "-P 2ya", 13, "b3", "P_2/c = P_1_2/a_1" }, - { "-P 2a", 13, "c1", "P_2/c = P_1_1_2/a" }, - { "-P 2ab", 13, "c2", "P_2/c = P_1_1_2/n" }, - { "-P 2b", 13, "c3", "P_2/c = P_1_1_2/b = P_2/b" }, - { "-P 2xb", 13, "a1", "P_2/c = P_2/b_1_1" }, - { "-P 2xbc", 13, "a2", "P_2/c = P_2/n_1_1" }, - { "-P 2xc", 13, "a3", "P_2/c = P_2/c_1_1" }, - { "-P 2ybc", 14, "b1", "P_21/c = P_1_21/c_1" }, - { "-P 2yn", 14, "b2", "P_21/c = P_1_21/n_1" }, - { "-P 2yab", 14, "b3", "P_21/c = P_1_21/a_1" }, - { "-P 2ac", 14, "c1", "P_21/c = P_1_1_21/a" }, - { "-P 2n", 14, "c2", "P_21/c = P_1_1_21/n" }, - { "-P 2bc", 14, "c3", "P_21/c = P_1_1_21/b = P_21/b" }, - { "-P 2xab", 14, "a1", "P_21/c = P_21/b_1_1" }, - { "-P 2xn", 14, "a2", "P_21/c = P_21/n_1_1" }, - { "-P 2xac", 14, "a3", "P_21/c = P_21/c_1_1" }, - { "-C 2yc", 15, "b1", "C_2/c = C_1_2/c_1" }, - { "-A 2yac", 15, "b2", "C_2/c = A_1_2/n_1" }, - { "-I 2ya", 15, "b3", "C_2/c = I_1_2/a_1" }, - { "-A 2ya", 15, "-b1", "C_2/c = A_1_2/a_1" }, - { "-C 2ybc", 15, "-b2", "C_2/c = C_1_2/n_1" }, - { "-I 2yc", 15, "-b3", "C_2/c = I_1_2/c_1" }, - { "-A 2a", 15, "c1", "C_2/c = A_1_1_2/a" }, - { "-B 2bc", 15, "c2", "C_2/c = B_1_1_2/n" }, - { "-I 2b", 15, "c3", "C_2/c = I_1_1_2/b" }, - { "-B 2b", 15, "-c1", "C_2/c = B_1_1_2/b = B_2/b" }, - { "-A 2ac", 15, "-c2", "C_2/c = A_1_1_2/n" }, - { "-I 2a", 15, "-c3", "C_2/c = I_1_1_2/a" }, - { "-B 2xb", 15, "a1", "C_2/c = B_2/b_1_1" }, - { "-C 2xbc", 15, "a2", "C_2/c = C_2/n_1_1" }, - { "-I 2xc", 15, "a3", "C_2/c = I_2/c_1_1" }, - { "-C 2xc", 15, "-a1", "C_2/c = C_2/c_1_1" }, - { "-B 2xbc", 15, "-a2", "C_2/c = B_2/n_1_1" }, - { "-I 2xb", 15, "-a3", "C_2/c = I_2/b_1_1" }, - { " P 2 2", 16, "", "P_2_2_2" }, - { " P 2c 2", 17, "", "P_2_2_21" }, - { " P 2a 2a", 17, "cab", "P_21_2_2" }, - { " P 2 2b", 17, "bca", "P_2_21_2" }, - { " P 2 2ab", 18, "", "P_21_21_2" }, - { " P 2bc 2", 18, "cab", "P_2_21_21" }, - { " P 2ac 2ac", 18, "bca", "P_21_2_21" }, - { " P 2ac 2ab", 19, "", "P_21_21_21" }, - { " C 2c 2", 20, "", "C_2_2_21" }, - { " A 2a 2a", 20, "cab", "A_21_2_2" }, - { " B 2 2b", 20, "bca", "B_2_21_2" }, - { " C 2 2", 21, "", "C_2_2_2" }, - { " A 2 2", 21, "cab", "A_2_2_2" }, - { " B 2 2", 21, "bca", "B_2_2_2" }, - { " F 2 2", 22, "", "F_2_2_2" }, - { " I 2 2", 23, "", "I_2_2_2" }, - { " I 2b 2c", 24, "", "I_21_21_21" }, - { " P 2 -2", 25, "", "P_m_m_2" }, - { " P -2 2", 25, "cab", "P_2_m_m" }, - { " P -2 -2", 25, "bca", "P_m_2_m" }, - { " P 2c -2", 26, "", "P_m_c_21" }, - { " P 2c -2c", 26, "ba-c", "P_c_m_21" }, - { " P -2a 2a", 26, "cab", "P_21_m_a" }, - { " P -2 2a", 26, "-cba", "P_21_a_m" }, - { " P -2 -2b", 26, "bca", "P_b_21_m" }, - { " P -2b -2", 26, "a-cb", "P_m_21_b" }, - { " P 2 -2c", 27, "", "P_c_c_2" }, - { " P -2a 2", 27, "cab", "P_2_a_a" }, - { " P -2b -2b", 27, "bca", "P_b_2_b" }, - { " P 2 -2a", 28, "", "P_m_a_2" }, - { " P 2 -2b", 28, "ba-c", "P_b_m_2" }, - { " P -2b 2", 28, "cab", "P_2_m_b" }, - { " P -2c 2", 28, "-cba", "P_2_c_m" }, - { " P -2c -2c", 28, "bca", "P_c_2_m" }, - { " P -2a -2a", 28, "a-cb", "P_m_2_a" }, - { " P 2c -2ac", 29, "", "P_c_a_21" }, - { " P 2c -2b", 29, "ba-c", "P_b_c_21" }, - { " P -2b 2a", 29, "cab", "P_21_a_b" }, - { " P -2ac 2a", 29, "-cba", "P_21_c_a" }, - { " P -2bc -2c", 29, "bca", "P_c_21_b" }, - { " P -2a -2ab", 29, "a-cb", "P_b_21_a" }, - { " P 2 -2bc", 30, "", "P_n_c_2" }, - { " P 2 -2ac", 30, "ba-c", "P_c_n_2" }, - { " P -2ac 2", 30, "cab", "P_2_n_a" }, - { " P -2ab 2", 30, "-cba", "P_2_a_n" }, - { " P -2ab -2ab", 30, "bca", "P_b_2_n" }, - { " P -2bc -2bc", 30, "a-cb", "P_n_2_b" }, - { " P 2ac -2", 31, "", "P_m_n_21" }, - { " P 2bc -2bc", 31, "ba-c", "P_n_m_21" }, - { " P -2ab 2ab", 31, "cab", "P_21_m_n" }, - { " P -2 2ac", 31, "-cba", "P_21_n_m" }, - { " P -2 -2bc", 31, "bca", "P_n_21_m" }, - { " P -2ab -2", 31, "a-cb", "P_m_21_n" }, - { " P 2 -2ab", 32, "", "P_b_a_2" }, - { " P -2bc 2", 32, "cab", "P_2_c_b" }, - { " P -2ac -2ac", 32, "bca", "P_c_2_a" }, - { " P 2c -2n", 33, "", "P_n_a_21" }, - { " P 2c -2ab", 33, "ba-c", "P_b_n_21" }, - { " P -2bc 2a", 33, "cab", "P_21_n_b" }, - { " P -2n 2a", 33, "-cba", "P_21_c_n" }, - { " P -2n -2ac", 33, "bca", "P_c_21_n" }, - { " P -2ac -2n", 33, "a-cb", "P_n_21_a" }, - { " P 2 -2n", 34, "", "P_n_n_2" }, - { " P -2n 2", 34, "cab", "P_2_n_n" }, - { " P -2n -2n", 34, "bca", "P_n_2_n" }, - { " C 2 -2", 35, "", "C_m_m_2" }, - { " A -2 2", 35, "cab", "A_2_m_m" }, - { " B -2 -2", 35, "bca", "B_m_2_m" }, - { " C 2c -2", 36, "", "C_m_c_21" }, - { " C 2c -2c", 36, "ba-c", "C_c_m_21" }, - { " A -2a 2a", 36, "cab", "A_21_m_a" }, - { " A -2 2a", 36, "-cba", "A_21_a_m" }, - { " B -2 -2b", 36, "bca", "B_b_21_m" }, - { " B -2b -2", 36, "a-cb", "B_m_21_b" }, - { " C 2 -2c", 37, "", "C_c_c_2" }, - { " A -2a 2", 37, "cab", "A_2_a_a" }, - { " B -2b -2b", 37, "bca", "B_b_2_b" }, - { " A 2 -2", 38, "", "A_m_m_2" }, - { " B 2 -2", 38, "ba-c", "B_m_m_2" }, - { " B -2 2", 38, "cab", "B_2_m_m" }, - { " C -2 2", 38, "-cba", "C_2_m_m" }, - { " C -2 -2", 38, "bca", "C_m_2_m" }, - { " A -2 -2", 38, "a-cb", "A_m_2_m" }, - { " A 2 -2c", 39, "", "A_b_m_2" }, - { " B 2 -2c", 39, "ba-c", "B_m_a_2" }, - { " B -2c 2", 39, "cab", "B_2_c_m" }, - { " C -2b 2", 39, "-cba", "C_2_m_b" }, - { " C -2b -2b", 39, "bca", "C_m_2_a" }, - { " A -2c -2c", 39, "a-cb", "A_c_2_m" }, - { " A 2 -2a", 40, "", "A_m_a_2" }, - { " B 2 -2b", 40, "ba-c", "B_b_m_2" }, - { " B -2b 2", 40, "cab", "B_2_m_b" }, - { " C -2c 2", 40, "-cba", "C_2_c_m" }, - { " C -2c -2c", 40, "bca", "C_c_2_m" }, - { " A -2a -2a", 40, "a-cb", "A_m_2_a" }, - { " A 2 -2ac", 41, "", "A_b_a_2" }, - { " B 2 -2bc", 41, "ba-c", "B_b_a_2" }, - { " B -2bc 2", 41, "cab", "B_2_c_b" }, - { " C -2bc 2", 41, "-cba", "C_2_c_b" }, - { " C -2bc -2bc", 41, "bca", "C_c_2_a" }, - { " A -2ac -2ac", 41, "a-cb", "A_c_2_a" }, - { " F 2 -2", 42, "", "F_m_m_2" }, - { " F -2 2", 42, "cab", "F_2_m_m" }, - { " F -2 -2", 42, "bca", "F_m_2_m" }, - { " F 2 -2d", 43, "", "F_d_d_2" }, - { " F -2d 2", 43, "cab", "F_2_d_d" }, - { " F -2d -2d", 43, "bca", "F_d_2_d" }, - { " I 2 -2", 44, "", "I_m_m_2" }, - { " I -2 2", 44, "cab", "I_2_m_m" }, - { " I -2 -2", 44, "bca", "I_m_2_m" }, - { " I 2 -2c", 45, "", "I_b_a_2" }, - { " I -2a 2", 45, "cab", "I_2_c_b" }, - { " I -2b -2b", 45, "bca", "I_c_2_a" }, - { " I 2 -2a", 46, "", "I_m_a_2" }, - { " I 2 -2b", 46, "ba-c", "I_b_m_2" }, - { " I -2b 2", 46, "cab", "I_2_m_b" }, - { " I -2c 2", 46, "-cba", "I_2_c_m" }, - { " I -2c -2c", 46, "bca", "I_c_2_m" }, - { " I -2a -2a", 46, "a-cb", "I_m_2_a" }, - { "-P 2 2", 47, "", "P_m_m_m" }, - { " P 2 2 -1n", 48, "1", "P_n_n_n" }, - { "-P 2ab 2bc", 48, "2", "P_n_n_n" }, - { "-P 2 2c", 49, "", "P_c_c_m" }, - { "-P 2a 2", 49, "cab", "P_m_a_a" }, - { "-P 2b 2b", 49, "bca", "P_b_m_b" }, - { " P 2 2 -1ab", 50, "1", "P_b_a_n" }, - { "-P 2ab 2b", 50, "2", "P_b_a_n" }, - { " P 2 2 -1bc", 50, "1cab", "P_n_c_b" }, - { "-P 2b 2bc", 50, "2cab", "P_n_c_b" }, - { " P 2 2 -1ac", 50, "1bca", "P_c_n_a" }, - { "-P 2a 2c", 50, "2bca", "P_c_n_a" }, - { "-P 2a 2a", 51, "", "P_m_m_a" }, - { "-P 2b 2", 51, "ba-c", "P_m_m_b" }, - { "-P 2 2b", 51, "cab", "P_b_m_m" }, - { "-P 2c 2c", 51, "-cba", "P_c_m_m" }, - { "-P 2c 2", 51, "bca", "P_m_c_m" }, - { "-P 2 2a", 51, "a-cb", "P_m_a_m" }, - { "-P 2a 2bc", 52, "", "P_n_n_a" }, - { "-P 2b 2n", 52, "ba-c", "P_n_n_b" }, - { "-P 2n 2b", 52, "cab", "P_b_n_n" }, - { "-P 2ab 2c", 52, "-cba", "P_c_n_n" }, - { "-P 2ab 2n", 52, "bca", "P_n_c_n" }, - { "-P 2n 2bc", 52, "a-cb", "P_n_a_n" }, - { "-P 2ac 2", 53, "", "P_m_n_a" }, - { "-P 2bc 2bc", 53, "ba-c", "P_n_m_b" }, - { "-P 2ab 2ab", 53, "cab", "P_b_m_n" }, - { "-P 2 2ac", 53, "-cba", "P_c_n_m" }, - { "-P 2 2bc", 53, "bca", "P_n_c_m" }, - { "-P 2ab 2", 53, "a-cb", "P_m_a_n" }, - { "-P 2a 2ac", 54, "", "P_c_c_a" }, - { "-P 2b 2c", 54, "ba-c", "P_c_c_b" }, - { "-P 2a 2b", 54, "cab", "P_b_a_a" }, - { "-P 2ac 2c", 54, "-cba", "P_c_a_a" }, - { "-P 2bc 2b", 54, "bca", "P_b_c_b" }, - { "-P 2b 2ab", 54, "a-cb", "P_b_a_b" }, - { "-P 2 2ab", 55, "", "P_b_a_m" }, - { "-P 2bc 2", 55, "cab", "P_m_c_b" }, - { "-P 2ac 2ac", 55, "bca", "P_c_m_a" }, - { "-P 2ab 2ac", 56, "", "P_c_c_n" }, - { "-P 2ac 2bc", 56, "cab", "P_n_a_a" }, - { "-P 2bc 2ab", 56, "bca", "P_b_n_b" }, - { "-P 2c 2b", 57, "", "P_b_c_m" }, - { "-P 2c 2ac", 57, "ba-c", "P_c_a_m" }, - { "-P 2ac 2a", 57, "cab", "P_m_c_a" }, - { "-P 2b 2a", 57, "-cba", "P_m_a_b" }, - { "-P 2a 2ab", 57, "bca", "P_b_m_a" }, - { "-P 2bc 2c", 57, "a-cb", "P_c_m_b" }, - { "-P 2 2n", 58, "", "P_n_n_m" }, - { "-P 2n 2", 58, "cab", "P_m_n_n" }, - { "-P 2n 2n", 58, "bca", "P_n_m_n" }, - { " P 2 2ab -1ab", 59, "1", "P_m_m_n" }, - { "-P 2ab 2a", 59, "2", "P_m_m_n" }, - { " P 2bc 2 -1bc", 59, "1cab", "P_n_m_m" }, - { "-P 2c 2bc", 59, "2cab", "P_n_m_m" }, - { " P 2ac 2ac -1ac", 59, "1bca", "P_m_n_m" }, - { "-P 2c 2a", 59, "2bca", "P_m_n_m" }, - { "-P 2n 2ab", 60, "", "P_b_c_n" }, - { "-P 2n 2c", 60, "ba-c", "P_c_a_n" }, - { "-P 2a 2n", 60, "cab", "P_n_c_a" }, - { "-P 2bc 2n", 60, "-cba", "P_n_a_b" }, - { "-P 2ac 2b", 60, "bca", "P_b_n_a" }, - { "-P 2b 2ac", 60, "a-cb", "P_c_n_b" }, - { "-P 2ac 2ab", 61, "", "P_b_c_a" }, - { "-P 2bc 2ac", 61, "ba-c", "P_c_a_b" }, - { "-P 2ac 2n", 62, "", "P_n_m_a" }, - { "-P 2bc 2a", 62, "ba-c", "P_m_n_b" }, - { "-P 2c 2ab", 62, "cab", "P_b_n_m" }, - { "-P 2n 2ac", 62, "-cba", "P_c_m_n" }, - { "-P 2n 2a", 62, "bca", "P_m_c_n" }, - { "-P 2c 2n", 62, "a-cb", "P_n_a_m" }, - { "-C 2c 2", 63, "", "C_m_c_m" }, - { "-C 2c 2c", 63, "ba-c", "C_c_m_m" }, - { "-A 2a 2a", 63, "cab", "A_m_m_a" }, - { "-A 2 2a", 63, "-cba", "A_m_a_m" }, - { "-B 2 2b", 63, "bca", "B_b_m_m" }, - { "-B 2b 2", 63, "a-cb", "B_m_m_b" }, - { "-C 2bc 2", 64, "", "C_m_c_a" }, - { "-C 2bc 2bc", 64, "ba-c", "C_c_m_b" }, - { "-A 2ac 2ac", 64, "cab", "A_b_m_a" }, - { "-A 2 2ac", 64, "-cba", "A_c_a_m" }, - { "-B 2 2bc", 64, "bca", "B_b_c_m" }, - { "-B 2bc 2", 64, "a-cb", "B_m_a_b" }, - { "-C 2 2", 65, "", "C_m_m_m" }, - { "-A 2 2", 65, "cab", "A_m_m_m" }, - { "-B 2 2", 65, "bca", "B_m_m_m" }, - { "-C 2 2c", 66, "", "C_c_c_m" }, - { "-A 2a 2", 66, "cab", "A_m_a_a" }, - { "-B 2b 2b", 66, "bca", "B_b_m_b" }, - { "-C 2b 2", 67, "", "C_m_m_a" }, - { "-C 2b 2b", 67, "ba-c", "C_m_m_b" }, - { "-A 2c 2c", 67, "cab", "A_b_m_m" }, - { "-A 2 2c", 67, "-cba", "A_c_m_m" }, - { "-B 2 2c", 67, "bca", "B_m_c_m" }, - { "-B 2c 2", 67, "a-cb", "B_m_a_m" }, - { " C 2 2 -1bc", 68, "1", "C_c_c_a" }, - { "-C 2b 2bc", 68, "2", "C_c_c_a" }, - { " C 2 2 -1bc", 68, "1ba-c", "C_c_c_b" }, - { "-C 2b 2c", 68, "2ba-c", "C_c_c_b" }, - { " A 2 2 -1ac", 68, "1cab", "A_b_a_a" }, - { "-A 2a 2c", 68, "2cab", "A_b_a_a" }, - { " A 2 2 -1ac", 68, "1-cba", "A_c_a_a" }, - { "-A 2ac 2c", 68, "2-cba", "A_c_a_a" }, - { " B 2 2 -1bc", 68, "1bca", "B_b_c_b" }, - { "-B 2bc 2b", 68, "2bca", "B_b_c_b" }, - { " B 2 2 -1bc", 68, "1a-cb", "B_b_a_b" }, - { "-B 2b 2bc", 68, "2a-cb", "B_b_a_b" }, - { "-F 2 2", 69, "", "F_m_m_m" }, - { " F 2 2 -1d", 70, "1", "F_d_d_d" }, - { "-F 2uv 2vw", 70, "2", "F_d_d_d" }, - { "-I 2 2", 71, "", "I_m_m_m" }, - { "-I 2 2c", 72, "", "I_b_a_m" }, - { "-I 2a 2", 72, "cab", "I_m_c_b" }, - { "-I 2b 2b", 72, "bca", "I_c_m_a" }, - { "-I 2b 2c", 73, "", "I_b_c_a" }, - { "-I 2a 2b", 73, "ba-c", "I_c_a_b" }, - { "-I 2b 2", 74, "", "I_m_m_a" }, - { "-I 2a 2a", 74, "ba-c", "I_m_m_b" }, - { "-I 2c 2c", 74, "cab", "I_b_m_m" }, - { "-I 2 2b", 74, "-cba", "I_c_m_m" }, - { "-I 2 2a", 74, "bca", "I_m_c_m" }, - { "-I 2c 2", 74, "a-cb", "I_m_a_m" }, - { " P 4", 75, "", "P_4" }, - { " P 4w", 76, "", "P_41" }, - { " P 4c", 77, "", "P_42" }, - { " P 4cw", 78, "", "P_43" }, - { " I 4", 79, "", "I_4" }, - { " I 4bw", 80, "", "I_41" }, - { " P -4", 81, "", "P_-4" }, - { " I -4", 82, "", "I_-4" }, - { "-P 4", 83, "", "P_4/m" }, - { "-P 4c", 84, "", "P_42/m" }, - { " P 4ab -1ab", 85, "1", "P_4/n" }, - { "-P 4a", 85, "2", "P_4/n" }, - { " P 4n -1n", 86, "1", "P_42/n" }, - { "-P 4bc", 86, "2", "P_42/n" }, - { "-I 4", 87, "", "I_4/m" }, - { " I 4bw -1bw", 88, "1", "I_41/a" }, - { "-I 4ad", 88, "2", "I_41/a" }, - { " P 4 2", 89, "", "P_4_2_2" }, - { " P 4ab 2ab", 90, "", "P_42_1_2" }, - { " P 4w 2c", 91, "", "P_41_2_2" }, - { " P 4abw 2nw", 92, "", "P_41_21_2" }, - { " P 4c 2", 93, "", "P_42_2_2" }, - { " P 4n 2n", 94, "", "P_42_21_2" }, - { " P 4cw 2c", 95, "", "P_43_2_2" }, - { " P 4nw 2abw", 96, "", "P_43_21_2" }, - { " I 4 2", 97, "", "I_4_2_2" }, - { " I 4bw 2bw", 98, "", "I_41_2_2" }, - { " P 4 -2", 99, "", "P_4_m_m" }, - { " P 4 -2ab", 100, "", "P_4_b_m" }, - { " P 4c -2c", 101, "", "P_42_c_m" }, - { " P 4n -2n", 102, "", "P_42_n_m" }, - { " P 4 -2c", 103, "", "P_4_c_c" }, - { " P 4 -2n", 104, "", "P_4_n_c" }, - { " P 4c -2", 105, "", "P_42_m_c" }, - { " P 4c -2ab", 106, "", "P_42_b_c" }, - { " I 4 -2", 107, "", "I_4_m_m" }, - { " I 4 -2c", 108, "", "I_4_c_m" }, - { " I 4bw -2", 109, "", "I_41_m_d" }, - { " I 4bw -2c", 110, "", "I_41_c_d" }, - { " P -4 2", 111, "", "P_-4_2_m" }, - { " P -4 2c", 112, "", "P_-4_2_c" }, - { " P -4 2ab", 113, "", "P_-4_21_m" }, - { " P -4 2n", 114, "", "P_-4_21_c" }, - { " P -4 -2", 115, "", "P_-4_m_2" }, - { " P -4 -2c", 116, "", "P_-4_c_2" }, - { " P -4 -2ab", 117, "", "P_-4_b_2" }, - { " P -4 -2n", 118, "", "P_-4_n_2" }, - { " I -4 -2", 119, "", "I_-4_m_2" }, - { " I -4 -2c", 120, "", "I_-4_c_2" }, - { " I -4 2", 121, "", "I_-4_2_m" }, - { " I -4 2bw", 122, "", "I_-4_2_d" }, - { "-P 4 2", 123, "", "P_4/m_m_m" }, - { "-P 4 2c", 124, "", "P_4/m_c_c" }, - { " P 4 2 -1ab", 125, "1", "P_4/n_b_m" }, - { "-P 4a 2b", 125, "2", "P_4/n_b_m" }, - { " P 4 2 -1n", 126, "1", "P_4/n_n_c" }, - { "-P 4a 2bc", 126, "2", "P_4/n_n_c" }, - { "-P 4 2ab", 127, "", "P_4/m_b_m" }, - { "-P 4 2n", 128, "", "P_4/m_n_c" }, - { " P 4ab 2ab -1ab", 129, "1", "P_4/n_m_m" }, - { "-P 4a 2a", 129, "2", "P_4/n_m_m" }, - { " P 4ab 2n -1ab", 130, "1", "P_4/n_c_c" }, - { "-P 4a 2ac", 130, "2", "P_4/n_c_c" }, - { "-P 4c 2", 131, "", "P_42/m_m_c" }, - { "-P 4c 2c", 132, "", "P_42/m_c_m" }, - { " P 4n 2c -1n", 133, "1", "P_42/n_b_c" }, - { "-P 4ac 2b", 133, "2", "P_42/n_b_c" }, - { " P 4n 2 -1n", 134, "1", "P_42/n_n_m" }, - { "-P 4ac 2bc", 134, "2", "P_42/n_n_m" }, - { "-P 4c 2ab", 135, "", "P_42/m_b_c" }, - { "-P 4n 2n", 136, "", "P_42/m_n_m" }, - { " P 4n 2n -1n", 137, "1", "P_42/n_m_c" }, - { "-P 4ac 2a", 137, "2", "P_42/n_m_c" }, - { " P 4n 2ab -1n", 138, "1", "P_42/n_c_m" }, - { "-P 4ac 2ac", 138, "2", "P_42/n_c_m" }, - { "-I 4 2", 139, "", "I_4/m_m_m" }, - { "-I 4 2c", 140, "", "I_4/m_c_m" }, - { " I 4bw 2bw -1bw", 141, "1", "I_41/a_m_d" }, - { "-I 4bd 2", 141, "2", "I_41/a_m_d" }, - { " I 4bw 2aw -1bw", 142, "1", "I_41/a_c_d" }, - { "-I 4bd 2c", 142, "2", "I_41/a_c_d" }, - { " P 3", 143, "", "P_3" }, - { " P 31", 144, "", "P_31" }, - { " P 32", 145, "", "P_32" }, - { " R 3", 146, "H", "R_3" }, - { " P 3*", 146, "R", "R_3" }, - { "-P 3", 147, "", "P_-3" }, - { "-R 3", 148, "H", "R_-3" }, - { "-P 3*", 148, "R", "R_-3" }, - { " P 3 2", 149, "", "P_3_1_2" }, - { " P 3 2\"", 150, "", "P_3_2_1" }, - { " P 31 2c (0 0 1)", 151, "", "P_31_1_2" }, - { " P 31 2\"", 152, "", "P_31_2_1" }, - { " P 32 2c (0 0 -1)", 153, "", "P_32_1_2" }, - { " P 32 2\"", 154, "", "P_32_2_1" }, - { " R 3 2\"", 155, "H", "R_32" }, - { " P 3* 2", 155, "R", "R_32" }, - { " P 3 -2\"", 156, "", "P_3_m_1" }, - { " P 3 -2", 157, "", "P_3_1_m" }, - { " P 3 -2\"c", 158, "", "P_3_c_1" }, - { " P 3 -2c", 159, "", "P_3_1_c" }, - { " R 3 -2\"", 160, "H", "R_3_m" }, - { " P 3* -2", 160, "R", "R_3_m" }, - { " R 3 -2\"c", 161, "H", "R_3_c" }, - { " P 3* -2n", 161, "R", "R_3_c" }, - { "-P 3 2", 162, "", "P_-3_1_m" }, - { "-P 3 2c", 163, "", "P_-3_1_c" }, - { "-P 3 2\"", 164, "", "P_-3_m_1" }, - { "-P 3 2\"c", 165, "", "P_-3_c_1" }, - { "-R 3 2\"", 166, "H", "R_-3_m" }, - { "-P 3* 2", 166, "R", "R_-3_m" }, - { "-R 3 2\"c", 167, "H", "R_-3_c" }, - { "-P 3* 2n", 167, "R", "R_-3_c" }, - { " P 6", 168, "", "P_6" }, - { " P 61", 169, "", "P_61" }, - { " P 65", 170, "", "P_65" }, - { " P 62", 171, "", "P_62" }, - { " P 64", 172, "", "P_64" }, - { " P 6c", 173, "", "P_63" }, - { " P -6", 174, "", "P_-6" }, - { "-P 6", 175, "", "P_6/m" }, - { "-P 6c", 176, "", "P_63/m" }, - { " P 6 2", 177, "", "P_6_2_2" }, - { " P 61 2 (0 0 -1)", 178, "", "P_61_2_2" }, - { " P 65 2 (0 0 1)", 179, "", "P_65_2_2" }, - { " P 62 2c (0 0 1)", 180, "", "P_62_2_2" }, - { " P 64 2c (0 0 -1)", 181, "", "P_64_2_2" }, - { " P 6c 2c", 182, "", "P_63_2_2" }, - { " P 6 -2", 183, "", "P_6_m_m" }, - { " P 6 -2c", 184, "", "P_6_c_c" }, - { " P 6c -2", 185, "", "P_63_c_m" }, - { " P 6c -2c", 186, "", "P_63_m_c" }, - { " P -6 2", 187, "", "P_-6_m_2" }, - { " P -6c 2", 188, "", "P_-6_c_2" }, - { " P -6 -2", 189, "", "P_-6_2_m" }, - { " P -6c -2c", 190, "", "P_-6_2_c" }, - { "-P 6 2", 191, "", "P_6/m_m_m" }, - { "-P 6 2c", 192, "", "P_6/m_c_c" }, - { "-P 6c 2", 193, "", "P_63/m_c_m" }, - { "-P 6c 2c", 194, "", "P_63/m_m_c" }, - { " P 2 2 3", 195, "", "P_2_3" }, - { " F 2 2 3", 196, "", "F_2_3" }, - { " I 2 2 3", 197, "", "I_2_3" }, - { " P 2ac 2ab 3", 198, "", "P_21_3" }, - { " I 2b 2c 3", 199, "", "I_21_3" }, - { "-P 2 2 3", 200, "", "P_m_-3" }, - { " P 2 2 3 -1n", 201, "1", "P_n_-3" }, - { "-P 2ab 2bc 3", 201, "2", "P_n_-3" }, - { "-F 2 2 3", 202, "", "F_m_-3" }, - { " F 2 2 3 -1d", 203, "1", "F_d_-3" }, - { "-F 2uv 2vw 3", 203, "2", "F_d_-3" }, - { "-I 2 2 3", 204, "", "I_m_-3" }, - { "-P 2ac 2ab 3", 205, "", "P_a_-3" }, - { "-I 2b 2c 3", 206, "", "I_a_-3" }, - { " P 4 2 3", 207, "", "P_4_3_2" }, - { " P 4n 2 3", 208, "", "P_42_3_2" }, - { " F 4 2 3", 209, "", "F_4_3_2" }, - { " F 4d 2 3", 210, "", "F_41_3_2" }, - { " I 4 2 3", 211, "", "I_4_3_2" }, - { " P 4acd 2ab 3", 212, "", "P_43_3_2" }, - { " P 4bd 2ab 3", 213, "", "P_41_3_2" }, - { " I 4bd 2c 3", 214, "", "I_41_3_2" }, - { " P -4 2 3", 215, "", "P_-4_3_m" }, - { " F -4 2 3", 216, "", "F_-4_3_m" }, - { " I -4 2 3", 217, "", "I_-4_3_m" }, - { " P -4n 2 3", 218, "", "P_-4_3_n" }, - { " F -4c 2 3", 219, "", "F_-4_3_c" }, - { " I -4bd 2c 3", 220, "", "I_-4_3_d" }, - { "-P 4 2 3", 221, "", "P_m_-3_m" }, - { " P 4 2 3 -1n", 222, "1", "P_n_-3_n" }, - { "-P 4a 2bc 3", 222, "2", "P_n_-3_n" }, - { "-P 4n 2 3", 223, "", "P_m_-3_n" }, - { " P 4n 2 3 -1n", 224, "1", "P_n_-3_m" }, - { "-P 4bc 2bc 3", 224, "2", "P_n_-3_m" }, - { "-F 4 2 3", 225, "", "F_m_-3_m" }, - { "-F 4c 2 3", 226, "", "F_m_-3_c" }, - { " F 4d 2 3 -1d", 227, "1", "F_d_-3_m" }, - { "-F 4vw 2vw 3", 227, "2", "F_d_-3_m" }, - { " F 4d 2 3 -1cd", 228, "1", "F_d_-3_c" }, - { "-F 4cvw 2vw 3", 228, "2", "F_d_-3_c" }, - { "-I 4 2 3", 229, "", "I_m_-3_m" }, - { "-I 4bd 2c 3", 230, "", "I_a_-3_d" }, - { NULL, 0, NULL, NULL } - }; -#endif /* SGCLIB_C__ */ +const T_TabSgName TabSgName[] = { + {" P 1", 1, "", "P_1"}, + {"-P 1", 2, "", "P_-1"}, + {" P 2y", 3, "b", "P_2 = P_1_2_1"}, + {" P 2", 3, "c", "P_2 = P_1_1_2"}, + {" P 2x", 3, "a", "P_2 = P_2_1_1"}, + {" P 2yb", 4, "b", "P_21 = P_1_21_1"}, + {" P 2c", 4, "c", "P_21 = P_1_1_21"}, + {" P 2xa", 4, "a", "P_21 = P_21_1_1"}, + {" C 2y", 5, "b1", "C_2 = C_1_2_1"}, + {" A 2y", 5, "b2", "C_2 = A_1_2_1"}, + {" I 2y", 5, "b3", "C_2 = I_1_2_1"}, + {" A 2", 5, "c1", "C_2 = A_1_1_2"}, + {" B 2", 5, "c2", "C_2 = B_1_1_2 = B_2"}, + {" I 2", 5, "c3", "C_2 = I_1_1_2"}, + {" B 2x", 5, "a1", "C_2 = B_2_1_1"}, + {" C 2x", 5, "a2", "C_2 = C_2_1_1"}, + {" I 2x", 5, "a3", "C_2 = I_2_1_1"}, + {" P -2y", 6, "b", "P_m = P_1_m_1"}, + {" P -2", 6, "c", "P_m = P_1_1_m"}, + {" P -2x", 6, "a", "P_m = P_m_1_1"}, + {" P -2yc", 7, "b1", "P_c = P_1_c_1"}, + {" P -2yac", 7, "b2", "P_c = P_1_n_1"}, + {" P -2ya", 7, "b3", "P_c = P_1_a_1"}, + {" P -2a", 7, "c1", "P_c = P_1_1_a"}, + {" P -2ab", 7, "c2", "P_c = P_1_1_n"}, + {" P -2b", 7, "c3", "P_c = P_1_1_b = P_b"}, + {" P -2xb", 7, "a1", "P_c = P_b_1_1"}, + {" P -2xbc", 7, "a2", "P_c = P_n_1_1"}, + {" P -2xc", 7, "a3", "P_c = P_c_1_1"}, + {" C -2y", 8, "b1", "C_m = C_1_m_1"}, + {" A -2y", 8, "b2", "C_m = A_1_m_1"}, + {" I -2y", 8, "b3", "C_m = I_1_m_1"}, + {" A -2", 8, "c1", "C_m = A_1_1_m"}, + {" B -2", 8, "c2", "C_m = B_1_1_m = B_m"}, + {" I -2", 8, "c3", "C_m = I_1_1_m"}, + {" B -2x", 8, "a1", "C_m = B_m_1_1"}, + {" C -2x", 8, "a2", "C_m = C_m_1_1"}, + {" I -2x", 8, "a3", "C_m = I_m_1_1"}, + {" C -2yc", 9, "b1", "C_c = C_1_c_1"}, + {" A -2yac", 9, "b2", "C_c = A_1_n_1"}, + {" I -2ya", 9, "b3", "C_c = I_1_a_1"}, + {" A -2ya", 9, "-b1", "C_c = A_1_a_1"}, + {" C -2ybc", 9, "-b2", "C_c = C_1_n_1"}, + {" I -2yc", 9, "-b3", "C_c = I_1_c_1"}, + {" A -2a", 9, "c1", "C_c = A_1_1_a"}, + {" B -2bc", 9, "c2", "C_c = B_1_1_n"}, + {" I -2b", 9, "c3", "C_c = I_1_1_b"}, + {" B -2b", 9, "-c1", "C_c = B_1_1_b = B_b"}, + {" A -2ac", 9, "-c2", "C_c = A_1_1_n"}, + {" I -2a", 9, "-c3", "C_c = I_1_1_a"}, + {" B -2xb", 9, "a1", "C_c = B_b_1_1"}, + {" C -2xbc", 9, "a2", "C_c = C_n_1_1"}, + {" I -2xc", 9, "a3", "C_c = I_c_1_1"}, + {" C -2xc", 9, "-a1", "C_c = C_c_1_1"}, + {" B -2xbc", 9, "-a2", "C_c = B_n_1_1"}, + {" I -2xb", 9, "-a3", "C_c = I_b_1_1"}, + {"-P 2y", 10, "b", "P_2/m = P_1_2/m_1"}, + {"-P 2", 10, "c", "P_2/m = P_1_1_2/m"}, + {"-P 2x", 10, "a", "P_2/m = P_2/m_1_1"}, + {"-P 2yb", 11, "b", "P_21/m = P_1_21/m_1"}, + {"-P 2c", 11, "c", "P_21/m = P_1_1_21/m"}, + {"-P 2xa", 11, "a", "P_21/m = P_21/m_1_1"}, + {"-C 2y", 12, "b1", "C_2/m = C_1_2/m_1"}, + {"-A 2y", 12, "b2", "C_2/m = A_1_2/m_1"}, + {"-I 2y", 12, "b3", "C_2/m = I_1_2/m_1"}, + {"-A 2", 12, "c1", "C_2/m = A_1_1_2/m"}, + {"-B 2", 12, "c2", "C_2/m = B_1_1_2/m = B_2/m"}, + {"-I 2", 12, "c3", "C_2/m = I_1_1_2/m"}, + {"-B 2x", 12, "a1", "C_2/m = B_2/m_1_1"}, + {"-C 2x", 12, "a2", "C_2/m = C_2/m_1_1"}, + {"-I 2x", 12, "a3", "C_2/m = I_2/m_1_1"}, + {"-P 2yc", 13, "b1", "P_2/c = P_1_2/c_1"}, + {"-P 2yac", 13, "b2", "P_2/c = P_1_2/n_1"}, + {"-P 2ya", 13, "b3", "P_2/c = P_1_2/a_1"}, + {"-P 2a", 13, "c1", "P_2/c = P_1_1_2/a"}, + {"-P 2ab", 13, "c2", "P_2/c = P_1_1_2/n"}, + {"-P 2b", 13, "c3", "P_2/c = P_1_1_2/b = P_2/b"}, + {"-P 2xb", 13, "a1", "P_2/c = P_2/b_1_1"}, + {"-P 2xbc", 13, "a2", "P_2/c = P_2/n_1_1"}, + {"-P 2xc", 13, "a3", "P_2/c = P_2/c_1_1"}, + {"-P 2ybc", 14, "b1", "P_21/c = P_1_21/c_1"}, + {"-P 2yn", 14, "b2", "P_21/c = P_1_21/n_1"}, + {"-P 2yab", 14, "b3", "P_21/c = P_1_21/a_1"}, + {"-P 2ac", 14, "c1", "P_21/c = P_1_1_21/a"}, + {"-P 2n", 14, "c2", "P_21/c = P_1_1_21/n"}, + {"-P 2bc", 14, "c3", "P_21/c = P_1_1_21/b = P_21/b"}, + {"-P 2xab", 14, "a1", "P_21/c = P_21/b_1_1"}, + {"-P 2xn", 14, "a2", "P_21/c = P_21/n_1_1"}, + {"-P 2xac", 14, "a3", "P_21/c = P_21/c_1_1"}, + {"-C 2yc", 15, "b1", "C_2/c = C_1_2/c_1"}, + {"-A 2yac", 15, "b2", "C_2/c = A_1_2/n_1"}, + {"-I 2ya", 15, "b3", "C_2/c = I_1_2/a_1"}, + {"-A 2ya", 15, "-b1", "C_2/c = A_1_2/a_1"}, + {"-C 2ybc", 15, "-b2", "C_2/c = C_1_2/n_1"}, + {"-I 2yc", 15, "-b3", "C_2/c = I_1_2/c_1"}, + {"-A 2a", 15, "c1", "C_2/c = A_1_1_2/a"}, + {"-B 2bc", 15, "c2", "C_2/c = B_1_1_2/n"}, + {"-I 2b", 15, "c3", "C_2/c = I_1_1_2/b"}, + {"-B 2b", 15, "-c1", "C_2/c = B_1_1_2/b = B_2/b"}, + {"-A 2ac", 15, "-c2", "C_2/c = A_1_1_2/n"}, + {"-I 2a", 15, "-c3", "C_2/c = I_1_1_2/a"}, + {"-B 2xb", 15, "a1", "C_2/c = B_2/b_1_1"}, + {"-C 2xbc", 15, "a2", "C_2/c = C_2/n_1_1"}, + {"-I 2xc", 15, "a3", "C_2/c = I_2/c_1_1"}, + {"-C 2xc", 15, "-a1", "C_2/c = C_2/c_1_1"}, + {"-B 2xbc", 15, "-a2", "C_2/c = B_2/n_1_1"}, + {"-I 2xb", 15, "-a3", "C_2/c = I_2/b_1_1"}, + {" P 2 2", 16, "", "P_2_2_2"}, + {" P 2c 2", 17, "", "P_2_2_21"}, + {" P 2a 2a", 17, "cab", "P_21_2_2"}, + {" P 2 2b", 17, "bca", "P_2_21_2"}, + {" P 2 2ab", 18, "", "P_21_21_2"}, + {" P 2bc 2", 18, "cab", "P_2_21_21"}, + {" P 2ac 2ac", 18, "bca", "P_21_2_21"}, + {" P 2ac 2ab", 19, "", "P_21_21_21"}, + {" C 2c 2", 20, "", "C_2_2_21"}, + {" A 2a 2a", 20, "cab", "A_21_2_2"}, + {" B 2 2b", 20, "bca", "B_2_21_2"}, + {" C 2 2", 21, "", "C_2_2_2"}, + {" A 2 2", 21, "cab", "A_2_2_2"}, + {" B 2 2", 21, "bca", "B_2_2_2"}, + {" F 2 2", 22, "", "F_2_2_2"}, + {" I 2 2", 23, "", "I_2_2_2"}, + {" I 2b 2c", 24, "", "I_21_21_21"}, + {" P 2 -2", 25, "", "P_m_m_2"}, + {" P -2 2", 25, "cab", "P_2_m_m"}, + {" P -2 -2", 25, "bca", "P_m_2_m"}, + {" P 2c -2", 26, "", "P_m_c_21"}, + {" P 2c -2c", 26, "ba-c", "P_c_m_21"}, + {" P -2a 2a", 26, "cab", "P_21_m_a"}, + {" P -2 2a", 26, "-cba", "P_21_a_m"}, + {" P -2 -2b", 26, "bca", "P_b_21_m"}, + {" P -2b -2", 26, "a-cb", "P_m_21_b"}, + {" P 2 -2c", 27, "", "P_c_c_2"}, + {" P -2a 2", 27, "cab", "P_2_a_a"}, + {" P -2b -2b", 27, "bca", "P_b_2_b"}, + {" P 2 -2a", 28, "", "P_m_a_2"}, + {" P 2 -2b", 28, "ba-c", "P_b_m_2"}, + {" P -2b 2", 28, "cab", "P_2_m_b"}, + {" P -2c 2", 28, "-cba", "P_2_c_m"}, + {" P -2c -2c", 28, "bca", "P_c_2_m"}, + {" P -2a -2a", 28, "a-cb", "P_m_2_a"}, + {" P 2c -2ac", 29, "", "P_c_a_21"}, + {" P 2c -2b", 29, "ba-c", "P_b_c_21"}, + {" P -2b 2a", 29, "cab", "P_21_a_b"}, + {" P -2ac 2a", 29, "-cba", "P_21_c_a"}, + {" P -2bc -2c", 29, "bca", "P_c_21_b"}, + {" P -2a -2ab", 29, "a-cb", "P_b_21_a"}, + {" P 2 -2bc", 30, "", "P_n_c_2"}, + {" P 2 -2ac", 30, "ba-c", "P_c_n_2"}, + {" P -2ac 2", 30, "cab", "P_2_n_a"}, + {" P -2ab 2", 30, "-cba", "P_2_a_n"}, + {" P -2ab -2ab", 30, "bca", "P_b_2_n"}, + {" P -2bc -2bc", 30, "a-cb", "P_n_2_b"}, + {" P 2ac -2", 31, "", "P_m_n_21"}, + {" P 2bc -2bc", 31, "ba-c", "P_n_m_21"}, + {" P -2ab 2ab", 31, "cab", "P_21_m_n"}, + {" P -2 2ac", 31, "-cba", "P_21_n_m"}, + {" P -2 -2bc", 31, "bca", "P_n_21_m"}, + {" P -2ab -2", 31, "a-cb", "P_m_21_n"}, + {" P 2 -2ab", 32, "", "P_b_a_2"}, + {" P -2bc 2", 32, "cab", "P_2_c_b"}, + {" P -2ac -2ac", 32, "bca", "P_c_2_a"}, + {" P 2c -2n", 33, "", "P_n_a_21"}, + {" P 2c -2ab", 33, "ba-c", "P_b_n_21"}, + {" P -2bc 2a", 33, "cab", "P_21_n_b"}, + {" P -2n 2a", 33, "-cba", "P_21_c_n"}, + {" P -2n -2ac", 33, "bca", "P_c_21_n"}, + {" P -2ac -2n", 33, "a-cb", "P_n_21_a"}, + {" P 2 -2n", 34, "", "P_n_n_2"}, + {" P -2n 2", 34, "cab", "P_2_n_n"}, + {" P -2n -2n", 34, "bca", "P_n_2_n"}, + {" C 2 -2", 35, "", "C_m_m_2"}, + {" A -2 2", 35, "cab", "A_2_m_m"}, + {" B -2 -2", 35, "bca", "B_m_2_m"}, + {" C 2c -2", 36, "", "C_m_c_21"}, + {" C 2c -2c", 36, "ba-c", "C_c_m_21"}, + {" A -2a 2a", 36, "cab", "A_21_m_a"}, + {" A -2 2a", 36, "-cba", "A_21_a_m"}, + {" B -2 -2b", 36, "bca", "B_b_21_m"}, + {" B -2b -2", 36, "a-cb", "B_m_21_b"}, + {" C 2 -2c", 37, "", "C_c_c_2"}, + {" A -2a 2", 37, "cab", "A_2_a_a"}, + {" B -2b -2b", 37, "bca", "B_b_2_b"}, + {" A 2 -2", 38, "", "A_m_m_2"}, + {" B 2 -2", 38, "ba-c", "B_m_m_2"}, + {" B -2 2", 38, "cab", "B_2_m_m"}, + {" C -2 2", 38, "-cba", "C_2_m_m"}, + {" C -2 -2", 38, "bca", "C_m_2_m"}, + {" A -2 -2", 38, "a-cb", "A_m_2_m"}, + {" A 2 -2c", 39, "", "A_b_m_2"}, + {" B 2 -2c", 39, "ba-c", "B_m_a_2"}, + {" B -2c 2", 39, "cab", "B_2_c_m"}, + {" C -2b 2", 39, "-cba", "C_2_m_b"}, + {" C -2b -2b", 39, "bca", "C_m_2_a"}, + {" A -2c -2c", 39, "a-cb", "A_c_2_m"}, + {" A 2 -2a", 40, "", "A_m_a_2"}, + {" B 2 -2b", 40, "ba-c", "B_b_m_2"}, + {" B -2b 2", 40, "cab", "B_2_m_b"}, + {" C -2c 2", 40, "-cba", "C_2_c_m"}, + {" C -2c -2c", 40, "bca", "C_c_2_m"}, + {" A -2a -2a", 40, "a-cb", "A_m_2_a"}, + {" A 2 -2ac", 41, "", "A_b_a_2"}, + {" B 2 -2bc", 41, "ba-c", "B_b_a_2"}, + {" B -2bc 2", 41, "cab", "B_2_c_b"}, + {" C -2bc 2", 41, "-cba", "C_2_c_b"}, + {" C -2bc -2bc", 41, "bca", "C_c_2_a"}, + {" A -2ac -2ac", 41, "a-cb", "A_c_2_a"}, + {" F 2 -2", 42, "", "F_m_m_2"}, + {" F -2 2", 42, "cab", "F_2_m_m"}, + {" F -2 -2", 42, "bca", "F_m_2_m"}, + {" F 2 -2d", 43, "", "F_d_d_2"}, + {" F -2d 2", 43, "cab", "F_2_d_d"}, + {" F -2d -2d", 43, "bca", "F_d_2_d"}, + {" I 2 -2", 44, "", "I_m_m_2"}, + {" I -2 2", 44, "cab", "I_2_m_m"}, + {" I -2 -2", 44, "bca", "I_m_2_m"}, + {" I 2 -2c", 45, "", "I_b_a_2"}, + {" I -2a 2", 45, "cab", "I_2_c_b"}, + {" I -2b -2b", 45, "bca", "I_c_2_a"}, + {" I 2 -2a", 46, "", "I_m_a_2"}, + {" I 2 -2b", 46, "ba-c", "I_b_m_2"}, + {" I -2b 2", 46, "cab", "I_2_m_b"}, + {" I -2c 2", 46, "-cba", "I_2_c_m"}, + {" I -2c -2c", 46, "bca", "I_c_2_m"}, + {" I -2a -2a", 46, "a-cb", "I_m_2_a"}, + {"-P 2 2", 47, "", "P_m_m_m"}, + {" P 2 2 -1n", 48, "1", "P_n_n_n"}, + {"-P 2ab 2bc", 48, "2", "P_n_n_n"}, + {"-P 2 2c", 49, "", "P_c_c_m"}, + {"-P 2a 2", 49, "cab", "P_m_a_a"}, + {"-P 2b 2b", 49, "bca", "P_b_m_b"}, + {" P 2 2 -1ab", 50, "1", "P_b_a_n"}, + {"-P 2ab 2b", 50, "2", "P_b_a_n"}, + {" P 2 2 -1bc", 50, "1cab", "P_n_c_b"}, + {"-P 2b 2bc", 50, "2cab", "P_n_c_b"}, + {" P 2 2 -1ac", 50, "1bca", "P_c_n_a"}, + {"-P 2a 2c", 50, "2bca", "P_c_n_a"}, + {"-P 2a 2a", 51, "", "P_m_m_a"}, + {"-P 2b 2", 51, "ba-c", "P_m_m_b"}, + {"-P 2 2b", 51, "cab", "P_b_m_m"}, + {"-P 2c 2c", 51, "-cba", "P_c_m_m"}, + {"-P 2c 2", 51, "bca", "P_m_c_m"}, + {"-P 2 2a", 51, "a-cb", "P_m_a_m"}, + {"-P 2a 2bc", 52, "", "P_n_n_a"}, + {"-P 2b 2n", 52, "ba-c", "P_n_n_b"}, + {"-P 2n 2b", 52, "cab", "P_b_n_n"}, + {"-P 2ab 2c", 52, "-cba", "P_c_n_n"}, + {"-P 2ab 2n", 52, "bca", "P_n_c_n"}, + {"-P 2n 2bc", 52, "a-cb", "P_n_a_n"}, + {"-P 2ac 2", 53, "", "P_m_n_a"}, + {"-P 2bc 2bc", 53, "ba-c", "P_n_m_b"}, + {"-P 2ab 2ab", 53, "cab", "P_b_m_n"}, + {"-P 2 2ac", 53, "-cba", "P_c_n_m"}, + {"-P 2 2bc", 53, "bca", "P_n_c_m"}, + {"-P 2ab 2", 53, "a-cb", "P_m_a_n"}, + {"-P 2a 2ac", 54, "", "P_c_c_a"}, + {"-P 2b 2c", 54, "ba-c", "P_c_c_b"}, + {"-P 2a 2b", 54, "cab", "P_b_a_a"}, + {"-P 2ac 2c", 54, "-cba", "P_c_a_a"}, + {"-P 2bc 2b", 54, "bca", "P_b_c_b"}, + {"-P 2b 2ab", 54, "a-cb", "P_b_a_b"}, + {"-P 2 2ab", 55, "", "P_b_a_m"}, + {"-P 2bc 2", 55, "cab", "P_m_c_b"}, + {"-P 2ac 2ac", 55, "bca", "P_c_m_a"}, + {"-P 2ab 2ac", 56, "", "P_c_c_n"}, + {"-P 2ac 2bc", 56, "cab", "P_n_a_a"}, + {"-P 2bc 2ab", 56, "bca", "P_b_n_b"}, + {"-P 2c 2b", 57, "", "P_b_c_m"}, + {"-P 2c 2ac", 57, "ba-c", "P_c_a_m"}, + {"-P 2ac 2a", 57, "cab", "P_m_c_a"}, + {"-P 2b 2a", 57, "-cba", "P_m_a_b"}, + {"-P 2a 2ab", 57, "bca", "P_b_m_a"}, + {"-P 2bc 2c", 57, "a-cb", "P_c_m_b"}, + {"-P 2 2n", 58, "", "P_n_n_m"}, + {"-P 2n 2", 58, "cab", "P_m_n_n"}, + {"-P 2n 2n", 58, "bca", "P_n_m_n"}, + {" P 2 2ab -1ab", 59, "1", "P_m_m_n"}, + {"-P 2ab 2a", 59, "2", "P_m_m_n"}, + {" P 2bc 2 -1bc", 59, "1cab", "P_n_m_m"}, + {"-P 2c 2bc", 59, "2cab", "P_n_m_m"}, + {" P 2ac 2ac -1ac", 59, "1bca", "P_m_n_m"}, + {"-P 2c 2a", 59, "2bca", "P_m_n_m"}, + {"-P 2n 2ab", 60, "", "P_b_c_n"}, + {"-P 2n 2c", 60, "ba-c", "P_c_a_n"}, + {"-P 2a 2n", 60, "cab", "P_n_c_a"}, + {"-P 2bc 2n", 60, "-cba", "P_n_a_b"}, + {"-P 2ac 2b", 60, "bca", "P_b_n_a"}, + {"-P 2b 2ac", 60, "a-cb", "P_c_n_b"}, + {"-P 2ac 2ab", 61, "", "P_b_c_a"}, + {"-P 2bc 2ac", 61, "ba-c", "P_c_a_b"}, + {"-P 2ac 2n", 62, "", "P_n_m_a"}, + {"-P 2bc 2a", 62, "ba-c", "P_m_n_b"}, + {"-P 2c 2ab", 62, "cab", "P_b_n_m"}, + {"-P 2n 2ac", 62, "-cba", "P_c_m_n"}, + {"-P 2n 2a", 62, "bca", "P_m_c_n"}, + {"-P 2c 2n", 62, "a-cb", "P_n_a_m"}, + {"-C 2c 2", 63, "", "C_m_c_m"}, + {"-C 2c 2c", 63, "ba-c", "C_c_m_m"}, + {"-A 2a 2a", 63, "cab", "A_m_m_a"}, + {"-A 2 2a", 63, "-cba", "A_m_a_m"}, + {"-B 2 2b", 63, "bca", "B_b_m_m"}, + {"-B 2b 2", 63, "a-cb", "B_m_m_b"}, + {"-C 2bc 2", 64, "", "C_m_c_a"}, + {"-C 2bc 2bc", 64, "ba-c", "C_c_m_b"}, + {"-A 2ac 2ac", 64, "cab", "A_b_m_a"}, + {"-A 2 2ac", 64, "-cba", "A_c_a_m"}, + {"-B 2 2bc", 64, "bca", "B_b_c_m"}, + {"-B 2bc 2", 64, "a-cb", "B_m_a_b"}, + {"-C 2 2", 65, "", "C_m_m_m"}, + {"-A 2 2", 65, "cab", "A_m_m_m"}, + {"-B 2 2", 65, "bca", "B_m_m_m"}, + {"-C 2 2c", 66, "", "C_c_c_m"}, + {"-A 2a 2", 66, "cab", "A_m_a_a"}, + {"-B 2b 2b", 66, "bca", "B_b_m_b"}, + {"-C 2b 2", 67, "", "C_m_m_a"}, + {"-C 2b 2b", 67, "ba-c", "C_m_m_b"}, + {"-A 2c 2c", 67, "cab", "A_b_m_m"}, + {"-A 2 2c", 67, "-cba", "A_c_m_m"}, + {"-B 2 2c", 67, "bca", "B_m_c_m"}, + {"-B 2c 2", 67, "a-cb", "B_m_a_m"}, + {" C 2 2 -1bc", 68, "1", "C_c_c_a"}, + {"-C 2b 2bc", 68, "2", "C_c_c_a"}, + {" C 2 2 -1bc", 68, "1ba-c", "C_c_c_b"}, + {"-C 2b 2c", 68, "2ba-c", "C_c_c_b"}, + {" A 2 2 -1ac", 68, "1cab", "A_b_a_a"}, + {"-A 2a 2c", 68, "2cab", "A_b_a_a"}, + {" A 2 2 -1ac", 68, "1-cba", "A_c_a_a"}, + {"-A 2ac 2c", 68, "2-cba", "A_c_a_a"}, + {" B 2 2 -1bc", 68, "1bca", "B_b_c_b"}, + {"-B 2bc 2b", 68, "2bca", "B_b_c_b"}, + {" B 2 2 -1bc", 68, "1a-cb", "B_b_a_b"}, + {"-B 2b 2bc", 68, "2a-cb", "B_b_a_b"}, + {"-F 2 2", 69, "", "F_m_m_m"}, + {" F 2 2 -1d", 70, "1", "F_d_d_d"}, + {"-F 2uv 2vw", 70, "2", "F_d_d_d"}, + {"-I 2 2", 71, "", "I_m_m_m"}, + {"-I 2 2c", 72, "", "I_b_a_m"}, + {"-I 2a 2", 72, "cab", "I_m_c_b"}, + {"-I 2b 2b", 72, "bca", "I_c_m_a"}, + {"-I 2b 2c", 73, "", "I_b_c_a"}, + {"-I 2a 2b", 73, "ba-c", "I_c_a_b"}, + {"-I 2b 2", 74, "", "I_m_m_a"}, + {"-I 2a 2a", 74, "ba-c", "I_m_m_b"}, + {"-I 2c 2c", 74, "cab", "I_b_m_m"}, + {"-I 2 2b", 74, "-cba", "I_c_m_m"}, + {"-I 2 2a", 74, "bca", "I_m_c_m"}, + {"-I 2c 2", 74, "a-cb", "I_m_a_m"}, + {" P 4", 75, "", "P_4"}, + {" P 4w", 76, "", "P_41"}, + {" P 4c", 77, "", "P_42"}, + {" P 4cw", 78, "", "P_43"}, + {" I 4", 79, "", "I_4"}, + {" I 4bw", 80, "", "I_41"}, + {" P -4", 81, "", "P_-4"}, + {" I -4", 82, "", "I_-4"}, + {"-P 4", 83, "", "P_4/m"}, + {"-P 4c", 84, "", "P_42/m"}, + {" P 4ab -1ab", 85, "1", "P_4/n"}, + {"-P 4a", 85, "2", "P_4/n"}, + {" P 4n -1n", 86, "1", "P_42/n"}, + {"-P 4bc", 86, "2", "P_42/n"}, + {"-I 4", 87, "", "I_4/m"}, + {" I 4bw -1bw", 88, "1", "I_41/a"}, + {"-I 4ad", 88, "2", "I_41/a"}, + {" P 4 2", 89, "", "P_4_2_2"}, + {" P 4ab 2ab", 90, "", "P_42_1_2"}, + {" P 4w 2c", 91, "", "P_41_2_2"}, + {" P 4abw 2nw", 92, "", "P_41_21_2"}, + {" P 4c 2", 93, "", "P_42_2_2"}, + {" P 4n 2n", 94, "", "P_42_21_2"}, + {" P 4cw 2c", 95, "", "P_43_2_2"}, + {" P 4nw 2abw", 96, "", "P_43_21_2"}, + {" I 4 2", 97, "", "I_4_2_2"}, + {" I 4bw 2bw", 98, "", "I_41_2_2"}, + {" P 4 -2", 99, "", "P_4_m_m"}, + {" P 4 -2ab", 100, "", "P_4_b_m"}, + {" P 4c -2c", 101, "", "P_42_c_m"}, + {" P 4n -2n", 102, "", "P_42_n_m"}, + {" P 4 -2c", 103, "", "P_4_c_c"}, + {" P 4 -2n", 104, "", "P_4_n_c"}, + {" P 4c -2", 105, "", "P_42_m_c"}, + {" P 4c -2ab", 106, "", "P_42_b_c"}, + {" I 4 -2", 107, "", "I_4_m_m"}, + {" I 4 -2c", 108, "", "I_4_c_m"}, + {" I 4bw -2", 109, "", "I_41_m_d"}, + {" I 4bw -2c", 110, "", "I_41_c_d"}, + {" P -4 2", 111, "", "P_-4_2_m"}, + {" P -4 2c", 112, "", "P_-4_2_c"}, + {" P -4 2ab", 113, "", "P_-4_21_m"}, + {" P -4 2n", 114, "", "P_-4_21_c"}, + {" P -4 -2", 115, "", "P_-4_m_2"}, + {" P -4 -2c", 116, "", "P_-4_c_2"}, + {" P -4 -2ab", 117, "", "P_-4_b_2"}, + {" P -4 -2n", 118, "", "P_-4_n_2"}, + {" I -4 -2", 119, "", "I_-4_m_2"}, + {" I -4 -2c", 120, "", "I_-4_c_2"}, + {" I -4 2", 121, "", "I_-4_2_m"}, + {" I -4 2bw", 122, "", "I_-4_2_d"}, + {"-P 4 2", 123, "", "P_4/m_m_m"}, + {"-P 4 2c", 124, "", "P_4/m_c_c"}, + {" P 4 2 -1ab", 125, "1", "P_4/n_b_m"}, + {"-P 4a 2b", 125, "2", "P_4/n_b_m"}, + {" P 4 2 -1n", 126, "1", "P_4/n_n_c"}, + {"-P 4a 2bc", 126, "2", "P_4/n_n_c"}, + {"-P 4 2ab", 127, "", "P_4/m_b_m"}, + {"-P 4 2n", 128, "", "P_4/m_n_c"}, + {" P 4ab 2ab -1ab", 129, "1", "P_4/n_m_m"}, + {"-P 4a 2a", 129, "2", "P_4/n_m_m"}, + {" P 4ab 2n -1ab", 130, "1", "P_4/n_c_c"}, + {"-P 4a 2ac", 130, "2", "P_4/n_c_c"}, + {"-P 4c 2", 131, "", "P_42/m_m_c"}, + {"-P 4c 2c", 132, "", "P_42/m_c_m"}, + {" P 4n 2c -1n", 133, "1", "P_42/n_b_c"}, + {"-P 4ac 2b", 133, "2", "P_42/n_b_c"}, + {" P 4n 2 -1n", 134, "1", "P_42/n_n_m"}, + {"-P 4ac 2bc", 134, "2", "P_42/n_n_m"}, + {"-P 4c 2ab", 135, "", "P_42/m_b_c"}, + {"-P 4n 2n", 136, "", "P_42/m_n_m"}, + {" P 4n 2n -1n", 137, "1", "P_42/n_m_c"}, + {"-P 4ac 2a", 137, "2", "P_42/n_m_c"}, + {" P 4n 2ab -1n", 138, "1", "P_42/n_c_m"}, + {"-P 4ac 2ac", 138, "2", "P_42/n_c_m"}, + {"-I 4 2", 139, "", "I_4/m_m_m"}, + {"-I 4 2c", 140, "", "I_4/m_c_m"}, + {" I 4bw 2bw -1bw", 141, "1", "I_41/a_m_d"}, + {"-I 4bd 2", 141, "2", "I_41/a_m_d"}, + {" I 4bw 2aw -1bw", 142, "1", "I_41/a_c_d"}, + {"-I 4bd 2c", 142, "2", "I_41/a_c_d"}, + {" P 3", 143, "", "P_3"}, + {" P 31", 144, "", "P_31"}, + {" P 32", 145, "", "P_32"}, + {" R 3", 146, "H", "R_3"}, + {" P 3*", 146, "R", "R_3"}, + {"-P 3", 147, "", "P_-3"}, + {"-R 3", 148, "H", "R_-3"}, + {"-P 3*", 148, "R", "R_-3"}, + {" P 3 2", 149, "", "P_3_1_2"}, + {" P 3 2\"", 150, "", "P_3_2_1"}, + {" P 31 2c (0 0 1)", 151, "", "P_31_1_2"}, + {" P 31 2\"", 152, "", "P_31_2_1"}, + {" P 32 2c (0 0 -1)", 153, "", "P_32_1_2"}, + {" P 32 2\"", 154, "", "P_32_2_1"}, + {" R 3 2\"", 155, "H", "R_32"}, + {" P 3* 2", 155, "R", "R_32"}, + {" P 3 -2\"", 156, "", "P_3_m_1"}, + {" P 3 -2", 157, "", "P_3_1_m"}, + {" P 3 -2\"c", 158, "", "P_3_c_1"}, + {" P 3 -2c", 159, "", "P_3_1_c"}, + {" R 3 -2\"", 160, "H", "R_3_m"}, + {" P 3* -2", 160, "R", "R_3_m"}, + {" R 3 -2\"c", 161, "H", "R_3_c"}, + {" P 3* -2n", 161, "R", "R_3_c"}, + {"-P 3 2", 162, "", "P_-3_1_m"}, + {"-P 3 2c", 163, "", "P_-3_1_c"}, + {"-P 3 2\"", 164, "", "P_-3_m_1"}, + {"-P 3 2\"c", 165, "", "P_-3_c_1"}, + {"-R 3 2\"", 166, "H", "R_-3_m"}, + {"-P 3* 2", 166, "R", "R_-3_m"}, + {"-R 3 2\"c", 167, "H", "R_-3_c"}, + {"-P 3* 2n", 167, "R", "R_-3_c"}, + {" P 6", 168, "", "P_6"}, + {" P 61", 169, "", "P_61"}, + {" P 65", 170, "", "P_65"}, + {" P 62", 171, "", "P_62"}, + {" P 64", 172, "", "P_64"}, + {" P 6c", 173, "", "P_63"}, + {" P -6", 174, "", "P_-6"}, + {"-P 6", 175, "", "P_6/m"}, + {"-P 6c", 176, "", "P_63/m"}, + {" P 6 2", 177, "", "P_6_2_2"}, + {" P 61 2 (0 0 -1)", 178, "", "P_61_2_2"}, + {" P 65 2 (0 0 1)", 179, "", "P_65_2_2"}, + {" P 62 2c (0 0 1)", 180, "", "P_62_2_2"}, + {" P 64 2c (0 0 -1)", 181, "", "P_64_2_2"}, + {" P 6c 2c", 182, "", "P_63_2_2"}, + {" P 6 -2", 183, "", "P_6_m_m"}, + {" P 6 -2c", 184, "", "P_6_c_c"}, + {" P 6c -2", 185, "", "P_63_c_m"}, + {" P 6c -2c", 186, "", "P_63_m_c"}, + {" P -6 2", 187, "", "P_-6_m_2"}, + {" P -6c 2", 188, "", "P_-6_c_2"}, + {" P -6 -2", 189, "", "P_-6_2_m"}, + {" P -6c -2c", 190, "", "P_-6_2_c"}, + {"-P 6 2", 191, "", "P_6/m_m_m"}, + {"-P 6 2c", 192, "", "P_6/m_c_c"}, + {"-P 6c 2", 193, "", "P_63/m_c_m"}, + {"-P 6c 2c", 194, "", "P_63/m_m_c"}, + {" P 2 2 3", 195, "", "P_2_3"}, + {" F 2 2 3", 196, "", "F_2_3"}, + {" I 2 2 3", 197, "", "I_2_3"}, + {" P 2ac 2ab 3", 198, "", "P_21_3"}, + {" I 2b 2c 3", 199, "", "I_21_3"}, + {"-P 2 2 3", 200, "", "P_m_-3"}, + {" P 2 2 3 -1n", 201, "1", "P_n_-3"}, + {"-P 2ab 2bc 3", 201, "2", "P_n_-3"}, + {"-F 2 2 3", 202, "", "F_m_-3"}, + {" F 2 2 3 -1d", 203, "1", "F_d_-3"}, + {"-F 2uv 2vw 3", 203, "2", "F_d_-3"}, + {"-I 2 2 3", 204, "", "I_m_-3"}, + {"-P 2ac 2ab 3", 205, "", "P_a_-3"}, + {"-I 2b 2c 3", 206, "", "I_a_-3"}, + {" P 4 2 3", 207, "", "P_4_3_2"}, + {" P 4n 2 3", 208, "", "P_42_3_2"}, + {" F 4 2 3", 209, "", "F_4_3_2"}, + {" F 4d 2 3", 210, "", "F_41_3_2"}, + {" I 4 2 3", 211, "", "I_4_3_2"}, + {" P 4acd 2ab 3", 212, "", "P_43_3_2"}, + {" P 4bd 2ab 3", 213, "", "P_41_3_2"}, + {" I 4bd 2c 3", 214, "", "I_41_3_2"}, + {" P -4 2 3", 215, "", "P_-4_3_m"}, + {" F -4 2 3", 216, "", "F_-4_3_m"}, + {" I -4 2 3", 217, "", "I_-4_3_m"}, + {" P -4n 2 3", 218, "", "P_-4_3_n"}, + {" F -4c 2 3", 219, "", "F_-4_3_c"}, + {" I -4bd 2c 3", 220, "", "I_-4_3_d"}, + {"-P 4 2 3", 221, "", "P_m_-3_m"}, + {" P 4 2 3 -1n", 222, "1", "P_n_-3_n"}, + {"-P 4a 2bc 3", 222, "2", "P_n_-3_n"}, + {"-P 4n 2 3", 223, "", "P_m_-3_n"}, + {" P 4n 2 3 -1n", 224, "1", "P_n_-3_m"}, + {"-P 4bc 2bc 3", 224, "2", "P_n_-3_m"}, + {"-F 4 2 3", 225, "", "F_m_-3_m"}, + {"-F 4c 2 3", 226, "", "F_m_-3_c"}, + {" F 4d 2 3 -1d", 227, "1", "F_d_-3_m"}, + {"-F 4vw 2vw 3", 227, "2", "F_d_-3_m"}, + {" F 4d 2 3 -1cd", 228, "1", "F_d_-3_c"}, + {"-F 4cvw 2vw 3", 228, "2", "F_d_-3_c"}, + {"-I 4 2 3", 229, "", "I_m_-3_m"}, + {"-I 4bd 2c 3", 230, "", "I_a_-3_d"}, + {NULL, 0, NULL, NULL} +}; +#endif /* SGCLIB_C__ */ #define Sg_nLoopInv(SgInfo_)\ @@ -1709,81 +1688,86 @@ void SetSgError(const char *msg); int iModPositive(int ix, int iy); int traceRotMx(const int *RotMx); int deterRotMx(const int *RotMx); -void RotMx_t_Vector(int *R_t_V, const int *RotMx, const int *Vector, int FacTr); +void RotMx_t_Vector(int *R_t_V, const int *RotMx, const int *Vector, + int FacTr); void RotMxMultiply(int *rmxab, const int *rmxa, const int *rmxb); void RotateRotMx(int *RotMx, const int *RMx, const int *InvRMx); -void SeitzMxMultiply(T_RTMx *smxab, const T_RTMx *smxa, const T_RTMx *smxb); -void RTMxMultiply(T_RTMx *rtmxab, const T_RTMx *rtmxa, const T_RTMx *rtmxb, - int FacAug, int FacTr); +void SeitzMxMultiply(T_RTMx * smxab, const T_RTMx * smxa, + const T_RTMx * smxb); +void RTMxMultiply(T_RTMx * rtmxab, const T_RTMx * rtmxa, + const T_RTMx * rtmxb, int FacAug, int FacTr); void InverseRotMx(const int *RotMx, int *InvRotMx); -void InverseRTMx(const T_RTMx *RTMx, T_RTMx *InvRTMx); -int IsSMxTransl0(const T_LatticeInfo *LatticeInfo, const int *SeitzMxT); -int CompareSeitzMx(const T_LatticeInfo *LatticeInfo, - const T_RTMx *SeitzMxA, const T_RTMx *SeitzMxB); +void InverseRTMx(const T_RTMx * RTMx, T_RTMx * InvRTMx); +int IsSMxTransl0(const T_LatticeInfo * LatticeInfo, const int *SeitzMxT); +int CompareSeitzMx(const T_LatticeInfo * LatticeInfo, + const T_RTMx * SeitzMxA, const T_RTMx * SeitzMxB); int GetRotMxOrder(const int *RotMx); -int GetRotMxInfo(const int *RotMx, T_RotMxInfo *RotMxInfo); -const T_RotMxInfo *ListOrBufRotMxInfo(const T_SgInfo *SgInfo, int iList, - T_RotMxInfo *BufRotMxInfo); -int Add2ListSeitzMx(T_SgInfo *SgInfo, const T_RTMx *NewSMx); -int AddInversion2ListSeitzMx(T_SgInfo *SgInfo); -int AddLatticeTr2ListSeitzMx(T_SgInfo *SgInfo, - const T_LatticeInfo *LatticeInfo); -int ApplyOriginShift(T_SgInfo *SgInfo); -int FindSeitzMx(const T_SgInfo *SgInfo, +int GetRotMxInfo(const int *RotMx, T_RotMxInfo * RotMxInfo); +const T_RotMxInfo *ListOrBufRotMxInfo(const T_SgInfo * SgInfo, int iList, + T_RotMxInfo * BufRotMxInfo); +int Add2ListSeitzMx(T_SgInfo * SgInfo, const T_RTMx * NewSMx); +int AddInversion2ListSeitzMx(T_SgInfo * SgInfo); +int AddLatticeTr2ListSeitzMx(T_SgInfo * SgInfo, + const T_LatticeInfo * LatticeInfo); +int ApplyOriginShift(T_SgInfo * SgInfo); +int FindSeitzMx(const T_SgInfo * SgInfo, int Order, int HonorSign, int RefAxis, int DirCode); -void InitSgInfo(T_SgInfo *SgInfo); -int CompleteSgInfo(T_SgInfo *SgInfo); -int CB_SMx(T_RTMx *CSiC, - const T_RTMx *CBMx, const T_RTMx *SMx, const T_RTMx *InvCBMx); -int TransformSgInfo(const T_SgInfo *SgInfo, - const T_RTMx *CBMx, const T_RTMx *InvCBMx, - T_SgInfo *BC_SgInfo); +void InitSgInfo(T_SgInfo * SgInfo); +int CompleteSgInfo(T_SgInfo * SgInfo); +int CB_SMx(T_RTMx * CSiC, + const T_RTMx * CBMx, const T_RTMx * SMx, + const T_RTMx * InvCBMx); +int TransformSgInfo(const T_SgInfo * SgInfo, const T_RTMx * CBMx, + const T_RTMx * InvCBMx, T_SgInfo * BC_SgInfo); /* sgio.c */ -const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter); -unsigned int SgID_Number(const T_TabSgName *tsgn); -int ParseSymXYZ(const char *SymXYZ, T_RTMx *SeitzMx, int FacTr); -int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo); -int PrintFullHM_SgName(const T_TabSgName *tsgn, int space, FILE *fpout); -void PrintTabSgNameEntry(const T_TabSgName *tsgn, int Style, int space, - FILE *fpout); +const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, + int VolLetter); +unsigned int SgID_Number(const T_TabSgName * tsgn); +int ParseSymXYZ(const char *SymXYZ, T_RTMx * SeitzMx, int FacTr); +int ParseHallSymbol(const char *hsym, T_SgInfo * SgInfo); +int PrintFullHM_SgName(const T_TabSgName * tsgn, int space, FILE * fpout); +void PrintTabSgNameEntry(const T_TabSgName * tsgn, int Style, int space, + FILE * fpout); const char *FormatFraction(int nume, int deno, int Decimal, char *Buffer, int SizeBuffer); -const char *RTMx2XYZ(const T_RTMx *RTMx, int FacRo, int FacTr, +const char *RTMx2XYZ(const T_RTMx * RTMx, int FacRo, int FacTr, int Decimal, int TrFirst, int Low, const char *Seperator, char *BufferXYZ, int SizeBufferXYZ); -void PrintMapleRTMx(const T_RTMx *RTMx, int FacRo, int FacTr, - const char *Label, FILE *fpout); -void ListSgInfo(const T_SgInfo *SgInfo, int F_XYZ, int F_Verbose, FILE *fpout); +void PrintMapleRTMx(const T_RTMx * RTMx, int FacRo, int FacTr, + const char *Label, FILE * fpout); +void ListSgInfo(const T_SgInfo * SgInfo, int F_XYZ, int F_Verbose, + FILE * fpout); /* sgfind.c */ -const T_TabSgName *FindReferenceSpaceGroup(T_SgInfo *SgInfo, - T_RTMx *CBMx, T_RTMx *InvCBMx); +const T_TabSgName *FindReferenceSpaceGroup(T_SgInfo * SgInfo, + T_RTMx * CBMx, + T_RTMx * InvCBMx); /* sghkl.c */ -int IsSysAbsent_hkl(const T_SgInfo *SgInfo, +int IsSysAbsent_hkl(const T_SgInfo * SgInfo, int h, int k, int l, int *TH_Restriction); -int BuildEq_hkl(const T_SgInfo *SgInfo, T_Eq_hkl *Eq_hkl, int h, int k, int l); -int AreSymEquivalent_hkl(const T_SgInfo *SgInfo, int h1, int k1, int l1, - int h2, int k2, int l2); -void SetListMin_hkl(const T_SgInfo *SgInfo, int Maxk, int Maxl, - int *Minh, int *Mink, int *Minl); -int IsSuppressed_hkl(const T_SgInfo *SgInfo, int Minh, int Mink, int Minl, - int Maxk, int Maxl, - int h, int k, int l); +int BuildEq_hkl(const T_SgInfo * SgInfo, T_Eq_hkl * Eq_hkl, int h, int k, + int l); +int AreSymEquivalent_hkl(const T_SgInfo * SgInfo, int h1, int k1, int l1, + int h2, int k2, int l2); +void SetListMin_hkl(const T_SgInfo * SgInfo, int Maxk, int Maxl, int *Minh, + int *Mink, int *Minl); +int IsSuppressed_hkl(const T_SgInfo * SgInfo, int Minh, int Mink, int Minl, + int Maxk, int Maxl, int h, int k, int l); /* sgsi.c */ -void MarkLegalOrigins(const T_SgInfo *SgInfo, int *TestField); +void MarkLegalOrigins(const T_SgInfo * SgInfo, int *TestField); int Verify_si(int h, int k, int l, const int *TestField); -int Is_si(const T_SgInfo *SgInfo, int h, int k, int l); -int Set_si(T_SgInfo *SgInfo); -void Set_uvw(const T_SgInfo *SgInfo, int h, int k, int l, int *uvw); +int Is_si(const T_SgInfo * SgInfo, int h, int k, int l); +int Set_si(T_SgInfo * SgInfo); +void Set_uvw(const T_SgInfo * SgInfo, int h, int k, int l, int *uvw); -#endif /* SGINFO_H__ */ +#endif /* SGINFO_H__ */ diff --git a/sgio.c b/sgio.c index e323fedb..2fde8810 100644 --- a/sgio.c +++ b/sgio.c @@ -12,69 +12,68 @@ #include "sginfo.h" -typedef struct - { - int OriginChoice; - int CellChoice; - int BasisChoice; - const char *BT_or_UA; - } - T_ExtInfo; +typedef struct { + int OriginChoice; + int CellChoice; + int BasisChoice; + const char *BT_or_UA; +} T_ExtInfo; -static const char *Ext_BT_or_UA[] = - { - /* 0 */ "abc", - /* 1 */ "ba-c", - /* 2 */ "cab", - /* 3 */ "-cba", - /* 4 */ "bca", - /* 5 */ "a-cb", - /* 6 */ "bac", /* 6 -> 1 */ - /* 7 */ "cba", /* 7 -> 3 */ - /* 8 */ "acb", /* 8 -> 5 */ - /* 9 */ "-b", "b-", "bb", "bb", /* 10, 11, 12 -> 9 */ - /* 13 */ "-c", "c-", "bc", "cb", /* 14, 15, 16 -> 13 */ - /* 17 */ "-a", "a-", "ba", "ab", /* 18, 19, 20 -> 17 */ - /* 21 */ "b", - /* 22 */ "c", - /* 23 */ "a", - NULL - }; +static const char *Ext_BT_or_UA[] = { + /* 0 */ "abc", + /* 1 */ "ba-c", + /* 2 */ "cab", + /* 3 */ "-cba", + /* 4 */ "bca", + /* 5 */ "a-cb", + /* 6 */ "bac", + /* 6 -> 1 */ + /* 7 */ "cba", + /* 7 -> 3 */ + /* 8 */ "acb", + /* 8 -> 5 */ + /* 9 */ "-b", "b-", "bb", "bb", + /* 10, 11, 12 -> 9 */ + /* 13 */ "-c", "c-", "bc", "cb", + /* 14, 15, 16 -> 13 */ + /* 17 */ "-a", "a-", "ba", "ab", + /* 18, 19, 20 -> 17 */ + /* 21 */ "b", + /* 22 */ "c", + /* 23 */ "a", + NULL +}; -typedef struct - { - int Improper, Rotation, RefAxis, DirCode, Screw; - T_RTMx SeitzMx; - } - T_HallGenerator; +typedef struct { + int Improper, Rotation, RefAxis, DirCode, Screw; + T_RTMx SeitzMx; +} T_HallGenerator; #define SkipWhite(cp) while (*(cp) && (*(cp) == '_' || isspace(*(cp)))) (cp)++ static const char *IErr_Corrupt_TabSgName = - "Internal Error: Corrupt TabSgName"; + "Internal Error: Corrupt TabSgName"; static int FindSchoenfliesSymbol(const char *SfSymbol) { - int SgNumber; - const char **TabSymbol; - const char *s, *t; + int SgNumber; + const char **TabSymbol; + const char *s, *t; TabSymbol = SchoenfliesSymbols + 1; - for (SgNumber = 1; SgNumber <= 230; SgNumber++) - { + for (SgNumber = 1; SgNumber <= 230; SgNumber++) { t = *TabSymbol; s = SfSymbol; - while (*t && *s) - { - if ( toupper(*t) != toupper(*s) + while (*t && *s) { + if (toupper(*t) != toupper(*s) && (*t != '^' || isalpha(*s) || isdigit(*s))) break; @@ -95,30 +94,27 @@ static int FindSchoenfliesSymbol(const char *SfSymbol) static int SgLabelCmp(const int SgNumber, const char *SgLabel, const char *WtdLbl) { - const char *sgl, *wl; + const char *sgl, *wl; /* first try: plain strcmp */ sgl = SgLabel; - for (wl = WtdLbl; ; wl++) - { + for (wl = WtdLbl;; wl++) { SkipWhite(wl); SkipWhite(sgl); - if (*sgl == '\0' || *sgl == '=') - { - if (*wl == '\0') return 0; + if (*sgl == '\0' || *sgl == '=') { + if (*wl == '\0') + return 0; break; } - if (*sgl == '-') - { + if (*sgl == '-') { if (*wl != '-' && toupper(*wl) != 'B') break; - } - else if (toupper(*sgl) != toupper(*wl)) + } else if (toupper(*sgl) != toupper(*wl)) break; sgl++; @@ -128,13 +124,11 @@ static int SgLabelCmp(const int SgNumber, */ sgl = SgLabel; - for (wl = WtdLbl; ; wl++) - { + for (wl = WtdLbl;; wl++) { SkipWhite(wl); SkipWhite(sgl); - if (*sgl == '-') - { + if (*sgl == '-') { if (wl[1] != '-' && toupper(wl[1]) != 'B') break; if (toupper(sgl[1]) != toupper(*wl)) @@ -142,12 +136,10 @@ static int SgLabelCmp(const int SgNumber, sgl++; wl++; - } - else - { - if (*sgl == '\0' || *sgl == '=') - { - if (*wl == '\0') return 0; + } else { + if (*sgl == '\0' || *sgl == '=') { + if (*wl == '\0') + return 0; break; } @@ -158,23 +150,21 @@ static int SgLabelCmp(const int SgNumber, sgl++; } - if (SgNumber >= 195) /* cubic space groups only */ - { + if (SgNumber >= 195) { /* cubic space groups only */ /* third try: ignore the "-3" dash */ sgl = SgLabel; - for (wl = WtdLbl; ; wl++) - { + for (wl = WtdLbl;; wl++) { SkipWhite(wl); SkipWhite(sgl); if (*sgl == '-' && sgl[1] == '3') sgl++; - if (*sgl == '\0' || *sgl == '=') - { - if (*wl == '\0') return 0; + if (*sgl == '\0' || *sgl == '=') { + if (*wl == '\0') + return 0; break; } @@ -189,65 +179,47 @@ static int SgLabelCmp(const int SgNumber, } -static int ParseExtension(const char *Ext, T_ExtInfo *ExtInfo) +static int ParseExtension(const char *Ext, T_ExtInfo * ExtInfo) { - int i, mode; - const char *e, *t; + int i, mode; + const char *e, *t; - ExtInfo->OriginChoice = - ExtInfo->CellChoice = - ExtInfo->BasisChoice = ' '; + ExtInfo->OriginChoice = ExtInfo->CellChoice = ExtInfo->BasisChoice = ' '; ExtInfo->BT_or_UA = ""; mode = 0; - while (*Ext) - { - if (strchr("12", *Ext) != NULL) - { - ExtInfo->CellChoice = - ExtInfo->OriginChoice = *Ext++; - } - else if (strchr("3", *Ext) != NULL) - { - ExtInfo->CellChoice = *Ext++; - } - else if (strchr("Ss", *Ext) != NULL) - { + while (*Ext) { + if (strchr("12", *Ext) != NULL) { + ExtInfo->CellChoice = ExtInfo->OriginChoice = *Ext++; + } else if (strchr("3", *Ext) != NULL) { + ExtInfo->CellChoice = *Ext++; + } else if (strchr("Ss", *Ext) != NULL) { ExtInfo->OriginChoice = '1'; Ext++; - } - else if (strchr("Zz", *Ext) != NULL) - { + } else if (strchr("Zz", *Ext) != NULL) { ExtInfo->OriginChoice = '2'; Ext++; - } - else if (strchr("Hh", *Ext) != NULL) - { + } else if (strchr("Hh", *Ext) != NULL) { ExtInfo->BasisChoice = 'H'; Ext++; - } - else if (strchr("Rr", *Ext) != NULL) - { + } else if (strchr("Rr", *Ext) != NULL) { ExtInfo->BasisChoice = 'R'; Ext++; - } - else if (mode == 0) + } else if (mode == 0) mode = 1; if (mode == 2) break; - for (i = 0; Ext_BT_or_UA[i]; i++) - { + for (i = 0; Ext_BT_or_UA[i]; i++) { for (e = Ext, t = Ext_BT_or_UA[i]; *t; e++, t++) if (toupper(*e) != toupper(*t)) break; - if (*t == '\0') - { - if (6 <= i && i <= 8) + if (*t == '\0') { + if (6 <= i && i <= 8) i = 2 * i - 11; else if (9 <= i && i <= 20) i = 9 + ((i - 9) / 4) * 4; @@ -273,75 +245,75 @@ static int ParseExtension(const char *Ext, T_ExtInfo *ExtInfo) static void ExpandMonoclinic(int unique_axis, const char *o, char *m) { - if (*o) *m++ = *o++; + if (*o) + *m++ = *o++; - switch (tolower(unique_axis)) - { - case 'a': - while (*o) *m++ = *o++; - *m++ = '1'; - *m++ = '1'; - break; - case 'c': - *m++ = '1'; - *m++ = '1'; - while (*o) *m++ = *o++; - break; - default: - *m++ = '1'; - while (*o) *m++ = *o++; - *m++ = '1'; - break; + switch (tolower(unique_axis)) { + case 'a': + while (*o) + *m++ = *o++; + *m++ = '1'; + *m++ = '1'; + break; + case 'c': + *m++ = '1'; + *m++ = '1'; + while (*o) + *m++ = *o++; + break; + default: + *m++ = '1'; + while (*o) + *m++ = *o++; + *m++ = '1'; + break; } *m = '\0'; } -const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) +const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, + int VolLetter) { #define MaxWtdLbl 20 - char WtdLblOriginal[MaxWtdLbl + 1]; - char WtdLblModified[MaxWtdLbl + 1]; - char *WtdLbl; + char WtdLblOriginal[MaxWtdLbl + 1]; + char WtdLblModified[MaxWtdLbl + 1]; + char *WtdLbl; #define MaxWtdExt 5 - char WtdExt[MaxWtdExt + 1]; - int WtdSgNumber; - int WtdLblOriginChoice; - int WtdLblBasisChoice; - int iwl, iwe; - char *wl, *we; + char WtdExt[MaxWtdExt + 1]; + int WtdSgNumber; + int WtdLblOriginChoice; + int WtdLblBasisChoice; + int iwl, iwe; + char *wl, *we; - int i, IsExpanded, lbl_match; - const char *sgl; - const T_TabSgName *tsgn; - int WtdCC; - const char *WtdUA; - char WtdUA_Buf[2]; - T_ExtInfo ExtInfo, WtdExtInfo; + int i, IsExpanded, lbl_match; + const char *sgl; + const T_TabSgName *tsgn; + int WtdCC; + const char *WtdUA; + char WtdUA_Buf[2]; + T_ExtInfo ExtInfo, WtdExtInfo; - if (VolLetter == 0 || isspace(VolLetter)) + if (VolLetter == 0 || isspace(VolLetter)) VolLetter = 'A'; else if (VolLetter == '1') VolLetter = 'I'; - else - { - VolLetter = toupper(VolLetter); - if ( VolLetter != 'I' - && VolLetter != 'A') + else { + VolLetter = toupper(VolLetter); + if (VolLetter != 'I' && VolLetter != 'A') return NULL; } WtdLbl = WtdLblOriginal; - wl = WtdLbl; + wl = WtdLbl; iwl = 0; - while (*UserSgName && *UserSgName != ':') - { - if (isspace(*UserSgName) == 0 && *UserSgName != '_') - { + while (*UserSgName && *UserSgName != ':') { + if (isspace(*UserSgName) == 0 && *UserSgName != '_') { if (iwl >= MaxWtdLbl) return NULL; @@ -357,18 +329,15 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) if (iwl == 0) return NULL; - we = WtdExt; + we = WtdExt; iwe = 0; *we = '\0'; - if (*UserSgName) - { + if (*UserSgName) { UserSgName++; - while (*UserSgName) - { - if (isspace(*UserSgName) == 0 && *UserSgName != '_') - { + while (*UserSgName) { + if (isspace(*UserSgName) == 0 && *UserSgName != '_') { if (iwe >= MaxWtdExt) return NULL; @@ -383,80 +352,81 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) *we = '\0'; WtdLblOriginChoice = ' '; - WtdLblBasisChoice = ' '; + WtdLblBasisChoice = ' '; - if (iwl > 1) - { + if (iwl > 1) { wl = &WtdLbl[iwl - 1]; - if (*wl == 'S' || *wl == 's') - { WtdLblOriginChoice = '1'; *wl = '\0'; iwl--; } - else if (*wl == 'Z' || *wl == 'z') - { WtdLblOriginChoice = '2'; *wl = '\0'; iwl--; } - else if (*wl == 'H' || *wl == 'h') - { WtdLblBasisChoice = 'H'; *wl = '\0'; iwl--; } - else if (*wl == 'R' || *wl == 'r') - { WtdLblBasisChoice = 'R'; *wl = '\0'; iwl--; } + if (*wl == 'S' || *wl == 's') { + WtdLblOriginChoice = '1'; + *wl = '\0'; + iwl--; + } else if (*wl == 'Z' || *wl == 'z') { + WtdLblOriginChoice = '2'; + *wl = '\0'; + iwl--; + } else if (*wl == 'H' || *wl == 'h') { + WtdLblBasisChoice = 'H'; + *wl = '\0'; + iwl--; + } else if (*wl == 'R' || *wl == 'r') { + WtdLblBasisChoice = 'R'; + *wl = '\0'; + iwl--; + } } if (isalpha(WtdLbl[0])) WtdSgNumber = FindSchoenfliesSymbol(WtdLbl); - else - { + else { for (wl = WtdLbl; *wl; wl++) if (isdigit(*wl) == 0) return NULL; - if ( sscanf(WtdLbl, "%d", &WtdSgNumber) != 1 - || WtdSgNumber < 1 - || WtdSgNumber > 230) + if (sscanf(WtdLbl, "%d", &WtdSgNumber) != 1 + || WtdSgNumber < 1 || WtdSgNumber > 230) return NULL; } if (ParseExtension(WtdExt, &WtdExtInfo) != 0) return NULL; - if (WtdExtInfo.OriginChoice == ' ') - WtdExtInfo.OriginChoice = WtdLblOriginChoice; + if (WtdExtInfo.OriginChoice == ' ') + WtdExtInfo.OriginChoice = WtdLblOriginChoice; else if (WtdExtInfo.OriginChoice != WtdLblOriginChoice - && WtdLblOriginChoice != ' ') + && WtdLblOriginChoice != ' ') return NULL; - if (WtdExtInfo.BasisChoice == ' ') - WtdExtInfo.BasisChoice = WtdLblBasisChoice; + if (WtdExtInfo.BasisChoice == ' ') + WtdExtInfo.BasisChoice = WtdLblBasisChoice; else if (WtdExtInfo.BasisChoice != WtdLblBasisChoice - && WtdLblBasisChoice != ' ') + && WtdLblBasisChoice != ' ') return NULL; - if ( WtdExtInfo.OriginChoice != ' ' - && WtdExtInfo.BasisChoice != ' ') + if (WtdExtInfo.OriginChoice != ' ' && WtdExtInfo.BasisChoice != ' ') return NULL; - for (IsExpanded = 0; IsExpanded < 4; IsExpanded++) - { - for (tsgn = TabSgName; tsgn->HallSymbol; tsgn++) - { - if ( IsExpanded != 0 - && tsgn->SgNumber > 15) + for (IsExpanded = 0; IsExpanded < 4; IsExpanded++) { + for (tsgn = TabSgName; tsgn->HallSymbol; tsgn++) { + if (IsExpanded != 0 && tsgn->SgNumber > 15) break; lbl_match = 0; - if (WtdSgNumber == -1) - { + if (WtdSgNumber == -1) { i = 1; - sgl = tsgn->SgLabels; - while (*sgl && i <= 2) - { - while (*sgl && strchr(" =\t", *sgl) != NULL) sgl++; + sgl = tsgn->SgLabels; + while (*sgl && i <= 2) { + while (*sgl && strchr(" =\t", *sgl) != NULL) + sgl++; - if (SgLabelCmp(tsgn->SgNumber, sgl, WtdLbl) == 0) - { + if (SgLabelCmp(tsgn->SgNumber, sgl, WtdLbl) == 0) { lbl_match = i; break; } - while (*sgl && strchr(" =\t", *sgl) == NULL) sgl++; + while (*sgl && strchr(" =\t", *sgl) == NULL) + sgl++; i++; } @@ -467,53 +437,45 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) return NULL; } - if (WtdSgNumber == tsgn->SgNumber || lbl_match != 0) - { - if ( tsgn->SgNumber >= 3 - && tsgn->SgNumber < 16) - { - if ( WtdLblOriginChoice != ' ' + if (WtdSgNumber == tsgn->SgNumber || lbl_match != 0) { + if (tsgn->SgNumber >= 3 && tsgn->SgNumber < 16) { + if (WtdLblOriginChoice != ' ' || WtdExtInfo.BasisChoice != ' ' || (int) strlen(WtdExtInfo.BT_or_UA) > 2) - continue; /* next tsgn */ + continue; /* next tsgn */ - if (WtdSgNumber == tsgn->SgNumber) - { + if (WtdSgNumber == tsgn->SgNumber) { if (WtdExtInfo.BT_or_UA[0]) WtdUA = WtdExtInfo.BT_or_UA; - else if (VolLetter == 'I') - { - if ( ExtInfo.BT_or_UA[0] != 'c' - && ExtInfo.BT_or_UA[1] != 'c') - continue; /* next tsgn */ + else if (VolLetter == 'I') { + if (ExtInfo.BT_or_UA[0] != 'c' && ExtInfo.BT_or_UA[1] != 'c') + continue; /* next tsgn */ - if ( ExtInfo.CellChoice == ' ' - && ( WtdExtInfo.CellChoice == ' ' + if (ExtInfo.CellChoice == ' ' + && (WtdExtInfo.CellChoice == ' ' || WtdExtInfo.CellChoice == '1')) return tsgn; i = 0; for (sgl = tsgn->SgLabels; *sgl; sgl++) - if (*sgl == '=') i++; + if (*sgl == '=') + i++; - if ( i == 2 - && ( WtdExtInfo.CellChoice == ' ' + if (i == 2 + && (WtdExtInfo.CellChoice == ' ' || WtdExtInfo.CellChoice == ExtInfo.CellChoice)) return tsgn; - continue; /* next tsgn */ - } - else + continue; /* next tsgn */ + } else WtdUA = "b"; - } - else /* if (lbl_match != 0) */ - { + } else { /* if (lbl_match != 0) */ + if (WtdExtInfo.BT_or_UA[0]) WtdUA = WtdExtInfo.BT_or_UA; else if (lbl_match > 1) WtdUA = ExtInfo.BT_or_UA; - else if ( VolLetter == 'I' - && ExtInfo.CellChoice == ' ') + else if (VolLetter == 'I' && ExtInfo.CellChoice == ' ') WtdUA = "c"; else WtdUA = "b"; @@ -526,8 +488,7 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) else WtdCC = ' '; - if (strcmp(ExtInfo.BT_or_UA, WtdUA) == 0) - { + if (strcmp(ExtInfo.BT_or_UA, WtdUA) == 0) { if (WtdCC == ' ' && lbl_match > 1) return tsgn; if (ExtInfo.CellChoice == WtdCC) @@ -537,41 +498,34 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) if (ExtInfo.CellChoice == '1' && WtdCC == ' ') return tsgn; } - } - else if (ExtInfo.BasisChoice != ' ') - { - if ( WtdExtInfo.OriginChoice != ' ' + } else if (ExtInfo.BasisChoice != ' ') { + if (WtdExtInfo.OriginChoice != ' ' || WtdExtInfo.CellChoice != ' ' || WtdExtInfo.BT_or_UA[0] != '\0') - continue; /* next tsgn */ + continue; /* next tsgn */ if (ExtInfo.BasisChoice == WtdExtInfo.BasisChoice) return tsgn; - if (WtdExtInfo.BasisChoice == ' ') - { + if (WtdExtInfo.BasisChoice == ' ') { if (ExtInfo.BasisChoice == 'R' && VolLetter == 'I') return tsgn; if (ExtInfo.BasisChoice == 'H' && VolLetter != 'I') return tsgn; } - } - else if (WtdExtInfo.BasisChoice == ' ') - { - if ( (WtdExtInfo.OriginChoice == ' ' && ExtInfo.OriginChoice == '1') - || (WtdExtInfo.OriginChoice == '1' && ExtInfo.OriginChoice == ' ') - || WtdExtInfo.OriginChoice == ExtInfo.OriginChoice) - { - if (WtdExtInfo.BT_or_UA[0]) - { + } else if (WtdExtInfo.BasisChoice == ' ') { + if ((WtdExtInfo.OriginChoice == ' ' + && ExtInfo.OriginChoice == '1') + || (WtdExtInfo.OriginChoice == '1' + && ExtInfo.OriginChoice == ' ') + || WtdExtInfo.OriginChoice == ExtInfo.OriginChoice) { + if (WtdExtInfo.BT_or_UA[0]) { if (WtdExtInfo.BT_or_UA == ExtInfo.BT_or_UA) return tsgn; - if ( WtdExtInfo.BT_or_UA == Ext_BT_or_UA[0] - && ExtInfo.BT_or_UA[0] == '\0') + if (WtdExtInfo.BT_or_UA == Ext_BT_or_UA[0] + && ExtInfo.BT_or_UA[0] == '\0') return tsgn; - } - else - { + } else { if (lbl_match != 0) return tsgn; if (ExtInfo.BT_or_UA[0] == '\0') @@ -588,18 +542,15 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) if ((int) strlen(WtdExtInfo.BT_or_UA) > 2) return NULL; - if (IsExpanded == 0) - { + if (IsExpanded == 0) { iwl += 2; if (iwl > MaxWtdLbl) IsExpanded = 2; - else - { + else { if (WtdExtInfo.BT_or_UA[0]) WtdUA = WtdExtInfo.BT_or_UA; - else - { + else { if (VolLetter == 'I') WtdUA = "c"; else @@ -610,9 +561,7 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) WtdLbl = WtdLblModified; } - } - else if (IsExpanded == 1) - { + } else if (IsExpanded == 1) { if (WtdExtInfo.BT_or_UA[0]) return NULL; @@ -624,8 +573,7 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) ExpandMonoclinic(WtdUA[0], WtdLblOriginal, WtdLblModified); } - if (IsExpanded == 2) - { + if (IsExpanded == 2) { if (WtdExtInfo.BT_or_UA[0]) return NULL; @@ -633,9 +581,9 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) if (iwl < 2) return NULL; - iwl--; + iwl--; WtdUA_Buf[0] = tolower(WtdLblOriginal[iwl]); - WtdLblOriginal[iwl] = '\0'; + WtdLblOriginal[iwl] = '\0'; WtdUA_Buf[1] = '\0'; if (strchr("abc", WtdUA_Buf[0]) == NULL) @@ -658,12 +606,12 @@ const T_TabSgName *FindTabSgNameEntry(const char *UserSgName, int VolLetter) } -unsigned int SgID_Number(const T_TabSgName *tsgn) +unsigned int SgID_Number(const T_TabSgName * tsgn) { - unsigned int ID; - int iBT; - const char *UA; - T_ExtInfo ExtInfo; + unsigned int ID; + int iBT; + const char *UA; + T_ExtInfo ExtInfo; ID = tsgn->SgNumber; @@ -671,65 +619,70 @@ unsigned int SgID_Number(const T_TabSgName *tsgn) if (ParseExtension(tsgn->Extension, &ExtInfo) != 0) ID = 0; - if (ID >= 3 && ID < 16) - { + if (ID >= 3 && ID < 16) { UA = ExtInfo.BT_or_UA; - if ( *UA != 'b' - || ( ExtInfo.CellChoice != ' ' - && ExtInfo.CellChoice != '1')) - { - if (*UA == '-') - { + if (*UA != 'b' + || (ExtInfo.CellChoice != ' ' && ExtInfo.CellChoice != '1')) { + if (*UA == '-') { ID += 3000; UA++; } - switch (*UA) - { - case 'b': ID += 10000; break; - case 'c': ID += 20000; break; - case 'a': ID += 30000; break; - default: ID = 0; break; + switch (*UA) { + case 'b': + ID += 10000; + break; + case 'c': + ID += 20000; + break; + case 'a': + ID += 30000; + break; + default: + ID = 0; + break; } - if (ID != 0) - { - switch (ExtInfo.CellChoice) - { - case ' ': break; - case '1': ID += 1000; break; - case '2': ID += 2000; break; - case '3': ID += 3000; break; - default: ID = 0; break; + if (ID != 0) { + switch (ExtInfo.CellChoice) { + case ' ': + break; + case '1': + ID += 1000; + break; + case '2': + ID += 2000; + break; + case '3': + ID += 3000; + break; + default: + ID = 0; + break; } } } - } - else - { + } else { if (ExtInfo.BasisChoice == 'R') ID += 20000; - else - { - if (ExtInfo.BT_or_UA[0]) - { + else { + if (ExtInfo.BT_or_UA[0]) { for (iBT = 0; iBT < 6; iBT++) if (ExtInfo.BT_or_UA == Ext_BT_or_UA[iBT]) break; - } - else + } else iBT = 0; - if (iBT < 6) - { - if (ExtInfo.OriginChoice == '2') ID += 20000; - else if (iBT) ID += 10000; + if (iBT < 6) { + if (ExtInfo.OriginChoice == '2') + ID += 20000; + else if (iBT) + ID += 10000; if (iBT) ID += (iBT + 1) * 1000; - } - else + } else ID = 0; } } @@ -741,14 +694,15 @@ unsigned int SgID_Number(const T_TabSgName *tsgn) } -int ParseSymXYZ(const char *SymXYZ, T_RTMx *SeitzMx, int FacTr) +int ParseSymXYZ(const char *SymXYZ, T_RTMx * SeitzMx, int FacTr) { - unsigned int P_mode; - int Row, Column, Sign, GotXYZ, i; - double Value, Value1, Value2, Delta; + unsigned int P_mode; + int Row, Column, Sign, GotXYZ, i; + double Value, Value1, Value2, Delta; - for (i = 0; i < 12; i++) SeitzMx->a[i] = 0; + for (i = 0; i < 12; i++) + SeitzMx->a[i] = 0; #define P_Blank 0x01u #define P_Comma 0x02u @@ -761,117 +715,139 @@ int ParseSymXYZ(const char *SymXYZ, T_RTMx *SeitzMx, int FacTr) Value1 = 0.; - Row = 0; - Sign = 1; - Value = 0.; + Row = 0; + Sign = 1; + Value = 0.; GotXYZ = 0; P_mode = P_Blank | P_Plus | P_Dash | P_Value1 | P_XYZ; - do - { - switch (*SymXYZ) - { - case ' ': - case '\t': - case '_': - if ((P_mode & P_Blank) == 0) return -1; - break; - case ',': - case ';': - if (Row == 2) return -1; - case '\0': - if ((P_mode & P_Comma) == 0) return -1; - if (GotXYZ == 0) return -1; - if (P_mode & P_Slash) Value += Value1; - Value *= FacTr; - if (Value < 0.) i = Value - .5; - else i = Value + .5; - Delta = Value - i; - if (Delta < 0.) Delta = -Delta; - if (Delta > .01 * FacTr) return -1; - i %= FacTr; if (i < 0) i += FacTr; - SeitzMx->s.T[Row] = i; - Row++; - Sign = 1; - Value = 0.; - P_mode = P_Blank | P_Plus | P_Dash | P_Value1 | P_XYZ; - GotXYZ = 0; - break; - case '+': - if ((P_mode & P_Plus) == 0) return -1; - if (P_mode & P_Slash) Value += Value1; - Sign = 1; - if (P_mode & P_Value2) - P_mode = P_Value2; - else - P_mode = P_Blank | P_Value1 | P_XYZ; - break; - case '-': - if ((P_mode & P_Dash) == 0) return -1; - if (P_mode & P_Slash) Value += Value1; - Sign = -1; - if (P_mode & P_Value2) - P_mode = P_Value2; - else - P_mode = P_Blank | P_Value1 | P_XYZ; - break; - case '/': - case ':': - if ((P_mode & P_Slash) == 0) return -1; - Sign = 1; - P_mode = P_Blank | P_Plus | P_Dash | P_Value2; - break; - case '.': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - if (P_mode & P_Value1) - { - if (sscanf(SymXYZ, "%lf%n", &Value1, &i) != 1) return -1; - if (Sign == -1) Value1 = -Value1; - P_mode = P_Blank | P_Comma | P_Plus | P_Dash | P_Slash; - } - else if (P_mode & P_Value2) - { - if (sscanf(SymXYZ, "%lf%n", &Value2, &i) != 1) return -1; - if (Sign == -1) Value2 = -Value2; - if (Value1 != 0.) - { - if (Value2 == 0.) return -1; - Value += Value1 / Value2; - } - P_mode = P_Blank | P_Comma | P_Plus | P_Dash; - } - else + do { + switch (*SymXYZ) { + case ' ': + case '\t': + case '_': + if ((P_mode & P_Blank) == 0) + return -1; + break; + case ',': + case ';': + if (Row == 2) + return -1; + case '\0': + if ((P_mode & P_Comma) == 0) + return -1; + if (GotXYZ == 0) + return -1; + if (P_mode & P_Slash) + Value += Value1; + Value *= FacTr; + if (Value < 0.) + i = Value - .5; + else + i = Value + .5; + Delta = Value - i; + if (Delta < 0.) + Delta = -Delta; + if (Delta > .01 * FacTr) + return -1; + i %= FacTr; + if (i < 0) + i += FacTr; + SeitzMx->s.T[Row] = i; + Row++; + Sign = 1; + Value = 0.; + P_mode = P_Blank | P_Plus | P_Dash | P_Value1 | P_XYZ; + GotXYZ = 0; + break; + case '+': + if ((P_mode & P_Plus) == 0) + return -1; + if (P_mode & P_Slash) + Value += Value1; + Sign = 1; + if (P_mode & P_Value2) + P_mode = P_Value2; + else + P_mode = P_Blank | P_Value1 | P_XYZ; + break; + case '-': + if ((P_mode & P_Dash) == 0) + return -1; + if (P_mode & P_Slash) + Value += Value1; + Sign = -1; + if (P_mode & P_Value2) + P_mode = P_Value2; + else + P_mode = P_Blank | P_Value1 | P_XYZ; + break; + case '/': + case ':': + if ((P_mode & P_Slash) == 0) + return -1; + Sign = 1; + P_mode = P_Blank | P_Plus | P_Dash | P_Value2; + break; + case '.': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (P_mode & P_Value1) { + if (sscanf(SymXYZ, "%lf%n", &Value1, &i) != 1) return -1; - SymXYZ += (i - 1); - break; - case 'X': - case 'x': Column = 0; goto Process_XYZ; - case 'Y': - case 'y': Column = 1; goto Process_XYZ; - case 'Z': - case 'z': Column = 2; - Process_XYZ: - if ((P_mode & P_XYZ) == 0) return -1; - i = Row * 3 + Column; - if (SeitzMx->s.R[i] != 0) return -1; - SeitzMx->s.R[i] = Sign; - GotXYZ = 1; + if (Sign == -1) + Value1 = -Value1; + P_mode = P_Blank | P_Comma | P_Plus | P_Dash | P_Slash; + } else if (P_mode & P_Value2) { + if (sscanf(SymXYZ, "%lf%n", &Value2, &i) != 1) + return -1; + if (Sign == -1) + Value2 = -Value2; + if (Value1 != 0.) { + if (Value2 == 0.) + return -1; + Value += Value1 / Value2; + } P_mode = P_Blank | P_Comma | P_Plus | P_Dash; - break; + } else + return -1; + SymXYZ += (i - 1); + break; + case 'X': + case 'x': + Column = 0; + goto Process_XYZ; + case 'Y': + case 'y': + Column = 1; + goto Process_XYZ; + case 'Z': + case 'z': + Column = 2; + Process_XYZ: + if ((P_mode & P_XYZ) == 0) + return -1; + i = Row * 3 + Column; + if (SeitzMx->s.R[i] != 0) + return -1; + SeitzMx->s.R[i] = Sign; + GotXYZ = 1; + P_mode = P_Blank | P_Comma | P_Plus | P_Dash; + break; } } while (*SymXYZ++); - if (Row != 3) return -1; + if (Row != 3) + return -1; return 0; @@ -886,52 +862,56 @@ int ParseSymXYZ(const char *SymXYZ, T_RTMx *SeitzMx, int FacTr) } -static int LookupRotMx(T_HallGenerator *HG) +static int LookupRotMx(T_HallGenerator * HG) { - int i, f, refaxis, dircode; - int iNextBasis, nNextBasis; - const T_TabXtalRotMx *txrmx; + int i, f, refaxis, dircode; + int iNextBasis, nNextBasis; + const T_TabXtalRotMx *txrmx; - if (HG->Rotation <= 0) return 0; + if (HG->Rotation <= 0) + return 0; refaxis = HG->RefAxis; dircode = HG->DirCode; - if (HG->Rotation == 1) - { + if (HG->Rotation == 1) { refaxis = 'o'; dircode = '.'; nNextBasis = 0; - } - else if (dircode == '*') - { - if (refaxis == 0) refaxis = 'o'; + } else if (dircode == '*') { + if (refaxis == 0) + refaxis = 'o'; nNextBasis = 0; - } - else - { - if (dircode == 0) dircode = '='; + } else { + if (dircode == 0) + dircode = '='; - switch (refaxis) - { - case 'z': nNextBasis = 0; break; - case 'x': nNextBasis = 1; break; - case 'y': nNextBasis = 2; break; - default: - return 0; + switch (refaxis) { + case 'z': + nNextBasis = 0; + break; + case 'x': + nNextBasis = 1; + break; + case 'y': + nNextBasis = 2; + break; + default: + return 0; } } for (txrmx = TabXtalRotMx; txrmx->Order; txrmx++) - if (txrmx->Order == HG->Rotation) break; + if (txrmx->Order == HG->Rotation) + break; - while (txrmx->Order == HG->Rotation) - { - if (txrmx->DirCode == dircode) - { - if (HG->Improper == 0) f = 1; - else f = -1; + while (txrmx->Order == HG->Rotation) { + if (txrmx->DirCode == dircode) { + if (HG->Improper == 0) + f = 1; + else + f = -1; for (i = 0; i < 9; i++) HG->SeitzMx.s.R[i] = txrmx->RMx[i] * f; @@ -949,37 +929,36 @@ static int LookupRotMx(T_HallGenerator *HG) } -int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo) +int ParseHallSymbol(const char *hsym, T_SgInfo * SgInfo) { - int c, i, pos_hsym; - const int *ht; - int Centric; - const T_LatticeInfo *LatticeInfo; - int FieldType, PreviousFT; - int iOriginShift, SignOriginShift; - int digit, rotation, refaxis, dircode; - const int *translation; - int PreviousRotation, PreviousRefAxis; - int nHG, ClearHG; - T_HallGenerator HG; + int c, i, pos_hsym; + const int *ht; + int Centric; + const T_LatticeInfo *LatticeInfo; + int FieldType, PreviousFT; + int iOriginShift, SignOriginShift; + int digit, rotation, refaxis, dircode; + const int *translation; + int PreviousRotation, PreviousRefAxis; + int nHG, ClearHG; + T_HallGenerator HG; - enum ListOfFieldTypes - { - FT_Delimiter, - FT_Improper, - FT_Digit, - FT_Rotation, - FT_RefAxis, - FT_DirCode, - FT_Translation, - FT_OriginShift - }; + enum ListOfFieldTypes { + FT_Delimiter, + FT_Improper, + FT_Digit, + FT_Rotation, + FT_RefAxis, + FT_DirCode, + FT_Translation, + FT_OriginShift + }; static const char *Err_Ill_ori_shi_val = - "Error: Illegal origin shift value"; + "Error: Illegal origin shift value"; static const char *Err_Too_ori_shi_val = - "Error: Too much origin shift values"; + "Error: Too much origin shift values"; Centric = 0; @@ -997,8 +976,7 @@ int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo) pos_hsym = 0; - do - { + do { if (*hsym == '_' || *hsym == '.' || *hsym == '\t' || *hsym == '\0') c = ' '; else @@ -1006,43 +984,56 @@ int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo) pos_hsym++; - if (LatticeInfo == NULL) - { - if (Centric == 0 && c == '-') - { + if (LatticeInfo == NULL) { + if (Centric == 0 && c == '-') { if (AddInversion2ListSeitzMx(SgInfo) < 0) return pos_hsym; Centric = 1; - } - else if (c != ' ') - { + } else if (c != ' ') { c = toupper(c); - switch (c) - { - case 'P': LatticeInfo = LI_P; break; - case 'A': LatticeInfo = LI_A; break; - case 'B': LatticeInfo = LI_B; break; - case 'C': LatticeInfo = LI_C; break; - case 'I': LatticeInfo = LI_I; break; - case 'R': LatticeInfo = LI_R; break; - case 'S': LatticeInfo = LI_S; break; - case 'T': LatticeInfo = LI_T; break; - case 'F': LatticeInfo = LI_F; break; - default: - SetSgError("Error: Illegal lattice code"); - return pos_hsym; + switch (c) { + case 'P': + LatticeInfo = LI_P; + break; + case 'A': + LatticeInfo = LI_A; + break; + case 'B': + LatticeInfo = LI_B; + break; + case 'C': + LatticeInfo = LI_C; + break; + case 'I': + LatticeInfo = LI_I; + break; + case 'R': + LatticeInfo = LI_R; + break; + case 'S': + LatticeInfo = LI_S; + break; + case 'T': + LatticeInfo = LI_T; + break; + case 'F': + LatticeInfo = LI_F; + break; + default: + SetSgError("Error: Illegal lattice code"); + return pos_hsym; } if (AddLatticeTr2ListSeitzMx(SgInfo, LatticeInfo) < 0) return pos_hsym; } - } - else if (FieldType != FT_OriginShift) - { + } else if (FieldType != FT_OriginShift) { c = tolower(c); - if (c == 'q') c = '\''; - else if (c == '+') c = '"'; + if (c == 'q') + c = '\''; + else if (c == '+') + c = '"'; PreviousFT = FieldType; digit = rotation = refaxis = dircode = 0; @@ -1050,10 +1041,8 @@ int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo) ht = HallTranslations; - while (*ht) - { - if (c == *ht) - { + while (*ht) { + if (c == *ht) { translation = ht; FieldType = FT_Translation; break; @@ -1061,86 +1050,101 @@ int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo) ht += 4; } - if (translation == NULL) - { - switch (c) - { - case ' ': FieldType = FT_Delimiter; break; + if (translation == NULL) { + switch (c) { + case ' ': + FieldType = FT_Delimiter; + break; - case '-': FieldType = FT_Improper; break; + case '-': + FieldType = FT_Improper; + break; - case '1': digit = 1; FieldType = FT_Digit; break; - case '2': digit = 2; FieldType = FT_Digit; break; - case '3': digit = 3; FieldType = FT_Digit; break; - case '4': digit = 4; FieldType = FT_Digit; break; - case '5': digit = 5; FieldType = FT_Digit; break; - case '6': digit = 6; FieldType = FT_Digit; break; + case '1': + digit = 1; + FieldType = FT_Digit; + break; + case '2': + digit = 2; + FieldType = FT_Digit; + break; + case '3': + digit = 3; + FieldType = FT_Digit; + break; + case '4': + digit = 4; + FieldType = FT_Digit; + break; + case '5': + digit = 5; + FieldType = FT_Digit; + break; + case '6': + digit = 6; + FieldType = FT_Digit; + break; - case 'x': - case 'y': - case 'z': refaxis = c; FieldType = FT_RefAxis; break; + case 'x': + case 'y': + case 'z': + refaxis = c; + FieldType = FT_RefAxis; + break; - case '"': - case '\'': - case '*': dircode = c; FieldType = FT_DirCode; break; + case '"': + case '\'': + case '*': + dircode = c; + FieldType = FT_DirCode; + break; - case '(': FieldType = FT_OriginShift; break; + case '(': + FieldType = FT_OriginShift; + break; - default: - SetSgError("Error: Illegal character in Hall symbol"); - return pos_hsym; + default: + SetSgError("Error: Illegal character in Hall symbol"); + return pos_hsym; } - if (FieldType == FT_Digit) - { - if ( ClearHG == 0 - && HG.Rotation > digit - && HG.Screw == 0 - && HG.DirCode == 0) - { + if (FieldType == FT_Digit) { + if (ClearHG == 0 + && HG.Rotation > digit && HG.Screw == 0 && HG.DirCode == 0) { HG.Screw = digit; FieldType = FT_Translation; - } - else if (digit == 5) - { + } else if (digit == 5) { SetSgError("Error: Illegal 5-fold rotation"); return pos_hsym; - } - else - { + } else { rotation = digit; FieldType = FT_Rotation; } } } - if ( ClearHG == 0 - && ( FieldType == FT_Delimiter - || FieldType == FT_OriginShift - || FieldType < PreviousFT + if (ClearHG == 0 + && (FieldType == FT_Delimiter + || FieldType == FT_OriginShift + || FieldType < PreviousFT || (FieldType == PreviousFT && FieldType != FT_Translation)) - && ! ( FieldType == FT_RefAxis && HG.RefAxis == 0 - && PreviousFT == FT_DirCode)) - { - if (HG.RefAxis == 0) - { + && !(FieldType == FT_RefAxis && HG.RefAxis == 0 + && PreviousFT == FT_DirCode)) { + if (HG.RefAxis == 0) { if (nHG == 0) HG.RefAxis = 'z'; - else - { - if (HG.Rotation == 2) - { - if (PreviousRotation == 2 || PreviousRotation == 4) + else { + if (HG.Rotation == 2) { + if (PreviousRotation == 2 || PreviousRotation == 4) HG.RefAxis = 'x'; - else if (PreviousRotation == 3 || PreviousRotation == 6) - { + else if (PreviousRotation == 3 || PreviousRotation == 6) { HG.RefAxis = PreviousRefAxis; - if (HG.DirCode == 0) HG.DirCode = '\''; + if (HG.DirCode == 0) + HG.DirCode = '\''; } - } - else if (HG.Rotation == 3) - { - if (HG.DirCode == 0) HG.DirCode = '*'; + } else if (HG.Rotation == 3) { + if (HG.DirCode == 0) + HG.DirCode = '*'; } } } @@ -1148,24 +1152,29 @@ int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo) PreviousRefAxis = HG.RefAxis; PreviousRotation = HG.Rotation; - if (LookupRotMx(&HG) == 0) - { - SetSgError("Error: Illegal generator or need explicit axis symbol"); + if (LookupRotMx(&HG) == 0) { + SetSgError + ("Error: Illegal generator or need explicit axis symbol"); return pos_hsym - 1; } - if (HG.Screw) - { - switch (HG.RefAxis) - { - case 'x': i = 0; break; - case 'y': i = 1; break; - case 'z': i = 2; break; - default: i = -1; break; + if (HG.Screw) { + switch (HG.RefAxis) { + case 'x': + i = 0; + break; + case 'y': + i = 1; + break; + case 'z': + i = 2; + break; + default: + i = -1; + break; } - if (HG.DirCode != 0 || i < 0) - { + if (HG.DirCode != 0 || i < 0) { SetSgError("Error: Screw for non-principal direction"); return pos_hsym - 1; } @@ -1179,8 +1188,7 @@ int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo) if (Add2ListSeitzMx(SgInfo, &HG.SeitzMx) < 0) return pos_hsym - 1; - if (SgInfo->StatusLatticeTr == -1) - { + if (SgInfo->StatusLatticeTr == -1) { if (AddLatticeTr2ListSeitzMx(SgInfo, SgInfo->LatticeInfo) < 0) return pos_hsym - 1; } @@ -1189,89 +1197,107 @@ int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo) ClearHG = 1; } - if (FieldType != FT_Delimiter && FieldType != FT_OriginShift) - { - if (ClearHG) - { + if (FieldType != FT_Delimiter && FieldType != FT_OriginShift) { + if (ClearHG) { HG.Improper = 0; HG.Rotation = 1; HG.RefAxis = 0; HG.DirCode = 0; HG.Screw = 0; - for (i = 0; i < 12; i++) HG.SeitzMx.a[i] = 0; + for (i = 0; i < 12; i++) + HG.SeitzMx.a[i] = 0; ClearHG = 0; } - switch (FieldType) - { - case FT_Improper: HG.Improper = 1; break; - case FT_Rotation: HG.Rotation = rotation; break; - case FT_RefAxis: HG.RefAxis = refaxis; break; - case FT_DirCode: HG.DirCode = dircode; break; - case FT_Translation: - if (translation != NULL) - { - for (i = 0; i < 3; i++) - HG.SeitzMx.s.T[i] += *(++translation); - } - break; + switch (FieldType) { + case FT_Improper: + HG.Improper = 1; + break; + case FT_Rotation: + HG.Rotation = rotation; + break; + case FT_RefAxis: + HG.RefAxis = refaxis; + break; + case FT_DirCode: + HG.DirCode = dircode; + break; + case FT_Translation: + if (translation != NULL) { + for (i = 0; i < 3; i++) + HG.SeitzMx.s.T[i] += *(++translation); + } + break; } } - } - else /* FieldType == FT_OriginShift */ - { + } else { /* FieldType == FT_OriginShift */ + if (iOriginShift > 3) { SetSgError(Err_Too_ori_shi_val); return pos_hsym; } - if (*hsym == '\0') c = ')'; + if (*hsym == '\0') + c = ')'; digit = -1; - switch (c) - { - case ' ': break; + switch (c) { + case ' ': + break; - case ')': - if (iOriginShift != 3) - { - SetSgError("Error: Missing origin shift values"); - return pos_hsym; - } - iOriginShift++; - FieldType = FT_Delimiter; - break; + case ')': + if (iOriginShift != 3) { + SetSgError("Error: Missing origin shift values"); + return pos_hsym; + } + iOriginShift++; + FieldType = FT_Delimiter; + break; - case '-': - if (SignOriginShift != 0) { - SetSgError(Err_Ill_ori_shi_val); - return pos_hsym; - } - SignOriginShift = 1; - break; - - case '0': digit = 0; break; - case '1': digit = 1; break; - case '2': digit = 2; break; - case '3': digit = 3; break; - case '4': digit = 4; break; - case '5': digit = 5; break; - case '6': digit = 6; break; - - default: + case '-': + if (SignOriginShift != 0) { SetSgError(Err_Ill_ori_shi_val); return pos_hsym; + } + SignOriginShift = 1; + break; + + case '0': + digit = 0; + break; + case '1': + digit = 1; + break; + case '2': + digit = 2; + break; + case '3': + digit = 3; + break; + case '4': + digit = 4; + break; + case '5': + digit = 5; + break; + case '6': + digit = 6; + break; + + default: + SetSgError(Err_Ill_ori_shi_val); + return pos_hsym; } - if (digit >= 0) - { + if (digit >= 0) { if (iOriginShift >= 3) { SetSgError(Err_Too_ori_shi_val); return pos_hsym; } - if (SignOriginShift) digit *= -1; + if (SignOriginShift) + digit *= -1; SignOriginShift = 0; SgInfo->OriginShift[iOriginShift++] = digit; } @@ -1289,22 +1315,19 @@ int ParseHallSymbol(const char *hsym, T_SgInfo *SgInfo) static const char *PrintSgLabel(const char *lbl, int space, int *n, - FILE *fpout) + FILE * fpout) { - while (*lbl && *lbl != ' ') - { - if (*lbl == '_') - { - if (space) - { + while (*lbl && *lbl != ' ') { + if (*lbl == '_') { + if (space) { putc(space, fpout); - if (n) (*n)++; + if (n) + (*n)++; } - } - else - { + } else { putc(*lbl, fpout); - if (n) (*n)++; + if (n) + (*n)++; } lbl++; @@ -1314,16 +1337,18 @@ static const char *PrintSgLabel(const char *lbl, int space, int *n, } -int PrintFullHM_SgName(const T_TabSgName *tsgn, int space, FILE *fpout) +int PrintFullHM_SgName(const T_TabSgName * tsgn, int space, FILE * fpout) { - int n; - const char *lbl; + int n; + const char *lbl; lbl = tsgn->SgLabels; if (tsgn->SgNumber >= 3 && tsgn->SgNumber < 16) - while (*lbl) if (*lbl++ == '=') break; + while (*lbl) + if (*lbl++ == '=') + break; SkipWhite(lbl); @@ -1333,8 +1358,7 @@ int PrintFullHM_SgName(const T_TabSgName *tsgn, int space, FILE *fpout) lbl = tsgn->Extension; - if (*lbl && strchr("12HhRr", *lbl)) - { + if (*lbl && strchr("12HhRr", *lbl)) { putc(':', fpout); putc(*lbl, fpout); n += 2; @@ -1344,26 +1368,31 @@ int PrintFullHM_SgName(const T_TabSgName *tsgn, int space, FILE *fpout) } -void PrintTabSgNameEntry(const T_TabSgName *tsgn, int Style, int space, - FILE *fpout) +void PrintTabSgNameEntry(const T_TabSgName * tsgn, int Style, int space, + FILE * fpout) { - int n; - const char *lbl, *SfSymbol; + int n; + const char *lbl, *SfSymbol; if (Style) n = fprintf(fpout, "%3d", tsgn->SgNumber); else - n = fprintf(fpout, "%d", tsgn->SgNumber); + n = fprintf(fpout, "%d", tsgn->SgNumber); if (tsgn->Extension[0]) n += fprintf(fpout, ":%s", tsgn->Extension); if (Style) - while (n < 9) { putc(' ', fpout); n++; } + while (n < 9) { + putc(' ', fpout); + n++; + } - putc(' ', fpout); n++; - putc(' ', fpout); n++; + putc(' ', fpout); + n++; + putc(' ', fpout); + n++; if (tsgn->SgNumber >= 1 && tsgn->SgNumber <= 230) SfSymbol = SchoenfliesSymbols[tsgn->SgNumber]; @@ -1373,38 +1402,53 @@ void PrintTabSgNameEntry(const T_TabSgName *tsgn, int Style, int space, n += fprintf(fpout, "%s", SfSymbol); if (Style) - while (n < 23) { putc(' ', fpout); n++; } + while (n < 23) { + putc(' ', fpout); + n++; + } - putc(' ', fpout); n++; - putc(' ', fpout); n++; + putc(' ', fpout); + n++; + putc(' ', fpout); + n++; - if (tsgn->SgNumber >= 3 && tsgn->SgNumber < 16) - { + if (tsgn->SgNumber >= 3 && tsgn->SgNumber < 16) { lbl = PrintSgLabel(tsgn->SgLabels, space, &n, fpout); if (tsgn->Extension[0]) n += fprintf(fpout, ":%s", tsgn->Extension); - putc(' ', fpout); putc('=', fpout); putc(' ', fpout); n += 3; + putc(' ', fpout); + putc('=', fpout); + putc(' ', fpout); + n += 3; n += PrintFullHM_SgName(tsgn, space, fpout); - while (*lbl) if (*lbl++ == '=') break; - while (*lbl) if (*lbl++ == '=') break; + while (*lbl) + if (*lbl++ == '=') + break; + while (*lbl) + if (*lbl++ == '=') + break; SkipWhite(lbl); - if (*lbl) - { - putc(' ', fpout); putc('=', fpout); putc(' ', fpout); n += 3; + if (*lbl) { + putc(' ', fpout); + putc('=', fpout); + putc(' ', fpout); + n += 3; PrintSgLabel(lbl, space, &n, fpout); } - } - else + } else n += PrintFullHM_SgName(tsgn, space, fpout); if (Style) - while (n < 51) { putc(' ', fpout); n++; } + while (n < 51) { + putc(' ', fpout); + n++; + } putc(' ', fpout); putc(' ', fpout); @@ -1415,21 +1459,32 @@ void PrintTabSgNameEntry(const T_TabSgName *tsgn, int Style, int space, static int FindGCD2(int ri, int rj) { - int rk; + int rk; - if (ri < 0) ri = -ri; + if (ri < 0) + ri = -ri; - if (rj) - { - for (;;) - { - rk = ri % rj; if (rk == 0) { ri = rj; break; } - ri = rj % rk; if (ri == 0) { ri = rk; break; } - rj = rk % ri; if (rj == 0) { break; } + if (rj) { + for (;;) { + rk = ri % rj; + if (rk == 0) { + ri = rj; + break; + } + ri = rj % rk; + if (ri == 0) { + ri = rk; + break; + } + rj = rk % ri; + if (rj == 0) { + break; + } } - if (ri < 0) ri = -ri; + if (ri < 0) + ri = -ri; } return ri; @@ -1439,8 +1494,7 @@ static int FindGCD2(int ri, int rj) static void SimplifyFraction(int nume, int deno, int *o_nume, int *o_deno) { int gcd = FindGCD2(nume, deno); - if (gcd) - { + if (gcd) { *o_nume = nume / gcd; *o_deno = deno / gcd; @@ -1455,35 +1509,34 @@ static void SimplifyFraction(int nume, int deno, int *o_nume, int *o_deno) const char *FormatFraction(int nume, int deno, int Decimal, char *Buffer, int SizeBuffer) { - int n, d; - char *cp, *cpp; - static char StaticBuffer[40]; + int n, d; + char *cp, *cpp; + static char StaticBuffer[40]; if (NULL == Buffer) { - Buffer = StaticBuffer; - SizeBuffer = sizeof StaticBuffer / sizeof (*StaticBuffer); + Buffer = StaticBuffer; + SizeBuffer = sizeof StaticBuffer / sizeof(*StaticBuffer); } Buffer[SizeBuffer - 1] = '\0'; - if (nume == 0) - { + if (nume == 0) { Buffer[0] = '0'; Buffer[1] = '\0'; } - if (Decimal) - { + if (Decimal) { sprintf(Buffer, "%.6g", (double) nume / deno); - cp = Buffer; - if (*cp == '-') cp++; + cp = Buffer; + if (*cp == '-') + cp++; if (*cp == '0') { - cpp = cp + 1; while (*cp) *cp++ = *cpp++; + cpp = cp + 1; + while (*cp) + *cp++ = *cpp++; } - } - else - { + } else { SimplifyFraction(nume, deno, &n, &d); if (d == 1) @@ -1493,7 +1546,7 @@ const char *FormatFraction(int nume, int deno, int Decimal, } if (Buffer[SizeBuffer - 1] != '\0') { - Buffer[SizeBuffer - 1] = '\0'; + Buffer[SizeBuffer - 1] = '\0'; SetSgError("Internal Error: FormatFraction(): Buffer too small"); return NULL; } @@ -1502,7 +1555,7 @@ const char *FormatFraction(int nume, int deno, int Decimal, } -const char *RTMx2XYZ(const T_RTMx *RTMx, int FacRo, int FacTr, +const char *RTMx2XYZ(const T_RTMx * RTMx, int FacRo, int FacTr, int Decimal, int TrFirst, int Low, const char *Seperator, char *BufferXYZ, int SizeBufferXYZ) @@ -1510,16 +1563,16 @@ const char *RTMx2XYZ(const T_RTMx *RTMx, int FacRo, int FacTr, static const char *UpperXYZ = "XYZ"; static const char *LowerXYZ = "xyz"; - int i, j, p, iRo, iTr; - char *xyz, buf_tr[32]; - const char *sep, *LetterXYZ, *ro, *tr; + int i, j, p, iRo, iTr; + char *xyz, buf_tr[32]; + const char *sep, *LetterXYZ, *ro, *tr; - static char StaticBufferXYZ[80]; + static char StaticBufferXYZ[80]; if (NULL == BufferXYZ) { - BufferXYZ = StaticBufferXYZ; - SizeBufferXYZ = sizeof StaticBufferXYZ / sizeof (*StaticBufferXYZ); + BufferXYZ = StaticBufferXYZ; + SizeBufferXYZ = sizeof StaticBufferXYZ / sizeof(*StaticBufferXYZ); } BufferXYZ[SizeBufferXYZ - 1] = '\0'; @@ -1530,47 +1583,48 @@ const char *RTMx2XYZ(const T_RTMx *RTMx, int FacRo, int FacTr, LetterXYZ = UpperXYZ; if (Seperator == NULL) - Seperator = ","; + Seperator = ","; xyz = BufferXYZ; - for (i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { if (i != 0) - for (sep = Seperator; *sep; sep++) *xyz++ = *sep; + for (sep = Seperator; *sep; sep++) + *xyz++ = *sep; - iTr = iModPositive(RTMx->s.T[i], FacTr); - if (iTr > FacTr / 2) - iTr -= FacTr; + iTr = iModPositive(RTMx->s.T[i], FacTr); + if (iTr > FacTr / 2) + iTr -= FacTr; - tr = FormatFraction(iTr, FacTr, Decimal, - buf_tr, sizeof buf_tr / sizeof (*buf_tr)); + tr = FormatFraction(iTr, FacTr, Decimal, + buf_tr, sizeof buf_tr / sizeof(*buf_tr)); if (tr == NULL) return NULL; p = 0; - if ( TrFirst && iTr) { - if (*tr) p = 1; - while (*tr) *xyz++ = *tr++; + if (TrFirst && iTr) { + if (*tr) + p = 1; + while (*tr) + *xyz++ = *tr++; } - for (j = 0; j < 3; j++) - { - iRo = RTMx->s.R[i * 3 + j]; - if (iRo) - { - ro = FormatFraction(iRo, FacRo, Decimal, NULL, 0); + for (j = 0; j < 3; j++) { + iRo = RTMx->s.R[i * 3 + j]; + if (iRo) { + ro = FormatFraction(iRo, FacRo, Decimal, NULL, 0); if (ro == NULL) return NULL; - if (*ro == '-') + if (*ro == '-') *xyz++ = *ro++; else if (*ro && p) *xyz++ = '+'; if (ro[0] != '1' || ro[1] != '\0') { - while (*ro) *xyz++ = *ro++; + while (*ro) + *xyz++ = *ro++; *xyz++ = '*'; } @@ -1580,19 +1634,19 @@ const char *RTMx2XYZ(const T_RTMx *RTMx, int FacRo, int FacTr, } } - if (! TrFirst && iTr) - { + if (!TrFirst && iTr) { if (*tr && *tr != '-' && p) *xyz++ = '+'; - while (*tr) *xyz++ = *tr++; + while (*tr) + *xyz++ = *tr++; } } *xyz = '\0'; if (BufferXYZ[SizeBufferXYZ - 1] != '\0') { - BufferXYZ[SizeBufferXYZ - 1] = '\0'; + BufferXYZ[SizeBufferXYZ - 1] = '\0'; SetSgError("Internal Error: RTMx2XYZ(): BufferXYZ too small"); return NULL; } @@ -1601,12 +1655,12 @@ const char *RTMx2XYZ(const T_RTMx *RTMx, int FacRo, int FacTr, } -void PrintMapleRTMx(const T_RTMx *RTMx, int FacRo, int FacTr, - const char *Label, FILE *fpout) +void PrintMapleRTMx(const T_RTMx * RTMx, int FacRo, int FacTr, + const char *Label, FILE * fpout) { - int i, j, nt; - const int *r, *t; - const char *ff; + int i, j, nt; + const int *r, *t; + const char *ff; if (Label) @@ -1617,24 +1671,22 @@ void PrintMapleRTMx(const T_RTMx *RTMx, int FacRo, int FacTr, r = RTMx->s.R; t = RTMx->s.T; - for (i = 0; i < 3; i++, t++) - { + for (i = 0; i < 3; i++, t++) { putc(' ', fpout); - for (j = 0; j < 3; j++, r++) - { - ff = FormatFraction(*r, FacRo, 0, NULL, 0); + for (j = 0; j < 3; j++, r++) { + ff = FormatFraction(*r, FacRo, 0, NULL, 0); if (ff == NULL) return; fprintf(fpout, "%s,", ff); } - nt = iModPositive(*t, FacTr); - if (nt > FacTr / 2) - nt -= FacTr; + nt = iModPositive(*t, FacTr); + if (nt > FacTr / 2) + nt -= FacTr; - ff = FormatFraction(nt, FacTr, 0, NULL, 0); + ff = FormatFraction(nt, FacTr, 0, NULL, 0); if (ff == NULL) return; @@ -1645,27 +1697,26 @@ void PrintMapleRTMx(const T_RTMx *RTMx, int FacRo, int FacTr, } -static void PrintSeitzMx(const T_RTMx *SMx, FILE *fpout) +static void PrintSeitzMx(const T_RTMx * SMx, FILE * fpout) { - int i, nt; - const char *ff; - const int *r, *t; + int i, nt; + const char *ff; + const int *r, *t; r = SMx->s.R; t = SMx->s.T; - for (i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { fprintf(fpout, " %2d", *r++); fprintf(fpout, " %2d", *r++); fprintf(fpout, " %2d", *r++); - nt = iModPositive(*t++, STBF); - if (nt > STBF / 2) - nt -= STBF; + nt = iModPositive(*t++, STBF); + if (nt > STBF / 2) + nt -= STBF; - ff = FormatFraction(nt, STBF, 0, NULL, 0); + ff = FormatFraction(nt, STBF, 0, NULL, 0); if (ff == NULL) return; @@ -1676,25 +1727,25 @@ static void PrintSeitzMx(const T_RTMx *SMx, FILE *fpout) } -void ListSgInfo(const T_SgInfo *SgInfo, int F_XYZ, int F_Verbose, FILE *fpout) +void ListSgInfo(const T_SgInfo * SgInfo, int F_XYZ, int F_Verbose, + FILE * fpout) { - int iList, i_si_v; - char buf[8]; - const char *xyz; - const T_RTMx *lsmx; - T_RotMxInfo *rmxi, RotMxInfo; + int iList, i_si_v; + char buf[8]; + const char *xyz; + const T_RTMx *lsmx; + T_RotMxInfo *rmxi, RotMxInfo; iList = PG_Index(SgInfo->PointGroup); fprintf(fpout, "Point Group %s\n", PG_Names[iList]); fprintf(fpout, "Laue Group %s\n", - PG_Names[PG_Index(LG_Code_of_PG_Index[iList])]); + PG_Names[PG_Index(LG_Code_of_PG_Index[iList])]); fprintf(fpout, "%s\n", XS_Name[SgInfo->XtalSystem]); - if (SgInfo->UniqueRefAxis != 0 || SgInfo->UniqueDirCode != 0) - { + if (SgInfo->UniqueRefAxis != 0 || SgInfo->UniqueDirCode != 0) { fprintf(fpout, "Unique Axis "); if (SgInfo->UniqueRefAxis != 0 && SgInfo->UniqueRefAxis != 'o') fprintf(fpout, "%c", SgInfo->UniqueRefAxis); @@ -1715,61 +1766,62 @@ void ListSgInfo(const T_SgInfo *SgInfo, int F_XYZ, int F_Verbose, FILE *fpout) fprintf(fpout, "Order P %3d\n", SgInfo->OrderP); putc('\n', fpout); - if (SgInfo->n_si_Vector >= 0) - { + if (SgInfo->n_si_Vector >= 0) { fprintf(fpout, "s.i.Vector Modulus\n"); for (i_si_v = 0; i_si_v < SgInfo->n_si_Vector; i_si_v++) fprintf(fpout, " %2d %2d %2d %d\n", - SgInfo->si_Vector[i_si_v * 3 + 0], - SgInfo->si_Vector[i_si_v * 3 + 1], - SgInfo->si_Vector[i_si_v * 3 + 2], - SgInfo->si_Modulus[i_si_v]); + SgInfo->si_Vector[i_si_v * 3 + 0], + SgInfo->si_Vector[i_si_v * 3 + 1], + SgInfo->si_Vector[i_si_v * 3 + 2], + SgInfo->si_Modulus[i_si_v]); putc('\n', fpout); } - if (F_XYZ || F_Verbose) - { + if (F_XYZ || F_Verbose) { fprintf(fpout, "#List %3d\n", SgInfo->nList); putc('\n', fpout); lsmx = SgInfo->ListSeitzMx; rmxi = SgInfo->ListRotMxInfo; - if (rmxi == NULL) rmxi = &RotMxInfo; + if (rmxi == NULL) + rmxi = &RotMxInfo; - for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) - { - if (rmxi == &RotMxInfo) - { + for (iList = 0; iList < SgInfo->nList; iList++, lsmx++) { + if (rmxi == &RotMxInfo) { if (GetRotMxInfo(lsmx->s.R, &RotMxInfo) == 0) { SetSgError("Error: Illegal SeitzMx in list"); return; } } - if (F_Verbose) - { + if (F_Verbose) { sprintf(buf, "(%d)", iList + 1); fprintf(fpout, "%-4s", buf); fprintf(fpout, " %2d", rmxi->Order); - if (rmxi->Inverse) fprintf(fpout, "^-1"); - else fprintf(fpout, " "); + if (rmxi->Inverse) + fprintf(fpout, "^-1"); + else + fprintf(fpout, " "); fprintf(fpout, " [%2d %2d %2d]", - rmxi->EigenVector[0], - rmxi->EigenVector[1], - rmxi->EigenVector[2]); + rmxi->EigenVector[0], + rmxi->EigenVector[1], rmxi->EigenVector[2]); - if (rmxi->RefAxis) fprintf(fpout, " '%c'", rmxi->RefAxis); - else fprintf(fpout, " "); - if (rmxi->DirCode) fprintf(fpout, " '%c'", rmxi->DirCode); - else fprintf(fpout, " "); + if (rmxi->RefAxis) + fprintf(fpout, " '%c'", rmxi->RefAxis); + else + fprintf(fpout, " "); + if (rmxi->DirCode) + fprintf(fpout, " '%c'", rmxi->DirCode); + else + fprintf(fpout, " "); fprintf(fpout, " "); } - xyz = RTMx2XYZ(lsmx, 1, STBF, 0, 0, 1, ", ", NULL, 0); + xyz = RTMx2XYZ(lsmx, 1, STBF, 0, 0, 1, ", ", NULL, 0); if (xyz) fprintf(fpout, "%s", xyz); @@ -1781,7 +1833,8 @@ void ListSgInfo(const T_SgInfo *SgInfo, int F_XYZ, int F_Verbose, FILE *fpout) if (F_Verbose) PrintSeitzMx(lsmx, fpout); - if (rmxi != &RotMxInfo) rmxi++; + if (rmxi != &RotMxInfo) + rmxi++; } if (iList && F_Verbose == 0) diff --git a/sgsi.c b/sgsi.c index aaf13f02..f9f53ebd 100644 --- a/sgsi.c +++ b/sgsi.c @@ -28,89 +28,114 @@ */ -void MarkLegalOrigins(const T_SgInfo *SgInfo, int *TestField) +void MarkLegalOrigins(const T_SgInfo * SgInfo, int *TestField) { - int O[3], V[3], lx, ly, lz, mx, my, mz, i; - int IsFine, iList, iLoopInv, nLoopInv; - int BufMx[9]; - const T_RTMx *lsmx; - int nTrV, iTrV; - const int *TrV; + int O[3], V[3], lx, ly, lz, mx, my, mz, i; + int IsFine, iList, iLoopInv, nLoopInv; + int BufMx[9]; + const T_RTMx *lsmx; + int nTrV, iTrV; + const int *TrV; nLoopInv = Sg_nLoopInv(SgInfo); nTrV = SgInfo->LatticeInfo->nTrVector; - switch (SgInfo->LatticeInfo->Code) - { - default: - case 'P': lx = ly = lz = 12; break; - case 'A': lx = ly = 12; lz = 6; break; - case 'B': ly = lz = 12; lx = 6; break; - case 'C': lz = lx = 12; ly = 6; break; - case 'I': lx = ly = 12; lz = 6; break; - case 'R': lx = ly = 12; lz = 4; break; - case 'S': lz = lx = 12; ly = 4; break; - case 'T': ly = lz = 12; lx = 4; break; - case 'F': lx = 12; ly = lz = 6; break; + switch (SgInfo->LatticeInfo->Code) { + default: + case 'P': + lx = ly = lz = 12; + break; + case 'A': + lx = ly = 12; + lz = 6; + break; + case 'B': + ly = lz = 12; + lx = 6; + break; + case 'C': + lz = lx = 12; + ly = 6; + break; + case 'I': + lx = ly = 12; + lz = 6; + break; + case 'R': + lx = ly = 12; + lz = 4; + break; + case 'S': + lz = lx = 12; + ly = 4; + break; + case 'T': + ly = lz = 12; + lx = 4; + break; + case 'F': + lx = 12; + ly = lz = 6; + break; } for (O[0] = 0; O[0] < 12; O[0]++) - for (O[1] = 0; O[1] < 12; O[1]++) - for (O[2] = 0; O[2] < 12; O[2]++) - { - IsFine = 1; + for (O[1] = 0; O[1] < 12; O[1]++) + for (O[2] = 0; O[2] < 12; O[2]++) { + IsFine = 1; - for (iList = 0; IsFine && iList < SgInfo->nList; iList++) - { - lsmx = &SgInfo->ListSeitzMx[iList]; + for (iList = 0; IsFine && iList < SgInfo->nList; iList++) { + lsmx = &SgInfo->ListSeitzMx[iList]; - for (iLoopInv = 0; IsFine && iLoopInv < nLoopInv; iLoopInv++) - { - if (iLoopInv == 0) - for (i = 0; i < 9; i++) - { - if (i % 4) BufMx[i] = lsmx->s.R[i]; - else BufMx[i] = lsmx->s.R[i] - 1; + for (iLoopInv = 0; IsFine && iLoopInv < nLoopInv; iLoopInv++) { + if (iLoopInv == 0) + for (i = 0; i < 9; i++) { + if (i % 4) + BufMx[i] = lsmx->s.R[i]; + else + BufMx[i] = lsmx->s.R[i] - 1; + } else + for (i = 0; i < 9; i++) { + if (i % 4) + BufMx[i] = -lsmx->s.R[i]; + else + BufMx[i] = -lsmx->s.R[i] - 1; + } + + RotMx_t_Vector(V, BufMx, O, 12); + + TrV = SgInfo->LatticeInfo->TrVector; + + for (iTrV = 0; iTrV < nTrV; iTrV++) { + mx = (V[0] * (STBF / 12) + *TrV++) % STBF; + my = (V[1] * (STBF / 12) + *TrV++) % STBF; + mz = (V[2] * (STBF / 12) + *TrV++) % STBF; + + if (mx == 0 && my == 0 && mz == 0) + break; + } + + if (iTrV == nTrV) + IsFine = 0; } - else - for (i = 0; i < 9; i++) - { - if (i % 4) BufMx[i] = -lsmx->s.R[i]; - else BufMx[i] = -lsmx->s.R[i] - 1; - } - - RotMx_t_Vector(V, BufMx, O, 12); - - TrV = SgInfo->LatticeInfo->TrVector; - - for (iTrV = 0; iTrV < nTrV; iTrV++) - { - mx = (V[0] * (STBF / 12) + *TrV++) % STBF; - my = (V[1] * (STBF / 12) + *TrV++) % STBF; - mz = (V[2] * (STBF / 12) + *TrV++) % STBF; - - if (mx == 0 && my == 0 && mz == 0) - break; } - if (iTrV == nTrV) IsFine = 0; - } - } + if (!(O[0] < lx && O[1] < ly && O[2] < lz)) + IsFine = -IsFine; - if (! (O[0] < lx && O[1] < ly && O[2] < lz)) - IsFine = -IsFine; - - *TestField++ = IsFine; + *TestField++ = IsFine; #if DEBUG_MarkLegalOrigins - if (IsFine == 1) putc(' ', stdout); - else if (IsFine == -1) putc('#', stdout); - if (IsFine != 0) - fprintf(stdout, " %2d %2d %2d\n", O[0], O[1], O[2]); + if (IsFine == 1) + putc(' ', stdout); + else if (IsFine == -1) + putc('#', stdout); + if (IsFine != 0) + fprintf(stdout, " %2d %2d %2d\n", O[0], O[1], O[2]); #endif - } + } } @@ -121,49 +146,54 @@ void MarkLegalOrigins(const T_SgInfo *SgInfo, int *TestField) int Verify_si(int h, int k, int l, const int *TestField) { - int O[3], TH; + int O[3], TH; for (O[0] = 0; O[0] < 12; O[0]++) - for (O[1] = 0; O[1] < 12; O[1]++) - for (O[2] = 0; O[2] < 12; O[2]++) - { - if (*TestField++) - { + for (O[1] = 0; O[1] < 12; O[1]++) + for (O[2] = 0; O[2] < 12; O[2]++) { + if (*TestField++) { TH = h * O[0] + k * O[1] + l * O[2]; TH %= 12; - if (TH) return 0; + if (TH) + return 0; - if (IsArbitraryShift(O[0])) TH += h; - if (IsArbitraryShift(O[1])) TH += k; - if (IsArbitraryShift(O[2])) TH += l; - if (TH) return 0; - } - } + if (IsArbitraryShift(O[0])) + TH += h; + if (IsArbitraryShift(O[1])) + TH += k; + if (IsArbitraryShift(O[2])) + TH += l; + if (TH) + return 0; + } + } return 1; } -int Is_si(const T_SgInfo *SgInfo, int h, int k, int l) +int Is_si(const T_SgInfo * SgInfo, int h, int k, int l) { - int i_si_v, u; - const int *si_v, *si_m; + int i_si_v, u; + const int *si_v, *si_m; si_v = SgInfo->si_Vector; si_m = SgInfo->si_Modulus; - for (i_si_v = 0; i_si_v < SgInfo->n_si_Vector; i_si_v++) - { - u = *si_v++ * h; + for (i_si_v = 0; i_si_v < SgInfo->n_si_Vector; i_si_v++) { + u = *si_v++ * h; u += *si_v++ * k; u += *si_v++ * l; if (*si_m) { - if (u % (*si_m)) return 0; } - else { - if (u) return 0; } + if (u % (*si_m)) + return 0; + } else { + if (u) + return 0; + } si_m++; } @@ -172,168 +202,167 @@ int Is_si(const T_SgInfo *SgInfo, int h, int k, int l) } -int Set_si(T_SgInfo *SgInfo) +int Set_si(T_SgInfo * SgInfo) { - static const int TabTrial_si[] = - { - 0, + static const int TabTrial_si[] = { + 0, - 1, 0, 2, -1, 4, /* I -4 */ - 1, 2, -1, 0, 4, - 1, -1, 0, 2, 4, + 1, 0, 2, -1, 4, /* I -4 */ + 1, 2, -1, 0, 4, + 1, -1, 0, 2, 4, - 1, 2, 4, 3, 6, /* P 3 2 */ - 1, 4, 3, 2, 6, - 1, 3, 2, 4, 6, + 1, 2, 4, 3, 6, /* P 3 2 */ + 1, 4, 3, 2, 6, + 1, 3, 2, 4, 6, - 1, 1, 1, 1, 4, - 1, 1, 1, 1, 2, - 1, 1, 1, 1, 0, + 1, 1, 1, 1, 4, + 1, 1, 1, 1, 2, + 1, 1, 1, 1, 0, - 1, 0, 0, 1, 2, - 1, 0, 1, 0, 2, - 1, 1, 0, 0, 2, + 1, 0, 0, 1, 2, + 1, 0, 1, 0, 2, + 1, 1, 0, 0, 2, - 1, 0, 0, 1, 0, - 1, 0, 1, 0, 0, - 1, 1, 0, 0, 0, + 1, 0, 0, 1, 0, + 1, 0, 1, 0, 0, + 1, 1, 0, 0, 0, - 2, 1, -1, 0, 3, - 0, 0, 1, 0, - 2, -1, 0, 1, 3, - 0, 1, 0, 0, - 2, 0, 1, -1, 3, - 1, 0, 0, 0, + 2, 1, -1, 0, 3, + 0, 0, 1, 0, + 2, -1, 0, 1, 3, + 0, 1, 0, 0, + 2, 0, 1, -1, 3, + 1, 0, 0, 0, - 2, 0, 1, 1, 4, /* F 2x */ - 1, 0, 0, 0, - 2, 1, 0, 1, 4, /* F 2y */ - 0, 1, 0, 0, - 2, 1, 1, 0, 4, /* F 2z */ - 0, 0, 1, 0, + 2, 0, 1, 1, 4, /* F 2x */ + 1, 0, 0, 0, + 2, 1, 0, 1, 4, /* F 2y */ + 0, 1, 0, 0, + 2, 1, 1, 0, 4, /* F 2z */ + 0, 0, 1, 0, - 2, 1, 0, 0, 2, - 0, 0, 1, 2, - 2, 0, 1, 0, 2, - 0, 0, 1, 2, - 2, 1, 0, 0, 2, - 0, 1, 0, 2, + 2, 1, 0, 0, 2, + 0, 0, 1, 2, + 2, 0, 1, 0, 2, + 0, 0, 1, 2, + 2, 1, 0, 0, 2, + 0, 1, 0, 2, - 2, 1, 1, 0, 2, - 0, 0, 1, 2, - 2, 1, 0, 1, 2, - 0, 1, 0, 2, - 2, 0, 1, 1, 2, - 1, 0, 0, 2, + 2, 1, 1, 0, 2, + 0, 0, 1, 2, + 2, 1, 0, 1, 2, + 0, 1, 0, 2, + 2, 0, 1, 1, 2, + 1, 0, 0, 2, - 2, 1, 0, 0, 2, - 0, 0, 1, 0, - 2, 0, 1, 0, 2, - 0, 0, 1, 0, - 2, 1, 0, 0, 2, - 0, 1, 0, 0, + 2, 1, 0, 0, 2, + 0, 0, 1, 0, + 2, 0, 1, 0, 2, + 0, 0, 1, 0, + 2, 1, 0, 0, 2, + 0, 1, 0, 0, - 2, 1, 0, 0, 0, - 0, 0, 1, 2, - 2, 0, 1, 0, 0, - 0, 0, 1, 2, - 2, 1, 0, 0, 0, - 0, 1, 0, 2, + 2, 1, 0, 0, 0, + 0, 0, 1, 2, + 2, 0, 1, 0, 0, + 0, 0, 1, 2, + 2, 1, 0, 0, 0, + 0, 1, 0, 2, - 2, 1, 1, 0, 2, - 0, 0, 1, 0, - 2, 1, 0, 1, 2, - 0, 1, 0, 0, - 2, 0, 1, 1, 2, - 1, 0, 0, 0, + 2, 1, 1, 0, 2, + 0, 0, 1, 0, + 2, 1, 0, 1, 2, + 0, 1, 0, 0, + 2, 0, 1, 1, 2, + 1, 0, 0, 0, - 2, 1, 0, 0, 0, - 0, 0, 1, 0, - 2, 0, 1, 0, 0, - 0, 0, 1, 0, - 2, 1, 0, 0, 0, - 0, 1, 0, 0, + 2, 1, 0, 0, 0, + 0, 0, 1, 0, + 2, 0, 1, 0, 0, + 0, 0, 1, 0, + 2, 1, 0, 0, 0, + 0, 1, 0, 0, - 3, 1, 0, 0, 2, - 0, 1, 0, 2, - 0, 0, 1, 2, + 3, 1, 0, 0, 2, + 0, 1, 0, 2, + 0, 0, 1, 2, - 3, 1, 0, 0, 0, - 0, 1, 0, 2, - 0, 0, 1, 2, + 3, 1, 0, 0, 0, + 0, 1, 0, 2, + 0, 0, 1, 2, - 3, 1, 0, 0, 2, - 0, 1, 0, 0, - 0, 0, 1, 2, + 3, 1, 0, 0, 2, + 0, 1, 0, 0, + 0, 0, 1, 2, - 3, 1, 0, 0, 2, - 0, 1, 0, 2, - 0, 0, 1, 0, + 3, 1, 0, 0, 2, + 0, 1, 0, 2, + 0, 0, 1, 0, - 3, 1, 0, 0, 2, - 0, 1, 0, 0, - 0, 0, 1, 0, + 3, 1, 0, 0, 2, + 0, 1, 0, 0, + 0, 0, 1, 0, - 3, 1, 0, 0, 0, - 0, 1, 0, 2, - 0, 0, 1, 0, + 3, 1, 0, 0, 0, + 0, 1, 0, 2, + 0, 0, 1, 0, - 3, 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 2, + 3, 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 2, - 3, 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, + 3, 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, - 3, -1, 0, 0, 2, /* -A 1 */ - 0, -1, 1, 4, - 0, 1, 1, 4, + 3, -1, 0, 0, 2, /* -A 1 */ + 0, -1, 1, 4, + 0, 1, 1, 4, - 3, -1, 0, 1, 4, /* -B 1 */ - 0, -1, 0, 2, - 1, 0, 1, 4, + 3, -1, 0, 1, 4, /* -B 1 */ + 0, -1, 0, 2, + 1, 0, 1, 4, - 3, 1, 1, 0, 4, /* -C 1 */ - 1, -1, 0, 4, - 0, 0, -1, 2, + 3, 1, 1, 0, 4, /* -C 1 */ + 1, -1, 0, 4, + 0, 0, -1, 2, - 3, -1, 1, 1, 4, /* -I 1 */ - 1, -1, 1, 4, - 1, 1, -1, 4, + 3, -1, 1, 1, 4, /* -I 1 */ + 1, -1, 1, 4, + 1, 1, -1, 4, - 3, 0, 1, 1, 4, /* -F 1 */ - 1, 0, 1, 4, - 1, 1, 0, 4, + 3, 0, 1, 1, 4, /* -F 1 */ + 1, 0, 1, 4, + 1, 1, 0, 4, - 3, -1, 0, 0, 0, /* A 2x */ - 0, -1, 1, 4, - 0, 1, 1, 4, + 3, -1, 0, 0, 0, /* A 2x */ + 0, -1, 1, 4, + 0, 1, 1, 4, - 3, -1, 0, 1, 4, /* B 2y */ - 0, -1, 0, 0, - 1, 0, 1, 4, + 3, -1, 0, 1, 4, /* B 2y */ + 0, -1, 0, 0, + 1, 0, 1, 4, - 3, 1, 1, 0, 4, /* C 2z */ - 1, -1, 0, 4, - 0, 0, -1, 0, + 3, 1, 1, 0, 4, /* C 2z */ + 1, -1, 0, 4, + 0, 0, -1, 0, - -1 - }; + -1 + }; - int h, k, l, iList; - int Maxh, Maxk, Maxl; - int Minh, Mink, Minl; - int nTestField, *TestField; - int nProperty, *Property, *pp; - int IsFine, would_be, is; - int i_si, *si_v; - const int *trial_si; + int h, k, l, iList; + int Maxh, Maxk, Maxl; + int Minh, Mink, Minl; + int nTestField, *TestField; + int nProperty, *Property, *pp; + int IsFine, would_be, is; + int i_si, *si_v; + const int *trial_si; SgInfo->n_si_Vector = -1; - nTestField = 12 * 12 * 12; + nTestField = 12 * 12 * 12; AppMalloc(TestField, nTestField); if (TestField == NULL) { SetSgError("Not enough core"); @@ -345,9 +374,9 @@ int Set_si(T_SgInfo *SgInfo) Maxh = Maxk = Maxl = 7; SetListMin_hkl(SgInfo, Maxk, Maxl, &Minh, &Mink, &Minl); - nProperty = (Maxh - Minh + 1) - * (Maxk - Mink + 1) - * (Maxl - Minl + 1); + nProperty = (Maxh - Minh + 1) + * (Maxk - Mink + 1) + * (Maxl - Minl + 1); AppMalloc(Property, nProperty); if (Property == NULL) { SetSgError("Not enough core"); @@ -357,30 +386,26 @@ int Set_si(T_SgInfo *SgInfo) pp = Property; for (h = Minh; h <= Maxh; h++) - for (k = Mink; k <= Maxk; k++) - for (l = Minl; l <= Maxl; l++) - { - iList = IsSysAbsent_hkl(SgInfo, h, k, l, NULL); - if (SgError != NULL) - { - AppFree(Property, nProperty); - AppFree(TestField, nTestField); - return -1; - } + for (k = Mink; k <= Maxk; k++) + for (l = Minl; l <= Maxl; l++) { + iList = IsSysAbsent_hkl(SgInfo, h, k, l, NULL); + if (SgError != NULL) { + AppFree(Property, nProperty); + AppFree(TestField, nTestField); + return -1; + } - if (iList == 0) - *pp++ = Verify_si(h, k, l, TestField); - else - *pp++ = -1; - } + if (iList == 0) + *pp++ = Verify_si(h, k, l, TestField); + else + *pp++ = -1; + } trial_si = TabTrial_si; - while (*trial_si >= 0) - { + while (*trial_si >= 0) { SgInfo->n_si_Vector = *trial_si++; si_v = SgInfo->si_Vector; - for (i_si = 0; i_si < SgInfo->n_si_Vector; i_si++) - { + for (i_si = 0; i_si < SgInfo->n_si_Vector; i_si++) { *si_v++ = *trial_si++; *si_v++ = *trial_si++; *si_v++ = *trial_si++; @@ -391,21 +416,18 @@ int Set_si(T_SgInfo *SgInfo) pp = Property; for (h = Minh; IsFine && h <= Maxh; h++) - for (k = Mink; IsFine && k <= Maxk; k++) - for (l = Minl; IsFine && l <= Maxl; l++) - { - is = *pp++; + for (k = Mink; IsFine && k <= Maxk; k++) + for (l = Minl; IsFine && l <= Maxl; l++) { + is = *pp++; - if (is >= 0) - { - would_be = Is_si(SgInfo, h, k, l); - if (is != would_be) - IsFine = 0; - } - } + if (is >= 0) { + would_be = Is_si(SgInfo, h, k, l); + if (is != would_be) + IsFine = 0; + } + } - if (IsFine) - { + if (IsFine) { AppFree(Property, nProperty); AppFree(TestField, nTestField); return 0; @@ -422,22 +444,22 @@ int Set_si(T_SgInfo *SgInfo) } -void Set_uvw(const T_SgInfo *SgInfo, int h, int k, int l, int *uvw) +void Set_uvw(const T_SgInfo * SgInfo, int h, int k, int l, int *uvw) { - int i_si_v, u; - const int *si_v, *si_m; + int i_si_v, u; + const int *si_v, *si_m; si_v = SgInfo->si_Vector; si_m = SgInfo->si_Modulus; - for (i_si_v = 0; i_si_v < SgInfo->n_si_Vector; i_si_v++) - { - u = *si_v++ * h; + for (i_si_v = 0; i_si_v < SgInfo->n_si_Vector; i_si_v++) { + u = *si_v++ * h; u += *si_v++ * k; u += *si_v++ * l; - if (*si_m) u %= (*si_m); + if (*si_m) + u %= (*si_m); si_m++; uvw[i_si_v] = u; diff --git a/sics.h b/sics.h index c585831d..ac6cd792 100644 --- a/sics.h +++ b/sics.h @@ -10,15 +10,15 @@ #ifndef SICSSICS #define SICSSICS - typedef enum { - eTimer, - ePreset - }CounterMode; +typedef enum { + eTimer, + ePreset +} CounterMode; /* the following line suppresses const declarations in tcl.h. WARNING: including sics.h must always be done before tcl.h -> makes the compiler happy M.Z. */ -#define NO_CONST +#define NO_CONST #include #include @@ -35,7 +35,7 @@ #include "nserver.h" #include "servlog.h" - extern pServer pServ; +extern pServer pServ; /** * Decode privilege text. Implemented in access.c @@ -43,6 +43,5 @@ * @return -1 if code invalid, else the privilege code */ int decodeSICSPriv(char *privText); - + #endif - diff --git a/sicscron.c b/sicscron.c index dcb34795..738a03db 100644 --- a/sicscron.c +++ b/sicscron.c @@ -18,197 +18,180 @@ #include "sicscron.h" - typedef struct { - int iInterval; - time_t tNext; - char *pCommand; - SConnection *pCon; - int iEnd; - Statistics *stat; - } Cron, *pCron; +typedef struct { + int iInterval; + time_t tNext; + char *pCommand; + SConnection *pCon; + int iEnd; + Statistics *stat; +} Cron, *pCron; + +typedef struct { + SConnection *pCon; + int dolater; +} CronListData; - typedef struct { - SConnection *pCon; - int dolater; - } CronListData; - /*------------------------------------------------------------------------*/ - static void KillCron(void *pData) - { - pCron self = (pCron)pData; - - if(!self) - { - return; - } - if(self->pCommand) - { - free(self->pCommand); - } - if(self->pCon) - { - SCDeleteConnection(self->pCon); - } - if (self->stat) { - StatisticsKill(self->stat); - } - free(self); +static void KillCron(void *pData) +{ + pCron self = (pCron) pData; + + if (!self) { + return; } + if (self->pCommand) { + free(self->pCommand); + } + if (self->pCon) { + SCDeleteConnection(self->pCon); + } + if (self->stat) { + StatisticsKill(self->stat); + } + free(self); +} + /*-----------------------------------------------------------------------*/ - static int CronTask(void *pData) - { - Statistics *old; +static int CronTask(void *pData) +{ + Statistics *old; - pCron self = (pCron)pData; - int iRet; - Tcl_Interp *pTcl = pServ->pSics->pTcl; - time_t now; + pCron self = (pCron) pData; + int iRet; + Tcl_Interp *pTcl = pServ->pSics->pTcl; + time_t now; - if(!self) - { - return 0; - } - - now = time(NULL); - if(now >= self->tNext) - { - MacroPush(self->pCon); - old=StatisticsBegin(self->stat); - iRet = Tcl_Eval(pTcl,self->pCommand); - StatisticsEnd(old); - MacroPop(); - if (iRet != TCL_OK) { - SCPrintf(self->pCon, eLogError, - "ERROR in sicscron script: %s", pTcl->result); - self->iEnd = 0; - return 0; - } - if (self->iEnd == 2) { /* dolater command */ - self->iEnd = 0; - return 0; - } - self->tNext += self->iInterval; - if (now > self->tNext) self->tNext = now + 1; - } - return self->iEnd > 0; + if (!self) { + return 0; } + + now = time(NULL); + if (now >= self->tNext) { + MacroPush(self->pCon); + old = StatisticsBegin(self->stat); + iRet = Tcl_Eval(pTcl, self->pCommand); + StatisticsEnd(old); + MacroPop(); + if (iRet != TCL_OK) { + SCPrintf(self->pCon, eLogError, + "ERROR in sicscron script: %s", pTcl->result); + self->iEnd = 0; + return 0; + } + if (self->iEnd == 2) { /* dolater command */ + self->iEnd = 0; + return 0; + } + self->tNext += self->iInterval; + if (now > self->tNext) + self->tNext = now + 1; + } + return self->iEnd > 0; +} + /*-----------------------------------------------------------------------*/ - static void CronSignal(void *pData, int iID, void *pSigData) - { - pCron self = (pCron)pData; - int *iInt; - struct tm tm; - char datim[24]; - CronListData *data; - - if(iID == SICSINT) - { - iInt = (int *)pSigData; - if(*iInt >= eEndServer) - { - self->iEnd = 0; - } - } - if(iID == CRONLIST) { - data = pSigData; - if (self->iEnd == 2 && data->dolater) { - tm = *localtime(&self->tNext); - strftime(datim, sizeof datim, "%Y-%m-%d %T", &tm); - SCPrintf(data->pCon, eLog, "%s %s", datim, - self->pCommand); - } else if (self->iEnd == 1 && !data->dolater) { - tm = *localtime(&self->tNext); - strftime(datim, sizeof datim, "%Y-%m-%d %T", &tm); - SCPrintf(data->pCon, eLog, "%s %8d %s", datim, - self->iInterval, self->pCommand); - } - } +static void CronSignal(void *pData, int iID, void *pSigData) +{ + pCron self = (pCron) pData; + int *iInt; + struct tm tm; + char datim[24]; + CronListData *data; + + if (iID == SICSINT) { + iInt = (int *) pSigData; + if (*iInt >= eEndServer) { + self->iEnd = 0; + } } + if (iID == CRONLIST) { + data = pSigData; + if (self->iEnd == 2 && data->dolater) { + tm = *localtime(&self->tNext); + strftime(datim, sizeof datim, "%Y-%m-%d %T", &tm); + SCPrintf(data->pCon, eLog, "%s %s", datim, self->pCommand); + } else if (self->iEnd == 1 && !data->dolater) { + tm = *localtime(&self->tNext); + strftime(datim, sizeof datim, "%Y-%m-%d %T", &tm); + SCPrintf(data->pCon, eLog, "%s %8d %s", datim, + self->iInterval, self->pCommand); + } + } +} + /*-----------------------------------------------------------------------*/ - int MakeCron(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pCron pNew = NULL; - int iVal, iRet, rights; - char *cmd; - CronListData data; - - /* need user priv. */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } +int MakeCron(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pCron pNew = NULL; + int iVal, iRet, rights; + char *cmd; + CronListData data; - if (argc == 2 && strcasecmp(argv[1], "list") == 0) { - if (strcasecmp(argv[0], "dolater") == 0) { - data.dolater = 1; - SCPrintf(pCon, eError, "Date Time Command"); - } else { - data.dolater = 0; - SCPrintf(pCon, eError, "Date Time Interval Command"); - } - data.pCon = pCon; - TaskSignal(pServ->pTasker, CRONLIST, &data); - return 1; - } - - /* enough arguments? */ - if(argc < 3) - { - SCPrintf(pCon,eError,"ERROR: not enough arguments to %s", argv[0]); - return 0; - } - - /* interpret first argument as interval in seconds */ - iRet = Tcl_GetInt(pSics->pTcl,argv[1],&iVal); - if(iRet != TCL_OK) - { - SCWrite(pCon,"ERROR: failed to convert interval argument to int", - eError); - return 0; - } - - /* concatenate the rest to the command */ - cmd = Arg2Tcl(argc-2,&argv[2],NULL,0); - - /* create data structure and install task */ - pNew = (pCron)malloc(sizeof(Cron)); - if(!pNew || !cmd) - { - SCWrite(pCon,"ERROR: out of memory in sicscron",eError); - return 0; - } - pNew->pCon = SCCreateDummyConnection(pSics); - if(!pNew->pCon) - { - SCWrite(pCon,"ERROR: out of memory in sicscron",eError); - return 0; - } - rights = SCGetRights(pCon); - if (rights > usMugger) { - /* transfer the rights to the dummy connection */ - SCSetRights(pNew->pCon, rights); - } - pNew->pCommand = cmd; - pNew->tNext = time(NULL) + iVal; - if (strcasecmp(argv[0], "dolater") == 0) { - pNew->iInterval = -1; - pNew->iEnd = 2; - } else { - pNew->iInterval = iVal; - pNew->iEnd = 1; - } - pNew->stat = StatisticsNew(cmd); - - TaskRegister(pServ->pTasker, - CronTask, - CronSignal, - KillCron, - pNew, - 1); - SCSendOK(pCon); - return 1; + /* need user priv. */ + if (!SCMatchRights(pCon, usUser)) { + return 0; } + if (argc == 2 && strcasecmp(argv[1], "list") == 0) { + if (strcasecmp(argv[0], "dolater") == 0) { + data.dolater = 1; + SCPrintf(pCon, eError, "Date Time Command"); + } else { + data.dolater = 0; + SCPrintf(pCon, eError, "Date Time Interval Command"); + } + data.pCon = pCon; + TaskSignal(pServ->pTasker, CRONLIST, &data); + return 1; + } + /* enough arguments? */ + if (argc < 3) { + SCPrintf(pCon, eError, "ERROR: not enough arguments to %s", argv[0]); + return 0; + } + /* interpret first argument as interval in seconds */ + iRet = Tcl_GetInt(pSics->pTcl, argv[1], &iVal); + if (iRet != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert interval argument to int", + eError); + return 0; + } + + /* concatenate the rest to the command */ + cmd = Arg2Tcl(argc - 2, &argv[2], NULL, 0); + + /* create data structure and install task */ + pNew = (pCron) malloc(sizeof(Cron)); + if (!pNew || !cmd) { + SCWrite(pCon, "ERROR: out of memory in sicscron", eError); + return 0; + } + pNew->pCon = SCCreateDummyConnection(pSics); + if (!pNew->pCon) { + SCWrite(pCon, "ERROR: out of memory in sicscron", eError); + return 0; + } + rights = SCGetRights(pCon); + if (rights > usMugger) { + /* transfer the rights to the dummy connection */ + SCSetRights(pNew->pCon, rights); + } + pNew->pCommand = cmd; + pNew->tNext = time(NULL) + iVal; + if (strcasecmp(argv[0], "dolater") == 0) { + pNew->iInterval = -1; + pNew->iEnd = 2; + } else { + pNew->iInterval = iVal; + pNew->iEnd = 1; + } + pNew->stat = StatisticsNew(cmd); + + TaskRegister(pServ->pTasker, CronTask, CronSignal, KillCron, pNew, 1); + SCSendOK(pCon); + return 1; +} diff --git a/sicscron.h b/sicscron.h index 4baf1ea6..f8eaa0a9 100644 --- a/sicscron.h +++ b/sicscron.h @@ -7,7 +7,7 @@ --------------------------------------------------------------------------*/ #ifndef SICSCRON #define SICSCRON - int MakeCron(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeCron(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/sicsdata.c b/sicsdata.c index 6c1d12a9..b24b1223 100644 --- a/sicsdata.c +++ b/sicsdata.c @@ -22,255 +22,283 @@ #include "sicsdata.h" #define ABS(x) (x < 0 ? -(x) : (x)) /*--------------------------------------------------------------------*/ -static void KillSICSData(void *pData){ +static void KillSICSData(void *pData) +{ pSICSData self = NULL; - self = (pSICSData)pData; - if(!self){ + self = (pSICSData) pData; + if (!self) { return; } - if(self->data != NULL){ + if (self->data != NULL) { free(self->data); } - if(self->dataType != NULL){ + if (self->dataType != NULL) { free(self->dataType); } - if(self->pDes != NULL){ + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); } free(self); } + /*---------------------------------------------------------------------*/ -pSICSData createSICSData(void){ +pSICSData createSICSData(void) +{ pSICSData pNew = NULL; - pNew = (pSICSData)malloc(sizeof(SICSData)); - if(!pNew){ + pNew = (pSICSData) malloc(sizeof(SICSData)); + if (!pNew) { return NULL; } - memset(pNew,0,sizeof(SICSData)); + memset(pNew, 0, sizeof(SICSData)); pNew->pDes = CreateDescriptor("SICSData"); - pNew->data = (int *)malloc(1024*sizeof(int)); - pNew->dataType = (char *)malloc(1024*sizeof(char)); - if(pNew->pDes == NULL || pNew->data == NULL || - pNew->dataType == NULL){ + pNew->data = (int *) malloc(1024 * sizeof(int)); + pNew->dataType = (char *) malloc(1024 * sizeof(char)); + if (pNew->pDes == NULL || pNew->data == NULL || pNew->dataType == NULL) { KillSICSData(pNew); return NULL; } - memset(pNew->data,0,1024*sizeof(int)); - memset(pNew->dataType,0,1024*sizeof(char)); + memset(pNew->data, 0, 1024 * sizeof(int)); + memset(pNew->dataType, 0, 1024 * sizeof(char)); pNew->currentDataSize = 1024; pNew->dataUsed = 0; return pNew; } + /*---------------------------------------------------------------------------*/ -int getSICSDataInt(pSICSData self, int pos, int *value){ - - if(pos >= self->dataUsed || self->dataType[pos] != INTTYPE){ - return 0; - } - *value = self->data[pos]; - return 1; +int getSICSDataInt(pSICSData self, int pos, int *value) +{ + + if (pos >= self->dataUsed || self->dataType[pos] != INTTYPE) { + return 0; + } + *value = self->data[pos]; + return 1; } + /*---------------------------------------------------------------------------*/ -int getSICSDataFloat(pSICSData self, int pos, float *value){ - if(pos >= self->dataUsed || self->dataType[pos] != FLOATTYPE){ - return 0; - } - memcpy(value,&self->data[pos],sizeof(float)); - return 1; +int getSICSDataFloat(pSICSData self, int pos, float *value) +{ + if (pos >= self->dataUsed || self->dataType[pos] != FLOATTYPE) { + return 0; + } + memcpy(value, &self->data[pos], sizeof(float)); + return 1; } + /*---------------------------------------------------------------------------*/ -int setSICSDataInt(pSICSData self, int pos, int value){ - int *idata = NULL; - - idata = getSICSDataPointer(self,0,pos+1); - if(idata == NULL){ - return 0; - } - idata[pos] = value; - self->dataType[pos] = INTTYPE; - return 1; +int setSICSDataInt(pSICSData self, int pos, int value) +{ + int *idata = NULL; + + idata = getSICSDataPointer(self, 0, pos + 1); + if (idata == NULL) { + return 0; + } + idata[pos] = value; + self->dataType[pos] = INTTYPE; + return 1; } + /*----------------------------------------------------------------------------*/ -int setSICSDataFloat(pSICSData self, int pos, float value){ - int *idata = NULL; - - idata = getSICSDataPointer(self,0,pos+1); - if(idata == NULL){ - return 0; - } - memcpy(&idata[pos],&value,sizeof(float)); - self->dataType[pos] = FLOATTYPE; - return 1; +int setSICSDataFloat(pSICSData self, int pos, float value) +{ + int *idata = NULL; + + idata = getSICSDataPointer(self, 0, pos + 1); + if (idata == NULL) { + return 0; + } + memcpy(&idata[pos], &value, sizeof(float)); + self->dataType[pos] = FLOATTYPE; + return 1; } + /*-------------------------------------------------------------------*/ -int *getSICSDataPointer(pSICSData self, int start, int end){ +int *getSICSDataPointer(pSICSData self, int start, int end) +{ int newSize; int *newData = NULL; char *newType = NULL; assert(self); - if(end >= self->currentDataSize) { + if (end >= self->currentDataSize) { /* we have to resize */ - if(self->currentDataSize*2 > end){ + if (self->currentDataSize * 2 > end) { newSize = self->currentDataSize * 2.; - }else { + } else { newSize = end + self->dataUsed; } - newData = (int *)malloc(newSize*sizeof(int)); - newType = (char *)malloc(newSize*sizeof(char)); - if(newData == NULL || newType == NULL){ + newData = (int *) malloc(newSize * sizeof(int)); + newType = (char *) malloc(newSize * sizeof(char)); + if (newData == NULL || newType == NULL) { return NULL; } - memset(newData,0,newSize*sizeof(int)); - memset(newType,0,newSize*sizeof(char)); - memcpy(newData,self->data,self->dataUsed*sizeof(int)); - memcpy(newType,self->dataType,self->dataUsed*sizeof(char)); + memset(newData, 0, newSize * sizeof(int)); + memset(newType, 0, newSize * sizeof(char)); + memcpy(newData, self->data, self->dataUsed * sizeof(int)); + memcpy(newType, self->dataType, self->dataUsed * sizeof(char)); free(self->data); free(self->dataType); self->data = newData; self->dataType = newType; self->currentDataSize = newSize; } - if(end > self->dataUsed){ + if (end > self->dataUsed) { self->dataUsed = end; } return &self->data[start]; } + /*------------------------------------------------------------------------ assign a type to a couple of data values --------------------------------------------------------------------------*/ -static void assignType(pSICSData self, int start, int end, int type){ +static void assignType(pSICSData self, int start, int end, int type) +{ int i; assert(self); assert(end <= self->currentDataSize); assert(type == INTTYPE || type == FLOATTYPE); - for(i = start; i < end; i++){ + for (i = start; i < end; i++) { self->dataType[i] = type; - } -} -/*-----------------------------------------------------------------------*/ -void assignSICSType(pSICSData self, int start, int end, int type){ - assignType(self,start,end,type); + } } + +/*-----------------------------------------------------------------------*/ +void assignSICSType(pSICSData self, int start, int end, int type) +{ + assignType(self, start, end, type); +} + /*------------------------------------------------------------------------ netEncode transforms the data in the array into network format. - int become ints in network byte order - floats become fixed point and thus ints in network byte order as well -------------------------------------------------------------------------*/ -static void netEncode(pSICSData self){ +static void netEncode(pSICSData self) +{ int i; float fVal; assert(self); - for(i = 0; i < self->dataUsed; i++){ - if(self->dataType[i] == INTTYPE){ + for (i = 0; i < self->dataUsed; i++) { + if (self->dataType[i] == INTTYPE) { self->data[i] = htonl(self->data[i]); } - if(self->dataType[i] == FLOATTYPE){ - memcpy(&fVal,self->data + i,sizeof(float)); + if (self->dataType[i] == FLOATTYPE) { + memcpy(&fVal, self->data + i, sizeof(float)); fVal *= 65536.; - self->data[i] = htonl((int)fVal); + self->data[i] = htonl((int) fVal); } - } + } } + /*---------------------------------------------------------------------*/ -void clearSICSData(pSICSData self){ +void clearSICSData(pSICSData self) +{ assert(self); int clearSize = 8192; - + self->dataUsed = 0; - if(self->currentDataSize > clearSize){ + if (self->currentDataSize > clearSize) { free(self->data); free(self->dataType); - self->data = (int *)malloc(clearSize*sizeof(int)); - self->dataType = (char *)malloc(clearSize*sizeof(char)); + self->data = (int *) malloc(clearSize * sizeof(int)); + self->dataType = (char *) malloc(clearSize * sizeof(char)); self->currentDataSize = clearSize; } - memset(self->data,0,self->currentDataSize*sizeof(int)); - memset(self->dataType,0,self->currentDataSize*sizeof(char)); + memset(self->data, 0, self->currentDataSize * sizeof(int)); + memset(self->dataType, 0, self->currentDataSize * sizeof(char)); } + /*--------------------------------------------------------------------*/ -static int dumpSICSDataXY(pSICSData self, char *filename, SConnection *pCon){ +static int dumpSICSDataXY(pSICSData self, char *filename, + SConnection * pCon) +{ FILE *fd = NULL; char pBueffel[132]; int i; float fVal; - fd = fopen(filename,"w"); - if(fd == NULL){ - snprintf(pBueffel,131,"ERROR: cannot open %s", filename); - SCWrite(pCon,pBueffel,eError); + fd = fopen(filename, "w"); + if (fd == NULL) { + snprintf(pBueffel, 131, "ERROR: cannot open %s", filename); + SCWrite(pCon, pBueffel, eError); return 0; } - for(i = 0; i < self->dataUsed; i++){ - if(self->dataType[i] == INTTYPE){ - fprintf(fd,"%10d %25d\n",i,self->data[i]); + for (i = 0; i < self->dataUsed; i++) { + if (self->dataType[i] == INTTYPE) { + fprintf(fd, "%10d %25d\n", i, self->data[i]); } - if(self->dataType[i] == FLOATTYPE){ - memcpy(&fVal,self->data + i,sizeof(float)); - fprintf(fd,"%10d %25.5f\n",i,fVal); + if (self->dataType[i] == FLOATTYPE) { + memcpy(&fVal, self->data + i, sizeof(float)); + fprintf(fd, "%10d %25.5f\n", i, fVal); } } fclose(fd); SCSendOK(pCon); return 1; } + /*--------------------------------------------------------------------*/ -static int dumpSICSData(pSICSData self, char *filename, SConnection *pCon){ +static int dumpSICSData(pSICSData self, char *filename, SConnection * pCon) +{ FILE *fd = NULL; char pBueffel[132]; int i; float fVal; - fd = fopen(filename,"w"); - if(fd == NULL){ - snprintf(pBueffel,131,"ERROR: cannot open %s", filename); - SCWrite(pCon,pBueffel,eError); + fd = fopen(filename, "w"); + if (fd == NULL) { + snprintf(pBueffel, 131, "ERROR: cannot open %s", filename); + SCWrite(pCon, pBueffel, eError); return 0; } - for(i = 0; i < self->dataUsed; i++){ - if(self->dataType[i] == INTTYPE){ - fprintf(fd," %d", self->data[i]); + for (i = 0; i < self->dataUsed; i++) { + if (self->dataType[i] == INTTYPE) { + fprintf(fd, " %d", self->data[i]); } - if(self->dataType[i] == FLOATTYPE){ - memcpy(&fVal,self->data + i,sizeof(float)); - fprintf(fd," %.5f",fVal); + if (self->dataType[i] == FLOATTYPE) { + memcpy(&fVal, self->data + i, sizeof(float)); + fprintf(fd, " %.5f", fVal); } } fclose(fd); SCSendOK(pCon); return 1; } + /*-------------------------------------------------------------------*/ -static int putInt(pSICSData self, int argc, char *argv[], - SConnection *pCon, SicsInterp *pSics){ +static int putInt(pSICSData self, int argc, char *argv[], + SConnection * pCon, SicsInterp * pSics) +{ int status, iVal, pos, *iData = NULL; assert(self); - - if(argc < 2) { - SCWrite(pCon,"ERROR: not enough arguments to SICSData putint",eError); + + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to SICSData putint", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[0],&pos); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert putint position to integer", - eError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[0], &pos); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert putint position to integer", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[1],&iVal); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert putint value to integer", - eError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[1], &iVal); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert putint value to integer", + eError); return 0; } - iData = getSICSDataPointer(self,pos,pos+1); - if(!iData){ - SCWrite(pCon,"ERROR: out of memory in putint",eError); + iData = getSICSDataPointer(self, pos, pos + 1); + if (!iData) { + SCWrite(pCon, "ERROR: out of memory in putint", eError); return 0; } *iData = iVal; @@ -278,601 +306,628 @@ static int putInt(pSICSData self, int argc, char *argv[], self->dataType[pos] = INTTYPE; return 1; } + /*-------------------------------------------------------------------*/ -static int putFloat(pSICSData self, int argc, char *argv[], - SConnection *pCon, SicsInterp *pSics){ +static int putFloat(pSICSData self, int argc, char *argv[], + SConnection * pCon, SicsInterp * pSics) +{ int status, pos, *iData = NULL; float fVal; double dVal; char buffer[256]; assert(self); - - if(argc < 2) { - SCWrite(pCon,"ERROR: not enough arguments to SICSData putfloat",eError); + + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to SICSData putfloat", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[0],&pos); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert putfloat position to integer", - eError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[0], &pos); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert putfloat position to integer", + eError); return 0; } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[1],&dVal); - if(status != TCL_OK){ - snprintf(buffer,255,"ERROR: faiuld to convert putfloat value %s to float", - argv[1]); - SCWrite(pCon,buffer,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[1], &dVal); + if (status != TCL_OK) { + snprintf(buffer, 255, + "ERROR: faiuld to convert putfloat value %s to float", + argv[1]); + SCWrite(pCon, buffer, eError); return 0; } - iData = getSICSDataPointer(self,pos,pos+1); - if(!iData){ - SCWrite(pCon,"ERROR: out of memory in putfloat",eError); + iData = getSICSDataPointer(self, pos, pos + 1); + if (!iData) { + SCWrite(pCon, "ERROR: out of memory in putfloat", eError); return 0; } - fVal = (float)dVal; - memcpy(iData,&fVal,sizeof(float)); + fVal = (float) dVal; + memcpy(iData, &fVal, sizeof(float)); self->dataType[pos] = FLOATTYPE; SCSendOK(pCon); return 1; } + /*------------------------------------------------------------------*/ -static int getPos(pSICSData self, char *name, - SConnection *pCon, int pos){ - char pBueffel[512]; - float value; - - if(pos >= self->dataUsed){ - SCWrite(pCon,"ERROR: requested position out of range",eError); - return 0; - } - if(self->dataType[pos] == FLOATTYPE){ - memcpy(&value,&self->data[pos],sizeof(float)); - snprintf(pBueffel,511,"%s = %f", name, value); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - if(self->dataType[pos] == INTTYPE){ - snprintf(pBueffel,511,"%s = %d", name, self->data[pos]); - SCWrite(pCon,pBueffel,eValue); - return 1; - } +static int getPos(pSICSData self, char *name, SConnection * pCon, int pos) +{ + char pBueffel[512]; + float value; + + if (pos >= self->dataUsed) { + SCWrite(pCon, "ERROR: requested position out of range", eError); return 0; + } + if (self->dataType[pos] == FLOATTYPE) { + memcpy(&value, &self->data[pos], sizeof(float)); + snprintf(pBueffel, 511, "%s = %f", name, value); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + if (self->dataType[pos] == INTTYPE) { + snprintf(pBueffel, 511, "%s = %d", name, self->data[pos]); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + return 0; } + /*------------------------------------------------------------------*/ -static float getDataPos(pSICSData self, int pos){ - float value; - - assert(pos < self->dataUsed); - if(self->dataType[pos] == FLOATTYPE){ - memcpy(&value,&self->data[pos],sizeof(float)); - } else { - value = (float)self->data[pos]; - } - return value; +static float getDataPos(pSICSData self, int pos) +{ + float value; + + assert(pos < self->dataUsed); + if (self->dataType[pos] == FLOATTYPE) { + memcpy(&value, &self->data[pos], sizeof(float)); + } else { + value = (float) self->data[pos]; + } + return value; } + /*------------------------------------------------------------------*/ -static int divideSicsData(pSICSData self, SicsInterp *pSics, - SConnection *pCon, char *name){ - int i; - pSICSData other = NULL; - float val, div; - - other = (pSICSData)FindCommandData(pSics,name,"SICSData"); - if(other == NULL){ - SCWrite(pCon,"ERROR: requested SICSData object to divide not found", - eError); - return 0; - } - if(other->dataUsed < self->dataUsed){ - SCWrite(pCon,"ERROR: not enough data in SICSData for division", +static int divideSicsData(pSICSData self, SicsInterp * pSics, + SConnection * pCon, char *name) +{ + int i; + pSICSData other = NULL; + float val, div; + + other = (pSICSData) FindCommandData(pSics, name, "SICSData"); + if (other == NULL) { + SCWrite(pCon, "ERROR: requested SICSData object to divide not found", eError); - return 0; + return 0; + } + if (other->dataUsed < self->dataUsed) { + SCWrite(pCon, "ERROR: not enough data in SICSData for division", + eError); + return 0; + } + for (i = 0; i < self->dataUsed; i++) { + div = getDataPos(other, i); + if (ABS(div) > .00001) { + val = getDataPos(self, i) / div; + } else { + val = .0; } - for(i = 0; i < self->dataUsed; i++){ - div = getDataPos(other,i); - if(ABS(div) > .00001){ - val = getDataPos(self,i)/div; - } else { - val = .0; - } - if(self->dataType[i] == INTTYPE){ - self->data[i] = (int)val; - } else { - memcpy(&self->data[i],&val,sizeof(float)); - } - } - return 1; -} + if (self->dataType[i] == INTTYPE) { + self->data[i] = (int) val; + } else { + memcpy(&self->data[i], &val, sizeof(float)); + } + } + return 1; +} + /*------------------------------------------------------------------*/ -static int scaleSicsData(pSICSData self, SicsInterp *pSics, - SConnection *pCon, float scale){ - int i; - float div; - - for(i = 0; i < self->dataUsed; i++){ - div = getDataPos(self,i); - div *= scale; - if(self->dataType[i] == INTTYPE){ - self->data[i] = (int)fabsf(div); - } else { - memcpy(&self->data[i],&div,sizeof(float)); - } - } - return 1; -} +static int scaleSicsData(pSICSData self, SicsInterp * pSics, + SConnection * pCon, float scale) +{ + int i; + float div; + + for (i = 0; i < self->dataUsed; i++) { + div = getDataPos(self, i); + div *= scale; + if (self->dataType[i] == INTTYPE) { + self->data[i] = (int) fabsf(div); + } else { + memcpy(&self->data[i], &div, sizeof(float)); + } + } + return 1; +} + /*-------------------------------------------------------------------*/ -static int copyScanCounts(pSICSData self, int argc, char *argv[], - SConnection *pCon, SicsInterp *pSics){ - int status, pos, np ,i; +static int copyScanCounts(pSICSData self, int argc, char *argv[], + SConnection * pCon, SicsInterp * pSics) +{ + int status, pos, np, i; pScanData pScan = NULL; int *iData = NULL; long *lData = NULL; - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to SICSData copyscancounts", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to SICSData copyscancounts", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[0],&pos); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[0], &pos); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyscancounts position to integer", - eError); + "ERROR: failed to convert copyscancounts position to integer", + eError); return 0; } - pScan = FindCommandData(pSics,argv[1],"ScanObject"); - if(!pScan){ - SCWrite(pCon,"ERROR: scan object not found in copyscancounts", - eError); + pScan = FindCommandData(pSics, argv[1], "ScanObject"); + if (!pScan) { + SCWrite(pCon, "ERROR: scan object not found in copyscancounts", + eError); return 0; } np = GetScanNP(pScan); - iData = getSICSDataPointer(self,pos,pos+np); - lData = (long *)malloc(np*sizeof(long)); - if(!iData || !lData){ - SCWrite(pCon,"ERROR: out of memory in copyscancounts",eError); + iData = getSICSDataPointer(self, pos, pos + np); + lData = (long *) malloc(np * sizeof(long)); + if (!iData || !lData) { + SCWrite(pCon, "ERROR: out of memory in copyscancounts", eError); return 0; } - memset(lData,0,np*sizeof(long)); - GetScanCounts(pScan,lData,np); - for(i = 0; i < np; i++){ - self->data[pos + i] = (int)lData[i]; + memset(lData, 0, np * sizeof(long)); + GetScanCounts(pScan, lData, np); + for (i = 0; i < np; i++) { + self->data[pos + i] = (int) lData[i]; self->dataType[pos + i] = INTTYPE; } free(lData); SCSendOK(pCon); return 1; } + /*-------------------------------------------------------------------*/ -static int copyScanMonitor(pSICSData self, int argc, char *argv[], - SConnection *pCon, SicsInterp *pSics){ - int status, pos, np ,i, monitor; +static int copyScanMonitor(pSICSData self, int argc, char *argv[], + SConnection * pCon, SicsInterp * pSics) +{ + int status, pos, np, i, monitor; pScanData pScan = NULL; int *iData = NULL; long *lData = NULL; - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to SICSData copyscanmon", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to SICSData copyscanmon", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[0],&pos); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[0], &pos); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyscancounts position to integer", - eError); + "ERROR: failed to convert copyscancounts position to integer", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&monitor); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &monitor); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyscancounts monitor to integer", - eError); + "ERROR: failed to convert copyscancounts monitor to integer", + eError); return 0; } - pScan = FindCommandData(pSics,argv[1],"ScanObject"); - if(!pScan){ - SCWrite(pCon,"ERROR: scan object not found in copyscanmonitor", - eError); + pScan = FindCommandData(pSics, argv[1], "ScanObject"); + if (!pScan) { + SCWrite(pCon, "ERROR: scan object not found in copyscanmonitor", + eError); return 0; } np = GetScanNP(pScan); - iData = getSICSDataPointer(self,pos,pos+np); - lData = (long *)malloc(np*sizeof(long)); - if(!iData || !lData){ - SCWrite(pCon,"ERROR: out of memory in copyscanmonitor",eError); + iData = getSICSDataPointer(self, pos, pos + np); + lData = (long *) malloc(np * sizeof(long)); + if (!iData || !lData) { + SCWrite(pCon, "ERROR: out of memory in copyscanmonitor", eError); return 0; } - memset(lData,0,np*sizeof(long)); - GetScanMonitor(pScan,monitor,lData,np); - for(i = 0; i < np; i++){ - self->data[pos + i] = (int)lData[i]; + memset(lData, 0, np * sizeof(long)); + GetScanMonitor(pScan, monitor, lData, np); + for (i = 0; i < np; i++) { + self->data[pos + i] = (int) lData[i]; self->dataType[pos + i] = INTTYPE; } free(lData); SCSendOK(pCon); return 1; } + /*-------------------------------------------------------------------*/ -static int copyScanVar(pSICSData self, int argc, char *argv[], - SConnection *pCon, SicsInterp *pSics){ - int status, pos, np ,i, var; +static int copyScanVar(pSICSData self, int argc, char *argv[], + SConnection * pCon, SicsInterp * pSics) +{ + int status, pos, np, i, var; pScanData pScan = NULL; int *iData = NULL; float *fData = NULL; - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to SICSData copyscanvar", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to SICSData copyscanvar", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[0],&pos); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[0], &pos); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyscanvar position to integer", - eError); + "ERROR: failed to convert copyscanvar position to integer", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&var); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &var); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyscanvar varID to integer", - eError); + "ERROR: failed to convert copyscanvar varID to integer", + eError); return 0; } - pScan = FindCommandData(pSics,argv[1],"ScanObject"); - if(!pScan){ - SCWrite(pCon,"ERROR: scan object not found in copyscanvar", - eError); + pScan = FindCommandData(pSics, argv[1], "ScanObject"); + if (!pScan) { + SCWrite(pCon, "ERROR: scan object not found in copyscanvar", eError); return 0; } np = GetScanNP(pScan); - iData = getSICSDataPointer(self,pos,pos+np); - fData = (float *)malloc(np*sizeof(float)); - if(!iData || !fData){ - SCWrite(pCon,"ERROR: out of memory in copyscanvar",eError); + iData = getSICSDataPointer(self, pos, pos + np); + fData = (float *) malloc(np * sizeof(float)); + if (!iData || !fData) { + SCWrite(pCon, "ERROR: out of memory in copyscanvar", eError); return 0; } - memset(fData,0,np*sizeof(float)); - GetSoftScanVar(pScan,var,fData,np); - for(i = 0; i < np; i++){ - memcpy(self->data + pos +i,fData + i,sizeof(float)); + memset(fData, 0, np * sizeof(float)); + GetSoftScanVar(pScan, var, fData, np); + for (i = 0; i < np; i++) { + memcpy(self->data + pos + i, fData + i, sizeof(float)); self->dataType[pos + i] = FLOATTYPE; } free(fData); SCSendOK(pCon); return 1; } + /*--------------------------------------------------------------------*/ -static int copyTimeBin(pSICSData self, int argc, char *argv[], - SConnection *pCon, SicsInterp *pSics){ +static int copyTimeBin(pSICSData self, int argc, char *argv[], + SConnection * pCon, SicsInterp * pSics) +{ int status, noTimeBin, pos, i; pHistMem pHist = NULL; const float *fTimeBin = NULL; int *iData = NULL; - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to SICSData copytimebin", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to SICSData copytimebin", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[0],&pos); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[0], &pos); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copytimebin position to integer", - eError); + "ERROR: failed to convert copytimebin position to integer", + eError); return 0; } - pHist = (pHistMem)FindCommandData(pSics,argv[1],"HistMem"); - if(!pHist){ - SCWrite(pCon,"ERROR: histogram memory not found in copytimebin", - eError); + pHist = (pHistMem) FindCommandData(pSics, argv[1], "HistMem"); + if (!pHist) { + SCWrite(pCon, "ERROR: histogram memory not found in copytimebin", + eError); return 0; } - fTimeBin = GetHistTimeBin(pHist,&noTimeBin); - iData = getSICSDataPointer(self,pos,pos+noTimeBin); - if(!fTimeBin || !iData){ - SCWrite(pCon,"ERROR: out of memory in SICSData copytimebin",eError); + fTimeBin = GetHistTimeBin(pHist, &noTimeBin); + iData = getSICSDataPointer(self, pos, pos + noTimeBin); + if (!fTimeBin || !iData) { + SCWrite(pCon, "ERROR: out of memory in SICSData copytimebin", eError); return 0; } - for(i = 0; i < noTimeBin; i++){ - setSICSDataInt(self,pos+i,(int)(fTimeBin[i])); + for (i = 0; i < noTimeBin; i++) { + setSICSDataInt(self, pos + i, (int) (fTimeBin[i])); } SCSendOK(pCon); return 1; } + /*--------------------------------------------------------------------*/ -static int copyHM(pSICSData self, int argc, char *argv[], - SConnection *pCon, SicsInterp *pSics){ +static int copyHM(pSICSData self, int argc, char *argv[], + SConnection * pCon, SicsInterp * pSics) +{ int status, pos, i, subset = 0, start, end; pHistMem pHist = NULL; const float *fTimeBin = NULL; int *iData = NULL; - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to SICSData copyhm", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to SICSData copyhm", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[0],&pos); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[0], &pos); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyhm position to integer", - eError); + "ERROR: failed to convert copyhm position to integer", eError); return 0; } - pHist = (pHistMem)FindCommandData(pSics,argv[1],"HistMem"); - if(!pHist){ - SCWrite(pCon,"ERROR: histogram memory not found in copytimebin", - eError); + pHist = (pHistMem) FindCommandData(pSics, argv[1], "HistMem"); + if (!pHist) { + SCWrite(pCon, "ERROR: histogram memory not found in copytimebin", + eError); return 0; } start = 0; end = GetHistLength(pHist); - if(argc > 3) { + if (argc > 3) { subset = 1; - status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&start); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &start); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyhm start to integer", - eError); + "ERROR: failed to convert copyhm start to integer", eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[3],&end); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[3], &end); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyhm end to integer", - eError); + "ERROR: failed to convert copyhm end to integer", eError); return 0; } } - iData = getSICSDataPointer(self,pos,pos+(end-start)); - if(!iData){ - SCWrite(pCon,"ERROR: out of memory in SICSData copyhm",eError); + iData = getSICSDataPointer(self, pos, pos + (end - start)); + if (!iData) { + SCWrite(pCon, "ERROR: out of memory in SICSData copyhm", eError); return 0; } - GetHistogramDirect(pHist,pCon,0,start,end,iData,(end-start)*sizeof(int)); - assignType(self,pos,pos+(end-start),INTTYPE); + GetHistogramDirect(pHist, pCon, 0, start, end, iData, + (end - start) * sizeof(int)); + assignType(self, pos, pos + (end - start), INTTYPE); SCSendOK(pCon); return 1; } + /*--------------------------------------------------------------------*/ -static int copyHMBank(pSICSData self, int argc, char *argv[], - SConnection *pCon, SicsInterp *pSics){ +static int copyHMBank(pSICSData self, int argc, char *argv[], + SConnection * pCon, SicsInterp * pSics) +{ int status, pos, i, bank, dataLength; pHistMem pHist = NULL; const float *fTimeBin = NULL; int *iData = NULL; - if(argc < 4){ - SCWrite(pCon,"ERROR: not enough arguments to SICSData copyhm", - eError); + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough arguments to SICSData copyhm", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[0],&pos); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[0], &pos); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyhmbank position to integer", - eError); + "ERROR: failed to convert copyhmbank position to integer", + eError); return 0; } - pHist = (pHistMem)FindCommandData(pSics,argv[1],"HistMem"); - if(!pHist){ - SCWrite(pCon,"ERROR: histogram memory not found in copyhmbank", - eError); + pHist = (pHistMem) FindCommandData(pSics, argv[1], "HistMem"); + if (!pHist) { + SCWrite(pCon, "ERROR: histogram memory not found in copyhmbank", + eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&bank); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &bank); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyhmbank bank to integer", - eError); + "ERROR: failed to convert copyhmbank bank to integer", eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[3],&dataLength); - if(status != TCL_OK){ + status = Tcl_GetInt(InterpGetTcl(pSics), argv[3], &dataLength); + if (status != TCL_OK) { SCWrite(pCon, - "ERROR: failed to convert copyhmbank dataLength to integer", - eError); + "ERROR: failed to convert copyhmbank dataLength to integer", + eError); return 0; } - - iData = getSICSDataPointer(self,pos,pos+dataLength); - if(!iData){ - SCWrite(pCon,"ERROR: out of memory in SICSData copyhmbank",eError); + + iData = getSICSDataPointer(self, pos, pos + dataLength); + if (!iData) { + SCWrite(pCon, "ERROR: out of memory in SICSData copyhmbank", eError); return 0; } - GetHistogramDirect(pHist,pCon,bank,0,dataLength,iData, - dataLength*sizeof(int)); - assignType(self,pos,pos+dataLength,INTTYPE); + GetHistogramDirect(pHist, pCon, bank, 0, dataLength, iData, + dataLength * sizeof(int)); + assignType(self, pos, pos + dataLength, INTTYPE); SCSendOK(pCon); return 1; } -/*----------------------------------------------------------------------*/ -static int copyData(pSICSData self,SicsInterp *pSics, - SConnection *pCon,int argc, char *argv[]){ - pSICSData other = NULL; - int pos, start, end, i; - - if(argc < 6){ - SCWrite(pCon,"ERROR: Insufficient number of arguments to copydata", - eError); - return 0; - } - pos = atoi(argv[2]); - start = atoi(argv[4]); - end = atoi(argv[5]); - if((other = FindCommandData(pSics,argv[3],"SICSData")) == NULL){ - SCWrite(pCon,"ERROR: invalid SICSData requested",eError); - return 0; - } - if(start > end || end > other->dataUsed){ - SCWrite(pCon,"ERROR: invalid copy range specified",eError); - return 0; - } - getSICSDataPointer(self,pos, pos + (end -start)); - memcpy(&self->data[pos],&other->data[start],(end-start)*sizeof(int)); - memcpy(&self->dataType[pos],&other->dataType[start], - (end-start)*sizeof(char)); - return 1; -} +/*----------------------------------------------------------------------*/ +static int copyData(pSICSData self, SicsInterp * pSics, + SConnection * pCon, int argc, char *argv[]) +{ + pSICSData other = NULL; + int pos, start, end, i; + + if (argc < 6) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to copydata", + eError); + return 0; + } + pos = atoi(argv[2]); + start = atoi(argv[4]); + end = atoi(argv[5]); + if ((other = FindCommandData(pSics, argv[3], "SICSData")) == NULL) { + SCWrite(pCon, "ERROR: invalid SICSData requested", eError); + return 0; + } + if (start > end || end > other->dataUsed) { + SCWrite(pCon, "ERROR: invalid copy range specified", eError); + return 0; + } + getSICSDataPointer(self, pos, pos + (end - start)); + memcpy(&self->data[pos], &other->data[start], + (end - start) * sizeof(int)); + memcpy(&self->dataType[pos], &other->dataType[start], + (end - start) * sizeof(char)); + + return 1; +} + /*---------------------------------------------------------------------- Look here in order to find out about commands understood ----------------------------------------------------------------------*/ -int SICSDataAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int SICSDataAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pSICSData self = NULL; char pBueffel[132]; int pos; float scale; - self = (pSICSData)pData; + self = (pSICSData) pData; assert(self); - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to act upon data",eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to act upon data", eError); return 0; } strtolower(argv[1]); /*------ clear*/ - if(strcmp(argv[1],"clear") == 0){ + if (strcmp(argv[1], "clear") == 0) { clearSICSData(self); SCSendOK(pCon); return 1; - } else if (strcmp(argv[1],"used") == 0){ + } else if (strcmp(argv[1], "used") == 0) { /*--------- used */ - snprintf(pBueffel,131,"%s = %d", argv[0], self->dataUsed); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 131, "%s = %d", argv[0], self->dataUsed); + SCWrite(pCon, pBueffel, eValue); return 1; - } else if(strcmp(argv[1],"dumpxy") == 0){ + } else if (strcmp(argv[1], "dumpxy") == 0) { /* --------- dump */ - if(argc < 3){ - SCWrite(pCon,"ERROR: need a file name to dump to",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: need a file name to dump to", eError); return 0; } - return dumpSICSDataXY(self,argv[2],pCon); - } else if(strcmp(argv[1],"dump") == 0){ + return dumpSICSDataXY(self, argv[2], pCon); + } else if (strcmp(argv[1], "dump") == 0) { /* --------- dump */ - if(argc < 3){ - SCWrite(pCon,"ERROR: need a file name to dump to",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: need a file name to dump to", eError); return 0; } - return dumpSICSData(self,argv[2],pCon); - } else if(strcmp(argv[1],"get") == 0){ - if(argc < 3){ - SCWrite(pCon,"ERROR: need a position to read",eError); + return dumpSICSData(self, argv[2], pCon); + } else if (strcmp(argv[1], "get") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: need a position to read", eError); return 0; } pos = atoi(argv[2]); - return getPos(self,argv[0],pCon,pos); - } else if(strcmp(argv[1],"divideby") == 0){ - if(argc < 3){ - SCWrite(pCon,"ERROR: need a SICSdata to divide by",eError); + return getPos(self, argv[0], pCon, pos); + } else if (strcmp(argv[1], "divideby") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: need a SICSdata to divide by", eError); return 0; } - return divideSicsData(self,pSics,pCon,argv[2]); - } else if(strcmp(argv[1],"scale") == 0){ - if(argc < 3){ - SCWrite(pCon,"ERROR: need a scale factor to apply",eError); + return divideSicsData(self, pSics, pCon, argv[2]); + } else if (strcmp(argv[1], "scale") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: need a scale factor to apply", eError); return 0; } - return scaleSicsData(self,pSics,pCon,atof(argv[2])); - } else if(strcmp(argv[1],"copydata") == 0){ - return copyData(self,pSics,pCon,argc, argv); - } else if(strcmp(argv[1],"putint") == 0){ + return scaleSicsData(self, pSics, pCon, atof(argv[2])); + } else if (strcmp(argv[1], "copydata") == 0) { + return copyData(self, pSics, pCon, argc, argv); + } else if (strcmp(argv[1], "putint") == 0) { /*---------- putint */ - return putInt(self,argc-2,&argv[2],pCon, pSics); - } else if(strcmp(argv[1],"putfloat") == 0){ + return putInt(self, argc - 2, &argv[2], pCon, pSics); + } else if (strcmp(argv[1], "putfloat") == 0) { /*---------- putfloat */ - return putFloat(self,argc-2,&argv[2],pCon, pSics); - } else if(strcmp(argv[1],"copyscancounts") == 0){ + return putFloat(self, argc - 2, &argv[2], pCon, pSics); + } else if (strcmp(argv[1], "copyscancounts") == 0) { /*-------- copyscancounts*/ - return copyScanCounts(self,argc-2,&argv[2],pCon,pSics); - } else if(strcmp(argv[1],"copyscanmon") == 0){ + return copyScanCounts(self, argc - 2, &argv[2], pCon, pSics); + } else if (strcmp(argv[1], "copyscanmon") == 0) { /*-------- copyscanmon*/ - return copyScanMonitor(self,argc-2,&argv[2],pCon,pSics); - } else if(strcmp(argv[1],"copyscanvar") == 0){ + return copyScanMonitor(self, argc - 2, &argv[2], pCon, pSics); + } else if (strcmp(argv[1], "copyscanvar") == 0) { /*--------- copyscanvar */ - return copyScanVar(self,argc-2,&argv[2],pCon,pSics); - } else if(strcmp(argv[1],"copytimebin") == 0){ + return copyScanVar(self, argc - 2, &argv[2], pCon, pSics); + } else if (strcmp(argv[1], "copytimebin") == 0) { /*--------- copytimebin */ - return copyTimeBin(self,argc-2,&argv[2],pCon,pSics); - } else if(strcmp(argv[1],"copyhm") == 0){ + return copyTimeBin(self, argc - 2, &argv[2], pCon, pSics); + } else if (strcmp(argv[1], "copyhm") == 0) { /*--------- copyhm */ - return copyHM(self,argc-2,&argv[2],pCon,pSics); - } else if(strcmp(argv[1],"copyhmbank") == 0){ + return copyHM(self, argc - 2, &argv[2], pCon, pSics); + } else if (strcmp(argv[1], "copyhmbank") == 0) { /*--------- copyhmbank */ - return copyHMBank(self,argc-2,&argv[2],pCon,pSics); - } else if(strcmp(argv[1],"writezipped") == 0){ + return copyHMBank(self, argc - 2, &argv[2], pCon, pSics); + } else if (strcmp(argv[1], "writezipped") == 0) { /*--------- writezipped */ - if(argc < 3){ - SCWrite(pCon,"ERROR: need a name for writezipped",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: need a name for writezipped", eError); return 0; } netEncode(self); - SCWriteZipped(pCon,argv[2],self->data,self->dataUsed*sizeof(int)); + SCWriteZipped(pCon, argv[2], self->data, self->dataUsed * sizeof(int)); return 1; - } else if(strcmp(argv[1],"writeuu") == 0){ + } else if (strcmp(argv[1], "writeuu") == 0) { /*--------- writeuu */ - if(argc < 3){ - SCWrite(pCon,"ERROR: need a name for writeuu",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: need a name for writeuu", eError); return 0; } netEncode(self); - SCWriteUUencoded(pCon,argv[2],self->data,self->dataUsed*sizeof(int)); + SCWriteUUencoded(pCon, argv[2], self->data, + self->dataUsed * sizeof(int)); return 1; } - SCWrite(pCon,"ERROR: object command to SICSData not recognized",eError); + SCWrite(pCon, "ERROR: object command to SICSData not recognized", + eError); return 0; } + /*----------------------------------------------------------------------*/ -int SICSDataFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int SICSDataFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pSICSData self = NULL; int iRet; - if(argc < 3){ - SCWrite(pCon,"ERROR: not enough arguments to SICSDataFactory",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: not enough arguments to SICSDataFactory", + eError); return 0; } strtolower(argv[1]); strtolower(argv[2]); - - if(strcmp(argv[1],"new") == 0){ + + if (strcmp(argv[1], "new") == 0) { self = createSICSData(); - if(self == NULL){ - SCWrite(pCon,"ERROR: not enough memory to create SICSData",eError); + if (self == NULL) { + SCWrite(pCon, "ERROR: not enough memory to create SICSData", eError); return 0; } - iRet = AddCommand(pSics,argv[2],SICSDataAction,KillSICSData, - self); - if(!iRet){ - SCWrite(pCon,"ERROR: new SICSData not created due to name collision", - eError); + iRet = AddCommand(pSics, argv[2], SICSDataAction, KillSICSData, self); + if (!iRet) { + SCWrite(pCon, + "ERROR: new SICSData not created due to name collision", + eError); KillSICSData(self); return 0; } SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"del") == 0){ - self = (pSICSData)FindCommandData(pSics,argv[2],"SICSData"); - if(self == NULL){ - SCWrite(pCon,"ERROR: SICSData to kill not found!",eError); + } else if (strcmp(argv[1], "del") == 0) { + self = (pSICSData) FindCommandData(pSics, argv[2], "SICSData"); + if (self == NULL) { + SCWrite(pCon, "ERROR: SICSData to kill not found!", eError); return 0; } - RemoveCommand(pSics,argv[2]); + RemoveCommand(pSics, argv[2]); SCSendOK(pCon); return 1; } - SCWrite(pCon,"ERROR: object command to SICSData not recognized",eError); + SCWrite(pCon, "ERROR: object command to SICSData not recognized", + eError); return 0; } - - - diff --git a/sicsdata.h b/sicsdata.h index 9d3bf8d3..a364faf5 100644 --- a/sicsdata.h +++ b/sicsdata.h @@ -15,36 +15,34 @@ #define FLOATTYPE 1 - typedef struct { - pObjectDescriptor pDes; - int *data; - char *dataType; - int dataUsed; - int currentDataSize; - }SICSData, *pSICSData; - +typedef struct { + pObjectDescriptor pDes; + int *data; + char *dataType; + int dataUsed; + int currentDataSize; +} SICSData, *pSICSData; + /*------------------------------------------------------------------*/ - int *getSICSDataPointer(pSICSData self, int start, int end); - - pSICSData createSICSData(void); +int *getSICSDataPointer(pSICSData self, int start, int end); - void assignSICSType(pSICSData self, int start, int end, int type); +pSICSData createSICSData(void); - int SICSDataFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]); +void assignSICSType(pSICSData self, int start, int end, int type); + +int SICSDataFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + +int SICSDataAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + +void clearSICSData(pSICSData self); +int getSICSDataInt(pSICSData self, int pos, int *value); +int getSICSDataFloat(pSICSData self, int pos, float *value); +int setSICSDataInt(pSICSData self, int pos, int value); +int setSICSDataFloat(pSICSData self, int pos, float value); - int SICSDataAction(SConnection *pCon, SicsInterp *pSics, - void *pData, - int argc, char *argv[]); - - void clearSICSData(pSICSData self); - int getSICSDataInt(pSICSData self, int pos, int *value); - int getSICSDataFloat(pSICSData self, int pos, float *value); - int setSICSDataInt(pSICSData self, int pos, int value); - int setSICSDataFloat(pSICSData self, int pos, float value); - #endif diff --git a/sicsexit.c b/sicsexit.c index 2903d41d..03e0ef25 100644 --- a/sicsexit.c +++ b/sicsexit.c @@ -48,46 +48,41 @@ /*---------------------------------------------------------------------- Below waits for 5 cycles in order to give everybody time to shut down properly. Then this one will die as well -*/ - static int WaitTask(void *pData) - { - static int iCount = 0; +*/ +static int WaitTask(void *pData) +{ + static int iCount = 0; - iCount++; - if(iCount > 4) - { - return 0; - } - return 1; + iCount++; + if (iCount > 4) { + return 0; } + return 1; +} /*-------------------------------------------------------------------------*/ - int SicsExit(SConnection *pCon, SicsInterp *pInterp, void *pData, - int argc, char *argv[]) - { - pTaskMan pTask = NULL; - long lID; +int SicsExit(SConnection * pCon, SicsInterp * pInterp, void *pData, + int argc, char *argv[]) +{ + pTaskMan pTask = NULL; + long lID; - assert(pCon); - assert(pInterp); - - pTask = GetTasker(); - assert(pTask); - - if(SCMatchRights(pCon,usMugger)) /* only Muggers are allowed to do it*/ - { - SetInterrupt(eEndServer); - lID = TaskRegister(pTask,WaitTask,NULL,NULL,NULL,1); - TaskWait(pTask,lID); - TaskStop(pTask); - return 1; - } - else - { - SCWrite(pCon,"You are not privileged to close the server",eError); - SCWrite(pCon," Get a Manager to do it",eError); - return 0; - } - } + assert(pCon); + assert(pInterp); + pTask = GetTasker(); + assert(pTask); + + if (SCMatchRights(pCon, usMugger)) { /* only Muggers are allowed to do it */ + SetInterrupt(eEndServer); + lID = TaskRegister(pTask, WaitTask, NULL, NULL, NULL, 1); + TaskWait(pTask, lID); + TaskStop(pTask); + return 1; + } else { + SCWrite(pCon, "You are not privileged to close the server", eError); + SCWrite(pCon, " Get a Manager to do it", eError); + return 0; + } +} diff --git a/sicsexit.h b/sicsexit.h index 1e53a288..d9f3ae78 100644 --- a/sicsexit.h +++ b/sicsexit.h @@ -10,7 +10,7 @@ #define SICSEXIT #include "conman.h" - int SicsExit(SConnection *pCon,SicsInterp *pInterp, void *pData, int argc, - char *argv[]); - +int SicsExit(SConnection * pCon, SicsInterp * pInterp, void *pData, + int argc, char *argv[]); + #endif diff --git a/sicshdbadapter.c b/sicshdbadapter.c index bc0f59c0..0ac612e7 100644 --- a/sicshdbadapter.c +++ b/sicshdbadapter.c @@ -29,785 +29,833 @@ #include "sicshdbadapter.h" #include "sicsdata.h" -#define PRIVNAM "priv" +#define PRIVNAM "priv" /*==================== support code ====================================*/ -static void AddPrivProperty(pHdb node, int priv){ - char pPriv[80]; - switch(priv){ - case usInternal: - strcpy(pPriv,"internal"); - break; - case usMugger: - strcpy(pPriv,"manager"); - break; - case usUser: - strcpy(pPriv,"user"); - break; - case usSpy: - strcpy(pPriv,"spy"); - break; - default: - assert(0); - break; - } - SetHdbProperty(node,PRIVNAM,pPriv); +static void AddPrivProperty(pHdb node, int priv) +{ + char pPriv[80]; + switch (priv) { + case usInternal: + strcpy(pPriv, "internal"); + break; + case usMugger: + strcpy(pPriv, "manager"); + break; + case usUser: + strcpy(pPriv, "user"); + break; + case usSpy: + strcpy(pPriv, "spy"); + break; + default: + assert(0); + break; + } + SetHdbProperty(node, PRIVNAM, pPriv); } + /*=================== motor code =======================================*/ -static int MoveCallback(int iEvent, void *eventData, void *userData){ - MotCallback *motData = (MotCallback *)eventData; - pHdb motor = (pHdb)userData; - pHdb pos = NULL; - - if(iEvent == MOTDRIVE && motData != NULL && motor != NULL){ - UpdateHipadabaPar(motor,MakeHdbFloat((double)motData->fVal) - ,NULL); - pos = GetHipadabaNode(motor,"position"); - if(pos != NULL){ - UpdateHipadabaPar(pos,MakeHdbFloat((double)motData->fVal) - ,NULL); - } +static int MoveCallback(int iEvent, void *eventData, void *userData) +{ + MotCallback *motData = (MotCallback *) eventData; + pHdb motor = (pHdb) userData; + pHdb pos = NULL; + + if (iEvent == MOTDRIVE && motData != NULL && motor != NULL) { + UpdateHipadabaPar(motor, MakeHdbFloat((double) motData->fVal) + , NULL); + pos = GetHipadabaNode(motor, "position"); + if (pos != NULL) { + UpdateHipadabaPar(pos, MakeHdbFloat((double) motData->fVal) + , NULL); } - return 1; + } + return 1; } + /*---------------------------------------------------------------------*/ -static int MotorValueCallback(int iEvent, void *eventData, void *userData){ - pHdb motor = (pHdb)userData; - pMotor pMot = (pMotor)eventData; - pHdb current = NULL; - float fVal; - - /* - * as setting some motor parameters might cause other motor - * parametes to change too, I opt for the cheap solution to check - * them all. - */ - if(iEvent == HDBVAL && motor != NULL && pMot != NULL){ - current = motor->child; - while(current != NULL){ - MotorGetPar(pMot,current->name,&fVal); - if(fVal != current->value.v.doubleValue) { - UpdateHipadabaPar(current,MakeHdbFloat((double)fVal),NULL); - } - current = current->next; - } - } - return 1; -} -/*---------------------------------------------------------------------*/ -static hdbCallbackReturn MotorParSetCallback(pHdb currentNode, void *userData, - pHdbMessage message){ - pMotor pMot = (pMotor)userData; - SConnection *pCon = NULL; - int status; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - pCon = mm->callData; - - assert(pMot != NULL && pCon != NULL); - status = MotorSetPar(pMot,pCon,currentNode->name, - (float)mm->v->v.doubleValue); - if(status == 1){ - return hdbContinue; - } else { - return hdbAbort; +static int MotorValueCallback(int iEvent, void *eventData, void *userData) +{ + pHdb motor = (pHdb) userData; + pMotor pMot = (pMotor) eventData; + pHdb current = NULL; + float fVal; + + /* + * as setting some motor parameters might cause other motor + * parametes to change too, I opt for the cheap solution to check + * them all. + */ + if (iEvent == HDBVAL && motor != NULL && pMot != NULL) { + current = motor->child; + while (current != NULL) { + MotorGetPar(pMot, current->name, &fVal); + if (fVal != current->value.v.doubleValue) { + UpdateHipadabaPar(current, MakeHdbFloat((double) fVal), NULL); + } + current = current->next; } + } + return 1; } + +/*---------------------------------------------------------------------*/ +static hdbCallbackReturn MotorParSetCallback(pHdb currentNode, + void *userData, + pHdbMessage message) +{ + pMotor pMot = (pMotor) userData; + SConnection *pCon = NULL; + int status; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + pCon = mm->callData; + + assert(pMot != NULL && pCon != NULL); + status = MotorSetPar(pMot, pCon, currentNode->name, + (float) mm->v->v.doubleValue); + if (status == 1) { + return hdbContinue; + } else { + return hdbAbort; + } +} + /*----------------------------------------------------------------------*/ -static hdbCallbackReturn MotorParGetCallback(pHdb currentNode, void *userData, - pHdbMessage message){ - pMotor pMot = (pMotor)userData; - float fVal; - int status; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbGetMessage(message)) == NULL){ - return hdbContinue; - } - - assert(pMot != NULL); - status = MotorGetPar(pMot,currentNode->name,&fVal); - currentNode->value.v.doubleValue = fVal; - if(status == 1){ - return hdbContinue; - } else { - return hdbAbort; - } +static hdbCallbackReturn MotorParGetCallback(pHdb currentNode, + void *userData, + pHdbMessage message) +{ + pMotor pMot = (pMotor) userData; + float fVal; + int status; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbGetMessage(message)) == NULL) { + return hdbContinue; + } + + assert(pMot != NULL); + status = MotorGetPar(pMot, currentNode->name, &fVal); + currentNode->value.v.doubleValue = fVal; + if (status == 1) { + return hdbContinue; + } else { + return hdbAbort; + } } + /*---------------------------------------------------------------------*/ -static pHdb MakeMotParNode(char *name, pMotor pMot){ - pHdb node = NULL; - pHdbCallback pCall = NULL; - char command[1024]; - - node = MakeHipadabaNode(name, HIPFLOAT, 1); - if(node != NULL) { - pCall = MakeHipadabaCallback(MotorParSetCallback,pMot,NULL); - if(pCall == NULL){ - return NULL; - } - AppendHipadabaCallback(node,pCall); - pCall = MakeHipadabaCallback(MotorParGetCallback,pMot,NULL); - if(pCall == NULL){ - return NULL; - } - AppendHipadabaCallback(node,pCall); - snprintf(command,1023,"%s %s ", pMot->name, name); - SetHdbProperty(node,"sicscommand", command); - } - return node; +static pHdb MakeMotParNode(char *name, pMotor pMot) +{ + pHdb node = NULL; + pHdbCallback pCall = NULL; + char command[1024]; + + node = MakeHipadabaNode(name, HIPFLOAT, 1); + if (node != NULL) { + pCall = MakeHipadabaCallback(MotorParSetCallback, pMot, NULL); + if (pCall == NULL) { + return NULL; + } + AppendHipadabaCallback(node, pCall); + pCall = MakeHipadabaCallback(MotorParGetCallback, pMot, NULL); + if (pCall == NULL) { + return NULL; + } + AppendHipadabaCallback(node, pCall); + snprintf(command, 1023, "%s %s ", pMot->name, name); + SetHdbProperty(node, "sicscommand", command); + } + return node; } + /*---------------------------------------------------------------------*/ -static int AddStdMotorPar(pHdb motorNode, pMotor pMot){ - int i; - pHdb parNode = NULL; - char *addPar[] = {"target", - "hardlowerlim", - "hardupperlim", - NULL}; - - i = 0; - while(addPar[i] != NULL){ - parNode = MakeMotParNode(addPar[i],pMot); - SetHdbProperty(parNode,PRIVNAM,"internal"); - if(parNode == NULL){ - return 0; - } - AddHipadabaChild(motorNode,parNode, NULL); - i++; +static int AddStdMotorPar(pHdb motorNode, pMotor pMot) +{ + int i; + pHdb parNode = NULL; + char *addPar[] = { "target", + "hardlowerlim", + "hardupperlim", + NULL + }; + + i = 0; + while (addPar[i] != NULL) { + parNode = MakeMotParNode(addPar[i], pMot); + SetHdbProperty(parNode, PRIVNAM, "internal"); + if (parNode == NULL) { + return 0; } - - /* - * Add the parameters in the obpar array - */ - for(i = 0; i < MOTOBPARLENGTH; i++){ - parNode = MakeMotParNode(pMot->ParArray[i].name,pMot); - if(parNode == NULL){ - return 0; - } - AddHipadabaChild(motorNode,parNode, NULL); - AddPrivProperty(parNode,pMot->ParArray[i].iCode); + AddHipadabaChild(motorNode, parNode, NULL); + i++; + } + + /* + * Add the parameters in the obpar array + */ + for (i = 0; i < MOTOBPARLENGTH; i++) { + parNode = MakeMotParNode(pMot->ParArray[i].name, pMot); + if (parNode == NULL) { + return 0; } - return 1; + AddHipadabaChild(motorNode, parNode, NULL); + AddPrivProperty(parNode, pMot->ParArray[i].iCode); + } + return 1; } + /*--------------------------------------------------------------------------*/ -static char *getDriverParList(MotorDriver *pDriv){ - SConnection *pCon = NULL; - pDynString list = NULL; - char *listData = NULL; - - if(pDriv->ListDriverPar != NULL){ - pCon = SCCreateDummyConnection(pServ->pSics); - if(pCon == NULL){ - return NULL; - } - SCStartBuffering(pCon); - pDriv->ListDriverPar(pDriv,"test.", pCon); - list = SCEndBuffering(pCon); - if(list != NULL){ - listData = strdup(GetCharArray(list)); - SCDeleteConnection(pCon); - } else { - listData = NULL; - } - return listData; +static char *getDriverParList(MotorDriver * pDriv) +{ + SConnection *pCon = NULL; + pDynString list = NULL; + char *listData = NULL; + + if (pDriv->ListDriverPar != NULL) { + pCon = SCCreateDummyConnection(pServ->pSics); + if (pCon == NULL) { + return NULL; } - return NULL; + SCStartBuffering(pCon); + pDriv->ListDriverPar(pDriv, "test.", pCon); + list = SCEndBuffering(pCon); + if (list != NULL) { + listData = strdup(GetCharArray(list)); + SCDeleteConnection(pCon); + } else { + listData = NULL; + } + return listData; + } + return NULL; } + /*--------------------------------------------------------------------------*/ extern char *trim(char *str); /*--------------------------------------------------------------------------*/ -static char *extractName(char *line){ - char *name = NULL, *pEnd = NULL; - - name = strchr(line,'.'); - assert(name != NULL); - while(*name == '.'){ - name++; - } - pEnd = strchr(name,'='); - assert(pEnd != NULL); - *pEnd = '\0'; - return trim(name); -} -/*------------------------------------------------------------------------*/ -static int CreateDriverParameters(pMotor pM, pHdb parent){ - char *listPtr = NULL, line[80], *pPtr, *name; - pHdb node = NULL; - - listPtr = getDriverParList(pM->pDriver); - if(listPtr == NULL){ - /* - * no driver parameters - */ - return 1; - } - pPtr = listPtr; - while((pPtr = stptok(pPtr,line,79,"\n")) != NULL){ - name = extractName(line); - node = MakeMotParNode(name,pM); - SetHdbProperty(node,PRIVNAM,"manager"); - if(node != NULL){ - AddHipadabaChild(parent,node,NULL); - } - } - free(listPtr); - return 1; -} -/*----------------------------------------------------------------------*/ -static pHdb CreateMotorAdapter(char *name, pMotor pMot){ - pHdb result = NULL; - commandContext comCom; - float access; - - assert(pMot != NULL); - - result = MakeSICSHdbDriv(name,usUser,pMot,HIPFLOAT); - if(result == NULL){ - return NULL; - } - MotorGetPar(pMot,"accesscode",&access); - AddPrivProperty(result,(int)access); - SetHdbProperty(result,"type","drivable"); - SetHdbProperty(result,"sicsdev",pMot->name); - /* - * We want to be notified when this motor drives around. Or - * its parameters change. - */ - strncpy(comCom.deviceID,name,255); - comCom.transID = -77; - RegisterCallback(pMot->pCall,MOTDRIVE, MoveCallback, - result,NULL); - RegisterCallback(pMot->pCall,HDBVAL, MotorValueCallback, - result,NULL); - - if(!AddStdMotorPar(result,pMot)){ - DeleteHipadabaNode(result,NULL); - return NULL; - } +static char *extractName(char *line) +{ + char *name = NULL, *pEnd = NULL; - if(!CreateDriverParameters(pMot,result)){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - result->protected = 1; - - return result; + name = strchr(line, '.'); + assert(name != NULL); + while (*name == '.') { + name++; + } + pEnd = strchr(name, '='); + assert(pEnd != NULL); + *pEnd = '\0'; + return trim(name); } + +/*------------------------------------------------------------------------*/ +static int CreateDriverParameters(pMotor pM, pHdb parent) +{ + char *listPtr = NULL, line[80], *pPtr, *name; + pHdb node = NULL; + + listPtr = getDriverParList(pM->pDriver); + if (listPtr == NULL) { + /* + * no driver parameters + */ + return 1; + } + pPtr = listPtr; + while ((pPtr = stptok(pPtr, line, 79, "\n")) != NULL) { + name = extractName(line); + node = MakeMotParNode(name, pM); + SetHdbProperty(node, PRIVNAM, "manager"); + if (node != NULL) { + AddHipadabaChild(parent, node, NULL); + } + } + free(listPtr); + return 1; +} + +/*----------------------------------------------------------------------*/ +static pHdb CreateMotorAdapter(char *name, pMotor pMot) +{ + pHdb result = NULL; + commandContext comCom; + float access; + + assert(pMot != NULL); + + result = MakeSICSHdbDriv(name, usUser, pMot, HIPFLOAT); + if (result == NULL) { + return NULL; + } + MotorGetPar(pMot, "accesscode", &access); + AddPrivProperty(result, (int) access); + SetHdbProperty(result, "type", "drivable"); + SetHdbProperty(result, "sicsdev", pMot->name); + /* + * We want to be notified when this motor drives around. Or + * its parameters change. + */ + strncpy(comCom.deviceID, name, 255); + comCom.transID = -77; + RegisterCallback(pMot->pCall, MOTDRIVE, MoveCallback, result, NULL); + RegisterCallback(pMot->pCall, HDBVAL, MotorValueCallback, result, NULL); + + if (!AddStdMotorPar(result, pMot)) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + + if (!CreateDriverParameters(pMot, result)) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + result->protected = 1; + + return result; +} + /*============== histogram memory ======================================*/ -static long totalSum(int *data, int length){ - long result = 0l; - int i; - - if(data == NULL){ - return 0; - } - for(i = 0; i < length; i++){ - result += data[i]; - } - return result; +static long totalSum(int *data, int length) +{ + long result = 0l; + int i; + + if (data == NULL) { + return 0; + } + for (i = 0; i < length; i++) { + result += data[i]; + } + return result; } + /*----------------------------------------------------------------------*/ typedef struct { - pHistMem pHM; - long oldSum; + pHistMem pHM; + long oldSum; } HMAdapter, *pHMAdapter; /*-------------------------------------------------------------------------*/ -static hdbCallbackReturn HMDataGetCallback(pHdb currentNode, void *userData, - pHdbMessage message){ - pHMAdapter pHMA = (pHMAdapter)userData; - SConnection *pCon = NULL; - long sum1; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbGetMessage(message)) == NULL){ - return hdbContinue; - } - pCon = mm->callData; - assert(pHMA != NULL && pHMA->pHM != NULL); - if(pCon == NULL){ - return hdbAbort; - } - currentNode->value.arrayLength = GetHistLength(pHMA->pHM); - currentNode->value.v.intArray = (int *)GetHistogramPointer(pHMA->pHM,pCon); - sum1 = totalSum(currentNode->value.v.intArray, currentNode->value.arrayLength); - if(sum1 != pHMA->oldSum){ - UpdateHipadabaPar(currentNode,currentNode->value,NULL); - pHMA->oldSum = sum1; - } - return hdbContinue; +static hdbCallbackReturn HMDataGetCallback(pHdb currentNode, + void *userData, + pHdbMessage message) +{ + pHMAdapter pHMA = (pHMAdapter) userData; + SConnection *pCon = NULL; + long sum1; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbGetMessage(message)) == NULL) { + return hdbContinue; + } + pCon = mm->callData; + assert(pHMA != NULL && pHMA->pHM != NULL); + if (pCon == NULL) { + return hdbAbort; + } + currentNode->value.arrayLength = GetHistLength(pHMA->pHM); + currentNode->value.v.intArray = + (int *) GetHistogramPointer(pHMA->pHM, pCon); + sum1 = + totalSum(currentNode->value.v.intArray, + currentNode->value.arrayLength); + if (sum1 != pHMA->oldSum) { + UpdateHipadabaPar(currentNode, currentNode->value, NULL); + pHMA->oldSum = sum1; + } + return hdbContinue; } + /*----------------------------------------------------------------------*/ -static pHdb MakeHMDataNode(pHistMem pHM, char *name){ - pHdb node = NULL; - pHdbCallback pCall = NULL; - pHMAdapter pHMA = NULL; - - node = MakeHipadabaNode(name,HIPINTVARAR,2); - pHMA = malloc(sizeof(HMAdapter)); - if(node == NULL || pHMA == NULL){ - return NULL; - } - pHMA->pHM = pHM; - pHMA->oldSum = 0; - node->value.doNotFree = 1; - pCall = MakeHipadabaCallback(HMDataGetCallback,pHMA,free); - if(pCall == NULL){ - return NULL; - } - AppendHipadabaCallback(node,pCall); - AppendHipadabaCallback(node,MakeReadOnlyCallback()); - - return node; +static pHdb MakeHMDataNode(pHistMem pHM, char *name) +{ + pHdb node = NULL; + pHdbCallback pCall = NULL; + pHMAdapter pHMA = NULL; + + node = MakeHipadabaNode(name, HIPINTVARAR, 2); + pHMA = malloc(sizeof(HMAdapter)); + if (node == NULL || pHMA == NULL) { + return NULL; + } + pHMA->pHM = pHM; + pHMA->oldSum = 0; + node->value.doNotFree = 1; + pCall = MakeHipadabaCallback(HMDataGetCallback, pHMA, free); + if (pCall == NULL) { + return NULL; + } + AppendHipadabaCallback(node, pCall); + AppendHipadabaCallback(node, MakeReadOnlyCallback()); + + return node; } + /*================ SICS Variable ======================================*/ -static hdbCallbackReturn SicsVarSetCallback(pHdb currentNode, void *userData, - pHdbMessage message){ - pSicsVariable pVar = (pSicsVariable)userData; - SConnection *pCon = NULL; - int userRights = usMugger; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - pCon = mm->callData; - - assert(pVar != NULL); - - if(pCon != NULL){ - userRights = SCGetRights(pCon); - } - switch(currentNode->value.dataType){ - case HIPINT: - VarSetInt(pVar, mm->v->v.intValue, userRights); - break; - case HIPFLOAT: - VarSetFloat(pVar, (float)mm->v->v.doubleValue, userRights); - break; - case HIPTEXT: - VarSetText(pVar, mm->v->v.text, userRights); - break; - } - return hdbContinue; +static hdbCallbackReturn SicsVarSetCallback(pHdb currentNode, + void *userData, + pHdbMessage message) +{ + pSicsVariable pVar = (pSicsVariable) userData; + SConnection *pCon = NULL; + int userRights = usMugger; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + pCon = mm->callData; + + assert(pVar != NULL); + + if (pCon != NULL) { + userRights = SCGetRights(pCon); + } + switch (currentNode->value.dataType) { + case HIPINT: + VarSetInt(pVar, mm->v->v.intValue, userRights); + break; + case HIPFLOAT: + VarSetFloat(pVar, (float) mm->v->v.doubleValue, userRights); + break; + case HIPTEXT: + VarSetText(pVar, mm->v->v.text, userRights); + break; + } + return hdbContinue; } + /*----------------------------------------------------------------------*/ -static int ValueCallback(int iEvent, void *eventData, void *userData){ - pSicsVariable pVar = (pSicsVariable)eventData; - pHdb node = (pHdb)userData; - hdbValue v; - - if(iEvent == VALUECHANGE && pVar != NULL && node != NULL){ - switch(pVar->eType){ - case veInt: - v = MakeHdbInt(pVar->iVal); - break; - case veFloat: - v = MakeHdbFloat((double)pVar->fVal); - break; - case veText: - v = MakeHdbText(pVar->text); - break; - } - UpdateHipadabaPar(node,v,NULL); - } - - return 1; +static int ValueCallback(int iEvent, void *eventData, void *userData) +{ + pSicsVariable pVar = (pSicsVariable) eventData; + pHdb node = (pHdb) userData; + hdbValue v; + + if (iEvent == VALUECHANGE && pVar != NULL && node != NULL) { + switch (pVar->eType) { + case veInt: + v = MakeHdbInt(pVar->iVal); + break; + case veFloat: + v = MakeHdbFloat((double) pVar->fVal); + break; + case veText: + v = MakeHdbText(pVar->text); + break; + } + UpdateHipadabaPar(node, v, NULL); + } + + return 1; } + /*----------------------------------------------------------------------*/ -static pHdb MakeSicsVarNode(pSicsVariable pVar, char *name){ - pHdb node = NULL; - pHdbCallback pCall = NULL; - commandContext comCom; - int type; - char command[1024]; - - switch(pVar->eType){ - case veInt: - type = HIPINT; - break; - case veFloat: - type = HIPFLOAT; - break; - case veText: - type = HIPTEXT; - break; - } - node = MakeHipadabaNode(name,type,1); - if(node == NULL){ - return NULL; - } - if(pVar->iLock == 1) { - AddPrivProperty(node,usInternal); - } else { - AddPrivProperty(node,pVar->iAccessCode); - } - pCall = MakeHipadabaCallback(SicsVarSetCallback,pVar,NULL); - if(pCall == NULL){ - return NULL; - } - AppendHipadabaCallback(node,pCall); - RegisterCallback(pVar->pCall,VALUECHANGE, ValueCallback, - node,NULL); - snprintf(command,1023,"%s ", pVar->name); - SetHdbProperty(node,"sicscommand",command); - - node->protected = 1; - return node; +static pHdb MakeSicsVarNode(pSicsVariable pVar, char *name) +{ + pHdb node = NULL; + pHdbCallback pCall = NULL; + commandContext comCom; + int type; + char command[1024]; + + switch (pVar->eType) { + case veInt: + type = HIPINT; + break; + case veFloat: + type = HIPFLOAT; + break; + case veText: + type = HIPTEXT; + break; + } + node = MakeHipadabaNode(name, type, 1); + if (node == NULL) { + return NULL; + } + if (pVar->iLock == 1) { + AddPrivProperty(node, usInternal); + } else { + AddPrivProperty(node, pVar->iAccessCode); + } + pCall = MakeHipadabaCallback(SicsVarSetCallback, pVar, NULL); + if (pCall == NULL) { + return NULL; + } + AppendHipadabaCallback(node, pCall); + RegisterCallback(pVar->pCall, VALUECHANGE, ValueCallback, node, NULL); + snprintf(command, 1023, "%s ", pVar->name); + SetHdbProperty(node, "sicscommand", command); + + node->protected = 1; + return node; } + /*================ counter =============================================*/ typedef struct { - pHdb node; - int monitor; /* -1 == time */ - pCounter counter; + pHdb node; + int monitor; /* -1 == time */ + pCounter counter; } CountEntry; static int countList = -10; /*---------------------------------------------------------------------*/ -static void updateCountList(){ - int status; - hdbValue v; - CountEntry hugo; - long monitor; - float time; - SConnection *pDummy = NULL; - - if(countList < 0){ - return; +static void updateCountList() +{ + int status; + hdbValue v; + CountEntry hugo; + long monitor; + float time; + SConnection *pDummy = NULL; + + if (countList < 0) { + return; + } + pDummy = SCCreateDummyConnection(pServ->pSics); + if (pDummy == NULL) { + return; + } + + status = LLDnodePtr2First(countList); + while (status != 0) { + LLDnodeDataTo(countList, &hugo); + if (hugo.monitor < 0) { + time = GetCountTime(hugo.counter, pDummy); + v = MakeHdbFloat((double) time); + UpdateHipadabaPar(hugo.node, v, NULL); + } else { + monitor = GetMonitor(hugo.counter, hugo.monitor, pDummy); + v = MakeHdbInt((int) monitor); + UpdateHipadabaPar(hugo.node, v, NULL); } - pDummy = SCCreateDummyConnection(pServ->pSics); - if(pDummy == NULL){ - return; - } - - status = LLDnodePtr2First(countList); - while(status != 0){ - LLDnodeDataTo(countList,&hugo); - if(hugo.monitor < 0){ - time = GetCountTime(hugo.counter,pDummy); - v = MakeHdbFloat((double)time); - UpdateHipadabaPar(hugo.node,v, NULL); - } else { - monitor = GetMonitor(hugo.counter, hugo.monitor, pDummy); - v = MakeHdbInt((int)monitor); - UpdateHipadabaPar(hugo.node,v, NULL); - } - status = LLDnodePtr2Next(countList); - } - SCDeleteConnection(pDummy); + status = LLDnodePtr2Next(countList); + } + SCDeleteConnection(pDummy); } + /*---------------------------------------------------------------------------*/ -static int CounterCallback(int iEvent, void *eventData, void *userData){ - if(iEvent == MONITOR || iEvent == COUNTEND){ - updateCountList(); - } - return 1; +static int CounterCallback(int iEvent, void *eventData, void *userData) +{ + if (iEvent == MONITOR || iEvent == COUNTEND) { + updateCountList(); + } + return 1; }/*=================== SICSData ========================================*/ -static void copyIntSicsData(pHdb node, pSICSData data){ - if(node->value.arrayLength != data->dataUsed){ - if(node->value.v.intArray != NULL){ - free(node->value.v.intArray); - } - node->value.arrayLength = data->dataUsed; - node->value.v.intArray = malloc(data->dataUsed*sizeof(int)); - if(node->value.v.intArray == NULL){ - node->value.arrayLength = 0; - return; - } - } - memcpy(node->value.v.intArray, data->data, - data->dataUsed*sizeof(int)); +static void copyIntSicsData(pHdb node, pSICSData data) +{ + if (node->value.arrayLength != data->dataUsed) { + if (node->value.v.intArray != NULL) { + free(node->value.v.intArray); + } + node->value.arrayLength = data->dataUsed; + node->value.v.intArray = malloc(data->dataUsed * sizeof(int)); + if (node->value.v.intArray == NULL) { + node->value.arrayLength = 0; + return; + } + } + memcpy(node->value.v.intArray, data->data, data->dataUsed * sizeof(int)); } + /*-----------------------------------------------------------------------*/ -static void copyFloatSicsData(pHdb node, pSICSData data){ - int i; - float val; - - if(node->value.arrayLength != data->dataUsed){ - if(node->value.v.floatArray != NULL){ - free(node->value.v.floatArray); - } - node->value.arrayLength = data->dataUsed; - node->value.v.floatArray = malloc(data->dataUsed*sizeof(double)); - if(node->value.v.floatArray == NULL){ - node->value.arrayLength = 0; - return; - } - } - for(i = 0; i < data->dataUsed; i++){ - getSICSDataFloat(data,i,&val); - node->value.v.floatArray[i] = val; - } +static void copyFloatSicsData(pHdb node, pSICSData data) +{ + int i; + float val; + + if (node->value.arrayLength != data->dataUsed) { + if (node->value.v.floatArray != NULL) { + free(node->value.v.floatArray); + } + node->value.arrayLength = data->dataUsed; + node->value.v.floatArray = malloc(data->dataUsed * sizeof(double)); + if (node->value.v.floatArray == NULL) { + node->value.arrayLength = 0; + return; + } + } + for (i = 0; i < data->dataUsed; i++) { + getSICSDataFloat(data, i, &val); + node->value.v.floatArray[i] = val; + } } + /*----------------------------------------------------------------------*/ static hdbCallbackReturn SICSDataCallback(pHdb node, void *userData, - pHdbMessage message){ - pSICSData self = (pSICSData)userData; - pHdbDataMessage mm = NULL; - int i, status; - char script[256], error[1024]; - - assert(self != NULL); - - /* - * I have to make copies because the floats in SICSData - * are floats but doubles in Hipdaba. Siiiigggghhhh! - * But it is cleaner in some way anyway. - */ - if((mm = GetHdbGetMessage(message)) != NULL){ - memset(script,0,256); - if(GetHdbProperty(node,"readscript", script,256) == 1){ - status = Tcl_Eval(InterpGetTcl(pServ->pSics),script); - if(status != TCL_OK){ - snprintf(error,1023,"ERROR: Tcl returned error: %s", - Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); - if(mm->callData != NULL){ - SCWrite((SConnection *)mm->callData, error, eError); - return hdbAbort; - } - } - } - if(node->value.dataType == HIPINTVARAR){ - copyIntSicsData(node, self); - } else if(node->value.dataType == HIPFLOATVARAR){ - copyFloatSicsData(node, self); - } - return hdbContinue; - } - - if((mm = GetHdbSetMessage(message)) != NULL){ - if(node->value.dataType == HIPINTVARAR){ - for(i = 0; i < mm->v->arrayLength; i++){ - setSICSDataInt(self,i,mm->v->v.intArray[i]); - } - } else if(node->value.dataType == HIPFLOATVARAR){ - for(i = 0; i < mm->v->arrayLength; i++){ - setSICSDataFloat(self,i,(float)mm->v->v.floatArray[i]); - } - } - memset(script,0,256); - if(GetHdbProperty(node,"writescript", script,256) == 1){ - status = Tcl_Eval(InterpGetTcl(pServ->pSics),script); - if(status != TCL_OK){ - snprintf(error,1023,"ERROR: Tcl returned error: %s", - Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); - if(mm->callData != NULL){ - SCWrite((SConnection *)mm->callData, error, eError); - return hdbAbort; - } - } - } - return hdbContinue; - } - - return hdbContinue; -} -/*============== interpreter function ==================================*/ -int SICSHdbAdapter(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb path = NULL; - pHdb node = NULL; - pMotor pMot = NULL; - pHistMem pHM = NULL; - CommandList *pCom = NULL; - pIDrivable pDriv = NULL; - pSicsVariable pVar = NULL; - char buffer[512]; - pCounter pCount = NULL; - CountEntry hugo; - pSICSData data = NULL; - int type; - pHdbCallback pCall = NULL; - - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - if(argc < 4) { - SCWrite(pCon,"ERROR: Insufficient number of arguments",eError); - return 0; - } - - path = FindHdbNode(NULL,argv[1],pCon); - if(path == NULL){ - SCWrite(pCon,"ERROR: path to attach object too not found",eError); - return 0; - } + pHdbMessage message) +{ + pSICSData self = (pSICSData) userData; + pHdbDataMessage mm = NULL; + int i, status; + char script[256], error[1024]; - /* - * look for motors - */ - pMot = (pMotor)FindCommandData(pSics,argv[2],"Motor"); - if(pMot != NULL){ - node = CreateMotorAdapter(argv[3],pMot); - if(node == NULL){ - SCWrite(pCon,"ERROR: out of memory creating motor node",eError); - return 0; + assert(self != NULL); + + /* + * I have to make copies because the floats in SICSData + * are floats but doubles in Hipdaba. Siiiigggghhhh! + * But it is cleaner in some way anyway. + */ + if ((mm = GetHdbGetMessage(message)) != NULL) { + memset(script, 0, 256); + if (GetHdbProperty(node, "readscript", script, 256) == 1) { + status = Tcl_Eval(InterpGetTcl(pServ->pSics), script); + if (status != TCL_OK) { + snprintf(error, 1023, "ERROR: Tcl returned error: %s", + Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); + if (mm->callData != NULL) { + SCWrite((SConnection *) mm->callData, error, eError); + return hdbAbort; } - AddHipadabaChild(path,node,pCon); - SCSendOK(pCon); - return 1; + } } - /* - * look for drivables - */ - pDriv = FindDrivable(pSics,argv[2]); - pCom = FindCommand(pSics,argv[2]); - if(pDriv != NULL && pCom != NULL && pCom->pData != NULL){ - node = MakeSICSHdbDriv(argv[3],usUser,pCom->pData,HIPFLOAT); - if(node == NULL){ - SCWrite(pCon,"ERROR: out of memory creating drivable node",eError); - return 0; + if (node->value.dataType == HIPINTVARAR) { + copyIntSicsData(node, self); + } else if (node->value.dataType == HIPFLOATVARAR) { + copyFloatSicsData(node, self); + } + return hdbContinue; + } + + if ((mm = GetHdbSetMessage(message)) != NULL) { + if (node->value.dataType == HIPINTVARAR) { + for (i = 0; i < mm->v->arrayLength; i++) { + setSICSDataInt(self, i, mm->v->v.intArray[i]); + } + } else if (node->value.dataType == HIPFLOATVARAR) { + for (i = 0; i < mm->v->arrayLength; i++) { + setSICSDataFloat(self, i, (float) mm->v->v.floatArray[i]); + } + } + memset(script, 0, 256); + if (GetHdbProperty(node, "writescript", script, 256) == 1) { + status = Tcl_Eval(InterpGetTcl(pServ->pSics), script); + if (status != TCL_OK) { + snprintf(error, 1023, "ERROR: Tcl returned error: %s", + Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); + if (mm->callData != NULL) { + SCWrite((SConnection *) mm->callData, error, eError); + return hdbAbort; } - SetHdbProperty(node,PRIVNAM,"user"); - SetHdbProperty(node,"type","drivable"); - SetHdbProperty(node,"sicsdev",argv[2]); - AddHipadabaChild(path,node,pCon); - SCSendOK(pCon); - return 1; + } } + return hdbContinue; + } + + return hdbContinue; +} + +/*============== interpreter function ==================================*/ +int SICSHdbAdapter(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHdb path = NULL; + pHdb node = NULL; + pMotor pMot = NULL; + pHistMem pHM = NULL; + CommandList *pCom = NULL; + pIDrivable pDriv = NULL; + pSicsVariable pVar = NULL; + char buffer[512]; + pCounter pCount = NULL; + CountEntry hugo; + pSICSData data = NULL; + int type; + pHdbCallback pCall = NULL; + + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + if (argc < 4) { + SCWrite(pCon, "ERROR: Insufficient number of arguments", eError); + return 0; + } + + path = FindHdbNode(NULL, argv[1], pCon); + if (path == NULL) { + SCWrite(pCon, "ERROR: path to attach object too not found", eError); + return 0; + } + + /* + * look for motors + */ + pMot = (pMotor) FindCommandData(pSics, argv[2], "Motor"); + if (pMot != NULL) { + node = CreateMotorAdapter(argv[3], pMot); + if (node == NULL) { + SCWrite(pCon, "ERROR: out of memory creating motor node", eError); + return 0; + } + AddHipadabaChild(path, node, pCon); + SCSendOK(pCon); + return 1; + } + /* + * look for drivables + */ + pDriv = FindDrivable(pSics, argv[2]); + pCom = FindCommand(pSics, argv[2]); + if (pDriv != NULL && pCom != NULL && pCom->pData != NULL) { + node = MakeSICSHdbDriv(argv[3], usUser, pCom->pData, HIPFLOAT); + if (node == NULL) { + SCWrite(pCon, "ERROR: out of memory creating drivable node", eError); + return 0; + } + SetHdbProperty(node, PRIVNAM, "user"); + SetHdbProperty(node, "type", "drivable"); + SetHdbProperty(node, "sicsdev", argv[2]); + AddHipadabaChild(path, node, pCon); + SCSendOK(pCon); + return 1; + } /** * look for SICS Variables */ - pVar = (pSicsVariable)FindCommandData(pSics,argv[2],"SicsVariable"); - if(pVar != NULL){ - node = MakeSicsVarNode(pVar,argv[3]); - if(node == NULL){ - SCWrite(pCon,"ERROR: out of memory creating SICS variable node", - eError); - return 0; - } - AddHipadabaChild(path,node,pCon); - SCSendOK(pCon); - return 1; - } - - /* - * look for histogram memories - */ - pHM = (pHistMem)FindCommandData(pSics,argv[2],"HistMem"); - if(pHM != NULL){ - node = MakeHMDataNode(pHM,argv[3]); - if(node == NULL){ - SCWrite(pCon,"ERROR: out of memory creating HM node",eError); - return 0; - } - AddHipadabaChild(path,node,pCon); - SCSendOK(pCon); - return 1; + pVar = (pSicsVariable) FindCommandData(pSics, argv[2], "SicsVariable"); + if (pVar != NULL) { + node = MakeSicsVarNode(pVar, argv[3]); + if (node == NULL) { + SCWrite(pCon, "ERROR: out of memory creating SICS variable node", + eError); + return 0; } + AddHipadabaChild(path, node, pCon); + SCSendOK(pCon); + return 1; + } + + /* + * look for histogram memories + */ + pHM = (pHistMem) FindCommandData(pSics, argv[2], "HistMem"); + if (pHM != NULL) { + node = MakeHMDataNode(pHM, argv[3]); + if (node == NULL) { + SCWrite(pCon, "ERROR: out of memory creating HM node", eError); + return 0; + } + AddHipadabaChild(path, node, pCon); + SCSendOK(pCon); + return 1; + } /** * look for counters */ - pCount = (pCounter)FindCommandData(pSics,argv[2],"SingleCounter"); - if(pCount != NULL){ - hugo.monitor = atoi(argv[3]); - hugo.counter = pCount; - hugo.node = path; - if(countList < 0){ - countList = LLDcreate(sizeof(CountEntry)); - RegisterCallback(pCount->pCall, - COUNTSTART, CounterCallback, - NULL, NULL); - RegisterCallback(pCount->pCall, - COUNTEND, CounterCallback, - NULL, NULL); - RegisterCallback(pCount->pCall, - MONITOR, CounterCallback, - NULL, NULL); - } - LLDnodeAppendFrom(countList,&hugo); - SCSendOK(pCon); - return 1; - } + pCount = (pCounter) FindCommandData(pSics, argv[2], "SingleCounter"); + if (pCount != NULL) { + hugo.monitor = atoi(argv[3]); + hugo.counter = pCount; + hugo.node = path; + if (countList < 0) { + countList = LLDcreate(sizeof(CountEntry)); + RegisterCallback(pCount->pCall, + COUNTSTART, CounterCallback, NULL, NULL); + RegisterCallback(pCount->pCall, + COUNTEND, CounterCallback, NULL, NULL); + RegisterCallback(pCount->pCall, + MONITOR, CounterCallback, NULL, NULL); + } + LLDnodeAppendFrom(countList, &hugo); + SCSendOK(pCon); + return 1; + } /** * look for SICSData */ - data = (pSICSData)FindCommandData(pSics,argv[2],"SICSData"); - if(data != NULL){ - if(argc < 5){ - SCWrite(pCon,"ERROR: need type and name to create SICSData adapter", - eError); - return 0; - } - type = convertHdbType(argv[3]); - if(type != HIPINTVARAR && type != HIPFLOATVARAR ){ - SCWrite(pCon, - "ERROR: need intvarar or floatvarar type for SICSData adapter", - eError); - return 0; - } - node = MakeHipadabaNode(argv[4],type,0); - if(node == NULL){ - SCWrite(pCon,"ERROR: out of memory in SICSHdbAdapter", eError); - return 0; - } - pCall = MakeHipadabaCallback(SICSDataCallback,data,NULL); - if(pCall == NULL){ - SCWrite(pCon,"ERROR: out of memory in SICSHdbAdapter", eError); - return 0; - } - AppendHipadabaCallback(node,pCall); - AddHipadabaChild(path,node,pCon); - SCSendOK(pCon); - return 1; - } - - snprintf(buffer,511, - "ERROR: attaching this type of object: %s at %s not implemented", - argv[2], argv[1]); - SCWrite(pCon,buffer,eError); - return 0; -} -/*====================== SubSample =========================================*/ -int HdbSubSample(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHistMem pHM = NULL; - pHdb node = NULL; - int bank = 0, length = -1, status; - HistInt *data = NULL; - char *pPtr = NULL; - hdbValue v; - - if(argc < 4){ - SCWrite(pCon,"ERROR: insufficient number of arguments to HdbSubSample", - eError); - return 0; - } - - pPtr = strchr(argv[1],':'); - if(pPtr != NULL){ - *pPtr = '\0'; - pPtr++; - sscanf(pPtr,"%d",&bank); - } - pHM = (pHistMem)FindCommandData(pSics,argv[1],"HistMem"); - node = FindHdbNode(NULL,argv[2], pCon); - if(pHM == NULL || node == NULL){ - SCWrite(pCon,"ERROR: either histogram memory or node not found!", - eError); - return 0; - } + data = (pSICSData) FindCommandData(pSics, argv[2], "SICSData"); + if (data != NULL) { + if (argc < 5) { + SCWrite(pCon, "ERROR: need type and name to create SICSData adapter", + eError); + return 0; + } + type = convertHdbType(argv[3]); + if (type != HIPINTVARAR && type != HIPFLOATVARAR) { + SCWrite(pCon, + "ERROR: need intvarar or floatvarar type for SICSData adapter", + eError); + return 0; + } + node = MakeHipadabaNode(argv[4], type, 0); + if (node == NULL) { + SCWrite(pCon, "ERROR: out of memory in SICSHdbAdapter", eError); + return 0; + } + pCall = MakeHipadabaCallback(SICSDataCallback, data, NULL); + if (pCall == NULL) { + SCWrite(pCon, "ERROR: out of memory in SICSHdbAdapter", eError); + return 0; + } + AppendHipadabaCallback(node, pCall); + AddHipadabaChild(path, node, pCon); + SCSendOK(pCon); + return 1; + } - if(pHM->pDriv->SubSample == NULL){ - SCWrite(pCon,"ERROR: hm does not support subsampling", eError); - return 0; - } - data = pHM->pDriv->SubSample(pHM->pDriv, pCon, bank, argv[3]); - if(data == NULL){ - SCWrite(pCon,"ERROR: sub sampling failed", eError); - return 0; - } - - v.dataType = HIPINTVARAR; - v.arrayLength = data[0]; - v.v.intArray = data+1; - - UpdateHipadabaPar(node,v,pCon); - free(data); - SCSendOK(pCon); - return 1; + snprintf(buffer, 511, + "ERROR: attaching this type of object: %s at %s not implemented", + argv[2], argv[1]); + SCWrite(pCon, buffer, eError); + return 0; +} + +/*====================== SubSample =========================================*/ +int HdbSubSample(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHistMem pHM = NULL; + pHdb node = NULL; + int bank = 0, length = -1, status; + HistInt *data = NULL; + char *pPtr = NULL; + hdbValue v; + + if (argc < 4) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to HdbSubSample", + eError); + return 0; + } + + pPtr = strchr(argv[1], ':'); + if (pPtr != NULL) { + *pPtr = '\0'; + pPtr++; + sscanf(pPtr, "%d", &bank); + } + pHM = (pHistMem) FindCommandData(pSics, argv[1], "HistMem"); + node = FindHdbNode(NULL, argv[2], pCon); + if (pHM == NULL || node == NULL) { + SCWrite(pCon, "ERROR: either histogram memory or node not found!", + eError); + return 0; + } + + if (pHM->pDriv->SubSample == NULL) { + SCWrite(pCon, "ERROR: hm does not support subsampling", eError); + return 0; + } + data = pHM->pDriv->SubSample(pHM->pDriv, pCon, bank, argv[3]); + if (data == NULL) { + SCWrite(pCon, "ERROR: sub sampling failed", eError); + return 0; + } + + v.dataType = HIPINTVARAR; + v.arrayLength = data[0]; + v.v.intArray = data + 1; + + UpdateHipadabaPar(node, v, pCon); + free(data); + SCSendOK(pCon); + return 1; } diff --git a/sicshdbadapter.h b/sicshdbadapter.h index 563b95f9..63ed3e87 100644 --- a/sicshdbadapter.h +++ b/sicshdbadapter.h @@ -17,9 +17,9 @@ #ifndef SICSHDBADAPTER_H_ #define SICSHDBADAPTER_H_ -int SICSHdbAdapter(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int HdbSubSample(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SICSHdbAdapter(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int HdbSubSample(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -#endif /*SICSHDBADAPTER_H_*/ +#endif /*SICSHDBADAPTER_H_ */ diff --git a/sicshdbfactory.c b/sicshdbfactory.c index b1856f78..cdc17cfc 100644 --- a/sicshdbfactory.c +++ b/sicshdbfactory.c @@ -9,344 +9,359 @@ */ #include #include "statusfile.h" - + #define MAX_HDB_PATH 1024 /*-------------------------------------------------------------------------*/ -static int MakePlainNode(pHdb parent, char *name, SConnection *pCon, - int argc, char *argv[]){ - pHdb child = NULL; - int type = 0, length = 0, priv = -1; - hdbValue val; - - if(argc < 5){ - SCWrite(pCon,"ERROR: not enough arguments to create plain node", - eError); - return 0; - } - - /* - * convert privilege - */ - priv = decodeSICSPriv(argv[3]); - if(priv < 0){ - SCPrintf(pCon,eError,"ERROR: %s is no valid privilege code", argv[3]); - return 0; - } - /* - * convert datatype - */ - strtolower(argv[4]); - type = convertHdbType(argv[4]); - if(type > HIPFLOATVARAR){ - SCWrite(pCon, +static int MakePlainNode(pHdb parent, char *name, SConnection * pCon, + int argc, char *argv[]) +{ + pHdb child = NULL; + int type = 0, length = 0, priv = -1; + hdbValue val; + + if (argc < 5) { + SCWrite(pCon, "ERROR: not enough arguments to create plain node", + eError); + return 0; + } + + /* + * convert privilege + */ + priv = decodeSICSPriv(argv[3]); + if (priv < 0) { + SCPrintf(pCon, eError, "ERROR: %s is no valid privilege code", + argv[3]); + return 0; + } + /* + * convert datatype + */ + strtolower(argv[4]); + type = convertHdbType(argv[4]); + if (type > HIPFLOATVARAR) { + SCWrite(pCon, "ERROR: invalid type requested: none, int, float, text, intar, floatar, intvarar, floatvarar supported", eError); - return 0; - } - if(type >= HIPINTAR){ - if( argc < 6){ - SCWrite(pCon,"ERROR: array length missing for array data type", - eError); - return 0; - } else { - length = atoi(argv[5]); - } - } + return 0; + } + if (type >= HIPINTAR) { + if (argc < 6) { + SCWrite(pCon, "ERROR: array length missing for array data type", + eError); + return 0; + } else { + length = atoi(argv[5]); + } + } - if(type != HIPNONE){ - val = makeHdbValue(type,length); - child = MakeSICSHdbPar(name, priv, val); - ReleaseHdbValue(&val); - } else { - child = MakeHipadabaNode(name,type,length); - } - if(child == NULL){ - SCWrite(pCon,"ERROR: out of memory creating node",eError); - return 0; - } - - AddHipadabaChild(parent,child,pCon); - SCSendOK(pCon); - return 1; + if (type != HIPNONE) { + val = makeHdbValue(type, length); + child = MakeSICSHdbPar(name, priv, val); + ReleaseHdbValue(&val); + } else { + child = MakeHipadabaNode(name, type, length); + } + if (child == NULL) { + SCWrite(pCon, "ERROR: out of memory creating node", eError); + return 0; + } + + AddHipadabaChild(parent, child, pCon); + SCSendOK(pCon); + return 1; } + /*--------------------------------------------------------------------------*/ -static int MakeScriptNode(pHdb parent, char *name, SConnection *pCon, - int argc, char *argv[]){ - int type, length; - pHdb child = NULL; - hdbValue v; +static int MakeScriptNode(pHdb parent, char *name, SConnection * pCon, + int argc, char *argv[]) +{ + int type, length; + pHdb child = NULL; + hdbValue v; - if(argc < 5){ - SCWrite(pCon, - "ERROR: not enough arguments to create script parameter node", - eError); - return 0; - } + if (argc < 5) { + SCWrite(pCon, + "ERROR: not enough arguments to create script parameter node", + eError); + return 0; + } - /* - * convert datatype - */ - strtolower(argv[5]); - type = convertHdbType(argv[5]); - if(type >= 7){ - SCWrite(pCon, + /* + * convert datatype + */ + strtolower(argv[5]); + type = convertHdbType(argv[5]); + if (type >= 7) { + SCWrite(pCon, "ERROR: invalid type requested: none, int, float, text, intar, floatar, intvarar, floatvarar supported", eError); - return 0; - } - if(type > 2){ - if( argc < 7){ - SCWrite(pCon,"ERROR: array length missing for array data type", - eError); - return 0; - } else { - length = atoi(argv[6]); - } - } - - v = makeHdbValue(type,length); - child = MakeSICSScriptPar(name, argv[4], argv[3], v); - ReleaseHdbValue(&v); - if(child == NULL){ - SCWrite(pCon,"ERROR: out of memory creating node",eError); - return 0; - } - - AddHipadabaChild(parent,child,pCon); - SCSendOK(pCon); - return 1; + return 0; + } + if (type > 2) { + if (argc < 7) { + SCWrite(pCon, "ERROR: array length missing for array data type", + eError); + return 0; + } else { + length = atoi(argv[6]); + } + } + + v = makeHdbValue(type, length); + child = MakeSICSScriptPar(name, argv[4], argv[3], v); + ReleaseHdbValue(&v); + if (child == NULL) { + SCWrite(pCon, "ERROR: out of memory creating node", eError); + return 0; + } + + AddHipadabaChild(parent, child, pCon); + SCSendOK(pCon); + return 1; } + /*-------------------------------------------------------------------------*/ -static int MakeLinkNode(pHdb parent, char *name, SConnection *pCon, - int argc, char *argv[]){ - pHdb node = NULL; - pObjectDescriptor pDes = NULL; - char buffer[256]; - - if(argc < 4){ - SCWrite(pCon,"ERROR: not enough arguments to create script node", - eError); - return 0; - } - pDes = FindCommandDescriptor(pServ->pSics,argv[3]); - if(pDes == NULL){ - snprintf(buffer,255,"ERROR: failed to find object %s", argv[3]); - SCWrite(pCon,buffer,eError); - return 0; - } - if(pDes->parNode == NULL){ - snprintf(buffer,255, - "ERROR: Object %s does not use Hipadaba natively and thus cannot be linked", - argv[3]); - SCWrite(pCon,buffer,eError); - return 0; - } +static int MakeLinkNode(pHdb parent, char *name, SConnection * pCon, + int argc, char *argv[]) +{ + pHdb node = NULL; + pObjectDescriptor pDes = NULL; + char buffer[256]; - if(pDes->parNode->mama != NULL){ - snprintf(buffer,255, - "ERROR: Object %s is already linked somewhere else", - argv[3]); - SCWrite(pCon,buffer,eError); - return 0; - } + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough arguments to create script node", + eError); + return 0; + } + pDes = FindCommandDescriptor(pServ->pSics, argv[3]); + if (pDes == NULL) { + snprintf(buffer, 255, "ERROR: failed to find object %s", argv[3]); + SCWrite(pCon, buffer, eError); + return 0; + } + if (pDes->parNode == NULL) { + snprintf(buffer, 255, + "ERROR: Object %s does not use Hipadaba natively and thus cannot be linked", + argv[3]); + SCWrite(pCon, buffer, eError); + return 0; + } - AddHipadabaChild(parent,pDes->parNode,pCon); - if(pDes->parNode->name != NULL){ - free(pDes->parNode->name); - } - pDes->parNode->name = strdup(name); - SCSendOK(pCon); - return 1; + if (pDes->parNode->mama != NULL) { + snprintf(buffer, 255, + "ERROR: Object %s is already linked somewhere else", argv[3]); + SCWrite(pCon, buffer, eError); + return 0; + } + + AddHipadabaChild(parent, pDes->parNode, pCon); + if (pDes->parNode->name != NULL) { + free(pDes->parNode->name); + } + pDes->parNode->name = strdup(name); + SCSendOK(pCon); + return 1; } + /* -------------------------------------------------------------------------- * This is actually SCInvoke but without advancing the context. I think this * is only of local use. It makes sure that commands executed as Hipadaba * commands get logged properly. - ---------------------------------------------------------------------------*/ - static int HDBInvoke(SConnection *self, SicsInterp *pInter, char *pCommand) - { - int iRet; - long lLen; - const char *pResult = NULL; - char *pBuffer = NULL, *pFile = NULL; - char pBueffel[80]; - int i, iSpace; - - assert(pInter); - - /* print command to log files */ - /* + ---------------------------------------------------------------------------*/ +static int HDBInvoke(SConnection * self, SicsInterp * pInter, + char *pCommand) +{ + int iRet; + long lLen; + const char *pResult = NULL; + char *pBuffer = NULL, *pFile = NULL; + char pBueffel[80]; + int i, iSpace; + + assert(pInter); + + /* print command to log files */ + /* for( i = 0; i < self->iFiles; i++) { - if(self->pFiles[i]) - { - fprintf(self->pFiles[i],"SICS>> %s\n",pCommand); - } - } - */ - - /* print to command log if user or manager */ - if(SCGetRights(self) <= usUser) + if(self->pFiles[i]) { - if(self->pSock != NULL) - { - sprintf(pBueffel,"sock %d>>",self->pSock->sockid); - } + fprintf(self->pFiles[i],"SICS>> %s\n",pCommand); } - - /* invoke */ - self->inUse++; - self->eInterrupt = eContinue; - /* - get first word of command - */ - iRet = InterpExecute(pInter,self,pCommand); - - StatusFileTask(NULL); /* save changed parameters */ + } + */ - self->inUse--; - return iRet; + /* print to command log if user or manager */ + if (SCGetRights(self) <= usUser) { + if (self->pSock != NULL) { + sprintf(pBueffel, "sock %d>>", self->pSock->sockid); + } } -/*---------------------------------------------------------------------------*/ -static hdbCallbackReturn CommandSetCallback(pHdb node, void *userData, - pHdbMessage message){ - SConnection *pCon = NULL; - pDynString cmd = NULL, par = NULL; - pHdb current = NULL; - int status; - pHdbDataMessage mm = NULL; - hdbValue v; - - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - pCon = (SConnection *)mm->callData; - v = *(mm->v); - - if(pCon == NULL){ - printf("Cannot invoke command without connection\n"); - return hdbAbort; - } - - if(v.dataType == HIPTEXT){ - if(strstr(v.v.text,"start") != NULL) { - cmd = CreateDynString(64,64); - if(cmd == 0){ - SCWrite(pCon,"ERROR: out of memory in CommandSetCallback",eError); - return 0; - } - DynStringCopy(cmd, node->value.v.text); - DynStringConcat(cmd," "); - current = node->child; - while(current != NULL){ - par = formatValue(current->value, current); - if(par != NULL){ - DynStringConcat(cmd, GetCharArray(par)); - DynStringConcat(cmd," "); - DeleteDynString(par); - } - current = current->next; - } - SendHdbStatusMessage(node,"start"); - status = HDBInvoke(pCon,pServ->pSics, GetCharArray(cmd)); - SendHdbStatusMessage(node,"stop"); - DeleteDynString(cmd); - if(status == 1){ - return hdbContinue; - } else { - return hdbAbort; - } - } else { - SCWrite(pCon,"ERROR: this node only understands start as value",eError); - return hdbAbort; - } - } - return hdbContinue; -} -/*---------------------------------------------------------------------------*/ -static hdbCallbackReturn CommandGetCallback(pHdb node, void *userData, - pHdbMessage message){ - pHdbDataMessage mm = NULL; - - if((mm = GetHdbGetMessage(message)) == NULL){ - return hdbContinue; - } - - hdbValue v2 = MakeHdbText(strdup("Nothing to get")); - copyHdbValue(&v2, mm->v); - return hdbContinue; -} -/*--------------------------------------------------------------------------*/ -static int MakeCommandNode(pHdb parent, char *name, SConnection *pCon, - int argc, char *argv[]){ - pHdb node = NULL; - pHdbCallback kalle = NULL; - - if(argc < 4){ - SCWrite(pCon,"ERROR: not enough arguments to create command node", - eError); - return 0; - } - node = MakeHipadabaNode(name, HIPTEXT, 1); - if(node == NULL){ - SCWrite(pCon,"ERROR: out of memory in hcommand",eError); - return 0; - } - node->value.v.text = strdup(argv[3]); - node->value.arrayLength = strlen(argv[3]); - SetHdbProperty(node,"sicscommand", argv[3]); - - kalle = MakeHipadabaCallback(CommandSetCallback,NULL, NULL); - if(kalle == NULL){ - SCWrite(pCon,"ERROR: out of memory in hcommand",eError); - return 0; - } - AppendHipadabaCallback(node,kalle); - kalle = MakeHipadabaCallback(CommandGetCallback,NULL, NULL); - if(kalle == NULL){ - SCWrite(pCon,"ERROR: out of memory in hcommand",eError); - return 0; - } - AppendHipadabaCallback(node,kalle); - - AddHipadabaChild(parent,node,pCon); - - SCSendOK(pCon); - return 1; + /* invoke */ + self->inUse++; + self->eInterrupt = eContinue; + /* + get first word of command + */ + iRet = InterpExecute(pInter, self, pCommand); + + StatusFileTask(NULL); /* save changed parameters */ + + self->inUse--; + return iRet; } -/*--------------------------------------------------------------------------*/ -int HdbNodeFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - char *name = NULL; - pHdb parent = NULL; - - if(!SCMatchRights(pCon,usMugger)){ + +/*---------------------------------------------------------------------------*/ +static hdbCallbackReturn CommandSetCallback(pHdb node, void *userData, + pHdbMessage message) +{ + SConnection *pCon = NULL; + pDynString cmd = NULL, par = NULL; + pHdb current = NULL; + int status; + pHdbDataMessage mm = NULL; + hdbValue v; + + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + pCon = (SConnection *) mm->callData; + v = *(mm->v); + + if (pCon == NULL) { + printf("Cannot invoke command without connection\n"); + return hdbAbort; + } + + if (v.dataType == HIPTEXT) { + if (strstr(v.v.text, "start") != NULL) { + cmd = CreateDynString(64, 64); + if (cmd == 0) { + SCWrite(pCon, "ERROR: out of memory in CommandSetCallback", + eError); return 0; - } - - if(argc < 3) { - SCWrite(pCon,"ERROR: not enough arguments to hfactory",eError); - return 0; - } - - parent = FindHdbParent(NULL, argv[1], &name, pCon); - if (parent == NULL) { - return 0; /* error messages written inside FindHdbParent */ - } - - strtolower(argv[2]); - if(strcmp(argv[2],"plain") == 0){ - return MakePlainNode(parent,name,pCon,argc,argv); - } else if(strcmp(argv[2],"script") == 0){ - return MakeScriptNode(parent,name,pCon,argc,argv); - } else if(strcmp(argv[2],"link") == 0){ - return MakeLinkNode(parent,name,pCon,argc,argv); - } else if(strcmp(argv[2],"command") == 0){ - return MakeCommandNode(parent,name,pCon,argc,argv); + } + DynStringCopy(cmd, node->value.v.text); + DynStringConcat(cmd, " "); + current = node->child; + while (current != NULL) { + par = formatValue(current->value, current); + if (par != NULL) { + DynStringConcat(cmd, GetCharArray(par)); + DynStringConcat(cmd, " "); + DeleteDynString(par); + } + current = current->next; + } + SendHdbStatusMessage(node, "start"); + status = HDBInvoke(pCon, pServ->pSics, GetCharArray(cmd)); + SendHdbStatusMessage(node, "stop"); + DeleteDynString(cmd); + if (status == 1) { + return hdbContinue; + } else { + return hdbAbort; + } } else { - SCWrite(pCon,"ERROR: node type not recognised", eError); - return 0; + SCWrite(pCon, "ERROR: this node only understands start as value", + eError); + return hdbAbort; } - return 0; + } + return hdbContinue; +} + +/*---------------------------------------------------------------------------*/ +static hdbCallbackReturn CommandGetCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbGetMessage(message)) == NULL) { + return hdbContinue; + } + + hdbValue v2 = MakeHdbText(strdup("Nothing to get")); + copyHdbValue(&v2, mm->v); + return hdbContinue; +} + +/*--------------------------------------------------------------------------*/ +static int MakeCommandNode(pHdb parent, char *name, SConnection * pCon, + int argc, char *argv[]) +{ + pHdb node = NULL; + pHdbCallback kalle = NULL; + + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough arguments to create command node", + eError); + return 0; + } + node = MakeHipadabaNode(name, HIPTEXT, 1); + if (node == NULL) { + SCWrite(pCon, "ERROR: out of memory in hcommand", eError); + return 0; + } + node->value.v.text = strdup(argv[3]); + node->value.arrayLength = strlen(argv[3]); + SetHdbProperty(node, "sicscommand", argv[3]); + + kalle = MakeHipadabaCallback(CommandSetCallback, NULL, NULL); + if (kalle == NULL) { + SCWrite(pCon, "ERROR: out of memory in hcommand", eError); + return 0; + } + AppendHipadabaCallback(node, kalle); + + kalle = MakeHipadabaCallback(CommandGetCallback, NULL, NULL); + if (kalle == NULL) { + SCWrite(pCon, "ERROR: out of memory in hcommand", eError); + return 0; + } + AppendHipadabaCallback(node, kalle); + + AddHipadabaChild(parent, node, pCon); + + SCSendOK(pCon); + return 1; +} + +/*--------------------------------------------------------------------------*/ +int HdbNodeFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char *name = NULL; + pHdb parent = NULL; + + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + if (argc < 3) { + SCWrite(pCon, "ERROR: not enough arguments to hfactory", eError); + return 0; + } + + parent = FindHdbParent(NULL, argv[1], &name, pCon); + if (parent == NULL) { + return 0; /* error messages written inside FindHdbParent */ + } + + strtolower(argv[2]); + if (strcmp(argv[2], "plain") == 0) { + return MakePlainNode(parent, name, pCon, argc, argv); + } else if (strcmp(argv[2], "script") == 0) { + return MakeScriptNode(parent, name, pCon, argc, argv); + } else if (strcmp(argv[2], "link") == 0) { + return MakeLinkNode(parent, name, pCon, argc, argv); + } else if (strcmp(argv[2], "command") == 0) { + return MakeCommandNode(parent, name, pCon, argc, argv); + } else { + SCWrite(pCon, "ERROR: node type not recognised", eError); + return 0; + } + return 0; } diff --git a/sicshipadaba.c b/sicshipadaba.c index 22c9dfe0..e14e815b 100644 --- a/sicshipadaba.c +++ b/sicshipadaba.c @@ -46,1298 +46,1409 @@ typedef enum { } Protocol; char *trim(char *str); /*====================== Messages ==================================================*/ -static char killID[] = {"killID"}; -static char killInternalID[] = {"killInternalID"}; -static char killPtr[] = {"killPtr"}; -static char startID[] = {"start"}; -static char stopID[] = {"stop"}; +static char killID[] = { "killID" }; +static char killInternalID[] = { "killInternalID" }; +static char killPtr[] = { "killPtr" }; +static char startID[] = { "start" }; +static char stopID[] = { "stop" }; + /*----------------------------------------------------------------------------------*/ -pHdbIDMessage GetKillIDMessage(pHdbMessage message){ - if(message->type == killID){ - return (pHdbIDMessage)message; - } - return NULL; +pHdbIDMessage GetKillIDMessage(pHdbMessage message) +{ + if (message->type == killID) { + return (pHdbIDMessage) message; + } + return NULL; } + /*-----------------------------------------------------------------------------------*/ -pHdbIDMessage GetKillInternalIDMessage(pHdbMessage message){ - if(message->type == killInternalID){ - return (pHdbIDMessage)message; - } - return NULL; +pHdbIDMessage GetKillInternalIDMessage(pHdbMessage message) +{ + if (message->type == killInternalID) { + return (pHdbIDMessage) message; + } + return NULL; } + /*-----------------------------------------------------------------------------------*/ -pHdbPtrMessage GetKillPtrMessage(pHdbMessage message){ - if(message->type == killPtr){ - return (pHdbPtrMessage)message; - } - return NULL; +pHdbPtrMessage GetKillPtrMessage(pHdbMessage message) +{ + if (message->type == killPtr) { + return (pHdbPtrMessage) message; + } + return NULL; } + /*-----------------------------------------------------------------------------------*/ -pHdbMessage GetHdbStartMessage(pHdbMessage message){ - if(message->type == startID){ - return (pHdbMessage)message; - } - return NULL; +pHdbMessage GetHdbStartMessage(pHdbMessage message) +{ + if (message->type == startID) { + return (pHdbMessage) message; + } + return NULL; } + /*-----------------------------------------------------------------------------------*/ -pHdbMessage GetHdbStopMessage(pHdbMessage message){ - if(message->type == stopID){ - return (pHdbMessage)message; - } - return NULL; +pHdbMessage GetHdbStopMessage(pHdbMessage message) +{ + if (message->type == stopID) { + return (pHdbMessage) message; + } + return NULL; } + /*-----------------------------------------------------------------------------------*/ -void SendHdbStatusMessage(pHdb node, char *status){ - pHdbMessage pRes = NULL; - pRes = malloc(sizeof(hdbMessage)); - if(pRes == NULL){ - return; - } - if(strcmp(status,"start") == 0){ - pRes->type = startID; - } else if(strcmp(status,"stop") == 0){ - pRes->type = stopID; - } else { - /* someone is trying to create an non existent message */ - assert(0); - } - InvokeCallbackChain(node,pRes); - free(pRes); +void SendHdbStatusMessage(pHdb node, char *status) +{ + pHdbMessage pRes = NULL; + pRes = malloc(sizeof(hdbMessage)); + if (pRes == NULL) { + return; + } + if (strcmp(status, "start") == 0) { + pRes->type = startID; + } else if (strcmp(status, "stop") == 0) { + pRes->type = stopID; + } else { + /* someone is trying to create an non existent message */ + assert(0); + } + InvokeCallbackChain(node, pRes); + free(pRes); } + /*=============== common callback functions used for SICS ===========================*/ -static hdbCallbackReturn SICSCheckPermissionCallback(pHdb node, void *userData, - pHdbMessage message){ - int *testPriv = NULL; - SConnection *pCon = NULL; - pHdbDataMessage mm = NULL; - - testPriv = (int *)userData; - - mm = GetHdbSetMessage(message); - if(mm == NULL){ - return hdbContinue; - } - pCon = (SConnection *)mm->callData; - - /* - * If pCon is NULL, then this is an internal call from some driver - * code where no permission check is necessary. However, when called - * through the hipadaba tree commands and other upper level code, the - * check will be honoured. - */ - if(pCon == NULL){ - return hdbContinue; - } - - assert(testPriv != NULL); - - if(SCMatchRights(pCon,*testPriv) == 1){ - return hdbContinue; - } else { - return hdbAbort; - } +static hdbCallbackReturn SICSCheckPermissionCallback(pHdb node, + void *userData, + pHdbMessage message) +{ + int *testPriv = NULL; + SConnection *pCon = NULL; + pHdbDataMessage mm = NULL; + + testPriv = (int *) userData; + + mm = GetHdbSetMessage(message); + if (mm == NULL) { + return hdbContinue; + } + pCon = (SConnection *) mm->callData; + + /* + * If pCon is NULL, then this is an internal call from some driver + * code where no permission check is necessary. However, when called + * through the hipadaba tree commands and other upper level code, the + * check will be honoured. + */ + if (pCon == NULL) { + return hdbContinue; + } + + assert(testPriv != NULL); + + if (SCMatchRights(pCon, *testPriv) == 1) { + return hdbContinue; + } else { + return hdbAbort; + } } + /*--------------------------------------------------------------------------------------*/ -pHdbCallback MakeCheckPermissionCallback(int priv){ - int *testPriv = NULL; - - testPriv = malloc(sizeof(int)); - if(testPriv == NULL){ - return NULL; - } - *testPriv = priv; - return MakeHipadabaCallback(SICSCheckPermissionCallback, testPriv,free); +pHdbCallback MakeCheckPermissionCallback(int priv) +{ + int *testPriv = NULL; + + testPriv = malloc(sizeof(int)); + if (testPriv == NULL) { + return NULL; + } + *testPriv = priv; + return MakeHipadabaCallback(SICSCheckPermissionCallback, testPriv, free); } + /*-------------------------------------------------------------------------------------*/ static char *removeSetUpdateID = "removeSetUpdate"; -void RemoveSetUpdateCallback(pHdb node) { - hdbPtrMessage m; +void RemoveSetUpdateCallback(pHdb node) +{ + hdbPtrMessage m; + + m.type = killPtr; + m.pPtr = removeSetUpdateID; + InvokeCallbackChain(node, (pHdbMessage) & m); +} - m.type = killPtr; - m.pPtr = removeSetUpdateID; - InvokeCallbackChain(node, (pHdbMessage)&m); -} /*-------------------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSSetUpdateCallback(pHdb node, void *userData, - pHdbMessage message){ - pHdbDataMessage mm = NULL; - pHdbPtrMessage pm = NULL; - int status; - - pm = GetKillPtrMessage(message); - if (pm != NULL) { - if (pm->pPtr == removeSetUpdateID) { - return hdbKill; - } - return hdbContinue; - } - mm = GetHdbSetMessage(message); - if(mm == NULL){ - return hdbContinue; - } - status = UpdateHipadabaPar(node,*(mm->v),mm->callData); - if (status) { - SCSendOK(mm->callData); +static hdbCallbackReturn SICSSetUpdateCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdbDataMessage mm = NULL; + pHdbPtrMessage pm = NULL; + int status; + + pm = GetKillPtrMessage(message); + if (pm != NULL) { + if (pm->pPtr == removeSetUpdateID) { + return hdbKill; } return hdbContinue; + } + mm = GetHdbSetMessage(message); + if (mm == NULL) { + return hdbContinue; + } + status = UpdateHipadabaPar(node, *(mm->v), mm->callData); + if (status) { + SCSendOK(mm->callData); + } + return hdbContinue; } + /*-------------------------------------------------------------------------------------*/ -pHdbCallback MakeSetUpdateCallback(){ - return MakeHipadabaCallback(SICSSetUpdateCallback, NULL,NULL); +pHdbCallback MakeSetUpdateCallback() +{ + return MakeHipadabaCallback(SICSSetUpdateCallback, NULL, NULL); } + /*---------------------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSReadOnlyCallback(pHdb node, void *userData, pHdbMessage message){ - SConnection *pCon = NULL; - pHdbDataMessage mm = NULL; - - mm = GetHdbSetMessage(message); - if(mm == NULL){ - return hdbContinue; - } - pCon = (SConnection *)mm->callData; - - if(pCon != NULL){ - SCWrite(pCon,"ERROR: parameter is READ-ONLY", eError); - } +static hdbCallbackReturn SICSReadOnlyCallback(pHdb node, void *userData, + pHdbMessage message) +{ + SConnection *pCon = NULL; + pHdbDataMessage mm = NULL; + + mm = GetHdbSetMessage(message); + if (mm == NULL) { + return hdbContinue; + } + pCon = (SConnection *) mm->callData; + + if (pCon != NULL) { + SCWrite(pCon, "ERROR: parameter is READ-ONLY", eError); + } + return hdbAbort; +} + +/*-------------------------------------------------------------------------------------*/ +pHdbCallback MakeReadOnlyCallback() +{ + return MakeHipadabaCallback(SICSReadOnlyCallback, NULL, NULL); +} + +/*-------------------------------------------------------------------------------------*/ +static hdbCallbackReturn SICSDriveCallback(pHdb node, void *userData, + pHdbMessage message) +{ + SConnection *pCon = NULL; + pDummy dum = NULL; + char pSicsdev[80]; + int status; + pHdbDataMessage mm = NULL; + hdbValue v; + + mm = GetHdbSetMessage(message); + if (mm == NULL) { + return hdbContinue; + } + + pCon = (SConnection *) mm->callData; + v = *(mm->v); + + dum = (pDummy) userData; + assert(pCon != NULL && dum != NULL); + if (GetHdbProperty(node, "sicsdev", pSicsdev, 79)) { + status = StartDevice(pServ->pExecutor, pSicsdev, dum->pDescriptor, + userData, pCon, (float) v.v.doubleValue); + } else { + status = StartDevice(pServ->pExecutor, node->name, dum->pDescriptor, + userData, pCon, (float) v.v.doubleValue); + } + if (status == 1) { + return hdbContinue; + } else { return hdbAbort; + } } -/*-------------------------------------------------------------------------------------*/ -pHdbCallback MakeReadOnlyCallback(){ - return MakeHipadabaCallback(SICSReadOnlyCallback, NULL,NULL); -} -/*-------------------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSDriveCallback(pHdb node, void *userData, - pHdbMessage message){ - SConnection *pCon = NULL; - pDummy dum = NULL; - char pSicsdev[80]; - int status; - pHdbDataMessage mm = NULL; - hdbValue v; - - mm = GetHdbSetMessage(message); - if(mm == NULL){ - return hdbContinue; - } - - pCon = (SConnection *)mm->callData; - v = *(mm->v); - - dum = (pDummy)userData; - assert(pCon != NULL && dum != NULL); - if(GetHdbProperty(node,"sicsdev",pSicsdev,79)){ - status = StartDevice(pServ->pExecutor,pSicsdev,dum->pDescriptor, - userData, pCon, (float)v.v.doubleValue); - } else { - status = StartDevice(pServ->pExecutor,node->name,dum->pDescriptor, - userData, pCon, (float)v.v.doubleValue); - } - if(status == 1){ - return hdbContinue; - } else { - return hdbAbort; - } -} + /*---------------------------------------------------------------------------------------*/ -pHdbCallback MakeSICSDriveCallback(void *sicsObject){ - return MakeHipadabaCallback(SICSDriveCallback, sicsObject,NULL); +pHdbCallback MakeSICSDriveCallback(void *sicsObject) +{ + return MakeHipadabaCallback(SICSDriveCallback, sicsObject, NULL); } + /*---------------------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSReadDriveCallback(pHdb node, void *userData, - pHdbMessage message){ - static SConnection *defCon = NULL; - SConnection *pCon = NULL; - pDummy dum = NULL; - pIDrivable pDriv = NULL; - float value; - pHdbDataMessage mm = NULL; - - mm = GetHdbGetMessage(message); - if(mm == NULL){ - return hdbContinue; - } - - pCon = (SConnection *)mm->callData; - dum = (pDummy)userData; - assert(dum != NULL); - - if(defCon == NULL){ - defCon = SCCreateDummyConnection(pServ->pSics); - } - - pDriv = dum->pDescriptor->GetInterface(dum,DRIVEID); - assert(pDriv != NULL); - if(pCon != NULL){ - value = pDriv->GetValue(dum,pCon); - node->value.v.doubleValue = (double)value; - mm->v->v.doubleValue = (double)value; - } else { - if(defCon != NULL){ - value = pDriv->GetValue(dum,defCon); - node->value.v.doubleValue = (double)value; - mm->v->v.doubleValue = (double)value; - } - } +static hdbCallbackReturn SICSReadDriveCallback(pHdb node, void *userData, + pHdbMessage message) +{ + static SConnection *defCon = NULL; + SConnection *pCon = NULL; + pDummy dum = NULL; + pIDrivable pDriv = NULL; + float value; + pHdbDataMessage mm = NULL; + + mm = GetHdbGetMessage(message); + if (mm == NULL) { return hdbContinue; + } + + pCon = (SConnection *) mm->callData; + dum = (pDummy) userData; + assert(dum != NULL); + + if (defCon == NULL) { + defCon = SCCreateDummyConnection(pServ->pSics); + } + + pDriv = dum->pDescriptor->GetInterface(dum, DRIVEID); + assert(pDriv != NULL); + if (pCon != NULL) { + value = pDriv->GetValue(dum, pCon); + node->value.v.doubleValue = (double) value; + mm->v->v.doubleValue = (double) value; + } else { + if (defCon != NULL) { + value = pDriv->GetValue(dum, defCon); + node->value.v.doubleValue = (double) value; + mm->v->v.doubleValue = (double) value; + } + } + return hdbContinue; } + /*--------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSFuncCallback(pHdb node, void *userData, - pHdbMessage message){ - pHdb par[64], current = NULL; - int nPar = 0; - SICSOBJFunc func = NULL; - pHdbDataMessage mm = NULL; - int status; - - mm = GetHdbSetMessage(message); - if(mm == NULL){ - return hdbContinue; - } - - assert(node->value.dataType == HIPFUNC); - if(userData == NULL || mm->callData == NULL){ - printf("Great Badness in calling SICSFuncCallback\n"); - return hdbAbort; - } - - current = node->child; - while(current != NULL){ - par[nPar] = current; - nPar++; - current = current->next; - } - func = (SICSOBJFunc)node->value.v.func; - if(func != NULL){ - SendHdbStatusMessage(node, "start"); - status = func((pSICSOBJ)userData,(SConnection *)mm->callData, - node, par,nPar); - SendHdbStatusMessage(node, "stop"); - } else { - printf("Great Badness in calling SICSFuncCallback\n"); - return hdbAbort; - } - if(status == 1){ - return hdbContinue; - } else { - return hdbAbort; - } +static hdbCallbackReturn SICSFuncCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdb par[64], current = NULL; + int nPar = 0; + SICSOBJFunc func = NULL; + pHdbDataMessage mm = NULL; + int status; + + mm = GetHdbSetMessage(message); + if (mm == NULL) { + return hdbContinue; + } + + assert(node->value.dataType == HIPFUNC); + if (userData == NULL || mm->callData == NULL) { + printf("Great Badness in calling SICSFuncCallback\n"); + return hdbAbort; + } + + current = node->child; + while (current != NULL) { + par[nPar] = current; + nPar++; + current = current->next; + } + func = (SICSOBJFunc) node->value.v.func; + if (func != NULL) { + SendHdbStatusMessage(node, "start"); + status = func((pSICSOBJ) userData, (SConnection *) mm->callData, + node, par, nPar); + SendHdbStatusMessage(node, "stop"); + } else { + printf("Great Badness in calling SICSFuncCallback\n"); + return hdbAbort; + } + if (status == 1) { + return hdbContinue; + } else { + return hdbAbort; + } } + /*---------------------------------------------------------------------------*/ -pHdbCallback MakeSICSFuncCallback(void *obj){ - return MakeHipadabaCallback(SICSFuncCallback, obj,NULL); +pHdbCallback MakeSICSFuncCallback(void *obj) +{ + return MakeHipadabaCallback(SICSFuncCallback, obj, NULL); } + /*--------------------------------------------------------------------------------------*/ -pHdbCallback MakeSICSReadDriveCallback(void *sicsObject){ - return MakeHipadabaCallback(SICSReadDriveCallback, sicsObject,NULL); +pHdbCallback MakeSICSReadDriveCallback(void *sicsObject) +{ + return MakeHipadabaCallback(SICSReadDriveCallback, sicsObject, NULL); } + /*---------------------------------------------------------------------------------------*/ typedef struct { - SConnection *pCon; - int ID; - int internalID; -}HdbCBInfo; + SConnection *pCon; + int ID; + int internalID; +} HdbCBInfo; -static Protocol isJSON(SConnection *pCon) { - char proName[128]; - void *pData; +static Protocol isJSON(SConnection * pCon) +{ + char proName[128]; + void *pData; - if(SCinMacro(pCon)){ - return normal_protocol; - } - pData = FindCommandData(pServ->pSics, "protocol","Protocol"); - ProtocolGet(pCon, pData, proName, 128); - if (strcmp(proName, "json") == 0) - return json_protocol; - else - return normal_protocol; + if (SCinMacro(pCon)) { + return normal_protocol; + } + pData = FindCommandData(pServ->pSics, "protocol", "Protocol"); + ProtocolGet(pCon, pData, proName, 128); + if (strcmp(proName, "json") == 0) + return json_protocol; + else + return normal_protocol; } /* Format a name,value pair according to the given protocol */ -int formatNameValue(Protocol protocol, char *name, char *value, pDynString result, int hdtype) { +int formatNameValue(Protocol protocol, char *name, char *value, + pDynString result, int hdtype) +{ char *char_arr, *ptr; - switch(protocol) { - case normal_protocol: - DynStringCopy(result,name); - DynStringConcat(result," = "); - DynStringConcat(result,value); - break; - case json_protocol: - switch(hdtype){ - case HIPNONE: - break; - case HIPINT: - case HIPFLOAT: - DynStringCopy(result,"{\""); - DynStringConcat(result,name); - DynStringConcat(result,"\": "); - DynStringConcat(result,value); - DynStringConcat(result,"}"); - break; - case HIPTEXT: - DynStringCopy(result,"{\""); - DynStringConcat(result,name); - DynStringConcat(result,"\": \""); - DynStringConcat(result,value); - DynStringConcat(result,"\"}"); - break; - case HIPINTAR: - case HIPINTVARAR: - case HIPFLOATAR: - case HIPFLOATVARAR: - char_arr = ptr = strdup(trim(value)); - while(*ptr != '\0') { - if (isspace(*ptr)) - *ptr=','; - ptr++; - } - DynStringCopy(result,"{\""); - DynStringConcat(result,name); - DynStringConcat(result,"\": [ "); - DynStringConcat(result,char_arr); - DynStringConcat(result," ]}"); - if (char_arr != NULL ) free(char_arr); - break; - } + switch (protocol) { + case normal_protocol: + DynStringCopy(result, name); + DynStringConcat(result, " = "); + DynStringConcat(result, value); + break; + case json_protocol: + switch (hdtype) { + case HIPNONE: + break; + case HIPINT: + case HIPFLOAT: + DynStringCopy(result, "{\""); + DynStringConcat(result, name); + DynStringConcat(result, "\": "); + DynStringConcat(result, value); + DynStringConcat(result, "}"); + break; + case HIPTEXT: + DynStringCopy(result, "{\""); + DynStringConcat(result, name); + DynStringConcat(result, "\": \""); + DynStringConcat(result, value); + DynStringConcat(result, "\"}"); + break; + case HIPINTAR: + case HIPINTVARAR: + case HIPFLOATAR: + case HIPFLOATVARAR: + char_arr = ptr = strdup(trim(value)); + while (*ptr != '\0') { + if (isspace(*ptr)) + *ptr = ','; + ptr++; + } + DynStringCopy(result, "{\""); + DynStringConcat(result, name); + DynStringConcat(result, "\": [ "); + DynStringConcat(result, char_arr); + DynStringConcat(result, " ]}"); + if (char_arr != NULL) + free(char_arr); + break; } + } return protocol; } + /*----------------------------------------------------------------------------*/ -static int sendZippedNodeData(pHdb node, SConnection *pCon){ - hdbValue newValue; - int i, *iData = NULL; - char *path = NULL; - - newValue = node->value; - path = GetHipadabaPath(node); - switch(newValue.dataType){ - case HIPINTAR: - case HIPINTVARAR: - if(newValue.v.intArray == NULL){ - free(path); - return 0; - } - iData = (int *)malloc(newValue.arrayLength*sizeof(int)); - if(iData == NULL){ - SCWrite(pCon,"ERROR: out of memory in sendZippedData",eError); - free(path); - return 0; - } - memset(iData,0,newValue.arrayLength*sizeof(int)); - for(i = 0; i < newValue.arrayLength; i++){ - iData[i] = htonl(newValue.v.intArray[i]); - } - SCWriteZipped(pCon,path, iData, - newValue.arrayLength*sizeof(int)); - free(iData); - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - if(newValue.v.floatArray == NULL){ - free(path); - return 0; - } - iData = (int *)malloc(newValue.arrayLength*sizeof(int)); - if(iData == NULL){ - SCWrite(pCon,"ERROR: out of memory in sendZippedData",eError); - free(path); - return 0; - } - memset(iData,0,newValue.arrayLength*sizeof(int)); - for(i = 0; i < newValue.arrayLength; i++){ - iData[i] = htonl((int)(newValue.v.floatArray[i]*65536.)); - } - SCWriteZipped(pCon,path, iData, - newValue.arrayLength*sizeof(int)); - free(iData); - break; - default: - SCWrite(pCon,"ERROR: zipped writing not supported for this datatype", - eError); - free(path); - return 0; - } +static int sendZippedNodeData(pHdb node, SConnection * pCon) +{ + hdbValue newValue; + int i, *iData = NULL; + char *path = NULL; + + newValue = node->value; + path = GetHipadabaPath(node); + switch (newValue.dataType) { + case HIPINTAR: + case HIPINTVARAR: + if (newValue.v.intArray == NULL) { + free(path); + return 0; + } + iData = (int *) malloc(newValue.arrayLength * sizeof(int)); + if (iData == NULL) { + SCWrite(pCon, "ERROR: out of memory in sendZippedData", eError); + free(path); + return 0; + } + memset(iData, 0, newValue.arrayLength * sizeof(int)); + for (i = 0; i < newValue.arrayLength; i++) { + iData[i] = htonl(newValue.v.intArray[i]); + } + SCWriteZipped(pCon, path, iData, newValue.arrayLength * sizeof(int)); + free(iData); + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + if (newValue.v.floatArray == NULL) { + free(path); + return 0; + } + iData = (int *) malloc(newValue.arrayLength * sizeof(int)); + if (iData == NULL) { + SCWrite(pCon, "ERROR: out of memory in sendZippedData", eError); + free(path); + return 0; + } + memset(iData, 0, newValue.arrayLength * sizeof(int)); + for (i = 0; i < newValue.arrayLength; i++) { + iData[i] = htonl((int) (newValue.v.floatArray[i] * 65536.)); + } + SCWriteZipped(pCon, path, iData, newValue.arrayLength * sizeof(int)); + free(iData); + break; + default: + SCWrite(pCon, "ERROR: zipped writing not supported for this datatype", + eError); free(path); - return 1; + return 0; + } + free(path); + return 1; } + /*----------------------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSNotifyCallback(pHdb node, void *userData, - pHdbMessage message ){ - HdbCBInfo *cbInfo = NULL; - pDynString printedData = NULL; - pDynString result = NULL; - char *pPath = NULL; - Protocol protocol = normal_protocol; - int outCode, macro, status; - char value[80]; - pHdbIDMessage idm = NULL; - pHdbPtrMessage cmm = NULL; - pHdbDataMessage mm = NULL; - SConnection *tstCon; - - cbInfo = (HdbCBInfo *)userData; - - /* - * handle kills first - */ - if((idm = GetKillIDMessage(message)) != NULL){ - if(idm->ID == cbInfo->ID){ - return hdbKill; - } else { - return hdbContinue; - } +static hdbCallbackReturn SICSNotifyCallback(pHdb node, void *userData, + pHdbMessage message) +{ + HdbCBInfo *cbInfo = NULL; + pDynString printedData = NULL; + pDynString result = NULL; + char *pPath = NULL; + Protocol protocol = normal_protocol; + int outCode, macro, status; + char value[80]; + pHdbIDMessage idm = NULL; + pHdbPtrMessage cmm = NULL; + pHdbDataMessage mm = NULL; + SConnection *tstCon; + + cbInfo = (HdbCBInfo *) userData; + + /* + * handle kills first + */ + if ((idm = GetKillIDMessage(message)) != NULL) { + if (idm->ID == cbInfo->ID) { + return hdbKill; + } else { + return hdbContinue; } - if((idm = GetKillInternalIDMessage(message)) != NULL){ - if(idm->ID == cbInfo->internalID){ - return hdbKill; - } else { - return hdbContinue; - } + } + if ((idm = GetKillInternalIDMessage(message)) != NULL) { + if (idm->ID == cbInfo->internalID) { + return hdbKill; + } else { + return hdbContinue; } - if((cmm = GetKillPtrMessage(message)) != NULL){ - tstCon = cmm->pPtr; - if(tstCon != NULL && tstCon->ident == cbInfo->pCon->ident){ - return hdbKill; - } else { - return hdbContinue; - } + } + if ((cmm = GetKillPtrMessage(message)) != NULL) { + tstCon = cmm->pPtr; + if (tstCon != NULL && tstCon->ident == cbInfo->pCon->ident) { + return hdbKill; + } else { + return hdbContinue; } - + } + /** * handle start and stop messages */ - if(GetHdbStartMessage(message) != NULL){ - pPath = GetHipadabaPath(node); - result = CreateDynString(128,128); - DynStringConcat(result, pPath); - DynStringConcat(result," STARTED"); - SCWrite(cbInfo->pCon, GetCharArray(result), eEvent); - DeleteDynString(result); - free(pPath); - return hdbContinue; - } - - if(GetHdbStopMessage(message) != NULL){ - pPath = GetHipadabaPath(node); - result = CreateDynString(128,128); - DynStringConcat(result, pPath); - DynStringConcat(result," FINISHED"); - SCWrite(cbInfo->pCon, GetCharArray(result), eEvent); - DeleteDynString(result); - free(pPath); - return hdbContinue; - } - - /* - * Deal with update messages - */ - if((mm = GetHdbUpdateMessage(message)) == NULL){ - return hdbContinue; - } - + if (GetHdbStartMessage(message) != NULL) { pPath = GetHipadabaPath(node); - result = CreateDynString(128,128); - if ((protocol = isJSON(cbInfo->pCon)) == 1) - outCode = eHdbEvent; - else - outCode = eEvent; + result = CreateDynString(128, 128); + DynStringConcat(result, pPath); + DynStringConcat(result, " STARTED"); + SCWrite(cbInfo->pCon, GetCharArray(result), eEvent); + DeleteDynString(result); + free(pPath); + return hdbContinue; + } + + if (GetHdbStopMessage(message) != NULL) { + pPath = GetHipadabaPath(node); + result = CreateDynString(128, 128); + DynStringConcat(result, pPath); + DynStringConcat(result, " FINISHED"); + SCWrite(cbInfo->pCon, GetCharArray(result), eEvent); + DeleteDynString(result); + free(pPath); + return hdbContinue; + } + + /* + * Deal with update messages + */ + if ((mm = GetHdbUpdateMessage(message)) == NULL) { + return hdbContinue; + } + + pPath = GetHipadabaPath(node); + result = CreateDynString(128, 128); + if ((protocol = isJSON(cbInfo->pCon)) == 1) + outCode = eHdbEvent; + else + outCode = eEvent; + - /** * if transfer = zip always transfer data in zipped form */ - if(GetHdbProperty(node,"transfer",value,80) == 1){ - if(strstr(value,"zip") != NULL){ - status = sendZippedNodeData(node, cbInfo->pCon); - free(pPath); - DeleteDynString(result); - return hdbContinue; - } + if (GetHdbProperty(node, "transfer", value, 80) == 1) { + if (strstr(value, "zip") != NULL) { + status = sendZippedNodeData(node, cbInfo->pCon); + free(pPath); + DeleteDynString(result); + return hdbContinue; } - if(mm->v->arrayLength < 100){ - printedData = formatValue(*(mm->v), node); - if(pPath == NULL || printedData == NULL || result == NULL){ - SCWrite(cbInfo->pCon,"ERROR: out of memory formatting data" , - eEvent); - /* - * no need to interrupt something because writing data to a client does - * not work - */ - return hdbContinue; - } - formatNameValue(protocol, pPath, GetCharArray(printedData), result, - mm->v->dataType); - SCWrite(cbInfo->pCon,GetCharArray(result), - outCode); - DeleteDynString(printedData); - } else { - formatNameValue(protocol, pPath,"!!datachange!!", result, HIPTEXT); - SCWrite(cbInfo->pCon,GetCharArray(result), - outCode); - } - free(pPath); - DeleteDynString(result); - - return hdbContinue; -} -/*-----------------------------------------------------------------------------------------*/ -static void cbKill(void *pData){ - HdbCBInfo *cbInfo = (HdbCBInfo *)pData; - if(cbInfo == NULL){ - return; + } + if (mm->v->arrayLength < 100) { + printedData = formatValue(*(mm->v), node); + if (pPath == NULL || printedData == NULL || result == NULL) { + SCWrite(cbInfo->pCon, "ERROR: out of memory formatting data", + eEvent); + /* + * no need to interrupt something because writing data to a client does + * not work + */ + return hdbContinue; } - if(cbInfo->pCon != NULL){ - SCDeleteConnection(cbInfo->pCon); - } - free(cbInfo); -} -/*-----------------------------------------------------------------------------------------*/ -pHdbCallback MakeNotifyCallback(SConnection *pCon, int id){ - HdbCBInfo *cbInfo = NULL; - - cbInfo = malloc(sizeof(HdbCBInfo)); - if(cbInfo == NULL){ - return NULL; - } - cbInfo->pCon = SCCopyConnection(pCon); - if(cbInfo->pCon == NULL){ - return NULL; - } - SCsetMacro(cbInfo->pCon,0); - cbInfo->ID = id; - cbInfo->internalID = -1; - return MakeHipadabaCallback(SICSNotifyCallback, cbInfo,cbKill); -} -/*-------------------------------------------------------------------------*/ -static hdbCallbackReturn TreeChangeCallback(pHdb node, void *userData, - pHdbMessage message){ - char *path = NULL; - char buffer[1024]; - pDynString result = NULL; - Protocol protocol = normal_protocol; - int outCode; - pHdbIDMessage idm = NULL; - pHdbPtrMessage cmm = NULL; - pHdbTreeChangeMessage tm = NULL; - SConnection *tstCon = NULL; - - HdbCBInfo *cbInfo = (HdbCBInfo *)userData; - - /* - * handle kills first - */ - if((idm = GetKillIDMessage(message)) != NULL){ - if(idm->ID == cbInfo->ID){ - return hdbKill; - } else { - return hdbContinue; - } - } - if((idm = GetKillInternalIDMessage(message)) != NULL){ - if(idm->ID == cbInfo->internalID){ - return hdbKill; - } else { - return hdbContinue; - } - } - if((cmm = GetKillPtrMessage(message)) != NULL){ - tstCon = cmm->pPtr; - if(tstCon != NULL && tstCon->ident == cbInfo->pCon->ident){ - return hdbKill; - } else { - return hdbContinue; - } - } - - if((tm = GetHdbTreeChangeMessage(message)) == NULL){ - return hdbContinue; - } - - if(cbInfo != NULL && cbInfo->pCon != NULL){ - result = CreateDynString(128,128); - if(result == NULL){ - SCWrite(cbInfo->pCon,"ERROR: out of memory in TreeChangeCallback",outCode); - return hdbAbort; - } - path = GetHipadabaPath(node); - if ((protocol = isJSON(cbInfo->pCon)) == 1) - outCode = eHdbEvent; - else - outCode = eEvent; - formatNameValue(protocol, "treechange", path, result, node->value.dataType); - SCWrite(cbInfo->pCon,GetCharArray(result),outCode); - DeleteDynString(result); - free(path); - } - return hdbContinue; -} -/*-------------------------------------------------------------------------*/ -pHdbCallback MakeTreeChangeCallback(SConnection *pCon, int id){ - HdbCBInfo *cbInfo = NULL; - - cbInfo = malloc(sizeof(HdbCBInfo)); - if(cbInfo == NULL){ - return NULL; - } - cbInfo->pCon = SCCopyConnection(pCon); - if(cbInfo->pCon == NULL){ - return NULL; - } - cbInfo->ID = id; - return MakeHipadabaCallback(TreeChangeCallback, cbInfo,cbKill); -} -/*----------------------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSScriptWriteCallback(pHdb node, void *userData, - pHdbMessage message){ - char *command = NULL; - SConnection *pCon = NULL; - pDynString newVal = NULL; - char error[1024]; - int status; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - - command = (char *)userData; - pCon = (SConnection *)mm->callData; + formatNameValue(protocol, pPath, GetCharArray(printedData), result, + mm->v->dataType); + SCWrite(cbInfo->pCon, GetCharArray(result), outCode); + DeleteDynString(printedData); + } else { + formatNameValue(protocol, pPath, "!!datachange!!", result, HIPTEXT); + SCWrite(cbInfo->pCon, GetCharArray(result), outCode); + } + free(pPath); + DeleteDynString(result); + + return hdbContinue; +} + +/*-----------------------------------------------------------------------------------------*/ +static void cbKill(void *pData) +{ + HdbCBInfo *cbInfo = (HdbCBInfo *) pData; + if (cbInfo == NULL) { + return; + } + if (cbInfo->pCon != NULL) { + SCDeleteConnection(cbInfo->pCon); + } + free(cbInfo); +} + +/*-----------------------------------------------------------------------------------------*/ +pHdbCallback MakeNotifyCallback(SConnection * pCon, int id) +{ + HdbCBInfo *cbInfo = NULL; + + cbInfo = malloc(sizeof(HdbCBInfo)); + if (cbInfo == NULL) { + return NULL; + } + cbInfo->pCon = SCCopyConnection(pCon); + if (cbInfo->pCon == NULL) { + return NULL; + } + SCsetMacro(cbInfo->pCon, 0); + cbInfo->ID = id; + cbInfo->internalID = -1; + return MakeHipadabaCallback(SICSNotifyCallback, cbInfo, cbKill); +} + +/*-------------------------------------------------------------------------*/ +static hdbCallbackReturn TreeChangeCallback(pHdb node, void *userData, + pHdbMessage message) +{ + char *path = NULL; + char buffer[1024]; + pDynString result = NULL; + Protocol protocol = normal_protocol; + int outCode; + pHdbIDMessage idm = NULL; + pHdbPtrMessage cmm = NULL; + pHdbTreeChangeMessage tm = NULL; + SConnection *tstCon = NULL; + + HdbCBInfo *cbInfo = (HdbCBInfo *) userData; + + /* + * handle kills first + */ + if ((idm = GetKillIDMessage(message)) != NULL) { + if (idm->ID == cbInfo->ID) { + return hdbKill; + } else { + return hdbContinue; + } + } + if ((idm = GetKillInternalIDMessage(message)) != NULL) { + if (idm->ID == cbInfo->internalID) { + return hdbKill; + } else { + return hdbContinue; + } + } + if ((cmm = GetKillPtrMessage(message)) != NULL) { + tstCon = cmm->pPtr; + if (tstCon != NULL && tstCon->ident == cbInfo->pCon->ident) { + return hdbKill; + } else { + return hdbContinue; + } + } + + if ((tm = GetHdbTreeChangeMessage(message)) == NULL) { + return hdbContinue; + } + + if (cbInfo != NULL && cbInfo->pCon != NULL) { + result = CreateDynString(128, 128); + if (result == NULL) { + SCWrite(cbInfo->pCon, "ERROR: out of memory in TreeChangeCallback", + outCode); + return hdbAbort; + } + path = GetHipadabaPath(node); + if ((protocol = isJSON(cbInfo->pCon)) == 1) + outCode = eHdbEvent; + else + outCode = eEvent; + formatNameValue(protocol, "treechange", path, result, + node->value.dataType); + SCWrite(cbInfo->pCon, GetCharArray(result), outCode); + DeleteDynString(result); + free(path); + } + return hdbContinue; +} + +/*-------------------------------------------------------------------------*/ +pHdbCallback MakeTreeChangeCallback(SConnection * pCon, int id) +{ + HdbCBInfo *cbInfo = NULL; + + cbInfo = malloc(sizeof(HdbCBInfo)); + if (cbInfo == NULL) { + return NULL; + } + cbInfo->pCon = SCCopyConnection(pCon); + if (cbInfo->pCon == NULL) { + return NULL; + } + cbInfo->ID = id; + return MakeHipadabaCallback(TreeChangeCallback, cbInfo, cbKill); +} + +/*----------------------------------------------------------------------------------------*/ +static hdbCallbackReturn SICSScriptWriteCallback(pHdb node, void *userData, + pHdbMessage message) +{ + char *command = NULL; + SConnection *pCon = NULL; + pDynString newVal = NULL; + char error[1024]; + int status; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + + command = (char *) userData; + pCon = (SConnection *) mm->callData; + + assert(command != NULL && pCon != NULL); + + newVal = formatValue(*(mm->v), node); + if (newVal == NULL) { + SCWrite(pCon, "ERROR: out of memory setting parameter", eError); + return hdbAbort; + } - assert(command != NULL && pCon != NULL); - - newVal = formatValue(*(mm->v), node); - if(newVal == NULL){ - SCWrite(pCon,"ERROR: out of memory setting parameter",eError); - return hdbAbort; - } - /** * prepend command */ - DynStringInsert(newVal," ", 0); - DynStringInsert(newVal,command,0); - - /* - * evaluate - */ - status = Tcl_Eval(InterpGetTcl(pServ->pSics),GetCharArray(newVal)); - if(status != TCL_OK){ - snprintf(error,1023,"ERROR: tcl returned error: %s", - Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); - SCWrite(pCon,error,eError); - status = 0; - } else { - status = 1; - } - DeleteDynString(newVal); - if(status == 1){ - return hdbContinue; - } else{ - return hdbAbort; - } -} + DynStringInsert(newVal, " ", 0); + DynStringInsert(newVal, command, 0); + + /* + * evaluate + */ + status = Tcl_Eval(InterpGetTcl(pServ->pSics), GetCharArray(newVal)); + if (status != TCL_OK) { + snprintf(error, 1023, "ERROR: tcl returned error: %s", + Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); + SCWrite(pCon, error, eError); + status = 0; + } else { + status = 1; + } + DeleteDynString(newVal); + if (status == 1) { + return hdbContinue; + } else { + return hdbAbort; + } +} + /*---------------------------------------------------------------------------------------*/ -static pHdbCallback MakeSICSWriteScriptCallback(char *script){ - return MakeHipadabaCallback(SICSScriptWriteCallback, strdup(script),free); +static pHdbCallback MakeSICSWriteScriptCallback(char *script) +{ + return MakeHipadabaCallback(SICSScriptWriteCallback, strdup(script), + free); } + /*----------------------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSScriptReadCallback(pHdb node, void *userData, - pHdbMessage message){ - char *command = NULL, *data = NULL, *equal = NULL; - SConnection *pCon = NULL; - pDynString newVal = NULL; - char error[1024]; - int status; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbGetMessage(message)) == NULL){ - return hdbContinue; - } - - command = (char *)userData; - pCon = (SConnection *)mm->callData; +static hdbCallbackReturn SICSScriptReadCallback(pHdb node, void *userData, + pHdbMessage message) +{ + char *command = NULL, *data = NULL, *equal = NULL; + SConnection *pCon = NULL; + pDynString newVal = NULL; + char error[1024]; + int status; + pHdbDataMessage mm = NULL; - assert(command != NULL); - - /* - * evaluate - */ - if(pCon != NULL){ - MacroPush(pCon); - } - status = Tcl_Eval(InterpGetTcl(pServ->pSics),command); - if(pCon != NULL){ - MacroPop(); - } - if(status != TCL_OK){ - snprintf(error,1023,"ERROR: Tcl returned error: %s", - Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); - if(pCon != NULL){ - SCWrite(pCon,error,eError); - } - status = 0; - } else { - status = 1; - } + if ((mm = GetHdbGetMessage(message)) == NULL) { + return hdbContinue; + } - /* - * decode result. This handles both the case of the standard SICS answer - * something = anything - * as well as a plain value alone - */ - data = (char *)Tcl_GetStringResult(InterpGetTcl(pServ->pSics)); - if(data == NULL){ - if(pCon != NULL){ - SCWrite(pCon,"ERROR: no result returned from script",eError); - } - return hdbAbort; + command = (char *) userData; + pCon = (SConnection *) mm->callData; + + assert(command != NULL); + + /* + * evaluate + */ + if (pCon != NULL) { + MacroPush(pCon); + } + status = Tcl_Eval(InterpGetTcl(pServ->pSics), command); + if (pCon != NULL) { + MacroPop(); + } + if (status != TCL_OK) { + snprintf(error, 1023, "ERROR: Tcl returned error: %s", + Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); + if (pCon != NULL) { + SCWrite(pCon, error, eError); } - - /* - * do we need to copy? - */ - if(strstr(data,"@@NOCOPY@@") != NULL){ - return hdbContinue; - } - - /* - * we need to copy: do it - */ - equal = strchr(data,'='); - if(equal != NULL){ - data = equal + 1; - } - strcpy(error,"ERROR: "); - status = readHdbValue(&node->value,data, error+7, 1024-7); - if(status != 1){ - if(pCon != NULL){ - SCWrite(pCon,error,eError); - } - return hdbAbort; - } - if(status == 1){ - return hdbContinue; - } else { - return hdbAbort; - } -} -/*----------------------------------------------------------------------------*/ -static pHdbCallback MakeSICSReadScriptCallback(char *script){ - return MakeHipadabaCallback(SICSScriptReadCallback, strdup(script), - free); -} -/*---------------------------------------------------------------------------*/ -typedef struct { - int min; - int max; -}hdbIntRange, *pHdbIntRange; -/*---------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSIntRangeCallback(pHdb node, void *userData, - pHdbMessage message){ - char buffer[256]; - pHdbIntRange range = NULL; - SConnection *pCon = NULL; - int status = 1; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - - range = (pHdbIntRange)userData; - pCon = (SConnection *)mm->callData; - - assert(range != NULL); - - if(mm->v->v.intValue > range->max || mm->v->v.intValue < range->min) { - status = SICSCBRANGE; - if(pCon != NULL){ - snprintf(buffer,255,"ERROR: %d is not within permitted range: %d to %d", - (int)mm->v->v.intValue, range->min, range->max); - SCWrite(pCon,buffer,eError); - } - return hdbAbort; - } - return hdbContinue; -} -/*---------------------------------------------------------------------------*/ -pHdbCallback MakeIntRangeCallback(int min, int max){ - pHdbIntRange range = NULL; - - range = malloc(sizeof(hdbIntRange)); - if(range == NULL){ - return NULL; - } - range->min = min; - range->max = max; - return MakeHipadabaCallback(SICSIntRangeCallback, range, - free); -} -/*---------------------------------------------------------------------------*/ -typedef struct { - double min; - double max; -}hdbFloatRange, *pHdbFloatRange; -/*---------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSFloatRangeCallback(pHdb node, void *userData, - pHdbMessage message){ - char buffer[256]; - pHdbFloatRange range = NULL; - SConnection *pCon = NULL; - int status = 1; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - - range = (pHdbFloatRange)userData; - pCon = (SConnection *)mm->callData; - - assert(range != NULL); - - if(mm->v->v.doubleValue > range->max || mm->v->v.doubleValue < range->min) { - status = SICSCBRANGE; - if(pCon != NULL){ - snprintf(buffer,255,"ERROR: %lf is not within permitted range: %lf to %lf", - mm->v->v.doubleValue, range->min, range->max); - SCWrite(pCon,buffer,eError); - } - return hdbAbort; - } - return hdbContinue; -} -/*---------------------------------------------------------------------------*/ -pHdbCallback MakeFloatRangeCallback(double min, double max){ - pHdbFloatRange range = NULL; - - range = malloc(sizeof(hdbFloatRange)); - if(range == NULL){ - return NULL; - } - range->min = min; - range->max = max; - return MakeHipadabaCallback(SICSFloatRangeCallback, range, - free); -} -/*------------------------------------------------------------------------*/ -static hdbCallbackReturn MemGenReadCallback(pHdb node, void *userData, - pHdbMessage message){ - pHdbDataMessage mm = NULL; - - if((mm = GetHdbGetMessage(message)) == NULL){ - return hdbContinue; - } - - switch(node->value.dataType){ - case HIPINT: - node->value.v.intValue = *(int *)userData; - break; - case HIPFLOAT: - node->value.v.doubleValue = *(double *)userData; - break; - case HIPTEXT: - if(node->value.v.text != NULL){ - free(node->value.v.text); - } - node->value.v.text = strdup((char *)userData); - break; - case HIPINTAR: - memcpy(&node->value.v.intArray,userData, - node->value.arrayLength *sizeof(int)); - break; - case HIPFLOATAR: - memcpy(&node->value.v.floatArray,userData, - node->value.arrayLength *sizeof(double)); - break; - default: - assert(0); - break; - } - return hdbContinue; -} -/*-------------------------------------------------------------------------*/ -pHdbCallback MakeMemGenReadCallback(void *address){ - return MakeHipadabaCallback(MemGenReadCallback, address, - NULL); -} -/*-------------------------------------------------------------------------*/ -static hdbCallbackReturn MemGenSetCallback(pHdb node, void *userData, - pHdbMessage message){ - const char *pPtr = NULL; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - - - if(mm->v->dataType != node->value.dataType){ - assert(0); - return 0; - } - - switch(node->value.dataType){ - case HIPINT: - memcpy(userData,&mm->v->v.intValue,sizeof(int)); - break; - case HIPFLOAT: - memcpy(userData,&mm->v->v.doubleValue,sizeof(double)); - break; - case HIPTEXT: - strncpy((char *)userData,(const char *)mm->v->v.text, - node->value.arrayLength); - break; - case HIPINTAR: - memcpy(userData,&mm->v->v.intArray,node->value.arrayLength*sizeof(int)); - break; - case HIPFLOATAR: - memcpy(userData,&mm->v->v.floatArray, - node->value.arrayLength*sizeof(double)); - break; - default: - assert(0); - return 0; - break; - } - UpdateHipadabaPar(node,*(mm->v),mm->callData); - return hdbContinue; -} -/*-------------------------------------------------------------------------*/ -pHdbCallback MakeMemGenSetCallback(void *address){ - return MakeHipadabaCallback(MemGenSetCallback, address, - NULL); -} -/*--------------------------------------------------------------------------*/ -static void killHdbValue(void *pData){ - hdbValue *v = NULL; - - v = (hdbValue *)pData; - if(v == NULL){ - return; - } - ReleaseHdbValue(v); - free(v); -} -/*--------------------------------------------------------------------------*/ -static hdbCallbackReturn SICSIntFixedCallback(pHdb node, void *userData, - pHdbMessage message){ - hdbValue *allowed = NULL; - SConnection *pCon = NULL; - int i; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - - allowed = (hdbValue *)userData; - pCon = (SConnection *)mm->callData; - assert(allowed != NULL && allowed->dataType == HIPINTAR); - for(i = 0; i < allowed->arrayLength; i++){ - if(mm->v->v.intValue == allowed->v.intArray[i]){ - return hdbContinue; - } - } - if(pCon != NULL){ - SCWrite(pCon,"ERROR: value is not in the list of allowed values",eError); + status = 0; + } else { + status = 1; + } + + /* + * decode result. This handles both the case of the standard SICS answer + * something = anything + * as well as a plain value alone + */ + data = (char *) Tcl_GetStringResult(InterpGetTcl(pServ->pSics)); + if (data == NULL) { + if (pCon != NULL) { + SCWrite(pCon, "ERROR: no result returned from script", eError); } return hdbAbort; + } + + /* + * do we need to copy? + */ + if (strstr(data, "@@NOCOPY@@") != NULL) { + return hdbContinue; + } + + /* + * we need to copy: do it + */ + equal = strchr(data, '='); + if (equal != NULL) { + data = equal + 1; + } + strcpy(error, "ERROR: "); + status = readHdbValue(&node->value, data, error + 7, 1024 - 7); + if (status != 1) { + if (pCon != NULL) { + SCWrite(pCon, error, eError); + } + return hdbAbort; + } + if (status == 1) { + return hdbContinue; + } else { + return hdbAbort; + } } + +/*----------------------------------------------------------------------------*/ +static pHdbCallback MakeSICSReadScriptCallback(char *script) +{ + return MakeHipadabaCallback(SICSScriptReadCallback, strdup(script), + free); +} + /*---------------------------------------------------------------------------*/ -pHdbCallback MakeIntFixedCallback(int *data, int length){ - pHdbCallback result = NULL; - hdbValue *v = NULL; - - v = malloc(sizeof(hdbValue)); - if(v == NULL){ - return NULL; +typedef struct { + int min; + int max; +} hdbIntRange, *pHdbIntRange; +/*---------------------------------------------------------------------------*/ +static hdbCallbackReturn SICSIntRangeCallback(pHdb node, void *userData, + pHdbMessage message) +{ + char buffer[256]; + pHdbIntRange range = NULL; + SConnection *pCon = NULL; + int status = 1; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + + range = (pHdbIntRange) userData; + pCon = (SConnection *) mm->callData; + + assert(range != NULL); + + if (mm->v->v.intValue > range->max || mm->v->v.intValue < range->min) { + status = SICSCBRANGE; + if (pCon != NULL) { + snprintf(buffer, 255, + "ERROR: %d is not within permitted range: %d to %d", + (int) mm->v->v.intValue, range->min, range->max); + SCWrite(pCon, buffer, eError); } - v->dataType = HIPINTAR; - v->arrayLength = length; - v->v.intArray = malloc(length*sizeof(int)); - if(v->v.intArray == NULL){ - return NULL; - } - memcpy(v->v.intArray,data,length*sizeof(int)); - return MakeHipadabaCallback(SICSIntFixedCallback, v, - killHdbValue); + return hdbAbort; + } + return hdbContinue; } + +/*---------------------------------------------------------------------------*/ +pHdbCallback MakeIntRangeCallback(int min, int max) +{ + pHdbIntRange range = NULL; + + range = malloc(sizeof(hdbIntRange)); + if (range == NULL) { + return NULL; + } + range->min = min; + range->max = max; + return MakeHipadabaCallback(SICSIntRangeCallback, range, free); +} + +/*---------------------------------------------------------------------------*/ +typedef struct { + double min; + double max; +} hdbFloatRange, *pHdbFloatRange; +/*---------------------------------------------------------------------------*/ +static hdbCallbackReturn SICSFloatRangeCallback(pHdb node, void *userData, + pHdbMessage message) +{ + char buffer[256]; + pHdbFloatRange range = NULL; + SConnection *pCon = NULL; + int status = 1; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + + range = (pHdbFloatRange) userData; + pCon = (SConnection *) mm->callData; + + assert(range != NULL); + + if (mm->v->v.doubleValue > range->max + || mm->v->v.doubleValue < range->min) { + status = SICSCBRANGE; + if (pCon != NULL) { + snprintf(buffer, 255, + "ERROR: %lf is not within permitted range: %lf to %lf", + mm->v->v.doubleValue, range->min, range->max); + SCWrite(pCon, buffer, eError); + } + return hdbAbort; + } + return hdbContinue; +} + +/*---------------------------------------------------------------------------*/ +pHdbCallback MakeFloatRangeCallback(double min, double max) +{ + pHdbFloatRange range = NULL; + + range = malloc(sizeof(hdbFloatRange)); + if (range == NULL) { + return NULL; + } + range->min = min; + range->max = max; + return MakeHipadabaCallback(SICSFloatRangeCallback, range, free); +} + +/*------------------------------------------------------------------------*/ +static hdbCallbackReturn MemGenReadCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbGetMessage(message)) == NULL) { + return hdbContinue; + } + + switch (node->value.dataType) { + case HIPINT: + node->value.v.intValue = *(int *) userData; + break; + case HIPFLOAT: + node->value.v.doubleValue = *(double *) userData; + break; + case HIPTEXT: + if (node->value.v.text != NULL) { + free(node->value.v.text); + } + node->value.v.text = strdup((char *) userData); + break; + case HIPINTAR: + memcpy(&node->value.v.intArray, userData, + node->value.arrayLength * sizeof(int)); + break; + case HIPFLOATAR: + memcpy(&node->value.v.floatArray, userData, + node->value.arrayLength * sizeof(double)); + break; + default: + assert(0); + break; + } + return hdbContinue; +} + +/*-------------------------------------------------------------------------*/ +pHdbCallback MakeMemGenReadCallback(void *address) +{ + return MakeHipadabaCallback(MemGenReadCallback, address, NULL); +} + +/*-------------------------------------------------------------------------*/ +static hdbCallbackReturn MemGenSetCallback(pHdb node, void *userData, + pHdbMessage message) +{ + const char *pPtr = NULL; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + + + if (mm->v->dataType != node->value.dataType) { + assert(0); + return 0; + } + + switch (node->value.dataType) { + case HIPINT: + memcpy(userData, &mm->v->v.intValue, sizeof(int)); + break; + case HIPFLOAT: + memcpy(userData, &mm->v->v.doubleValue, sizeof(double)); + break; + case HIPTEXT: + strncpy((char *) userData, (const char *) mm->v->v.text, + node->value.arrayLength); + break; + case HIPINTAR: + memcpy(userData, &mm->v->v.intArray, + node->value.arrayLength * sizeof(int)); + break; + case HIPFLOATAR: + memcpy(userData, &mm->v->v.floatArray, + node->value.arrayLength * sizeof(double)); + break; + default: + assert(0); + return 0; + break; + } + UpdateHipadabaPar(node, *(mm->v), mm->callData); + return hdbContinue; +} + +/*-------------------------------------------------------------------------*/ +pHdbCallback MakeMemGenSetCallback(void *address) +{ + return MakeHipadabaCallback(MemGenSetCallback, address, NULL); +} + +/*--------------------------------------------------------------------------*/ +static void killHdbValue(void *pData) +{ + hdbValue *v = NULL; + + v = (hdbValue *) pData; + if (v == NULL) { + return; + } + ReleaseHdbValue(v); + free(v); +} + +/*--------------------------------------------------------------------------*/ +static hdbCallbackReturn SICSIntFixedCallback(pHdb node, void *userData, + pHdbMessage message) +{ + hdbValue *allowed = NULL; + SConnection *pCon = NULL; + int i; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + + allowed = (hdbValue *) userData; + pCon = (SConnection *) mm->callData; + assert(allowed != NULL && allowed->dataType == HIPINTAR); + for (i = 0; i < allowed->arrayLength; i++) { + if (mm->v->v.intValue == allowed->v.intArray[i]) { + return hdbContinue; + } + } + if (pCon != NULL) { + SCWrite(pCon, "ERROR: value is not in the list of allowed values", + eError); + } + return hdbAbort; +} + +/*---------------------------------------------------------------------------*/ +pHdbCallback MakeIntFixedCallback(int *data, int length) +{ + pHdbCallback result = NULL; + hdbValue *v = NULL; + + v = malloc(sizeof(hdbValue)); + if (v == NULL) { + return NULL; + } + v->dataType = HIPINTAR; + v->arrayLength = length; + v->v.intArray = malloc(length * sizeof(int)); + if (v->v.intArray == NULL) { + return NULL; + } + memcpy(v->v.intArray, data, length * sizeof(int)); + return MakeHipadabaCallback(SICSIntFixedCallback, v, killHdbValue); +} + /*============= Parameter Creation ===========================================*/ -pHdb MakeSICSHdbPar(char *name, int priv, hdbValue v){ - pHdb result = NULL; - pHdbCallback pHcb = NULL; - char pPriv[20]; - - result = MakeHipadabaNode(name,v.dataType,v.arrayLength); - if(result == NULL){ - return NULL; - } - copyHdbValue(&v,&result->value); +pHdb MakeSICSHdbPar(char *name, int priv, hdbValue v) +{ + pHdb result = NULL; + pHdbCallback pHcb = NULL; + char pPriv[20]; - pHcb = MakeCheckPermissionCallback(priv); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); - - pHcb = MakeSetUpdateCallback(); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); - switch(priv){ - case 0: - strcpy(pPriv,"internal"); - break; - case 1: - strcpy(pPriv,"manager"); - break; - case 2: - strcpy(pPriv,"user"); - break; - case 3: - strcpy(pPriv,"spy"); - break; - } - SetHdbProperty(result,"priv",pPriv); + result = MakeHipadabaNode(name, v.dataType, v.arrayLength); + if (result == NULL) { + return NULL; + } + copyHdbValue(&v, &result->value); - return result; + pHcb = MakeCheckPermissionCallback(priv); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); + + pHcb = MakeSetUpdateCallback(); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); + switch (priv) { + case 0: + strcpy(pPriv, "internal"); + break; + case 1: + strcpy(pPriv, "manager"); + break; + case 2: + strcpy(pPriv, "user"); + break; + case 3: + strcpy(pPriv, "spy"); + break; + } + SetHdbProperty(result, "priv", pPriv); + + return result; } + /*----------------------------------------------------------------------------*/ -pHdb MakeSICSHdbDriv(char *name, int priv, void *sicsObject, int dataType){ - pHdb result = NULL; - pHdbCallback pHcb = NULL; - - result = MakeHipadabaNode(name,dataType,0); - if(result == NULL){ - return NULL; - } +pHdb MakeSICSHdbDriv(char *name, int priv, void *sicsObject, int dataType) +{ + pHdb result = NULL; + pHdbCallback pHcb = NULL; - pHcb = MakeCheckPermissionCallback(priv); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); - - pHcb = MakeSICSDriveCallback(sicsObject); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); + result = MakeHipadabaNode(name, dataType, 0); + if (result == NULL) { + return NULL; + } - pHcb = MakeSICSReadDriveCallback(sicsObject); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); + pHcb = MakeCheckPermissionCallback(priv); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); - return result; + pHcb = MakeSICSDriveCallback(sicsObject); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); + + pHcb = MakeSICSReadDriveCallback(sicsObject); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); + + return result; } + /*---------------------------------------------------------------------------*/ -pHdb MakeSICSMemPar(char *name, int priv, float *address){ - pHdb result = NULL; - pHdbCallback pHcb = NULL; - - result = MakeHipadabaNode(name,HIPFLOAT,1); - if(result == NULL){ - return NULL; - } +pHdb MakeSICSMemPar(char *name, int priv, float *address) +{ + pHdb result = NULL; + pHdbCallback pHcb = NULL; - pHcb = MakeCheckPermissionCallback(priv); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); + result = MakeHipadabaNode(name, HIPFLOAT, 1); + if (result == NULL) { + return NULL; + } - pHcb = MakeMemGenSetCallback(address); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); - - pHcb = MakeMemGenReadCallback(address); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); + pHcb = MakeCheckPermissionCallback(priv); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); - return result; + pHcb = MakeMemGenSetCallback(address); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); + + pHcb = MakeMemGenReadCallback(address); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); + + return result; } + /*----------------------------------------------------------------------------*/ -pHdb MakeSICSROPar(char *name, hdbValue v){ - pHdb result = NULL; - pHdbCallback pHcb = NULL; - - result = MakeHipadabaNode(name,v.dataType,v.arrayLength); - if(result == NULL){ - return NULL; - } - copyHdbValue(&v,&result->value); +pHdb MakeSICSROPar(char *name, hdbValue v) +{ + pHdb result = NULL; + pHdbCallback pHcb = NULL; - pHcb = MakeReadOnlyCallback(); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); - - return result; + result = MakeHipadabaNode(name, v.dataType, v.arrayLength); + if (result == NULL) { + return NULL; + } + copyHdbValue(&v, &result->value); + + pHcb = MakeReadOnlyCallback(); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); + + return result; } + /*---------------------------------------------------------------------------*/ -pHdb MakeSICSScriptPar(char *name, char *setScript, char *readScript, - hdbValue v){ - pHdb result = NULL; - pHdbCallback pHcb = NULL; - - result = MakeHipadabaNode(name,v.dataType,v.arrayLength); - if(result == NULL){ - return NULL; - } - copyHdbValue(&v,&result->value); +pHdb MakeSICSScriptPar(char *name, char *setScript, char *readScript, + hdbValue v) +{ + pHdb result = NULL; + pHdbCallback pHcb = NULL; - pHcb = MakeSICSWriteScriptCallback(setScript); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); + result = MakeHipadabaNode(name, v.dataType, v.arrayLength); + if (result == NULL) { + return NULL; + } + copyHdbValue(&v, &result->value); - pHcb = MakeSICSReadScriptCallback(readScript); - if(pHcb == NULL){ - DeleteHipadabaNode(result,NULL); - return NULL; - } - AppendHipadabaCallback(result,pHcb); + pHcb = MakeSICSWriteScriptCallback(setScript); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); + + pHcb = MakeSICSReadScriptCallback(readScript); + if (pHcb == NULL) { + DeleteHipadabaNode(result, NULL); + return NULL; + } + AppendHipadabaCallback(result, pHcb); /** * put into the list of nodes to check with the update task */ - /* LLDnodeAppend(scriptUpdate,&result); */ - SetHdbProperty(result,"sicscommand",setScript); - return result; + /* LLDnodeAppend(scriptUpdate,&result); */ + SetHdbProperty(result, "sicscommand", setScript); + return result; } + /*--------------------------------------------------------------------------*/ -static void removeNodeFromUpdateList(pHdb node){ - pHdb current = NULL; - int status; - char *objName = NULL; - - objName = GetHipadabaPath(node); - if(objName != NULL){ - removePollObject(poller, objName); - free(objName); - } +static void removeNodeFromUpdateList(pHdb node) +{ + pHdb current = NULL; + int status; + char *objName = NULL; + + objName = GetHipadabaPath(node); + if (objName != NULL) { + removePollObject(poller, objName); + free(objName); + } } + /*-----------------------------------------------------------------------*/ -static void SICSDeleteNodeData(pHdb node){ - pHdb tmp = NULL; +static void SICSDeleteNodeData(pHdb node) +{ + pHdb tmp = NULL; - if(node == NULL){ - return; - } + if (node == NULL) { + return; + } - removeNodeFromUpdateList(node); - while(node->child != NULL){ - tmp = node->child; - node->child = node->child->next; - SICSDeleteNodeData(tmp); - } - if(node->properties != NULL){ - DeleteStringDict(node->properties); - } - DeleteCallbackChain(node); - - if(node->name != NULL){ - free(node->name); - } - ReleaseHdbValue(&node->value); - node->magic = 000000; + removeNodeFromUpdateList(node); + while (node->child != NULL) { + tmp = node->child; + node->child = node->child->next; + SICSDeleteNodeData(tmp); + } + if (node->properties != NULL) { + DeleteStringDict(node->properties); + } + DeleteCallbackChain(node); - free(node); + if (node->name != NULL) { + free(node->name); + } + ReleaseHdbValue(&node->value); + node->magic = 000000; + + free(node); } + /*--------------------------------------------------------------------------*/ -void RemoveSICSPar(pHdb node, void *callData){ - pHdb current = NULL, tmp = NULL; - - if(node == NULL){ - return; - } - - RemoveHdbNodeFromParent(node,NULL); - - SICSDeleteNodeData(node); +void RemoveSICSPar(pHdb node, void *callData) +{ + pHdb current = NULL, tmp = NULL; + + if (node == NULL) { + return; + } + + RemoveHdbNodeFromParent(node, NULL); + + SICSDeleteNodeData(node); } + /*===================== add functions =======================================*/ -pHdb AddSICSHdbPar(pHdb parent, char *name, int priv, hdbValue v){ - pHdb child = NULL; - - child = MakeSICSHdbPar(name,priv,v); - if(child != NULL){ - AddHipadabaChild(parent,child,NULL); - } - return child; +pHdb AddSICSHdbPar(pHdb parent, char *name, int priv, hdbValue v) +{ + pHdb child = NULL; + + child = MakeSICSHdbPar(name, priv, v); + if (child != NULL) { + AddHipadabaChild(parent, child, NULL); + } + return child; } + /*---------------------------------------------------------------------------*/ -pHdb AddSICSHdbROPar(pHdb parent, char *name, hdbValue v){ - pHdb child = NULL; - - child = MakeSICSROPar(name,v); - if(child != NULL){ - AddHipadabaChild(parent,child,NULL); - } - return child; +pHdb AddSICSHdbROPar(pHdb parent, char *name, hdbValue v) +{ + pHdb child = NULL; + + child = MakeSICSROPar(name, v); + if (child != NULL) { + AddHipadabaChild(parent, child, NULL); + } + return child; } + /*--------------------------------------------------------------------------*/ pHdb AddSICSHdbMemPar(pHdb parent, char *name, int priv, - void *data, int datalength, int type, int length){ - pHdb child = NULL; - pHdbCallback pHcb = NULL; - - if(type == HIPINTVARAR || type == HIPFLOATVARAR){ - assert(0); - return NULL; - } - - child = MakeHipadabaNode(name,type,length); - if(child == NULL){ - return NULL; - } + void *data, int datalength, int type, int length) +{ + pHdb child = NULL; + pHdbCallback pHcb = NULL; - pHcb = MakeCheckPermissionCallback(priv); - if(pHcb == NULL){ - DeleteHipadabaNode(child,NULL); - return NULL; - } - AppendHipadabaCallback(child,pHcb); + if (type == HIPINTVARAR || type == HIPFLOATVARAR) { + assert(0); + return NULL; + } - pHcb = MakeMemGenSetCallback(data); - if(pHcb == NULL){ - DeleteHipadabaNode(child,NULL); - return NULL; - } - AppendHipadabaCallback(child,pHcb); - - pHcb = MakeMemGenReadCallback(data); - if(pHcb == NULL){ - DeleteHipadabaNode(child,NULL); - return NULL; - } - AppendHipadabaCallback(child,pHcb); - AddHipadabaChild(parent,child,NULL); + child = MakeHipadabaNode(name, type, length); + if (child == NULL) { + return NULL; + } - return child; + pHcb = MakeCheckPermissionCallback(priv); + if (pHcb == NULL) { + DeleteHipadabaNode(child, NULL); + return NULL; + } + AppendHipadabaCallback(child, pHcb); + + pHcb = MakeMemGenSetCallback(data); + if (pHcb == NULL) { + DeleteHipadabaNode(child, NULL); + return NULL; + } + AppendHipadabaCallback(child, pHcb); + + pHcb = MakeMemGenReadCallback(data); + if (pHcb == NULL) { + DeleteHipadabaNode(child, NULL); + return NULL; + } + AppendHipadabaCallback(child, pHcb); + AddHipadabaChild(parent, child, NULL); + + return child; } + /*==================== access support functions ==============================*/ -pHdb FindHdbParent(char *rootpath, char *relpath, char **namePtr, SConnection *pCon) { +pHdb FindHdbParent(char *rootpath, char *relpath, char **namePtr, + SConnection * pCon) +{ /* for namePtr == NULL, implements also "find node" */ char *element; char buffer[MAX_HDB_PATH]; @@ -1347,35 +1458,38 @@ pHdb FindHdbParent(char *rootpath, char *relpath, char **namePtr, SConnection *p char *slash; pObjectDescriptor pDes; int iret; - - if (relpath[0] == '/' || rootpath == NULL) { /* absolute path */ + + if (relpath[0] == '/' || rootpath == NULL) { /* absolute path */ iret = snprintf(buffer, sizeof buffer, "%s", relpath); } else { iret = snprintf(buffer, sizeof buffer, "%s/%s", rootpath, relpath); } if (iret < 0 || iret >= sizeof(buffer)) { - SCWrite(pCon,"ERROR: path too long",eError); + SCWrite(pCon, "ERROR: path too long", eError); return NULL; } element = buffer; if (strncmp(element, "/sics/", 6) == 0) { /* sics object case */ - slash = strchr(element+6, '/'); - if (slash != NULL) *slash = '\0'; /* split off object name */ + slash = strchr(element + 6, '/'); + if (slash != NULL) + *slash = '\0'; /* split off object name */ - pDes = FindCommandDescriptor(pServ->pSics, element+6); + pDes = FindCommandDescriptor(pServ->pSics, element + 6); if (pDes == NULL) { SCPrintf(pCon, eError, "ERROR: object %s not found", element); return NULL; } node = pDes->parNode; if (node == NULL) { - SCPrintf(pCon, eError, "ERROR: object %s does not use hipadaba", element); + SCPrintf(pCon, eError, "ERROR: object %s does not use hipadaba", + element); return NULL; } - if (slash == NULL) goto nodeFound; + if (slash == NULL) + goto nodeFound; *slash = '/'; - element = slash+1; + element = slash + 1; parent = node; /* parent is sics object, path is relative to it */ } else { @@ -1384,7 +1498,8 @@ pHdb FindHdbParent(char *rootpath, char *relpath, char **namePtr, SConnection *p } while (1) { slash = strchr(element, '/'); - if (slash != NULL) *slash = '\0'; /* split off next path element */ + if (slash != NULL) + *slash = '\0'; /* split off next path element */ if (strcmp(element, "") == 0 || strcmp(element, ".") == 0) { /* cases "//" and "/./" : do not move in tree */ if (slash == NULL) { @@ -1400,48 +1515,55 @@ pHdb FindHdbParent(char *rootpath, char *relpath, char **namePtr, SConnection *p } } if (node == NULL) { - if (namePtr) { /* "find parent" case */ - if (slash != NULL) { /* element is not the last in path */ + if (namePtr) { /* "find parent" case */ + if (slash != NULL) { /* element is not the last in path */ *slash = '/'; - SCPrintf(pCon, eError, "ERROR: parent of %s not found", buffer); + SCPrintf(pCon, eError, "ERROR: parent of %s not found", + buffer); return NULL; } /* the name must be taken from the end of relpath, as element is no longer valid */ *namePtr = relpath + (element - buffer); - return parent; /* parent found, and node does not yet exist */ + return parent; /* parent found, and node does not yet exist */ } /* "find node" case */ - if (slash != NULL) *slash = '/'; + if (slash != NULL) + *slash = '/'; SCPrintf(pCon, eError, "ERROR: node %s not found", buffer); return NULL; } /* node found */ - if (slash == NULL) goto nodeFound; + if (slash == NULL) + goto nodeFound; parent = node; *slash = '/'; element = slash + 1; } } nodeFound: - if (namePtr) { /* "find parent" case */ + if (namePtr) { /* "find parent" case */ *namePtr = node->name; SCPrintf(pCon, eError, "ERROR: node %s exists already", buffer); return NULL; } - return node; /* node found */ + return node; /* node found */ } + /*--------------------------------------------------------------------------*/ -pHdb FindHdbNode(char *rootpath, char *relpath, SConnection *pCon) { +pHdb FindHdbNode(char *rootpath, char *relpath, SConnection * pCon) +{ return FindHdbParent(rootpath, relpath, NULL, pCon); } + /*--------------------------------------------------------------------------*/ -int GetHdbPath(pHdb nodeArg, char *path, size_t pathlen) { +int GetHdbPath(pHdb nodeArg, char *path, size_t pathlen) +{ pHdb node, parent; int len, pos, l; - static char *sics="/sics"; + static char *sics = "/sics"; pObjectDescriptor pDes; - - path[0]='\0'; + + path[0] = '\0'; if (nodeArg == NULL) { return 0; } @@ -1450,392 +1572,420 @@ int GetHdbPath(pHdb nodeArg, char *path, size_t pathlen) { len = 0; for (node = nodeArg; node != NULL && node != root; node = node->mama) { len += strlen(node->name) + 1; - if (len >= pathlen) return 0; /* buffer overflow (recursive path?) */ + if (len >= pathlen) + return 0; /* buffer overflow (recursive path?) */ parent = node; } - + /* check root and add prefix */ - if (parent->mama != root) { /* not anchored in root */ + if (parent->mama != root) { /* not anchored in root */ pDes = FindCommandDescriptor(pServ->pSics, parent->name); if (!pDes) { - return 0; /* not a sics object */ + return 0; /* not a sics object */ } if (pDes->parNode != parent) { /* node named as a sics object, but command is not related to node */ return 0; } - l= strlen(sics); + l = strlen(sics); len += l; - if (len > pathlen) return 0; /* buffer overflow */ + if (len > pathlen) + return 0; /* buffer overflow */ strncpy(path, sics, l); } - + /* build the path backwards */ - path[len]='\0'; + path[len] = '\0'; pos = len; for (node = nodeArg; node != NULL && node != root; node = node->mama) { len = strlen(node->name); pos -= len; - assert(pos>0); - strncpy(path+pos, node->name, len); + assert(pos > 0); + strncpy(path + pos, node->name, len); pos--; - path[pos]='/'; + path[pos] = '/'; } return 1; } + /*--------------------------------------------------------------------------*/ -static int RemoveParNodeCallback(char *name, pDummy object, void *internalID) { - hdbPtrMessage m; - - m.type = killPtr; - m.pPtr = internalID; - if (object->pDescriptor->parNode) { - RecurseCallbackChains(object->pDescriptor->parNode,(pHdbMessage)&m); - } - return 1; +static int RemoveParNodeCallback(char *name, pDummy object, + void *internalID) +{ + hdbPtrMessage m; + + m.type = killPtr; + m.pPtr = internalID; + if (object->pDescriptor->parNode) { + RecurseCallbackChains(object->pDescriptor->parNode, (pHdbMessage) & m); + } + return 1; } + /*--------------------------------------------------------------------------*/ -void RemoveSICSInternalCallback(void *internalID) { - hdbPtrMessage m; - - m.type = killPtr; - m.pPtr = internalID; - RecurseCallbackChains(GetHipadabaRoot(),(pHdbMessage)&m); - ForEachCommand(RemoveParNodeCallback, internalID); +void RemoveSICSInternalCallback(void *internalID) +{ + hdbPtrMessage m; + + m.type = killPtr; + m.pPtr = internalID; + RecurseCallbackChains(GetHipadabaRoot(), (pHdbMessage) & m); + ForEachCommand(RemoveParNodeCallback, internalID); } + /*--------------------------------------------------------------------------*/ -int SICSHdbGetPar(void *obj, SConnection *pCon, char *path, hdbValue *v){ - pHdb par = NULL; - int status; - char buffer[256]; - pDummy pDum; - - pDum = (pDummy)obj; - if(pDum == NULL || pDum->pDescriptor->parNode == NULL){ - if(pCon != NULL){ - snprintf(buffer,255,"ERROR: parameter %s not found", path); - SCWrite(pCon,buffer,eError); - } - return SICSNOPAR; - } - - par = GetHipadabaNode(pDum->pDescriptor->parNode,path); - if(par == NULL){ - if(pCon != NULL){ - snprintf(buffer,255,"ERROR: parameter %s not found", path); - SCWrite(pCon,buffer,eError); - } - return SICSNOPAR; - } - - status = GetHipadabaPar(par,v,pCon); - if(status < 0){ - return status; - } - return 1; +int SICSHdbGetPar(void *obj, SConnection * pCon, char *path, hdbValue * v) +{ + pHdb par = NULL; + int status; + char buffer[256]; + pDummy pDum; + + pDum = (pDummy) obj; + if (pDum == NULL || pDum->pDescriptor->parNode == NULL) { + if (pCon != NULL) { + snprintf(buffer, 255, "ERROR: parameter %s not found", path); + SCWrite(pCon, buffer, eError); + } + return SICSNOPAR; + } + + par = GetHipadabaNode(pDum->pDescriptor->parNode, path); + if (par == NULL) { + if (pCon != NULL) { + snprintf(buffer, 255, "ERROR: parameter %s not found", path); + SCWrite(pCon, buffer, eError); + } + return SICSNOPAR; + } + + status = GetHipadabaPar(par, v, pCon); + if (status < 0) { + return status; + } + return 1; } + /*--------------------------------------------------------------------------*/ -int SICSHdbUpdatePar(void *obj, SConnection *pCon, char *path, hdbValue v){ - pHdb par = NULL; - int status; - char buffer[256]; - pDummy pDum; - - pDum = (pDummy)obj; - if(pDum == NULL || pDum->pDescriptor->parNode == NULL){ - if(pCon != NULL){ - snprintf(buffer,255,"ERROR: parameter %s not found", path); - SCWrite(pCon,buffer,eError); - } - return SICSNOPAR; - } - - par = GetHipadabaNode(pDum->pDescriptor->parNode,path); - if(par == NULL){ - if(pCon != NULL){ - snprintf(buffer,255,"ERROR: parameter %s not found", path); - SCWrite(pCon,buffer,eError); - } - return SICSNOPAR; - } - - status = UpdateHipadabaPar(par,v,pCon); - if(status < 0){ - return status; - } - return 1; +int SICSHdbUpdatePar(void *obj, SConnection * pCon, char *path, hdbValue v) +{ + pHdb par = NULL; + int status; + char buffer[256]; + pDummy pDum; + + pDum = (pDummy) obj; + if (pDum == NULL || pDum->pDescriptor->parNode == NULL) { + if (pCon != NULL) { + snprintf(buffer, 255, "ERROR: parameter %s not found", path); + SCWrite(pCon, buffer, eError); + } + return SICSNOPAR; + } + + par = GetHipadabaNode(pDum->pDescriptor->parNode, path); + if (par == NULL) { + if (pCon != NULL) { + snprintf(buffer, 255, "ERROR: parameter %s not found", path); + SCWrite(pCon, buffer, eError); + } + return SICSNOPAR; + } + + status = UpdateHipadabaPar(par, v, pCon); + if (status < 0) { + return status; + } + return 1; } + /*--------------------------------------------------------------------------*/ -int SICSHdbSetPar(void *obj, SConnection *pCon, char *path, hdbValue v){ - pHdb par = NULL; - int status; - char buffer[256]; - pDummy pDum; - - pDum = (pDummy)obj; - if(pDum == NULL || pDum->pDescriptor->parNode == NULL){ - if(pCon != NULL){ - snprintf(buffer,255,"ERROR: parameter %s not found", path); - SCWrite(pCon,buffer,eError); - } - return SICSNOPAR; - } - - par = GetHipadabaNode(pDum->pDescriptor->parNode,path); - if(par == NULL){ - if(pCon != NULL){ - snprintf(buffer,255,"ERROR: parameter %s not found", path); - SCWrite(pCon,buffer,eError); - } - return SICSNOPAR; - } - - status = SetHipadabaPar(par,v,pCon); - if(status <= 0){ - return status; - } - return 1; +int SICSHdbSetPar(void *obj, SConnection * pCon, char *path, hdbValue v) +{ + pHdb par = NULL; + int status; + char buffer[256]; + pDummy pDum; + + pDum = (pDummy) obj; + if (pDum == NULL || pDum->pDescriptor->parNode == NULL) { + if (pCon != NULL) { + snprintf(buffer, 255, "ERROR: parameter %s not found", path); + SCWrite(pCon, buffer, eError); + } + return SICSNOPAR; + } + + par = GetHipadabaNode(pDum->pDescriptor->parNode, path); + if (par == NULL) { + if (pCon != NULL) { + snprintf(buffer, 255, "ERROR: parameter %s not found", path); + SCWrite(pCon, buffer, eError); + } + return SICSNOPAR; + } + + status = SetHipadabaPar(par, v, pCon); + if (status <= 0) { + return status; + } + return 1; } + /*---------------------------------------------------------------------------*/ -int InstallSICSNotify(pHdb node, SConnection *pCon, int id, int recurse){ - pHdb currentChild = NULL; - pHdbCallback noty = NULL; - pHdbCallback treeChange = NULL; - - treeChange = MakeTreeChangeCallback(pCon,id); - noty = MakeNotifyCallback(pCon,id); - if(noty == NULL || treeChange == NULL){ - SCWrite(pCon,"ERROR: out of memory installing callback", eError); - return 0; - } - AppendHipadabaCallback(node, noty); - AppendHipadabaCallback(node, treeChange); - - if(recurse == 1){ - currentChild = node->child; - while(currentChild != NULL){ - InstallSICSNotify(currentChild,pCon,id,recurse); - currentChild = currentChild->next; - } - } - return 1; -} -/*---------------------------------------------------------------------------*/ -void RemoveConnectionCallbacks(pHdb root, SConnection *pCon){ - hdbPtrMessage dsm; - - dsm.type = killPtr; - dsm.pPtr = pCon; - RecurseCallbackChains(root,(pHdbMessage)&dsm); -} -/*---------------------------------------------------------------------------*/ -int ProcessSICSHdbPar(pHdb root, SConnection *pCon, - char *printPrefix, int argc, char *argv[]){ - hdbValue input; - pHdb parNode = NULL; - pDynString parData = NULL; - char error[512]; - int i, status; - - assert(root != NULL && pCon != NULL); - - if(argc < 1){ - SCWrite(pCon,"ERROR: no parameter to treat specified",eError); - return -1; - } - - parNode = GetHipadabaNode(root,argv[0]); - if(parNode == NULL){ - /* no error reporting here, upper level code might wish to continue - * processing commands after having tested for parameters. - */ - return -1; - } - - if(argc > 1) { - /* - * setting the value is attempted. - */ - memset(&input,0,sizeof(hdbValue)); - input.dataType = parNode->value.dataType; - copyHdbValue(&parNode->value,&input); - parData = CreateDynString(64,64); - if(parData == NULL){ - SCWrite(pCon,"ERROR: out of memory processing parameter",eError); - return 0; - } - for(i = 1; i < argc; i++){ - DynStringConcat(parData," "); - DynStringConcat(parData, argv[i]); - } - strcpy(error,"ERROR: "); - if(!readHdbValue(&input, GetCharArray(parData), - error+7,512-7)){ - SCWrite(pCon,error, eError); - return 0; - } - DeleteDynString(parData); - status = SetHipadabaPar(parNode,input,pCon); - ReleaseHdbValue(&input); - if(status == 1){ - /* SCSendOK(pCon); do not send OK. this has to be done by the callback */ - SCparChange(pCon); - } - return status; - } else { - /* - * reading is in demand - */ - status = GetHipadabaPar(parNode,&input, pCon); - if(status != 1){ - return 0; - } - parData = formatValue(input, parNode); - if(parData == NULL){ - SCWrite(pCon,"ERROR: out of memory reading parameter data",eError); - return 0; - } - DynStringInsert(parData," = ", 0); - DynStringInsert(parData,argv[0],0); - if(printPrefix != NULL){ - DynStringInsert(parData,printPrefix,0); - } - SCWrite(pCon,GetCharArray(parData),eValue); - DeleteDynString(parData); - ReleaseHdbValue(&input); - return 1; - } -} -/*--------------------------------------------------------------------------*/ -void PrintSICSParList(pHdb node, SConnection *pCon, char *prefix){ - char childPrefix[1024]; - pHdb child = NULL; - pDynString value = NULL; - hdbValue v; - - child = node->child; - while(child != NULL){ - if(child->value.dataType != HIPNONE){ - GetHipadabaPar(child,&v,pCon); - value = formatValue(child->value, child); - if(value != NULL){ - SCPrintf(pCon,eValue,"%s%s = %s", prefix, child->name, - GetCharArray(value)); - DeleteDynString(value); - } - } - if(child->child != NULL){ - strncpy(childPrefix,prefix,1024); - strncat(childPrefix,child->name, 1024); - strncat(childPrefix,"/",1024); - PrintSICSParList(child, pCon,prefix); - } - child = child->next; - } -} -/*---------------------------------------------------------------------------*/ -void SaveSICSHipadaba(FILE *fd, pHdb node, char *prefix){ - pHdb currentChild = NULL; - pDynString data = NULL; - hdbValue v; - +int InstallSICSNotify(pHdb node, SConnection * pCon, int id, int recurse) +{ + pHdb currentChild = NULL; + pHdbCallback noty = NULL; + pHdbCallback treeChange = NULL; + + treeChange = MakeTreeChangeCallback(pCon, id); + noty = MakeNotifyCallback(pCon, id); + if (noty == NULL || treeChange == NULL) { + SCWrite(pCon, "ERROR: out of memory installing callback", eError); + return 0; + } + AppendHipadabaCallback(node, noty); + AppendHipadabaCallback(node, treeChange); + + if (recurse == 1) { currentChild = node->child; - while(currentChild != NULL){ - if(currentChild->value.dataType != HIPNONE && !isSICSHdbRO(currentChild)){ - data = formatValue(currentChild->value, currentChild); - if(data != NULL){ - fprintf(fd,"%s%s %s\n", prefix, currentChild->name, GetCharArray(data)); - DeleteDynString(data); - } - } - if(currentChild->child != NULL){ - /* - * build a new prefix string and recurse - */ - data = CreateDynString(64,64); - if(data != NULL){ - DynStringCopy(data,prefix); - DynStringConcat(data,currentChild->name); - DynStringConcat(data,"/"); - SaveSICSHipadaba(fd,currentChild,GetCharArray(data)); - DeleteDynString(data); - } - } - currentChild = currentChild->next; + while (currentChild != NULL) { + InstallSICSNotify(currentChild, pCon, id, recurse); + currentChild = currentChild->next; } + } + return 1; } + +/*---------------------------------------------------------------------------*/ +void RemoveConnectionCallbacks(pHdb root, SConnection * pCon) +{ + hdbPtrMessage dsm; + + dsm.type = killPtr; + dsm.pPtr = pCon; + RecurseCallbackChains(root, (pHdbMessage) & dsm); +} + +/*---------------------------------------------------------------------------*/ +int ProcessSICSHdbPar(pHdb root, SConnection * pCon, + char *printPrefix, int argc, char *argv[]) +{ + hdbValue input; + pHdb parNode = NULL; + pDynString parData = NULL; + char error[512]; + int i, status; + + assert(root != NULL && pCon != NULL); + + if (argc < 1) { + SCWrite(pCon, "ERROR: no parameter to treat specified", eError); + return -1; + } + + parNode = GetHipadabaNode(root, argv[0]); + if (parNode == NULL) { + /* no error reporting here, upper level code might wish to continue + * processing commands after having tested for parameters. + */ + return -1; + } + + if (argc > 1) { + /* + * setting the value is attempted. + */ + memset(&input, 0, sizeof(hdbValue)); + input.dataType = parNode->value.dataType; + copyHdbValue(&parNode->value, &input); + parData = CreateDynString(64, 64); + if (parData == NULL) { + SCWrite(pCon, "ERROR: out of memory processing parameter", eError); + return 0; + } + for (i = 1; i < argc; i++) { + DynStringConcat(parData, " "); + DynStringConcat(parData, argv[i]); + } + strcpy(error, "ERROR: "); + if (!readHdbValue(&input, GetCharArray(parData), error + 7, 512 - 7)) { + SCWrite(pCon, error, eError); + return 0; + } + DeleteDynString(parData); + status = SetHipadabaPar(parNode, input, pCon); + ReleaseHdbValue(&input); + if (status == 1) { + /* SCSendOK(pCon); do not send OK. this has to be done by the callback */ + SCparChange(pCon); + } + return status; + } else { + /* + * reading is in demand + */ + status = GetHipadabaPar(parNode, &input, pCon); + if (status != 1) { + return 0; + } + parData = formatValue(input, parNode); + if (parData == NULL) { + SCWrite(pCon, "ERROR: out of memory reading parameter data", eError); + return 0; + } + DynStringInsert(parData, " = ", 0); + DynStringInsert(parData, argv[0], 0); + if (printPrefix != NULL) { + DynStringInsert(parData, printPrefix, 0); + } + SCWrite(pCon, GetCharArray(parData), eValue); + DeleteDynString(parData); + ReleaseHdbValue(&input); + return 1; + } +} + +/*--------------------------------------------------------------------------*/ +void PrintSICSParList(pHdb node, SConnection * pCon, char *prefix) +{ + char childPrefix[1024]; + pHdb child = NULL; + pDynString value = NULL; + hdbValue v; + + child = node->child; + while (child != NULL) { + if (child->value.dataType != HIPNONE) { + GetHipadabaPar(child, &v, pCon); + value = formatValue(child->value, child); + if (value != NULL) { + SCPrintf(pCon, eValue, "%s%s = %s", prefix, child->name, + GetCharArray(value)); + DeleteDynString(value); + } + } + if (child->child != NULL) { + strncpy(childPrefix, prefix, 1024); + strncat(childPrefix, child->name, 1024); + strncat(childPrefix, "/", 1024); + PrintSICSParList(child, pCon, prefix); + } + child = child->next; + } +} + +/*---------------------------------------------------------------------------*/ +void SaveSICSHipadaba(FILE * fd, pHdb node, char *prefix) +{ + pHdb currentChild = NULL; + pDynString data = NULL; + hdbValue v; + + currentChild = node->child; + while (currentChild != NULL) { + if (currentChild->value.dataType != HIPNONE + && !isSICSHdbRO(currentChild)) { + data = formatValue(currentChild->value, currentChild); + if (data != NULL) { + fprintf(fd, "%s%s %s\n", prefix, currentChild->name, + GetCharArray(data)); + DeleteDynString(data); + } + } + if (currentChild->child != NULL) { + /* + * build a new prefix string and recurse + */ + data = CreateDynString(64, 64); + if (data != NULL) { + DynStringCopy(data, prefix); + DynStringConcat(data, currentChild->name); + DynStringConcat(data, "/"); + SaveSICSHipadaba(fd, currentChild, GetCharArray(data)); + DeleteDynString(data); + } + } + currentChild = currentChild->next; + } +} + /*================ value helpers ============================================*/ -pDynString formatValue(hdbValue v, pHdb node){ +pDynString formatValue(hdbValue v, pHdb node) +{ pDynString result = NULL; int i; char number[30]; char format[16]; - - result = CreateDynString(64,64); - if(result == NULL){ + + result = CreateDynString(64, 64); + if (result == NULL) { return NULL; } - switch(v.dataType){ - case HIPNONE: - break; - case HIPINT: - snprintf(number,30,"%d", v.v.intValue); - DynStringCopy(result,number); - break; - case HIPFLOAT: - if (GetHdbProperty(node, "fmt", format, sizeof format -1)) { - snprintf(number,30,format, v.v.doubleValue); - } else { - snprintf(number,30,"%.6g", v.v.doubleValue); - } - DynStringCopy(result,number); - break; - case HIPTEXT: - DynStringCopy(result,v.v.text); - break; - case HIPINTAR: - case HIPINTVARAR: - for(i = 0; i < v.arrayLength; i++){ - snprintf(number,30," %d", v.v.intArray[i]); - DynStringConcat(result,number); - } - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - if (GetHdbProperty(node, "fmt", format+1, sizeof format -2)) { - format[0]=' '; - } else { - strcpy(format, " %.6g"); - } - for(i = 0; i < v.arrayLength; i++){ - snprintf(number,30,format, v.v.floatArray[i]); - DynStringConcat(result,number); - } - break; - case HIPFUNC: - DynStringConcat(result,"FUNCTION"); - break; - case HIPOBJ: - DynStringConcat(result,"OBJECT"); - break; + switch (v.dataType) { + case HIPNONE: + break; + case HIPINT: + snprintf(number, 30, "%d", v.v.intValue); + DynStringCopy(result, number); + break; + case HIPFLOAT: + if (GetHdbProperty(node, "fmt", format, sizeof format - 1)) { + snprintf(number, 30, format, v.v.doubleValue); + } else { + snprintf(number, 30, "%.6g", v.v.doubleValue); + } + DynStringCopy(result, number); + break; + case HIPTEXT: + DynStringCopy(result, v.v.text); + break; + case HIPINTAR: + case HIPINTVARAR: + for (i = 0; i < v.arrayLength; i++) { + snprintf(number, 30, " %d", v.v.intArray[i]); + DynStringConcat(result, number); + } + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + if (GetHdbProperty(node, "fmt", format + 1, sizeof format - 2)) { + format[0] = ' '; + } else { + strcpy(format, " %.6g"); + } + for (i = 0; i < v.arrayLength; i++) { + snprintf(number, 30, format, v.v.floatArray[i]); + DynStringConcat(result, number); + } + break; + case HIPFUNC: + DynStringConcat(result, "FUNCTION"); + break; + case HIPOBJ: + DynStringConcat(result, "OBJECT"); + break; } return result; } + /*-------------------------------------------------------------------*/ -static char *getNextHdbNumber(char *pStart, char pNumber[80]){ +static char *getNextHdbNumber(char *pStart, char pNumber[80]) +{ int charCount = 0; pNumber[0] = '\0'; /* advance to first digit */ - while(isspace(*pStart) && *pStart != '\0'){ + while (isspace(*pStart) && *pStart != '\0') { pStart++; } - if(*pStart == '\0'){ + if (*pStart == '\0') { return NULL; } /* copy */ - while(!isspace(*pStart) && *pStart != '\0' && charCount < 78){ + while (!isspace(*pStart) && *pStart != '\0' && charCount < 78) { pNumber[charCount] = *pStart; pStart++; charCount++; @@ -1843,1414 +1993,1496 @@ static char *getNextHdbNumber(char *pStart, char pNumber[80]){ pNumber[charCount] = '\0'; return pStart; } + /*---------------------------------------------------------------------------------*/ -static int adjustDataLength(hdbValue *v, char *data){ - char number[80]; - int count = 0; - char *pPtr = NULL; - - pPtr = data; - while((pPtr = getNextHdbNumber(pPtr,number)) != NULL){ - count++; +static int adjustDataLength(hdbValue * v, char *data) +{ + char number[80]; + int count = 0; + char *pPtr = NULL; + + pPtr = data; + while ((pPtr = getNextHdbNumber(pPtr, number)) != NULL) { + count++; + } + if (count != v->arrayLength) { + v->arrayLength = count; + if (v->dataType == HIPINTVARAR) { + if (v->v.intArray != NULL) { + free(v->v.intArray); + } + v->v.intArray = malloc(count * sizeof(int)); + if (v->v.intArray == NULL) { + return 0; + } + memset(v->v.intArray, 0, count * sizeof(int)); } - if(count != v->arrayLength){ - v->arrayLength = count; - if(v->dataType == HIPINTVARAR){ - if(v->v.intArray != NULL){ - free(v->v.intArray); - } - v->v.intArray = malloc(count*sizeof(int)); - if(v->v.intArray == NULL){ - return 0; - } - memset(v->v.intArray,0,count*sizeof(int)); - } - if(v->dataType == HIPFLOATVARAR){ - if(v->v.floatArray != NULL){ - free(v->v.floatArray); - } - v->v.floatArray = malloc(count*sizeof(double)); - if(v->v.floatArray == NULL){ - return 0; - } - memset(v->v.floatArray,0,count*sizeof(double)); - } + if (v->dataType == HIPFLOATVARAR) { + if (v->v.floatArray != NULL) { + free(v->v.floatArray); + } + v->v.floatArray = malloc(count * sizeof(double)); + if (v->v.floatArray == NULL) { + return 0; + } + memset(v->v.floatArray, 0, count * sizeof(double)); } - return 1; + } + return 1; } + /*---------------------------------------------------------------------------------*/ -int readHdbValue(hdbValue *v, char *data, char *error, int errlen){ - int i, status; - int lValue; - double dValue; - char number[80]; - char *pPtr = NULL; - void *objData; - - switch(v->dataType){ - case HIPNONE: - break; - case HIPINT: - getNextHdbNumber(data,number); - status = sscanf(number,"%d", &v->v.intValue); - if(status != 1){ - snprintf(error,errlen,"Failed to convert %s to integer", - data); - return 0; - } - break; - case HIPFLOAT: - getNextHdbNumber(data,number); - status = sscanf(number,"%lf", &v->v.doubleValue); - if(status != 1){ - snprintf(error,errlen,"Failed to convert %s to double", - data); - return 0; - } - break; - case HIPTEXT: - if(v->v.text != NULL){ - free(v->v.text); - } - v->v.text = strdup(data); - break; - case HIPINTVARAR: - if(!adjustDataLength(v,data)){ - snprintf(error,errlen,"Out of memory allocating variable length data"); - return 0; - } - case HIPINTAR: - for(i = 0; i < v->arrayLength; i++){ - data = getNextHdbNumber(data,number); - if(data == NULL){ - snprintf(error,errlen,"Not enough values to parse, current index %d", - i); - return 0; - } - status = sscanf(number,"%d", &lValue); - if(status != 1){ - snprintf(error,errlen,"Failed to convert %s to integer", - data); - return 0; - } - v->v.intArray[i] = lValue; - } - break; - case HIPFLOATVARAR: - if(!adjustDataLength(v,data)){ - snprintf(error,errlen,"Out of memory allocating variable length data"); - return 0; - } - case HIPFLOATAR: - for(i = 0; i < v->arrayLength; i++){ - data = getNextHdbNumber(data,number); - if(data == NULL){ - snprintf(error,errlen,"Not enough values to parse, current index %d", - i); - return 0; - } - status = sscanf(number,"%lf", &dValue); - if(status != 1){ - snprintf(error,errlen,"Failed to convert %s to double", - data); - return 0; - } - v->v.floatArray[i] = dValue; - } - break; - case HIPOBJ: - break; - case HIPFUNC: - break; - default: - assert(0); - break; - } - return 1; +int readHdbValue(hdbValue * v, char *data, char *error, int errlen) +{ + int i, status; + int lValue; + double dValue; + char number[80]; + char *pPtr = NULL; + void *objData; + + switch (v->dataType) { + case HIPNONE: + break; + case HIPINT: + getNextHdbNumber(data, number); + status = sscanf(number, "%d", &v->v.intValue); + if (status != 1) { + snprintf(error, errlen, "Failed to convert %s to integer", data); + return 0; + } + break; + case HIPFLOAT: + getNextHdbNumber(data, number); + status = sscanf(number, "%lf", &v->v.doubleValue); + if (status != 1) { + snprintf(error, errlen, "Failed to convert %s to double", data); + return 0; + } + break; + case HIPTEXT: + if (v->v.text != NULL) { + free(v->v.text); + } + v->v.text = strdup(data); + break; + case HIPINTVARAR: + if (!adjustDataLength(v, data)) { + snprintf(error, errlen, + "Out of memory allocating variable length data"); + return 0; + } + case HIPINTAR: + for (i = 0; i < v->arrayLength; i++) { + data = getNextHdbNumber(data, number); + if (data == NULL) { + snprintf(error, errlen, + "Not enough values to parse, current index %d", i); + return 0; + } + status = sscanf(number, "%d", &lValue); + if (status != 1) { + snprintf(error, errlen, "Failed to convert %s to integer", data); + return 0; + } + v->v.intArray[i] = lValue; + } + break; + case HIPFLOATVARAR: + if (!adjustDataLength(v, data)) { + snprintf(error, errlen, + "Out of memory allocating variable length data"); + return 0; + } + case HIPFLOATAR: + for (i = 0; i < v->arrayLength; i++) { + data = getNextHdbNumber(data, number); + if (data == NULL) { + snprintf(error, errlen, + "Not enough values to parse, current index %d", i); + return 0; + } + status = sscanf(number, "%lf", &dValue); + if (status != 1) { + snprintf(error, errlen, "Failed to convert %s to double", data); + return 0; + } + v->v.floatArray[i] = dValue; + } + break; + case HIPOBJ: + break; + case HIPFUNC: + break; + default: + assert(0); + break; + } + return 1; } + /*-------------------------------------------------------------------------*/ -hdbValue MakeSICSFunc(SICSOBJFunc func) { - return MakeHdbFunc((voidFunc *)func); +hdbValue MakeSICSFunc(SICSOBJFunc func) +{ + return MakeHdbFunc((voidFunc *) func); } + /*================ interpreter interface ==================================*/ -pHdb GetHipadabaRoot(){ - return root; +pHdb GetHipadabaRoot() +{ + return root; } -/*-------------------------------------------------------------------------*/ -static char *hdbTypes[] = {"none", - "int", - "float", - "text", - "intar", - "floatar", - "intvarar", - "floatvarar", - "object", - "func", - NULL}; -/*-------------------------------------------------------------------------*/ -int convertHdbType(char *text){ - int type; - type = 0; - while(hdbTypes[type] != NULL){ - if(strcmp(hdbTypes[type], text) == 0){ - break; - } - type++; - } - type--; /* we start counting at -1 */ - return type; -} /*-------------------------------------------------------------------------*/ -static char *hdbTypeToText(int type){ - return hdbTypes[type+1]; +static char *hdbTypes[] = { "none", + "int", + "float", + "text", + "intar", + "floatar", + "intvarar", + "floatvarar", + "object", + "func", + NULL +}; + +/*-------------------------------------------------------------------------*/ +int convertHdbType(char *text) +{ + int type; + + type = 0; + while (hdbTypes[type] != NULL) { + if (strcmp(hdbTypes[type], text) == 0) { + break; + } + type++; + } + type--; /* we start counting at -1 */ + return type; } + +/*-------------------------------------------------------------------------*/ +static char *hdbTypeToText(int type) +{ + return hdbTypes[type + 1]; +} + /*--------------------------------------------------------------------------*/ -static int MakeHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - int type = 0, i, length = 0, priv = -1; - char *name = NULL; - pHdb parent = NULL; - pHdb child = NULL; - char buffer[512], buffer2[512]; - hdbValue val; - - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - if(argc < 4) { - SCWrite(pCon,"ERROR: not enough arguments to MakeHdbNode",eError); - return 0; - } - - /* - * convert privilege - */ - priv = decodeSICSPriv(argv[2]); - /* - * convert datatype - */ - strtolower(argv[3]); - type = convertHdbType(argv[3]); - if(type > HIPFLOATVARAR){ - SCWrite(pCon, - "ERROR: invalid type requested: none, int, float, text, intar, floatar, intvarar, floatvarar supported", - eError); - return 0; - } - if(type >= HIPINTAR){ - if( argc < 5){ - SCWrite(pCon,"ERROR: array length missing for array data type", - eError); - return 0; - } else { - length = atoi(argv[3]); - } - } +static int MakeHdbNode(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int type = 0, i, length = 0, priv = -1; + char *name = NULL; + pHdb parent = NULL; + pHdb child = NULL; + char buffer[512], buffer2[512]; + hdbValue val; - parent = FindHdbParent(NULL, argv[1], &name, pCon); - if (parent == NULL) { - return 0; /* error messages written inside FindHdbParent */ - } - if(type != HIPNONE){ - val = makeHdbValue(type,length); - child = MakeSICSHdbPar(name, priv, val); - ReleaseHdbValue(&val); - } else { - child = MakeHipadabaNode(name,type,length); - } - if(child == NULL){ - SCWrite(pCon,"ERROR: out of memory creating node",eError); - return 0; - } - - AddHipadabaChild(parent,child,pCon); - SCSendOK(pCon); - return 1; -} -/*--------------------------------------------------------------------------*/ -static int MakeHdbScriptNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - int type = 0, i, length = 0; - char *name = NULL; - pHdb parent = NULL; - pHdb child = NULL; - pHdb current = NULL; - char *urgv[] = {"5", NULL}; - char driver[] = {"hdb"}; - char buffer[512], buffer2[512]; - - - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - if(argc < 5) { - SCWrite(pCon,"ERROR: not enough arguments to MakeHdbNode",eError); - return 0; - } - - /* - * convert datatype - */ - strtolower(argv[4]); - type = convertHdbType(argv[4]); - if(type >= 7){ - SCWrite(pCon, - "ERROR: invalid type requested: none, int, float, text, intar, floatar, intvarar, floatvarar supported", - eError); - return 0; - } - if(type > 2){ - if( argc < 6){ - SCWrite(pCon,"ERROR: array length missing for array data type", - eError); - return 0; - } else { - length = atoi(argv[5]); - } - } - - parent = FindHdbParent(NULL, argv[1], &name, pCon); - if (parent == NULL) { - return 0; /* error messages written inside FindHdbParent */ - } - child = MakeSICSScriptPar(name, argv[3], argv[2], - makeHdbValue(type,length)); - if(child == NULL){ - SCWrite(pCon,"ERROR: out of memory creating node",eError); - return 0; - } - - AddHipadabaChild(parent,child,pCon); - /* - * have it polled automatically - */ - addPollObject(poller,pCon, GetHipadabaPath(child),driver,1,urgv); - - SCSendOK(pCon); - return 1; -} -/*------------------------------------------------------------------------------*/ -static int isNodeProtected(pHdb node){ - pHdb current = NULL; - - if(node->protected == 1){ - return 1; - } - current = node->child; - while(current != NULL){ - if(isNodeProtected(current)){ - return 1; - } - current = current->next; - } - + if (!SCMatchRights(pCon, usMugger)) { return 0; -} -/*-----------------------------------------------------------------------------------------*/ -static int DeleteHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb killNode = NULL; - - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - if(argc < 2){ - SCWrite(pCon,"ERROR: need path to node to delete",eError); - return 0; - } - killNode = FindHdbNode(NULL, argv[1], pCon); - if(killNode == NULL){ - SCWrite(pCon,"ERROR: node to delete not found",eError); - return 0; - } - if(isNodeProtected(killNode)){ - SCWrite(pCon,"ERROR: this node or one of its children is protected", - eError); - return 0; - } - - RemoveSICSPar(killNode, pCon); - SCSendOK(pCon); - return 1; -} -/*---------------------------------------------------------------------------*/ -static int SetHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - hdbValue newValue; - pDynString parData = NULL; - char error[512]; - int i, status; - - if(!SCMatchRights(pCon,usUser)){ - return 0; - } + } - if(argc < 3) { - SCWrite(pCon,"ERROR: insufficient number of arguments to SetHdbNode", + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough arguments to MakeHdbNode", eError); + return 0; + } + + /* + * convert privilege + */ + priv = decodeSICSPriv(argv[2]); + /* + * convert datatype + */ + strtolower(argv[3]); + type = convertHdbType(argv[3]); + if (type > HIPFLOATVARAR) { + SCWrite(pCon, + "ERROR: invalid type requested: none, int, float, text, intar, floatar, intvarar, floatvarar supported", eError); - return 0; - } - - - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - return 0; + return 0; + } + if (type >= HIPINTAR) { + if (argc < 5) { + SCWrite(pCon, "ERROR: array length missing for array data type", + eError); + return 0; + } else { + length = atoi(argv[3]); } - if(!cloneHdbValue(&targetNode->value,&newValue)){ - SCWrite(pCon,"ERROR: out of memory cloning node", + } + + parent = FindHdbParent(NULL, argv[1], &name, pCon); + if (parent == NULL) { + return 0; /* error messages written inside FindHdbParent */ + } + if (type != HIPNONE) { + val = makeHdbValue(type, length); + child = MakeSICSHdbPar(name, priv, val); + ReleaseHdbValue(&val); + } else { + child = MakeHipadabaNode(name, type, length); + } + if (child == NULL) { + SCWrite(pCon, "ERROR: out of memory creating node", eError); + return 0; + } + + AddHipadabaChild(parent, child, pCon); + SCSendOK(pCon); + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int MakeHdbScriptNode(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + int type = 0, i, length = 0; + char *name = NULL; + pHdb parent = NULL; + pHdb child = NULL; + pHdb current = NULL; + char *urgv[] = { "5", NULL }; + char driver[] = { "hdb" }; + char buffer[512], buffer2[512]; + + + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + if (argc < 5) { + SCWrite(pCon, "ERROR: not enough arguments to MakeHdbNode", eError); + return 0; + } + + /* + * convert datatype + */ + strtolower(argv[4]); + type = convertHdbType(argv[4]); + if (type >= 7) { + SCWrite(pCon, + "ERROR: invalid type requested: none, int, float, text, intar, floatar, intvarar, floatvarar supported", eError); - return 0; + return 0; + } + if (type > 2) { + if (argc < 6) { + SCWrite(pCon, "ERROR: array length missing for array data type", + eError); + return 0; + } else { + length = atoi(argv[5]); } - parData = CreateDynString(64,64); - if(parData == NULL){ - SCWrite(pCon,"ERROR: out of memory reading parameter",eError); - return 0; + } + + parent = FindHdbParent(NULL, argv[1], &name, pCon); + if (parent == NULL) { + return 0; /* error messages written inside FindHdbParent */ + } + child = MakeSICSScriptPar(name, argv[3], argv[2], + makeHdbValue(type, length)); + if (child == NULL) { + SCWrite(pCon, "ERROR: out of memory creating node", eError); + return 0; + } + + AddHipadabaChild(parent, child, pCon); + /* + * have it polled automatically + */ + addPollObject(poller, pCon, GetHipadabaPath(child), driver, 1, urgv); + + SCSendOK(pCon); + return 1; +} + +/*------------------------------------------------------------------------------*/ +static int isNodeProtected(pHdb node) +{ + pHdb current = NULL; + + if (node->protected == 1) { + return 1; + } + current = node->child; + while (current != NULL) { + if (isNodeProtected(current)) { + return 1; } - DynStringConcat(parData, argv[2]); - for(i = 3; i < argc; i++){ - DynStringConcat(parData," "); - DynStringConcat(parData, argv[i]); + current = current->next; + } + + return 0; +} + +/*-----------------------------------------------------------------------------------------*/ +static int DeleteHdbNode(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb killNode = NULL; + + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + if (argc < 2) { + SCWrite(pCon, "ERROR: need path to node to delete", eError); + return 0; + } + killNode = FindHdbNode(NULL, argv[1], pCon); + if (killNode == NULL) { + SCWrite(pCon, "ERROR: node to delete not found", eError); + return 0; + } + if (isNodeProtected(killNode)) { + SCWrite(pCon, "ERROR: this node or one of its children is protected", + eError); + return 0; + } + + RemoveSICSPar(killNode, pCon); + SCSendOK(pCon); + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int SetHdbNode(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHdb targetNode = NULL; + hdbValue newValue; + pDynString parData = NULL; + char error[512]; + int i, status; + + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficient number of arguments to SetHdbNode", + eError); + return 0; + } + + + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + return 0; + } + if (!cloneHdbValue(&targetNode->value, &newValue)) { + SCWrite(pCon, "ERROR: out of memory cloning node", eError); + return 0; + } + parData = CreateDynString(64, 64); + if (parData == NULL) { + SCWrite(pCon, "ERROR: out of memory reading parameter", eError); + return 0; + } + DynStringConcat(parData, argv[2]); + for (i = 3; i < argc; i++) { + DynStringConcat(parData, " "); + DynStringConcat(parData, argv[i]); + } + strcpy(error, "ERROR: "); + if (!readHdbValue(&newValue, GetCharArray(parData), error + 7, 512 - 7)) { + SCWrite(pCon, error, eError); + return 0; + } + DeleteDynString(parData); + status = SetHipadabaPar(targetNode, newValue, pCon); + ReleaseHdbValue(&newValue); + if (status == 1) { + /* SCSendOK(pCon); sending ok has to be done by the callback. */ + } + return status; +} + +/*---------------------------------------------------------------------------*/ +static int UpdateHdbNode(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb targetNode = NULL; + hdbValue newValue; + pDynString parData = NULL; + char error[512]; + int i, status; + + /* + if(!SCMatchRights(pCon,usUser)){ + return 0; + } + */ + + if (argc < 2) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to UpdateHdbNode", + eError); + return 0; + } + + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + return 0; + } + if (argc > 2) { + if (!cloneHdbValue(&targetNode->value, &newValue)) { + SCWrite(pCon, "ERROR: out of memory cloning node", eError); + return 0; } - strcpy(error,"ERROR: "); - if(!readHdbValue(&newValue, GetCharArray(parData), - error+7,512-7)){ - SCWrite(pCon,error, eError); - return 0; + parData = CreateDynString(64, 64); + if (parData == NULL) { + SCWrite(pCon, "ERROR: out of memory reading parameter", eError); + return 0; + } + for (i = 2; i < argc; i++) { + DynStringConcat(parData, " "); + DynStringConcat(parData, argv[i]); + } + strcpy(error, "ERROR: "); + if (!readHdbValue(&newValue, GetCharArray(parData), + error + 7, 512 - 7)) { + SCWrite(pCon, error, eError); + return 0; } DeleteDynString(parData); - status = SetHipadabaPar(targetNode,newValue,pCon); - ReleaseHdbValue(&newValue); - if(status == 1){ - /* SCSendOK(pCon); sending ok has to be done by the callback. */ - } - return status; + } else { + memset(&newValue, 0, sizeof(hdbValue)); + GetHipadabaPar(targetNode, &newValue, pCon); + } + status = UpdateHipadabaPar(targetNode, newValue, pCon); + ReleaseHdbValue(&newValue); + if (status == 1) { + SCSendOK(pCon); + } + return status; } -/*---------------------------------------------------------------------------*/ -static int UpdateHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - hdbValue newValue; - pDynString parData = NULL; - char error[512]; - int i, status; - - /* - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - */ - if(argc < 2) { - SCWrite(pCon,"ERROR: insufficient number of arguments to UpdateHdbNode", - eError); - return 0; - } - - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - return 0; - } - if(argc > 2){ - if(!cloneHdbValue(&targetNode->value,&newValue)){ - SCWrite(pCon,"ERROR: out of memory cloning node", - eError); - return 0; - } - parData = CreateDynString(64,64); - if(parData == NULL){ - SCWrite(pCon,"ERROR: out of memory reading parameter",eError); - return 0; - } - for(i = 2; i < argc; i++){ - DynStringConcat(parData," "); - DynStringConcat(parData, argv[i]); - } - strcpy(error,"ERROR: "); - if(!readHdbValue(&newValue, GetCharArray(parData), - error+7,512-7)){ - SCWrite(pCon,error, eError); - return 0; - } - DeleteDynString(parData); - } else { - memset(&newValue,0,sizeof(hdbValue)); - GetHipadabaPar(targetNode,&newValue,pCon); - } - status = UpdateHipadabaPar(targetNode,newValue,pCon); - ReleaseHdbValue(&newValue); - if(status == 1){ - SCSendOK(pCon); - } - return status; -} /*-----------------------------------------------------------------------------*/ -static int ZipGetHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - char error[512], oriPath[512]; - int status; - hdbValue newValue; - - if(argc < 2) { - SCWrite(pCon,"ERROR: need path to node",eError); - return 0; - } - - strncpy(oriPath,argv[1], 511); - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - return 0; - } - memset(&newValue,0,sizeof(hdbValue)); - GetHipadabaPar(targetNode, &newValue, pCon); - ReleaseHdbValue(&newValue); - return sendZippedNodeData(targetNode,pCon); -} -/*---------------------------------------------------------------------------*/ -static int GetHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - hdbValue newValue; - pDynString parData = NULL, result = NULL; - char error[512], oriPath[512];; - int i, status; - Protocol protocol = normal_protocol; - int outCode; - char value[80]; +static int ZipGetHdbNode(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb targetNode = NULL; + char error[512], oriPath[512]; + int status; + hdbValue newValue; - /* - if(strstr(argv[1],"values") != NULL){ - printf("Found!!\n"); + if (argc < 2) { + SCWrite(pCon, "ERROR: need path to node", eError); + return 0; + } + + strncpy(oriPath, argv[1], 511); + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + return 0; + } + memset(&newValue, 0, sizeof(hdbValue)); + GetHipadabaPar(targetNode, &newValue, pCon); + ReleaseHdbValue(&newValue); + return sendZippedNodeData(targetNode, pCon); +} + +/*---------------------------------------------------------------------------*/ +static int GetHdbNode(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHdb targetNode = NULL; + hdbValue newValue; + pDynString parData = NULL, result = NULL; + char error[512], oriPath[512];; + int i, status; + Protocol protocol = normal_protocol; + int outCode; + char value[80]; + + /* + if(strstr(argv[1],"values") != NULL){ + printf("Found!!\n"); + } + */ + + if (argc < 2) { + SCWrite(pCon, "ERROR: need path to node to print", eError); + return 0; + } + + strncpy(oriPath, argv[1], 511); + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + return 0; + } + /* + * if transfer = zip, redirect to zip + */ + if (GetHdbProperty(targetNode, "transfer", value, 80) == 1) { + if (strstr(value, "zip") != NULL) { + return ZipGetHdbNode(pCon, pSics, pData, argc, argv); } - */ - - if(argc < 2) { - SCWrite(pCon,"ERROR: need path to node to print",eError); - return 0; - } - - strncpy(oriPath,argv[1], 511); - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - return 0; - } - /* - * if transfer = zip, redirect to zip - */ - if(GetHdbProperty(targetNode,"transfer", value,80) == 1){ - if(strstr(value,"zip") != NULL){ - return ZipGetHdbNode(pCon,pSics,pData,argc,argv); - } - } - memset(&newValue,0,sizeof(hdbValue)); - GetHipadabaPar(targetNode, &newValue, pCon); - parData = formatValue(newValue, targetNode); - if(parData == NULL){ - SCWrite(pCon,"ERROR: out of memory formatting data",eError); - return 0; - } - if ((protocol = isJSON(pCon)) == 1) + } + memset(&newValue, 0, sizeof(hdbValue)); + GetHipadabaPar(targetNode, &newValue, pCon); + parData = formatValue(newValue, targetNode); + if (parData == NULL) { + SCWrite(pCon, "ERROR: out of memory formatting data", eError); + return 0; + } + if ((protocol = isJSON(pCon)) == 1) + outCode = eHdbEvent; + else + outCode = eValue; + + result = CreateDynString(128, 128); + formatNameValue(protocol, oriPath, GetCharArray(parData), result, + newValue.dataType); + SCWrite(pCon, GetCharArray(result), outCode); + DeleteDynString(parData); + DeleteDynString(result); + ReleaseHdbValue(&newValue); + + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int GetHdbVal(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHdb targetNode = NULL; + hdbValue newValue; + pDynString parData = NULL; + char error[512], oriPath[512]; + int i, status, protocol, outCode; + char value[80]; + + if (argc < 2) { + SCWrite(pCon, "ERROR: need path to node to print", eError); + return 0; + } + + strncpy(oriPath, argv[1], 511); + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + return 0; + } + memset(&newValue, 0, sizeof(hdbValue)); + GetHipadabaPar(targetNode, &newValue, pCon); + parData = formatValue(newValue, targetNode); + if (parData == NULL) { + SCWrite(pCon, "ERROR: out of memory formatting data", eError); + return 0; + } else { + if ((protocol = isJSON(pCon)) == 1) outCode = eHdbEvent; else outCode = eValue; - - result = CreateDynString(128,128); - formatNameValue(protocol, oriPath, GetCharArray(parData), result, newValue.dataType); - SCWrite(pCon,GetCharArray(result),outCode); + SCWrite(pCon, GetCharArray(parData), outCode); DeleteDynString(parData); - DeleteDynString(result); ReleaseHdbValue(&newValue); - - return 1; + return 1; + } + return 1; } -/*---------------------------------------------------------------------------*/ -static int GetHdbVal(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - hdbValue newValue; - pDynString parData = NULL; - char error[512], oriPath[512]; - int i, status, protocol, outCode; - char value[80]; - if(argc < 2) { - SCWrite(pCon,"ERROR: need path to node to print",eError); - return 0; - } - - strncpy(oriPath,argv[1], 511); - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - return 0; - } - memset(&newValue,0,sizeof(hdbValue)); - GetHipadabaPar(targetNode, &newValue, pCon); - parData = formatValue(newValue, targetNode); - if(parData == NULL){ - SCWrite(pCon,"ERROR: out of memory formatting data",eError); - return 0; - } else { - if ((protocol = isJSON(pCon)) == 1) - outCode = eHdbEvent; - else - outCode = eValue; - SCWrite(pCon,GetCharArray(parData), outCode); - DeleteDynString(parData); - ReleaseHdbValue(&newValue); - return 1; - } - return 1; -} /*--------------------------------------------------------------------------*/ -static int countChildren(pHdb node){ - pHdb current = NULL; - int count = 0; - - current = node->child; - while(current != NULL){ - count++; - current = current->next; - } - return count; -} -/*---------------------------------------------------------------------------*/ -static int HdbNodeInfo(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - char error[512], oriPath[512], info[512]; - int i, status, length; +static int countChildren(pHdb node) +{ + pHdb current = NULL; + int count = 0; - if(argc < 2) { - SCWrite(pCon,"ERROR: need path to node to get info",eError); - return 0; - } - - strncpy(oriPath,argv[1], 511); - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - return 0; - } - length = targetNode->value.arrayLength; - if(length == 0){ - length = 1; - } - snprintf(info,511,"%s,%d,%d",hdbTypeToText(targetNode->value.dataType), - countChildren(targetNode), length); - SCWrite(pCon,info,eValue); - - return 1; -} -/*---------------------------------------------------------------------------*/ -static int HdbNodeVal(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - hdbValue newValue; - pDynString parData = NULL; - char error[512]; - int i, status; - - if(argc < 2) { - SCWrite(pCon,"ERROR: need path to node to print",eError); - return 0; - } - - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - return 0; - } - memset(&newValue,0,sizeof(hdbValue)); - GetHipadabaPar(targetNode, &newValue, pCon); - parData = formatValue(newValue, targetNode); - if(parData == NULL){ - SCWrite(pCon,"ERROR: out of memory formatting data",eError); - return 0; - } - SCWrite(pCon,GetCharArray(parData),eHdbValue); - DeleteDynString(parData); - ReleaseHdbValue(&newValue); - - return 1; + current = node->child; + while (current != NULL) { + count++; + current = current->next; + } + return count; } /*---------------------------------------------------------------------------*/ -int isSICSHdbRO(pHdb node){ - pHdbCallback current = NULL; - - current = node->callBackChain; - while(current != NULL){ - if(current->userCallback == SICSReadOnlyCallback) { - return 1; - } - current = current->next; - } +static int HdbNodeInfo(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHdb targetNode = NULL; + char error[512], oriPath[512], info[512]; + int i, status, length; + + if (argc < 2) { + SCWrite(pCon, "ERROR: need path to node to get info", eError); return 0; -} -/*---------------------------------------------------------------------------*/ -static pDynString formatPlainList(pHdb node){ - pHdb current; - pDynString result = NULL; - - result = CreateDynString(128,128); - if(result == NULL){ - return NULL; - } - - current = node->child; - while(current != NULL){ - DynStringConcat(result,current->name); - DynStringConcat(result,"\n"); - current = current->next; - } - return result; + } + + strncpy(oriPath, argv[1], 511); + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + return 0; + } + length = targetNode->value.arrayLength; + if (length == 0) { + length = 1; + } + snprintf(info, 511, "%s,%d,%d", + hdbTypeToText(targetNode->value.dataType), + countChildren(targetNode), length); + SCWrite(pCon, info, eValue); + + return 1; } + /*---------------------------------------------------------------------------*/ -static pDynString formatJSONList(pHdb node){ +static int HdbNodeVal(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHdb targetNode = NULL; + hdbValue newValue; + pDynString parData = NULL; + char error[512]; + int i, status; + + if (argc < 2) { + SCWrite(pCon, "ERROR: need path to node to print", eError); + return 0; + } + + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + return 0; + } + memset(&newValue, 0, sizeof(hdbValue)); + GetHipadabaPar(targetNode, &newValue, pCon); + parData = formatValue(newValue, targetNode); + if (parData == NULL) { + SCWrite(pCon, "ERROR: out of memory formatting data", eError); + return 0; + } + SCWrite(pCon, GetCharArray(parData), eHdbValue); + DeleteDynString(parData); + ReleaseHdbValue(&newValue); + + return 1; +} + +/*---------------------------------------------------------------------------*/ +int isSICSHdbRO(pHdb node) +{ + pHdbCallback current = NULL; + + current = node->callBackChain; + while (current != NULL) { + if (current->userCallback == SICSReadOnlyCallback) { + return 1; + } + current = current->next; + } + return 0; +} + +/*---------------------------------------------------------------------------*/ +static pDynString formatPlainList(pHdb node) +{ + pHdb current; + pDynString result = NULL; + + result = CreateDynString(128, 128); + if (result == NULL) { + return NULL; + } + + current = node->child; + while (current != NULL) { + DynStringConcat(result, current->name); + DynStringConcat(result, "\n"); + current = current->next; + } + return result; +} + +/*---------------------------------------------------------------------------*/ +static pDynString formatJSONList(pHdb node) +{ pHdb current; pDynString result = NULL; pDynString data = NULL; - if (node->child == NULL) return NULL; - result = CreateDynString(128,128); - if(result == NULL){ + if (node->child == NULL) return NULL; - } + result = CreateDynString(128, 128); + if (result == NULL) { + return NULL; + } - if(node->child->value.dataType == HIPNONE) - DynStringCopy(result,"["); + if (node->child->value.dataType == HIPNONE) + DynStringCopy(result, "["); else - DynStringCopy(result,"{"); + DynStringCopy(result, "{"); current = node->child; - while(current != NULL){ - DynStringConcat(result,"\""); - DynStringConcat(result,current->name); - DynStringConcat(result,"\""); - if(current->value.dataType != HIPNONE){ + while (current != NULL) { + DynStringConcat(result, "\""); + DynStringConcat(result, current->name); + DynStringConcat(result, "\""); + if (current->value.dataType != HIPNONE) { data = formatValue(current->value, current); - if(data != NULL){ - DynStringConcat(result,": "); - DynStringConcat(result,GetCharArray(data)); + if (data != NULL) { + DynStringConcat(result, ": "); + DynStringConcat(result, GetCharArray(data)); DeleteDynString(data); } } - if (current->next != NULL) DynStringConcat(result,", "); + if (current->next != NULL) + DynStringConcat(result, ", "); current = current->next; } - if(node->child->value.dataType == HIPNONE) - DynStringConcat(result,"]"); + if (node->child->value.dataType == HIPNONE) + DynStringConcat(result, "]"); else - DynStringConcat(result,"}"); - + DynStringConcat(result, "}"); + return result; } -/*---------------------------------------------------------------------------*/ -static pDynString formatListWithVal(pHdb node){ - pHdb current; - pDynString result = NULL; - pDynString data = NULL; - - result = CreateDynString(128,128); - if(result == NULL){ - return NULL; - } - - current = node->child; - while(current != NULL){ - if(current->value.dataType != HIPNONE){ - DynStringConcat(result,current->name); - data = formatValue(current->value, current); - if(data != NULL){ - DynStringConcat(result," = "); - DynStringConcat(result,GetCharArray(data)); - DeleteDynString(data); - } - DynStringConcat(result,"\n"); - } - current = current->next; - } - return result; -} -/*---------------------------------------------------------------------------*/ -static pDynString formatClientList(pHdb node){ - pHdb current; - pDynString result = NULL; - int length; - int i; - char number[50]; - - result = CreateDynString(128,128); - if(result == NULL){ - return NULL; - } - - current = node->child; - while(current != NULL){ - DynStringConcat(result,current->name); - DynStringConcat(result,","); - DynStringConcat(result,hdbTypeToText(current->value.dataType)); - DynStringConcat(result,","); - snprintf(number,50,"%d",countChildren(current)); - DynStringConcat(result,number); - DynStringConcat(result,","); - if(current->value.dataType >= 3){ - length = current->value.arrayLength; - } else { - length = 1; - } - snprintf(number,50,"%d",length); - DynStringConcat(result,number); - DynStringConcat(result,","); - switch(current->value.dataType){ - case HIPNONE: - break; - case HIPINT: - snprintf(number,50,"%d",current->value.v.intValue); - DynStringConcat(result,number); - break; - case HIPFLOAT: - snprintf(number,50,"%lg",current->value.v.doubleValue); - DynStringConcat(result,number); - break; - case HIPTEXT: - DynStringConcat(result,current->value.v.text); - break; - case HIPINTAR: - case HIPINTVARAR: - for(i = 0; i < length; i++){ - snprintf(number,50,"%d",current->value.v.intArray[i]); - DynStringConcat(result,number); - if(i > length -1){ - DynStringConcat(result,","); - } - } - break; - case HIPFLOATAR: - case HIPFLOATVARAR: - for(i = 0; i < length; i++){ - snprintf(number,50,"%lf",current->value.v.floatArray[i]); - DynStringConcat(result,number); - if(i > length -1){ - DynStringConcat(result,","); - } - } - break; - } - DynStringConcat(result,"\n"); - current = current->next; - } - return result; -} -/*---------------------------------------------------------------------------*/ -static int ListHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb node = NULL; - int pathArg = 1; - pDynString listData = NULL; - Protocol protocol = normal_protocol; - int outCode; - - if(argc < 2) { - SCWrite(pCon,"ERROR: need path to node to print",eError); - return 0; - } - - if(argv[1][0] == '-'){ - pathArg = 2; - if(argc < 3){ - SCWrite(pCon,"ERROR: need path to node to print",eError); - return 0; - } - } - node = FindHdbNode(NULL,argv[pathArg],pCon); - if(node == NULL){ - return 0; - } - - if(pathArg == 2) { - strtolower(argv[1]); - } - if(strcmp(argv[1],"-val") == 0){ - listData = formatListWithVal(node); - } else if(strcmp(argv[1],"-cli") == 0){ - listData = formatClientList(node); - } else { - if ((protocol = isJSON(pCon)) == 1) { - listData = formatJSONList(node); - outCode = eHdbEvent; - } else { - listData = formatPlainList(node); - outCode = eValue; +/*---------------------------------------------------------------------------*/ +static pDynString formatListWithVal(pHdb node) +{ + pHdb current; + pDynString result = NULL; + pDynString data = NULL; + + result = CreateDynString(128, 128); + if (result == NULL) { + return NULL; + } + + current = node->child; + while (current != NULL) { + if (current->value.dataType != HIPNONE) { + DynStringConcat(result, current->name); + data = formatValue(current->value, current); + if (data != NULL) { + DynStringConcat(result, " = "); + DynStringConcat(result, GetCharArray(data)); + DeleteDynString(data); } + DynStringConcat(result, "\n"); } - if(listData == NULL){ - SCWrite(pCon,"ERROR: failed to format list", - eError); - return 0; - } - if( (strcmp(argv[1],"-val") == 0) || (strcmp(argv[1],"-cli") == 0) ){ - SCWrite(pCon,GetCharArray(listData),eValue); + current = current->next; + } + return result; +} + +/*---------------------------------------------------------------------------*/ +static pDynString formatClientList(pHdb node) +{ + pHdb current; + pDynString result = NULL; + int length; + int i; + char number[50]; + + result = CreateDynString(128, 128); + if (result == NULL) { + return NULL; + } + + current = node->child; + while (current != NULL) { + DynStringConcat(result, current->name); + DynStringConcat(result, ","); + DynStringConcat(result, hdbTypeToText(current->value.dataType)); + DynStringConcat(result, ","); + snprintf(number, 50, "%d", countChildren(current)); + DynStringConcat(result, number); + DynStringConcat(result, ","); + if (current->value.dataType >= 3) { + length = current->value.arrayLength; } else { - SCWrite(pCon,GetCharArray(listData),outCode); + length = 1; } - DeleteDynString(listData); - return 1; -} -/*---------------------------------------------------------------------------*/ -static int AutoNotifyHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb node = NULL; - int id, status; - - if(argc < 3) { - SCWrite(pCon,"ERROR: need path and id in order to add notify", - eError); - return 0; - } - - node = FindHdbNode(NULL,argv[1],pCon); - if(node == NULL){ - return 0; - } - - id = atoi(argv[2]); - - status = InstallSICSNotify(node, pCon, id, 1); - if(status == 1){ - SCSendOK(pCon); - } - - return status; -} -/*---------------------------------------------------------------------------*/ -static int RemoveHdbCallback(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - int id; - hdbIDMessage m; - - if(argc < 2) { - SCWrite(pCon,"ERROR: need callback id to remove", - eError); - return 0; - } - id = atoi(argv[1]); - m.type = killID; - m.ID = id; - RecurseCallbackChains(root,(pHdbMessage)&m); - SCSendOK(pCon); - return 1; -} -/*---------------------------------------------------------------------------*/ -static int LinkHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb node = NULL; - char buffer[256]; - pObjectDescriptor pDes = NULL; - - if(argc < 3) { - SCWrite(pCon,"ERROR: need path and object name to link", - eError); - return 0; - } - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - node = GetHipadabaNode(root,argv[1]); - if(node == NULL){ - snprintf(buffer,255,"ERROR: path %s NOT found!", argv[1]); - SCWrite(pCon,buffer,eError); - return 0; - } - - pDes = FindCommandDescriptor(pSics,argv[2]); - if(pDes == NULL){ - snprintf(buffer,255,"ERROR: failed to find object %s", argv[2]); - SCWrite(pCon,buffer,eError); - return 0; - } - if(pDes->parNode == NULL){ - snprintf(buffer,255, - "ERROR: Object %s does not use Hipadaba natively and thus cannot be linked", - argv[2]); - SCWrite(pCon,buffer,eError); - return 0; - } - - if(pDes->parNode->mama != NULL){ - snprintf(buffer,255, - "ERROR: Object %s is already linked somewhere else", - argv[2]); - SCWrite(pCon,buffer,eError); - return 0; - } - - AddHipadabaChild(node,pDes->parNode,pCon); - - if(argc > 3){ - if(pDes->parNode->name != NULL){ - free(pDes->parNode->name); + snprintf(number, 50, "%d", length); + DynStringConcat(result, number); + DynStringConcat(result, ","); + switch (current->value.dataType) { + case HIPNONE: + break; + case HIPINT: + snprintf(number, 50, "%d", current->value.v.intValue); + DynStringConcat(result, number); + break; + case HIPFLOAT: + snprintf(number, 50, "%lg", current->value.v.doubleValue); + DynStringConcat(result, number); + break; + case HIPTEXT: + DynStringConcat(result, current->value.v.text); + break; + case HIPINTAR: + case HIPINTVARAR: + for (i = 0; i < length; i++) { + snprintf(number, 50, "%d", current->value.v.intArray[i]); + DynStringConcat(result, number); + if (i > length - 1) { + DynStringConcat(result, ","); } - pDes->parNode->name = strdup(argv[3]); + } + break; + case HIPFLOATAR: + case HIPFLOATVARAR: + for (i = 0; i < length; i++) { + snprintf(number, 50, "%lf", current->value.v.floatArray[i]); + DynStringConcat(result, number); + if (i > length - 1) { + DynStringConcat(result, ","); + } + } + break; } + DynStringConcat(result, "\n"); + current = current->next; + } + return result; +} - SCSendOK(pCon); - return 1; -} -/*-------------------------------------------------------------------------*/ -static hdbCallbackReturn ChainCallback(pHdb node, void *userData, - pHdbMessage message){ - pHdb slave = (pHdb)userData; - hdbValue vv, old; - pHdbDataMessage mm = NULL; - - if((mm = GetHdbUpdateMessage(message)) == NULL){ - return hdbContinue; +/*---------------------------------------------------------------------------*/ +static int ListHdbNode(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHdb node = NULL; + int pathArg = 1; + pDynString listData = NULL; + Protocol protocol = normal_protocol; + int outCode; + + if (argc < 2) { + SCWrite(pCon, "ERROR: need path to node to print", eError); + return 0; + } + + if (argv[1][0] == '-') { + pathArg = 2; + if (argc < 3) { + SCWrite(pCon, "ERROR: need path to node to print", eError); + return 0; } - - if(slave != NULL){ - memset(&vv,0,sizeof(hdbValue)); - GetHipadabaPar(slave,&vv,mm->callData); - UpdateHipadabaPar(slave, vv, mm->callData); - ReleaseHdbValue(&vv); + } + + node = FindHdbNode(NULL, argv[pathArg], pCon); + if (node == NULL) { + return 0; + } + + if (pathArg == 2) { + strtolower(argv[1]); + } + if (strcmp(argv[1], "-val") == 0) { + listData = formatListWithVal(node); + } else if (strcmp(argv[1], "-cli") == 0) { + listData = formatClientList(node); + } else { + if ((protocol = isJSON(pCon)) == 1) { + listData = formatJSONList(node); + outCode = eHdbEvent; + } else { + listData = formatPlainList(node); + outCode = eValue; } - return hdbContinue; + } + if (listData == NULL) { + SCWrite(pCon, "ERROR: failed to format list", eError); + return 0; + } + if ((strcmp(argv[1], "-val") == 0) || (strcmp(argv[1], "-cli") == 0)) { + SCWrite(pCon, GetCharArray(listData), eValue); + } else { + SCWrite(pCon, GetCharArray(listData), outCode); + } + DeleteDynString(listData); + return 1; } -/*--------------------------------------------------------------------------*/ -static int ChainHdbNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb master = NULL, slave = NULL; - char buffer[512]; - pHdbCallback kalle = NULL; - - if(argc < 3) { - SCWrite(pCon,"ERROR: insufficent number of arguments to hchain", + +/*---------------------------------------------------------------------------*/ +static int AutoNotifyHdbNode(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb node = NULL; + int id, status; + + if (argc < 3) { + SCWrite(pCon, "ERROR: need path and id in order to add notify", eError); - } - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - slave = GetHipadabaNode(root,argv[1]); - if(slave == NULL){ - snprintf(buffer,511,"ERROR: slave %s not found",argv[1]); - SCWrite(pCon,buffer,eError); - return 0; - } + return 0; + } - master = GetHipadabaNode(root,argv[2]); - if(master == NULL){ - snprintf(buffer,511,"ERROR: master %s not found",argv[1]); - SCWrite(pCon,buffer,eError); - return 0; - } - - kalle = MakeHipadabaCallback(ChainCallback,slave, NULL); - if(kalle == NULL){ - SCWrite(pCon,"ERROR: out of memory creating callback",eError); - return 0; - } - AppendHipadabaCallback(master,kalle); + node = FindHdbNode(NULL, argv[1], pCon); + if (node == NULL) { + return 0; + } + + id = atoi(argv[2]); + + status = InstallSICSNotify(node, pCon, id, 1); + if (status == 1) { SCSendOK(pCon); - return 1; + } + + return status; } + +/*---------------------------------------------------------------------------*/ +static int RemoveHdbCallback(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + int id; + hdbIDMessage m; + + if (argc < 2) { + SCWrite(pCon, "ERROR: need callback id to remove", eError); + return 0; + } + id = atoi(argv[1]); + m.type = killID; + m.ID = id; + RecurseCallbackChains(root, (pHdbMessage) & m); + SCSendOK(pCon); + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int LinkHdbNode(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pHdb node = NULL; + char buffer[256]; + pObjectDescriptor pDes = NULL; + + if (argc < 3) { + SCWrite(pCon, "ERROR: need path and object name to link", eError); + return 0; + } + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + node = GetHipadabaNode(root, argv[1]); + if (node == NULL) { + snprintf(buffer, 255, "ERROR: path %s NOT found!", argv[1]); + SCWrite(pCon, buffer, eError); + return 0; + } + + pDes = FindCommandDescriptor(pSics, argv[2]); + if (pDes == NULL) { + snprintf(buffer, 255, "ERROR: failed to find object %s", argv[2]); + SCWrite(pCon, buffer, eError); + return 0; + } + if (pDes->parNode == NULL) { + snprintf(buffer, 255, + "ERROR: Object %s does not use Hipadaba natively and thus cannot be linked", + argv[2]); + SCWrite(pCon, buffer, eError); + return 0; + } + + if (pDes->parNode->mama != NULL) { + snprintf(buffer, 255, + "ERROR: Object %s is already linked somewhere else", argv[2]); + SCWrite(pCon, buffer, eError); + return 0; + } + + AddHipadabaChild(node, pDes->parNode, pCon); + + if (argc > 3) { + if (pDes->parNode->name != NULL) { + free(pDes->parNode->name); + } + pDes->parNode->name = strdup(argv[3]); + } + + SCSendOK(pCon); + return 1; +} + +/*-------------------------------------------------------------------------*/ +static hdbCallbackReturn ChainCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdb slave = (pHdb) userData; + hdbValue vv, old; + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbUpdateMessage(message)) == NULL) { + return hdbContinue; + } + + if (slave != NULL) { + memset(&vv, 0, sizeof(hdbValue)); + GetHipadabaPar(slave, &vv, mm->callData); + UpdateHipadabaPar(slave, vv, mm->callData); + ReleaseHdbValue(&vv); + } + return hdbContinue; +} + +/*--------------------------------------------------------------------------*/ +static int ChainHdbNode(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb master = NULL, slave = NULL; + char buffer[512]; + pHdbCallback kalle = NULL; + + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficent number of arguments to hchain", + eError); + } + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + slave = GetHipadabaNode(root, argv[1]); + if (slave == NULL) { + snprintf(buffer, 511, "ERROR: slave %s not found", argv[1]); + SCWrite(pCon, buffer, eError); + return 0; + } + + master = GetHipadabaNode(root, argv[2]); + if (master == NULL) { + snprintf(buffer, 511, "ERROR: master %s not found", argv[1]); + SCWrite(pCon, buffer, eError); + return 0; + } + + kalle = MakeHipadabaCallback(ChainCallback, slave, NULL); + if (kalle == NULL) { + SCWrite(pCon, "ERROR: out of memory creating callback", eError); + return 0; + } + AppendHipadabaCallback(master, kalle); + SCSendOK(pCon); + return 1; +} + /* -------------------------------------------------------------------------- * This is actually SCInvoke but without advancing the context. I think this * is only of local use. It makes sure that commands executed as Hipadaba * commands get logged properly. - */ - static int HDBInvoke(SConnection *self, SicsInterp *pInter, char *pCommand) - { - int iRet; - long lLen; - const char *pResult = NULL; - char *pBuffer = NULL, *pFile = NULL; - char pBueffel[80]; - int i, iSpace; - - assert(pInter); - - /* print command to log files */ - /* + */ +static int HDBInvoke(SConnection * self, SicsInterp * pInter, + char *pCommand) +{ + int iRet; + long lLen; + const char *pResult = NULL; + char *pBuffer = NULL, *pFile = NULL; + char pBueffel[80]; + int i, iSpace; + + assert(pInter); + + /* print command to log files */ + /* for( i = 0; i < self->iFiles; i++) { - if(self->pFiles[i]) - { - fprintf(self->pFiles[i],"SICS>> %s\n",pCommand); - } - } - */ - - /* print to command log if user or manager */ - if(SCGetRights(self) <= usUser) + if(self->pFiles[i]) { - if(self->pSock != NULL) - { - sprintf(pBueffel,"sock %d>>",self->pSock->sockid); - } + fprintf(self->pFiles[i],"SICS>> %s\n",pCommand); } - - /* invoke */ - self->inUse++; - self->eInterrupt = eContinue; - /* - get first word of command - */ - iRet = InterpExecute(pInter,self,pCommand); - - StatusFileTask(NULL); /* save changed parameters */ + } + */ - self->inUse--; - return iRet; + /* print to command log if user or manager */ + if (SCGetRights(self) <= usUser) { + if (self->pSock != NULL) { + sprintf(pBueffel, "sock %d>>", self->pSock->sockid); + } } + + /* invoke */ + self->inUse++; + self->eInterrupt = eContinue; + /* + get first word of command + */ + iRet = InterpExecute(pInter, self, pCommand); + + StatusFileTask(NULL); /* save changed parameters */ + + self->inUse--; + return iRet; +} + /*---------------------------------------------------------------------------*/ -static hdbCallbackReturn CommandSetCallback(pHdb node, void *userData, - pHdbMessage message){ - SConnection *pCon = NULL; - pDynString cmd = NULL, par = NULL; - pHdb current = NULL; - int status; - pHdbDataMessage mm = NULL; - hdbValue v; - +static hdbCallbackReturn CommandSetCallback(pHdb node, void *userData, + pHdbMessage message) +{ + SConnection *pCon = NULL; + pDynString cmd = NULL, par = NULL; + pHdb current = NULL; + int status; + pHdbDataMessage mm = NULL; + hdbValue v; + /** * TODO: this is a duplicate: resolve. It is still here because the old * Hipadaba configuration commands still work */ - if((mm = GetHdbSetMessage(message)) == NULL){ - return hdbContinue; - } - pCon = (SConnection *)mm->callData; - v = *(mm->v); - - if(pCon == NULL){ - printf("Cannot invoke command without connection\n"); - return hdbAbort; - } - - if(v.dataType == HIPTEXT){ - if(strstr(v.v.text,"start") != NULL) { - cmd = CreateDynString(64,64); - if(cmd == 0){ - SCWrite(pCon,"ERROR: out of memory in CommandSetCallback",eError); - return 0; - } - DynStringCopy(cmd, node->value.v.text); - DynStringConcat(cmd," "); - current = node->child; - while(current != NULL){ - par = formatValue(current->value, current); - if(par != NULL){ - DynStringConcat(cmd, GetCharArray(par)); - DynStringConcat(cmd," "); - DeleteDynString(par); - } - current = current->next; - } - SendHdbStatusMessage(node,"start"); - status = HDBInvoke(pCon,pServ->pSics, GetCharArray(cmd)); - SendHdbStatusMessage(node,"stop"); - DeleteDynString(cmd); - if(status == 1){ - return hdbContinue; - } else { - return hdbAbort; - } - } else { - SCWrite(pCon,"ERROR: this node only understands start as value",eError); - return hdbAbort; + if ((mm = GetHdbSetMessage(message)) == NULL) { + return hdbContinue; + } + pCon = (SConnection *) mm->callData; + v = *(mm->v); + + if (pCon == NULL) { + printf("Cannot invoke command without connection\n"); + return hdbAbort; + } + + if (v.dataType == HIPTEXT) { + if (strstr(v.v.text, "start") != NULL) { + cmd = CreateDynString(64, 64); + if (cmd == 0) { + SCWrite(pCon, "ERROR: out of memory in CommandSetCallback", + eError); + return 0; + } + DynStringCopy(cmd, node->value.v.text); + DynStringConcat(cmd, " "); + current = node->child; + while (current != NULL) { + par = formatValue(current->value, current); + if (par != NULL) { + DynStringConcat(cmd, GetCharArray(par)); + DynStringConcat(cmd, " "); + DeleteDynString(par); } + current = current->next; + } + SendHdbStatusMessage(node, "start"); + status = HDBInvoke(pCon, pServ->pSics, GetCharArray(cmd)); + SendHdbStatusMessage(node, "stop"); + DeleteDynString(cmd); + if (status == 1) { + return hdbContinue; + } else { + return hdbAbort; + } + } else { + SCWrite(pCon, "ERROR: this node only understands start as value", + eError); + return hdbAbort; } - return hdbContinue; + } + return hdbContinue; } + /*---------------------------------------------------------------------------*/ -static hdbCallbackReturn CommandGetCallback(pHdb node, void *userData, - pHdbMessage message){ - pHdbDataMessage mm = NULL; - - if((mm = GetHdbGetMessage(message)) == NULL){ - return hdbContinue; - } - - hdbValue v2 = MakeHdbText("Nothing to get"); - copyHdbValue(&v2, mm->v); /* MakeHdbText makes no strdup ! */ +static hdbCallbackReturn CommandGetCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pHdbDataMessage mm = NULL; + + if ((mm = GetHdbGetMessage(message)) == NULL) { return hdbContinue; + } + + hdbValue v2 = MakeHdbText("Nothing to get"); + copyHdbValue(&v2, mm->v); /* MakeHdbText makes no strdup ! */ + return hdbContinue; } + /*--------------------------------------------------------------------------*/ -static int SicsCommandNode(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - char *name = NULL; - pHdbCallback kalle = NULL; - pHdb parent = NULL, node = NULL; - - if(argc < 3) { - SCWrite(pCon,"ERROR: insufficent number of arguments to hcommand", +static int SicsCommandNode(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + char *name = NULL; + pHdbCallback kalle = NULL; + pHdb parent = NULL, node = NULL; + + if (argc < 3) { + SCWrite(pCon, "ERROR: insufficent number of arguments to hcommand", eError); - } - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - parent = FindHdbParent(NULL, argv[1], &name, pCon); - if(parent == NULL){ - return 0; /* error message already written */ - } - node = MakeHipadabaNode(name, HIPTEXT, 1); - if(node == NULL){ - SCWrite(pCon,"ERROR: out of memory in hcommand",eError); - return 0; - } - node->value.v.text = strdup(argv[2]); - node->value.arrayLength = strlen(argv[2]); - SetHdbProperty(node,"sicscommand", argv[2]); - - kalle = MakeHipadabaCallback(CommandSetCallback,NULL, NULL); - if(kalle == NULL){ - SCWrite(pCon,"ERROR: out of memory in hcommand",eError); - return 0; - } - AppendHipadabaCallback(node,kalle); + } + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } - kalle = MakeHipadabaCallback(CommandGetCallback,NULL, NULL); - if(kalle == NULL){ - SCWrite(pCon,"ERROR: out of memory in hcommand",eError); - return 0; - } - AppendHipadabaCallback(node,kalle); - - AddHipadabaChild(parent,node,pCon); - - SCSendOK(pCon); - return 1; + parent = FindHdbParent(NULL, argv[1], &name, pCon); + if (parent == NULL) { + return 0; /* error message already written */ + } + node = MakeHipadabaNode(name, HIPTEXT, 1); + if (node == NULL) { + SCWrite(pCon, "ERROR: out of memory in hcommand", eError); + return 0; + } + node->value.v.text = strdup(argv[2]); + node->value.arrayLength = strlen(argv[2]); + SetHdbProperty(node, "sicscommand", argv[2]); + + kalle = MakeHipadabaCallback(CommandSetCallback, NULL, NULL); + if (kalle == NULL) { + SCWrite(pCon, "ERROR: out of memory in hcommand", eError); + return 0; + } + AppendHipadabaCallback(node, kalle); + + kalle = MakeHipadabaCallback(CommandGetCallback, NULL, NULL); + if (kalle == NULL) { + SCWrite(pCon, "ERROR: out of memory in hcommand", eError); + return 0; + } + AppendHipadabaCallback(node, kalle); + + AddHipadabaChild(parent, node, pCon); + + SCSendOK(pCon); + return 1; } + /*======================= Property Functions ================================*/ -static int SetSICSHdbProperty(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - char buffer[512]; - char *val; +static int SetSICSHdbProperty(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb targetNode = NULL; + char buffer[512]; + char *val; + + if (argc < 4) { + SCWrite(pCon, "ERROR: need path key value as parameters", eError); + return 0; + } + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + SCWrite(pCon, "ERROR: node not found", eError); + return 0; + } + val = Arg2Tcl(argc - 3, &argv[3], buffer, sizeof buffer); + if (val) { + SetHdbProperty(targetNode, argv[2], val); + if (val != buffer) + free(val); + } + SCSendOK(pCon); + return 1; +} - if(argc < 4) { - SCWrite(pCon,"ERROR: need path key value as parameters",eError); - return 0; - } - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - SCWrite(pCon,"ERROR: node not found",eError); - return 0; - } - val = Arg2Tcl(argc-3, &argv[3], buffer, sizeof buffer); - if (val) { - SetHdbProperty(targetNode,argv[2], val); - if (val != buffer) free(val); - } - SCSendOK(pCon); - return 1; - } /*-------------------------------------------------------------------------------*/ -static int DelSICSHdbProperty(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; +static int DelSICSHdbProperty(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb targetNode = NULL; + + if (argc < 3) { + SCWrite(pCon, "ERROR: need path key as parameters", eError); + return 0; + } + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + SCWrite(pCon, "ERROR: node not found", eError); + return 0; + } + SetHdbProperty(targetNode, argv[2], NULL); + SCSendOK(pCon); + return 1; +} - if(argc < 3) { - SCWrite(pCon,"ERROR: need path key as parameters",eError); - return 0; - } - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - SCWrite(pCon,"ERROR: node not found",eError); - return 0; - } - SetHdbProperty(targetNode,argv[2], NULL); - SCSendOK(pCon); - return 1; - } /*--------------------------------------------------------------------------*/ -static int GetSICSHdbProperty(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - char buffer[512]; - int status; +static int GetSICSHdbProperty(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb targetNode = NULL; + char buffer[512]; + int status; - if(argc < 3) { - SCWrite(pCon,"ERROR: need path key as parameters",eError); - return 0; - } - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - SCWrite(pCon,"ERROR: node not found",eValue); - return 0; - } - status = GetHdbProperty(targetNode,argv[2],buffer,511); - if(status != 1){ - SCPrintf(pCon,eValue,"ERROR: property %s not found", argv[2]); - return 0; - } - SCPrintf(pCon,eValue,"%s.%s = %s", argv[1], argv[2], buffer); - return 1; - } - /*--------------------------------------------------------------------------*/ -static int GetSICSHdbPropertyVal(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - char buffer[512]; - int status; - - if(argc < 3) { - SCWrite(pCon,"ERROR: need path key as parameters",eError); - return 0; - } - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - SCWrite(pCon,"ERROR: node not found",eValue); - return 0; - } - status = GetHdbProperty(targetNode,argv[2],buffer,511); - if(status != 1){ - SCWrite(pCon,"ERROR: attribute not found",eValue); - return 0; - } - SCPrintf(pCon,eValue,"%s", buffer); - return 1; - } - /*--------------------------------------------------------------------------*/ -static int ListSICSHdbProperty(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb targetNode = NULL; - char buffer[512]; - const char *pKey = NULL; - pDynString data = NULL; - - if(argc < 2) { - SCWrite(pCon,"ERROR: need path as parameter",eError); - return 0; - } - targetNode = FindHdbNode(NULL,argv[1],pCon); - if(targetNode == NULL){ - SCWrite(pCon,"ERROR: node not found",eError); - return 0; - } - data = CreateDynString(64,64); - if(data == NULL){ - SCWrite(pCon,"ERROR: out of memory in ListSICSHdbProperty",eError); - return 0; - } - InitHdbPropertySearch(targetNode); - while((pKey = GetNextHdbProperty(targetNode, buffer, 511)) != NULL){ - DynStringConcat(data,(char *)pKey); - DynStringConcat(data,"="); - DynStringConcat(data,buffer); - DynStringConcat(data,"\n"); - } - SCWrite(pCon,GetCharArray(data), eValue); - DeleteDynString(data); - return 1; - } -/*---------------------------------------------------------------------------*/ -static pHdb matchHdbProp(pHdb root, char *propname, char *buffer){ - char value[1024]; - pHdb current = NULL, search; - - memset(value,0,1024); - if(GetHdbProperty(root,propname,value,1023) == 1){ - if(strstr(buffer,value) != NULL){ - return root; - } - } - current = root->child; - while(current != NULL){ - search = matchHdbProp(current,propname,buffer); - if(search != NULL){ - return search; - } - current = current->next; - } - - return NULL; + if (argc < 3) { + SCWrite(pCon, "ERROR: need path key as parameters", eError); + return 0; + } + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + SCWrite(pCon, "ERROR: node not found", eValue); + return 0; + } + status = GetHdbProperty(targetNode, argv[2], buffer, 511); + if (status != 1) { + SCPrintf(pCon, eValue, "ERROR: property %s not found", argv[2]); + return 0; + } + SCPrintf(pCon, eValue, "%s.%s = %s", argv[1], argv[2], buffer); + return 1; } -/*---------------------------------------------------------------------------*/ -static int MatchHdbProperty(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pHdb root = NULL; - pHdb foundNode = NULL; - char buffer[1024], *path = NULL; - - if(argc < 4){ - SCWrite(pCon,"ERROR: need root, property name and target string for search", - eError); - return 0; - } - memset(buffer,0,1024); - Arg2Text(argc-3,&argv[3],buffer,1023); - root = GetHipadabaNode(GetHipadabaRoot(), argv[1]); - if(root == NULL){ - SCWrite(pCon,"ERROR: start node for search not found",eError); - return 0; - } - - strtolower(argv[2]); - strtolower(buffer); - foundNode = matchHdbProp(root,argv[2],buffer); - - if(foundNode == NULL){ - SCWrite(pCon,"NONE", eValue); - } else { - path = GetHipadabaPath(foundNode); - SCWrite(pCon,path,eValue); - free(path); - } - return 1; + + /*--------------------------------------------------------------------------*/ +static int GetSICSHdbPropertyVal(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb targetNode = NULL; + char buffer[512]; + int status; + + if (argc < 3) { + SCWrite(pCon, "ERROR: need path key as parameters", eError); + return 0; + } + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + SCWrite(pCon, "ERROR: node not found", eValue); + return 0; + } + status = GetHdbProperty(targetNode, argv[2], buffer, 511); + if (status != 1) { + SCWrite(pCon, "ERROR: attribute not found", eValue); + return 0; + } + SCPrintf(pCon, eValue, "%s", buffer); + return 1; } + + /*--------------------------------------------------------------------------*/ +static int ListSICSHdbProperty(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb targetNode = NULL; + char buffer[512]; + const char *pKey = NULL; + pDynString data = NULL; + + if (argc < 2) { + SCWrite(pCon, "ERROR: need path as parameter", eError); + return 0; + } + targetNode = FindHdbNode(NULL, argv[1], pCon); + if (targetNode == NULL) { + SCWrite(pCon, "ERROR: node not found", eError); + return 0; + } + data = CreateDynString(64, 64); + if (data == NULL) { + SCWrite(pCon, "ERROR: out of memory in ListSICSHdbProperty", eError); + return 0; + } + InitHdbPropertySearch(targetNode); + while ((pKey = GetNextHdbProperty(targetNode, buffer, 511)) != NULL) { + DynStringConcat(data, (char *) pKey); + DynStringConcat(data, "="); + DynStringConcat(data, buffer); + DynStringConcat(data, "\n"); + } + SCWrite(pCon, GetCharArray(data), eValue); + DeleteDynString(data); + return 1; +} + +/*---------------------------------------------------------------------------*/ +static pHdb matchHdbProp(pHdb root, char *propname, char *buffer) +{ + char value[1024]; + pHdb current = NULL, search; + + memset(value, 0, 1024); + if (GetHdbProperty(root, propname, value, 1023) == 1) { + if (strstr(buffer, value) != NULL) { + return root; + } + } + current = root->child; + while (current != NULL) { + search = matchHdbProp(current, propname, buffer); + if (search != NULL) { + return search; + } + current = current->next; + } + + return NULL; +} + +/*---------------------------------------------------------------------------*/ +static int MatchHdbProperty(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pHdb root = NULL; + pHdb foundNode = NULL; + char buffer[1024], *path = NULL; + + if (argc < 4) { + SCWrite(pCon, + "ERROR: need root, property name and target string for search", + eError); + return 0; + } + memset(buffer, 0, 1024); + Arg2Text(argc - 3, &argv[3], buffer, 1023); + root = GetHipadabaNode(GetHipadabaRoot(), argv[1]); + if (root == NULL) { + SCWrite(pCon, "ERROR: start node for search not found", eError); + return 0; + } + + strtolower(argv[2]); + strtolower(buffer); + foundNode = matchHdbProp(root, argv[2], buffer); + + if (foundNode == NULL) { + SCWrite(pCon, "NONE", eValue); + } else { + path = GetHipadabaPath(foundNode); + SCWrite(pCon, path, eValue); + free(path); + } + return 1; +} + /*======================= Factory Functions =================================*/ -void killSICSHipadaba(){ - if(root != NULL){ - DeleteHipadabaNode(root,NULL); - } - root = NULL; +void killSICSHipadaba() +{ + if (root != NULL) { + DeleteHipadabaNode(root, NULL); + } + root = NULL; } -/*---------------------------------------------------------------------------*/ -extern int HdbNodeFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); /* from sicshdbfactory.c */ -/*---------------------------------------------------------------------------*/ -int InstallSICSHipadaba(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - - root = MakeHipadabaNode("/",HIPNONE,0); - AddCommand(pSics,"hmake", MakeHdbNode, NULL, NULL); - AddCommand(pSics,"hfactory", HdbNodeFactory, NULL, NULL); - AddCommand(pSics,"hmakescript", MakeHdbScriptNode, NULL, NULL); - AddCommand(pSics,"hattach", SICSHdbAdapter, NULL, NULL); - AddCommand(pSics,"hsubsamplehm", HdbSubSample, NULL, NULL); - AddCommand(pSics,"hdel", DeleteHdbNode, NULL, NULL); - AddCommand(pSics,"hset", SetHdbNode, NULL, NULL); - AddCommand(pSics,"hupdate", UpdateHdbNode, NULL, NULL); - AddCommand(pSics,"hget", GetHdbNode, NULL, NULL); - AddCommand(pSics,"hval", GetHdbVal, NULL, NULL); - AddCommand(pSics,"hzipget",ZipGetHdbNode, NULL, NULL); - AddCommand(pSics,"hlist", ListHdbNode, NULL, NULL); - AddCommand(pSics,"hnotify", AutoNotifyHdbNode, NULL, NULL); - AddCommand(pSics,"hdelcb", RemoveHdbCallback, NULL, NULL); - AddCommand(pSics,"hlink", LinkHdbNode, NULL, NULL); - AddCommand(pSics,"hinfo", HdbNodeInfo, NULL, NULL); - AddCommand(pSics,"hval", HdbNodeVal, NULL, NULL); - AddCommand(pSics,"hchain", ChainHdbNode, NULL, NULL); - AddCommand(pSics,"hcommand",SicsCommandNode, NULL, NULL); - AddCommand(pSics,"hsetprop",SetSICSHdbProperty, NULL, NULL); - AddCommand(pSics,"hdelprop",DelSICSHdbProperty, NULL, NULL); - AddCommand(pSics,"hgetprop",GetSICSHdbProperty, NULL, NULL); - AddCommand(pSics,"hgetpropval",GetSICSHdbPropertyVal, NULL, NULL); - AddCommand(pSics,"hmatchprop",MatchHdbProperty, NULL, NULL); - AddCommand(pSics,"hlistprop",ListSICSHdbProperty, NULL, NULL); - InstallSICSPoll(pCon,pSics,pData,argc,argv); - poller = (pSicsPoll)FindCommandData(pSics,"sicspoll","SicsPoll"); +/*---------------------------------------------------------------------------*/ +extern int HdbNodeFactory(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]); /* from sicshdbfactory.c */ +/*---------------------------------------------------------------------------*/ +int InstallSICSHipadaba(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ - return 1; + root = MakeHipadabaNode("/", HIPNONE, 0); + AddCommand(pSics, "hmake", MakeHdbNode, NULL, NULL); + AddCommand(pSics, "hfactory", HdbNodeFactory, NULL, NULL); + AddCommand(pSics, "hmakescript", MakeHdbScriptNode, NULL, NULL); + AddCommand(pSics, "hattach", SICSHdbAdapter, NULL, NULL); + AddCommand(pSics, "hsubsamplehm", HdbSubSample, NULL, NULL); + AddCommand(pSics, "hdel", DeleteHdbNode, NULL, NULL); + AddCommand(pSics, "hset", SetHdbNode, NULL, NULL); + AddCommand(pSics, "hupdate", UpdateHdbNode, NULL, NULL); + AddCommand(pSics, "hget", GetHdbNode, NULL, NULL); + AddCommand(pSics, "hval", GetHdbVal, NULL, NULL); + AddCommand(pSics, "hzipget", ZipGetHdbNode, NULL, NULL); + AddCommand(pSics, "hlist", ListHdbNode, NULL, NULL); + AddCommand(pSics, "hnotify", AutoNotifyHdbNode, NULL, NULL); + AddCommand(pSics, "hdelcb", RemoveHdbCallback, NULL, NULL); + AddCommand(pSics, "hlink", LinkHdbNode, NULL, NULL); + AddCommand(pSics, "hinfo", HdbNodeInfo, NULL, NULL); + AddCommand(pSics, "hval", HdbNodeVal, NULL, NULL); + AddCommand(pSics, "hchain", ChainHdbNode, NULL, NULL); + AddCommand(pSics, "hcommand", SicsCommandNode, NULL, NULL); + AddCommand(pSics, "hsetprop", SetSICSHdbProperty, NULL, NULL); + AddCommand(pSics, "hdelprop", DelSICSHdbProperty, NULL, NULL); + AddCommand(pSics, "hgetprop", GetSICSHdbProperty, NULL, NULL); + AddCommand(pSics, "hgetpropval", GetSICSHdbPropertyVal, NULL, NULL); + AddCommand(pSics, "hmatchprop", MatchHdbProperty, NULL, NULL); + AddCommand(pSics, "hlistprop", ListSICSHdbProperty, NULL, NULL); + + InstallSICSPoll(pCon, pSics, pData, argc, argv); + poller = (pSicsPoll) FindCommandData(pSics, "sicspoll", "SicsPoll"); + + return 1; } diff --git a/sicshipadaba.h b/sicshipadaba.h index f4f770a5..e948b3d3 100644 --- a/sicshipadaba.h +++ b/sicshipadaba.h @@ -16,22 +16,22 @@ /*======================== callback error codes ===============================*/ #define SICSCBRO -607 #define SICSCBPERM -608 -#define SICSCBRANGE -609 +#define SICSCBRANGE -609 #define SICSCBBADFIXED -610 #define SICSNOPAR -611 /*======================== SICS Messages ======================================*/ typedef struct { - char *type; - int ID; -}hdbIDMessage, *pHdbIDMessage; + char *type; + int ID; +} hdbIDMessage, *pHdbIDMessage; /*------------------------------------------------------------------------------*/ pHdbIDMessage GetKillIDMessage(pHdbMessage message); pHdbIDMessage GetKillInternalIDMessage(pHdbMessage message); /*-----------------------------------------------------------------------------*/ typedef struct { - char *type; - void *pPtr; -}hdbPtrMessage, *pHdbPtrMessage; + char *type; + void *pPtr; +} hdbPtrMessage, *pHdbPtrMessage; /*-----------------------------------------------------------------------------*/ pHdbPtrMessage GetKillPtrMessage(pHdbMessage message); pHdbMessage GetHdbStartMessage(pHdbMessage message); @@ -39,10 +39,10 @@ pHdbMessage GetHdbStopMessage(pHdbMessage message); void SendHdbStatusMessage(pHdb node, char *status); /*======================== data structure for automatic parameter update =======*/ typedef struct { - SConnection *pCon; - int updateList; - int iEnd; -}hdbUpdateTask, *pHdbUpdateTask; + SConnection *pCon; + int updateList; + int iEnd; +} hdbUpdateTask, *pHdbUpdateTask; /*======================== common callbacks =====================================*/ /** * make a ReadOnly callback @@ -93,7 +93,7 @@ pHdbCallback MakeSICSReadDriveCallback(void *sicsObject); * @return a suitably initialized callback structure for * automatic notification. */ -pHdbCallback MakeNotifyCallback(SConnection *pCon, int id); +pHdbCallback MakeNotifyCallback(SConnection * pCon, int id); /** * make a callback for checking if a parameter is within a given * range of integers @@ -142,13 +142,13 @@ pHdbCallback MakeMemSetCallback(float *address); * @param pCon The connection to notfy on tree chnages * @param id The ID of this callback * @return a suitable callback for notififications about tree changes. - */ - pHdbCallback MakeTreeChangeCallback(SConnection *pCon, int id); + */ +pHdbCallback MakeTreeChangeCallback(SConnection * pCon, int id); /** * make a clalback to invoke a function node */ - pHdbCallback MakeSICSFuncCallback(void *obj); - +pHdbCallback MakeSICSFuncCallback(void *obj); + /*======================== parameter creation ===================================*/ /** * make a simple SICS hdb parameter. Setting it will call update immediately. Use @@ -169,7 +169,7 @@ pHdb MakeSICSHdbPar(char *name, int priv, hdbValue v); * @param datatype The datatype of this variable * @return A new suitably configured Hdb parameter or NULL when out of memory. */ -pHdb MakeSICSHdbDriv(char *name, int priv,void *sicsObject, int datatype); +pHdb MakeSICSHdbDriv(char *name, int priv, void *sicsObject, int datatype); /** * make SICS hdb variable which is connected to a memory location, perhaps in * an objects data structure. @@ -183,7 +183,7 @@ pHdb MakeSICSMemPar(char *name, int priv, float *address); * @param name The name of the parameter * @param v The initial value and datatype of this parameter * @return A new suitably configured Hdb parameter or NULL when out of memory. - */ + */ pHdb MakeSICSROPar(char *name, hdbValue v); /** * make a SICS scriptable parameter. I.e. when this parameter is set or read, @@ -194,7 +194,8 @@ pHdb MakeSICSROPar(char *name, hdbValue v); * @param v The initial value and datatype of this parameter * @return A new suitably configured Hdb parameter or NULL when out of memory. */ -pHdb MakeSICSScriptPar(char *name, char *setScript, char *readScript, hdbValue v); +pHdb MakeSICSScriptPar(char *name, char *setScript, char *readScript, + hdbValue v); /** * remove a SICS paramameter node and its children. In contrast to the @@ -238,7 +239,7 @@ pHdb AddSICSHdbROPar(pHdb parent, char *name, hdbValue v); * @return the created node on success, NULL else */ pHdb AddSICSHdbMemPar(pHdb parent, char *name, int priv, - void *data, int datalength, int type, int length); + void *data, int datalength, int type, int length); /*============== access support functions =================================*/ /** Find the parent of a node to be created * @param rootpath the root path (where to start). May be NULL for absolute paths @@ -256,7 +257,8 @@ pHdb AddSICSHdbMemPar(pHdb parent, char *name, int priv, * Nodes anchored in the sics object list are also found when * the path starts with "/sics/" */ -pHdb FindHdbParent(char *rootpath, char *relpath, char **namePtr, SConnection *pCon); +pHdb FindHdbParent(char *rootpath, char *relpath, char **namePtr, + SConnection * pCon); /** FindHdbNode finds a node * @param rootpath the root path (where to start). May be NULL for absolute paths. * @param relpath an absolute or relative path @@ -269,7 +271,7 @@ pHdb FindHdbParent(char *rootpath, char *relpath, char **namePtr, SConnection *p * Nodes anchored in the sics object list are also found when * the path starts with "/sics/" */ -pHdb FindHdbNode(char *rootpath, char *relpath, SConnection *pCon); +pHdb FindHdbNode(char *rootpath, char *relpath, SConnection * pCon); /** Get the absolute path of a node anchored in the * Hipadaba root or in a sics object * @param nodeArg the input node @@ -289,8 +291,8 @@ void RemoveSICSInternalCallback(void *internalID); * @param path The path to the parameter. * @param v the value * @return 1 on success, a negative error code else. - */ -int SICSHdbGetPar(void *obj, SConnection *pCon, char *path, hdbValue *v); + */ +int SICSHdbGetPar(void *obj, SConnection * pCon, char *path, hdbValue * v); /** * SICSHdbUpdatePar updates the value of a parameter. * @param obj The object for which to get a parameter. @@ -298,8 +300,9 @@ int SICSHdbGetPar(void *obj, SConnection *pCon, char *path, hdbValue *v); * @param path The path to the parameter. * @param v the value * @return 1 on success, a negative error code else. - */ -int SICSHdbUpdatePar(void *obj, SConnection *pCon, char *path, hdbValue v); + */ +int SICSHdbUpdatePar(void *obj, SConnection * pCon, char *path, + hdbValue v); /** * SICSHdbSetPar sets the value of a parameter. * @param obj The object for which to set a parameter. @@ -307,14 +310,14 @@ int SICSHdbUpdatePar(void *obj, SConnection *pCon, char *path, hdbValue v); * @param path The path to the parameter. * @param v the value * @return positive on success, a negative error code else. - */ -int SICSHdbSetPar(void *obj, SConnection *pCon, char *path, hdbValue v); + */ +int SICSHdbSetPar(void *obj, SConnection * pCon, char *path, hdbValue v); /** * query function if a parameter is read only. * @param node The ndoe to query * @return 1 when RO, 0 else */ -int isSICSHdbRO(pHdb node); +int isSICSHdbRO(pHdb node); /*============= common SICS Interactions ===================================*/ /** * Install a SICS automatic notification callback on the node. This is @@ -328,13 +331,13 @@ int isSICSHdbRO(pHdb node); * installed to all nodes recursively. * @return 1 on success, 0 when out of memory. */ -int InstallSICSNotify(pHdb node, SConnection *pCon, int id, int recurse); +int InstallSICSNotify(pHdb node, SConnection * pCon, int id, int recurse); /** * remove all Callbacks associated with a given conenction * @param root Where to start removing callbacks * @param pCon The connection for which to remove callbacks - */ -void RemoveConnectionCallbacks(pHdb root, SConnection *pCon); + */ +void RemoveConnectionCallbacks(pHdb root, SConnection * pCon); /** * handles the common task of checking for, and processing a SICS parameter. * @param root The node at which to search for parameters @@ -345,17 +348,17 @@ void RemoveConnectionCallbacks(pHdb root, SConnection *pCon); * @param argv The arguments to process. argv[0] should be the parameter * name. * @return -1 when argv[0] is no parameter, 0 on failure, 1 on success. - */ -int ProcessSICSHdbPar(pHdb root, SConnection *pCon, char *printPrefix, - int argc, char *argv[]); + */ +int ProcessSICSHdbPar(pHdb root, SConnection * pCon, char *printPrefix, + int argc, char *argv[]); /** * print a listing of the parameters of node to pCon, using the * specified prefix. * @param node The node to print * @param pCon The connection to print to * @param prefix The prefix to use for printing - */ -void PrintSICSParList(pHdb node, SConnection *pCon, char *prefix); + */ +void PrintSICSParList(pHdb node, SConnection * pCon, char *prefix); /** * save the content of the Hipadaba starting at node into a file. This can * be used to save the configuration of an instrument. This routine is @@ -363,8 +366,8 @@ void PrintSICSParList(pHdb node, SConnection *pCon, char *prefix); * @param fd The file to write to * @param node The node to print from * @param prefix A prefix to use for printing. - */ -void SaveSICSHipadaba(FILE *fd, pHdb node, char *prefix); + */ +void SaveSICSHipadaba(FILE * fd, pHdb node, char *prefix); /** * A SICS task which scans a Hipadaba and reads and updates all parameters, * one per invocation. TODO: how to distinguish between automatic pars which @@ -382,7 +385,7 @@ void SICSHipadabaSignal(void *pData, int iSignal, void *pSigData); * @param node The Hdb node (for format property) * @return a dynamic string holding the formatted data. NULL when * out of memory - */ + */ pDynString formatValue(hdbValue v, pHdb node); /** * read values for a Hdb value from a string. @@ -394,7 +397,7 @@ pDynString formatValue(hdbValue v, pHdb node); * @param errlen The length of the error string * @return 0 on failure, 1 on success */ -int readHdbValue(hdbValue *v, char *data, char *error, int errlen); +int readHdbValue(hdbValue * v, char *data, char *error, int errlen); /** * convert from test to a Hipadaba type * @param text The type text @@ -419,16 +422,16 @@ hdbValue MakeSICSFunc(SICSOBJFunc func); * @param argv[] The text arguments * @return 0 on filaure, 1 on success */ -int InstallSICSHipadaba(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int InstallSICSHipadaba(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); /** * get the root of the SICS Hipadaba tree * @return The root node of the hipdaba - */ -pHdb GetHipadabaRoot(); + */ +pHdb GetHipadabaRoot(); /** * kill the SICS hierarchical database * Only to be called when shutting down the SICServer */ -void killSICSHipadaba(void); -#endif /*SICSHIPADABA_H_*/ +void killSICSHipadaba(void); +#endif /*SICSHIPADABA_H_ */ diff --git a/sicslist.c b/sicslist.c index 52bfe9d0..9da82d6a 100644 --- a/sicslist.c +++ b/sicslist.c @@ -14,519 +14,544 @@ #include "lld.h" #include "lld_str.h" /*------------------------------------------------------------------*/ -static void listAllObjects(SConnection *pCon, SicsInterp *pSics){ - CommandList *pCom = NULL; - Tcl_DString lst; - - Tcl_DStringInit(&lst); - - pCom = pSics->pCList; - while(pCom != NULL){ - Tcl_DStringAppend(&lst,pCom->pName,-1); - pCom = pCom->pNext; - Tcl_DStringAppend(&lst, ",",-1); - } - Tcl_DStringAppend(&lst,"ENDLIST",-1); - SCWrite(pCon,Tcl_DStringValue(&lst), eValue); - Tcl_DStringFree(&lst); +static void listAllObjects(SConnection * pCon, SicsInterp * pSics) +{ + CommandList *pCom = NULL; + Tcl_DString lst; + + Tcl_DStringInit(&lst); + + pCom = pSics->pCList; + while (pCom != NULL) { + Tcl_DStringAppend(&lst, pCom->pName, -1); + pCom = pCom->pNext; + Tcl_DStringAppend(&lst, ",", -1); + } + Tcl_DStringAppend(&lst, "ENDLIST", -1); + SCWrite(pCon, Tcl_DStringValue(&lst), eValue); + Tcl_DStringFree(&lst); } + /*------------------------------------------------------------------*/ -static void listAllObjectData(SConnection *pCon, char *name, pDummy data){ - Tcl_DString lst; - char buffer[256]; - IPair *prop = NULL; - - Tcl_DStringInit(&lst); - if(data == NULL){ - snprintf(buffer,255,"%s = command, ", name); - Tcl_DStringAppend(&lst,buffer,-1); +static void listAllObjectData(SConnection * pCon, char *name, pDummy data) +{ + Tcl_DString lst; + char buffer[256]; + IPair *prop = NULL; + + Tcl_DStringInit(&lst); + if (data == NULL) { + snprintf(buffer, 255, "%s = command, ", name); + Tcl_DStringAppend(&lst, buffer, -1); + } else { + snprintf(buffer, 255, "%s=obj, ", name); + Tcl_DStringAppend(&lst, buffer, -1); + snprintf(buffer, 255, "type=%s, ", data->pDescriptor->name); + Tcl_DStringAppend(&lst, buffer, -1); + if (data->pDescriptor->GetInterface(data, DRIVEID) != NULL) { + snprintf(buffer, 255, "drivable=true, "); } else { - snprintf(buffer,255,"%s=obj, ", name); - Tcl_DStringAppend(&lst,buffer,-1); - snprintf(buffer,255,"type=%s, ",data->pDescriptor->name); - Tcl_DStringAppend(&lst,buffer,-1); - if(data->pDescriptor->GetInterface(data,DRIVEID) != NULL){ - snprintf(buffer,255,"drivable=true, "); - } else { - snprintf(buffer,255,"drivable=false, "); - } - Tcl_DStringAppend(&lst,buffer,-1); - if(data->pDescriptor->GetInterface(data,COUNTID) != NULL){ - snprintf(buffer,255,"countable=true, "); - } else { - snprintf(buffer,255,"countable=false, "); - } - Tcl_DStringAppend(&lst,buffer,-1); - if(data->pDescriptor->GetInterface(data,CALLBACKINTERFACE) != NULL){ - snprintf(buffer,255,"callback=true, "); - } else { - snprintf(buffer,255,"callback=false, "); - } - Tcl_DStringAppend(&lst,buffer,-1); - if(data->pDescriptor->GetInterface(data,ENVIRINTERFACE) != NULL){ - snprintf(buffer,255,"environment=true, "); - } else { - snprintf(buffer,255,"environment=false, "); - } - Tcl_DStringAppend(&lst,buffer,-1); - prop = data->pDescriptor->pKeys; - while(prop != NULL){ - snprintf(buffer,255,"%s=%s, ",prop->name,prop->value); - Tcl_DStringAppend(&lst,buffer,-1); - prop = prop->pNext; - } + snprintf(buffer, 255, "drivable=false, "); } - Tcl_DStringAppend(&lst,"ENDLIST",-1); - SCWrite(pCon,Tcl_DStringValue(&lst),eValue); - Tcl_DStringFree(&lst); + Tcl_DStringAppend(&lst, buffer, -1); + if (data->pDescriptor->GetInterface(data, COUNTID) != NULL) { + snprintf(buffer, 255, "countable=true, "); + } else { + snprintf(buffer, 255, "countable=false, "); + } + Tcl_DStringAppend(&lst, buffer, -1); + if (data->pDescriptor->GetInterface(data, CALLBACKINTERFACE) != NULL) { + snprintf(buffer, 255, "callback=true, "); + } else { + snprintf(buffer, 255, "callback=false, "); + } + Tcl_DStringAppend(&lst, buffer, -1); + if (data->pDescriptor->GetInterface(data, ENVIRINTERFACE) != NULL) { + snprintf(buffer, 255, "environment=true, "); + } else { + snprintf(buffer, 255, "environment=false, "); + } + Tcl_DStringAppend(&lst, buffer, -1); + prop = data->pDescriptor->pKeys; + while (prop != NULL) { + snprintf(buffer, 255, "%s=%s, ", prop->name, prop->value); + Tcl_DStringAppend(&lst, buffer, -1); + prop = prop->pNext; + } + } + Tcl_DStringAppend(&lst, "ENDLIST", -1); + SCWrite(pCon, Tcl_DStringValue(&lst), eValue); + Tcl_DStringFree(&lst); } + /*------------------------------------------------------------------*/ -static int getObjectData(pDummy obj, char *key, char buffer[512]){ - char *ptr = NULL; - void *iPtr = NULL; - int status = 0; - - /* - * first check attributes - */ - ptr = IFindOption(obj->pDescriptor->pKeys,key); - if(ptr != NULL){ - snprintf(buffer,511,"%s",ptr); - return 1; - } - /* - * check indirect attributes - */ - strtolower(key); - if(strcmp(key,"type") == 0){ - snprintf(buffer,511,"%s",obj->pDescriptor->name); - return 1; - } else if(strcmp(key,"drivable") == 0){ - iPtr = obj->pDescriptor->GetInterface(obj,DRIVEID); - if(iPtr != NULL){ - status = 1; - snprintf(buffer,511,"true"); - } else { - status = 0; - snprintf(buffer,511,"false"); - } - } else if(strcmp(key,"countable") == 0){ - iPtr = obj->pDescriptor->GetInterface(obj,COUNTID); - if(iPtr != NULL){ - status = 1; - snprintf(buffer,511,"true"); - } else { - status = 0; - snprintf(buffer,511,"false"); - } - } else if(strcmp(key,"callback") == 0){ - iPtr = obj->pDescriptor->GetInterface(obj,CALLBACKINTERFACE); - if(iPtr != NULL){ - status = 1; - snprintf(buffer,511,"true"); - } else { - status = 0; - snprintf(buffer,511,"false"); - } - } else if(strcmp(key,"environment") == 0){ - iPtr = obj->pDescriptor->GetInterface(obj,ENVIRINTERFACE); - if(iPtr != NULL){ - status = 1; - snprintf(buffer,511,"true"); - } else { - status = 0; - snprintf(buffer,511,"false"); - } - } else { - return -1; - } - return status; +static int getObjectData(pDummy obj, char *key, char buffer[512]) +{ + char *ptr = NULL; + void *iPtr = NULL; + int status = 0; + + /* + * first check attributes + */ + ptr = IFindOption(obj->pDescriptor->pKeys, key); + if (ptr != NULL) { + snprintf(buffer, 511, "%s", ptr); + return 1; + } + /* + * check indirect attributes + */ + strtolower(key); + if (strcmp(key, "type") == 0) { + snprintf(buffer, 511, "%s", obj->pDescriptor->name); + return 1; + } else if (strcmp(key, "drivable") == 0) { + iPtr = obj->pDescriptor->GetInterface(obj, DRIVEID); + if (iPtr != NULL) { + status = 1; + snprintf(buffer, 511, "true"); + } else { + status = 0; + snprintf(buffer, 511, "false"); + } + } else if (strcmp(key, "countable") == 0) { + iPtr = obj->pDescriptor->GetInterface(obj, COUNTID); + if (iPtr != NULL) { + status = 1; + snprintf(buffer, 511, "true"); + } else { + status = 0; + snprintf(buffer, 511, "false"); + } + } else if (strcmp(key, "callback") == 0) { + iPtr = obj->pDescriptor->GetInterface(obj, CALLBACKINTERFACE); + if (iPtr != NULL) { + status = 1; + snprintf(buffer, 511, "true"); + } else { + status = 0; + snprintf(buffer, 511, "false"); + } + } else if (strcmp(key, "environment") == 0) { + iPtr = obj->pDescriptor->GetInterface(obj, ENVIRINTERFACE); + if (iPtr != NULL) { + status = 1; + snprintf(buffer, 511, "true"); + } else { + status = 0; + snprintf(buffer, 511, "false"); + } + } else { + return -1; + } + return status; } + /*-----------------------------------------------------------------*/ -static int printObjectData(SConnection *pCon, pDummy obj, char *key){ - char value[512]; - char buffer[1024]; - int status; - - status = getObjectData(obj,key,value); - if(status >= 0){ - snprintf(buffer,1023,"%s=%s",key,value); - } else { - snprintf(buffer,1023,"%s=UNDEFINED",key); - } - SCWrite(pCon,buffer,eValue); - if(status < 0){ - return 0; - } else { - return 1; - } +static int printObjectData(SConnection * pCon, pDummy obj, char *key) +{ + char value[512]; + char buffer[1024]; + int status; + + status = getObjectData(obj, key, value); + if (status >= 0) { + snprintf(buffer, 1023, "%s=%s", key, value); + } else { + snprintf(buffer, 1023, "%s=UNDEFINED", key); + } + SCWrite(pCon, buffer, eValue); + if (status < 0) { + return 0; + } else { + return 1; + } } + /*----------------------------------------------------------------- * this function implements a set on top of a list. This means that * the list is first searched for the occurence of name. name is only * added when it does not exist in list - * ----------------------------------------------------------------*/ -static void addItemToList(int list, char *name){ - int status; - char *pPtr = NULL; - - status = LLDnodePtr2First(list); - while(status != 0){ - pPtr = (char *)LLDnodePtr(list); - if(pPtr != NULL){ - if(strcmp(pPtr,name) == 0){ - return; - } - } - status = LLDnodePtr2Next(list); - } - LLDstringAppend(list,name); -} -/*-----------------------------------------------------------------*/ -static void listToString(int list,Tcl_DString *txt){ - int status; - char *pPtr = NULL; - - status = LLDnodePtr2First(list); - while(status != 0){ - pPtr = (char *)LLDnodePtr(list); - if(pPtr != NULL){ - Tcl_DStringAppend(txt,pPtr,-1); - Tcl_DStringAppend(txt, ",",-1); - } - status = LLDnodePtr2Next(list); - } -} -/*----------------------------------------------------------------*/ -static void printKeyTypes(SicsInterp *pSics, SConnection *pCon, - char *key){ - CommandList *pCom = NULL; - int list; - int status; - char value[512]; - Tcl_DString result; - - if(strcmp(key,"interface") == 0){ - SCWrite(pCon,"drivable, countable, callback, environment",eValue); + * ----------------------------------------------------------------*/ +static void addItemToList(int list, char *name) +{ + int status; + char *pPtr = NULL; + + status = LLDnodePtr2First(list); + while (status != 0) { + pPtr = (char *) LLDnodePtr(list); + if (pPtr != NULL) { + if (strcmp(pPtr, name) == 0) { return; + } } - - list = LLDstringCreate(); - Tcl_DStringInit(&result); - pCom = pSics->pCList; - while(pCom != NULL){ - status = getObjectData((pDummy)pCom->pData,key,value); - if(status >= 0){ - addItemToList(list,value); - } - pCom = pCom->pNext; - } - LLDstringAppend(list,"ENDLIST"); - - listToString(list,&result); - SCWrite(pCon,Tcl_DStringValue(&result),eValue); - Tcl_DStringFree(&result); - LLDstringDelete(list); + status = LLDnodePtr2Next(list); + } + LLDstringAppend(list, name); } -/*----------------------------------------------------------------*/ -static void printObjectsMatchingKeyVal(SicsInterp *pSics, - SConnection *pCon,char *key, char *value){ - CommandList *pCom = NULL; - Tcl_DString result; - int status; - char buffer[512]; - - Tcl_DStringInit(&result); - pCom = pSics->pCList; - strtolower(value); - while(pCom != NULL){ - if(strcmp(key,"interface") == 0){ - status = getObjectData((pDummy)pCom->pData,value, - buffer); - } else { - status = getObjectData((pDummy)pCom->pData,key, - buffer); - if(status == 1){ - strtolower(buffer); - if(strcmp(buffer,value) == 0){ - status = 1; - } else { - status = 0; - } - } - } - if(status == 1){ - Tcl_DStringAppend(&result,pCom->pName,-1); - Tcl_DStringAppend(&result, ",",-1); - } - pCom = pCom->pNext; + +/*-----------------------------------------------------------------*/ +static void listToString(int list, Tcl_DString * txt) +{ + int status; + char *pPtr = NULL; + + status = LLDnodePtr2First(list); + while (status != 0) { + pPtr = (char *) LLDnodePtr(list); + if (pPtr != NULL) { + Tcl_DStringAppend(txt, pPtr, -1); + Tcl_DStringAppend(txt, ",", -1); } - Tcl_DStringAppend(&result,"ENDLIST",-1); - SCWrite(pCon,Tcl_DStringValue(&result),eValue); - Tcl_DStringFree(&result); -} + status = LLDnodePtr2Next(list); + } +} + /*----------------------------------------------------------------*/ -static int setAttribute(SConnection *pCon, SicsInterp *pSics, - char *obj, char *key, char *value){ - CommandList *pCom = NULL; - pDummy pDum = NULL; +static void printKeyTypes(SicsInterp * pSics, SConnection * pCon, + char *key) +{ + CommandList *pCom = NULL; + int list; + int status; + char value[512]; + Tcl_DString result; - if(!SCMatchRights(pCon,usMugger)){ - return 0; + if (strcmp(key, "interface") == 0) { + SCWrite(pCon, "drivable, countable, callback, environment", eValue); + return; + } + + list = LLDstringCreate(); + Tcl_DStringInit(&result); + pCom = pSics->pCList; + while (pCom != NULL) { + status = getObjectData((pDummy) pCom->pData, key, value); + if (status >= 0) { + addItemToList(list, value); } - - strtolower(key); - if(strcmp(key,"type") == 0 || strcmp(key,"interface") == 0){ - SCWrite(pCon,"ERROR: this key is forbidden",eError); - return 0; - } - - pCom = FindCommand(pSics, obj); - if(pCom == NULL){ - SCWrite(pCon,"ERROR: object not found",eError); - return 0; - } - pDum = (pDummy)pCom->pData; - - if(pDum != NULL){ - if(IFindOption(pDum->pDescriptor->pKeys,key) == NULL){ - pDum->pDescriptor->pKeys = IFAddOption(pDum->pDescriptor->pKeys, - key,value); + pCom = pCom->pNext; + } + LLDstringAppend(list, "ENDLIST"); + + listToString(list, &result); + SCWrite(pCon, Tcl_DStringValue(&result), eValue); + Tcl_DStringFree(&result); + LLDstringDelete(list); +} + +/*----------------------------------------------------------------*/ +static void printObjectsMatchingKeyVal(SicsInterp * pSics, + SConnection * pCon, char *key, + char *value) +{ + CommandList *pCom = NULL; + Tcl_DString result; + int status; + char buffer[512]; + + Tcl_DStringInit(&result); + pCom = pSics->pCList; + strtolower(value); + while (pCom != NULL) { + if (strcmp(key, "interface") == 0) { + status = getObjectData((pDummy) pCom->pData, value, buffer); + } else { + status = getObjectData((pDummy) pCom->pData, key, buffer); + if (status == 1) { + strtolower(buffer); + if (strcmp(buffer, value) == 0) { + status = 1; } else { - IFSetOption(pDum->pDescriptor->pKeys,key,value); + status = 0; } + } } - SCSendOK(pCon); - - return 1; + if (status == 1) { + Tcl_DStringAppend(&result, pCom->pName, -1); + Tcl_DStringAppend(&result, ",", -1); + } + pCom = pCom->pNext; + } + Tcl_DStringAppend(&result, "ENDLIST", -1); + SCWrite(pCon, Tcl_DStringValue(&result), eValue); + Tcl_DStringFree(&result); } -/*-----------------------------------------------------------------*/ -static int printObjStatus(SConnection *pCon, SicsInterp *pSics, - char *name){ - CommandList *pCom = NULL; - pDummy pDum = NULL; - pIDrivable pDriv = NULL; - pICountable pCount = NULL; - pEVInterface pEV = NULL; - int status = -1, evStatus = -1; - char buffer[256]; - - pCom = FindCommand(pSics,name); - if(pCom == NULL){ - SCWrite(pCon,"ERROR: object not found",eError); - return 0; - } - pDum = (pDummy)pCom->pData; - if(pDum != NULL){ - pDriv = GetDrivableInterface(pDum); - if(pDriv != NULL){ - status = pDriv->CheckStatus(pDum,pCon); - } - pCount = GetCountableInterface(pDum); - if(pCount != NULL){ - status = pCount->CheckCountStatus(pDum,pCon); - } - pEV = pDum->pDescriptor->GetInterface(pDum,ENVIRINTERFACE); - if(pEV != NULL){ - evStatus = pEV->IsInTolerance(pDum); - } - } - switch(status){ - case HWBusy: - snprintf(buffer,255,"%s = running",pCom->pName); - break; - case HWIdle: - case OKOK: - if(evStatus < 0){ - snprintf(buffer,255,"%s = idle",pCom->pName); - } else if(evStatus == 1){ - snprintf(buffer,255,"%s = intolerance",pCom->pName); - } else { - snprintf(buffer,255,"%s = outoftolerance",pCom->pName); - } - break; - case HWFault: - case HWPosFault: - snprintf(buffer,255,"%s = faulty",pCom->pName); - break; - case HWPause: - snprintf(buffer,255,"%s = paused",pCom->pName); - break; - case HWNoBeam: - snprintf(buffer,255,"%s = nobeam",pCom->pName); - break; - default: - snprintf(buffer,255,"%s = nostatus",pCom->pName); - break; - } - SCWrite(pCon,buffer,eValue); - return 1; -} -/*-----------------------------------------------------------------*/ -static int printServer(SConnection *pCon){ - Tcl_DString txt; - IPair *current = NULL; - char buffer[512]; - - Tcl_DStringInit(&txt); - current = pSICSOptions; - while(current != NULL){ - snprintf(buffer,511,"%s=%s, ",current->name,current->value); - Tcl_DStringAppend(&txt,buffer,-1); - current = current->pNext; - } - Tcl_DStringAppend(&txt,"ENDLIST",-1); - SCWrite(pCon,Tcl_DStringValue(&txt),eValue); - Tcl_DStringFree(&txt); - return 1; -} -/*------------------------------------------------------------------*/ -static int printObjectPar(SConnection *pCon,SicsInterp *pSics, char *obj){ - CommandList *pCom = NULL; - FILE *fd = NULL; - char *buffer = NULL, tmpfile[80]; - pDummy pDum = NULL; - long length; - struct stat statbuf; - - snprintf(tmpfile,80,"SICS%6.6d.dat",getpid()); - pCom = FindCommand(pSics, obj); - if(pCom == NULL){ - SCWrite(pCon,"ERROR: object to list not found",eError); - return 0; - } - fd = fopen(tmpfile,"w"); - if(fd == NULL){ - SCWrite(pCon,"ERROR: failed to open tmpfile",eError); - return 0; - } - pDum = (pDummy)pCom->pData; - if(pDum != NULL){ - pDum->pDescriptor->SaveStatus(pDum, obj, fd); - fclose(fd); - stat(tmpfile, &statbuf); - length = statbuf.st_size; - fd = fopen(tmpfile,"r"); - if(fd == NULL){ - SCWrite(pCon,"ERROR: failed to open tmpfile",eError); - return 0; - } - buffer = malloc(length+1); - if(buffer == NULL){ - SCWrite(pCon,"ERROR: out of memory in list par",eError); - fclose(fd); - unlink(tmpfile); - return 0; - } - memset(buffer,0,length+1); - fread(buffer,length,1,fd); - fclose(fd); - SCWrite(pCon,buffer,eValue); - free(buffer); - unlink(tmpfile); - return 1; - } - return 0; -} -/*-----------------------------------------------------------------*/ -extern int match(const char *mask, const char *name); /* from wwildcard.c */ -static void printMatch(SConnection *pCon, SicsInterp *pSics, - char *mask){ - CommandList *current = NULL; - Tcl_DString txt; - - Tcl_DStringInit(&txt); - current = pSics->pCList; - while(current != NULL){ - if(!match(mask,current->pName)){ - Tcl_DStringAppend(&txt, current->pName,-1); - Tcl_DStringAppend(&txt, ",",-1); - } - current = current->pNext; +/*----------------------------------------------------------------*/ +static int setAttribute(SConnection * pCon, SicsInterp * pSics, + char *obj, char *key, char *value) +{ + CommandList *pCom = NULL; + pDummy pDum = NULL; + + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + strtolower(key); + if (strcmp(key, "type") == 0 || strcmp(key, "interface") == 0) { + SCWrite(pCon, "ERROR: this key is forbidden", eError); + return 0; + } + + pCom = FindCommand(pSics, obj); + if (pCom == NULL) { + SCWrite(pCon, "ERROR: object not found", eError); + return 0; + } + pDum = (pDummy) pCom->pData; + + if (pDum != NULL) { + if (IFindOption(pDum->pDescriptor->pKeys, key) == NULL) { + pDum->pDescriptor->pKeys = IFAddOption(pDum->pDescriptor->pKeys, + key, value); + } else { + IFSetOption(pDum->pDescriptor->pKeys, key, value); } - Tcl_DStringAppend(&txt,"ENDLIST",-1); - SCWrite(pCon,Tcl_DStringValue(&txt), eValue); - Tcl_DStringFree(&txt); + } + SCSendOK(pCon); + + return 1; +} + +/*-----------------------------------------------------------------*/ +static int printObjStatus(SConnection * pCon, SicsInterp * pSics, + char *name) +{ + CommandList *pCom = NULL; + pDummy pDum = NULL; + pIDrivable pDriv = NULL; + pICountable pCount = NULL; + pEVInterface pEV = NULL; + int status = -1, evStatus = -1; + char buffer[256]; + + pCom = FindCommand(pSics, name); + if (pCom == NULL) { + SCWrite(pCon, "ERROR: object not found", eError); + return 0; + } + pDum = (pDummy) pCom->pData; + if (pDum != NULL) { + pDriv = GetDrivableInterface(pDum); + if (pDriv != NULL) { + status = pDriv->CheckStatus(pDum, pCon); + } + pCount = GetCountableInterface(pDum); + if (pCount != NULL) { + status = pCount->CheckCountStatus(pDum, pCon); + } + pEV = pDum->pDescriptor->GetInterface(pDum, ENVIRINTERFACE); + if (pEV != NULL) { + evStatus = pEV->IsInTolerance(pDum); + } + } + switch (status) { + case HWBusy: + snprintf(buffer, 255, "%s = running", pCom->pName); + break; + case HWIdle: + case OKOK: + if (evStatus < 0) { + snprintf(buffer, 255, "%s = idle", pCom->pName); + } else if (evStatus == 1) { + snprintf(buffer, 255, "%s = intolerance", pCom->pName); + } else { + snprintf(buffer, 255, "%s = outoftolerance", pCom->pName); + } + break; + case HWFault: + case HWPosFault: + snprintf(buffer, 255, "%s = faulty", pCom->pName); + break; + case HWPause: + snprintf(buffer, 255, "%s = paused", pCom->pName); + break; + case HWNoBeam: + snprintf(buffer, 255, "%s = nobeam", pCom->pName); + break; + default: + snprintf(buffer, 255, "%s = nostatus", pCom->pName); + break; + } + SCWrite(pCon, buffer, eValue); + return 1; +} + +/*-----------------------------------------------------------------*/ +static int printServer(SConnection * pCon) +{ + Tcl_DString txt; + IPair *current = NULL; + char buffer[512]; + + Tcl_DStringInit(&txt); + current = pSICSOptions; + while (current != NULL) { + snprintf(buffer, 511, "%s=%s, ", current->name, current->value); + Tcl_DStringAppend(&txt, buffer, -1); + current = current->pNext; + } + Tcl_DStringAppend(&txt, "ENDLIST", -1); + SCWrite(pCon, Tcl_DStringValue(&txt), eValue); + Tcl_DStringFree(&txt); + return 1; +} + +/*------------------------------------------------------------------*/ +static int printObjectPar(SConnection * pCon, SicsInterp * pSics, + char *obj) +{ + CommandList *pCom = NULL; + FILE *fd = NULL; + char *buffer = NULL, tmpfile[80]; + pDummy pDum = NULL; + long length; + struct stat statbuf; + + snprintf(tmpfile, 80, "SICS%6.6d.dat", getpid()); + pCom = FindCommand(pSics, obj); + if (pCom == NULL) { + SCWrite(pCon, "ERROR: object to list not found", eError); + return 0; + } + fd = fopen(tmpfile, "w"); + if (fd == NULL) { + SCWrite(pCon, "ERROR: failed to open tmpfile", eError); + return 0; + } + pDum = (pDummy) pCom->pData; + if (pDum != NULL) { + pDum->pDescriptor->SaveStatus(pDum, obj, fd); + fclose(fd); + stat(tmpfile, &statbuf); + length = statbuf.st_size; + fd = fopen(tmpfile, "r"); + if (fd == NULL) { + SCWrite(pCon, "ERROR: failed to open tmpfile", eError); + return 0; + } + buffer = malloc(length + 1); + if (buffer == NULL) { + SCWrite(pCon, "ERROR: out of memory in list par", eError); + fclose(fd); + unlink(tmpfile); + return 0; + } + memset(buffer, 0, length + 1); + fread(buffer, length, 1, fd); + fclose(fd); + SCWrite(pCon, buffer, eValue); + free(buffer); + unlink(tmpfile); + return 1; + } + return 0; +} + +/*-----------------------------------------------------------------*/ +extern int match(const char *mask, const char *name); /* from wwildcard.c */ + +static void printMatch(SConnection * pCon, SicsInterp * pSics, char *mask) +{ + CommandList *current = NULL; + Tcl_DString txt; + + Tcl_DStringInit(&txt); + current = pSics->pCList; + while (current != NULL) { + if (!match(mask, current->pName)) { + Tcl_DStringAppend(&txt, current->pName, -1); + Tcl_DStringAppend(&txt, ",", -1); + } + current = current->pNext; + } + Tcl_DStringAppend(&txt, "ENDLIST", -1); + SCWrite(pCon, Tcl_DStringValue(&txt), eValue); + Tcl_DStringFree(&txt); } /*==================================================================*/ -int SicsList(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - CommandList *pCom = NULL; - - if(argc < 2){ - listAllObjects(pCon,pSics); - return 1; - } +int SicsList(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL; - if(strcmp(argv[1],"objstatus") == 0){ - if(argc < 3){ - SCWrite(pCon,"ERROR: Insufficient number of arguments to status", - eError); - return 0; - } - return printObjStatus(pCon,pSics,argv[2]); - } - - if(strcmp(argv[1],"server") == 0){ - printServer(pCon); - return 1; - } - - if(strcmp(argv[1],"par") == 0){ - if(argc > 2) { - return printObjectPar(pCon,pSics, argv[2]); - } else { - SCWrite(pCon,"ERROR: not enough arguments to list par",eError); - return 0; - } - } - - if(strcmp(argv[1],"match") == 0){ - if(argc > 2) { - printMatch(pCon,pSics, argv[2]); - return 1; - } else { - SCWrite(pCon,"ERROR: not enough arguments to list match",eError); - return 0; - } - } + if (argc < 2) { + listAllObjects(pCon, pSics); + return 1; + } - /* - * object properties - */ - pCom = FindCommand(pSics,argv[1]); - if(pCom != NULL){ - if(argc < 3){ - listAllObjectData(pCon,argv[1],(pDummy)pCom->pData); - return 1; - } else { - return printObjectData(pCon,(pDummy)pCom->pData, argv[2]); - } - } + if (strcmp(argv[1], "objstatus") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to status", + eError); + return 0; + } + return printObjStatus(pCon, pSics, argv[2]); + } - /* - * attribute setting and status - */ - if(strcmp(argv[1],"setatt") == 0){ - if(argc < 5){ - SCWrite(pCon,"ERROR: Insufficient number of arguments to setatt", - eError); - return 0; - } - return setAttribute(pCon, pSics, argv[2],argv[3], argv[4]); - } + if (strcmp(argv[1], "server") == 0) { + printServer(pCon); + return 1; + } - /* - * classes and class membership - */ - if(argc < 3){ - printKeyTypes(pSics, pCon,argv[1]); - return 1; - } else { - printObjectsMatchingKeyVal(pSics,pCon,argv[1],argv[2]); - return 1; - } - return 0; + if (strcmp(argv[1], "par") == 0) { + if (argc > 2) { + return printObjectPar(pCon, pSics, argv[2]); + } else { + SCWrite(pCon, "ERROR: not enough arguments to list par", eError); + return 0; + } + } + + if (strcmp(argv[1], "match") == 0) { + if (argc > 2) { + printMatch(pCon, pSics, argv[2]); + return 1; + } else { + SCWrite(pCon, "ERROR: not enough arguments to list match", eError); + return 0; + } + } + + /* + * object properties + */ + pCom = FindCommand(pSics, argv[1]); + if (pCom != NULL) { + if (argc < 3) { + listAllObjectData(pCon, argv[1], (pDummy) pCom->pData); + return 1; + } else { + return printObjectData(pCon, (pDummy) pCom->pData, argv[2]); + } + } + + /* + * attribute setting and status + */ + if (strcmp(argv[1], "setatt") == 0) { + if (argc < 5) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to setatt", + eError); + return 0; + } + return setAttribute(pCon, pSics, argv[2], argv[3], argv[4]); + } + + /* + * classes and class membership + */ + if (argc < 3) { + printKeyTypes(pSics, pCon, argv[1]); + return 1; + } else { + printObjectsMatchingKeyVal(pSics, pCon, argv[1], argv[2]); + return 1; + } + return 0; } diff --git a/sicslist.h b/sicslist.h index 39a385bf..9a038219 100644 --- a/sicslist.h +++ b/sicslist.h @@ -9,7 +9,7 @@ #ifndef SICSLIST_H_ #define SICSLIST_H_ #include -int SicsList(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - -#endif /*SICSLIST_H_*/ +int SicsList(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + +#endif /*SICSLIST_H_ */ diff --git a/sicsobj.c b/sicsobj.c index f291db97..cdaa9164 100644 --- a/sicsobj.c +++ b/sicsobj.c @@ -17,438 +17,474 @@ #include "initializer.h" #include "splitter.h" -extern int decodeSICSPriv(char *txt); /* from access.c */ +extern int decodeSICSPriv(char *txt); /* from access.c */ /*--------------------------------------------------------------------------*/ -void DefaultKill(void *data){ - return; +void DefaultKill(void *data) +{ + return; +} + +/*--------------------------------------------------------------------------*/ +void DefaultFree(void *data) +{ + if (data != NULL) { + free(data); + } } -/*--------------------------------------------------------------------------*/ -void DefaultFree(void *data){ - if(data != NULL){ - free(data); - } -} -/*---------------------------------------------------------------------------*/ -static void saveSICSNode(pHdb node, char *prefix, FILE *fd){ - char newprefix[1024], val[20]; - pHdb child; - hdbValue v; - pDynString data = NULL; - - if(GetHdbProperty(node,"__save",val,20) == 1){ - GetHipadabaPar(node,&v,NULL); - data = formatValue(v,node); - if(data != NULL){ - fprintf(fd,"%s %s\n", prefix, GetCharArray(data)); - DeleteDynString(data); - } - child = node->child; - while(child != NULL){ - snprintf(newprefix,1024,"%s/%s", prefix,child->name); - saveSICSNode(child,newprefix,fd); - child = child->next; - } - } -} -/*---------------------------------------------------------------------------*/ -int SaveSICSOBJ(void *data, char *name, FILE *fd){ - pSICSOBJ self = (pSICSOBJ)data; - char prefix[1024]; - pHdb node; - - if(self != NULL && self->objectNode != NULL){ - node = self->objectNode->child; - while(node != NULL){ - snprintf(prefix, 1024,"%s %s", name, node->name); - saveSICSNode(node, prefix, fd); - node = node->next; - } - } - return 1; -} -/*---------------------------------------------------------------------------*/ -pSICSOBJ MakeSICSOBJv(char *name, char *class, int type, int priv){ - pSICSOBJ pNew = NULL; - hdbValue val; - - pNew = (pSICSOBJ)malloc(sizeof(SICSOBJ)); - if(pNew == NULL){ - return NULL; - } - memset(pNew,0,sizeof(SICSOBJ)); - pNew->pDes = CreateDescriptor(class); - pNew->pDes->SaveStatus = SaveSICSOBJ; - if (type == HIPNONE) { - pNew->objectNode = MakeHipadabaNode(name, HIPNONE, 1); - } else { - val = makeHdbValue(type,0); - pNew->objectNode = MakeSICSHdbPar(name, priv, val); - ReleaseHdbValue(&val); - } - if(pNew->pDes == NULL || pNew->objectNode == NULL){ - free(pNew); - return(NULL); - } - pNew->pDes->parNode = pNew->objectNode; - pNew->KillPrivate = DefaultKill; - return pNew; -} -/*---------------------------------------------------------------------------*/ -pSICSOBJ MakeSICSOBJ(char *name, char *class){ - return MakeSICSOBJv(name, class, HIPNONE, 0); -} -/*---------------------------------------------------------------------------*/ -void KillSICSOBJ(void *data){ - pSICSOBJ self = (pSICSOBJ)data; - if(self == NULL){ - return; - } - if(self->KillPrivate != NULL && self->pPrivate != NULL){ - self->KillPrivate(self->pPrivate); - } - RemoveHdbNodeFromParent(self->objectNode, pServ->dummyCon); - if(self->pDes != NULL){ - DeleteDescriptor(self->pDes); /* kill descriptor including node */ - } - free(self); -} -/*===========================================================================*/ -static int assignPar(pHdb node, SConnection *pCon, char *data){ - char error[132], buffer[256]; - int status; - - status = readHdbValue(&node->value,data, error, 132); - if(status != 1){ - snprintf(buffer,255,"ERROR: error parsing %s: %s", - node->name, error); - SCWrite(pCon,buffer,eError); - return 0; - } - return 1; -} -/*---------------------------------------------------------------------------*/ -static int invokeOBJFunction(pSICSOBJ object, pHdb commandNode, SConnection *pCon, - int argc, char *argv[]){ - int status, i, count = 0; - pHdb currentPar = NULL; - SICSOBJFunc pFunc = NULL; - pHdb parArray[64]; - char buffer[1024]; - - /* - * If the first argument has the special name args, concatenate all arguments - * and put the result as text into this parameter. This allows for the - * object function to parse and interpret the arguments itself. - */ - if(commandNode->child != NULL && strcmp(commandNode->child->name,"args") == 0) { - Arg2Text(argc,argv,buffer,1024); - assignPar(commandNode->child,pCon,buffer); - parArray[0] = commandNode->child; - count = 1; - goto invoke; - } - - /* - * assign parameters and fill parameter array for function at the same - * time. Be lenient about missing parameters: Then the old values will - * be used. - */ - for(i = 0, currentPar = commandNode->child; - i < argc && currentPar != NULL; - i++, currentPar = currentPar->next){ - if(argv[i] != NULL){ - status = assignPar(currentPar,pCon, argv[i]); - } - if(status != 1){ - return status; - } - parArray[i] = currentPar; - count++; - } - -invoke: pFunc = (SICSOBJFunc)commandNode->value.v.func; - if(pFunc == NULL){ - SCWrite(pCon,"ERROR: internal error, function not found",eError); - return 0; - } - SendHdbStatusMessage(commandNode,"start"); - status = pFunc(object, pCon, commandNode, parArray,count); - SendHdbStatusMessage(commandNode,"stop"); - return status; -} -/*---------------------------------------------------------------------------*/ -static int ScriptObjFunc(pSICSOBJ obj, SConnection *pCon, pHdb commandNode, - pHdb par[], int nCount){ - int status, i; - Tcl_Interp *pTcl = NULL; - Tcl_DString com; - char value[256]; - pDynString val = NULL; - char *pPtr = NULL; - - memset(value,0,256); - GetHdbProperty(commandNode,"priv",value,256); - status = decodeSICSPriv(value); - if(!SCMatchRights(pCon,status)){ - return 0; - } - - if(GetHdbProperty(commandNode,"script",value,256) != 1){ - SCWrite(pCon,"ERROR: script property not configured on this node", - eError); - return 0; - } - - Tcl_DStringInit(&com); - Tcl_DStringAppend(&com,value,strlen(value)); - for(i = 0; i < nCount; i++){ - val = formatValue(par[i]->value, par[i]); - if(val != NULL){ - Tcl_DStringAppend(&com," ", 1); - pPtr = GetCharArray(val); - Tcl_DStringAppend(&com,pPtr,strlen(pPtr)); - DeleteDynString(val); - } - } - - MacroPush(pCon); - pTcl = InterpGetTcl(pServ->pSics); - status = Tcl_Eval(pTcl,Tcl_DStringValue(&com)); - Tcl_DStringFree(&com); - MacroPop(); - - if(status == TCL_OK){ - SCWrite(pCon,Tcl_GetStringResult(pTcl),eValue); - return 1; - } else { - SCWrite(pCon,Tcl_GetStringResult(pTcl),eError); - return 0; - } - return 1; -} -/*--------------------------------------------------------------------------*/ -static int MakeScriptFunc(pSICSOBJ self, SConnection *pCon, - int argc, char *argv[]){ - char path[512], *pPtr = NULL; - pHdb parent = NULL, node = NULL; - hdbValue func; - - if(argc < 5){ - SCWrite(pCon, - "ERROR: not enough arguments: obj makescriptfunc path script priv", - eError); - return 0; - } - - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - - strncpy(path,argv[2],511); - pPtr = strrchr(path,'/'); - if(pPtr == NULL){ - /* no hierarchy */ - parent = self->objectNode; - node = MakeHipadabaNode(path,HIPFUNC,1); - } else { - /* hierarchy */ - *pPtr = '\0'; - parent = GetHipadabaNode(self->objectNode,path); - pPtr++; - node = MakeHipadabaNode(pPtr,HIPFUNC,1); - } - if(parent == NULL || node == NULL){ - SCWrite(pCon,"ERROR: root path error or out of memory",eError); - return 0; - } - node->value = MakeSICSFunc(ScriptObjFunc); - SetHdbProperty(node,"script",argv[3]); - SetHdbProperty(node,"priv",argv[4]); - AppendHipadabaCallback(node,MakeSICSFuncCallback(self)); - AddHipadabaChild(parent,node,pCon); - SCSendOK(pCon); - return 1; -} -/*---------------------------------------------------------------------------*/ -static int isNodePrintable(pHdb node){ - switch(node->value.dataType){ - case HIPNONE: - case HIPFUNC: - return 0; - default: - return 1; - } -} -/*---------------------------------------------------------------------------*/ -static void objFormatNode(pHdb node, pDynString data){ - char par[40]; - pDynString val = NULL; - - snprintf(par,40,"%-20s = ",node->name); - DynStringConcat(data,par); - val = formatValue(node->value,node); - if(val != NULL){ - DynStringConcat(data,GetCharArray(val)); - DynStringConcatChar(data,'\n'); - DeleteDynString(val); - } -} -/*---------------------------------------------------------------------------*/ -static int ListObj(pSICSOBJ self, SConnection *pCon, int argc, char *argv[]){ - pHdb node = NULL; - pDynString data; - - data = CreateDynString(128,128); - if(data == NULL){ - return 0; - } - node = self->pDes->parNode; - if(node != NULL){ - objFormatNode(node,data); - node = node->child; - while(node != NULL){ - objFormatNode(node,data); - node = node->next; - } - } - SCWrite(pCon,GetCharArray(data),eValue); - DeleteDynString(data); - return 1; -} -/*---------------------------------------------------------------------------*/ -int InvokeSICSOBJ(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pSICSOBJ self = NULL; - int status; - pHdb parNode; - char buffer[132]; - hdbValue data; - pDynString parData; - - self = (pSICSOBJ)pData; - assert(self != NULL); - - if (argc == 1) { - parNode = self->objectNode; - if(parNode != NULL && isNodePrintable(parNode) ){ - status = GetHipadabaPar(parNode,&data,pCon); - if(status != 1){ - return 0; - } - parData = formatValue(data, parNode); - if(parData == NULL){ - SCWrite(pCon,"ERROR: failed to format data", eError); - return 0; - } - SCPrintf(pCon,eValue,"%s = %s", argv[0], GetCharArray(parData)); - DeleteDynString(parData); - return 1; - } else { - SCWrite(pCon,"ERROR: nothing to print", eError); - return 0; - } - } else { - parNode = GetHipadabaNode(self->objectNode,argv[1]); - } - if(parNode != NULL && parNode->value.dataType == HIPFUNC){ - status = invokeOBJFunction(self, parNode, pCon, argc-2, &argv[2]); - } else { - snprintf(buffer, sizeof buffer, "%s ", argv[0]); - status = ProcessSICSHdbPar(self->objectNode,pCon, buffer, - argc-1,&argv[1]); - } - if(status == -1){ - if(strcmp(argv[1],"makescriptfunc") == 0) { - return MakeScriptFunc(self,pCon,argc,argv); - } else if(strcmp(argv[1],"list") == 0){ - return ListObj(self,pCon,argc,argv); - } - SCPrintf(pCon, eError, "ERROR: %s %s not found", argv[0], argv[1]); - } - - return status; -} -/*---------------------------------------------------------------------------*/ -int InterInvokeSICSOBJ(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - int status; - char buffer[132]; - - status = InvokeSICSOBJ(pCon,pSics,pData,argc,argv); - if(status == -1){ - status = 0; - if(argc > 1){ - snprintf(buffer,131,"ERROR: no command or parameter found for key: %s", - argv[1]); - } else { - snprintf(buffer,131,"ERROR: no argument found"); - } - SCWrite(pCon,buffer,eError); - status = 0; - } - return status; -} -/*---------------------------------------------------------------------------*/ -pSICSOBJ SetupSICSOBJ(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pSICSOBJ pNew = NULL; - int status; - int type; - int priv; - - if(argc < 3){ - SCWrite(pCon,"ERROR: not enough arguments to InstallSICSOBJ",eError); - return NULL; - } - if (argc < 5) { - type = HIPNONE; - priv = usInternal; - } else { - /* convert privilege */ - priv = decodeSICSPriv(argv[3]); - /* convert datatype */ - strtolower(argv[4]); - type = convertHdbType(argv[4]); - if(type > HIPFLOAT){ - SCWrite(pCon, - "ERROR: invalid type requested: none, int, float supported", - eError); - return 0; - } - } - - pNew = MakeSICSOBJv(argv[1], argv[2], type, priv); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating new SICS object",eError); - return NULL; - } - if (strcasecmp(argv[0],"DynSicsObj") == 0) { - /* make object dynamic by defining a descriptor command */ - SetDescriptorKey(pNew->pDes, "creationCommand", "0"); - } - status = AddCommand(pSics, - argv[1], - InterInvokeSICSOBJ, - KillSICSOBJ, - pNew); - if(status != 1){ - KillSICSOBJ(pNew); - SCPrintf(pCon,eError,"ERROR: failed create duplicate command %s", argv[1]); - return NULL; - } - return pNew; - } /*---------------------------------------------------------------------------*/ -int InstallSICSOBJ(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pSICSOBJ pNew = NULL; - - pNew = SetupSICSOBJ(pCon, pSics, pData, argc, argv); - if(pNew == NULL){ - return 0; - } else { - return 1; - } -} +static void saveSICSNode(pHdb node, char *prefix, FILE * fd) +{ + char newprefix[1024], val[20]; + pHdb child; + hdbValue v; + pDynString data = NULL; + + if (GetHdbProperty(node, "__save", val, 20) == 1) { + GetHipadabaPar(node, &v, NULL); + data = formatValue(v, node); + if (data != NULL) { + fprintf(fd, "%s %s\n", prefix, GetCharArray(data)); + DeleteDynString(data); + } + child = node->child; + while (child != NULL) { + snprintf(newprefix, 1024, "%s/%s", prefix, child->name); + saveSICSNode(child, newprefix, fd); + child = child->next; + } + } +} + +/*---------------------------------------------------------------------------*/ +int SaveSICSOBJ(void *data, char *name, FILE * fd) +{ + pSICSOBJ self = (pSICSOBJ) data; + char prefix[1024]; + pHdb node; + + if (self != NULL && self->objectNode != NULL) { + node = self->objectNode->child; + while (node != NULL) { + snprintf(prefix, 1024, "%s %s", name, node->name); + saveSICSNode(node, prefix, fd); + node = node->next; + } + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +pSICSOBJ MakeSICSOBJv(char *name, char *class, int type, int priv) +{ + pSICSOBJ pNew = NULL; + hdbValue val; + + pNew = (pSICSOBJ) malloc(sizeof(SICSOBJ)); + if (pNew == NULL) { + return NULL; + } + memset(pNew, 0, sizeof(SICSOBJ)); + pNew->pDes = CreateDescriptor(class); + pNew->pDes->SaveStatus = SaveSICSOBJ; + if (type == HIPNONE) { + pNew->objectNode = MakeHipadabaNode(name, HIPNONE, 1); + } else { + val = makeHdbValue(type, 0); + pNew->objectNode = MakeSICSHdbPar(name, priv, val); + ReleaseHdbValue(&val); + } + if (pNew->pDes == NULL || pNew->objectNode == NULL) { + free(pNew); + return (NULL); + } + pNew->pDes->parNode = pNew->objectNode; + pNew->KillPrivate = DefaultKill; + return pNew; +} + +/*---------------------------------------------------------------------------*/ +pSICSOBJ MakeSICSOBJ(char *name, char *class) +{ + return MakeSICSOBJv(name, class, HIPNONE, 0); +} + +/*---------------------------------------------------------------------------*/ +void KillSICSOBJ(void *data) +{ + pSICSOBJ self = (pSICSOBJ) data; + if (self == NULL) { + return; + } + if (self->KillPrivate != NULL && self->pPrivate != NULL) { + self->KillPrivate(self->pPrivate); + } + RemoveHdbNodeFromParent(self->objectNode, pServ->dummyCon); + if (self->pDes != NULL) { + DeleteDescriptor(self->pDes); /* kill descriptor including node */ + } + free(self); +} + +/*===========================================================================*/ +static int assignPar(pHdb node, SConnection * pCon, char *data) +{ + char error[132], buffer[256]; + int status; + + status = readHdbValue(&node->value, data, error, 132); + if (status != 1) { + snprintf(buffer, 255, "ERROR: error parsing %s: %s", + node->name, error); + SCWrite(pCon, buffer, eError); + return 0; + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int invokeOBJFunction(pSICSOBJ object, pHdb commandNode, + SConnection * pCon, int argc, char *argv[]) +{ + int status, i, count = 0; + pHdb currentPar = NULL; + SICSOBJFunc pFunc = NULL; + pHdb parArray[64]; + char buffer[1024]; + + /* + * If the first argument has the special name args, concatenate all arguments + * and put the result as text into this parameter. This allows for the + * object function to parse and interpret the arguments itself. + */ + if (commandNode->child != NULL + && strcmp(commandNode->child->name, "args") == 0) { + Arg2Text(argc, argv, buffer, 1024); + assignPar(commandNode->child, pCon, buffer); + parArray[0] = commandNode->child; + count = 1; + goto invoke; + } + + /* + * assign parameters and fill parameter array for function at the same + * time. Be lenient about missing parameters: Then the old values will + * be used. + */ + for (i = 0, currentPar = commandNode->child; + i < argc && currentPar != NULL; + i++, currentPar = currentPar->next) { + if (argv[i] != NULL) { + status = assignPar(currentPar, pCon, argv[i]); + } + if (status != 1) { + return status; + } + parArray[i] = currentPar; + count++; + } + +invoke:pFunc = (SICSOBJFunc) commandNode->value.v.func; + if (pFunc == NULL) { + SCWrite(pCon, "ERROR: internal error, function not found", eError); + return 0; + } + SendHdbStatusMessage(commandNode, "start"); + status = pFunc(object, pCon, commandNode, parArray, count); + SendHdbStatusMessage(commandNode, "stop"); + return status; +} + +/*---------------------------------------------------------------------------*/ +static int ScriptObjFunc(pSICSOBJ obj, SConnection * pCon, + pHdb commandNode, pHdb par[], int nCount) +{ + int status, i; + Tcl_Interp *pTcl = NULL; + Tcl_DString com; + char value[256]; + pDynString val = NULL; + char *pPtr = NULL; + + memset(value, 0, 256); + GetHdbProperty(commandNode, "priv", value, 256); + status = decodeSICSPriv(value); + if (!SCMatchRights(pCon, status)) { + return 0; + } + + if (GetHdbProperty(commandNode, "script", value, 256) != 1) { + SCWrite(pCon, "ERROR: script property not configured on this node", + eError); + return 0; + } + + Tcl_DStringInit(&com); + Tcl_DStringAppend(&com, value, strlen(value)); + for (i = 0; i < nCount; i++) { + val = formatValue(par[i]->value, par[i]); + if (val != NULL) { + Tcl_DStringAppend(&com, " ", 1); + pPtr = GetCharArray(val); + Tcl_DStringAppend(&com, pPtr, strlen(pPtr)); + DeleteDynString(val); + } + } + + MacroPush(pCon); + pTcl = InterpGetTcl(pServ->pSics); + status = Tcl_Eval(pTcl, Tcl_DStringValue(&com)); + Tcl_DStringFree(&com); + MacroPop(); + + if (status == TCL_OK) { + SCWrite(pCon, Tcl_GetStringResult(pTcl), eValue); + return 1; + } else { + SCWrite(pCon, Tcl_GetStringResult(pTcl), eError); + return 0; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int MakeScriptFunc(pSICSOBJ self, SConnection * pCon, + int argc, char *argv[]) +{ + char path[512], *pPtr = NULL; + pHdb parent = NULL, node = NULL; + hdbValue func; + + if (argc < 5) { + SCWrite(pCon, + "ERROR: not enough arguments: obj makescriptfunc path script priv", + eError); + return 0; + } + + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + + strncpy(path, argv[2], 511); + pPtr = strrchr(path, '/'); + if (pPtr == NULL) { + /* no hierarchy */ + parent = self->objectNode; + node = MakeHipadabaNode(path, HIPFUNC, 1); + } else { + /* hierarchy */ + *pPtr = '\0'; + parent = GetHipadabaNode(self->objectNode, path); + pPtr++; + node = MakeHipadabaNode(pPtr, HIPFUNC, 1); + } + if (parent == NULL || node == NULL) { + SCWrite(pCon, "ERROR: root path error or out of memory", eError); + return 0; + } + node->value = MakeSICSFunc(ScriptObjFunc); + SetHdbProperty(node, "script", argv[3]); + SetHdbProperty(node, "priv", argv[4]); + AppendHipadabaCallback(node, MakeSICSFuncCallback(self)); + AddHipadabaChild(parent, node, pCon); + SCSendOK(pCon); + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int isNodePrintable(pHdb node) +{ + switch (node->value.dataType) { + case HIPNONE: + case HIPFUNC: + return 0; + default: + return 1; + } +} + +/*---------------------------------------------------------------------------*/ +static void objFormatNode(pHdb node, pDynString data) +{ + char par[40]; + pDynString val = NULL; + + snprintf(par, 40, "%-20s = ", node->name); + DynStringConcat(data, par); + val = formatValue(node->value, node); + if (val != NULL) { + DynStringConcat(data, GetCharArray(val)); + DynStringConcatChar(data, '\n'); + DeleteDynString(val); + } +} + +/*---------------------------------------------------------------------------*/ +static int ListObj(pSICSOBJ self, SConnection * pCon, int argc, + char *argv[]) +{ + pHdb node = NULL; + pDynString data; + + data = CreateDynString(128, 128); + if (data == NULL) { + return 0; + } + node = self->pDes->parNode; + if (node != NULL) { + objFormatNode(node, data); + node = node->child; + while (node != NULL) { + objFormatNode(node, data); + node = node->next; + } + } + SCWrite(pCon, GetCharArray(data), eValue); + DeleteDynString(data); + return 1; +} + +/*---------------------------------------------------------------------------*/ +int InvokeSICSOBJ(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSICSOBJ self = NULL; + int status; + pHdb parNode; + char buffer[132]; + hdbValue data; + pDynString parData; + + self = (pSICSOBJ) pData; + assert(self != NULL); + + if (argc == 1) { + parNode = self->objectNode; + if (parNode != NULL && isNodePrintable(parNode)) { + status = GetHipadabaPar(parNode, &data, pCon); + if (status != 1) { + return 0; + } + parData = formatValue(data, parNode); + if (parData == NULL) { + SCWrite(pCon, "ERROR: failed to format data", eError); + return 0; + } + SCPrintf(pCon, eValue, "%s = %s", argv[0], GetCharArray(parData)); + DeleteDynString(parData); + return 1; + } else { + SCWrite(pCon, "ERROR: nothing to print", eError); + return 0; + } + } else { + parNode = GetHipadabaNode(self->objectNode, argv[1]); + } + if (parNode != NULL && parNode->value.dataType == HIPFUNC) { + status = invokeOBJFunction(self, parNode, pCon, argc - 2, &argv[2]); + } else { + snprintf(buffer, sizeof buffer, "%s ", argv[0]); + status = ProcessSICSHdbPar(self->objectNode, pCon, buffer, + argc - 1, &argv[1]); + } + if (status == -1) { + if (strcmp(argv[1], "makescriptfunc") == 0) { + return MakeScriptFunc(self, pCon, argc, argv); + } else if (strcmp(argv[1], "list") == 0) { + return ListObj(self, pCon, argc, argv); + } + SCPrintf(pCon, eError, "ERROR: %s %s not found", argv[0], argv[1]); + } + + return status; +} + +/*---------------------------------------------------------------------------*/ +int InterInvokeSICSOBJ(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int status; + char buffer[132]; + + status = InvokeSICSOBJ(pCon, pSics, pData, argc, argv); + if (status == -1) { + status = 0; + if (argc > 1) { + snprintf(buffer, 131, + "ERROR: no command or parameter found for key: %s", + argv[1]); + } else { + snprintf(buffer, 131, "ERROR: no argument found"); + } + SCWrite(pCon, buffer, eError); + status = 0; + } + return status; +} + +/*---------------------------------------------------------------------------*/ +pSICSOBJ SetupSICSOBJ(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSICSOBJ pNew = NULL; + int status; + int type; + int priv; + + if (argc < 3) { + SCWrite(pCon, "ERROR: not enough arguments to InstallSICSOBJ", eError); + return NULL; + } + if (argc < 5) { + type = HIPNONE; + priv = usInternal; + } else { + /* convert privilege */ + priv = decodeSICSPriv(argv[3]); + /* convert datatype */ + strtolower(argv[4]); + type = convertHdbType(argv[4]); + if (type > HIPFLOAT) { + SCWrite(pCon, + "ERROR: invalid type requested: none, int, float supported", + eError); + return 0; + } + } + + pNew = MakeSICSOBJv(argv[1], argv[2], type, priv); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating new SICS object", eError); + return NULL; + } + if (strcasecmp(argv[0], "DynSicsObj") == 0) { + /* make object dynamic by defining a descriptor command */ + SetDescriptorKey(pNew->pDes, "creationCommand", "0"); + } + + status = AddCommand(pSics, + argv[1], InterInvokeSICSOBJ, KillSICSOBJ, pNew); + if (status != 1) { + KillSICSOBJ(pNew); + SCPrintf(pCon, eError, "ERROR: failed create duplicate command %s", + argv[1]); + return NULL; + } + return pNew; +} + +/*---------------------------------------------------------------------------*/ +int InstallSICSOBJ(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSICSOBJ pNew = NULL; + + pNew = SetupSICSOBJ(pCon, pSics, pData, argc, argv); + if (pNew == NULL) { + return 0; + } else { + return 1; + } +} diff --git a/sicsobj.h b/sicsobj.h index 6512146e..5af02cab 100644 --- a/sicsobj.h +++ b/sicsobj.h @@ -14,16 +14,16 @@ * in its first fields with the SICS object descriptor as defined in * obdes.h in order to achieve backwards compatibility with old style * SICS objects. - * =====================================================================*/ + * =====================================================================*/ typedef struct { - pObjectDescriptor pDes; - pHdb objectNode; - void *pPrivate; - void (*KillPrivate)(void *pPrivate); -}SICSOBJ, *pSICSOBJ; + pObjectDescriptor pDes; + pHdb objectNode; + void *pPrivate; + void (*KillPrivate) (void *pPrivate); +} SICSOBJ, *pSICSOBJ; /*-----------------------------------------------------------------------*/ -typedef int (*SICSOBJFunc)(pSICSOBJ self, SConnection *pCon, - pHdb commandNode, pHdb par[], int nPar); +typedef int (*SICSOBJFunc) (pSICSOBJ self, SConnection * pCon, + pHdb commandNode, pHdb par[], int nPar); /*======================= Live & Death =================================*/ pSICSOBJ MakeSICSOBJ(char *name, char *class); pSICSOBJ MakeSICSOBJv(char *name, char *class, int type, int priv); @@ -31,26 +31,26 @@ void KillSICSOBJ(void *data); void DefaultKill(void *data); void DefaultFree(void *data); -int SaveSICSOBJ(void *data, char *name, FILE *fd); +int SaveSICSOBJ(void *data, char *name, FILE * fd); /** * This creates a new SICS object and installs it in the interpreter. It returns * the newly created SICS object such that the caller can continue * configuring it. - */ -pSICSOBJ SetupSICSOBJ(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); + */ +pSICSOBJ SetupSICSOBJ(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*====================== Interpreter Interface =========================== * InvokeSICSObj is special in that it returns -1 if it cannot handle * the command. This leaves calling code the opportunity to process * further commands.It returns 1 on success and 0 on failures though. * ------------------------------------------------------------------------*/ -int InvokeSICSOBJ(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int InterInvokeSICSOBJ(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int InstallSICSOBJ(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +int InvokeSICSOBJ(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int InterInvokeSICSOBJ(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int InstallSICSOBJ(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -#endif /*SICSOBJ2_H_*/ + +#endif /*SICSOBJ2_H_ */ diff --git a/sicspoll.c b/sicspoll.c index fe798bbb..69671170 100644 --- a/sicspoll.c +++ b/sicspoll.c @@ -24,340 +24,359 @@ /*================== data structure =====================================*/ static SConnection *defCon = NULL; -struct __SICSPOLL{ - pObjectDescriptor pDes; - int pollList; /* list with polled objects */ - int listDirty; /* a flag to set when the list has been modified. This will - cause the list polling task to go back to the start. */ - SConnection *pCon; /* connection to use for polling */ - int iEnd; /* flag ending this */ - int nPoll; /* how many to poll in one run */ - long taskID; -}; +struct __SICSPOLL { + pObjectDescriptor pDes; + int pollList; /* list with polled objects */ + int listDirty; /* a flag to set when the list has been modified. This will + cause the list polling task to go back to the start. */ + SConnection *pCon; /* connection to use for polling */ + int iEnd; /* flag ending this */ + int nPoll; /* how many to poll in one run */ + long taskID; +}; /*-----------------------------------------------------------------------*/ -void killSicsPoll(void *data){ - pSicsPoll self = (pSicsPoll)data; - int status; - pPollDriv poll = NULL; - - self->iEnd = 1; - status = LLDnodePtr2First(self->pollList); - while(status != 0){ - poll = LLDnodePtr(self->pollList); - if(poll != NULL){ - deletePollDriv(poll); - } - status = LLDnodePtr2Next(self->pollList); - } - LLDdelete(self->pollList); - if(self->pDes) { - DeleteDescriptor(self->pDes); - } - free(self); - if(defCon != NULL){ - SCDeleteConnection(defCon); +void killSicsPoll(void *data) +{ + pSicsPoll self = (pSicsPoll) data; + int status; + pPollDriv poll = NULL; + + self->iEnd = 1; + status = LLDnodePtr2First(self->pollList); + while (status != 0) { + poll = LLDnodePtr(self->pollList); + if (poll != NULL) { + deletePollDriv(poll); } + status = LLDnodePtr2Next(self->pollList); + } + LLDdelete(self->pollList); + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + free(self); + if (defCon != NULL) { + SCDeleteConnection(defCon); + } } + /*----------------- list access -----------------------------------------*/ -static pPollDriv locateObject(int list, char *objectIdentifier){ - int status; - pPollDriv data = NULL; - - status = LLDnodePtr2First(list); - while(status != 0){ - data = (pPollDriv)LLDnodePtr(list); - if(data != NULL){ - if(strcmp(data->objectIdentifier,objectIdentifier) == 0){ - return data; - } - } - status = LLDnodePtr2Next(list); - } - return NULL; -} -/*===================== task function ==================================*/ -static int incrList(int list){ - int status; - - if(LLDcheck(list) == LIST_EMPTY){ - return 0; +static pPollDriv locateObject(int list, char *objectIdentifier) +{ + int status; + pPollDriv data = NULL; + + status = LLDnodePtr2First(list); + while (status != 0) { + data = (pPollDriv) LLDnodePtr(list); + if (data != NULL) { + if (strcmp(data->objectIdentifier, objectIdentifier) == 0) { + return data; + } } status = LLDnodePtr2Next(list); - if(status == 0) { - status = LLDnodePtr2First(list); - } - return status; + } + return NULL; } + +/*===================== task function ==================================*/ +static int incrList(int list) +{ + int status; + + if (LLDcheck(list) == LIST_EMPTY) { + return 0; + } + status = LLDnodePtr2Next(list); + if (status == 0) { + status = LLDnodePtr2First(list); + } + return status; +} + /*---------------------------------------------------------------------------*/ -void SicsPollSignal(void *pData, int iSignal, void *pSigData){ - pSicsPoll self = NULL; - int *iInt; - - self = (pSicsPoll)pData; - - if(iSignal == SICSINT){ - iInt = (int *)pSigData; - if(*iInt == eEndServer){ - self->iEnd = 1; - } +void SicsPollSignal(void *pData, int iSignal, void *pSigData) +{ + pSicsPoll self = NULL; + int *iInt; + + self = (pSicsPoll) pData; + + if (iSignal == SICSINT) { + iInt = (int *) pSigData; + if (*iInt == eEndServer) { + self->iEnd = 1; } + } } + /*----------------------------------------------------------------------*/ -static int PollTask(void *data){ - pSicsPoll self = (pSicsPoll) data; - pPollDriv poll = NULL; - int status, i; - time_t now = time(NULL); - - if(self == NULL || self->iEnd == 1){ - return 0; - } - if(LLDcheck(self->pollList) == LIST_EMPTY){ - return 1; - } - - /* - * increment list - */ - if(self->listDirty == 1){ - self->listDirty = 0; - status = LLDnodePtr2First(self->pollList); - } +static int PollTask(void *data) +{ + pSicsPoll self = (pSicsPoll) data; + pPollDriv poll = NULL; + int status, i; + time_t now = time(NULL); - /* - * actually do poll - */ - for(i = 0; i < self->nPoll; i++){ - status = incrList(self->pollList); - poll = (pPollDriv)LLDnodePtr(self->pollList); - if(status != 0 && poll != NULL){ - if(poll->isDue(poll,now,self->pCon)){ - poll->poll(poll,self->pCon); - } - } - } + if (self == NULL || self->iEnd == 1) { + return 0; + } + if (LLDcheck(self->pollList) == LIST_EMPTY) { return 1; -} -/*==================== interface functions ==============================*/ -int removePollObject(pSicsPoll self, char *objectIdentifier){ - pPollDriv target = NULL; - - self->listDirty = 1; - target = locateObject(self->pollList, objectIdentifier); - if(target != NULL){ - LLDnodeDelete(self->pollList); - deletePollDriv(target); - return 1; - } else{ - return 0; - } -} -/*------------------------------------------------------------------------*/ -int addPollObject(SicsPoll *self, SConnection *pCon, char *objectIdentifier, - char *driver, int argc, char *argv[]){ - int status; - pPollDriv driv = NULL; - - driv = makePollDriver(pCon, driver,objectIdentifier, - argc,argv); - if(driv == NULL){ - return 0; - } - - LLDnodeAppend(self->pollList,&driv); - return 1; -} -/*-----------------------------------------------------------------------*/ -static void printPollList(pSicsPoll self, SConnection *pCon){ - int status; - pPollDriv driv = NULL; - char buffer[512]; - + } + + /* + * increment list + */ + if (self->listDirty == 1) { + self->listDirty = 0; status = LLDnodePtr2First(self->pollList); - while(status != 0){ - driv = (pPollDriv)LLDnodePtr(self->pollList); - if(driv != NULL){ - snprintf(buffer,512,"%60s %3d", - driv->objectIdentifier, driv->pollIntervall); - SCWrite(pCon,buffer,eValue); - } - status = LLDnodePtr2Next(self->pollList); + } + + /* + * actually do poll + */ + for (i = 0; i < self->nPoll; i++) { + status = incrList(self->pollList); + poll = (pPollDriv) LLDnodePtr(self->pollList); + if (status != 0 && poll != NULL) { + if (poll->isDue(poll, now, self->pCon)) { + poll->poll(poll, self->pCon); + } } + } + return 1; } -/*================== interpreter interface ===============================*/ -int SICSPollWrapper(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pSicsPoll self = (pSicsPoll)pData; - pPollDriv driv = NULL; - int status, iVal; - char buffer[512]; - pDynString txt = NULL; - - assert(self != NULL); - if(argc < 2){ - SCWrite(pCon,"ERROR: Not enough arguments",eError); - return 0; - } - strtolower(argv[1]); - if(strcmp(argv[1],"del") == 0) { - if(argc < 3){ - SCWrite(pCon,"ERROR: Not enough arguments",eError); - return 0; - } +/*==================== interface functions ==============================*/ +int removePollObject(pSicsPoll self, char *objectIdentifier) +{ + pPollDriv target = NULL; - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - status = removePollObject(self,argv[2]); - if(status == 0) { - SCWrite(pCon,"ERROR: object to remove from poll list not found",eError); - return 0; - } else { - SCSendOK(pCon); - return 1; - } - } else if(strcmp(argv[1],"add") == 0) { - if(argc < 4){ - SCWrite(pCon,"ERROR: Not enough arguments",eError); - return 0; - } - - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - driv = makePollDriver(pCon,argv[3], argv[2], - argc-4, &argv[4]); - if(driv != NULL){ - LLDnodeAppend(self->pollList,&driv); - SCSendOK(pCon); - return 1; - } else { - return 0; - } - } else if (strcmp(argv[1],"npoll") == 0) { - if(argc < 3) { - snprintf(buffer,512,"%s.%s = %d", argv[0], "npoll", self->nPoll); - } else { - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - status = sscanf(argv[2],"%d",&self->nPoll); - if(status != 1) { - snprintf(buffer,512,"ERROR: failed to convert %s to int",argv[2]); - SCWrite(pCon,buffer,eError); - return 0; - } else { - SCSendOK(pCon); - return 1; - } - } - } else if (strcmp(argv[1],"listen") == 0) { - self->pCon = pCon; - SCSendOK(pCon); - return 1; - } else if (strcmp(argv[1],"unlisten") == 0) { - self->pCon = defCon; - SCSendOK(pCon); - return 1; - } else if (strcmp(argv[1],"intervall") == 0){ - if(argc < 3){ - SCWrite(pCon,"ERROR: Not enough arguments",eError); - return 0; - } - - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - - driv = locateObject(self->pollList,argv[2]); - if(driv == NULL){ - SCWrite(pCon,"ERROR: object not in polling list",eError); - return 0; - } - if(argc > 3){ - status = sscanf(argv[3],"%d", &iVal); - if(status != 1){ - snprintf(buffer,511,"ERROR: failed to convert %s to int", - argv[3]); - SCWrite(pCon,buffer,eError); - return 0; - } - if(iVal < 0) { - SCWrite(pCon,"ERROR: new value for intervall out of range",eError); - return 0; - } - driv->pollIntervall = iVal; - SCSendOK(pCon); - return 1; - } else { - snprintf(buffer,511,"%s.intervall = %d",driv->objectIdentifier, - driv->pollIntervall); - SCWrite(pCon,buffer,eValue); - return 1; - } - } else if (strcmp(argv[1],"list") == 0) { - SCStartBuffering(pCon); - printPollList(self,pCon); - txt = SCEndBuffering(pCon); - if(txt != NULL){ - SCWrite(pCon,GetCharArray(txt),eValue); - } - return 1; - } else if (strcmp(argv[1],"poll") == 0) { - if(argc < 3){ - SCWrite(pCon,"ERROR: Not enough arguments",eError); - return 0; - } - - driv = locateObject(self->pollList,argv[2]); - if(driv == NULL){ - SCWrite(pCon,"ERROR: object not in polling list",eError); - return 0; - } - status = driv->poll(driv,pCon); - if(status != 1){ - SCWrite(pCon,"ERROR: polling object",eError); - return 0; - } - SCWrite(pCon,"Object polled OK",eError); - return 1; - } + self->listDirty = 1; + target = locateObject(self->pollList, objectIdentifier); + if (target != NULL) { + LLDnodeDelete(self->pollList); + deletePollDriv(target); return 1; + } else { + return 0; + } } + /*------------------------------------------------------------------------*/ -int InstallSICSPoll(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pSicsPoll pNew = NULL; - - pNew = malloc(sizeof(SicsPoll)); - if(pNew == NULL){ - return 0; - } - memset(pNew,0,sizeof(SicsPoll)); +int addPollObject(SicsPoll * self, SConnection * pCon, + char *objectIdentifier, char *driver, int argc, + char *argv[]) +{ + int status; + pPollDriv driv = NULL; - pNew->pDes = CreateDescriptor("SicsPoll"); - pNew->pollList = LLDcreate(sizeof(void *)); - defCon = SCCreateDummyConnection(pSics); - - if(pNew->pDes == NULL|| pNew->pollList < 0 || defCon == NULL){ - SCWrite(pCon,"ERROR: out of memory creating SicsPoll",eError); - return 0; - } - pNew->pCon = defCon; - pNew->nPoll = 3; - - TaskRegister(pServ->pTasker,PollTask,SicsPollSignal,NULL,pNew, 10); - - if(argc > 1){ - AddCommand(pSics,argv[1],SICSPollWrapper, - killSicsPoll,pNew); - } else { - AddCommand(pSics,"sicspoll",SICSPollWrapper, - killSicsPoll,pNew); - } - - return 1; + driv = makePollDriver(pCon, driver, objectIdentifier, argc, argv); + if (driv == NULL) { + return 0; + } + + LLDnodeAppend(self->pollList, &driv); + return 1; +} + +/*-----------------------------------------------------------------------*/ +static void printPollList(pSicsPoll self, SConnection * pCon) +{ + int status; + pPollDriv driv = NULL; + char buffer[512]; + + status = LLDnodePtr2First(self->pollList); + while (status != 0) { + driv = (pPollDriv) LLDnodePtr(self->pollList); + if (driv != NULL) { + snprintf(buffer, 512, "%60s %3d", + driv->objectIdentifier, driv->pollIntervall); + SCWrite(pCon, buffer, eValue); + } + status = LLDnodePtr2Next(self->pollList); + } +} + +/*================== interpreter interface ===============================*/ +int SICSPollWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSicsPoll self = (pSicsPoll) pData; + pPollDriv driv = NULL; + int status, iVal; + char buffer[512]; + pDynString txt = NULL; + + assert(self != NULL); + if (argc < 2) { + SCWrite(pCon, "ERROR: Not enough arguments", eError); + return 0; + } + + strtolower(argv[1]); + if (strcmp(argv[1], "del") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: Not enough arguments", eError); + return 0; + } + + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + status = removePollObject(self, argv[2]); + if (status == 0) { + SCWrite(pCon, "ERROR: object to remove from poll list not found", + eError); + return 0; + } else { + SCSendOK(pCon); + return 1; + } + } else if (strcmp(argv[1], "add") == 0) { + if (argc < 4) { + SCWrite(pCon, "ERROR: Not enough arguments", eError); + return 0; + } + + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + driv = makePollDriver(pCon, argv[3], argv[2], argc - 4, &argv[4]); + if (driv != NULL) { + LLDnodeAppend(self->pollList, &driv); + SCSendOK(pCon); + return 1; + } else { + return 0; + } + } else if (strcmp(argv[1], "npoll") == 0) { + if (argc < 3) { + snprintf(buffer, 512, "%s.%s = %d", argv[0], "npoll", self->nPoll); + } else { + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + status = sscanf(argv[2], "%d", &self->nPoll); + if (status != 1) { + snprintf(buffer, 512, "ERROR: failed to convert %s to int", + argv[2]); + SCWrite(pCon, buffer, eError); + return 0; + } else { + SCSendOK(pCon); + return 1; + } + } + } else if (strcmp(argv[1], "listen") == 0) { + self->pCon = pCon; + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "unlisten") == 0) { + self->pCon = defCon; + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "intervall") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: Not enough arguments", eError); + return 0; + } + + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + + driv = locateObject(self->pollList, argv[2]); + if (driv == NULL) { + SCWrite(pCon, "ERROR: object not in polling list", eError); + return 0; + } + if (argc > 3) { + status = sscanf(argv[3], "%d", &iVal); + if (status != 1) { + snprintf(buffer, 511, "ERROR: failed to convert %s to int", + argv[3]); + SCWrite(pCon, buffer, eError); + return 0; + } + if (iVal < 0) { + SCWrite(pCon, "ERROR: new value for intervall out of range", + eError); + return 0; + } + driv->pollIntervall = iVal; + SCSendOK(pCon); + return 1; + } else { + snprintf(buffer, 511, "%s.intervall = %d", driv->objectIdentifier, + driv->pollIntervall); + SCWrite(pCon, buffer, eValue); + return 1; + } + } else if (strcmp(argv[1], "list") == 0) { + SCStartBuffering(pCon); + printPollList(self, pCon); + txt = SCEndBuffering(pCon); + if (txt != NULL) { + SCWrite(pCon, GetCharArray(txt), eValue); + } + return 1; + } else if (strcmp(argv[1], "poll") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: Not enough arguments", eError); + return 0; + } + + driv = locateObject(self->pollList, argv[2]); + if (driv == NULL) { + SCWrite(pCon, "ERROR: object not in polling list", eError); + return 0; + } + status = driv->poll(driv, pCon); + if (status != 1) { + SCWrite(pCon, "ERROR: polling object", eError); + return 0; + } + SCWrite(pCon, "Object polled OK", eError); + return 1; + } + return 1; +} + +/*------------------------------------------------------------------------*/ +int InstallSICSPoll(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSicsPoll pNew = NULL; + + pNew = malloc(sizeof(SicsPoll)); + if (pNew == NULL) { + return 0; + } + memset(pNew, 0, sizeof(SicsPoll)); + + pNew->pDes = CreateDescriptor("SicsPoll"); + pNew->pollList = LLDcreate(sizeof(void *)); + defCon = SCCreateDummyConnection(pSics); + + if (pNew->pDes == NULL || pNew->pollList < 0 || defCon == NULL) { + SCWrite(pCon, "ERROR: out of memory creating SicsPoll", eError); + return 0; + } + pNew->pCon = defCon; + pNew->nPoll = 3; + + TaskRegister(pServ->pTasker, PollTask, SicsPollSignal, NULL, pNew, 10); + + if (argc > 1) { + AddCommand(pSics, argv[1], SICSPollWrapper, killSicsPoll, pNew); + } else { + AddCommand(pSics, "sicspoll", SICSPollWrapper, killSicsPoll, pNew); + } + + return 1; } diff --git a/sicspoll.h b/sicspoll.h index 3d307223..c4e570d3 100644 --- a/sicspoll.h +++ b/sicspoll.h @@ -16,14 +16,14 @@ /** * the factory function */ -int InstallSICSPoll(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int InstallSICSPoll(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* * the actual wrapper which allows to configure and query the polling * module */ -int SICSPollWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SICSPollWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*================== Internal Interface ===================================*/ typedef struct __SICSPOLL SicsPoll, *pSicsPoll; /** @@ -38,16 +38,17 @@ typedef struct __SICSPOLL SicsPoll, *pSicsPoll; * poll driver * @param argv[] The parameters to pass to the poll driver. * @return 1 on success or a negative error code when things go wrong. - */ -int addPollObject(SicsPoll *self, SConnection *pCon, char *objectIdentifier, - char *driver, int argc, char *argv[]); + */ +int addPollObject(SicsPoll * self, SConnection * pCon, + char *objectIdentifier, char *driver, int argc, + char *argv[]); /** * remove an object from the polling loop. * @param self A pointer to a sicsPoll object managing the poll loop. * @param objectIdentifier The identifier of the object to remove from * the poll loop. * @return 1 on success, a negative error code on failure. - */ -int removePollObject(SicsPoll *self, char *objectIdentifier); + */ +int removePollObject(SicsPoll * self, char *objectIdentifier); -#endif /*SICSPOLL_H_*/ +#endif /*SICSPOLL_H_ */ diff --git a/sicsvar.h b/sicsvar.h index c9823a19..bb956882 100644 --- a/sicsvar.h +++ b/sicsvar.h @@ -12,63 +12,62 @@ #include "obdes.h" /* Variable Types */ - typedef enum { veText, veInt, veFloat } VarType; - - - +typedef enum { veText, veInt, veFloat } VarType; + + + /* the actual variable type, all in one to get rid of inheritance */ - typedef struct { - pObjectDescriptor pDescriptor; - VarType eType; - int iAccessCode; - float fVal; - int iVal; - int iLock; - char *text; - char *name; - pICallBack pCall; - } SicsVariable; - - - typedef SicsVariable *pSicsVariable; - - /* Create and Kill */ - pSicsVariable VarCreate(int iAccessCode, VarType eTyp, char *name); +typedef struct { + pObjectDescriptor pDescriptor; + VarType eType; + int iAccessCode; + float fVal; + int iVal; + int iLock; + char *text; + char *name; + pICallBack pCall; +} SicsVariable; + + +typedef SicsVariable *pSicsVariable; + + /* Create and Kill */ +pSicsVariable VarCreate(int iAccessCode, VarType eTyp, char *name); /* creates a new Variable - */ - int VarFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); + */ +int VarFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /* the factory method for creating variables - */ - - int VarKill(pSicsVariable self); - + */ + +int VarKill(pSicsVariable self); + /* setting and reading */ - int VarSetFloat(pSicsVariable self, float fNew, int iUserRight); - int VarSetInt(pSicsVariable self , int iNew, int iUserRight); - int VarSetText(pSicsVariable self, char *pNew, int iUserRight); - - int VarGetFloat(pSicsVariable self, float *fNew); - int VarGetInt(pSicsVariable self, int *iNew); - int VarGetText(pSicsVariable self, char **pNew); - +int VarSetFloat(pSicsVariable self, float fNew, int iUserRight); +int VarSetInt(pSicsVariable self, int iNew, int iUserRight); +int VarSetText(pSicsVariable self, char *pNew, int iUserRight); + +int VarGetFloat(pSicsVariable self, float *fNew); +int VarGetInt(pSicsVariable self, int *iNew); +int VarGetText(pSicsVariable self, char **pNew); + /* Infomation and Configuration */ - VarType GetVarType(pSicsVariable self); - int VarSetRights(pSicsVariable self, int iNewRights, int iYourRights); +VarType GetVarType(pSicsVariable self); +int VarSetRights(pSicsVariable self, int iNewRights, int iYourRights); /* sets new userights for the variable, only Muggers are allowed to do this - */ + */ /* the wrapper function to make variables objects */ - int VarWrapper(SConnection *pCon, SicsInterp *pInter, void *pData, - int argc, char *argv[]); +int VarWrapper(SConnection * pCon, SicsInterp * pInter, void *pData, + int argc, char *argv[]); /* a utility function to find a variable in the Sics interpreter */ - pSicsVariable FindVariable(SicsInterp *pSics, char *name); - +pSicsVariable FindVariable(SicsInterp * pSics, char *name); + #endif - diff --git a/sicvar.c b/sicvar.c index 34ec3102..2bce9e27 100644 --- a/sicvar.c +++ b/sicvar.c @@ -47,80 +47,78 @@ #include "sicsvar.h" /*-------------------------------------------------------------------------*/ - static int VarSave(void *pData, char *name, FILE *fd) - { - char pBueffel[512]; - pSicsVariable pVar = NULL; - - assert(pData); - assert(fd); - pVar = (pSicsVariable)pData; - if(pVar->iLock || pVar->iAccessCode == usInternal) - { - return 1; - } - sprintf(pBueffel,"# Variable %s\n",name); - switch(pVar->eType) - { - case veText: - sprintf(pBueffel,"%s %s\n",name, pVar->text); - break; - case veInt: - sprintf(pBueffel,"%s %d\n",name, pVar->iVal); - break; - case veFloat: - sprintf(pBueffel,"%s %f\n",name,pVar->fVal); - break; - } - fputs(pBueffel,fd); - sprintf(pBueffel,"%s setAccess %d\n",name,pVar->iAccessCode); - fputs(pBueffel,fd); +static int VarSave(void *pData, char *name, FILE * fd) +{ + char pBueffel[512]; + pSicsVariable pVar = NULL; + + assert(pData); + assert(fd); + pVar = (pSicsVariable) pData; + if (pVar->iLock || pVar->iAccessCode == usInternal) { return 1; } -/*------------------------------------------------------------------------*/ - static void *VarInterface(void *pData, int iInter) - { - pSicsVariable self = NULL; - - self = (pSicsVariable)pData; - assert(self); - - if(iInter == CALLBACKINTERFACE) - { - return self->pCall; - } - return NULL; - } -/*--------------------------------------------------------------------------*/ - pSicsVariable VarCreate(int iAccessCode, VarType eTyp, char *name) - { - pSicsVariable pRes = NULL; - - pRes = (SicsVariable *)malloc(sizeof(SicsVariable)); - if(!pRes) - { - return NULL; - } - - pRes->pDescriptor = CreateDescriptor("SicsVariable"); - if(!pRes->pDescriptor) - { - free(pRes); - return NULL; - } - pRes->pDescriptor->GetInterface = VarInterface; - pRes->pDescriptor->SaveStatus = VarSave; - pRes->eType = eTyp; - pRes->iAccessCode = iAccessCode; - pRes->fVal = .0; - pRes->iVal = 0; - pRes->iLock = 0; - pRes->text = strdup("UNKNOWN"); - pRes->name = strdup(name); + sprintf(pBueffel, "# Variable %s\n", name); + switch (pVar->eType) { + case veText: + sprintf(pBueffel, "%s %s\n", name, pVar->text); + break; + case veInt: + sprintf(pBueffel, "%s %d\n", name, pVar->iVal); + break; + case veFloat: + sprintf(pBueffel, "%s %f\n", name, pVar->fVal); + break; + } + fputs(pBueffel, fd); + sprintf(pBueffel, "%s setAccess %d\n", name, pVar->iAccessCode); + fputs(pBueffel, fd); + return 1; +} + +/*------------------------------------------------------------------------*/ +static void *VarInterface(void *pData, int iInter) +{ + pSicsVariable self = NULL; + + self = (pSicsVariable) pData; + assert(self); + + if (iInter == CALLBACKINTERFACE) { + return self->pCall; + } + return NULL; +} + +/*--------------------------------------------------------------------------*/ +pSicsVariable VarCreate(int iAccessCode, VarType eTyp, char *name) +{ + pSicsVariable pRes = NULL; + + pRes = (SicsVariable *) malloc(sizeof(SicsVariable)); + if (!pRes) { + return NULL; + } + + pRes->pDescriptor = CreateDescriptor("SicsVariable"); + if (!pRes->pDescriptor) { + free(pRes); + return NULL; + } + pRes->pDescriptor->GetInterface = VarInterface; + pRes->pDescriptor->SaveStatus = VarSave; + pRes->eType = eTyp; + pRes->iAccessCode = iAccessCode; + pRes->fVal = .0; + pRes->iVal = 0; + pRes->iLock = 0; + pRes->text = strdup("UNKNOWN"); + pRes->name = strdup(name); + + pRes->pCall = CreateCallBackInterface(); + return pRes; +} - pRes->pCall = CreateCallBackInterface(); - return pRes; - } /*-------------------------------------------------------------------------- VarFactory will be used in the initialisation phase to configure a new variable. @@ -130,302 +128,283 @@ type can be one of: Text, Int, Float access can be one of: Internal, Mugger, User, Spy -------------------------------------------------------------------------*/ - static char *cType[] = { - "text", - "int", - "float", - NULL - }; - - int VarFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pSicsVariable pRes = NULL; - char pBueffel[512]; - VarType eType; - int i; - int iCode, iRet; - - assert(pCon); - assert(pSics); - - /* check if enough commands */ - argtolower(argc,argv); - if(argc < 4) - { - sprintf(pBueffel,"Insufficient no of args to %s, Usage: %s name type accescode", - argv[0],argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* argv[1] is expected to be the name of the var, argv[2] the type*/ - /* interpret the type */ - i = 0; - while(cType[i] != NULL) - { - if(strcmp(cType[i],argv[2]) == 0) - { - break; - } - i++; - } - switch(i) - { - case 0: - eType = veText; - break; - case 1: - eType = veInt; - break; - case 2: - eType = veFloat; - break; - default: - sprintf(pBueffel,"Var %s Type --> %s <-- not recognized", - argv[1], argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +static char *cType[] = { + "text", + "int", + "float", + NULL +}; + +int VarFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSicsVariable pRes = NULL; + char pBueffel[512]; + VarType eType; + int i; + int iCode, iRet; + + assert(pCon); + assert(pSics); + + /* check if enough commands */ + argtolower(argc, argv); + if (argc < 4) { + sprintf(pBueffel, + "Insufficient no of args to %s, Usage: %s name type accescode", + argv[0], argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* argv[1] is expected to be the name of the var, argv[2] the type */ + /* interpret the type */ + i = 0; + while (cType[i] != NULL) { + if (strcmp(cType[i], argv[2]) == 0) { + break; + } + i++; + } + switch (i) { + case 0: + eType = veText; + break; + case 1: + eType = veInt; + break; + case 2: + eType = veFloat; + break; + default: + sprintf(pBueffel, "Var %s Type --> %s <-- not recognized", + argv[1], argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* argv[3] must be the access code, check that now */ + i = decodeSICSPriv(argv[3]); + if (i < 0) { + sprintf(pBueffel, " %s access code %s not recognized", + argv[1], argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* now we can actually install the variable */ + pRes = VarCreate(i, eType, argv[1]); + if (!pRes) { + sprintf(pBueffel, "Memory Error creating variable %s", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = AddCommand(pSics, argv[1], VarWrapper, (KillFunc) VarKill, pRes); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + VarKill(pRes); + return 0; + } + return 1; +} - /* argv[3] must be the access code, check that now */ - i = decodeSICSPriv(argv[3]); - if(i < 0){ - sprintf(pBueffel," %s access code %s not recognized", - argv[1], argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* now we can actually install the variable */ - pRes = VarCreate(i,eType,argv[1]); - if(!pRes) - { - sprintf(pBueffel,"Memory Error creating variable %s", argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = AddCommand(pSics,argv[1],VarWrapper,(KillFunc)VarKill,pRes); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBueffel,eError); - VarKill(pRes); - return 0; - } - return 1; - } /*---------------------------------------------------------------------------*/ - int VarKill(pSicsVariable self) - { - - assert(self); - - if(self->text) - { - free(self->text); - } - if(self->pDescriptor) - { - DeleteDescriptor(self->pDescriptor); - } - if(self->pCall) - { - DeleteCallBackInterface(self->pCall); - } - if(self->name) - { - free(self->name); - } - - free(self); - return 1; - } +int VarKill(pSicsVariable self) +{ + + assert(self); + + if (self->text) { + free(self->text); + } + if (self->pDescriptor) { + DeleteDescriptor(self->pDescriptor); + } + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + } + if (self->name) { + free(self->name); + } + + free(self); + return 1; +} + /*---------------------------------------------------------------------------*/ - int VarSetFloat(pSicsVariable self, float fNew, int iUserRights) - { - assert(self); - assert(self->eType == veFloat); - - if(self->iAccessCode < iUserRights) - { - return 0; - } - else - { - self->fVal = fNew; - InvokeCallBack(self->pCall, VALUECHANGE, self); - } - return 1; +int VarSetFloat(pSicsVariable self, float fNew, int iUserRights) +{ + assert(self); + assert(self->eType == veFloat); + + if (self->iAccessCode < iUserRights) { + return 0; + } else { + self->fVal = fNew; + InvokeCallBack(self->pCall, VALUECHANGE, self); } + return 1; +} + /*--------------------------------------------------------------------------*/ - int VarSetInt(pSicsVariable self, int iNew, int iUserRights) - { - assert(self); - assert(self->eType == veInt); - - if(self->iAccessCode < iUserRights) - { - return 0; - } - else - { - self->iVal = iNew; - InvokeCallBack(self->pCall, VALUECHANGE, self); - } - return 1; +int VarSetInt(pSicsVariable self, int iNew, int iUserRights) +{ + assert(self); + assert(self->eType == veInt); + + if (self->iAccessCode < iUserRights) { + return 0; + } else { + self->iVal = iNew; + InvokeCallBack(self->pCall, VALUECHANGE, self); } + return 1; +} + /*--------------------------------------------------------------------------*/ - int VarSetText(pSicsVariable self, char *pNew, int iUserRights) - { - assert(self); - assert(self->eType == veText); - - if(self->iAccessCode < iUserRights) - { - return 0; - } - else - { - if(self->text) - { - free(self->text); - } - self->text = strdup(pNew); - InvokeCallBack(self->pCall, VALUECHANGE, self); - } - return 1; +int VarSetText(pSicsVariable self, char *pNew, int iUserRights) +{ + assert(self); + assert(self->eType == veText); + + if (self->iAccessCode < iUserRights) { + return 0; + } else { + if (self->text) { + free(self->text); + } + self->text = strdup(pNew); + InvokeCallBack(self->pCall, VALUECHANGE, self); } + return 1; +} + /*--------------------------------------------------------------------------*/ - int VarGetFloat(pSicsVariable self, float *fNew) - { - assert(self); - assert(self->eType == veFloat); - - *fNew = self->fVal; - return 1; - } +int VarGetFloat(pSicsVariable self, float *fNew) +{ + assert(self); + assert(self->eType == veFloat); + + *fNew = self->fVal; + return 1; +} + /*--------------------------------------------------------------------------*/ - int VarGetInt(pSicsVariable self, int *iNew) - { - assert(self); - assert(self->eType == veInt); - - *iNew = self->iVal; - return 1; - } +int VarGetInt(pSicsVariable self, int *iNew) +{ + assert(self); + assert(self->eType == veInt); + + *iNew = self->iVal; + return 1; +} + /*--------------------------------------------------------------------------*/ - int VarGetText(pSicsVariable self, char **pNew) - { - assert(self); - assert(self->eType == veText); - - *pNew = strdup(self->text); - return 1; - } +int VarGetText(pSicsVariable self, char **pNew) +{ + assert(self); + assert(self->eType == veText); + + *pNew = strdup(self->text); + return 1; +} + /*------------------------------------------------------------------------*/ - VarType GetVarType(pSicsVariable self) - { - assert(self); - return self->eType; - } +VarType GetVarType(pSicsVariable self) +{ + assert(self); + return self->eType; +} + /*--------------------------------------------------------------------------*/ - int VarSetRights(pSicsVariable self, int iNewRights, int iYourRights) - { - assert(self); - - if( iYourRights > 1) /* only muggers allowed here */ - { - return 0; - } - else - { - self->iAccessCode = iNewRights; - return 1; - } - } +int VarSetRights(pSicsVariable self, int iNewRights, int iYourRights) +{ + assert(self); + + if (iYourRights > 1) { /* only muggers allowed here */ + return 0; + } else { + self->iAccessCode = iNewRights; + return 1; + } +} + /*--------------------------------------------------------------------*/ - static int VarInterestCallback(int iEvent, void *pEvent, void *pUser) - { - SConnection *pCon; - char pBueffel[512]; - pSicsVariable pVar = NULL; - int iVal, status; - float fVal; - char *pText; - - assert(pEvent); - assert(pUser); - - pVar = (pSicsVariable)pEvent; - pCon = (SConnection *)pUser; +static int VarInterestCallback(int iEvent, void *pEvent, void *pUser) +{ + SConnection *pCon; + char pBueffel[512]; + pSicsVariable pVar = NULL; + int iVal, status; + float fVal; + char *pText; - /* check kill conditions */ - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } + assert(pEvent); + assert(pUser); + + pVar = (pSicsVariable) pEvent; + pCon = (SConnection *) pUser; + + /* check kill conditions */ + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + switch (pVar->eType) { + case veInt: + VarGetInt(pVar, &iVal); + sprintf(pBueffel, "%s = %d", pVar->name, iVal); + SCWrite(pCon, pBueffel, eValue); + status = 1; + break; + case veFloat: + VarGetFloat(pVar, &fVal); + sprintf(pBueffel, "%s = %f", pVar->name, fVal); + SCWrite(pCon, pBueffel, eValue); + status = 1; + break; + case veText: + VarGetText(pVar, &pText); + sprintf(pBueffel, "%s = %s", pVar->name, pText); + SCWrite(pCon, pBueffel, eValue); + if (pText) { + free(pText); + } + status = 1; + break; + } + return status; +} - switch(pVar->eType) - { - case veInt: - VarGetInt(pVar,&iVal); - sprintf(pBueffel,"%s = %d",pVar->name,iVal); - SCWrite(pCon,pBueffel,eValue); - status = 1; - break; - case veFloat: - VarGetFloat(pVar,&fVal); - sprintf(pBueffel,"%s = %f",pVar->name,fVal); - SCWrite(pCon,pBueffel,eValue); - status = 1; - break; - case veText: - VarGetText(pVar,&pText); - sprintf(pBueffel,"%s = %s", pVar->name,pText); - SCWrite(pCon,pBueffel,eValue); - if(pText) - { - free(pText); - } - status = 1; - break; - } - return status; - } /*----------------------------------------------------------------------*/ -static int VarSetFromText(pSicsVariable self, SConnection *pCon, char *text) +static int VarSetFromText(pSicsVariable self, SConnection * pCon, + char *text) { int status; double dVal; char pBueffel[132]; - if(!SCMatchRights(pCon,self->iAccessCode)) - { + if (!SCMatchRights(pCon, self->iAccessCode)) { return 0; } - if(self->eType == veText) - { - return VarSetText(self,text,SCGetRights(pCon)); + if (self->eType == veText) { + return VarSetText(self, text, SCGetRights(pCon)); } - status = Tcl_GetDouble(InterpGetTcl(pServ->pSics), text,&dVal); - if(status != TCL_OK) - { - snprintf(pBueffel,131,"ERROR: failed to convert %s to number", - text); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pServ->pSics), text, &dVal); + if (status != TCL_OK) { + snprintf(pBueffel, 131, "ERROR: failed to convert %s to number", text); + SCWrite(pCon, pBueffel, eError); return 0; } - if(self->eType == veInt) - { - return VarSetInt(self,(int)dVal,SCGetRights(pCon)); - } - else if(self->eType == veFloat) - { - return VarSetFloat(self,(float)dVal,SCGetRights(pCon)); + if (self->eType == veInt) { + return VarSetInt(self, (int) dVal, SCGetRights(pCon)); + } else if (self->eType == veFloat) { + return VarSetFloat(self, (float) dVal, SCGetRights(pCon)); } return 0; -} +} + /*-------------------------------------------------------------------------- Variables understands some commands: setrights : for setting user rights @@ -433,228 +412,196 @@ static int VarSetFromText(pSicsVariable self, SConnection *pCon, char *text) interest : for notifictaion on value change uninterest : delete notification */ - int VarWrapper(SConnection *pCon, SicsInterp *pInterp, void *pData, - int argc, char *argv[]) - { - float fVal; - int iVal; - char *pText = NULL; - pSicsVariable pVar = NULL; - VarType eTyp; - TokenList *pList = NULL; - TokenList *pCurrent; - char pBueffel[256]; - int iRet; - Status eStat; - long lID; +int VarWrapper(SConnection * pCon, SicsInterp * pInterp, void *pData, + int argc, char *argv[]) +{ + float fVal; + int iVal; + char *pText = NULL; + pSicsVariable pVar = NULL; + VarType eTyp; + TokenList *pList = NULL; + TokenList *pCurrent; + char pBueffel[256]; + int iRet; + Status eStat; + long lID; - assert(pCon); - assert(pInterp); - assert(pData); - - /* get Variable pointer */ - pVar = ( pSicsVariable ) pData; - eTyp = GetVarType(pVar); - - /* tokenize arguments */ - pList = SplitArguments(argc, argv); - if(!pList) - { - SCWrite(pCon,"ERROR: cannot parse arguments",eError); - return 0; - } - - pCurrent = pList->pNext; /* if only one arg: print the value */ - if(!pCurrent) - { - switch(eTyp) - { - case veInt: - VarGetInt(pVar,&iVal); - sprintf(pBueffel,"%s = %d",argv[0],iVal); - SCWrite(pCon,pBueffel,eValue); - DeleteTokenList(pList); - return 1; - case veFloat: - VarGetFloat(pVar,&fVal); - sprintf(pBueffel,"%s = %f",argv[0],fVal); - SCWrite(pCon,pBueffel,eValue); - DeleteTokenList(pList); - return 1; - case veText: - VarGetText(pVar,&pText); - sprintf(pBueffel,"%s = %s", argv[0],pText); - SCWrite(pCon,pBueffel,eValue); - if(pText) - { - free(pText); - } - DeleteTokenList(pList); - return 1; - } - } + assert(pCon); + assert(pInterp); + assert(pData); - /* now either new value, lock or setAccess */ - strtolower(pCurrent->text); - if (strcmp(pCurrent->text,"setaccess") == 0) - { - pCurrent = pCurrent->pNext; - if(pCurrent) - { - if(pCurrent->Type != eInt) - { - SCWrite(pCon,"Wrong argument for setAccess, expect Integer",eError); - DeleteTokenList(pList); - return 0; - } - else - { - /* is control grabbed ? */ - if(SCGetGrab(pCon) != 0) - { - SCWrite(pCon, - "ERROR: somebody else has grabbed control, Request REJECTED", - eError); - DeleteTokenList(pList); - return 0; - } - /* finaly do it */ - iRet = VarSetRights(pVar,pCurrent->iVal,SCGetRights(pCon)); - if(!iRet) - { - SCWrite(pCon, - "You have no privilege to change AccessCodes",eError); - } - DeleteTokenList(pList); - SCSendOK(pCon); - return 1; - } - } - else - { - SCWrite(pCon, - "Missing argument to setAccess",eError); - DeleteTokenList(pList); - return 0; - } - } - else if(strcmp(pCurrent->text,"interest") == 0) /* interest */ - { - lID = RegisterCallback(pVar->pCall, - VALUECHANGE, VarInterestCallback, - SCCopyConnection(pCon), SCDeleteConnection); + /* get Variable pointer */ + pVar = (pSicsVariable) pData; + eTyp = GetVarType(pVar); + + /* tokenize arguments */ + pList = SplitArguments(argc, argv); + if (!pList) { + SCWrite(pCon, "ERROR: cannot parse arguments", eError); + return 0; + } + + pCurrent = pList->pNext; /* if only one arg: print the value */ + if (!pCurrent) { + switch (eTyp) { + case veInt: + VarGetInt(pVar, &iVal); + sprintf(pBueffel, "%s = %d", argv[0], iVal); + SCWrite(pCon, pBueffel, eValue); + DeleteTokenList(pList); + return 1; + case veFloat: + VarGetFloat(pVar, &fVal); + sprintf(pBueffel, "%s = %f", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + DeleteTokenList(pList); + return 1; + case veText: + VarGetText(pVar, &pText); + sprintf(pBueffel, "%s = %s", argv[0], pText); + SCWrite(pCon, pBueffel, eValue); + if (pText) { + free(pText); + } + DeleteTokenList(pList); + return 1; + } + } + + /* now either new value, lock or setAccess */ + strtolower(pCurrent->text); + if (strcmp(pCurrent->text, "setaccess") == 0) { + pCurrent = pCurrent->pNext; + if (pCurrent) { + if (pCurrent->Type != eInt) { + SCWrite(pCon, "Wrong argument for setAccess, expect Integer", + eError); DeleteTokenList(pList); - SCSendOK(pCon); - return 1; - } - else if(strcmp(pCurrent->text,"uninterest") == 0) - { - RemoveCallbackCon(pVar->pCall,pCon); - DeleteTokenList(pList); - SCSendOK(pCon); - return 1; - } - else if(strcmp(pCurrent->text,"lock") == 0) - { - pVar->iLock = 1; + return 0; + } else { + /* is control grabbed ? */ + if (SCGetGrab(pCon) != 0) { + SCWrite(pCon, + "ERROR: somebody else has grabbed control, Request REJECTED", + eError); + DeleteTokenList(pList); + return 0; + } + /* finaly do it */ + iRet = VarSetRights(pVar, pCurrent->iVal, SCGetRights(pCon)); + if (!iRet) { + SCWrite(pCon, + "You have no privilege to change AccessCodes", eError); + } DeleteTokenList(pList); SCSendOK(pCon); return 1; - } - else if(strcmp(pCurrent->text,"force") == 0) - { - /* - Undocumented feauture: force a set even while driving etc. - Internal privilege required to do this. - */ - if(!SCMatchRights(pCon,usInternal)) - { - return 0; - } - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - SCWrite(pCon,"ERROR: new value missing for force",eError); - return 0; - } - Arg2Text(argc-2,&argv[2],pBueffel,255); - iRet = VarSetFromText(pVar,pCon,pBueffel); - if(iRet == 1) - { - SCSendOK(pCon); - } - SCparChange(pCon); - DeleteTokenList(pList); - return iRet; - } - else - { - /* now, only a new value is still possible */ - eStat = GetStatus(); - if( (eStat != eEager) && (eStat != eBatch) ) - { - SCWrite(pCon, - "You cannot set variables while a scan is running",eError); - DeleteTokenList(pList); - return 0; + } + } else { + SCWrite(pCon, "Missing argument to setAccess", eError); + DeleteTokenList(pList); + return 0; + } + } else if (strcmp(pCurrent->text, "interest") == 0) { /* interest */ + lID = RegisterCallback(pVar->pCall, + VALUECHANGE, VarInterestCallback, + SCCopyConnection(pCon), SCDeleteConnection); + DeleteTokenList(pList); + SCSendOK(pCon); + return 1; + } else if (strcmp(pCurrent->text, "uninterest") == 0) { + RemoveCallbackCon(pVar->pCall, pCon); + DeleteTokenList(pList); + SCSendOK(pCon); + return 1; + } else if (strcmp(pCurrent->text, "lock") == 0) { + pVar->iLock = 1; + DeleteTokenList(pList); + SCSendOK(pCon); + return 1; + } else if (strcmp(pCurrent->text, "force") == 0) { + /* + Undocumented feauture: force a set even while driving etc. + Internal privilege required to do this. + */ + if (!SCMatchRights(pCon, usInternal)) { + return 0; + } + pCurrent = pCurrent->pNext; + if (!pCurrent) { + SCWrite(pCon, "ERROR: new value missing for force", eError); + return 0; + } + Arg2Text(argc - 2, &argv[2], pBueffel, 255); + iRet = VarSetFromText(pVar, pCon, pBueffel); + if (iRet == 1) { + SCSendOK(pCon); + } + SCparChange(pCon); + DeleteTokenList(pList); + return iRet; + } else { + /* now, only a new value is still possible */ + eStat = GetStatus(); + if ((eStat != eEager) && (eStat != eBatch)) { + SCWrite(pCon, + "You cannot set variables while a scan is running", eError); + DeleteTokenList(pList); + return 0; - } - iRet = 0; - if(pCurrent) - { - /* is it locked ? */ - if(pVar->iLock) - { - sprintf(pBueffel,"ERROR: variable %s is configured locked!", - argv[0]); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return 0; - } - /* is control grabbed ? */ - if(SCGetGrab(pCon) != 0) - { - SCWrite(pCon,"ERROR: somebody else has grabbed control, Request REJECTED",eError); - DeleteTokenList(pList); - return 0; - } - Arg2Text(argc-1,&argv[1],pBueffel,255); - iRet = VarSetFromText(pVar,pCon,pBueffel); - if(iRet == 1) - { - SCSendOK(pCon); - } - SCparChange(pCon); - DeleteTokenList(pList); - return iRet; - } - } - - /* if we are here, no valid command was found */ - SCWrite(pCon, - "No valid syntax found in Variable",eError); - DeleteTokenList(pList); - return 0; + } + iRet = 0; + if (pCurrent) { + /* is it locked ? */ + if (pVar->iLock) { + sprintf(pBueffel, "ERROR: variable %s is configured locked!", + argv[0]); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return 0; + } + /* is control grabbed ? */ + if (SCGetGrab(pCon) != 0) { + SCWrite(pCon, + "ERROR: somebody else has grabbed control, Request REJECTED", + eError); + DeleteTokenList(pList); + return 0; + } + Arg2Text(argc - 1, &argv[1], pBueffel, 255); + iRet = VarSetFromText(pVar, pCon, pBueffel); + if (iRet == 1) { + SCSendOK(pCon); + } + SCparChange(pCon); + DeleteTokenList(pList); + return iRet; + } } + + /* if we are here, no valid command was found */ + SCWrite(pCon, "No valid syntax found in Variable", eError); + DeleteTokenList(pList); + return 0; +} + /*-------------------------------------------------------------------------*/ - pSicsVariable FindVariable(SicsInterp *pSics, char *name) - { - CommandList *pC; - pSicsVariable pVar; - - pC = FindCommand(pSics,name); - if(!pC) - { - return NULL; - } - pVar = (pSicsVariable)pC->pData; - if(!pVar) - { - return NULL; - } - if(strcmp(pVar->pDescriptor->name,"SicsVariable") != 0) - { - return NULL; - } - return pVar; +pSicsVariable FindVariable(SicsInterp * pSics, char *name) +{ + CommandList *pC; + pSicsVariable pVar; + + pC = FindCommand(pSics, name); + if (!pC) { + return NULL; } + pVar = (pSicsVariable) pC->pData; + if (!pVar) { + return NULL; + } + if (strcmp(pVar->pDescriptor->name, "SicsVariable") != 0) { + return NULL; + } + return pVar; +} diff --git a/sig_die.c b/sig_die.c index cf20f5a1..eead5765 100644 --- a/sig_die.c +++ b/sig_die.c @@ -8,45 +8,43 @@ #endif #ifdef KR_headers -void sig_die(s, kill) register char *s; int kill; +void sig_die(s, kill) +register char *s; +int kill; #else #include "stdlib.h" #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus -extern "C" { + extern "C" { #endif - void f_exit(void){ - exit(0); - } - -void sig_die(register char *s, int kill) + void f_exit(void) { + exit(0); + } void sig_die(register char *s, int kill) #endif -{ - /* print error message, then clear buffers */ - fprintf(stderr, "%s\n", s); + { + /* print error message, then clear buffers */ + fprintf(stderr, "%s\n", s); - if(kill) - { - fflush(stderr); - f_exit(); - fflush(stderr); - /* now get a core */ + if (kill) { + fflush(stderr); + f_exit(); + fflush(stderr); + /* now get a core */ #ifdef SIGIOT - signal(SIGIOT, SIG_DFL); + signal(SIGIOT, SIG_DFL); #endif - abort(); - } - else { + abort(); + } else { #ifdef NO_ONEXIT - f_exit(); + f_exit(); #endif - exit(1); - } - } + exit(1); + } + } #ifdef __cplusplus -} + } #endif #ifdef __cplusplus } diff --git a/simchop.c b/simchop.c index b2e4e33b..08c508f0 100644 --- a/simchop.c +++ b/simchop.c @@ -23,305 +23,276 @@ #define FAILRATE 0.00005 #define WARNRATE 0.00001 /*-----------------------------------------------------------------------*/ - typedef struct { - time_t tTarget; - float fRot; - float fPhase; - float fRatio; - int iError; - int iStop; - }ChopPriv, *pChopPriv; +typedef struct { + time_t tTarget; + float fRot; + float fPhase; + float fRatio; + int iError; + int iStop; +} ChopPriv, *pChopPriv; /*------------------------------------------------------------------------*/ - static float SimRandom(void) - { - float fVal; - - fVal = ( (float) rand() / (float)RAND_MAX) * 100.0; - return fVal; - } +static float SimRandom(void) +{ + float fVal; + + fVal = ((float) rand() / (float) RAND_MAX) * 100.0; + return fVal; +} + /*--------------- Driver functions ---------------------------------------*/ - static int SDInit(pCodri self) - { - return 1; - } +static int SDInit(pCodri self) +{ + return 1; +} + /*--------------------------------------------------------------------- */ - static int SDClose(pCodri self) - { - return 1; - } +static int SDClose(pCodri self) +{ + return 1; +} + /*-----------------------------------------------------------------------*/ - static int SDDelete(pCodri self) - { - if(self->pParList) - free(self->pParList); - if(self->pPrivate) - free(self->pPrivate); - return 1; - } +static int SDDelete(pCodri self) +{ + if (self->pParList) + free(self->pParList); + if (self->pPrivate) + free(self->pPrivate); + return 1; +} + /*----------------------------------------------------------------------*/ - static int SDHalt(pCodri self) - { - pChopPriv pPriv = NULL; +static int SDHalt(pCodri self) +{ + pChopPriv pPriv = NULL; - assert(self); - pPriv = (pChopPriv)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pChopPriv) self->pPrivate; + assert(pPriv); + + pPriv->iStop = 1; + return 1; +} - pPriv->iStop = 1; - return 1; - } /*-----------------------------------------------------------------------*/ - static int SDSetPar(pCodri self, char *parname, float fValue) - { - pChopPriv pPriv = NULL; +static int SDSetPar(pCodri self, char *parname, float fValue) +{ + pChopPriv pPriv = NULL; - assert(self); - pPriv = (pChopPriv)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pChopPriv) self->pPrivate; + assert(pPriv); - /* clear stop flag */ - pPriv->iStop = 0; + /* clear stop flag */ + pPriv->iStop = 0; + + if (strcmp(parname, "speed") == 0) { + pPriv->fRot = fValue; + pPriv->tTarget = time(NULL) + 20; + return 1; + } else if (strcmp(parname, "phase") == 0) { + pPriv->fPhase = fValue; + pPriv->tTarget = time(NULL) + 20; + return 1; + } else if (strcmp(parname, "ratio") == 0) { + pPriv->fRatio = fValue; + pPriv->tTarget = time(NULL) + 20; + return 1; + } else { + pPriv->iError = UNKNOWNPAR; + return 0; + } +} - if(strcmp(parname,"speed") == 0) - { - pPriv->fRot = fValue; - pPriv->tTarget = time(NULL) + 20; - return 1; - } - else if(strcmp(parname,"phase") == 0) - { - pPriv->fPhase = fValue; - pPriv->tTarget = time(NULL) + 20; - return 1; - } - else if(strcmp(parname,"ratio") == 0) - { - pPriv->fRatio = fValue; - pPriv->tTarget = time(NULL) + 20; - return 1; - } - else - { - pPriv->iError = UNKNOWNPAR; - return 0; - } - } /*------------------------------------------------------------------------*/ - static int SDSetPar2(pCodri self, char *parname, char *pValue) - { - pChopPriv pPriv = NULL; +static int SDSetPar2(pCodri self, char *parname, char *pValue) +{ + pChopPriv pPriv = NULL; - assert(self); - pPriv = (pChopPriv)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pChopPriv) self->pPrivate; + assert(pPriv); + pPriv->iError = UNKNOWNPAR; + return 0; +} + +/*-------------------------------------------------------------------------*/ +static int SDGetPar(pCodri self, char *parname, char *pBuffer, int iBufLen) +{ + pChopPriv pPriv = NULL; + float fFail; + char pBueffel[50]; + + assert(self); + pPriv = (pChopPriv) self->pPrivate; + assert(pPriv); + + /* failure calculation first, we do so randomly in order to + check error processing code + */ + fFail = SimRandom(); + if (fFail < WARNRATE) { + pPriv->iError = RANDOMWARNING; + return 0; + } + if (fFail < FAILRATE) { + pPriv->iError = RANDOMERROR; + return 0; + } + + /* are we busy driving something? */ + if (time(NULL) < pPriv->tTarget) { + if (strcmp(parname, "speed") == 0) { + sprintf(pBueffel, "%f", pPriv->fRot - 1.); + } else if (strcmp(parname, "phase") == 0) { + sprintf(pBueffel, "%f", pPriv->fPhase - 1.); + } else if (strcmp(parname, "ratio") == 0) { + sprintf(pBueffel, "%f", pPriv->fRatio - 1.); + } else { pPriv->iError = UNKNOWNPAR; - return 0; - } -/*-------------------------------------------------------------------------*/ - static int SDGetPar(pCodri self, char *parname, char *pBuffer, int iBufLen) - { - pChopPriv pPriv = NULL; - float fFail; - char pBueffel[50]; + return 0; + } + strncpy(pBuffer, pBueffel, iBufLen); + return 1; + } - assert(self); - pPriv = (pChopPriv)self->pPrivate; - assert(pPriv); + /* all normal */ + if (strcmp(parname, "speed") == 0) { + sprintf(pBueffel, "%f", pPriv->fRot); + } else if (strcmp(parname, "phase") == 0) { + sprintf(pBueffel, "%f", pPriv->fPhase); + } else if (strcmp(parname, "ratio") == 0) { + sprintf(pBueffel, "%f", pPriv->fRatio); + } else { + pPriv->iError = UNKNOWNPAR; + return 0; + } + strncpy(pBuffer, pBueffel, iBufLen); + return 1; +} - /* failure calculation first, we do so randomly in order to - check error processing code - */ - fFail = SimRandom(); - if(fFail < WARNRATE) - { - pPriv->iError = RANDOMWARNING; - return 0; - } - if(fFail < FAILRATE) - { - pPriv->iError = RANDOMERROR; - return 0; - } - - /* are we busy driving something? */ - if(time(NULL) < pPriv->tTarget) - { - if(strcmp(parname,"speed") == 0) - { - sprintf(pBueffel,"%f",pPriv->fRot - 1.); - } - else if(strcmp(parname,"phase") == 0) - { - sprintf(pBueffel,"%f",pPriv->fPhase - 1.); - } - else if(strcmp(parname,"ratio") == 0) - { - sprintf(pBueffel,"%f",pPriv->fRatio - 1.); - } - else - { - pPriv->iError = UNKNOWNPAR; - return 0; - } - strncpy(pBuffer,pBueffel,iBufLen); - return 1; - } - - /* all normal */ - if(strcmp(parname,"speed") == 0) - { - sprintf(pBueffel,"%f",pPriv->fRot); - } - else if(strcmp(parname,"phase") == 0) - { - sprintf(pBueffel,"%f",pPriv->fPhase); - } - else if(strcmp(parname,"ratio") == 0) - { - sprintf(pBueffel,"%f",pPriv->fRatio); - } - else - { - pPriv->iError = UNKNOWNPAR; - return 0; - } - strncpy(pBuffer,pBueffel,iBufLen); - return 1; - } /*------------------------------------------------------------------------*/ - static int SDCheckPar(pCodri self, char *parname) - { - pChopPriv pPriv = NULL; - float fFail; +static int SDCheckPar(pCodri self, char *parname) +{ + pChopPriv pPriv = NULL; + float fFail; - assert(self); - pPriv = (pChopPriv)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pChopPriv) self->pPrivate; + assert(pPriv); - /* - throw a HWFalut when stopped */ - if(pPriv->iStop) - { - pPriv->iError = STOPPED; - return HWFault; - } + /* + throw a HWFalut when stopped */ + if (pPriv->iStop) { + pPriv->iError = STOPPED; + return HWFault; + } + + /* failure calculation first, we do so randomly in order to + check error processing code + */ + fFail = SimRandom(); + if (fFail < WARNRATE) { + pPriv->iError = RANDOMWARNING; + return HWFault; + } + if (fFail < FAILRATE) { + pPriv->iError = RANDOMERROR; + return HWFault; + } + + /* are we busy driving something? */ + if (time(NULL) < pPriv->tTarget) { + return HWBusy; + } + return HWIdle; +} - /* failure calculation first, we do so randomly in order to - check error processing code - */ - fFail = SimRandom(); - if(fFail < WARNRATE) - { - pPriv->iError = RANDOMWARNING; - return HWFault; - } - if(fFail < FAILRATE) - { - pPriv->iError = RANDOMERROR; - return HWFault; - } - - /* are we busy driving something? */ - if(time(NULL) < pPriv->tTarget) - { - return HWBusy; - } - return HWIdle; - } /*-----------------------------------------------------------------------*/ - static int SDGetError(pCodri self, int *iCode, char *pError, int iErrLen) - { - pChopPriv pPriv = NULL; +static int SDGetError(pCodri self, int *iCode, char *pError, int iErrLen) +{ + pChopPriv pPriv = NULL; - assert(self); - pPriv = (pChopPriv)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pChopPriv) self->pPrivate; + assert(pPriv); - *iCode = pPriv->iError; + *iCode = pPriv->iError; + + switch (pPriv->iError) { + case UNKNOWNPAR: + strncpy(pError, "Parameter Unknown", iErrLen); + break; + case RANDOMWARNING: + strncpy(pError, "Random non deadly error", iErrLen); + break; + case RANDOMERROR: + strncpy(pError, "Random DEADLY Error", iErrLen); + break; + case STOPPED: + strncpy(pError, "User initiated STOP", iErrLen); + break; + default: + strncpy(pError, "Unknown error code", iErrLen); + break; + } + return 1; +} - switch(pPriv->iError) - { - case UNKNOWNPAR: - strncpy(pError,"Parameter Unknown",iErrLen); - break; - case RANDOMWARNING: - strncpy(pError,"Random non deadly error",iErrLen); - break; - case RANDOMERROR: - strncpy(pError,"Random DEADLY Error",iErrLen); - break; - case STOPPED: - strncpy(pError,"User initiated STOP",iErrLen); - break; - default: - strncpy(pError,"Unknown error code",iErrLen); - break; - } - return 1; - } /*-------------------------------------------------------------------------*/ - static int SDTryFixIt(pCodri self, int iCode) - { - pChopPriv pPriv = NULL; +static int SDTryFixIt(pCodri self, int iCode) +{ + pChopPriv pPriv = NULL; - assert(self); - pPriv = (pChopPriv)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pChopPriv) self->pPrivate; + assert(pPriv); + + switch (iCode) { + case UNKNOWNPAR: + case RANDOMERROR: + case STOPPED: + return CHFAIL; + case RANDOMWARNING: + return CHREDO; + default: + break; + } + return CHFAIL; +} - switch(iCode) - { - case UNKNOWNPAR: - case RANDOMERROR: - case STOPPED: - return CHFAIL; - case RANDOMWARNING: - return CHREDO; - default: - break; - } - return CHFAIL; - } /*------------------------------------------------------------------------*/ - pCodri MakeSimChopper(void) - { - pCodri pNew = NULL; - pChopPriv pPriv = NULL; - - /* allocate space */ - pNew = (pCodri)malloc(sizeof(Codri)); - pPriv = (pChopPriv)malloc(sizeof(ChopPriv)); - memset(pPriv,0,sizeof(ChopPriv)); - pPriv->tTarget = time(NULL); - - if( (pPriv == NULL) || (pNew == NULL) ) - { - return NULL; - } - - /* initialize this thing */ - pNew->Init = SDInit; - pNew->Close = SDClose; - pNew->Delete = SDDelete; - pNew->SetPar = SDSetPar; - pNew->SetPar2 = SDSetPar2; - pNew->GetPar = SDGetPar; - pNew->CheckPar = SDCheckPar; - pNew->GetError = SDGetError; - pNew->TryFixIt = SDTryFixIt; - pNew->Halt = SDHalt; - - pNew->pParList = strdup("speed,phase,ratio"); - pNew->pPrivate = pPriv; - - return pNew; - } - - - - +pCodri MakeSimChopper(void) +{ + pCodri pNew = NULL; + pChopPriv pPriv = NULL; + /* allocate space */ + pNew = (pCodri) malloc(sizeof(Codri)); + pPriv = (pChopPriv) malloc(sizeof(ChopPriv)); + memset(pPriv, 0, sizeof(ChopPriv)); + pPriv->tTarget = time(NULL); + if ((pPriv == NULL) || (pNew == NULL)) { + return NULL; + } + /* initialize this thing */ + pNew->Init = SDInit; + pNew->Close = SDClose; + pNew->Delete = SDDelete; + pNew->SetPar = SDSetPar; + pNew->SetPar2 = SDSetPar2; + pNew->GetPar = SDGetPar; + pNew->CheckPar = SDCheckPar; + pNew->GetError = SDGetError; + pNew->TryFixIt = SDTryFixIt; + pNew->Halt = SDHalt; + pNew->pParList = strdup("speed,phase,ratio"); + pNew->pPrivate = pPriv; + return pNew; +} diff --git a/simcter.c b/simcter.c index 821cc0a4..dd24d210 100644 --- a/simcter.c +++ b/simcter.c @@ -52,309 +52,290 @@ */ static float FAILRATE; /*----------------------------------------------------------------------------*/ - static float SimRandom(void) - { - float fVal; - - fVal = ( (float) rand() / (float)RAND_MAX) * 100.0; - return fVal; - } -/*---------------------------------------------------------------------------*/ - typedef struct { - long lEnd; - int iPause; - long tStart; - } SimSt; -/*---------------------------------------------------------------------------*/ - static int SIMGetStatus(struct __COUNTER *self, float *fControl) - { - SimSt *pSim = NULL; - time_t tD, tDe; - int iRun; - - assert(self); - pSim = (SimSt *)self->pData; - assert(pSim); - - /* - no fail, no wait case - */ - if(FAILRATE < .0) - { - return HWIdle; - } +static float SimRandom(void) +{ + float fVal; - if(pSim->iPause == 1) - { - return HWPause; - } - - if(SimRandom() < FAILRATE) - { - return HWFault; - } - - /* calculate time */ - self->fTime = (long)time(NULL) - pSim->tStart; - - iRun = 1; - if(self->eMode == eTimer) - { - if((long)time(&tD) > pSim->lEnd) - { - iRun = 0; - } - tDe = pSim->lEnd - tD; - *fControl = (float)tDe; - - } - else - { - pSim->lEnd += SimRandom(); - if(pSim->lEnd > (long)self->fPreset) - { - iRun = 0; - } - *fControl = (float)pSim->lEnd; - } - if(iRun) - { - return HWBusy; - } - else - { - return HWIdle; - } - } -/*---------------------------------------------------------------------------*/ - static int SIMStart(struct __COUNTER *self) - { - SimSt *pSim = NULL; - time_t tD; - int iRun; - - assert(self); - pSim = (SimSt *)self->pData; - assert(pSim); - - pSim->iPause = 0; - pSim->tStart = time(NULL); - if(self->eMode == eTimer) - { - pSim->lEnd = (long)time(&tD) + (long)self->fPreset; - } - else - { - pSim->lEnd = 0; - } - - if(FAILRATE < .0) - { - return OKOK; - } - - if(SimRandom() < FAILRATE) - { - return HWFault; - } - - return OKOK; - } -/*---------------------------------------------------------------------------*/ - static int SIMPause(struct __COUNTER *self) - { - SimSt *pSim = NULL; - time_t tD; - int iRun; - - assert(self); - pSim = (SimSt *)self->pData; - assert(pSim); - - pSim->iPause = 1; - - /* - no fail, no wait case - */ - if(FAILRATE < .0) - { - return OKOK; - } - - if(SimRandom() < FAILRATE) - { - return HWFault; - } - - return OKOK; - } -/*---------------------------------------------------------------------------*/ - static int SIMContinue(struct __COUNTER *self) - { - SimSt *pSim = NULL; - time_t tD; - int iRun; - - assert(self); - pSim = (SimSt *)self->pData; - assert(pSim); - - pSim->iPause = 0; - - if(FAILRATE < .0) - { - return OKOK; - } - - if(SimRandom() < FAILRATE) - { - return HWFault; - } - - return OKOK; - } -/*--------------------------------------------------------------------------*/ - static int SIMHalt(struct __COUNTER *self) - { - SimSt *pSim = NULL; - int iRun; - - assert(self); - pSim = (SimSt *)self->pData; - assert(pSim); - - if(FAILRATE < .0) - { - return OKOK; - } - - if(SimRandom() < FAILRATE) - { - return HWFault; - } - if(self->eMode == eTimer) - { - pSim->lEnd = 0; - } - else - { - pSim->lEnd = (long)self->fPreset + 10; - } - return OKOK; - } -/*-------------------------------------------------------------------------*/ - static int SIMReadValues(struct __COUNTER *self) - { - SimSt *pSim = NULL; - int i; - - assert(self); - pSim = (SimSt *)self->pData; - assert(pSim); - - /* - no fail, no wait case - */ - if(FAILRATE < .0) - { - for(i = 0; i < MAXCOUNT; i++) - { - self->lCounts[i] = (long)(SimRandom()*100); - } - self->lCounts[1] = self->fPreset; - return OKOK; - } - - if(SimRandom() < FAILRATE) - { - return HWFault; - } - - for(i = 0; i < MAXCOUNT; i++) - { - self->lCounts[i] = (long)(SimRandom()*100); - } - self->lCounts[1] = self->fPreset; - return OKOK; - } -/*-------------------------------------------------------------------------*/ - static int SIMGetError(struct __COUNTER *self, int *iCode, char *error, - int iErrLen) - { - strncpy(error,"Randomly simulated counter error",iErrLen); - *iCode = 1; - return 1; - } -/*--------------------------------------------------------------------------*/ - static int SIMTryAndFixIt(struct __COUNTER *self, int iCode) - { - if(SimRandom() < FAILRATE) - { - return COTERM; - } - return COREDO; - } -/*--------------------------------------------------------------------------*/ - static int SIMSet(struct __COUNTER *self, char *name, int iCter, float FVal) - { - return 1; - } -/*--------------------------------------------------------------------------*/ - static int SIMGet(struct __COUNTER *self, char *name, int iCter, float *fVal) - { - *fVal = 25.999; - return 1; - } -/*---------------------------------------------------------------------------*/ - static int SIMSend(struct __COUNTER *self, char *pText, - char *pReply, int iReplyLen) - { - strncpy(pReply,"Simulated response",iReplyLen); - return 1; - } -/*---------------------------------------------------------------------------*/ - pCounterDriver NewSIMCounter(char *name, float fFail) - { - pCounterDriver pRes = NULL; - SimSt *pData = NULL; - int iRet; - int iC1, iC2, iC3; - char *pErr; - char pBueffel[132]; - - pRes = CreateCounterDriver(name, "SIM"); - if(!pRes) - { - return NULL; - } - - pData = (SimSt *)malloc(sizeof(SimSt)); - if(!pData) - { - DeleteCounterDriver(pRes); - return NULL; - } - pData->lEnd = 0; - pData->iPause = 0; - pRes->pData = (void *)pData; - pRes->iNoOfMonitors = 8; - pRes->fTime = 0; - - /* assign functions */ - pRes->GetStatus = SIMGetStatus; - pRes->Start = SIMStart; - pRes->Halt = SIMHalt; - pRes->ReadValues = SIMReadValues; - pRes->GetError = SIMGetError; - pRes->TryAndFixIt = SIMTryAndFixIt; - pRes->Pause = SIMPause; - pRes->Continue = SIMContinue; - pRes->Set = SIMSet; - pRes->Get = SIMGet; - pRes->Send = SIMSend; - pRes->KillPrivate = NULL; - - FAILRATE = fFail; - return pRes; + fVal = ((float) rand() / (float) RAND_MAX) * 100.0; + return fVal; +} + +/*---------------------------------------------------------------------------*/ +typedef struct { + long lEnd; + int iPause; + long tStart; +} SimSt; +/*---------------------------------------------------------------------------*/ +static int SIMGetStatus(struct __COUNTER *self, float *fControl) +{ + SimSt *pSim = NULL; + time_t tD, tDe; + int iRun; + + assert(self); + pSim = (SimSt *) self->pData; + assert(pSim); + + /* + no fail, no wait case + */ + if (FAILRATE < .0) { + return HWIdle; + } + + if (pSim->iPause == 1) { + return HWPause; + } + + if (SimRandom() < FAILRATE) { + return HWFault; + } + + /* calculate time */ + self->fTime = (long) time(NULL) - pSim->tStart; + + iRun = 1; + if (self->eMode == eTimer) { + if ((long) time(&tD) > pSim->lEnd) { + iRun = 0; + } + tDe = pSim->lEnd - tD; + *fControl = (float) tDe; + + } else { + pSim->lEnd += SimRandom(); + if (pSim->lEnd > (long) self->fPreset) { + iRun = 0; + } + *fControl = (float) pSim->lEnd; + } + if (iRun) { + return HWBusy; + } else { + return HWIdle; + } +} + +/*---------------------------------------------------------------------------*/ +static int SIMStart(struct __COUNTER *self) +{ + SimSt *pSim = NULL; + time_t tD; + int iRun; + + assert(self); + pSim = (SimSt *) self->pData; + assert(pSim); + + pSim->iPause = 0; + pSim->tStart = time(NULL); + if (self->eMode == eTimer) { + pSim->lEnd = (long) time(&tD) + (long) self->fPreset; + } else { + pSim->lEnd = 0; + } + + if (FAILRATE < .0) { + return OKOK; + } + + if (SimRandom() < FAILRATE) { + return HWFault; + } + + return OKOK; +} + +/*---------------------------------------------------------------------------*/ +static int SIMPause(struct __COUNTER *self) +{ + SimSt *pSim = NULL; + time_t tD; + int iRun; + + assert(self); + pSim = (SimSt *) self->pData; + assert(pSim); + + pSim->iPause = 1; + + /* + no fail, no wait case + */ + if (FAILRATE < .0) { + return OKOK; + } + + if (SimRandom() < FAILRATE) { + return HWFault; + } + + return OKOK; +} + +/*---------------------------------------------------------------------------*/ +static int SIMContinue(struct __COUNTER *self) +{ + SimSt *pSim = NULL; + time_t tD; + int iRun; + + assert(self); + pSim = (SimSt *) self->pData; + assert(pSim); + + pSim->iPause = 0; + + if (FAILRATE < .0) { + return OKOK; + } + + if (SimRandom() < FAILRATE) { + return HWFault; + } + + return OKOK; +} + +/*--------------------------------------------------------------------------*/ +static int SIMHalt(struct __COUNTER *self) +{ + SimSt *pSim = NULL; + int iRun; + + assert(self); + pSim = (SimSt *) self->pData; + assert(pSim); + + if (FAILRATE < .0) { + return OKOK; + } + + if (SimRandom() < FAILRATE) { + return HWFault; + } + if (self->eMode == eTimer) { + pSim->lEnd = 0; + } else { + pSim->lEnd = (long) self->fPreset + 10; + } + return OKOK; +} + +/*-------------------------------------------------------------------------*/ +static int SIMReadValues(struct __COUNTER *self) +{ + SimSt *pSim = NULL; + int i; + + assert(self); + pSim = (SimSt *) self->pData; + assert(pSim); + + /* + no fail, no wait case + */ + if (FAILRATE < .0) { + for (i = 0; i < MAXCOUNT; i++) { + self->lCounts[i] = (long) (SimRandom() * 100); + } + self->lCounts[1] = self->fPreset; + return OKOK; + } + + if (SimRandom() < FAILRATE) { + return HWFault; + } + + for (i = 0; i < MAXCOUNT; i++) { + self->lCounts[i] = (long) (SimRandom() * 100); + } + self->lCounts[1] = self->fPreset; + return OKOK; +} + +/*-------------------------------------------------------------------------*/ +static int SIMGetError(struct __COUNTER *self, int *iCode, char *error, + int iErrLen) +{ + strncpy(error, "Randomly simulated counter error", iErrLen); + *iCode = 1; + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int SIMTryAndFixIt(struct __COUNTER *self, int iCode) +{ + if (SimRandom() < FAILRATE) { + return COTERM; + } + return COREDO; +} + +/*--------------------------------------------------------------------------*/ +static int SIMSet(struct __COUNTER *self, char *name, int iCter, + float FVal) +{ + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int SIMGet(struct __COUNTER *self, char *name, int iCter, + float *fVal) +{ + *fVal = 25.999; + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int SIMSend(struct __COUNTER *self, char *pText, + char *pReply, int iReplyLen) +{ + strncpy(pReply, "Simulated response", iReplyLen); + return 1; +} + +/*---------------------------------------------------------------------------*/ +pCounterDriver NewSIMCounter(char *name, float fFail) +{ + pCounterDriver pRes = NULL; + SimSt *pData = NULL; + int iRet; + int iC1, iC2, iC3; + char *pErr; + char pBueffel[132]; + + pRes = CreateCounterDriver(name, "SIM"); + if (!pRes) { + return NULL; + } + + pData = (SimSt *) malloc(sizeof(SimSt)); + if (!pData) { + DeleteCounterDriver(pRes); + return NULL; + } + pData->lEnd = 0; + pData->iPause = 0; + pRes->pData = (void *) pData; + pRes->iNoOfMonitors = 8; + pRes->fTime = 0; + + /* assign functions */ + pRes->GetStatus = SIMGetStatus; + pRes->Start = SIMStart; + pRes->Halt = SIMHalt; + pRes->ReadValues = SIMReadValues; + pRes->GetError = SIMGetError; + pRes->TryAndFixIt = SIMTryAndFixIt; + pRes->Pause = SIMPause; + pRes->Continue = SIMContinue; + pRes->Set = SIMSet; + pRes->Get = SIMGet; + pRes->Send = SIMSend; + pRes->KillPrivate = NULL; + + FAILRATE = fFail; + return pRes; } - diff --git a/simdriv.c b/simdriv.c index d8112738..5f3883c3 100644 --- a/simdriv.c +++ b/simdriv.c @@ -51,341 +51,297 @@ #include "servlog.h" #include "splitter.h" /*-------------------------------------------------------------------------*/ - static float SimRandom(void) - { - float fVal; - - fVal = ( (float) rand() / (float)RAND_MAX) * 100.0; - return fVal; - } +static float SimRandom(void) +{ + float fVal; + + fVal = ((float) rand() / (float) RAND_MAX) * 100.0; + return fVal; +} + /*---------------------------------------------------------------------------*/ - static int RunComplete(SIMDriv *self) - { - int sign; - time_t now; - - if (self->iTime == 0) { - return 1; - } - now=time(NULL); - /* move */ - if (self->fTarget > self->fPos) { - sign=1; - } else { - sign=-1; - } - self->fPos += sign * self->fSpeed * (now - self->iTime); - self->iTime = now; - if (sign*(self->fPos - self->fTarget) > 0) { - self->fPos = self->fTarget; - return 1; - } - return 0; +static int RunComplete(SIMDriv * self) +{ + int sign; + time_t now; + + if (self->iTime == 0) { + return 1; } + now = time(NULL); + /* move */ + if (self->fTarget > self->fPos) { + sign = 1; + } else { + sign = -1; + } + self->fPos += sign * self->fSpeed * (now - self->iTime); + self->iTime = now; + if (sign * (self->fPos - self->fTarget) > 0) { + self->fPos = self->fTarget; + return 1; + } + return 0; +} + /*----------------------------------------------------------------------------*/ - static int GetSimPos(void *self, float *fPos) - { - SIMDriv *pDriv; - - assert(self); - pDriv = (SIMDriv *)self; +static int GetSimPos(void *self, float *fPos) +{ + SIMDriv *pDriv; - /* - no error checking case - */ - if(pDriv->fFailure < .0) - { - *fPos = pDriv->fPos; - return OKOK; - } + assert(self); + pDriv = (SIMDriv *) self; - if(SimRandom() < pDriv->fFailure) - { - *fPos = SimRandom(); - return HWFault; - } - + /* + no error checking case + */ + if (pDriv->fFailure < .0) { *fPos = pDriv->fPos; return OKOK; - } + } + + if (SimRandom() < pDriv->fFailure) { + *fPos = SimRandom(); + return HWFault; + } + + *fPos = pDriv->fPos; + return OKOK; +} + /*----------------------------------------------------------------------------*/ - static int SimRun(void *self, float fVal) - { - SIMDriv *pDriv; - - assert(self); - pDriv = (SIMDriv *)self; +static int SimRun(void *self, float fVal) +{ + SIMDriv *pDriv; - /* - no failure, no wait situation - */ - if(pDriv->fFailure < .0) - { - pDriv->fPos = fVal; - return OKOK; - } + assert(self); + pDriv = (SIMDriv *) self; - - /* set start time */ - pDriv->fTarget = fVal; - pDriv->iTime = time(NULL); - - /* in a fifth the failures, simply die, else simply do not find pos */ - if(SimRandom() < (pDriv->fFailure/5)) - { - return HWFault; - } - else if(SimRandom() < pDriv->fFailure) - { - pDriv->fPos = fVal - 1.; - return OKOK; - } - else - { - /* pDriv->fPos = fVal; */ - return OKOK; - } - } -/*--------------------------------------------------------------------------*/ - static void SimError(void *self, int *iCode, char *error, int iErrLen) - { - assert(self); - - if(RunComplete((SIMDriv *)self)) - { - *iCode = 56; - strncpy(error,"ERROR: HW: HahahahahahahHahahHahaha-Mmmpfff",iErrLen); - } - else - { - *iCode = 12; - strncpy(error,"Motor still creeping along",iErrLen-1); - } - } -/*---------------------------------------------------------------------------*/ - static int SimFix(void *self, int iError, float fNew) - { - SIMDriv *pDriv; - float fRand; - - /* return the three values MOTREDO, MOTFAIL, MOTOK with a third - randomness - */ - assert(self); - fRand = SimRandom(); - pDriv = (SIMDriv *)self; - - if(iError == 12) - { - return MOTREDO; - } - - SICSLogWrite("Simulated Motor dying randomly",eHWError); - if(fRand < 0.3333) - { - return MOTOK; - } - else if(fRand < 0.66666) - { - return MOTREDO; - } - else - { - pDriv->iTime = 0; - return MOTFAIL; - } - } -/*--------------------------------------------------------------------------*/ - static int SimHalt(void *self) - { - SIMDriv *pDriv; - assert(self); - - pDriv = (SIMDriv *)self; - pDriv->iTime = 0; + /* + no failure, no wait situation + */ + if (pDriv->fFailure < .0) { + pDriv->fPos = fVal; return OKOK; } -/*--------------------------------------------------------------------------*/ - static int SimStat(void *self) - { - SIMDriv *pDriv; - - assert(self); - pDriv = (SIMDriv *)self; - /* - no wait, no fail situation - */ - if(pDriv->fFailure < .0) - { - return HWIdle; - } - if(RunComplete(pDriv)) - { - return HWIdle; - } - else - { - if(SimRandom() < pDriv->fFailure/2) - { - return HWPosFault; - } - else if(SimRandom() < pDriv->fFailure) - { - return HWFault; - } - return HWBusy; - } + /* set start time */ + pDriv->fTarget = fVal; + pDriv->iTime = time(NULL); + + /* in a fifth the failures, simply die, else simply do not find pos */ + if (SimRandom() < (pDriv->fFailure / 5)) { + return HWFault; + } else if (SimRandom() < pDriv->fFailure) { + pDriv->fPos = fVal - 1.; + return OKOK; + } else { + /* pDriv->fPos = fVal; */ + return OKOK; } +} + +/*--------------------------------------------------------------------------*/ +static void SimError(void *self, int *iCode, char *error, int iErrLen) +{ + assert(self); + + if (RunComplete((SIMDriv *) self)) { + *iCode = 56; + strncpy(error, "ERROR: HW: HahahahahahahHahahHahaha-Mmmpfff", iErrLen); + } else { + *iCode = 12; + strncpy(error, "Motor still creeping along", iErrLen - 1); + } +} + +/*---------------------------------------------------------------------------*/ +static int SimFix(void *self, int iError, float fNew) +{ + SIMDriv *pDriv; + float fRand; + + /* return the three values MOTREDO, MOTFAIL, MOTOK with a third + randomness + */ + assert(self); + fRand = SimRandom(); + pDriv = (SIMDriv *) self; + + if (iError == 12) { + return MOTREDO; + } + + SICSLogWrite("Simulated Motor dying randomly", eHWError); + if (fRand < 0.3333) { + return MOTOK; + } else if (fRand < 0.66666) { + return MOTREDO; + } else { + pDriv->iTime = 0; + return MOTFAIL; + } +} + +/*--------------------------------------------------------------------------*/ +static int SimHalt(void *self) +{ + SIMDriv *pDriv; + assert(self); + + pDriv = (SIMDriv *) self; + pDriv->iTime = 0; + return OKOK; +} + +/*--------------------------------------------------------------------------*/ +static int SimStat(void *self) +{ + SIMDriv *pDriv; + + assert(self); + pDriv = (SIMDriv *) self; + + /* + no wait, no fail situation + */ + if (pDriv->fFailure < .0) { + return HWIdle; + } + + if (RunComplete(pDriv)) { + return HWIdle; + } else { + if (SimRandom() < pDriv->fFailure / 2) { + return HWPosFault; + } else if (SimRandom() < pDriv->fFailure) { + return HWFault; + } + return HWBusy; + } +} + /*-----------------------------------------------------------------------*/ -static int SimSetPar(void *self, SConnection *pCon, char *name, float newValue) +static int SimSetPar(void *self, SConnection * pCon, char *name, + float newValue) { SIMDriv *pDriv = (SIMDriv *) self; assert(self); assert(pCon); - if(strcmp(name,"hardupperlim") == 0) - { + if (strcmp(name, "hardupperlim") == 0) { pDriv->fUpper = newValue; return 1; } - if(strcmp(name,"hardlowerlim") == 0) - { + if (strcmp(name, "hardlowerlim") == 0) { pDriv->fLower = newValue; return 1; } return 0; } -/*---------------------------------------------------------------------------*/ - void KillSIM(void *pData) - { - return; - } -/*--------------------------------------------------------------------------*/ - MotorDriver *CreateSIM(SConnection *pCon, int argc, char *argv[]) - { - TokenList *pList = NULL; - TokenList *pCurrent; - SIMDriv *pDriv = NULL; - - assert(pCon); - - /* check number of arguments */ - if(argc < 3) - { - SCWrite(pCon,"Insufficient numbers of arguments for SimMotor",eError); - return NULL; - } - - /* split arguments */ - pList = SplitArguments(argc, argv); - if(!pList) - { - SCWrite(pCon,"Error parsing arguments in SimMotor",eError); - return NULL; - } - - /* allocate memory */ - pDriv = (SIMDriv *)malloc(sizeof(SIMDriv)); - if(!pDriv) - { - SCWrite(pCon,"Error allocating memory in SimMotor",eError); - DeleteTokenList(pList); - return NULL; - } - memset(pDriv,0,sizeof(SIMDriv)); - - /* check and enter args, first lowerLimit */ - pCurrent = pList; - if(pCurrent->Type == eInt) - { - pDriv->fLower = (float)pCurrent->iVal; - } - else if(pCurrent->Type == eFloat) - { - pDriv->fLower = pCurrent->fVal; - } - else - { - SCWrite(pCon,"Non float argument to SimMotor",eError); - free(pDriv); - DeleteTokenList(pList); - return NULL; - } - /* upper limit */ - pCurrent = pCurrent->pNext; - if(pCurrent->Type == eInt) - { - pDriv->fUpper = (float)pCurrent->iVal; - } - else if(pCurrent->Type == eFloat) - { - pDriv->fUpper = pCurrent->fVal; - } - else - { - SCWrite(pCon,"Non float argument to SimMotor",eError); - free(pDriv); - DeleteTokenList(pList); - return NULL; - } - - /* failure rate */ - pCurrent = pCurrent->pNext; - if(pCurrent->Type == eInt) - { - pDriv->fFailure = (float)pCurrent->iVal; - } - else if(pCurrent->Type == eFloat) - { - pDriv->fFailure = pCurrent->fVal; - } - else - { - SCWrite(pCon,"Non float argument to SimMotor",eError); - free(pDriv); - DeleteTokenList(pList); - return NULL; - } - - - /* calculate current position, initialise func pters */ - pDriv->fPos = (pDriv->fUpper + pDriv->fLower)/2.; - pDriv->fTarget = pDriv->fPos; - pDriv->name = strdup("Simulant"); - pDriv->GetPosition = GetSimPos; - pDriv->RunTo = SimRun; - pDriv->GetStatus = SimStat; - pDriv->GetError = SimError; - pDriv->TryAndFixIt = SimFix; - /* pDriv->SetDriverPar = SimSetPar; */ - pDriv->Halt = SimHalt; - pDriv->fSpeed = .01; - pDriv->iTime = 0; - pDriv->KillPrivate = KillSIM; - - /* check for optional speed paramter */ - pCurrent = pCurrent->pNext; - if(pCurrent) - { - if(pCurrent->Type == eFloat) - { - pDriv->fSpeed = pCurrent->fVal; - } - } - DeleteTokenList(pList); - return (MotorDriver *)pDriv; +/*---------------------------------------------------------------------------*/ +void KillSIM(void *pData) +{ + return; +} + +/*--------------------------------------------------------------------------*/ +MotorDriver *CreateSIM(SConnection * pCon, int argc, char *argv[]) +{ + TokenList *pList = NULL; + TokenList *pCurrent; + SIMDriv *pDriv = NULL; + + assert(pCon); + + /* check number of arguments */ + if (argc < 3) { + SCWrite(pCon, "Insufficient numbers of arguments for SimMotor", + eError); + return NULL; + } + + /* split arguments */ + pList = SplitArguments(argc, argv); + if (!pList) { + SCWrite(pCon, "Error parsing arguments in SimMotor", eError); + return NULL; + } + + /* allocate memory */ + pDriv = (SIMDriv *) malloc(sizeof(SIMDriv)); + if (!pDriv) { + SCWrite(pCon, "Error allocating memory in SimMotor", eError); + DeleteTokenList(pList); + return NULL; + } + memset(pDriv, 0, sizeof(SIMDriv)); + + /* check and enter args, first lowerLimit */ + pCurrent = pList; + if (pCurrent->Type == eInt) { + pDriv->fLower = (float) pCurrent->iVal; + } else if (pCurrent->Type == eFloat) { + pDriv->fLower = pCurrent->fVal; + } else { + SCWrite(pCon, "Non float argument to SimMotor", eError); + free(pDriv); + DeleteTokenList(pList); + return NULL; + } + + /* upper limit */ + pCurrent = pCurrent->pNext; + if (pCurrent->Type == eInt) { + pDriv->fUpper = (float) pCurrent->iVal; + } else if (pCurrent->Type == eFloat) { + pDriv->fUpper = pCurrent->fVal; + } else { + SCWrite(pCon, "Non float argument to SimMotor", eError); + free(pDriv); + DeleteTokenList(pList); + return NULL; + } + + /* failure rate */ + pCurrent = pCurrent->pNext; + if (pCurrent->Type == eInt) { + pDriv->fFailure = (float) pCurrent->iVal; + } else if (pCurrent->Type == eFloat) { + pDriv->fFailure = pCurrent->fVal; + } else { + SCWrite(pCon, "Non float argument to SimMotor", eError); + free(pDriv); + DeleteTokenList(pList); + return NULL; } + /* calculate current position, initialise func pters */ + pDriv->fPos = (pDriv->fUpper + pDriv->fLower) / 2.; + pDriv->fTarget = pDriv->fPos; + pDriv->name = strdup("Simulant"); + pDriv->GetPosition = GetSimPos; + pDriv->RunTo = SimRun; + pDriv->GetStatus = SimStat; + pDriv->GetError = SimError; + pDriv->TryAndFixIt = SimFix; + /* pDriv->SetDriverPar = SimSetPar; */ + pDriv->Halt = SimHalt; + pDriv->fSpeed = .01; + pDriv->iTime = 0; + pDriv->KillPrivate = KillSIM; - - - - - - - + /* check for optional speed paramter */ + pCurrent = pCurrent->pNext; + if (pCurrent) { + if (pCurrent->Type == eFloat) { + pDriv->fSpeed = pCurrent->fVal; + } + } + DeleteTokenList(pList); + return (MotorDriver *) pDriv; +} diff --git a/simev.c b/simev.c index c6585099..af218123 100644 --- a/simev.c +++ b/simev.c @@ -50,220 +50,213 @@ #include "evdriver.h" #include "simev.h" /*-----------------------------------------------------------------------*/ - typedef struct { - float fFailure; - float fTarget; - float fSpeed; - time_t tFinish; - } SimST, *pSimST; +typedef struct { + float fFailure; + float fTarget; + float fSpeed; + time_t tFinish; +} SimST, *pSimST; /*-----------------------------------------------------------------------*/ - static float SimRandom(void) - { - float fVal; - - fVal = ( (float) rand() / (float)RAND_MAX) * 100.0; - return fVal; - } -/*---------------------------------------------------------------------------*/ - static int RunComplete(pEVDriver self) - { - pSimST pMe = NULL; - time_t tD; - - assert(self); - pMe = (pSimST)self->pPrivate; - assert(pMe); - - if(pMe->fFailure < .0){ - return 1; - } +static float SimRandom(void) +{ + float fVal; - if((int)time(&tD) > pMe->tFinish) - { - return 1; - } - return 0; + fVal = ((float) rand() / (float) RAND_MAX) * 100.0; + return fVal; +} + +/*---------------------------------------------------------------------------*/ +static int RunComplete(pEVDriver self) +{ + pSimST pMe = NULL; + time_t tD; + + assert(self); + pMe = (pSimST) self->pPrivate; + assert(pMe); + + if (pMe->fFailure < .0) { + return 1; } + + if ((int) time(&tD) > pMe->tFinish) { + return 1; + } + return 0; +} + /*----------------------------------------------------------------------------*/ - static int GetSimPos(pEVDriver self, float *fPos) - { - pSimST pMe = NULL; - - assert(self); - pMe = (pSimST)self->pPrivate; - assert(pMe); +static int GetSimPos(pEVDriver self, float *fPos) +{ + pSimST pMe = NULL; + + assert(self); + pMe = (pSimST) self->pPrivate; + assert(pMe); + + + if (SimRandom() < pMe->fFailure) { + *fPos = SimRandom(); + return 0; + } + + if (RunComplete(self)) { + if (pMe->fFailure < .0) { + *fPos = pMe->fTarget; + } else { + *fPos = pMe->fTarget + SimRandom() / 50 - 1.0; + } + } else { /* simulate a mispositioned motor */ + + *fPos = pMe->fTarget - 10.; + return 1; + } + return 1; +} - - if(SimRandom() < pMe->fFailure) - { - *fPos = SimRandom(); - return 0; - } - - if(RunComplete(self)) - { - if(pMe->fFailure < .0){ - *fPos = pMe->fTarget; - } else { - *fPos = pMe->fTarget + SimRandom()/50-1.0; - } - } - else /* simulate a mispositioned motor */ - { - *fPos = pMe->fTarget - 10.; - return 1; - } - return 1; - } /*----------------------------------------------------------------------------*/ - static int SimRun(pEVDriver self, float fVal) - { - pSimST pMe = NULL; - float fDiff; - time_t tD; - - assert(self); - pMe = (pSimST)self->pPrivate; - assert(pMe); +static int SimRun(pEVDriver self, float fVal) +{ + pSimST pMe = NULL; + float fDiff; + time_t tD; - /* calculate time for completion */ - fDiff = fVal - pMe->fTarget; - if(fDiff < .0) fDiff = -fDiff; - pMe->tFinish = (int)time(&tD) + (int)(fDiff/pMe->fSpeed); + assert(self); + pMe = (pSimST) self->pPrivate; + assert(pMe); - pMe->fTarget = fVal; + /* calculate time for completion */ + fDiff = fVal - pMe->fTarget; + if (fDiff < .0) + fDiff = -fDiff; + pMe->tFinish = (int) time(&tD) + (int) (fDiff / pMe->fSpeed); - /* in a fifth the failures, simply die, else simply do not find pos */ - if(SimRandom() < (pMe->fFailure/5)) - { - return 0; - } - - return 1; - } -/*--------------------------------------------------------------------------*/ - static int SimError(pEVDriver self, int *iCode, char *error, int iErrLen) - { - assert(self); - - if(RunComplete(self)) - { - *iCode = 56; - strncpy(error,"ERROR: (-: Simulated environment device error :-) ",iErrLen); - } - else - { - *iCode = 12; - strncpy(error,"Environment still creeping along",iErrLen-1); - } - return 1; + pMe->fTarget = fVal; + + /* in a fifth the failures, simply die, else simply do not find pos */ + if (SimRandom() < (pMe->fFailure / 5)) { + return 0; } + + return 1; +} + /*--------------------------------------------------------------------------*/ - static int SimSend(pEVDriver self, char *pCommand, char *pReply, int iLen) - { - pSimST pMe = NULL; - float fDiff; - time_t tD; - - assert(self); - pMe = (pSimST)self->pPrivate; - assert(pMe); - - if(SimRandom() < pMe->fFailure) - { - return 0; - } - - strncpy(pReply,"Device gracefully accepted command",iLen); - return 1; - } +static int SimError(pEVDriver self, int *iCode, char *error, int iErrLen) +{ + assert(self); + + if (RunComplete(self)) { + *iCode = 56; + strncpy(error, "ERROR: (-: Simulated environment device error :-) ", + iErrLen); + } else { + *iCode = 12; + strncpy(error, "Environment still creeping along", iErrLen - 1); + } + return 1; +} + /*--------------------------------------------------------------------------*/ - static int SimSim(pEVDriver self) - { - return 1; - } +static int SimSend(pEVDriver self, char *pCommand, char *pReply, int iLen) +{ + pSimST pMe = NULL; + float fDiff; + time_t tD; + + assert(self); + pMe = (pSimST) self->pPrivate; + assert(pMe); + + if (SimRandom() < pMe->fFailure) { + return 0; + } + + strncpy(pReply, "Device gracefully accepted command", iLen); + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int SimSim(pEVDriver self) +{ + return 1; +} + /*---------------------------------------------------------------------------*/ - static int SimFix(pEVDriver self, int iError) - { - float fRand; - - /* return the three values MOTREDO, MOTFAIL, MOTOK with a third - randomness - */ - assert(self); - fRand = SimRandom(); - - if(iError == 12) - { - return DEVREDO; - } - - SICSLogWrite("Simulated Environment device dying randomly",eHWError); - if(fRand < 0.3333) - { - return DEVOK; - } - else if(fRand < 0.66666) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } +static int SimFix(pEVDriver self, int iError) +{ + float fRand; + + /* return the three values MOTREDO, MOTFAIL, MOTOK with a third + randomness + */ + assert(self); + fRand = SimRandom(); + + if (iError == 12) { + return DEVREDO; } + + SICSLogWrite("Simulated Environment device dying randomly", eHWError); + if (fRand < 0.3333) { + return DEVOK; + } else if (fRand < 0.66666) { + return DEVREDO; + } else { + return DEVFAULT; + } +} + /*--------------------------------------------------------------------------*/ - static int SimHalt(pEVDriver *self) - { - assert(self); - - return 1; - } +static int SimHalt(pEVDriver * self) +{ + assert(self); + + return 1; +} + /*------------------------------------------------------------------------*/ - pEVDriver CreateSIMEVDriver(int argc, char *argv[]) - { - pEVDriver pNew = NULL; - pSimST pSim = NULL; - - pNew = CreateEVDriver(argc,argv); - pSim = (pSimST)malloc(sizeof(SimST)); - if(!pNew || !pSim) - { - return NULL; - } - pNew->pPrivate = pSim; - /* This causes problems with fortify. Apparently the free does not - get replaced properly with the proper debug malloc function. +pEVDriver CreateSIMEVDriver(int argc, char *argv[]) +{ + pEVDriver pNew = NULL; + pSimST pSim = NULL; + + pNew = CreateEVDriver(argc, argv); + pSim = (pSimST) malloc(sizeof(SimST)); + if (!pNew || !pSim) { + return NULL; + } + pNew->pPrivate = pSim; + /* This causes problems with fortify. Apparently the free does not + get replaced properly with the proper debug malloc function. pNew->KillPrivate = free; - */ - - pNew->KillPrivate = NULL; - - /* initalise SimST */ - pSim->fFailure = .1; - pSim->fSpeed = 1.; - pSim->fTarget = 0.0; - pSim->tFinish = 0; - - /* are there parameters which give values for SIM ? */ - if(argc > 0) - { - pSim->fFailure = atof(argv[0]); - } - if(argc > 1) - { - pSim->fSpeed = atof(argv[1]); - } - - /* initialise function pointers */ - pNew->SetValue = SimRun; - pNew->GetValue = GetSimPos; - pNew->Send = SimSend; - pNew->GetError = SimError; - pNew->TryFixIt = SimFix; - pNew->Init = SimSim; - pNew->Close = SimSim; - - return pNew; - } + */ + + pNew->KillPrivate = NULL; + + /* initalise SimST */ + pSim->fFailure = .1; + pSim->fSpeed = 1.; + pSim->fTarget = 0.0; + pSim->tFinish = 0; + + /* are there parameters which give values for SIM ? */ + if (argc > 0) { + pSim->fFailure = atof(argv[0]); + } + if (argc > 1) { + pSim->fSpeed = atof(argv[1]); + } + + /* initialise function pointers */ + pNew->SetValue = SimRun; + pNew->GetValue = GetSimPos; + pNew->Send = SimSend; + pNew->GetError = SimError; + pNew->TryFixIt = SimFix; + pNew->Init = SimSim; + pNew->Close = SimSim; + + return pNew; +} diff --git a/simev.h b/simev.h index f1559b3f..261aeeef 100644 --- a/simev.h +++ b/simev.h @@ -7,6 +7,6 @@ --------------------------------------------------------------------------*/ #ifndef SICSSIMEV #define SICSSIMEV - pEVDriver CreateSIMEVDriver(int argc, char *argv[]); - +pEVDriver CreateSIMEVDriver(int argc, char *argv[]); + #endif diff --git a/simidx.c b/simidx.c index 87c7d7ac..430b3f6f 100644 --- a/simidx.c +++ b/simidx.c @@ -31,10 +31,10 @@ #define MAXREF 20 #define MAXIDX 20 #define MAXSOLUTION 20 -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*======================== types =============================*/ typedef struct { - int h,k,l; + int h, k, l; double diff; } HKL, *pHKL; @@ -62,179 +62,208 @@ static int outLevel = 10; static IndexSolution solutions[MAXSOLUTION]; static int nSolutions; /*------------------------------------------------------------*/ -void SimIdxInit(){ +void SimIdxInit() +{ int i; - for(i = 0; i < MAXREF; i++){ - reflections[i].UVW = mat_creat(3,1,ZERO_MATRIX); + for (i = 0; i < MAXREF; i++) { + reflections[i].UVW = mat_creat(3, 1, ZERO_MATRIX); } } + /*=============== configuration functions =====================*/ -void SimIdxSetCell(double cell[6]){ +void SimIdxSetCell(double cell[6]) +{ direct.a = cell[0]; direct.b = cell[1]; direct.c = cell[2]; direct.alpha = cell[3]; - direct.beta = cell[4]; + direct.beta = cell[4]; direct.gamma = cell[5]; } + /*-------------------------------------------------------------*/ -void SimIdxSetLambda(double lmda){ +void SimIdxSetLambda(double lmda) +{ lambda = lmda; } + /*-------------------------------------------------------------*/ -void SimIdxSetSttLim(double lmda){ +void SimIdxSetSttLim(double lmda) +{ sttlim = lmda; } + /*-------------------------------------------------------------*/ -void SimIdxSetAngLim(double lmda){ +void SimIdxSetAngLim(double lmda) +{ anglim = lmda; } + /*-------------------------------------------------------------*/ -void SimIdxSetSpacegroup(T_SgInfo *sg){ +void SimIdxSetSpacegroup(T_SgInfo * sg) +{ spgrp = sg; } + /*-------------------------------------------------------------*/ -void SimIdxClearReflection(){ - nReflections = 0; +void SimIdxClearReflection() +{ + nReflections = 0; } + /*-------------------------------------------------------------*/ -void SimIdxAddReflection(double uvw[3]){ +void SimIdxAddReflection(double uvw[3]) +{ int i; - if(nReflections < MAXREF){ - memcpy(&reflections[nReflections].uvw, uvw, 3*sizeof(double)); + if (nReflections < MAXREF) { + memcpy(&reflections[nReflections].uvw, uvw, 3 * sizeof(double)); reflections[nReflections].nHKL = 0; reflections[nReflections].currentIDX = 0; reflections[nReflections].originalID = nReflections; - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { reflections[nReflections].UVW[i][0] = uvw[i]; } nReflections++; } } + /*-------------------------------------------------------------*/ -void SimIdxOutput(void *data, OutFunc out, int level){ +void SimIdxOutput(void *data, OutFunc out, int level) +{ userData = data; outFunc = out; outLevel = level; } + /*-------------------------------------------------------------*/ -static void SimIdxPrint(int level, char *fmt, ...){ +static void SimIdxPrint(int level, char *fmt, ...) +{ va_list ap; char buf[1024]; int l; - if(level > outLevel){ + if (level > outLevel) { return; } va_start(ap, fmt); l = vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); - if(outFunc != NULL){ - outFunc(userData,buf); + if (outFunc != NULL) { + outFunc(userData, buf); } else { - printf("%s\n",buf); + printf("%s\n", buf); } } + /*=============== The alkoholism ===============================*/ -static int thetaCompare(const void *d1, const void *d2){ +static int thetaCompare(const void *d1, const void *d2) +{ pIndexVector iv1, iv2; - iv1 = (pIndexVector)d1; - iv2 = (pIndexVector)d2; + iv1 = (pIndexVector) d1; + iv2 = (pIndexVector) d2; - if(iv1->twotheta == iv2->twotheta) { + if (iv1->twotheta == iv2->twotheta) { return 0; } - if(iv1->twotheta < iv2->twotheta){ + if (iv1->twotheta < iv2->twotheta) { return -1; } else { return 1; } } + /*--------------------------------------------------------------*/ -static void calcRefTheta(){ +static void calcRefTheta() +{ int i; double theta, d; - for(i = 0; i < nReflections; i++){ + for (i = 0; i < nReflections; i++) { calcTheta(lambda, reflections[i].UVW, &d, &theta); - reflections[i].twotheta = 2.* theta; + reflections[i].twotheta = 2. * theta; } - qsort(reflections,nReflections, sizeof(IndexVector), - thetaCompare); + qsort(reflections, nReflections, sizeof(IndexVector), thetaCompare); - SimIdxPrint(10,"%d Reflections", nReflections); + SimIdxPrint(10, "%d Reflections", nReflections); } + /*---------------------------------------------------------------*/ -double calcIdxTwoTheta(int h, int k, int l, MATRIX B){ +double calcIdxTwoTheta(int h, int k, int l, MATRIX B) +{ MATRIX H, Z1; double om, d; - H = mat_creat(3,1,ZERO_MATRIX); - if(H == NULL){ - SimIdxPrint(1,"ERROR: out of memory calculating H matrix"); + H = mat_creat(3, 1, ZERO_MATRIX); + if (H == NULL) { + SimIdxPrint(1, "ERROR: out of memory calculating H matrix"); return 0.; } - H[0][0] = (double)h; - H[1][0] = (double)k; - H[2][0] = (double)l; - Z1 = mat_mul(B,H); - calcTheta(lambda,Z1,&d,&om); + H[0][0] = (double) h; + H[1][0] = (double) k; + H[2][0] = (double) l; + Z1 = mat_mul(B, H); + calcTheta(lambda, Z1, &d, &om); om *= 2.; mat_free(Z1); mat_free(H); - + return om; } + /*---------------------------------------------------------------*/ -static void AddCandidate(int n, int h, int k, int l, - double diff){ +static void AddCandidate(int n, int h, int k, int l, double diff) +{ int cur = reflections[n].nHKL; - if(cur < MAXCANDIDATES){ + if (cur < MAXCANDIDATES) { reflections[n].indices[cur].h = h; reflections[n].indices[cur].k = k; reflections[n].indices[cur].l = l; - reflections[n].indices[cur].diff = diff ; + reflections[n].indices[cur].diff = diff; reflections[n].nHKL++; } } + /*---------------------------------------------------------------*/ -static int calcIndexes(){ +static int calcIndexes() +{ int h, k, l, i, status; int minh, mink, minl; MATRIX B; double twotheta; - B = mat_creat(3,3,UNIT_MATRIX); - if(B == NULL){ - SimIdxPrint(1,"ERROR: out of memory calculating B matrix"); + B = mat_creat(3, 3, UNIT_MATRIX); + if (B == NULL) { + SimIdxPrint(1, "ERROR: out of memory calculating B matrix"); return 0; } - status = calculateBMatrix(direct,B); - if(status < 0) { - SimIdxPrint(1,"ERROR: invalid cell constants, failed to calculate B matrix"); + status = calculateBMatrix(direct, B); + if (status < 0) { + SimIdxPrint(1, + "ERROR: invalid cell constants, failed to calculate B matrix"); return 0; } minh = -MAXIDX; mink = -MAXIDX; minl = -MAXIDX; - SetListMin_hkl(spgrp,MAXIDX, MAXIDX,&minh, &mink, &minl); + SetListMin_hkl(spgrp, MAXIDX, MAXIDX, &minh, &mink, &minl); - for(h = MAXIDX; h > -MAXIDX; h--){ - for(k = MAXIDX; k > -MAXIDX; k--){ - for(l = MAXIDX; l > -MAXIDX; l--){ - if(IsSysAbsent_hkl(spgrp,h,k,l,NULL) != 0) { - continue; - } - twotheta = calcIdxTwoTheta(h,k,l,B); - for(i = 0; i < nReflections; i++){ - if(reflections[i].twotheta > twotheta - sttlim && - reflections[i].twotheta < twotheta + sttlim){ - AddCandidate(i, h,k,l, ABS(twotheta - reflections[i].twotheta)); - } + for (h = MAXIDX; h > -MAXIDX; h--) { + for (k = MAXIDX; k > -MAXIDX; k--) { + for (l = MAXIDX; l > -MAXIDX; l--) { + if (IsSysAbsent_hkl(spgrp, h, k, l, NULL) != 0) { + continue; + } + twotheta = calcIdxTwoTheta(h, k, l, B); + for (i = 0; i < nReflections; i++) { + if (reflections[i].twotheta > twotheta - sttlim && + reflections[i].twotheta < twotheta + sttlim) { + AddCandidate(i, h, k, l, + ABS(twotheta - reflections[i].twotheta)); + } } } } @@ -242,53 +271,59 @@ static int calcIndexes(){ mat_free(B); return 1; } + /*-------------------------------------------------------------*/ -static double angleBetweenScatVec(MATRIX v1, MATRIX v2){ +static double angleBetweenScatVec(MATRIX v1, MATRIX v2) +{ double angle; - angle = angleBetween(v1,v2); + angle = angleBetween(v1, v2); return angle; } + /*---------------------------------------------------------------*/ -static void printRefDiagnostic(){ +static void printRefDiagnostic() +{ int i, j; double angle; - - SimIdxPrint(10,"Reflection List and Candidate Indices"); - SimIdxPrint(10," N STT U V W"); - for(i = 0; i < nReflections; i++){ - SimIdxPrint(10,"%3.3d %8.4f %8.4f %8.4f %8.4f", i, - reflections[i].twotheta, - reflections[i].uvw[0], - reflections[i].uvw[1], reflections[i].uvw[2]); - for(j = 0; j < reflections[i].nHKL; j++){ - SimIdxPrint(10,"\t%4d %4d %4d", - reflections[i].indices[j].h, - reflections[i].indices[j].k, - reflections[i].indices[j].l); + SimIdxPrint(10, "Reflection List and Candidate Indices"); + SimIdxPrint(10, " N STT U V W"); + + for (i = 0; i < nReflections; i++) { + SimIdxPrint(10, "%3.3d %8.4f %8.4f %8.4f %8.4f", i, + reflections[i].twotheta, + reflections[i].uvw[0], + reflections[i].uvw[1], reflections[i].uvw[2]); + for (j = 0; j < reflections[i].nHKL; j++) { + SimIdxPrint(10, "\t%4d %4d %4d", + reflections[i].indices[j].h, + reflections[i].indices[j].k, + reflections[i].indices[j].l); } } - SimIdxPrint(10,"Angles between reflections"); - SimIdxPrint(10,"IDX1 IDX2 Angle"); - for(i = 0; i < nReflections; i++){ - for(j = i; j < nReflections; j++){ - if(i != j){ - angle = angleBetweenScatVec(reflections[i].UVW, reflections[j].UVW); - SimIdxPrint(10,"%3d %3d %8.2f",i,j,angle); - } - } + SimIdxPrint(10, "Angles between reflections"); + SimIdxPrint(10, "IDX1 IDX2 Angle"); + for (i = 0; i < nReflections; i++) { + for (j = i; j < nReflections; j++) { + if (i != j) { + angle = + angleBetweenScatVec(reflections[i].UVW, reflections[j].UVW); + SimIdxPrint(10, "%3d %3d %8.2f", i, j, angle); + } + } } } + /*-------------------------------------------------------------*/ -static double calculateVolume(double v1[3], double v2[3], - double v3[3]){ +static double calculateVolume(double v1[3], double v2[3], double v3[3]) +{ MATRIX m; int i; double vol; - m = mat_creat(3,3,ZERO_MATRIX); - for(i = 0; i < 3; i++){ + m = mat_creat(3, 3, ZERO_MATRIX); + for (i = 0; i < 3; i++) { m[i][0] = v1[i]; m[i][1] = v2[i]; m[i][2] = v3[i]; @@ -297,31 +332,34 @@ static double calculateVolume(double v1[3], double v2[3], mat_free(m); return vol; } + /*-------------------------------------------------------------*/ -static int areCoplanar(MATRIX v1, MATRIX v2, - MATRIX v3){ +static int areCoplanar(MATRIX v1, MATRIX v2, MATRIX v3) +{ MATRIX norm; double dot; - norm = vectorCrossProduct(v1,v2); - if(norm != NULL){ - dot = vectorDotProduct(norm,v3); + norm = vectorCrossProduct(v1, v2); + if (norm != NULL) { + dot = vectorDotProduct(norm, v3); mat_free(norm); } else { dot = .0; } - if(ABS(dot) > .00001){ + if (ABS(dot) > .00001) { return 0; } else { return 1; } } + /*-------------------------------------------------------------- * - We want the shortest vectors * - We do not want vectors at 180 to each other * - We do not want the three vectors to be coplanar *-------------------------------------------------------------*/ -static int chooseTriplet(int triplet[3]){ +static int chooseTriplet(int triplet[3]) +{ double angle, vol; int idx = 1; @@ -329,36 +367,36 @@ static int chooseTriplet(int triplet[3]){ /* * test for 180 */ - while(idx < nReflections){ - angle = angleBetweenScatVec(reflections[0].UVW, - reflections[idx].UVW); - if(angle < 160 && angle > -160){ + while (idx < nReflections) { + angle = angleBetweenScatVec(reflections[0].UVW, reflections[idx].UVW); + if (angle < 160 && angle > -160) { triplet[1] = idx; break; } idx++; } - if(idx >= nReflections){ - SimIdxPrint(1,"ERROR: no second index found"); + if (idx >= nReflections) { + SimIdxPrint(1, "ERROR: no second index found"); return 0; } - for(idx = 1; idx < nReflections; idx++){ - if(idx != triplet[1]) { - if(!areCoplanar(reflections[triplet[0]].UVW, - reflections[triplet[1]].UVW, - reflections[idx].UVW)){ - triplet[2] = idx; - return 1; + for (idx = 1; idx < nReflections; idx++) { + if (idx != triplet[1]) { + if (!areCoplanar(reflections[triplet[0]].UVW, + reflections[triplet[1]].UVW, + reflections[idx].UVW)) { + triplet[2] = idx; + return 1; } } } - SimIdxPrint(1,"ERROR: no three non coplanar reflections found"); + SimIdxPrint(1, "ERROR: no three non coplanar reflections found"); return 0; } + /*------------------------------------------------------------*/ -static double reflectionsAngle(MATRIX B, int hkl1[3], -int hkl2[3]){ +static double reflectionsAngle(MATRIX B, int hkl1[3], int hkl2[3]) +{ double angle; reflection r1, r2; @@ -370,45 +408,48 @@ int hkl2[3]){ r2.k = hkl2[1]; r2.l = hkl2[2]; - return angleBetweenReflections(B,r1,r2); + return angleBetweenReflections(B, r1, r2); } + /*-------------------------------------------------------------*/ -static int findAngleMatch(MATRIX B, int idxr1, int r1, - int r2start, int r2, double *diff){ +static int findAngleMatch(MATRIX B, int idxr1, int r1, + int r2start, int r2, double *diff) +{ double scatAngle, hklAngle; MATRIX H1, H2; int i, r, hkl1[3], hkl2[3]; - scatAngle = angleBetweenScatVec(reflections[r1].UVW, - reflections[r2].UVW); + scatAngle = angleBetweenScatVec(reflections[r1].UVW, + reflections[r2].UVW); hkl1[0] = reflections[r1].indices[idxr1].h; hkl1[1] = reflections[r1].indices[idxr1].k; hkl1[2] = reflections[r1].indices[idxr1].l; - for(i = r2start; i < reflections[r2].nHKL; i++){ + for (i = r2start; i < reflections[r2].nHKL; i++) { hkl2[0] = reflections[r2].indices[i].h; hkl2[1] = reflections[r2].indices[i].k; hkl2[2] = reflections[r2].indices[i].l; - hklAngle = reflectionsAngle(B,hkl1, hkl2); + hklAngle = reflectionsAngle(B, hkl1, hkl2); *diff = ABS(scatAngle - hklAngle); - if(*diff < anglim){ + if (*diff < anglim) { return i; } } return -1; } + /*------------------------------------------------------------- * If the system is right handed the determinat of the * matrix having the indices as columns must be positive -------------------------------------------------------------*/ -static int testRightHandedness(int r1, int r1idx, - int r2, int r2idx, - int r3, int r3idx){ +static int testRightHandedness(int r1, int r1idx, + int r2, int r2idx, int r3, int r3idx) +{ MATRIX T; double vol; - T = mat_creat(3,3,ZERO_MATRIX); - if(T == NULL){ + T = mat_creat(3, 3, ZERO_MATRIX); + if (T == NULL) { return 0; } T[0][0] = reflections[r1].indices[r1idx].h; @@ -422,30 +463,32 @@ static int testRightHandedness(int r1, int r1idx, T[2][2] = reflections[r3].indices[r3idx].l; vol = mat_det(T); mat_free(T); - if(vol > .0){ + if (vol > .0) { return 1; } else { return 0; } } + /*-------------------------------------------------------------*/ -static void storeSolution(int r1, int r1idx, - int r2, int r2idx, - int r3, int r3idx, double diff){ +static void storeSolution(int r1, int r1idx, + int r2, int r2idx, + int r3, int r3idx, double diff) +{ IndexSolution is; is.h[0] = reflections[r1].indices[r1idx].h; is.k[0] = reflections[r1].indices[r1idx].k; is.l[0] = reflections[r1].indices[r1idx].l; is.originalID[0] = reflections[r1].originalID; is.diff = reflections[r1].indices[r1idx].diff; - + is.h[1] = reflections[r2].indices[r2idx].h; is.k[1] = reflections[r2].indices[r2idx].k; is.l[1] = reflections[r2].indices[r2idx].l; is.originalID[1] = reflections[r2].originalID; is.diff += reflections[r2].indices[r2idx].diff; - if(r3 != 999){ + if (r3 != 999) { is.h[2] = reflections[r3].indices[r3idx].h; is.k[2] = reflections[r3].indices[r3idx].k; is.l[2] = reflections[r3].indices[r3idx].l; @@ -458,21 +501,23 @@ static void storeSolution(int r1, int r1idx, is.originalID[2] = 999; } is.diff += diff; - + solutions[nSolutions] = is; nSolutions++; } + /*----------------------------------------------------------------------*/ -static int compareSolution(const void *d1, const void *d2){ +static int compareSolution(const void *d1, const void *d2) +{ IndexSolution *iv1, *iv2; - iv1 = (IndexSolution *)d1; - iv2 = (IndexSolution *)d2; + iv1 = (IndexSolution *) d1; + iv2 = (IndexSolution *) d2; - if(iv1->diff == iv2->diff) { + if (iv1->diff == iv2->diff) { return 0; } - if(iv1->diff < iv2->diff){ + if (iv1->diff < iv2->diff) { return -1; } else { return 1; @@ -480,7 +525,8 @@ static int compareSolution(const void *d1, const void *d2){ } /*--------------------------------------------------------------*/ -static int findSolutionsForTriplet(int triplet[3], int testRight){ +static int findSolutionsForTriplet(int triplet[3], int testRight) +{ int r1, r2, r3, i, status; int match1, match2, r2start, r3start; double diff1, diff2; @@ -490,54 +536,55 @@ static int findSolutionsForTriplet(int triplet[3], int testRight){ r2 = triplet[1]; r3 = triplet[2]; - B = mat_creat(3,3,UNIT_MATRIX); - if(B == NULL){ - SimIdxPrint(1,"ERROR: out of memory calculating B matrix"); + B = mat_creat(3, 3, UNIT_MATRIX); + if (B == NULL) { + SimIdxPrint(1, "ERROR: out of memory calculating B matrix"); return 0; } - status = calculateBMatrix(direct,B); - if(status < 0) { - SimIdxPrint(1,"ERROR: invalid cell constants, failed to calculate B matrix"); + status = calculateBMatrix(direct, B); + if (status < 0) { + SimIdxPrint(1, + "ERROR: invalid cell constants, failed to calculate B matrix"); return 0; } - for(i = 0; i < reflections[r1].nHKL; i++){ + for (i = 0; i < reflections[r1].nHKL; i++) { r2start = 0; - while((match1 = findAngleMatch(B, i, r1, r2start, r2,&diff1)) >=0){ + while ((match1 = findAngleMatch(B, i, r1, r2start, r2, &diff1)) >= 0) { r3start = 0; - while((match2 = findAngleMatch(B, i, r1, r3start, r3,&diff2)) >= 0){ - if(testRight == 1){ - if(testRightHandedness(r1, i, r2, match1, r3, match2)){ - storeSolution(r1,i,r2,match1, r3,match2, diff1 + diff2); - } - } else { - storeSolution(r1,i,r2,match1, r3,match2, diff1 + diff2); - } - r3start = match2 + 1; + while ((match2 = findAngleMatch(B, i, r1, r3start, r3, &diff2)) >= 0) { + if (testRight == 1) { + if (testRightHandedness(r1, i, r2, match1, r3, match2)) { + storeSolution(r1, i, r2, match1, r3, match2, diff1 + diff2); + } + } else { + storeSolution(r1, i, r2, match1, r3, match2, diff1 + diff2); + } + r3start = match2 + 1; } r2start = match1 + 1; } } - qsort(solutions,nSolutions, sizeof(IndexSolution), - compareSolution); - + qsort(solutions, nSolutions, sizeof(IndexSolution), compareSolution); + return 1; } + /*------------------------------------------------------------- * If the system is right handed the determinat of the * matrix having the indices as columns must be positive. * As I have only two vectors, I simulate the third by * using the nromal on the other two. -------------------------------------------------------------*/ -static int testDuoRightHandedness(int r1, int r1idx, - int r2, int r2idx){ +static int testDuoRightHandedness(int r1, int r1idx, int r2, int r2idx) +{ MATRIX T; double vol; int r3, r3idx; - T = mat_creat(3,3,ZERO_MATRIX); - if(T == NULL){ + T = mat_creat(3, 3, ZERO_MATRIX); + if (T == NULL) { return 0; } T[0][0] = reflections[r1].indices[r1idx].h; @@ -551,92 +598,102 @@ static int testDuoRightHandedness(int r1, int r1idx, T[2][2] = reflections[r3].indices[r3idx].l; vol = mat_det(T); mat_free(T); - if(vol > .0){ + if (vol > .0) { return 1; } else { return 0; } } + /*--------------------------------------------------------------*/ -static int findSolutionsForDuett(int triplet[3]){ +static int findSolutionsForDuett(int triplet[3]) +{ MATRIX B; int r1, r2, r2start, i, status, match1; double diff; - - if(triplet[1] == 999){ - SimIdxPrint(1,"ERROR: No suitable reflection set found"); + + if (triplet[1] == 999) { + SimIdxPrint(1, "ERROR: No suitable reflection set found"); return 0; } r1 = triplet[0]; r2 = triplet[1]; - - B = mat_creat(3,3,UNIT_MATRIX); - if(B == NULL){ - SimIdxPrint(1,"ERROR: out of memory calculating B matrix"); + + B = mat_creat(3, 3, UNIT_MATRIX); + if (B == NULL) { + SimIdxPrint(1, "ERROR: out of memory calculating B matrix"); return 0; } - status = calculateBMatrix(direct,B); - if(status < 0) { - SimIdxPrint(1,"ERROR: invalid cell constants, failed to calculate B matrix"); + status = calculateBMatrix(direct, B); + if (status < 0) { + SimIdxPrint(1, + "ERROR: invalid cell constants, failed to calculate B matrix"); return 0; } - for(i = 0; i < reflections[r1].nHKL; i++){ + for (i = 0; i < reflections[r1].nHKL; i++) { r2start = 0; - while((match1 = findAngleMatch(B, i, r1, r2start, r2,&diff)) >=0){ - storeSolution(r1,i,r2,match1,999,0,diff); + while ((match1 = findAngleMatch(B, i, r1, r2start, r2, &diff)) >= 0) { + storeSolution(r1, i, r2, match1, 999, 0, diff); r2start = match1 + 1; } } - qsort(solutions,nSolutions, sizeof(IndexSolution), - compareSolution); + qsort(solutions, nSolutions, sizeof(IndexSolution), compareSolution); return 1; } + /*-------------------------------------------------------------- * This is used if we cannot find a solution for a triplet. * Then we try to reduce to a duett. So we look for a second * reflection in the original triplett which is closest * to 90 degree in angle. - */ -static int secondForDuett(int triplet[3]){ - double diff1, diff2; - - diff1 = ABS(90. - angleBetweenScatVec( - reflections[triplet[0]].UVW,reflections[triplet[1]].UVW)); - diff2 = ABS(90. - angleBetweenScatVec( - reflections[triplet[0]].UVW,reflections[triplet[2]].UVW)); - if(diff1 < diff2){ - return triplet[1]; - } else { - return triplet[2]; - } -} -/*--------------------------------------------------------------*/ -int SimIdxRun(){ - int triplet[3] = {999,999,999}, status; + */ +static int secondForDuett(int triplet[3]) +{ + double diff1, diff2; - SimIdxPrint(10,"SimIdx calculating with parameters:"); - SimIdxPrint(10, "Cell = %f %f %f %f %f %f", direct.a, direct.b, direct.c, - direct.alpha, direct.beta, direct.gamma); - SimIdxPrint(10,"Lambda = %f", lambda); - SimIdxPrint(10,"Sttlim, anglim = %f %f", sttlim, anglim); + diff1 = + ABS(90. - + angleBetweenScatVec(reflections[triplet[0]].UVW, + reflections[triplet[1]].UVW)); + diff2 = + ABS(90. - + angleBetweenScatVec(reflections[triplet[0]].UVW, + reflections[triplet[2]].UVW)); + if (diff1 < diff2) { + return triplet[1]; + } else { + return triplet[2]; + } +} + +/*--------------------------------------------------------------*/ +int SimIdxRun() +{ + int triplet[3] = { 999, 999, 999 }, status; + + SimIdxPrint(10, "SimIdx calculating with parameters:"); + SimIdxPrint(10, "Cell = %f %f %f %f %f %f", direct.a, direct.b, direct.c, + direct.alpha, direct.beta, direct.gamma); + SimIdxPrint(10, "Lambda = %f", lambda); + SimIdxPrint(10, "Sttlim, anglim = %f %f", sttlim, anglim); nSolutions = 0; calcRefTheta(); - if(!calcIndexes()){ + if (!calcIndexes()) { return 0; } - if(outLevel >= 10){ + if (outLevel >= 10) { printRefDiagnostic(); } - if(nReflections >= 3){ - if(!chooseTriplet(triplet)){ + if (nReflections >= 3) { + if (!chooseTriplet(triplet)) { return findSolutionsForDuett(triplet); } } else { @@ -645,30 +702,35 @@ int SimIdxRun(){ return findSolutionsForDuett(triplet); } - SimIdxPrint(10,"Choosen triplet: %d, %d, %d\n", triplet[0], - triplet[1], triplet[2]); + SimIdxPrint(10, "Choosen triplet: %d, %d, %d\n", triplet[0], + triplet[1], triplet[2]); - status = findSolutionsForTriplet(triplet,1); - if(nSolutions == 0){ - SimIdxPrint(1,"WARNING: found no right handed solution set, trying to find lefthanded"); - status = findSolutionsForTriplet(triplet,0); + status = findSolutionsForTriplet(triplet, 1); + if (nSolutions == 0) { + SimIdxPrint(1, + "WARNING: found no right handed solution set, trying to find lefthanded"); + status = findSolutionsForTriplet(triplet, 0); } - if(nSolutions == 0){ - SimIdxPrint(10,"Failed to find solution for triplet, trying duett"); - status = secondForDuett(triplet); - triplet[1] = status; - status = findSolutionsForDuett(triplet); + if (nSolutions == 0) { + SimIdxPrint(10, "Failed to find solution for triplet, trying duett"); + status = secondForDuett(triplet); + triplet[1] = status; + status = findSolutionsForDuett(triplet); } return status; } + /*=========================== solution retrieval ===================*/ -int SimIdxGetNSolutions(){ +int SimIdxGetNSolutions() +{ return nSolutions; } + /*------------------------------------------------------------------*/ -IndexSolution SimIdxGetSolution(int id){ +IndexSolution SimIdxGetSolution(int id) +{ IndexSolution broken; - if(id >= 0 && id < nSolutions){ + if (id >= 0 && id < nSolutions) { return solutions[id]; } broken.h[0] = -999; @@ -676,4 +738,3 @@ IndexSolution SimIdxGetSolution(int id){ broken.h[2] = -999; return broken; } - diff --git a/simidx.h b/simidx.h index 6f45c31a..1c24a01e 100644 --- a/simidx.h +++ b/simidx.h @@ -22,7 +22,7 @@ typedef struct { int h[3], k[3], l[3]; int originalID[3]; double diff; -}IndexSolution; +} IndexSolution; /** * \brief To be called before using simidx @@ -55,7 +55,7 @@ void SimIdxSetAngLim(double limit); * \brief set the spacegroup * \param spgrp The new spacegroup */ -void SimIdxSetSpacegroup(T_SgInfo *spgrp); +void SimIdxSetSpacegroup(T_SgInfo * spgrp); /** * \brief clear the reflection list * */ @@ -65,7 +65,7 @@ void SimIdxClearReflection(); * \param uvw The coordinates of the scattering vector */ void SimIdxAddReflection(double uvw[3]); -typedef void (*OutFunc)(void *userData, char *text); +typedef void (*OutFunc) (void *userData, char *text); /** * \brief configure the output for the algorithm * \param userData A pointer to user data which is passed to the @@ -100,5 +100,3 @@ int SimIdxGetNSolutions(); IndexSolution SimIdxGetSolution(int id); #endif - - diff --git a/sinfox.c b/sinfox.c index 280ad819..f6e7aa13 100644 --- a/sinfox.c +++ b/sinfox.c @@ -11,13 +11,13 @@ #include #include #include -#include /* incl. SCWrite */ +#include /* incl. SCWrite */ #include #include #include #include #include "sinfox.h" - + /*----------------------------------------------------------------------- * External Interface defined in sinfox.h includes * struct pSinfox @@ -28,1200 +28,1123 @@ * int argc, char *argv[]); * and lists of option keys *-----------------------------------------------------------------------*/ - + /* Core module functions */ static pSinfox CreateSinfox(void); -static int SinfoxInit(SicsInterp *pSics, char *infofile); -static int SinfoxHelp(pSinfox pSin, SicsInterp* pSics); -static int SinfoxReset(pSinfox pSin, SicsInterp* pSics); -static int SinfoxSetDesc(pSinfox pSin, SicsInterp *pSics, - char *objName, char *pDesc); -static int SinfoxSetGrp(pSinfox pSin, SicsInterp *pSics, - char *objName, char *pGrp); -static int SinfoxSetKey(pSinfox pSin, SicsInterp *pSics, - char *objName, char *keyName, char *eltValue); -static int SinfoxReadKey(pSinfox pSin, SicsInterp *pSics, - char *objName, char *fileName); -static int SinfoxList(pSinfox pSin, SicsInterp* pSics, SConnection *pCon, - char *pObjName, char *pKeyName, char *pEltName); -static int SinfoxEnumerate(pSinfox pSin, SicsInterp* pSics, - SConnection *pCon, char *keyName); -static int SinfoxShow(pSinfox pSin, SicsInterp* pSics, SConnection *pCon, - char *keyName, char *eltName); -static int SinfoxDevice(pSinfox pSin, SicsInterp* pSics, SConnection *pCon, - char *devName, char *keyName, char *eltName); -static int SinfoxGetGrp(pSinfox pSin, SicsInterp *pSics, - char *objName); - -/* Utility functions */ +static int SinfoxInit(SicsInterp * pSics, char *infofile); +static int SinfoxHelp(pSinfox pSin, SicsInterp * pSics); +static int SinfoxReset(pSinfox pSin, SicsInterp * pSics); +static int SinfoxSetDesc(pSinfox pSin, SicsInterp * pSics, + char *objName, char *pDesc); +static int SinfoxSetGrp(pSinfox pSin, SicsInterp * pSics, + char *objName, char *pGrp); +static int SinfoxSetKey(pSinfox pSin, SicsInterp * pSics, + char *objName, char *keyName, char *eltValue); +static int SinfoxReadKey(pSinfox pSin, SicsInterp * pSics, + char *objName, char *fileName); +static int SinfoxList(pSinfox pSin, SicsInterp * pSics, SConnection * pCon, + char *pObjName, char *pKeyName, char *pEltName); +static int SinfoxEnumerate(pSinfox pSin, SicsInterp * pSics, + SConnection * pCon, char *keyName); +static int SinfoxShow(pSinfox pSin, SicsInterp * pSics, SConnection * pCon, + char *keyName, char *eltName); +static int SinfoxDevice(pSinfox pSin, SicsInterp * pSics, + SConnection * pCon, char *devName, char *keyName, + char *eltName); +static int SinfoxGetGrp(pSinfox pSin, SicsInterp * pSics, char *objName); + +/* Utility functions */ static int EnumChoice(char *pList[], int iLength, char *pInput); static int LinkVar(char *tcl_var_name, char *pAddress, int link_flags); -static void setOKE(char *obj, char *key, char *elt, - char *oVal, char *kVal, char *eVal); +static void setOKE(char *obj, char *key, char *elt, + char *oVal, char *kVal, char *eVal); static int isNameDevice(char *name); static int isNameCommand(char *name); -static int isObjectDevice(CommandList *pObj); -static int isObjectCommand(CommandList *pObj); -static void addToList(Tcl_Interp *tTcl, Tcl_Obj *tList, char *prefix, char *sVal); -static void addPairsToList(Tcl_Interp *tTcl, Tcl_Obj *tList, IPair *pList); +static int isObjectDevice(CommandList * pObj); +static int isObjectCommand(CommandList * pObj); +static void addToList(Tcl_Interp * tTcl, Tcl_Obj * tList, char *prefix, + char *sVal); +static void addPairsToList(Tcl_Interp * tTcl, Tcl_Obj * tList, + IPair * pList); static void RemoveWhiteSpace(char *pText); /*--------------------------------------------------------------------------*/ pSinfox CreateSinfox(void) { - int i; - pSinfox pNew = NULL; - SicsInterp *pSics; - Tcl_Interp *tTcl; - - pNew = (pSinfox)malloc(sizeof(Sinfox)); - if(!pNew) - { - return NULL; - } - pNew->pDes = CreateDescriptor("sinfox"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - pSics = GetInterpreter(); - tTcl = (Tcl_Interp *)(pSics->pTcl); - pNew->tTcl = tTcl; - /* LinkVar("server::configName",pNew->configName,TCL_LINK_STRING); */ - pNew->buildVersion = Tcl_GetVar(tTcl, - "::server::buildVersion",TCL_GLOBAL_ONLY); - pNew->configName = Tcl_GetVar(tTcl, - "::server::configName",TCL_GLOBAL_ONLY); - pNew->configVersion = Tcl_GetVar(tTcl, - "::server::configVersion",TCL_GLOBAL_ONLY); - pNew->description = Tcl_GetVar(tTcl, - "::server::description",TCL_GLOBAL_ONLY); - pNew->instrument = Tcl_GetVar(tTcl, - "::server::instrument",TCL_GLOBAL_ONLY); - pNew->schemaVersion = Tcl_GetVar(tTcl, - "::server::schemaVersion",TCL_GLOBAL_ONLY); - pNew->pDes->pKeys = NULL; - return pNew; + int i; + pSinfox pNew = NULL; + SicsInterp *pSics; + Tcl_Interp *tTcl; + + pNew = (pSinfox) malloc(sizeof(Sinfox)); + if (!pNew) { + return NULL; + } + pNew->pDes = CreateDescriptor("sinfox"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + pSics = GetInterpreter(); + tTcl = (Tcl_Interp *) (pSics->pTcl); + pNew->tTcl = tTcl; + /* LinkVar("server::configName",pNew->configName,TCL_LINK_STRING); */ + pNew->buildVersion = Tcl_GetVar(tTcl, + "::server::buildVersion", + TCL_GLOBAL_ONLY); + pNew->configName = + Tcl_GetVar(tTcl, "::server::configName", TCL_GLOBAL_ONLY); + pNew->configVersion = + Tcl_GetVar(tTcl, "::server::configVersion", TCL_GLOBAL_ONLY); + pNew->description = + Tcl_GetVar(tTcl, "::server::description", TCL_GLOBAL_ONLY); + pNew->instrument = + Tcl_GetVar(tTcl, "::server::instrument", TCL_GLOBAL_ONLY); + pNew->schemaVersion = + Tcl_GetVar(tTcl, "::server::schemaVersion", TCL_GLOBAL_ONLY); + pNew->pDes->pKeys = NULL; + return pNew; } -/*-------------------------------------------------------------------------*/ +/*-------------------------------------------------------------------------*/ void DeleteSinfox(void *self) { - int i; - pSinfox pOld = (pSinfox)self; - - if(NULL==pOld) - { - return; - } - if(pOld->buildVersion) - { - free((void *)(pOld->buildVersion)); - } - if(pOld->configName) - { - free((void *)(pOld->configName)); - } - if(pOld->configVersion) - { - free((void *)(pOld->configVersion)); - } - if(pOld->description) - { - free((void *)(pOld->description)); - } - if(pOld->instrument) - { - free((void *)(pOld->instrument)); - } - if(pOld->schemaVersion) - { - free((void *)(pOld->schemaVersion)); - } - if(pOld->pDes) - { - DeleteDescriptor(pOld->pDes); - } - free(pOld); + int i; + pSinfox pOld = (pSinfox) self; + + if (NULL == pOld) { + return; + } + if (pOld->buildVersion) { + free((void *) (pOld->buildVersion)); + } + if (pOld->configName) { + free((void *) (pOld->configName)); + } + if (pOld->configVersion) { + free((void *) (pOld->configVersion)); + } + if (pOld->description) { + free((void *) (pOld->description)); + } + if (pOld->instrument) { + free((void *) (pOld->instrument)); + } + if (pOld->schemaVersion) { + free((void *) (pOld->schemaVersion)); + } + if (pOld->pDes) { + DeleteDescriptor(pOld->pDes); + } + free(pOld); } /*--------------------------------------------------------------------------*/ -int InstallSinfox(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) +int InstallSinfox(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) { - pSinfox pNew = NULL; - pNew = CreateSinfox(); - if(NULL==pNew) - { - SCWrite(pCon,"No memory to create Sinfox",eError); - return 0; - } - AddCommand(pSics,"sinfox",SinfoxAction,DeleteSinfox,pNew); - SCSendOK(pCon); - return 1; + pSinfox pNew = NULL; + pNew = CreateSinfox(); + if (NULL == pNew) { + SCWrite(pCon, "No memory to create Sinfox", eError); + return 0; + } + AddCommand(pSics, "sinfox", SinfoxAction, DeleteSinfox, pNew); + SCSendOK(pCon); + return 1; } /*--------------------------------------------------------------------------*/ -static int SinfoxInit(SicsInterp *pSics, char *infofile) +static int SinfoxInit(SicsInterp * pSics, char *infofile) { - SConnection *pCon = NULL; - char pBuf[1024]; - int iRet; - - /* create a connection */ - pCon = SCCreateDummyConnection(pSics); - if(!pCon) - { - return 0; - } - /* - pCon->iFiles = 1; - pCon->pFiles[0] = stdout; - */ + SConnection *pCon = NULL; + char pBuf[1024]; + int iRet; - /* evaluate the file */ - sprintf(pBuf,"fileeval %s",infofile); - iRet = InterpExecute(pSics,pCon,pBuf); - /* - pCon->iFiles = 0; - */ - SCDeleteConnection(pCon); - - return iRet; -} - -/*------------------------------------------------------------------------*/ -static int SinfoxHelp(pSinfox pSin, SicsInterp* pSics) -{ - Tcl_SetResult((Tcl_Interp *)(pSics->pTcl),"Sinfox Help",TCL_VOLATILE); - return 1; -} - -/*------------------------------------------------------------------------*/ -static int SinfoxReset(pSinfox pSin, SicsInterp* pSics) -{ - int i; - - pSin->buildVersion = Tcl_GetVar(pSin->tTcl, - "::server::buildVersion",TCL_GLOBAL_ONLY); - pSin->configName = Tcl_GetVar(pSin->tTcl, - "::server::configName",TCL_GLOBAL_ONLY); - pSin->configVersion = Tcl_GetVar(pSin->tTcl, - "::server::configVersion",TCL_GLOBAL_ONLY); - pSin->description = Tcl_GetVar(pSin->tTcl, - "::server::description",TCL_GLOBAL_ONLY); - pSin->instrument = Tcl_GetVar(pSin->tTcl, - "::server::instrument",TCL_GLOBAL_ONLY); - pSin->schemaVersion = Tcl_GetVar(pSin->tTcl, - "::server::schemaVersion",TCL_GLOBAL_ONLY); - - Tcl_SetResult(pSin->tTcl,"{Sinfox Reset}",TCL_VOLATILE); - return 1; -} - -/*------------------------------------------------------------------------*/ -static int SinfoxSetDesc(pSinfox pSin, SicsInterp *pSics, - char *objName, char *pDesc) -{ - CommandList *pCurrent; - pObjectDescriptor pDes = NULL; - char pBuf[256]; - - memset(pBuf,0,256); - pCurrent = pSics->pCList; - - pCurrent = FindCommand(pSics,objName); - if(NULL != pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - SetDescriptorDescription(pDes,pDesc); - sprintf(pBuf,"description=%s",pDesc); - Tcl_SetObjResult(pSin->tTcl,Tcl_NewStringObj(pBuf,strlen(pBuf))); - return 1; - } - } - sprintf(pBuf,"error=unable to set %s.description to %s",objName,pDesc); - Tcl_SetObjResult(pSin->tTcl,Tcl_NewStringObj(pBuf,strlen(pBuf))); + /* create a connection */ + pCon = SCCreateDummyConnection(pSics); + if (!pCon) { return 0; + } + /* + pCon->iFiles = 1; + pCon->pFiles[0] = stdout; + */ + + /* evaluate the file */ + sprintf(pBuf, "fileeval %s", infofile); + iRet = InterpExecute(pSics, pCon, pBuf); + /* + pCon->iFiles = 0; + */ + SCDeleteConnection(pCon); + + return iRet; } /*------------------------------------------------------------------------*/ -static int SinfoxSetGrp(pSinfox pSin, SicsInterp *pSics, - char *objName, char *pGrp) +static int SinfoxHelp(pSinfox pSin, SicsInterp * pSics) { - CommandList *pCurrent; - pObjectDescriptor pDes = NULL; - char pBuf[256]; - - memset(pBuf,0,256); - pCurrent = pSics->pCList; - - pCurrent = FindCommand(pSics,objName); - if(NULL!=pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - SetDescriptorGroup(pDes,pGrp); - sprintf(pBuf,"group=%s",pGrp); - Tcl_SetObjResult(pSin->tTcl,Tcl_NewStringObj(pBuf,strlen(pBuf))); - return 1; - } - } - sprintf(pBuf,"error=unable to set %s.group to %s",objName,pGrp); - Tcl_SetObjResult(pSin->tTcl,Tcl_NewStringObj(pBuf,strlen(pBuf))); - return 0; + Tcl_SetResult((Tcl_Interp *) (pSics->pTcl), "Sinfox Help", TCL_VOLATILE); + return 1; } -static int SinfoxGetGrp(pSinfox pSin, SicsInterp *pSics, - char *objName) +/*------------------------------------------------------------------------*/ +static int SinfoxReset(pSinfox pSin, SicsInterp * pSics) +{ + int i; + + pSin->buildVersion = Tcl_GetVar(pSin->tTcl, + "::server::buildVersion", + TCL_GLOBAL_ONLY); + pSin->configName = + Tcl_GetVar(pSin->tTcl, "::server::configName", TCL_GLOBAL_ONLY); + pSin->configVersion = + Tcl_GetVar(pSin->tTcl, "::server::configVersion", TCL_GLOBAL_ONLY); + pSin->description = + Tcl_GetVar(pSin->tTcl, "::server::description", TCL_GLOBAL_ONLY); + pSin->instrument = + Tcl_GetVar(pSin->tTcl, "::server::instrument", TCL_GLOBAL_ONLY); + pSin->schemaVersion = + Tcl_GetVar(pSin->tTcl, "::server::schemaVersion", TCL_GLOBAL_ONLY); + + Tcl_SetResult(pSin->tTcl, "{Sinfox Reset}", TCL_VOLATILE); + return 1; +} + +/*------------------------------------------------------------------------*/ +static int SinfoxSetDesc(pSinfox pSin, SicsInterp * pSics, + char *objName, char *pDesc) { CommandList *pCurrent; - pObjectDescriptor pDes = NULL; + pObjectDescriptor pDes = NULL; char pBuf[256]; - pBuf[0]='\0'; + memset(pBuf, 0, 256); pCurrent = pSics->pCList; - pCurrent = FindCommand(pSics,objName); - if(NULL==pCurrent) { - sprintf(pBuf,"%s.group=none",objName); - Tcl_SetObjResult(pSin->tTcl,Tcl_NewStringObj(pBuf,strlen(pBuf))); - return 1; - } else { + pCurrent = FindCommand(pSics, objName); + if (NULL != pCurrent) { pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - sprintf(pBuf,"%s.group=%s",objName, GetDescriptorGroup(pDes)); - Tcl_SetObjResult(pSin->tTcl,Tcl_NewStringObj(pBuf,strlen(pBuf))); - return 1; + if (NULL != pDes) { + SetDescriptorDescription(pDes, pDesc); + sprintf(pBuf, "description=%s", pDesc); + Tcl_SetObjResult(pSin->tTcl, Tcl_NewStringObj(pBuf, strlen(pBuf))); + return 1; + } + } + sprintf(pBuf, "error=unable to set %s.description to %s", objName, + pDesc); + Tcl_SetObjResult(pSin->tTcl, Tcl_NewStringObj(pBuf, strlen(pBuf))); + return 0; +} + +/*------------------------------------------------------------------------*/ +static int SinfoxSetGrp(pSinfox pSin, SicsInterp * pSics, + char *objName, char *pGrp) +{ + CommandList *pCurrent; + pObjectDescriptor pDes = NULL; + char pBuf[256]; + + memset(pBuf, 0, 256); + pCurrent = pSics->pCList; + + pCurrent = FindCommand(pSics, objName); + if (NULL != pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + SetDescriptorGroup(pDes, pGrp); + sprintf(pBuf, "group=%s", pGrp); + Tcl_SetObjResult(pSin->tTcl, Tcl_NewStringObj(pBuf, strlen(pBuf))); + return 1; + } + } + sprintf(pBuf, "error=unable to set %s.group to %s", objName, pGrp); + Tcl_SetObjResult(pSin->tTcl, Tcl_NewStringObj(pBuf, strlen(pBuf))); + return 0; +} + +static int SinfoxGetGrp(pSinfox pSin, SicsInterp * pSics, char *objName) +{ + CommandList *pCurrent; + pObjectDescriptor pDes = NULL; + char pBuf[256]; + + pBuf[0] = '\0'; + pCurrent = pSics->pCList; + + pCurrent = FindCommand(pSics, objName); + if (NULL == pCurrent) { + sprintf(pBuf, "%s.group=none", objName); + Tcl_SetObjResult(pSin->tTcl, Tcl_NewStringObj(pBuf, strlen(pBuf))); + return 1; + } else { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + sprintf(pBuf, "%s.group=%s", objName, GetDescriptorGroup(pDes)); + Tcl_SetObjResult(pSin->tTcl, Tcl_NewStringObj(pBuf, strlen(pBuf))); + return 1; } } return 0; } + /*------------------------------------------------------------------------*/ -static int SinfoxSetKey(pSinfox pSin, SicsInterp *pSics, - char *objName, char *keyName, char *eltValue) +static int SinfoxSetKey(pSinfox pSin, SicsInterp * pSics, + char *objName, char *keyName, char *eltValue) { - CommandList *pCurrent; - pObjectDescriptor pDes = NULL; - int bOK = 0; - char *obj; - char pBuf[256]; - memset(pBuf,0,256); - + CommandList *pCurrent; + pObjectDescriptor pDes = NULL; + int bOK = 0; + char *obj; + char pBuf[256]; + memset(pBuf, 0, 256); + + obj = strdup(objName); + strtolower(obj); + + if (0 == strcmp(obj, "server")) { /* sinfox object is surrogate for server object inside SICS */ + free(obj); + obj = strdup("sinfox"); + } else { + free(obj); obj = strdup(objName); - strtolower(obj); - - if(0==strcmp(obj,"server")) - { /* sinfox object is surrogate for server object inside SICS */ - free(obj); - obj = strdup("sinfox"); - } - else - { - free(obj); - obj = strdup(objName); - } - - pCurrent = pSics->pCList; - pCurrent = FindCommand(pSics,obj); + } - if(NULL != pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - strtolower(keyName); - strtolower(eltValue); - pDes->pKeys = IFSetOption(pDes->pKeys,keyName,eltValue); - if(NULL != pDes->pKeys) - { - bOK=1; - } - } + pCurrent = pSics->pCList; + pCurrent = FindCommand(pSics, obj); + + if (NULL != pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + strtolower(keyName); + strtolower(eltValue); + pDes->pKeys = IFSetOption(pDes->pKeys, keyName, eltValue); + if (NULL != pDes->pKeys) { + bOK = 1; + } } - - if(bOK==1) - { - sprintf(pBuf,"%s.%s=%s", - pCurrent->pName,pDes->pKeys->name,pDes->pKeys->value); - } - else - { - sprintf(pBuf,"error=unable to set %s.%s to %s", - obj,keyName,eltValue); - } - - Tcl_SetObjResult(pSin->tTcl,Tcl_NewStringObj(pBuf,strlen(pBuf))); - return bOK; + } + + if (bOK == 1) { + sprintf(pBuf, "%s.%s=%s", + pCurrent->pName, pDes->pKeys->name, pDes->pKeys->value); + } else { + sprintf(pBuf, "error=unable to set %s.%s to %s", + obj, keyName, eltValue); + } + + Tcl_SetObjResult(pSin->tTcl, Tcl_NewStringObj(pBuf, strlen(pBuf))); + return bOK; } /*------------------------------------------------------------------------*/ -static int SinfoxReadKey(pSinfox pSin, SicsInterp *pSics, - char *objName, char *fileName) +static int SinfoxReadKey(pSinfox pSin, SicsInterp * pSics, + char *objName, char *fileName) { - static FILE *fKeyFile = NULL; - CommandList *pCurrent; - pObjectDescriptor pDes = NULL; - char pBuf[256]; - char pName[132]; - char pValue[132]; - char *pPos; - int iLen; + static FILE *fKeyFile = NULL; + CommandList *pCurrent; + pObjectDescriptor pDes = NULL; + char pBuf[256]; + char pName[132]; + char pValue[132]; + char *pPos; + int iLen; - memset(pBuf,0,256); - - pCurrent = pSics->pCList; - pCurrent = FindCommand(pSics,objName); + memset(pBuf, 0, 256); - if(NULL != pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - fKeyFile = fopen(fileName,"r"); - if(NULL == fKeyFile) - { - return 0; - } + pCurrent = pSics->pCList; + pCurrent = FindCommand(pSics, objName); - while(!feof(fKeyFile)) - { - fgets(pBuf,255,fKeyFile); - if(feof(fKeyFile)) continue; - - if(pBuf[0] == '#') continue; - - pPos = strchr(pBuf,'='); - if(!pPos) continue; - - iLen = pPos - pBuf; - strncpy(pName,pBuf,iLen); - pName[iLen] = '\0'; - strcpy(pValue,(pPos+1)); - RemoveWhiteSpace(pName); - RemoveWhiteSpace(pValue); - strtolower(pName); - strtolower(pValue); - - pDes->pKeys = IFAddOption(pDes->pKeys,pName,pValue); - if(NULL==pDes->pKeys) return 0; - } + if (NULL != pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + fKeyFile = fopen(fileName, "r"); + if (NULL == fKeyFile) { + return 0; + } - fclose(fKeyFile); - return 1; - } + while (!feof(fKeyFile)) { + fgets(pBuf, 255, fKeyFile); + if (feof(fKeyFile)) + continue; + + if (pBuf[0] == '#') + continue; + + pPos = strchr(pBuf, '='); + if (!pPos) + continue; + + iLen = pPos - pBuf; + strncpy(pName, pBuf, iLen); + pName[iLen] = '\0'; + strcpy(pValue, (pPos + 1)); + RemoveWhiteSpace(pName); + RemoveWhiteSpace(pValue); + strtolower(pName); + strtolower(pValue); + + pDes->pKeys = IFAddOption(pDes->pKeys, pName, pValue); + if (NULL == pDes->pKeys) + return 0; + } + + fclose(fKeyFile); + return 1; } - return 0; + } + return 0; } - + /*------------------------------------------------------------------------*/ -static int SinfoxList(pSinfox pSin, SicsInterp* pSics, SConnection *pCon, - char *pObjName, char *pKeyName, char *pEltName) +static int SinfoxList(pSinfox pSin, SicsInterp * pSics, SConnection * pCon, + char *pObjName, char *pKeyName, char *pEltName) { - int iRet; - char *objName; - char *keyName = NULL; - char *eltName = NULL; - CommandList *pObj = NULL; - - objName = strdup(pObjName); strtolower(objName); - if (NULL!=pKeyName) - { - keyName = strdup(pKeyName); strtolower(keyName); + int iRet; + char *objName; + char *keyName = NULL; + char *eltName = NULL; + CommandList *pObj = NULL; + + objName = strdup(pObjName); + strtolower(objName); + if (NULL != pKeyName) { + keyName = strdup(pKeyName); + strtolower(keyName); + } + if (NULL != pEltName) { + eltName = strdup(pEltName); + strtolower(eltName); + } + + /* check if objName is an interfaceName */ + iRet = EnumChoice(pIFaces, iNumIFaces, objName); + if (-1 < iRet) { + if ((0 == strcmp(keyName, "device")) || keyName == NULL) { /* format as sinfox list server interface interfaceName */ + setOKE(objName, keyName, eltName, "server", "interface", objName); + } else if (0 == strcmp(keyName, "command")) { /* todo: not yet implemented */ + return SinfoxHelp(pSin, pSics); } - if (NULL!=pEltName) - { - eltName = strdup(pEltName); strtolower(eltName); + } + + /* check if objName is commandName */ + /* check if objName is a deviceName */ + pObj = FindCommand(pSics, objName); + if (NULL != pObj) { + if (1 == isObjectDevice(pObj)) { + return SinfoxDevice(pSin, pSics, pCon, objName, keyName, eltName); + } else { /* command */ + return 0; + iRet = EnumChoice(pCommandKeys, iNumCommandKeys, keyName); + switch (iRet) { + case 1: /* argument */ + /* todo: not yet implemented */ + case 2: /* device */ + /* todo: secondary: not yet implemented */ + case 3: /* interface */ + /* todo: secondary: not yet implemented */ + default: /* sinfox list server command commandName */ + setOKE(objName, keyName, eltName, "server", "command", objName); + break; + } } - - /* check if objName is an interfaceName */ - iRet = EnumChoice(pIFaces,iNumIFaces,objName); - if(-1 < iRet) - { - if((0==strcmp(keyName,"device")) || keyName == NULL ) - { /* format as sinfox list server interface interfaceName */ - setOKE(objName,keyName,eltName,"server","interface",objName); - } else if(0==strcmp(keyName,"command")) - { /* todo: not yet implemented */ - return SinfoxHelp(pSin,pSics); - } + } + + if (0 == strcmp(objName, "server")) { + iRet = EnumChoice(pServerKeys, iNumServerKeys, keyName); + /* if invalid (iRet < 0) then default to "help" command */ + switch (iRet) { + /* cases that have no eltName argument */ + case 1: /* list */ + case 3: /* connection */ + case 6: /* experiment */ + case 9: /* key */ + return SinfoxEnumerate(pSin, pSics, pCon, keyName); + break; + /* cases that are not fully implemented */ + case 2: /* command */ + case 4: /* device */ + case 5: /* deviceType */ + case 7: /* group */ + case 8: /* interface */ + return SinfoxShow(pSin, pSics, pCon, keyName, eltName); + break; + /* fully functional cases */ + case 0: /* help */ + default: + return SinfoxHelp(pSin, pSics); + break; } - - /* check if objName is commandName */ - /* check if objName is a deviceName */ - pObj = FindCommand(pSics,objName); - if(NULL != pObj) - { - if(1==isObjectDevice(pObj)) - { - return SinfoxDevice(pSin,pSics,pCon,objName,keyName,eltName); - } - else /* command */ - { return 0; - iRet = EnumChoice(pCommandKeys,iNumCommandKeys,keyName); - switch(iRet) - { - case 1: /* argument */ - /* todo: not yet implemented */ - case 2: /* device */ - /* todo: secondary: not yet implemented */ - case 3: /* interface */ - /* todo: secondary: not yet implemented */ - default: /* sinfox list server command commandName */ - setOKE(objName,keyName,eltName,"server","command",objName); - break; - } - } - } - - if(0 == strcmp(objName,"server")) - { - iRet = EnumChoice(pServerKeys,iNumServerKeys,keyName); - /* if invalid (iRet < 0) then default to "help" command */ - switch(iRet) - { - /* cases that have no eltName argument */ - case 1: /* list */ - case 3: /* connection */ - case 6: /* experiment */ - case 9: /* key */ - return SinfoxEnumerate(pSin,pSics,pCon,keyName); - break; - /* cases that are not fully implemented */ - case 2: /* command */ - case 4: /* device */ - case 5: /* deviceType */ - case 7: /* group */ - case 8: /* interface */ - return SinfoxShow(pSin,pSics,pCon,keyName,eltName); - break; - /* fully functional cases */ - case 0: /* help */ - default: - return SinfoxHelp(pSin,pSics); - break; - } - return 1; - } - return 0; + return 1; + } + return 0; } /*------------------------------------------------------------------------*/ /* Retrieve a list of elements from CommandList matching criteria */ -static int SinfoxEnumerate(pSinfox pSin, SicsInterp* pSics, - SConnection *pCon, char *keyName) +static int SinfoxEnumerate(pSinfox pSin, SicsInterp * pSics, + SConnection * pCon, char *keyName) { - CommandList *pCurrent; - pObjectDescriptor pDes = NULL; - Tcl_Interp *tTcl; - Tcl_Obj *tList; - IPair *pOption = NULL; - IPair *pGroups = NULL; - pSicsVariable pSVar = NULL; - int iRet; - char pBuf[256], *pPtr = NULL; - int checkDeviceTypes[iNumDeviceTypes]; + CommandList *pCurrent; + pObjectDescriptor pDes = NULL; + Tcl_Interp *tTcl; + Tcl_Obj *tList; + IPair *pOption = NULL; + IPair *pGroups = NULL; + pSicsVariable pSVar = NULL; + int iRet; + char pBuf[256], *pPtr = NULL; + int checkDeviceTypes[iNumDeviceTypes]; - pCurrent = pSics->pCList; - tTcl = (Tcl_Interp *)(pSics->pTcl); - tList = Tcl_NewListObj(0,NULL); - memset(pBuf,0,256); - - iRet = EnumChoice(pServerKeys,iNumServerKeys,keyName); - /* if invalid (iRet < 0) then default to "help" command */ - switch(iRet) - { - /* cases that have no eltName argument - not fully implemented */ - case 1: /* list */ - addToList(tTcl,tList,"buildVersion",(char *)(pSin->buildVersion)); - addToList(tTcl,tList,"configName",(char *)(pSin->configName)); - addToList(tTcl,tList,"configVersion",(char *)(pSin->configVersion)); - addToList(tTcl,tList,"description",(char *)(pSin->description)); - addToList(tTcl,tList,"instrument",(char *)(pSin->instrument)); - addToList(tTcl,tList,"schemaVersion",(char *)(pSin->schemaVersion)); - addPairsToList(tTcl,tList,pSin->pDes->pKeys); - addPairsToList(tTcl,tList,pSICSOptions); - break; - case 2: /* command */ - while(pCurrent) - { - if(1==isObjectCommand(pCurrent)) - { - strcpy(pBuf,pCurrent->pName); - Tcl_ListObjAppendElement(tTcl,tList, - Tcl_NewStringObj(pBuf,strlen(pBuf))); - } - pCurrent = pCurrent->pNext; - } - break; - case 3: /* connection */ - sprintf(pBuf,"%d",SCGetRights(pCon)); - addToList(tTcl,tList,"userAccessLevel",pBuf); - addToList(tTcl,tList,"protocol",GetProtocolName(pCon)); - break; - case 6: /* experiment */ - while(pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - strcpy(pBuf,pDes->name); - strtolower(pBuf); - if(0==strcmp(pBuf,"sicsvariable")) - { - pSVar=FindVariable(pSics,pCurrent->pName); - addToList(tTcl,tList,pCurrent->pName,pSVar->text); - } - } - pCurrent = pCurrent->pNext; - } - break; - case 9: /* key */ - for(iRet=0;iRetpName); - Tcl_ListObjAppendElement(tTcl,tList, - Tcl_NewStringObj(pBuf,strlen(pBuf))); - } - pCurrent = pCurrent->pNext; - } - break; - case 5: /* deviceType */ - for(iRet=0;iRetpData); - if(NULL != pDes) - { - strcpy(pBuf,pDes->name); - strtolower(pBuf); - iRet = EnumChoice(pDeviceTypes,iNumDeviceTypes,pBuf); - if(-1 < iRet) - { - if(1!=checkDeviceTypes[iRet]) - { - Tcl_ListObjAppendElement(tTcl,tList, - Tcl_NewStringObj(pBuf,strlen(pBuf))); - checkDeviceTypes[iRet] = 1; - } - } - } - pCurrent = pCurrent->pNext; - } - break; - case 7: /* group */ - pCurrent = pSics->pCList; - /* Always add default group "none" */ - pGroups = IFAddOption(pGroups,"none","OK"); - Tcl_ListObjAppendElement(tTcl,tList,Tcl_NewStringObj("none",4)); - while(pCurrent) - { - if(1==isObjectDevice(pCurrent)) - { - pDes = FindDescriptor(pCurrent->pData); - if((pPtr = IFindOption(pDes->pKeys,"group")) != NULL) - { - strcpy(pBuf,pPtr); - strtolower(pBuf); - if(NULL==IFindOption(pGroups,pBuf)) - { - pGroups = IFAddOption(pGroups,pBuf,"OK"); - Tcl_ListObjAppendElement(tTcl,tList, - Tcl_NewStringObj(pBuf,strlen(pBuf))); - } - } - } - pCurrent = pCurrent->pNext; - } - if(NULL!=pGroups) - { - IFDeleteOptions(pGroups); - } - break; - case 8: /* interface */ - for(iRet=0;iRetpCList; + tTcl = (Tcl_Interp *) (pSics->pTcl); + tList = Tcl_NewListObj(0, NULL); + memset(pBuf, 0, 256); - pCurrent = pSics->pCList; - tTcl = (Tcl_Interp *)(pSics->pTcl); - tList = Tcl_NewListObj(0,NULL); - memset(pBuf,0,256); - - if (NULL==eltName) - { - return SinfoxEnumerate(pSin,pSics,pCon,keyName); + iRet = EnumChoice(pServerKeys, iNumServerKeys, keyName); + /* if invalid (iRet < 0) then default to "help" command */ + switch (iRet) { + /* cases that have no eltName argument - not fully implemented */ + case 1: /* list */ + addToList(tTcl, tList, "buildVersion", (char *) (pSin->buildVersion)); + addToList(tTcl, tList, "configName", (char *) (pSin->configName)); + addToList(tTcl, tList, "configVersion", + (char *) (pSin->configVersion)); + addToList(tTcl, tList, "description", (char *) (pSin->description)); + addToList(tTcl, tList, "instrument", (char *) (pSin->instrument)); + addToList(tTcl, tList, "schemaVersion", + (char *) (pSin->schemaVersion)); + addPairsToList(tTcl, tList, pSin->pDes->pKeys); + addPairsToList(tTcl, tList, pSICSOptions); + break; + case 2: /* command */ + while (pCurrent) { + if (1 == isObjectCommand(pCurrent)) { + strcpy(pBuf, pCurrent->pName); + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pBuf, strlen(pBuf))); + } + pCurrent = pCurrent->pNext; } - pElt = strdup(eltName); - strtolower(pElt); - - iRet = EnumChoice(pServerKeys,iNumServerKeys,keyName); - /* if invalid (iRet < 0) then default to "help" command */ - switch(iRet) - { - case 2: /* command */ - case 4: /* device - list deviceName {attribute|command|interface} */ - //addToList(tTcl,tList,pElt,"is being searched for"); - pCurrent = FindCommand(pSics,pElt); - if(NULL!=pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - //addToList(tTcl,tList,"debug2","descriptor found"); - if(1==isObjectDevice(pCurrent)) - { - if(NULL!=pDes->name) - { - strcpy(pBuf,pDes->name); - strtolower(pBuf); - addToList(tTcl,tList,"devicetype",pBuf); - } - if((pTmp = IFindOption(pDes->pKeys,"group")) != NULL) - { - strcpy(pBuf,pTmp); - strtolower(pBuf); - addToList(tTcl,tList,"group",pBuf); - } - } - if((pTmp = IFindOption(pDes->pKeys,"description")) != NULL) - { - strcpy(pBuf,pTmp); - strtolower(pBuf); - addToList(tTcl,tList,"description",pBuf); - } - //addToList(tTcl,tList,"debug3","default fields processed"); - if(NULL!=pDes->pKeys) - { - addPairsToList(tTcl,tList,pDes->pKeys); - } - } - } - //addToList(tTcl,tList,"debug4","device show finished"); - break; - case 5: /* devicetype */ - iRet = EnumChoice(pDeviceTypes,iNumDeviceTypes,pElt); - if (0 > iRet) - { - if((0==strcmp(pElt,"all"))||(0==strcmp(pElt,"*"))) - { - Tcl_SetVar(tTcl,"name",keyName,0); - return SinfoxEnumerate(pSin,pSics,pCon,keyName); - } - } - else - { - while(pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - strcpy(pBuf,pDes->name); - strtolower(pBuf); - if(0==strcmp(pElt,pBuf)) - { - strcpy(pBuf,pCurrent->pName); - strtolower(pBuf); - Tcl_ListObjAppendElement(tTcl,tList, - Tcl_NewStringObj(pBuf,strlen(pBuf))); - } - } - pCurrent = pCurrent->pNext; - } - } - break; - case 7: /* group */ - if((0==strcmp(pElt,"all"))||(0==strcmp(pElt,"*"))) - { - Tcl_SetVar(tTcl,"name",keyName,0); - return SinfoxEnumerate(pSin,pSics,pCon,keyName); - } - while(NULL!=pCurrent) - { - if(1==isObjectDevice(pCurrent)) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - if((pTmp = IFindOption(pDes->pKeys,"group")) == NULL) - { - strcpy(pBuf,"none"); - } - else - { - strcpy(pBuf,pTmp); - strtolower(pBuf); - } - if(0==strcmp(pElt,pBuf)) - { - strcpy(pBuf,pCurrent->pName); - strtolower(pBuf); - Tcl_ListObjAppendElement(tTcl,tList, - Tcl_NewStringObj(pBuf,strlen(pBuf))); - } - } - } - pCurrent = pCurrent->pNext; - } - break; - case 8: /* interface */ - iRet = EnumChoice(pIFaces,iNumIFaces,pElt); - if (0 > iRet) - { - if((0==strcmp(pElt,"all"))||(0==strcmp(pElt,"*"))) - { - Tcl_SetVar(tTcl,"name",keyName,0); - return SinfoxEnumerate(pSin,pSics,pCon,keyName); - } - } - else - { - switch(iRet) - { - case 0: /* callback */ - iType = CALLBACKINTERFACE; break; - case 1: /* countable */ - iType = COUNTID; break; - case 2: /* drivable */ - iType = DRIVEID; break; - case 3: /* environment */ - iType = ENVIRINTERFACE; break; - default: /* interface not recognised */ - Tcl_SetObjResult(tTcl,tList); - return 1; - break; - } - while(pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - if(NULL != pDes->GetInterface(pDes,iType)) - { - strcpy(pBuf,pCurrent->pName); - strtolower(pBuf); - Tcl_ListObjAppendElement(tTcl,tList, - Tcl_NewStringObj(pBuf,strlen(pBuf))); - } - } - pCurrent = pCurrent->pNext; - } - } - break; - default: - addToList(tTcl,tList,"error","unknown key"); - break; + break; + case 3: /* connection */ + sprintf(pBuf, "%d", SCGetRights(pCon)); + addToList(tTcl, tList, "userAccessLevel", pBuf); + addToList(tTcl, tList, "protocol", GetProtocolName(pCon)); + break; + case 6: /* experiment */ + while (pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + strcpy(pBuf, pDes->name); + strtolower(pBuf); + if (0 == strcmp(pBuf, "sicsvariable")) { + pSVar = FindVariable(pSics, pCurrent->pName); + addToList(tTcl, tList, pCurrent->pName, pSVar->text); + } + } + pCurrent = pCurrent->pNext; } - Tcl_SetObjResult(tTcl,tList); - return 1; -} - -/*-------------------------------------------------------------------------*/ -static int SinfoxDevice(pSinfox pSin, SicsInterp* pSics, SConnection *pCon, - char *devName, char *keyName, char *eltName) -{ - int i,iRet,iType; - Tcl_Obj *tList; - char pBuf[256]; - char *pTmp; - CommandList *pCurrent; - pObjectDescriptor pDes = NULL; - - memset(pBuf,0,256); + break; + case 9: /* key */ + for (iRet = 0; iRet < iNumServerKeys; iRet++) { + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pServerKeys[iRet], + strlen(pServerKeys + [iRet]))); + } + break; + /* cases that have not specified eltName */ + case 4: /* device */ + while (pCurrent) { + if (1 == isObjectDevice(pCurrent)) { + strcpy(pBuf, pCurrent->pName); + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pBuf, strlen(pBuf))); + } + pCurrent = pCurrent->pNext; + } + break; + case 5: /* deviceType */ + for (iRet = 0; iRet < iNumDeviceTypes; iRet++) { + checkDeviceTypes[iRet] = 0; + } + while (pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + strcpy(pBuf, pDes->name); + strtolower(pBuf); + iRet = EnumChoice(pDeviceTypes, iNumDeviceTypes, pBuf); + if (-1 < iRet) { + if (1 != checkDeviceTypes[iRet]) { + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pBuf, strlen(pBuf))); + checkDeviceTypes[iRet] = 1; + } + } + } + pCurrent = pCurrent->pNext; + } + break; + case 7: /* group */ pCurrent = pSics->pCList; - tList = Tcl_NewListObj(0,NULL); - pCurrent = FindCommand(pSics,devName); -/* debug */ -addToList(pSin->tTcl,tList,"dev",devName); -addToList(pSin->tTcl,tList,"key",keyName); -addToList(pSin->tTcl,tList,"elt",eltName); -/*-------*/ - iRet = EnumChoice(pDeviceKeys,iNumDeviceKeys,keyName); - switch(iRet) - { - case 2: /* interface */ - if(NULL!=pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - for(i=0;itTcl,tList); - return 0; - break; - } - if(NULL != pDes->GetInterface(pDes,iType)) - { - strcpy(pBuf,pIFaces[i]); - Tcl_ListObjAppendElement(pSin->tTcl,tList, - Tcl_NewStringObj(pBuf,strlen(pBuf))); - } - } - } - } - break; - case 0: /* attribute */ - if(NULL==eltName) - { - return SinfoxShow(pSin,pSics,pCon,"device",devName); - } - else - { - if(NULL!=pCurrent) - { - pDes = FindDescriptor(pCurrent->pData); - if(NULL != pDes) - { - pTmp = IFindOption(pDes->pKeys,eltName); - if(NULL!=pTmp) - { - strcpy(pBuf,pTmp); - addToList(pSin->tTcl,tList,eltName,pTmp); - } - } - } - } - break; - case 1: /* command */ - /* todo: secondary: not yet implemented */ - default: /* sinfox list server device deviceName */ - return SinfoxShow(pSin,pSics,pCon,"device",devName); - break; - } - Tcl_SetObjResult(pSin->tTcl,tList); - return 1; + /* Always add default group "none" */ + pGroups = IFAddOption(pGroups, "none", "OK"); + Tcl_ListObjAppendElement(tTcl, tList, Tcl_NewStringObj("none", 4)); + while (pCurrent) { + if (1 == isObjectDevice(pCurrent)) { + pDes = FindDescriptor(pCurrent->pData); + if ((pPtr = IFindOption(pDes->pKeys, "group")) != NULL) { + strcpy(pBuf, pPtr); + strtolower(pBuf); + if (NULL == IFindOption(pGroups, pBuf)) { + pGroups = IFAddOption(pGroups, pBuf, "OK"); + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pBuf, strlen(pBuf))); + } + } + } + pCurrent = pCurrent->pNext; + } + if (NULL != pGroups) { + IFDeleteOptions(pGroups); + } + break; + case 8: /* interface */ + for (iRet = 0; iRet < iNumIFaces; iRet++) { + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pIFaces[iRet], + strlen(pIFaces[iRet]))); + } + break; + /* special cases */ + case 0: /* help */ + default: + return SinfoxHelp(pSin, pSics); + break; + } + Tcl_SetObjResult(tTcl, tList); + return 1; } -/*-------------------------------------------------------------------------*/ -int SinfoxAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) -{ - int iRet; - char **argx; - FuPaResult PaRes; - pSinfox pSin = NULL; - - const int iNumCmds = 8; - FuncTemplate CommandTemplate[] = { - {"help",0,{0,0}}, - {"list",3,{FUPATEXT,FUPATEXT,FUPAOPT}}, - {"setdesc",2,{FUPATEXT,FUPATEXT}}, - {"setgrp",2,{FUPATEXT,FUPATEXT}}, - {"setkey",3,{FUPATEXT,FUPATEXT,FUPATEXT}}, - {"reset",0,{0,0}}, - {"readkey",2,{FUPATEXT,FUPATEXT}}, - {"getgrp",1,{FUPATEXT}}, - {NULL} - }; - assert(pCon); - assert(pSics); - pSin = (pSinfox)pData; - assert(pSin); - - /* You need to have User level access rights to use this facility */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; +/*------------------------------------------------------------------------*/ +static int SinfoxShow(pSinfox pSin, SicsInterp * pSics, SConnection * pCon, + char *keyName, char *eltName) +{ + CommandList *pCurrent; + pObjectDescriptor pDes = NULL; + Tcl_Interp *tTcl; + Tcl_Obj *tList; + int iRet, iType; + char pBuf[256]; + char *pTmp; + char *pElt; + + pCurrent = pSics->pCList; + tTcl = (Tcl_Interp *) (pSics->pTcl); + tList = Tcl_NewListObj(0, NULL); + memset(pBuf, 0, 256); + + if (NULL == eltName) { + return SinfoxEnumerate(pSin, pSics, pCon, keyName); + } + pElt = strdup(eltName); + strtolower(pElt); + + iRet = EnumChoice(pServerKeys, iNumServerKeys, keyName); + /* if invalid (iRet < 0) then default to "help" command */ + switch (iRet) { + case 2: /* command */ + case 4: /* device - list deviceName {attribute|command|interface} */ + //addToList(tTcl,tList,pElt,"is being searched for"); + pCurrent = FindCommand(pSics, pElt); + if (NULL != pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + //addToList(tTcl,tList,"debug2","descriptor found"); + if (1 == isObjectDevice(pCurrent)) { + if (NULL != pDes->name) { + strcpy(pBuf, pDes->name); + strtolower(pBuf); + addToList(tTcl, tList, "devicetype", pBuf); + } + if ((pTmp = IFindOption(pDes->pKeys, "group")) != NULL) { + strcpy(pBuf, pTmp); + strtolower(pBuf); + addToList(tTcl, tList, "group", pBuf); + } + } + if ((pTmp = IFindOption(pDes->pKeys, "description")) != NULL) { + strcpy(pBuf, pTmp); + strtolower(pBuf); + addToList(tTcl, tList, "description", pBuf); + } + //addToList(tTcl,tList,"debug3","default fields processed"); + if (NULL != pDes->pKeys) { + addPairsToList(tTcl, tList, pDes->pKeys); + } + } } - - /* parse function args */ - argtolower(argc,argv); - argx = &argv[1]; - iRet = EvaluateFuPa((pFuncTemplate)&CommandTemplate,iNumCmds,argc-1,argx,&PaRes); - /* if invalid (iRet < 0) then default to "help" command */ - switch(iRet) - { - case 1: /* list */ - if(1==PaRes.Arg[2].iVal) - { - iRet = SinfoxList(pSin,pSics,pCon, - PaRes.Arg[0].text,PaRes.Arg[1].text,PaRes.Arg[2].text); - } - else - { - iRet = SinfoxList(pSin,pSics,pCon, - PaRes.Arg[0].text,PaRes.Arg[1].text,NULL); - } - return iRet; - break; - case 2: /* setdesc */ - return SinfoxSetDesc(pSin,pSics, - PaRes.Arg[0].text,PaRes.Arg[1].text); - break; - case 3: /* setgrp */ - return SinfoxSetGrp(pSin,pSics, - PaRes.Arg[0].text,PaRes.Arg[1].text); - break; - case 4: /* setkey */ - return SinfoxSetKey(pSin,pSics, - PaRes.Arg[0].text,PaRes.Arg[1].text,PaRes.Arg[2].text); - break; - case 5: /* reset */ - return SinfoxReset(pSin,pSics); - break; - case 6: /* readkey */ - return SinfoxReadKey(pSin,pSics, - PaRes.Arg[0].text,PaRes.Arg[1].text); - break; - case 7: /*getgrp */ - return SinfoxGetGrp(pSin, pSics, PaRes.Arg[0].text); - break; - case 0: /* help */ - default: - return SinfoxHelp(pSin,pSics); - break; + //addToList(tTcl,tList,"debug4","device show finished"); + break; + case 5: /* devicetype */ + iRet = EnumChoice(pDeviceTypes, iNumDeviceTypes, pElt); + if (0 > iRet) { + if ((0 == strcmp(pElt, "all")) || (0 == strcmp(pElt, "*"))) { + Tcl_SetVar(tTcl, "name", keyName, 0); + return SinfoxEnumerate(pSin, pSics, pCon, keyName); + } + } else { + while (pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + strcpy(pBuf, pDes->name); + strtolower(pBuf); + if (0 == strcmp(pElt, pBuf)) { + strcpy(pBuf, pCurrent->pName); + strtolower(pBuf); + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pBuf, strlen(pBuf))); + } + } + pCurrent = pCurrent->pNext; + } } - return 1; + break; + case 7: /* group */ + if ((0 == strcmp(pElt, "all")) || (0 == strcmp(pElt, "*"))) { + Tcl_SetVar(tTcl, "name", keyName, 0); + return SinfoxEnumerate(pSin, pSics, pCon, keyName); + } + while (NULL != pCurrent) { + if (1 == isObjectDevice(pCurrent)) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + if ((pTmp = IFindOption(pDes->pKeys, "group")) == NULL) { + strcpy(pBuf, "none"); + } else { + strcpy(pBuf, pTmp); + strtolower(pBuf); + } + if (0 == strcmp(pElt, pBuf)) { + strcpy(pBuf, pCurrent->pName); + strtolower(pBuf); + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pBuf, strlen(pBuf))); + } + } + } + pCurrent = pCurrent->pNext; + } + break; + case 8: /* interface */ + iRet = EnumChoice(pIFaces, iNumIFaces, pElt); + if (0 > iRet) { + if ((0 == strcmp(pElt, "all")) || (0 == strcmp(pElt, "*"))) { + Tcl_SetVar(tTcl, "name", keyName, 0); + return SinfoxEnumerate(pSin, pSics, pCon, keyName); + } + } else { + switch (iRet) { + case 0: /* callback */ + iType = CALLBACKINTERFACE; + break; + case 1: /* countable */ + iType = COUNTID; + break; + case 2: /* drivable */ + iType = DRIVEID; + break; + case 3: /* environment */ + iType = ENVIRINTERFACE; + break; + default: /* interface not recognised */ + Tcl_SetObjResult(tTcl, tList); + return 1; + break; + } + while (pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + if (NULL != pDes->GetInterface(pDes, iType)) { + strcpy(pBuf, pCurrent->pName); + strtolower(pBuf); + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pBuf, strlen(pBuf))); + } + } + pCurrent = pCurrent->pNext; + } + } + break; + default: + addToList(tTcl, tList, "error", "unknown key"); + break; + } + Tcl_SetObjResult(tTcl, tList); + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int SinfoxDevice(pSinfox pSin, SicsInterp * pSics, + SConnection * pCon, char *devName, char *keyName, + char *eltName) +{ + int i, iRet, iType; + Tcl_Obj *tList; + char pBuf[256]; + char *pTmp; + CommandList *pCurrent; + pObjectDescriptor pDes = NULL; + + memset(pBuf, 0, 256); + pCurrent = pSics->pCList; + tList = Tcl_NewListObj(0, NULL); + pCurrent = FindCommand(pSics, devName); +/* debug */ + addToList(pSin->tTcl, tList, "dev", devName); + addToList(pSin->tTcl, tList, "key", keyName); + addToList(pSin->tTcl, tList, "elt", eltName); +/*-------*/ + iRet = EnumChoice(pDeviceKeys, iNumDeviceKeys, keyName); + switch (iRet) { + case 2: /* interface */ + if (NULL != pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + for (i = 0; i < iNumIFaces; i++) { + switch (i) { + case 0: /* callback */ + iType = CALLBACKINTERFACE; + break; + case 1: /* countable */ + iType = COUNTID; + break; + case 2: /* drivable */ + iType = DRIVEID; + break; + case 3: /* environment */ + iType = ENVIRINTERFACE; + break; + default: /* interface not recognised */ + Tcl_SetObjResult(pSin->tTcl, tList); + return 0; + break; + } + if (NULL != pDes->GetInterface(pDes, iType)) { + strcpy(pBuf, pIFaces[i]); + Tcl_ListObjAppendElement(pSin->tTcl, tList, + Tcl_NewStringObj(pBuf, strlen(pBuf))); + } + } + } + } + break; + case 0: /* attribute */ + if (NULL == eltName) { + return SinfoxShow(pSin, pSics, pCon, "device", devName); + } else { + if (NULL != pCurrent) { + pDes = FindDescriptor(pCurrent->pData); + if (NULL != pDes) { + pTmp = IFindOption(pDes->pKeys, eltName); + if (NULL != pTmp) { + strcpy(pBuf, pTmp); + addToList(pSin->tTcl, tList, eltName, pTmp); + } + } + } + } + break; + case 1: /* command */ + /* todo: secondary: not yet implemented */ + default: /* sinfox list server device deviceName */ + return SinfoxShow(pSin, pSics, pCon, "device", devName); + break; + } + Tcl_SetObjResult(pSin->tTcl, tList); + return 1; +} + +/*-------------------------------------------------------------------------*/ +int SinfoxAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet; + char **argx; + FuPaResult PaRes; + pSinfox pSin = NULL; + + const int iNumCmds = 8; + FuncTemplate CommandTemplate[] = { + {"help", 0, {0, 0}}, + {"list", 3, {FUPATEXT, FUPATEXT, FUPAOPT}}, + {"setdesc", 2, {FUPATEXT, FUPATEXT}}, + {"setgrp", 2, {FUPATEXT, FUPATEXT}}, + {"setkey", 3, {FUPATEXT, FUPATEXT, FUPATEXT}}, + {"reset", 0, {0, 0}}, + {"readkey", 2, {FUPATEXT, FUPATEXT}}, + {"getgrp", 1, {FUPATEXT}}, + {NULL} + }; + + assert(pCon); + assert(pSics); + pSin = (pSinfox) pData; + assert(pSin); + + /* You need to have User level access rights to use this facility */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + + /* parse function args */ + argtolower(argc, argv); + argx = &argv[1]; + iRet = + EvaluateFuPa((pFuncTemplate) & CommandTemplate, iNumCmds, argc - 1, + argx, &PaRes); + /* if invalid (iRet < 0) then default to "help" command */ + switch (iRet) { + case 1: /* list */ + if (1 == PaRes.Arg[2].iVal) { + iRet = SinfoxList(pSin, pSics, pCon, + PaRes.Arg[0].text, PaRes.Arg[1].text, + PaRes.Arg[2].text); + } else { + iRet = SinfoxList(pSin, pSics, pCon, + PaRes.Arg[0].text, PaRes.Arg[1].text, NULL); + } + return iRet; + break; + case 2: /* setdesc */ + return SinfoxSetDesc(pSin, pSics, + PaRes.Arg[0].text, PaRes.Arg[1].text); + break; + case 3: /* setgrp */ + return SinfoxSetGrp(pSin, pSics, PaRes.Arg[0].text, PaRes.Arg[1].text); + break; + case 4: /* setkey */ + return SinfoxSetKey(pSin, pSics, + PaRes.Arg[0].text, PaRes.Arg[1].text, + PaRes.Arg[2].text); + break; + case 5: /* reset */ + return SinfoxReset(pSin, pSics); + break; + case 6: /* readkey */ + return SinfoxReadKey(pSin, pSics, + PaRes.Arg[0].text, PaRes.Arg[1].text); + break; + case 7: /*getgrp */ + return SinfoxGetGrp(pSin, pSics, PaRes.Arg[0].text); + break; + case 0: /* help */ + default: + return SinfoxHelp(pSin, pSics); + break; + } + return 1; } /*-------------------------------------------------------------------------*/ static int EnumChoice(char *pList[], int iLength, char *pInput) { - int i; - int iRet = -1; - - for(i=0;ipTcl); - /* tcl_flags = f(link_flags)*/ - switch(link_flags) - { - case TCL_LINK_INT : - break; - case TCL_LINK_DOUBLE: - case TCL_LINK_BOOLEAN: - case TCL_LINK_STRING: - tcl_flags = link_flags; - break; - default : return 0; - } - Tcl_LinkVar(pTcl,tcl_var_name,pAddress,tcl_flags); - return 1; + SicsInterp *pSics = NULL; + Tcl_Interp *pTcl = NULL; + int tcl_flags = TCL_LINK_INT; + + pSics = GetInterpreter(); + pTcl = (Tcl_Interp *) (pSics->pTcl); + /* tcl_flags = f(link_flags) */ + switch (link_flags) { + case TCL_LINK_INT: + break; + case TCL_LINK_DOUBLE: + case TCL_LINK_BOOLEAN: + case TCL_LINK_STRING: + tcl_flags = link_flags; + break; + default: + return 0; + } + Tcl_LinkVar(pTcl, tcl_var_name, pAddress, tcl_flags); + return 1; } /*-------------------------------------------------------------------------*/ -static void setOKE(char *obj, char *key, char *elt, char *oVal, char *kVal, char *eVal) +static void setOKE(char *obj, char *key, char *elt, char *oVal, char *kVal, + char *eVal) { - char *eBuf; - char *kBuf; - char *oBuf; - eBuf = strdup(eVal); - kBuf = strdup(kVal); - oBuf = strdup(oVal); - free(elt); elt = eBuf; - free(key); key = kBuf; - free(obj); obj = oBuf; + char *eBuf; + char *kBuf; + char *oBuf; + eBuf = strdup(eVal); + kBuf = strdup(kVal); + oBuf = strdup(oVal); + free(elt); + elt = eBuf; + free(key); + key = kBuf; + free(obj); + obj = oBuf; } /*-------------------------------------------------------------------------*/ static int isNameDevice(char *name) { - SicsInterp *pSics; - CommandList *pObj = NULL; - Dummy *pDum = NULL; - - pSics = GetInterpreter(); - pObj = FindCommand(pSics,name); - if(NULL != pObj) - { - pDum = (Dummy *)pObj->pData; - if(NULL != pDum) - { - if(NULL != pDum->pDescriptor->GetInterface(pDum,DRIVEID)) return 1; - if(NULL != pDum->pDescriptor->GetInterface(pDum,COUNTID)) return 1; - if(NULL != pDum->pDescriptor->GetInterface(pDum,ENVIRINTERFACE)) return 1; - } + SicsInterp *pSics; + CommandList *pObj = NULL; + Dummy *pDum = NULL; + + pSics = GetInterpreter(); + pObj = FindCommand(pSics, name); + if (NULL != pObj) { + pDum = (Dummy *) pObj->pData; + if (NULL != pDum) { + if (NULL != pDum->pDescriptor->GetInterface(pDum, DRIVEID)) + return 1; + if (NULL != pDum->pDescriptor->GetInterface(pDum, COUNTID)) + return 1; + if (NULL != pDum->pDescriptor->GetInterface(pDum, ENVIRINTERFACE)) + return 1; } - return 0; + } + return 0; } /*-------------------------------------------------------------------------*/ static int isNameCommand(char *name) { - SicsInterp *pSics; - CommandList *pObj = NULL; - Dummy *pDum = NULL; - - pSics = GetInterpreter(); - pObj = FindCommand(pSics,name); - if(NULL != pObj) - { - pDum = (Dummy *)pObj->pData; - if(NULL != pDum) - { - if(NULL != pDum->pDescriptor->GetInterface(pDum,DRIVEID)) return 0; - if(NULL != pDum->pDescriptor->GetInterface(pDum,COUNTID)) return 0; - if(NULL != pDum->pDescriptor->GetInterface(pDum,ENVIRINTERFACE)) return 0; - } + SicsInterp *pSics; + CommandList *pObj = NULL; + Dummy *pDum = NULL; + + pSics = GetInterpreter(); + pObj = FindCommand(pSics, name); + if (NULL != pObj) { + pDum = (Dummy *) pObj->pData; + if (NULL != pDum) { + if (NULL != pDum->pDescriptor->GetInterface(pDum, DRIVEID)) + return 0; + if (NULL != pDum->pDescriptor->GetInterface(pDum, COUNTID)) + return 0; + if (NULL != pDum->pDescriptor->GetInterface(pDum, ENVIRINTERFACE)) + return 0; + } + return 1; + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +static int isObjectDevice(CommandList * pObj) +{ + Dummy *pDum = NULL; + if (NULL != pObj) { + pDum = (Dummy *) pObj->pData; + if (NULL != pDum) { + if (NULL != pDum->pDescriptor->GetInterface(pDum, DRIVEID)) + return 1; + if (NULL != pDum->pDescriptor->GetInterface(pDum, COUNTID)) + return 1; + if (NULL != pDum->pDescriptor->GetInterface(pDum, ENVIRINTERFACE)) return 1; } - return 0; + } + return 0; } /*-------------------------------------------------------------------------*/ -static int isObjectDevice(CommandList *pObj) +static int isObjectCommand(CommandList * pObj) { - Dummy *pDum = NULL; - if(NULL != pObj) - { - pDum = (Dummy *)pObj->pData; - if(NULL != pDum) - { - if(NULL != pDum->pDescriptor->GetInterface(pDum,DRIVEID)) return 1; - if(NULL != pDum->pDescriptor->GetInterface(pDum,COUNTID)) return 1; - if(NULL != pDum->pDescriptor->GetInterface(pDum,ENVIRINTERFACE)) - return 1; - } + Dummy *pDum = NULL; + if (NULL != pObj) { + pDum = (Dummy *) pObj->pData; + if (NULL != pDum) { + if (NULL != pDum->pDescriptor->GetInterface(pDum, DRIVEID)) + return 0; + if (NULL != pDum->pDescriptor->GetInterface(pDum, COUNTID)) + return 0; + if (NULL != pDum->pDescriptor->GetInterface(pDum, ENVIRINTERFACE)) + return 0; } - return 0; + return 1; + } + return 0; } /*-------------------------------------------------------------------------*/ -static int isObjectCommand(CommandList *pObj) +static void addToList(Tcl_Interp * tTcl, Tcl_Obj * tList, char *prefix, + char *sVal) { - Dummy *pDum = NULL; - if(NULL != pObj) - { - pDum = (Dummy *)pObj->pData; - if(NULL != pDum) - { - if(NULL != pDum->pDescriptor->GetInterface(pDum,DRIVEID)) return 0; - if(NULL != pDum->pDescriptor->GetInterface(pDum,COUNTID)) return 0; - if(NULL != pDum->pDescriptor->GetInterface(pDum,ENVIRINTERFACE)) return 0; - } - return 1; - } - return 0; + char pBuf[256]; + if (NULL != sVal) { + memset(pBuf, 0, 256); + sprintf(pBuf, "%s=%s", prefix, sVal); + Tcl_ListObjAppendElement(tTcl, tList, + Tcl_NewStringObj(pBuf, strlen(pBuf))); + } } /*-------------------------------------------------------------------------*/ -static void addToList(Tcl_Interp *tTcl, Tcl_Obj *tList, char *prefix, char *sVal) +static void addPairsToList(Tcl_Interp * tTcl, Tcl_Obj * tList, + IPair * pList) { - char pBuf[256]; - if(NULL!=sVal) - { - memset(pBuf,0,256); - sprintf(pBuf,"%s=%s",prefix,sVal); - Tcl_ListObjAppendElement(tTcl,tList,Tcl_NewStringObj(pBuf,strlen(pBuf))); - } -} -/*-------------------------------------------------------------------------*/ -static void addPairsToList(Tcl_Interp *tTcl, Tcl_Obj *tList, IPair *pList) -{ - IPair *pCurrent; - if(NULL!=pList) - { - pCurrent = pList; - while(NULL!=pCurrent) - { - addToList(tTcl,tList,pCurrent->name,pCurrent->value); - pCurrent = pCurrent->pNext; - } + IPair *pCurrent; + if (NULL != pList) { + pCurrent = pList; + while (NULL != pCurrent) { + addToList(tTcl, tList, pCurrent->name, pCurrent->value); + pCurrent = pCurrent->pNext; } + } } + /*--------------------------------------------------------------------------*/ static void RemoveWhiteSpace(char *pText) { - int i, ii, i3; - char *pPtr; - - if(NULL==pText) return; - - /* find start */ - i = 0; - while(isspace(pText[i])) - { - i++; - } - - /* find end */ - ii = strlen(pText); + int i, ii, i3; + char *pPtr; + + if (NULL == pText) + return; + + /* find start */ + i = 0; + while (isspace(pText[i])) { + i++; + } + + /* find end */ + ii = strlen(pText); + ii--; + while ((isspace(pText[ii])) || (pText[ii] == '\n')) { ii--; - while( (isspace(pText[ii])) || (pText[ii] == '\n') ) - { - ii--; - } - - /* copy it */ - pPtr = pText; - for(i3 = i; i3 < (ii+1); i3++) - { - *pPtr = pText[i3]; - pPtr++; - } - *pPtr = '\0'; + } + + /* copy it */ + pPtr = pText; + for (i3 = i; i3 < (ii + 1); i3++) { + *pPtr = pText[i3]; + pPtr++; + } + *pPtr = '\0'; } diff --git a/sinfox.h b/sinfox.h index 7e66b929..4d688532 100644 --- a/sinfox.h +++ b/sinfox.h @@ -6,110 +6,110 @@ #include typedef struct __Sinfox { - pObjectDescriptor pDes; /* required as first field */ - const char *buildVersion; - const char *configName; - const char *configVersion; - const char *description; - const char *instrument; - const char *schemaVersion; - Tcl_Interp *tTcl; + pObjectDescriptor pDes; /* required as first field */ + const char *buildVersion; + const char *configName; + const char *configVersion; + const char *description; + const char *instrument; + const char *schemaVersion; + Tcl_Interp *tTcl; } Sinfox; typedef struct __Sinfox *pSinfox; -#ifndef SICSSITE /* Avoid duplicate declaration in site_ansto.c */ +#ifndef SICSSITE /* Avoid duplicate declaration in site_ansto.c */ const int iNumInfoKeys = 6; char *pInfoKeys[7] = { - "buildVersion", - "configName", - "configVersion", - "description", - "instrument", - "schemaVersion", - NULL + "buildVersion", + "configName", + "configVersion", + "description", + "instrument", + "schemaVersion", + NULL }; - + const int iNumCommandKeys = 3; char *pCommandKeys[4] = { - "argument", - "device", - "interface", - NULL + "argument", + "device", + "interface", + NULL }; const int iNumDeviceKeys = 3; char *pDeviceKeys[4] = { - "attribute", - "command", - "interface", - NULL + "attribute", + "command", + "interface", + NULL }; const int iNumDeviceTypes = 24; char *pDeviceTypes[25] = { - "4-circle-calculus", - "anticollider", - "chopper", - "chopperadaptor", - "connection", - "crystalselector", - "environment monitor", - "environment controller", - "gpib", - "hklscan", - "hmcontrol", - "lin2ang", - "local maximum detector", - "maximizer", - "mesure", - "motor", - "mulmot", - "omega2theta", - "rs232 controller", - "scanobject", - "sicsvariable", - "singlecounter", - "velocityselector", - "xytable", - NULL + "4-circle-calculus", + "anticollider", + "chopper", + "chopperadaptor", + "connection", + "crystalselector", + "environment monitor", + "environment controller", + "gpib", + "hklscan", + "hmcontrol", + "lin2ang", + "local maximum detector", + "maximizer", + "mesure", + "motor", + "mulmot", + "omega2theta", + "rs232 controller", + "scanobject", + "sicsvariable", + "singlecounter", + "velocityselector", + "xytable", + NULL }; const int iNumIFaces = 4; char *pIFaces[5] = { - "callback", - "countable", - "drivable", - "environment", - NULL + "callback", + "countable", + "drivable", + "environment", + NULL }; const int iNumServerKeys = 10; char *pServerKeys[11] = { - "help", - "list", - "command", - "connection", - "device", - "devicetype", - "experiment", - "group", - "interface", - "key", - NULL + "help", + "list", + "command", + "connection", + "device", + "devicetype", + "experiment", + "group", + "interface", + "key", + NULL }; - -#endif /* SICSSITE */ + +#endif /* SICSSITE */ /*--------------------- lifecycle -------------------------------------- */ -int InstallSinfox(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int InstallSinfox(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); void DeleteSinfox(void *pSelf); - + /*--------------------- operations --------------------------------------*/ -int SinfoxAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int SinfoxAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*-----------------------------------------------------------------------*/ -#endif /* ANSTO_SINFOX */ +#endif /* ANSTO_SINFOX */ diff --git a/singletas.c b/singletas.c index a03cdb42..00d9c887 100644 --- a/singletas.c +++ b/singletas.c @@ -20,250 +20,265 @@ #include "fourlib.h" /*---------------------------------------------------------------------*/ -static int calculateTASSettings(pSingleDiff self, - double *hkl, double *settings){ - tasQEPosition qe; - tasAngles angles; - double e, *normal; - int status; - MATRIX mn; - char error[132]; - float fHard; - - e = 9.045/self->lambda; - e = e*e; - qe.ki = energyToK(e); - qe.kf = energyToK(e); - qe.qh = hkl[0]; - qe.qk = hkl[1]; - qe.ql = hkl[2]; - - normal = SXGetPlanenormal(); - if(normal == NULL){ - return 0; - } - mn = vectorToMatrix(normal); - if(mn == NULL){ - return 0; - } - - status = calcTasQAngles(self->UB, mn, 1, qe, &angles); - if(status < 0) { - status = 0; - } else { - status = 1; - } - settings[0] = angles.a3; - settings[1] = angles.sample_two_theta; - settings[2] = angles.sgu; - settings[3] = angles.sgl; - if(!MotorCheckBoundary(SXGetMotor(Omega), (float)settings[0],&fHard, - error, 132)){ - status = 0; - } - if(!MotorCheckBoundary(SXGetMotor(TwoTheta), (float)settings[1],&fHard, - error, 132)){ - status = 0; - } - if(!MotorCheckBoundary(SXGetMotor(Sgu), (float)settings[2],&fHard, - error, 132)){ - status = 0; - } - if(!MotorCheckBoundary(SXGetMotor(Sgl), (float)settings[3],&fHard, - error, 132)){ - status = 0; - } - free(normal); - mat_free(mn); - return status; +static int calculateTASSettings(pSingleDiff self, + double *hkl, double *settings) +{ + tasQEPosition qe; + tasAngles angles; + double e, *normal; + int status; + MATRIX mn; + char error[132]; + float fHard; + + e = 9.045 / self->lambda; + e = e * e; + qe.ki = energyToK(e); + qe.kf = energyToK(e); + qe.qh = hkl[0]; + qe.qk = hkl[1]; + qe.ql = hkl[2]; + + normal = SXGetPlanenormal(); + if (normal == NULL) { + return 0; + } + mn = vectorToMatrix(normal); + if (mn == NULL) { + return 0; + } + + status = calcTasQAngles(self->UB, mn, 1, qe, &angles); + if (status < 0) { + status = 0; + } else { + status = 1; + } + settings[0] = angles.a3; + settings[1] = angles.sample_two_theta; + settings[2] = angles.sgu; + settings[3] = angles.sgl; + if (!MotorCheckBoundary(SXGetMotor(Omega), (float) settings[0], &fHard, + error, 132)) { + status = 0; + } + if (!MotorCheckBoundary + (SXGetMotor(TwoTheta), (float) settings[1], &fHard, error, 132)) { + status = 0; + } + if (!MotorCheckBoundary(SXGetMotor(Sgu), (float) settings[2], &fHard, + error, 132)) { + status = 0; + } + if (!MotorCheckBoundary(SXGetMotor(Sgl), (float) settings[3], &fHard, + error, 132)) { + status = 0; + } + free(normal); + mat_free(mn); + return status; } + /*-------------------------------------------------------------------*/ -static int settingsToTasList(struct __SingleDiff *self, double *settings){ - - setNewMotorTarget(self->motList, (char *)SXGetMotorName(Omega), - (float)settings[0]); - setNewMotorTarget(self->motList, (char *)SXGetMotorName(TwoTheta), - (float)settings[1]); - setNewMotorTarget(self->motList, (char *)SXGetMotorName(Sgu), - (float)settings[2]); - setNewMotorTarget(self->motList, (char *)SXGetMotorName(Sgl), - (float)settings[3]); - return 1; -} -/*--------------------------------------------------------------------*/ -static int hklFromTasAngles(struct __SingleDiff *self, double *hkl){ - pIDrivable pDriv; - double e, stt, om, sgu, sgl; - tasQEPosition qe; - tasAngles angles; - int status = 1; - - e = 9.045/self->lambda; - e = e*e; - qe.ki = energyToK(e); - qe.kf = energyToK(e); - - pDriv = makeMotListInterface(); - pDriv->GetValue(&self->motList, pServ->dummyCon); - - stt = getListMotorPosition(self->motList, - (char *)SXGetMotorName(TwoTheta)); - om = getListMotorPosition(self->motList, - (char *)SXGetMotorName(Omega)); - sgu = getListMotorPosition(self->motList, - (char *)SXGetMotorName(Sgu)); - sgl = getListMotorPosition(self->motList, - (char *)SXGetMotorName(Sgl)); +static int settingsToTasList(struct __SingleDiff *self, double *settings) +{ - angles.a3 = om; - angles.sample_two_theta = stt; - angles.sgu = sgu; - angles.sgl = sgl; - - status = calcTasQH(self->UB, angles, &qe); - if(status < 0){ - status = 0; - } - hkl[0] = qe.qh; - hkl[1] = qe.qk; - hkl[2] = qe.ql; - - return status; + setNewMotorTarget(self->motList, (char *) SXGetMotorName(Omega), + (float) settings[0]); + setNewMotorTarget(self->motList, (char *) SXGetMotorName(TwoTheta), + (float) settings[1]); + setNewMotorTarget(self->motList, (char *) SXGetMotorName(Sgu), + (float) settings[2]); + setNewMotorTarget(self->motList, (char *) SXGetMotorName(Sgl), + (float) settings[3]); + return 1; } + +/*--------------------------------------------------------------------*/ +static int hklFromTasAngles(struct __SingleDiff *self, double *hkl) +{ + pIDrivable pDriv; + double e, stt, om, sgu, sgl; + tasQEPosition qe; + tasAngles angles; + int status = 1; + + e = 9.045 / self->lambda; + e = e * e; + qe.ki = energyToK(e); + qe.kf = energyToK(e); + + pDriv = makeMotListInterface(); + pDriv->GetValue(&self->motList, pServ->dummyCon); + + stt = getListMotorPosition(self->motList, + (char *) SXGetMotorName(TwoTheta)); + om = getListMotorPosition(self->motList, (char *) SXGetMotorName(Omega)); + sgu = getListMotorPosition(self->motList, (char *) SXGetMotorName(Sgu)); + sgl = getListMotorPosition(self->motList, (char *) SXGetMotorName(Sgl)); + + angles.a3 = om; + angles.sample_two_theta = stt; + angles.sgu = sgu; + angles.sgl = sgl; + + status = calcTasQH(self->UB, angles, &qe); + if (status < 0) { + status = 0; + } + hkl[0] = qe.qh; + hkl[1] = qe.qk; + hkl[2] = qe.ql; + + return status; +} + /*-------------------------------------------------------------------------*/ -static int hklFromTasAnglesGiven(struct __SingleDiff *self, - double *settings, double *hkl){ - double e; - tasQEPosition qe; - tasAngles angles; - int status = 1; - - e = 9.045/self->lambda; - e = e*e; - qe.ki = energyToK(e); - qe.kf = energyToK(e); - - angles.a3 = settings[0]; - angles.sample_two_theta = settings[1]; - angles.sgu = settings[2]; - angles.sgl = settings[3]; - - status = calcTasQH(self->UB, angles, &qe); - if(status < 0){ - status = 0; - } - hkl[0] = qe.qh; - hkl[1] = qe.qk; - hkl[2] = qe.ql; - - return status; -} -/*------------------------------------------------------------------*/ -static int getTasReflection(char *id, tasReflection *r){ - pSICSOBJ refList; - double hkl[3], angles[4]; - double lambda, e; - - lambda = SXGetLambda(); - e = 9.045/lambda; - e = e*e; - - refList = SXGetReflectionList(); - if(!GetRefIndexID(refList,id,hkl)){ - return 0; - } else { - r->qe.qh = hkl[0]; - r->qe.qk = hkl[1]; - r->qe.ql = hkl[2]; - r->qe.ki = energyToK(e); - r->qe.kf = energyToK(e); - GetRefAnglesID(refList,id,angles); - r->angles.a3 = angles[0]; - r->angles.sample_two_theta = angles[1]; - r->angles.sgu = angles[2]; - r->angles.sgl = angles[3]; - } - return 1; -} -/*--------------------------------------------------------------------------*/ -MATRIX calcTasUBFromTwo(pSingleDiff self, - char *refid1, char *refid2, int *err){ - MATRIX ub = NULL, pl = NULL; - tasReflection r1, r2; - lattice direct; - double p[3]; - - direct.a = self->cell[0]; - direct.b = self->cell[1]; - direct.c = self->cell[2]; - direct.alpha = self->cell[3]; - direct.beta = self->cell[4]; - direct.gamma = self->cell[5]; +static int hklFromTasAnglesGiven(struct __SingleDiff *self, + double *settings, double *hkl) +{ + double e; + tasQEPosition qe; + tasAngles angles; + int status = 1; - if(!getTasReflection(refid1,&r1)){ - *err = REFERR; - return NULL; - } - if(!getTasReflection(refid2,&r2)){ - *err = REFERR; - return NULL; - } - - ub = calcTasUBFromTwoReflections(direct,r1,r2,err); - pl = calcPlaneNormal(r1,r2); - if(pl != NULL){ - matrixToVector(pl,p); - SXSetPlanenormal(p); - mat_free(pl); - } - return ub; + e = 9.045 / self->lambda; + e = e * e; + qe.ki = energyToK(e); + qe.kf = energyToK(e); + + angles.a3 = settings[0]; + angles.sample_two_theta = settings[1]; + angles.sgu = settings[2]; + angles.sgl = settings[3]; + + status = calcTasQH(self->UB, angles, &qe); + if (status < 0) { + status = 0; + } + hkl[0] = qe.qh; + hkl[1] = qe.qk; + hkl[2] = qe.ql; + + return status; } + +/*------------------------------------------------------------------*/ +static int getTasReflection(char *id, tasReflection * r) +{ + pSICSOBJ refList; + double hkl[3], angles[4]; + double lambda, e; + + lambda = SXGetLambda(); + e = 9.045 / lambda; + e = e * e; + + refList = SXGetReflectionList(); + if (!GetRefIndexID(refList, id, hkl)) { + return 0; + } else { + r->qe.qh = hkl[0]; + r->qe.qk = hkl[1]; + r->qe.ql = hkl[2]; + r->qe.ki = energyToK(e); + r->qe.kf = energyToK(e); + GetRefAnglesID(refList, id, angles); + r->angles.a3 = angles[0]; + r->angles.sample_two_theta = angles[1]; + r->angles.sgu = angles[2]; + r->angles.sgl = angles[3]; + } + return 1; +} + /*--------------------------------------------------------------------------*/ -MATRIX calcTasUBFromThree(pSingleDiff self, - char *refid1, char *refid2, char *refid3, int *err){ - /* - * not implemented yet - * There is also a problem: if I have three reflections, which - * defines the plane normal? This also does not make much sense anyway: - * we usually will not have a reflection out of plane: thus the three - * will be coplanar and the results may not be useful at all! - */ - return NULL; +MATRIX calcTasUBFromTwo(pSingleDiff self, + char *refid1, char *refid2, int *err) +{ + MATRIX ub = NULL, pl = NULL; + tasReflection r1, r2; + lattice direct; + double p[3]; + + direct.a = self->cell[0]; + direct.b = self->cell[1]; + direct.c = self->cell[2]; + direct.alpha = self->cell[3]; + direct.beta = self->cell[4]; + direct.gamma = self->cell[5]; + + if (!getTasReflection(refid1, &r1)) { + *err = REFERR; + return NULL; + } + if (!getTasReflection(refid2, &r2)) { + *err = REFERR; + return NULL; + } + + ub = calcTasUBFromTwoReflections(direct, r1, r2, err); + pl = calcPlaneNormal(r1, r2); + if (pl != NULL) { + matrixToVector(pl, p); + SXSetPlanenormal(p); + mat_free(pl); + } + return ub; } + +/*--------------------------------------------------------------------------*/ +MATRIX calcTasUBFromThree(pSingleDiff self, + char *refid1, char *refid2, char *refid3, + int *err) +{ + /* + * not implemented yet + * There is also a problem: if I have three reflections, which + * defines the plane normal? This also does not make much sense anyway: + * we usually will not have a reflection out of plane: thus the three + * will be coplanar and the results may not be useful at all! + */ + return NULL; +} + /*--------------------------------------------------------------------*/ -static int calcTasZ1(pSingleDiff self, char *refid, double z1[3]){ - tasReflection r1; - MATRIX u = NULL; - - if(!getTasReflection(refid,&r1)){ - return 0; - } - u = calcTasUVectorFromAngles(r1); - if(u == NULL){ - return 0; - } else { - matrixToVector(u,z1); - mat_free(u); - } - return 1; +static int calcTasZ1(pSingleDiff self, char *refid, double z1[3]) +{ + tasReflection r1; + MATRIX u = NULL; + + if (!getTasReflection(refid, &r1)) { + return 0; + } + u = calcTasUVectorFromAngles(r1); + if (u == NULL) { + return 0; + } else { + matrixToVector(u, z1); + mat_free(u); + } + return 1; } + /*--------------------------------------------------------------------*/ -void initializeSingleTas(pSingleDiff diff){ - - if(diff->motList >= 0){ - LLDdelete(diff->motList); - } - diff->motList = LLDcreate(sizeof(MotControl)); - addMotorToList(diff->motList, (char *)SXGetMotorName(TwoTheta), .0); - addMotorToList(diff->motList, (char *)SXGetMotorName(Omega), .0); - addMotorToList(diff->motList, (char *)SXGetMotorName(Sgu), .0); - addMotorToList(diff->motList, (char *)SXGetMotorName(Sgl), .0); - - diff->calculateSettings = calculateTASSettings; - diff->settingsToList = settingsToTasList; - diff->hklFromAngles = hklFromTasAngles; - diff->hklFromAnglesGiven = hklFromTasAnglesGiven; - diff->calcUBFromTwo = calcTasUBFromTwo; - diff->calcUBFromThree = calcTasUBFromThree; - diff->calcZ1 = calcTasZ1; +void initializeSingleTas(pSingleDiff diff) +{ + + if (diff->motList >= 0) { + LLDdelete(diff->motList); + } + diff->motList = LLDcreate(sizeof(MotControl)); + addMotorToList(diff->motList, (char *) SXGetMotorName(TwoTheta), .0); + addMotorToList(diff->motList, (char *) SXGetMotorName(Omega), .0); + addMotorToList(diff->motList, (char *) SXGetMotorName(Sgu), .0); + addMotorToList(diff->motList, (char *) SXGetMotorName(Sgl), .0); + + diff->calculateSettings = calculateTASSettings; + diff->settingsToList = settingsToTasList; + diff->hklFromAngles = hklFromTasAngles; + diff->hklFromAnglesGiven = hklFromTasAnglesGiven; + diff->calcUBFromTwo = calcTasUBFromTwo; + diff->calcUBFromThree = calcTasUBFromThree; + diff->calcZ1 = calcTasZ1; } diff --git a/singletas.h b/singletas.h index b3ad0248..51ce5219 100644 --- a/singletas.h +++ b/singletas.h @@ -15,4 +15,4 @@ void initializeSingleTas(pSingleDiff diff); -#endif /*SINGLETAS_H_*/ +#endif /*SINGLETAS_H_ */ diff --git a/sinqhmtcl.c b/sinqhmtcl.c index 3ef0b129..cac4ffe7 100644 --- a/sinqhmtcl.c +++ b/sinqhmtcl.c @@ -42,534 +42,484 @@ #include "sinqhm.h" /* as you are reading this: check if the typedefs below match your machine - */ - typedef short int SQint16; /* 16 bit integer */ - typedef int SQint32; /* 32 bit integer */ + */ +typedef short int SQint16; /* 16 bit integer */ +typedef int SQint32; /* 32 bit integer */ /*--------------------------------------------------------------------------*/ - static void SINQKill(void *pData) - { - pSINQHM self; - - self = (pSINQHM)pData; - DeleteSINQHM(self); +static void SINQKill(void *pData) +{ + pSINQHM self; + + self = (pSINQHM) pData; + DeleteSINQHM(self); +} + +/*--------------------------------------------------------------------------*/ +static int DAQAction(ClientData pData, Tcl_Interp * interp, + int argc, char *argv[]) +{ + + pSINQHM self; + int iMode, iDaq, iRank, iBin, iLength, iClients, iByte, i; + FuPaResult PaRes; + void *pBuffer; + SQint16 *pPtr16; + SQint32 *pPtr32; + char *pPtr, *pVal; + char pNumber[20]; + char pIndex[20]; + char **argx; + int iRet, status, iVal; + char pBueffel[256]; + FuncTemplate BufferTemplate[] = { + {"read", 4, {FUPAINT, FUPAINT, FUPAINT, FUPATEXT}}, + {"write", 4, {FUPAINT, FUPAINT, FUPAINT, FUPATEXT}}, + {"zero", 3, {FUPAINT, FUPAINT, FUPAINT}}, + {"start", 0, {FUPATEXT}}, + {"stop", 0, {FUPATEXT}}, + {"inhibit", 0, {FUPATEXT}}, + {"continue", 0, {FUPATEXT}}, + }; + + self = (pSINQHM) pData; + assert(self); + + /* parse function args */ + argx = &argv[1]; + iRet = + EvaluateFuPa((pFuncTemplate) & BufferTemplate, 7, argc - 1, argx, + &PaRes); + if (iRet < 0) { + Tcl_AppendResult(interp, PaRes.pError, NULL); + return TCL_ERROR; } -/*--------------------------------------------------------------------------*/ - static int DAQAction(ClientData pData, Tcl_Interp *interp, - int argc, char *argv[]) - { + switch (iRet) { + case 0: /* read */ + /* get status first, in order to get info */ + status = SINQHMGetStatus(self, &iMode, &iDaq, + &iRank, &iBin, &iLength, &iClients); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + /* calculate necessary buffer size */ + iByte = iBin * PaRes.Arg[2].iVal; + pBuffer = NULL; + pBuffer = malloc(iByte); + if (!pBuffer) { + Tcl_AppendResult(interp, "Out of memory in DAQAction", NULL); + return TCL_ERROR; + } - pSINQHM self; - int iMode, iDaq, iRank, iBin, iLength, iClients, iByte, i; - FuPaResult PaRes; - void *pBuffer; - SQint16 *pPtr16; - SQint32 *pPtr32; - char *pPtr, *pVal; - char pNumber[20]; - char pIndex[20]; - char **argx; - int iRet, status, iVal; - char pBueffel[256]; - FuncTemplate BufferTemplate[] = { - {"read",4,{FUPAINT, FUPAINT, FUPAINT,FUPATEXT} }, - {"write",4,{FUPAINT, FUPAINT, FUPAINT, FUPATEXT} }, - {"zero",3,{FUPAINT,FUPAINT,FUPAINT}}, - {"start",0,{FUPATEXT}}, - {"stop",0,{FUPATEXT}}, - {"inhibit",0,{FUPATEXT}}, - {"continue",0,{FUPATEXT}}, - }; + /* read histogram's */ + status = SINQHMRead(self, PaRes.Arg[0].iVal, + PaRes.Arg[1].iVal, PaRes.Arg[2].iVal, + pBuffer, iByte); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } - self = (pSINQHM)pData; - assert(self); - - /* parse function args */ - argx = &argv[1]; - iRet = EvaluateFuPa((pFuncTemplate)&BufferTemplate,7,argc-1,argx,&PaRes); - if(iRet < 0) - { - Tcl_AppendResult(interp,PaRes.pError,NULL); - return TCL_ERROR; - } - - switch(iRet) - { - case 0: /* read */ - /* get status first, in order to get info */ - status = SINQHMGetStatus(self,&iMode, &iDaq, - &iRank,&iBin, &iLength,&iClients); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - /* calculate necessary buffer size */ - iByte = iBin * PaRes.Arg[2].iVal; - pBuffer = NULL; - pBuffer = malloc(iByte); - if(!pBuffer) - { - Tcl_AppendResult(interp,"Out of memory in DAQAction",NULL); - return TCL_ERROR; - } - - /* read histogram's */ - status = SINQHMRead(self,PaRes.Arg[0].iVal, - PaRes.Arg[1].iVal,PaRes.Arg[2].iVal, - pBuffer, iByte); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - - /* convert to list, depending on BinWidth */ - if(iBin == 1) /* char's */ - { - pPtr = (char *)pBuffer; - for(i = 0; i < PaRes.Arg[2].iVal; i++, pPtr++) - { - sprintf(pNumber,"%d",(int)*pPtr); - sprintf(pIndex,"%d",i); - Tcl_SetVar2(interp,argv[5],pIndex,pNumber,TCL_LEAVE_ERR_MSG); - } - free(pBuffer); - } - else if(iBin == 2) - { - pPtr16 = (SQint16 *)pBuffer; - for(i = 0; i < PaRes.Arg[2].iVal; i++, pPtr16++) - { - sprintf(pNumber,"%d",(int)*pPtr16); - sprintf(pIndex,"%d",i); - Tcl_SetVar2(interp,argv[5],pIndex,pNumber,TCL_LEAVE_ERR_MSG); - } - free(pBuffer); - } - else if(iBin == 4) - { - pPtr32 = (SQint32 *)pBuffer; - for(i = 0; i < PaRes.Arg[2].iVal; i++, pPtr32++) - { - sprintf(pNumber,"%d",(int)*pPtr32); - sprintf(pIndex,"%d",i); - Tcl_SetVar2(interp,argv[5],pIndex,pNumber,TCL_LEAVE_ERR_MSG); - } - free(pBuffer); - } - else - { - Tcl_AppendResult(interp,"Invalid bin width in DAQAction",NULL); - free(pBuffer); - return TCL_ERROR; - } - break; - case 1: /* write */ - /* get status first, in order to get info */ - status = SINQHMGetStatus(self,&iMode, &iDaq, - &iRank,&iBin, &iLength,&iClients); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - - /* calculate necessary buffer size */ - iByte = iBin * PaRes.Arg[2].iVal; - pBuffer = NULL; - pBuffer = malloc(iByte); - if(!pBuffer) - { - Tcl_AppendResult(interp,"Out of memory in DAQAction",NULL); - return TCL_ERROR; - } - memset(pBuffer,0,iByte); - - /* read data array into buffer, sorted for binwidth */ - if(iBin == 1) - { - pPtr = pBuffer; - for(i = 0; i < PaRes.Arg[3].iVal; i++, pPtr++) - { - sprintf(pIndex,"%d",i); - pVal = Tcl_GetVar2(interp,argv[5],pIndex,TCL_LEAVE_ERR_MSG); - if(pVal) - { - Tcl_GetInt(interp,pVal,&iVal); - *pPtr = (char )iVal; - } - } - } - else if(iBin == 2) - { - pPtr16 = pBuffer; - for(i = 0; i < PaRes.Arg[3].iVal; i++, pPtr16++) - { - sprintf(pIndex,"%d",i); - pVal = Tcl_GetVar2(interp,argv[5],pIndex,TCL_LEAVE_ERR_MSG); - if(pVal) - { - Tcl_GetInt(interp,pVal,&iVal); - *pPtr16 = iVal; - } - } - } - else if(iBin == 4) - { - pPtr32 = pBuffer; - for(i = 0; i < PaRes.Arg[2].iVal; i++, pPtr32++) - { - sprintf(pIndex,"%d",i); - pVal = Tcl_GetVar2(interp,argv[5],pIndex,TCL_LEAVE_ERR_MSG); - if(pVal) - { - Tcl_GetInt(interp,pVal,&iVal); - *pPtr32 = iVal; - } - } - } - else - { - Tcl_AppendResult(interp,"Invalid bin width in DAQAction",NULL); - free(pBuffer); - return TCL_ERROR; - } - - /* write ! */ - status = SINQHMWrite(self,PaRes.Arg[0].iVal, - PaRes.Arg[1].iVal,PaRes.Arg[2].iVal, - pBuffer); - free(pBuffer); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - case 2: /* zero */ - status = SINQHMZero(self,PaRes.Arg[0].iVal, - PaRes.Arg[1].iVal,PaRes.Arg[2].iVal); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - case 3: /* start */ - status = SINQHMStartDAQ(self); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - case 4: /* stop */ - status = SINQHMStopDAQ(self); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - case 5: /* inhibit */ - status = SINQHMInhibitDAQ(self); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - case 6: /* continue */ - status = SINQHMContinueDAQ(self); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - default: - Tcl_AppendResult(interp,"Internal error in DAQAction",NULL); - return TCL_ERROR; - } - return TCL_OK; + /* convert to list, depending on BinWidth */ + if (iBin == 1) { /* char's */ + pPtr = (char *) pBuffer; + for (i = 0; i < PaRes.Arg[2].iVal; i++, pPtr++) { + sprintf(pNumber, "%d", (int) *pPtr); + sprintf(pIndex, "%d", i); + Tcl_SetVar2(interp, argv[5], pIndex, pNumber, TCL_LEAVE_ERR_MSG); + } + free(pBuffer); + } else if (iBin == 2) { + pPtr16 = (SQint16 *) pBuffer; + for (i = 0; i < PaRes.Arg[2].iVal; i++, pPtr16++) { + sprintf(pNumber, "%d", (int) *pPtr16); + sprintf(pIndex, "%d", i); + Tcl_SetVar2(interp, argv[5], pIndex, pNumber, TCL_LEAVE_ERR_MSG); + } + free(pBuffer); + } else if (iBin == 4) { + pPtr32 = (SQint32 *) pBuffer; + for (i = 0; i < PaRes.Arg[2].iVal; i++, pPtr32++) { + sprintf(pNumber, "%d", (int) *pPtr32); + sprintf(pIndex, "%d", i); + Tcl_SetVar2(interp, argv[5], pIndex, pNumber, TCL_LEAVE_ERR_MSG); + } + free(pBuffer); + } else { + Tcl_AppendResult(interp, "Invalid bin width in DAQAction", NULL); + free(pBuffer); + return TCL_ERROR; + } + break; + case 1: /* write */ + /* get status first, in order to get info */ + status = SINQHMGetStatus(self, &iMode, &iDaq, + &iRank, &iBin, &iLength, &iClients); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + + /* calculate necessary buffer size */ + iByte = iBin * PaRes.Arg[2].iVal; + pBuffer = NULL; + pBuffer = malloc(iByte); + if (!pBuffer) { + Tcl_AppendResult(interp, "Out of memory in DAQAction", NULL); + return TCL_ERROR; + } + memset(pBuffer, 0, iByte); + + /* read data array into buffer, sorted for binwidth */ + if (iBin == 1) { + pPtr = pBuffer; + for (i = 0; i < PaRes.Arg[3].iVal; i++, pPtr++) { + sprintf(pIndex, "%d", i); + pVal = Tcl_GetVar2(interp, argv[5], pIndex, TCL_LEAVE_ERR_MSG); + if (pVal) { + Tcl_GetInt(interp, pVal, &iVal); + *pPtr = (char) iVal; + } + } + } else if (iBin == 2) { + pPtr16 = pBuffer; + for (i = 0; i < PaRes.Arg[3].iVal; i++, pPtr16++) { + sprintf(pIndex, "%d", i); + pVal = Tcl_GetVar2(interp, argv[5], pIndex, TCL_LEAVE_ERR_MSG); + if (pVal) { + Tcl_GetInt(interp, pVal, &iVal); + *pPtr16 = iVal; + } + } + } else if (iBin == 4) { + pPtr32 = pBuffer; + for (i = 0; i < PaRes.Arg[2].iVal; i++, pPtr32++) { + sprintf(pIndex, "%d", i); + pVal = Tcl_GetVar2(interp, argv[5], pIndex, TCL_LEAVE_ERR_MSG); + if (pVal) { + Tcl_GetInt(interp, pVal, &iVal); + *pPtr32 = iVal; + } + } + } else { + Tcl_AppendResult(interp, "Invalid bin width in DAQAction", NULL); + free(pBuffer); + return TCL_ERROR; + } + + /* write ! */ + status = SINQHMWrite(self, PaRes.Arg[0].iVal, + PaRes.Arg[1].iVal, PaRes.Arg[2].iVal, pBuffer); + free(pBuffer); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + case 2: /* zero */ + status = SINQHMZero(self, PaRes.Arg[0].iVal, + PaRes.Arg[1].iVal, PaRes.Arg[2].iVal); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + case 3: /* start */ + status = SINQHMStartDAQ(self); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + case 4: /* stop */ + status = SINQHMStopDAQ(self); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + case 5: /* inhibit */ + status = SINQHMInhibitDAQ(self); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + case 6: /* continue */ + status = SINQHMContinueDAQ(self); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + default: + Tcl_AppendResult(interp, "Internal error in DAQAction", NULL); + return TCL_ERROR; } -/*--------------------------------------------------------------------------*/ - static int Text2Mode(char *text) - { - char *pText[] = { - "SQHM_TRANS", - "SQHM_HM_DIG", - "SQHM_HM_PSD", - "SQHM_HM_TOF", - NULL }; - int i = 0; - while(pText[i] != NULL) - { - if(strcmp(text,pText[i]) == 0) - { - break; - } - i++; - } + return TCL_OK; +} - switch(i) - { - case 0: - return SQHM__TRANS; - break; - case 1: - return SQHM__HM_DIG; - break; - case 2: - return SQHM__HM_PSD; - break; - case 3: - return SQHM__TOF; - break; - default: - return -1; - } - return -1; - } /*--------------------------------------------------------------------------*/ - static int Text2Modifier(char *text) - { - char *pText[] = { - "SQHM_DEBUG", - "SQHM_UD", - "SQHM_CNT_OR", - "SQHM_BO_MSK", - "SQHM_BO_IGN", - "SQHM_BO_SMAX", - "SQHM_BO_CNT", - "SQHM_STROBO", - "NULL", - NULL }; - int i = 0; - while(pText[i] != NULL) - { - if(strcmp(text,pText[i]) == 0) - { - break; - } - i++; - } - - switch(i) - { - case 0: - return SQHM__DEBUG; - break; - case 1: - return SQHM__UD; - break; - case 2: - return SQHM__CNT_OR; - break; - case 3: - return SQHM__BO_MSK; - break; - case 4: - return SQHM__BO_IGN; - break; - case 5: - return SQHM__BO_SMAX; - break; - case 6: - return SQHM__BO_CNT; - break; - case 7: - return SQHM__STROBO; - break; - case 8: - return 0; - break; - default: - return -1; - } - return -1; +static int Text2Mode(char *text) +{ + char *pText[] = { + "SQHM_TRANS", + "SQHM_HM_DIG", + "SQHM_HM_PSD", + "SQHM_HM_TOF", + NULL + }; + int i = 0; + while (pText[i] != NULL) { + if (strcmp(text, pText[i]) == 0) { + break; + } + i++; } + switch (i) { + case 0: + return SQHM__TRANS; + break; + case 1: + return SQHM__HM_DIG; + break; + case 2: + return SQHM__HM_PSD; + break; + case 3: + return SQHM__TOF; + break; + default: + return -1; + } + return -1; +} + /*--------------------------------------------------------------------------*/ - static int ControlAction(ClientData pData, Tcl_Interp *interp, - int argc, char *argv[]) - { - int iRet; - int status; - char **argx; - int iMode, iModifier, iDaq, iRank, iBin, iLength, iClients; - pSINQHM self; - pSINQHM pNew = NULL; - char pBueffel[256]; - FuPaResult PaRes; - FuncTemplate BufferTemplate[] = { - {"config",5,{FUPATEXT, FUPATEXT, FUPAINT, FUPAINT, FUPAINT} }, - {"deconfig",1,{FUPAINT} }, - {"debug",1,{FUPAINT}}, - {"exit",0,{FUPATEXT}}, - {"DAQ",1,{FUPATEXT}}, - {"status",0,{FUPATEXT}}, - {"delDAQ",1,{FUPATEXT}} - }; +static int Text2Modifier(char *text) +{ + char *pText[] = { + "SQHM_DEBUG", + "SQHM_UD", + "SQHM_CNT_OR", + "SQHM_BO_MSK", + "SQHM_BO_IGN", + "SQHM_BO_SMAX", + "SQHM_BO_CNT", + "SQHM_STROBO", + "NULL", + NULL + }; + int i = 0; + while (pText[i] != NULL) { + if (strcmp(text, pText[i]) == 0) { + break; + } + i++; + } - self = (pSINQHM)pData; - assert(self); - - /* parse function args */ - argx = &argv[1]; - iRet = EvaluateFuPa((pFuncTemplate)&BufferTemplate,6,argc-1,argx,&PaRes); - if(iRet < 0) - { - Tcl_AppendResult(interp,PaRes.pError,NULL); - return TCL_ERROR; - } + switch (i) { + case 0: + return SQHM__DEBUG; + break; + case 1: + return SQHM__UD; + break; + case 2: + return SQHM__CNT_OR; + break; + case 3: + return SQHM__BO_MSK; + break; + case 4: + return SQHM__BO_IGN; + break; + case 5: + return SQHM__BO_SMAX; + break; + case 6: + return SQHM__BO_CNT; + break; + case 7: + return SQHM__STROBO; + break; + case 8: + return 0; + break; + default: + return -1; + } + return -1; +} + +/*--------------------------------------------------------------------------*/ +static int ControlAction(ClientData pData, Tcl_Interp * interp, + int argc, char *argv[]) +{ + int iRet; + int status; + char **argx; + int iMode, iModifier, iDaq, iRank, iBin, iLength, iClients; + pSINQHM self; + pSINQHM pNew = NULL; + char pBueffel[256]; + FuPaResult PaRes; + FuncTemplate BufferTemplate[] = { + {"config", 5, {FUPATEXT, FUPATEXT, FUPAINT, FUPAINT, FUPAINT}}, + {"deconfig", 1, {FUPAINT}}, + {"debug", 1, {FUPAINT}}, + {"exit", 0, {FUPATEXT}}, + {"DAQ", 1, {FUPATEXT}}, + {"status", 0, {FUPATEXT}}, + {"delDAQ", 1, {FUPATEXT}} + }; + + self = (pSINQHM) pData; + assert(self); + + /* parse function args */ + argx = &argv[1]; + iRet = + EvaluateFuPa((pFuncTemplate) & BufferTemplate, 6, argc - 1, argx, + &PaRes); + if (iRet < 0) { + Tcl_AppendResult(interp, PaRes.pError, NULL); + return TCL_ERROR; + } + + switch (iRet) { + case 0: /* config */ + iMode = Text2Mode(PaRes.Arg[0].text); + if (iMode < 0) { + Tcl_AppendResult(interp, "Invalid Mode parameter", NULL); + return TCL_ERROR; + } + iModifier = Text2Modifier(PaRes.Arg[1].text); + if (iModifier < 0) { + Tcl_AppendResult(interp, "Invalid Modifier parameter", NULL); + return TCL_ERROR; + } + iMode = iMode | iModifier; + status = SINQHMConfigure(self, iMode, + PaRes.Arg[2].iVal, PaRes.Arg[3].iVal, + PaRes.Arg[4].iVal, 0, 0); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + case 1: /* deconfig */ + status = SINQHMDeconfigure(self, PaRes.Arg[0].iVal); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + case 2: /* debug */ + status = SINQHMDebug(self, PaRes.Arg[0].iVal); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + case 3: /* exit */ + status = SINQHMKill(self); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + break; + case 4: /* DAQ */ + pNew = CopySINQHM(self); + if (!pNew) { + Tcl_AppendResult(interp, "Memory error in ControlAction", NULL); + return TCL_ERROR; + } + status = SINQHMOpenDAQ(pNew); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + DeleteSINQHM(pNew); + return TCL_ERROR; + } + + /* initialise internal data fields */ + status = SINQHMGetStatus(self, &iMode, &iDaq, + &iRank, &iBin, &iLength, &iClients); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + SINQHMSetPar(pNew, iRank, iLength, iBin); + Tcl_CreateCommand(interp, strdup(argv[2]), DAQAction, pNew, SINQKill); + break; + case 5: /* status */ + status = SINQHMGetStatus(self, &iMode, &iDaq, + &iRank, &iBin, &iLength, &iClients); + if (status < 0) { + SINQHMError2Text(status, pBueffel, 131); + Tcl_AppendResult(interp, pBueffel, NULL); + return TCL_ERROR; + } + sprintf(pBueffel, + "Mode = %d, DAQ = %d, Rank = %d, BinWidth = %d, Length = %d, NoClients = %d", + iMode, iDaq, iRank, iBin, iLength, iClients); + Tcl_AppendResult(interp, pBueffel, NULL); + break; + case 6: /* delDAQ */ + return Tcl_DeleteCommand(interp, PaRes.Arg[0].text); + default: + Tcl_AppendResult(interp, "Internal error in ControlAction", NULL); + return TCL_ERROR; + } + return TCL_OK; +} - switch(iRet) - { - case 0: /* config */ - iMode = Text2Mode(PaRes.Arg[0].text); - if(iMode < 0) - { - Tcl_AppendResult(interp,"Invalid Mode parameter",NULL); - return TCL_ERROR; - } - iModifier = Text2Modifier(PaRes.Arg[1].text); - if(iModifier < 0) - { - Tcl_AppendResult(interp,"Invalid Modifier parameter",NULL); - return TCL_ERROR; - } - iMode = iMode | iModifier; - status = SINQHMConfigure(self,iMode, - PaRes.Arg[2].iVal,PaRes.Arg[3].iVal, - PaRes.Arg[4].iVal,0,0); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - case 1: /* deconfig */ - status = SINQHMDeconfigure(self,PaRes.Arg[0].iVal); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - case 2: /* debug */ - status = SINQHMDebug(self,PaRes.Arg[0].iVal); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - case 3: /* exit */ - status = SINQHMKill(self); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - break; - case 4: /* DAQ */ - pNew = CopySINQHM(self); - if(!pNew) - { - Tcl_AppendResult(interp,"Memory error in ControlAction",NULL); - return TCL_ERROR; - } - status = SINQHMOpenDAQ(pNew); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - DeleteSINQHM(pNew); - return TCL_ERROR; - } - - /* initialise internal data fields */ - status = SINQHMGetStatus(self,&iMode, &iDaq, - &iRank,&iBin, &iLength,&iClients); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - SINQHMSetPar(pNew,iRank, iLength, iBin); - Tcl_CreateCommand(interp,strdup(argv[2]),DAQAction,pNew, - SINQKill); - break; - case 5: /* status */ - status = SINQHMGetStatus(self,&iMode, &iDaq, - &iRank,&iBin, &iLength,&iClients); - if(status < 0) - { - SINQHMError2Text(status, pBueffel,131); - Tcl_AppendResult(interp,pBueffel,NULL); - return TCL_ERROR; - } - sprintf(pBueffel, - "Mode = %d, DAQ = %d, Rank = %d, BinWidth = %d, Length = %d, NoClients = %d", - iMode, iDaq, iRank, iBin,iLength,iClients); - Tcl_AppendResult(interp,pBueffel,NULL); - break; - case 6: /* delDAQ */ - return Tcl_DeleteCommand(interp,PaRes.Arg[0].text); - default: - Tcl_AppendResult(interp,"Internal error in ControlAction",NULL); - return TCL_ERROR; - } - return TCL_OK; - } /*-------------------------------------------------------------------------*/ - int SINQHM(ClientData pData, Tcl_Interp *interp, - int argc, char *argv[]) - { - int iPort, status; - pSINQHM pNew = NULL; - - /* check arguments, first number */ - if(argc < 4) - { - Tcl_AppendResult(interp,"Insufficient number of arguments to ", - argv[0],NULL); - return TCL_ERROR; - } - - /* last argument must be port number */ - status = Tcl_GetInt(interp,argv[3],&iPort); - if(status != TCL_OK) - { - return status; - } - - /* open the HM */ - pNew = CreateSINQHM(argv[2],iPort); - if(!pNew) - { - Tcl_AppendResult(interp,"Error allocating SINQHM datastructure",NULL); - return TCL_ERROR; - } - - /* install the command */ - Tcl_CreateCommand(interp,argv[1],ControlAction,pNew,SINQKill); - return TCL_OK; - } +int SINQHM(ClientData pData, Tcl_Interp * interp, int argc, char *argv[]) +{ + int iPort, status; + pSINQHM pNew = NULL; + + /* check arguments, first number */ + if (argc < 4) { + Tcl_AppendResult(interp, "Insufficient number of arguments to ", + argv[0], NULL); + return TCL_ERROR; + } + + /* last argument must be port number */ + status = Tcl_GetInt(interp, argv[3], &iPort); + if (status != TCL_OK) { + return status; + } + + /* open the HM */ + pNew = CreateSINQHM(argv[2], iPort); + if (!pNew) { + Tcl_AppendResult(interp, "Error allocating SINQHM datastructure", + NULL); + return TCL_ERROR; + } + + /* install the command */ + Tcl_CreateCommand(interp, argv[1], ControlAction, pNew, SINQKill); + return TCL_OK; +} diff --git a/site.h b/site.h index 3d6edf37..939b4756 100644 --- a/site.h +++ b/site.h @@ -26,31 +26,24 @@ being compiled. #include #include - typedef struct { - void (*AddSiteCommands)(SicsInterp *pSics); - void (*RemoveSiteCommands)(SicsInterp *pSics); - pMotor (*CreateMotor)(SConnection *pCon, - int argc, char *argv[]); - pCounterDriver (*CreateCounterDriver)( - SConnection *pCon, - int argc, - char *argv[]); - HistDriver *(*CreateHistogramMemoryDriver)( - char *name, pStringDict pOption); - pVelSelDriv (*CreateVelocitySelector)(char *name, - char *array, Tcl_Interp *pTcl); - pCodri (*CreateControllerDriver)(SConnection *pCon, - int argc, - char *argv[]); - pEVControl (*InstallEnvironmentController)( - SicsInterp *pSics, - SConnection *pCon, - int argc, - char *argv[]); - int (*ConfigureScan)(pScanData self, - char *option); - void (*KillSite)(void *pData); -}Site, *pSite; +typedef struct { + void (*AddSiteCommands) (SicsInterp * pSics); + void (*RemoveSiteCommands) (SicsInterp * pSics); + pMotor(*CreateMotor) (SConnection * pCon, int argc, char *argv[]); + pCounterDriver(*CreateCounterDriver) (SConnection * pCon, + int argc, char *argv[]); + HistDriver *(*CreateHistogramMemoryDriver) (char *name, + pStringDict pOption); + pVelSelDriv(*CreateVelocitySelector) (char *name, char *array, + Tcl_Interp * pTcl); + pCodri(*CreateControllerDriver) (SConnection * pCon, int argc, + char *argv[]); + pEVControl(*InstallEnvironmentController) (SicsInterp * pSics, + SConnection * pCon, int argc, + char *argv[]); + int (*ConfigureScan) (pScanData self, char *option); + void (*KillSite) (void *pData); +} Site, *pSite; /*-------------------------------------------------------------------*/ pSite getSite(void); diff --git a/splitter.c b/splitter.c index 09543881..436b106c 100644 --- a/splitter.c +++ b/splitter.c @@ -14,397 +14,369 @@ #include "tcl.h" #include "splitter.h" -typedef enum _CharType {eSpace, eNum,eeText,eQuote} CharType; +typedef enum _CharType { eSpace, eNum, eeText, eQuote } CharType; /* ------------------------ local prototypes ------------------------------*/ - static TokenList *CreateToken(TokenList *pN, TokenList *P); - static CharType CheckSpecial(char *pWord); - static int isEnd(char c); - +static TokenList *CreateToken(TokenList * pN, TokenList * P); +static CharType CheckSpecial(char *pWord); +static int isEnd(char c); + /*=========================================================================*/ - static TokenList *CreateToken(TokenList *pN, TokenList *pP) - { - TokenList *pRes = NULL; - - pRes = (TokenList *) malloc(sizeof(TokenList)); - if(!pRes)return NULL; - - pRes->fVal = .0; - pRes->iVal = 0; - pRes->Type = eUndefined; - pRes->text = NULL; - pRes->pNext = pN; - if(pN) - { - pN->pPrevious = pRes; - } - pRes->pPrevious = pP; - if(pP) - { - pP->pNext = pRes; - } - return pRes; - } -/*---------------------------------------------------------------------------*/ +static TokenList *CreateToken(TokenList * pN, TokenList * pP) +{ + TokenList *pRes = NULL; - static CharType CheckSpecial(char *pWord) - { - CharType eRes = eText; - int iFlag = 0; - - if(isspace(pWord[0]))return(eSpace); - if(isdigit(pWord[0]))return(eNum); + pRes = (TokenList *) malloc(sizeof(TokenList)); + if (!pRes) + return NULL; - /* simple cases */ - if(pWord[0] == '*') return(eeText); - if(pWord[0] == '/') return(eeText); - if(pWord[0] == '\\') return(eeText); - if(pWord[0] == ']') return(eeText); - if(pWord[0] == '[') return(eeText); - if(pWord[0] == '"') return(eQuote); - - /* difficult cases, next characters will be searched for decision*/ - - if( pWord[0] == '-') iFlag = 1; - if( pWord[0] == '+') iFlag = 1; - if( pWord[0] == '.') iFlag = 1; - - if (iFlag == 1) - { - - if( isdigit(pWord[1]) ) - { - return(eNum); - } - else if( isalpha(pWord[1] )) - { - return(eeText); - } - else if (!isspace( pWord[1]) ) - { - pWord++; - return(CheckSpecial(pWord)); - } - } - - return(eeText); - } -/*--------------------------------------------------------------------------*/ - static int isEnd(char c) - { - if( (c == '\0') || (c == '\n') || (c == '\r') ) - { - return 2; - } - else if ( c== ' ') - { - return 1; - } - else - { - return 0; - } - } -/*--------------------------------------------------------------------------*/ - - TokenList *SplitText(char *pLine) - { - TokenList *pList = NULL; - TokenList *pCurrent; - char pBueffel[256]; - char *pChar; - CharType eWhat; - int i, n; - - if(!pLine)return NULL; - - pChar = pLine; - - /* loop through line */ - while(isEnd(*pChar) != 2) - { - - eWhat = CheckSpecial(pChar); - - /* skip spaces */ - if (eWhat == eSpace) - { - pChar++; - continue; - } - - /* no space, read word in first place */ - if(eWhat == eQuote) - { - i = 0; - pChar++; - while( (isEnd(*pChar) != 2) && (CheckSpecial(pChar) != eQuote) && i < 250) - { - if (*pChar == '\\') { - pBueffel[i] = Tcl_Backslash(pChar, &n); - pChar += n; - } else { - pBueffel[i] = *pChar; - pChar++; - } - i++; - } - pBueffel[i] = '\0'; - pChar++; - eWhat = eeText; - } - else - { - i = 0; - while(!isEnd(*pChar)) - { - pBueffel[i] = *pChar; - i++; - pChar++; - } - pBueffel[i] = '\0'; - } - if(pList == NULL) - { - pList = CreateToken(NULL,NULL); - pCurrent = pList; - } - else - { - pCurrent = CreateToken(NULL,pCurrent); - } - if(!pCurrent) return NULL; - - /* copyy text always */ - pCurrent->text = strdup(pBueffel); - if(eWhat == eeText) - { - pCurrent->Type = eText; - } - else if(eWhat == eNum) - { - /* float ? */ - if(strchr(pBueffel,'.')== NULL) - { - pCurrent->Type = eInt; - sscanf(pBueffel,"%ld",&(pCurrent->iVal)); - } - else - { - pCurrent->Type = eFloat; - sscanf(pBueffel,"%f",&(pCurrent->fVal)); - } - } -/* pChar++;*/ if(isEnd(*pChar) == 2)break; - } /* eof big while */ - return pList; - - } -/*--------------------------------------------------------------------------*/ - void DeleteTokenList(TokenList *pToken) - { - TokenList *pCurrent; - TokenList *pTemp; - - pCurrent = pToken; - while(pCurrent != NULL) - { - pTemp = pCurrent->pNext; - if(pCurrent->text) - { - free(pCurrent->text); - } - free(pCurrent); - pCurrent = pTemp; - } - } -/*--------------------------------------------------------------------------*/ - TokenList *SplitArguments(int argc, char *argv[]) - { - int i, ii; - TokenList *pList = NULL; - TokenList *pCurrent; - CharType eWhat; - - /* loop through arguments */ - for( i = 0; i < argc; i++) - { - /* figure out what we have */ - for(ii = 0; ii < strlen(argv[i]); ii++) - { - eWhat = CheckSpecial(argv[i]); - - /* skip whitespace */ - if(eWhat != eSpace) break; - } - /* Create Token */ - if(pList == NULL) - { - pList = CreateToken(NULL, pList); - pCurrent = pList; - } - else - { - pCurrent = CreateToken(NULL,pCurrent); - } - if(!pCurrent) - return NULL; - - /* copy text always */ - pCurrent->text = strdup(argv[i]); - - /* numbers */ - if(eWhat == eNum) - { - /* float ? */ - if(strchr(argv[i],'.')== NULL) - { - pCurrent->Type = eInt; -/* sscanf(argv[i],"%d",&(pCurrent->iVal)); -*/ pCurrent->iVal = atoi(argv[i]); - } - else - { - pCurrent->Type = eFloat; - sscanf(argv[i],"%f",&(pCurrent->fVal)); - } - } - else - { /* all else is text */ - pCurrent->Type = eText; - } - } - return pList; - } -/*--------------------------------------------------------------------------*/ - int Text2Arg(char *pLine, int *argc, char **argv[]) - { - TokenList *pList = NULL; - TokenList *pCurrent = NULL; - char **margv = NULL; - int margc = 0; - int i = 0; - - /* split to a TokenList */ - pList = SplitText(pLine); - if(!pList) - { - return 0; - } - - /* figure out how many args */ - pCurrent = pList; - while(pCurrent) - { - margc++; - pCurrent = pCurrent->pNext; - } - - /* allocate memory */ - margv = (char **)malloc((margc + 2) * sizeof(char *)); - if(!margv) - { - DeleteTokenList(pList); - return 0; - } - - /* copy to argc, argv */ - *argc = margc; - pCurrent = pList; - i = 0; - while(pCurrent) - { - margv[i] = strdup(pCurrent->text); - i++; - pCurrent = pCurrent->pNext; - } - - /* done, clean up etc */ - margv[i] = NULL; - *argv = margv; - DeleteTokenList(pList); - return 1; - - } -/*---------------------------------------------------------------------------*/ - int Arg2Text(int argc, char *argv[], char *buf, int iBufLen) - { - int i, iBufCount = 0; - - strcpy(buf,"\0"); - if(argc < 1) - { - return 1; - } - if(strlen(argv[0]) < iBufLen) - { - strcpy(buf, argv[0]); - iBufCount += strlen(argv[0]); - } - else - { - return 0; - } - - for(i = 1; i < argc; i++) - { - iBufCount += strlen(argv[i]) + 1; - if(iBufCount >= iBufLen) - { - return 0; - } - strcat(buf," "); - strcat(buf,argv[i]); - } - return 1; + pRes->fVal = .0; + pRes->iVal = 0; + pRes->Type = eUndefined; + pRes->text = NULL; + pRes->pNext = pN; + if (pN) { + pN->pPrevious = pRes; } + pRes->pPrevious = pP; + if (pP) { + pP->pNext = pRes; + } + return pRes; +} + +/*---------------------------------------------------------------------------*/ + +static CharType CheckSpecial(char *pWord) +{ + CharType eRes = eText; + int iFlag = 0; + + if (isspace(pWord[0])) + return (eSpace); + if (isdigit(pWord[0])) + return (eNum); + + /* simple cases */ + if (pWord[0] == '*') + return (eeText); + if (pWord[0] == '/') + return (eeText); + if (pWord[0] == '\\') + return (eeText); + if (pWord[0] == ']') + return (eeText); + if (pWord[0] == '[') + return (eeText); + if (pWord[0] == '"') + return (eQuote); + + /* difficult cases, next characters will be searched for decision */ + + if (pWord[0] == '-') + iFlag = 1; + if (pWord[0] == '+') + iFlag = 1; + if (pWord[0] == '.') + iFlag = 1; + + if (iFlag == 1) { + + if (isdigit(pWord[1])) { + return (eNum); + } else if (isalpha(pWord[1])) { + return (eeText); + } else if (!isspace(pWord[1])) { + pWord++; + return (CheckSpecial(pWord)); + } + } + + return (eeText); +} + /*--------------------------------------------------------------------------*/ - int GetShellLine(FILE *fd, char *Buffer, int iBufLen) - { - char *pChar = NULL; - - while(fgets(Buffer,iBufLen-1,fd) != NULL) - { - if(Buffer[0] != '#') - { - return 1; - } - } - return EOF; - } -/*---------------------------------------------------------------------*/ - int isNumeric(char *pText) - { - int i, ii, iGood; - static char pNum[13] = {"1234567890.+-"}; - - for(i = 0; i < strlen(pText); i++) - { - for(ii = 0; ii < 13; ii++) - { - iGood = 0; - if(pText[i] == pNum[ii]) - { - iGood = 1; - break; - } - } - if(!iGood) - { - return 0; - } - } +static int isEnd(char c) +{ + if ((c == '\0') || (c == '\n') || (c == '\r')) { + return 2; + } else if (c == ' ') { return 1; - } + } else { + return 0; + } +} + /*--------------------------------------------------------------------------*/ -char *Arg2Tcl0(int argc, char *argv[], char *buffer, int buffersize, char *prepend) { + +TokenList *SplitText(char *pLine) +{ + TokenList *pList = NULL; + TokenList *pCurrent; + char pBueffel[256]; + char *pChar; + CharType eWhat; + int i, n; + + if (!pLine) + return NULL; + + pChar = pLine; + + /* loop through line */ + while (isEnd(*pChar) != 2) { + + eWhat = CheckSpecial(pChar); + + /* skip spaces */ + if (eWhat == eSpace) { + pChar++; + continue; + } + + /* no space, read word in first place */ + if (eWhat == eQuote) { + i = 0; + pChar++; + while ((isEnd(*pChar) != 2) && (CheckSpecial(pChar) != eQuote) + && i < 250) { + if (*pChar == '\\') { + pBueffel[i] = Tcl_Backslash(pChar, &n); + pChar += n; + } else { + pBueffel[i] = *pChar; + pChar++; + } + i++; + } + pBueffel[i] = '\0'; + pChar++; + eWhat = eeText; + } else { + i = 0; + while (!isEnd(*pChar)) { + pBueffel[i] = *pChar; + i++; + pChar++; + } + pBueffel[i] = '\0'; + } + if (pList == NULL) { + pList = CreateToken(NULL, NULL); + pCurrent = pList; + } else { + pCurrent = CreateToken(NULL, pCurrent); + } + if (!pCurrent) + return NULL; + + /* copyy text always */ + pCurrent->text = strdup(pBueffel); + if (eWhat == eeText) { + pCurrent->Type = eText; + } else if (eWhat == eNum) { + /* float ? */ + if (strchr(pBueffel, '.') == NULL) { + pCurrent->Type = eInt; + sscanf(pBueffel, "%ld", &(pCurrent->iVal)); + } else { + pCurrent->Type = eFloat; + sscanf(pBueffel, "%f", &(pCurrent->fVal)); + } + } +/* pChar++;*/ + if (isEnd(*pChar) == 2) + break; + } /* eof big while */ + return pList; + +} + +/*--------------------------------------------------------------------------*/ +void DeleteTokenList(TokenList * pToken) +{ + TokenList *pCurrent; + TokenList *pTemp; + + pCurrent = pToken; + while (pCurrent != NULL) { + pTemp = pCurrent->pNext; + if (pCurrent->text) { + free(pCurrent->text); + } + free(pCurrent); + pCurrent = pTemp; + } +} + +/*--------------------------------------------------------------------------*/ +TokenList *SplitArguments(int argc, char *argv[]) +{ + int i, ii; + TokenList *pList = NULL; + TokenList *pCurrent; + CharType eWhat; + + /* loop through arguments */ + for (i = 0; i < argc; i++) { + /* figure out what we have */ + for (ii = 0; ii < strlen(argv[i]); ii++) { + eWhat = CheckSpecial(argv[i]); + + /* skip whitespace */ + if (eWhat != eSpace) + break; + } + /* Create Token */ + if (pList == NULL) { + pList = CreateToken(NULL, pList); + pCurrent = pList; + } else { + pCurrent = CreateToken(NULL, pCurrent); + } + if (!pCurrent) + return NULL; + + /* copy text always */ + pCurrent->text = strdup(argv[i]); + + /* numbers */ + if (eWhat == eNum) { + /* float ? */ + if (strchr(argv[i], '.') == NULL) { + pCurrent->Type = eInt; +/* sscanf(argv[i],"%d",&(pCurrent->iVal)); +*/ pCurrent->iVal = atoi(argv[i]); + } else { + pCurrent->Type = eFloat; + sscanf(argv[i], "%f", &(pCurrent->fVal)); + } + } else { /* all else is text */ + pCurrent->Type = eText; + } + } + return pList; +} + +/*--------------------------------------------------------------------------*/ +int Text2Arg(char *pLine, int *argc, char **argv[]) +{ + TokenList *pList = NULL; + TokenList *pCurrent = NULL; + char **margv = NULL; + int margc = 0; + int i = 0; + + /* split to a TokenList */ + pList = SplitText(pLine); + if (!pList) { + return 0; + } + + /* figure out how many args */ + pCurrent = pList; + while (pCurrent) { + margc++; + pCurrent = pCurrent->pNext; + } + + /* allocate memory */ + margv = (char **) malloc((margc + 2) * sizeof(char *)); + if (!margv) { + DeleteTokenList(pList); + return 0; + } + + /* copy to argc, argv */ + *argc = margc; + pCurrent = pList; + i = 0; + while (pCurrent) { + margv[i] = strdup(pCurrent->text); + i++; + pCurrent = pCurrent->pNext; + } + + /* done, clean up etc */ + margv[i] = NULL; + *argv = margv; + DeleteTokenList(pList); + return 1; + +} + +/*---------------------------------------------------------------------------*/ +int Arg2Text(int argc, char *argv[], char *buf, int iBufLen) +{ + int i, iBufCount = 0; + + strcpy(buf, "\0"); + if (argc < 1) { + return 1; + } + if (strlen(argv[0]) < iBufLen) { + strcpy(buf, argv[0]); + iBufCount += strlen(argv[0]); + } else { + return 0; + } + + for (i = 1; i < argc; i++) { + iBufCount += strlen(argv[i]) + 1; + if (iBufCount >= iBufLen) { + return 0; + } + strcat(buf, " "); + strcat(buf, argv[i]); + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int GetShellLine(FILE * fd, char *Buffer, int iBufLen) +{ + char *pChar = NULL; + + while (fgets(Buffer, iBufLen - 1, fd) != NULL) { + if (Buffer[0] != '#') { + return 1; + } + } + return EOF; +} + +/*---------------------------------------------------------------------*/ +int isNumeric(char *pText) +{ + int i, ii, iGood; + static char pNum[13] = { "1234567890.+-" }; + + for (i = 0; i < strlen(pText); i++) { + for (ii = 0; ii < 13; ii++) { + iGood = 0; + if (pText[i] == pNum[ii]) { + iGood = 1; + break; + } + } + if (!iGood) { + return 0; + } + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +char *Arg2Tcl0(int argc, char *argv[], char *buffer, int buffersize, + char *prepend) +{ int i, l, firstArgToQuote, quote, prependlen; char ch; char *res, *arg; - + if (prepend) { prependlen = strlen(prepend); l = prependlen + 1; @@ -414,39 +386,49 @@ char *Arg2Tcl0(int argc, char *argv[], char *buffer, int buffersize, char *prepe } firstArgToQuote = argc; quote = 0; - for (i=0; i buffersize) { - buffer = calloc(l,1); - if (buffer == NULL) return NULL; + buffer = calloc(l, 1); + if (buffer == NULL) + return NULL; } res = buffer; if (prepend) { @@ -454,46 +436,67 @@ char *Arg2Tcl0(int argc, char *argv[], char *buffer, int buffersize, char *prepe res += prependlen; *res++ = ' '; } - for (i=0; i= firstArgToQuote) *res++ = '"'; + for (i = 0; i < argc; i++) { + if (i >= firstArgToQuote) + *res++ = '"'; arg = argv[i]; ch = *arg++; while (ch != '\0') { switch (ch) { - case '"': *res++ = '\\'; *res++ = '"'; break; - case '\\': *res++ = '\\'; *res++ = '\\'; break; - case '\r': *res++ = '\\'; *res++ = 'r'; break; - case '\n': *res++ = '\\'; *res++ = 'n'; break; - default: *res++ = ch; break; + case '"': + *res++ = '\\'; + *res++ = '"'; + break; + case '\\': + *res++ = '\\'; + *res++ = '\\'; + break; + case '\r': + *res++ = '\\'; + *res++ = 'r'; + break; + case '\n': + *res++ = '\\'; + *res++ = 'n'; + break; + default: + *res++ = ch; + break; } ch = *arg++; } - if (i >= firstArgToQuote) *res++ = '"'; + if (i >= firstArgToQuote) + *res++ = '"'; *res++ = ' '; } - if (res > buffer) res--; /* remove trailing space */ - *res='\0'; + if (res > buffer) + res--; /* remove trailing space */ + *res = '\0'; return buffer; } + /*--------------------------------------------------------------------------*/ -char *Arg2Tcl(int argc, char *argv[], char *buffer, int buffersize) { +char *Arg2Tcl(int argc, char *argv[], char *buffer, int buffersize) +{ return Arg2Tcl0(argc, argv, buffer, buffersize, NULL); } + /*----------------------------------------------------------------------------*/ -char *sicsNextNumber(char *pStart, char pNumber[80]){ +char *sicsNextNumber(char *pStart, char pNumber[80]) +{ int charCount = 0; pNumber[0] = '\0'; /* advance to first digit */ - while(isspace(*pStart) && *pStart != '\0'){ + while (isspace(*pStart) && *pStart != '\0') { pStart++; } - if(*pStart == '\0'){ + if (*pStart == '\0') { return NULL; } /* copy */ - while(!isspace(*pStart) && *pStart != '\0' && charCount < 78){ + while (!isspace(*pStart) && *pStart != '\0' && charCount < 78) { pNumber[charCount] = *pStart; pStart++; charCount++; @@ -501,43 +504,34 @@ char *sicsNextNumber(char *pStart, char pNumber[80]){ pNumber[charCount] = '\0'; return pStart; } - + /*============================================================================ Testprogram, can be activated by defining MAIN */ #ifdef MAIN - int main(int argc, char *argv[]) - { - TokenList *pList = NULL; - TokenList *pCurrent; - - pList = SplitText("Hallo 22 mal 0.8 Furz"); - pCurrent = pList; - while(pCurrent) - { - if(pCurrent->Type == eText) - { - printf("TextToken = %s\n",pCurrent->text); - } - else if(pCurrent->Type == eFloat) - { - printf("FloatToken = %f\n",pCurrent->fVal); - } - else if(pCurrent->Type == eInt) - { - printf("IntToken = %d\n",pCurrent->iVal); - } - else - { - puts("ERRRRRRRRRROOOOOOOOOOOORRRRRRR!!!!!!!!"); - } - pCurrent = pCurrent->pNext; - - } - DeleteTokenList(pList); - - } +int main(int argc, char *argv[]) +{ + TokenList *pList = NULL; + TokenList *pCurrent; + + pList = SplitText("Hallo 22 mal 0.8 Furz"); + pCurrent = pList; + while (pCurrent) { + if (pCurrent->Type == eText) { + printf("TextToken = %s\n", pCurrent->text); + } else if (pCurrent->Type == eFloat) { + printf("FloatToken = %f\n", pCurrent->fVal); + } else if (pCurrent->Type == eInt) { + printf("IntToken = %d\n", pCurrent->iVal); + } else { + puts("ERRRRRRRRRROOOOOOOOOOOORRRRRRR!!!!!!!!"); + } + pCurrent = pCurrent->pNext; + + } + DeleteTokenList(pList); + +} #endif - diff --git a/splitter.h b/splitter.h index 84849d38..d181a3a4 100644 --- a/splitter.h +++ b/splitter.h @@ -11,69 +11,69 @@ #ifndef MKSPLITTER #define MKSPLITTER - -typedef enum {eText, eInt, eFloat, eUndefined } eType; + +typedef enum { eText, eInt, eFloat, eUndefined } eType; typedef struct _TokenEntry { - eType Type; - char *text; - long iVal; - float fVal; - struct _TokenEntry *pNext; - struct _TokenEntry *pPrevious; - } TokenList; - + eType Type; + char *text; + long iVal; + float fVal; + struct _TokenEntry *pNext; + struct _TokenEntry *pPrevious; +} TokenList; + /* --------------------- exported functions ------------------------------*/ - TokenList *SplitText(char *pLine); - /*! - Splits a line of text into a list of tokens as defined above. - Any item in the line which is separated from others by spaces - is considered a token. The type of the token will be determined - as well. Possible types recognized are: int, float and text. - !*/ - - TokenList *SplitArguments(int argc, char *argv[]); +TokenList *SplitText(char *pLine); /*! - Very much like SplitText, but uses an argc, argv[] pair as input. - !*/ - - void DeleteTokenList(TokenList *pList); - /*! - Deletes a TokenList as returned by SplitText or - SplitArguments. Nver forget to call this once you are done - with the token list. - !*/ - - int Text2Arg(char *pLine, int *argc, char **argv[]); + Splits a line of text into a list of tokens as defined above. + Any item in the line which is separated from others by spaces + is considered a token. The type of the token will be determined + as well. Possible types recognized are: int, float and text. + ! */ + +TokenList *SplitArguments(int argc, char *argv[]); + /*! + Very much like SplitText, but uses an argc, argv[] pair as input. + ! */ + +void DeleteTokenList(TokenList * pList); + /*! + Deletes a TokenList as returned by SplitText or + SplitArguments. Nver forget to call this once you are done + with the token list. + ! */ + +int Text2Arg(char *pLine, int *argc, char **argv[]); /*! Text2Arg converts a line of text given in pLine to an argc, argv[] pair. Note that the caller is responsible for freeing the memory occupied by argv[]. This implies, that Text2Arg allocates the necessary space for the argv[] array. - !*/ + ! */ - int Arg2Text(int argc, char *argv[], char *buf, int iBuflen); +int Arg2Text(int argc, char *argv[], char *buf, int iBuflen); /*! Arg2Text converts an argc, argv[] pair into a line of text. The result will be stored in buf, allocated by the caller. The parameter iBufLen specifies the length of buf, in order to prevent memory overwrite. Returns 1 on success, 0 on failure. - !*/ - - int GetShellLine(FILE *fd, char *Buffer, int iBufLen); + ! */ + +int GetShellLine(FILE * fd, char *Buffer, int iBufLen); /*! GetShellLine reads the next line from the file fd, which does not start with the comment character "#". Returns 1 for success, or EOF when the end of file has been reached. - !*/ - int isNumeric(char *pText); + ! */ +int isNumeric(char *pText); /*! isNumeric test if pText is a number - !*/ - char *Arg2Tcl(int argc, char *argv[], char *buffer, int buffersize); + ! */ +char *Arg2Tcl(int argc, char *argv[], char *buffer, int buffersize); /*! Arg2Tcl converts an argc, argv[] pair into a line of text. Args are quoted if needed, in order to be interpreted as @@ -83,20 +83,21 @@ typedef struct _TokenEntry { If no memory is available or any element of argv is NULL, NULL is returned. The result has to be freed by the caller after use be something like: - - if (result != NULL && result != buffer) free(result); - - !*/ - char *Arg2Tcl0(int argc, char *argv[], char *buffer, int buffersize, char *prepend); + + if (result != NULL && result != buffer) free(result); + + ! */ +char *Arg2Tcl0(int argc, char *argv[], char *buffer, int buffersize, + char *prepend); /*! This function is added for convenience, and acts similar to Arg2Tcl. If prepend is not NULL, its contents appear untreated before the args. A space is used as separator. - !*/ - char *sicsNextNumber(char *pStart, char pNumber[80]); + ! */ +char *sicsNextNumber(char *pStart, char pNumber[80]); /*! - This function reads the next number from the string in pStart. - The number is put into pNumber, a pointer to the string after - the number is returned or NULL whne the string is exhausted. - !*/ -#endif + This function reads the next number from the string in pStart. + The number is put into pNumber, a pointer to the string after + the number is returned or NULL whne the string is exhausted. + ! */ +#endif diff --git a/statemon.c b/statemon.c index db5f4c1c..8a7a5364 100644 --- a/statemon.c +++ b/statemon.c @@ -8,7 +8,7 @@ * copyright: see file COPYRIGHT * * Mark Koennecke, January 2007 - */ + */ #include #include "exeman.h" #include "scan.h" @@ -18,332 +18,352 @@ #include "sicshipadaba.h" /*==========================================================================*/ typedef struct __STATEMON { - pObjectDescriptor pDes; - pICallBack pCall; -}StateMon; + pObjectDescriptor pDes; + pICallBack pCall; +} StateMon; /*============================ Callbacks =================================*/ - static int DevexecCallback(int iEvent, void *text, void *pData){ - char pDevice[132]; - int eventCode; - pStateMon self = (pStateMon)pData; - - memset(pDevice,0,132); - if(iEvent == DRIVSTAT){ - stptok(text,pDevice,131," "); - if(strstr(text,"started") != NULL){ - eventCode = STSTART; - } else if(strstr(text,"finished") != NULL) { - eventCode = STEND; - } else { - printf("Unrecognized event text from devexec in statemon.c: %s\n", - (char *)text); - return 0; - } - if(self != NULL){ - InvokeCallBack(self->pCall,eventCode,pDevice); - } - } - return 1; - } -/*---------------------------------------------------------------------------*/ -static int StateMonScanInterest(int iEvent, void *pEventData, void *pUser){ - pScanData pScan = NULL; - pStateMon self = (pStateMon)pUser; - - pScan = (pScanData)pEventData; - - if(pScan == NULL || self == NULL){ - printf("Bad StateMonScanInterst in statemon\n"); - return 0; - } - - if(iEvent == SCANSTART){ - InvokeCallBack(self->pCall,STSTART,pScan->objectName); - return 1; - }else if(iEvent == SCANEND){ - InvokeCallBack(self->pCall,STEND,pScan->objectName); - return 1; - } - return 1; +static int DevexecCallback(int iEvent, void *text, void *pData) +{ + char pDevice[132]; + int eventCode; + pStateMon self = (pStateMon) pData; + + memset(pDevice, 0, 132); + if (iEvent == DRIVSTAT) { + stptok(text, pDevice, 131, " "); + if (strstr(text, "started") != NULL) { + eventCode = STSTART; + } else if (strstr(text, "finished") != NULL) { + eventCode = STEND; + } else { + printf("Unrecognized event text from devexec in statemon.c: %s\n", + (char *) text); + return 0; + } + if (self != NULL) { + InvokeCallBack(self->pCall, eventCode, pDevice); + } + } + return 1; } -/*--------------------------------------------------------------------------*/ -static int ExeCallback(int iEvent, void *pEvent, void *pUser){ - pStateMon self = (pStateMon)pUser; - char *name = (char *)pEvent; - char pBueffel[131]; - - if(self == NULL || name == NULL){ - printf("Bad ExeCallback in statemon\n"); - return 0; + +/*---------------------------------------------------------------------------*/ +static int StateMonScanInterest(int iEvent, void *pEventData, void *pUser) +{ + pScanData pScan = NULL; + pStateMon self = (pStateMon) pUser; + + pScan = (pScanData) pEventData; + + if (pScan == NULL || self == NULL) { + printf("Bad StateMonScanInterst in statemon\n"); + return 0; } - if(iEvent == BATCHSTART){ - snprintf(pBueffel,131,"exe %s",name); - InvokeCallBack(self->pCall,STSTART,pBueffel); + if (iEvent == SCANSTART) { + InvokeCallBack(self->pCall, STSTART, pScan->objectName); + return 1; + } else if (iEvent == SCANEND) { + InvokeCallBack(self->pCall, STEND, pScan->objectName); return 1; } - if(iEvent == BATCHEND){ - snprintf(pBueffel,131,"exe %s",name); - InvokeCallBack(self->pCall,STEND,pBueffel); + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int ExeCallback(int iEvent, void *pEvent, void *pUser) +{ + pStateMon self = (pStateMon) pUser; + char *name = (char *) pEvent; + char pBueffel[131]; + + if (self == NULL || name == NULL) { + printf("Bad ExeCallback in statemon\n"); + return 0; + } + + if (iEvent == BATCHSTART) { + snprintf(pBueffel, 131, "exe %s", name); + InvokeCallBack(self->pCall, STSTART, pBueffel); + return 1; + } + if (iEvent == BATCHEND) { + snprintf(pBueffel, 131, "exe %s", name); + InvokeCallBack(self->pCall, STEND, pBueffel); return 1; } return 0; } + /*=============== user callbacks ============================================*/ -static int StateInterest(int iEvent, void *pEvent, void *pUser){ - SConnection *pCon = (SConnection *)pUser; - char *device = (char *)pEvent; - char buffer[256]; - - if(pCon == NULL || !SCisConnected(pCon)){ - return -1; - } +static int StateInterest(int iEvent, void *pEvent, void *pUser) +{ + SConnection *pCon = (SConnection *) pUser; + char *device = (char *) pEvent; + char buffer[256]; - if(pCon == NULL || device == NULL){ - printf("Bad StateInterest in statemon\n"); - return 0; - } - if(iEvent == STSTART){ - snprintf(buffer,255,"STARTED = %s", device); - SCWrite(pCon,buffer,eWarning); - } - if(iEvent == STEND){ - snprintf(buffer,255,"FINISH = %s", device); - SCWrite(pCon,buffer,eWarning); - } - return 1; -} -/*--------------------------------------------------------------------------*/ -static pHdb recurseInterestNode(pHdb current, char *pDevice){ - char pSicsdev[131], pAlias[132]; - pHdb result = NULL; - char *alias = NULL, *pPtr = NULL; - - memset(pSicsdev,0,132); - memset(pAlias,0,132); - if(current != NULL){ - if(GetHdbProperty(current,"sicsdev",pSicsdev,131) != 0){ - strtolower(pSicsdev); - if(strcmp(pSicsdev,pDevice) == 0){ - return current; - } - /* - * try to look for aliases, too - */ - alias = FindAliases(pServ->pSics,pSicsdev); - pPtr = alias; - if(pPtr != NULL){ - while((pPtr = stptok(pPtr,pAlias,131,",")) != NULL){ - if(strcmp(pAlias,pDevice) == 0){ - return current; - } - } - if(alias != NULL){ - free(alias); - } - } - } - current = current->child; - while(current != NULL){ - result = recurseInterestNode(current, pDevice); - if(result != NULL){ - return result; - } - current = current->next; - } - } - return NULL; -} -/*--------------------------------------------------------------------------*/ -static pHdb locateInterestNode(char *device){ - char pDevice[132], pSicsdev[132]; - pHdb current = NULL, result = NULL; - - memset(pDevice,0,132); - memset(pSicsdev,0,132); - - /* - * this is to strip off exes batch file name - */ - stptok(device,pDevice,131," "); - strtolower(pDevice); - - current = GetHipadabaRoot(); - return recurseInterestNode(current,pDevice); -} -/*--------------------------------------------------------------------------*/ -static int StateHdbInterest(int iEvent, void *pEvent, void *pUser){ - SConnection *pCon = (SConnection *)pUser; - char *device = (char *)pEvent, *path = NULL; - char buffer[1024]; - pHdb node = NULL; - - if(pCon == NULL || !SCisConnected(pCon)){ - return -1; - } + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } - if(device == NULL){ - printf("Bad StateHdbInterest in statemon\n"); - return 0; - } - node = locateInterestNode(device); - if(node != NULL){ - path = GetHipadabaPath(node); - if(iEvent == STSTART){ - snprintf(buffer,1024,"%s STARTED", path); - SCWrite(pCon,buffer,eWarning); - } - if(iEvent == STEND){ - snprintf(buffer,1024,"%s FINISH", path); - SCWrite(pCon,buffer,eWarning); - } - if(path != NULL){ - free(path); - } - } - return 1; -} -/*====================== interpreter interface ==============================*/ -static void killStateMon(void *pData){ - pStateMon self = NULL; - - self = (pStateMon)pData; - if(self != NULL){ - if(self->pDes != NULL){ - DeleteDescriptor(self->pDes); - } - if(self->pCall != NULL){ - DeleteCallBackInterface(self->pCall); - } - free(self); - } + if (pCon == NULL || device == NULL) { + printf("Bad StateInterest in statemon\n"); + return 0; + } + if (iEvent == STSTART) { + snprintf(buffer, 255, "STARTED = %s", device); + SCWrite(pCon, buffer, eWarning); + } + if (iEvent == STEND) { + snprintf(buffer, 255, "FINISH = %s", device); + SCWrite(pCon, buffer, eWarning); + } + return 1; } -/*---------------------------------------------------------------------------*/ -int StateMonFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pStateMon pNew = NULL; - commandContext cc; - pICallBack target = NULL; - void *pPtr = NULL, *exe = NULL, *pDevexec = NULL; - - exe = FindCommandData(pSics,"exe", "ExeManager"); - pDevexec = FindCommandData(pSics,"stopexe","DeviceExecutor"); - if(exe == NULL || pDevexec == NULL){ - SCWrite(pCon, - "ERROR: both the device executor and the batch file module must be installed before initialising statemon", - eError); - return 0; - } - - /* - * generate data structures - */ - strcpy(cc.deviceID,"statemon"); - cc.transID = -120; - pNew = (pStateMon)malloc(sizeof(StateMon)); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating StateMon",eError); - return 0; - } - memset(pNew,0,sizeof(StateMon)); - pNew->pDes = CreateDescriptor("statemon"); - pNew->pCall = CreateCallBackInterface(); - if(pNew->pDes == NULL || pNew->pCall == NULL){ - SCWrite(pCon,"ERROR: out of memory creating StateMon",eError); - return 0; - } - /* - * register callbacks - */ - target = GetCallbackInterface(pDevexec); - assert(target != NULL); - RegisterCallback(target,DRIVSTAT,DevexecCallback,pNew,NULL); - target = GetCallbackInterface(exe); - assert(target != NULL); - RegisterCallback(target,BATCHSTART,ExeCallback,pNew,NULL); - RegisterCallback(target,BATCHEND,ExeCallback,pNew,NULL); - - if(argc > 1) { - pPtr = FindCommandData(pSics,argv[1],"ScanObject"); - if(pPtr == NULL){ - SCWrite(pCon,"ERROR: failked to locate scan object",eError); - } else { - target = GetCallbackInterface(pPtr); - assert(target != NULL); - RegisterCallback(target,SCANSTART,StateMonScanInterest,pNew,NULL); - RegisterCallback(target,SCANEND,StateMonScanInterest,pNew,NULL); - } - } - AddCommand(pSics,"statemon",StateMonAction,killStateMon,pNew); - return 1; -} -/*---------------------------------------------------------------------------*/ -int StateMonAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - long lID; - int i; - pStateMon self = NULL; - SConnection *callCon = NULL; - - self = (pStateMon)pData; - assert(self != NULL); - - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to statemon",eError); - return 0; - } - strtolower(argv[1]); - if(strcmp(argv[1],"interest") == 0){ - callCon = SCCopyConnection(pCon); - if(callCon == NULL){ - SCWrite(pCon,"ERROR: out of memory registering interest",eError); - return 0; - } - lID = RegisterCallback(self->pCall, STSTART, StateInterest, - callCon, SCDeleteConnection); - SCRegister(pCon,pSics, self->pCall,lID); - lID = RegisterCallback(self->pCall, STEND, StateInterest, - callCon, NULL); - SCRegister(pCon,pSics, self->pCall,lID); - SCSendOK(pCon); - return 1; - } else if(strcmp(argv[1],"uninterest") == 0) { - for(i = 0; i < 2; i++){ - lID = SCgetCallbackID(pCon,self->pCall); - if(lID >= 0){ - RemoveCallback(self->pCall,lID); + +/*--------------------------------------------------------------------------*/ +static pHdb recurseInterestNode(pHdb current, char *pDevice) +{ + char pSicsdev[131], pAlias[132]; + pHdb result = NULL; + char *alias = NULL, *pPtr = NULL; + + memset(pSicsdev, 0, 132); + memset(pAlias, 0, 132); + if (current != NULL) { + if (GetHdbProperty(current, "sicsdev", pSicsdev, 131) != 0) { + strtolower(pSicsdev); + if (strcmp(pSicsdev, pDevice) == 0) { + return current; + } + /* + * try to look for aliases, too + */ + alias = FindAliases(pServ->pSics, pSicsdev); + pPtr = alias; + if (pPtr != NULL) { + while ((pPtr = stptok(pPtr, pAlias, 131, ",")) != NULL) { + if (strcmp(pAlias, pDevice) == 0) { + return current; } - } - SCSendOK(pCon); - return 1; - } else if(strcmp(argv[1],"hdbinterest") == 0){ - callCon = SCCopyConnection(pCon); - if(callCon == NULL){ - SCWrite(pCon,"ERROR: out of memory registering interest",eError); - return 0; - } - lID = RegisterCallback(self->pCall, STSTART, StateHdbInterest, - callCon, SCDeleteConnection); - lID = RegisterCallback(self->pCall, STEND, StateHdbInterest, - callCon, NULL); - SCSendOK(pCon); - return 1; - } else if(strcmp(argv[1],"start") == 0) { - if(argc > 2){ - InvokeCallBack(self->pCall,STSTART,argv[2]); - SCSendOK(pCon); - return 1; } - return 0; - } else if(strcmp(argv[1],"stop") == 0) { - if(argc > 2){ - InvokeCallBack(self->pCall,STEND,argv[2]); - SCSendOK(pCon); - return 1; + if (alias != NULL) { + free(alias); } - return 0; - } - - SCWrite(pCon,"ERROR: keyword not recognized",eError); - return 0; -} + } + } + current = current->child; + while (current != NULL) { + result = recurseInterestNode(current, pDevice); + if (result != NULL) { + return result; + } + current = current->next; + } + } + return NULL; +} + +/*--------------------------------------------------------------------------*/ +static pHdb locateInterestNode(char *device) +{ + char pDevice[132], pSicsdev[132]; + pHdb current = NULL, result = NULL; + + memset(pDevice, 0, 132); + memset(pSicsdev, 0, 132); + + /* + * this is to strip off exes batch file name + */ + stptok(device, pDevice, 131, " "); + strtolower(pDevice); + + current = GetHipadabaRoot(); + return recurseInterestNode(current, pDevice); +} + +/*--------------------------------------------------------------------------*/ +static int StateHdbInterest(int iEvent, void *pEvent, void *pUser) +{ + SConnection *pCon = (SConnection *) pUser; + char *device = (char *) pEvent, *path = NULL; + char buffer[1024]; + pHdb node = NULL; + + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + if (device == NULL) { + printf("Bad StateHdbInterest in statemon\n"); + return 0; + } + node = locateInterestNode(device); + if (node != NULL) { + path = GetHipadabaPath(node); + if (iEvent == STSTART) { + snprintf(buffer, 1024, "%s STARTED", path); + SCWrite(pCon, buffer, eWarning); + } + if (iEvent == STEND) { + snprintf(buffer, 1024, "%s FINISH", path); + SCWrite(pCon, buffer, eWarning); + } + if (path != NULL) { + free(path); + } + } + return 1; +} + +/*====================== interpreter interface ==============================*/ +static void killStateMon(void *pData) +{ + pStateMon self = NULL; + + self = (pStateMon) pData; + if (self != NULL) { + if (self->pDes != NULL) { + DeleteDescriptor(self->pDes); + } + if (self->pCall != NULL) { + DeleteCallBackInterface(self->pCall); + } + free(self); + } +} + +/*---------------------------------------------------------------------------*/ +int StateMonFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pStateMon pNew = NULL; + commandContext cc; + pICallBack target = NULL; + void *pPtr = NULL, *exe = NULL, *pDevexec = NULL; + + exe = FindCommandData(pSics, "exe", "ExeManager"); + pDevexec = FindCommandData(pSics, "stopexe", "DeviceExecutor"); + if (exe == NULL || pDevexec == NULL) { + SCWrite(pCon, + "ERROR: both the device executor and the batch file module must be installed before initialising statemon", + eError); + return 0; + } + + /* + * generate data structures + */ + strcpy(cc.deviceID, "statemon"); + cc.transID = -120; + pNew = (pStateMon) malloc(sizeof(StateMon)); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating StateMon", eError); + return 0; + } + memset(pNew, 0, sizeof(StateMon)); + pNew->pDes = CreateDescriptor("statemon"); + pNew->pCall = CreateCallBackInterface(); + if (pNew->pDes == NULL || pNew->pCall == NULL) { + SCWrite(pCon, "ERROR: out of memory creating StateMon", eError); + return 0; + } + /* + * register callbacks + */ + target = GetCallbackInterface(pDevexec); + assert(target != NULL); + RegisterCallback(target, DRIVSTAT, DevexecCallback, pNew, NULL); + target = GetCallbackInterface(exe); + assert(target != NULL); + RegisterCallback(target, BATCHSTART, ExeCallback, pNew, NULL); + RegisterCallback(target, BATCHEND, ExeCallback, pNew, NULL); + + if (argc > 1) { + pPtr = FindCommandData(pSics, argv[1], "ScanObject"); + if (pPtr == NULL) { + SCWrite(pCon, "ERROR: failked to locate scan object", eError); + } else { + target = GetCallbackInterface(pPtr); + assert(target != NULL); + RegisterCallback(target, SCANSTART, StateMonScanInterest, pNew, + NULL); + RegisterCallback(target, SCANEND, StateMonScanInterest, pNew, NULL); + } + } + AddCommand(pSics, "statemon", StateMonAction, killStateMon, pNew); + return 1; +} + +/*---------------------------------------------------------------------------*/ +int StateMonAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + long lID; + int i; + pStateMon self = NULL; + SConnection *callCon = NULL; + + self = (pStateMon) pData; + assert(self != NULL); + + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to statemon", eError); + return 0; + } + strtolower(argv[1]); + if (strcmp(argv[1], "interest") == 0) { + callCon = SCCopyConnection(pCon); + if (callCon == NULL) { + SCWrite(pCon, "ERROR: out of memory registering interest", eError); + return 0; + } + lID = RegisterCallback(self->pCall, STSTART, StateInterest, + callCon, SCDeleteConnection); + SCRegister(pCon, pSics, self->pCall, lID); + lID = RegisterCallback(self->pCall, STEND, StateInterest, + callCon, NULL); + SCRegister(pCon, pSics, self->pCall, lID); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "uninterest") == 0) { + for (i = 0; i < 2; i++) { + lID = SCgetCallbackID(pCon, self->pCall); + if (lID >= 0) { + RemoveCallback(self->pCall, lID); + } + } + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "hdbinterest") == 0) { + callCon = SCCopyConnection(pCon); + if (callCon == NULL) { + SCWrite(pCon, "ERROR: out of memory registering interest", eError); + return 0; + } + lID = RegisterCallback(self->pCall, STSTART, StateHdbInterest, + callCon, SCDeleteConnection); + lID = RegisterCallback(self->pCall, STEND, StateHdbInterest, + callCon, NULL); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "start") == 0) { + if (argc > 2) { + InvokeCallBack(self->pCall, STSTART, argv[2]); + SCSendOK(pCon); + return 1; + } + return 0; + } else if (strcmp(argv[1], "stop") == 0) { + if (argc > 2) { + InvokeCallBack(self->pCall, STEND, argv[2]); + SCSendOK(pCon); + return 1; + } + return 0; + } + + SCWrite(pCon, "ERROR: keyword not recognized", eError); + return 0; +} diff --git a/statemon.h b/statemon.h index 686cdcd9..c06eb837 100644 --- a/statemon.h +++ b/statemon.h @@ -8,14 +8,14 @@ * copyright: see file COPYRIGHT * * Mark Koennecke, January 2007 - */ + */ #ifndef STATEMON_H_ #define STATEMON_H_ typedef struct __STATEMON *pStateMon; /*===================== The interpreter interface ===========================*/ -int StateMonFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int StateMonAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -#endif /*STATEMON_H_*/ +int StateMonFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int StateMonAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +#endif /*STATEMON_H_ */ diff --git a/statistics.c b/statistics.c index decfafde..cddbbc8c 100644 --- a/statistics.c +++ b/statistics.c @@ -18,33 +18,40 @@ static tv_t last, lastStat; static Statistics *idle = NULL, *list = NULL; static int init = 1; /*-----------------------------------------------------------------------*/ -tv_t timeDif(tv_t t1, tv_t t2) { +tv_t timeDif(tv_t t1, tv_t t2) +{ tv_t result; result.tv_usec = t2.tv_usec - t1.tv_usec; result.tv_sec = t2.tv_sec - t1.tv_sec; if (result.tv_usec < 0) { result.tv_usec += 1000000; - result.tv_sec --; + result.tv_sec--; } if (result.tv_sec < 0) { - result.tv_sec += 24*3600; + result.tv_sec += 24 * 3600; } return result; } + /*-----------------------------------------------------------------------*/ -void timeAdd(tv_t *t1, tv_t t2) { +void timeAdd(tv_t * t1, tv_t t2) +{ t1->tv_usec += t2.tv_usec; t1->tv_sec += t2.tv_sec + (t1->tv_usec / 1000000); t1->tv_usec %= 1000000; } + /*-----------------------------------------------------------------------*/ -double timeFloat(tv_t t) { +double timeFloat(tv_t t) +{ return t.tv_sec + 1e-6 * t.tv_usec; } + /*-----------------------------------------------------------------------*/ -int StatisticsCommand(SConnection *con, SicsInterp *pSics, void *pData, - int argc, char *argv[]) { +int StatisticsCommand(SConnection * con, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ Statistics *p; tv_t now; double dif, percent, full, dt, calls; @@ -65,7 +72,7 @@ int StatisticsCommand(SConnection *con, SicsInterp *pSics, void *pData, dt = 0; } SCPrintf(con, eValue, "%7.1f %7.1f %7.1f %8.2f %s", calls, - percent, full, dt, p->name); + percent, full, dt, p->name); } } p->cnt = 0; @@ -79,8 +86,10 @@ int StatisticsCommand(SConnection *con, SicsInterp *pSics, void *pData, lastStat = now; return 1; } + /*-----------------------------------------------------------------------*/ -Statistics *StatisticsNew(char *name) { +Statistics *StatisticsNew(char *name) +{ Statistics *new; if (init) { @@ -88,7 +97,7 @@ Statistics *StatisticsNew(char *name) { last = lastStat; init = 0; } - new = calloc(1,sizeof(*new)); + new = calloc(1, sizeof(*new)); if (new) { new->cnt = 0; new->tim.tv_sec = 0; @@ -102,8 +111,10 @@ Statistics *StatisticsNew(char *name) { } return new; } + /*-----------------------------------------------------------------------*/ -void StatisticsKill(Statistics *stat) { +void StatisticsKill(Statistics * stat) +{ Statistics *p, **last; /* find in list */ @@ -124,39 +135,45 @@ void StatisticsKill(Statistics *stat) { } free(stat); } + /*-----------------------------------------------------------------------*/ -Statistics *StatisticsBegin(Statistics *stat) { +Statistics *StatisticsBegin(Statistics * stat) +{ Statistics *res; tv_t now; - + res = current; gettimeofday(&now, 0); - if(current != NULL){ - timeAdd(¤t->tim, timeDif(last, now)); + if (current != NULL) { + timeAdd(¤t->tim, timeDif(last, now)); } last = now; current = stat; stat->last = now; - stat->cnt ++; + stat->cnt++; return res; } + /*-----------------------------------------------------------------------*/ -void StatisticsEnd(Statistics *stat) { +void StatisticsEnd(Statistics * stat) +{ tv_t now; gettimeofday(&now, 0); timeAdd(¤t->tim, timeDif(last, now)); last = now; - if(current != NULL){ - if (current->last.tv_sec >= 0) { - timeAdd(¤t->total, timeDif(current->last, now)); - } - current->last.tv_sec = -1; + if (current != NULL) { + if (current->last.tv_sec >= 0) { + timeAdd(¤t->total, timeDif(current->last, now)); + } + current->last.tv_sec = -1; } current = stat; } + /*-----------------------------------------------------------------------*/ -void StatisticsInit(void) { +void StatisticsInit(void) +{ if (idle == NULL) { AddCmd("statistics", StatisticsCommand); last = lastStat; @@ -164,4 +181,3 @@ void StatisticsInit(void) { current = idle; } } - diff --git a/statistics.h b/statistics.h index b3d5b599..8be30d4a 100644 --- a/statistics.h +++ b/statistics.h @@ -12,11 +12,11 @@ typedef struct Statistics Statistics; Statistics *StatisticsNew(char *name); /* create a new Statistics item */ -void StatisticsKill(Statistics *s); +void StatisticsKill(Statistics * s); /* kill item */ -Statistics *StatisticsBegin(Statistics *s); -void StatisticsEnd(Statistics *s); +Statistics *StatisticsBegin(Statistics * s); +void StatisticsEnd(Statistics * s); /* Switch statistics to item s. diff --git a/status.c b/status.c index 2813aabd..47f131a9 100644 --- a/status.c +++ b/status.c @@ -55,291 +55,285 @@ #undef VALUECHANGE #define VALUECHANGE 2 - - static char *pText[] = { - "Eager to execute commands", - "User requested Wait", - "Counting", - "No Beam", - "Paused", - "Driving", - "Running", - "Running a scan", - "Writing data", - "Processing a batch file", - "Halted", - "Dead", - "Waiting for User Input", - "Counting/Driving", - "Working", - NULL }; - static char *iText[] = { - "eager", - "userwait", - "count", - "nobeam", - "paused", - "driving", - "running", - "scanning", - "writing", - "batch", - "halt", - "dead", - "input", - "count/drive", - "working", - NULL }; - - static pICallBack pCall = NULL; - static int fixed = 0; - static Status eCode = eEager; +static char *pText[] = { + "Eager to execute commands", + "User requested Wait", + "Counting", + "No Beam", + "Paused", + "Driving", + "Running", + "Running a scan", + "Writing data", + "Processing a batch file", + "Halted", + "Dead", + "Waiting for User Input", + "Counting/Driving", + "Working", + NULL +}; + +static char *iText[] = { + "eager", + "userwait", + "count", + "nobeam", + "paused", + "driving", + "running", + "scanning", + "writing", + "batch", + "halt", + "dead", + "input", + "count/drive", + "working", + NULL +}; + +static pICallBack pCall = NULL; +static int fixed = 0; +static Status eCode = eEager; /*-------------------------------------------------------------------------*/ - void KillStatus(void *pData) - { - if(pCall != NULL) - { - DeleteCallBackInterface(pCall); - } - } +void KillStatus(void *pData) +{ + if (pCall != NULL) { + DeleteCallBackInterface(pCall); + } +} + /*--------------------------------------------------------------------------*/ - void SetStatus(Status eNew) - { - if(!fixed) - { - if(eCode == eNew) - { - return; - } - eCode = eNew; - InvokeCallBack(pCall,VALUECHANGE,NULL); - } - } +void SetStatus(Status eNew) +{ + if (!fixed) { + if (eCode == eNew) { + return; + } + eCode = eNew; + InvokeCallBack(pCall, VALUECHANGE, NULL); + } +} + /*----------------------------------------------------------------------*/ - void SetStatusFixed(Status eNew) - { - if(eCode == eNew) - { - return; - } - eCode = eNew; - InvokeCallBack(pCall,VALUECHANGE,NULL); - fixed = 1; - } +void SetStatusFixed(Status eNew) +{ + if (eCode == eNew) { + return; + } + eCode = eNew; + InvokeCallBack(pCall, VALUECHANGE, NULL); + fixed = 1; +} + /*----------------------------------------------------------------------*/ - void ClearFixedStatus(Status eNew) - { - if(eCode == eNew) - { - return; - } - eCode = eNew; - InvokeCallBack(pCall,VALUECHANGE,NULL); - fixed = 0; - } -/*-------------------------------------------------------------------------*/ - Status GetStatus(void) - { - return eCode; - } -/*-------------------------------------------------------------------------*/ - void GetStatusText(char *buf, int iBufLen) - { - strncpy(buf,pText[(int)eCode],iBufLen-1); - } +void ClearFixedStatus(Status eNew) +{ + if (eCode == eNew) { + return; + } + eCode = eNew; + InvokeCallBack(pCall, VALUECHANGE, NULL); + fixed = 0; +} + /*-------------------------------------------------------------------------*/ - int SetStatusFromText(char *text) - { - int i = 0; +Status GetStatus(void) +{ + return eCode; +} - /* check for short form */ - strtolower(text); - while(iText[i] != NULL) - { - if(strcmp(text,iText[i]) == 0) - { - break; - } - i++; +/*-------------------------------------------------------------------------*/ +void GetStatusText(char *buf, int iBufLen) +{ + strncpy(buf, pText[(int) eCode], iBufLen - 1); +} + +/*-------------------------------------------------------------------------*/ +int SetStatusFromText(char *text) +{ + int i = 0; + + /* check for short form */ + strtolower(text); + while (iText[i] != NULL) { + if (strcmp(text, iText[i]) == 0) { + break; + } + i++; + } + if (i >= 10) { + /* check for long form */ + i = 0; + while (pText[i] != NULL) { + if (strcmp(text, pText[i]) == 0) { + break; } - if(i >= 10) - { - /* check for long form */ - i = 0; - while(pText[i] != NULL) - { - if(strcmp(text,pText[i]) == 0) - { - break; - } - i++; - } - if(i >= 10) - { - return 0; - } - } - SetStatus((Status)i); + i++; + } + if (i >= 10) { + return 0; + } + } + SetStatus((Status) i); + return 1; +} + +/*------------------- The CallBack function for interest ------------------*/ +static int StatusCallback(int iEvent, void *pEvent, void *pUser) +{ + SConnection *pCon; + char pBueffel[80]; + + assert(pUser); + + pCon = (SConnection *) pUser; + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + sprintf(pBueffel, "status = %s", pText[(int) eCode]); + SCWrite(pCon, pBueffel, eLog); + return 1; +} + +/*------------------- The CallBack function for interest ------------------*/ +static int StatusHDBCallback(int iEvent, void *pEvent, void *pUser) +{ + pHdb node = NULL; + hdbValue v; + + assert(pUser); + + node = (pHdb) pUser; + v = MakeHdbText(pText[eCode]); + if (node != NULL && iEvent == VALUECHANGE) { + UpdateHipadabaPar(node, v, NULL); + } + return 1; +} + +/*-----------------------------------------------------------------------*/ +int UserStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512]; + long lID; + pHdb node = NULL; + + assert(pSics); + assert(pCon); + + /* create callback if not present */ + if (pCall == NULL) { + pCall = CreateCallBackInterface(); + } + + /* check for interest */ + if (argc > 1) { + strtolower(argv[1]); + if (strcmp(argv[1], "interest") == 0) { + lID = RegisterCallback(pCall, + VALUECHANGE, StatusCallback, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); return 1; - } -/*------------------- The CallBack function for interest ------------------*/ - static int StatusCallback(int iEvent, void *pEvent, void *pUser) - { - SConnection *pCon; - char pBueffel[80]; - - assert(pUser); - - pCon = (SConnection *)pUser; - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } - - sprintf(pBueffel,"status = %s", pText[(int)eCode]); - SCWrite(pCon,pBueffel,eLog); - return 1; - } -/*------------------- The CallBack function for interest ------------------*/ - static int StatusHDBCallback(int iEvent, void *pEvent, void *pUser) - { - pHdb node = NULL; - hdbValue v; - - assert(pUser); - - node = (pHdb)pUser; - v = MakeHdbText(pText[eCode]); - if(node != NULL && iEvent == VALUECHANGE){ - UpdateHipadabaPar(node,v,NULL); - } - return 1; - } -/*-----------------------------------------------------------------------*/ - int UserStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - long lID; - pHdb node = NULL; - - assert(pSics); - assert(pCon); - - /* create callback if not present */ - if(pCall == NULL) - { - pCall = CreateCallBackInterface(); - } - - /* check for interest */ - if(argc > 1) - { - strtolower(argv[1]); - if(strcmp(argv[1],"interest") == 0) - { - lID = RegisterCallback(pCall, - VALUECHANGE, StatusCallback, - SCCopyConnection(pCon), SCDeleteConnection); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"hdbinterest") == 0) - { - if(argc > 2){ - node = GetHipadabaNode(GetHipadabaRoot(),argv[2]); - if(node != NULL){ - lID = RegisterCallback(pCall, - VALUECHANGE, StatusHDBCallback, - node, NULL); - SCSendOK(pCon); - return 1; - } else { - SCWrite(pCon,"ERROR: Hipadaba node not found",eError); - return 0; - } - } + } else if (strcmp(argv[1], "hdbinterest") == 0) { + if (argc > 2) { + node = GetHipadabaNode(GetHipadabaRoot(), argv[2]); + if (node != NULL) { + lID = RegisterCallback(pCall, + VALUECHANGE, StatusHDBCallback, + node, NULL); + SCSendOK(pCon); + return 1; } else { - SCWrite(pCon,"ERROR: require node parameter to register status callback", - eError); - return 0; + SCWrite(pCon, "ERROR: Hipadaba node not found", eError); + return 0; } } - - /* else just print value */ - sprintf(pBueffel,"status = %s", pText[(int)eCode]); - SCWrite(pCon,pBueffel,eValue); - return 1; - } -/*-------------------------------------------------------------------------*/ - int ResetStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - assert(pCon); - assert(pSics); + } else { + SCWrite(pCon, + "ERROR: require node parameter to register status callback", + eError); + return 0; + } + } + + /* else just print value */ + sprintf(pBueffel, "status = %s", pText[(int) eCode]); + SCWrite(pCon, pBueffel, eValue); + return 1; +} + +/*-------------------------------------------------------------------------*/ +int ResetStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + assert(pCon); + assert(pSics); + + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "Insufficient authorisation to reset server", eError); + return 0; + } + SetStatus(eEager); + SetInterrupt(eContinue); + ClearExecutor(GetExecutor()); + SCsetMacro(pCon, 0); + return 1; +} + +/* ===================== Control Connection Management ====================*/ +static SConnection *pOwner = NULL; + +void SetControl(SConnection * pCon) +{ + pOwner = pCon; +} - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"Insufficient authorisation to reset server",eError); - return 0; - } - SetStatus(eEager); - SetInterrupt(eContinue); - ClearExecutor(GetExecutor()); - SCsetMacro(pCon,0); - return 1; - } -/* ===================== Control Connection Management ====================*/ - static SConnection *pOwner = NULL; - - void SetControl(SConnection *pCon) - { - pOwner = pCon; - } -/*--------------------------------------------------------------------------*/ - int IsControl(SConnection *pCon) - { - if(pCon == pOwner) - { - return 1; - } - else - { - return 0; - } - } /*--------------------------------------------------------------------------*/ - SConnection *GetControl(void) - { - return pOwner; - } +int IsControl(SConnection * pCon) +{ + if (pCon == pOwner) { + return 1; + } else { + return 0; + } +} + /*--------------------------------------------------------------------------*/ - int RedirectControl(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - assert(pCon); - assert(pSics); - - /* check user Rights */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon, - "You have NO, I repeat NO, Privilege to grab a control connection", +SConnection *GetControl(void) +{ + return pOwner; +} + +/*--------------------------------------------------------------------------*/ +int RedirectControl(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + assert(pCon); + assert(pSics); + + /* check user Rights */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, + "You have NO, I repeat NO, Privilege to grab a control connection", eError); - return 0; - } - - /* check if the connection is dead at all */ - if(pCon->sockHandle < 0) - { - SCWrite(pCon, - "GOTCHA!!! Control still lives! You CANNOT grab it! FUCK OFF", - eError); - return 0; - } - - /* now the wizardry */ - pOwner->sockHandle = pCon->sockHandle; - return 1; - } + return 0; + } + + /* check if the connection is dead at all */ + if (pCon->sockHandle < 0) { + SCWrite(pCon, + "GOTCHA!!! Control still lives! You CANNOT grab it! FUCK OFF", + eError); + return 0; + } + + /* now the wizardry */ + pOwner->sockHandle = pCon->sockHandle; + return 1; +} diff --git a/status.h b/status.h index f80774da..468e0354 100644 --- a/status.h +++ b/status.h @@ -8,46 +8,46 @@ #ifndef SICSSTATUS #define SICSSTATUS - typedef enum { - eEager, - eUserWait, - eCounting, - eOutOfBeam, - ePaused, - eDriving, - eRunning, - eScanning, - eWriting, - eBatch, - eHalted, - eDead, - eInput, - eCountDrive, - eWorking - } Status; - +typedef enum { + eEager, + eUserWait, + eCounting, + eOutOfBeam, + ePaused, + eDriving, + eRunning, + eScanning, + eWriting, + eBatch, + eHalted, + eDead, + eInput, + eCountDrive, + eWorking +} Status; + /* for status display */ - void SetStatus(Status eNew); - int SetStatusFromText(char *text); - void KillStatus(void *pData); +void SetStatus(Status eNew); +int SetStatusFromText(char *text); +void KillStatus(void *pData); /** * set a status and disallow any further changes to the status. This serves * in order to prevent massive message flows to the client from status * changes while processing synchronisation files */ - void SetStatusFixed(Status eNew); +void SetStatusFixed(Status eNew); /** * clear a fixed status again, status will be updated again. */ - void ClearFixedStatus(Status eNew); +void ClearFixedStatus(Status eNew); - Status GetStatus(void); - void GetStatusText(char *buf, int iBufLen); +Status GetStatus(void); +void GetStatusText(char *buf, int iBufLen); - int UserStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int ResetStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int UserStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int ResetStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/statusfile.c b/statusfile.c index 85371cbb..622cb55d 100644 --- a/statusfile.c +++ b/statusfile.c @@ -53,244 +53,247 @@ #include "exebuf.h" static int parameterChange = 0; -/*-----------------------------------------------------------------------*/ -int StatusFileTask(void *data) { +/*-----------------------------------------------------------------------*/ +int StatusFileTask(void *data) +{ char *pFile = NULL; if (parameterChange) { parameterChange = 0; assert(pServ->pSics); - pFile = IFindOption(pSICSOptions,"statusfile"); + pFile = IFindOption(pSICSOptions, "statusfile"); if (pFile) { - WriteSicsStatus(pServ->pSics,pFile,0); + WriteSicsStatus(pServ->pSics, pFile, 0); } } return 1; } -/*---------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------*/ static int motorSave = 0; -/*-----------------------------------------------------------------------*/ - int BackupStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet; - char pBueffel[512]; - char *pFile = NULL; +/*-----------------------------------------------------------------------*/ +int BackupStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet; + char pBueffel[512]; + char *pFile = NULL; - assert(pSics); - assert(pCon); - - if(argc < 2) - { - pFile = IFindOption(pSICSOptions,"statusfile"); - if(pFile) - { - iRet = WriteSicsStatus(pSics,pFile,motorSave); - } - else - { - SCWrite(pCon,"ERROR: No filename given for backup, Aborted.", - eError); - return 0; - } - } + assert(pSics); + assert(pCon); + + if (argc < 2) { + pFile = IFindOption(pSICSOptions, "statusfile"); + if (pFile) { + iRet = WriteSicsStatus(pSics, pFile, motorSave); + } else { + SCWrite(pCon, "ERROR: No filename given for backup, Aborted.", + eError); + return 0; + } + } else { + if (strcmp(argv[1], "motorSave") == 0) { + if (motorSave == 1) + motorSave = 0; else - { - if(strcmp(argv[1],"motorSave") == 0) - { - if(motorSave== 1) - motorSave= 0; - else - motorSave= 1; - sprintf(pBueffel,"New Value of motorSave= %d\n",motorSave); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { - iRet = WriteSicsStatus(pSics,argv[1],motorSave); - } - } - - if(!iRet) - { - sprintf(pBueffel,"ERROR: could not open file %s\n", argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - SCSendOK(pCon); + motorSave = 1; + sprintf(pBueffel, "New Value of motorSave= %d\n", motorSave); + SCWrite(pCon, pBueffel, eValue); return 1; - } -/*---------------------------------------------------------------------*/ -static int restoreOccurred = 0; -int hasRestored(){ - return restoreOccurred; + } else { + iRet = WriteSicsStatus(pSics, argv[1], motorSave); + } + } + + if (!iRet) { + sprintf(pBueffel, "ERROR: could not open file %s\n", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + SCSendOK(pCon); + return 1; } + +/*---------------------------------------------------------------------*/ +static int restoreOccurred = 0; +int hasRestored() +{ + return restoreOccurred; +} + /*---------------------------------------------------------------------------*/ typedef struct { - pObjectDescriptor pDes; - int errList; -}RestoreObj, *pRestoreObj; + pObjectDescriptor pDes; + int errList; +} RestoreObj, *pRestoreObj; /*---------------------------------------------------------------------------*/ -static void killRestore(void *data){ - pRestoreObj self = (pRestoreObj)data; - if(self == NULL){ - return; - } - if(self->errList >= 0){ - LLDdeleteBlob(self->errList); - } - if(self->pDes != NULL){ - DeleteDescriptor(self->pDes); - } - free(self); -} -/*--------------------------------------------------------------------------*/ -static int SaveRestore(void *obj, char *name, FILE *fd){ - int status; - char buffer[1024]; - - pRestoreObj self = (pRestoreObj)obj; - if(self == NULL){ - return 0; - } - fprintf(fd,"\n#--- BEGIN (commands producing errors on last restore)\n"); - status = LLDnodePtr2First(self->errList); - while(status == 1){ - LLDstringData(self->errList,buffer); - fprintf(fd,"%s", buffer); - status = LLDnodePtr2Next(self->errList); - } - fprintf(fd,"#--- END (commands producing errors on last restore)\n\n"); - return 1; -} -/*---------------------------------------------------------------------------*/ -int InstallBckRestore(SConnection *pCon, SicsInterp *pSics){ - pRestoreObj pNew = NULL; - - pNew = malloc(sizeof(RestoreObj)); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: no memory to create restore object! This is SERIOUS!!!", - eError); - return 0; - } - pNew->pDes = CreateDescriptor("BckRestore"); - pNew->errList = LLDstringCreate(); - if(pNew->pDes == NULL || pNew->errList < 0){ - SCWrite(pCon,"ERROR: no memory to create restore object! This is SERIOUS!!!", - eError); - return 0; - } - pNew->pDes->SaveStatus = SaveRestore; - AddCommand(pSics,"Backup",BackupStatus,NULL,NULL); - AddCommand(pSics,"Restore",RestoreStatus,killRestore,pNew); - - return 1; -} -/*-----------------------------------------------------------------------*/ -static int listRestoreErr(pRestoreObj self, SConnection *pCon){ - char buffer[1024]; - int status; - pDynString data = NULL; - - SCStartBuffering(pCon); - status = LLDnodePtr2First(self->errList); - while(status == 1){ - LLDstringData(self->errList,buffer); - SCWrite(pCon,buffer,eValue); - status = LLDnodePtr2Next(self->errList); - } - data = SCEndBuffering(pCon); - if(data != NULL){ - SCWrite(pCon,GetCharArray(data),eValue); - } - return 1; -} -/*-----------------------------------------------------------------------*/ - int RestoreStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512]; - int iRights; - int iRet; - char *pFile = NULL; - writeFunc oldWrite; - pExeBuf buffi = NULL; - pRestoreObj self = (pRestoreObj)pData; - - assert(pSics); - assert(pCon); - assert(self != NULL); - - if(argc < 2) - { - pFile = IFindOption(pSICSOptions,"statusfile"); - if(pFile) - { - sprintf(pBueffel,"%s",pFile); - } - else - { - SCWrite(pCon,"ERROR: No filename given for backup, Aborted.", - eError); - return 0; - } - } - else - { - if(strcasecmp(argv[1],"listerr") == 0){ - return listRestoreErr(self,pCon); - } else if(strcasecmp(argv[1],"killerr") == 0){ - if(self->errList >= 0){ - LLDdeleteBlob(self->errList); - } - self->errList = LLDstringCreate(); - StatusFileDirty(); - SCSendOK(pCon); - return 1; - } else { - sprintf(pBueffel,"%s",argv[1]); - } - } - - buffi = exeBufCreate("restore"); - if(buffi == NULL){ - SCWrite(pCon,"ERROR: failed to allocate buffer for restore",eError); - return 0; - } - iRet = exeBufLoad(buffi,pBueffel); - if(iRet != 1){ - exeBufDelete(buffi); - SCWrite(pCon,"ERROR: failed open status file",eError); - return 0; - } - LLDdeleteBlob(self->errList); - self->errList = LLDstringCreate(); - iRights = SCGetRights(pCon); - pCon->iUserRights = usInternal; - oldWrite = SCGetWriteFunc(pCon); - SCSetWriteFunc(pCon,SCNotWrite); - iRet = exeBufProcessErrList(buffi,pSics,pCon,self->errList); - restoreOccurred = 1; - SCSetWriteFunc(pCon,oldWrite); - pCon->iUserRights = iRights; - exeBufDelete(buffi); - /* - if we do not override parameterChange here, the backup file - would be overwritten after each restore... Not the right thing - to do! - */ - parameterChange = 0; - SCSendOK(pCon); - return iRet; - } -/*-----------------------------------------------------------------------*/ -void StatusFileDirty(void) { - parameterChange = 1; -} -/*-----------------------------------------------------------------------*/ -void StatusFileInit(void) { - TaskRegister(pServ->pTasker, StatusFileTask, NULL, NULL, NULL, 0); +static void killRestore(void *data) +{ + pRestoreObj self = (pRestoreObj) data; + if (self == NULL) { + return; + } + if (self->errList >= 0) { + LLDdeleteBlob(self->errList); + } + if (self->pDes != NULL) { + DeleteDescriptor(self->pDes); + } + free(self); } +/*--------------------------------------------------------------------------*/ +static int SaveRestore(void *obj, char *name, FILE * fd) +{ + int status; + char buffer[1024]; + + pRestoreObj self = (pRestoreObj) obj; + if (self == NULL) { + return 0; + } + fprintf(fd, + "\n#--- BEGIN (commands producing errors on last restore)\n"); + status = LLDnodePtr2First(self->errList); + while (status == 1) { + LLDstringData(self->errList, buffer); + fprintf(fd, "%s", buffer); + status = LLDnodePtr2Next(self->errList); + } + fprintf(fd, "#--- END (commands producing errors on last restore)\n\n"); + return 1; +} + +/*---------------------------------------------------------------------------*/ +int InstallBckRestore(SConnection * pCon, SicsInterp * pSics) +{ + pRestoreObj pNew = NULL; + + pNew = malloc(sizeof(RestoreObj)); + if (pNew == NULL) { + SCWrite(pCon, + "ERROR: no memory to create restore object! This is SERIOUS!!!", + eError); + return 0; + } + pNew->pDes = CreateDescriptor("BckRestore"); + pNew->errList = LLDstringCreate(); + if (pNew->pDes == NULL || pNew->errList < 0) { + SCWrite(pCon, + "ERROR: no memory to create restore object! This is SERIOUS!!!", + eError); + return 0; + } + pNew->pDes->SaveStatus = SaveRestore; + AddCommand(pSics, "Backup", BackupStatus, NULL, NULL); + AddCommand(pSics, "Restore", RestoreStatus, killRestore, pNew); + + return 1; +} + +/*-----------------------------------------------------------------------*/ +static int listRestoreErr(pRestoreObj self, SConnection * pCon) +{ + char buffer[1024]; + int status; + pDynString data = NULL; + + SCStartBuffering(pCon); + status = LLDnodePtr2First(self->errList); + while (status == 1) { + LLDstringData(self->errList, buffer); + SCWrite(pCon, buffer, eValue); + status = LLDnodePtr2Next(self->errList); + } + data = SCEndBuffering(pCon); + if (data != NULL) { + SCWrite(pCon, GetCharArray(data), eValue); + } + return 1; +} + +/*-----------------------------------------------------------------------*/ +int RestoreStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512]; + int iRights; + int iRet; + char *pFile = NULL; + writeFunc oldWrite; + pExeBuf buffi = NULL; + pRestoreObj self = (pRestoreObj) pData; + + assert(pSics); + assert(pCon); + assert(self != NULL); + + if (argc < 2) { + pFile = IFindOption(pSICSOptions, "statusfile"); + if (pFile) { + sprintf(pBueffel, "%s", pFile); + } else { + SCWrite(pCon, "ERROR: No filename given for backup, Aborted.", + eError); + return 0; + } + } else { + if (strcasecmp(argv[1], "listerr") == 0) { + return listRestoreErr(self, pCon); + } else if (strcasecmp(argv[1], "killerr") == 0) { + if (self->errList >= 0) { + LLDdeleteBlob(self->errList); + } + self->errList = LLDstringCreate(); + StatusFileDirty(); + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "%s", argv[1]); + } + } + + buffi = exeBufCreate("restore"); + if (buffi == NULL) { + SCWrite(pCon, "ERROR: failed to allocate buffer for restore", eError); + return 0; + } + iRet = exeBufLoad(buffi, pBueffel); + if (iRet != 1) { + exeBufDelete(buffi); + SCWrite(pCon, "ERROR: failed open status file", eError); + return 0; + } + LLDdeleteBlob(self->errList); + self->errList = LLDstringCreate(); + iRights = SCGetRights(pCon); + pCon->iUserRights = usInternal; + oldWrite = SCGetWriteFunc(pCon); + SCSetWriteFunc(pCon, SCNotWrite); + iRet = exeBufProcessErrList(buffi, pSics, pCon, self->errList); + restoreOccurred = 1; + SCSetWriteFunc(pCon, oldWrite); + pCon->iUserRights = iRights; + exeBufDelete(buffi); + /* + if we do not override parameterChange here, the backup file + would be overwritten after each restore... Not the right thing + to do! + */ + parameterChange = 0; + SCSendOK(pCon); + return iRet; +} + +/*-----------------------------------------------------------------------*/ +void StatusFileDirty(void) +{ + parameterChange = 1; +} + +/*-----------------------------------------------------------------------*/ +void StatusFileInit(void) +{ + TaskRegister(pServ->pTasker, StatusFileTask, NULL, NULL, NULL, 0); +} diff --git a/statusfile.h b/statusfile.h index 39976d8b..2ff118c0 100644 --- a/statusfile.h +++ b/statusfile.h @@ -9,16 +9,15 @@ #include - int InstallBckRestore(SConnection *pCon, SicsInterp *pSics); - int BackupStatus(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int InstallBckRestore(SConnection * pCon, SicsInterp * pSics); +int BackupStatus(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - int RestoreStatus(SConnection *pCon, SicsInterp *pSics, void *pData, +int RestoreStatus(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]); - int hasRestored(); - - int StatusFileTask(void *data); /* saves status file if parameters have changed */ - - void StatusFileDirty(void); /* indicate that the status file has to be rewritten */ +int hasRestored(); + +int StatusFileTask(void *data); /* saves status file if parameters have changed */ + +void StatusFileDirty(void); /* indicate that the status file has to be rewritten */ #endif - diff --git a/stdscan.c b/stdscan.c index 53949e12..d56538ab 100644 --- a/stdscan.c +++ b/stdscan.c @@ -33,1071 +33,1019 @@ /*-----------------------------------------------------------------------*/ static char *fixExtension(char *filename) { - if(strstr(filename,".hdf") != NULL) - { - changeExtension(filename,"dat"); + if (strstr(filename, ".hdf") != NULL) { + changeExtension(filename, "dat"); } return filename; } -/*------------------------------------------------------------------------*/ - char *ScanMakeFileName(SicsInterp *pSics, SConnection *pCon) - { - pSicsVariable pPath = NULL, pPref = NULL, pEnd = NULL; - char *pRes = NULL; - int iLen, iNum, iYear; - char pNumText[10]; - CommandList *pCom = NULL; - char simName[255]; - - /* - make a simulated filename if in simulation mode - */ - if(pServ->simMode){ - snprintf(simName,255,"%s/tmp/sim001001901.sim",getenv("HOME")); - return strdup(simName); - } - pRes = makeFilename(pSics,pCon); - if(pRes == NULL) - { - pRes = strdup("emergency.scn"); - } - return fixExtension(pRes); - } -/*-------------------------------------------------------------------------*/ -void WriteTemplate(FILE *fd, FILE *temp, char *filename, pScanData pScan, - SConnection *pCon, SicsInterp *pSics) +/*------------------------------------------------------------------------*/ +char *ScanMakeFileName(SicsInterp * pSics, SConnection * pCon) { - char pBuffer[512], pError[512], *pPtr, *pName; - CommandList *pCom = NULL; - pSicsVariable pVar = NULL; - pDummy pDum = NULL; - pIDrivable pDriv = NULL; - pMotor pMot = NULL; - pVarEntry pScanVar = NULL; - void *pVoid = NULL; - float fVal; - int iRet; - - /* loop through description file and act along the way */ - while(fgets(pBuffer,511,temp) != NULL) - { - pPtr = strstr(pBuffer,"!!VAR("); - if(pPtr) /* handle a Sics variable */ - { - /* extract the name */ - pName = pPtr + 6; /* first char of name */ - *pPtr = '\0'; /* this is the starter of the line */ - pPtr = pName; - while( (*pPtr != '\0') && (*pPtr != ')') ) - { - pPtr++; - } - *pPtr = '\0'; - /* find the variable */ - pCom = FindCommand(pSics,pName); - if(!pCom) - { - sprintf(pError,"ERROR: variable %s NOT found",pName); - SCWrite(pCon,pError,eLogError); - continue; - } - pVar = (pSicsVariable)pCom->pData; - if(!pVar) - { - sprintf(pError,"ERROR: variable %s NOT found",pName); - SCWrite(pCon,pError,eLogError); - continue; - } - switch(pVar->eType) - { - case veFloat: - sprintf(pError,"%f",pVar->fVal); - break; - case veInt: - sprintf(pError,"%d",pVar->iVal); - break; - case veText: - sprintf(pError,"%s",pVar->text); - break; - } - /* finally write */ - fprintf(fd,"%s %s\n",pBuffer,pError); - continue; - }/* end variable */ -/*------- Drivable */ - pPtr = strstr(pBuffer,"!!DRIV("); - if(pPtr) - { - /* extract the name */ - pName = pPtr + 7; /* first char of name */ - *pPtr = '\0'; /* this is the starter of the line */ - pPtr = pName; - while( (*pPtr != '\0') && (*pPtr != ')') ) - { - pPtr++; - } - *pPtr = '\0'; - /* find the variable */ - pCom = FindCommand(pSics,pName); - if(!pCom) - { - sprintf(pError,"ERROR: variable %s NOT found",pName); - SCWrite(pCon,pError,eLogError); - continue; - } - pDum = (pDummy)pCom->pData; - if(!pDum) - { - sprintf(pError,"ERROR: variable %s is NOT drivable",pName); - SCWrite(pCon,pError,eLogError); - continue; - } - pDriv = (pIDrivable)pDum->pDescriptor->GetInterface(pDum,DRIVEID); - if(!pDriv) - { - sprintf(pError,"ERROR: variable %s is NOT drivable",pName); - SCWrite(pCon,pError,eLogError); - continue; - } - fVal = pDriv->GetValue(pDum,pCon); - fprintf(fd,"%s %f\n",pBuffer,fVal); - continue; - } /* end drive */ -/*------- zero point */ - pPtr = strstr(pBuffer,"!!ZERO("); - if(pPtr) - { - /* extract the name */ - pName = pPtr + 7; /* first char of name */ - *pPtr = '\0'; /* this is the starter of the line */ - pPtr = pName; - while( (*pPtr != '\0') && (*pPtr != ')') ) - { - pPtr++; - } - *pPtr = '\0'; - /* find the motor */ - pMot = FindMotor(pSics,pName); - if(!pMot) - { - sprintf(pError,"ERROR: motor %s NOT found",pName); - SCWrite(pCon,pError,eLogError); - continue; - } - iRet = MotorGetPar(pMot,"softzero",&fVal); - if(!iRet) - { - SCWrite(pCon,"ERROR: failed to read zero point",eLogError); - continue; - } - fprintf(fd,"%s %f\n",pBuffer,fVal); - continue; - } /* end zero point */ -/*---------- scripted info */ - pPtr = strstr(pBuffer,"!!SCRIPT("); - if(pPtr) - { - /* extract the name */ - pName = pPtr + 9; /* first char of name */ - *pPtr = '\0'; /* this is the starter of the line */ - pPtr = pName; - while( (*pPtr != '\0') && (*pPtr != ')') ) - { - pPtr++; - } - *pPtr = '\0'; - if(Tcl_Eval(InterpGetTcl(pSics),pName) == TCL_OK) - { - fprintf(fd,"%s\n",Tcl_GetStringResult(InterpGetTcl(pSics))); - } - else - { - SCWrite(pCon,"ERROR: failed to execute Tcl command",eError); - strncpy(pBuffer, Tcl_GetStringResult(InterpGetTcl(pSics)), 511); - SCWrite(pCon,pBuffer,eLogError); - continue; - } - } + pSicsVariable pPath = NULL, pPref = NULL, pEnd = NULL; + char *pRes = NULL; + int iLen, iNum, iYear; + char pNumText[10]; + CommandList *pCom = NULL; + char simName[255]; + + /* + make a simulated filename if in simulation mode + */ + if (pServ->simMode) { + snprintf(simName, 255, "%s/tmp/sim001001901.sim", getenv("HOME")); + return strdup(simName); + } + + pRes = makeFilename(pSics, pCon); + if (pRes == NULL) { + pRes = strdup("emergency.scn"); + } + return fixExtension(pRes); +} + +/*-------------------------------------------------------------------------*/ +void WriteTemplate(FILE * fd, FILE * temp, char *filename, pScanData pScan, + SConnection * pCon, SicsInterp * pSics) +{ + char pBuffer[512], pError[512], *pPtr, *pName; + CommandList *pCom = NULL; + pSicsVariable pVar = NULL; + pDummy pDum = NULL; + pIDrivable pDriv = NULL; + pMotor pMot = NULL; + pVarEntry pScanVar = NULL; + void *pVoid = NULL; + float fVal; + int iRet; + + /* loop through description file and act along the way */ + while (fgets(pBuffer, 511, temp) != NULL) { + pPtr = strstr(pBuffer, "!!VAR("); + if (pPtr) { /* handle a Sics variable */ + /* extract the name */ + pName = pPtr + 6; /* first char of name */ + *pPtr = '\0'; /* this is the starter of the line */ + pPtr = pName; + while ((*pPtr != '\0') && (*pPtr != ')')) { + pPtr++; + } + *pPtr = '\0'; + /* find the variable */ + pCom = FindCommand(pSics, pName); + if (!pCom) { + sprintf(pError, "ERROR: variable %s NOT found", pName); + SCWrite(pCon, pError, eLogError); + continue; + } + pVar = (pSicsVariable) pCom->pData; + if (!pVar) { + sprintf(pError, "ERROR: variable %s NOT found", pName); + SCWrite(pCon, pError, eLogError); + continue; + } + switch (pVar->eType) { + case veFloat: + sprintf(pError, "%f", pVar->fVal); + break; + case veInt: + sprintf(pError, "%d", pVar->iVal); + break; + case veText: + sprintf(pError, "%s", pVar->text); + break; + } + /* finally write */ + fprintf(fd, "%s %s\n", pBuffer, pError); + continue; + } + /* end variable */ + /*------- Drivable */ + pPtr = strstr(pBuffer, "!!DRIV("); + if (pPtr) { + /* extract the name */ + pName = pPtr + 7; /* first char of name */ + *pPtr = '\0'; /* this is the starter of the line */ + pPtr = pName; + while ((*pPtr != '\0') && (*pPtr != ')')) { + pPtr++; + } + *pPtr = '\0'; + /* find the variable */ + pCom = FindCommand(pSics, pName); + if (!pCom) { + sprintf(pError, "ERROR: variable %s NOT found", pName); + SCWrite(pCon, pError, eLogError); + continue; + } + pDum = (pDummy) pCom->pData; + if (!pDum) { + sprintf(pError, "ERROR: variable %s is NOT drivable", pName); + SCWrite(pCon, pError, eLogError); + continue; + } + pDriv = (pIDrivable) pDum->pDescriptor->GetInterface(pDum, DRIVEID); + if (!pDriv) { + sprintf(pError, "ERROR: variable %s is NOT drivable", pName); + SCWrite(pCon, pError, eLogError); + continue; + } + fVal = pDriv->GetValue(pDum, pCon); + fprintf(fd, "%s %f\n", pBuffer, fVal); + continue; + } + /* end drive */ + /*------- zero point */ + pPtr = strstr(pBuffer, "!!ZERO("); + if (pPtr) { + /* extract the name */ + pName = pPtr + 7; /* first char of name */ + *pPtr = '\0'; /* this is the starter of the line */ + pPtr = pName; + while ((*pPtr != '\0') && (*pPtr != ')')) { + pPtr++; + } + *pPtr = '\0'; + /* find the motor */ + pMot = FindMotor(pSics, pName); + if (!pMot) { + sprintf(pError, "ERROR: motor %s NOT found", pName); + SCWrite(pCon, pError, eLogError); + continue; + } + iRet = MotorGetPar(pMot, "softzero", &fVal); + if (!iRet) { + SCWrite(pCon, "ERROR: failed to read zero point", eLogError); + continue; + } + fprintf(fd, "%s %f\n", pBuffer, fVal); + continue; + } + /* end zero point */ + /*---------- scripted info */ + pPtr = strstr(pBuffer, "!!SCRIPT("); + if (pPtr) { + /* extract the name */ + pName = pPtr + 9; /* first char of name */ + *pPtr = '\0'; /* this is the starter of the line */ + pPtr = pName; + while ((*pPtr != '\0') && (*pPtr != ')')) { + pPtr++; + } + *pPtr = '\0'; + if (Tcl_Eval(InterpGetTcl(pSics), pName) == TCL_OK) { + fprintf(fd, "%s\n", Tcl_GetStringResult(InterpGetTcl(pSics))); + } else { + SCWrite(pCon, "ERROR: failed to execute Tcl command", eError); + strncpy(pBuffer, Tcl_GetStringResult(InterpGetTcl(pSics)), 511); + SCWrite(pCon, pBuffer, eLogError); + continue; + } + } /* ------- date */ - pPtr = strstr(pBuffer,"!!DATE!!"); - if(pPtr) - { - *pPtr = '\0'; - SNXFormatTime(pError,511); - fprintf(fd,"%s %s\n",pBuffer,pError); - continue; - } -/*-------- filename */ - pPtr = strstr(pBuffer,"!!FILE!!"); - if(pPtr) - { - *pPtr = '\0'; - fprintf(fd,"%s %s\n",pBuffer,filename); - continue; - } + pPtr = strstr(pBuffer, "!!DATE!!"); + if (pPtr) { + *pPtr = '\0'; + SNXFormatTime(pError, 511); + fprintf(fd, "%s %s\n", pBuffer, pError); + continue; + } +/*-------- filename */ + pPtr = strstr(pBuffer, "!!FILE!!"); + if (pPtr) { + *pPtr = '\0'; + fprintf(fd, "%s %s\n", pBuffer, filename); + continue; + } /*------------ scanzero */ - pPtr = strstr(pBuffer,"!!SCANZERO!!"); - if(pPtr && pScan != NULL) - { - *pPtr = '\0'; - /* write zero point of first scan variable if motor */ - DynarGet(pScan->pScanVar,0,&pVoid); - pScanVar = (pVarEntry)pVoid; - if(pScanVar) - { - pMot = NULL; - pMot = FindMotor(pSics,ScanVarName(pScanVar)); - if(pMot != NULL) - { - MotorGetPar(pMot,"softzero",&fVal); - fprintf(fd,"%s zero = %8.3f\n",ScanVarName(pScanVar), - fVal); - } - } + pPtr = strstr(pBuffer, "!!SCANZERO!!"); + if (pPtr && pScan != NULL) { + *pPtr = '\0'; + /* write zero point of first scan variable if motor */ + DynarGet(pScan->pScanVar, 0, &pVoid); + pScanVar = (pVarEntry) pVoid; + if (pScanVar) { + pMot = NULL; + pMot = FindMotor(pSics, ScanVarName(pScanVar)); + if (pMot != NULL) { + MotorGetPar(pMot, "softzero", &fVal); + fprintf(fd, "%s zero = %8.3f\n", ScanVarName(pScanVar), fVal); } + } + } /* --------- plain text */ - fprintf(fd,"%s",pBuffer); - } /* end while */ -} + fprintf(fd, "%s", pBuffer); + } /* end while */ +} + /*---------------------------------------------------------------------------*/ - int WriteHeader(pScanData self) - { - int i, iRet; - FILE *fd; +int WriteHeader(pScanData self) +{ + int i, iRet; + FILE *fd; - assert(self->pSics); - assert(self->pCon); - - /* open data file */ - self->fd = fopen(self->pFile,"w"); - if(!self->fd) - { - SCWrite(self->pCon,"ERROR: cannot write data file",eLogError); - return 0; - } - - /* open header description file */ - fd = fopen(self->pHeaderFile,"r"); - if(!fd) - { - SCWrite(self->pCon,"ERROR: cannot open header description file",eLogError); - return 0; - } + assert(self->pSics); + assert(self->pCon); - WriteTemplate(self->fd,fd,self->pFile, - self, self->pCon, self->pSics); - - /* remember position for seeking to it for writing data */ - self->lPos = ftell(self->fd); + /* open data file */ + self->fd = fopen(self->pFile, "w"); + if (!self->fd) { + SCWrite(self->pCon, "ERROR: cannot write data file", eLogError); + return 0; + } + + /* open header description file */ + fd = fopen(self->pHeaderFile, "r"); + if (!fd) { + SCWrite(self->pCon, "ERROR: cannot open header description file", + eLogError); + return 0; + } + + WriteTemplate(self->fd, fd, self->pFile, self, self->pCon, self->pSics); + + /* remember position for seeking to it for writing data */ + self->lPos = ftell(self->fd); + + fclose(fd); + fclose(self->fd); + self->fd = NULL; + return 1; +} - fclose(fd); - fclose(self->fd); - self->fd = NULL; - return 1; - } /*---------------------------------------------------------------------------*/ - int WriteHeaderOld(pScanData self) - { - int i, iRet; - FILE *fd; - char pBuffer[512], pError[512], *pPtr, *pName; - CommandList *pCom = NULL; - pSicsVariable pVar = NULL; - pDummy pDum = NULL; - pIDrivable pDriv = NULL; - float fVal; - pMotor pMot = NULL; - pVarEntry pScanVar = NULL; - void *pVoid = NULL; - - assert(self->pSics); - assert(self->pCon); - - /* open data file */ - self->fd = fopen(self->pFile,"w"); - if(!self->fd) - { - SCWrite(self->pCon,"ERROR: cannot write data file",eError); - return 0; - } - - /* open header description file */ - fd = fopen(self->pHeaderFile,"r"); - if(!fd) - { - SCWrite(self->pCon,"ERROR: cannot open header description file",eError); - return 0; - } - - /* loop through description file and act along the way */ - while(fgets(pBuffer,511,fd) != NULL) - { - pPtr = strstr(pBuffer,"!!VAR("); - if(pPtr) /* handle a Sics variable */ - { - /* extract the name */ - pName = pPtr + 6; /* first char of name */ - *pPtr = '\0'; /* this is the starter of the line */ - pPtr = pName; - while( (*pPtr != '\0') && (*pPtr != ')') ) - { - pPtr++; - } - *pPtr = '\0'; - /* find the variable */ - pCom = FindCommand(self->pSics,pName); - if(!pCom) - { - sprintf(pError,"ERROR: variable %s NOT found",pName); - SCWrite(self->pCon,pError,eError); - continue; - } - pVar = (pSicsVariable)pCom->pData; - if(!pVar) - { - sprintf(pError,"ERROR: variable %s NOT found",pName); - SCWrite(self->pCon,pError,eError); - continue; - } - switch(pVar->eType) - { - case veFloat: - sprintf(pError,"%f",pVar->fVal); - break; - case veInt: - sprintf(pError,"%d",pVar->iVal); - break; - case veText: - sprintf(pError,"%s",pVar->text); - break; - } - /* finally write */ - fprintf(self->fd,"%s %s\n",pBuffer,pError); - continue; - }/* end variable */ -/*------- Drivable */ - pPtr = strstr(pBuffer,"!!DRIV("); - if(pPtr) - { - /* extract the name */ - pName = pPtr + 7; /* first char of name */ - *pPtr = '\0'; /* this is the starter of the line */ - pPtr = pName; - while( (*pPtr != '\0') && (*pPtr != ')') ) - { - pPtr++; - } - *pPtr = '\0'; - /* find the variable */ - pCom = FindCommand(self->pSics,pName); - if(!pCom) - { - sprintf(pError,"ERROR: variable %s NOT found",pName); - SCWrite(self->pCon,pError,eError); - continue; - } - pDum = (pDummy)pCom->pData; - if(!pDum) - { - sprintf(pError,"ERROR: variable %s is NOT drivable",pName); - SCWrite(self->pCon,pError,eError); - continue; - } - pDriv = (pIDrivable)pDum->pDescriptor->GetInterface(pDum,DRIVEID); - if(!pDriv) - { - sprintf(pError,"ERROR: variable %s is NOT drivable",pName); - SCWrite(self->pCon,pError,eError); - continue; - } - fVal = pDriv->GetValue(pDum,self->pCon); - fprintf(self->fd,"%s %f\n",pBuffer,fVal); - continue; - } /* end drive */ -/*------- zero point */ - pPtr = strstr(pBuffer,"!!ZERO("); - if(pPtr) - { - /* extract the name */ - pName = pPtr + 7; /* first char of name */ - *pPtr = '\0'; /* this is the starter of the line */ - pPtr = pName; - while( (*pPtr != '\0') && (*pPtr != ')') ) - { - pPtr++; - } - *pPtr = '\0'; - /* find the motor */ - pMot = FindMotor(self->pSics,pName); - if(!pMot) - { - sprintf(pError,"ERROR: motor %s NOT found",pName); - SCWrite(self->pCon,pError,eError); - continue; - } - iRet = MotorGetPar(pMot,"softzero",&fVal); - if(!iRet) - { - SCWrite(self->pCon,"ERROR: failed to read zero point",eError); - continue; - } - fprintf(self->fd,"%s %f\n",pBuffer,fVal); - continue; - } /* end zero point */ -/* ------- date */ - pPtr = strstr(pBuffer,"!!DATE!!"); - if(pPtr) - { - *pPtr = '\0'; - SNXFormatTime(pError,511); - fprintf(self->fd,"%s %s\n",pBuffer,pError); - continue; - } -/*-------- filename */ - pPtr = strstr(pBuffer,"!!FILE!!"); - if(pPtr) - { - *pPtr = '\0'; - fprintf(self->fd,"%s %s\n",pBuffer,self->pFile); - continue; - } +int WriteHeaderOld(pScanData self) +{ + int i, iRet; + FILE *fd; + char pBuffer[512], pError[512], *pPtr, *pName; + CommandList *pCom = NULL; + pSicsVariable pVar = NULL; + pDummy pDum = NULL; + pIDrivable pDriv = NULL; + float fVal; + pMotor pMot = NULL; + pVarEntry pScanVar = NULL; + void *pVoid = NULL; + + assert(self->pSics); + assert(self->pCon); + + /* open data file */ + self->fd = fopen(self->pFile, "w"); + if (!self->fd) { + SCWrite(self->pCon, "ERROR: cannot write data file", eError); + return 0; + } + + /* open header description file */ + fd = fopen(self->pHeaderFile, "r"); + if (!fd) { + SCWrite(self->pCon, "ERROR: cannot open header description file", + eError); + return 0; + } + + /* loop through description file and act along the way */ + while (fgets(pBuffer, 511, fd) != NULL) { + pPtr = strstr(pBuffer, "!!VAR("); + if (pPtr) { /* handle a Sics variable */ + /* extract the name */ + pName = pPtr + 6; /* first char of name */ + *pPtr = '\0'; /* this is the starter of the line */ + pPtr = pName; + while ((*pPtr != '\0') && (*pPtr != ')')) { + pPtr++; + } + *pPtr = '\0'; + /* find the variable */ + pCom = FindCommand(self->pSics, pName); + if (!pCom) { + sprintf(pError, "ERROR: variable %s NOT found", pName); + SCWrite(self->pCon, pError, eError); + continue; + } + pVar = (pSicsVariable) pCom->pData; + if (!pVar) { + sprintf(pError, "ERROR: variable %s NOT found", pName); + SCWrite(self->pCon, pError, eError); + continue; + } + switch (pVar->eType) { + case veFloat: + sprintf(pError, "%f", pVar->fVal); + break; + case veInt: + sprintf(pError, "%d", pVar->iVal); + break; + case veText: + sprintf(pError, "%s", pVar->text); + break; + } + /* finally write */ + fprintf(self->fd, "%s %s\n", pBuffer, pError); + continue; + } + /* end variable */ + /*------- Drivable */ + pPtr = strstr(pBuffer, "!!DRIV("); + if (pPtr) { + /* extract the name */ + pName = pPtr + 7; /* first char of name */ + *pPtr = '\0'; /* this is the starter of the line */ + pPtr = pName; + while ((*pPtr != '\0') && (*pPtr != ')')) { + pPtr++; + } + *pPtr = '\0'; + /* find the variable */ + pCom = FindCommand(self->pSics, pName); + if (!pCom) { + sprintf(pError, "ERROR: variable %s NOT found", pName); + SCWrite(self->pCon, pError, eError); + continue; + } + pDum = (pDummy) pCom->pData; + if (!pDum) { + sprintf(pError, "ERROR: variable %s is NOT drivable", pName); + SCWrite(self->pCon, pError, eError); + continue; + } + pDriv = (pIDrivable) pDum->pDescriptor->GetInterface(pDum, DRIVEID); + if (!pDriv) { + sprintf(pError, "ERROR: variable %s is NOT drivable", pName); + SCWrite(self->pCon, pError, eError); + continue; + } + fVal = pDriv->GetValue(pDum, self->pCon); + fprintf(self->fd, "%s %f\n", pBuffer, fVal); + continue; + } + /* end drive */ + /*------- zero point */ + pPtr = strstr(pBuffer, "!!ZERO("); + if (pPtr) { + /* extract the name */ + pName = pPtr + 7; /* first char of name */ + *pPtr = '\0'; /* this is the starter of the line */ + pPtr = pName; + while ((*pPtr != '\0') && (*pPtr != ')')) { + pPtr++; + } + *pPtr = '\0'; + /* find the motor */ + pMot = FindMotor(self->pSics, pName); + if (!pMot) { + sprintf(pError, "ERROR: motor %s NOT found", pName); + SCWrite(self->pCon, pError, eError); + continue; + } + iRet = MotorGetPar(pMot, "softzero", &fVal); + if (!iRet) { + SCWrite(self->pCon, "ERROR: failed to read zero point", eError); + continue; + } + fprintf(self->fd, "%s %f\n", pBuffer, fVal); + continue; + } + /* end zero point */ + /* ------- date */ + pPtr = strstr(pBuffer, "!!DATE!!"); + if (pPtr) { + *pPtr = '\0'; + SNXFormatTime(pError, 511); + fprintf(self->fd, "%s %s\n", pBuffer, pError); + continue; + } +/*-------- filename */ + pPtr = strstr(pBuffer, "!!FILE!!"); + if (pPtr) { + *pPtr = '\0'; + fprintf(self->fd, "%s %s\n", pBuffer, self->pFile); + continue; + } /*------------ scanzero */ - pPtr = strstr(pBuffer,"!!SCANZERO!!"); - if(pPtr) - { - *pPtr = '\0'; - /* write zero point of first scan variable if motor */ - DynarGet(self->pScanVar,0,&pVoid); - pScanVar = (pVarEntry)pVoid; - if(pScanVar) - { - pMot = NULL; - pMot = FindMotor(self->pSics,ScanVarName(pScanVar)); - if(pMot != NULL) - { - MotorGetPar(pMot,"softzero",&fVal); - fprintf(self->fd,"%s zero = %8.3f\n",ScanVarName(pScanVar), - fVal); - } - } + pPtr = strstr(pBuffer, "!!SCANZERO!!"); + if (pPtr) { + *pPtr = '\0'; + /* write zero point of first scan variable if motor */ + DynarGet(self->pScanVar, 0, &pVoid); + pScanVar = (pVarEntry) pVoid; + if (pScanVar) { + pMot = NULL; + pMot = FindMotor(self->pSics, ScanVarName(pScanVar)); + if (pMot != NULL) { + MotorGetPar(pMot, "softzero", &fVal); + fprintf(self->fd, "%s zero = %8.3f\n", ScanVarName(pScanVar), + fVal); } + } + } /* --------- plain text */ - fprintf(self->fd,"%s",pBuffer); - } /* end while */ + fprintf(self->fd, "%s", pBuffer); + } /* end while */ - /* remember position for seeking to it for writing data */ - self->lPos = ftell(self->fd); + /* remember position for seeking to it for writing data */ + self->lPos = ftell(self->fd); + + fclose(fd); + fclose(self->fd); + self->fd = NULL; + return 1; +} - fclose(fd); - fclose(self->fd); - self->fd = NULL; - return 1; - } /*--------------------------------------------------------------------------*/ - int WriteScanPoints(pScanData self, int iPoint) - { - int i, i2; - char pLine[512], pItem[30], pInfo[1024], pSteps[256]; - pVarEntry pVar = NULL; - pCountEntry pData = NULL; - void *pPtr = NULL; - - assert(self->pCon); - assert(self->pSics); +int WriteScanPoints(pScanData self, int iPoint) +{ + int i, i2; + char pLine[512], pItem[30], pInfo[1024], pSteps[256]; + pVarEntry pVar = NULL; + pCountEntry pData = NULL; + void *pPtr = NULL; - /* reopen file */ - self->fd = fopen(self->pFile,"r+"); - if(!self->fd) - { - SCWrite(self->pCon, - "ERROR: Failed to reopen scan file, aborting scan", - eLogError); - return 0; - } + assert(self->pCon); + assert(self->pSics); - - /* jump to end of header */ - fseek(self->fd,self->lPos, SEEK_SET); - if(self->iChannel != 0) - { - fprintf(self->fd,"WARNING: Scanning monitor %d\n",self->iChannel); + /* reopen file */ + self->fd = fopen(self->pFile, "r+"); + if (!self->fd) { + SCWrite(self->pCon, + "ERROR: Failed to reopen scan file, aborting scan", eLogError); + return 0; + } + + + /* jump to end of header */ + fseek(self->fd, self->lPos, SEEK_SET); + if (self->iChannel != 0) { + fprintf(self->fd, "WARNING: Scanning monitor %d\n", self->iChannel); + } + + /* make the data header */ + sprintf(pLine, "%-4s ", "NP"); + strcpy(pInfo, "Scanning Variables: "); + strcpy(pSteps, "Steps: "); + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + sprintf(pItem, "%-9.9s ", ScanVarName(pVar)); + strcat(pLine, pItem); + sprintf(pItem, "%s, ", ScanVarName(pVar)); + strcat(pInfo, pItem); + sprintf(pItem, "%f ", ScanVarStep(pVar)); + strcat(pSteps, pItem); } - - /* make the data header */ - sprintf(pLine,"%-4s ","NP"); - strcpy(pInfo,"Scanning Variables: "); - strcpy(pSteps,"Steps: "); - for(i = 0; i < self->iScanVar;i++) - { - DynarGet(self->pScanVar,i,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - sprintf(pItem,"%-9.9s ",ScanVarName(pVar)); - strcat(pLine,pItem); - sprintf(pItem,"%s, ",ScanVarName(pVar)); - strcat(pInfo,pItem); - sprintf(pItem,"%f ",ScanVarStep(pVar)); - strcat(pSteps,pItem); + } + strcat(pLine, " Counts "); + strcat(pLine, "Monitor1 "); + strcat(pLine, "Monitor2 "); + strcat(pLine, "Monitor3 "); + strcat(pLine, "Time "); + strcat(pInfo, pSteps); + sprintf(pItem, "\n%d Points,", self->iNP); + strcat(pInfo, pItem); + if (self->iMode == eTimer) { + strcat(pInfo, " Mode: Timer,"); + } else { + strcat(pInfo, " Mode: Monitor,"); + } + sprintf(pItem, " Preset %f", self->fPreset); + strcat(pInfo, pItem); + fprintf(self->fd, "%s\n", pInfo); + fprintf(self->fd, "%s\n", pLine); + + /* now the scan points */ + for (i = 0; i < self->iCounts; i++) { + sprintf(pLine, "%-4d ", i); + /* print vars */ + for (i2 = 0; i2 < self->iScanVar; i2++) { + DynarGet(self->pScanVar, i2, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + sprintf(pItem, "%-9.3f ", GetScanVarPos(pVar, i)); + strcat(pLine, pItem); } } - strcat(pLine," Counts "); - strcat(pLine,"Monitor1 "); - strcat(pLine,"Monitor2 "); - strcat(pLine,"Monitor3 "); - strcat(pLine,"Time "); - strcat(pInfo,pSteps); - sprintf(pItem,"\n%d Points,",self->iNP); - strcat(pInfo,pItem); - if(self->iMode == eTimer) - { - strcat(pInfo," Mode: Timer,"); + /* print Counts & Monitor */ + DynarGet(self->pCounts, i, &pPtr); + pData = (pCountEntry) pPtr; + if (pData) { + sprintf(pItem, " %-11ld ", pData->lCount); + strcat(pLine, pItem); + sprintf(pItem, "%-11ld ", pData->Monitors[0]); + strcat(pLine, pItem); + sprintf(pItem, "%-11ld ", pData->Monitors[1]); + strcat(pLine, pItem); + sprintf(pItem, "%-11ld ", pData->Monitors[2]); + strcat(pLine, pItem); + sprintf(pItem, "%-5.1f ", pData->fTime); + strcat(pLine, pItem); } - else - { - strcat(pInfo," Mode: Monitor,"); - } - sprintf(pItem," Preset %f",self->fPreset); - strcat(pInfo,pItem); - fprintf(self->fd,"%s\n",pInfo); - fprintf(self->fd,"%s\n",pLine); - - /* now the scan points */ - for(i = 0; i < self->iCounts; i++) - { - sprintf(pLine,"%-4d ",i); - /* print vars */ - for(i2 = 0; i2 < self->iScanVar; i2++) - { - DynarGet(self->pScanVar,i2,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - sprintf(pItem,"%-9.3f ",GetScanVarPos(pVar,i)); - strcat(pLine,pItem); - } - } - /* print Counts & Monitor */ - DynarGet(self->pCounts,i,&pPtr); - pData = (pCountEntry)pPtr; - if(pData) - { - sprintf(pItem," %-11ld ",pData->lCount); - strcat(pLine,pItem); - sprintf(pItem,"%-11ld ",pData->Monitors[0]); - strcat(pLine,pItem); - sprintf(pItem,"%-11ld ",pData->Monitors[1]); - strcat(pLine,pItem); - sprintf(pItem,"%-11ld ",pData->Monitors[2]); - strcat(pLine,pItem); - sprintf(pItem,"%-5.1f ",pData->fTime); - strcat(pLine,pItem); - } - fprintf(self->fd,"%s\n",pLine); - } - - /* done */ - fprintf(self->fd,"END-OF-DATA\n"); - fclose(self->fd); - self->fd = NULL; - return 1; - } + fprintf(self->fd, "%s\n", pLine); + } + + /* done */ + fprintf(self->fd, "END-OF-DATA\n"); + fclose(self->fd); + self->fd = NULL; + return 1; +} + /*------------------------------------------------------------------------*/ -int prepareDataFile(pScanData self){ +int prepareDataFile(pScanData self) +{ char *pPtr = NULL; char pBueffel[512]; - /* allocate a new data file */ - pPtr = ScanMakeFileName(pServ->pSics,self->pCon); - if(!pPtr) - { - SCWrite(self->pCon, - "ERROR: cannot allocate new data filename, Scan aborted", - eLogError); - self->pCon = NULL; - self->pSics = NULL; - return 0; - } - snprintf(pBueffel,511,"Writing data file: %s ...",pPtr); - SCWrite(self->pCon,pBueffel,eLog); - strcpy(self->pFile,pPtr); - free(pPtr); - return 1; + /* allocate a new data file */ + pPtr = ScanMakeFileName(pServ->pSics, self->pCon); + if (!pPtr) { + SCWrite(self->pCon, + "ERROR: cannot allocate new data filename, Scan aborted", + eLogError); + self->pCon = NULL; + self->pSics = NULL; + return 0; + } + snprintf(pBueffel, 511, "Writing data file: %s ...", pPtr); + SCWrite(self->pCon, pBueffel, eLog); + strcpy(self->pFile, pPtr); + free(pPtr); + return 1; } -/*--------------------------------------------------------------------------*/ - int PrepareScan(pScanData self) - { - pVarEntry pVar = NULL; - void *pDings; - int i, iRet; - float fVal; - char pBueffel[512]; - char pMessage[1024]; - - assert(self); - assert(self->pCon); - - /* check boundaries of scan variables and allocate storage */ - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pDings); - pVar = (pVarEntry)pDings; - if(pVar) - { - iRet = CheckScanVar(pVar,self->pCon,self->iNP - 1); - if(!iRet) - { - return 0; - } - InitScanVar(pVar); - } - else - { - SCWrite(self->pCon, - "WARNING: Internal error, no scan variable, I try to continue", - eLog); - } - pVar = NULL; - } /* end for */ - - /* configure counter */ - SetCounterMode((pCounter)self->pCounterData,self->iMode); - SetCounterPreset((pCounter)self->pCounterData, self->fPreset); - self->iCounts = 0; - if(!prepareDataFile(self)){ - return 0; - } - - return 1; - } /*--------------------------------------------------------------------------*/ - int SilentPrepare(pScanData self) - { - pVarEntry pVar = NULL; - void *pDings; - int i, iRet; - float fVal; - char pBueffel[512]; - char pMessage[1024]; - - assert(self); - assert(self->iNP > 0); - assert(self->pCon); - - /* check boundaries of scan variables and allocate storage */ - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pDings); - pVar = (pVarEntry)pDings; - if(pVar) - { - iRet = CheckScanVar(pVar,self->pCon,self->iNP); - if(!iRet) - { - return 0; - } - InitScanVar(pVar); - } - else - { - SCWrite(self->pCon, - "WARNING: Internal error, no scan variable, I try to continue", - eLog); - } - pVar = NULL; - } /* end for */ - - /* configure counter */ - SetCounterMode((pCounter)self->pCounterData,self->iMode); - SetCounterPreset((pCounter)self->pCounterData, self->fPreset); - self->iCounts = 0; +int PrepareScan(pScanData self) +{ + pVarEntry pVar = NULL; + void *pDings; + int i, iRet; + float fVal; + char pBueffel[512]; + char pMessage[1024]; + + assert(self); + assert(self->pCon); + + /* check boundaries of scan variables and allocate storage */ + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pDings); + pVar = (pVarEntry) pDings; + if (pVar) { + iRet = CheckScanVar(pVar, self->pCon, self->iNP - 1); + if (!iRet) { + return 0; + } + InitScanVar(pVar); + } else { + SCWrite(self->pCon, + "WARNING: Internal error, no scan variable, I try to continue", + eLog); + } + pVar = NULL; + } /* end for */ + + /* configure counter */ + SetCounterMode((pCounter) self->pCounterData, self->iMode); + SetCounterPreset((pCounter) self->pCounterData, self->fPreset); + self->iCounts = 0; + + if (!prepareDataFile(self)) { + return 0; + } + + return 1; +} - return 1; - } /*--------------------------------------------------------------------------*/ - int NonCheckPrepare(pScanData self) - { - pVarEntry pVar = NULL; - void *pDings; - int i, iRet; - char pBueffel[512]; - char pMessage[1024]; - - assert(self); - assert(self->iNP > 0); - assert(self->pCon); - - /* allocate storage for scan variables */ - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pDings); - pVar = (pVarEntry)pDings; - if(pVar) - { - InitScanVar(pVar); - } - else - { - SCWrite(self->pCon, - "WARNING: Internal error, no scan variable, I try to continue", - eLog); - } - pVar = NULL; - } /* end for */ - - /* configure counter */ - SetCounterMode((pCounter)self->pCounterData,self->iMode); - SetCounterPreset((pCounter)self->pCounterData, self->fPreset); - self->iCounts = 0; +int SilentPrepare(pScanData self) +{ + pVarEntry pVar = NULL; + void *pDings; + int i, iRet; + float fVal; + char pBueffel[512]; + char pMessage[1024]; + + assert(self); + assert(self->iNP > 0); + assert(self->pCon); + + /* check boundaries of scan variables and allocate storage */ + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pDings); + pVar = (pVarEntry) pDings; + if (pVar) { + iRet = CheckScanVar(pVar, self->pCon, self->iNP); + if (!iRet) { + return 0; + } + InitScanVar(pVar); + } else { + SCWrite(self->pCon, + "WARNING: Internal error, no scan variable, I try to continue", + eLog); + } + pVar = NULL; + } /* end for */ + + /* configure counter */ + SetCounterMode((pCounter) self->pCounterData, self->iMode); + SetCounterPreset((pCounter) self->pCounterData, self->fPreset); + self->iCounts = 0; + + return 1; +} + +/*--------------------------------------------------------------------------*/ +int NonCheckPrepare(pScanData self) +{ + pVarEntry pVar = NULL; + void *pDings; + int i, iRet; + char pBueffel[512]; + char pMessage[1024]; + + assert(self); + assert(self->iNP > 0); + assert(self->pCon); + + /* allocate storage for scan variables */ + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pDings); + pVar = (pVarEntry) pDings; + if (pVar) { + InitScanVar(pVar); + } else { + SCWrite(self->pCon, + "WARNING: Internal error, no scan variable, I try to continue", + eLog); + } + pVar = NULL; + } /* end for */ + + /* configure counter */ + SetCounterMode((pCounter) self->pCounterData, self->iMode); + SetCounterPreset((pCounter) self->pCounterData, self->fPreset); + self->iCounts = 0; + + if (!prepareDataFile(self)) { + return 0; + } + + return 1; +} - if(!prepareDataFile(self)){ - return 0; - } - - return 1; - } /*------------------------------------------------------------------------*/ - static int CollectScanDataIntern(pScanData self, int iPoint, int jochenFlag) - { - pVarEntry pVar = NULL; - void *pDings; - int i, iRet, status; - char pStatus[2024], pItem[20]; - char pHead[2024]; - float fVal; - CountEntry sCount; +static int CollectScanDataIntern(pScanData self, int iPoint, + int jochenFlag) +{ + pVarEntry pVar = NULL; + void *pDings; + int i, iRet, status; + char pStatus[2024], pItem[20]; + char pHead[2024]; + float fVal; + CountEntry sCount; - assert(self); - assert(self->pCon); - InitCountEntry(&sCount); + assert(self); + assert(self->pCon); + InitCountEntry(&sCount); - /* prepare output header */ - sprintf(pHead,"%-4.4s ","NP"); - sprintf(pStatus,"%-4d ",iPoint); - - /* loop over all scan variables */ - status = 1; - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pDings); - pVar = (pVarEntry)pDings; - if(pVar) - { - fVal = pVar->pInter->GetValue(pVar->pObject,self->pCon); - AppendScanVar(pVar,fVal); - sprintf(pItem,"%-9.9s ",ScanVarName(pVar)); - strcat(pHead,pItem); - sprintf(pItem,"%-9.3f ",fVal); - strcat(pStatus,pItem); - } - } - - /* store counter data */ - sCount = CollectCounterData(self); + /* prepare output header */ + sprintf(pHead, "%-4.4s ", "NP"); + sprintf(pStatus, "%-4d ", iPoint); - /* - format header - */ - strcat(pHead,"Counts "); + /* loop over all scan variables */ + status = 1; + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pDings); + pVar = (pVarEntry) pDings; + if (pVar) { + fVal = pVar->pInter->GetValue(pVar->pObject, self->pCon); + AppendScanVar(pVar, fVal); + sprintf(pItem, "%-9.9s ", ScanVarName(pVar)); + strcat(pHead, pItem); + sprintf(pItem, "%-9.3f ", fVal); + strcat(pStatus, pItem); + } + } - sprintf(pItem,"%-14ld ",sCount.lCount); - strcat(pStatus,pItem); + /* store counter data */ + sCount = CollectCounterData(self); - strcat(pHead,"Monitor1 "); - sprintf(pItem,"%-11ld ",sCount.Monitors[0]); - strcat(pStatus,pItem); - strcat(pHead,"Monitor2 "); - sprintf(pItem,"%-11ld ",sCount.Monitors[1]); - strcat(pStatus,pItem); - strcat(pHead,"Monitor3 "); - sprintf(pItem,"%-11ld ",sCount.Monitors[2]); - strcat(pStatus,pItem); - strcat(pHead,"Time "); - sprintf(pItem,"%-6.1f",sCount.fTime); - strcat(pStatus,pItem); + /* + format header + */ + strcat(pHead, "Counts "); - /* write progress */ - /* + sprintf(pItem, "%-14ld ", sCount.lCount); + strcat(pStatus, pItem); + + strcat(pHead, "Monitor1 "); + sprintf(pItem, "%-11ld ", sCount.Monitors[0]); + strcat(pStatus, pItem); + strcat(pHead, "Monitor2 "); + sprintf(pItem, "%-11ld ", sCount.Monitors[1]); + strcat(pStatus, pItem); + strcat(pHead, "Monitor3 "); + sprintf(pItem, "%-11ld ", sCount.Monitors[2]); + strcat(pStatus, pItem); + strcat(pHead, "Time "); + sprintf(pItem, "%-6.1f", sCount.fTime); + strcat(pStatus, pItem); + + /* write progress */ + /* strcat(pHead,"\r\n"); strcat(pStatus,"\r\n"); - */ - SCWrite(self->pCon,pHead,eLog); - SCWrite(self->pCon,pStatus,eLog); - - return 1; - } + */ + SCWrite(self->pCon, pHead, eLog); + SCWrite(self->pCon, pStatus, eLog); + + return 1; +} + /*---------------------------------------------------------------------------*/ - int CollectScanData(pScanData self, int iPoint) - { - return CollectScanDataIntern(self,iPoint,0); - } +int CollectScanData(pScanData self, int iPoint) +{ + return CollectScanDataIntern(self, iPoint, 0); +} + /*------------------------------------------------------------------------*/ - int CollectSilent(pScanData self, int iPoint) - { - pVarEntry pVar = NULL; - void *pDings; - int i, iRet, status, jochenFlag = 1; - float fVal; - CountEntry sCount; +int CollectSilent(pScanData self, int iPoint) +{ + pVarEntry pVar = NULL; + void *pDings; + int i, iRet, status, jochenFlag = 1; + float fVal; + CountEntry sCount; - assert(self); - assert(self->pCon); - InitCountEntry(&sCount); + assert(self); + assert(self->pCon); + InitCountEntry(&sCount); + + /* loop over all scan variables */ + status = 1; + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pDings); + pVar = (pVarEntry) pDings; + if (pVar) { + fVal = pVar->pInter->GetValue(pVar->pObject, self->pCon); + AppendScanVar(pVar, fVal); + } + } + + /* store counter data */ + sCount = CollectCounterData(self); + + return 1; +} - /* loop over all scan variables */ - status = 1; - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pDings); - pVar = (pVarEntry)pDings; - if(pVar) - { - fVal = pVar->pInter->GetValue(pVar->pObject,self->pCon); - AppendScanVar(pVar,fVal); - } - } - - /* store counter data */ - sCount = CollectCounterData(self); - - return 1; - } /*--------------------------------------------------------------------------*/ - static int StartToDrive(pScanData self, int iPoint) - { - pVarEntry pVar = NULL; - void *pDings; - int i, iRet, status; +static int StartToDrive(pScanData self, int iPoint) +{ + pVarEntry pVar = NULL; + void *pDings; + int i, iRet, status; - assert(self); - assert(self->pCon); - - - /* loop over all scan variables */ - status = 1; - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pDings); - pVar = (pVarEntry)pDings; - if(pVar) - { - iRet = StartScanVar(pVar,self->pCon,iPoint); - if(!iRet) - { - status = 0; - break; - } - } - } - return status; - } -/*------------------------------------------------------------------------*/ - int ScanDrive(pScanData self, int iPoint) - { - int iRet; - long lTask; - int status; + assert(self); + assert(self->pCon); - iRet = StartToDrive(self,iPoint); - if(!iRet) - { - SCWrite(self->pCon,"ERROR: Cannot Drive, Scan aborted",eLogError); - status = 0; + + /* loop over all scan variables */ + status = 1; + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pDings); + pVar = (pVarEntry) pDings; + if (pVar) { + iRet = StartScanVar(pVar, self->pCon, iPoint); + if (!iRet) { + status = 0; + break; + } } - else - { - status = 1; - } - /* wait for finish */ - lTask = GetDevexecID(pServ->pExecutor); - if(lTask > 0) - { - TaskWait(pServ->pTasker,lTask); - } - return status; } + return status; +} + /*------------------------------------------------------------------------*/ - int ScanFastDrive(pScanData self, int iPoint) - { - int iRet; - long lTask; - int status; +int ScanDrive(pScanData self, int iPoint) +{ + int iRet; + long lTask; + int status; - /* - * drive the first point normally, otherwise there is to much intensity - * in the first data point from the long time driving to the start - * position. - */ - if(iPoint == 0) - { - return ScanDrive(self,iPoint); - } - - iRet = StartToDrive(self,iPoint); - if(!iRet) - { - SCWrite(self->pCon,"ERROR: Cannot Drive, Scan aborted",eLogError); - status = 0; - } - else - { - status = 1; - } - return status; + iRet = StartToDrive(self, iPoint); + if (!iRet) { + SCWrite(self->pCon, "ERROR: Cannot Drive, Scan aborted", eLogError); + status = 0; + } else { + status = 1; } + /* wait for finish */ + lTask = GetDevexecID(pServ->pExecutor); + if (lTask > 0) { + TaskWait(pServ->pTasker, lTask); + } + return status; +} + +/*------------------------------------------------------------------------*/ +int ScanFastDrive(pScanData self, int iPoint) +{ + int iRet; + long lTask; + int status; + + /* + * drive the first point normally, otherwise there is to much intensity + * in the first data point from the long time driving to the start + * position. + */ + if (iPoint == 0) { + return ScanDrive(self, iPoint); + } + + iRet = StartToDrive(self, iPoint); + if (!iRet) { + SCWrite(self->pCon, "ERROR: Cannot Drive, Scan aborted", eLogError); + status = 0; + } else { + status = 1; + } + return status; +} + /*--------------------------------------------------------------------------*/ - int ScanCount(pScanData self, int iPoint) - { - pDummy pDum; - int iRet; - long lTask; +int ScanCount(pScanData self, int iPoint) +{ + pDummy pDum; + int iRet; + long lTask; - pDum = (pDummy)self->pCounterData; - iRet = StartDevice(pServ->pExecutor, - "ScanCounter", - pDum->pDescriptor, - self->pCounterData, - self->pCon, - self->fPreset); - if(!iRet) - { - SCWrite(self->pCon,"ERROR: Cannot Count, Scan aborted",eLogError); - return 0; - } - SetStatus(eCounting); - /* wait for finish */ - lTask = GetDevexecID(pServ->pExecutor); - if(lTask > 0); - { - TaskWait(pServ->pTasker,lTask); - } - return 1; + pDum = (pDummy) self->pCounterData; + iRet = StartDevice(pServ->pExecutor, + "ScanCounter", + pDum->pDescriptor, + self->pCounterData, self->pCon, self->fPreset); + if (!iRet) { + SCWrite(self->pCon, "ERROR: Cannot Count, Scan aborted", eLogError); + return 0; } + SetStatus(eCounting); + /* wait for finish */ + lTask = GetDevexecID(pServ->pExecutor); + if (lTask > 0); + { + TaskWait(pServ->pTasker, lTask); + } + return 1; +} + /*====================== script invocation functions ====================*/ -static pDynString GetStandardInvocation(pScanData self, char *function){ +static pDynString GetStandardInvocation(pScanData self, char *function) +{ pDynString result = NULL; char value[132]; - result = CreateDynString(80,80); - if(result == NULL){ - SCWrite(self->pCon,"ERROR: out of memory in scan invocation",eLogError); + result = CreateDynString(80, 80); + if (result == NULL) { + SCWrite(self->pCon, "ERROR: out of memory in scan invocation", + eLogError); return NULL; } - if(StringDictGet(self->scanFunctions,function,value,131) != 1){ - snprintf(value,131,"ERROR: scan function %s not found",function); - SCWrite(self->pCon,value,eLogError); + if (StringDictGet(self->scanFunctions, function, value, 131) != 1) { + snprintf(value, 131, "ERROR: scan function %s not found", function); + SCWrite(self->pCon, value, eLogError); DeleteDynString(result); return NULL; } - DynStringCopy(result,value); - DynStringConcatChar(result,' '); + DynStringCopy(result, value); + DynStringConcatChar(result, ' '); DynStringConcat(result, self->objectName); - DynStringConcatChar(result,' '); + DynStringConcatChar(result, ' '); value[0] = '\0'; - StringDictGet(self->scanFunctions,"userdata",value,131); - DynStringConcat(result,value); - DynStringConcatChar(result,' '); + StringDictGet(self->scanFunctions, "userdata", value, 131); + DynStringConcat(result, value); + DynStringConcatChar(result, ' '); return result; } + /*-----------------------------------------------------------------------*/ -static int StandardScriptInvoke(pScanData self, char *function){ +static int StandardScriptInvoke(pScanData self, char *function) +{ pDynString command = NULL; int status; - command = GetStandardInvocation(self,function); - if(command == NULL){ + command = GetStandardInvocation(self, function); + if (command == NULL) { return 0; } - status = InterpExecute(self->pSics, self->pCon, - GetCharArray(command)); + status = InterpExecute(self->pSics, self->pCon, GetCharArray(command)); DeleteDynString(command); - if(status != 1) { + if (status != 1) { return 0; } return status; } + /*-----------------------------------------------------------------------*/ -static int StandardScriptInvokeWithPoint(pScanData self, - char *function, int iPoint){ +static int StandardScriptInvokeWithPoint(pScanData self, + char *function, int iPoint) +{ pDynString command = NULL; int status; char pNumber[50]; - command = GetStandardInvocation(self,function); - if(command == NULL){ + command = GetStandardInvocation(self, function); + if (command == NULL) { return 0; } - snprintf(pNumber,49,"%d",iPoint); - DynStringConcat(command,pNumber); - status = InterpExecute(self->pSics, self->pCon, - GetCharArray(command)); + snprintf(pNumber, 49, "%d", iPoint); + DynStringConcat(command, pNumber); + status = InterpExecute(self->pSics, self->pCon, GetCharArray(command)); DeleteDynString(command); - if(status != 1) { + if (status != 1) { return 0; } return status; } + /*------------------------------------------------------------------------*/ -int ScriptWriteHeader(pScanData self){ - return StandardScriptInvoke(self,"writeheader"); +int ScriptWriteHeader(pScanData self) +{ + return StandardScriptInvoke(self, "writeheader"); } + /*---------------------------------------------------------------------*/ -int ScriptPrepareScan(pScanData self){ +int ScriptPrepareScan(pScanData self) +{ /* configure counter */ - SetCounterMode((pCounter)self->pCounterData,self->iMode); - SetCounterPreset((pCounter)self->pCounterData, self->fPreset); + SetCounterMode((pCounter) self->pCounterData, self->iMode); + SetCounterPreset((pCounter) self->pCounterData, self->fPreset); self->iCounts = 0; - return StandardScriptInvoke(self,"prepare"); + return StandardScriptInvoke(self, "prepare"); } + /*-----------------------------------------------------------------------*/ -int ScriptScanDrive(pScanData self, int iPoint){ - return StandardScriptInvokeWithPoint(self,"drive",iPoint); +int ScriptScanDrive(pScanData self, int iPoint) +{ + return StandardScriptInvokeWithPoint(self, "drive", iPoint); } + /*------------------------------------------------------------------------*/ -int ScriptScanCount(pScanData self, int iPoint){ +int ScriptScanCount(pScanData self, int iPoint) +{ pDynString command = NULL; int status; char pNumber[50]; - command = GetStandardInvocation(self,"count"); - if(command == NULL){ + command = GetStandardInvocation(self, "count"); + if (command == NULL) { return 0; } - snprintf(pNumber,49,"%d",iPoint); - DynStringConcat(command,pNumber); - if(self->iMode == eTimer){ - DynStringConcat(command," timer "); + snprintf(pNumber, 49, "%d", iPoint); + DynStringConcat(command, pNumber); + if (self->iMode == eTimer) { + DynStringConcat(command, " timer "); } else { - DynStringConcat(command," monitor "); + DynStringConcat(command, " monitor "); } - snprintf(pNumber,49," %f ", self->fPreset); - DynStringConcat(command,pNumber); + snprintf(pNumber, 49, " %f ", self->fPreset); + DynStringConcat(command, pNumber); - status = InterpExecute(self->pSics, self->pCon, - GetCharArray(command)); + status = InterpExecute(self->pSics, self->pCon, GetCharArray(command)); DeleteDynString(command); - if(status != 1) { + if (status != 1) { return 0; } return status; } + /*-------------------------------------------------------------------------*/ -int ScriptScanCollect(pScanData self, int iPoint){ - return StandardScriptInvokeWithPoint(self,"collect",iPoint); +int ScriptScanCollect(pScanData self, int iPoint) +{ + return StandardScriptInvokeWithPoint(self, "collect", iPoint); } + /*----------------------------------------------------------------------*/ -int ScriptWriteScanPoints(pScanData self, int iPoint){ - return StandardScriptInvokeWithPoint(self,"writepoint",iPoint); +int ScriptWriteScanPoints(pScanData self, int iPoint) +{ + return StandardScriptInvokeWithPoint(self, "writepoint", iPoint); } + /*--------------------------------------------------------------------*/ -int ScriptScanFinish(pScanData self){ - return StandardScriptInvoke(self,"finish"); +int ScriptScanFinish(pScanData self) +{ + return StandardScriptInvoke(self, "finish"); } + /*---------------------------------------------------------------------*/ -void ConfigureScript(pScanData self){ +void ConfigureScript(pScanData self) +{ assert(self); self->PrepareScan = ScriptPrepareScan; @@ -1107,60 +1055,62 @@ void ConfigureScript(pScanData self){ self->ScanCount = ScriptScanCount; self->CollectScanData = ScriptScanCollect; } + /*======================================================================*/ -int StandardScanWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int StandardScanWrapper(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ pScanData self = NULL; int iPoint; char pError[132]; - if(argc < 4) { - SCWrite(pCon,"ERROR: not enough arguments to stdscan",eError); + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough arguments to stdscan", eError); return 0; } strtolower(argv[1]); - self = (pScanData)FindCommandData(pSics,argv[2],"ScanObject"); - if(self == NULL){ - SCWrite(pCon,"ERROR: scan object not found",eError); + self = (pScanData) FindCommandData(pSics, argv[2], "ScanObject"); + if (self == NULL) { + SCWrite(pCon, "ERROR: scan object not found", eError); return 0; } - if(self->pCon == NULL){ + if (self->pCon == NULL) { self->pCon = pCon; } - if(strcmp(argv[1],"writeheader") == 0){ + if (strcmp(argv[1], "writeheader") == 0) { return WriteHeader(self); - } else if(strcmp(argv[1],"prepare") == 0){ + } else if (strcmp(argv[1], "prepare") == 0) { return PrepareScan(self); - } else if(strcmp(argv[1],"finish") == 0) { + } else if (strcmp(argv[1], "finish") == 0) { return 1; } /* - from here on we need a scan point - */ - if(argc < 5) { - SCWrite(pCon,"ERROR: not enough arguments to stdscan",eError); + from here on we need a scan point + */ + if (argc < 5) { + SCWrite(pCon, "ERROR: not enough arguments to stdscan", eError); return 0; } iPoint = atoi(argv[4]); - if(strcmp(argv[1],"drive") == 0){ - return ScanDrive(self,iPoint); - } else if(strcmp(argv[1],"count") == 0){ - return ScanCount(self,iPoint); - } else if(strcmp(argv[1],"collect") == 0){ - return CollectScanData(self,iPoint); - } else if(strcmp(argv[1],"silentcollect") == 0){ - return CollectSilent(self,iPoint); - } else if(strcmp(argv[1],"writepoint") == 0){ - return WriteScanPoints(self,iPoint); + if (strcmp(argv[1], "drive") == 0) { + return ScanDrive(self, iPoint); + } else if (strcmp(argv[1], "count") == 0) { + return ScanCount(self, iPoint); + } else if (strcmp(argv[1], "collect") == 0) { + return CollectScanData(self, iPoint); + } else if (strcmp(argv[1], "silentcollect") == 0) { + return CollectSilent(self, iPoint); + } else if (strcmp(argv[1], "writepoint") == 0) { + return WriteScanPoints(self, iPoint); } else { - snprintf(pError,131,"ERROR: subcommand %s to stdscan not found", - argv[1]); - SCWrite(pCon,pError,eError); + snprintf(pError, 131, "ERROR: subcommand %s to stdscan not found", + argv[1]); + SCWrite(pCon, pError, eError); return 0; } - return 0; + return 0; } diff --git a/stdscan.h b/stdscan.h index d0030c9e..69430cf8 100644 --- a/stdscan.h +++ b/stdscan.h @@ -14,98 +14,98 @@ /** * make a filename according to SICS rules for this scan */ - char *ScanMakeFileName(SicsInterp *pSics, SConnection *pCon); +char *ScanMakeFileName(SicsInterp * pSics, SConnection * pCon); /* * write the header bits from the template */ - void WriteTemplate(FILE *fd, FILE *temp, char *filename, pScanData pScan, - SConnection *pCon, SicsInterp *pSics); +void WriteTemplate(FILE * fd, FILE * temp, char *filename, pScanData pScan, + SConnection * pCon, SicsInterp * pSics); /** * write the header of the scan file */ - int WriteHeader(pScanData self); +int WriteHeader(pScanData self); /** * WriteScanPoints is called for each point to write the scan data * to screen and to file. - */ - int WriteScanPoints(pScanData self, int iPoint); + */ +int WriteScanPoints(pScanData self, int iPoint); /** * Called before the scan to prepare. The default implementation * checks if all scan positions are available and configures the * counter. */ - int PrepareScan(pScanData self); +int PrepareScan(pScanData self); /** * allocate a new data file */ - int prepareDataFile(pScanData self); +int prepareDataFile(pScanData self); /** * second version of PrepareScan which does not check scan limits - */ - int NonCheckPrepare(pScanData self); + */ +int NonCheckPrepare(pScanData self); /** * prepare for a scan without complaining... */ - int SilentPrepare(pScanData self); +int SilentPrepare(pScanData self); /** * ScanDrive handles driving to the scan point iPoint. - */ - int ScanDrive(pScanData self, int iPoint); + */ +int ScanDrive(pScanData self, int iPoint); /** * ScanFastDrive starts driving to the scan point iPoint, but * does not wait. Use this for implementing slightly faster * scans. - */ - int ScanFastDrive(pScanData self, int iPoint); + */ +int ScanFastDrive(pScanData self, int iPoint); /** * ScanCount is called at each scan step to do the counting. */ - int ScanCount(pScanData self, int iPoint); +int ScanCount(pScanData self, int iPoint); /** * CollectScanData stores the scans count results into * the scan data structure and prints the information about the * scan progress. */ - int CollectScanData(pScanData self, int iPoint); - int CollectScanDataJochen(pScanData self, int iPoint); - int CollectSilent(pScanData self, int iPoint); +int CollectScanData(pScanData self, int iPoint); +int CollectScanDataJochen(pScanData self, int iPoint); +int CollectSilent(pScanData self, int iPoint); /*===================================================================*/ /** * Script invocation for writing the scan header. */ - int ScriptWriteHeader(pScanData self); +int ScriptWriteHeader(pScanData self); /** * Script writing each scan point */ - int ScriptWriteScanPoints(pScanData self, int iPoint); +int ScriptWriteScanPoints(pScanData self, int iPoint); /** * Script preparation of the scan. */ - int ScriptPrepareScan(pScanData self); +int ScriptPrepareScan(pScanData self); /** * Script driving to a scan point */ - int ScriptScanDrive(pScanData self, int iPoint); +int ScriptScanDrive(pScanData self, int iPoint); /** * Script counting a scan point */ - int ScriptScanCount(pScanData self, int iPoint); +int ScriptScanCount(pScanData self, int iPoint); /** * Script collecting scan data for each scan point */ - int ScriptScanCollect(pScanData self, int iPoint); +int ScriptScanCollect(pScanData self, int iPoint); /** * ScriptScanFinish invokes a script after the scan has finished */ - int ScriptScanFinish(pScanData self); +int ScriptScanFinish(pScanData self); /** * ConfigureScript assigns the script invocation functions for * scan */ - void ConfigureScript(pScanData self); +void ConfigureScript(pScanData self); /*=====================================================================*/ - int StandardScanWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int StandardScanWrapper(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); #endif diff --git a/stptok.c b/stptok.c index 7000e83b..fc742acb 100644 --- a/stptok.c +++ b/stptok.c @@ -15,50 +15,36 @@ char *stptok(const char *s, char *tok, size_t toklen, char *brk) { - char *lim, *b; + char *lim, *b; - if (!*s) - return NULL; + if (!*s) + return NULL; - lim = tok + toklen - 1; - while ( *s && tok < lim ) - { - for ( b = brk; *b; b++ ) - { - if ( *s == *b ) - { - *tok = 0; - return (char *)(s+1); - } - } - *tok++ = *s++; + lim = tok + toklen - 1; + while (*s && tok < lim) { + for (b = brk; *b; b++) { + if (*s == *b) { + *tok = 0; + return (char *) (s + 1); } - *tok = 0; - return (char *)s; + } + *tok++ = *s++; + } + *tok = 0; + return (char *) s; } + /*---------------------------------------------------------------------------*/ - char *SkipSpace(char *pText) - { - char *pRes; - - pRes = pText; - while(*pRes) - { - if( (*pRes != ' ') && (*pRes != '\t') && (*pRes != '\r') ) - { - return pRes; - } - pRes++; - } - return NULL; - } - - - - - - - - - +char *SkipSpace(char *pText) +{ + char *pRes; + pRes = pText; + while (*pRes) { + if ((*pRes != ' ') && (*pRes != '\t') && (*pRes != '\r')) { + return pRes; + } + pRes++; + } + return NULL; +} diff --git a/stptok.h b/stptok.h index f1935ea7..6e03e451 100644 --- a/stptok.h +++ b/stptok.h @@ -8,11 +8,9 @@ ** full, and will always leave the buffer null-terminated. It will ** return a pointer to the first non-breaking character after the one ** that stopped the scan. -*/ - +*/ #ifndef STPSTPTOK #define STPSTPTOK - char *stptok(const char *s, char *tok, size_t toklen, char *brk); #endif diff --git a/strdup.c b/strdup.c index 6b88b1f3..288f717e 100644 --- a/strdup.c +++ b/strdup.c @@ -9,21 +9,20 @@ #include - char *Fortify_STRDUP(const char *in, char *file,unsigned long lLine) - { - char *pResult = NULL; - - if(!in) - return NULL; - - pResult = (char *)Fortify_malloc((strlen(in)+2)*sizeof(char),file,lLine); - if(!pResult) - { - return NULL; - } - else - { - strcpy(pResult,in); - } - return pResult; +char *Fortify_STRDUP(const char *in, char *file, unsigned long lLine) +{ + char *pResult = NULL; + + if (!in) + return NULL; + + pResult = + (char *) Fortify_malloc((strlen(in) + 2) * sizeof(char), file, + lLine); + if (!pResult) { + return NULL; + } else { + strcpy(pResult, in); } + return pResult; +} diff --git a/stringdict.c b/stringdict.c index 16767163..36892844 100644 --- a/stringdict.c +++ b/stringdict.c @@ -46,261 +46,239 @@ #include "stringdict.h" /*-------------------------------------------------------------------------*/ - typedef struct __StringDict { - int iList; - int iTraverse; - } StringDict; +typedef struct __StringDict { + int iList; + int iTraverse; +} StringDict; - typedef struct { - char *name; - char *value; - } SDE, *pSDE; -/*-------------------------------------------------------------------------*/ - pStringDict CreateStringDict(void) - { - pStringDict pNew = NULL; - - pNew = (pStringDict)malloc(sizeof(StringDict)); - if(!pNew) - { - return NULL; - } - pNew->iList = LLDcreate(sizeof(SDE)); - if(pNew->iList < 0) - { - free(pNew); - return NULL; - } - pNew->iTraverse = 0; - return pNew; - } -/*------------------------------------------------------------------------*/ - void DeleteStringDict(pStringDict self) - { - int iRet; - SDE sVal; - - assert(self); - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sVal); - if(sVal.name) - { - free(sVal.name); - } - if(sVal.value) - { - free(sVal.value); - } - iRet = LLDnodePtr2Next(self->iList); - } - LLDdelete(self->iList); - free(self); - } +typedef struct { + char *name; + char *value; +} SDE, *pSDE; /*-------------------------------------------------------------------------*/ - int StringDictAddPair(pStringDict self, char *name, char *value) - { - SDE sVal; - - assert(self); - sVal.name = NULL; - sVal.value = NULL; - - sVal.name = strdup(name); - sVal.value = strdup(value); - - LLDnodeAppendFrom(self->iList,&sVal); - return 1; +pStringDict CreateStringDict(void) +{ + pStringDict pNew = NULL; + + pNew = (pStringDict) malloc(sizeof(StringDict)); + if (!pNew) { + return NULL; } -/*---------------------------------------------------------------------------*/ - int StringDictExists(pStringDict self, char *name) - { - SDE sVal; - int iRet; - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sVal); - if(strcmp(sVal.name,name) == 0) - { - return 1; - } - iRet = LLDnodePtr2Next(self->iList); - } - return 0; - } -/*--------------------------------------------------------------------------*/ - int StringDictUpdate(pStringDict self, char *name, char *value) - { - SDE sVal; - int iRet; - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sVal); - if(strcmp(sVal.name,name) == 0) - { - if(sVal.value) - { - free(sVal.value); - } - sVal.value = strdup(value); - LLDnodeDataFrom(self->iList,&sVal); - return 1; - } - iRet = LLDnodePtr2Next(self->iList); - } - return 0; - } -/*--------------------------------------------------------------------------*/ - int StringDictGet(pStringDict self, char *name, char *pResult, int iLen) - { - SDE sVal; - int iRet; - - if(pResult != NULL) - { - pResult[0] = '\0'; - } - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sVal); - if(strcmp(sVal.name,name) == 0) - { - if(pResult == NULL) - { - return strlen(sVal.value) + 1; /* for \0 */ - } - else - { - strncpy(pResult,sVal.value,iLen); - /* strncpy is not guaranteed to be '\0' terminated */ - if (iLen > 0 && pResult[iLen-1] != '\0') { - /* overflow */ - pResult[iLen-1] = '\0'; - } - return 1; - } - } - iRet = LLDnodePtr2Next(self->iList); - } - return 0; - } -/*--------------------------------------------------------------------------*/ - char *StringDictGetShort(pStringDict self, char *name) - { - SDE sVal; - int iRet; - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sVal); - if(strcmp(sVal.name,name) == 0) - { - return sVal.value; - } - iRet = LLDnodePtr2Next(self->iList); - } - return NULL; - } -/*------------------------------------------------------------------------*/ - int StringDictDelete(pStringDict self, char *name) - { - SDE sVal; - int iRet; - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&sVal); - if(strcmp(sVal.name,name) == 0) - { - if(sVal.name) - { - free(sVal.name); - } - if(sVal.value) - { - free(sVal.value); - } - LLDnodeDelete(self->iList); - return 1; - } - iRet = LLDnodePtr2Next(self->iList); - } - return 0; - } + pNew->iList = LLDcreate(sizeof(SDE)); + if (pNew->iList < 0) { + free(pNew); + return NULL; + } + pNew->iTraverse = 0; + return pNew; +} + /*------------------------------------------------------------------------*/ - int StringDictGetAsNumber(pStringDict self, char *name, float *fVal) - { - char pBueffel[80]; - int iRet; - SDE sVal; - - assert(self); - - iRet = StringDictGet(self,name,pBueffel,79); - if(!iRet) - { - return iRet; - } - - iRet = sscanf(pBueffel,"%f",fVal); - if(iRet != 1) - { - return 0; - } - return 1; - } -/*-------------------------------------------------------------------------*/ - const char *StringDictGetNext(pStringDict self, char *pValue, int iValLen) - { - int iRet; - SDE sVal; - - assert(self); - - if(self->iTraverse) - { - iRet = LLDnodePtr2Next(self->iList); - if(iRet == 0) /* exhausted */ - { - self->iTraverse = 0; - return NULL; - } - else - { - LLDnodeDataTo(self->iList,&sVal); - strncpy(pValue,sVal.value,iValLen); - return sVal.name; - } - } - else /* start a new one */ - { - iRet = LLDnodePtr2First(self->iList); - if(iRet == 0) - { - return NULL; - } - else - { - self->iTraverse = 1; - LLDnodeDataTo(self->iList,&sVal); - strncpy(pValue,sVal.value,iValLen); - return sVal.name; - } - } - return NULL; +void DeleteStringDict(pStringDict self) +{ + int iRet; + SDE sVal; + + assert(self); + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sVal); + if (sVal.name) { + free(sVal.name); + } + if (sVal.value) { + free(sVal.value); + } + iRet = LLDnodePtr2Next(self->iList); } + LLDdelete(self->iList); + free(self); +} + /*-------------------------------------------------------------------------*/ - void StringDictKillScan(pStringDict self) - { - assert(self); - self->iTraverse = 0; +int StringDictAddPair(pStringDict self, char *name, char *value) +{ + SDE sVal; + + assert(self); + sVal.name = NULL; + sVal.value = NULL; + + sVal.name = strdup(name); + sVal.value = strdup(value); + + LLDnodeAppendFrom(self->iList, &sVal); + return 1; +} + +/*---------------------------------------------------------------------------*/ +int StringDictExists(pStringDict self, char *name) +{ + SDE sVal; + int iRet; + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sVal); + if (strcmp(sVal.name, name) == 0) { + return 1; + } + iRet = LLDnodePtr2Next(self->iList); } + return 0; +} + +/*--------------------------------------------------------------------------*/ +int StringDictUpdate(pStringDict self, char *name, char *value) +{ + SDE sVal; + int iRet; + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sVal); + if (strcmp(sVal.name, name) == 0) { + if (sVal.value) { + free(sVal.value); + } + sVal.value = strdup(value); + LLDnodeDataFrom(self->iList, &sVal); + return 1; + } + iRet = LLDnodePtr2Next(self->iList); + } + return 0; +} + +/*--------------------------------------------------------------------------*/ +int StringDictGet(pStringDict self, char *name, char *pResult, int iLen) +{ + SDE sVal; + int iRet; + + if (pResult != NULL) { + pResult[0] = '\0'; + } + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sVal); + if (strcmp(sVal.name, name) == 0) { + if (pResult == NULL) { + return strlen(sVal.value) + 1; /* for \0 */ + } else { + strncpy(pResult, sVal.value, iLen); + /* strncpy is not guaranteed to be '\0' terminated */ + if (iLen > 0 && pResult[iLen - 1] != '\0') { + /* overflow */ + pResult[iLen - 1] = '\0'; + } + return 1; + } + } + iRet = LLDnodePtr2Next(self->iList); + } + return 0; +} + +/*--------------------------------------------------------------------------*/ +char *StringDictGetShort(pStringDict self, char *name) +{ + SDE sVal; + int iRet; + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sVal); + if (strcmp(sVal.name, name) == 0) { + return sVal.value; + } + iRet = LLDnodePtr2Next(self->iList); + } + return NULL; +} + +/*------------------------------------------------------------------------*/ +int StringDictDelete(pStringDict self, char *name) +{ + SDE sVal; + int iRet; + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &sVal); + if (strcmp(sVal.name, name) == 0) { + if (sVal.name) { + free(sVal.name); + } + if (sVal.value) { + free(sVal.value); + } + LLDnodeDelete(self->iList); + return 1; + } + iRet = LLDnodePtr2Next(self->iList); + } + return 0; +} + +/*------------------------------------------------------------------------*/ +int StringDictGetAsNumber(pStringDict self, char *name, float *fVal) +{ + char pBueffel[80]; + int iRet; + SDE sVal; + + assert(self); + + iRet = StringDictGet(self, name, pBueffel, 79); + if (!iRet) { + return iRet; + } + + iRet = sscanf(pBueffel, "%f", fVal); + if (iRet != 1) { + return 0; + } + return 1; +} + +/*-------------------------------------------------------------------------*/ +const char *StringDictGetNext(pStringDict self, char *pValue, int iValLen) +{ + int iRet; + SDE sVal; + + assert(self); + + if (self->iTraverse) { + iRet = LLDnodePtr2Next(self->iList); + if (iRet == 0) { /* exhausted */ + self->iTraverse = 0; + return NULL; + } else { + LLDnodeDataTo(self->iList, &sVal); + strncpy(pValue, sVal.value, iValLen); + return sVal.name; + } + } else { /* start a new one */ + + iRet = LLDnodePtr2First(self->iList); + if (iRet == 0) { + return NULL; + } else { + self->iTraverse = 1; + LLDnodeDataTo(self->iList, &sVal); + strncpy(pValue, sVal.value, iValLen); + return sVal.name; + } + } + return NULL; +} + +/*-------------------------------------------------------------------------*/ +void StringDictKillScan(pStringDict self) +{ + assert(self); + self->iTraverse = 0; +} diff --git a/stringdict.h b/stringdict.h index 9d20ce9b..20395537 100644 --- a/stringdict.h +++ b/stringdict.h @@ -13,31 +13,29 @@ #ifndef SICSSTRINGDICT #define SICSSTRINGDICT - typedef struct __StringDict *pStringDict; +typedef struct __StringDict *pStringDict; #line 6 "stringdict.w" - pStringDict CreateStringDict(void); - void DeleteStringDict(pStringDict self); +pStringDict CreateStringDict(void); +void DeleteStringDict(pStringDict self); + +int StringDictAddPair(pStringDict self, char *name, char *value); +int StringDictExists(pStringDict self, char *name); +int StringDictUpdate(pStringDict self, char *name, char *value); +int StringDictGet(pStringDict self, char *name, char *pResult, int iLen); - int StringDictAddPair(pStringDict self, char *name, char *value); - int StringDictExists(pStringDict self, char *name); - int StringDictUpdate(pStringDict self, char *name, char *value); - int StringDictGet(pStringDict self, char *name, char *pResult, int iLen); - /* the result of StringDictGetShort is only valid as long that the entry is not changed */ - char *StringDictGetShort(pStringDict self, char *name); - - int StringDictGetAsNumber(pStringDict self, char *name, float *fVal); - int StringDictDelete(pStringDict self, char *name); +char *StringDictGetShort(pStringDict self, char *name); - const char *StringDictGetNext(pStringDict self, - char *pValue, int iValLen); - void StringDictKillScan(pStringDict self); +int StringDictGetAsNumber(pStringDict self, char *name, float *fVal); +int StringDictDelete(pStringDict self, char *name); + +const char *StringDictGetNext(pStringDict self, char *pValue, int iValLen); +void StringDictKillScan(pStringDict self); #line 68 "stringdict.w" #endif - diff --git a/strrepl.c b/strrepl.c index 777e4872..92f86c6b 100644 --- a/strrepl.c +++ b/strrepl.c @@ -28,16 +28,16 @@ char *StrReplace(char *Str, char *OldStr, char *NewStr) { - int OldLen, NewLen; - char *p, *q; + int OldLen, NewLen; + char *p, *q; - if(NULL == (p = strstr(Str, OldStr))) - return p; - OldLen = strlen(OldStr); - NewLen = strlen(NewStr); - memmove(q = p+NewLen, p+OldLen, strlen(p+OldLen)+1); - memcpy(p, NewStr, NewLen); - return q; + if (NULL == (p = strstr(Str, OldStr))) + return p; + OldLen = strlen(OldStr); + NewLen = strlen(NewStr); + memmove(q = p + NewLen, p + OldLen, strlen(p + OldLen) + 1); + memcpy(p, NewStr, NewLen); + return q; } #ifdef TEST @@ -54,22 +54,19 @@ char *StrReplace(char *Str, char *OldStr, char *NewStr) int main(int argc, char *argv[]) { - char buf[200]; - char *Start; + char buf[200]; + char *Start; - if(argc != 3) - exit(1); + if (argc != 3) + exit(1); - /* Repeat until all occurences replaced */ + /* Repeat until all occurences replaced */ - while(NULL != (Start = gets(buf))) - { - while(NULL != (Start = StrReplace(Start, argv[1], argv[2]))) - ; - printf("%s\n", buf); - } - return 0; + while (NULL != (Start = gets(buf))) { + while (NULL != (Start = StrReplace(Start, argv[1], argv[2]))); + printf("%s\n", buf); + } + return 0; } -#endif - +#endif diff --git a/synchronize.c b/synchronize.c index dd21137c..256d56a7 100644 --- a/synchronize.c +++ b/synchronize.c @@ -24,8 +24,8 @@ Some file statics which hold the connection parameters ------------------------------------------------------------------------*/ static char *hostname, *looser, *password, *syncFile; -static int port; -static mkChannel *connection = NULL; +static int port; +static mkChannel *connection = NULL; /*-----------------------------------------------------------------------*/ static void syncLogin(void) { @@ -33,27 +33,23 @@ static void syncLogin(void) char pBueffel[2048], pRead[80]; /* - connect - */ + connect + */ connection = NETConnect(hostname, port); - for(i = 0; i < 10; i++) - { - NETRead(connection,pBueffel,1020,10); /* 10 ms M.Z */ - if(strstr(pBueffel,"OK") != NULL) - { + for (i = 0; i < 10; i++) { + NETRead(connection, pBueffel, 1020, 10); /* 10 ms M.Z */ + if (strstr(pBueffel, "OK") != NULL) { break; } SicsWait(1); } - if(connection != NULL) - { + if (connection != NULL) { /* - try a login - */ - sprintf(pBueffel,"%s %s\n", looser, password); - test = NETWrite(connection,pBueffel,strlen(pBueffel)); - if(test != 1) - { + try a login + */ + sprintf(pBueffel, "%s %s\n", looser, password); + test = NETWrite(connection, pBueffel, strlen(pBueffel)); + if (test != 1) { printf("Failed at writing user/password\n"); NETClosePort(connection); free(connection); @@ -61,248 +57,219 @@ static void syncLogin(void) } pBueffel[0] = '\0'; - for(i = 0; i < 60; i++) - { - memset(pRead,0,80); - test = NETRead(connection,pRead,70,10); /* 10 ms M.Z. */ - if(test < 0) - { - NETClosePort(connection); - free(connection); - connection = NULL; + for (i = 0; i < 60; i++) { + memset(pRead, 0, 80); + test = NETRead(connection, pRead, 70, 10); /* 10 ms M.Z. */ + if (test < 0) { + NETClosePort(connection); + free(connection); + connection = NULL; + } else { + strcat(pBueffel, pRead); } - else - { - strcat(pBueffel,pRead); - } - if(strstr(pBueffel,"Login OK") == NULL) - { - test = 0; - } - else - { - test = 1; + if (strstr(pBueffel, "Login OK") == NULL) { + test = 0; + } else { + test = 1; break; } - SicsWait(1); + SicsWait(1); } - if(!test) - { - printf("Bad reply to login: %s\n",pBueffel); + if (!test) { + printf("Bad reply to login: %s\n", pBueffel); NETClosePort(connection); free(connection); connection = NULL; } } } + /*---------------------------------------------------------------------*/ static void killSync(void *pData) { - if(connection) - { + if (connection) { NETClosePort(connection); free(connection); } - if(hostname) + if (hostname) free(hostname); - if(looser) + if (looser) free(looser); - if(password) + if (password) free(password); - if(syncFile) + if (syncFile) free(syncFile); } + /*----------------------------------------------------------------------*/ -int MakeSync(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) +int MakeSync(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) { char pBueffel[256]; int iRet; /* - check arguments: we need host, port, user and passwd - */ - if(argc < 5) - { + check arguments: we need host, port, user and passwd + */ + if (argc < 5) { SCWrite(pCon, - "ERROR: need parameters: host port user passwd : for sync creation", - eError); + "ERROR: need parameters: host port user passwd : for sync creation", + eError); return 0; } /* - copy parameters - */ + copy parameters + */ hostname = strdup(argv[1]); port = atof(argv[2]); looser = strdup(argv[3]); password = strdup(argv[4]); - if(argc > 5) - { + if (argc > 5) { syncFile = strdup(argv[5]); - } - else - { + } else { syncFile = NULL; } pServ->simMode = 1; /* - add the command to the Interpreter - */ - iRet = AddCommand(pSics,"sync",Synchronize,killSync,NULL); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command sync not created"); - killSync(NULL); - SCWrite(pCon,pBueffel,eError); - return 0; + add the command to the Interpreter + */ + iRet = AddCommand(pSics, "sync", Synchronize, killSync, NULL); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command sync not created"); + killSync(NULL); + SCWrite(pCon, pBueffel, eError); + return 0; } return 1; } + /*----------------------------------------------------------------------*/ -int Synchronize(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) +int Synchronize(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) { char pBueffel[2048]; char pRead[80]; - int test,i; + int test, i; SConnection *internalCon = NULL; int try; - + try = 2; tryagain: try--; /* - check for connection - */ - if(connection == NULL) - { + check for connection + */ + if (connection == NULL) { syncLogin(); - if(connection == NULL) - { - sprintf(pBueffel,"ERROR: failed to connect to %s, %d for sync 'ing", - hostname, port); - SCWrite(pCon,pBueffel, eError); + if (connection == NULL) { + sprintf(pBueffel, "ERROR: failed to connect to %s, %d for sync 'ing", + hostname, port); + SCWrite(pCon, pBueffel, eError); return 0; - } + } } /* - first tell the remote server to backup - */ + first tell the remote server to backup + */ SetStatusFixed(eBatch); - strcpy(pBueffel,"transact syncbackup"); - if(syncFile != NULL) - { - strcat(pBueffel," "); - strcat(pBueffel,syncFile); + strcpy(pBueffel, "transact syncbackup"); + if (syncFile != NULL) { + strcat(pBueffel, " "); + strcat(pBueffel, syncFile); } - strcat(pBueffel,"\n"); - test = NETWrite(connection,pBueffel,strlen(pBueffel)); - if(test != 1) - { + strcat(pBueffel, "\n"); + test = NETWrite(connection, pBueffel, strlen(pBueffel)); + if (test != 1) { NETClosePort(connection); free(connection); connection = NULL; ClearFixedStatus(eEager); - if (try > 0) goto tryagain; - SCWrite(pCon,"ERROR: Failed to contact main SICS server",eError); + if (try > 0) + goto tryagain; + SCWrite(pCon, "ERROR: Failed to contact main SICS server", eError); return 0; } /* - wait 60 seconds for correct message - */ - pServ->simMode = 0; /* bug fix: SicsWait returns right away if this would be - left at normal. Reset after loop - */ + wait 60 seconds for correct message + */ + pServ->simMode = 0; /* bug fix: SicsWait returns right away if this would be + left at normal. Reset after loop + */ pBueffel[0] = '\0'; - for(i = 0; i < 60; i++) - { - pRead[0] = '\0'; - test = NETRead(connection,pRead,75,20); /* 20 ms M.Z. */ - if(test < 0) - { - NETClosePort(connection); - free(connection); - connection = NULL; - ClearFixedStatus(eEager); - pServ->simMode = 1; - if (try > 0) goto tryagain; - SCWrite(pCon,"ERROR: Failed to contact main SICS server",eError); - return 0; + for (i = 0; i < 60; i++) { + pRead[0] = '\0'; + test = NETRead(connection, pRead, 75, 20); /* 20 ms M.Z. */ + if (test < 0) { + NETClosePort(connection); + free(connection); + connection = NULL; + ClearFixedStatus(eEager); + pServ->simMode = 1; + if (try > 0) + goto tryagain; + SCWrite(pCon, "ERROR: Failed to contact main SICS server", eError); + return 0; + } else { + if (test > 0) { + strncat(pBueffel, pRead, 2047 - strlen(pBueffel)); } - else - { - if(test > 0) - { - strncat(pBueffel,pRead, 2047 - strlen(pBueffel)); - } - } - if(strstr(pBueffel,"TRANSACTIONFINISHED") != NULL) - { - test = 1; - break; - } - else - { - test = 0; - } - SicsWait(1); + } + if (strstr(pBueffel, "TRANSACTIONFINISHED") != NULL) { + test = 1; + break; + } else { + test = 0; + } + SicsWait(1); } pServ->simMode = 1; - if(!test) - { - SCWrite(pCon,"WARNING: sync server may not have exectued backup", + if (!test) { + SCWrite(pCon, "WARNING: sync server may not have exectued backup", eWarning); } - - /* - * relase the connection, this may be more stable - */ - NETClosePort(connection); - free(connection); - connection = NULL; - - - + /* - now read the backup file and we are done - */ + * relase the connection, this may be more stable + */ + NETClosePort(connection); + free(connection); + connection = NULL; + + + + /* + now read the backup file and we are done + */ internalCon = SCCreateDummyConnection(pSics); - if(internalCon == NULL) - { - SCWrite(pCon,"ERROR: out of memory in sync", - eError); + if (internalCon == NULL) { + SCWrite(pCon, "ERROR: out of memory in sync", eError); ClearFixedStatus(eEager); return 0; - + } - if(syncFile != NULL) - { - sprintf(pBueffel,"restore %s",syncFile); + if (syncFile != NULL) { + sprintf(pBueffel, "restore %s", syncFile); + } else { + strcpy(pBueffel, "restore"); } - else - { - strcpy(pBueffel,"restore"); - } - test = InterpExecute(pSics,internalCon,pBueffel); + test = InterpExecute(pSics, internalCon, pBueffel); SCDeleteConnection(internalCon); ClearFixedStatus(eEager); - if(test != 1) - { - SCWrite(pCon,"ERROR: Failed to read sync information",eError); + if (test != 1) { + SCWrite(pCon, "ERROR: Failed to read sync information", eError); return 0; } /* - tell everybody that we have sync'ed - */ - ServerWriteGlobal("Simulation Server has SYNCHRONIZED!",eWarning); + tell everybody that we have sync'ed + */ + ServerWriteGlobal("Simulation Server has SYNCHRONIZED!", eWarning); ServerWriteGlobal("Fixed motors may not have correct positions", - eWarning); + eWarning); return 1; } - diff --git a/synchronize.h b/synchronize.h index 02018cc2..c7dde3d0 100644 --- a/synchronize.h +++ b/synchronize.h @@ -10,10 +10,10 @@ #ifndef SICSSYNC #define SICSSYNC - int MakeSync(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int Synchronize(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeSync(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int Synchronize(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/tacov.c b/tacov.c index 805d7c6c..e0126ffd 100644 --- a/tacov.c +++ b/tacov.c @@ -8,8 +8,8 @@ /* Common Block Declarations */ struct { - integer inx; - real c1rx, c2rx, rmin, rmax, cl1r; + integer inx; + real c1rx, c2rx, rmin, rmax, cl1r; } curve_; #define curve_1 curve_ @@ -29,49 +29,61 @@ static doublereal c_b9 = 360.; /* SUBROUTINE HELM_CASE(HX,HY,HZ,P_IH,AKI,AKF,A4,QM,HELM,IER) */ /* SUBROUTINE FLIP_CASE(IF1,IF2,P_IH,F1V,F1H,F2V,F2H,AKI,AKF,IER) */ /* ----------------------------------------------------------------------- */ -/* Subroutine */ int t_conv__(real *ei, real *aki, real *ef, real *akf, real * - qhkl, real *en, real *hx, real *hy, real *hz, integer *if1, integer * - if2, logical *ldk, logical *ldh, logical *ldf, logical *lpa, real *dm, - real *da, real *helm, real *f1h, real *f1v, real *f2h, real *f2v, - real *f, integer *ifx, integer *iss, integer *ism, integer *isa, real - *t_a__, real *t_rm__, real *t_alm__, real *qm, logical *ldra, logical - *ldr_rm__, logical *ldr_alm__, real *p_ih__, real *c_ih__, integer * - ier) +/* Subroutine */ int t_conv__(real * ei, real * aki, real * ef, real * akf, + real * + qhkl, real * en, real * hx, real * hy, + real * hz, integer * if1, integer * if2, + logical * ldk, logical * ldh, logical * ldf, + logical * lpa, real * dm, real * da, + real * helm, real * f1h, real * f1v, + real * f2h, real * f2v, real * f, + integer * ifx, integer * iss, integer * ism, + integer * isa, real * t_a__, real * t_rm__, + real * t_alm__, real * qm, logical * ldra, + logical * ldr_rm__, logical * ldr_alm__, + real * p_ih__, real * c_ih__, integer * ier) { - /* System generated locals */ - doublereal d__1; + /* System generated locals */ + doublereal d__1; - /* Builtin functions */ - double sqrt(doublereal); + /* Builtin functions */ + double sqrt(doublereal); - /* Local variables */ - static doublereal edef[2], dakf, daki; - static integer imod; - extern /* Subroutine */ int sam_case__(doublereal *, doublereal *, - doublereal *, doublereal *, doublereal *, doublereal *, - doublereal *, integer *, integer *); - static integer i__; - static doublereal akdef[2]; - extern /* Subroutine */ int helm_case__(real *, real *, real *, real *, - real *, real *, real *, doublereal *, real *, real *, integer *); - static doublereal dqhkl[3]; - extern /* Subroutine */ int flip_case__(integer *, integer *, real *, - real *, real *, real *, real *, real *, real *, integer *); - static logical lmoan[2]; - static doublereal a1, a2, a3, a4, a5, a6; - static integer id; - static doublereal ra; - extern /* Subroutine */ int rl2spv_(doublereal *, doublereal *, - doublereal *, doublereal *, integer *); - static integer iq; - static doublereal rm; - static logical lqhkle; - extern /* Subroutine */ int erreso_(integer *, integer *); - static doublereal dda, ala, def, dei, ddm, alm, dqm; - extern /* Subroutine */ int ex_case__(doublereal *, integer *, doublereal - *, doublereal *, doublereal *, doublereal *, doublereal *, - integer *); - static doublereal dqt[3], dqs; + /* Local variables */ + static doublereal edef[2], dakf, daki; + static integer imod; + extern /* Subroutine */ int sam_case__(doublereal *, doublereal *, + doublereal *, doublereal *, + doublereal *, doublereal *, + doublereal *, integer *, + integer *); + static integer i__; + static doublereal akdef[2]; + extern /* Subroutine */ int helm_case__(real *, real *, real *, real *, + real *, real *, real *, + doublereal *, real *, real *, + integer *); + static doublereal dqhkl[3]; + extern /* Subroutine */ int flip_case__(integer *, integer *, real *, + real *, real *, real *, real *, + real *, real *, integer *); + static logical lmoan[2]; + static doublereal a1, a2, a3, a4, a5, a6; + static integer id; + static doublereal ra; + extern /* Subroutine */ int rl2spv_(doublereal *, doublereal *, + doublereal *, doublereal *, + integer *); + static integer iq; + static doublereal rm; + static logical lqhkle; + extern /* Subroutine */ int erreso_(integer *, integer *); + static doublereal dda, ala, def, dei, ddm, alm, dqm; + extern /* Subroutine */ int ex_case__(doublereal *, integer *, doublereal + *, doublereal *, doublereal *, + doublereal *, doublereal *, + integer *); + static doublereal dqt[3], dqs; /* ----------------------------------------------------------------------- */ @@ -112,67 +124,67 @@ static doublereal c_b9 = 360.; /* AND VARIABLE ENERGY IN EDEF(2) */ /* IF ISA IS NUL SET IFX TO 1 AND PUT EF,KF, EQUAL TO EI,KI */ - /* Parameter adjustments */ - --c_ih__; - --p_ih__; - --ldra; - --t_a__; - --ldk; - --qhkl; + /* Parameter adjustments */ + --c_ih__; + --p_ih__; + --ldra; + --t_a__; + --ldk; + --qhkl; - /* Function Body */ - imod = 3; - ddm = *dm; - dda = *da; - for (i__ = 1; i__ <= 2; ++i__) { - lmoan[i__ - 1] = FALSE_; - } - lqhkle = FALSE_; - for (iq = 5; iq <= 8; ++iq) { - lqhkle = lqhkle || ldk[iq]; - } - daki = *aki; - dakf = *akf; - if (*isa == 0) { - *ifx = 1; - } - edef[*ifx - 1] = *ei; - akdef[*ifx - 1] = *aki; - edef[3 - *ifx - 1] = *ef; - akdef[3 - *ifx - 1] = *akf; - if (*isa == 0) { - edef[1] = edef[0]; - akdef[1] = akdef[0]; - ldk[3] = TRUE_; - ldk[4] = TRUE_; - t_a__[5] = 0.f; - t_a__[6] = 0.f; - ldra[5] = TRUE_; - ldra[6] = TRUE_; - } + /* Function Body */ + imod = 3; + ddm = *dm; + dda = *da; + for (i__ = 1; i__ <= 2; ++i__) { + lmoan[i__ - 1] = FALSE_; + } + lqhkle = FALSE_; + for (iq = 5; iq <= 8; ++iq) { + lqhkle = lqhkle || ldk[iq]; + } + daki = *aki; + dakf = *akf; + if (*isa == 0) { + *ifx = 1; + } + edef[*ifx - 1] = *ei; + akdef[*ifx - 1] = *aki; + edef[3 - *ifx - 1] = *ef; + akdef[3 - *ifx - 1] = *akf; + if (*isa == 0) { + edef[1] = edef[0]; + akdef[1] = akdef[0]; + ldk[3] = TRUE_; + ldk[4] = TRUE_; + t_a__[5] = 0.f; + t_a__[6] = 0.f; + ldra[5] = TRUE_; + ldra[6] = TRUE_; + } /* ----------------------------------------------------------------------- */ /* FIRST TAKE IN ACCOUNT THE FIXED ENERGY PB */ - if (ldk[(*ifx << 1) - 1] || ldk[*ifx * 2]) { - lmoan[*ifx - 1] = TRUE_; - if (ldk[(*ifx << 1) - 1]) { - *ier = 1; - if (edef[0] < .1) { - goto L999; - } - *ier = 0; - akdef[0] = sqrt(edef[0] / *f); - } else { - *ier = 1; - if (akdef[0] < .1) { - goto L999; - } - *ier = 0; + if (ldk[(*ifx << 1) - 1] || ldk[*ifx * 2]) { + lmoan[*ifx - 1] = TRUE_; + if (ldk[(*ifx << 1) - 1]) { + *ier = 1; + if (edef[0] < .1) { + goto L999; + } + *ier = 0; + akdef[0] = sqrt(edef[0] / *f); + } else { + *ier = 1; + if (akdef[0] < .1) { + goto L999; + } + *ier = 0; /* Computing 2nd power */ - d__1 = akdef[0]; - edef[0] = *f * (d__1 * d__1); - } + d__1 = akdef[0]; + edef[0] = *f * (d__1 * d__1); } + } /* ----------------------------------------------------------------------- */ /* NOW TAKE IN ACCOUNT THE VARIABLE ENERGY PB */ /* VARIABLE ENERGUY IS DRIVEN EITHER EXPLICITLY */ @@ -187,131 +199,132 @@ static doublereal c_b9 = 360.; /* IF KF IS CONSTANT USE ALWAYS THE VALUE IN TARGET AND */ /* DO A DRIVE OF KF TO KEEP A5/A6 IN RIGHT POSITION */ - if (ldk[5 - (*ifx << 1)] || ldk[6 - (*ifx << 1)]) { - lmoan[3 - *ifx - 1] = TRUE_; - if (ldk[5 - (*ifx << 1)]) { - *ier = 1; - if (edef[1] < 1e-4) { - goto L999; - } - *ier = 0; - akdef[1] = sqrt(edef[1] / *f); - } else { - *ier = 1; - if (akdef[1] < 1e-4) { - goto L999; - } - *ier = 0; + if (ldk[5 - (*ifx << 1)] || ldk[6 - (*ifx << 1)]) { + lmoan[3 - *ifx - 1] = TRUE_; + if (ldk[5 - (*ifx << 1)]) { + *ier = 1; + if (edef[1] < 1e-4) { + goto L999; + } + *ier = 0; + akdef[1] = sqrt(edef[1] / *f); + } else { + *ier = 1; + if (akdef[1] < 1e-4) { + goto L999; + } + *ier = 0; /* Computing 2nd power */ - d__1 = akdef[1]; - edef[1] = *f * (d__1 * d__1); - } - *en = (3 - (*ifx << 1)) * (edef[0] - edef[1]); - } else if (lqhkle) { - lmoan[3 - *ifx - 1] = TRUE_; - edef[1] = edef[0] + ((*ifx << 1) - 3) * *en; - *ier = 1; - if (edef[1] < 1e-4) { - goto L999; - } - *ier = 0; - akdef[1] = sqrt(edef[1] / *f); + d__1 = akdef[1]; + edef[1] = *f * (d__1 * d__1); } + *en = (3 - (*ifx << 1)) * (edef[0] - edef[1]); + } else if (lqhkle) { + lmoan[3 - *ifx - 1] = TRUE_; + edef[1] = edef[0] + ((*ifx << 1) - 3) * *en; + *ier = 1; + if (edef[1] < 1e-4) { + goto L999; + } + *ier = 0; + akdef[1] = sqrt(edef[1] / *f); + } /* ----------------------------------------------------------------------- */ /* CALCULATE MONOCHROMATOR AND ANALYSER ANGLES */ - if (lmoan[0]) { - dei = edef[*ifx - 1]; - daki = akdef[*ifx - 1]; - ex_case__(&ddm, ism, &daki, &a1, &a2, &rm, &alm, ier); - if (*ier == 0) { - *aki = daki; - *ei = dei; - t_a__[1] = a1; - t_a__[2] = a2; - *t_rm__ = rm; - *t_alm__ = alm; - ldra[1] = TRUE_; - ldra[2] = TRUE_; - *ldr_rm__ = TRUE_; - *ldr_alm__ = TRUE_; - } else { - goto L999; - } + if (lmoan[0]) { + dei = edef[*ifx - 1]; + daki = akdef[*ifx - 1]; + ex_case__(&ddm, ism, &daki, &a1, &a2, &rm, &alm, ier); + if (*ier == 0) { + *aki = daki; + *ei = dei; + t_a__[1] = a1; + t_a__[2] = a2; + *t_rm__ = rm; + *t_alm__ = alm; + ldra[1] = TRUE_; + ldra[2] = TRUE_; + *ldr_rm__ = TRUE_; + *ldr_alm__ = TRUE_; + } else { + goto L999; } - if (lmoan[1]) { - def = edef[3 - *ifx - 1]; - dakf = akdef[3 - *ifx - 1]; - ex_case__(&dda, isa, &dakf, &a5, &a6, &ra, &ala, ier); - if (*ier == 0) { - *akf = dakf; - *ef = def; - t_a__[5] = a5; - t_a__[6] = a6; - ldra[5] = TRUE_; - ldra[6] = TRUE_; - } else { - goto L999; - } + } + if (lmoan[1]) { + def = edef[3 - *ifx - 1]; + dakf = akdef[3 - *ifx - 1]; + ex_case__(&dda, isa, &dakf, &a5, &a6, &ra, &ala, ier); + if (*ier == 0) { + *akf = dakf; + *ef = def; + t_a__[5] = a5; + t_a__[6] = a6; + ldra[5] = TRUE_; + ldra[6] = TRUE_; + } else { + goto L999; } + } /* ----------------------------------------------------------------------- */ /* USE (QH,QK,QL) TO CALCULATE A3 AND A4 */ /* CALCULATE Q1 AND Q2 IN SCATTERING PLANE */ - imod = 2; - if (lqhkle) { - for (id = 1; id <= 3; ++id) { - dqhkl[id - 1] = qhkl[id]; - } - rl2spv_(dqhkl, dqt, &dqm, &dqs, ier); - if (*ier != 0) { - goto L999; - } - sam_case__(dqt, &dqm, &dqs, &daki, &dakf, &a3, &a4, iss, ier); - if (*ier == 0) { - t_a__[3] = a3; - t_a__[4] = a4; - ldra[3] = TRUE_; - ldra[4] = TRUE_; - *qm = dqm; - } else { - goto L999; - } + imod = 2; + if (lqhkle) { + for (id = 1; id <= 3; ++id) { + dqhkl[id - 1] = qhkl[id]; } + rl2spv_(dqhkl, dqt, &dqm, &dqs, ier); + if (*ier != 0) { + goto L999; + } + sam_case__(dqt, &dqm, &dqs, &daki, &dakf, &a3, &a4, iss, ier); + if (*ier == 0) { + t_a__[3] = a3; + t_a__[4] = a4; + ldra[3] = TRUE_; + ldra[4] = TRUE_; + *qm = dqm; + } else { + goto L999; + } + } /* ----------------------------------------------------------------------- */ /* DEAL WITH FLIPPERS AND HELMOTZ COILS IF LPA */ - if (*lpa && (lmoan[0] || lmoan[1])) { - if (*ldf) { - flip_case__(if1, if2, &p_ih__[1], f1v, f1h, f2v, f2h, aki, akf, - ier); - } - if (*ldh) { - helm_case__(hx, hy, hz, &p_ih__[1], &c_ih__[1], aki, akf, &a4, qm, - helm, ier); - } + if (*lpa && (lmoan[0] || lmoan[1])) { + if (*ldf) { + flip_case__(if1, if2, &p_ih__[1], f1v, f1h, f2v, f2h, aki, akf, ier); } + if (*ldh) { + helm_case__(hx, hy, hz, &p_ih__[1], &c_ih__[1], aki, akf, &a4, qm, + helm, ier); + } + } /* ----------------------------------------------------------------------- */ L999: - if (*ier != 0) { - erreso_(&imod, ier); - } - return 0; -} /* t_conv__ */ + if (*ier != 0) { + erreso_(&imod, ier); + } + return 0; +} /* t_conv__ */ -/* Subroutine */ int ex_case__(doublereal *dx, integer *isx, doublereal *akx, - doublereal *ax1, doublereal *ax2, doublereal *rx, doublereal *alx, - integer *ier) +/* Subroutine */ int ex_case__(doublereal * dx, integer * isx, + doublereal * akx, + doublereal * ax1, doublereal * ax2, + doublereal * rx, doublereal * alx, + integer * ier) { - /* System generated locals */ - doublereal d__1, d__2; + /* System generated locals */ + doublereal d__1, d__2; - /* Builtin functions */ - double asin(doublereal), sin(doublereal), cos(doublereal), sqrt( - doublereal); + /* Builtin functions */ + double asin(doublereal), sin(doublereal), cos(doublereal), + sqrt(doublereal); - /* Local variables */ - static doublereal dcl1r, dc1rx, dc2rx, drmin, drmax, arg; + /* Local variables */ + static doublereal dcl1r, dc1rx, dc2rx, drmin, drmax, arg; /* ----------------------------------------------------------------------- */ /* CALCULATE ANGLES ON MONO/ANALYSER */ @@ -347,30 +360,30 @@ L999: /* ----------------------------------------------------------------------- */ /* INIT AND TEST */ - *ier = 0; - dc1rx = curve_1.c1rx; - dc2rx = curve_1.c2rx; - drmin = curve_1.rmin; - drmax = curve_1.rmax; - dcl1r = curve_1.cl1r; - if (*dx < .1f) { - *ier = 1; - } - if (*akx < .1f) { - *ier = 2; - } - arg = 3.1415926535897932384626433832795f / (*dx * *akx); - if (abs(arg) > 1.f) { - *ier = 3; - } - if (*ier != 0) { - goto L999; - } + *ier = 0; + dc1rx = curve_1.c1rx; + dc2rx = curve_1.c2rx; + drmin = curve_1.rmin; + drmax = curve_1.rmax; + dcl1r = curve_1.cl1r; + if (*dx < .1f) { + *ier = 1; + } + if (*akx < .1f) { + *ier = 2; + } + arg = 3.1415926535897932384626433832795f / (*dx * *akx); + if (abs(arg) > 1.f) { + *ier = 3; + } + if (*ier != 0) { + goto L999; + } /* ----------------------------------------------------------------------- */ /* CALCULATION OF THE TWO ANGLES */ - *ax1 = asin(arg) * *isx * 57.29577951308232087679815481410517f; - *ax2 = *ax1 * 2.; + *ax1 = asin(arg) * *isx * 57.29577951308232087679815481410517f; + *ax2 = *ax1 * 2.; /* ----------------------------------------------------------------------- */ /* CALCULATION OF MONO CURVATURE RM OR ANALYSER CURVATURE RA */ /* STANDARD LAW IS C1RX+C2RX/SIN(A1/RD) */ @@ -381,39 +394,45 @@ L999: /* RMIN=0. */ /* RMAX=20. */ /* IN1/IN3/IN12/IN14/IN20 CASE */ - if (curve_1.inx == 0) { + if (curve_1.inx == 0) { /* Computing MIN */ /* Computing MAX */ - d__2 = dc1rx + dc2rx / sin(abs(*ax1) / - 57.29577951308232087679815481410517f); - d__1 = max(d__2,drmin); - *rx = min(d__1,drmax); - } else { + d__2 = dc1rx + dc2rx / sin(abs(*ax1) / + 57.29577951308232087679815481410517f); + d__1 = max(d__2, drmin); + *rx = min(d__1, drmax); + } else { /* IN8 CASE */ - *alx = dcl1r / sin(*ax2 / 57.29577951308232087679815481410517f) * cos( - *ax2 / 57.29577951308232087679815481410517f); - *rx = dc2rx * sqrt(sin(*ax2 / 57.29577951308232087679815481410517f)) - - dc1rx; - } + *alx = + dcl1r / sin(*ax2 / 57.29577951308232087679815481410517f) * + cos(*ax2 / 57.29577951308232087679815481410517f); + *rx = dc2rx * sqrt(sin(*ax2 / 57.29577951308232087679815481410517f)) + - dc1rx; + } /* ----------------------------------------------------------------------- */ L999: - return 0; -} /* ex_case__ */ + return 0; +} /* ex_case__ */ /* ========================================================================= */ -/* Subroutine */ int sam_case__(doublereal *qt, doublereal *qm, doublereal * - qs, doublereal *aki, doublereal *akf, doublereal *ax3, doublereal * - ax4, integer *iss, integer *ier) +/* Subroutine */ int sam_case__(doublereal * qt, doublereal * qm, + doublereal * + qs, doublereal * aki, doublereal * akf, + doublereal * ax3, doublereal * ax4, + integer * iss, integer * ier) { - /* System generated locals */ - doublereal d__1, d__2; + /* System generated locals */ + doublereal d__1, d__2; - /* Builtin functions */ - double acos(doublereal), atan2(doublereal, doublereal), d_sign(doublereal - *, doublereal *), d_mod(doublereal *, doublereal *); + /* Builtin functions */ + double acos(doublereal), atan2(doublereal, doublereal), d_sign(doublereal + *, + doublereal + *), + d_mod(doublereal *, doublereal *); - /* Local variables */ - static doublereal arg, sax3; + /* Local variables */ + static doublereal arg, sax3; /* ----------------------------------------------------------------------- */ /* DEAL WITH SAMPLE ANGLES CALCULATION FROM Q VERTOR IN C-N PLANE */ @@ -438,39 +457,42 @@ L999: /* ----------------------------------------------------------------------- */ /* INIT AND TEST */ - /* Parameter adjustments */ - --qt; + /* Parameter adjustments */ + --qt; - /* Function Body */ - *ier = 0; - if (abs(*qs) < 1e-6 || abs(*qm) < .001) { - *ier = 3; - goto L999; - } + /* Function Body */ + *ier = 0; + if (abs(*qs) < 1e-6 || abs(*qm) < .001) { + *ier = 3; + goto L999; + } /* ----------------------------------------------------------------------- */ /* CALCULATE A3 AND MOVE IT INTHE -180 ,+180 INTERVAL */ /* Computing 2nd power */ - d__1 = *aki; + d__1 = *aki; /* Computing 2nd power */ - d__2 = *akf; - arg = (d__1 * d__1 + d__2 * d__2 - *qs) / (*aki * 2. * *akf); - if (abs(arg) > 1.) { - *ier = 4; - goto L999; - } else { - *ax4 = acos(arg) * *iss * 57.29577951308232087679815481410517; - } + d__2 = *akf; + arg = (d__1 * d__1 + d__2 * d__2 - *qs) / (*aki * 2. * *akf); + if (abs(arg) > 1.) { + *ier = 4; + goto L999; + } else { + *ax4 = acos(arg) * *iss * 57.29577951308232087679815481410517; + } /* Computing 2nd power */ - d__1 = *akf; + d__1 = *akf; /* Computing 2nd power */ - d__2 = *aki; - *ax3 = (-atan2(qt[2], qt[1]) - acos((d__1 * d__1 - *qs - d__2 * d__2) / (* - qm * -2. * *aki)) * d_sign(&c_b7, ax4)) * - 57.29577951308232087679815481410517; - sax3 = d_sign(&c_b7, ax3); - d__1 = *ax3 + sax3 * 180.; - *ax3 = d_mod(&d__1, &c_b9) - sax3 * 180.; + d__2 = *aki; + *ax3 = + (-atan2(qt[2], qt[1]) - + acos((d__1 * d__1 - *qs - + d__2 * d__2) / (*qm * -2. * *aki)) * d_sign(&c_b7, + ax4)) * + 57.29577951308232087679815481410517; + sax3 = d_sign(&c_b7, ax3); + d__1 = *ax3 + sax3 * 180.; + *ax3 = d_mod(&d__1, &c_b9) - sax3 * 180.; /* IF(LPLATE) AX3=-ATAN(SIN(AX4/RD)/(LSA*TAN(AX5/RD)/(ALMS*C */ /* 1 TAN(AX1/RD))*(AKI/KF)**2-COS(AX4/RD)))*RD !PLATE FOCALIZATION OPTION */ @@ -479,25 +501,27 @@ L999: /* IF(LPLATE.AND.A3.GT.0.0) AX3=AX3-180 */ /* C----------------------------------------------------------------------- */ L999: - return 0; -} /* sam_case__ */ + return 0; +} /* sam_case__ */ /* ============================================================================ */ -/* Subroutine */ int helm_case__(real *hx, real *hy, real *hz, real *t_ih__, - real *c_ih__, real *aki, real *akf, doublereal *a4, real *qm, real * - helm, integer *ier) +/* Subroutine */ int helm_case__(real * hx, real * hy, real * hz, + real * t_ih__, + real * c_ih__, real * aki, real * akf, + doublereal * a4, real * qm, real * helm, + integer * ier) { - /* System generated locals */ - real r__1, r__2; + /* System generated locals */ + real r__1, r__2; - /* Builtin functions */ - double cos(doublereal), sin(doublereal), atan2(doublereal, doublereal), - sqrt(doublereal); + /* Builtin functions */ + double cos(doublereal), sin(doublereal), atan2(doublereal, doublereal), + sqrt(doublereal); - /* Local variables */ - static real hrad, hdir, qpar, hdir2, qperp; - static integer ic; - static real phi; + /* Local variables */ + static real hrad, hdir, qpar, hdir2, qperp; + static integer ic; + static real phi; /* ----------------------------------------------------------------------- */ /* DEAL WITH HELMOTZ COIL FIELD CALCULATIONS */ @@ -508,24 +532,24 @@ L999: /* ----------------------------------------------------------------------- */ /* INIT AND TEST */ - /* Parameter adjustments */ - --c_ih__; - --t_ih__; + /* Parameter adjustments */ + --c_ih__; + --t_ih__; - /* Function Body */ - *ier = 1; - if (dabs(*qm) < 1e-4f) { - goto L999; - } - *ier = 0; - for (ic = 1; ic <= 4; ++ic) { - if (c_ih__[ic] < 1e-4f) { - *ier = 2; - } - } - if (*ier != 0) { - goto L999; + /* Function Body */ + *ier = 1; + if (dabs(*qm) < 1e-4f) { + goto L999; + } + *ier = 0; + for (ic = 1; ic <= 4; ++ic) { + if (c_ih__[ic] < 1e-4f) { + *ier = 2; } + } + if (*ier != 0) { + goto L999; + } /* ----------------------------------------------------------------------- */ /* CALCULATE MODULE AND ANGLES OF IN PLANE FIELD H */ /* PHI !ANGLE BETWEEN Q AND KI */ @@ -533,37 +557,40 @@ L999: /* HDIR !DIRECTION OF H (IN RADIANS) */ /* HDIR2 !ANGLE BETWEEN FIELD AND AXE OF COIL 1 */ - qpar = *aki - *akf * cos(*a4 / 57.29577951308232087679815481410517f); - qperp = *akf * sin(*a4 / 57.29577951308232087679815481410517f); - phi = atan2(qpar, qperp); + qpar = *aki - *akf * cos(*a4 / 57.29577951308232087679815481410517f); + qperp = *akf * sin(*a4 / 57.29577951308232087679815481410517f); + phi = atan2(qpar, qperp); /* Computing 2nd power */ - r__1 = *hx; + r__1 = *hx; /* Computing 2nd power */ - r__2 = *hy; - hrad = sqrt(r__1 * r__1 + r__2 * r__2); - if (hrad > 1e-4f) { - hdir = atan2(*hy, *hx); - } - hdir2 = phi + hdir + *helm / 57.29577951308232087679815481410517f + - 1.5707963267948966f; + r__2 = *hy; + hrad = sqrt(r__1 * r__1 + r__2 * r__2); + if (hrad > 1e-4f) { + hdir = atan2(*hy, *hx); + } + hdir2 = phi + hdir + *helm / 57.29577951308232087679815481410517f + + 1.5707963267948966f; /* ----------------------------------------------------------------------- */ /* !CALC CURRENTS */ /* !POSITION OF PSP FOR COIL I */ - for (ic = 1; ic <= 3; ++ic) { - t_ih__[ic + 4] = cos(hdir2 + (ic - 1) * 2.f * - 3.1415926535897932384626433832795f / 3.f) * hrad / c_ih__[ic] - / 1.5f; - } - t_ih__[8] = *hz / c_ih__[4]; + for (ic = 1; ic <= 3; ++ic) { + t_ih__[ic + 4] = cos(hdir2 + (ic - 1) * 2.f * + 3.1415926535897932384626433832795f / 3.f) * hrad / + c_ih__[ic] + / 1.5f; + } + t_ih__[8] = *hz / c_ih__[4]; /* ----------------------------------------------------------------------- */ L999: - return 0; -} /* helm_case__ */ + return 0; +} /* helm_case__ */ -/* Subroutine */ int flip_case__(integer *if1, integer *if2, real *t_ih__, - real *f1v, real *f1h, real *f2v, real *f2h, real *aki, real *akf, - integer *ier) +/* Subroutine */ int flip_case__(integer * if1, integer * if2, + real * t_ih__, + real * f1v, real * f1h, real * f2v, + real * f2h, real * aki, real * akf, + integer * ier) { /* ----------------------------------------------------------------------- */ /* DEAL WITH FLIPPER COIL CALCULATIONS */ @@ -573,29 +600,28 @@ L999: /* ----------------------------------------------------------------------- */ /* INIT AND TEST */ - /* Parameter adjustments */ - --t_ih__; + /* Parameter adjustments */ + --t_ih__; - /* Function Body */ - *ier = 0; + /* Function Body */ + *ier = 0; /* ----------------------------------------------------------------------- */ - if (*if1 == 1) { - t_ih__[1] = *f1v; - t_ih__[2] = *aki * *f1h; - } else { - t_ih__[1] = 0.f; - t_ih__[2] = 0.f; - } - if (*if2 == 1) { - t_ih__[3] = *f2v; - t_ih__[4] = *akf * *f2h; - } else { - t_ih__[3] = 0.f; - t_ih__[4] = 0.f; - } + if (*if1 == 1) { + t_ih__[1] = *f1v; + t_ih__[2] = *aki * *f1h; + } else { + t_ih__[1] = 0.f; + t_ih__[2] = 0.f; + } + if (*if2 == 1) { + t_ih__[3] = *f2v; + t_ih__[4] = *akf * *f2h; + } else { + t_ih__[3] = 0.f; + t_ih__[4] = 0.f; + } /* ----------------------------------------------------------------------- */ /* L999: */ - return 0; -} /* flip_case__ */ - + return 0; +} /* flip_case__ */ diff --git a/tasdrive.c b/tasdrive.c index 2d00de02..5f1d14ac 100644 --- a/tasdrive.c +++ b/tasdrive.c @@ -12,7 +12,7 @@ #include "sics.h" #include "tasdrive.h" -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) #define MOTPREC .01 /*------------------- motor indexes in motor data structure --------- @@ -32,171 +32,189 @@ #define ACH 11 /*============== Drivable Interface functions =====================*/ -static long TASSetValue(void *pData, SConnection *pCon, - float value){ - ptasMot self = (ptasMot)pData; +static long TASSetValue(void *pData, SConnection * pCon, float value) +{ + ptasMot self = (ptasMot) pData; assert(self); - if(self->code > 5 && self->math->tasMode == ELASTIC){ - SCWrite(pCon,"ERROR: cannot drive this motor in elastic mode", - eError); - return HWFault; + if (self->code > 5 && self->math->tasMode == ELASTIC) { + SCWrite(pCon, "ERROR: cannot drive this motor in elastic mode", + eError); + return HWFault; } - setTasPar(&self->math->target,self->math->tasMode,self->code,value); + setTasPar(&self->math->target, self->math->tasMode, self->code, value); self->math->mustDrive = 1; return OKOK; -} +} + /*----------------------------------------------------------------*/ -static int readTASMotAngles(ptasUB self, SConnection *pCon, - ptasAngles ang){ +static int readTASMotAngles(ptasUB self, SConnection * pCon, + ptasAngles ang) +{ int status; float val, theta; /* - Monochromator - */ - status = MotorGetSoftPosition(self->motors[A1],pCon,&val); - if(status == 0){ + Monochromator + */ + status = MotorGetSoftPosition(self->motors[A1], pCon, &val); + if (status == 0) { return status; } theta = val; - status = MotorGetSoftPosition(self->motors[A2],pCon,&val); - if(status == 0){ + status = MotorGetSoftPosition(self->motors[A2], pCon, &val); + if (status == 0) { return status; } ang->monochromator_two_theta = val; - if(ABS(val/2. - theta) > .1){ - SCWrite(pCon,"WARNING: theta monochromator not half of two theta",eWarning); - } - - /* - Analyzer - */ - if(self->tasMode != ELASTIC){ - status = MotorGetSoftPosition(self->motors[A5],pCon,&val); - if(status == 0){ - return status; - } - theta = val; - status = MotorGetSoftPosition(self->motors[A6],pCon,&val); - if(status == 0){ - return status; - } - ang->analyzer_two_theta = val; - if(ABS(val/2. - theta) > .1){ - SCWrite(pCon,"WARNING: theta analyzer not half of two theta",eWarning); - } - } else { - ang->analyzer_two_theta = ang->monochromator_two_theta; + if (ABS(val / 2. - theta) > .1) { + SCWrite(pCon, "WARNING: theta monochromator not half of two theta", + eWarning); } /* - crystal - */ - status = MotorGetSoftPosition(self->motors[A3],pCon,&val); - if(status == 0){ + Analyzer + */ + if (self->tasMode != ELASTIC) { + status = MotorGetSoftPosition(self->motors[A5], pCon, &val); + if (status == 0) { + return status; + } + theta = val; + status = MotorGetSoftPosition(self->motors[A6], pCon, &val); + if (status == 0) { + return status; + } + ang->analyzer_two_theta = val; + if (ABS(val / 2. - theta) > .1) { + SCWrite(pCon, "WARNING: theta analyzer not half of two theta", + eWarning); + } + } else { + ang->analyzer_two_theta = ang->monochromator_two_theta; + } + + /* + crystal + */ + status = MotorGetSoftPosition(self->motors[A3], pCon, &val); + if (status == 0) { return status; } ang->a3 = val; - status = MotorGetSoftPosition(self->motors[A4],pCon,&val); - if(status == 0){ + status = MotorGetSoftPosition(self->motors[A4], pCon, &val); + if (status == 0) { return status; } ang->sample_two_theta = val; - status = MotorGetSoftPosition(self->motors[SGU],pCon,&val); - if(status == 0){ + status = MotorGetSoftPosition(self->motors[SGU], pCon, &val); + if (status == 0) { return status; } ang->sgu = val; - status = MotorGetSoftPosition(self->motors[SGL],pCon,&val); - if(status == 0){ + status = MotorGetSoftPosition(self->motors[SGL], pCon, &val); + if (status == 0) { return status; } ang->sgl = val; return 1; } + /*-------------------------------------------------------------*/ -static float TASGetValue(void *pData, SConnection *pCon){ - ptasMot self = (ptasMot)pData; +static float TASGetValue(void *pData, SConnection * pCon) +{ + ptasMot self = (ptasMot) pData; int status; tasAngles angles; double val; assert(self); - if(self->math->mustRecalculate == 1) { + if (self->math->mustRecalculate == 1) { status = readTASMotAngles(self->math, pCon, &angles); - if(status != 1){ + if (status != 1) { return -999.99; } - status = calcTasQEPosition(&self->math->machine, angles, &self->math->current); - if(status < 0){ - SCWrite(pCon,"ERROR: out of memory calculating Q-E variables",eError); + status = + calcTasQEPosition(&self->math->machine, angles, + &self->math->current); + if (status < 0) { + SCWrite(pCon, "ERROR: out of memory calculating Q-E variables", + eError); return -999.99; } - if(self->math->tasMode == ELASTIC){ - self->math->current.kf = self->math->current.ki; + if (self->math->tasMode == ELASTIC) { + self->math->current.kf = self->math->current.ki; } self->math->mustRecalculate = 0; } - val = getTasPar(self->math->current,self->code); - if(self->code > 5 && self->math->tasMode == ELASTIC){ - SCWrite(pCon,"WARNING: value for this motor is meaningless in elastic mode", - eWarning); + val = getTasPar(self->math->current, self->code); + if (self->code > 5 && self->math->tasMode == ELASTIC) { + SCWrite(pCon, + "WARNING: value for this motor is meaningless in elastic mode", + eWarning); } - return (float)val; + return (float) val; } + /*-----------------------------------------------------------------*/ -static float TASQMGetValue(void *pData, SConnection *pCon){ - ptasMot self = (ptasMot)pData; +static float TASQMGetValue(void *pData, SConnection * pCon) +{ + ptasMot self = (ptasMot) pData; int status; tasAngles angles; double val; assert(self); - if(self->math->mustRecalculate == 1) { + if (self->math->mustRecalculate == 1) { status = readTASMotAngles(self->math, pCon, &angles); - if(status != 1){ + if (status != 1) { return -999.99; } - status = calcTasPowderPosition(&self->math->machine, - angles, &self->math->current); - if(status < 0){ - SCWrite(pCon,"ERROR: out of memory calculating Q-E variables",eError); + status = calcTasPowderPosition(&self->math->machine, + angles, &self->math->current); + if (status < 0) { + SCWrite(pCon, "ERROR: out of memory calculating Q-E variables", + eError); return -999.99; } - if(self->math->tasMode == ELASTIC){ - self->math->current.kf = self->math->current.ki; + if (self->math->tasMode == ELASTIC) { + self->math->current.kf = self->math->current.ki; } self->math->mustRecalculate = 0; } - val = getTasPar(self->math->current,self->code); - return (float)val; + val = getTasPar(self->math->current, self->code); + return (float) val; } + /*---------------------------------------------------------------------------------*/ -static int TASCheckLimits(void *pData, float fVal, char *error, int iErrLen){ +static int TASCheckLimits(void *pData, float fVal, char *error, + int iErrLen) +{ /* - There is no meaningful implementation here. This gets called when starting the motor. - At that stage not all other values may be known. If the calculation fails, - this will die at status check time. - */ + There is no meaningful implementation here. This gets called when starting the motor. + At that stage not all other values may be known. If the calculation fails, + this will die at status check time. + */ return 1; } + /*---------------------------------------------------------------------------------*/ -static int TASHalt(void *pData){ - ptasMot self = (ptasMot)pData; +static int TASHalt(void *pData) +{ + ptasMot self = (ptasMot) pData; int i, length = 12; assert(self); /** * disregard non existing analyzer motors */ - if(self->math->tasMode == ELASTIC){ - length = 8; + if (self->math->tasMode == ELASTIC) { + length = 8; } - for(i = 0; i < length; i++){ - if(self->math->motors[i] != NULL){ + for (i = 0; i < length; i++) { + if (self->math->motors[i] != NULL) { self->math->motors[i]->pDrivInt->Halt(self->math->motors[i]); } } @@ -204,313 +222,336 @@ static int TASHalt(void *pData){ } /*--------------------------------------------------------------------------*/ -static void writeMotPos(SConnection *pCon, int silent, char *name, - float val, float target){ - char pBueffel[132]; - - if(silent != 1) { - snprintf(pBueffel,131,"Driving %5s from %8.3f to %8.3f", - name, val, target); - SCWrite(pCon,pBueffel,eWarning); - } +static void writeMotPos(SConnection * pCon, int silent, char *name, + float val, float target) +{ + char pBueffel[132]; + + if (silent != 1) { + snprintf(pBueffel, 131, "Driving %5s from %8.3f to %8.3f", + name, val, target); + SCWrite(pCon, pBueffel, eWarning); + } } + /*--------------------------------------------------------------------------*/ -static float getMotorValue(pMotor mot, SConnection *pCon){ - float val; - - MotorGetSoftPosition(mot,pCon,&val); - return val; -} +static float getMotorValue(pMotor mot, SConnection * pCon) +{ + float val; + + MotorGetSoftPosition(mot, pCon, &val); + return val; +} + /*--------------------------------------------------------------------------*/ -static int startTASMotor(pMotor mot, SConnection *pCon, char *name, - double target, int silent){ +static int startTASMotor(pMotor mot, SConnection * pCon, char *name, + double target, int silent) +{ float val, fixed; int status = OKOK; char buffer[132]; - - val = getMotorValue(mot,pCon); - MotorGetPar(mot,"fixed",&fixed); - if(ABS(fixed - 1.0) < .1) { - snprintf(buffer,131,"WARNING: %s is FIXED", name); - SCWrite(pCon,buffer,eWarning); + + val = getMotorValue(mot, pCon); + MotorGetPar(mot, "fixed", &fixed); + if (ABS(fixed - 1.0) < .1) { + snprintf(buffer, 131, "WARNING: %s is FIXED", name); + SCWrite(pCon, buffer, eWarning); return OKOK; } - if(ABS(val - target) > MOTPREC){ - status = mot->pDrivInt->SetValue(mot,pCon,(float)target); - if(status != OKOK){ + if (ABS(val - target) > MOTPREC) { + status = mot->pDrivInt->SetValue(mot, pCon, (float) target); + if (status != OKOK) { return status; } } - writeMotPos(pCon,silent,name,val, target); - return status; -} + writeMotPos(pCon, silent, name, val, target); + return status; +} + /*---------------------------------------------------------------------------*/ -static int startMotors(ptasMot self, tasAngles angles, - SConnection *pCon, int driveQ, int driveTilt){ +static int startMotors(ptasMot self, tasAngles angles, + SConnection * pCon, int driveQ, int driveTilt) +{ double curve; int status, silent; silent = self->math->silent; self->math->mustRecalculate = 1; /* - monochromator - */ - status = startTASMotor(self->math->motors[A1],pCon, "a1", - angles.monochromator_two_theta/2.,silent); - if(status != OKOK){ + monochromator + */ + status = startTASMotor(self->math->motors[A1], pCon, "a1", + angles.monochromator_two_theta / 2., silent); + if (status != OKOK) { return status; } - status = startTASMotor(self->math->motors[A2],pCon, "a2", - angles.monochromator_two_theta,silent); - if(status != OKOK){ + status = startTASMotor(self->math->motors[A2], pCon, "a2", + angles.monochromator_two_theta, silent); + if (status != OKOK) { return status; } - if(self->math->motors[MCV] != NULL){ + if (self->math->motors[MCV] != NULL) { curve = maCalcVerticalCurvature(self->math->machine.monochromator, - angles.monochromator_two_theta); - status = startTASMotor(self->math->motors[MCV],pCon, "mcv", - curve,silent); - if(status != OKOK){ - return status; + angles.monochromator_two_theta); + status = startTASMotor(self->math->motors[MCV], pCon, "mcv", + curve, silent); + if (status != OKOK) { + return status; } } - if(self->math->motors[MCH] != NULL){ + if (self->math->motors[MCH] != NULL) { curve = maCalcHorizontalCurvature(self->math->machine.monochromator, - angles.monochromator_two_theta); - status = startTASMotor(self->math->motors[MCH],pCon, "mch", - curve,silent); - if(status != OKOK){ - return status; + angles.monochromator_two_theta); + status = startTASMotor(self->math->motors[MCH], pCon, "mch", + curve, silent); + if (status != OKOK) { + return status; } } - + /* - analyzer - */ - if(self->math->tasMode != ELASTIC){ - status = startTASMotor(self->math->motors[A5],pCon, "a5", - angles.analyzer_two_theta/2.0,silent); - if(status != OKOK){ - return status; + analyzer + */ + if (self->math->tasMode != ELASTIC) { + status = startTASMotor(self->math->motors[A5], pCon, "a5", + angles.analyzer_two_theta / 2.0, silent); + if (status != OKOK) { + return status; } - status = startTASMotor(self->math->motors[A6],pCon, "a6", - angles.analyzer_two_theta,silent); - if(status != OKOK){ - return status; + status = startTASMotor(self->math->motors[A6], pCon, "a6", + angles.analyzer_two_theta, silent); + if (status != OKOK) { + return status; } - if(self->math->motors[ACV] != NULL){ - curve = maCalcVerticalCurvature(self->math->machine.analyzer, - angles.analyzer_two_theta); - status = startTASMotor(self->math->motors[ACV],pCon, "acv", - curve,silent); - if(status != OKOK){ - return status; - } + if (self->math->motors[ACV] != NULL) { + curve = maCalcVerticalCurvature(self->math->machine.analyzer, + angles.analyzer_two_theta); + status = startTASMotor(self->math->motors[ACV], pCon, "acv", + curve, silent); + if (status != OKOK) { + return status; + } } - if(self->math->motors[ACH] != NULL){ - curve = maCalcHorizontalCurvature(self->math->machine.analyzer, - angles.analyzer_two_theta); - status = startTASMotor(self->math->motors[ACH],pCon, "ach", - curve,silent); - if(status != OKOK){ - return status; - } + if (self->math->motors[ACH] != NULL) { + curve = maCalcHorizontalCurvature(self->math->machine.analyzer, + angles.analyzer_two_theta); + status = startTASMotor(self->math->motors[ACH], pCon, "ach", + curve, silent); + if (status != OKOK) { + return status; + } } } - - if(driveQ == 0){ + + if (driveQ == 0) { return OKOK; } /* - crystal - */ - status = startTASMotor(self->math->motors[A3],pCon, "a3", - angles.a3,silent); - if(status != OKOK){ + crystal + */ + status = startTASMotor(self->math->motors[A3], pCon, "a3", + angles.a3, silent); + if (status != OKOK) { return status; } - status = startTASMotor(self->math->motors[A4],pCon, "a4", - angles.sample_two_theta,silent); - if(status != OKOK){ + status = startTASMotor(self->math->motors[A4], pCon, "a4", + angles.sample_two_theta, silent); + if (status != OKOK) { return status; } - if(driveTilt == 1){ - status = startTASMotor(self->math->motors[SGL],pCon, "sgl", - angles.sgl,silent); - if(status != OKOK){ - return status; - } - status = startTASMotor(self->math->motors[SGU],pCon, "sgu", - angles.sgu,silent); - if(status != OKOK){ - return status; - } + if (driveTilt == 1) { + status = startTASMotor(self->math->motors[SGL], pCon, "sgl", + angles.sgl, silent); + if (status != OKOK) { + return status; + } + status = startTASMotor(self->math->motors[SGU], pCon, "sgu", + angles.sgu, silent); + if (status != OKOK) { + return status; + } } self->math->mustDrive = 0; return OKOK; } + /*---------------------------------------------------------------------------*/ -static int checkQMotorLimits(ptasMot self, SConnection *pCon, - tasAngles angles, int driveTilt){ +static int checkQMotorLimits(ptasMot self, SConnection * pCon, + tasAngles angles, int driveTilt) +{ int status, retVal = 1; char error[131]; char pBueffel[256]; float val; - - MotorGetPar(self->math->motors[A3],"fixed",&val); - if((int)val != 1){ - status = self->math->motors[A3]->pDrivInt->CheckLimits(self->math->motors[A3], - angles.a3, - error, - 131); - if(status != 1) { - retVal = 0; - snprintf(pBueffel,256,"ERROR: limit violation an a3: %s", error); - SCWrite(pCon,pBueffel,eError); + + MotorGetPar(self->math->motors[A3], "fixed", &val); + if ((int) val != 1) { + status = + self->math->motors[A3]->pDrivInt->CheckLimits(self->math-> + motors[A3], + angles.a3, error, + 131); + if (status != 1) { + retVal = 0; + snprintf(pBueffel, 256, "ERROR: limit violation an a3: %s", error); + SCWrite(pCon, pBueffel, eError); } } - - status = self->math->motors[A4]->pDrivInt->CheckLimits(self->math->motors[A4], - angles.sample_two_theta, - error, - 131); - if(status != 1) { + + status = + self->math->motors[A4]->pDrivInt->CheckLimits(self->math->motors[A4], + angles. + sample_two_theta, + error, 131); + if (status != 1) { retVal = 0; - snprintf(pBueffel,256,"ERROR: limit violation an a4: %s", error); - SCWrite(pCon,pBueffel,eError); + snprintf(pBueffel, 256, "ERROR: limit violation an a4: %s", error); + SCWrite(pCon, pBueffel, eError); } - if(driveTilt == 1){ - status = self->math->motors[A3]->pDrivInt->CheckLimits(self->math->motors[SGU], - angles.sgu, - error, - 131); - if(status != 1) { - retVal = 0; - snprintf(pBueffel,256,"ERROR: limit violation an SGU: %s", error); - SCWrite(pCon,pBueffel,eError); - } + if (driveTilt == 1) { + status = + self->math->motors[A3]->pDrivInt->CheckLimits(self->math-> + motors[SGU], + angles.sgu, error, + 131); + if (status != 1) { + retVal = 0; + snprintf(pBueffel, 256, "ERROR: limit violation an SGU: %s", error); + SCWrite(pCon, pBueffel, eError); + } - status = self->math->motors[SGL]->pDrivInt->CheckLimits(self->math->motors[SGL], - angles.sgl, - error, - 131); - if(status != 1) { - retVal = 0; - snprintf(pBueffel,256,"ERROR: limit violation an SGL: %s", error); - SCWrite(pCon,pBueffel,eError); - } + status = + self->math->motors[SGL]->pDrivInt->CheckLimits(self->math-> + motors[SGL], + angles.sgl, error, + 131); + if (status != 1) { + retVal = 0; + snprintf(pBueffel, 256, "ERROR: limit violation an SGL: %s", error); + SCWrite(pCon, pBueffel, eError); + } } return retVal; } + /*-----------------------------------------------------------------------------*/ -static int calculateAndDrive(ptasMot self, SConnection *pCon){ +static int calculateAndDrive(ptasMot self, SConnection * pCon) +{ tasAngles angles; int status, driveQ = 1, driveTilt = 1; MATRIX scatteringPlaneNormal = NULL; - if(self->math->ubValid == 0){ - SCWrite(pCon,"WARNING: UB matrix invalid",eWarning); + if (self->math->ubValid == 0) { + SCWrite(pCon, "WARNING: UB matrix invalid", eWarning); } status = calcAllTasAngles(&self->math->machine, self->math->target, - &angles); + &angles); self->math->mustDrive = 0; - switch(status){ + switch (status) { case ENERGYTOBIG: - SCWrite(pCon,"ERROR: desired energy to big",eError); + SCWrite(pCon, "ERROR: desired energy to big", eError); return HWFault; break; case UBNOMEMORY: - SCWrite(pCon,"ERROR: out of memory calculating angles",eError); + SCWrite(pCon, "ERROR: out of memory calculating angles", eError); driveQ = 0; break; case BADRMATRIX: - SCWrite(pCon,"ERROR: bad crystallographic parameters or bad UB",eError); + SCWrite(pCon, "ERROR: bad crystallographic parameters or bad UB", + eError); driveQ = 0; break; case BADUBORQ: - SCWrite(pCon,"ERROR: bad UB matrix or bad Q-vector",eError); + SCWrite(pCon, "ERROR: bad UB matrix or bad Q-vector", eError); driveQ = 0; break; case TRIANGLENOTCLOSED: - SCWrite(pCon,"ERROR: cannot close scattering triangle",eError); + SCWrite(pCon, "ERROR: cannot close scattering triangle", eError); driveQ = 0; break; } /** * check out of plane condition and permission */ - if(self->math->outOfPlaneAllowed != 1){ + if (self->math->outOfPlaneAllowed != 1) { scatteringPlaneNormal = calcScatteringPlaneNormal(self->math->r1.qe, - self->math->r2.qe); - if(scatteringPlaneNormal == NULL){ - SCWrite(pCon,"ERROR: unable to calculate scattering plane normal",eError); - driveQ = 0; - } else { - if(!isInPlane(scatteringPlaneNormal,self->math->target)){ - SCWrite(pCon, - "WARNING: scattering vector is out of plane and you disallowed me to try to drive there", - eWarning); - } + self->math->r2.qe); + if (scatteringPlaneNormal == NULL) { + SCWrite(pCon, "ERROR: unable to calculate scattering plane normal", + eError); + driveQ = 0; + } else { + if (!isInPlane(scatteringPlaneNormal, self->math->target)) { + SCWrite(pCon, + "WARNING: scattering vector is out of plane and you disallowed me to try to drive there", + eWarning); + } } driveTilt = 0; } - - if(driveQ != 0){ - if(!checkQMotorLimits(self,pCon,angles,driveTilt)){ - driveQ = 0; + + if (driveQ != 0) { + if (!checkQMotorLimits(self, pCon, angles, driveTilt)) { + driveQ = 0; } } - if(driveQ == 0){ - SCWrite(pCon,"WARNING: NOT driving Q-vector because of errors",eError); + if (driveQ == 0) { + SCWrite(pCon, "WARNING: NOT driving Q-vector because of errors", + eError); } - return startMotors(self,angles,pCon, driveQ,driveTilt); + return startMotors(self, angles, pCon, driveQ, driveTilt); } + /*-----------------------------------------------------------------------------*/ -static int checkMotors(ptasMot self, SConnection *pCon){ +static int checkMotors(ptasMot self, SConnection * pCon) +{ int i, status, length = 12; int mask[12]; self->math->mustRecalculate = 1; - if(self->math->tasMode == ELASTIC){ - length = 8; + if (self->math->tasMode == ELASTIC) { + length = 8; } - memset(mask,0,12*sizeof(int)); - for(i = 0; i < length; i++){ - mask[i] = 1; + memset(mask, 0, 12 * sizeof(int)); + for (i = 0; i < length; i++) { + mask[i] = 1; } - if(self->math->outOfPlaneAllowed != 0){ + if (self->math->outOfPlaneAllowed != 0) { mask[SGU] = 0; mask[SGL] = 0; } - - for(i = 0; i < 12; i++){ - if(self->math->motors[i] != NULL && mask[i] != 0){ - status = self->math->motors[i]->pDrivInt->CheckStatus(self->math->motors[i], - pCon); - if(status != HWIdle && status != OKOK){ - return status; + + for (i = 0; i < 12; i++) { + if (self->math->motors[i] != NULL && mask[i] != 0) { + status = + self->math->motors[i]->pDrivInt->CheckStatus(self->math-> + motors[i], pCon); + if (status != HWIdle && status != OKOK) { + return status; } } } return HWIdle; } + /*------------------------------------------------------------------------------*/ -static int TASGetStatus(void *pData, SConnection *pCon){ - ptasMot self = (ptasMot)pData; +static int TASGetStatus(void *pData, SConnection * pCon) +{ + ptasMot self = (ptasMot) pData; int status; assert(self); - if(self->math->mustDrive == 1){ - status = calculateAndDrive(self,pCon); - if(status != OKOK){ + if (self->math->mustDrive == 1) { + status = calculateAndDrive(self, pCon); + if (status != OKOK) { return HWFault; } else { return HWBusy; @@ -519,124 +560,130 @@ static int TASGetStatus(void *pData, SConnection *pCon){ return checkMotors(self, pCon); } } + /*---------------------------------------------------------------------------*/ -static int startQMMotors(ptasMot self, tasAngles angles, - SConnection *pCon){ +static int startQMMotors(ptasMot self, tasAngles angles, + SConnection * pCon) +{ float val; double curve; int status, silent; silent = self->math->silent; /* - monochromator - */ - status = startTASMotor(self->math->motors[A1],pCon, "a1", - angles.monochromator_two_theta/2.,silent); - if(status != OKOK){ + monochromator + */ + status = startTASMotor(self->math->motors[A1], pCon, "a1", + angles.monochromator_two_theta / 2., silent); + if (status != OKOK) { return status; } - status = startTASMotor(self->math->motors[A2],pCon, "a2", - angles.monochromator_two_theta,silent); - if(status != OKOK){ + status = startTASMotor(self->math->motors[A2], pCon, "a2", + angles.monochromator_two_theta, silent); + if (status != OKOK) { return status; } - if(self->math->motors[MCV] != NULL){ + if (self->math->motors[MCV] != NULL) { curve = maCalcVerticalCurvature(self->math->machine.monochromator, - angles.monochromator_two_theta); - status = startTASMotor(self->math->motors[MCV],pCon, "mcv", - curve,silent); - if(status != OKOK){ - return status; + angles.monochromator_two_theta); + status = startTASMotor(self->math->motors[MCV], pCon, "mcv", + curve, silent); + if (status != OKOK) { + return status; } } - if(self->math->motors[MCH] != NULL){ + if (self->math->motors[MCH] != NULL) { curve = maCalcHorizontalCurvature(self->math->machine.monochromator, - angles.monochromator_two_theta); - status = startTASMotor(self->math->motors[MCH],pCon, "mch", - curve,silent); - if(status != OKOK){ - return status; + angles.monochromator_two_theta); + status = startTASMotor(self->math->motors[MCH], pCon, "mch", + curve, silent); + if (status != OKOK) { + return status; } } - + /* - analyzer - */ - status = startTASMotor(self->math->motors[A5],pCon, "a5", - angles.analyzer_two_theta/2.0,silent); - if(status != OKOK){ - return status; - } - status = startTASMotor(self->math->motors[A6],pCon, "a6", - angles.analyzer_two_theta,silent); - if(status != OKOK){ - return status; - } - - if(self->math->motors[ACV] != NULL){ - curve = maCalcVerticalCurvature(self->math->machine.analyzer, - angles.analyzer_two_theta); - status = startTASMotor(self->math->motors[ACV],pCon, "acv", - curve,silent); - if(status != OKOK){ - return status; - } - } - if(self->math->motors[ACH] != NULL){ - curve = maCalcHorizontalCurvature(self->math->machine.analyzer, - angles.analyzer_two_theta); - status = startTASMotor(self->math->motors[ACH],pCon, "ach", - curve,silent); - if(status != OKOK){ - return status; - } - } - - /* - crystal - */ - status = startTASMotor(self->math->motors[A4],pCon, "a4", - angles.sample_two_theta,silent); - if(status != OKOK){ + analyzer + */ + status = startTASMotor(self->math->motors[A5], pCon, "a5", + angles.analyzer_two_theta / 2.0, silent); + if (status != OKOK) { return status; } - + status = startTASMotor(self->math->motors[A6], pCon, "a6", + angles.analyzer_two_theta, silent); + if (status != OKOK) { + return status; + } + + if (self->math->motors[ACV] != NULL) { + curve = maCalcVerticalCurvature(self->math->machine.analyzer, + angles.analyzer_two_theta); + status = startTASMotor(self->math->motors[ACV], pCon, "acv", + curve, silent); + if (status != OKOK) { + return status; + } + } + if (self->math->motors[ACH] != NULL) { + curve = maCalcHorizontalCurvature(self->math->machine.analyzer, + angles.analyzer_two_theta); + status = startTASMotor(self->math->motors[ACH], pCon, "ach", + curve, silent); + if (status != OKOK) { + return status; + } + } + + /* + crystal + */ + status = startTASMotor(self->math->motors[A4], pCon, "a4", + angles.sample_two_theta, silent); + if (status != OKOK) { + return status; + } + self->math->mustDrive = 0; return OKOK; } + /*-----------------------------------------------------------------------------*/ -static int calculateQMAndDrive(ptasMot self, SConnection *pCon){ +static int calculateQMAndDrive(ptasMot self, SConnection * pCon) +{ tasAngles angles; int status; status = calcTasPowderAngles(&self->math->machine, self->math->target, - &angles); - switch(status){ + &angles); + switch (status) { case ENERGYTOBIG: - SCWrite(pCon,"ERROR: desired energy to big",eError); + SCWrite(pCon, "ERROR: desired energy to big", eError); return HWFault; break; case TRIANGLENOTCLOSED: - SCWrite(pCon,"ERROR: cannot close scattering triangle",eError); + SCWrite(pCon, "ERROR: cannot close scattering triangle", eError); return HWFault; break; default: - return startQMMotors(self,angles,pCon); + return startQMMotors(self, angles, pCon); } return HWFault; } + /*------------------------------------------------------------------------------*/ -static int TASQMGetStatus(void *pData, SConnection *pCon){ - ptasMot self = (ptasMot)pData; +static int TASQMGetStatus(void *pData, SConnection * pCon) +{ + ptasMot self = (ptasMot) pData; int status; assert(self); - if(self->math->mustDrive == 1){ - status = calculateQMAndDrive(self,pCon); - if(status != OKOK){ + if (self->math->mustDrive == 1) { + status = calculateQMAndDrive(self, pCon); + if (status != OKOK) { return HWFault; } else { return HWBusy; @@ -645,45 +692,52 @@ static int TASQMGetStatus(void *pData, SConnection *pCon){ return checkMotors(self, pCon); } } + /*================== Life and Death =========================================*/ -static void KillTasMot(void *pData){ - ptasMot self = (ptasMot)pData; - if(self == NULL){ +static void KillTasMot(void *pData) +{ + ptasMot self = (ptasMot) pData; + if (self == NULL) { return; } - if(self->pDes != NULL){ + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); self->pDes == NULL; } - if(self->pDriv != NULL){ + if (self->pDriv != NULL) { free(self->pDriv); self->pDriv = NULL; } free(self); } -/*---------------------------------------------------------------------------*/ -static void *GetTasInterface(void *pData, int interfaceID){ - ptasMot self = (ptasMot)pData; - if(self != NULL && interfaceID == DRIVEID){ +/*---------------------------------------------------------------------------*/ +static void *GetTasInterface(void *pData, int interfaceID) +{ + ptasMot self = (ptasMot) pData; + + if (self != NULL && interfaceID == DRIVEID) { return self->pDriv; } else { return NULL; } } + /*-------------------------------------------------------------------------*/ -int InstallTasMotor(SicsInterp *pSics, ptasUB self, int tasVar, char *name){ +int InstallTasMotor(SicsInterp * pSics, ptasUB self, int tasVar, + char *name) +{ ptasMot pNew = NULL; - pNew = (ptasMot)malloc(sizeof(tasMot)); - if(!pNew){ + pNew = (ptasMot) malloc(sizeof(tasMot)); + if (!pNew) { return 0; } - memset(pNew,0,sizeof(tasMot)); + memset(pNew, 0, sizeof(tasMot)); pNew->pDes = CreateDescriptor("TasMot"); pNew->pDriv = CreateDrivableInterface(); - if(!pNew->pDes || !pNew->pDriv) { + if (!pNew->pDes || !pNew->pDriv) { free(pNew); return 0; } @@ -696,21 +750,23 @@ int InstallTasMotor(SicsInterp *pSics, ptasUB self, int tasVar, char *name){ pNew->math = self; pNew->code = tasVar; - return AddCommand(pSics,name, TasMot, KillTasMot,pNew); + return AddCommand(pSics, name, TasMot, KillTasMot, pNew); } + /*-------------------------------------------------------------------------*/ -int InstallTasQMMotor(SicsInterp *pSics, ptasUB self){ +int InstallTasQMMotor(SicsInterp * pSics, ptasUB self) +{ ptasMot pNew = NULL; - pNew = (ptasMot)malloc(sizeof(tasMot)); - if(!pNew){ + pNew = (ptasMot) malloc(sizeof(tasMot)); + if (!pNew) { return 0; } - memset(pNew,0,sizeof(tasMot)); + memset(pNew, 0, sizeof(tasMot)); pNew->pDes = CreateDescriptor("TasMot"); pNew->pDriv = CreateDrivableInterface(); - if(!pNew->pDes || !pNew->pDriv) { + if (!pNew->pDes || !pNew->pDriv) { free(pNew); return 0; } @@ -723,30 +779,33 @@ int InstallTasQMMotor(SicsInterp *pSics, ptasUB self){ pNew->math = self; pNew->code = QM; - return AddCommand(pSics,"qm", TasMot, KillTasMot,pNew); + return AddCommand(pSics, "qm", TasMot, KillTasMot, pNew); } + /*------------------------------------------------------------------------*/ -int TasMot(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - ptasMot self = (ptasMot)pData; +int TasMot(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + ptasMot self = (ptasMot) pData; float value; char pBueffel[132]; - if(argc > 1){ + if (argc > 1) { strtolower(argv[1]); - if(strcmp(argv[1],"target") == 0){ - snprintf(pBueffel,131,"%s.target = %f", - argv[0], getTasPar(self->math->target,self->code)); - SCWrite(pCon,pBueffel,eValue); + if (strcmp(argv[1], "target") == 0) { + snprintf(pBueffel, 131, "%s.target = %f", + argv[0], getTasPar(self->math->target, self->code)); + SCWrite(pCon, pBueffel, eValue); return 1; } else { - snprintf(pBueffel,131,"ERROR: tasmot does not understand %s", argv[1]); - SCWrite(pCon,pBueffel,eError); + snprintf(pBueffel, 131, "ERROR: tasmot does not understand %s", + argv[1]); + SCWrite(pCon, pBueffel, eError); return 0; } } - value = self->pDriv->GetValue(self,pCon); - snprintf(pBueffel,131,"%s = %f", argv[0], value); - SCWrite(pCon,pBueffel,eValue); + value = self->pDriv->GetValue(self, pCon); + snprintf(pBueffel, 131, "%s = %f", argv[0], value); + SCWrite(pCon, pBueffel, eValue); return 1; } diff --git a/tasdrive.h b/tasdrive.h index c6c061ca..8fcc8e22 100644 --- a/tasdrive.h +++ b/tasdrive.h @@ -10,8 +10,9 @@ #define TASDRIV #include "tasub.h" -int InstallTasMotor(SicsInterp *pSics, ptasUB self, int tasVar, char *name); -int InstallTasQMMotor(SicsInterp *pSics, ptasUB self); -int TasMot(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int InstallTasMotor(SicsInterp * pSics, ptasUB self, int tasVar, + char *name); +int InstallTasQMMotor(SicsInterp * pSics, ptasUB self); +int TasMot(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/task.c b/task.c index 74ff28b4..3239c76e 100644 --- a/task.c +++ b/task.c @@ -19,353 +19,328 @@ #define WAITING 2 #define YIELDING 3 /*--------------------------------------------------------------------------*/ - typedef struct __TaskHead { - long lID; - int iStatus; - long lWait; - TaskFunc pRun; - SignalFunc pSignal; - void *pData; - TaskKillFunc pKill; - pTaskHead pNext; - pTaskHead pPrevious; - } TaskHead; - - typedef struct __TaskMan { - int iID; - int iStop; - pTaskHead pCurrent; - pTaskHead pHead; - } TaskMan; +typedef struct __TaskHead { + long lID; + int iStatus; + long lWait; + TaskFunc pRun; + SignalFunc pSignal; + void *pData; + TaskKillFunc pKill; + pTaskHead pNext; + pTaskHead pPrevious; +} TaskHead; + +typedef struct __TaskMan { + int iID; + int iStop; + pTaskHead pCurrent; + pTaskHead pHead; +} TaskMan; /*---------------------------------------------------------------------------*/ - static long lIDMama = 0L; -#define TASKERID 123399 +static long lIDMama = 0L; +#define TASKERID 123399 /*---------------------------------------------------------------------------*/ - static pTaskHead MakeTaskHead(TaskFunc pTask, SignalFunc pSignal, - void *pData, TaskKillFunc pKill) - { - pTaskHead pNew = NULL; - - pNew = (pTaskHead)malloc(sizeof(TaskHead)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(TaskHead)); - - pNew->pRun = pTask; - pNew->pSignal = pSignal; - pNew->pData = pData; - pNew->pKill = pKill; - pNew->lID = lIDMama++; - pNew->iStatus = READY; - - return pNew; +static pTaskHead MakeTaskHead(TaskFunc pTask, SignalFunc pSignal, + void *pData, TaskKillFunc pKill) +{ + pTaskHead pNew = NULL; + + pNew = (pTaskHead) malloc(sizeof(TaskHead)); + if (!pNew) { + return NULL; } + memset(pNew, 0, sizeof(TaskHead)); + + pNew->pRun = pTask; + pNew->pSignal = pSignal; + pNew->pData = pData; + pNew->pKill = pKill; + pNew->lID = lIDMama++; + pNew->iStatus = READY; + + return pNew; +} + /*--------------------------------------------------------------------------*/ - static void DeleteTaskHead(pTaskHead self) - { - assert(self); - - if(self->pKill) - { - if(self->pData) - { - self->pKill(self->pData); - } - } - /* unlink */ - if(self->pPrevious != NULL) - { - self->pPrevious->pNext = self->pNext; - } - if(self->pNext != NULL) - { - self->pNext->pPrevious = self->pPrevious; - } - free(self); - } -/*--------------------------------------------------------------------------*/ - static int DummyTask(void *pData) - { - return 1; - } -/*--------------------------------------------------------------------------*/ - int TaskerInit(pTaskMan *self) - { - pTaskMan pNew = NULL; - pTaskHead pDummyTask = NULL; - - *self = NULL; - /* a new Task manager */ - pNew = (pTaskMan)malloc(sizeof(TaskMan)); - if(!pNew) - { - return 0; - } - memset(pNew, 0, sizeof(TaskMan)); - pNew->iID = TASKERID; - - /* create a dummy task as start point */ - pDummyTask = MakeTaskHead(DummyTask,NULL,NULL,NULL); - if(!pDummyTask) - { - free(pNew); - return 0; - } - - /* link */ - pDummyTask->pNext = NULL; - pDummyTask->pPrevious = NULL; - - pNew->pCurrent = pDummyTask; - pNew->pHead = pDummyTask; - *self = pNew; - return 1; - } -/*---------------------------------------------------------------------------*/ - int TaskerDelete(pTaskMan *pData) - { - pTaskMan self = *pData; - pTaskHead pCurrent, pKill; - - assert(self); - assert(self->iID == TASKERID); - - pCurrent = self->pHead; - while(pCurrent != NULL) - { - pKill = pCurrent; - pCurrent = pCurrent->pNext; - DeleteTaskHead(pKill); +static void DeleteTaskHead(pTaskHead self) +{ + assert(self); + + if (self->pKill) { + if (self->pData) { + self->pKill(self->pData); } - free(self); - *pData = NULL; - return 1; } -/*---------------------------------------------------------------------------*/ - long TaskRegister(pTaskMan self, TaskFunc pTask, SignalFunc pSignal, - TaskKillFunc pKill, void *pData, int iPriority) - { - pTaskHead pNew = NULL; - - assert(self); - assert(self->iID == TASKERID); - assert(pTask); - - pNew = MakeTaskHead(pTask,pSignal, pData, pKill); - if(!pNew) - { - return -1; - } - - /* link it in */ - if(self->pCurrent->pNext) - { - self->pCurrent->pNext->pPrevious = pNew; - } - pNew->pPrevious = self->pCurrent; - pNew->pNext = self->pCurrent->pNext; - self->pCurrent->pNext = pNew; - - return pNew->lID; - } -/*-------------------------------------------------------------------------*/ - static void IncrTaskPointer(pTaskMan self) - { - self->pCurrent = self->pCurrent->pNext; - if(self->pCurrent == NULL) - { - self->pCurrent = self->pHead; - } - } -/*-------------------------------------------------------------------------*/ - static int TaskExist(pTaskMan self, long lID) - { - pTaskHead pCur = self->pHead; - while(pCur != NULL) - { - if(pCur->lID == lID) - { - return 1; - } - pCur = pCur->pNext; - } + /* unlink */ + if (self->pPrevious != NULL) { + self->pPrevious->pNext = self->pNext; + } + if (self->pNext != NULL) { + self->pNext->pPrevious = self->pPrevious; + } + free(self); +} + +/*--------------------------------------------------------------------------*/ +static int DummyTask(void *pData) +{ + return 1; +} + +/*--------------------------------------------------------------------------*/ +int TaskerInit(pTaskMan * self) +{ + pTaskMan pNew = NULL; + pTaskHead pDummyTask = NULL; + + *self = NULL; + /* a new Task manager */ + pNew = (pTaskMan) malloc(sizeof(TaskMan)); + if (!pNew) { return 0; } + memset(pNew, 0, sizeof(TaskMan)); + pNew->iID = TASKERID; + + /* create a dummy task as start point */ + pDummyTask = MakeTaskHead(DummyTask, NULL, NULL, NULL); + if (!pDummyTask) { + free(pNew); + return 0; + } + + /* link */ + pDummyTask->pNext = NULL; + pDummyTask->pPrevious = NULL; + + pNew->pCurrent = pDummyTask; + pNew->pHead = pDummyTask; + *self = pNew; + return 1; +} + +/*---------------------------------------------------------------------------*/ +int TaskerDelete(pTaskMan * pData) +{ + pTaskMan self = *pData; + pTaskHead pCurrent, pKill; + + assert(self); + assert(self->iID == TASKERID); + + pCurrent = self->pHead; + while (pCurrent != NULL) { + pKill = pCurrent; + pCurrent = pCurrent->pNext; + DeleteTaskHead(pKill); + } + free(self); + *pData = NULL; + return 1; +} + +/*---------------------------------------------------------------------------*/ +long TaskRegister(pTaskMan self, TaskFunc pTask, SignalFunc pSignal, + TaskKillFunc pKill, void *pData, int iPriority) +{ + pTaskHead pNew = NULL; + + assert(self); + assert(self->iID == TASKERID); + assert(pTask); + + pNew = MakeTaskHead(pTask, pSignal, pData, pKill); + if (!pNew) { + return -1; + } + + /* link it in */ + if (self->pCurrent->pNext) { + self->pCurrent->pNext->pPrevious = pNew; + } + pNew->pPrevious = self->pCurrent; + pNew->pNext = self->pCurrent->pNext; + self->pCurrent->pNext = pNew; + + return pNew->lID; +} + +/*-------------------------------------------------------------------------*/ +static void IncrTaskPointer(pTaskMan self) +{ + self->pCurrent = self->pCurrent->pNext; + if (self->pCurrent == NULL) { + self->pCurrent = self->pHead; + } +} + +/*-------------------------------------------------------------------------*/ +static int TaskExist(pTaskMan self, long lID) +{ + pTaskHead pCur = self->pHead; + while (pCur != NULL) { + if (pCur->lID == lID) { + return 1; + } + pCur = pCur->pNext; + } + return 0; +} + /*--------------------------------------------------------------------------*/ - int TaskSchedule(pTaskMan self) - { - int iRet; - pTaskHead pTemp; - - assert(self); - assert(self->iID == TASKERID); - - /* forever, until stop is called somehow */ - while(self->iStop == 0) - { - if(self->pCurrent->iStatus == READY) - { - iRet = self->pCurrent->pRun(self->pCurrent->pData); - if(iRet != 1) - { - pTemp = self->pCurrent; - IncrTaskPointer(self); - DeleteTaskHead(pTemp); - } - else - { - IncrTaskPointer(self); - } - } - else - { - IncrTaskPointer(self); - } - } - return 1; - } -/*-----------------------------------------------------------------*/ - int TaskWait(pTaskMan self, long lID) - { - int iRet; - long lTest; - pTaskHead pTemp, pEnd; - - assert(self); - assert(self->iID == TASKERID); - - /* Cycle until lID is killed. Stop is obeyed as well */ - pEnd = self->pCurrent; - pEnd->iStatus = WAITING; - IncrTaskPointer(self); - while(self->iStop == 0) - { - if((self->pCurrent != pEnd) && (self->pCurrent->iStatus == READY) - && self->pCurrent != NULL) - /* omit ourselves! */ - { - iRet = self->pCurrent->pRun(self->pCurrent->pData); - if(iRet != 1) - { - pTemp = self->pCurrent; - lTest = pTemp->lID; - IncrTaskPointer(self); - DeleteTaskHead(pTemp); - if(lTest == lID) - { - goto ente; - } - } - else - { - IncrTaskPointer(self); - } - } - else - { - IncrTaskPointer(self); - } - if(self->pCurrent == self->pHead) - { - if(!TaskExist(self,lID)) - goto ente; - } - } - -ente: - /* task ended, we need to continue to pEnd before we are done */ - while(self->pCurrent != pEnd) - { +int TaskSchedule(pTaskMan self) +{ + int iRet; + pTaskHead pTemp; + + assert(self); + assert(self->iID == TASKERID); + + /* forever, until stop is called somehow */ + while (self->iStop == 0) { + if (self->pCurrent->iStatus == READY) { + iRet = self->pCurrent->pRun(self->pCurrent->pData); + if (iRet != 1) { + pTemp = self->pCurrent; + IncrTaskPointer(self); + DeleteTaskHead(pTemp); + } else { + IncrTaskPointer(self); + } + } else { IncrTaskPointer(self); } - pEnd->iStatus = READY; - return 1; - } -/*----------------------------------------------------------------*/ - int TaskYield(pTaskMan self) - { - int iRet; - long lTest; - pTaskHead pTemp, pEnd; - - assert(self); - assert(self->iID == TASKERID); - - /* Cycle until back at ourselves */ - pEnd = self->pCurrent; - pEnd->iStatus = WAITING; - IncrTaskPointer(self); - while((self->iStop == 0) && (self->pCurrent != pEnd)) - { - if((self->pCurrent != pEnd) && (self->pCurrent->iStatus == READY)) - /* omit ourselves! */ - { - iRet = self->pCurrent->pRun(self->pCurrent->pData); - if(iRet != 1) - { - pTemp = self->pCurrent; - lTest = pTemp->lID; - IncrTaskPointer(self); - DeleteTaskHead(pTemp); - } - else - { - IncrTaskPointer(self); - } - } - else - { - IncrTaskPointer(self); - } - } - pEnd->iStatus = READY; - return 1; - } + } + return 1; +} + +/*-----------------------------------------------------------------*/ +int TaskWait(pTaskMan self, long lID) +{ + int iRet; + long lTest; + pTaskHead pTemp, pEnd; + + assert(self); + assert(self->iID == TASKERID); + + /* Cycle until lID is killed. Stop is obeyed as well */ + pEnd = self->pCurrent; + pEnd->iStatus = WAITING; + IncrTaskPointer(self); + while (self->iStop == 0) { + if ((self->pCurrent != pEnd) && (self->pCurrent->iStatus == READY) + && self->pCurrent != NULL) + /* omit ourselves! */ + { + iRet = self->pCurrent->pRun(self->pCurrent->pData); + if (iRet != 1) { + pTemp = self->pCurrent; + lTest = pTemp->lID; + IncrTaskPointer(self); + DeleteTaskHead(pTemp); + if (lTest == lID) { + goto ente; + } + } else { + IncrTaskPointer(self); + } + } else { + IncrTaskPointer(self); + } + if (self->pCurrent == self->pHead) { + if (!TaskExist(self, lID)) + goto ente; + } + } + +ente: + /* task ended, we need to continue to pEnd before we are done */ + while (self->pCurrent != pEnd) { + IncrTaskPointer(self); + } + pEnd->iStatus = READY; + return 1; +} + +/*----------------------------------------------------------------*/ +int TaskYield(pTaskMan self) +{ + int iRet; + long lTest; + pTaskHead pTemp, pEnd; + + assert(self); + assert(self->iID == TASKERID); + + /* Cycle until back at ourselves */ + pEnd = self->pCurrent; + pEnd->iStatus = WAITING; + IncrTaskPointer(self); + while ((self->iStop == 0) && (self->pCurrent != pEnd)) { + if ((self->pCurrent != pEnd) && (self->pCurrent->iStatus == READY)) + /* omit ourselves! */ + { + iRet = self->pCurrent->pRun(self->pCurrent->pData); + if (iRet != 1) { + pTemp = self->pCurrent; + lTest = pTemp->lID; + IncrTaskPointer(self); + DeleteTaskHead(pTemp); + } else { + IncrTaskPointer(self); + } + } else { + IncrTaskPointer(self); + } + } + pEnd->iStatus = READY; + return 1; +} + /*---------------------------------------------------------------------------*/ - int TaskSignal(pTaskMan self, int iSignal, void *pSigData) - { - pTaskHead pTemp, pEnd; - - assert(self); - assert(self->iID == TASKERID); - - /* Do one cycle until we are at the caller, then return to him*/ - pEnd = self->pCurrent; - IncrTaskPointer(self); - while(self->pCurrent != pEnd) - { - if(self->pCurrent->pSignal) - { - self->pCurrent->pSignal(self->pCurrent->pData, iSignal, pSigData); - } - IncrTaskPointer(self); - } - /* finally, tell me about the thingie as well */ - if(pEnd->pSignal) - { - pEnd->pSignal(pEnd->pData, iSignal, pSigData); - } - - return 1; - } +int TaskSignal(pTaskMan self, int iSignal, void *pSigData) +{ + pTaskHead pTemp, pEnd; + + assert(self); + assert(self->iID == TASKERID); + + /* Do one cycle until we are at the caller, then return to him */ + pEnd = self->pCurrent; + IncrTaskPointer(self); + while (self->pCurrent != pEnd) { + if (self->pCurrent->pSignal) { + self->pCurrent->pSignal(self->pCurrent->pData, iSignal, pSigData); + } + IncrTaskPointer(self); + } + /* finally, tell me about the thingie as well */ + if (pEnd->pSignal) { + pEnd->pSignal(pEnd->pData, iSignal, pSigData); + } + + return 1; +} + /*--------------------------------------------------------------------------*/ - int TaskStop(pTaskMan self) - { - assert(self); - assert(self->iID == TASKERID); - - self->iStop = 1; - return 1; - } -/*--------------------------------------------------------------------------*/ - int TaskContinue(pTaskMan self) - { - assert(self); - assert(self->iID == TASKERID); - - self->iStop = 0; - return 1; - } +int TaskStop(pTaskMan self) +{ + assert(self); + assert(self->iID == TASKERID); + + self->iStop = 1; + return 1; +} + +/*--------------------------------------------------------------------------*/ +int TaskContinue(pTaskMan self) +{ + assert(self); + assert(self->iID == TASKERID); + + self->iStop = 0; + return 1; +} diff --git a/task.h b/task.h index 7be25cd6..e6db8a7d 100644 --- a/task.h +++ b/task.h @@ -13,7 +13,7 @@ #define TASKOMAT /*---------------------------------------------------------------------------*/ - typedef int (*TaskFunc)(void *pData); +typedef int (*TaskFunc) (void *pData); /* a task function must be implemented by each task. This function will be @@ -25,15 +25,15 @@ 1. */ /*--------------------------------------------------------------------------*/ - typedef void (*TaskKillFunc)(void *pData); +typedef void (*TaskKillFunc) (void *pData); /* Each task using private data structures must define this functions. It's task is to clear the private data structure of the task and free all memory associated with it. This function will be called automatically by the Tasker when a task finishes or when the whole Tasker is shut down. -*/ +*/ /*---------------------------------------------------------------------------*/ - typedef void (*SignalFunc)(void *pUser,int iSignal, void *pSigData); +typedef void (*SignalFunc) (void *pUser, int iSignal, void *pSigData); /* A SignalFunction can be implemented by each task. It is the means of @@ -43,78 +43,75 @@ ID's and signal data structures is up to the client of this code. */ /*--------------------------------------------------------------------------*/ - typedef struct __TaskHead *pTaskHead; - typedef struct __TaskMan *pTaskMan; +typedef struct __TaskHead *pTaskHead; +typedef struct __TaskMan *pTaskMan; /* two data structure used internally and defined in task.c */ /*=========================================================================== ALL FUNTIONS RETURN 0 on FAILURE, 1 ON SUCCESS WHEN NOT MENTIONED OTHERWISE -============================================================================*/ - int TaskerInit(pTaskMan *self); +============================================================================*/ +int TaskerInit(pTaskMan * self); /* Initalises a Task Manager. - */ - int TaskerDelete(pTaskMan *self); + */ +int TaskerDelete(pTaskMan * self); /* - Stops all running tasks and clears all data structures associated with - tasks and the TaskManager. - */ + Stops all running tasks and clears all data structures associated with + tasks and the TaskManager. + */ /*--------------------------------------------------------------------------*/ - long TaskRegister(pTaskMan self, TaskFunc pTaskRun, - SignalFunc pSignalFunc, - TaskKillFunc pKillFunc, - void *pData, - int iPriority); +long TaskRegister(pTaskMan self, TaskFunc pTaskRun, + SignalFunc pSignalFunc, + TaskKillFunc pKillFunc, void *pData, int iPriority); /* - This call enter a new task into the system. The caller has to - specify: - a TaskFunction [Required] - a SignalFunction [Optional, can be NULL] - a KillFunction for task private data. - [Optional, can be NULL] - a pointer to task private data - [Optional, can be NULL] - a priority for this task. This is currently unused. - On Success a positive value denoting the ID of the task is returned. - On error a negative value is returned. - */ -/*-------------------------------------------------------------------------*/ - int TaskSchedule(pTaskMan self); + This call enter a new task into the system. The caller has to + specify: + a TaskFunction [Required] + a SignalFunction [Optional, can be NULL] + a KillFunction for task private data. + [Optional, can be NULL] + a pointer to task private data + [Optional, can be NULL] + a priority for this task. This is currently unused. + On Success a positive value denoting the ID of the task is returned. + On error a negative value is returned. + */ +/*-------------------------------------------------------------------------*/ +int TaskSchedule(pTaskMan self); /* - Starts task switching. - */ + Starts task switching. + */ /*-----------------------------------------------------------------------*/ - int TaskStop(pTaskMan self); +int TaskStop(pTaskMan self); /* - Interrupts task switching all together - */ + Interrupts task switching all together + */ /*------------------------------------------------------------------------*/ - int TaskContinue(pTaskMan self); +int TaskContinue(pTaskMan self); /* - Continues an task switching session interrupted by TaskStop. After this - the apopriate TaskYield, TaskSchedule or wahtever has to be called. - */ + Continues an task switching session interrupted by TaskStop. After this + the apopriate TaskYield, TaskSchedule or wahtever has to be called. + */ /*-------------------------------------------------------------------------*/ - int TaskWait(pTaskMan self, long lID); +int TaskWait(pTaskMan self, long lID); /* - Waits until the task specified by lID has finished. lID is obtained from - a call to TaskRegister. - */ + Waits until the task specified by lID has finished. lID is obtained from + a call to TaskRegister. + */ /*-------------------------------------------------------------------------*/ - int TaskYield(pTaskMan self); +int TaskYield(pTaskMan self); /* - does one cycle of the task loop and returns to the caller.This call allows - other tasks to execute while a task executes a lengthy calculation. - */ + does one cycle of the task loop and returns to the caller.This call allows + other tasks to execute while a task executes a lengthy calculation. + */ /*--------------------------------------------------------------------------*/ - int TaskSignal(pTaskMan self, int iSignal, void *pSigData); +int TaskSignal(pTaskMan self, int iSignal, void *pSigData); /* - Invokes each Task's signal function with parameters iSignal and - pSigData. - */ + Invokes each Task's signal function with parameters iSignal and + pSigData. + */ /*-------------------------------------------------------------------------*/ - + #endif - diff --git a/tasscanub.c b/tasscanub.c index 2b0fbbaf..df7eaa4b 100644 --- a/tasscanub.c +++ b/tasscanub.c @@ -29,90 +29,93 @@ -------------------------------------------------------------------------*/ static void charLine(char *pBueffel, char c) { - int i; + int i; - for(i = 0; i < 80; i++) - { - pBueffel[i] = c; - } - pBueffel[80] = '\n'; - pBueffel[81] = '\0'; + for (i = 0; i < 80; i++) { + pBueffel[i] = c; + } + pBueffel[80] = '\n'; + pBueffel[81] = '\0'; } + /*------------------------------------------------------------------------*/ static void strtoupper(char *pText) { - assert(pText); - - while(*pText != '\0') - { - *pText = toupper(*pText); - pText++; - } + assert(pText); + + while (*pText != '\0') { + *pText = toupper(*pText); + pText++; + } } + /*-----------------------------------------------------------------------*/ static void strcenter(char *str, char *target, int iLength) { int iPtr, i; /* - catch the error if target is to long - */ - if(strlen(str) >= iLength) - { - strncpy(target,str,iLength); + catch the error if target is to long + */ + if (strlen(str) >= iLength) { + strncpy(target, str, iLength); } - iPtr = (iLength - strlen(str))/2; - for(i = 0; i < iPtr;i++) - { + iPtr = (iLength - strlen(str)) / 2; + for (i = 0; i < iPtr; i++) { target[i] = ' '; } target[iPtr] = '\0'; - strcat(target,str); - for(i = iPtr + strlen(str); i < iLength - 1; i++) - { + strcat(target, str); + for (i = iPtr + strlen(str); i < iLength - 1; i++) { target[i] = ' '; } - target[iLength-1] = '\0'; + target[iLength - 1] = '\0'; } + /*----------------------------------------------------------------------*/ -static char *GetVarText(char *name) { +static char *GetVarText(char *name) +{ pSicsVariable pVar = NULL; - pVar = (pSicsVariable)FindCommandData(pServ->pSics,name, "SicsVariable"); - if(pVar != NULL){ + pVar = + (pSicsVariable) FindCommandData(pServ->pSics, name, "SicsVariable"); + if (pVar != NULL) { return pVar->text; } else { return NULL; } } + /*----------------------------------------------------------------------- helper function for TASHeader ------------------------------------------------------------------------*/ -static void writePolFile(FILE *fd, pTASdata pTAS){ +static void writePolFile(FILE * fd, pTASdata pTAS) +{ char pLine[132]; FILE *fpol = NULL; assert(fd); assert(pTAS); - fpol = fopen(GetVarText("polfile"),"r"); - if(!fpol){ + fpol = fopen(GetVarText("polfile"), "r"); + if (!fpol) { /* - error gets reported anyway later on - */ + error gets reported anyway later on + */ return; } - - while(fgets(pLine,131,fpol) != NULL){ - if(strstr(pLine,"\n") == NULL){ - fprintf(fd,"POLAN: %s\n", pLine); + + while (fgets(pLine, 131, fpol) != NULL) { + if (strstr(pLine, "\n") == NULL) { + fprintf(fd, "POLAN: %s\n", pLine); } else { - fprintf(fd,"POLAN: %s", pLine); + fprintf(fd, "POLAN: %s", pLine); } } fclose(fpol); } + /*-----------------------------------------------------------------------*/ static char *findLastPoint(char *text) { @@ -120,21 +123,21 @@ static char *findLastPoint(char *text) int i; pPtr = text + strlen(text) - 1; - for(i = strlen(text); i > 0; i--, pPtr--) - { - if(*pPtr == '.') - { + for (i = strlen(text); i > 0; i--, pPtr--) { + if (*pPtr == '.') { return pPtr; } } return NULL; } + /*----------------------------------------------------------------------- readDrivable tries to read the value of one of the magnet currents. All errors are ignored because most of the time currents will not be present in the system. -----------------------------------------------------------------------*/ -static float readDrivable(char *val, SConnection *pCon){ +static float readDrivable(char *val, SConnection * pCon) +{ pIDrivable pDriv; CommandList *pCom; pDummy pDum; @@ -142,39 +145,44 @@ static float readDrivable(char *val, SConnection *pCon){ float fVal; /* - read general drivable - */ - pCom = FindCommand(pServ->pSics,val); - if(pCom != NULL){ + read general drivable + */ + pCom = FindCommand(pServ->pSics, val); + if (pCom != NULL) { pDriv = GetDrivableInterface(pCom->pData); - if(pDriv != NULL){ - return pDriv->GetValue(pCom->pData,pCon); + if (pDriv != NULL) { + return pDriv->GetValue(pCom->pData, pCon); } } return -999.99; } + /*-----------------------------------------------------------------------*/ -static float GetVarFloat(char *name){ +static float GetVarFloat(char *name) +{ pSicsVariable pVar = NULL; - pVar = (pSicsVariable)FindCommandData(pServ->pSics,name, "SicsVariable"); - if(pVar != NULL){ + pVar = + (pSicsVariable) FindCommandData(pServ->pSics, name, "SicsVariable"); + if (pVar != NULL) { return pVar->fVal; } else { return -999.99; } } + /*------------------------------------------------------------------------- TASHeader writes the header of a TAS data file. The format is an obscure format from ILL ( not ill but Institute Laue Langevin). No documentation about this exists except the files themselves. This is long and tiresome code. ----------------------------------------------------------------------------*/ +---------------------------------------------------------------------------*/ static int TASUBHeader(pScanData self) { - pTASdata pTAS = (pTASdata)self->pSpecial; + pTASdata pTAS = (pTASdata) self->pSpecial; int i, iCount, status, iFileNO; - char pBueffel[1024], pHeader[1024], pWork[132], pWork2[60], pTen[12], *pcPtr; + char pBueffel[1024], pHeader[1024], pWork[132], pWork2[60], pTen[12], + *pcPtr; time_t iDate; struct tm *psTime; pVarEntry pVar = NULL; @@ -197,385 +205,338 @@ static int TASUBHeader(pScanData self) assert(self->pSics); /* open data file */ - self->fd = fopen(self->pFile,"w"); - if(!self->fd) - { - SCWrite(self->pCon,"ERROR: cannot write data file",eLogError); - return 0; + self->fd = fopen(self->pFile, "w"); + if (!self->fd) { + SCWrite(self->pCon, "ERROR: cannot write data file", eLogError); + return 0; } /* - extract the file number from the name for entry into the - datafile - */ + extract the file number from the name for entry into the + datafile + */ pcPtr = findLastPoint(self->pFile); - if(pcPtr != NULL) - { - pcPtr -= 6; /* 6 digits for number */ - for(i = 0; i < 6; i++, pcPtr++) - { + if (pcPtr != NULL) { + pcPtr -= 6; /* 6 digits for number */ + for (i = 0; i < 6; i++, pcPtr++) { pWork[i] = *pcPtr; } pWork[6] = '\0'; iFileNO = atoi(pWork); - } - else - { - SCWrite(self->pCon,"WARNING: failed to decode file number",eLog); + } else { + SCWrite(self->pCon, "WARNING: failed to decode file number", eLog); } /* the bizarre R, A, V header */ - charLine(pBueffel,'R'); - fputs(pBueffel,self->fd); - fprintf(self->fd,"%8d%8d%8d\n",iFileNO,1,0); - fputs("ILL TAS data in the new ASCII format follow after the line VV...V\n", - self->fd); - charLine(pBueffel,'A'); - fputs(pBueffel,self->fd); - fprintf(self->fd,"%8d%8d\n",42,0); + charLine(pBueffel, 'R'); + fputs(pBueffel, self->fd); + fprintf(self->fd, "%8d%8d%8d\n", iFileNO, 1, 0); + fputs + ("ILL TAS data in the new ASCII format follow after the line VV...V\n", + self->fd); + charLine(pBueffel, 'A'); + fputs(pBueffel, self->fd); + fprintf(self->fd, "%8d%8d\n", 42, 0); /* - format time to TAS format - */ + format time to TAS format + */ iDate = time(NULL); psTime = localtime(&iDate); - memset(pWork,0,59); - strftime(pWork,59,"%d-%b-%Y %H:%M:%S",psTime); - fprintf(self->fd,"%-10s%-12s%-s\n",GetVarText("instrument"), - GetVarText("user"),pWork); + memset(pWork, 0, 59); + strftime(pWork, 59, "%d-%b-%Y %H:%M:%S", psTime); + fprintf(self->fd, "%-10s%-12s%-s\n", GetVarText("instrument"), + GetVarText("user"), pWork); - charLine(pBueffel,'V'); - fputs(pBueffel,self->fd); + charLine(pBueffel, 'V'); + fputs(pBueffel, self->fd); /* - output a plethora of parameters - */ - fprintf(self->fd,"INSTR: %s\n",GetVarText("instrument")); - fprintf(self->fd,"EXPNO: \n"); - fprintf(self->fd,"USER_: %s\n",GetVarText("user")); - fprintf(self->fd,"LOCAL: %s\n",GetVarText("local")); - fprintf(self->fd,"FILE_: %d\n",iFileNO); - fprintf(self->fd,"DATE_: %s\n",pWork); - fprintf(self->fd,"TITLE: %s\n",GetVarText("title")); - fprintf(self->fd,"COMND: %s\n",GetVarText("lastscancommand")); + output a plethora of parameters + */ + fprintf(self->fd, "INSTR: %s\n", GetVarText("instrument")); + fprintf(self->fd, "EXPNO: \n"); + fprintf(self->fd, "USER_: %s\n", GetVarText("user")); + fprintf(self->fd, "LOCAL: %s\n", GetVarText("local")); + fprintf(self->fd, "FILE_: %d\n", iFileNO); + fprintf(self->fd, "DATE_: %s\n", pWork); + fprintf(self->fd, "TITLE: %s\n", GetVarText("title")); + fprintf(self->fd, "COMND: %s\n", GetVarText("lastscancommand")); fprintf(self->fd, - "POSQE: QH=%8.4f, QK=%8.4f, QL=%8.4f, EN=%8.4f, UN=MEV\n", + "POSQE: QH=%8.4f, QK=%8.4f, QL=%8.4f, EN=%8.4f, UN=MEV\n", pTAS->ub->current.qh, pTAS->ub->current.qk, - pTAS->ub->current.qk, - getTasPar(pTAS->ub->current,EN)); + pTAS->ub->current.qk, getTasPar(pTAS->ub->current, EN)); /* - build the steps line - */ - sprintf(pBueffel,"STEPS: "); - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - strncpy(pWork2,ScanVarName(pVar),59); - strtoupper(pWork2); - sprintf(pWork,"D%s=%8.4f, ",pWork2,ScanVarStep(pVar)); - strcat(pBueffel,pWork); - } - } - strcat(pBueffel,"\n"); - fputs(pBueffel,self->fd); + build the steps line + */ + sprintf(pBueffel, "STEPS: "); + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + strncpy(pWork2, ScanVarName(pVar), 59); + strtoupper(pWork2); + sprintf(pWork, "D%s=%8.4f, ", pWork2, ScanVarStep(pVar)); + strcat(pBueffel, pWork); + } + } + strcat(pBueffel, "\n"); + fputs(pBueffel, self->fd); /* - a lot of parameters - */ - fprintf(self->fd,"PARAM: DM=%8.4f, DA=%8.4f, SM=%2d, SS=%2d, SA=%2d\n", + a lot of parameters + */ + fprintf(self->fd, "PARAM: DM=%8.4f, DA=%8.4f, SM=%2d, SS=%2d, SA=%2d\n", pTAS->ub->machine.monochromator.dd, pTAS->ub->machine.analyzer.dd, pTAS->ub->machine.monochromator.ss, - pTAS->ub->machine.ss_sample, - pTAS->ub->machine.analyzer.ss); - if(pTAS->ub->tasMode == KICONST){ + pTAS->ub->machine.ss_sample, pTAS->ub->machine.analyzer.ss); + if (pTAS->ub->tasMode == KICONST) { fx = 2; - kfix = getTasPar(pTAS->ub->current,KI); + kfix = getTasPar(pTAS->ub->current, KI); } else { fx = 1; - kfix = getTasPar(pTAS->ub->current,KF); + kfix = getTasPar(pTAS->ub->current, KF); } - fprintf(self->fd,"PARAM: FX=%3d, KFIX=%8.4f\n", - fx, - kfix); - fprintf(self->fd,"PARAM: ALF1=%8.4f, ALF2=%8.4f, ALF3=%8.4f, ALF4=%8.4f\n", - GetVarFloat("alf1"), - GetVarFloat("alf2"), - GetVarFloat("alf3"), + fprintf(self->fd, "PARAM: FX=%3d, KFIX=%8.4f\n", fx, kfix); + fprintf(self->fd, + "PARAM: ALF1=%8.4f, ALF2=%8.4f, ALF3=%8.4f, ALF4=%8.4f\n", + GetVarFloat("alf1"), GetVarFloat("alf2"), GetVarFloat("alf3"), GetVarFloat("alf4")); - fprintf(self->fd,"PARAM: BET1=%8.4f, BET2=%8.4f, BET3=%8.4f, BET4=%8.4f\n", - GetVarFloat("bet1"), - GetVarFloat("bet2"), - GetVarFloat("bet3"), + fprintf(self->fd, + "PARAM: BET1=%8.4f, BET2=%8.4f, BET3=%8.4f, BET4=%8.4f\n", + GetVarFloat("bet1"), GetVarFloat("bet2"), GetVarFloat("bet3"), GetVarFloat("bet4")); - fprintf(self->fd,"PARAM: ETAM=%8.4f, ETAA=%8.4f\n", - GetVarFloat("etam"), + fprintf(self->fd, "PARAM: ETAM=%8.4f, ETAA=%8.4f\n", GetVarFloat("etam"), GetVarFloat("etaa")); - fprintf(self->fd,"PARAM: AS=%8.4f, BS=%8.4f, CS=%8.4f\n", - pTAS->ub->cell.a, - pTAS->ub->cell.b, - pTAS->ub->cell.c); - fprintf(self->fd,"PARAM: AA=%8.4f, BB=%8.4f, CC=%8.4f\n", - pTAS->ub->cell.alpha, - pTAS->ub->cell.beta, - pTAS->ub->cell.gamma); + fprintf(self->fd, "PARAM: AS=%8.4f, BS=%8.4f, CS=%8.4f\n", + pTAS->ub->cell.a, pTAS->ub->cell.b, pTAS->ub->cell.c); + fprintf(self->fd, "PARAM: AA=%8.4f, BB=%8.4f, CC=%8.4f\n", + pTAS->ub->cell.alpha, pTAS->ub->cell.beta, pTAS->ub->cell.gamma); r = pTAS->ub->r1; - fprintf(self->fd,"PARAM: AX=%8.4f, AY=%8.4f, AZ=%8.4f\n", - r.qe.qh, - r.qe.qk, - r.qe.ql); + fprintf(self->fd, "PARAM: AX=%8.4f, AY=%8.4f, AZ=%8.4f\n", + r.qe.qh, r.qe.qk, r.qe.ql); r = pTAS->ub->r2; - fprintf(self->fd,"PARAM: BX=%8.4f, BY=%8.4f, BZ=%8.4f\n", - r.qe.qh, - r.qe.qk, - r.qe.ql); + fprintf(self->fd, "PARAM: BX=%8.4f, BY=%8.4f, BZ=%8.4f\n", + r.qe.qh, r.qe.qk, r.qe.ql); /* * write mupad stuff if available */ - sVar = FindCommandData(pServ->pSics,"w1","SicsVariable"); - if(sVar != NULL) - { + sVar = FindCommandData(pServ->pSics, "w1", "SicsVariable"); + if (sVar != NULL) { f1 = sVar->fVal; - sVar = FindCommandData(pServ->pSics,"w2","SicsVariable"); - if(sVar != NULL) - { - f2 = sVar->fVal; - } - sVar = FindCommandData(pServ->pSics,"w3","SicsVariable"); - if(sVar != NULL) - { - f3 = sVar->fVal; - } - sVar = FindCommandData(pServ->pSics,"w4","SicsVariable"); - if(sVar != NULL) - { - f4 = sVar->fVal; - } - fprintf(self->fd,"PARAM: W1=%8.4f, W2=%8.4f, W3=%8.4f, W4=%8.4f\n", - f1, f2, f3, f4); - - sVar = FindCommandData(pServ->pSics,"p1","SicsVariable"); - if(sVar != NULL) - { - f1 = sVar->fVal; - } - sVar = FindCommandData(pServ->pSics,"p2","SicsVariable"); - if(sVar != NULL) - { - f2 = sVar->fVal; - } - sVar = FindCommandData(pServ->pSics,"p3","SicsVariable"); - if(sVar != NULL) - { - f3 = sVar->fVal; - } - sVar = FindCommandData(pServ->pSics,"p4","SicsVariable"); - if(sVar != NULL) - { - f4 = sVar->fVal; - } - fprintf(self->fd,"PARAM: P1=%8.4f, P2=%8.4f, P3=%8.4f, P4=%8.4f\n", - f1, f2, f3, f4); - - - } + sVar = FindCommandData(pServ->pSics, "w2", "SicsVariable"); + if (sVar != NULL) { + f2 = sVar->fVal; + } + sVar = FindCommandData(pServ->pSics, "w3", "SicsVariable"); + if (sVar != NULL) { + f3 = sVar->fVal; + } + sVar = FindCommandData(pServ->pSics, "w4", "SicsVariable"); + if (sVar != NULL) { + f4 = sVar->fVal; + } + fprintf(self->fd, "PARAM: W1=%8.4f, W2=%8.4f, W3=%8.4f, W4=%8.4f\n", + f1, f2, f3, f4); + + sVar = FindCommandData(pServ->pSics, "p1", "SicsVariable"); + if (sVar != NULL) { + f1 = sVar->fVal; + } + sVar = FindCommandData(pServ->pSics, "p2", "SicsVariable"); + if (sVar != NULL) { + f2 = sVar->fVal; + } + sVar = FindCommandData(pServ->pSics, "p3", "SicsVariable"); + if (sVar != NULL) { + f3 = sVar->fVal; + } + sVar = FindCommandData(pServ->pSics, "p4", "SicsVariable"); + if (sVar != NULL) { + f4 = sVar->fVal; + } + fprintf(self->fd, "PARAM: P1=%8.4f, P2=%8.4f, P3=%8.4f, P4=%8.4f\n", + f1, f2, f3, f4); + + + } /* - write currents if in polarisation mode - */ - if(pTAS->iPOL >= 0){ - fprintf(self->fd,"VARIA: "); - iCount = 0; - for(i = 0; i < 8; i++) - { - snprintf(pWork2,59,"i%1.1d",i); - fVal = readDrivable(pWork2,self->pCon); - strtoupper(pWork2); - fprintf(self->fd,"%-8s=%8.4f, ",pWork2,fVal); - iCount++; - } - fprintf(self->fd,"\n"); + write currents if in polarisation mode + */ + if (pTAS->iPOL >= 0) { + fprintf(self->fd, "VARIA: "); + iCount = 0; + for (i = 0; i < 8; i++) { + snprintf(pWork2, 59, "i%1.1d", i); + fVal = readDrivable(pWork2, self->pCon); + strtoupper(pWork2); + fprintf(self->fd, "%-8s=%8.4f, ", pWork2, fVal); + iCount++; + } + fprintf(self->fd, "\n"); } /* - write motors - */ - fprintf(self->fd,"VARIA: "); + write motors + */ + fprintf(self->fd, "VARIA: "); iCount = 0; pCom = pServ->pSics->pCList; - while(pCom != NULL) - { - pDum = (pDummy)pCom->pData; - if(pDum != NULL ) - { - if(strcmp(pDum->pDescriptor->name,"Motor") == 0) - { - fVal = readDrivable(pCom->pName,self->pCon); - if(iCount == 3) - { - iCount = 0; - fprintf(self->fd,"\nVARIA: "); - } - strcpy(pWork2,pCom->pName); - strtoupper(pWork2); - fprintf(self->fd,"%-8s=%8.4f, ",pWork2,fVal); - iCount++; + while (pCom != NULL) { + pDum = (pDummy) pCom->pData; + if (pDum != NULL) { + if (strcmp(pDum->pDescriptor->name, "Motor") == 0) { + fVal = readDrivable(pCom->pName, self->pCon); + if (iCount == 3) { + iCount = 0; + fprintf(self->fd, "\nVARIA: "); + } + strcpy(pWork2, pCom->pName); + strtoupper(pWork2); + fprintf(self->fd, "%-8s=%8.4f, ", pWork2, fVal); + iCount++; } } pCom = pCom->pNext; } - fprintf(self->fd,"\n"); - + fprintf(self->fd, "\n"); + /* - write zeros - */ - fprintf(self->fd,"ZEROS: "); + write zeros + */ + fprintf(self->fd, "ZEROS: "); iCount = 0; pCom = pServ->pSics->pCList; - while(pCom != NULL) - { - pDum = (pDummy)pCom->pData; - if(pDum != NULL ) - { - if(strcmp(pDum->pDescriptor->name,"Motor") == 0) - { - pMot = (pMotor)pCom->pData; - if(pMot) - { - status = MotorGetPar(pMot,"softzero",&fVal); - if(!status) - { - fVal = -9999.77; - } - fVal *= -1; - if(iCount == 3) - { - iCount = 0; - fprintf(self->fd,"\nZEROS: "); - } - strcpy(pWork2,pCom->pName); - strtoupper(pWork2); - fprintf(self->fd,"%-8s=%8.4f, ",pWork2,fVal); - iCount++; - } + while (pCom != NULL) { + pDum = (pDummy) pCom->pData; + if (pDum != NULL) { + if (strcmp(pDum->pDescriptor->name, "Motor") == 0) { + pMot = (pMotor) pCom->pData; + if (pMot) { + status = MotorGetPar(pMot, "softzero", &fVal); + if (!status) { + fVal = -9999.77; + } + fVal *= -1; + if (iCount == 3) { + iCount = 0; + fprintf(self->fd, "\nZEROS: "); + } + strcpy(pWork2, pCom->pName); + strtoupper(pWork2); + fprintf(self->fd, "%-8s=%8.4f, ", pWork2, fVal); + iCount++; + } } } pCom = pCom->pNext; } - fprintf(self->fd,"\n"); + fprintf(self->fd, "\n"); - if(pTAS->iPOL >= 0){ - writePolFile(self->fd,pTAS); + if (pTAS->iPOL >= 0) { + writePolFile(self->fd, pTAS); } /* - write counter parameters - */ + write counter parameters + */ fVal = GetCounterPreset(self->pCounterData); - if(GetCounterMode(self->pCounterData) == eTimer) - { - fprintf(self->fd,"PARAM: TI=%8.4f\n",fVal); + if (GetCounterMode(self->pCounterData) == eTimer) { + fprintf(self->fd, "PARAM: TI=%8.4f\n", fVal); + } else { + fprintf(self->fd, "PARAM: MN=%8f\n", fVal); } - else - { - fprintf(self->fd,"PARAM: MN=%8f\n",fVal); - } - + /* - write temperature data - */ - pCom = FindCommand(self->pSics,"temperature"); - if(pCom) - { - pDum = (pDummy)pCom->pData; - pDrive = pDum->pDescriptor->GetInterface(pDum,DRIVEID); - if(pDrive) /* a proper environment device */ - { - fVal = pDrive->GetValue(pDum,self->pCon); - pTem = (pEVControl)pCom->pData; - EVCGetPar(pTem,"target",&fVal2); - fprintf(self->fd,"PARAM: TT=%8.4f, RT=%8.4f\n",fVal, fVal2); - } + write temperature data + */ + pCom = FindCommand(self->pSics, "temperature"); + if (pCom) { + pDum = (pDummy) pCom->pData; + pDrive = pDum->pDescriptor->GetInterface(pDum, DRIVEID); + if (pDrive) { /* a proper environment device */ + fVal = pDrive->GetValue(pDum, self->pCon); + pTem = (pEVControl) pCom->pData; + EVCGetPar(pTem, "target", &fVal2); + fprintf(self->fd, "PARAM: TT=%8.4f, RT=%8.4f\n", fVal, fVal2); + } } - + /* build both the format and the data header line, start with the scan variables - */ - if(pTAS->iPOL >= 0 ){ - strcpy(pBueffel,"FORMT: (I4,I4,"); - strcpy(pHeader," PNT PAL"); + */ + if (pTAS->iPOL >= 0) { + strcpy(pBueffel, "FORMT: (I4,I4,"); + strcpy(pHeader, " PNT PAL"); } else { - strcpy(pBueffel,"FORMT: (I4,1X,"); - strcpy(pHeader," PNT "); + strcpy(pBueffel, "FORMT: (I4,1X,"); + strcpy(pHeader, " PNT "); } - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - strcat(pBueffel,"F9.4,1X,"); - strncpy(pWork2,pVar->Name,59); - strtoupper(pWork2); - strcenter(pWork2,pTen,11); - strcat(pHeader,pTen); - } - } - /* - put the standard counter things - */ - strcat(pBueffel,"F8.0,1X,F8.0,1X,F9.2,1X,F8.0,1X,F8.0,1X,"); - strcat(pHeader," M1 M2 TIME CNTS M3 "); - /* - now the additional variables - */ - for(i = 0; i < pTAS->addCount; i++) - { - if(i == pTAS->addCount -1){ - strcat(pBueffel,"F9.4"); - } else { - strcat(pBueffel,"F9.4,1X,"); + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + strcat(pBueffel, "F9.4,1X,"); + strncpy(pWork2, pVar->Name, 59); + strtoupper(pWork2); + strcenter(pWork2, pTen, 11); + strcat(pHeader, pTen); } - strcpy(pWork2,pTAS->out[i]); - strtoupper(pWork2); - strcenter(pWork2,pTen,11); - strcat(pHeader,pTen); - } - strcat(pBueffel,")"); + } + /* + put the standard counter things + */ + strcat(pBueffel, "F8.0,1X,F8.0,1X,F9.2,1X,F8.0,1X,F8.0,1X,"); + strcat(pHeader, " M1 M2 TIME CNTS M3 "); + /* + now the additional variables + */ + for (i = 0; i < pTAS->addCount; i++) { + if (i == pTAS->addCount - 1) { + strcat(pBueffel, "F9.4"); + } else { + strcat(pBueffel, "F9.4,1X,"); + } + strcpy(pWork2, pTAS->out[i]); + strtoupper(pWork2); + strcenter(pWork2, pTen, 11); + strcat(pHeader, pTen); + } + strcat(pBueffel, ")"); /* - write the final bit - */ - fprintf(self->fd,"%s\nDATA_:\n%s\n",pBueffel,pHeader); + write the final bit + */ + fprintf(self->fd, "%s\nDATA_:\n%s\n", pBueffel, pHeader); /* - write header to screen as well - */ - SCWrite(self->pCon,pHeader,eLog); + write header to screen as well + */ + SCWrite(self->pCon, pHeader, eLog); /* - close the file, we will reopen later with append for the data - */ + close the file, we will reopen later with append for the data + */ fclose(self->fd); self->fd = NULL; return 1; } + /*-------------------------------------------------------------------------- TASScanPoint writes the data at each ScanPoint ---------------------------------------------------------------------------*/ static int TASUBScanPoint(pScanData self, int iPoint) { - pTASdata pTAS = (pTASdata)self->pSpecial; + pTASdata pTAS = (pTASdata) self->pSpecial; pVarEntry pVar = NULL; void *pPtr = NULL; int i, status, iPtr; @@ -585,98 +546,91 @@ static int TASUBScanPoint(pScanData self, int iPoint) char pBueffel[1024], pWork[80], pError[132]; /* - after polarisation analysis, this has to be ignored as it is called - another time from the ScanLoop - */ - if(pTAS->iIgnore){ + after polarisation analysis, this has to be ignored as it is called + another time from the ScanLoop + */ + if (pTAS->iIgnore) { return 1; } /* - reopen file for appending - */ - self->fd = fopen(self->pFile,"a"); - if(!self->fd) - { - SCWrite(self->pCon,"ERROR: cannot append to data file",eLogError); - return 0; + reopen file for appending + */ + self->fd = fopen(self->pFile, "a"); + if (!self->fd) { + SCWrite(self->pCon, "ERROR: cannot append to data file", eLogError); + return 0; } /* write point number - */ - if(pTAS->iPOL >= 0) - { - sprintf(pBueffel,"%3d %3d",iPoint+1,pTAS->iPOL); - } - else - { - sprintf(pBueffel,"%4d ", iPoint+1); + */ + if (pTAS->iPOL >= 0) { + sprintf(pBueffel, "%3d %3d", iPoint + 1, pTAS->iPOL); + } else { + sprintf(pBueffel, "%4d ", iPoint + 1); } /* - write the scan variables - */ - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - fVal = readDrivable(ScanVarName(pVar),self->pCon); - } - sprintf(pWork,"%9.4f ", fVal); - strcat(pBueffel,pWork); + write the scan variables + */ + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + fVal = readDrivable(ScanVarName(pVar), self->pCon); + } + sprintf(pWork, "%9.4f ", fVal); + strcat(pBueffel, pWork); } /* - write monitors and counters - */ - m1 = GetMonitor(self->pCounterData,1,self->pCon); - m2 = GetMonitor(self->pCounterData,2,self->pCon); - m3 = GetMonitor(self->pCounterData,3,self->pCon); - cnts = GetCounts(self->pCounterData,self->pCon); + write monitors and counters + */ + m1 = GetMonitor(self->pCounterData, 1, self->pCon); + m2 = GetMonitor(self->pCounterData, 2, self->pCon); + m3 = GetMonitor(self->pCounterData, 3, self->pCon); + cnts = GetCounts(self->pCounterData, self->pCon); fVal = GetCountTime(self->pCounterData, self->pCon); - sprintf(pWork,"%8ld %8ld %9.2f %8ld %8ld ",m1,m2,fVal, cnts, m3); - strcat(pBueffel,pWork); + sprintf(pWork, "%8ld %8ld %9.2f %8ld %8ld ", m1, m2, fVal, cnts, m3); + strcat(pBueffel, pWork); /* write additional parameters - */ - for(i = 0; i < pTAS->addCount; i++) - { + */ + for (i = 0; i < pTAS->addCount; i++) { fVal = -999.99; - fVal = readDrivable(pTAS->out[i],self->pCon); - if(fVal < -990.){ - snprintf(pError,131,"WARNING: problem reading %s", - pTAS->out[i]); - SCWrite(self->pCon, pError,eWarning); + fVal = readDrivable(pTAS->out[i], self->pCon); + if (fVal < -990.) { + snprintf(pError, 131, "WARNING: problem reading %s", pTAS->out[i]); + SCWrite(self->pCon, pError, eWarning); } - sprintf(pWork,"%9.4f ", fVal); - strcat(pBueffel,pWork); + sprintf(pWork, "%9.4f ", fVal); + strcat(pBueffel, pWork); } /* - write both to file and onto screen - */ - fprintf(self->fd,"%s\n",pBueffel); - SCWrite(self->pCon,pBueffel,eLog); + write both to file and onto screen + */ + fprintf(self->fd, "%s\n", pBueffel); + SCWrite(self->pCon, pBueffel, eLog); /* - close the file - */ + close the file + */ fclose(self->fd); self->fd = NULL; return 1; - -} + +} + /*------------------------------------------------------------------------ TASScanDrive starts all the motors necessary to drive to a new scan position. It thereby takes care of the TAS calculation if necessary. -------------------------------------------------------------------------*/ static int TASUBScanDrive(pScanData self, int iPoint) { - pTASdata pTAS = (pTASdata)self->pSpecial; + pTASdata pTAS = (pTASdata) self->pSpecial; pVarEntry pVar = NULL; void *pPtr = NULL; int i, status, iPtr; @@ -685,38 +639,34 @@ static int TASUBScanDrive(pScanData self, int iPoint) pTAS->ub->silent = 1; /* - loop through all the scan variables - */ - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pPtr); - pVar = (pVarEntry)pPtr; - if(pVar) - { - StartMotor(pServ->pExecutor,self->pSics, self->pCon, pVar->Name, - pVar->fStart + iPoint * pVar->fStep); - /* - Ignore errors. TAS scans continues when a motor runs into - a limit. - */ - } + loop through all the scan variables + */ + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pPtr); + pVar = (pVarEntry) pPtr; + if (pVar) { + StartMotor(pServ->pExecutor, self->pSics, self->pCon, pVar->Name, + pVar->fStart + iPoint * pVar->fStep); + /* + Ignore errors. TAS scans continues when a motor runs into + a limit. + */ + } } /* - now wait for our motors to arrive, thereby ignoring any error - returns. DO NOT WAIT if fast scan! - */ - if(pTAS->iFast) - { - return 1; - } - else - { - status = Wait4Success(GetExecutor()); - pTAS->ub->silent = 0; + now wait for our motors to arrive, thereby ignoring any error + returns. DO NOT WAIT if fast scan! + */ + if (pTAS->iFast) { + return 1; + } else { + status = Wait4Success(GetExecutor()); + pTAS->ub->silent = 0; } return 1; } + /*----------------------------------------------------------------------- RunPolScan does a polarized scan ------------------------------------------------------------------------*/ @@ -724,29 +674,29 @@ static int RunPolScan(pScanData self, int iPoint) { FILE *fd = NULL; char buffer[132]; - pTASdata pTAS = (pTASdata)self->pSpecial; + pTASdata pTAS = (pTASdata) self->pSpecial; - fd = fopen(GetVarText("polfile"),"r"); - if(!fd){ - SCWrite(self->pCon,"ERROR: failed to open polarisation analysis file", - eError); + fd = fopen(GetVarText("polfile"), "r"); + if (!fd) { + SCWrite(self->pCon, "ERROR: failed to open polarisation analysis file", + eError); return 0; } pTAS->iPOL = 0; - while(fgets(buffer,131,fd) != NULL){ + while (fgets(buffer, 131, fd) != NULL) { /* - ignore all errors here - */ - InterpExecute(self->pSics,self->pCon,buffer); + ignore all errors here + */ + InterpExecute(self->pSics, self->pCon, buffer); strtolower(buffer); - if(strstr(buffer,"co") != NULL){ + if (strstr(buffer, "co") != NULL) { pTAS->iPOL++; - self->WriteScanPoints(self,iPoint); + self->WriteScanPoints(self, iPoint); } /* - but allow for interrupts - */ - if(SCGetInterrupt(self->pCon) != eContinue){ + but allow for interrupts + */ + if (SCGetInterrupt(self->pCon) != eContinue) { break; } } @@ -756,121 +706,109 @@ static int RunPolScan(pScanData self, int iPoint) return 1; } + /*--------------------------------------------------------------------------- TASScanCount starts the counter for a TAS scan or runs the polarization analysis. ----------------------------------------------------------------------------*/ +---------------------------------------------------------------------------*/ static int TASUBScanCount(pScanData self, int iPoint) { - pTASdata pTAS = (pTASdata)self->pSpecial; + pTASdata pTAS = (pTASdata) self->pSpecial; float fVal; int status, iRet; Status eOld; pTAS->iIgnore = 0; /* - call the polarisation scan function if necessary - */ - if(pTAS->iPOL >= 0) - { + call the polarisation scan function if necessary + */ + if (pTAS->iPOL >= 0) { return RunPolScan(self, iPoint); } /* - this is easy, just an ordinary scan, start a counter - */ - fVal = GetCounterPreset(self->pCounterData); + this is easy, just an ordinary scan, start a counter + */ + fVal = GetCounterPreset(self->pCounterData); eOld = GetStatus(); - status = DoCount(self->pCounterData,fVal,self->pCon,0); + status = DoCount(self->pCounterData, fVal, self->pCon, 0); iRet = Wait4Success(GetExecutor()); - if(iRet == DEVINT) - { - SCWrite(self->pCon,"Counting aborted due to Interrupt",eLog); - status = 0; - } - else if(iRet == DEVERROR) - { - SCWrite(self->pCon,"Counting finished with Problems",eLog); - status = 0; - } - else - { + if (iRet == DEVINT) { + SCWrite(self->pCon, "Counting aborted due to Interrupt", eLog); + status = 0; + } else if (iRet == DEVERROR) { + SCWrite(self->pCon, "Counting finished with Problems", eLog); + status = 0; + } else { status = 1; } SetStatus(eOld); - + return status; } + /*-------------------------------------------------------------------------- TAS stores the scan data. This is necessary in order to support things like peak or center which require the scan data for operation --------------------------------------------------------------------------*/ - static int TASUBCollect(pScanData self, int iPoint) - { - pVarEntry pVar = NULL; - void *pDings; - int i, iRet, status, iPtr; - float fVal; - CountEntry sCount; - char *pAns = NULL, *pPtr = NULL ; - pTASdata pTAS = (pTASdata)self->pSpecial; - pMotor pMot; - char pError[132]; +static int TASUBCollect(pScanData self, int iPoint) +{ + pVarEntry pVar = NULL; + void *pDings; + int i, iRet, status, iPtr; + float fVal; + CountEntry sCount; + char *pAns = NULL, *pPtr = NULL; + pTASdata pTAS = (pTASdata) self->pSpecial; + pMotor pMot; + char pError[132]; - assert(self); - assert(self->pCon); - - /* loop over all scan variables */ - status = 1; - - pTAS->ub->silent = 0; - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pDings); - pVar = (pVarEntry)pDings; - fVal = readDrivable(ScanVarName(pVar),self->pCon); - if(fVal < -990) - { - snprintf(pError,131,"WARNING: failed to read %s", - ScanVarName(pVar)); - SCWrite(self->pCon,pError,eLog); - } - AppendScanVar(pVar,fVal); - } - - /* store counter data */ - /* monitors */ - for(i = 1; i < 10; i++) - { - sCount.Monitors[i-1] = GetMonitor((pCounter)self->pCounterData,i, + assert(self); + assert(self->pCon); + + /* loop over all scan variables */ + status = 1; + + pTAS->ub->silent = 0; + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pDings); + pVar = (pVarEntry) pDings; + fVal = readDrivable(ScanVarName(pVar), self->pCon); + if (fVal < -990) { + snprintf(pError, 131, "WARNING: failed to read %s", + ScanVarName(pVar)); + SCWrite(self->pCon, pError, eLog); + } + AppendScanVar(pVar, fVal); + } + + /* store counter data */ + /* monitors */ + for (i = 1; i < 10; i++) { + sCount.Monitors[i - 1] = GetMonitor((pCounter) self->pCounterData, i, self->pCon); - } - if( self->iChannel != 0 && self->iChannel != -10 ) - { - sCount.Monitors[self->iChannel - 1] = - GetCounts((pCounter)self->pCounterData, - self->pCon); - } + } + if (self->iChannel != 0 && self->iChannel != -10) { + sCount.Monitors[self->iChannel - 1] = + GetCounts((pCounter) self->pCounterData, self->pCon); + } - /* counts, depending on iChannel */ - if(self->iChannel == 0) - { - sCount.lCount = GetCounts((pCounter)self->pCounterData,self->pCon); - } - else - { - sCount.lCount = GetMonitor((pCounter)self->pCounterData, - self->iChannel, self->pCon); - } + /* counts, depending on iChannel */ + if (self->iChannel == 0) { + sCount.lCount = GetCounts((pCounter) self->pCounterData, self->pCon); + } else { + sCount.lCount = GetMonitor((pCounter) self->pCounterData, + self->iChannel, self->pCon); + } + + /* get time */ + sCount.fTime = GetCountTime((pCounter) self->pCounterData, self->pCon); + /* stow away */ + DynarReplace(self->pCounts, self->iCounts, &sCount, sizeof(CountEntry)); + self->iCounts++; + return 1; +} - /* get time */ - sCount.fTime = GetCountTime((pCounter)self->pCounterData, - self->pCon); - /* stow away */ - DynarReplace(self->pCounts,self->iCounts,&sCount,sizeof(CountEntry)); - self->iCounts++; - return 1; - } /*----------------------------------------------------------------------- prepare2Parse removes all unnecessary delimiters from the parse string. These are: ' = @@ -880,117 +818,109 @@ static void prepare2Parse(char *line) int i, iLang; iLang = strlen(line); - for(i = 0; i < iLang; i++) - { - if(line[i] == ',' || line[i] == '=') - { - line[i] = ' '; + for (i = 0; i < iLang; i++) { + if (line[i] == ',' || line[i] == '=') { + line[i] = ' '; } } } + /*----------------------------------------------------------------*/ extern char *stptok(const char *s, char *t, int len, char *brk); -extern char*trim(char *txt); +extern char *trim(char *txt); /*----------------------------------------------------------------------- During a TAS scan additional output variables can be printed. These are defined in a text variable called ouput. ParseOutput now parses this variable and enters the variables found in there into the TAS data structure so that they can be printed during the scan. ------------------------------------------------------------------------*/ -static void ParseOutput(pTASdata pTAS, SConnection *pCon) +static void ParseOutput(pTASdata pTAS, SConnection * pCon) { - char *pText = NULL, *pPtr, pToken[20], pWarn[256]; - int iPtr; + char *pText = NULL, *pPtr, pToken[20], pWarn[256]; + int iPtr; - /* + /* get a copy of output - */ - pText = (char *)malloc((strlen(GetVarText("output"))+1)*sizeof(char)); - if(!pText) - { - SCWrite(pCon,"WARNING: out of memory while parsing output variable", - eWarning); - return; - } - strcpy(pText,GetVarText("output")); - - /* - wash it */ - prepare2Parse(pText); + pText = + (char *) malloc((strlen(GetVarText("output")) + 1) * sizeof(char)); + if (!pText) { + SCWrite(pCon, "WARNING: out of memory while parsing output variable", + eWarning); + return; + } + strcpy(pText, GetVarText("output")); - /* + /* + wash it + */ + prepare2Parse(pText); + + /* parse */ - pTAS->addCount = 0; - pPtr = pText; - while(pPtr != NULL) - { - pPtr = stptok(pPtr,pToken,20," ,="); - if(strlen(pToken) < 1 || pPtr == NULL) - continue; - - if(FindCommand(pServ->pSics,trim(pToken))) - { - strncpy(pTAS->out[pTAS->addCount],trim(pToken),10); - pTAS->addCount++; - } - else - { - strtolower(pToken); - if(strcmp(pToken,"unknown") != 0) { - sprintf(pWarn,"WARNING: ignored invalid token > %s < in output", - pToken); - SCWrite(pCon,pWarn,eWarning); - } - } - } - free(pText); + pTAS->addCount = 0; + pPtr = pText; + while (pPtr != NULL) { + pPtr = stptok(pPtr, pToken, 20, " ,="); + if (strlen(pToken) < 1 || pPtr == NULL) + continue; + + if (FindCommand(pServ->pSics, trim(pToken))) { + strncpy(pTAS->out[pTAS->addCount], trim(pToken), 10); + pTAS->addCount++; + } else { + strtolower(pToken); + if (strcmp(pToken, "unknown") != 0) { + sprintf(pWarn, "WARNING: ignored invalid token > %s < in output", + pToken); + SCWrite(pCon, pWarn, eWarning); + } + } + } + free(pText); } + /*----------------------------------------------------------------------*/ int TASUBPrepare(pScanData self) { int status; - pTASdata pTAS = (pTASdata)self->pSpecial; + pTASdata pTAS = (pTASdata) self->pSpecial; time_t iDate; struct tm *psTime; char pWork[70]; char pLine[1024]; status = NonCheckPrepare(self); - - ParseOutput(pTAS,self->pCon); - /* - print some status information for the looser + ParseOutput(pTAS, self->pCon); + + /* + print some status information for the looser */ - iDate = time(NULL); - psTime = localtime(&iDate); - memset(pWork,0,69); - strftime(pWork,69,"%d-%b-%Y %H:%M:%S",psTime); - snprintf(pLine,1023,"%8s %3d Points Scan %3d Scanned Variable(s) %s", + iDate = time(NULL); + psTime = localtime(&iDate); + memset(pWork, 0, 69); + strftime(pWork, 69, "%d-%b-%Y %H:%M:%S", psTime); + snprintf(pLine, 1023, "%8s %3d Points Scan %3d Scanned Variable(s) %s", GetVarText("instrument"), - pTAS->pScan->iNP, pTAS->pScan->iScanVar, - pWork); - SCWrite(self->pCon,pLine,eLog); + pTAS->pScan->iNP, pTAS->pScan->iScanVar, pWork); + SCWrite(self->pCon, pLine, eLog); - if(GetCounterMode(pTAS->pScan->pCounterData) == eTimer) - { - sprintf(pLine," %8f Seconds per point", - GetCounterPreset(pTAS->pScan->pCounterData)); - } - else - { - sprintf(pLine," %8f Monitor Counts per point", - GetCounterPreset(pTAS->pScan->pCounterData)); + if (GetCounterMode(pTAS->pScan->pCounterData) == eTimer) { + sprintf(pLine, " %8f Seconds per point", + GetCounterPreset(pTAS->pScan->pCounterData)); + } else { + sprintf(pLine, " %8f Monitor Counts per point", + GetCounterPreset(pTAS->pScan->pCounterData)); - } - SCWrite(self->pCon,pLine,eLog); - SCWrite(self->pCon," ",eLog); - SCWrite(self->pCon," ",eLog); - - /* - snprintf(pLine,1023, + } + SCWrite(self->pCon, pLine, eLog); + SCWrite(self->pCon, " ", eLog); + SCWrite(self->pCon, " ", eLog); + + /* + snprintf(pLine,1023, " %12s %6s HKLE: %5.2f %5.2f %5.2f %8.4f %6.3f %6.3f %6.3f %6.3f", GetVarText("title"), GetVarText("user"), @@ -1002,83 +932,88 @@ int TASUBPrepare(pScanData self) pTAS->tasPar[DQK]->fVal, pTAS->tasPar[DQL]->fVal, pTAS->tasPar[DEN]->fVal); - SCWrite(pCon,pLine,eWarning); + SCWrite(pCon,pLine,eWarning); */ - if(pTAS->ub->tasMode == KICONST) - { - snprintf(pLine,1023," Constant KI Scan: KI= %7.4f Angs-1; EI= %9.4f", - getTasPar(pTAS->ub->current,KI), - getTasPar(pTAS->ub->current,EI)); - } - else - { - snprintf(pLine,1023," Constant KF Scan: KF= %7.4f Angs-1; EF= %9.4f", - getTasPar(pTAS->ub->current,KF), - getTasPar(pTAS->ub->current,EF)); - } - SCWrite(self->pCon,pLine,eLog); + if (pTAS->ub->tasMode == KICONST) { + snprintf(pLine, 1023, + " Constant KI Scan: KI= %7.4f Angs-1; EI= %9.4f", + getTasPar(pTAS->ub->current, KI), getTasPar(pTAS->ub->current, + EI)); + } else { + snprintf(pLine, 1023, + " Constant KF Scan: KF= %7.4f Angs-1; EF= %9.4f", + getTasPar(pTAS->ub->current, KF), getTasPar(pTAS->ub->current, + EF)); + } + SCWrite(self->pCon, pLine, eLog); return status; -} +} + /*---------------------------------------------------------------------*/ -static void TASUBDump(pTASdata self, SicsInterp *pSics, SConnection *pCon, - int argc, char *argv[]){ +static void TASUBDump(pTASdata self, SicsInterp * pSics, + SConnection * pCon, int argc, char *argv[]) +{ float v[9], ub[3][3], cell[6]; int status, i, j; pNXScript nxscript = NULL; char pBueffel[256]; tasReflection r; - if(argc < 4){ - SCWrite(pCon,"ERROR: not enough argument to dump tasub",eError); + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough argument to dump tasub", eError); return; } - nxscript = (pNXScript)FindCommandData(pSics,argv[2],"NXScript"); - if(nxscript == NULL){ - snprintf(pBueffel,255,"ERROR: %s is no NXScript object", - argv[2]); - SCWrite(pCon,pBueffel,eError); + nxscript = (pNXScript) FindCommandData(pSics, argv[2], "NXScript"); + if (nxscript == NULL) { + snprintf(pBueffel, 255, "ERROR: %s is no NXScript object", argv[2]); + SCWrite(pCon, pBueffel, eError); return; } - if(nxscript->fileHandle == NULL){ - SCWrite(pCon,"ERROR: files is closed, cannot write",eError); + if (nxscript->fileHandle == NULL) { + SCWrite(pCon, "ERROR: files is closed, cannot write", eError); return; } - + /* - write cell - */ - snprintf(pBueffel,255,"%s_cell",argv[3]); + write cell + */ + snprintf(pBueffel, 255, "%s_cell", argv[3]); cell[0] = self->ub->cell.a; cell[1] = self->ub->cell.b; cell[2] = self->ub->cell.c; cell[3] = self->ub->cell.alpha; cell[4] = self->ub->cell.beta; cell[5] = self->ub->cell.gamma; - status = NXDputalias(nxscript->fileHandle,nxscript->dictHandle,pBueffel,cell); - if(status != NX_OK){ - snprintf(pBueffel,255,"ERROR: failed to write cell to %s_cell",argv[3]); - SCWrite(pCon,pBueffel,eWarning); + status = + NXDputalias(nxscript->fileHandle, nxscript->dictHandle, pBueffel, + cell); + if (status != NX_OK) { + snprintf(pBueffel, 255, "ERROR: failed to write cell to %s_cell", + argv[3]); + SCWrite(pCon, pBueffel, eWarning); } /* - write planenormal - */ - for(i = 0; i < 3; i++){ + write planenormal + */ + for (i = 0; i < 3; i++) { v[i] = self->ub->machine.planeNormal[i][0]; } - snprintf(pBueffel,255,"%s_norm",argv[3]); - status = NXDputalias(nxscript->fileHandle,nxscript->dictHandle,pBueffel,v); - if(status != NX_OK){ - snprintf(pBueffel,255,"ERROR: failed to write plane_normal to %s_norm",argv[3]); - SCWrite(pCon,pBueffel,eWarning); + snprintf(pBueffel, 255, "%s_norm", argv[3]); + status = + NXDputalias(nxscript->fileHandle, nxscript->dictHandle, pBueffel, v); + if (status != NX_OK) { + snprintf(pBueffel, 255, + "ERROR: failed to write plane_normal to %s_norm", argv[3]); + SCWrite(pCon, pBueffel, eWarning); } /* - write orienting reflections - */ - snprintf(pBueffel,255,"%s_vec1",argv[3]); + write orienting reflections + */ + snprintf(pBueffel, 255, "%s_vec1", argv[3]); r = self->ub->r1; v[0] = r.qe.qh; v[1] = r.qe.qk; @@ -1089,12 +1024,14 @@ static void TASUBDump(pTASdata self, SicsInterp *pSics, SConnection *pCon, v[6] = r.angles.sgu; v[7] = KtoEnergy(r.qe.ki); v[8] = KtoEnergy(r.qe.kf); - status = NXDputalias(nxscript->fileHandle,nxscript->dictHandle,pBueffel,v); - if(status != NX_OK){ - snprintf(pBueffel,255,"ERROR: failed to write plane vector 1 to %s_vec1",argv[3]); - SCWrite(pCon,pBueffel,eWarning); + status = + NXDputalias(nxscript->fileHandle, nxscript->dictHandle, pBueffel, v); + if (status != NX_OK) { + snprintf(pBueffel, 255, + "ERROR: failed to write plane vector 1 to %s_vec1", argv[3]); + SCWrite(pCon, pBueffel, eWarning); } - snprintf(pBueffel,255,"%s_vec2",argv[3]); + snprintf(pBueffel, 255, "%s_vec2", argv[3]); r = self->ub->r2; v[0] = r.qe.qh; v[1] = r.qe.qk; @@ -1105,133 +1042,145 @@ static void TASUBDump(pTASdata self, SicsInterp *pSics, SConnection *pCon, v[6] = r.angles.sgu; v[7] = KtoEnergy(r.qe.ki); v[8] = KtoEnergy(r.qe.kf); - status = NXDputalias(nxscript->fileHandle,nxscript->dictHandle,pBueffel,v); - if(status != NX_OK){ - snprintf(pBueffel,255,"ERROR: failed to write plane vector 2 to %s_vec2",argv[3]); - SCWrite(pCon,pBueffel,eWarning); + status = + NXDputalias(nxscript->fileHandle, nxscript->dictHandle, pBueffel, v); + if (status != NX_OK) { + snprintf(pBueffel, 255, + "ERROR: failed to write plane vector 2 to %s_vec2", argv[3]); + SCWrite(pCon, pBueffel, eWarning); } /* - write UB - */ - for(i = 0; i < 3; i++){ - for(j = 0; j < 3; j++){ - ub[i][j] = self->ub->machine.UB[i][j]; + write UB + */ + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + ub[i][j] = self->ub->machine.UB[i][j]; } } - snprintf(pBueffel,255,"%s_ub",argv[3]); - status = NXDputalias(nxscript->fileHandle,nxscript->dictHandle,pBueffel,ub); - if(status != NX_OK){ - snprintf(pBueffel,255,"ERROR: failed to write UB to %s_ub",argv[3]); - SCWrite(pCon,pBueffel,eWarning); + snprintf(pBueffel, 255, "%s_ub", argv[3]); + status = + NXDputalias(nxscript->fileHandle, nxscript->dictHandle, pBueffel, + ub); + if (status != NX_OK) { + snprintf(pBueffel, 255, "ERROR: failed to write UB to %s_ub", argv[3]); + SCWrite(pCon, pBueffel, eWarning); } } + /*----------------------------------------------------------------------*/ -int TASUBScan(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int TASUBScan(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pTASdata self = NULL; char pBueffel[256]; int np; - self = (pTASdata)pData; + self = (pTASdata) pData; assert(self); self->pScan->pSpecial = self; - if(argc < 2) { - SCWrite(pCon,"ERROR: not enough arguments to tasscan",eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to tasscan", eError); return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"pol") == 0){ - if(argc > 2){ - if(!SCMatchRights(pCon,usUser)){ - return 0; + if (strcmp(argv[1], "pol") == 0) { + if (argc > 2) { + if (!SCMatchRights(pCon, usUser)) { + return 0; } self->iPOL = atoi(argv[2]); SCSendOK(pCon); return 1; } else { - snprintf(pBueffel,255,"%s.pol = %d",argv[0],self->iPOL); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "%s.pol = %d", argv[0], self->iPOL); + SCWrite(pCon, pBueffel, eValue); return 1; - } - }else if(strcmp(argv[1],"fast") == 0){ - if(argc > 2){ - if(!SCMatchRights(pCon,usUser)){ - return 0; + } + } else if (strcmp(argv[1], "fast") == 0) { + if (argc > 2) { + if (!SCMatchRights(pCon, usUser)) { + return 0; } self->iFast = atoi(argv[2]); SCSendOK(pCon); return 1; } else { - snprintf(pBueffel,255,"%s.fast = %d",argv[0],self->iFast); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "%s.fast = %d", argv[0], self->iFast); + SCWrite(pCon, pBueffel, eValue); return 1; - } - } else if(strcmp(argv[1],"prepare") == 0){ + } + } else if (strcmp(argv[1], "prepare") == 0) { return TASUBPrepare(self->pScan); - } else if(strcmp(argv[1],"nxdump") == 0){ - TASUBDump(self,pSics,pCon,argc,argv); + } else if (strcmp(argv[1], "nxdump") == 0) { + TASUBDump(self, pSics, pCon, argc, argv); return 1; - } else if(strcmp(argv[1],"drive") == 0){ - if(argc < 5) { - SCWrite(pCon,"ERROR: insufficient number of arguments to tasscan drive", - eError); + } else if (strcmp(argv[1], "drive") == 0) { + if (argc < 5) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to tasscan drive", + eError); return 0; } np = atoi(argv[4]); - return TASUBScanDrive(self->pScan,np); - } else if(strcmp(argv[1],"header") == 0){ + return TASUBScanDrive(self->pScan, np); + } else if (strcmp(argv[1], "header") == 0) { return TASUBHeader(self->pScan); - } else if(strcmp(argv[1],"count") == 0){ - if(argc < 7) { - SCWrite(pCon,"ERROR: insufficient number of arguments to tasscan count", - eError); - return 0; - } - np = atoi(argv[4]); - return TASUBScanCount(self->pScan,np); - } else if(strcmp(argv[1],"collect") == 0){ - if(argc < 5) { + } else if (strcmp(argv[1], "count") == 0) { + if (argc < 7) { SCWrite(pCon, - "ERROR: insufficient number of arguments to tasscan collect", - eError); + "ERROR: insufficient number of arguments to tasscan count", + eError); return 0; } np = atoi(argv[4]); - return TASUBCollect(self->pScan,np); - } else if(strcmp(argv[1],"writepoint") == 0){ - if(argc < 5) { + return TASUBScanCount(self->pScan, np); + } else if (strcmp(argv[1], "collect") == 0) { + if (argc < 5) { SCWrite(pCon, - "ERROR: insufficient number of arguments to tasscan writepoint", - eError); + "ERROR: insufficient number of arguments to tasscan collect", + eError); return 0; } np = atoi(argv[4]); - return TASUBScanPoint(self->pScan,np); + return TASUBCollect(self->pScan, np); + } else if (strcmp(argv[1], "writepoint") == 0) { + if (argc < 5) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to tasscan writepoint", + eError); + return 0; + } + np = atoi(argv[4]); + return TASUBScanPoint(self->pScan, np); } else { - SCWrite(pCon,"ERROR: subcommand to tasscan not understood",eError); + SCWrite(pCon, "ERROR: subcommand to tasscan not understood", eError); return 0; } return 1; } + /*---------------------------------------------------------------------*/ -static void KillTAS(void *pData){ - pTASdata self = (pTASdata)pData; - if(self == NULL){ +static void KillTAS(void *pData) +{ + pTASdata self = (pTASdata) pData; + if (self == NULL) { return; } - if(self->pDes != NULL){ + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); } free(self); } + /*----------------------------------------------------------------------*/ -int TASUBScanFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int TASUBScanFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pTASdata pNew = NULL; char pBueffel[512]; int i; @@ -1247,50 +1196,53 @@ int TASUBScanFactory(SConnection *pCon, SicsInterp *pSics, void *pData, }; - if(argc < 3){ - SCWrite(pCon,"ERROR: not enough arguments to TASUBScanFactory",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: not enough arguments to TASUBScanFactory", + eError); return 0; } - pNew = (pTASdata)malloc(sizeof(TASdata)); - if(!pNew){ - SCWrite(pCon,"ERROR: out of memory creating tasscan object",eError); + pNew = (pTASdata) malloc(sizeof(TASdata)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory creating tasscan object", eError); return 0; } - memset(pNew,0,sizeof(TASdata)); + memset(pNew, 0, sizeof(TASdata)); pNew->pDes = CreateDescriptor("TAS Scan Stuff"); - if(!pNew->pDes){ - SCWrite(pCon,"ERROR: out of memory creating tasscan object",eError); + if (!pNew->pDes) { + SCWrite(pCon, "ERROR: out of memory creating tasscan object", eError); free(pNew); return 0; } - pNew->pScan = (pScanData)FindCommandData(pSics,argv[1],"ScanObject"); - if(!pNew->pScan){ - snprintf(pBueffel,511,"ERROR: cannot locate scan object %s", argv[1]); + pNew->pScan = (pScanData) FindCommandData(pSics, argv[1], "ScanObject"); + if (!pNew->pScan) { + snprintf(pBueffel, 511, "ERROR: cannot locate scan object %s", + argv[1]); free(pNew); - SCWrite(pCon,pBueffel,eError); + SCWrite(pCon, pBueffel, eError); return 0; } - pNew->counter = (pCounter)pNew->pScan->pCounterData; + pNew->counter = (pCounter) pNew->pScan->pCounterData; - pNew->ub = (ptasUB)FindCommandData(pSics,argv[2],"TAS-UB"); - if(!pNew->ub){ - snprintf(pBueffel,511,"ERROR: cannot locate TAS-UB object %s", argv[2]); + pNew->ub = (ptasUB) FindCommandData(pSics, argv[2], "TAS-UB"); + if (!pNew->ub) { + snprintf(pBueffel, 511, "ERROR: cannot locate TAS-UB object %s", + argv[2]); free(pNew); - SCWrite(pCon,pBueffel,eError); + SCWrite(pCon, pBueffel, eError); return 0; } - + i = 0; - while(pVar[i] != NULL){ - if(FindCommandData(pSics,pVar[i],"SicsVariable") == NULL){ - snprintf(pBueffel,511,"ERROR: variable %s missing", pVar[i]); - SCWrite(pCon,pBueffel,eError); + while (pVar[i] != NULL) { + if (FindCommandData(pSics, pVar[i], "SicsVariable") == NULL) { + snprintf(pBueffel, 511, "ERROR: variable %s missing", pVar[i]); + SCWrite(pCon, pBueffel, eError); free(pNew); return 0; } i++; } - return AddCommand(pSics,"tasscan",TASUBScan,KillTAS,pNew); + return AddCommand(pSics, "tasscan", TASUBScan, KillTAS, pNew); } diff --git a/tasscanub.h b/tasscanub.h index 571fc74e..faf0bb89 100644 --- a/tasscanub.h +++ b/tasscanub.h @@ -4,7 +4,7 @@ Mark Koennecke, May 2005, using code from an earlier TASAMAD emulation core. -------------------------------------------------------------------------*/ +------------------------------------------------------------------------*/ #ifndef SICUBSTAS #define SICSUBTAS #include @@ -12,25 +12,25 @@ /* --------------------- data structure -------------------------------*/ #define MAXADD 20 typedef struct { - pObjectDescriptor pDes; - pCounter counter; - pScanData pScan; - ptasUB ub; - int iPOL; - int iIgnore; /* in order to ignore writing scan points again - in polarisation mode; - */ - char out[MAXADD][10]; - int addCount; - int iFileNO; - int iFast; - char scanVar[80]; - }TASdata, *pTASdata; + pObjectDescriptor pDes; + pCounter counter; + pScanData pScan; + ptasUB ub; + int iPOL; + int iIgnore; /* in order to ignore writing scan points again + in polarisation mode; + */ + char out[MAXADD][10]; + int addCount; + int iFileNO; + int iFast; + char scanVar[80]; +} TASdata, *pTASdata; /*---------------------- interface ----------------------------------*/ - int TASUBScanFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int TASUBScan(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int TASUBScanFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int TASUBScan(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/tasub.c b/tasub.c index 7822128d..b515ee50 100644 --- a/tasub.c +++ b/tasub.c @@ -27,82 +27,92 @@ #define ACH 11 /*----------------- data structure management code -------------------*/ static void saveCrystal(char *objName, char *name, pmaCrystal crystal, - FILE *fd){ - fprintf(fd,"%s %s dd %f\n",objName, name, crystal->dd); - fprintf(fd,"%s %s hb1 %f\n",objName, name, crystal->HB1); - fprintf(fd,"%s %s hb2 %f\n",objName, name, crystal->HB2); - fprintf(fd,"%s %s vb1 %f\n",objName, name, crystal->VB1); - fprintf(fd,"%s %s vb2 %f\n",objName, name, crystal->VB2); - fprintf(fd,"%s %s ss %d\n",objName, name, crystal->ss); + FILE * fd) +{ + fprintf(fd, "%s %s dd %f\n", objName, name, crystal->dd); + fprintf(fd, "%s %s hb1 %f\n", objName, name, crystal->HB1); + fprintf(fd, "%s %s hb2 %f\n", objName, name, crystal->HB2); + fprintf(fd, "%s %s vb1 %f\n", objName, name, crystal->VB1); + fprintf(fd, "%s %s vb2 %f\n", objName, name, crystal->VB2); + fprintf(fd, "%s %s ss %d\n", objName, name, crystal->ss); } + /*------------------------------------------------------------------*/ -static void saveReflections(ptasUB self, char *name, FILE *fd){ +static void saveReflections(ptasUB self, char *name, FILE * fd) +{ tasReflection r; int status; status = LLDnodePtr2First(self->reflectionList); - fprintf(fd,"%s clear\n",name); - while(status == 1){ - LLDnodeDataTo(self->reflectionList,&r); - fprintf(fd,"%s addref %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n", - name, r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, r.angles.sample_two_theta, - r.angles.sgu, r.angles.sgl, - KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); + fprintf(fd, "%s clear\n", name); + while (status == 1) { + LLDnodeDataTo(self->reflectionList, &r); + fprintf(fd, + "%s addref %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n", + name, r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, + r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, + KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); status = LLDnodePtr2Next(self->reflectionList); } } + /*-------------------------------------------------------------------*/ -static int tasUBSave(void *pData, char *name, FILE *fd){ - ptasUB self = (ptasUB)pData; +static int tasUBSave(void *pData, char *name, FILE * fd) +{ + ptasUB self = (ptasUB) pData; tasReflection r; - if(self == NULL){ + if (self == NULL) { return 0; } - fprintf(fd,"#---- tasUB module %s\n", name); - saveCrystal(name,"mono",&self->machine.monochromator,fd); - saveCrystal(name,"ana",&self->machine.analyzer,fd); - fprintf(fd,"%s cell %f %f %f %f %f %f\n", name, self->cell.a, - self->cell.b, self->cell.c, self->cell.alpha, - self->cell.beta, self->cell.gamma); - saveReflections(self,name,fd); - fprintf(fd,"%s outofplane %d\n", name, self->outOfPlaneAllowed); - if(self->tasMode == KICONST){ - fprintf(fd,"%s const ki\n",name); - }else if(self->tasMode == ELASTIC){ - fprintf(fd,"%s const elastic\n",name); + fprintf(fd, "#---- tasUB module %s\n", name); + saveCrystal(name, "mono", &self->machine.monochromator, fd); + saveCrystal(name, "ana", &self->machine.analyzer, fd); + fprintf(fd, "%s cell %f %f %f %f %f %f\n", name, self->cell.a, + self->cell.b, self->cell.c, self->cell.alpha, + self->cell.beta, self->cell.gamma); + saveReflections(self, name, fd); + fprintf(fd, "%s outofplane %d\n", name, self->outOfPlaneAllowed); + if (self->tasMode == KICONST) { + fprintf(fd, "%s const ki\n", name); + } else if (self->tasMode == ELASTIC) { + fprintf(fd, "%s const elastic\n", name); } else { - fprintf(fd,"%s const kf\n",name); + fprintf(fd, "%s const kf\n", name); } - fprintf(fd,"%s ss %d\n", name,self->machine.ss_sample); - fprintf(fd," %s setub %f %f %f %f %f %f %f %f %f\n", - name, - self->machine.UB[0][0], self->machine.UB[0][1], self->machine.UB[0][2], - self->machine.UB[1][0], self->machine.UB[1][1], self->machine.UB[1][2], - self->machine.UB[2][0], self->machine.UB[2][1], self->machine.UB[2][2]); - fprintf(fd," %s setnormal %f %f %f\n", - name, - self->machine.planeNormal[0][0], self->machine.planeNormal[1][0], - self->machine.planeNormal[2][0]); - fprintf(fd,"%s settarget %f %f %f %f %f %f\n", - name, - self->target.qh, self->target.qk, self->target.ql, self->target.qm, - self->target.ki, self->target.kf); + fprintf(fd, "%s ss %d\n", name, self->machine.ss_sample); + fprintf(fd, " %s setub %f %f %f %f %f %f %f %f %f\n", + name, + self->machine.UB[0][0], self->machine.UB[0][1], + self->machine.UB[0][2], self->machine.UB[1][0], + self->machine.UB[1][1], self->machine.UB[1][2], + self->machine.UB[2][0], self->machine.UB[2][1], + self->machine.UB[2][2]); + fprintf(fd, " %s setnormal %f %f %f\n", name, + self->machine.planeNormal[0][0], self->machine.planeNormal[1][0], + self->machine.planeNormal[2][0]); + fprintf(fd, "%s settarget %f %f %f %f %f %f\n", name, self->target.qh, + self->target.qk, self->target.ql, self->target.qm, + self->target.ki, self->target.kf); r = self->r1; - fprintf(fd,"%s r1 %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n", - name, r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, r.angles.sample_two_theta, - r.angles.sgu, r.angles.sgl, - KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); + fprintf(fd, + "%s r1 %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n", + name, r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, + r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, + KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); r = self->r2; - fprintf(fd,"%s r2 %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n", - name, r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, r.angles.sample_two_theta, - r.angles.sgu, r.angles.sgl, - KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); - fprintf(fd,"%s update\n", name); + fprintf(fd, + "%s r2 %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n", + name, r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, + r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, + KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); + fprintf(fd, "%s update\n", name); return 1; } + /*------------------------------------------------------------------*/ -static void defaultMonochromator(pmaCrystal mono){ +static void defaultMonochromator(pmaCrystal mono) +{ mono->dd = 3.35; mono->ss = 1; mono->HB1 = 1.; @@ -110,26 +120,28 @@ static void defaultMonochromator(pmaCrystal mono){ mono->VB1 = 1.; mono->VB2 = 1.; } + /*--------------------------------------------------------------------*/ -static ptasUB MakeTasUB(){ +static ptasUB MakeTasUB() +{ ptasUB pNew = NULL; - pNew = (ptasUB)malloc(sizeof(tasUB)); - if(pNew == NULL){ + pNew = (ptasUB) malloc(sizeof(tasUB)); + if (pNew == NULL) { return NULL; } - memset(pNew,0,sizeof(tasUB)); - + memset(pNew, 0, sizeof(tasUB)); + pNew->pDes = CreateDescriptor("TAS-UB"); - pNew->machine.UB = mat_creat(3,3,UNIT_MATRIX); - pNew->machine.planeNormal = mat_creat(3,1,ZERO_MATRIX); + pNew->machine.UB = mat_creat(3, 3, UNIT_MATRIX); + pNew->machine.planeNormal = mat_creat(3, 1, ZERO_MATRIX); pNew->reflectionList = LLDcreate(sizeof(tasReflection)); - if(!pNew->pDes || !pNew->machine.UB || pNew->reflectionList < 0 || - pNew->machine.planeNormal == NULL){ + if (!pNew->pDes || !pNew->machine.UB || pNew->reflectionList < 0 || + pNew->machine.planeNormal == NULL) { free(pNew); return NULL; } - + pNew->pDes->SaveStatus = tasUBSave; pNew->machine.ss_sample = 1; defaultMonochromator(&pNew->machine.monochromator); @@ -143,228 +155,240 @@ static ptasUB MakeTasUB(){ return pNew; } + /*-------------------------------------------------------------------*/ -static void KillTasUB(void *pData){ - ptasUB self = (ptasUB)pData; - - if(self == NULL){ +static void KillTasUB(void *pData) +{ + ptasUB self = (ptasUB) pData; + + if (self == NULL) { return; } LLDdelete(self->reflectionList); - if(self->pDes != NULL){ + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); } - if(self->machine.UB != NULL){ + if (self->machine.UB != NULL) { mat_free(self->machine.UB); } - if(self->machine.planeNormal != NULL){ + if (self->machine.planeNormal != NULL) { mat_free(self->machine.planeNormal); } free(self); } + /*===================== computation section =========================*/ -static int readTASAngles(ptasUB self, SConnection *pCon, - ptasAngles ang){ +static int readTASAngles(ptasUB self, SConnection * pCon, ptasAngles ang) +{ int status; float val; /* - Monochromator - */ - status = MotorGetSoftPosition(self->motors[A2],pCon,&val); - if(status == 0){ + Monochromator + */ + status = MotorGetSoftPosition(self->motors[A2], pCon, &val); + if (status == 0) { return status; } ang->monochromator_two_theta = val; /* - Analyzer - */ - if(self->tasMode != ELASTIC){ - status = MotorGetSoftPosition(self->motors[A6],pCon,&val); - if(status == 0){ - return status; - } - ang->analyzer_two_theta = val; + Analyzer + */ + if (self->tasMode != ELASTIC) { + status = MotorGetSoftPosition(self->motors[A6], pCon, &val); + if (status == 0) { + return status; + } + ang->analyzer_two_theta = val; } else { - ang->analyzer_two_theta = ang->monochromator_two_theta; + ang->analyzer_two_theta = ang->monochromator_two_theta; } /* - crystal - */ - status = MotorGetSoftPosition(self->motors[A3],pCon,&val); - if(status == 0){ + crystal + */ + status = MotorGetSoftPosition(self->motors[A3], pCon, &val); + if (status == 0) { return status; } ang->a3 = val; - status = MotorGetSoftPosition(self->motors[A4],pCon,&val); - if(status == 0){ + status = MotorGetSoftPosition(self->motors[A4], pCon, &val); + if (status == 0) { return status; } ang->sample_two_theta = val; - status = MotorGetSoftPosition(self->motors[SGU],pCon,&val); - if(status == 0){ + status = MotorGetSoftPosition(self->motors[SGU], pCon, &val); + if (status == 0) { return status; } ang->sgu = val; - status = MotorGetSoftPosition(self->motors[SGL],pCon,&val); - if(status == 0){ + status = MotorGetSoftPosition(self->motors[SGL], pCon, &val); + if (status == 0) { return status; } ang->sgl = val; return 1; } + /*==================== interpreter interface section =================*/ -static int testMotor(ptasUB pNew, SConnection *pCon, char *name, int idx){ +static int testMotor(ptasUB pNew, SConnection * pCon, char *name, int idx) +{ char pBueffel[132]; - if(pNew->motors[idx] == NULL){ - snprintf(pBueffel,131,"ERROR: required motor %s NOT found",name); - SCWrite(pCon,pBueffel,eError); + if (pNew->motors[idx] == NULL) { + snprintf(pBueffel, 131, "ERROR: required motor %s NOT found", name); + SCWrite(pCon, pBueffel, eError); return 0; } else { return 1; } } + /*-------------------------------------------------------------------*/ -static void updateTargets(ptasUB pNew, SConnection *pCon){ - tasAngles ang; - - readTASAngles(pNew,pCon,&ang); - calcTasQEPosition(&pNew->machine, ang, &pNew->target); +static void updateTargets(ptasUB pNew, SConnection * pCon) +{ + tasAngles ang; + + readTASAngles(pNew, pCon, &ang); + calcTasQEPosition(&pNew->machine, ang, &pNew->target); } -/*--------------------------------------------------------------------*/ -int TasUBFactory(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]){ + +/*--------------------------------------------------------------------*/ +int TasUBFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ ptasUB pNew = NULL; int status = 0, i; char pBueffel[132]; - char names[][3] = {"ei","ki", - "qh","qk","ql", - "ef","kf", - "en"}; + char names[][3] = { "ei", "ki", + "qh", "qk", "ql", + "ef", "kf", + "en" + }; - if(argc < 2) { - SCWrite(pCon,"ERROR: need name to install tasUB",eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: need name to install tasUB", eError); return 0; } - if(argc > 2 && argc < 14){ - SCWrite(pCon,"ERROR: not enough motor names specified for MakeTasUB",eError); + if (argc > 2 && argc < 14) { + SCWrite(pCon, "ERROR: not enough motor names specified for MakeTasUB", + eError); return 0; } pNew = MakeTasUB(); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating tasUB",eError); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating tasUB", eError); return 0; } /* - assign motors - */ - if(argc < 14){ + assign motors + */ + if (argc < 14) { /* * default names and assignement */ - pNew->motors[0] = FindMotor(pSics,"a1"); - pNew->motors[1] = FindMotor(pSics,"a2"); - pNew->motors[2] = FindMotor(pSics,"mcv"); - pNew->motors[3] = FindMotor(pSics,"mch"); - pNew->motors[4] = FindMotor(pSics,"a3"); - pNew->motors[5] = FindMotor(pSics,"a4"); - pNew->motors[6] = FindMotor(pSics,"sgu"); - pNew->motors[7] = FindMotor(pSics,"sgl"); - pNew->motors[8] = FindMotor(pSics,"a5"); - pNew->motors[9] = FindMotor(pSics,"a6"); - pNew->motors[10] = FindMotor(pSics,"acv"); - pNew->motors[11] = FindMotor(pSics,"ach"); + pNew->motors[0] = FindMotor(pSics, "a1"); + pNew->motors[1] = FindMotor(pSics, "a2"); + pNew->motors[2] = FindMotor(pSics, "mcv"); + pNew->motors[3] = FindMotor(pSics, "mch"); + pNew->motors[4] = FindMotor(pSics, "a3"); + pNew->motors[5] = FindMotor(pSics, "a4"); + pNew->motors[6] = FindMotor(pSics, "sgu"); + pNew->motors[7] = FindMotor(pSics, "sgl"); + pNew->motors[8] = FindMotor(pSics, "a5"); + pNew->motors[9] = FindMotor(pSics, "a6"); + pNew->motors[10] = FindMotor(pSics, "acv"); + pNew->motors[11] = FindMotor(pSics, "ach"); } else { /* * user defined names */ - pNew->motors[0] = FindMotor(pSics,argv[2]); - pNew->motors[1] = FindMotor(pSics,argv[3]); - pNew->motors[2] = FindMotor(pSics,argv[4]); - pNew->motors[3] = FindMotor(pSics,argv[5]); - pNew->motors[4] = FindMotor(pSics,argv[6]); - pNew->motors[5] = FindMotor(pSics,argv[7]); - pNew->motors[6] = FindMotor(pSics,argv[8]); - pNew->motors[7] = FindMotor(pSics,argv[9]); - pNew->motors[8] = FindMotor(pSics,argv[10]); - pNew->motors[9] = FindMotor(pSics,argv[11]); - pNew->motors[10] = FindMotor(pSics,argv[12]); - pNew->motors[11] = FindMotor(pSics,argv[13]); + pNew->motors[0] = FindMotor(pSics, argv[2]); + pNew->motors[1] = FindMotor(pSics, argv[3]); + pNew->motors[2] = FindMotor(pSics, argv[4]); + pNew->motors[3] = FindMotor(pSics, argv[5]); + pNew->motors[4] = FindMotor(pSics, argv[6]); + pNew->motors[5] = FindMotor(pSics, argv[7]); + pNew->motors[6] = FindMotor(pSics, argv[8]); + pNew->motors[7] = FindMotor(pSics, argv[9]); + pNew->motors[8] = FindMotor(pSics, argv[10]); + pNew->motors[9] = FindMotor(pSics, argv[11]); + pNew->motors[10] = FindMotor(pSics, argv[12]); + pNew->motors[11] = FindMotor(pSics, argv[13]); } /* - curvature motors may be missing, anything else is a serious problem - */ - status += testMotor(pNew, pCon,"a1",A1); - status += testMotor(pNew, pCon,"a2",A2); - status += testMotor(pNew, pCon,"a3",A3); - status += testMotor(pNew, pCon,"a4",A4); - status += testMotor(pNew, pCon,"sgu",SGU); - status += testMotor(pNew, pCon,"sgl",SGL); - status += testMotor(pNew, pCon,"a5",A5); - status += testMotor(pNew, pCon,"a6",A6); - if(status != 8){ - SCWrite(pCon,"ERROR: a required motor is mssing, tasub NOT installed",eError); + curvature motors may be missing, anything else is a serious problem + */ + status += testMotor(pNew, pCon, "a1", A1); + status += testMotor(pNew, pCon, "a2", A2); + status += testMotor(pNew, pCon, "a3", A3); + status += testMotor(pNew, pCon, "a4", A4); + status += testMotor(pNew, pCon, "sgu", SGU); + status += testMotor(pNew, pCon, "sgl", SGL); + status += testMotor(pNew, pCon, "a5", A5); + status += testMotor(pNew, pCon, "a6", A6); + if (status != 8) { + SCWrite(pCon, "ERROR: a required motor is mssing, tasub NOT installed", + eError); return 0; } - - status = AddCommand(pSics,argv[1], - TasUBWrapper, - KillTasUB, - pNew); - if(status != 1){ - SCWrite(pCon,"ERROR: duplicate tasUB command not created",eError); + + status = AddCommand(pSics, argv[1], TasUBWrapper, KillTasUB, pNew); + if (status != 1) { + SCWrite(pCon, "ERROR: duplicate tasUB command not created", eError); return 0; } /* - install virtual motors - */ - for(i = 0; i < 8; i++){ - status = InstallTasMotor(pSics,pNew,i+1,names[i]); - if(status != 1){ - snprintf(pBueffel,131,"ERROR: failed to create TAS motor %s", names[i]); - SCWrite(pCon,pBueffel,eError); + install virtual motors + */ + for (i = 0; i < 8; i++) { + status = InstallTasMotor(pSics, pNew, i + 1, names[i]); + if (status != 1) { + snprintf(pBueffel, 131, "ERROR: failed to create TAS motor %s", + names[i]); + SCWrite(pCon, pBueffel, eError); } } - status = InstallTasQMMotor(pSics,pNew); - if(status != 1){ - snprintf(pBueffel,131,"ERROR: failed to create TAS motor qm"); - SCWrite(pCon,pBueffel,eError); + status = InstallTasQMMotor(pSics, pNew); + if (status != 1) { + snprintf(pBueffel, 131, "ERROR: failed to create TAS motor qm"); + SCWrite(pCon, pBueffel, eError); } return 1; } + /*-----------------------------------------------------------------*/ -static int setCrystalParameters(pmaCrystal crystal, SConnection *pCon, - int argc, char *argv[]){ +static int setCrystalParameters(pmaCrystal crystal, SConnection * pCon, + int argc, char *argv[]) +{ int status; double d; char pBueffel[132]; - status = Tcl_GetDouble(InterpGetTcl(pServ->pSics),argv[3],&d); - if(status != TCL_OK){ - snprintf(pBueffel,131,"ERROR: failed to convert %s to number", - argv[3]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pServ->pSics), argv[3], &d); + if (status != TCL_OK) { + snprintf(pBueffel, 131, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 1; } - if(!SCMatchRights(pCon,usMugger)){ + if (!SCMatchRights(pCon, usMugger)) { return 0; } strtolower(argv[2]); - if(strcmp(argv[2],"dd") == 0){ + if (strcmp(argv[2], "dd") == 0) { crystal->dd = d; SCSendOK(pCon); SCparChange(pCon); return 1; - }else if(strcmp(argv[2],"ss") == 0){ - if(d > .0){ + } else if (strcmp(argv[2], "ss") == 0) { + if (d > .0) { crystal->ss = 1; } else { crystal->ss = -1; @@ -372,167 +396,193 @@ static int setCrystalParameters(pmaCrystal crystal, SConnection *pCon, SCSendOK(pCon); SCparChange(pCon); return 1; - }else if(strcmp(argv[2],"hb1") == 0){ + } else if (strcmp(argv[2], "hb1") == 0) { crystal->HB1 = d; SCSendOK(pCon); SCparChange(pCon); return 1; - }else if(strcmp(argv[2],"hb2") == 0){ + } else if (strcmp(argv[2], "hb2") == 0) { crystal->HB2 = d; SCSendOK(pCon); SCparChange(pCon); return 1; - }else if(strcmp(argv[2],"vb1") == 0){ + } else if (strcmp(argv[2], "vb1") == 0) { crystal->VB1 = d; SCSendOK(pCon); SCparChange(pCon); return 1; - }else if(strcmp(argv[2],"vb2") == 0){ + } else if (strcmp(argv[2], "vb2") == 0) { crystal->VB2 = d; SCSendOK(pCon); SCparChange(pCon); return 1; } else { - snprintf(pBueffel,131,"ERROR: crystal parameter %s not known", - argv[2]); - SCWrite(pCon,pBueffel,eError); + snprintf(pBueffel, 131, "ERROR: crystal parameter %s not known", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } } + /*-----------------------------------------------------------------*/ -static int getCrystalParameters(pmaCrystal crystal, SConnection *pCon, - int argc, char *argv[]){ +static int getCrystalParameters(pmaCrystal crystal, SConnection * pCon, + int argc, char *argv[]) +{ char pBueffel[132]; strtolower(argv[2]); - if(strcmp(argv[2],"dd") == 0){ - snprintf(pBueffel,131,"%s.%s.dd = %f",argv[0],argv[1],crystal->dd); - SCWrite(pCon,pBueffel,eValue); + if (strcmp(argv[2], "dd") == 0) { + snprintf(pBueffel, 131, "%s.%s.dd = %f", argv[0], argv[1], + crystal->dd); + SCWrite(pCon, pBueffel, eValue); return 1; - }else if(strcmp(argv[2],"hb1") == 0){ - snprintf(pBueffel,131,"%s.%s.hb1 = %f",argv[0],argv[1],crystal->HB1); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(argv[2], "hb1") == 0) { + snprintf(pBueffel, 131, "%s.%s.hb1 = %f", argv[0], argv[1], + crystal->HB1); + SCWrite(pCon, pBueffel, eValue); return 1; - }else if(strcmp(argv[2],"hb2") == 0){ - snprintf(pBueffel,131,"%s.%s.hb2 = %f",argv[0],argv[1],crystal->HB2); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(argv[2], "hb2") == 0) { + snprintf(pBueffel, 131, "%s.%s.hb2 = %f", argv[0], argv[1], + crystal->HB2); + SCWrite(pCon, pBueffel, eValue); return 1; - }else if(strcmp(argv[2],"vb1") == 0){ - snprintf(pBueffel,131,"%s.%s.vb1 = %f",argv[0],argv[1],crystal->VB1); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(argv[2], "vb1") == 0) { + snprintf(pBueffel, 131, "%s.%s.vb1 = %f", argv[0], argv[1], + crystal->VB1); + SCWrite(pCon, pBueffel, eValue); return 1; - }else if(strcmp(argv[2],"vb2") == 0){ - snprintf(pBueffel,131,"%s.%s.vb2 = %f",argv[0],argv[1],crystal->VB2); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(argv[2], "vb2") == 0) { + snprintf(pBueffel, 131, "%s.%s.vb2 = %f", argv[0], argv[1], + crystal->VB2); + SCWrite(pCon, pBueffel, eValue); return 1; - }else if(strcmp(argv[2],"ss") == 0){ - snprintf(pBueffel,131,"%s.%s.ss = %d",argv[0],argv[1],crystal->ss); - SCWrite(pCon,pBueffel,eValue); + } else if (strcmp(argv[2], "ss") == 0) { + snprintf(pBueffel, 131, "%s.%s.ss = %d", argv[0], argv[1], + crystal->ss); + SCWrite(pCon, pBueffel, eValue); return 1; - }else { - snprintf(pBueffel,131,"ERROR: crystal parameter %s not known", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } -} -/*------------------------------------------------------------------*/ -static int handleCrystalCommands(pmaCrystal crystal, SConnection *pCon, - int argc, char *argv[]){ - char pBueffel[132]; - - if(argc < 3){ - snprintf(pBueffel,131,"ERROR: insufficent number of arguments to %s %s", - argv[0],argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(argc > 3) { - return setCrystalParameters(crystal,pCon,argc,argv); } else { - return getCrystalParameters(crystal,pCon,argc,argv); + snprintf(pBueffel, 131, "ERROR: crystal parameter %s not known", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } } + +/*------------------------------------------------------------------*/ +static int handleCrystalCommands(pmaCrystal crystal, SConnection * pCon, + int argc, char *argv[]) +{ + char pBueffel[132]; + + if (argc < 3) { + snprintf(pBueffel, 131, + "ERROR: insufficent number of arguments to %s %s", argv[0], + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (argc > 3) { + return setCrystalParameters(crystal, pCon, argc, argv); + } else { + return getCrystalParameters(crystal, pCon, argc, argv); + } +} + /*---------------------------------------------------------------------*/ -static int tasReadCell(SConnection *pCon, ptasUB self, int argc, char *argv[]){ +static int tasReadCell(SConnection * pCon, ptasUB self, int argc, + char *argv[]) +{ int status; Tcl_Interp *pTcl = InterpGetTcl(pServ->pSics); char pBueffel[256]; - if(argc < 8){ - SCWrite(pCon,"ERROR: insufficient number of arguments to tasub cell", - eError); + if (argc < 8) { + SCWrite(pCon, "ERROR: insufficient number of arguments to tasub cell", + eError); return 0; } - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - status = Tcl_GetDouble(pTcl,argv[2],&self->cell.a); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(pTcl, argv[2], &self->cell.a); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } - status = Tcl_GetDouble(pTcl,argv[3],&self->cell.b); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(pTcl, argv[3], &self->cell.b); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; } - status = Tcl_GetDouble(pTcl,argv[4],&self->cell.c); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(pTcl, argv[4], &self->cell.c); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); return 0; } - status = Tcl_GetDouble(pTcl,argv[5],&self->cell.alpha); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[5]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(pTcl, argv[5], &self->cell.alpha); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[5]); + SCWrite(pCon, pBueffel, eError); return 0; } - status = Tcl_GetDouble(pTcl,argv[6],&self->cell.beta); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[6]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(pTcl, argv[6], &self->cell.beta); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[6]); + SCWrite(pCon, pBueffel, eError); return 0; } - status = Tcl_GetDouble(pTcl,argv[7],&self->cell.gamma); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[7]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(pTcl, argv[7], &self->cell.gamma); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[7]); + SCWrite(pCon, pBueffel, eError); return 0; } self->ubValid = 0; - SCWrite(pCon,"WARNING: UB is now invalid",eWarning); + SCWrite(pCon, "WARNING: UB is now invalid", eWarning); SCparChange(pCon); SCSendOK(pCon); return 1; } + /*---------------------------------------------------------------------*/ -static void tasListCell(SConnection *pCon, char *name, lattice direct){ +static void tasListCell(SConnection * pCon, char *name, lattice direct) +{ char pBueffel[255]; - snprintf(pBueffel,255,"%s.cell = %f %f %f %f %f %f", - name,direct.a, direct.b,direct.c, - direct.alpha,direct.beta,direct.gamma); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "%s.cell = %f %f %f %f %f %f", + name, direct.a, direct.b, direct.c, + direct.alpha, direct.beta, direct.gamma); + SCWrite(pCon, pBueffel, eValue); } + /*--------------------------------------------------------------------*/ -static void clearReflections(ptasUB self){ +static void clearReflections(ptasUB self) +{ int status; status = LLDnodePtr2First(self->reflectionList); - while(status != 0){ + while (status != 0) { LLDnodeDelete(self->reflectionList); status = LLDnodePtr2Next(self->reflectionList); } self->ubValid = 0; } + /*------------------------------------------------------------------*/ -static void listReflections(ptasUB self, SConnection *pCon){ +static void listReflections(ptasUB self, SConnection * pCon) +{ tasReflection r; int status; int count = 0; @@ -540,235 +590,266 @@ static void listReflections(ptasUB self, SConnection *pCon){ Tcl_DString list; Tcl_DStringInit(&list); - snprintf(line,255, - " NO QH QK QL A3 A4 SGU SGL EI EF\n"); - Tcl_DStringAppend(&list,line,-1); + snprintf(line, 255, + " NO QH QK QL A3 A4 SGU SGL EI EF\n"); + Tcl_DStringAppend(&list, line, -1); status = LLDnodePtr2First(self->reflectionList); - while(status == 1){ + while (status == 1) { count++; - LLDnodeDataTo(self->reflectionList,&r); - snprintf(line,255,"%3d %6.2f %6.2f %6.2f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", - count, r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, r.angles.sample_two_theta, - r.angles.sgu, r.angles.sgl, KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); - Tcl_DStringAppend(&list,line,-1); + LLDnodeDataTo(self->reflectionList, &r); + snprintf(line, 255, + "%3d %6.2f %6.2f %6.2f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", + count, r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, + r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, + KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); + Tcl_DStringAppend(&list, line, -1); status = LLDnodePtr2Next(self->reflectionList); } - if(count == 0){ - SCWrite(pCon,"Reflection list is empty",eValue); + if (count == 0) { + SCWrite(pCon, "Reflection list is empty", eValue); } else { - SCWrite(pCon,Tcl_DStringValue(&list),eValue); + SCWrite(pCon, Tcl_DStringValue(&list), eValue); } Tcl_DStringFree(&list); } + /*-------------------------------------------------------------------*/ -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*-------------------------------------------------------------------*/ -static int addReflection(ptasUB self, SicsInterp *pSics, - SConnection *pCon, - int argc, char *argv[]){ +static int addReflection(ptasUB self, SicsInterp * pSics, + SConnection * pCon, int argc, char *argv[]) +{ tasReflection r; int status, count = 11; char pBueffel[256]; tasAngles angles; Tcl_DString list; - if(argc < 5){ - SCWrite(pCon,"ERROR: need at least miller indices to add reflection", - eError); + if (argc < 5) { + SCWrite(pCon, "ERROR: need at least miller indices to add reflection", + eError); return 0; } - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[2],&r.qe.qh); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], &r.qe.qh); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&r.qe.qk); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&r.qe.ql); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - if(self->tasMode == ELASTIC){ - count = 10; } - if(argc >= count){ - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[5],&r.angles.a3); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[5]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &r.qe.qk); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &r.qe.ql); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + if (self->tasMode == ELASTIC) { + count = 10; + } + if (argc >= count) { + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[5], &r.angles.a3); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[5]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[6],&r.angles.sample_two_theta); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[6]); - SCWrite(pCon,pBueffel,eError); + } + status = + Tcl_GetDouble(InterpGetTcl(pSics), argv[6], + &r.angles.sample_two_theta); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[6]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[7],&r.angles.sgu); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[7]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[7], &r.angles.sgu); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[7]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[8],&r.angles.sgl); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[8]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[8], &r.angles.sgl); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[8]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[9],&r.qe.ki); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[9]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[9], &r.qe.ki); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[9]); + SCWrite(pCon, pBueffel, eError); return 0; - } - r.qe.ki = energyToK(r.qe.ki); - if(self->tasMode != ELASTIC){ - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[10],&r.qe.kf); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[10]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - r.qe.kf = energyToK(r.qe.kf); + } + r.qe.ki = energyToK(r.qe.ki); + if (self->tasMode != ELASTIC) { + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[10], &r.qe.kf); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[10]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + r.qe.kf = energyToK(r.qe.kf); } else { - r.qe.kf = r.qe.ki; + r.qe.kf = r.qe.ki; } } else { - if(argc > 5){ + if (argc > 5) { SCWrite(pCon, - "WARNING: not all angles given on command line, using positions instead", - eWarning); + "WARNING: not all angles given on command line, using positions instead", + eWarning); } - status = readTASAngles(self,pCon,&r.angles); - if(status != 1){ + status = readTASAngles(self, pCon, &r.angles); + if (status != 1) { return status; } - r.qe.ki = maCalcK(self->machine.monochromator,r.angles.monochromator_two_theta); - r.qe.kf = maCalcK(self->machine.analyzer,r.angles.analyzer_two_theta); + r.qe.ki = + maCalcK(self->machine.monochromator, + r.angles.monochromator_two_theta); + r.qe.kf = maCalcK(self->machine.analyzer, r.angles.analyzer_two_theta); } - if(self->tasMode == ELASTIC){ - r.qe.kf = r.qe.ki; + if (self->tasMode == ELASTIC) { + r.qe.kf = r.qe.ki; } - if(ABS(r.qe.ki - r.qe.kf) > .01) { - SCWrite(pCon,"WARNING: KI != KF!",eWarning); + if (ABS(r.qe.ki - r.qe.kf) > .01) { + SCWrite(pCon, "WARNING: KI != KF!", eWarning); } - LLDnodeAppend(self->reflectionList,&r); + LLDnodeAppend(self->reflectionList, &r); Tcl_DStringInit(&list); - snprintf(pBueffel,255, - " QH QK QL A3 A4 SGU SGL EI EF\n"); - Tcl_DStringAppend(&list,pBueffel,-1); - snprintf(pBueffel,255, - " %6.2f %6.2f %6.2f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", - r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, r.angles.sample_two_theta, - r.angles.sgu, r.angles.sgl, KtoEnergy(r.qe.ki), - KtoEnergy(r.qe.kf)); - Tcl_DStringAppend(&list,pBueffel,-1); - SCWrite(pCon,Tcl_DStringValue(&list),eValue); + snprintf(pBueffel, 255, + " QH QK QL A3 A4 SGU SGL EI EF\n"); + Tcl_DStringAppend(&list, pBueffel, -1); + snprintf(pBueffel, 255, + " %6.2f %6.2f %6.2f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", + r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, + r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, + KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); + Tcl_DStringAppend(&list, pBueffel, -1); + SCWrite(pCon, Tcl_DStringValue(&list), eValue); Tcl_DStringFree(&list); SCparChange(pCon); return 1; } + /*------------------------------------------------------------------------------*/ -static int readReflection(SConnection *pCon, SicsInterp *pSics, - ptasReflection res, - int argc, char *argv[]){ +static int readReflection(SConnection * pCon, SicsInterp * pSics, + ptasReflection res, int argc, char *argv[]) +{ tasReflection r; int status; char pBueffel[256]; - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - if(argc < 11){ - SCWrite(pCon,"ERROR: not enough parameters to read reflection",eError); + if (argc < 11) { + SCWrite(pCon, "ERROR: not enough parameters to read reflection", + eError); return 0; } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[2],&r.qe.qh); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], &r.qe.qh); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&r.qe.qk); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &r.qe.qk); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&r.qe.ql); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &r.qe.ql); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[5],&r.angles.a3); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[5]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[5], &r.angles.a3); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[5]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[6],&r.angles.sample_two_theta); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[6]); - SCWrite(pCon,pBueffel,eError); + } + status = + Tcl_GetDouble(InterpGetTcl(pSics), argv[6], + &r.angles.sample_two_theta); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[6]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[7],&r.angles.sgu); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[7]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[7], &r.angles.sgu); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[7]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[8],&r.angles.sgl); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[8]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[8], &r.angles.sgl); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[8]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[9],&r.qe.ki); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[9]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[9], &r.qe.ki); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[9]); + SCWrite(pCon, pBueffel, eError); return 0; - } + } r.qe.ki = energyToK(r.qe.ki); - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[10],&r.qe.kf); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[10]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[10], &r.qe.kf); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[10]); + SCWrite(pCon, pBueffel, eError); return 0; - } + } r.qe.kf = energyToK(r.qe.kf); - if(ABS(r.qe.ki - r.qe.kf) > .01) { - SCWrite(pCon,"WARNING: KI != KF!",eWarning); + if (ABS(r.qe.ki - r.qe.kf) > .01) { + SCWrite(pCon, "WARNING: KI != KF!", eWarning); } *res = r; return 1; } + /*-----------------------------------------------------------------*/ -int findReflection(int list, int idx, ptasReflection r){ +int findReflection(int list, int idx, ptasReflection r) +{ int count = 0; int status; status = LLDnodePtr2First(list); - while(status == 1){ - if(count == idx){ - LLDnodeDataTo(list,r); + while (status == 1) { + if (count == idx) { + LLDnodeDataTo(list, r); return 1; } status = LLDnodePtr2Next(list); @@ -776,59 +857,64 @@ int findReflection(int list, int idx, ptasReflection r){ } return 0; } + /*------------------------------------------------------------------*/ -static void listUB(ptasUB self , SConnection *pCon){ +static void listUB(ptasUB self, SConnection * pCon) +{ Tcl_DString list; char pBueffel[255]; int i; tasReflection r; Tcl_DStringInit(&list); - if(self->machine.UB == NULL){ - Tcl_DStringAppend(&list,"NO UB",-1); - } else { - Tcl_DStringAppend(&list,"UB = ", -1); - snprintf(pBueffel,255,"%f %f %f\n", self->machine.UB[0][0], - self->machine.UB[0][1],self->machine.UB[0][2]); - Tcl_DStringAppend(&list,pBueffel,-1); - for(i = 1; i < 3; i++){ - snprintf(pBueffel,255," %f %f %f\n", self->machine.UB[i][0], - self->machine.UB[i][1],self->machine.UB[i][2]); - Tcl_DStringAppend(&list,pBueffel,-1); + if (self->machine.UB == NULL) { + Tcl_DStringAppend(&list, "NO UB", -1); + } else { + Tcl_DStringAppend(&list, "UB = ", -1); + snprintf(pBueffel, 255, "%f %f %f\n", self->machine.UB[0][0], + self->machine.UB[0][1], self->machine.UB[0][2]); + Tcl_DStringAppend(&list, pBueffel, -1); + for (i = 1; i < 3; i++) { + snprintf(pBueffel, 255, " %f %f %f\n", self->machine.UB[i][0], + self->machine.UB[i][1], self->machine.UB[i][2]); + Tcl_DStringAppend(&list, pBueffel, -1); } } - snprintf(pBueffel,255,"UB generated from reflections:\n"); - Tcl_DStringAppend(&list,pBueffel,-1); - snprintf(pBueffel,255, - " QH QK QL A3 A4 SGU SGL EI EF\n"); - Tcl_DStringAppend(&list,pBueffel,-1); + snprintf(pBueffel, 255, "UB generated from reflections:\n"); + Tcl_DStringAppend(&list, pBueffel, -1); + snprintf(pBueffel, 255, + " QH QK QL A3 A4 SGU SGL EI EF\n"); + Tcl_DStringAppend(&list, pBueffel, -1); r = self->r1; - snprintf(pBueffel,255, - " %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", - r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, - r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, - KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); - Tcl_DStringAppend(&list,pBueffel,-1); + snprintf(pBueffel, 255, + " %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", + r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, + r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, + KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); + Tcl_DStringAppend(&list, pBueffel, -1); r = self->r2; - snprintf(pBueffel,255, - " %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", - r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, - r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, - KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); - Tcl_DStringAppend(&list,pBueffel,-1); - snprintf(pBueffel,255,"Plane Normal: %8.4f %8.4f %8.4f\n", - self->machine.planeNormal[0][0], self->machine.planeNormal[1][0], - self->machine.planeNormal[2][0]); - Tcl_DStringAppend(&list,pBueffel,-1); - if(self->ubValid == 0){ - Tcl_DStringAppend(&list,"WARNING: UB matrix is invalid\n",-1); + snprintf(pBueffel, 255, + " %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", + r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, + r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, + KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); + Tcl_DStringAppend(&list, pBueffel, -1); + snprintf(pBueffel, 255, "Plane Normal: %8.4f %8.4f %8.4f\n", + self->machine.planeNormal[0][0], + self->machine.planeNormal[1][0], + self->machine.planeNormal[2][0]); + Tcl_DStringAppend(&list, pBueffel, -1); + if (self->ubValid == 0) { + Tcl_DStringAppend(&list, "WARNING: UB matrix is invalid\n", -1); } - SCWrite(pCon,Tcl_DStringValue(&list),eValue); + SCWrite(pCon, Tcl_DStringValue(&list), eValue); Tcl_DStringFree(&list); } + /*-----------------------------------------------------------------*/ -static void printReflectionDiagnostik(ptasUB self, SConnection *pCon, - tasReflection r){ +static void printReflectionDiagnostik(ptasUB self, SConnection * pCon, + tasReflection r) +{ tasReflection r2; Tcl_DString list; char line[256]; @@ -836,776 +922,842 @@ static void printReflectionDiagnostik(ptasUB self, SConnection *pCon, tasAngles angles; Tcl_DStringInit(&list); - snprintf(line,255, - "METHOD QH QK QL A3 A4 SGU SGL EI EF\n"); - Tcl_DStringAppend(&list,line,-1); - snprintf(line,255, - "INPUT %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", - r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, - r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, - KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); - Tcl_DStringAppend(&list,line,-1); + snprintf(line, 255, + "METHOD QH QK QL A3 A4 SGU SGL EI EF\n"); + Tcl_DStringAppend(&list, line, -1); + snprintf(line, 255, + "INPUT %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", + r.qe.qh, r.qe.qk, r.qe.ql, r.angles.a3, + r.angles.sample_two_theta, r.angles.sgu, r.angles.sgl, + KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); + Tcl_DStringAppend(&list, line, -1); qe.ki = r.qe.ki; qe.kf = r.qe.kf; qe.qh = r.qe.qh; qe.qk = r.qe.qk; qe.ql = r.qe.ql; - calcAllTasAngles(&self->machine,qe,&angles); - snprintf(line,255, - "QE->ANG %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", - r.qe.qh, r.qe.qk, r.qe.ql, - angles.a3, angles.sample_two_theta, - angles.sgu, angles.sgl, KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); - Tcl_DStringAppend(&list,line,-1); + calcAllTasAngles(&self->machine, qe, &angles); + snprintf(line, 255, + "QE->ANG %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", + r.qe.qh, r.qe.qk, r.qe.ql, + angles.a3, angles.sample_two_theta, + angles.sgu, angles.sgl, KtoEnergy(r.qe.ki), KtoEnergy(r.qe.kf)); + Tcl_DStringAppend(&list, line, -1); angles.a3 = r.angles.a3; angles.sample_two_theta = r.angles.sample_two_theta; angles.sgu = r.angles.sgu; angles.sgl = r.angles.sgl; - calcTasQEPosition(&self->machine,angles,&qe); - snprintf(line,255, - "ANG->QE %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", - qe.qh, qe.qk, qe.ql, angles.a3, angles.sample_two_theta, - angles.sgu, angles.sgl, KtoEnergy(qe.ki), KtoEnergy(qe.kf)); - Tcl_DStringAppend(&list,line,-1); - SCWrite(pCon,Tcl_DStringValue(&list),eWarning); + calcTasQEPosition(&self->machine, angles, &qe); + snprintf(line, 255, + "ANG->QE %8.4f %8.4f %8.4f %7.2f %7.2f %6.2f %6.2f %6.2f %6.2f\n", + qe.qh, qe.qk, qe.ql, angles.a3, angles.sample_two_theta, + angles.sgu, angles.sgl, KtoEnergy(qe.ki), KtoEnergy(qe.kf)); + Tcl_DStringAppend(&list, line, -1); + SCWrite(pCon, Tcl_DStringValue(&list), eWarning); Tcl_DStringFree(&list); } + /*------------------------------------------------------------------*/ -static void listDiagnostik(ptasUB self, SConnection *pCon){ +static void listDiagnostik(ptasUB self, SConnection * pCon) +{ tasReflection r; int status; status = LLDnodePtr2First(self->reflectionList); - while(status == 1){ - LLDnodeDataTo(self->reflectionList,&r); - printReflectionDiagnostik(self,pCon,r); + while (status == 1) { + LLDnodeDataTo(self->reflectionList, &r); + printReflectionDiagnostik(self, pCon, r); status = LLDnodePtr2Next(self->reflectionList); } } + /*-----------------------------------------------------------------*/ -static int addAuxReflection(ptasUB self, SConnection *pCon, - SicsInterp *pSics, int argc, char *argv[]){ +static int addAuxReflection(ptasUB self, SConnection * pCon, + SicsInterp * pSics, int argc, char *argv[]) +{ int status; tasReflection r1, r2; float value = -999.99; char pBueffel[256]; MATRIX UB = NULL, B = NULL; - if(argc < 5){ + if (argc < 5) { SCWrite(pCon, - "ERROR: not enough arguments auxiliary reflection, need HKL", - eError); + "ERROR: not enough arguments auxiliary reflection, need HKL", + eError); return 0; } - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[2],&r2.qe.qh); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&r2.qe.qk); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&r2.qe.ql); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - B = mat_creat(3,3,ZERO_MATRIX); - if(B == NULL){ - SCWrite(pCon,"ERROR: out of memory creating B matrix",eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], &r2.qe.qh); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } - status = calculateBMatrix(self->cell,B); - if(status < 0){ - SCWrite(pCon,"ERROR: bad cell constants, no volume",eError); - mat_free(B); - return 0; + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &r2.qe.qk); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &r2.qe.ql); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); + return 0; } - status = findReflection(self->reflectionList, 0,&r1); - if(status != 1){ + B = mat_creat(3, 3, ZERO_MATRIX); + if (B == NULL) { + SCWrite(pCon, "ERROR: out of memory creating B matrix", eError); + return 0; + } + status = calculateBMatrix(self->cell, B); + if (status < 0) { + SCWrite(pCon, "ERROR: bad cell constants, no volume", eError); + mat_free(B); + return 0; + } + + status = findReflection(self->reflectionList, 0, &r1); + if (status != 1) { r2.qe.kf = self->current.kf; r2.qe.ki = self->current.ki; - MotorGetSoftPosition(self->motors[A3],pCon,&value); + MotorGetSoftPosition(self->motors[A3], pCon, &value); r2.angles.a3 = value + 180.; r2.angles.sgu = .0; r2.angles.sgl = .0; - calcTwoTheta(B,r2.qe,self->machine.ss_sample,&r2.angles.sample_two_theta); + calcTwoTheta(B, r2.qe, self->machine.ss_sample, + &r2.angles.sample_two_theta); r1 = r2; } - - status = makeAuxReflection(B, r1, &r2,self->machine.ss_sample); + + status = makeAuxReflection(B, r1, &r2, self->machine.ss_sample); mat_free(B); - if(status < 0){ - SCWrite(pCon,"ERROR: out of memory in makeAuxUB or scattering angle not closed", - eError); - return 0; + if (status < 0) { + SCWrite(pCon, + "ERROR: out of memory in makeAuxUB or scattering angle not closed", + eError); + return 0; } - LLDnodeAppend(self->reflectionList,&r2); + LLDnodeAppend(self->reflectionList, &r2); SCSendOK(pCon); - return 1; + return 1; } + /*------------------------------------------------------------------*/ -static int calcAuxUB(ptasUB self, SConnection *pCon, SicsInterp *pSics, - int argc, char *argv[]){ +static int calcAuxUB(ptasUB self, SConnection * pCon, SicsInterp * pSics, + int argc, char *argv[]) +{ int status; tasReflection r1, r2; char pBueffel[256]; MATRIX UB = NULL, B = NULL; - if(argc < 5){ + if (argc < 5) { SCWrite(pCon, - "ERROR: not enough arguments for UB calculation, need HKL of second plane vector", - eError); + "ERROR: not enough arguments for UB calculation, need HKL of second plane vector", + eError); return 0; } - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[2],&r2.qe.qh); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], &r2.qe.qh); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&r2.qe.qk); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &r2.qe.qk); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&r2.qe.ql); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &r2.qe.ql); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); return 0; - } + } - status = findReflection(self->reflectionList, 0,&r1); - if(status != 1){ - snprintf(pBueffel,255,"ERROR: cannot find first reflection"); - SCWrite(pCon,pBueffel,eError); + status = findReflection(self->reflectionList, 0, &r1); + if (status != 1) { + snprintf(pBueffel, 255, "ERROR: cannot find first reflection"); + SCWrite(pCon, pBueffel, eError); return 0; } - B = mat_creat(3,3,ZERO_MATRIX); - if(B == NULL){ - SCWrite(pCon,"ERROR: out of memory creating B matrix",eError); + B = mat_creat(3, 3, ZERO_MATRIX); + if (B == NULL) { + SCWrite(pCon, "ERROR: out of memory creating B matrix", eError); return 0; } - status = calculateBMatrix(self->cell,B); - if(status < 0){ - SCWrite(pCon,"ERROR: bad cell constants, no volume",eError); - mat_free(B); - return 0; + status = calculateBMatrix(self->cell, B); + if (status < 0) { + SCWrite(pCon, "ERROR: bad cell constants, no volume", eError); + mat_free(B); + return 0; } - - status = makeAuxReflection(B, r1, &r2,self->machine.ss_sample); + + status = makeAuxReflection(B, r1, &r2, self->machine.ss_sample); mat_free(B); - if(status < 0){ - SCWrite(pCon,"ERROR: out of memory in makeAuxUB",eError); - return 0; + if (status < 0) { + SCWrite(pCon, "ERROR: out of memory in makeAuxUB", eError); + return 0; } - UB = calcTasUBFromTwoReflections(self->cell,r1,r2,&status); - if(UB == NULL){ - switch(status){ + UB = calcTasUBFromTwoReflections(self->cell, r1, r2, &status); + if (UB == NULL) { + switch (status) { case UBNOMEMORY: - SCWrite(pCon,"ERROR: out of memory calculating UB matrix",eError); + SCWrite(pCon, "ERROR: out of memory calculating UB matrix", eError); break; case REC_NO_VOLUME: - SCWrite(pCon,"ERROR: bad cell constants, no volume",eError); + SCWrite(pCon, "ERROR: bad cell constants, no volume", eError); break; } return 0; } - if(mat_det(UB) < .000001){ - SCWrite(pCon,"ERROR: invalid UB matrix, check reflections",eError); + if (mat_det(UB) < .000001) { + SCWrite(pCon, "ERROR: invalid UB matrix, check reflections", eError); return 0; } - if(self->machine.UB != NULL){ + if (self->machine.UB != NULL) { mat_free(self->machine.UB); } - if(self->machine.planeNormal != NULL){ + if (self->machine.planeNormal != NULL) { mat_free(self->machine.planeNormal); } self->machine.UB = UB; - self->machine.planeNormal = calcPlaneNormal(r1,r2); + self->machine.planeNormal = calcPlaneNormal(r1, r2); self->ubValid = 1; SCparChange(pCon); SCSendOK(pCon); return 1; } + /*------------------------------------------------------------------*/ -static int calcUB(ptasUB self, SConnection *pCon, SicsInterp *pSics, - int argc, char *argv[]){ +static int calcUB(ptasUB self, SConnection * pCon, SicsInterp * pSics, + int argc, char *argv[]) +{ int idx1, idx2, status; tasReflection r1, r2; char pBueffel[256]; MATRIX UB = NULL; - if(argc < 4){ + if (argc < 4) { SCWrite(pCon, - "ERROR: not enough arguments for UB calculation, need index of two reflections", - eError); + "ERROR: not enough arguments for UB calculation, need index of two reflections", + eError); return 0; } - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&idx1); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &idx1); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } + } idx1--; - status = findReflection(self->reflectionList, idx1,&r1); - if(status != 1){ - snprintf(pBueffel,255,"ERROR: cannot find reflection with index %d",idx1+1); - SCWrite(pCon,pBueffel,eError); + status = findReflection(self->reflectionList, idx1, &r1); + if (status != 1) { + snprintf(pBueffel, 255, "ERROR: cannot find reflection with index %d", + idx1 + 1); + SCWrite(pCon, pBueffel, eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[3],&idx2); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[3], &idx2); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; - } + } idx2--; - status = findReflection(self->reflectionList, idx2,&r2); - if(status != 1){ - snprintf(pBueffel,255,"ERROR: cannot find reflection with index %d",idx2+1); - SCWrite(pCon,pBueffel,eError); + status = findReflection(self->reflectionList, idx2, &r2); + if (status != 1) { + snprintf(pBueffel, 255, "ERROR: cannot find reflection with index %d", + idx2 + 1); + SCWrite(pCon, pBueffel, eError); return 0; } - UB = calcTasUBFromTwoReflections(self->cell,r1,r2,&status); - if(UB == NULL){ - switch(status){ + UB = calcTasUBFromTwoReflections(self->cell, r1, r2, &status); + if (UB == NULL) { + switch (status) { case UBNOMEMORY: - SCWrite(pCon,"ERROR: out of memory calculating UB matrix",eError); + SCWrite(pCon, "ERROR: out of memory calculating UB matrix", eError); break; case REC_NO_VOLUME: - SCWrite(pCon,"ERROR: bad cell constants, no volume",eError); + SCWrite(pCon, "ERROR: bad cell constants, no volume", eError); break; } return 0; } - if(mat_det(UB) < .000001){ - SCWrite(pCon,"ERROR: invalid UB matrix, check reflections",eError); + if (mat_det(UB) < .000001) { + SCWrite(pCon, "ERROR: invalid UB matrix, check reflections", eError); return 0; } - if(self->machine.UB != NULL){ + if (self->machine.UB != NULL) { mat_free(self->machine.UB); } - if(self->machine.planeNormal != NULL){ + if (self->machine.planeNormal != NULL) { mat_free(self->machine.planeNormal); } self->machine.UB = UB; - self->machine.planeNormal = calcPlaneNormal(r1,r2); + self->machine.planeNormal = calcPlaneNormal(r1, r2); self->r1 = r1; self->r2 = r2; self->ubValid = 1; - listUB(self,pCon); - listDiagnostik(self,pCon); + listUB(self, pCon); + listDiagnostik(self, pCon); SCparChange(pCon); return 1; } + /*-----------------------------------------------------------------*/ -static int calcUBFromCell(ptasUB self, SConnection *pCon){ - MATRIX B, U, UB; - tasReflection r1; - int status; - - B = mat_creat(3,3,UNIT_MATRIX); - U = mat_creat(3,3,UNIT_MATRIX); - status = findReflection(self->reflectionList, 0,&r1); - if(status == 1) { - /* - U[0][0] = Cosd(r1.angles.a3); - U[0][1] = -Sind(r1.angles.a3); - U[1][0] = Sind(r1.angles.a3); - U[1][1] = Cosd(r1.angles.a3); - */ - } - if(B == NULL || U == NULL){ - SCWrite(pCon,"ERROR: out of memory in calcUBFromCell",eError); - return 0; - } - status = calculateBMatrix(self->cell,B); - if(status == REC_NO_VOLUME){ - SCWrite(pCon,"ERROR: cell has no volume",eError); - return 0; - } - UB = mat_mul(U,B); - if(UB == NULL){ - SCWrite(pCon,"ERROR: matrix multiplication failed",eError); - return 0; - } - if(mat_det(UB) < .000001){ - SCWrite(pCon,"ERROR: invalid UB matrix, check cell",eError); - return 0; - } - if(self->machine.UB != NULL){ - mat_free(self->machine.UB); - } - self->machine.UB = UB; - self->machine.planeNormal[0][0] = .0; - self->machine.planeNormal[1][0] = .0; - self->machine.planeNormal[2][0] = 1.; - self->ubValid = 1; - SCparChange(pCon); - mat_free(U); - mat_free(B); - return 1; +static int calcUBFromCell(ptasUB self, SConnection * pCon) +{ + MATRIX B, U, UB; + tasReflection r1; + int status; + + B = mat_creat(3, 3, UNIT_MATRIX); + U = mat_creat(3, 3, UNIT_MATRIX); + status = findReflection(self->reflectionList, 0, &r1); + if (status == 1) { + /* + U[0][0] = Cosd(r1.angles.a3); + U[0][1] = -Sind(r1.angles.a3); + U[1][0] = Sind(r1.angles.a3); + U[1][1] = Cosd(r1.angles.a3); + */ + } + if (B == NULL || U == NULL) { + SCWrite(pCon, "ERROR: out of memory in calcUBFromCell", eError); + return 0; + } + status = calculateBMatrix(self->cell, B); + if (status == REC_NO_VOLUME) { + SCWrite(pCon, "ERROR: cell has no volume", eError); + return 0; + } + UB = mat_mul(U, B); + if (UB == NULL) { + SCWrite(pCon, "ERROR: matrix multiplication failed", eError); + return 0; + } + if (mat_det(UB) < .000001) { + SCWrite(pCon, "ERROR: invalid UB matrix, check cell", eError); + return 0; + } + if (self->machine.UB != NULL) { + mat_free(self->machine.UB); + } + self->machine.UB = UB; + self->machine.planeNormal[0][0] = .0; + self->machine.planeNormal[1][0] = .0; + self->machine.planeNormal[2][0] = 1.; + self->ubValid = 1; + SCparChange(pCon); + mat_free(U); + mat_free(B); + return 1; } + /*------------------------------------------------------------------*/ -static int calcRefAngles(ptasUB self, SConnection *pCon, - SicsInterp *pSics, - int argc, char *argv[]){ +static int calcRefAngles(ptasUB self, SConnection * pCon, + SicsInterp * pSics, int argc, char *argv[]) +{ tasQEPosition q; tasAngles angles; char pBueffel[256]; int status; - if(self->tasMode == ELASTIC){ - if(argc < 6){ - SCWrite(pCon,"ERROR: need Qh, Qk, Ql, EI for calculation", - eError); - return 0; - } + if (self->tasMode == ELASTIC) { + if (argc < 6) { + SCWrite(pCon, "ERROR: need Qh, Qk, Ql, EI for calculation", eError); + return 0; + } } else { - if(argc < 7){ - SCWrite(pCon,"ERROR: need Qh, Qk, Ql, EI, EF for calculation", - eError); - return 0; - } - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[2],&q.qh); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + if (argc < 7) { + SCWrite(pCon, "ERROR: need Qh, Qk, Ql, EI, EF for calculation", + eError); + return 0; + } + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], &q.qh); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&q.qk); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &q.qk); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&q.ql); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &q.ql); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[5],&q.ki); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[5]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[5], &q.ki); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[5]); + SCWrite(pCon, pBueffel, eError); return 0; - } - if(self->tasMode != ELASTIC){ - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[6],&q.kf); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[6]); - SCWrite(pCon,pBueffel,eError); - return 0; - } + } + if (self->tasMode != ELASTIC) { + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[6], &q.kf); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[6]); + SCWrite(pCon, pBueffel, eError); + return 0; + } } else { - q.kf = q.ki; + q.kf = q.ki; } q.ki = energyToK(q.ki); q.kf = energyToK(q.kf); - status = calcAllTasAngles(&self->machine,q,&angles); - switch(status){ + status = calcAllTasAngles(&self->machine, q, &angles); + switch (status) { case ENERGYTOBIG: - SCWrite(pCon,"ERROR: energy to big",eError); + SCWrite(pCon, "ERROR: energy to big", eError); return 0; break; case UBNOMEMORY: - SCWrite(pCon,"ERROR: Out of memory calculating angles",eError); + SCWrite(pCon, "ERROR: Out of memory calculating angles", eError); return 0; break; case BADRMATRIX: - SCWrite(pCon,"ERROR: bad crystallographic parameters or bad UB",eError); + SCWrite(pCon, "ERROR: bad crystallographic parameters or bad UB", + eError); return 0; break; case TRIANGLENOTCLOSED: - SCWrite(pCon,"ERROR: scattering triangle not closed",eError); + SCWrite(pCon, "ERROR: scattering triangle not closed", eError); return 0; break; } - if(self->tasMode != ELASTIC){ - snprintf(pBueffel,255," %8.2f %8.2f %8.2f %8.2f %8.2f %8.2f", - angles.monochromator_two_theta, - angles.a3, angles.sample_two_theta, - angles.sgl, angles.sgu, - angles.analyzer_two_theta); + if (self->tasMode != ELASTIC) { + snprintf(pBueffel, 255, " %8.2f %8.2f %8.2f %8.2f %8.2f %8.2f", + angles.monochromator_two_theta, + angles.a3, angles.sample_two_theta, + angles.sgl, angles.sgu, angles.analyzer_two_theta); } else { - snprintf(pBueffel,255," %8.2f %8.2f %8.2f %8.2f %8.2f", - angles.monochromator_two_theta, - angles.a3, angles.sample_two_theta, - angles.sgl, angles.sgu); + snprintf(pBueffel, 255, " %8.2f %8.2f %8.2f %8.2f %8.2f", + angles.monochromator_two_theta, + angles.a3, angles.sample_two_theta, angles.sgl, angles.sgu); } - SCWrite(pCon,pBueffel,eValue); + SCWrite(pCon, pBueffel, eValue); return 1; } + /*------------------------------------------------------------------*/ -static int calcQFromAngles(ptasUB self, SConnection *pCon, - SicsInterp *pSics, - int argc, char *argv[]){ +static int calcQFromAngles(ptasUB self, SConnection * pCon, + SicsInterp * pSics, int argc, char *argv[]) +{ tasQEPosition q; tasAngles angles; char pBueffel[256]; int status; - if(self->tasMode != ELASTIC){ - if(argc < 8){ - SCWrite(pCon,"ERROR: need a2, a3, a4, sgu, sgl, a6 for calculation", - eError); - return 0; - } + if (self->tasMode != ELASTIC) { + if (argc < 8) { + SCWrite(pCon, "ERROR: need a2, a3, a4, sgu, sgl, a6 for calculation", + eError); + return 0; + } } else { - if(argc < 7){ - SCWrite(pCon,"ERROR: need a2, a3, a4, sgu, sgl for calculation", - eError); - return 0; - } - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[2], - &angles.monochromator_two_theta); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + if (argc < 7) { + SCWrite(pCon, "ERROR: need a2, a3, a4, sgu, sgl for calculation", + eError); + return 0; + } + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], + &angles.monochromator_two_theta); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&angles.a3); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &angles.a3); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&angles.sample_two_theta); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); + } + status = + Tcl_GetDouble(InterpGetTcl(pSics), argv[4], + &angles.sample_two_theta); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[5],&angles.sgu); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[5]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[5], &angles.sgu); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[5]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[6],&angles.sgl); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[6]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[6], &angles.sgl); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[6]); + SCWrite(pCon, pBueffel, eError); return 0; - } - if(self->tasMode != ELASTIC){ - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[7],&angles.analyzer_two_theta); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[7]); - SCWrite(pCon,pBueffel,eError); - return 0; - } + } + if (self->tasMode != ELASTIC) { + status = + Tcl_GetDouble(InterpGetTcl(pSics), argv[7], + &angles.analyzer_two_theta); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[7]); + SCWrite(pCon, pBueffel, eError); + return 0; + } } else { - angles.analyzer_two_theta = angles.monochromator_two_theta; - } - status = calcTasQEPosition(&self->machine,angles,&q); - switch(status){ + angles.analyzer_two_theta = angles.monochromator_two_theta; + } + status = calcTasQEPosition(&self->machine, angles, &q); + switch (status) { case UBNOMEMORY: - SCWrite(pCon,"ERROR: Out of memory calculating angles",eError); + SCWrite(pCon, "ERROR: Out of memory calculating angles", eError); return 0; break; } - if(self->tasMode == ELASTIC){ - q.kf = q.ki; + if (self->tasMode == ELASTIC) { + q.kf = q.ki; } - snprintf(pBueffel,255,"%8.4f %8.4f %8.4f %8.4f %8.4f", - q.qh, - q.qk, - q.ql, - KtoEnergy(q.ki), - KtoEnergy(q.kf)); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "%8.4f %8.4f %8.4f %8.4f %8.4f", + q.qh, q.qk, q.ql, KtoEnergy(q.ki), KtoEnergy(q.kf)); + SCWrite(pCon, pBueffel, eValue); return 1; } + /*------------------------------------------------------------------*/ -static int setUB(SConnection *pCon, SicsInterp *pSics, ptasUB self, - int argc, char *argv[]){ +static int setUB(SConnection * pCon, SicsInterp * pSics, ptasUB self, + int argc, char *argv[]) +{ double value; char pBueffel[256]; int status; - if(argc < 11){ - SCWrite(pCon,"ERROR: not enough arguments for setting UB", - eError); + if (argc < 11) { + SCWrite(pCon, "ERROR: not enough arguments for setting UB", eError); return 0; } - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[2],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.UB[0][0] = value; + } + self->machine.UB[0][0] = value; - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.UB[0][1] = value; + } + self->machine.UB[0][1] = value; - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.UB[0][2] = value; + } + self->machine.UB[0][2] = value; - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[5],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[5]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[5], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[5]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.UB[1][0] = value; + } + self->machine.UB[1][0] = value; - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[6],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[6]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[6], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[6]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.UB[1][1] = value; + } + self->machine.UB[1][1] = value; - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[7],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[7]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[7], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[7]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.UB[1][2] = value; + } + self->machine.UB[1][2] = value; - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[8],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[8]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[8], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[8]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.UB[2][0] = value; + } + self->machine.UB[2][0] = value; - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[9],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[9]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[9], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[9]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.UB[2][1] = value; + } + self->machine.UB[2][1] = value; - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[10],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[10]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[10], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[10]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.UB[2][2] = value; + } + self->machine.UB[2][2] = value; self->ubValid = 1; SCSendOK(pCon); SCparChange(pCon); return 1; } + /*------------------------------------------------------------------*/ -static int getUB(SConnection *pCon, SicsInterp *pSics, ptasUB self, - int argc, char *argv[]){ +static int getUB(SConnection * pCon, SicsInterp * pSics, ptasUB self, + int argc, char *argv[]) +{ double value; char pBueffel[512]; int status; - snprintf(pBueffel,511,"tasub.ub = %f %f %f %f %f %f %f %f %f", - self->machine.UB[0][0], self->machine.UB[0][1], self->machine.UB[0][2], - self->machine.UB[1][0], self->machine.UB[1][1], self->machine.UB[1][2], - self->machine.UB[2][0], self->machine.UB[2][1], self->machine.UB[2][2]); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 511, "tasub.ub = %f %f %f %f %f %f %f %f %f", + self->machine.UB[0][0], self->machine.UB[0][1], + self->machine.UB[0][2], self->machine.UB[1][0], + self->machine.UB[1][1], self->machine.UB[1][2], + self->machine.UB[2][0], self->machine.UB[2][1], + self->machine.UB[2][2]); + SCWrite(pCon, pBueffel, eValue); return 1; } + /*------------------------------------------------------------------*/ -static int setNormal(SConnection *pCon, SicsInterp *pSics, ptasUB self, - int argc, char *argv[]){ +static int setNormal(SConnection * pCon, SicsInterp * pSics, ptasUB self, + int argc, char *argv[]) +{ double value; char pBueffel[256]; int status; - if(argc < 5){ - SCWrite(pCon,"ERROR: not enough arguments for setting plane normal", - eError); - return 0; - } - - if(!SCMatchRights(pCon,usUser)){ + if (argc < 5) { + SCWrite(pCon, "ERROR: not enough arguments for setting plane normal", + eError); return 0; } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[2],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + if (!SCMatchRights(pCon, usUser)) { return 0; - } - self->machine.planeNormal[0][0] = value; + } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.planeNormal[1][0] = value; + } + self->machine.planeNormal[0][0] = value; - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&value); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; - } - self->machine.planeNormal[2][0] = value; + } + self->machine.planeNormal[1][0] = value; + + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &value); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->machine.planeNormal[2][0] = value; SCSendOK(pCon); SCparChange(pCon); return 1; } + /*------------------------------------------------------------------*/ -static int setTarget(SConnection *pCon, SicsInterp *pSics, ptasUB self, - int argc, char *argv[]){ +static int setTarget(SConnection * pCon, SicsInterp * pSics, ptasUB self, + int argc, char *argv[]) +{ double value; char pBueffel[256]; int status; - if(argc < 8){ - SCWrite(pCon,"ERROR: not enough arguments for setting qe target", - eError); - return 0; - } - - if(!SCMatchRights(pCon,usUser)){ + if (argc < 8) { + SCWrite(pCon, "ERROR: not enough arguments for setting qe target", + eError); return 0; } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[2],&self->target.qh); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + if (!SCMatchRights(pCon, usUser)) { return 0; - } + } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[3],&self->target.qk); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[2], &self->target.qh); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } + } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[4],&self->target.ql); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[4]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[3], &self->target.qk); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[3]); + SCWrite(pCon, pBueffel, eError); return 0; - } + } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[5],&self->target.qm); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[5]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[4], &self->target.ql); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[4]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[6],&self->target.ki); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[6]); - SCWrite(pCon,pBueffel,eError); + } + + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[5], &self->target.qm); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[5]); + SCWrite(pCon, pBueffel, eError); return 0; - } - status = Tcl_GetDouble(InterpGetTcl(pSics),argv[7],&self->target.kf); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[7]); - SCWrite(pCon,pBueffel,eError); + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[6], &self->target.ki); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[6]); + SCWrite(pCon, pBueffel, eError); return 0; - } + } + status = Tcl_GetDouble(InterpGetTcl(pSics), argv[7], &self->target.kf); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[7]); + SCWrite(pCon, pBueffel, eError); + return 0; + } SCSendOK(pCon); return 1; } + /*------------------------------------------------------------------*/ -static int tasUpdate(SConnection *pCon, ptasUB self){ +static int tasUpdate(SConnection * pCon, ptasUB self) +{ int status; tasAngles angles; - - status = readTASAngles(self,pCon,&angles); - if(status != 1){ + + status = readTASAngles(self, pCon, &angles); + if (status != 1) { return status; } status = calcTasQEPosition(&self->machine, angles, &self->current); - if(status < 0){ - SCWrite(pCon,"ERROR: out of memory calculating Q-E variables",eError); + if (status < 0) { + SCWrite(pCon, "ERROR: out of memory calculating Q-E variables", + eError); return 0; } - if(self->tasMode == ELASTIC){ - self->current.kf = self->current.ki; + if (self->tasMode == ELASTIC) { + self->current.kf = self->current.ki; } self->mustRecalculate = 0; SCSendOK(pCon); return 1; -} +} + /*------------------------------------------------------------------*/ -static int deleteReflection(SConnection *pCon, SicsInterp *pSics, - ptasUB self, int argc, char *argv[]){ +static int deleteReflection(SConnection * pCon, SicsInterp * pSics, + ptasUB self, int argc, char *argv[]) +{ int idx, count = 0, status; char pBueffel[256]; - if(argc < 3){ - SCWrite(pCon,"ERROR: need number of reflection to delete",eError); + if (argc < 3) { + SCWrite(pCon, "ERROR: need number of reflection to delete", eError); return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&idx); - if(status != TCL_OK){ - snprintf(pBueffel,255,"ERROR: failed to convert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &idx); + if (status != TCL_OK) { + snprintf(pBueffel, 255, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; - } + } idx--; status = LLDnodePtr2First(self->reflectionList); - while(status == 1){ - if(count == idx){ + while (status == 1) { + if (count == idx) { LLDnodeDelete(self->reflectionList); break; } @@ -1615,183 +1767,193 @@ static int deleteReflection(SConnection *pCon, SicsInterp *pSics, SCSendOK(pCon); return 1; } + /*-------------------------------------------------------------------*/ -int TasUBWrapper(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int TasUBWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ ptasUB self = NULL; char pBueffel[131]; int status, newSS; - self = (ptasUB)pData; + self = (ptasUB) pData; assert(self != NULL); - if(argc < 2){ - SCWrite(pCon,"ERROR: insufficient arguments to tasUB",eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient arguments to tasUB", eError); return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"mono") == 0){ - status = handleCrystalCommands(&self->machine.monochromator,pCon,argc,argv); + if (strcmp(argv[1], "mono") == 0) { + status = + handleCrystalCommands(&self->machine.monochromator, pCon, argc, + argv); self->mustRecalculate = 1; return status; - } else if(strcmp(argv[1],"ana") == 0){ - status = handleCrystalCommands(&self->machine.analyzer,pCon,argc,argv); + } else if (strcmp(argv[1], "ana") == 0) { + status = + handleCrystalCommands(&self->machine.analyzer, pCon, argc, argv); self->mustRecalculate = 1; return status; - }else if(strcmp(argv[1],"cell") == 0){ - if(argc > 2){ - return tasReadCell(pCon,self,argc,argv); + } else if (strcmp(argv[1], "cell") == 0) { + if (argc > 2) { + return tasReadCell(pCon, self, argc, argv); } else { - tasListCell(pCon,argv[0],self->cell); + tasListCell(pCon, argv[0], self->cell); return 1; } - } else if(strcmp(argv[1],"clear") == 0){ + } else if (strcmp(argv[1], "clear") == 0) { clearReflections(self); clearReflections(self); - SCWrite(pCon,"WARNING: UB is now invalid",eWarning); + SCWrite(pCon, "WARNING: UB is now invalid", eWarning); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"listref") == 0){ - listReflections(self,pCon); + } else if (strcmp(argv[1], "listref") == 0) { + listReflections(self, pCon); return 1; - } else if(strcmp(argv[1],"addref") == 0){ - return addReflection(self,pSics,pCon,argc,argv); - } else if(strcmp(argv[1],"listub") == 0){ - listUB(self,pCon); + } else if (strcmp(argv[1], "addref") == 0) { + return addReflection(self, pSics, pCon, argc, argv); + } else if (strcmp(argv[1], "listub") == 0) { + listUB(self, pCon); return 1; - } else if(strcmp(argv[1],"makeub") == 0){ - return calcUB(self,pCon,pSics,argc,argv); - } else if(strcmp(argv[1],"makeauxub") == 0){ - return calcAuxUB(self,pCon,pSics,argc,argv); - } else if(strcmp(argv[1],"addauxref") == 0){ - return addAuxReflection(self,pCon,pSics,argc,argv); - } else if(strcmp(argv[1],"makeubfromcell") == 0){ - return calcUBFromCell(self,pCon); - } else if(strcmp(argv[1],"calcang") == 0){ - return calcRefAngles(self,pCon,pSics,argc,argv); - } else if(strcmp(argv[1],"calcqe") == 0){ - return calcQFromAngles(self,pCon,pSics,argc,argv); - } else if(strcmp(argv[1],"setub") == 0){ - return setUB(pCon,pSics,self,argc,argv); - } else if(strcmp(argv[1],"getub") == 0){ - return getUB(pCon,pSics,self,argc,argv); - } else if(strcmp(argv[1],"setnormal") == 0){ - return setNormal(pCon,pSics,self,argc,argv); - } else if(strcmp(argv[1],"settarget") == 0){ - return setTarget(pCon,pSics,self,argc,argv); - } else if(strcmp(argv[1],"update") == 0){ - return tasUpdate(pCon,self); - } else if(strcmp(argv[1],"del") == 0){ - return deleteReflection(pCon,pSics,self,argc,argv); - } else if(strcmp(argv[1],"r1") == 0){ - return readReflection(pCon,pSics,&self->r1,argc,argv); - } else if(strcmp(argv[1],"r2") == 0){ - return readReflection(pCon,pSics,&self->r2,argc,argv); - } else if(strcmp(argv[1],"updatetargets") == 0){ - updateTargets(self,pCon); + } else if (strcmp(argv[1], "makeub") == 0) { + return calcUB(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "makeauxub") == 0) { + return calcAuxUB(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "addauxref") == 0) { + return addAuxReflection(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "makeubfromcell") == 0) { + return calcUBFromCell(self, pCon); + } else if (strcmp(argv[1], "calcang") == 0) { + return calcRefAngles(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "calcqe") == 0) { + return calcQFromAngles(self, pCon, pSics, argc, argv); + } else if (strcmp(argv[1], "setub") == 0) { + return setUB(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "getub") == 0) { + return getUB(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "setnormal") == 0) { + return setNormal(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "settarget") == 0) { + return setTarget(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "update") == 0) { + return tasUpdate(pCon, self); + } else if (strcmp(argv[1], "del") == 0) { + return deleteReflection(pCon, pSics, self, argc, argv); + } else if (strcmp(argv[1], "r1") == 0) { + return readReflection(pCon, pSics, &self->r1, argc, argv); + } else if (strcmp(argv[1], "r2") == 0) { + return readReflection(pCon, pSics, &self->r2, argc, argv); + } else if (strcmp(argv[1], "updatetargets") == 0) { + updateTargets(self, pCon); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"const") == 0){ - if(argc > 2){ + } else if (strcmp(argv[1], "const") == 0) { + if (argc > 2) { strtolower(argv[2]); - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - if(strcmp(argv[2],"ki") == 0){ - self->tasMode = KICONST; - } else if(strcmp(argv[2],"kf") == 0){ - self->tasMode = KFCONST; - } else if(strcmp(argv[2],"elastic") == 0){ - self->tasMode = ELASTIC; - } else { - SCWrite(pCon, - "ERROR: unknown triple axis mode, accepted are ki, kf, elastic", - eError); - return 0; - } - SCSendOK(pCon); - return 1; - } else { - if(self->tasMode == KICONST){ - snprintf(pBueffel,131,"%s.const = ki",argv[0]); - } else if(self->tasMode == ELASTIC){ - snprintf(pBueffel,131,"%s.const = elastic", argv[0]); - } else { - snprintf(pBueffel,131,"%s.const = kf",argv[0]); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } else if(strcmp(argv[1],"ss") == 0){ - if(argc > 2){ - strtolower(argv[2]); - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&newSS); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert argument to number",eError); - return 0; - } - if(newSS != 1 && newSS != -1){ - SCWrite(pCon,"ERROR: invalid value for scattering sense, only 1, -1 allowed", - eError); - return 0; - } - self->machine.ss_sample = newSS; - tasUpdate(pCon,self); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,131,"%s.ss = %d",argv[0],self->machine.ss_sample); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } else if(strcmp(argv[1],"outofplane") == 0){ - if(argc > 2){ - strtolower(argv[2]); - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&newSS); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert argument to number",eError); + if (strcmp(argv[2], "ki") == 0) { + self->tasMode = KICONST; + } else if (strcmp(argv[2], "kf") == 0) { + self->tasMode = KFCONST; + } else if (strcmp(argv[2], "elastic") == 0) { + self->tasMode = ELASTIC; + } else { + SCWrite(pCon, + "ERROR: unknown triple axis mode, accepted are ki, kf, elastic", + eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else { + if (self->tasMode == KICONST) { + snprintf(pBueffel, 131, "%s.const = ki", argv[0]); + } else if (self->tasMode == ELASTIC) { + snprintf(pBueffel, 131, "%s.const = elastic", argv[0]); + } else { + snprintf(pBueffel, 131, "%s.const = kf", argv[0]); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[1], "ss") == 0) { + if (argc > 2) { + strtolower(argv[2]); + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + status = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &newSS); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert argument to number", + eError); + return 0; + } + if (newSS != 1 && newSS != -1) { + SCWrite(pCon, + "ERROR: invalid value for scattering sense, only 1, -1 allowed", + eError); + return 0; + } + self->machine.ss_sample = newSS; + tasUpdate(pCon, self); + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 131, "%s.ss = %d", argv[0], + self->machine.ss_sample); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[1], "outofplane") == 0) { + if (argc > 2) { + strtolower(argv[2]); + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + status = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &newSS); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert argument to number", + eError); return 0; } self->outOfPlaneAllowed = newSS; SCSendOK(pCon); return 1; } else { - snprintf(pBueffel,131,"%s.outofplane = %d",argv[0],self->outOfPlaneAllowed); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 131, "%s.outofplane = %d", argv[0], + self->outOfPlaneAllowed); + SCWrite(pCon, pBueffel, eValue); return 1; } - } else if(strcmp(argv[1],"silent") == 0){ - if(argc > 2){ + } else if (strcmp(argv[1], "silent") == 0) { + if (argc > 2) { strtolower(argv[2]); - if(!SCMatchRights(pCon,usUser)){ + if (!SCMatchRights(pCon, usUser)) { return 0; } - status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&newSS); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert argument to number",eError); + status = Tcl_GetInt(InterpGetTcl(pSics), argv[2], &newSS); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert argument to number", + eError); return 0; } self->silent = newSS; SCSendOK(pCon); return 1; } else { - snprintf(pBueffel,131,"%s.silent = %d",argv[0],self->silent); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 131, "%s.silent = %d", argv[0], self->silent); + SCWrite(pCon, pBueffel, eValue); return 1; } } else { - snprintf(pBueffel,131,"ERROR: subcommand %s to %s not defined",argv[1], - argv[0]); - SCWrite(pCon,pBueffel,eError); + snprintf(pBueffel, 131, "ERROR: subcommand %s to %s not defined", + argv[1], argv[0]); + SCWrite(pCon, pBueffel, eError); return 0; } return 1; } - diff --git a/tasub.h b/tasub.h index 1d22c3ab..d94e7284 100644 --- a/tasub.h +++ b/tasub.h @@ -15,40 +15,40 @@ #include "motor.h" /*------------------- defines for tasMode -----------------------------------*/ - typedef struct{ - pObjectDescriptor pDes; - tasMachine machine; - int reflectionList; - lattice cell; - tasQEPosition target; - tasQEPosition current; - int tasMode; - int outOfPlaneAllowed; - double targetEn, actualEn; - int mustRecalculate; - int mustDrive; - pMotor motors[12]; - tasReflection r1, r2; - int ubValid; - int silent; -}tasUB, *ptasUB; +typedef struct { + pObjectDescriptor pDes; + tasMachine machine; + int reflectionList; + lattice cell; + tasQEPosition target; + tasQEPosition current; + int tasMode; + int outOfPlaneAllowed; + double targetEn, actualEn; + int mustRecalculate; + int mustDrive; + pMotor motors[12]; + tasReflection r1, r2; + int ubValid; + int silent; +} tasUB, *ptasUB; /*--------------------- the tas virtual motor data structure ---------------------*/ typedef struct { - pObjectDescriptor pDes; - pIDrivable pDriv; - ptasUB math; - int code; - }tasMot, *ptasMot; + pObjectDescriptor pDes; + pIDrivable pDriv; + ptasUB math; + int code; +} tasMot, *ptasMot; /*--------------------------------------------------------------------*/ -int TasUBFactory(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int TasUBWrapper(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int TasUBFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int TasUBWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); int findReflection(int list, int idx, ptasReflection r); -#endif +#endif diff --git a/tasublib.c b/tasublib.c index 6ceebb29..ac897c69 100644 --- a/tasublib.c +++ b/tasublib.c @@ -14,7 +14,7 @@ #include "vector.h" #include "tasublib.h" -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) #define PI 3.141592653589793 #define ECONST 2.072 #define DEGREE_RAD (PI/180.0) /* Radians per degree */ @@ -22,269 +22,303 @@ #define HOR 1 #define INPLANEPREC 0.01 /*============== monochromator/analyzer stuff =========================*/ -double energyToK(double energy){ +double energyToK(double energy) +{ double K; - - K = sqrt(energy/ECONST); + + K = sqrt(energy / ECONST); return K; } + /*---------------------------------------------------------------------*/ -double KtoEnergy(double k){ +double KtoEnergy(double k) +{ double energy; - energy = ECONST*k*k; + energy = ECONST * k * k; return energy; } + /*-------------------------------------------------------------------*/ -static double calcCurvature(double B1, double B2, double theta, - int ori){ +static double calcCurvature(double B1, double B2, double theta, int ori) +{ assert(ori == VERT || ori == HOR); - if(ori == VERT){ - return B1 + B2/Sind(ABS(theta)); + if (ori == VERT) { + return B1 + B2 / Sind(ABS(theta)); } else { - return B1 + B2*Sind(ABS(theta)); + return B1 + B2 * Sind(ABS(theta)); } } + /*--------------------------------------------------------------------*/ -int maCalcTwoTheta(maCrystal data, double k, double *two_theta){ +int maCalcTwoTheta(maCrystal data, double k, double *two_theta) +{ double fd, theta; /* fd = k/(2.*data.dd); */ - fd = PI/(data.dd*k); - if(fd > 1.0) { + fd = PI / (data.dd * k); + if (fd > 1.0) { return ENERGYTOBIG; } - theta = Asind(fd)*data.ss; - *two_theta = 2.*theta; + theta = Asind(fd) * data.ss; + *two_theta = 2. * theta; return 1; } + /*--------------------------------------------------------------------*/ -double maCalcVerticalCurvature(maCrystal data, double two_theta){ - return calcCurvature(data.VB1,data.VB2, two_theta/2.,VERT); +double maCalcVerticalCurvature(maCrystal data, double two_theta) +{ + return calcCurvature(data.VB1, data.VB2, two_theta / 2., VERT); } + /*-------------------------------------------------------------------*/ -double maCalcHorizontalCurvature(maCrystal data, double two_theta){ - return calcCurvature(data.HB1,data.HB2, two_theta/2.,HOR); +double maCalcHorizontalCurvature(maCrystal data, double two_theta) +{ + return calcCurvature(data.HB1, data.HB2, two_theta / 2., HOR); } + /*--------------------------------------------------------------------*/ -double maCalcK(maCrystal data, double two_theta){ +double maCalcK(maCrystal data, double two_theta) +{ double k; - k = ABS(data.dd * Sind(two_theta/2)); - if(ABS(k) > .001){ + k = ABS(data.dd * Sind(two_theta / 2)); + if (ABS(k) > .001) { k = PI / k; } else { k = .0; } return k; } + /*==================== reciprocal space ==============================*/ -static MATRIX tasReflectionToHC(tasQEPosition r, MATRIX B){ +static MATRIX tasReflectionToHC(tasQEPosition r, MATRIX B) +{ MATRIX h = NULL, hc = NULL; h = makeVector(); - if(h == NULL){ + if (h == NULL) { return NULL; } - vectorSet(h,0,r.qh); - vectorSet(h,1,r.qk); - vectorSet(h,2,r.ql); + vectorSet(h, 0, r.qh); + vectorSet(h, 1, r.qk); + vectorSet(h, 2, r.ql); - hc = mat_mul(B,h); + hc = mat_mul(B, h); killVector(h); return hc; } + /*------------------------------------------------------------------ a quadrant dependent tangens ------------------------------------------------------------------*/ -static double rtan(double y, double x){ +static double rtan(double y, double x) +{ double val; - if( (x == 0.) && (y == 0.) ) { + if ((x == 0.) && (y == 0.)) { return .0; - } - if( x == 0.) { - if(y < 0.){ - return -PI/2.; - } else { - return PI/2.; - } } - if(ABS(y) < ABS(x)) { - val = atan(ABS(y/x)); - if(x < 0.) { - val = PI - val; + if (x == 0.) { + if (y < 0.) { + return -PI / 2.; + } else { + return PI / 2.; + } + } + if (ABS(y) < ABS(x)) { + val = atan(ABS(y / x)); + if (x < 0.) { + val = PI - val; + } + if (y < 0.) { + val = -val; } - if(y < 0.){ - val = -val; - } return val; } else { - val = PI/2. - atan(ABS(x/y)); - if(x < 0.) { + val = PI / 2. - atan(ABS(x / y)); + if (x < 0.) { val = PI - val; - } - if( y < 0.) { - val = - val; - } + } + if (y < 0.) { + val = -val; + } } return val; } + /*---------------------------------------------------------------*/ -static double calcTheta(double ki, double kf, double two_theta){ +static double calcTheta(double ki, double kf, double two_theta) +{ /** * |ki| - |kf|cos(two_theta) * tan(theta) = -------------------------- * |kf|sin(two_theta) */ - return rtan(ABS(ki) - ABS(kf)*Cosd(two_theta), - ABS(kf)*Sind(two_theta))/DEGREE_RAD; + return rtan(ABS(ki) - ABS(kf) * Cosd(two_theta), + ABS(kf) * Sind(two_theta)) / DEGREE_RAD; } -/*-------------------------------------------------------------------------*/ -double tasAngleBetweenReflections(MATRIX B, tasReflection r1, tasReflection r2){ - MATRIX chi1, chi2, h1, h2; - double angle; - - h1 = makeVector(); - if(h1 == NULL){ - return -9999.99; - } - h1[0][0] = r1.qe.qh; - h1[1][0] = r1.qe.qk; - h1[2][0] = r1.qe.ql; - h2 = makeVector(); - if(h2 == NULL){ - return -999.99; - } - h2[0][0] = r2.qe.qh; - h2[1][0] = r2.qe.qk; - h2[2][0] = r2.qe.ql; - - chi1 = mat_mul(B,h1); - chi2 = mat_mul(B,h2); - if(chi1 != NULL && chi2 != NULL){ - angle = angleBetween(chi1,chi2); - killVector(chi1); - killVector(chi2); - } - killVector(h1); - killVector(h2); - return angle; +/*-------------------------------------------------------------------------*/ +double tasAngleBetweenReflections(MATRIX B, tasReflection r1, + tasReflection r2) +{ + MATRIX chi1, chi2, h1, h2; + double angle; + + h1 = makeVector(); + if (h1 == NULL) { + return -9999.99; + } + h1[0][0] = r1.qe.qh; + h1[1][0] = r1.qe.qk; + h1[2][0] = r1.qe.ql; + + h2 = makeVector(); + if (h2 == NULL) { + return -999.99; + } + h2[0][0] = r2.qe.qh; + h2[1][0] = r2.qe.qk; + h2[2][0] = r2.qe.ql; + + chi1 = mat_mul(B, h1); + chi2 = mat_mul(B, h2); + if (chi1 != NULL && chi2 != NULL) { + angle = angleBetween(chi1, chi2); + killVector(chi1); + killVector(chi2); + } + killVector(h1); + killVector(h2); + return angle; } + /*--------------------------------------------------------------------*/ -static MATRIX uFromAngles(double om, double sgu, double sgl){ +static MATRIX uFromAngles(double om, double sgu, double sgl) +{ MATRIX u; u = makeVector(); - if(u == NULL){ + if (u == NULL) { return NULL; } - vectorSet(u,0,-Cosd(sgl)*Cosd(om)); - vectorSet(u,1,Cosd(sgu)*Sind(om) - Sind(sgu)*Sind(sgl)*Cosd(om)); - vectorSet(u,2,-Sind(sgu)*Sind(om) - Cosd(sgu)*Sind(sgl)*Cosd(om)); - - return u; + vectorSet(u, 0, -Cosd(sgl) * Cosd(om)); + vectorSet(u, 1, Cosd(sgu) * Sind(om) - Sind(sgu) * Sind(sgl) * Cosd(om)); + vectorSet(u, 2, + -Sind(sgu) * Sind(om) - Cosd(sgu) * Sind(sgl) * Cosd(om)); + + return u; } + /*---------------------------------------------------------------*/ -MATRIX calcTasUVectorFromAngles(tasReflection r){ +MATRIX calcTasUVectorFromAngles(tasReflection r) +{ double theta, om; - theta = calcTheta(r.qe.ki,r.qe.kf,r.angles.sample_two_theta); + theta = calcTheta(r.qe.ki, r.qe.kf, r.angles.sample_two_theta); om = r.angles.a3 - theta; - return uFromAngles(om,r.angles.sgu, r.angles.sgl); + return uFromAngles(om, r.angles.sgu, r.angles.sgl); } + /*-----------------------------------------------------------------------------*/ -static MATRIX tasReflectionToQC(tasQEPosition r, MATRIX UB){ +static MATRIX tasReflectionToQC(tasQEPosition r, MATRIX UB) +{ MATRIX Q, QC; Q = makeVector(); - if(Q == NULL){ + if (Q == NULL) { return NULL; } - vectorSet(Q,0,r.qh); - vectorSet(Q,1,r.qk); - vectorSet(Q,2,r.ql); - QC = mat_mul(UB,Q); + vectorSet(Q, 0, r.qh); + vectorSet(Q, 1, r.qk); + vectorSet(Q, 2, r.ql); + QC = mat_mul(UB, Q); killVector(Q); return QC; } + /*-----------------------------------------------------------------*/ -int makeAuxReflection(MATRIX B, tasReflection r1, tasReflection *r2, - int ss){ - double theta, om, q, cos2t; - MATRIX QC; - - r2->angles = r1.angles; - r2->qe.ki = r1.qe.ki; - r2->qe.kf= r1.qe.kf; +int makeAuxReflection(MATRIX B, tasReflection r1, tasReflection * r2, + int ss) +{ + double theta, om, q, cos2t; + MATRIX QC; - theta = calcTheta(r1.qe.ki,r1.qe.kf,r1.angles.sample_two_theta); - om = r1.angles.a3 - theta; - om += tasAngleBetweenReflections(B,r1,*r2); - - QC = tasReflectionToHC(r2->qe,B); - if(QC == NULL){ - return UBNOMEMORY; - } + r2->angles = r1.angles; + r2->qe.ki = r1.qe.ki; + r2->qe.kf = r1.qe.kf; - q = vectorLength(QC); - q = 2.*PI*vectorLength(QC); - cos2t = (r1.qe.ki*r1.qe.ki + r1.qe.kf*r1.qe.kf - q*q)/ - (2. * ABS(r1.qe.ki) * ABS(r1.qe.kf)); - if(ABS(cos2t) > 1.){ - killVector(QC); - return TRIANGLENOTCLOSED; - } - r2->angles.sample_two_theta = ss*Acosd(cos2t); - theta = calcTheta(r1.qe.ki,r1.qe.kf,r2->angles.sample_two_theta); - r2->angles.a3 = om + theta; - r2->angles.a3 -= 180.; - if(r2->angles.a3 < -180.){ - r2->angles.a3 += 360.; - } - mat_free(QC); - - return 1; -} -/*------------------------------------------------------------------*/ -int calcTwoTheta(MATRIX B, tasQEPosition ref, int ss, double *value){ - MATRIX QC; - double cos2t, q; - - QC = tasReflectionToHC(ref,B); - if(QC == NULL){ - return UBNOMEMORY; - } + theta = calcTheta(r1.qe.ki, r1.qe.kf, r1.angles.sample_two_theta); + om = r1.angles.a3 - theta; + om += tasAngleBetweenReflections(B, r1, *r2); - q = vectorLength(QC); - q = 2.*PI*vectorLength(QC); + QC = tasReflectionToHC(r2->qe, B); + if (QC == NULL) { + return UBNOMEMORY; + } + + q = vectorLength(QC); + q = 2. * PI * vectorLength(QC); + cos2t = (r1.qe.ki * r1.qe.ki + r1.qe.kf * r1.qe.kf - q * q) / + (2. * ABS(r1.qe.ki) * ABS(r1.qe.kf)); + if (ABS(cos2t) > 1.) { killVector(QC); - - cos2t = (ref.ki*ref.ki + ref.kf*ref.kf - q*q)/ - (2. * ABS(ref.ki) * ABS(ref.kf)); - if(ABS(cos2t) > 1.){ - return TRIANGLENOTCLOSED; - } - *value = ss*Acosd(cos2t); - - return 1; + return TRIANGLENOTCLOSED; + } + r2->angles.sample_two_theta = ss * Acosd(cos2t); + theta = calcTheta(r1.qe.ki, r1.qe.kf, r2->angles.sample_two_theta); + r2->angles.a3 = om + theta; + r2->angles.a3 -= 180.; + if (r2->angles.a3 < -180.) { + r2->angles.a3 += 360.; + } + mat_free(QC); + + return 1; } + +/*------------------------------------------------------------------*/ +int calcTwoTheta(MATRIX B, tasQEPosition ref, int ss, double *value) +{ + MATRIX QC; + double cos2t, q; + + QC = tasReflectionToHC(ref, B); + if (QC == NULL) { + return UBNOMEMORY; + } + + q = vectorLength(QC); + q = 2. * PI * vectorLength(QC); + killVector(QC); + + cos2t = (ref.ki * ref.ki + ref.kf * ref.kf - q * q) / + (2. * ABS(ref.ki) * ABS(ref.kf)); + if (ABS(cos2t) > 1.) { + return TRIANGLENOTCLOSED; + } + *value = ss * Acosd(cos2t); + + return 1; +} + /*-------------------------------------------------------------------*/ -MATRIX calcPlaneNormal(tasReflection r1, tasReflection r2){ +MATRIX calcPlaneNormal(tasReflection r1, tasReflection r2) +{ MATRIX u1 = NULL, u2 = NULL, planeNormal = NULL; int i; u1 = calcTasUVectorFromAngles(r1); u2 = calcTasUVectorFromAngles(r2); - if(u1 != NULL && u2 != NULL){ - planeNormal = vectorCrossProduct(u1,u2); + if (u1 != NULL && u2 != NULL) { + planeNormal = vectorCrossProduct(u1, u2); /* - The plane normal has to point to the stars and not to the earth - core in order for the algorithm to work. - */ - if(planeNormal[2][0] < .0){ - for(i = 0; i < 3; i++){ - planeNormal[i][0] = -1.*planeNormal[i][0]; + The plane normal has to point to the stars and not to the earth + core in order for the algorithm to work. + */ + if (planeNormal[2][0] < .0) { + for (i = 0; i < 3; i++) { + planeNormal[i][0] = -1. * planeNormal[i][0]; } } mat_free(u1); @@ -295,10 +329,12 @@ MATRIX calcPlaneNormal(tasReflection r1, tasReflection r2){ return NULL; } } + /*--------------------------------------------------------------------*/ MATRIX calcTasUBFromTwoReflections(lattice cell, tasReflection r1, - tasReflection r2, int *errorCode){ - MATRIX B, HT, UT, U, UB, HTT ; + tasReflection r2, int *errorCode) +{ + MATRIX B, HT, UT, U, UB, HTT; MATRIX u1, u2, h1, h2, planeNormal; double ud[3]; int status; @@ -306,23 +342,23 @@ MATRIX calcTasUBFromTwoReflections(lattice cell, tasReflection r1, *errorCode = 1; /* - calculate the B matrix and the HT matrix - */ - B = mat_creat(3,3,ZERO_MATRIX); - status = calculateBMatrix(cell,B); - if(status < 0){ + calculate the B matrix and the HT matrix + */ + B = mat_creat(3, 3, ZERO_MATRIX); + status = calculateBMatrix(cell, B); + if (status < 0) { *errorCode = status; return NULL; } - h1 = tasReflectionToHC(r1.qe,B); - h2 = tasReflectionToHC(r2.qe,B); - if(h1 == NULL || h2 == NULL){ + h1 = tasReflectionToHC(r1.qe, B); + h2 = tasReflectionToHC(r2.qe, B); + if (h1 == NULL || h2 == NULL) { *errorCode = UBNOMEMORY; mat_free(B); return NULL; } - HT = matFromTwoVectors(h1,h2); - if(HT == NULL){ + HT = matFromTwoVectors(h1, h2); + if (HT == NULL) { *errorCode = UBNOMEMORY; mat_free(B); mat_free(h1); @@ -331,19 +367,19 @@ MATRIX calcTasUBFromTwoReflections(lattice cell, tasReflection r1, } /* - calculate U vectors and UT matrix - */ + calculate U vectors and UT matrix + */ u1 = calcTasUVectorFromAngles(r1); u2 = calcTasUVectorFromAngles(r2); - if(u1 == NULL || u2 == NULL){ + if (u1 == NULL || u2 == NULL) { *errorCode = UBNOMEMORY; mat_free(B); mat_free(h1); mat_free(h2); return NULL; } - UT = matFromTwoVectors(u1,u2); - if(UT == NULL){ + UT = matFromTwoVectors(u1, u2); + if (UT == NULL) { *errorCode = UBNOMEMORY; mat_free(B); mat_free(h1); @@ -355,10 +391,10 @@ MATRIX calcTasUBFromTwoReflections(lattice cell, tasReflection r1, } /* - UT = U * HT - */ + UT = U * HT + */ HTT = mat_tran(HT); - if(HTT == NULL){ + if (HTT == NULL) { *errorCode = UBNOMEMORY; mat_free(B); mat_free(h1); @@ -368,9 +404,9 @@ MATRIX calcTasUBFromTwoReflections(lattice cell, tasReflection r1, mat_free(HT); return NULL; } - U = mat_mul(UT,HTT); - if(U == NULL){ - *errorCode = UBNOMEMORY; + U = mat_mul(UT, HTT); + if (U == NULL) { + *errorCode = UBNOMEMORY; mat_free(B); mat_free(h1); mat_free(h2); @@ -380,8 +416,8 @@ MATRIX calcTasUBFromTwoReflections(lattice cell, tasReflection r1, mat_free(HTT); return NULL; } - UB = mat_mul(U,B); - if(UB == NULL){ + UB = mat_mul(U, B); + if (UB == NULL) { mat_free(B); mat_free(h1); mat_free(h2); @@ -394,8 +430,8 @@ MATRIX calcTasUBFromTwoReflections(lattice cell, tasReflection r1, } /* - clean up - */ + clean up + */ killVector(h1); killVector(h2); mat_free(HT); @@ -403,30 +439,32 @@ MATRIX calcTasUBFromTwoReflections(lattice cell, tasReflection r1, killVector(u1); killVector(u2); - mat_free(UT); + mat_free(UT); mat_free(U); mat_free(B); return UB; } + /*-----------------------------------------------------------------------------*/ -static MATRIX buildTVMatrix(MATRIX U1V, MATRIX U2V){ +static MATRIX buildTVMatrix(MATRIX U1V, MATRIX U2V) +{ MATRIX T, T3V; int i; normalizeVector(U2V); - T3V = vectorCrossProduct(U1V,U2V); + T3V = vectorCrossProduct(U1V, U2V); normalizeVector(T3V); - if(T3V == NULL){ + if (T3V == NULL) { return NULL; } - T = mat_creat(3,3,ZERO_MATRIX); - if(T == NULL){ + T = mat_creat(3, 3, ZERO_MATRIX); + if (T == NULL) { killVector(T3V); return NULL; } - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { T[i][0] = U1V[i][0]; T[i][1] = U2V[i][0]; T[i][2] = T3V[i][0]; @@ -434,35 +472,37 @@ static MATRIX buildTVMatrix(MATRIX U1V, MATRIX U2V){ killVector(T3V); return T; } + /*----------------------------------------------------------------------------*/ static MATRIX buildRMatrix(MATRIX UB, MATRIX planeNormal, - tasQEPosition qe, int *errorCode){ + tasQEPosition qe, int *errorCode) +{ MATRIX U1V, U2V, TV, TVINV, M; - - + + *errorCode = 1; - U1V = tasReflectionToQC(qe,UB); - if(U1V == NULL){ + U1V = tasReflectionToQC(qe, UB); + if (U1V == NULL) { *errorCode = UBNOMEMORY; return NULL; } normalizeVector(U1V); - U2V = vectorCrossProduct(planeNormal,U1V); - if(U2V == NULL){ + U2V = vectorCrossProduct(planeNormal, U1V); + if (U2V == NULL) { killVector(U1V); *errorCode = UBNOMEMORY; return NULL; } - if(vectorLength(U2V) < .0001){ + if (vectorLength(U2V) < .0001) { *errorCode = BADUBORQ; killVector(U1V); killVector(U2V); return NULL; } - TV = buildTVMatrix(U1V,U2V); - if(TV == NULL){ + TV = buildTVMatrix(U1V, U2V); + if (TV == NULL) { killVector(U1V); killVector(U2V); *errorCode = UBNOMEMORY; @@ -470,7 +510,7 @@ static MATRIX buildRMatrix(MATRIX UB, MATRIX planeNormal, } TVINV = mat_inv(TV); - if(TVINV == NULL){ + if (TVINV == NULL) { *errorCode = BADUBORQ; } @@ -479,68 +519,72 @@ static MATRIX buildRMatrix(MATRIX UB, MATRIX planeNormal, mat_free(TV); return TVINV; } + /*-------------------------------------------------------------------------------*/ -int calcTasQAngles(MATRIX UB, MATRIX planeNormal, int ss, tasQEPosition qe, - ptasAngles angles){ +int calcTasQAngles(MATRIX UB, MATRIX planeNormal, int ss, tasQEPosition qe, + ptasAngles angles) +{ MATRIX R, QC; double om, q, theta, cos2t; int errorCode = 1; R = buildRMatrix(UB, planeNormal, qe, &errorCode); - if(R == NULL){ + if (R == NULL) { return errorCode; } - + angles->sgl = Asind(-R[2][0]); - if(ABS(angles->sgl -90.) < .5){ - mat_free(R); + if (ABS(angles->sgl - 90.) < .5) { + mat_free(R); return BADUBORQ; } /* - Now, this is slightly different then in the publication by M. Lumsden. - The reason is that the atan2 helps to determine the sign of om - whereas the sin, cos formula given by M. Lumsden yield ambiguous signs - especially for om. - sgu = atan(R[2][1],R[2][2]) where: - R[2][1] = cos(sgl)sin(sgu) - R[2][2] = cos(sgu)cos(sgl) - om = atan(R[1][0],R[0][0]) where: - R[1][0] = sin(om)cos(sgl) - R[0][0] = cos(om)cos(sgl) - The definitions of th R components are taken from M. Lumsden - R-matrix definition. - */ + Now, this is slightly different then in the publication by M. Lumsden. + The reason is that the atan2 helps to determine the sign of om + whereas the sin, cos formula given by M. Lumsden yield ambiguous signs + especially for om. + sgu = atan(R[2][1],R[2][2]) where: + R[2][1] = cos(sgl)sin(sgu) + R[2][2] = cos(sgu)cos(sgl) + om = atan(R[1][0],R[0][0]) where: + R[1][0] = sin(om)cos(sgl) + R[0][0] = cos(om)cos(sgl) + The definitions of th R components are taken from M. Lumsden + R-matrix definition. + */ - om = Atan2d(R[1][0],R[0][0]); - angles->sgu = Atan2d(R[2][1],R[2][2]); + om = Atan2d(R[1][0], R[0][0]); + angles->sgu = Atan2d(R[2][1], R[2][2]); - QC = tasReflectionToQC(qe,UB); - if(QC == NULL){ - mat_free(R); + QC = tasReflectionToQC(qe, UB); + if (QC == NULL) { + mat_free(R); return UBNOMEMORY; } q = vectorLength(QC); - q = 2.*PI*vectorLength(QC); - cos2t = (qe.ki*qe.ki + qe.kf*qe.kf - q*q)/(2. * ABS(qe.ki) * ABS(qe.kf)); - if(ABS(cos2t) > 1.){ - mat_free(R); - killVector(QC); + q = 2. * PI * vectorLength(QC); + cos2t = + (qe.ki * qe.ki + qe.kf * qe.kf - + q * q) / (2. * ABS(qe.ki) * ABS(qe.kf)); + if (ABS(cos2t) > 1.) { + mat_free(R); + killVector(QC); return TRIANGLENOTCLOSED; } - angles->sample_two_theta = ss*Acosd(cos2t); - - theta = calcTheta(qe.ki, qe.kf,angles->sample_two_theta); - + angles->sample_two_theta = ss * Acosd(cos2t); + + theta = calcTheta(qe.ki, qe.kf, angles->sample_two_theta); + angles->a3 = om + theta; /* - put a3 into -180, 180 properly. We can always turn by 180 because the - scattering geometry is symmetric in this respect. It is like looking at - the scattering plane from the other side - */ + put a3 into -180, 180 properly. We can always turn by 180 because the + scattering geometry is symmetric in this respect. It is like looking at + the scattering plane from the other side + */ angles->a3 -= 180.; - if(angles->a3 < -180.){ + if (angles->a3 < -180.) { angles->a3 += 360.; } @@ -549,8 +593,10 @@ int calcTasQAngles(MATRIX UB, MATRIX planeNormal, int ss, tasQEPosition qe, return 1; } + /*------------------------------------------------------------------------*/ -int calcTasQH(MATRIX UB, tasAngles angles, ptasQEPosition qe){ +int calcTasQH(MATRIX UB, tasAngles angles, ptasQEPosition qe) +{ MATRIX UBINV = NULL, QV = NULL, Q = NULL; double q; tasReflection r; @@ -560,25 +606,25 @@ int calcTasQH(MATRIX UB, tasAngles angles, ptasQEPosition qe){ r.angles = angles; r.qe = *qe; QV = calcTasUVectorFromAngles(r); - if(UBINV == NULL || QV == NULL){ + if (UBINV == NULL || QV == NULL) { return UBNOMEMORY; } /* - normalize the QV vector to be the length of the Q vector - Thereby take into account the physicists magic fudge - 2PI factor - */ - q = sqrt(qe->ki*qe->ki + qe->kf*qe->kf - - 2.*qe->ki*qe->kf*Cosd(angles.sample_two_theta)); + normalize the QV vector to be the length of the Q vector + Thereby take into account the physicists magic fudge + 2PI factor + */ + q = sqrt(qe->ki * qe->ki + qe->kf * qe->kf - + 2. * qe->ki * qe->kf * Cosd(angles.sample_two_theta)); qe->qm = q; q /= 2. * PI; - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { QV[i][0] *= q; } - Q = mat_mul(UBINV,QV); - if(Q == NULL){ + Q = mat_mul(UBINV, QV); + if (Q == NULL) { mat_free(UBINV); killVector(QV); return UBNOMEMORY; @@ -593,118 +639,132 @@ int calcTasQH(MATRIX UB, tasAngles angles, ptasQEPosition qe){ return 1; } + /*---------------------------------------------------------------------*/ int calcAllTasAngles(ptasMachine machine, tasQEPosition qe, - ptasAngles angles){ + ptasAngles angles) +{ int status; tasReflection r; - status = maCalcTwoTheta(machine->monochromator,qe.ki, - &angles->monochromator_two_theta); - if(status != 1){ + status = maCalcTwoTheta(machine->monochromator, qe.ki, + &angles->monochromator_two_theta); + if (status != 1) { return status; } - status = maCalcTwoTheta(machine->analyzer,qe.kf,& - angles->analyzer_two_theta); - if(status != 1){ + status = + maCalcTwoTheta(machine->analyzer, qe.kf, + &angles->analyzer_two_theta); + if (status != 1) { return status; } status = calcTasQAngles(machine->UB, machine->planeNormal, - machine->ss_sample, qe,angles); - if(status != 1){ + machine->ss_sample, qe, angles); + if (status != 1) { return status; } return 1; } + /*----------------------------------------------------------------------*/ int calcTasQEPosition(ptasMachine machine, tasAngles angles, - ptasQEPosition qe){ + ptasQEPosition qe) +{ int status; - qe->ki = maCalcK(machine->monochromator,angles.monochromator_two_theta); - qe->kf = maCalcK(machine->analyzer,angles.analyzer_two_theta); + qe->ki = maCalcK(machine->monochromator, angles.monochromator_two_theta); + qe->kf = maCalcK(machine->analyzer, angles.analyzer_two_theta); - status = calcTasQH(machine->UB,angles,qe); - if(status != 1){ + status = calcTasQH(machine->UB, angles, qe); + if (status != 1) { return status; } return 1; } + /*================== POWDER Implementation ===========================*/ int calcTasPowderAngles(ptasMachine machine, tasQEPosition qe, - ptasAngles angles){ + ptasAngles angles) +{ double cos2t; int status; tasReflection r; - status = maCalcTwoTheta(machine->monochromator,qe.ki, - &angles->monochromator_two_theta); - if(status != 1){ + status = maCalcTwoTheta(machine->monochromator, qe.ki, + &angles->monochromator_two_theta); + if (status != 1) { return status; } - cos2t = (qe.ki*qe.ki + qe.kf*qe.kf - qe.qm*qe.qm)/(2. * ABS(qe.ki) * ABS(qe.kf)); - if(cos2t > 1.){ + cos2t = + (qe.ki * qe.ki + qe.kf * qe.kf - + qe.qm * qe.qm) / (2. * ABS(qe.ki) * ABS(qe.kf)); + if (cos2t > 1.) { return TRIANGLENOTCLOSED; } - angles->sample_two_theta = machine->ss_sample*Acosd(cos2t); - + angles->sample_two_theta = machine->ss_sample * Acosd(cos2t); - status = maCalcTwoTheta(machine->analyzer,qe.kf,& - angles->analyzer_two_theta); - if(status != 1){ + + status = + maCalcTwoTheta(machine->analyzer, qe.kf, + &angles->analyzer_two_theta); + if (status != 1) { return status; } return 1; } + /*---------------------------------------------------------------------*/ -int calcTasPowderPosition(ptasMachine machine, tasAngles angles, - ptasQEPosition qe){ - +int calcTasPowderPosition(ptasMachine machine, tasAngles angles, + ptasQEPosition qe) +{ + int status; - qe->ki = maCalcK(machine->monochromator,angles.monochromator_two_theta); - qe->kf = maCalcK(machine->analyzer,angles.analyzer_two_theta); + qe->ki = maCalcK(machine->monochromator, angles.monochromator_two_theta); + qe->kf = maCalcK(machine->analyzer, angles.analyzer_two_theta); - qe->qm = sqrt(qe->ki*qe->ki + qe->kf*qe->kf - - 2.*qe->ki*qe->kf*Cosd(angles.sample_two_theta)); + qe->qm = sqrt(qe->ki * qe->ki + qe->kf * qe->kf - + 2. * qe->ki * qe->kf * Cosd(angles.sample_two_theta)); return 1; } + /*====================== Logic implementation =========================*/ -void setTasPar(ptasQEPosition qe, int tasMode, int tasVar, double value){ +void setTasPar(ptasQEPosition qe, int tasMode, int tasVar, double value) +{ double et; assert(tasMode == KICONST || tasMode == KFCONST || tasMode == ELASTIC); - switch(tasVar){ + switch (tasVar) { case KF: - if(tasMode == ELASTIC){ - qe->kf = qe->ki; - } else { - qe->kf = value; - } + if (tasMode == ELASTIC) { + qe->kf = qe->ki; + } else { + qe->kf = value; + } break; case EF: - if(tasMode == ELASTIC){ - qe->kf = qe->ki; - }else { - qe->kf = energyToK(value); - } + if (tasMode == ELASTIC) { + qe->kf = qe->ki; + } else { + qe->kf = energyToK(value); + } break; case KI: qe->ki = value; - if(tasMode == ELASTIC){ - qe->kf = value; + if (tasMode == ELASTIC) { + qe->kf = value; } break; case EI: qe->ki = energyToK(value); - if(tasMode == ELASTIC){ - qe->kf = qe->ki; + if (tasMode == ELASTIC) { + qe->kf = qe->ki; } break; case QH: @@ -717,14 +777,14 @@ void setTasPar(ptasQEPosition qe, int tasMode, int tasVar, double value){ qe->ql = value; break; case EN: - if(tasMode == KICONST){ + if (tasMode == KICONST) { et = KtoEnergy(qe->ki) - value; qe->kf = energyToK(et); - } else if(tasMode == KFCONST){ + } else if (tasMode == KFCONST) { et = KtoEnergy(qe->kf) + value; qe->ki = energyToK(et); - }else if(tasMode == ELASTIC){ - qe->kf = qe->ki; + } else if (tasMode == ELASTIC) { + qe->kf = qe->ki; } else { assert(0); } @@ -735,11 +795,13 @@ void setTasPar(ptasQEPosition qe, int tasMode, int tasVar, double value){ default: assert(0); break; - } + } } + /*-------------------------------------------------------------------------*/ -double getTasPar(tasQEPosition qe, int tasVar){ - switch(tasVar){ +double getTasPar(tasQEPosition qe, int tasVar) +{ + switch (tasVar) { case EI: return KtoEnergy(qe.ki); break; @@ -771,44 +833,48 @@ double getTasPar(tasQEPosition qe, int tasVar){ assert(0); } } -/*-------------------------------------------------------------------------*/ -int isInPlane(MATRIX planeNormal, tasQEPosition qe){ - MATRIX v = NULL; - double val; - - v = makeVector(); - v[0][0] = qe.qh; - v[1][0] = qe.qk; - v[2][0] = qe.ql; - val = vectorDotProduct(planeNormal,v); - mat_free(v); - if(ABS(val) > INPLANEPREC){ - return 0; - } else { - return 1; - } -} -/*--------------------------------------------------------------------*/ -MATRIX calcScatteringPlaneNormal(tasQEPosition qe1, tasQEPosition qe2){ - MATRIX v1 = NULL, v2 = NULL, planeNormal; - - v1 = makeVector(); - v2 = makeVector(); - if(v1 != NULL && v2 != NULL){ - v1[0][0] = qe1.qh; - v1[1][0] = qe1.qk; - v1[2][0] = qe1.ql; - v2[0][0] = qe2.qh; - v2[1][0] = qe2.qk; - v2[2][0] = qe2.ql; - - planeNormal = vectorCrossProduct(v1,v2); - normalizeVector(planeNormal); - mat_free(v1); - mat_free(v2); - return planeNormal; - } else { - return NULL; - } +/*-------------------------------------------------------------------------*/ +int isInPlane(MATRIX planeNormal, tasQEPosition qe) +{ + MATRIX v = NULL; + double val; + + v = makeVector(); + v[0][0] = qe.qh; + v[1][0] = qe.qk; + v[2][0] = qe.ql; + val = vectorDotProduct(planeNormal, v); + mat_free(v); + if (ABS(val) > INPLANEPREC) { + return 0; + } else { + return 1; + } +} + +/*--------------------------------------------------------------------*/ +MATRIX calcScatteringPlaneNormal(tasQEPosition qe1, tasQEPosition qe2) +{ + MATRIX v1 = NULL, v2 = NULL, planeNormal; + + v1 = makeVector(); + v2 = makeVector(); + if (v1 != NULL && v2 != NULL) { + v1[0][0] = qe1.qh; + v1[1][0] = qe1.qk; + v1[2][0] = qe1.ql; + + v2[0][0] = qe2.qh; + v2[1][0] = qe2.qk; + v2[2][0] = qe2.ql; + + planeNormal = vectorCrossProduct(v1, v2); + normalizeVector(planeNormal); + mat_free(v1); + mat_free(v2); + return planeNormal; + } else { + return NULL; + } } diff --git a/tasublib.h b/tasublib.h index d41c9987..954ec1b3 100644 --- a/tasublib.h +++ b/tasublib.h @@ -13,7 +13,7 @@ #include "matrix/matrix.h" /*================= error codes =====================================*/ #define ENERGYTOBIG -700 -#define BADSYNC -701 /* mono/analyzer out of sync: 2*theta != two_theta*/ +#define BADSYNC -701 /* mono/analyzer out of sync: 2*theta != two_theta */ #define UBNOMEMORY -200 #define TRIANGLENOTCLOSED -703 #define BADRMATRIX -704 @@ -21,7 +21,7 @@ /*========================== defines for tasMode ====================*/ #define KICONST 1 #define KFCONST 2 -#define ELASTIC 3 +#define ELASTIC 3 /* * in elastic mode A5, A5 will be disregarded and ki = kf at all times */ @@ -40,10 +40,10 @@ * data structure describing a monochromator or analyzer crystal */ typedef struct { - double dd; /* lattice spacing */ - int ss; /* scattering sense */ - double HB1, HB2; /* horizontal curvature parameters */ - double VB1, VB2; /* vertical curvature parameters */ + double dd; /* lattice spacing */ + int ss; /* scattering sense */ + double HB1, HB2; /* horizontal curvature parameters */ + double VB1, VB2; /* vertical curvature parameters */ } maCrystal, *pmaCrystal; /** * the machine parameters of a triple axis spectrometer @@ -51,17 +51,17 @@ typedef struct { typedef struct { maCrystal monochromator, analyzer; MATRIX UB; - MATRIX planeNormal; - int ss_sample; /* scattering sense sample */ -}tasMachine, *ptasMachine; + MATRIX planeNormal; + int ss_sample; /* scattering sense sample */ +} tasMachine, *ptasMachine; /** * a position in Q - Energy space - */ + */ typedef struct { double ki, kf; - double qh,qk,ql; + double qh, qk, ql; double qm; -}tasQEPosition, *ptasQEPosition; +} tasQEPosition, *ptasQEPosition; /** * A triple axis angle position */ @@ -72,14 +72,14 @@ typedef struct { double sgl; double sgu; double analyzer_two_theta; -}tasAngles, *ptasAngles; +} tasAngles, *ptasAngles; /** * a full triple axis reflection */ typedef struct { tasQEPosition qe; tasAngles angles; -}tasReflection, *ptasReflection; +} tasReflection, *ptasReflection; /*================= Monochromator/Analyzer stuff =====================*/ /** * convert an energy in meV to Ki, Kf type values @@ -92,7 +92,7 @@ double energyToK(double energy); * @param input K value * @return output energy in meV */ -double KtoEnergy(double k); +double KtoEnergy(double k); /*----------------------------------------------------------------------*/ /** * calculate two_theta for k @@ -135,8 +135,8 @@ double maCalcK(maCrystal data, double two_theta); * @param ss The scattering sense at the sample * @return 1 on success, a negative error code on failure. */ -int makeAuxReflection(MATRIX B, tasReflection r1, - tasReflection *r2, int ss); +int makeAuxReflection(MATRIX B, tasReflection r1, + tasReflection * r2, int ss); /** * calculate the scattering vector * @param r The reflection for which to calculate the scattering vector. @@ -162,9 +162,9 @@ int calcTwoTheta(MATRIX B, tasQEPosition ref, int ss, double *twoTheta); * when an error occurs. * @return a UB matix on sucess, or NULL on failure. Then errorCode * can be inspected what caused the problem. - */ + */ MATRIX calcTasUBFromTwoReflections(lattice cell, tasReflection r1, - tasReflection r2, int *errorCode); + tasReflection r2, int *errorCode); /** * calcluate the normal to the plane describe by the two reflections r1, r2 * @param r1 first reflection @@ -181,10 +181,9 @@ MATRIX calcPlaneNormal(tasReflection r1, tasReflection r2); * @param qe The desired Q Energy position * @param angles The resulting angles. * @return 1 on success, a negative error code when errors are encountered - */ -int calcTasQAngles(MATRIX UB, MATRIX planeNormal, - int ss, tasQEPosition qe, - ptasAngles angles); + */ +int calcTasQAngles(MATRIX UB, MATRIX planeNormal, + int ss, tasQEPosition qe, ptasAngles angles); /** * calculate QH, QK, QL from the angles given * @param UB The UB matrix to use @@ -202,7 +201,7 @@ int calcTasQH(MATRIX UB, tasAngles angles, ptasQEPosition qe); * @return 1 on success, a negative error code in case of problems */ int calcAllTasAngles(ptasMachine machine, tasQEPosition qe, - ptasAngles angles); + ptasAngles angles); /** * calculate the current position of the spectrometer in Q-E space from * angles. @@ -212,7 +211,7 @@ int calcAllTasAngles(ptasMachine machine, tasQEPosition qe, * @return 1 on success, a negative error code on errors. */ int calcTasQEPosition(ptasMachine machine, tasAngles angles, - ptasQEPosition qe); + ptasQEPosition qe); /*======================== POWDER MODE ================================= Powder mode is driving only QM, A3, SGGU, SGL will not be touched, only energy and sample two theta will be driven. @@ -225,7 +224,7 @@ int calcTasQEPosition(ptasMachine machine, tasAngles angles, * @return 1 on success, a negative error code else */ int calcTasPowderAngles(ptasMachine machine, tasQEPosition qe, - ptasAngles angles); + ptasAngles angles); /** * calculate the current energy qm position from angles. * @param machine The spectrometer parameters. @@ -233,8 +232,8 @@ int calcTasPowderAngles(ptasMachine machine, tasQEPosition qe, * @param qe The resulting qe position * @return 1 on success, a negative error code on errors */ -int calcTasPowderPosition(ptasMachine machine, tasAngles angles, - ptasQEPosition qe); +int calcTasPowderPosition(ptasMachine machine, tasAngles angles, + ptasQEPosition qe); /*======================= TAS Logic =====================================*/ /** * set triple axis parameters, thereby taking the tasMode into account @@ -243,7 +242,7 @@ int calcTasPowderPosition(ptasMachine machine, tasAngles angles, * @param tasVar The TAS variable to handle. This MUST be one of the * defines at the top of this file. * @param value The value to set for tasPar - */ + */ void setTasPar(ptasQEPosition qe, int tasMode, int tasVar, double value); /** * calculates the value of a TAS parameter from qe. @@ -260,7 +259,7 @@ double getTasPar(tasQEPosition qe, int tasVar); * @param qe The QE position to check * @return 0 when not in plane,1 when in plane */ -int isInPlane(MATRIX scatteringPlaneNormal, tasQEPosition qe); +int isInPlane(MATRIX scatteringPlaneNormal, tasQEPosition qe); /** * calculate the normal of the scattering plane from two reflections * @param qe1 QE Position of first reflection in scattering plane @@ -268,5 +267,5 @@ int isInPlane(MATRIX scatteringPlaneNormal, tasQEPosition qe); * @return The scattering plane normal */ MATRIX calcScatteringPlaneNormal(tasQEPosition qe1, tasQEPosition qe2); - + #endif diff --git a/tcldrivable.c b/tcldrivable.c index 0b91c1f2..460fee9c 100644 --- a/tcldrivable.c +++ b/tcldrivable.c @@ -24,86 +24,93 @@ static int tclDrivableDictionary = -1; /*======================================================================= The structure used for keeping data associated with this scheme --------------------------------------------------------------------------*/ -typedef struct{ - void *objectPointer; - char *tclName; - char *tclHalt; - char *tclCheckLimits; - char *tclSetValue; - char *tclCheckStatus; - char *tclGetValue; - }TclDrivable, *pTclDrivable; +typedef struct { + void *objectPointer; + char *tclName; + char *tclHalt; + char *tclCheckLimits; + char *tclSetValue; + char *tclCheckStatus; + char *tclGetValue; +} TclDrivable, *pTclDrivable; /*========================================================================= book keeping and search functions for the dictionary -------------------------------------------------------------------------*/ -static void clearTclDrivable(pTclDrivable pNew){ - memset(pNew,0,sizeof(TclDrivable)); +static void clearTclDrivable(pTclDrivable pNew) +{ + memset(pNew, 0, sizeof(TclDrivable)); } + /*-----------------------------------------------------------------------*/ -static void deleteTclDrivable(pTclDrivable target){ - if(target->tclName != NULL){ +static void deleteTclDrivable(pTclDrivable target) +{ + if (target->tclName != NULL) { free(target->tclName); } - if(target->tclHalt != NULL){ + if (target->tclHalt != NULL) { free(target->tclHalt); } - if(target->tclCheckLimits != NULL){ + if (target->tclCheckLimits != NULL) { free(target->tclCheckLimits); } - if(target->tclSetValue != NULL){ + if (target->tclSetValue != NULL) { free(target->tclSetValue); } - if(target->tclCheckStatus != NULL){ + if (target->tclCheckStatus != NULL) { free(target->tclCheckStatus); } - if(target->tclGetValue != NULL){ + if (target->tclGetValue != NULL) { free(target->tclGetValue); } } + /*-------------- compare function for lld to find key in list Function must return 0 if found --------*/ -static int tclDrivableCompare(const void *p1, const void *p2){ +static int tclDrivableCompare(const void *p1, const void *p2) +{ pTclDrivable pt1, pt2; - pt1 = (pTclDrivable)p1; - pt2 = (pTclDrivable)p2; + pt1 = (pTclDrivable) p1; + pt2 = (pTclDrivable) p2; - if(pt1->objectPointer == pt2->objectPointer){ + if (pt1->objectPointer == pt2->objectPointer) { return 0; } return 1; } + /*--------------- assignFunction --------------------------------------*/ -static void assignFunction(pTclDrivable self, int functionIndex, - char *script){ - switch(functionIndex){ +static void assignFunction(pTclDrivable self, int functionIndex, + char *script) +{ + switch (functionIndex) { case TCLHALT: - if(self->tclHalt != NULL){ + if (self->tclHalt != NULL) { free(self->tclHalt); } self->tclHalt = strdup(script); break; case TCLCHECK: - if(self->tclCheckLimits != NULL){ + if (self->tclCheckLimits != NULL) { free(self->tclCheckLimits); } self->tclCheckLimits = strdup(script); break; case TCLSET: - if(self->tclSetValue != NULL){ + if (self->tclSetValue != NULL) { free(self->tclSetValue); } self->tclSetValue = strdup(script); break; case TCLSTATUS: - if(self->tclCheckStatus != NULL){ + if (self->tclCheckStatus != NULL) { free(self->tclCheckStatus); } self->tclCheckStatus = strdup(script); break; case TCLGET: - if(self->tclGetValue != NULL){ + if (self->tclGetValue != NULL) { free(self->tclGetValue); } self->tclGetValue = strdup(script); @@ -112,83 +119,86 @@ static void assignFunction(pTclDrivable self, int functionIndex, assert(0); } } + /*-----------------------------------------------------------------------*/ -static int registerTclDrivableFunction(void *objectPointer, - int functionIndex, - char *script, - char *tclName){ +static int registerTclDrivableFunction(void *objectPointer, + int functionIndex, + char *script, char *tclName) +{ TclDrivable entry; /* - if no list: create it - */ - if(tclDrivableDictionary < 0){ + if no list: create it + */ + if (tclDrivableDictionary < 0) { tclDrivableDictionary = LLDcreate(sizeof(TclDrivable)); } /* - find entry, or create a new one if it does not exist - */ + find entry, or create a new one if it does not exist + */ LLDnodePtr2First(tclDrivableDictionary); entry.objectPointer = objectPointer; - if(LLDnodeFind(tclDrivableDictionary,tclDrivableCompare, - &entry) == 0){ - LLDnodeDataTo(tclDrivableDictionary,&entry); - if(strcmp(tclName,entry.tclName) != 0){ + if (LLDnodeFind(tclDrivableDictionary, tclDrivableCompare, &entry) == 0) { + LLDnodeDataTo(tclDrivableDictionary, &entry); + if (strcmp(tclName, entry.tclName) != 0) { return 0; } - assignFunction(&entry,functionIndex,script); - LLDnodeDataFrom(tclDrivableDictionary,&entry); + assignFunction(&entry, functionIndex, script); + LLDnodeDataFrom(tclDrivableDictionary, &entry); } else { clearTclDrivable(&entry); entry.objectPointer = objectPointer; entry.tclName = strdup(tclName); - assignFunction(&entry,functionIndex,script); - LLDnodeAppendFrom(tclDrivableDictionary,&entry); + assignFunction(&entry, functionIndex, script); + LLDnodeAppendFrom(tclDrivableDictionary, &entry); } return 1; } + /*-----------------------------------------------------------------*/ -static char *combine(char *t1, char *t2){ +static char *combine(char *t1, char *t2) +{ char *result = NULL; int len; - + len = strlen(t1) + strlen(t2) + 3; - result = (char *)malloc(len*sizeof(char)); - if(!result){ + result = (char *) malloc(len * sizeof(char)); + if (!result) { return NULL; } - memset(result,0,len); - strcpy(result,t1); - strcat(result," "); - strcat(result,t2); + memset(result, 0, len); + strcpy(result, t1); + strcat(result, " "); + strcat(result, t2); return result; } + /*------------------------------------------------------------------*/ -static char *getTclDrivableCommand(void *objectPointer, - int functionIndex){ +static char *getTclDrivableCommand(void *objectPointer, int functionIndex) +{ TclDrivable entry; assert(tclDrivableDictionary > 0); LLDnodePtr2First(tclDrivableDictionary); entry.objectPointer = objectPointer; - if(LLDnodeFind(tclDrivableDictionary,tclDrivableCompare,&entry) == 0){ - LLDnodeDataTo(tclDrivableDictionary,&entry); - switch(functionIndex){ + if (LLDnodeFind(tclDrivableDictionary, tclDrivableCompare, &entry) == 0) { + LLDnodeDataTo(tclDrivableDictionary, &entry); + switch (functionIndex) { case TCLHALT: - return combine(entry.tclHalt,entry.tclName); + return combine(entry.tclHalt, entry.tclName); break; case TCLCHECK: - return combine(entry.tclCheckLimits,entry.tclName); + return combine(entry.tclCheckLimits, entry.tclName); break; case TCLSET: - return combine(entry.tclSetValue,entry.tclName); + return combine(entry.tclSetValue, entry.tclName); break; case TCLSTATUS: - return combine(entry.tclCheckStatus,entry.tclName); + return combine(entry.tclCheckStatus, entry.tclName); break; case TCLGET: - return combine(entry.tclGetValue,entry.tclName); + return combine(entry.tclGetValue, entry.tclName); break; default: assert(0); @@ -197,15 +207,17 @@ static char *getTclDrivableCommand(void *objectPointer, return NULL; } } + /*---------------------------------------------------------------------------*/ -void killTclDrivable(){ +void killTclDrivable() +{ TclDrivable entry; int stat; - if(tclDrivableDictionary > 0){ + if (tclDrivableDictionary > 0) { stat = LLDnodePtr2First(tclDrivableDictionary); - while(stat != 0){ - LLDnodeDataTo(tclDrivableDictionary,&entry); + while (stat != 0) { + LLDnodeDataTo(tclDrivableDictionary, &entry); deleteTclDrivable(&entry); stat = LLDnodePtr2Next(tclDrivableDictionary); } @@ -213,55 +225,61 @@ void killTclDrivable(){ tclDrivableDictionary = -1; } } + /*--------------------------------------------------------------------------*/ -int mapDrivableFunctionNames(char *name){ - if(strcmp(name,"halt") == 0){ +int mapDrivableFunctionNames(char *name) +{ + if (strcmp(name, "halt") == 0) { return TCLHALT; } - if(strcmp(name,"checklimits") == 0){ + if (strcmp(name, "checklimits") == 0) { return TCLCHECK; } - if(strcmp(name,"setvalue") == 0){ + if (strcmp(name, "setvalue") == 0) { return TCLSET; } - if(strcmp(name,"checkstatus") == 0){ + if (strcmp(name, "checkstatus") == 0) { return TCLSTATUS; } - if(strcmp(name,"getvalue") == 0){ + if (strcmp(name, "getvalue") == 0) { return TCLGET; } return -1; } + /*=========================================================================== The functions with which to overload the original functions ----------------------------------------------------------------------------*/ -static int TclDrivableHalt(void *data){ +static int TclDrivableHalt(void *data) +{ char *command = NULL; Tcl_Interp *pTcl; int status; pTcl = InterpGetTcl(pServ->pSics); - command = getTclDrivableCommand(data,TCLHALT); - if(command != NULL){ - status = Tcl_Eval(pTcl,command); - if(status != TCL_OK){ - fprintf(stderr,"Tcl ERROR: while invoking %s\n\tTcl reported %s\n", - command,pTcl->result); - status = 0 ; + command = getTclDrivableCommand(data, TCLHALT); + if (command != NULL) { + status = Tcl_Eval(pTcl, command); + if (status != TCL_OK) { + fprintf(stderr, "Tcl ERROR: while invoking %s\n\tTcl reported %s\n", + command, pTcl->result); + status = 0; } else { status = 1; } free(command); } else { status = 0; - fprintf(stderr,"Tcl ERROR: trying to invoke non existent Tcl %s\n", - "drivable halt function"); + fprintf(stderr, "Tcl ERROR: trying to invoke non existent Tcl %s\n", + "drivable halt function"); } return status; } + /*--------------------------------------------------------------------*/ static int TclDrivableCheckLimits(void *data, float fVal, - char *error, int errlen){ + char *error, int errlen) +{ char *commandPart1 = NULL; char *command = NULL; char pNum[30]; @@ -269,33 +287,35 @@ static int TclDrivableCheckLimits(void *data, float fVal, int status; pTcl = InterpGetTcl(pServ->pSics); - commandPart1 = getTclDrivableCommand(data,TCLCHECK); - if(commandPart1 != NULL){ - sprintf(pNum,"%f",fVal); - command = combine(commandPart1,pNum); - if(command){ - status = Tcl_Eval(pTcl,command); - if(status != TCL_OK){ - strncpy(error,pTcl->result,errlen); - status = 0; + commandPart1 = getTclDrivableCommand(data, TCLCHECK); + if (commandPart1 != NULL) { + sprintf(pNum, "%f", fVal); + command = combine(commandPart1, pNum); + if (command) { + status = Tcl_Eval(pTcl, command); + if (status != TCL_OK) { + strncpy(error, pTcl->result, errlen); + status = 0; } else { - status = 1; + status = 1; } free(command); } else { - fprintf(stderr,"Out of memory creating drivable command\n"); + fprintf(stderr, "Out of memory creating drivable command\n"); status = 0; } free(commandPart1); } else { status = 0; - fprintf(stderr,"Tcl ERROR: trying to invoke non existent Tcl %s\n", - "drivable CheckLimits function"); + fprintf(stderr, "Tcl ERROR: trying to invoke non existent Tcl %s\n", + "drivable CheckLimits function"); } return status; } + /*--------------------------------------------------------------------------*/ -static long TclDrivableSetValue(void *data, SConnection *pCon, float fVal){ +static long TclDrivableSetValue(void *data, SConnection * pCon, float fVal) +{ Tcl_Interp *pTcl; int status; char *commandHead = NULL, *command = NULL; @@ -304,41 +324,44 @@ static long TclDrivableSetValue(void *data, SConnection *pCon, float fVal){ pTcl = InterpGetTcl(pServ->pSics); /* - build and check command string - */ - sprintf(pNum,"%f", fVal); - commandHead = getTclDrivableCommand(data,TCLSET); - if(commandHead == NULL){ + build and check command string + */ + sprintf(pNum, "%f", fVal); + commandHead = getTclDrivableCommand(data, TCLSET); + if (commandHead == NULL) { SCWrite(pCon, - "ERROR: trying to invoke non existent Tcl drivable function SetValue", - eError); + "ERROR: trying to invoke non existent Tcl drivable function SetValue", + eError); return HWFault; } - command = combine(commandHead,pNum); - if(command == NULL){ - SCWrite(pCon,"ERROR: out of memory creating tcl drivable SetValue command", - eError); + command = combine(commandHead, pNum); + if (command == NULL) { + SCWrite(pCon, + "ERROR: out of memory creating tcl drivable SetValue command", + eError); return HWFault; } /* - invoke - */ - status = Tcl_Eval(pTcl,command); + invoke + */ + status = Tcl_Eval(pTcl, command); free(command); free(commandHead); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: Tcl drivable SetValue reported",eError); - SCWrite(pCon,pTcl->result,eError); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: Tcl drivable SetValue reported", eError); + SCWrite(pCon, pTcl->result, eError); return HWFault; } status = atoi(pTcl->result); return status; } + /*--------------------------------------------------------------------------*/ -static int TclDrivableCheckStatus(void *data, SConnection *pCon){ +static int TclDrivableCheckStatus(void *data, SConnection * pCon) +{ Tcl_Interp *pTcl; int status; char *command = NULL; @@ -346,33 +369,33 @@ static int TclDrivableCheckStatus(void *data, SConnection *pCon){ pTcl = InterpGetTcl(pServ->pSics); /* - build and check command string - */ - command = getTclDrivableCommand(data,TCLSTATUS); - if(command == NULL){ - SCWrite(pCon, - "ERROR: Tcl drivable CheckStatus not found!", - eError); + build and check command string + */ + command = getTclDrivableCommand(data, TCLSTATUS); + if (command == NULL) { + SCWrite(pCon, "ERROR: Tcl drivable CheckStatus not found!", eError); return HWFault; } /* - invoke - */ - status = Tcl_Eval(pTcl,command); + invoke + */ + status = Tcl_Eval(pTcl, command); free(command); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: Tcl drivable CheckStatus reported",eError); - SCWrite(pCon,pTcl->result,eError); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: Tcl drivable CheckStatus reported", eError); + SCWrite(pCon, pTcl->result, eError); return HWFault; } status = atoi(pTcl->result); return status; } + /*--------------------------------------------------------------------------*/ -static float TclDrivableGetValue(void *data, SConnection *pCon){ +static float TclDrivableGetValue(void *data, SConnection * pCon) +{ Tcl_Interp *pTcl; int status; char *command = NULL; @@ -380,59 +403,59 @@ static float TclDrivableGetValue(void *data, SConnection *pCon){ pTcl = InterpGetTcl(pServ->pSics); /* - build and check command string - */ - command = getTclDrivableCommand(data,TCLGET); - if(command == NULL){ - SCWrite(pCon, - "ERROR: Tcl drivable GetValue not found!", - eError); + build and check command string + */ + command = getTclDrivableCommand(data, TCLGET); + if (command == NULL) { + SCWrite(pCon, "ERROR: Tcl drivable GetValue not found!", eError); return -999999.99; } /* - invoke - */ - status = Tcl_Eval(pTcl,command); + invoke + */ + status = Tcl_Eval(pTcl, command); free(command); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: Tcl drivable GetValue reported",eError); - SCWrite(pCon,pTcl->result,eError); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: Tcl drivable GetValue reported", eError); + SCWrite(pCon, pTcl->result, eError); return -99999.99; } return atof(pTcl->result); } + /*====================================================================== The function for doing it alltogether ------------------------------------------------------------------------*/ int replaceDrivableByTcl(void *commandData, int functionIndex, - char *script, char *tclName){ + char *script, char *tclName) +{ pIDrivable pDriv = NULL; int status; - pDriv = GetDrivableInterface(commandData); + pDriv = GetDrivableInterface(commandData); assert(pDriv != NULL); /* - register the new script - */ - status = registerTclDrivableFunction(commandData,functionIndex, - script,tclName); - if(status <= 0){ + register the new script + */ + status = registerTclDrivableFunction(commandData, functionIndex, + script, tclName); + if (status <= 0) { return status; } /* - replace the appropriate Drivable function - */ - switch(functionIndex){ + replace the appropriate Drivable function + */ + switch (functionIndex) { case TCLHALT: pDriv->Halt = TclDrivableHalt; break; case TCLCHECK: - pDriv->CheckLimits = TclDrivableCheckLimits; + pDriv->CheckLimits = TclDrivableCheckLimits; break; case TCLSET: pDriv->SetValue = TclDrivableSetValue; @@ -449,11 +472,13 @@ int replaceDrivableByTcl(void *commandData, int functionIndex, } return 1; } + /*========================================================================= Interpreter Interface ------------------------------------------------------------------------*/ -int TclReplaceDrivable(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ +int TclReplaceDrivable(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ pIDrivable pDriv = NULL; void *commandData; CommandList *pCom = NULL; @@ -461,62 +486,64 @@ int TclReplaceDrivable(SConnection *pCon, SicsInterp *pSics, char pBueffel[256]; /* - only managers can do this! - */ - if(!SCMatchRights(pCon,usMugger)){ + only managers can do this! + */ + if (!SCMatchRights(pCon, usMugger)) { return 0; } /* - we need tons of arguments! - */ - if(argc < 5){ - SCWrite(pCon,"ERROR: not enough arguments to TclReplaceDrivable", - eError); + we need tons of arguments! + */ + if (argc < 5) { + SCWrite(pCon, "ERROR: not enough arguments to TclReplaceDrivable", + eError); return 0; } /* - get and check object - */ + get and check object + */ strtolower(argv[1]); - pDriv = FindDrivable(pSics,argv[1]); - if(!pDriv){ - snprintf(pBueffel,255,"ERROR: %s is not drivable!",argv[1]); - SCWrite(pCon,pBueffel,eError); + pDriv = FindDrivable(pSics, argv[1]); + if (!pDriv) { + snprintf(pBueffel, 255, "ERROR: %s is not drivable!", argv[1]); + SCWrite(pCon, pBueffel, eError); return 0; } /* - This must work as FindDrivable could not work else - */ - pCom = FindCommand(pSics,argv[1]); + This must work as FindDrivable could not work else + */ + pCom = FindCommand(pSics, argv[1]); commandData = pCom->pData; /* - convert and check function name - */ + convert and check function name + */ strtolower(argv[2]); functionIndex = mapDrivableFunctionNames(argv[2]); - if(functionIndex <= 0){ - snprintf(pBueffel,255, - "ERROR: %s is not a known function name for drivable", - argv[2]); - SCWrite(pCon,pBueffel,eError); + if (functionIndex <= 0) { + snprintf(pBueffel, 255, + "ERROR: %s is not a known function name for drivable", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } - status = replaceDrivableByTcl(commandData,functionIndex,argv[3], - argv[4]); - if(status <= 0){ - SCWrite(pCon,"ERROR mismatch in parameter tclName",eError); + status = replaceDrivableByTcl(commandData, functionIndex, argv[3], + argv[4]); + if (status <= 0) { + SCWrite(pCon, "ERROR mismatch in parameter tclName", eError); return 0; } SCSendOK(pCon); return 1; } + /*-----------------------------------------------------------------------*/ -int TclDrivableInvoke(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]){ +int TclDrivableInvoke(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ pIDrivable pDriv = NULL; void *commandData; CommandList *pCom = NULL; @@ -525,115 +552,108 @@ int TclDrivableInvoke(SConnection *pCon, SicsInterp *pSics, float fVal; /* - we need tons of arguments! - */ - if(argc < 3){ - SCWrite(pCon,"ERROR: not enough arguments to TclDrivableInvoke", - eError); + we need tons of arguments! + */ + if (argc < 3) { + SCWrite(pCon, "ERROR: not enough arguments to TclDrivableInvoke", + eError); return 0; } /* - get and check object - */ + get and check object + */ strtolower(argv[1]); - pDriv = FindDrivable(pSics,argv[1]); - if(!pDriv){ - snprintf(pBueffel,255,"ERROR: %s is not drivable!",argv[1]); - SCWrite(pCon,pBueffel,eError); + pDriv = FindDrivable(pSics, argv[1]); + if (!pDriv) { + snprintf(pBueffel, 255, "ERROR: %s is not drivable!", argv[1]); + SCWrite(pCon, pBueffel, eError); return 0; } /* - This must work as FindDrivable could not work else - */ - pCom = FindCommand(pSics,argv[1]); + This must work as FindDrivable could not work else + */ + pCom = FindCommand(pSics, argv[1]); commandData = pCom->pData; /* - convert and check function name - */ + convert and check function name + */ strtolower(argv[2]); functionIndex = mapDrivableFunctionNames(argv[2]); - if(functionIndex <= 0){ - snprintf(pBueffel,255, - "ERROR: %s is not a known function name for drivable", - argv[2]); - SCWrite(pCon,pBueffel,eError); + if (functionIndex <= 0) { + snprintf(pBueffel, 255, + "ERROR: %s is not a known function name for drivable", + argv[2]); + SCWrite(pCon, pBueffel, eError); return 0; } /* - invoke and report - */ - memset(pError,0,132*sizeof(char)); - switch(functionIndex){ + invoke and report + */ + memset(pError, 0, 132 * sizeof(char)); + switch (functionIndex) { case TCLHALT: - if(!pDriv->Halt){ - SCWrite(pCon,"ERROR: no drivable Halt function!",eError); + if (!pDriv->Halt) { + SCWrite(pCon, "ERROR: no drivable Halt function!", eError); return 0; } status = pDriv->Halt(commandData); - snprintf(pBueffel,255,"Drivable Halt returned: %d",status); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "Drivable Halt returned: %d", status); + SCWrite(pCon, pBueffel, eValue); break; case TCLCHECK: - if(!pDriv->CheckLimits){ - SCWrite(pCon,"ERROR: no drivable CheckLimits function!",eError); + if (!pDriv->CheckLimits) { + SCWrite(pCon, "ERROR: no drivable CheckLimits function!", eError); return 0; } - if(argc < 4){ - SCWrite(pCon,"ERROR: need drive target for CheckLimits",eError); + if (argc < 4) { + SCWrite(pCon, "ERROR: need drive target for CheckLimits", eError); return 0; } - status = pDriv->CheckLimits(commandData,atof(argv[3]),pError,131); - snprintf(pBueffel,255,"Drivable CheckLimits returned: %d, %s", - status,pError); - SCWrite(pCon,pBueffel,eValue); + status = pDriv->CheckLimits(commandData, atof(argv[3]), pError, 131); + snprintf(pBueffel, 255, "Drivable CheckLimits returned: %d, %s", + status, pError); + SCWrite(pCon, pBueffel, eValue); break; case TCLSET: - if(!pDriv->SetValue){ - SCWrite(pCon,"ERROR: no drivable SetValue function!",eError); + if (!pDriv->SetValue) { + SCWrite(pCon, "ERROR: no drivable SetValue function!", eError); return 0; } - if(argc < 4){ - SCWrite(pCon,"ERROR: need drive target for SetValue",eError); + if (argc < 4) { + SCWrite(pCon, "ERROR: need drive target for SetValue", eError); return 0; } - status = (int)pDriv->SetValue(commandData,pCon,atof(argv[3])); - snprintf(pBueffel,255,"Drivable SetValue returned %d", status); - SCWrite(pCon,pBueffel,eValue); + status = (int) pDriv->SetValue(commandData, pCon, atof(argv[3])); + snprintf(pBueffel, 255, "Drivable SetValue returned %d", status); + SCWrite(pCon, pBueffel, eValue); break; case TCLSTATUS: - if(!pDriv->CheckStatus){ - SCWrite(pCon,"ERROR: no drivable CheckStatus function!",eError); + if (!pDriv->CheckStatus) { + SCWrite(pCon, "ERROR: no drivable CheckStatus function!", eError); return 0; } - status = pDriv->CheckStatus(commandData,pCon); - snprintf(pBueffel,255,"Drivable CheckStatus returned %d", status); - SCWrite(pCon,pBueffel,eValue); + status = pDriv->CheckStatus(commandData, pCon); + snprintf(pBueffel, 255, "Drivable CheckStatus returned %d", status); + SCWrite(pCon, pBueffel, eValue); break; case TCLGET: - if(!pDriv->GetValue){ - SCWrite(pCon,"ERROR: no drivable GetValue function!",eError); + if (!pDriv->GetValue) { + SCWrite(pCon, "ERROR: no drivable GetValue function!", eError); return 0; } - fVal = pDriv->GetValue(commandData,pCon); - snprintf(pBueffel,255,"Drivable GetValue returned: %f", fVal); - SCWrite(pCon,pBueffel,eValue); + fVal = pDriv->GetValue(commandData, pCon); + snprintf(pBueffel, 255, "Drivable GetValue returned: %f", fVal); + SCWrite(pCon, pBueffel, eValue); break; default: /* - do not know how I could get here - */ + do not know how I could get here + */ assert(0); } return 1; } - - - - - - - diff --git a/tcldrivable.h b/tcldrivable.h index d4f92088..243a894e 100644 --- a/tcldrivable.h +++ b/tcldrivable.h @@ -8,8 +8,8 @@ Mark Koennecke, September 2003 ----------------------------------------------------------------------*/ -#ifndef SICSTCLDRIVABLE -#define SICSTCLDRIVABLE +#ifndef SICSTCLDRIVABLE +#define SICSTCLDRIVABLE /* Function codes for functionIndex @@ -21,33 +21,32 @@ #define TCLGET 5 /* - This installs a Tcl replacement for a drivable function - */ - int TclReplaceDrivable(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); + This installs a Tcl replacement for a drivable function + */ +int TclReplaceDrivable(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); /* - This allows to invoke a replaced function for debugging - purposes - */ - int TclDrivableInvoke(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - - /* - This is for use from C - */ - int replaceDrivableByTcl(void *sicsObject, int functionIndex, - char *scriptName, char *tclName); + This allows to invoke a replaced function for debugging + purposes + */ +int TclDrivableInvoke(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); /* - map name to a functionIndex for use in replaceDrivableByTcl. - Returns 0 on failure, a usefule index > 0 in the case of success - */ - int mapDrivableFunctionNames(char *name); + This is for use from C + */ +int replaceDrivableByTcl(void *sicsObject, int functionIndex, + char *scriptName, char *tclName); /* - This is called from StopServer/nserver.c in order to remove - all memory related to this class - */ - void killTclDrivable(void); + map name to a functionIndex for use in replaceDrivableByTcl. + Returns 0 on failure, a usefule index > 0 in the case of success + */ +int mapDrivableFunctionNames(char *name); + + /* + This is called from StopServer/nserver.c in order to remove + all memory related to this class + */ +void killTclDrivable(void); #endif - diff --git a/tclev.c b/tclev.c index 211cb887..a17074ef 100644 --- a/tclev.c +++ b/tclev.c @@ -16,7 +16,7 @@ #include "fortify.h" #include "obpar.h" #include "evcontroller.h" -#include "evcontroller.i" +#include "evcontroller.i" #include "evdriver.i" #include "tclev.h" #include "tclev.i" @@ -25,508 +25,444 @@ The first section starts with the definition of the wrappers for all the driver functions. -----------------------------------------------------------------------------*/ - static int TclSetValue(pEVDriver self, float fNew) - { - pTclEv pPriv = NULL; - char pBueffel[1024]; - int iRet, iErrCode; - - pPriv = (pTclEv)self->pPrivate; - assert(pPriv); - - /* build command line */ - sprintf(pBueffel,"%s %s %f",pPriv->pSetValue, pPriv->pArray, fNew); - iRet = Tcl_Eval(pPriv->pTcl,pBueffel); - if(iRet != TCL_OK) - { - strncpy(pBueffel,pPriv->pTcl->result,1023); - iRet = Tcl_GetInt(pPriv->pTcl,pBueffel,&iErrCode); - if(iRet != TCL_OK) - { - pPriv->iLastError = STUPIDTCL; - return 0; - } - pPriv->iLastError = iErrCode; - return 0; - } - return 1; - } -/*-------------------------------------------------------------------------*/ - static int TclGetValue(pEVDriver self, float *fVal) - { - pTclEv pPriv = NULL; - char pBueffel[1024]; - int iRet, iErrCode; - double d; - - pPriv = (pTclEv)self->pPrivate; - assert(pPriv); - - /* build command line */ - sprintf(pBueffel,"%s %s",pPriv->pGetValue, pPriv->pArray); - iRet = Tcl_Eval(pPriv->pTcl,pBueffel); - if(iRet != TCL_OK) - { - strncpy(pBueffel,pPriv->pTcl->result,1023); - iRet = Tcl_GetInt(pPriv->pTcl,pBueffel,&iErrCode); - if(iRet != TCL_OK) - { - pPriv->iLastError = STUPIDTCL; - return 0; - } - pPriv->iLastError = iErrCode; - return 0; - } - else - { - if(strstr(pPriv->pTcl->result,"pending") != NULL) - { - *fVal = 90.; - return -1; - } - iRet = Tcl_GetDouble(pPriv->pTcl,pPriv->pTcl->result,&d); - if(iRet != TCL_OK) - { - pPriv->iLastError = STUPIDTCL; - return 0; - } - else - { - *fVal = (float)d; - return 1; - } - } - return 1; - } -/*-------------------------------------------------------------------------*/ - static int TclSend(pEVDriver self, char *pCommand, - char *pReply, int iReplyLen) - { - pTclEv pPriv = NULL; - char pBueffel[1024]; - int iRet, iErrCode; - double d; - - pPriv = (pTclEv)self->pPrivate; - assert(pPriv); - - /* build command line */ - sprintf(pBueffel,"%s %s %s",pPriv->pSend, pPriv->pArray,pCommand); - iRet = Tcl_Eval(pPriv->pTcl,pBueffel); - if(iRet != TCL_OK) - { - strncpy(pBueffel,pPriv->pTcl->result,1023); - iRet = Tcl_GetInt(pPriv->pTcl,pBueffel,&iErrCode); - if(iRet != TCL_OK) - { - pPriv->iLastError = STUPIDTCL; - return 0; - } - pPriv->iLastError = iErrCode; - return 0; - } - else - { - strncpy(pReply,pPriv->pTcl->result,iReplyLen); - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int TclGetError(pEVDriver self, int *iCode, - char *pReply, int iReplyLen) - { - pTclEv pPriv = NULL; - char pBueffel[1024]; - int iRet, iErrCode; - double d; - - pPriv = (pTclEv)self->pPrivate; - assert(pPriv); - - /* do the iCode first */ - *iCode = pPriv->iLastError; - - /* catch the stupid Tcl thing */ - if(pPriv->iLastError == STUPIDTCL) - { - sprintf(pBueffel,"Your Tcl-script returned a stupid answer:\n --> %s <--", - pPriv->pTcl->result); - strncpy(pReply,pBueffel,iReplyLen); - return 1; - } - - /* build command line */ - sprintf(pBueffel,"%s %s %d",pPriv->pGetError, pPriv->pArray,pPriv->iLastError); - iRet = Tcl_Eval(pPriv->pTcl,pBueffel); - if(iRet != TCL_OK) - { - strncpy(pBueffel,pPriv->pTcl->result,1023); - iRet = Tcl_GetInt(pPriv->pTcl,pPriv->pTcl->result,&iErrCode); - if(iRet != TCL_OK) - { - pPriv->iLastError = STUPIDTCL; - return 0; - } - pPriv->iLastError = iErrCode; - return 0; - } - else - { - strncpy(pReply,pPriv->pTcl->result,iReplyLen); - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int TclTryFixIt(pEVDriver self, int iCode) - { - pTclEv pPriv = NULL; - char pBueffel[1024]; - int iRet, iErrCode; - double d; - - pPriv = (pTclEv)self->pPrivate; - assert(pPriv); - - - /* catch the stupid Tcl thing */ - if(iCode == STUPIDTCL) - { - return DEVREDO; - } - - /* build command line */ - sprintf(pBueffel,"%s %s %d",pPriv->pTryFixIt, pPriv->pArray,iCode); - iRet = Tcl_Eval(pPriv->pTcl,pBueffel); - if(iRet != TCL_OK) - { - return DEVFAULT; - } - else - { - if(strcmp(pPriv->pTcl->result,"DEVFAULT") == 0) - { - return DEVFAULT; - } - else if(strcmp(pPriv->pTcl->result,"DEVREDO") == 0) - { - return DEVREDO; - } - else if(strcmp(pPriv->pTcl->result,"DEVOK") == 0) - { - return DEVOK; - } - else - { - pPriv->iLastError = STUPIDTCL; - return 0; - } - } - return 1; - } -/*-------------------------------------------------------------------------*/ - static int TclInit(pEVDriver self) - { - pTclEv pPriv = NULL; - char pBueffel[1024]; - int iRet, iErrCode; - - pPriv = (pTclEv)self->pPrivate; - assert(pPriv); - - /* build command line */ - sprintf(pBueffel,"%s %s",pPriv->pInit, pPriv->pArray); - iRet = Tcl_Eval(pPriv->pTcl,pBueffel); - if(iRet != TCL_OK) - { - strncpy(pBueffel,pPriv->pTcl->result,1023); - iRet = Tcl_GetInt(pPriv->pTcl,pBueffel,&iErrCode); - if(iRet != TCL_OK) - { - pPriv->iLastError = STUPIDTCL; - return 0; - } - pPriv->iLastError = iErrCode; - return 0; - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int TclClose(pEVDriver self) - { - pTclEv pPriv = NULL; - char pBueffel[1024]; - int iRet, iErrCode; - - pPriv = (pTclEv)self->pPrivate; - assert(pPriv); - - /* build command line */ - sprintf(pBueffel,"%s %s",pPriv->pClose, pPriv->pArray); - iRet = Tcl_Eval(pPriv->pTcl,pBueffel); - if(iRet != TCL_OK) - { - strncpy(pBueffel,pPriv->pTcl->result,1023); - iRet = Tcl_GetInt(pPriv->pTcl,pBueffel,&iErrCode); - if(iRet != TCL_OK) - { - pPriv->iLastError = STUPIDTCL; - return 0; - } - pPriv->iLastError = iErrCode; - return 0; - } - return 1; - } -/*---------------------------------------------------------------------------*/ - static void KillPrivate(void *pData) - { - pTclEv pPriv = NULL; - - pPriv = (pTclEv)pData; - assert(pPriv); - - if(pPriv->pArray) - { - free(pPriv->pArray); - } - if(pPriv->pInit) - { - free(pPriv->pInit); - } - if(pPriv->pClose) - { - free(pPriv->pClose); - } - if(pPriv->pSetValue) - { - free(pPriv->pSetValue); - } - if(pPriv->pGetValue) - { - free(pPriv->pGetValue); - } - if(pPriv->pSend) - { - free(pPriv->pSend); - } - if(pPriv->pGetError) - { - free(pPriv->pGetError); - } - if(pPriv->pTryFixIt) - { - free(pPriv->pTryFixIt); - } - if(pPriv->pWrapper) - { - free(pPriv->pWrapper); - } - if(pPriv->pName) - { - free(pPriv->pName); - } - free(pPriv); - } -/*-----------------------------------------------------------------------*/ - pEVDriver CreateTclDriver(int argc, char *argv[],char *pName, - SConnection *pCon) - { - pEVDriver pNew = NULL; - pTclEv pPriv = NULL; - int iRet; - /* the "const" saves us from a couple of warnings M.Z.*/ - const char *pPtr = NULL; - - if(argc < 1)/* we expect a Tcl array with all data */ - { - return NULL; - } - - pPriv = (pTclEv)malloc(sizeof(TclEv)); - if(!pPriv) - { - return NULL; - } - memset(pPriv,0,sizeof(TclEv)); - - /* find the names of all the functions we need in the Tcl Array */ - pPriv->pTcl = InterpGetTcl(pServ->pSics); - assert(pPriv->pTcl); - pPriv->pArray = strdup(argv[0]); - pPtr = Tcl_GetVar2(pPriv->pTcl,argv[0],"Init",TCL_GLOBAL_ONLY); - if(!pPtr) - { - SCWrite(pCon,"ERROR: Init script not found",eError); - KillPrivate(pPriv); - return NULL; - } - else - { - pPriv->pInit = strdup(pPtr); - } - pPtr = NULL; - pPtr = Tcl_GetVar2(pPriv->pTcl,argv[0],"Close",TCL_GLOBAL_ONLY); - if(!pPtr) - { - SCWrite(pCon,"ERROR: Close script not found",eError); - KillPrivate(pPriv); - return NULL; - } - else - { - pPriv->pClose = strdup(pPtr); - } - pPtr = NULL; - pPtr = Tcl_GetVar2(pPriv->pTcl,argv[0],"SetValue",TCL_GLOBAL_ONLY); - if(!pPtr) - { - SCWrite(pCon,"ERROR: SetValue script not found",eError); - KillPrivate(pPriv); - return NULL; - } - else - { - pPriv->pSetValue = strdup(pPtr); - } - pPtr = NULL; - pPtr = Tcl_GetVar2(pPriv->pTcl,argv[0],"GetValue",TCL_GLOBAL_ONLY); - if(!pPtr) - { - SCWrite(pCon,"ERROR: GetValue script not found",eError); - KillPrivate(pPriv); - return NULL; - } - else - { - pPriv->pGetValue = strdup(pPtr); - } - pPtr = Tcl_GetVar2(pPriv->pTcl,argv[0],"Send",TCL_GLOBAL_ONLY); - if(!pPtr) - { - SCWrite(pCon,"ERROR: Send script not found",eError); - KillPrivate(pPriv); - return NULL; - } - else - { - pPriv->pSend = strdup(pPtr); - } - pPtr = NULL; - pPtr = Tcl_GetVar2(pPriv->pTcl,argv[0],"GetError",TCL_GLOBAL_ONLY); - if(!pPtr) - { - SCWrite(pCon,"ERROR: GetError script not found",eError); - KillPrivate(pPriv); - return NULL; - } - else - { - pPriv->pGetError = strdup(pPtr); - } - pPtr = NULL; - pPtr = Tcl_GetVar2(pPriv->pTcl,argv[0],"TryFixIt",TCL_GLOBAL_ONLY); - if(!pPtr) - { - SCWrite(pCon,"ERROR: TryFixIt script not found",eError); - KillPrivate(pPriv); - return NULL; - } - else - { - pPriv->pTryFixIt = strdup(pPtr); - } - pPtr = NULL; - pPtr = Tcl_GetVar2(pPriv->pTcl,argv[0],"Wrapper",TCL_GLOBAL_ONLY); - if(!pPtr) - { - SCWrite(pCon,"ERROR: Wrapper script not found",eError); - KillPrivate(pPriv); - return NULL; - } - else - { - pPriv->pWrapper = strdup(pPtr); - } +static int TclSetValue(pEVDriver self, float fNew) +{ + pTclEv pPriv = NULL; + char pBueffel[1024]; + int iRet, iErrCode; - /* well all there, do the driver */ - pNew = CreateEVDriver(argc,argv); - if(!pNew) - { - KillPrivate(pPriv); - return NULL; - } - - /* handle the name */ - pPriv->pName = strdup(pName); - pPtr = Tcl_SetVar2(pPriv->pTcl,argv[0],"MyName",pName, TCL_GLOBAL_ONLY); - - /* initialise driver and functions */ - pNew->pPrivate = pPriv; - pNew->SetValue = TclSetValue; - pNew->GetValue = TclGetValue; - pNew->Send = TclSend; - pNew->GetError = TclGetError; - pNew->TryFixIt = TclTryFixIt; - pNew->Init = TclInit; - pNew->Close = TclClose; - pNew->KillPrivate = KillPrivate; - - /* driver loaded, ready steady fire! */ - return pNew; - } -/*-------------------------------------------------------------------------*/ - int UpdateTclVariable(pEVDriver self, char *name, float fVal) - { - pTclEv pPriv = NULL; - char pBueffel[132]; - const char *pPtr = NULL; - - assert(self); - pPriv = (pTclEv)self->pPrivate; - assert(pPriv); - - sprintf(pBueffel,"%f",fVal); - pPtr = Tcl_SetVar2(pPriv->pTcl,pPriv->pArray,name, - pBueffel,TCL_GLOBAL_ONLY); - if(pPtr == NULL) - { - return 0; - } - return 1; - } -#define MAXLEN 2048 -/*--------------------------------------------------------------------------*/ - int TclEnvironmentWrapper(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) - { - int iRet, i; - char pBueffel[MAXLEN+1]; - pTclEv pPriv = NULL; - pEVControl pEv = NULL; - - pEv = (pEVControl)pData; - assert(pEv); - pPriv = pEv->pDriv->pPrivate; - assert(pPriv); - - /* build command line */ - sprintf(pBueffel,"%s %s",pPriv->pWrapper,pPriv->pArray); - for(i = 1; i < argc; i++) - { - if((strlen(pBueffel) + strlen(argv[i])) < MAXLEN) - { - strcat(pBueffel," "); - strcat(pBueffel,argv[i]); - } + pPriv = (pTclEv) self->pPrivate; + assert(pPriv); + + /* build command line */ + sprintf(pBueffel, "%s %s %f", pPriv->pSetValue, pPriv->pArray, fNew); + iRet = Tcl_Eval(pPriv->pTcl, pBueffel); + if (iRet != TCL_OK) { + strncpy(pBueffel, pPriv->pTcl->result, 1023); + iRet = Tcl_GetInt(pPriv->pTcl, pBueffel, &iErrCode); + if (iRet != TCL_OK) { + pPriv->iLastError = STUPIDTCL; + return 0; } - /* execute Tcl */ - iRet = Tcl_Eval(pPriv->pTcl,pBueffel); - if(iRet == TCL_OK) - { + pPriv->iLastError = iErrCode; + return 0; + } + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int TclGetValue(pEVDriver self, float *fVal) +{ + pTclEv pPriv = NULL; + char pBueffel[1024]; + int iRet, iErrCode; + double d; + + pPriv = (pTclEv) self->pPrivate; + assert(pPriv); + + /* build command line */ + sprintf(pBueffel, "%s %s", pPriv->pGetValue, pPriv->pArray); + iRet = Tcl_Eval(pPriv->pTcl, pBueffel); + if (iRet != TCL_OK) { + strncpy(pBueffel, pPriv->pTcl->result, 1023); + iRet = Tcl_GetInt(pPriv->pTcl, pBueffel, &iErrCode); + if (iRet != TCL_OK) { + pPriv->iLastError = STUPIDTCL; + return 0; + } + pPriv->iLastError = iErrCode; + return 0; + } else { + if (strstr(pPriv->pTcl->result, "pending") != NULL) { + *fVal = 90.; + return -1; + } + iRet = Tcl_GetDouble(pPriv->pTcl, pPriv->pTcl->result, &d); + if (iRet != TCL_OK) { + pPriv->iLastError = STUPIDTCL; + return 0; + } else { + *fVal = (float) d; return 1; } - else - { - return EVControlWrapper(pCon,pSics,pData,argc,argv); + } + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int TclSend(pEVDriver self, char *pCommand, + char *pReply, int iReplyLen) +{ + pTclEv pPriv = NULL; + char pBueffel[1024]; + int iRet, iErrCode; + double d; + + pPriv = (pTclEv) self->pPrivate; + assert(pPriv); + + /* build command line */ + sprintf(pBueffel, "%s %s %s", pPriv->pSend, pPriv->pArray, pCommand); + iRet = Tcl_Eval(pPriv->pTcl, pBueffel); + if (iRet != TCL_OK) { + strncpy(pBueffel, pPriv->pTcl->result, 1023); + iRet = Tcl_GetInt(pPriv->pTcl, pBueffel, &iErrCode); + if (iRet != TCL_OK) { + pPriv->iLastError = STUPIDTCL; + return 0; + } + pPriv->iLastError = iErrCode; + return 0; + } else { + strncpy(pReply, pPriv->pTcl->result, iReplyLen); + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int TclGetError(pEVDriver self, int *iCode, + char *pReply, int iReplyLen) +{ + pTclEv pPriv = NULL; + char pBueffel[1024]; + int iRet, iErrCode; + double d; + + pPriv = (pTclEv) self->pPrivate; + assert(pPriv); + + /* do the iCode first */ + *iCode = pPriv->iLastError; + + /* catch the stupid Tcl thing */ + if (pPriv->iLastError == STUPIDTCL) { + sprintf(pBueffel, + "Your Tcl-script returned a stupid answer:\n --> %s <--", + pPriv->pTcl->result); + strncpy(pReply, pBueffel, iReplyLen); + return 1; + } + + /* build command line */ + sprintf(pBueffel, "%s %s %d", pPriv->pGetError, pPriv->pArray, + pPriv->iLastError); + iRet = Tcl_Eval(pPriv->pTcl, pBueffel); + if (iRet != TCL_OK) { + strncpy(pBueffel, pPriv->pTcl->result, 1023); + iRet = Tcl_GetInt(pPriv->pTcl, pPriv->pTcl->result, &iErrCode); + if (iRet != TCL_OK) { + pPriv->iLastError = STUPIDTCL; + return 0; + } + pPriv->iLastError = iErrCode; + return 0; + } else { + strncpy(pReply, pPriv->pTcl->result, iReplyLen); + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int TclTryFixIt(pEVDriver self, int iCode) +{ + pTclEv pPriv = NULL; + char pBueffel[1024]; + int iRet, iErrCode; + double d; + + pPriv = (pTclEv) self->pPrivate; + assert(pPriv); + + + /* catch the stupid Tcl thing */ + if (iCode == STUPIDTCL) { + return DEVREDO; + } + + /* build command line */ + sprintf(pBueffel, "%s %s %d", pPriv->pTryFixIt, pPriv->pArray, iCode); + iRet = Tcl_Eval(pPriv->pTcl, pBueffel); + if (iRet != TCL_OK) { + return DEVFAULT; + } else { + if (strcmp(pPriv->pTcl->result, "DEVFAULT") == 0) { + return DEVFAULT; + } else if (strcmp(pPriv->pTcl->result, "DEVREDO") == 0) { + return DEVREDO; + } else if (strcmp(pPriv->pTcl->result, "DEVOK") == 0) { + return DEVOK; + } else { + pPriv->iLastError = STUPIDTCL; + return 0; } } + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int TclInit(pEVDriver self) +{ + pTclEv pPriv = NULL; + char pBueffel[1024]; + int iRet, iErrCode; + + pPriv = (pTclEv) self->pPrivate; + assert(pPriv); + + /* build command line */ + sprintf(pBueffel, "%s %s", pPriv->pInit, pPriv->pArray); + iRet = Tcl_Eval(pPriv->pTcl, pBueffel); + if (iRet != TCL_OK) { + strncpy(pBueffel, pPriv->pTcl->result, 1023); + iRet = Tcl_GetInt(pPriv->pTcl, pBueffel, &iErrCode); + if (iRet != TCL_OK) { + pPriv->iLastError = STUPIDTCL; + return 0; + } + pPriv->iLastError = iErrCode; + return 0; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int TclClose(pEVDriver self) +{ + pTclEv pPriv = NULL; + char pBueffel[1024]; + int iRet, iErrCode; + + pPriv = (pTclEv) self->pPrivate; + assert(pPriv); + + /* build command line */ + sprintf(pBueffel, "%s %s", pPriv->pClose, pPriv->pArray); + iRet = Tcl_Eval(pPriv->pTcl, pBueffel); + if (iRet != TCL_OK) { + strncpy(pBueffel, pPriv->pTcl->result, 1023); + iRet = Tcl_GetInt(pPriv->pTcl, pBueffel, &iErrCode); + if (iRet != TCL_OK) { + pPriv->iLastError = STUPIDTCL; + return 0; + } + pPriv->iLastError = iErrCode; + return 0; + } + return 1; +} + +/*---------------------------------------------------------------------------*/ +static void KillPrivate(void *pData) +{ + pTclEv pPriv = NULL; + + pPriv = (pTclEv) pData; + assert(pPriv); + + if (pPriv->pArray) { + free(pPriv->pArray); + } + if (pPriv->pInit) { + free(pPriv->pInit); + } + if (pPriv->pClose) { + free(pPriv->pClose); + } + if (pPriv->pSetValue) { + free(pPriv->pSetValue); + } + if (pPriv->pGetValue) { + free(pPriv->pGetValue); + } + if (pPriv->pSend) { + free(pPriv->pSend); + } + if (pPriv->pGetError) { + free(pPriv->pGetError); + } + if (pPriv->pTryFixIt) { + free(pPriv->pTryFixIt); + } + if (pPriv->pWrapper) { + free(pPriv->pWrapper); + } + if (pPriv->pName) { + free(pPriv->pName); + } + free(pPriv); +} + +/*-----------------------------------------------------------------------*/ +pEVDriver CreateTclDriver(int argc, char *argv[], char *pName, + SConnection * pCon) +{ + pEVDriver pNew = NULL; + pTclEv pPriv = NULL; + int iRet; + /* the "const" saves us from a couple of warnings M.Z. */ + const char *pPtr = NULL; + + if (argc < 1) { /* we expect a Tcl array with all data */ + return NULL; + } + + pPriv = (pTclEv) malloc(sizeof(TclEv)); + if (!pPriv) { + return NULL; + } + memset(pPriv, 0, sizeof(TclEv)); + + /* find the names of all the functions we need in the Tcl Array */ + pPriv->pTcl = InterpGetTcl(pServ->pSics); + assert(pPriv->pTcl); + pPriv->pArray = strdup(argv[0]); + pPtr = Tcl_GetVar2(pPriv->pTcl, argv[0], "Init", TCL_GLOBAL_ONLY); + if (!pPtr) { + SCWrite(pCon, "ERROR: Init script not found", eError); + KillPrivate(pPriv); + return NULL; + } else { + pPriv->pInit = strdup(pPtr); + } + pPtr = NULL; + pPtr = Tcl_GetVar2(pPriv->pTcl, argv[0], "Close", TCL_GLOBAL_ONLY); + if (!pPtr) { + SCWrite(pCon, "ERROR: Close script not found", eError); + KillPrivate(pPriv); + return NULL; + } else { + pPriv->pClose = strdup(pPtr); + } + pPtr = NULL; + pPtr = Tcl_GetVar2(pPriv->pTcl, argv[0], "SetValue", TCL_GLOBAL_ONLY); + if (!pPtr) { + SCWrite(pCon, "ERROR: SetValue script not found", eError); + KillPrivate(pPriv); + return NULL; + } else { + pPriv->pSetValue = strdup(pPtr); + } + pPtr = NULL; + pPtr = Tcl_GetVar2(pPriv->pTcl, argv[0], "GetValue", TCL_GLOBAL_ONLY); + if (!pPtr) { + SCWrite(pCon, "ERROR: GetValue script not found", eError); + KillPrivate(pPriv); + return NULL; + } else { + pPriv->pGetValue = strdup(pPtr); + } + pPtr = Tcl_GetVar2(pPriv->pTcl, argv[0], "Send", TCL_GLOBAL_ONLY); + if (!pPtr) { + SCWrite(pCon, "ERROR: Send script not found", eError); + KillPrivate(pPriv); + return NULL; + } else { + pPriv->pSend = strdup(pPtr); + } + pPtr = NULL; + pPtr = Tcl_GetVar2(pPriv->pTcl, argv[0], "GetError", TCL_GLOBAL_ONLY); + if (!pPtr) { + SCWrite(pCon, "ERROR: GetError script not found", eError); + KillPrivate(pPriv); + return NULL; + } else { + pPriv->pGetError = strdup(pPtr); + } + pPtr = NULL; + pPtr = Tcl_GetVar2(pPriv->pTcl, argv[0], "TryFixIt", TCL_GLOBAL_ONLY); + if (!pPtr) { + SCWrite(pCon, "ERROR: TryFixIt script not found", eError); + KillPrivate(pPriv); + return NULL; + } else { + pPriv->pTryFixIt = strdup(pPtr); + } + pPtr = NULL; + pPtr = Tcl_GetVar2(pPriv->pTcl, argv[0], "Wrapper", TCL_GLOBAL_ONLY); + if (!pPtr) { + SCWrite(pCon, "ERROR: Wrapper script not found", eError); + KillPrivate(pPriv); + return NULL; + } else { + pPriv->pWrapper = strdup(pPtr); + } + + /* well all there, do the driver */ + pNew = CreateEVDriver(argc, argv); + if (!pNew) { + KillPrivate(pPriv); + return NULL; + } + + /* handle the name */ + pPriv->pName = strdup(pName); + pPtr = + Tcl_SetVar2(pPriv->pTcl, argv[0], "MyName", pName, TCL_GLOBAL_ONLY); + + /* initialise driver and functions */ + pNew->pPrivate = pPriv; + pNew->SetValue = TclSetValue; + pNew->GetValue = TclGetValue; + pNew->Send = TclSend; + pNew->GetError = TclGetError; + pNew->TryFixIt = TclTryFixIt; + pNew->Init = TclInit; + pNew->Close = TclClose; + pNew->KillPrivate = KillPrivate; + + /* driver loaded, ready steady fire! */ + return pNew; +} + +/*-------------------------------------------------------------------------*/ +int UpdateTclVariable(pEVDriver self, char *name, float fVal) +{ + pTclEv pPriv = NULL; + char pBueffel[132]; + const char *pPtr = NULL; + + assert(self); + pPriv = (pTclEv) self->pPrivate; + assert(pPriv); + + sprintf(pBueffel, "%f", fVal); + pPtr = Tcl_SetVar2(pPriv->pTcl, pPriv->pArray, name, + pBueffel, TCL_GLOBAL_ONLY); + if (pPtr == NULL) { + return 0; + } + return 1; +} + +#define MAXLEN 2048 +/*--------------------------------------------------------------------------*/ +int TclEnvironmentWrapper(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + int iRet, i; + char pBueffel[MAXLEN + 1]; + pTclEv pPriv = NULL; + pEVControl pEv = NULL; + + pEv = (pEVControl) pData; + assert(pEv); + pPriv = pEv->pDriv->pPrivate; + assert(pPriv); + + /* build command line */ + sprintf(pBueffel, "%s %s", pPriv->pWrapper, pPriv->pArray); + for (i = 1; i < argc; i++) { + if ((strlen(pBueffel) + strlen(argv[i])) < MAXLEN) { + strcat(pBueffel, " "); + strcat(pBueffel, argv[i]); + } + } + /* execute Tcl */ + iRet = Tcl_Eval(pPriv->pTcl, pBueffel); + if (iRet == TCL_OK) { + return 1; + } else { + return EVControlWrapper(pCon, pSics, pData, argc, argv); + } +} diff --git a/tclev.h b/tclev.h index 68ffe808..e86d2a18 100644 --- a/tclev.h +++ b/tclev.h @@ -11,15 +11,14 @@ ------------------------------------------------------------------------------*/ #ifndef SICSTCLEV #define SICSTCLEV - - pEVDriver CreateTclDriver(int argc, char *argv[],char *pName, SConnection *pCon); - int UpdateTclVariable(pEVDriver self, char *name, float fVal); - int TclEnvironmentWrapper(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - +pEVDriver CreateTclDriver(int argc, char *argv[], char *pName, + SConnection * pCon); +int UpdateTclVariable(pEVDriver self, char *name, float fVal); + +int TclEnvironmentWrapper(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + #endif - - diff --git a/tclintimpl.c b/tclintimpl.c index 3b340f25..07d860c4 100644 --- a/tclintimpl.c +++ b/tclintimpl.c @@ -24,165 +24,178 @@ typedef struct { FILE *fd; } tclInt, *pTclInt; /*======================= interface functions ============================*/ -static int TclSaveStatus(void *pData, char *name, FILE *fd){ +static int TclSaveStatus(void *pData, char *name, FILE * fd) +{ pTclInt self = NULL; char pBuffer[1024]; - self = (pTclInt)pData; + self = (pTclInt) pData; assert(self); - if(self->saveScript == NULL){ - return 1; - } - - if(strlen(self->saveScript) + strlen(name) + 2 >= 1023){ - fprintf(fd,"#ERROR: arguments to long for save scripting"); + if (self->saveScript == NULL) { return 1; } - strcpy(pBuffer,self->saveScript); - strcat(pBuffer," "); - strcat(pBuffer,name); + + if (strlen(self->saveScript) + strlen(name) + 2 >= 1023) { + fprintf(fd, "#ERROR: arguments to long for save scripting"); + return 1; + } + strcpy(pBuffer, self->saveScript); + strcat(pBuffer, " "); + strcat(pBuffer, name); self->fd = fd; - Tcl_Eval(InterpGetTcl(pServ->pSics),pBuffer); + Tcl_Eval(InterpGetTcl(pServ->pSics), pBuffer); self->fd = NULL; return 1; } + /*-----------------------------------------------------------------------*/ -static void *TclGetInterface(void *pData, int id){ +static void *TclGetInterface(void *pData, int id) +{ pTclInt self = NULL; - self = (pTclInt)pData; - if(self == NULL){ + self = (pTclInt) pData; + if (self == NULL) { return NULL; } - if(id == DRIVEID){ + if (id == DRIVEID) { return self->pDriv; } else { return NULL; } } + /*======================== data structure creation and deletion ==========*/ -static pTclInt MakeTclIntData(void){ +static pTclInt MakeTclIntData(void) +{ pTclInt pNew = NULL; - pNew = (pTclInt)malloc(sizeof(tclInt)); - if(pNew == NULL){ + pNew = (pTclInt) malloc(sizeof(tclInt)); + if (pNew == NULL) { return NULL; } - memset(pNew,0,sizeof(tclInt)); + memset(pNew, 0, sizeof(tclInt)); pNew->pDes = CreateDescriptor("SICS Interfaces in Tcl"); pNew->pDes->SaveStatus = TclSaveStatus; pNew->pDes->GetInterface = TclGetInterface; pNew->pDriv = CreateDrivableInterface(); - if(!pNew->pDes || !pNew->pDriv){ + if (!pNew->pDes || !pNew->pDriv) { free(pNew); return NULL; } return pNew; } + /*------------------------------------------------------------------------*/ -static void KillTclInt(void *pData){ +static void KillTclInt(void *pData) +{ pTclInt self = NULL; - self = (pTclInt)pData; - if(self == NULL){ + self = (pTclInt) pData; + if (self == NULL) { return; } - - if(self->pDes != NULL){ + + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); } - if(self->saveScript != NULL){ + if (self->saveScript != NULL) { free(self->saveScript); } - if(self->pDriv){ + if (self->pDriv) { free(self->pDriv); } free(self); } + /*=============== interpreter interface + helper functions =============*/ -int MakeTclInt(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int MakeTclInt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pTclInt pNew = NULL; char pBuffer[132]; int iRet; - if(argc < 2) { - SCWrite(pCon,"ERROR: I need a name argument for the script interface", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: I need a name argument for the script interface", + eError); return 0; } pNew = MakeTclIntData(); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: no memory to create SICS script interface", - eError); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: no memory to create SICS script interface", + eError); return 0; } - iRet = AddCommand(pSics,argv[1],TclIntAction,KillTclInt,(void *)pNew); - if(!iRet){ - sprintf(pBuffer,"ERROR: duplicate command %s not created",argv[1]); - SCWrite(pCon,pBuffer,eError); - return 0; + iRet = + AddCommand(pSics, argv[1], TclIntAction, KillTclInt, (void *) pNew); + if (!iRet) { + sprintf(pBuffer, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBuffer, eError); + return 0; } return 1; } + /*--------------------------------------------------------------------*/ -int TclIntAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int TclIntAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pTclInt self = NULL; char pBuffer[1024]; char *cmd; float val; - self = (pTclInt)pData; + self = (pTclInt) pData; assert(self); - if(argc < 2){ - if(self->pDriv->GetValue != NULL){ - val = self->pDriv->GetValue(self,pCon); - snprintf(pBuffer,1024,"%s = %f", argv[0], val); - SCWrite(pCon,pBuffer,eValue); - return 1; + if (argc < 2) { + if (self->pDriv->GetValue != NULL) { + val = self->pDriv->GetValue(self, pCon); + snprintf(pBuffer, 1024, "%s = %f", argv[0], val); + SCWrite(pCon, pBuffer, eValue); + return 1; } else { - sprintf(pBuffer,"ERROR: %s expects at least one argument!", argv[0]); - SCWrite(pCon,pBuffer,eError); - return 0; + sprintf(pBuffer, "ERROR: %s expects at least one argument!", + argv[0]); + SCWrite(pCon, pBuffer, eError); + return 0; } } strtolower(argv[1]); - if(strcmp(argv[1],"savescript") == 0){ - if(argc < 3){ - SCWrite(pCon,"ERROR: missing argument to savescript",eError); + if (strcmp(argv[1], "savescript") == 0) { + if (argc < 3) { + SCWrite(pCon, "ERROR: missing argument to savescript", eError); return 0; } - if(self->saveScript != NULL){ + if (self->saveScript != NULL) { free(self->saveScript); self->saveScript = NULL; } self->saveScript = strdup(argv[2]); SCSendOK(pCon); return 1; - } else if(strcmp(argv[1],"backup") == 0){ - cmd = Arg2Tcl(argc-2, &argv[2],pBuffer,1023); + } else if (strcmp(argv[1], "backup") == 0) { + cmd = Arg2Tcl(argc - 2, &argv[2], pBuffer, 1023); if (cmd) { - if(self->fd != NULL){ - fprintf(self->fd,"%s\n",cmd); + if (self->fd != NULL) { + fprintf(self->fd, "%s\n", cmd); } - if (cmd != pBuffer) free(cmd); + if (cmd != pBuffer) + free(cmd); SCSendOK(pCon); } return 1; } else { - sprintf(pBuffer,"ERROR: keyword %s to %s not recognized", - argv[1],argv[0]); - SCWrite(pCon,pBuffer,eError); + sprintf(pBuffer, "ERROR: keyword %s to %s not recognized", + argv[1], argv[0]); + SCWrite(pCon, pBuffer, eError); return 0; } return 1; } - diff --git a/tclintimpl.h b/tclintimpl.h index d7ef6fc8..77cc3a71 100644 --- a/tclintimpl.h +++ b/tclintimpl.h @@ -15,12 +15,10 @@ #include "sics.h" -int MakeTclInt(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeTclInt(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -int TclIntAction(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int TclIntAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif - - diff --git a/tclmotdriv.c b/tclmotdriv.c index a6dedfa0..59892af3 100644 --- a/tclmotdriv.c +++ b/tclmotdriv.c @@ -35,360 +35,374 @@ #define TCLERROR -11001 #define NOTCLRESULT -11002 /*----------------------------------------------------------------------------*/ -static int buildStandardCommandPart(TCLDriv *pDriv, char *command, - char *tclCommand, int commandLen){ - char tclFunc[132]; - int status; - - status = StringDictGet(pDriv->mappings,command,tclFunc,131); - if(status != 1) { - return 0; - } - snprintf(tclCommand,commandLen,"%s %s ", tclFunc, pDriv->motName); - return 1; -} -/*----------------------------------------------------------------------------*/ - static int GetTclPos(void *self, float *fPos){ - TCLDriv *pDriv; - char tclCommand[1024]; - int status; - const char *result = NULL; - - assert(self); - pDriv = (TCLDriv *)self; +static int buildStandardCommandPart(TCLDriv * pDriv, char *command, + char *tclCommand, int commandLen) +{ + char tclFunc[132]; + int status; - pDriv->errorCode = 0; - if(!buildStandardCommandPart(pDriv,"getpos",tclCommand,1023)){ - pDriv->errorCode = FUNCNOTFOUND; - return HWFault; - } - - status = Tcl_Eval(pServ->pSics->pTcl,tclCommand); - result = Tcl_GetStringResult(pServ->pSics->pTcl); - if(result == NULL){ - pDriv->errorCode = NOTCLRESULT; - return HWFault; - } - if(status != TCL_OK){ - pDriv->errorCode = TCLERROR; - strncpy(pDriv->tclError,result,1023); - return HWFault; - } - sscanf(result,"%f",fPos); - return OKOK; - } -/*----------------------------------------------------------------------------*/ - static int TclRun(void *self, float fVal) { - TCLDriv *pDriv; - char tclCommand[1024]; - char num[80]; - int status; - const char *result = NULL; - - assert(self); - pDriv = (TCLDriv *)self; - - pDriv->errorCode = 0; - if(!buildStandardCommandPart(pDriv,"run",tclCommand,1023)){ - pDriv->errorCode = FUNCNOTFOUND; - return HWFault; - } - snprintf(num,79,"%f",fVal); - strncat(tclCommand,num,1023-strlen(tclCommand)); - - status = Tcl_Eval(pServ->pSics->pTcl,tclCommand); - result = Tcl_GetStringResult(pServ->pSics->pTcl); - if(result == NULL) { - pDriv->errorCode = NOTCLRESULT; - return HWFault; - } - if(status != TCL_OK){ - pDriv->errorCode = TCLERROR; - strncpy(pDriv->tclError,result,1023); - return HWFault; - } - sscanf(result,"%d",&status); - return status; - } -/*-------------------------------------------------------------------------*/ -static int evaluateInternalErrors(TCLDriv *pDriv, int *iCode, - char *error, int iErrLen){ - switch(pDriv->errorCode){ - case FUNCNOTFOUND: - strncpy(error,"Config Error: Tcl function for driver not found",iErrLen); - *iCode = pDriv->errorCode; - return 1; - break; - case TCLERROR: - strncpy(error,pDriv->tclError,iErrLen); - *iCode = pDriv->errorCode; - return 1; - break; - case NOTCLRESULT: - strncpy(error,"Tcl function did not return result",iErrLen); - *iCode = pDriv->errorCode; - return 1; - break; - default: - return 0; - break; - } + status = StringDictGet(pDriv->mappings, command, tclFunc, 131); + if (status != 1) { return 0; -} -/*--------------------------------------------------------------------------*/ - static void TclError(void *self, int *iCode, char *error, int iErrLen){ - TCLDriv *pDriv; - char tclCommand[1024]; - int status = 1; - const char *result = NULL; - - assert(self); - pDriv = (TCLDriv *)self; - - if(evaluateInternalErrors(pDriv,iCode,error,iErrLen) == 1) { - return; - } - - if(!buildStandardCommandPart(pDriv,"geterror",tclCommand,1023)){ - pDriv->errorCode = FUNCNOTFOUND; - status = 0; - } - - if(status != 0){ - status = Tcl_Eval(pServ->pSics->pTcl,tclCommand); - result = Tcl_GetStringResult(pServ->pSics->pTcl); - if(result == NULL) { - pDriv->errorCode = NOTCLRESULT; - } - if(status != TCL_OK && result != NULL){ - pDriv->errorCode = TCLERROR; - strncpy(pDriv->tclError,result,1023); - } - } - - if(evaluateInternalErrors(pDriv,iCode,error,iErrLen) == 1) { - return; - } - strncpy(error,result,iErrLen); } + snprintf(tclCommand, commandLen, "%s %s ", tclFunc, pDriv->motName); + return 1; +} + +/*----------------------------------------------------------------------------*/ +static int GetTclPos(void *self, float *fPos) +{ + TCLDriv *pDriv; + char tclCommand[1024]; + int status; + const char *result = NULL; + + assert(self); + pDriv = (TCLDriv *) self; + + pDriv->errorCode = 0; + if (!buildStandardCommandPart(pDriv, "getpos", tclCommand, 1023)) { + pDriv->errorCode = FUNCNOTFOUND; + return HWFault; + } + + status = Tcl_Eval(pServ->pSics->pTcl, tclCommand); + result = Tcl_GetStringResult(pServ->pSics->pTcl); + if (result == NULL) { + pDriv->errorCode = NOTCLRESULT; + return HWFault; + } + if (status != TCL_OK) { + pDriv->errorCode = TCLERROR; + strncpy(pDriv->tclError, result, 1023); + return HWFault; + } + sscanf(result, "%f", fPos); + return OKOK; +} + +/*----------------------------------------------------------------------------*/ +static int TclRun(void *self, float fVal) +{ + TCLDriv *pDriv; + char tclCommand[1024]; + char num[80]; + int status; + const char *result = NULL; + + assert(self); + pDriv = (TCLDriv *) self; + + pDriv->errorCode = 0; + if (!buildStandardCommandPart(pDriv, "run", tclCommand, 1023)) { + pDriv->errorCode = FUNCNOTFOUND; + return HWFault; + } + snprintf(num, 79, "%f", fVal); + strncat(tclCommand, num, 1023 - strlen(tclCommand)); + + status = Tcl_Eval(pServ->pSics->pTcl, tclCommand); + result = Tcl_GetStringResult(pServ->pSics->pTcl); + if (result == NULL) { + pDriv->errorCode = NOTCLRESULT; + return HWFault; + } + if (status != TCL_OK) { + pDriv->errorCode = TCLERROR; + strncpy(pDriv->tclError, result, 1023); + return HWFault; + } + sscanf(result, "%d", &status); + return status; +} + +/*-------------------------------------------------------------------------*/ +static int evaluateInternalErrors(TCLDriv * pDriv, int *iCode, + char *error, int iErrLen) +{ + switch (pDriv->errorCode) { + case FUNCNOTFOUND: + strncpy(error, "Config Error: Tcl function for driver not found", + iErrLen); + *iCode = pDriv->errorCode; + return 1; + break; + case TCLERROR: + strncpy(error, pDriv->tclError, iErrLen); + *iCode = pDriv->errorCode; + return 1; + break; + case NOTCLRESULT: + strncpy(error, "Tcl function did not return result", iErrLen); + *iCode = pDriv->errorCode; + return 1; + break; + default: + return 0; + break; + } + return 0; +} + +/*--------------------------------------------------------------------------*/ +static void TclError(void *self, int *iCode, char *error, int iErrLen) +{ + TCLDriv *pDriv; + char tclCommand[1024]; + int status = 1; + const char *result = NULL; + + assert(self); + pDriv = (TCLDriv *) self; + + if (evaluateInternalErrors(pDriv, iCode, error, iErrLen) == 1) { + return; + } + + if (!buildStandardCommandPart(pDriv, "geterror", tclCommand, 1023)) { + pDriv->errorCode = FUNCNOTFOUND; + status = 0; + } + + if (status != 0) { + status = Tcl_Eval(pServ->pSics->pTcl, tclCommand); + result = Tcl_GetStringResult(pServ->pSics->pTcl); + if (result == NULL) { + pDriv->errorCode = NOTCLRESULT; + } + if (status != TCL_OK && result != NULL) { + pDriv->errorCode = TCLERROR; + strncpy(pDriv->tclError, result, 1023); + } + } + + if (evaluateInternalErrors(pDriv, iCode, error, iErrLen) == 1) { + return; + } + strncpy(error, result, iErrLen); +} + /*---------------------------------------------------------------------------*/ - static int TclFix(void *self, int iError, float fNew){ - TCLDriv *pDriv; - char tclCommand[1024]; - char num[80]; - int status; - const char *result = NULL; - - assert(self); - pDriv = (TCLDriv *)self; +static int TclFix(void *self, int iError, float fNew) +{ + TCLDriv *pDriv; + char tclCommand[1024]; + char num[80]; + int status; + const char *result = NULL; - if(!buildStandardCommandPart(pDriv,"fixit",tclCommand,1023)){ - pDriv->errorCode = FUNCNOTFOUND; - return HWFault; - } - snprintf(num,79,"%d %f",pDriv->errorCode, fNew); - strncat(tclCommand,num,1023-strlen(tclCommand)); + assert(self); + pDriv = (TCLDriv *) self; - status = Tcl_Eval(pServ->pSics->pTcl,tclCommand); - result = Tcl_GetStringResult(pServ->pSics->pTcl); - if(result == NULL) { - pDriv->errorCode = NOTCLRESULT; - return HWFault; - } - if(status != TCL_OK){ - pDriv->errorCode = TCLERROR; - strncpy(pDriv->tclError,result,1023); - return HWFault; - } - sscanf(result,"%d",&status); - return status; + if (!buildStandardCommandPart(pDriv, "fixit", tclCommand, 1023)) { + pDriv->errorCode = FUNCNOTFOUND; + return HWFault; } + snprintf(num, 79, "%d %f", pDriv->errorCode, fNew); + strncat(tclCommand, num, 1023 - strlen(tclCommand)); + + status = Tcl_Eval(pServ->pSics->pTcl, tclCommand); + result = Tcl_GetStringResult(pServ->pSics->pTcl); + if (result == NULL) { + pDriv->errorCode = NOTCLRESULT; + return HWFault; + } + if (status != TCL_OK) { + pDriv->errorCode = TCLERROR; + strncpy(pDriv->tclError, result, 1023); + return HWFault; + } + sscanf(result, "%d", &status); + return status; +} + /*--------------------------------------------------------------------------*/ - static int TclHalt(void *self) - { - TCLDriv *pDriv; - char tclCommand[1024]; - int status; - const char *result = NULL; - - assert(self); - pDriv = (TCLDriv *)self; +static int TclHalt(void *self) +{ + TCLDriv *pDriv; + char tclCommand[1024]; + int status; + const char *result = NULL; - pDriv->errorCode = 0; - if(!buildStandardCommandPart(pDriv,"halt",tclCommand,1023)){ - pDriv->errorCode = FUNCNOTFOUND; - return HWFault; - } + assert(self); + pDriv = (TCLDriv *) self; - status = Tcl_Eval(pServ->pSics->pTcl,tclCommand); - result = Tcl_GetStringResult(pServ->pSics->pTcl); - if(result == NULL){ - pDriv->errorCode = NOTCLRESULT; - return HWFault; - } - if(status != TCL_OK){ - pDriv->errorCode = TCLERROR; - strncpy(pDriv->tclError,result,1023); - return HWFault; - } - return OKOK; + pDriv->errorCode = 0; + if (!buildStandardCommandPart(pDriv, "halt", tclCommand, 1023)) { + pDriv->errorCode = FUNCNOTFOUND; + return HWFault; } + + status = Tcl_Eval(pServ->pSics->pTcl, tclCommand); + result = Tcl_GetStringResult(pServ->pSics->pTcl); + if (result == NULL) { + pDriv->errorCode = NOTCLRESULT; + return HWFault; + } + if (status != TCL_OK) { + pDriv->errorCode = TCLERROR; + strncpy(pDriv->tclError, result, 1023); + return HWFault; + } + return OKOK; +} + /*--------------------------------------------------------------------------*/ - static int TclStat(void *self) - { - TCLDriv *pDriv; - char tclCommand[1024]; - int status; - const char *result = NULL; - - assert(self); - pDriv = (TCLDriv *)self; +static int TclStat(void *self) +{ + TCLDriv *pDriv; + char tclCommand[1024]; + int status; + const char *result = NULL; - pDriv->errorCode = 0; - if(!buildStandardCommandPart(pDriv,"status",tclCommand,1023)){ - pDriv->errorCode = FUNCNOTFOUND; - return HWFault; - } + assert(self); + pDriv = (TCLDriv *) self; - status = Tcl_Eval(pServ->pSics->pTcl,tclCommand); - result = Tcl_GetStringResult(pServ->pSics->pTcl); - if(result == NULL){ - pDriv->errorCode = NOTCLRESULT; - return HWFault; - } - if(status != TCL_OK){ - pDriv->errorCode = TCLERROR; - strncpy(pDriv->tclError,result,1023); - return HWFault; - } - sscanf(result,"%d",&status); - return status; + pDriv->errorCode = 0; + if (!buildStandardCommandPart(pDriv, "status", tclCommand, 1023)) { + pDriv->errorCode = FUNCNOTFOUND; + return HWFault; } + + status = Tcl_Eval(pServ->pSics->pTcl, tclCommand); + result = Tcl_GetStringResult(pServ->pSics->pTcl); + if (result == NULL) { + pDriv->errorCode = NOTCLRESULT; + return HWFault; + } + if (status != TCL_OK) { + pDriv->errorCode = TCLERROR; + strncpy(pDriv->tclError, result, 1023); + return HWFault; + } + sscanf(result, "%d", &status); + return status; +} + /*-----------------------------------------------------------------------*/ -static int TclSetPar(void *self, SConnection *pCon, char *name, float newValue){ +static int TclSetPar(void *self, SConnection * pCon, char *name, + float newValue) +{ TCLDriv *pDriv = (TCLDriv *) self; assert(self); assert(pCon); - if(strcmp(name,"hardupperlim") == 0) - { + if (strcmp(name, "hardupperlim") == 0) { pDriv->fUpper = newValue; return 1; } - if(strcmp(name,"hardlowerlim") == 0) - { + if (strcmp(name, "hardlowerlim") == 0) { pDriv->fLower = newValue; return 1; } - if(strcmp(name,"errorcode") == 0) - { - pDriv->errorCode = (int)newValue; + if (strcmp(name, "errorcode") == 0) { + pDriv->errorCode = (int) newValue; return 1; } return 0; } + /*-----------------------------------------------------------------------*/ -static int TclGetPar(void *self, char *name, float *value){ +static int TclGetPar(void *self, char *name, float *value) +{ TCLDriv *pDriv = (TCLDriv *) self; assert(self); - if(strcmp(name,"errorcode") == 0) - { - *value = (float)pDriv->errorCode; + if (strcmp(name, "errorcode") == 0) { + *value = (float) pDriv->errorCode; return 1; } return 0; } + /*---------------------------------------------------------------------------*/ - void KillTCL(void *pData) - { - TCLDriv *pDriv = (TCLDriv *) pData; +void KillTCL(void *pData) +{ + TCLDriv *pDriv = (TCLDriv *) pData; - if(pDriv != NULL){ - DeleteStringDict(pDriv->mappings); - } - - return; - } -/*-------------------------------------------------------------------------*/ -static int assignMappings(TCLDriv *pDriv, SConnection *pCon, char *arrayName){ - const char *funcName = NULL; - char *funcText[] = {"getpos", - "run", - "status", - "halt", - "geterror", - "fixit", - NULL}; - char error[256]; - int count = 0; - - while(funcText[count] != NULL) { - funcName = Tcl_GetVar2(pServ->pSics->pTcl,arrayName,funcText[count],TCL_GLOBAL_ONLY); - if(funcName == NULL) { - snprintf(error,255,"ERROR: entry for %s not found in tcl-array %s", - funcText[count], arrayName); - SCWrite(pCon,error,eError); - return 0; - } - StringDictAddPair(pDriv->mappings,funcText[count],(char *)funcName); - count++; - } - return 1; -} -/*--------------------------------------------------------------------------*/ - MotorDriver *CreateTclMotDriv(SConnection *pCon, int argc, char *argv[]) - { - TCLDriv *pDriv = NULL; - - assert(pCon); - - if(argc < 4) { - SCWrite(pCon,"ERROR: not enough arguments to initilaize Tcl-driver",eError); - return NULL; - } - - pDriv = (TCLDriv *)malloc(sizeof(TCLDriv)); - if(!pDriv){ - SCWrite(pCon,"Error allocating memory in TclMotor",eError); - return NULL; - } - memset(pDriv,0,sizeof(TCLDriv)); - pDriv->mappings = CreateStringDict(); - if(pDriv->mappings == NULL){ - SCWrite(pCon,"Error allocating memory in TclMotor",eError); - free(pDriv); - return NULL; - } - if(assignMappings(pDriv,pCon,argv[3]) != 1){ - DeleteStringDict(pDriv->mappings); - free(pDriv); - return NULL; - } - - pDriv->name = strdup("Tcl-Driver"); - strncpy(pDriv->motName, argv[1], 131); - pDriv->GetPosition = GetTclPos; - pDriv->RunTo = TclRun; - pDriv->GetStatus = TclStat; - pDriv->GetError = TclError; - pDriv->TryAndFixIt = TclFix; - pDriv->SetDriverPar = TclSetPar; - pDriv->GetDriverPar = TclGetPar; - pDriv->Halt = TclHalt; - pDriv->KillPrivate = KillTCL; - - return (MotorDriver *)pDriv; + if (pDriv != NULL) { + DeleteStringDict(pDriv->mappings); } + return; +} +/*-------------------------------------------------------------------------*/ +static int assignMappings(TCLDriv * pDriv, SConnection * pCon, + char *arrayName) +{ + const char *funcName = NULL; + char *funcText[] = { "getpos", + "run", + "status", + "halt", + "geterror", + "fixit", + NULL + }; + char error[256]; + int count = 0; + while (funcText[count] != NULL) { + funcName = + Tcl_GetVar2(pServ->pSics->pTcl, arrayName, funcText[count], + TCL_GLOBAL_ONLY); + if (funcName == NULL) { + snprintf(error, 255, "ERROR: entry for %s not found in tcl-array %s", + funcText[count], arrayName); + SCWrite(pCon, error, eError); + return 0; + } + StringDictAddPair(pDriv->mappings, funcText[count], (char *) funcName); + count++; + } + return 1; +} +/*--------------------------------------------------------------------------*/ +MotorDriver *CreateTclMotDriv(SConnection * pCon, int argc, char *argv[]) +{ + TCLDriv *pDriv = NULL; + assert(pCon); + if (argc < 4) { + SCWrite(pCon, "ERROR: not enough arguments to initilaize Tcl-driver", + eError); + return NULL; + } + pDriv = (TCLDriv *) malloc(sizeof(TCLDriv)); + if (!pDriv) { + SCWrite(pCon, "Error allocating memory in TclMotor", eError); + return NULL; + } + memset(pDriv, 0, sizeof(TCLDriv)); + pDriv->mappings = CreateStringDict(); + if (pDriv->mappings == NULL) { + SCWrite(pCon, "Error allocating memory in TclMotor", eError); + free(pDriv); + return NULL; + } + if (assignMappings(pDriv, pCon, argv[3]) != 1) { + DeleteStringDict(pDriv->mappings); + free(pDriv); + return NULL; + } + pDriv->name = strdup("Tcl-Driver"); + strncpy(pDriv->motName, argv[1], 131); + pDriv->GetPosition = GetTclPos; + pDriv->RunTo = TclRun; + pDriv->GetStatus = TclStat; + pDriv->GetError = TclError; + pDriv->TryAndFixIt = TclFix; + pDriv->SetDriverPar = TclSetPar; + pDriv->GetDriverPar = TclGetPar; + pDriv->Halt = TclHalt; + pDriv->KillPrivate = KillTCL; - + return (MotorDriver *) pDriv; +} diff --git a/tclmotdriv.h b/tclmotdriv.h index aff43a6c..853a9207 100644 --- a/tclmotdriv.h +++ b/tclmotdriv.h @@ -8,37 +8,35 @@ Mark Koennecke, December 2005 --------------------------------------------------------------------------*/ #ifndef TCLMOTDRIV -#define TCLMOTDRIV +#define TCLMOTDRIV #include "stringdict.h" - typedef struct ___TclDriv { - /* general motor driver interface - fields. REQUIRED! - */ - float fUpper; /* upper limit */ - float fLower; /* lower limit */ - char *name; - int (*GetPosition)(void *self,float *fPos); - int (*RunTo)(void *self, float fNewVal); - int (*GetStatus)(void *self); - void (*GetError)(void *self, int *iCode, char *buffer, int iBufLen); - int (*TryAndFixIt)(void *self,int iError, float fNew); - int (*Halt)(void *self); - int (*GetDriverPar)(void *self, char *name, - float *value); - int (*SetDriverPar)(void *self,SConnection *pCon, - char *name, float newValue); - void (*ListDriverPar)(void *self, char *motorName, - SConnection *pCon); - void (*KillPrivate)(void *self); - - /* Tcl specific fields */ - pStringDict mappings; - int errorCode; - char tclError[1024]; - char motName[132]; - } TCLDriv; - -MotorDriver *CreateTclMotDriv(SConnection *pCon, int argc, char *argv[]); +typedef struct ___TclDriv { + /* general motor driver interface + fields. REQUIRED! + */ + float fUpper; /* upper limit */ + float fLower; /* lower limit */ + char *name; + int (*GetPosition) (void *self, float *fPos); + int (*RunTo) (void *self, float fNewVal); + int (*GetStatus) (void *self); + void (*GetError) (void *self, int *iCode, char *buffer, int iBufLen); + int (*TryAndFixIt) (void *self, int iError, float fNew); + int (*Halt) (void *self); + int (*GetDriverPar) (void *self, char *name, float *value); + int (*SetDriverPar) (void *self, SConnection * pCon, + char *name, float newValue); + void (*ListDriverPar) (void *self, char *motorName, SConnection * pCon); + void (*KillPrivate) (void *self); + + /* Tcl specific fields */ + pStringDict mappings; + int errorCode; + char tclError[1024]; + char motName[132]; +} TCLDriv; + +MotorDriver *CreateTclMotDriv(SConnection * pCon, int argc, char *argv[]); #endif diff --git a/telnet.c b/telnet.c index d845cfef..d791c806 100644 --- a/telnet.c +++ b/telnet.c @@ -14,419 +14,378 @@ #include "telnet.h" #include "commandlog.h" #include "fortify.h" -#define LOGINWAIT 300 +#define LOGINWAIT 300 /* 300 == 5 minutes to wait for valid username password */ /*-------------------------------------------------------------------------*/ - typedef struct __TelTask { - SConnection *pCon; - int iLogin; - char pLoginWord[132]; - time_t tStart; - } TelTask; +typedef struct __TelTask { + SConnection *pCon; + int iLogin; + char pLoginWord[132]; + time_t tStart; +} TelTask; /*--------------------------------------------------------------------------*/ - pTelTask CreateTelnet(SConnection *pCon) - { - pTelTask pRes = NULL; - char *pPtr = NULL; - time_t shit; - assert(pCon); - - /* check for the login word */ - pPtr = IFindOption(pSICSOptions,"TelWord"); - if(!pPtr) - { - return NULL; - } - pRes = (pTelTask)malloc(sizeof(TelTask)); - if(!pRes) - { - return NULL; - } - - /* initialise */ - memset(pRes,0,sizeof(TelTask)); - pRes->pCon = pCon; - pRes->iLogin = 0; - pRes->tStart = time(&shit); - strcpy(pRes->pLoginWord,pPtr); - return pRes; - } -/*--------------------------------------------------------------------------*/ - void DeleteTelnet(void *pData) - { - pTelTask pKill = NULL; - assert(pData); - - pKill = (pTelTask)pData; - - if(pKill->pCon) - { - SCDeleteConnection(pKill->pCon); - } - free(pKill); - } -/*-------------------------------------------------------------------------*/ - static void SendWelcome(SConnection *pCon) - { - SCWrite(pCon,"--------- Welcome to SICS ------------",eError); - SCWrite(pCon,"You are now connected to a SICS Instrument Control Server",eError); - SCWrite(pCon,"\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",eError); - SCWrite(pCon,"WARNING: Proceed with utmost care!",eError); - SCWrite(pCon,"YOU MAY BE MOVING HARDWARE IN THE EXPERIMENT HALL",eError); - SCWrite(pCon,"YOU MAY CAUSE GRIEVIOUS BODILY HARM TO SOMEBODY",eError); - SCWrite(pCon,"YOU MAY DAMAGE VALUABLE AND SOMETIMES IRREPLACABLE HARDWARE", - eError); - SCWrite(pCon,"Continuing here seriously compromises hacker's ethics",eError); - SCWrite(pCon,"You will NOT find valuable data here!",eError); - SCWrite(pCon,"The SICS server does NOT allow you to spawn to the system",eError); - SCWrite(pCon,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",eError); - } -/*-------------------------------------------------------------------------*/ - static void SendGA(SConnection *pCon) - { - char pReply[2]; - - pReply[0] = (char)255; - pReply[1] = (char)249; - NETWrite(pCon->pSock,pReply,2); - } -/*--------------------------------------------------------------------------*/ - int TelnetTaskOld(void *pData) - { - pTelTask self = NULL; - char *pPtr = NULL; - char *pLogin = NULL; - char *pUser = NULL, *pPasswd = NULL; - char pBuffer[512], pHost[131]; - int iRet; - time_t shit; - - self = (pTelTask)pData; - assert(self); - - if(self->pCon->iEnd) - { - if(SCActive(self->pCon)) - { - return 1; - } - else - { - return 0; - } - } - - /* pop and execute */ - iRet = CostaPop(self->pCon->pStack,&pPtr); - if(iRet) - { - if(pPtr) - { - if(self->iLogin) /* handle normal command */ - { - /* check for logoff */ - if(strstr(pPtr,"logoff") != NULL) - { - NetReadRemove(pServ->pReader,self->pCon->pSock); - free(pPtr); - self->pCon->iEnd = 1; - return 0; - } - /* invoke command */ - CostaLock(self->pCon->pStack); - SCInvoke(self->pCon,pServ->pSics,pPtr); - CostaUnlock(self->pCon->pStack); - SendGA(self->pCon); - free(pPtr); - } - else /* handle login messages */ - { - pLogin = strstr(pPtr,self->pLoginWord); - if(!pLogin) - { - SCWrite(self->pCon, - "------------------- Get Lost -------------------", - eError); - if(time(&shit) > self->tStart + LOGINWAIT) - { - SCWrite(self->pCon, - "I cannot stand your login attempts anymore!", - eError); - NetReadRemove(pServ->pReader,self->pCon->pSock); - self->pCon->iEnd = 1; - free(pPtr); - return 0; - } - free(pPtr); - return 1; - } - else /* check username / password */ - { - pLogin += strlen(self->pLoginWord); - pUser = strtok(pLogin," \t"); - pPasswd = strtok(NULL," \t\r\n"); - iRet = IsValidUser(pUser,pPasswd); - if(iRet < 0) - { - sprintf(pBuffer,"SYSTEM ATTACK by %s / %s",pUser, - pPasswd); - SICSLogWrite(pBuffer,eInternal); - SCWrite(self->pCon, - "I do not know you, I do not let you in",eError); - SendGA(self->pCon); - free(pPtr); - return 1; - } - else - { - NETInfo(self->pCon->pSock,pHost,131); - sprintf(pBuffer,"Accepted connection on socket %d from %s", - self->pCon->pSock->sockid, pHost); - SICSLogWrite(pBuffer,eInternal); - WriteToCommandLog("SYS >", pBuffer); - SendWelcome(self->pCon); - SCSetRights(self->pCon,iRet); - self->iLogin = 1; - SendGA(self->pCon); - free(pPtr); - return 1; - } - } - } - } - } - /* check for no commands but timeout on telnet */ - if( !self->iLogin && (time(&shit) > self->tStart + LOGINWAIT) ) - { - self->pCon->iEnd = 1; - NetReadRemove(pServ->pReader,self->pCon->pSock); - return 0; - } - - - /* check for end */ - if(self->pCon->iEnd) - { - if(SCActive(self->pCon)) - { - return 1; - } - else - { - return 0; - } - } - - return 1; - } -/*--------------------------------------------------------------------------*/ - int TelnetTask(void *pData) - { - pTelTask self = NULL; - char *pPtr = NULL; - char *pLogin = NULL; - char *pUser = NULL, *pPasswd = NULL; - char pBuffer[512], pHost[131]; - int iRet; - time_t shit; - - self = (pTelTask)pData; - assert(self); - - if(self->pCon->iEnd) - { - if(SCActive(self->pCon)) - { - return 1; - } - else - { - return 0; - } - } - - /* pop and execute */ - iRet = CostaPop(self->pCon->pStack,&pPtr); - if(iRet) - { - if(pPtr) - { - if(self->iLogin) /* handle normal command */ - { - /* check for logoff */ - if(strstr(pPtr,"logoff") != NULL) - { - ANETclose(self->pCon->sockHandle); - free(pPtr); - self->pCon->iEnd = 1; - return 0; - } - /* invoke command */ - CostaLock(self->pCon->pStack); - SCInvoke(self->pCon,pServ->pSics,pPtr); - CostaUnlock(self->pCon->pStack); - SendGA(self->pCon); - free(pPtr); - } - else /* handle login messages */ - { - pLogin = strstr(pPtr,self->pLoginWord); - if(!pLogin) - { - SCWrite(self->pCon, - "------------------- Get Lost -------------------", - eError); - if(time(&shit) > self->tStart + LOGINWAIT) - { - SCWrite(self->pCon, - "I cannot stand your login attempts anymore!", - eError); - ANETclose(self->pCon->sockHandle); - self->pCon->iEnd = 1; - free(pPtr); - return 0; - } - free(pPtr); - return 1; - } - else /* check username / password */ - { - pLogin += strlen(self->pLoginWord); - pUser = strtok(pLogin," \t"); - pPasswd = strtok(NULL," \t\r\n"); - iRet = IsValidUser(pUser,pPasswd); - if(iRet < 0) - { - sprintf(pBuffer,"SYSTEM ATTACK by %s / %s",pUser, - pPasswd); - SICSLogWrite(pBuffer,eInternal); - SCWrite(self->pCon, - "I do not know you, I do not let you in",eError); - SendGA(self->pCon); - free(pPtr); - return 1; - } - else - { - sprintf(pBuffer,"Accepted telnet connection on handle %d", - self->pCon->sockHandle); - SICSLogWrite(pBuffer,eInternal); - WriteToCommandLog("SYS >", pBuffer); - SendWelcome(self->pCon); - SCSetRights(self->pCon,iRet); - self->iLogin = 1; - SendGA(self->pCon); - free(pPtr); - return 1; - } - } - } - } - } - /* check for no commands but timeout on telnet */ - if( !self->iLogin && (time(&shit) > self->tStart + LOGINWAIT) ) - { - self->pCon->iEnd = 1; - ANETclose(self->pCon->sockHandle); - return 0; - } - - - /* check for end */ - if(self->pCon->iEnd) - { - if(SCActive(self->pCon)) - { - return 1; - } - else - { - return 0; - } - } - - return 1; - } -/*---------------------------------------------------------------------------*/ - void TelnetSignal(void *pData, int iSignal, void *pSigData) - { - pTelTask self = NULL; - int *iInt; - char *pPtr; - - self = (pTelTask)pData; - assert(self); - - if(iSignal == SICSINT) - { - iInt = (int *)pSigData; - SCSetInterrupt(self->pCon,*iInt); - if(*iInt == eEndServer) - { - self->pCon->iEnd = 1; - } - } - else if(iSignal == SICSBROADCAST) - { - pPtr = (char *)pSigData; - if(pPtr) - { - SCWrite(self->pCon,pPtr,eWarning); - } - } - else if(iSignal == TOKENRELEASE) - { - self->pCon->iGrab = 0; - } - else if(iSignal == TOKENGRAB) - { - self->pCon->iGrab = 1; - } - } -/*-------------------------------------------------------------------------*/ - static mkChannel *pTelnet = NULL; - - void InstallTelnet(void) - { - char *pPtr = NULL; - int i, iPort; +pTelTask CreateTelnet(SConnection * pCon) +{ + pTelTask pRes = NULL; + char *pPtr = NULL; + time_t shit; + assert(pCon); - /* No double telnet ports ! */ - assert(!pTelnet); - - /* if the option is not there or invalid, telnet is disabled */ - pPtr = IFindOption(pSICSOptions,"TelnetPort"); - if(!pPtr) - { - return; - } - i = sscanf(pPtr,"%d",&iPort); - /* + /* check for the login word */ + pPtr = IFindOption(pSICSOptions, "TelWord"); + if (!pPtr) { + return NULL; + } + pRes = (pTelTask) malloc(sizeof(TelTask)); + if (!pRes) { + return NULL; + } + + /* initialise */ + memset(pRes, 0, sizeof(TelTask)); + pRes->pCon = pCon; + pRes->iLogin = 0; + pRes->tStart = time(&shit); + strcpy(pRes->pLoginWord, pPtr); + return pRes; +} + +/*--------------------------------------------------------------------------*/ +void DeleteTelnet(void *pData) +{ + pTelTask pKill = NULL; + assert(pData); + + pKill = (pTelTask) pData; + + if (pKill->pCon) { + SCDeleteConnection(pKill->pCon); + } + free(pKill); +} + +/*-------------------------------------------------------------------------*/ +static void SendWelcome(SConnection * pCon) +{ + SCWrite(pCon, "--------- Welcome to SICS ------------", eError); + SCWrite(pCon, + "You are now connected to a SICS Instrument Control Server", + eError); + SCWrite(pCon, "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", + eError); + SCWrite(pCon, "WARNING: Proceed with utmost care!", eError); + SCWrite(pCon, "YOU MAY BE MOVING HARDWARE IN THE EXPERIMENT HALL", + eError); + SCWrite(pCon, "YOU MAY CAUSE GRIEVIOUS BODILY HARM TO SOMEBODY", eError); + SCWrite(pCon, + "YOU MAY DAMAGE VALUABLE AND SOMETIMES IRREPLACABLE HARDWARE", + eError); + SCWrite(pCon, "Continuing here seriously compromises hacker's ethics", + eError); + SCWrite(pCon, "You will NOT find valuable data here!", eError); + SCWrite(pCon, + "The SICS server does NOT allow you to spawn to the system", + eError); + SCWrite(pCon, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", + eError); +} + +/*-------------------------------------------------------------------------*/ +static void SendGA(SConnection * pCon) +{ + char pReply[2]; + + pReply[0] = (char) 255; + pReply[1] = (char) 249; + NETWrite(pCon->pSock, pReply, 2); +} + +/*--------------------------------------------------------------------------*/ +int TelnetTaskOld(void *pData) +{ + pTelTask self = NULL; + char *pPtr = NULL; + char *pLogin = NULL; + char *pUser = NULL, *pPasswd = NULL; + char pBuffer[512], pHost[131]; + int iRet; + time_t shit; + + self = (pTelTask) pData; + assert(self); + + if (self->pCon->iEnd) { + if (SCActive(self->pCon)) { + return 1; + } else { + return 0; + } + } + + /* pop and execute */ + iRet = CostaPop(self->pCon->pStack, &pPtr); + if (iRet) { + if (pPtr) { + if (self->iLogin) { /* handle normal command */ + /* check for logoff */ + if (strstr(pPtr, "logoff") != NULL) { + NetReadRemove(pServ->pReader, self->pCon->pSock); + free(pPtr); + self->pCon->iEnd = 1; + return 0; + } + /* invoke command */ + CostaLock(self->pCon->pStack); + SCInvoke(self->pCon, pServ->pSics, pPtr); + CostaUnlock(self->pCon->pStack); + SendGA(self->pCon); + free(pPtr); + } else { /* handle login messages */ + + pLogin = strstr(pPtr, self->pLoginWord); + if (!pLogin) { + SCWrite(self->pCon, + "------------------- Get Lost -------------------", + eError); + if (time(&shit) > self->tStart + LOGINWAIT) { + SCWrite(self->pCon, + "I cannot stand your login attempts anymore!", eError); + NetReadRemove(pServ->pReader, self->pCon->pSock); + self->pCon->iEnd = 1; + free(pPtr); + return 0; + } + free(pPtr); + return 1; + } else { /* check username / password */ + + pLogin += strlen(self->pLoginWord); + pUser = strtok(pLogin, " \t"); + pPasswd = strtok(NULL, " \t\r\n"); + iRet = IsValidUser(pUser, pPasswd); + if (iRet < 0) { + sprintf(pBuffer, "SYSTEM ATTACK by %s / %s", pUser, pPasswd); + SICSLogWrite(pBuffer, eInternal); + SCWrite(self->pCon, + "I do not know you, I do not let you in", eError); + SendGA(self->pCon); + free(pPtr); + return 1; + } else { + NETInfo(self->pCon->pSock, pHost, 131); + sprintf(pBuffer, "Accepted connection on socket %d from %s", + self->pCon->pSock->sockid, pHost); + SICSLogWrite(pBuffer, eInternal); + WriteToCommandLog("SYS >", pBuffer); + SendWelcome(self->pCon); + SCSetRights(self->pCon, iRet); + self->iLogin = 1; + SendGA(self->pCon); + free(pPtr); + return 1; + } + } + } + } + } + /* check for no commands but timeout on telnet */ + if (!self->iLogin && (time(&shit) > self->tStart + LOGINWAIT)) { + self->pCon->iEnd = 1; + NetReadRemove(pServ->pReader, self->pCon->pSock); + return 0; + } + + + /* check for end */ + if (self->pCon->iEnd) { + if (SCActive(self->pCon)) { + return 1; + } else { + return 0; + } + } + + return 1; +} + +/*--------------------------------------------------------------------------*/ +int TelnetTask(void *pData) +{ + pTelTask self = NULL; + char *pPtr = NULL; + char *pLogin = NULL; + char *pUser = NULL, *pPasswd = NULL; + char pBuffer[512], pHost[131]; + int iRet; + time_t shit; + + self = (pTelTask) pData; + assert(self); + + if (self->pCon->iEnd) { + if (SCActive(self->pCon)) { + return 1; + } else { + return 0; + } + } + + /* pop and execute */ + iRet = CostaPop(self->pCon->pStack, &pPtr); + if (iRet) { + if (pPtr) { + if (self->iLogin) { /* handle normal command */ + /* check for logoff */ + if (strstr(pPtr, "logoff") != NULL) { + ANETclose(self->pCon->sockHandle); + free(pPtr); + self->pCon->iEnd = 1; + return 0; + } + /* invoke command */ + CostaLock(self->pCon->pStack); + SCInvoke(self->pCon, pServ->pSics, pPtr); + CostaUnlock(self->pCon->pStack); + SendGA(self->pCon); + free(pPtr); + } else { /* handle login messages */ + + pLogin = strstr(pPtr, self->pLoginWord); + if (!pLogin) { + SCWrite(self->pCon, + "------------------- Get Lost -------------------", + eError); + if (time(&shit) > self->tStart + LOGINWAIT) { + SCWrite(self->pCon, + "I cannot stand your login attempts anymore!", eError); + ANETclose(self->pCon->sockHandle); + self->pCon->iEnd = 1; + free(pPtr); + return 0; + } + free(pPtr); + return 1; + } else { /* check username / password */ + + pLogin += strlen(self->pLoginWord); + pUser = strtok(pLogin, " \t"); + pPasswd = strtok(NULL, " \t\r\n"); + iRet = IsValidUser(pUser, pPasswd); + if (iRet < 0) { + sprintf(pBuffer, "SYSTEM ATTACK by %s / %s", pUser, pPasswd); + SICSLogWrite(pBuffer, eInternal); + SCWrite(self->pCon, + "I do not know you, I do not let you in", eError); + SendGA(self->pCon); + free(pPtr); + return 1; + } else { + sprintf(pBuffer, "Accepted telnet connection on handle %d", + self->pCon->sockHandle); + SICSLogWrite(pBuffer, eInternal); + WriteToCommandLog("SYS >", pBuffer); + SendWelcome(self->pCon); + SCSetRights(self->pCon, iRet); + self->iLogin = 1; + SendGA(self->pCon); + free(pPtr); + return 1; + } + } + } + } + } + /* check for no commands but timeout on telnet */ + if (!self->iLogin && (time(&shit) > self->tStart + LOGINWAIT)) { + self->pCon->iEnd = 1; + ANETclose(self->pCon->sockHandle); + return 0; + } + + + /* check for end */ + if (self->pCon->iEnd) { + if (SCActive(self->pCon)) { + return 1; + } else { + return 0; + } + } + + return 1; +} + +/*---------------------------------------------------------------------------*/ +void TelnetSignal(void *pData, int iSignal, void *pSigData) +{ + pTelTask self = NULL; + int *iInt; + char *pPtr; + + self = (pTelTask) pData; + assert(self); + + if (iSignal == SICSINT) { + iInt = (int *) pSigData; + SCSetInterrupt(self->pCon, *iInt); + if (*iInt == eEndServer) { + self->pCon->iEnd = 1; + } + } else if (iSignal == SICSBROADCAST) { + pPtr = (char *) pSigData; + if (pPtr) { + SCWrite(self->pCon, pPtr, eWarning); + } + } else if (iSignal == TOKENRELEASE) { + self->pCon->iGrab = 0; + } else if (iSignal == TOKENGRAB) { + self->pCon->iGrab = 1; + } +} + +/*-------------------------------------------------------------------------*/ +static mkChannel *pTelnet = NULL; + +void InstallTelnet(void) +{ + char *pPtr = NULL; + int i, iPort; + + /* No double telnet ports ! */ + assert(!pTelnet); + + /* if the option is not there or invalid, telnet is disabled */ + pPtr = IFindOption(pSICSOptions, "TelnetPort"); + if (!pPtr) { + return; + } + i = sscanf(pPtr, "%d", &iPort); + /* if(i > 0) { - pTelnet = NETOpenPort(iPort); + pTelnet = NETOpenPort(iPort); } - - if(pTelnet) - { - NetReadRegister(pServ->pReader,pTelnet, taccept, NULL); - } - */ - /* when we have a port have the NetReader listen and handle it */ - NetReadInstallANETPort(pServ->pReader,taccept, iPort); - } -/*---------------------------------------------------------------------------*/ - void KillTelnet(void) - { if(pTelnet) { - NETClosePort(pTelnet); -/* NetReadRemove(pServ->pReader,pTelnet); */ - free(pTelnet); - pTelnet = NULL; + NetReadRegister(pServ->pReader,pTelnet, taccept, NULL); } - } + */ + /* when we have a port have the NetReader listen and handle it */ + NetReadInstallANETPort(pServ->pReader, taccept, iPort); + +} + +/*---------------------------------------------------------------------------*/ +void KillTelnet(void) +{ + if (pTelnet) { + NETClosePort(pTelnet); +/* NetReadRemove(pServ->pReader,pTelnet); */ + free(pTelnet); + pTelnet = NULL; + } +} /*------------------------------------------------------------------------ Telnet is fully described in RFC-854. This implementation is very simple. @@ -437,7 +396,7 @@ /* Telnet codes */ #define SE 240 #define NOP 241 -#define DM 242 /* data mark */ +#define DM 242 /* data mark */ #define BRK 243 #define IP 244 #define AO 245 diff --git a/telnet.h b/telnet.h index 97de2d6e..a00367cf 100644 --- a/telnet.h +++ b/telnet.h @@ -11,17 +11,16 @@ #ifndef SICSTELNET #define SICSTELNET - typedef struct __TelTask *pTelTask; +typedef struct __TelTask *pTelTask; /*--------------------------------------------------------------------------*/ - pTelTask CreateTelnet(SConnection *pCon); - void DeleteTelnet(void *pData); +pTelTask CreateTelnet(SConnection * pCon); +void DeleteTelnet(void *pData); /*---------------------------------------------------------------------------*/ - int TelnetTask(void *pData); - void TelnetSignal(void *pData, int iSignal, void *pSigData); +int TelnetTask(void *pData); +void TelnetSignal(void *pData, int iSignal, void *pSigData); /*--------------------------------------------------------------------------*/ - void InstallTelnet(void); - void KillTelnet(void); +void InstallTelnet(void); +void KillTelnet(void); #endif - diff --git a/token.c b/token.c index 4df9e587..11c7370c 100644 --- a/token.c +++ b/token.c @@ -14,143 +14,130 @@ #include "status.h" /*---------------------- token Management ----------------------------------*/ - static int iToken = 0; - static char pTokenPassword[256]; +static int iToken = 0; +static char pTokenPassword[256]; /*--------------------------------------------------------------------------*/ - int TokenGrabActive(void) - { - return iToken; - } -/*-------------------------------------------------------------------------*/ - void TokenRelease(void) - { - iToken = 0; - } -/*-------------------------------------------------------------------------*/ - int TokenInit(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet; - - /* we need a password for token forcing as a parameter */ - if(argc < 2) - { - SCWrite(pCon,"ERROR: I need a password for token forcing!", eError); - return 0; - } - - - if(strlen(argv[1]) > 255) - { - SCWrite(pCon, "ERROR: TokenPassword to long!",eError); - return 0; - } - memset(pTokenPassword,0,255); - strcpy(pTokenPassword,argv[1]); - - /* create command */ - iRet = AddCommand(pSics, - "token", - TokenWrapper, - NULL, - NULL); - if(!iRet) - { - SCWrite(pCon,"ERROR: token command already exists ??? !!",eError); - } - return iRet; - - } -/*-------------------------------------------------------------------------*/ - int TokenWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[256]; - - if(argc < 2) - { - SCWrite(pCon,"ERROR: expected subcommand to token",eError); - return 0; - } - - /* handle grab */ - if(strcmp(argv[1],"grab") == 0) - { - /* check user rights */ - if(usUser < SCGetRights(pCon)) - { - SCWrite(pCon,"ERROR: you are not authorised to grab anything at all!", - eError); - return 0; - } - /* is there already a grab? */ - if(iToken) - { - SCWrite(pCon,"ERROR: Somebody else has already control! You are REJECTED", - eError); - return 0; - } - /* is somebody doing a scan ? */ - if(GetStatus() != eEager) - { - SCWrite(pCon,"ERROR: you cannot grab control while a scan is still running", - eError); - return 0; - } - /* we can do it */ - iToken = 1; - TaskSignal(pServ->pTasker,TOKENGRAB,NULL); - pCon->iGrab = 0; /* to enable us to do commands */ - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"release") == 0) - { - if(pCon->iGrab != 0) - { - SCWrite(pCon,"ERROR: you cannot release somebody elses control token!", - eError); - return 0; - } - iToken = 0; - TaskSignal(pServ->pTasker,TOKENRELEASE,NULL); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"force") == 0) - { - /* check force password */ - if(argc < 3) - { - SCWrite(pCon,"ERROR: I need a password for this operation! Request REJECTED", - eError); - return 0; - } - if(strcmp(argv[2],pTokenPassword) == 0) - { - if(usMugger < SCGetRights(pCon)) - { - SCWrite(pCon,"ERROR: Manager privilege required to force your way into a SICS server", - eError); - SCWrite(pCon,"ERROR: You are REJECTED",eError); - return 0; - } - iToken = 0; - TaskSignal(pServ->pTasker,TOKENRELEASE,0); - SCWrite(pCon,"Token forcefully released, no grab active",eWarning); - return 1; - } - else - { - SCWrite(pCon,"ERROR: The specified password is WRONG!",eError); - SCWrite(pCon,"ERROR: Your request has been REJECTED",eError); - return 0; - } - } - /* default */ - sprintf(pBueffel,"ERROR: subcommand %s to token NOT understood", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; +int TokenGrabActive(void) +{ + return iToken; +} - } +/*-------------------------------------------------------------------------*/ +void TokenRelease(void) +{ + iToken = 0; +} + +/*-------------------------------------------------------------------------*/ +int TokenInit(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet; + + /* we need a password for token forcing as a parameter */ + if (argc < 2) { + SCWrite(pCon, "ERROR: I need a password for token forcing!", eError); + return 0; + } + + + if (strlen(argv[1]) > 255) { + SCWrite(pCon, "ERROR: TokenPassword to long!", eError); + return 0; + } + memset(pTokenPassword, 0, 255); + strcpy(pTokenPassword, argv[1]); + + /* create command */ + iRet = AddCommand(pSics, "token", TokenWrapper, NULL, NULL); + if (!iRet) { + SCWrite(pCon, "ERROR: token command already exists ??? !!", eError); + } + return iRet; + +} + +/*-------------------------------------------------------------------------*/ +int TokenWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[256]; + + if (argc < 2) { + SCWrite(pCon, "ERROR: expected subcommand to token", eError); + return 0; + } + + /* handle grab */ + if (strcmp(argv[1], "grab") == 0) { + /* check user rights */ + if (usUser < SCGetRights(pCon)) { + SCWrite(pCon, + "ERROR: you are not authorised to grab anything at all!", + eError); + return 0; + } + /* is there already a grab? */ + if (iToken) { + SCWrite(pCon, + "ERROR: Somebody else has already control! You are REJECTED", + eError); + return 0; + } + /* is somebody doing a scan ? */ + if (GetStatus() != eEager) { + SCWrite(pCon, + "ERROR: you cannot grab control while a scan is still running", + eError); + return 0; + } + /* we can do it */ + iToken = 1; + TaskSignal(pServ->pTasker, TOKENGRAB, NULL); + pCon->iGrab = 0; /* to enable us to do commands */ + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "release") == 0) { + if (pCon->iGrab != 0) { + SCWrite(pCon, + "ERROR: you cannot release somebody elses control token!", + eError); + return 0; + } + iToken = 0; + TaskSignal(pServ->pTasker, TOKENRELEASE, NULL); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "force") == 0) { + /* check force password */ + if (argc < 3) { + SCWrite(pCon, + "ERROR: I need a password for this operation! Request REJECTED", + eError); + return 0; + } + if (strcmp(argv[2], pTokenPassword) == 0) { + if (usMugger < SCGetRights(pCon)) { + SCWrite(pCon, + "ERROR: Manager privilege required to force your way into a SICS server", + eError); + SCWrite(pCon, "ERROR: You are REJECTED", eError); + return 0; + } + iToken = 0; + TaskSignal(pServ->pTasker, TOKENRELEASE, 0); + SCWrite(pCon, "Token forcefully released, no grab active", eWarning); + return 1; + } else { + SCWrite(pCon, "ERROR: The specified password is WRONG!", eError); + SCWrite(pCon, "ERROR: Your request has been REJECTED", eError); + return 0; + } + } + /* default */ + sprintf(pBueffel, "ERROR: subcommand %s to token NOT understood", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + +} diff --git a/token.h b/token.h index 6dcff35d..df3bc3cb 100644 --- a/token.h +++ b/token.h @@ -12,25 +12,25 @@ ----------------------------------------------------------------*/ #ifndef SICSTOKEN #define SICSTOKEN - int TokenInit(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); +int TokenInit(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); /* - The Token Factory function. - */ - int TokenWrapper(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - + The Token Factory function. + */ +int TokenWrapper(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + /* - The wrapper function for the token command. - */ - - int TokenGrabActive(void); + The wrapper function for the token command. + */ + +int TokenGrabActive(void); /* Returns 1, if a token grab is active, else 0 - */ - - void TokenRelease(void); + */ + +void TokenRelease(void); /* - Releases a Token Grab - */ -#endif + Releases a Token Grab + */ +#endif diff --git a/trigd.c b/trigd.c index f8167ed0..53a39065 100644 --- a/trigd.c +++ b/trigd.c @@ -15,98 +15,106 @@ /*******************************************************************************/ double Sign(double d) { - if(d < .0){ + if (d < .0) { return -1; } else { return 1; } } + /******************************************************************************* * Sinus of angle in degrees. *******************************************************************************/ -extern double Sind (double x) +extern double Sind(double x) { - return (sin (x*DEGREE_RAD)); + return (sin(x * DEGREE_RAD)); } + /******************************************************************************* * Tangens of angle in degrees. *******************************************************************************/ extern double Tand(double x) { - return (tan(x*DEGREE_RAD)); + return (tan(x * DEGREE_RAD)); } + /******************************************************************************* * cotangens of angle in degrees *****************************************************************************/ -extern double Cotd(double x){ - if(tan(x*DEGREE_RAD) > .00001){ - return (1./tan(x*DEGREE_RAD)); - } else { - return 0; - } -} +extern double Cotd(double x) +{ + if (tan(x * DEGREE_RAD) > .00001) { + return (1. / tan(x * DEGREE_RAD)); + } else { + return 0; + } +} + /******************************************************************************* * Cosinus of angle in degrees. *******************************************************************************/ -extern double Cosd (double x) +extern double Cosd(double x) { - return (cos (x*DEGREE_RAD)); + return (cos(x * DEGREE_RAD)); } + /******************************************************************************* * Atan of angle in degrees. *******************************************************************************/ -extern double Atand (double x) +extern double Atand(double x) { double data; - data = (atan(x)/DEGREE_RAD); + data = (atan(x) / DEGREE_RAD); return (data); } + /******************************************************************************* * Atan of angle in degrees. *******************************************************************************/ -extern double Atan2d (double x, double y) +extern double Atan2d(double x, double y) { double data; - data = (atan2(x,y)/DEGREE_RAD); + data = (atan2(x, y) / DEGREE_RAD); return (data); } + /******************************************************************************* * Atan2 of angle in degrees. *******************************************************************************/ -extern double Atand2 (double x) +extern double Atand2(double x) { double data; - data = (atan(x)/DEGREE_RAD); + data = (atan(x) / DEGREE_RAD); return (data); } + /******************************************************************************* * Acos of angle in degrees. *******************************************************************************/ -extern double Acosd (double x) +extern double Acosd(double x) { double data; - data = acos(x)/DEGREE_RAD; + data = acos(x) / DEGREE_RAD; return (data); } + /******************************************************************************* * Asin of angle in degrees. *******************************************************************************/ -extern double Asind (double x) +extern double Asind(double x) { double data; - data = x*x; + data = x * x; if (data == 1.0) - return (180.00 - Sign (x)*90.00); - else if (data > 1) - { + return (180.00 - Sign(x) * 90.00); + else if (data > 1) { return (0); - } - else - return (Atand (x/sqrt (1 - data))); + } else + return (Atand(x / sqrt(1 - data))); } diff --git a/trigd.h b/trigd.h index 7668bacc..1fdad191 100644 --- a/trigd.h +++ b/trigd.h @@ -6,14 +6,14 @@ */ #ifndef SICSTRIGD #define SICSTRIGD - double Sign(double d); - double Sind (double x); - double Tand(double x); - double Cotd(double x); - double Cosd (double x); - double Atand (double x); - double Atand2 (double x); - double Acosd (double x); - double Asind (double x); - double Atan2d(double x, double y); +double Sign(double d); +double Sind(double x); +double Tand(double x); +double Cotd(double x); +double Cosd(double x); +double Atand(double x); +double Atand2(double x); +double Acosd(double x); +double Asind(double x); +double Atan2d(double x, double y); #endif diff --git a/trim.c b/trim.c index 409c0809..b253a232 100644 --- a/trim.c +++ b/trim.c @@ -11,58 +11,52 @@ char *trim(char *str) { - char *ibuf = str, *obuf = str; - int i = 0, cnt = 0; + char *ibuf = str, *obuf = str; + int i = 0, cnt = 0; - /* - ** Trap NULL - */ + /* + ** Trap NULL + */ - if (str) - { - /* - ** Remove leading spaces (from RMLEAD.C) - */ + if (str) { + /* + ** Remove leading spaces (from RMLEAD.C) + */ - for (ibuf = str; *ibuf && isspace(*ibuf); ++ibuf) - ; - if (str != ibuf) - memmove(str, ibuf, ibuf - str); + for (ibuf = str; *ibuf && isspace(*ibuf); ++ibuf); + if (str != ibuf) + memmove(str, ibuf, ibuf - str); - /* - ** Collapse embedded spaces (from LV1WS.C) - */ + /* + ** Collapse embedded spaces (from LV1WS.C) + */ - while (*ibuf) - { - if (isspace(*ibuf) && cnt) - ibuf++; - else - { - if (!isspace(*ibuf)) - cnt = 0; - else - { - *ibuf = ' '; - cnt = 1; - } - obuf[i++] = *ibuf++; - } - } - obuf[i] = NUL; - - /* - ** Remove trailing spaces (from RMTRAIL.C) - */ - - while (--i >= 0) - { - if (!isspace(obuf[i])) - break; - } - obuf[++i] = NUL; + while (*ibuf) { + if (isspace(*ibuf) && cnt) + ibuf++; + else { + if (!isspace(*ibuf)) + cnt = 0; + else { + *ibuf = ' '; + cnt = 1; + } + obuf[i++] = *ibuf++; } - return str; + } + obuf[i] = NUL; + + /* + ** Remove trailing spaces (from RMTRAIL.C) + */ + + while (--i >= 0) { + if (!isspace(obuf[i])) + break; + } + obuf[++i] = NUL; + } + return str; } #ifdef TEST @@ -71,8 +65,8 @@ char *trim(char *str) main(int argc, char *argv[]) { - printf("trim(\"%s\") ", argv[1]); - printf("returned \"%s\"\n", trim(argv[1])); + printf("trim(\"%s\") ", argv[1]); + printf("returned \"%s\"\n", trim(argv[1])); } -#endif /* TEST */ +#endif /* TEST */ diff --git a/ubcalc.c b/ubcalc.c index 02054166..3c3146be 100644 --- a/ubcalc.c +++ b/ubcalc.c @@ -25,42 +25,47 @@ #include "reflist.h" #include "singlediff.h" /*----------------------------------------------------------------------*/ -static void killUBCALC(void *pData){ - pUBCALC self = (pUBCALC)pData; - if(self == NULL){ +static void killUBCALC(void *pData) +{ + pUBCALC self = (pUBCALC) pData; + if (self == NULL) { return; } - if(self->pDes != NULL){ + if (self->pDes != NULL) { DeleteDescriptor(self->pDes); } - if(self->UB != NULL){ + if (self->UB != NULL) { mat_free(self->UB); } free(self); } + /*--------------------------------------------------------------------*/ -static int SaveUBCalc(void *data, char *name, FILE *fd){ - pUBCALC self = (pUBCALC)data; - if(self == NULL){ +static int SaveUBCalc(void *data, char *name, FILE * fd) +{ + pUBCALC self = (pUBCALC) data; + if (self == NULL) { return 0; } - fprintf(fd,"%s difftheta %f\n", name, self->allowedDeviation); + fprintf(fd, "%s difftheta %f\n", name, self->allowedDeviation); fprintf(fd, "%s maxindex %d\n", name, self->indexSearchLimit); - fprintf(fd ,"%s maxlist %d\n", name, self->maxSuggestions); + fprintf(fd, "%s maxlist %d\n", name, self->maxSuggestions); return 1; } + /*---------------------------------------------------------------------*/ -static pUBCALC makeUBCALC(pHKL hkl){ +static pUBCALC makeUBCALC(pHKL hkl) +{ pUBCALC pNew = NULL; - pNew = (pUBCALC)malloc(sizeof(UBCALC)); - if(pNew == NULL){ + pNew = (pUBCALC) malloc(sizeof(UBCALC)); + if (pNew == NULL) { return NULL; } - memset(pNew,0,sizeof(UBCALC)); + memset(pNew, 0, sizeof(UBCALC)); pNew->pDes = CreateDescriptor("UBcalc"); - pNew->UB = mat_creat(3,3,UNIT_MATRIX); - if(pNew->pDes == NULL || pNew->UB == NULL){ + pNew->UB = mat_creat(3, 3, UNIT_MATRIX); + if (pNew->pDes == NULL || pNew->UB == NULL) { return NULL; } pNew->pDes->SaveStatus = SaveUBCalc; @@ -70,161 +75,176 @@ static pUBCALC makeUBCALC(pHKL hkl){ pNew->maxSuggestions = 10; return pNew; } + /*----------------------------------------------------------------------*/ -int CreateUBCalc(SConnection *pCon, SicsInterp *pSics, char *name, - char *hklname){ - pUBCALC pNew = NULL; - int status; - pHKL hkl = NULL; +int CreateUBCalc(SConnection * pCon, SicsInterp * pSics, char *name, + char *hklname) +{ + pUBCALC pNew = NULL; + int status; + pHKL hkl = NULL; - hkl = FindCommandData(pSics,hklname,"4-Circle-Calculus"); - if(hkl == NULL){ - SCWrite(pCon,"ERROR: HKL object not found or wrong type",eError); - return 0; - } + hkl = FindCommandData(pSics, hklname, "4-Circle-Calculus"); + if (hkl == NULL) { + SCWrite(pCon, "ERROR: HKL object not found or wrong type", eError); + return 0; + } - pNew = makeUBCALC(hkl); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating UBCALC",eError); - return 0; - } - status = AddCommand(pSics,name,UBCalcWrapper,killUBCALC,pNew); - if(status != 1){ - SCWrite(pCon,"ERROR: failed to create duplicate UBCALC module",eError); - } - return status; + pNew = makeUBCALC(hkl); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating UBCALC", eError); + return 0; + } + status = AddCommand(pSics, name, UBCalcWrapper, killUBCALC, pNew); + if (status != 1) { + SCWrite(pCon, "ERROR: failed to create duplicate UBCALC module", + eError); + } + return status; } + /*----------------------------------------------------------------------*/ -int MakeUBCalc(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int MakeUBCalc(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ - if(argc < 3){ - SCWrite(pCon,"ERROR: missing argument to MakeUBCalc: MakeUBCalc name hklobject",eError); - return 0; - } - return CreateUBCalc(pCon,pSics,argv[1], argv[2]); + if (argc < 3) { + SCWrite(pCon, + "ERROR: missing argument to MakeUBCalc: MakeUBCalc name hklobject", + eError); + return 0; + } + return CreateUBCalc(pCon, pSics, argv[1], argv[2]); } + /*---------------------------------------------------------------------*/ -static void listUB(SConnection *pCon, MATRIX UB){ +static void listUB(SConnection * pCon, MATRIX UB) +{ Tcl_DString list; char pBueffel[255]; int i; Tcl_DStringInit(&list); - if(UB == NULL){ - Tcl_DStringAppend(&list,"NO UB",-1); + if (UB == NULL) { + Tcl_DStringAppend(&list, "NO UB", -1); } else { - Tcl_DStringAppend(&list,"UB = ", -1); - for(i = 0; i < 3; i++){ - snprintf(pBueffel,255,"%f %f %f\n", UB[i][0], - UB[i][1],UB[i][2]); - Tcl_DStringAppend(&list,pBueffel,-1); + Tcl_DStringAppend(&list, "UB = ", -1); + for (i = 0; i < 3; i++) { + snprintf(pBueffel, 255, "%f %f %f\n", UB[i][0], UB[i][1], UB[i][2]); + Tcl_DStringAppend(&list, pBueffel, -1); } } - SCWrite(pCon,Tcl_DStringValue(&list),eValue); + SCWrite(pCon, Tcl_DStringValue(&list), eValue); Tcl_DStringFree(&list); } + /*---------------------------------------------------------------------*/ -static int updateUBCALC(pUBCALC self, SConnection *pCon, - char *id1, char *id2, char *id3){ - const double *cell; - double hkl[3], angles[4]; - pSICSOBJ refList; - - cell = SXGetCell(); - self->direct.a = cell[0]; - self->direct.b = cell[1]; - self->direct.c = cell[2]; - self->direct.alpha = cell[3]; - self->direct.beta = cell[4]; - self->direct.gamma = cell[5]; +static int updateUBCALC(pUBCALC self, SConnection * pCon, + char *id1, char *id2, char *id3) +{ + const double *cell; + double hkl[3], angles[4]; + pSICSOBJ refList; - refList = SXGetReflectionList(); - if(id1 != NULL){ - if(!GetRefIndexID(refList,id1,hkl)){ - SCPrintf(pCon,eError,"ERROR: reflection with id %s not found",id1); - return 0; - } else { - self->r1.h = hkl[0]; - self->r1.k = hkl[1]; - self->r1.l = hkl[2]; - GetRefAnglesID(refList,id1,angles); - self->r1.s2t = angles[0]; - self->r1.om = angles[1]; - self->r1.chi = angles[2]; - self->r1.phi = angles[3]; - } - } + cell = SXGetCell(); + self->direct.a = cell[0]; + self->direct.b = cell[1]; + self->direct.c = cell[2]; + self->direct.alpha = cell[3]; + self->direct.beta = cell[4]; + self->direct.gamma = cell[5]; - if(id2 != NULL){ - if(!GetRefIndexID(refList,id2,hkl)){ - SCPrintf(pCon,eError,"ERROR: reflection with id %s not found",id2); - return 0; - } else { - self->r2.h = hkl[0]; - self->r2.k = hkl[1]; - self->r2.l = hkl[2]; - GetRefAnglesID(refList,id2,angles); - self->r2.s2t = angles[0]; - self->r2.om = angles[1]; - self->r2.chi = angles[2]; - self->r2.phi = angles[3]; - } - } - if(id3 != NULL){ - if(!GetRefIndexID(refList,id3,hkl)){ - SCPrintf(pCon,eError,"ERROR: reflection with id %s not found",id3); - return 0; - } else { - self->r3.h = hkl[0]; - self->r3.k = hkl[1]; - self->r3.l = hkl[2]; - GetRefAnglesID(refList,id3,angles); - self->r3.s2t = angles[0]; - self->r3.om = angles[1]; - self->r3.chi = angles[2]; - self->r3.phi = angles[3]; - } - } - return 1; + refList = SXGetReflectionList(); + if (id1 != NULL) { + if (!GetRefIndexID(refList, id1, hkl)) { + SCPrintf(pCon, eError, "ERROR: reflection with id %s not found", + id1); + return 0; + } else { + self->r1.h = hkl[0]; + self->r1.k = hkl[1]; + self->r1.l = hkl[2]; + GetRefAnglesID(refList, id1, angles); + self->r1.s2t = angles[0]; + self->r1.om = angles[1]; + self->r1.chi = angles[2]; + self->r1.phi = angles[3]; + } + } + + if (id2 != NULL) { + if (!GetRefIndexID(refList, id2, hkl)) { + SCPrintf(pCon, eError, "ERROR: reflection with id %s not found", + id2); + return 0; + } else { + self->r2.h = hkl[0]; + self->r2.k = hkl[1]; + self->r2.l = hkl[2]; + GetRefAnglesID(refList, id2, angles); + self->r2.s2t = angles[0]; + self->r2.om = angles[1]; + self->r2.chi = angles[2]; + self->r2.phi = angles[3]; + } + } + if (id3 != NULL) { + if (!GetRefIndexID(refList, id3, hkl)) { + SCPrintf(pCon, eError, "ERROR: reflection with id %s not found", + id3); + return 0; + } else { + self->r3.h = hkl[0]; + self->r3.k = hkl[1]; + self->r3.l = hkl[2]; + GetRefAnglesID(refList, id3, angles); + self->r3.s2t = angles[0]; + self->r3.om = angles[1]; + self->r3.chi = angles[2]; + self->r3.phi = angles[3]; + } + } + return 1; } + /*---------------------------------------------------------------------*/ -static int calcUB(pUBCALC self, SConnection *pCon, - char *ref1, char *ref2){ +static int calcUB(pUBCALC self, SConnection * pCon, char *ref1, char *ref2) +{ MATRIX newUB = NULL; int err = 1; pSingleDiff single = NULL; - - if(!updateUBCALC(self,pCon,ref1,ref2,NULL)){ - return 0; + + if (!updateUBCALC(self, pCon, ref1, ref2, NULL)) { + return 0; } - + single = SXGetDiffractometer(); assert(single != NULL); - - newUB = single->calcUBFromTwo(single,ref1, ref2, &err); - if(newUB == NULL){ - switch(err){ + + newUB = single->calcUBFromTwo(single, ref1, ref2, &err); + if (newUB == NULL) { + switch (err) { case REFERR: - SCWrite(pCon,"ERROR: one of reflections ID's is invalid",eError); - return 0; - break; + SCWrite(pCon, "ERROR: one of reflections ID's is invalid", eError); + return 0; + break; case UBNOMEMORY: - SCWrite(pCon,"ERROR: out of memory while calculating UB",eError); + SCWrite(pCon, "ERROR: out of memory while calculating UB", eError); return 0; break; case REC_NO_VOLUME: - SCWrite(pCon,"ERROR: bad cell constants",eError); + SCWrite(pCon, "ERROR: bad cell constants", eError); return 0; break; default: - SCWrite(pCon,"ERROR: unknown error on UB matrix calculation",eError); + SCWrite(pCon, "ERROR: unknown error on UB matrix calculation", + eError); return 0; } } else { - if(self->UB != NULL){ + if (self->UB != NULL) { mat_free(self->UB); } self->UB = newUB; @@ -232,45 +252,49 @@ static int calcUB(pUBCALC self, SConnection *pCon, return 1; } } + /*---------------------------------------------------------------------*/ -static int sendUBToHKL(SConnection *pCon, SicsInterp *pSics, - pHKL hkl, MATRIX UB){ +static int sendUBToHKL(SConnection * pCon, SicsInterp * pSics, + pHKL hkl, MATRIX UB) +{ float ub[9]; int i; assert(hkl != NULL); - for(i = 0; i < 3; i++){ - ub[i] = UB[0][i]; - ub[i+3] = UB[1][i]; - ub[i+6] = UB[2][i]; + for (i = 0; i < 3; i++) { + ub[i] = UB[0][i]; + ub[i + 3] = UB[1][i]; + ub[i + 6] = UB[2][i]; } - SetUB(hkl,ub); + SetUB(hkl, ub); SCSendOK(pCon); return 1; -} -/*---------------------------------------------------------------------*/ -static int setUBCalcParameters(pUBCALC self, SConnection *pCon, - char *name, char *value){ +} - if(strcmp(name,"difftheta") == 0){ - if(!SCMatchRights(pCon,usUser)){ +/*---------------------------------------------------------------------*/ +static int setUBCalcParameters(pUBCALC self, SConnection * pCon, + char *name, char *value) +{ + + if (strcmp(name, "difftheta") == 0) { + if (!SCMatchRights(pCon, usUser)) { return 0; } self->allowedDeviation = atof(value); SCparChange(pCon); SCSendOK(pCon); return 1; - } else if(strcmp(name,"maxindex") == 0){ - if(!SCMatchRights(pCon,usUser)){ + } else if (strcmp(name, "maxindex") == 0) { + if (!SCMatchRights(pCon, usUser)) { return 0; } self->indexSearchLimit = atoi(value); SCparChange(pCon); SCSendOK(pCon); return 1; - } else if(strcmp(name,"maxlist") == 0){ - if(!SCMatchRights(pCon,usUser)){ + } else if (strcmp(name, "maxlist") == 0) { + if (!SCMatchRights(pCon, usUser)) { return 0; } self->maxSuggestions = atoi(value); @@ -278,45 +302,56 @@ static int setUBCalcParameters(pUBCALC self, SConnection *pCon, SCSendOK(pCon); return 1; } else { - SCWrite(pCon,"ERROR: subcommand not recognized",eError); + SCWrite(pCon, "ERROR: subcommand not recognized", eError); return 0; } } + /*---------------------------------------------------------------------*/ -static int getUBCalcParameters(pUBCALC self, SConnection *pCon, char *name){ +static int getUBCalcParameters(pUBCALC self, SConnection * pCon, + char *name) +{ char pBueffel[255]; int ret = 0; - if(strcmp(name,"difftheta") == 0){ - snprintf(pBueffel,255,"ubcalc.difftheta = %f",self->allowedDeviation); + if (strcmp(name, "difftheta") == 0) { + snprintf(pBueffel, 255, "ubcalc.difftheta = %f", + self->allowedDeviation); ret = 1; - } else if(strcmp(name,"maxindex") == 0){ - snprintf(pBueffel,255,"ubcalc.maxindex = %d", self->indexSearchLimit); + } else if (strcmp(name, "maxindex") == 0) { + snprintf(pBueffel, 255, "ubcalc.maxindex = %d", + self->indexSearchLimit); ret = 1; - } else if(strcmp(name,"maxlist") == 0){ - snprintf(pBueffel,255,"ubcalc.maxindex = %d", self->maxSuggestions); + } else if (strcmp(name, "maxlist") == 0) { + snprintf(pBueffel, 255, "ubcalc.maxindex = %d", self->maxSuggestions); ret = 1; } else { - snprintf(pBueffel,255,"ERROR: subcommand not known"); + snprintf(pBueffel, 255, "ERROR: subcommand not known"); } - SCWrite(pCon,pBueffel,eValue); + SCWrite(pCon, pBueffel, eValue); return ret; } + /*---------------------------------------------------------------------*/ -static void listPar(pUBCALC self, char *name, SConnection *pCon){ +static void listPar(pUBCALC self, char *name, SConnection * pCon) +{ char pBueffel[255]; - snprintf(pBueffel,255,"%s.difftheta = %f", name, self->allowedDeviation); - SCWrite(pCon,pBueffel,eValue); - snprintf(pBueffel,255,"%s.maxindex = %d", name, self->indexSearchLimit); - SCWrite(pCon,pBueffel,eValue); - snprintf(pBueffel,255,"%s.maxlist = %d", name, self->maxSuggestions); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "%s.difftheta = %f", name, + self->allowedDeviation); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.maxindex = %d", name, + self->indexSearchLimit); + SCWrite(pCon, pBueffel, eValue); + snprintf(pBueffel, 255, "%s.maxlist = %d", name, self->maxSuggestions); + SCWrite(pCon, pBueffel, eValue); } + /*---------------------------------------------------------------------*/ -static int findIndex(pUBCALC self, SConnection *pCon, SicsInterp *pSics, - int argc, char *argv[]){ +static int findIndex(pUBCALC self, SConnection * pCon, SicsInterp * pSics, + int argc, char *argv[]) +{ float two_theta; pMotor pMot = NULL; int status, numRef, i; @@ -324,104 +359,109 @@ static int findIndex(pUBCALC self, SConnection *pCon, SicsInterp *pSics, Tcl_DString list; char pLine[255]; double lambda; - - if(argc > 2){ + + if (argc > 2) { two_theta = atof(argv[2]); } else { pMot = SXGetMotor(TwoTheta); - if(pMot == NULL){ - SCWrite(pCon,"ERROR: cannot find stt motor",eError); + if (pMot == NULL) { + SCWrite(pCon, "ERROR: cannot find stt motor", eError); return 0; } - MotorGetSoftPosition(pMot,pCon,&two_theta); + MotorGetSoftPosition(pMot, pCon, &two_theta); } lambda = SXGetLambda(); - updateUBCALC(self,pCon,NULL,NULL,NULL); - + updateUBCALC(self, pCon, NULL, NULL, NULL); + numRef = self->maxSuggestions; - index = (refIndex *)malloc(numRef*sizeof(refIndex)); - if(index == NULL){ - SCWrite(pCon,"ERROR: out of memory allocating index list",eError); + index = (refIndex *) malloc(numRef * sizeof(refIndex)); + if (index == NULL) { + SCWrite(pCon, "ERROR: out of memory allocating index list", eError); return 0; } - memset(index,0,numRef*sizeof(refIndex)); + memset(index, 0, numRef * sizeof(refIndex)); - status = searchIndex(self->direct,lambda, two_theta,self->allowedDeviation, - self->indexSearchLimit, index, numRef); + status = + searchIndex(self->direct, lambda, two_theta, self->allowedDeviation, + self->indexSearchLimit, index, numRef); - if(status < 0){ - if(status == UBNOMEMORY){ - SCWrite(pCon,"ERROR: out of memory searching indices",eError); + if (status < 0) { + if (status == UBNOMEMORY) { + SCWrite(pCon, "ERROR: out of memory searching indices", eError); return 0; - } else if(status == REC_NO_VOLUME){ - SCWrite(pCon,"ERROR: bad cell parameters",eError); + } else if (status == REC_NO_VOLUME) { + SCWrite(pCon, "ERROR: bad cell parameters", eError); return 0; } else { - SCWrite(pCon,"ERROR: unknown error code",eError); + SCWrite(pCon, "ERROR: unknown error code", eError); return 0; } } - if(status < numRef) { + if (status < numRef) { numRef = status; } Tcl_DStringInit(&list); - for(i = 0; i < numRef; i++){ - snprintf(pLine,255," %3d %3d %3d %8.2f %8.2f %8.2f\r\n", - (int)index[i].h, (int)index[i].k, (int)index[i].l, - two_theta, index[i].t2calc,index[i].t2diff); - Tcl_DStringAppend(&list,pLine,-1); + for (i = 0; i < numRef; i++) { + snprintf(pLine, 255, " %3d %3d %3d %8.2f %8.2f %8.2f\r\n", + (int) index[i].h, (int) index[i].k, (int) index[i].l, + two_theta, index[i].t2calc, index[i].t2diff); + Tcl_DStringAppend(&list, pLine, -1); } - if(numRef == 0){ - Tcl_DStringAppend(&list,"No suitable reflections found",-1); + if (numRef == 0) { + Tcl_DStringAppend(&list, "No suitable reflections found", -1); } - SCWrite(pCon,Tcl_DStringValue(&list),eValue); + SCWrite(pCon, Tcl_DStringValue(&list), eValue); Tcl_DStringFree(&list); free(index); return 1; } + /*---------------------------------------------------------------------*/ -static int calcUB3Ref(pUBCALC self, SConnection *pCon, - char *id1, char *id2, char *id3){ +static int calcUB3Ref(pUBCALC self, SConnection * pCon, + char *id1, char *id2, char *id3) +{ double lambda; MATRIX newUB = NULL; int errCode = 1; char pBueffel[256]; pSingleDiff single = NULL; - + lambda = SXGetLambda(); - if(!updateUBCALC(self, pCon, id1, id2, id3)){ - return 0; + if (!updateUBCALC(self, pCon, id1, id2, id3)) { + return 0; } - + single = SXGetDiffractometer(); assert(single != NULL); - - newUB = single->calcUBFromThree(single,id1, id2, id3, &errCode); - if(newUB == NULL){ - switch(errCode){ + + newUB = single->calcUBFromThree(single, id1, id2, id3, &errCode); + if (newUB == NULL) { + switch (errCode) { case REFERR: - SCWrite(pCon,"ERROR: one of reflections ID's is invalid",eError); - return 0; - break; + SCWrite(pCon, "ERROR: one of reflections ID's is invalid", eError); + return 0; + break; case UBNOMEMORY: - SCWrite(pCon,"ERROR: out of memory calculating UB",eError); + SCWrite(pCon, "ERROR: out of memory calculating UB", eError); break; case INVALID_LAMBDA: - SCWrite(pCon,"ERROR: bad value for wavelength",eError); + SCWrite(pCon, "ERROR: bad value for wavelength", eError); break; case NOTRIGHTHANDED: - SCWrite(pCon,"ERROR: reflections are coplanar or do not form a right handed system", - eError); + SCWrite(pCon, + "ERROR: reflections are coplanar or do not form a right handed system", + eError); break; default: - SCWrite(pCon,"ERROR: unknown error code from UB calculation",eError); + SCWrite(pCon, "ERROR: unknown error code from UB calculation", + eError); break; } return 0; } else { - if(self->UB != NULL){ + if (self->UB != NULL) { mat_free(self->UB); } self->UB = newUB; @@ -429,109 +469,117 @@ static int calcUB3Ref(pUBCALC self, SConnection *pCon, } return 1; } + /*--------------------------------------------------------------------*/ -static int cellFromUBWrapper(pUBCALC self, SConnection *pCon){ +static int cellFromUBWrapper(pUBCALC self, SConnection * pCon) +{ int status; char pBueffel[256]; lattice direct; const double *ub; MATRIX UB; int i; - - UB = mat_creat(3,3,UNIT_MATRIX); + + UB = mat_creat(3, 3, UNIT_MATRIX); ub = SXGetUB(); - for(i = 0; i < 3; i++){ - UB[0][i] = ub[i]; - UB[1][i] = ub[i+3]; - UB[2][i] = ub[i+6]; + for (i = 0; i < 3; i++) { + UB[0][i] = ub[i]; + UB[1][i] = ub[i + 3]; + UB[2][i] = ub[i + 6]; } - - status = cellFromUB(UB,&direct); + + status = cellFromUB(UB, &direct); mat_free(UB); - - if(status < 0){ - switch(status){ + + if (status < 0) { + switch (status) { case CELLNOMEMORY: - SCWrite(pCon,"ERROR: out of memory while calculating cell",eError); + SCWrite(pCon, "ERROR: out of memory while calculating cell", eError); break; default: - SCWrite(pCon,"ERROR: unknown error calculating cell",eError); + SCWrite(pCon, "ERROR: unknown error calculating cell", eError); break; } return 0; } else { - snprintf(pBueffel,255,"%f %f %f %f %f %f", - direct.a, direct.b, direct.c, - direct.alpha, direct.beta, direct.gamma); - SCWrite(pCon,pBueffel,eValue); + snprintf(pBueffel, 255, "%f %f %f %f %f %f", + direct.a, direct.b, direct.c, + direct.alpha, direct.beta, direct.gamma); + SCWrite(pCon, pBueffel, eValue); } return 1; } + /*----------------------------------------------------------------------*/ -int UBCalcWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pUBCALC self = (pUBCALC)pData; +int UBCalcWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pUBCALC self = (pUBCALC) pData; char pBuffer[512]; - + assert(self); - if(argc < 2){ - SCWrite(pCon,"Insuffcient number of arguments to ubcalc",eError); - return 0; + if (argc < 2) { + SCWrite(pCon, "Insuffcient number of arguments to ubcalc", eError); + return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"listub") == 0){ - listUB(pCon,self->UB); + if (strcmp(argv[1], "listub") == 0) { + listUB(pCon, self->UB); return 1; - } else if(strcmp(argv[1],"ub2ref") == 0){ - if(argc < 4){ - SCWrite(pCon,"Insuffcient number of arguments to ubcalc ub2ref",eError); - return 0; - } - return calcUB(self,pCon, argv[2], argv[3]); - } else if(strcmp(argv[1],"ub3ref") == 0){ - if(argc < 5){ - SCWrite(pCon,"Insuffcient number of arguments to ubcalc ub3ref",eError); - return 0; - } - return calcUB3Ref(self,pCon,argv[2],argv[3],argv[4]); - } else if(strcmp(argv[1],"cellub") == 0){ - return cellFromUBWrapper(self,pCon); - }else if(strcmp(argv[1],"list") == 0){ - listUB(pCon,self->UB); - listPar(self,argv[0],pCon); + } else if (strcmp(argv[1], "ub2ref") == 0) { + if (argc < 4) { + SCWrite(pCon, "Insuffcient number of arguments to ubcalc ub2ref", + eError); + return 0; + } + return calcUB(self, pCon, argv[2], argv[3]); + } else if (strcmp(argv[1], "ub3ref") == 0) { + if (argc < 5) { + SCWrite(pCon, "Insuffcient number of arguments to ubcalc ub3ref", + eError); + return 0; + } + return calcUB3Ref(self, pCon, argv[2], argv[3], argv[4]); + } else if (strcmp(argv[1], "cellub") == 0) { + return cellFromUBWrapper(self, pCon); + } else if (strcmp(argv[1], "list") == 0) { + listUB(pCon, self->UB); + listPar(self, argv[0], pCon); return 1; - } else if(strcmp(argv[1],"activate") == 0){ - return sendUBToHKL(pCon,pSics,self->hkl,self->UB); - } else if(strcmp(argv[1],"index") == 0){ - return findIndex(self,pCon,pSics,argc, argv); + } else if (strcmp(argv[1], "activate") == 0) { + return sendUBToHKL(pCon, pSics, self->hkl, self->UB); + } else if (strcmp(argv[1], "index") == 0) { + return findIndex(self, pCon, pSics, argc, argv); } else { - if(argc > 2){ - return setUBCalcParameters(self,pCon,argv[1],argv[2]); + if (argc > 2) { + return setUBCalcParameters(self, pCon, argv[1], argv[2]); } else { - return getUBCalcParameters(self,pCon,argv[1]); + return getUBCalcParameters(self, pCon, argv[1]); } } return 1; } + /*------------------------------------------------------------------------*/ -reflection getReflection(void *ubcalc, int no){ - pUBCALC self = (pUBCALC)ubcalc; - - assert(self != NULL); - - switch(no){ - case 0: - return self->r1; - break; - case 1: - return self->r2; - break; - case 2: - return self->r3; - break; - default: - assert(0); - break; - } +reflection getReflection(void *ubcalc, int no) +{ + pUBCALC self = (pUBCALC) ubcalc; + + assert(self != NULL); + + switch (no) { + case 0: + return self->r1; + break; + case 1: + return self->r2; + break; + case 2: + return self->r3; + break; + default: + assert(0); + break; + } } diff --git a/ubcalc.h b/ubcalc.h index 2cea5157..1807d932 100644 --- a/ubcalc.h +++ b/ubcalc.h @@ -27,11 +27,12 @@ typedef struct { int maxSuggestions; } UBCALC, *pUBCALC; /*-------------------------------------------------------------------*/ -int MakeUBCalc(SConnection *pCon,SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int CreateUBCalc(SConnection *pCon,SicsInterp *pSics, char *name, char *hkl); -int UBCalcWrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +int MakeUBCalc(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int CreateUBCalc(SConnection * pCon, SicsInterp * pSics, char *name, + char *hkl); +int UBCalcWrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + reflection getReflection(void *ubcalc, int no); -#endif +#endif diff --git a/ubfour.c b/ubfour.c index e79a5788..ec571162 100644 --- a/ubfour.c +++ b/ubfour.c @@ -17,14 +17,15 @@ #include "trigd.h" #include "fourlib.h" #include "lld.h" -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*--------------------------------------------------------------------------------------*/ -static MATRIX calcUVectorFromAngles(reflection r){ +static MATRIX calcUVectorFromAngles(reflection r) +{ MATRIX u; double om; u = makeVector(); - if(u == NULL){ + if (u == NULL) { return NULL; } /* @@ -32,32 +33,38 @@ static MATRIX calcUVectorFromAngles(reflection r){ * position. This is why we have to correct for two_theta/2 here in order * to arrive at the proper rotation around the omega axis. */ - om = r.om - r.s2t/2.; - vectorSet(u,0,Cosd(om)*Cosd(r.chi)*Cosd(r.phi) - Sind(om)*Sind(r.phi)); - vectorSet(u,1,Cosd(om)*Cosd(r.chi)*Sind(r.phi) + Sind(om)*Cosd(r.phi)); - vectorSet(u,2,Cosd(om)*Sind(r.chi)); - return u; + om = r.om - r.s2t / 2.; + vectorSet(u, 0, + Cosd(om) * Cosd(r.chi) * Cosd(r.phi) - Sind(om) * Sind(r.phi)); + vectorSet(u, 1, + Cosd(om) * Cosd(r.chi) * Sind(r.phi) + Sind(om) * Cosd(r.phi)); + vectorSet(u, 2, Cosd(om) * Sind(r.chi)); + return u; } + /*--------------------------------------------------------------------------------------*/ -static MATRIX reflectionToHC(reflection r, MATRIX B){ +static MATRIX reflectionToHC(reflection r, MATRIX B) +{ MATRIX h = NULL, hc = NULL; h = makeVector(); - if(h == NULL){ + if (h == NULL) { return NULL; } - vectorSet(h,0,r.h); - vectorSet(h,1,r.k); - vectorSet(h,2,r.l); + vectorSet(h, 0, r.h); + vectorSet(h, 1, r.k); + vectorSet(h, 2, r.l); - hc = mat_mul(B,h); + hc = mat_mul(B, h); killVector(h); return hc; } + /*---------------------------------------------------------------------------------------*/ -MATRIX calcUBFromCellAndReflections(lattice direct, reflection r1, - reflection r2, int *errCode){ - MATRIX B, HT, UT, U, UB, HTT ; +MATRIX calcUBFromCellAndReflections(lattice direct, reflection r1, + reflection r2, int *errCode) +{ + MATRIX B, HT, UT, U, UB, HTT; MATRIX u1, u2, h1, h2; double ud[3]; int status; @@ -66,72 +73,72 @@ MATRIX calcUBFromCellAndReflections(lattice direct, reflection r1, *errCode = 1; /* - calculate the B matrix and the HT matrix - */ - B = mat_creat(3,3,ZERO_MATRIX); - status = calculateBMatrix(direct,B); - if(status < 0){ + calculate the B matrix and the HT matrix + */ + B = mat_creat(3, 3, ZERO_MATRIX); + status = calculateBMatrix(direct, B); + if (status < 0) { *errCode = status; return NULL; } - h1 = reflectionToHC(r1,B); - h2 = reflectionToHC(r2,B); - if(h1 == NULL || h2 == NULL){ + h1 = reflectionToHC(r1, B); + h2 = reflectionToHC(r2, B); + if (h1 == NULL || h2 == NULL) { *errCode = UBNOMEMORY; return NULL; } - HT = matFromTwoVectors(h1,h2); - if(HT == NULL){ + HT = matFromTwoVectors(h1, h2); + if (HT == NULL) { *errCode = UBNOMEMORY; return NULL; } /* - calculate U vectors and UT matrix - */ + calculate U vectors and UT matrix + */ u1 = calcUVectorFromAngles(r1); u2 = calcUVectorFromAngles(r2); - if(u1 == NULL || u2 == NULL){ + if (u1 == NULL || u2 == NULL) { *errCode = UBNOMEMORY; return NULL; } - UT = matFromTwoVectors(u1,u2); - if(UT == NULL){ + UT = matFromTwoVectors(u1, u2); + if (UT == NULL) { *errCode = UBNOMEMORY; return NULL; } /* - debugging output - printf("B-matrix\n"); - mat_dump(B); - printf("HT-matrix\n"); - mat_dump(HT); - printf("UT-matrix\n"); - mat_dump(UT); - */ + debugging output + printf("B-matrix\n"); + mat_dump(B); + printf("HT-matrix\n"); + mat_dump(HT); + printf("UT-matrix\n"); + mat_dump(UT); + */ /* - UT = U * HT - */ + UT = U * HT + */ HTT = mat_tran(HT); - if(HTT == NULL){ + if (HTT == NULL) { *errCode = UBNOMEMORY; return NULL; } - U = mat_mul(UT,HTT); - if(U == NULL){ - *errCode = UBNOMEMORY; + U = mat_mul(UT, HTT); + if (U == NULL) { + *errCode = UBNOMEMORY; return NULL; } - UB = mat_mul(U,B); - if(UB == NULL){ + UB = mat_mul(U, B); + if (UB == NULL) { *errCode = UBNOMEMORY; } /* - clean up - */ + clean up + */ killVector(h1); killVector(h2); mat_free(HT); @@ -139,16 +146,18 @@ MATRIX calcUBFromCellAndReflections(lattice direct, reflection r1, killVector(u1); killVector(u2); - mat_free(UT); + mat_free(UT); mat_free(U); mat_free(B); return UB; } + /*-----------------------------------------------------------------------------------*/ -static void storeReflection(reflection r, double two_theta_obs, - double two_theta_calc, int list){ +static void storeReflection(reflection r, double two_theta_obs, + double two_theta_calc, int list) +{ refIndex ri, test; int count = 0, status, pos = 0; @@ -160,85 +169,91 @@ static void storeReflection(reflection r, double two_theta_obs, ri.t2diff = ABS(two_theta_obs - two_theta_calc); /* - locate the last entry bigger then us - */ + locate the last entry bigger then us + */ status = LLDnodePtr2First(list); - while(status == 1){ - LLDnodeDataTo(list,&test); + while (status == 1) { + LLDnodeDataTo(list, &test); count++; - if(test.t2diff == ri.t2diff){ - LLDnodeDataFrom(list,&ri); + if (test.t2diff == ri.t2diff) { + LLDnodeDataFrom(list, &ri); return; } - if(test.t2diff > ri.t2diff){ + if (test.t2diff > ri.t2diff) { break; } status = LLDnodePtr2Next(list); } /* - special case: empty list - */ - if(count == 0){ - LLDnodeAppendFrom(list,&ri); + special case: empty list + */ + if (count == 0) { + LLDnodeAppendFrom(list, &ri); return; } /* - special case: append after last - */ + special case: append after last + */ LLDnodePtr2Last(list); - LLDnodeDataTo(list,&test); - if(ri.t2diff > test.t2diff){ - LLDnodeAppendFrom(list,&ri); + LLDnodeDataTo(list, &test); + if (ri.t2diff > test.t2diff) { + LLDnodeAppendFrom(list, &ri); return; } status = LLDnodePtr2First(list); pos = 0; - while(status == 1){ - LLDnodeDataTo(list,&test); + while (status == 1) { + LLDnodeDataTo(list, &test); pos++; - if(pos == count){ - LLDnodeInsertFrom(list,&ri); + if (pos == count) { + LLDnodeInsertFrom(list, &ri); return; } status = LLDnodePtr2Next(list); } } + /*---------------------------------------------------------------------------- u_transform(i) = u(i)*(2*sin(theta)/lambda) - -----------------------------------------------------------------------------*/ -static void uToScatteringVector(MATRIX u, double theta, double lambda){ + -----------------------------------------------------------------------------*/ +static void uToScatteringVector(MATRIX u, double theta, double lambda) +{ double scale; int i; - scale = (2. * Sind(theta))/lambda; - for(i = 0; i < 3; i++){ + scale = (2. * Sind(theta)) / lambda; + for (i = 0; i < 3; i++) { u[i][0] *= scale; } } + /*----------------------------------------------------------------------------*/ -static MATRIX buildHCHIMatrix(MATRIX u1, MATRIX u2, MATRIX u3){ +static MATRIX buildHCHIMatrix(MATRIX u1, MATRIX u2, MATRIX u3) +{ int i; MATRIX HCHI; - HCHI = mat_creat(3,3,ZERO_MATRIX); - if(HCHI == NULL){ + HCHI = mat_creat(3, 3, ZERO_MATRIX); + if (HCHI == NULL) { return NULL; } - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { HCHI[i][0] = u1[i][0]; HCHI[i][1] = u2[i][0]; HCHI[i][2] = u3[i][0]; } return HCHI; } + /*----------------------------------------------------------------------------*/ -static MATRIX buildIndexMatrix(reflection r1, reflection r2, reflection r3){ +static MATRIX buildIndexMatrix(reflection r1, reflection r2, reflection r3) +{ MATRIX HI; int i; - HI = mat_creat(3,3,ZERO_MATRIX); - if(HI == NULL){ + HI = mat_creat(3, 3, ZERO_MATRIX); + if (HI == NULL) { return NULL; } HI[0][0] = r1.h; @@ -255,13 +270,16 @@ static MATRIX buildIndexMatrix(reflection r1, reflection r2, reflection r3){ return HI; } + /*-----------------------------------------------------------------------------*/ -MATRIX calcUBFromThreeReflections(reflection r1, reflection r2, reflection r3, - double lambda, int *errCode){ - MATRIX u1, u2, u3, HCHI, HI, HIINV, UB; +MATRIX calcUBFromThreeReflections(reflection r1, reflection r2, + reflection r3, double lambda, + int *errCode) +{ + MATRIX u1, u2, u3, HCHI, HI, HIINV, UB; double det; - if(lambda <= .1){ + if (lambda <= .1) { *errCode = INVALID_LAMBDA; return NULL; } @@ -271,13 +289,13 @@ MATRIX calcUBFromThreeReflections(reflection r1, reflection r2, reflection r3, u1 = calcUVectorFromAngles(r1); u2 = calcUVectorFromAngles(r2); u3 = calcUVectorFromAngles(r3); - uToScatteringVector(u1,r1.s2t/2.,lambda); - uToScatteringVector(u2,r2.s2t/2.,lambda); - uToScatteringVector(u3,r3.s2t/2.,lambda); - - HCHI = buildHCHIMatrix(u1,u2,u3); - HI = buildIndexMatrix(r1,r2,r3); - if(HCHI == NULL || HI == NULL){ + uToScatteringVector(u1, r1.s2t / 2., lambda); + uToScatteringVector(u2, r2.s2t / 2., lambda); + uToScatteringVector(u3, r3.s2t / 2., lambda); + + HCHI = buildHCHIMatrix(u1, u2, u3); + HI = buildIndexMatrix(r1, r2, r3); + if (HCHI == NULL || HI == NULL) { *errCode = UBNOMEMORY; killVector(u1); killVector(u2); @@ -286,7 +304,7 @@ MATRIX calcUBFromThreeReflections(reflection r1, reflection r2, reflection r3, } HIINV = mat_inv(HI); - if(HIINV == NULL){ + if (HIINV == NULL) { *errCode = NOTRIGHTHANDED; killVector(u1); killVector(u2); @@ -295,10 +313,10 @@ MATRIX calcUBFromThreeReflections(reflection r1, reflection r2, reflection r3, mat_free(HCHI); return NULL; } - UB = mat_mul(HCHI,HIINV); + UB = mat_mul(HCHI, HIINV); det = mat_det(UB); - if(det < .0){ + if (det < .0) { mat_free(UB); UB = NULL; *errCode = NOTRIGHTHANDED; @@ -310,204 +328,215 @@ MATRIX calcUBFromThreeReflections(reflection r1, reflection r2, reflection r3, mat_free(HI); mat_free(HCHI); mat_free(HIINV); - + return UB; } + /*---------------------------------------------------------------------------------*/ -static int copyReflections(int list, refIndex index[], int maxIndex){ +static int copyReflections(int list, refIndex index[], int maxIndex) +{ int count = 0, status; refIndex ri; status = LLDnodePtr2First(list); - while(status == 1 && count < maxIndex){ - LLDnodeDataTo(list,&ri); + while (status == 1 && count < maxIndex) { + LLDnodeDataTo(list, &ri); index[count] = ri; status = LLDnodePtr2Next(list); count++; } return count; } + /*----------------------------------------------------------------------------------- - matching reflections will be entered in to a list in a sorted way. This list is copied into the index array. - There is some waste here in allocating and deallocating the HC vector in the inner loop. I'am to lazy to resolve this.... May be I'am spared..... - -----------------------------------------------------------------------------------*/ -int searchIndex(lattice direct, double lambda, double two_theta, double max_deviation, - int limit, refIndex index[], int maxIndex){ + -----------------------------------------------------------------------------------*/ +int searchIndex(lattice direct, double lambda, double two_theta, + double max_deviation, int limit, refIndex index[], + int maxIndex) +{ int status, i, j, k, list; MATRIX B, HC; double theta, d; reflection r; - B = mat_creat(3,3,UNIT_MATRIX); - if(B == NULL) { - return UBNOMEMORY; + B = mat_creat(3, 3, UNIT_MATRIX); + if (B == NULL) { + return UBNOMEMORY; } - status = calculateBMatrix(direct,B); - if(status < 0) { + status = calculateBMatrix(direct, B); + if (status < 0) { return status; } list = LLDcreate(sizeof(refIndex)); - if(list <0) { - return UBNOMEMORY; + if (list < 0) { + return UBNOMEMORY; } - - for(i = -limit; i < limit; i++){ - r.h = (double)i; - for(j = -limit; j < limit; j++){ - r.k = (double)j; - for(k = -limit; k < limit; k++){ - r.l = (double)k; - HC = reflectionToHC(r,B); - status = calcTheta(lambda, HC, &d, &theta); - if(status == 1){ - if(ABS(two_theta - 2. * theta) <= max_deviation){ - storeReflection(r,two_theta, theta * 2., list); + + for (i = -limit; i < limit; i++) { + r.h = (double) i; + for (j = -limit; j < limit; j++) { + r.k = (double) j; + for (k = -limit; k < limit; k++) { + r.l = (double) k; + HC = reflectionToHC(r, B); + status = calcTheta(lambda, HC, &d, &theta); + if (status == 1) { + if (ABS(two_theta - 2. * theta) <= max_deviation) { + storeReflection(r, two_theta, theta * 2., list); } - } + } killVector(HC); } } } mat_free(B); - status = copyReflections(list,index,maxIndex); + status = copyReflections(list, index, maxIndex); LLDdelete(list); return status; -} -/*-------------------------------------------------------------------------*/ -double angleBetweenReflections(MATRIX B, reflection r1, reflection r2){ - MATRIX chi1, chi2, h1, h2; - double angle; - - h1 = makeVector(); - if(h1 == NULL){ - return -9999.99; - } - h1[0][0] = r1.h; - h1[1][0] = r1.k; - h1[2][0] = r1.l; +} - h2 = makeVector(); - if(h2 == NULL){ - return -999.99; - } - h2[0][0] = r2.h; - h2[1][0] = r2.k; - h2[2][0] = r2.l; - - chi1 = mat_mul(B,h1); - chi2 = mat_mul(B,h2); - if(chi1 != NULL && chi2 != NULL){ - angle = angleBetween(chi1,chi2); - killVector(chi1); - killVector(chi2); - } - killVector(h1); - killVector(h2); - return angle; +/*-------------------------------------------------------------------------*/ +double angleBetweenReflections(MATRIX B, reflection r1, reflection r2) +{ + MATRIX chi1, chi2, h1, h2; + double angle; + + h1 = makeVector(); + if (h1 == NULL) { + return -9999.99; + } + h1[0][0] = r1.h; + h1[1][0] = r1.k; + h1[2][0] = r1.l; + + h2 = makeVector(); + if (h2 == NULL) { + return -999.99; + } + h2[0][0] = r2.h; + h2[1][0] = r2.k; + h2[2][0] = r2.l; + + chi1 = mat_mul(B, h1); + chi2 = mat_mul(B, h2); + if (chi1 != NULL && chi2 != NULL) { + angle = angleBetween(chi1, chi2); + killVector(chi1); + killVector(chi2); + } + killVector(h1); + killVector(h2); + return angle; } + /*---------------------------------------------------------------------------*/ -MATRIX makeInstToConeVectorMatrix(reflection r,double lambda){ - double z1[3], alpha, beta; - MATRIX mAlpha = NULL, mBeta = NULL, inst2CS = NULL; - - z1FromAngles(lambda,r.s2t,r.om,r.chi,r.phi,z1); - alpha = atan2(z1[1],z1[0]); - beta = -atan2(z1[0],z1[2]); +MATRIX makeInstToConeVectorMatrix(reflection r, double lambda) +{ + double z1[3], alpha, beta; + MATRIX mAlpha = NULL, mBeta = NULL, inst2CS = NULL; + + z1FromAngles(lambda, r.s2t, r.om, r.chi, r.phi, z1); + alpha = atan2(z1[1], z1[0]); + beta = -atan2(z1[0], z1[2]); /* printf("alpha = %f, beta = %f\n", alpha*57.57, beta*57.57);*/ - - mAlpha = mat_creat(3,3,ZERO_MATRIX); - mBeta = mat_creat(3,3,ZERO_MATRIX); - if(mAlpha == NULL || mBeta == NULL){ - return NULL; - } - mAlpha[0][0] = cos(alpha); - mAlpha[0][1] = sin(alpha); - mAlpha[1][0] = -sin(alpha); - mAlpha[1][1] = cos(alpha); - mAlpha[2][2] = 1.; - - mBeta[0][0] = cos(beta); - mBeta[0][2] = sin(beta); - mBeta[1][1] = 1.; - mBeta[2][0] = -sin(beta); - mBeta[2][2] = cos(beta); - - inst2CS = mat_mul(mBeta,mAlpha); - mat_free(mAlpha); - mat_free(mBeta); - - return inst2CS; + + mAlpha = mat_creat(3, 3, ZERO_MATRIX); + mBeta = mat_creat(3, 3, ZERO_MATRIX); + if (mAlpha == NULL || mBeta == NULL) { + return NULL; + } + mAlpha[0][0] = cos(alpha); + mAlpha[0][1] = sin(alpha); + mAlpha[1][0] = -sin(alpha); + mAlpha[1][1] = cos(alpha); + mAlpha[2][2] = 1.; + + mBeta[0][0] = cos(beta); + mBeta[0][2] = sin(beta); + mBeta[1][1] = 1.; + mBeta[2][0] = -sin(beta); + mBeta[2][2] = cos(beta); + + inst2CS = mat_mul(mBeta, mAlpha); + mat_free(mAlpha); + mat_free(mBeta); + + return inst2CS; } + /*--------------------------------------------------------------------------*/ -MATRIX calcConeVector(double openingAngle, double coneAngle, - double length, MATRIX coneToPsi){ - MATRIX coneRot = NULL, nullVector = NULL, coneVector = NULL; - MATRIX coneVectorScatter = NULL; - double testAngle; - MATRIX z; - - z = makeVector(); - z[2][0] = 1.; - - - coneRot = mat_creat(3,3,ZERO_MATRIX); - if(coneRot == NULL){ - return NULL; - } - coneRot[0][0] = Cosd(coneAngle); - coneRot[0][1] = -Sind(coneAngle); - coneRot[1][0] = Sind(coneAngle); - coneRot[1][1] = Cosd(coneAngle); - coneRot[2][2] = 1.0; - - nullVector = makeVector(); - if(nullVector == NULL){ - return NULL; - } - nullVector[0][0] = Sind(openingAngle); - nullVector[1][0] = .0; - nullVector[2][0] = Cosd(openingAngle); - normalizeVector(nullVector); - scaleVector(nullVector,length); - testAngle = angleBetween(z,nullVector); - - coneVector = mat_mul(coneRot,nullVector); - if(coneVector == NULL){ - return NULL; - } - testAngle = angleBetween(z,coneVector); - - coneVectorScatter = mat_mul(coneToPsi,coneVector); - - mat_free(coneRot); - killVector(nullVector); - killVector(coneVector); - - return coneVectorScatter; +MATRIX calcConeVector(double openingAngle, double coneAngle, + double length, MATRIX coneToPsi) +{ + MATRIX coneRot = NULL, nullVector = NULL, coneVector = NULL; + MATRIX coneVectorScatter = NULL; + double testAngle; + MATRIX z; + + z = makeVector(); + z[2][0] = 1.; + + + coneRot = mat_creat(3, 3, ZERO_MATRIX); + if (coneRot == NULL) { + return NULL; + } + coneRot[0][0] = Cosd(coneAngle); + coneRot[0][1] = -Sind(coneAngle); + coneRot[1][0] = Sind(coneAngle); + coneRot[1][1] = Cosd(coneAngle); + coneRot[2][2] = 1.0; + + nullVector = makeVector(); + if (nullVector == NULL) { + return NULL; + } + nullVector[0][0] = Sind(openingAngle); + nullVector[1][0] = .0; + nullVector[2][0] = Cosd(openingAngle); + normalizeVector(nullVector); + scaleVector(nullVector, length); + testAngle = angleBetween(z, nullVector); + + coneVector = mat_mul(coneRot, nullVector); + if (coneVector == NULL) { + return NULL; + } + testAngle = angleBetween(z, coneVector); + + coneVectorScatter = mat_mul(coneToPsi, coneVector); + + mat_free(coneRot); + killVector(nullVector); + killVector(coneVector); + + return coneVectorScatter; } + /*---------------------------------------------------------------------------*/ -double scatteringVectorLength(MATRIX B, reflection r){ - MATRIX h = NULL, psi = NULL; - double length; - - h = makeVector(); - if(h == NULL){ - return -9999.9; - } - h[0][0] = r.h; - h[1][0] = r.k; - h[2][0] = r.l; - - psi = mat_mul(B,h); - - length = vectorLength(psi); - killVector(h); - killVector(psi); - return length; +double scatteringVectorLength(MATRIX B, reflection r) +{ + MATRIX h = NULL, psi = NULL; + double length; + + h = makeVector(); + if (h == NULL) { + return -9999.9; + } + h[0][0] = r.h; + h[1][0] = r.k; + h[2][0] = r.l; + + psi = mat_mul(B, h); + + length = vectorLength(psi); + killVector(h); + killVector(psi); + return length; } - - diff --git a/ubfour.h b/ubfour.h index 7c617de5..90e595b2 100644 --- a/ubfour.h +++ b/ubfour.h @@ -31,10 +31,10 @@ * a reflection data structure holding the indices h,k,l and * the magic four circle angles two_theta, om, chi and phi. */ -typedef struct{ - double h,k,l; - double s2t,om,chi,phi; -}reflection; +typedef struct { + double h, k, l; + double s2t, om, chi, phi; +} reflection; /** * calculate a UB matrix from cell constants and two reflections * @param direct The direct cell constants @@ -43,7 +43,8 @@ typedef struct{ * @param errCode an error indicator if things go wrong. * @return The resulting UB matrix or NULL on errors */ -MATRIX calcUBFromCellAndReflections(lattice direct, reflection r1, reflection r2, int *errCode); +MATRIX calcUBFromCellAndReflections(lattice direct, reflection r1, + reflection r2, int *errCode); /** * calculate the UB matrix from three reflections. The three reflections must not be * coplanar and must reflect a right handed @@ -54,15 +55,16 @@ MATRIX calcUBFromCellAndReflections(lattice direct, reflection r1, reflection r2 * @return A UB matrix on success or NULL on errors. Then errcode will indicate * the type of teh error. */ -MATRIX calcUBFromThreeReflections(reflection r1, reflection r2, reflection r3, - double lambda, int *errCode); +MATRIX calcUBFromThreeReflections(reflection r1, reflection r2, + reflection r3, double lambda, + int *errCode); /** * a data structure holding an indexing suggestion */ typedef struct { - double h, k, l; /* suggested index */ - double t2obs, t2calc, t2diff; /* 2 theta observed and calculated and the difference */ -}refIndex, *prefIndex; + double h, k, l; /* suggested index */ + double t2obs, t2calc, t2diff; /* 2 theta observed and calculated and the difference */ +} refIndex, *prefIndex; /** * search for possible indexes matching the two theta value given. This is a brute force search * @param direct The lattice constants of the crystal @@ -76,15 +78,16 @@ typedef struct { * @return The number of indexes in index or a negative error code when an error * occurs. */ -int searchIndex(lattice direct, double lambda, double two_theta, double max_deviation, - int limit, refIndex index[], int maxIndex); +int searchIndex(lattice direct, double lambda, double two_theta, + double max_deviation, int limit, refIndex index[], + int maxIndex); /** * calculate the angle between two reflections, given their miller indices * @param B The B metric matrix * @param r1 first reflection * @param r2 second reflection * @return angle between reflections - */ + */ double angleBetweenReflections(MATRIX B, reflection r1, reflection r2); /** * calculate the length of the scattering vector belonging to r @@ -111,6 +114,6 @@ MATRIX makeInstToConeVectorMatrix(reflection r, double lambda); * system to the psi instrument coordinate system. * @return a scattering vector on the cone */ -MATRIX calcConeVector(double openingAngle, double coneAngle, - double length, MATRIX coneToPsi); -#endif +MATRIX calcConeVector(double openingAngle, double coneAngle, + double length, MATRIX coneToPsi); +#endif diff --git a/udpquieck.c b/udpquieck.c index 0565a751..b9a281c2 100644 --- a/udpquieck.c +++ b/udpquieck.c @@ -13,108 +13,96 @@ #include "udpquieck.h" /* the UDP port */ - static mkChannel *port = NULL; - static char pError[256]; +static mkChannel *port = NULL; +static char pError[256]; /* the UDP port number, -1 means not configured */ - static int iPort = -1; +static int iPort = -1; /*----------------------------------------------------------------------*/ - void KillQuieck(void *pData) - { - if(port) - { - free(port); - } - if(pData) - KillDummy(pData); +void KillQuieck(void *pData) +{ + if (port) { + free(port); } - + if (pData) + KillDummy(pData); +} + /*------------------------------------------------------------------------*/ - int SendQuieck(int iType, char *pText) - { - char *pPtr = NULL; - int iRet; - char pMessage[512]; - - /* do we know the type */ - if(iType != QUIECK) - { - strcpy(pError,"ERROR: unknown UDP broadcast message type"); - return 0; - } - - /* if no port number, get it from ServerOptions */ - if(iPort < 0) - { - pPtr = IFindOption(pSICSOptions,"QuieckPort"); - if(pPtr) - { - iPort = atoi(pPtr); - } - else - { - iPort = 2108; - } - } - - /* do we have a channel ?*/ - if(port == NULL) - { - port = UDPConnect("localhost",iPort); - if(port == NULL) - { - strcpy(pError,"ERROR: cannot connect to UDP port, may be nobody listening"); - return 0; - } - } +int SendQuieck(int iType, char *pText) +{ + char *pPtr = NULL; + int iRet; + char pMessage[512]; + + /* do we know the type */ + if (iType != QUIECK) { + strcpy(pError, "ERROR: unknown UDP broadcast message type"); + return 0; + } + + /* if no port number, get it from ServerOptions */ + if (iPort < 0) { + pPtr = IFindOption(pSICSOptions, "QuieckPort"); + if (pPtr) { + iPort = atoi(pPtr); + } else { + iPort = 2108; + } + } + + /* do we have a channel ? */ + if (port == NULL) { + port = UDPConnect("localhost", iPort); + if (port == NULL) { + strcpy(pError, + "ERROR: cannot connect to UDP port, may be nobody listening"); + return 0; + } + } + + /* format a message and blast into space */ + switch (iType) { + case QUIECK: + strcpy(pMessage, "QUIECK/"); + strcat(pMessage, pText); + break; + default: + strcpy(pMessage, "Error"); + break; + } + iRet = UDPWrite(port, pMessage, strlen(pMessage)); + if (iRet != 1) { + strcpy(pError, "ERROR: failed to send UDP message"); + free(port); + port = NULL; + return 0; + } + return 1; +} - /* format a message and blast into space */ - switch(iType) - { - case QUIECK: - strcpy(pMessage,"QUIECK/"); - strcat(pMessage,pText); - break; - default: - strcpy(pMessage,"Error"); - break; - } - iRet = UDPWrite(port,pMessage,strlen(pMessage)); - if(iRet != 1) - { - strcpy(pError,"ERROR: failed to send UDP message"); - free(port); - port = NULL; - return 0; - } - return 1; - } /*--------------------------------------------------------------------------*/ - int QuieckAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet; - - if(argc < 2) - { - SCWrite(pCon,"ERROR: expected a message for udpquieck",eError); - return 0; - } +int QuieckAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet; - if(!SCMatchRights(pCon,usMugger)) - { - SCWrite(pCon, - "ERROR: permission denied to use internal command udpquieck", + if (argc < 2) { + SCWrite(pCon, "ERROR: expected a message for udpquieck", eError); + return 0; + } + + if (!SCMatchRights(pCon, usMugger)) { + SCWrite(pCon, + "ERROR: permission denied to use internal command udpquieck", eError); - return 0; - } - - iRet = SendQuieck(QUIECK,argv[1]); - if(iRet != 1) - { - SCWrite(pCon,pError,eError); - return 0; - } - SCSendOK(pCon); - return 1; - } + return 0; + } + iRet = SendQuieck(QUIECK, argv[1]); + if (iRet != 1) { + SCWrite(pCon, pError, eError); + return 0; + } + SCSendOK(pCon); + return 1; +} diff --git a/udpquieck.h b/udpquieck.h index 5231e12f..8d3833f3 100644 --- a/udpquieck.h +++ b/udpquieck.h @@ -13,12 +13,12 @@ #define QUIECK 1 - void KillQuieck(void *pData); +void KillQuieck(void *pData); - int SendQuieck(int iType, char *filename); +int SendQuieck(int iType, char *filename); - int QuieckAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int QuieckAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/ufortify.h b/ufortify.h index 148b570e..b876f1ec 100644 --- a/ufortify.h +++ b/ufortify.h @@ -9,29 +9,29 @@ #define FORTIFY_STORAGE -#define FORTIFY_BEFORE_SIZE 16 /* Bytes to allocate before block */ -#define FORTIFY_BEFORE_VALUE 0xA3 /* Fill value before block */ - -#define FORTIFY_AFTER_SIZE 16 /* Bytes to allocate after block */ -#define FORTIFY_AFTER_VALUE 0xA5 /* Fill value after block */ +#define FORTIFY_BEFORE_SIZE 16 /* Bytes to allocate before block */ +#define FORTIFY_BEFORE_VALUE 0xA3 /* Fill value before block */ -#define FILL_ON_MALLOC /* Nuke out malloc'd memory */ -#define FILL_ON_MALLOC_VALUE 0xA7 /* Value to initialize with */ +#define FORTIFY_AFTER_SIZE 16 /* Bytes to allocate after block */ +#define FORTIFY_AFTER_VALUE 0xA5 /* Fill value after block */ -#define FILL_ON_FREE /* free'd memory is cleared */ -#define FILL_ON_FREE_VALUE 0xA9 /* Value to de-initialize with */ +#define FILL_ON_MALLOC /* Nuke out malloc'd memory */ +#define FILL_ON_MALLOC_VALUE 0xA7 /* Value to initialize with */ -#define CHECK_ALL_MEMORY_ON_MALLOC -#define CHECK_ALL_MEMORY_ON_FREE +#define FILL_ON_FREE /* free'd memory is cleared */ +#define FILL_ON_FREE_VALUE 0xA9 /* Value to de-initialize with */ + +#define CHECK_ALL_MEMORY_ON_MALLOC +#define CHECK_ALL_MEMORY_ON_FREE /* #define PARANOID_FREE */ -#define WARN_ON_MALLOC_FAIL /* A debug is issued on a failed malloc */ -#define WARN_ON_ZERO_MALLOC /* A debug is issued on a malloc(0) */ -#define WARN_ON_FALSE_FAIL /* See Fortify_SetMallocFailRate */ -#define WARN_ON_SIZE_T_OVERFLOW/* Watch for breaking the 64K limit in */ +#define WARN_ON_MALLOC_FAIL /* A debug is issued on a failed malloc */ +#define WARN_ON_ZERO_MALLOC /* A debug is issued on a malloc(0) */ +#define WARN_ON_FALSE_FAIL /* See Fortify_SetMallocFailRate */ +#define WARN_ON_SIZE_T_OVERFLOW /* Watch for breaking the 64K limit in */ /* some braindead architectures... */ -#define FORTIFY_LOCK() -#define FORTIFY_UNLOCK() +#define FORTIFY_LOCK() +#define FORTIFY_UNLOCK() diff --git a/uselect.c b/uselect.c index dca4f0cc..8f8f9cfb 100644 --- a/uselect.c +++ b/uselect.c @@ -10,14 +10,15 @@ /* an uninterruptable version of select. M.Z. Oct 2008 */ int uselect(int nfds, - fd_set *readfds, fd_set *writefds, fd_set *exceptfds, - struct timeval *timeout) { + fd_set * readfds, fd_set * writefds, fd_set * exceptfds, + struct timeval *timeout) +{ sigset_t sigmask; struct timespec tmo, *tmoPtr; int result; char buffer[80]; - + sigfillset(&sigmask); if (timeout) { tmo.tv_sec = timeout->tv_sec; @@ -28,7 +29,7 @@ int uselect(int nfds, } result = pselect(nfds, readfds, writefds, exceptfds, tmoPtr, &sigmask); if (result < 0 && errno == EINTR) { - WriteToCommandLog("SYS>","pselect was interrupted!"); + WriteToCommandLog("SYS>", "pselect was interrupted!"); } return result; } diff --git a/uselect.h b/uselect.h index 4d848d92..55263b88 100644 --- a/uselect.h +++ b/uselect.h @@ -3,5 +3,5 @@ /* an uninterruptable version of select. M.Z. Oct 2008 */ int uselect(int nfds, - fd_set *readfds, fd_set *writefds, fd_set *exceptfds, - struct timeval *timeout); + fd_set * readfds, fd_set * writefds, fd_set * exceptfds, + struct timeval *timeout); diff --git a/userscan.c b/userscan.c index c40116d8..153215db 100644 --- a/userscan.c +++ b/userscan.c @@ -21,10 +21,11 @@ static int UserScanPoints(pScanData self, int iPoint) { /* - do nothing as the user is supposed to take care of the data file - */ + do nothing as the user is supposed to take care of the data file + */ return 1; } + /*----------------------------------------------------------------------- Execute the users special procedure ------------------------------------------------------------------------*/ @@ -38,33 +39,33 @@ static int UserCount(pScanData self, int iPoint) assert(self->pCon); /* check for existence of command to run */ - if(self->pCommand == NULL) - { + if (self->pCommand == NULL) { SCWrite(self->pCon, - "ERROR: configuration error, need procedure to run for user scan", + "ERROR: configuration error, need procedure to run for user scan", eLogError); - SCSetInterrupt(self->pCon,eAbortScan); + SCSetInterrupt(self->pCon, eAbortScan); return 0; } /* invoke command */ - snprintf(pBueffel,511,"%s %d",self->pCommand, iPoint); - status = Tcl_Eval(self->pSics->pTcl,pBueffel); - if(status != TCL_OK) - { - sprintf(pBueffel,"ERROR in count script: %s", - Tcl_GetStringResult(self->pSics->pTcl)); - SCWrite(self->pCon,pBueffel,eLogError); + snprintf(pBueffel, 511, "%s %d", self->pCommand, iPoint); + status = Tcl_Eval(self->pSics->pTcl, pBueffel); + if (status != TCL_OK) { + sprintf(pBueffel, "ERROR in count script: %s", + Tcl_GetStringResult(self->pSics->pTcl)); + SCWrite(self->pCon, pBueffel, eLogError); return 0; } return 1; } + /*------------------------------------------------------------------------*/ int UserCollect(pScanData self, int iPoint) { - /* do nothing, its the users job*/ + /* do nothing, its the users job */ return 1; } + /*------------------------------------------------------------------------*/ void ConfigureUserScan(pScanData self) { diff --git a/userscan.h b/userscan.h index c9bd09c0..8b3f9724 100644 --- a/userscan.h +++ b/userscan.h @@ -13,7 +13,7 @@ #define USERSCAN - void ConfigureUserScan(pScanData self); +void ConfigureUserScan(pScanData self); #endif diff --git a/uubuffer.c b/uubuffer.c index 0fbd804e..0ec831cc 100644 --- a/uubuffer.c +++ b/uubuffer.c @@ -16,151 +16,143 @@ #include "uubuffer.h" /*--------------------------------------------------------------------------*/ - typedef struct _ReadBuf { - char *pPtr; - char *pCurrent; - int iBufPtr; - int iBufLen; - } ReadBuf, *pReadBuf; - +typedef struct _ReadBuf { + char *pPtr; + char *pCurrent; + int iBufPtr; + int iBufLen; +} ReadBuf, *pReadBuf; + /*--------------------------------------------------------------------------*/ - static int ReadBytes(pReadBuf self, char *pBuffer, int iLen) - { - int iLeft; - - if(self->iBufPtr+iLen < self->iBufLen) - { - memcpy(pBuffer,&self->pPtr[self->iBufPtr],iLen); - self->iBufPtr += iLen; - self->pCurrent += iLen; - return iLen; - } - else - { - iLeft = self->iBufLen - self->iBufPtr; - if(iLeft == 0) - { - return 0; - } - memcpy(pBuffer,&self->pPtr[self->iBufPtr],iLeft); - self->iBufPtr = self->iBufLen; - self->pCurrent += iLeft; - return iLeft; - } - } +static int ReadBytes(pReadBuf self, char *pBuffer, int iLen) +{ + int iLeft; + + if (self->iBufPtr + iLen < self->iBufLen) { + memcpy(pBuffer, &self->pPtr[self->iBufPtr], iLen); + self->iBufPtr += iLen; + self->pCurrent += iLen; + return iLen; + } else { + iLeft = self->iBufLen - self->iBufPtr; + if (iLeft == 0) { + return 0; + } + memcpy(pBuffer, &self->pPtr[self->iBufPtr], iLeft); + self->iBufPtr = self->iBufLen; + self->pCurrent += iLeft; + return iLeft; + } +} + /*-------------------------------------------------------------------------*/ - static int ReadPut(pReadBuf self, char c) - { - *(self->pCurrent)= c; - self->iBufPtr++; - self->pCurrent++; - return 1; - } +static int ReadPut(pReadBuf self, char c) +{ + *(self->pCurrent) = c; + self->iBufPtr++; + self->pCurrent++; + return 1; +} + /*--------------------------------------------------------------------------*/ - static int ReadWrite(pReadBuf self, char *pText) - { - int i; - - for(i = 0; i < strlen(pText); i++) - { - ReadPut(self,pText[i]); - } - return 1; - } +static int ReadWrite(pReadBuf self, char *pText) +{ + int i; + + for (i = 0; i < strlen(pText); i++) { + ReadPut(self, pText[i]); + } + return 1; +} + /*-------------------------------------------------------------------------*/ /* ENC is the basic 1 character encoding function to make a char printing */ #define ENC(c) (((c) & 077) + ' ') - static void OutDec(char *p, pReadBuf self) - { - int c1, c2, c3, c4; - - c1 = *p >> 2; - c2 = ((p[0] << 4) & 060) | ((p[1] >> 4) & 017); - c3 = ((p[1] << 2) & 074) | ((p[2] >> 6) & 03); - c4 = p[2] & 077; - /* original, replaced by code below for efficiency. - Saves a couple of function call overhead. The profiler - showed this as a bottleneck. - ReadPut(self,ENC(c1)); - ReadPut(self,ENC(c2)); - ReadPut(self,ENC(c3)); - ReadPut(self,ENC(c4)); - */ - *(self->pCurrent) = ENC(c1); - self->pCurrent++; - *(self->pCurrent) = ENC(c2); - self->pCurrent++; - *(self->pCurrent) = ENC(c3); - self->pCurrent++; - *(self->pCurrent) = ENC(c4); - self->pCurrent++; - self->iBufPtr += 4; - - } -/*--------------------------------------------------------------------------*/ - - int UUencodeBuffer(void *pBuffer, int iBufLen, char *pName, - void **pEncoded, int *iLength) - { - char pBuffel[80]; - ReadBuf sRead, sWrite; - int i, n; - - assert(pBuffer); - assert(iBufLen > 0); - - /* set up read buffer */ - sRead.pPtr = pBuffer; - sRead.iBufPtr = 0; - sRead.iBufLen = iBufLen; - sRead.pCurrent = pBuffer; - - /* set up write buffer. uuencode increases size by 33%, we do 50% - + a bit for newlines etc. - */ - iBufLen += iBufLen/2; - sWrite.pPtr = NULL; - sWrite.pPtr = (char *)malloc((512 + iBufLen)*sizeof(char)); - if(!sWrite.pPtr) - { - return 0; - } - memset(sWrite.pPtr,0,(512+iBufLen)*sizeof(char)); - sWrite.iBufPtr = 0; - sWrite.iBufLen = iBufLen + 512; - sWrite.pCurrent = sWrite.pPtr; - - /* do the header */ - ReadWrite(&sWrite,"begin 622 "); - ReadWrite(&sWrite,pName); - ReadWrite(&sWrite," \r\n"); - - /* well, do it */ - for( ; ;) - { - n = ReadBytes(&sRead,pBuffel,45); - if(n > 0) - { - ReadPut(&sWrite,ENC(n)); - - for(i = 0; i < n; i += 3) - { - OutDec(&pBuffel[i],&sWrite); - } - ReadWrite(&sWrite,"\r\n"); - } - else - { - break; - } - } +static void OutDec(char *p, pReadBuf self) +{ + int c1, c2, c3, c4; - /* finish the game */ - ReadWrite(&sWrite,"end \r\n"); - *pEncoded = sWrite.pPtr; - *iLength = sWrite.iBufPtr; - return 1; - } - + c1 = *p >> 2; + c2 = ((p[0] << 4) & 060) | ((p[1] >> 4) & 017); + c3 = ((p[1] << 2) & 074) | ((p[2] >> 6) & 03); + c4 = p[2] & 077; + /* original, replaced by code below for efficiency. + Saves a couple of function call overhead. The profiler + showed this as a bottleneck. + ReadPut(self,ENC(c1)); + ReadPut(self,ENC(c2)); + ReadPut(self,ENC(c3)); + ReadPut(self,ENC(c4)); + */ + *(self->pCurrent) = ENC(c1); + self->pCurrent++; + *(self->pCurrent) = ENC(c2); + self->pCurrent++; + *(self->pCurrent) = ENC(c3); + self->pCurrent++; + *(self->pCurrent) = ENC(c4); + self->pCurrent++; + self->iBufPtr += 4; + +} + +/*--------------------------------------------------------------------------*/ + +int UUencodeBuffer(void *pBuffer, int iBufLen, char *pName, + void **pEncoded, int *iLength) +{ + char pBuffel[80]; + ReadBuf sRead, sWrite; + int i, n; + + assert(pBuffer); + assert(iBufLen > 0); + + /* set up read buffer */ + sRead.pPtr = pBuffer; + sRead.iBufPtr = 0; + sRead.iBufLen = iBufLen; + sRead.pCurrent = pBuffer; + + /* set up write buffer. uuencode increases size by 33%, we do 50% + + a bit for newlines etc. + */ + iBufLen += iBufLen / 2; + sWrite.pPtr = NULL; + sWrite.pPtr = (char *) malloc((512 + iBufLen) * sizeof(char)); + if (!sWrite.pPtr) { + return 0; + } + memset(sWrite.pPtr, 0, (512 + iBufLen) * sizeof(char)); + sWrite.iBufPtr = 0; + sWrite.iBufLen = iBufLen + 512; + sWrite.pCurrent = sWrite.pPtr; + + /* do the header */ + ReadWrite(&sWrite, "begin 622 "); + ReadWrite(&sWrite, pName); + ReadWrite(&sWrite, " \r\n"); + + /* well, do it */ + for (;;) { + n = ReadBytes(&sRead, pBuffel, 45); + if (n > 0) { + ReadPut(&sWrite, ENC(n)); + + for (i = 0; i < n; i += 3) { + OutDec(&pBuffel[i], &sWrite); + } + ReadWrite(&sWrite, "\r\n"); + } else { + break; + } + } + + /* finish the game */ + ReadWrite(&sWrite, "end \r\n"); + *pEncoded = sWrite.pPtr; + *iLength = sWrite.iBufPtr; + return 1; +} diff --git a/uubuffer.h b/uubuffer.h index 06ef28b1..fb090c28 100644 --- a/uubuffer.h +++ b/uubuffer.h @@ -9,19 +9,18 @@ #ifndef UUBUFFER #define UUBUFFER - int UUencodeBuffer(void *pBuffer, int iBufLen, char *pName, - void **pEncoded, int *iLength); - +int UUencodeBuffer(void *pBuffer, int iBufLen, char *pName, + void **pEncoded, int *iLength); + /* - pBuffer is the buffer to encode - iBufLen is the length of buffer to encode - pName is the name to write instead of a filename - *pEncoded is the pointer to the encoded buffer - *iLength is the length of the encoded buffer. - On success, a 1 will be returned, 0 else. - UUencodeBuffer allocates memory for pEncoded. It is the callers - responsability to free this memory after use. - */ - -#endif + On success, a 1 will be returned, 0 else. + UUencodeBuffer allocates memory for pEncoded. It is the callers + responsability to free this memory after use. + */ +#endif diff --git a/uusend.c b/uusend.c index 20d9f1e3..4621f745 100644 --- a/uusend.c +++ b/uusend.c @@ -39,108 +39,103 @@ static char sccsid[] = "@(#)uuencode.c 5.1 (Berkeley) 7/2/83"; #define ENC(c) (((c) & 077) + ' ') -void encode(FILE *in, FILE *out); -void outdec(char *p, FILE *f); -int fr(FILE *fd, char *buf, int cnt); +void encode(FILE * in, FILE * out); +void outdec(char *p, FILE * f); +int fr(FILE * fd, char *buf, int cnt); main(int argc, char *argv[]) { - FILE *in; - struct stat sbuf; - int mode; + FILE *in; + struct stat sbuf; + int mode; - /* optional 1st argument */ + /* optional 1st argument */ - if (argc > 2) - { + if (argc > 2) { #ifdef MSDOS - /* Use binary mode */ - if ((in = fopen(argv[1], "rb")) == NULL) - { + /* Use binary mode */ + if ((in = fopen(argv[1], "rb")) == NULL) { #else - if ((in = fopen(argv[1], "r")) == NULL) - { + if ((in = fopen(argv[1], "r")) == NULL) { #endif - perror(argv[1]); - exit(1); - } - argv++; argc--; - } - else in = stdin; + perror(argv[1]); + exit(1); + } + argv++; + argc--; + } else + in = stdin; - if (argc != 2) - { - printf("Usage: uuencode [infile] remotefile\n"); - exit(2); - } + if (argc != 2) { + printf("Usage: uuencode [infile] remotefile\n"); + exit(2); + } - /* figure out the input file mode */ + /* figure out the input file mode */ - fstat(fileno(in), &sbuf); - mode = sbuf.st_mode & 0777; - printf("begin %o %s\n", mode, argv[1]); + fstat(fileno(in), &sbuf); + mode = sbuf.st_mode & 0777; + printf("begin %o %s\n", mode, argv[1]); - encode(in, stdout); + encode(in, stdout); - printf("end\n"); - return 0; + printf("end\n"); + return 0; } /* * copy from in to out, encoding as you go along. */ -void encode(FILE *in, FILE *out) +void encode(FILE * in, FILE * out) { - char buf[80]; - int i, n; + char buf[80]; + int i, n; - for (;;) - { - /* 1 (up to) 45 character line */ + for (;;) { + /* 1 (up to) 45 character line */ - n = fr(in, buf, 45); - putc(ENC(n), out); + n = fr(in, buf, 45); + putc(ENC(n), out); - for (i = 0; i < n; i += 3) - outdec(&buf[i], out); + for (i = 0; i < n; i += 3) + outdec(&buf[i], out); - putc('\n', out); - if (n <= 0) - break; - } + putc('\n', out); + if (n <= 0) + break; + } } /* * output one group of 3 bytes, pointed at by p, on file f. */ -void outdec(char *p, FILE *f) +void outdec(char *p, FILE * f) { - int c1, c2, c3, c4; + int c1, c2, c3, c4; - c1 = *p >> 2; - c2 = ((p[0] << 4) & 060) | ((p[1] >> 4) & 017); - c3 = ((p[1] << 2) & 074) | ((p[2] >> 6) & 03); - c4 = p[2] & 077; - putc(ENC(c1), f); - putc(ENC(c2), f); - putc(ENC(c3), f); - putc(ENC(c4), f); + c1 = *p >> 2; + c2 = ((p[0] << 4) & 060) | ((p[1] >> 4) & 017); + c3 = ((p[1] << 2) & 074) | ((p[2] >> 6) & 03); + c4 = p[2] & 077; + putc(ENC(c1), f); + putc(ENC(c2), f); + putc(ENC(c3), f); + putc(ENC(c4), f); } /* fr: like read but stdio */ -int fr(FILE *fd, char *buf, int cnt) +int fr(FILE * fd, char *buf, int cnt) { - int c, i; + int c, i; - for (i = 0; i < cnt; i++) - { - c = getc(fd); - if (c == EOF) - return(i); - buf[i] = (char)c; - } - return (cnt); + for (i = 0; i < cnt; i++) { + c = getc(fd); + if (c == EOF) + return (i); + buf[i] = (char) c; + } + return (cnt); } diff --git a/varlog.c b/varlog.c index 806821d6..a8f3f2c3 100644 --- a/varlog.c +++ b/varlog.c @@ -66,175 +66,168 @@ */ #define MAXRING 1024 /*------------------------------------------------------------------------*/ - typedef struct __VarLog - { - time_t tFrequency; - time_t tNext; - int iCount; - double dSum; - double dDeviation; - FILE *fd; - pCircular pTail; - }VarLog; +typedef struct __VarLog { + time_t tFrequency; + time_t tNext; + int iCount; + double dSum; + double dDeviation; + FILE *fd; + pCircular pTail; +} VarLog; /*------------------------------------------------------------------------*/ - typedef struct { - time_t tTime; - float fVal; - }LogItem, *pLogItem; +typedef struct { + time_t tTime; + float fVal; +} LogItem, *pLogItem; /*--------------------------------------------------------------------------*/ - int VarlogInit(pVarLog *self) - { - int i; - pVarLog pNew = NULL; - - pNew = (pVarLog)malloc(sizeof(VarLog)); - if(!pNew) - { - return 0; - } - pNew->tFrequency = 300; /* 5 minutes */ - pNew->tNext = 0; - pNew->iCount = 0; - pNew->dSum = 0.; - pNew->dDeviation = 0.; - pNew->fd = NULL; - pNew->pTail = createCircular(MAXRING,free); - if(!pNew->pTail) - { - VarlogDelete(pNew); - return 0; - } +int VarlogInit(pVarLog * self) +{ + int i; + pVarLog pNew = NULL; + + pNew = (pVarLog) malloc(sizeof(VarLog)); + if (!pNew) { + return 0; + } + pNew->tFrequency = 300; /* 5 minutes */ + pNew->tNext = 0; + pNew->iCount = 0; + pNew->dSum = 0.; + pNew->dDeviation = 0.; + pNew->fd = NULL; + pNew->pTail = createCircular(MAXRING, free); + if (!pNew->pTail) { + VarlogDelete(pNew); + return 0; + } + + *self = pNew; + return 1; +} - *self = pNew; - return 1; - } /*---------------------------------------------------------------------------*/ - int VarlogDelete(pVarLog self) - { - if(self->fd != NULL) - { - fclose(self->fd); - } - if(self->pTail != NULL) - { - deleteCircular(self->pTail); - } - free(self); /* M.Z. */ - return 1; - } +int VarlogDelete(pVarLog self) +{ + if (self->fd != NULL) { + fclose(self->fd); + } + if (self->pTail != NULL) { + deleteCircular(self->pTail); + } + free(self); /* M.Z. */ + return 1; +} + /*--------------------------------------------------------------------------*/ - int VarlogClear(pVarLog self) - { - int iRet, iList; - - self->iCount = 0; - self->dSum = 0.; - self->dDeviation = 0.; - self->tNext = 0; - return 1; - } +int VarlogClear(pVarLog self) +{ + int iRet, iList; + + self->iCount = 0; + self->dSum = 0.; + self->dDeviation = 0.; + self->tNext = 0; + return 1; +} + /*-------------------------------------------------------------------------*/ - static void VLFormatTime(time_t tTime, char *pBuffer, int iBufLen) - { - struct tm *psTime; +static void VLFormatTime(time_t tTime, char *pBuffer, int iBufLen) +{ + struct tm *psTime; + + /* make time string */ + psTime = localtime(&tTime); + memset(pBuffer, 0, iBufLen); + strftime(pBuffer, iBufLen, "%Y-%d-%m %H:%M:%S", psTime); +} - /* make time string */ - psTime = localtime(&tTime); - memset(pBuffer,0,iBufLen); - strftime(pBuffer,iBufLen,"%Y-%d-%m %H:%M:%S",psTime); - } /*--------------------------------------------------------------------------*/ - int VarlogAdd(pVarLog self, float fVal) - { - LogItem sItem; - time_t tCurrent; - int iFile = 0; - char pBuffer[80]; - double dMean, dTmp; - pLogItem newLog = NULL; +int VarlogAdd(pVarLog self, float fVal) +{ + LogItem sItem; + time_t tCurrent; + int iFile = 0; + char pBuffer[80]; + double dMean, dTmp; + pLogItem newLog = NULL; - assert(self); - - tCurrent = time(NULL); + assert(self); - /* check if we are logging to file */ - if(self->fd != NULL) - { - iFile = 1; + tCurrent = time(NULL); + + /* check if we are logging to file */ + if (self->fd != NULL) { + iFile = 1; + } + + + /* update the running mean */ + self->dSum += fVal; + self->iCount++; + dMean = self->dSum / self->iCount; + dTmp = fVal - dMean; + self->dDeviation += dTmp * dTmp; + + + /* if not initialised, do it */ + if (self->tNext < 1) { + if (iFile) { + VLFormatTime(tCurrent, pBuffer, 79); + fprintf(self->fd, " %s %f \n", pBuffer, fVal); } - - - /* update the running mean */ - self->dSum += fVal; - self->iCount++; - dMean = self->dSum/self->iCount; - dTmp = fVal - dMean; - self->dDeviation += dTmp*dTmp; - - - /* if not initialised, do it */ - if(self->tNext < 1) - { - if(iFile) - { - VLFormatTime(tCurrent,pBuffer,79); - fprintf(self->fd," %s %f \n", pBuffer,fVal); - } - self->tNext = tCurrent + self->tFrequency; - return 1; + self->tNext = tCurrent + self->tFrequency; + return 1; + } + + /* if, log time passed, write to file and into ring buffer */ + if (tCurrent > self->tNext) { + if (iFile) { + VLFormatTime(tCurrent, pBuffer, 79); + fprintf(self->fd, " %s %f \n", pBuffer, fVal); } - - /* if, log time passed, write to file and into ring buffer */ - if(tCurrent > self->tNext) - { - if(iFile) - { - VLFormatTime(tCurrent,pBuffer,79); - fprintf(self->fd," %s %f \n", pBuffer,fVal); - } - newLog = (pLogItem)malloc(sizeof(LogItem)); - if(newLog != NULL) - { - newLog->tTime = tCurrent; - newLog->fVal = fVal; - setCircular(self->pTail,newLog); - nextCircular(self->pTail); - } - self->tNext = tCurrent + self->tFrequency; - return 1; + newLog = (pLogItem) malloc(sizeof(LogItem)); + if (newLog != NULL) { + newLog->tTime = tCurrent; + newLog->fVal = fVal; + setCircular(self->pTail, newLog); + nextCircular(self->pTail); } - return 1; - } + self->tNext = tCurrent + self->tFrequency; + return 1; + } + return 1; +} + /*--------------------------------------------------------------------------*/ - int VarlogLength(pVarLog self, int *iLength) - { - *iLength = self->iCount; - return 1; - } +int VarlogLength(pVarLog self, int *iLength) +{ + *iLength = self->iCount; + return 1; +} + /*---------------------------------------------------------------------------*/ - int VarlogGetMean(pVarLog self, float *fMean, float *fStdDev) - { - double dMean, dStdDev; - int success; +int VarlogGetMean(pVarLog self, float *fMean, float *fStdDev) +{ + double dMean, dStdDev; + int success; - if(self->iCount > 0) - { - dMean = self->dSum/(double)self->iCount; - dStdDev = sqrt(self->dDeviation/(double)self->iCount); - success = 1; - } - else - { - dMean = .0; - dStdDev = .0; - success = 0; - } - *fMean = (float)dMean; - *fStdDev = (float)dStdDev; + if (self->iCount > 0) { + dMean = self->dSum / (double) self->iCount; + dStdDev = sqrt(self->dDeviation / (double) self->iCount); + success = 1; + } else { + dMean = .0; + dStdDev = .0; + success = 0; + } + *fMean = (float) dMean; + *fStdDev = (float) dStdDev; + + return success; +} - return success; - } /*-----------------------------------------------------------------------*/ static int VarlogToSicsData(pVarLog self, pSICSData data) { @@ -242,44 +235,41 @@ static int VarlogToSicsData(pVarLog self, pSICSData data) int *dataPtr = NULL; pLogItem log = NULL; - dataPtr = getSICSDataPointer(data,0,2*MAXRING+1); - if(!dataPtr) - { + dataPtr = getSICSDataPointer(data, 0, 2 * MAXRING + 1); + if (!dataPtr) { return 0; } dataPtr[0] = MAXRING; /* skip back MAXRING steps - */ - for(i = 0; i < MAXRING; i++) - { + */ + for (i = 0; i < MAXRING; i++) { previousCircular(self->pTail); } /* - forward again and copy data - */ - for(i = 0; i < MAXRING; i++) - { + forward again and copy data + */ + for (i = 0; i < MAXRING; i++) { log = getCircular(self->pTail); - if(log != NULL) - { - dataPtr[i+1] = (int)log->tTime; - memcpy(&dataPtr[i+1+MAXRING],&log->fVal,sizeof(float)); + if (log != NULL) { + dataPtr[i + 1] = (int) log->tTime; + memcpy(&dataPtr[i + 1 + MAXRING], &log->fVal, sizeof(float)); } nextCircular(self->pTail); } - + /* - assign data types - */ - assignSICSType(data,0,MAXRING+1,INTTYPE); - assignSICSType(data,MAXRING+1,2*MAXRING+1,FLOATTYPE); + assign data types + */ + assignSICSType(data, 0, MAXRING + 1, INTTYPE); + assignSICSType(data, MAXRING + 1, 2 * MAXRING + 1, FLOATTYPE); return 1; } + /*-----------------------------------------------------------------------*/ -static void VarlogDump(pVarLog self, SConnection *pCon) +static void VarlogDump(pVarLog self, SConnection * pCon) { int i, length; pLogItem log = NULL; @@ -287,31 +277,28 @@ static void VarlogDump(pVarLog self, SConnection *pCon) /* skip back MAXRING steps - */ - for(i = 0; i < MAXRING; i++) - { + */ + for (i = 0; i < MAXRING; i++) { previousCircular(self->pTail); } /* - forward again and print data - */ - for(i = 0; i < MAXRING; i++) - { + forward again and print data + */ + for (i = 0; i < MAXRING; i++) { log = getCircular(self->pTail); - if(log != NULL) - { - if(log->tTime > 0) - { - VLFormatTime(log->tTime,timeBuffer,131); - snprintf(pBueffel,255,"%s %12.3f",timeBuffer,log->fVal); - SCWrite(pCon,pBueffel,eValue); + if (log != NULL) { + if (log->tTime > 0) { + VLFormatTime(log->tTime, timeBuffer, 131); + snprintf(pBueffel, 255, "%s %12.3f", timeBuffer, log->fVal); + SCWrite(pCon, pBueffel, eValue); } } nextCircular(self->pTail); } } + /*-----------------------------------------------------------------------*/ -static void VarLogDumpFile(pVarLog self, FILE *fd) +static void VarLogDumpFile(pVarLog self, FILE * fd) { int i, length; pLogItem log = NULL; @@ -319,198 +306,164 @@ static void VarLogDumpFile(pVarLog self, FILE *fd) /* skip back MAXRING steps - */ - for(i = 0; i < MAXRING; i++) - { + */ + for (i = 0; i < MAXRING; i++) { previousCircular(self->pTail); } /* - forward again and print data - */ - for(i = 0; i < MAXRING; i++) - { + forward again and print data + */ + for (i = 0; i < MAXRING; i++) { log = getCircular(self->pTail); - if(log != NULL) - { - if(log->tTime > 0) - { - VLFormatTime(log->tTime,timeBuffer,131); - fprintf(fd,"%s %12.3f",timeBuffer,log->fVal); + if (log != NULL) { + if (log->tTime > 0) { + VLFormatTime(log->tTime, timeBuffer, 131); + fprintf(fd, "%s %12.3f", timeBuffer, log->fVal); } } nextCircular(self->pTail); } } + /*--------------------------------------------------------------------------*/ - int VarlogWrapper(pVarLog self, SConnection *pCon, - char *subcommand, char *sub2, char *pVarName) - { - float fMean, fStdDev, *fData = NULL; - time_t *pTArray = NULL; - int iLength, iRet, i, iList; - char pBueffel[256]; - char *pData = NULL; - long lNew; - pSICSData data = NULL; - FILE *fd = NULL; - - - strtolower(subcommand); +int VarlogWrapper(pVarLog self, SConnection * pCon, + char *subcommand, char *sub2, char *pVarName) +{ + float fMean, fStdDev, *fData = NULL; + time_t *pTArray = NULL; + int iLength, iRet, i, iList; + char pBueffel[256]; + char *pData = NULL; + long lNew; + pSICSData data = NULL; + FILE *fd = NULL; + + + strtolower(subcommand); /*--------- file */ - if(strcmp(subcommand,"file") == 0) - { - if(self->fd != NULL) - { - fclose(self->fd); - self->fd = NULL; - } - self->fd = fopen(sub2,"w"); - if(!self->fd) - { - sprintf(pBueffel,"ERROR: failed to open temperature log file: %s", - sub2); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(self->tFrequency < 20) - { - self->tFrequency = 300; - } - SCSendOK(pCon); - return 1; + if (strcmp(subcommand, "file") == 0) { + if (self->fd != NULL) { + fclose(self->fd); + self->fd = NULL; } + self->fd = fopen(sub2, "w"); + if (!self->fd) { + sprintf(pBueffel, "ERROR: failed to open temperature log file: %s", + sub2); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (self->tFrequency < 20) { + self->tFrequency = 300; + } + SCSendOK(pCon); + return 1; + } /*----- flush */ - else if(strcmp(subcommand,"flush") == 0) - { - if(self->fd != NULL) - { - fflush(self->fd); - } - SCSendOK(pCon); - return 1; + else if (strcmp(subcommand, "flush") == 0) { + if (self->fd != NULL) { + fflush(self->fd); } + SCSendOK(pCon); + return 1; + } /*----- close */ - else if(strcmp(subcommand,"close") == 0) - { - if(self->fd != NULL) - { - fclose(self->fd); - self->fd = NULL; - } - SCSendOK(pCon); - return 1; + else if (strcmp(subcommand, "close") == 0) { + if (self->fd != NULL) { + fclose(self->fd); + self->fd = NULL; } + SCSendOK(pCon); + return 1; + } /*----- status */ - else if(strcmp(subcommand,"status") == 0) - { - if(self->fd != NULL) - { - SCWrite(pCon,"Logging to file on",eValue); - } - else - { - SCWrite(pCon,"No Logging to file",eValue); - } - return 1; + else if (strcmp(subcommand, "status") == 0) { + if (self->fd != NULL) { + SCWrite(pCon, "Logging to file on", eValue); + } else { + SCWrite(pCon, "No Logging to file", eValue); } + return 1; + } /*--------- getmean */ - else if(strcmp(subcommand,"getmean") == 0) - { - iRet = VarlogGetMean(self,&fMean,&fStdDev); - if(!iRet) - { - SCWrite(pCon,"WARNING: No mean and stddev log values available ", - eWarning); - return 0; - } - sprintf(pBueffel,"%s.Mean = %8.2f %s.StdDev = %8.2f", - pVarName,fMean,pVarName,fStdDev); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + else if (strcmp(subcommand, "getmean") == 0) { + iRet = VarlogGetMean(self, &fMean, &fStdDev); + if (!iRet) { + SCWrite(pCon, "WARNING: No mean and stddev log values available ", + eWarning); + return 0; + } + sprintf(pBueffel, "%s.Mean = %8.2f %s.StdDev = %8.2f", + pVarName, fMean, pVarName, fStdDev); + SCWrite(pCon, pBueffel, eValue); + return 1; + } /*------------ clear */ - else if(strcmp(subcommand,"clear") == 0) - { - return VarlogClear(self); - } + else if (strcmp(subcommand, "clear") == 0) { + return VarlogClear(self); + } /*------------- frequency */ - else if(strcmp(subcommand,"frequency") == 0) - { - if(sub2) - { - iRet = sscanf(sub2,"%ld",&lNew); - } - else - { - iRet = 0; - } - if(iRet == 1) /* new value */ - { - self->tFrequency = lNew; - return 1; - } - else /* print */ - { - sprintf(pBueffel,"%s.frequency = %d",pVarName,(int)self->tFrequency); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + else if (strcmp(subcommand, "frequency") == 0) { + if (sub2) { + iRet = sscanf(sub2, "%ld", &lNew); + } else { + iRet = 0; } - /*-------------- tosicsdata */ - else if(strcmp(subcommand,"tosicsdata") == 0) - { - if(!sub2) - { - SCWrite(pCon,"ERROR: tosicsdata needs an argument",eError); - return 0; - } - data = FindCommandData(pServ->pSics,sub2,"SICSData"); - if(!data) - { - snprintf(pBueffel,255,"ERROR: %s is no sicsdata object",sub2); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = VarlogToSicsData(self,data); - if(iRet == 0) - { - SCWrite(pCon,"ERROR: out of memory in VarlogToSicsData",eError); - return 0; - } - SCSendOK(pCon); + if (iRet == 1) { /* new value */ + self->tFrequency = lNew; return 1; - } - /* ---------------- dumpring */ - else if(strcmp(subcommand,"dump") == 0) - { - VarlogDump(self,pCon); + } else { /* print */ + + sprintf(pBueffel, "%s.frequency = %d", pVarName, + (int) self->tFrequency); + SCWrite(pCon, pBueffel, eValue); return 1; } - /*---------------- dumptofile */ - else if(strcmp(subcommand,"dumptofile") == 0) - { - if(sub2 != NULL) - { - fd = fopen(sub2,"w"); - } - if(fd == NULL) - { - snprintf(pBueffel,255,"ERROR: failed to open %s",sub2); - SCWrite(pCon,pBueffel,eError); - return 0; - } - VarLogDumpFile(self,fd); - fclose(fd); - SCSendOK(pCon); - return 1; - } -/* command not recognized */ - else - { - sprintf(pBueffel,"ERROR: %s no valid command to varlog",subcommand); - SCWrite(pCon,pBueffel,eError); - return 0; - } } - - + /*-------------- tosicsdata */ + else if (strcmp(subcommand, "tosicsdata") == 0) { + if (!sub2) { + SCWrite(pCon, "ERROR: tosicsdata needs an argument", eError); + return 0; + } + data = FindCommandData(pServ->pSics, sub2, "SICSData"); + if (!data) { + snprintf(pBueffel, 255, "ERROR: %s is no sicsdata object", sub2); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = VarlogToSicsData(self, data); + if (iRet == 0) { + SCWrite(pCon, "ERROR: out of memory in VarlogToSicsData", eError); + return 0; + } + SCSendOK(pCon); + return 1; + } + /* ---------------- dumpring */ + else if (strcmp(subcommand, "dump") == 0) { + VarlogDump(self, pCon); + return 1; + } + /*---------------- dumptofile */ + else if (strcmp(subcommand, "dumptofile") == 0) { + if (sub2 != NULL) { + fd = fopen(sub2, "w"); + } + if (fd == NULL) { + snprintf(pBueffel, 255, "ERROR: failed to open %s", sub2); + SCWrite(pCon, pBueffel, eError); + return 0; + } + VarLogDumpFile(self, fd); + fclose(fd); + SCSendOK(pCon); + return 1; + } +/* command not recognized */ + else { + sprintf(pBueffel, "ERROR: %s no valid command to varlog", subcommand); + SCWrite(pCon, pBueffel, eError); + return 0; + } +} diff --git a/varlog.h b/varlog.h index 31d571a6..3a5ff49c 100644 --- a/varlog.h +++ b/varlog.h @@ -13,21 +13,21 @@ #define SICSVARLOG #include -/*---------------------------- birth and death ----------------------------*/ - typedef struct __VarLog *pVarLog; +/*---------------------------- birth and death ----------------------------*/ +typedef struct __VarLog *pVarLog; - int VarlogInit(pVarLog *self); - int VarlogDelete(pVarLog self); +int VarlogInit(pVarLog * self); +int VarlogDelete(pVarLog self); /*----------------------------- operation -------------------------------*/ - int VarlogClear(pVarLog self); - int VarlogAdd(pVarLog self, float fVal); +int VarlogClear(pVarLog self); +int VarlogAdd(pVarLog self, float fVal); /*------------------------------ data recovery -------------------------*/ - int VarlogLength(pVarLog self, int *iLength); - int VarlogGetTime(pVarLog self, time_t *tTime); - int VarlogGetVal(pVarLog self, float *fValues); - int VarlogGetMean(pVarLog self, float *fMean, float *fStdDev); +int VarlogLength(pVarLog self, int *iLength); +int VarlogGetTime(pVarLog self, time_t * tTime); +int VarlogGetVal(pVarLog self, float *fValues); +int VarlogGetMean(pVarLog self, float *fMean, float *fStdDev); /*------------------------------ interpreter ---------------------------*/ - int VarlogWrapper(pVarLog self,SConnection *pCon, - char *subcommand, char *sub2,char *pVarName); +int VarlogWrapper(pVarLog self, SConnection * pCon, + char *subcommand, char *sub2, char *pVarName); #endif diff --git a/vector.c b/vector.c index c8754240..a24e53bf 100644 --- a/vector.c +++ b/vector.c @@ -15,156 +15,190 @@ #include "trigd.h" /*----------------------------------------------------------------------*/ -MATRIX makeVector(){ - return mat_creat(3,1,ZERO_MATRIX); +MATRIX makeVector() +{ + return mat_creat(3, 1, ZERO_MATRIX); } + /*---------------------------------------------------------------------*/ -MATRIX makeVectorInit(double val[3]){ +MATRIX makeVectorInit(double val[3]) +{ int i; MATRIX result = NULL; result = makeVector(); - if(result == NULL){ + if (result == NULL) { return result; } - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { result[i][0] = val[i]; - } + } return result; } + /*---------------------------------------------------------------------*/ -void vectorToArray(MATRIX v, double val[3]){ +void vectorToArray(MATRIX v, double val[3]) +{ int i; assert(MatCol(v) == 3); - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { val[i] = v[i][0]; } } + /*----------------------------------------------------------------------*/ -void killVector(MATRIX v){ +void killVector(MATRIX v) +{ mat_free(v); } + /*----------------------------------------------------------------------*/ -void vectorSet(MATRIX v, int idx, double value){ +void vectorSet(MATRIX v, int idx, double value) +{ assert(idx >= 0 && idx < 3); v[idx][0] = value; } + /*----------------------------------------------------------------------*/ -double vectorGet(MATRIX v, int idx){ +double vectorGet(MATRIX v, int idx) +{ assert(idx >= 0 && idx < 3); return v[idx][0]; } + /*----------------------------------------------------------------------*/ -double vectorLength(MATRIX v){ +double vectorLength(MATRIX v) +{ assert(MatRow(v) == 3); - return sqrt(v[0][0]*v[0][0] + v[1][0]*v[1][0] + v[2][0]*v[2][0]); + return sqrt(v[0][0] * v[0][0] + v[1][0] * v[1][0] + v[2][0] * v[2][0]); } + /*---------------------------------------------------------------------*/ -void normalizeVector(MATRIX v){ +void normalizeVector(MATRIX v) +{ int i; double norm; norm = vectorLength(v); - if(norm > .00001) { - for(i = 0; i < 3; i++){ + if (norm > .00001) { + for (i = 0; i < 3; i++) { v[i][0] /= norm; } } else { - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { v[i][0] = .0; } } } + /*----------------------------------------------------------------------*/ -double vectorDotProduct(MATRIX v1, MATRIX v2){ +double vectorDotProduct(MATRIX v1, MATRIX v2) +{ double sum; int i; assert(MatRow(v1) == MatRow(v2)); sum = .0; - for(i = 0; i < MatRow(v1); i++){ - sum += v1[i][0]*v2[i][0]; + for (i = 0; i < MatRow(v1); i++) { + sum += v1[i][0] * v2[i][0]; } return sum; } + /*----------------------------------------------------------------------*/ -MATRIX vectorCrossProduct(MATRIX v1, MATRIX v2){ +MATRIX vectorCrossProduct(MATRIX v1, MATRIX v2) +{ MATRIX result; assert(MatRow(v1) == 3); assert(MatRow(v2) == 3); result = makeVector(); - if(result == NULL){ + if (result == NULL) { return NULL; } - vectorSet(result,0,vectorGet(v1,1)*vectorGet(v2,2) - vectorGet(v1,2)*vectorGet(v2,1)); - vectorSet(result,1,vectorGet(v1,2)*vectorGet(v2,0) - vectorGet(v1,0)*vectorGet(v2,2)); - vectorSet(result,2,vectorGet(v1,0)*vectorGet(v2,1) - vectorGet(v1,1)*vectorGet(v2,0)); + vectorSet(result, 0, + vectorGet(v1, 1) * vectorGet(v2, 2) - vectorGet(v1, + 2) * + vectorGet(v2, 1)); + vectorSet(result, 1, + vectorGet(v1, 2) * vectorGet(v2, 0) - vectorGet(v1, + 0) * + vectorGet(v2, 2)); + vectorSet(result, 2, + vectorGet(v1, 0) * vectorGet(v2, 1) - vectorGet(v1, + 1) * + vectorGet(v2, 0)); return result; } + /*-------------------------------------------------------------------------*/ -MATRIX matFromTwoVectors(MATRIX v1, MATRIX v2){ +MATRIX matFromTwoVectors(MATRIX v1, MATRIX v2) +{ MATRIX a1, a2, a3, result; int i; a1 = mat_copy(v1); - if(a1 == NULL){ + if (a1 == NULL) { return NULL; } normalizeVector(a1); - a3 = vectorCrossProduct(v1,v2); - if(a3 == NULL){ + a3 = vectorCrossProduct(v1, v2); + if (a3 == NULL) { return NULL; } normalizeVector(a3); - a2 = vectorCrossProduct(a1,a3); - if(a2 == NULL){ + a2 = vectorCrossProduct(a1, a3); + if (a2 == NULL) { return NULL; } - result = mat_creat(3,3,ZERO_MATRIX); - if(result == NULL){ + result = mat_creat(3, 3, ZERO_MATRIX); + if (result == NULL) { return NULL; } - for(i = 0; i < 3; i++){ - result[i][0] = vectorGet(a1,i); - result[i][1] = vectorGet(a2,i); - result[i][2] = vectorGet(a3,i); + for (i = 0; i < 3; i++) { + result[i][0] = vectorGet(a1, i); + result[i][1] = vectorGet(a2, i); + result[i][2] = vectorGet(a3, i); } killVector(a1); killVector(a2); killVector(a3); return result; } + /*-----------------------------------------------------------------------*/ -double angleBetween(MATRIX v1, MATRIX v2){ - double angle, angles; - MATRIX v3 = NULL; - - angle = vectorDotProduct(v1,v2)/(vectorLength(v1) * vectorLength(v2)); - v3 = vectorCrossProduct(v1,v2); - if(v3 != NULL){ - angles = vectorLength(v3)/(vectorLength(v1) * vectorLength(v2)); - angle = Atan2d(angles,angle); - } else { - angle = Acosd(angle); - } - return angle; +double angleBetween(MATRIX v1, MATRIX v2) +{ + double angle, angles; + MATRIX v3 = NULL; + + angle = vectorDotProduct(v1, v2) / (vectorLength(v1) * vectorLength(v2)); + v3 = vectorCrossProduct(v1, v2); + if (v3 != NULL) { + angles = vectorLength(v3) / (vectorLength(v1) * vectorLength(v2)); + angle = Atan2d(angles, angle); + } else { + angle = Acosd(angle); + } + return angle; } + /*----------------------------------------------------------------------*/ -void scaleVector(MATRIX v, double scale){ - int i; - - for(i = 0; i < 3; i++){ - v[i][0] *= scale; - } +void scaleVector(MATRIX v, double scale) +{ + int i; + + for (i = 0; i < 3; i++) { + v[i][0] *= scale; + } } diff --git a/velo.c b/velo.c index 184f6876..9b12f3dd 100644 --- a/velo.c +++ b/velo.c @@ -57,575 +57,551 @@ #include "site.h" /* -------- defines for parameters to velocity selector */ -#define INT 0 -#define RIGHT 1 +#define INT 0 +#define RIGHT 1 #define TILTPREC 2 /* ------------------ the functions for the drivable interface --------------*/ - static int VSHalt(void *pData) - { - pVelSel self = NULL; - - self = (pVelSel)pData; - assert(self); - - self->pDriv->Halt(self->pDriv); - EVCSetMode(self->pMonitor,EVIdle); - return 1; - } -/*---------------------------------------------------------------------------*/ - static int VSLimits(void *pData, float fVal, char *pError, int iErrLen) - { - pVelSel self = NULL; - Verbot Alcatraz; - int iRet; - char pBueffel[512]; - - self = (pVelSel)pData; - assert(self); - - - /* first let us check if we are in the overall range. - The first entry in the forbidden region thing is meant to - contain this information - */ - iRet = LLDnodePtr2First(self->iForbidden); - LLDnodeDataTo(self->iForbidden,&Alcatraz); - if( (fVal < Alcatraz.fMin) || (fVal > Alcatraz.fMax) ) - { - sprintf(pBueffel," %f out of range: %f --- %f", - fVal, Alcatraz.fMin, Alcatraz.fMax); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - - /* now search through the rest if in some forbidden region */ - iRet = LLDnodePtr2Next(self->iForbidden); - while(iRet != 0) - { - LLDnodeDataTo(self->iForbidden,&Alcatraz); - if( (fVal > Alcatraz.fMin) && (fVal < Alcatraz.fMax)) - { - sprintf(pBueffel," %f violates forbidden region %f --- %f", - fVal, Alcatraz.fMin, Alcatraz.fMax); - strncpy(pError,pBueffel,iErrLen); - return 0; - } - iRet = LLDnodePtr2Next(self->iForbidden); - } - /* Success ! */ - return 1; - } -/*-----------------------------------------------------------------------*/ -static void VSListForbidden(pVelSel self, SConnection *pCon){ - Tcl_DString message; - int status; - Verbot Alcatraz; - char pBueffel[256]; +static int VSHalt(void *pData) +{ + pVelSel self = NULL; - Tcl_DStringInit(&message); - /* - The first entry in the forbidden region thing is meant to - contain the overall range: skip it! - */ - status = LLDnodePtr2First(self->iForbidden); - LLDnodeDataTo(self->iForbidden,&Alcatraz); - if(status == 1){ - snprintf(pBueffel,255,"%s.forbidden = {%f -inf", self->pName, Alcatraz.fMax); - Tcl_DStringAppend(&message,pBueffel,strlen(pBueffel)); - } - - /* now search the forbidden regions */ - status = LLDnodePtr2Next(self->iForbidden); - while(status != 0){ - LLDnodeDataTo(self->iForbidden,&Alcatraz); - snprintf(pBueffel,255,", %f - %f", Alcatraz.fMin, Alcatraz.fMax); - Tcl_DStringAppend(&message,pBueffel,strlen(pBueffel)); - status = LLDnodePtr2Next(self->iForbidden); - } - Tcl_DStringAppend(&message,"}",1); - SCWrite(pCon,Tcl_DStringValue(&message),eValue); - Tcl_DStringFree(&message); + self = (pVelSel) pData; + assert(self); + + self->pDriv->Halt(self->pDriv); + EVCSetMode(self->pMonitor, EVIdle); + return 1; } -/*-------------------------------------------------------------------------*/ - static long VSSetValue(void *pData,SConnection *pCon, float fVal) - { - pVelSel self = NULL; - int i, iRet, iCode, iTest; - char pError[132], pBueffel[512]; - self = (pVelSel)pData; - assert(self); - - /* check user rights */ - iRet = SCMatchRights(pCon,(int)ObVal(self->pPar,RIGHT)); - if(iRet != 1 ) - { - SCWrite(pCon,"ERROR: you are not authorised to drive velocity selector", - eError); - return 0; - } - - /* try mimimum three times to get there */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->SetRotation(self->pDriv,fVal); - if(iRet) - { - EVCSetMode(self->pMonitor,EVDrive); - return 1; - } - else /* error case */ - { - self->pDriv->GetError(self->pDriv, &iCode, pError, 131); - sprintf(pBueffel,"WARNING: trying to fix: %s", - pError); - SCWrite(pCon,pBueffel,eLog); - iTest = self->pDriv->TryAndFixIt(self->pDriv,iCode); - switch(iTest) - { - case VELOOK: - EVCSetMode(self->pMonitor,EVDrive); - return 1; - break; - case VELOREDO: - /* actual redo done by loop */ - break; - case VELOFAIL: - sprintf(pBueffel,"ERROR: aborting with %s", pError); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,(int)ObVal(self->pPar,INT)); - return 0; - default: - assert(0); - } - } - } - /* if we are here we tried three times and failed to get it - work - */ - sprintf(pBueffel, - "ERRROR: Failed 3 times to vary rotation speed. Failing."); - SCWrite(pCon,pBueffel,eError); - SCSetInterrupt(pCon,(int)ObVal(self->pPar,INT)); - EVCSetMode(self->pMonitor,EVIdle); - return 0; - } -/*-----------------------------------------------------------------------*/ - static int VSCheckStatus(void *pData, SConnection *pCon) - { - pVelSel self = NULL; - int iRet, iCode,iTest; - char pError[132], pBueffel[512]; - int iSig; - float fVal; - - self = (pVelSel)pData; - assert(self); - - iRet = self->pDriv->GetStatus(self->pDriv,&iSig,&fVal); - InvokeCallBack(self->pCall,iSig,&fVal); - if(SCGetInterrupt(pCon) != eContinue) - { - return HWFault; - } - switch(iRet) - { - case VSACCEL: - return HWBusy; - break; - case VSOK: - EVCSetMode(self->pMonitor,EVMonitor); - return OKOK; - break; - case VSNOCON: - case VSFAIL: - self->pDriv->GetError(self->pDriv,&iCode,pError,131); - sprintf(pBueffel,"WARNING: %s detected",pError); - SCWrite(pCon,pBueffel,eWarning); - iTest = self->pDriv->TryAndFixIt(self->pDriv,iCode); - switch(iTest) - { - case VELOOK: - case VELOREDO: - return HWBusy; - break; - case VELOFAIL: - SCWrite(pCon, - "ERROR: velocity selector can not fix problem", - eError); - SCSetInterrupt(pCon,(int)ObVal(self->pPar,INT)); - EVCSetMode(self->pMonitor,EVIdle); - return HWFault; - default: - assert(0); - } - - default: - assert(0); - } - /* not reached */ - return HWFault; - } /*---------------------------------------------------------------------------*/ - static float VSGetValue(void *pData, SConnection *pCon) - { - pVelSel self = NULL; - int iRet, iCode,i, iTest; - char pError[132], pBueffel[512]; - float fVal; - - self = (pVelSel)pData; - assert(self); +static int VSLimits(void *pData, float fVal, char *pError, int iErrLen) +{ + pVelSel self = NULL; + Verbot Alcatraz; + int iRet; + char pBueffel[512]; - /* try three times, maximum */ - for(i = 0; i < 3; i++) - { - iRet = self->pDriv->GetRotation(self->pDriv,&fVal); - if(!iRet) - { - self->pDriv->GetError(self->pDriv,&iCode,pError,131); - iTest = self->pDriv->TryAndFixIt(self->pDriv,iCode); - switch(iTest) - { - case VELOOK: - case VELOREDO: - sprintf(pBueffel,"WARNING: problem %s fixed",pError); - SCWrite(pCon,pBueffel,eLog); - break; - case VELOFAIL: - sprintf(pBueffel,"ERROR: %s", pError); - SCWrite(pCon,pBueffel,eError); - return -9999.; - default: - assert(0); - } - } - else - { - return fVal; - } - } - return -9999; - } -/*-------------------------------------------------------------------------*/ - static void *VSGetInterface(void *pData, int iID) - { - pVelSel self = NULL; - - self = (pVelSel)pData; - assert(self); + self = (pVelSel) pData; + assert(self); - if(iID == DRIVEID) - { - return self->pDrivInt; - } - return NULL; - } -/*--------------------------------------------------------------------------*/ - pVelSel VSCreate(pMotor pTilt, pVelSelDriv pDriv) - { - pVelSel pNew = NULL; - SConnection *pCon = NULL; - - assert(pTilt); - assert(pDriv); - - /* allocate memory */ - pNew = (pVelSel)malloc(sizeof(VelSel)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(VelSel)); - - /* make descriptor */ - pNew->pDes = CreateDescriptor("VelocitySelector"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - pNew->pDes->GetInterface = VSGetInterface; - - /* create list */ - pNew->iForbidden = LLDcreate(sizeof(Verbot)); - if(pNew->iForbidden < 0) - { - VSDestroy(pNew); - return NULL; - } - - /* the parameter array */ - pNew->pPar = ObParCreate(3); - if(!pNew->pPar) - { - VSDestroy(pNew); - return NULL; - } - ObParInit(pNew->pPar,INT,"interrupt",(float)eAbortBatch,usMugger); - ObParInit(pNew->pPar,RIGHT,"userrights",(float)usUser,usMugger); - ObParInit(pNew->pPar,TILTPREC,"tilttolerance",0.1,usMugger); - /* the driveable interface */ - pNew->pDrivInt = CreateDrivableInterface(); - if(!pNew->pDrivInt) - { - VSDestroy(pNew); - return NULL; - } - pNew->pDrivInt->Halt = VSHalt; - pNew->pDrivInt->CheckLimits = VSLimits; - pNew->pDrivInt->SetValue = VSSetValue; - pNew->pDrivInt->CheckStatus = VSCheckStatus; - pNew->pDrivInt->GetValue = VSGetValue; + /* first let us check if we are in the overall range. + The first entry in the forbidden region thing is meant to + contain this information + */ + iRet = LLDnodePtr2First(self->iForbidden); + LLDnodeDataTo(self->iForbidden, &Alcatraz); + if ((fVal < Alcatraz.fMin) || (fVal > Alcatraz.fMax)) { + sprintf(pBueffel, " %f out of range: %f --- %f", + fVal, Alcatraz.fMin, Alcatraz.fMax); + strncpy(pError, pBueffel, iErrLen); + return 0; + } - /* The callback interface */ - pNew->pCall = CreateCallBackInterface(); - if(!pNew->pCall) - { - VSDestroy(pNew); - return 0; - } - - /* deal with that motor, have him AccessCode Internal */ - pNew->pTilt = pTilt; - pCon = SCCreateDummyConnection(pServ->pSics); - if(pCon != NULL) - { - MotorSetPar(pTilt,pCon,"accesscode",(float)usInternal); - SCDeleteConnection(pCon); - } - - /* enter driver */ - pNew->pDriv = pDriv; - pNew->pDriv->fTolerance = 15.; - - return pNew; - } -/*-------------------------------------------------------------------------*/ - void VSDestroy(void *pData) - { - char pBueffel[132]; - pVelSel self = NULL; - - self = (pVelSel)pData; - assert(self); - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - - if(self->pPar) - { - ObParDelete(self->pPar); - } - - if(self->pDriv) - { - VSDeleteDriver(self->pDriv); - } - - if(self->pCall) - { - DeleteCallBackInterface(self->pCall); - } - LLDdelete(self->iForbidden); - - if(self->pDrivInt) - { - free(self->pDrivInt); - } - - if(self->pMonitor) - { - strtolower(self->pName); - sprintf(pBueffel,"%swatch",self->pName); -/* EVUnregister(FindEMON(pServ->pSics),pBueffel); */ - DeleteEVController(self->pMonitor); - } - if(self->pName) - free(self->pName); - free(self); - } -/*--------------------------------------------------------------------------*/ - int VSAddVerbot(pVelSel self, float fMin, float fMax) - { - Verbot Alcatraz; - - assert(self); - - Alcatraz.fMin = fMin; - Alcatraz.fMax = fMax; - - LLDnodeAppendFrom(self->iForbidden,&Alcatraz); - return 1; - } -/*-------------------------------------------------------------------------*/ - int VSGetPar(pVelSel self, char *name, float *fVal) - { - ObPar *pPar = NULL; - - assert(self); - - pPar = ObParFind(self->pPar,name); - if(pPar) - { - *fVal = pPar->fVal; - return 1; - } + /* now search through the rest if in some forbidden region */ + iRet = LLDnodePtr2Next(self->iForbidden); + while (iRet != 0) { + LLDnodeDataTo(self->iForbidden, &Alcatraz); + if ((fVal > Alcatraz.fMin) && (fVal < Alcatraz.fMax)) { + sprintf(pBueffel, " %f violates forbidden region %f --- %f", + fVal, Alcatraz.fMin, Alcatraz.fMax); + strncpy(pError, pBueffel, iErrLen); return 0; - } + } + iRet = LLDnodePtr2Next(self->iForbidden); + } + /* Success ! */ + return 1; +} + +/*-----------------------------------------------------------------------*/ +static void VSListForbidden(pVelSel self, SConnection * pCon) +{ + Tcl_DString message; + int status; + Verbot Alcatraz; + char pBueffel[256]; + + Tcl_DStringInit(&message); + /* + The first entry in the forbidden region thing is meant to + contain the overall range: skip it! + */ + status = LLDnodePtr2First(self->iForbidden); + LLDnodeDataTo(self->iForbidden, &Alcatraz); + if (status == 1) { + snprintf(pBueffel, 255, "%s.forbidden = {%f -inf", self->pName, + Alcatraz.fMax); + Tcl_DStringAppend(&message, pBueffel, strlen(pBueffel)); + } + + /* now search the forbidden regions */ + status = LLDnodePtr2Next(self->iForbidden); + while (status != 0) { + LLDnodeDataTo(self->iForbidden, &Alcatraz); + snprintf(pBueffel, 255, ", %f - %f", Alcatraz.fMin, Alcatraz.fMax); + Tcl_DStringAppend(&message, pBueffel, strlen(pBueffel)); + status = LLDnodePtr2Next(self->iForbidden); + } + Tcl_DStringAppend(&message, "}", 1); + SCWrite(pCon, Tcl_DStringValue(&message), eValue); + Tcl_DStringFree(&message); +} + /*-------------------------------------------------------------------------*/ - int VSSetPar(pVelSel self,SConnection *pCon, char *name, float fVal) - { - assert(self); - return ObParSet(self->pPar,self->pDes->name, name, fVal,pCon); - } -/*------------------------------------------------------------------------*/ - int VSGetRotation(pVelSel self, float *fRot) - { - assert(self); - - return self->pDriv->GetRotation(self->pDriv,fRot); +static long VSSetValue(void *pData, SConnection * pCon, float fVal) +{ + pVelSel self = NULL; + int i, iRet, iCode, iTest; + char pError[132], pBueffel[512]; - } -/*------------------------------------------------------------------------*/ - int VSGetTilt(pVelSel self, float *fTilt) - { - assert(self); - - return self->pTilt->pDriver->GetPosition(self->pTilt->pDriver, fTilt); - - } -/*------------------------------------------------------------------------*/ - int VSSetTiltRot(pVelSel self, SConnection *pCon, float fNewRot, - float fNewTilt) - { - float fDelta, fOldTilt; - int iRet; - int iOldRight; - char pError[132]; - char pBueffel[256]; - - - assert(self); + self = (pVelSel) pData; + assert(self); - /* check if rotation in limits */ - iRet = VSLimits(self,fNewRot,pError,131); - if(!iRet) - { - sprintf(pBueffel,"ERROR: %s",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - - /* second: do I really need to modify tilt? */ - iRet = MotorGetSoftPosition(self->pTilt, pCon,&fOldTilt); - if(!iRet) - { - return 0; - } - fDelta = fNewTilt - fOldTilt; - if(fDelta < 0)fDelta = -fDelta; - if(fDelta > ObVal(self->pPar,TILTPREC)) /* yes */ - { - /* first stop the Rotation of the selector */ - iRet = StartDevice(GetExecutor(),"Velocity Selector Rot", - self->pDes, self, pCon,-10.); - if(!iRet) - { - return 0; - } - - /* wait for this to finish */ - SCWrite(pCon,"Stopping Velocity Selector, this may take a long while",eWarning); - iRet = Wait4Success(GetExecutor()); - if(iRet == DEVINT) - { - if(SCGetInterrupt(pCon) == eAbortOperation) - { - SCSetInterrupt(pCon,eContinue); - } - return 0; - } - - /* OK, selector stoped, drive tilt motor. We have to give internal - privilege to us beforehand, though - */ - iOldRight = SCGetRights(pCon); - SCSetRights(pCon,usInternal); - iRet = StartDevice(GetExecutor(),"Velocity Selector Tilt", - self->pTilt->pDescriptor, self->pTilt, - pCon,fNewTilt); + /* check user rights */ + iRet = SCMatchRights(pCon, (int) ObVal(self->pPar, RIGHT)); + if (iRet != 1) { + SCWrite(pCon, + "ERROR: you are not authorised to drive velocity selector", + eError); + return 0; + } - /* wait for this to finish */ - SCWrite(pCon,"Driving tilt-angle",eWarning); - iRet = Wait4Success(GetExecutor()); - if(iRet == DEVINT) - { - if(SCGetInterrupt(pCon) == eAbortOperation) - { - SCSetInterrupt(pCon,eContinue); - } - return 0; - } - - /* reset userrights */ - SCSetRights(pCon,iOldRight); - - } - - - /* drive rotation */ - iRet = StartDevice(GetExecutor(),"Velocity Selector Rot", - self->pDes, self, pCon,fNewRot); - if(!iRet) - { - return 0; - } - - /* wait for this to finish */ - SCWrite(pCon,"Running velocity selector to speed, this may take ages", - eWarning); - iRet = Wait4Success(GetExecutor()); - if(iRet == DEVINT) - { - if(SCGetInterrupt(pCon) == eAbortOperation) - { - SCSetInterrupt(pCon,eContinue); - } - return 0; - } + /* try mimimum three times to get there */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->SetRotation(self->pDriv, fVal); + if (iRet) { + EVCSetMode(self->pMonitor, EVDrive); return 1; - } + } else { /* error case */ + + self->pDriv->GetError(self->pDriv, &iCode, pError, 131); + sprintf(pBueffel, "WARNING: trying to fix: %s", pError); + SCWrite(pCon, pBueffel, eLog); + iTest = self->pDriv->TryAndFixIt(self->pDriv, iCode); + switch (iTest) { + case VELOOK: + EVCSetMode(self->pMonitor, EVDrive); + return 1; + break; + case VELOREDO: + /* actual redo done by loop */ + break; + case VELOFAIL: + sprintf(pBueffel, "ERROR: aborting with %s", pError); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, (int) ObVal(self->pPar, INT)); + return 0; + default: + assert(0); + } + } + } + /* if we are here we tried three times and failed to get it + work + */ + sprintf(pBueffel, + "ERRROR: Failed 3 times to vary rotation speed. Failing."); + SCWrite(pCon, pBueffel, eError); + SCSetInterrupt(pCon, (int) ObVal(self->pPar, INT)); + EVCSetMode(self->pMonitor, EVIdle); + return 0; +} + +/*-----------------------------------------------------------------------*/ +static int VSCheckStatus(void *pData, SConnection * pCon) +{ + pVelSel self = NULL; + int iRet, iCode, iTest; + char pError[132], pBueffel[512]; + int iSig; + float fVal; + + self = (pVelSel) pData; + assert(self); + + iRet = self->pDriv->GetStatus(self->pDriv, &iSig, &fVal); + InvokeCallBack(self->pCall, iSig, &fVal); + if (SCGetInterrupt(pCon) != eContinue) { + return HWFault; + } + switch (iRet) { + case VSACCEL: + return HWBusy; + break; + case VSOK: + EVCSetMode(self->pMonitor, EVMonitor); + return OKOK; + break; + case VSNOCON: + case VSFAIL: + self->pDriv->GetError(self->pDriv, &iCode, pError, 131); + sprintf(pBueffel, "WARNING: %s detected", pError); + SCWrite(pCon, pBueffel, eWarning); + iTest = self->pDriv->TryAndFixIt(self->pDriv, iCode); + switch (iTest) { + case VELOOK: + case VELOREDO: + return HWBusy; + break; + case VELOFAIL: + SCWrite(pCon, + "ERROR: velocity selector can not fix problem", eError); + SCSetInterrupt(pCon, (int) ObVal(self->pPar, INT)); + EVCSetMode(self->pMonitor, EVIdle); + return HWFault; + default: + assert(0); + } + + default: + assert(0); + } + /* not reached */ + return HWFault; +} + +/*---------------------------------------------------------------------------*/ +static float VSGetValue(void *pData, SConnection * pCon) +{ + pVelSel self = NULL; + int iRet, iCode, i, iTest; + char pError[132], pBueffel[512]; + float fVal; + + self = (pVelSel) pData; + assert(self); + + /* try three times, maximum */ + for (i = 0; i < 3; i++) { + iRet = self->pDriv->GetRotation(self->pDriv, &fVal); + if (!iRet) { + self->pDriv->GetError(self->pDriv, &iCode, pError, 131); + iTest = self->pDriv->TryAndFixIt(self->pDriv, iCode); + switch (iTest) { + case VELOOK: + case VELOREDO: + sprintf(pBueffel, "WARNING: problem %s fixed", pError); + SCWrite(pCon, pBueffel, eLog); + break; + case VELOFAIL: + sprintf(pBueffel, "ERROR: %s", pError); + SCWrite(pCon, pBueffel, eError); + return -9999.; + default: + assert(0); + } + } else { + return fVal; + } + } + return -9999; +} + +/*-------------------------------------------------------------------------*/ +static void *VSGetInterface(void *pData, int iID) +{ + pVelSel self = NULL; + + self = (pVelSel) pData; + assert(self); + + if (iID == DRIVEID) { + return self->pDrivInt; + } + return NULL; +} + /*--------------------------------------------------------------------------*/ - int VSGetLossCurrent(pVelSel self, SConnection *pCon, float *fLoss) - { - int iRet, iCode; - char pError[132], pBueffel[512]; - Status eOld; - - - assert(self); - assert(pCon); - - eOld = GetStatus(); - SetStatus(eRunning); - iRet = self->pDriv->GetLossCurrent(self->pDriv,fLoss); - SetStatus(eOld); - if(!iRet) - { - self->pDriv->GetError(self->pDriv,&iCode,pError,131); - sprintf(pBueffel,"ERROR: %s while trying to measure loss current", - pError); - SCWrite(pCon,pBueffel,eError); - return 0; +pVelSel VSCreate(pMotor pTilt, pVelSelDriv pDriv) +{ + pVelSel pNew = NULL; + SConnection *pCon = NULL; + + assert(pTilt); + assert(pDriv); + + /* allocate memory */ + pNew = (pVelSel) malloc(sizeof(VelSel)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(VelSel)); + + /* make descriptor */ + pNew->pDes = CreateDescriptor("VelocitySelector"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + pNew->pDes->GetInterface = VSGetInterface; + + /* create list */ + pNew->iForbidden = LLDcreate(sizeof(Verbot)); + if (pNew->iForbidden < 0) { + VSDestroy(pNew); + return NULL; + } + + /* the parameter array */ + pNew->pPar = ObParCreate(3); + if (!pNew->pPar) { + VSDestroy(pNew); + return NULL; + } + ObParInit(pNew->pPar, INT, "interrupt", (float) eAbortBatch, usMugger); + ObParInit(pNew->pPar, RIGHT, "userrights", (float) usUser, usMugger); + ObParInit(pNew->pPar, TILTPREC, "tilttolerance", 0.1, usMugger); + + /* the driveable interface */ + pNew->pDrivInt = CreateDrivableInterface(); + if (!pNew->pDrivInt) { + VSDestroy(pNew); + return NULL; + } + pNew->pDrivInt->Halt = VSHalt; + pNew->pDrivInt->CheckLimits = VSLimits; + pNew->pDrivInt->SetValue = VSSetValue; + pNew->pDrivInt->CheckStatus = VSCheckStatus; + pNew->pDrivInt->GetValue = VSGetValue; + + /* The callback interface */ + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pCall) { + VSDestroy(pNew); + return 0; + } + + /* deal with that motor, have him AccessCode Internal */ + pNew->pTilt = pTilt; + pCon = SCCreateDummyConnection(pServ->pSics); + if (pCon != NULL) { + MotorSetPar(pTilt, pCon, "accesscode", (float) usInternal); + SCDeleteConnection(pCon); + } + + /* enter driver */ + pNew->pDriv = pDriv; + pNew->pDriv->fTolerance = 15.; + + return pNew; +} + +/*-------------------------------------------------------------------------*/ +void VSDestroy(void *pData) +{ + char pBueffel[132]; + pVelSel self = NULL; + + self = (pVelSel) pData; + assert(self); + + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + + if (self->pPar) { + ObParDelete(self->pPar); + } + + if (self->pDriv) { + VSDeleteDriver(self->pDriv); + } + + if (self->pCall) { + DeleteCallBackInterface(self->pCall); + } + LLDdelete(self->iForbidden); + + if (self->pDrivInt) { + free(self->pDrivInt); + } + + if (self->pMonitor) { + strtolower(self->pName); + sprintf(pBueffel, "%swatch", self->pName); +/* EVUnregister(FindEMON(pServ->pSics),pBueffel); */ + DeleteEVController(self->pMonitor); + } + if (self->pName) + free(self->pName); + free(self); +} + +/*--------------------------------------------------------------------------*/ +int VSAddVerbot(pVelSel self, float fMin, float fMax) +{ + Verbot Alcatraz; + + assert(self); + + Alcatraz.fMin = fMin; + Alcatraz.fMax = fMax; + + LLDnodeAppendFrom(self->iForbidden, &Alcatraz); + return 1; +} + +/*-------------------------------------------------------------------------*/ +int VSGetPar(pVelSel self, char *name, float *fVal) +{ + ObPar *pPar = NULL; + + assert(self); + + pPar = ObParFind(self->pPar, name); + if (pPar) { + *fVal = pPar->fVal; + return 1; + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +int VSSetPar(pVelSel self, SConnection * pCon, char *name, float fVal) +{ + assert(self); + return ObParSet(self->pPar, self->pDes->name, name, fVal, pCon); +} + +/*------------------------------------------------------------------------*/ +int VSGetRotation(pVelSel self, float *fRot) +{ + assert(self); + + return self->pDriv->GetRotation(self->pDriv, fRot); + +} + +/*------------------------------------------------------------------------*/ +int VSGetTilt(pVelSel self, float *fTilt) +{ + assert(self); + + return self->pTilt->pDriver->GetPosition(self->pTilt->pDriver, fTilt); + +} + +/*------------------------------------------------------------------------*/ +int VSSetTiltRot(pVelSel self, SConnection * pCon, float fNewRot, + float fNewTilt) +{ + float fDelta, fOldTilt; + int iRet; + int iOldRight; + char pError[132]; + char pBueffel[256]; + + + assert(self); + + /* check if rotation in limits */ + iRet = VSLimits(self, fNewRot, pError, 131); + if (!iRet) { + sprintf(pBueffel, "ERROR: %s", pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + + /* second: do I really need to modify tilt? */ + iRet = MotorGetSoftPosition(self->pTilt, pCon, &fOldTilt); + if (!iRet) { + return 0; + } + fDelta = fNewTilt - fOldTilt; + if (fDelta < 0) + fDelta = -fDelta; + if (fDelta > ObVal(self->pPar, TILTPREC)) { /* yes */ + /* first stop the Rotation of the selector */ + iRet = StartDevice(GetExecutor(), "Velocity Selector Rot", + self->pDes, self, pCon, -10.); + if (!iRet) { + return 0; + } + + /* wait for this to finish */ + SCWrite(pCon, "Stopping Velocity Selector, this may take a long while", + eWarning); + iRet = Wait4Success(GetExecutor()); + if (iRet == DEVINT) { + if (SCGetInterrupt(pCon) == eAbortOperation) { + SCSetInterrupt(pCon, eContinue); } - return 1; - } + return 0; + } + + /* OK, selector stoped, drive tilt motor. We have to give internal + privilege to us beforehand, though + */ + iOldRight = SCGetRights(pCon); + SCSetRights(pCon, usInternal); + iRet = StartDevice(GetExecutor(), "Velocity Selector Tilt", + self->pTilt->pDescriptor, self->pTilt, + pCon, fNewTilt); + + /* wait for this to finish */ + SCWrite(pCon, "Driving tilt-angle", eWarning); + iRet = Wait4Success(GetExecutor()); + if (iRet == DEVINT) { + if (SCGetInterrupt(pCon) == eAbortOperation) { + SCSetInterrupt(pCon, eContinue); + } + return 0; + } + + /* reset userrights */ + SCSetRights(pCon, iOldRight); + + } + + + /* drive rotation */ + iRet = StartDevice(GetExecutor(), "Velocity Selector Rot", + self->pDes, self, pCon, fNewRot); + if (!iRet) { + return 0; + } + + /* wait for this to finish */ + SCWrite(pCon, "Running velocity selector to speed, this may take ages", + eWarning); + iRet = Wait4Success(GetExecutor()); + if (iRet == DEVINT) { + if (SCGetInterrupt(pCon) == eAbortOperation) { + SCSetInterrupt(pCon, eContinue); + } + return 0; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +int VSGetLossCurrent(pVelSel self, SConnection * pCon, float *fLoss) +{ + int iRet, iCode; + char pError[132], pBueffel[512]; + Status eOld; + + + assert(self); + assert(pCon); + + eOld = GetStatus(); + SetStatus(eRunning); + iRet = self->pDriv->GetLossCurrent(self->pDriv, fLoss); + SetStatus(eOld); + if (!iRet) { + self->pDriv->GetError(self->pDriv, &iCode, pError, 131); + sprintf(pBueffel, "ERROR: %s while trying to measure loss current", + pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} + /*======================================================================= Functions and definitions for the dummy environment device driver for the velocity selector. This has to be here, as it uses many static @@ -634,142 +610,141 @@ static void VSListForbidden(pVelSel self, SConnection *pCon){ #define VELONOTPERMITTED -1122 #include "evdriver.i" /*------------------ driver private data structure -----------------------*/ - typedef struct { - pVelSel pSel; - int iLastError; - } *pVelPrivate, VelPrivate; +typedef struct { + pVelSel pSel; + int iLastError; +} *pVelPrivate, VelPrivate; /*------------------------------------------------------------------------*/ - static void KillVelPrivate(void *pData) - { - pVelPrivate self = NULL; - - self = (pVelPrivate)pData; - if(self) - { - free(self); - } - } -/*------------------------------------------------------------------------*/ - static int DummyVelSet(pEVDriver self, float fNew) - { - pVelPrivate ich = NULL; - - assert(self); - ich = (pVelPrivate)self->pPrivate; - assert(ich); - - /* not permitted, must be done through nvs */ - ich->iLastError = VELONOTPERMITTED; - return 0; - } -/*-------------------------------------------------------------------------*/ - static int DummyVelGet(pEVDriver self, float *fPos) - { - float fVal; - pVelPrivate ich = NULL; - - assert(self); - ich = (pVelPrivate)self->pPrivate; - assert(ich); - - ich->iLastError = 0; - return ich->pSel->pDriv->GetRotation(ich->pSel->pDriv,fPos); - } -/*-------------------------------------------------------------------------*/ - static int DummyVelSend(pEVDriver self, char *pCommand, - char *pReply, int ReplyLen) - { - pVelPrivate ich = NULL; - - assert(self); - ich = (pVelPrivate)self->pPrivate; - assert(ich); - - /* not permitted, must be done through nvs */ - ich->iLastError = VELONOTPERMITTED; - return 0; - } -/*-------------------------------------------------------------------------*/ - static int DummyVelError(pEVDriver self, int *iCode, char *pError, - int iErrLen) - { - pVelPrivate ich = NULL; - - assert(self); - ich = (pVelPrivate)self->pPrivate; - assert(ich); - - if(ich->iLastError == VELONOTPERMITTED) - { - strncpy(pError, - "ERROR: this operation is NOT Permitted, use velocity selector object instead", - iErrLen); - *iCode = VELONOTPERMITTED; - return 1; - } - else - { - return ich->pSel->pDriv->GetError(ich->pSel->pDriv,iCode, - pError,iErrLen); - } - } -/*-------------------------------------------------------------------------*/ - static int DummyVelFix(pEVDriver self, int iCode) - { - pVelPrivate ich = NULL; - - assert(self); - ich = (pVelPrivate)self->pPrivate; - assert(ich); +static void KillVelPrivate(void *pData) +{ + pVelPrivate self = NULL; - if(ich->iLastError == VELONOTPERMITTED) - { - ich->iLastError = 0; - return DEVFAULT; - } - else - { - return ich->pSel->pDriv->TryAndFixIt(ich->pSel->pDriv,iCode); - } + self = (pVelPrivate) pData; + if (self) { + free(self); } +} + +/*------------------------------------------------------------------------*/ +static int DummyVelSet(pEVDriver self, float fNew) +{ + pVelPrivate ich = NULL; + + assert(self); + ich = (pVelPrivate) self->pPrivate; + assert(ich); + + /* not permitted, must be done through nvs */ + ich->iLastError = VELONOTPERMITTED; + return 0; +} + /*-------------------------------------------------------------------------*/ - static int DummyVelInit(pEVDriver self) - { - return 1; - } +static int DummyVelGet(pEVDriver self, float *fPos) +{ + float fVal; + pVelPrivate ich = NULL; + + assert(self); + ich = (pVelPrivate) self->pPrivate; + assert(ich); + + ich->iLastError = 0; + return ich->pSel->pDriv->GetRotation(ich->pSel->pDriv, fPos); +} + /*-------------------------------------------------------------------------*/ - pEVDriver MakeDummyVel(pVelSel pVel) - { - pEVDriver pNew = NULL; - pVelPrivate ich = NULL; - - pNew = (pEVDriver)malloc(sizeof(EVDriver)); - if(!pNew) - { - return NULL; - } - ich = (pVelPrivate)malloc(sizeof(VelPrivate)); - if(!ich) - { - free(pNew); - return NULL; - } - memset(pNew,0,sizeof(EVDriver)); - memset(ich,0,sizeof(VelPrivate)); - - /* initialise function pointers */ - pNew->SetValue = DummyVelSet; - pNew->GetValue = DummyVelGet; - pNew->Send = DummyVelSend; - pNew->GetError = DummyVelError; - pNew->TryFixIt = DummyVelFix; - pNew->Init = DummyVelInit; - pNew->Close = DummyVelInit; - ich->pSel = pVel; - pNew->pPrivate = ich; - pNew->KillPrivate = KillVelPrivate; - return pNew; - } +static int DummyVelSend(pEVDriver self, char *pCommand, + char *pReply, int ReplyLen) +{ + pVelPrivate ich = NULL; + + assert(self); + ich = (pVelPrivate) self->pPrivate; + assert(ich); + + /* not permitted, must be done through nvs */ + ich->iLastError = VELONOTPERMITTED; + return 0; +} + +/*-------------------------------------------------------------------------*/ +static int DummyVelError(pEVDriver self, int *iCode, char *pError, + int iErrLen) +{ + pVelPrivate ich = NULL; + + assert(self); + ich = (pVelPrivate) self->pPrivate; + assert(ich); + + if (ich->iLastError == VELONOTPERMITTED) { + strncpy(pError, + "ERROR: this operation is NOT Permitted, use velocity selector object instead", + iErrLen); + *iCode = VELONOTPERMITTED; + return 1; + } else { + return ich->pSel->pDriv->GetError(ich->pSel->pDriv, iCode, + pError, iErrLen); + } +} + +/*-------------------------------------------------------------------------*/ +static int DummyVelFix(pEVDriver self, int iCode) +{ + pVelPrivate ich = NULL; + + assert(self); + ich = (pVelPrivate) self->pPrivate; + assert(ich); + + if (ich->iLastError == VELONOTPERMITTED) { + ich->iLastError = 0; + return DEVFAULT; + } else { + return ich->pSel->pDriv->TryAndFixIt(ich->pSel->pDriv, iCode); + } +} + +/*-------------------------------------------------------------------------*/ +static int DummyVelInit(pEVDriver self) +{ + return 1; +} + +/*-------------------------------------------------------------------------*/ +pEVDriver MakeDummyVel(pVelSel pVel) +{ + pEVDriver pNew = NULL; + pVelPrivate ich = NULL; + + pNew = (pEVDriver) malloc(sizeof(EVDriver)); + if (!pNew) { + return NULL; + } + ich = (pVelPrivate) malloc(sizeof(VelPrivate)); + if (!ich) { + free(pNew); + return NULL; + } + memset(pNew, 0, sizeof(EVDriver)); + memset(ich, 0, sizeof(VelPrivate)); + + /* initialise function pointers */ + pNew->SetValue = DummyVelSet; + pNew->GetValue = DummyVelGet; + pNew->Send = DummyVelSend; + pNew->GetError = DummyVelError; + pNew->TryFixIt = DummyVelFix; + pNew->Init = DummyVelInit; + pNew->Close = DummyVelInit; + ich->pSel = pVel; + pNew->pPrivate = ich; + pNew->KillPrivate = KillVelPrivate; + return pNew; +} + /*--------------------------------------------------------------------------- Usage: VelSelFactory name TiltMot DRIVER optionname @@ -778,483 +753,440 @@ static void VSListForbidden(pVelSel self, SConnection *pCon){ - DRIVER is the type of driver to use. - TclArray is a Tcl array containing configuration options for the driver. -*/ - int VelSelFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pVelSelDriv pDriv = NULL; - pVelSel pNew = NULL; - pMotor pTilt = NULL; - char pBueffel[256]; - Tcl_Interp *pT = NULL; - int iRet; - pEVDriver pMonDriv = NULL; - pSite site = NULL; +*/ +int VelSelFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pVelSelDriv pDriv = NULL; + pVelSel pNew = NULL; + pMotor pTilt = NULL; + char pBueffel[256]; + Tcl_Interp *pT = NULL; + int iRet; + pEVDriver pMonDriv = NULL; + pSite site = NULL; - assert(pCon); - assert(pSics); - - /* minimum 4 arguments! */ - if(argc < 4) - { - SCWrite(pCon,"ERROR: Insufficient number of arguments to VelSelFactory", - eError); - return 0; - } - - /* first one is name */ - /* second one should be motor */ - strtolower(argv[1]); - strtolower(argv[2]); - pTilt = FindMotor(pSics,argv[2]); - if(!pTilt) - { - sprintf(pBueffel,"ERROR: in VelSelFactory --> %s is not valid motor!", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* third should be driver name */ - strtolower(argv[3]); - if(strcmp(argv[3],"sim") == 0) /* Mr. Simulation */ - { - pDriv = VSCreateSim(); - } - else - { - if(argc < 5) - { - sprintf(pBueffel, - "ERROR: missing options array for velocity selector"); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pT = InterpGetTcl(pSics); - site = getSite(); - if(site != NULL) - { - pDriv = site->CreateVelocitySelector(argv[3],argv[4],pT); - } - if(!pDriv) - { - SCWrite(pCon,pT->result,eError); - return 0; - } - } - - if(!pDriv) - { - sprintf(pBueffel,"ERROR: creating velocity selector driver %s", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* now initialise this and install it as command */ - pNew = VSCreate(pTilt,pDriv); - if(!pNew) - { - SCWrite(pCon,"ERROR: creating velocity selector, no memory",eError); - return 0; - } - iRet = pDriv->Init(pDriv,pCon); - if(!iRet) - { - SCWrite(pCon,"ERROR: failed to initialize velocity selector", - eError); - VSDestroy(pNew); - return 0; - } - pNew->pName = strdup(argv[1]); - iRet = AddCommand(pSics,argv[1],VelSelAction, - VSDestroy,pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",argv[2]); - SCWrite(pCon,pBueffel,eError); - VSDestroy((void *)pNew); - return 0; - } - - /* install the evcontroller bit of the velocity selector */ - pMonDriv = MakeDummyVel(pNew); - if(!pMonDriv) - { - RemoveCommand(pSics,argv[1]); - SCWrite(pCon,"ERROR: failed to create monitor for nvs",eError); - return 0; - } - pBueffel[0] = '\0'; - strcpy(pBueffel,argv[1]); - strcat(pBueffel,"watch"); - pNew->pMonitor = CreateEVController(pMonDriv,pBueffel,&iRet); - if(!pNew->pMonitor) - { - DeleteEVDriver(pMonDriv); /* was missing M.Z. Jul 04 */ - SCWrite(pCon,"ERROR: failed to create monitor for nvs",eError); - return 0; - } - iRet = AddCommand(pSics,pBueffel,EVControlWrapper, - NULL,pNew->pMonitor); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",pBueffel); - RemoveCommand(pSics,argv[1]); - return 0; - } - EVRegisterController(FindEMON(pSics),pBueffel,pNew->pMonitor,pCon); - return iRet; - } -/*------------------------------------------------------------------------*/ - typedef struct { - SConnection *pCon; - char *pName; - } CBData; -/*------------------------------------------------------------------------*/ - static void KillCB(void *pData) - { - CBData *pCB = NULL; - - pCB = (CBData *)pData; - if(pCB) - { - if(pCB->pName) - { - free(pCB->pName); - } - if(pCB->pCon) - { - SCDeleteConnection(pCB->pCon); - } - free(pCB); + assert(pCon); + assert(pSics); + + /* minimum 4 arguments! */ + if (argc < 4) { + SCWrite(pCon, + "ERROR: Insufficient number of arguments to VelSelFactory", + eError); + return 0; + } + + /* first one is name */ + /* second one should be motor */ + strtolower(argv[1]); + strtolower(argv[2]); + pTilt = FindMotor(pSics, argv[2]); + if (!pTilt) { + sprintf(pBueffel, "ERROR: in VelSelFactory --> %s is not valid motor!", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* third should be driver name */ + strtolower(argv[3]); + if (strcmp(argv[3], "sim") == 0) { /* Mr. Simulation */ + pDriv = VSCreateSim(); + } else { + if (argc < 5) { + sprintf(pBueffel, + "ERROR: missing options array for velocity selector"); + SCWrite(pCon, pBueffel, eError); + return 0; } - } + pT = InterpGetTcl(pSics); + site = getSite(); + if (site != NULL) { + pDriv = site->CreateVelocitySelector(argv[3], argv[4], pT); + } + if (!pDriv) { + SCWrite(pCon, pT->result, eError); + return 0; + } + } + + if (!pDriv) { + sprintf(pBueffel, "ERROR: creating velocity selector driver %s", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* now initialise this and install it as command */ + pNew = VSCreate(pTilt, pDriv); + if (!pNew) { + SCWrite(pCon, "ERROR: creating velocity selector, no memory", eError); + return 0; + } + iRet = pDriv->Init(pDriv, pCon); + if (!iRet) { + SCWrite(pCon, "ERROR: failed to initialize velocity selector", eError); + VSDestroy(pNew); + return 0; + } + pNew->pName = strdup(argv[1]); + iRet = AddCommand(pSics, argv[1], VelSelAction, VSDestroy, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[2]); + SCWrite(pCon, pBueffel, eError); + VSDestroy((void *) pNew); + return 0; + } + + /* install the evcontroller bit of the velocity selector */ + pMonDriv = MakeDummyVel(pNew); + if (!pMonDriv) { + RemoveCommand(pSics, argv[1]); + SCWrite(pCon, "ERROR: failed to create monitor for nvs", eError); + return 0; + } + pBueffel[0] = '\0'; + strcpy(pBueffel, argv[1]); + strcat(pBueffel, "watch"); + pNew->pMonitor = CreateEVController(pMonDriv, pBueffel, &iRet); + if (!pNew->pMonitor) { + DeleteEVDriver(pMonDriv); /* was missing M.Z. Jul 04 */ + SCWrite(pCon, "ERROR: failed to create monitor for nvs", eError); + return 0; + } + iRet = AddCommand(pSics, pBueffel, EVControlWrapper, + NULL, pNew->pMonitor); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", pBueffel); + RemoveCommand(pSics, argv[1]); + return 0; + } + EVRegisterController(FindEMON(pSics), pBueffel, pNew->pMonitor, pCon); + return iRet; +} + /*------------------------------------------------------------------------*/ - static int RotationInterest(int iEvent, void *pData, void *pUser) - { - CBData *pDat = NULL; - float *fVal = NULL; - char pBueffel[512]; - - fVal = (float *)pData; - pDat = (CBData *)pUser; - assert(fVal); - assert(pData); - - if(!SCisConnected(pDat->pCon)){ - return -1; - } - - if(iEvent == ROTSTART) - { - sprintf(pBueffel,"%s Starting",pDat->pName); - SCWrite(pDat->pCon,pBueffel,eWarning); - } - else if(iEvent == ROTMOVE) - { - sprintf(pBueffel,"%s.rpm = %f",pDat->pName, *fVal); - SCWrite(pDat->pCon,pBueffel,eWarning); - } - return 1; - } +typedef struct { + SConnection *pCon; + char *pName; +} CBData; /*------------------------------------------------------------------------*/ - int VelSelAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pVelSel self = NULL; - char pCommand[512], pBueffel[256]; - char *pPtr = NULL; - float fTilt, fRot, fVal; - int iDrive = 0; - int iRet; - float fMin, fMax, fLoss, fTol; - double dVal; - ObPar *pPar = NULL; - CBData *pCB = NULL; - long lID; - - self = (pVelSel)pData; - - assert(self); - assert(pCon); - assert(pSics); - - if(argc < 2) - { - sprintf(pBueffel,"ERROR: %s expects at least one parameter",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +static void KillCB(void *pData) +{ + CBData *pCB = NULL; - /* check for parameters */ - pPar = ObParFind(self->pPar,argv[1]); - if(pPar) /* yes it is a parameter */ - { - if(argc >= 3) /* user wants to set */ - { - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: %s not recognized as numeric value for parameter", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return ObParSet(self->pPar,argv[0], argv[1],(float)dVal,pCon); - } - else /* just print it */ - { - sprintf(pBueffel,"%s.%s = %f",argv[0],argv[1],pPar->fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - - /* rotinterest command */ - if(strcmp(argv[1],"rotinterest") == 0) - { - pCB = (CBData *)malloc(sizeof(CBData)); - if(!pCB) - { - SCWrite(pCon,"ERROR: no memory in velo.c ",eError); - return 0; - } - pCB->pCon = SCCopyConnection(pCon); - pCB->pName = strdup(argv[0]); - lID = RegisterCallback(self->pCall,ROTSTART, RotationInterest, - pCB, KillCB); - lID = RegisterCallback(self->pCall, ROTMOVE, RotationInterest, - pCB, NULL); - SCSendOK(pCon); - return 1; - } + pCB = (CBData *) pData; + if (pCB) { + if (pCB->pName) { + free(pCB->pName); + } + if (pCB->pCon) { + SCDeleteConnection(pCB->pCon); + } + free(pCB); + } +} - /* add command, adds forbidden regions */ - if(strcmp(argv[1],"add") == 0) - { - /* only Managers may do this */ - if(!SCMatchRights(pCon,usMugger)) - { - SCWrite(pCon,"ERROR: you are NOT authorised to drive velocity selector", - eError); - return 0; - } - /* next two arguments must be min, max */ - if( argc < 4) - { - sprintf(pBueffel,"ERROR: insufficient number to %s add", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* OK find fMin */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: %s not recognized as numeric value for fMin", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fMin = (float)dVal; - - /* OK find fMax */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[3],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: %s not recognized as numeric value for fMax", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fMax = (float)dVal; - - /* do it */ - VSAddVerbot(self,fMin,fMax); - SCSendOK(pCon); - return 1; - } +/*------------------------------------------------------------------------*/ +static int RotationInterest(int iEvent, void *pData, void *pUser) +{ + CBData *pDat = NULL; + float *fVal = NULL; + char pBueffel[512]; - /* list forbidden regions */ - if(strcmp(argv[1],"forbidden") == 0) - { - VSListForbidden(self,pCon); - return 1; - } - - /* status, prints a status message */ - if(strcmp(argv[1],"status") == 0) - { - self->pDriv->GetDriverText(self->pDriv,pBueffel,511); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - - /* loss command, determine loss current */ - if(strcmp(argv[1],"loss") == 0 ) - { - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: you are NOT authorised to determine loss current", - eError); - return 0; - } - iRet = VSGetLossCurrent(self,pCon,&fLoss); - if(iRet) - { - sprintf(pBueffel,"%s.LossCurrent = %f",argv[0], fLoss); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { /* error should have been reported in VSGetLossCurrent */ - return 0; - } - } + fVal = (float *) pData; + pDat = (CBData *) pUser; + assert(fVal); + assert(pData); - /* init command for reinitialising */ - if(strcmp(argv[1],"init") == 0 ) - { - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: you are NOT authorised to determine loss current", - eError); - return 0; - } - iRet = self->pDriv->Init(self->pDriv,pCon); - if(iRet) - { - SCSendOK(pCon); - return 1; - } - else - { /* error should have been reported in Init */ - return 0; - } - } + if (!SCisConnected(pDat->pCon)) { + return -1; + } - if(strcmp(argv[1],"rottolerance") == 0){ - if(argc > 2){ - /* set case */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK){ - sprintf(pBueffel,"ERROR: %s not recognized as numeric value for fMax", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - self->pDriv->fTolerance = dVal; - SCSendOK(pCon); - return 1; - } else { - sprintf(pBueffel,"%s.rottolerance = %f", - argv[0],self->pDriv->fTolerance); - SCWrite(pCon,pBueffel,eError); - return 1; - } - } - - /* initialise the tilt and rot to current values */ - iRet = VSGetRotation(self,&fRot); - if(!iRet) - { - SCWrite(pCon,"ERROR: cannot find current rotation speed",eError); - return 0; - } - iRet = MotorGetSoftPosition(self->pTilt,pCon,&fTilt); - if(!iRet) - { - SCWrite(pCon,"ERROR: failed to read tilt angle",eError); - return 0; - } - - - /* search for Tilt */ - if(strcmp(argv[1],"tilt") == 0){ - if(argc > 2){ - /* set case */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK){ - sprintf(pBueffel,"ERROR: %s not recognized as numeric value for fMax", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fTilt = dVal; - iDrive = 1; - } else { - sprintf(pBueffel,"%s tilt = %f",argv[0],fTilt); - SCWrite(pCon,pBueffel,eError); - return 1; - } - } - - - /* same for rot */ - if(strcmp(argv[1],"rot") == 0){ - if(argc > 2){ - /* set case */ - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK){ - sprintf(pBueffel,"ERROR: %s not recognized as numeric value for fMax", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fRot = dVal; - iDrive = 1; - } else { - sprintf(pBueffel,"%s rot = %f",argv[0],fRot); - SCWrite(pCon,pBueffel,eError); - return 1; - } - } + if (iEvent == ROTSTART) { + sprintf(pBueffel, "%s Starting", pDat->pName); + SCWrite(pDat->pCon, pBueffel, eWarning); + } else if (iEvent == ROTMOVE) { + sprintf(pBueffel, "%s.rpm = %f", pDat->pName, *fVal); + SCWrite(pDat->pCon, pBueffel, eWarning); + } + return 1; +} - /* do drive if we really need to */ - if(iDrive) - { - /* first check permission */ - if(!SCMatchRights(pCon,ObVal(self->pPar,RIGHT)) ) - { - SCWrite(pCon,"ERROR: you are NOT authorised to drive velocity selector", - eError); - return 0; - } - SetStatus(eDriving); - iRet = VSSetTiltRot(self,pCon,fRot,fTilt); - SetStatus(eEager); - if(iRet) - { - SCSendOK(pCon); - return 1; - } - else - { - return 0; - } - } - - /* no driving asked for, check for other commands */ - if(argc < 2) - { - goto end; - } - /* list command */ - if(strcmp(argv[1],"list") == 0) - { - sprintf(pBueffel,"%s.rotation = %f\n%s.Tilt = %f",argv[0], fRot, - argv[0],fTilt); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - - end: - /* command not recognized */ - sprintf(pBueffel,"ERROR: command %s not recognized",pCommand); - SCWrite(pCon,pBueffel,eError); - return 0; - } +/*------------------------------------------------------------------------*/ +int VelSelAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pVelSel self = NULL; + char pCommand[512], pBueffel[256]; + char *pPtr = NULL; + float fTilt, fRot, fVal; + int iDrive = 0; + int iRet; + float fMin, fMax, fLoss, fTol; + double dVal; + ObPar *pPar = NULL; + CBData *pCB = NULL; + long lID; + + self = (pVelSel) pData; + + assert(self); + assert(pCon); + assert(pSics); + + if (argc < 2) { + sprintf(pBueffel, "ERROR: %s expects at least one parameter", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* check for parameters */ + pPar = ObParFind(self->pPar, argv[1]); + if (pPar) { /* yes it is a parameter */ + if (argc >= 3) { /* user wants to set */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: %s not recognized as numeric value for parameter", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return ObParSet(self->pPar, argv[0], argv[1], (float) dVal, pCon); + } else { /* just print it */ + + sprintf(pBueffel, "%s.%s = %f", argv[0], argv[1], pPar->fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + + /* rotinterest command */ + if (strcmp(argv[1], "rotinterest") == 0) { + pCB = (CBData *) malloc(sizeof(CBData)); + if (!pCB) { + SCWrite(pCon, "ERROR: no memory in velo.c ", eError); + return 0; + } + pCB->pCon = SCCopyConnection(pCon); + pCB->pName = strdup(argv[0]); + lID = RegisterCallback(self->pCall, ROTSTART, RotationInterest, + pCB, KillCB); + lID = RegisterCallback(self->pCall, ROTMOVE, RotationInterest, + pCB, NULL); + SCSendOK(pCon); + return 1; + } + + /* add command, adds forbidden regions */ + if (strcmp(argv[1], "add") == 0) { + /* only Managers may do this */ + if (!SCMatchRights(pCon, usMugger)) { + SCWrite(pCon, + "ERROR: you are NOT authorised to drive velocity selector", + eError); + return 0; + } + /* next two arguments must be min, max */ + if (argc < 4) { + sprintf(pBueffel, "ERROR: insufficient number to %s add", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* OK find fMin */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: %s not recognized as numeric value for fMin", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fMin = (float) dVal; + + /* OK find fMax */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[3], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: %s not recognized as numeric value for fMax", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fMax = (float) dVal; + + /* do it */ + VSAddVerbot(self, fMin, fMax); + SCSendOK(pCon); + return 1; + } + + /* list forbidden regions */ + if (strcmp(argv[1], "forbidden") == 0) { + VSListForbidden(self, pCon); + return 1; + } + + /* status, prints a status message */ + if (strcmp(argv[1], "status") == 0) { + self->pDriv->GetDriverText(self->pDriv, pBueffel, 511); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + + /* loss command, determine loss current */ + if (strcmp(argv[1], "loss") == 0) { + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, + "ERROR: you are NOT authorised to determine loss current", + eError); + return 0; + } + iRet = VSGetLossCurrent(self, pCon, &fLoss); + if (iRet) { + sprintf(pBueffel, "%s.LossCurrent = %f", argv[0], fLoss); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { /* error should have been reported in VSGetLossCurrent */ + return 0; + } + } + + /* init command for reinitialising */ + if (strcmp(argv[1], "init") == 0) { + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, + "ERROR: you are NOT authorised to determine loss current", + eError); + return 0; + } + iRet = self->pDriv->Init(self->pDriv, pCon); + if (iRet) { + SCSendOK(pCon); + return 1; + } else { /* error should have been reported in Init */ + return 0; + } + } + + if (strcmp(argv[1], "rottolerance") == 0) { + if (argc > 2) { + /* set case */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: %s not recognized as numeric value for fMax", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + self->pDriv->fTolerance = dVal; + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "%s.rottolerance = %f", + argv[0], self->pDriv->fTolerance); + SCWrite(pCon, pBueffel, eError); + return 1; + } + } + + /* initialise the tilt and rot to current values */ + iRet = VSGetRotation(self, &fRot); + if (!iRet) { + SCWrite(pCon, "ERROR: cannot find current rotation speed", eError); + return 0; + } + iRet = MotorGetSoftPosition(self->pTilt, pCon, &fTilt); + if (!iRet) { + SCWrite(pCon, "ERROR: failed to read tilt angle", eError); + return 0; + } + + + /* search for Tilt */ + if (strcmp(argv[1], "tilt") == 0) { + if (argc > 2) { + /* set case */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: %s not recognized as numeric value for fMax", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fTilt = dVal; + iDrive = 1; + } else { + sprintf(pBueffel, "%s tilt = %f", argv[0], fTilt); + SCWrite(pCon, pBueffel, eError); + return 1; + } + } + + + /* same for rot */ + if (strcmp(argv[1], "rot") == 0) { + if (argc > 2) { + /* set case */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, + "ERROR: %s not recognized as numeric value for fMax", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fRot = dVal; + iDrive = 1; + } else { + sprintf(pBueffel, "%s rot = %f", argv[0], fRot); + SCWrite(pCon, pBueffel, eError); + return 1; + } + } + + /* do drive if we really need to */ + if (iDrive) { + /* first check permission */ + if (!SCMatchRights(pCon, ObVal(self->pPar, RIGHT))) { + SCWrite(pCon, + "ERROR: you are NOT authorised to drive velocity selector", + eError); + return 0; + } + SetStatus(eDriving); + iRet = VSSetTiltRot(self, pCon, fRot, fTilt); + SetStatus(eEager); + if (iRet) { + SCSendOK(pCon); + return 1; + } else { + return 0; + } + } + + /* no driving asked for, check for other commands */ + if (argc < 2) { + goto end; + } + /* list command */ + if (strcmp(argv[1], "list") == 0) { + sprintf(pBueffel, "%s.rotation = %f\n%s.Tilt = %f", argv[0], fRot, + argv[0], fTilt); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + +end: + /* command not recognized */ + sprintf(pBueffel, "ERROR: command %s not recognized", pCommand); + SCWrite(pCon, pBueffel, eError); + return 0; +} diff --git a/velo.h b/velo.h index 136b7d7b..72555fd8 100644 --- a/velo.h +++ b/velo.h @@ -19,17 +19,17 @@ #line 100 "velo.w" - typedef struct __VelSel *pVelSel; - typedef struct __VelSelDriv *pVelSelDriv; +typedef struct __VelSel *pVelSel; +typedef struct __VelSelDriv *pVelSelDriv; - pVelSel VSCreate(pMotor pTilt, pVelSelDriv pDriv); - void VSDestroy(void *self); +pVelSel VSCreate(pMotor pTilt, pVelSelDriv pDriv); +void VSDestroy(void *self); - int VSAddVerbot(pVelSel self, float fMin, float fMax); - int VSSetPar(pVelSel self,SConnection *pCon, char *name, float fVal); - int VSGetPar(pVelSel self,char *name, float *fVal); - int VSGetRotation(pVelSel self, float *fRot); - int VSGetTilt(pVelSel self, float *fTilt); +int VSAddVerbot(pVelSel self, float fMin, float fMax); +int VSSetPar(pVelSel self, SConnection * pCon, char *name, float fVal); +int VSGetPar(pVelSel self, char *name, float *fVal); +int VSGetRotation(pVelSel self, float *fRot); +int VSGetTilt(pVelSel self, float *fTilt); #line 262 "velo.w" @@ -41,14 +41,14 @@ int VSSetRotation(pVelSel self, SConnection *pCon, float fNew); int VSSetTilt(pVelSel self, SConnection *pCon, float FNewTilt); */ - int VSSetTiltRot(pVelSel self, SConnection *pCon, - float fNewRot, float fNewTilt); +int VSSetTiltRot(pVelSel self, SConnection * pCon, + float fNewRot, float fNewTilt); #line 264 "velo.w" #line 164 "velo.w" - int VSGetLossCurrent(pVelSel self, SConnection *pCon, float *fLoss); +int VSGetLossCurrent(pVelSel self, SConnection * pCon, float *fLoss); #line 265 "velo.w" @@ -56,11 +56,11 @@ #line 173 "velo.w" - int VelSelFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int VelSelAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +int VelSelFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int VelSelAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + #line 267 "velo.w" diff --git a/velodriv.h b/velodriv.h index 9ca1a20e..24feecd1 100644 --- a/velodriv.h +++ b/velodriv.h @@ -15,37 +15,28 @@ #line 185 "velo.w" - typedef struct __VelSelDriv { - void *pPrivate; - void (*DeletePrivate)(void *pData); - float fTolerance; - int (*Halt)(pVelSelDriv self); - int (*GetError)(pVelSelDriv self, - int *iCode, char *pError, - int iErrlen); - int (*TryAndFixIt)(pVelSelDriv self, - int iCode); - int (*GetRotation)(pVelSelDriv self, - float *fRot); - int (*SetRotation)(pVelSelDriv self, - float fRot); - int (*GetStatus)(pVelSelDriv self, - int *iCall, float *fCur); - int (*GetDriverText)(pVelSelDriv self, - char *pText, - int iTextLen); - int (*GetLossCurrent)(pVelSelDriv self, - float *fLoss); - int (*Init)(pVelSelDriv self, - SConnection *pCon); - }VelSelDriv; +typedef struct __VelSelDriv { + void *pPrivate; + void (*DeletePrivate) (void *pData); + float fTolerance; + int (*Halt) (pVelSelDriv self); + int (*GetError) (pVelSelDriv self, + int *iCode, char *pError, int iErrlen); + int (*TryAndFixIt) (pVelSelDriv self, int iCode); + int (*GetRotation) (pVelSelDriv self, float *fRot); + int (*SetRotation) (pVelSelDriv self, float fRot); + int (*GetStatus) (pVelSelDriv self, int *iCall, float *fCur); + int (*GetDriverText) (pVelSelDriv self, char *pText, int iTextLen); + int (*GetLossCurrent) (pVelSelDriv self, float *fLoss); + int (*Init) (pVelSelDriv self, SConnection * pCon); +} VelSelDriv; #line 307 "velo.w" /*-------------------- live & death ----------------------------------------*/ - pVelSelDriv VSCreateSim(void); - pVelSelDriv VSCreateDornierSINQ(char *name,Tcl_Interp *pTcl); +pVelSelDriv VSCreateSim(void); +pVelSelDriv VSCreateDornierSINQ(char *name, Tcl_Interp * pTcl); - void VSDeleteDriver(pVelSelDriv self); +void VSDeleteDriver(pVelSelDriv self); -#endif +#endif diff --git a/velosim.c b/velosim.c index 20fccb60..6e7012f7 100644 --- a/velosim.c +++ b/velosim.c @@ -60,260 +60,245 @@ typedef struct __VelSelDriv *pVelSelDriv; #define VSACCEL -7 #define VSFAIL -2 -#define FAILURE 1 /* a flat 1% error rate for trouble detection */ +#define FAILURE 1 /* a flat 1% error rate for trouble detection */ /* -------- A private datastructure for velocity selector simulation */ - - typedef struct { - long lTime; - float fPos; - } Simi, *pSimi; + +typedef struct { + long lTime; + float fPos; +} Simi, *pSimi; /*----------------------------------------------------------------------------*/ - static float SimRandom(void) - { - float fVal; - - fVal = ( (float) rand() / (float)RAND_MAX) * 100.0; - return fVal; - } -/*---------------------------------------------------------------------------*/ - static int RunComplete(pVelSelDriv self) - { - time_t tD; - pSimi pDriv; - - pDriv = (pSimi)self->pPrivate; - if((int)time(&tD) > pDriv->lTime) - { - return 1; - } - return 0; - } -/*--------------------------------------------------------------------------*/ - static int SimInit(pVelSelDriv self, SConnection *pCon) - { - pSimi pDriv; - - assert(self); +static float SimRandom(void) +{ + float fVal; - pDriv = (pSimi)self->pPrivate; - pDriv->fPos = 0.0; + fVal = ((float) rand() / (float) RAND_MAX) * 100.0; + return fVal; +} + +/*---------------------------------------------------------------------------*/ +static int RunComplete(pVelSelDriv self) +{ + time_t tD; + pSimi pDriv; + + pDriv = (pSimi) self->pPrivate; + if ((int) time(&tD) > pDriv->lTime) { return 1; } + return 0; +} + +/*--------------------------------------------------------------------------*/ +static int SimInit(pVelSelDriv self, SConnection * pCon) +{ + pSimi pDriv; + + assert(self); + + pDriv = (pSimi) self->pPrivate; + pDriv->fPos = 0.0; + return 1; +} /*----------------------------------------------------------------------------*/ - static int GetSimPos(pVelSelDriv self, float *fPos) - { - - pSimi pDriv; +static int GetSimPos(pVelSelDriv self, float *fPos) +{ - assert(self); - if(SimRandom() < FAILURE) - { - *fPos = SimRandom(); - return HWFault; - } - - pDriv = (pSimi)self->pPrivate; - if(RunComplete(self)) - { - *fPos = pDriv->fPos; - } - else /* simulate a selector running at a strange speed */ - { - if(SimRandom() < FAILURE) - { - *fPos = pDriv->fPos - 10.; - } - else - { - *fPos = pDriv->fPos; - } - return OKOK; + pSimi pDriv; + + assert(self); + if (SimRandom() < FAILURE) { + *fPos = SimRandom(); + return HWFault; + } + + pDriv = (pSimi) self->pPrivate; + if (RunComplete(self)) { + *fPos = pDriv->fPos; + } else { /* simulate a selector running at a strange speed */ + + if (SimRandom() < FAILURE) { + *fPos = pDriv->fPos - 10.; + } else { + *fPos = pDriv->fPos; } return OKOK; - } -/*----------------------------------------------------------------------------*/ - static int SimRun(pVelSelDriv self, float fVal) - { - float fDiff; - time_t tD; - pSimi pDriv; - - assert(self); - - /* calculate time for completion */ - pDriv = (pSimi)self->pPrivate; - fDiff = fVal - pDriv->fPos; - if(fDiff < .0) fDiff = -fDiff; - pDriv->lTime = (int)time(&tD) + (int)(fDiff/10000.); - - /* in a fifth the failures, simply die, else simply do not find pos */ - if(SimRandom() < (FAILURE/5)) - { - return HWFault; - } - else - { - pDriv->fPos = fVal; - return OKOK; - } - } -/*--------------------------------------------------------------------------*/ - static int SimError(pVelSelDriv self, int *iCode, char *error, int iErrLen) - { - assert(self); - - if(RunComplete(self)) - { - *iCode = 56; - strncpy(error, - "ERROR: HW: Simulated selector error on simulated selector",iErrLen); - } - else - { - *iCode = 12; - strncpy(error,"Selector still creeping along",iErrLen-1); - } - return 1; } + return OKOK; +} + +/*----------------------------------------------------------------------------*/ +static int SimRun(pVelSelDriv self, float fVal) +{ + float fDiff; + time_t tD; + pSimi pDriv; + + assert(self); + + /* calculate time for completion */ + pDriv = (pSimi) self->pPrivate; + fDiff = fVal - pDriv->fPos; + if (fDiff < .0) + fDiff = -fDiff; + pDriv->lTime = (int) time(&tD) + (int) (fDiff / 10000.); + + /* in a fifth the failures, simply die, else simply do not find pos */ + if (SimRandom() < (FAILURE / 5)) { + return HWFault; + } else { + pDriv->fPos = fVal; + return OKOK; + } +} + +/*--------------------------------------------------------------------------*/ +static int SimError(pVelSelDriv self, int *iCode, char *error, int iErrLen) +{ + assert(self); + + if (RunComplete(self)) { + *iCode = 56; + strncpy(error, + "ERROR: HW: Simulated selector error on simulated selector", + iErrLen); + } else { + *iCode = 12; + strncpy(error, "Selector still creeping along", iErrLen - 1); + } + return 1; +} + /*---------------------------------------------------------------------------*/ - static int SimFix(pVelSelDriv self, int iError) - { - float fRand; - - /* return the three values MOTREDO, MOTFAIL, MOTOK with a third - randomness - */ - assert(self); - fRand = SimRandom(); - - if(iError == 12) - { - return VELOREDO; - } - - SICSLogWrite("Selector dying randomly",eHWError); - if(fRand < 0.3333) - { - return VELOOK; - } - else if(fRand < 0.66666) - { - return VELOREDO; - } - else - { - return VELOFAIL; - } - } -/*--------------------------------------------------------------------------*/ - static int SimHalt(pVelSelDriv self) - { - pSimi pDriv; - - assert(self); - pDriv = (pSimi)self->pPrivate; - - pDriv->lTime = 0; - return OKOK; - } -/*--------------------------------------------------------------------------*/ - static int SimStat(pVelSelDriv self, int *iCode, float *fVal) - { - pSimi pDriv; - - assert(self); - pDriv = (pSimi)self->pPrivate; +static int SimFix(pVelSelDriv self, int iError) +{ + float fRand; - *iCode = ROTMOVE; - if(RunComplete(self)) - { - *fVal = pDriv->fPos; - return VSOK; - } - else - { - if(SimRandom() < FAILURE/2) - { - return VSFAIL; - } - else if(SimRandom() < FAILURE) - { - return VSFAIL; - } - *fVal = random()/150678; - return VSACCEL; - } + /* return the three values MOTREDO, MOTFAIL, MOTOK with a third + randomness + */ + assert(self); + fRand = SimRandom(); + + if (iError == 12) { + return VELOREDO; } + + SICSLogWrite("Selector dying randomly", eHWError); + if (fRand < 0.3333) { + return VELOOK; + } else if (fRand < 0.66666) { + return VELOREDO; + } else { + return VELOFAIL; + } +} + +/*--------------------------------------------------------------------------*/ +static int SimHalt(pVelSelDriv self) +{ + pSimi pDriv; + + assert(self); + pDriv = (pSimi) self->pPrivate; + + pDriv->lTime = 0; + return OKOK; +} + +/*--------------------------------------------------------------------------*/ +static int SimStat(pVelSelDriv self, int *iCode, float *fVal) +{ + pSimi pDriv; + + assert(self); + pDriv = (pSimi) self->pPrivate; + + *iCode = ROTMOVE; + if (RunComplete(self)) { + *fVal = pDriv->fPos; + return VSOK; + } else { + if (SimRandom() < FAILURE / 2) { + return VSFAIL; + } else if (SimRandom() < FAILURE) { + return VSFAIL; + } + *fVal = random() / 150678; + return VSACCEL; + } +} + /*-------------------------------------------------------------------------*/ - static int SimText(pVelSelDriv self, char *pText, int iTextLen) - { - strncpy(pText,"Simulated Info on a simulated velocity selector", - iTextLen); - return 1; - } +static int SimText(pVelSelDriv self, char *pText, int iTextLen) +{ + strncpy(pText, "Simulated Info on a simulated velocity selector", + iTextLen); + return 1; +} + /*------------------------------------------------------------------------*/ - static int SimLoss(pVelSelDriv self, float *fLoss) - { - *fLoss = 20.33338; - return 1; - } -/*-------------------------------------------------------------------------*/ - static void SimKill(void *pData) - { - free(pData); - } -/*-------------------------------------------------------------------------*/ - pVelSelDriv VSCreateSim(void) - { - pVelSelDriv pNew = NULL; - - /* business as usual: allocate memory */ - pNew = (pVelSelDriv)malloc(sizeof(VelSelDriv)); - if(!pNew) - { - return NULL; - } - /* zero the world */ - memset(pNew,0,sizeof(VelSelDriv)); - pNew->pPrivate = malloc(sizeof(Simi)); - if(!pNew->pPrivate) - { - free(pNew); - return NULL; - } - - /* initialise function pointers */ - pNew->DeletePrivate = SimKill; - pNew->Halt = SimHalt; - pNew->GetError = SimError; - pNew->TryAndFixIt = SimFix; - pNew->GetRotation = GetSimPos; - pNew->SetRotation = SimRun; - pNew->GetStatus = SimStat; - pNew->GetDriverText = SimText; - pNew->GetLossCurrent = SimLoss; - pNew->Init = SimInit; - - /* done it */ - return pNew; - } -/*--------------------------------------------------------------------------*/ - void VSDeleteDriver(pVelSelDriv self) - { - assert(self); - - /* try to delete the private parts */ - if(self->DeletePrivate) - { - self->DeletePrivate(self->pPrivate); - } - - /* now we cleans ourselves */ - free(self); - } +static int SimLoss(pVelSelDriv self, float *fLoss) +{ + *fLoss = 20.33338; + return 1; +} +/*-------------------------------------------------------------------------*/ +static void SimKill(void *pData) +{ + free(pData); +} + +/*-------------------------------------------------------------------------*/ +pVelSelDriv VSCreateSim(void) +{ + pVelSelDriv pNew = NULL; + + /* business as usual: allocate memory */ + pNew = (pVelSelDriv) malloc(sizeof(VelSelDriv)); + if (!pNew) { + return NULL; + } + /* zero the world */ + memset(pNew, 0, sizeof(VelSelDriv)); + pNew->pPrivate = malloc(sizeof(Simi)); + if (!pNew->pPrivate) { + free(pNew); + return NULL; + } + + /* initialise function pointers */ + pNew->DeletePrivate = SimKill; + pNew->Halt = SimHalt; + pNew->GetError = SimError; + pNew->TryAndFixIt = SimFix; + pNew->GetRotation = GetSimPos; + pNew->SetRotation = SimRun; + pNew->GetStatus = SimStat; + pNew->GetDriverText = SimText; + pNew->GetLossCurrent = SimLoss; + pNew->Init = SimInit; + + /* done it */ + return pNew; +} + +/*--------------------------------------------------------------------------*/ +void VSDeleteDriver(pVelSelDriv self) +{ + assert(self); + + /* try to delete the private parts */ + if (self->DeletePrivate) { + self->DeletePrivate(self->pPrivate); + } + + /* now we cleans ourselves */ + free(self); +} diff --git a/wwildcard.c b/wwildcard.c index 93d047ff..436cb1c7 100644 --- a/wwildcard.c +++ b/wwildcard.c @@ -3,48 +3,53 @@ int match(const char *mask, const char *name) { - int calls=0, wild=0, q=0; - const char *m=mask, *n=name, *ma=mask, *na=name; + int calls = 0, wild = 0, q = 0; + const char *m = mask, *n = name, *ma = mask, *na = name; - for(;;) { - if (++calls > MAX_CALLS) return 1; - if (*m == '*') { - while (*m == '*') ++m; - wild = 1; - ma = m; - na = n; - } + for (;;) { + if (++calls > MAX_CALLS) + return 1; + if (*m == '*') { + while (*m == '*') + ++m; + wild = 1; + ma = m; + na = n; + } - if (!*m) { - if (!*n) return 0; + if (!*m) { + if (!*n) + return 0; - for (--m; (m > mask) && (*m == '?'); --m) ; + for (--m; (m > mask) && (*m == '?'); --m); - if ((*m == '*') && (m > mask) && - (m[-1] != '\\')) - return 0; - if (!wild) - return 1; - m = ma; - } else if (!*n) { - while(*m == '*') ++m; - return (*m != 0); - } - if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?'))) { - ++m; - q = 1; - } else { - q = 0; - } + if ((*m == '*') && (m > mask) && (m[-1] != '\\')) + return 0; + if (!wild) + return 1; + m = ma; + } else if (!*n) { + while (*m == '*') + ++m; + return (*m != 0); + } + if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?'))) { + ++m; + q = 1; + } else { + q = 0; + } - if ((tolower(*m) != tolower(*n)) && ((*m != '?') || q)) { - if (!wild) return 1; - m = ma; - n = ++na; - } else { - if (*m) ++m; - if (*n) ++n; - } - } + if ((tolower(*m) != tolower(*n)) && ((*m != '?') || q)) { + if (!wild) + return 1; + m = ma; + n = ++na; + } else { + if (*m) + ++m; + if (*n) + ++n; + } + } } - diff --git a/xytable.c b/xytable.c index d577a244..8c5ddfe5 100644 --- a/xytable.c +++ b/xytable.c @@ -16,298 +16,264 @@ #include "xytable.h" /*-------------------------------------------------------------------------*/ - static void KillXY(void *pData) - { - pXYTable self = NULL; +static void KillXY(void *pData) +{ + pXYTable self = NULL; - self = (pXYTable)pData; - if(!self) - return; + self = (pXYTable) pData; + if (!self) + return; - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - LLDdelete(self->iList); - - free(self); + if (self->pDes) { + DeleteDescriptor(self->pDes); } + LLDdelete(self->iList); + + free(self); +} + /*------------------------------------------------------------------------*/ - int XYFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pXYTable pNew = NULL; - int iRet; - char pBueffel[512]; +int XYFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pXYTable pNew = NULL; + int iRet; + char pBueffel[512]; - /* I want a name as argument */ - if(argc < 2) - { - SCWrite(pCon,"ERROR: need a name for the XYTable",eError); - return 0; - } - - /* mallocate memory */ - pNew = (pXYTable)malloc(sizeof(XYTable)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory in function XYFactory", - eError); - return 0; - } - memset(pNew,0,sizeof(XYTable)); - pNew->pDes = CreateDescriptor("XYTable"); - - pNew->iList = LLDcreate(sizeof(TableEntry)); - - if( (pNew->iList < 0) || (pNew->pDes == NULL) ) - { - SCWrite(pCon,"ERROR: out of memory in function XYFactory", - eError); - return 0; - } - - iRet = AddCommand(pSics, - argv[1], - XYAction, - KillXY, - pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; + /* I want a name as argument */ + if (argc < 2) { + SCWrite(pCon, "ERROR: need a name for the XYTable", eError); + return 0; } + + /* mallocate memory */ + pNew = (pXYTable) malloc(sizeof(XYTable)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory in function XYFactory", eError); + return 0; + } + memset(pNew, 0, sizeof(XYTable)); + pNew->pDes = CreateDescriptor("XYTable"); + + pNew->iList = LLDcreate(sizeof(TableEntry)); + + if ((pNew->iList < 0) || (pNew->pDes == NULL)) { + SCWrite(pCon, "ERROR: out of memory in function XYFactory", eError); + return 0; + } + + iRet = AddCommand(pSics, argv[1], XYAction, KillXY, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} + /*-----------------------------------------------------------------------*/ - int XYClear(pXYTable self) - { - assert(self); +int XYClear(pXYTable self) +{ + assert(self); - LLDdelete(self->iList); - self->iList = LLDcreate(sizeof(TableEntry)); - self->iCount = 0; - if(self->iList > 0) - { - return 1; - } - else - { - return 0; - } + LLDdelete(self->iList); + self->iList = LLDcreate(sizeof(TableEntry)); + self->iCount = 0; + if (self->iList > 0) { + return 1; + } else { + return 0; } +} + /*----------------------------------------------------------------------*/ - int XYAdd(pXYTable self, float x, float y) - { - TableEntry te; +int XYAdd(pXYTable self, float x, float y) +{ + TableEntry te; - assert(self); + assert(self); - te.x = x; - te.y = y; - LLDnodeAppendFrom(self->iList,&te); - self->iCount++; - return 1; - } - extern void SNXFormatTime(char *pBueffel, int ilen); + te.x = x; + te.y = y; + LLDnodeAppendFrom(self->iList, &te); + self->iCount++; + return 1; +} +extern void SNXFormatTime(char *pBueffel, int ilen); /*----------------------------------------------------------------------*/ - int XYWrite(pXYTable self, FILE *fd) - { - char pBueffel[132]; - TableEntry pData; - int iRet; - - assert(self); - assert(fd); +int XYWrite(pXYTable self, FILE * fd) +{ + char pBueffel[132]; + TableEntry pData; + int iRet; - SNXFormatTime(pBueffel,131); - fprintf(fd,"XYTable written at: %s\n",pBueffel); - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&pData); - fprintf(fd," %12.4f %12.4f\n",pData.x, pData.y); - iRet = LLDnodePtr2Next(self->iList); - } - return 1; + assert(self); + assert(fd); + + SNXFormatTime(pBueffel, 131); + fprintf(fd, "XYTable written at: %s\n", pBueffel); + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &pData); + fprintf(fd, " %12.4f %12.4f\n", pData.x, pData.y); + iRet = LLDnodePtr2Next(self->iList); } + return 1; +} + /*----------------------------------------------------------------------*/ - int XYList(pXYTable self, SConnection *pCon) - { - char pBueffel[132]; - char *pBuffer = NULL; - TableEntry pData; - int iRet; - - assert(self); - assert(pCon); +int XYList(pXYTable self, SConnection * pCon) +{ + char pBueffel[132]; + char *pBuffer = NULL; + TableEntry pData; + int iRet; - if(self->iCount < 1) - { - SCWrite(pCon,"WARNING: nothing to list",eWarning); - return 1; - } + assert(self); + assert(pCon); - /* malloc space */ - pBuffer = (char *)malloc((self->iCount*30)*sizeof(char)); - if(!pBuffer) - { - SCWrite(pCon,"ERROR: out of memory in XYlist",eError); - return 0; - } - memset(pBuffer,0,(self->iCount*30)*sizeof(char)); - - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&pData); - sprintf(pBueffel," %12.4f %12.4f\n",pData.x, pData.y); - strcat(pBuffer,pBueffel); - iRet = LLDnodePtr2Next(self->iList); - } - SCWrite(pCon,pBuffer,eValue); - free(pBuffer); - return 1; + if (self->iCount < 1) { + SCWrite(pCon, "WARNING: nothing to list", eWarning); + return 1; } + + /* malloc space */ + pBuffer = (char *) malloc((self->iCount * 30) * sizeof(char)); + if (!pBuffer) { + SCWrite(pCon, "ERROR: out of memory in XYlist", eError); + return 0; + } + memset(pBuffer, 0, (self->iCount * 30) * sizeof(char)); + + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &pData); + sprintf(pBueffel, " %12.4f %12.4f\n", pData.x, pData.y); + strcat(pBuffer, pBueffel); + iRet = LLDnodePtr2Next(self->iList); + } + SCWrite(pCon, pBuffer, eValue); + free(pBuffer); + return 1; +} + /*----------------------------------------------------------------------*/ - int XYSendUU(pXYTable self, SConnection *pCon) - { - int *iData = NULL; - int iRet, i, i2; - TableEntry pData; +int XYSendUU(pXYTable self, SConnection * pCon) +{ + int *iData = NULL; + int iRet, i, i2; + TableEntry pData; - assert(self); - iData = (int *)malloc((self->iCount*2+1)*sizeof(int)); - if(!iData) - { - SCWrite(pCon,"ERROR: out of memory in XYSendUU",eError); - return 0; - } - iData[0] = htonl(self->iCount); - i = 1; - i2 = self->iCount + 1; - iRet = LLDnodePtr2First(self->iList); - while(iRet != 0) - { - LLDnodeDataTo(self->iList,&pData); - iData[i] = htonl((int)(pData.x*65536)); - iData[i2] = htonl((int)(pData.y*65536)); - i++; - i2++; - iRet = LLDnodePtr2Next(self->iList); - } - SCWriteUUencoded(pCon,"XYTable",iData, - (self->iCount*2 + 1)*sizeof(int)); - free(iData); - return 1; + assert(self); + iData = (int *) malloc((self->iCount * 2 + 1) * sizeof(int)); + if (!iData) { + SCWrite(pCon, "ERROR: out of memory in XYSendUU", eError); + return 0; } + iData[0] = htonl(self->iCount); + i = 1; + i2 = self->iCount + 1; + iRet = LLDnodePtr2First(self->iList); + while (iRet != 0) { + LLDnodeDataTo(self->iList, &pData); + iData[i] = htonl((int) (pData.x * 65536)); + iData[i2] = htonl((int) (pData.y * 65536)); + i++; + i2++; + iRet = LLDnodePtr2Next(self->iList); + } + SCWriteUUencoded(pCon, "XYTable", iData, + (self->iCount * 2 + 1) * sizeof(int)); + free(iData); + return 1; +} + /*-----------------------------------------------------------------------*/ - int XYAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pXYTable self = NULL; - char pBueffel[512]; - float fX, fY; - double dVal; - FILE *fd = NULL; - int iRet; +int XYAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pXYTable self = NULL; + char pBueffel[512]; + float fX, fY; + double dVal; + FILE *fd = NULL; + int iRet; - self = (pXYTable)pData; - assert(self); - assert(pCon); - assert(pSics); + self = (pXYTable) pData; + assert(self); + assert(pCon); + assert(pSics); - if(argc < 2) - { - sprintf(pBueffel,"ERROR: need command word for %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - strtolower(argv[1]); - if(strcmp(argv[1],"clear") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - XYClear(self); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"add") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(argc < 4) - { - sprintf(pBueffel,"ERROR: insufficient no of args to %s add",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl, argv[2],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to conert %s to number",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fX = (float)dVal; - iRet = Tcl_GetDouble(pSics->pTcl, argv[3],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to conert %s to number",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fY = (float)dVal; - XYAdd(self,fX,fY); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"write") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(argc < 3) - { - sprintf(pBueffel,"ERROR: insufficient no of args to %s write", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - fd = fopen(argv[2],"w"); - if(fd == NULL) - { - sprintf(pBueffel,"ERROR: failed to open %s for writing", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - XYWrite(self,fd); - fclose(fd); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"uuget") == 0) - { - XYSendUU(self,pCon); - return 1; - } - else if(strcmp(argv[1],"list") == 0) - { - XYList(self,pCon); - return 1; - } - sprintf(pBueffel,"ERROR: subcommand %s to %s unknonw", - argv[1], argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; + if (argc < 2) { + sprintf(pBueffel, "ERROR: need command word for %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; } + strtolower(argv[1]); + if (strcmp(argv[1], "clear") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + XYClear(self); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "add") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (argc < 4) { + sprintf(pBueffel, "ERROR: insufficient no of args to %s add", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to conert %s to number", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fX = (float) dVal; + iRet = Tcl_GetDouble(pSics->pTcl, argv[3], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to conert %s to number", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fY = (float) dVal; + XYAdd(self, fX, fY); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "write") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (argc < 3) { + sprintf(pBueffel, "ERROR: insufficient no of args to %s write", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + fd = fopen(argv[2], "w"); + if (fd == NULL) { + sprintf(pBueffel, "ERROR: failed to open %s for writing", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + XYWrite(self, fd); + fclose(fd); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "uuget") == 0) { + XYSendUU(self, pCon); + return 1; + } else if (strcmp(argv[1], "list") == 0) { + XYList(self, pCon); + return 1; + } + sprintf(pBueffel, "ERROR: subcommand %s to %s unknonw", + argv[1], argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; +} diff --git a/xytable.h b/xytable.h index ad19075d..1e4fcf39 100644 --- a/xytable.h +++ b/xytable.h @@ -11,17 +11,17 @@ #ifndef XYTABLE #define XYTABLE - typedef struct __XYTABLE *pXYTable; +typedef struct __XYTABLE *pXYTable; /*------------------------------------------------------------------------*/ - int XYClear(pXYTable self); - int XYAdd(pXYTable self, float x, float y); - int XYWrite(pXYTable self, FILE *fd); - int XYSendUU(pXYTable self, SConnection *pCon); - int XYList(pXYTable self, SConnection *pCon); +int XYClear(pXYTable self); +int XYAdd(pXYTable self, float x, float y); +int XYWrite(pXYTable self, FILE * fd); +int XYSendUU(pXYTable self, SConnection * pCon); +int XYList(pXYTable self, SConnection * pCon); /*----------------------- interpreter interface --------------------------*/ - int XYFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int XYAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int XYFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int XYAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif