from CameraModel import CameraModel from CameraCommander import CameraCommander from WaitAuthentication import WaitAuthentication from WaitEnabledModeReply import WaitEnabledModeReply from WaitDisabledModeReply import WaitDisabledModeReply from WaitDisconnectedReply import WaitDisconnectedReply from DeadState import DeadState class CameraContext: class InvalidStateException(Exception): pass def __init__(self, connection): self.camera = None self.connection = connection self.state = WaitAuthentication() def handle(self): return self.state.handle(self) def tic(self): self.state.tic(self) def enable(self, userCommand = None): if not self.camera or not self.connection: raise CameraContext.InvalidStateException() if not self.connection.send("enable"): print("[CameraContext] : Connection lost with camera ({}) at {}:{}".format(self.camera.id, self.connection.addr, self.connection.port)) self.close() if userCommand: userCommand.callback(False, "connection_lost") return False print("[CameraContext] : Ask for enabling RTMP streaming on camera ({}) at {}:{}".format(self.camera.id, self.connection.addr, self.connection.port)) self.state = WaitEnabledModeReply(userCommand) return True def disable(self, userCommand = None): if not self.camera or not self.connection: raise CameraContext.InvalidStateException() if not self.connection.send("disable"): print("[CameraContext] : Connection lost with camera ({}) at {}:{}".format(self.camera.id, self.connection.addr, self.connection.port)) self.close() if userCommand: userCommand.callback(False, "connection_lost") return False print("[CameraContext] : Ask for disabling RTMP streaming on camera ({}) at {}:{}".format(self.camera.id, self.connection.addr, self.connection.port)) self.state = WaitDisabledModeReply(userCommand) return True def disconnect(self, userCommand = None): if not self.camera or not self.connection: raise CameraContext.InvalidStateException() if not self.connection.send("disconnect"): print("[CameraContext] : Connection lost with camera ({}) at {}:{}".format(self.camera.id, self.connection.addr, self.connection.port)) self.close() if userCommand: userCommand.callback(False, "connection_lost") return False print("[CameraContext] : Ask for disconnecting camera ({}) at {}:{}".format(self.camera.id, self.connection.addr, self.connection.port)) self.state = WaitDisconnectedReply(userCommand) return True def close(self): if not self.connection: raise CameraContext.InvalidStateException() if CameraCommander.IsRegistered(self): CameraCommander.Remove(self) if not self.camera: raise CameraContext.InvalidStateException() mdl = CameraModel() self.camera.available = False self.camera.rtmp_handle = "" mdl.update(self.camera) self.camera = None print("[CameraContext] : Close connection with {}:{}".format(self.connection.addr, self.connection.port)) self.connection.close() self.connection = None self.state = DeadState()