Sending sensor data to Logix from pycomm3

Newbie (sorry)
iv got sensor data ( a number string)

once every second i want to be able to send it to the Logix system (Allen Bradley), this is new to me.

is pycomm3 the best way, or should i be looking to do it another way.

Thanks in advance, Jeff

Ignition has drivers for Logix PLCs.

Is this question purposely in General Discussion because it's not Ignition related?

Tip: punctuate and capitalise your posts properly for readability - especially for non-English speakers / translator software - and to maintain some credibility.

Otherwise, welcome to the forum.

Depends on your context, is this a critical industrial process or a home DIY project you're enjoying the build process on?

it is not ignition related, its a linux device reading data from a sensor,
i want to send it to Logix, from there they can process the new readings

Sure, use pycomm3 :person_shrugging:

Is there a different programming language you're more comfortable with than Python?

its industrial, the critical part will be done in Logix, I just to get the data to Logix
Looking for options.
thanks

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.

Thanks for the input, ill check it out

A few seconds with an LLM gave me this:

#!/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()

caveat emptor.

LOL, looks like i need to invest time into a LLM

thanks for the quick responses appreciate it. :slight_smile: