SNAP7: read_all_NQ_chunk.py

File read_all_NQ_chunk.py, 2.4 KB (added by krit, 3 weeks ago)
Line 
1#!/usr/bin/env python3
2
3import pylibmodbus
4import time
5
6# Siemens LOGO! 8 Modbus TCP Configuration
7PLC_IP = "192.168.1.103"  # Change this to your LOGO! 8 IP
8PLC_PORT = 502  # Default Modbus TCP Port
9
10# NQ Register Mapping
11NQ_START_COIL = 0  # First NQ coil (adjust as needed)
12NQ_TOTAL_COUNT = 1024  # Adjust based on the number of NQ outputs
13CHUNK_SIZE = 5  # Reduce the number of coils read at a time
14
15# NQ Holding Register Mapping (Adjust based on LOGO! 8 settings)
16NQ_START_REGISTER = 64  # First NQ register (check Siemens LOGO! register map)
17
18
19
20def main():
21    """Read all NQ (Network Output) values from Siemens LOGO! 8 in chunks."""
22    modbus = pylibmodbus.ModbusTcp(PLC_IP, PLC_PORT)
23
24    try:
25        if modbus.connect() == -1:
26            print("❌ Failed to connect to Siemens LOGO! 8 PLC")
27            return
28       
29        print("✅ Connected to Siemens LOGO! 8 PLC")
30
31        # Read NQ outputs in smaller chunks
32        for start in range(NQ_START_COIL, NQ_TOTAL_COUNT, CHUNK_SIZE):
33            end = min(start + CHUNK_SIZE, NQ_TOTAL_COUNT)
34            nq_coils = modbus.read_bits(start, end - start)
35
36            if nq_coils is not None:
37                for i, value in enumerate(nq_coils):
38                    if ( value != 0 ):
39                        print(f"🔹 NQ{start + i + 1} (Coil {start + i}) = {value}")
40            else:
41                print(f"⚠ Failed to read NQ outputs for Coils {start} to {end - 1}")
42
43            time.sleep(0.1)  # Small delay to avoid overloading LOGO! 8
44        # Read NQ outputs register
45        for start in range(NQ_START_REGISTER, NQ_START_REGISTER + NQ_TOTAL_COUNT, CHUNK_SIZE):
46            end = min(start + CHUNK_SIZE, NQ_START_REGISTER + NQ_TOTAL_COUNT)
47            nq_registers = modbus.read_registers(start, end - start)
48
49            if nq_registers is not None:
50                for i, value in enumerate(nq_registers):
51                    if ( value != 0):
52                        print(f"🔹 NQ{start + i - NQ_START_REGISTER + 1} (Register {start + i}) = {value}")
53            else:
54                print(f"⚠ Failed to read NQ outputs for Registers {start} to {end - 1}")
55
56            time.sleep(0.1)  # Small delay to avoid overloading LOGO! 8
57
58    except Exception as e:
59        print(f"❌ Exception: {e}")
60
61    finally:
62        modbus.close()
63        print("🔌 Disconnected from Siemens LOGO! 8 PLC")
64
65if __name__ == "__main__":
66    main()
67