rasProject_01 / weSweetHome  R. 240
process control       /     RasPi software         by   weinert-automation
Loading...
Searching...
No Matches
sysBasic.h File Reference

Some very basic definitions. More...

#include <basicTyCo.h>
#include <time.h>
#include <stdio.h>
#include <string.h>

Macros

#define ABS_MONOTIME
 /def ABS_MONOTIME More...
 
#define DAY_EQNOX_AUTUMN
 Day of the autumn equinox. More...
 
#define DAY_EQNOX_SPRING
 Day of the spring equinox. More...
 
#define MS100_ns
 Hundred milliseconds in ns.
 
#define MS10_ns
 Ten milliseconds in ns.
 
#define MS1_ns
 One millisecond in ns.
 
#define SETPRGDATA
 Frame for program data definition. More...
 

Typedefs

typedef struct timespec timespec
 The Linux time structure. More...
 

Functions

float cosDay (short int dayInYear)
 Cosine of day in year, function. More...
 
uint8_t errLogIsStd (void)
 Error log (errLog) is standard stream or outLog.
 
int formatDec2Digs (char *targTxt, uint32_t value)
 Format number as two digit decimal number with leading zeroes. More...
 
int formatDec3Digs (char *targTxt, uint32_t value)
 Format number as three digit decimal number with leading zeroes. More...
 
int formatTmTim (char *rTmTxt, struct tm *rTm)
 Format broken down real time and date as standard text. More...
 
int formatTmTiMs (char *rTmTxt, struct tm *rTm, int millis)
 Format broken down real time clock+ms as standard text. More...
 
__time_t getDaySunrise (short int const dayInYear, uint32_t const meanSunriseSec, uint16_t const halfRiseDeltaMin)
 Get sunrise in s from UTC midnight. More...
 
__time_t getDaySunset (short int const dayInYear, uint32_t const meanSunsetSec, uint16_t const halfSetDeltaMin)
 Get sunset in s from UTC midnight. More...
 
uint8_t isFNaN (float const val)
 Floating point NaN. More...
 
uint8_t littleEndian ()
 Actual runtime / architecture is little endian. More...
 
void logEventText (char const *txt)
 Log an event/log message on outLog. More...
 
void monoTimeInit (timespec *timer)
 Absolute timer initialisation. More...
 
uint8_t outLogIsStd (void)
 Event log (outLog) is standard stream.
 
void printNamRevDat (void)
 Print the program name, SVN revision and date. More...
 
void printRevDat (void)
 Print the program SVN revision and date. More...
 
char const * progDat ()
 The program date. More...
 
char const * progNam ()
 The program name. More...
 
char const * progNamB ()
 The program name with blank. More...
 
char const * progRev ()
 The program revision. More...
 
size_t strlcat (char *dest, char const *src, size_t num)
 String concatenation with limit. More...
 
size_t strlcpy (char *dest, char const *src, size_t const num)
 String copy with limit. More...
 
int switchErrorLog (char const *const errFilNam)
 Switch errlog to other file. More...
 
int switchEventLog (char const *const logFilNam)
 Switch outLog to other file. More...
 
void timeAddNs (timespec *t1, long ns)
 Add a ns increment to a time overwriting it. More...
 
int timeStep (timespec *timeSp, unsigned int micros)
 A delay to an absolute step specified in number of ‹¨«s to a given time. More...
 
void updateReaLocalTime (void)
 Update local real time. More...
 

Variables

timespec actRTime
 Actual time (structure, real time clock).
 
struct tm actRTm
 Actual time (broken down structure / local). More...
 
float const cosDiY [192]
 Cosine of day in year, look up. More...
 
short int const cosDiY60 [192]
 Cosine of day in year * 60. More...
 
char const dec2digs [128][2]
 Format two digit decimal, leading zero, by lookup. More...
 
char const dec3digs [1024][4]
 Format three digit decimal, leading zero, 0-terminated, by lookup. More...
 
char const dow [9][4]
 English weekdays, two letter abbreviation. More...
 
FILE * errLog
 Error log output. More...
 
char const fType [16][8]
 Translation of directory entry typed to 8 char text. More...
 
char const *const lckPiGpioPth
 Common path to a lock file for GpIO use. More...
 
__time_t localMidnight
 Actual local midnight. More...
 
uint32_t noLgdEvnt
 Number of events logged. More...
 
FILE * outLog
 Event log output. More...
 
char const prgNamPure []
 The pure program name. More...
 
char const prgSVNdat []
 The complete SVN date string. More...
 
char const prgSVNrev []
 The complete SVN revision string. More...
 
int retCode
 Basic start-up function failure. More...
 
int todayInYear
 Today's day in year. More...
 
int useErrLogFiles
 Log on files. More...
 
uint8_t useOutLog4errLog
 Use outLog for errors too. More...
 
__time_t utcMidnight
 Actual (local) UTC midnight. More...
 
char const zif2charMod10 [44]
 The digits 0..9 repeated as 44 characters. More...
 

Detailed Description

Some very basic definitions.

Copyright (c) 2020 Albrecht Weinert
weinert-automation.de a-weinert.de
/ / /\
/ /___ / \ |
\ /____\ /____\ | _|__
\ /\ / \ / \| |
\/ \/ \__/ \__/|_

Revision history

Rev. 263 19.09.2024
Rev. 66+ 16.11.2017 : new, excerpted from weUtil.h V.66
weModbus.h V.66 (and others)
Rev. 147 16.06.2018 : time handling enhanced improved, Hippogreiff relay
Rev. 152 21.06.2018 : some definitions put to basicTyCo.h
Rev. 164 11.07.2018 : sunset/sunrise location parameters; string functions
Rev. 190 14.02.2019 : minor, comments only
Rev. 209 22.07.2019 : work around a Doxygen bug
Rev. 229 23.07.2020 : UTF 8 BOM for log and error file

This file contains some definitions concerning system values and platform properties, made and probed with Raspberry Pis.

Macro Definition Documentation

◆ SETPRGDATA

#define SETPRGDATA

Frame for program data definition.

To prevent Doxygen to duplicate the documentation of extern variables, like prgNamPure, prgSVNrev, prgSVNdat etc., in the program's source frame those definition in #if SETPRGDATA ... #endif.

◆ ABS_MONOTIME

#define ABS_MONOTIME

/def ABS_MONOTIME

Clock used for absolutely monotonic delays, cycles and intervals.

This clock must never jump and just run on in a monotonic way. We accept it
A) having no relation to any calendar date and time and
B) getting no corrections by NTP clients, DCF77 receivers or what else, as well as
C) this clock being slightly inaccurate and (cf. B)) never be tuned or corrected.

Short note on A): In most literature it is said the monotonic clocks would start at boot. Even if this is observed, it is not mandatory. Assume an arbitrary zero-point.

The inaccuracy C) is explained by some implementations deriving monotonic clocks with no further ado from an μC's quartz oscillator, usually the same oscillator used for communication links timing. On Raspberry Pi 3s with Raspian Jessie (early 2017) we observed +5s in an 24h interval (i.e. being a bit late) growing linear. This stable deviation is in the range of mid prized quartz watches.

Until August 2017, we had adapted to C) by allowing a millisecond used for chained steps or as base for delays not having 1000000ns of this (ABS_MONOTIME) clock, allowing up to +-110ns difference. The value (vcoCorrNs) was then preset at compile by a device specific macro. Its default value -40 was good for a couple of Raspberry Pi 3s. An automatic correction of this adjusted millisecond by standard time sources (with simplified VCO PLL algorithm) was used.

Update on C) since August 2017:
In the latest Jessies (8) CLOCK_MONOTONIC is frequency adjusted to NTP. Hence B) and C) above are obsolete and vcoCorrNs will be initialised as 0. Nevertheless, this corrective +/-100 ns value vcoCorrNs is kept for catching up or slowing down the derived second tick to CLOCK_REALTIME after the latter's jumps due to corrections. As the derived (monotonic) second's tick is started synchronised with the CLOCK_REALTIME one's, this would hardly happen. On a leap second 1000s slow down (the current "solution) on a leap second, we would 1000s slow down and afterwards catch up, without getting an extra "monotonic" second.

Candidates (Raspbian lite) for an absolute monotonic clock are:
CLOCK_MONOTONIC (should always be available and OK, default)
CLOCK_MONOTONIC_RAW (same without NTP tuning)

value: CLOCK_MONOTONIC (NTP tuning now assumed)

◆ DAY_EQNOX_SPRING

#define DAY_EQNOX_SPRING

Day of the spring equinox.

This is the day in year number (79) of the spring equinox (March 20th). From thence the time between sunrise and sunset is more than 12 hours.

See also
todayInYear
DAY_EQNOX_AUTUMN

◆ DAY_EQNOX_AUTUMN

#define DAY_EQNOX_AUTUMN

Day of the autumn equinox.

This is the day in year number (265) of the autumn equinox (Sept. 22nd). From thence the time between sunrise and sunset is less than 12 hours. This value and DAY_EQNOX_SPRING is used for battery handling (defaults).

Typedef Documentation

◆ timespec

typedef struct timespec timespec

The Linux time structure.

This is the timespec structure consisting of two (type obfuscated) long variables: tv_sec and tv_nsec.
Note: This is to allow using timespec without prepending struct, only.

Function Documentation

◆ progNam()

char const * progNam ( )

The program name.

Returns
the program's name as pure text, "homeDoorPhone", e.g.

◆ progNamB()

char const * progNamB ( )

The program name with blank.

Same as progNam but with at least one trailing blank or so many blanks to get a minimal length of 17, , "homeDoorPhone ", e.g.

Returns
the program's name with trailing blank(s)

◆ progRev()

char const * progRev ( )

The program revision.

Returns
the program's SVN revision as pure text, "0", "341" e.g.

◆ progDat()

char const * progDat ( )

The program date.

Returns
the program's SVN date "2020-07-23" e.g., length 10

◆ printRevDat()

void printRevDat ( void  )

Print the program SVN revision and date.

This function prints a line in the form (4 leading blanks)

Revision 229 (2020-07-23)

to outLog

◆ printNamRevDat()

void printNamRevDat ( void  )

Print the program name, SVN revision and date.

This function prints a line in the form (4 leading blanks)

theLittleProg R. 229 (2020-07-23)

to outLog

◆ littleEndian()

uint8_t littleEndian ( )

Actual runtime / architecture is little endian.

This boolean function is evaluated by char* to int comparison.

To save runtime resources use the marco PLATFlittlE instead, which would fall back to littleEndian() (this function) when no target platform informations on endianness are available.

Returns
true when platform is little endian (evaluated at run time)

◆ isFNaN()

uint8_t isFNaN ( float const  val)

Floating point NaN.

Parameters
valthe floating point value to be checked for IEEE754 NaN
Returns
0xFF (true) when not a number, else 0

◆ switchErrorLog()

int switchErrorLog ( char const *const  errFilNam)

Switch errlog to other file.

Parameters
errFilNamthe name of the file to switch to; NULL or empty: switch (back) to stderr
Returns
96 : file name can't be opened for append, old state kept; 97 : useOutLog4errLog is ON, nothing done 0 : OK

◆ switchEventLog()

int switchEventLog ( char const *const  logFilNam)

Switch outLog to other file.

If useOutLog4errLog is ON the errLog file will point to the same named file on success.

Parameters
logFilNamthe name of the file to switch to; NULL or empty: switch (back) to stdout
Returns
96 : file name can't be opened for append; old state kept.

◆ logEventText()

void logEventText ( char const *  txt)

Log an event/log message on outLog.

If txt is not null it will be output to outLog and outLog will be flushed. No line feed will be appended; the text is put as is.

Parameters
txttext to be output; n.b not LF appended and not counted as line

◆ strlcpy()

size_t strlcpy ( char *  dest,
char const *  src,
size_t const  num 
)

