diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 267ffd2..b913f47 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -52,6 +52,17 @@ jobs: tools/modbus_codec_test.c app/engine/modbus_codec.c app/cJSON.c -lm /tmp/modbus_codec_test + scheduler: + name: Day/Night scheduler tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: Build and run the sunrise/sunset window tests + run: | + cc -std=gnu11 -Wall -Wextra -Werror -fsanitize=address,undefined \ + -o /tmp/scheduler_test tools/scheduler_test.c app/cJSON.c -lm + /tmp/scheduler_test + gps_nmea: name: GPS NMEA parser tests runs-on: ubuntu-latest diff --git a/AI_RULE_GUIDE.md b/AI_RULE_GUIDE.md index 77742c2..869a023 100644 --- a/AI_RULE_GUIDE.md +++ b/AI_RULE_GUIDE.md @@ -563,15 +563,21 @@ Checks the current state of a VAPIX event instance on the local or a remote devi "type": "day_night", "state": "day", "lat": 59.3293, - "lon": 18.0686 + "lon": 18.0686, + "sunrise_offset_minutes": 60, + "sunset_offset_minutes": -30 } ``` | Field | Type | Description | |-------|------|-------------| | `state` | `"day"` \| `"night"` | Required state | -| `lat` | number | Latitude (optional, defaults to engine setting) | +| `lat` | number | Latitude (optional, defaults to engine setting; 0/0 also uses the engine setting) | | `lon` | number | Longitude (optional, defaults to engine setting) | +| `sunrise_offset_minutes` | number | Optional, default 0. Shifts sunrise (positive = later, clamped to ±720). `60` keeps it night until 1 h after sunrise | +| `sunset_offset_minutes` | number | Optional, default 0. Shifts sunset (positive = later, clamped to ±720). `-30` starts night 30 min before sunset | + +Day is from sunrise + offset until sunset + offset, and may run past midnight. If the offsets make that window empty, it is night all day. On days with no sunrise or sunset, midnight sun counts as day and polar night as night, whatever the offsets. ### 8. `aoa_occupancy` — AOA Occupancy Check @@ -1897,7 +1903,7 @@ For a map, put `register`, `var`, `type`, `order`, and optional scaling fields i | `scale` | number | `1` | Numeric values are reported as `raw × scale + offset`; must not be zero | | `offset` | number | `0` | Numeric value offset | | `decimals` | integer (0–10) | automatic | Optional rounding after scaling | -| `length` | integer (1–125) | `8` | String length in registers (single value or map entry); the text ends at the first NUL | +| `length` | integer (1–125) | `8` | String length in 2-byte registers (single value or map entry), not characters; UTF-8 characters may use multiple bytes. The text ends at the first NUL | | `encoding` | `"utf-8"` \| `"ascii"` \| `"iso-8859-1"` \| `"iso-8859-2"` \| `"windows-1250"` \| `"windows-1252"` | `"utf-8"` | String encoding (single value or map entry). Text is stored in variables as UTF-8; invalid bytes read as `?` | | `variable` | string | — | Optional variable updated by a single-value read | | `map` | array | — | Register-map entries; each requires `register` and a unique `var`, and may include `type`, `order`, `scale`, `offset`, `decimals`, `length`, or `encoding`. One request reads up to 125 registers or 2000 bits; a larger map is read in several requests, spanning at most 2000 registers | @@ -1928,7 +1934,7 @@ The trigger data includes `state` (`"failing"` or `"recovered"`), `device`, `sla ## Action: `modbus_write` -Writes one typed value or a block of values to Modbus. Automatic function selection uses FC06/FC05 for one register/coil and FC16/FC15 for multiple contiguous values. In block mode, adjacent values are batched into one request of up to 123 registers or 1968 coils; longer runs and strings longer than 123 registers are split, and gaps start a new request. Strings are padded with NUL to `length`. When tested from the editor (`POST /actions`), the write waits for the device and returns its error, if any. +Writes one typed value or a block of values to Modbus. Automatic function selection uses FC06/FC05 for one register/coil and FC16/FC15 for multiple contiguous values. In block mode, adjacent values are batched into one request of up to 123 registers or 1968 coils; longer runs and strings longer than 123 registers are split, and gaps start a new request. Strings are padded to `length` with NUL, or with spaces as `fill` says. When tested from the editor (`POST /actions`), the write waits for the device and returns its error, if any. ```json { @@ -1980,8 +1986,9 @@ For multiple values, use `values` instead of `register` and `value`. Each entry | `word_order` | `"ABCD"` \| `"CDAB"` \| `"BADC"` \| `"DCBA"` | `"ABCD"` | Byte and word order for 32/64-bit values. For 16-bit values and strings only `"ABCD"` and `"BADC"` (bytes swapped) differ | | `scale` | number | `1` | Input value is converted to raw form using `(value - offset) / scale` | | `offset` | number | `0` | Numeric value offset | -| `length` | integer (1–125) | `8` | String length in registers; shorter text is padded with NUL (0x00) | +| `length` | integer (1–125) | `8` | String length in 2-byte registers, not characters; UTF-8 characters may use multiple bytes. Shorter text is padded as `fill` says | | `encoding` | `"utf-8"` \| `"ascii"` \| `"iso-8859-1"` \| `"iso-8859-2"` \| `"windows-1250"` \| `"windows-1252"` | `"utf-8"` | String encoding. Literal text with characters the encoding lacks is rejected; template text gets `?` instead. The length check counts encoded bytes (in UTF-8, `ż` is 2 bytes) | +| `fill` | `"nul"` \| `"space_left"` \| `"space_right"` \| `"space_center"` | `"nul"` | String padding. `nul` puts the text first and fills with 0x00. The `space_*` values fill with spaces (0x20) and put the text left, right or in the middle (an odd space goes after the text). Counted in bytes of the encoding | | `value` | number \| string | — | Value to write; supports templates. Required for numbers and coils; an empty string clears a text register. A `uint16` also accepts -32768 to -1, written as two's complement. Coils accept `0`, `1`, `true`, `false`, `on`, or `off` | -| `values` | array | — | Block entries with `register`, `value`, and optional `type`, `order`, `scale`, `offset`, `length`, and `encoding`. Overlapping entries are rejected; gaps create separate requests. A request carries at most 123 registers or 1968 coils; longer runs are split, up to 32 requests per action | +| `values` | array | — | Block entries with `register`, `value`, and optional `type`, `order`, `scale`, `offset`, `length`, `encoding`, and `fill`. Overlapping entries are rejected; gaps create separate requests. A request carries at most 123 registers or 1968 coils; longer runs are split, up to 32 requests per action | | `function` | `"auto"` \| `"fc05"` \| `"fc15"` \| `"fc06"` \| `"fc16"` | `"auto"` | Force a compatible single/multiple-coil or register write function | diff --git a/README.md b/README.md index 134fd9f..2313d40 100644 --- a/README.md +++ b/README.md @@ -137,7 +137,7 @@ The web UI is accessible at | Type | Description | |------|-------------| | **Time Window** | Only allow firing between two times of day on specified days. Supports wraparound (e.g. 22:00–06:00) | -| **Day / Night** | Pass only during daytime (after sunrise) or nighttime (after sunset). Uses the sunrise/sunset engine with latitude/longitude from Settings. The UI shows today's computed sunrise and sunset times. Optional per-condition lat/lon override | +| **Day / Night** | Pass only during daytime (after sunrise) or nighttime (after sunset). Uses the sunrise/sunset engine with latitude/longitude from Settings. Optional sunrise/sunset offsets in minutes (e.g. +60 to stay "night" until an hour after sunrise). The UI shows today's resulting times as you type. Optional per-condition lat/lon override | | **I/O State** | Check the current state of an I/O port. Supports **remote device** target | | **Counter Compare** | Compare a counter value against a threshold | | **Variable Compare** | Compare a named variable against a value | @@ -227,7 +227,7 @@ stop a siren when motion ends). | Type | Description | |------|-------------| -| **Modbus Write** | Write typed values or blocks over Modbus TCP or RTU/RS-485. Supports FC05/FC15 coil writes and FC06/FC16 register writes, including adjacent-register batching (split at the 123-register limit), data types, word order, scaling and strings in several encodings | +| **Modbus Write** | Write typed values or blocks over Modbus TCP or RTU/RS-485. Supports FC05/FC15 coil writes and FC06/FC16 register writes, including adjacent-register batching (split at the 123-register limit), data types, word order, scaling and strings in several encodings, padded with NUL or with spaces (text left, right or centered) | ### Industrial diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index fce7cc5..12a9245 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,5 +1,63 @@ # Release Notes +## v1.10.4 - Day/Night offsets and Modbus text padding + +The Day / Night condition can shift sunrise and sunset by a number of minutes, +and now works after midnight and in polar regions. Modbus Write can pad text +with spaces for displays that show 0x00 as a character. The Rules page appears +sooner, and the rule editor no longer loses edits while its lists load. + +### Upgrading to 1.10.4 + +The `signed_*.eap` packages install normally on AXIS OS 12.10 and later, as an +in-place upgrade. Rules, settings and variables are kept. Two changes can make +existing rules behave differently: + +- Day / Night conditions without coordinates (or with 0, 0), such as those + created from the Night-Only Action template, now use the camera's Location + setting instead of 0°N, 0°E. +- During polar night a Night condition now passes, and during midnight sun a + Day condition passes. Before, neither passed. + +### New in 1.10.4 + +- **Day / Night offsets:** shift sunrise and sunset independently, in + minutes (up to ±720). For example, if sunrise is 06:44, a sunrise offset of + `60` keeps the condition at Night until 07:44. The editor shows today's + resulting times as you type coordinates or offsets. +- **Modbus text padding:** a new **Fill** option on Modbus Write chooses what + goes in the bytes the text doesn't use: NUL (0x00, the default and the + previous behavior), or spaces with the text left, right or centered. In the + API it is `fill`: `nul`, `space_left`, `space_right` or `space_center`. +- **Modbus editor:** Encoding is shown only for text values. The Length hint + explains that it counts 2-byte registers, not characters, and that a UTF-8 + character can take several bytes. + +### Fixes in 1.10.4 + +- **Location setting ignored:** Day / Night conditions and Sunrise/Sunset + schedule triggers without their own coordinates read the Location setting + from the wrong place, so they used 0°N, 0°E. +- **Day / Night after midnight:** where local sunset falls after midnight + (for example Reykjavik in June), the condition reported Night all day. It + now stays Day until sunset, also when a sunset offset moves sunset past + midnight. +- **Day / Night preview:** the sunrise and sunset times shown in the editor + didn't change when you edited the coordinates; they only updated after + saving and reopening the rule. They now update as you type. +- **Day / Night in polar regions:** during polar night the condition passed + for neither Day nor Night, so a Night-Only rule never ran. Polar night now + counts as Night, and midnight sun as Day. +- **Slow Rules page:** the rule list waited for every device capability + lookup. It now appears first; editor choices such as device parameters can + still take a few seconds to fill in. +- **Rule editor lost edits:** when a device list finished loading while the + editor was open, unsaved changes were discarded. Adding or removing a + trigger or condition also reset schedule days to Monday to Friday and + cleared geofence polygons, and saving kept the reset values. +- **Rule cards:** Modbus Write and the GPS triggers showed their internal + names instead of labels. + ## v1.10.3 - No pause after saving; MQTT and Sparkplug B fixes Saving a rule or the Sparkplug B settings no longer pauses event handling, a diff --git a/app/engine/actions.c b/app/engine/actions.c index e530dfa..7af2256 100644 --- a/app/engine/actions.c +++ b/app/engine/actions.c @@ -4706,7 +4706,7 @@ static int mb_encode_value(cJSON* v, const mb_field_t* f, int bits, cJSON* trigg else if (mb_parse_number(text, &d) == 0) regs[0] = d != 0; else { snprintf(err, err_size, "'%.40s' is not on/off or a number", text); rc = -1; } } else if (f->type == MB_T_STRING) { - if (mb_encode_string(text, f->nregs, f->order, f->charset, regs, NULL) != 0) { + if (mb_encode_string(text, f->nregs, f->order, f->charset, f->fill, regs, NULL) != 0) { snprintf(err, err_size, "text is %d bytes in %s; %d registers hold %d", (int)mb_text_encode(text, f->charset, NULL, 0, NULL, NULL), mb_charset_name(f->charset), f->nregs, f->nregs * 2); diff --git a/app/engine/conditions.c b/app/engine/conditions.c index fb85bac..df08c59 100644 --- a/app/engine/conditions.c +++ b/app/engine/conditions.c @@ -94,10 +94,21 @@ static int cond_time_window(cJSON* cfg) { /*----------------------------------------------------- * day_night - * config: { "state": "day"|"night", "lat": 51.5, "lon": -0.12 } + * config: { "state": "day"|"night", "lat": 51.5, "lon": -0.12, + * "sunrise_offset_minutes": 60, "sunset_offset_minutes": -30 } * Uses the sunrise/sunset engine from scheduler.c. * If no lat/lon provided, reads from engine settings. + * Offsets are optional (default 0, positive = later, clamped to ±12 h). *-----------------------------------------------------*/ +static int day_night_offset_sec(cJSON* cfg, const char* key) { + cJSON* j = cJSON_GetObjectItem(cfg, key); + if (!j || !cJSON_IsNumber(j)) return 0; + double m = j->valuedouble; + if (m > 720.0) m = 720.0; + if (m < -720.0) m = -720.0; + return (int)(m * 60.0); +} + static int cond_day_night(cJSON* cfg) { const char* want = cJSON_GetStringValue(cJSON_GetObjectItem(cfg, "state")); if (!want) want = "day"; @@ -108,8 +119,10 @@ static int cond_day_night(cJSON* cfg) { if (lat_j) lat = lat_j->valuedouble; if (lon_j) lon = lon_j->valuedouble; - if (!lat_j && !lon_j) { - cJSON* eng = ACAP_Get_Config("engine"); + /* 0/0 means "not set" (older templates saved it), same as astronomical triggers */ + if (lat == 0.0 && lon == 0.0) { + cJSON* sett = ACAP_Get_Config("settings"); + cJSON* eng = sett ? cJSON_GetObjectItem(sett, "engine") : NULL; if (eng) { cJSON* sl = cJSON_GetObjectItem(eng, "latitude"); cJSON* so = cJSON_GetObjectItem(eng, "longitude"); @@ -118,8 +131,9 @@ static int cond_day_night(cJSON* cfg) { } } - int is_day = Scheduler_Is_Daytime(lat, lon); - if (is_day < 0) return 0; /* polar — can't determine */ + int is_day = Scheduler_Is_Daytime(lat, lon, + day_night_offset_sec(cfg, "sunrise_offset_minutes"), + day_night_offset_sec(cfg, "sunset_offset_minutes")); return (strcmp(want, "day") == 0) ? is_day : !is_day; } diff --git a/app/engine/modbus_codec.c b/app/engine/modbus_codec.c index 75ee187..f2d0150 100644 --- a/app/engine/modbus_codec.c +++ b/app/engine/modbus_codec.c @@ -60,6 +60,15 @@ const char* mb_charset_name(mb_charset_t cs) { return (cs >= MB_CS_UTF8 && cs <= MB_CS_CP1252) ? charset_names[cs] : "invalid"; } +static const char* const fill_names[] = { "nul", "space_left", "space_right", "space_center", NULL }; + +mb_fill_t mb_fill_parse(const char* s) { + if (!s || !s[0]) return MB_FILL_NUL; + for (int i = 0; fill_names[i]; i++) + if (strcmp(s, fill_names[i]) == 0) return (mb_fill_t)i; + return MB_FILL_INVALID; +} + /* Unicode code points of bytes 0x80-0xFF; 0 = not defined. 0x80-0x9F of * ISO-8859-2 are C1 controls, which are treated as not printable. */ static const uint16_t cs_latin2[128] = { @@ -341,12 +350,18 @@ int mb_encode_number(double v, mb_type_t t, mb_order_t o, uint16_t* regs) { } int mb_encode_string(const char* s, int nregs, mb_order_t o, mb_charset_t cs, - uint16_t* regs, int* bad) { + mb_fill_t fill, uint16_t* regs, int* bad) { if (nregs < 1 || nregs > MB_MAX_STRING_REGS) return -1; + uint8_t text[2 * MB_MAX_STRING_REGS]; + size_t len = mb_text_encode(s, cs, text, sizeof(text), bad, NULL); + size_t total = (size_t)nregs * 2; + if (len > total) return -1; + size_t pad = total - len, start = 0; + if (fill == MB_FILL_SPACE_RIGHT) start = pad; + else if (fill == MB_FILL_SPACE_CENTER) start = pad / 2; uint8_t bytes[2 * MB_MAX_STRING_REGS]; - memset(bytes, 0, sizeof(bytes)); - size_t len = mb_text_encode(s, cs, bytes, sizeof(bytes), bad, NULL); - if (len > (size_t)nregs * 2) return -1; + memset(bytes, fill == MB_FILL_NUL ? 0x00 : 0x20, total); + memcpy(bytes + start, text, len); int swap = (o == MB_O_BADC || o == MB_O_DCBA); for (int i = 0; i < nregs; i++) { uint8_t hi = bytes[2 * i], lo = bytes[2 * i + 1]; @@ -473,6 +488,12 @@ int mb_field_parse(cJSON* obj, const char* type_key, const char* order_key, "windows-1250 or windows-1252)", cs); return -1; } + const char* fs = cJSON_GetStringValue(cJSON_GetObjectItem(obj, "fill")); + f->fill = mb_fill_parse(fs); + if (f->fill == MB_FILL_INVALID) { + snprintf(err, err_size, "unknown fill '%s' (use nul, space_left, space_right or space_center)", fs); + return -1; + } } f->nregs = mb_type_regs(f->type, f->length); if (f->reg + f->nregs - 1 > 65535) { diff --git a/app/engine/modbus_codec.h b/app/engine/modbus_codec.h index 2314a43..f13efc1 100644 --- a/app/engine/modbus_codec.h +++ b/app/engine/modbus_codec.h @@ -58,11 +58,21 @@ typedef enum { MB_CS_CP1252 /* Windows-1252 */ } mb_charset_t; -/* NULL or "" give the default (uint16, ABCD, utf-8). Encodings are matched +/* How a string write fills the registers the text doesn't use. */ +typedef enum { + MB_FILL_INVALID = -1, + MB_FILL_NUL = 0, /* text first, then 0x00 */ + MB_FILL_SPACE_LEFT, /* text first, then spaces */ + MB_FILL_SPACE_RIGHT, /* spaces, then text */ + MB_FILL_SPACE_CENTER /* text centred in spaces; an odd one goes after */ +} mb_fill_t; + +/* NULL or "" give the default (uint16, ABCD, utf-8, nul). Encodings are matched * without case, and also as utf8, latin1, latin2, cp1250 and cp1252. */ mb_type_t mb_type_parse(const char* s); mb_order_t mb_order_parse(const char* s); mb_charset_t mb_charset_parse(const char* s); +mb_fill_t mb_fill_parse(const char* s); const char* mb_type_name(mb_type_t t); const char* mb_charset_name(mb_charset_t cs); @@ -91,11 +101,11 @@ size_t mb_text_encode(const char* s, mb_charset_t cs, uint8_t* out, size_t out_s * -1 if the value is NaN or out of range for the type. */ int mb_encode_number(double v, mb_type_t t, mb_order_t o, uint16_t* regs); -/* UTF-8 text to nregs registers in cs, padded with NUL to the end. Returns - * -1 if the encoded text is longer than nregs * 2 bytes. *bad as for - * mb_text_encode (may be NULL). */ +/* UTF-8 text to nregs registers in cs; the unused bytes are filled as fill + * says. Returns -1 if the encoded text is longer than nregs * 2 bytes. *bad as + * for mb_text_encode (may be NULL). */ int mb_encode_string(const char* s, int nregs, mb_order_t o, mb_charset_t cs, - uint16_t* regs, int* bad); + mb_fill_t fill, uint16_t* regs, int* bad); /* value = raw * scale + offset, rounded to decimals (< 0: noise of the double * arithmetic only, 15 significant digits). */ @@ -120,6 +130,7 @@ typedef struct { int decimals; /* -1 = not set */ int length; /* string length in registers */ mb_charset_t charset; /* strings */ + mb_fill_t fill; /* string writes */ } mb_field_t; /* Field from a JSON object. type_key/order_key name the keys ("data_type"/ diff --git a/app/engine/scheduler.c b/app/engine/scheduler.c index bc364a3..99fbef4 100644 --- a/app/engine/scheduler.c +++ b/app/engine/scheduler.c @@ -151,14 +151,18 @@ static int days_array_to_mask(cJSON* days) { /*----------------------------------------------------- * Solar calculation (NOAA simplified algorithm) - * Returns seconds-of-day in local time, or -1 if the event doesn't - * occur today (polar day/night). + * solar_event_local_sec() gives the event in local seconds from midnight, + * not wrapped to one day (a sunset after midnight is above 86400). It returns + * 0, or 1 if the sun stays above the event's angle all day (midnight sun) and + * -1 if it stays below (polar night). + * compute_solar_event() wraps that to 0..86399, or returns -1 if the event + * doesn't occur today. *-----------------------------------------------------*/ #ifndef M_PI #define M_PI 3.14159265358979323846 #endif -static int compute_solar_event(double lat, double lon, int event, time_t now) { +static int solar_event_local_sec(double lat, double lon, int event, time_t now, double* out) { struct tm* gm = gmtime(&now); int doy = gm->tm_yday + 1; /* 1-366 */ @@ -191,7 +195,8 @@ static int compute_solar_event(double lat, double lon, int event, time_t now) { /* Hour angle */ double cos_ha = (sin(elev_r) - sin(lat_r) * sin(decl)) / (cos(lat_r) * cos(decl)); - if (cos_ha < -1.0 || cos_ha > 1.0) return -1; /* polar day/night */ + if (cos_ha < -1.0) return 1; + if (cos_ha > 1.0) return -1; double ha_deg = acos(cos_ha) * 180.0 / M_PI; if (event == ASTRO_SUNRISE || event == ASTRO_DAWN) @@ -205,20 +210,40 @@ static int compute_solar_event(double lat, double lon, int event, time_t now) { /* tm_gmtoff is POSIX extension (available on Linux) */ long tz_offset_sec = local_tm->tm_gmtoff; - double event_local_sec = event_utc_min * 60.0 + (double)tz_offset_sec; - while (event_local_sec < 0) event_local_sec += 86400.0; - while (event_local_sec >= 86400) event_local_sec -= 86400.0; + *out = event_utc_min * 60.0 + (double)tz_offset_sec; + return 0; +} - return (int)event_local_sec; +static int compute_solar_event(double lat, double lon, int event, time_t now) { + double sec; + if (solar_event_local_sec(lat, lon, event, now, &sec) != 0) return -1; + while (sec < 0) sec += 86400.0; + while (sec >= 86400) sec -= 86400.0; + return (int)sec; } -int Scheduler_Is_Daytime(double lat, double lon) { +int Scheduler_Is_Daytime(double lat, double lon, int sunrise_offset_sec, int sunset_offset_sec) { time_t now = time(NULL); - int sunrise = compute_solar_event(lat, lon, ASTRO_SUNRISE, now); - int sunset = compute_solar_event(lat, lon, ASTRO_SUNSET, now); - if (sunrise < 0 || sunset < 0) return -1; /* polar */ - int sod = ACAP_DEVICE_Seconds_Since_Midnight(); - return (sod >= sunrise && sod < sunset) ? 1 : 0; + double sunrise, sunset; + int polar = solar_event_local_sec(lat, lon, ASTRO_SUNRISE, now, &sunrise); + if (polar == 0) polar = solar_event_local_sec(lat, lon, ASTRO_SUNSET, now, &sunset); + if (polar != 0) return polar > 0 ? 1 : 0; + sunrise = floor(sunrise) + sunrise_offset_sec; + sunset = floor(sunset) + sunset_offset_sec; + if (sunset <= sunrise) return 0; + if (sunset - sunrise >= 86400.0) return 1; + /* Move the window so its middle falls today; it can then start before or + * end after midnight. Today's times stand in for the neighbouring days' + * (they differ by a few minutes at most). */ + double shift = floor((sunrise + sunset) / 2.0 / 86400.0) * 86400.0; + sunrise -= shift; + sunset -= shift; + double sod = ACAP_DEVICE_Seconds_Since_Midnight(); + for (int day = -1; day <= 1; day++) { + double t = sod + day * 86400.0; + if (t >= sunrise && t < sunset) return 1; + } + return 0; } /*----------------------------------------------------- @@ -285,7 +310,8 @@ int Scheduler_Register(const char* rule_id, int trigger_index, cJSON* config) { double lon_val = lon_j ? lon_j->valuedouble : 0.0; /* Fall back to engine settings lat/lon if trigger doesn't specify them */ if (lat_val == 0.0 && lon_val == 0.0) { - cJSON* eng = ACAP_Get_Config("engine"); + cJSON* sett = ACAP_Get_Config("settings"); + cJSON* eng = sett ? cJSON_GetObjectItem(sett, "engine") : NULL; if (eng) { cJSON* elat = cJSON_GetObjectItem(eng, "latitude"); cJSON* elon = cJSON_GetObjectItem(eng, "longitude"); diff --git a/app/engine/scheduler.h b/app/engine/scheduler.h index 9710404..439cb01 100644 --- a/app/engine/scheduler.h +++ b/app/engine/scheduler.h @@ -33,8 +33,11 @@ void Scheduler_Unregister_Rule(const char* rule_id); void Scheduler_Tick(void); /* Returns 1 if the current time is between sunrise and sunset for the given - * latitude/longitude, 0 if it is nighttime, or -1 on error (polar day/night). */ -int Scheduler_Is_Daytime(double lat, double lon); + * latitude/longitude, else 0. The offsets (seconds, positive = later) shift + * sunrise and sunset; if they make the day window empty, it is night all day. + * The window may cross midnight. Midnight sun counts as day all day and polar + * night as night all day, whatever the offsets. */ +int Scheduler_Is_Daytime(double lat, double lon, int sunrise_offset_sec, int sunset_offset_sec); #ifdef __cplusplus } diff --git a/app/html/app.js b/app/html/app.js index ef09c56..59d4aa9 100644 --- a/app/html/app.js +++ b/app/html/app.js @@ -164,7 +164,8 @@ const RULE_TYPE_LABELS = { vapix_event: 'Device Event', schedule: 'Schedule', mqtt_message: 'MQTT', http_webhook: 'Webhook', io_input: 'I/O Input', counter_threshold: 'Counter', rule_fired: 'Rule Fired', aoa_scenario: 'AOA Scenario', manual: 'Manual', - modbus_read: 'Modbus Read', modbus_error: 'Modbus Error', sparkplug_command: 'Sparkplug Cmd' + modbus_read: 'Modbus Read', modbus_error: 'Modbus Error', sparkplug_command: 'Sparkplug Cmd', + gps_update: 'GPS Update', gps_speed: 'GPS Speed', gps_geofence: 'GPS Geofence', gps_fix: 'GPS Fix' }, condition: { time_window: 'Time Window', io_state: 'I/O State', counter: 'Counter', @@ -183,7 +184,7 @@ const RULE_TYPE_LABELS = { ftp_upload: 'FTP Upload', digest: 'Digest', snapshot_upload: 'Snapshot', guard_tour: 'Guard Tour', ir_cut_filter: 'IR Cut', light_control: 'Light', privacy_mask: 'Privacy Mask', wiper: 'Wiper', set_device_param: 'Device Param', - acap_control: 'ACAP Control', + acap_control: 'ACAP Control', modbus_write: 'Modbus Write', speaker_display: 'Speaker Display', paging_console_execute: 'Paging Execute', paging_console_button: 'Paging Button' @@ -707,7 +708,7 @@ const RULE_TEMPLATES = [ name: 'Night-Only Action', enabled: true, trigger_logic: 'OR', condition_logic: 'AND', triggers: [{ type: 'vapix_event', topic0: { tns1: 'RuleEngine' }, topic1: { tnsaxis: 'MotionDetection' }, filter_key: 'active', filter_value: true }], - conditions: [{ type: 'day_night', state: 'night', lat: 0, lon: 0 }], + conditions: [{ type: 'day_night', state: 'night' }], actions: [{ type: 'recording', operation: 'start', duration: 30 }], cooldown: 30, } @@ -958,6 +959,9 @@ let _uiSaveTimer = null; async function loadUiSettings() { try { const s = await API.get('settings'); + const eng = (s && s.engine) || {}; + if (eng.latitude !== undefined) engineLat = eng.latitude; + if (eng.longitude !== undefined) engineLon = eng.longitude; if (s && s.ui) { _uiSettings.rule_order = s.ui.rule_order || []; _uiSettings.rule_tags = s.ui.rule_tags || {}; @@ -1763,7 +1767,18 @@ window.addEventListener('DOMContentLoaded', () => { const appIcon = document.getElementById('app-icon'); if (appIcon) appIcon.src = initTheme === 'light' ? 'event_engine_icon_dark.svg' : 'event_engine_icon_light.svg'; - loadUiSettings().then(() => loadRules()); + /* The camera slows down when many requests run at once, so show the + * rules first and only then fetch status and device capabilities. */ + loadUiSettings().then(() => loadRules()).finally(() => loadSecondaryData()); + + window.__appBooted = true; + } catch (e) { + showFatalUiError(e && e.message ? e.message : String(e)); + } +}); + +function loadSecondaryData() { + try { loadStatus(); startPoll(); loadVapixEventCatalog(); @@ -1787,20 +1802,11 @@ window.addEventListener('DOMContentLoaded', () => { loadPagingConsoleData() ]).then(() => renderDeviceCapabilities()).catch(() => {}); - /* Load engine lat/lon early so astronomical trigger defaults are correct */ - API.get('settings').then(s => { - const eng = (s && s.engine) || {}; - if (eng.latitude !== undefined) engineLat = eng.latitude; - if (eng.longitude !== undefined) engineLon = eng.longitude; - }).catch(() => {}); - API.getVariables().then(v => { knownVarNames = Object.keys(v || {}).filter(k => !(v[k] && v[k].is_counter)); knownCounterNames = Object.keys(v || {}).filter(k => v[k] && v[k].is_counter); }).catch(() => {}); - - window.__appBooted = true; } catch (e) { showFatalUiError(e && e.message ? e.message : String(e)); } -}); +} diff --git a/app/html/device-capabilities.js b/app/html/device-capabilities.js index ae0b6a8..31be847 100644 --- a/app/html/device-capabilities.js +++ b/app/html/device-capabilities.js @@ -3,6 +3,15 @@ /* key = "host:::query", value = array */ const remoteCapCache = {}; +/* Re-renders the open rule editor after a capability list loads, keeping + * edits made while it loaded. */ +function refreshOpenEditor(triggers, actions, conditions) { + if (document.getElementById('modal-overlay').classList.contains('hidden')) return; + if (triggers) { flushTriggerRows(); renderTriggerList(); } + if (actions) { flushActionRows(); renderActionList(); } + if (conditions) { flushConditionRows(); renderConditionList(); } +} + function rowHttps(row) { const el = row.querySelector('[data-k="remote_https"]'); return !!(el && el.checked); @@ -194,10 +203,7 @@ async function loadVapixEventCatalog() { vapixEventCatalog = []; } /* If the rule editor is open, re-render so catalog-based hints and dropdowns update */ - if (!document.getElementById('modal-overlay').classList.contains('hidden')) { - renderTriggerList(); - renderActionList(); - } + refreshOpenEditor(true, true, false); } async function loadPtzPresets() { @@ -307,8 +313,7 @@ async function loadAcapApps() { acapApps = apps.sort((a, b) => a.niceName.localeCompare(b.niceName)); } catch(e) { acapApps = []; } renderDeviceCapabilities(); - if (!document.getElementById('modal-overlay').classList.contains('hidden')) - renderActionList(); + refreshOpenEditor(false, true, false); } async function loadPrivacyMasks() { @@ -321,8 +326,7 @@ async function loadPrivacyMasks() { privacyMasks = list.map(m => ({ name: m.name })); } catch(e) { privacyMasks = []; } renderDeviceCapabilities(); - if (!document.getElementById('modal-overlay').classList.contains('hidden')) - renderActionList(); + refreshOpenEditor(false, true, false); } async function loadDeviceParams() { @@ -337,8 +341,7 @@ async function loadDeviceParams() { } deviceParams = params; } catch(e) { deviceParams = []; } - if (!document.getElementById('modal-overlay').classList.contains('hidden')) - renderActionList(); + refreshOpenEditor(false, true, false); } async function loadGuardTours() { @@ -357,8 +360,7 @@ async function loadGuardTours() { guardTours = Object.values(byId).sort((a, b) => a.id - b.id); } catch(e) { guardTours = []; } renderDeviceCapabilities(); - if (!document.getElementById('modal-overlay').classList.contains('hidden')) - renderActionList(); + refreshOpenEditor(false, true, false); } async function loadAoaScenarios() { @@ -369,11 +371,7 @@ async function loadAoaScenarios() { aoaScenarios = Array.isArray(data) ? data : []; } catch(e) { aoaScenarios = []; } renderDeviceCapabilities(); - if (!document.getElementById('modal-overlay').classList.contains('hidden')) { - renderTriggerList(); - renderActionList(); - renderConditionList(); - } + refreshOpenEditor(true, true, true); } async function loadPagingConsoleData() { @@ -415,8 +413,7 @@ async function loadPagingConsoleData() { .sort((a, b) => a.name.localeCompare(b.name)); } catch(e) { pagingPages = []; } - if (!document.getElementById('modal-overlay').classList.contains('hidden')) - renderActionList(); + refreshOpenEditor(false, true, false); } /* Called onblur from the set_device_param parameter input. */ diff --git a/app/html/help.html b/app/html/help.html index 920ef5b..12420c4 100644 --- a/app/html/help.html +++ b/app/html/help.html @@ -581,7 +581,7 @@

Modbus Read

OptionDescription ConnectionTCP connects to the device host and port. Serial Gateway uses the camera's configured PortManager service. RTU direct selects a serial device, baud rate and parity. ReadOne value reads a single value; Block of values reads a register map. One request covers up to 125 registers (the Modbus limit) or 2000 bits; a larger map is read in several requests, up to 2000 registers from the first to the last address. - Data typeRegisters support unsigned/signed 16-, 32- and 64-bit integers, 32- and 64-bit floats, and strings (two bytes per register, up to 125 registers; the text ends at the first NUL). Bit reads return 0 or 1. + Data typeRegisters support unsigned/signed 16-, 32- and 64-bit integers, 32- and 64-bit floats, and strings (two bytes per register, up to 125 registers; the text ends at the first NUL). String length is counted in registers, not characters; UTF-8 characters may use multiple bytes. Bit reads return 0 or 1. Word / byte orderABCD, CDAB, BADC, or DCBA for 32- and 64-bit values. For 16-bit values and strings, choose AB (normal) or BA (byte swap): the two bytes of each register. EncodingFor strings: UTF-8 (default), ASCII, ISO-8859-1, ISO-8859-2, Windows-1250 or Windows-1252. Text is converted to UTF-8 for variables; bytes that are not valid in the encoding read as ?. Scale / offsetNumeric values are reported as raw × scale + offset, e.g. a register of 231 with scale 0.1 reads as 23.1. Both accept decimals with a point or a comma (-0,5). Optional decimal rounding is applied after scaling. @@ -694,9 +694,10 @@

Day / Night

- + +
OptionDescription
PeriodDay or Night.
Lat/Lon overrideOptional per-condition coordinates, overriding the global Location setting.
Sunrise / Sunset offsetOptional minutes to shift each boundary (positive = later, up to ±720). For example, a sunrise offset of 60 keeps it night until one hour after sunrise, and a sunset offset of -30 starts night 30 minutes before sunset.
Lat/Lon overrideOptional per-condition coordinates, overriding the global Location setting. Leave empty (or 0/0) to use the Location setting.
-

The rule editor shows today's computed sunrise and sunset times for the configured location.

+

The rule editor shows when day and night start today, including any offsets, and updates as you type coordinates or offsets. Day can run past midnight, for example when a positive sunset offset moves sunset after 00:00. On days with no sunrise or sunset, midnight sun counts as day and polar night as night.

Device Event State

Check the current state of any device event by polling the device’s event instances.

@@ -1106,8 +1107,8 @@

AOA Get Counts

Modbus Write

Write one typed value or several values to holding registers or coils over TCP, serial gateway, or direct RTU/RS-485. The automatic function uses FC06/FC05 for one value and FC16/FC15 for several. Adjacent entries are batched; gaps start another request. Coils accept 0, 1, true, false, on, or off.

-

Register types include signed/unsigned 16-, 32- and 64-bit integers, 32-/64-bit floats, and strings (two bytes per register, up to 125 registers). Set the word order for 32/64-bit values, or the byte order for 16-bit values and strings. Scale and offset convert the requested value to raw form using (value - offset) / scale. Values can contain templates such as {{trigger.temperature}}. Numbers and coils need a value; an empty string clears a text register.

