Tip: punctuate and capitalise your posts properly for readability - especially for non-English speakers / translator software - and to maintain some credibility.
no, in fact im still very new with python as well, however some of my scripts have proved useful for us, when it comes to interacting with different hardware
Glad to hear pycomm3 will work, do you know of similar code that i could compare ?
I would use the OPCUA interface in Linx Gateway on a computer and use a python OPCUA client to interact with it. That way its a manufacturer supported communication method, and the python part is in the IT level. The last thing you want is to adversely affect the comms on the PLC with a badly implemented python library that you don't control.
#!/usr/bin/env python3
# /// script
# dependencies = [
# "pycomm3>=1.2.14",
# ]
# requires-python = ">=3.11"
# ///
"""
PLC Data Writer - Reads sensor data from a file and writes to a Logix PLC tag
Usage: uv run plc_data_writer.py <file_path> <tag_name> <plc_ip>
python3 plc_data_writer.py <file_path> <tag_name> <plc_ip>
"""
import argparse
import time
import sys
from pathlib import Path
from pycomm3 import LogixDriver
def read_sensor_data(file_path):
"""
Read sensor data from the specified file.
Returns the data as a string, stripped of whitespace.
"""
try:
with open(file_path, 'r') as f:
data = f.read().strip()
return data
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return None
except Exception as e:
print(f"Error reading file: {e}")
return None
def write_to_plc(plc, tag_name, value):
"""
Write a value to the specified PLC tag.
Returns True if successful, False otherwise.
"""
try:
# Try to convert to numeric if possible
try:
# Try integer first
numeric_value = int(value)
except ValueError:
try:
# Try float
numeric_value = float(value)
except ValueError:
# Keep as string if not numeric
numeric_value = value
result = plc.write(tag_name, numeric_value)
if result:
print(f"Successfully wrote '{numeric_value}' to tag '{tag_name}'")
return True
else:
print(f"Failed to write to tag '{tag_name}'")
return False
except Exception as e:
print(f"Error writing to PLC: {e}")
return False
def main():
parser = argparse.ArgumentParser(
description='Read sensor data from a file and write to a Logix PLC tag every second.'
)
parser.add_argument('file_path', help='Path to the file containing sensor data')
parser.add_argument('tag_name', help='Name of the PLC tag to write to')
parser.add_argument('plc_ip', help='IP address of the Logix PLC')
parser.add_argument('--slot', type=int, default=0,
help='PLC slot number (default: 0)')
args = parser.parse_args()
# Verify file exists
if not Path(args.file_path).exists():
print(f"Error: File '{args.file_path}' does not exist.")
sys.exit(1)
# Connect to PLC
print(f"Connecting to PLC at {args.plc_ip}...")
try:
with LogixDriver(args.plc_ip, slot=args.slot) as plc:
if not plc.connected:
print("Failed to connect to PLC.")
sys.exit(1)
print(f"Connected to PLC: {plc.info}")
print(f"Reading from file: {args.file_path}")
print(f"Writing to tag: {args.tag_name}")
print("Press Ctrl+C to stop...\n")
# Main loop - read and write every second
while True:
# Read sensor data from file
sensor_data = read_sensor_data(args.file_path)
if sensor_data is not None:
# Write to PLC tag
write_to_plc(plc, args.tag_name, sensor_data)
# Wait 1 second before next iteration
time.sleep(1)
except KeyboardInterrupt:
print("\n\nStopping program...")
sys.exit(0)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()