String copy with limit.

This function copies at most num - 1 characters from src to dst. If not terminated by a 0 from src, dest[num-1] will be set 0. Hence, except for num == 0, dest will be 0-terminated.

The value returned is the length of string src; if this value is not less than num truncation occurred.

Hint: This function resembles the one from bsd/string.h usually not available with standard Linuxes and Raspbians .

Parameters
destthe character array to copy to; must not be shorter than num
srcthe string to copy from
numthe maximum allowed string length of dest
Returns
the length of src

◆ strlcat()

size_t strlcat ( char *  dest,
char const *  src,
size_t  num 
)

String concatenation with limit.

This function appends at most num - 1 characters from src to the end of dest. If not terminated by a 0 from src, dest[num-1] will be set 0. Hence, except for num == 0, dest will be 0-terminated.

The value returned is the length of string src (if no truncation occurred).

Hint: This function resembles the one from bsd/string.h usually not available with standard Linuxes and Raspbians .

Parameters
destthe character array to copy to; must not be shorter than num
srcthe string to copy from
numthe maximum allowed string length of dest
Returns
the length of src

◆ monoTimeInit()

void monoTimeInit ( timespec timer)

Absolute timer initialisation.

This function sets the time structure provided to the current absolute monotonic ABS_MONOTIME (default: CLOCK_MONOTONIC).

Note: Error returns, suppressed here, cannot occur, as long as the time library functions and used clock IDs are implemented. Otherwise all else timing done here would fail completely.

Parameters
timerthe time structure to be used (never NULL!)

◆ timeStep()

int timeStep ( timespec timeSp,
unsigned int  micros 
)

A delay to an absolute step specified in number of ‹¨«s to a given time.

This function does an absolute monotonic real time delay until timer += micros;

Chaining this calls can give absolute triggers relative to a given start. One must initialise the time structure timespec before every start of a new cycle chain. Afterwards the structure time must not be written to. See timeAddNs, ABS_MONOTIME and monoTimeInit (or clock_gettime).

Chaining absolute delays accomplishes long term exact periods respectively cycles. See also explanations in ABS_MONOTIME (default: CLOCK_MONOTONIC).

Parameters
timeSpthe time structure to be used (never NULL!)
microsdelay in ‹¨«s (recommended 100‹¨«s .. 1h)
Returns
sleep's return value if of interest (0: uninterrupted)

◆ timeAddNs()

void timeAddNs ( timespec t1,
long  ns 
)

Add a ns increment to a time overwriting it.

Parameters
t1the time structure to add to (not NULL!, will be modified)
nsthe increment in nanoseconds

◆ updateReaLocalTime()

void updateReaLocalTime ( void  )

Update local real time.

This function initialises / updates both actRTime and actRTm.

◆ cosDay()

float cosDay ( short int  dayInYear)

Cosine of day in year, function.

This function provides the cosine by the day of the year very efficiently by using a lookup table (cosDiY) and cosine's periodic properties.

For the main purpose of approximate sunrise or sunset time determination the usual (approximate) algorithm relates to shortest day (23.12.). In this case add 8 to the real day in the year.

Parameters
dayInYearthe day in the year; 0: 1.1. (respectively 23.12.)

◆ getDaySunrise()

__time_t getDaySunrise ( short int const  dayInYear,
uint32_t const  meanSunriseSec,
uint16_t const  halfRiseDeltaMin 
)

Get sunrise in s from UTC midnight.

The value will be approximately (but very fast) calculated on base of the the location's (and optimally year's) sunrise data.
Caveat: Consider the units and bases of the parameters.

Parameters
dayInYearday in the year
meanSunriseSeclocation's mean sunrise time in s from midnight UTC
halfRiseDeltaMinthe location's half sunrise time swing in minutes
Returns
that days's sunrise in seconds from UTC midnight

◆ getDaySunset()

__time_t getDaySunset ( short int const  dayInYear,
uint32_t const  meanSunsetSec,
uint16_t const  halfSetDeltaMin 
)

Get sunset in s from UTC midnight.

The value will be approximately (but very fast) calculated on base of the the location's (and optimally year's) sunset data.
Caveat: Consider the units and bases of the parameters.

Parameters
dayInYearday in the year (0 is January 1st)
meanSunsetSeclocation's mean sunset time in s from midnight UTC
halfSetDeltaMinthe location's half sunset time swing in minutes
Returns
that days's sunset in seconds from UTC midnight

◆ formatDec2Digs()

int formatDec2Digs ( char *  targTxt,
uint32_t  value 
)

Format number as two digit decimal number with leading zeroes.

The format is: 00 to 99

The length is always 2. There is no trailing character zero appended.
returned is the number of leading zeroes in the range 0 o 1. N.B. the value 0 yielding "00" is considered to have one leading zero.

See also
dec2digs formatDec3Digs
Parameters
targTxtpointer to the target text buffer, must have place for 3 characters (!)
valuethe value to be formatted; values outside 0 .. 999 will yield incorrect results
Returns
the number of leading zeroes (0 or 1)

◆ formatDec3Digs()

int formatDec3Digs ( char *  targTxt,
uint32_t  value 
)

Format number as three digit decimal number with leading zeroes.

The format is: 000 to 999

The length is always 3. There is no trailing character zero appended.
returned is the number of leading zeroes in the range 0 to 2. N.B. the value 0 yielding "000" is considered to have 2 leading zeroes.

See also
dec3digs formatDec2Digs
Parameters
targTxtpointer to the target text buffer, must have place for 3 characters (!)
valuethe value to be formatted; values outside 0 .. 999 will yield incorrect results
Returns
the number of leading zeroes (0..2)

◆ formatTmTim()

int formatTmTim ( char *  rTmTxt,
struct tm *  rTm 
)

Format broken down real time and date as standard text.

The format is: Fr 2017-10-20 13:55:12 UTC+20 ................0123456789x123456789v123456789t The length is 29. See formatTmTiMs() for a longer format with 3 digit ms.

Parameters
rTmTxtpointer to the target text buffer, must have place for 30 characters (!)
rTmpointer to broken down real time; NULL will take actRTm
Returns
the number of characters put (should be 28) or 0: error (rTmTxT NULL)

◆ formatTmTiMs()

int formatTmTiMs ( char *  rTmTxt,
struct tm *  rTm,
int  millis 
)

Format broken down real time clock+ms as standard text.

/code The format is: Fr 2017-10-20 13:55:12.987 UTC+20 ................0123456789x123456789v123456789t123 +3 ................0123456789x123456789v123456789t /endcode The length is 33. See formatTmTim() for a shorter format without ms.

Parameters
rTmTxtpointer to the target text buffer, must have place for 34 characters (!)
rTmpointer to broken down real time; NULL will take actRTm
millismilliseconds 0..999 supplement to rTm
Returns
the number of characters put (should be 32) or 0: error (rTmTxT NULL)

Variable Documentation

◆ prgNamPure

char const prgNamPure[]
extern

The pure program name.

To be provided in the application's / program's source.

See also
progNam() progNamB()

◆ prgSVNrev

char const prgSVNrev[]
extern

The complete SVN revision string.

To be provided in the application's / program's source.

See also
progRev()

◆ prgSVNdat

char const prgSVNdat[]
extern

The complete SVN date string.

To be provided in the application's / program's source.

See also
progDat()

◆ retCode

int retCode
extern

Basic start-up function failure.

Allows for compact code without saving the (error) return:
if (openLock(lckPiGpioPth, ON)) return retCode;

Storage for return/error codes. Used by: openLock(char const *, uint8_t) theCyclistStart(int) theCyclistWaitEnd()

Value: 0: OK, else: error

◆ lckPiGpioPth

char const* const lckPiGpioPth
extern

Common path to a lock file for GpIO use.

Programs using GPIO in any form usually (and forced by some libraries) have to do this exclusively. This is implemented here by locking a file named /home/pi/bin/.lockPiGpio
Make the lock file by: touch /home/pi/bin/.lockPiGpio

Without locking this file those programs must not start.
So, deleting this file inhibits the start even by cron etc.

◆ useErrLogFiles

int useErrLogFiles
extern

Log on files.

If true (default) logging and errors go to files or one file, otherwise to console

◆ outLog

FILE* outLog
extern

Event log output.

default: standard output; may be put to a file.

◆ noLgdEvnt

uint32_t noLgdEvnt
extern

Number of events logged.

Counter for lines put to or events logged on outLog.

◆ useOutLog4errLog

uint8_t useOutLog4errLog
extern

Use outLog for errors too.

When set true errLog will be set to outLog when using files. In this case there is just one event log file. Hence, doubling the same entry to both errLog and outLog should be avoided.

◆ errLog

FILE* errLog
extern

Error log output.

default: standard error; may be put to a file.

◆ actRTm

struct tm actRTm
extern

Actual time (broken down structure / local).

This structure is initialised may be updated by some timing and cyclic functions. See initStartRTime() and others.

◆ todayInYear

int todayInYear
extern

Today's day in year.

The value should be set at start (will be by updateReaLocalTime()) and updated at midnight.

◆ utcMidnight

__time_t utcMidnight
extern

Actual (local) UTC midnight.

This is the actual "local" UTC midnight. "Local" means that on early hours, i.e. those within zone offset, UTC midnight will be corrected to the next (east of Greenwich) respectively previous day (west). The rationale is to point to the same day or date at day time (around Europe).
Or, to put it simple, utcMidnight is to be set so, that the equation
      local Midnight = utcMidnight - UTCoffset
holds.

The value will will be set correctly by updateReaLocalTime(). It should be updated at day change (if used).

◆ localMidnight

__time_t localMidnight
extern

Actual local midnight.

This is the UTC Linux timestamp of the actual day's / time's local midnight. See also utcMidnight for explanations.

Note: On days with DST changes this value will shift within the day. It's mostly better to make calculations relative to day start — sunrise and sunset e.g. — relative to UTC midnight.

◆ cosDiY

float const cosDiY[192]
extern

Cosine of day in year, look up.

This lookup table provides the cosine by the day of the year without resource eating floating point arithmetic or math.h. The rationale is the approximate calculation of sunrise and sunset times based on earliest, latest and delta for any given location within the arctic circles.

The length of the look up table is abundant 192. According to cosine's periodic properties it shall be used in the range 0..183 by applying the following operations to the day in year value
absolute when < 0,
modulo FOURYEARS when >= FOURYEARS,
modulo 365 when >= 365 and
x = 365 - x when > 190.

Note: These rules are implemented in the function cosDay() and in the function cosDay60() using the look up table cosDiY60

◆ cosDiY60

short int const cosDiY60[192]
extern

Cosine of day in year * 60.

This look up table is the same as cosDiY, except the values being multiplied by 60 which includes minutes to seconds conversion, avoiding a multiplication and all floating point operations for some applications.

lenght: 192

◆ zif2charMod10

char const zif2charMod10[44]
extern

The digits 0..9 repeated as 44 characters.

By using a number 0..43 as index this will give modulo 10 respectively the last decimal digit as character.

◆ dec2digs

char const dec2digs[128][2]
extern

Format two digit decimal, leading zero, by lookup.

"00" .. "99" + "00", "_1" .. "_7"

◆ dec3digs

char const dec3digs[1024][4]
extern

Format three digit decimal, leading zero, 0-terminated, by lookup.

"000" .. "999" + "000" .. "023"

◆ dow

char const dow[9][4]
extern

English weekdays, two letter abbreviation.

Monday (Mo) is 1; Sunday (Su) is 7 or, also, 0.

◆ fType

char const fType[16][8]
extern

Translation of directory entry typed to 8 char text.

direntry.d_type as index in the range 0..15 gives an 8 character short type text. Note: Only 0, 1, 2, 4, 6, 8, 10, 12 and 14 are defined d_type values. The undefined ones give undef3 .. undefF