-

Strings are converted to the selected encoding (UTF-8, ASCII, ISO-8859-1, ISO-8859-2, Windows-1250 or Windows-1252) and padded with NUL (0x00) to the configured length. A typed-in character the encoding can't represent is rejected when the rule is saved; text from a template is sent with ? in its place. One request carries at most 123 registers or 1968 coils (the Modbus limit); longer runs and long strings are split into several requests automatically.

+

Register types include signed/unsigned 16-, 32- and 64-bit integers, 32-/64-bit floats, and strings (two bytes per register, up to 125 registers). String length is counted in registers, not characters; UTF-8 characters may use multiple bytes. Set the word order for 32/64-bit values, or the byte order for 16-bit values and strings. Scale and offset convert the requested value to raw form using (value - offset) / scale. Values can contain templates such as {{trigger.temperature}}. Numbers and coils need a value; an empty string clears a text register.

+

Strings are converted to the selected encoding (UTF-8, ASCII, ISO-8859-1, ISO-8859-2, Windows-1250 or Windows-1252) and padded to the configured length. Fill chooses the padding: NUL (0x00, the default) after the text, or spaces with the text left, right or centered (an odd space goes after the text). Choose spaces if the device shows 0x00 as a character. A typed-in character the encoding can't represent is rejected when the rule is saved; text from a template is sent with ? in its place. One request carries at most 123 registers or 1968 coils (the Modbus limit); longer runs and long strings are split into several requests automatically.

Test sends the write and waits for the device's answer, so it reports timeouts, refused connections and Modbus exceptions. A pooled TCP connection that the device closed while idle is reopened automatically.

