1 | #!/usr/bin/env python3 |
---|
2 | |
---|
3 | import pylibmodbus |
---|
4 | import time |
---|
5 | import os |
---|
6 | |
---|
7 | |
---|
8 | |
---|
9 | # Siemens LOGO! 8 Modbus TCP Configuration |
---|
10 | PLC_IP = "192.168.1.103" # Change this to your LOGO! 8 IP |
---|
11 | PLC_PORT = 502 # Default Modbus TCP Port |
---|
12 | |
---|
13 | # NAQ Register Mapping (Adjust based on Siemens LOGO! 8 documentation) |
---|
14 | NAQ_START_REGISTER = 1 # Example: Start address of NAQ registers |
---|
15 | NAQ_TOTAL_COUNT = 3 # Adjust based on the number of NAQs available |
---|
16 | CHUNK_SIZE = 2 # Read registers in smaller chunks to avoid Modbus limits |
---|
17 | |
---|
18 | # MQTT server |
---|
19 | SERVER = "188.166.217.51" |
---|
20 | MQ_USER = "t108" |
---|
21 | MQ_PASS = "t108@kmitl" |
---|
22 | TOPIC = "kmitlt108/data" |
---|
23 | |
---|
24 | def main(): |
---|
25 | """Read all NAQ (Network Analog Output) values from Siemens LOGO! 8.""" |
---|
26 | modbus = pylibmodbus.ModbusTcp(PLC_IP, PLC_PORT) |
---|
27 | temp=[] |
---|
28 | try: |
---|
29 | if modbus.connect() == -1: |
---|
30 | print("❌ Failed to connect to Siemens LOGO! 8 PLC") |
---|
31 | return |
---|
32 | |
---|
33 | print("✅ Connected to Siemens LOGO! 8 PLC") |
---|
34 | |
---|
35 | # Read NAQ outputs in smaller chunks |
---|
36 | for start in range(NAQ_START_REGISTER, NAQ_START_REGISTER + NAQ_TOTAL_COUNT, CHUNK_SIZE): |
---|
37 | end = min(start + CHUNK_SIZE, NAQ_START_REGISTER + NAQ_TOTAL_COUNT) |
---|
38 | naq_values = modbus.read_registers(start, end - start) |
---|
39 | |
---|
40 | if naq_values is not None: |
---|
41 | for i, value in enumerate(naq_values): |
---|
42 | if ( value != 0 ): |
---|
43 | print(f"🔹 NAQ{start + i - NAQ_START_REGISTER + 1} (Register {start + i}) = {value}") |
---|
44 | temp.append(value) |
---|
45 | else: |
---|
46 | print(f"⚠ Failed to read NAQ registers {start} to {end - 1}") |
---|
47 | |
---|
48 | time.sleep(0.1) # Small delay to avoid overloading LOGO! 8 |
---|
49 | |
---|
50 | except Exception as e: |
---|
51 | print(f"❌ Exception: {e}") |
---|
52 | |
---|
53 | finally: |
---|
54 | modbus.close() |
---|
55 | print("🔌 Disconnected from Siemens LOGO! 8 PLC") |
---|
56 | print(f"Temp={temp}") |
---|
57 | cmd = "mosquitto_pub -h %s -u %s -P %s -t \'%s\' -m \'{\"T1\":%s, \"T2\":%s}\' " |
---|
58 | cmd = cmd % (SERVER, MQ_USER, MQ_PASS, TOPIC, temp[0], temp[1]) |
---|
59 | print(cmd) |
---|
60 | output = os.popen(cmd).read() |
---|
61 | |
---|
62 | if __name__ == "__main__": |
---|
63 | main() |
---|
64 | |
---|