Skip to main content

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​

  1. Console QuickEdit Protection: On startup, the script invokes disable_console_quickedit() using the Windows Win32 API (kernel32.SetConsoleMode). This removes ENABLE_QUICK_EDIT_MODE (0x0040), preventing accidental terminal clicks or text selections in the Command Prompt window from freezing the Python process.
  2. 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.
  3. 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.
  4. 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).
  5. 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.
  6. Heartbeat Health Monitoring: Every 10 minutes (HEARTBEAT_INTERVAL), if no other sync activity has occurred, the script transmits a heartbeat ping to api/sage/heartbeat with current file signatures. Shelter flags a system alert if no communication is received within 30 minutes.
  7. 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.json and output/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": []
}
SettingTypeDescription
site_urlstringBase URL of the Shelter API (ending with /).
file_pathstringDirectory path where SAGE exports the CSV files.
sales_file_namestringFilename of the active/current sales order export (SEISalesOrder.csv).
historical_file_namestringFilename of the historical sales order export (SEIHistoricalExport.csv).
api_keystringSecret Bearer authorization token.
controllerstringBase API route prefix (default: sage).
functionstringEndpoint action for order batch imports (import_orders).
census_functionstringEndpoint action for open order census reconciliation (sync_complete).
batch_sizeintegerMaximum number of orders sent in a single HTTP POST request (default: 200).
sales_headersarrayExpected column names in the active sales CSV.
historical_headersarrayExpected column names in the historical sales CSV.
escape_item_codesarrayList 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 via SageDataImporter, upserts Sales_order_model records, 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 items array to generate distinct job tickets across different specialized database tables (like Eifs_job_model, Prepuff_job_model, etc.) based on the product_line logic 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​

  1. Console QuickEdit Protection: On startup, the script invokes disable_console_quickedit() using the Windows Win32 API (kernel32.SetConsoleMode). This removes ENABLE_QUICK_EDIT_MODE (0x0040) while preserving ENABLE_EXTENDED_FLAGS (0x0080), preventing mouse clicks inside the console window from suspending Python execution.
  2. Dynamic Daily FTP Download: Every polling cycle (read_interval, default 60 seconds), create_script_command_file() generates ftp_commands.txt formatted 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.txt and Alarm_YYMMDD.txt).
  3. Memory-Safe UTF-16 Parsing: read_file() parses the UTF-16 tab-delimited files, extracting Date and PSEUDOCENTEMP from the trend log and Date and Message from 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, and gc.collect() reclaims memory after each run.
  4. Chunked Streaming with Exponential Backoff: post_data() streams records in batches (default 200 items via generator stream_chunks()) using a persistent requests.Session() with Bearer token authentication. If the server returns HTTP 429 (rate limited) or HTTP 5xx (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.
  5. Cycle Interval Sleep: The script sleeps for the configured read_interval seconds 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
}
SettingTypeDescription
site_urlstringBase URL of the Shelter web application (ending with /).
api_keystringBearer token validated by the API authorization layer.
controllerstringBase route path for temperature endpoints (typically api/temperature).
temp_functionstringEndpoint action for temperature readings (import_temps).
alarm_functionstringEndpoint action for alarm logs (import_alarms).
ftp_hoststringIP address or hostname of the PLC / USB logger.
ftp_userstringUsername for FTP login on the logger.
ftp_passwordstringPassword for FTP login on the logger.
download_pathstringLocal filesystem path where FTP files are saved.
read_intervalintegerWait time in seconds between polling cycles (e.g. 60).
batch_sizeintegerNumber of records sent per HTTP POST request (default 200).
batch_delayfloatSeconds to wait between successive batches (default 1.0).
max_retriesintegerMaximum retry attempts per batch upon server or network error (default 5).
initial_backofffloatBase 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: Validates Date and numeric PSEUDOCENTEMP values, storing them in the temperature database table inside an Eloquent database transaction (Capsule::transaction). Idempotent lookups ensure existing readings for the same timestamp are safely updated without duplication.
  • import_alarms: Validates Date and Message. 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 in Notification_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 PSEUDOCENTEMP key is renamed and stored as temp in the Temperature_model database table.
  • Alarm data is not stored in a dedicated alarms table. Instead, it is stored generically in the Notification_model table.
  • The Message transmitted 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​

  1. Initialization: The script loads configuration variables from config.json and attempts to connect to the physical scale via a USB serial port.
  2. GUI Display: A full-screen Tkinter interface is launched to display the current weight and bag number to the operator.
  3. Continuous Monitoring: The script operates in an infinite loop, continuously polling the scale via serial communication every 3 seconds.
  4. 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).
  5. Transmission: A JSON payload containing the station, weight, unit, and scale configuration is sent via HTTP POST to the Shelter application.
  6. 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_bag function) 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_num identifier (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​

  1. QuickEdit Mode Disabling: On startup, the script invokes Win32 API functions via ctypes to disable Windows Console QuickEdit mode. This prevents operators or plant personnel from accidentally clicking in the command prompt window and freezing the process.
  2. Initial Heartbeat: Sends an immediate POST request to /api/preexpand/heartbeat with the file's modification time, notifying the Shelter server that the daemon is online.
  3. 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 in state/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).
  4. File Monitoring & Stabilization: Checks the active CSV file's stat signature (mtime, size) every sleep_time seconds (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.
  5. 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 against state/sent_expansions.json, and POSTs only new or modified expansion records in batches (batch_size, default 100). If a batch is rejected with HTTP 400/422, it is split in half to isolate the invalid record and quarantine it in state/failed_expansions.json so valid records still sync. Auth, config, rate-limit (401/403/404/429), 5xx, and network errors are not quarantined and are retried automatically.
  6. 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).
  7. Periodic Heartbeats: During idle periods with no new expansions, the script sends a heartbeat to /api/preexpand/heartbeat every heartbeat_interval seconds (default 300s / 5 minutes) so the Shelter Admin Dashboard knows the daemon is alive.
  8. 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/ or http://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 via kernel32.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 as import_preexp_data): Accepts grouped silo expansions. Validates timestamps, silo machine labels, and material codes. Matches or creates records in preexp_job, links consumed raw material lots from Lot_model, marks bags as expanded, and returns updated available inventory. Automatically invokes PreexpSyncStatus::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 the last_contact_at timestamp in the preexp_sync_status database table.
  • GET /api/preexpand/status (and CLI php 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/status and preexpand_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.

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_num string identifier (e.g., "1") is converted to an actual database relation (silo_id) referencing the Silo_model.
  • The date and time values sent in the payload are ignored by the server. Only silo_start and silo_end are utilized (stored as start_time and end_time in the Preexp_job_model).
  • The lots array 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 via bag_id_1, bag_id_2, and bag_id_3 columns.
  • The server generates its own internal key_string to 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​

  1. QuickEdit Mode Disabling: On startup, the script disables Windows Console QuickEdit mode via ctypes.windll.kernel32.SetConsoleMode to guarantee that mouse clicks inside the command window do not pause execution.
  2. Initial Heartbeat: Sends an immediate POST request to /api/mold/heartbeat with the file's modification timestamp, notifying the Shelter server that the daemon is online.
  3. Startup Processing: Parses the current month's mold .dat file (e.g., 202610.dat). If blocks exist, it structures the data, saves a local JSON backup under json_files/, and posts the blocks in chunks to /api/mold/import_mold_data.
  4. File Monitoring & Hash Detection: Continuously monitors the active .dat file using SHA3-512 hashing every sleep_time seconds (default 30s). When changes are detected, it switches to a 10s polling interval until file writing concludes.
  5. Periodic Heartbeats: During idle operational periods when no blocks are produced, the script dispatches a heartbeat to /api/mold/heartbeat every heartbeat_interval seconds (default 300s / 5 minutes) to keep the Admin Dashboard health badge green.
  6. 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.
  7. 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/ or http://localhost/).
  • mold_file_path: Directory path where the machine exports monthly .dat files.
  • 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 .dat export 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 via kernel32.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 with import_data): Receives block arrays in chunks of 50. Performs validation on dimensions, weights, and density labels. Creates or updates records in block (Block_model), links the blocks to silo models via raw_silo and ground_silo, and invokes intelligent FIFO material consumption tracking (calculate_block_material_consumption). Automatically updates mold_sync_status with the import timestamp and block count.
  • POST /api/mold/heartbeat: Receives background liveness pings and optional file modification timestamps from the daemon. Updates the last_contact_at timestamp in the mold_sync_status database table.
  • GET /api/mold/status (and CLI php 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/status and block_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.