diff --git a/app/html/index.html b/app/html/index.html index 7376b10..ff02081 100644 --- a/app/html/index.html +++ b/app/html/index.html @@ -4,7 +4,7 @@ Event Engine - + - - - - - + + + + + + diff --git a/app/html/openapi.json b/app/html/openapi.json index ae03519..a9082bc 100644 --- a/app/html/openapi.json +++ b/app/html/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "ACAP Event Engine", "description": "REST API for the Axis Event Engine ACAP — an If-This-Then-That style rule engine running on Axis cameras.\n\nAll endpoints are served via FastCGI at `/local/acap_event_engine/{endpoint}` and require HTTP Basic Auth with admin credentials.\n\n### Template Variables\nAction strings (URLs, payloads, messages, overlay text, etc.) support `{{...}}` substitution:\n\n| Variable | Value |\n|----------|-------|\n| `{{timestamp}}` | RFC 3339 timestamp in device local time (e.g. `2026-04-30T13:00:00+02:00`) |\n| `{{date}}` | YYYY-MM-DD |\n| `{{time}}` | HH:MM:SS |\n| `{{camera.serial}}` | Device serial number |\n| `{{camera.model}}` | Device model name |\n| `{{camera.ip}}` | Device IP address |\n| `{{trigger_json}}` | Full trigger event data as compact JSON |\n| `{{trigger.KEY}}` | Individual field from the trigger event |\n| `{{var.NAME}}` | Named variable value |\n| `{{counter.NAME}}` | Named counter value |\n| `{{gps.latitude}}`, `{{gps.longitude}}` | Latest coordinates from a fresh GPS fix |\n| `{{gps.speed_kmh}}`, `{{gps.speed_mph}}`, `{{gps.speed_knots}}`, `{{gps.speed_mps}}` | Latest speed in the named units |\n| `{{gps.heading}}`, `{{gps.heading_cardinal}}`, `{{gps.altitude_m}}` | Heading, compass direction, and altitude |\n| `{{gps.age}}` | Seconds since the latest valid fix |\n| `{{trigger.snapshot_base64}}` | Base64 JPEG (when `attach_snapshot` is true on HTTP Request, Email, MQTT Publish, Slack, Teams, or Telegram actions) |\n\nNumeric formatting: `{{trigger.KEY|N}}` rounds a numeric field to N decimal places — e.g. `{{trigger.Temperature|2}}` → `20.35`. GPS values other than age resolve to `--` unless GPS is enabled and a fresh fix is available.\n", - "version": "1.10.3", + "version": "1.10.4", "contact": { "name": "GitHub", "url": "https://github.com/Mo3he" @@ -1303,8 +1303,9 @@ "word_order": { "type": "string", "enum": ["ABCD", "CDAB", "BADC", "DCBA"], "default": "ABCD", "description": "Byte order. All four apply to 32/64-bit values; for 16-bit values and strings only ABCD (normal) and BADC (bytes swapped in each register) differ" }, "scale": { "type": "number", "default": 1, "description": "Numeric input is converted to raw form using (value - offset) / scale; cannot be zero" }, "offset": { "type": "number", "default": 0, "description": "Numeric value offset" }, - "length": { "type": "integer", "minimum": 1, "maximum": 125, "default": 8, "description": "String length in registers (2 bytes each); shorter text is padded with NUL" }, + "length": { "type": "integer", "minimum": 1, "maximum": 125, "default": 8, "description": "String length in registers (2 bytes each); shorter text is padded as fill says" }, "encoding": { "type": "string", "enum": ["utf-8", "ascii", "iso-8859-1", "iso-8859-2", "windows-1250", "windows-1252"], "default": "utf-8", "description": "Character encoding of a string; characters it can't represent are rejected in literal values and sent as ? from templates" }, + "fill": { "type": "string", "enum": ["nul", "space_left", "space_right", "space_center"], "default": "nul", "description": "String padding: nul puts the text first and fills with 0x00; space_* fill with spaces and put the text left, right or centered (an odd space goes after)" }, "value": { "oneOf": [ { "type": "number" }, @@ -1333,7 +1334,8 @@ "scale": { "type": "number", "default": 1 }, "offset": { "type": "number", "default": 0 }, "length": { "type": "integer", "minimum": 1, "maximum": 125, "default": 8 }, - "encoding": { "type": "string", "enum": ["utf-8", "ascii", "iso-8859-1", "iso-8859-2", "windows-1250", "windows-1252"], "default": "utf-8" } + "encoding": { "type": "string", "enum": ["utf-8", "ascii", "iso-8859-1", "iso-8859-2", "windows-1250", "windows-1252"], "default": "utf-8" }, + "fill": { "type": "string", "enum": ["nul", "space_left", "space_right", "space_center"], "default": "nul" } } } } diff --git a/app/html/rule-editor.js b/app/html/rule-editor.js index 88fbfe6..bfb6542 100644 --- a/app/html/rule-editor.js +++ b/app/html/rule-editor.js @@ -395,7 +395,7 @@ function triggerFields(t, rowIdx) {
- +
Comma-separated day numbers (0=Sun)
` : ''} @@ -643,7 +643,7 @@ function triggerFields(t, rowIdx) {
- +
Fires on transitions after the first valid GPS position. A polygon needs at least 3 points.
`; @@ -778,6 +778,11 @@ const MB_ENCODINGS = [ ['iso-8859-1', 'ISO-8859-1 (Latin-1)'], ['iso-8859-2', 'ISO-8859-2 (Latin-2)'], ['windows-1250', 'Windows-1250 (Central European)'], ['windows-1252', 'Windows-1252 (Western)'], ]; +/* How a string write fills the bytes the text doesn't use: value, label, short label for the table. */ +const MB_FILLS = [ + ['nul', 'NUL (0x00)', 'NUL'], ['space_left', 'Spaces, text left', 'Space, left'], + ['space_right', 'Spaces, text right', 'Space, right'], ['space_center', 'Spaces, centered', 'Space, center'], +]; const MB_MAX_STRING_REGS = 125; const MB_TYPE_REGS = { uint16: 1, int16: 1, uint32: 2, int32: 2, float32: 2, uint64: 4, int64: 4, float64: 4 }; @@ -861,6 +866,10 @@ function mbEncodingOptions(sel, short) { const cur = (sel || 'utf-8').toLowerCase(); return MB_ENCODINGS.map(([v, l]) => ``).join(''); } +function mbFillOptions(sel, short) { + const cur = sel || 'nul'; + return MB_FILLS.map(([v, l, s]) => ``).join(''); +} /* Data type, word/byte order, scaling, string length and encoding of a * single value. withDecimals: a read (scaling applies forwards). */ @@ -893,13 +902,18 @@ function mbTypeFields(o, typeKey, orderKey, rerender, withDecimals) {
-
1-${MB_MAX_STRING_REGS}. ${withDecimals ? 'Text stops at the first NUL.' : 'Shorter text is padded with NUL (0x00).'}
+
1-${MB_MAX_STRING_REGS} registers (2 bytes each). This is not a character count; UTF-8 characters may use multiple bytes. ${withDecimals ? 'Text stops at the first NUL.' : 'Fill sets what goes in the bytes shorter text leaves free.'}
Character set of the device. In UTF-8, letters such as ą or ż take 2 bytes.
-
` : ` + ${withDecimals ? '' : ` +
+ + +
What goes in the bytes the text doesn't use. Use spaces if the device shows 0x00 as a character.
+
`}` : ` ${num('scale', 'Scale (multiplier)', '', '1', withDecimals ? 'value = raw × scale + offset' : 'raw = (value − offset) ÷ scale')} ${num('offset', 'Offset', '', '0', 'e.g. -0.5')} ${withDecimals ? num('decimals', 'Decimals', '', 'auto', 'Rounding') : ''}`} @@ -918,20 +932,21 @@ const MB_COLS = { scale: { label: 'Scale', w: 64, input: 'decimal', ph: '1', title: 'Scale (multiplier)' }, offset: { label: 'Offset', w: 64, input: 'decimal', ph: '0' }, decimals: { label: 'Decimals', w: 72, input: 'decimal', ph: 'auto', title: 'Decimals (rounding)' }, - length: { label: 'Length', w: 60, input: 'number', ph: '8', title: 'Length in registers (text, 1-125)' }, + length: { label: 'Length', w: 60, input: 'number', ph: '8', title: 'String length in registers (2 bytes each; UTF-8 characters may use multiple bytes)' }, encoding: { label: 'Encoding', w: 104, title: 'Character encoding (text)' }, + fill: { label: 'Fill', w: 116, title: 'Bytes the text doesn\'t use: NUL (0x00) or spaces with the text left, right or centered' }, }; function mbTableCols(kind, bits) { if (kind === 'map') return bits ? ['register', 'var'] : ['register', 'var', 'type', 'order', 'scale', 'offset', 'decimals', 'length', 'encoding']; - return bits ? ['register', 'value'] : ['register', 'value', 'type', 'order', 'scale', 'offset', 'length', 'encoding']; + return bits ? ['register', 'value'] : ['register', 'value', 'type', 'order', 'scale', 'offset', 'length', 'encoding', 'fill']; } -/* Cells that don't apply to the row's type: length and encoding are for +/* Cells that don't apply to the row's type: length, encoding and fill are for * strings only, and scaling is for numbers only. */ function mbCellOff(c, type) { const str = (type || 'uint16') === 'string'; - return c === 'length' || c === 'encoding' ? !str : (str && (c === 'scale' || c === 'offset' || c === 'decimals')); + return c === 'length' || c === 'encoding' || c === 'fill' ? !str : (str && (c === 'scale' || c === 'offset' || c === 'decimals')); } function mbTableRow(kind, r, bits) { @@ -942,7 +957,8 @@ function mbTableRow(kind, r, bits) { let ctl; if (c === 'type') ctl = ``; else if (c === 'order') ctl = ``; - else if (c === 'encoding') ctl = ``; + else if (c === 'encoding') ctl = ``; + else if (c === 'fill') ctl = ``; else if (def.input === 'decimal') ctl = ``; else ctl = ` MB_COLS[c].w ? `` : '').join('') + ''; const head = cols.map(c => `${MB_COLS[c].label}`).join(''); - const hint = kind === 'map' + const hint = (kind === 'map' ? `Read from the lowest to the highest address, ${bits ? 'up to 2000 bits in one request' : 'up to 125 registers per request; larger maps are read in several requests (at most 2000 registers)'}. Each value is stored in its variable and is {{trigger.NAME}} in actions.` - : `Adjacent ${bits ? 'coils are written in one request (FC15, up to 1968)' : 'registers are written in one request (FC16, up to 123 registers); longer runs are split'}, and a gap starts a new request. Values can use placeholders.`; + : `Adjacent ${bits ? 'coils are written in one request (FC15, up to 1968)' : 'registers are written in one request (FC16, up to 123 registers); longer runs are split'}, and a gap starts a new request. Values can use placeholders.`) + + (!bits ? ' For string rows, Length counts 2-byte registers, not characters; UTF-8 characters may use multiple bytes.' : ''); return `
@@ -990,9 +1007,10 @@ function mbTableSync(el) { } o.order = ord.value; } - tr.querySelectorAll('input[data-mk], select[data-mk="encoding"]').forEach(i => { + tr.querySelectorAll('input[data-mk], select[data-mk="encoding"], select[data-mk="fill"]').forEach(i => { const c = i.dataset.mk; i.disabled = mbCellOff(c, o.type); + if (c === 'encoding' || c === 'fill') i.hidden = i.disabled; if (i.tagName === 'INPUT') i.placeholder = i.disabled ? '' : (MB_COLS[c].ph || ''); if (i.disabled) delete o[c]; }); @@ -1046,6 +1064,7 @@ function mbNormField(src, out, typeKey, orderKey, withDecimals) { out.length = parseInt(src.length) || 8; const enc = (src.encoding || 'utf-8').toLowerCase(); if (enc !== 'utf-8') out.encoding = enc; + if (!withDecimals && src.fill && src.fill !== 'nul') out.fill = src.fill; return; } const scale = mbNumOrText(src.scale), offset = mbNumOrText(src.offset), decimals = mbNumOrText(src.decimals); @@ -1202,15 +1221,7 @@ function renderTriggerList() { }); } -function flushTriggerRows() { - triggerRows = triggerRows.map((_, i) => { - const el = document.getElementById('trow-' + i); - if (!el) return _; - const data = { type: _.type }; - el.querySelectorAll('[data-k]').forEach(inp => { data[inp.dataset.k] = inp.value; }); - return data; - }); -} +function flushTriggerRows() { triggerRows = collectRows(triggerRows, 'trow'); } function addTriggerRow() { flushTriggerRows(); triggerRows.push({ type: 'vapix_event' }); @@ -1323,7 +1334,7 @@ function conditionFields(c, rowIdx) {
- +
`; if (type === 'counter') return ` @@ -1512,13 +1523,7 @@ function conditionFields(c, rowIdx) { `; } if (type === 'day_night') { - const lat = c.lat !== undefined && c.lat !== '' ? parseFloat(c.lat) : engineLat; - const lon = c.lon !== undefined && c.lon !== '' ? parseFloat(c.lon) : engineLon; - const rise = calcSolarEvent(lat, lon, 'sunrise', 0); - const set = calcSolarEvent(lat, lon, 'sunset', 0); - const solarHint = rise && set - ? `Today: sunrise ${rise}, sunset ${set}` - : (lat === 0 && lon === 0 ? 'Set latitude/longitude in Location' : 'No sunrise/sunset today (polar)'); + const solarHint = dayNightHint(c.lat, c.lon, c.sunrise_offset_minutes, c.sunset_offset_minutes); return `
@@ -1527,17 +1532,29 @@ function conditionFields(c, rowIdx) { -
${solarHint}
+
${escHtml(solarHint)}
+
+
+
+
+ + +
E.g. 60 keeps it "night" until 1 hour after sunrise
+
+
+ + +
E.g. -30 starts "night" 30 minutes before sunset
- +
- +
`; } @@ -1754,6 +1771,34 @@ function collectConditionRow(i) { conditionRows[i] = data; } +/* Mirrors cond_day_night: empty or 0/0 coordinates fall back to Location settings */ +function dayNightHint(latIn, lonIn, sunriseOffset, sunsetOffset) { + let lat = parseFloat(latIn), lon = parseFloat(lonIn); + if (isNaN(lat)) lat = 0; + if (isNaN(lon)) lon = 0; + if (lat === 0 && lon === 0) { lat = parseFloat(engineLat) || 0; lon = parseFloat(engineLon) || 0; } + const riseOff = parseFloat(sunriseOffset) || 0; + const setOff = parseFloat(sunsetOffset) || 0; + const rise = calcSolarEvent(lat, lon, 'sunrise', riseOff); + const set = calcSolarEvent(lat, lon, 'sunset', setOff); + if (!rise || !set) { + if (lat === 0 && lon === 0) return 'Set latitude/longitude in Location'; + return isMidnightSun(lat) ? 'No sunset today (midnight sun): day all day' + : 'No sunrise today (polar night): night all day'; + } + const offNote = riseOff || setOff ? ' (with offsets)' : ''; + return `Today: day starts ${rise}, night starts ${set}${offNote}`; +} + +/* Live-update the day_night hint while coordinates/offsets are typed */ +function refreshDayNightHint(inp) { + const row = inp.closest('.tca-row'); + if (!row) return; + const val = k => { const e = row.querySelector(`[data-k="${k}"]`); return e ? e.value : ''; }; + const hint = row.querySelector('[data-role="day-night-hint"]'); + if (hint) hint.textContent = dayNightHint(val('lat'), val('lon'), val('sunrise_offset_minutes'), val('sunset_offset_minutes')); +} + function rerenderCondition(sel) { const row = sel.closest('.tca-row'); const i = parseInt(row.id.replace('crow-', '')); @@ -3866,6 +3911,8 @@ function collectRows(rows, prefix) { const el = document.getElementById(`${prefix}-${i}`); if (!el) return _; const data = { type: _.type }; + /* Editor-only state (e.g. _adding, _dataTypes) has no input; keep it */ + for (const k of Object.keys(_)) if (k.startsWith('_')) data[k] = _[k]; el.querySelectorAll('[data-k]').forEach(inp => { data[inp.dataset.k] = inp.type === 'checkbox' ? inp.checked : inp.value; }); @@ -3999,6 +4046,10 @@ function normalizeCondition(c) { out.state = c.state || 'day'; if (c.lat !== undefined && c.lat !== '') out.lat = parseFloat(c.lat); if (c.lon !== undefined && c.lon !== '') out.lon = parseFloat(c.lon); + const riseOff = parseFloat(c.sunrise_offset_minutes) || 0; + const setOff = parseFloat(c.sunset_offset_minutes) || 0; + if (riseOff !== 0) out.sunrise_offset_minutes = riseOff; + if (setOff !== 0) out.sunset_offset_minutes = setOff; } else if (c.type === 'vapix_event_state') { out.event_key = c.event_key || ''; out.data_key = c.data_key || ''; diff --git a/app/html/settings.js b/app/html/settings.js index 3a6e2ab..a6ff076 100644 --- a/app/html/settings.js +++ b/app/html/settings.js @@ -228,6 +228,17 @@ function calcSolarEvent(lat, lon, eventType, offsetMin) { return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}`; } +/* For a day with no sunrise or sunset: true for midnight sun, false for polar night. */ +function isMidnightSun(lat) { + const now = new Date(); + const doy = Math.floor((now - new Date(now.getFullYear(), 0, 0)) / 86400000); + const B = 2 * Math.PI * (doy - 1) / 365; + const decl = 0.006918 - 0.399912*Math.cos(B) + 0.070257*Math.sin(B) + - 0.006758*Math.cos(2*B) + 0.000907*Math.sin(2*B) + - 0.002697*Math.cos(3*B) + 0.00148 *Math.sin(3*B); + return lat * decl > 0; +} + function refreshSolarPreview(lat, lon, containerId) { const el = document.getElementById(containerId); if (!el) return; diff --git a/app/manifest.json b/app/manifest.json index 614cd5f..1f87160 100644 --- a/app/manifest.json +++ b/app/manifest.json @@ -8,7 +8,7 @@ "vendorId": "70ee172dd9", "vendorUrl": "https://github.com/Mo3he", "runMode": "respawn", - "version": "1.10.3", + "version": "1.10.4", "compatibleOsVersions": [ { "min": "11.11", diff --git a/docs/help.html b/docs/help.html index e180b0b..4242918 100644 --- a/docs/help.html +++ b/docs/help.html @@ -582,7 +582,7 @@

Modbus Read

OptionDescription ConnectionTCP connects to the device host and port. Serial Gateway uses the camera's configured PortManager service. RTU direct selects a serial device, baud rate and parity. ReadOne value reads a single value; Block of values reads a register map. One request covers up to 125 registers (the Modbus limit) or 2000 bits; a larger map is read in several requests, up to 2000 registers from the first to the last address. - Data typeRegisters support unsigned/signed 16-, 32- and 64-bit integers, 32- and 64-bit floats, and strings (two bytes per register, up to 125 registers; the text ends at the first NUL). Bit reads return 0 or 1. + Data typeRegisters support unsigned/signed 16-, 32- and 64-bit integers, 32- and 64-bit floats, and strings (two bytes per register, up to 125 registers; the text ends at the first NUL). String length is counted in registers, not characters; UTF-8 characters may use multiple bytes. Bit reads return 0 or 1. Word / byte orderABCD, CDAB, BADC, or DCBA for 32- and 64-bit values. For 16-bit values and strings, choose AB (normal) or BA (byte swap): the two bytes of each register. EncodingFor strings: UTF-8 (default), ASCII, ISO-8859-1, ISO-8859-2, Windows-1250 or Windows-1252. Text is converted to UTF-8 for variables; bytes that are not valid in the encoding read as ?. Scale / offsetNumeric values are reported as raw × scale + offset, e.g. a register of 231 with scale 0.1 reads as 23.1. Both accept decimals with a point or a comma (-0,5). Optional decimal rounding is applied after scaling. @@ -695,9 +695,10 @@

Day / Night

- + +
OptionDescription
PeriodDay or Night.
Lat/Lon overrideOptional per-condition coordinates, overriding the global Location setting.
Sunrise / Sunset offsetOptional minutes to shift each boundary (positive = later, up to ±720). For example, a sunrise offset of 60 keeps it night until one hour after sunrise, and a sunset offset of -30 starts night 30 minutes before sunset.
Lat/Lon overrideOptional per-condition coordinates, overriding the global Location setting. Leave empty (or 0/0) to use the Location setting.
-

The rule editor shows today's computed sunrise and sunset times for the configured location.

+

The rule editor shows when day and night start today, including any offsets, and updates as you type coordinates or offsets. Day can run past midnight, for example when a positive sunset offset moves sunset after 00:00. On days with no sunrise or sunset, midnight sun counts as day and polar night as night.

Device Event State

Check the current state of any device event by polling the device’s event instances.

@@ -1107,8 +1108,8 @@

AOA Get Counts

Modbus Write

Write one typed value or several values to holding registers or coils over TCP, serial gateway, or direct RTU/RS-485. The automatic function uses FC06/FC05 for one value and FC16/FC15 for several. Adjacent entries are batched; gaps start another request. Coils accept 0, 1, true, false, on, or off.

-

Register types include signed/unsigned 16-, 32- and 64-bit integers, 32-/64-bit floats, and strings (two bytes per register, up to 125 registers). Set the word order for 32/64-bit values, or the byte order for 16-bit values and strings. Scale and offset convert the requested value to raw form using (value - offset) / scale. Values can contain templates such as {{trigger.temperature}}. Numbers and coils need a value; an empty string clears a text register.

-

Strings are converted to the selected encoding (UTF-8, ASCII, ISO-8859-1, ISO-8859-2, Windows-1250 or Windows-1252) and padded with NUL (0x00) to the configured length. A typed-in character the encoding can't represent is rejected when the rule is saved; text from a template is sent with ? in its place. One request carries at most 123 registers or 1968 coils (the Modbus limit); longer runs and long strings are split into several requests automatically.

+

Register types include signed/unsigned 16-, 32- and 64-bit integers, 32-/64-bit floats, and strings (two bytes per register, up to 125 registers). String length is counted in registers, not characters; UTF-8 characters may use multiple bytes. Set the word order for 32/64-bit values, or the byte order for 16-bit values and strings. Scale and offset convert the requested value to raw form using (value - offset) / scale. Values can contain templates such as {{trigger.temperature}}. Numbers and coils need a value; an empty string clears a text register.

+

Strings are converted to the selected encoding (UTF-8, ASCII, ISO-8859-1, ISO-8859-2, Windows-1250 or Windows-1252) and padded to the configured length. Fill chooses the padding: NUL (0x00, the default) after the text, or spaces with the text left, right or centered (an odd space goes after the text). Choose spaces if the device shows 0x00 as a character. A typed-in character the encoding can't represent is rejected when the rule is saved; text from a template is sent with ? in its place. One request carries at most 123 registers or 1968 coils (the Modbus limit); longer runs and long strings are split into several requests automatically.

Test sends the write and waits for the device's answer, so it reports timeouts, refused connections and Modbus exceptions. A pooled TCP connection that the device closed while idle is reopened automatically.

diff --git a/docs/index.html b/docs/index.html index 43bf8f9..4ed2342 100644 --- a/docs/index.html +++ b/docs/index.html @@ -937,7 +937,7 @@
- v1.10.3 - No pause after saving; MQTT and Sparkplug B fixes + v1.10.4 - Day/Night offsets and Modbus text padding

Automate your
Axis camera

diff --git a/tools/modbus_codec_test.c b/tools/modbus_codec_test.c index 725011e..35132af 100644 --- a/tools/modbus_codec_test.c +++ b/tools/modbus_codec_test.c @@ -98,20 +98,20 @@ static void test_round_trip(void) { static void test_strings(void) { uint16_t regs[3]; - CHECK(mb_encode_string("HELLO", 3, MB_O_ABCD, MB_CS_ASCII, regs, NULL) == 0, "encode HELLO"); + CHECK(mb_encode_string("HELLO", 3, MB_O_ABCD, MB_CS_ASCII, MB_FILL_NUL, regs, NULL) == 0, "encode HELLO"); uint16_t want[3] = { 0x4845, 0x4C4C, 0x4F00 }; expect_regs("string ABCD", regs, want, 3); char out[16]; mb_decode_string(regs, 3, MB_O_ABCD, MB_CS_ASCII, out, sizeof(out)); CHECK(strcmp(out, "HELLO") == 0, "decode HELLO got '%s'", out); - CHECK(mb_encode_string("HELLO", 3, MB_O_BADC, MB_CS_ASCII, regs, NULL) == 0, "encode HELLO BADC"); + CHECK(mb_encode_string("HELLO", 3, MB_O_BADC, MB_CS_ASCII, MB_FILL_NUL, regs, NULL) == 0, "encode HELLO BADC"); uint16_t want_sw[3] = { 0x4548, 0x4C4C, 0x004F }; expect_regs("string BADC", regs, want_sw, 3); mb_decode_string(regs, 3, MB_O_BADC, MB_CS_ASCII, out, sizeof(out)); CHECK(strcmp(out, "HELLO") == 0, "decode HELLO BADC got '%s'", out); - CHECK(mb_encode_string("TOO LONG", 3, MB_O_ABCD, MB_CS_ASCII, regs, NULL) == -1, "string too long"); + CHECK(mb_encode_string("TOO LONG", 3, MB_O_ABCD, MB_CS_ASCII, MB_FILL_NUL, regs, NULL) == -1, "string too long"); uint16_t padded[3] = { 0x4F4B, 0x2020, 0x2020 }; /* "OK " */ mb_decode_string(padded, 3, MB_O_ABCD, MB_CS_ASCII, out, sizeof(out)); @@ -124,11 +124,51 @@ static void test_strings(void) { /* The rest of the registers is NUL, whatever was there before */ uint16_t pad[4] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF }; - CHECK(mb_encode_string("ABC", 4, MB_O_ABCD, MB_CS_ASCII, pad, NULL) == 0, "encode ABC"); + CHECK(mb_encode_string("ABC", 4, MB_O_ABCD, MB_CS_ASCII, MB_FILL_NUL, pad, NULL) == 0, "encode ABC"); uint16_t want_pad[4] = { 0x4142, 0x4300, 0x0000, 0x0000 }; expect_regs("NUL padding", pad, want_pad, 4); } +static void test_fill(void) { + CHECK(mb_fill_parse(NULL) == MB_FILL_NUL && mb_fill_parse("") == MB_FILL_NUL, "fill defaults to nul"); + CHECK(mb_fill_parse("space_center") == MB_FILL_SPACE_CENTER, "fill space_center"); + CHECK(mb_fill_parse("spaces") == MB_FILL_INVALID, "unknown fill"); + + struct { mb_fill_t fill; mb_order_t o; uint16_t want[3]; const char* name; } cases[] = { + { MB_FILL_SPACE_LEFT, MB_O_ABCD, { 0x4142, 0x4320, 0x2020 }, "space_left" }, /* "ABC " */ + { MB_FILL_SPACE_RIGHT, MB_O_ABCD, { 0x2020, 0x2041, 0x4243 }, "space_right" }, /* " ABC" */ + { MB_FILL_SPACE_CENTER, MB_O_ABCD, { 0x2041, 0x4243, 0x2020 }, "space_center" }, /* " ABC " */ + { MB_FILL_SPACE_RIGHT, MB_O_BADC, { 0x2020, 0x4120, 0x4342 }, "space_right BADC" }, + }; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + uint16_t regs[3] = { 0xFFFF, 0xFFFF, 0xFFFF }; + CHECK(mb_encode_string("ABC", 3, cases[i].o, MB_CS_ASCII, cases[i].fill, regs, NULL) == 0, "encode %s", cases[i].name); + expect_regs(cases[i].name, regs, cases[i].want, 3); + } + /* Centring an even gap splits it evenly; full-length text has no fill */ + uint16_t regs[3]; + CHECK(mb_encode_string("AB", 2, MB_O_ABCD, MB_CS_ASCII, MB_FILL_SPACE_CENTER, regs, NULL) == 0, "encode AB centred"); + uint16_t want_even[2] = { 0x2041, 0x4220 }; + expect_regs("space_center even", regs, want_even, 2); + CHECK(mb_encode_string("ABCDEF", 3, MB_O_ABCD, MB_CS_ASCII, MB_FILL_SPACE_RIGHT, regs, NULL) == 0, "encode full length"); + uint16_t want_full[3] = { 0x4142, 0x4344, 0x4546 }; + expect_regs("full length right", regs, want_full, 3); + CHECK(mb_encode_string("ABCDEFG", 3, MB_O_ABCD, MB_CS_ASCII, MB_FILL_SPACE_LEFT, regs, NULL) == -1, "too long with fill"); + /* Bytes, not characters: "ż" is 2 bytes in UTF-8, so "żA" leaves 1 */ + CHECK(mb_encode_string("\xC5\xBC" "A", 2, MB_O_ABCD, MB_CS_UTF8, MB_FILL_SPACE_RIGHT, regs, NULL) == 0, "encode UTF-8 right"); + uint16_t want_utf8[2] = { 0x20C5, 0xBC41 }; + expect_regs("UTF-8 right", regs, want_utf8, 2); + /* An empty text fills the registers */ + CHECK(mb_encode_string("", 2, MB_O_ABCD, MB_CS_ASCII, MB_FILL_SPACE_CENTER, regs, NULL) == 0, "encode empty"); + uint16_t want_empty[2] = { 0x2020, 0x2020 }; + expect_regs("empty with spaces", regs, want_empty, 2); + /* Right-aligned text reads back with its leading spaces */ + CHECK(mb_encode_string("ABC", 3, MB_O_ABCD, MB_CS_ASCII, MB_FILL_SPACE_RIGHT, regs, NULL) == 0, "encode for read back"); + char out[16]; + mb_decode_string(regs, 3, MB_O_ABCD, MB_CS_ASCII, out, sizeof(out)); + CHECK(strcmp(out, " ABC") == 0, "right-aligned reads back as '%s'", out); +} + static void test_encodings(void) { const char* pl = "Za\xC5\xBC\xC3\xB3\xC5\x82\xC4\x87"; /* "Zażółć" in UTF-8 */ struct { mb_charset_t cs; const char* bytes; int n; } cases[] = { @@ -143,7 +183,7 @@ static void test_encodings(void) { CHECK(n == (size_t)cases[i].n && bad == 0 && memcmp(buf, cases[i].bytes, n) == 0, "%s encodes to %d bytes, bad %d", mb_charset_name(cases[i].cs), (int)n, bad); uint16_t regs[8]; - CHECK(mb_encode_string(pl, 8, MB_O_ABCD, cases[i].cs, regs, NULL) == 0, "encode %s", mb_charset_name(cases[i].cs)); + CHECK(mb_encode_string(pl, 8, MB_O_ABCD, cases[i].cs, MB_FILL_NUL, regs, NULL) == 0, "encode %s", mb_charset_name(cases[i].cs)); char out[64]; mb_decode_string(regs, 8, MB_O_ABCD, cases[i].cs, out, sizeof(out)); CHECK(strcmp(out, pl) == 0, "%s round trip got '%s'", mb_charset_name(cases[i].cs), out); @@ -166,8 +206,8 @@ static void test_encodings(void) { CHECK(n == 3 && bad == 1 && first == 0xFFFD && memcmp(buf, "a?b", 3) == 0, "invalid UTF-8 input"); /* The byte length counts against the registers: 6 characters, 10 bytes */ uint16_t regs[5]; - CHECK(mb_encode_string(pl, 4, MB_O_ABCD, MB_CS_UTF8, regs, NULL) == -1, "utf-8 too long for 4 registers"); - CHECK(mb_encode_string(pl, 5, MB_O_ABCD, MB_CS_UTF8, regs, NULL) == 0, "utf-8 fits 5 registers"); + CHECK(mb_encode_string(pl, 4, MB_O_ABCD, MB_CS_UTF8, MB_FILL_NUL, regs, NULL) == -1, "utf-8 too long for 4 registers"); + CHECK(mb_encode_string(pl, 5, MB_O_ABCD, MB_CS_UTF8, MB_FILL_NUL, regs, NULL) == 0, "utf-8 fits 5 registers"); char out[32]; uint16_t raw[2] = { 0x41C5, 0x0000 }; /* 'A' then a lone UTF-8 lead byte */ @@ -322,12 +362,19 @@ static void test_validation(void) { valid(mb_validate_write, "{\"data_type\":\"string\",\"length\":8,\"encoding\":\"ascii\"," "\"value\":\"Za\xC5\xBC\"}", "can't be written in ascii"); valid(mb_validate_write, "{\"register_type\":\"coil\",\"values\":[{\"register\":0,\"value\":1},{\"register\":1,\"value\":0}]}", NULL); + + /* Fill */ + valid(mb_validate_write, "{\"data_type\":\"string\",\"fill\":\"space_right\",\"value\":\"A\"}", NULL); + valid(mb_validate_write, "{\"values\":[{\"register\":0,\"type\":\"string\",\"fill\":\"space_center\",\"value\":\"A\"}]}", NULL); + valid(mb_validate_write, "{\"data_type\":\"string\",\"fill\":\"spaces\",\"value\":\"A\"}", "unknown fill"); + valid(mb_validate_write, "{\"data_type\":\"string\",\"length\":2,\"fill\":\"space_left\",\"value\":\"HELLO\"}", "text is 5 bytes"); } int main(void) { test_orders(); test_round_trip(); test_strings(); + test_fill(); test_encodings(); test_plans(); test_scaling(); diff --git a/tools/scheduler_test.c b/tools/scheduler_test.c new file mode 100644 index 0000000..f61be30 --- /dev/null +++ b/tools/scheduler_test.c @@ -0,0 +1,110 @@ +/* Tests for the Day/Night window: offsets, windows that cross midnight, + * time zones far from their longitude, and polar day/night. Builds + * app/engine/scheduler.c with a fixed clock and without the ACAP runtime. */ + +#define _GNU_SOURCE +#include +#include +#include + +#include "../app/cJSON.h" + +/* Keep the real ACAP.h (GLib, FastCGI) out; scheduler.c needs only these. */ +#define _ACAP_H_ +cJSON* ACAP_Get_Config(const char* service); +int ACAP_DEVICE_Seconds_Since_Midnight(void); + +static time_t fake_now; +static time_t fake_time(time_t* t) { if (t) *t = fake_now; return fake_now; } +#define time(x) fake_time(x) +#include "../app/engine/scheduler.c" +#undef time + +cJSON* ACAP_Get_Config(const char* service) { (void)service; return NULL; } +void EventLog_Syslog(int priority, const char* source, const char* fmt, ...) { + (void)priority; (void)source; (void)fmt; +} +int ACAP_DEVICE_Seconds_Since_Midnight(void) { + struct tm* t = localtime(&fake_now); + return t->tm_hour * 3600 + t->tm_min * 60 + t->tm_sec; +} + +static int failures; + +static void set_clock(const char* tz, int y, int mo, int d, int sod) { + setenv("TZ", tz, 1); + tzset(); + struct tm tm = {0}; + tm.tm_year = y - 1900; tm.tm_mon = mo - 1; tm.tm_mday = d; + tm.tm_hour = sod / 3600; tm.tm_min = sod / 60 % 60; tm.tm_sec = sod % 60; + tm.tm_isdst = -1; + fake_now = mktime(&tm); +} + +static void check(const char* name, int got, int want) { + if (got != want) { + printf("FAIL %s: got %d, want %d\n", name, got, want); + failures++; + } +} + +/* Is it day at sod (local seconds) on the given date? */ +static int day_at(const char* tz, double lat, double lon, int y, int mo, int d, int sod, + int rise_off_min, int set_off_min) { + set_clock(tz, y, mo, d, sod); + return Scheduler_Is_Daytime(lat, lon, rise_off_min * 60, set_off_min * 60); +} + +int main(void) { + const char* sthlm = "Europe/Stockholm"; + const double sla = 59.3293, slo = 18.0686; + + /* Offsets move the boundaries to the second */ + set_clock(sthlm, 2026, 11, 26, 12 * 3600); + int rise = compute_solar_event(sla, slo, ASTRO_SUNRISE, fake_now); + int set = compute_solar_event(sla, slo, ASTRO_SUNSET, fake_now); + check("Stockholm sunrise is around 08:05", rise / 60, 8 * 60 + 5); + check("Stockholm sunset is around 15:04", set / 60, 15 * 60 + 4); + check("1 s before sunrise+60 is night", day_at(sthlm, sla, slo, 2026, 11, 26, rise + 3600 - 1, 60, -30), 0); + check("sunrise+60 is day", day_at(sthlm, sla, slo, 2026, 11, 26, rise + 3600, 60, -30), 1); + check("1 s before sunset-30 is day", day_at(sthlm, sla, slo, 2026, 11, 26, set - 1800 - 1, 60, -30), 1); + check("sunset-30 is night", day_at(sthlm, sla, slo, 2026, 11, 26, set - 1800, 60, -30), 0); + check("offsets that empty the day give night", day_at(sthlm, sla, slo, 2026, 11, 26, 12 * 3600, 720, -720), 0); + check("window of 24 h or more is day", day_at(sthlm, sla, slo, 2026, 6, 21, 3 * 3600, -720, 720), 1); + + /* A sunset offset past midnight keeps it day after 00:00 */ + check("sunset+120 in midsummer: 23:59 is day", day_at(sthlm, sla, slo, 2026, 6, 21, 23 * 3600 + 59 * 60, 0, 120), 1); + check("sunset+120 in midsummer: 00:05 is day", day_at(sthlm, sla, slo, 2026, 6, 22, 5 * 60, 0, 120), 1); + check("sunset+120 in midsummer: 01:00 is night", day_at(sthlm, sla, slo, 2026, 6, 22, 3600, 0, 120), 0); + + /* Local sunset after midnight without offsets (about 00:03) */ + const char* rvk = "Atlantic/Reykjavik"; + check("Reykjavik midsummer noon is day", day_at(rvk, 64.1466, -21.9426, 2026, 6, 21, 12 * 3600, 0, 0), 1); + check("Reykjavik midsummer 00:02 is day", day_at(rvk, 64.1466, -21.9426, 2026, 6, 22, 2 * 60, 0, 0), 1); + check("Reykjavik midsummer 01:00 is night", day_at(rvk, 64.1466, -21.9426, 2026, 6, 22, 3600, 0, 0), 0); + + /* UTC+13 at longitude -175: local noon is far from the UTC day */ + const char* tonga = "Pacific/Tongatapu"; + check("Tonga noon is day", day_at(tonga, -21.1394, -175.2049, 2026, 11, 26, 12 * 3600, 0, 0), 1); + check("Tonga 02:00 is night", day_at(tonga, -21.1394, -175.2049, 2026, 11, 26, 2 * 3600, 0, 0), 0); + check("Tonga 23:00 is night", day_at(tonga, -21.1394, -175.2049, 2026, 11, 26, 23 * 3600, 0, 0), 0); + + /* Polar night is night and midnight sun is day, whatever the offsets */ + const char* oslo = "Europe/Oslo"; + check("Tromso polar night noon is night", day_at(oslo, 69.6492, 18.9553, 2026, 12, 15, 12 * 3600, -720, 720), 0); + check("Tromso midnight sun 00:00 is day", day_at(oslo, 69.6492, 18.9553, 2026, 6, 21, 0, 720, -720), 1); + + /* Astronomical triggers still get wrapped times, -1 in polar night */ + set_clock(rvk, 2026, 6, 21, 12 * 3600); + check("Reykjavik sunset wraps to just after 00:00", + compute_solar_event(64.1466, -21.9426, ASTRO_SUNSET, fake_now) < 3600, 1); + set_clock(oslo, 2026, 12, 15, 12 * 3600); + check("no sunrise in polar night", compute_solar_event(69.6492, 18.9553, ASTRO_SUNRISE, fake_now), -1); + + if (failures) { + printf("%d failure(s)\n", failures); + return 1; + } + printf("all scheduler tests passed\n"); + return 0; +}