### Cyclic Programming Example Source: https://revpimodio2.readthedocs.io/en/latest/cyclic_programming.html Illustrates a typical setup for cyclic programming, including the main loop and cycle timing considerations. Keep cycle logic fast for optimal performance. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() while rpi.cycleloop(): # Perform cyclic tasks here pass rpi.cleanup() ``` -------------------------------- ### Basic Usage Example Source: https://revpimodio2.readthedocs.io/en/latest/cyclic_programming.html A fundamental example demonstrating the basic instantiation and usage of the RevPiModIO class. This is a starting point for most applications. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() # Access I/O, core functions, etc. print(rpi.io.MyInput.value) rpi.core.set_led(RevPiModIO.GREEN) ``` -------------------------------- ### LED Control Example Source: https://revpimodio2.readthedocs.io/en/latest/_modules/index.html Demonstrates how to control the LEDs on the Raspberry Pi. This example shows setting LEDs to different colors and states. ```python from revpimodio2 import RevPiModIO, GREEN, RED, OFF rpi = RevPiModIO() rpi.core.set_led(GREEN) rpi.core.set_led(RED, 1) rpi.core.set_led(OFF, 2) ``` -------------------------------- ### Practical Examples Source: https://revpimodio2.readthedocs.io/en/latest/cyclic_programming.html Provides practical examples of cyclic programming, such as temperature control and production counting. ```APIDOC ## Practical Examples ### Temperature Control Demonstrates how to use cyclic programming to read temperature sensors and control heating/cooling elements to maintain a setpoint. ### Production Counter Illustrates implementing a counter that increments based on events detected within the cyclic loop, often used for tracking manufactured items. ``` -------------------------------- ### Read Input, Control Output Example Source: https://revpimodio2.readthedocs.io/en/latest/basics.html A simple example demonstrating reading an input and controlling an output based on its value. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() if rpi.io.MyInput.value == 1: rpi.io.MyOutput.value = 1 else: rpi.io.MyOutput.value = 0 ``` -------------------------------- ### simulator property Source: https://revpimodio2.readthedocs.io/en/latest/api/revpimodio.html Gets whether the system started as a simulator. ```APIDOC ## property simulator: bool ### Description Getter function. ### Returns * **bool** - True if started as simulator ``` -------------------------------- ### Install RevPiModIO from Source Source: https://revpimodio2.readthedocs.io/en/latest/installation.html Clone the RevPiModIO repository from GitHub and install it locally. This method is useful for development or when you need the latest unreleased code. ```bash git clone https://github.com/naruxde/revpimodio2.git cd revpimodio2 pip install . ``` -------------------------------- ### Watchdog Management Example Source: https://revpimodio2.readthedocs.io/en/latest/api/helper.html Demonstrates how to manage the watchdog timer for system monitoring. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() # Toggle the watchdog (requires configuration) # rpi.core.watchdog_toggle() # Example within a cycle loop to keep the watchdog alive def keep_watchdog_alive(): # rpi.core.watchdog_toggle() pass rpi.cycleloop(keep_watchdog_alive) rpi.exit() ``` -------------------------------- ### Temperature Control Example Source: https://revpimodio2.readthedocs.io/en/latest/basics.html A practical example of a temperature control system using cyclic programming. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() setpoint = 25.0 while True: current_temp = rpi.io.TemperatureSensor.value if current_temp < setpoint: rpi.io.Heater.value = 1 else: rpi.io.Heater.value = 0 rpi.cycleloop() ``` -------------------------------- ### LED Control Example Source: https://revpimodio2.readthedocs.io/en/latest/basics.html Example of controlling an LED connected to an output pin. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() rpi.io.MyLED.value = 1 # Turn LED on # rpi.io.MyLED.value = 0 # Turn LED off ``` -------------------------------- ### Iterate All IOs Example Source: https://revpimodio2.readthedocs.io/en/latest/basics.html Demonstrates iterating through all available Input/Output pins and printing their status. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() for io_name, io_obj in rpi.io.items(): print(f"IO: {io_name}, Value: {io_obj.value}") ``` -------------------------------- ### Install RevPiModIO from PyPI Source: https://revpimodio2.readthedocs.io/en/latest/_sources/installation.rst.txt Install the RevPiModIO library directly from the Python Package Index (PyPI) using pip. ```bash pip install revpimodio2 ``` -------------------------------- ### Install RevPiModIO from Source Source: https://revpimodio2.readthedocs.io/en/latest/_sources/installation.rst.txt Clone the RevPiModIO repository from GitHub and install it locally using pip. This method is useful for development or when needing the latest unreleased changes. ```bash git clone https://github.com/naruxde/revpimodio2.git cd revpimodio2 pip install . ``` -------------------------------- ### DeviceList Example Source: https://revpimodio2.readthedocs.io/en/latest/_sources/api/device.rst.txt Demonstrates how to access and iterate through devices using the DeviceList container. ```APIDOC ## DeviceList Access ### Description Provides methods to access and manage Revolution Pi devices. ### Method N/A (Class usage) ### Endpoint N/A (Class usage) ### Parameters N/A (Class usage) ### Request Example ```python # Access device by name dio_module = rpi.device.DIO_Module_1 # Access device by position first_device = rpi.device[0] # Iterate all devices for device in rpi.device: print(f"Device: {device.name}") ``` ### Response N/A (Class usage) ``` -------------------------------- ### Verify RevPiModIO Installation Source: https://revpimodio2.readthedocs.io/en/latest/_sources/installation.rst.txt Test the installation by importing the revpimodio2 library and printing its version. This confirms that the library is accessible and installed correctly. ```python python3 -c "import revpimodio2; print(revpimodio2.__version__)" ``` -------------------------------- ### Install RevPiModIO from Source Source: https://revpimodio2.readthedocs.io/en/latest/installation.html Install RevPiModIO directly from its source code. This method is useful for development or when needing the latest unreleased changes. ```bash git clone https://github.com/RevPiModIO/RevPiModIO.git cd RevPiModIO pip install . ``` -------------------------------- ### LED Control Example Source: https://revpimodio2.readthedocs.io/en/latest/quickstart.html Demonstrates how to control the color of an LED using the RevPiModIO library. ```python from revpimodio2 import RevPiModIO, GREEN rpi = RevPiModIO() rpi.core.led.value = GREEN rpi.exit() ``` -------------------------------- ### Install RevPiPyLoad Source: https://revpimodio2.readthedocs.io/en/latest/_sources/installation.rst.txt Install the RevPiPyLoad package, which provides advanced features such as an XML-RPC server and MQTT integration. This requires updating the apt package list first. ```bash sudo apt-get update sudo apt-get install revpipyload ``` -------------------------------- ### Sensor Logging Example Source: https://revpimodio2.readthedocs.io/en/latest/event_programming.html Log sensor data to a file whenever a change is detected on a specific input. This example demonstrates reacting to sensor events and performing I/O operations. ```python from revpimodio2 import RevPiModIO import datetime rpi = RevPiModIO() log_file = "sensor_log.txt" def log_sensor_data(sender, value): timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open(log_file, "a") as f: f.write(f"{timestamp} - Sensor {sender} changed to {value}\n") print(f"Logged change for {sender}: {value}") # Register callback for the sensor input rpi.io.sensor_input.onChange(log_sensor_data) rpi.mainloop() ``` -------------------------------- ### Basic Instantiation with Configuration Parameters Source: https://revpimodio2.readthedocs.io/en/latest/_modules/index.html Shows how to initialize RevPiModIO with specific configuration parameters. This allows for customization of the library's behavior. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO(userconfigjson="/path/to/your/config.json", autoconfig=False, debug=True) ``` -------------------------------- ### Getting a System Summary via `rpi.summary` Source: https://revpimodio2.readthedocs.io/en/latest/search.html Demonstrates how to retrieve a summary of the system's I/O status and configuration. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() system_summary = rpi.summary print(system_summary) ``` -------------------------------- ### monitoring property Source: https://revpimodio2.readthedocs.io/en/latest/api/revpimodio.html Gets whether the system started as monitoring. ```APIDOC ## property monitoring: bool ### Description Getter function. ### Returns * **bool** - True if started as monitoring ``` -------------------------------- ### Iterating Through All IOs Source: https://revpimodio2.readthedocs.io/en/latest/api/index.html This example shows how to loop through all available Input/Output (IO) points in the RevPiModIO system. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() # Iterate over all IOs and print their values for io_point in rpi.io: print(f"IO: {io_point.name}, Value: {io_point.value}") ``` -------------------------------- ### Basic Instantiation Source: https://revpimodio2.readthedocs.io/en/latest/_sources/basics.rst.txt Create a RevPiModIO instance to access your hardware. Ensure to call exit() when done. ```python import revpimodio2 rpi = revpimodio2.RevPiModIO(autorefresh=True) # Your code here rpi.exit() ``` -------------------------------- ### Getting Simulator Status Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/modio.html Returns a boolean indicating whether the module was started in simulator mode. ```python def _get_simulator(self) -> bool: """ Getter function. :return: True if started as simulator """ return self._simulator ``` -------------------------------- ### Getting Monitoring Status Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/modio.html Returns a boolean indicating whether the module was started in monitoring mode. ```python def _get_monitoring(self) -> bool: """ Getter function. :return: True if started as monitoring """ return self._monitoring ``` -------------------------------- ### Device Initialization and Configuration Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/modio.html This code snippet demonstrates the process of iterating through configured devices, applying selection criteria, and initializing them based on their type and product type. It includes handling potential configuration errors and specific device mappings. ```Python for dev in self._devselect.values: if type(dev) not in (int, str): raise ValueError( "need device position as or device name as " ) lst_devices = [] for dev in jconfigrsc["Devices"]: if self._devselect.type and self._devselect.type != dev["type"]: continue if self._devselect.other_device_key: key_value = str(dev[self._devselect.other_device_key]) if key_value not in self._devselect.values: # The list is always filled with continue else: # Auto search depending of value item type if not ( dev["name"] in self._devselect.values or int(dev["position"]) in self._devselect.values ): continue lst_devices.append(dev) else: # Take devices from JSON lst_devices = jconfigrsc["Devices"] # Create Device and IO classes self.device = devicemodule.DeviceList() self.io = IOList(self) # Initialize devices err_names_check = {} for device in sorted(lst_devices, key=lambda x: x["offset"]): # Pre-check of values if float(device.get("offset")) != int(device.get("offset")): # Offset misconfigured warnings.warn( "Offset value {0} of device {1} on position {2} is invalid. " "This device and all IOs are ignored.".format( device.get("offset"), device.get("name"), device.get("position"), ) ) continue # Change VDev of old piCtory versions to KUNBUS standard if device["position"] == "adap.": device["position"] = 64 while device["position"] in self.device: device["position"] += 1 if device["type"] == DeviceType.BASE: # Base devices pt = int(device["productType"]) if pt == ProductType.REVPI_CORE: # RevPi Core dev_new = devicemodule.Core(self, device, simulator=self._simulator) self.core = dev_new elif pt == ProductType.REVPI_CONNECT: # RevPi Connect dev_new = devicemodule.Connect(self, device, simulator=self._simulator) self.core = dev_new elif pt == ProductType.REVPI_CONNECT_4: # RevPi Connect 4 dev_new = devicemodule.Connect4(self, device, simulator=self._simulator) self.core = dev_new elif pt == ProductType.REVPI_CONNECT_5: # RevPi Connect 5 dev_new = devicemodule.Connect5(self, device, simulator=self._simulator) self.core = dev_new elif pt == ProductType.REVPI_COMPACT: # RevPi Compact dev_new = devicemodule.Compact(self, device, simulator=self._simulator) self.core = dev_new elif pt == ProductType.REVPI_FLAT: # RevPi Flat dev_new = devicemodule.Flat(self, device, simulator=self._simulator) self.core = dev_new else: # Always use Base as fallback dev_new = devicemodule.Base(self, device, simulator=self._simulator) elif device["type"] == DeviceType.LEFT_RIGHT: # IOs pt = int(device["productType"]) if pt == ProductType.DIO or pt == ProductType.DI or pt == ProductType.DO: # DIO / DI / DO dev_new = devicemodule.DioModule(self, device, simulator=self._simulator) elif pt == ProductType.RO: # RO dev_new = devicemodule.RoModule(self, device, simulator=self._simulator) else: # All other IO devices dev_new = devicemodule.Device(self, device, simulator=self._simulator) elif device["type"] == DeviceType.VIRTUAL: # Virtuals dev_new = devicemodule.Virtual(self, device, simulator=self._simulator) elif device["type"] == DeviceType.EDGE: # Gateways dev_new = devicemodule.Gateway(self, device, simulator=self._simulator) elif device["type"] == DeviceType.RIGHT: # Connectdevice dev_new = None else: ``` -------------------------------- ### Get Runtime in Milliseconds Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/helper.html Calculates and returns the runtime of the cycle function in milliseconds since the timer started. ```python @property def runtime(self) -> float: """ Runtime im milliseconds of cycle function till now. This property will return the actual runtime of the function. So on the beginning of your function it will be about 0 and will rise during the runtime to the max in the last line of your function. """ return (default_timer() - self._start_timer) * 1000 ``` -------------------------------- ### RevPiModIO with Configuration Parameters Source: https://revpimodio2.readthedocs.io/en/latest/api/index.html Shows how to instantiate RevPiModIO with specific configuration parameters, such as cycle time and watchdog settings. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO(cycletime=0.01, watchdog=True) ``` -------------------------------- ### Get Device Offset Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/device.html Retrieves the starting offset of the device within the process image. This is essential for correctly mapping device data. ```python def _get_offset(self) -> int: """ Returns the device offset in the process image. :return: Device offset """ return self._offset ``` -------------------------------- ### runtime Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/helper.html Gets the runtime in milliseconds of the cycle function. This property returns the actual runtime of the function, rising from 0 at the start to the maximum at the end of the function. ```APIDOC ## runtime ### Description Gets the runtime in milliseconds of the cycle function. This property returns the actual runtime of the function, rising from 0 at the start to the maximum at the end of the function. ### Method GET (assumed) ### Endpoint /helper/runtime ### Response #### Success Response (200) - **runtime_ms** (float) - The runtime of the cycle function in milliseconds. ``` -------------------------------- ### Cycletools Example: Main Logic Source: https://revpimodio2.readthedocs.io/en/latest/_sources/api/helper.rst.txt Demonstrates initializing variables, detecting changes in IO, using timing flags for LED control, and performing cleanup actions within a cyclic function. ```python def main(ct: revpimodio2.Cycletools): if ct.first: # Initialize ct.var.counter = 0 # Main logic if ct.changed(ct.io.sensor): ct.var.counter += 1 # Blink LED using timing flag ct.io.led.value = ct.flag5c if ct.last: # Cleanup print(f"Final: {ct.var.counter}") ``` -------------------------------- ### Complex State Machine Controller Source: https://revpimodio2.readthedocs.io/en/latest/_sources/cyclic_programming.rst.txt A more complex state machine example demonstrating transitions between IDLE, STARTING, and RUNNING states. It uses on-delay timers and edge detection for state changes. ```python def machine_controller(ct: revpimodio2.Cycletools): """Multi-state machine controller.""" if ct.first: ct.var.state = "IDLE" ct.var.production_count = 0 # State: IDLE - Ready to start if ct.var.state == "IDLE": ct.io.motor.value = False ct.io.green_led.value = True ct.io.red_led.value = False if ct.changed(ct.io.start_button, edge=revpimodio2.RISING): ct.var.state = "STARTING" print("Starting...") # State: STARTING - Startup sequence elif ct.var.state == "STARTING": ct.io.yellow_led.value = True # 2-second startup delay ct.set_ton("startup", 2000) if ct.get_ton("startup"): ct.var.state = "RUNNING" print("Running") # State: RUNNING - Normal operation elif ct.var.state == "RUNNING": ``` -------------------------------- ### Configure and Implement Logging Source: https://revpimodio2.readthedocs.io/en/latest/advanced.html Sets up basic logging with a specified format and logs system start, errors, temperature status, and system stop events. ```python import logging from datetime import datetime # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) def main_cycle(ct): if ct.first: logging.info("System started") ct.var.error_count = 0 # Log errors if ct.io.error_sensor.value: ct.var.error_count += 1 logging.error(f"Error detected: {ct.var.error_count}") # Log status periodically if ct.flank100c: logging.info(f"Temperature: {ct.io.temperature.value}°C") if ct.last: logging.info("System stopped") ``` -------------------------------- ### Production Counter Example Source: https://revpimodio2.readthedocs.io/en/latest/basics.html An example of a production counter that increments based on an input signal. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() production_count = 0 while True: if rpi.io.ProductDetected.was_triggered(): # Assumes a trigger mechanism production_count += 1 rpi.io.DisplayCount.value = production_count rpi.cycleloop() ``` -------------------------------- ### Initialize LEDs, Switch, and Relais Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/device.html Initializes LED outputs, a switch input, and a relais output using the IOBase class. This snippet demonstrates the setup for controlling and reading various device components. ```python lst_led = self._modio.io[self._slc_devoff][self._slc_led.start] if len(lst_led) == 8: exp_a1green = lst_led[0].export exp_a1red = lst_led[1].export exp_a2green = lst_led[2].export exp_a2red = lst_led[3].export exp_a3green = lst_led[4].export exp_a3red = lst_led[5].export exp_a4green = lst_led[6].export exp_a4red = lst_led[7].export # Next byte lst_led = self._modio.io[self._slc_devoff][self._slc_led.start + 1] exp_a5green = lst_led[0].export exp_a5red = lst_led[1].export else: exp_a1green = lst_led[0].export exp_a1red = exp_a1green exp_a2green = exp_a1green exp_a2red = exp_a1green exp_a3green = exp_a1green exp_a3red = exp_a1green exp_a4green = exp_a1green exp_a4red = exp_a1green exp_a5green = exp_a1green exp_a5red = exp_a1green # Create actual IOs self.a1green = IOBase( self, ["core.a1green", 0, 1, self._slc_led.start, exp_a1green, None, "LED_A1_GREEN", "0"], OUT, "little", False, ) """LED A1 green.""" self.a1red = IOBase( self, ["core.a1red", 0, 1, self._slc_led.start, exp_a1red, None, "LED_A1_RED", "1"], OUT, "little", False, ) """LED A1 red.""" self.a2green = IOBase( self, ["core.a2green", 0, 1, self._slc_led.start, exp_a2green, None, "LED_A2_GREEN", "2"], OUT, "little", False, ) """LED A2 green.""" self.a2red = IOBase( self, ["core.a2red", 0, 1, self._slc_led.start, exp_a2red, None, "LED_A2_RED", "3"], OUT, "little", False, ) """LED A2 red.""" self.a3green = IOBase( self, ["core.a3green", 0, 1, self._slc_led.start, exp_a3green, None, "LED_A3_GREEN", "4"], OUT, "little", False, ) """LED A3 green.""" self.a3red = IOBase( self, ["core.a3red", 0, 1, self._slc_led.start, exp_a3red, None, "LED_A3_RED", "5"], OUT, "little", False, ) """LED A3 red.""" self.a4green = IOBase( self, ["core.a4green", 0, 1, self._slc_led.start, exp_a4green, None, "LED_A4_GREEN", "6"], OUT, "little", False, ) """LED A4 green.""" self.a4red = IOBase( self, ["core.a4red", 0, 1, self._slc_led.start, exp_a4red, None, "LED_A4_RED", "7"], OUT, "little", False, ) """LED A4 red.""" self.a5green = IOBase( self, ["core.a5green", 0, 1, self._slc_led.start, exp_a5green, None, "LED_A5_GREEN", "8"], OUT, "little", False, ) """LED A5 green.""" self.a5red = IOBase( self, ["core.a5red", 0, 1, self._slc_led.start, exp_a5red, None, "LED_A5_RED", "9"], OUT, "little", False, ) """LED A5 red.""" # Real IO for switch lst_io = self._modio.io[self._slc_devoff][self._slc_switch.start] exp_io = lst_io[0].export self.switch = IOBase( self, ["flat.switch", 0, 1, self._slc_switch.start, exp_io, None, "Flat_Switch", "0"], INP, "little", False, ) """Switch input.""" # Real IO for relais lst_io = self._modio.io[self._slc_devoff][self._slc_dout.start] exp_io = lst_io[0].export self.relais = IOBase( self, ["flat.relais", 0, 1, self._slc_dout.start, exp_io, None, "Flat_Relais", "0"], OUT, "little", False, ) """Relais output.""" # Software watchdog einrichten self.wd = IOBase( self, ["core.wd", 0, 1, self._slc_led.start, False, None, "WatchDog", "15"], OUT, "little", False, ) """Watchdog bit.""" ``` -------------------------------- ### RevPiModIO Initialization and Configuration Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/modio.html Illustrates the initialization of RevPiModIO, including setting up private variables, module variables, and piCtory classes. It also shows the configuration process based on piCtory resources and checks if the system is running on a Raspberry Pi. ```python # -*- coding: utf-8 -*- # TODO: check if file exists for simulator and procimg / create it? # Private variables self.__cleanupfunc = None self._buffedwrite = False self._debug = 1 self._devselect = DevSelect() self._exit = Event() self._exit_level = 0 self._imgwriter = None self._ioerror = 0 self._length = 0 self._looprunning = False self._lst_refresh = [] self._maxioerrors = 0 self._myfh = None self._myfh_lck = Lock() self._replace_io_file = replace_io_file self._th_mainloop = None self._waitexit = Event() # Module variables self.core = None # piCtory classes self.app = None self.device = None self.io = None self.summary = None # Event for user actions self.exitsignal = Event() # Set value via setter self.debug = debug try: self._run_on_pi = S_ISCHR(osstat(self._procimg).st_mode) except Exception: self._run_on_pi = False # Only configure if not inherited if type(self) == RevPiModIO: self._configure(self.get_jconfigrsc()) ``` -------------------------------- ### Using Configuration Files for Custom IOs Source: https://revpimodio2.readthedocs.io/en/latest/basics.html Shows how to load custom IO definitions from a configuration file. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO(configfile="/path/to/your/custom_io.conf") ``` -------------------------------- ### Initialize LEDs and Watchdog Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/device.html Sets up individual LED outputs (green/red for A1, A2) and a watchdog timer. Each IOBase is configured with specific parameters including its name, index, direction, start position, export flag, and a unique identifier. ```python exp_a2green = exp_a1green exp_a2red = exp_a1green # Create actual IOs self.a1green = IOBase( self, ["core.a1green", 0, 1, self._slc_led.start, exp_a1green, None, "LED_A1_GREEN", "0"], OUT, "little", False, ) """LED A1 green.""" self.a1red = IOBase( self, ["core.a1red", 0, 1, self._slc_led.start, exp_a1red, None, "LED_A1_RED", "1"], OUT, "little", False, ) """LED A1 red.""" self.a2green = IOBase( self, ["core.a2green", 0, 1, self._slc_led.start, exp_a2green, None, "LED_A2_GREEN", "2"], OUT, "little", False, ) """LED A2 green.""" self.a2red = IOBase( self, ["core.a2red", 0, 1, self._slc_led.start, exp_a2red, None, "LED_A2_RED", "3"], OUT, "little", False, ) """LED A2 red.""" # Software watchdog einrichten self.wd = IOBase( self, ["core.wd", 0, 1, self._slc_led.start, False, None, "WatchDog", "7"], OUT, "little", False, ) """Watchdog bit.""" ``` -------------------------------- ### Initialize LEDs with IOBase Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/device.html Initializes various LED outputs using the IOBase class. Each LED is configured with specific parameters including its name, channel, and output type. ```Python self.a2green = IOBase( self, ["core.a2green", 0, 1, self._slc_led.start, exp_a2green, None, "LED_A2_GREEN", "4"], OUT, "little", False, ) """LED A2 green.""" self.a2blue = IOBase( self, ["core.a2blue", 0, 1, self._slc_led.start, exp_a2blue, None, "LED_A2_BLUE", "5"], OUT, "little", False, ) """LED A2 blue.""" self.a3red = IOBase( self, ["core.a3red", 0, 1, self._slc_led.start, exp_a3red, None, "LED_A3_RED", "6"], OUT, "little", False, ) """LED A3 red.""" self.a3green = IOBase( self, ["core.a3green", 0, 1, self._slc_led.start, exp_a3green, None, "LED_A3_GREEN", "7"], OUT, "little", False, ) """LED A3 green.""" self.a3blue = IOBase( self, ["core.a3blue", 0, 1, self._slc_led.start, exp_a3blue, None, "LED_A3_BLUE", "8"], OUT, "little", False, ) """LED A3 blue.""" self.a4red = IOBase( self, ["core.a4red", 0, 1, self._slc_led.start, exp_a4red, None, "LED_A4_RED", "9"], OUT, "little", False, ) """LED A4 red.""" self.a4green = IOBase( self, ["core.a4green", 0, 1, self._slc_led.start, exp_a4green, None, "LED_A4_GREEN", "10"], OUT, "little", False, ) """LED A4 green.""" self.a4blue = IOBase( self, ["core.a4blue", 0, 1, self._slc_led.start, exp_a4blue, None, "LED_A4_BLUE", "11"], OUT, "little", False, ) """LED A4 blue.""" self.a5red = IOBase( self, ["core.a5red", 0, 1, self._slc_led.start, exp_a5red, None, "LED_A5_RED", "12"], OUT, "little", False, ) """LED A5 red.""" self.a5green = IOBase( self, ["core.a5green", 0, 1, self._slc_led.start, exp_a5green, None, "LED_A5_GREEN", "13"], OUT, "little", False, ) """LED A5 green.""" self.a5blue = IOBase( self, ["core.a5blue", 0, 1, self._slc_led.start, exp_a5blue, None, "LED_A5_BLUE", "14"], OUT, "little", False, ) """LED A5 blue.""" ``` -------------------------------- ### Initialize and Use RevPiModIO Source: https://revpimodio2.readthedocs.io/en/latest/_sources/api/revpimodio.rst.txt Demonstrates how to initialize the RevPiModIO class with auto-refresh enabled, access input/output values, and perform a clean shutdown. ```python import revpimodio2 # Initialize with auto-refresh rpi = revpimodio2.RevPiModIO(autorefresh=True) # Access IOs if rpi.io.button.value: rpi.io.led.value = True # Clean shutdown rpi.exit() ``` -------------------------------- ### Accessing System Control via `rpi.core` Source: https://revpimodio2.readthedocs.io/en/latest/search.html Demonstrates how to access system-level functionalities like LED control and watchdog management through the `core` attribute. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() rpi.core.led(GREEN) rpi.core.watchdog_toggle() ``` -------------------------------- ### Get Switching Cycles (Network - Not Supported) Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/io.html Placeholder for network-based ioctl calls to get switching cycles, currently raising a RuntimeError as it's not supported via RevPiNetIO. ```python elif hasattr(self._parentdevice._modio._myfh, "ioctl"): # IOCTL over network """ The ioctl function over the network does not return a value. Only the successful execution of the ioctl call is checked and reported back. If a new function has been implemented in RevPiPyLoad, the subsequent source code can be activated. with self._parentdevice._modio._myfh_lck: try: ioctl_return_value = self._parentdevice._modio._myfh.ioctl( 19229, self.__ioctl_arg ) except Exception as e: self._parentdevice._modio._gotioerror("net_rocounter", e) """ raise RuntimeError("Can not be called over network via RevPiNetIO") ``` -------------------------------- ### Simple State Machine Example Source: https://revpimodio2.readthedocs.io/en/latest/api/helper.html Illustrates the basic structure of a state machine using RevPiModIO. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() state = 'IDLE' def state_machine(): global state if state == 'IDLE' and rpi.io.StartButton.value == 1: state = 'RUNNING' print('Entering RUNNING state') elif state == 'RUNNING' and rpi.io.StopButton.value == 1: state = 'IDLE' print('Entering IDLE state') rpi.cycleloop(state_machine) rpi.exit() ``` -------------------------------- ### __init__ Source: https://revpimodio2.readthedocs.io/en/latest/api/io.html Creates an IO object with struct formatting. This constructor allows for detailed configuration of the IO, including its name, struct format, and various optional parameters like descriptions, bit registration, byte/word order, and default values. ```APIDOC ## __init__ ### Description Creates an IO with struct formatting. ### Parameters * **parentio** – ParentIO object that will be replaced * **name** – Name of the new IO * **frm** – struct formatting (1 character) or ‘NUMBERs’ e.g. ‘8s’ * **kwargs** – Additional parameters: * bmk: Description for IO * bit: Registers IO as at specified bit in byte * byteorder: Byteorder for IO, default from replaced IO * wordorder: Wordorder is applied before byteorder * defaultvalue: Default value for IO, default from replaced IO ``` -------------------------------- ### Get or Set Integer IO Value Source: https://revpimodio2.readthedocs.io/en/latest/api/io.html Allows getting or setting the integer value of an IO using function call syntax. Raises TypeError if the provided value is not an integer. ```python # Get current value current_value = io_object() # Set new value io_object(10) ``` -------------------------------- ### Get or Set IO Value using Call Syntax Source: https://revpimodio2.readthedocs.io/en/latest/api/io.html Allows getting the current IO value by calling the object without arguments, or setting the value by passing an argument. ```python __call__(_value =None_) ``` -------------------------------- ### Basic RevPiModIO Instantiation Source: https://revpimodio2.readthedocs.io/en/latest/basics.html Create a RevPiModIO instance to access your hardware. Set autorefresh to True for automatic synchronization. ```python import revpimodio2 rpi = revpimodio2.RevPiModIO(autorefresh=True) # Your code here rpi.exit() ``` -------------------------------- ### Get/Set Integer Value via Call Source: https://revpimodio2.readthedocs.io/en/latest/api/io.html Allows getting or setting the integer IO value using function call syntax. Call with no arguments to get the value, or with an integer to set it. ```python rpi.io.setpoint(1500) ``` -------------------------------- ### Context Management with `__enter__` and `__exit__` Source: https://revpimodio2.readthedocs.io/en/latest/search.html Shows how to use the `RevPiModIO` object as a context manager for automatic setup and cleanup. ```python from revpimodio2 import RevPiModIO with RevPiModIO() as rpi: # Use rpi within this block rpi.io.MyOutput.value = True # Cleanup is automatically called when exiting the 'with' block. ``` -------------------------------- ### Start Mainloop with Event Monitoring Source: https://revpimodio2.readthedocs.io/en/latest/api/revpimodio.html Starts the main event monitoring loop. The program thread will be blocked here until .exit() is called, unless blocking is set to False. It processes registered IO events as they occur. ```python rpi.mainloop(blocking=True) ``` -------------------------------- ### Initialize and Cleanup Source: https://revpimodio2.readthedocs.io/en/latest/cyclic_programming.html Shows the essential steps for initializing the RevPiModIO object and cleaning up resources afterward. Always include these for proper operation. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() # ... your code ... rpi.cleanup() ``` -------------------------------- ### LED Toggle on Button Press Example Source: https://revpimodio2.readthedocs.io/en/latest/event_programming.html A practical example demonstrating how to toggle an LED's state when a button is pressed using event-driven programming. This involves registering a callback for the button's change event. ```python from revpimodio2 import RevPiModIO, RISING rpi = RevPiModIO() def toggle_led(sender, value): # Toggle the LED state rpi.io.led_output.value = not rpi.io.led_output.value print(f"LED toggled to: {rpi.io.led_output.value}") # Register the callback for the rising edge of the button input rpi.io.button_input.onChange(toggle_led, edge=RISING) print("Press the button to toggle the LED. Press Ctrl+C to exit.") rpi.mainloop() ``` -------------------------------- ### Basic RevPiModIO Usage Source: https://revpimodio2.readthedocs.io/en/latest/api/device.html Demonstrates the fundamental steps of initializing RevPiModIO, accessing core functionalities, and performing a cleanup. This is a starting point for most applications. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() # Access core functionalities print(rpi.core.get_identity()) # Perform cleanup when done rpi.cleanup() ``` -------------------------------- ### Get or Set IO Value via Call Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/io.html Allows getting the current IO value by calling the object without arguments, or setting a new value by passing an argument. Handles both bitwise and byte-wise IO. ```Python def __call__(self, value=None): """ Get or set the IO value using function call syntax. :param value: If None, returns current value; otherwise sets the value :return: Current IO value when called without arguments """ if value is None: # Inline get_value() if self._bitshift: return bool( self._parentdevice._ba_devdata[self._slc_address.start] & self._bitshift ) else: return bytes(self._parentdevice._ba_devdata[self._slc_address]) else: self.set_value(value) ``` -------------------------------- ### Start RevPi ModIO Main Loop (Non-Blocking) Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/modio.html Starts the main loop for event monitoring in a separate thread, allowing the main program to continue execution. This is useful for GUI applications or when concurrent processing is required. ```python # Create thread if it should not block if not blocking: self._th_mainloop = Thread(target=self.mainloop, kwargs={"blocking": True}) self._th_mainloop.start() return ``` -------------------------------- ### Initialization and Cleanup in Cyclic Programming Source: https://revpimodio2.readthedocs.io/en/latest/basics.html Demonstrates proper initialization before the cycle loop and cleanup after it terminates. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() rpi.setdefaultvalues() # Initialize outputs try: while True: # ... cyclic logic ... rpi.cycleloop() finally: rpi.cleanup() # Ensure cleanup ``` -------------------------------- ### Iterating Through All IOs Source: https://revpimodio2.readthedocs.io/en/latest/api/helper.html Demonstrates how to loop through all available IO objects in the system. ```python from revpimodio2 import RevPiModIO rpi = RevPiModIO() for io_name, io_object in rpi.io.items(): print(f"IO Name: {io_name}, Value: {io_object.value}, Type: {io_object.type}") rpi.exit() ``` -------------------------------- ### Start Main Loop with Event Monitoring Source: https://revpimodio2.readthedocs.io/en/latest/api/revpimodio.html Starts the main loop for event monitoring. The program thread is trapped here until exit() is called (unless blocking=False). It monitors for changes in registered IOs and executes associated functions. ```python driver.mainloop(True) ``` -------------------------------- ### Get or Set Integer IO Value Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/io.html Provides a convenient way to get or set the integer value of an IO pin using function call syntax. It handles the conversion to and from bytes based on the IO's configuration. ```python if value is None: # Inline get_intvalue() return int.from_bytes( self._parentdevice._ba_devdata[self._slc_address], byteorder=self._byteorder, signed=self._signed, ) else: # Inline from set_intvalue() if type(value) == int: self.set_value( value.to_bytes( self._length, byteorder=self._byteorder, signed=self._signed, ) ) else: raise TypeError( "'{0}' need a value, but {1} was given" "".format(self._name, type(value)) ) ``` -------------------------------- ### Using RevPiModIO as a Context Manager Source: https://revpimodio2.readthedocs.io/en/latest/genindex.html Shows how to use RevPiModIO with Python's `with` statement for automatic initialization and cleanup. This is the recommended approach for managing resources. ```python from revpimodio2 import RevPiModIO with RevPiModIO() as rpi: # ... use rpi object ... pass # rpi is automatically cleaned up here ``` -------------------------------- ### Start RevPi ModIO Main Loop (Blocking) Source: https://revpimodio2.readthedocs.io/en/latest/_modules/revpimodio2/modio.html Starts the main loop for event monitoring. This call blocks the current thread until RevPiDevicelist.exit() is called. It's suitable for applications that need to continuously monitor and react to IO changes. ```python from threading import Thread from queue import Empty from time import default_timer import warnings # ... (previous code) # User event self.exitsignal.clear() # Clean event before entering mainloop self._exit.clear() self._looprunning = True # Create byte copy and attach prefire when entering mainloop for dev in self._lst_refresh: with dev._filelock: dev._ba_datacp = dev._ba_devdata[:] # Prepare prefire events for io in dev._dict_events: for regfunc in dev._dict_events[io]: if not regfunc.prefire: continue if ( regfunc.edge == BOTH or regfunc.edge == RISING and io.value or regfunc.edge == FALLING and not io.value ): if regfunc.as_thread: self._imgwriter._eventqth.put((regfunc, io._name, io.value), False) else: self._imgwriter._eventq.put((regfunc, io._name, io.value), False) # Activate ImgWriter with event monitoring self._imgwriter._collect_events(True) e = None runtime = -1 if self._debug == -1 else 0 while not self._exit.is_set(): # Set runtime of event queue to 0 if self._imgwriter._eventq.qsize() == 0: runtime = -1 if self._debug == -1 else 0 try: tup_fire = self._imgwriter._eventq.get(timeout=1) # Start measuring runtime of the queue if runtime == 0: runtime = default_timer() # Call directly since check is in io.IOBase.reg_event tup_fire[0].func(tup_fire[1], tup_fire[2]) self._imgwriter._eventq.task_done() # Runtime check if runtime != -1 and default_timer() - runtime > self._imgwriter._refresh: runtime = -1 warnings.warn( "can not execute all event functions in one cycle - " "optimize your event functions or rise .cycletime", RuntimeWarning, ) except Empty: if not self._exit.is_set() and not self._imgwriter.is_alive(): e = RuntimeError("autorefresh thread not running") break except Exception as ex: e = ex break # Leave mainloop self._imgwriter._collect_events(False) self._looprunning = False self._th_mainloop = None # Check for errors that were thrown in the loop if e is not None: self.exit(full=False) self.__exit_jobs() raise e # Execute exit strategy self.__exit_jobs() ``` -------------------------------- ### Start Cycle Loop Source: https://revpimodio2.readthedocs.io/en/latest/api/revpimodio.html Starts a cycle loop to execute a function periodically. The loop traps the current thread until exit() is called or the function returns a non-None value. Ensure the function's runtime does not exceed the cycle time. ```python driver.cycleloop(my_function, 50, True) ```