Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import socket
- import time
- PLC_PORT = 2101
- def bcc_xor(data: bytes) -> bytes:
- """XOR BCC, returned as 2 ASCII hex chars."""
- b = 0
- for x in data:
- b ^= x
- return f"{b:02X}".encode("ascii")
- def frame(msg: bytes) -> bytes:
- """Append BCC + CR."""
- return msg + bcc_xor(msg) + b"\r"
- def recv_until_cr(sock: socket.socket, limit: int = 4096) -> bytes:
- """Read until CR or socket timeout/close."""
- buf = bytearray()
- while len(buf) < limit:
- chunk = sock.recv(256)
- if not chunk:
- break
- buf += chunk
- if b"\r" in chunk:
- break
- return bytes(buf)
- def xmit(ip: str, payload: bytes, timeout: float = 2.0) -> bytes:
- with socket.create_connection((ip, PLC_PORT), timeout=timeout) as s:
- s.settimeout(timeout)
- s.sendall(payload)
- return recv_until_cr(s)
- def write_y_bit(ip: str, bit_index: int, value: int, device: str = "FF") -> bytes:
- """
- Write 1-bit output using request message 1:
- ENQ + Device(2 ASCII) + '0' + 'W' + 'y' + addr(4 ASCII) + ('0'/'1') + BCC + CR
- Data type 'y' = Output 1-bit designation. :contentReference[oaicite:1]{index=1}
- """
- if bit_index < 0 or bit_index > 7:
- raise ValueError("This demo expects outputs 0..7")
- if value not in (0, 1):
- raise ValueError("value must be 0 or 1")
- # Address as 4 ASCII digits (matches your existing style, e.g. 0004)
- addr = f"{bit_index:04d}".encode("ascii")
- msg = b"\x05" + device.encode("ascii") + b"0W" + b"y" + addr + (b"1" if value else b"0")
- return xmit(ip, frame(msg))
- def demo(ip: str):
- # Turn outputs on one-by-one (0 -> 7)
- for i in range(8):
- rx = write_y_bit(ip, i, 1)
- print(f"TX: set Y{i}=1 -> RX: {rx!r}")
- time.sleep(1)
- # Hold on for a moment (optional)
- time.sleep(1)
- # Turn outputs off one-by-one (7 -> 0)
- for i in range(7, -1, -1):
- rx = write_y_bit(ip, i, 0)
- print(f"TX: set Y{i}=0 -> RX: {rx!r}")
- time.sleep(1)
- def main():
- ip = "10.1.0.15"
- demo(ip)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment