Skip to content

[RTOP-49] Implement base code to commands#4

Merged
thiagoralves merged 32 commits into
developmentfrom
RTOP-49-Implement-base-code-to-Commands
Sep 16, 2025
Merged

[RTOP-49] Implement base code to commands#4
thiagoralves merged 32 commits into
developmentfrom
RTOP-49-Implement-base-code-to-Commands

Conversation

@lucasbutzke
Copy link
Copy Markdown
Contributor

@lucasbutzke lucasbutzke commented Sep 15, 2025

Summary by CodeRabbit

  • New Features

    • Initial PLC runtime with start/stop control, real-time cycle stats, and watchdog.
    • UNIX socket control interface and helper scripts.
    • HTTPS REST API with JWT auth, user management, runtime control, file upload, and status endpoints.
  • Chores

    • Docker image and run scripts, installation script, CMake build setup.
    • Pre-commit hooks, code formatting, editor settings, .gitignore, and dependency requirements.
  • Tests

    • Authentication and protected route tests with reusable fixtures.
  • Documentation

    • Updated project title and enabled structured logging.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Sep 15, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Initializes a full runtime stack: C-based PLC core with plugin loading, timing, logging, watchdog, and a UNIX socket control server; a Flask REST API with JWT auth and a Unix-socket client; build/tooling (CMake, Docker, pre-commit), scripts, and tests. Adds configs, types, and executable entry point.

Changes

Cohort / File(s) Summary of Changes
Build system & tooling
CMakeLists.txt, core/src/CMakeLists.txt
Adds CMake projects and targets to build plc_main with strict compiler flags, includes, and output directory.
Code style & editor
.clang-format, .vscode/settings.json
Introduces C/C formatting rules (LLVM-derived) and VSCode associations/formatter settings with format-on-save.
VCS hygiene
.gitignore
Adds ignore patterns for builds, generated code, IDE, venvs, caches, binaries, and temp files.
Pre-commit hooks
.pre-commit-config.yaml
Configures pylint, black, isort, ruff, mypy, clang-format, and generic hygiene hooks.
Containerization & setup
Dockerfile, install.sh, scripts/run-image.sh, scripts/build-docker-image.sh
Adds Debian-based Docker image, dependency install paths (docker/linux), container run script with RT caps, and image build helper.
Build/exec scripts
scripts/compile.sh, scripts/exec.sh, scripts/generate-gluevars.sh
Adds PLC shared-lib compilation, combined runtime+webserver executor, and gluevars generation helper.
Project docs
README.md
Updates title to “OpenPLC Runtime v4”.
Python deps
requirements.txt
Adds Flask, JWT, SQLAlchemy, cryptography, pytest, and pre-commit dependencies.
Core types
core/src/lib/iec_types.h
Introduces IEC primitive types, time structs, string type, and init macros.
Core utils: logging
core/src/plc_app/utils/log.h, core/src/plc_app/utils/log.c
Adds thread-safe logging API with levels and variadic functions.
Core utils: time/sched
core/src/plc_app/utils/utils.h, core/src/plc_app/utils/utils.c
Adds timespec normalization, sleep-until, diff, realtime priority, and tick globals.
Core utils: watchdog
core/src/plc_app/utils/watchdog.h, core/src/plc_app/utils/watchdog.c
Adds heartbeat monitor thread and init function; terminates on stalled heartbeat.
Scan cycle timing
core/src/plc_app/scan_cycle_manager.h, core/src/plc_app/scan_cycle_manager.c
Adds timing stats struct and start/end functions tracking scan/cycle/latency and overruns.
Plugin manager
core/src/plc_app/plcapp_manager.h, core/src/plc_app/plcapp_manager.c
Adds opaque manager to dlopen/dlsym/dlclose plugins and retrieve symbols.
I/O image binding
core/src/plc_app/image_tables.h, core/src/plc_app/image_tables.c
Declares buffers for IO/memory and initializes external plugin symbols, wiring buffer pointers.
PLC state machine
core/src/plc_app/plc_state_manager.h, core/src/plc_app/plc_state_manager.c
Adds PLC lifecycle with states, cycle thread, load/unload plugin, and transitions.
UNIX socket server
core/src/plc_app/unix_socket.h, core/src/plc_app/unix_socket.c
Adds AF_UNIX server handling PING/STATUS/START/STOP and delegating to PLC state APIs.
PLC entrypoint
core/src/plc_app/plc_main.c
Main program: sets logging, signal handling, watchdog, state manager, socket server, and stats thread.
Webserver: init
webserver/__init__.py
Sets module metadata and root logging configuration.
Webserver: config/env
webserver/config.py
Manages .env generation/validation and provides Dev/Prod config classes.
Webserver: credentials
webserver/credentials.py
Generates/validates self-signed TLS certificates (RSA 2048, SAN).
Webserver: REST API
webserver/restapi.py
Flask Blueprint with JWT auth, user management, token revocation, and pluggable GET/POST callbacks.
Webserver: Unix client
webserver/unixclient.py
Async Unix-domain client to send PING/START/STOP via validated messages and a command queue.
Webserver: app
webserver/app.py
HTTPS server, command dispatch to Unix client, file upload and compilation status routing, threads for server and socket client.
Testing setup
conftest.py
Pytest fixtures for Flask app, DB, JWT, client, and authenticated client wrapper.
API tests
test_api.py
Adds auth and protected endpoint tests with parametrized authenticated calls.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User/Client
  participant F as Flask REST API
  participant Q as Command Queue
  participant AC as Async Unix Client
  participant US as Unix Socket Server
  participant SM as PLC State Manager
  participant PM as Plugin Manager

  rect rgba(220,235,255,0.4)
  U->>F: HTTPS GET/POST (e.g., start-plc)
  F->>Q: enqueue("START")
  note right of F: JWT-authenticated routes
  end

  par Client Worker
    F->>AC: start_unix_socket_client()
    AC->>US: Connect /run/runtime/plc_runtime.socket
    loop While commands
      AC->>Q: dequeue()
      AC->>US: SEND: START/STOP/PING
      US-->>AC: RESP: START:OK/ERROR
    end
  and Runtime Control
    US->>SM: handle command
    alt START
      SM->>PM: load plugin, init symbols
      SM->>SM: start cycle thread
    else STOP
      SM->>SM: stop cycle thread
      SM->>PM: unload plugin
    else PING/STATUS
      SM-->>US: status
    end
  end
