nec_control/include/control.py

48 lines
1.5 KiB
Python
Raw Normal View History

2017-09-19 20:30:16 +03:00
#!/usr/bin/env python
import socket
class nec_control:
def __init__(self, address, id, port=7142):
self.__id = (id + int("40", 16)).to_bytes(1, "big")
self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__socket.connect((address, port))
def __genmsg(self, msgbody, msglength):
# Header
message = b""
message += b"\x01\x30" # SOH (Start Of Header)
message += self.__id # Destination (Monitor ID)
message += b"\x30" # Source (for controller - always 0x30h (ASCII '0'))
message += b"\x41" # Message type
message += msglength # Message length in hex (example: 0x3Ah must be encoded as ASCII characters '3' and 'A')
# Message
message += b"\x02" # STX (Start of Message)
message += msgbody
message += b"\x03" # ETX (End of message)
# Check code
xor = message[1]
for i in range (2, len(message)):
xor = xor ^ message[i]
message += bytes([xor])
# Delimiter
message += b"\x0d" # CR (carriage return)
return(message)
def powerOn(self):
msgbody = b"\x43\x32\x30\x33\x44\x36\x30\x30\x30\x31"
msglength = b"0C"
message = self.__genmsg(msgbody, msglength)
self.__socket.send(message)
def powerOff(self):
msgbody = b"\x43\x32\x30\x33\x44\x36\x30\x30\x30\x34"
msglength = b"0C"
message = self.__genmsg(msgbody, msglength)
self.__socket.send(message)