import threading import time import socket class ProjectorControl(threading.Thread): def __init__(self, ip, port, type=1): threading.Thread.__init__(self) self.lock = threading.Lock() self.sock = None self.ip = ip self.port = port self.statu = None self.close = False if type == 1: self.open_str = "41 54 2B 4C 69 67 68 74 53 6F 75 72 63 65 3D 4F 6E 0D" self.close_str = "41 54 2B 4C 69 67 68 74 53 6F 75 72 63 65 3D 4F 66 66 0D" else: self.open_str = "25 31 41 56 4d 54 20 33 30 0d" self.close_str = "25 31 41 56 4d 54 20 33 31 0d" def lightOn(self): self.lock.acquire() self.statu = "open" self.lock.release() def lightOff(self): self.lock.acquire() self.statu = "close" self.lock.release() def exit(self): self.close = True def run(self): while self.close is not True: if self.statu is not None and self.statu == "open": self.open_illuminant() self.lock.acquire() self.statu = None self.lock.release() elif self.statu is not None and self.statu == "close": self.close_illuminant() self.lock.acquire() self.statu = None self.lock.release() time.sleep(0.01) def open_illuminant(self): t_time = time.time() while (time.time() - t_time) < 3: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(1) try: self.sock.connect((self.ip, self.port)) self.sock.send(bytes.fromhex(self.open_str)) print(bytes.fromhex(self.open_str)) print("open projector \033[0:32mSUCCEND\033[m ") break except Exception as e: print("open projector \033[0:31mERROR\033[m: %s" % e.args) time.sleep(0.01) time.sleep(0.5) self.sock.close() def close_illuminant(self): t_time = time.time() while (time.time() - t_time) < 3: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(1) try: self.sock.connect((self.ip, self.port)) self.sock.send(bytes.fromhex(self.close_str)) print(bytes.fromhex(self.close_str)) print("close projector \033[0:32mSUCCEND\033[m ") break except Exception as e: print("close projector \033[0:31mERROR\033[m: %s" % e.args) time.sleep(0.01) time.sleep(0.5) self.sock.close() # 按间距中的绿色按钮以运行脚本。 # if __name__ == '__main__': # p = ProjectorControl("192.168.1.191", 4352, 2) # p.start() # p.open()