Loading
sequenceDiagram
  participant CT as Cycle Thread
  participant TM as Timing Manager
  participant WG as Watchdog

  CT->>TM: scan_cycle_time_start()
  CT->>CT: ext_config_run__(tick++)
  CT->>CT: ext_updateTime()
  CT->>TM: scan_cycle_time_end()
  CT->>CT: sleep_until(next_tick)
  WG-->>WG: Check heartbeat periodically
  WG->>WG: Exit on stall
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Poem

I nibbled wires, then pressed “build” with cheer,
A socket now whispers, “START” in my ear.
The PLC hums, the web sings along,
Watchdogs keep time with a tick-tock song.
In burrows of code, I hop, I compile—
Runtime is ready. Deploy with a smile! 🐇⚙️


Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands and usage tips.

@lucasbutzke lucasbutzke reopened this Sep 15, 2025
@lucasbutzke lucasbutzke changed the base branch from main to development September 15, 2025 19:01
@thiagoralves thiagoralves merged commit ff9eec8 into development Sep 16, 2025
1 check passed
@thiagoralves thiagoralves deleted the RTOP-49-Implement-base-code-to-Commands branch September 16, 2025 17:55
devin-ai-integration Bot added a commit that referenced this pull request Oct 9, 2025
This change migrates the certificate generation from the Python Cryptography
library to OpenSSL CLI commands, following the same approach as PR #4 in the
OpenPLC_v3 repository.

Key changes:
- Replaced credentials.py to use subprocess calls to OpenSSL instead of cryptography library
- Upgraded from RSA 2048-bit to 4096-bit keys for enhanced security
- Increased certificate validity from 365 days to 36500 days (~100 years)
- Removed cryptography dependency from requirements.txt
- Added platform detection to app.py: HTTPS on Linux, HTTP on other platforms
- Maintained same CertGen class interface for backward compatibility

Benefits:
- OpenSSL is universally available on Linux systems
- No complex Python library dependencies
- Stronger security with 4096-bit keys
- Cross-platform compatibility with HTTP fallback for non-Linux systems

Implements the same changes as:
- OpenPLC_v3 PR #4: Autonomy-Logic/OpenPLC_v3#4
- Commits: 1b82973, b3a1e65

Requested by: Thiago Alves (@thiagoralves)
Devin run: https://app.devin.ai/sessions/7734798dc74e4823ab03bc8402ba6cfa

Co-Authored-By: Thiago Alves <thiagoralves@gmail.com>
thiagoralves added a commit that referenced this pull request Mar 5, 2026
- Fix #2: Guard buffer mutex release after crash with a volatile flag
  (holding_buffer_mutex) to avoid undefined behavior when unlocking a
  mutex not owned by the calling thread

- Fix #3: Reset plc_crash_signal to 0 at the start of plc_cycle_thread
  so stale values don't persist after successful recovery

- Fix #4: Add plc_force_error_state() function for the watchdog to
  transition to ERROR state through the mutex instead of writing
  plc_state directly. Remove extern PLCState from watchdog.c

- Fix #5: Skip watchdog heartbeat check when already in ERROR state
  to prevent repeated error log spam every 2 seconds. Move heartbeat
  reset to the non-RUNNING branch so it happens once on ERROR entry

- Fix #6: Add trailing newline to plc_state_manager.h

- Fix #8: Add threading.Lock to protect _crash_times and _safe_mode
  in RuntimeManager against concurrent access from the monitor and
  compilation threads

- Fix #9: Rename _should_enter_safe_mode to
  _record_crash_and_check_safe_mode to make the side effect explicit

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants