Virtual Machine Functions
SAGE Script
The SAGE Script (shelter-sage-app) mirrors SAGE 100 sales orders to the Shelter web application. It runs as an automated background service on the plant's Windows VM, monitoring active and historical sales export files and synchronizing changes via authenticated REST API calls.
For details on SAGE 100 ERP configuration, Visual Integrator exports, and table schemas, see the SAGE Documentation.
Application Workflow
- Console QuickEdit Protection: On startup, the script invokes
disable_console_quickedit()using the Windows Win32 API (kernel32.SetConsoleMode). This removesENABLE_QUICK_EDIT_MODE (0x0040), preventing accidental terminal clicks or text selections in the Command Prompt window from freezing the Python process. - File Signature & Stability Detection: The scheduler loop wakes every 60 seconds (
TICK_SECONDS). Rather than reading files that are actively being exported by SAGE ERP,wait_until_stable()verifies that the file size and modification time remain constant across multiple checks before attempting to read. - Fingerprint & Delta-Only Syncing: The script maintains local persistent state in
state/by hashing individual orders. It only transmits orders that are brand new or have modified contents since the last sync. Unchanged orders are completely skipped, dramatically reducing network traffic, server CPU usage, and database queries. - Resilient Batch Transmission: Orders are parsed into structured JSON and sent in manageable chunks (default 200 orders) using a persistent
requests.Session()with Bearer authentication. Failed requests automatically retry using progressive backoff delays (5s,15s,45s). - Open Order Census Reconciliation: After synchronizing active orders, the script compiles a complete list of all currently open orders (
open_orders) and posts it to the census endpoint (api/sage/sync_complete). Shelter compares this against its database to safely identify deleted or completed orders:- Orders missing for two consecutive syncs are marked as archived (never hard deleted).
- Safety Safeguard: If a census drops by more than 10% (
CENSUS_MAX_DROP = 0.9) or would archive over 200 orders, Shelter rejects the census and triggers a "SAGE Error" notification to protect against truncated or incomplete exports.
- Heartbeat Health Monitoring: Every 10 minutes (
HEARTBEAT_INTERVAL), if no other sync activity has occurred, the script transmits a heartbeat ping toapi/sage/heartbeatwith current file signatures. Shelter flags a system alert if no communication is received within 30 minutes. - Scheduled Full Resync: As a safety net to clear drift, the script automatically triggers a full resync once a week (
FULL_RESYNC_INTERVAL = 7 days), re-evaluating every order regardless of local state.
Command-Line Arguments
The script supports command-line flags for administrative and maintenance tasks:
python main.py [OPTIONS]
--full: Forces an immediate full resync of every order (bypassing local hash state), then resumes continuous monitoring.--once: Executes a single synchronization cycle for current and historical exports, then immediately exits.--debug-dump: Writes full parsed order JSON objects to local disk (output/sales_data.jsonandoutput/historical_sales_data.json) for inspection.
Configuration
The script reads its settings from settings.json located in its root directory:
{
"site_url": "https://shelter-enterprises.app/api/",
"file_path": "C:\\Sage\\Exports\\",
"sales_file_name": "SEISalesOrder.csv",
"historical_file_name": "SEIHistoricalExport.csv",
"api_key": "YOUR_SECRET_API_KEY",
"controller": "sage",
"function": "import_orders",
"census_function": "sync_complete",
"batch_size": 200,
"sales_headers": [...],
"historical_headers": [...],
"escape_item_codes": []
}
| Setting | Type | Description |
|---|---|---|
site_url | string | Base URL of the Shelter API (ending with /). |
file_path | string | Directory path where SAGE exports the CSV files. |
sales_file_name | string | Filename of the active/current sales order export (SEISalesOrder.csv). |
historical_file_name | string | Filename of the historical sales order export (SEIHistoricalExport.csv). |
api_key | string | Secret Bearer authorization token. |
controller | string | Base API route prefix (default: sage). |
function | string | Endpoint action for order batch imports (import_orders). |
census_function | string | Endpoint action for open order census reconciliation (sync_complete). |
batch_size | integer | Maximum number of orders sent in a single HTTP POST request (default: 200). |
sales_headers | array | Expected column names in the active sales CSV. |
historical_headers | array | Expected column names in the historical sales CSV. |
escape_item_codes | array | List of ERP item codes to filter out during parsing. |
Python Dependencies
requests: Manages HTTP sessions, Keep-Alive connections, and REST API calls.hashlib: Generates SHA-256 hashes of orders for fingerprint and delta tracking.csv: Streams and parses tab-delimited or comma-delimited export files.json: Serializes nested order payloads and manages local state files.logging&logging.handlers: Provides console logging and daily midnight rotating files (logs/log-YYYY-MM-DD.txt) with 7-day retention.ctypes: Interfaces directly with the Windows Win32 API (kernel32.dll) to disable console QuickEdit mode.time/datetime: Manages scheduling ticks, intervals, and timestamp formatting.
Shelter Application Integration
The Python script communicates directly with App\Controllers\Api\Sage in the Shelter web application:
import_orders: Accepts batches of grouped orders. It validates historical vs. active order structures, resolves data conflicts viaSageDataImporter, upsertsSales_order_modelrecords, and creates or updates shop floor job tickets (e.g. EIFS, Pre-Puff, Sill Seal, Pool Steps) based on item product lines.sync_complete: Processes the open orders census to detect missing orders and safely manage archiving without hard deletions.heartbeat: Updates the last-seen timestamp and file signature tracking in Shelter.
Data Transmission & Storage
Transmitted Payload:
The Python script sends JSON data in batches grouped by sales_order_number:
{
"is_historical": 0,
"data": {
"123456": {
"order_info": {
"status": "O",
"type": "S",
"order_date": "10/24/2026"
},
"customer_info": {
"customer_po_number": "PO-999",
"billing_address": {
"name": "Customer Name",
"street1": "123 Billing St",
"street2": "",
"city": "Cityville",
"state": "NY",
"zipcode": "12345"
},
"shipping_address": {
"name": "Customer Name",
"street1": "123 Shipping St",
"street2": "",
"city": "Cityville",
"state": "NY",
"zipcode": "12345"
}
},
"items": [
{
"item_code": "EF1",
"item_code_description": "EIFS Block",
"item_type": "1",
"unit_of_measurement": "EACH",
"quantity": "50",
"unit_price": "10.00",
"unit_cost": "5.00",
"extension_amount": "500.00",
"product_line": "EIFS"
}
]
}
}
}
Storage Discrepancies:
- The transmitted JSON dictionary groups all rows by their
sales_order_number. - Instead of just saving the data verbatim, the server parses the
itemsarray to generate distinct job tickets across different specialized database tables (likeEifs_job_model,Prepuff_job_model, etc.) based on theproduct_linelogic mapping. - Cost attributes and completion dates are continually reconciled against the ERP data, so the Shelter application's database mirrors the active truth of the SAGE server.
Temperature Script
The Temperature Script (temp_sensor) monitors environmental curing conditions and equipment alarms by reading data from an FTP-enabled PLC logger and synchronizing it with the Shelter web application.
For detailed operational runbooks and PLC configuration, see the Temperature Documentation.
Application Workflow
- Console QuickEdit Protection: On startup, the script invokes
disable_console_quickedit()using the Windows Win32 API (kernel32.SetConsoleMode). This removesENABLE_QUICK_EDIT_MODE (0x0040)while preservingENABLE_EXTENDED_FLAGS (0x0080), preventing mouse clicks inside the console window from suspending Python execution. - Dynamic Daily FTP Download: Every polling cycle (
read_interval, default 60 seconds),create_script_command_file()generatesftp_commands.txtformatted for the PLC's directory structure (/USB_Pen_Memory/Log/). It downloads the current day's log files using a 2-digit year timestamp (Temperature Trend_Center_YYMMDD.txtandAlarm_YYMMDD.txt). - Memory-Safe UTF-16 Parsing:
read_file()parses the UTF-16 tab-delimited files, extractingDateandPSEUDOCENTEMPfrom the trend log andDateandMessagefrom the alarm log. Timestamps (HH:MM:SS MM-DD-YYYY) are normalized to standard SQL format (YYYY-MM-DD HH:MM:SS). Header lists are recycled to prevent memory growth leaks, andgc.collect()reclaims memory after each run. - Chunked Streaming with Exponential Backoff:
post_data()streams records in batches (default 200 items via generatorstream_chunks()) using a persistentrequests.Session()with Bearer token authentication. If the server returns HTTP429(rate limited) or HTTP5xx(500, 502, 503, 504), or if network drops occur, the script automatically retries up to 5 times with progressive exponential backoff (backoff = initial_backoff * attempt). An inter-batch delay (batch_delay) paces requests to prevent web server throttling. - Cycle Interval Sleep: The script sleeps for the configured
read_intervalseconds before beginning the next check.
Configuration
The script reads its parameters from settings.json located in its root directory:
{
"site_url": "https://shelter-enterprises.app/",
"api_key": "YOUR_SECRET_API_KEY",
"controller": "api/temperature",
"temp_function": "import_temps",
"alarm_function": "import_alarms",
"ftp_host": "192.168.1.100",
"ftp_user": "plc_user",
"ftp_password": "plc_password",
"download_path": "C:\\temp_sensor\\downloads",
"read_interval": 60,
"batch_size": 200,
"batch_delay": 1.0,
"max_retries": 5,
"initial_backoff": 5.0
}
| Setting | Type | Description |
|---|---|---|
site_url | string | Base URL of the Shelter web application (ending with /). |
api_key | string | Bearer token validated by the API authorization layer. |
controller | string | Base route path for temperature endpoints (typically api/temperature). |
temp_function | string | Endpoint action for temperature readings (import_temps). |
alarm_function | string | Endpoint action for alarm logs (import_alarms). |
ftp_host | string | IP address or hostname of the PLC / USB logger. |
ftp_user | string | Username for FTP login on the logger. |
ftp_password | string | Password for FTP login on the logger. |
download_path | string | Local filesystem path where FTP files are saved. |
read_interval | integer | Wait time in seconds between polling cycles (e.g. 60). |
batch_size | integer | Number of records sent per HTTP POST request (default 200). |
batch_delay | float | Seconds to wait between successive batches (default 1.0). |
max_retries | integer | Maximum retry attempts per batch upon server or network error (default 5). |
initial_backoff | float | Base backoff multiplier in seconds for retry delays (default 5.0). |
Python Dependencies
requests: Sends authenticated HTTP POST requests in persistent sessions.codecs: Reads UTF-16 tab-delimited sensor log files without corruption.csv: Parses tabular temperature and alarm readings.logging&logging.handlers: Manages console output and daily rotating logs (logs/log-YYYY-MM-DD.txt) with a 7-day retention limit.ctypes: Interfaces with Windows kernel32 to disable console QuickEdit mode.time/datetime: Formats timestamps and manages backoff/polling delays.os/sys/gc: Manages file I/O, invokes FTP commands, and performs explicit garbage collection.
Shelter Application Integration
The script integrates with App\Controllers\Api\Temperature in the Shelter web application:
import_temps: ValidatesDateand numericPSEUDOCENTEMPvalues, storing them in thetemperaturedatabase table inside an Eloquent database transaction (Capsule::transaction). Idempotent lookups ensure existing readings for the same timestamp are safely updated without duplication.import_alarms: ValidatesDateandMessage. To give operators actionable context, the controller queries the database for the closest recorded temperature reading at the moment the alarm occurred, appends it to the alarm text (e.g.Alarm text<br><br>Current Temperature: 78.5), and creates a "Temp Alarm" notification record inNotification_model.get&get_last_24_hours: Power the frontend dashboard, providing the latest reading (with server-side calculated age) and 24-hour smoothed 30-minute averages.
Data Transmission & Storage
Transmitted Payload: The Python script sends JSON data in batches:
{
"temperatures": [
{
"Date": "YYYY-MM-DD HH:MM:SS",
"PSEUDOCENTEMP": "72.5"
}
],
"alarms": [
{
"Date": "YYYY-MM-DD HH:MM:SS",
"Message": "Alarm description"
}
]
}
Storage Discrepancies:
- The
PSEUDOCENTEMPkey is renamed and stored astempin theTemperature_modeldatabase table. - Alarm data is not stored in a dedicated alarms table. Instead, it is stored generically in the
Notification_modeltable. - The
Messagetransmitted from the alarm is modified before storage; the server appends the closest chronological temperature reading to the end of the text (e.g.,Alarm description<br><br>Current Temperature: 72.5).
Scales Script
[!WARNING] DEPRECATED: The Scale Script (
shelter-ent-scale-app) is the only deprecated script across the facility because the Pre-puff manufacturing process is currently not being run/used. All other Python scripts (SAGE Sync, Temperature Sensor, Pre-Expander, and Mold) are active production services. The documentation below is retained for legacy and historical reference.
The Scale Script (shelter-ent-scale-app) is a Python application that reads weights directly from a connected serial scale and transmits the data to the Shelter web application. It features a full-screen GUI designed to run on a Raspberry Pi to provide visual feedback to operators.
Application Workflow
- Initialization: The script loads configuration variables from
config.jsonand attempts to connect to the physical scale via a USB serial port. - GUI Display: A full-screen Tkinter interface is launched to display the current weight and bag number to the operator.
- Continuous Monitoring: The script operates in an infinite loop, continuously polling the scale via serial communication every 3 seconds.
- Data Processing: Upon receiving a valid, non-negative weight reading, it parses the string for weight and unit. It will automatically convert pound/ounce (
lboz) formats to purely pounds (lb). - Transmission: A JSON payload containing the station, weight, unit, and scale configuration is sent via HTTP POST to the Shelter application.
- Feedback: The server responds with either a bag number (success) or an error. The Tkinter GUI updates its display color and text based on the response.
Configuration
A config.json file is required in the same directory. Keys include:
site_url: The base URL of the Shelter web application.api_key: Authorization bearer token.station: Identifier for the physical station where the scale is located (e.g., "Downstairs").scale: Numeric identifier for the scale.controller: The API controller path (e.g.,api).function: The specific function endpoint (e.g.,scan_bag).
Python Dependencies
pyserial: Handles USB serial communication with the scale hardware.numpy: Used for array manipulation during weight string parsing.requests: Sends POST requests to the Shelter web application.json: Parses the API response.Tkinter: Generates the full-screen visual GUI for operators.logging: Records interactions to standard output and rotating daily log files.socket: Performs basic connectivity checks (e.g., pinging Google).
Data Transmission & Storage
Transmitted Payload: The Python script sends the following flat data via an HTTP POST request:
{
"station": "Downstairs",
"weight": 105.5,
"unit": "lb",
"scale": "1"
}
Storage Discrepancies:
- The transmitted data is processed by the server (e.g., via the
scan_bagfunction) to log a finished bag for an ongoing job at the specified station. - The server does not merely store this payload verbatim; it creates a bag record in the database related to an active job.
- The server responds with the newly generated
bag_numidentifier (e.g.,{"bag_num": 123}), which is not part of the transmitted payload but is displayed on the local Raspberry Pi screen. If no job is active, the server returns an error.
Pre-Expander Script
The Pre-Expander Script (shelter-preexp-app) is an active production daemon that monitors CSV files exported by EPS bead pre-expansion equipment, parses batch expansion runs, synchronizes lot consumption with the Shelter database, and reports periodic heartbeats to ensure operational health.
Application Workflow
- QuickEdit Mode Disabling: On startup, the script invokes Win32 API functions via
ctypesto disable Windows Console QuickEdit mode. This prevents operators or plant personnel from accidentally clicking in the command prompt window and freezing the process. - Initial Heartbeat: Sends an immediate POST request to
/api/preexpand/heartbeatwith the file's modification time, notifying the Shelter server that the daemon is online. - Startup Full Sync: Parses the current month's CSV export (e.g.,
YYYY_MM_PJX.csv) from the machine directory and performs a full sync (force=True) to/api/preexpand/import_preexp_data, recording every accepted expansion hash instate/sent_expansions.json. Optional CLI flags include--no-full-on-start(skip the initial full send and use local state immediately) and--once(run a single sync cycle and exit). - File Monitoring & Stabilization: Checks the active CSV file's stat signature (
mtime,size) everysleep_timeseconds (default 30s). When a change is detected, it polls every 10s until the file stops changing and confirms with a SHA3-512 hash before parsing. - Delta Sync, Batching & Quarantine: On subsequent file changes, the script writes a local JSON snapshot (
output/silo.json), compares each row's key (silo|date|time|silo_start) and SHA-1 payload hash againststate/sent_expansions.json, and POSTs only new or modified expansion records in batches (batch_size, default100). If a batch is rejected with HTTP400/422, it is split in half to isolate the invalid record and quarantine it instate/failed_expansions.jsonso valid records still sync. Auth, config, rate-limit (401/403/404/429),5xx, and network errors are not quarantined and are retried automatically. - Verbose HTTP/HTTPS Error Logging: All failed HTTP/HTTPS requests (including heartbeats) log structured diagnostics: HTTP status code and reason phrase, request URL, attempt count and retry delay, elapsed time in ms, payload byte size, diagnostic response headers (
Content-Type,Server,Location,WWW-Authenticate,Retry-After,X-Request-Id,CF-Ray), actionable status hints, response body, and specific TLS/timeout exception details (SSLError,ConnectTimeout,ReadTimeout,ConnectionError). - Periodic Heartbeats: During idle periods with no new expansions, the script sends a heartbeat to
/api/preexpand/heartbeateveryheartbeat_intervalseconds (default 300s / 5 minutes) so the Shelter Admin Dashboard knows the daemon is alive. - Daily Graceful Restart: At 11:59 PM, the script cleanly exits to allow daily log rotation (
logs/log-YYYY-MM-DD.txt) and memory cleanup. Windows Task Scheduler or the Startup folder relaunches the script.
Configuration
The settings.json file (gitignored; create locally from example.settings.json) controls script operation:
site_url: The base URL of the Shelter web application (e.g.,https://dev.shelter-ent.app/index.php/orhttp://localhost/).file_path: Directory path where the pre-expander machinery exports CSV files.data_folder: Directory for storing local output files (e.g., JSON backups).api_key: Authorization bearer token for the API.controller: The API controller path (default:"api/preexpand").function: The API function endpoint (default:"import_preexp_data"or"import_data").sleep_time: Polling interval in seconds between file change checks (default:30).heartbeat_interval: Interval in seconds between background heartbeat pings sent to the server (default:300).batch_size: Maximum number of expansion records sent per HTTP POST request (default:100).headers: An array of strings defining expected CSV column names (date,time,silo_num,silo_start,silo_end,code,lot_num_1,bag_num_1, etc.).
Python Dependencies
ctypes: Native Windows API interface used to disable console QuickEdit mode viakernel32.SetConsoleMode.csv: Parses tab-delimited pre-expander equipment exports (dialect="excel-tab").hashlib: Computes SHA3-512 file hashes to detect file modification and write stabilization.json: Serializes data payloads for API communication and local state storage.logging/logging.handlers: Manages midnight-rotating log files (TimedRotatingFileHandler) and stdout streaming.requests: Sends authenticated HTTP POST requests with bearer token authorization.time/datetime: Manages polling cycles, timestamps, and 11:59 PM daily restart detection.
Shelter Application Integration
The Python script communicates with App\Controllers\Api\Preexpand in the Shelter web application across several endpoints:
POST /api/preexpand/import_data(aliased asimport_preexp_data): Accepts grouped silo expansions. Validates timestamps, silo machine labels, and material codes. Matches or creates records inpreexp_job, links consumed raw material lots fromLot_model, marks bags as expanded, and returns updated available inventory. Automatically invokesPreexpSyncStatus::record(...)with the current timestamp and job count.POST /api/preexpand/heartbeat: Receives background liveness pings and optional file modification timestamps from the daemon. Updates thelast_contact_attimestamp in thepreexp_sync_statusdatabase table.GET /api/preexpand/status(and CLIphp public/index.php api/preexpand/status): Returns a JSON summary of synchronization health:{
"state": "healthy",
"seconds_ago": 12,
"minutes_since_contact": 0,
"duration_since_contact": "0m",
"stale_after": 30,
"last_contact_at": "2026-10-11 18:38:23",
"last_import_at": "2026-10-11 17:15:00",
"date_label": "Oct 11, 6:38 PM",
"file_modified": null
}- Admin Dashboard Integration (
/admin): The Pre-Expansion card on the executive/admin dashboard queries/api/preexpand/statusandpreexpand_helper. It displays:- Last synced: Humanized age string (e.g.
Last synced: Oct 11, 6:38 PM (just now)). - Health Badge: Toggles between Healthy (green) and Stalled (red) if more than 30 minutes elapse without contact, matching the SAGE and Temperature cards.
- Last synced: Humanized age string (e.g.
Data Transmission & Storage
Transmitted Payload: The Python script sends JSON data grouped by silo numbers. The payload structure is:
{
"silos": {
"1": {
"expansions": [
{
"date": "MM/DD/YYYY",
"time": "HH:MM:SS AM",
"silo_start": "MM/DD/YYYY HH:MM:SS AM",
"silo_end": "MM/DD/YYYY HH:MM:SS AM",
"code": "A123",
"lots": [
{ "lot": "LOT_NAME", "bag": "123" },
{ "lot": "LOT_NAME", "bag": "124" },
{ "lot": "LOT_NAME", "bag": "125" }
]
}
]
}
}
}
Storage Discrepancies:
- The flat
silo_numstring identifier (e.g.,"1") is converted to an actual database relation (silo_id) referencing theSilo_model. - The
dateandtimevalues sent in the payload are ignored by the server. Onlysilo_startandsilo_endare utilized (stored asstart_timeandend_timein thePreexp_job_model). - The
lotsarray is not stored verbatim. Instead, the server finds the corresponding lot entries in the inventory (Lot_model) and links their database IDs to the job viabag_id_1,bag_id_2, andbag_id_3columns. - The server generates its own internal
key_stringto uniquely identify each job, which is not part of the transmitted payload.
Mold Script
The Mold Script (shelter-ent-mold-app) is an active production daemon that monitors monthly block molding machine export files (YYYYMM.dat), parses dimensional and density measurements, tracks raw material lot consumption, posts batches to the Shelter API, and sends recurring heartbeats to report machine and daemon operational health.
Application Workflow
- QuickEdit Mode Disabling: On startup, the script disables Windows Console QuickEdit mode via
ctypes.windll.kernel32.SetConsoleModeto guarantee that mouse clicks inside the command window do not pause execution. - Initial Heartbeat: Sends an immediate POST request to
/api/mold/heartbeatwith the file's modification timestamp, notifying the Shelter server that the daemon is online. - Startup Processing: Parses the current month's mold
.datfile (e.g.,202610.dat). If blocks exist, it structures the data, saves a local JSON backup underjson_files/, and posts the blocks in chunks to/api/mold/import_mold_data. - File Monitoring & Hash Detection: Continuously monitors the active
.datfile using SHA3-512 hashing everysleep_timeseconds (default 30s). When changes are detected, it switches to a 10s polling interval until file writing concludes. - Periodic Heartbeats: During idle operational periods when no blocks are produced, the script dispatches a heartbeat to
/api/mold/heartbeateveryheartbeat_intervalseconds (default 300s / 5 minutes) to keep the Admin Dashboard health badge green. - Data Parsing & Chunked Transmission: Parses tab-delimited block rows, maps dimensions, filters blocks with zero/unweighed metrics, writes local JSON backups, and transmits blocks in chunks of 50 to the Shelter web application.
- Daily Graceful Restart: At 11:59 PM, the script cleanly terminates to allow daily log rotation (
logs/log-YYYY-MM-DD.txt) and memory cleanup. Windows Task Scheduler or the Startup folder relaunches the script.
Configuration
The settings.json file controls script operation:
site_url: Base URL of the Shelter web application (e.g.,https://dev.shelter-ent.app/index.php/orhttp://localhost/).mold_file_path: Directory path where the machine exports monthly.datfiles.file_path: Directory path for storing local JSON backup files.controller: API controller endpoint path (default:"api/mold").function: API function endpoint (default:"import_mold_data"or"import_data").api_key: Authorization bearer token for the API.sleep_time: Polling interval in seconds between file checks (default:30).heartbeat_interval: Interval in seconds between background heartbeat pings (default:300).headers: Array of column names matching the mold machine's.datexport schema (time,date,density,block_num,height,depth,load_weight,weight,req_density,regrind,silo_density,block_density,stab_t,cycle_time,steam_time,raw_silo,raw_code,ground_silo,ground_code).
Python Dependencies
ctypes: Native Windows API interface used to disable console QuickEdit mode viakernel32.SetConsoleMode.csv: Parses tab-delimited equipment exports (dialect="excel-tab").hashlib: Computes SHA3-512 hashes to detect new machine output.json: Serializes block data for API calls and stores local JSON archives.logging/logging.handlers: Manages rotating daily log files (TimedRotatingFileHandler) and stdout streaming.requests: Sends authenticated HTTP POST requests with bearer token authorization.time/datetime: Manages polling cycles, timestamps, and 11:59 PM daily restart detection.
Shelter Application Integration
The Python script communicates with App\Controllers\Api\Mold in the Shelter web application:
POST /api/mold/import_mold_data(aliased withimport_data): Receives block arrays in chunks of 50. Performs validation on dimensions, weights, and density labels. Creates or updates records inblock(Block_model), links the blocks tosilomodels viaraw_siloandground_silo, and invokes intelligent FIFO material consumption tracking (calculate_block_material_consumption). Automatically updatesmold_sync_statuswith the import timestamp and block count.POST /api/mold/heartbeat: Receives background liveness pings and optional file modification timestamps from the daemon. Updates thelast_contact_attimestamp in themold_sync_statusdatabase table.GET /api/mold/status(and CLIphp public/index.php api/mold/status): Returns a JSON summary of synchronization health:{
"state": "healthy",
"seconds_ago": 8,
"minutes_since_contact": 0,
"duration_since_contact": "0m",
"stale_after": 30,
"last_contact_at": "2026-10-11 18:42:05",
"last_import_at": null,
"date_label": "Oct 11, 6:42 PM",
"file_modified": null
}- Admin Dashboard Integration (
/admin): The Mold card on the admin dashboard queries/api/mold/statusandblock_helper. It displays:- Blocks Created: Count of blocks produced today.
- Last synced: Humanized age string (e.g.,
Last synced: Oct 11, 6:42 PM (just now)). - Health Badge: Toggles between Healthy (green) and Stalled (red) if more than 30 minutes elapse without contact, matching the SAGE, Temperature, and Pre-Expansion cards.