Merge branch 'master' into multicounter

This commit is contained in:
2015-08-04 10:35:05 +02:00
11 changed files with 2887 additions and 12 deletions

View File

@ -266,8 +266,7 @@ int AsconReadChar(int fd, char *chr)
if (ret <= 0) if (ret <= 0)
return ret; return ret;
ret = recv(fd, chr, 1, 0); ret = recv(fd, chr, 1, 0);
/* PrintChar(*chr); */ /* PrintChar(*chr); fflush(stdout); */
fflush(stdout);
if (ret > 0) if (ret > 0)
return 1; return 1;
if (ret == 0) { if (ret == 0) {

View File

@ -53,18 +53,19 @@
* modbus-crc: CRC-16-IBM, order: lo,hi * modbus-crc: CRC-16-IBM, order: lo,hi
* keller-crc: CRC-16-IBM, order: hi,lo * keller-crc: CRC-16-IBM, order: hi,lo
* sycon-crc: sort of mod 256 checksum, byte stuffing included (no float allowed) * sycon-crc: sort of mod 256 checksum, byte stuffing included (no float allowed)
* chksum-crc: simple 8bit checksum
*/ */
typedef enum {intType, hexType, floatType, typedef enum {intType, hexType, floatType,
skipType, codeType, crcType, dumpType, errorType} BinDataType; skipType, codeType, crcType, dumpType, errorType} BinDataType;
// dumpType, errorType must be the last items // dumpType, errorType must be the last items
typedef enum {modbusCrc, kellerCrc, rsportCrc, syconCrc} CrcAlgorithm; typedef enum {modbusCrc, kellerCrc, rsportCrc, syconCrc, chksumCrc} CrcAlgorithm;
typedef struct { typedef struct {
CrcAlgorithm crcAlgorithm; CrcAlgorithm crcAlgorithm;
pDynString inp; pDynString inp;
char *nextFmt; char *nextFmt; // position of next format token
pDynString result; pDynString result;
int expectedChars; int expectedChars;
BinDataType type; BinDataType type;
@ -135,6 +136,23 @@ static int calc_crc8(char *inp, int inpLen)
} }
return crc; return crc;
} }
/*----------------------------------------------------------------------------*/
static int calc_chksum(char *inp, int inpLen)
{
/** simple 8bit checksum
*/
unsigned char crc = 0;
unsigned char data;
int n;
while (inpLen--) {
data = *(unsigned char *) inp;
crc += data;
inp++;
}
return crc;
}
/*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/
int BinReadItem(Ascon *a) { int BinReadItem(Ascon *a) {
@ -154,7 +172,11 @@ int BinReadItem(Ascon *a) {
if (strcasecmp(item, "crc") == 0) { if (strcasecmp(item, "crc") == 0) {
p->type = crcType; p->type = crcType;
if (p->crcAlgorithm == chksumCrc) {
p->expectedChars = 1;
} else {
p->expectedChars = 2; p->expectedChars = 2;
}
p->nextFmt += valen; p->nextFmt += valen;
return 1; return 1;
} else if (strncasecmp(item, "int", 3) == 0) { } else if (strncasecmp(item, "int", 3) == 0) {
@ -281,6 +303,10 @@ int BinHandler(Ascon *a) {
DynStringConcatChar(dyn, crc % 256); DynStringConcatChar(dyn, crc % 256);
DynStringConcatChar(dyn, crc / 256); DynStringConcatChar(dyn, crc / 256);
break; break;
case chksumCrc:
crc = calc_chksum(GetCharArray(dyn), l);
DynStringConcatChar(dyn, crc % 256);
break;
case rsportCrc: case rsportCrc:
crc = calc_crc8(GetCharArray(dyn), l); crc = calc_crc8(GetCharArray(dyn), l);
DynStringConcatChar(dyn, crc); DynStringConcatChar(dyn, crc);
@ -509,6 +535,11 @@ int BinHandler(Ascon *a) {
DynStringConcat(p->result, "badCRC "); DynStringConcat(p->result, "badCRC ");
} }
break; break;
case chksumCrc:
if (calc_chksum(str, l-1) != (unsigned char)str[l-1]) {
DynStringConcat(p->result, "badCRC ");
}
break;
case kellerCrc: case kellerCrc:
i = str[l-2]; i = str[l-2];
str[l-2] = str[l-1]; str[l-2] = str[l-1];
@ -560,6 +591,8 @@ static int BinInit(Ascon * a, SConnection * con, int argc, char *argv[])
p->crcAlgorithm = syconCrc; p->crcAlgorithm = syconCrc;
} else if (strcasecmp(argv[2], "rsport-crc") == 0) { } else if (strcasecmp(argv[2], "rsport-crc") == 0) {
p->crcAlgorithm = rsportCrc; p->crcAlgorithm = rsportCrc;
} else if (strcasecmp(argv[2], "chksum-crc") == 0) {
p->crcAlgorithm = chksumCrc;
} else if (strcasecmp(argv[2], "modbus-crc") != 0) { } else if (strcasecmp(argv[2], "modbus-crc") != 0) {
SCPrintf(con, eError, "ERROR: unknown crc-algorithm %s", argv[2]); SCPrintf(con, eError, "ERROR: unknown crc-algorithm %s", argv[2]);
a->private = NULL; a->private = NULL;

View File

@ -393,7 +393,7 @@ static int FourMessStoreIntern(pSICSOBJ self, SConnection * pCon,
double fHkl[3], double fPosition[4], char *extra) double fHkl[3], double fPosition[4], char *extra)
{ {
pFourMess priv = self->pPrivate; pFourMess priv = self->pPrivate;
float fSum, fSigma, fTemp, fStep, fPreset; float fSum, fSigma, fTemp, fMF, fStep, fPreset;
int i, iLF, iRet, iNP, ii; int i, iLF, iRet, iNP, ii;
long *lCounts = NULL; long *lCounts = NULL;
pEVControl pEva = NULL; pEVControl pEva = NULL;
@ -486,6 +486,23 @@ static int FourMessStoreIntern(pSICSOBJ self, SConnection * pCon,
iRet = EVCGetPos(pEva, pCon, &fTemp); iRet = EVCGetPos(pEva, pCon, &fTemp);
} }
/* get mf */
fMF = -777.77;
pEva = (pEVControl) FindCommandData(pServ->pSics, "mf",
"Environment Controller");
if (pEva == NULL) {
pPtr = (pDummy) FindCommandData(pServ->pSics, "mf",
"RemObject");
if (pPtr != NULL) {
pDriv = pPtr->pDescriptor->GetInterface(pPtr, DRIVEID);
if (pDriv != NULL) {
fMF = pDriv->GetValue(pPtr, pCon);
}
}
} else {
iRet = EVCGetPos(pEva, pCon, &fMF);
}
/* write profile */ /* write profile */
if (priv->profFile) { if (priv->profFile) {
/* collect data */ /* collect data */
@ -493,12 +510,16 @@ static int FourMessStoreIntern(pSICSOBJ self, SConnection * pCon,
GetScanVarStep(priv->pScanner, 0, &fStep); GetScanVarStep(priv->pScanner, 0, &fStep);
fPreset = GetScanPreset(priv->pScanner); fPreset = GetScanPreset(priv->pScanner);
prot = getProtonAverage(priv); prot = getProtonAverage(priv);
/*
They rather wanted fMF in place of the proton average which fell victim to the
monitor assignement chaos anyway.
*/
if(extra == NULL){ if(extra == NULL){
fprintf(priv->profFile, "%3d %7.4f %9.0f %7.3f %12f %s\n", iNP, fStep, fprintf(priv->profFile, "%3d %7.4f %9.0f %7.3f %12f %s\n", iNP, fStep,
fPreset, fTemp, prot, pBueffel); fPreset, fTemp, fMF, pBueffel);
} else { } else {
fprintf(priv->profFile, "%3d %7.4f %9.0f %7.3f %12f %s %s\n", iNP, fStep, fprintf(priv->profFile, "%3d %7.4f %9.0f %7.3f %12f %s %s\n", iNP, fStep,
fPreset, fTemp, prot, pBueffel,extra); fPreset, fTemp, fMF, pBueffel,extra);
} }
for (i = 0; i < iNP; i++) { for (i = 0; i < iNP; i++) {
for (ii = 0; ii < 10 && i < iNP; ii++) { for (ii = 0; ii < 10 && i < iNP; ii++) {

View File

@ -1194,7 +1194,7 @@ int GetHdbProperty(pHdb node, char *key, char *value, int len)
/*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
char *GetHdbProp(pHdb node, char *key) char *GetHdbProp(pHdb node, char *key)
{ {
if (node != NULL && node->properties != NULL) { if (node != NULL && isHdbNodeValid(node) && node->properties != NULL) {
return StringDictGetShort(node->properties, key); return StringDictGetShort(node->properties, key);
} else { } else {
return NULL; return NULL;

View File

@ -47,7 +47,7 @@ SOBJ = network.o ifile.o conman.o SCinter.o splitter.o passwd.o \
histmemsec.o sansbc.o sicsutil.o strlutil.o genbinprot.o trace.o\ histmemsec.o sansbc.o sicsutil.o strlutil.o genbinprot.o trace.o\
singlebinb.o taskobj.o sctcomtask.o tasmono.o multicountersec.o \ singlebinb.o taskobj.o sctcomtask.o tasmono.o multicountersec.o \
messagepipe.o sicsget.o remoteobject.o pmacprot.o charbychar.o binprot.o \ messagepipe.o sicsget.o remoteobject.o pmacprot.o charbychar.o binprot.o \
cnvrt.o cnvrt.o tclClock.o tclDate.o tclUnixTime.o
MOTOROBJ = motor.o simdriv.o MOTOROBJ = motor.o simdriv.o
COUNTEROBJ = countdriv.o simcter.o counter.o COUNTEROBJ = countdriv.o simcter.o counter.o

View File

@ -1620,8 +1620,19 @@ static int SctProcessCmd(pSICSOBJ ccmd, SConnection * con,
startTime = time(NULL); startTime = time(NULL);
DevQueue(c->devser, data, WritePRIO, DevQueue(c->devser, data, WritePRIO,
SctWriteHandler, SctTransactMatch, NULL, SctDataInfo); SctWriteHandler, SctTransactMatch, NULL, SctDataInfo);
while (data->busy == 1 && time(NULL) < startTime + 20) {
while (data->busy == 1){
TaskYield(pServ->pTasker); TaskYield(pServ->pTasker);
if(time(NULL) >= startTime + 20) {
/*
if data would still come after such a long timeout, it
might end up in the next action: see comment in devser.c
*/
SCPrintf(con,eError,"ERROR: timeout processing node %s", par[0]->value.v.text);
DevRemoveAction(c->devser,data);
SctKillData(data);
return 0;
}
} }
SctKillData(data); SctKillData(data);

View File

@ -153,6 +153,7 @@ static int InvokeSICSFunc(void *ms, void *userData)
SCsetMacro(pCon,0); SCsetMacro(pCon,0);
if(!status){ if(!status){
self->success = 0; self->success = 0;
SCDeleteConnection(pCon);
return MPSTOP; return MPSTOP;
} }
self->response = strdup(Tcl_GetStringResult(InterpGetTcl(pServ->pSics))); self->response = strdup(Tcl_GetStringResult(InterpGetTcl(pServ->pSics)));

View File

@ -2850,6 +2850,37 @@ static int GetHdbVal(SConnection * pCon, SicsInterp * pSics, void *pData,
return 1; return 1;
} }
/*---------------------------------------------------------------------------*/
static int GetHdbValIgnoreError(
SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[])
{
pHdb targetNode = NULL;
pDynString parData = NULL;
int protocol, outCode;
if (argc != 2) {
SCWrite(pCon, "ERROR: syntax must be: hvali <path>", eError);
return 0;
}
targetNode = FindHdbNode(NULL, argv[1], pCon);
if (targetNode == NULL) {
return 0;
}
parData = formatValue(targetNode->value, targetNode);
if (parData == NULL) {
SCWrite(pCon, "ERROR: out of memory formatting data", eError);
return 0;
}
if ((protocol = isJSON(pCon, 0)) == 1)
outCode = eHdbEvent;
else
outCode = eValue;
SCWrite(pCon, GetCharArray(parData), outCode);
DeleteDynString(parData);
return 1;
}
/*--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/
static int countChildren(pHdb node) static int countChildren(pHdb node)
{ {
@ -4269,6 +4300,7 @@ int InstallSICSHipadaba(SConnection * pCon, SicsInterp * pSics,
AddCommand(pSics, "hupdate", UpdateHdbNode, NULL, NULL); AddCommand(pSics, "hupdate", UpdateHdbNode, NULL, NULL);
AddCommand(pSics, "hget", GetHdbNode, NULL, NULL); AddCommand(pSics, "hget", GetHdbNode, NULL, NULL);
AddCommand(pSics, "hval", GetHdbVal, NULL, NULL); AddCommand(pSics, "hval", GetHdbVal, NULL, NULL);
AddCommand(pSics, "hvali", GetHdbValIgnoreError, NULL, NULL);
AddCommand(pSics, "hzipget", ZipGetHdbNode, NULL, NULL); AddCommand(pSics, "hzipget", ZipGetHdbNode, NULL, NULL);
AddCommand(pSics, "hzipread", ZipReadHdbNode, NULL, NULL); AddCommand(pSics, "hzipread", ZipReadHdbNode, NULL, NULL);
AddCommand(pSics, "hbinread", BinReadHdbNode, NULL, NULL); AddCommand(pSics, "hbinread", BinReadHdbNode, NULL, NULL);
@ -4277,7 +4309,6 @@ int InstallSICSHipadaba(SConnection * pCon, SicsInterp * pSics,
AddCommand(pSics, "hdelcb", RemoveHdbCallback, NULL, NULL); AddCommand(pSics, "hdelcb", RemoveHdbCallback, NULL, NULL);
AddCommand(pSics, "hlink", LinkHdbNode, NULL, NULL); AddCommand(pSics, "hlink", LinkHdbNode, NULL, NULL);
AddCommand(pSics, "hinfo", HdbNodeInfo, NULL, NULL); AddCommand(pSics, "hinfo", HdbNodeInfo, NULL, NULL);
/* AddCommand(pSics, "hval", HdbNodeVal, NULL, NULL);*/
AddCommand(pSics, "hchain", ChainHdbNode, NULL, NULL); AddCommand(pSics, "hchain", ChainHdbNode, NULL, NULL);
AddCommand(pSics, "hcommand", SicsCommandNode, NULL, NULL); AddCommand(pSics, "hcommand", SicsCommandNode, NULL, NULL);
AddCommand(pSics, "harray", HdbArrayNode, NULL, NULL); AddCommand(pSics, "harray", HdbArrayNode, NULL, NULL);

410
tclClock.c Normal file
View File

@ -0,0 +1,410 @@
/*
* tclClock.c --
*
* Contains the time and date related commands. This code
* is derived from the time and date facilities of TclX,
* by Mark Diekhans and Karl Lehenbauer.
*
* Copyright 1991-1995 Karl Lehenbauer and Mark Diekhans.
* Copyright (c) 1995 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
* RCS: @(#) $Id: tclClock.c,v 1.1 2012/03/29 08:45:52 koennecke Exp $
*
* Slightly modified for inclusion into SICS, Mark Koennecke, February 2012
*/
#include <tcl.h>
#include <tcl-private/generic/tclInt.h>
#include <tcl-private/generic/tclPort.h>
typedef long TIMEZONE_t;
/*
* from tclDate.c
*/
int TclGetDate(char *p, Tcl_WideInt now, long zone, Tcl_WideInt *timePtr);
/*
* from tclUnixDate.c
*/
size_t TclpStrftime(char *s, size_t maxsize, CONST char *format, CONST struct tm *t, int useGMT);
struct tm * TclppGetDate(time_t time, int useGMT);
/*
* The date parsing stuff uses lexx and has tons o statics.
*/
TCL_DECLARE_MUTEX(clockMutex)
/*
* Function prototypes for local procedures in this file:
*/
static int FormatClock _ANSI_ARGS_((Tcl_Interp *interp,
Tcl_WideInt clockVal, int useGMT,
char *format));
/*
*-------------------------------------------------------------------------
*
* Tcl_ClockObjCmd --
*
* This procedure is invoked to process the "clock" Tcl command.
* See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*-------------------------------------------------------------------------
*/
int
Tcl_ClockObjCmd (client, interp, objc, objv)
ClientData client; /* Not used. */
Tcl_Interp *interp; /* Current interpreter. */
int objc; /* Number of arguments. */
Tcl_Obj *CONST objv[]; /* Argument values. */
{
Tcl_Obj *resultPtr;
int index;
Tcl_Obj *CONST *objPtr;
int useGMT = 0;
char *format = "%a %b %d %X %Z %Y";
int dummy;
Tcl_WideInt baseClock, clockVal;
long zone;
Tcl_Obj *baseObjPtr = NULL;
char *scanStr;
int n;
static CONST char *switches[] =
{"clicks", "format", "scan", "seconds", (char *) NULL};
enum command { COMMAND_CLICKS, COMMAND_FORMAT, COMMAND_SCAN,
COMMAND_SECONDS
};
static CONST char *formatSwitches[] = {"-format", "-gmt", (char *) NULL};
static CONST char *scanSwitches[] = {"-base", "-gmt", (char *) NULL};
resultPtr = Tcl_GetObjResult(interp);
if (objc < 2) {
Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
return TCL_ERROR;
}
if (Tcl_GetIndexFromObj(interp, objv[1], switches, "option", 0, &index)
!= TCL_OK) {
return TCL_ERROR;
}
switch ((enum command) index) {
case COMMAND_CLICKS: { /* clicks */
int forceMilli = 0;
if (objc == 3) {
format = Tcl_GetStringFromObj(objv[2], &n);
if ( ( n >= 2 )
&& ( strncmp( format, "-milliseconds",
(unsigned int) n) == 0 ) ) {
forceMilli = 1;
} else {
Tcl_AppendStringsToObj(resultPtr,
"bad switch \"", format,
"\": must be -milliseconds", (char *) NULL);
return TCL_ERROR;
}
} else if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, "?-milliseconds?");
return TCL_ERROR;
}
if (forceMilli) {
/*
* We can enforce at least millisecond granularity
*/
Tcl_Time time;
Tcl_GetTime(&time);
Tcl_SetLongObj(resultPtr,
(long) (time.sec*1000 + time.usec/1000));
} else {
Tcl_SetLongObj(resultPtr, (long) TclpGetClicks());
}
return TCL_OK;
}
case COMMAND_FORMAT: /* format */
if ((objc < 3) || (objc > 7)) {
wrongFmtArgs:
Tcl_WrongNumArgs(interp, 2, objv,
"clockval ?-format string? ?-gmt boolean?");
return TCL_ERROR;
}
if (Tcl_GetWideIntFromObj(interp, objv[2], &clockVal)
!= TCL_OK) {
return TCL_ERROR;
}
objPtr = objv+3;
objc -= 3;
while (objc > 1) {
if (Tcl_GetIndexFromObj(interp, objPtr[0], formatSwitches,
"switch", 0, &index) != TCL_OK) {
return TCL_ERROR;
}
switch (index) {
case 0: /* -format */
format = Tcl_GetStringFromObj(objPtr[1], &dummy);
break;
case 1: /* -gmt */
if (Tcl_GetBooleanFromObj(interp, objPtr[1],
&useGMT) != TCL_OK) {
return TCL_ERROR;
}
break;
}
objPtr += 2;
objc -= 2;
}
if (objc != 0) {
goto wrongFmtArgs;
}
return FormatClock(interp, clockVal, useGMT,
format);
case COMMAND_SCAN: /* scan */
if ((objc < 3) || (objc > 7)) {
wrongScanArgs:
Tcl_WrongNumArgs(interp, 2, objv,
"dateString ?-base clockValue? ?-gmt boolean?");
return TCL_ERROR;
}
objPtr = objv+3;
objc -= 3;
while (objc > 1) {
if (Tcl_GetIndexFromObj(interp, objPtr[0], scanSwitches,
"switch", 0, &index) != TCL_OK) {
return TCL_ERROR;
}
switch (index) {
case 0: /* -base */
baseObjPtr = objPtr[1];
break;
case 1: /* -gmt */
if (Tcl_GetBooleanFromObj(interp, objPtr[1],
&useGMT) != TCL_OK) {
return TCL_ERROR;
}
break;
}
objPtr += 2;
objc -= 2;
}
if (objc != 0) {
goto wrongScanArgs;
}
if (baseObjPtr != NULL) {
if (Tcl_GetWideIntFromObj(interp, baseObjPtr,
&baseClock) != TCL_OK) {
return TCL_ERROR;
}
} else {
baseClock = TclpGetSeconds();
}
if (useGMT) {
zone = -50000; /* Force GMT */
} else {
zone = TclpGetTimeZone(baseClock);
}
scanStr = Tcl_GetStringFromObj(objv[2], &dummy);
Tcl_MutexLock(&clockMutex);
if (TclGetDate(scanStr, baseClock, zone,
&clockVal) < 0) {
Tcl_MutexUnlock(&clockMutex);
Tcl_AppendStringsToObj(resultPtr,
"unable to convert date-time string \"",
scanStr, "\"", (char *) NULL);
return TCL_ERROR;
}
Tcl_MutexUnlock(&clockMutex);
Tcl_SetWideIntObj(resultPtr, clockVal);
return TCL_OK;
case COMMAND_SECONDS: /* seconds */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, NULL);
return TCL_ERROR;
}
Tcl_SetLongObj(resultPtr, (long) TclpGetSeconds());
return TCL_OK;
default:
return TCL_ERROR; /* Should never be reached. */
}
}
/*
*-----------------------------------------------------------------------------
*
* FormatClock --
*
* Formats a time value based on seconds into a human readable
* string.
*
* Results:
* Standard Tcl result.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static int
FormatClock(interp, clockVal, useGMT, format)
Tcl_Interp *interp; /* Current interpreter. */
Tcl_WideInt clockVal; /* Time in seconds. */
int useGMT; /* Boolean */
char *format; /* Format string */
{
struct tm *timeDataPtr;
Tcl_DString buffer, uniBuffer;
int bufSize;
char *p;
int result;
time_t tclockVal;
#if !defined(HAVE_TM_ZONE) && !defined(WIN32)
TIMEZONE_t savedTimeZone = 0; /* lint. */
char *savedTZEnv = NULL; /* lint. */
#endif
#ifdef HAVE_TZSET
/*
* Some systems forgot to call tzset in localtime, make sure its done.
*/
static int calledTzset = 0;
Tcl_MutexLock(&clockMutex);
if (!calledTzset) {
tzset();
calledTzset = 1;
}
Tcl_MutexUnlock(&clockMutex);
#endif
/*
* If the user gave us -format "", just return now
*/
if (*format == '\0') {
return TCL_OK;
}
#if !defined(HAVE_TM_ZONE) && !defined(WIN32)
/*
* This is a kludge for systems not having the timezone string in
* struct tm. No matter what was specified, they use the local
* timezone string. Since this kludge requires fiddling with the
* TZ environment variable, it will mess up if done on multiple
* threads at once. Protect it with a the clock mutex.
*/
Tcl_MutexLock( &clockMutex );
if (useGMT) {
CONST char *varValue;
varValue = Tcl_GetVar2(interp, "env", "TZ", TCL_GLOBAL_ONLY);
if (varValue != NULL) {
savedTZEnv = strcpy(ckalloc(strlen(varValue) + 1), varValue);
} else {
savedTZEnv = NULL;
}
Tcl_SetVar2(interp, "env", "TZ", "GMT0", TCL_GLOBAL_ONLY);
savedTimeZone = timezone;
timezone = 0;
tzset();
}
#endif
tclockVal = (time_t) clockVal;
timeDataPtr = TclppGetDate(tclockVal, useGMT);
/*
* Make a guess at the upper limit on the substituted string size
* based on the number of percents in the string.
*/
for (bufSize = 1, p = format; *p != '\0'; p++) {
if (*p == '%') {
bufSize += 40;
if (p[1] == 'c') {
bufSize += 226;
}
} else {
bufSize++;
}
}
Tcl_DStringInit(&uniBuffer);
Tcl_UtfToExternalDString(NULL, format, -1, &uniBuffer);
Tcl_DStringInit(&buffer);
Tcl_DStringSetLength(&buffer, bufSize);
/* If we haven't locked the clock mutex up above, lock it now. */
#if defined(HAVE_TM_ZONE) || defined(WIN32)
Tcl_MutexLock(&clockMutex);
#endif
result = TclpStrftime(buffer.string, (unsigned int) bufSize,
Tcl_DStringValue(&uniBuffer), timeDataPtr, useGMT);
#if defined(HAVE_TM_ZONE) || defined(WIN32)
Tcl_MutexUnlock(&clockMutex);
#endif
Tcl_DStringFree(&uniBuffer);
#if !defined(HAVE_TM_ZONE) && !defined(WIN32)
if (useGMT) {
if (savedTZEnv != NULL) {
Tcl_SetVar2(interp, "env", "TZ", savedTZEnv, TCL_GLOBAL_ONLY);
ckfree(savedTZEnv);
} else {
Tcl_UnsetVar2(interp, "env", "TZ", TCL_GLOBAL_ONLY);
}
timezone = savedTimeZone;
tzset();
}
Tcl_MutexUnlock( &clockMutex );
#endif
if (result == 0) {
/*
* A zero return is the error case (can also mean the strftime
* didn't get enough space to write into). We know it doesn't
* mean that we wrote zero chars because the check for an empty
* format string is above.
*/
Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
"bad format string \"", format, "\"", (char *) NULL);
return TCL_ERROR;
}
/*
* Convert the time to UTF from external encoding [Bug: 3345]
*/
Tcl_DStringInit(&uniBuffer);
Tcl_ExternalToUtfDString(NULL, buffer.string, -1, &uniBuffer);
Tcl_SetStringObj(Tcl_GetObjResult(interp), uniBuffer.string, -1);
Tcl_DStringFree(&uniBuffer);
Tcl_DStringFree(&buffer);
return TCL_OK;
}

1876
tclDate.c Normal file

File diff suppressed because it is too large Load Diff

493
tclUnixTime.c Normal file
View File

@ -0,0 +1,493 @@
/*
* tclUnixTime.c --
*
* Contains Unix specific versions of Tcl functions that
* obtain time values from the operating system.
*
* Copyright (c) 1995 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
* RCS: @(#) $Id: tclUnixTime.c,v 1.1 2012/03/29 08:45:52 koennecke Exp $
*/
#include <tcl-private/generic/tclInt.h>
#include <tcl-private/generic/tclPort.h>
#include <locale.h>
#include <sys/time.h>
#define TM_YEAR_BASE 1900
#define IsLeapYear(x) ((x % 4 == 0) && (x % 100 != 0 || x % 400 == 0))
/*
* TclpGetDate is coded to return a pointer to a 'struct tm'. For
* thread safety, this structure must be in thread-specific data.
* The 'tmKey' variable is the key to this buffer.
*/
static Tcl_ThreadDataKey tmKey;
typedef struct ThreadSpecificData {
struct tm gmtime_buf;
struct tm localtime_buf;
} ThreadSpecificData;
/*
* If we fall back on the thread-unsafe versions of gmtime and localtime,
* use this mutex to try to protect them.
*/
TCL_DECLARE_MUTEX(tmMutex)
static char* lastTZ = NULL; /* Holds the last setting of the
* TZ environment variable, or an
* empty string if the variable was
* not set. */
/* Static functions declared in this file */
static void SetTZIfNecessary _ANSI_ARGS_((void));
static void CleanupMemory _ANSI_ARGS_((ClientData));
/*
*-----------------------------------------------------------------------------
*
* TclpGetSeconds --
*
* This procedure returns the number of seconds from the epoch. On
* most Unix systems the epoch is Midnight Jan 1, 1970 GMT.
*
* Results:
* Number of seconds from the epoch.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
unsigned long
TclpGetSeconds()
{
return time((time_t *) NULL);
}
/*
*-----------------------------------------------------------------------------
*
* TclpGetClicks --
*
* This procedure returns a value that represents the highest resolution
* clock available on the system. There are no garantees on what the
* resolution will be. In Tcl we will call this value a "click". The
* start time is also system dependant.
*
* Results:
* Number of clicks from some start time.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
unsigned long
TclpGetClicks()
{
unsigned long now;
#ifdef NO_GETTOD
struct tms dummy;
#else
struct timeval date;
#endif
#ifdef NO_GETTOD
now = (unsigned long) times(&dummy);
#else
gettimeofday(&date, NULL);
now = date.tv_sec*1000000 + date.tv_usec;
#endif
return now;
}
/*
*----------------------------------------------------------------------
*
* TclpGetTimeZone --
*
* Determines the current timezone. The method varies wildly
* between different platform implementations, so its hidden in
* this function.
*
* Results:
* The return value is the local time zone, measured in
* minutes away from GMT (-ve for east, +ve for west).
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TclpGetTimeZone (currentTime)
unsigned long currentTime;
{
/*
* We prefer first to use the time zone in "struct tm" if the
* structure contains such a member. Following that, we try
* to locate the external 'timezone' variable and use its value.
* If both of those methods fail, we attempt to convert a known
* time to local time and use the difference from UTC as the local
* time zone. In all cases, we need to undo any Daylight Saving Time
* adjustment.
*/
#if defined(HAVE_TM_TZADJ)
# define TCL_GOT_TIMEZONE
/* Struct tm contains tm_tzadj - that value may be used. */
time_t curTime = (time_t) currentTime;
struct tm *timeDataPtr = TclpLocaltime((time_t *) &curTime);
int timeZone;
timeZone = timeDataPtr->tm_tzadj / 60;
if (timeDataPtr->tm_isdst) {
timeZone += 60;
}
return timeZone;
#endif
#if defined(HAVE_TM_GMTOFF) && !defined (TCL_GOT_TIMEZONE)
# define TCL_GOT_TIMEZONE
/* Struct tm contains tm_gmtoff - that value may be used. */
time_t curTime = (time_t) currentTime;
struct tm *timeDataPtr = TclpLocaltime((time_t *) &curTime);
int timeZone;
timeZone = -(timeDataPtr->tm_gmtoff / 60);
if (timeDataPtr->tm_isdst) {
timeZone += 60;
}
return timeZone;
#endif
#if defined(HAVE_TIMEZONE_VAR) && !defined(TCL_GOT_TIMEZONE) && !defined(USE_DELTA_FOR_TZ)
# define TCL_GOT_TIMEZONE
int timeZone;
/* The 'timezone' external var is present and may be used. */
SetTZIfNecessary();
/*
* Note: this is not a typo in "timezone" below! See tzset
* documentation for details.
*/
timeZone = timezone / 60;
return timeZone;
#endif
#if !defined(TCL_GOT_TIMEZONE)
#define TCL_GOT_TIMEZONE 1
/*
* Fallback - determine time zone with a known reference time.
*/
int timeZone;
time_t tt;
struct tm *stm;
tt = 849268800L; /* 1996-11-29 12:00:00 GMT */
stm = TclpLocaltime((time_t *) &tt); /* eg 1996-11-29 6:00:00 CST6CDT */
/* The calculation below assumes a max of +12 or -12 hours from GMT */
timeZone = (12 - stm->tm_hour)*60 + (0 - stm->tm_min);
if ( stm -> tm_isdst ) {
timeZone += 60;
}
return timeZone; /* eg +360 for CST6CDT */
#endif
#ifndef TCL_GOT_TIMEZONE
/*
* Cause compile error, we don't know how to get timezone.
*/
#error autoconf did not figure out how to determine the timezone.
#endif
}
/*
*----------------------------------------------------------------------
*
* Tcl_GetTime --
*
* Gets the current system time in seconds and microseconds
* since the beginning of the epoch: 00:00 UCT, January 1, 1970.
*
* Results:
* Returns the current time in timePtr.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
Tcl_GetTime(timePtr)
Tcl_Time *timePtr; /* Location to store time information. */
{
struct timeval tv;
(void) gettimeofday(&tv, NULL);
timePtr->sec = tv.tv_sec;
timePtr->usec = tv.tv_usec;
}
/*
*----------------------------------------------------------------------
*
* TclpGetDate --
*
* This function converts between seconds and struct tm. If
* useGMT is true, then the returned date will be in Greenwich
* Mean Time (GMT). Otherwise, it will be in the local time zone.
*
* Results:
* Returns a static tm structure.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
struct tm *
TclppGetDate(time, useGMT)
time_t time;
int useGMT;
{
time_t mtime = time;
if (useGMT) {
return TclpGmtime(&mtime);
} else {
return TclpLocaltime(&mtime);
}
}
/*
*----------------------------------------------------------------------
*
* TclpStrftime --
*
* On Unix, we can safely call the native strftime implementation,
* and also ignore the useGMT parameter.
*
* Results:
* The normal strftime result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
size_t
TclpStrftime(s, maxsize, format, t, useGMT)
char *s;
size_t maxsize;
CONST char *format;
CONST struct tm *t;
int useGMT;
{
if (format[0] == '%' && format[1] == 'Q') {
/* Format as a stardate */
sprintf(s, "Stardate %2d%03d.%01d",
(((t->tm_year + TM_YEAR_BASE) + 377) - 2323),
(((t->tm_yday + 1) * 1000) /
(365 + IsLeapYear((t->tm_year + TM_YEAR_BASE)))),
(((t->tm_hour * 60) + t->tm_min)/144));
return(strlen(s));
}
setlocale(LC_TIME, "");
return strftime(s, maxsize, format, t);
}
/*
*----------------------------------------------------------------------
*
* TclpGmtime --
*
* Wrapper around the 'gmtime' library function to make it thread
* safe.
*
* Results:
* Returns a pointer to a 'struct tm' in thread-specific data.
*
* Side effects:
* Invokes gmtime or gmtime_r as appropriate.
*
*----------------------------------------------------------------------
*/
struct tm *
TclpGmtime( tt )
CONST time_t *tt;
{
CONST time_t *timePtr = (CONST time_t *) tt;
/* Pointer to the number of seconds
* since the local system's epoch */
/*
* Get a thread-local buffer to hold the returned time.
*/
ThreadSpecificData *tsdPtr = TCL_TSD_INIT( &tmKey );
#ifdef HAVE_GMTIME_R
gmtime_r(timePtr, &( tsdPtr->gmtime_buf ));
#else
Tcl_MutexLock( &tmMutex );
memcpy( (VOID *) &( tsdPtr->gmtime_buf ),
(VOID *) gmtime( timePtr ),
sizeof( struct tm ) );
Tcl_MutexUnlock( &tmMutex );
#endif
return &( tsdPtr->gmtime_buf );
}
/*
* Forwarder for obsolete item in Stubs
*/
struct tm*
TclpGmtime_unix( timePtr )
CONST time_t *timePtr;
{
return TclpGmtime( timePtr );
}
/*
*----------------------------------------------------------------------
*
* TclpLocaltime --
*
* Wrapper around the 'localtime' library function to make it thread
* safe.
*
* Results:
* Returns a pointer to a 'struct tm' in thread-specific data.
*
* Side effects:
* Invokes localtime or localtime_r as appropriate.
*
*----------------------------------------------------------------------
*/
struct tm *
TclpLocaltime( tt )
CONST time_t *tt;
{
CONST time_t *timePtr = (CONST time_t *) tt;
/* Pointer to the number of seconds
* since the local system's epoch */
/*
* Get a thread-local buffer to hold the returned time.
*/
ThreadSpecificData *tsdPtr = TCL_TSD_INIT( &tmKey );
SetTZIfNecessary();
#ifdef HAVE_LOCALTIME_R
localtime_r( timePtr, &( tsdPtr->localtime_buf ) );
#else
Tcl_MutexLock( &tmMutex );
memcpy( (VOID *) &( tsdPtr -> localtime_buf ),
(VOID *) localtime( timePtr ),
sizeof( struct tm ) );
Tcl_MutexUnlock( &tmMutex );
#endif
return &( tsdPtr->localtime_buf );
}
/*
* Forwarder for obsolete item in Stubs
*/
struct tm*
TclpLocaltime_unix( timePtr )
CONST time_t *timePtr;
{
return TclpLocaltime( timePtr );
}
/*
*----------------------------------------------------------------------
*
* SetTZIfNecessary --
*
* Determines whether a call to 'tzset' is needed prior to the
* next call to 'localtime' or examination of the 'timezone' variable.
*
* Results:
* None.
*
* Side effects:
* If 'tzset' has never been called in the current process, or if
* the value of the environment variable TZ has changed since the
* last call to 'tzset', then 'tzset' is called again.
*
*----------------------------------------------------------------------
*/
static void
SetTZIfNecessary() {
CONST char* newTZ = getenv( "TZ" );
Tcl_MutexLock(&tmMutex);
if ( newTZ == NULL ) {
newTZ = "";
}
if ( lastTZ == NULL || strcmp( lastTZ, newTZ ) ) {
tzset();
if ( lastTZ == NULL ) {
Tcl_CreateExitHandler( CleanupMemory, (ClientData) NULL );
} else {
Tcl_Free( lastTZ );
}
lastTZ = ckalloc( strlen( newTZ ) + 1 );
strcpy( lastTZ, newTZ );
}
Tcl_MutexUnlock(&tmMutex);
}
/*
*----------------------------------------------------------------------
*
* CleanupMemory --
*
* Releases the private copy of the TZ environment variable
* upon exit from Tcl.
*
* Results:
* None.
*
* Side effects:
* Frees allocated memory.
*
*----------------------------------------------------------------------
*/
static void
CleanupMemory( ClientData ignored )
{
ckfree( lastTZ );
}